19 Commits

Author SHA256 Message Date
Alphaeus Mote 59c06e33bb feat(shell): clipboard for the remote shell [skip ci]
Copy with Ctrl+Shift+C, Ctrl+Insert or Ctrl+C over a selection (Ctrl+C
alone still interrupts); paste with Ctrl+V, Ctrl+Shift+V or Shift+Insert
through the browser's own paste; right-click copies the selection or
pastes. Copy and Paste buttons on the shell page and the pop-out toolbar.
Terminal Settings: right-click behaviour, Copy on Select, and Ask Before
Multi-Line Paste for shells that would run each pasted line. Pastes over
1 MiB are refused; input goes to the device in 32 KiB pieces.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 19:51:08 -05:00
Alphaeus Mote 974c0528d6 Merge branch 'feat/intellisense' [skip ci] 2026-11-18 17:46:58 -05:00
Alphaeus Mote dfd0cf36bf Merge branch 'feat/snippets' [skip ci] 2026-11-18 17:46:57 -05:00
Alphaeus Mote c3cdd36922 fix(shell): a multi-line snippet never types into a shell that would run each line [skip ci]
Without bracketed paste every line break is an Enter; the picker says so
and inserts nothing.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 17:46:46 -05:00
Alphaeus Mote 7c3488705d feat(editor): full PowerShell IntelliSense catalog — .NET types and members, 1,100 commands [skip ci]
- .NET: 2,664 types across 68 namespaces (System, IO, Net, Text, Collections,
  Security/Cryptography, Diagnostics, Threading, Management.Automation,
  Microsoft.Win32, DirectoryServices, Xml, Web, InteropServices, …) with
  overload signatures, constants, enum values, constructors, the 107 type
  accelerators and ETS members. [Type]:: lists static members and new(),
  [System.IO. completes namespaces and types, generic arguments included.
- Commands: core Microsoft.PowerShell.* modules, CimCmdlets, NetTCPIP,
  NetSecurity, ScheduledTasks, Storage, Defender, PKI, Dism, BitLocker, … with
  typed parameters, parameter sets (syntax in hover), ValidateSet/enum values
  after -Parameter, output types, aliases, and the edition where a command or
  parameter exists on only one of 5.1 / 7. 680 curated synopses.
- Instance members after $x. when the type is evident: [T]$x declarations and
  params, assignments from casts, ::new(), static members, New-Object,
  commands (output types, Get-CimInstance class, registry and Cert: paths),
  pipelines (Where/Sort/Select -ExpandProperty/-Property), foreach loops,
  $_ in ForEach-Object/Where-Object and catch blocks, hashtable and
  [pscustomobject] literal keys, CIM class properties, $Files.<name>.
- Signature help for method and constructor overloads; hover for types,
  members, parameters, aliases and inferred variable types.
- Catalog JSON loads as two lazy chunks on first PowerShell focus or
  completion; generator under src/WebUI/scripts/powershell-catalog.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 17:45:57 -05:00
Alphaeus Mote 4f689ba4be feat(scripts): Snippets library for the editors and the remote shell [skip ci]
A shared library of code to insert, under Automation > Snippets. 55 built-in
snippets ship with the server (PowerShell for Windows admins, Bash for Linux,
and ExecuteR's own: exit 3010/194, $Secrets, $Files, $ExecuteRJobDir,
$Trigger); operators add their own. Built-ins come from code with fixed ids:
they can be read and copied, never changed or deleted.

- /api/snippets CRUD plus /api/snippets/{id}/copy: Scripts View to read,
  Manage Scripts to change, audited under Scripts.
- Script and function editors: snippets for the editor's language appear in
  completions (CompletionItemKind.Snippet) and in a searchable Snippets picker
  that inserts at the cursor with live tab stops.
- Remote shell: the Snippets picker types one at the prompt, tab stops filled
  with their defaults, no Enter.
- Tab stops are ${1:default}, ${1}, ${1|a,b|} and ${0}; everything else is
  code as written (Bash's ${1:-x} included), converted to Monaco's syntax at
  insertion.

Migration for all three providers.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 17:42:41 -05:00
Alphaeus Mote 244032f7a9 feat(devices): Restart and Shut Down for devices and groups [skip ci]
Restart… and Shut Down… in the device, selection and group menus start a
run of a built-in script (never stored) with Restart After Run on, so the
delay, the warning, cancel-while-scheduled, AllowRestart and the run's
targets, exclusions, Only Devices Online Now (on by default) and stagger
spread all come from the existing pipeline. POST /api/power, permission
devices.power (Admin, Operator, Help Desk).

Install Pending Updates (Windows, off by default) passes
SHUTDOWN_INSTALL_UPDATES only when asked; off, updates waiting for
"Update and restart" stay waiting. Shutting down is SHUTDOWN_POWEROFF on
Windows (wpeutil shutdown on PE) and logind PowerOff / ScheduleShutdown
("poweroff") / poweroff.target on Linux. Console actions give Windows a
planned Other: Maintenance reason. Shut down and updates need agent
1.14.0: older agents get their job failed instead of restarting.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 17:24:11 -05:00
Alphaeus Mote a431eadd2f fix(release): a rerun never attaches a second copy of a published file [skip ci]
Assets were skipped only when name and size matched. A rerun rebuilds the
binaries, whose sizes differ by a few bytes, so v1.13.0's rerun attached ten
duplicates the published checksums do not describe. Skip by name.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 13:13:57 -05:00
Alphaeus Mote e1fcdf4cea feat(scripts): Run As Each Signed-In User [skip ci]
The script editor's Run As is now a choice: Agent Account, Signed-In User, or
Each Signed-In User. Each runs the script once per signed-in user, in turn,
under one timeout; any failure fails the job and names who. Nobody signed in
runs nothing and succeeds. The server refuses it for agents before 1.14.0.
Migration for all three providers.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 12:28:54 -05:00
Alphaeus Mote b05837d51f feat(shell): choose which signed-in user a Run As shell opens as [skip ci]
The agent lists who is signed in with each shell state; the console's Run As
menu offers each name, and the agent opens as that user only while they are
signed in. Several users with nobody at the console is no longer a dead end.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 12:04:50 -05:00
Alphaeus Mote 3832790484 Merge branch 'feat/install-repair' [skip ci] 2026-11-18 09:29:49 -05:00
Alphaeus Mote 21e9bad12f feat(groups): script groups, joined and left by what a script reports [skip ci]
- Every script gets built-ins: Set-ExecuteRGroupMembership (member when the
  value is true, above 0, a non-empty collection or yes-like text; pipe results
  in), Add-/Remove-ExecuteRGroupMembership, and executer_group in Bash. They
  need no credentials: the agent takes their lines out of the output and sends
  the answers with the job's final state.
- The server adds or removes the device in that script group, creating it (top
  level, kind Script) the first time a device joins. Each run decides again.
- Only script groups change: a curated group by that name is ignored, so a
  device can never add itself to one. Last answer per group wins; 25 a job.
- Console: Script kind in the group editor, tree and lists (reported devices,
  no hand-listing), editor completions and snippets for the built-ins.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 09:29:48 -05:00
Alphaeus Mote 0b85bd5e8a feat(install): idempotent install scripts that upgrade or repair a failed agent [skip ci]
Every served install script (Windows/WinPE PowerShell 5.1, Linux and macOS
bash) now looks at the device before acting: a healthy, current agent
enrolled with this server is left alone (Already Installed), an older one is
upgraded in place with its enrollment kept, a failed one (service missing,
disabled, stopped or crash-looping, watchdog down, binary missing or broken,
Windows Installer registration or cache gone) is restarted through the
agent's own initialize and, if that does not help, reinstalled (MSI repair
REINSTALL=ALL REINSTALLMODE=vamus, cache restored from the kept package,
uninstall+install with ProgramData and the registry key set aside as a last
resort; Linux/macOS move files in one by one and re-register the unit or
daemon). The bootstrap token is used only when there is no usable credential
or the agent points at another server, never printed, and masked out of
failure messages. One setup at a time, leftovers of interrupted runs cleared.
Each run ends with one outcome line and exits 1 on failure.

The agent's status verb now prints a JSON line with version, server URL,
credential state (valid/missing/unreadable/other-device) and whether a
bootstrap token is pending, which the scripts read.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 09:20:40 -05:00
Alphaeus Mote 505e9849eb Merge branch 'feat/log-format' [skip ci] 2026-11-18 09:03:20 -05:00
Alphaeus Mote 0e2056ca6c feat(runs): run again on a status's devices, the checked ones or the failed ones [skip ci]
- Each status tile of a run (Failed, Timed Out, Skipped, ...) has Run Again on
  These: right-click it or use its ⋯.
- Checked rows get Run Again on N beside Download Logs.
- The run page adds Run Again on N Failed (failed and timed out) next to Run Again.
- The same from a script's Executions panel. Each opens Run Script with those
  devices as targets.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 09:03:11 -05:00
Alphaeus Mote 3e994102ed feat(agent): shells and scripts can run as the signed-in user [skip ci]
- Remote Shell gets Run As: Agent Account (default) or Signed-In User. Windows
  starts the shell with the user's own token, environment and profile folder on
  their desktop, headless; Linux and macOS start their login shell through su -l.
- Scripts get Run As Signed-In User. Every engine then runs out of process as the
  user (PowerShell 7 in the agent's built-in host, 5.1, Bash; su on unix), with
  no window, and the user is given that job folder only.
- The user is the console's, else the only one signed in; several and nobody at
  the console is refused rather than guessed.
- The server never sends either to agents older than 1.13.0 (they would ignore it
  and run as the agent's account): such jobs are created failed, the shell is
  refused. Migration for all three providers.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 08:59:56 -05:00
Alphaeus Mote 28b2a53c29 feat(logging): one log line format everywhere, repeated warnings bounded [skip ci]
Every text line ExecuteR writes now reads
[2026-11-16T17:53:40.653Z] - [Category] - [LEVEL] - message key=value:
UTC time to the millisecond, a short category (the logging type without its
namespace, or Agent/Server), TRACE..FATAL, the rendered message and the
properties it did not use as key=value (correlation fields kept, enrichment
noise left out). Serilog writes it through LogLineFormatter (console, file
and the live views' message text); LOG_JSON keeps compact JSON. The watchdog
and its MSI/removal runners write the same format, and the Rust screen host
too (a tracing layer), with the agent taking each host line apart and logging
it once at the host's level and category, without a second timestamp.

LogLineParser reads the format back and the old ones still in device files
(services' [yyyy-MM-dd HH:mm:ss.fff LVL] Source: message, the watchdog's
...Z [LVL] message, tracing's default); the watchdog's live view uses it.

A warning, error or fatal that repeats (same level, SourceContext and
template) is written once, then counted for 60 s; the window's end writes one
line with repeated=N window=60s, a quiet window forgets it, at most 1,000 keys
are tracked and disposing writes open counts. The screen host does the same.

The console's log viewer shows the new level names and categories and copies
lines in the file format.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 08:55:11 -05:00
Alphaeus Mote 09818d81c4 feat(console): agent downloads under Storage & Agent Packages, break-glass in the hover, more terminal themes [skip ci]
- The Agent Downloads card (public links, package list) moves from Enrollment
  Tokens to the Storage & Agent Packages tab.
- Built-In Sign-In drops the Break-Glass Account row; the card's hover names it.
- Eleven more terminal themes: Dracula, One Dark, Monokai, Nord, Gruvbox Dark,
  Tokyo Night, Ubuntu, High Contrast, Green Phosphor, Amber, Solarized Light.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 08:07:32 -05:00
Alphaeus Mote 34a46f3c40 feat(shell): terminal themes, text size and longer scrollback [skip ci]
Terminal Settings (per browser, live in every open shell, docked or popped
out): five themes, text size 9-28 px (Ctrl + = / - / 0 and Ctrl + wheel in
the terminal), scrollback 1,000-25,000 lines, 10,000 by default (was
xterm's 1,000).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 16:56:31 -05:00
162 changed files with 32785 additions and 678 deletions
+207 -3
View File
@@ -1042,7 +1042,7 @@ ExecuteR-Agent.exe start start the service
ExecuteR-Agent.exe stop stop the service
ExecuteR-Agent.exe initialize install + start
ExecuteR-Agent.exe remove stop + remove the service
ExecuteR-Agent.exe status machine- and human-readable state
ExecuteR-Agent.exe status JSON line (service, version, server, credential) + human-readable
ExecuteR-Agent.exe version unified build version
ExecuteR-Agent.exe run <name|id> start an On Demand script (see "On Demand and the device CLI")
ExecuteR-Agent.exe upload <path> send files up to S3 (see "Device uploads to S3")
@@ -1098,6 +1098,53 @@ back. Closing the window brings it back when the console is showing that
device's shell and ends the session otherwise; reloading or closing the
console tab ends every popped-out shell, since they run on its page.
**Terminal Settings** (the **Tt** button; theme and text size also sit in a
pop-out's toolbar) are remembered per browser and apply to every open shell at
once: a theme (Dark, Classic, PowerShell Blue, Solarized Dark, Dracula, One Dark,
Monokai, Nord, Gruvbox Dark, Tokyo Night, Ubuntu, High Contrast, Green Phosphor,
Amber, Light, Solarized Light), the text
size (9-28 px; in the terminal Ctrl + = / Ctrl + - or Ctrl + mouse wheel, Ctrl + 0
resets) and the scrollback, the output lines kept above the screen (1,000 to
25,000; 10,000 by default). Older lines drop off as new output arrives.
**Clipboard.** Copy and paste work as in Windows Terminal:
- **Copy:** Ctrl+Shift+C or Ctrl+Insert, or Ctrl+C while text is selected
(with nothing selected, Ctrl+C still interrupts).
- **Paste:** Ctrl+V, Ctrl+Shift+V or Shift+Insert.
- **macOS:** ⌘C and ⌘V.
- **Right-click** copies the selection, or pastes when nothing is selected.
- The **Copy** and **Paste** buttons sit on the shell page and in a pop-out's
toolbar.
The browser asks once for permission to read the clipboard; the keyboard paste
needs no permission. On plain HTTP the browser gives no clipboard reading: the
keys and copying still work, but there is no **Paste** button, and a right-click
with nothing selected opens the browser's menu.
Terminal Settings can:
- make right-click open the browser menu instead;
- turn on **Copy on Select**;
- turn off **Ask Before Multi-Line Paste**.
That question appears when a paste has line breaks and the shell would run
each line as it arrives. A shell in bracketed paste mode, such as bash 5.1 or
later, takes the paste as one edit and isn't asked about. Pastes over
1 MiB are refused, and large pastes go to the device in 32 KiB pieces.
**Run As** picks whose account a new shell runs as: the **Agent Account**
(LocalSystem, root; the default each time) or the **Signed-In User**: the
console's user, else the only user signed in (several users and nobody at the
console is ambiguous, so the shell is refused rather than guessed), or one of
the signed-in users by name. The agent reports who is signed in with every
shell it opens, and with a refused run-as-user open, so the menu lists them;
it refuses a name that is not signed in (on macOS, anyone but the console's
user). Windows
starts the shell with that user's own token (`WTSQueryUserToken`), environment
and profile folder on their desktop, headless: no window appears for them.
Linux and macOS start the user's login shell through `su -l`. The server
refuses it for agents older than 1.13.0, which would ignore it and start the
agent's account instead; the audit entry records which account was asked for.
---
## Agent upgrades and the watchdog
@@ -1472,6 +1519,37 @@ 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.
**Running the command again is safe.** Every script (Windows, Windows PE,
Linux, macOS) looks at the device before it acts and ends with one outcome
line — `Installed`, `Upgraded`, `Repaired`, `Already Installed` or
`Failed: <reason>` (exit code 1):
| What the device has | What the script does |
|---------------------|----------------------|
| No agent | Installs as above (MSI; the portable ZIP in Windows PE or with `&type=zip`) |
| A healthy agent, as new as the server's package or newer, enrolled with this server | Nothing |
| An older agent | Upgrades in place (the MSI as a major upgrade; Linux/macOS lay the files down again); the enrollment is kept |
| Service missing, disabled, stopped or crash-looping; watchdog not running | Restarts it through the agent's own `initialize` (re-registers the service as Automatic, starts agent and watchdog); if that does not help, installs the package again |
| Agent binary missing or not running; Windows Installer registration or its cached package gone | Installs the package again: the same MSI build as a repair (`REINSTALL=ALL REINSTALLMODE=vamus`, re-caching it; a lost cache is first restored from the MSI the agent keeps under `%ProgramData%\ExecuteR\packages`), another build as an upgrade, every file laid down (`amus`). Only when Windows Installer refuses that does it uninstall and install again, with `%ProgramData%\ExecuteR` and `HKLM\SOFTWARE\ExecuteR` set aside and put back, so the enrollment and settings survive. Linux/macOS move the files in one by one and register the unit / daemon again |
| No usable credential (missing, unreadable, of other hardware), or pointed at another server | Hands the agent this command's bootstrap token and restarts it. A valid enrollment is never replaced, so the device keeps its identity; re-enrolling the same hardware keeps the same device row anyway |
The decision reads `executer-agent status` / `ExecuteR-Agent.exe status`,
whose first line is JSON: service state, version, server URL, credential
(`valid`, `missing`, `unreadable`, `other-device`; an expired credential is
still `valid`, it renews itself) and whether a bootstrap token is pending —
never the token. Health means the service is registered, enabled and still
running a few seconds later, the watchdog runs, the credential is valid and
the server URL matches (case and a trailing slash aside; a Group Policy
`ServerURL` pointing elsewhere is a failure, not something the script
overrides). The script embeds the version the package link serves, so a
current device downloads nothing. Interrupted runs do not break a rerun: one
setup runs at a time (a global mutex on Windows, a lock directory on
Linux/macOS), leftover downloads and half-moved files are cleared, a Windows
Installer operation in progress is waited for, and data set aside by an
interrupted last-resort reinstall is put back first. The token goes only to
`msiexec`'s hidden `BOOTSTRAPTOKEN`, the agent's registry / `agent.json`, or
`configure --token`; it is masked out of failure messages.
![Add device](docs/screenshots/add-device.png)
---
@@ -1714,6 +1792,26 @@ roles, making Admin/Operator/Viewer handy templates.
![Script editor](docs/screenshots/script-editor.png)
### Snippets
**Snippets** (under Automation) is a shared library of code to insert: about
fifty built-in snippets ship with the server (try/catch logging, registry,
services, event logs, disk space, installed software, pending restart,
downloads, retries, certificates, local admins, systemctl, journalctl,
apt/dnf, and ExecuteR's own `exit 3010`, `$Secrets`, `$Files`,
`$ExecuteRJobDir` and `$Trigger`), and operators add their own (View Scripts
to read, Manage Scripts to change; changes are audited under Scripts).
Built-ins cannot be changed; **Copy to Edit** makes one your own.
In the script and function editors, snippets for the editor's language appear
in completions and under **Snippets** in the editor's toolbar, inserting at
the cursor. On a remote shell, **Snippets** types one at the prompt with its
tab stops filled in and no Enter. A snippet's tab stops are `${1:default}`,
`${1}` (the same text again), `${1|a,b|}` (a choice) and `${0}` (where the
cursor ends); everything else is code as written, Bash's `${1:-default}`
included. The API is `/api/snippets` (`GET`, `POST`), `/api/snippets/{id}`
(`GET`, `PUT`, `DELETE`) and `/api/snippets/{id}/copy` (`POST`).
---
## Script engines
@@ -1778,7 +1876,9 @@ Per-script options in the editor (Details):
| Option | Default | What it does |
|--------|---------|--------------|
| **Run From File** | off | PowerShell 7 stages the script in the job folder and runs it by path (`AddCommand`), not from memory. PowerShell 5 and Bash always run from a file. |
| **Set Working Directory to Script Folder** | off | Starts a staged script in its job folder (the process's directory for 5.1 and Bash; the runspace's location for PowerShell 7, never the shared agent process's). Only with a staged file. Off keeps the engine's usual directory: the agent's own (`C:\Windows\System32` for the service). |
| **Set Working Directory to Script Folder** | off | Starts a staged script in its job folder (the process's directory for 5.1 and Bash; the runspace's location for PowerShell 7, never the shared agent process's). Only with a staged file. Off keeps the engine's usual directory: the agent's own (`C:\Windows\System32` for the service), or the user's profile folder or home with Run As Signed-In User. |
| **Run As** | Agent Account | **Each Signed-In User** runs the script once per signed-in user, one after another, each run as described below, under one timeout. The output marks each user's part, and the job fails if any run fails, naming those users. Nobody signed in: nothing runs and the job succeeds. Needs agent 1.14.0 or later; the server fails the job for older agents. **Signed-In User**: below. |
| **Run As Signed-In User** | off | Runs the script as the person signed in on the device (the console's user, else the only one signed in) instead of the agent's account. Every engine runs out of process: PowerShell 7 in the agent's built-in host, 5.1 in `powershell.exe`, Bash in `bash` (through `su` on Linux and macOS), with output and errors but no progress records. Windows uses the user's token, environment (plus the bundled modules) and profile folder, headless, so nothing appears on their screen. The user is given that job folder only (Windows: Modify on it; Linux/macOS: it becomes theirs and the job root traverse-only). Nobody signed in, or several and nobody at the console, fails the job; so does an agent older than 1.13.0, which the server never sends it to. |
| **Clean Up After Run** | on | Deletes the job folder when the run ends. |
| **Restart After Run** | Off | Restarts the device after the run: **Always**, or **When the Script Asks**, with an optional delay (up to 60 minutes) and an optional warning for signed-in users. See [Restart After Run](#restart-after-run). |
@@ -2052,6 +2152,32 @@ registry or `agent.json` > default; MSI property `ALLOWRESTART`; ADMX
*Allow Restart After Run*). Off, a requested restart is refused and the job says
so; it is read when the run ends and again when a delay ends.
### Restart and Shut Down
**Restart…** and **Shut Down…** in a device's menu, a selection's Actions and
a group's menu (permission `devices.power`: Admin, Operator, Help Desk) start
one run of a built-in script that does nothing but end, with Restart After Run
set to Always. So it is a run like any other (`POST /api/power`, audited as
`jobs/restart` or `jobs/shut-down`), with:
| Option | Default | |
|--------|---------|---|
| Exclude | none | Devices and groups left out, as a script's run. |
| Delay | 0 | Up to 60 minutes after each device's job; the job's chip cancels it meanwhile. |
| Warn Signed-In Users | Off | The system's own notice, 15 s to 10 min, when someone is signed in. |
| Install Pending Updates | Off | Windows: `SHUTDOWN_INSTALL_UPDATES` is passed only when on, so updates waiting for *Update and restart* / *Update and shut down* stay waiting. An update Windows has already part-installed still finishes on any restart; that is servicing, not a choice. |
| Only Devices Online Now | **On** | Off: an offline device restarts (or shuts down) as soon as it reconnects. |
| Stagger | Off | Spreads the devices over up to 24 hours, in batches, as a script's run. |
Shutting down is `SHUTDOWN_POWEROFF` on Windows (a full shutdown, never Fast
Startup's hybrid one; `wpeutil shutdown` on Windows PE) and logind's `PowerOff`
/ `ScheduleShutdown("poweroff", …)` on Linux (`poweroff.target` without logind).
Console-ordered actions give Windows a planned *Other: Maintenance* reason.
`AllowRestart` off refuses both. Shutting down and installing updates need agent
**1.14.0** or later: an older agent would restart instead (and skip the
updates), so its job fails with the reason; a plain restart goes to any agent.
A shut-down device's job reads *Back On* once it is switched on again.
---
## Sequences
@@ -2198,13 +2324,14 @@ way as manual runs.
## Device groups and script triggers
Groups form a **tree**. Each group is one of three kinds:
Groups form a **tree**. Each group is one of four kinds:
| Kind | Members |
|------|---------|
| **Folder** | None of its own — it organizes the groups nested under it |
| **Static** | An explicit list of devices |
| **Dynamic** | The devices matching its rules, evaluated against live device data |
| **Script** | The devices whose scripts last reported they belong ([Script groups](#script-groups)) |
A group's membership **includes every group nested under it**, so running,
scheduling or scoping a role on `Sites` reaches `Sites › Office › Web` too.
@@ -2315,6 +2442,41 @@ Windows PowerShell 5.1 and Bash, the `EXECUTER_TRIGGER_KIND`, `_USER`,
`_SESSION_ID`, `_OCCURRED_UTC` and `_SCHEDULE_ID` environment variables. `Kind`
is `enrollment`, `agent-ready`, `logon` or `device-cli`.
### Script groups
A script decides whether its device belongs in a group, on the device, and the
console follows: every script has the built-ins below (no credentials: the agent
carries the answer with the job's final state), the device joins or leaves the
named group when the job ends, and the group is created (top level, kind Script)
the first time a device joins it. Each run decides again, so a scheduled script
keeps the group current.
```powershell
# Member when the value is $true, above 0, a non-empty collection, or text other than false/0/no/off.
Get-Package -Name 'Java*' -ErrorAction SilentlyContinue | Set-ExecuteRGroupMembership 'Has Java'
Set-ExecuteRGroupMembership -Name 'Low Disk' -Value ((Get-PSDrive C).Free -lt 10GB)
Add-ExecuteRGroupMembership 'Pilot Ring'
Remove-ExecuteRGroupMembership 'Pilot Ring'
```
```bash
executer_group "Has Java" "$(pgrep -c java)" # true/false, a number (above 0) or text; default true
```
- The job's output shows each answer as a line (`Script group “Has Java”: this
device is a member.`); the built-ins' own marker lines never reach the log.
- Names are matched without regard to case; the last answer per group in a job
wins; a job reports on at most 25 groups.
- Only script groups change. A name that belongs to a static, dynamic or folder
group is ignored (logged on the server), so a device can never put itself into
a group an operator curates; a device only ever changes its own membership.
- Script groups can be renamed, moved into folders, targeted, scheduled and
used in role scopes like any group; their members cannot be listed by hand.
Saving one as dynamic or a folder drops its reported devices. Not being a
member of a group that does not exist yet creates nothing.
- Joins, leaves and the group's creation are audited (actor `script:<name>`)
and show in the activity feed.
### At Logon
The agent watches interactive sign-ins and reports each one with the user
@@ -2773,6 +2935,48 @@ cookies and authorization headers. A structured property with one of those names
(`{Password}`, `{Jwt}`, … see `Redaction.NeverLog`) is masked as `[redacted]`
before any sink sees it, live views included.
### Log line format
Every text line any ExecuteR process writes (server, agent, watchdog, MSI and
removal runners, screen host) has one shape:
```text
[2026-11-16T17:53:40.653Z] - [LeafRouter] - [INFO] - The site's leaf answers again; moving back to it from the hub leaf=wss://172.18.16.104:9001
[2026-11-16T17:53:40.687Z] - [EventBus] - [WARN] - The site's leaf could not be reached; the bus goes through the server meanwhile reason="TLS: certificate expired"
[2026-11-16T17:54:40.701Z] - [EventBus] - [WARN] - The site's leaf could not be reached; the bus goes through the server meanwhile reason="TLS: certificate expired" repeated=37 window=60s
```
- **Time**: UTC, ISO 8601, milliseconds, `Z`.
- **Category**: a short component name: the logging type without its namespace
or generic arguments (`Agent.Screen.ScreenSessions` → `ScreenSessions`, a
nested `Outer+Inner` → `Outer.Inner`); `Agent` or `Server` for a line with no
type; `Watchdog`, `MsiRunner`, `RemovalRunner` for the watchdog's;
`ScreenHost` (or a dependency's crate, `ironrdp_server`) for the screen host's.
- **Level**: `TRACE`, `DEBUG`, `INFO`, `WARN`, `ERROR`, `FATAL`.
- **Message**: rendered with strings bare, then every property the message did
not use as ` key=value` (correlation fields such as `CorrelationId`,
`ClientId`, `JobId` included; `SourceContext`, `MachineName`, `Application`,
`EventId` and the framework's `RequestId`/`ConnectionId`/`ActionId` left out).
A value with whitespace, `=` or `"` is double-quoted with `\"` escaped; a
missing value is `null`. An exception follows on the next lines.
`LOG_JSON=1` writes compact JSON instead, unchanged. The live views carry the
same message text. Log files from earlier versions
(`[2026-11-06 12:00:00.000 INF] Source: message`, the watchdog's
`2026-11-06 12:00:00.000Z [INF] message`) are still read by the watchdog's live
view (`LogLineParser`).
**Repeats are bounded.** A warning, error or fatal is the same as another when
its level, category (full SourceContext) and message template match. The first
is written at once; the same one again within 60 s is only counted, and when the
window ends with any counted, one line is written: the last of them with
`repeated=N window=60s`. While it keeps repeating that summary comes once a
minute; a minute without it forgets it, so the next one is written at once. At
most 1,000 distinct events are tracked (the oldest goes first, with its count
written), and stopping the process writes every count still open. Information
and below are never held back. The screen host does the same for its own
warnings and errors.
### Live logs and log files in the console
Every process keeps its last 2,000 log lines in memory (a Serilog sink feeding a
+5 -2
View File
@@ -7,7 +7,7 @@ server artifact of that version from ./artifacts attached.
.DESCRIPTION
The version is a release version X.Y.Z (scripts/Get-NextRelease.ps1). Safe to
run again: an existing tag or release of the same commit is reused and files
already uploaded whole are skipped. A tag or release of that version on another
it already has (by name) are skipped, so its first files and checksums stand. A tag or release of that version on another
commit is refused: a version names one commit.
No-ops with a clear message when GITEA_URL/TOKEN/OWNER/REPOSITORY are not all
@@ -109,7 +109,10 @@ if ($assets.Count -eq 0) {
$uploaded = @($release.assets | Where-Object { $_ })
foreach ($asset in $assets) {
if ($uploaded | Where-Object { $_.name -eq $asset.Name -and $_.size -eq $asset.Length }) {
# By name only: a rerun rebuilds the binaries, which are not byte-identical, so a size
# check would attach a second copy that the first run's checksums do not describe.
# A published version keeps the files it was first published with.
if ($uploaded | Where-Object { $_.name -eq $asset.Name }) {
Write-Host "Already uploaded $($asset.Name)"
continue
}
@@ -59,7 +59,7 @@ public static class RemovalHost
DataDirectory = Path.GetFullPath(data),
SelfPath = null,
};
var log = new WatchdogLog(runnerDirectory, console: false, name: RemovalRunner.LogFileName);
var log = new WatchdogLog(runnerDirectory, console: false, name: RemovalRunner.LogFileName, category: "RemovalRunner");
var agentPath = Path.Combine(options.InstallDirectory, options.AgentExecutable);
IAgentService agent;
+1 -1
View File
@@ -192,7 +192,7 @@ public static class WatchdogCli
{
var (options, _) = ParseOptions(args);
options = options with { SelfPath = null };
var log = new WatchdogLog(options.LogDirectory, console: false, name: "ExecuteR-Watchdog-msi");
var log = new WatchdogLog(options.LogDirectory, console: false, name: "ExecuteR-Watchdog-msi", category: "MsiRunner");
var agent = new WindowsAgentService(Branding.AgentServiceName, Path.Combine(options.InstallDirectory, options.AgentExecutable), log);
var watchdog = new WindowsAgentService(Branding.WatchdogServiceName,
Path.Combine(options.InstallDirectory, Branding.WatchdogExecutableName), log);
+19 -6
View File
@@ -6,22 +6,31 @@ namespace Agent.Watchdog;
/// The watchdog's own log: one small rolling file in the agent's log folder
/// (<c>ExecuteR-Watchdog.log</c>, rolled at 1 MB, three files kept), the
/// console in the foreground, and the lines of the current upgrade run kept in
/// memory so a failure's outcome can carry them.
/// memory so a failure's outcome can carry them. Lines are ExecuteR's one log
/// format (as <c>Shared.Infrastructure.Logging.LogLineFormatter</c> writes it,
/// without Serilog, which the watchdog does not carry):
/// <c>[2026-11-16T17:53:40.653Z] - [Watchdog] - [INFO] - message</c>.
/// </summary>
public sealed class WatchdogLog
{
public const long RollBytes = 1024 * 1024;
public const int KeptFiles = 3;
/// <summary>The category of the watchdog's own lines.</summary>
public const string DefaultCategory = "Watchdog";
private readonly Lock gate = new();
private readonly string? path;
private readonly bool console;
private readonly string category;
private readonly List<string> run = [];
private bool fileBroken;
public WatchdogLog(string? directory, bool console, string? name = null)
/// <param name="category">The component each line names (<c>Watchdog</c>, <c>MsiRunner</c>, <c>RemovalRunner</c>).</param>
public WatchdogLog(string? directory, bool console, string? name = null, string category = DefaultCategory)
{
this.console = console;
this.category = category;
if (!string.IsNullOrWhiteSpace(directory))
{
name ??= Path.GetFileNameWithoutExtension(Environment.ProcessPath) is { Length: > 0 } exe
@@ -35,11 +44,11 @@ public sealed class WatchdogLog
/// <summary>Every line written, for tests and the foreground.</summary>
public event Action<string>? Written;
public void Info(string message) => Write("INF", message);
public void Info(string message) => Write("INFO", message);
public void Warn(string message, Exception? exception = null) => Write("WRN", With(message, exception));
public void Warn(string message, Exception? exception = null) => Write("WARN", With(message, exception));
public void Error(string message, Exception? exception = null) => Write("ERR", With(message, exception));
public void Error(string message, Exception? exception = null) => Write("ERROR", With(message, exception));
/// <summary>Starts collecting the lines of an upgrade run.</summary>
public void BeginRun()
@@ -59,12 +68,16 @@ public sealed class WatchdogLog
}
}
/// <summary>One line: <c>[2026-11-16T17:53:40.653Z] - [Watchdog] - [INFO] - message</c>.</summary>
public static string Format(DateTimeOffset time, string category, string level, string message)
=> $"[{time.UtcDateTime.ToString("yyyy-MM-dd'T'HH:mm:ss.fff'Z'", CultureInfo.InvariantCulture)}] - [{category}] - [{level}] - {message}";
private static string With(string message, Exception? exception)
=> exception is null ? message : $"{message}: {exception.GetBaseException().Message}";
private void Write(string level, string message)
{
var line = $"{DateTimeOffset.UtcNow.ToString("yyyy-MM-dd HH:mm:ss.fff'Z'", CultureInfo.InvariantCulture)} [{level}] {message}";
var line = Format(DateTimeOffset.UtcNow, category, level, message);
lock (gate)
{
run.Add(line);
+31 -3
View File
@@ -94,7 +94,7 @@ public static class AgentCli
}
case "status":
return Lifecycle.Status();
return Status();
// Cross-platform enrollment configuration (registry on Windows,
// /etc/executer/agent.json elsewhere) — what the MSI does via
@@ -151,12 +151,20 @@ public static class AgentCli
public static int Remove() => ServiceLifecycle.Remove();
public static int Start() => ServiceLifecycle.Start();
public static int Stop() => ServiceLifecycle.Stop();
public static int Status() => ServiceLifecycle.Status();
public static (bool Installed, string State, string? StartType) Query() => ServiceLifecycle.Query();
public static string ServiceName => Branding.AgentServiceName;
/// <summary>Nothing after the human-readable lines on Windows.</summary>
public static int Status() => 0;
#else
public static int Install() => UnixServiceLifecycle.Install();
public static int Remove() => UnixServiceLifecycle.Remove();
public static int Start() => UnixServiceLifecycle.Start();
public static int Stop() => UnixServiceLifecycle.Stop();
public static (bool Installed, string State, string? StartType) Query() => UnixServiceLifecycle.Query();
public static string ServiceName => OperatingSystem.IsMacOS() ? Branding.AgentLaunchdLabel : Branding.AgentSystemdUnit;
/// <summary>systemctl status / launchctl print after the human-readable lines.</summary>
public static int Status() => UnixServiceLifecycle.Status();
#endif
}
@@ -187,6 +195,26 @@ public static class AgentCli
return exitCode;
}
/// <summary>
/// One JSON line first (service, state, version, server, credential: what the
/// install scripts read to decide between leave alone, repair and re-enroll),
/// the human-readable lines after it. Always 0: the report is the answer.
/// </summary>
private static int Status()
{
var (installed, state, startType) = Lifecycle.Query();
var report = AgentHealth.ReadLocal();
Console.WriteLine(AgentHealth.Json(Lifecycle.ServiceName, installed, state, startType, report));
Console.WriteLine($"Service '{Branding.AgentServiceDisplayName}': {state}{(startType is null ? "" : $" ({startType})")}");
foreach (var line in AgentHealth.Describe(report))
{
Console.WriteLine(line);
}
Lifecycle.Status();
return 0;
}
private static int Configure(string[] args)
{
string? url = null;
@@ -274,7 +302,7 @@ public static class AgentCli
Console.WriteLine(" start Start the installed service");
Console.WriteLine(" stop Stop the service (the watchdog never undoes a stop)");
Console.WriteLine(" initialize install + start (agent and watchdog)");
Console.WriteLine(" status Show service and enrollment state");
Console.WriteLine(" status Show service, version, server and enrollment state (JSON line first)");
Console.WriteLine(" version Print the build version");
Console.WriteLine(" run <name|id> [-p Name=Value]... [--wait] [--timeout <s>]");
Console.WriteLine(" Start an On Demand script (run --list shows them, run --help for more)");
+156
View File
@@ -0,0 +1,156 @@
using System.Text.Encodings.Web;
using System.Text.Json;
using Agent.Configuration;
using Agent.Enrollment;
using Agent.Identity;
using Agent.Platform;
using Microsoft.Extensions.Logging.Abstractions;
using Shared.Infrastructure.Constants;
using Shared.Infrastructure.Versioning;
namespace Agent.Commands;
/// <summary>
/// What <c>status</c> reports beyond the service state: the version, the server the
/// agent is pointed at and whether its enrollment credential is usable. The install
/// scripts read it to choose between leaving a device alone, repairing it and
/// re-enrolling it with their bootstrap token. Never the token itself.
/// </summary>
public static class AgentHealth
{
/// <summary>The credential loads and belongs to this hardware (an expired one renews itself).</summary>
public const string CredentialValid = "valid";
/// <summary>No credential file: never enrolled, or purged.</summary>
public const string CredentialMissing = "missing";
/// <summary>A credential file that does not decrypt or parse.</summary>
public const string CredentialUnreadable = "unreadable";
/// <summary>A credential of another client id: the hardware changed; the agent re-enrolls as a new device.</summary>
public const string CredentialOtherDevice = "other-device";
public sealed record Report(
string Version,
string? ServerUrl,
string Credential,
string? EnrollmentId,
DateTimeOffset? CredentialExpiresUtc,
bool BootstrapTokenPending);
/// <summary>
/// The report from configuration (Group Policy first, as the agent reads it), the
/// credential store and the client id this hardware computes (null when it cannot
/// be read: the credential is then judged without it).
/// </summary>
public static Report Read(
AgentConfiguration configuration, ICredentialStore credentials, bool credentialFileExists, Func<string?> clientId, string version)
{
string credential;
AgentCredentials? stored = null;
if (!credentialFileExists)
{
credential = CredentialMissing;
}
else if ((stored = credentials.Load()) is null)
{
credential = CredentialUnreadable;
}
else if (clientId() is { } current && !string.Equals(current, stored.ClientId, StringComparison.Ordinal))
{
credential = CredentialOtherDevice;
}
else
{
credential = CredentialValid;
}
return new Report(
version,
string.IsNullOrWhiteSpace(configuration.ServerUrlText.Value) ? null : configuration.ServerUrlText.Value.Trim(),
credential,
stored?.EnrollmentId.ToString("D"),
stored?.ExpiresUtc,
configuration.HasBootstrapToken);
}
/// <summary>The report of this machine's installed agent.</summary>
public static Report ReadLocal()
{
var registry = PlatformServices.CreateRegistryStore();
var configuration = new AgentConfigurationLoader(registry, allowEnvironment: false).Load();
var store = new CredentialStore(NullLogger<CredentialStore>.Instance);
var file = Path.Combine(Branding.AgentProgramDataDirectory, Branding.CredentialFileName);
return Read(configuration, store, File.Exists(file), LocalClientId, BuildVersion.Resolve(typeof(AgentHealth).Assembly));
}
private static string? LocalClientId()
{
try
{
return ClientIdentityFactory.ComputeClientId(PlatformServices.CreateIdentitySource().Read());
}
catch (Exception)
{
// No hardware identity here (WinPE without WMI): judge the credential on its own.
return null;
}
}
/// <summary>
/// The machine-readable line <c>status</c> prints first: one JSON object, URLs
/// unescaped so a shell script can read fields with sed.
/// </summary>
public static string Json(string service, bool installed, string state, string? startType, Report report)
{
using var buffer = new MemoryStream();
using (var writer = new Utf8JsonWriter(buffer, new JsonWriterOptions { Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping }))
{
writer.WriteStartObject();
writer.WriteString("service", service);
writer.WriteBoolean("installed", installed);
writer.WriteString("state", state);
if (startType is not null)
{
writer.WriteString("startType", startType);
}
writer.WriteString("version", report.Version);
writer.WriteString("serverUrl", report.ServerUrl);
writer.WriteString("credential", report.Credential);
writer.WriteString("enrollmentId", report.EnrollmentId);
if (report.CredentialExpiresUtc is { } expires)
{
writer.WriteString("credentialExpiresUtc", expires.ToUniversalTime().ToString("O"));
}
else
{
writer.WriteNull("credentialExpiresUtc");
}
writer.WriteBoolean("bootstrapTokenPending", report.BootstrapTokenPending);
writer.WriteEndObject();
}
return System.Text.Encoding.UTF8.GetString(buffer.ToArray());
}
/// <summary>The human-readable lines after the JSON one.</summary>
public static IEnumerable<string> Describe(Report report)
{
yield return $"Version: {report.Version}";
yield return $"Server: {report.ServerUrl ?? "(not configured)"}";
yield return report.Credential switch
{
CredentialValid => $"Enrollment: {report.EnrollmentId ?? "enrolled"}",
CredentialMissing => "Enrollment: none",
CredentialUnreadable => "Enrollment: credential unreadable",
CredentialOtherDevice => "Enrollment: credential of another device",
_ => $"Enrollment: {report.Credential}",
};
if (report.BootstrapTokenPending)
{
yield return "Bootstrap token: present (enrollment pending)";
}
}
}
+11 -26
View File
@@ -1,6 +1,4 @@
using System.Globalization;
using System.Text;
using System.Text.RegularExpressions;
using Shared.Contracts.Api;
using Shared.Infrastructure.Logging;
@@ -12,7 +10,7 @@ namespace Agent.Logs;
/// got shorter, or a different file, was rolled: it is read from its start. Only whole
/// lines are taken; a line still being written waits for the next poll.
/// </summary>
public sealed partial class LogFileFollower(Func<string?> locate)
public sealed class LogFileFollower(Func<string?> locate)
{
/// <summary>How much of the end of the file the first poll reads.</summary>
public const int Backlog = 64 * 1024;
@@ -96,33 +94,20 @@ public sealed partial class LogFileFollower(Func<string?> locate)
}
}
/// <summary><c>2026-11-06 12:00:00.000Z [INF] message</c>, as <c>WatchdogLog</c> writes it.</summary>
/// <summary>
/// <c>[2026-11-06T12:00:00.000Z] - [Watchdog] - [INFO] - message</c>, as <c>WatchdogLog</c>
/// writes it, or a line from before that format (see <see cref="LogLineParser"/>).
/// Anything else (an exception's stack) is a line of its own, as information.
/// </summary>
private void Add(string line)
{
var match = LinePattern().Match(line);
if (!match.Success)
if (LogLineParser.TryParse(line, out var parsed))
{
Live.Append(parsed.TimestampUtc, parsed.Level, parsed.Category, parsed.Message);
}
else
{
Live.Append(DateTimeOffset.UtcNow, LogLevels.Information, null, line);
return;
}
var time = DateTimeOffset.TryParseExact(
match.Groups["time"].Value, "yyyy-MM-dd HH:mm:ss.fff", CultureInfo.InvariantCulture,
DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal, out var parsed)
? parsed
: DateTimeOffset.UtcNow;
var level = match.Groups["level"].Value switch
{
"VRB" => LogLevels.Verbose,
"DBG" => LogLevels.Debug,
"WRN" => LogLevels.Warning,
"ERR" => LogLevels.Error,
"FTL" => LogLevels.Fatal,
_ => LogLevels.Information,
};
Live.Append(time, level, null, match.Groups["message"].Value);
}
[GeneratedRegex(@"^(?<time>\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}\.\d{3})Z \[(?<level>[A-Z]{3})\] (?<message>.*)$")]
private static partial Regex LinePattern();
}
+194
View File
@@ -0,0 +1,194 @@
#if WINDOWS_AGENT
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Security.Principal;
using System.Text;
using Agent.Sessions;
namespace Agent.Platform;
/// <summary>
/// The signed-in user's primary token (<c>WTSQueryUserToken</c>, which only LocalSystem may
/// call), and what a process started with it gets: the user's own environment block and
/// profile folder, as Explorer would give it.
/// </summary>
internal sealed partial class WindowsUserToken : IDisposable
{
private const int ErrorPrivilegeNotHeld = 1314;
private WindowsUserToken(IntPtr handle, string name)
{
Handle = handle;
Name = name;
}
public IntPtr Handle { get; private set; }
/// <summary>DOMAIN\user, as the session reports it.</summary>
public string Name { get; }
/// <summary>The user's SID (for granting it a job folder).</summary>
public SecurityIdentifier? Sid
{
get
{
using var identity = new WindowsIdentity(Handle);
return identity.User;
}
}
public static WindowsUserToken Open(SignedInUser user)
{
if (user.WindowsSession is not { } session)
{
throw new InvalidOperationException($"{user.Name} has no session to run in.");
}
if (!WTSQueryUserToken((uint)session, out var token))
{
var error = Marshal.GetLastWin32Error();
throw new Win32Exception(error, error == ErrorPrivilegeNotHeld
? "Only an agent running as LocalSystem can start processes as the signed-in user."
: $"The token of {user.Name} could not be obtained.");
}
return new WindowsUserToken(token, user.Name);
}
/// <summary>The user's profile folder (C:\Users\name), or null when it cannot be read.</summary>
public string? ProfileDirectory()
{
uint size = 0;
GetUserProfileDirectoryW(Handle, null, ref size);
if (size == 0)
{
return null;
}
var buffer = new StringBuilder((int)size);
return GetUserProfileDirectoryW(Handle, buffer, ref size) ? buffer.ToString() : null;
}
/// <summary>
/// The user's environment (not the agent's) with <paramref name="overrides"/> applied and
/// <paramref name="modulePath"/> (the agent's bundled modules) added to PSModulePath, as a
/// CreateProcess block (CREATE_UNICODE_ENVIRONMENT). Free it with <see cref="Marshal.FreeHGlobal"/>.
/// </summary>
public IntPtr EnvironmentBlock(IReadOnlyDictionary<string, string>? overrides, string? modulePath = null)
{
var variables = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
if (CreateEnvironmentBlock(out var block, Handle, false))
{
try
{
foreach (var (name, value) in ReadBlock(block))
{
variables[name] = value;
}
}
finally
{
DestroyEnvironmentBlock(block);
}
}
foreach (var (name, value) in overrides ?? new Dictionary<string, string>())
{
// Keep the caller's spelling (bash under Git Bash is case-sensitive).
variables.Remove(name);
variables[name] = value;
}
if (modulePath is not null)
{
variables["PSModulePath"] = AppendPath(variables.GetValueOrDefault("PSModulePath"), modulePath);
}
return Marshal.StringToHGlobalUni(BuildBlock(variables));
}
/// <summary><paramref name="list"/> (a ;-separated path list) with <paramref name="path"/> at the end, once.</summary>
internal static string AppendPath(string? list, string path)
{
var parts = (list ?? string.Empty).Split(';', StringSplitOptions.RemoveEmptyEntries).ToList();
if (!parts.Contains(path, StringComparer.OrdinalIgnoreCase))
{
parts.Add(path);
}
return string.Join(';', parts);
}
/// <summary>The name=value pairs of a native environment block (UTF-16, double-NUL terminated).</summary>
internal static IEnumerable<KeyValuePair<string, string>> ReadBlock(IntPtr block)
{
var entries = new List<KeyValuePair<string, string>>();
var cursor = block;
while (true)
{
var entry = Marshal.PtrToStringUni(cursor);
if (string.IsNullOrEmpty(entry))
{
break;
}
// Names may start with '=' (per-drive folders): the separator is the next '='.
var equals = entry.IndexOf('=', 1);
if (equals > 0)
{
entries.Add(new(entry[..equals], entry[(equals + 1)..]));
}
cursor += (entry.Length + 1) * sizeof(char);
}
return entries;
}
/// <summary>A block CreateProcess accepts: sorted by name (case-insensitive), each "name=value\0", then a final "\0".</summary>
internal static string BuildBlock(IEnumerable<KeyValuePair<string, string>> variables)
{
var builder = new StringBuilder();
foreach (var (name, value) in variables.OrderBy(v => v.Key, StringComparer.OrdinalIgnoreCase))
{
builder.Append(name).Append('=').Append(value).Append('\0');
}
if (builder.Length == 0)
{
builder.Append('\0');
}
return builder.Append('\0').ToString();
}
public void Dispose()
{
if (Handle != IntPtr.Zero)
{
CloseHandle(Handle);
Handle = IntPtr.Zero;
}
}
[LibraryImport("wtsapi32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static partial bool WTSQueryUserToken(uint sessionId, out IntPtr token);
[LibraryImport("userenv.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static partial bool CreateEnvironmentBlock(out IntPtr environment, IntPtr token, [MarshalAs(UnmanagedType.Bool)] bool inherit);
[LibraryImport("userenv.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static partial bool DestroyEnvironmentBlock(IntPtr environment);
[DllImport("userenv.dll", SetLastError = true, CharSet = CharSet.Unicode)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool GetUserProfileDirectoryW(IntPtr token, StringBuilder? profileDirectory, ref uint size);
[LibraryImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static partial bool CloseHandle(IntPtr handle);
}
#endif
+132 -18
View File
@@ -63,7 +63,8 @@ public static class ExternalScriptRunner
JobFolder? folder = null,
string scriptName = "script",
bool setWorkingDirectory = false,
JobTrigger? trigger = null)
JobTrigger? trigger = null,
Agent.Sessions.SignedInUser? runAs = null)
{
// Child processes inherit PSModulePath, so 5.1 also sees the bundled
// gallery modules (PSResourceGet supports Windows PowerShell 5.1+).
@@ -71,13 +72,22 @@ public static class ExternalScriptRunner
var owned = folder is null;
folder ??= JobFolder.Create(JobRoot.DefaultPath(), Guid.NewGuid());
var run = new ProcessRun(folder, setWorkingDirectory, runAs);
try
{
return engine == ScriptEngine.WindowsPowerShell
? await RunWindowsPowerShellAsync(
content, prelude, parameters, secrets, secretsVariableName, files, filesRoot, folder, scriptName, setWorkingDirectory, trigger, onRecord, cancellationToken)
: await RunBashAsync(
content, prelude, parameters, secrets, files, filesRoot, folder, scriptName, setWorkingDirectory, trigger, onRecord, cancellationToken);
return engine switch
{
ScriptEngine.Bash => await RunBashAsync(
content, prelude, parameters, secrets, files, filesRoot, folder, scriptName, trigger, run, onRecord, cancellationToken),
// PowerShell 7 as the signed-in user: the agent's own engine in a process of theirs
// (the built-in host), with the same wrapper as 5.1.
ScriptEngine.PowerShell => await RunWindowsPowerShellAsync(
content, prelude, parameters, secrets, secretsVariableName, files, filesRoot, folder, scriptName, trigger, run, onRecord, cancellationToken,
AgentLocation.ExecutablePath, [Agent.Shell.WindowsShellResolver.HostVerb]),
_ => await RunWindowsPowerShellAsync(
content, prelude, parameters, secrets, secretsVariableName, files, filesRoot, folder, scriptName, trigger, run, onRecord, cancellationToken,
WindowsPowerShellPath(runAs is not null), []),
};
}
finally
{
@@ -98,10 +108,12 @@ public static class ExternalScriptRunner
DirectoryInfo? filesRoot,
JobFolder folder,
string scriptName,
bool setWorkingDirectory,
JobTrigger? trigger,
ProcessRun run,
Action<NormalizedOutputRecord> onRecord,
CancellationToken cancellationToken)
CancellationToken cancellationToken,
string interpreter,
IReadOnlyList<string> interpreterArguments)
{
var scriptPath = folder.WriteScript(scriptName, ScriptEngine.WindowsPowerShell, content);
@@ -162,14 +174,19 @@ public static class ExternalScriptRunner
var wrapperPath = folder.WriteHelper(WrapperFileName, wrapper.ToString());
return await RunProcessAsync(
"powershell.exe",
$"-NoProfile -NonInteractive -ExecutionPolicy Bypass -File \"{wrapperPath}\"",
interpreter,
[.. interpreterArguments, "-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-File", wrapperPath],
WindowsPowerShellEnvironment(folder, trigger),
setWorkingDirectory ? folder.Path : null,
run,
onRecord,
cancellationToken);
}
/// <summary>Windows PowerShell: by name for the agent's own processes; by full path for a user's (CreateProcessAsUser does not search PATH).</summary>
private static string WindowsPowerShellPath(bool fullPath) => fullPath
? Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.System), "WindowsPowerShell", "v1.0", "powershell.exe")
: "powershell.exe";
private static async Task<ExternalResult> RunBashAsync(
string content,
string? prelude,
@@ -179,8 +196,8 @@ public static class ExternalScriptRunner
DirectoryInfo? filesRoot,
JobFolder folder,
string scriptName,
bool setWorkingDirectory,
JobTrigger? trigger,
ProcessRun run,
Action<NormalizedOutputRecord> onRecord,
CancellationToken cancellationToken)
{
@@ -252,8 +269,17 @@ public static class ExternalScriptRunner
}
}
return await RunProcessAsync(
bash, $"\"{BashPath(scriptPath)}\"", environment, setWorkingDirectory ? folder.Path : null, onRecord, cancellationToken);
return await RunProcessAsync(bash, [BashPath(scriptPath)], environment, run, onRecord, cancellationToken);
}
/// <summary>
/// Where and as whom a script's process runs: the job folder (its working directory with
/// Set Working Directory) and, for Run As Signed-In User, the user.
/// </summary>
internal sealed record ProcessRun(JobFolder Folder, bool SetWorkingDirectory, Agent.Sessions.SignedInUser? RunAs)
{
/// <summary>The job folder with Set Working Directory; otherwise null (the agent's own folder, or the user's home).</summary>
public string? WorkingDirectory => SetWorkingDirectory ? Folder.Path : null;
}
/// <summary>The job folder (EXECUTER_JOB_DIR), the agent (EXECUTER_AGENT_*) and what started the job (EXECUTER_TRIGGER_*).</summary>
@@ -276,20 +302,36 @@ public static class ExternalScriptRunner
private static async Task<ExternalResult> RunProcessAsync(
string fileName,
string arguments,
IReadOnlyList<string> arguments,
IReadOnlyDictionary<string, string>? environment,
string? workingDirectory,
ProcessRun run,
Action<NormalizedOutputRecord> onRecord,
CancellationToken cancellationToken)
{
if (run.RunAs is { } user)
{
// The user reads (and may write) their job folder; nothing else of the agent's.
UserJobAccess.Grant(run.Folder.Path, user);
#if WINDOWS_AGENT
return await RunAsWindowsUserAsync(fileName, arguments, environment, run, user, onRecord, cancellationToken);
#else
// su (root needs no password) keeps this environment; the user's shell execs the
// interpreter, from their home unless Set Working Directory starts it in the job folder.
var command = run.SetWorkingDirectory ? "exec \"$0\" \"$@\"" : "cd 2>/dev/null; exec \"$0\" \"$@\"";
var su = new[] { "/bin/su", "/usr/bin/su" }.FirstOrDefault(File.Exists)
?? throw new InvalidOperationException("su is not available on this device.");
arguments = [user.Name, "-c", command, fileName, .. arguments];
fileName = su;
#endif
}
using var process = new Process
{
StartInfo = new ProcessStartInfo
{
FileName = fileName,
Arguments = arguments,
// Empty inherits the agent's current directory (unchanged default).
WorkingDirectory = workingDirectory ?? string.Empty,
WorkingDirectory = run.WorkingDirectory ?? string.Empty,
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardError = true,
@@ -297,6 +339,11 @@ public static class ExternalScriptRunner
StandardErrorEncoding = Encoding.UTF8,
},
};
foreach (var argument in arguments)
{
process.StartInfo.ArgumentList.Add(argument);
}
if (environment is not null)
{
foreach (var (key, value) in environment)
@@ -351,6 +398,73 @@ public static class ExternalScriptRunner
}
}
#if WINDOWS_AGENT
/// <summary>
/// The interpreter as the signed-in user: their token, environment (plus this run's variables and the
/// agent's bundled modules) and profile folder, headless (no window, hidden) in a kill-on-close job.
/// </summary>
private static async Task<ExternalResult> RunAsWindowsUserAsync(
string fileName,
IReadOnlyList<string> arguments,
IReadOnlyDictionary<string, string>? environment,
ProcessRun run,
Agent.Sessions.SignedInUser user,
Action<NormalizedOutputRecord> onRecord,
CancellationToken cancellationToken)
{
Agent.Screen.IScreenProcess process;
using (var token = Agent.Platform.WindowsUserToken.Open(user))
{
var block = token.EnvironmentBlock(environment, PowerShellRunspaceFactory.BundledModulesPath);
try
{
process = Agent.Screen.WindowsScreenProcessLauncher.Launch(
token.Handle, user.WindowsSession, fileName, arguments, block, run.WorkingDirectory ?? token.ProfileDirectory());
}
finally
{
System.Runtime.InteropServices.Marshal.FreeHGlobal(block);
}
}
await using (process)
{
// Nothing is typed in: end of input at once.
await process.Input.DisposeAsync();
var output = PumpLinesAsync(process.Output, line => onRecord(new NormalizedOutputRecord(OutputStreamKind.Output, line.TrimEnd())));
var error = PumpLinesAsync(process.Error, line => onRecord(new NormalizedOutputRecord(OutputStreamKind.Error, line)));
try
{
var exitCode = await process.Exited.WaitAsync(cancellationToken);
await Task.WhenAll(output, error);
return new ExternalResult(exitCode, WasCancelled: false);
}
catch (OperationCanceledException)
{
// Disposing closes the job, which takes the whole tree.
process.Kill();
return new ExternalResult(-1, WasCancelled: true);
}
}
}
private static async Task PumpLinesAsync(Stream stream, Action<string> onLine)
{
using var reader = new StreamReader(stream, Encoding.UTF8);
try
{
while (await reader.ReadLineAsync() is { } line)
{
onLine(line);
}
}
catch (Exception exception) when (exception is IOException or ObjectDisposedException)
{
// The process went away.
}
}
#endif
private static string? ResolveBash()
{
if (!OperatingSystem.IsWindows())
+148 -49
View File
@@ -29,7 +29,8 @@ public sealed class PowerShellJobHandler(
Agent.LocalRun.JobObservers? observers = null,
JobStartClock? clock = null,
Agent.Restart.RestartCoordinator? restarts = null,
Func<bool>? allowRestart = null)
Func<bool>? allowRestart = null,
Agent.Sessions.ISignedInUserResolver? signedInUsers = null)
{
/// <summary>Most output lines a job that may restart keeps for sending again after the restart.</summary>
public const int MaxKeptOutputLines = 20_000;
@@ -54,6 +55,10 @@ public sealed class PowerShellJobHandler(
ScriptFileFetcher.FetchResult? fetch = null;
var tapId = command.Trigger?.RequestId;
// Script groups: the built-ins come before the script's own functions; their lines become the job's reports.
var prelude = ScriptGroupBuiltIns.Compose(command.Engine, command.Prelude);
var groupReports = new ScriptGroupReportCollector();
// A job that may restart the device keeps its output, so what has not reached the
// server when it restarts can be sent again (bounded; see RestartCoordinator).
var kept = command.RestartAfterRun != RestartAfterRun.Off ? new List<JobOutputPayload>() : null;
@@ -199,12 +204,56 @@ public sealed class PowerShellJobHandler(
}
}
// Run As Signed-In User: whose account, decided before anything runs. Nobody (or nobody
// clear) fails the job rather than running it as the agent's account.
// Each Signed-In User: everyone signed in, one after another (nobody: nothing to run).
List<Agent.Sessions.SignedInUser>? runAsUsers = null;
string? runAsFailure = null;
if (command.RunAsUser)
{
var resolver = signedInUsers ?? Agent.Sessions.SignedInUsers.Default;
if (command.RunAsEachUser)
{
var all = resolver.Resolve();
if (all.SignedIn is null)
{
runAsFailure = $"Not run for each signed-in user: {all.Reason}";
}
else
{
runAsUsers = all.SignedIn
.Select(name => resolver.Resolve(name).User)
.OfType<Agent.Sessions.SignedInUser>()
.ToList();
}
}
else
{
var lookup = resolver.Resolve();
runAsUsers = lookup.User is { } one ? [one] : null;
runAsFailure = lookup.User is null ? $"Not run as the signed-in user: {lookup.Reason}" : null;
}
if (runAsUsers is not null)
{
logger.LogInformation("Job {JobId} runs as {Users}", jobId,
runAsUsers.Count == 0 ? "nobody (nobody is signed in)" : string.Join(", ", runAsUsers.Select(u => u.Name)));
}
}
if (folderFailure is not null)
{
finalState = JobState.Failed;
exitCode = 1;
message = folderFailure;
}
else if (runAsFailure is not null)
{
finalState = JobState.Failed;
exitCode = 1;
message = runAsFailure;
await Task.WhenAll(pending);
}
else if (deliveryFailure is not null)
{
finalState = JobState.Failed;
@@ -222,9 +271,19 @@ public sealed class PowerShellJobHandler(
: $"Execution exceeded the {timeout.TotalSeconds:F0}s timeout while downloading files.";
await Task.WhenAll(pending);
}
else if (command.Engine != ScriptEngine.PowerShell)
else if (runAsUsers is { Count: 0 })
{
// Out-of-process engine: Windows PowerShell 5.1 or Bash.
// Each Signed-In User with nobody signed in: nothing to do.
finalState = JobState.Succeeded;
exitCode = 0;
message = "Nobody is signed in; it ran for nobody.";
pending.Add(PublishOutputAsync(
new NormalizedOutputRecord(OutputStreamKind.Information, message), Interlocked.Increment(ref sequence)));
await Task.WhenAll(pending);
}
else if (command.Engine != ScriptEngine.PowerShell || runAsUsers is not null)
{
// Out-of-process engine: Windows PowerShell 5.1 or Bash, or any engine as the signed-in user.
if (!ExternalScriptRunner.IsAvailable(command.Engine))
{
finalState = JobState.Failed;
@@ -234,56 +293,90 @@ public sealed class PowerShellJobHandler(
else
{
var externalParameters = ExpandForExternal(boundParameters, expansions);
// An external engine reports no exception: its first stderr line stands in.
string? firstStderr = null;
var external = await ExternalScriptRunner.RunAsync(
command.Engine,
command.Content,
command.Prelude,
externalParameters,
command.Secrets,
string.IsNullOrWhiteSpace(command.SecretsVariableName) ? "Secrets" : command.SecretsVariableName,
record =>
// Once as the agent's account, or once per user (Each Signed-In User runs them in turn).
var accounts = runAsUsers is null
? new Agent.Sessions.SignedInUser?[] { null }
: runAsUsers.Select(u => (Agent.Sessions.SignedInUser?)u).ToArray();
var failedAs = new List<string>();
finalState = JobState.Succeeded;
exitCode = 0;
message = null;
foreach (var runAs in accounts)
{
if (command.RunAsEachUser && runAs is not null)
{
if (record.Stream == OutputStreamKind.Error && !string.IsNullOrWhiteSpace(record.Text))
pending.Add(PublishOutputAsync(
new NormalizedOutputRecord(OutputStreamKind.Information, $"── As {runAs.Name} ──"), Interlocked.Increment(ref sequence)));
}
// An external engine reports no exception: its first stderr line stands in.
string? firstStderr = null;
var external = await ExternalScriptRunner.RunAsync(
command.Engine,
command.Content,
prelude,
externalParameters,
command.Secrets,
string.IsNullOrWhiteSpace(command.SecretsVariableName) ? "Secrets" : command.SecretsVariableName,
record =>
{
Interlocked.CompareExchange(ref firstStderr, record.Text, null);
if (record.Stream == OutputStreamKind.Error && !string.IsNullOrWhiteSpace(record.Text))
{
Interlocked.CompareExchange(ref firstStderr, record.Text, null);
}
pending.Add(PublishOutputAsync(record, Interlocked.Increment(ref sequence)));
},
timeoutCts.Token,
files: filesDict,
filesRoot: fetch?.Root,
folder: folder,
scriptName: command.ScriptName,
setWorkingDirectory: command.SetWorkingDirectory,
trigger: command.Trigger,
runAs: runAs);
if (external.WasCancelled && cancellationToken.IsCancellationRequested)
{
finalState = JobState.Cancelled;
exitCode = -1;
message = "Execution cancelled.";
break;
}
if (external.WasCancelled)
{
// One timeout covers the whole job, every user's run included.
finalState = JobState.TimedOut;
exitCode = -1;
message = $"Execution exceeded the {timeout.TotalSeconds:F0}s timeout.";
break;
}
if (external.ExitCode != 0)
{
// The first failure's exit code and error stand for the job; later users still run.
if (finalState == JobState.Succeeded)
{
finalState = JobState.Failed;
exitCode = external.ExitCode;
message = $"Process exited with {external.ExitCode}.";
if (firstStderr is not null)
{
error = new ScriptErrorInfo(null, null, firstStderr.Length > ScriptErrorInfo.MaxTextLength
? firstStderr[..ScriptErrorInfo.MaxTextLength]
: firstStderr);
}
}
pending.Add(PublishOutputAsync(record, Interlocked.Increment(ref sequence)));
},
timeoutCts.Token,
files: filesDict,
filesRoot: fetch?.Root,
folder: folder,
scriptName: command.ScriptName,
setWorkingDirectory: command.SetWorkingDirectory,
trigger: command.Trigger);
if (external.WasCancelled && cancellationToken.IsCancellationRequested)
{
finalState = JobState.Cancelled;
exitCode = -1;
message = "Execution cancelled.";
}
else if (external.WasCancelled)
{
finalState = JobState.TimedOut;
exitCode = -1;
message = $"Execution exceeded the {timeout.TotalSeconds:F0}s timeout.";
}
else
{
finalState = external.ExitCode == 0 ? JobState.Succeeded : JobState.Failed;
exitCode = external.ExitCode;
message = external.ExitCode == 0 ? null : $"Process exited with {external.ExitCode}.";
if (external.ExitCode != 0 && firstStderr is not null)
{
error = new ScriptErrorInfo(null, null, firstStderr.Length > ScriptErrorInfo.MaxTextLength
? firstStderr[..ScriptErrorInfo.MaxTextLength]
: firstStderr);
failedAs.Add(runAs?.Name ?? string.Empty);
}
}
if (command.RunAsEachUser && failedAs.Count > 0 && finalState == JobState.Failed)
{
message = $"Failed as {failedAs.Count} of {accounts.Length} users ({string.Join(", ", failedAs)}); first exit code {exitCode}.";
}
}
await Task.WhenAll(pending);
@@ -298,7 +391,7 @@ public sealed class PowerShellJobHandler(
var result = await executionService.ExecuteAsync(
command.Content,
boundParameters,
command.Prelude,
prelude,
onRecord: record => pending.Add(PublishOutputAsync(record, Interlocked.Increment(ref sequence))),
onProgress: progress => pending.Add(PublishProgressAsync(progress)),
cancellationToken: timeoutCts.Token,
@@ -343,6 +436,10 @@ public sealed class PowerShellJobHandler(
var plan = Agent.Restart.RestartDecision.Decide(
command.Restart, finalState, exitCode, allowRestart?.Invoke() ?? true, unix);
if (plan is not null && Shared.Contracts.Models.PowerActions.Of(command.ScriptId) is not null)
{
plan = Agent.Restart.RestartDecision.FromConsole(plan);
}
if (plan is { State: JobRestartState.Requested } && restarts is null)
{
plan = plan with { State = JobRestartState.Failed, Message = "This agent cannot restart the device." };
@@ -447,6 +544,7 @@ public sealed class PowerShellJobHandler(
async Task PublishOutputAsync(NormalizedOutputRecord record, long seq)
{
record = groupReports.Take(record);
observers?.Output(tapId, record.Stream, record.Text);
var line = new JobOutputPayload(jobId, publisher.ClientId, seq, record.Stream, DateTimeOffset.UtcNow, record.Text);
if (kept is not null)
@@ -511,7 +609,8 @@ public sealed class PowerShellJobHandler(
ErrorType: error?.Type, ErrorId: error?.Id, ErrorMessage: error?.Message,
Restart: plan?.State,
RestartDelaySeconds: plan is null ? null : (int)plan.Delay.TotalSeconds,
RestartMessage: plan?.Message);
RestartMessage: plan?.Message,
GroupMemberships: state is JobState.Running ? null : groupReports.Reports);
async Task PublishFinalAsync(JobStatePayload payload)
{
@@ -29,6 +29,10 @@ public static class PowerShellRunspaceFactory
/// both resolve them. Idempotent; a no-op for dev builds where the staged
/// directory does not exist.
/// </summary>
/// <summary>The agent's bundled Modules directory, or null when it has none (development builds).</summary>
public static string? BundledModulesPath =>
Directory.Exists(Path.Combine(AppContext.BaseDirectory, "Modules")) ? Path.Combine(AppContext.BaseDirectory, "Modules") : null;
public static void EnsureBundledModulesOnPath()
{
if (modulesPathEnsured)
+165
View File
@@ -0,0 +1,165 @@
using System.Text.Json;
using Shared.Contracts.Messages;
using Shared.Contracts.Models;
namespace Agent.PowerShell;
/// <summary>
/// The built-ins every script gets for script groups (<see cref="ScriptGroups"/>), and the
/// collector that takes their lines out of a job's output for the job's final state. The
/// built-ins only write a line: no credentials are involved, the agent carries the result.
/// </summary>
public static class ScriptGroupBuiltIns
{
/// <summary>PowerShell (7 and 5.1): Set-, Add- and Remove-ExecuteRGroupMembership.</summary>
public const string PowerShell = """
function Set-ExecuteRGroupMembership {
<#
.SYNOPSIS
Puts this device in an ExecuteR script group, or takes it out, from a result.
.DESCRIPTION
The device is a member when the value is $true, a number above 0, a non-empty
collection (pipe a command's results in), or text other than false/0/no/off.
The group is created the first time a device joins it. Each run decides again.
.EXAMPLE
Get-Package -Name 'Java*' -ErrorAction SilentlyContinue | Set-ExecuteRGroupMembership 'Has Java'
.EXAMPLE
Set-ExecuteRGroupMembership -Name 'Low Disk' -Value ((Get-PSDrive C).Free -lt 10GB)
#>
[CmdletBinding()]
param(
[Parameter(Mandatory, Position = 0)][string] $Name,
[Parameter(Position = 1, ValueFromPipeline)] $Value
)
begin { $__items = [System.Collections.Generic.List[object]]::new() }
process { if ($MyInvocation.ExpectingInput) { $__items.Add($Value) } }
end {
if (-not $MyInvocation.ExpectingInput -and $PSBoundParameters.ContainsKey('Value')) {
if ($Value -is [System.Collections.IEnumerable] -and $Value -isnot [string]) { foreach ($__i in $Value) { $__items.Add($__i) } }
else { $__items.Add($Value) }
}
$__member = $false
if ($__items.Count -gt 1) { $__member = $true }
elseif ($__items.Count -eq 1) {
$__v = $__items[0]
if ($null -eq $__v) { $__member = $false }
elseif ($__v -is [bool]) { $__member = $__v }
elseif ($__v -is [byte] -or $__v -is [int16] -or $__v -is [int] -or $__v -is [long] -or $__v -is [double] -or $__v -is [decimal] -or $__v -is [single] -or $__v -is [uint32] -or $__v -is [uint64]) { $__member = $__v -gt 0 }
elseif ($__v -is [string]) { $__member = @('', 'false', '0', 'no', 'off') -notcontains $__v.Trim().ToLowerInvariant() }
else { $__member = $true }
}
Write-ExecuteRGroupMembership $Name $__member
}
}
function Add-ExecuteRGroupMembership {
<# .SYNOPSIS Puts this device in an ExecuteR script group (created if missing). #>
param([Parameter(Mandatory, Position = 0)][string] $Name)
Write-ExecuteRGroupMembership $Name $true
}
function Remove-ExecuteRGroupMembership {
<# .SYNOPSIS Takes this device out of an ExecuteR script group. #>
param([Parameter(Mandatory, Position = 0)][string] $Name)
Write-ExecuteRGroupMembership $Name $false
}
function Write-ExecuteRGroupMembership([string] $Name, [bool] $Member) {
$json = @{ group = $Name; member = $Member } | ConvertTo-Json -Compress
[Console]::Out.Flush()
Write-Host ('::executer-group::' + $json)
}
""";
/// <summary>Bash: executer_group NAME [VALUE] (VALUE: true/false, a number, or text; default true).</summary>
public const string Bash = """
executer_group() {
local name="$1" value="${2-true}" lower member=true
lower=$(printf '%s' "$value" | tr '[:upper:]' '[:lower:]' | tr -d '[:space:]')
case "$lower" in
''|false|0|no|off) member=false ;;
*) if printf '%s' "$lower" | grep -Eq '^-?[0-9]+$'; then [ "$lower" -gt 0 ] && member=true || member=false; fi ;;
esac
name=$(printf '%s' "$name" | sed 's/\\/\\\\/g; s/"/\\"/g')
printf '::executer-group::{"group":"%s","member":%s}\n' "$name" "$member"
}
""";
/// <summary>The prelude a job runs: the built-ins for its engine, then its own functions.</summary>
public static string Compose(ScriptEngine engine, string? prelude)
=> (engine == ScriptEngine.Bash ? Bash.Replace("\r\n", "\n") : PowerShell) + (prelude ?? string.Empty);
}
/// <summary>
/// Takes the built-ins' lines out of a job's output (any stream: in process they arrive as
/// information records, out of process as stdout) and keeps the last word per group.
/// </summary>
public sealed class ScriptGroupReportCollector
{
private readonly Lock gate = new();
private readonly List<GroupMembershipReport> reports = [];
/// <summary>What the job said, in order, the last per group (null when nothing).</summary>
public IReadOnlyList<GroupMembershipReport>? Reports
{
get
{
lock (gate)
{
return reports.Count == 0 ? null : [.. reports];
}
}
}
/// <summary>The record to publish: a report line becomes a readable one; anything else is unchanged.</summary>
public NormalizedOutputRecord Take(NormalizedOutputRecord record)
{
var text = record.Text?.TrimStart();
if (text is null || !text.StartsWith(ScriptGroups.Marker, StringComparison.Ordinal))
{
return record;
}
GroupMembershipReport? report = null;
try
{
using var json = JsonDocument.Parse(text[ScriptGroups.Marker.Length..]);
var root = json.RootElement;
if (root.TryGetProperty("group", out var group) && group.ValueKind == JsonValueKind.String
&& root.TryGetProperty("member", out var member) && member.ValueKind is JsonValueKind.True or JsonValueKind.False)
{
report = new GroupMembershipReport(group.GetString()!, member.GetBoolean());
}
}
catch (JsonException)
{
// Not ours after all: shown as written.
}
if (report is null)
{
return record;
}
if (ScriptGroups.Normalize(report.Group) is not { } name)
{
return new NormalizedOutputRecord(OutputStreamKind.Warning, $"Script group “{report.Group}” ignored: the name is empty, too long or has / or \\.");
}
lock (gate)
{
reports.RemoveAll(r => string.Equals(r.Group, name, StringComparison.OrdinalIgnoreCase));
if (reports.Count >= ScriptGroups.MaxReportsPerJob)
{
return new NormalizedOutputRecord(OutputStreamKind.Warning, $"Script group “{name}” ignored: a job reports on at most {ScriptGroups.MaxReportsPerJob} groups.");
}
reports.Add(report with { Group = name });
}
return new NormalizedOutputRecord(
OutputStreamKind.Information, report.Member ? $"Script group “{name}”: this device is a member." : $"Script group “{name}”: this device is not a member.");
}
}
+94
View File
@@ -0,0 +1,94 @@
using System.Diagnostics;
using System.Globalization;
using System.Runtime.InteropServices;
#if WINDOWS_AGENT
using System.Security.AccessControl;
using System.Security.Principal;
#endif
using Agent.Sessions;
namespace Agent.PowerShell;
/// <summary>
/// Run As Signed-In User: hands one job folder to the user its script runs as, and nothing more.
/// Windows adds the user (Modify) to the folder and everything in it (the files carry their own
/// locked-down ACLs). Linux/macOS give the folder to the user and let others traverse (not list)
/// the job root, whose other folders stay root's own 0700.
/// </summary>
public static class UserJobAccess
{
public static void Grant(string folder, SignedInUser user)
{
#if WINDOWS_AGENT
using var token = Agent.Platform.WindowsUserToken.Open(user);
var sid = token.Sid ?? throw new InvalidOperationException($"The SID of {user.Name} could not be read.");
GrantWindows(new DirectoryInfo(folder), sid);
#else
if (OperatingSystem.IsWindows())
{
return;
}
var (uid, gid) = Ids(user.Name);
var root = Path.GetDirectoryName(Path.TrimEndingDirectorySeparator(folder));
if (!string.IsNullOrEmpty(root))
{
var mode = File.GetUnixFileMode(root);
File.SetUnixFileMode(root, mode | UnixFileMode.GroupExecute | UnixFileMode.OtherExecute);
}
foreach (var path in Directory.EnumerateFileSystemEntries(folder, "*", SearchOption.AllDirectories).Prepend(folder))
{
if (lchown(path, uid, gid) != 0)
{
throw new InvalidOperationException($"{path} could not be given to {user.Name} (errno {Marshal.GetLastPInvokeError()}).");
}
}
#endif
}
#if WINDOWS_AGENT
private static void GrantWindows(DirectoryInfo folder, SecurityIdentifier sid)
{
var security = folder.GetAccessControl();
security.AddAccessRule(new FileSystemAccessRule(
sid, FileSystemRights.Modify | FileSystemRights.Synchronize,
InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Allow));
folder.SetAccessControl(security);
foreach (var file in folder.EnumerateFiles())
{
var fileSecurity = file.GetAccessControl();
fileSecurity.AddAccessRule(new FileSystemAccessRule(sid, FileSystemRights.Modify | FileSystemRights.Synchronize, AccessControlType.Allow));
file.SetAccessControl(fileSecurity);
}
foreach (var child in folder.EnumerateDirectories())
{
if ((child.Attributes & FileAttributes.ReparsePoint) == 0)
{
GrantWindows(child, sid);
}
}
}
#else
/// <summary>The user's uid and primary gid (<c>id -u</c>, <c>id -g</c>).</summary>
private static (uint Uid, uint Gid) Ids(string user)
=> (uint.Parse(Id("-u", user), NumberStyles.None, CultureInfo.InvariantCulture),
uint.Parse(Id("-g", user), NumberStyles.None, CultureInfo.InvariantCulture));
private static string Id(string flag, string user)
{
var start = new ProcessStartInfo("id") { RedirectStandardOutput = true, RedirectStandardError = true, UseShellExecute = false };
start.ArgumentList.Add(flag);
start.ArgumentList.Add(user);
using var process = Process.Start(start) ?? throw new InvalidOperationException("id could not be started.");
var output = process.StandardOutput.ReadToEnd().Trim();
process.WaitForExit(5000);
return process.ExitCode == 0 && output.Length > 0 ? output : throw new InvalidOperationException($"{user} is not a user on this device.");
}
[DllImport("libc", SetLastError = true)]
private static extern int lchown([MarshalAs(UnmanagedType.LPUTF8Str)] string path, uint owner, uint group);
#endif
}
+26 -11
View File
@@ -55,21 +55,36 @@ public sealed class LinuxSystemRestart(
public static DBusCall Reboot() => new(Login1Destination, Login1Path, Login1Interface, "Reboot", "b", [false]);
/// <summary>The reboot at <paramref name="whenUtc"/>, in microseconds of CLOCK_REALTIME as logind takes it.</summary>
public static DBusCall ScheduleReboot(DateTimeOffset whenUtc)
=> new(Login1Destination, Login1Path, Login1Interface, "ScheduleShutdown", "st",
["reboot", (ulong)whenUtc.ToUnixTimeMilliseconds() * 1000UL]);
public static DBusCall PowerOff() => new(Login1Destination, Login1Path, Login1Interface, "PowerOff", "b", [false]);
public static DBusCall StartRebootTarget()
=> new(SystemdDestination, SystemdPath, SystemdInterface, "StartUnit", "ss", ["reboot.target", "replace-irreversibly"]);
/// <summary>The reboot at <paramref name="whenUtc"/>, in microseconds of CLOCK_REALTIME as logind takes it.</summary>
public static DBusCall ScheduleReboot(DateTimeOffset whenUtc) => Schedule("reboot", whenUtc);
/// <summary>The power-off at <paramref name="whenUtc"/>, as <see cref="ScheduleReboot"/>.</summary>
public static DBusCall SchedulePowerOff(DateTimeOffset whenUtc) => Schedule("poweroff", whenUtc);
private static DBusCall Schedule(string kind, DateTimeOffset whenUtc)
=> new(Login1Destination, Login1Path, Login1Interface, "ScheduleShutdown", "st",
[kind, (ulong)whenUtc.ToUnixTimeMilliseconds() * 1000UL]);
public static DBusCall StartRebootTarget() => StartTarget("reboot.target");
public static DBusCall StartPowerOffTarget() => StartTarget("poweroff.target");
private static DBusCall StartTarget(string unit)
=> new(SystemdDestination, SystemdPath, SystemdInterface, "StartUnit", "ss", [unit, "replace-irreversibly"]);
/// <summary>What logind's wall message says while a scheduled reboot waits.</summary>
public static DBusCall SetWallMessage(string message)
=> new(Login1Destination, Login1Path, Login1Interface, "SetWallMessage", "sb", [message, true]);
public async Task<RestartResult> RestartAsync(TimeSpan delay, string message, CancellationToken cancellationToken)
/// <summary>Shutting down is the same with PowerOff, "poweroff" and poweroff.target. Updates: none to install here.</summary>
public async Task<RestartResult> PowerAsync(TimeSpan delay, string message, PowerOptions options, CancellationToken cancellationToken)
{
var call = delay > TimeSpan.Zero ? ScheduleReboot(clock.GetUtcNow() + delay) : Reboot();
var off = options.ShutsDown;
var call = delay > TimeSpan.Zero
? off ? SchedulePowerOff(clock.GetUtcNow() + delay) : ScheduleReboot(clock.GetUtcNow() + delay)
: off ? PowerOff() : Reboot();
var mechanism = $"login1.{call.Member}";
if (delay > TimeSpan.Zero)
{
@@ -103,16 +118,16 @@ public sealed class LinuxSystemRestart(
await wait(delay, cancellationToken);
}
const string fallback = "systemd1.StartUnit(reboot.target)";
var fallback = off ? "systemd1.StartUnit(poweroff.target)" : "systemd1.StartUnit(reboot.target)";
try
{
await bus.CallAsync(StartRebootTarget(), cancellationToken);
await bus.CallAsync(off ? StartPowerOffTarget() : StartRebootTarget(), cancellationToken);
return new RestartResult(RestartOutcome.Started, fallback);
}
catch (DBusCallException ex)
{
return new RestartResult(RestartOutcome.Failed, fallback,
$"Neither logind nor systemd took the restart ({ex.ErrorName ?? "no system bus"}: {ex.Message}).");
$"Neither logind nor systemd took the {(off ? "shutdown" : "restart")} ({ex.ErrorName ?? "no system bus"}: {ex.Message}).");
}
}
}
+24 -6
View File
@@ -21,11 +21,14 @@ public sealed record RestartTicket(
string? Continuation = null,
TimeSpan Warning = default)
{
/// <summary>A ticket from a plan's delay and warning (the same for a run and a sequence step).</summary>
/// <summary>Restart or shut down, with or without updates.</summary>
public PowerOptions Power { get; init; } = PowerOptions.Restart;
/// <summary>A ticket from a plan's delay, warning and power options (the same for a run and a sequence step).</summary>
public static RestartTicket For(
Guid jobId, string scriptName, RestartPlan plan, JobStatePayload finalState, IReadOnlyList<JobOutputPayload> output,
long outputLines, string? continuation = null)
=> new(jobId, scriptName, plan.Delay, finalState, output, outputLines, continuation, plan.Warning);
=> new(jobId, scriptName, plan.Delay, finalState, output, outputLines, continuation, plan.Warning) { Power = plan.Power };
}
/// <summary>
@@ -58,7 +61,16 @@ public sealed record PendingRestart(
bool Continued = false,
int WarningSeconds = 0,
DateTimeOffset? DueUtc = null,
int? GraceSeconds = null);
int? GraceSeconds = null,
// Shut down instead of restarting, pending Windows updates installed on the way, from the console;
// absent in records kept by older agents (a script's restart, no updates).
PowerAction Action = PowerAction.Restart,
bool InstallUpdates = false,
bool FromConsole = false)
{
[System.Text.Json.Serialization.JsonIgnore]
public PowerOptions Power => new(Action, InstallUpdates, FromConsole);
}
/// <summary>The server end of a restart: the request, and output lines it is missing.</summary>
public interface IRestartServer
@@ -194,7 +206,8 @@ public sealed class RestartCoordinator(
var restart = new PendingRestart(
ticket.JobId, ticket.ScriptName, (int)ticket.Delay.TotalSeconds, ticket.FinalState, ticket.Output,
ticket.OutputLines, clock.UtcNow, clock.BootUtc, Continuation: ticket.Continuation,
WarningSeconds: RestartOptions.ClampWarning((int)ticket.Warning.TotalSeconds));
WarningSeconds: RestartOptions.ClampWarning((int)ticket.Warning.TotalSeconds),
Action: ticket.Power.Action, InstallUpdates: ticket.Power.InstallUpdates, FromConsole: ticket.Power.FromConsole);
store.SavePendingRestart(restart);
var delay = TimeSpan.FromSeconds(restart.DelaySeconds);
@@ -434,7 +447,7 @@ public sealed class RestartCoordinator(
restart = restart with { InitiatedUtc = clock.UtcNow, GraceSeconds = (int)grace.TotalSeconds };
store.SavePendingRestart(restart);
var result = await system.RestartAsync(grace, MessageFor(restart), cancellationToken);
var result = await system.PowerAsync(grace, MessageFor(restart), restart.Power, cancellationToken);
restart = restart with { Mechanism = result.Mechanism };
if (!result.Accepted)
{
@@ -606,7 +619,12 @@ public sealed class RestartCoordinator(
/// <summary>What a signed-in user is told, where the platform tells them.</summary>
public static string MessageFor(PendingRestart restart)
=> $"{Branding.ProductName} restarts this device after “{restart.ScriptName}”.";
{
var does = restart.Action == PowerAction.ShutDown ? "shuts down" : "restarts";
return restart.FromConsole
? $"{Branding.ProductName} {does} this device."
: $"{Branding.ProductName} {does} this device after “{restart.ScriptName}”.";
}
/// <summary>Nobody can tell who is signed in: a job with a warning gives it.</summary>
private sealed class UnknownSignedInUsers : ISignedInUsers
+21 -3
View File
@@ -6,7 +6,11 @@ namespace Agent.Restart;
/// What a finished job's Restart After Run comes to: Requested or Refused, the delay the agent
/// holds, why, and the warning signed-in users get when it comes due (zero: none).
/// </summary>
public sealed record RestartPlan(JobRestartState State, TimeSpan Delay, string Message, TimeSpan Warning = default);
public sealed record RestartPlan(JobRestartState State, TimeSpan Delay, string Message, TimeSpan Warning = default)
{
/// <summary>Restart or shut down, with or without updates; from the console or a script.</summary>
public PowerOptions Power { get; init; } = PowerOptions.Restart;
}
/// <summary>Restart After Run's rules, applied to a job that has ended.</summary>
public static class RestartDecision
@@ -52,15 +56,29 @@ public static class RestartDecision
var held = settings.Clamped();
var delay = TimeSpan.FromSeconds(held.DelaySeconds);
var warning = TimeSpan.FromSeconds(held.WarningSeconds);
var power = new PowerOptions(settings.Action, settings.InstallUpdates);
if (!allowRestart)
{
return new RestartPlan(JobRestartState.Refused, delay, RefusedMessage, warning);
return new RestartPlan(
JobRestartState.Refused, delay, power.ShutsDown ? ShutDownRefusedMessage : RefusedMessage, warning) { Power = power };
}
return new RestartPlan(
JobRestartState.Requested,
delay,
settings.Mode == RestartAfterRun.Always ? "Restart After Run: Always." : $"The script asked for a restart (exit code {exitCode}).",
warning);
warning) { Power = power };
}
public const string ShutDownRefusedMessage = "Shut down refused: AllowRestart is off on this device.";
/// <summary>Restart or Shut Down from the console (a built-in power script): its own words, and its reason on Windows.</summary>
public static RestartPlan FromConsole(RestartPlan plan)
=> plan.State == JobRestartState.Requested
? plan with
{
Message = plan.Power.ShutsDown ? "Shut down from the console." : "Restart from the console.",
Power = plan.Power with { FromConsole = true },
}
: plan with { Power = plan.Power with { FromConsole = true } };
}
+29 -6
View File
@@ -25,7 +25,22 @@ public sealed record RestartResult(RestartOutcome Outcome, string Mechanism, str
}
/// <summary>
/// Restarts the machine cleanly through the platform's own API: never a shell, never
/// What the machine does: restart (the default) or shut down; on Windows, whether pending updates
/// install on the way (off: they wait, as a plain Restart in the Start menu leaves them);
/// <see cref="FromConsole"/>: Restart or Shut Down from the console, not a script's Restart After Run.
/// </summary>
public sealed record PowerOptions(
Shared.Contracts.Models.PowerAction Action = Shared.Contracts.Models.PowerAction.Restart,
bool InstallUpdates = false,
bool FromConsole = false)
{
public static readonly PowerOptions Restart = new();
public bool ShutsDown => Action == Shared.Contracts.Models.PowerAction.ShutDown;
}
/// <summary>
/// Restarts or shuts down the machine cleanly through the platform's own API: never a shell, never
/// <c>shutdown.exe</c>, <c>Restart-Computer</c> or <c>systemctl</c> (Windows PE, which has
/// no shutdown service of its own, is the one place a documented tool may run). Tests
/// replace it, so they never restart anything.
@@ -33,19 +48,27 @@ public sealed record RestartResult(RestartOutcome Outcome, string Mechanism, str
public interface ISystemRestart
{
/// <summary>
/// Asks for a restart in <paramref name="delay"/>: the system's own grace period, which is the
/// warning for signed-in users (zero: at once; the agent holds the delay before calling).
/// Asks for a restart or shutdown in <paramref name="delay"/>: the system's own grace period, which
/// is the warning for signed-in users (zero: at once; the agent holds the delay before calling).
/// <paramref name="message"/> is what a signed-in user is told where the platform tells them.
/// </summary>
Task<RestartResult> RestartAsync(TimeSpan delay, string message, CancellationToken cancellationToken);
Task<RestartResult> PowerAsync(TimeSpan delay, string message, PowerOptions options, CancellationToken cancellationToken);
}
public static class SystemRestartExtensions
{
/// <summary>A restart, installing no updates.</summary>
public static Task<RestartResult> RestartAsync(this ISystemRestart system, TimeSpan delay, string message, CancellationToken cancellationToken)
=> system.PowerAsync(delay, message, PowerOptions.Restart, cancellationToken);
}
/// <summary>A platform without a supported restart (macOS: no API a root launchd daemon may use for a clean one).</summary>
public sealed class UnsupportedSystemRestart(string platform) : ISystemRestart
{
public Task<RestartResult> RestartAsync(TimeSpan delay, string message, CancellationToken cancellationToken)
public Task<RestartResult> PowerAsync(TimeSpan delay, string message, PowerOptions options, CancellationToken cancellationToken)
=> Task.FromResult(new RestartResult(
RestartOutcome.Unsupported, "none", $"Restart After Run is not supported on {platform}."));
RestartOutcome.Unsupported, "none",
options.ShutsDown ? $"Shutting down is not supported on {platform}." : $"Restart After Run is not supported on {platform}."));
}
/// <summary>The restart mechanism of the running platform.</summary>
+40 -15
View File
@@ -12,17 +12,21 @@ public interface IWindowsShutdownApi
int InitiateShutdown(string message, uint gracePeriodSeconds, uint flags, uint reason);
/// <summary>
/// Windows PE only: <c>%SystemRoot%\System32\wpeutil.exe reboot</c>, started directly (no shell,
/// arguments as a list); its exit code and what it printed.
/// Windows PE only: <c>%SystemRoot%\System32\wpeutil.exe reboot</c> (or <c>shutdown</c>), started
/// directly (no shell, arguments as a list); its exit code and what it printed.
/// </summary>
(int ExitCode, string Output) RunWpeutilReboot();
(int ExitCode, string Output) RunWpeutil(string command);
}
/// <summary>
/// Windows: <c>InitiateShutdownW</c> with <c>SHUTDOWN_RESTART</c>, the grace it is given as its
/// Windows: <c>InitiateShutdownW</c> with <c>SHUTDOWN_RESTART</c> (shutting down:
/// <c>SHUTDOWN_POWEROFF</c>, a full shutdown, not Fast Startup's hybrid one), the grace it is given as its
/// grace period (the warning for signed-in users, or none: the agent holds the delay before it;
/// Windows shows a signed-in user its own "restarting" notice meanwhile) and a planned
/// "Application: Installation" reason, after SeShutdownPrivilege is enabled.
/// "Application: Installation" reason (from the console: a planned "Other: Maintenance"), after
/// SeShutdownPrivilege is enabled. Pending updates install only with <c>SHUTDOWN_INSTALL_UPDATES</c>,
/// which is passed only when asked for; without it they wait, as after a plain Restart. An update
/// Windows has already part-installed still finishes on any restart: that is servicing, not a choice.
/// <c>SHUTDOWN_FORCE_OTHERS</c> is needed because the agent is a service: every signed-in user
/// is "another" user, and without it the call fails with ERROR_SHUTDOWN_USERS_LOGGED_ON.
/// A restart already in progress or scheduled counts as taken. During the grace period
@@ -40,25 +44,39 @@ public sealed class WindowsSystemRestart(
{
public const uint ShutdownForceOthers = 0x00000001;
public const uint ShutdownRestart = 0x00000004;
public const uint ShutdownPowerOff = 0x00000008;
public const uint ShutdownInstallUpdates = 0x00000040;
public const uint ReasonMajorApplication = 0x00040000;
public const uint ReasonMajorOther = 0x00000000;
public const uint ReasonMinorMaintenance = 0x00000001;
public const uint ReasonMinorInstallation = 0x00000002;
public const uint ReasonFlagPlanned = 0x80000000;
public const uint Flags = ShutdownRestart | ShutdownForceOthers;
public const uint Reason = ReasonMajorApplication | ReasonMinorInstallation | ReasonFlagPlanned;
public const uint ConsoleReason = ReasonMajorOther | ReasonMinorMaintenance | ReasonFlagPlanned;
/// <summary>The InitiateShutdown flags for these options.</summary>
public static uint FlagsFor(PowerOptions options)
=> (options.ShutsDown ? ShutdownPowerOff : ShutdownRestart)
| ShutdownForceOthers
| (options.InstallUpdates ? ShutdownInstallUpdates : 0);
public static uint ReasonFor(PowerOptions options) => options.FromConsole ? ConsoleReason : Reason;
public const int ErrorShutdownInProgress = 1115;
public const int ErrorShutdownIsScheduled = 1190;
public const string InitiateShutdownMechanism = "InitiateShutdownW";
public const string WpeutilMechanism = "wpeutil reboot";
public const string WpeutilShutdownMechanism = "wpeutil shutdown";
/// <summary>Windows PE: how long past the delay the API gets before wpeutil follows.</summary>
public static readonly TimeSpan WinPeFallbackAfter = TimeSpan.FromMinutes(1);
private readonly Func<TimeSpan, CancellationToken, Task> wait = delay ?? Task.Delay;
public async Task<RestartResult> RestartAsync(TimeSpan delay, string message, CancellationToken cancellationToken)
public async Task<RestartResult> PowerAsync(TimeSpan delay, string message, PowerOptions options, CancellationToken cancellationToken)
{
var privilege = api.EnableShutdownPrivilege();
if (privilege != 0)
@@ -68,7 +86,7 @@ public sealed class WindowsSystemRestart(
}
var grace = (uint)Math.Clamp(delay.TotalSeconds, 0, Shared.Contracts.Models.RestartOptions.MaxDelaySeconds);
var error = api.InitiateShutdown(message, grace, Flags, Reason);
var error = api.InitiateShutdown(message, grace, FlagsFor(options), ReasonFor(options));
if (error is ErrorShutdownInProgress or ErrorShutdownIsScheduled)
{
return new RestartResult(RestartOutcome.AlreadyInProgress, InitiateShutdownMechanism,
@@ -86,21 +104,23 @@ public sealed class WindowsSystemRestart(
// Windows PE: the machine going down ends this wait (and the agent).
if (error == 0)
{
logger.LogInformation("Windows PE: InitiateShutdown took the restart; wpeutil follows if it has not happened {Seconds}s after the delay",
logger.LogInformation("Windows PE: InitiateShutdown took it; wpeutil follows if it has not happened {Seconds}s after the delay",
WinPeFallbackAfter.TotalSeconds);
await wait(TimeSpan.FromSeconds(grace) + WinPeFallbackAfter, cancellationToken);
}
else
{
logger.LogInformation("Windows PE: InitiateShutdown failed ({Error}); restarting with wpeutil after the delay", error);
logger.LogInformation("Windows PE: InitiateShutdown failed ({Error}); using wpeutil after the delay", error);
await wait(TimeSpan.FromSeconds(grace), cancellationToken);
}
var (exitCode, output) = api.RunWpeutilReboot();
logger.LogInformation("wpeutil reboot exited with {ExitCode}: {Output}", exitCode, output.Trim());
var command = options.ShutsDown ? "shutdown" : "reboot";
var mechanism = options.ShutsDown ? WpeutilShutdownMechanism : WpeutilMechanism;
var (exitCode, output) = api.RunWpeutil(command);
logger.LogInformation("wpeutil {Command} exited with {ExitCode}: {Output}", command, exitCode, output.Trim());
return exitCode == 0
? new RestartResult(RestartOutcome.Started, WpeutilMechanism)
: new RestartResult(RestartOutcome.Failed, WpeutilMechanism, $"wpeutil reboot exited with {exitCode}.");
? new RestartResult(RestartOutcome.Started, mechanism)
: new RestartResult(RestartOutcome.Failed, mechanism, $"{mechanism} exited with {exitCode}.");
}
}
@@ -162,8 +182,13 @@ internal sealed partial class Win32ShutdownApi(ILogger logger) : IWindowsShutdow
public int InitiateShutdown(string message, uint gracePeriodSeconds, uint flags, uint reason)
=> (int)InitiateShutdownW(null, message, gracePeriodSeconds, flags, reason);
public (int ExitCode, string Output) RunWpeutilReboot()
public (int ExitCode, string Output) RunWpeutil(string command)
{
if (command is not ("reboot" or "shutdown"))
{
throw new ArgumentOutOfRangeException(nameof(command), command, "Only reboot and shutdown.");
}
var path = Path.Combine(Environment.SystemDirectory, "wpeutil.exe");
var start = new System.Diagnostics.ProcessStartInfo(path)
{
@@ -172,7 +197,7 @@ internal sealed partial class Win32ShutdownApi(ILogger logger) : IWindowsShutdow
RedirectStandardOutput = true,
RedirectStandardError = true,
};
start.ArgumentList.Add("reboot");
start.ArgumentList.Add(command);
try
{
using var process = System.Diagnostics.Process.Start(start)
+67
View File
@@ -0,0 +1,67 @@
using Microsoft.Extensions.Logging;
using Shared.Contracts.Api;
using Shared.Infrastructure.Logging;
namespace Agent.Screen;
/// <summary>
/// The screen host's own log lines (its stderr, <c>@event</c> lines aside) into the agent's
/// log. The host writes ExecuteR's one format; its time, category and level prefix is taken
/// apart here and the rest (message and <c>key=value</c> fields) logged again at the host's
/// level under the host's category, so the agent's file shows each host line once, in the
/// same format, without a second timestamp. The host bounds its own repeats; a line that
/// is not in a known format is logged whole, as information.
/// </summary>
public static class ScreenHostLog
{
/// <summary>The category of the host's own lines (and of any line that names none).</summary>
public const string Category = "ScreenHost";
/// <summary>How much of one line is kept.</summary>
public const int MaxLineChars = 2000;
/// <summary>Logs one stderr line of the host.</summary>
/// <param name="loggers">Where a category's logger comes from; without one, everything goes to <paramref name="fallback"/>.</param>
public static void Relay(string line, ILoggerFactory? loggers, ILogger fallback)
{
if (line.Length > MaxLineChars)
{
line = line[..MaxLineChars];
}
var (category, level, message) = LogLineParser.TryParse(line, out var parsed)
? (CategoryOf(parsed.Category), ToLogLevel(parsed.Level), parsed.Message)
: (Category, LogLevel.Information, line);
var logger = loggers?.CreateLogger(category) ?? fallback;
logger.Log(level, "{HostLine}", message);
}
/// <summary>A short, safe category for a host line: <c>ScreenHost</c>, or the crate it names (<c>ironrdp_server</c>).</summary>
public static string CategoryOf(string? category)
{
if (string.IsNullOrWhiteSpace(category))
{
return Category;
}
// An older host writes the tracing target (executer_screen::video).
var crate = category.Split("::", 2)[0];
if (crate.StartsWith("executer_screen", StringComparison.Ordinal) || crate.Length > 64
|| !crate.All(c => char.IsAsciiLetterOrDigit(c) || c is '_' or '-' or '.'))
{
return Category;
}
return crate;
}
public static LogLevel ToLogLevel(string level) => level switch
{
LogLevels.Verbose => LogLevel.Trace,
LogLevels.Debug => LogLevel.Debug,
LogLevels.Warning => LogLevel.Warning,
LogLevels.Error => LogLevel.Error,
LogLevels.Fatal => LogLevel.Critical,
_ => LogLevel.Information,
};
}
+7 -2
View File
@@ -26,6 +26,9 @@ public sealed class ScreenSessions : IAsyncDisposable
private readonly Func<bool> enabled;
private readonly Func<string?> logLevel;
private readonly ILogger logger;
/// <summary>Loggers for the screen host's own lines, by its category (<see cref="ScreenHostLog"/>).</summary>
private readonly ILoggerFactory? hostLoggers;
private readonly ConcurrentDictionary<Guid, ScreenStream> streams = new();
private readonly ConcurrentDictionary<Guid, (string Consent, DateTimeOffset Expires)> granted = new();
private readonly ConcurrentDictionary<Guid, ScreenBannerEntry> viewing = new();
@@ -45,10 +48,12 @@ public sealed class ScreenSessions : IAsyncDisposable
Func<string?>? logLevel = null,
TimeSpan? heartbeat = null,
TimeSpan? idle = null,
Agent.Sessions.SessionWatcher? watcher = null)
Agent.Sessions.SessionWatcher? watcher = null,
ILoggerFactory? hostLoggers = null)
{
this.host = host;
this.watcher = watcher;
this.hostLoggers = hostLoggers;
this.enabled = enabled;
this.logger = logger;
this.logLevel = logLevel ?? (() => null);
@@ -192,7 +197,7 @@ public sealed class ScreenSessions : IAsyncDisposable
return new ScreenOpenReply(ScreenOpenStatuses.Failed, "The console session changed; try again.");
}
var stream = new ScreenStream(request.SessionId, request.StreamId, process, publish, logger, request.ViewOnly, heartbeat, idle, cipher: cipher);
var stream = new ScreenStream(request.SessionId, request.StreamId, process, publish, logger, request.ViewOnly, heartbeat, idle, cipher: cipher, hostLoggers: hostLoggers);
streams[request.StreamId] = stream;
stream.Start();
_ = ForgetWhenDoneAsync(stream);
+7 -3
View File
@@ -9,7 +9,8 @@ namespace Agent.Screen;
/// (waiting while a window is unacknowledged, so a slow browser stalls the host's
/// writes instead of growing memory here), the server's bytes go to stdin (and are
/// acknowledged only once written), <c>@event</c> lines on stderr become state
/// frames and every other stderr line goes to the agent log. Ends when the host
/// frames and every other stderr line goes to the agent log (see
/// <see cref="ScreenHostLog"/>). Ends when the host
/// exits, the server ends the stream or goes silent, or <see cref="Stop"/> is
/// called; then the host is closed (stdin EOF), killed if it lingers, and
/// disposed.
@@ -21,6 +22,7 @@ public sealed class ScreenStream
private readonly IScreenProcess process;
private readonly ScreenStreamPump pump;
private readonly ILogger logger;
private readonly ILoggerFactory? hostLoggers;
private readonly TaskCompletionSource<string> stopped = new(TaskCreationOptions.RunContinuationsAsynchronously);
private readonly TaskCompletionSource<ScreenHostEvent?> ready = new(TaskCreationOptions.RunContinuationsAsynchronously);
private readonly CancellationTokenSource cancel = new();
@@ -38,13 +40,15 @@ public sealed class ScreenStream
TimeSpan? heartbeat = null,
TimeSpan? idle = null,
int windowBytes = ScreenStreamDefaults.WindowBytes,
StreamCipher? cipher = null)
StreamCipher? cipher = null,
ILoggerFactory? hostLoggers = null)
{
SessionId = sessionId;
StreamId = streamId;
ViewOnly = viewOnly;
this.process = process;
this.logger = logger;
this.hostLoggers = hostLoggers;
pump = new ScreenStreamPump(
publish,
windowBytes,
@@ -195,7 +199,7 @@ public sealed class ScreenStream
}
else if (line.Length > 0)
{
logger.LogInformation("Screen host: {Line}", line.Length <= 2000 ? line : line[..2000]);
ScreenHostLog.Relay(line, hostLoggers, logger);
}
}
}
+39 -22
View File
@@ -26,23 +26,16 @@ internal sealed class WindowsScreenProcessLauncher(bool intoConsoleSession, bool
public IScreenProcess Start(string fileName, IReadOnlyList<string> arguments)
{
var stdin = new AnonymousPipeServerStream(PipeDirection.Out, HandleInheritability.Inheritable);
var stdout = new AnonymousPipeServerStream(PipeDirection.In, HandleInheritability.Inheritable);
var stderr = new AnonymousPipeServerStream(PipeDirection.In, HandleInheritability.Inheritable);
var token = IntPtr.Zero;
var job = IntPtr.Zero;
var attributeList = IntPtr.Zero;
var handleList = IntPtr.Zero;
var processInfo = default(PROCESS_INFORMATION);
try
{
uint? session = null;
int? session = null;
if (intoConsoleSession)
{
var console = WTSGetActiveConsoleSessionId();
if (console != InvalidSession)
{
session = console;
session = (int)console;
token = ConsoleToken(console);
}
else if (consoleRequired)
@@ -51,7 +44,36 @@ internal sealed class WindowsScreenProcessLauncher(bool intoConsoleSession, bool
}
}
// Only the three pipe ends cross into the host.
return Launch(token, session, fileName, arguments, IntPtr.Zero, Path.GetDirectoryName(fileName));
}
finally
{
if (token != IntPtr.Zero)
{
CloseHandle(token);
}
}
}
/// <summary>
/// Starts <paramref name="fileName"/> on the interactive desktop with redirected stdio, no window and
/// only its three pipe ends inherited, in a kill-on-close job. With a <paramref name="token"/> it runs
/// as that token (the caller keeps it); <paramref name="environment"/> is a Unicode block or zero for
/// the token's defaults; <paramref name="session"/> is what <see cref="IScreenProcess.SessionId"/> reports.
/// </summary>
internal static IScreenProcess Launch(
IntPtr token, int? session, string fileName, IReadOnlyList<string> arguments, IntPtr environment, string? folder)
{
var stdin = new AnonymousPipeServerStream(PipeDirection.Out, HandleInheritability.Inheritable);
var stdout = new AnonymousPipeServerStream(PipeDirection.In, HandleInheritability.Inheritable);
var stderr = new AnonymousPipeServerStream(PipeDirection.In, HandleInheritability.Inheritable);
var job = IntPtr.Zero;
var attributeList = IntPtr.Zero;
var handleList = IntPtr.Zero;
var processInfo = default(PROCESS_INFORMATION);
try
{
// Only the three pipe ends cross into the process.
var handles = new[]
{
stdin.ClientSafePipeHandle.DangerousGetHandle(),
@@ -69,7 +91,7 @@ internal sealed class WindowsScreenProcessLauncher(bool intoConsoleSession, bool
attributeList, 0, PROC_THREAD_ATTRIBUTE_HANDLE_LIST, handleList,
IntPtr.Size * handles.Length, IntPtr.Zero, IntPtr.Zero))
{
throw new Win32Exception(Marshal.GetLastWin32Error(), "The screen host's handle list could not be set.");
throw new Win32Exception(Marshal.GetLastWin32Error(), "The process's handle list could not be set.");
}
var startup = new STARTUPINFOEX { lpAttributeList = attributeList };
@@ -82,14 +104,14 @@ internal sealed class WindowsScreenProcessLauncher(bool intoConsoleSession, bool
startup.StartupInfo.hStdError = handles[2];
var commandLine = new StringBuilder(CommandLine(fileName, arguments));
var flags = EXTENDED_STARTUPINFO_PRESENT | CREATE_NO_WINDOW | CREATE_SUSPENDED;
var folder = Path.GetDirectoryName(fileName);
var flags = EXTENDED_STARTUPINFO_PRESENT | CREATE_NO_WINDOW | CREATE_SUSPENDED
| (environment != IntPtr.Zero ? CREATE_UNICODE_ENVIRONMENT : 0);
var started = token != IntPtr.Zero
? CreateProcessAsUserW(token, fileName, commandLine, IntPtr.Zero, IntPtr.Zero, true, flags, IntPtr.Zero, folder, ref startup, out processInfo)
: CreateProcess(fileName, commandLine, IntPtr.Zero, IntPtr.Zero, true, flags, IntPtr.Zero, folder, ref startup, out processInfo);
? CreateProcessAsUserW(token, fileName, commandLine, IntPtr.Zero, IntPtr.Zero, true, flags, environment, folder, ref startup, out processInfo)
: CreateProcess(fileName, commandLine, IntPtr.Zero, IntPtr.Zero, true, flags, environment, folder, ref startup, out processInfo);
if (!started)
{
throw new Win32Exception(Marshal.GetLastWin32Error(), "The screen host did not start.");
throw new Win32Exception(Marshal.GetLastWin32Error(), $"{Path.GetFileName(fileName)} did not start.");
}
job = KillOnCloseJob();
@@ -108,7 +130,7 @@ internal sealed class WindowsScreenProcessLauncher(bool intoConsoleSession, bool
stdout.DisposeLocalCopyOfClientHandle();
stderr.DisposeLocalCopyOfClientHandle();
var process = new WindowsScreenProcess(processInfo.hProcess, job, stdin, stdout, stderr, session is { } id ? (int)id : null);
var process = new WindowsScreenProcess(processInfo.hProcess, job, stdin, stdout, stderr, session);
processInfo.hProcess = IntPtr.Zero;
job = IntPtr.Zero;
return process;
@@ -138,11 +160,6 @@ internal sealed class WindowsScreenProcessLauncher(bool intoConsoleSession, bool
}
finally
{
if (token != IntPtr.Zero)
{
CloseHandle(token);
}
if (attributeList != IntPtr.Zero)
{
DeleteProcThreadAttributeList(attributeList);
+1 -1
View File
@@ -50,7 +50,7 @@ public static class AgentHost
// LOG_DIRECTORY moved the agent's).
var liveLog = new LiveLog();
builder.Logging.ClearProviders();
builder.Services.AddSerilog(LoggingSetup.CreateLogger(logSettings, "agent", liveLog), dispose: true);
builder.Services.AddSerilog(LoggingSetup.CreateLogger(logSettings, "Agent", liveLog), dispose: true);
builder.Services.AddSingleton(new Logs.AgentLogs(
liveLog, logSettings.Directory, Path.Combine(Upgrade.UpgradeFolders.Installed.InstallDirectory, "Logs")));
+2 -1
View File
@@ -175,7 +175,8 @@ public sealed class AgentSession : IAgentSession
() => configuration.AllowRemoteView.Value,
() => Agent.Screen.ScreenHost.PolicyOf(configuration),
screenLogger,
watcher: sessions);
watcher: sessions,
hostLoggers: loggerFactory);
// The Being Viewed banner (RemoteViewBanner, off by default; read at service start like the rest).
Agent.Screen.ScreenBanner? banner = null;
+19 -14
View File
@@ -237,24 +237,29 @@ public static class ServiceLifecycle
return 0;
}
public static int Status()
/// <summary>
/// The registration and state <c>status</c> reports: NotInstalled when the SCM has no
/// such service; the start type (Automatic, Manual, Disabled) is null when unreadable.
/// </summary>
public static (bool Installed, string State, string? StartType) Query()
{
string state;
var installed = Exists();
if (installed)
if (!Exists())
{
using var controller = new ServiceController(Branding.AgentServiceName);
state = controller.Status.ToString();
}
else
{
state = "NotInstalled";
return (false, "NotInstalled", null);
}
// 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;
using var controller = new ServiceController(Branding.AgentServiceName);
string? startType;
try
{
startType = controller.StartType.ToString();
}
catch (InvalidOperationException)
{
startType = null;
}
return (true, controller.Status.ToString(), startType);
}
private static bool Exists()
+52
View File
@@ -99,11 +99,63 @@ public static class UnixServiceLifecycle
? Run("launchctl", $"kill SIGTERM system/{LaunchdLabel}", ignoreErrors: true)
: Run("systemctl", $"stop {SystemdUnit}", ignoreErrors: true);
/// <summary>The service manager's own description, after the JSON line <c>status</c> prints.</summary>
public static int Status()
=> OperatingSystem.IsMacOS()
? Run("launchctl", $"print system/{LaunchdLabel}", ignoreErrors: true)
: Run("systemctl", $"status {SystemdUnit} --no-pager", ignoreErrors: true);
/// <summary>
/// The registration and state <c>status</c> reports: the unit file / plist present,
/// and systemd's ActiveState (active, inactive, failed, activating) or launchd's
/// "running" / "not running" / "not loaded".
/// </summary>
public static (bool Installed, string State, string? StartType) Query()
{
if (OperatingSystem.IsMacOS())
{
var plist = $"/Library/LaunchDaemons/{LaunchdLabel}.plist";
var (code, output) = Capture("launchctl", $"print system/{LaunchdLabel}");
var state = code != 0 ? "not loaded" : output.Contains("state = running", StringComparison.Ordinal) ? "running" : "not running";
return (File.Exists(plist), state, null);
}
var unit = $"/etc/systemd/system/{SystemdUnit}.service";
var active = Capture("systemctl", $"is-active {SystemdUnit}").Output.Trim();
var enabled = Capture("systemctl", $"is-enabled {SystemdUnit}").Output.Trim();
return (File.Exists(unit), active.Length == 0 ? "unknown" : active, enabled.Length == 0 ? null : enabled);
}
private static (int ExitCode, string Output) Capture(string fileName, string arguments)
{
try
{
using var process = Process.Start(new ProcessStartInfo
{
FileName = fileName,
Arguments = arguments,
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardError = true,
});
if (process is null)
{
return (-1, string.Empty);
}
var errors = process.StandardError.ReadToEndAsync();
var output = process.StandardOutput.ReadToEnd();
process.WaitForExit();
_ = errors.Result;
return (process.ExitCode, output);
}
catch (System.ComponentModel.Win32Exception)
{
// No systemctl / launchctl here (a container): nothing registered.
return (-1, string.Empty);
}
}
private static int InstallSystemd()
{
var unit = $"/etc/systemd/system/{SystemdUnit}.service";
+179
View File
@@ -0,0 +1,179 @@
using System.Diagnostics;
namespace Agent.Sessions;
/// <summary>
/// The account a shell or script runs as for Run As Signed-In User: its name (DOMAIN\user on
/// Windows) and, on Windows, the session whose token it uses.
/// </summary>
public sealed record SignedInUser(string Name, int? WindowsSession = null);
/// <summary>
/// Who to run as, or why nobody can be picked; <see cref="SignedIn"/> names everyone signed in
/// (sorted; null when the sessions could not be read), so the operator can choose one.
/// </summary>
public sealed record SignedInUserLookup(SignedInUser? User, string? Reason, IReadOnlyList<string>? SignedIn = null)
{
public static SignedInUserLookup Nobody(string reason, IReadOnlyList<string>? signedIn = null) => new(null, reason, signedIn);
public static SignedInUserLookup Of(SignedInUser user, IReadOnlyList<string>? signedIn = null) => new(user, null, signedIn ?? [user.Name]);
}
/// <summary>Finds the user to run as on this device.</summary>
public interface ISignedInUserResolver
{
/// <summary>
/// <paramref name="requested"/>: that signed-in user (by name, any case), refused when they are
/// not signed in; null: the usual rule (see <see cref="SignedInUsers.Pick"/>).
/// </summary>
SignedInUserLookup Resolve(string? requested = null);
}
/// <summary>
/// The rule every platform shares: the console's user when someone is at the console;
/// otherwise the only signed-in user. Several users and nobody at the console is ambiguous
/// (a terminal server), so nothing is picked rather than the wrong person.
/// </summary>
public static class SignedInUsers
{
public const string NobodyReason = "Nobody is signed in on the device.";
/// <summary>The resolver for this platform.</summary>
public static ISignedInUserResolver Default { get; } =
#if WINDOWS_AGENT
new WindowsSignedInUserResolver(new WindowsSessionQuery());
#else
OperatingSystem.IsMacOS() ? new MacSignedInUserResolver() : new LinuxSignedInUserResolver();
#endif
/// <summary>
/// Picks from <paramref name="sessions"/> (each with its user). <paramref name="requested"/>
/// names one: their console session when they have it, else their first; nobody when they
/// are not signed in (never an account that merely exists). Otherwise the console's user,
/// else the only user signed in.
/// </summary>
public static SignedInUserLookup Pick<TSession>(
IReadOnlyList<TSession> sessions, Func<TSession, string?> user, Func<TSession, bool> atConsole, Func<TSession, SignedInUser> toUser,
string? requested = null)
{
var signedIn = sessions.Where(s => !string.IsNullOrWhiteSpace(user(s))).ToList();
var names = signedIn.Select(s => user(s)!).Distinct(StringComparer.OrdinalIgnoreCase).Order(StringComparer.OrdinalIgnoreCase).ToList();
if (!string.IsNullOrWhiteSpace(requested))
{
// The exact name first (unix names are case-sensitive), else any case (Windows').
var theirs = signedIn.Where(s => string.Equals(user(s), requested.Trim(), StringComparison.Ordinal)).ToList();
if (theirs.Count == 0)
{
theirs = signedIn.Where(s => string.Equals(user(s), requested.Trim(), StringComparison.OrdinalIgnoreCase)).ToList();
}
return theirs.Count == 0
? SignedInUserLookup.Nobody($"{requested.Trim()} is not signed in on the device.", names)
: SignedInUserLookup.Of(toUser(theirs.FirstOrDefault(atConsole) ?? theirs[0]), names);
}
if (signedIn.FirstOrDefault(atConsole) is { } console)
{
return SignedInUserLookup.Of(toUser(console), names);
}
return names.Count switch
{
0 => SignedInUserLookup.Nobody(NobodyReason, names),
1 => SignedInUserLookup.Of(toUser(signedIn[0]), names),
_ => SignedInUserLookup.Nobody(
$"Several users are signed in ({string.Join(", ", names)}) and nobody is at the console; choose one under Run As.", names),
};
}
}
#if WINDOWS_AGENT
/// <summary>Terminal Services sessions: the active console session's user, else the only signed-in user.</summary>
public sealed class WindowsSignedInUserResolver(ISessionQuery query) : ISignedInUserResolver
{
public SignedInUserLookup Resolve(string? requested = null)
{
var console = query.ActiveConsoleSession();
var sessions = query.Enumerate();
if (sessions is null)
{
return SignedInUserLookup.Nobody("The device's sessions could not be read.");
}
return SignedInUsers.Pick(
sessions, s => s.User, s => s.SessionId == console, s => new SignedInUser(s.User!, s.SessionId), requested);
}
}
#endif
/// <summary>logind's user sessions: a local one's user (the seat's), else the only signed-in user.</summary>
public sealed class LinuxSignedInUserResolver(Func<IReadOnlyList<LogonEvent>?>? sessions = null) : ISignedInUserResolver
{
private readonly Func<IReadOnlyList<LogonEvent>?> current = sessions
?? (() => new LinuxLogonSource(Microsoft.Extensions.Logging.Abstractions.NullLogger.Instance).Current());
public SignedInUserLookup Resolve(string? requested = null)
{
var list = current();
if (list is null)
{
return SignedInUserLookup.Nobody("The device's sessions could not be read (loginctl is unavailable).");
}
// Local sessions stand in for the console: with one local user that is the one. root's own
// sessions are never "the user" (it is the agent's account already).
var users = list.Where(l => !string.IsNullOrWhiteSpace(l.User) && l.User != "root").ToList();
var local = users.Where(l => l.Detail == "local").Select(l => l.User!).Distinct(StringComparer.Ordinal).ToList();
return SignedInUsers.Pick(
users,
l => l.User,
l => local.Count == 1 && l.User == local[0],
l => new SignedInUser(l.User!),
requested);
}
}
/// <summary>The owner of /dev/console (the user at the login window is root: nobody).</summary>
public sealed class MacSignedInUserResolver(Func<string?>? consoleOwner = null) : ISignedInUserResolver
{
private readonly Func<string?> owner = consoleOwner ?? ReadConsoleOwner;
public SignedInUserLookup Resolve(string? requested = null)
{
var name = owner()?.Trim();
if (string.IsNullOrEmpty(name) || name is "root" or "_mbsetupuser")
{
return SignedInUserLookup.Nobody(
string.IsNullOrWhiteSpace(requested) ? SignedInUsers.NobodyReason : $"{requested.Trim()} is not signed in on the device.", []);
}
// Only the console's user counts on macOS (fast user switching's others have no shell to lend).
return string.IsNullOrWhiteSpace(requested) || string.Equals(requested.Trim(), name, StringComparison.Ordinal)
? SignedInUserLookup.Of(new SignedInUser(name))
: SignedInUserLookup.Nobody($"{requested.Trim()} is not the user at the device's console.", [name]);
}
private static string? ReadConsoleOwner()
{
try
{
var start = new ProcessStartInfo("/usr/bin/stat") { RedirectStandardOutput = true, RedirectStandardError = true, UseShellExecute = false };
start.ArgumentList.Add("-f");
start.ArgumentList.Add("%Su");
start.ArgumentList.Add("/dev/console");
using var process = Process.Start(start);
if (process is null)
{
return null;
}
var output = process.StandardOutput.ReadToEnd();
return process.WaitForExit(5000) && process.ExitCode == 0 ? output : null;
}
catch (Exception exception) when (exception is System.ComponentModel.Win32Exception or InvalidOperationException or IOException)
{
return null;
}
}
}
+35 -1
View File
@@ -5,11 +5,19 @@ using static Agent.Shell.ConPtyInterop;
namespace Agent.Shell;
/// <summary>
/// Who a ConPTY shell runs as when not the agent's own account: a primary token (the caller
/// keeps it until <see cref="ConPtySession.Start"/> returns), its environment block and the
/// folder to start in.
/// </summary>
internal sealed record PtyUser(IntPtr Token, IntPtr Environment, string? Directory);
/// <summary>
/// A live ConPTY-backed shell process. Terminal output is delivered via
/// <see cref="OutputReceived"/>; input is written with <see cref="WriteAsync"/>.
/// With a <see cref="PtyUser"/> it starts as that user, on their desktop.
/// </summary>
public sealed class ConPtySession : IPtySession
internal sealed class ConPtySession(PtyUser? user = null) : IPtySession
{
private IntPtr pseudoConsole = IntPtr.Zero;
private IntPtr attributeList = IntPtr.Zero;
@@ -90,6 +98,32 @@ public sealed class ConPtySession : IPtySession
throw new InvalidOperationException("UpdateProcThreadAttribute failed.");
}
if (user is not null)
{
// On the user's desktop, so a window the shell opens shows there; the shell itself is
// headless (the pseudoconsole has no window) and starts hidden, so nothing flashes.
startupInfo.StartupInfo.lpDesktop = @"winsta0\default";
startupInfo.StartupInfo.dwFlags = Agent.Screen.WindowsScreenInterop.STARTF_USESHOWWINDOW;
startupInfo.StartupInfo.wShowWindow = 0;
if (!Agent.Screen.WindowsScreenInterop.CreateProcessAsUserW(
user.Token,
null,
new System.Text.StringBuilder(commandLine),
IntPtr.Zero,
IntPtr.Zero,
false,
EXTENDED_STARTUPINFO_PRESENT | Agent.Screen.WindowsScreenInterop.CREATE_UNICODE_ENVIRONMENT,
user.Environment,
user.Directory,
ref startupInfo,
out processInfo))
{
throw new InvalidOperationException($"CreateProcessAsUser failed (Win32 {Marshal.GetLastWin32Error()}).");
}
return;
}
if (!CreateProcessW(
lpApplicationName: null,
lpCommandLine: commandLine,
+113 -8
View File
@@ -1,4 +1,5 @@
using Agent.Messaging;
using Agent.Sessions;
using Microsoft.Extensions.Logging;
using Shared.Contracts.Messages;
using Shared.Contracts.Models;
@@ -13,8 +14,9 @@ namespace Agent.Shell;
/// one closes the previous. Output is published as base64 over Core NATS with
/// a monotonic sequence.
/// </summary>
public sealed class ShellManager(AgentPublisher publisher, ILogger logger) : IDisposable
public sealed class ShellManager(AgentPublisher publisher, ILogger logger, ISignedInUserResolver? users = null) : IDisposable
{
private readonly ISignedInUserResolver signedIn = users ?? SignedInUsers.Default;
private readonly Lock gate = new();
private ActiveShell? current;
@@ -45,7 +47,42 @@ public sealed class ShellManager(AgentPublisher publisher, ILogger logger) : IDi
return;
}
var pty = CreatePty();
// As the signed-in user: their token (Windows) or su -l (linux/macOS), never the agent's account.
string? asUser = null;
IDisposable? userResources = null;
IPtySession pty;
// Who is signed in travels with the state, so the console can offer each of them.
IReadOnlyList<string>? signedInUsers;
if (command.AsUser)
{
var lookup = signedIn.Resolve(command.User);
signedInUsers = lookup.SignedIn;
if (lookup.User is not { } user)
{
var reason = $"Not opened as the signed-in user: {lookup.Reason}";
logger.LogWarning("Shell session {SessionId} not opened: {Reason}", sessionId, reason);
PublishState(sessionId, ShellSessionState.Failed, reason, signedInUsers: signedInUsers);
return;
}
try
{
(pty, launch, userResources) = CreateUserPty(user, launch);
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
logger.LogWarning("Shell session {SessionId} not opened as {User}: {Reason}", sessionId, user.Name, ex.Message);
PublishState(sessionId, ShellSessionState.Failed, $"Not opened as {user.Name}: {ex.Message}", signedInUsers: signedInUsers);
return;
}
asUser = user.Name;
}
else
{
pty = CreatePty();
signedInUsers = SignedInNames();
}
var active = new ActiveShell
{
@@ -65,10 +102,19 @@ public sealed class ShellManager(AgentPublisher publisher, ILogger logger) : IDi
try
{
pty.Start(launch.FileName, launch.Args, Math.Max(command.Cols, 1), Math.Max(command.Rows, 1));
PublishState(sessionId, ShellSessionState.Open, null, launch.Kind);
logger.LogInformation("Shell session {SessionId} opened: {Kind} ({Shell}, requested {Requested})",
sessionId, launch.Kind ?? "login shell", launch.FileName, command.Shell ?? ShellKinds.Auto);
try
{
pty.Start(launch.FileName, launch.Args, Math.Max(command.Cols, 1), Math.Max(command.Rows, 1));
}
finally
{
// The token and environment block are only needed to start the process.
userResources?.Dispose();
}
PublishState(sessionId, ShellSessionState.Open, null, launch.Kind, asUser, signedInUsers);
logger.LogInformation("Shell session {SessionId} opened: {Kind} ({Shell}, requested {Requested}) as {User}",
sessionId, launch.Kind ?? "login shell", launch.FileName, command.Shell ?? ShellKinds.Auto, asUser ?? "the agent's account");
}
catch (Exception ex)
{
@@ -78,6 +124,50 @@ public sealed class ShellManager(AgentPublisher publisher, ILogger logger) : IDi
}
}
#if WINDOWS_AGENT
/// <summary>A ConPTY started with the user's token, environment and profile folder (the resources go once it has started).</summary>
private static (IPtySession Pty, ShellLaunch Launch, IDisposable Resources) CreateUserPty(SignedInUser user, ShellLaunch launch)
{
var token = Agent.Platform.WindowsUserToken.Open(user);
try
{
var environment = token.EnvironmentBlock(null);
var resources = new UserPtyResources(token, environment);
return (new ConPtySession(new PtyUser(token.Handle, environment, token.ProfileDirectory())), launch, resources);
}
catch
{
token.Dispose();
throw;
}
}
private sealed class UserPtyResources(Agent.Platform.WindowsUserToken token, IntPtr environment) : IDisposable
{
public void Dispose()
{
System.Runtime.InteropServices.Marshal.FreeHGlobal(environment);
token.Dispose();
}
}
#else
/// <summary>The user's login shell through su (root needs no password); the requested shell does not apply.</summary>
private static (IPtySession Pty, ShellLaunch Launch, IDisposable Resources) CreateUserPty(SignedInUser user, ShellLaunch launch)
{
_ = launch;
var su = new[] { "/bin/su", "/usr/bin/su" }.FirstOrDefault(File.Exists)
?? throw new InvalidOperationException("su is not available on this device.");
return (new UnixPtySession(), new ShellLaunch(null, su, ["-l", user.Name]), new NoResources());
}
private sealed class NoResources : IDisposable
{
public void Dispose()
{
}
}
#endif
public async Task WriteAsync(ShellInputPayload input, CancellationToken cancellationToken)
{
ActiveShell? active;
@@ -170,12 +260,27 @@ public sealed class ShellManager(AgentPublisher publisher, ILogger logger) : IDi
payload);
}
private void PublishState(Guid sessionId, ShellSessionState state, string? message, string? shell = null)
private void PublishState(
Guid sessionId, ShellSessionState state, string? message, string? shell = null, string? user = null, IReadOnlyList<string>? signedInUsers = null)
{
_ = publisher.PublishAsync(
NatsSubjects.AgentShellState(publisher.ClientId, sessionId),
MessageTypes.ShellState,
new ShellStatePayload(sessionId, state, message, shell));
new ShellStatePayload(sessionId, state, message, shell, user, signedInUsers));
}
/// <summary>Who is signed in (for the console's Run As list); null when it cannot be read.</summary>
private IReadOnlyList<string>? SignedInNames()
{
try
{
return signedIn.Resolve().SignedIn;
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
logger.LogDebug("Signed-in users could not be listed: {Message}", ex.Message);
return null;
}
}
private static void DisposeShell(ActiveShell? active, string reason)
+5 -3
View File
@@ -16,6 +16,7 @@ public static class Permissions
public const string DevicesManage = "devices.manage";
public const string DevicesRemove = "devices.remove";
public const string DevicesLogs = "devices.logs";
public const string DevicesPower = "devices.power";
public const string GroupsView = "groups.view";
public const string GroupsManage = "groups.manage";
public const string ScriptsView = "scripts.view";
@@ -50,6 +51,7 @@ public static class Permissions
new(DevicesManage, "Manage devices", "Refresh inventory and edit device tags."),
new(DevicesRemove, "Remove devices", "Remove devices from the system and uninstall their agents."),
new(DevicesLogs, "View device logs", "Follow an agent's live log and download its log files, without file browsing."),
new(DevicesPower, "Restart and shut down", "Restart or shut down devices and groups' members."),
]),
new("Groups",
[
@@ -114,13 +116,13 @@ public static class Permissions
[
DevicesView, DevicesManage, GroupsView, GroupsManage, ScriptsView, ScriptsManage,
FunctionsView, FunctionsManage, JobsView, JobsRun, AutomationView, AutomationManage,
SecretsUse, ShellUse, FilesSend, FilesBrowse, FilesManage, DevicesLogs, ScreenView, ScreenControl, RegistryView, RegistryEdit,
SecretsUse, ShellUse, FilesSend, FilesBrowse, FilesManage, DevicesLogs, DevicesPower, ScreenView, ScreenControl, RegistryView, RegistryEdit,
];
public static readonly IReadOnlyList<string> HelpDeskSet =
[
DevicesView, GroupsView, ScriptsView, FunctionsView, JobsView, JobsRun, AutomationView,
SecretsUse, ShellUse, FilesSend, FilesBrowse, DevicesLogs, ScreenView, ScreenControl, RegistryView,
SecretsUse, ShellUse, FilesSend, FilesBrowse, DevicesLogs, DevicesPower, ScreenView, ScreenControl, RegistryView,
];
public static readonly IReadOnlyList<string> ScriptAuthorSet =
@@ -143,7 +145,7 @@ public static class Permissions
return permissions.Any(p =>
p.EndsWith(".manage", StringComparison.Ordinal)
|| p is JobsRun or ShellUse or FilesSend or FilesManage or ScreenControl or RegistryEdit)
|| p is JobsRun or DevicesPower or ShellUse or FilesSend or FilesManage or ScreenControl or RegistryEdit)
? UserRole.Operator
: UserRole.Viewer;
}
+20
View File
@@ -45,6 +45,9 @@ public class AppDbContext(DbContextOptions<AppDbContext> options) : DbContext(op
public DbSet<SequenceRunEntity> SequenceRuns => Set<SequenceRunEntity>();
public DbSet<SequenceDeviceRunEntity> SequenceDeviceRuns => Set<SequenceDeviceRunEntity>();
// Snippets: the shared library of code to insert (built-ins come from code).
public DbSet<SnippetEntity> Snippets => Set<SnippetEntity>();
/// <summary>
/// SQLite cannot ORDER BY / compare DateTimeOffset natively, so it stores
/// timestamps as UTC ticks. Postgres and SQL Server use native timestamp
@@ -540,5 +543,22 @@ public class AppDbContext(DbContextOptions<AppDbContext> options) : DbContext(op
// The sweep deletes what can no longer be replayed.
entity.HasIndex(e => e.ForgetUtc);
});
ConfigureSnippets(modelBuilder);
}
private static void ConfigureSnippets(ModelBuilder modelBuilder)
{
modelBuilder.Entity<SnippetEntity>(entity =>
{
entity.ToTable("Snippets");
entity.HasKey(e => e.Id);
entity.Property(e => e.Name).HasMaxLength(200);
entity.Property(e => e.Description).HasMaxLength(1000);
entity.Property(e => e.Language).HasConversion<string>().HasMaxLength(32);
entity.Property(e => e.CreatedBy).HasMaxLength(256);
entity.Property(e => e.UpdatedBy).HasMaxLength(256);
entity.HasIndex(e => e.Name);
});
}
}
+15
View File
@@ -649,6 +649,21 @@ public sealed class ScriptEntity : IFolderItem
/// <see cref="RestartOptions.MaxWarningSeconds"/>).
/// </summary>
public int RestartWarningSeconds { get; set; }
/// <summary>Run as the device's signed-in user (out of process) instead of the agent's account.</summary>
public bool RunAsUser { get; set; }
/// <summary>With <see cref="RunAsUser"/>: once for each signed-in user, one after another.</summary>
public bool RunAsEachUser { get; set; }
/// <summary>
/// What Restart After Run does: only the built-in power scripts (<see cref="PowerActions"/>,
/// never stored) shut down, so it is not a column; a run's snapshot carries it.
/// </summary>
[System.ComponentModel.DataAnnotations.Schema.NotMapped]
public PowerAction RestartAction { get; set; }
/// <summary>Windows: the built-in power scripts' restart or shutdown installs pending updates. Not a column either.</summary>
[System.ComponentModel.DataAnnotations.Schema.NotMapped]
public bool RestartInstallsUpdates { get; set; }
public DateTimeOffset CreatedUtc { get; set; }
public DateTimeOffset UpdatedUtc { get; set; }
public string? CreatedBy { get; set; }
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,29 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Backend.Data.Migrations.Postgres
{
/// <inheritdoc />
public partial class ScriptRunAsUser : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<bool>(
name: "RunAsUser",
table: "Scripts",
type: "boolean",
nullable: false,
defaultValue: false);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "RunAsUser",
table: "Scripts");
}
}
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,29 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Backend.Data.Migrations.Postgres
{
/// <inheritdoc />
public partial class ScriptRunAsEachUser : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<bool>(
name: "RunAsEachUser",
table: "Scripts",
type: "boolean",
nullable: false,
defaultValue: false);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "RunAsEachUser",
table: "Scripts");
}
}
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,46 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Backend.Data.Migrations.Postgres
{
/// <inheritdoc />
public partial class Snippets : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Snippets",
columns: table => new
{
Id = table.Column<Guid>(type: "uuid", nullable: false),
Name = table.Column<string>(type: "character varying(200)", maxLength: 200, nullable: false),
Description = table.Column<string>(type: "character varying(1000)", maxLength: 1000, nullable: true),
Language = table.Column<string>(type: "character varying(32)", maxLength: 32, nullable: false),
Content = table.Column<string>(type: "text", nullable: false),
CreatedUtc = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false),
CreatedBy = table.Column<string>(type: "character varying(256)", maxLength: 256, nullable: true),
UpdatedUtc = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false),
UpdatedBy = table.Column<string>(type: "character varying(256)", maxLength: 256, nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Snippets", x => x.Id);
});
migrationBuilder.CreateIndex(
name: "IX_Snippets_Name",
table: "Snippets",
column: "Name");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "Snippets");
}
}
}
@@ -1122,6 +1122,12 @@ namespace Backend.Data.Migrations.Postgres
b.Property<int>("RestartWarningSeconds")
.HasColumnType("integer");
b.Property<bool>("RunAsEachUser")
.HasColumnType("boolean");
b.Property<bool>("RunAsUser")
.HasColumnType("boolean");
b.Property<bool>("RunFromFile")
.HasColumnType("boolean");
@@ -1636,6 +1642,51 @@ namespace Backend.Data.Migrations.Postgres
b.ToTable("SignInThrottles", (string)null);
});
modelBuilder.Entity("Backend.Data.SnippetEntity", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<string>("Content")
.IsRequired()
.HasColumnType("text");
b.Property<string>("CreatedBy")
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.Property<DateTimeOffset>("CreatedUtc")
.HasColumnType("timestamp with time zone");
b.Property<string>("Description")
.HasMaxLength(1000)
.HasColumnType("character varying(1000)");
b.Property<string>("Language")
.IsRequired()
.HasMaxLength(32)
.HasColumnType("character varying(32)");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(200)
.HasColumnType("character varying(200)");
b.Property<string>("UpdatedBy")
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.Property<DateTimeOffset>("UpdatedUtc")
.HasColumnType("timestamp with time zone");
b.HasKey("Id");
b.HasIndex("Name");
b.ToTable("Snippets", (string)null);
});
modelBuilder.Entity("Backend.Data.StepUpEntity", b =>
{
b.Property<string>("SessionId")
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,29 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Backend.Data.Migrations.SqlServer
{
/// <inheritdoc />
public partial class ScriptRunAsUser : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<bool>(
name: "RunAsUser",
table: "Scripts",
type: "bit",
nullable: false,
defaultValue: false);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "RunAsUser",
table: "Scripts");
}
}
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,29 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Backend.Data.Migrations.SqlServer
{
/// <inheritdoc />
public partial class ScriptRunAsEachUser : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<bool>(
name: "RunAsEachUser",
table: "Scripts",
type: "bit",
nullable: false,
defaultValue: false);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "RunAsEachUser",
table: "Scripts");
}
}
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,46 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Backend.Data.Migrations.SqlServer
{
/// <inheritdoc />
public partial class Snippets : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Snippets",
columns: table => new
{
Id = table.Column<Guid>(type: "uniqueidentifier", nullable: false),
Name = table.Column<string>(type: "nvarchar(200)", maxLength: 200, nullable: false),
Description = table.Column<string>(type: "nvarchar(1000)", maxLength: 1000, nullable: true),
Language = table.Column<string>(type: "nvarchar(32)", maxLength: 32, nullable: false),
Content = table.Column<string>(type: "nvarchar(max)", nullable: false),
CreatedUtc = table.Column<DateTimeOffset>(type: "datetimeoffset", nullable: false),
CreatedBy = table.Column<string>(type: "nvarchar(256)", maxLength: 256, nullable: true),
UpdatedUtc = table.Column<DateTimeOffset>(type: "datetimeoffset", nullable: false),
UpdatedBy = table.Column<string>(type: "nvarchar(256)", maxLength: 256, nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Snippets", x => x.Id);
});
migrationBuilder.CreateIndex(
name: "IX_Snippets_Name",
table: "Snippets",
column: "Name");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "Snippets");
}
}
}
@@ -1122,6 +1122,12 @@ namespace Backend.Data.Migrations.SqlServer
b.Property<int>("RestartWarningSeconds")
.HasColumnType("int");
b.Property<bool>("RunAsEachUser")
.HasColumnType("bit");
b.Property<bool>("RunAsUser")
.HasColumnType("bit");
b.Property<bool>("RunFromFile")
.HasColumnType("bit");
@@ -1636,6 +1642,51 @@ namespace Backend.Data.Migrations.SqlServer
b.ToTable("SignInThrottles", (string)null);
});
modelBuilder.Entity("Backend.Data.SnippetEntity", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<string>("Content")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("CreatedBy")
.HasMaxLength(256)
.HasColumnType("nvarchar(256)");
b.Property<DateTimeOffset>("CreatedUtc")
.HasColumnType("datetimeoffset");
b.Property<string>("Description")
.HasMaxLength(1000)
.HasColumnType("nvarchar(1000)");
b.Property<string>("Language")
.IsRequired()
.HasMaxLength(32)
.HasColumnType("nvarchar(32)");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(200)
.HasColumnType("nvarchar(200)");
b.Property<string>("UpdatedBy")
.HasMaxLength(256)
.HasColumnType("nvarchar(256)");
b.Property<DateTimeOffset>("UpdatedUtc")
.HasColumnType("datetimeoffset");
b.HasKey("Id");
b.HasIndex("Name");
b.ToTable("Snippets", (string)null);
});
modelBuilder.Entity("Backend.Data.StepUpEntity", b =>
{
b.Property<string>("SessionId")
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,29 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Backend.Data.Migrations.Sqlite
{
/// <inheritdoc />
public partial class ScriptRunAsUser : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<bool>(
name: "RunAsUser",
table: "Scripts",
type: "INTEGER",
nullable: false,
defaultValue: false);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "RunAsUser",
table: "Scripts");
}
}
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,29 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Backend.Data.Migrations.Sqlite
{
/// <inheritdoc />
public partial class ScriptRunAsEachUser : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<bool>(
name: "RunAsEachUser",
table: "Scripts",
type: "INTEGER",
nullable: false,
defaultValue: false);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "RunAsEachUser",
table: "Scripts");
}
}
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,46 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Backend.Data.Migrations.Sqlite
{
/// <inheritdoc />
public partial class Snippets : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Snippets",
columns: table => new
{
Id = table.Column<Guid>(type: "TEXT", nullable: false),
Name = table.Column<string>(type: "TEXT", maxLength: 200, nullable: false),
Description = table.Column<string>(type: "TEXT", maxLength: 1000, nullable: true),
Language = table.Column<string>(type: "TEXT", maxLength: 32, nullable: false),
Content = table.Column<string>(type: "TEXT", nullable: false),
CreatedUtc = table.Column<long>(type: "INTEGER", nullable: false),
CreatedBy = table.Column<string>(type: "TEXT", maxLength: 256, nullable: true),
UpdatedUtc = table.Column<long>(type: "INTEGER", nullable: false),
UpdatedBy = table.Column<string>(type: "TEXT", maxLength: 256, nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Snippets", x => x.Id);
});
migrationBuilder.CreateIndex(
name: "IX_Snippets_Name",
table: "Snippets",
column: "Name");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "Snippets");
}
}
}
@@ -1111,6 +1111,12 @@ namespace Backend.Data.Migrations.Sqlite
b.Property<int>("RestartWarningSeconds")
.HasColumnType("INTEGER");
b.Property<bool>("RunAsEachUser")
.HasColumnType("INTEGER");
b.Property<bool>("RunAsUser")
.HasColumnType("INTEGER");
b.Property<bool>("RunFromFile")
.HasColumnType("INTEGER");
@@ -1623,6 +1629,51 @@ namespace Backend.Data.Migrations.Sqlite
b.ToTable("SignInThrottles", (string)null);
});
modelBuilder.Entity("Backend.Data.SnippetEntity", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("TEXT");
b.Property<string>("Content")
.IsRequired()
.HasColumnType("TEXT");
b.Property<string>("CreatedBy")
.HasMaxLength(256)
.HasColumnType("TEXT");
b.Property<long>("CreatedUtc")
.HasColumnType("INTEGER");
b.Property<string>("Description")
.HasMaxLength(1000)
.HasColumnType("TEXT");
b.Property<string>("Language")
.IsRequired()
.HasMaxLength(32)
.HasColumnType("TEXT");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(200)
.HasColumnType("TEXT");
b.Property<string>("UpdatedBy")
.HasMaxLength(256)
.HasColumnType("TEXT");
b.Property<long>("UpdatedUtc")
.HasColumnType("INTEGER");
b.HasKey("Id");
b.HasIndex("Name");
b.ToTable("Snippets", (string)null);
});
modelBuilder.Entity("Backend.Data.StepUpEntity", b =>
{
b.Property<string>("SessionId")
+22
View File
@@ -0,0 +1,22 @@
using Shared.Contracts.Models;
namespace Backend.Data;
/// <summary>
/// A snippet of the shared library: code operators insert into the script and function editors and
/// type into a remote shell. The content marks tab stops as <c>${1:default}</c> (see Backend.Snippets).
/// Built-in snippets are not stored; they come from <c>Backend.Snippets.BuiltInSnippets</c>.
/// </summary>
public sealed class SnippetEntity
{
public Guid Id { get; set; }
public required string Name { get; set; }
public string? Description { get; set; }
/// <summary>The engine the snippet is written for: it is offered in editors of that language.</summary>
public ScriptEngine Language { get; set; }
public required string Content { get; set; }
public DateTimeOffset CreatedUtc { get; set; }
public string? CreatedBy { get; set; }
public DateTimeOffset UpdatedUtc { get; set; }
public string? UpdatedBy { get; set; }
}
+90 -108
View File
@@ -12,7 +12,8 @@ namespace Backend.Enrollment;
///
/// 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).
/// AGENT_PACKAGE_PATH (default /data/agent). Every script is safe to run again:
/// it installs, upgrades, repairs or leaves the agent alone (<see cref="InstallScripts"/>).
/// </summary>
public static class InstallEndpoints
{
@@ -50,8 +51,9 @@ public static class InstallEndpoints
: Results.Text(pem, "application/x-pem-file; charset=utf-8");
}
private static IResult GetInstallScript(
HttpContext context, IConfiguration configuration, Backend.Tls.TlsSettings tls, string? token, string? type)
private static async Task<IResult> GetInstallScript(
HttpContext context, IConfiguration configuration, Backend.Tls.TlsSettings tls, Files.AgentPackageService packages,
Upgrades.AgentCatalogService catalog, string? token, string? type, CancellationToken cancellationToken)
{
if (string.IsNullOrWhiteSpace(token))
{
@@ -78,14 +80,24 @@ public static class InstallEndpoints
// scripts also work in Windows PE: there the MSI script switches to the
// portable package (Windows Installer does not run in WinPE).
// The package links carry the token: without public downloads, a live token is what lets them through.
// Each script compares the installed agent with the version the package link
// serves, so a rerun on a current, healthy device changes nothing.
var catalogued = (await catalog.NewestByTypeAsync(cancellationToken))
.ToDictionary(p => p.Key, p => p.Value.Version, StringComparer.OrdinalIgnoreCase);
string? Version(string packageType) => ServedVersion(packageType, catalogued, packages);
var tokenQuery = "token=" + Uri.EscapeDataString(token!);
var zipUrl = $"{baseUrl}{ApiRoutes.AgentPackage}?type=zip&{tokenQuery}";
var script = type?.ToLowerInvariant() switch
{
"linux" => BuildUnixScript(baseUrl, token!, "linux", tokenQuery, skipDownloadVerify, fingerprint),
"osx" or "mac" or "macos" or "darwin" => BuildUnixScript(baseUrl, token!, "osx", tokenQuery, skipDownloadVerify, fingerprint),
"zip" => BuildZipScript(baseUrl, token!, zipUrl, skipDownloadVerify, fingerprint),
_ => BuildMsiScript(baseUrl, token!, $"{baseUrl}{ApiRoutes.AgentPackage}?type=msi&{tokenQuery}", zipUrl, skipDownloadVerify, fingerprint),
"linux" => BuildUnixScript(baseUrl, token!, "linux", tokenQuery, skipDownloadVerify, fingerprint,
Version(AgentPackageTypes.LinuxX64), Version(AgentPackageTypes.LinuxArm64)),
"osx" or "mac" or "macos" or "darwin" => BuildUnixScript(baseUrl, token!, "osx", tokenQuery, skipDownloadVerify, fingerprint,
Version(AgentPackageTypes.MacX64), Version(AgentPackageTypes.MacArm64)),
"zip" => BuildWindowsScript(baseUrl, token!, msiUrl: null, zipUrl, msiVersion: null, Version(AgentPackageTypes.WindowsZip),
skipDownloadVerify, fingerprint),
_ => BuildWindowsScript(baseUrl, token!, $"{baseUrl}{ApiRoutes.AgentPackage}?type=msi&{tokenQuery}", zipUrl,
Version(AgentPackageTypes.Msi), Version(AgentPackageTypes.WindowsZip), skipDownloadVerify, fingerprint),
};
return Results.Text(script, "text/plain; charset=utf-8");
@@ -191,129 +203,99 @@ public static class InstallEndpoints
// an elevated PowerShell — the Add device modal states this prerequisite.
// Windows PE (the MiniNT key) has no Windows Installer, so there the MSI
// script takes the portable path instead — same service, same enrollment.
private static string BuildMsiScript(
string baseUrl, string token, string packageUrl, string zipUrl, bool skipDownloadVerify, string? fingerprint) => $$"""
// The body (InstallScripts) looks before it acts: install, upgrade, repair or
// nothing, and the token only where the enrollment needs it.
internal static string BuildWindowsScript(
string baseUrl, string token, string? msiUrl, string zipUrl, string? msiVersion, string? zipVersion,
bool skipDownloadVerify, string? fingerprint) => $$"""
$ErrorActionPreference = 'Stop'
{{PsDownloadTls}}
{{(skipDownloadVerify ? PsAcceptCert : "")}}
$server = '{{baseUrl}}'
$token = '{{token}}'
$server = {{PsQuote(baseUrl)}}
$token = {{PsQuote(token)}}
$msiUrl = {{PsQuote(msiUrl ?? "")}}
$zipUrl = {{PsQuote(zipUrl)}}
$msiVersion = {{PsQuote(msiVersion ?? "")}}
$zipVersion = {{PsQuote(zipVersion ?? "")}}
$portableOnly = {{(msiUrl is null ? "$true" : "$false")}}
{{PsDownload(fingerprint)}}
if (Test-Path '{{PsWinPeKey}}') {
Write-Host 'Windows PE detected: installing ExecuteR Agent (portable)...'
{{PortableInstall(zipUrl)}}
}
else {
Write-Host 'Installing ExecuteR Agent...'
$msi = Join-Path $env:TEMP ('ExecuteRAgent-' + [guid]::NewGuid().ToString('N') + '.msi')
try {
Save-ExecuteRFile '{{packageUrl}}' $msi
$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 const string PsWinPeKey = @"HKLM:\SYSTEM\CurrentControlSet\Control\MiniNT";
/// <summary>
/// The portable install body (expects <c>$server</c>/<c>$token</c>): unpack
/// the zip under Program Files (X:\ in Windows PE), seed enrollment, then
/// register and start the Windows service through the agent's own
/// <c>initialize</c> (Service Control Manager APIs, never sc.exe). Unzips
/// with System.IO.Compression rather than Expand-Archive, which a minimal
/// PowerShell (Windows PE) may lack; a re-run stops the running agent first
/// so its files can be replaced. ExtractToDirectory creates missing
/// parent folders.
/// </summary>
private static string PortableInstall(string packageUrl) => $$"""
$dest = Join-Path $env:ProgramFiles 'ExecuteR\Agent'
$exe = Join-Path $dest 'ExecuteR-Agent.exe'
$zip = Join-Path $env:TEMP ('ExecuteRAgent-' + [guid]::NewGuid().ToString('N') + '.zip')
$unpacked = $zip + '.d'
try {
Save-ExecuteRFile '{{packageUrl}}' $zip
Add-Type -AssemblyName System.IO.Compression.FileSystem
if (Test-Path $dest) {
[System.IO.Compression.ZipFile]::ExtractToDirectory($zip, $unpacked)
if (Test-Path $exe) { try { & $exe stop | Out-Null } catch { } }
Copy-Item -Path (Join-Path $unpacked '*') -Destination $dest -Recurse -Force
}
else {
# First install: unpack in place (Windows PE's RAM drive is small).
[System.IO.Compression.ZipFile]::ExtractToDirectory($zip, $dest)
}
# Windows PE: nobody signs in, so the Being Viewed banner has no place there.
if (Test-Path '{{PsWinPeKey}}') {
Remove-Item (Join-Path $dest '{{Shared.Infrastructure.Constants.Branding.BannerExecutableName}}') -Force -ErrorAction SilentlyContinue
}
# 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
if ($LASTEXITCODE -ne 0) { throw "ExecuteR-Agent initialize exited with $LASTEXITCODE" }
Write-Host 'ExecuteR Agent installed and starting.'
}
finally {
Remove-Item $zip -ErrorAction SilentlyContinue
Remove-Item $unpacked -Recurse -Force -ErrorAction SilentlyContinue
}
{{InstallScripts.WindowsFunctions}}
{{InstallScripts.WindowsMain}}
""";
/// <summary>
/// linux/macOS installer: detects the architecture, downloads the matching
/// agent zip, unpacks to /opt/executer/agent, configures enrollment via
/// the agent's own CLI and registers the systemd unit / launchd daemon.
/// linux/macOS installer: detects the architecture, then installs, upgrades or
/// repairs the agent from the matching zip under /opt/executer/agent, configures
/// enrollment through the agent's own CLI and registers the systemd unit /
/// launchd daemon through its initialize (InstallScripts has the rules).
/// </summary>
// ReplaceLineEndings("\n"): the .cs source is checked out with CRLF on
// Windows, but a bash script with CRLF fails hard when piped to bash
// (`set -euo pipefail\r` -> ": invalid option namepefail"). Force LF.
private static string BuildUnixScript(string baseUrl, string token, string os, string tokenQuery, bool skipDownloadVerify, string? fingerprint) => ($$"""
// Everything runs from main() on the last line: bash reads a piped script as
// it goes, so a cut-off download runs nothing.
internal static string BuildUnixScript(
string baseUrl, string token, string os, string tokenQuery, bool skipDownloadVerify, string? fingerprint,
string? x64Version, string? arm64Version) => ($$"""
#!/usr/bin/env bash
set -euo pipefail
if [ "$(id -u)" -ne 0 ]; then echo 'Run with sudo/root.' >&2; exit 1; fi
server='{{baseUrl}}'
token='{{token}}'
if [ "$(id -u)" -ne 0 ]; then echo 'Failed: run with sudo/root.' >&2; exit 1; fi
server={{ShQuote(baseUrl)}}
token={{ShQuote(token)}}
os='{{os}}'
case "$(uname -m)" in
x86_64|amd64) arch=x64 ;;
aarch64|arm64) arch=arm64 ;;
*) echo "Unsupported architecture: $(uname -m)" >&2; exit 1 ;;
*) echo "Failed: unsupported architecture $(uname -m)" >&2; exit 1 ;;
esac
pkg="{{baseUrl}}{{ApiRoutes.AgentPackage}}?type={{os}}-${arch}&{{tokenQuery}}"
case "$arch" in
x64) target={{ShQuote(x64Version ?? "")}} ;;
*) target={{ShQuote(arm64Version ?? "")}} ;;
esac
dest=/opt/executer/agent
tmp=$(mktemp -d)
trap 'rm -rf "$tmp"' EXIT
lock=/var/run/executer-install.lock
reported=0
locked=0
tmp=$(mktemp -d "${TMPDIR:-/tmp}/executer-install.XXXXXX")
cleanup() {
local rc=$?
rm -rf "$tmp"
if [ "$locked" = 1 ]; then rm -rf "$lock"; fi
if [ "$rc" -ne 0 ] && [ "$reported" = 0 ]; then echo "Failed: the setup stopped unexpectedly (exit $rc)."; fi
}
trap cleanup EXIT
{{ShDownload(fingerprint, skipDownloadVerify)}}
echo "Installing ExecuteR Agent ({{os}}-${arch})..."
download "$pkg" "$tmp/agent.zip"
mkdir -p "$dest"
if command -v unzip >/dev/null 2>&1; then
unzip -oq "$tmp/agent.zip" -d "$dest"
else
python3 -m zipfile -e "$tmp/agent.zip" "$dest"
fi
chmod +x "$dest/executer-agent"
"$dest/executer-agent" configure --url "$server" --token "$token"
"$dest/executer-agent" initialize
echo 'ExecuteR Agent installed. It will enroll and start automatically.'
{{InstallScripts.UnixFunctions}}
main
""").ReplaceLineEndings("\n");
private static string BuildZipScript(string baseUrl, string token, string packageUrl, bool skipDownloadVerify, string? fingerprint) => $$"""
$ErrorActionPreference = 'Stop'
Write-Host 'Installing ExecuteR Agent (portable)...'
{{PsDownloadTls}}
{{(skipDownloadVerify ? PsAcceptCert : "")}}
$server = '{{baseUrl}}'
$token = '{{token}}'
{{PsDownload(fingerprint)}}
{{PortableInstall(packageUrl)}}
""";
/// <summary>A PowerShell single-quoted literal.</summary>
internal static string PsQuote(string value) => "'" + value.Replace("'", "''") + "'";
/// <summary>A bash single-quoted literal.</summary>
internal static string ShQuote(string value) => "'" + value.Replace("'", "'\\''") + "'";
/// <summary>
/// The version the package link serves for a type (as <see cref="ServePackageAsync"/>
/// picks: the catalog's newest unless this node holds a newer one), or null when
/// unknown. Only a version the comparison understands goes into a script.
/// </summary>
internal static string? ServedVersion(string packageType, IReadOnlyDictionary<string, string> catalogued, Files.AgentPackageService packages)
{
var path = packages.ResolveLocalPath(packageType);
var local = path is null ? null : Files.AgentPackageService.ReadVersionMarker(Path.GetDirectoryName(path));
var version = catalogued.TryGetValue(packageType, out var newest) && (path is null || !AgentVersions.IsNewer(local, newest))
? newest
: local;
return ScriptSafeVersion(version);
}
internal static string? ScriptSafeVersion(string? version)
=> version is not null && AgentVersions.IsValid(version)
&& version.Trim().All(c => char.IsAsciiLetterOrDigit(c) || c is '.' or '+' or '-')
? version.Trim()
: null;
/// <summary>
/// The CA fingerprint a bootstrap token carries ("secret.fp", 64 hex
File diff suppressed because it is too large Load Diff
+4 -4
View File
@@ -145,7 +145,7 @@ public sealed class DeviceGroupService(AppDbContext db, InventoryReportCache inv
var known = devices.Select(d => d.ClientId).ToHashSet(StringComparer.Ordinal);
var direct = groups.ToDictionary(g => g.Id, _ => new HashSet<string>(StringComparer.Ordinal));
var staticIds = groups.Where(g => g.Kind == GroupKind.Static).Select(g => g.Id).ToHashSet();
var staticIds = groups.Where(g => ScriptGroups.HasMemberRows(g.Kind)).Select(g => g.Id).ToHashSet();
foreach (var row in staticRows)
{
// Rows for deleted devices or non-static groups are ignored.
@@ -197,7 +197,7 @@ public sealed class DeviceGroupService(AppDbContext db, InventoryReportCache inv
{
switch (group.Kind)
{
case GroupKind.Static:
case GroupKind.Static or GroupKind.Script:
return await db.DeviceGroupMembers.AsNoTracking()
.Where(m => m.GroupId == group.Id && db.Devices.Any(d => d.ClientId == m.ClientId))
.Select(m => m.ClientId)
@@ -306,7 +306,7 @@ public sealed class DeviceGroupService(AppDbContext db, InventoryReportCache inv
var directIds = groups
.Where(group => group.Kind switch
{
GroupKind.Static => staticGroupIds.Contains(group.Id),
GroupKind.Static or GroupKind.Script => staticGroupIds.Contains(group.Id),
GroupKind.Dynamic => ParseRules(group.RulesJson) is { } rules && RuleEvaluator.Matches(rules, fields),
_ => false,
})
@@ -397,7 +397,7 @@ public sealed class DeviceGroupService(AppDbContext db, InventoryReportCache inv
return (await GetMembershipAsync(cancellationToken)).Effective(group.Id).Contains(clientId);
}
if (group.Kind == GroupKind.Static)
if (ScriptGroups.HasMemberRows(group.Kind))
{
return await db.DeviceGroupMembers.AsNoTracking()
.AnyAsync(m => m.GroupId == group.Id && m.ClientId == clientId, cancellationToken);
+9 -6
View File
@@ -127,9 +127,9 @@ public static class GroupEndpoints
return rulesProblem;
}
// Only static groups keep an explicit list; switching kind drops it so
// a later switch back does not resurrect stale members.
if (request.Kind != GroupKind.Static && entity.Kind == GroupKind.Static)
// Only static and script groups keep an explicit list; switching to a kind without one drops
// it so a later switch back does not resurrect stale members.
if (!ScriptGroups.HasMemberRows(request.Kind) && ScriptGroups.HasMemberRows(entity.Kind))
{
await db.DeviceGroupMembers.Where(m => m.GroupId == id).ExecuteDeleteAsync(cancellationToken);
}
@@ -292,9 +292,12 @@ public static class GroupEndpoints
{
return Results.BadRequest(new
{
error = entity.Kind == GroupKind.Dynamic
? "Membership of a dynamic group is determined by its rules."
: "A folder holds groups, not devices. Add the devices to a static group inside it.",
error = entity.Kind switch
{
GroupKind.Dynamic => "Membership of a dynamic group is determined by its rules.",
GroupKind.Script => "Membership of a script group is set by the scripts that report on it.",
_ => "A folder holds groups, not devices. Add the devices to a static group inside it.",
},
});
}
+122
View File
@@ -0,0 +1,122 @@
using Backend.Data;
using Backend.Security;
using Microsoft.EntityFrameworkCore;
using Shared.Contracts.Models;
namespace Backend.Groups;
/// <summary>
/// Applies what a device's job said about its script groups (<see cref="ScriptGroups"/>): each named
/// script group gains or loses that device, and a group a device joins first is created (top level).
/// Only script groups change: a report naming a static, dynamic or folder group is ignored, so a
/// device can never put itself into a group an operator curates. One device's report only ever
/// changes that device's own membership.
/// </summary>
public sealed class ScriptGroupMembership(AppDbContext db, AuditService audit, ILogger<ScriptGroupMembership> logger)
{
/// <summary>What changed, for the activity feed.</summary>
public sealed record Outcome(IReadOnlyList<string> Joined, IReadOnlyList<string> Left, IReadOnlyList<string> Created, IReadOnlyList<string> Ignored)
{
public bool Changed => Joined.Count + Left.Count > 0;
}
public async Task<Outcome> ApplyAsync(
string clientId, string scriptName, IReadOnlyList<GroupMembershipReport> reports, CancellationToken cancellationToken)
{
var joined = new List<string>();
var left = new List<string>();
var created = new List<string>();
var ignored = new List<string>();
// The last word per group wins; past the limit nothing more is read.
var wanted = new Dictionary<string, bool>(StringComparer.OrdinalIgnoreCase);
foreach (var report in reports.Take(ScriptGroups.MaxReportsPerJob))
{
if (ScriptGroups.Normalize(report.Group) is { } name)
{
wanted.Remove(name);
wanted[name] = report.Member;
}
}
if (wanted.Count == 0 || !await db.Devices.AnyAsync(d => d.ClientId == clientId, cancellationToken))
{
return new Outcome(joined, left, created, ignored);
}
var lowered = wanted.Keys.Select(k => k.ToLowerInvariant()).ToList();
var named = await db.DeviceGroups
.Where(g => lowered.Contains(g.Name.ToLower()))
.ToListAsync(cancellationToken);
var now = DateTimeOffset.UtcNow;
foreach (var (name, member) in wanted)
{
var matches = named.Where(g => string.Equals(g.Name, name, StringComparison.OrdinalIgnoreCase)).ToList();
var group = matches.FirstOrDefault(g => g.Kind == GroupKind.Script);
if (group is null && matches.Count > 0)
{
// A curated group by that name: never touched by a device.
ignored.Add(name);
continue;
}
if (group is null)
{
if (!member)
{
continue;
}
group = new DeviceGroupEntity
{
Id = Guid.NewGuid(),
Name = name,
Kind = GroupKind.Script,
Description = $"Devices whose scripts report they belong; first reported by “{scriptName}”.",
CreatedUtc = now,
UpdatedUtc = now,
UpdatedBy = $"script:{scriptName}",
};
db.DeviceGroups.Add(group);
named.Add(group);
created.Add(name);
}
var row = await db.DeviceGroupMembers.SingleOrDefaultAsync(m => m.GroupId == group.Id && m.ClientId == clientId, cancellationToken);
if (member && row is null)
{
db.DeviceGroupMembers.Add(new DeviceGroupMemberEntity { GroupId = group.Id, ClientId = clientId, AddedUtc = now });
joined.Add(group.Name);
}
else if (!member && row is not null)
{
db.DeviceGroupMembers.Remove(row);
left.Add(group.Name);
}
}
await db.SaveChangesAsync(cancellationToken);
foreach (var name in created)
{
await audit.LogAsync(AuditCategories.Admin, "group-created", $"script:{scriptName}",
clientId: clientId, detail: $"{name} (Script)", cancellationToken: cancellationToken);
}
if (joined.Count + left.Count > 0)
{
await audit.LogAsync(AuditCategories.Admin, "group-members", $"script:{scriptName}", clientId: clientId,
detail: $"joined={string.Join(", ", joined)} left={string.Join(", ", left)}", cancellationToken: cancellationToken);
}
if (ignored.Count > 0)
{
logger.LogWarning(
"Device {ClientId} reported membership of {Groups} from “{Script}”; ignored: those are not script groups",
clientId, string.Join(", ", ignored), scriptName);
}
return new Outcome(joined, left, created, ignored);
}
}
+10 -1
View File
@@ -122,7 +122,9 @@ public sealed class JobDispatcher(IServiceScopeFactory scopeFactory, ILogger<Job
return delivering;
}
if (!await db.Scripts.AnyAsync(s => s.Id == snapshot.ScriptId, cancellationToken))
// The built-in power scripts are never stored.
if (Shared.Contracts.Models.PowerActions.Of(snapshot.ScriptId) is null
&& !await db.Scripts.AnyAsync(s => s.Id == snapshot.ScriptId, cancellationToken))
{
await FailAllAsync(runner, jobs, "The script was deleted before this device's start.", tally, cancellationToken);
return delivering;
@@ -133,6 +135,7 @@ public sealed class JobDispatcher(IServiceScopeFactory scopeFactory, ILogger<Job
.Where(d => clientIds.Contains(d.ClientId))
.ToDictionaryAsync(d => d.ClientId, StringComparer.Ordinal, cancellationToken);
var script = snapshot.ToScript();
var skips = new List<RunSkip>();
var sendable = new List<(JobEntity Job, DeviceEntity Device)>();
foreach (var job in jobs)
@@ -155,6 +158,12 @@ public sealed class JobDispatcher(IServiceScopeFactory scopeFactory, ILogger<Job
skips.Add(new RunSkip(device.ClientId, device.Hostname, SkipReasons.Offline));
await RemoveAsync(db, job, cancellationToken);
}
else if (JobRunner.Refusal(script, device.AgentVersion) is { } refusal)
{
// An older agent would ignore Run As Signed-In User and run as its own account,
// or restart where it was told to shut down.
await FailAsync(runner, job, refusal, tally, cancellationToken);
}
else
{
sendable.Add((job, device));
+88
View File
@@ -19,6 +19,7 @@ public static class JobEndpoints
{
app.MapGet(ApiRoutes.Jobs, ListAsync).RequirePermission(Permissions.JobsView);
app.MapPost(ApiRoutes.Jobs, CreateAsync).RequirePermission(Permissions.JobsRun);
app.MapPost(ApiRoutes.Power, PowerAsync).RequirePermission(Permissions.DevicesPower);
app.MapGet(ApiRoutes.Job, GetAsync).RequirePermission(Permissions.JobsView);
app.MapGet(ApiRoutes.JobOutput, GetOutputAsync).RequirePermission(Permissions.JobsView);
app.MapGet(ApiRoutes.ScriptExecutions, ListExecutionsAsync).RequirePermission(Permissions.JobsView);
@@ -718,6 +719,93 @@ public static class JobEndpoints
jobs, skippedOrphaned, jobs.Count > 0 ? runId : null, skippedOffline));
}
/// <summary>
/// Restart or Shut Down: a run of the built-in power script (it does nothing; Restart After Run
/// is Always) on the devices and groups' members, with the same targets, exclusions, scope,
/// Only Devices Online Now and spread as a script's run. The delay, the warning and the
/// device's AllowRestart are Restart After Run's; a job's scheduled restart can be cancelled
/// from the console as any other. Agents too old to shut down (or to install updates) get
/// their job already failed. Always answers with a <see cref="GroupRunDto"/>.
/// </summary>
private static async Task<IResult> PowerAsync(
PowerRequest request,
AppDbContext db,
JobRunner runner,
Backend.Groups.DeviceGroupService groups,
DeviceScopeService scope,
AuditService audit,
HttpContext context,
CancellationToken cancellationToken)
{
if (!Enum.IsDefined(request.Action))
{
return Results.BadRequest(new { error = "Unknown power action." });
}
var groupIds = (request.GroupIds ?? []).Distinct().ToList();
var clientIds = (request.ClientIds ?? []).Distinct(StringComparer.Ordinal).ToList();
if (groupIds.Count == 0 && clientIds.Count == 0)
{
return Results.BadRequest(new { error = "Choose at least one device or group." });
}
var excludeGroupIds = (request.ExcludeGroupIds ?? []).Distinct().ToList();
var excludeClientIds = (request.ExcludeClientIds ?? []).Distinct(StringComparer.Ordinal).ToList();
if (clientIds.Concat(excludeClientIds).FirstOrDefault(id => !SubjectIdentifier.IsValid(id)) is not null)
{
return Results.BadRequest(new { error = "Invalid client id." });
}
if ((JobStagger.Validate(request.StaggerSeconds, request.StaggerBatchSize)
?? Shared.Contracts.Models.RestartOptions.ValidateDelay(request.DelaySeconds)
?? Shared.Contracts.Models.RestartOptions.ValidateWarning(request.WarningSeconds)) is { } invalid)
{
return Results.BadRequest(new { error = invalid });
}
var (resolved, targetsProblem) = await ResolveTargetsAsync(
groupIds, clientIds, excludeGroupIds, excludeClientIds, request.OnlineOnly, db, groups, scope, context, cancellationToken);
if (resolved is null)
{
return targetsProblem!;
}
var (selected, devices, eligible, skipped) = resolved;
var script = PowerScripts.For(request.Action, request.DelaySeconds, request.WarningSeconds, request.InstallUpdates);
var actor = context.User.Identity?.Name;
var runId = Guid.NewGuid();
var skippedOrphaned = skipped.Where(s => s.Reason == SkipReasons.Orphaned).Select(s => s.Hostname).ToList();
var skippedOffline = skipped.Where(s => s.Reason == SkipReasons.Offline).Select(s => s.Hostname).ToList();
if (eligible.Count > 0)
{
await runner.RecordRunAsync(
runId, script, actor, RunSources.Manual, TargetsLabel(selected, clientIds, devices), skipped,
cancellationToken, request.OnlineOnly);
}
var hostnames = eligible.ToDictionary(d => d.ClientId, d => d.Hostname, StringComparer.Ordinal);
var jobs = (await runner.StartRunAsync(
runId, new PreparedScript(script, null, null, null), null, eligible, actor, request.StaggerSeconds,
request.StaggerBatchSize, device => $"{script.Name} queued for {device.Hostname}", cancellationToken))
.Select(job => ToDto(job, hostnames.GetValueOrDefault(job.ClientId)))
.ToList();
await audit.LogAsync(AuditCategories.Jobs, request.Action == Shared.Contracts.Models.PowerAction.ShutDown ? "shut-down" : "restart", actor,
clientId: eligible.Count == 1 && groupIds.Count == 0 ? eligible[0].ClientId : null,
detail: $"run={runId} groups={selected.Count} devices={clientIds.Count} jobs={jobs.Count} " +
$"skippedOrphaned={skippedOrphaned.Count} skippedOffline={skippedOffline.Count}" +
(excludeGroupIds.Count + excludeClientIds.Count > 0
? $" excludedGroups={excludeGroupIds.Count} excludedDevices={excludeClientIds.Count}"
: string.Empty) +
(request.StaggerSeconds > 0 ? $" staggerSeconds={request.StaggerSeconds} staggerBatchSize={request.StaggerBatchSize}" : string.Empty) +
$" delaySeconds={request.DelaySeconds}" +
(request.WarningSeconds > 0 ? $" warningSeconds={request.WarningSeconds}" : string.Empty) +
(request.InstallUpdates ? " installUpdates=true" : string.Empty),
cancellationToken: cancellationToken);
return Results.Ok(new GroupRunDto(jobs, skippedOrphaned, jobs.Count > 0 ? runId : null, skippedOffline));
}
/// <summary>A run's targets as it starts: the groups named, every device reached, and those that get a job or are skipped.</summary>
private sealed record RunTargets(
List<DeviceGroupEntity> Groups, List<DeviceEntity> Devices, List<DeviceEntity> Eligible, List<RunSkip> Skipped);
+66 -4
View File
@@ -118,6 +118,41 @@ public sealed class JobRunner(
return job;
}
/// <summary>
/// Why a job of a Run As Signed-In User script cannot go to an agent at <paramref name="agentVersion"/>
/// (it would ignore the option and run as its own account), or null when it can.
/// </summary>
internal static string? RunAsUserRefusal(bool runAsUser, string? agentVersion, bool eachUser = false)
=> !runAsUser ? null
: !RunAsUser.Supported(agentVersion) ? RunAsUser.Unsupported(agentVersion)
: eachUser && !RunAsUser.EachUserSupported(agentVersion) ? RunAsUser.EachUserUnsupported(agentVersion)
: null;
/// <summary>
/// Why a job of <paramref name="script"/> cannot go to an agent at <paramref name="agentVersion"/>, or
/// null: Run As Signed-In User (it would run as its own account), and shutting down or installing
/// updates (it would restart, without them).
/// </summary>
internal static string? Refusal(ScriptEntity script, string? agentVersion)
=> RunAsUserRefusal(script.RunAsUser, agentVersion, script.RunAsEachUser)
?? (script.RestartAfterRun == RestartAfterRun.Off
? null
: PowerActions.Refusal(script.RestartAction, script.RestartInstallsUpdates, agentVersion));
/// <summary>True when the script's jobs may be refused for some agent versions.</summary>
internal static bool MayRefuse(ScriptEntity script)
=> script.RunAsUser
|| (script.RestartAfterRun != RestartAfterRun.Off && PowerActions.NeedsCurrentAgent(script.RestartAction, script.RestartInstallsUpdates));
/// <summary>A job created already failed (never sent).</summary>
private static JobEntity Refused(JobEntity job, string message, DateTimeOffset now)
{
job.State = JobState.Failed;
job.CompletedUtc = now;
job.OutputSummary = message;
return job;
}
private static JobEntity NewJob(ScriptEntity script, string clientId, string? requestedBy, Guid? runId, DateTimeOffset createdUtc) => new()
{
JobId = Guid.NewGuid(),
@@ -192,10 +227,19 @@ public sealed class JobRunner(
foreach (var chunk in devices.Chunk(WriteBatch))
{
var now = DateTimeOffset.UtcNow;
var batch = chunk.Select(d => new Outgoing(NewJob(prepared.Script, d.ClientId, requestedBy, runId, now), activityText(d))).ToList();
// A device whose agent cannot honor Run As Signed-In User gets its job already failed.
var created = chunk.Select(d =>
{
var job = NewJob(prepared.Script, d.ClientId, requestedBy, runId, now);
return (Device: d, Job: Refusal(prepared.Script, d.AgentVersion) is { } refusal ? Refused(job, refusal, now) : job);
}).ToList();
var batch = created
.Where(c => c.Job.State == JobState.Queued)
.Select(c => new Outgoing(c.Job, activityText(c.Device)))
.ToList();
undecided.UnionWith(batch.Select(o => o.Job));
await InsertAsync(batch.Select(o => o.Job).ToList(), cancellationToken);
jobs.AddRange(batch.Select(o => o.Job));
await InsertAsync(created.Select(c => c.Job).ToList(), cancellationToken);
jobs.AddRange(created.Select(c => c.Job));
var previous = sending;
var sent = publishing is null ? null : await publishing;
@@ -366,7 +410,11 @@ public sealed class JobRunner(
Trigger: trigger,
RestartAfterRun: script.RestartAfterRun,
RestartDelaySeconds: script.RestartDelaySeconds,
RestartWarningSeconds: script.RestartWarningSeconds),
RestartWarningSeconds: script.RestartWarningSeconds,
RunAsUser: script.RunAsUser,
RunAsEachUser: script.RunAsUser && script.RunAsEachUser,
RestartAction: script.RestartAction,
RestartInstallsUpdates: script.RestartInstallsUpdates),
cancellationToken);
}
@@ -604,6 +652,20 @@ public sealed class JobRunner(
DateTimeOffset? notBeforeUtc = null,
JobTrigger? trigger = null)
{
if (MayRefuse(prepared.Script))
{
var agentVersion = await db.Devices.AsNoTracking()
.Where(d => d.ClientId == job.ClientId)
.Select(d => d.AgentVersion)
.FirstOrDefaultAsync(cancellationToken);
if (Refusal(prepared.Script, agentVersion) is { } refusal)
{
// Settled here: nothing for the dispatcher to retry.
await MarkFailedAsync(job, refusal, cancellationToken);
return true;
}
}
var dispatched = await PublishAsync(prepared, job, arguments, notBeforeUtc, trigger, cancellationToken);
if (dispatched)
+29
View File
@@ -0,0 +1,29 @@
using Backend.Data;
using Shared.Contracts.Models;
namespace Backend.Jobs;
/// <summary>
/// The built-in scripts behind Restart and Shut Down (<see cref="PowerActions"/>): never stored,
/// they do nothing but end, and Restart After Run (Always) does the rest on the device.
/// </summary>
public static class PowerScripts
{
public static ScriptEntity For(PowerAction action, int delaySeconds, int warningSeconds, bool installUpdates)
{
var name = PowerActions.NameOf(action);
return new ScriptEntity
{
Id = PowerActions.ScriptIdOf(action),
Name = name,
Language = Backend.Scripts.ScriptEndpoints.ScriptLanguage,
Content = $"# {name}: Restart After Run does it once this run has ended.",
CleanUpAfterRun = true,
RestartAfterRun = RestartAfterRun.Always,
RestartDelaySeconds = delaySeconds,
RestartWarningSeconds = warningSeconds,
RestartAction = action,
RestartInstallsUpdates = installUpdates,
};
}
}
+17 -2
View File
@@ -32,7 +32,14 @@ public sealed record RunSnapshot(
DateTimeOffset? NotBeforeUtc = null,
Shared.Contracts.Messages.JobTrigger? Trigger = null,
// Warn Signed-In Users; null in snapshots sealed before it existed (off).
int? RestartWarningSeconds = null)
int? RestartWarningSeconds = null,
// Run as the signed-in user; null in snapshots sealed before it existed (off).
bool? RunAsUser = null,
// Once for each signed-in user; null in snapshots sealed before it existed (off).
bool? RunAsEachUser = null,
// The built-in power scripts' action and updates; null in snapshots sealed before they existed (restart, none).
Shared.Contracts.Models.PowerAction? RestartAction = null,
bool? RestartInstallsUpdates = null)
{
/// <summary>
/// The snapshot of a run; <paramref name="notBeforeUtc"/> and <paramref name="trigger"/> belong to
@@ -58,7 +65,11 @@ public sealed record RunSnapshot(
prepared.Script.RestartDelaySeconds,
notBeforeUtc,
trigger,
prepared.Script.RestartWarningSeconds);
prepared.Script.RestartWarningSeconds,
prepared.Script.RunAsUser,
prepared.Script.RunAsEachUser,
prepared.Script.RestartAction,
prepared.Script.RestartInstallsUpdates);
/// <summary>A detached script entity to prepare and dispatch from.</summary>
public ScriptEntity ToScript() => new()
@@ -77,6 +88,10 @@ public sealed record RunSnapshot(
RestartAfterRun = RestartAfterRun ?? Shared.Contracts.Models.RestartAfterRun.Off,
RestartDelaySeconds = RestartDelaySeconds ?? 0,
RestartWarningSeconds = RestartWarningSeconds ?? 0,
RunAsUser = RunAsUser ?? false,
RunAsEachUser = RunAsEachUser ?? false,
RestartAction = RestartAction ?? Shared.Contracts.Models.PowerAction.Restart,
RestartInstallsUpdates = RestartInstallsUpdates ?? false,
};
}
+28
View File
@@ -1461,6 +1461,34 @@ public sealed class MessagingWorkers(
await broadcaster.BroadcastActivityAsync(new ActivityEventPayload(
"job-completed", $"Job “{stored.ScriptName}” {payload.State.ToString().ToLowerInvariant()}",
payload.ClientId, payload.JobId, DateTimeOffset.UtcNow), cancellationToken);
// What the script said about its device's script groups, once (a redelivered final state is not applied).
if (stored.Applied && payload.GroupMemberships is { Count: > 0 } reports)
{
await ApplyGroupMembershipsAsync(payload, stored.ScriptName, reports, cancellationToken);
}
}
}
private async Task ApplyGroupMembershipsAsync(
JobStatePayload payload, string scriptName, IReadOnlyList<GroupMembershipReport> reports, CancellationToken cancellationToken)
{
try
{
using var scope = scopeFactory.CreateScope();
var outcome = await scope.ServiceProvider.GetRequiredService<Backend.Groups.ScriptGroupMembership>()
.ApplyAsync(payload.ClientId, scriptName, reports, cancellationToken);
if (outcome.Changed)
{
var parts = outcome.Joined.Select(g => $"joined “{g}”").Concat(outcome.Left.Select(g => $"left “{g}”"));
await broadcaster.BroadcastActivityAsync(new ActivityEventPayload(
"group-membership", $"“{scriptName}”: device {string.Join(", ", parts)}",
payload.ClientId, payload.JobId, DateTimeOffset.UtcNow), cancellationToken);
}
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
logger.LogError(ex, "Job {JobId}: its script group memberships could not be applied", payload.JobId);
}
}
+3 -1
View File
@@ -90,7 +90,7 @@ var logSettings = LogSettings.FromConfiguration(
// The last lines in memory too, for Server Logs in the console.
var liveLog = new LiveLog();
builder.Logging.ClearProviders();
builder.Services.AddSerilog(LoggingSetup.CreateLogger(logSettings, "backend", liveLog), dispose: true);
builder.Services.AddSerilog(LoggingSetup.CreateLogger(logSettings, "Server", liveLog), dispose: true);
builder.Services.AddSingleton(new Backend.Logs.ServerLogs(liveLog, logSettings.Directory));
builder.Services.ConfigureHttpJsonOptions(options =>
@@ -157,6 +157,7 @@ builder.Services.AddSingleton(DeviceLifecycleOptions.FromConfiguration(builder.C
builder.Services.AddSingleton<Backend.Groups.InventoryReportCache>();
builder.Services.AddSingleton<Backend.Dashboard.DashboardCache>();
builder.Services.AddScoped<DeviceGroupService>();
builder.Services.AddScoped<Backend.Groups.ScriptGroupMembership>();
builder.Services.AddScoped<ScriptTriggerService>();
builder.Services.AddScoped<Backend.Groups.DeviceRunService>();
@@ -522,6 +523,7 @@ AgentDownloadEndpoints.Map(app);
DeviceEndpoints.Map(app);
ScriptEndpoints.Map(app);
FunctionEndpoints.Map(app);
Backend.Snippets.SnippetEndpoints.Map(app);
Backend.Sequences.SequenceEndpoints.Map(app);
Backend.Folders.LibraryFolderEndpoints.Map(app);
JobEndpoints.Map(app);
+17 -4
View File
@@ -144,6 +144,8 @@ public static class ScriptEndpoints
RestartAfterRun = request.RestartAfterRun ?? RestartAfterRun.Off,
RestartDelaySeconds = request.RestartDelaySeconds ?? 0,
RestartWarningSeconds = request.RestartWarningSeconds ?? 0,
RunAsUser = request.RunAsUser ?? false,
RunAsEachUser = request.RunAsEachUser ?? false,
CreatedUtc = now,
UpdatedUtc = now,
CreatedBy = actor,
@@ -220,6 +222,9 @@ public static class ScriptEndpoints
script.RestartAfterRun = request.RestartAfterRun ?? script.RestartAfterRun;
script.RestartDelaySeconds = request.RestartDelaySeconds ?? script.RestartDelaySeconds;
script.RestartWarningSeconds = request.RestartWarningSeconds ?? script.RestartWarningSeconds;
script.RunAsUser = request.RunAsUser ?? script.RunAsUser;
// Turning Run As Signed-In User off turns Each Signed-In User off with it.
script.RunAsEachUser = request.RunAsEachUser ?? (request.RunAsUser == false ? false : script.RunAsEachUser);
NormalizeOptions(script);
script.UpdatedUtc = DateTimeOffset.UtcNow;
script.UpdatedBy = context.User.Identity?.Name;
@@ -285,15 +290,23 @@ public static class ScriptEndpoints
script.SetWorkingDirectory,
script.RestartAfterRun,
script.RestartDelaySeconds,
script.RestartWarningSeconds);
script.RestartWarningSeconds,
script.RunAsUser,
script.RunAsEachUser);
/// <summary>
/// Set Working Directory needs a staged file: PowerShell 7 stages one only
/// with Run From File (5.1 and Bash always do), so without it the option is off.
/// Set Working Directory needs a staged file: PowerShell 7 stages one only with Run From
/// File or Run As Signed-In User (5.1 and Bash always do), so without either the option is off.
/// </summary>
internal static void NormalizeOptions(ScriptEntity script)
{
if (ParseEngine(script.Language) == ScriptEngine.PowerShell && !script.RunFromFile)
// Each Signed-In User is a kind of Run As Signed-In User: one turns the other on.
if (script.RunAsEachUser)
{
script.RunAsUser = true;
}
if (ParseEngine(script.Language) == ScriptEngine.PowerShell && !script.RunFromFile && !script.RunAsUser)
{
script.SetWorkingDirectory = false;
}
+6 -4
View File
@@ -40,15 +40,17 @@ public sealed class ShellBridge(
}
/// <summary>
/// Publishes the privileged shell.open command to the agent (<paramref name="shell"/>: a <see cref="ShellKinds"/> value);
/// false when it may not be sent (Require Sealed Agents, and the device does not seal).
/// Publishes the privileged shell.open command to the agent (<paramref name="shell"/>: a <see cref="ShellKinds"/> value;
/// <paramref name="asUser"/>: as the signed-in user); false when it may not be sent (Require Sealed Agents, and the
/// device does not seal).
/// </summary>
public async Task<bool> OpenAsync(ShellBinding binding, int cols, int rows, string? shell, CancellationToken cancellationToken)
public async Task<bool> OpenAsync(
ShellBinding binding, int cols, int rows, string? shell, CancellationToken cancellationToken, bool asUser = false, string? user = null)
{
var envelope = MessageEnvelope.Create(
MessageTypes.CommandShellOpen,
BackendSource,
new ShellOpenCommandPayload(binding.ShellId, cols, rows, shell),
new ShellOpenCommandPayload(binding.ShellId, cols, rows, shell, asUser, asUser ? user : null),
new EndpointRef(EndpointKinds.Agent, binding.ClientId));
if (!await PublishToAgentAsync(binding.ClientId, NatsSubjects.AgentCommandShellOpen(binding.ClientId), envelope, cancellationToken))
+16 -2
View File
@@ -61,6 +61,19 @@ public static class ShellEndpoints
return Results.NotFound();
}
// An older agent would ignore As Signed-In User and start the shell as its own account.
if (request.AsUser && !RunAsUser.Supported(device.AgentVersion))
{
return Results.Problem(statusCode: StatusCodes.Status409Conflict, title: RunAsUser.Unsupported(device.AgentVersion));
}
// A chosen signed-in user: a plain account name (a Windows domain account or a unix name), never a path or a list.
var user = string.IsNullOrWhiteSpace(request.User) ? null : request.User.Trim();
if (user is not null && (!request.AsUser || user.Length > 256 || user.Any(c => char.IsControl(c) || c is '/' or ':' or ',' or '"')))
{
return Results.BadRequest(new { error = "User must name one signed-in user, with Run As Signed-In User." });
}
var shellId = Guid.NewGuid();
var actor = context.User.Identity?.Name;
@@ -75,7 +88,8 @@ public static class ShellEndpoints
await db.SaveChangesAsync(cancellationToken);
var binding = bridge.Register(shellId, clientId, request.BrowserSessionId);
if (!await bridge.OpenAsync(binding, Math.Clamp(request.Cols, 1, 500), Math.Clamp(request.Rows, 1, 200), shell, cancellationToken))
if (!await bridge.OpenAsync(
binding, Math.Clamp(request.Cols, 1, 500), Math.Clamp(request.Rows, 1, 200), shell, cancellationToken, request.AsUser, user))
{
return Results.Problem(
statusCode: StatusCodes.Status409Conflict,
@@ -84,7 +98,7 @@ public static class ShellEndpoints
// The requested shell lives in the audit detail (the session row has no column for it).
await audit.LogAsync(AuditCategories.Shell, "opened", actor,
clientId: clientId, detail: $"shell={shellId} kind={shell}",
clientId: clientId, detail: $"shell={shellId} kind={shell} as={(request.AsUser ? user ?? "signed-in-user" : "agent")}",
remoteIp: Proxy.ClientIp.EffectiveText(context), cancellationToken: cancellationToken);
return Results.Ok(new CreateShellResponse(
+623
View File
@@ -0,0 +1,623 @@
using System.Security.Cryptography;
using System.Text;
using Shared.Contracts.Api;
using Shared.Contracts.Models;
namespace Backend.Snippets;
/// <summary>
/// The snippets every server ships with. They are not stored: each has a fixed id (from its key), is
/// listed with the library's own and can be copied, never changed. Tab stops are <c>${1:default}</c>,
/// <c>${1}</c> (the same text again) and <c>${1|a,b|}</c> (a choice); see <see cref="SnippetDto"/>.
/// </summary>
public static class BuiltInSnippets
{
private const ScriptEngine Ps = ScriptEngine.PowerShell;
private const ScriptEngine Bash = ScriptEngine.Bash;
public static IReadOnlyList<SnippetDto> All { get; } = Build();
private static readonly Dictionary<Guid, SnippetDto> ById = All.ToDictionary(s => s.Id);
public static SnippetDto? Find(Guid id) => ById.GetValueOrDefault(id);
/// <summary>The fixed id of the built-in snippet with <paramref name="key"/>.</summary>
public static Guid IdOf(string key)
{
var hash = SHA256.HashData(Encoding.UTF8.GetBytes("executer.snippet." + key));
var bytes = hash.AsSpan(0, 16).ToArray();
// RFC 4122 layout: version 8 (custom), variant 10.
bytes[7] = (byte)((bytes[7] & 0x0F) | 0x80);
bytes[8] = (byte)((bytes[8] & 0x3F) | 0x80);
return new Guid(bytes);
}
private static List<SnippetDto> Build()
{
var list = new List<SnippetDto>();
void Add(string key, string name, string description, ScriptEngine language, string content)
=> list.Add(new SnippetDto(IdOf(key), name, description, language, content.ReplaceLineEndings("\n").TrimEnd() + "\n", BuiltIn: true));
// ── PowerShell: structure ─────────────────────────────────────────────
Add("ps.try-catch-log", "Try/Catch with Logging",
"Stops on the first error, logs it with a timestamp and fails the job.", Ps,
"""
$ErrorActionPreference = 'Stop'
try {
${1:Get-Item -Path 'C:\Missing'}
}
catch {
Write-Output "[$(Get-Date -Format s)] ERROR ${2:step}: $($_.Exception.Message)"
Write-Output $_.ScriptStackTrace
exit 1
}
""");
Add("ps.param-block", "Parameter Block",
"A param() block; ExecuteR reads it into the script's parameters.", Ps,
"""
[CmdletBinding()]
param(
[Parameter(Mandatory)]
[string]$${1:ComputerName},
[ValidateSet('Install', 'Uninstall')]
[string]$${2:Action} = 'Install',
[switch]$${3:Force}
)
""");
Add("ps.advanced-function", "Advanced Function",
"A function with CmdletBinding, a mandatory parameter and pipeline input.", Ps,
"""
function ${1:Get-Thing} {
[CmdletBinding()]
param(
[Parameter(Mandatory, ValueFromPipeline)]
[string]$${2:Name}
)
process {
Write-Output $${2}${0}
}
}
""");
Add("ps.require-admin", "Require Administrator",
"Fails the job unless it runs elevated (an administrator or SYSTEM).", Ps,
"""
$principal = [Security.Principal.WindowsPrincipal]::new([Security.Principal.WindowsIdentity]::GetCurrent())
if (-not $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) {
Write-Output 'This script must run elevated (as an administrator or SYSTEM).'
exit 1
}
""");
Add("ps.retry", "Retry with Backoff",
"Runs a command until it succeeds, waiting longer after each failure.", Ps,
"""
$attempts = ${1:5}
for ($i = 1; $i -le $attempts; $i++) {
try {
${2:Invoke-RestMethod -Uri 'https://example.com/health' -ErrorAction Stop}
break
}
catch {
if ($i -eq $attempts) { throw }
Write-Output "Attempt $i of $attempts failed: $($_.Exception.Message)"
Start-Sleep -Seconds ([math]::Pow(2, $i))
}
}
""");
Add("ps.log-file", "Write to a Log File",
"A Write-Log helper that appends timestamped lines to a file and the job output.", Ps,
"""
$logPath = Join-Path "${1:$env:ProgramData\Contoso\Logs}" '${2:script}.log'
New-Item -ItemType Directory -Path (Split-Path $logPath) -Force | Out-Null
function Write-Log {
param([string]$Message, [ValidateSet('INFO', 'WARN', 'ERROR')][string]$Level = 'INFO')
$line = '{0} [{1}] {2}' -f (Get-Date -Format 'yyyy-MM-dd HH:mm:ss'), $Level, $Message
Add-Content -Path $logPath -Value $line
Write-Output $line
}
Write-Log '${3:Started}'
""");
// ── PowerShell: registry, services, events ────────────────────────────
Add("ps.registry-read", "Read a Registry Value",
"Reads one value; says so when it is not set.", Ps,
"""
$path = '${1:HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion}'
$name = '${2:DisplayVersion}'
$value = (Get-ItemProperty -Path $path -Name $name -ErrorAction SilentlyContinue).$name
if ($null -eq $value) { Write-Output "$name is not set under $path" } else { Write-Output "$name = $value" }
""");
Add("ps.registry-write", "Write a Registry Value",
"Creates the key when missing and sets a typed value.", Ps,
"""
$path = '${1:HKLM:\SOFTWARE\Contoso}'
if (-not (Test-Path $path)) { New-Item -Path $path -Force | Out-Null }
New-ItemProperty -Path $path -Name '${2:Setting}' -Value ${3:1} -PropertyType ${4|DWord,String,QWord,ExpandString,MultiString,Binary|} -Force | Out-Null
""");
Add("ps.service-status", "Service Status",
"Status and start type of a service.", Ps,
"""
Get-Service -Name '${1:Spooler}' -ErrorAction Stop | Select-Object Name, DisplayName, Status, StartType
""");
Add("ps.service-restart", "Restart a Service",
"Restarts a service and waits until it is running again.", Ps,
"""
$name = '${1:Spooler}'
Restart-Service -Name $name -Force -ErrorAction Stop
$service = Get-Service -Name $name
$service.WaitForStatus('Running', [TimeSpan]::FromSeconds(${2:30}))
Write-Output "$name is $($service.Status)"
""");
Add("ps.event-log", "Query an Event Log",
"Recent errors (or another level) from a Windows event log.", Ps,
"""
Get-WinEvent -FilterHashtable @{
LogName = '${1|System,Application,Security,Setup|}'
Level = ${2:2} # 1 critical, 2 error, 3 warning, 4 information
StartTime = (Get-Date).AddHours(-${3:24})
} -MaxEvents ${4:50} -ErrorAction SilentlyContinue |
Select-Object TimeCreated, Id, ProviderName, LevelDisplayName, Message |
Format-Table -AutoSize -Wrap
""");
Add("ps.scheduled-task", "Create a Scheduled Task",
"Registers (or replaces) a daily task that runs a script as SYSTEM.", Ps,
"""
$action = New-ScheduledTaskAction -Execute 'powershell.exe' -Argument '-NoProfile -ExecutionPolicy Bypass -File "${1:C:\Scripts\Task.ps1}"'
$trigger = New-ScheduledTaskTrigger -Daily -At '${2:03:00}'
$principal = New-ScheduledTaskPrincipal -UserId 'SYSTEM' -LogonType ServiceAccount -RunLevel Highest
Register-ScheduledTask -TaskName '${3:Contoso Maintenance}' -Action $action -Trigger $trigger -Principal $principal -Force | Out-Null
Get-ScheduledTask -TaskName '${3}' | Select-Object TaskName, State
""");
Add("ps.firewall-rule", "Add a Firewall Rule",
"Adds a Windows Firewall rule unless one with the name exists.", Ps,
"""
$name = '${1:Contoso App}'
if (-not (Get-NetFirewallRule -DisplayName $name -ErrorAction SilentlyContinue)) {
New-NetFirewallRule -DisplayName $name -Direction ${2|Inbound,Outbound|} -Protocol ${3|TCP,UDP|} -LocalPort ${4:8080} -Action ${5|Allow,Block|} | Out-Null
}
Get-NetFirewallRule -DisplayName $name | Select-Object DisplayName, Enabled, Direction, Action
""");
// ── PowerShell: inventory and health ──────────────────────────────────
Add("ps.disk-space", "Disk Space",
"Size and free space of each fixed disk; fails below a free-space threshold.", Ps,
"""
$threshold = ${1:10} # percent free
$disks = Get-CimInstance -ClassName Win32_LogicalDisk -Filter 'DriveType = 3' |
Select-Object DeviceID,
@{ Name = 'SizeGB'; Expression = { [math]::Round($_.Size / 1GB, 1) } },
@{ Name = 'FreeGB'; Expression = { [math]::Round($_.FreeSpace / 1GB, 1) } },
@{ Name = 'FreePct'; Expression = { [math]::Round(100 * $_.FreeSpace / $_.Size, 1) } }
$disks | Format-Table -AutoSize
if ($disks | Where-Object FreePct -lt $threshold) {
Write-Output "Low disk space: under $threshold% free."
exit 1
}
""");
Add("ps.installed-software", "Installed Software",
"Programs from the uninstall keys (64- and 32-bit), filtered by name.", Ps,
"""
$keys = @(
'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\*'
'HKLM:\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*'
)
Get-ItemProperty -Path $keys -ErrorAction SilentlyContinue |
Where-Object { $_.DisplayName -like '${1:*}' } |
Select-Object DisplayName, DisplayVersion, Publisher, InstallDate |
Sort-Object DisplayName |
Format-Table -AutoSize
""");
Add("ps.pending-reboot", "Pending Restart Check",
"Whether Windows is waiting for a restart, and why.", Ps,
"""
$reasons = @()
if (Test-Path 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Component Based Servicing\RebootPending') { $reasons += 'Component Based Servicing' }
if (Test-Path 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update\RebootRequired') { $reasons += 'Windows Update' }
$sessionManager = Get-ItemProperty 'HKLM:\SYSTEM\CurrentControlSet\Control\Session Manager' -ErrorAction SilentlyContinue
if ($sessionManager.PendingFileRenameOperations) { $reasons += 'Pending file renames' }
$active = (Get-ItemProperty 'HKLM:\SYSTEM\CurrentControlSet\Control\ComputerName\ActiveComputerName').ComputerName
$next = (Get-ItemProperty 'HKLM:\SYSTEM\CurrentControlSet\Control\ComputerName\ComputerName').ComputerName
if ($active -ne $next) { $reasons += 'Computer rename' }
if ($reasons) { Write-Output "Restart pending: $($reasons -join ', ')" } else { Write-Output 'No restart pending.' }
""");
Add("ps.processes", "Top Processes",
"The processes using the most CPU time or memory.", Ps,
"""
Get-Process |
Sort-Object -Property ${1|CPU,WorkingSet64|} -Descending |
Select-Object -First ${2:10} Name, Id, CPU,
@{ Name = 'MemoryMB'; Expression = { [math]::Round($_.WorkingSet64 / 1MB, 1) } } |
Format-Table -AutoSize
""");
Add("ps.certificate-expiry", "Expiring Certificates",
"Machine certificates that expire within a number of days.", Ps,
"""
$limit = (Get-Date).AddDays(${1:30})
Get-ChildItem -Path Cert:\LocalMachine\${2|My,WebHosting,Root|} |
Where-Object { $_.NotAfter -lt $limit } |
Select-Object Subject, Thumbprint, NotAfter,
@{ Name = 'DaysLeft'; Expression = { [int]($_.NotAfter - (Get-Date)).TotalDays } } |
Sort-Object NotAfter |
Format-Table -AutoSize
""");
Add("ps.local-admins", "Local Administrators",
"Members of the local Administrators group (by SID, so any language).", Ps,
"""
try {
Get-LocalGroupMember -SID 'S-1-5-32-544' -ErrorAction Stop | Select-Object Name, ObjectClass, PrincipalSource
}
catch {
# Get-LocalGroupMember fails on unresolvable members; ADSI still lists them.
$group = (Get-CimInstance -ClassName Win32_Group -Filter "LocalAccount = TRUE AND SID = 'S-1-5-32-544'").Name
([ADSI]"WinNT://$env:COMPUTERNAME/$group,group").psbase.Invoke('Members') |
ForEach-Object { $_.GetType().InvokeMember('AdsPath', 'GetProperty', $null, $_, $null) }
}
""");
Add("ps.signed-in-users", "Signed-In Users",
"The console user and every session on the device.", Ps,
"""
$console = (Get-CimInstance -ClassName Win32_ComputerSystem).UserName
Write-Output "Console user: $(if ($console) { $console } else { 'nobody' })"
quser 2>$null
""");
Add("ps.uptime", "Uptime and Last Boot",
"When the device last started and how long it has been up.", Ps,
"""
$boot = (Get-CimInstance -ClassName Win32_OperatingSystem).LastBootUpTime
$up = (Get-Date) - $boot
Write-Output ('Up {0} days {1} hours (last boot {2:yyyy-MM-dd HH:mm})' -f $up.Days, $up.Hours, $boot)
""");
Add("ps.hotfixes", "Recent Updates",
"The most recently installed Windows updates.", Ps,
"""
Get-HotFix | Sort-Object InstalledOn -Descending | Select-Object -First ${1:10} HotFixID, Description, InstalledOn, InstalledBy
""");
Add("ps.bitlocker", "BitLocker Status",
"Encryption and protection status of each volume.", Ps,
"""
Get-BitLockerVolume | Select-Object MountPoint, VolumeStatus, ProtectionStatus, EncryptionPercentage, EncryptionMethod
""");
Add("ps.defender", "Defender Status",
"Microsoft Defender's protection state and signature age.", Ps,
"""
Get-MpComputerStatus |
Select-Object AMServiceEnabled, AntivirusEnabled, RealTimeProtectionEnabled, AntivirusSignatureLastUpdated, QuickScanAge, FullScanAge
""");
// ── PowerShell: files, web and data ───────────────────────────────────
Add("ps.download", "Download a File",
"Invoke-WebRequest with TLS 1.2 and no progress bar (much faster on 5.1).", Ps,
"""
[Net.ServicePointManager]::SecurityProtocol = [Net.ServicePointManager]::SecurityProtocol -bor [Net.SecurityProtocolType]::Tls12
$ProgressPreference = 'SilentlyContinue'
$destination = Join-Path $env:TEMP '${2:file.zip}'
Invoke-WebRequest -Uri '${1:https://example.com/file.zip}' -OutFile $destination -UseBasicParsing -ErrorAction Stop
Write-Output "Downloaded $((Get-Item $destination).Length) bytes to $destination"
""");
Add("ps.rest", "Call a REST API",
"Invoke-RestMethod with a bearer token from the script's secrets.", Ps,
"""
$headers = @{ Authorization = "Bearer $($Secrets.${1:ApiToken})"; Accept = 'application/json' }
$response = Invoke-RestMethod -Uri '${2:https://api.example.com/items}' -Method ${3|Get,Post,Put,Delete|} -Headers $headers -ErrorAction Stop
$response | ConvertTo-Json -Depth 5
""");
Add("ps.json", "Read and Write JSON",
"Loads a JSON file, changes a setting and saves it.", Ps,
"""
$path = '${1:C:\ProgramData\Contoso\config.json}'
$config = Get-Content -Path $path -Raw | ConvertFrom-Json
$config | Add-Member -NotePropertyName '${2:setting}' -NotePropertyValue '${3:value}' -Force
$config | ConvertTo-Json -Depth 10 | Set-Content -Path $path -Encoding UTF8
""");
Add("ps.csv", "Export to CSV",
"Pipes objects to a CSV file in the temp folder.", Ps,
"""
${1:Get-Service} |
Select-Object ${2:Name, Status} |
Export-Csv -Path (Join-Path $env:TEMP '${3:report.csv}') -NoTypeInformation -Encoding UTF8
""");
Add("ps.test-port", "Test a TCP Port",
"Whether a host accepts connections on a port (any platform); fails when it does not.", Ps,
"""
$client = [System.Net.Sockets.TcpClient]::new()
try { $open = $client.ConnectAsync('${1:server.contoso.com}', ${2:443}).Wait(${3:3000}) } catch { $open = $false } finally { $client.Dispose() }
Write-Output "${1}:${2} is $(if ($open) { 'open' } else { 'closed or filtered' })"
if (-not $open) { exit 1 }
""");
Add("ps.clean-old-files", "Remove Old Files",
"Deletes files older than a number of days under a folder and reports what it freed.", Ps,
"""
$cutoff = (Get-Date).AddDays(-${2:30})
$old = Get-ChildItem -Path '${1:C:\Windows\Temp}' -File -Recurse -Force -ErrorAction SilentlyContinue | Where-Object LastWriteTime -lt $cutoff
$bytes = ($old | Measure-Object -Property Length -Sum).Sum
$old | Remove-Item -Force -ErrorAction SilentlyContinue
Write-Output ('Removed {0} files ({1:N1} MB) older than {2:d}' -f @($old).Count, ($bytes / 1MB), $cutoff)
""");
Add("ps.file-hash", "File Hash",
"The hash of a file.", Ps,
"""
Get-FileHash -Path '${1:C:\Path\To\File}' -Algorithm ${2|SHA256,SHA1,SHA512,MD5|} | Select-Object Algorithm, Hash, Path
""");
// ── ExecuteR (PowerShell) ─────────────────────────────────────────────
Add("executer.ps.ask-restart", "Ask for a Restart (exit 3010)",
"Exit 3010: with Restart After Run set to When Requested, ExecuteR restarts the device after the run.", Ps,
"""
$restartNeeded = ${1:$true}
if ($restartNeeded) {
Write-Output 'Asking for a restart.'
exit 3010 # 1641 works too; Restart After Run: When Requested
}
""");
Add("executer.ps.secret", "Use a Secret",
"A secret bound on the script's Secrets tab, from $Secrets (or the variable named there).", Ps,
"""
$${1:apiKey} = $Secrets.${2:ApiKey}
if (-not $${1}) { throw 'The ${2} secret is not bound to this script.' }
""");
Add("executer.ps.secret-credential", "Credential from Secrets",
"A PSCredential built from a user name and password bound as secrets.", Ps,
"""
$credential = [pscredential]::new(
$Secrets.${1:UserName},
(ConvertTo-SecureString -String $Secrets.${2:Password} -AsPlainText -Force))
""");
Add("executer.ps.files", "Use a Delivered File",
"A file bound on the script's Files tab: $Files.<Name> is its FileInfo (a DirectoryInfo for a folder).", Ps,
"""
$file = $Files.${1:Installer}
if (-not $file -or -not $file.Exists) { throw 'The ${1} file was not delivered.' }
Write-Output "Using $($file.FullName) ($($file.Length) bytes)"
""");
Add("executer.ps.job-folder", "Work in the Job Folder",
"$ExecuteRJobDir: the run's own folder, cleaned up after the run (unless Clean Up After Run is off).", Ps,
"""
$base = if ($ExecuteRJobDir) { $ExecuteRJobDir } else { [IO.Path]::GetTempPath() }
$work = Join-Path $base '${1:work}'
New-Item -ItemType Directory -Path $work -Force | Out-Null
""");
Add("executer.ps.trigger", "What Started the Run",
"$Trigger: the event that started the run (enrollment, agent-ready, logon, device-cli), else not set.", Ps,
"""
if ($Trigger) {
Write-Output "Started by $($Trigger.Kind) at $($Trigger.OccurredUtc)$(if ($Trigger.User) { " for $($Trigger.User)" })"
}
else {
Write-Output 'Started from the console or a schedule.'
}
""");
// ── Bash ──────────────────────────────────────────────────────────────
Add("bash.strict", "Strict Mode Header",
"Stops on errors, unset variables and failed pipes, and names the failing line.", Bash,
"""
#!/usr/bin/env bash
set -euo pipefail
trap 'echo "Failed at line $LINENO: $BASH_COMMAND" >&2' ERR
""");
Add("bash.require-root", "Require Root",
"Fails the job unless it runs as root.", Bash,
"""
if [ "$(id -u)" -ne 0 ]; then
echo "This script must run as root." >&2
exit 1
fi
""");
Add("bash.retry", "Retry with Backoff",
"Runs a command until it succeeds, waiting longer after each failure.", Bash,
"""
attempts=${1:5}
for i in $(seq 1 "$attempts"); do
if ${2:curl -fsS https://example.com/health}; then
break
fi
if [ "$i" -eq "$attempts" ]; then
echo "Failed after $attempts attempts." >&2
exit 1
fi
sleep $((2 ** i))
done
""");
Add("bash.disk", "Disk Usage",
"Usage of each real filesystem; fails when one is over a threshold.", Bash,
"""
threshold=${1:90} # percent used
df -hP -x tmpfs -x devtmpfs -x squashfs -x overlay
full=$(df -P -x tmpfs -x devtmpfs -x squashfs -x overlay | awk -v t="$threshold" 'NR > 1 { sub("%", "", $5); if ($5 + 0 >= t) print $6 " (" $5 "%)" }')
if [ -n "$full" ]; then
echo "At or over $threshold% used:"
echo "$full"
exit 1
fi
""");
Add("bash.service-status", "Service Status (systemctl)",
"Whether a systemd service is running, with its recent log lines.", Bash,
"""
service='${1:ssh}'
if systemctl is-active --quiet "$service"; then echo "$service is running"; else echo "$service is not running"; fi
systemctl status "$service" --no-pager --lines=${2:10} || true
""");
Add("bash.service-restart", "Restart a Service (systemctl)",
"Restarts a systemd service; shows its journal and fails if it does not come back.", Bash,
"""
service='${1:nginx}'
systemctl restart "$service"
sleep ${2:3}
if systemctl is-active --quiet "$service"; then
echo "$service restarted"
else
journalctl -u "$service" -n 20 --no-pager
exit 1
fi
""");
Add("bash.package-query", "Installed Package Version",
"A package's installed version, with dpkg (Debian, Ubuntu) or rpm (RHEL, Fedora, SUSE).", Bash,
"""
package='${1:openssl}'
if command -v dpkg-query >/dev/null 2>&1; then
dpkg-query -W -f='${Package} ${Version} ${Status}\n' "$package" 2>/dev/null || echo "$package is not installed"
elif command -v rpm >/dev/null 2>&1; then
rpm -q "$package" || true
else
echo "Neither dpkg nor rpm is available." >&2
exit 1
fi
""");
Add("bash.package-install", "Install a Package",
"Installs a package with apt, dnf, yum or zypper, whichever the system has.", Bash,
"""
package='${1:curl}'
if command -v apt-get >/dev/null 2>&1; then
apt-get update -q && DEBIAN_FRONTEND=noninteractive apt-get install -y -q "$package"
elif command -v dnf >/dev/null 2>&1; then
dnf install -y -q "$package"
elif command -v yum >/dev/null 2>&1; then
yum install -y -q "$package"
elif command -v zypper >/dev/null 2>&1; then
zypper --non-interactive install "$package"
else
echo "No known package manager." >&2
exit 1
fi
""");
Add("bash.journal", "Journal Errors",
"Recent journal entries at or above a priority.", Bash,
"""
journalctl -p ${1|err,warning,crit|} --since "${2:24 hours ago}" --no-pager -n ${3:100}
""");
Add("bash.users", "Local Users and Sudoers",
"Accounts that can sign in, and members of the sudo, wheel and admin groups.", Bash,
"""
getent passwd | awk -F: '$3 == 0 || ($3 >= 1000 && $3 < 65534) { print $1 " (uid " $3 ", " $7 ")" }'
echo "Administrators:"
getent group sudo wheel admin | cut -d: -f1,4
""");
Add("bash.download", "Download a File (curl)",
"Downloads with retries and fails on HTTP errors.", Bash,
"""
dest='${2:/tmp/file.tar.gz}'
curl -fsSL --retry 3 --retry-delay 5 -o "$dest" '${1:https://example.com/file.tar.gz}'
echo "Downloaded $(wc -c < "$dest") bytes to $dest"
""");
Add("bash.pending-reboot", "Pending Restart Check (Linux)",
"Whether the system is waiting for a restart (Debian/Ubuntu flag file, or needs-restarting).", Bash,
"""
if [ -f /var/run/reboot-required ]; then
echo "Restart pending:"
cat /var/run/reboot-required.pkgs 2>/dev/null || true
elif command -v needs-restarting >/dev/null 2>&1; then
needs-restarting -r || true
else
echo "No restart pending."
fi
""");
Add("bash.ports", "Listening Ports",
"TCP and UDP ports in use and the processes holding them.", Bash,
"""
ss -tulpn 2>/dev/null || netstat -tulpn
""");
Add("bash.processes", "Top Processes (ps)",
"The processes using the most CPU or memory.", Bash,
"""
ps -eo pid,user,%cpu,%mem,etime,comm --sort=-${1|%cpu,%mem|} | head -n ${2:11}
""");
Add("bash.os", "OS and Kernel",
"Distribution, kernel, architecture and uptime.", Bash,
"""
. /etc/os-release
echo "$PRETTY_NAME, kernel $(uname -r) ($(uname -m))"
uptime
""");
// ── ExecuteR (Bash) ───────────────────────────────────────────────────
Add("executer.bash.ask-restart", "Ask for a Restart (exit 194)",
"Exit 194 (what exit 3010 becomes on Linux and macOS): with Restart After Run set to When Requested, ExecuteR restarts the device.", Bash,
"""
restart_needed=${1:true}
if [ "$restart_needed" = true ]; then
echo "Asking for a restart."
exit 194 # Restart After Run: When Requested
fi
""");
Add("executer.bash.secret", "Use a Secret (Bash)",
"A secret bound on the script's Secrets tab arrives as an environment variable named after the binding.", Bash,
"""
if [ -z "${${1:API_KEY}:-}" ]; then
echo "The ${1} secret is not bound to this script." >&2
exit 1
fi
""");
Add("executer.bash.files", "Use a Delivered File (Bash)",
"A file bound on the script's Files tab: its path is in EXECUTER_FILE_<NAME>.", Bash,
"""
file="$EXECUTER_FILE_${1:INSTALLER}"
if [ ! -e "$file" ]; then
echo "The ${1} file was not delivered." >&2
exit 1
fi
echo "Using $file"
""");
return list;
}
}
+227
View File
@@ -0,0 +1,227 @@
using Backend.Auth;
using Backend.Data;
using Backend.Security;
using Microsoft.EntityFrameworkCore;
using Shared.Contracts.Api;
using Shared.Contracts.Models;
namespace Backend.Snippets;
/// <summary>
/// The snippet library: the built-in snippets (from code, read-only) and the library's own
/// (stored). Reading follows scripts (Scripts View); changing needs Manage Scripts.
/// </summary>
public static class SnippetEndpoints
{
public const int MaxNameLength = 200;
public const int MaxDescriptionLength = 1000;
public const int MaxContentLength = 64 * 1024;
private const string BuiltInRefusal = "Built-in snippets cannot be changed. Copy one to make it your own.";
public static void Map(WebApplication app)
{
app.MapGet(ApiRoutes.Snippets, ListAsync).RequirePermission(Permissions.ScriptsView);
app.MapPost(ApiRoutes.Snippets, CreateAsync).RequirePermission(Permissions.ScriptsManage);
app.MapGet(ApiRoutes.Snippet, GetAsync).RequirePermission(Permissions.ScriptsView);
app.MapPut(ApiRoutes.Snippet, UpdateAsync).RequirePermission(Permissions.ScriptsManage);
app.MapDelete(ApiRoutes.Snippet, DeleteAsync).RequirePermission(Permissions.ScriptsManage);
app.MapPost(ApiRoutes.SnippetCopy, CopyAsync).RequirePermission(Permissions.ScriptsManage);
}
private static async Task<IResult> ListAsync(AppDbContext db, CancellationToken cancellationToken)
{
var stored = await db.Snippets.AsNoTracking().ToListAsync(cancellationToken);
var all = BuiltInSnippets.All
.Concat(stored.Select(ToDto))
.OrderBy(s => s.Name, StringComparer.OrdinalIgnoreCase)
.ThenBy(s => s.BuiltIn)
.ToList();
return Results.Ok(all);
}
private static async Task<IResult> GetAsync(Guid id, AppDbContext db, CancellationToken cancellationToken)
{
if (BuiltInSnippets.Find(id) is { } builtIn)
{
return Results.Ok(builtIn);
}
var snippet = await db.Snippets.AsNoTracking().SingleOrDefaultAsync(s => s.Id == id, cancellationToken);
return snippet is null ? Results.NotFound() : Results.Ok(ToDto(snippet));
}
private static async Task<IResult> CreateAsync(
SaveSnippetRequest request, AppDbContext db, AuditService audit, HttpContext context, CancellationToken cancellationToken)
{
if (Validate(request) is { } problem)
{
return Results.BadRequest(new { error = problem });
}
var snippet = New(request.Name.Trim(), request.Description, request.Language, request.Content, context.User.Identity?.Name);
db.Snippets.Add(snippet);
await db.SaveChangesAsync(cancellationToken);
await audit.LogAsync(AuditCategories.Scripts, "snippet-created", snippet.CreatedBy, detail: snippet.Name, cancellationToken: cancellationToken);
return Results.Created(ApiRoutes.For.Snippet(snippet.Id), ToDto(snippet));
}
private static async Task<IResult> UpdateAsync(
Guid id, SaveSnippetRequest request, AppDbContext db, AuditService audit, HttpContext context, CancellationToken cancellationToken)
{
if (BuiltInSnippets.Find(id) is not null)
{
return Results.Conflict(new { error = BuiltInRefusal });
}
var snippet = await db.Snippets.SingleOrDefaultAsync(s => s.Id == id, cancellationToken);
if (snippet is null)
{
return Results.NotFound();
}
if (Validate(request) is { } problem)
{
return Results.BadRequest(new { error = problem });
}
snippet.Name = request.Name.Trim();
snippet.Description = Normalize(request.Description);
snippet.Language = request.Language;
snippet.Content = request.Content ?? string.Empty;
snippet.UpdatedUtc = DateTimeOffset.UtcNow;
snippet.UpdatedBy = context.User.Identity?.Name;
await db.SaveChangesAsync(cancellationToken);
await audit.LogAsync(AuditCategories.Scripts, "snippet-updated", snippet.UpdatedBy, detail: snippet.Name, cancellationToken: cancellationToken);
return Results.Ok(ToDto(snippet));
}
private static async Task<IResult> DeleteAsync(
Guid id, AppDbContext db, AuditService audit, HttpContext context, CancellationToken cancellationToken)
{
if (BuiltInSnippets.Find(id) is not null)
{
return Results.Conflict(new { error = BuiltInRefusal });
}
var snippet = await db.Snippets.SingleOrDefaultAsync(s => s.Id == id, cancellationToken);
if (snippet is null)
{
return Results.NotFound();
}
db.Snippets.Remove(snippet);
await db.SaveChangesAsync(cancellationToken);
await audit.LogAsync(AuditCategories.Scripts, "snippet-deleted", context.User.Identity?.Name, detail: snippet.Name, cancellationToken: cancellationToken);
return Results.NoContent();
}
/// <summary>A copy of any snippet, built-in or not, as a new snippet of the library's own.</summary>
private static async Task<IResult> CopyAsync(
Guid id, CopySnippetRequest? request, AppDbContext db, AuditService audit, HttpContext context, CancellationToken cancellationToken)
{
var source = BuiltInSnippets.Find(id);
if (source is null)
{
var stored = await db.Snippets.AsNoTracking().SingleOrDefaultAsync(s => s.Id == id, cancellationToken);
source = stored is null ? null : ToDto(stored);
}
if (source is null)
{
return Results.NotFound();
}
var name = request?.Name?.Trim();
if (string.IsNullOrEmpty(name))
{
var taken = await db.Snippets.AsNoTracking().Select(s => s.Name).ToListAsync(cancellationToken);
name = CopyName(source.Name, taken);
}
if (name.Length > MaxNameLength)
{
return Results.BadRequest(new { error = $"The name can be at most {MaxNameLength} characters." });
}
var snippet = New(name, source.Description, source.Language, source.Content, context.User.Identity?.Name);
db.Snippets.Add(snippet);
await db.SaveChangesAsync(cancellationToken);
await audit.LogAsync(AuditCategories.Scripts, "snippet-copied", snippet.CreatedBy,
detail: $"{source.Name} → {snippet.Name}", cancellationToken: cancellationToken);
return Results.Created(ApiRoutes.For.Snippet(snippet.Id), ToDto(snippet));
}
/// <summary>"Name (copy)", then "Name (copy 2)" and on, the first no snippet of the library's own has.</summary>
internal static string CopyName(string name, IReadOnlyCollection<string> taken)
{
var names = taken.ToHashSet(StringComparer.OrdinalIgnoreCase);
string Named(string suffix) => (name.Length + suffix.Length > MaxNameLength ? name[..(MaxNameLength - suffix.Length)] : name) + suffix;
var candidate = Named(" (copy)");
for (var i = 2; names.Contains(candidate); i++)
{
candidate = Named($" (copy {i})");
}
return candidate;
}
internal static string? Validate(SaveSnippetRequest request)
{
if (string.IsNullOrWhiteSpace(request.Name))
{
return "Name is required.";
}
if (request.Name.Trim().Length > MaxNameLength)
{
return $"The name can be at most {MaxNameLength} characters.";
}
if (request.Description is { Length: > MaxDescriptionLength })
{
return $"The description can be at most {MaxDescriptionLength} characters.";
}
if (!Enum.IsDefined(request.Language))
{
return "Unknown language.";
}
if (string.IsNullOrWhiteSpace(request.Content))
{
return "The snippet has no code.";
}
return request.Content.Length > MaxContentLength
? $"A snippet can be at most {MaxContentLength / 1024} KB."
: null;
}
private static SnippetEntity New(string name, string? description, ScriptEngine language, string? content, string? actor)
{
var now = DateTimeOffset.UtcNow;
return new SnippetEntity
{
Id = Guid.NewGuid(),
Name = name,
Description = Normalize(description),
Language = language,
Content = content ?? string.Empty,
CreatedUtc = now,
CreatedBy = actor,
UpdatedUtc = now,
UpdatedBy = actor,
};
}
private static string? Normalize(string? description) => string.IsNullOrWhiteSpace(description) ? null : description.Trim();
private static SnippetDto ToDto(SnippetEntity s) =>
new(s.Id, s.Name, s.Description, s.Language, s.Content, false, s.CreatedUtc, s.CreatedBy, s.UpdatedUtc, s.UpdatedBy);
}
+1 -1
View File
@@ -32,7 +32,7 @@ rayon = "1"
serde = { version = "1", features = ["derive"] }
serde_json = "1"
tracing = "0.1"
tracing-subscriber = { version = "0.3", default-features = false, features = ["fmt", "std"] }
tracing-subscriber = { version = "0.3", default-features = false, features = ["registry", "std"] }
[target.'cfg(windows)'.dependencies.windows]
version = "0.62"
+14 -1
View File
@@ -70,7 +70,20 @@ TLS). The username and password the client sends are ignored.
### stderr
Human log lines, plus machine events as single lines `@event <json>`:
Log lines in ExecuteR's one log format (`src/logging.rs`; see the root README, *Log line format*):
```text
[2026-11-16T17:53:40.653Z] - [ScreenHost] - [WARN] - hardware H.264 encoder failed; using software reason="MFT busy"
```
UTC time to the millisecond, the category `ScreenHost` (a dependency's events carry its crate name,
such as `ironrdp_server`), the level (`TRACE` … `ERROR`), the message and the event's fields as
`key=value`. A warning or error that repeats is written once, then counted for 60 s; the window's
end writes one line with `repeated=N window=60s` (the last of them), and a quiet window forgets it.
Counts still open are written before the host exits. The agent logs each such line once, under the
host's category and level with this prefix taken off, so its own file has no second timestamp.
Plus machine events as single lines `@event <json>`:
| Event | When |
|---|---|
+9 -2
View File
@@ -11,6 +11,7 @@ pub mod events;
pub mod geometry;
pub mod input;
pub mod keymap;
pub mod logging;
pub mod mux;
pub mod platform;
pub mod rdcleanpath;
@@ -18,7 +19,8 @@ pub mod session;
pub mod tls;
pub mod video;
/// Initialises stderr logging at the given level.
/// Initialises stderr logging at the given level, in ExecuteR's one log format with
/// repeated warnings and errors bounded (see [`logging`]).
pub fn init_logging(level: cli::LogLevel) {
use tracing_subscriber::filter::LevelFilter;
let filter = match level {
@@ -27,5 +29,10 @@ pub fn init_logging(level: cli::LogLevel) {
cli::LogLevel::Info => LevelFilter::INFO,
cli::LogLevel::Debug => LevelFilter::DEBUG,
};
let _ = tracing_subscriber::fmt().with_writer(std::io::stderr).with_ansi(false).with_max_level(filter).try_init();
logging::init(filter);
}
/// Writes the repeat counts still open; call before the process exits.
pub fn flush_logging() {
logging::flush();
}
+515
View File
@@ -0,0 +1,515 @@
//! The host's log lines on stderr, in ExecuteR's one log format:
//!
//! ```text
//! [2026-11-16T17:53:40.653Z] - [ScreenHost] - [WARN] - hardware H.264 encoder failed; using software reason="MFT busy"
//! ```
//!
//! UTC to the millisecond; the category `ScreenHost` (or the crate an event comes from, such as
//! `ironrdp_server`); TRACE, DEBUG, INFO, WARN or ERROR; the message, then the event's fields as
//! `key=value` (a value with whitespace, `=` or `"` double-quoted). The agent reads these lines
//! from stderr and logs each again under the host's category and level, without this prefix.
//!
//! A warning or error that repeats is written once; the same one again within a minute is
//! counted, and when the minute ends with any counted ONE line says so: the last of them with
//! `repeated=N window=60s`. A quiet minute forgets it (see [`Throttle`]).
use std::collections::HashMap;
use std::fmt::{self, Write as _};
use std::io::Write as _;
use std::sync::{Arc, Mutex, OnceLock};
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
use tracing::field::{Field, Visit};
use tracing::{Event, Level, Subscriber};
use tracing_subscriber::layer::{Context, Layer};
/// The category of the host's own lines.
pub const CATEGORY: &str = "ScreenHost";
/// How long repeats are counted before one summary line.
pub const REPEAT_WINDOW: Duration = Duration::from_secs(60);
/// How many distinct warnings and errors are tracked at once (the oldest goes first).
pub const MAX_KEYS: usize = 1000;
/// `2026-11-16T17:53:40.653Z`.
pub fn format_timestamp(time: SystemTime) -> String {
let since = time.duration_since(UNIX_EPOCH).unwrap_or_default();
let secs = since.as_secs();
let (year, month, day) = civil_from_days((secs / 86_400) as i64);
let rest = secs % 86_400;
format!(
"{year:04}-{month:02}-{day:02}T{:02}:{:02}:{:02}.{:03}Z",
rest / 3600,
rest % 3600 / 60,
rest % 60,
since.subsec_millis()
)
}
/// Days since 1970-01-01 as a proleptic Gregorian date (H. Hinnant's `civil_from_days`).
fn civil_from_days(days: i64) -> (i64, u32, u32) {
let z = days + 719_468;
let era = z.div_euclid(146_097);
let doe = z.rem_euclid(146_097);
let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
let mp = (5 * doy + 2) / 153;
let day = (doy - (153 * mp + 2) / 5 + 1) as u32;
let month = (if mp < 10 { mp + 3 } else { mp - 9 }) as u32;
let year = yoe + era * 400 + i64::from(month <= 2);
(year, month, day)
}
/// The level as the line spells it.
pub fn level_name(level: Level) -> &'static str {
match level {
Level::TRACE => "TRACE",
Level::DEBUG => "DEBUG",
Level::INFO => "INFO",
Level::WARN => "WARN",
_ => "ERROR",
}
}
/// `ScreenHost` for the host's own code, the crate's name for a dependency's (`ironrdp_server`).
pub fn category(target: &str) -> String {
let krate = target.split("::").next().unwrap_or_default();
if krate.is_empty() || krate.to_ascii_lowercase().starts_with("executer_screen") {
CATEGORY.to_owned()
} else {
krate.to_owned()
}
}
/// A field value as a line shows it: bare, or double-quoted (escaping `"` and control
/// characters) when it is empty or holds whitespace, `=` or `"`.
pub fn quote(value: &str) -> String {
if !value.is_empty() && !value.chars().any(|c| c.is_whitespace() || c == '=' || c == '"' || c.is_control()) {
return value.to_owned();
}
let mut quoted = String::with_capacity(value.len() + 2);
quoted.push('"');
for c in value.chars() {
match c {
'"' => quoted.push_str("\\\""),
'\n' => quoted.push_str("\\n"),
'\r' => quoted.push_str("\\r"),
'\t' => quoted.push_str("\\t"),
c if c.is_control() => {
let _ = write!(quoted, "\\u{:04x}", u32::from(c));
}
c => quoted.push(c),
}
}
quoted.push('"');
quoted
}
/// What one line says, before its time is put on it.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Line {
pub level: Level,
pub category: String,
/// The message and its `key=value` fields.
pub text: String,
}
impl Line {
/// The whole line, without its newline.
pub fn format(&self, time: SystemTime) -> String {
format!("[{}] - [{}] - [{}] - {}", format_timestamp(time), self.category, level_name(self.level), self.text)
}
}
/// Collects an event's message and its fields as `key=value`.
#[derive(Default)]
struct Fields {
message: String,
rest: String,
}
impl Fields {
fn push(&mut self, field: &Field, value: &str) {
if field.name() == "message" {
self.message.push_str(value);
} else {
let _ = write!(self.rest, " {}={}", field.name(), quote(value));
}
}
fn into_text(self) -> String {
self.message + &self.rest
}
}
impl Visit for Fields {
fn record_str(&mut self, field: &Field, value: &str) {
self.push(field, value);
}
fn record_debug(&mut self, field: &Field, value: &dyn fmt::Debug) {
self.push(field, &format!("{value:?}"));
}
}
/// What tells one warning from another: its level and where it is logged (target and callsite).
pub type Key = (Level, &'static str, &'static str);
struct Entry {
start: Instant,
order: u64,
suppressed: u64,
last: Option<Line>,
}
/// Bounds repeated warnings and errors: the first is written, the same one again within the
/// window is counted, the window's end writes one summary of what was counted and starts the
/// next, and a window with nothing counted forgets the key. Time comes in as an argument.
pub struct Throttle {
window: Duration,
max_keys: usize,
entries: HashMap<Key, Entry>,
order: u64,
}
impl Throttle {
pub fn new(window: Duration, max_keys: usize) -> Self {
Self { window, max_keys: max_keys.max(1), entries: HashMap::new(), order: 0 }
}
/// How many keys are tracked now.
pub fn tracked(&self) -> usize {
self.entries.len()
}
/// A warning or error at `now`: the lines to write (summaries first, then the line itself
/// unless it is held back as a repeat).
pub fn admit(&mut self, key: Key, now: Instant, line: Line) -> Vec<Line> {
let mut out = Vec::new();
if let Some(entry) = self.entries.get_mut(&key)
&& now.saturating_duration_since(entry.start) >= self.window
{
match Self::close(entry, now, self.window) {
Some(summary) => out.push(summary),
None => {
self.entries.remove(&key);
}
}
}
if let Some(entry) = self.entries.get_mut(&key) {
entry.suppressed += 1;
entry.last = Some(line);
return out;
}
if self.entries.len() >= self.max_keys
&& let Some(oldest) = self.entries.iter().min_by_key(|(_, e)| e.order).map(|(k, _)| *k)
&& let Some(evicted) = self.entries.remove(&oldest)
&& let Some(summary) = Self::summary(&evicted, self.window)
{
out.push(summary);
}
self.order += 1;
self.entries.insert(key, Entry { start: now, order: self.order, suppressed: 0, last: None });
out.push(line);
out
}
/// Ends every window that is over at `now`: the summaries to write.
pub fn sweep(&mut self, now: Instant) -> Vec<Line> {
let window = self.window;
let mut out = Vec::new();
self.entries.retain(|_, entry| {
if now.saturating_duration_since(entry.start) < window {
return true;
}
match Self::close(entry, now, window) {
Some(summary) => {
out.push(summary);
true
}
None => false,
}
});
out
}
/// Every count still open (at exit), oldest key first; nothing is tracked afterwards.
pub fn drain(&mut self) -> Vec<Line> {
let mut entries: Vec<Entry> = self.entries.drain().map(|(_, e)| e).collect();
entries.sort_by_key(|e| e.order);
entries.iter().filter_map(|e| Self::summary(e, self.window)).collect()
}
fn close(entry: &mut Entry, now: Instant, window: Duration) -> Option<Line> {
let summary = Self::summary(entry, window)?;
entry.start = now;
entry.suppressed = 0;
entry.last = None;
Some(summary)
}
fn summary(entry: &Entry, window: Duration) -> Option<Line> {
let last = entry.last.as_ref().filter(|_| entry.suppressed > 0)?;
let mut line = last.clone();
let _ = write!(line.text, " repeated={} window={}", entry.suppressed, format_window(window));
Some(line)
}
}
/// `60s`, `1.5s`, `250ms`.
pub fn format_window(window: Duration) -> String {
if window >= Duration::from_secs(1) {
let secs = window.as_secs_f64();
if secs.fract() == 0.0 { format!("{}s", window.as_secs()) } else { format!("{secs}s") }
} else {
format!("{}ms", window.as_millis())
}
}
type LineSink = Box<dyn Fn(&str) + Send + Sync>;
/// Where lines go (stderr, or a test's sink) and the repeat throttle in front of it.
pub struct HostLog {
throttle: Mutex<Throttle>,
sink: LineSink,
}
impl HostLog {
pub fn new(sink: LineSink) -> Self {
Self { throttle: Mutex::new(Throttle::new(REPEAT_WINDOW, MAX_KEYS)), sink }
}
/// Writes to stderr, one whole line per write.
pub fn stderr() -> Self {
Self::new(Box::new(|line| {
let mut stderr = std::io::stderr().lock();
let _ = stderr.write_all(format!("{line}\n").as_bytes());
let _ = stderr.flush();
}))
}
fn throttle(&self) -> std::sync::MutexGuard<'_, Throttle> {
self.throttle.lock().unwrap_or_else(std::sync::PoisonError::into_inner)
}
fn write(&self, lines: Vec<Line>) {
let now = SystemTime::now();
for line in lines {
(self.sink)(&line.format(now));
}
}
/// One event's line: warnings and errors through the throttle, the rest straight out.
pub fn log(&self, key: Key, line: Line) {
if matches!(line.level, Level::WARN | Level::ERROR) {
let lines = self.throttle().admit(key, Instant::now(), line);
self.write(lines);
} else {
self.write(vec![line]);
}
}
/// Writes the summaries of windows that are over.
pub fn sweep(&self) {
let lines = self.throttle().sweep(Instant::now());
self.write(lines);
}
/// Writes every count still open (before the process exits).
pub fn flush(&self) {
let lines = self.throttle().drain();
self.write(lines);
}
}
/// The `tracing` layer that writes each event through a [`HostLog`].
pub struct HostLayer(pub Arc<HostLog>);
impl<S: Subscriber> Layer<S> for HostLayer {
fn on_event(&self, event: &Event<'_>, _ctx: Context<'_, S>) {
let metadata = event.metadata();
let mut fields = Fields::default();
event.record(&mut fields);
let line = Line { level: *metadata.level(), category: category(metadata.target()), text: fields.into_text() };
self.0.log((*metadata.level(), metadata.target(), metadata.name()), line);
}
}
static HOST_LOG: OnceLock<Arc<HostLog>> = OnceLock::new();
/// Installs stderr logging at `filter`, with a thread that writes repeat summaries as windows end.
pub fn init(filter: tracing_subscriber::filter::LevelFilter) {
use tracing_subscriber::layer::SubscriberExt as _;
use tracing_subscriber::util::SubscriberInitExt as _;
let log = Arc::clone(HOST_LOG.get_or_init(|| Arc::new(HostLog::stderr())));
if tracing_subscriber::registry().with(filter).with(HostLayer(Arc::clone(&log))).try_init().is_ok() {
let _ = std::thread::Builder::new().name("log-repeats".into()).spawn(move || {
loop {
std::thread::sleep(Duration::from_secs(1));
log.sweep();
}
});
}
}
/// Writes every repeat count still open; call before the process exits.
pub fn flush() {
if let Some(log) = HOST_LOG.get() {
log.flush();
}
}
#[cfg(test)]
mod tests {
use super::*;
use tracing_subscriber::layer::SubscriberExt as _;
fn line(level: Level, text: &str) -> Line {
Line { level, category: CATEGORY.to_owned(), text: text.to_owned() }
}
fn texts(lines: &[Line]) -> Vec<&str> {
lines.iter().map(|l| l.text.as_str()).collect()
}
const A: Key = (Level::WARN, "executer_screen::video", "event src/video.rs:94");
const B: Key = (Level::WARN, "executer_screen::video", "event src/video.rs:245");
const C: Key = (Level::ERROR, "executer_screen::session", "event src/session.rs:70");
#[test]
fn timestamps_are_utc_iso_with_milliseconds() {
assert_eq!(format_timestamp(UNIX_EPOCH), "1970-01-01T00:00:00.000Z");
assert_eq!(format_timestamp(UNIX_EPOCH + Duration::from_millis(1_794_851_620_653)), "2026-11-16T17:53:40.653Z");
assert_eq!(format_timestamp(UNIX_EPOCH + Duration::from_millis(1_709_251_199_999)), "2024-02-29T23:59:59.999Z");
assert_eq!(format_timestamp(UNIX_EPOCH + Duration::from_secs(951_868_800)), "2000-03-01T00:00:00.000Z");
}
#[test]
fn a_line_is_time_category_level_message() {
let l = Line { level: Level::WARN, category: "ScreenHost".into(), text: "slow reason=\"a b\"".into() };
assert_eq!(
l.format(UNIX_EPOCH + Duration::from_millis(1_794_851_620_653)),
"[2026-11-16T17:53:40.653Z] - [ScreenHost] - [WARN] - slow reason=\"a b\""
);
assert_eq!(level_name(Level::TRACE), "TRACE");
assert_eq!(level_name(Level::DEBUG), "DEBUG");
assert_eq!(level_name(Level::INFO), "INFO");
assert_eq!(level_name(Level::ERROR), "ERROR");
}
#[test]
fn values_are_quoted_only_when_they_must_be() {
assert_eq!(quote("plain"), "plain");
assert_eq!(quote("C:\\Windows"), "C:\\Windows");
assert_eq!(quote("two words"), "\"two words\"");
assert_eq!(quote("a=b"), "\"a=b\"");
assert_eq!(quote("say \"hi\""), "\"say \\\"hi\\\"\"");
assert_eq!(quote("line\nnext"), "\"line\\nnext\"");
assert_eq!(quote(""), "\"\"");
}
#[test]
fn the_category_is_screenhost_or_the_crate() {
assert_eq!(category("executer_screen::platform::windows::dxgi"), "ScreenHost");
assert_eq!(category("ExecuteR_Screen"), "ScreenHost");
assert_eq!(category("ironrdp_server::server"), "ironrdp_server");
assert_eq!(category(""), "ScreenHost");
}
#[test]
fn the_window_reads_short() {
assert_eq!(format_window(Duration::from_secs(60)), "60s");
assert_eq!(format_window(Duration::from_millis(1500)), "1.5s");
assert_eq!(format_window(Duration::from_millis(250)), "250ms");
}
#[test]
fn the_first_is_written_repeats_are_counted_and_the_window_ends_with_one_summary() {
let mut throttle = Throttle::new(REPEAT_WINDOW, MAX_KEYS);
let t0 = Instant::now();
assert_eq!(texts(&throttle.admit(A, t0, line(Level::WARN, "slow 1"))), ["slow 1"]);
for i in 2..=5 {
assert!(throttle.admit(A, t0 + Duration::from_secs(i), line(Level::WARN, &format!("slow {i}"))).is_empty());
}
assert!(throttle.sweep(t0 + Duration::from_secs(59)).is_empty());
assert_eq!(texts(&throttle.sweep(t0 + Duration::from_secs(60))), ["slow 5 repeated=4 window=60s"]);
}
#[test]
fn it_keeps_summarizing_once_per_window_and_a_quiet_window_starts_over() {
let mut throttle = Throttle::new(REPEAT_WINDOW, MAX_KEYS);
let t0 = Instant::now();
throttle.admit(C, t0, line(Level::ERROR, "broke 1"));
throttle.admit(C, t0, line(Level::ERROR, "broke 2"));
assert_eq!(texts(&throttle.sweep(t0 + REPEAT_WINDOW)), ["broke 2 repeated=1 window=60s"]);
let t1 = t0 + REPEAT_WINDOW;
assert!(throttle.admit(C, t1, line(Level::ERROR, "broke 3")).is_empty());
assert!(throttle.admit(C, t1, line(Level::ERROR, "broke 4")).is_empty());
assert_eq!(texts(&throttle.sweep(t1 + REPEAT_WINDOW)), ["broke 4 repeated=2 window=60s"]);
let t2 = t1 + REPEAT_WINDOW;
assert!(throttle.sweep(t2 + REPEAT_WINDOW).is_empty());
assert_eq!(throttle.tracked(), 0);
assert_eq!(texts(&throttle.admit(C, t2 + REPEAT_WINDOW, line(Level::ERROR, "broke 5"))), ["broke 5"]);
}
#[test]
fn a_repeat_after_the_window_without_a_sweep_gets_its_summary_first() {
let mut throttle = Throttle::new(REPEAT_WINDOW, MAX_KEYS);
let t0 = Instant::now();
throttle.admit(A, t0, line(Level::WARN, "slow 1"));
throttle.admit(A, t0, line(Level::WARN, "slow 2"));
let later = t0 + REPEAT_WINDOW + Duration::from_secs(1);
assert_eq!(texts(&throttle.admit(A, later, line(Level::WARN, "slow 3"))), ["slow 2 repeated=1 window=60s"]);
assert_eq!(texts(&throttle.drain()), ["slow 3 repeated=1 window=60s"]);
}
#[test]
fn keys_tell_events_apart_and_the_table_is_bounded() {
let mut throttle = Throttle::new(REPEAT_WINDOW, 2);
let t0 = Instant::now();
assert_eq!(texts(&throttle.admit(A, t0, line(Level::WARN, "a 1"))), ["a 1"]);
assert!(throttle.admit(A, t0, line(Level::WARN, "a 2")).is_empty());
assert_eq!(texts(&throttle.admit(B, t0, line(Level::WARN, "b 1"))), ["b 1"]);
assert_eq!(texts(&throttle.admit(C, t0, line(Level::ERROR, "c 1"))), ["a 2 repeated=1 window=60s", "c 1"]);
assert_eq!(throttle.tracked(), 2);
}
#[test]
fn the_layer_writes_the_format_and_bounds_repeats() {
let written = Arc::new(Mutex::new(Vec::<String>::new()));
let sink = Arc::clone(&written);
let log = Arc::new(HostLog::new(Box::new(move |l| sink.lock().unwrap().push(l.to_owned()))));
let subscriber = tracing_subscriber::registry().with(HostLayer(Arc::clone(&log)));
tracing::subscriber::with_default(subscriber, || {
tracing::info!(monitor = ?Some(1), name = "DISPLAY 1", "starting screen host");
for count in 0..3 {
tracing::warn!(reason = "MFT busy", count, "hardware H.264 encoder failed; using software");
}
});
log.flush();
let lines = written.lock().unwrap().clone();
assert_eq!(lines.len(), 3, "{lines:?}");
assert!(
lines[0].ends_with("] - [ScreenHost] - [INFO] - starting screen host monitor=Some(1) name=\"DISPLAY 1\""),
"{}",
lines[0]
);
assert!(lines[0].starts_with('['));
assert!(
lines[1].ends_with(
"] - [ScreenHost] - [WARN] - hardware H.264 encoder failed; using software reason=\"MFT busy\" count=0"
),
"{}",
lines[1]
);
assert!(lines[2].ends_with(" reason=\"MFT busy\" count=2 repeated=2 window=60s"), "{}", lines[2]);
}
}
+2
View File
@@ -42,6 +42,7 @@ fn main() -> ExitCode {
Command::Probe { log_level } => {
executer_screen::init_logging(log_level);
let report = platform::probe();
executer_screen::flush_logging();
match serde_json::to_string(&report) {
Ok(json) => println!("{json}"),
Err(e) => {
@@ -54,6 +55,7 @@ fn main() -> ExitCode {
Command::Serve(args) => {
executer_screen::init_logging(args.log_level);
let code = serve(&args);
executer_screen::flush_logging();
// Exit right away: a blocking stdin read must not keep the process alive.
std::process::exit(i32::from(code));
}
+11
View File
@@ -38,6 +38,8 @@ public static class ApiRoutes
public const string AgentDownload = "/api/downloads/agent/{fileName}";
public const string Devices = "/api/devices";
/// <summary>POST: restart or shut down devices and groups (<see cref="PowerRequest"/>).</summary>
public const string Power = "/api/power";
public const string Device = "/api/devices/{clientId}";
public const string DeviceInventory = "/api/devices/{clientId}/inventory";
public const string DeviceHistory = "/api/devices/{clientId}/history";
@@ -110,6 +112,13 @@ public static class ApiRoutes
/// <summary>POST: move function modules into a folder.</summary>
public const string FunctionModulesMove = "/api/functions/move";
/// <summary>GET: the built-in snippets and the library's own. POST: create one.</summary>
public const string Snippets = "/api/snippets";
/// <summary>GET, PUT, DELETE one snippet (a built-in can be read only).</summary>
public const string Snippet = "/api/snippets/{id:guid}";
/// <summary>POST: copy a snippet (a built-in too) into a new one of the library's own.</summary>
public const string SnippetCopy = "/api/snippets/{id:guid}/copy";
public const string Sequences = "/api/sequences";
public const string Sequence = "/api/sequences/{id:guid}";
/// <summary>GET: every folder path. POST: create one. DELETE (?path=): delete an empty one.</summary>
@@ -307,6 +316,8 @@ public static class ApiRoutes
public static string ServerLogFile(string name) => $"/api/logs/server/files/{Uri.EscapeDataString(name)}";
public static string Script(Guid id) => $"/api/scripts/{id:D}";
public static string FunctionModule(Guid id) => $"/api/functions/{id:D}";
public static string Snippet(Guid id) => $"/api/snippets/{id:D}";
public static string SnippetCopy(Guid id) => $"/api/snippets/{id:D}/copy";
public static string Sequence(Guid id) => $"/api/sequences/{id:D}";
public static string SequenceRun(Guid id) => $"/api/sequence-runs/{id:D}";
public static string SequenceRunCancel(Guid id) => $"/api/sequence-runs/{id:D}/cancel";
+38 -4
View File
@@ -348,7 +348,9 @@ public sealed record ScriptDto(
bool SetWorkingDirectory = false,
RestartAfterRun RestartAfterRun = RestartAfterRun.Off,
int RestartDelaySeconds = 0,
int RestartWarningSeconds = 0);
int RestartWarningSeconds = 0,
bool RunAsUser = false,
bool RunAsEachUser = false);
/// <summary>
/// POST/PUT /api/scripts request body. <c>Folder</c> places the script ("/"
@@ -358,6 +360,9 @@ public sealed record ScriptDto(
/// (0 to <see cref="RestartOptions.MaxDelaySeconds"/>) and <c>RestartWarningSeconds</c> (Warn
/// Signed-In Users: 0 for off, otherwise <see cref="RestartOptions.MinWarningSeconds"/> to
/// <see cref="RestartOptions.MaxWarningSeconds"/>) left out keep theirs too (off, 0 and off).
/// <c>RunAsUser</c> (run as the signed-in user instead of the agent's account) left out keeps
/// the stored value (off for a new script); so does <c>RunAsEachUser</c> (once per signed-in
/// user; turns RunAsUser on).
/// </summary>
public sealed record SaveScriptRequest(
string Name,
@@ -378,7 +383,9 @@ public sealed record SaveScriptRequest(
bool? SetWorkingDirectory = null,
RestartAfterRun? RestartAfterRun = null,
int? RestartDelaySeconds = null,
int? RestartWarningSeconds = null);
int? RestartWarningSeconds = null,
bool? RunAsUser = null,
bool? RunAsEachUser = null);
/// <summary>A folder of a library (scripts, functions).</summary>
public sealed record FolderDto(string Path, string Name);
@@ -580,6 +587,26 @@ public sealed record CreateJobRequest(
Guid? SequenceId = null,
int? RestartWarningSeconds = null);
/// <summary>
/// POST /api/power request body: restart or shut down devices and groups' members, as a run of
/// the built-in <see cref="PowerActions"/> script. Targets, exclusions, <c>OnlineOnly</c> and the
/// spread (<c>StaggerSeconds</c>, <c>StaggerBatchSize</c>) are as a script's run; <c>DelaySeconds</c>
/// and <c>WarningSeconds</c> as Restart After Run's. <c>InstallUpdates</c> (Windows) lets the
/// restart or shutdown install pending updates; off, they wait. Answers with a <see cref="GroupRunDto"/>.
/// </summary>
public sealed record PowerRequest(
PowerAction Action,
IReadOnlyList<string>? ClientIds = null,
IReadOnlyList<Guid>? GroupIds = null,
int DelaySeconds = 0,
int WarningSeconds = 0,
bool InstallUpdates = false,
bool OnlineOnly = false,
int StaggerSeconds = 0,
int StaggerBatchSize = 1,
IReadOnlyList<string>? ExcludeClientIds = null,
IReadOnlyList<Guid>? ExcludeGroupIds = null);
/// <summary>
/// POST /api/executions/{runId}/output/archive request body: the run's jobs to
/// include (null or empty = every job), with or without line timestamps.
@@ -608,12 +635,19 @@ public sealed record JobOutputRecordDto(
DateTimeOffset TimestampUtc,
string Text);
/// <summary>POST /api/devices/{clientId}/shell request body; <c>Shell</c> is a <see cref="ShellKinds"/> value (null = automatic).</summary>
/// <summary>
/// POST /api/devices/{clientId}/shell request body; <c>Shell</c> is a <see cref="ShellKinds"/> value (null = automatic).
/// <c>AsUser</c> starts it as the device's signed-in user instead of the agent's account;
/// <c>User</c> names which of them (one the agent listed as signed in; null = the console's user,
/// else the only one).
/// </summary>
public sealed record CreateShellRequest(
string BrowserSessionId,
int Cols,
int Rows,
string? Shell = null);
string? Shell = null,
bool AsUser = false,
string? User = null);
/// <summary>POST /api/devices/{clientId}/shell response body.</summary>
public sealed record CreateShellResponse(
+31
View File
@@ -0,0 +1,31 @@
using Shared.Contracts.Models;
namespace Shared.Contracts.Api;
/// <summary>
/// A snippet of the shared library. <see cref="Content"/> marks tab stops as <c>${1:default}</c>,
/// <c>${1}</c> or <c>${1|first,second|}</c> (a choice); every other character is code, and
/// <c>$${</c> types a literal <c>${</c>. A <see cref="BuiltIn"/> snippet ships with the server:
/// it can be read and copied, never changed; it has no times or authors.
/// </summary>
public sealed record SnippetDto(
Guid Id,
string Name,
string? Description,
ScriptEngine Language,
string Content,
bool BuiltIn,
DateTimeOffset? CreatedUtc = null,
string? CreatedBy = null,
DateTimeOffset? UpdatedUtc = null,
string? UpdatedBy = null);
/// <summary>Creates or replaces a snippet of the library's own.</summary>
public sealed record SaveSnippetRequest(
string Name,
string? Description,
ScriptEngine Language,
string? Content);
/// <summary>Copies a snippet; the copy is named <see cref="Name"/>, else after the original.</summary>
public sealed record CopySnippetRequest(string? Name = null);
+30 -7
View File
@@ -101,6 +101,12 @@ public sealed record ScriptFileDelivery(
/// <see cref="RestartOptions.MinWarningSeconds"/> to <see cref="RestartOptions.MaxWarningSeconds"/>)
/// is the system's warning to signed-in users when the restart comes due and someone is signed
/// in. Older agents ignore it and hand the delay to the system as its grace period.
/// <see cref="RunAsUser"/> runs the script as the device's signed-in user (out of process,
/// whatever the engine); the server never sends it to agents older than
/// <see cref="Shared.Contracts.Models.RunAsUser.MinimumAgentVersion"/>, which would ignore it.
/// <see cref="RunAsEachUser"/> (with RunAsUser) runs it once for each signed-in user, one after
/// another; never sent to agents older than
/// <see cref="Shared.Contracts.Models.RunAsUser.EachUserMinimumAgentVersion"/>.
/// </summary>
public sealed record ScriptCommandPayload(
Guid JobId,
@@ -125,11 +131,17 @@ public sealed record ScriptCommandPayload(
JobTrigger? Trigger = null,
RestartAfterRun RestartAfterRun = RestartAfterRun.Off,
int RestartDelaySeconds = 0,
int RestartWarningSeconds = 0)
int RestartWarningSeconds = 0,
bool RunAsUser = false,
bool RunAsEachUser = false,
// What Restart After Run does (an older agent restarts: the server never sends it ShutDown).
PowerAction RestartAction = PowerAction.Restart,
// Windows: the restart or shutdown installs pending updates (off: they wait).
bool RestartInstallsUpdates = false)
{
/// <summary>The command's Restart After Run as one record.</summary>
[System.Text.Json.Serialization.JsonIgnore]
public RestartSettings Restart => new(RestartAfterRun, RestartDelaySeconds, RestartWarningSeconds);
public RestartSettings Restart => new(RestartAfterRun, RestartDelaySeconds, RestartWarningSeconds, RestartAction, RestartInstallsUpdates);
}
/// <summary>
@@ -271,7 +283,8 @@ public sealed record JobStatePayload(
int? RestartDelaySeconds = null,
string? RestartMessage = null,
DateTimeOffset? RestartBootUtc = null,
DateTimeOffset? RestartDueUtc = null);
DateTimeOffset? RestartDueUtc = null,
IReadOnlyList<GroupMembershipReport>? GroupMemberships = null);
/// <summary>
/// A job's restart: a request on the agent event subject (<see cref="MessageTypes.AgentJobRestart"/>),
@@ -331,13 +344,18 @@ public sealed record RestartCancelCommandPayload(Guid JobId, string Message, str
/// <summary>
/// Opens a remote shell; sent on <c>agent.&lt;clientId&gt;.command.shell.open</c>.
/// <c>Shell</c> is a <see cref="ShellKinds"/> value (null = automatic); unix
/// agents, and agents that predate it, ignore it.
/// agents, and agents that predate it, ignore it. <c>AsUser</c> starts the shell as the
/// signed-in user; the server refuses it for agents older than
/// <see cref="Shared.Contracts.Models.RunAsUser.MinimumAgentVersion"/>. <c>User</c> picks which
/// signed-in user (refused unless they are signed in); null applies the usual rule.
/// </summary>
public sealed record ShellOpenCommandPayload(
Guid SessionId,
int Cols,
int Rows,
string? Shell = null);
string? Shell = null,
bool AsUser = false,
string? User = null);
/// <summary>Terminal input bytes (base64) for an open shell session.</summary>
public sealed record ShellInputPayload(
@@ -363,13 +381,18 @@ public sealed record ShellOutputPayload(
/// <summary>
/// Shell session state on <c>agent.&lt;clientId&gt;.shell.&lt;sessionId&gt;.state</c>.
/// <c>Shell</c> is the <see cref="ShellKinds"/> value started (Windows agents, on <c>Open</c>).
/// <c>Shell</c> is the <see cref="ShellKinds"/> value started (Windows agents, on <c>Open</c>);
/// <c>User</c> the account it runs as when started as the signed-in user. <c>SignedInUsers</c>
/// lists who is signed in on the device (on <c>Open</c>, and on a <c>Failed</c> run-as-user open),
/// for the console to offer.
/// </summary>
public sealed record ShellStatePayload(
Guid SessionId,
ShellSessionState State,
string? Message,
string? Shell = null);
string? Shell = null,
string? User = null,
IReadOnlyList<string>? SignedInUsers = null);
/// <summary>System event: a device enrolled.</summary>
public sealed record AgentEnrolledEvent(
+37 -2
View File
@@ -2,16 +2,51 @@ namespace Shared.Contracts.Models;
/// <summary>
/// Static groups hold an explicit member list; dynamic groups evaluate rules;
/// folders hold no devices of their own and only organize nested groups.
/// Every kind also includes the devices of the groups nested under it.
/// folders hold no devices of their own and only organize nested groups;
/// script groups hold the devices whose scripts last reported them members
/// (<see cref="ScriptGroups"/>). Every kind also includes the devices of the
/// groups nested under it.
/// </summary>
public enum GroupKind
{
Static,
Dynamic,
Folder,
Script,
}
/// <summary>
/// Script groups: a script on the device says whether the device belongs (the built-in
/// <c>Set-ExecuteRGroupMembership</c>, or <c>executer_group</c> in Bash), the agent sends that with
/// the job's final state, and the server adds or removes the device, creating the group the first
/// time a device joins it. Each run says it again, so membership follows the device.
/// </summary>
public static class ScriptGroups
{
/// <summary>The line the built-ins write; the agent takes it out of the output.</summary>
public const string Marker = "::executer-group::";
/// <summary>The most groups one job may report on (the rest are ignored).</summary>
public const int MaxReportsPerJob = 25;
public const int MaxNameLength = 100;
/// <summary>Kinds whose members are rows (static, script), not rules.</summary>
public static bool HasMemberRows(GroupKind kind) => kind is GroupKind.Static or GroupKind.Script;
/// <summary>A usable group name (trimmed, no control characters or slashes, 1 to 100 long), or null.</summary>
public static string? Normalize(string? name)
{
var trimmed = name?.Trim();
return string.IsNullOrEmpty(trimmed) || trimmed.Length > MaxNameLength || trimmed.Any(c => char.IsControl(c) || c is '/' or '\\')
? null
: trimmed;
}
}
/// <summary>A device's own report that it belongs (or no longer belongs) in the named script group.</summary>
public sealed record GroupMembershipReport(string Group, bool Member);
/// <summary>How sibling conditions (or sibling groups) combine.</summary>
public enum RuleCombine
{
@@ -0,0 +1,54 @@
namespace Shared.Contracts.Models;
/// <summary>What a device does when its Restart After Run comes due.</summary>
public enum PowerAction
{
/// <summary>Restart (the default, and all an older agent knows).</summary>
Restart,
/// <summary>Shut down and power off.</summary>
ShutDown,
}
/// <summary>
/// Restart and Shut Down from the console: a run of a built-in script that does nothing, with
/// Restart After Run on (Always), so a power action is a job like any other: it has a run, a
/// spread, a delay the console can cancel, the warning for signed-in users and the device's
/// AllowRestart. The built-in scripts are never stored; their ids name them in jobs and runs.
/// Shutting down, and installing pending Windows updates on the way, need
/// <see cref="MinimumAgentVersion"/>: an older agent would restart, and skip the updates.
/// </summary>
public static class PowerActions
{
public static readonly Guid RestartScriptId = new("7e57a7e0-0000-4000-8000-000000000001");
public static readonly Guid ShutDownScriptId = new("7e57a7e0-0000-4000-8000-000000000002");
public const string RestartName = "Restart";
public const string ShutDownName = "Shut Down";
/// <summary>The first agent version that shuts down, and installs updates when asked.</summary>
public const string MinimumAgentVersion = "1.14.0";
/// <summary>The power action a built-in script id names, or null for any other script.</summary>
public static PowerAction? Of(Guid scriptId)
=> scriptId == RestartScriptId ? PowerAction.Restart
: scriptId == ShutDownScriptId ? PowerAction.ShutDown
: null;
public static Guid ScriptIdOf(PowerAction action) => action == PowerAction.ShutDown ? ShutDownScriptId : RestartScriptId;
public static string NameOf(PowerAction action) => action == PowerAction.ShutDown ? ShutDownName : RestartName;
/// <summary>True when the options need an agent of <see cref="MinimumAgentVersion"/> or later.</summary>
public static bool NeedsCurrentAgent(PowerAction action, bool installUpdates) => action == PowerAction.ShutDown || installUpdates;
/// <summary>Why an agent at <paramref name="agentVersion"/> cannot honor the options, or null.</summary>
public static string? Refusal(PowerAction action, bool installUpdates, string? agentVersion)
=> !NeedsCurrentAgent(action, installUpdates) || AgentVersions.Compare(agentVersion, MinimumAgentVersion) >= 0
? null
: $"The agent ({(string.IsNullOrWhiteSpace(agentVersion) ? "unknown version" : agentVersion)}) cannot "
+ (action == PowerAction.ShutDown ? "shut down" : "install updates on restart")
+ $"; upgrade it to {MinimumAgentVersion} or later.";
}
+5 -1
View File
@@ -64,7 +64,11 @@ public enum JobRestartState
public sealed record RestartSettings(
RestartAfterRun Mode = RestartAfterRun.Off,
int DelaySeconds = 0,
int WarningSeconds = 0)
int WarningSeconds = 0,
// Shut down instead of restarting (Restart and Shut Down from the console).
PowerAction Action = PowerAction.Restart,
// Windows: install pending updates on the way down; off, they wait.
bool InstallUpdates = false)
{
/// <summary>Never restarts.</summary>
public static RestartSettings Off { get; } = new();
+29
View File
@@ -0,0 +1,29 @@
namespace Shared.Contracts.Models;
/// <summary>
/// Running a shell or a script as the device's signed-in user instead of the agent's own
/// account (LocalSystem, root). Agents older than <see cref="MinimumAgentVersion"/> ignore the
/// request and would run as the agent's account, so the server refuses it for them.
/// </summary>
public static class RunAsUser
{
/// <summary>The first agent version that honors the request.</summary>
public const string MinimumAgentVersion = "1.13.0";
/// <summary>True when an agent at <paramref name="agentVersion"/> honors the request.</summary>
public static bool Supported(string? agentVersion) => AgentVersions.Compare(agentVersion, MinimumAgentVersion) >= 0;
/// <summary>The first agent version that runs a script once for each signed-in user.</summary>
public const string EachUserMinimumAgentVersion = "1.14.0";
/// <summary>True when an agent at <paramref name="agentVersion"/> honors Each Signed-In User.</summary>
public static bool EachUserSupported(string? agentVersion) => AgentVersions.Compare(agentVersion, EachUserMinimumAgentVersion) >= 0;
/// <summary>Why an agent at <paramref name="agentVersion"/> cannot run a script for each signed-in user.</summary>
public static string EachUserUnsupported(string? agentVersion) =>
$"The agent ({(string.IsNullOrWhiteSpace(agentVersion) ? "unknown version" : agentVersion)}) cannot run for each signed-in user; upgrade it to {EachUserMinimumAgentVersion} or later.";
/// <summary>Why an agent at <paramref name="agentVersion"/> cannot run as the signed-in user.</summary>
public static string Unsupported(string? agentVersion) =>
$"The agent ({(string.IsNullOrWhiteSpace(agentVersion) ? "unknown version" : agentVersion)}) cannot run as the signed-in user; upgrade it to {MinimumAgentVersion} or later.";
}
@@ -1,25 +1,24 @@
using System.Globalization;
using Serilog.Core;
using Serilog.Events;
using Serilog.Formatting.Display;
using Shared.Contracts.Api;
namespace Shared.Infrastructure.Logging;
/// <summary>Feeds every event the logger writes into a <see cref="LiveLog"/>, rendered as the log file renders it.</summary>
public sealed class LiveLogSink(LiveLog live) : ILogEventSink
/// <summary>
/// Feeds every event the logger writes into a <see cref="LiveLog"/>, rendered as the log file
/// renders it (the message, then its unused properties as <c>key=value</c>). The source is the
/// full SourceContext, or the application when there is none; a viewer shortens it to the
/// category as <see cref="LogLineFormatter.Category(string?, string)"/> does.
/// </summary>
public sealed class LiveLogSink(LiveLog live, string? application = null) : ILogEventSink
{
private static readonly MessageTemplateTextFormatter Message = new("{Message:lj}", CultureInfo.InvariantCulture);
public void Emit(LogEvent logEvent)
{
using var text = new StringWriter(CultureInfo.InvariantCulture);
Message.Format(logEvent, text);
live.Append(
logEvent.Timestamp.ToUniversalTime(),
LevelName(logEvent.Level),
logEvent.Properties.TryGetValue("SourceContext", out var source) && source is ScalarValue { Value: string name } ? name : null,
text.ToString(),
LogLineFormatter.SourceContext(logEvent) ?? application,
LogLineFormatter.RenderMessage(logEvent),
logEvent.Exception?.ToString());
}
@@ -0,0 +1,259 @@
using System.Globalization;
using System.Text;
using System.Text.RegularExpressions;
using Serilog.Events;
using Serilog.Formatting;
using Serilog.Formatting.Json;
using Shared.Contracts.Api;
namespace Shared.Infrastructure.Logging;
/// <summary>
/// ExecuteR's one text log format, for every line any of its processes writes:
/// <c>[2026-11-16T17:53:40.653Z] - [Category] - [LEVEL] - message key=value …</c>.
/// The time is UTC to the millisecond; the category is a short component name (the
/// logging type without its namespace); the level is TRACE, DEBUG, INFO, WARN, ERROR or
/// FATAL; the message is rendered with its strings unquoted, followed by the event's
/// properties the message did not use, as <c>key=value</c> (correlation fields among
/// them; enrichment noise left out). An exception follows on the next lines.
/// </summary>
public sealed partial class LogLineFormatter(string application) : ITextFormatter
{
/// <summary>The timestamp as written: UTC, ISO 8601, milliseconds, Z.</summary>
public const string TimestampFormat = "yyyy-MM-dd'T'HH:mm:ss.fff'Z'";
/// <summary>Properties that say nothing a reader of one line needs (the file already names its machine and process).</summary>
public static readonly IReadOnlySet<string> Unlisted = new HashSet<string>(StringComparer.Ordinal)
{
"SourceContext", "MachineName", "Application", "EventId",
"RequestId", "RequestPath", "ConnectionId", "ActionId", "ActionName",
"SpanId", "TraceId", "ParentId", "Scope", "ThreadId", "ProcessId",
};
private static readonly JsonValueFormatter Json = new(typeTagName: null);
public void Format(LogEvent logEvent, TextWriter output)
{
WriteLine(
output,
logEvent.Timestamp,
Category(logEvent, application),
LevelName(logEvent.Level),
RenderMessage(logEvent));
if (logEvent.Exception is not null)
{
output.Write(logEvent.Exception.ToString());
output.Write(Environment.NewLine);
}
}
/// <summary>One whole line, its newline included.</summary>
public static void WriteLine(TextWriter output, DateTimeOffset timestamp, string category, string level, string message)
{
output.Write('[');
output.Write(timestamp.UtcDateTime.ToString(TimestampFormat, CultureInfo.InvariantCulture));
output.Write("] - [");
output.Write(category);
output.Write("] - [");
output.Write(level);
output.Write("] - ");
output.Write(message);
output.Write(Environment.NewLine);
}
/// <summary>One whole line, without its newline.</summary>
public static string Line(DateTimeOffset timestamp, string category, string level, string message)
{
using var text = new StringWriter(CultureInfo.InvariantCulture);
WriteLine(text, timestamp, category, level, message);
return text.ToString().TrimEnd('\r', '\n');
}
/// <summary>The level as the line spells it.</summary>
public static string LevelName(LogEventLevel level) => level switch
{
LogEventLevel.Verbose => "TRACE",
LogEventLevel.Debug => "DEBUG",
LogEventLevel.Information => "INFO",
LogEventLevel.Warning => "WARN",
LogEventLevel.Error => "ERROR",
_ => "FATAL",
};
/// <summary>The level as the line spells it, from a <see cref="LogLevels"/> name.</summary>
public static string LevelName(string level) => level switch
{
LogLevels.Verbose => "TRACE",
LogLevels.Debug => "DEBUG",
LogLevels.Warning => "WARN",
LogLevels.Error => "ERROR",
LogLevels.Fatal => "FATAL",
_ => "INFO",
};
/// <summary>The event's category: its SourceContext shortened, or the application.</summary>
public static string Category(LogEvent logEvent, string application)
=> Category(SourceContext(logEvent), application);
/// <summary>
/// A short component name from a logger's category: the type name without its
/// namespace or generic arguments, a nested type as <c>Outer.Inner</c>
/// (<c>Agent.Screen.ScreenHost+Session</c> is <c>ScreenHost.Session</c>). Nothing → <paramref name="fallback"/>.
/// </summary>
public static string Category(string? sourceContext, string fallback)
{
if (string.IsNullOrWhiteSpace(sourceContext))
{
return fallback;
}
var name = sourceContext.Trim();
var generic = name.IndexOfAny(['[', '<']);
if (generic > 0)
{
name = name[..generic];
}
name = Arity().Replace(name, string.Empty);
var parts = name.Split('+', StringSplitOptions.RemoveEmptyEntries);
if (parts.Length == 0)
{
return fallback;
}
parts[0] = parts[0][(parts[0].LastIndexOf('.') + 1)..];
var category = string.Join('.', parts.Where(p => p.Length > 0));
return category.Length > 0 ? category : fallback;
}
/// <summary>The SourceContext of an event, when it has one.</summary>
public static string? SourceContext(LogEvent logEvent)
=> logEvent.Properties.TryGetValue("SourceContext", out var source) && source is ScalarValue { Value: string name } ? name : null;
/// <summary>The message as rendered, then the properties it did not use as <c>key=value</c>.</summary>
public static string RenderMessage(LogEvent logEvent)
{
using var text = new StringWriter(CultureInfo.InvariantCulture);
WriteMessage(logEvent, text);
AppendProperties(logEvent, text);
return text.ToString();
}
/// <summary>
/// The message as <c>{Message:lj}</c> renders it (strings bare, structures as JSON), except
/// that other scalars are bare too: a Guid or a time reads as itself, not as a JSON string.
/// </summary>
public static void WriteMessage(LogEvent logEvent, TextWriter output)
{
foreach (var token in logEvent.MessageTemplate.Tokens)
{
if (token is not Serilog.Parsing.PropertyToken property)
{
token.Render(logEvent.Properties, output, CultureInfo.InvariantCulture);
}
else if (!logEvent.Properties.TryGetValue(property.PropertyName, out var value))
{
output.Write(property.ToString());
}
else if (value is ScalarValue { Value: string text })
{
output.Write(text);
}
else if (value is ScalarValue scalar)
{
scalar.Render(output, property.Format, CultureInfo.InvariantCulture);
}
else
{
Json.Format(value, output);
}
}
}
/// <summary>Writes <c> key=value</c> for each property of the event its message template does not name.</summary>
public static void AppendProperties(LogEvent logEvent, TextWriter output)
{
HashSet<string>? used = null;
foreach (var token in logEvent.MessageTemplate.Tokens)
{
if (token is Serilog.Parsing.PropertyToken property)
{
(used ??= new HashSet<string>(StringComparer.Ordinal)).Add(property.PropertyName);
}
}
foreach (var (name, value) in logEvent.Properties)
{
if (Unlisted.Contains(name) || (used?.Contains(name) ?? false))
{
continue;
}
output.Write(' ');
output.Write(name);
output.Write('=');
output.Write(Value(value));
}
}
/// <summary>A property value as a line shows it: bare, or double-quoted when it holds whitespace, '=' or '"'.</summary>
public static string Value(LogEventPropertyValue value)
{
var text = value switch
{
ScalarValue { Value: null } => "null",
ScalarValue { Value: string s } => Quote(s),
ScalarValue { Value: bool b } => b ? "true" : "false",
ScalarValue { Value: DateTimeOffset d } => d.ToString("O", CultureInfo.InvariantCulture),
ScalarValue { Value: DateTime d } => d.ToString("O", CultureInfo.InvariantCulture),
ScalarValue { Value: IFormattable f } => Quote(f.ToString(null, CultureInfo.InvariantCulture)),
ScalarValue { Value: var v } => Quote(v.ToString() ?? string.Empty),
_ => Quote(JsonText(value)),
};
return text;
}
/// <summary>Double-quotes a value that holds whitespace, '=' or '"' (or is empty), escaping quotes and control characters.</summary>
public static string Quote(string value)
{
if (value.Length > 0 && !value.Any(c => char.IsWhiteSpace(c) || c == '=' || c == '"' || char.IsControl(c)))
{
return value;
}
var quoted = new StringBuilder(value.Length + 2).Append('"');
foreach (var c in value)
{
switch (c)
{
case '"': quoted.Append("\\\""); break;
case '\n': quoted.Append("\\n"); break;
case '\r': quoted.Append("\\r"); break;
case '\t': quoted.Append("\\t"); break;
default:
if (char.IsControl(c))
{
quoted.Append(CultureInfo.InvariantCulture, $"\\u{(int)c:x4}");
}
else
{
quoted.Append(c);
}
break;
}
}
return quoted.Append('"').ToString();
}
private static string JsonText(LogEventPropertyValue value)
{
using var text = new StringWriter(CultureInfo.InvariantCulture);
Json.Format(value, text);
return text.ToString();
}
[GeneratedRegex(@"`\d+")]
private static partial Regex Arity();
}
@@ -0,0 +1,110 @@
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Text.RegularExpressions;
using Shared.Contracts.Api;
namespace Shared.Infrastructure.Logging;
/// <summary>One log line read back: when, how severe (a <see cref="LogLevels"/> name), from which component, and what.</summary>
public sealed record ParsedLogLine(DateTimeOffset TimestampUtc, string Level, string? Category, string Message);
/// <summary>
/// Reads a text log line back into its parts. Takes ExecuteR's format
/// (<c>[2026-11-16T17:53:40.653Z] - [Category] - [INFO] - message</c>, see
/// <see cref="LogLineFormatter"/>) and what was written before it, still in files on
/// devices: the services' <c>[2026-11-06 12:00:00.000 INF] Source: message</c> (local
/// time), the watchdog's <c>2026-11-06 12:00:00.000Z [INF] message</c>, and a screen
/// host's <c>2026-11-06T12:00:00.000000Z WARN target: message</c>.
/// </summary>
public static partial class LogLineParser
{
public static bool TryParse(string? line, [NotNullWhen(true)] out ParsedLogLine? parsed)
{
parsed = null;
if (string.IsNullOrEmpty(line))
{
return false;
}
if (Current().Match(line) is { Success: true } current)
{
var category = current.Groups["category"].Value;
parsed = new ParsedLogLine(
Utc(current.Groups["time"].Value, "yyyy-MM-dd'T'HH:mm:ss.FFFFFFF'Z'", DateTimeStyles.AssumeUniversal),
Level(current.Groups["level"].Value),
category.Length > 0 ? category : null,
current.Groups["message"].Value);
return true;
}
if (Service().Match(line) is { Success: true } service)
{
var source = service.Groups["source"];
parsed = new ParsedLogLine(
Utc(service.Groups["time"].Value, "yyyy-MM-dd HH:mm:ss.fff", DateTimeStyles.AssumeLocal),
Level(service.Groups["level"].Value),
source.Success && source.Value.Length > 0 ? source.Value : null,
service.Groups["message"].Value);
return true;
}
if (Watchdog().Match(line) is { Success: true } watchdog)
{
parsed = new ParsedLogLine(
Utc(watchdog.Groups["time"].Value, "yyyy-MM-dd HH:mm:ss.fff", DateTimeStyles.AssumeUniversal),
Level(watchdog.Groups["level"].Value),
null,
watchdog.Groups["message"].Value);
return true;
}
if (Tracing().Match(line) is { Success: true } tracing)
{
parsed = new ParsedLogLine(
Utc(tracing.Groups["time"].Value, "yyyy-MM-dd'T'HH:mm:ss.FFFFFFF'Z'", DateTimeStyles.AssumeUniversal),
Level(tracing.Groups["level"].Value),
tracing.Groups["source"].Value,
tracing.Groups["message"].Value);
return true;
}
return false;
}
/// <summary>A <see cref="LogLevels"/> name from any level spelling a line may carry.</summary>
public static string Level(string level) => level.ToUpperInvariant() switch
{
"TRACE" or "VRB" or "VERBOSE" => LogLevels.Verbose,
"DEBUG" or "DBG" => LogLevels.Debug,
"WARN" or "WRN" or "WARNING" => LogLevels.Warning,
"ERROR" or "ERR" => LogLevels.Error,
"FATAL" or "FTL" => LogLevels.Fatal,
_ => LogLevels.Information,
};
private static DateTimeOffset Utc(string text, string format, DateTimeStyles style)
{
// At most 7 fractional digits parse; a screen host writes up to 9.
var dot = text.IndexOf('.', StringComparison.Ordinal);
if (dot > 0 && text.EndsWith('Z') && text.Length - dot - 2 > 7)
{
text = string.Concat(text.AsSpan(0, dot + 8), "Z");
}
return DateTimeOffset.TryParseExact(text, format, CultureInfo.InvariantCulture, style | DateTimeStyles.AdjustToUniversal, out var time)
? time.ToUniversalTime()
: DateTimeOffset.UtcNow;
}
[GeneratedRegex(@"^\[(?<time>\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,7})?Z)\] - \[(?<category>[^\]]*)\] - \[(?<level>[A-Z]{4,5})\] - ?(?<message>.*)$")]
private static partial Regex Current();
[GeneratedRegex(@"^\[(?<time>\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}\.\d{3}) (?<level>[A-Z]{3})\] (?:(?<source>\S*?): )?(?<message>.*)$")]
private static partial Regex Service();
[GeneratedRegex(@"^(?<time>\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}\.\d{3})Z \[(?<level>[A-Z]{3})\] (?<message>.*)$")]
private static partial Regex Watchdog();
[GeneratedRegex(@"^(?<time>\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?Z)\s+(?<level>TRACE|DEBUG|INFO|WARN|ERROR) (?<source>[A-Za-z0-9_:]+): (?<message>.*)$")]
private static partial Regex Tracing();
}
@@ -1,59 +1,48 @@
using Serilog;
using Serilog.Core;
using Serilog.Events;
using Serilog.Formatting;
using Serilog.Formatting.Compact;
namespace Shared.Infrastructure.Logging;
/// <summary>
/// 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.
/// JSON) plus a daily rolling file with size caps and retention. Text lines are
/// ExecuteR's one format (<see cref="LogLineFormatter"/>):
/// <c>[2026-11-16T17:53:40.653Z] - [Category] - [INFO] - message key=value</c>.
/// Correlation fields (CorrelationId, ClientId, JobId, ShellSessionId,
/// BrowserSessionId, RemoteIp) flow through as structured properties from log
/// scopes and show as <c>key=value</c>. A warning or error that repeats is written
/// once and then counted (<see cref="RepeatThrottleSink"/>).
/// Secret material is never logged — see <see cref="Redaction"/>.
/// </summary>
public static class LoggingSetup
{
/// <summary>Human-readable console/file template including correlation context.</summary>
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}";
/// <summary>
/// The pipeline for <paramref name="application"/>. With <paramref name="live"/>, every
/// event written also lands in that in-memory ring, for the console's live log views.
/// The pipeline for <paramref name="application"/> (also the category of a line
/// without a SourceContext: <c>Agent</c>, <c>Server</c>). With <paramref name="live"/>,
/// every event written also lands in that in-memory ring, for the console's live log
/// views. Events pass the level filter, the enrichers (redaction last) and the repeat
/// throttle before any sink sees them.
/// </summary>
public static Logger CreateLogger(LogSettings settings, string application, LiveLog? live = null)
public static Logger CreateLogger(LogSettings settings, string application, LiveLog? live = null, TimeProvider? clock = null)
{
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)
// Last, so it also sees what log scopes added.
.Enrich.With<RedactionEnricher>();
var sinks = new LoggerConfiguration().MinimumLevel.Verbose();
var text = new LogLineFormatter(application);
if (live is not null)
{
configuration.WriteTo.Sink(new LiveLogSink(live));
sinks.WriteTo.Sink(new LiveLogSink(live, application));
}
if (settings.Json)
{
configuration.WriteTo.Console(new CompactJsonFormatter());
sinks.WriteTo.Console(new CompactJsonFormatter());
}
else
{
configuration.WriteTo.Console(outputTemplate: SimpleTemplate);
sinks.WriteTo.Console(text);
}
if (settings.FileEnabled)
@@ -67,28 +56,14 @@ public static class LoggingSetup
{
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);
}
sinks.WriteTo.File(
settings.Json ? new CompactJsonFormatter() : (ITextFormatter)text,
path,
rollingInterval: RollingInterval.Day,
rollOnFileSizeLimit: true,
fileSizeLimitBytes: settings.FileSizeLimitBytes,
retainedFileCountLimit: settings.RetainedFileCount,
shared: true);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
@@ -98,7 +73,24 @@ public static class LoggingSetup
}
}
return configuration.CreateLogger();
// The sinks sit behind the repeat throttle, which is behind the filters and
// enrichers: what is counted is already redacted, and disposing the logger
// writes any count still open before the sinks close.
var throttle = new RepeatThrottleSink(sinks.CreateLogger(), clock);
return 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)
// Last, so it also sees what log scopes added.
.Enrich.With<RedactionEnricher>()
.WriteTo.Sink(throttle)
.CreateLogger();
}
private static LogEventLevel ParseLevel(string level)
@@ -0,0 +1,286 @@
using System.Globalization;
using Serilog.Core;
using Serilog.Events;
using Serilog.Parsing;
namespace Shared.Infrastructure.Logging;
/// <summary>
/// Keeps a warning, error or fatal that repeats from flooding the log. An event is the
/// same as another when its level, SourceContext and message template are (a template
/// that is only placeholders, such as a relayed <c>{Line}</c>, compares by its rendered
/// text instead). The first is written at once; the same event again within the window
/// is counted, not written; when the window ends with any counted, ONE line is written:
/// the last of them with <c>repeated=N window=60s</c> appended, and a new window starts.
/// A window with none counted forgets the event, so the next one is written at once.
/// At most <see cref="DefaultMaxKeys"/> events are tracked (the oldest goes first, its
/// count written); disposing writes every count still open. Information and below pass
/// straight through.
/// </summary>
public sealed class RepeatThrottleSink : ILogEventSink, IDisposable
{
public static readonly TimeSpan DefaultWindow = TimeSpan.FromSeconds(60);
public const int DefaultMaxKeys = 1000;
/// <summary>The property a summary line carries: how many more times the event happened.</summary>
public const string RepeatedProperty = "repeated";
/// <summary>The property a summary line carries: the window it counts (<c>60s</c>).</summary>
public const string WindowProperty = "window";
private const int RenderedKeyChars = 256;
private readonly ILogEventSink target;
private readonly bool ownsTarget;
private readonly TimeProvider clock;
private readonly TimeSpan window;
private readonly int maxKeys;
private readonly string windowText;
private readonly Lock gate = new();
private readonly Dictionary<Key, Entry> entries = [];
private readonly ITimer? timer;
private long order;
private bool disposed;
/// <param name="target">Where events go (the logger holding the console, file and live sinks).</param>
/// <param name="clock">Time, injectable for tests.</param>
/// <param name="window">How long repeats are counted before one summary line.</param>
/// <param name="maxKeys">How many distinct events are tracked at once.</param>
/// <param name="sweepEvery">How often ended windows are looked for; <see cref="Timeout.InfiniteTimeSpan"/> for never (tests call <see cref="Sweep"/>).</param>
/// <param name="ownsTarget">Dispose <paramref name="target"/> along with this sink.</param>
public RepeatThrottleSink(
ILogEventSink target,
TimeProvider? clock = null,
TimeSpan? window = null,
int maxKeys = DefaultMaxKeys,
TimeSpan? sweepEvery = null,
bool ownsTarget = true)
{
ArgumentNullException.ThrowIfNull(target);
ArgumentOutOfRangeException.ThrowIfLessThan(maxKeys, 1);
this.target = target;
this.ownsTarget = ownsTarget;
this.clock = clock ?? TimeProvider.System;
this.window = window ?? DefaultWindow;
ArgumentOutOfRangeException.ThrowIfLessThanOrEqual(this.window, TimeSpan.Zero, nameof(window));
this.maxKeys = maxKeys;
windowText = FormatWindow(this.window);
var every = sweepEvery ?? TimeSpan.FromSeconds(1);
if (every != Timeout.InfiniteTimeSpan)
{
timer = this.clock.CreateTimer(_ => SweepQuietly(), null, every, every);
}
}
/// <summary>How many distinct events are being tracked now.</summary>
public int Tracked
{
get
{
lock (gate)
{
return entries.Count;
}
}
}
public void Emit(LogEvent logEvent)
{
if (logEvent.Level < LogEventLevel.Warning)
{
target.Emit(logEvent);
return;
}
var key = KeyOf(logEvent);
LogEvent? evicted = null;
LogEvent? summary = null;
var write = true;
lock (gate)
{
if (!disposed)
{
var now = clock.GetUtcNow();
if (entries.TryGetValue(key, out var entry) && now - entry.Start >= window)
{
summary = Close(key, entry, now);
if (summary is null)
{
entry = null;
}
}
if (entry is null)
{
evicted = MakeRoom();
entries[key] = new Entry(now, ++order);
}
else
{
entry.Suppressed++;
entry.Last = logEvent;
write = false;
}
}
}
if (evicted is not null)
{
target.Emit(evicted);
}
if (summary is not null)
{
target.Emit(summary);
}
if (write)
{
target.Emit(logEvent);
}
}
/// <summary>Ends every window that is over: a summary line for each that counted repeats; the quiet ones are forgotten.</summary>
public void Sweep()
{
List<LogEvent>? summaries = null;
lock (gate)
{
if (disposed || entries.Count == 0)
{
return;
}
var now = clock.GetUtcNow();
foreach (var (key, entry) in entries.Where(e => now - e.Value.Start >= window).ToList())
{
if (Close(key, entry, now) is { } summary)
{
(summaries ??= []).Add(summary);
}
}
}
foreach (var summary in summaries ?? [])
{
target.Emit(summary);
}
}
/// <summary>Writes every count still open, then stops (events after this pass straight through).</summary>
public void Dispose()
{
List<LogEvent> summaries;
lock (gate)
{
if (disposed)
{
return;
}
disposed = true;
summaries = [.. entries.Values.Where(e => e.Suppressed > 0).OrderBy(e => e.Order).Select(Summary)];
entries.Clear();
}
timer?.Dispose();
foreach (var summary in summaries)
{
target.Emit(summary);
}
if (ownsTarget)
{
(target as IDisposable)?.Dispose();
}
}
/// <summary><c>60s</c>, <c>1.5s</c>, <c>250ms</c>.</summary>
public static string FormatWindow(TimeSpan window)
=> window.TotalSeconds >= 1
? window.TotalSeconds.ToString("0.###", CultureInfo.InvariantCulture) + "s"
: window.TotalMilliseconds.ToString("0", CultureInfo.InvariantCulture) + "ms";
private static Key KeyOf(LogEvent logEvent)
{
var template = logEvent.MessageTemplate;
var text = template.Tokens.Any(t => t is TextToken token && !string.IsNullOrWhiteSpace(token.Text))
? template.Text
: logEvent.RenderMessage(CultureInfo.InvariantCulture);
if (text.Length > RenderedKeyChars)
{
text = text[..RenderedKeyChars];
}
return new Key(logEvent.Level, LogLineFormatter.SourceContext(logEvent), text);
}
/// <summary>The window of <paramref name="entry"/> is over: its summary (and a new window), or nothing (and it is forgotten).</summary>
private LogEvent? Close(Key key, Entry entry, DateTimeOffset now)
{
if (entry.Suppressed == 0)
{
entries.Remove(key);
return null;
}
var summary = Summary(entry);
entry.Start = now;
entry.Suppressed = 0;
entry.Last = null;
return summary;
}
private LogEvent? MakeRoom()
{
if (entries.Count < maxKeys)
{
return null;
}
var oldest = entries.MinBy(e => e.Value.Order);
entries.Remove(oldest.Key);
return oldest.Value.Suppressed > 0 ? Summary(oldest.Value) : null;
}
private LogEvent Summary(Entry entry)
{
var last = entry.Last!;
var summary = new LogEvent(
clock.GetUtcNow(),
last.Level,
last.Exception,
last.MessageTemplate,
last.Properties.Select(p => new LogEventProperty(p.Key, p.Value)));
summary.AddOrUpdateProperty(new LogEventProperty(RepeatedProperty, new ScalarValue(entry.Suppressed)));
summary.AddOrUpdateProperty(new LogEventProperty(WindowProperty, new ScalarValue(windowText)));
return summary;
}
private void SweepQuietly()
{
try
{
Sweep();
}
catch (Exception exception)
{
// A sink that throws must never take the timer (or the process) down with it.
Serilog.Debugging.SelfLog.WriteLine("Repeat summary failed: {0}", exception);
}
}
private readonly record struct Key(LogEventLevel Level, string? Source, string Template);
private sealed class Entry(DateTimeOffset start, long order)
{
public DateTimeOffset Start { get; set; } = start;
public long Order { get; } = order;
public int Suppressed { get; set; }
public LogEvent? Last { get; set; }
}
}
@@ -0,0 +1,124 @@
#Requires -Version 7.4
<#
.SYNOPSIS
Regenerates the editor's PowerShell IntelliSense catalog (src/utils/monaco/catalog/*.json).
.DESCRIPTION
Read-only introspection on a Windows machine: commands from PowerShell 7
and, when present, Windows PowerShell 5.1 (merged, with the edition noted
where they differ), CIM classes, and .NET types through reflection.
Synopses come from synopses.json beside this script (help content is
rarely installed, so they are curated).
pwsh -NoProfile -File src/WebUI/scripts/powershell-catalog/Build-PowerShellCatalog.ps1
#>
[CmdletBinding()]
param(
[string]$OutDirectory = (Join-Path $PSScriptRoot '../../src/utils/monaco/catalog')
)
$ErrorActionPreference = 'Stop'
$Modules = @(
'Microsoft.PowerShell.Core', 'Microsoft.PowerShell.Management', 'Microsoft.PowerShell.Utility', 'Microsoft.PowerShell.Security',
'Microsoft.PowerShell.Archive', 'Microsoft.PowerShell.Diagnostics', 'Microsoft.PowerShell.Host', 'Microsoft.PowerShell.LocalAccounts',
'Microsoft.PowerShell.ThreadJob', 'ThreadJob', 'Microsoft.PowerShell.PSResourceGet', 'PowerShellGet', 'PackageManagement',
'Microsoft.WSMan.Management', 'CimCmdlets', 'NetTCPIP', 'NetSecurity', 'NetAdapter', 'NetConnection', 'DnsClient',
'NetworkConnectivityStatus', 'VpnClient', 'SmbShare', 'ScheduledTasks', 'Storage', 'Defender', 'PKI', 'Dism', 'BitLocker',
'TrustedPlatformModule', 'SecureBoot', 'PnpDevice', 'International', 'Appx', 'WindowsUpdate', 'PrintManagement',
'DeliveryOptimization', 'LanguagePackManagement', 'StartLayout', 'WindowsErrorReporting'
)
$CimClasses = @(
'Win32_OperatingSystem', 'Win32_ComputerSystem', 'Win32_ComputerSystemProduct', 'Win32_BIOS', 'Win32_BaseBoard', 'Win32_Processor',
'Win32_PhysicalMemory', 'Win32_LogicalDisk', 'Win32_DiskDrive', 'Win32_DiskPartition', 'Win32_Volume', 'Win32_MappedLogicalDisk',
'Win32_Service', 'Win32_Process', 'Win32_SystemDriver', 'Win32_NetworkAdapter', 'Win32_NetworkAdapterConfiguration', 'Win32_Product',
'Win32_InstalledWin32Program', 'Win32_QuickFixEngineering', 'Win32_UserProfile', 'Win32_UserAccount', 'Win32_Group',
'Win32_GroupUser', 'Win32_Share', 'Win32_StartupCommand', 'Win32_SystemEnclosure', 'Win32_TimeZone', 'Win32_LocalTime',
'Win32_Printer', 'Win32_VideoController', 'Win32_DesktopMonitor', 'Win32_SoundDevice', 'Win32_USBController', 'Win32_PnPEntity',
'Win32_PnPSignedDriver', 'Win32_LoggedOnUser', 'Win32_LogonSession', 'Win32_NetworkLoginProfile', 'Win32_Environment',
'Win32_PageFileUsage', 'Win32_Battery', 'Win32_OptionalFeature', 'Win32_ShadowCopy', 'Win32_ReliabilityRecords', 'Win32_NTLogEvent',
'SoftwareLicensingProduct', 'SoftwareLicensingService'
) | ForEach-Object { "root/cimv2:$_" }
$CimClasses += @(
'root/cimv2/Security/MicrosoftVolumeEncryption:Win32_EncryptableVolume', 'root/cimv2/Security/MicrosoftTpm:Win32_Tpm',
'root/Microsoft/Windows/DeviceGuard:Win32_DeviceGuard', 'root/cimv2/mdm/dmmap:MDM_DevDetail_Ext01',
'root/Microsoft/Windows/Defender:MSFT_MpComputerStatus', 'root/Microsoft/Windows/Defender:MSFT_MpPreference',
'root/Microsoft/Windows/Defender:MSFT_MpThreat', 'root/Microsoft/Windows/Defender:MSFT_MpThreatDetection'
)
$work = Join-Path ([System.IO.Path]::GetTempPath()) "ps-catalog-$PID"
New-Item -ItemType Directory -Path $work -Force | Out-Null
$exporter = Join-Path $PSScriptRoot 'Export-Commands.ps1'
try {
# PowerShell 7 also describes the CIM classes: the curated ones and every one a CDXML command returns.
$core = Join-Path $work 'core.json'
$cimList = Join-Path $work 'cim.txt'
$CimClasses | Set-Content -LiteralPath $cimList
& pwsh -NoProfile -File $exporter -OutFile $core -Module ($Modules -join ',') -CimClass "@$cimList" -DescribeOutputClasses
if ($LASTEXITCODE) { throw "Export-Commands.ps1 failed in PowerShell 7." }
$seven = Get-Content $core -Raw | ConvertFrom-Json -AsHashtable
$desktop = $null
if (Get-Command powershell.exe -ErrorAction Ignore) {
$windows = Join-Path $work 'desktop.json'
& powershell.exe -NoProfile -File $exporter -OutFile $windows -Module ($Modules -join ',')
if ($LASTEXITCODE) { throw "Export-Commands.ps1 failed in Windows PowerShell." }
$desktop = Get-Content $windows -Raw | ConvertFrom-Json -AsHashtable
}
# Merge: PowerShell 7's view wins; whatever exists on one edition only is marked "5" or "7".
$byName = [ordered]@{}
foreach ($c in $seven.commands) { $byName[$c.n] = $c }
if ($desktop) {
$desktopNames = @{}
foreach ($c in $desktop.commands) {
$desktopNames[$c.n] = $true
$mine = $byName[$c.n]
if (-not $mine) { $c.e = '5'; $byName[$c.n] = $c; continue }
$have = @{}
foreach ($p in $mine.p) { $have[$p[0]] = $true }
$desktopParameters = @{}
foreach ($p in $c.p) { $desktopParameters[$p[0]] = $true }
$mine.p = @(foreach ($p in $mine.p) {
if ($desktopParameters.ContainsKey($p[0])) { , $p }
else { , @($p[0], $p[1], $(if ($p.Count -gt 2) { , $p[2] } else { $null }), '7') }
})
foreach ($p in $c.p) {
if (-not $have.ContainsKey($p[0])) { $mine.p += , @($p[0], $p[1], $(if ($p.Count -gt 2) { , $p[2] } else { $null }), '5') }
}
if ($c.o) { $mine.o = @(@($mine.o) + @($c.o) | Where-Object { $_ } | Select-Object -Unique) }
}
foreach ($c in $byName.Values) { if (-not $c.e -and -not $desktopNames.ContainsKey($c.n)) { $c.e = '7' } }
}
$synopses = Get-Content (Join-Path $PSScriptRoot 'synopses.json') -Raw | ConvertFrom-Json -AsHashtable
foreach ($c in $byName.Values) { if ($synopses.ContainsKey($c.n)) { $c.d = $synopses[$c.n] } }
$aliases = [ordered]@{}
foreach ($source in @($desktop, $seven)) {
if (-not $source) { continue }
foreach ($a in $source.aliases.GetEnumerator()) { $aliases[$a.Key] = $a.Value }
}
$commands = [ordered]@{
generated = "$($seven.edition)$(if ($desktop) { " + $($desktop.edition)" })"
commands = @($byName.Values | Sort-Object { $_.n })
aliases = $aliases
cim = $seven.cim
}
New-Item -ItemType Directory -Path $OutDirectory -Force | Out-Null
$commandsFile = Join-Path $OutDirectory 'commands.json'
[System.IO.File]::WriteAllText($commandsFile, ($commands | ConvertTo-Json -Depth 10 -Compress), [System.Text.UTF8Encoding]::new($false))
Write-Host "Commands: $($byName.Count), aliases: $($aliases.Count), CIM classes: $($seven.cim.Count) -> $commandsFile"
# .NET: the usual namespaces plus every type a command says it returns.
$outputTypes = @($byName.Values | ForEach-Object { $_.o } | Where-Object { $_ } | ForEach-Object { ($_ -split '#')[0] } | Sort-Object -Unique)
$typeList = Join-Path $work 'types.txt'
$outputTypes | Set-Content -LiteralPath $typeList
& pwsh -NoProfile -File (Join-Path $PSScriptRoot 'Export-DotNet.ps1') -OutFile (Join-Path $OutDirectory 'dotnet.json') -ExtraType "@$typeList"
if ($LASTEXITCODE) { throw "Export-DotNet.ps1 failed." }
}
finally {
Remove-Item $work -Recurse -Force -ErrorAction Ignore
}
@@ -0,0 +1,148 @@
<#
.SYNOPSIS
Writes the commands of the given modules as seen by the PowerShell running this script.
.DESCRIPTION
Read-only: Get-Command metadata (parameters, their types, ValidateSet and
enum values, parameter sets and output types), the built-in aliases and,
when asked, the properties and methods of CIM classes. Runs on Windows
PowerShell 5.1 and PowerShell 7 alike; Build-PowerShellCatalog.ps1 runs it
in both and merges the results.
#>
[CmdletBinding()]
param(
[Parameter(Mandatory)]
[string]$OutFile,
[Parameter(Mandatory)]
[string[]]$Module,
# CIM classes to describe, as "namespace:class".
[string[]]$CimClass = @(),
# Also describe every CIM class a command declares as output (CDXML modules).
[switch]$DescribeOutputClasses
)
$ErrorActionPreference = 'Stop'
$ProgressPreference = 'SilentlyContinue'
# Lists arrive from the command line as "a,b,c" or "@file" (one per line).
function Expand-List([string[]]$Value) {
foreach ($v in $Value) {
if ($v -like '@*') { Get-Content -LiteralPath $v.Substring(1) | Where-Object { $_ } }
else { $v -split ',' | Where-Object { $_ } }
}
}
$Module = @(Expand-List $Module)
$CimClass = @(Expand-List $CimClass)
$commonNames = @(
'Verbose', 'Debug', 'ErrorAction', 'WarningAction', 'InformationAction', 'ProgressAction', 'ErrorVariable', 'WarningVariable',
'InformationVariable', 'OutVariable', 'OutBuffer', 'PipelineVariable', 'WhatIf', 'Confirm', 'UseTransaction'
)
$common = @{}
foreach ($n in $commonNames) { $common[$n] = $true }
$aliases = @{
'System.String' = 'string'; 'System.Int32' = 'int'; 'System.Int64' = 'long'; 'System.Boolean' = 'bool'; 'System.Object' = 'object'
'System.Double' = 'double'; 'System.Byte' = 'byte'; 'System.Char' = 'char'; 'System.UInt32' = 'uint'; 'System.UInt64' = 'ulong'
'System.UInt16' = 'ushort'; 'System.Int16' = 'short'; 'System.DateTime' = 'datetime'; 'System.TimeSpan' = 'timespan'
'System.Collections.Hashtable' = 'hashtable'; 'System.Management.Automation.SwitchParameter' = 'switch'
'System.Management.Automation.ScriptBlock' = 'scriptblock'; 'System.Management.Automation.PSObject' = 'psobject'
'System.Management.Automation.PSCredential' = 'pscredential'; 'System.Security.SecureString' = 'securestring'
'System.Guid' = 'guid'; 'System.Uri' = 'uri'; 'System.Version' = 'version'
}
function Format-Type([type]$Type) {
if ($Type.IsArray) { return (Format-Type $Type.GetElementType()) + '[]' }
if ($Type.IsGenericType) {
$arguments = @($Type.GetGenericArguments() | ForEach-Object { Format-Type $_ })
if ($Type.GetGenericTypeDefinition().FullName -eq 'System.Nullable`1') { return $arguments[0] }
return ($Type.Name -replace '`\d+$', '') + '[' + ($arguments -join ', ') + ']'
}
if ($aliases.ContainsKey($Type.FullName)) { return $aliases[$Type.FullName] }
return $Type.Name
}
function Get-Values($Parameter) {
foreach ($attribute in $Parameter.Attributes) {
if ($attribute -is [System.Management.Automation.ValidateSetAttribute]) { return @($attribute.ValidValues) }
}
$type = $Parameter.ParameterType
if ($type.IsArray) { $type = $type.GetElementType() }
if ($type.IsGenericType -and $type.GetGenericTypeDefinition().FullName -eq 'System.Nullable`1') { $type = $type.GetGenericArguments()[0] }
if ($type.IsEnum) { return @([Enum]::GetNames($type) | Select-Object -First 80) }
return $null
}
$commands = New-Object System.Collections.Generic.List[object]
foreach ($name in $Module) {
$found = @(Get-Command -Module $name -CommandType Cmdlet, Function -ErrorAction SilentlyContinue)
foreach ($c in $found) {
try { $parameters = @($c.Parameters.Values) } catch { $parameters = @() }
$index = @{}
$list = New-Object System.Collections.Generic.List[object]
foreach ($p in $parameters | Where-Object { $_ -and -not $common.ContainsKey($_.Name) }) {
$entry = New-Object System.Collections.Generic.List[object]
$entry.Add($p.Name)
$entry.Add((Format-Type $p.ParameterType))
$values = Get-Values $p
if ($values) { $entry.Add([object[]]$values) }
$index[$p.Name] = $list.Count
$list.Add($entry.ToArray())
}
$sets = New-Object System.Collections.Generic.List[object]
try { $parameterSets = @($c.ParameterSets | Where-Object { $_ }) } catch { $parameterSets = @() }
foreach ($s in $parameterSets) {
$tokens = foreach ($sp in $s.Parameters) {
if (-not $index.ContainsKey($sp.Name)) { continue }
$token = [string]$index[$sp.Name]
if ($sp.IsMandatory) { $token += 'm' }
if ($sp.Position -ge 0) { $token += "p$($sp.Position)" }
$token
}
$setName = if ($s.Name -eq '__AllParameterSets') { '' } else { $s.Name }
$sets.Add(@($setName, $(if ($s.IsDefault) { 1 } else { 0 }), (@($tokens) -join ' ')))
}
$outputs = @($c.OutputType | ForEach-Object { $_.Name } | Where-Object { $_ } | Select-Object -Unique)
$entry = [ordered]@{ n = $c.Name; m = $c.ModuleName; p = $list.ToArray(); s = $sets.ToArray() }
if ($outputs.Count) { $entry.o = $outputs }
$commands.Add($entry)
}
}
$known = @{}
foreach ($c in $commands) { $known[$c.n] = $true }
$aliasMap = [ordered]@{}
foreach ($a in Get-Alias | Sort-Object Name) {
if ($a.Definition -and $known.ContainsKey($a.Definition)) { $aliasMap[$a.Name] = $a.Definition }
}
if ($DescribeOutputClasses) {
foreach ($c in $commands) {
foreach ($o in $c.o) { if ($o -match '#(.+)[\\/]([^\\/]+)$') { $CimClass += "$($Matches[1] -replace '\\', '/'):$($Matches[2])" } }
}
$CimClass = @($CimClass | Select-Object -Unique)
}
$cim = [ordered]@{}
foreach ($spec in $CimClass) {
$namespace, $className = $spec -split ':', 2
try { $class = Get-CimClass -Namespace $namespace -ClassName $className -ErrorAction Stop } catch { continue }
$properties = @($class.CimClassProperties | ForEach-Object { , @($_.Name, [string]$_.CimType) })
$methods = @($class.CimClassMethods | ForEach-Object {
$in = @($_.Parameters | Where-Object { $_.Qualifiers.Name -contains 'In' } | ForEach-Object { "$($_.CimType) $($_.Name)" })
, @($_.Name, ($in -join ', '))
})
$cim[$className] = [ordered]@{ ns = $namespace; p = $properties; m = $methods }
}
$result = [ordered]@{
edition = "$($PSVersionTable.PSEdition) $($PSVersionTable.PSVersion)"
commands = $commands.ToArray()
aliases = $aliasMap
cim = $cim
}
$json = $result | ConvertTo-Json -Depth 8 -Compress
[System.IO.File]::WriteAllText($OutFile, $json, (New-Object System.Text.UTF8Encoding $false))
Write-Host "$($result.edition): $($commands.Count) commands, $($aliasMap.Count) aliases, $($cim.Count) CIM classes -> $OutFile"
@@ -0,0 +1,266 @@
#Requires -Version 7.4
<#
.SYNOPSIS
Writes the .NET part of the editor's PowerShell IntelliSense catalog.
.DESCRIPTION
Read-only reflection over the assemblies that ship with PowerShell 7:
public types in the namespaces scripts reach for, their members and
overloads, enum values, constructors, PowerShell's type accelerators and
the extended-type-system (ETS) members PowerShell adds. Run through
Build-PowerShellCatalog.ps1.
#>
[CmdletBinding()]
param(
[Parameter(Mandatory)]
[string]$OutFile,
# Types that must be present whatever their namespace (cmdlet output types).
[string[]]$ExtraType = @()
)
$ErrorActionPreference = 'Stop'
# Lists arrive from the command line as "a,b,c" or "@file" (one per line).
$ExtraType = @(foreach ($v in $ExtraType) {
if ($v -like '@*') { Get-Content -LiteralPath $v.Substring(1) | Where-Object { $_ } } else { $v -split ',' | Where-Object { $_ } }
})
# Every managed assembly PowerShell ships with (it is self-contained, so $PSHOME is the runtime directory).
foreach ($dll in Get-ChildItem $PSHOME -Filter *.dll) {
if ($dll.Name -notmatch '^(System|Microsoft\.(Win32|Management\.Infrastructure\.dll|PowerShell\.Commands|VisualBasic\.Core))') { continue }
try { [void][Reflection.Assembly]::LoadFrom($dll.FullName) } catch { }
}
# Binary modules whose types commands return.
Import-Module Microsoft.PowerShell.LocalAccounts, BitLocker -ErrorAction Ignore -WarningAction Ignore
# Namespaces whose public types are all listed.
$Namespaces = [System.Collections.Generic.HashSet[string]]::new([string[]]@(
'System', 'System.IO', 'System.IO.Compression', 'System.Net', 'System.Net.Http', 'System.Net.Http.Headers',
'System.Net.Sockets', 'System.Net.NetworkInformation', 'System.Net.Security', 'System.Net.Mail',
'System.Text', 'System.Text.RegularExpressions', 'System.Text.Json',
'System.Collections', 'System.Collections.Generic', 'System.Collections.Specialized', 'System.Collections.Concurrent',
'System.Collections.ObjectModel', 'System.Security', 'System.Security.Principal', 'System.Security.AccessControl',
'System.Security.Cryptography', 'System.Security.Cryptography.X509Certificates', 'System.Diagnostics',
'System.Diagnostics.Eventing.Reader', 'System.Threading', 'System.Threading.Tasks', 'System.Management.Automation',
'System.Management.Automation.Runspaces', 'System.Management.Automation.Host',
'Microsoft.Win32', 'System.DirectoryServices', 'System.DirectoryServices.AccountManagement', 'System.Xml', 'System.Xml.Linq',
'System.Web', 'System.Runtime.InteropServices', 'System.Globalization', 'System.ServiceProcess',
'System.Reflection', 'System.Timers', 'System.Data', 'System.Data.SqlClient', 'System.Management',
'Microsoft.Management.Infrastructure'
), [StringComparer]::Ordinal)
# Single types from namespaces too large or too specialised to list whole.
$SingleTypes = @(
'System.Linq.Enumerable', 'System.Numerics.BigInteger', 'System.Numerics.Complex',
'System.Management.Automation.Language.Parser', 'System.Management.Automation.Language.Token',
'System.Management.Automation.Language.Ast', 'System.Management.Automation.Language.ScriptBlockAst',
'System.Management.Automation.Language.CodeGeneration',
# Returned by commands that declare no output type.
'Microsoft.PowerShell.Commands.LocalUser', 'Microsoft.PowerShell.Commands.LocalGroup', 'Microsoft.PowerShell.Commands.LocalPrincipal',
'Microsoft.BitLocker.Structures.BitLockerVolume'
)
$Aliases = @{
'System.String' = 'string'; 'System.Int32' = 'int'; 'System.Int64' = 'long'; 'System.Int16' = 'short'; 'System.Boolean' = 'bool'
'System.Object' = 'object'; 'System.Void' = 'void'; 'System.Double' = 'double'; 'System.Single' = 'float'; 'System.Byte' = 'byte'
'System.SByte' = 'sbyte'; 'System.Char' = 'char'; 'System.Decimal' = 'decimal'; 'System.UInt32' = 'uint'; 'System.UInt64' = 'ulong'
'System.UInt16' = 'ushort'; 'System.DateTime' = 'datetime'; 'System.TimeSpan' = 'timespan'; 'System.Guid' = 'guid'
'System.Collections.Hashtable' = 'hashtable'; 'System.Management.Automation.SwitchParameter' = 'switch'
'System.Management.Automation.ScriptBlock' = 'scriptblock'; 'System.Management.Automation.PSObject' = 'psobject'
'System.IntPtr' = 'IntPtr'; 'System.Type' = 'type'
}
$obsolete = [ObsoleteAttribute]
function Test-Hidden([System.Reflection.MemberInfo]$Member) {
$o = [Attribute]::GetCustomAttribute($Member, $obsolete, $false)
return $o -and $o.IsError
}
# A type as PowerShell writes it: aliases for primitives, Name[Arg] for generics; namespaces kept when $Full.
function Format-Type([type]$Type, [bool]$Full) {
if ($Type.IsByRef) { return '[ref] ' + (Format-Type $Type.GetElementType() $Full) }
if ($Type.IsPointer) { return (Format-Type $Type.GetElementType() $Full) + '*' }
if ($Type.IsArray) { return (Format-Type $Type.GetElementType() $Full) + '[' + (',' * ($Type.GetArrayRank() - 1)) + ']' }
if ($Type.IsGenericParameter) { return $Type.Name }
if ($Type.IsGenericType) {
$definition = $Type.GetGenericTypeDefinition()
$arguments = $Type.GetGenericArguments() | ForEach-Object { Format-Type $_ $Full }
if ($definition.FullName -eq 'System.Nullable`1') { return "Nullable[$($arguments -join ', ')]" }
$name = if ($Full -and $definition.FullName) { $definition.FullName } else { $definition.Name }
return ($name -replace '`\d+$', '') + '[' + ($arguments -join ', ') + ']'
}
if ($Type.FullName -and $Aliases.ContainsKey($Type.FullName)) { return $Aliases[$Type.FullName] }
if ($Full -and $Type.FullName) { return $Type.FullName }
if ($Type.IsNested) { return (Format-Type $Type.DeclaringType $false) + '+' + $Type.Name }
return $Type.Name
}
function Test-Unusable([type]$Type) {
while ($Type.HasElementType) { if ($Type.IsPointer) { return $true }; $Type = $Type.GetElementType() }
return $Type.IsByRefLike -or $Type.IsPointer -or $Type.FullName -like 'System.Span*' -or $Type.FullName -like 'System.ReadOnlySpan*'
}
function Format-Parameters([System.Reflection.ParameterInfo[]]$Parameters) {
$parts = foreach ($p in $Parameters) {
$type = if ($p.IsOut) { '[ref] ' + (Format-Type $p.ParameterType.GetElementType() $false) } else { Format-Type $p.ParameterType $false }
if ($p.GetCustomAttributes([ParamArrayAttribute], $false).Count) { $type = "params $type" }
$text = "$type $($p.Name)"
if ($p.IsOptional -and $p.HasDefaultValue) {
$value = $p.DefaultValue
$text += ' = ' + $(if ($null -eq $value) { if ($p.ParameterType.IsValueType) { 'default' } else { 'null' } } elseif ($value -is [string]) { "'$value'" } elseif ($value -is [bool]) { "`$$value".ToLower() } else { "$value" })
}
$text
}
return $parts -join ', '
}
$MaxOverloads = 12
$Declared = [Reflection.BindingFlags]'Public, Instance, Static, DeclaredOnly'
function Get-Members([type]$Type) {
$members = [System.Collections.Generic.List[object]]::new()
if ($Type.IsEnum -or $Type.IsSubclassOf([Delegate])) { return , $members }
$isAttribute = $Type.IsSubclassOf([Attribute])
if (-not $isAttribute) {
$methods = $Type.GetMethods($Declared) | Where-Object {
-not $_.IsSpecialName -and -not (Test-Hidden $_) -and -not (Test-Unusable $_.ReturnType) -and
-not ($_.GetParameters() | Where-Object { Test-Unusable $_.ParameterType })
}
foreach ($group in $methods | Group-Object { "$($_.IsStatic)|$($_.Name)" }) {
$first = $group.Group[0]
$overloads = [System.Collections.Generic.List[object]]::new()
foreach ($m in $group.Group | Sort-Object { $_.GetParameters().Count } | Select-Object -First $MaxOverloads) {
$overload = [System.Collections.Generic.List[string]]::new()
$overload.Add((Format-Type $m.ReturnType $true))
$overload.Add((Format-Parameters $m.GetParameters()))
if ($m.IsGenericMethodDefinition) { $overload.Add((($m.GetGenericArguments() | ForEach-Object Name) -join ', ')) }
$overloads.Add($overload.ToArray())
}
$members.Add(@($first.Name, $(if ($first.IsStatic) { 'ms' } else { 'm' }), $overloads.ToArray()))
}
}
foreach ($p in $Type.GetProperties($Declared)) {
if ($p.GetIndexParameters().Count -or (Test-Hidden $p) -or (Test-Unusable $p.PropertyType)) { continue }
$accessor = $p.GetMethod ?? $p.SetMethod
if (-not $accessor -or -not $accessor.IsPublic) { continue }
$flags = 'p' + $(if ($accessor.IsStatic) { 's' } else { '' }) + $(if ($p.SetMethod -and $p.SetMethod.IsPublic) { 'w' } else { '' })
$members.Add(@($p.Name, $flags, (Format-Type $p.PropertyType $true)))
}
foreach ($f in $Type.GetFields($Declared)) {
if ((Test-Hidden $f) -or (Test-Unusable $f.FieldType)) { continue }
$flags = 'f' + $(if ($f.IsStatic) { 's' } else { '' }) + $(if ($f.IsLiteral) { 'c' } elseif (-not $f.IsInitOnly) { 'w' } else { '' })
$entry = @($f.Name, $flags, (Format-Type $f.FieldType $true))
if ($f.IsLiteral) {
$value = $f.GetRawConstantValue()
if ($value -is [string] -or $value -is [char] -or $value.GetType().IsPrimitive) { $entry += [string]$value }
}
$members.Add($entry)
}
if (-not $isAttribute) {
foreach ($e in $Type.GetEvents($Declared)) {
if (Test-Hidden $e) { continue }
$members.Add(@($e.Name, $(if ($e.AddMethod.IsStatic) { 'es' } else { 'e' }), (Format-Type $e.EventHandlerType $true)))
}
}
# What PowerShell's type data adds (ScriptProperty, AliasProperty, CodeMethod, …);
# an alias property carries the member it stands for, so its type can be followed.
$typeData = Get-TypeData -TypeName ([WildcardPattern]::Escape($Type.FullName)) -ErrorAction Ignore
if ($typeData) {
foreach ($entry in $typeData.Members.GetEnumerator()) {
$kind = $entry.Value.GetType().Name
if ($kind -eq 'AliasPropertyData') { $members.Add(@($entry.Key, 'x', '', $entry.Value.ReferencedMemberName)) }
elseif ($kind -like '*PropertyData') { $members.Add(@($entry.Key, 'x', '')) }
elseif ($kind -like '*MethodData') { $members.Add(@($entry.Key, 'y', '')) }
}
}
return , $members
}
function Get-Kind([type]$Type) {
if ($Type.IsEnum) { return 'e' }
if ($Type.IsInterface) { return 'i' }
if ($Type.IsSubclassOf([Delegate])) { return 'd' }
if ($Type.IsValueType) { return 's' }
if ($Type.IsAbstract -and $Type.IsSealed) { return 'sc' }
if ($Type.IsAbstract) { return 'ac' }
return 'c'
}
function Test-Listed([type]$Type) {
if (-not $Type.IsVisible -or $Type.FullName -match '[<>]' -or (Test-Hidden $Type) -or $Type.IsByRefLike) { return $false }
# Attributes: only PowerShell's own ([Parameter()], [ValidateSet()], …).
if ($Type.IsSubclassOf([Attribute]) -and $Type.Namespace -ne 'System.Management.Automation') { return $false }
return $true
}
$types = [ordered]@{}
$queue = [System.Collections.Generic.Queue[type]]::new()
$assemblies = [AppDomain]::CurrentDomain.GetAssemblies() | Where-Object { -not $_.IsDynamic } | Sort-Object FullName
foreach ($assembly in $assemblies) {
try { $exported = $assembly.GetExportedTypes() } catch { continue }
foreach ($t in $exported) {
if ($t.Namespace -and $Namespaces.Contains($t.Namespace) -and (Test-Listed $t)) { $queue.Enqueue($t) }
}
}
# Accelerators and extra (output) types are listed even outside those namespaces.
$accelerators = [ordered]@{}
$acceleratorTable = [psobject].Assembly.GetType('System.Management.Automation.TypeAccelerators')::Get
foreach ($name in $acceleratorTable.Keys | Sort-Object) {
$t = $acceleratorTable[$name]
$accelerators[$name] = $t.FullName
$queue.Enqueue($t)
}
foreach ($name in @($SingleTypes) + $ExtraType) {
$t = $name -as [type]
if ($t) { $queue.Enqueue($t) }
}
$seen = [System.Collections.Generic.HashSet[string]]::new()
while ($queue.Count) {
$t = $queue.Dequeue()
while ($t.HasElementType) { $t = $t.GetElementType() }
if ($t.IsGenericType -and -not $t.IsGenericTypeDefinition) { $t = $t.GetGenericTypeDefinition() }
if (-not $t.FullName -or -not $seen.Add($t.FullName)) { continue }
$entry = [ordered]@{ k = Get-Kind $t }
$base = $t.BaseType
if ($base -and $base.FullName -and $base.FullName -notin 'System.Object', 'System.ValueType', 'System.Enum', 'System.MulticastDelegate') {
$definition = if ($base.IsGenericType) { $base.GetGenericTypeDefinition() } else { $base }
$entry.b = Format-Type $base $true
if (Test-Listed $definition) { $queue.Enqueue($definition) }
}
if ($t.IsGenericTypeDefinition) { $entry.g = @($t.GetGenericArguments() | ForEach-Object Name) }
if ($t.IsEnum) {
$entry.e = @([Enum]::GetNames($t))
if ($t.IsDefined([FlagsAttribute], $false)) { $entry.fl = 1 }
}
elseif ($entry.k -in 'c', 's') {
$ctors = $t.GetConstructors() | Where-Object { -not (Test-Hidden $_) -and -not ($_.GetParameters() | Where-Object { Test-Unusable $_.ParameterType }) } |
Sort-Object { $_.GetParameters().Count } | Select-Object -First $MaxOverloads
if ($ctors -or $t.IsValueType) { $entry.c = @(@($ctors) | ForEach-Object { Format-Parameters $_.GetParameters() }) }
if ($t.IsValueType -and '' -notin $entry.c) { $entry.c = @('') + $entry.c }
}
$members = Get-Members $t
if ($members.Count) { $entry.m = $members.ToArray() }
if ($t.IsNested -and $t.DeclaringType) { $entry.n = 1 }
$types[$t.FullName] = $entry
}
$sorted = [ordered]@{}
foreach ($key in $types.Keys | Sort-Object { $_ } -CaseSensitive) { $sorted[$key] = $types[$key] }
$catalog = [ordered]@{
generated = "PowerShell $($PSVersionTable.PSVersion) on .NET $([Environment]::Version)"
accelerators = $accelerators
types = $sorted
}
$json = $catalog | ConvertTo-Json -Depth 12 -Compress
[System.IO.File]::WriteAllText($OutFile, $json, [System.Text.UTF8Encoding]::new($false))
Write-Host "Types: $($types.Count) -> $OutFile ($([math]::Round($json.Length / 1KB)) KB)"
@@ -0,0 +1,720 @@
{
"Export-BinaryMiLog": "Creates a binary encoded representation of an object or objects and stores it in a file.",
"Get-CimAssociatedInstance": "Retrieves the CIM instances that are connected to a specific CIM instance by an association.",
"Get-CimClass": "Gets a list of CIM classes in a specific namespace.",
"Get-CimInstance": "Gets the CIM instances of a class from a CIM server.",
"Get-CimSession": "Gets the CIM session objects from the current session.",
"Import-BinaryMiLog": "Used to re-create the saved objects based on the contents of an export file.",
"Invoke-CimMethod": "Invokes a method of a CIM class or instance.",
"New-CimInstance": "Creates a CIM instance.",
"New-CimSession": "Creates a CIM session.",
"New-CimSessionOption": "Specifies advanced options for the New-CimSession cmdlet.",
"Register-CimIndicationEvent": "Subscribes to indications using a filter expression or a query expression.",
"Remove-CimInstance": "Removes a CIM instance from a computer.",
"Remove-CimSession": "Removes one or more CIM sessions.",
"Set-CimInstance": "Modifies a CIM instance on a CIM server by calling the ModifyInstance method of the CIM class.",
"Compress-Archive": "Creates a compressed archive, or zipped file, from specified files and directories.",
"Expand-Archive": "Extracts files from a specified archive (zipped) file.",
"Add-History": "Appends entries to the session history.",
"Add-PSSnapin": "Adds one or more Windows PowerShell snap-ins to the current session.",
"Clear-History": "Deletes entries from the PowerShell session command history.",
"Connect-PSSession": "Reconnects to disconnected sessions.",
"Debug-Job": "Debugs a running background or remote job.",
"Disable-ExperimentalFeature": "Disables an experimental feature on startup of new instances of PowerShell.",
"Disable-PSRemoting": "Prevents PowerShell endpoints from receiving remote connections.",
"Disable-PSSessionConfiguration": "Disables session configurations on the local computer.",
"Disconnect-PSSession": "Disconnects from a session.",
"Enable-ExperimentalFeature": "Enables an experimental feature on startup of new instances of PowerShell.",
"Enable-PSRemoting": "Configures the computer to receive remote commands.",
"Enable-PSSessionConfiguration": "Enables the session configurations on the local computer.",
"Enter-PSHostProcess": "Connects to and enters into an interactive session with a local process.",
"Enter-PSSession": "Starts an interactive session with a remote computer.",
"Exit-PSHostProcess": "Closes an interactive session with a local process.",
"Exit-PSSession": "Ends an interactive session with a remote computer.",
"Export-Console": "Exports the names of snap-ins in the current session to a console file.",
"Export-ModuleMember": "Specifies the module members that are exported.",
"ForEach-Object": "Performs an operation against each item in a collection of input objects.",
"Get-Command": "Gets all commands.",
"Get-ExperimentalFeature": "Gets experimental features.",
"Get-Help": "Displays information about PowerShell commands and concepts.",
"Get-History": "Gets a list of the commands entered during the current session.",
"Get-Job": "Gets PowerShell background jobs that are running in the current session.",
"Get-Module": "Lists the modules imported in the current session or that can be imported from the PSModulePath.",
"Get-PSHostProcessInfo": "Gets process information about the PowerShell host.",
"Get-PSSession": "Gets the PowerShell sessions on local and remote computers.",
"Get-PSSessionCapability": "Gets the capabilities of a specific user on a constrained session configuration.",
"Get-PSSessionConfiguration": "Gets the registered session configurations on the computer.",
"Get-PSSnapin": "Gets the Windows PowerShell snap-ins on the computer.",
"Get-PSSubsystem": "Retrieves information about the subsystems registered in PowerShell.",
"Import-Module": "Adds modules to the current session.",
"Invoke-Command": "Runs commands on local and remote computers.",
"Invoke-History": "Runs commands from the session history.",
"New-Module": "Creates a new dynamic module that exists only in memory.",
"New-ModuleManifest": "Creates a new module manifest.",
"New-PSRoleCapabilityFile": "Creates a file that defines a set of capabilities to be exposed through a session configuration.",
"New-PSSession": "Creates a persistent connection to a local or remote computer.",
"New-PSSessionConfigurationFile": "Creates a file that defines a session configuration.",
"New-PSSessionOption": "Creates an object that contains advanced options for a PSSession.",
"New-PSTransportOption": "Creates an object that contains advanced options for a session configuration.",
"Out-Default": "Sends the output to the default formatter and to the default output cmdlet.",
"Out-Host": "Sends output to the command line.",
"Out-Null": "Hides the output instead of sending it down the pipeline or displaying it.",
"Receive-Job": "Gets the results of the PowerShell background jobs in the current session.",
"Receive-PSSession": "Gets results of commands in disconnected sessions.",
"Register-ArgumentCompleter": "Registers a custom argument completer.",
"Register-PSSessionConfiguration": "Creates and registers a new session configuration.",
"Remove-Job": "Deletes a PowerShell background job.",
"Remove-Module": "Removes modules from the current session.",
"Remove-PSSession": "Closes one or more PowerShell sessions (PSSessions).",
"Remove-PSSnapin": "Removes Windows PowerShell snap-ins from the current session.",
"Resume-Job": "Restarts a suspended job.",
"Save-Help": "Downloads and saves the newest help files to a file system directory.",
"Set-PSDebug": "Turns script debugging features on and off, sets the trace level, and toggles strict mode.",
"Set-PSSessionConfiguration": "Changes the properties of a registered session configuration.",
"Set-StrictMode": "Establishes and enforces coding rules in expressions, scripts, and script blocks.",
"Start-Job": "Starts a PowerShell background job.",
"Stop-Job": "Stops a PowerShell background job.",
"Suspend-Job": "Temporarily stops workflow jobs.",
"Test-ModuleManifest": "Verifies that a module manifest file accurately describes the contents of a module.",
"Test-PSSessionConfigurationFile": "Verifies the keys and values in a session configuration file.",
"Unregister-PSSessionConfiguration": "Deletes registered session configurations from the computer.",
"Update-Help": "Downloads and installs the newest help files on your computer.",
"Wait-Job": "Waits until one or all of the PowerShell jobs running in the session are in a terminating state.",
"Where-Object": "Selects objects from a collection based on their property values.",
"Export-Counter": "Exports performance counter data to log files.",
"Get-Counter": "Gets performance counter data from local and remote computers.",
"Get-WinEvent": "Gets events from event logs and event tracing log files on local and remote computers.",
"Import-Counter": "Imports performance counter log files and creates the objects that represent each counter sample in the log.",
"New-WinEvent": "Creates a new Windows event for the specified event provider.",
"Start-Transcript": "Creates a record of all or part of a PowerShell session to a text file.",
"Stop-Transcript": "Stops a transcript.",
"Add-LocalGroupMember": "Adds members to a local group.",
"Disable-LocalUser": "Disables a local user account.",
"Enable-LocalUser": "Enables a local user account.",
"Get-LocalGroup": "Gets the local security groups.",
"Get-LocalGroupMember": "Gets members from a local group.",
"Get-LocalUser": "Gets local user accounts.",
"New-LocalGroup": "Creates a local security group.",
"New-LocalUser": "Creates a local user account.",
"Remove-LocalGroup": "Deletes local security groups.",
"Remove-LocalGroupMember": "Removes members from a local group.",
"Remove-LocalUser": "Deletes local user accounts.",
"Rename-LocalGroup": "Renames a local security group.",
"Rename-LocalUser": "Renames a local user account.",
"Set-LocalGroup": "Changes a local security group.",
"Set-LocalUser": "Modifies a local user account.",
"Add-Computer": "Adds the local computer or remote computers to a domain or workgroup.",
"Add-Content": "Adds content to the specified items, such as adding words to a file.",
"Checkpoint-Computer": "Creates a system restore point on the local computer.",
"Clear-Content": "Deletes the contents of an item, but does not delete the item.",
"Clear-EventLog": "Clears all entries from specified event logs on the local or remote computers.",
"Clear-Item": "Clears the contents of an item, but does not delete the item.",
"Clear-ItemProperty": "Clears the value of a property but does not delete the property.",
"Clear-RecycleBin": "Clears the contents of a recycle bin.",
"Complete-Transaction": "Commits the active transaction.",
"Convert-Path": "Converts a path from a PowerShell path to a PowerShell provider path.",
"Copy-Item": "Copies an item from one location to another.",
"Copy-ItemProperty": "Copies a property and value from a specified location to another location.",
"Debug-Process": "Debugs one or more processes running on the local computer.",
"Disable-ComputerRestore": "Disables the System Restore feature on the specified file system drive.",
"Enable-ComputerRestore": "Enables the System Restore feature on the specified file system drive.",
"Get-ChildItem": "Gets the items and child items in one or more specified locations.",
"Get-Clipboard": "Gets the contents of the clipboard.",
"Get-ComputerInfo": "Gets a consolidated object of system and operating system properties.",
"Get-ComputerRestorePoint": "Gets the restore points on the local computer.",
"Get-Content": "Gets the content of the item at the specified location.",
"Get-ControlPanelItem": "Gets control panel items.",
"Get-EventLog": "Gets the events in an event log, or a list of the event logs, on the local computer or remote computers.",
"Get-HotFix": "Gets the hotfixes that are installed on local or remote computers.",
"Get-Item": "Gets the item at the specified location.",
"Get-ItemProperty": "Gets the properties of a specified item.",
"Get-ItemPropertyValue": "Gets the value for one or more properties of a specified item.",
"Get-Location": "Gets information about the current working location or a location stack.",
"Get-Process": "Gets the processes that are running on the local computer.",
"Get-PSDrive": "Gets drives in the current session.",
"Get-PSProvider": "Gets information about the specified PowerShell provider.",
"Get-Service": "Gets the services on the computer.",
"Get-TimeZone": "Gets the current time zone or a list of available time zones.",
"Get-Transaction": "Gets the current (active) transaction.",
"Get-WmiObject": "Gets instances of WMI classes or information about the available classes.",
"Invoke-Item": "Performs the default action on the specified item.",
"Invoke-WmiMethod": "Calls WMI methods.",
"Join-Path": "Combines a path and a child path into a single path.",
"Limit-EventLog": "Sets the event log properties that limit the size of the event log and the age of its entries.",
"Move-Item": "Moves an item from one location to another.",
"Move-ItemProperty": "Moves a property from one location to another.",
"New-EventLog": "Creates a new event log and a new event source on a local or remote computer.",
"New-Item": "Creates a new item.",
"New-ItemProperty": "Creates a new property for an item and sets its value.",
"New-PSDrive": "Creates temporary and persistent drives that are associated with a location in an item data store.",
"New-Service": "Creates a new Windows service.",
"New-WebServiceProxy": "Creates a Web service proxy object that lets you use and manage the Web service in PowerShell.",
"Pop-Location": "Changes the current location to the location most recently pushed onto the stack.",
"Push-Location": "Adds the current location to the top of a location stack.",
"Register-WmiEvent": "Subscribes to a Windows Management Instrumentation (WMI) event.",
"Remove-Computer": "Removes the local computer from its domain.",
"Remove-EventLog": "Deletes an event log or unregisters an event source.",
"Remove-Item": "Deletes the specified items.",
"Remove-ItemProperty": "Deletes the property and its value from an item.",
"Remove-PSDrive": "Deletes temporary PowerShell drives and disconnects mapped network drives.",
"Remove-Service": "Removes a Windows service.",
"Remove-WmiObject": "Deletes an instance of an existing WMI class.",
"Rename-Computer": "Renames a computer.",
"Rename-Item": "Renames an item in a PowerShell provider namespace.",
"Rename-ItemProperty": "Renames a property of an item.",
"Reset-ComputerMachinePassword": "Resets the machine account password for the computer.",
"Resolve-Path": "Resolves the wildcard characters in a path, and displays the path contents.",
"Restart-Computer": "Restarts the operating system on local and remote computers.",
"Restart-Service": "Stops and then starts one or more services.",
"Restore-Computer": "Starts a system restore on the local computer.",
"Resume-Service": "Resumes one or more suspended (paused) services.",
"Set-Clipboard": "Sets the contents of the clipboard.",
"Set-Content": "Writes new content or replaces existing content in a file.",
"Set-Item": "Changes the value of an item to the value specified in the command.",
"Set-ItemProperty": "Creates or changes the value of a property of an item.",
"Set-Location": "Sets the current working location to a specified location.",
"Set-Service": "Starts, stops, and suspends a service, and changes its properties.",
"Set-TimeZone": "Sets the system time zone to a specified time zone.",
"Set-WmiInstance": "Creates or updates an instance of an existing WMI class.",
"Show-ControlPanelItem": "Opens control panel items.",
"Show-EventLog": "Displays the event logs of the local or a remote computer in Event Viewer.",
"Split-Path": "Returns the specified part of a path.",
"Start-Process": "Starts one or more processes on the local computer.",
"Start-Service": "Starts one or more stopped services.",
"Start-Transaction": "Starts a transaction.",
"Stop-Computer": "Stops (shuts down) local and remote computers.",
"Stop-Process": "Stops one or more running processes.",
"Stop-Service": "Stops one or more running services.",
"Suspend-Service": "Suspends (pauses) one or more running services.",
"Test-ComputerSecureChannel": "Tests and repairs the secure channel between the local computer and its domain.",
"Test-Connection": "Sends ICMP echo request packets, or pings, to one or more computers.",
"Test-Path": "Determines whether all elements of a path exist.",
"Undo-Transaction": "Rolls back the active transaction.",
"Use-Transaction": "Adds the script block to the active transaction.",
"Wait-Process": "Waits for the processes to be stopped before accepting more input.",
"Write-EventLog": "Writes an event to an event log.",
"Compress-PSResource": "Compresses a module or script into a .nupkg package.",
"Find-PSResource": "Searches for packages from a repository (local or remote), based on a name or other package properties.",
"Get-InstalledPSResource": "Returns modules and scripts installed on the machine via PowerShellGet.",
"Get-PSResourceRepository": "Finds and returns registered repository information.",
"Get-PSScriptFileInfo": "Returns the metadata for a script.",
"Import-PSGetRepository": "Finds the repositories registered with PowerShellGet 2.x and registers them for PSResourceGet.",
"Install-PSResource": "Installs resources from a registered repository.",
"New-PSScriptFileInfo": "Creates a new script file with the metadata block.",
"Publish-PSResource": "Publishes a specified module from the local computer to a PSResource repository.",
"Register-PSResourceRepository": "Registers a repository for PowerShell resources.",
"Reset-PSResourceRepository": "Resets the repository store to its default state, with only PSGallery registered.",
"Save-PSResource": "Saves resources (modules and scripts) from a registered repository onto the machine.",
"Set-PSResourceRepository": "Sets information for a registered repository.",
"Test-PSScriptFileInfo": "Tests the comment-based metadata in a .ps1 file to ensure it's valid for publication.",
"Uninstall-PSResource": "Uninstalls a resource that was installed using PowerShellGet.",
"Unregister-PSResourceRepository": "Removes a registered repository from the local machine.",
"Update-PSModuleManifest": "Updates a module manifest file.",
"Update-PSResource": "Downloads and installs the newest version of a package already installed on the local machine.",
"Update-PSScriptFileInfo": "Updates the metadata of a script.",
"ConvertFrom-SecureString": "Converts a secure string to an encrypted standard string.",
"ConvertTo-SecureString": "Converts plain text or encrypted strings to secure strings.",
"Get-Acl": "Gets the security descriptor for a resource, such as a file or registry key.",
"Get-AuthenticodeSignature": "Gets information about the Authenticode signature for a file.",
"Get-CmsMessage": "Gets content that has been encrypted by using the Cryptographic Message Syntax format.",
"Get-Credential": "Gets a credential object based on a user name and password.",
"Get-ExecutionPolicy": "Gets the execution policies for the current session.",
"Get-PfxCertificate": "Gets information about PFX certificate files on the computer.",
"New-FileCatalog": "Creates a Windows catalog file containing cryptographic hashes for files and folders in the specified paths.",
"Protect-CmsMessage": "Encrypts content by using the Cryptographic Message Syntax format.",
"Set-Acl": "Changes the security descriptor of a specified item, such as a file or a registry key.",
"Set-AuthenticodeSignature": "Adds an Authenticode signature to a PowerShell script or other file.",
"Set-ExecutionPolicy": "Sets the PowerShell execution policies for Windows computers.",
"Test-FileCatalog": "Validates whether the hashes contained in a catalog file (.cat) match the hashes of the actual files.",
"Unprotect-CmsMessage": "Decrypts content that has been encrypted by using the Cryptographic Message Syntax format.",
"Start-ThreadJob": "Creates background jobs similar to the Start-Job cmdlet, running on threads in the current process.",
"Add-Member": "Adds custom properties and methods to an instance of a PowerShell object.",
"Add-Type": "Adds a Microsoft .NET class to a PowerShell session.",
"Clear-Variable": "Deletes the value of a variable.",
"Compare-Object": "Compares two sets of objects.",
"Convert-String": "Formats a string to match examples.",
"ConvertFrom-CliXml": "Converts a CliXml-formatted string to a custom PSObject.",
"ConvertFrom-Csv": "Converts object properties in character-separated value (CSV) format into CSV versions of the original objects.",
"ConvertFrom-Json": "Converts a JSON-formatted string to a custom object or a hash table.",
"ConvertFrom-Markdown": "Converts the contents of a string or a file to a MarkdownInfo object.",
"ConvertFrom-SddlString": "Converts a SDDL string to a custom object.",
"ConvertFrom-String": "Extracts and parses structured properties from string content.",
"ConvertFrom-StringData": "Converts a string containing one or more key and value pairs to a hash table.",
"ConvertTo-CliXml": "Converts an object to a CliXml-formatted string.",
"ConvertTo-Csv": "Converts .NET objects into a series of character-separated value (CSV) strings.",
"ConvertTo-Html": "Converts .NET objects into HTML that can be displayed in a Web browser.",
"ConvertTo-Json": "Converts an object to a JSON-formatted string.",
"ConvertTo-Xml": "Creates an XML-based representation of an object.",
"Debug-Runspace": "Starts an interactive debugging session with a runspace.",
"Disable-PSBreakpoint": "Disables the breakpoints in the current console.",
"Disable-RunspaceDebug": "Disables debugging on one or more runspaces, and releases any pending debugger stop.",
"Enable-PSBreakpoint": "Enables the breakpoints in the current console.",
"Enable-RunspaceDebug": "Enables debugging on runspaces where any breakpoint is preserved until a debugger is attached.",
"Export-Alias": "Exports information about currently defined aliases to a file.",
"Export-Clixml": "Creates an XML-based representation of an object or objects and stores it in a file.",
"Export-Csv": "Converts objects into a series of character-separated value (CSV) strings and saves the strings to a file.",
"Export-FormatData": "Saves formatting data from the current session in a formatting file.",
"Export-PSSession": "Exports commands from another session and saves them in a PowerShell module.",
"Format-Custom": "Uses a customized view to format the output.",
"Format-Hex": "Displays a file or other input as hexadecimal.",
"Format-List": "Formats the output as a list of properties in which each property appears on a new line.",
"Format-Table": "Formats the output as a table.",
"Format-Wide": "Formats objects as a wide table that displays only one property of each object.",
"Get-Alias": "Gets the aliases for the current session.",
"Get-Culture": "Gets the current culture set in the operating system.",
"Get-Date": "Gets the current date and time.",
"Get-Error": "Gets and displays the most recent error messages from the current session.",
"Get-Event": "Gets the events in the event queue.",
"Get-EventSubscriber": "Gets the event subscribers in the current session.",
"Get-FileHash": "Computes the hash value for a file by using a specified hash algorithm.",
"Get-FormatData": "Gets the formatting data in the current session.",
"Get-Host": "Gets an object that represents the current host program.",
"Get-MarkdownOption": "Returns the current colors and styles used for rendering Markdown content in the console.",
"Get-Member": "Gets the properties and methods of objects.",
"Get-PSBreakpoint": "Gets the breakpoints that are set in the current session.",
"Get-PSCallStack": "Displays the current call stack.",
"Get-Random": "Gets a random number, or selects objects randomly from a collection.",
"Get-Runspace": "Gets active runspaces within a PowerShell host process.",
"Get-RunspaceDebug": "Shows runspace debugging options.",
"Get-SecureRandom": "Gets a random number, or selects objects randomly from a collection, using a cryptographically secure generator.",
"Get-TraceSource": "Gets PowerShell components that are instrumented for tracing.",
"Get-TypeData": "Gets the extended type data in the current session.",
"Get-UICulture": "Gets the current UI culture settings in the operating system.",
"Get-Unique": "Returns unique items from a sorted list.",
"Get-Uptime": "Gets the TimeSpan since the last boot.",
"Get-Variable": "Gets the variables in the current console.",
"Get-Verb": "Gets approved PowerShell verbs.",
"Group-Object": "Groups objects that contain the same value for specified properties.",
"Import-Alias": "Imports an alias list from a file.",
"Import-Clixml": "Imports a CLIXML file and creates corresponding objects in PowerShell.",
"Import-Csv": "Creates table-like custom objects from the items in a character-separated value (CSV) file.",
"Import-LocalizedData": "Imports language-specific data into scripts and functions based on the UI culture.",
"Import-PowerShellDataFile": "Imports values from a .psd1 file without invoking its contents.",
"Import-PSSession": "Imports commands from another session into the current session.",
"Invoke-Expression": "Runs commands or expressions on the local computer.",
"Invoke-RestMethod": "Sends an HTTP or HTTPS request to a RESTful web service.",
"Invoke-WebRequest": "Gets content from a web page on the internet.",
"Join-String": "Combines objects from the pipeline into a single string.",
"Measure-Command": "Measures the time it takes to run script blocks and cmdlets.",
"Measure-Object": "Calculates the numeric properties of objects, and the characters, words, and lines in string objects.",
"New-Alias": "Creates a new alias.",
"New-Event": "Creates a new event.",
"New-Guid": "Creates a GUID.",
"New-Object": "Creates an instance of a Microsoft .NET Framework or COM object.",
"New-TemporaryFile": "Creates a temporary file.",
"New-TimeSpan": "Creates a TimeSpan object.",
"New-Variable": "Creates a new variable.",
"Out-File": "Sends output to a file.",
"Out-GridView": "Sends output to an interactive table in a separate window.",
"Out-Printer": "Sends output to a printer.",
"Out-String": "Outputs input objects as a string.",
"Read-Host": "Reads a line of input from the console.",
"Register-EngineEvent": "Subscribes to events that are generated by the PowerShell engine and by the New-Event cmdlet.",
"Register-ObjectEvent": "Subscribes to the events that are generated by a Microsoft .NET Framework object.",
"Remove-Alias": "Remove an alias from the current session.",
"Remove-Event": "Deletes events from the event queue.",
"Remove-PSBreakpoint": "Deletes breakpoints from the current console.",
"Remove-TypeData": "Deletes extended types from the current session.",
"Remove-Variable": "Deletes a variable and its value.",
"Select-Object": "Selects objects or object properties.",
"Select-String": "Finds text in strings and files.",
"Select-Xml": "Finds text in an XML string or document.",
"Send-MailMessage": "Sends an email message (obsolete: no secure connection guarantee).",
"Set-Alias": "Creates or changes an alias for a cmdlet or other command in the current PowerShell session.",
"Set-Date": "Changes the system time on the computer to a time that you specify.",
"Set-MarkdownOption": "Sets the colors and styles used for rendering Markdown content in the console.",
"Set-PSBreakpoint": "Sets a breakpoint on a line, command, or variable.",
"Set-TraceSource": "Configures, starts, and stops a trace of PowerShell components.",
"Set-Variable": "Sets the value of a variable. Creates the variable if one with the requested name does not exist.",
"Show-Command": "Displays PowerShell command information in a graphical window.",
"Show-Markdown": "Shows a Markdown file or string in the console in a friendly way using VT100 escape sequences or in a browser.",
"Sort-Object": "Sorts objects by property values.",
"Start-Sleep": "Suspends the activity in a script or session for the specified period of time.",
"Tee-Object": "Saves command output in a file or variable and also sends it down the pipeline.",
"Test-Json": "Tests whether a string is a valid JSON document.",
"Trace-Command": "Configures and starts a trace of the specified expression or command.",
"Unblock-File": "Unblocks files that were downloaded from the internet.",
"Unregister-Event": "Cancels an event subscription.",
"Update-FormatData": "Updates the formatting data in the current session.",
"Update-List": "Adds items to and removes items from a property value that contains a collection of objects.",
"Update-TypeData": "Updates the extended type data in the session.",
"Wait-Debugger": "Stops a script in the debugger before running the next statement in the script.",
"Wait-Event": "Waits until a particular event is raised before continuing to run.",
"Write-Debug": "Writes a debug message to the console.",
"Write-Error": "Writes an object to the error stream.",
"Write-Host": "Writes customized output to a host.",
"Write-Information": "Specifies how PowerShell handles information stream data for a command.",
"Write-Output": "Writes the specified objects to the pipeline.",
"Write-Progress": "Displays a progress bar within a PowerShell command window.",
"Write-Verbose": "Writes text to the verbose message stream.",
"Write-Warning": "Writes a warning message.",
"Connect-WSMan": "Connects to the WinRM service on a remote computer.",
"Disable-WSManCredSSP": "Disables CredSSP authentication on a computer.",
"Disconnect-WSMan": "Disconnects the client from the WinRM service on a remote computer.",
"Enable-WSManCredSSP": "Enables CredSSP authentication on a computer.",
"Get-WSManCredSSP": "Gets the Credential Security Support Provider-related configuration for the client.",
"Get-WSManInstance": "Displays management information for a resource instance specified by a Resource URI.",
"Invoke-WSManAction": "Invokes an action on the object that is specified by the Resource URI and by the selectors.",
"New-WSManInstance": "Creates a new instance of a management resource.",
"New-WSManSessionOption": "Creates session option hash table to use as input parameters for WS-Management cmdlets.",
"Remove-WSManInstance": "Deletes a management resource instance.",
"Set-WSManInstance": "Modifies the management information that is related to a resource.",
"Set-WSManQuickConfig": "Configures the local computer for remote management.",
"Test-WSMan": "Tests whether the WinRM service is running on a local or remote computer.",
"Find-Package": "Finds software packages in available package sources.",
"Find-PackageProvider": "Returns a list of Package Management package providers available for installation.",
"Get-Package": "Returns a list of all software packages that were installed with PackageManagement.",
"Get-PackageProvider": "Returns a list of package providers that are connected to Package Management.",
"Get-PackageSource": "Gets a list of package sources that are registered for a package provider.",
"Import-PackageProvider": "Adds Package Management package providers to the current session.",
"Install-Package": "Installs one or more software packages.",
"Install-PackageProvider": "Installs one or more Package Management package providers.",
"Register-PackageSource": "Adds a package source for a specified package provider.",
"Save-Package": "Saves packages to the local computer without installing them.",
"Set-PackageSource": "Replaces a package source for a specified package provider.",
"Uninstall-Package": "Uninstalls one or more software packages.",
"Unregister-PackageSource": "Removes a registered package source.",
"Find-Command": "Finds PowerShell commands in modules.",
"Find-DscResource": "Finds Desired State Configuration (DSC) resources.",
"Find-Module": "Finds modules in a repository that match specified criteria.",
"Find-RoleCapability": "Finds role capabilities in modules.",
"Find-Script": "Finds a script.",
"Get-InstalledModule": "Gets a list of modules on the computer that were installed by PowerShellGet.",
"Get-InstalledScript": "Gets an installed script.",
"Get-PSRepository": "Gets PowerShell repositories.",
"Install-Module": "Downloads one or more modules from a repository, and installs them on the local computer.",
"Install-Script": "Installs a script.",
"New-ScriptFileInfo": "Creates a script file with metadata.",
"Publish-Module": "Publishes a specified module from the local computer to an online gallery.",
"Publish-Script": "Publishes a script.",
"Register-PSRepository": "Registers a PowerShell repository.",
"Save-Module": "Saves a module and its dependencies on the local computer but doesn't install the module.",
"Save-Script": "Saves a script.",
"Set-PSRepository": "Sets values for a registered repository.",
"Test-ScriptFileInfo": "Validates a comment block for a script.",
"Uninstall-Module": "Uninstalls a module.",
"Uninstall-Script": "Uninstalls a script.",
"Unregister-PSRepository": "Unregisters a repository.",
"Update-Module": "Downloads and installs the newest version of specified modules from an online gallery to the local computer.",
"Update-ModuleManifest": "Updates a module manifest file.",
"Update-Script": "Updates a script.",
"Update-ScriptFileInfo": "Updates information for a script.",
"Get-NetIPAddress": "Gets the IP address configuration.",
"New-NetIPAddress": "Creates and configures an IP address.",
"Set-NetIPAddress": "Modifies the configuration of an IP address.",
"Remove-NetIPAddress": "Removes an IP address and its configuration.",
"Get-NetIPConfiguration": "Gets IP network configuration (addresses, gateways and DNS servers per interface).",
"Get-NetIPInterface": "Gets an IP interface.",
"Set-NetIPInterface": "Modifies an IP interface.",
"Get-NetRoute": "Gets the IP route information from the IP routing table.",
"New-NetRoute": "Creates a route in the IP routing table.",
"Set-NetRoute": "Modifies properties of IP routes.",
"Remove-NetRoute": "Deletes one or more IP routes from the IP routing table.",
"Get-NetTCPConnection": "Gets TCP connections.",
"Get-NetUDPEndpoint": "Gets statistics for UDP endpoints.",
"Get-NetTCPSetting": "Gets TCP settings and configurations.",
"Get-NetNeighbor": "Gets neighbor cache entries (ARP / ND).",
"Remove-NetNeighbor": "Removes neighbor cache entries.",
"Get-NetIPv4Protocol": "Gets information about the IPv4 protocol configuration.",
"Get-NetIPv6Protocol": "Gets information about the IPv6 protocol configuration.",
"Get-NetPrefixPolicy": "Gets prefix policies for each prefix.",
"Get-NetCompartment": "Gets all network compartments in the protocol stack.",
"Test-NetConnection": "Displays diagnostic information for a connection (ping, TCP port test, trace route).",
"Find-NetRoute": "Finds the best local IP address and route to reach a remote address.",
"Get-NetAdapter": "Gets the basic network adapter properties.",
"Enable-NetAdapter": "Enables a network adapter.",
"Disable-NetAdapter": "Disables a network adapter.",
"Restart-NetAdapter": "Restarts a network adapter by disabling and then re-enabling it.",
"Rename-NetAdapter": "Renames a network adapter.",
"Set-NetAdapter": "Sets the basic network adapter properties.",
"Get-NetAdapterAdvancedProperty": "Gets the advanced properties for a network adapter.",
"Set-NetAdapterAdvancedProperty": "Sets the advanced properties of a network adapter.",
"Reset-NetAdapterAdvancedProperty": "Resets the advanced properties of a network adapter to their factory default values.",
"Get-NetAdapterBinding": "Gets a list of bindings for a network adapter.",
"Enable-NetAdapterBinding": "Enables a binding to a network adapter.",
"Disable-NetAdapterBinding": "Disables a binding to a network adapter.",
"Get-NetAdapterStatistics": "Gets networking statistics from a network adapter.",
"Get-NetAdapterPowerManagement": "Gets the power management features of a network adapter.",
"Set-NetAdapterPowerManagement": "Sets the power management properties on a network adapter.",
"Get-NetAdapterHardwareInfo": "Gets the PCI configuration information of a network adapter.",
"Get-NetAdapterVmq": "Gets the VMQ properties of a network adapter.",
"Get-NetAdapterRss": "Gets the receive side scaling (RSS) properties of a network adapter.",
"Get-NetConnectionProfile": "Gets a connection profile (network category of each connected network).",
"Set-NetConnectionProfile": "Changes the network category of a connection profile (Public, Private).",
"Get-NetFirewallRule": "Retrieves firewall rules from the target computer.",
"New-NetFirewallRule": "Creates a new inbound or outbound firewall rule and adds the rule to the target computer.",
"Set-NetFirewallRule": "Modifies existing firewall rules.",
"Remove-NetFirewallRule": "Deletes one or more firewall rules that match the specified criteria.",
"Enable-NetFirewallRule": "Enables a previously disabled firewall rule.",
"Disable-NetFirewallRule": "Disables a firewall rule.",
"Rename-NetFirewallRule": "Renames a single IPsec rule.",
"Copy-NetFirewallRule": "Copies an entire firewall rule, and associated filters, to the same or to a different policy store.",
"Show-NetFirewallRule": "Displays all of the existing IPsec rules and associated objects in a fully expanded view.",
"Get-NetFirewallProfile": "Displays settings that apply to the per-profile configurations of the Windows Firewall.",
"Set-NetFirewallProfile": "Configures settings that apply to the per-profile configurations of the Windows Firewall.",
"Get-NetFirewallSetting": "Retrieves the global firewall settings of the target computer.",
"Set-NetFirewallSetting": "Modifies the global firewall settings of the target computer.",
"Get-NetFirewallPortFilter": "Retrieves port filter objects associated with the input firewall rules.",
"Set-NetFirewallPortFilter": "Modifies port filter objects, thereby modifying the protocol and port conditions of the firewall rules.",
"Get-NetFirewallApplicationFilter": "Retrieves application filter objects associated with the input firewall rules.",
"Set-NetFirewallApplicationFilter": "Modifies the application filter objects, thereby modifying the program conditions of the firewall rules.",
"Get-NetFirewallAddressFilter": "Retrieves address filter objects associated with the input firewall rules.",
"Set-NetFirewallAddressFilter": "Modifies address filter objects, thereby modifying the local and remote address conditions of the firewall rules.",
"Get-NetFirewallServiceFilter": "Retrieves service filter objects associated with the input firewall rules.",
"Get-NetFirewallSecurityFilter": "Retrieves security filter objects associated with the input firewall rules.",
"Get-NetFirewallInterfaceFilter": "Retrieves interface filter objects associated with the input firewall rules.",
"Resolve-DnsName": "Performs a DNS query resolution for the specified name.",
"Get-DnsClient": "Retrieves details of the network interfaces configured on a specified computer.",
"Set-DnsClient": "Sets the interface-specific DNS client configurations on the computer.",
"Get-DnsClientServerAddress": "Gets DNS server IP addresses from the TCP/IP properties on an interface.",
"Set-DnsClientServerAddress": "Sets DNS server addresses associated with the TCP/IP properties on an interface.",
"Get-DnsClientCache": "Retrieves the contents of the DNS client cache.",
"Clear-DnsClientCache": "Clears the contents of the DNS client cache.",
"Get-DnsClientGlobalSetting": "Retrieves global DNS client settings like the suffix search list.",
"Set-DnsClientGlobalSetting": "Sets the DNS client global, non-interface specific, settings.",
"Register-DnsClient": "Registers all of the IP addresses on the computer onto the configured DNS server.",
"Get-DnsClientNrptPolicy": "Retrieves the NRPT policy that is configured on the computer.",
"Get-DnsClientNrptRule": "Retrieves the DNS client NRPT rules.",
"Add-DnsClientNrptRule": "Adds a rule to the NRPT.",
"Remove-DnsClientNrptRule": "Removes the specified DNS client NRPT rule.",
"Get-SmbShare": "Retrieves the SMB shares on the computer.",
"New-SmbShare": "Creates an SMB share.",
"Set-SmbShare": "Modifies the properties of the SMB share.",
"Remove-SmbShare": "Deletes the specified SMB shares.",
"Get-SmbShareAccess": "Retrieves the ACL of the SMB share.",
"Grant-SmbShareAccess": "Adds an allow ACE for a trustee to the security descriptor of the SMB share.",
"Revoke-SmbShareAccess": "Removes all of the allow ACEs for a trustee from the security descriptor of the SMB share.",
"Block-SmbShareAccess": "Adds a deny ACE for a trustee to the security descriptor of the SMB share.",
"Get-SmbMapping": "Retrieves the SMB client directory mappings created for a server.",
"New-SmbMapping": "Creates an SMB mapping (mapped drive).",
"Remove-SmbMapping": "Removes the SMB mapping to an SMB share.",
"Get-SmbConnection": "Retrieves the connections established from the SMB client to the SMB servers.",
"Get-SmbSession": "Retrieves information about the SMB sessions that are currently established between the SMB server and the associated clients.",
"Close-SmbSession": "Ends forcibly the SMB session.",
"Get-SmbOpenFile": "Retrieves basic information about the files that are open on behalf of the clients of the SMB server.",
"Close-SmbOpenFile": "Closes a file that is open by one of the clients of the SMB server.",
"Get-SmbServerConfiguration": "Retrieves the SMB server configuration.",
"Set-SmbServerConfiguration": "Sets the SMB Service configuration.",
"Get-SmbClientConfiguration": "Retrieves the SMB client configuration.",
"Set-SmbClientConfiguration": "Sets the SMB client configuration.",
"Get-ScheduledTask": "Gets the task definition object of a scheduled task that is registered on the local computer.",
"Register-ScheduledTask": "Registers a scheduled task definition on a local computer.",
"Unregister-ScheduledTask": "Unregisters a scheduled task.",
"Set-ScheduledTask": "Modifies a scheduled task.",
"Start-ScheduledTask": "Starts one or more instances of a scheduled task.",
"Stop-ScheduledTask": "Stops all running instances of a task.",
"Enable-ScheduledTask": "Enables a scheduled task.",
"Disable-ScheduledTask": "Disables a scheduled task.",
"Get-ScheduledTaskInfo": "Gets run-time information for a scheduled task (last and next run time, last result).",
"Export-ScheduledTask": "Exports a scheduled task as an XML string.",
"New-ScheduledTask": "Creates a scheduled task instance.",
"New-ScheduledTaskAction": "Creates a scheduled task action.",
"New-ScheduledTaskTrigger": "Creates a scheduled task trigger object.",
"New-ScheduledTaskPrincipal": "Creates an object that contains a scheduled task principal.",
"New-ScheduledTaskSettingsSet": "Creates a new scheduled task settings object.",
"Get-ClusteredScheduledTask": "Gets clustered scheduled tasks for a failover cluster.",
"Get-Disk": "Gets one or more disks visible to the operating system.",
"Initialize-Disk": "Initializes a RAW disk for first time use, enabling the disk to be formatted and used to store data.",
"Clear-Disk": "Cleans a disk by removing all partition information and un-initializing it, erasing all data on the disk.",
"Set-Disk": "Takes a disk offline or online, makes it read-only or writable, or changes its partition style.",
"Update-Disk": "Updates cached information about the specified disk object.",
"Get-PhysicalDisk": "Gets a list of all PhysicalDisk objects visible across any available Storage Management Providers.",
"Get-Partition": "Returns a list of all partition objects visible on all disks, or optionally a filtered list.",
"New-Partition": "Creates a new partition on an existing Disk object.",
"Remove-Partition": "Deletes the specified Partition object on an existing disk and any underlying Volume objects.",
"Resize-Partition": "Resizes a partition and the underlying file system.",
"Set-Partition": "Sets attributes of a partition, such as active, read-only, and offline states.",
"Get-PartitionSupportedSize": "Returns information on supported partition sizes for the specified Disk object.",
"Add-PartitionAccessPath": "Adds an access path such as a drive letter or folder to a partition.",
"Remove-PartitionAccessPath": "Removes an access path such as a drive letter or folder from a partition.",
"Get-Volume": "Gets the specified Volume object, or all Volume objects if no filter is provided.",
"Format-Volume": "Formats one or more existing volumes or a new volume on an existing partition.",
"Optimize-Volume": "Optimizes a volume (defragmentation, TRIM, slab consolidation).",
"Repair-Volume": "Performs repairs on a volume.",
"Set-Volume": "Sets or changes the file system label of an existing volume.",
"Get-DiskImage": "Gets one or more disk image objects (virtual hard disk or ISO).",
"Mount-DiskImage": "Mounts a previously created disk image (virtual hard disk or ISO), making it appear as a normal disk.",
"Dismount-DiskImage": "Dismounts a disk image (virtual hard disk or ISO) so that it can no longer be accessed as a disk.",
"Get-StoragePool": "Gets a specific storage pool, or a set of StoragePool objects.",
"Get-VirtualDisk": "Returns a list of VirtualDisk objects.",
"Get-StorageReliabilityCounter": "Gets storage reliability counters (temperature, errors, wear) for a disk.",
"Get-MpComputerStatus": "Gets the status of antimalware software on the computer.",
"Get-MpPreference": "Gets preferences for the Windows Defender scans and updates.",
"Set-MpPreference": "Configures preferences for Windows Defender scans and updates.",
"Add-MpPreference": "Modifies settings for Windows Defender (adds exclusions and other list values).",
"Remove-MpPreference": "Removes exclusions or default actions.",
"Start-MpScan": "Starts a scan on a computer.",
"Start-MpWDOScan": "Starts a Windows Defender offline scan.",
"Update-MpSignature": "Updates the antimalware definitions on a computer.",
"Get-MpThreat": "Gets the history of threats detected on the computer.",
"Get-MpThreatCatalog": "Gets known threats from the definitions catalog.",
"Get-MpThreatDetection": "Gets active and past malware threats that Windows Defender detected.",
"Remove-MpThreat": "Removes active threats from a computer.",
"Get-Certificate": "Submits a certificate request to an enrollment server and installs the response or retrieves a certificate for a previously submitted request.",
"New-SelfSignedCertificate": "Creates a new self-signed certificate for testing purposes.",
"Import-Certificate": "Imports one or more certificates into a certificate store.",
"Export-Certificate": "Exports a certificate from a certificate store into a file.",
"Import-PfxCertificate": "Imports certificates and private keys from a Personal Information Exchange (PFX) file to the destination store.",
"Export-PfxCertificate": "Exports a certificate or a PFXData object to a Personal Information Exchange (PFX) file.",
"Test-Certificate": "Verifies a certificate including its chain and revocation status.",
"Get-PfxData": "Extracts the content of a Personal Information Exchange (PFX) file into a structure.",
"Switch-Certificate": "Marks a certificate as replaced by another one.",
"Get-WindowsOptionalFeature": "Gets information about optional features in a Windows image.",
"Enable-WindowsOptionalFeature": "Enables a feature in a Windows image.",
"Disable-WindowsOptionalFeature": "Disables a feature in a Windows image.",
"Get-WindowsCapability": "Gets Windows capabilities for an image or a running operating system.",
"Add-WindowsCapability": "Installs a Windows capability package on the specified operating system image.",
"Remove-WindowsCapability": "Uninstalls a Windows capability package from an image.",
"Get-WindowsPackage": "Gets information about packages in a Windows image.",
"Add-WindowsPackage": "Adds a single .cab or .msu file to a Windows image.",
"Remove-WindowsPackage": "Removes a package from a Windows image.",
"Get-AppxProvisionedPackage": "Gets information about app packages (.appx) in an image that will be installed for each new user.",
"Add-AppxProvisionedPackage": "Adds an app package (.appx) that will install for each new user to a Windows image.",
"Remove-AppxProvisionedPackage": "Removes an app package (.appx) from a Windows image.",
"Get-WindowsImage": "Gets information about a Windows image in a WIM or VHD file.",
"Mount-WindowsImage": "Mounts a Windows image in a WIM or VHD file to a directory on the local computer.",
"Dismount-WindowsImage": "Dismounts a Windows image from the directory it is mapped to.",
"Repair-WindowsImage": "Repairs a Windows image in a WIM or VHD file (or the running OS with -Online).",
"Get-WindowsDriver": "Displays information about drivers in a Windows image.",
"Add-WindowsDriver": "Adds a driver to an offline Windows image.",
"Remove-WindowsDriver": "Removes a driver from an offline Windows image.",
"Get-WindowsEdition": "Gets edition information about a Windows image.",
"Set-WindowsEdition": "Changes a Windows image to a higher edition.",
"Set-WindowsProductKey": "Sets the product key for the Windows image.",
"Export-WindowsImage": "Exports a copy of the specified image to another image file.",
"Expand-WindowsImage": "Applies an image to a specified location.",
"New-WindowsImage": "Captures an image of a drive to a new WIM file.",
"Get-BitLockerVolume": "Gets information about volumes that BitLocker can protect.",
"Enable-BitLocker": "Enables encryption for a BitLocker volume.",
"Disable-BitLocker": "Disables BitLocker encryption for a volume.",
"Suspend-BitLocker": "Suspends BitLocker encryption for the specified volume.",
"Resume-BitLocker": "Restores encryption on a volume.",
"Lock-BitLocker": "Prevents access to encrypted data on a BitLocker volume.",
"Unlock-BitLocker": "Restores access to data on a BitLocker volume.",
"Add-BitLockerKeyProtector": "Adds a key protector for a BitLocker volume.",
"Remove-BitLockerKeyProtector": "Removes a key protector for a BitLocker volume.",
"Backup-BitLockerKeyProtector": "Saves a key protector for a BitLocker volume in AD DS.",
"BackupToAAD-BitLockerKeyProtector": "Saves a key protector for a BitLocker volume in Microsoft Entra ID.",
"Enable-BitLockerAutoUnlock": "Enables automatic unlocking for a BitLocker volume.",
"Disable-BitLockerAutoUnlock": "Disables automatic unlocking for a BitLocker volume.",
"Clear-BitLockerAutoUnlock": "Removes BitLocker automatic unlocking keys.",
"Get-Tpm": "Gets an object that contains information about a TPM.",
"Initialize-Tpm": "Performs part of the provisioning process for a TPM.",
"Clear-Tpm": "Resets TPM to its default state.",
"Get-TpmEndorsementKeyInfo": "Gets information about the endorsement key and certificates of the TPM.",
"Get-TpmSupportedFeature": "Gets a list of features that the TPM supports.",
"Enable-TpmAutoProvisioning": "Enables TPM auto-provisioning.",
"Disable-TpmAutoProvisioning": "Disables TPM auto-provisioning.",
"Confirm-SecureBootUEFI": "Confirms that Secure Boot is enabled by checking the Secure Boot status on UEFI computers.",
"Get-SecureBootPolicy": "Gets the publisher GUID and the policy version of the Secure Boot configuration policy.",
"Get-SecureBootUEFI": "Gets information about a specified UEFI environment variable.",
"Set-SecureBootUEFI": "Sets the UEFI variables that are related to Secure Boot.",
"Format-SecureBootUEFI": "Formats certificates or hashes into a content object for Set-SecureBootUEFI.",
"Get-PnpDevice": "Returns information about PnP devices.",
"Enable-PnpDevice": "Enables a PnP device.",
"Disable-PnpDevice": "Disables a PnP device.",
"Get-PnpDeviceProperty": "Gets device properties for a PnP device.",
"Get-WinSystemLocale": "Gets the system locale (the language for non-Unicode programs).",
"Set-WinSystemLocale": "Sets the system locale (the language for non-Unicode programs) for the current computer.",
"Get-WinUserLanguageList": "Gets the language list for the current user account.",
"Set-WinUserLanguageList": "Sets the language list and associated properties for the current user account.",
"New-WinUserLanguageList": "Creates an object that contains a list of language identifiers.",
"Get-WinHomeLocation": "Gets the Windows GeoID home location setting for the current user account.",
"Set-WinHomeLocation": "Sets the home location setting for the current user account.",
"Get-WinUILanguageOverride": "Gets the Windows UI language override for the current user account.",
"Set-WinUILanguageOverride": "Sets the user interface language override for the current user account.",
"Get-WinCultureFromLanguageListOptOut": "Gets whether the culture settings follow the language list.",
"Set-Culture": "Sets the user culture for the current user account.",
"Get-WinDefaultInputMethodOverride": "Gets the default input method override setting for the current user account.",
"Set-WinDefaultInputMethodOverride": "Sets the default input method override for the current user account.",
"Copy-UserInternationalSettingsToSystem": "Copies the current user's international settings to the Welcome screen, system accounts and new users.",
"Get-AppxPackage": "Gets a list of the app packages that are installed in a user profile.",
"Add-AppxPackage": "Adds a signed app package to a user account.",
"Remove-AppxPackage": "Removes an app package from one or more user accounts.",
"Reset-AppxPackage": "Resets app package data, as if the app had just been installed.",
"Get-AppxPackageManifest": "Gets the manifest of an app package.",
"Move-AppxPackage": "Moves a package from its current location to another appx volume.",
"Get-AppxLastError": "Gets the last error reported in the app package installation logs.",
"Get-AppxLog": "Gets an app package installation log.",
"Get-WindowsUpdateLog": "Merges Windows Update .etl files into a single log file.",
"Get-Printer": "Retrieves a list of printers installed on a computer.",
"Add-Printer": "Adds a printer to the specified computer.",
"Set-Printer": "Updates the configuration of an existing printer.",
"Remove-Printer": "Removes a printer from the specified computer.",
"Rename-Printer": "Renames the specified printer.",
"Get-PrinterDriver": "Retrieves the list of printer drivers installed on the specified computer.",
"Add-PrinterDriver": "Installs a printer driver on the specified computer.",
"Remove-PrinterDriver": "Deletes printer driver from the specified computer.",
"Get-PrinterPort": "Retrieves a list of printer ports installed on the specified computer.",
"Add-PrinterPort": "Installs a printer port on the specified computer.",
"Remove-PrinterPort": "Removes the specified printer port from the specified computer.",
"Get-PrintJob": "Retrieves a list of print jobs in the specified printer.",
"Remove-PrintJob": "Removes a print job on the specified printer.",
"Restart-PrintJob": "Restarts a print job on the specified printer.",
"Suspend-PrintJob": "Suspends a print job on the specified printer.",
"Resume-PrintJob": "Resumes a suspended print job.",
"Get-PrintConfiguration": "Gets the configuration information of a printer.",
"Set-PrintConfiguration": "Sets the configuration information for the specified printer.",
"Get-PrinterProperty": "Retrieves printer properties for the specified printer.",
"Get-DeliveryOptimizationStatus": "Returns details for active Delivery Optimization downloads and uploads.",
"Get-DeliveryOptimizationPerfSnap": "Returns a performance snapshot of Delivery Optimization.",
"Get-DeliveryOptimizationLog": "Retrieves and parses Delivery Optimization log files.",
"Delete-DeliveryOptimizationCache": "Deletes the Delivery Optimization cache.",
"Install-Language": "Installs a language pack and its features on the device.",
"Uninstall-Language": "Uninstalls a language pack and its features from the device.",
"Get-InstalledLanguage": "Returns the language packs and their features installed on the device.",
"Get-SystemPreferredUILanguage": "Returns the system-preferred UI language.",
"Set-SystemPreferredUILanguage": "Sets the system-preferred UI language.",
"Export-StartLayout": "Exports the layout of the Start screen.",
"Import-StartLayout": "Imports the layout of the Start into a mounted Windows image.",
"Get-StartApps": "Gets the names and AppIDs of installed apps.",
"Get-WindowsErrorReporting": "Gets the status of Windows Error Reporting.",
"Enable-WindowsErrorReporting": "Enables Windows Error Reporting.",
"Disable-WindowsErrorReporting": "Disables Windows Error Reporting.",
"Add-VpnConnection": "Adds a VPN connection to the Connection Manager phone book.",
"Get-VpnConnection": "Retrieves the specified VPN connection profile information.",
"Set-VpnConnection": "Changes the configuration settings of an existing VPN connection profile.",
"Remove-VpnConnection": "Removes a VPN connection profile.",
"Add-VpnConnectionRoute": "Adds a route to a VPN connection.",
"Remove-VpnConnectionRoute": "Removes a route from a VPN connection.",
"Get-NCSIPolicyConfiguration": "Gets the Network Connectivity Status Indicator (NCSI) policy configuration.",
"Get-DAConnectionStatus": "Gets the DirectAccess connection status."
}
+25 -2
View File
@@ -43,6 +43,7 @@ import type {
GroupFieldValueDto,
GroupRuleSet,
GroupRunDto,
PowerRequest,
JobDto,
JobOutputRecordDto,
LogTailDto,
@@ -83,6 +84,7 @@ import type {
VaultFolderDto,
VaultSecretDto
} from './types';
import type { ScriptEngine, SnippetDto } from './types';
export interface AgentUpgradeQuery {
clientId?: string;
@@ -110,6 +112,8 @@ export interface SaveScriptBody {
runFromFile?: boolean;
cleanUpAfterRun?: boolean;
setWorkingDirectory?: boolean;
runAsUser?: boolean;
runAsEachUser?: boolean;
restartAfterRun?: RestartAfterRun;
restartDelaySeconds?: number;
restartWarningSeconds?: number;
@@ -123,6 +127,13 @@ export interface SaveFunctionBody {
folder?: string;
}
export interface SaveSnippetBody {
name: string;
description?: string;
language: ScriptEngine;
content: string;
}
export interface SaveSecretsProviderBody {
name: string;
kind: string;
@@ -298,8 +309,10 @@ export const api = {
devices: () => request<DeviceDto[]>('/api/devices'),
device: (clientId: string) => request<DeviceDetailDto>(`/api/devices/${enc(clientId)}`),
refreshInventory: (clientId: string) => request<void>(`/api/devices/${enc(clientId)}/inventory`, { method: 'POST' }),
openShell: (clientId: string, body: { browserSessionId: string; cols: number; rows: number; shell?: string }) =>
request<CreateShellResponse>(`/api/devices/${enc(clientId)}/shell`, json('POST', body)),
openShell: (
clientId: string,
body: { browserSessionId: string; cols: number; rows: number; shell?: string; asUser?: boolean; user?: string }
) => request<CreateShellResponse>(`/api/devices/${enc(clientId)}/shell`, json('POST', body)),
/** Remote View: a session and its first one-time socket ticket. */
openScreen: (clientId: string, body: { viewOnly: boolean; monitor?: number }) =>
request<CreateScreenResponse>(`/api/devices/${enc(clientId)}/screen`, json('POST', body)),
@@ -408,6 +421,12 @@ export const api = {
updateFunction: (id: string, body: SaveFunctionBody) => request<FunctionModuleDto>(`/api/functions/${id}`, json('PUT', body)),
deleteFunction: (id: string) => request<void>(`/api/functions/${id}`, { method: 'DELETE' }),
// Snippets
createSnippet: (body: SaveSnippetBody) => request<SnippetDto>('/api/snippets', json('POST', body)),
updateSnippet: (id: string, body: SaveSnippetBody) => request<SnippetDto>(`/api/snippets/${id}`, json('PUT', body)),
deleteSnippet: (id: string) => request<void>(`/api/snippets/${id}`, { method: 'DELETE' }),
copySnippet: (id: string, name?: string) => request<SnippetDto>(`/api/snippets/${id}/copy`, json('POST', { name })),
// Folders of scripts, function modules and sequences
folders: (library: FolderLibrary) => request<string[]>(`/api/${library}/folders`),
createFolder: (library: FolderLibrary, path: string) => request<FolderDto>(`/api/${library}/folders`, json('POST', { path })),
@@ -430,6 +449,8 @@ export const api = {
executions: (limit = 50) => request<ExecutionSummaryDto[]>(`/api/executions?limit=${limit}`),
/** Runs a script on any mix of devices and groups as one execution. */
runScript: (body: RunScriptBody) => request<GroupRunDto>('/api/jobs', json('POST', body)),
/** Restart or Shut Down devices and groups' members as one run. */
power: (body: PowerRequest) => request<GroupRunDto>('/api/power', json('POST', body)),
/** Cancels the run's jobs that have not been sent yet. */
cancelWaiting: (runId: string) => request<{ cancelled: number }>(`/api/executions/${runId}/cancel-waiting`, json('POST', {})),
@@ -644,6 +665,8 @@ export const keys = {
scripts: '/api/scripts',
script: (id: string) => `/api/scripts/${id}`,
functions: '/api/functions',
/** The built-in snippets and the library's own. */
snippets: '/api/snippets',
/** Every folder path of a library, for its tree. */
folders: (library: FolderLibrary) => `/api/${library}/folders`,
vaultFolders: '/api/secrets/vault/folders',
+45 -1
View File
@@ -7,6 +7,25 @@ export type JobState = 'queued' | 'dispatched' | 'running' | 'succeeded' | 'fail
/** Restart After Run: off, after every run, or when the script asks (exit 3010 or 1641; 194 on linux/macOS). */
export type RestartAfterRun = 'off' | 'always' | 'whenRequested';
/** Restart or Shut Down from the console. */
export type PowerAction = 'restart' | 'shutDown';
/** POST /api/power: a run of the built-in power script on devices and groups' members. */
export interface PowerRequest {
action: PowerAction;
clientIds?: string[];
groupIds?: string[];
delaySeconds?: number;
warningSeconds?: number;
/** Windows: pending updates install on the way down; off, they wait. */
installUpdates?: boolean;
onlineOnly?: boolean;
staggerSeconds?: number;
staggerBatchSize?: number;
excludeClientIds?: string[];
excludeGroupIds?: string[];
}
/** One restart setting as a value (a sequence step's Restart On Completion). */
export interface RestartSettings {
mode: RestartAfterRun;
@@ -53,7 +72,7 @@ export type AgentInstallKind = 'msi' | 'portable';
// ── Device grouping ───────────────────────────────────────────────────
/** Folders hold no devices of their own; every kind includes its nested groups' devices. */
export type GroupKind = 'static' | 'dynamic' | 'folder';
export type GroupKind = 'static' | 'dynamic' | 'folder' | 'script';
export type RuleCombine = 'and' | 'or';
export type RuleOperator =
| 'equals'
@@ -1198,6 +1217,10 @@ export interface ScriptDto {
cleanUpAfterRun?: boolean;
/** Start a file-run script in its job folder. */
setWorkingDirectory?: boolean;
/** Run as the device's signed-in user instead of the agent's account. */
runAsUser?: boolean;
/** With runAsUser: once for each signed-in user. */
runAsEachUser?: boolean;
restartAfterRun?: RestartAfterRun;
/** Seconds before the restart (0 to 3600). */
restartDelaySeconds?: number;
@@ -1304,6 +1327,23 @@ export interface FunctionModuleDto {
folder: string;
}
/**
* A snippet of the shared library. `content` marks tab stops as ${1:default}, ${1} or ${1|a,b|}
* (see utils/monaco/snippets). A built-in ships with the server: read-only, copyable, no times or authors.
*/
export interface SnippetDto {
id: string;
name: string;
description?: string | null;
language: ScriptEngine;
content: string;
builtIn: boolean;
createdUtc?: string | null;
createdBy?: string | null;
updatedUtc?: string | null;
updatedBy?: string | null;
}
export interface JobDto {
jobId: string;
clientId: string;
@@ -1763,6 +1803,10 @@ export interface ShellStatePayload {
message?: string;
/** The shell the agent started (a ShellKind; Windows agents, on open). */
shell?: string;
/** The account it runs as, when started as the signed-in user. */
user?: string;
/** Who is signed in on the device (on open, and when a run-as-user open failed). */
signedInUsers?: string[];
}
export interface DeviceFileRoot {
+45 -3
View File
@@ -1,4 +1,4 @@
import { useEffect, useRef, useState } from 'react';
import { Ref, useEffect, useImperativeHandle, useRef, useState } from 'react';
// material-ui
import { useColorScheme } from '@mui/material/styles';
@@ -15,7 +15,9 @@ import { editorPrefs, setEditorPref, useEditorPrefs, type EditorPrefs } from 'co
import StatusBar, { type StatusInfo } from 'components/code-editor/StatusBar';
import { MONO_FONT_FAMILY } from 'config';
import { lineChanges } from 'utils/monaco/line-diff';
import { loadCatalog } from 'utils/monaco/powershell-catalog';
import { functionAt, validate, type CompletionContext } from 'utils/monaco/powershell-language';
import { attachSnippets, insertSnippet } from 'utils/monaco/snippets';
import { EDITOR_THEME } from 'utils/monaco/themes';
// assets
@@ -23,6 +25,13 @@ import CloseOutlined from '@ant-design/icons/CloseOutlined';
// types
import type * as Monaco from 'monaco-editor';
import type { ScriptEngine, SnippetDto } from 'api/types';
/** What a parent can do with a mounted editor. */
export interface CodeEditorHandle {
/** Inserts snippet content (with tab stops) at the cursor. */
insertSnippet: (content: string) => void;
}
export type CodeLanguage = 'powershell' | 'shell' | 'plaintext' | 'json' | 'xml' | 'yaml' | 'ini' | 'bat' | 'python' | 'sql' | 'markdown';
@@ -53,6 +62,10 @@ interface Props {
completionContext?: CompletionContext;
/** The saved text: change bars in the gutter and Compare with Saved. */
original?: string;
/** Offers `snippets` for this engine in completions (none without one). */
snippetEngine?: ScriptEngine;
snippets?: SnippetDto[];
editorRef?: Ref<CodeEditorHandle>;
}
interface Instance {
@@ -123,7 +136,10 @@ export default function CodeEditor({
height = 480,
intellisense = true,
completionContext,
original
original,
snippetEngine,
snippets,
editorRef
}: Props) {
const { colorScheme } = useColorScheme();
const prefs = useEditorPrefs();
@@ -261,7 +277,11 @@ export default function CodeEditor({
}),
model.onDidChangeOptions(refresh),
editor.onDidChangeCursorSelection(refresh),
editor.onDidFocusEditorWidget(() => setFocused(true)),
editor.onDidFocusEditorWidget(() => {
setFocused(true);
// The full PowerShell catalog (its own chunks) starts loading before the first completion asks for it.
if (sourceRef.current.intellisense && model.getLanguageId() === 'powershell') void loadCatalog().catch(() => undefined);
}),
editor.onDidBlurEditorWidget(() => setFocused(false)),
monaco.editor.onDidChangeMarkers((uris) => uris.some((uri) => uri.toString() === model.uri.toString()) && refresh()),
editor.addAction({
@@ -307,6 +327,28 @@ export default function CodeEditor({
};
}, []);
// Snippets in completions: one source per editor, kept current without re-registering.
const snippetSourceRef = useRef({ engine: snippetEngine ?? 'PowerShell', snippets: snippets ?? [] });
useEffect(() => {
snippetSourceRef.current = { engine: snippetEngine ?? 'PowerShell', snippets: snippets ?? [] };
}, [snippetEngine, snippets]);
const offersSnippets = Boolean(snippetEngine);
useEffect(() => {
if (!instance || !offersSnippets) return;
const attached = attachSnippets(instance.monaco, instance.model, snippetSourceRef);
return () => attached.dispose();
}, [instance, offersSnippets]);
useImperativeHandle(
editorRef,
() => ({
insertSnippet: (content: string) => {
if (instance && !readOnly) insertSnippet(instance.editor, content);
}
}),
[instance, readOnly]
);
// Theme is global to Monaco; follow the resolved MUI color scheme.
useEffect(() => {
instance?.monaco.editor.setTheme(colorScheme === 'dark' ? EDITOR_THEME.dark : EDITOR_THEME.light);
+35
View File
@@ -0,0 +1,35 @@
import { MouseEvent, ReactNode } from 'react';
import { Link as RouterLink } from 'react-router-dom';
// material-ui
import Link from '@mui/material/Link';
import Typography from '@mui/material/Typography';
// project imports
import { isPowerScript } from 'utils/powerActions';
/** A job's or run's script: a link to its page, or plain text for Restart and Shut Down (built in, no page). */
export default function ScriptLink({
scriptId,
children,
onClick,
underline = 'hover'
}: {
scriptId: string;
children: ReactNode;
onClick?: (event: MouseEvent) => void;
underline?: 'none' | 'hover' | 'always';
}) {
if (isPowerScript(scriptId)) {
return (
<Typography component="span" variant="body2" sx={{ fontWeight: 500 }}>
{children}
</Typography>
);
}
return (
<Link component={RouterLink} to={`/scripts/${scriptId}`} underline={underline} onClick={onClick}>
{children}
</Link>
);
}
+47 -12
View File
@@ -14,6 +14,7 @@ import { api } from 'api/client';
import useNow from 'hooks/useNow';
import useSession from 'hooks/useSession';
import { formatCountdown } from 'utils/format';
import { powerActionOf } from 'utils/powerActions';
import CloseCircleOutlined from '@ant-design/icons/CloseCircleOutlined';
import type { DeviceStatus, JobRestartState, JobState } from 'api/types';
@@ -87,9 +88,31 @@ const RESTART_HELP: Record<JobRestartState, string> = {
failed: 'The device could not restart.'
};
const SHUT_DOWN_LABEL: Record<JobRestartState, string> = {
requested: 'Shut Down Requested',
refused: 'Shut Down Refused',
scheduled: 'Shut Down Scheduled',
restarting: 'Shutting Down',
restarted: 'Back On',
cancelled: 'Shut Down Cancelled',
failed: 'Shut Down Failed'
};
const SHUT_DOWN_HELP: Record<JobRestartState, string> = {
requested: 'The device shuts down once the server has the result.',
refused: 'AllowRestart is off on the device.',
scheduled: 'The device holds the delay, then shuts down.',
restarting: 'The server has the result; the device is shutting down.',
restarted: 'The device was switched on again.',
cancelled: 'The shutdown was cancelled.',
failed: 'The device could not shut down.'
};
export interface JobRestartInfo {
/** Set where the chip may offer Cancel Restart. */
jobId?: string;
/** The job's script: Shut Down's chips say so. */
scriptId?: string;
restart?: JobRestartState | null;
restartMessage?: string | null;
restartBootUtc?: string | null;
@@ -101,6 +124,7 @@ export interface JobRestartInfo {
/** The restart fields of a job (or run target). */
export const restartOf = (job: JobRestartInfo): JobRestartInfo => ({
jobId: job.jobId,
scriptId: job.scriptId,
restart: job.restart,
restartMessage: job.restartMessage,
restartBootUtc: job.restartBootUtc,
@@ -109,25 +133,33 @@ export const restartOf = (job: JobRestartInfo): JobRestartInfo => ({
});
/** Restart at a time, counting down, with Cancel Restart for who may run jobs. */
function ScheduledRestartChip({ jobId, restartDueUtc }: JobRestartInfo) {
function ScheduledRestartChip({ jobId, restartDueUtc, scriptId }: JobRestartInfo) {
const now = useNow(1000);
const { can } = useSession();
const [confirming, setConfirming] = useState(false);
const off = powerActionOf(scriptId) === 'shutDown';
const word = off ? 'Shut Down' : 'Restart';
const due = restartDueUtc ? Date.parse(restartDueUtc) : NaN;
const known = !Number.isNaN(due);
const label = !known
? TONES['restart-scheduled'].label
? off
? SHUT_DOWN_LABEL.scheduled
: TONES['restart-scheduled'].label
: due > now
? `Restart at ${new Date(due).toLocaleTimeString(undefined, { hour: '2-digit', minute: '2-digit' })} (${formatCountdown(due - now)})`
: 'Restart Due';
? `${word} at ${new Date(due).toLocaleTimeString(undefined, { hour: '2-digit', minute: '2-digit' })} (${formatCountdown(due - now)})`
: `${word} Due`;
const cancellable = Boolean(jobId) && can('jobs.run');
const cancel = async () => {
await api.cancelRestart(jobId!);
await mutateKey((key) => typeof key === 'string' && (key.startsWith('/api/jobs') || key.startsWith('/api/executions')));
setConfirming(false);
enqueueSnackbar('Restart cancelled.', { variant: 'success' });
enqueueSnackbar(`${word} cancelled.`, { variant: 'success' });
};
const help = [RESTART_HELP.scheduled, known ? `Due ${new Date(due).toLocaleString()}.` : '', cancellable ? '✕ cancels it.' : '']
const help = [
(off ? SHUT_DOWN_HELP : RESTART_HELP).scheduled,
known ? `Due ${new Date(due).toLocaleString()}.` : '',
cancellable ? '✕ cancels it.' : ''
]
.filter(Boolean)
.join(' ');
return (
@@ -141,15 +173,17 @@ function ScheduledRestartChip({ jobId, restartDueUtc }: JobRestartInfo) {
label={label}
icon={<Dot size={6} color="info" sx={{ ml: 0.75 }} />}
sx={{ fontWeight: 500 }}
{...(cancellable ? { onDelete: () => setConfirming(true), deleteIcon: <CloseCircleOutlined aria-label="Cancel Restart" /> } : {})}
{...(cancellable
? { onDelete: () => setConfirming(true), deleteIcon: <CloseCircleOutlined aria-label={`Cancel ${word}`} /> }
: {})}
/>
</Tooltip>
{cancellable && (
<ConfirmDialog
open={confirming}
title="Cancel Restart"
message="The device will not restart for this job."
confirmLabel="Cancel Restart"
title={`Cancel ${word}`}
message={off ? 'The device will not shut down for this job.' : 'The device will not restart for this job.'}
confirmLabel={`Cancel ${word}`}
destructive
onConfirm={cancel}
onClose={() => setConfirming(false)}
@@ -163,14 +197,15 @@ function ScheduledRestartChip({ jobId, restartDueUtc }: JobRestartInfo) {
export function RestartChip({ restart, restartMessage, restartBootUtc, restartDelaySeconds, ...rest }: JobRestartInfo) {
if (!restart) return null;
if (restart === 'scheduled') return <ScheduledRestartChip restart={restart} {...rest} />;
const off = powerActionOf(rest.scriptId) === 'shutDown';
const detail = [
restartMessage ?? RESTART_HELP[restart],
restartMessage ?? (off ? SHUT_DOWN_HELP : RESTART_HELP)[restart],
restart === 'restarting' && restartDelaySeconds ? `Delay ${restartDelaySeconds}s.` : '',
restartBootUtc ? `Booted ${new Date(restartBootUtc).toLocaleString()}.` : ''
]
.filter(Boolean)
.join(' ');
return <StatusChip status={`restart-${restart}`} tooltip={detail} />;
return <StatusChip status={`restart-${restart}`} label={off ? SHUT_DOWN_LABEL[restart] : undefined} tooltip={detail} />;
}
export function JobStateChip({ state, exitCode, ...restart }: { state: JobState; exitCode?: number | null } & JobRestartInfo) {
@@ -1,4 +1,4 @@
import { ReactNode, useEffect, useState } from 'react';
import { ReactNode, useEffect, useRef, useState } from 'react';
// material-ui
import Box from '@mui/material/Box';
@@ -10,7 +10,9 @@ import Tooltip from '@mui/material/Tooltip';
import Typography from '@mui/material/Typography';
// project imports
import CodeEditor, { type CodeLanguage } from 'components/CodeEditor';
import CodeEditor, { type CodeEditorHandle, type CodeLanguage } from 'components/CodeEditor';
import SnippetPicker from 'components/snippets/SnippetPicker';
import useSnippets from 'hooks/useSnippets';
import { setEditorPref, useEditorPrefs } from './prefs';
import SaveButton, { type SaveControl } from './SaveButton';
@@ -19,6 +21,7 @@ import FullscreenExitOutlined from '@ant-design/icons/FullscreenExitOutlined';
import FullscreenOutlined from '@ant-design/icons/FullscreenOutlined';
// types
import type { ScriptEngine } from 'api/types';
import type { CompletionContext } from 'utils/monaco/powershell-language';
const DEFAULT_HINT = 'Context-aware completions, hover cards and checks for cmdlets, parameters and variables.';
@@ -42,6 +45,8 @@ interface Props {
toolbar?: ReactNode;
/** Save, shown in the toolbar while the editor fills the window and hides the page's own. */
save?: SaveControl;
/** Offers the snippet library for this engine: in completions and a Snippets picker. */
snippetEngine?: ScriptEngine;
}
// ==============================|| CODE WORKSPACE ||============================== //
@@ -58,11 +63,14 @@ export default function CodeWorkspace({
intellisenseHint = DEFAULT_HINT,
height = 'max(380px, 56vh)',
toolbar,
save
save,
snippetEngine
}: Props) {
const prefs = useEditorPrefs();
const [fullscreen, setFullscreen] = useState(false);
const powershell = language === 'powershell';
const editorRef = useRef<CodeEditorHandle>(null);
const { data: snippets } = useSnippets(Boolean(snippetEngine));
useEffect(() => {
if (!fullscreen) return;
@@ -95,6 +103,13 @@ export default function CodeWorkspace({
</Typography>
<Stack direction="row" sx={{ gap: 1, alignItems: 'center' }}>
{toolbar}
{snippetEngine && !readOnly && (
<SnippetPicker
engine={snippetEngine}
hint="Insert a snippet at the cursor (snippets are in completions too)"
onPick={(snippet) => editorRef.current?.insertSnippet(snippet.content)}
/>
)}
<Tooltip title={powershell ? intellisenseHint : 'Completions are for PowerShell.'}>
<FormControlLabel
disabled={!powershell}
@@ -132,6 +147,9 @@ export default function CodeWorkspace({
intellisense={prefs.intellisense && powershell}
completionContext={completionContext}
original={original}
snippetEngine={snippetEngine}
snippets={snippetEngine ? snippets : undefined}
editorRef={editorRef}
/>
</Box>
</Box>

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