0.4.1
release-tag / release-image (push) Successful in 2m4s
release-main / release-images (push) Successful in 3m38s

This commit is contained in:
2026-08-23 00:05:58 +02:00
parent e104e7289f
commit 1b29cbb39d
10 changed files with 137 additions and 24 deletions
+55
View File
@@ -0,0 +1,55 @@
package windowsx
import (
"encoding/json"
"fmt"
"strings"
)
// decodePowerShellJSON extracts the first JSON value from PowerShell stdout.
// Windows PowerShell can occasionally surround redirected output with startup,
// progress, or CLIXML noise. The command runner keeps stderr separate, but this
// parser is deliberately defensive so a valid JSON payload is not discarded
// merely because a host emits an unexpected banner before/after it.
func decodePowerShellJSON(raw string, out any) error {
raw = strings.TrimSpace(strings.TrimPrefix(raw, "\ufeff"))
if raw == "" {
raw = "[]"
}
payload, err := firstJSONValue(raw)
if err != nil {
return fmt.Errorf("no JSON value in PowerShell output: %w (output=%q)", err, raw)
}
payload = strings.TrimSpace(payload)
// Windows PowerShell/ConvertTo-Json may return a single object when only one
// item exists. RemoteApp callers always decode into a slice, so normalize it.
if strings.HasPrefix(payload, "{") {
payload = "[" + payload + "]"
}
if err := json.Unmarshal([]byte(payload), out); err != nil {
return fmt.Errorf("decode PowerShell JSON: %w (json=%q, output=%q)", err, payload, raw)
}
return nil
}
func firstJSONValue(raw string) (string, error) {
var lastErr error
for i := 0; i < len(raw); i++ {
if raw[i] != '[' && raw[i] != '{' {
continue
}
dec := json.NewDecoder(strings.NewReader(raw[i:]))
var msg json.RawMessage
if err := dec.Decode(&msg); err != nil {
lastErr = err
continue
}
return string(msg), nil
}
if lastErr == nil {
lastErr = fmt.Errorf("missing JSON object/array delimiter")
}
return "", lastErr
}
+40
View File
@@ -0,0 +1,40 @@
package windowsx
import (
"testing"
"github.com/example/sessionguard/internal/model"
)
func TestDecodePowerShellJSONCleanArray(t *testing.T) {
var got []model.RemoteAppStatus
if err := decodePowerShellJSON(`[{"alias":"Calc","published":true}]`, &got); err != nil {
t.Fatal(err)
}
if len(got) != 1 || got[0].Alias != "Calc" || !got[0].Published {
t.Fatalf("unexpected result: %#v", got)
}
}
func TestDecodePowerShellJSONSingleObject(t *testing.T) {
var got []model.RemoteAppStatus
if err := decodePowerShellJSON(`{"alias":"Calc","published":true}`, &got); err != nil {
t.Fatal(err)
}
if len(got) != 1 || got[0].Alias != "Calc" {
t.Fatalf("unexpected result: %#v", got)
}
}
func TestDecodePowerShellJSONIgnoresCLIXMLNoise(t *testing.T) {
raw := "#< CLIXML\r\n" +
`[{"resource_id":"281750fc5851c7fd","alias":"Rechner","display_name":"Rechner","path":"C:\\Windows\\system32\\win32calc.exe","path_exists":true,"published":true,"managed":true,"in_sync":true}]` +
"\r\nSystem.Management.Automation.PSCustomObjectSystem.Object1Module werden fuer erstmalige Verwendung vorbereitet."
var got []model.RemoteAppStatus
if err := decodePowerShellJSON(raw, &got); err != nil {
t.Fatal(err)
}
if len(got) != 1 || got[0].Alias != "Rechner" || got[0].Path != `C:\Windows\system32\win32calc.exe` {
t.Fatalf("unexpected result: %#v", got)
}
}
+21 -16
View File
@@ -3,6 +3,7 @@
package windowsx
import (
"bytes"
"encoding/base64"
"encoding/json"
"fmt"
@@ -180,29 +181,33 @@ ConvertTo-Json -InputObject @($results) -Compress -Depth 5`, payload)
}
func runPowerShellJSON(script string, out any) error {
encoded := encodePowerShell(script)
// Suppress PowerShell's auxiliary streams. On Windows PowerShell 5.1 these
// can otherwise be serialized as "#< CLIXML" when handles are redirected.
// stderr is also kept separate from stdout so progress/information records
// can never corrupt the JSON protocol used between PowerShell and the agent.
preamble := `$ProgressPreference='SilentlyContinue'
$InformationPreference='SilentlyContinue'
$VerbosePreference='SilentlyContinue'
$DebugPreference='SilentlyContinue'
$WarningPreference='SilentlyContinue'
try { [Console]::OutputEncoding = New-Object System.Text.UTF8Encoding($false) } catch {}
`
encoded := encodePowerShell(preamble + script)
cmd := exec.Command("powershell.exe", "-NoLogo", "-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-EncodedCommand", encoded)
b, err := cmd.CombinedOutput()
var stderr bytes.Buffer
cmd.Stderr = &stderr
b, err := cmd.Output()
if err != nil {
msg := strings.TrimSpace(string(b))
msg := strings.TrimSpace(stderr.String())
if msg == "" {
msg = strings.TrimSpace(string(b))
}
if msg == "" {
msg = err.Error()
}
return fmt.Errorf("PowerShell: %s", msg)
}
raw := strings.TrimSpace(string(b))
if raw == "" {
raw = "[]"
}
// ConvertTo-Json emits an object instead of an array when there is exactly
// one item on older Windows PowerShell. Accept both forms.
if strings.HasPrefix(raw, "{") {
raw = "[" + raw + "]"
}
if err := json.Unmarshal([]byte(raw), out); err != nil {
return fmt.Errorf("decode PowerShell JSON: %w (output=%q)", err, raw)
}
return nil
return decodePowerShellJSON(string(b), out)
}
func encodePowerShell(script string) string {