9 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
93 changed files with 19575 additions and 239 deletions
+71
View File
@@ -1107,6 +1107,30 @@ size (9-28 px; in the terminal Ctrl + = / Ctrl + - or Ctrl + mouse wheel, Ctrl +
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
@@ -1768,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
@@ -1833,6 +1877,7 @@ Per-script options in the editor (Details):
|--------|---------|--------------|
| **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), 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). |
@@ -2107,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
+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
}
+121 -52
View File
@@ -206,16 +206,38 @@ 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.
Agent.Sessions.SignedInUser? runAs = null;
// 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 lookup = (signedInUsers ?? Agent.Sessions.SignedInUsers.Default).Resolve();
runAs = lookup.User;
runAsFailure = runAs is null ? $"Not run as the signed-in user: {lookup.Reason}" : null;
if (runAs is not null)
var resolver = signedInUsers ?? Agent.Sessions.SignedInUsers.Default;
if (command.RunAsEachUser)
{
logger.LogInformation("Job {JobId} runs as {User}", jobId, runAs.Name);
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)));
}
}
@@ -249,7 +271,17 @@ 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 || runAs is not null)
else if (runAsUsers is { Count: 0 })
{
// 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))
@@ -261,57 +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,
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,
runAs: runAs);
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);
@@ -371,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." };
+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)
+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);
});
}
}
+13
View File
@@ -651,6 +651,19 @@ public sealed class ScriptEntity : IFolderItem
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 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,9 @@ namespace Backend.Data.Migrations.Postgres
b.Property<int>("RestartWarningSeconds")
.HasColumnType("integer");
b.Property<bool>("RunAsEachUser")
.HasColumnType("boolean");
b.Property<bool>("RunAsUser")
.HasColumnType("boolean");
@@ -1639,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 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,9 @@ namespace Backend.Data.Migrations.SqlServer
b.Property<int>("RestartWarningSeconds")
.HasColumnType("int");
b.Property<bool>("RunAsEachUser")
.HasColumnType("bit");
b.Property<bool>("RunAsUser")
.HasColumnType("bit");
@@ -1639,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 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,9 @@ namespace Backend.Data.Migrations.Sqlite
b.Property<int>("RestartWarningSeconds")
.HasColumnType("INTEGER");
b.Property<bool>("RunAsEachUser")
.HasColumnType("INTEGER");
b.Property<bool>("RunAsUser")
.HasColumnType("INTEGER");
@@ -1626,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; }
}
+7 -3
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,9 +158,10 @@ 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.RunAsUserRefusal(snapshot.RunAsUser == true, device.AgentVersion) is { } refusal)
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.
// 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
+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);
+28 -6
View File
@@ -122,8 +122,27 @@ public sealed class JobRunner(
/// 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)
=> runAsUser && !RunAsUser.Supported(agentVersion) ? RunAsUser.Unsupported(agentVersion) : null;
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)
@@ -212,7 +231,7 @@ public sealed class JobRunner(
var created = chunk.Select(d =>
{
var job = NewJob(prepared.Script, d.ClientId, requestedBy, runId, now);
return (Device: d, Job: RunAsUserRefusal(prepared.Script.RunAsUser, d.AgentVersion) is { } refusal ? Refused(job, refusal, now) : job);
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)
@@ -392,7 +411,10 @@ public sealed class JobRunner(
RestartAfterRun: script.RestartAfterRun,
RestartDelaySeconds: script.RestartDelaySeconds,
RestartWarningSeconds: script.RestartWarningSeconds,
RunAsUser: script.RunAsUser),
RunAsUser: script.RunAsUser,
RunAsEachUser: script.RunAsUser && script.RunAsEachUser,
RestartAction: script.RestartAction,
RestartInstallsUpdates: script.RestartInstallsUpdates),
cancellationToken);
}
@@ -630,13 +652,13 @@ public sealed class JobRunner(
DateTimeOffset? notBeforeUtc = null,
JobTrigger? trigger = null)
{
if (prepared.Script.RunAsUser)
if (MayRefuse(prepared.Script))
{
var agentVersion = await db.Devices.AsNoTracking()
.Where(d => d.ClientId == job.ClientId)
.Select(d => d.AgentVersion)
.FirstOrDefaultAsync(cancellationToken);
if (RunAsUserRefusal(true, agentVersion) is { } refusal)
if (Refusal(prepared.Script, agentVersion) is { } refusal)
{
// Settled here: nothing for the dispatcher to retry.
await MarkFailedAsync(job, refusal, cancellationToken);
+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,
};
}
}
+13 -2
View File
@@ -34,7 +34,12 @@ public sealed record RunSnapshot(
// Warn Signed-In Users; null in snapshots sealed before it existed (off).
int? RestartWarningSeconds = null,
// Run as the signed-in user; null in snapshots sealed before it existed (off).
bool? RunAsUser = null)
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
@@ -61,7 +66,10 @@ public sealed record RunSnapshot(
notBeforeUtc,
trigger,
prepared.Script.RestartWarningSeconds,
prepared.Script.RunAsUser);
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()
@@ -81,6 +89,9 @@ public sealed record RunSnapshot(
RestartDelaySeconds = RestartDelaySeconds ?? 0,
RestartWarningSeconds = RestartWarningSeconds ?? 0,
RunAsUser = RunAsUser ?? false,
RunAsEachUser = RunAsEachUser ?? false,
RestartAction = RestartAction ?? Shared.Contracts.Models.PowerAction.Restart,
RestartInstallsUpdates = RestartInstallsUpdates ?? false,
};
}
+1
View File
@@ -523,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);
+11 -1
View File
@@ -145,6 +145,7 @@ public static class ScriptEndpoints
RestartDelaySeconds = request.RestartDelaySeconds ?? 0,
RestartWarningSeconds = request.RestartWarningSeconds ?? 0,
RunAsUser = request.RunAsUser ?? false,
RunAsEachUser = request.RunAsEachUser ?? false,
CreatedUtc = now,
UpdatedUtc = now,
CreatedBy = actor,
@@ -222,6 +223,8 @@ public static class ScriptEndpoints
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;
@@ -288,7 +291,8 @@ public static class ScriptEndpoints
script.RestartAfterRun,
script.RestartDelaySeconds,
script.RestartWarningSeconds,
script.RunAsUser);
script.RunAsUser,
script.RunAsEachUser);
/// <summary>
/// Set Working Directory needs a staged file: PowerShell 7 stages one only with Run From
@@ -296,6 +300,12 @@ public static class ScriptEndpoints
/// </summary>
internal static void NormalizeOptions(ScriptEntity script)
{
// 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;
+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);
}
+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";
+26 -3
View File
@@ -349,7 +349,8 @@ public sealed record ScriptDto(
RestartAfterRun RestartAfterRun = RestartAfterRun.Off,
int RestartDelaySeconds = 0,
int RestartWarningSeconds = 0,
bool RunAsUser = false);
bool RunAsUser = false,
bool RunAsEachUser = false);
/// <summary>
/// POST/PUT /api/scripts request body. <c>Folder</c> places the script ("/"
@@ -360,7 +361,8 @@ public sealed record ScriptDto(
/// 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).
/// 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,
@@ -382,7 +384,8 @@ public sealed record SaveScriptRequest(
RestartAfterRun? RestartAfterRun = null,
int? RestartDelaySeconds = null,
int? RestartWarningSeconds = null,
bool? RunAsUser = null);
bool? RunAsUser = null,
bool? RunAsEachUser = null);
/// <summary>A folder of a library (scripts, functions).</summary>
public sealed record FolderDto(string Path, string Name);
@@ -584,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.
+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);
+10 -2
View File
@@ -104,6 +104,9 @@ public sealed record ScriptFileDelivery(
/// <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,
@@ -129,11 +132,16 @@ public sealed record ScriptCommandPayload(
RestartAfterRun RestartAfterRun = RestartAfterRun.Off,
int RestartDelaySeconds = 0,
int RestartWarningSeconds = 0,
bool RunAsUser = false)
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>
@@ -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();
+10
View File
@@ -13,6 +13,16 @@ public static class RunAsUser
/// <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.";
@@ -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."
}
+20
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;
@@ -111,6 +113,7 @@ export interface SaveScriptBody {
cleanUpAfterRun?: boolean;
setWorkingDirectory?: boolean;
runAsUser?: boolean;
runAsEachUser?: boolean;
restartAfterRun?: RestartAfterRun;
restartDelaySeconds?: number;
restartWarningSeconds?: number;
@@ -124,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;
@@ -411,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 })),
@@ -433,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', {})),
@@ -647,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',
+38
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;
@@ -1200,6 +1219,8 @@ export interface ScriptDto {
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;
@@ -1306,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;
+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>
@@ -0,0 +1,205 @@
import { KeyboardEvent, useMemo, useRef, useState } from 'react';
import { Link as RouterLink } from 'react-router-dom';
// material-ui
import Box from '@mui/material/Box';
import Button, { ButtonProps } from '@mui/material/Button';
import Chip from '@mui/material/Chip';
import InputAdornment from '@mui/material/InputAdornment';
import Link from '@mui/material/Link';
import List from '@mui/material/List';
import ListItemButton from '@mui/material/ListItemButton';
import ListItemText from '@mui/material/ListItemText';
import Popover from '@mui/material/Popover';
import Stack from '@mui/material/Stack';
import TextField from '@mui/material/TextField';
import Tooltip from '@mui/material/Tooltip';
import Typography from '@mui/material/Typography';
// project imports
import useSnippets from 'hooks/useSnippets';
import { ENGINE_LABEL, snippetsFor, toPlainText } from 'utils/monaco/snippets';
// assets
import SearchOutlined from '@ant-design/icons/SearchOutlined';
import SnippetsOutlined from '@ant-design/icons/SnippetsOutlined';
// types
import type { ScriptEngine, SnippetDto } from 'api/types';
interface Props {
/** The language to offer snippets for; all of them without one. */
engine?: ScriptEngine;
onPick: (snippet: SnippetDto) => void;
disabled?: boolean;
/** Hover text for the button. */
hint?: string;
size?: ButtonProps['size'];
variant?: ButtonProps['variant'];
/** Offer a link to the Snippets page (not from a window without the console's navigation). */
manageLink?: boolean;
}
const matches = (snippet: SnippetDto, needle: string) =>
!needle || [snippet.name, snippet.description, ENGINE_LABEL[snippet.language]].some((v) => v?.toLowerCase().includes(needle));
// ==============================|| SNIPPET PICKER ||============================== //
/** "Snippets" button with a searchable list of the library's snippets for a language and a preview of the highlighted one. */
export default function SnippetPicker({
engine,
onPick,
disabled,
hint = 'Insert a snippet at the cursor',
size = 'small',
variant = 'text',
manageLink = true
}: Props) {
const { data, loading, error } = useSnippets();
const [anchor, setAnchor] = useState<HTMLElement | null>(null);
const [search, setSearch] = useState('');
const [active, setActive] = useState(0);
const listRef = useRef<HTMLUListElement>(null);
const offered = useMemo(() => snippetsFor(data, engine), [data, engine]);
const needle = search.trim().toLowerCase();
const shown = useMemo(() => offered.filter((s) => matches(s, needle)), [offered, needle]);
const current = shown[Math.min(active, shown.length - 1)];
const mixed = new Set(offered.map((s) => s.language)).size > 1;
const close = () => {
setAnchor(null);
setSearch('');
setActive(0);
};
const pick = (snippet: SnippetDto | undefined) => {
if (!snippet) return;
close();
onPick(snippet);
};
const move = (step: number) => {
if (shown.length === 0) return;
const next = (Math.min(active, shown.length - 1) + step + shown.length) % shown.length;
setActive(next);
listRef.current?.children[next]?.scrollIntoView({ block: 'nearest' });
};
const onKeyDown = (event: KeyboardEvent) => {
if (event.key === 'ArrowDown') move(1);
else if (event.key === 'ArrowUp') move(-1);
else if (event.key === 'Enter') pick(current);
else return;
event.preventDefault();
};
return (
<>
<Tooltip title={hint}>
<span>
<Button
size={size}
variant={variant}
color="secondary"
startIcon={<SnippetsOutlined />}
disabled={disabled}
onClick={(e) => setAnchor(e.currentTarget)}
aria-haspopup="dialog"
>
Snippets
</Button>
</span>
</Tooltip>
<Popover
open={Boolean(anchor)}
anchorEl={anchor}
onClose={close}
anchorOrigin={{ vertical: 'bottom', horizontal: 'right' }}
transformOrigin={{ vertical: 'top', horizontal: 'right' }}
disableRestoreFocus
slotProps={{ paper: { sx: { width: { xs: 'calc(100vw - 32px)', sm: 560 }, maxWidth: 560 } } }}
>
<Stack sx={{ p: 1.5, gap: 1 }} onKeyDown={onKeyDown}>
<TextField
size="small"
autoFocus
fullWidth
placeholder={engine === 'Bash' ? 'Search Bash Snippets' : engine ? 'Search PowerShell Snippets' : 'Search Snippets'}
value={search}
onChange={(e) => {
setSearch(e.target.value);
setActive(0);
}}
slotProps={{
input: {
startAdornment: (
<InputAdornment position="start">
<SearchOutlined />
</InputAdornment>
)
}
}}
/>
{shown.length === 0 ? (
<Typography variant="body2" color="text.secondary" sx={{ py: 2, textAlign: 'center' }}>
{loading ? 'Loading…' : error ? 'Snippets could not be loaded.' : needle ? 'No Matches' : 'No Snippets'}
</Typography>
) : (
<List ref={listRef} dense disablePadding sx={{ maxHeight: 260, overflowY: 'auto' }} role="listbox" aria-label="Snippets">
{shown.map((snippet, index) => (
<ListItemButton
key={snippet.id}
selected={snippet === current}
onMouseEnter={() => setActive(index)}
onClick={() => pick(snippet)}
role="option"
aria-selected={snippet === current}
sx={{ borderRadius: 1, gap: 1 }}
>
<ListItemText
primary={snippet.name}
secondary={snippet.description}
slotProps={{ primary: { noWrap: true }, secondary: { noWrap: true } }}
/>
{mixed && <Chip size="small" variant="outlined" label={ENGINE_LABEL[snippet.language]} />}
{!snippet.builtIn && <Chip size="small" color="primary" variant="outlined" label="Custom" />}
</ListItemButton>
))}
</List>
)}
{current && (
<Box
component="pre"
aria-label="Preview"
sx={{
m: 0,
p: 1,
maxHeight: 180,
overflow: 'auto',
fontFamily: 'var(--font-mono)',
fontSize: '0.75rem',
lineHeight: 1.5,
bgcolor: 'action.hover',
borderRadius: 1,
whiteSpace: 'pre'
}}
>
{toPlainText(current.content)}
</Box>
)}
<Stack direction="row" sx={{ justifyContent: 'space-between', alignItems: 'center' }}>
<Typography variant="caption" color="text.secondary">
↑↓ to choose · Enter to insert
</Typography>
{manageLink && (
<Link component={RouterLink} to="/snippets" variant="caption" underline="hover" onClick={close}>
Manage Snippets
</Link>
)}
</Stack>
</Stack>
</Popover>
</>
);
}
+13 -2
View File
@@ -1,10 +1,16 @@
import { createContext, ReactNode, useCallback, useMemo, useState } from 'react';
// project imports
import PowerDialog from 'sections/devices/PowerDialog';
import RunScriptDialog from 'sections/runs/RunScriptDialog';
import ScheduleEditor, { SchedulePreset } from 'sections/schedules/ScheduleEditor';
import type { RunTarget } from 'sections/runs/TargetPicker';
import type { ScriptTriggerDto } from 'api/types';
import type { PowerAction, ScriptTriggerDto } from 'api/types';
export interface PowerRequestDraft {
action: PowerAction;
targets: RunTarget[];
}
export interface RunRequest {
scriptId?: string;
@@ -18,6 +24,8 @@ export interface AutomationContextValue {
openRun: (request?: RunRequest) => void;
/** Opens the schedule editor for a new schedule (preset) or an existing one. */
openSchedule: (request?: { trigger?: ScriptTriggerDto; preset?: SchedulePreset }) => void;
/** Opens Restart / Shut Down for these devices and groups. */
openPower: (request: PowerRequestDraft) => void;
}
export const AutomationContext = createContext<AutomationContextValue | undefined>(undefined);
@@ -31,7 +39,9 @@ export function AutomationProvider({ children }: { children: ReactNode }) {
const openRun = useCallback((request: RunRequest = {}) => setRun(request), []);
const openSchedule = useCallback((request: { trigger?: ScriptTriggerDto; preset?: SchedulePreset } = {}) => setSchedule(request), []);
const value = useMemo(() => ({ openRun, openSchedule }), [openRun, openSchedule]);
const [power, setPower] = useState<PowerRequestDraft | null>(null);
const openPower = useCallback((request: PowerRequestDraft) => setPower(request), []);
const value = useMemo(() => ({ openRun, openSchedule, openPower }), [openRun, openSchedule, openPower]);
return (
<AutomationContext.Provider value={value}>
@@ -49,6 +59,7 @@ export function AutomationProvider({ children }: { children: ReactNode }) {
trigger={schedule?.trigger ?? null}
preset={schedule?.preset}
/>
<PowerDialog open={power !== null} onClose={() => setPower(null)} action={power?.action} targets={power?.targets} />
</AutomationContext.Provider>
);
}
+13
View File
@@ -0,0 +1,13 @@
// project imports
import { keys } from 'api/client';
import useApi from 'hooks/useApi';
import useSession from 'hooks/useSession';
// types
import type { SnippetDto } from 'api/types';
/** The snippet library (built-ins and the library's own); nothing without View Scripts or while not `enabled`. */
export default function useSnippets(enabled = true) {
const { can } = useSession();
return useApi<SnippetDto[]>(enabled && can('scripts.view') ? keys.snippets : null, { revalidateOnFocus: false });
}
+9
View File
@@ -11,6 +11,7 @@ import HistoryOutlined from '@ant-design/icons/HistoryOutlined';
import LockOutlined from '@ant-design/icons/LockOutlined';
import OrderedListOutlined from '@ant-design/icons/OrderedListOutlined';
import SettingOutlined from '@ant-design/icons/SettingOutlined';
import SnippetsOutlined from '@ant-design/icons/SnippetsOutlined';
// types
import { NavGroupType, NavItemType } from 'types/menu';
@@ -51,6 +52,14 @@ const menuItems: NavGroupType[] = [
permission: 'functions.view',
permissionLabel: 'View Functions'
},
{
id: 'snippets',
title: 'Snippets',
url: '/snippets',
icon: SnippetsOutlined,
permission: 'scripts.view',
permissionLabel: 'View Scripts'
},
{
id: 'sequences',
title: 'Sequences',
+34 -2
View File
@@ -11,21 +11,27 @@ import TextField from '@mui/material/TextField';
import Tooltip from '@mui/material/Tooltip';
import Typography from '@mui/material/Typography';
// third-party
import { enqueueSnackbar } from 'notistack';
// project imports
import GatedButton from 'components/GatedButton';
import HoverHelp from 'components/HoverHelp';
import MainCard from 'components/MainCard';
import { platformOf } from 'components/OsIcon';
import SnippetPicker from 'components/snippets/SnippetPicker';
import StatusChip from 'components/StatusChip';
import useApi from 'hooks/useApi';
import useSession, { useGate } from 'hooks/useSession';
import DeviceToolFrame, { useToolSurface } from 'sections/deviceTools/DeviceToolFrame';
import { useIsPopOut } from 'sections/deviceTools/popOut';
import useRemoteShell, { SHELL_KINDS, shellLabel, ShellKind, ShellState } from 'sections/shell/useRemoteShell';
import { ClipboardButtons, ClipboardPromptCard } from 'sections/shell/ShellClipboard';
import TerminalSettings from 'sections/shell/TerminalSettings';
import { themeOf, useTerminalPrefs } from 'sections/shell/terminalPrefs';
import { toPlainText } from 'utils/monaco/snippets';
import { keys } from 'api/client';
import type { DeviceDetailDto } from 'api/types';
import type { DeviceDetailDto, ScriptEngine } from 'api/types';
// assets
import '@xterm/xterm/css/xterm.css';
@@ -48,6 +54,13 @@ const STATUS: Record<ShellState, { status: string; label: string }> = {
/** States with a session that can still be closed from here. */
const ACTIVE: ShellState[] = ['connecting', 'opening', 'open', 'noResponse'];
/** Which snippets suit the open shell: PowerShell on Windows (not cmd), Bash elsewhere; all while unknown. */
function snippetEngineFor(platform: string | undefined, startedShell: string | undefined): ScriptEngine | undefined {
if (!platform || platform === 'unknown') return undefined;
if (platform !== 'windows') return 'Bash';
return startedShell === 'cmd' ? undefined : 'PowerShell';
}
/** Which shell a Windows device starts; picking one opens a new session with it. */
function ShellPicker({ value, started, onChange }: { value: ShellKind; started?: string; onChange: (kind: ShellKind) => void }) {
return (
@@ -165,6 +178,8 @@ function ShellView({ clientId }: { clientId: string }) {
user,
startedUser,
signedInUsers,
hasSelection,
clipboard,
controller,
close,
reconnect,
@@ -173,7 +188,8 @@ function ShellView({ clientId }: { clientId: string }) {
chooseRunAs
} = useRemoteShell(clientId, allowed);
// The shell choice applies to Windows devices only (unix agents start the login shell).
const windows = platformOf(detail?.device.osCaption) === 'windows';
const platform = detail ? platformOf(detail.device.osCaption) : undefined;
const windows = platform === 'windows';
const knownHostname = detail?.device.hostname;
useEffect(() => {
@@ -203,6 +219,21 @@ function ShellView({ clientId }: { clientId: string }) {
{controller && (
<RunAsPicker asUser={asUser} user={user} started={startedUser} signedIn={signedInUsers} onChange={chooseRunAs} />
)}
{controller && can('scripts.view') && (
<SnippetPicker
engine={snippetEngineFor(platform, startedShell)}
variant="outlined"
size="medium"
disabled={state !== 'open' || poppedOut}
manageLink={!popout}
hint="Type a snippet at the prompt (tab stops filled with their defaults, no Enter)"
onPick={(snippet) => {
if (controller.insertText(toPlainText(snippet.content)) === 'multiline')
enqueueSnackbar('This shell would run each line on its own. Use the snippet in a script.', { variant: 'warning' });
}}
/>
)}
{controller && !poppedOut && <ClipboardButtons controller={controller} hasSelection={hasSelection} open={state === 'open'} />}
<TerminalSettings />
{poppedOut && !popout && (
<Button variant="outlined" color="secondary" startIcon={<ImportOutlined />} onClick={bringBack}>
@@ -239,6 +270,7 @@ function ShellView({ clientId }: { clientId: string }) {
{/* xterm sizes itself to this element (the padding lives on the parent so fitting stays exact).
It stays mounted while popped out so closing the window can dock the terminal straight back. */}
<Box ref={hostRef} aria-label="Terminal" sx={{ width: 1, height: 1, '& .xterm': { height: 1 } }} />
{controller && clipboard && !poppedOut && <ClipboardPromptCard prompt={clipboard} controller={controller} />}
{poppedOut && (
<Stack
sx={{ position: 'absolute', inset: 0, alignItems: 'center', justifyContent: 'center', gap: 2, p: 3, textAlign: 'center' }}
+3 -2
View File
@@ -14,6 +14,7 @@ import TextField from '@mui/material/TextField';
import Typography from '@mui/material/Typography';
// project imports
import ScriptLink from 'components/ScriptLink';
import DataTable, { Column } from 'components/DataTable';
import { RelativeTime } from 'components/DateTime';
import EmptyState from 'components/EmptyState';
@@ -144,9 +145,9 @@ export default function JobsPage() {
header: 'Script',
cell: (job) => (
<Stack direction="row" sx={{ gap: 1, alignItems: 'center', minWidth: 0 }}>
<Link component={RouterLink} to={`/scripts/${job.scriptId}`} underline="hover" onClick={stop}>
<ScriptLink scriptId={job.scriptId} onClick={stop}>
{job.scriptName}
</Link>
</ScriptLink>
<SequenceRefChip sequence={job.sequence} compact />
</Stack>
),
+22 -9
View File
@@ -18,6 +18,7 @@ import RunProgress, { RUN_SOURCE_LABEL, runCounts, runFinished, useRun } from 's
import { downloads, errorMessage } from 'api/client';
import useAutomation from 'hooks/useAutomation';
import { useGate } from 'hooks/useSession';
import { powerActionOf } from 'utils/powerActions';
// assets
import DownloadOutlined from '@ant-design/icons/DownloadOutlined';
@@ -47,10 +48,14 @@ export default function RunPage() {
const { runId = '' } = useParams();
const [params, setParams] = useSearchParams();
const openJobId = params.get('job');
const runGate = useGate('jobs.run', 'Run Jobs');
const { openRun } = useAutomation();
const { openRun, openPower } = useAutomation();
const execution = useRun(runId);
const run = execution.data;
// A Restart or Shut Down runs again as itself, for who may.
const power = powerActionOf(run?.scriptId);
const scriptGate = useGate('jobs.run', 'Run Jobs');
const powerGate = useGate('devices.power', 'Restart and Shut Down');
const runGate = power ? powerGate : scriptGate;
const setJob = (jobId: string | null) =>
setParams(
@@ -64,12 +69,12 @@ export default function RunPage() {
);
// The same script on these devices (every target, skipped ones included: they may be back).
const runAgainOn = (clientIds: string[]) =>
run &&
openRun({
scriptId: run.scriptId,
targets: [...new Set(clientIds)].map((id) => ({ kind: 'device' as const, id }))
});
const runAgainOn = (clientIds: string[]) => {
if (!run) return;
const targets = [...new Set(clientIds)].map((id) => ({ kind: 'device' as const, id }));
if (power) openPower({ action: power, targets });
else openRun({ scriptId: run.scriptId, targets });
};
const runAgain = () => run && runAgainOn([...run.targets.map((t) => t.clientId), ...(run.skipped ?? []).map((s) => s.clientId)]);
// Failed and timed out: the ones that ran and did not succeed.
const failedTargets = (run?.targets ?? []).filter((t) => t.state === 'failed' || t.state === 'timedOut').map((t) => t.clientId);
@@ -122,7 +127,15 @@ export default function RunPage() {
</Button>
</Tooltip>
{failedTargets.length > 0 && (
<Tooltip title={runGate ? '' : 'The same script again on the devices that failed or timed out.'}>
<Tooltip
title={
runGate
? ''
: power
? 'Again on the devices that failed.'
: 'The same script again on the devices that failed or timed out.'
}
>
<span>
<GatedButton
variant="outlined"
+40 -9
View File
@@ -114,6 +114,23 @@ function OptionSwitch(props: { label: string; help: string; checked: boolean; di
);
}
/** Whose account a script runs as. */
type RunAs = 'agent' | 'user' | 'each';
const RUN_AS: { value: RunAs; label: string; hint: string }[] = [
{ value: 'agent', label: 'Agent Account', hint: 'LocalSystem on Windows, root on Linux and macOS.' },
{
value: 'user',
label: 'Signed-In User',
hint: "The console's user, else the only one signed in, out of sight. Fails when that is unclear. Agent 1.13.0 or later."
},
{
value: 'each',
label: 'Each Signed-In User',
hint: 'Once per signed-in user, in turn. Nobody signed in: nothing runs. Agent 1.14.0 or later.'
}
];
/** How the script runs on the device: from a staged file, cleanup and working directory. */
function RunOptions({ draft, edit, readOnly }: { draft: ScriptDraft; edit: (patch: Partial<ScriptDraft>) => void; readOnly: boolean }) {
const pwsh7 = draft.engine === 'PowerShell';
@@ -133,20 +150,33 @@ function RunOptions({ draft, edit, readOnly }: { draft: ScriptDraft; edit: (patc
/>
<OptionSwitch
label="Set Working Directory to Script Folder"
help={staged ? 'Starts the script in its job folder.' : 'Needs Run From File or Run As Signed-In User.'}
help={staged ? 'Starts the script in its job folder.' : 'Needs Run From File, or Run As a signed-in user.'}
checked={staged && draft.setWorkingDirectory}
disabled={readOnly || !staged}
onChange={(setWorkingDirectory) => edit({ setWorkingDirectory })}
/>
<OptionSwitch
label="Run As Signed-In User"
help="Runs as the person signed in on the device (the console's user, else the only one) instead of the agent's account, out of sight. Fails when nobody is signed in, or on agents before 1.13.0."
checked={draft.runAsUser}
<TextField
select
size="small"
label="Run As"
value={!draft.runAsUser ? 'agent' : draft.runAsEachUser ? 'each' : 'user'}
disabled={readOnly}
onChange={(runAsUser) =>
edit(runAsUser || stagesFile(draft.engine, draft.runFromFile) ? { runAsUser } : { runAsUser, setWorkingDirectory: false })
}
/>
onChange={(e) => {
const runAs = e.target.value as RunAs;
const runAsUser = runAs !== 'agent';
const patch = { runAsUser, runAsEachUser: runAs === 'each' };
edit(runAsUser || stagesFile(draft.engine, draft.runFromFile) ? patch : { ...patch, setWorkingDirectory: false });
}}
sx={{ minWidth: 200, mr: 3, my: 0.5 }}
>
{RUN_AS.map(({ value, label, hint }) => (
<MenuItem key={value} value={value}>
<Tooltip title={hint} placement="right">
<span style={{ flex: 1 }}>{label}</span>
</Tooltip>
</MenuItem>
))}
</TextField>
<OptionSwitch
label="Clean Up After Run"
help="Deletes the job folder when the run ends. Off keeps it for 7 days; secrets never stay."
@@ -576,6 +606,7 @@ function ScriptEditor({ id }: { id: string }) {
title={title}
intellisenseHint="Context-aware completions, hover cards and checks for cmdlets, parameters, variables, secrets and attached functions."
save={saveControl}
snippetEngine={draft.engine}
toolbar={
sync.status !== 'off' && (
<Tooltip title={syncState.hint}>
+355
View File
@@ -0,0 +1,355 @@
import { MouseEvent, useMemo, useState } from 'react';
import { useSearchParams } from 'react-router-dom';
// material-ui
import Chip from '@mui/material/Chip';
import InputAdornment from '@mui/material/InputAdornment';
import MenuItem from '@mui/material/MenuItem';
import Skeleton from '@mui/material/Skeleton';
import Stack from '@mui/material/Stack';
import TextField from '@mui/material/TextField';
import Typography from '@mui/material/Typography';
// third-party
import { enqueueSnackbar } from 'notistack';
import { mutate } from 'swr';
// project imports
import IconButton from 'components/@extended/IconButton';
import ActionMenu, { MenuEntry } from 'components/ActionMenu';
import ConfirmDialog from 'components/ConfirmDialog';
import DataTable, { Column } from 'components/DataTable';
import { RelativeTime } from 'components/DateTime';
import EmptyState from 'components/EmptyState';
import GatedButton from 'components/GatedButton';
import HoverHelp from 'components/HoverHelp';
import MainCard from 'components/MainCard';
import PageHeader from 'components/PageHeader';
import SnippetEditor, { TAB_STOP_HELP } from 'sections/snippets/SnippetEditor';
import { api, errorMessage, keys } from 'api/client';
import useSnippets from 'hooks/useSnippets';
import { useGate } from 'hooks/useSession';
import { ENGINE_HINT, ENGINE_LABEL } from 'utils/monaco/snippets';
// assets
import CopyOutlined from '@ant-design/icons/CopyOutlined';
import DeleteOutlined from '@ant-design/icons/DeleteOutlined';
import EditOutlined from '@ant-design/icons/EditOutlined';
import EyeOutlined from '@ant-design/icons/EyeOutlined';
import MoreOutlined from '@ant-design/icons/MoreOutlined';
import PlusOutlined from '@ant-design/icons/PlusOutlined';
import SearchOutlined from '@ant-design/icons/SearchOutlined';
import SnippetsOutlined from '@ant-design/icons/SnippetsOutlined';
// types
import type { ScriptEngine, SnippetDto } from 'api/types';
const NEW = 'new';
type LanguageFilter = 'all' | ScriptEngine;
type SourceFilter = 'all' | 'builtIn' | 'custom';
const LANGUAGE_FILTERS: { value: LanguageFilter; label: string }[] = [
{ value: 'all', label: 'All Languages' },
{ value: 'PowerShell', label: ENGINE_LABEL.PowerShell },
{ value: 'WindowsPowerShell', label: ENGINE_LABEL.WindowsPowerShell },
{ value: 'Bash', label: ENGINE_LABEL.Bash }
];
const SOURCE_FILTERS: { value: SourceFilter; label: string }[] = [
{ value: 'all', label: 'All Snippets' },
{ value: 'builtIn', label: 'Built-In' },
{ value: 'custom', label: 'Custom' }
];
// ==============================|| SNIPPETS ||============================== //
export default function SnippetsPage() {
const [params, setParams] = useSearchParams();
const selectedId = params.get('id');
const gate = useGate('scripts.manage', 'Manage Scripts');
const { data: snippets, error, loading, validating } = useSnippets();
const [search, setSearch] = useState('');
const [language, setLanguage] = useState<LanguageFilter>('all');
const [source, setSource] = useState<SourceFilter>('all');
const [menu, setMenu] = useState<{ anchor?: HTMLElement; position?: { top: number; left: number }; snippet: SnippetDto } | null>(null);
const [deleting, setDeleting] = useState<SnippetDto | null>(null);
const selected = selectedId && selectedId !== NEW ? snippets?.find((s) => s.id === selectedId) : undefined;
const rows = useMemo(() => {
if (!snippets) return undefined;
const needle = search.trim().toLowerCase();
return snippets.filter(
(s) =>
(language === 'all' || s.language === language) &&
(source === 'all' || (source === 'builtIn') === s.builtIn) &&
(!needle || [s.name, s.description, s.content].some((v) => v?.toLowerCase().includes(needle)))
);
}, [snippets, search, language, source]);
/** Opens a snippet (the open editor asks first when it has unsaved edits); null shows the list. */
const select = (id: string | null) => {
if (id === selectedId) return;
setParams((current) => {
const next = new URLSearchParams(current);
if (id) next.set('id', id);
else next.delete('id');
return next;
});
};
const copy = async (snippet: SnippetDto) => {
try {
const created = await api.copySnippet(snippet.id);
await mutate(keys.snippets);
select(created.id);
enqueueSnackbar('Copied — you are editing the copy.', { variant: 'success' });
} catch (e) {
enqueueSnackbar(errorMessage(e, 'Copy failed.'), { variant: 'error' });
}
};
const menuEntries = (snippet: SnippetDto): MenuEntry[] => [
{
kind: 'item',
id: 'open',
label: snippet.builtIn ? 'View' : 'Open',
icon: snippet.builtIn ? <EyeOutlined /> : <EditOutlined />,
onSelect: () => select(snippet.id)
},
{ kind: 'item', id: 'copy', label: 'Copy', icon: <CopyOutlined />, disabledReason: gate, onSelect: () => void copy(snippet) },
...(snippet.builtIn
? []
: ([
{ kind: 'divider' },
{
kind: 'item',
id: 'delete',
label: 'Delete…',
icon: <DeleteOutlined />,
destructive: true,
disabledReason: gate,
onSelect: () => setDeleting(snippet)
}
] satisfies MenuEntry[]))
];
const columns: Column<SnippetDto>[] = [
{
id: 'name',
header: 'Name',
sortValue: (s) => s.name,
cell: (s) => (
<Stack sx={{ minWidth: 0, maxWidth: 560 }}>
<Typography variant="subtitle1" noWrap>
{s.name}
</Typography>
{s.description && (
<Typography variant="caption" color="text.secondary" noWrap>
{s.description}
</Typography>
)}
</Stack>
)
},
{
id: 'language',
header: 'Language',
nowrap: true,
width: 150,
sortValue: (s) => ENGINE_LABEL[s.language],
cell: (s) => <Chip size="small" variant="outlined" label={ENGINE_LABEL[s.language]} title={ENGINE_HINT[s.language]} />
},
{
id: 'source',
header: 'Source',
nowrap: true,
width: 220,
sortValue: (s) => (s.builtIn ? '' : (s.updatedUtc ?? '')),
cell: (s) =>
s.builtIn ? (
<Chip size="small" variant="light" color="secondary" label="Built-In" />
) : (
<Stack>
{s.updatedUtc && <RelativeTime value={s.updatedUtc} />}
{s.updatedBy && (
<Typography variant="caption" color="text.secondary" noWrap>
by {s.updatedBy}
</Typography>
)}
</Stack>
)
},
{
id: 'actions',
header: '',
width: 56,
align: 'right',
cell: (s) => (
<IconButton
size="small"
color="secondary"
aria-label={`Actions for ${s.name}`}
onClick={(e: MouseEvent<HTMLButtonElement>) => {
e.stopPropagation();
setMenu({ anchor: e.currentTarget, snippet: s });
}}
>
<MoreOutlined />
</IconButton>
)
}
];
const newSnippet = (
<GatedButton gate={gate} variant="contained" startIcon={<PlusOutlined />} onClick={() => select(NEW)}>
New Snippet
</GatedButton>
);
let content;
if (selectedId === NEW) {
content = <SnippetEditor key={NEW} snippet={null} gate={gate} onSelect={select} />;
} else if (selected) {
content = <SnippetEditor key={selected.id} snippet={selected} gate={gate} onSelect={select} />;
} else if (selectedId && loading) {
content = (
<MainCard>
<Skeleton variant="rectangular" height={480} />
</MainCard>
);
} else if (selectedId) {
content = (
<MainCard>
<EmptyState icon={<SnippetsOutlined />} title="Snippet Not Found" detail="It may have been deleted." />
</MainCard>
);
} else {
const filtered = Boolean(search.trim()) || language !== 'all' || source !== 'all';
content = (
<MainCard content={false}>
<DataTable
columns={columns}
rows={rows}
rowId={(s) => s.id}
loading={loading}
refreshing={validating && !loading}
error={error?.message}
onRowClick={(s) => select(s.id)}
onRowContextMenu={(s, position) => setMenu({ position, snippet: s })}
defaultSort={{ id: 'name', direction: 'asc' }}
rowLabel={(s) => s.name}
minWidth={560}
toolbar={
<Stack direction="row" sx={{ alignItems: 'center', gap: 2, flexWrap: 'wrap' }}>
<TextField
size="small"
placeholder="Search Snippets"
value={search}
onChange={(e) => setSearch(e.target.value)}
sx={{ minWidth: { sm: 300 }, width: { xs: '100%', sm: 'auto' } }}
slotProps={{
input: {
startAdornment: (
<InputAdornment position="start">
<SearchOutlined />
</InputAdornment>
)
}
}}
/>
<TextField
select
size="small"
aria-label="Language"
value={language}
onChange={(e) => setLanguage(e.target.value as LanguageFilter)}
sx={{ minWidth: 170 }}
>
{LANGUAGE_FILTERS.map((f) => (
<MenuItem key={f.value} value={f.value}>
{f.label}
</MenuItem>
))}
</TextField>
<TextField
select
size="small"
aria-label="Source"
value={source}
onChange={(e) => setSource(e.target.value as SourceFilter)}
sx={{ minWidth: 150 }}
>
{SOURCE_FILTERS.map((f) => (
<MenuItem key={f.value} value={f.value}>
{f.label}
</MenuItem>
))}
</TextField>
</Stack>
}
empty={
filtered ? (
<EmptyState dense title="No Matches" detail="No snippet matches the filters." />
) : (
<EmptyState icon={<SnippetsOutlined />} title="No Snippets Yet" action={newSnippet} />
)
}
/>
</MainCard>
);
}
return (
<Stack sx={{ gap: 3 }}>
<PageHeader
title="Snippets"
breadcrumbs={
selectedId
? [{ label: 'Snippets', to: '/snippets' }, { label: selectedId === NEW ? 'New Snippet' : (selected?.name ?? '…') }]
: undefined
}
description={
<>
Reusable code for scripts, functions and shells.
<HoverHelp
title={
<>
Insert one with Snippets in the script and function editors (or type its name for completions), or type one into a remote
shell. {TAB_STOP_HELP}
</>
}
/>
</>
}
primaryAction={newSnippet}
/>
{content}
{menu && (
<ActionMenu
anchorEl={menu.anchor}
anchorPosition={menu.position}
onClose={() => setMenu(null)}
entries={menuEntries(menu.snippet)}
/>
)}
<ConfirmDialog
open={deleting !== null}
title="Delete Snippet?"
message={deleting ? `Delete “${deleting.name}”? This cannot be undone.` : ''}
confirmLabel="Delete"
destructive
onClose={() => setDeleting(null)}
onConfirm={async () => {
await api.deleteSnippet(deleting!.id);
await mutate(keys.snippets);
enqueueSnackbar(`Deleted ${deleting!.name}`, { variant: 'success' });
}}
/>
</Stack>
);
}
+2
View File
@@ -24,6 +24,7 @@ const ScriptEditor = Loadable(lazy(() => import('pages/scripts/editor')));
const S3Files = Loadable(lazy(() => import('pages/s3')));
const Vault = Loadable(lazy(() => import('pages/vault')));
const Functions = Loadable(lazy(() => import('pages/functions')));
const Snippets = Loadable(lazy(() => import('pages/snippets')));
const Sequences = Loadable(lazy(() => import('pages/sequences')));
const SequenceEditor = Loadable(lazy(() => import('pages/sequences/editor')));
const SequenceRun = Loadable(lazy(() => import('pages/sequences/run')));
@@ -104,6 +105,7 @@ const router = createBrowserRouter([
{ path: 's3', element: <S3Files /> },
{ path: 'vault', element: <Vault /> },
{ path: 'functions', element: <Functions /> },
{ path: 'snippets', element: <Snippets /> },
{ path: 'sequences', element: <Sequences /> },
{ path: 'sequences/:id', element: <SequenceEditor /> },
{ path: 'sequence-runs/:id', element: <SequenceRun /> },
@@ -7,6 +7,7 @@ import Stack from '@mui/material/Stack';
import Typography from '@mui/material/Typography';
// project imports
import ScriptLink from 'components/ScriptLink';
import DataTable, { Column } from 'components/DataTable';
import { RelativeTime } from 'components/DateTime';
import EmptyState from 'components/EmptyState';
@@ -38,9 +39,9 @@ export default function DeviceJobs({ clientId }: { clientId: string }) {
sortValue: (j) => j.scriptName,
cell: (j) => (
<Stack direction="row" sx={{ gap: 1, alignItems: 'center', minWidth: 0 }}>
<Link component={RouterLink} to={`/scripts/${j.scriptId}`} onClick={(e) => e.stopPropagation()}>
<ScriptLink scriptId={j.scriptId} underline="always" onClick={(e) => e.stopPropagation()}>
{j.scriptName}
</Link>
</ScriptLink>
<SequenceRefChip sequence={j.sequence} />
</Stack>
)
@@ -0,0 +1,361 @@
import { ReactNode, useEffect, useMemo, useState } from 'react';
import { useNavigate } from 'react-router-dom';
// material-ui
import Alert from '@mui/material/Alert';
import Box from '@mui/material/Box';
import Button from '@mui/material/Button';
import Chip from '@mui/material/Chip';
import Dialog from '@mui/material/Dialog';
import DialogActions from '@mui/material/DialogActions';
import DialogContent from '@mui/material/DialogContent';
import DialogTitle from '@mui/material/DialogTitle';
import FormControlLabel from '@mui/material/FormControlLabel';
import Stack from '@mui/material/Stack';
import Switch from '@mui/material/Switch';
import TextField from '@mui/material/TextField';
import ToggleButton from '@mui/material/ToggleButton';
import ToggleButtonGroup from '@mui/material/ToggleButtonGroup';
import Tooltip from '@mui/material/Tooltip';
import Typography from '@mui/material/Typography';
// third-party
import { enqueueSnackbar } from 'notistack';
import { mutate } from 'swr';
// project imports
import HoverHelp from 'components/HoverHelp';
import StaggerFields, { defaultStagger, staggerBody, StaggerForm, staggerProblem } from 'sections/runs/StaggerFields';
import TargetPicker, { effectiveReach, RunTarget, splitTargets, targetLabel } from 'sections/runs/TargetPicker';
import { runHeadline } from 'sections/runs/RunScriptDialog';
import {
DEFAULT_RESTART_WARNING_SECONDS,
MAX_RESTART_WARNING_SECONDS,
MIN_RESTART_WARNING_SECONDS,
restartDelayProblem,
restartWarningProblem
} from 'sections/scripts/RestartAfterRunFields';
import { compareVersions } from 'sections/upgrades/agentVersions';
import useApi from 'hooks/useApi';
import { api, errorMessage, keys } from 'api/client';
import { plural } from 'utils/format';
import { POWER_LABEL, POWER_MINIMUM_AGENT_VERSION } from 'utils/powerActions';
import type { DeviceDto, DeviceGroupDto, PowerAction } from 'api/types';
// assets
import ApartmentOutlined from '@ant-design/icons/ApartmentOutlined';
import PoweroffOutlined from '@ant-design/icons/PoweroffOutlined';
import ReloadOutlined from '@ant-design/icons/ReloadOutlined';
interface Props {
open: boolean;
onClose: () => void;
action?: PowerAction;
/** The devices and groups to restart or shut down. */
targets?: RunTarget[];
}
function Row({ label, children }: { label: ReactNode; children: ReactNode }) {
return (
<Stack
direction={{ xs: 'column', sm: 'row' }}
sx={{ gap: { xs: 0.5, sm: 2 }, py: 1.25, borderBottom: '1px solid', borderColor: 'divider' }}
>
<Typography variant="subtitle2" color="text.secondary" sx={{ width: { sm: 150 }, flex: 'none', pt: { sm: 0.75 } }}>
{label}
</Typography>
<Box sx={{ flex: 1, minWidth: 0 }}>{children}</Box>
</Stack>
);
}
// ==============================|| RESTART / SHUT DOWN ||============================== //
/**
* Restart or Shut Down the chosen devices and groups' members: a run like any other, with the
* delay, the warning for signed-in users, updates on Windows, Only Devices Online Now and a spread.
*/
export default function PowerDialog({ open, onClose, action: initialAction = 'restart', targets = [] }: Props) {
const navigate = useNavigate();
const { data: devices } = useApi<DeviceDto[]>(open ? keys.devices : null);
const { data: groups } = useApi<DeviceGroupDto[]>(open ? keys.groups : null);
const [action, setAction] = useState<PowerAction>(initialAction);
const [excludes, setExcludes] = useState<RunTarget[]>([]);
const [delayMinutes, setDelayMinutes] = useState('0');
const [warningSeconds, setWarningSeconds] = useState(0);
const [installUpdates, setInstallUpdates] = useState(false);
const [onlineOnly, setOnlineOnly] = useState(true);
const [stagger, setStagger] = useState<StaggerForm>(defaultStagger);
const [busy, setBusy] = useState(false);
const [error, setError] = useState('');
useEffect(() => {
if (!open) return;
setAction(initialAction);
setExcludes([]);
setDelayMinutes('0');
setWarningSeconds(0);
setInstallUpdates(false);
setOnlineOnly(true);
setStagger(defaultStagger());
setError('');
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [open]);
const { devices: reached, excluded } = useMemo(
() => effectiveReach(devices ?? [], groups ?? [], targets, excludes),
[devices, groups, targets, excludes]
);
const orphaned = reached.filter((d) => d.isOrphaned).length;
const online = reached.filter((d) => d.status === 'online' && !d.isOrphaned).length;
const offline = reached.length - orphaned - online;
const going = reached.filter((d) => !d.isOrphaned && (!onlineOnly || d.status === 'online'));
// Too old to shut down or install updates: their jobs fail rather than restart them.
const needsCurrent = action === 'shutDown' || installUpdates;
const tooOld = needsCurrent ? going.filter((d) => compareVersions(d.agentVersion, POWER_MINIMUM_AGENT_VERSION) < 0).length : 0;
const willGo = going.length - tooOld;
const delaySeconds = delayMinutes.trim() === '' ? 0 : Math.round(Number(delayMinutes) * 60);
const label = POWER_LABEL[action];
const blocked =
targets.length === 0
? 'Choose devices or groups.'
: willGo === 0
? 'None of these devices can do it now.'
: (restartDelayProblem(delaySeconds) ?? restartWarningProblem(warningSeconds) ?? staggerProblem(stagger) ?? undefined);
const start = async () => {
setBusy(true);
setError('');
try {
const { clientIds, groupIds } = splitTargets(targets);
const result = await api.power({
action,
clientIds,
groupIds,
excludeClientIds: splitTargets(excludes).clientIds,
excludeGroupIds: splitTargets(excludes).groupIds,
delaySeconds,
warningSeconds,
installUpdates,
onlineOnly,
...staggerBody(stagger)
});
void mutate((key) => typeof key === 'string' && (key.startsWith(keys.dashboardPrefix) || key.startsWith('/api/executions')));
enqueueSnackbar(`${label}: ${runHeadline(result)}`, { variant: result.jobs.length > 0 ? 'success' : 'warning' });
onClose();
if (result.runId) navigate(`/runs/${result.runId}`);
} catch (e) {
setError(errorMessage(e, `${label} could not be started.`));
} finally {
setBusy(false);
}
};
return (
<Dialog open={open} onClose={busy ? undefined : onClose} maxWidth="md" fullWidth>
<DialogTitle sx={{ pb: 1 }}>
<Stack direction="row" sx={{ gap: 1.5, alignItems: 'center', flexWrap: 'wrap' }}>
{label}
<ToggleButtonGroup
exclusive
size="small"
value={action}
onChange={(_, next: PowerAction | null) => next && setAction(next)}
aria-label="Power action"
disabled={busy}
>
<ToggleButton value="restart">
<ReloadOutlined style={{ marginRight: 6 }} />
Restart
</ToggleButton>
<ToggleButton value="shutDown">
<PoweroffOutlined style={{ marginRight: 6 }} />
Shut Down
</ToggleButton>
</ToggleButtonGroup>
</Stack>
</DialogTitle>
<DialogContent sx={{ px: 3, py: 1 }}>
<Row label="Targets">
<Stack direction="row" sx={{ gap: 0.75, flexWrap: 'wrap', pt: 0.5 }}>
{targets.slice(0, 12).map((t) => (
<Chip
key={`${t.kind}:${t.id}`}
size="small"
variant="light"
color={t.kind === 'group' ? 'primary' : 'secondary'}
icon={t.kind === 'group' ? <ApartmentOutlined /> : undefined}
label={targetLabel(t, devices ?? [], groups ?? [])}
/>
))}
{targets.length > 12 && <Chip size="small" variant="outlined" label={`+${(targets.length - 12).toLocaleString()}`} />}
</Stack>
</Row>
<Row label="Exclude">
<TargetPicker
multiple
exclude
label="Exclude"
devices={devices ?? []}
groups={groups ?? []}
value={excludes}
onChange={setExcludes}
disabled={busy}
/>
</Row>
<Row label="Reach">
<Stack direction="row" sx={{ gap: 2.5, flexWrap: 'wrap', pt: 0.5 }}>
<Typography variant="body2">
<b>{reached.length}</b> {reached.length === 1 ? 'Device' : 'Devices'}
</Typography>
{excluded > 0 && (
<Typography variant="body2" color="text.secondary">
<b>{excluded}</b> Excluded
</Typography>
)}
<Typography variant="body2" color="success.main">
<b>{online}</b> Online
</Typography>
<Tooltip title={onlineOnly ? 'Skipped: Only Devices Online Now is on.' : `They ${label.toLowerCase()} when they reconnect.`}>
<Typography variant="body2" color="text.secondary">
<b>{offline}</b> Offline
</Typography>
</Tooltip>
{orphaned > 0 && (
<Tooltip title="Skipped until they re-enroll.">
<Typography variant="body2" color="warning.main">
<b>{orphaned}</b> Orphaned
</Typography>
</Tooltip>
)}
{tooOld > 0 && (
<Tooltip title={`Agents older than ${POWER_MINIMUM_AGENT_VERSION}: their jobs fail instead.`}>
<Typography variant="body2" color="error.main">
<b>{tooOld}</b> Agent Too Old
</Typography>
</Tooltip>
)}
</Stack>
</Row>
<Row label="When">
<Stack direction="row" sx={{ gap: 1.5, alignItems: 'flex-start', flexWrap: 'wrap' }}>
<TextField
size="small"
type="number"
label={
<>
Delay (min)
<HoverHelp title="0 to 60 minutes after each device's job. Cancel it from the job meanwhile." />
</>
}
value={delayMinutes}
disabled={busy}
error={Boolean(restartDelayProblem(delaySeconds))}
helperText={restartDelayProblem(delaySeconds) ?? undefined}
onChange={(e) => setDelayMinutes(e.target.value)}
sx={{ width: 140 }}
slotProps={{ htmlInput: { min: 0, max: 60 } }}
/>
<FormControlLabel
sx={{ ml: 0, mt: 0.5 }}
disabled={busy}
control={
<Switch
size="small"
checked={warningSeconds !== 0}
onChange={(e) => setWarningSeconds(e.target.checked ? DEFAULT_RESTART_WARNING_SECONDS : 0)}
/>
}
label={
<>
Warn Signed-In Users
<HoverHelp title="The system's own notice for this long before it goes; nobody signed in: at once. Older agents show it for the whole delay." />
</>
}
/>
{warningSeconds !== 0 && (
<TextField
size="small"
type="number"
label="Warning (s)"
value={String(warningSeconds)}
disabled={busy}
error={Boolean(restartWarningProblem(warningSeconds))}
helperText={restartWarningProblem(warningSeconds) ?? undefined}
onChange={(e) =>
setWarningSeconds(e.target.value.trim() === '' ? MIN_RESTART_WARNING_SECONDS : Math.round(Number(e.target.value)))
}
sx={{ width: 120 }}
slotProps={{ htmlInput: { min: MIN_RESTART_WARNING_SECONDS, max: MAX_RESTART_WARNING_SECONDS } }}
/>
)}
</Stack>
</Row>
<Row label="Windows Updates">
<FormControlLabel
sx={{ m: 0 }}
disabled={busy}
control={<Switch checked={installUpdates} onChange={(e) => setInstallUpdates(e.target.checked)} />}
label={
<span>
Install Pending Updates
<HoverHelp
title={`Off: updates waiting for "Update and ${action === 'shutDown' ? 'shut down' : 'restart'}" stay waiting. An update Windows has already part-installed still finishes. Windows only; agent ${POWER_MINIMUM_AGENT_VERSION} or later.`}
/>
</span>
}
/>
</Row>
<Row label="Delivery">
<Stack sx={{ gap: 1 }}>
<FormControlLabel
sx={{ m: 0 }}
disabled={busy}
control={<Switch checked={onlineOnly} onChange={(e) => setOnlineOnly(e.target.checked)} />}
label={
<span>
Only Devices Online Now
<HoverHelp title={`Off: offline devices ${label.toLowerCase()} as soon as they reconnect.`} />
</span>
}
/>
<StaggerFields
value={stagger}
onChange={setStagger}
targets={willGo}
disabled={busy}
help="Spreads the devices over a period instead of all at once, in a shuffled order; each one's delay starts at its own turn."
/>
</Stack>
</Row>
</DialogContent>
{error && (
<Alert severity="error" sx={{ mx: 3, mt: 1.5 }} onClose={() => setError('')}>
{error}
</Alert>
)}
<DialogActions sx={{ px: 3, py: 2, gap: 1 }}>
<Button color="secondary" onClick={onClose} disabled={busy}>
Cancel
</Button>
<Tooltip title={blocked ?? ''}>
<span>
<Button
variant="contained"
color={action === 'shutDown' ? 'error' : 'warning'}
startIcon={action === 'shutDown' ? <PoweroffOutlined /> : <ReloadOutlined />}
onClick={start}
disabled={busy || Boolean(blocked)}
>
{busy ? 'Starting…' : willGo > 0 ? `${label} ${plural(willGo, 'Device')}` : label}
</Button>
</span>
</Tooltip>
</DialogActions>
</Dialog>
);
}
@@ -49,7 +49,7 @@ export default function useDeviceActions(
) {
const navigate = useNavigate();
const { can } = useSession();
const { openRun, openSchedule } = useAutomation();
const { openRun, openSchedule, openPower } = useAutomation();
const tools = useDeviceToolOpener();
const { data: groups } = useApi<DeviceGroupDto[]>(keys.groups);
@@ -87,6 +87,16 @@ export default function useDeviceActions(
{
run: () => openRun({ targets: devices.filter((d) => !d.isOrphaned).map((d) => ({ kind: 'device', id: d.clientId })) }),
schedule: () => openSchedule({ preset: { target: { kind: 'device', id: devices[0].clientId } } }),
restart: () =>
openPower({
action: 'restart',
targets: devices.filter((d) => !d.isOrphaned).map((d) => ({ kind: 'device', id: d.clientId }))
}),
shutDown: () =>
openPower({
action: 'shutDown',
targets: devices.filter((d) => !d.isOrphaned).map((d) => ({ kind: 'device', id: d.clientId }))
}),
openTool: (target) => tools.openHere(devices[0].clientId, target),
popOutTool: (target) => tools.popOut(devices[0], target),
addToGroup: () => {
@@ -224,6 +224,7 @@ export default function FunctionEditor({ module, folder, existingNames, gate, on
title={draft.name.trim() || title}
height="max(420px, calc(100vh - 460px))"
save={saveControl}
snippetEngine="PowerShell"
/>
</Stack>
@@ -33,6 +33,8 @@ import DisconnectOutlined from '@ant-design/icons/DisconnectOutlined';
import EditOutlined from '@ant-design/icons/EditOutlined';
import PlayCircleOutlined from '@ant-design/icons/PlayCircleOutlined';
import PlusOutlined from '@ant-design/icons/PlusOutlined';
import PoweroffOutlined from '@ant-design/icons/PoweroffOutlined';
import ReloadOutlined from '@ant-design/icons/ReloadOutlined';
import RollbackOutlined from '@ant-design/icons/RollbackOutlined';
import VerticalAlignTopOutlined from '@ant-design/icons/VerticalAlignTopOutlined';
@@ -50,6 +52,8 @@ export function groupMenu(
duplicate: () => void;
toTop: () => void;
viewDevices: () => void;
restart: () => void;
shutDown: () => void;
upgradeAgents: () => void;
rollBackAgents: () => void;
removeAgents: () => void;
@@ -79,6 +83,23 @@ export function groupMenu(
},
{ kind: 'item', id: 'devices', label: 'View Devices', icon: <DesktopOutlined />, onSelect: handlers.viewDevices },
{ kind: 'divider' },
{
kind: 'item',
id: 'restart',
label: 'Restart…',
icon: <ReloadOutlined />,
disabledReason: can('devices.power') ? empty : NEEDS('Restart and Shut Down'),
onSelect: handlers.restart
},
{
kind: 'item',
id: 'shut-down',
label: 'Shut Down…',
icon: <PoweroffOutlined />,
disabledReason: can('devices.power') ? empty : NEEDS('Restart and Shut Down'),
onSelect: handlers.shutDown
},
{ kind: 'divider' },
{
kind: 'item',
id: 'upgrade-agents',
@@ -150,7 +171,7 @@ export default function useGroupActions(
) {
const navigate = useNavigate();
const { can } = useSession();
const { openRun, openSchedule } = useAutomation();
const { openRun, openSchedule, openPower } = useAutomation();
const { data: groups } = useApi<DeviceGroupDto[]>(keys.groups);
const { data: devices } = useApi<DeviceDto[]>(keys.devices);
const { data: triggers } = useApi<ScriptTriggerDto[]>(can('automation.view') ? keys.triggers : null);
@@ -209,6 +230,8 @@ export default function useGroupActions(
duplicate: () => void duplicate(group),
toTop: () => requestMove(group.id, null),
viewDevices: () => navigate(`/devices?group=${group.id}`),
restart: () => openPower({ action: 'restart', targets: [{ kind: 'group', id: group.id }] }),
shutDown: () => openPower({ action: 'shutDown', targets: [{ kind: 'group', id: group.id }] }),
upgradeAgents: () =>
upgrades.upgrade({ groupIds: [group.id], name: { group: groupPath(groups ?? [], group.id) }, count: group.memberCount }),
rollBackAgents: () => upgrades.rollBack({ groupIds: [group.id], name: { group: groupPath(groups ?? [], group.id) } }),
@@ -19,6 +19,7 @@ import Tooltip from '@mui/material/Tooltip';
import Typography from '@mui/material/Typography';
// project imports
import ScriptLink from 'components/ScriptLink';
import IconButton from 'components/@extended/IconButton';
import CopyButton from 'components/CopyButton';
import { AbsoluteTime } from 'components/DateTime';
@@ -298,9 +299,7 @@ function JobOutputPanel({ jobId, onClose }: { jobId: string; onClose: () => void
</Link>
</Meta>
<Meta label="Script">
<Link component={RouterLink} to={`/scripts/${job.scriptId}`} underline="hover">
{job.scriptName}
</Link>
<ScriptLink scriptId={job.scriptId}>{job.scriptName}</ScriptLink>
</Meta>
<Meta label="Exit Code">
<Box component="span" sx={{ fontFamily: 'var(--font-mono)' }}>
+4 -4
View File
@@ -1,16 +1,16 @@
import { MouseEvent, useCallback, useMemo, useState } from 'react';
import { Link as RouterLink, useNavigate } from 'react-router-dom';
import { useNavigate } from 'react-router-dom';
// material-ui
import Chip from '@mui/material/Chip';
import InputAdornment from '@mui/material/InputAdornment';
import Link from '@mui/material/Link';
import MenuItem from '@mui/material/MenuItem';
import Stack from '@mui/material/Stack';
import TextField from '@mui/material/TextField';
import Typography from '@mui/material/Typography';
// project imports
import ScriptLink from 'components/ScriptLink';
import DataTable, { Column } from 'components/DataTable';
import { RelativeTime } from 'components/DateTime';
import EmptyState from 'components/EmptyState';
@@ -54,9 +54,9 @@ export const runColumns = (showScript: boolean): Column<ExecutionSummaryDto>[] =
sortValue: (r: ExecutionSummaryDto) => r.scriptName,
cell: (r: ExecutionSummaryDto) => (
<Stack sx={{ gap: 0.5, alignItems: 'flex-start', minWidth: 0 }}>
<Link component={RouterLink} to={`/scripts/${r.scriptId}`} underline="hover" onClick={stop}>
<ScriptLink scriptId={r.scriptId} onClick={stop}>
{r.scriptName ?? 'Script'}
</Link>
</ScriptLink>
<SequenceRefChip sequence={r.sequence} />
</Stack>
)
@@ -518,6 +518,8 @@ export default function RunProgress({
const start = t.state === 'queued' && t.notBeforeUtc ? Date.parse(t.notBeforeUtc) : undefined;
return {
...t,
// Shut Down's restart words come from the run's script.
scriptId: run.scriptId,
id: t.jobId,
hostname: t.hostname ?? t.clientId,
startsAt: start !== undefined && start > serverNow ? start - serverNow + receivedAt : undefined
@@ -56,6 +56,8 @@ export interface ScriptDraft {
cleanUpAfterRun: boolean;
setWorkingDirectory: boolean;
runAsUser: boolean;
/** With runAsUser: once for each signed-in user. */
runAsEachUser: boolean;
restartAfterRun: RestartAfterRun;
restartDelaySeconds: number;
/** Warn Signed-In Users: 0 is off. */
@@ -82,6 +84,7 @@ export const NEW_SCRIPT_DRAFT: ScriptDraft = {
cleanUpAfterRun: true,
setWorkingDirectory: false,
runAsUser: false,
runAsEachUser: false,
restartAfterRun: 'off',
restartDelaySeconds: 0,
restartWarningSeconds: 0
@@ -105,6 +108,7 @@ export function draftFromScript(script: ScriptDto): ScriptDraft {
cleanUpAfterRun: script.cleanUpAfterRun ?? true,
setWorkingDirectory: script.setWorkingDirectory ?? false,
runAsUser: script.runAsUser ?? false,
runAsEachUser: script.runAsEachUser ?? false,
restartAfterRun: script.restartAfterRun ?? 'off',
restartDelaySeconds: script.restartDelaySeconds ?? 0,
restartWarningSeconds: script.restartWarningSeconds ?? 0
@@ -143,6 +147,7 @@ export function saveBody(draft: ScriptDraft, name = draft.name): SaveScriptBody
cleanUpAfterRun: stored.cleanUpAfterRun,
setWorkingDirectory: stagesFile(stored.engine, stored.runFromFile, stored.runAsUser) && stored.setWorkingDirectory,
runAsUser: stored.runAsUser,
runAsEachUser: stored.runAsUser && stored.runAsEachUser,
restartAfterRun: stored.restartAfterRun,
restartDelaySeconds: stored.restartAfterRun === 'off' ? 0 : stored.restartDelaySeconds,
restartWarningSeconds: stored.restartAfterRun === 'off' ? 0 : stored.restartWarningSeconds
@@ -0,0 +1,90 @@
// material-ui
import Alert from '@mui/material/Alert';
import Button from '@mui/material/Button';
import ButtonGroup from '@mui/material/ButtonGroup';
import Paper from '@mui/material/Paper';
import Stack from '@mui/material/Stack';
import Tooltip from '@mui/material/Tooltip';
import Typography from '@mui/material/Typography';
// project imports
import HoverHelp from 'components/HoverHelp';
import { COPY_KEYS, PASTE_HELP, PASTE_KEYS, pasteQuestion, type ClipboardPrompt, type ShellController } from './shellSessions';
// assets
import CopyOutlined from '@ant-design/icons/CopyOutlined';
/** Copy the terminal's selection, paste the operator's clipboard. */
export function ClipboardButtons({
controller,
hasSelection,
open
}: {
controller: ShellController;
hasSelection: boolean;
open: boolean;
}) {
return (
<ButtonGroup variant="outlined" color="secondary" aria-label="Clipboard">
<Tooltip title={`Copy the selected text (${COPY_KEYS})`}>
<span>
<Button
startIcon={<CopyOutlined />}
disabled={!hasSelection}
// Keep the terminal's focus and selection.
onMouseDown={(e) => e.preventDefault()}
onClick={() => controller.copySelection(false)}
>
Copy
</Button>
</span>
</Tooltip>
{controller.canReadClipboard && (
<Tooltip title={`Type the clipboard's text at the prompt (${PASTE_KEYS}, or right-click)`}>
<span>
<Button disabled={!open} onMouseDown={(e) => e.preventDefault()} onClick={() => void controller.pasteFromClipboard()}>
Paste
</Button>
</span>
</Tooltip>
)}
</ButtonGroup>
);
}
/** The question before a multi-line paste, or a short clipboard notice, over the terminal's corner. */
export function ClipboardPromptCard({ prompt, controller }: { prompt: ClipboardPrompt; controller: ShellController }) {
const placement = { position: 'absolute', right: 16, bottom: 16, zIndex: 2, maxWidth: 'calc(100% - 32px)' } as const;
if (prompt.kind === 'note')
return (
<Alert severity="warning" onClose={() => controller.dismissClipboard()} sx={placement}>
{prompt.text}
</Alert>
);
return (
<Paper
elevation={8}
role="alertdialog"
aria-label={pasteQuestion(prompt.lines)}
onKeyDown={(e) => {
if (e.key === 'Escape') controller.dismissClipboard();
}}
sx={{ ...placement, p: 1.5, pl: 2 }}
>
<Stack direction="row" sx={{ alignItems: 'center', gap: 1.5 }}>
<Stack direction="row" sx={{ alignItems: 'center' }}>
<Typography variant="subtitle1">{pasteQuestion(prompt.lines)}</Typography>
<HoverHelp title={PASTE_HELP} />
</Stack>
<Button variant="contained" size="small" autoFocus onClick={() => controller.confirmPaste()}>
Paste
</Button>
<Button size="small" color="secondary" onClick={() => controller.dismissClipboard()}>
Cancel
</Button>
</Stack>
</Paper>
);
}
+79 -2
View File
@@ -3,10 +3,22 @@ import { createPortal } from 'react-dom';
import { useNavigate } from 'react-router-dom';
// project imports
import { shellLabel, shells, TERMINAL_THEME, type ShellController, type ShellState } from './shellSessions';
import {
COPY_KEYS,
PASTE_HELP,
PASTE_KEYS,
pasteQuestion,
shellLabel,
shells,
TERMINAL_THEME,
type ClipboardPrompt,
type ShellController,
type ShellState
} from './shellSessions';
import { FONT_SIZE, TERMINAL_THEMES, terminalPrefs, useTerminalPrefs } from './terminalPrefs';
// assets
import CopyOutlined from '@ant-design/icons/CopyOutlined';
import ImportOutlined from '@ant-design/icons/ImportOutlined';
import PoweroffOutlined from '@ant-design/icons/PoweroffOutlined';
import ReloadOutlined from '@ant-design/icons/ReloadOutlined';
@@ -61,11 +73,55 @@ const CHROME_CSS = `
.prefs .size { min-width: 34px; text-align: center; color: #c9d4e5; font-variant-numeric: tabular-nums; }
select { height: 28px; border-radius: 4px; border: 1px solid #2a3b5c; background: #111a29; color: ${TERMINAL_THEME.foreground}; font: inherit; padding: 0 6px; }
select:focus-visible { outline: 2px solid ${TERMINAL_THEME.cursor}; outline-offset: 1px; }
button:disabled { opacity: 0.45; cursor: default; background: transparent; }
.clip { position: fixed; right: 16px; bottom: 16px; z-index: 10; max-width: calc(100% - 32px); display: flex; align-items: center;
gap: 8px; padding: 8px 8px 8px 14px; border-radius: 6px; background: #111a29; border: 1px solid #2a3b5c;
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.45); }
.clip .question { font-weight: 600; white-space: nowrap; }
.clip.note { border-color: #d29922; color: #e3b341; }
.clip button.primary { background: ${TERMINAL_THEME.cursor}; border-color: ${TERMINAL_THEME.cursor}; color: #fff; }
`;
/** The paste question or a clipboard notice, over the terminal's corner. */
function ClipboardCard({ controller, prompt }: { controller: ShellController; prompt: ClipboardPrompt }) {
if (prompt.kind === 'note')
return (
<div className="clip note" role="status">
<span>{prompt.text}</span>
<button type="button" aria-label="Dismiss" onClick={() => controller.dismissClipboard()}>
✕
</button>
</div>
);
return (
<div
className="clip"
role="alertdialog"
aria-label={pasteQuestion(prompt.lines)}
onKeyDown={(e) => {
if (e.key === 'Escape') controller.dismissClipboard();
}}
>
<span className="question" title={PASTE_HELP}>
{pasteQuestion(prompt.lines)}
</span>
{/* Focused so Enter confirms and Escape cancels. */}
<button type="button" className="primary" autoFocus onClick={() => controller.confirmPaste()}>
Paste
</button>
<button type="button" onClick={() => controller.dismissClipboard()}>
Cancel
</button>
</div>
);
}
function Chrome({ controller }: { controller: ShellController }) {
const navigate = useNavigate();
const { state, message, hostname, startedShell } = useSyncExternalStore(controller.subscribe, controller.getSnapshot);
const { state, message, hostname, startedShell, hasSelection, clipboard } = useSyncExternalStore(
controller.subscribe,
controller.getSnapshot
);
const started = shellLabel(startedShell);
const name = hostname || controller.clientId.slice(0, 12);
const active = ACTIVE.includes(state);
@@ -118,6 +174,26 @@ function Chrome({ controller }: { controller: ShellController }) {
A+
</button>
</div>
<button
type="button"
title={`Copy the selected text (${COPY_KEYS})`}
disabled={!hasSelection}
onMouseDown={(e) => e.preventDefault()}
onClick={() => controller.copySelection(false)}
>
<CopyOutlined /> Copy
</button>
{controller.canReadClipboard && (
<button
type="button"
title={`Type the clipboard's text at the prompt (${PASTE_KEYS}, or right-click)`}
disabled={state !== 'open'}
onMouseDown={(e) => e.preventDefault()}
onClick={() => void controller.pasteFromClipboard()}
>
Paste
</button>
)}
{active ? (
<button type="button" className="danger" onClick={() => controller.close()}>
<PoweroffOutlined /> Close Session
@@ -137,6 +213,7 @@ function Chrome({ controller }: { controller: ShellController }) {
</button>
</div>
</div>
{clipboard && <ClipboardCard controller={controller} prompt={clipboard} />}
</>
);
}
@@ -4,10 +4,12 @@ import { useState } from 'react';
import Box from '@mui/material/Box';
import Button from '@mui/material/Button';
import ButtonBase from '@mui/material/ButtonBase';
import FormControlLabel from '@mui/material/FormControlLabel';
import IconButton from '@mui/material/IconButton';
import MenuItem from '@mui/material/MenuItem';
import Popover from '@mui/material/Popover';
import Stack from '@mui/material/Stack';
import Switch from '@mui/material/Switch';
import TextField from '@mui/material/TextField';
import Tooltip from '@mui/material/Tooltip';
import Typography from '@mui/material/Typography';
@@ -15,14 +17,38 @@ import Typography from '@mui/material/Typography';
// project imports
import HoverHelp from 'components/HoverHelp';
import { MONO_FONT_FAMILY } from 'config';
import { FONT_SIZE, SCROLLBACK_OPTIONS, TERMINAL_THEMES, terminalPrefs, useTerminalPrefs } from './terminalPrefs';
import { CLIPBOARD_KEYS_HELP } from './shellSessions';
import { FONT_SIZE, SCROLLBACK_OPTIONS, TERMINAL_THEMES, terminalPrefs, useTerminalPrefs, type RightClick } from './terminalPrefs';
// assets
import FontSizeOutlined from '@ant-design/icons/FontSizeOutlined';
import MinusOutlined from '@ant-design/icons/MinusOutlined';
import PlusOutlined from '@ant-design/icons/PlusOutlined';
/** Theme, text size and scrollback of every terminal in this browser. */
function SettingSwitch({
label,
help,
checked,
onChange
}: {
label: string;
help: string;
checked: boolean;
onChange: (on: boolean) => void;
}) {
return (
<Stack direction="row" sx={{ alignItems: 'center' }}>
<FormControlLabel
control={<Switch size="small" checked={checked} onChange={(e) => onChange(e.target.checked)} />}
label={label}
sx={{ mr: 0 }}
/>
<HoverHelp title={help} />
</Stack>
);
}
/** Theme, text size, scrollback and clipboard behaviour of every terminal in this browser. */
export default function TerminalSettings() {
const prefs = useTerminalPrefs();
const [anchor, setAnchor] = useState<HTMLElement | null>(null);
@@ -128,6 +154,35 @@ export default function TerminalSettings() {
))}
</TextField>
</Stack>
<Stack sx={{ gap: 1 }}>
<Stack direction="row" sx={{ alignItems: 'center' }}>
<Typography variant="subtitle2">Clipboard</Typography>
<HoverHelp title={CLIPBOARD_KEYS_HELP} />
</Stack>
<TextField
select
size="small"
label="Right-Click"
value={prefs.rightClick}
onChange={(e) => terminalPrefs.set({ rightClick: e.target.value as RightClick })}
>
<MenuItem value="copyPaste">Copy Selection, Else Paste</MenuItem>
<MenuItem value="menu">Browser Menu</MenuItem>
</TextField>
<SettingSwitch
label="Copy on Select"
help="Selecting text copies it at once."
checked={prefs.copyOnSelect}
onChange={(copyOnSelect) => terminalPrefs.set({ copyOnSelect })}
/>
<SettingSwitch
label="Ask Before Multi-Line Paste"
help="A shell without bracketed paste runs each pasted line as it arrives."
checked={prefs.warnMultiLine}
onChange={(warnMultiLine) => terminalPrefs.set({ warnMultiLine })}
/>
</Stack>
</Stack>
</Popover>
</>
+261 -10
View File
@@ -7,7 +7,7 @@ import { api, errorMessage } from 'api/client';
import { MONO_FONT_FAMILY } from 'config';
import { POPOUT_SIZE, popOutWindowName } from 'sections/deviceTools/deviceTools';
import { nats, type ShellEvent } from 'messaging/nats';
import { terminalPrefs, themeOf } from './terminalPrefs';
import { terminalPrefs, themeOf, type TerminalPrefs } from './terminalPrefs';
// assets
import xtermCss from '@xterm/xterm/css/xterm.css?inline';
@@ -38,6 +38,57 @@ export interface ShellSnapshot {
startedUser?: string;
/** Who the agent last reported signed in on the device (kept across reconnects). */
signedInUsers?: string[];
/** Text is selected in the terminal (something to copy). */
hasSelection: boolean;
/** A paste waiting for the operator to confirm it, or a short clipboard notice. */
clipboard?: ClipboardPrompt;
}
export type ClipboardPrompt = { kind: 'confirm'; lines: number } | { kind: 'note'; text: string };
const IS_MAC = /Mac|iPhone|iPad/.test(navigator.platform);
/** The paste shortcut as this operator's keyboard spells it. */
export const PASTE_KEYS = IS_MAC ? '⌘V' : 'Ctrl+V';
export const COPY_KEYS = IS_MAC ? '⌘C' : 'Ctrl+C or Ctrl+Shift+C';
export const CLIPBOARD_KEYS_HELP = IS_MAC
? 'Copy: ⌘C. Paste: ⌘V.'
: 'Copy: Ctrl+Shift+C, or Ctrl+C while text is selected (with nothing selected it interrupts). Paste: Ctrl+V, Ctrl+Shift+V or Shift+Insert.';
export const pasteQuestion = (lines: number) => `Paste ${lines.toLocaleString()} ${lines === 1 ? 'Line' : 'Lines'}?`;
export const PASTE_HELP = 'This shell runs each line as it arrives. Terminal Settings can turn this question off.';
/** A paste larger than this (UTF-8) is refused, as Remote View's clipboard is. */
const MAX_PASTE_BYTES = 1024 * 1024;
/** Input is sent in pieces no larger than this, so a big paste never makes one huge message. */
const INPUT_CHUNK_BYTES = 32 * 1024;
/** How long a clipboard notice stays. */
const NOTE_MS = 5000;
/** The lines a paste would type (a final line break ends the last line rather than starting another). */
function lineCount(text: string): number {
const lines = text.split(/\r\n|\r|\n/);
return lines[lines.length - 1] === '' ? lines.length - 1 : lines.length;
}
/** A right-click that copies or pastes must not first select the word under it (xterm does on macOS). */
const rightClickSelectsWord = (prefs: TerminalPrefs) => prefs.rightClick === 'menu' && IS_MAC;
/** Which clipboard shortcut a key event is, if any. macOS needs none: ⌘C and ⌘V reach the terminal as copy and paste. */
function clipboardKey(event: KeyboardEvent, hasSelection: boolean): 'copy' | 'paste' | null {
if (IS_MAC || event.altKey || event.metaKey) return null;
const key = event.key.toLowerCase();
if (event.ctrlKey) {
// Ctrl+C copies only while text is selected; otherwise it interrupts, as always.
if (key === 'c') return event.shiftKey || hasSelection ? 'copy' : null;
if (key === 'v') return 'paste';
if (key === 'insert' && !event.shiftKey) return 'copy';
return null;
}
return event.shiftKey && key === 'insert' ? 'paste' : null;
}
/** The shells a Windows device can start (ShellKinds on the server). */
@@ -157,7 +208,17 @@ export class ShellController {
private observer: ResizeObserver | null = null;
private offPrefs: (() => void) | null = null;
private session: Session | null = null;
private snapshot: ShellSnapshot = { state: 'connecting', hostname: '', poppedOut: false, shell: rememberedShell(), asUser: false };
private snapshot: ShellSnapshot = {
state: 'connecting',
hostname: '',
poppedOut: false,
shell: rememberedShell(),
asUser: false,
hasSelection: false
};
/** The text of a paste waiting for confirmation. */
private pendingPaste: string | null = null;
private noteTimer: number | undefined;
private readonly listeners = new Set<() => void>();
/** The shell page's terminal host while that page is mounted. */
@@ -233,12 +294,14 @@ export class ShellController {
fontSize: prefs.fontSize,
scrollback: prefs.scrollback,
cursorBlink: true,
theme: themeOf(prefs).theme
theme: themeOf(prefs).theme,
rightClickSelectsWord: rightClickSelectsWord(prefs)
});
this.term.loadAddon(this.fit);
this.term.open(this.element);
this.offPrefs = terminalPrefs.subscribe(() => this.applyPrefs());
this.bindZoom(this.term);
this.bindKeys(this.term);
this.bindClipboard(this.term);
this.term.onResize(({ cols, rows }) => {
const session = this.session;
if (session?.id && !session.closed) publish(session.id, 'command.shell.resize', { sessionId: session.id, cols, rows });
@@ -269,13 +332,30 @@ export class ShellController {
term.options.theme = theme;
term.options.fontSize = prefs.fontSize;
term.options.scrollback = prefs.scrollback;
term.options.rightClickSelectsWord = rightClickSelectsWord(prefs);
if (this.popup && !this.popup.closed) this.popup.document.body.style.background = theme.background;
this.safeFit();
}
/** Ctrl (or Cmd) with = / - / 0, or with the wheel, sizes the text while the terminal has focus. */
private bindZoom(term: Terminal) {
/**
* Ctrl (or Cmd) with = / - / 0, or with the wheel, sizes the text while the terminal has focus.
* Ctrl+Shift+C (or Ctrl+C over a selection, or Ctrl+Insert) copies; Ctrl+V, Ctrl+Shift+V and
* Shift+Insert paste through the browser's own paste, so no clipboard permission is asked.
*/
private bindKeys(term: Terminal) {
term.attachCustomKeyEventHandler((event) => {
const clip = clipboardKey(event, term.hasSelection());
if (clip === 'copy') {
if (event.type === 'keydown') {
event.preventDefault();
this.copySelection(true);
}
return false;
}
// Not handled by xterm (which would send ^V) and not prevented: the browser pastes into
// the terminal, and the paste listener below takes it from there.
if (clip === 'paste') return false;
if (event.type !== 'keydown' || !(event.ctrlKey || event.metaKey) || event.altKey || event.shiftKey) return true;
const step = event.key === '=' || event.key === '+' ? 1 : event.key === '-' ? -1 : event.key === '0' ? 0 : null;
if (step === null) return true;
@@ -295,6 +375,150 @@ export class ShellController {
);
}
// ── Clipboard ──────────────────────────────────────────────────────────
/** The window the terminal is in now (the console's or its pop-out's): its clipboard is the one that works. */
private get view(): Window {
return this.element.ownerDocument.defaultView ?? window;
}
/** The browser lets this page read the clipboard on request (a secure page; it may still ask once). */
get canReadClipboard(): boolean {
return typeof this.view.navigator.clipboard?.readText === 'function';
}
/**
* Every paste (keys, the browser's menu, a right-click, the Paste button) goes through
* pasteText, so the size cap and the multi-line check apply to all of them.
*/
private bindClipboard(term: Terminal) {
// Ahead of xterm's own paste handler (on elements inside this one), which it replaces.
this.element.addEventListener(
'paste',
(event) => {
event.preventDefault();
event.stopPropagation();
this.pasteText(event.clipboardData?.getData('text/plain') ?? '');
},
{ capture: true }
);
this.element.addEventListener(
'contextmenu',
(event) => {
if (terminalPrefs.get().rightClick !== 'copyPaste') return;
if (term.hasSelection()) {
event.preventDefault();
this.copySelection(true);
} else if (this.canReadClipboard) {
event.preventDefault();
void this.pasteFromClipboard();
}
// Otherwise the browser's menu opens; its Paste works without clipboard access.
},
{ capture: true }
);
this.element.addEventListener('mouseup', (event) => {
if (event.button === 0 && terminalPrefs.get().copyOnSelect && term.hasSelection()) this.copySelection(false);
});
term.onSelectionChange(() => {
const hasSelection = term.hasSelection();
if (hasSelection !== this.snapshot.hasSelection) this.update({ hasSelection });
});
}
/** Copies the terminal's selection; `clear` drops the selection once copied. False when nothing is selected. */
copySelection(clear: boolean): boolean {
const term = this.term;
if (!term?.hasSelection()) return false;
const text = term.getSelection();
const done = () => {
if (clear) term.clearSelection();
};
const clipboard = this.view.navigator.clipboard;
if (typeof clipboard?.writeText === 'function') {
clipboard.writeText(text).then(done, () => (this.copyByCommand() ? done() : this.note('The browser blocked the clipboard.')));
} else if (this.copyByCommand()) {
done();
} else {
this.note('The browser blocked the clipboard.');
}
return true;
}
/** Plain HTTP has no clipboard API: the copy command still works, and xterm's copy handler supplies the selection. */
private copyByCommand(): boolean {
this.term?.focus();
try {
return this.element.ownerDocument.execCommand('copy');
} catch {
return false;
}
}
/** Pastes what the operator's clipboard holds (the Paste button, a right-click). */
async pasteFromClipboard() {
const clipboard = this.view.navigator.clipboard;
if (typeof clipboard?.readText !== 'function') {
this.note(`This page cannot read the clipboard. Use ${PASTE_KEYS}.`);
return;
}
try {
this.pasteText(await clipboard.readText());
} catch {
this.note(`The browser blocked reading the clipboard. Use ${PASTE_KEYS}.`);
}
}
/** Types pasted text into the shell, asking first when the shell would run its lines one by one. */
private pasteText(text: string) {
const term = this.term;
const session = this.session;
if (!term || !text || !session?.id || session.closed) return;
if (encoder.encode(text).length > MAX_PASTE_BYTES) {
this.note('Not pasted: more than 1 MiB.');
return;
}
// A shell in bracketed paste mode takes the whole paste as one edit and runs nothing.
if (/[\r\n]/.test(text) && !term.modes.bracketedPasteMode && terminalPrefs.get().warnMultiLine) {
window.clearTimeout(this.noteTimer);
this.pendingPaste = text;
this.update({ clipboard: { kind: 'confirm', lines: lineCount(text) } });
return;
}
term.paste(text);
term.focus();
}
/** The operator confirmed the waiting paste. */
confirmPaste() {
const text = this.pendingPaste;
this.pendingPaste = null;
this.update({ clipboard: undefined });
const session = this.session;
if (text && this.term && session?.id && !session.closed) this.term.paste(text);
this.term?.focus();
}
/** Drops the waiting paste or the notice. */
dismissClipboard() {
window.clearTimeout(this.noteTimer);
this.pendingPaste = null;
if (this.snapshot.clipboard) this.update({ clipboard: undefined });
this.term?.focus();
}
private note(text: string) {
window.clearTimeout(this.noteTimer);
this.pendingPaste = null;
this.update({ clipboard: { kind: 'note', text } });
this.noteTimer = window.setTimeout(() => {
if (this.snapshot.clipboard?.kind === 'note') this.update({ clipboard: undefined });
}, NOTE_MS);
}
private safeFit() {
// Hidden or zero-sized hosts cannot be measured; the observer refits once visible.
if (this.element.isConnected && this.element.clientWidth > 0) this.fit.fit();
@@ -427,7 +651,10 @@ export class ShellController {
}
};
this.session = session;
this.update({ state: 'connecting', message: undefined, startedShell: undefined, startedUser: undefined });
// A paste waiting for the last session is not typed into the next one.
this.pendingPaste = null;
window.clearTimeout(this.noteTimer);
this.update({ state: 'connecting', message: undefined, startedShell: undefined, startedUser: undefined, clipboard: undefined });
const handle = (event: ShellEvent) => {
if (event.type === 'shell.output') {
@@ -446,7 +673,8 @@ export class ShellController {
window.clearTimeout(timer);
session.closed = true;
const text = next === 'failed' ? `Failed: ${detail ?? 'unknown error'}` : `Closed: ${detail ?? 'session ended'}`;
this.update({ state: next, message: text });
this.pendingPaste = null;
this.update({ state: next, message: text, clipboard: undefined });
this.writeNotice(text, 90);
}
};
@@ -460,7 +688,10 @@ export class ShellController {
const input = term.onData((data) => {
if (!session.id || session.closed) return;
publish(session.id, 'shell.input', { sessionId: session.id, dataBase64: toBase64(encoder.encode(data)) });
// The agent writes the bytes straight to the terminal, so a piece may end mid-character.
const bytes = encoder.encode(data);
for (let i = 0; i < bytes.length; i += INPUT_CHUNK_BYTES)
publish(session.id, 'shell.input', { sessionId: session.id, dataBase64: toBase64(bytes.subarray(i, i + INPUT_CHUNK_BYTES)) });
});
void (async () => {
@@ -510,7 +741,8 @@ export class ShellController {
if (!session || session.closed) return;
session.closed = true;
if (session.id) publish(session.id, 'command.shell.close', { sessionId: session.id, reason });
if (!this.disposed) this.update({ state: 'disconnected', message: undefined });
this.pendingPaste = null;
if (!this.disposed) this.update({ state: 'disconnected', message: undefined, clipboard: undefined });
}
/** Opens a new session as a signed-in user (`user`, or the usual pick) or the agent's account. */
@@ -529,6 +761,23 @@ export class ShellController {
if (this.term) this.reconnect();
}
/**
* Types `text` at the shell's prompt as a paste (bracketed when the shell asked for it), without
* the trailing line break, so nothing runs until the operator presses Enter. False when no session is open.
*/
insertText(text: string): 'inserted' | 'closed' | 'multiline' {
const term = this.term;
const session = this.session;
if (!term || !session?.id || session.closed) return 'closed';
const trimmed = text.replace(/\s+$/, '');
// Each line break would be an Enter, and that line would run, unless the shell asked for
// bracketed paste (then it takes the whole paste as one edit and runs nothing).
if (/[\r\n]/.test(trimmed) && !term.modes.bracketedPasteMode) return 'multiline';
term.paste(trimmed);
term.focus();
return 'inserted';
}
/** Closes any current session and opens a new one in the same terminal. */
reconnect() {
this.close('reconnecting');
@@ -542,6 +791,8 @@ export class ShellController {
if (this.disposed) return;
this.close(reason);
this.disposed = true;
window.clearTimeout(this.noteTimer);
this.pendingPaste = null;
this.session?.dispose();
this.session = null;
this.closePopup();
+23 -3
View File
@@ -418,23 +418,43 @@ export const FONT_SIZE = { min: 9, max: 28, default: 13 };
export const SCROLLBACK_OPTIONS = [1_000, 5_000, 10_000, 25_000];
const DEFAULT_SCROLLBACK = 10_000;
/** What a right-click in the terminal does: copy the selection, else paste (as Windows Terminal and PuTTY do), or open the browser's menu. */
export type RightClick = 'copyPaste' | 'menu';
export interface TerminalPrefs {
themeId: string;
fontSize: number;
scrollback: number;
/** Selecting text copies it at once. */
copyOnSelect: boolean;
rightClick: RightClick;
/** Ask before a paste of several lines that the shell would run one by one. */
warnMultiLine: boolean;
}
const KEY = 'executer-terminal-prefs';
const DEFAULTS: TerminalPrefs = { themeId: TERMINAL_THEMES[0].id, fontSize: FONT_SIZE.default, scrollback: DEFAULT_SCROLLBACK };
const DEFAULTS: TerminalPrefs = {
themeId: TERMINAL_THEMES[0].id,
fontSize: FONT_SIZE.default,
scrollback: DEFAULT_SCROLLBACK,
copyOnSelect: false,
rightClick: 'copyPaste',
warnMultiLine: true
};
function sanitize(value: Partial<TerminalPrefs> | null | undefined): TerminalPrefs {
const themeId = TERMINAL_THEMES.some((t) => t.id === value?.themeId) ? value!.themeId! : DEFAULTS.themeId;
const size = Number(value?.fontSize);
const fontSize = Number.isFinite(size) ? Math.min(FONT_SIZE.max, Math.max(FONT_SIZE.min, Math.round(size))) : DEFAULTS.fontSize;
const scrollback = SCROLLBACK_OPTIONS.includes(Number(value?.scrollback)) ? Number(value!.scrollback) : DEFAULTS.scrollback;
return { themeId, fontSize, scrollback };
const copyOnSelect = typeof value?.copyOnSelect === 'boolean' ? value.copyOnSelect : DEFAULTS.copyOnSelect;
const rightClick = value?.rightClick === 'menu' || value?.rightClick === 'copyPaste' ? value.rightClick : DEFAULTS.rightClick;
const warnMultiLine = typeof value?.warnMultiLine === 'boolean' ? value.warnMultiLine : DEFAULTS.warnMultiLine;
return { themeId, fontSize, scrollback, copyOnSelect, rightClick, warnMultiLine };
}
const samePrefs = (a: TerminalPrefs, b: TerminalPrefs) => (Object.keys(a) as (keyof TerminalPrefs)[]).every((key) => a[key] === b[key]);
function load(): TerminalPrefs {
try {
return sanitize(JSON.parse(localStorage.getItem(KEY) ?? 'null') as Partial<TerminalPrefs> | null);
@@ -457,7 +477,7 @@ export const terminalPrefs = {
},
set(patch: Partial<TerminalPrefs>) {
const next = sanitize({ ...current, ...patch });
if (next.themeId === current.themeId && next.fontSize === current.fontSize && next.scrollback === current.scrollback) return;
if (samePrefs(next, current)) return;
current = next;
try {
localStorage.setItem(KEY, JSON.stringify(current));
@@ -5,7 +5,7 @@ import { shells, type ShellController, type ShellKind, type ShellSnapshot } from
export { SHELL_KINDS, shellLabel, TERMINAL_THEME, type ShellKind, type ShellState } from './shellSessions';
const IDLE: ShellSnapshot = { state: 'connecting', hostname: '', poppedOut: false, shell: 'auto', asUser: false };
const IDLE: ShellSnapshot = { state: 'connecting', hostname: '', poppedOut: false, shell: 'auto', asUser: false, hasSelection: false };
const noSubscribe = () => () => {};
// ==============================|| REMOTE SHELL SESSION ||============================== //
@@ -0,0 +1,286 @@
import { useState } from 'react';
import { mutate } from 'swr';
import { enqueueSnackbar } from 'notistack';
// material-ui
import Alert from '@mui/material/Alert';
import Chip from '@mui/material/Chip';
import Grid from '@mui/material/Grid';
import MenuItem from '@mui/material/MenuItem';
import Stack from '@mui/material/Stack';
import TextField from '@mui/material/TextField';
import Tooltip from '@mui/material/Tooltip';
import Typography from '@mui/material/Typography';
// project imports
import CodeWorkspace from 'components/code-editor/CodeWorkspace';
import SaveButton, { type SaveControl } from 'components/code-editor/SaveButton';
import { UnsavedChip, useSaveShortcut, useUnsavedChangesGuard } from 'components/code-editor/session';
import ConfirmDialog from 'components/ConfirmDialog';
import { RelativeTime } from 'components/DateTime';
import GatedButton from 'components/GatedButton';
import HoverHelp from 'components/HoverHelp';
import MainCard from 'components/MainCard';
import { editorLanguage } from 'sections/scripts/scriptModel';
import { ENGINE_HINT, ENGINE_LABEL } from 'utils/monaco/snippets';
import { api, errorMessage, keys } from 'api/client';
// assets
import CopyOutlined from '@ant-design/icons/CopyOutlined';
import DeleteOutlined from '@ant-design/icons/DeleteOutlined';
// types
import type { Location } from 'react-router-dom';
import type { ScriptEngine, SnippetDto } from 'api/types';
const LANGUAGES: ScriptEngine[] = ['PowerShell', 'WindowsPowerShell', 'Bash'];
export const TAB_STOP_HELP =
'Tab stops: ${1:default} is filled in first and Tab moves to ${2:…}; ${1} repeats it; ${1|a,b|} offers a choice; ${0} is where the cursor ends. Everything else is inserted as written. In a shell, tab stops become their defaults.';
interface Props {
/** The snippet being edited; null for a new one. */
snippet: SnippetDto | null;
/** Why the user cannot change snippets (undefined when they can). */
gate?: string;
/** Switches the page to another snippet (null: none). */
onSelect: (id: string | null) => void;
}
interface Draft {
name: string;
description: string;
language: ScriptEngine;
content: string;
}
const NEW_SNIPPET: Draft = {
name: '',
description: '',
language: 'PowerShell',
content: "Get-Service -Name '${1:Spooler}' | Select-Object Name, Status\n"
};
/** The page shows one snippet per `?id=`: switching snippet leaves this one as much as leaving the page. */
const leavesSnippet = (current: Location, next: Location) =>
current.pathname !== next.pathname || new URLSearchParams(current.search).get('id') !== new URLSearchParams(next.search).get('id');
const draftOf = (snippet: SnippetDto | null): Draft =>
snippet
? { name: snippet.name, description: snippet.description ?? '', language: snippet.language, content: snippet.content }
: NEW_SNIPPET;
// ==============================|| SNIPPET EDITOR ||============================== //
/** Name, language and code of one snippet; a built-in is read-only and can be copied. Mount with `key` per snippet. */
export default function SnippetEditor({ snippet, gate, onSelect }: Props) {
const [saved, setSaved] = useState<Draft>(() => draftOf(snippet));
const [draft, setDraft] = useState<Draft>(saved);
const [busy, setBusy] = useState(false);
const [error, setError] = useState('');
const [confirmDelete, setConfirmDelete] = useState(false);
const builtIn = Boolean(snippet?.builtIn);
const readOnly = Boolean(gate) || builtIn;
const dirty = !builtIn && (Object.keys(draft) as (keyof Draft)[]).some((key) => draft[key] !== saved[key]);
const guard = useUnsavedChangesGuard(dirty, leavesSnippet);
const update = (patch: Partial<Draft>) => setDraft((current) => ({ ...current, ...patch }));
const save = async () => {
if (busy || readOnly || (snippet && !dirty)) return;
if (!draft.name.trim()) {
setError('Name is required.');
return;
}
setBusy(true);
setError('');
try {
const body = { ...draft, name: draft.name.trim() };
if (snippet) {
await api.updateSnippet(snippet.id, body);
setSaved(body);
setDraft(body);
await mutate(keys.snippets);
} else {
const created = await api.createSnippet(body);
await mutate(keys.snippets);
guard.allowLeave();
onSelect(created.id);
}
enqueueSnackbar('Saved', { variant: 'success' });
} catch (e) {
setError(errorMessage(e, 'Save failed.'));
} finally {
setBusy(false);
}
};
useSaveShortcut(() => void save());
const saveControl: SaveControl = { onSave: () => void save(), saving: busy, disabled: Boolean(snippet) && !dirty, gate };
/** A built-in as it is; one of the library's own with any edits in the editor. */
const copy = async () => {
if (!snippet) return;
setBusy(true);
setError('');
try {
const created =
builtIn || !dirty
? await api.copySnippet(snippet.id)
: await api.createSnippet({ ...draft, name: `${draft.name.trim() || saved.name} (copy)` });
await mutate(keys.snippets);
guard.allowLeave();
onSelect(created.id);
enqueueSnackbar('Copied — you are editing the copy.', { variant: 'success' });
} catch (e) {
setError(errorMessage(e, 'Copy failed.'));
} finally {
setBusy(false);
}
};
const remove = async () => {
await api.deleteSnippet(snippet!.id);
guard.allowLeave();
await mutate(keys.snippets);
onSelect(null);
enqueueSnackbar(`Deleted ${snippet!.name}`, { variant: 'success' });
};
const title = snippet ? saved.name : 'New Snippet';
return (
<MainCard
title={
<Stack direction="row" sx={{ alignItems: 'center', gap: 1, minWidth: 0 }}>
<Typography variant="subtitle1" noWrap>
{title}
</Typography>
{builtIn && (
<Tooltip title="Ships with ExecuteR and cannot be changed. Copy it to make your own.">
<Chip size="small" variant="light" color="secondary" label="Built-In" />
</Tooltip>
)}
<UnsavedChip dirty={dirty} />
</Stack>
}
subheader={
snippet?.updatedUtc && (
<>
Updated <RelativeTime value={snippet.updatedUtc} variant="caption" />
{snippet.updatedBy ? ` by ${snippet.updatedBy}` : ''}
</>
)
}
secondary={
<Stack direction="row" sx={{ gap: 1 }}>
{snippet && !builtIn && (
<GatedButton
gate={gate}
color="error"
variant="outlined"
startIcon={<DeleteOutlined />}
onClick={() => setConfirmDelete(true)}
disabled={busy}
>
Delete
</GatedButton>
)}
{snippet && (
<GatedButton
gate={gate}
color={builtIn ? 'primary' : 'secondary'}
variant={builtIn ? 'contained' : 'outlined'}
startIcon={<CopyOutlined />}
onClick={copy}
disabled={busy}
>
{builtIn ? 'Copy to Edit' : 'Copy'}
</GatedButton>
)}
{!builtIn && <SaveButton control={saveControl} />}
</Stack>
}
>
<Stack sx={{ gap: 2 }}>
{error && (
<Alert severity="error" onClose={() => setError('')}>
{error}
</Alert>
)}
<Grid container spacing={2}>
<Grid size={{ xs: 12, md: 4 }}>
<TextField
fullWidth
required
label="Name"
placeholder="Snippet Name"
value={draft.name}
onChange={(e) => update({ name: e.target.value })}
slotProps={{ input: { readOnly } }}
autoFocus={!snippet}
/>
</Grid>
<Grid size={{ xs: 12, md: 3 }}>
<TextField
select
fullWidth
label="Language"
value={draft.language}
onChange={(e) => update({ language: e.target.value as ScriptEngine })}
disabled={readOnly}
>
{LANGUAGES.map((language) => (
<MenuItem key={language} value={language}>
<Tooltip title={ENGINE_HINT[language]} placement="right">
<span style={{ flex: 1 }}>{ENGINE_LABEL[language]}</span>
</Tooltip>
</MenuItem>
))}
</TextField>
</Grid>
<Grid size={{ xs: 12, md: 5 }}>
<TextField
fullWidth
label="Description"
placeholder="Optional"
value={draft.description}
onChange={(e) => update({ description: e.target.value })}
slotProps={{ input: { readOnly } }}
/>
</Grid>
</Grid>
<CodeWorkspace
value={draft.content}
onChange={(content) => update({ content })}
language={editorLanguage(draft.language)}
readOnly={readOnly}
original={builtIn ? undefined : saved.content}
title={draft.name.trim() || title}
height="max(360px, calc(100vh - 480px))"
save={builtIn ? undefined : saveControl}
toolbar={
<Typography variant="caption" color="text.secondary" sx={{ display: 'inline-flex', alignItems: 'center' }}>
Tab Stops
<HoverHelp title={TAB_STOP_HELP} />
</Typography>
}
/>
</Stack>
{snippet && !builtIn && (
<ConfirmDialog
open={confirmDelete}
title="Delete Snippet?"
message={`Delete “${snippet.name}”? This cannot be undone.`}
confirmLabel="Delete"
destructive
onConfirm={remove}
onClose={() => setConfirmDelete(false)}
/>
)}
{guard.dialog}
</MainCard>
);
}
+26
View File
@@ -17,6 +17,8 @@ import EyeOutlined from '@ant-design/icons/EyeOutlined';
import HistoryOutlined from '@ant-design/icons/HistoryOutlined';
import MinusCircleOutlined from '@ant-design/icons/MinusCircleOutlined';
import PlayCircleOutlined from '@ant-design/icons/PlayCircleOutlined';
import PoweroffOutlined from '@ant-design/icons/PoweroffOutlined';
import ReloadOutlined from '@ant-design/icons/ReloadOutlined';
import RollbackOutlined from '@ant-design/icons/RollbackOutlined';
import SyncOutlined from '@ant-design/icons/SyncOutlined';
import TagsOutlined from '@ant-design/icons/TagsOutlined';
@@ -24,6 +26,8 @@ import TagsOutlined from '@ant-design/icons/TagsOutlined';
export interface DeviceActionHandlers {
run: () => void;
schedule: () => void;
restart: () => void;
shutDown: () => void;
/** A device tool in this window. */
openTool: (target: DeviceToolTarget) => void;
/** A device tool in its own window. */
@@ -113,6 +117,28 @@ export function deviceActionMenu(
),
onSelect: handlers.schedule
},
{
kind: 'item',
id: 'restart',
label: 'Restart…',
icon: <ReloadOutlined />,
disabledReason: first(
can('devices.power') ? undefined : needs('Restart and Shut Down'),
runnable.length === 0 ? 'Orphaned devices refuse jobs until they re-enroll.' : undefined
),
onSelect: handlers.restart
},
{
kind: 'item',
id: 'shut-down',
label: 'Shut Down…',
icon: <PoweroffOutlined />,
disabledReason: first(
can('devices.power') ? undefined : needs('Restart and Shut Down'),
runnable.length === 0 ? 'Orphaned devices refuse jobs until they re-enroll.' : undefined
),
onSelect: handlers.shutDown
},
// One device's live tools, each here or in its own window.
...(one ? deviceToolEntries(deviceTools(one, can, context.inventory), handlers) : []),
{ kind: 'divider' },
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -0,0 +1,614 @@
/**
* The full PowerShell IntelliSense catalog: .NET types and members, the
* commands of the core and Windows modules (parameters, sets, value sets,
* output types), aliases and CIM classes. Generated by
* scripts/powershell-catalog/Build-PowerShellCatalog.ps1 and loaded on demand
* (its own chunks), so editors open without it and gain it a moment later.
*/
// ── Raw shapes (see the generator) ───────────────────────────────────────
/** [returnType, parameters, genericArguments?] */
type RawOverload = [string, string, string?];
/** [name, flags, type | overloads, constantValue?]; flags: m/p/f/e/x/y + s(tatic), w(ritable), c(onstant). */
type RawMember = [string, string, (string | RawOverload[])?, string?];
interface RawType {
/** c class, sc static class, ac abstract class, s struct, e enum, i interface, d delegate */
k: string;
b?: string;
g?: string[];
e?: string[];
fl?: number;
c?: string[];
m?: RawMember[];
n?: number;
}
interface RawDotNet {
generated: string;
accelerators: Record<string, string>;
types: Record<string, RawType>;
}
/** [name, type, values?, edition?] */
type RawParameter = [string, string, (string[] | null)?, string?];
/** [name, isDefault, "0p0 1m 2 …"] */
type RawSet = [string, number, string];
interface RawCommand {
n: string;
m: string;
p: RawParameter[];
s: RawSet[];
o?: string[];
/** Present on one edition only: "5" (Windows PowerShell) or "7". */
e?: string;
d?: string;
}
interface RawCim {
ns: string;
p: [string, string][];
m: [string, string][];
}
interface RawCommands {
generated: string;
commands: RawCommand[];
aliases: Record<string, string>;
cim: Record<string, RawCim>;
}
// ── Public model ─────────────────────────────────────────────────────────
export type TypeKind = 'class' | 'static class' | 'abstract class' | 'struct' | 'enum' | 'interface' | 'delegate';
export interface TypeInfo {
/** Catalog key: namespace-qualified, `N for generic definitions, + for nesting. */
key: string;
/** As written in PowerShell: System.Collections.Generic.List[T]. */
display: string;
namespace: string;
/** Simple name without arity (List, SpecialFolder). */
name: string;
kind: TypeKind;
base?: string;
generics?: string[];
enumValues?: string[];
flags?: boolean;
constructors?: string[];
members: RawMember[];
nested: boolean;
}
export interface Overload {
returns: string;
parameters: string;
generics?: string;
}
export type MemberKind = 'method' | 'property' | 'field' | 'event' | 'enum';
export interface MemberInfo {
name: string;
kind: MemberKind;
isStatic: boolean;
/** Property/field/event type (fully qualified where known). */
type?: string;
overloads?: Overload[];
writable?: boolean;
constant?: boolean;
value?: string;
/** Added by PowerShell's extended type system. */
extended?: boolean;
/** An ETS alias property: the member it stands for. */
aliasOf?: string;
/** Display name of the declaring type. */
owner: string;
}
export interface ParameterInfo {
name: string;
type: string;
values?: string[];
/** Only on one edition: '5' or '7'. */
edition?: string;
}
export interface ParameterSetInfo {
name: string;
isDefault: boolean;
parameters: { index: number; mandatory: boolean; position?: number }[];
}
export interface CommandInfo {
name: string;
module: string;
synopsis: string;
parameters: ParameterInfo[];
sets: ParameterSetInfo[];
outputs: string[];
edition?: string;
}
export interface CimClassInfo {
name: string;
namespace: string;
properties: [string, string][];
methods: [string, string][];
}
export interface Catalog {
generated: string;
types: Map<string, TypeInfo>;
accelerators: Map<string, string>;
/** [name as PowerShell spells it, full type name]. */
acceleratorList: [string, string][];
/** Lower-case namespace → its types and child namespaces. */
namespaces: Map<string, { name: string; types: TypeInfo[]; children: Set<string> }>;
commands: Map<string, CommandInfo>;
commandList: CommandInfo[];
aliases: Map<string, string>;
cim: Map<string, CimClassInfo>;
/** membersOf results, by type, arguments and static-ness. */
memberCache: Map<string, MemberInfo[]>;
}
const KINDS: Record<string, TypeKind> = {
c: 'class',
sc: 'static class',
ac: 'abstract class',
s: 'struct',
e: 'enum',
i: 'interface',
d: 'delegate'
};
const VERB_FORMS: Record<string, string> = {
New: 'Creates',
ConvertTo: 'Converts to',
ConvertFrom: 'Converts from',
Delete: 'Deletes',
BackupToAAD: 'Backs up to Entra ID'
};
/** "Gets NetFirewallRule" when no curated synopsis exists. */
function verbSynopsis(name: string): string {
const dash = name.indexOf('-');
if (dash < 1) return '';
const verb = name.slice(0, dash);
const noun = name.slice(dash + 1);
const form =
VERB_FORMS[verb] ?? (/(sh|ch|ss|x)$/.test(verb) ? `${verb}es` : /[^aeiou]y$/.test(verb) ? `${verb.slice(0, -1)}ies` : `${verb}s`);
return `${form} ${noun}.`;
}
function build(dotnet: RawDotNet, commands: RawCommands): Catalog {
const types = new Map<string, TypeInfo>();
const namespaces: Catalog['namespaces'] = new Map();
const namespaceOf = (name: string) => {
const key = name.toLowerCase();
let entry = namespaces.get(key);
if (!entry) {
entry = { name, types: [], children: new Set() };
namespaces.set(key, entry);
const dot = name.lastIndexOf('.');
const parent = dot > 0 ? name.slice(0, dot) : '';
namespaceOf(parent).children.add(name.slice(dot + 1));
}
return entry;
};
namespaces.set('', { name: '', types: [], children: new Set() });
for (const [key, raw] of Object.entries(dotnet.types)) {
const plus = key.lastIndexOf('+');
const dot = key.lastIndexOf('.', plus > 0 ? plus : undefined);
const namespace = dot > 0 ? key.slice(0, dot) : '';
const local = key.slice(dot + 1).replace(/`\d+/g, '');
const name = local.slice(local.lastIndexOf('+') + 1);
const info: TypeInfo = {
key,
display: `${namespace ? `${namespace}.` : ''}${local}${raw.g ? `[${raw.g.join(', ')}]` : ''}`,
namespace,
name,
kind: KINDS[raw.k] ?? 'class',
base: raw.b,
generics: raw.g,
enumValues: raw.e,
flags: raw.fl === 1,
constructors: raw.c,
members: raw.m ?? [],
nested: raw.n === 1
};
types.set(key.toLowerCase(), info);
if (!info.nested) namespaceOf(namespace).types.push(info);
}
const accelerators = new Map<string, string>();
for (const [name, full] of Object.entries(dotnet.accelerators)) accelerators.set(name.toLowerCase(), full);
const commandList: CommandInfo[] = commands.commands.map((c) => ({
name: c.n,
module: c.m,
synopsis: c.d ?? verbSynopsis(c.n),
parameters: c.p.map(([name, type, values, edition]) => ({ name, type, values: values ?? undefined, edition })),
sets: c.s.map(([name, isDefault, tokens]) => ({
name: name.replace(/\s*\(cdxml\)$/, ''),
isDefault: isDefault === 1,
parameters: tokens
.split(' ')
.filter(Boolean)
.map((token) => {
const match = /^(\d+)(m?)(?:p(\d+))?$/.exec(token);
return { index: Number(match?.[1] ?? 0), mandatory: match?.[2] === 'm', position: match?.[3] ? Number(match[3]) : undefined };
})
})),
outputs: c.o ?? [],
edition: c.e
}));
const cim = new Map<string, CimClassInfo>();
for (const [name, raw] of Object.entries(commands.cim ?? {})) {
cim.set(name.toLowerCase(), { name, namespace: raw.ns, properties: raw.p ?? [], methods: raw.m ?? [] });
}
return {
generated: `${dotnet.generated}; ${commands.generated}`,
types,
accelerators,
acceleratorList: Object.entries(dotnet.accelerators).sort(([a], [b]) => a.localeCompare(b)),
namespaces,
commands: new Map(commandList.map((c) => [c.name.toLowerCase(), c])),
commandList,
aliases: new Map(Object.entries(commands.aliases).map(([alias, target]) => [alias.toLowerCase(), target])),
cim,
memberCache: new Map()
};
}
// ── Loading ──────────────────────────────────────────────────────────────
let catalog: Catalog | null = null;
let loading: Promise<Catalog> | null = null;
const listeners = new Set<() => void>();
/** Loads the catalog once (two lazy chunks); retried after a failure. */
export function loadCatalog(): Promise<Catalog> {
loading ??= Promise.all([import('./catalog/dotnet.json'), import('./catalog/commands.json')])
.then(([dotnet, commands]) => {
catalog = build(dotnet.default as unknown as RawDotNet, commands.default as unknown as RawCommands);
listeners.forEach((listener) => listener());
return catalog;
})
.catch((error: unknown) => {
loading = null;
throw error;
});
return loading;
}
/** The catalog if it has loaded. */
export const loadedCatalog = (): Catalog | null => catalog;
/** Notified once the catalog has loaded. */
export function onCatalogLoaded(listener: () => void): () => void {
listeners.add(listener);
return () => listeners.delete(listener);
}
// ── Type names ───────────────────────────────────────────────────────────
/** Splits "a, b[c, d], e" at top-level commas. */
export function splitTopLevel(text: string, separator = ','): string[] {
const parts: string[] = [];
let depth = 0;
let start = 0;
for (let i = 0; i < text.length; i++) {
const c = text[i];
if (c === '"' || c === "'") {
const close = text.indexOf(c, i + 1);
if (close < 0) break;
i = close;
} else if (c === '[' || c === '(' || c === '{') depth++;
else if (c === ']' || c === ')' || c === '}') depth--;
else if (c === separator && depth === 0) {
parts.push(text.slice(start, i).trim());
start = i + 1;
}
}
parts.push(text.slice(start).trim());
return parts.filter((p, i) => p || i < parts.length - 1);
}
export interface ResolvedType {
type: TypeInfo;
/** Generic arguments as written. */
args: string[];
/** Array rank wrappers ("[]" count). */
arrays: number;
}
/** Parses "Name[Arg, Arg][]" into name, arguments and array depth. */
export function parseTypeName(text: string): { name: string; args: string[]; arrays: number } {
let name = text.trim();
let arrays = 0;
while (/\[\s*,*\s*\]$/.test(name)) {
name = name.replace(/\[\s*,*\s*\]$/, '');
arrays++;
}
let args: string[] = [];
if (name.endsWith(']')) {
let depth = 0;
for (let i = name.length - 1; i >= 0; i--) {
if (name[i] === ']') depth++;
else if (name[i] === '[') depth--;
if (depth === 0) {
args = splitTopLevel(name.slice(i + 1, -1)).map((a) => a.replace(/^\[|\]$/g, ''));
name = name.slice(0, i);
break;
}
}
}
return { name: name.trim().replace(/`\d+$/, ''), args, arrays };
}
/**
* Resolves a type as PowerShell would: accelerators, the full name, the name
* under System., then under each `using namespace`.
*/
export function resolveType(cat: Catalog, text: string, usings: string[] = []): ResolvedType | null {
const { name, args, arrays } = parseTypeName(text);
if (!name) return null;
const lower = name.toLowerCase();
const arity = args.length ? `\`${args.length}` : '';
const candidates: string[] = [];
const accelerated = cat.accelerators.get(lower);
if (accelerated) candidates.push(accelerated.toLowerCase());
for (const prefix of ['', 'system.', ...usings.map((u) => `${u.toLowerCase()}.`)]) {
candidates.push(`${prefix}${lower}${arity}`);
if (!arity) candidates.push(`${prefix}${lower}\`1`);
}
for (const key of candidates) {
const type = cat.types.get(key);
if (type) return { type, args, arrays };
}
return null;
}
/** Fully-qualified display of a resolved type, with its arguments. */
export function displayResolved(resolved: ResolvedType): string {
const { type, args, arrays } = resolved;
const base = args.length ? `${type.display.replace(/\[.*\]$/, '')}[${args.join(', ')}]` : type.display;
return base + '[]'.repeat(arrays);
}
// ── Members ──────────────────────────────────────────────────────────────
const toMember = (raw: RawMember, owner: string): MemberInfo => {
const [name, flags, data, value] = raw;
const letter = flags[0];
const kind: MemberKind = letter === 'm' || letter === 'y' ? 'method' : letter === 'f' ? 'field' : letter === 'e' ? 'event' : 'property';
return {
name,
kind,
isStatic: flags.includes('s'),
type: typeof data === 'string' && data ? data : undefined,
overloads: Array.isArray(data) ? data.map(([returns, parameters, generics]) => ({ returns, parameters, generics })) : undefined,
writable: flags.includes('w'),
constant: flags.includes('c'),
value: letter === 'x' ? undefined : value,
aliasOf: letter === 'x' ? value : undefined,
extended: letter === 'x' || letter === 'y',
owner
};
};
/** Replaces generic parameter names (T, TKey) with the arguments of a constructed type. */
function substitute(text: string, map: Map<string, string>): string {
if (!map.size) return text;
return text.replace(/\b[A-Z]\w*\b/g, (word) => map.get(word) ?? word);
}
function bind(member: MemberInfo, map: Map<string, string>): MemberInfo {
if (!map.size) return member;
return {
...member,
type: member.type && substitute(member.type, map),
overloads: member.overloads?.map((o) => ({ ...o, returns: substitute(o.returns, map), parameters: substitute(o.parameters, map) }))
};
}
/**
* Members of a type and its bases (derived first, one entry per name), static
* or instance. Enums list their values as static members.
*/
export function membersOf(cat: Catalog, resolved: ResolvedType, isStatic: boolean): MemberInfo[] {
const cacheKey = `${resolved.type.key}|${resolved.args.join(',')}|${resolved.arrays}|${isStatic}`;
const cached = cat.memberCache.get(cacheKey);
if (cached) return cached;
const members = collectMembers(cat, resolved, isStatic);
if (cat.memberCache.size > 500) cat.memberCache.clear();
cat.memberCache.set(cacheKey, members);
return members;
}
function collectMembers(cat: Catalog, resolved: ResolvedType, isStatic: boolean): MemberInfo[] {
const seen = new Set<string>();
const result: MemberInfo[] = [];
const add = (member: MemberInfo) => {
const key = member.name.toLowerCase();
if (seen.has(key)) return;
seen.add(key);
result.push(member);
};
if (resolved.arrays > 0) {
if (isStatic) return [];
const array = cat.types.get('system.array');
if (array) for (const m of membersOf(cat, { type: array, args: [], arrays: 0 }, false)) add(m);
return result;
}
let current: ResolvedType | null = resolved;
const visited = new Set<string>();
while (current && !visited.has(current.type.key)) {
visited.add(current.type.key);
const { type, args } = current;
const map = new Map<string, string>();
type.generics?.forEach((g, i) => args[i] && map.set(g, args[i]));
if (isStatic && type.kind === 'enum') {
for (const value of type.enumValues ?? []) {
add({ name: value, kind: 'enum', isStatic: true, type: type.display, owner: type.display });
}
}
for (const raw of type.members) {
const member = toMember(raw, type.display);
if (member.isStatic === isStatic || (member.extended && !isStatic)) add(bind(member, map));
}
if (!current.type.base) break;
current = resolveType(cat, substitute(current.type.base, map));
}
if (!isStatic && resolved.type.kind !== 'interface') {
const object = cat.types.get('system.object');
if (object && !visited.has(object.key)) for (const raw of object.members) if (!raw[1].includes('s')) add(toMember(raw, 'object'));
}
// Alias properties take the type of the member they stand for.
for (const m of result) {
if (m.aliasOf && !m.type) m.type = result.find((t) => t.name.toLowerCase() === m.aliasOf!.toLowerCase())?.type;
}
return result;
}
/** One member by name (case-insensitive). */
export function findMember(cat: Catalog, resolved: ResolvedType, name: string, isStatic: boolean): MemberInfo | undefined {
const key = name.toLowerCase();
return membersOf(cat, resolved, isStatic).find((m) => m.name.toLowerCase() === key);
}
/** Constructors as parameter lists ('' is the parameterless one). */
export function constructorsOf(resolved: ResolvedType): string[] {
const map = new Map<string, string>();
resolved.type.generics?.forEach((g, i) => resolved.args[i] && map.set(g, resolved.args[i]));
return (resolved.type.constructors ?? []).map((c) => substitute(c, map));
}
/** C#-style declaration of a member, one line per overload. */
export function memberSignatures(member: MemberInfo): string[] {
const prefix = member.isStatic && member.kind !== 'enum' ? 'static ' : '';
if (member.kind === 'method') {
return (member.overloads ?? []).map(
(o) => `${prefix}${shortType(o.returns)} ${member.name}${o.generics ? `[${o.generics}]` : ''}(${o.parameters})`
);
}
if (member.kind === 'enum') return [`${member.owner}::${member.name}`];
const type = member.type ? shortType(member.type) : member.extended ? 'PSObject' : 'object';
if (member.kind === 'property') {
return [
`${prefix}${type} ${member.name} { get;${member.writable ? ' set;' : ''} }${member.aliasOf ? ` # alias of ${member.aliasOf}` : member.extended ? ' # ETS' : ''}`
];
}
if (member.kind === 'event') return [`${prefix}event ${type} ${member.name}`];
return [
`${member.constant ? 'const ' : prefix}${type} ${member.name}${member.value !== undefined ? ` = ${/^(string|char)$/.test(type) ? `'${member.value}'` : member.value}` : ''}`
];
}
/** Drops namespaces from a type for display: System.Collections.Generic.List[System.String] → List[String]. */
export function shortType(type: string): string {
return type.replace(/(?:[A-Za-z_]\w*\.)+(?=[A-Za-z_]\w*)/g, '');
}
// ── Commands ─────────────────────────────────────────────────────────────
/** A command by name or alias. */
export function findCommand(cat: Catalog, name: string): { command: CommandInfo; alias?: string } | undefined {
const key = name.toLowerCase();
const direct = cat.commands.get(key);
if (direct) return { command: direct };
const target = cat.aliases.get(key);
const viaAlias = target ? cat.commands.get(target.toLowerCase()) : undefined;
return viaAlias ? { command: viaAlias, alias: name } : undefined;
}
/** Syntax lines, one per parameter set, as Get-Command -Syntax prints them. */
export function commandSyntax(command: CommandInfo, limit = 4): string[] {
const sets = [...command.sets].sort((a, b) => Number(b.isDefault) - Number(a.isDefault));
const lines = sets.slice(0, limit).map((set) => {
const parts = [...set.parameters]
.sort((a, b) => (a.position ?? 999) - (b.position ?? 999))
.map(({ index, mandatory, position }) => {
const p = command.parameters[index];
if (!p) return '';
const name = position !== undefined ? `[-${p.name}]` : `-${p.name}`;
const typed = p.type === 'switch' ? name : `${name} <${p.type}>`;
return mandatory ? typed : `[${typed}]`;
})
.filter(Boolean);
return [command.name, ...parts, '[<CommonParameters>]'].join(' ');
});
if (!lines.length) lines.push(`${command.name} ${command.parameters.map((p) => `[-${p.name}]`).join(' ')}`.trim());
return lines;
}
export const editionNote = (edition?: string) =>
edition === '5' ? 'Windows PowerShell 5.1 only' : edition === '7' ? 'PowerShell 7+ only' : '';
/** The most useful output type of a command. */
export function commandOutput(cat: Catalog, command: CommandInfo): string | undefined {
const preferred = PREFERRED_OUTPUT[command.name.toLowerCase()];
if (preferred) return preferred;
const cimType = command.outputs.find((o) => o.includes('#'));
if (cimType) return cimType;
return command.outputs.find((o) => resolveType(cat, o)) ?? command.outputs[0];
}
/** Where the declared output types lead astray (first listed is a side case). */
const PREFERRED_OUTPUT: Record<string, string> = {
'get-content': 'System.String',
'get-process': 'System.Diagnostics.Process',
'get-date': 'System.DateTime',
'get-item': 'System.IO.FileInfo',
'get-childitem': 'System.IO.FileInfo',
'get-random': 'System.Int32',
'get-command': 'System.Management.Automation.CommandInfo',
'resolve-path': 'System.Management.Automation.PathInfo',
'get-location': 'System.Management.Automation.PathInfo',
'get-uptime': 'System.TimeSpan',
'get-computerinfo': 'Microsoft.PowerShell.Commands.ComputerInfo',
'measure-object': 'Microsoft.PowerShell.Commands.GenericMeasureInfo',
'test-connection': 'Microsoft.PowerShell.Commands.TestConnectionCommand+PingStatus',
'get-winevent': 'System.Diagnostics.Eventing.Reader.EventLogRecord',
'get-acl': 'System.Security.AccessControl.FileSecurity',
'get-wmiobject': 'System.Management.ManagementObject',
'get-ciminstance': 'Microsoft.Management.Infrastructure.CimInstance',
'new-temporaryfile': 'System.IO.FileInfo',
'invoke-webrequest': 'Microsoft.PowerShell.Commands.BasicHtmlWebResponseObject',
'get-filehash': 'Microsoft.PowerShell.Commands.FileHashInfo',
'get-itemproperty': 'System.Management.Automation.PSCustomObject',
'import-csv': 'System.Management.Automation.PSCustomObject',
'convertfrom-json': 'System.Management.Automation.PSCustomObject',
'get-localuser': 'Microsoft.PowerShell.Commands.LocalUser',
'get-localgroup': 'Microsoft.PowerShell.Commands.LocalGroup',
'get-localgroupmember': 'Microsoft.PowerShell.Commands.LocalPrincipal',
'get-bitlockervolume': 'Microsoft.BitLocker.Structures.BitLockerVolume',
'get-member': 'Microsoft.PowerShell.Commands.MemberDefinition',
'get-pssession': 'System.Management.Automation.Runspaces.PSSession',
'new-pssession': 'System.Management.Automation.Runspaces.PSSession',
'get-psdrive': 'System.Management.Automation.PSDriveInfo',
'select-string': 'Microsoft.PowerShell.Commands.MatchInfo',
'get-authenticodesignature': 'System.Management.Automation.Signature',
'get-pfxcertificate': 'System.Security.Cryptography.X509Certificates.X509Certificate2',
'get-credential': 'System.Management.Automation.PSCredential',
'convertto-securestring': 'System.Security.SecureString',
'get-error': 'System.Management.Automation.ErrorRecord'
};
// ── CIM ──────────────────────────────────────────────────────────────────
/** The CIM class named by a "CimInstance#namespace/Class" type, or a bare class name. */
export function cimClassOf(cat: Catalog, type: string): CimClassInfo | undefined {
const hash = type.indexOf('#');
const name = (hash >= 0 ? type.slice(hash + 1) : type).split(/[\\/]/).pop() ?? '';
return cat.cim.get(name.toLowerCase());
}
+111 -24
View File
@@ -2,7 +2,9 @@
* Curated PowerShell reference data for the editor: the cmdlets scripts
* reach for most, each with a one-line synopsis and its everyday parameters
* (completion after `-`, hover cards), plus keywords, automatic variables,
* type accelerators and snippets. Offline and deliberately small.
* type accelerators and snippets. Offline and deliberately small: it
* answers at once, and the full catalog (powershell-catalog.ts: every .NET
* type, ~1,100 commands) takes over when its lazy chunks arrive.
*/
export interface CmdletInfo {
@@ -459,32 +461,101 @@ export const CONTROL_KEYWORDS = [
'in'
];
export const AUTOMATIC_VARIABLES: { name: string; doc: string }[] = [
/** Automatic and preference variables; `type` drives member completion after `$name.`. */
export const AUTOMATIC_VARIABLES: { name: string; doc: string; type?: string }[] = [
{ name: '$_', doc: 'The current object in the pipeline (same as $PSItem).' },
{ name: '$PSItem', doc: 'The current object in the pipeline.' },
{ name: '$args', doc: 'Undeclared arguments passed to a function or script.' },
{ name: '$Error', doc: 'The most recent errors, newest first.' },
{ name: '$LASTEXITCODE', doc: 'Exit code of the last native program that ran.' },
{ name: '$?', doc: 'True when the last command succeeded.' },
{ name: '$PSVersionTable', doc: 'Version details of the running PowerShell.' },
{ name: '$PSScriptRoot', doc: 'Directory of the running script.' },
{ name: '$PSCommandPath', doc: 'Full path of the running script.' },
{ name: '$PSBoundParameters', doc: 'The parameters passed to the script or function, by name.' },
{ name: '$MyInvocation', doc: 'Information about the current command.' },
{ name: '$Host', doc: 'The current host application.' },
{ name: '$PID', doc: 'Process id of the PowerShell process.' },
{ name: '$IsWindows', doc: 'True on Windows (PowerShell 7+).' },
{ name: '$IsLinux', doc: 'True on Linux (PowerShell 7+).' },
{ name: '$IsMacOS', doc: 'True on macOS (PowerShell 7+).' },
{ name: '$true', doc: 'Boolean true.' },
{ name: '$false', doc: 'Boolean false.' },
{ name: '$args', doc: 'Undeclared arguments passed to a function or script.', type: 'System.Object[]' },
{ name: '$input', doc: 'An enumerator over the input piped to a function or script block.', type: 'System.Collections.IEnumerator' },
{ name: '$this', doc: 'The object a script property, script method or class member is running on.' },
{ name: '$Error', doc: 'The most recent errors, newest first.', type: 'System.Collections.ArrayList' },
{ name: '$LASTEXITCODE', doc: 'Exit code of the last native program that ran.', type: 'System.Int32' },
{ name: '$?', doc: 'True when the last command succeeded.', type: 'System.Boolean' },
{ name: '$Matches', doc: 'The groups the last -match captured, by number and name.', type: 'System.Collections.Hashtable' },
{
name: '$PSVersionTable',
doc: 'Version details of the running PowerShell.',
type: 'System.Management.Automation.PSVersionHashTable{PSVersion=System.Version;PSEdition=System.String;GitCommitId=System.String;OS=System.String;Platform=System.String;PSCompatibleVersions=System.Version[];PSRemotingProtocolVersion=System.Version;SerializationVersion=System.Version;WSManStackVersion=System.Version;BuildVersion=System.Version;CLRVersion=System.Version}'
},
{ name: '$PSEdition', doc: 'Desktop (Windows PowerShell 5.1) or Core (PowerShell 7+).', type: 'System.String' },
{ name: '$PSScriptRoot', doc: 'Directory of the running script.', type: 'System.String' },
{ name: '$PSCommandPath', doc: 'Full path of the running script.', type: 'System.String' },
{
name: '$PSBoundParameters',
doc: 'The parameters passed to the script or function, by name.',
type: 'System.Collections.Generic.Dictionary[string, object]'
},
{ name: '$PSCmdlet', doc: 'The running advanced function or script ([CmdletBinding()]).', type: 'System.Management.Automation.PSCmdlet' },
{ name: '$MyInvocation', doc: 'Information about the current command.', type: 'System.Management.Automation.InvocationInfo' },
{
name: '$ExecutionContext',
doc: 'The engine intrinsics: providers, session state, invoke command.',
type: 'System.Management.Automation.EngineIntrinsics'
},
{ name: '$Host', doc: 'The current host application.', type: 'System.Management.Automation.Host.PSHost' },
{ name: '$PID', doc: 'Process id of the PowerShell process.', type: 'System.Int32' },
{ name: '$PWD', doc: 'The current location.', type: 'System.Management.Automation.PathInfo' },
{ name: '$HOME', doc: "The user's home directory.", type: 'System.String' },
{ name: '$PSHOME', doc: 'The PowerShell installation directory.', type: 'System.String' },
{ name: '$PSCulture', doc: 'Name of the culture in use (en-US).', type: 'System.String' },
{ name: '$PSUICulture', doc: 'Name of the UI culture in use.', type: 'System.String' },
{ name: '$ShellId', doc: 'Identifier of the current shell.', type: 'System.String' },
{ name: '$StackTrace', doc: 'Stack trace of the most recent error.', type: 'System.String' },
{ name: '$NestedPromptLevel', doc: 'Depth of nested prompts.', type: 'System.Int32' },
{ name: '$Event', doc: 'The event being processed, in an event action block.', type: 'System.Management.Automation.PSEventArgs' },
{ name: '$EventArgs', doc: 'The event arguments, in an event action block.' },
{ name: '$EventSubscriber', doc: 'The subscriber of the event being processed.', type: 'System.Management.Automation.PSEventSubscriber' },
{ name: '$Sender', doc: 'The object that raised the event, in an event action block.' },
{ name: '$foreach', doc: 'The enumerator of the enclosing foreach loop.', type: 'System.Collections.IEnumerator' },
{ name: '$switch', doc: 'The enumerator of the enclosing switch statement.', type: 'System.Collections.IEnumerator' },
{ name: '$IsWindows', doc: 'True on Windows (PowerShell 7+).', type: 'System.Boolean' },
{ name: '$IsLinux', doc: 'True on Linux (PowerShell 7+).', type: 'System.Boolean' },
{ name: '$IsMacOS', doc: 'True on macOS (PowerShell 7+).', type: 'System.Boolean' },
{ name: '$IsCoreCLR', doc: 'True on .NET (PowerShell 7+).', type: 'System.Boolean' },
{ name: '$EnabledExperimentalFeatures', doc: 'Names of the experimental features turned on (PowerShell 7+).' },
{ name: '$true', doc: 'Boolean true.', type: 'System.Boolean' },
{ name: '$false', doc: 'Boolean false.', type: 'System.Boolean' },
{ name: '$null', doc: 'The null value.' },
{ name: '$ErrorActionPreference', doc: 'How non-terminating errors are handled (Continue, Stop, SilentlyContinue, …).' },
{ name: '$ProgressPreference', doc: 'How progress records are handled; SilentlyContinue speeds up web cmdlets.' },
{ name: '$VerbosePreference', doc: 'Whether verbose messages are written.' },
{ name: '$WarningPreference', doc: 'How warnings are handled.' },
{ name: '$InformationPreference', doc: 'How information records are handled.' },
{ name: '$ConfirmPreference', doc: 'Impact level at which confirmation is requested.' }
{
name: '$ErrorActionPreference',
doc: 'How non-terminating errors are handled (Continue, Stop, SilentlyContinue, …).',
type: 'System.Management.Automation.ActionPreference'
},
{
name: '$ProgressPreference',
doc: 'How progress records are handled; SilentlyContinue speeds up web cmdlets.',
type: 'System.Management.Automation.ActionPreference'
},
{ name: '$VerbosePreference', doc: 'Whether verbose messages are written.', type: 'System.Management.Automation.ActionPreference' },
{ name: '$DebugPreference', doc: 'Whether debug messages are written.', type: 'System.Management.Automation.ActionPreference' },
{ name: '$WarningPreference', doc: 'How warnings are handled.', type: 'System.Management.Automation.ActionPreference' },
{ name: '$InformationPreference', doc: 'How information records are handled.', type: 'System.Management.Automation.ActionPreference' },
{
name: '$ConfirmPreference',
doc: 'Impact level at which confirmation is requested.',
type: 'System.Management.Automation.ConfirmImpact'
},
{ name: '$WhatIfPreference', doc: 'When true, commands that support -WhatIf only report what they would do.', type: 'System.Boolean' },
{ name: '$ErrorView', doc: 'How errors are displayed (ConciseView, NormalView, CategoryView).' },
{ name: '$FormatEnumerationLimit', doc: 'How many items of a collection formatting shows.', type: 'System.Int32' },
{ name: '$MaximumHistoryCount', doc: 'How many commands the session history keeps.', type: 'System.Int32' },
{ name: '$OFS', doc: 'Output field separator used when an array is converted to a string.', type: 'System.String' },
{ name: '$OutputEncoding', doc: 'Encoding used when piping to native programs.', type: 'System.Text.Encoding' },
{
name: '$PSDefaultParameterValues',
doc: 'Default values for cmdlet parameters ("Cmdlet:Parameter" = value).',
type: 'System.Management.Automation.DefaultParameterDictionary'
},
{ name: '$PSModuleAutoLoadingPreference', doc: 'Whether modules are imported automatically on first use.' },
{
name: '$PSNativeCommandUseErrorActionPreference',
doc: 'When true, a failing native command honours $ErrorActionPreference (PowerShell 7.4+).',
type: 'System.Boolean'
},
{ name: '$PSNativeCommandArgumentPassing', doc: 'How arguments are passed to native programs (Legacy, Standard, Windows).' },
{ name: '$PSStyle', doc: 'ANSI rendering settings and escape sequences (PowerShell 7.2+).' },
{ name: '$PSSessionConfigurationName', doc: 'Default session configuration for remote sessions.', type: 'System.String' },
{ name: '$PSEmailServer', doc: 'Default SMTP server for Send-MailMessage.', type: 'System.String' }
];
export const ENVIRONMENT_VARIABLES = [
@@ -505,8 +576,24 @@ export const ENVIRONMENT_VARIABLES = [
'PATH',
'PSModulePath',
'PROCESSOR_ARCHITECTURE',
'PROCESSOR_IDENTIFIER',
'NUMBER_OF_PROCESSORS',
'OS',
'ALLUSERSPROFILE',
'PUBLIC',
'CommonProgramFiles',
'CommonProgramFiles(x86)',
'ProgramW6432',
'ComSpec',
'PATHEXT',
'HOMEDRIVE',
'HOMEPATH',
'LOGONSERVER',
'USERDNSDOMAIN',
'SESSIONNAME',
'OneDrive',
'DriverData',
'PSExecutionPolicyPreference',
'HOME',
'HOSTNAME',
'SHELL',
+559 -24
View File
@@ -10,6 +10,27 @@ import {
type Analysis,
type FunctionDecl
} from './powershell-analysis';
import {
cimClassOf,
commandOutput,
commandSyntax,
constructorsOf,
displayResolved,
editionNote,
findCommand,
loadCatalog,
loadedCatalog,
memberSignatures,
membersOf,
resolveType,
shortType,
splitTopLevel,
type Catalog,
type CommandInfo,
type MemberInfo,
type ParameterInfo,
type ResolvedType
} from './powershell-catalog';
import {
AUTOMATIC_VARIABLES,
BASH_COMMANDS,
@@ -24,6 +45,16 @@ import {
type CmdletInfo
} from './powershell-data';
import { powershellGrammar } from './powershell-grammar';
import {
chainAt,
inferChain,
instanceMembers,
splitNotes,
usingNamespaces,
variableType,
withNotes,
type TypeEnv
} from './powershell-types';
/** A function from a function module attached to the script. */
export interface ModuleFunction {
@@ -57,6 +88,20 @@ const CMDLET_INDEX = new Map(CMDLETS.map((c) => [c.name.toLowerCase(), c]));
const AUTOMATIC_INDEX = new Map(AUTOMATIC_VARIABLES.map((v) => [v.name.slice(1).toLowerCase(), v]));
export const MARKER_OWNER = 'executer';
/** Values of the common parameters that take one. */
const COMMON_VALUES: Record<string, string[]> = {
erroraction: ['Continue', 'Ignore', 'Inquire', 'SilentlyContinue', 'Stop', 'Suspend', 'Break'],
warningaction: ['Continue', 'Ignore', 'Inquire', 'SilentlyContinue', 'Stop', 'Break'],
informationaction: ['Continue', 'Ignore', 'Inquire', 'SilentlyContinue', 'Stop', 'Break'],
progressaction: ['Continue', 'Ignore', 'Inquire', 'SilentlyContinue', 'Stop', 'Break']
};
/** Commands whose -ClassName (or first argument) is a CIM class. */
const CIM_COMMANDS = new Set(['get-ciminstance', 'get-cimclass', 'invoke-cimmethod', 'new-ciminstance', 'get-wmiobject']);
/** Attributes written in brackets ([Parameter()], …), offered with the types. */
const ATTRIBUTES = TYPE_ACCELERATORS.filter((t) => /^[A-Z]/.test(t) && !t.includes('.'));
const syntax = (name: string, parameters: string[]) =>
[name, ...parameters.slice(0, 8).map((p) => `[-${p}]`), parameters.length > 8 ? '…' : ''].filter(Boolean).join(' ');
@@ -64,23 +109,72 @@ function cmdletDoc(cmdlet: CmdletInfo): Monaco.IMarkdownString {
return { value: ['```powershell', syntax(cmdlet.name, cmdlet.parameters), '```', cmdlet.synopsis].join('\n') };
}
const commandDocs = new Map<CommandInfo, string>();
/** Hover card / completion documentation for a catalog command. */
function commandDoc(catalog: Catalog, command: CommandInfo, alias?: string): Monaco.IMarkdownString {
let body = commandDocs.get(command);
if (body === undefined) {
const output = commandOutput(catalog, command);
const footer = [
`*${command.module}*`,
editionNote(command.edition),
output ? `→ \`${shortType(output.split('#').pop() ?? output)}\`` : ''
]
.filter(Boolean)
.join(' · ');
body = ['```powershell', commandSyntax(command).join('\n\n'), '```', command.synopsis, footer].filter(Boolean).join('\n\n');
commandDocs.set(command, body);
}
return { value: alias ? `\`${alias}\` → **${command.name}**\n\n${body}` : body };
}
function functionDoc(fn: { name: string; parameters: string[]; synopsis?: string }, where: string): Monaco.IMarkdownString {
return {
value: ['```powershell', syntax(fn.name, fn.parameters), '```', fn.synopsis ?? '', `*${where}*`].filter(Boolean).join('\n\n')
};
}
/** Signature lines of a member, as a C# block. */
function memberDoc(member: MemberInfo): Monaco.IMarkdownString {
const signatures = memberSignatures(member);
const shown = signatures.slice(0, 8);
const more = signatures.length > shown.length ? `\n\n+${signatures.length - shown.length} more overloads` : '';
return { value: ['```csharp', ...shown, '```', `*${shortType(member.owner)}*${member.extended ? ' · ETS' : ''}${more}`].join('\n') };
}
function typeDoc(resolved: ResolvedType, written?: string): Monaco.IMarkdownString {
const { type } = resolved;
const head = `${type.kind} ${displayResolved(resolved)}${type.base ? ` : ${shortType(type.base)}` : ''}`;
const lines = ['```csharp', head, '```'];
if (type.enumValues?.length) {
const values = type.enumValues.slice(0, 12).join(', ');
lines.push(`${type.flags ? '[Flags] ' : ''}${values}${type.enumValues.length > 12 ? ', …' : ''}`);
}
if (written && written.toLowerCase() !== type.key.toLowerCase() && !written.includes('.')) lines.push(`*[${written}]*`);
return { value: lines.join('\n') };
}
/** The command a `-Parameter` belongs to: the first word of the current pipeline segment. */
function commandBefore(prefix: string): string | null {
const segment = prefix.split(/[|;{(]/).pop() ?? '';
const match = /^\s*(?:&\s*)?([\w][\w-]*)/.exec(segment);
const match = /^\s*(?:&\s*)?([\w%?][\w-]*)/.exec(segment);
return match ? match[1] : null;
}
const kindLabel: Record<MemberInfo['kind'], string> = {
method: 'method',
property: 'property',
field: 'field',
event: 'event',
enum: 'enum value'
};
/** Monaco registrations for PowerShell and Bash; call once per Monaco instance. */
export function registerScriptLanguages(monaco: typeof Monaco, resolve: ContextResolver): Monaco.IDisposable[] {
const { CompletionItemKind: Kind, CompletionItemInsertTextRule: InsertRule, SymbolKind } = monaco.languages;
const disposables: Monaco.IDisposable[] = [];
const parameterHints = { id: 'editor.action.triggerParameterHints', title: 'Parameter hints' };
disposables.push(monaco.languages.setMonarchTokensProvider('powershell', powershellGrammar));
@@ -94,13 +188,93 @@ export function registerScriptLanguages(monaco: typeof Monaco, resolve: ContextR
return { own, modules };
};
/** Typing environment at a position: the document, `using namespace`s and the script's own bindings. */
const typeEnv = (
catalog: Catalog,
model: Monaco.editor.ITextModel,
line: number,
column: number,
context: CompletionContext | null
): TypeEnv => {
const lines = model.getLinesContent();
const secrets = (context?.secretsVariable?.trim() || 'Secrets').toLowerCase();
return {
catalog,
lines,
line,
column,
usings: usingNamespaces(lines),
special: (key) => {
if (key === 'files') {
return withNotes(
'System.Collections.Hashtable',
(context?.fileBindings ?? []).map((f) => ({
name: f.name,
type: f.directory ? 'System.IO.DirectoryInfo' : 'System.IO.FileInfo'
}))
);
}
if (key === 'filesroot') return 'System.IO.DirectoryInfo';
if (key === secrets) return withNotes('System.Collections.Hashtable', context?.secretNames ?? []);
return undefined;
}
};
};
const memberItem = (member: MemberInfo, range: Monaco.IRange, index: number): Monaco.languages.CompletionItem => {
const isMethod = member.kind === 'method';
const first = member.overloads?.[0];
const takesArguments = (member.overloads ?? []).some((o) => o.parameters);
const detail = isMethod
? `(${first?.parameters ?? ''})${(member.overloads?.length ?? 0) > 1 ? ` +${member.overloads!.length - 1}` : ''}`
: member.kind === 'enum'
? ''
: member.value !== undefined
? ` = ${member.value}`
: '';
return {
label: {
label: member.name,
detail: detail ? ` ${detail}` : undefined,
description: shortType(isMethod ? (first?.returns ?? '') : (member.type ?? (member.extended ? 'ETS' : '')))
},
kind: isMethod
? Kind.Method
: member.kind === 'enum'
? Kind.EnumMember
: member.kind === 'event'
? Kind.Event
: member.kind === 'field'
? member.constant
? Kind.Constant
: Kind.Field
: Kind.Property,
detail: `${member.isStatic && member.kind !== 'enum' ? 'static ' : ''}${kindLabel[member.kind]} · ${shortType(member.owner)}`,
documentation: memberDoc(member),
insertText: isMethod ? `${member.name}(${takesArguments ? '' : ')'}` : member.name,
command: isMethod && takesArguments ? parameterHints : undefined,
filterText: member.name,
range,
sortText: `${member.extended ? '1' : '0'}${String(index).padStart(4, '0')}`
};
};
/** Enum values in declared order first, then members alphabetically. */
const sortedMembers = (members: MemberInfo[]) => [
...members.filter((m) => m.kind === 'enum'),
...members.filter((m) => m.kind !== 'enum').sort((a, b) => a.name.localeCompare(b.name))
];
// ── Completion ────────────────────────────────────────────────────────
disposables.push(
monaco.languages.registerCompletionItemProvider('powershell', {
triggerCharacters: ['-', '$', '.', ':', '['],
provideCompletionItems(model, position) {
async provideCompletionItems(model, position) {
const context = resolve(model);
if (!context) return { suggestions: [] };
// The full catalog loads on first use (its own chunks); until then the curated data answers.
const catalog = loadedCatalog() ?? (await loadCatalog().catch(() => null));
if (model.isDisposed()) return { suggestions: [] };
const analysis = analyze(monaco, model);
const prefix = model.getValueInRange({
@@ -113,6 +287,7 @@ export function registerScriptLanguages(monaco: typeof Monaco, resolve: ContextR
const range = new monaco.Range(position.lineNumber, word.startColumn, position.lineNumber, word.endColumn);
const secretsVariable = context.secretsVariable?.trim() || 'Secrets';
const suggestions: Monaco.languages.CompletionItem[] = [];
const env = () => typeEnv(catalog!, model, position.lineNumber, position.column, context);
// $Secrets.<name> / $Files.<name>
const member = /\$(\w+)\.(\w*)$/.exec(prefix);
@@ -136,9 +311,63 @@ export function registerScriptLanguages(monaco: typeof Monaco, resolve: ContextR
}
return { suggestions };
}
}
// [Type]::<static member>
const staticAccess = /\[((?:[^[\]]|\[[^[\]]*\])+)\]::(\w*)$/.exec(prefix);
if (staticAccess) {
const resolved = catalog && resolveType(catalog, staticAccess[1], usingNamespaces(model.getLinesContent()));
if (!resolved) return { suggestions };
const members = sortedMembers(membersOf(catalog!, resolved, true));
members.forEach((m, i) => suggestions.push(memberItem(m, range, i)));
const constructors = constructorsOf(resolved);
if (constructors.length && resolved.type.kind !== 'static class' && resolved.type.kind !== 'abstract class') {
suggestions.push({
label: { label: 'new', detail: ` (${constructors[0]})${constructors.length > 1 ? ` +${constructors.length - 1}` : ''}` },
kind: Kind.Constructor,
detail: `constructor · ${shortType(displayResolved(resolved))}`,
documentation: {
value: ['```csharp', ...constructors.slice(0, 8).map((c) => `${resolved.type.name}(${c})`), '```'].join('\n')
},
insertText: constructors.some(Boolean) ? 'new(' : 'new()',
command: constructors.some(Boolean) ? parameterHints : undefined,
range,
sortText: '00000'
});
}
return { suggestions };
}
// <expression>.<instance member>
const dot = /(^|[^.])\.(\w*)$/.exec(prefix);
if (dot) {
const before = prefix.slice(0, prefix.length - dot[2].length - 1);
const chain = chainAt(before);
if (chain && !/^\d/.test(chain) && /[\w)\]'"}]$/.test(before)) {
const type = catalog ? inferChain(chain, env()) : null;
if (catalog && type) {
sortedMembers(instanceMembers(catalog, type, usingNamespaces(model.getLinesContent()))).forEach((m, i) =>
suggestions.push(memberItem(m, range, i))
);
const { base } = splitNotes(type);
if (/\[\s*\]$/.test(base) || /(List|Collection|Set)(\[[^\]]*\])?$/.test(base)) {
for (const intrinsic of ['ForEach', 'Where']) {
suggestions.push({
label: { label: intrinsic, detail: ' ({ … })' },
kind: Kind.Method,
detail: 'intrinsic method',
insertText: `${intrinsic}({ $0 })`,
insertTextRules: InsertRule.InsertAsSnippet,
range,
sortText: '2'
});
}
}
}
return { suggestions };
}
}
// $env:<name>
if (/\$env:[\w()]*$/i.test(prefix)) {
for (const name of ENVIRONMENT_VARIABLES)
@@ -181,28 +410,125 @@ export function registerScriptLanguages(monaco: typeof Monaco, resolve: ContextR
add('FilesRoot', Kind.Variable, 'Download To', 'The Download To folder, as a DirectoryInfo.', '1');
}
add('env:', Kind.Module, 'Environment variables', undefined, '3');
for (const auto of AUTOMATIC_VARIABLES) add(auto.name.slice(1), Kind.Variable, 'Automatic variable', auto.doc, '4');
for (const scope of ['script:', 'global:', 'using:']) add(scope, Kind.Module, 'Scope modifier', undefined, '5');
for (const auto of AUTOMATIC_VARIABLES) {
add(
auto.name.slice(1),
Kind.Variable,
auto.type ? `Automatic · ${shortType(splitNotes(auto.type).base)}` : 'Automatic variable',
auto.doc,
'4'
);
}
return { suggestions };
}
// [<type>
const type = /(^|[^\w\])$])\[([\w.]*)$/.exec(prefix);
// [<type> — also generic arguments ([List[<type>) and New-Object <type>
const type =
/(?:^|[^\w\])$])\[([\w.]*)$/.exec(prefix) ??
/\[[\w.]+\[(?:[\w.[\]]+,\s*)*([\w.]*)$/.exec(prefix) ??
/\bNew-Object\s+(?:-TypeName\s+)?([\w.]*)$/i.exec(prefix);
if (type) {
for (const name of TYPE_ACCELERATORS)
suggestions.push({ label: name, kind: Kind.Class, detail: 'Type', insertText: name, range });
const typed = type[1];
if (!catalog) {
for (const name of TYPE_ACCELERATORS)
suggestions.push({ label: name, kind: Kind.Class, detail: 'Type', insertText: name, range });
return { suggestions };
}
const dotAt = typed.lastIndexOf('.');
const typeRange = new monaco.Range(
position.lineNumber,
position.column - (typed.length - dotAt - 1),
position.lineNumber,
position.column
);
const seen = new Set<string>();
const addNamespace = (name: string, full: string) => {
if (seen.has(`n:${name.toLowerCase()}`)) return;
seen.add(`n:${name.toLowerCase()}`);
suggestions.push({
label: name,
kind: Kind.Module,
detail: `namespace ${full}`,
insertText: name,
range: typeRange,
sortText: `1${name}`
});
};
const addTypes = (namespace: string) => {
for (const t of catalog.namespaces.get(namespace.toLowerCase())?.types ?? []) {
const key = `t:${t.name.toLowerCase()}`;
if (seen.has(key)) continue;
seen.add(key);
suggestions.push({
label: { label: t.name, detail: t.generics ? `[${t.generics.join(', ')}]` : undefined, description: t.namespace },
kind:
t.kind === 'enum' ? Kind.Enum : t.kind === 'interface' ? Kind.Interface : t.kind === 'struct' ? Kind.Struct : Kind.Class,
detail: `${t.kind} ${t.display}`,
insertText: t.name,
filterText: t.name,
range: typeRange,
sortText: `2${t.name}`
});
}
};
if (dotAt >= 0) {
const namespace = typed.slice(0, dotAt);
for (const ns of [namespace, `System.${namespace}`]) {
const entry = catalog.namespaces.get(ns.toLowerCase());
if (!entry) continue;
for (const child of entry.children) addNamespace(child, `${entry.name}.${child}`);
addTypes(ns);
}
} else {
for (const [accelerator, full] of catalog.acceleratorList) {
suggestions.push({
label: { label: accelerator, description: shortType(full) },
kind: Kind.TypeParameter,
detail: `[${accelerator}] → ${full}`,
insertText: accelerator,
range: typeRange,
sortText: `0${accelerator}`
});
seen.add(`t:${accelerator.toLowerCase()}`);
}
for (const child of catalog.namespaces.get('')?.children ?? []) addNamespace(child, child);
for (const child of catalog.namespaces.get('system')?.children ?? []) addNamespace(child, `System.${child}`);
addTypes('System');
for (const ns of usingNamespaces(model.getLinesContent())) addTypes(ns);
if (!/New-Object/i.test(type[0])) {
for (const attribute of ATTRIBUTES) {
if (seen.has(`t:${attribute.toLowerCase()}`)) continue;
suggestions.push({
label: attribute,
kind: Kind.Class,
detail: 'attribute',
insertText: attribute,
range: typeRange,
sortText: `0${attribute}`
});
}
}
}
return { suggestions };
}
const { own, modules } = functionsOf(analysis, context);
const lookupCommand = (name: string): { parameters: ParameterInfo[]; label: string } | undefined => {
const key = name.toLowerCase();
const fn = own.get(key) ?? modules.get(key);
if (fn) return { parameters: fn.parameters.map((p) => ({ name: p, type: '' })), label: fn.name };
const found = catalog ? findCommand(catalog, name) : undefined;
if (found) return { parameters: found.command.parameters, label: found.command.name };
const curated = CMDLET_INDEX.get(key);
return curated ? { parameters: curated.parameters.map((p) => ({ name: p, type: '' })), label: curated.name } : undefined;
};
// -<Parameter> for the segment's command, or -<operator> after a value
const dash = /(^|\s)-(\w*)$/.exec(prefix);
if (dash) {
const command = commandBefore(prefix.slice(0, prefix.length - dash[0].length + dash[1].length));
const { own, modules } = functionsOf(analysis, context);
const known = command
? (CMDLET_INDEX.get(command.toLowerCase())?.parameters ??
own.get(command.toLowerCase())?.parameters ??
modules.get(command.toLowerCase())?.parameters)
: undefined;
const known = command ? lookupCommand(command) : undefined;
const dashRange = new monaco.Range(
position.lineNumber,
position.column - dash[2].length - 1,
@@ -210,12 +536,12 @@ export function registerScriptLanguages(monaco: typeof Monaco, resolve: ContextR
position.column
);
if (known) {
known.forEach((p, i) =>
known.parameters.forEach((p, i) =>
suggestions.push({
label: `-${p}`,
label: { label: `-${p.name}`, description: p.type ? (p.type === 'switch' ? 'switch' : `<${p.type}>`) : undefined },
kind: Kind.Property,
detail: command ?? '',
insertText: `-${p}`,
detail: [known.label, editionNote(p.edition)].filter(Boolean).join(' · '),
insertText: `-${p.name}`,
range: dashRange,
sortText: `0${String(i).padStart(3, '0')}`
})
@@ -238,8 +564,44 @@ export function registerScriptLanguages(monaco: typeof Monaco, resolve: ContextR
return { suggestions };
}
// -Parameter <value>: ValidateSet / enum values, CIM class names
const value = /(?:^|\s)-(\w+)(?:\s+|:)(['"]?)([\w.-]*)$/.exec(prefix);
const positional = /(?:^|[|;({]\s*|^\s*)([\w-]+)\s+(['"]?)(\w*)$/.exec(prefix);
if (value || positional) {
const commandName = value ? commandBefore(prefix.slice(0, prefix.length - value[0].length)) : positional![1];
const known = commandName ? lookupCommand(commandName) : undefined;
const canonical = known?.label.toLowerCase() ?? '';
let values: string[] | undefined;
let detail = '';
if (value) {
const parameter = value[1].toLowerCase();
values = known?.parameters.find((p) => p.name.toLowerCase() === parameter)?.values ?? COMMON_VALUES[parameter];
detail = `-${value[1]}`;
if (!values && catalog && CIM_COMMANDS.has(canonical) && /^class(name)?$/.test(parameter)) {
values = [...catalog.cim.values()].filter((c) => c.namespace.toLowerCase() === 'root/cimv2').map((c) => c.name);
detail = 'CIM class';
}
} else if (catalog && CIM_COMMANDS.has(canonical) && canonical !== 'invoke-cimmethod') {
values = [...catalog.cim.values()].filter((c) => c.namespace.toLowerCase() === 'root/cimv2').map((c) => c.name);
detail = 'CIM class';
}
if (values?.length) {
const quote = (value ?? positional)![2];
values.forEach((v, i) =>
suggestions.push({
label: v,
kind: Kind.EnumMember,
detail,
insertText: !quote && /[\s,;|]/.test(v) ? `'${v}'` : v,
range,
sortText: String(i).padStart(3, '0')
})
);
return { suggestions };
}
}
// Commands, keywords and snippets
const { own, modules } = functionsOf(analysis, context);
for (const fn of own.values()) {
suggestions.push({
label: fn.name,
@@ -263,7 +625,24 @@ export function registerScriptLanguages(monaco: typeof Monaco, resolve: ContextR
sortText: `0${fn.name}`
});
}
const listed = new Set<string>();
if (catalog) {
for (const command of catalog.commandList) {
listed.add(command.name.toLowerCase());
suggestions.push({
label: { label: command.name, description: command.module },
kind: Kind.Method,
detail: [command.module, editionNote(command.edition)].filter(Boolean).join(' · '),
documentation: commandDoc(catalog, command),
insertText: command.name,
filterText: command.name,
range,
sortText: `1${command.name}`
});
}
}
for (const cmdlet of CMDLETS) {
if (listed.has(cmdlet.name.toLowerCase())) continue;
suggestions.push({
label: cmdlet.name,
kind: Kind.Method,
@@ -302,6 +681,99 @@ export function registerScriptLanguages(monaco: typeof Monaco, resolve: ContextR
})
);
// ── Signature help: .NET method and constructor overloads ─────────────
disposables.push(
monaco.languages.registerSignatureHelpProvider('powershell', {
signatureHelpTriggerCharacters: ['(', ','],
signatureHelpRetriggerCharacters: [')'],
async provideSignatureHelp(model, position) {
const context = resolve(model);
if (!context) return null;
const catalog = loadedCatalog() ?? (await loadCatalog().catch(() => null));
if (!catalog || model.isDisposed()) return null;
const firstLine = Math.max(1, position.lineNumber - 15);
const text = model.getValueInRange({
startLineNumber: firstLine,
startColumn: 1,
endLineNumber: position.lineNumber,
endColumn: position.column
});
// The innermost unclosed ( before the cursor.
let depth = 0;
let open = -1;
for (let i = text.length - 1; i >= 0; i--) {
const c = text[i];
if (c === '"' || c === "'") {
const start = text.lastIndexOf(c, i - 1);
if (start < 0) return null;
i = start;
} else if (c === ')' || c === ']' || c === '}') depth++;
else if (c === '(' || c === '[' || c === '{') {
if (depth === 0) {
if (c === '(') open = i;
break;
}
depth--;
}
}
if (open < 0) return null;
const head = text.slice(0, open);
const access = /(::|\.)(\w+)\s*$/.exec(head);
if (!access) return null;
const owner = chainAt(head.slice(0, access.index));
const usings = usingNamespaces(model.getLinesContent());
const name = access[2];
let overloads: { returns: string; parameters: string; label: string }[] = [];
if (access[1] === '::') {
const typeText = /^\[(.+)\]$/.exec(owner)?.[1];
const resolved = typeText ? resolveType(catalog, typeText, usings) : null;
if (!resolved) return null;
if (name.toLowerCase() === 'new') {
overloads = constructorsOf(resolved).map((c) => ({ returns: '', parameters: c, label: `${resolved.type.name}(${c})` }));
} else {
const member = membersOf(catalog, resolved, true).find((m) => m.name.toLowerCase() === name.toLowerCase());
overloads = (member?.overloads ?? []).map((o) => ({
...o,
label: `static ${shortType(o.returns)} ${member!.name}(${o.parameters})`
}));
}
} else {
const lineOfOwner = position.lineNumber;
const type = owner ? inferChain(owner, typeEnv(catalog, model, lineOfOwner, position.column, context)) : null;
if (!type) return null;
const member = instanceMembers(catalog, type, usings).find((m) => m.name.toLowerCase() === name.toLowerCase());
overloads = (member?.overloads ?? []).map((o) => ({ ...o, label: `${shortType(o.returns)} ${member!.name}(${o.parameters})` }));
}
if (!overloads.length) return null;
const inner = text.slice(open + 1);
const active = inner.trim() ? splitTopLevel(inner).length - 1 : 0;
const signatures: Monaco.languages.SignatureInformation[] = overloads.map((o) => {
const start = o.label.indexOf('(') + 1;
const parameters: Monaco.languages.ParameterInformation[] = [];
let offset = start;
for (const p of o.parameters ? splitTopLevel(o.parameters) : []) {
const at = o.label.indexOf(p, offset);
if (at < 0) {
parameters.push({ label: p });
continue;
}
parameters.push({ label: [at, at + p.length] });
offset = at + p.length;
}
return { label: o.label, parameters };
});
const fits = signatures.findIndex((s) => s.parameters.length > active || (active === 0 && s.parameters.length === 0));
return {
value: { signatures, activeSignature: fits >= 0 ? fits : signatures.length - 1, activeParameter: active },
dispose: () => {}
};
}
})
);
// ── Hover ─────────────────────────────────────────────────────────────
disposables.push(
monaco.languages.registerHoverProvider('powershell', {
@@ -310,53 +782,116 @@ export function registerScriptLanguages(monaco: typeof Monaco, resolve: ContextR
const token = tokenAt(analysis, position.lineNumber, position.column);
if (!token) return null;
const context = resolve(model);
const catalog = loadedCatalog();
if (!catalog && context) void loadCatalog().catch(() => undefined);
const range = new monaco.Range(token.line, token.col, token.line, token.col + token.text.length);
const contents: Monaco.IMarkdownString[] = [];
const secretsVariable = (context?.secretsVariable?.trim() || 'Secrets').toLowerCase();
const usings = () => usingNamespaces(model.getLinesContent());
const lineText = model.getLineContent(token.line);
if (token.type === 'member') {
if (token.type === 'member' || token.type === 'member.function') {
const index = analysis.tokens.indexOf(token);
const separator = analysis.tokens[index - 1];
const owner = analysis.tokens[index - 2];
const ownerName = owner?.type === 'variable' ? owner.text.slice(1).toLowerCase() : '';
if (ownerName === secretsVariable) {
if (separator?.text === '.' && ownerName === secretsVariable) {
const bound = context?.secretNames?.some((s) => s.toLowerCase() === token.text.toLowerCase());
contents.push({
value: bound
? `**Secret** \`${token.text}\`\n\nResolved from the vault when the job runs; never written to output or logs.`
: `**Secret** \`${token.text}\` is not bound to this script. Add it on the **Secrets** tab.`
});
} else if (ownerName === 'files') {
} else if (separator?.text === '.' && ownerName === 'files') {
const file = context?.fileBindings?.find((f) => f.name.toLowerCase() === token.text.toLowerCase());
contents.push({
value: file
? `**${file.directory ? 'Directory' : 'File'}** \`${token.text}\`\n\nDelivered to the device before the script runs (${file.directory ? 'DirectoryInfo' : 'FileInfo'}).`
: `**File** \`${token.text}\` is not bound to this script. Add it on the **Files** tab.`
});
} else if (catalog && context) {
const before = lineText.slice(0, token.col - 1 - (separator?.text.length ?? 1));
const key = token.text.toLowerCase();
let found: MemberInfo | undefined;
if (separator?.text === '::') {
const typeText = /^\[(.+)\]$/.exec(chainAt(before))?.[1];
const resolved = typeText ? resolveType(catalog, typeText, usings()) : null;
if (resolved && key === 'new') {
const constructors = constructorsOf(resolved);
contents.push({
value: ['```csharp', ...constructors.slice(0, 8).map((c) => `${resolved.type.name}(${c})`), '```'].join('\n')
});
}
found = resolved ? membersOf(catalog, resolved, true).find((m) => m.name.toLowerCase() === key) : undefined;
} else {
const chain = chainAt(before);
const type = chain ? inferChain(chain, typeEnv(catalog, model, token.line, token.col, context)) : null;
found = type ? instanceMembers(catalog, type, usings()).find((m) => m.name.toLowerCase() === key) : undefined;
}
if (found) contents.push(memberDoc(found));
}
} else if (token.type === 'type') {
const written = token.text.replace(/^\[|\]$/g, '');
const resolved = catalog ? resolveType(catalog, written, usings()) : null;
if (resolved) contents.push(typeDoc(resolved, written));
} else if (token.type === 'parameter') {
const command = commandBefore(lineText.slice(0, token.col - 1));
const found = catalog && command ? findCommand(catalog, command) : undefined;
const name = token.text.slice(1).toLowerCase();
const parameter = found?.command.parameters.find((p) => p.name.toLowerCase() === name);
if (found && parameter) {
const index = found.command.parameters.indexOf(parameter);
const sets = found.command.sets.filter((s) => s.parameters.some((p) => p.index === index));
const mandatory = sets.some((s) => s.parameters.some((p) => p.index === index && p.mandatory));
const position = sets.flatMap((s) => s.parameters).find((p) => p.index === index && p.position !== undefined)?.position;
const facts = [
mandatory ? 'mandatory' : 'optional',
position !== undefined ? `position ${position}` : 'named',
editionNote(parameter.edition),
sets.length && found.command.sets.length > 1 ? `sets: ${sets.map((s) => s.name || 'default').join(', ')}` : ''
].filter(Boolean);
const values = parameter.values?.length
? `\n\n${parameter.values.slice(0, 16).join(', ')}${parameter.values.length > 16 ? ', …' : ''}`
: '';
contents.push({
value: `\`-${parameter.name}\` \`<${parameter.type}>\` — ${found.command.name}\n\n${facts.join(' · ')}${values}`
});
}
} else if (token.type === 'variable') {
const name = token.text.replace(/^\$\{?|\}$/g, '');
const key = name.toLowerCase();
const auto = AUTOMATIC_INDEX.get(key);
const declared = analysis.variables.get(key);
const inferred =
catalog && context ? variableType(name, typeEnv(catalog, model, token.line, lineText.length + 1, context)) : null;
const typeLine = inferred ? `\n\n\`${shortType(splitNotes(inferred).base)}\`` : '';
if (key === secretsVariable)
contents.push({ value: '**Secret bindings**\n\nThe secrets bound to this script, resolved when the job runs.' });
else if (key === 'files')
contents.push({ value: '**Delivered files**\n\nFiles and directories delivered with this script, by binding name.' });
else if (auto) contents.push({ value: `\`${auto.name}\` — automatic variable\n\n${auto.doc}` });
else if (auto) contents.push({ value: `\`${auto.name}\` — automatic variable\n\n${auto.doc}${typeLine}` });
else if (context?.parameterNames?.some((p) => p.toLowerCase() === key)) {
contents.push({ value: `\`$${name}\` — script parameter\n\nSupplied when the script is run (Parameters tab).` });
contents.push({ value: `\`$${name}\` — script parameter\n\nSupplied when the script is run (Parameters tab).${typeLine}` });
} else if (declared) {
const line = model.getLineContent(declared.line).trim();
const what = declared.kind === 'parameter' ? 'parameter' : declared.kind === 'loop' ? 'loop variable' : 'variable';
contents.push({ value: `\`$${declared.name}\` — ${what}, line ${declared.line}\n\n\`\`\`powershell\n${line}\n\`\`\`` });
contents.push({
value: `\`$${declared.name}\` — ${what}, line ${declared.line}${typeLine}\n\n\`\`\`powershell\n${line}\n\`\`\``
});
}
} else if (token.type === 'support.function' || token.type === 'identifier' || token.type === 'entity.name.function') {
const key = token.text.toLowerCase();
const { own, modules } = functionsOf(analysis, context);
const fn = own.get(key) ?? modules.get(key);
const found = catalog ? findCommand(catalog, token.text) : undefined;
const cmdlet = CMDLET_INDEX.get(key);
if (fn) contents.push(functionDoc(fn, fn.where));
else if (found) contents.push(commandDoc(catalog!, found.command, found.alias));
else if (cmdlet) contents.push(cmdletDoc(cmdlet));
else if (catalog) {
const cim = cimClassOf(catalog, token.text);
if (cim) contents.push({ value: `**${cim.name}** — CIM class\n\n\`${cim.namespace}\` · ${cim.properties.length} properties` });
}
}
return contents.length ? { range, contents } : null;
@@ -0,0 +1,679 @@
import {
cimClassOf,
commandOutput,
findCommand,
membersOf,
parseTypeName,
resolveType,
splitTopLevel,
type Catalog,
type MemberInfo
} from './powershell-catalog';
import { AUTOMATIC_VARIABLES } from './powershell-data';
/**
* Best-effort static typing of PowerShell expressions for member completion,
* hover and signature help: what `$x.`, `(Get-Date).` or
* `[IO.File]::OpenRead($p).` hold. Reads the text only — declarations
* ([T]$x), assignments, foreach loops, pipelines into ForEach-Object and
* catch blocks — and gives up (null) rather than guess.
*
* Types are strings: .NET names as the catalog writes them
* ("System.IO.FileInfo", "string[]", "List[string]"), CIM instances as
* "CimInstance#namespace/Class", and known extra note properties as a
* "{A,B}" suffix (hashtable and [pscustomobject] literals, Select-Object).
*/
export interface TypeEnv {
catalog: Catalog;
lines: string[];
/** Only text before this position is read (1-based). */
line: number;
column: number;
usings: string[];
/** Types the editor context knows ($Files, $FilesRoot, …); undefined when it does not apply. */
special?: (name: string) => string | null | undefined;
}
const AUTOMATIC_TYPES = new Map(AUTOMATIC_VARIABLES.filter((v) => v.type).map((v) => [v.name.slice(1).toLowerCase(), v.type!]));
const CIM_INSTANCE = 'Microsoft.Management.Infrastructure.CimInstance';
const CUSTOM_OBJECT = 'System.Management.Automation.PSCustomObject';
const MAX_DEPTH = 6;
/** `using namespace X` declarations in the document. */
export function usingNamespaces(lines: string[]): string[] {
const result: string[] = [];
for (const line of lines) {
const match = /^\s*using\s+namespace\s+([\w.]+)/i.exec(line);
if (match) result.push(match[1]);
}
return result;
}
/** Splits "Type{A;B=System.IO.FileInfo}" into the type and its extra note properties. */
export function splitNotes(type: string): { base: string; notes: { name: string; type?: string }[] } {
const match = /^(.*)\{([^{}]*)\}$/.exec(type);
if (!match) return { base: type, notes: [] };
const notes = match[2]
.split(';')
.filter(Boolean)
.map((note) => {
const [name, noteType] = note.split('=');
return { name, type: noteType || undefined };
});
return { base: match[1], notes };
}
/** "Type{A;B}" from a type and note property names (optionally typed). */
export const withNotes = (type: string, notes: (string | { name: string; type?: string })[]) =>
notes.length ? `${type}{${notes.map((n) => (typeof n === 'string' ? n : n.type ? `${n.name}=${n.type}` : n.name)).join(';')}}` : type;
const CIM_TYPES: Record<string, string> = {
string: 'System.String',
boolean: 'System.Boolean',
datetime: 'System.DateTime',
uint8: 'System.Byte',
sint8: 'System.SByte',
uint16: 'System.UInt16',
sint16: 'System.Int16',
uint32: 'System.UInt32',
sint32: 'System.Int32',
uint64: 'System.UInt64',
sint64: 'System.Int64',
real32: 'System.Single',
real64: 'System.Double',
char16: 'System.Char',
instance: CIM_INSTANCE,
reference: CIM_INSTANCE
};
/** A CIM property type ("UInt32", "StringArray") as .NET. */
function cimToDotNet(cimType: string): string {
const lower = cimType.toLowerCase();
if (lower.endsWith('array')) return `${CIM_TYPES[lower.slice(0, -5)] ?? 'System.Object'}[]`;
return CIM_TYPES[lower] ?? 'System.Object';
}
/** Instance members of a type string (CIM classes, note properties and array elements included). */
export function instanceMembers(catalog: Catalog, type: string, usings: string[] = []): MemberInfo[] {
const { base, notes } = splitNotes(type);
const result: MemberInfo[] = notes.map(({ name, type: noteType }) => ({
name,
kind: 'property',
isStatic: false,
type: noteType,
writable: true,
extended: true,
owner: 'NoteProperty'
}));
const seen = new Set(notes.map((n) => n.name.toLowerCase()));
const add = (members: MemberInfo[]) => {
for (const m of members) {
const key = m.name.toLowerCase();
if (!seen.has(key)) {
seen.add(key);
result.push(m);
}
}
};
let dotnet = base;
if (base.includes('#')) {
const cim = cimClassOf(catalog, base);
if (cim) {
add(
cim.properties.map(([name, cimType]) => ({
name,
kind: 'property' as const,
isStatic: false,
type: cimToDotNet(cimType),
writable: true,
owner: cim.name
}))
);
}
dotnet = base.slice(0, base.indexOf('#'));
}
const resolved = resolveType(catalog, dotnet, usings);
if (!resolved) return result;
add(membersOf(catalog, resolved, false));
if (resolved.arrays > 0) {
const element = resolveType(catalog, dotnet.replace(/\[\s*\]$/, ''), usings);
if (element) add(membersOf(catalog, element, false));
}
return result;
}
/** The type of `.name` / `.name(…)` on a value of `type`. */
function memberType(catalog: Catalog, type: string, name: string, call: boolean, args: number, usings: string[]): string | null {
const key = name.toLowerCase();
const member = instanceMembers(catalog, type, usings).find((m) => m.name.toLowerCase() === key);
if (!member) return null;
if (member.kind === 'method') {
if (!call) return null;
const overloads = member.overloads ?? [];
const match = overloads.find((o) => splitTopLevel(o.parameters).filter(Boolean).length === args) ?? overloads[0];
return match && match.returns !== 'void' ? match.returns : null;
}
return member.type ?? null;
}
/** The type of `[T]::name` / `[T]::name(…)`. */
function staticMemberType(catalog: Catalog, typeText: string, name: string, call: boolean, args: number, usings: string[]): string | null {
const resolved = resolveType(catalog, typeText, usings);
if (!resolved) return null;
if (name.toLowerCase() === 'new') return call ? typeText : null;
const key = name.toLowerCase();
const member = membersOf(catalog, resolved, true).find((m) => m.name.toLowerCase() === key);
if (!member) return null;
if (member.kind === 'enum') return typeText;
if (member.kind === 'method') {
if (!call) return null;
const overloads = member.overloads ?? [];
const match = overloads.find((o) => splitTopLevel(o.parameters).filter(Boolean).length === args) ?? overloads[0];
return match && match.returns !== 'void' ? match.returns : null;
}
return member.type ?? null;
}
/** What indexing or enumerating a value of `type` yields. */
export function elementType(catalog: Catalog, type: string): string | null {
const { base } = splitNotes(type);
if (/\[\s*\]$/.test(base)) return base.replace(/\[\s*\]$/, '');
const { name, args } = parseTypeName(base);
const simple = name.split('.').pop()?.toLowerCase() ?? '';
if (
args.length === 1 &&
/^(list|ilist|icollection|ienumerable|ireadonlylist|ireadonlycollection|collection|observablecollection|hashset|sortedset|queue|stack|linkedlist|concurrentbag|concurrentqueue|blockingcollection)$/.test(
simple
)
) {
return args[0];
}
if (args.length === 2 && /dictionary$/.test(simple)) return args[1];
if (/^(string|system\.string)$/i.test(base)) return 'System.Char';
if (catalog && /^(hashtable|system\.collections\.hashtable|arraylist|system\.collections\.arraylist)$/i.test(base))
return 'System.Object';
return null;
}
// ── Scanning ─────────────────────────────────────────────────────────────
/** Index of the bracket matching the opener at `open` (strings skipped), or -1. */
function matchForward(text: string, open: number): number {
const opener = text[open];
const closer = opener === '(' ? ')' : opener === '[' ? ']' : '}';
let depth = 0;
for (let i = open; i < text.length; i++) {
const c = text[i];
if (c === '"' || c === "'") {
const end = text.indexOf(c, i + 1);
if (end < 0) return -1;
i = end;
continue;
}
if (c === '(' || c === '[' || c === '{') depth++;
else if (c === ')' || c === ']' || c === '}') {
depth--;
if (depth === 0) return c === closer ? i : -1;
}
}
return -1;
}
/** Index of the opener matching the closer just before `end`, or -1. */
function matchBackward(text: string, end: number): number {
let depth = 0;
for (let i = end - 1; i >= 0; i--) {
const c = text[i];
if (c === '"' || c === "'") {
const start = text.lastIndexOf(c, i - 1);
if (start < 0) return -1;
i = start;
continue;
}
if (c === ')' || c === ']' || c === '}') depth++;
else if (c === '(' || c === '[' || c === '{') {
depth--;
if (depth === 0) return i;
}
}
return -1;
}
/**
* The member-access chain that ends the text: `$a.B.C(1)[0]`,
* `[IO.File]::OpenRead($p)`, `(Get-Date).Date`, `'text'.Length`.
*/
export function chainAt(text: string): string {
let i = text.length;
while (i > 0) {
const c = text[i - 1];
if (c === ')' || c === ']') {
const j = matchBackward(text, i);
if (j < 0) return '';
i = j;
if (c === ')' && (text[i - 1] === '$' || text[i - 1] === '@')) {
i--;
break;
}
continue;
}
if (c === '}') {
// ${braced variable}
const j = text.lastIndexOf('${', i);
if (j < 0 || text.slice(j, i).includes('\n')) break;
i = j;
break;
}
if (/\w/.test(c)) {
while (i > 0 && /\w/.test(text[i - 1])) i--;
if (text[i - 1] === '$') {
i--;
break;
}
// $env:Name, $script:x
if (text[i - 1] === ':' && text[i - 2] !== ':') {
let k = i - 1;
while (k > 0 && /\w/.test(text[k - 1])) k--;
if (text[k - 1] === '$') {
i = k - 1;
break;
}
}
continue;
}
if (c === '.') {
if (text[i - 2] === '.') break;
i--;
continue;
}
if (c === ':' && text[i - 2] === ':') {
i -= 2;
continue;
}
if (c === '"' || c === "'") {
const j = text.lastIndexOf(c, i - 2);
if (j >= 0) i = j;
break;
}
if (c === '_' || c === '?') break;
break;
}
return text.slice(i).trim();
}
const countArgs = (inner: string) => (inner.trim() ? splitTopLevel(inner).length : 0);
/** The type a chain evaluates to. */
export function inferChain(chain: string, env: TypeEnv, depth = 0): string | null {
if (depth > MAX_DEPTH || !chain) return null;
const { catalog, usings } = env;
let rest = chain;
let type: string | null = null;
let staticType: string | null = null;
const variable = /^\$\{([^}]+)\}|^\$((?:\w+:)?\w+)/.exec(rest);
if (variable) {
type = variableType(variable[1] ?? variable[2], env, depth + 1);
rest = rest.slice(variable[0].length);
} else if (rest.startsWith('[')) {
const end = matchForward(rest, 0);
if (end < 0) return null;
const typeText = rest.slice(1, end);
rest = rest.slice(end + 1);
if (rest.startsWith('::')) staticType = typeText;
else if (!rest) return null;
else type = 'System.Type';
} else if (/^[$@]?\(/.test(rest)) {
const open = rest.indexOf('(');
const end = matchForward(rest, open);
if (end < 0) return null;
const inner = rest.slice(open + 1, end);
type = rest.startsWith('@') ? 'System.Object[]' : inferExpression(inner, env, depth + 1);
rest = rest.slice(end + 1);
} else if (/^["']/.test(rest)) {
const end = rest.indexOf(rest[0], 1);
if (end < 0) return null;
type = 'System.String';
rest = rest.slice(end + 1);
} else if (/^\d/.test(rest)) {
const number = /^\d+(\.\d+)?/.exec(rest)!;
type = number[1] ? 'System.Double' : 'System.Int32';
rest = rest.slice(number[0].length);
} else {
return null;
}
while (rest) {
const access = /^(::|\.)(\w+)/.exec(rest);
if (access) {
rest = rest.slice(access[0].length);
let call = false;
let args = 0;
if (rest.startsWith('(')) {
const end = matchForward(rest, 0);
if (end < 0) return null;
call = true;
args = countArgs(rest.slice(1, end));
rest = rest.slice(end + 1);
}
if (access[1] === '::') {
if (!staticType) return null;
type = staticMemberType(catalog, staticType, access[2], call, args, usings);
staticType = null;
} else {
if (!type) return null;
type = memberType(catalog, type, access[2], call, args, usings);
}
if (!type) return null;
continue;
}
if (rest.startsWith('[')) {
const end = matchForward(rest, 0);
if (end < 0 || !type) return null;
type = elementType(catalog, type);
if (!type) return null;
rest = rest.slice(end + 1);
continue;
}
return null;
}
return staticType ? null : type;
}
/** Hashtable keys written in a literal (`@{ A = 1; 'B' = 2 }`, one level deep). */
function literalKeys(text: string): string[] {
const open = text.indexOf('{');
const end = matchForward(text, open);
const body = text.slice(open + 1, end < 0 ? undefined : end);
const keys: string[] = [];
let depth = 0;
let segmentStart = 0;
const take = (segment: string) => {
const match = /^\s*['"]?([\w-]+)['"]?\s*=/.exec(segment);
if (match && !keys.includes(match[1])) keys.push(match[1]);
};
for (let i = 0; i < body.length; i++) {
const c = body[i];
if (c === '"' || c === "'") {
const close = body.indexOf(c, i + 1);
if (close < 0) break;
i = close;
} else if (c === '(' || c === '[' || c === '{') depth++;
else if (c === ')' || c === ']' || c === '}') depth--;
else if (depth === 0 && (c === ';' || c === '\n')) {
take(body.slice(segmentStart, i));
segmentStart = i + 1;
}
}
take(body.slice(segmentStart));
return keys;
}
/** The value of `-Name value` or the n-th positional argument in an argument list. */
function argument(args: string, names: string[], position: number): string | undefined {
const tokens = args.match(/'[^']*'|"[^"]*"|\S+/g) ?? [];
let positional = 0;
for (let i = 0; i < tokens.length; i++) {
const token = tokens[i];
if (token.startsWith('-')) {
const name = token.slice(1).replace(/:$/, '').toLowerCase();
if (names.some((n) => n.startsWith(name) && name.length >= 2)) return tokens[i + 1]?.replace(/^['"]|['"]$/g, '');
// Assume a value follows a named parameter unless the next token is another parameter.
if (tokens[i + 1] && !tokens[i + 1].startsWith('-')) i++;
continue;
}
if (positional++ === position) return token.replace(/^['"]|['"]$/g, '');
}
return undefined;
}
/** The type a command invocation writes. */
function commandType(name: string, args: string, env: TypeEnv): string | null {
const { catalog } = env;
const found = findCommand(catalog, name);
if (!found) return null;
const command = found.command;
switch (command.name.toLowerCase()) {
case 'new-object': {
if (/-com/i.test(args)) return null;
const typeName = argument(args, ['typename'], 0);
return typeName && resolveType(catalog, typeName, env.usings) ? typeName : null;
}
case 'get-ciminstance':
case 'get-wmiobject': {
const query = argument(args, ['query'], 99);
const className = query ? /\bfrom\s+(\w+)/i.exec(query)?.[1] : argument(args, ['classname', 'class'], 0);
const base = command.name.toLowerCase() === 'get-wmiobject' ? 'System.Management.ManagementObject' : CIM_INSTANCE;
return className ? `${base}#${className}` : base;
}
case 'get-item':
case 'get-childitem': {
const path = argument(args, ['path', 'literalpath'], 0) ?? '';
if (/^(HK(LM|CU|CR|U|CC)|Registry::)/i.test(path)) return 'Microsoft.Win32.RegistryKey';
if (/^Cert:/i.test(path)) return 'System.Security.Cryptography.X509Certificates.X509Certificate2';
if (/^Env:/i.test(path)) return 'System.Collections.DictionaryEntry';
if (/(^|\s)-(ad|directory)\b/i.test(args)) return 'System.IO.DirectoryInfo';
break;
}
}
return commandOutput(catalog, command) ?? null;
}
/** Commands that pass their input through unchanged. */
const PASS_THROUGH = new Set(['where-object', 'sort-object', 'tee-object', 'get-unique', 'out-host']);
function pipelineStep(input: string | null, segment: string, env: TypeEnv, depth: number): string | null {
const match = /^\s*(?:&\s*)?([\w%?][\w.-]*)\s*([\s\S]*)$/.exec(segment);
if (!match) return null;
const found = findCommand(env.catalog, match[1]);
if (!found) return null;
const name = found.command.name.toLowerCase();
const args = match[2].trim();
if (PASS_THROUGH.has(name)) return input;
if (name === 'select-object') {
const expand = argument(args, ['expandproperty'], 99);
if (expand) return input ? memberType(env.catalog, input, expand, false, 0, env.usings) : null;
const property = argument(args, ['property'], 0);
if (!property) return input;
const names = splitTopLevel(
/(^|\s)-property\b/i.test(args) ? args.replace(/^.*?-property[:\s]+/i, '').split(/\s-\w/)[0] : args.split(/\s-\w/)[0]
)
.map((p) => (p.startsWith('@') ? /(?:name|n|label|l)\s*=\s*['"]([^'"]+)['"]/i.exec(p)?.[1] : p.replace(/^['"]|['"]$/g, '')))
.filter((p): p is string => Boolean(p) && /^[\w-]+$/.test(p!));
return names.length ? withNotes(CUSTOM_OBJECT, names) : input;
}
if (name === 'foreach-object') {
const member = /^\{\s*\$(?:_|PSItem)\.(\w+)\s*\}$/i.exec(args)?.[1] ?? argument(args, ['membername'], 0);
if (member && /^\w+$/.test(member) && input) return memberType(env.catalog, input, member, false, 0, env.usings);
return null;
}
return commandType(found.command.name, args, env);
}
/** The type of an expression (a right-hand side, a parenthesised command or pipeline). */
export function inferExpression(text: string, env: TypeEnv, depth = 0): string | null {
if (depth > MAX_DEPTH) return null;
// One statement, without a trailing comment.
const t = (splitTopLevel(text, ';')[0] ?? '').replace(/\s+#[^'"]*$/, '').trim();
if (!t) return null;
const segments = splitTopLevel(t, '|');
if (segments.length > 1 && segments.every(Boolean)) {
let type = inferSingle(segments[0], env, depth);
for (const segment of segments.slice(1)) type = pipelineStep(type, segment, env, depth);
return type;
}
return inferSingle(t, env, depth);
}
function inferSingle(t: string, env: TypeEnv, depth: number): string | null {
const { catalog } = env;
// Literals
if (/^\[ordered\]\s*@\{/i.test(t)) return withNotes('System.Collections.Specialized.OrderedDictionary', literalKeys(t));
if (/^\[(pscustomobject|psobject)\]\s*@\{/i.test(t)) return withNotes(CUSTOM_OBJECT, literalKeys(t));
if (t.startsWith('@{')) return withNotes('System.Collections.Hashtable', literalKeys(t));
if (t.startsWith('@(') && matchForward(t, 1) === t.length - 1) return 'System.Object[]';
if (/^\$(true|false)$/i.test(t)) return 'System.Boolean';
if (/^-?\d+$/.test(t)) return 'System.Int32';
if (/^-?\d+[lL]$/.test(t)) return 'System.Int64';
if (/^-?\d*\.\d+$/.test(t)) return 'System.Double';
if (/^\d+\s*\.\.\s*\d+$/.test(t)) return 'System.Object[]';
// Operators whose result type is fixed
if (/(^|\s)-(join|f|replace|creplace|ireplace)\s/i.test(t) || /^-join\b/i.test(t)) return 'System.String';
if (/(^|\s)-(split|csplit|isplit)\s/i.test(t) || /^-split\b/i.test(t)) return 'System.String[]';
const as = /\s-as\s+\[([^\]]+(?:\[[^\]]*\])?)\]\s*$/i.exec(t);
if (as) return as[1];
if (
/\s-(c|i)?(eq|ne|gt|ge|lt|le|like|notlike|match|notmatch|contains|notcontains|in|notin|is|isnot)\s|\s-(and|or|xor)\s|^-not\b|^!/i.test(
t
)
) {
return 'System.Boolean';
}
// A cast: [T]value (not [T]::Member)
if (t.startsWith('[')) {
const end = matchForward(t, 0);
if (end > 0 && !t.slice(end + 1).startsWith('::') && !t.slice(end + 1).startsWith('.') && t.length > end + 1) {
const typeText = t.slice(1, end);
if (!typeText.includes('(') && resolveType(catalog, typeText, env.usings)) return typeText;
}
}
// A string, alone
if (/^'[^']*'$/.test(t) || /^"[^"]*"$/.test(t) || /^@['"]/.test(t)) return 'System.String';
// A member-access chain
if (/^[$[('"\d@]/.test(t) && chainAt(t) === t) return inferChain(t, env, depth + 1);
// A command
const command = /^(?:&\s*)?([A-Za-z][\w]*(?:-[\w.]+)?|%|\?)(?=\s|$)([\s\S]*)$/.exec(t);
if (command) return commandType(command[1], command[2].trim(), env);
return null;
}
/** Text from `start` on `line` up to where brackets balance again (statements spanning lines). */
function statementFrom(lines: string[], line: number, start: string): string {
let text = start;
let depth = 0;
const measure = (s: string) => {
for (const c of s.replace(/'[^']*'|"[^"]*"/g, '')) {
if (c === '{' || c === '(' || c === '[') depth++;
else if (c === '}' || c === ')' || c === ']') depth--;
}
};
measure(start);
for (let n = line + 1; depth > 0 && n <= lines.length && n <= line + 60; n++) {
text += `\n${lines[n - 1]}`;
measure(lines[n - 1]);
}
return text;
}
const escape = (s: string) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
/** The type of `$name` at the environment's position, from the nearest declaration above it. */
export function variableType(name: string, env: TypeEnv, depth = 0): string | null {
if (depth > MAX_DEPTH) return null;
const bare = name.replace(/^(global|script|local|private|using):/i, '');
const key = bare.toLowerCase();
const special = env.special?.(key);
if (special !== undefined) return special;
if (key === '_' || key === 'psitem') return pipelineItemType(env, depth);
const automatic = AUTOMATIC_TYPES.get(key);
if (automatic) return automatic;
if (key.startsWith('env:')) return 'System.String';
const id = escape(bare);
const typed = new RegExp(`\\[((?:[^\\[\\]]|\\[[^\\[\\]]*\\])+)\\]\\s*\\$(?:\\w+:)?${id}\\b(?!\\s*[.\\[])`, 'gi');
const assign = new RegExp(`\\$(?:\\w+:)?${id}\\s*=(?!=)\\s*`, 'gi');
const loop = new RegExp(`\\bforeach\\s*\\(\\s*\\$${id}\\s+in\\s+`, 'gi');
for (let n = Math.min(env.line, env.lines.length); n >= 1; n--) {
const full = env.lines[n - 1] ?? '';
const text = n === env.line ? full.slice(0, Math.max(0, env.column - 1)) : full;
if (!text.includes('$')) continue;
let best: { index: number; type: string | null } | null = null;
for (const m of text.matchAll(typed)) {
if (m[1].includes('(') || /^(parameter|alias|cmdletbinding|validate\w*|allow\w*|outputtype)$/i.test(m[1])) continue;
// `= [int]$x` is a cast of an existing value, not a declaration.
if (/=\s*$/.test(text.slice(0, m.index))) continue;
if (!best || m.index! > best.index) best = { index: m.index!, type: m[1] };
}
for (const m of text.matchAll(assign)) {
// [T]$x = … is typed by T (matched above).
if (/\]\s*$/.test(text.slice(0, m.index))) continue;
const rhsStart = m.index! + m[0].length;
const rhs = statementFrom(env.lines, n, full.slice(rhsStart));
const inner: TypeEnv = { ...env, line: n, column: m.index! + 1 };
const type = inferExpression(rhs, inner, depth + 1);
if (!best || m.index! > best.index) best = { index: m.index!, type };
}
for (const m of text.matchAll(loop)) {
const open = text.lastIndexOf('(', m.index! + m[0].length);
const close = matchForward(full, open);
const collection = full.slice(m.index! + m[0].length, close < 0 ? undefined : close);
const inner: TypeEnv = { ...env, line: n, column: m.index! + 1 };
const type = inferExpression(collection, inner, depth + 1);
const element = type ? (elementType(env.catalog, type) ?? (/\[\s*\]$/.test(type) ? null : type)) : null;
if (!best || m.index! > best.index) best = { index: m.index!, type: element };
}
if (best) return best.type;
}
return null;
}
/** `$_` inside `… | ForEach-Object { … }`, `Where-Object { … }`, or a catch block. */
function pipelineItemType(env: TypeEnv, depth: number): string | null {
const before = [...env.lines.slice(0, env.line - 1), (env.lines[env.line - 1] ?? '').slice(0, env.column - 1)].join('\n');
// The innermost unclosed {
let depthCount = 0;
let open = -1;
for (let i = before.length - 1; i >= 0; i--) {
const c = before[i];
if (c === '}') depthCount++;
else if (c === '{') {
if (depthCount === 0) {
open = i;
break;
}
depthCount--;
}
}
if (open < 0) return null;
const head = before.slice(0, open).trimEnd();
if (/\b(catch|trap)(\s*\[[^\]]*\])*$/i.test(head)) return 'System.Management.Automation.ErrorRecord';
const filter = /\|\s*(?:ForEach-Object|Where-Object|foreach|where|%|\?)(?:\s+-(?:Process|FilterScript))?$/i.exec(head);
if (!filter) return null;
// The pipeline before it: back to the start of the statement.
const upTo = head.slice(0, filter.index);
let start = 0;
let level = 0;
for (let i = upTo.length - 1; i >= 0; i--) {
const c = upTo[i];
if (c === ')' || c === '}' || c === ']') level++;
else if (c === '(' || c === '{' || c === '[') {
if (level === 0) {
start = i + 1;
break;
}
level--;
} else if (level === 0 && (c === ';' || (c === '\n' && !/[|`]\s*$/.test(upTo.slice(0, i))))) {
start = i + 1;
break;
}
}
const pipeline = upTo
.slice(start)
.replace(/^\s*\$\w+\s*=\s*/, '')
.trim();
const lineOfStart = before.slice(0, start).split('\n').length;
const type = inferExpression(pipeline, { ...env, line: lineOfStart, column: 1 }, depth + 1);
if (!type) return null;
return elementType(env.catalog, type) ?? type;
}
+188
View File
@@ -0,0 +1,188 @@
// types
import type * as Monaco from 'monaco-editor';
import type { ScriptEngine, SnippetDto } from 'api/types';
// ==============================|| SNIPPET SYNTAX ||============================== //
//
// A snippet's content is code with tab stops, a subset of Monaco's (and VS Code's) snippet syntax:
// ${1:default} a tab stop with default text (braces inside it balance)
// ${1} a tab stop, or the same text as an earlier ${1:…}
// ${1|a,b,c|} a choice
// ${0} is where the cursor ends. Everything else is code, as typed: `$name`, `${name}`, `$1`,
// backslashes and braces need no escaping, and Bash's ${1:-default} (also :=, :+, :?) stays code.
export type SnippetPart = { kind: 'text'; text: string } | { kind: 'stop'; index: number; text?: string; choices?: string[] };
const START = /\$\{(\d+)(?=[}:|])/y;
const BASH_EXPANSION = /:[-=+?]/y;
/** Reads tab stops out of snippet content; anything that does not close is code. */
export function parseSnippet(content: string): SnippetPart[] {
const parts: SnippetPart[] = [];
let text = '';
let i = 0;
const flush = () => {
if (text) parts.push({ kind: 'text', text });
text = '';
};
while (i < content.length) {
START.lastIndex = i;
const start = content[i] === '$' ? START.exec(content) : null;
const stop = start && readStop(content, START.lastIndex, Number(start[1]));
if (!stop) {
text += content[i++];
continue;
}
flush();
parts.push(stop.part);
i = stop.end;
}
flush();
return parts;
}
function readStop(content: string, at: number, index: number): { part: SnippetPart; end: number } | null {
const next = content[at];
if (next === '}') return { part: { kind: 'stop', index }, end: at + 1 };
if (next === '|') {
const close = content.indexOf('|}', at + 1);
if (close < 0) return null;
const choices = content.slice(at + 1, close).split(',');
return { part: { kind: 'stop', index, choices }, end: close + 2 };
}
// ':' — a default, unless it is a Bash expansion.
BASH_EXPANSION.lastIndex = at;
if (BASH_EXPANSION.test(content)) return null;
let depth = 1;
for (let j = at + 1; j < content.length; j++) {
if (content[j] === '{') depth++;
else if (content[j] === '}' && --depth === 0) return { part: { kind: 'stop', index, text: content.slice(at + 1, j) }, end: j + 1 };
}
return null;
}
/** Monaco escapes: `$`, `}` and `\` are literal only escaped. */
const escapeText = (text: string) => text.replace(/[\\$}]/g, (c) => `\\${c}`);
const escapeChoice = (text: string) => text.replace(/[\\$},|]/g, (c) => `\\${c}`);
/** The content as a Monaco snippet (for insertAsSnippet and the snippet controller). */
export function toMonacoSnippet(content: string): string {
return parseSnippet(content)
.map((part) => {
if (part.kind === 'text') return escapeText(part.text);
if (part.choices) return `\${${part.index}|${part.choices.map(escapeChoice).join(',')}|}`;
if (part.text !== undefined) return `\${${part.index}:${escapeText(part.text)}}`;
return `\${${part.index}}`;
})
.join('');
}
/** The content with every tab stop filled with its default (a choice: its first option; a repeat: the earlier default). */
export function toPlainText(content: string): string {
const parts = parseSnippet(content);
const defaults = new Map<number, string>();
for (const part of parts) {
if (part.kind !== 'stop' || defaults.has(part.index)) continue;
if (part.choices) defaults.set(part.index, part.choices[0] ?? '');
else if (part.text !== undefined) defaults.set(part.index, part.text);
}
return parts
.map((part) => (part.kind === 'text' ? part.text : (part.choices?.[0] ?? part.text ?? defaults.get(part.index) ?? '')))
.join('');
}
// ==============================|| LANGUAGES ||============================== //
/** Both PowerShell engines take each other's snippets; Bash takes Bash. */
export const engineFamily = (engine: ScriptEngine): ScriptEngine[] => (engine === 'Bash' ? ['Bash'] : ['PowerShell', 'WindowsPowerShell']);
export const ENGINE_LABEL: Record<ScriptEngine, string> = {
PowerShell: 'PowerShell',
WindowsPowerShell: 'PowerShell 5',
Bash: 'Bash'
};
/** What each snippet language means, for hover text. */
export const ENGINE_HINT: Record<ScriptEngine, string> = {
PowerShell: 'Offered in PowerShell 7 and PowerShell 5 scripts, functions and Windows shells.',
WindowsPowerShell: 'Written for Windows PowerShell 5.1; offered wherever PowerShell snippets are.',
Bash: 'Offered in Bash scripts and Linux and macOS shells.'
};
/** The snippets for an engine (all of them without one), the engine's own first, then by name. */
export function snippetsFor(snippets: SnippetDto[] | undefined, engine?: ScriptEngine): SnippetDto[] {
const family = engine ? engineFamily(engine) : undefined;
return (snippets ?? [])
.filter((s) => !family || family.includes(s.language))
.sort((a, b) => Number(b.language === engine) - Number(a.language === engine) || a.name.localeCompare(b.name));
}
// ==============================|| MONACO ||============================== //
interface SnippetSource {
engine: ScriptEngine;
snippets: SnippetDto[];
}
/** Each editor's engine and snippets, by model URI (one provider per language serves them all). */
const sources = new Map<string, { current: SnippetSource }>();
const registered = new WeakSet<typeof Monaco>();
function register(monaco: typeof Monaco) {
if (registered.has(monaco)) return;
registered.add(monaco);
const provider: Monaco.languages.CompletionItemProvider = {
provideCompletionItems(model, position) {
const source = sources.get(model.uri.toString())?.current;
if (!source) return { suggestions: [] };
const word = model.getWordUntilPosition(position);
const range = new monaco.Range(position.lineNumber, word.startColumn, position.lineNumber, word.endColumn);
return {
suggestions: snippetsFor(source.snippets, source.engine).map((snippet) => ({
label: { label: snippet.name, description: snippet.builtIn ? 'Built-In Snippet' : 'Snippet' },
kind: monaco.languages.CompletionItemKind.Snippet,
detail: snippet.description ?? undefined,
documentation: { value: '```\n' + toPlainText(snippet.content).replace(/```/g, '`​``') + '\n```' },
insertText: toMonacoSnippet(snippet.content),
insertTextRules: monaco.languages.CompletionItemInsertTextRule.InsertAsSnippet,
// After the language's own suggestions.
sortText: `~${snippet.name}`,
range
}))
};
}
};
monaco.languages.registerCompletionItemProvider('powershell', provider);
monaco.languages.registerCompletionItemProvider('shell', provider);
}
/** Offers `source`'s snippets in the model's completions until disposed. */
export function attachSnippets(
monaco: typeof Monaco,
model: Monaco.editor.ITextModel,
source: { current: SnippetSource }
): Monaco.IDisposable {
register(monaco);
const key = model.uri.toString();
sources.set(key, source);
return { dispose: () => sources.get(key) === source && sources.delete(key) };
}
interface SnippetController {
insert(template: string): void;
}
/** Inserts the snippet at the cursor (replacing a selection), with its tab stops live. */
export function insertSnippet(editor: Monaco.editor.IStandaloneCodeEditor, content: string) {
editor.focus();
const controller = editor.getContribution('snippetController2') as unknown as SnippetController | null;
if (controller?.insert) {
controller.insert(toMonacoSnippet(content));
return;
}
const selection = editor.getSelection();
if (selection) editor.executeEdits('snippet', [{ range: selection, text: toPlainText(content), forceMoveMarkers: true }]);
}
+19
View File
@@ -0,0 +1,19 @@
// The built-in scripts behind Restart and Shut Down (Shared.Contracts PowerActions): never stored,
// so jobs and runs of them have no script page to link to.
import type { PowerAction } from 'api/types';
export const RESTART_SCRIPT_ID = '7e57a7e0-0000-4000-8000-000000000001';
export const SHUT_DOWN_SCRIPT_ID = '7e57a7e0-0000-4000-8000-000000000002';
/** The first agent version that shuts down, and installs updates when asked. */
export const POWER_MINIMUM_AGENT_VERSION = '1.14.0';
/** The power action a script id names, or null for any other script. */
export function powerActionOf(scriptId: string | null | undefined): PowerAction | null {
const id = scriptId?.toLowerCase();
return id === RESTART_SCRIPT_ID ? 'restart' : id === SHUT_DOWN_SCRIPT_ID ? 'shutDown' : null;
}
export const isPowerScript = (scriptId: string | null | undefined) => powerActionOf(scriptId) !== null;
export const POWER_LABEL: Record<PowerAction, string> = { restart: 'Restart', shutDown: 'Shut Down' };
+108 -4
View File
@@ -89,14 +89,17 @@ internal sealed class FakeSystemRestart(RestartLog log, JobHistoryStore store) :
public List<(TimeSpan Delay, string Message)> Calls { get; } = [];
public List<PowerOptions> Options { get; } = [];
public IReadOnlyList<PendingRestart> KeptAtRestart { get; private set; } = [];
/// <summary>Set: the machine "goes down" (the agent is stopped) once the restart is taken.</summary>
public CancellationTokenSource? GoesDown { get; set; }
public Task<RestartResult> RestartAsync(TimeSpan delay, string message, CancellationToken cancellationToken)
public Task<RestartResult> PowerAsync(TimeSpan delay, string message, PowerOptions options, CancellationToken cancellationToken)
{
Calls.Add((delay, message));
Options.Add(options);
KeptAtRestart = store.PendingRestarts();
log.Add("restart");
GoesDown?.Cancel();
@@ -172,6 +175,22 @@ public sealed class RestartDecisionTests
[InlineData(RestartAfterRun.WhenRequested, 1, false, false)]
public void AnAskingExitCodeIsASuccessWhenTheOptionIsOn(RestartAfterRun option, int exitCode, bool unix, bool success)
=> Assert.Equal(success, RestartDecision.IsSuccessfulAsk(option, JobState.Failed, exitCode, unix));
[Fact]
public void ThePlanCarriesShutDownAndUpdatesAndTheConsoleHasItsOwnWords()
{
var settings = new RestartSettings(RestartAfterRun.Always, 30, 0, PowerAction.ShutDown, InstallUpdates: true);
var plan = RestartDecision.Decide(settings, JobState.Succeeded, 0, allowRestart: true, unix: false)!;
Assert.Equal(new PowerOptions(PowerAction.ShutDown, true), plan.Power);
var console = RestartDecision.FromConsole(plan);
Assert.Equal("Shut down from the console.", console.Message);
Assert.True(console.Power.FromConsole);
var refused = RestartDecision.Decide(settings, JobState.Succeeded, 0, allowRestart: false, unix: false)!;
Assert.Equal((JobRestartState.Refused, RestartDecision.ShutDownRefusedMessage), (refused.State, refused.Message));
}
}
public sealed class RestartCoordinatorTests : IDisposable
@@ -246,6 +265,36 @@ public sealed class RestartCoordinatorTests : IDisposable
Assert.Equal((start.AddSeconds(60), start.AddSeconds(60), 0), (kept.DueUtc, kept.InitiatedUtc, kept.GraceSeconds));
}
[Fact]
public async Task AShutdownFromTheConsoleGoesToTheSystemWithItsOptionsAndIsKept()
{
using var down = new CancellationTokenSource();
system.GoesDown = down;
var power = new PowerOptions(PowerAction.ShutDown, InstallUpdates: true, FromConsole: true);
await Coordinator().RunAsync(Ticket(delaySeconds: 0) with { Power = power }, down.Token);
Assert.Equal(power, system.Options.Single());
Assert.Equal("ExecuteR shuts down this device.", system.Calls.Single().Message);
var kept = Assert.Single(system.KeptAtRestart);
Assert.Equal((PowerAction.ShutDown, true, true), (kept.Action, kept.InstallUpdates, kept.FromConsole));
// An agent that starts again before the machine is down keeps them too.
var reread = Assert.Single(store.PendingRestarts());
Assert.Equal(power, reread.Power);
}
[Fact]
public async Task AScriptsRestartIsARestartWithoutUpdates()
{
using var down = new CancellationTokenSource();
system.GoesDown = down;
await Coordinator().RunAsync(Ticket(delaySeconds: 0), down.Token);
Assert.Equal(PowerOptions.Restart, system.Options.Single());
}
[Fact]
public async Task NoDelayTheRestartFollowsTheServersAnswer()
{
@@ -682,9 +731,9 @@ public sealed class WindowsSystemRestartTests
return ShutdownError;
}
public (int ExitCode, string Output) RunWpeutilReboot()
public (int ExitCode, string Output) RunWpeutil(string command)
{
Calls.Add("wpeutil reboot");
Calls.Add($"wpeutil {command}");
return (WpeutilExitCode, "Rebooting...");
}
}
@@ -715,6 +764,35 @@ public sealed class WindowsSystemRestartTests
Assert.Empty(waits);
}
[Theory]
[InlineData(PowerAction.Restart, false, false, 0x4u | 0x1u, 0x80000000u | 0x00040000u | 0x00000002u)]
[InlineData(PowerAction.Restart, true, true, 0x4u | 0x1u | 0x40u, 0x80000000u | 0x00000001u)]
[InlineData(PowerAction.ShutDown, false, true, 0x8u | 0x1u, 0x80000000u | 0x00000001u)] // SHUTDOWN_POWEROFF, never HYBRID
[InlineData(PowerAction.ShutDown, true, true, 0x8u | 0x1u | 0x40u, 0x80000000u | 0x00000001u)] // + SHUTDOWN_INSTALL_UPDATES
public async Task ShuttingDownAndUpdatesAreFlagsAndTheConsoleIsPlannedMaintenance(
PowerAction action, bool updates, bool console, uint expectedFlags, uint expectedReason)
{
var api = new FakeShutdownApi();
await Restart(api).PowerAsync(TimeSpan.Zero, "m", new PowerOptions(action, updates, console), CancellationToken.None);
var (_, flags, reason, _) = api.Initiated!.Value;
Assert.Equal(expectedFlags, flags);
Assert.Equal(expectedReason, reason);
}
[Fact]
public async Task WindowsPeShutsDownWithWpeutilShutdown()
{
var api = new FakeShutdownApi { ShutdownError = 1 };
var result = await Restart(api, winPe: true).PowerAsync(
TimeSpan.Zero, "m", new PowerOptions(PowerAction.ShutDown), CancellationToken.None);
Assert.Equal(["privilege", "InitiateShutdown", "wpeutil shutdown"], api.Calls);
Assert.Equal((RestartOutcome.Started, WindowsSystemRestart.WpeutilShutdownMechanism), (result.Outcome, result.Mechanism));
}
[Fact]
public async Task WithoutThePrivilegeNothingIsAsked()
{
@@ -834,6 +912,28 @@ public sealed class LinuxSystemRestartTests
Assert.Empty(waits);
}
[Fact]
public async Task ShuttingDownIsLogindsPowerOffOrAScheduledPowerOffOrPowerOffTarget()
{
var off = new PowerOptions(PowerAction.ShutDown);
var bus = new FakeBus();
await Restart(bus).PowerAsync(TimeSpan.Zero, "m", off, CancellationToken.None);
Assert.Equal(("PowerOff", "b"), (bus.Calls.Single().Member, bus.Calls.Single().Signature));
var scheduled = new FakeBus();
await Restart(scheduled).PowerAsync(TimeSpan.FromMinutes(1), "m", off, CancellationToken.None);
Assert.Equal(["SetWallMessage", "ScheduleShutdown"], scheduled.Calls.Select(c => c.Member));
Assert.Equal("poweroff", scheduled.Calls[1].Arguments[0]);
var noLogind = new FakeBus
{
Fails = call => call.Destination == LinuxSystemRestart.Login1Destination ? new DBusCallException("x", "no logind") : null,
};
var result = await Restart(noLogind).PowerAsync(TimeSpan.Zero, "m", off, CancellationToken.None);
Assert.Equal(["poweroff.target", "replace-irreversibly"], noLogind.Calls.Last().Arguments);
Assert.Equal("systemd1.StartUnit(poweroff.target)", result.Mechanism);
}
[Fact]
public async Task AShutdownUnderWayCountsAsTaken()
{
@@ -928,6 +1028,10 @@ public sealed class LinuxSystemRestartTests
Assert.Equal(RestartOutcome.Unsupported, result.Outcome);
Assert.False(result.Accepted);
var off = await new UnsupportedSystemRestart("macOS").PowerAsync(
TimeSpan.Zero, "m", new PowerOptions(PowerAction.ShutDown), CancellationToken.None);
Assert.Equal("Shutting down is not supported on macOS.", off.Message);
}
}
@@ -1009,6 +1113,6 @@ public sealed class RestartWarningTests
$$"""{"jobId":"{{Guid.NewGuid()}}","scriptId":"{{Guid.NewGuid()}}","scriptName":"n","content":"c","restartAfterRun":"always","restartDelaySeconds":30}""")!;
Assert.Equal(new RestartSettings(RestartAfterRun.Always, 30, 0), command.Restart);
Assert.DoesNotContain("\"restart\"", Shared.Contracts.Serialization.JsonDefaults.Serialize(command), StringComparison.Ordinal);
Assert.DoesNotContain("\"restart\":", Shared.Contracts.Serialization.JsonDefaults.Serialize(command), StringComparison.Ordinal);
}
}
+84
View File
@@ -0,0 +1,84 @@
using Agent.Configuration;
using Agent.PowerShell;
using Agent.Sessions;
using Agent.Storage;
using Microsoft.Extensions.Logging.Abstractions;
using Shared.Contracts.Messages;
using Shared.Contracts.Models;
using Xunit;
namespace Agent.Tests;
/// <summary>Each Signed-In User: the script runs once per signed-in user, and nobody means nothing to do.</summary>
public sealed class RunAsEachUserTests : IDisposable
{
private readonly string root = Path.Combine(Path.GetTempPath(), "executer-runaseach-tests", Guid.NewGuid().ToString("N"));
private readonly RecordingPublisher publisher = new(() => DateTimeOffset.UtcNow);
private readonly JobHistoryStore history;
public RunAsEachUserTests()
{
Directory.CreateDirectory(root);
history = new JobHistoryStore(Path.Combine(root, "jobs.db"));
}
public void Dispose()
{
history.Dispose();
Microsoft.Data.Sqlite.SqliteConnection.ClearAllPools();
try
{
Directory.Delete(root, recursive: true);
}
catch (IOException)
{
}
}
private sealed class FixedUsers(SignedInUserLookup lookup) : ISignedInUserResolver
{
public SignedInUserLookup Resolve(string? requested = null) => lookup;
}
private async Task<JobStatePayload> RunAsync(SignedInUserLookup lookup, bool eachUser)
{
var handler = new PowerShellJobHandler(
new PowerShellExecutionService(), publisher, history, new Agent.Files.ServerDownloads(null, false), NullLogger.Instance,
new JobRootInfo(Path.Combine(root, "jobs"), Shared.Infrastructure.Configuration.ConfigurationSource.Default),
signedInUsers: new FixedUsers(lookup));
var command = new ScriptCommandPayload(
Guid.NewGuid(), Guid.NewGuid(), "Per User", "'ran'", 60, RunAsUser: true, RunAsEachUser: eachUser);
await handler.RunJobAsync(command, Guid.NewGuid(), null, TestContext.Current.CancellationToken);
return publisher.States.Last(s => s.JobId == command.JobId);
}
[Fact]
public async Task NobodySignedInRunsForNobodyAndSucceeds()
{
var state = await RunAsync(SignedInUserLookup.Nobody(SignedInUsers.NobodyReason, []), eachUser: true);
Assert.Equal(JobState.Succeeded, state.State);
Assert.Contains("ran for nobody", state.Message);
Assert.DoesNotContain(publisher.Output, o => o.Text.Contains("ran") && !o.Text.Contains("nobody"));
}
[Fact]
public async Task SessionsThatCannotBeReadFailTheJob()
{
var state = await RunAsync(SignedInUserLookup.Nobody("The device's sessions could not be read."), eachUser: true);
Assert.Equal(JobState.Failed, state.State);
Assert.Contains("could not be read", state.Message);
}
[Fact]
public async Task OneSignedInUserStillFailsWhenNobodyIsClear()
{
var state = await RunAsync(SignedInUserLookup.Nobody("Several users are signed in", ["ann", "bob"]), eachUser: false);
Assert.Equal(JobState.Failed, state.State);
Assert.Contains("Several users", state.Message);
}
}
+141
View File
@@ -0,0 +1,141 @@
using System.Net;
using System.Net.Http.Json;
using Backend.Jobs;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging.Abstractions;
using Shared.Contracts.Api;
using Shared.Contracts.Messages;
using Shared.Contracts.Models;
using Shared.Contracts.Serialization;
using Xunit;
namespace Backend.Tests;
/// <summary>
/// Restart and Shut Down: a run of the built-in power script with Restart After Run on, the
/// spread of any run, and never a shutdown (or updates) sent to an agent that would restart instead.
/// </summary>
public class PowerTests(BackendTestFixture fixture) : IClassFixture<BackendTestFixture>
{
private const string Old = "1.13.0";
private static Task<HttpResponseMessage> PostAsync(HttpClient client, PowerRequest request)
=> client.PostAsJsonAsync(ApiRoutes.Power, request, JsonDefaults.Options);
private static async Task<GroupRunDto> PowerAsync(HttpClient client, PowerRequest request)
{
var response = await PostAsync(client, request);
response.EnsureSuccessStatusCode();
return (await response.Content.ReadFromJsonAsync<GroupRunDto>(JsonDefaults.Options))!;
}
private List<ScriptCommandPayload> Sent(string clientId)
{
lock (fixture.Scripts.Sent)
{
return fixture.Scripts.Sent.Where(s => s.ClientId == clientId).Select(s => s.Command).ToList();
}
}
[Fact]
public async Task ARestartIsARunOfTheBuiltInScriptWithRestartAfterRunAlways()
{
fixture.Scripts.Accept = true;
using var client = await fixture.SignedInAsync("power-admin");
var device = await fixture.SeedDeviceAsync("POWER-RESTART", agentVersion: Old);
var run = await PowerAsync(client, new PowerRequest(PowerAction.Restart, [device], DelaySeconds: 120, WarningSeconds: 60));
var job = Assert.Single(run.Jobs);
Assert.Equal((PowerActions.RestartScriptId, PowerActions.RestartName), (job.ScriptId, job.ScriptName));
Assert.NotNull(run.RunId);
var sent = Sent(device).Single();
Assert.Equal(
(RestartAfterRun.Always, 120, 60, PowerAction.Restart, false),
(sent.RestartAfterRun, sent.RestartDelaySeconds, sent.RestartWarningSeconds, sent.RestartAction, sent.RestartInstallsUpdates));
Assert.Equal(PowerActions.RestartScriptId, sent.ScriptId);
}
[Fact]
public async Task ShuttingDownGoesOnlyToAgentsThatCanAndOlderOnesGetAFailedJob()
{
fixture.Scripts.Accept = true;
using var client = await fixture.SignedInAsync("power-admin");
var current = await fixture.SeedDeviceAsync("POWER-OFF-NEW", agentVersion: PowerActions.MinimumAgentVersion);
var old = await fixture.SeedDeviceAsync("POWER-OFF-OLD", agentVersion: Old);
var run = await PowerAsync(client, new PowerRequest(PowerAction.ShutDown, [current, old], InstallUpdates: true));
Assert.Equal(2, run.Jobs.Count);
var sent = Sent(current).Single();
Assert.Equal((PowerAction.ShutDown, true), (sent.RestartAction, sent.RestartInstallsUpdates));
Assert.Empty(Sent(old));
var refused = await fixture.WithDbAsync(db => db.Jobs.AsNoTracking().SingleAsync(j => j.ClientId == old && j.RunId == run.RunId));
Assert.Equal(JobState.Failed, refused.State);
Assert.Contains("cannot shut down", refused.OutputSummary);
Assert.Contains(PowerActions.MinimumAgentVersion, refused.OutputSummary);
}
[Fact]
public async Task InstallingUpdatesNeedsACurrentAgentButAPlainRestartDoesNot()
{
Assert.Null(PowerActions.Refusal(PowerAction.Restart, false, Old));
Assert.Contains("install updates", PowerActions.Refusal(PowerAction.Restart, true, Old));
Assert.Null(PowerActions.Refusal(PowerAction.ShutDown, true, PowerActions.MinimumAgentVersion));
Assert.NotNull(PowerActions.Refusal(PowerAction.ShutDown, false, null));
fixture.Scripts.Accept = true;
using var client = await fixture.SignedInAsync("power-admin");
var old = await fixture.SeedDeviceAsync("POWER-UPDATES-OLD", agentVersion: Old);
await PowerAsync(client, new PowerRequest(PowerAction.Restart, [old], InstallUpdates: true));
Assert.Empty(Sent(old));
}
[Fact]
public async Task ASpreadShutdownIsSentByTheDispatcherFromTheRunsSnapshot()
{
fixture.Scripts.Accept = true;
using var client = await fixture.SignedInAsync("power-admin");
var current = await fixture.SeedDeviceAsync("POWER-SPREAD-NEW", agentVersion: PowerActions.MinimumAgentVersion);
var old = await fixture.SeedDeviceAsync("POWER-SPREAD-OLD", agentVersion: Old);
var run = await PowerAsync(client, new PowerRequest(
PowerAction.ShutDown, [current, old], DelaySeconds: 30, StaggerSeconds: 600, StaggerBatchSize: 1));
Assert.True(Sent(current).Count + Sent(old).Count <= 1); // only the first slot may be due now
var latest = await fixture.WithDbAsync(db => db.Jobs.AsNoTracking().Where(j => j.RunId == run.RunId).MaxAsync(j => j.NotBeforeUtc));
await new JobDispatcher(fixture.Services.GetRequiredService<IServiceScopeFactory>(), NullLogger<JobDispatcher>.Instance)
.RunPassAsync(latest!.Value.AddSeconds(1), CancellationToken.None);
var sent = Sent(current).Single();
Assert.Equal((PowerAction.ShutDown, RestartAfterRun.Always, 30), (sent.RestartAction, sent.RestartAfterRun, sent.RestartDelaySeconds));
Assert.Empty(Sent(old));
var refused = await fixture.WithDbAsync(db => db.Jobs.AsNoTracking().SingleAsync(j => j.RunId == run.RunId && j.ClientId == old));
Assert.Equal(JobState.Failed, refused.State);
}
[Fact]
public async Task ItNeedsThePowerPermissionAndValidTargetsAndTimes()
{
using var viewer = await fixture.SignedInAsync("power-viewer", "Viewer");
var device = await fixture.SeedDeviceAsync("POWER-PERM");
Assert.Equal(HttpStatusCode.Forbidden, (await PostAsync(viewer, new PowerRequest(PowerAction.Restart, [device]))).StatusCode);
using var client = await fixture.SignedInAsync("power-admin");
Assert.Equal(HttpStatusCode.BadRequest, (await PostAsync(client, new PowerRequest(PowerAction.Restart))).StatusCode);
Assert.Equal(HttpStatusCode.BadRequest, (await PostAsync(client, new PowerRequest(PowerAction.Restart, [device], DelaySeconds: 3601))).StatusCode);
Assert.Equal(HttpStatusCode.BadRequest, (await PostAsync(client, new PowerRequest(PowerAction.Restart, [device], WarningSeconds: 5))).StatusCode);
Assert.Equal(HttpStatusCode.BadRequest, (await PostAsync(client, new PowerRequest(PowerAction.Restart, [device], StaggerSeconds: -1))).StatusCode);
Assert.Equal(HttpStatusCode.BadRequest, (await PostAsync(client, new PowerRequest((PowerAction)7, [device]))).StatusCode);
}
[Fact]
public void OperatorsAndHelpDeskMayRestartAndViewersMayNot()
{
Assert.Contains(Backend.Auth.Permissions.DevicesPower, Backend.Auth.Permissions.OperatorSet);
Assert.Contains(Backend.Auth.Permissions.DevicesPower, Backend.Auth.Permissions.HelpDeskSet);
Assert.DoesNotContain(Backend.Auth.Permissions.DevicesPower, Backend.Auth.Permissions.ViewerSet);
Assert.Contains(Backend.Auth.Permissions.DevicesPower, Backend.Auth.Permissions.KnownKeys);
}
}
+35
View File
@@ -97,6 +97,41 @@ public class RunAsUserTests(BackendTestFixture fixture) : IClassFixture<BackendT
Assert.Equal(JobState.Failed, refused.State);
}
[Fact]
public async Task EachSignedInUserTurnsRunAsOnAndTurningRunAsOffClearsIt()
{
using var client = await fixture.SignedInAsync("runas-each-admin");
var created = await SaveAsync(client, new SaveScriptRequest("runas-each", null, "'hi'", RunAsEachUser: true));
Assert.True(created.RunAsUser);
Assert.True(created.RunAsEachUser);
Assert.True((await SaveAsync(client, Request("runas-each"), created.Id)).RunAsEachUser);
var off = await SaveAsync(client, Request("runas-each", asUser: false), created.Id);
Assert.False(off.RunAsUser);
Assert.False(off.RunAsEachUser);
}
[Fact]
public async Task EachSignedInUserGoesOnlyToAgentsThatHonorIt()
{
fixture.Scripts.Accept = true;
using var client = await fixture.SignedInAsync("runas-each-run");
var script = await SaveAsync(client, new SaveScriptRequest("runas-each-dispatch", null, "'hi'", RunAsEachUser: true));
var current = await fixture.SeedDeviceAsync("RUNAS-EACH-NEW", agentVersion: RunAsUser.EachUserMinimumAgentVersion);
var older = await fixture.SeedDeviceAsync("RUNAS-EACH-OLD", agentVersion: Current);
(await client.PostAsJsonAsync(ApiRoutes.Jobs, new CreateJobRequest(null, script.Id, ClientIds: [current, older]), JsonDefaults.Options))
.EnsureSuccessStatusCode();
var sent = Sent(current).Single();
Assert.True(sent.RunAsUser && sent.RunAsEachUser);
Assert.Empty(Sent(older));
var refused = await fixture.WithDbAsync(db => db.Jobs.AsNoTracking().SingleAsync(j => j.ClientId == older && j.ScriptId == script.Id));
Assert.Equal(JobState.Failed, refused.State);
Assert.Contains(RunAsUser.EachUserMinimumAgentVersion, refused.OutputSummary);
}
[Fact]
public async Task ScriptsThatRunAsTheAgentStillGoToOlderAgents()
{
+202
View File
@@ -0,0 +1,202 @@
using System.Net;
using System.Net.Http.Json;
using System.Text.RegularExpressions;
using Backend.Auth;
using Backend.Data;
using Backend.Security;
using Backend.Snippets;
using Microsoft.EntityFrameworkCore;
using Shared.Contracts.Api;
using Shared.Contracts.Models;
using Shared.Contracts.Serialization;
using Xunit;
namespace Backend.Tests;
/// <summary>The snippet library: built-ins listed and read-only, the library's own stored, copies, permissions and audit.</summary>
public partial class SnippetTests(BackendTestFixture fixture) : IClassFixture<BackendTestFixture>
{
private static async Task<SnippetDto> CreateAsync(HttpClient client, SaveSnippetRequest request)
{
var response = await client.PostAsJsonAsync(ApiRoutes.Snippets, request, JsonDefaults.Options);
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
return (await response.Content.ReadFromJsonAsync<SnippetDto>(JsonDefaults.Options))!;
}
private static async Task<List<SnippetDto>> ListAsync(HttpClient client)
=> (await client.GetFromJsonAsync<List<SnippetDto>>(ApiRoutes.Snippets, JsonDefaults.Options))!;
/// <summary>A signed-in client whose only role grants exactly <paramref name="permissions"/>.</summary>
private async Task<HttpClient> SignedInWithAsync(string username, params string[] permissions)
{
var roleId = await fixture.WithDbAsync(async db =>
{
var role = new RoleEntity
{
Id = Guid.NewGuid(), Name = $"snippets-{Guid.NewGuid():N}",
PermissionsJson = JsonDefaults.Serialize(permissions),
CreatedUtc = DateTimeOffset.UtcNow, UpdatedUtc = DateTimeOffset.UtcNow,
};
db.Roles.Add(role);
await db.SaveChangesAsync();
return role.Id;
});
return await fixture.SignedInAsync(username, roleId: roleId);
}
[Fact]
public async Task TheListHasTheBuiltInsAndTheLibrarysOwn()
{
using var client = await fixture.SignedInAsync("snippets-list");
var created = await CreateAsync(client, new SaveSnippetRequest("Snippet List Own", "mine", ScriptEngine.Bash, "echo ${1:hi}"));
var list = await ListAsync(client);
Assert.Equal(BuiltInSnippets.All.Count, list.Count(s => s.BuiltIn));
var own = Assert.Single(list, s => s.Id == created.Id);
Assert.False(own.BuiltIn);
Assert.Equal(ScriptEngine.Bash, own.Language);
Assert.Equal("snippets-list", own.CreatedBy);
Assert.Contains(list, s => s.BuiltIn && s.Language == ScriptEngine.PowerShell);
Assert.Contains(list, s => s.BuiltIn && s.Language == ScriptEngine.Bash);
}
[Fact]
public async Task ASnippetIsCreatedReadUpdatedAndDeletedWithAuditEntries()
{
using var client = await fixture.SignedInAsync("snippets-crud");
var created = await CreateAsync(client, new SaveSnippetRequest(" Snippet Crud ", " desc ", ScriptEngine.PowerShell, "Get-Service ${1:Spooler}"));
Assert.Equal("Snippet Crud", created.Name);
Assert.Equal("desc", created.Description);
var read = await client.GetFromJsonAsync<SnippetDto>(ApiRoutes.For.Snippet(created.Id), JsonDefaults.Options);
Assert.Equal("Get-Service ${1:Spooler}", read!.Content);
var updated = await client.PutAsJsonAsync(ApiRoutes.For.Snippet(created.Id),
new SaveSnippetRequest("Snippet Crud 2", null, ScriptEngine.WindowsPowerShell, "Get-WmiObject Win32_BIOS"), JsonDefaults.Options);
updated.EnsureSuccessStatusCode();
var dto = (await updated.Content.ReadFromJsonAsync<SnippetDto>(JsonDefaults.Options))!;
Assert.Equal(ScriptEngine.WindowsPowerShell, dto.Language);
Assert.Null(dto.Description);
Assert.Equal("snippets-crud", dto.UpdatedBy);
Assert.Equal(HttpStatusCode.NoContent, (await client.DeleteAsync(ApiRoutes.For.Snippet(created.Id))).StatusCode);
Assert.Equal(HttpStatusCode.NotFound, (await client.GetAsync(ApiRoutes.For.Snippet(created.Id))).StatusCode);
var actions = await fixture.WithDbAsync(db => db.AuditEvents.AsNoTracking()
.Where(e => e.Category == AuditCategories.Scripts && e.Actor == "snippets-crud")
.Select(e => e.Action).ToListAsync());
Assert.Contains("snippet-created", actions);
Assert.Contains("snippet-updated", actions);
Assert.Contains("snippet-deleted", actions);
}
[Theory]
[InlineData("", "echo hi")]
[InlineData("Empty Code", " ")]
public async Task ASnippetNeedsANameAndCode(string name, string content)
{
using var client = await fixture.SignedInAsync("snippets-invalid");
var response = await client.PostAsJsonAsync(ApiRoutes.Snippets, new SaveSnippetRequest(name, null, ScriptEngine.Bash, content), JsonDefaults.Options);
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
}
[Fact]
public async Task ABuiltInCanBeReadAndCopiedButNotChangedOrDeleted()
{
using var client = await fixture.SignedInAsync("snippets-builtin");
var builtIn = BuiltInSnippets.All[0];
var read = await client.GetFromJsonAsync<SnippetDto>(ApiRoutes.For.Snippet(builtIn.Id), JsonDefaults.Options);
Assert.True(read!.BuiltIn);
Assert.Equal(builtIn.Content, read.Content);
var put = await client.PutAsJsonAsync(ApiRoutes.For.Snippet(builtIn.Id),
new SaveSnippetRequest("Changed", null, ScriptEngine.PowerShell, "x"), JsonDefaults.Options);
Assert.Equal(HttpStatusCode.Conflict, put.StatusCode);
Assert.Equal(HttpStatusCode.Conflict, (await client.DeleteAsync(ApiRoutes.For.Snippet(builtIn.Id))).StatusCode);
var first = await client.PostAsJsonAsync(ApiRoutes.For.SnippetCopy(builtIn.Id), new CopySnippetRequest(), JsonDefaults.Options);
Assert.Equal(HttpStatusCode.Created, first.StatusCode);
var copy = (await first.Content.ReadFromJsonAsync<SnippetDto>(JsonDefaults.Options))!;
Assert.False(copy.BuiltIn);
Assert.NotEqual(builtIn.Id, copy.Id);
Assert.Equal($"{builtIn.Name} (copy)", copy.Name);
Assert.Equal(builtIn.Content, copy.Content);
Assert.Equal(builtIn.Language, copy.Language);
// A second copy gets the next free name; the copy itself can be changed.
var second = (await (await client.PostAsync(ApiRoutes.For.SnippetCopy(builtIn.Id), null))
.Content.ReadFromJsonAsync<SnippetDto>(JsonDefaults.Options))!;
Assert.Equal($"{builtIn.Name} (copy 2)", second.Name);
(await client.PutAsJsonAsync(ApiRoutes.For.Snippet(copy.Id),
new SaveSnippetRequest("Mine Now", null, copy.Language, copy.Content + "# edited\n"), JsonDefaults.Options)).EnsureSuccessStatusCode();
Assert.Equal(HttpStatusCode.NotFound, (await client.PostAsync(ApiRoutes.For.SnippetCopy(Guid.NewGuid()), null)).StatusCode);
}
[Fact]
public async Task ReadingNeedsScriptsViewAndChangingNeedsManageScripts()
{
using var admin = await fixture.SignedInAsync("snippets-owner");
var own = await CreateAsync(admin, new SaveSnippetRequest("Snippet Perms", null, ScriptEngine.Bash, "uptime"));
using var viewer = await SignedInWithAsync("snippets-viewer", Permissions.ScriptsView);
Assert.NotEmpty(await ListAsync(viewer));
Assert.Equal(HttpStatusCode.Forbidden, (await viewer.PostAsJsonAsync(ApiRoutes.Snippets,
new SaveSnippetRequest("No", null, ScriptEngine.Bash, "uptime"), JsonDefaults.Options)).StatusCode);
Assert.Equal(HttpStatusCode.Forbidden, (await viewer.PutAsJsonAsync(ApiRoutes.For.Snippet(own.Id),
new SaveSnippetRequest("No", null, ScriptEngine.Bash, "uptime"), JsonDefaults.Options)).StatusCode);
Assert.Equal(HttpStatusCode.Forbidden, (await viewer.DeleteAsync(ApiRoutes.For.Snippet(own.Id))).StatusCode);
Assert.Equal(HttpStatusCode.Forbidden, (await viewer.PostAsync(ApiRoutes.For.SnippetCopy(own.Id), null)).StatusCode);
using var nobody = await SignedInWithAsync("snippets-nobody", Permissions.DevicesView);
Assert.Equal(HttpStatusCode.Forbidden, (await nobody.GetAsync(ApiRoutes.Snippets)).StatusCode);
}
[Fact]
public void TheBuiltInsHaveStableUniqueIdsNamesAndWellFormedTabStops()
{
var all = BuiltInSnippets.All;
Assert.InRange(all.Count, 30, 60);
Assert.Equal(all.Count, all.Select(s => s.Id).Distinct().Count());
Assert.Equal(all.Count, all.Select(s => (s.Name, s.Language)).Distinct().Count());
Assert.Equal(BuiltInSnippets.IdOf("ps.try-catch-log"), all.Single(s => s.Name == "Try/Catch with Logging").Id);
foreach (var snippet in all)
{
Assert.True(snippet.BuiltIn);
Assert.False(string.IsNullOrWhiteSpace(snippet.Description), snippet.Name);
Assert.Null(SnippetEndpoints.Validate(new SaveSnippetRequest(snippet.Name, snippet.Description, snippet.Language, snippet.Content)));
Assert.DoesNotContain('\r', snippet.Content);
Assert.DoesNotContain('\t', snippet.Content);
// Every tab stop that opens closes: ${N}, ${N:default} (braces in it balanced) or ${N|a,b|}.
foreach (Match start in TabStop().Matches(snippet.Content))
{
var depth = 1;
var i = start.Index + start.Length;
for (; i < snippet.Content.Length && depth > 0; i++)
{
depth += snippet.Content[i] switch { '{' => 1, '}' => -1, _ => 0 };
}
Assert.True(depth == 0, $"{snippet.Name}: unclosed tab stop at {start.Index}");
}
}
}
[Fact]
public void CopyNamesStayUniqueAndWithinTheLimit()
{
Assert.Equal("A (copy)", SnippetEndpoints.CopyName("A", []));
Assert.Equal("A (copy 3)", SnippetEndpoints.CopyName("A", ["a (copy)", "A (copy 2)"]));
var longName = new string('x', SnippetEndpoints.MaxNameLength);
var copy = SnippetEndpoints.CopyName(longName, []);
Assert.Equal(SnippetEndpoints.MaxNameLength, copy.Length);
Assert.EndsWith(" (copy)", copy);
}
[GeneratedRegex(@"\$\{\d+(?!\d)(?!:[-=+?])")]
private static partial Regex TabStop();
}