From fd498f51c33d33e76029c36ea3b3b0cae9846015 Mon Sep 17 00:00:00 2001 From: Gordon Breuer Date: Fri, 23 Oct 2026 19:57:03 +0200 Subject: [PATCH 01/26] feat: implement first Spectre CLI, USB and phone output, and Copilot host --- .github/dependabot.yml | 6 +- .github/workflows/dotnet-ci.yml | 23 +++ Directory.Build.props | 9 + NOTICE.md | 14 ++ README.md | 36 +++- SidePulse.NET.slnx | 9 + docs/wiki/Getting-Started.md | 100 ++++++++++ docs/wiki/Home.md | 2 + docs/wiki/_Sidebar.md | 2 + global.json | 3 + scripts/cli_smoke.py | 64 +++++++ src/SidePulse.Cli/Commands.cs | 152 +++++++++++++++ src/SidePulse.Cli/Hooks.cs | 185 +++++++++++++++++++ src/SidePulse.Cli/Program.cs | 24 +++ src/SidePulse.Cli/SidePulse.Cli.csproj | 14 ++ src/SidePulse.Core/DeviceTransport.cs | 56 ++++++ src/SidePulse.Core/LedProgram.cs | 47 +++++ src/SidePulse.Core/PhoneBridge.cs | 28 +++ src/SidePulse.Core/Sessions.cs | 70 +++++++ src/SidePulse.Core/SidePulse.Core.csproj | 1 + tests/SidePulse.Tests/CoreTests.cs | 101 ++++++++++ tests/SidePulse.Tests/SidePulse.Tests.csproj | 9 + third-party/spectre.console/LICENSE.md | 21 +++ 23 files changed, 965 insertions(+), 11 deletions(-) create mode 100644 Directory.Build.props create mode 100644 SidePulse.NET.slnx create mode 100644 docs/wiki/Getting-Started.md create mode 100644 global.json create mode 100644 scripts/cli_smoke.py create mode 100644 src/SidePulse.Cli/Commands.cs create mode 100644 src/SidePulse.Cli/Hooks.cs create mode 100644 src/SidePulse.Cli/Program.cs create mode 100644 src/SidePulse.Cli/SidePulse.Cli.csproj create mode 100644 src/SidePulse.Core/DeviceTransport.cs create mode 100644 src/SidePulse.Core/LedProgram.cs create mode 100644 src/SidePulse.Core/PhoneBridge.cs create mode 100644 src/SidePulse.Core/Sessions.cs create mode 100644 src/SidePulse.Core/SidePulse.Core.csproj create mode 100644 tests/SidePulse.Tests/CoreTests.cs create mode 100644 tests/SidePulse.Tests/SidePulse.Tests.csproj create mode 100644 third-party/spectre.console/LICENSE.md diff --git a/.github/dependabot.yml b/.github/dependabot.yml index c365cd1..e9c3609 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -5,4 +5,8 @@ updates: schedule: interval: weekly open-pull-requests-limit: 5 -# Add NuGet updates when the first project and package manifests exist. + - package-ecosystem: nuget + directory: / + schedule: + interval: weekly + open-pull-requests-limit: 5 diff --git a/.github/workflows/dotnet-ci.yml b/.github/workflows/dotnet-ci.yml index ff7ee3e..1f21f2b 100644 --- a/.github/workflows/dotnet-ci.yml +++ b/.github/workflows/dotnet-ci.yml @@ -64,3 +64,26 @@ jobs: SOLUTION: ${{ needs.detect.outputs.solution }} shell: pwsh run: dotnet test $env:SOLUTION --configuration Release --no-build + - name: Exercise CLI and local host with simulated hardware + shell: pwsh + run: | + $binary = if ($IsWindows) { 'sidepulse-net.exe' } else { 'sidepulse-net' } + python scripts/cli_smoke.py "src/SidePulse.Cli/bin/Release/net10.0/$binary" + - name: Publish self-contained Windows preview + if: runner.os == 'Windows' + shell: pwsh + run: | + dotnet publish src/SidePulse.Cli -c Release -r win-x64 --self-contained true -o artifacts/win-x64 + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + Copy-Item LICENSE,NOTICE.md artifacts/win-x64 + Copy-Item -Recurse third-party artifacts/win-x64 + Copy-Item docs/wiki/Getting-Started.md artifacts/win-x64 + python scripts/cli_smoke.py artifacts/win-x64/sidepulse-net.exe + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + - name: Upload Windows preview + if: runner.os == 'Windows' + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4 + with: + name: sidepulse-net-win-x64-preview + path: artifacts/win-x64/ + retention-days: 14 diff --git a/Directory.Build.props b/Directory.Build.props new file mode 100644 index 0000000..ed9620b --- /dev/null +++ b/Directory.Build.props @@ -0,0 +1,9 @@ + + + net10.0 + enable + enable + true + true + + diff --git a/NOTICE.md b/NOTICE.md index 9c639fc..ddec976 100644 --- a/NOTICE.md +++ b/NOTICE.md @@ -19,3 +19,17 @@ Peter Kuhar or InteliWEAR. No original branding artwork is included. Spectre.Console and Spectre.Console.Cli are planned dependencies. Their licenses must be recorded with other distributed third-party components when dependencies are introduced. No Spectre package is included in this planning commit. + +## First implementation preview + +`src/SidePulse.Core/LedProgram.cs` adapts status animation profiles from the Python +Windows companion and the upstream LEDS.LED protocol. `DeviceTransport.cs` follows +the upstream virtual-file write contract and `PhoneBridge.cs` follows the APNS +bridge payload/channel contract. Reference: upstream revision above, files +`LEDS_FORMAT.md`, `src/sidepulse/device_writer.py` and `src/sidepulse/links.py`. +The retained upstream MIT notice applies to these adapted portions. + +Spectre.Console, Spectre.Console.Cli and Spectre.Console.Ansi 0.57.2 are MIT +licensed dependencies, copyright Patrik Svensson, Phil Scott, Nils Andresen, Cédric Luthi and contributors. +Their repository license is retained in `third-party/spectre.console/LICENSE.md` and included in CI distribution artifacts. +Test packages are development dependencies and are not part of the application. diff --git a/README.md b/README.md index b017837..49c0362 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,9 @@ An unofficial .NET companion for SidePulse, with a Spectre.Console terminal interface. -**Status: concept and project preparation. No C# application, downloads or feature-complete port exist yet.** +**Status: first C# implementation preview. Feature parity and hardware validation are still in progress.** + +Start with [Getting started](docs/wiki/Getting-Started.md) for build, USB, phone delivery and Copilot CLI instructions. SidePulse.NET will bring the SidePulse workflow to a native Windows application: pair a phone or connect a USB device, enable an agent integration, and see when @@ -45,23 +47,37 @@ The reference baseline is upstream commit [`ffb1d3c2f3eed3b7e80e32d7876a7e1d67bd5dfb`](https://github.com/inteliwear/sidepulse/commit/ffb1d3c2f3eed3b7e80e32d7876a7e1d67bd5dfb), checked on 2026-10-23. Upstream is MIT licensed. See [NOTICE.md](NOTICE.md) and the retained [upstream license](third-party/inteliwear-sidepulse/LICENSE). -No upstream application code or animation assets have been copied into this initial setup. +Status LED profiles and protocol behavior are adapted from this baseline; see the provenance notice. ## Development -Application implementation has not started. Review the concept and compatibility -inventory before creating the solution. Future commands shown in the wiki are -proposals, not currently executable instructions. +```shell +dotnet build -c Release +dotnet test -c Release +dotnet run --project src/SidePulse.Cli -- dashboard +``` + + +The solution contains a portable core, a Spectre.Console CLI and behavioral tests. +Implemented commands: `devices`, `state`, `write`, `dashboard`, `host` and +`hook-config`. Use `--help` for details and `--dry-run` before sending a program. +The command name `sidepulse-net` coexists with the existing Python port. + +QR pairing, protected token storage, a persistent service, full DSL validation, +other upstream integrations and a signed installer remain planned. The wiki's +concept pages describe the intended complete product; the getting-started page +records what is implemented now. -The initial repository contains documentation checks, conditional .NET CI, -optional wiki publication, Dependabot configuration, issue templates and a -backlog of [11 planning issues](https://github.com/Anheledir/SidePulse.NET/issues). -It does not claim a passing application build or test suite. +CI builds and tests Windows, Linux and macOS; Windows CI produces a self-contained +preview artifact. Wiki publishing uses the built-in Actions token. A weekly +upstream check opens or updates a review issue when the original repository +changes. See [automation setup](docs/wiki/Project-Setup.md). -Run the current checks with Python 3: +Documentation checks: ```shell python scripts/check_docs.py +python -m unittest discover -s scripts/tests -v ``` Contributions: [CONTRIBUTING.md](CONTRIBUTING.md). License: [MIT](LICENSE). diff --git a/SidePulse.NET.slnx b/SidePulse.NET.slnx new file mode 100644 index 0000000..3b127e1 --- /dev/null +++ b/SidePulse.NET.slnx @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/docs/wiki/Getting-Started.md b/docs/wiki/Getting-Started.md new file mode 100644 index 0000000..1554f7d --- /dev/null +++ b/docs/wiki/Getting-Started.md @@ -0,0 +1,100 @@ +# Getting started with the implementation preview + +The first implementation is an alpha preview. USB discovery/writes, status profiles, +raw programs, silent iPhone bridge delivery with an existing APNS token, session +aggregation and a foreground Copilot CLI host are implemented. QR pairing, protected +credential storage, background-service installation, full LED grammar validation, +animation rendering, migration and other agent integrations remain planned. + +## Build and run + +Install the .NET 10 SDK, then: + +```shell +dotnet build -c Release +dotnet test -c Release +dotnet run --project src/SidePulse.Cli -- dashboard +dotnet run --project src/SidePulse.Cli -- state working --dry-run --json +``` + +Publish a Windows application without a Python or .NET runtime requirement: + +```shell +dotnet publish src/SidePulse.Cli -c Release -r win-x64 --self-contained true -o artifacts/win-x64 +``` + +Run `artifacts/win-x64/sidepulse-net.exe`. The CI Windows job also publishes a +self-contained folder as an Actions artifact. This is a preview build, not a signed +installer or stable release. + +## USB device + +```powershell +sidepulse-net devices --json +sidepulse-net state working --device E:\ +sidepulse-net write 'off\n#ff9900 1.6s pulse\nrepeat' --escapes --device E:\ +``` + +An explicit directory must contain `LEDS.LED`; the tool will not create device files +on unrelated volumes. With no target, exactly one discovered device is selected. +Only one writer should control a device. Physical device behavior still needs +Windows hardware verification. Validation checks the 512-byte/20-line envelope; +the firmware remains responsible for LED syntax validation. + +## Phone delivery + +Set `SIDEPULSE_TOKEN` in the current process environment to an existing iPhone push +token from the SidePulse app. Keep it out of scripts, command history, source +control and screenshots. The preview does not read or modify the Python port's +configuration, and does not persist tokens. + +```powershell +sidepulse-net state working --token-env SIDEPULSE_TOKEN +sidepulse-net host --token-env SIDEPULSE_TOKEN +``` + +The bridge uses HTTPS and silent APNS payloads with unique event IDs. An HTTP +success is bridge acceptance, not proof of delivery to the hardware. Android, +custom bridge servers, phone registration and QR pairing are not implemented yet. + +## Copilot CLI on Windows + +Start the host in a terminal, choosing either USB or the phone environment token: + +```powershell +sidepulse-net host --device E:\ +``` + +Create the hook directory if needed, then generate a new, separate hook file: + +```powershell +New-Item -ItemType Directory -Force "$env:USERPROFILE\.copilot\hooks" | Out-Null +sidepulse-net hook-config --exe C:\Tools\SidePulse.NET\sidepulse-net.exe --output "$env:USERPROFILE\.copilot\hooks\sidepulse-net.json" +``` + +If `COPILOT_HOME` is set, use its `hooks` directory instead. Existing files are never +overwritten. Restart Copilot CLI after installation. PowerShell 7 is required for +Copilot's Windows shell hooks. Remove this file and restart Copilot to uninstall. +Avoid running the Python and C# hook integrations for the same output simultaneously. + +Hooks forward stdin to a current-user-only named pipe. They have a short connection +budget, emit no output and always return zero for runtime input/connection failures. +The generated PowerShell wrapper also returns zero if the executable is unavailable. +No prompt, tool arguments or transcript content is forwarded to the host, persisted +or sent to the bridge. The host accepts bounded messages and sessions; network +output runs separately through a latest-state queue. Rapid intermediate states may +be coalesced. If the host is absent or overloaded, hook events may be dropped. +Start the host before Copilot. Restarted hosts start unknown and do not replay old +sessions. Crashed/missing sessions are not inferred complete; restart the host to +clear stale state. Stopping the host leaves the last LED program on the device. + +Waiting takes precedence over working, then errors, completed turns and idle. +Completion is inferred only from `agentStop` with `stopReason=end_turn`, never a +subagent/background completion or timeout. The host UI appends session tables on +events; `--plain` provides simple lines and `--json` provides structured snapshots. +The standalone `dashboard` is a static overview in this preview. + +The event mapping follows the [GitHub Copilot hook reference](https://docs.github.com/en/copilot/reference/hooks-reference). +Actual Copilot/Windows and phone/hardware validation remain separate from unit +and simulated transport tests. Keep the working Python installation available +until this preview is validated on your setup. diff --git a/docs/wiki/Home.md b/docs/wiki/Home.md index b9c73f5..5e45f0c 100644 --- a/docs/wiki/Home.md +++ b/docs/wiki/Home.md @@ -1,3 +1,5 @@ +> Implementation preview: [[Getting-Started]] lists working commands and current limitations. Other pages describe the complete planned product. + # SidePulse.NET **An unofficial .NET companion for SidePulse.** diff --git a/docs/wiki/_Sidebar.md b/docs/wiki/_Sidebar.md index 0b57584..410f1ba 100644 --- a/docs/wiki/_Sidebar.md +++ b/docs/wiki/_Sidebar.md @@ -11,3 +11,5 @@ - [[Roadmap]] - [[Project-Setup]] - [[Upstream-and-Licensing]] + +- [[Getting started|Getting-Started]] diff --git a/global.json b/global.json new file mode 100644 index 0000000..ebd0c5d --- /dev/null +++ b/global.json @@ -0,0 +1,3 @@ +{ + "sdk": { "version": "10.0.100", "rollForward": "latestFeature" } +} diff --git a/scripts/cli_smoke.py b/scripts/cli_smoke.py new file mode 100644 index 0000000..8782439 --- /dev/null +++ b/scripts/cli_smoke.py @@ -0,0 +1,64 @@ +"""Exercise published CLI, local hooks and a simulated device without hardware.""" +import json +import os +from pathlib import Path +import subprocess +import sys +import tempfile +import time + + +def main(): + exe = str(Path(sys.argv[1]).resolve()) + + def run(*args, input=None): + result = subprocess.run([exe, *args], input=input, text=True, capture_output=True, timeout=10) + assert result.returncode == 0, (args, result.stdout, result.stderr) + return result + + preview = json.loads(run('state', 'working', '--dry-run', '--json').stdout) + assert preview['program'] == 'off\n#00e5ff 1.6s pulse\nrepeat' + malformed = run('hook', 'preToolUse', input='invalid') + assert not malformed.stdout and not malformed.stderr + disconnected = run('hook', 'agentStop', input=json.dumps({'sessionId': 'a', 'timestamp': 1, 'stopReason': 'end_turn'})) + assert not disconnected.stdout and not disconnected.stderr + with tempfile.TemporaryDirectory() as directory: + target = Path(directory) / 'LEDS.LED' + target.write_text('off') + run('state', 'waiting', '--device', directory) + assert '#ff9900' in target.read_text() + config = Path(directory) / 'hooks.json' + run('hook-config', '--exe', exe, '--output', str(config)) + hooks = json.loads(config.read_text())['hooks'] + assert 'permissionRequest' not in hooks and 'subagentStop' not in hooks + assert 'exit 0' in hooks['preToolUse'][0]['powershell'] + refused = subprocess.run([exe, 'hook-config', '--exe', exe, '--output', str(config)], capture_output=True) + assert refused.returncode != 0 + with open(Path(directory) / 'host.log', 'w') as log: + host = subprocess.Popen([exe, 'host', '--device', directory, '--plain'], stdout=log, stderr=log) + try: + # Repeated idempotent input accommodates host startup without a timing-only assertion. + for attempt in range(30): + assert host.poll() is None, 'Host exited: ' + (Path(directory) / 'host.log').read_text() + result = run('hook', 'userPromptSubmitted', input=json.dumps({'sessionId': 'smoke', 'timestamp': attempt + 1})) + assert not result.stdout and not result.stderr + if '#00e5ff' in target.read_text(): + break + time.sleep(0.1) + else: + raise AssertionError('Host did not deliver the working state') + run('hook', 'agentStop', input=json.dumps({'sessionId': 'smoke', 'timestamp': 100, 'stopReason': 'end_turn'})) + for _ in range(30): + if '#00ff66' in target.read_text(): + break + time.sleep(0.1) + else: + raise AssertionError('Host did not deliver the completed state') + finally: + host.terminate() + host.wait(timeout=10) + print('CLI, hook isolation, configuration and host/device smoke checks passed.') + + +if __name__ == '__main__': + main() diff --git a/src/SidePulse.Cli/Commands.cs b/src/SidePulse.Cli/Commands.cs new file mode 100644 index 0000000..b462250 --- /dev/null +++ b/src/SidePulse.Cli/Commands.cs @@ -0,0 +1,152 @@ +using System.ComponentModel; +using System.Text.Json; +using System.Text.Json.Serialization; +using SidePulse.Core; +using Spectre.Console; +using Spectre.Console.Cli; + +namespace SidePulse.Cli; + +public static class Output +{ + public static readonly JsonSerializerOptions Json = new() { WriteIndented = true, Converters = { new JsonStringEnumConverter() } }; + public static void Print(object value) => Console.WriteLine(JsonSerializer.Serialize(value, Json)); + public static string Color(AgentState state) => state switch + { + AgentState.Working => "cyan", AgentState.Waiting => "orange1", AgentState.Done => "green", + AgentState.Error => "red", _ => "grey" + }; +} + +public class DevicesSettings : CommandSettings +{ + [CommandOption("--json")] + [Description("Emit structured output for scripts.")] + public bool Json { get; init; } +} + +public sealed class DevicesCommand : Command +{ + public override int Execute(CommandContext context, DevicesSettings settings, CancellationToken cancellationToken) + { + var devices = DeviceTransport.Discover(); + if (settings.Json) Output.Print(devices); + else + { + var table = new Table().Border(TableBorder.Rounded).AddColumn("Device").AddColumn("LEDS.LED"); + foreach (var device in devices) table.AddRow(Markup.Escape(device.Label), Markup.Escape(device.Path)); + AnsiConsole.Write(table); + if (devices.Count == 0) AnsiConsole.WriteLine("No mounted devices found. An iPhone-connected device uses the phone bridge."); + } + return 0; + } +} + +public class TargetSettings : CommandSettings +{ + [CommandOption("--device ")] + [Description("Mounted directory or existing LEDS.LED path. Auto-selects a single discovered device.")] + public string? Device { get; init; } + [CommandOption("--token-env ")] + [Description("Environment variable holding an iPhone push token. Selects phone delivery.")] + public string? TokenEnvironment { get; init; } + [CommandOption("--dry-run")] + [Description("Preview the program without writing or sending anything.")] + public bool DryRun { get; init; } + [CommandOption("--json")] + public bool Json { get; init; } + + public override ValidationResult Validate() => Device is not null && TokenEnvironment is not null + ? ValidationResult.Error("Choose either --device or --token-env.") : ValidationResult.Success(); +} + +public static class Delivery +{ + public static async Task Send(TargetSettings settings, LedProgram program, CancellationToken cancellationToken) + { + if (settings.DryRun) return; + if (settings.TokenEnvironment is { } variable) + { + var token = Environment.GetEnvironmentVariable(variable); + if (string.IsNullOrWhiteSpace(token)) throw new ArgumentException("The selected token environment variable is empty."); + using var client = new HttpClient { Timeout = TimeSpan.FromSeconds(10) }; + await new PhoneBridge(client).SendAsync(token, program, cancellationToken); + } + else DeviceTransport.Write(DeviceTransport.Resolve(settings.Device), program); + } + public static void Receipt(TargetSettings settings, LedProgram program) + { + if (settings.Json) Output.Print(new { dryRun = settings.DryRun, bytes = program.ByteCount, lines = program.LineCount, program = program.Text }); + else if (settings.DryRun) AnsiConsole.Write(new Panel(new Text(program.Text)).Header("LED preview").Border(BoxBorder.Rounded)); + else AnsiConsole.MarkupLine("[green]Sent.[/]"); + } +} + +public sealed class StateSettings : TargetSettings +{ + [CommandArgument(0, "")] + public AgentState State { get; init; } + public override ValidationResult Validate() + { + var target = base.Validate(); + if (!target.Successful) return target; + return Enum.IsDefined(State) ? ValidationResult.Success() : ValidationResult.Error("Unknown agent state."); + } +} +public sealed class StateCommand : AsyncCommand +{ + public override async Task ExecuteAsync(CommandContext context, StateSettings settings, CancellationToken cancellationToken) + { + var program = LedProgram.ForState(settings.State); + await Delivery.Send(settings, program, cancellationToken); + Delivery.Receipt(settings, program); + return 0; + } +} +public sealed class WriteSettings : TargetSettings +{ + [CommandArgument(0, "[PROGRAM]")] + public string? Program { get; init; } + [CommandOption("--file ")] + public string? File { get; init; } + [CommandOption("--escapes")] + [Description("Decode literal backslash-n, backslash-r, backslash-t and backslash-backslash.")] + public bool Escapes { get; init; } + public override ValidationResult Validate() + { + var target = base.Validate(); + if (!target.Successful) return target; + return (Program is null) == (File is null) ? ValidationResult.Error("Supply one program argument or --file.") : ValidationResult.Success(); + } +} +public sealed class WriteCommand : AsyncCommand +{ + public override async Task ExecuteAsync(CommandContext context, WriteSettings settings, CancellationToken cancellationToken) + { + var text = settings.File is { } file ? await System.IO.File.ReadAllTextAsync(file, cancellationToken) : settings.Program!; + var program = new LedProgram(settings.Escapes ? LedProgram.DecodeEscapes(text) : text); + await Delivery.Send(settings, program, cancellationToken); + Delivery.Receipt(settings, program); + return 0; + } +} +public sealed class DashboardCommand : Command +{ + public override int Execute(CommandContext context, DevicesSettings settings, CancellationToken cancellationToken) + { + if (settings.Json) { Output.Print(new { devices = DeviceTransport.Discover(), profiles = Enum.GetNames() }); return 0; } + AnsiConsole.Write(new Rule("[cyan]SidePulse[/][white].NET[/]").LeftJustified()); + AnsiConsole.MarkupLine("[grey]Small signals. Clear status.[/]\n"); + new DevicesCommand().Execute(context, settings, cancellationToken); + var profiles = new Table().Border(TableBorder.Rounded).AddColumn("Status").AddColumn("Signal"); + foreach (var state in Enum.GetValues()) + profiles.AddRow($"[{Output.Color(state)}]{state}[/]", state switch + { + AgentState.Working => "Cyan pulse", AgentState.Waiting => "Amber pulse", + AgentState.Done => "Green", AgentState.Error => "Red pulse", _ => "Off" + }); + AnsiConsole.Write(profiles); + AnsiConsole.MarkupLine("[grey]Use host for live Copilot sessions. Done means the turn ended.[/]"); + return 0; + } +} diff --git a/src/SidePulse.Cli/Hooks.cs b/src/SidePulse.Cli/Hooks.cs new file mode 100644 index 0000000..5f23d89 --- /dev/null +++ b/src/SidePulse.Cli/Hooks.cs @@ -0,0 +1,185 @@ +using System.ComponentModel; +using System.IO.Pipes; +using System.Security.Cryptography; +using System.Text; +using System.Text.Json; +using System.Threading.Channels; +using SidePulse.Core; +using Spectre.Console; +using Spectre.Console.Cli; + +namespace SidePulse.Cli; + +public static class LocalPipe +{ + // Per-user namespace plus OS-enforced current-user access on server and client. + public static string Name => "sidepulse-net-" + Convert.ToHexString(SHA256.HashData( + Encoding.UTF8.GetBytes(Environment.UserDomainName + "\\" + Environment.UserName)))[..20]; + public const int MaximumMessageBytes = 16384; +} + +public sealed class HookSettings : CommandSettings +{ + [CommandArgument(0, "")] + public string Event { get; init; } = ""; +} +public sealed class HookCommand : AsyncCommand +{ + public override async Task ExecuteAsync(CommandContext context, HookSettings settings, CancellationToken cancellationToken) + { + // Every path is silent and returns zero. Hooks must never change Copilot permission decisions. + try + { + using var timeout = new CancellationTokenSource(TimeSpan.FromMilliseconds(600)); + var buffer = new char[LocalPipe.MaximumMessageBytes + 1]; + var length = 0; + while (length < buffer.Length) + { + var read = await Console.In.ReadAsync(buffer.AsMemory(length), timeout.Token); + if (read == 0) break; + length += read; + } + if (length > LocalPipe.MaximumMessageBytes) return 0; + var item = CopilotEvents.Parse(settings.Event, new string(buffer, 0, length)); + if (item is null) return 0; + var bytes = JsonSerializer.SerializeToUtf8Bytes(item); + if (bytes.Length > LocalPipe.MaximumMessageBytes) return 0; + using var pipe = new NamedPipeClientStream(".", LocalPipe.Name, PipeDirection.Out, + PipeOptions.Asynchronous | PipeOptions.CurrentUserOnly); + await pipe.ConnectAsync(timeout.Token); + await pipe.WriteAsync(bytes, timeout.Token); + await pipe.FlushAsync(timeout.Token); + } + catch (Exception) { /* A missing host or invalid hook input must not break Copilot. */ } + return 0; + } +} +public sealed class HostSettings : TargetSettings +{ + [CommandOption("--plain")] + [Description("Write plain state changes instead of terminal panels.")] + public bool Plain { get; init; } +} +public sealed class HostCommand : AsyncCommand +{ + public override async Task ExecuteAsync(CommandContext context, HostSettings settings, CancellationToken cancellationToken) + { + using var shutdown = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + ConsoleCancelEventHandler cancel = (_, args) => { args.Cancel = true; shutdown.Cancel(); }; + Console.CancelKeyPress += cancel; + var sessions = new Sessions(); + AgentState? queued = null; + var outputs = Channel.CreateBounded(new BoundedChannelOptions(1) + { + SingleReader = true, SingleWriter = true, FullMode = BoundedChannelFullMode.DropOldest + }); + var delivery = Task.Run(async () => + { + try + { + await foreach (var program in outputs.Reader.ReadAllAsync(shutdown.Token)) + { + try { await Delivery.Send(settings, program, shutdown.Token); } + catch (Exception ex) when (ex is IOException or ArgumentException or OperationCanceledException) + { + Console.Error.WriteLine("Output unavailable; check the device, token environment variable or network."); + } + } + } + catch (OperationCanceledException) when (shutdown.IsCancellationRequested) { } + }, CancellationToken.None); + if (!settings.Json) AnsiConsole.WriteLine("SidePulse.NET host | Ctrl+C to stop | session state starts unknown"); + try + { + // FirstPipeInstance prevents competing hosts from accepting alternate events. + using var pipe = new NamedPipeServerStream(LocalPipe.Name, PipeDirection.In, 1, + PipeTransmissionMode.Byte, PipeOptions.Asynchronous | PipeOptions.CurrentUserOnly | PipeOptions.FirstPipeInstance); + while (!shutdown.IsCancellationRequested) + { + await pipe.WaitForConnectionAsync(shutdown.Token); + try + { + using var deadline = CancellationTokenSource.CreateLinkedTokenSource(shutdown.Token); + deadline.CancelAfter(TimeSpan.FromSeconds(1)); + using var message = new MemoryStream(); + var buffer = new byte[4096]; + while (message.Length <= LocalPipe.MaximumMessageBytes) + { + var count = await pipe.ReadAsync(buffer, deadline.Token); + if (count == 0) break; + message.Write(buffer, 0, count); + } + if (message.Length > LocalPipe.MaximumMessageBytes) continue; + var item = JsonSerializer.Deserialize(message.ToArray()); + if (item is null || !Enum.IsDefined(item.State) || !sessions.Apply(item)) continue; + var state = sessions.State; + if (settings.Json) Output.Print(new { state, sessions = sessions.Snapshot }); + else if (settings.Plain || Console.IsOutputRedirected) Console.WriteLine($"{DateTimeOffset.Now:HH:mm:ss} {state} ({sessions.Snapshot.Count} sessions)"); + else + { + var table = new Table().Border(TableBorder.Rounded).AddColumn("Session").AddColumn("Status"); + foreach (var session in sessions.Snapshot) + table.AddRow(Markup.Escape(session.Id), $"[{Output.Color(session.State)}]{session.State}[/]"); + AnsiConsole.Write(table); + } + // Delivery runs separately so bridge latency cannot block pipe acceptance. + // The bounded queue keeps the latest state during slow network delivery. + // Re-enqueue repeated states to recover after a failed delivery. + if (state != queued || !settings.DryRun) + { + outputs.Writer.TryWrite(LedProgram.ForState(state)); + queued = state; + } + } + catch (Exception ex) when (ex is JsonException or IOException or OperationCanceledException) { } + finally { pipe.Disconnect(); } + } + } + catch (OperationCanceledException) when (shutdown.IsCancellationRequested) { } + finally + { + shutdown.Cancel(); + outputs.Writer.TryComplete(); + await delivery; + Console.CancelKeyPress -= cancel; + } + return 0; + } +} +public sealed class HookConfigSettings : CommandSettings +{ + [CommandOption("--exe ")] + [Description("Absolute path to a published sidepulse-net executable.")] + public string Executable { get; init; } = Environment.ProcessPath ?? "sidepulse-net"; + [CommandOption("--output ")] + [Description("Create a NEW hook file. Existing files are never overwritten. Otherwise prints JSON.")] + public string? OutputPath { get; init; } +} +public sealed class HookConfigCommand : Command +{ + public override int Execute(CommandContext context, HookConfigSettings settings, CancellationToken cancellationToken) + { + var exe = Path.GetFullPath(settings.Executable); + if (!File.Exists(exe) || !Path.GetFileNameWithoutExtension(exe).Equals("sidepulse-net", StringComparison.OrdinalIgnoreCase)) + throw new ArgumentException("Use --exe with the path of a published sidepulse-net executable."); + var hooks = new Dictionary(); + foreach (var name in new[] { "sessionStart", "userPromptSubmitted", "preToolUse", "postToolUse", "agentStop", "errorOccurred", "postToolUseFailure", "sessionEnd", "notification" }) + { + var command = "$ErrorActionPreference = 'SilentlyContinue'; try { $input | & '" + exe.Replace("'", "''") + + "' hook " + name + " | Out-Null } catch {}; exit 0"; + var entry = new Dictionary { ["type"] = "command", ["powershell"] = command, ["timeoutSec"] = 2 }; + if (name == "notification") entry["matcher"] = "permission_prompt|elicitation_dialog"; + hooks[name] = new[] { entry }; + } + var json = JsonSerializer.Serialize(new { version = 1, hooks }, Output.Json) + Environment.NewLine; + if (settings.OutputPath is { } path) + { + using var file = new FileStream(path, FileMode.CreateNew, FileAccess.Write); + using var writer = new StreamWriter(file, new UTF8Encoding(false)); + writer.Write(json); + AnsiConsole.WriteLine("Created hook configuration. Restart Copilot CLI after installing it in your hooks directory."); + } + else Console.Write(json); + return 0; + } +} diff --git a/src/SidePulse.Cli/Program.cs b/src/SidePulse.Cli/Program.cs new file mode 100644 index 0000000..32d13dd --- /dev/null +++ b/src/SidePulse.Cli/Program.cs @@ -0,0 +1,24 @@ +using Spectre.Console; +using Spectre.Console.Cli; +using SidePulse.Cli; + +var app = new CommandApp(); +app.Configure(config => +{ + config.SetApplicationName("sidepulse-net"); + config.SetApplicationVersion("0.1.0-alpha.1"); + config.AddCommand("devices").WithDescription("List mounted SidePulse devices."); + config.AddCommand("state").WithDescription("Display an agent state on USB or iPhone."); + config.AddCommand("write").WithDescription("Send a raw LED program with firmware envelope checks."); + config.AddCommand("dashboard").WithDescription("Show devices and built-in status profiles."); + config.AddCommand("host").WithDescription("Run the local Copilot event listener (foreground)."); + config.AddCommand("hook").IsHidden(); + config.AddCommand("hook-config").WithDescription("Generate opt-in Copilot CLI hook configuration."); + config.SetExceptionHandler((exception, _) => + { + // Credential-bearing HTTP exception details are never displayed. + AnsiConsole.MarkupLine("[red]Error:[/] " + Markup.Escape(exception.Message)); + return 1; + }); +}); +return app.Run(args); diff --git a/src/SidePulse.Cli/SidePulse.Cli.csproj b/src/SidePulse.Cli/SidePulse.Cli.csproj new file mode 100644 index 0000000..39c06d7 --- /dev/null +++ b/src/SidePulse.Cli/SidePulse.Cli.csproj @@ -0,0 +1,14 @@ + + + Exe + sidepulse-net + 0.1.0-alpha.1 + Unofficial SidePulse companion + MIT + + + + + + + diff --git a/src/SidePulse.Core/DeviceTransport.cs b/src/SidePulse.Core/DeviceTransport.cs new file mode 100644 index 0000000..632b154 --- /dev/null +++ b/src/SidePulse.Core/DeviceTransport.cs @@ -0,0 +1,56 @@ +using System.Text; + +namespace SidePulse.Core; + +public sealed record Device(string Path, string Label); + +public static class DeviceTransport +{ + public static IReadOnlyList Discover() + { + var result = new List(); + foreach (var drive in DriveInfo.GetDrives()) + { + try + { + if (!drive.IsReady) continue; + var path = System.IO.Path.Combine(drive.RootDirectory.FullName, "LEDS.LED"); + if (File.Exists(path)) result.Add(new Device(path, drive.VolumeLabel)); + } + catch (IOException) { } + catch (UnauthorizedAccessException) { } + } + return result; + } + + public static string Resolve(string? path) + { + if (!string.IsNullOrWhiteSpace(path)) + { + var full = System.IO.Path.GetFullPath(path); + if (Directory.Exists(full)) full = System.IO.Path.Combine(full, "LEDS.LED"); + if (!System.IO.Path.GetFileName(full).Equals("LEDS.LED", StringComparison.OrdinalIgnoreCase)) + throw new ArgumentException("Device path must be a mount directory or LEDS.LED file."); + if (!File.Exists(full)) throw new IOException("LEDS.LED was not found at the selected device path."); + return full; + } + var devices = Discover(); + return devices.Count switch + { + 1 => devices[0].Path, + 0 => throw new IOException("No mounted SidePulse found. Use --device with its LEDS.LED path."), + _ => throw new IOException("Multiple devices found. Select one with --device.") + }; + } + + public static void Write(string path, LedProgram program) + { + // Write to the existing virtual file. Atomic rename is unsuitable for the device filesystem. + using var stream = new FileStream(Resolve(path), FileMode.Open, FileAccess.Write, FileShare.Read, + 4096, FileOptions.WriteThrough); + var bytes = Encoding.UTF8.GetBytes(program.Text); + stream.Write(bytes); + stream.SetLength(bytes.Length); + stream.Flush(true); + } +} diff --git a/src/SidePulse.Core/LedProgram.cs b/src/SidePulse.Core/LedProgram.cs new file mode 100644 index 0000000..7c5fc08 --- /dev/null +++ b/src/SidePulse.Core/LedProgram.cs @@ -0,0 +1,47 @@ +using System.Text; + +namespace SidePulse.Core; + +public enum AgentState { Unknown, Idle, Working, Waiting, Done, Error } + +/// Firmware envelope validation, not a full firmware grammar parser. +public sealed record LedProgram +{ + public string Text { get; } + public int ByteCount => Encoding.UTF8.GetByteCount(Text); + public int LineCount => Text.Split('\n').Length; + + public LedProgram(string text) + { + Text = text.Replace("\r\n", "\n").Replace('\r', '\n').TrimEnd('\n'); + if (string.IsNullOrWhiteSpace(Text)) throw new ArgumentException("LED program is empty."); + if (Text.Contains('\0')) throw new ArgumentException("LED programs cannot contain NUL characters."); + if (ByteCount > 512) throw new ArgumentException("LED program exceeds 512 UTF-8 bytes."); + if (LineCount > 20) throw new ArgumentException("LED program exceeds 20 physical lines."); + } + + public static string DecodeEscapes(string text) + { + var result = new StringBuilder(); + for (var i = 0; i < text.Length; i++) + { + if (text[i] == '\\' && i + 1 < text.Length) + { + var decoded = text[i + 1] switch { 'n' => '\n', 'r' => '\r', 't' => '\t', '\\' => '\\', _ => '\0' }; + if (decoded != '\0') { result.Append(decoded); i++; continue; } + } + result.Append(text[i]); + } + return result.ToString(); + } + + // Protocol profiles adapted from inteliwear/sidepulse, baseline in NOTICE.md. + public static LedProgram ForState(AgentState state) => new(state switch + { + AgentState.Working => "off\n#00e5ff 1.6s pulse\nrepeat", + AgentState.Waiting => "off\n#ff9900 1.6s pulse\nrepeat", + AgentState.Done => "off\n#00ff66", + AgentState.Error => "off\n#ff1800 0.4s pulse\nrepeat", + _ => "off" + }); +} diff --git a/src/SidePulse.Core/PhoneBridge.cs b/src/SidePulse.Core/PhoneBridge.cs new file mode 100644 index 0000000..43ca55e --- /dev/null +++ b/src/SidePulse.Core/PhoneBridge.cs @@ -0,0 +1,28 @@ +using System.Net.Http.Json; +using System.Text.RegularExpressions; + +namespace SidePulse.Core; + +public sealed class PhoneBridge(HttpClient client) +{ + public async Task SendAsync(string token, LedProgram program, CancellationToken cancellationToken = default) + { + // Initial implementation supports APNS registration tokens only; never print tokens or request URLs. + if (!Regex.IsMatch(token, @"\A(?:dev_)?[0-9a-f]{64}(?:_[A-Za-z0-9_-]{1,128})?\z")) + throw new ArgumentException("Invalid iPhone push token."); + var payload = new Dictionary + { + ["aps"] = new Dictionary { ["content-available"] = 1 }, + ["leds"] = program.Text, + ["data"] = new Dictionary { ["sidepulse_event_id"] = Guid.NewGuid().ToString() } + }; + try + { + using var response = await client.PostAsJsonAsync( + "https://bridge.sidepulse.io/api/leds/" + Uri.EscapeDataString("apns_" + token), payload, cancellationToken); + if (!response.IsSuccessStatusCode) + throw new IOException($"Phone bridge returned HTTP {(int)response.StatusCode}."); + } + catch (HttpRequestException) { throw new IOException("Phone bridge request failed. Check network connectivity."); } + } +} diff --git a/src/SidePulse.Core/Sessions.cs b/src/SidePulse.Core/Sessions.cs new file mode 100644 index 0000000..4224e0f --- /dev/null +++ b/src/SidePulse.Core/Sessions.cs @@ -0,0 +1,70 @@ +using System.Text.Json; + +namespace SidePulse.Core; + +public sealed record SessionEvent(string SessionId, AgentState State, long Timestamp); +public sealed record SessionView(string Id, AgentState State, long Timestamp); + +public sealed class Sessions +{ + private readonly Dictionary sessions = new(); + public IReadOnlyList Snapshot => sessions.Values.OrderBy(s => s.Id).ToArray(); + public bool Apply(SessionEvent item) + { + if (string.IsNullOrWhiteSpace(item.SessionId) || item.SessionId.Length > 256 || item.Timestamp < 0) return false; + if (sessions.TryGetValue(item.SessionId, out var previous) && item.Timestamp < previous.Timestamp) return false; + // Bound memory. Never evict an active session silently. + if (!sessions.ContainsKey(item.SessionId) && sessions.Count >= 1024) + { + var old = sessions.Values.Where(s => s.State is AgentState.Idle or AgentState.Done) + .OrderBy(s => s.Timestamp).FirstOrDefault(); + if (old is null) return false; + sessions.Remove(old.Id); + } + sessions[item.SessionId] = new(item.SessionId, item.State, item.Timestamp); + return true; + } + public AgentState State + { + get + { + foreach (var state in new[] { AgentState.Waiting, AgentState.Working, AgentState.Error, AgentState.Done, AgentState.Idle }) + if (sessions.Values.Any(s => s.State == state)) return state; + return AgentState.Unknown; + } + } +} + +public static class CopilotEvents +{ + public static SessionEvent? Parse(string eventName, string json) + { + using var document = JsonDocument.Parse(json); + var root = document.RootElement; + string? Get(string camel, string? snake = null) => root.TryGetProperty(camel, out var value) + ? value.ToString() : snake is not null && root.TryGetProperty(snake, out value) ? value.ToString() : null; + var session = Get("sessionId", "session_id"); + // Missing identity must not merge unrelated sessions under a shared placeholder. + if (string.IsNullOrWhiteSpace(session)) return null; + var timestampText = Get("timestamp"); + long timestamp; + if (!long.TryParse(timestampText, out timestamp)) + { + if (!DateTimeOffset.TryParse(timestampText, out var date)) return null; + timestamp = date.ToUnixTimeMilliseconds(); + } + AgentState? state = eventName switch + { + "userPromptSubmitted" => AgentState.Working, + "sessionStart" => string.IsNullOrWhiteSpace(Get("initialPrompt", "initial_prompt")) ? AgentState.Idle : AgentState.Working, + "preToolUse" => Get("toolName", "tool_name") == "ask_user" ? AgentState.Waiting : AgentState.Working, + "postToolUse" => AgentState.Working, + "agentStop" when Get("stopReason", "stop_reason") == "end_turn" => AgentState.Done, + "errorOccurred" or "postToolUseFailure" => AgentState.Error, + "sessionEnd" => Get("reason") is "error" or "timeout" ? AgentState.Error : AgentState.Idle, + "notification" when Get("notificationType", "notification_type") is "permission_prompt" or "elicitation_dialog" => AgentState.Waiting, + _ => null + }; + return state.HasValue ? new(session, state.Value, timestamp) : null; + } +} diff --git a/src/SidePulse.Core/SidePulse.Core.csproj b/src/SidePulse.Core/SidePulse.Core.csproj new file mode 100644 index 0000000..6b512ec --- /dev/null +++ b/src/SidePulse.Core/SidePulse.Core.csproj @@ -0,0 +1 @@ + diff --git a/tests/SidePulse.Tests/CoreTests.cs b/tests/SidePulse.Tests/CoreTests.cs new file mode 100644 index 0000000..3f238f3 --- /dev/null +++ b/tests/SidePulse.Tests/CoreTests.cs @@ -0,0 +1,101 @@ +using System.Net; +using System.Text.Json; +using SidePulse.Core; +using Xunit; + +namespace SidePulse.Tests; + +public sealed class CoreTests +{ + [Fact] + public void LimitsUseUtf8BytesAndPhysicalLines() + { + Assert.Equal(512, new LedProgram(new string('é', 256)).ByteCount); + Assert.Throws(() => new LedProgram(new string('é', 257))); + Assert.Equal(20, new LedProgram(string.Join('\n', Enumerable.Repeat("off", 20))).LineCount); + Assert.Throws(() => new LedProgram(string.Join('\n', Enumerable.Repeat("off", 21)))); + Assert.Throws(() => new LedProgram("\0")); + Assert.Throws(() => new LedProgram(" ")); + } + [Fact] + public void EscapeDecodingIsSinglePassAndPreservesUnknownEscapes() + { + Assert.Equal("off\n#ff0000", LedProgram.DecodeEscapes(@"off\n#ff0000")); + Assert.Equal(@"\n", LedProgram.DecodeEscapes(@"\\n")); + Assert.Equal(@"\q", LedProgram.DecodeEscapes(@"\q")); + } + [Theory] + [InlineData(AgentState.Working, "off\n#00e5ff 1.6s pulse\nrepeat")] + [InlineData(AgentState.Waiting, "off\n#ff9900 1.6s pulse\nrepeat")] + [InlineData(AgentState.Done, "off\n#00ff66")] + [InlineData(AgentState.Error, "off\n#ff1800 0.4s pulse\nrepeat")] + [InlineData(AgentState.Unknown, "off")] + public void StateProfilesMatchReference(AgentState state, string expected) => Assert.Equal(expected, LedProgram.ForState(state).Text); + + [Fact] + public void WritesTruncateStaleBytesAndDoNotCreateUnrelatedFiles() + { + var directory = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); + Directory.CreateDirectory(directory); + try + { + var path = Path.Combine(directory, "LEDS.LED"); + File.WriteAllText(path, new string('x', 100)); + DeviceTransport.Write(directory, new LedProgram("off")); + Assert.Equal("off", File.ReadAllText(path)); + Assert.Throws(() => DeviceTransport.Resolve(Path.Combine(directory, "notes.txt"))); + File.Delete(path); + Assert.Throws(() => DeviceTransport.Write(directory, new LedProgram("off"))); + } + finally { Directory.Delete(directory, true); } + } + [Fact] + public void WaitingWinsAndAnotherSessionsCompletionDoesNotHideWork() + { + var sessions = new Sessions(); + sessions.Apply(new("a", AgentState.Working, 1)); + sessions.Apply(new("b", AgentState.Done, 1)); + Assert.Equal(AgentState.Working, sessions.State); + sessions.Apply(new("c", AgentState.Waiting, 1)); + Assert.Equal(AgentState.Waiting, sessions.State); + Assert.False(sessions.Apply(new("c", AgentState.Done, 0))); + Assert.Equal(AgentState.Waiting, sessions.State); + } + [Theory] + [InlineData("permissionRequest")] + [InlineData("subagentStop")] + public void NonTerminalEventsDoNotChangeMainSession(string name) => Assert.Null(CopilotEvents.Parse(name, "{\"sessionId\":\"a\",\"timestamp\":1}")); + [Fact] + public void HookMapsWaitingAndRequiresIdentityAndTime() + { + Assert.Equal(AgentState.Waiting, CopilotEvents.Parse("preToolUse", "{\"sessionId\":\"a\",\"timestamp\":1,\"toolName\":\"ask_user\"}")!.State); + Assert.Null(CopilotEvents.Parse("agentStop", "{\"timestamp\":1}")); + Assert.Null(CopilotEvents.Parse("agentStop", "{\"sessionId\":\"a\"}")); + Assert.Equal(AgentState.Done, CopilotEvents.Parse("agentStop", "{\"session_id\":\"a\",\"timestamp\":\"2026-10-23T12:00:00Z\",\"stop_reason\":\"end_turn\"}")!.State); + } + [Fact] + public async Task BridgeSendsSilentApnsEnvelopeAndRedactsNetworkFailures() + { + var handler = new FakeHandler(); + using var client = new HttpClient(handler); + await new PhoneBridge(client).SendAsync(new string('a', 64), new LedProgram("off")); + using var body = JsonDocument.Parse(handler.Body!); + Assert.Equal(1, body.RootElement.GetProperty("aps").GetProperty("content-available").GetInt32()); + Assert.Equal("off", body.RootElement.GetProperty("leds").GetString()); + Assert.False(body.RootElement.GetProperty("aps").TryGetProperty("alert", out _)); + handler.Throw = true; + var error = await Assert.ThrowsAsync(() => new PhoneBridge(client).SendAsync(new string('a', 64), new LedProgram("off"))); + Assert.DoesNotContain(new string('a', 64), error.Message); + } + private sealed class FakeHandler : HttpMessageHandler + { + public string? Body { get; private set; } + public bool Throw { get; set; } + protected override async Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) + { + if (Throw) throw new HttpRequestException(request.RequestUri!.ToString()); + Body = await request.Content!.ReadAsStringAsync(cancellationToken); + return new HttpResponseMessage(HttpStatusCode.OK); + } + } +} diff --git a/tests/SidePulse.Tests/SidePulse.Tests.csproj b/tests/SidePulse.Tests/SidePulse.Tests.csproj new file mode 100644 index 0000000..30b4b1e --- /dev/null +++ b/tests/SidePulse.Tests/SidePulse.Tests.csproj @@ -0,0 +1,9 @@ + + truefalse + + + + + all + + diff --git a/third-party/spectre.console/LICENSE.md b/third-party/spectre.console/LICENSE.md new file mode 100644 index 0000000..a8373c4 --- /dev/null +++ b/third-party/spectre.console/LICENSE.md @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2020 Patrik Svensson, Phil Scott, Nils Andresen + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. From 60055154d3c7a63c2d3f4585bfb4143097168fbd Mon Sep 17 00:00:00 2001 From: Gordon Breuer Date: Fri, 23 Oct 2026 19:59:51 +0200 Subject: [PATCH 02/26] build: lock dependencies, include runtime notices and clarify preview status --- .github/workflows/dotnet-ci.yml | 4 +- CONTRIBUTING.md | 12 +-- Directory.Build.props | 1 + Directory.Packages.props | 10 ++ docs/wiki/Architecture.md | 3 +- docs/wiki/Home.md | 5 +- scripts/check_docs.py | 2 +- src/SidePulse.Cli/SidePulse.Cli.csproj | 4 +- src/SidePulse.Cli/packages.lock.json | 33 ++++++ src/SidePulse.Core/packages.lock.json | 6 ++ tests/SidePulse.Tests/SidePulse.Tests.csproj | 6 +- tests/SidePulse.Tests/packages.lock.json | 101 +++++++++++++++++++ 12 files changed, 171 insertions(+), 16 deletions(-) create mode 100644 Directory.Packages.props create mode 100644 src/SidePulse.Cli/packages.lock.json create mode 100644 src/SidePulse.Core/packages.lock.json create mode 100644 tests/SidePulse.Tests/packages.lock.json diff --git a/.github/workflows/dotnet-ci.yml b/.github/workflows/dotnet-ci.yml index 1f21f2b..6f19c69 100644 --- a/.github/workflows/dotnet-ci.yml +++ b/.github/workflows/dotnet-ci.yml @@ -53,7 +53,7 @@ jobs: env: SOLUTION: ${{ needs.detect.outputs.solution }} shell: pwsh - run: dotnet restore $env:SOLUTION + run: dotnet restore $env:SOLUTION --locked-mode - name: Build env: SOLUTION: ${{ needs.detect.outputs.solution }} @@ -76,6 +76,8 @@ jobs: dotnet publish src/SidePulse.Cli -c Release -r win-x64 --self-contained true -o artifacts/win-x64 if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } Copy-Item LICENSE,NOTICE.md artifacts/win-x64 + New-Item -ItemType Directory -Force artifacts/win-x64/third-party/dotnet | Out-Null + Copy-Item "$env:DOTNET_ROOT/LICENSE.txt","$env:DOTNET_ROOT/ThirdPartyNotices.txt" artifacts/win-x64/third-party/dotnet Copy-Item -Recurse third-party artifacts/win-x64 Copy-Item docs/wiki/Getting-Started.md artifacts/win-x64 python scripts/cli_smoke.py artifacts/win-x64/sidepulse-net.exe diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 0f384c6..e78bfb9 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,8 +1,8 @@ # Contributing -SidePulse.NET is currently in concept review. Discuss significant design choices -before implementation. Keep the application free of C# scaffolding until the -concept and first milestone are approved. +SidePulse.NET has an initial implementation preview. Discuss significant design +changes before expanding the architecture. Keep implemented and verified behavior +clearly distinguished from the complete planned product. ## Changes and reviews @@ -12,11 +12,11 @@ Update wiki sources in `docs/wiki` in the same pull request as behavior changes. The main repository is the documentation source of truth; direct wiki edits need to be brought back into it before the next automated publication. -## When implementation starts +## Implementation Use .NET 10 LTS and Spectre.Console for presentation. Keep state reduction, -protocol logic and device transports independent of the terminal UI. Introduce -central package management and lock files with the first solution. Add meaningful +protocol logic and device transports independent of the terminal UI. Keep +package versions in `Directory.Packages.props` and commit updated lock files. Add meaningful unit, transport-contract, hook-failure and hardware smoke tests as those areas arrive. Rendered, interactive output is for people. Hook and JSON output must have no diff --git a/Directory.Build.props b/Directory.Build.props index ed9620b..ce1e686 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -5,5 +5,6 @@ enable true true + true diff --git a/Directory.Packages.props b/Directory.Packages.props new file mode 100644 index 0000000..9e3f7ab --- /dev/null +++ b/Directory.Packages.props @@ -0,0 +1,10 @@ + + true + + + + + + + + diff --git a/docs/wiki/Architecture.md b/docs/wiki/Architecture.md index b21607b..3a41c47 100644 --- a/docs/wiki/Architecture.md +++ b/docs/wiki/Architecture.md @@ -1,6 +1,7 @@ # Architecture -Status: proposed; no application components have been implemented. +Status: target architecture. The first preview implements a core library, CLI, +foreground host and current-user IPC. See [[Getting-Started]] for limitations. ## Boundaries diff --git a/docs/wiki/Home.md b/docs/wiki/Home.md index 5e45f0c..7cd9fa6 100644 --- a/docs/wiki/Home.md +++ b/docs/wiki/Home.md @@ -4,8 +4,9 @@ **An unofficial .NET companion for SidePulse.** -This wiki describes the proposed product. Application implementation has not -started, and no SidePulse.NET binaries are available yet. +The first implementation preview is available in the source repository and CI +artifacts. Start with [[Getting-Started]] for working commands and limitations. +The concept pages describe the intended complete product. Start with [[Product-Concept]], [[Terminal-Experience]] and [[Roadmap]]. Technical detail lives in [[Architecture]], [[Compatibility]], [[Devices-and-Protocols]], diff --git a/scripts/check_docs.py b/scripts/check_docs.py index feba854..b1d357c 100644 --- a/scripts/check_docs.py +++ b/scripts/check_docs.py @@ -17,7 +17,7 @@ def check(root): count += 1 text = path.read_text(encoding='utf-8') name = str(path.relative_to(root)) - if not text.endswith('\n'): + if not text.endswith('\n') and path.name != 'packages.lock.json': errors.append(f'{name}: missing final newline') for number, line in enumerate(text.splitlines(), 1): if line.rstrip() != line: diff --git a/src/SidePulse.Cli/SidePulse.Cli.csproj b/src/SidePulse.Cli/SidePulse.Cli.csproj index 39c06d7..3623c94 100644 --- a/src/SidePulse.Cli/SidePulse.Cli.csproj +++ b/src/SidePulse.Cli/SidePulse.Cli.csproj @@ -8,7 +8,7 @@ - - + + diff --git a/src/SidePulse.Cli/packages.lock.json b/src/SidePulse.Cli/packages.lock.json new file mode 100644 index 0000000..aa243bb --- /dev/null +++ b/src/SidePulse.Cli/packages.lock.json @@ -0,0 +1,33 @@ +{ + "version": 2, + "dependencies": { + "net10.0": { + "Spectre.Console": { + "type": "Direct", + "requested": "[0.57.2, )", + "resolved": "0.57.2", + "contentHash": "wzsB+P9i6F9G+cFOJxRotCiQWNSzZVAMxi8YMiHlGXXU1JLMXGp7zSSqBMmROZS2bzpK5jk+Saa7Evp8HwqhKg==", + "dependencies": { + "Spectre.Console.Ansi": "0.57.2" + } + }, + "Spectre.Console.Cli": { + "type": "Direct", + "requested": "[0.57.2, )", + "resolved": "0.57.2", + "contentHash": "EAiwpJXAAvhyyzH6hljVo7z19ahG7WM+zViKEHtUagyPymYfJrsainXDOHzUakBHj6VYEpuaqPAShgqvs1N9aQ==", + "dependencies": { + "Spectre.Console": "0.57.2" + } + }, + "Spectre.Console.Ansi": { + "type": "Transitive", + "resolved": "0.57.2", + "contentHash": "Y1+u73shwP+JYHmrkdN6bSt2kaGBEAafhi2nrecczbXdFRey+k7J/WF9YPfcB0rqivv2S8fmif6FSBq9m/AFvw==" + }, + "sidepulse.core": { + "type": "Project" + } + } + } +} \ No newline at end of file diff --git a/src/SidePulse.Core/packages.lock.json b/src/SidePulse.Core/packages.lock.json new file mode 100644 index 0000000..6afd678 --- /dev/null +++ b/src/SidePulse.Core/packages.lock.json @@ -0,0 +1,6 @@ +{ + "version": 2, + "dependencies": { + "net10.0": {} + } +} \ No newline at end of file diff --git a/tests/SidePulse.Tests/SidePulse.Tests.csproj b/tests/SidePulse.Tests/SidePulse.Tests.csproj index 30b4b1e..a3e4f1a 100644 --- a/tests/SidePulse.Tests/SidePulse.Tests.csproj +++ b/tests/SidePulse.Tests/SidePulse.Tests.csproj @@ -2,8 +2,8 @@ truefalse - - - all + + + all diff --git a/tests/SidePulse.Tests/packages.lock.json b/tests/SidePulse.Tests/packages.lock.json new file mode 100644 index 0000000..4ee7a5d --- /dev/null +++ b/tests/SidePulse.Tests/packages.lock.json @@ -0,0 +1,101 @@ +{ + "version": 2, + "dependencies": { + "net10.0": { + "Microsoft.NET.Test.Sdk": { + "type": "Direct", + "requested": "[17.14.1, )", + "resolved": "17.14.1", + "contentHash": "HJKqKOE+vshXra2aEHpi2TlxYX7Z9VFYkr+E5rwEvHC8eIXiyO+K9kNm8vmNom3e2rA56WqxU+/N9NJlLGXsJQ==", + "dependencies": { + "Microsoft.CodeCoverage": "17.14.1", + "Microsoft.TestPlatform.TestHost": "17.14.1" + } + }, + "xunit": { + "type": "Direct", + "requested": "[2.9.3, )", + "resolved": "2.9.3", + "contentHash": "TlXQBinK35LpOPKHAqbLY4xlEen9TBafjs0V5KnA4wZsoQLQJiirCR4CbIXvOH8NzkW4YeJKP5P/Bnrodm0h9Q==", + "dependencies": { + "xunit.analyzers": "1.18.0", + "xunit.assert": "2.9.3", + "xunit.core": "[2.9.3]" + } + }, + "xunit.runner.visualstudio": { + "type": "Direct", + "requested": "[3.1.5, )", + "resolved": "3.1.5", + "contentHash": "tKi7dSTwP4m5m9eXPM2Ime4Kn7xNf4x4zT9sdLO/G4hZVnQCRiMTWoSZqI/pYTVeI27oPPqHBKYI/DjJ9GsYgA==" + }, + "Microsoft.CodeCoverage": { + "type": "Transitive", + "resolved": "17.14.1", + "contentHash": "pmTrhfFIoplzFVbhVwUquT+77CbGH+h4/3mBpdmIlYtBi9nAB+kKI6dN3A/nV4DFi3wLLx/BlHIPK+MkbQ6Tpg==" + }, + "Microsoft.TestPlatform.ObjectModel": { + "type": "Transitive", + "resolved": "17.14.1", + "contentHash": "xTP1W6Mi6SWmuxd3a+jj9G9UoC850WGwZUps1Wah9r1ZxgXhdJfj1QqDLJkFjHDCvN42qDL2Ps5KjQYWUU0zcQ==" + }, + "Microsoft.TestPlatform.TestHost": { + "type": "Transitive", + "resolved": "17.14.1", + "contentHash": "d78LPzGKkJwsJXAQwsbJJ7LE7D1wB+rAyhHHAaODF+RDSQ0NgMjDFkSA1Djw18VrxO76GlKAjRUhl+H8NL8Z+Q==", + "dependencies": { + "Microsoft.TestPlatform.ObjectModel": "17.14.1", + "Newtonsoft.Json": "13.0.3" + } + }, + "Newtonsoft.Json": { + "type": "Transitive", + "resolved": "13.0.3", + "contentHash": "HrC5BXdl00IP9zeV+0Z848QWPAoCr9P3bDEZguI+gkLcBKAOxix/tLEAAHC+UvDNPv4a2d18lOReHMOagPa+zQ==" + }, + "xunit.abstractions": { + "type": "Transitive", + "resolved": "2.0.3", + "contentHash": "pot1I4YOxlWjIb5jmwvvQNbTrZ3lJQ+jUGkGjWE3hEFM0l5gOnBWS+H3qsex68s5cO52g+44vpGzhAt+42vwKg==" + }, + "xunit.analyzers": { + "type": "Transitive", + "resolved": "1.18.0", + "contentHash": "OtFMHN8yqIcYP9wcVIgJrq01AfTxijjAqVDy/WeQVSyrDC1RzBWeQPztL49DN2syXRah8TYnfvk035s7L95EZQ==" + }, + "xunit.assert": { + "type": "Transitive", + "resolved": "2.9.3", + "contentHash": "/Kq28fCE7MjOV42YLVRAJzRF0WmEqsmflm0cfpMjGtzQ2lR5mYVj1/i0Y8uDAOLczkL3/jArrwehfMD0YogMAA==" + }, + "xunit.core": { + "type": "Transitive", + "resolved": "2.9.3", + "contentHash": "BiAEvqGvyme19wE0wTKdADH+NloYqikiU0mcnmiNyXaF9HyHmE6sr/3DC5vnBkgsWaE6yPyWszKSPSApWdRVeQ==", + "dependencies": { + "xunit.extensibility.core": "[2.9.3]", + "xunit.extensibility.execution": "[2.9.3]" + } + }, + "xunit.extensibility.core": { + "type": "Transitive", + "resolved": "2.9.3", + "contentHash": "kf3si0YTn2a8J8eZNb+zFpwfoyvIrQ7ivNk5ZYA5yuYk1bEtMe4DxJ2CF/qsRgmEnDr7MnW1mxylBaHTZ4qErA==", + "dependencies": { + "xunit.abstractions": "2.0.3" + } + }, + "xunit.extensibility.execution": { + "type": "Transitive", + "resolved": "2.9.3", + "contentHash": "yMb6vMESlSrE3Wfj7V6cjQ3S4TXdXpRqYeNEI3zsX31uTsGMJjEw6oD5F5u1cHnMptjhEECnmZSsPxB6ChZHDQ==", + "dependencies": { + "xunit.extensibility.core": "[2.9.3]" + } + }, + "sidepulse.core": { + "type": "Project" + } + } + } +} \ No newline at end of file From 4761b7557e869f1cefef931db8e00e8dcd901306 Mon Sep 17 00:00:00 2001 From: Gordon Breuer Date: Fri, 23 Oct 2026 20:00:59 +0200 Subject: [PATCH 03/26] fix: retain unhandled errors at turn end and exercise Unicode paths --- scripts/cli_smoke.py | 2 +- src/SidePulse.Core/Sessions.cs | 6 +++++- tests/SidePulse.Tests/CoreTests.cs | 11 +++++++++++ 3 files changed, 17 insertions(+), 2 deletions(-) diff --git a/scripts/cli_smoke.py b/scripts/cli_smoke.py index 8782439..11950c7 100644 --- a/scripts/cli_smoke.py +++ b/scripts/cli_smoke.py @@ -22,7 +22,7 @@ def run(*args, input=None): assert not malformed.stdout and not malformed.stderr disconnected = run('hook', 'agentStop', input=json.dumps({'sessionId': 'a', 'timestamp': 1, 'stopReason': 'end_turn'})) assert not disconnected.stdout and not disconnected.stderr - with tempfile.TemporaryDirectory() as directory: + with tempfile.TemporaryDirectory(prefix='SidePulse test ü ') as directory: target = Path(directory) / 'LEDS.LED' target.write_text('off') run('state', 'waiting', '--device', directory) diff --git a/src/SidePulse.Core/Sessions.cs b/src/SidePulse.Core/Sessions.cs index 4224e0f..b866f69 100644 --- a/src/SidePulse.Core/Sessions.cs +++ b/src/SidePulse.Core/Sessions.cs @@ -21,7 +21,11 @@ public bool Apply(SessionEvent item) if (old is null) return false; sessions.Remove(old.Id); } - sessions[item.SessionId] = new(item.SessionId, item.State, item.Timestamp); + // A turn-ending signal does not establish recovery from an earlier error. + // A subsequent working/waiting event or explicit session end can clear it. + var state = previous?.State == AgentState.Error && item.State == AgentState.Done + ? AgentState.Error : item.State; + sessions[item.SessionId] = new(item.SessionId, state, item.Timestamp); return true; } public AgentState State diff --git a/tests/SidePulse.Tests/CoreTests.cs b/tests/SidePulse.Tests/CoreTests.cs index 3f238f3..d8b26f1 100644 --- a/tests/SidePulse.Tests/CoreTests.cs +++ b/tests/SidePulse.Tests/CoreTests.cs @@ -61,6 +61,17 @@ public void WaitingWinsAndAnotherSessionsCompletionDoesNotHideWork() Assert.False(sessions.Apply(new("c", AgentState.Done, 0))); Assert.Equal(AgentState.Waiting, sessions.State); } + [Fact] + public void TurnEndDoesNotHideAnUnhandledError() + { + var sessions = new Sessions(); + sessions.Apply(new("a", AgentState.Error, 1)); + sessions.Apply(new("a", AgentState.Done, 2)); + Assert.Equal(AgentState.Error, sessions.State); + sessions.Apply(new("a", AgentState.Working, 3)); + Assert.Equal(AgentState.Working, sessions.State); + Assert.Null(CopilotEvents.Parse("agentStop", "{\"sessionId\":\"a\",\"timestamp\":4}")); + } [Theory] [InlineData("permissionRequest")] [InlineData("subagentStop")] From d2717356bce238a5e9b99cd9dee570cf48856935 Mon Sep 17 00:00:00 2001 From: Gordon Breuer Date: Fri, 23 Oct 2026 20:03:31 +0200 Subject: [PATCH 04/26] ci: fix notice packaging and avoid duplicate pull request builds --- .github/workflows/dotnet-ci.yml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.github/workflows/dotnet-ci.yml b/.github/workflows/dotnet-ci.yml index 6f19c69..5c7829f 100644 --- a/.github/workflows/dotnet-ci.yml +++ b/.github/workflows/dotnet-ci.yml @@ -1,6 +1,7 @@ name: .NET CI on: push: + branches: [main] pull_request: workflow_dispatch: permissions: @@ -76,9 +77,9 @@ jobs: dotnet publish src/SidePulse.Cli -c Release -r win-x64 --self-contained true -o artifacts/win-x64 if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } Copy-Item LICENSE,NOTICE.md artifacts/win-x64 + Copy-Item -Recurse third-party artifacts/win-x64 New-Item -ItemType Directory -Force artifacts/win-x64/third-party/dotnet | Out-Null Copy-Item "$env:DOTNET_ROOT/LICENSE.txt","$env:DOTNET_ROOT/ThirdPartyNotices.txt" artifacts/win-x64/third-party/dotnet - Copy-Item -Recurse third-party artifacts/win-x64 Copy-Item docs/wiki/Getting-Started.md artifacts/win-x64 python scripts/cli_smoke.py artifacts/win-x64/sidepulse-net.exe if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } From 0b045504521edaae856dca8b7267db2e76581dfb Mon Sep 17 00:00:00 2001 From: Gordon Breuer Date: Fri, 23 Oct 2026 20:52:40 +0200 Subject: [PATCH 05/26] feat: add iPhone QR pairing, protected phone links and local diagnostics --- Directory.Packages.props | 2 + NOTICE.md | 13 ++ README.md | 9 +- docs/wiki/Configuration.md | 4 + docs/wiki/Devices-and-Protocols.md | 4 + docs/wiki/Getting-Started.md | 67 +++++++-- scripts/cli_smoke.py | 21 ++- src/SidePulse.Cli/Commands.cs | 15 +- src/SidePulse.Cli/Doctor.cs | 69 +++++++++ src/SidePulse.Cli/Links.cs | 174 +++++++++++++++++++++++ src/SidePulse.Cli/Program.cs | 13 +- src/SidePulse.Cli/SidePulse.Cli.csproj | 3 +- src/SidePulse.Cli/packages.lock.json | 33 ++++- src/SidePulse.Core/LinkStore.cs | 155 ++++++++++++++++++++ src/SidePulse.Core/Pairing.cs | 138 ++++++++++++++++++ src/SidePulse.Core/PhoneBridge.cs | 5 +- src/SidePulse.Core/PhoneLink.cs | 32 +++++ src/SidePulse.Core/SidePulse.Core.csproj | 4 +- src/SidePulse.Core/packages.lock.json | 9 +- tests/SidePulse.Tests/PhoneTests.cs | 159 +++++++++++++++++++++ tests/SidePulse.Tests/packages.lock.json | 11 +- third-party/qrcoder/LICENSE.txt | 21 +++ 22 files changed, 934 insertions(+), 27 deletions(-) create mode 100644 src/SidePulse.Cli/Doctor.cs create mode 100644 src/SidePulse.Cli/Links.cs create mode 100644 src/SidePulse.Core/LinkStore.cs create mode 100644 src/SidePulse.Core/Pairing.cs create mode 100644 src/SidePulse.Core/PhoneLink.cs create mode 100644 tests/SidePulse.Tests/PhoneTests.cs create mode 100644 third-party/qrcoder/LICENSE.txt diff --git a/Directory.Packages.props b/Directory.Packages.props index 9e3f7ab..e5670d1 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -1,6 +1,8 @@ true + + diff --git a/NOTICE.md b/NOTICE.md index ddec976..2d4f455 100644 --- a/NOTICE.md +++ b/NOTICE.md @@ -33,3 +33,16 @@ Spectre.Console, Spectre.Console.Cli and Spectre.Console.Ansi 0.57.2 are MIT licensed dependencies, copyright Patrik Svensson, Phil Scott, Nils Andresen, Cédric Luthi and contributors. Their repository license is retained in `third-party/spectre.console/LICENSE.md` and included in CI distribution artifacts. Test packages are development dependencies and are not part of the application. + +## Phone linking and credential storage + +`Pairing.cs` and `PhoneLink.cs` adapt the QR URI, SSE registration and APNS token +normalization contracts from upstream `src/sidepulse/links.py` at the reference +revision above. `LinkStore.cs` and CLI link management are new .NET implementations. +The upstream MIT notice is retained with these adapted protocol portions. + +QRCoder 1.8.1 is MIT licensed, copyright Raffael Herrmann and Shane Krueger. +Its original license is retained in `third-party/qrcoder/LICENSE.txt`. +System.Security.Cryptography.ProtectedData 10.0.13 and the Microsoft libraries +resolved with QRCoder are MIT licensed .NET components. Windows preview artifacts +include the .NET license and third-party notices in `third-party/dotnet`. diff --git a/README.md b/README.md index 49c0362..c1e721b 100644 --- a/README.md +++ b/README.md @@ -59,12 +59,13 @@ dotnet run --project src/SidePulse.Cli -- dashboard The solution contains a portable core, a Spectre.Console CLI and behavioral tests. -Implemented commands: `devices`, `state`, `write`, `dashboard`, `host` and -`hook-config`. Use `--help` for details and `--dry-run` before sending a program. +Implemented commands: `devices`, `state`, `write`, `dashboard`, `host`, +`hook-config`, `doctor` and `link pair/list/import/default/rename/remove`. Use `--help` for details and `--dry-run` before sending a program. The command name `sidepulse-net` coexists with the existing Python port. -QR pairing, protected token storage, a persistent service, full DSL validation, -other upstream integrations and a signed installer remain planned. The wiki's +QR pairing and protected token storage are available on Windows. A persistent +service, full DSL validation, other upstream integrations and a signed installer +remain planned. The wiki's concept pages describe the intended complete product; the getting-started page records what is implemented now. diff --git a/docs/wiki/Configuration.md b/docs/wiki/Configuration.md index 1d2a93b..816d991 100644 --- a/docs/wiki/Configuration.md +++ b/docs/wiki/Configuration.md @@ -1,3 +1,7 @@ +> Implementation update: Windows links now use a separate current-user DPAPI store. +> Alias/default management and the `SIDEPULSE_NET_HOME` override are implemented. +> See [[Getting-Started]] for working commands. The remainder describes the target configuration design. + # Configuration and coexistence Status: proposed. diff --git a/docs/wiki/Devices-and-Protocols.md b/docs/wiki/Devices-and-Protocols.md index 23dc9e8..6233162 100644 --- a/docs/wiki/Devices-and-Protocols.md +++ b/docs/wiki/Devices-and-Protocols.md @@ -1,3 +1,7 @@ +> Implementation update: QR/SSE pairing for the default iPhone bridge and encrypted +> Windows link storage are implemented. Android and custom bridge origins remain planned. +> Hardware and TestFlight app verification are still pending. See [[Getting-Started]]. + # Devices and protocols ## Local hardware diff --git a/docs/wiki/Getting-Started.md b/docs/wiki/Getting-Started.md index 1554f7d..77caec3 100644 --- a/docs/wiki/Getting-Started.md +++ b/docs/wiki/Getting-Started.md @@ -2,8 +2,8 @@ The first implementation is an alpha preview. USB discovery/writes, status profiles, raw programs, silent iPhone bridge delivery with an existing APNS token, session -aggregation and a foreground Copilot CLI host are implemented. QR pairing, protected -credential storage, background-service installation, full LED grammar validation, +aggregation, QR pairing, Windows-protected phone links, diagnostics and a foreground +Copilot CLI host are implemented. Background-service installation, full LED grammar validation, animation rendering, migration and other agent integrations remain planned. ## Build and run @@ -41,21 +41,70 @@ Only one writer should control a device. Physical device behavior still needs Windows hardware verification. Validation checks the 512-byte/20-line envelope; the firmware remains responsible for LED syntax validation. -## Phone delivery +## Pair an iPhone on Windows -Set `SIDEPULSE_TOKEN` in the current process environment to an existing iPhone push -token from the SidePulse app. Keep it out of scripts, command history, source -control and screenshots. The preview does not read or modify the Python port's -configuration, and does not persist tokens. +```powershell +sidepulse-net link pair iphone +sidepulse-net link list +sidepulse-net state done --phone iphone +sidepulse-net host --phone default +``` + +Scan the terminal QR using the SidePulse app's pairing flow. The pairing URI is +also shown for terminals without ANSI support or enough width. Pairing expires +after five minutes, supports Ctrl+C cancellation and ignores unrelated or invalid +registration events. `--timeout 60` shortens the wait; `--no-qr` shows only the URI. +Treat the live pairing URI as temporary pairing access; keep it out of shared logs. +Actual QR scanning with the TestFlight app still requires device verification. + +The entire link document, including names and tokens, is encrypted with Windows +DPAPI for the current user. It is stored in `%LOCALAPPDATA%\SidePulse.NET\links.dpapi`. +There is no plaintext fallback. The store uses exclusive locking and atomic encrypted +file replacement. It preserves an unreadable store rather than overwriting it. +`SIDEPULSE_NET_HOME` can select another absolute directory, for isolated configurations +or testing; this does not make DPAPI credentials portable to another Windows user. +The app does not read or modify the Python port's configuration. + +The first linked phone becomes the default. Selection is explicit via `--phone`; +commands without a phone option continue to discover USB devices. + +```powershell +sidepulse-net link rename iphone personal +sidepulse-net link default personal +sidepulse-net link list --json +sidepulse-net link remove personal +sidepulse-net doctor --json +``` + +Aliases are case-insensitive and use 1–40 letters, digits, underscores or hyphens. +`default` is reserved. Existing aliases and duplicate tokens are rejected. +Removing a default link clears the default; it never silently selects another phone. +Removing a link only removes the local credential, and does not revoke the token +at the phone or bridge. Listing links and diagnostics never display tokens. +`doctor` checks local runtime, mounted devices, DPAPI/storage and hook-directory +presence; it sends no device writes or network requests. + +## Existing tokens and other platforms + +If you already have an iPhone token, set `SIDEPULSE_TOKEN` in the current process +environment. Keep the value out of command history, source control and screenshots. +Save it securely on Windows, or use it directly without persistence: ```powershell +sidepulse-net link import iphone --token-env SIDEPULSE_TOKEN sidepulse-net state working --token-env SIDEPULSE_TOKEN sidepulse-net host --token-env SIDEPULSE_TOKEN ``` +Saved phone links and pairing currently require Windows. Linux/macOS support +environment-token delivery without persistent storage. `--device`, `--phone` and +`--token-env` are mutually exclusive. A dry run previews the program without +reading credentials or validating that a saved phone exists. + The bridge uses HTTPS and silent APNS payloads with unique event IDs. An HTTP -success is bridge acceptance, not proof of delivery to the hardware. Android, -custom bridge servers, phone registration and QR pairing are not implemented yet. +success is bridge acceptance, not proof of delivery to the hardware. Android and +custom bridge servers are not implemented yet. Pairing and delivery follow the +upstream protocol at the revision in `upstream.json`. ## Copilot CLI on Windows diff --git a/scripts/cli_smoke.py b/scripts/cli_smoke.py index 11950c7..de8f9e8 100644 --- a/scripts/cli_smoke.py +++ b/scripts/cli_smoke.py @@ -11,8 +11,10 @@ def main(): exe = str(Path(sys.argv[1]).resolve()) + child_env = os.environ.copy() + def run(*args, input=None): - result = subprocess.run([exe, *args], input=input, text=True, capture_output=True, timeout=10) + result = subprocess.run([exe, *args], input=input, text=True, capture_output=True, timeout=10, env=child_env) assert result.returncode == 0, (args, result.stdout, result.stderr) return result @@ -23,6 +25,23 @@ def run(*args, input=None): disconnected = run('hook', 'agentStop', input=json.dumps({'sessionId': 'a', 'timestamp': 1, 'stopReason': 'end_turn'})) assert not disconnected.stdout and not disconnected.stderr with tempfile.TemporaryDirectory(prefix='SidePulse test ü ') as directory: + child_env['SIDEPULSE_NET_HOME'] = str(Path(directory) / 'config') + checks = json.loads(run('doctor', '--json').stdout) + assert all(check['Status'] != 'error' for check in checks) + if os.name == 'nt': + token = 'a' * 64 + '_TestKey' + child_env['SIDEPULSE_TEST_TOKEN'] = token + run('link', 'import', 'iphone', '--token-env', 'SIDEPULSE_TEST_TOKEN') + phones = run('link', 'list', '--json').stdout + assert token not in phones + assert json.loads(phones)[0]['IsDefault'] + blob = (Path(child_env['SIDEPULSE_NET_HOME']) / 'links.dpapi').read_bytes() + assert token.encode() not in blob + run('link', 'rename', 'iphone', 'personal') + run('link', 'default', 'personal') + run('state', 'done', '--phone', 'default', '--dry-run') + run('link', 'remove', 'personal') + assert json.loads(run('link', 'list', '--json').stdout) == [] target = Path(directory) / 'LEDS.LED' target.write_text('off') run('state', 'waiting', '--device', directory) diff --git a/src/SidePulse.Cli/Commands.cs b/src/SidePulse.Cli/Commands.cs index b462250..76aac37 100644 --- a/src/SidePulse.Cli/Commands.cs +++ b/src/SidePulse.Cli/Commands.cs @@ -50,14 +50,17 @@ public class TargetSettings : CommandSettings [CommandOption("--token-env ")] [Description("Environment variable holding an iPhone push token. Selects phone delivery.")] public string? TokenEnvironment { get; init; } + [CommandOption("--phone ")] + [Description("Use a saved phone alias, or 'default'. Windows protected storage.")] + public string? Phone { get; init; } [CommandOption("--dry-run")] [Description("Preview the program without writing or sending anything.")] public bool DryRun { get; init; } [CommandOption("--json")] public bool Json { get; init; } - public override ValidationResult Validate() => Device is not null && TokenEnvironment is not null - ? ValidationResult.Error("Choose either --device or --token-env.") : ValidationResult.Success(); + public override ValidationResult Validate() => new[] { Device, TokenEnvironment, Phone }.Count(v => v is not null) > 1 + ? ValidationResult.Error("Choose one of --device, --token-env or --phone.") : ValidationResult.Success(); } public static class Delivery @@ -65,7 +68,13 @@ public static class Delivery public static async Task Send(TargetSettings settings, LedProgram program, CancellationToken cancellationToken) { if (settings.DryRun) return; - if (settings.TokenEnvironment is { } variable) + if (settings.Phone is { } alias) + { + var phone = PhoneStores.Open().Get(alias); + using var client = new HttpClient { Timeout = TimeSpan.FromSeconds(10) }; + await new PhoneBridge(client).SendAsync(phone.Token, program, cancellationToken); + } + else if (settings.TokenEnvironment is { } variable) { var token = Environment.GetEnvironmentVariable(variable); if (string.IsNullOrWhiteSpace(token)) throw new ArgumentException("The selected token environment variable is empty."); diff --git a/src/SidePulse.Cli/Doctor.cs b/src/SidePulse.Cli/Doctor.cs new file mode 100644 index 0000000..cf7385c --- /dev/null +++ b/src/SidePulse.Cli/Doctor.cs @@ -0,0 +1,69 @@ +using System.ComponentModel; +using System.Runtime.InteropServices; +using SidePulse.Core; +using Spectre.Console; +using Spectre.Console.Cli; + +namespace SidePulse.Cli; + +public sealed record DiagnosticCheck(string Name, string Status, string Detail); +public sealed class DoctorSettings : CommandSettings +{ + [CommandOption("--json")] + [Description("Emit diagnostics without ANSI output or credential values.")] + public bool Json { get; init; } +} +public sealed class DoctorCommand : Command +{ + public override int Execute(CommandContext context, DoctorSettings settings, CancellationToken cancellationToken) + { + var checks = new List + { + new("Runtime", "ok", RuntimeInformation.FrameworkDescription), + new("Platform", "ok", RuntimeInformation.OSDescription) + }; + var devices = DeviceTransport.Discover(); + checks.Add(new("USB discovery", devices.Count == 0 ? "info" : "ok", $"{devices.Count} mounted device(s). No write was attempted.")); + if (OperatingSystem.IsWindows()) + { + try + { + var protector = new WindowsSecretProtector(); + var sample = new byte[] { 83, 80 }; + if (!protector.Unprotect(protector.Protect(sample)).AsSpan().SequenceEqual(sample)) throw new IOException(); + checks.Add(new("Credential protection", "ok", "Current-user DPAPI round trip succeeded.")); + if (File.Exists(LinkStore.DefaultPath)) + { + var links = PhoneStores.Open().List(); + checks.Add(new("Phone store", "ok", $"{links.Count} protected phone link(s). Tokens are never shown.")); + } + else checks.Add(new("Phone store", "info", "No saved phone store. Use link pair to get started.")); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or System.Security.Cryptography.CryptographicException) + { + checks.Add(new("Phone store / DPAPI", "error", "Protected storage is unavailable or unreadable. Existing data was preserved.")); + } + } + else checks.Add(new("Credential protection", "info", "Saved phone links require Windows. Environment-token delivery remains available.")); + var copilotHome = Environment.GetEnvironmentVariable("COPILOT_HOME"); + var hooks = string.IsNullOrWhiteSpace(copilotHome) + ? Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".copilot", "hooks") + : Path.Combine(copilotHome, "hooks"); + checks.Add(new("Copilot hooks", Directory.Exists(hooks) ? "ok" : "info", + Directory.Exists(hooks) ? "Hook directory exists. Use hook-config to generate a separate opt-in file." + : "Hook directory does not exist. See Getting started for installation.")); + if (settings.Json) Output.Print(checks); + else + { + AnsiConsole.Write(new Rule("[cyan]SidePulse.NET diagnostics[/]").LeftJustified()); + var table = new Table().Border(TableBorder.Rounded).AddColumn("Check").AddColumn("Status").AddColumn("Detail"); + foreach (var check in checks) + { + var color = check.Status == "error" ? "red" : check.Status == "ok" ? "green" : "grey"; + table.AddRow(Markup.Escape(check.Name), $"[{color}]{check.Status}[/]", Markup.Escape(check.Detail)); + } + AnsiConsole.Write(table); + } + return checks.Any(c => c.Status == "error") ? 1 : 0; + } +} diff --git a/src/SidePulse.Cli/Links.cs b/src/SidePulse.Cli/Links.cs new file mode 100644 index 0000000..8358113 --- /dev/null +++ b/src/SidePulse.Cli/Links.cs @@ -0,0 +1,174 @@ +using System.ComponentModel; +using QRCoder; +using SidePulse.Core; +using Spectre.Console; +using Spectre.Console.Cli; + +namespace SidePulse.Cli; + +public static class PhoneStores +{ + public static LinkStore Open() => new(LinkStore.DefaultPath, new WindowsSecretProtector()); +} +public class LinkListSettings : CommandSettings +{ + [CommandOption("--json")] + public bool Json { get; init; } +} +public sealed class LinkListCommand : Command +{ + public override int Execute(CommandContext context, LinkListSettings settings, CancellationToken cancellationToken) + { + var phones = PhoneStores.Open().List(); + if (settings.Json) Output.Print(phones); + else + { + var table = new Table().Border(TableBorder.Rounded).AddColumn("Alias").AddColumn("Phone").AddColumn("Default"); + foreach (var phone in phones) + table.AddRow(Markup.Escape(phone.Alias), Markup.Escape(phone.Name), phone.IsDefault ? "yes" : ""); + AnsiConsole.Write(table); + if (phones.Count == 0) AnsiConsole.WriteLine("No saved phones. Use link pair to connect an iPhone."); + } + return 0; + } +} +public class AliasSettings : CommandSettings +{ + [CommandArgument(0, "")] + public string Alias { get; init; } = ""; + public override ValidationResult Validate() + { + try { PhoneTokens.Alias(Alias); return ValidationResult.Success(); } + catch (ArgumentException ex) { return ValidationResult.Error(ex.Message); } + } +} +public sealed class DefaultPhoneCommand : Command +{ + public override int Execute(CommandContext context, AliasSettings settings, CancellationToken cancellationToken) + { + PhoneStores.Open().SetDefault(settings.Alias); + AnsiConsole.WriteLine("Default phone updated."); + return 0; + } +} +public sealed class RemovePhoneCommand : Command +{ + public override int Execute(CommandContext context, AliasSettings settings, CancellationToken cancellationToken) + { + PhoneStores.Open().Remove(settings.Alias); + AnsiConsole.WriteLine("Saved phone removed. This removes the local link; it does not revoke the token at the bridge."); + return 0; + } +} +public sealed class RenameSettings : AliasSettings +{ + [CommandArgument(1, "")] + public string NewAlias { get; init; } = ""; + public override ValidationResult Validate() + { + var original = base.Validate(); + if (!original.Successful) return original; + try { PhoneTokens.Alias(NewAlias); return ValidationResult.Success(); } + catch (ArgumentException ex) { return ValidationResult.Error(ex.Message); } + } +} +public sealed class RenamePhoneCommand : Command +{ + public override int Execute(CommandContext context, RenameSettings settings, CancellationToken cancellationToken) + { + PhoneStores.Open().Rename(settings.Alias, settings.NewAlias); + AnsiConsole.WriteLine("Phone alias updated."); + return 0; + } +} +public sealed class ImportPhoneSettings : AliasSettings +{ + [CommandOption("--token-env ")] + [Description("Environment variable holding an existing iPhone push token. The value is never printed.")] + public string TokenEnvironment { get; init; } = "SIDEPULSE_TOKEN"; + [CommandOption("--name ")] + public string Name { get; init; } = "iPhone"; +} +public sealed class ImportPhoneCommand : Command +{ + public override int Execute(CommandContext context, ImportPhoneSettings settings, CancellationToken cancellationToken) + { + var store = PhoneStores.Open(); + var token = Environment.GetEnvironmentVariable(settings.TokenEnvironment); + if (string.IsNullOrWhiteSpace(token)) throw new ArgumentException("The selected token environment variable is empty."); + store.Add(new(settings.Alias, settings.Name, token, DateTimeOffset.UtcNow)); + AnsiConsole.MarkupLine("[green]Phone saved in the protected store.[/]"); + return 0; + } +} +public sealed class PairPhoneSettings : AliasSettings +{ + [CommandOption("--timeout ")] + [DefaultValue(300)] + public int TimeoutSeconds { get; init; } = 300; + [CommandOption("--no-qr")] + [Description("Show only the pairing URI, for terminals that cannot render the QR code.")] + public bool NoQr { get; init; } + public override ValidationResult Validate() + { + var original = base.Validate(); + if (!original.Successful) return original; + return TimeoutSeconds is >= 1 and <= 300 ? ValidationResult.Success() : ValidationResult.Error("Pairing timeout must be 1–300 seconds."); + } +} +public sealed class PairPhoneCommand : AsyncCommand +{ + public override async Task ExecuteAsync(CommandContext context, PairPhoneSettings settings, CancellationToken cancellationToken) + { + var store = PhoneStores.Open(); + if (store.List().Any(p => p.Alias.Equals(settings.Alias, StringComparison.OrdinalIgnoreCase))) + throw new ArgumentException("That phone alias already exists. Remove it or choose a different alias."); + using var shutdown = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + ConsoleCancelEventHandler cancel = (_, args) => { args.Cancel = true; shutdown.Cancel(); }; + Console.CancelKeyPress += cancel; + var channel = Pairing.NewChannel(); + var url = Pairing.Url(channel); + try + { + using var client = new HttpClient { Timeout = Timeout.InfiniteTimeSpan }; + // Start subscribing before presenting the QR to reduce registration races. + var pairing = Pairing.WaitAsync(client, channel, settings.Alias, TimeSpan.FromSeconds(settings.TimeoutSeconds), shutdown.Token); + try + { + AnsiConsole.Write(new Rule("[cyan]Link iPhone[/]").LeftJustified()); + AnsiConsole.WriteLine("Scan with the SidePulse app, or open this pairing link on your phone:"); + AnsiConsole.WriteLine(url); + if (!settings.NoQr && !Console.IsOutputRedirected) + { + using var code = QRCodeGenerator.GenerateQrCode(url, QRCodeGenerator.ECCLevel.M); + if (AnsiConsole.Profile.Capabilities.Ansi && AnsiConsole.Profile.Width >= code.ModuleMatrix.Count * 2) + { + foreach (var row in code.ModuleMatrix) + { + AnsiConsole.MarkupLine(string.Concat(row.Cast().Select(dark => + dark ? "[white on black] [/]" : "[black on white] [/]"))); + } + } + else AnsiConsole.WriteLine("QR rendering needs an ANSI terminal with sufficient width. Use the pairing link above."); + } + AnsiConsole.WriteLine($"Waiting up to {settings.TimeoutSeconds} seconds. Ctrl+C cancels."); + var phone = await pairing; + store.Add(phone); + AnsiConsole.MarkupLine("[green]Linked and saved securely:[/] " + Markup.Escape(phone.Name)); + AnsiConsole.WriteLine($"Try: sidepulse-net state done --phone {phone.Alias}"); + return 0; + } + finally + { + shutdown.Cancel(); + try { await pairing; } catch (Exception ex) when (ex is OperationCanceledException or TimeoutException) { } + } + } + catch (OperationCanceledException) when (shutdown.IsCancellationRequested) + { + AnsiConsole.WriteLine("Pairing cancelled. No phone was saved."); + return 0; + } + finally { Console.CancelKeyPress -= cancel; } + } +} diff --git a/src/SidePulse.Cli/Program.cs b/src/SidePulse.Cli/Program.cs index 32d13dd..b6e4c57 100644 --- a/src/SidePulse.Cli/Program.cs +++ b/src/SidePulse.Cli/Program.cs @@ -6,7 +6,18 @@ app.Configure(config => { config.SetApplicationName("sidepulse-net"); - config.SetApplicationVersion("0.1.0-alpha.1"); + config.SetApplicationVersion("0.1.0-alpha.2"); + config.AddBranch("link", links => + { + links.SetDescription("Pair and manage protected iPhone links (Windows)."); + links.AddCommand("pair").WithDescription("Pair an iPhone by QR code."); + links.AddCommand("list").WithDescription("List saved phones without exposing tokens."); + links.AddCommand("import").WithDescription("Save an existing token from an environment variable."); + links.AddCommand("default").WithDescription("Choose the default saved phone."); + links.AddCommand("rename").WithDescription("Rename a phone alias."); + links.AddCommand("remove").WithDescription("Remove a local phone link."); + }); + config.AddCommand("doctor").WithDescription("Check local setup without sending to devices or the network."); config.AddCommand("devices").WithDescription("List mounted SidePulse devices."); config.AddCommand("state").WithDescription("Display an agent state on USB or iPhone."); config.AddCommand("write").WithDescription("Send a raw LED program with firmware envelope checks."); diff --git a/src/SidePulse.Cli/SidePulse.Cli.csproj b/src/SidePulse.Cli/SidePulse.Cli.csproj index 3623c94..5897798 100644 --- a/src/SidePulse.Cli/SidePulse.Cli.csproj +++ b/src/SidePulse.Cli/SidePulse.Cli.csproj @@ -2,12 +2,13 @@ Exe sidepulse-net - 0.1.0-alpha.1 + 0.1.0-alpha.2 Unofficial SidePulse companion MIT + diff --git a/src/SidePulse.Cli/packages.lock.json b/src/SidePulse.Cli/packages.lock.json index aa243bb..f612cf0 100644 --- a/src/SidePulse.Cli/packages.lock.json +++ b/src/SidePulse.Cli/packages.lock.json @@ -2,6 +2,15 @@ "version": 2, "dependencies": { "net10.0": { + "QRCoder": { + "type": "Direct", + "requested": "[1.8.1, )", + "resolved": "1.8.1", + "contentHash": "aGfRFpU/IPexAtEOEXCNxC3fMCAqgn6kqALRvXt6LxVAW0VolSDGHiyrY+o2CJgTITOsMpsrsDi7svMJaJ9Vfg==", + "dependencies": { + "System.Drawing.Common": "6.0.0" + } + }, "Spectre.Console": { "type": "Direct", "requested": "[0.57.2, )", @@ -20,13 +29,35 @@ "Spectre.Console": "0.57.2" } }, + "Microsoft.Win32.SystemEvents": { + "type": "Transitive", + "resolved": "6.0.0", + "contentHash": "hqTM5628jSsQiv+HGpiq3WKBl2c8v1KZfby2J6Pr7pEPlK9waPdgEO6b8A/+/xn/yZ9ulv8HuqK71ONy2tg67A==" + }, "Spectre.Console.Ansi": { "type": "Transitive", "resolved": "0.57.2", "contentHash": "Y1+u73shwP+JYHmrkdN6bSt2kaGBEAafhi2nrecczbXdFRey+k7J/WF9YPfcB0rqivv2S8fmif6FSBq9m/AFvw==" }, + "System.Drawing.Common": { + "type": "Transitive", + "resolved": "6.0.0", + "contentHash": "NfuoKUiP2nUWwKZN6twGqXioIe1zVD0RIj2t976A+czLHr2nY454RwwXs6JU9Htc6mwqL6Dn/nEL3dpVf2jOhg==", + "dependencies": { + "Microsoft.Win32.SystemEvents": "6.0.0" + } + }, "sidepulse.core": { - "type": "Project" + "type": "Project", + "dependencies": { + "System.Security.Cryptography.ProtectedData": "[10.0.13, )" + } + }, + "System.Security.Cryptography.ProtectedData": { + "type": "CentralTransitive", + "requested": "[10.0.13, )", + "resolved": "10.0.13", + "contentHash": "aUSmC6cPjFLSE0rDTsmkR3wvUOnscqewebOaaELEToh12sNmoltZqT3f0C81mJ1zhxKjWco25soHTvYwsXCsUw==" } } } diff --git a/src/SidePulse.Core/LinkStore.cs b/src/SidePulse.Core/LinkStore.cs new file mode 100644 index 0000000..0ac74aa --- /dev/null +++ b/src/SidePulse.Core/LinkStore.cs @@ -0,0 +1,155 @@ +using System.Security.Cryptography; +using System.Text.Json; + +namespace SidePulse.Core; + +public interface ISecretProtector +{ + byte[] Protect(byte[] plaintext); + byte[] Unprotect(byte[] ciphertext); +} + +public sealed class WindowsSecretProtector : ISecretProtector +{ + public WindowsSecretProtector() + { + if (!OperatingSystem.IsWindows()) + throw new PlatformNotSupportedException("Saved phone links currently require Windows DPAPI. Use --token-env on other platforms."); + } + public byte[] Protect(byte[] plaintext) + { + if (!OperatingSystem.IsWindows()) throw new PlatformNotSupportedException(); + return ProtectedData.Protect(plaintext, null, DataProtectionScope.CurrentUser); + } + public byte[] Unprotect(byte[] ciphertext) + { + if (!OperatingSystem.IsWindows()) throw new PlatformNotSupportedException(); + return ProtectedData.Unprotect(ciphertext, null, DataProtectionScope.CurrentUser); + } +} + +/// The entire document is encrypted; no plaintext credential file or silent recovery. +public sealed class LinkStore(string path, ISecretProtector protector) +{ + public static string DefaultPath + { + get + { + var home = Environment.GetEnvironmentVariable("SIDEPULSE_NET_HOME"); + if (string.IsNullOrWhiteSpace(home)) + home = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "SidePulse.NET"); + if (!Path.IsPathFullyQualified(home)) throw new ArgumentException("SIDEPULSE_NET_HOME must be an absolute directory path."); + return Path.Combine(home, "links.dpapi"); + } + } + private const int MaximumBytes = 262144; + private sealed record Document(int Version, string? DefaultAlias, List Links); + private readonly string fullPath = Path.GetFullPath(path); + + private FileStream Lock() + { + Directory.CreateDirectory(Path.GetDirectoryName(fullPath)!); + try { return new FileStream(fullPath + ".lock", FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None); } + catch (IOException) { throw new IOException("The phone store is busy. Retry after the other command finishes."); } + } + private Document Read() + { + if (!File.Exists(fullPath)) return new(1, null, []); + byte[]? plaintext = null; + try + { + if (new FileInfo(fullPath).Length > MaximumBytes) throw new InvalidDataException(); + plaintext = protector.Unprotect(File.ReadAllBytes(fullPath)); + if (plaintext.Length > MaximumBytes) throw new InvalidDataException(); + var document = JsonSerializer.Deserialize(plaintext); + if (document is null || document.Version != 1 || document.Links is null || document.Links.Count > 128) + throw new InvalidDataException(); + var aliases = new HashSet(StringComparer.OrdinalIgnoreCase); + foreach (var link in document.Links) + { + if (link is null || PhoneTokens.Alias(link.Alias) != link.Alias || !aliases.Add(link.Alias) + || PhoneTokens.Normalize(link.Token) != link.Token || string.IsNullOrWhiteSpace(link.Name) || link.Name.Length > 80) + throw new InvalidDataException(); + } + if (document.DefaultAlias is not null && !aliases.Contains(document.DefaultAlias)) throw new InvalidDataException(); + return document; + } + catch (Exception ex) when (ex is CryptographicException or JsonException or ArgumentException or InvalidDataException) + { + throw new IOException("The protected phone store cannot be read. Keep the file for recovery; it has not been replaced."); + } + finally { if (plaintext is not null) CryptographicOperations.ZeroMemory(plaintext); } + } + private void Save(Document document) + { + var plaintext = JsonSerializer.SerializeToUtf8Bytes(document); + byte[] encrypted; + try + { + if (plaintext.Length > MaximumBytes) throw new IOException("The phone store is full."); + encrypted = protector.Protect(plaintext); + } + finally { CryptographicOperations.ZeroMemory(plaintext); } + var temporary = fullPath + "." + Guid.NewGuid().ToString("N") + ".tmp"; + try + { + using (var file = new FileStream(temporary, FileMode.CreateNew, FileAccess.Write, FileShare.None, 4096, FileOptions.WriteThrough)) + { + file.Write(encrypted); + file.Flush(true); + } + File.Move(temporary, fullPath, true); + } + finally { if (File.Exists(temporary)) File.Delete(temporary); } + } + public IReadOnlyList List() + { + using var gate = Lock(); + var document = Read(); + return document.Links.Select(l => new PhoneSummary(l.Alias, l.Name, l.LinkedAt, l.Alias == document.DefaultAlias)).ToArray(); + } + public PhoneLink Get(string alias) + { + using var gate = Lock(); + var document = Read(); + var selected = alias.Equals("default", StringComparison.OrdinalIgnoreCase) ? document.DefaultAlias : PhoneTokens.Alias(alias); + return document.Links.FirstOrDefault(l => l.Alias == selected) + ?? throw new ArgumentException("Phone link was not found. Use link list or set a default phone."); + } + public void Add(PhoneLink link) + { + var alias = PhoneTokens.Alias(link.Alias); + var normalized = link with { Alias = alias, Token = PhoneTokens.Normalize(link.Token), Name = Pairing.CleanName(link.Name) }; + using var gate = Lock(); + var document = Read(); + if (document.Links.Any(l => l.Alias == alias)) throw new ArgumentException("That phone alias already exists. Remove it or choose a different alias."); + if (document.Links.Any(l => l.Token == normalized.Token)) throw new ArgumentException("This phone is already linked. Rename its existing alias instead."); + if (document.Links.Count >= 128) throw new IOException("The phone store is full."); + document.Links.Add(normalized); + Save(document with { DefaultAlias = document.DefaultAlias ?? alias }); + } + public void SetDefault(string alias) => Change(alias, (document, link) => document with { DefaultAlias = link.Alias }); + public void Rename(string alias, string newAlias) + { + newAlias = PhoneTokens.Alias(newAlias); + Change(alias, (document, link) => + { + if (document.Links.Any(l => l.Alias == newAlias)) throw new ArgumentException("That phone alias already exists."); + document.Links[document.Links.IndexOf(link)] = link with { Alias = newAlias }; + return document with { DefaultAlias = document.DefaultAlias == link.Alias ? newAlias : document.DefaultAlias }; + }); + } + public void Remove(string alias) => Change(alias, (document, link) => + { + document.Links.Remove(link); + return document with { DefaultAlias = document.DefaultAlias == link.Alias ? null : document.DefaultAlias }; + }); + private void Change(string alias, Func update) + { + alias = PhoneTokens.Alias(alias); + using var gate = Lock(); + var document = Read(); + var link = document.Links.FirstOrDefault(l => l.Alias == alias) ?? throw new ArgumentException("Phone link was not found."); + Save(update(document, link)); + } +} diff --git a/src/SidePulse.Core/Pairing.cs b/src/SidePulse.Core/Pairing.cs new file mode 100644 index 0000000..06987f7 --- /dev/null +++ b/src/SidePulse.Core/Pairing.cs @@ -0,0 +1,138 @@ +using System.Net.Http.Headers; +using System.Runtime.CompilerServices; +using System.Security.Cryptography; +using System.Text; +using System.Text.Json; +using System.Text.RegularExpressions; + +namespace SidePulse.Core; + +public static class Pairing +{ + public const string Server = "https://bridge.sidepulse.io"; + public static string NewChannel() => Convert.ToBase64String(RandomNumberGenerator.GetBytes(8)).TrimEnd('=').Replace('+', '-').Replace('/', '_'); + public static string Url(string channel) + { + if (!Regex.IsMatch(channel, @"\A[A-Za-z0-9_-]{11}\z")) throw new ArgumentException("Invalid pairing channel."); + return "sidepulse://p/" + channel; + } + public static string CleanName(string? name) + { + var clean = string.Concat((name ?? "iPhone").Where(c => !char.IsControl(c))).Trim(); + return string.IsNullOrWhiteSpace(clean) ? "iPhone" : clean[..Math.Min(clean.Length, 80)]; + } + public static PhoneLink? Parse(string message, string alias) + { + try + { + using var document = JsonDocument.Parse(message); + var root = document.RootElement; + if (root.ValueKind != JsonValueKind.Object || !root.TryGetProperty("v", out var version) + || !version.TryGetInt32(out var number) || number != 1 + || !root.TryGetProperty("type", out var type) || type.GetString() != "ios_registration" + || !root.TryGetProperty("device", out var device) || device.ValueKind != JsonValueKind.Object + || !device.TryGetProperty("bundle_id", out var bundle) || bundle.GetString() != "io.sidepulse.ios" + || !device.TryGetProperty("push_token", out var token)) return null; + var name = device.TryGetProperty("name", out var title) && title.ValueKind == JsonValueKind.String ? title.GetString() : "iPhone"; + return new(PhoneTokens.Alias(alias), CleanName(name), PhoneTokens.Normalize(token.GetString() ?? ""), DateTimeOffset.UtcNow); + } + catch (Exception ex) when (ex is JsonException or ArgumentException or InvalidOperationException) { return null; } + } + + /// Bounded SSE reader, including comments, CRLF, multiline data and EOF dispatch. + public static async IAsyncEnumerable Messages(Stream stream, [EnumeratorCancellation] CancellationToken cancellationToken = default) + { + const int maximum = 16384; + var line = new StringBuilder(); + var data = new StringBuilder(); + var buffer = new byte[1024]; + var dropping = false; + var droppingLine = false; + string? ProcessLine() + { + var text = line.ToString().TrimEnd('\r'); + line.Clear(); + if (droppingLine) { droppingLine = false; dropping = true; return null; } + if (text.Length == 0) + { + var message = !dropping && data.Length > 0 ? data.ToString().TrimEnd('\n') : null; + data.Clear(); dropping = false; + return message; + } + if (!dropping && text.StartsWith("data:", StringComparison.Ordinal)) + { + var value = text[5..]; + if (value.StartsWith(' ')) value = value[1..]; + if (data.Length + value.Length + 1 > maximum) { data.Clear(); dropping = true; } + else data.Append(value).Append('\n'); + } + return null; + } + // Read bytes before decoding to ensure even a malicious unterminated line is bounded. + // Registration JSON is UTF-8; decoding per complete line preserves multibyte names. + using var rawLine = new MemoryStream(); + while (true) + { + var count = await stream.ReadAsync(buffer, cancellationToken); + if (count == 0) break; + for (var i = 0; i < count; i++) + { + if (buffer[i] == (byte)'\n') + { + line.Append(Encoding.UTF8.GetString(rawLine.GetBuffer(), 0, (int)rawLine.Length)); + rawLine.SetLength(0); + var message = ProcessLine(); + if (message is not null) yield return message; + } + else if (!droppingLine) + { + if (rawLine.Length >= maximum) { rawLine.SetLength(0); droppingLine = true; } + else rawLine.WriteByte(buffer[i]); + } + } + } + if (rawLine.Length > 0 || droppingLine) + { + line.Append(Encoding.UTF8.GetString(rawLine.GetBuffer(), 0, (int)rawLine.Length)); + ProcessLine(); + } + if (!dropping && data.Length > 0) yield return data.ToString().TrimEnd('\n'); + } + + public static async Task WaitAsync(HttpClient client, string channel, string alias, + TimeSpan timeout, CancellationToken cancellationToken = default) + { + Url(channel); + alias = PhoneTokens.Alias(alias); + if (timeout <= TimeSpan.Zero || timeout > TimeSpan.FromMinutes(5)) throw new ArgumentOutOfRangeException(nameof(timeout)); + using var deadline = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + deadline.CancelAfter(timeout); + try + { + while (true) + { + deadline.Token.ThrowIfCancellationRequested(); + // Reconnect hung streams while preserving the overall pairing deadline. + using var attempt = CancellationTokenSource.CreateLinkedTokenSource(deadline.Token); + attempt.CancelAfter(TimeSpan.FromSeconds(20)); + try + { + using var request = new HttpRequestMessage(HttpMethod.Get, Server + "/api/leds/" + channel); + request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("text/event-stream")); + using var response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, attempt.Token); + response.EnsureSuccessStatusCode(); + using var stream = await response.Content.ReadAsStreamAsync(attempt.Token); + await foreach (var message in Messages(stream, attempt.Token)) + if (Parse(message, alias) is { } link) return link; + } + catch (Exception ex) when (ex is HttpRequestException or IOException) { } + catch (OperationCanceledException) when (!deadline.IsCancellationRequested) { } + await Task.Delay(500, deadline.Token); + } + } + catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested) + { + throw new TimeoutException("Pairing timed out. Check the phone connection and try again with a new QR code."); + } + } +} diff --git a/src/SidePulse.Core/PhoneBridge.cs b/src/SidePulse.Core/PhoneBridge.cs index 43ca55e..ee8291c 100644 --- a/src/SidePulse.Core/PhoneBridge.cs +++ b/src/SidePulse.Core/PhoneBridge.cs @@ -1,5 +1,4 @@ using System.Net.Http.Json; -using System.Text.RegularExpressions; namespace SidePulse.Core; @@ -7,9 +6,7 @@ public sealed class PhoneBridge(HttpClient client) { public async Task SendAsync(string token, LedProgram program, CancellationToken cancellationToken = default) { - // Initial implementation supports APNS registration tokens only; never print tokens or request URLs. - if (!Regex.IsMatch(token, @"\A(?:dev_)?[0-9a-f]{64}(?:_[A-Za-z0-9_-]{1,128})?\z")) - throw new ArgumentException("Invalid iPhone push token."); + token = PhoneTokens.Normalize(token); var payload = new Dictionary { ["aps"] = new Dictionary { ["content-available"] = 1 }, diff --git a/src/SidePulse.Core/PhoneLink.cs b/src/SidePulse.Core/PhoneLink.cs new file mode 100644 index 0000000..602be51 --- /dev/null +++ b/src/SidePulse.Core/PhoneLink.cs @@ -0,0 +1,32 @@ +using System.Text.RegularExpressions; + +namespace SidePulse.Core; + +public sealed record PhoneLink(string Alias, string Name, string Token, DateTimeOffset LinkedAt) +{ + public override string ToString() => $"{Alias} ({Name})"; +} +public sealed record PhoneSummary(string Alias, string Name, DateTimeOffset LinkedAt, bool IsDefault); + +public static class PhoneTokens +{ + public static string Normalize(string value) + { + var input = value.Trim(); + var prefix = input.StartsWith("dev_", StringComparison.OrdinalIgnoreCase) ? "dev_" : ""; + var raw = prefix.Length == 0 ? input : input[4..]; + var separator = raw.IndexOf('_'); + var device = separator < 0 ? raw : raw[..separator]; + var key = separator < 0 ? "" : raw[separator..]; + var normalized = prefix + string.Concat(device.Where(c => !char.IsWhiteSpace(c))).ToLowerInvariant() + key; + if (!Regex.IsMatch(normalized, @"\A(?:dev_)?[0-9a-f]{64}(?:_[A-Za-z0-9_-]{1,128})?\z")) + throw new ArgumentException("Invalid iPhone push token."); + return normalized; + } + public static string Alias(string alias) + { + if (!Regex.IsMatch(alias, @"\A[A-Za-z0-9][A-Za-z0-9_-]{0,39}\z") || alias.Equals("default", StringComparison.OrdinalIgnoreCase)) + throw new ArgumentException("Use an alias of 1–40 letters, digits, underscores or hyphens; 'default' is reserved."); + return alias.ToLowerInvariant(); + } +} diff --git a/src/SidePulse.Core/SidePulse.Core.csproj b/src/SidePulse.Core/SidePulse.Core.csproj index 6b512ec..7d08442 100644 --- a/src/SidePulse.Core/SidePulse.Core.csproj +++ b/src/SidePulse.Core/SidePulse.Core.csproj @@ -1 +1,3 @@ - + + + diff --git a/src/SidePulse.Core/packages.lock.json b/src/SidePulse.Core/packages.lock.json index 6afd678..5ad4745 100644 --- a/src/SidePulse.Core/packages.lock.json +++ b/src/SidePulse.Core/packages.lock.json @@ -1,6 +1,13 @@ { "version": 2, "dependencies": { - "net10.0": {} + "net10.0": { + "System.Security.Cryptography.ProtectedData": { + "type": "Direct", + "requested": "[10.0.13, )", + "resolved": "10.0.13", + "contentHash": "aUSmC6cPjFLSE0rDTsmkR3wvUOnscqewebOaaELEToh12sNmoltZqT3f0C81mJ1zhxKjWco25soHTvYwsXCsUw==" + } + } } } \ No newline at end of file diff --git a/tests/SidePulse.Tests/PhoneTests.cs b/tests/SidePulse.Tests/PhoneTests.cs new file mode 100644 index 0000000..3bd05d6 --- /dev/null +++ b/tests/SidePulse.Tests/PhoneTests.cs @@ -0,0 +1,159 @@ +using System.Net; +using System.Security.Cryptography; +using System.Text; +using System.Text.Json; +using SidePulse.Core; +using Xunit; + +namespace SidePulse.Tests; + +public sealed class PhoneTests +{ + private static string Registration(string token, string bundle = "io.sidepulse.ios") => JsonSerializer.Serialize(new + { + v = 1, type = "ios_registration", device = new { bundle_id = bundle, name = "Ned’s iPhone", push_token = token } + }); + [Fact] + public void PairingUrlAndRegistrationMatchUpstream() + { + for (var i = 0; i < 50; i++) Assert.Matches("^sidepulse://p/[A-Za-z0-9_-]{11}$", Pairing.Url(Pairing.NewChannel())); + Assert.Throws(() => Pairing.Url("../../secret")); + var link = Pairing.Parse(Registration(new string('A', 64) + "_MixedCase_Key"), "IPhone")!; + Assert.Equal("iphone", link.Alias); + Assert.Equal(new string('a', 64) + "_MixedCase_Key", link.Token); + Assert.Equal("Ned’s iPhone", link.Name); + Assert.DoesNotContain(link.Token, link.ToString()); + Assert.Null(Pairing.Parse(Registration(new string('a', 64), "unrelated.app"), "iphone")); + Assert.Null(Pairing.Parse("{\"v\":\"bad\"}", "iphone")); + Assert.Null(Pairing.Parse("[]", "iphone")); + } + [Fact] + public async Task SseHandlesCommentsMultilineUnicodeAndEof() + { + using var stream = new MemoryStream(Encoding.UTF8.GetBytes(": keepalive\r\ndata: first\r\ndata: ünicode\r\n\r\nevent: ignored\ndata:last")); + var messages = new List(); + await foreach (var message in Pairing.Messages(stream)) messages.Add(message); + Assert.Equal(new[] { "first\nünicode", "last" }, messages); + } + [Fact] + public async Task SseDropsOversizedEventsAndRecoversAtBoundary() + { + using var stream = new MemoryStream(Encoding.UTF8.GetBytes("data:" + new string('x', 20000) + "\n\ndata:ok\n\n")); + var messages = new List(); + await foreach (var message in Pairing.Messages(stream)) messages.Add(message); + Assert.Equal(new[] { "ok" }, messages); + } + [Fact] + public async Task PairingIgnoresUnrelatedEventsAndReconnects() + { + var handler = new PairingHandler(": heartbeat\n\n", "data:[]\n\ndata:" + Registration(new string('a', 64)) + "\n\n"); + using var client = new HttpClient(handler); + var link = await Pairing.WaitAsync(client, "abcdefghijk", "phone", TimeSpan.FromSeconds(5)); + Assert.Equal("phone", link.Alias); + Assert.Equal(2, handler.Requests); + Assert.Equal("text/event-stream", handler.Accept); + } + [Fact] + public async Task PairingTimeoutAndCancellationAreBounded() + { + using var client = new HttpClient(new HangingHandler()); + var error = await Assert.ThrowsAsync(() => Pairing.WaitAsync(client, "abcdefghijk", "phone", TimeSpan.FromMilliseconds(80))); + Assert.DoesNotContain("abcdefghijk", error.Message); + using var cancelled = new CancellationTokenSource(); + cancelled.Cancel(); + await Assert.ThrowsAnyAsync(() => Pairing.WaitAsync(client, "abcdefghijk", "phone", TimeSpan.FromSeconds(5), cancelled.Token)); + } + [Fact] + public void StoreEncryptsAndMaintainsAliasAndDefaultAcrossReopens() + { + var protectors = new List { new TestProtector() }; + if (OperatingSystem.IsWindows()) protectors.Add(new WindowsSecretProtector()); + foreach (var protector in protectors) + { + var directory = Path.Combine(Path.GetTempPath(), "SidePulse tests ü " + Guid.NewGuid()); + Directory.CreateDirectory(directory); + try + { + var path = Path.Combine(directory, "links.dpapi"); + var store = new LinkStore(path, protector); + var token = new string('a', 64); + store.Add(new("IPhone", "Ned’s iPhone", token, DateTimeOffset.UtcNow)); + var saved = File.ReadAllBytes(path); + Assert.DoesNotContain(token, Encoding.UTF8.GetString(saved)); + Assert.DoesNotContain("Ned’s iPhone", Encoding.UTF8.GetString(saved)); + Assert.Equal("iphone", new LinkStore(path, protector).Get("default").Alias); + store.Add(new("second", "Other phone", new string('b', 64), DateTimeOffset.UtcNow)); + store.SetDefault("SECOND"); + store.Rename("second", "Work"); + Assert.Equal("work", store.Get("default").Alias); + Assert.Throws(() => store.Add(new("work", "New", new string('c', 64), DateTimeOffset.UtcNow))); + Assert.Throws(() => store.Add(new("duplicate", "New", token, DateTimeOffset.UtcNow))); + Assert.DoesNotContain(token, JsonSerializer.Serialize(store.List())); + store.Remove("work"); + Assert.Throws(() => store.Get("default")); + Assert.Equal("iphone", Assert.Single(store.List()).Alias); + Assert.Empty(Directory.GetFiles(directory, "*.tmp")); + } + finally { Directory.Delete(directory, true); } + } + } + [Fact] + public void StorePreservesUnreadableDataAndPreventsConcurrentEdits() + { + var directory = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); + Directory.CreateDirectory(directory); + var path = Path.Combine(directory, "links.dpapi"); + try + { + var protector = new TestProtector(); + var store = new LinkStore(path, protector); + store.Add(new("iphone", "Phone", new string('a', 64), DateTimeOffset.UtcNow)); + using (var gate = new FileStream(path + ".lock", FileMode.Open, FileAccess.ReadWrite, FileShare.None)) + Assert.Throws(() => store.Remove("iphone")); + File.WriteAllBytes(path, [1, 2, 3]); + Assert.Throws(() => store.List()); + Assert.Throws(() => store.Add(new("new", "Phone", new string('b', 64), DateTimeOffset.UtcNow))); + Assert.Equal(new byte[] { 1, 2, 3 }, File.ReadAllBytes(path)); + } + finally { Directory.Delete(directory, true); } + } + private sealed class TestProtector : ISecretProtector + { + private readonly byte[] key = RandomNumberGenerator.GetBytes(32); + public byte[] Protect(byte[] plaintext) + { + var blob = new byte[28 + plaintext.Length]; + RandomNumberGenerator.Fill(blob.AsSpan(0, 12)); + using var aes = new AesGcm(key, 16); + aes.Encrypt(blob.AsSpan(0, 12), plaintext, blob.AsSpan(28), blob.AsSpan(12, 16)); + return blob; + } + public byte[] Unprotect(byte[] ciphertext) + { + if (ciphertext.Length < 28) throw new CryptographicException(); + var plaintext = new byte[ciphertext.Length - 28]; + using var aes = new AesGcm(key, 16); + aes.Decrypt(ciphertext.AsSpan(0, 12), ciphertext.AsSpan(28), ciphertext.AsSpan(12, 16), plaintext); + return plaintext; + } + } + private sealed class PairingHandler(params string[] streams) : HttpMessageHandler + { + public int Requests { get; private set; } + public string? Accept { get; private set; } + protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) + { + Accept = request.Headers.Accept.ToString(); + var stream = streams[Math.Min(Requests++, streams.Length - 1)]; + return Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(stream, Encoding.UTF8, "text/event-stream") }); + } + } + private sealed class HangingHandler : HttpMessageHandler + { + protected override async Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) + { + await Task.Delay(Timeout.Infinite, cancellationToken); + return new(HttpStatusCode.OK); + } + } +} diff --git a/tests/SidePulse.Tests/packages.lock.json b/tests/SidePulse.Tests/packages.lock.json index 4ee7a5d..e5c89fe 100644 --- a/tests/SidePulse.Tests/packages.lock.json +++ b/tests/SidePulse.Tests/packages.lock.json @@ -94,7 +94,16 @@ } }, "sidepulse.core": { - "type": "Project" + "type": "Project", + "dependencies": { + "System.Security.Cryptography.ProtectedData": "[10.0.13, )" + } + }, + "System.Security.Cryptography.ProtectedData": { + "type": "CentralTransitive", + "requested": "[10.0.13, )", + "resolved": "10.0.13", + "contentHash": "aUSmC6cPjFLSE0rDTsmkR3wvUOnscqewebOaaELEToh12sNmoltZqT3f0C81mJ1zhxKjWco25soHTvYwsXCsUw==" } } } diff --git a/third-party/qrcoder/LICENSE.txt b/third-party/qrcoder/LICENSE.txt new file mode 100644 index 0000000..90b272f --- /dev/null +++ b/third-party/qrcoder/LICENSE.txt @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2013-2025 Raffael Herrmann +Copyright (c) 2024-2025 Shane Krueger + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. From f68ac247aa62bd331559992badb25f052b3307be Mon Sep 17 00:00:00 2001 From: Gordon Breuer Date: Fri, 23 Oct 2026 21:06:17 +0200 Subject: [PATCH 06/26] feat: add native macOS and Linux credentials, Bash hooks and cross-platform builds --- .github/workflows/dotnet-ci.yml | 83 +++++++++++++--- scripts/cli_smoke.py | 13 ++- src/SidePulse.Cli/Commands.cs | 2 +- src/SidePulse.Cli/Doctor.cs | 29 +++--- src/SidePulse.Cli/Hooks.cs | 4 +- src/SidePulse.Cli/Links.cs | 2 +- src/SidePulse.Cli/Program.cs | 4 +- src/SidePulse.Cli/SidePulse.Cli.csproj | 2 +- src/SidePulse.Core/DeviceTransport.cs | 7 +- src/SidePulse.Core/LinkStore.cs | 17 +++- src/SidePulse.Core/MacKeychainVault.cs | 86 +++++++++++++++++ src/SidePulse.Core/PlatformSecrets.cs | 127 +++++++++++++++++++++++++ tests/SidePulse.Tests/PhoneTests.cs | 2 + tests/SidePulse.Tests/PlatformTests.cs | 59 ++++++++++++ 14 files changed, 390 insertions(+), 47 deletions(-) create mode 100644 src/SidePulse.Core/MacKeychainVault.cs create mode 100644 src/SidePulse.Core/PlatformSecrets.cs create mode 100644 tests/SidePulse.Tests/PlatformTests.cs diff --git a/.github/workflows/dotnet-ci.yml b/.github/workflows/dotnet-ci.yml index 5c7829f..00e48ea 100644 --- a/.github/workflows/dotnet-ci.yml +++ b/.github/workflows/dotnet-ci.yml @@ -43,6 +43,8 @@ jobs: matrix: os: [windows-latest, ubuntu-latest, macos-latest] runs-on: ${{ matrix.os }} + env: + SIDEPULSE_NATIVE_VAULT_TESTS: '1' steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 with: @@ -50,6 +52,26 @@ jobs: - uses: actions/setup-dotnet@a98b56852c35b8e3190ac28c8c2271da59106c68 # v6 with: dotnet-version: 10.0.x + - name: Prepare isolated native credential vault + if: runner.os != 'Windows' + shell: bash + run: | + if [ "$RUNNER_OS" = 'Linux' ]; then + sudo apt-get update -qq + sudo apt-get install -y libsecret-tools gnome-keyring dbus-x11 + bus_address=$(dbus-daemon --session --fork --print-address=1) + export DBUS_SESSION_BUS_ADDRESS="$bus_address" + echo "DBUS_SESSION_BUS_ADDRESS=$bus_address" >> "$GITHUB_ENV" + printf '%s' 'sidepulse-ci-only' | gnome-keyring-daemon --unlock --components=secrets + else + security default-keychain -d user > "$RUNNER_TEMP/sidepulse-previous-keychain" + security list-keychains -d user > "$RUNNER_TEMP/sidepulse-previous-search-list" + security create-keychain -p 'sidepulse-ci-only' "$RUNNER_TEMP/sidepulse-ci.keychain-db" + security default-keychain -d user -s "$RUNNER_TEMP/sidepulse-ci.keychain-db" + security list-keychains -d user -s "$RUNNER_TEMP/sidepulse-ci.keychain-db" + security unlock-keychain -p 'sidepulse-ci-only' "$RUNNER_TEMP/sidepulse-ci.keychain-db" + security set-keychain-settings -lut 21600 "$RUNNER_TEMP/sidepulse-ci.keychain-db" + fi - name: Restore env: SOLUTION: ${{ needs.detect.outputs.solution }} @@ -70,23 +92,54 @@ jobs: run: | $binary = if ($IsWindows) { 'sidepulse-net.exe' } else { 'sidepulse-net' } python scripts/cli_smoke.py "src/SidePulse.Cli/bin/Release/net10.0/$binary" - - name: Publish self-contained Windows preview - if: runner.os == 'Windows' + - name: Publish and exercise self-contained previews shell: pwsh run: | - dotnet publish src/SidePulse.Cli -c Release -r win-x64 --self-contained true -o artifacts/win-x64 - if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } - Copy-Item LICENSE,NOTICE.md artifacts/win-x64 - Copy-Item -Recurse third-party artifacts/win-x64 - New-Item -ItemType Directory -Force artifacts/win-x64/third-party/dotnet | Out-Null - Copy-Item "$env:DOTNET_ROOT/LICENSE.txt","$env:DOTNET_ROOT/ThirdPartyNotices.txt" artifacts/win-x64/third-party/dotnet - Copy-Item docs/wiki/Getting-Started.md artifacts/win-x64 - python scripts/cli_smoke.py artifacts/win-x64/sidepulse-net.exe - if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } - - name: Upload Windows preview - if: runner.os == 'Windows' + $prefix = if ($IsWindows) { 'win' } elseif ($IsMacOS) { 'osx' } else { 'linux' } + $native = "$prefix-$([System.Runtime.InteropServices.RuntimeInformation]::ProcessArchitecture.ToString().ToLowerInvariant())" + foreach ($architecture in @('x64', 'arm64')) { + $rid = "$prefix-$architecture" + $destination = "artifacts/$rid" + dotnet publish src/SidePulse.Cli -c Release -r $rid --self-contained true -o $destination + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + Copy-Item LICENSE,NOTICE.md $destination + Copy-Item -Recurse third-party $destination + New-Item -ItemType Directory -Force "$destination/third-party/dotnet" | Out-Null + Copy-Item "$env:DOTNET_ROOT/LICENSE.txt","$env:DOTNET_ROOT/ThirdPartyNotices.txt" "$destination/third-party/dotnet" + Copy-Item docs/wiki/Getting-Started.md $destination + if ($rid -eq $native) { + $binary = if ($IsWindows) { 'sidepulse-net.exe' } else { 'sidepulse-net' } + python scripts/cli_smoke.py "$destination/$binary" + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + } + if ($IsWindows) { + Compress-Archive -Path "$destination/*" -DestinationPath "artifacts/sidepulse-net-$rid.zip" + } else { + tar -czf "artifacts/sidepulse-net-$rid.tar.gz" -C $destination . + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + } + } + - name: Upload platform previews uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4 with: - name: sidepulse-net-win-x64-preview - path: artifacts/win-x64/ + name: sidepulse-net-${{ runner.os }}-preview + path: | + artifacts/*.zip + artifacts/*.tar.gz retention-days: 14 + - name: Remove temporary macOS keychain + if: always() && runner.os == 'macOS' + shell: bash + run: | + if [ -f "$RUNNER_TEMP/sidepulse-previous-keychain" ]; then + previous=$(cat "$RUNNER_TEMP/sidepulse-previous-keychain" | tr -d '"' | xargs) + security default-keychain -d user -s "$previous" + fi + if [ -f "$RUNNER_TEMP/sidepulse-previous-search-list" ]; then + keychains=() + while IFS= read -r keychain; do keychains+=("$keychain"); done < <(python3 -c 'import shlex,sys; print("\n".join(shlex.split(sys.stdin.read())))' < "$RUNNER_TEMP/sidepulse-previous-search-list") + security list-keychains -d user -s "${keychains[@]}" + fi + if [ -f "$RUNNER_TEMP/sidepulse-ci.keychain-db" ]; then + security delete-keychain "$RUNNER_TEMP/sidepulse-ci.keychain-db" + fi diff --git a/scripts/cli_smoke.py b/scripts/cli_smoke.py index de8f9e8..2e0ee30 100644 --- a/scripts/cli_smoke.py +++ b/scripts/cli_smoke.py @@ -28,14 +28,14 @@ def run(*args, input=None): child_env['SIDEPULSE_NET_HOME'] = str(Path(directory) / 'config') checks = json.loads(run('doctor', '--json').stdout) assert all(check['Status'] != 'error' for check in checks) - if os.name == 'nt': + if os.name == 'nt' or os.environ.get('SIDEPULSE_NATIVE_VAULT_TESTS') == '1': token = 'a' * 64 + '_TestKey' child_env['SIDEPULSE_TEST_TOKEN'] = token run('link', 'import', 'iphone', '--token-env', 'SIDEPULSE_TEST_TOKEN') phones = run('link', 'list', '--json').stdout assert token not in phones assert json.loads(phones)[0]['IsDefault'] - blob = (Path(child_env['SIDEPULSE_NET_HOME']) / 'links.dpapi').read_bytes() + blob = (Path(child_env['SIDEPULSE_NET_HOME']) / ('links.dpapi' if os.name == 'nt' else 'links.encrypted')).read_bytes() assert token.encode() not in blob run('link', 'rename', 'iphone', 'personal') run('link', 'default', 'personal') @@ -51,6 +51,7 @@ def run(*args, input=None): hooks = json.loads(config.read_text())['hooks'] assert 'permissionRequest' not in hooks and 'subagentStop' not in hooks assert 'exit 0' in hooks['preToolUse'][0]['powershell'] + assert 'exit 0' in hooks['preToolUse'][0]['bash'] refused = subprocess.run([exe, 'hook-config', '--exe', exe, '--output', str(config)], capture_output=True) assert refused.returncode != 0 with open(Path(directory) / 'host.log', 'w') as log: @@ -59,7 +60,13 @@ def run(*args, input=None): # Repeated idempotent input accommodates host startup without a timing-only assertion. for attempt in range(30): assert host.poll() is None, 'Host exited: ' + (Path(directory) / 'host.log').read_text() - result = run('hook', 'userPromptSubmitted', input=json.dumps({'sessionId': 'smoke', 'timestamp': attempt + 1})) + payload = json.dumps({'sessionId': 'smoke', 'timestamp': attempt + 1}) + if os.name == 'nt': + result = run('hook', 'userPromptSubmitted', input=payload) + else: + result = subprocess.run(['bash', '-c', hooks['userPromptSubmitted'][0]['bash']], + input=payload, text=True, capture_output=True, timeout=10, env=child_env) + assert result.returncode == 0 assert not result.stdout and not result.stderr if '#00e5ff' in target.read_text(): break diff --git a/src/SidePulse.Cli/Commands.cs b/src/SidePulse.Cli/Commands.cs index 76aac37..368783d 100644 --- a/src/SidePulse.Cli/Commands.cs +++ b/src/SidePulse.Cli/Commands.cs @@ -51,7 +51,7 @@ public class TargetSettings : CommandSettings [Description("Environment variable holding an iPhone push token. Selects phone delivery.")] public string? TokenEnvironment { get; init; } [CommandOption("--phone ")] - [Description("Use a saved phone alias, or 'default'. Windows protected storage.")] + [Description("Use a saved phone alias, or 'default', from native protected storage.")] public string? Phone { get; init; } [CommandOption("--dry-run")] [Description("Preview the program without writing or sending anything.")] diff --git a/src/SidePulse.Cli/Doctor.cs b/src/SidePulse.Cli/Doctor.cs index cf7385c..924888e 100644 --- a/src/SidePulse.Cli/Doctor.cs +++ b/src/SidePulse.Cli/Doctor.cs @@ -24,27 +24,22 @@ public override int Execute(CommandContext context, DoctorSettings settings, Can }; var devices = DeviceTransport.Discover(); checks.Add(new("USB discovery", devices.Count == 0 ? "info" : "ok", $"{devices.Count} mounted device(s). No write was attempted.")); - if (OperatingSystem.IsWindows()) + try { - try + var protector = PlatformSecrets.Create(LinkStore.DefaultPath); + checks.Add(new("Credential protection", "ok", PlatformSecrets.Description + ". An unlocked native vault is required for saved links.")); + if (File.Exists(LinkStore.DefaultPath)) { - var protector = new WindowsSecretProtector(); - var sample = new byte[] { 83, 80 }; - if (!protector.Unprotect(protector.Protect(sample)).AsSpan().SequenceEqual(sample)) throw new IOException(); - checks.Add(new("Credential protection", "ok", "Current-user DPAPI round trip succeeded.")); - if (File.Exists(LinkStore.DefaultPath)) - { - var links = PhoneStores.Open().List(); - checks.Add(new("Phone store", "ok", $"{links.Count} protected phone link(s). Tokens are never shown.")); - } - else checks.Add(new("Phone store", "info", "No saved phone store. Use link pair to get started.")); - } - catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or System.Security.Cryptography.CryptographicException) - { - checks.Add(new("Phone store / DPAPI", "error", "Protected storage is unavailable or unreadable. Existing data was preserved.")); + var links = PhoneStores.Open().List(); + checks.Add(new("Phone store", "ok", $"{links.Count} protected phone link(s). Tokens are never shown.")); } + else checks.Add(new("Phone store", "info", "No saved phone store. Use link pair to get started.")); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or System.Security.Cryptography.CryptographicException or PlatformNotSupportedException) + { + checks.Add(new("Credential protection", File.Exists(LinkStore.DefaultPath) ? "error" : "info", + "Native credentials are unavailable or unreadable. Unlock Keychain on macOS; on Linux install secret-tool and unlock a Secret Service keyring. Existing data was preserved. Environment-token delivery remains available.")); } - else checks.Add(new("Credential protection", "info", "Saved phone links require Windows. Environment-token delivery remains available.")); var copilotHome = Environment.GetEnvironmentVariable("COPILOT_HOME"); var hooks = string.IsNullOrWhiteSpace(copilotHome) ? Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".copilot", "hooks") diff --git a/src/SidePulse.Cli/Hooks.cs b/src/SidePulse.Cli/Hooks.cs index 5f23d89..d188d01 100644 --- a/src/SidePulse.Cli/Hooks.cs +++ b/src/SidePulse.Cli/Hooks.cs @@ -167,7 +167,9 @@ public override int Execute(CommandContext context, HookConfigSettings settings, { var command = "$ErrorActionPreference = 'SilentlyContinue'; try { $input | & '" + exe.Replace("'", "''") + "' hook " + name + " | Out-Null } catch {}; exit 0"; - var entry = new Dictionary { ["type"] = "command", ["powershell"] = command, ["timeoutSec"] = 2 }; + var quoted = "'" + exe.Replace("'", "'\"'\"'") + "'"; + var bash = quoted + " hook " + name + " >/dev/null 2>&1; exit 0"; + var entry = new Dictionary { ["type"] = "command", ["powershell"] = command, ["bash"] = bash, ["timeoutSec"] = 2 }; if (name == "notification") entry["matcher"] = "permission_prompt|elicitation_dialog"; hooks[name] = new[] { entry }; } diff --git a/src/SidePulse.Cli/Links.cs b/src/SidePulse.Cli/Links.cs index 8358113..5d2184f 100644 --- a/src/SidePulse.Cli/Links.cs +++ b/src/SidePulse.Cli/Links.cs @@ -8,7 +8,7 @@ namespace SidePulse.Cli; public static class PhoneStores { - public static LinkStore Open() => new(LinkStore.DefaultPath, new WindowsSecretProtector()); + public static LinkStore Open() => new(LinkStore.DefaultPath, PlatformSecrets.Create(LinkStore.DefaultPath)); } public class LinkListSettings : CommandSettings { diff --git a/src/SidePulse.Cli/Program.cs b/src/SidePulse.Cli/Program.cs index b6e4c57..3e25dcf 100644 --- a/src/SidePulse.Cli/Program.cs +++ b/src/SidePulse.Cli/Program.cs @@ -6,10 +6,10 @@ app.Configure(config => { config.SetApplicationName("sidepulse-net"); - config.SetApplicationVersion("0.1.0-alpha.2"); + config.SetApplicationVersion("0.1.0-alpha.3"); config.AddBranch("link", links => { - links.SetDescription("Pair and manage protected iPhone links (Windows)."); + links.SetDescription("Pair and manage protected iPhone links."); links.AddCommand("pair").WithDescription("Pair an iPhone by QR code."); links.AddCommand("list").WithDescription("List saved phones without exposing tokens."); links.AddCommand("import").WithDescription("Save an existing token from an environment variable."); diff --git a/src/SidePulse.Cli/SidePulse.Cli.csproj b/src/SidePulse.Cli/SidePulse.Cli.csproj index 5897798..9574cfb 100644 --- a/src/SidePulse.Cli/SidePulse.Cli.csproj +++ b/src/SidePulse.Cli/SidePulse.Cli.csproj @@ -2,7 +2,7 @@ Exe sidepulse-net - 0.1.0-alpha.2 + 0.1.0-alpha.3 Unofficial SidePulse companion MIT diff --git a/src/SidePulse.Core/DeviceTransport.cs b/src/SidePulse.Core/DeviceTransport.cs index 632b154..407f4b4 100644 --- a/src/SidePulse.Core/DeviceTransport.cs +++ b/src/SidePulse.Core/DeviceTransport.cs @@ -15,7 +15,12 @@ public static IReadOnlyList Discover() { if (!drive.IsReady) continue; var path = System.IO.Path.Combine(drive.RootDirectory.FullName, "LEDS.LED"); - if (File.Exists(path)) result.Add(new Device(path, drive.VolumeLabel)); + if (File.Exists(path)) + { + var label = drive.RootDirectory.Name; + try { label = drive.VolumeLabel; } catch (IOException) { } catch (UnauthorizedAccessException) { } + result.Add(new Device(path, label)); + } } catch (IOException) { } catch (UnauthorizedAccessException) { } diff --git a/src/SidePulse.Core/LinkStore.cs b/src/SidePulse.Core/LinkStore.cs index 0ac74aa..def0127 100644 --- a/src/SidePulse.Core/LinkStore.cs +++ b/src/SidePulse.Core/LinkStore.cs @@ -14,7 +14,7 @@ public sealed class WindowsSecretProtector : ISecretProtector public WindowsSecretProtector() { if (!OperatingSystem.IsWindows()) - throw new PlatformNotSupportedException("Saved phone links currently require Windows DPAPI. Use --token-env on other platforms."); + throw new PlatformNotSupportedException("DPAPI is available only on Windows."); } public byte[] Protect(byte[] plaintext) { @@ -39,7 +39,7 @@ public static string DefaultPath if (string.IsNullOrWhiteSpace(home)) home = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "SidePulse.NET"); if (!Path.IsPathFullyQualified(home)) throw new ArgumentException("SIDEPULSE_NET_HOME must be an absolute directory path."); - return Path.Combine(home, "links.dpapi"); + return Path.Combine(home, OperatingSystem.IsWindows() ? "links.dpapi" : "links.encrypted"); } } private const int MaximumBytes = 262144; @@ -48,10 +48,17 @@ private sealed record Document(int Version, string? DefaultAlias, ListGeneric-password items via the native SecItem API. Password bytes never enter process arguments. +public sealed class MacKeychainVault : ICredentialKeyVault +{ + private const string Security = "/System/Library/Frameworks/Security.framework/Security"; + private const string Foundation = "/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation"; + private static readonly Lazy SecurityHandle = new(() => NativeLibrary.Load(Security)); + private static readonly Lazy FoundationHandle = new(() => NativeLibrary.Load(Foundation)); + private static nint Symbol(string name, bool foundation = false) => Marshal.ReadIntPtr(NativeLibrary.GetExport( + foundation ? FoundationHandle.Value : SecurityHandle.Value, name)); + + public MacKeychainVault() + { + if (!OperatingSystem.IsMacOS()) throw new PlatformNotSupportedException(); + } + private sealed class Query : IDisposable + { + public nint Handle { get; } = CFDictionaryCreateMutable(0, 0, 0, 0); + private readonly List owned = []; + public Query(string id) + { + Set("kSecClass", Symbol("kSecClassGenericPassword")); + AddString("kSecAttrService", "io.sidepulse.net"); + AddString("kSecAttrAccount", id); + // Never surprise a foreground host with a blocking unlock dialog. + Set("kSecUseAuthenticationUI", Symbol("kSecUseAuthenticationUIFail")); + } + public void Set(string key, nint value) => CFDictionarySetValue(Handle, Symbol(key), value); + private void AddString(string key, string value) + { + var item = CFStringCreateWithCString(0, value, 0x08000100); + if (item == 0) throw new IOException("Could not allocate a Keychain query."); + owned.Add(item); Set(key, item); + } + public void AddData(byte[] data) + { + var item = CFDataCreate(0, data, data.Length); + if (item == 0) throw new IOException("Could not allocate a Keychain item."); + owned.Add(item); Set("kSecValueData", item); + } + public void Dispose() + { + CFRelease(Handle); + foreach (var item in owned) CFRelease(item); + } + } + public byte[]? Read(string id) + { + using var query = new Query(id); + query.Set("kSecReturnData", Symbol("kCFBooleanTrue", true)); + query.Set("kSecMatchLimit", Symbol("kSecMatchLimitOne")); + var status = SecItemCopyMatching(query.Handle, out var result); + if (status == -25300) return null; // errSecItemNotFound, not an authentication failure + if (status != 0) throw new IOException("Keychain access failed. Unlock the login keychain and allow access to SidePulse.NET. Existing data was preserved."); + try + { + if (CFDataGetLength(result) != 32) throw new CryptographicException("The Keychain encryption key is invalid."); + var key = new byte[32]; + Marshal.Copy(CFDataGetBytePtr(result), key, 0, key.Length); + return key; + } + finally { CFRelease(result); } + } + public void Add(string id, byte[] key) + { + using var query = new Query(id); + query.AddData(key); + var status = SecItemAdd(query.Handle, 0); + if (status != 0 && status != -25299) // duplicate item: preserve the existing key + throw new IOException("Could not save the encryption key in macOS Keychain. Unlock the login keychain first."); + } + + [DllImport(Security)] private static extern int SecItemCopyMatching(nint query, out nint result); + [DllImport(Security)] private static extern int SecItemAdd(nint attributes, nint result); + [DllImport(Foundation)] private static extern nint CFDictionaryCreateMutable(nint allocator, nint capacity, nint keyCallbacks, nint valueCallbacks); + [DllImport(Foundation)] private static extern void CFDictionarySetValue(nint dictionary, nint key, nint value); + [DllImport(Foundation)] private static extern nint CFStringCreateWithCString(nint allocator, [MarshalAs(UnmanagedType.LPUTF8Str)] string text, uint encoding); + [DllImport(Foundation)] private static extern nint CFDataCreate(nint allocator, byte[] bytes, nint length); + [DllImport(Foundation)] private static extern nint CFDataGetLength(nint data); + [DllImport(Foundation)] private static extern nint CFDataGetBytePtr(nint data); + [DllImport(Foundation)] private static extern void CFRelease(nint value); +} diff --git a/src/SidePulse.Core/PlatformSecrets.cs b/src/SidePulse.Core/PlatformSecrets.cs new file mode 100644 index 0000000..4250c8a --- /dev/null +++ b/src/SidePulse.Core/PlatformSecrets.cs @@ -0,0 +1,127 @@ +using System.ComponentModel; +using System.Diagnostics; +using System.Security.Cryptography; +using System.Text; + +namespace SidePulse.Core; + +public interface ICredentialKeyVault +{ + byte[]? Read(string id); + void Add(string id, byte[] key); +} + +/// AES-GCM document encryption with a key held in the user's native credential vault. +public sealed class VaultSecretProtector(ICredentialKeyVault vault, string id) : ISecretProtector +{ + public byte[] Protect(byte[] plaintext) + { + var key = vault.Read(id); + if (key is null) + { + key = RandomNumberGenerator.GetBytes(32); + try { vault.Add(id, key); } + finally { CryptographicOperations.ZeroMemory(key); } + key = vault.Read(id) ?? throw new CryptographicException("Credential key could not be retrieved."); + } + try + { + var result = new byte[32 + plaintext.Length]; + Encoding.ASCII.GetBytes("SPN1").CopyTo(result, 0); + RandomNumberGenerator.Fill(result.AsSpan(4, 12)); + using var aes = new AesGcm(key, 16); + aes.Encrypt(result.AsSpan(4, 12), plaintext, result.AsSpan(32), result.AsSpan(16, 16), Encoding.UTF8.GetBytes(id)); + return result; + } + finally { CryptographicOperations.ZeroMemory(key); } + } + public byte[] Unprotect(byte[] ciphertext) + { + if (ciphertext.Length < 32 || !ciphertext.AsSpan(0, 4).SequenceEqual("SPN1"u8)) throw new CryptographicException(); + var key = vault.Read(id) ?? throw new CryptographicException("The credential key is missing. Existing data was preserved."); + try + { + var plaintext = new byte[ciphertext.Length - 32]; + using var aes = new AesGcm(key, 16); + aes.Decrypt(ciphertext.AsSpan(4, 12), ciphertext.AsSpan(32), ciphertext.AsSpan(16, 16), plaintext, Encoding.UTF8.GetBytes(id)); + return plaintext; + } + finally { CryptographicOperations.ZeroMemory(key); } + } +} + +public static class PlatformSecrets +{ + public static string Description => OperatingSystem.IsWindows() ? "Current-user DPAPI" : OperatingSystem.IsMacOS() + ? "macOS Keychain with AES-GCM" : "Linux Secret Service with AES-GCM"; + public static ISecretProtector Create(string path) + { + if (OperatingSystem.IsWindows()) return new WindowsSecretProtector(); + var id = Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(Path.GetFullPath(path)))); + if (OperatingSystem.IsMacOS()) return new VaultSecretProtector(new MacKeychainVault(), id); + if (OperatingSystem.IsLinux()) return new VaultSecretProtector(new LinuxSecretServiceVault(), id); + throw new PlatformNotSupportedException("Supported platforms are Windows, macOS and Linux."); + } +} + +/// Uses libsecret's helper; secrets go through stdin/stdout, never command arguments or shell expansion. +public sealed class LinuxSecretServiceVault : ICredentialKeyVault +{ + private readonly string executable; + public LinuxSecretServiceVault() + { + if (!OperatingSystem.IsLinux()) throw new PlatformNotSupportedException(); + executable = new[] { "/usr/bin/secret-tool", "/bin/secret-tool" }.FirstOrDefault(File.Exists) + ?? throw new IOException("Install secret-tool (libsecret-tools) and enable an unlocked Secret Service session. Environment-token delivery is also available."); + } + private (int Exit, string Output, string Error) Run(string[] arguments, string? input = null) + { + try + { + return ExecuteAsync(arguments, input).GetAwaiter().GetResult(); + } + catch (Exception ex) when (ex is Win32Exception or OperationCanceledException or IOException) + { + throw new IOException("Secret Service is unavailable or timed out. Unlock the desktop keyring and check the D-Bus session."); + } + } + private async Task<(int, string, string)> ExecuteAsync(string[] arguments, string? input) + { + using var process = new Process + { + StartInfo = new ProcessStartInfo(executable) { UseShellExecute = false, RedirectStandardInput = true, + RedirectStandardOutput = true, RedirectStandardError = true, CreateNoWindow = true } + }; + foreach (var argument in arguments) process.StartInfo.ArgumentList.Add(argument); + process.Start(); + using var deadline = new CancellationTokenSource(TimeSpan.FromSeconds(10)); + try + { + var output = process.StandardOutput.ReadToEndAsync(deadline.Token); + var error = process.StandardError.ReadToEndAsync(deadline.Token); + if (input is not null) await process.StandardInput.WriteAsync(input.AsMemory(), deadline.Token); + process.StandardInput.Close(); + await process.WaitForExitAsync(deadline.Token); + return (process.ExitCode, await output, await error); + } + finally { if (!process.HasExited) { process.Kill(true); await process.WaitForExitAsync(); } } + } + public byte[]? Read(string id) + { + var result = Run(["lookup", "application", "io.sidepulse.net", "store", id]); + if (result.Exit == 1 && string.IsNullOrWhiteSpace(result.Output) && string.IsNullOrWhiteSpace(result.Error)) return null; + if (result.Exit != 0) throw new IOException("Could not unlock or read the Secret Service credential. Existing data was preserved."); + try + { + var key = Convert.FromBase64String(result.Output.Trim()); + if (key.Length != 32) throw new FormatException(); + return key; + } + catch (FormatException) { throw new CryptographicException("The stored credential key is invalid."); } + } + public void Add(string id, byte[] key) + { + var result = Run(["store", "--label=SidePulse.NET encryption key", "application", "io.sidepulse.net", "store", id], Convert.ToBase64String(key)); + if (result.Exit != 0) throw new IOException("Could not save the encryption key in Secret Service. No plaintext fallback is used."); + } +} diff --git a/tests/SidePulse.Tests/PhoneTests.cs b/tests/SidePulse.Tests/PhoneTests.cs index 3bd05d6..1f870c0 100644 --- a/tests/SidePulse.Tests/PhoneTests.cs +++ b/tests/SidePulse.Tests/PhoneTests.cs @@ -68,6 +68,8 @@ public void StoreEncryptsAndMaintainsAliasAndDefaultAcrossReopens() { var protectors = new List { new TestProtector() }; if (OperatingSystem.IsWindows()) protectors.Add(new WindowsSecretProtector()); + if (!OperatingSystem.IsWindows() && Environment.GetEnvironmentVariable("SIDEPULSE_NATIVE_VAULT_TESTS") == "1") + protectors.Add(PlatformSecrets.Create(Path.Combine(Path.GetTempPath(), "sidepulse-native-test-" + Guid.NewGuid()))); foreach (var protector in protectors) { var directory = Path.Combine(Path.GetTempPath(), "SidePulse tests ü " + Guid.NewGuid()); diff --git a/tests/SidePulse.Tests/PlatformTests.cs b/tests/SidePulse.Tests/PlatformTests.cs new file mode 100644 index 0000000..9b7b602 --- /dev/null +++ b/tests/SidePulse.Tests/PlatformTests.cs @@ -0,0 +1,59 @@ +using System.Security.Cryptography; +using System.Text; +using SidePulse.Core; +using Xunit; + +namespace SidePulse.Tests; + +public sealed class PlatformTests +{ + [Fact] + public void VaultEncryptionAuthenticatesCiphertextAndDoesNotRecreateMissingKeys() + { + var vault = new MemoryVault(); + var protector = new VaultSecretProtector(vault, "test-context"); + var plaintext = Encoding.UTF8.GetBytes("private phone credential"); + var ciphertext = protector.Protect(plaintext); + Assert.Equal(plaintext, protector.Unprotect(ciphertext)); + Assert.DoesNotContain("private phone", Encoding.UTF8.GetString(ciphertext)); + Assert.Equal(1, vault.Adds); + ciphertext[^1] ^= 1; + Assert.ThrowsAny(() => protector.Unprotect(ciphertext)); + var missing = new MemoryVault(); + Assert.Throws(() => new VaultSecretProtector(missing, "test-context").Unprotect(ciphertext)); + Assert.Equal(0, missing.Adds); + } + [Fact] + public void VaultEncryptionBindsTheStoreContextAndPreservesExistingKeys() + { + var vault = new MemoryVault(); + var first = new VaultSecretProtector(vault, "first"); + var ciphertext = first.Protect([1, 2, 3]); + Assert.ThrowsAny(() => new VaultSecretProtector(vault, "second").Unprotect(ciphertext)); + first.Protect([4, 5]); + Assert.Equal(1, vault.Adds); + } + [Fact] + public void UnixStoreFilesAreOwnerOnly() + { + if (OperatingSystem.IsWindows()) return; + var directory = Path.Combine(Path.GetTempPath(), "sidepulse-mode-" + Guid.NewGuid()); + try + { + var path = Path.Combine(directory, "links.encrypted"); + var store = new LinkStore(path, new VaultSecretProtector(new MemoryVault(), "permissions")); + store.Add(new("phone", "iPhone", new string('a', 64), DateTimeOffset.UtcNow)); + var mode = UnixFileMode.UserRead | UnixFileMode.UserWrite; + Assert.Equal(mode, File.GetUnixFileMode(path)); + Assert.Equal(mode, File.GetUnixFileMode(path + ".lock")); + } + finally { if (Directory.Exists(directory)) Directory.Delete(directory, true); } + } + private sealed class MemoryVault : ICredentialKeyVault + { + private byte[]? key; + public int Adds { get; private set; } + public byte[]? Read(string id) => key?.ToArray(); + public void Add(string id, byte[] value) { key = value.ToArray(); Adds++; } + } +} From bb80da79c5d96f25411fd87a35c25a7184216daa Mon Sep 17 00:00:00 2001 From: Gordon Breuer Date: Fri, 23 Oct 2026 21:10:38 +0200 Subject: [PATCH 07/26] fix: make Unix hosts restartable and document platform support --- NOTICE.md | 6 +++ README.md | 16 ++++--- docs/decisions/0003-platform-support.md | 17 ++++++++ docs/wiki/Compatibility.md | 11 +++-- docs/wiki/Configuration.md | 2 +- docs/wiki/Devices-and-Protocols.md | 2 +- docs/wiki/Getting-Started.md | 57 ++++++++++++++++++------- docs/wiki/Platforms.md | 52 ++++++++++++++++++++++ docs/wiki/Product-Concept.md | 2 +- docs/wiki/_Sidebar.md | 2 + scripts/cli_smoke.py | 17 ++++++++ src/SidePulse.Cli/Hooks.cs | 41 +++++++++++++++++- 12 files changed, 196 insertions(+), 29 deletions(-) create mode 100644 docs/decisions/0003-platform-support.md create mode 100644 docs/wiki/Platforms.md diff --git a/NOTICE.md b/NOTICE.md index 2d4f455..1ed2fbe 100644 --- a/NOTICE.md +++ b/NOTICE.md @@ -46,3 +46,9 @@ Its original license is retained in `third-party/qrcoder/LICENSE.txt`. System.Security.Cryptography.ProtectedData 10.0.13 and the Microsoft libraries resolved with QRCoder are MIT licensed .NET components. Windows preview artifacts include the .NET license and third-party notices in `third-party/dotnet`. + +## Platform adapters + +`PlatformSecrets.cs` and `MacKeychainVault.cs` are new implementations using native +OS credential APIs/helpers and .NET AES-GCM. No third-party source was copied for +these adapters. The credential APIs do not require a cloud account or token. diff --git a/README.md b/README.md index c1e721b..f3264f7 100644 --- a/README.md +++ b/README.md @@ -6,7 +6,7 @@ An unofficial .NET companion for SidePulse, with a Spectre.Console terminal inte Start with [Getting started](docs/wiki/Getting-Started.md) for build, USB, phone delivery and Copilot CLI instructions. -SidePulse.NET will bring the SidePulse workflow to a native Windows application: +SidePulse.NET brings the SidePulse workflow to Windows, macOS and Linux: pair a phone or connect a USB device, enable an agent integration, and see when an agent is working, waiting for input or finished. @@ -17,11 +17,12 @@ an agent is working, waiting for input or finished. - Native Copilot CLI hooks, followed by the other upstream integrations. - USB LED programs, iPhone linking and bridge delivery, animation previews and profiles. - Reliable session aggregation, device aliases, diagnostics and explicit configuration migration. -- A self-contained Windows distribution without a Python dependency. +- Self-contained Windows, macOS and Linux distributions without a Python dependency. The proposed baseline is **C# / .NET 10 LTS**, **Spectre.Console** and -**Spectre.Console.Cli**. Windows is the first delivery target. Platform-specific -features and later Linux/macOS support are tracked individually. +**Spectre.Console.Cli**. Windows, macOS and Linux are supported by the preview; +see the [platform matrix](docs/wiki/Platforms.md) for native credential requirements +and architecture-specific validation. ## Documentation @@ -63,14 +64,15 @@ Implemented commands: `devices`, `state`, `write`, `dashboard`, `host`, `hook-config`, `doctor` and `link pair/list/import/default/rename/remove`. Use `--help` for details and `--dry-run` before sending a program. The command name `sidepulse-net` coexists with the existing Python port. -QR pairing and protected token storage are available on Windows. A persistent +QR pairing and protected token storage use DPAPI on Windows, Keychain on macOS +and Secret Service on Linux. A persistent service, full DSL validation, other upstream integrations and a signed installer remain planned. The wiki's concept pages describe the intended complete product; the getting-started page records what is implemented now. -CI builds and tests Windows, Linux and macOS; Windows CI produces a self-contained -preview artifact. Wiki publishing uses the built-in Actions token. A weekly +CI builds and tests Windows, Linux and macOS; CI publishes self-contained x64 and ARM64 +preview archives for all three platforms. Wiki publishing uses the built-in Actions token. A weekly upstream check opens or updates a review issue when the original repository changes. See [automation setup](docs/wiki/Project-Setup.md). diff --git a/docs/decisions/0003-platform-support.md b/docs/decisions/0003-platform-support.md new file mode 100644 index 0000000..3366633 --- /dev/null +++ b/docs/decisions/0003-platform-support.md @@ -0,0 +1,17 @@ +# ADR 0003: Windows, macOS and Linux preview support + +Status: accepted, 2026-10-23, following the explicit request for multiple platforms. + +The application targets Windows, macOS and Linux with shared portable logic. +Runtime-specific credential adapters use DPAPI, native Keychain SecItem APIs and +Secret Service respectively. Unix link documents use authenticated AES-256-GCM +with per-configuration-path keys in the native vault. No plaintext fallback is +provided. Windows retains its existing path and format. + +Copilot hook files include PowerShell and Bash commands. Current-user .NET named +pipes provide local IPC on all three platforms. Platform CI must exercise native +credentials, hook forwarding and simulated device writes, and package x64/ARM64 +archives with execution checks for each runner's native architecture. + +This supersedes the initial Windows-only delivery priority. It does not promise +parity for upstream OS-specific helpers, raw USB, firmware, installers or services. diff --git a/docs/wiki/Compatibility.md b/docs/wiki/Compatibility.md index a9dc3c6..9f36ab6 100644 --- a/docs/wiki/Compatibility.md +++ b/docs/wiki/Compatibility.md @@ -2,17 +2,22 @@ Reference: inteliwear/sidepulse at [ffb1d3c2f3eed3b7e80e32d7876a7e1d67bd5dfb](https://github.com/inteliwear/sidepulse/commit/ffb1d3c2f3eed3b7e80e32d7876a7e1d67bd5dfb), -checked 2026-10-23. Every .NET row below is **planned**, not implemented. +checked 2026-10-23. The inventory below records the full planned scope. The preview already implements +firmware size limits, writable USB files, iPhone pairing/silent delivery, status +profiles, Copilot hooks, in-memory session aggregation and native credential +storage. Full LED grammar, visible notifications, broadcast and remaining +integrations remain planned. See [[Getting-Started]] and [[Platforms]] for +implemented commands and test boundaries. | Area | .NET plan | Verification required | |---|---|---| | LED text language and limits | M1 | Port upstream vectors, escapes, 512-byte/20-line boundaries | -| Writable USB volumes and discovery | M1 Windows | Dot hardware, volume labels, locked/removed media | +| Writable USB volumes and discovery | Preview, all three OSes | Dot hardware, volume labels, locked/removed media | | iPhone QR/token pairing and linked targets | M1 | Original app, production/development tokens, persistence | | LED bridge delivery and visible notifications | M1 | Silent versus visible delivery, timeouts and failure semantics | | Destination selection, stdin and broadcast | M1 | Compatible ambiguity checks and explicit broadcast | | Built-in animations and LED counts | M1 | Source attribution, Dot/Pro geometry and brightness | -| Copilot CLI hooks | M1 extension | Event payload fixtures and real Windows CLI | +| Copilot CLI hooks | Preview, Bash and PowerShell | Event fixtures and real CLI on each OS | | Codex, Claude, Cursor, Grok, Junie | M2 parity | Separate hook schemas, installation and permissions per provider | | Session collection, history and aggregation | M1/M2 | Concurrent sessions, stale events and restart | | Optional transcript recovery | M2 investigation | Privacy, format drift and opt-in behavior | diff --git a/docs/wiki/Configuration.md b/docs/wiki/Configuration.md index 816d991..9d80c42 100644 --- a/docs/wiki/Configuration.md +++ b/docs/wiki/Configuration.md @@ -1,4 +1,4 @@ -> Implementation update: Windows links now use a separate current-user DPAPI store. +> Implementation update: Links use native credentials: Windows DPAPI, macOS Keychain or Linux Secret Service. > Alias/default management and the `SIDEPULSE_NET_HOME` override are implemented. > See [[Getting-Started]] for working commands. The remainder describes the target configuration design. diff --git a/docs/wiki/Devices-and-Protocols.md b/docs/wiki/Devices-and-Protocols.md index 6233162..53b96ae 100644 --- a/docs/wiki/Devices-and-Protocols.md +++ b/docs/wiki/Devices-and-Protocols.md @@ -1,5 +1,5 @@ > Implementation update: QR/SSE pairing for the default iPhone bridge and encrypted -> Windows link storage are implemented. Android and custom bridge origins remain planned. +> native link storage are implemented on Windows, macOS and Linux. Android and custom bridge origins remain planned. > Hardware and TestFlight app verification are still pending. See [[Getting-Started]]. # Devices and protocols diff --git a/docs/wiki/Getting-Started.md b/docs/wiki/Getting-Started.md index 77caec3..c022666 100644 --- a/docs/wiki/Getting-Started.md +++ b/docs/wiki/Getting-Started.md @@ -2,7 +2,7 @@ The first implementation is an alpha preview. USB discovery/writes, status profiles, raw programs, silent iPhone bridge delivery with an existing APNS token, session -aggregation, QR pairing, Windows-protected phone links, diagnostics and a foreground +aggregation, QR pairing, native protected phone links, diagnostics and a foreground Copilot CLI host are implemented. Background-service installation, full LED grammar validation, animation rendering, migration and other agent integrations remain planned. @@ -23,9 +23,13 @@ Publish a Windows application without a Python or .NET runtime requirement: dotnet publish src/SidePulse.Cli -c Release -r win-x64 --self-contained true -o artifacts/win-x64 ``` -Run `artifacts/win-x64/sidepulse-net.exe`. The CI Windows job also publishes a -self-contained folder as an Actions artifact. This is a preview build, not a signed -installer or stable release. +Run `artifacts/win-x64/sidepulse-net.exe`. For macOS or Linux, replace `win-x64` +with the desired runtime identifier and run `./sidepulse-net`. CI publishes +archives for `win-x64`, `win-arm64`, `osx-x64`, `osx-arm64`, `linux-x64` and +`linux-arm64`. Windows archives use ZIP; Unix archives use tar.gz to retain +executable permissions. Extract the inner archive after downloading the Actions +artifact. See [[Platforms]] for prerequisites and validation limits. +These are unsigned preview builds, not installers or stable releases. ## USB device @@ -41,7 +45,7 @@ Only one writer should control a device. Physical device behavior still needs Windows hardware verification. Validation checks the 512-byte/20-line envelope; the firmware remains responsible for LED syntax validation. -## Pair an iPhone on Windows +## Pair an iPhone ```powershell sidepulse-net link pair iphone @@ -57,14 +61,26 @@ registration events. `--timeout 60` shortens the wait; `--no-qr` shows only the Treat the live pairing URI as temporary pairing access; keep it out of shared logs. Actual QR scanning with the TestFlight app still requires device verification. -The entire link document, including names and tokens, is encrypted with Windows -DPAPI for the current user. It is stored in `%LOCALAPPDATA%\SidePulse.NET\links.dpapi`. -There is no plaintext fallback. The store uses exclusive locking and atomic encrypted -file replacement. It preserves an unreadable store rather than overwriting it. -`SIDEPULSE_NET_HOME` can select another absolute directory, for isolated configurations -or testing; this does not make DPAPI credentials portable to another Windows user. +The entire link document, including names and tokens, is protected by the native +credential system. Windows keeps the existing DPAPI format at +`%LOCALAPPDATA%\SidePulse.NET\links.dpapi`. macOS and Linux encrypt a +`links.encrypted` file using AES-256-GCM, with a random key held in Keychain or +Secret Service respectively. The platform's local-application-data directory is +used unless `SIDEPULSE_NET_HOME` selects another absolute directory. + +There is no plaintext fallback. The store uses exclusive locking and atomic +encrypted replacement, with owner-only permissions for new Unix files. Missing +keys and unreadable stores are preserved, not reset. Vault keys are scoped to the +absolute store path; moving a Unix store requires pairing again or restoring its +original location. Copying the encrypted file alone is not a credential migration. The app does not read or modify the Python port's configuration. +macOS needs an unlocked Keychain and access for the executable. Linux needs +`secret-tool`, an unlocked Secret Service keyring and a working D-Bus session. +On Debian/Ubuntu, install `libsecret-tools`; desktop sessions commonly provide the +keyring service. Headless Linux needs its own unlocked Secret Service session, or +can use environment-token delivery without saved links. See [[Platforms]]. + The first linked phone becomes the default. Selection is explicit via `--phone`; commands without a phone option continue to discover USB devices. @@ -88,7 +104,7 @@ presence; it sends no device writes or network requests. If you already have an iPhone token, set `SIDEPULSE_TOKEN` in the current process environment. Keep the value out of command history, source control and screenshots. -Save it securely on Windows, or use it directly without persistence: +Save it securely using the native credential vault, or use it directly without persistence: ```powershell sidepulse-net link import iphone --token-env SIDEPULSE_TOKEN @@ -96,8 +112,9 @@ sidepulse-net state working --token-env SIDEPULSE_TOKEN sidepulse-net host --token-env SIDEPULSE_TOKEN ``` -Saved phone links and pairing currently require Windows. Linux/macOS support -environment-token delivery without persistent storage. `--device`, `--phone` and +Saved links and pairing are available on Windows, macOS and Linux when the native +credential backend is available. Environment-token delivery needs no persistent +credential backend. `--device`, `--phone` and `--token-env` are mutually exclusive. A dry run previews the program without reading credentials or validating that a saved phone exists. @@ -106,7 +123,7 @@ success is bridge acceptance, not proof of delivery to the hardware. Android and custom bridge servers are not implemented yet. Pairing and delivery follow the upstream protocol at the revision in `upstream.json`. -## Copilot CLI on Windows +## Copilot CLI Start the host in a terminal, choosing either USB or the phone environment token: @@ -121,6 +138,16 @@ New-Item -ItemType Directory -Force "$env:USERPROFILE\.copilot\hooks" | Out-Null sidepulse-net hook-config --exe C:\Tools\SidePulse.NET\sidepulse-net.exe --output "$env:USERPROFILE\.copilot\hooks\sidepulse-net.json" ``` +On macOS/Linux, use: + +```bash +mkdir -p ~/.copilot/hooks +sidepulse-net hook-config --exe /absolute/path/to/sidepulse-net --output ~/.copilot/hooks/sidepulse-net.json +sidepulse-net host --phone default +``` + +Generated files include both Bash and PowerShell wrappers. Bash inherits JSON +stdin and always returns zero, including when the executable is unavailable. If `COPILOT_HOME` is set, use its `hooks` directory instead. Existing files are never overwritten. Restart Copilot CLI after installation. PowerShell 7 is required for Copilot's Windows shell hooks. Remove this file and restart Copilot to uninstall. diff --git a/docs/wiki/Platforms.md b/docs/wiki/Platforms.md new file mode 100644 index 0000000..f6e481b --- /dev/null +++ b/docs/wiki/Platforms.md @@ -0,0 +1,52 @@ +# Platform support + +The preview supports Windows, macOS and Linux. The core, terminal UI, QR/SSE +pairing, phone delivery, local host, hook generation and mounted USB file transport +share one codebase. Native credentials are selected at runtime. + +| Platform | Saved phone protection | Requirements | Archives | +|---|---|---|---| +| Windows | Current-user DPAPI; existing store format retained | Windows desktop user profile | x64, ARM64 ZIP | +| macOS | Native SecItem Keychain API holds an AES-256-GCM key | Unlocked Keychain and access for the executable | x64, ARM64 tar.gz | +| Linux | Secret Service holds an AES-256-GCM key | `secret-tool`, unlocked keyring, D-Bus session; glibc distribution | x64, ARM64 tar.gz | + +Linux uses the fixed `/usr/bin/secret-tool` or `/bin/secret-tool` helper without a +shell. Encryption keys pass through stdin/stdout, never command arguments. The +helper has a bounded timeout. macOS calls Security/CoreFoundation directly and +fails with a useful error if Keychain access cannot proceed without a prompt. +Unlock the login Keychain and grant application access before starting the host. +There is no plaintext key file or fallback to unprotected persistence. + +A key is stored per absolute configuration path. Removing a phone removes the +local link, not the native encryption key or the remote registration. A missing +vault key does not cause replacement of an existing encrypted store. New Unix +store and lock files have owner-only permissions. Existing Windows DPAPI stores +continue to use `links.dpapi`; Unix stores use `links.encrypted`. + +The CLI's `doctor` command reports backend availability and checks an existing +store. It does not create an encryption key or prove that an absent store can be +created in a locked vault. `--token-env` remains available on headless machines +without a credential service. No root/admin access is required by the application; +the user must have write permission for the mounted device and config directory. + +## Tests and distribution + +CI runs builds, behavioral tests and simulated USB/host/CLI checks on Windows, +Linux and macOS. Linux CI provisions an isolated D-Bus/keyring session; macOS CI +creates and deletes a temporary Keychain. Native encryption and phone management +are exercised on all three. Bash hook commands are executed on Unix runners. Host tests reject competing +instances and verify restart after forced termination. Unix IPC uses a short +per-user private directory, an exclusive host lease and current-user-only sockets. + +Each platform produces x64 and ARM64 archives. CI executes the archive matching +its runner architecture; the other architecture is cross-published. This does +not establish hardware verification for every architecture. Alpine/musl, +32-bit systems, macOS notarization, signed Windows installers and OS service +installation are not included in this preview. + +USB discovery uses mounted drives and the existing `LEDS.LED` file. Explicit +`--device` paths work when autodiscovery cannot find a mount. On macOS use a +mounted path such as `/Volumes/SidePulseDot`; on Linux use its actual mount path, +for example `/media/$USER/SidePulseDot`. Do not run two writers for one device. +Actual hardware, TestFlight scans and real Copilot installations still require +manual verification on each target OS. diff --git a/docs/wiki/Product-Concept.md b/docs/wiki/Product-Concept.md index 1086c46..d71b7fc 100644 --- a/docs/wiki/Product-Concept.md +++ b/docs/wiki/Product-Concept.md @@ -15,7 +15,7 @@ A background host coordinates sessions and outputs. ## First milestone -Windows-native, self-contained distribution; direct writable USB devices; iPhone +Self-contained Windows, macOS and Linux distributions; direct writable USB devices; iPhone pairing and bridge delivery; core LED language; manual state commands; Copilot CLI integration; a device/session dashboard; and diagnostics. diff --git a/docs/wiki/_Sidebar.md b/docs/wiki/_Sidebar.md index 410f1ba..538bcc2 100644 --- a/docs/wiki/_Sidebar.md +++ b/docs/wiki/_Sidebar.md @@ -13,3 +13,5 @@ - [[Upstream-and-Licensing]] - [[Getting started|Getting-Started]] + +- [[Platforms]] diff --git a/scripts/cli_smoke.py b/scripts/cli_smoke.py index 2e0ee30..276f4e4 100644 --- a/scripts/cli_smoke.py +++ b/scripts/cli_smoke.py @@ -73,6 +73,9 @@ def run(*args, input=None): time.sleep(0.1) else: raise AssertionError('Host did not deliver the working state') + competing = subprocess.run([exe, 'host', '--device', directory, '--plain'], + text=True, capture_output=True, timeout=10, env=child_env) + assert competing.returncode != 0, 'A second host must not take ownership' run('hook', 'agentStop', input=json.dumps({'sessionId': 'smoke', 'timestamp': 100, 'stopReason': 'end_turn'})) for _ in range(30): if '#00ff66' in target.read_text(): @@ -83,6 +86,20 @@ def run(*args, input=None): finally: host.terminate() host.wait(timeout=10) + # A forcibly terminated host must be restartable without manual socket cleanup. + restarted = subprocess.Popen([exe, 'host', '--device', directory, '--plain'], stdout=log, stderr=log) + try: + for attempt in range(30): + assert restarted.poll() is None, 'Restarted host exited: ' + (Path(directory) / 'host.log').read_text() + run('hook', 'userPromptSubmitted', input=json.dumps({'sessionId': 'restart', 'timestamp': 200 + attempt})) + if '#00e5ff' in target.read_text(): + break + time.sleep(0.1) + else: + raise AssertionError('Restarted host did not accept hook input') + finally: + restarted.terminate() + restarted.wait(timeout=10) print('CLI, hook isolation, configuration and host/device smoke checks passed.') diff --git a/src/SidePulse.Cli/Hooks.cs b/src/SidePulse.Cli/Hooks.cs index d188d01..69ef9f6 100644 --- a/src/SidePulse.Cli/Hooks.cs +++ b/src/SidePulse.Cli/Hooks.cs @@ -13,8 +13,46 @@ namespace SidePulse.Cli; public static class LocalPipe { // Per-user namespace plus OS-enforced current-user access on server and client. - public static string Name => "sidepulse-net-" + Convert.ToHexString(SHA256.HashData( + private static string UserKey => Convert.ToHexString(SHA256.HashData( Encoding.UTF8.GetBytes(Environment.UserDomainName + "\\" + Environment.UserName)))[..20]; + // Use a short private path to stay below Unix-domain socket limits on macOS. + private static string UnixDirectory => Path.Combine("/tmp", "sidepulse-net-" + UserKey); + public static string Name => OperatingSystem.IsWindows() ? "sidepulse-net-" + UserKey : Path.Combine(UnixDirectory, "events"); + public static IDisposable AcquireHostLease() + { + if (OperatingSystem.IsWindows()) return new Lease(null, null); + Directory.CreateDirectory(UnixDirectory, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute); + if ((File.GetAttributes(UnixDirectory) & FileAttributes.ReparsePoint) != 0 + || (File.GetUnixFileMode(UnixDirectory) & (UnixFileMode.GroupRead | UnixFileMode.GroupWrite | UnixFileMode.GroupExecute + | UnixFileMode.OtherRead | UnixFileMode.OtherWrite | UnixFileMode.OtherExecute)) != 0) + throw new IOException("The local IPC directory must be a private, non-symlink directory for the current user."); + FileStream gate; + try + { + gate = new FileStream(Path.Combine(UnixDirectory, "host.lock"), new FileStreamOptions + { + Mode = FileMode.OpenOrCreate, Access = FileAccess.ReadWrite, Share = FileShare.None, + UnixCreateMode = UnixFileMode.UserRead | UnixFileMode.UserWrite + }); + } + catch (IOException) { throw new IOException("A SidePulse.NET host is already running for this user."); } + try + { + // A held lease proves no other cooperating host can own this endpoint. + // Remove the socket left by a killed host; never unlink an active host's socket. + File.Delete(Name); + return new Lease(gate, Name); + } + catch { gate.Dispose(); throw; } + } + private sealed class Lease(FileStream? gate, string? path) : IDisposable + { + public void Dispose() + { + try { if (path is not null) File.Delete(path); } + finally { gate?.Dispose(); } + } + } public const int MaximumMessageBytes = 16384; } @@ -92,6 +130,7 @@ public override async Task ExecuteAsync(CommandContext context, HostSetting try { // FirstPipeInstance prevents competing hosts from accepting alternate events. + using var lease = LocalPipe.AcquireHostLease(); using var pipe = new NamedPipeServerStream(LocalPipe.Name, PipeDirection.In, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous | PipeOptions.CurrentUserOnly | PipeOptions.FirstPipeInstance); while (!shutdown.IsCancellationRequested) From 4ea740be46d34efe30f7ccece18168a128885340 Mon Sep 17 00:00:00 2001 From: Gordon Breuer Date: Fri, 23 Oct 2026 21:45:20 +0200 Subject: [PATCH 08/26] feat: add Codex, Claude and Kiro hooks with managed setup and host lifecycle --- .github/workflows/dotnet-ci.yml | 5 + scripts/agent_smoke.py | 105 +++++++++++++++++++ src/SidePulse.Cli/Agents.cs | 87 ++++++++++++++++ src/SidePulse.Cli/Hooks.cs | 53 +++++----- src/SidePulse.Cli/HostLogs.cs | 70 +++++++++++++ src/SidePulse.Cli/HostManagement.cs | 99 ++++++++++++++++++ src/SidePulse.Cli/Program.cs | 24 ++++- src/SidePulse.Cli/SidePulse.Cli.csproj | 2 +- src/SidePulse.Core/AgentEvents.cs | 55 ++++++++++ src/SidePulse.Core/HookConfiguration.cs | 80 +++++++++++++++ src/SidePulse.Core/HookInstallation.cs | 108 ++++++++++++++++++++ src/SidePulse.Core/Sessions.cs | 14 +-- tests/SidePulse.Tests/AgentTests.cs | 130 ++++++++++++++++++++++++ 13 files changed, 800 insertions(+), 32 deletions(-) create mode 100644 scripts/agent_smoke.py create mode 100644 src/SidePulse.Cli/Agents.cs create mode 100644 src/SidePulse.Cli/HostLogs.cs create mode 100644 src/SidePulse.Cli/HostManagement.cs create mode 100644 src/SidePulse.Core/AgentEvents.cs create mode 100644 src/SidePulse.Core/HookConfiguration.cs create mode 100644 src/SidePulse.Core/HookInstallation.cs create mode 100644 tests/SidePulse.Tests/AgentTests.cs diff --git a/.github/workflows/dotnet-ci.yml b/.github/workflows/dotnet-ci.yml index 00e48ea..1a88711 100644 --- a/.github/workflows/dotnet-ci.yml +++ b/.github/workflows/dotnet-ci.yml @@ -92,6 +92,9 @@ jobs: run: | $binary = if ($IsWindows) { 'sidepulse-net.exe' } else { 'sidepulse-net' } python scripts/cli_smoke.py "src/SidePulse.Cli/bin/Release/net10.0/$binary" + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + python scripts/agent_smoke.py "src/SidePulse.Cli/bin/Release/net10.0/$binary" + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } - name: Publish and exercise self-contained previews shell: pwsh run: | @@ -111,6 +114,8 @@ jobs: $binary = if ($IsWindows) { 'sidepulse-net.exe' } else { 'sidepulse-net' } python scripts/cli_smoke.py "$destination/$binary" if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + python scripts/agent_smoke.py "$destination/$binary" + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } } if ($IsWindows) { Compress-Archive -Path "$destination/*" -DestinationPath "artifacts/sidepulse-net-$rid.zip" diff --git a/scripts/agent_smoke.py b/scripts/agent_smoke.py new file mode 100644 index 0000000..678656b --- /dev/null +++ b/scripts/agent_smoke.py @@ -0,0 +1,105 @@ +"""Exercise native generated wrappers, owned hook setup and detached host control, without agent accounts.""" +import json +import os +from pathlib import Path +import shlex +import subprocess +import sys +import tempfile +import time + + +def main(): + exe = str(Path(sys.argv[1]).resolve()) + with tempfile.TemporaryDirectory(prefix="SidePulse agents ü ") as directory: + root = Path(directory) + env = os.environ.copy() + env['SIDEPULSE_NET_HOME'] = str(root / 'state') + + def run(*args, timeout=15): + result = subprocess.run([exe, *args], text=True, capture_output=True, timeout=timeout, env=env) + assert result.returncode == 0, (args, result.stdout, result.stderr) + return result.stdout + + def status(): + return json.loads(run('host', 'status', '--json')) + + target = root / 'LEDS.LED' + target.write_text('off') + configs = {} + originals = {} + for provider in ('copilot', 'codex', 'claude', 'kiro'): + path = root / (provider + '.json') + original = '{"unrelated":"private-config-key","hooks":{}}\n' if provider in ('codex', 'claude') else None + if original: + path.write_text(original) + originals[provider] = original + preview = run('agents', 'install', provider, '--exe', exe, '--config', str(path), '--dry-run', '--json') + assert 'private-config-key' not in preview + assert (path.read_text() if path.exists() else None) == original + run('agents', 'install', provider, '--exe', exe, '--config', str(path)) + assert json.loads(run('agents', 'status', provider, '--config', str(path), '--json'))['State'] == 'installed' + configs[provider] = (path, json.loads(path.read_text())) + + started = False + try: + first = json.loads(run('host', 'start', '--exe', exe, '--device', directory, '--json', timeout=25)) + started = True + assert first['Running'] + assert status()['Running'] + second = json.loads(run('host', 'start', '--exe', exe, '--device', directory, '--json')) + assert second['ProcessId'] == first['ProcessId'] + + def send(provider, event): + configuration = configs[provider][1] + if provider == 'copilot': + entry = configuration['hooks'][event][0] + command = entry['powershell'] if os.name == 'nt' else entry['bash'] + elif provider == 'kiro': + command = next(h['action']['command'] for h in configuration['hooks'] if h['trigger'] == event) + else: + command = configuration['hooks'][event][0]['hooks'][0]['command'] + payload = {'session_id': 'same-id', 'prompt': 'DO-NOT-LOG-THIS', 'stopReason': 'end_turn'} + if provider == 'copilot': + payload.update(sessionId='same-id', timestamp=time.time_ns() // 1000000) + if os.name == 'nt': + arguments = ['pwsh', '-NoLogo', '-NoProfile', '-NonInteractive', '-Command', command] if provider == 'copilot' else shlex.split(command) + else: + arguments = ['bash', '-c', command] + result = subprocess.run(arguments, input=json.dumps(payload), text=True, capture_output=True, timeout=10, env=env) + assert result.returncode == 0 and not result.stdout and not result.stderr, (provider, result.stdout, result.stderr) + + for provider in configs: + send(provider, 'userPromptSubmitted' if provider == 'copilot' else 'UserPromptSubmit') + for _ in range(30): + snapshot = status() + if len(snapshot['Sessions']) == 4: + break + time.sleep(0.1) + assert len(snapshot['Sessions']) == 4, snapshot + assert {s['Provider'] for s in snapshot['Sessions']} == {'Copilot', 'Codex', 'Claude', 'Kiro'} + send('claude', 'Stop') + assert status()['State'] == 'Working' + for provider in ('copilot', 'codex', 'kiro'): + send(provider, 'agentStop' if provider == 'copilot' else 'Stop') + for _ in range(30): + if status()['State'] == 'Done': + break + time.sleep(0.1) + assert status()['State'] == 'Done' + run('host', 'stop', '--json') + started = False + assert not status()['Running'] + logs = run('host', 'logs', '--tail', '10') + assert 'DO-NOT-LOG-THIS' not in logs + finally: + if started: + run('host', 'stop', '--json') + for provider, (path, _) in configs.items(): + run('agents', 'uninstall', provider, '--config', str(path)) + assert (path.read_text() if path.exists() else None) == originals[provider] + print('Agent wrappers, mixed-session isolation, hook setup/backups and detached host lifecycle passed.') + + +if __name__ == '__main__': + main() diff --git a/src/SidePulse.Cli/Agents.cs b/src/SidePulse.Cli/Agents.cs new file mode 100644 index 0000000..7c24192 --- /dev/null +++ b/src/SidePulse.Cli/Agents.cs @@ -0,0 +1,87 @@ +using System.ComponentModel; +using SidePulse.Core; +using Spectre.Console; +using Spectre.Console.Cli; + +namespace SidePulse.Cli; + +public sealed class AgentsListCommand : Command +{ + public override int Execute(CommandContext context, HostActionSettings settings, CancellationToken cancellationToken) + { + if (settings.Json) Output.Print(AgentEvents.Capabilities); + else + { + var table = new Table().Border(TableBorder.Rounded).AddColumn("Agent").AddColumn("Target").AddColumn("Notes"); + foreach (var agent in AgentEvents.Capabilities) table.AddRow(agent.Provider.ToString(), agent.Target, Markup.Escape(agent.Limitations)); + AnsiConsole.Write(table); + } + return 0; + } +} +public sealed class AgentSettings : CommandSettings +{ + [CommandArgument(0, "")] + public AgentProvider Agent { get; init; } + [CommandOption("--exe ")] + public string Executable { get; init; } = Environment.ProcessPath ?? "sidepulse-net"; + [CommandOption("--config ")] + [Description("Explicit provider configuration file; useful for project-scoped or isolated setup.")] + public string? Config { get; init; } + [CommandOption("--dry-run")] + public bool DryRun { get; init; } + [CommandOption("--json")] + public bool Json { get; init; } + public override ValidationResult Validate() => Enum.IsDefined(Agent) ? ValidationResult.Success() : ValidationResult.Error("Unknown agent."); + public string Target + { + get + { + if (Config is not null) return Path.GetFullPath(Config); + var user = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile); + string Home(string variable, string fallback) => Environment.GetEnvironmentVariable(variable) is { Length: > 0 } home ? home : Path.Combine(user, fallback); + return Agent switch + { + AgentProvider.Copilot => Path.Combine(Home("COPILOT_HOME", ".copilot"), "hooks", "sidepulse-net.json"), + AgentProvider.Codex => Path.Combine(Home("CODEX_HOME", ".codex"), "hooks.json"), + AgentProvider.Claude => Path.Combine(user, ".claude", "settings.json"), + _ => Path.Combine(user, ".kiro", "hooks", "sidepulse-net.json") + }; + } + } + public HookInstallation Installation => new(Path.Combine(Path.GetDirectoryName(LinkStore.DefaultPath)!, "integrations")); +} +public sealed class AgentInstallCommand : Command +{ + public override int Execute(CommandContext context, AgentSettings settings, CancellationToken cancellationToken) + { + var generated = HookConfiguration.Generate(settings.Agent, HookConfiguration.Executable(settings.Executable), OperatingSystem.IsWindows()); + var status = settings.Installation.Install(settings.Target, settings.Agent, generated, settings.DryRun); + if (settings.Json) Output.Print(new { status, managedHooks = settings.DryRun ? generated : null }); + else + { + AnsiConsole.WriteLine($"{status.State}: {status.Target}"); + if (settings.DryRun) AnsiConsole.Write(new Text(generated.ToJsonString(Output.Json))); + else AnsiConsole.WriteLine("Restart the agent and review its hook trust prompts. Codex requires /hooks review; no trust or permissions were changed."); + } + return 0; + } +} +public sealed class AgentStatusCommand : Command +{ + public override int Execute(CommandContext context, AgentSettings settings, CancellationToken cancellationToken) + { + var status = settings.Installation.Status(settings.Target); + if (settings.Json) Output.Print(status); else AnsiConsole.WriteLine($"{status.State}: {status.Target}"); + return 0; + } +} +public sealed class AgentUninstallCommand : Command +{ + public override int Execute(CommandContext context, AgentSettings settings, CancellationToken cancellationToken) + { + var status = settings.Installation.Uninstall(settings.Target, settings.DryRun); + if (settings.Json) Output.Print(status); else AnsiConsole.WriteLine($"{status.State}: {status.Target}"); + return 0; + } +} diff --git a/src/SidePulse.Cli/Hooks.cs b/src/SidePulse.Cli/Hooks.cs index 69ef9f6..0410f03 100644 --- a/src/SidePulse.Cli/Hooks.cs +++ b/src/SidePulse.Cli/Hooks.cs @@ -60,6 +60,8 @@ public sealed class HookSettings : CommandSettings { [CommandArgument(0, "")] public string Event { get; init; } = ""; + [CommandOption("--source ")] + public AgentProvider Source { get; init; } = AgentProvider.Copilot; } public sealed class HookCommand : AsyncCommand { @@ -78,14 +80,14 @@ public override async Task ExecuteAsync(CommandContext context, HookSetting length += read; } if (length > LocalPipe.MaximumMessageBytes) return 0; - var item = CopilotEvents.Parse(settings.Event, new string(buffer, 0, length)); + var item = AgentEvents.Parse(settings.Source, settings.Event, new string(buffer, 0, length)); if (item is null) return 0; var bytes = JsonSerializer.SerializeToUtf8Bytes(item); if (bytes.Length > LocalPipe.MaximumMessageBytes) return 0; using var pipe = new NamedPipeClientStream(".", LocalPipe.Name, PipeDirection.Out, PipeOptions.Asynchronous | PipeOptions.CurrentUserOnly); await pipe.ConnectAsync(timeout.Token); - await pipe.WriteAsync(bytes, timeout.Token); + await pipe.WriteAsync(bytes.Concat(new byte[] { 10 }).ToArray(), timeout.Token); await pipe.FlushAsync(timeout.Token); } catch (Exception) { /* A missing host or invalid hook input must not break Copilot. */ } @@ -94,6 +96,10 @@ public override async Task ExecuteAsync(CommandContext context, HookSetting } public sealed class HostSettings : TargetSettings { + [CommandOption("--log-file ")] + public string? LogFile { get; init; } + [CommandOption("--background")] + public bool Background { get; init; } [CommandOption("--plain")] [Description("Write plain state changes instead of terminal panels.")] public bool Plain { get; init; } @@ -102,6 +108,7 @@ public sealed class HostCommand : AsyncCommand { public override async Task ExecuteAsync(CommandContext context, HostSettings settings, CancellationToken cancellationToken) { + if (settings.Background) HostLogs.Detach(); using var shutdown = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); ConsoleCancelEventHandler cancel = (_, args) => { args.Cancel = true; shutdown.Cancel(); }; Console.CancelKeyPress += cancel; @@ -131,7 +138,7 @@ public override async Task ExecuteAsync(CommandContext context, HostSetting { // FirstPipeInstance prevents competing hosts from accepting alternate events. using var lease = LocalPipe.AcquireHostLease(); - using var pipe = new NamedPipeServerStream(LocalPipe.Name, PipeDirection.In, 1, + using var pipe = new NamedPipeServerStream(LocalPipe.Name, PipeDirection.InOut, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous | PipeOptions.CurrentUserOnly | PipeOptions.FirstPipeInstance); while (!shutdown.IsCancellationRequested) { @@ -141,14 +148,27 @@ public override async Task ExecuteAsync(CommandContext context, HostSetting using var deadline = CancellationTokenSource.CreateLinkedTokenSource(shutdown.Token); deadline.CancelAfter(TimeSpan.FromSeconds(1)); using var message = new MemoryStream(); - var buffer = new byte[4096]; + var buffer = new byte[1]; while (message.Length <= LocalPipe.MaximumMessageBytes) { var count = await pipe.ReadAsync(buffer, deadline.Token); - if (count == 0) break; + if (count == 0 || buffer[0] == 10) break; message.Write(buffer, 0, count); } if (message.Length > LocalPipe.MaximumMessageBytes) continue; + using var request = JsonDocument.Parse(message.ToArray()); + if (request.RootElement.TryGetProperty("Command", out var command)) + { + var action = command.GetString(); + if (action is "status" or "stop") + { + var response = JsonSerializer.SerializeToUtf8Bytes(new HostSnapshot(true, Environment.ProcessId, sessions.State, sessions.Snapshot), Output.Json); + await pipe.WriteAsync(response, deadline.Token); + await pipe.FlushAsync(deadline.Token); + if (action == "stop") shutdown.Cancel(); + } + continue; + } var item = JsonSerializer.Deserialize(message.ToArray()); if (item is null || !Enum.IsDefined(item.State) || !sessions.Apply(item)) continue; var state = sessions.State; @@ -156,9 +176,9 @@ public override async Task ExecuteAsync(CommandContext context, HostSetting else if (settings.Plain || Console.IsOutputRedirected) Console.WriteLine($"{DateTimeOffset.Now:HH:mm:ss} {state} ({sessions.Snapshot.Count} sessions)"); else { - var table = new Table().Border(TableBorder.Rounded).AddColumn("Session").AddColumn("Status"); + var table = new Table().Border(TableBorder.Rounded).AddColumn("Agent").AddColumn("Session").AddColumn("Status"); foreach (var session in sessions.Snapshot) - table.AddRow(Markup.Escape(session.Id), $"[{Output.Color(session.State)}]{session.State}[/]"); + table.AddRow(session.Provider.ToString(), Markup.Escape(session.Id), $"[{Output.Color(session.State)}]{session.State}[/]"); AnsiConsole.Write(table); } // Delivery runs separately so bridge latency cannot block pipe acceptance. @@ -170,7 +190,7 @@ public override async Task ExecuteAsync(CommandContext context, HostSetting queued = state; } } - catch (Exception ex) when (ex is JsonException or IOException or OperationCanceledException) { } + catch (Exception ex) when (ex is JsonException or InvalidOperationException or IOException or OperationCanceledException) { } finally { pipe.Disconnect(); } } } @@ -198,21 +218,8 @@ public sealed class HookConfigCommand : Command { public override int Execute(CommandContext context, HookConfigSettings settings, CancellationToken cancellationToken) { - var exe = Path.GetFullPath(settings.Executable); - if (!File.Exists(exe) || !Path.GetFileNameWithoutExtension(exe).Equals("sidepulse-net", StringComparison.OrdinalIgnoreCase)) - throw new ArgumentException("Use --exe with the path of a published sidepulse-net executable."); - var hooks = new Dictionary(); - foreach (var name in new[] { "sessionStart", "userPromptSubmitted", "preToolUse", "postToolUse", "agentStop", "errorOccurred", "postToolUseFailure", "sessionEnd", "notification" }) - { - var command = "$ErrorActionPreference = 'SilentlyContinue'; try { $input | & '" + exe.Replace("'", "''") - + "' hook " + name + " | Out-Null } catch {}; exit 0"; - var quoted = "'" + exe.Replace("'", "'\"'\"'") + "'"; - var bash = quoted + " hook " + name + " >/dev/null 2>&1; exit 0"; - var entry = new Dictionary { ["type"] = "command", ["powershell"] = command, ["bash"] = bash, ["timeoutSec"] = 2 }; - if (name == "notification") entry["matcher"] = "permission_prompt|elicitation_dialog"; - hooks[name] = new[] { entry }; - } - var json = JsonSerializer.Serialize(new { version = 1, hooks }, Output.Json) + Environment.NewLine; + var exe = HookConfiguration.Executable(settings.Executable); + var json = HookConfiguration.Generate(AgentProvider.Copilot, exe, OperatingSystem.IsWindows()).ToJsonString(Output.Json) + Environment.NewLine; if (settings.OutputPath is { } path) { using var file = new FileStream(path, FileMode.CreateNew, FileAccess.Write); diff --git a/src/SidePulse.Cli/HostLogs.cs b/src/SidePulse.Cli/HostLogs.cs new file mode 100644 index 0000000..b7a97a3 --- /dev/null +++ b/src/SidePulse.Cli/HostLogs.cs @@ -0,0 +1,70 @@ +using System.ComponentModel; +using System.Runtime.InteropServices; +using System.Text; +using SidePulse.Core; +using Spectre.Console; +using Spectre.Console.Cli; + +namespace SidePulse.Cli; + +public static class HostLogs +{ + public static string PathName => Path.Combine(Path.GetDirectoryName(LinkStore.DefaultPath)!, "host", "host.log"); + public static IDisposable? Redirect(string[] args) + { + if (args.Length < 2 || args[0] != "host" || args[1] != "run") return null; + var position = Array.IndexOf(args, "--log-file"); + if (position < 0 || position + 1 >= args.Length) return null; + var writer = new RollingWriter(Path.GetFullPath(args[position + 1])); + var originalOut = Console.Out; + var originalError = Console.Error; + var sync = TextWriter.Synchronized(writer); + Console.SetOut(sync); + Console.SetError(sync); + return new Restore(originalOut, originalError, sync); + } + private sealed class Restore(TextWriter output, TextWriter error, TextWriter writer) : IDisposable + { + public void Dispose() { Console.SetOut(output); Console.SetError(error); writer.Dispose(); } + } + private sealed class RollingWriter(string path) : TextWriter + { + private StreamWriter? writer; + public override Encoding Encoding => Encoding.UTF8; + private StreamWriter Open() + { + if (writer is not null && writer.BaseStream.Length < 1048576) return writer; + writer?.Dispose(); + if (File.Exists(path) && new FileInfo(path).Length >= 1048576) File.Move(path, path + ".previous", true); + var options = new FileStreamOptions { Mode = FileMode.Append, Access = FileAccess.Write, Share = FileShare.ReadWrite }; + if (!OperatingSystem.IsWindows()) options.UnixCreateMode = UnixFileMode.UserRead | UnixFileMode.UserWrite; + writer = new StreamWriter(new FileStream(path, options), new UTF8Encoding(false)) { AutoFlush = true }; + return writer; + } + public override void Write(char value) => Open().Write(value); + public override void Write(string? value) => Open().Write(value); + public override void Flush() => writer?.Flush(); + protected override void Dispose(bool disposing) { if (disposing) writer?.Dispose(); base.Dispose(disposing); } + } + public static void Detach() + { + if (!OperatingSystem.IsWindows() && setsid() < 0) throw new IOException("Could not detach the host from its terminal session."); + } + [DllImport("libc", SetLastError = true)] private static extern int setsid(); +} +public sealed class HostLogsSettings : CommandSettings +{ + [CommandOption("--tail ")] + [DefaultValue(50)] + public int Tail { get; init; } = 50; + public override ValidationResult Validate() => Tail is >= 1 and <= 500 ? ValidationResult.Success() : ValidationResult.Error("Tail must be between 1 and 500."); +} +public sealed class HostLogsCommand : Command +{ + public override int Execute(CommandContext context, HostLogsSettings settings, CancellationToken cancellationToken) + { + if (!File.Exists(HostLogs.PathName)) { AnsiConsole.WriteLine("No background host log exists yet."); return 0; } + foreach (var line in File.ReadLines(HostLogs.PathName).TakeLast(settings.Tail)) Console.WriteLine(line); + return 0; + } +} diff --git a/src/SidePulse.Cli/HostManagement.cs b/src/SidePulse.Cli/HostManagement.cs new file mode 100644 index 0000000..eaf10dd --- /dev/null +++ b/src/SidePulse.Cli/HostManagement.cs @@ -0,0 +1,99 @@ +using System.ComponentModel; +using System.Diagnostics; +using System.IO.Pipes; +using System.Text; +using System.Text.Json; +using SidePulse.Core; +using Spectre.Console; +using Spectre.Console.Cli; + +namespace SidePulse.Cli; + +public sealed record HostSnapshot(bool Running, int? ProcessId, AgentState State, IReadOnlyList Sessions); +public static class HostControl +{ + public static async Task Request(string command, CancellationToken cancellationToken) + { + using var deadline = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + deadline.CancelAfter(TimeSpan.FromSeconds(2)); + using var pipe = new NamedPipeClientStream(".", LocalPipe.Name, PipeDirection.InOut, PipeOptions.Asynchronous | PipeOptions.CurrentUserOnly); + try { await pipe.ConnectAsync(deadline.Token); } + catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested) { return new(false, null, AgentState.Unknown, []); } + await pipe.WriteAsync(Encoding.UTF8.GetBytes(JsonSerializer.Serialize(new { Command = command }) + "\n"), deadline.Token); + await pipe.FlushAsync(deadline.Token); + using var reader = new StreamReader(pipe, Encoding.UTF8); + var response = await reader.ReadToEndAsync(deadline.Token); + return JsonSerializer.Deserialize(response, Output.Json) ?? throw new IOException("Invalid host response."); + } +} +public sealed class HostActionSettings : CommandSettings +{ + [CommandOption("--json")] + public bool Json { get; init; } +} +public sealed class HostStatusCommand : AsyncCommand +{ + public override async Task ExecuteAsync(CommandContext context, HostActionSettings settings, CancellationToken cancellationToken) + { + var state = await HostControl.Request("status", cancellationToken); + if (settings.Json) Output.Print(state); + else AnsiConsole.WriteLine(state.Running ? $"Host running (PID {state.ProcessId}), {state.State}, {state.Sessions.Count} sessions." : "Host is not running."); + return 0; + } +} +public sealed class HostStopCommand : AsyncCommand +{ + public override async Task ExecuteAsync(CommandContext context, HostActionSettings settings, CancellationToken cancellationToken) + { + var state = await HostControl.Request("stop", cancellationToken); + if (state.Running) + { + for (var attempt = 0; attempt < 25; attempt++) + { + await Task.Delay(100, cancellationToken); + if (!(await HostControl.Request("status", cancellationToken)).Running) break; + if (attempt == 24) throw new IOException("The host acknowledged stop but has not exited. No process was forcibly killed."); + } + } + if (settings.Json) Output.Print(new { stopped = state.Running }); + else AnsiConsole.WriteLine(state.Running ? "Host stopped." : "Host was not running."); + return 0; + } +} +public sealed class HostStartSettings : TargetSettings +{ + [CommandOption("--exe ")] + public string Executable { get; init; } = Environment.ProcessPath ?? "sidepulse-net"; +} +public sealed class HostStartCommand : AsyncCommand +{ + public override async Task ExecuteAsync(CommandContext context, HostStartSettings settings, CancellationToken cancellationToken) + { + var existing = await HostControl.Request("status", cancellationToken); + if (existing.Running) { if (settings.Json) Output.Print(existing); else AnsiConsole.WriteLine("Host is already running. Stop it before changing its target."); return 0; } + var exe = HookConfiguration.Executable(settings.Executable); + var directory = Path.Combine(Path.GetDirectoryName(LinkStore.DefaultPath)!, "host"); + if (OperatingSystem.IsWindows()) Directory.CreateDirectory(directory); + else Directory.CreateDirectory(directory, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute); + var log = Path.Combine(directory, "host.log"); + var info = new ProcessStartInfo(exe) { UseShellExecute = false, CreateNoWindow = true, RedirectStandardInput = true, RedirectStandardOutput = true, RedirectStandardError = true, WorkingDirectory = Path.GetDirectoryName(exe)! }; + foreach (var value in new[] { "host", "run", "--plain", "--background", "--log-file", log }) info.ArgumentList.Add(value); + if (settings.Device is { } device) { info.ArgumentList.Add("--device"); info.ArgumentList.Add(Path.GetFullPath(device)); } + if (settings.Phone is { } phone) { info.ArgumentList.Add("--phone"); info.ArgumentList.Add(phone); } + if (settings.TokenEnvironment is { } variable) { info.ArgumentList.Add("--token-env"); info.ArgumentList.Add(variable); } + if (settings.DryRun) info.ArgumentList.Add("--dry-run"); + using var process = Process.Start(info) ?? throw new IOException("Could not start the host."); + process.StandardInput.Close(); + for (var attempt = 0; attempt < 5; attempt++) + { + if (process.HasExited) throw new IOException("Host exited during startup. Check host.log in the configuration directory."); + var started = await HostControl.Request("status", cancellationToken); + if (started.Running) + { + if (settings.Json) Output.Print(started); else AnsiConsole.WriteLine($"Host started (PID {started.ProcessId}). Log: {log}"); + return 0; + } + } + throw new IOException("Host readiness could not be confirmed. Use host status before retrying."); + } +} diff --git a/src/SidePulse.Cli/Program.cs b/src/SidePulse.Cli/Program.cs index 3e25dcf..dfcfb7f 100644 --- a/src/SidePulse.Cli/Program.cs +++ b/src/SidePulse.Cli/Program.cs @@ -2,11 +2,15 @@ using Spectre.Console.Cli; using SidePulse.Cli; +// Preserve the original foreground shorthand while adding lifecycle subcommands. +if (args.Length >= 1 && args[0] == "host" && (args.Length == 1 || args[1].StartsWith('-') && args[1] is not "--help" and not "-h")) + args = new[] { "host", "run" }.Concat(args.Skip(1)).ToArray(); +using var logOutput = HostLogs.Redirect(args); var app = new CommandApp(); app.Configure(config => { config.SetApplicationName("sidepulse-net"); - config.SetApplicationVersion("0.1.0-alpha.3"); + config.SetApplicationVersion("0.1.0-alpha.4"); config.AddBranch("link", links => { links.SetDescription("Pair and manage protected iPhone links."); @@ -22,7 +26,23 @@ config.AddCommand("state").WithDescription("Display an agent state on USB or iPhone."); config.AddCommand("write").WithDescription("Send a raw LED program with firmware envelope checks."); config.AddCommand("dashboard").WithDescription("Show devices and built-in status profiles."); - config.AddCommand("host").WithDescription("Run the local Copilot event listener (foreground)."); + config.AddBranch("host", host => + { + host.SetDescription("Manage the shared agent host."); + host.AddCommand("run").WithDescription("Run in the foreground."); + host.AddCommand("start").WithDescription("Start a detached host with bounded local logs."); + host.AddCommand("status").WithDescription("Query the running host and agent sessions."); + host.AddCommand("stop").WithDescription("Request graceful shutdown over current-user IPC."); + host.AddCommand("logs").WithDescription("Show recent background host log lines."); + }); + config.AddBranch("agents", agents => + { + agents.SetDescription("Set up Copilot, Codex, Claude Code and Kiro lifecycle hooks."); + agents.AddCommand("list"); + agents.AddCommand("install"); + agents.AddCommand("status"); + agents.AddCommand("uninstall"); + }); config.AddCommand("hook").IsHidden(); config.AddCommand("hook-config").WithDescription("Generate opt-in Copilot CLI hook configuration."); config.SetExceptionHandler((exception, _) => diff --git a/src/SidePulse.Cli/SidePulse.Cli.csproj b/src/SidePulse.Cli/SidePulse.Cli.csproj index 9574cfb..82d123d 100644 --- a/src/SidePulse.Cli/SidePulse.Cli.csproj +++ b/src/SidePulse.Cli/SidePulse.Cli.csproj @@ -2,7 +2,7 @@ Exe sidepulse-net - 0.1.0-alpha.3 + 0.1.0-alpha.4 Unofficial SidePulse companion MIT diff --git a/src/SidePulse.Core/AgentEvents.cs b/src/SidePulse.Core/AgentEvents.cs new file mode 100644 index 0000000..be1a3ba --- /dev/null +++ b/src/SidePulse.Core/AgentEvents.cs @@ -0,0 +1,55 @@ +using System.Text.Json; + +namespace SidePulse.Core; + +public enum AgentProvider { Copilot, Codex, Claude, Kiro } +public sealed record AgentCapability(AgentProvider Provider, string Target, string[] Events, string Limitations); + +public static class AgentEvents +{ + public static IReadOnlyList Capabilities { get; } = + [ + new(AgentProvider.Copilot, "Copilot CLI", ["sessionStart", "userPromptSubmitted", "preToolUse", "postToolUse", "agentStop", "errorOccurred", "postToolUseFailure", "sessionEnd", "notification"], "Notification waiting signals; no permission decision hooks."), + new(AgentProvider.Codex, "Codex local lifecycle hooks", ["SessionStart", "UserPromptSubmit", "PreToolUse", "PostToolUse", "PermissionRequest", "Stop", "Interrupt", "SessionEnd"], "Review and trust installed hooks in Codex /hooks. Cloud orchestration is not supported."), + new(AgentProvider.Claude, "Claude Code", ["SessionStart", "UserPromptSubmit", "PreToolUse", "PostToolUse", "PostToolUseFailure", "Notification", "Stop", "StopFailure", "SessionEnd"], "Notification waiting signals can be delayed. Subagent events are ignored."), + new(AgentProvider.Kiro, "Kiro CLI V3 standalone hooks", ["SessionStart", "UserPromptSubmit", "PreToolUse", "PostToolUse", "Stop", "SessionEnd"], "No documented general permission-wait or error signal. CLI 2.x profiles are not edited.") + ]; + public static SessionEvent? Parse(AgentProvider provider, string name, string json, long? receivedAt = null) + { + if (provider == AgentProvider.Copilot) + { + try { return CopilotEvents.Parse(name, json); } + catch (Exception ex) when (ex is JsonException or InvalidOperationException) { return null; } + } + try + { + using var document = JsonDocument.Parse(json); + var root = document.RootElement; + if (root.ValueKind != JsonValueKind.Object) return null; + string? Get(string field) => root.TryGetProperty(field, out var value) && value.ValueKind == JsonValueKind.String ? value.GetString() : null; + var session = Get("session_id"); + if (string.IsNullOrWhiteSpace(session) || session.Length > 240) return null; + // Runtime child agents can share the root session ID. They must not finish or idle its state. + if (!string.IsNullOrEmpty(Get("agent_id"))) return null; + if (!Capabilities.Single(c => c.Provider == provider).Events.Contains(name)) return null; + if (name == "SessionStart" && Get("source") == "compact") return null; + var tool = Get("tool_name"); + AgentState? state = name switch + { + "SessionStart" or "SessionEnd" or "Interrupt" => AgentState.Idle, + "UserPromptSubmit" or "PostToolUse" => AgentState.Working, + "PreToolUse" when provider == AgentProvider.Claude && tool == "AskUserQuestion" => AgentState.Waiting, + "PreToolUse" when provider == AgentProvider.Codex && tool == "request_user_input" => AgentState.Waiting, + "PreToolUse" => AgentState.Working, + "PermissionRequest" when provider == AgentProvider.Codex => AgentState.Waiting, + "Notification" when Get("notification_type") is "permission_prompt" or "elicitation_dialog" or "elicitation_url_dialog" => AgentState.Waiting, + "PostToolUseFailure" or "StopFailure" => AgentState.Error, + "Stop" => AgentState.Done, + _ => null + }; + // These providers don't promise event timestamps. Use ingestion time, never read transcripts. + return state.HasValue ? new(session, state.Value, receivedAt ?? DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(), provider) : null; + } + catch (Exception ex) when (ex is JsonException or InvalidOperationException) { return null; } + } +} diff --git a/src/SidePulse.Core/HookConfiguration.cs b/src/SidePulse.Core/HookConfiguration.cs new file mode 100644 index 0000000..0cf87e3 --- /dev/null +++ b/src/SidePulse.Core/HookConfiguration.cs @@ -0,0 +1,80 @@ +using System.Text; +using System.Text.Json; +using System.Text.Json.Nodes; + +namespace SidePulse.Core; + +public static class HookConfiguration +{ + public static string Executable(string path) + { + path = Path.GetFullPath(path); + if (!File.Exists(path) || !Path.GetFileNameWithoutExtension(path).Equals("sidepulse-net", StringComparison.OrdinalIgnoreCase)) + throw new ArgumentException("Use --exe with a published sidepulse-net executable."); + return path; + } + public static (string Bash, string PowerShell) Commands(string exe, AgentProvider provider, string name) + { + var source = provider.ToString().ToLowerInvariant(); + var bash = "'" + exe.Replace("'", "'\"'\"'") + "' hook " + name + " --source " + source + " >/dev/null 2>&1; exit 0"; + var powershell = "$ErrorActionPreference = 'SilentlyContinue'; try { $input | & '" + exe.Replace("'", "''") + + "' hook " + name + " --source " + source + " 2>$null | Out-Null } catch {}; exit 0"; + return (bash, powershell); + } + public static JsonObject Generate(AgentProvider provider, string exe, bool windows) + { + var events = AgentEvents.Capabilities.Single(c => c.Provider == provider).Events; + var hooks = new JsonObject(); + var kiro = new JsonArray(); + foreach (var name in events) + { + var commands = Commands(exe, provider, name); + // An encoded PowerShell invocation works without relying on the provider's parent shell on Windows. + var portable = windows ? "pwsh -NoLogo -NoProfile -NonInteractive -EncodedCommand " + + Convert.ToBase64String(Encoding.Unicode.GetBytes(commands.PowerShell)) : commands.Bash; + if (provider == AgentProvider.Copilot) + { + var entry = new JsonObject { ["type"] = "command", ["powershell"] = commands.PowerShell, + ["bash"] = commands.Bash, ["timeoutSec"] = 2 }; + if (name == "notification") entry["matcher"] = "permission_prompt|elicitation_dialog"; + hooks[name] = new JsonArray(entry); + } + else if (provider == AgentProvider.Kiro) + { + kiro.Add(new JsonObject { ["name"] = "SidePulse.NET " + name, ["trigger"] = name, ["timeout"] = 2, + ["action"] = new JsonObject { ["type"] = "command", ["command"] = portable } }); + } + else + { + var handler = new JsonObject { ["type"] = "command", ["command"] = portable, ["timeout"] = 2 }; + var group = new JsonObject { ["hooks"] = new JsonArray(handler) }; + if (name == "Notification") group["matcher"] = "permission_prompt|elicitation_dialog|elicitation_url_dialog"; + hooks[name] = new JsonArray(group); + } + } + return provider switch + { + AgentProvider.Copilot => new JsonObject { ["version"] = 1, ["hooks"] = hooks }, + AgentProvider.Kiro => new JsonObject { ["version"] = "v1", ["hooks"] = kiro }, + _ => new JsonObject { ["hooks"] = hooks } + }; + } + public static JsonObject Merge(AgentProvider provider, JsonObject? existing, JsonObject generated) + { + if (provider is AgentProvider.Copilot or AgentProvider.Kiro) + { + if (existing is not null) throw new IOException("The dedicated hook file already exists and is not owned by this installation."); + return generated; + } + var result = existing?.DeepClone().AsObject() ?? new JsonObject(); + if (result["hooks"] is null) result["hooks"] = new JsonObject(); + if (result["hooks"] is not JsonObject hooks) throw new IOException("Existing hooks have an unsupported shape. No changes were made."); + foreach (var entry in generated["hooks"]!.AsObject()) + { + if (hooks[entry.Key] is null) hooks[entry.Key] = new JsonArray(); + if (hooks[entry.Key] is not JsonArray array) throw new IOException("Existing event hooks must be arrays. No changes were made."); + foreach (var value in entry.Value!.AsArray()) array.Add(value!.DeepClone()); + } + return result; + } +} diff --git a/src/SidePulse.Core/HookInstallation.cs b/src/SidePulse.Core/HookInstallation.cs new file mode 100644 index 0000000..21969c6 --- /dev/null +++ b/src/SidePulse.Core/HookInstallation.cs @@ -0,0 +1,108 @@ +using System.Security.Cryptography; +using System.Text.Json; +using System.Text.Json.Nodes; + +namespace SidePulse.Core; + +public sealed record InstallationStatus(string State, string Target, string? Backup); +public sealed class HookInstallation(string manifestDirectory) +{ + private sealed record Manifest(string Target, string BeforeHash, string InstalledHash, string? Backup); + private static string Hash(byte[]? bytes) => bytes is null ? "absent" : Convert.ToHexString(SHA256.HashData(bytes)); + private string ManifestPath(string target) => Path.Combine(manifestDirectory, Hash(System.Text.Encoding.UTF8.GetBytes(target)) + ".json"); + private static byte[]? Read(string target) => File.Exists(target) ? File.ReadAllBytes(target) : null; + private static string Target(string path) => Path.GetFullPath(path); + private Manifest? Load(string target) + { + var path = ManifestPath(target); + if (!File.Exists(path)) return null; + var record = JsonSerializer.Deserialize(File.ReadAllBytes(path)) ?? throw new IOException("Installation manifest is unreadable."); + if (record.Target != target || record.Backup is not null && !record.Backup.StartsWith(target + ".sidepulse-net-", StringComparison.Ordinal)) + throw new IOException("Installation manifest paths do not match this target."); + return record; + } + public InstallationStatus Status(string path) + { + var target = Target(path); + var manifest = Load(target); + if (manifest is null) return new("not-installed", target, null); + var hash = Hash(Read(target)); + return new(hash == manifest.InstalledHash ? "installed" : hash == manifest.BeforeHash ? "pending-or-restored" : "modified", target, manifest.Backup); + } + public InstallationStatus Install(string path, AgentProvider provider, JsonObject generated, bool dryRun) + { + var target = Target(path); + var existingManifest = Load(target); + if (existingManifest is not null) + { + var status = Status(target); + if (status.State == "installed") return status; + throw new IOException("An existing installation changed or is pending. Review it and uninstall before reinstalling; no files were overwritten."); + } + var before = Read(target); + JsonObject? original; + try + { + original = before is null ? null : JsonNode.Parse(before)?.AsObject(); + if (before is not null && original is null) throw new IOException("Existing configuration must be a JSON object."); + } + catch (Exception ex) when (ex is JsonException or InvalidOperationException) { throw new IOException("Existing configuration must be valid JSON. No files were changed."); } + var merged = HookConfiguration.Merge(provider, original, generated); + var after = System.Text.Encoding.UTF8.GetBytes(merged.ToJsonString(new JsonSerializerOptions { WriteIndented = true }) + "\n"); + if (dryRun) return new("preview", target, null); + Directory.CreateDirectory(Path.GetDirectoryName(target)!); + Directory.CreateDirectory(manifestDirectory); + using var gate = PrivateFile(target + ".sidepulse-net.lock", FileMode.OpenOrCreate); + if (Hash(Read(target)) != Hash(before) || Load(target) is not null) throw new IOException("Configuration changed while preparing installation. Retry after reviewing it."); + var backup = before is null ? null : target + ".sidepulse-net-" + DateTimeOffset.UtcNow.ToString("yyyyMMddHHmmss") + "-" + Guid.NewGuid().ToString("N") + ".bak"; + if (backup is not null) { using var file = PrivateFile(backup, FileMode.CreateNew); file.Write(before!); file.Flush(true); } + var record = new Manifest(target, Hash(before), Hash(after), backup); + // A manifest written before the target makes an interrupted installation detectable and recoverable. + AtomicWrite(ManifestPath(target), JsonSerializer.SerializeToUtf8Bytes(record)); + try + { + if (Hash(Read(target)) != Hash(before)) throw new IOException("Configuration changed during installation. No provider configuration was replaced."); + AtomicWrite(target, after); + } + catch { File.Delete(ManifestPath(target)); throw; } + return new("installed", target, backup); + } + public InstallationStatus Uninstall(string path, bool dryRun) + { + var target = Target(path); + var manifest = Load(target); + if (manifest is null) return new("not-installed", target, null); + using var gate = PrivateFile(target + ".sidepulse-net.lock", FileMode.OpenOrCreate); + var status = Status(target); + if (status.State == "modified") throw new IOException("Configuration was edited after installation. Review the backup and merge manually; uninstall will not overwrite those changes."); + if (dryRun) return status with { State = "preview-remove" }; + if (status.State == "installed") + { + if (manifest.BeforeHash == "absent") File.Delete(target); + else + { + var original = manifest.Backup is null ? null : Read(manifest.Backup); + if (Hash(original) != manifest.BeforeHash) throw new IOException("The original backup is missing or modified. No changes were made."); + AtomicWrite(target, original!); + } + } + File.Delete(ManifestPath(target)); + return status with { State = "removed" }; + } + private static FileStream PrivateFile(string path, FileMode mode) + { + var options = new FileStreamOptions { Mode = mode, Access = FileAccess.ReadWrite, Share = FileShare.None }; + if (!OperatingSystem.IsWindows()) options.UnixCreateMode = UnixFileMode.UserRead | UnixFileMode.UserWrite; + return new FileStream(path, options); + } + private static void AtomicWrite(string path, byte[] bytes) + { + var temporary = path + "." + Guid.NewGuid().ToString("N") + ".tmp"; + try + { + using (var file = PrivateFile(temporary, FileMode.CreateNew)) { file.Write(bytes); file.Flush(true); } + File.Move(temporary, path, true); + } + finally { if (File.Exists(temporary)) File.Delete(temporary); } + } +} diff --git a/src/SidePulse.Core/Sessions.cs b/src/SidePulse.Core/Sessions.cs index b866f69..b385d75 100644 --- a/src/SidePulse.Core/Sessions.cs +++ b/src/SidePulse.Core/Sessions.cs @@ -2,8 +2,8 @@ namespace SidePulse.Core; -public sealed record SessionEvent(string SessionId, AgentState State, long Timestamp); -public sealed record SessionView(string Id, AgentState State, long Timestamp); +public sealed record SessionEvent(string SessionId, AgentState State, long Timestamp, AgentProvider Provider = AgentProvider.Copilot); +public sealed record SessionView(string Id, AgentState State, long Timestamp, AgentProvider Provider = AgentProvider.Copilot); public sealed class Sessions { @@ -12,20 +12,22 @@ public sealed class Sessions public bool Apply(SessionEvent item) { if (string.IsNullOrWhiteSpace(item.SessionId) || item.SessionId.Length > 256 || item.Timestamp < 0) return false; - if (sessions.TryGetValue(item.SessionId, out var previous) && item.Timestamp < previous.Timestamp) return false; + if (!Enum.IsDefined(item.Provider) || !Enum.IsDefined(item.State)) return false; + var key = item.Provider + ":" + item.SessionId; + if (sessions.TryGetValue(key, out var previous) && item.Timestamp < previous.Timestamp) return false; // Bound memory. Never evict an active session silently. - if (!sessions.ContainsKey(item.SessionId) && sessions.Count >= 1024) + if (!sessions.ContainsKey(key) && sessions.Count >= 1024) { var old = sessions.Values.Where(s => s.State is AgentState.Idle or AgentState.Done) .OrderBy(s => s.Timestamp).FirstOrDefault(); if (old is null) return false; - sessions.Remove(old.Id); + sessions.Remove(old.Provider + ":" + old.Id); } // A turn-ending signal does not establish recovery from an earlier error. // A subsequent working/waiting event or explicit session end can clear it. var state = previous?.State == AgentState.Error && item.State == AgentState.Done ? AgentState.Error : item.State; - sessions[item.SessionId] = new(item.SessionId, state, item.Timestamp); + sessions[key] = new(item.SessionId, state, item.Timestamp, item.Provider); return true; } public AgentState State diff --git a/tests/SidePulse.Tests/AgentTests.cs b/tests/SidePulse.Tests/AgentTests.cs new file mode 100644 index 0000000..ced925e --- /dev/null +++ b/tests/SidePulse.Tests/AgentTests.cs @@ -0,0 +1,130 @@ +using System.Text; +using System.Text.Json.Nodes; +using SidePulse.Core; +using Xunit; + +namespace SidePulse.Tests; + +public sealed class AgentTests +{ + [Theory] + [InlineData(AgentProvider.Codex, "UserPromptSubmit", AgentState.Working)] + [InlineData(AgentProvider.Codex, "PermissionRequest", AgentState.Waiting)] + [InlineData(AgentProvider.Codex, "Stop", AgentState.Done)] + [InlineData(AgentProvider.Codex, "Interrupt", AgentState.Idle)] + [InlineData(AgentProvider.Claude, "UserPromptSubmit", AgentState.Working)] + [InlineData(AgentProvider.Claude, "PostToolUseFailure", AgentState.Error)] + [InlineData(AgentProvider.Claude, "StopFailure", AgentState.Error)] + [InlineData(AgentProvider.Kiro, "PreToolUse", AgentState.Working)] + [InlineData(AgentProvider.Kiro, "Stop", AgentState.Done)] + [InlineData(AgentProvider.Kiro, "SessionEnd", AgentState.Idle)] + public void MapsDocumentedEvents(AgentProvider provider, string name, AgentState expected) + { + var item = AgentEvents.Parse(provider, name, "{\"session_id\":\"example\"}", 123)!; + Assert.Equal(expected, item.State); + Assert.Equal(provider, item.Provider); + Assert.Equal(123, item.Timestamp); + } + [Fact] + public void ChildAgentsCompactionAndUnknownSignalsDoNotFinishRootWork() + { + Assert.Null(AgentEvents.Parse(AgentProvider.Claude, "Stop", "{\"session_id\":\"root\",\"agent_id\":\"child\"}")); + Assert.Null(AgentEvents.Parse(AgentProvider.Codex, "SessionStart", "{\"session_id\":\"root\",\"source\":\"compact\"}")); + Assert.Null(AgentEvents.Parse(AgentProvider.Kiro, "PermissionRequest", "{\"session_id\":\"root\"}")); + Assert.Null(AgentEvents.Parse(AgentProvider.Kiro, "Stop", "{}")); + Assert.Null(AgentEvents.Parse(AgentProvider.Claude, "Stop", "[]")); + Assert.Null(AgentEvents.Parse(AgentProvider.Codex, "Stop", "invalid")); + } + [Fact] + public void ProvidersCannotCollideEvenIfRuntimeSessionIdsMatch() + { + var sessions = new Sessions(); + sessions.Apply(new("same", AgentState.Working, 1, AgentProvider.Codex)); + sessions.Apply(new("same", AgentState.Done, 2, AgentProvider.Claude)); + Assert.Equal(2, sessions.Snapshot.Count); + Assert.Equal(AgentState.Working, sessions.State); + sessions.Apply(new("same", AgentState.Waiting, 3, AgentProvider.Copilot)); + Assert.Equal(AgentState.Waiting, sessions.State); + } + [Fact] + public void GeneratedSchemasContainSilentWrappersAndNoPolicyDecisions() + { + foreach (var provider in Enum.GetValues()) + { + var generated = HookConfiguration.Generate(provider, "/tmp/O'Brien test/sidepulse-net", false); + var json = generated.ToJsonString(); + Assert.DoesNotContain("permissionDecision", json); + Assert.DoesNotContain("dangerously", json); + if (provider == AgentProvider.Kiro) + { + Assert.Equal("v1", generated["version"]!.GetValue()); + Assert.NotEmpty(generated["hooks"]!.AsArray()); + } + else Assert.NotEmpty(generated["hooks"]!.AsObject()); + var windows = HookConfiguration.Generate(provider, @"C:\Tools\test\sidepulse-net.exe", true).ToJsonString(); + if (provider != AgentProvider.Copilot) Assert.Contains("EncodedCommand", windows); + } + } + [Fact] + public void InstallationPreviewMergeAndUninstallPreserveUnrelatedSettingsExactly() + { + WithDirectory(directory => + { + var target = Path.Combine(directory, "settings.json"); + var original = "{\n \"permissions\": {\"allow\": [\"Read\"]},\n \"hooks\": {\"Stop\": [{\"hooks\": [{\"type\":\"command\",\"command\":\"my-script\"}]}]}\n}\n"; + File.WriteAllText(target, original); + var installer = new HookInstallation(Path.Combine(directory, "manifests")); + var fragment = HookConfiguration.Generate(AgentProvider.Claude, "/tmp/sidepulse-net", false); + Assert.Equal("preview", installer.Install(target, AgentProvider.Claude, fragment, true).State); + Assert.Equal(original, File.ReadAllText(target)); + Assert.False(Directory.Exists(Path.Combine(directory, "manifests"))); + var installed = installer.Install(target, AgentProvider.Claude, fragment, false); + Assert.Equal("installed", installed.State); + Assert.Equal(original, File.ReadAllText(installed.Backup!)); + var merged = JsonNode.Parse(File.ReadAllText(target))!; + Assert.Equal("Read", merged["permissions"]!["allow"]![0]!.GetValue()); + Assert.Equal(2, merged["hooks"]!["Stop"]!.AsArray().Count); + Assert.Equal("installed", installer.Install(target, AgentProvider.Claude, fragment, false).State); + Assert.Equal("removed", installer.Uninstall(target, false).State); + Assert.Equal(original, File.ReadAllText(target)); + }); + } + [Fact] + public void UninstallRefusesChangedSettingsAndInvalidInputIsNotOverwritten() + { + WithDirectory(directory => + { + var target = Path.Combine(directory, "hooks.json"); + var installer = new HookInstallation(Path.Combine(directory, "manifests")); + installer.Install(target, AgentProvider.Codex, HookConfiguration.Generate(AgentProvider.Codex, "/tmp/sidepulse-net", false), false); + File.AppendAllText(target, " "); + Assert.Equal("modified", installer.Status(target).State); + Assert.Throws(() => installer.Uninstall(target, false)); + var invalid = Path.Combine(directory, "invalid.json"); + File.WriteAllText(invalid, "broken"); + Assert.Throws(() => installer.Install(invalid, AgentProvider.Claude, new JsonObject(), false)); + Assert.Equal("broken", File.ReadAllText(invalid)); + }); + } + [Fact] + public void DedicatedFilesAreRemovedButUnownedFilesAreNeverReplaced() + { + WithDirectory(directory => + { + var target = Path.Combine(directory, "sidepulse-net.json"); + var installer = new HookInstallation(Path.Combine(directory, "manifests")); + var fragment = HookConfiguration.Generate(AgentProvider.Kiro, "/tmp/sidepulse-net", false); + installer.Install(target, AgentProvider.Kiro, fragment, false); + installer.Uninstall(target, false); + Assert.False(File.Exists(target)); + File.WriteAllText(target, "{}"); + Assert.Throws(() => installer.Install(target, AgentProvider.Kiro, fragment, false)); + }); + } + private static void WithDirectory(Action action) + { + var directory = Path.Combine(Path.GetTempPath(), "sidepulse-agent-test-" + Guid.NewGuid()); + Directory.CreateDirectory(directory); + try { action(directory); } finally { Directory.Delete(directory, true); } + } +} From 8d48d266de0e83b86430fe115e72643cb06d8ca3 Mon Sep 17 00:00:00 2001 From: Gordon Breuer Date: Fri, 23 Oct 2026 21:49:11 +0200 Subject: [PATCH 09/26] docs: document agent setup and host management; verify live log access --- .github/workflows/dotnet-ci.yml | 1 + NOTICE.md | 7 +++ README.md | 27 +++++++-- docs/wiki/Agent-Integrations.md | 104 ++++++++++++++++++++++++++++++++ docs/wiki/Compatibility.md | 3 +- docs/wiki/Getting-Started.md | 6 +- docs/wiki/Host-Management.md | 52 ++++++++++++++++ docs/wiki/_Sidebar.md | 3 + scripts/agent_smoke.py | 1 + src/SidePulse.Cli/HostLogs.cs | 12 +++- 10 files changed, 207 insertions(+), 9 deletions(-) create mode 100644 docs/wiki/Agent-Integrations.md create mode 100644 docs/wiki/Host-Management.md diff --git a/.github/workflows/dotnet-ci.yml b/.github/workflows/dotnet-ci.yml index 1a88711..3231f0b 100644 --- a/.github/workflows/dotnet-ci.yml +++ b/.github/workflows/dotnet-ci.yml @@ -43,6 +43,7 @@ jobs: matrix: os: [windows-latest, ubuntu-latest, macos-latest] runs-on: ${{ matrix.os }} + timeout-minutes: 20 env: SIDEPULSE_NATIVE_VAULT_TESTS: '1' steps: diff --git a/NOTICE.md b/NOTICE.md index 1ed2fbe..17c00d7 100644 --- a/NOTICE.md +++ b/NOTICE.md @@ -52,3 +52,10 @@ include the .NET license and third-party notices in `third-party/dotnet`. `PlatformSecrets.cs` and `MacKeychainVault.cs` are new implementations using native OS credential APIs/helpers and .NET AES-GCM. No third-party source was copied for these adapters. The credential APIs do not require a cloud account or token. + +## Agent adapters and host lifecycle + +`AgentEvents.cs`, `HookConfiguration.cs`, `HookInstallation.cs` and the associated +CLI host/agent commands are new .NET implementations based on the public provider +protocols linked in `docs/wiki/Agent-Integrations.md`. No provider application +source or transcript data is copied. The adapter tests use synthetic payloads. diff --git a/README.md b/README.md index f3264f7..70fdff4 100644 --- a/README.md +++ b/README.md @@ -14,7 +14,7 @@ an agent is working, waiting for input or finished. - A live terminal dashboard for devices, agent sessions and recent events. - Fast, silent commands for hooks and scripts, alongside interactive setup. -- Native Copilot CLI hooks, followed by the other upstream integrations. +- Copilot CLI, Codex, Claude Code and Kiro CLI V3 hooks with shared status aggregation. - USB LED programs, iPhone linking and bridge delivery, animation previews and profiles. - Reliable session aggregation, device aliases, diagnostics and explicit configuration migration. - Self-contained Windows, macOS and Linux distributions without a Python dependency. @@ -61,13 +61,13 @@ dotnet run --project src/SidePulse.Cli -- dashboard The solution contains a portable core, a Spectre.Console CLI and behavioral tests. Implemented commands: `devices`, `state`, `write`, `dashboard`, `host`, -`hook-config`, `doctor` and `link pair/list/import/default/rename/remove`. Use `--help` for details and `--dry-run` before sending a program. +`hook-config`, `doctor`, `agents list/install/status/uninstall`, host lifecycle +commands and `link pair/list/import/default/rename/remove`. Use `--help` for details and `--dry-run` before sending a program. The command name `sidepulse-net` coexists with the existing Python port. QR pairing and protected token storage use DPAPI on Windows, Keychain on macOS -and Secret Service on Linux. A persistent -service, full DSL validation, other upstream integrations and a signed installer -remain planned. The wiki's +and Secret Service on Linux. Login-startup registration, full DSL validation, +remaining upstream integrations and signed installers remain planned. The wiki's concept pages describe the intended complete product; the getting-started page records what is implemented now. @@ -84,3 +84,20 @@ python -m unittest discover -s scripts/tests -v ``` Contributions: [CONTRIBUTING.md](CONTRIBUTING.md). License: [MIT](LICENSE). + +## Agent setup and background use + +```shell +sidepulse-net agents install codex --dry-run +sidepulse-net agents install codex +sidepulse-net agents install claude +sidepulse-net agents install kiro +sidepulse-net agents install copilot +sidepulse-net host start --phone default +sidepulse-net host status +sidepulse-net host stop +``` + +See [agent integrations](docs/wiki/Agent-Integrations.md) for provider capabilities, +configuration backups and trust requirements, and [host management](docs/wiki/Host-Management.md) +for logs and foreground use. Additional providers remain planned. diff --git a/docs/wiki/Agent-Integrations.md b/docs/wiki/Agent-Integrations.md new file mode 100644 index 0000000..b5abc7e --- /dev/null +++ b/docs/wiki/Agent-Integrations.md @@ -0,0 +1,104 @@ +# Agent integrations + +The preview supports Copilot CLI, current local Codex lifecycle hooks, Claude Code +and Kiro CLI V3 standalone hooks. They feed one current-user host and share the +same status reducer. Provider IDs namespace sessions, so equal session IDs from +different tools cannot collide. `agents list --json` reports supported events +and limitations. Unknown providers/events are not guessed from terminal text. + +## Setup, inspection and removal + +```shell +sidepulse-net agents list +sidepulse-net agents install copilot --dry-run +sidepulse-net agents install copilot +sidepulse-net agents install codex +sidepulse-net agents install claude +sidepulse-net agents install kiro +sidepulse-net agents status claude --json +sidepulse-net agents uninstall claude --dry-run +sidepulse-net agents uninstall claude +``` + +Run the published executable, or supply its absolute path with `--exe`. +Install defaults to the provider's user configuration. Use `--config ` for +an explicitly chosen project-scoped or isolated provider file. This is a file +path, not a directory. Do not register the same integration at user and project +scope unless duplicate events are intended. + +| Provider | Default file | Integration boundary | +|---|---|---| +| Copilot CLI | `$COPILOT_HOME/hooks/sidepulse-net.json` or `~/.copilot/hooks/sidepulse-net.json` | Dedicated version-1 hook file; Bash and PowerShell wrappers | +| Codex | `$CODEX_HOME/hooks.json` or `~/.codex/hooks.json` | Merge lifecycle groups into the hooks object | +| Claude Code | `~/.claude/settings.json` | Merge lifecycle groups while preserving unrelated settings | +| Kiro CLI V3 | `~/.kiro/hooks/sidepulse-net.json` | Dedicated version-v1 standalone hook document | + +Installation is explicit. Dry runs show only the new managed fragment and target, +never the rest of an existing settings file. Shared settings are backed up byte +for byte before being updated. Backups have a `.bak` suffix so agents do not load +them as hook files. SidePulse.NET stores a separate installation manifest with +before/after hashes. Repeated installation is idempotent; uninstall then install +to change the executable path or generated hook definitions. + +Uninstall restores the exact original file, or removes a dedicated file created +by SidePulse.NET. It refuses to overwrite files edited after installation or to +restore a missing/modified backup. Review and merge those cases manually. A +pending installation interrupted before its target write can be removed safely. +Backups remain available after removal. Do not delete them before uninstalling. +Malformed JSON, unsupported hook shapes and unowned dedicated files are refused. +The installer preserves permission settings and never approves tools, bypasses +trust, or edits agent instructions. Restart the agent after installing/removing. +Codex requires reviewing the new definitions in `/hooks` before they execute. + +## State mapping + +Prompt submission and tool activity indicate working; explicit root turn-stop +signals indicate done. Codex approval requests and supported Claude/Copilot input +notifications indicate waiting. Claude tool/turn failures and Copilot error +signals indicate error. Codex interrupt and session-end events indicate idle. +Kiro exposes working, idle and completed-turn signals in this adapter; no general +permission-wait or error event is inferred. Tool failure does not automatically +mean the entire task failed, and done does not establish correctness. + +Subagent and background completion events never finish root sessions. Child-agent +payloads with an explicit `agent_id` are ignored by the root adapter. A session +start caused by compaction does not clear active root work. Waiting wins over +working, then unhandled errors, completed turns and idle. A stop after an error +preserves that error until activity resumes or the session ends. + +Copilot uses its documented event timestamp. Other adapters use ingestion time +because their common payloads do not guarantee timestamps. Concurrent hooks may +arrive out of order. There is no transcript parsing, prompt classification or +account/API access. Missing session identities are ignored rather than combining +unrelated activity under a placeholder. The IPC message contains only provider, +session identity, state and timestamp; prompt and tool contents are discarded. + +Generated wrappers are silent and return zero on runtime failures. Hook commands +have bounded input and connection budgets. Windows command-only provider formats +use a PowerShell 7 encoded command to avoid parent-shell quoting ambiguities; +Copilot includes its native PowerShell field. Unix uses quoted shell commands. +These are passive status hooks: their output never contains policy decisions. + +## Validation and limits + +Tests cover representative documented payloads, each provider's configuration +shape, mixed-provider sessions, configuration preservation and generated command +execution through Bash or PowerShell. CI uses synthetic events and no paid agent +accounts. Actual agent installations still need manual checks, especially hooks +that other plugins can delay or continue. A Stop hook can run before another hook +requests continuation; subsequent activity returns the signal to working. + +Kiro CLI 2.x agent profiles, legacy Codex notification-only releases, remote/cloud +agent orchestration and other providers (Cursor, Gemini CLI, Grok, Junie, etc.) +remain separate adapters to implement and verify. The adapter registry and common +installer are intended to make those additions straightforward. + +## Protocol references + +Checked 2026-10-23: + +- [Copilot hook reference](https://docs.github.com/en/copilot/reference/hooks-reference) +- [Codex lifecycle hooks](https://developers.openai.com/codex/hooks) +- [Claude Code hooks](https://code.claude.com/docs/en/hooks) +- [Kiro standalone schema](https://kiro.dev/docs/hooks/) +- [Kiro triggers and session identity](https://kiro.dev/docs/hooks/types/) diff --git a/docs/wiki/Compatibility.md b/docs/wiki/Compatibility.md index 9f36ab6..c506f60 100644 --- a/docs/wiki/Compatibility.md +++ b/docs/wiki/Compatibility.md @@ -18,7 +18,8 @@ implemented commands and test boundaries. | Destination selection, stdin and broadcast | M1 | Compatible ambiguity checks and explicit broadcast | | Built-in animations and LED counts | M1 | Source attribution, Dot/Pro geometry and brightness | | Copilot CLI hooks | Preview, Bash and PowerShell | Event fixtures and real CLI on each OS | -| Codex, Claude, Cursor, Grok, Junie | M2 parity | Separate hook schemas, installation and permissions per provider | +| Codex, Claude Code, Kiro CLI V3 | Preview | Native schema fixtures and simulated wrapper execution; real agent checks pending | +| Cursor, Grok, Junie and other providers | M2 parity | Separate hooks and manual verification | | Session collection, history and aggregation | M1/M2 | Concurrent sessions, stale events and restart | | Optional transcript recovery | M2 investigation | Privacy, format drift and opt-in behavior | | Background host and service management | M1 Windows | Named-pipe access, foreground mode and login startup | diff --git a/docs/wiki/Getting-Started.md b/docs/wiki/Getting-Started.md index c022666..ab540dd 100644 --- a/docs/wiki/Getting-Started.md +++ b/docs/wiki/Getting-Started.md @@ -1,10 +1,14 @@ +> Shared background host commands and managed setup for Codex, Claude Code, Kiro +> and Copilot are now implemented. See [[Host-Management]] and [[Agent-Integrations]]. +> The manual Copilot hook generation below remains available for existing users. + # Getting started with the implementation preview The first implementation is an alpha preview. USB discovery/writes, status profiles, raw programs, silent iPhone bridge delivery with an existing APNS token, session aggregation, QR pairing, native protected phone links, diagnostics and a foreground Copilot CLI host are implemented. Background-service installation, full LED grammar validation, -animation rendering, migration and other agent integrations remain planned. +animation rendering, migration and remaining agent integrations remain planned. ## Build and run diff --git a/docs/wiki/Host-Management.md b/docs/wiki/Host-Management.md new file mode 100644 index 0000000..12e6288 --- /dev/null +++ b/docs/wiki/Host-Management.md @@ -0,0 +1,52 @@ +# Host management + +One shared host collects supported agent events and owns the selected output. +Start it before starting your agents. It uses current-user IPC, not a network +listener. The phone token remains in the native credential store or process +environment; it is never added to command arguments or logs. + +```shell +sidepulse-net host start --phone default +sidepulse-net host status +sidepulse-net host status --json +sidepulse-net host logs --tail 30 +sidepulse-net host stop +``` + +Choose a target with `--phone`, `--device` or `--token-env`. `--dry-run` runs the +host without delivery. `host start` launches a detached process and waits for an +IPC readiness response. The executable directory is its working directory; +explicit USB paths are made absolute before starting. Use `--exe` when invoking +through `dotnet` rather than a published apphost. Starting again reports the +existing host and does not silently switch its target. + +`host status` returns running state, PID, aggregate state and provider-specific +session snapshots. `host stop` requests shutdown over the same current-user IPC; +it never blindly kills a PID from a stale file. The host leaves the last LED +program in place. Stopping does not mark unfinished work complete. Sessions are +in memory only and begin unknown after restart. + +For a foreground session: + +```shell +sidepulse-net host run --phone default +``` + +The earlier `sidepulse-net host --phone default` shorthand remains supported. +Ctrl+C stops the foreground host. Upgrade by stopping the old host before +replacing binaries; older preview hosts do not implement the control protocol. +A process started from a terminal is detached on Unix. Windows launches it without +a console window. Background logs live under `host/host.log` in the SidePulse.NET +configuration directory, with rotation around 1 MiB and one previous file. Logs +contain state/count diagnostics, not prompts, tool arguments or credentials. +`host logs` reads the current log; `.previous` remains available for inspection. + +Login startup registration and system service installation are not implemented +in this preview. `host start` starts a user process for the current login session. +Linux desktop/Keychain availability can change after logout or keyring locking; +check `doctor` and the host log if phone output becomes unavailable. + +Tests exercise detached start, idempotent start, status snapshots, mixed-provider +hook delivery and graceful stop. Foreground tests also reject competing hosts +and verify restart after forced termination. These are simulated device tests, +not evidence of actual LED or phone receipt. diff --git a/docs/wiki/_Sidebar.md b/docs/wiki/_Sidebar.md index 538bcc2..11ecb0b 100644 --- a/docs/wiki/_Sidebar.md +++ b/docs/wiki/_Sidebar.md @@ -15,3 +15,6 @@ - [[Getting started|Getting-Started]] - [[Platforms]] + +- [[Agent integrations|Agent-Integrations]] +- [[Host management|Host-Management]] diff --git a/scripts/agent_smoke.py b/scripts/agent_smoke.py index 678656b..8bc172f 100644 --- a/scripts/agent_smoke.py +++ b/scripts/agent_smoke.py @@ -87,6 +87,7 @@ def send(provider, event): break time.sleep(0.1) assert status()['State'] == 'Done' + assert 'DO-NOT-LOG-THIS' not in run('host', 'logs', '--tail', '10') run('host', 'stop', '--json') started = False assert not status()['Running'] diff --git a/src/SidePulse.Cli/HostLogs.cs b/src/SidePulse.Cli/HostLogs.cs index b7a97a3..ab9ba0d 100644 --- a/src/SidePulse.Cli/HostLogs.cs +++ b/src/SidePulse.Cli/HostLogs.cs @@ -36,7 +36,7 @@ private StreamWriter Open() if (writer is not null && writer.BaseStream.Length < 1048576) return writer; writer?.Dispose(); if (File.Exists(path) && new FileInfo(path).Length >= 1048576) File.Move(path, path + ".previous", true); - var options = new FileStreamOptions { Mode = FileMode.Append, Access = FileAccess.Write, Share = FileShare.ReadWrite }; + var options = new FileStreamOptions { Mode = FileMode.Append, Access = FileAccess.Write, Share = FileShare.ReadWrite | FileShare.Delete }; if (!OperatingSystem.IsWindows()) options.UnixCreateMode = UnixFileMode.UserRead | UnixFileMode.UserWrite; writer = new StreamWriter(new FileStream(path, options), new UTF8Encoding(false)) { AutoFlush = true }; return writer; @@ -64,7 +64,15 @@ public sealed class HostLogsCommand : Command public override int Execute(CommandContext context, HostLogsSettings settings, CancellationToken cancellationToken) { if (!File.Exists(HostLogs.PathName)) { AnsiConsole.WriteLine("No background host log exists yet."); return 0; } - foreach (var line in File.ReadLines(HostLogs.PathName).TakeLast(settings.Tail)) Console.WriteLine(line); + using var file = new FileStream(HostLogs.PathName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete); + using var reader = new StreamReader(file); + var lines = new Queue(); + while (reader.ReadLine() is { } line) + { + lines.Enqueue(line); + if (lines.Count > settings.Tail) lines.Dequeue(); + } + foreach (var line in lines) Console.WriteLine(line); return 0; } } From 1be4ed8ca292f8f7418ccd1d080fed90f745dd27 Mon Sep 17 00:00:00 2001 From: Gordon Breuer Date: Fri, 23 Oct 2026 21:51:20 +0200 Subject: [PATCH 10/26] fix: detach Windows host handles and bound Linux CI package setup --- .github/workflows/dotnet-ci.yml | 4 ++-- scripts/agent_smoke.py | 4 ++++ src/SidePulse.Cli/HostManagement.cs | 6 ++++-- 3 files changed, 10 insertions(+), 4 deletions(-) diff --git a/.github/workflows/dotnet-ci.yml b/.github/workflows/dotnet-ci.yml index 3231f0b..98282c5 100644 --- a/.github/workflows/dotnet-ci.yml +++ b/.github/workflows/dotnet-ci.yml @@ -58,8 +58,8 @@ jobs: shell: bash run: | if [ "$RUNNER_OS" = 'Linux' ]; then - sudo apt-get update -qq - sudo apt-get install -y libsecret-tools gnome-keyring dbus-x11 + sudo apt-get update -qq -o Acquire::Retries=1 -o Acquire::http::Timeout=30 -o Acquire::https::Timeout=30 + sudo apt-get install -y --no-install-recommends libsecret-tools gnome-keyring dbus-x11 bus_address=$(dbus-daemon --session --fork --print-address=1) export DBUS_SESSION_BUS_ADDRESS="$bus_address" echo "DBUS_SESSION_BUS_ADDRESS=$bus_address" >> "$GITHUB_ENV" diff --git a/scripts/agent_smoke.py b/scripts/agent_smoke.py index 8bc172f..66c297e 100644 --- a/scripts/agent_smoke.py +++ b/scripts/agent_smoke.py @@ -41,10 +41,12 @@ def status(): assert json.loads(run('agents', 'status', provider, '--config', str(path), '--json'))['State'] == 'installed' configs[provider] = (path, json.loads(path.read_text())) + print("Agent setup/preview checks passed; starting detached host.", flush=True) started = False try: first = json.loads(run('host', 'start', '--exe', exe, '--device', directory, '--json', timeout=25)) started = True + print('Detached host ready.', flush=True) assert first['Running'] assert status()['Running'] second = json.loads(run('host', 'start', '--exe', exe, '--device', directory, '--json')) @@ -70,6 +72,7 @@ def send(provider, event): assert result.returncode == 0 and not result.stdout and not result.stderr, (provider, result.stdout, result.stderr) for provider in configs: + print('Exercising ' + provider + ' wrapper.', flush=True) send(provider, 'userPromptSubmitted' if provider == 'copilot' else 'UserPromptSubmit') for _ in range(30): snapshot = status() @@ -91,6 +94,7 @@ def send(provider, event): run('host', 'stop', '--json') started = False assert not status()['Running'] + print('Host stopped gracefully.', flush=True) logs = run('host', 'logs', '--tail', '10') assert 'DO-NOT-LOG-THIS' not in logs finally: diff --git a/src/SidePulse.Cli/HostManagement.cs b/src/SidePulse.Cli/HostManagement.cs index eaf10dd..dcbbc2b 100644 --- a/src/SidePulse.Cli/HostManagement.cs +++ b/src/SidePulse.Cli/HostManagement.cs @@ -76,14 +76,16 @@ public override async Task ExecuteAsync(CommandContext context, HostStartSe if (OperatingSystem.IsWindows()) Directory.CreateDirectory(directory); else Directory.CreateDirectory(directory, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute); var log = Path.Combine(directory, "host.log"); - var info = new ProcessStartInfo(exe) { UseShellExecute = false, CreateNoWindow = true, RedirectStandardInput = true, RedirectStandardOutput = true, RedirectStandardError = true, WorkingDirectory = Path.GetDirectoryName(exe)! }; + var info = new ProcessStartInfo(exe) { UseShellExecute = OperatingSystem.IsWindows(), WindowStyle = ProcessWindowStyle.Hidden, CreateNoWindow = true, + RedirectStandardInput = !OperatingSystem.IsWindows(), RedirectStandardOutput = !OperatingSystem.IsWindows(), + RedirectStandardError = !OperatingSystem.IsWindows(), WorkingDirectory = Path.GetDirectoryName(exe)! }; foreach (var value in new[] { "host", "run", "--plain", "--background", "--log-file", log }) info.ArgumentList.Add(value); if (settings.Device is { } device) { info.ArgumentList.Add("--device"); info.ArgumentList.Add(Path.GetFullPath(device)); } if (settings.Phone is { } phone) { info.ArgumentList.Add("--phone"); info.ArgumentList.Add(phone); } if (settings.TokenEnvironment is { } variable) { info.ArgumentList.Add("--token-env"); info.ArgumentList.Add(variable); } if (settings.DryRun) info.ArgumentList.Add("--dry-run"); using var process = Process.Start(info) ?? throw new IOException("Could not start the host."); - process.StandardInput.Close(); + if (!OperatingSystem.IsWindows()) process.StandardInput.Close(); for (var attempt = 0; attempt < 5; attempt++) { if (process.HasExited) throw new IOException("Host exited during startup. Check host.log in the configuration directory."); From d5d7f726461f5bbfbc041ddccaf564a38dc15f75 Mon Sep 17 00:00:00 2001 From: Gordon Breuer Date: Fri, 23 Oct 2026 21:53:04 +0200 Subject: [PATCH 11/26] fix: acknowledge host control replies before disconnecting Windows pipes --- src/SidePulse.Cli/Hooks.cs | 7 +++++-- src/SidePulse.Cli/HostManagement.cs | 4 +++- 2 files changed, 8 insertions(+), 3 deletions(-) diff --git a/src/SidePulse.Cli/Hooks.cs b/src/SidePulse.Cli/Hooks.cs index 0410f03..2dcf83b 100644 --- a/src/SidePulse.Cli/Hooks.cs +++ b/src/SidePulse.Cli/Hooks.cs @@ -162,9 +162,12 @@ public override async Task ExecuteAsync(CommandContext context, HostSetting var action = command.GetString(); if (action is "status" or "stop") { - var response = JsonSerializer.SerializeToUtf8Bytes(new HostSnapshot(true, Environment.ProcessId, sessions.State, sessions.Snapshot), Output.Json); - await pipe.WriteAsync(response, deadline.Token); + var response = JsonSerializer.SerializeToUtf8Bytes(new HostSnapshot(true, Environment.ProcessId, sessions.State, sessions.Snapshot)); + await pipe.WriteAsync(response.Concat(new byte[] { 10 }).ToArray(), deadline.Token); await pipe.FlushAsync(deadline.Token); + // Windows disconnect discards unread reply bytes. Wait for a bounded receipt + // acknowledgement before disconnecting; no unbounded pipe drain is needed. + await pipe.ReadAsync(new byte[1], deadline.Token); if (action == "stop") shutdown.Cancel(); } continue; diff --git a/src/SidePulse.Cli/HostManagement.cs b/src/SidePulse.Cli/HostManagement.cs index dcbbc2b..704bc32 100644 --- a/src/SidePulse.Cli/HostManagement.cs +++ b/src/SidePulse.Cli/HostManagement.cs @@ -22,7 +22,9 @@ public static async Task Request(string command, CancellationToken await pipe.WriteAsync(Encoding.UTF8.GetBytes(JsonSerializer.Serialize(new { Command = command }) + "\n"), deadline.Token); await pipe.FlushAsync(deadline.Token); using var reader = new StreamReader(pipe, Encoding.UTF8); - var response = await reader.ReadToEndAsync(deadline.Token); + var response = await reader.ReadLineAsync(deadline.Token) ?? throw new IOException("The host closed without a response."); + await pipe.WriteAsync(new byte[] { 10 }, deadline.Token); + await pipe.FlushAsync(deadline.Token); return JsonSerializer.Deserialize(response, Output.Json) ?? throw new IOException("Invalid host response."); } } From f2f514dbb860dd939593f7a702327bbc4895cc61 Mon Sep 17 00:00:00 2001 From: Gordon Breuer Date: Fri, 23 Oct 2026 21:54:16 +0200 Subject: [PATCH 12/26] fix: require an exact host control acknowledgement --- src/SidePulse.Cli/Hooks.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/SidePulse.Cli/Hooks.cs b/src/SidePulse.Cli/Hooks.cs index 2dcf83b..eafb1cc 100644 --- a/src/SidePulse.Cli/Hooks.cs +++ b/src/SidePulse.Cli/Hooks.cs @@ -167,7 +167,7 @@ public override async Task ExecuteAsync(CommandContext context, HostSetting await pipe.FlushAsync(deadline.Token); // Windows disconnect discards unread reply bytes. Wait for a bounded receipt // acknowledgement before disconnecting; no unbounded pipe drain is needed. - await pipe.ReadAsync(new byte[1], deadline.Token); + await pipe.ReadExactlyAsync(new byte[1], deadline.Token); if (action == "stop") shutdown.Cancel(); } continue; From b91fb6752656a8fb69214727fa0e28c5422a898a Mon Sep 17 00:00:00 2001 From: Gordon Breuer Date: Fri, 23 Oct 2026 22:40:28 +0200 Subject: [PATCH 13/26] Add Dot/Pro animation studio, interactive command builder and offline credits --- .github/workflows/dotnet-ci.yml | 6 + NOTICE.md | 16 + README.md | 27 +- docs/wiki/Animations.md | 66 + docs/wiki/Getting-Started.md | 5 + docs/wiki/Roadmap.md | 8 +- docs/wiki/Scripting-and-Menus.md | 57 + docs/wiki/_Sidebar.md | 3 + scripts/agent_smoke.py | 11 +- scripts/animation_smoke.py | 66 + scripts/terminal_smoke.py | 102 ++ src/SidePulse.Cli/About.cs | 118 ++ src/SidePulse.Cli/Animations.cs | 234 +++ src/SidePulse.Cli/Dependencies.json | 51 + src/SidePulse.Cli/Hooks.cs | 12 +- src/SidePulse.Cli/HostManagement.cs | 10 + src/SidePulse.Cli/Interactive.cs | 155 ++ src/SidePulse.Cli/PatternEditor.cs | 108 ++ src/SidePulse.Cli/Program.cs | 39 +- src/SidePulse.Cli/SidePulse.Cli.csproj | 10 +- src/SidePulse.Cli/TerminalMode.cs | 67 + src/SidePulse.Core/Animation.cs | 192 +++ src/SidePulse.Core/AnimationLibrary.cs | 116 ++ src/SidePulse.Core/Animations/amber-pulse.LED | 3 + .../Animations/cyan-complete.LED | 1 + src/SidePulse.Core/Animations/cyan-roll-2.LED | 3 + src/SidePulse.Core/Animations/cyan-roll-8.LED | 3 + .../Animations/ember-attention.LED | 3 + .../Animations/ember-tide-2.LED | 3 + .../Animations/ember-tide-8.LED | 3 + .../Animations/idle-pulse-2.LED | 3 + .../Animations/idle-pulse-8.LED | 3 + src/SidePulse.Core/Animations/kitt-2.LED | 4 + src/SidePulse.Core/Animations/kitt-8.LED | 4 + src/SidePulse.Core/Animations/kitt-red-2.LED | 4 + src/SidePulse.Core/Animations/kitt-red-8.LED | 4 + .../Animations/night-rider-2.LED | 3 + .../Animations/night-rider-8.LED | 4 + src/SidePulse.Core/Animations/off.LED | 1 + .../Animations/purple-attention.LED | 3 + .../Animations/purple-tide-2.LED | 3 + .../Animations/purple-tide-8.LED | 3 + src/SidePulse.Core/Animations/solid-green.LED | 1 + src/SidePulse.Core/SidePulse.Core.csproj | 3 + tests/SidePulse.Tests/AnimationTests.cs | 123 ++ tests/SidePulse.Tests/SidePulse.Tests.csproj | 1 + tests/SidePulse.Tests/TerminalTests.cs | 31 + tests/SidePulse.Tests/packages.lock.json | 54 + .../microsoft.win32.systemevents/LICENSE.TXT | 23 + .../THIRD-PARTY-NOTICES.TXT | 939 +++++++++++ .../system.drawing.common/LICENSE.TXT | 23 + .../THIRD-PARTY-NOTICES.TXT | 939 +++++++++++ .../LICENSE.txt | 23 + .../THIRD-PARTY-NOTICES.TXT | 1418 +++++++++++++++++ 54 files changed, 5105 insertions(+), 10 deletions(-) create mode 100644 docs/wiki/Animations.md create mode 100644 docs/wiki/Scripting-and-Menus.md create mode 100644 scripts/animation_smoke.py create mode 100644 scripts/terminal_smoke.py create mode 100644 src/SidePulse.Cli/About.cs create mode 100644 src/SidePulse.Cli/Animations.cs create mode 100644 src/SidePulse.Cli/Dependencies.json create mode 100644 src/SidePulse.Cli/Interactive.cs create mode 100644 src/SidePulse.Cli/PatternEditor.cs create mode 100644 src/SidePulse.Cli/TerminalMode.cs create mode 100644 src/SidePulse.Core/Animation.cs create mode 100644 src/SidePulse.Core/AnimationLibrary.cs create mode 100644 src/SidePulse.Core/Animations/amber-pulse.LED create mode 100644 src/SidePulse.Core/Animations/cyan-complete.LED create mode 100644 src/SidePulse.Core/Animations/cyan-roll-2.LED create mode 100644 src/SidePulse.Core/Animations/cyan-roll-8.LED create mode 100644 src/SidePulse.Core/Animations/ember-attention.LED create mode 100644 src/SidePulse.Core/Animations/ember-tide-2.LED create mode 100644 src/SidePulse.Core/Animations/ember-tide-8.LED create mode 100644 src/SidePulse.Core/Animations/idle-pulse-2.LED create mode 100644 src/SidePulse.Core/Animations/idle-pulse-8.LED create mode 100644 src/SidePulse.Core/Animations/kitt-2.LED create mode 100644 src/SidePulse.Core/Animations/kitt-8.LED create mode 100644 src/SidePulse.Core/Animations/kitt-red-2.LED create mode 100644 src/SidePulse.Core/Animations/kitt-red-8.LED create mode 100644 src/SidePulse.Core/Animations/night-rider-2.LED create mode 100644 src/SidePulse.Core/Animations/night-rider-8.LED create mode 100644 src/SidePulse.Core/Animations/off.LED create mode 100644 src/SidePulse.Core/Animations/purple-attention.LED create mode 100644 src/SidePulse.Core/Animations/purple-tide-2.LED create mode 100644 src/SidePulse.Core/Animations/purple-tide-8.LED create mode 100644 src/SidePulse.Core/Animations/solid-green.LED create mode 100644 tests/SidePulse.Tests/AnimationTests.cs create mode 100644 tests/SidePulse.Tests/TerminalTests.cs create mode 100644 third-party/dotnet-packages/microsoft.win32.systemevents/LICENSE.TXT create mode 100644 third-party/dotnet-packages/microsoft.win32.systemevents/THIRD-PARTY-NOTICES.TXT create mode 100644 third-party/dotnet-packages/system.drawing.common/LICENSE.TXT create mode 100644 third-party/dotnet-packages/system.drawing.common/THIRD-PARTY-NOTICES.TXT create mode 100644 third-party/dotnet-packages/system.security.cryptography.protecteddata/LICENSE.txt create mode 100644 third-party/dotnet-packages/system.security.cryptography.protecteddata/THIRD-PARTY-NOTICES.TXT diff --git a/.github/workflows/dotnet-ci.yml b/.github/workflows/dotnet-ci.yml index 98282c5..371a2d2 100644 --- a/.github/workflows/dotnet-ci.yml +++ b/.github/workflows/dotnet-ci.yml @@ -94,6 +94,10 @@ jobs: $binary = if ($IsWindows) { 'sidepulse-net.exe' } else { 'sidepulse-net' } python scripts/cli_smoke.py "src/SidePulse.Cli/bin/Release/net10.0/$binary" if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + python scripts/terminal_smoke.py "src/SidePulse.Cli/bin/Release/net10.0/$binary" + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + python scripts/animation_smoke.py "src/SidePulse.Cli/bin/Release/net10.0/$binary" + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } python scripts/agent_smoke.py "src/SidePulse.Cli/bin/Release/net10.0/$binary" if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } - name: Publish and exercise self-contained previews @@ -115,6 +119,8 @@ jobs: $binary = if ($IsWindows) { 'sidepulse-net.exe' } else { 'sidepulse-net' } python scripts/cli_smoke.py "$destination/$binary" if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + python scripts/animation_smoke.py "$destination/$binary" + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } python scripts/agent_smoke.py "$destination/$binary" if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } } diff --git a/NOTICE.md b/NOTICE.md index 17c00d7..f52d1dd 100644 --- a/NOTICE.md +++ b/NOTICE.md @@ -59,3 +59,19 @@ these adapters. The credential APIs do not require a cloud account or token. CLI host/agent commands are new .NET implementations based on the public provider protocols linked in `docs/wiki/Agent-Integrations.md`. No provider application source or transcript data is copied. The adapter tests use synthetic payloads. + +## Animation studio and credits + +`src/SidePulse.Core/Animations/*.LED` contains unchanged upstream animation assets +from `src/sidepulse/resources/animations/` at the reference revision above. +Copyright (c) 2026 Peter Kuhar, MIT. The retained upstream license accompanies +these assets. `Animation.cs` is a new managed interpreter based on that revision's +`LEDS_FORMAT.md`; it is an approximation and does not embed the firmware/WASM. + +The offline dependency registry in `src/SidePulse.Cli/Dependencies.json` is derived +from committed NuGet locks and package metadata. License texts and notices for +Microsoft package dependencies are retained under `third-party/dotnet-packages`. +All seven resolved runtime packages, including transitive packages, appear in +`about credits` / `about licenses`. Self-contained runtime notices are additionally +included by CI under `third-party/dotnet`. No affiliate relationship is implied; +manufacturer links are ordinary URLs. diff --git a/README.md b/README.md index 70fdff4..1b09558 100644 --- a/README.md +++ b/README.md @@ -66,7 +66,7 @@ commands and `link pair/list/import/default/rename/remove`. Use `--help` for det The command name `sidepulse-net` coexists with the existing Python port. QR pairing and protected token storage use DPAPI on Windows, Keychain on macOS -and Secret Service on Linux. Login-startup registration, full DSL validation, +and Secret Service on Linux. Login-startup registration, firmware-verified simulator parity, remaining upstream integrations and signed installers remain planned. The wiki's concept pages describe the intended complete product; the getting-started page records what is implemented now. @@ -101,3 +101,28 @@ sidepulse-net host stop See [agent integrations](docs/wiki/Agent-Integrations.md) for provider capabilities, configuration backups and trust requirements, and [host management](docs/wiki/Host-Management.md) for logs and foreground use. Additional providers remain planned. + +## Animation studio and scripting + +```shell +sidepulse-net animations preview cyan-roll --both +sidepulse-net animations edit --file custom.LED --model dot +sidepulse-net animations validate custom.LED --quiet +sidepulse-net animations import personal --file custom.LED --model dot +sidepulse-net animations apply personal --model dot --phone default --brightness 40 +sidepulse-net profiles set personal --state Working --pattern cyan-roll --brightness 40 +sidepulse-net host start --phone default --profile personal --model dot +sidepulse-net about credits +sidepulse-net about licenses --full +``` + +Run with no arguments in a terminal for arrow-key menus and guided setup. Review +shows the single-line command for copying into scripts. Redirected input/output, +`--no-interactive`, `--quiet` and `--json` never open menus. Errors use stderr and +nonzero exit codes. Preview is entirely Spectre.Console and supports pause, +frame stepping and restart; terminal colors/timing approximate the firmware. + +See [animations](docs/wiki/Animations.md) and +[scripting and menus](docs/wiki/Scripting-and-Menus.md). `docs --offline` reads +bundled documentation; `about` provides manufacturer/upstream/project links and +licensed dependency credits. Browser opening requires `--open`. diff --git a/docs/wiki/Animations.md b/docs/wiki/Animations.md new file mode 100644 index 0000000..b60a2f0 --- /dev/null +++ b/docs/wiki/Animations.md @@ -0,0 +1,66 @@ +# Animations and custom patterns + +SidePulse Dot (USB-C) has two LEDs; SidePulse Pro (SD slot) has eight. Both use +upstream `LEDS.LED` syntax. Named patterns select a model-specific variant. Preview +defaults to Dot; apply detects a known mounted model or requires `--model`. Phone +output requires an explicit model. File transport still requires writable storage; +this feature does not add direct USB or SD read transports. + +```sh +sidepulse-net animations list +sidepulse-net animations preview cyan-roll --model dot +sidepulse-net animations preview --file custom.LED --model pro +sidepulse-net animations preview --file custom.LED --both +sidepulse-net animations validate custom.LED --quiet +sidepulse-net animations edit --file custom.LED --model dot +sidepulse-net animations import personal --file custom.LED --model dot +sidepulse-net animations export personal --model dot --output exported.LED +sidepulse-net animations apply personal --model dot --phone default --brightness 40 +``` + +The editor supports guided color, per-LED color/hold, off, roll, brightness, +duration, easing, delay, raw line editing and repeat settings. Preview with Space +(pause), Right (advance 100ms), R (restart) and Escape (back). Save before leaving; +unsaved changes can be discarded explicitly. Existing files are replaced only if +they have not changed since opening. Import/export refuse replacement unless +`--force` is supplied. Built-ins cannot be overwritten; choose a custom name. +Custom files are stored separately for Dot and Pro. Import both variants under the +same name when their layouts differ. Names use lowercase letters, digits, `_`, `-`. + +The managed interpreter validates colors, indexes, duration/delay (up to 65535ms), +brightness 0..255, easing names, roll, finite/infinite repeats and the firmware's +512 UTF-8 byte / 20 physical line envelope. Indexed assignments preserve other +LEDs. A single color fills the strip; a color list clears trailing LEDs. Valid +out-of-range LEDs are ignored. Comments begin with `;`, `//` or `# `. + +Preview is entirely Spectre.Console text and colored blocks. It starts from black; +hardware may retain previous colors. Terminal colors, refresh rate, easing curves +and rounding are approximations and have not been validated against firmware. +Preview does not establish device receipt. `--both` compares the model-specific variants of named patterns, or plays the +same custom file on both layouts. +Brightness percent scales program brightness; an additional directive consumes +one physical line, so a program at the envelope limit may need shortening. + +Non-interactive preview emits one frame and exits immediately. `--at 500` selects +its time in milliseconds; `--json` emits model, timestamp and RGB values. Interactive +preview runs for 10 seconds by default; `--seconds` permits up to 600 seconds. + +## Agent state profiles + +```sh +sidepulse-net profiles set personal --state Working --pattern cyan-roll --brightness 40 +sidepulse-net profiles set personal --state Waiting --pattern amber-pulse +sidepulse-net profiles show personal --json +sidepulse-net host start --phone default --profile personal --model dot +``` + +Unassigned states retain the original status patterns. Profile brightness applies +to all states. Profiles are loaded at host startup; restart the host after edits. +Every referenced pattern must have a variant for the selected model. Existing +running hosts retain their startup configuration; stop first to apply changes. + +## Upstream credit + +Bundled patterns are copied from `inteliwear/sidepulse` at the revision in +`upstream.json`, under its MIT license. See [[Upstream-and-Licensing]]. The managed +interpreter is a new implementation from the public format specification. diff --git a/docs/wiki/Getting-Started.md b/docs/wiki/Getting-Started.md index ab540dd..05bcf15 100644 --- a/docs/wiki/Getting-Started.md +++ b/docs/wiki/Getting-Started.md @@ -178,3 +178,8 @@ The event mapping follows the [GitHub Copilot hook reference](https://docs.githu Actual Copilot/Windows and phone/hardware validation remain separate from unit and simulated transport tests. Keep the working Python installation available until this preview is validated on your setup. + +## Animation studio + +See [[Animations]] for Dot/Pro previews, custom editing and agent profiles, and +[[Scripting-and-Menus]] for interactive command building and quiet/JSON output. diff --git a/docs/wiki/Roadmap.md b/docs/wiki/Roadmap.md index 8831de2..df35e26 100644 --- a/docs/wiki/Roadmap.md +++ b/docs/wiki/Roadmap.md @@ -1,7 +1,11 @@ # Roadmap -All application work is planned. Only the initial documentation and automation -scaffolding are prepared. +The implementation preview now includes USB file output, protected phone links, +four agent integrations, a background host, Dot/Pro patterns, a managed animation +interpreter, Spectre previews and custom editing, profiles, menus and script output. +See [[Getting-Started]], [[Animations]] and [[Scripting-and-Menus]]. Native CI checks +are distinct from actual hardware/provider verification, which remains pending. +The milestone descriptions below retain broader acceptance targets. ## M0: Concept and project foundation diff --git a/docs/wiki/Scripting-and-Menus.md b/docs/wiki/Scripting-and-Menus.md new file mode 100644 index 0000000..05c647a --- /dev/null +++ b/docs/wiki/Scripting-and-Menus.md @@ -0,0 +1,57 @@ +# Scripting and interactive menus + +In a terminal, `sidepulse-net` opens an arrow-key menu. Bare groups `animations`, +`profiles`, `agents`, `host`, `link`, and `about` open their respective menus. +Up/Down select, Enter continues, Escape goes back. Fully specified commands always +execute directly. The legacy `host --phone default` shorthand remains supported. + +Guided actions display a single-line script command before running. Review offers +Run, Copy command, Choose shell and Back. PowerShell and Bash quoting preserve +literal values; CMD export rejects values it cannot safely represent. Clipboard +support uses the OS clipboard or installed `wl-copy` / `xclip`; otherwise copy the +printed line. Secrets are represented by phone aliases or environment variable +names, never token values. Editor commands reference the selected file; save it +before using a preview command elsewhere. + +Menus require both stdin and stdout to be terminals. Redirecting either stream, +passing `--no-interactive`, `--quiet`, or `--json` prevents menus. Bare groups then +show command help. No arguments show help. Missing required arguments fail without +prompting. Editors require a terminal. QR pairing remains an explicit pairing +operation with its existing timeout; it is not a script configuration wizard. + +Global flags may precede or follow subcommands: + +- `--quiet`: suppress stdout, preserve stderr and exit status. +- `--json`: structured output on commands advertising JSON. Takes precedence over + quiet. Runtime errors are JSON on stderr, never mixed with stdout data. +- `--no-interactive`: disable cursor menus and interactive playback. +- `--no-color`: disable ANSI colors. `NO_COLOR` and redirected stdout also disable + color. A non-interactive preview prints a single RGB frame instead of animating. + +Exit 0 indicates successful command execution, 1 indicates an error. Delivery +success means the OS or bridge accepted the write, not hardware acknowledgement. +Raw `write` retains envelope-only validation for forward compatibility; use +`animations validate` for grammar validation. Global flags are reserved before +`--`; literal values containing a flag should be passed after `--` where supported. + +```sh +sidepulse-net animations validate --file build.LED --quiet +sidepulse-net animations preview --file build.LED --model dot --at 500 --json +sidepulse-net state Working --phone default --quiet +sidepulse-net devices --json +sidepulse-net about credits --json +sidepulse-net about licenses --full +sidepulse-net about github +sidepulse-net about github --open +sidepulse-net docs --offline +``` + +`about` includes manufacturer, project and upstream links, credits, dependency +versions, license identifiers, and offline license texts. Browser launch is opt-in +through `--open`. Offline animation/scripting documentation ships with previews. +The public wiki receives these pages after the implementation branch is merged. + +The manufacturer's affiliate program currently requires individual approval. The +application uses ordinary manufacturer URLs; no referral identifier is fabricated. +An approved affiliate link would require clear disclosure next to it. See the +[official program](https://sidepulse.io/affiliates.html). diff --git a/docs/wiki/_Sidebar.md b/docs/wiki/_Sidebar.md index 11ecb0b..ae14e22 100644 --- a/docs/wiki/_Sidebar.md +++ b/docs/wiki/_Sidebar.md @@ -18,3 +18,6 @@ - [[Agent integrations|Agent-Integrations]] - [[Host management|Host-Management]] + +- [[Animations]] +- [[Scripting and menus|Scripting-and-Menus]] diff --git a/scripts/agent_smoke.py b/scripts/agent_smoke.py index 66c297e..4274f5e 100644 --- a/scripts/agent_smoke.py +++ b/scripts/agent_smoke.py @@ -41,10 +41,14 @@ def status(): assert json.loads(run('agents', 'status', provider, '--config', str(path), '--json'))['State'] == 'installed' configs[provider] = (path, json.loads(path.read_text())) + pattern = root / 'working.LED' + pattern.write_text('off\n#123456\n') + run('animations', 'import', 'smoke-working', '--file', str(pattern), '--model', 'dot', '--quiet') + run('profiles', 'set', 'smoke', '--state', 'Working', '--pattern', 'smoke-working', '--brightness', '40', '--quiet') print("Agent setup/preview checks passed; starting detached host.", flush=True) started = False try: - first = json.loads(run('host', 'start', '--exe', exe, '--device', directory, '--json', timeout=25)) + first = json.loads(run('host', 'start', '--exe', exe, '--device', directory, '--profile', 'smoke', '--model', 'dot', '--json', timeout=25)) started = True print('Detached host ready.', flush=True) assert first['Running'] @@ -81,6 +85,11 @@ def send(provider, event): time.sleep(0.1) assert len(snapshot['Sessions']) == 4, snapshot assert {s['Provider'] for s in snapshot['Sessions']} == {'Copilot', 'Codex', 'Claude', 'Kiro'} + for _ in range(30): + if target.read_text().strip() == 'brightness 102\noff\n#123456': + break + time.sleep(0.1) + assert target.read_text().strip() == 'brightness 102\noff\n#123456' send('claude', 'Stop') assert status()['State'] == 'Working' for provider in ('copilot', 'codex', 'kiro'): diff --git a/scripts/animation_smoke.py b/scripts/animation_smoke.py new file mode 100644 index 0000000..5fd5423 --- /dev/null +++ b/scripts/animation_smoke.py @@ -0,0 +1,66 @@ +"""Exercise animation, script output and offline credits against built/published CLI.""" +import json +import os +from pathlib import Path +import subprocess +import sys +import tempfile + + +def main(executable): + executable = str(Path(executable).resolve()) + with tempfile.TemporaryDirectory(prefix='sidepulse animations ü ') as temporary: + root = Path(temporary) + env = dict(os.environ, SIDEPULSE_NET_HOME=str(root / 'config'), NO_COLOR='1') + + def run(*args, code=0): + result = subprocess.run([executable, *args], env=env, capture_output=True, text=True, timeout=10) + assert result.returncode == code, (args, result.returncode, result.stdout, result.stderr) + assert '\x1b' not in result.stdout + result.stderr, args + if code == 0: + assert not result.stderr, (args, result.stderr) + return result + + patterns = json.loads(run('animations', 'list', '--json').stdout) + assert any(p['Name'] == 'cyan-roll' and p['Models'] == ['Dot', 'Pro'] for p in patterns) + frames = json.loads(run('animations', 'preview', 'cyan-roll', '--both', '--at', '500', '--json').stdout) + assert [len(f['colors']) for f in frames] == [2, 8] + assert len(run('animations', 'preview', 'cyan-roll', '--seconds', '600').stdout.splitlines()) == 1 + source = root / "Ned's custom.LED" + source.write_text('off\n0:#ff0000 1s pulse; 1:#00ff00 1s\nrepeat\n', encoding='utf-8') + assert run('animations', 'validate', str(source), '--quiet').stdout == '' + error = run('animations', 'validate', '--file', str(root / 'missing.LED'), '--json', code=1) + assert not error.stdout and 'error' in json.loads(error.stderr) + run('animations', 'import', 'personal', '--file', str(source), '--model', 'dot', '--quiet') + run('animations', 'import', 'personal', '--file', str(source), '--model', 'dot', code=1) + exported = root / 'exported.LED' + run('animations', 'export', 'personal', '--output', str(exported), '--quiet') + assert exported.read_text(encoding='utf-8') == source.read_text(encoding='utf-8') + run('animations', 'export', 'personal', '--output', str(exported), code=1) + device = root / 'LEDS.LED' + device.write_text('old data', encoding='utf-8') + assert not run('animations', 'apply', 'personal', '--model', 'dot', '--device', str(device), '--brightness', '40', '--quiet').stdout + assert device.read_text(encoding='utf-8').startswith('brightness 102\n') + run('animations', 'apply', 'personal', '--model', 'pro', '--device', str(device), code=1) + run('profiles', 'set', 'mine', '--state', 'Working', '--pattern', 'personal', '--brightness', '40', '--quiet') + profile = json.loads(run('profiles', 'show', 'mine', '--json').stdout) + assert profile['Brightness'] == 40 and profile['States']['Working'] == 'personal' + assert not run('state', 'Done', '--dry-run', '--quiet').stdout + assert json.loads(run('state', 'Done', '--dry-run', '--quiet', '--json').stdout)['dryRun'] + run('animations', 'edit', '--file', str(source), code=1) + run('state', code=1) + assert 'COMMANDS' in run('about').stdout + assert 'COMMANDS' in run('host').stdout + assert 'USAGE' in run().stdout + assert json.loads(run('about', 'info', '--json').stdout)['unofficial'] + assert run('about', 'website').stdout.strip() == 'https://sidepulse.io/' + credits = json.loads(run('about', 'credits', '--json').stdout) + assert len(credits['dependencies']) == 7 + licenses = json.loads(run('about', 'licenses', '--full', '--json').stdout) + assert len(licenses['notices']) >= 10 and all(n['text'] for n in licenses['notices']) + assert len(json.loads(run('docs', '--offline', '--json').stdout)) >= 2 + print('Animation studio, script output and offline credits smoke passed.') + + +if __name__ == '__main__': + main(sys.argv[1]) diff --git a/scripts/terminal_smoke.py b/scripts/terminal_smoke.py new file mode 100644 index 0000000..f1c011c --- /dev/null +++ b/scripts/terminal_smoke.py @@ -0,0 +1,102 @@ +"""Exercise real cursor menus and editor/preview controls on Unix pseudo terminals.""" +import os +from pathlib import Path +import select +import struct +import subprocess +import sys +import tempfile +import time + + +def main(executable): + if os.name == 'nt': + print('PTY smoke uses Unix APIs; Windows runs the redirected CLI smoke.') + return + import fcntl + import pty + import termios + executable = str(Path(executable).resolve()) + with tempfile.TemporaryDirectory(prefix='sidepulse terminal ') as temporary: + root = Path(temporary) + env = dict(os.environ, TERM='xterm-256color', COLORTERM='truecolor', SIDEPULSE_NET_HOME=str(root / 'config')) + env.pop('NO_COLOR', None) + + class Terminal: + def __init__(self, args): + self.master, slave = pty.openpty() + fcntl.ioctl(slave, termios.TIOCSWINSZ, struct.pack('HHHH', 40, 120, 0, 0)) + self.process = subprocess.Popen([executable, *args], stdin=slave, stdout=slave, stderr=slave, env=env) + os.close(slave) + self.output = b'' + + def until(self, text): + needle = text.encode('utf-8') + deadline = time.monotonic() + 10 + while time.monotonic() < deadline: + if select.select([self.master], [], [], 0.1)[0]: + try: + data = os.read(self.master, 65536) + except OSError: + break + self.output += data + if needle in self.output: + self.output = b'' + return + if self.process.poll() is not None: + break + raise AssertionError((text, self.process.poll(), self.output[-3000:].decode('utf-8', errors='replace'))) + + def send(self, keys): + os.write(self.master, keys) + + def finish(self): + try: + assert self.process.wait(timeout=10) == 0 + finally: + if self.process.poll() is None: + self.process.kill() + os.close(self.master) + + menu = Terminal([]) + try: + menu.until('About') + menu.send(b'\x1b[A\r') # wrap from Animations to About + menu.until('Manufacturer website') + menu.send(b'\x1b[B' * 4 + b'\r') + menu.until('Peter Kuhar') + menu.finish() + finally: + if menu.process.poll() is None: + menu.process.kill() + + file = root / 'custom.LED' + editor = Terminal(['animations', 'edit', '--file', str(file), '--model', 'dot']) + try: + editor.until('Save to library') + editor.send(b'\r') # preview + editor.until('Playing') + editor.send(b' ') + editor.until('Paused') + editor.send(b'\x1b[C') # frame step + time.sleep(0.15) + editor.send(b'r') + time.sleep(0.15) + editor.send(b'\x1b') # back to editor + editor.until('Save to library') + editor.send(b'\x1b[B' * 5 + b'\r') # save + editor.until('Save to library') + deadline = time.monotonic() + 5 + while not file.exists() and time.monotonic() < deadline: + time.sleep(0.05) + assert file.exists() and '#00e5ff' in file.read_text(encoding='utf-8') + editor.send(b'\x1b') + editor.finish() + finally: + if editor.process.poll() is None: + editor.process.kill() + print('Cursor menus, Spectre preview controls and editor save passed.') + + +if __name__ == '__main__': + main(sys.argv[1]) diff --git a/src/SidePulse.Cli/About.cs b/src/SidePulse.Cli/About.cs new file mode 100644 index 0000000..ecb8af6 --- /dev/null +++ b/src/SidePulse.Cli/About.cs @@ -0,0 +1,118 @@ +using System.Diagnostics; +using System.Reflection; +using System.Text.Json; +using Spectre.Console; +using Spectre.Console.Cli; + +namespace SidePulse.Cli; + +public sealed record DependencyCredit(string Name, string Version, string License, string Authors, string Website); +public class AboutSettings : CommandSettings +{ + [CommandOption("--json")] public bool Json { get; init; } + [CommandOption("--open")] public bool Open { get; init; } + [CommandOption("--offline")] public bool Offline { get; init; } + [CommandOption("--full")] public bool Full { get; init; } +} +public static class ProjectInfo +{ + public const string Website = "https://sidepulse.io/"; + public const string Github = "https://github.com/Anheledir/SidePulse.NET"; + public const string Upstream = "https://github.com/inteliwear/sidepulse"; + public const string Wiki = Github + "/wiki"; + private static Assembly Assembly => typeof(ProjectInfo).Assembly; + public static string Version => Assembly.GetCustomAttribute()?.InformationalVersion.Split('+')[0] ?? "unknown"; + public static IReadOnlyList Dependencies + { + get + { + using var stream = Assembly.GetManifestResourceStream("SidePulse.Cli.Dependencies.json") ?? throw new IOException("Dependency credits are missing."); + return JsonSerializer.Deserialize(stream, new JsonSerializerOptions { PropertyNameCaseInsensitive = true })!; + } + } + public static IReadOnlyList LicenseResources => Assembly.GetManifestResourceNames().Where(n => n.Contains(".Licenses.", StringComparison.Ordinal)).Order(StringComparer.Ordinal).ToArray(); + public static string LicenseText(string name) + { + using var reader = new StreamReader(Assembly.GetManifestResourceStream(name)!); return reader.ReadToEnd(); + } + public static int Link(string url, AboutSettings settings) + { + if (settings.Open) + { + // URLs are fixed application constants; no shell command construction. + try { Process.Start(new ProcessStartInfo(url) { UseShellExecute = true }); } + catch (Exception ex) when (ex is System.ComponentModel.Win32Exception or InvalidOperationException) { throw new IOException("Could not open the browser. Open this URL manually: " + url); } + } + if (settings.Json) Output.Print(new { url, opened = settings.Open }); else Console.WriteLine(url); + return 0; + } +} +public sealed class AboutCommand : Command +{ + public override int Execute(CommandContext context, AboutSettings settings, CancellationToken cancellationToken) + { + if (settings.Json) Output.Print(new { name = "SidePulse.NET", version = ProjectInfo.Version, license = "MIT", unofficial = true, website = ProjectInfo.Website, github = ProjectInfo.Github, upstream = ProjectInfo.Upstream }); + else Console.WriteLine($"SidePulse.NET {ProjectInfo.Version}\nUnofficial .NET companion · MIT\nOriginal SidePulse by Peter Kuhar / InteliWEAR\n{ProjectInfo.Github}"); + return 0; + } +} +public sealed class WebsiteCommand : Command +{ + public override int Execute(CommandContext context, AboutSettings settings, CancellationToken cancellationToken) => ProjectInfo.Link(ProjectInfo.Website, settings); +} +public sealed class GithubCommand : Command +{ + public override int Execute(CommandContext context, AboutSettings settings, CancellationToken cancellationToken) => ProjectInfo.Link(ProjectInfo.Github, settings); +} +public sealed class UpstreamCommand : Command +{ + public override int Execute(CommandContext context, AboutSettings settings, CancellationToken cancellationToken) => ProjectInfo.Link(ProjectInfo.Upstream, settings); +} +public sealed class DocsCommand : Command +{ + public override int Execute(CommandContext context, AboutSettings settings, CancellationToken cancellationToken) + { + if (!settings.Offline) return ProjectInfo.Link(ProjectInfo.Wiki, settings); + var directory = Path.Combine(AppContext.BaseDirectory, "docs"); + var files = Directory.Exists(directory) ? Directory.GetFiles(directory, "*.md").Order(StringComparer.Ordinal).ToArray() : []; + if (files.Length == 0) throw new IOException("Offline documentation is missing from this installation."); + if (settings.Json) Output.Print(files); else foreach (var file in files) { Console.WriteLine(Path.GetFileName(file)); Console.WriteLine(File.ReadAllText(file)); } + return 0; + } +} +public sealed class CreditsCommand : Command +{ + public override int Execute(CommandContext context, AboutSettings settings, CancellationToken cancellationToken) + { + if (settings.Json) Output.Print(new { project = "Gordon Breuer / Anheledir", upstream = "Peter Kuhar / InteliWEAR", dependencies = ProjectInfo.Dependencies }); + else + { + Console.WriteLine("SidePulse.NET: Gordon Breuer / Anheledir\nSidePulse hardware, protocol and original animations: Peter Kuhar / InteliWEAR\n" + ProjectInfo.Upstream); + foreach (var dependency in ProjectInfo.Dependencies) Console.WriteLine($"{dependency.Name} {dependency.Version} · {dependency.Authors} · {dependency.License}\n {dependency.Website}"); + Console.WriteLine("Thank you to the maintainers and contributors. Use about licenses --full for bundled license texts."); + } + return 0; + } +} +public sealed class LicensesCommand : Command +{ + public override int Execute(CommandContext context, AboutSettings settings, CancellationToken cancellationToken) + { + var resources = ProjectInfo.LicenseResources; + var runtimeDirectory = Path.Combine(AppContext.BaseDirectory, "third-party", "dotnet"); + var runtime = Directory.Exists(runtimeDirectory) ? Directory.GetFiles(runtimeDirectory).Order(StringComparer.Ordinal).ToArray() : []; + if (settings.Json) Output.Print(new { project = "MIT", dependencies = ProjectInfo.Dependencies, notices = resources.Select(r => new { name = r, text = settings.Full ? ProjectInfo.LicenseText(r) : null }), runtimeNotices = runtime.Select(r => new { name = Path.GetFileName(r), text = settings.Full ? File.ReadAllText(r) : null }) }); + else + { + Console.WriteLine("SidePulse.NET · MIT"); + foreach (var dependency in ProjectInfo.Dependencies) Console.WriteLine($"{dependency.Name} {dependency.Version} · {dependency.License}"); + if (settings.Full) + { + foreach (var resource in resources) { Console.WriteLine("\n" + resource); Console.WriteLine(ProjectInfo.LicenseText(resource)); } + foreach (var path in runtime) { Console.WriteLine("\n" + Path.GetFileName(path)); Console.WriteLine(File.ReadAllText(path)); } + } + else Console.WriteLine("Use --full for offline license texts and notices, including the runtime when bundled."); + } + return 0; + } +} diff --git a/src/SidePulse.Cli/Animations.cs b/src/SidePulse.Cli/Animations.cs new file mode 100644 index 0000000..0307072 --- /dev/null +++ b/src/SidePulse.Cli/Animations.cs @@ -0,0 +1,234 @@ +using System.Diagnostics; +using SidePulse.Core; +using Spectre.Console; +using Spectre.Console.Cli; +using Spectre.Console.Rendering; + +namespace SidePulse.Cli; + +public class PatternSettings : CommandSettings +{ + [CommandArgument(0, "[NAME]")] public string? Name { get; init; } + [CommandOption("--file ")] public string? File { get; init; } + [CommandOption("--model ")] public DeviceModel Model { get; init; } = DeviceModel.Dot; + [CommandOption("--brightness ")] public int? Brightness { get; init; } + [CommandOption("--json")] public bool Json { get; init; } + public override ValidationResult Validate() + { + if (!Enum.IsDefined(Model)) return ValidationResult.Error("Choose dot or pro."); + if (Brightness is < 0 or > 100) return ValidationResult.Error("Brightness must be 0..100."); + return (Name is null) == (File is null) ? ValidationResult.Error("Supply a pattern name or --file, but not both.") : ValidationResult.Success(); + } + public LedProgram Read() => AnimationLibrary.WithBrightness(File is { } file ? new LedProgram(System.IO.File.ReadAllText(file)) : AnimationLibrary.Default.Get(Name!, Model), Brightness); +} +public sealed class PatternListCommand : Command +{ + public override int Execute(CommandContext context, DevicesSettings settings, CancellationToken cancellationToken) + { + var items = AnimationLibrary.Default.List(); + if (settings.Json) Output.Print(items); + else if (!TerminalMode.Interactive) foreach (var item in items) Console.WriteLine($"{item.Name}\t{item.Source}\t{string.Join(',', item.Models)}"); + else + { + var table = new Table().Border(TableBorder.Rounded).AddColumn("Pattern").AddColumn("Source").AddColumn("Models"); + foreach (var item in items) table.AddRow(item.Name, item.Source, string.Join(", ", item.Models)); + AnsiConsole.Write(table); + } + return 0; + } +} +public sealed class PatternValidateCommand : Command +{ + public override int Execute(CommandContext context, PatternSettings settings, CancellationToken cancellationToken) + { + // Positional paths are accepted by validate for convenient scripting. + var program = settings.File is null && settings.Name is { } name && System.IO.File.Exists(name) + ? AnimationLibrary.WithBrightness(new(System.IO.File.ReadAllText(name)), settings.Brightness) : settings.Read(); + var animation = Animation.Parse(program, settings.Model); + if (settings.Json) Output.Print(new { valid = true, model = settings.Model, bytes = program.ByteCount, lines = program.LineCount, instructions = animation.Instructions.Count }); + else Console.WriteLine($"Valid ({program.ByteCount} bytes, {program.LineCount} lines, {settings.Model})."); + return 0; + } +} +public sealed class PreviewSettings : PatternSettings +{ + [CommandOption("--seconds ")] public double Seconds { get; init; } = 10; + [CommandOption("--at ")] public int At { get; init; } + [CommandOption("--both")] public bool Both { get; init; } + public override ValidationResult Validate() + { + var result = base.Validate(); + if (!result.Successful) return result; + return !double.IsFinite(Seconds) || Seconds is < 0 or > 600 || At is < 0 or > 600000 ? ValidationResult.Error("Seconds must be 0..600; --at must be 0..600000ms.") : ValidationResult.Success(); + } +} +public static class PatternPreview +{ + public static async Task Show(LedProgram program, DeviceModel model, double seconds, int at, bool both, string command, CancellationToken cancellationToken, Func? source = null) + { + var models = both ? Enum.GetValues() : [model]; + var players = models.Select(m => new AnimationPlayer(Animation.Parse(source?.Invoke(m) ?? program, m))).ToArray(); + foreach (var player in players) player.Advance(at); + if (!TerminalMode.Interactive || seconds == 0) + { + foreach (var pair in models.Zip(players)) Console.WriteLine($"{pair.First}: {string.Join(' ', pair.Second.Frame)}"); + return; + } + var paused = false; + var clock = Stopwatch.StartNew(); + var previous = clock.Elapsed.TotalMilliseconds; + double played = 0; + IRenderable Draw() + { + var rows = new List(); + foreach (var pair in models.Zip(players)) + { + rows.Add(new Text($"{pair.First} · {(int)pair.First} LEDs")); + var strip = new Table().NoBorder().HideHeaders(); + for (var i = 0; i < (int)pair.First; i++) strip.AddColumn(new TableColumn("").Padding(1, 0)); + strip.AddRow(pair.Second.Frame.Select(c => (IRenderable)(TerminalMode.ColorEnabled ? new Text(" ", new Style(background: new Color(c.R, c.G, c.B))) : new Text(c.ToString()))).ToArray()); + rows.Add(strip); + } + rows.Add(new Text($"{(paused ? "Paused" : "Playing")} · Space pause · Right step 100ms · R restart · Esc back")); + rows.Add(new Panel(new Text(command)).Header("Script command").Border(BoxBorder.Rounded)); + return new Panel(new Rows(rows)).Header("LED preview").Border(BoxBorder.Rounded); + } + await AnsiConsole.Live(Draw()).AutoClear(true).StartAsync(async live => + { + while (played < seconds * 1000 && !cancellationToken.IsCancellationRequested) + { + var now = clock.Elapsed.TotalMilliseconds; + var delta = now - previous; previous = now; + if (Console.KeyAvailable) + { + var key = Console.ReadKey(true).Key; + if (key is ConsoleKey.Escape or ConsoleKey.Q) break; + if (key == ConsoleKey.Spacebar) paused = !paused; + if (key == ConsoleKey.RightArrow) { paused = true; foreach (var player in players) player.Advance(100); played += 100; } + if (key == ConsoleKey.R) { players = models.Select(m => new AnimationPlayer(Animation.Parse(source?.Invoke(m) ?? program, m))).ToArray(); played = 0; } + } + if (!paused) { foreach (var player in players) player.Advance(delta); played += delta; } + live.UpdateTarget(Draw()); live.Refresh(); + await Task.Delay(50, cancellationToken); + } + }); + } +} +public sealed class PatternPreviewCommand : AsyncCommand +{ + public override async Task ExecuteAsync(CommandContext context, PreviewSettings settings, CancellationToken cancellationToken) + { + var program = settings.Read(); + if (settings.Json) + { + var models = settings.Both ? Enum.GetValues() : [settings.Model]; + Output.Print(models.Select(m => { var selected = settings.File is null ? AnimationLibrary.WithBrightness(AnimationLibrary.Default.Get(settings.Name!, m), settings.Brightness) : program; var player = new AnimationPlayer(Animation.Parse(selected, m)); player.Advance(settings.At); return new { model = m, at = settings.At, colors = player.Frame.Select(c => c.ToString()).ToArray() }; }).ToArray()); + } + else + { + var args = new List { "animations", "preview" }; + if (settings.File is { } file) args.AddRange(["--file", Path.GetFullPath(file)]); else args.Add(settings.Name!); + args.AddRange(["--model", settings.Model.ToString().ToLowerInvariant(), "--seconds", settings.Seconds.ToString(System.Globalization.CultureInfo.InvariantCulture), "--at", settings.At.ToString()]); + if (settings.Brightness is { } brightness) args.AddRange(["--brightness", brightness.ToString()]); + if (settings.Both) args.Add("--both"); + await PatternPreview.Show(program, settings.Model, settings.Seconds, settings.At, settings.Both, TerminalMode.Command(args), cancellationToken, settings.File is null ? m => AnimationLibrary.WithBrightness(AnimationLibrary.Default.Get(settings.Name!, m), settings.Brightness) : null); + } + return 0; + } +} +public sealed class PatternApplySettings : TargetSettings +{ + [CommandArgument(0, "[NAME]")] public string? Name { get; init; } + [CommandOption("--file ")] public string? File { get; init; } + [CommandOption("--model ")] public DeviceModel? Model { get; init; } + [CommandOption("--brightness ")] public int? Brightness { get; init; } + public override ValidationResult Validate() + { + var result = base.Validate(); if (!result.Successful) return result; + if (Model is { } model && !Enum.IsDefined(model)) return ValidationResult.Error("Choose dot or pro."); + if (Brightness is < 0 or > 100) return ValidationResult.Error("Brightness must be 0..100."); + return (Name is null) == (File is null) ? ValidationResult.Error("Supply a pattern name or --file.") : ValidationResult.Success(); + } +} +public sealed class PatternApplyCommand : AsyncCommand +{ + public override async Task ExecuteAsync(CommandContext context, PatternApplySettings settings, CancellationToken cancellationToken) + { + var model = settings.Model ?? AnimationLibrary.DetectModel(settings.Device); + var raw = settings.File is { } file ? new LedProgram(await System.IO.File.ReadAllTextAsync(file, cancellationToken)) : AnimationLibrary.Default.Get(settings.Name!, model); + var program = AnimationLibrary.WithBrightness(raw, settings.Brightness); + Animation.Parse(program, model); + await Delivery.Send(settings, program, cancellationToken); Delivery.Receipt(settings, program); + return 0; + } +} +public sealed class PatternImportSettings : CommandSettings +{ + [CommandArgument(0, "")] public string Name { get; init; } = ""; + [CommandOption("--file ")] public string File { get; init; } = ""; + [CommandOption("--model ")] public DeviceModel Model { get; init; } = DeviceModel.Dot; + [CommandOption("--force")] public bool Force { get; init; } + [CommandOption("--json")] public bool Json { get; init; } + public override ValidationResult Validate() => string.IsNullOrWhiteSpace(File) || !Enum.IsDefined(Model) ? ValidationResult.Error("Supply --file and a valid --model.") : ValidationResult.Success(); +} +public sealed class PatternImportCommand : Command +{ + public override int Execute(CommandContext context, PatternImportSettings settings, CancellationToken cancellationToken) + { + var path = AnimationLibrary.Default.Save(settings.Name, settings.Model, new(System.IO.File.ReadAllText(settings.File)), settings.Force); + if (settings.Json) Output.Print(new { saved = path }); else Console.WriteLine(path); + return 0; + } +} +public sealed class PatternExportSettings : PatternSettings +{ + [CommandOption("--output ")] public string? Destination { get; init; } + [CommandOption("--force")] public bool Force { get; init; } +} +public sealed class PatternExportCommand : Command +{ + public override int Execute(CommandContext context, PatternExportSettings settings, CancellationToken cancellationToken) + { + var program = settings.Read(); Animation.Parse(program, settings.Model); + if (settings.Destination is { } path) AnimationLibrary.WriteFile(path, program.Text + "\n", settings.Force); + if (settings.Json) Output.Print(new { program = program.Text, output = settings.Destination }); + else if (settings.Destination is null) Console.WriteLine(program.Text); + else Console.WriteLine(Path.GetFullPath(settings.Destination)); + return 0; + } +} +public sealed class ProfileSettings : CommandSettings +{ + [CommandArgument(0, "")] public string Name { get; init; } = ""; + [CommandOption("--state ")] public AgentState? State { get; init; } + [CommandOption("--pattern ")] public string? Pattern { get; init; } + [CommandOption("--brightness ")] public int? Brightness { get; init; } + [CommandOption("--json")] public bool Json { get; init; } + public override ValidationResult Validate() => (State is { } state && !Enum.IsDefined(state)) || Brightness is < 0 or > 100 ? ValidationResult.Error("Choose a valid state and brightness 0..100.") : ValidationResult.Success(); +} +public sealed class ProfileSetCommand : Command +{ + public override int Execute(CommandContext context, ProfileSettings settings, CancellationToken cancellationToken) + { + if (settings.Pattern is null || settings.State is null) throw new ArgumentException("Supply --state and --pattern."); + if (!AnimationLibrary.Default.List().Any(p => p.Name == settings.Pattern)) throw new ArgumentException("Pattern was not found. Import it first."); + AnimationProfile profile; + try { profile = AnimationLibrary.Default.LoadProfile(settings.Name); } + catch (FileNotFoundException) { profile = new([]); } + profile.States[settings.State.Value] = settings.Pattern; + profile = profile with { Brightness = settings.Brightness ?? profile.Brightness }; + var path = AnimationLibrary.Default.SaveProfile(settings.Name, profile, true); + if (settings.Json) Output.Print(new { path, profile }); else Console.WriteLine(path); + return 0; + } +} +public sealed class ProfileShowCommand : Command +{ + public override int Execute(CommandContext context, ProfileSettings settings, CancellationToken cancellationToken) + { + var profile = AnimationLibrary.Default.LoadProfile(settings.Name); + if (settings.Json) Output.Print(profile); + else { Console.WriteLine($"Brightness: {profile.Brightness}%"); foreach (var pair in profile.States) Console.WriteLine($"{pair.Key}: {pair.Value}"); } + return 0; + } +} diff --git a/src/SidePulse.Cli/Dependencies.json b/src/SidePulse.Cli/Dependencies.json new file mode 100644 index 0000000..44fa2e6 --- /dev/null +++ b/src/SidePulse.Cli/Dependencies.json @@ -0,0 +1,51 @@ +[ + { + "name": "QRCoder", + "version": "1.8.1", + "license": "MIT", + "authors": "Raffael Herrmann, Shane Krueger", + "website": "" + }, + { + "name": "Spectre.Console", + "version": "0.57.2", + "license": "MIT", + "authors": "Patrik Svensson, Phil Scott, Nils Andresen, C\u00e9dric Luthi", + "website": "https://github.com/spectreconsole/spectre.console" + }, + { + "name": "Spectre.Console.Cli", + "version": "0.57.2", + "license": "MIT", + "authors": "Patrik Svensson, Phil Scott, Nils Andresen, C\u00e9dric Luthi, Frank Ray", + "website": "https://github.com/spectreconsole/spectre.console.cli" + }, + { + "name": "Microsoft.Win32.SystemEvents", + "version": "6.0.0", + "license": "MIT", + "authors": "Microsoft", + "website": "https://dot.net/" + }, + { + "name": "Spectre.Console.Ansi", + "version": "0.57.2", + "license": "MIT", + "authors": "Patrik Svensson, Phil Scott, Nils Andresen, C\u00e9dric Luthi", + "website": "https://github.com/spectreconsole/spectre.console" + }, + { + "name": "System.Drawing.Common", + "version": "6.0.0", + "license": "MIT", + "authors": "Microsoft", + "website": "https://dot.net/" + }, + { + "name": "System.Security.Cryptography.ProtectedData", + "version": "10.0.13", + "license": "MIT", + "authors": "Microsoft", + "website": "https://dot.net/" + } +] diff --git a/src/SidePulse.Cli/Hooks.cs b/src/SidePulse.Cli/Hooks.cs index eafb1cc..2c5cd87 100644 --- a/src/SidePulse.Cli/Hooks.cs +++ b/src/SidePulse.Cli/Hooks.cs @@ -96,6 +96,10 @@ public override async Task ExecuteAsync(CommandContext context, HookSetting } public sealed class HostSettings : TargetSettings { + [CommandOption("--profile ")] + public string? Profile { get; init; } + [CommandOption("--model ")] + public DeviceModel? Model { get; init; } [CommandOption("--log-file ")] public string? LogFile { get; init; } [CommandOption("--background")] @@ -103,11 +107,17 @@ public sealed class HostSettings : TargetSettings [CommandOption("--plain")] [Description("Write plain state changes instead of terminal panels.")] public bool Plain { get; init; } + public override ValidationResult Validate() + { + var result = base.Validate(); + return !result.Successful ? result : Model is { } model && !Enum.IsDefined(model) ? ValidationResult.Error("Choose dot or pro.") : ValidationResult.Success(); + } } public sealed class HostCommand : AsyncCommand { public override async Task ExecuteAsync(CommandContext context, HostSettings settings, CancellationToken cancellationToken) { + var patterns = AnimationLibrary.ResolveProfile(settings.Profile, settings.Model, settings.Device); if (settings.Background) HostLogs.Detach(); using var shutdown = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); ConsoleCancelEventHandler cancel = (_, args) => { args.Cancel = true; shutdown.Cancel(); }; @@ -189,7 +199,7 @@ public override async Task ExecuteAsync(CommandContext context, HostSetting // Re-enqueue repeated states to recover after a failed delivery. if (state != queued || !settings.DryRun) { - outputs.Writer.TryWrite(LedProgram.ForState(state)); + outputs.Writer.TryWrite(patterns[state]); queued = state; } } diff --git a/src/SidePulse.Cli/HostManagement.cs b/src/SidePulse.Cli/HostManagement.cs index 704bc32..d291cbe 100644 --- a/src/SidePulse.Cli/HostManagement.cs +++ b/src/SidePulse.Cli/HostManagement.cs @@ -64,8 +64,15 @@ public override async Task ExecuteAsync(CommandContext context, HostActionS } public sealed class HostStartSettings : TargetSettings { + [CommandOption("--profile ")] public string? Profile { get; init; } + [CommandOption("--model ")] public DeviceModel? Model { get; init; } [CommandOption("--exe ")] public string Executable { get; init; } = Environment.ProcessPath ?? "sidepulse-net"; + public override ValidationResult Validate() + { + var result = base.Validate(); + return !result.Successful ? result : Model is { } model && !Enum.IsDefined(model) ? ValidationResult.Error("Choose dot or pro.") : ValidationResult.Success(); + } } public sealed class HostStartCommand : AsyncCommand { @@ -73,6 +80,7 @@ public override async Task ExecuteAsync(CommandContext context, HostStartSe { var existing = await HostControl.Request("status", cancellationToken); if (existing.Running) { if (settings.Json) Output.Print(existing); else AnsiConsole.WriteLine("Host is already running. Stop it before changing its target."); return 0; } + _ = AnimationLibrary.ResolveProfile(settings.Profile, settings.Model, settings.Device); var exe = HookConfiguration.Executable(settings.Executable); var directory = Path.Combine(Path.GetDirectoryName(LinkStore.DefaultPath)!, "host"); if (OperatingSystem.IsWindows()) Directory.CreateDirectory(directory); @@ -85,6 +93,8 @@ public override async Task ExecuteAsync(CommandContext context, HostStartSe if (settings.Device is { } device) { info.ArgumentList.Add("--device"); info.ArgumentList.Add(Path.GetFullPath(device)); } if (settings.Phone is { } phone) { info.ArgumentList.Add("--phone"); info.ArgumentList.Add(phone); } if (settings.TokenEnvironment is { } variable) { info.ArgumentList.Add("--token-env"); info.ArgumentList.Add(variable); } + if (settings.Profile is { } profile) { info.ArgumentList.Add("--profile"); info.ArgumentList.Add(profile); } + if (settings.Model is { } model) { info.ArgumentList.Add("--model"); info.ArgumentList.Add(model.ToString()); } if (settings.DryRun) info.ArgumentList.Add("--dry-run"); using var process = Process.Start(info) ?? throw new IOException("Could not start the host."); if (!OperatingSystem.IsWindows()) process.StandardInput.Close(); diff --git a/src/SidePulse.Cli/Interactive.cs b/src/SidePulse.Cli/Interactive.cs new file mode 100644 index 0000000..48e151b --- /dev/null +++ b/src/SidePulse.Cli/Interactive.cs @@ -0,0 +1,155 @@ +using SidePulse.Core; +using Spectre.Console; +using Spectre.Console.Rendering; + +namespace SidePulse.Cli; + +public sealed record MenuItem(string Label, string[]? Arguments = null); +public static class Interactive +{ + public static string[]? Resolve(string[] args) + { + if (!TerminalMode.Interactive) + { + if (args.Length == 0) return ["--help"]; + if (args.Length == 1 && args[0] is "about" or "animations" or "agents" or "link" or "host" or "profiles") return [args[0], "--help"]; + return args; + } + if (args.Length > 1 || args.Length == 1 && args[0] is not ("about" or "animations" or "agents" or "link" or "host" or "profiles")) return args; + var group = args.FirstOrDefault(); + while (true) + { + if (group is null) + { + var selected = Choose("SidePulse.NET", [new("Animations"), new("Devices", ["devices"]), new("Display state"), new("Agent hooks"), new("Background host"), new("Phone links"), new("Profiles"), new("Diagnostics", ["doctor"]), new("About")]); + if (selected is null) return null; + if (selected.Arguments is { } direct) return direct; + group = selected.Label switch { "Animations" => "animations", "Agent hooks" => "agents", "Background host" => "host", "Phone links" => "link", "Profiles" => "profiles", "About" => "about", _ => "state" }; + } + var command = Build(group); + if (command is not null) return command; + group = null; + } + } + public static MenuItem? Choose(string title, IReadOnlyList items) + { + if (!TerminalMode.Interactive) throw new ArgumentException("This action requires an interactive terminal."); + var selected = 0; + MenuItem? result = null; + IRenderable Draw() + { + var rows = items.Select((item, i) => (IRenderable)new Text((i == selected ? "> " : " ") + item.Label, i == selected ? new Style(Color.Cyan1, decoration: Decoration.Bold) : Style.Plain)).ToList(); + rows.Add(new Text("\n↑/↓ select · Enter continue · Esc back", new Style(Color.Grey))); + if (items[selected].Arguments is { } arguments) rows.Add(new Panel(new Text(TerminalMode.Command(arguments))).Header("Script command").Border(BoxBorder.Rounded)); + return new Panel(new Rows(rows)).Header(Markup.Escape(title)).Border(BoxBorder.Rounded); + } + AnsiConsole.Live(Draw()).AutoClear(true).Start(live => + { + live.Refresh(); + while (true) + { + var key = Console.ReadKey(true).Key; + if (key == ConsoleKey.Escape) break; + if (key == ConsoleKey.Enter) { result = items[selected]; break; } + if (key == ConsoleKey.UpArrow) selected = (selected + items.Count - 1) % items.Count; + if (key == ConsoleKey.DownArrow) selected = (selected + 1) % items.Count; + live.UpdateTarget(Draw()); live.Refresh(); + } + }); + return result; + } + public static string Ask(string prompt, string? value = null) => AnsiConsole.Prompt(value is null ? new TextPrompt(Markup.Escape(prompt)) : new TextPrompt(Markup.Escape(prompt)).DefaultValue(value)); + public static T Pick(string title, IEnumerable values) where T : notnull => AnsiConsole.Prompt(new SelectionPrompt().Title(Markup.Escape(title)).AddChoices(values)); + public static string[]? Review(List arguments) + { + var shell = TerminalMode.Shell; + while (true) + { + TerminalMode.Footer(arguments, shell); + var action = Choose("Ready", [new("Run", arguments.ToArray()), new("Copy command"), new("Choose shell"), new("Back")]); + if (action is null || action.Label == "Back") return null; + if (action.Label == "Run") return arguments.ToArray(); + if (action.Label == "Choose shell") { shell = Pick("Command shell", new[] { "powershell", "bash", "cmd" }); continue; } + try { Console.WriteLine(TerminalMode.Copy(TerminalMode.Command(arguments, shell)) ? "Command copied." : "Clipboard unavailable. Select and copy the displayed command."); } + catch (ArgumentException ex) { Console.Error.WriteLine(ex.Message); shell = TerminalMode.Shell; } + } + } + private static List Target() + { + var kind = Pick("Output target", new[] { "USB / SD", "Saved phone", "Token environment variable" }); + return kind switch + { + "Saved phone" => ["--phone", Ask("Saved phone alias", "default")], + "Token environment variable" => ["--token-env", Ask("Environment variable name")], + _ => ["--device", Path.GetFullPath(Ask("Mount directory or LEDS.LED path"))] + }; + } + private static string[]? Build(string group) + { + if (group == "about") + { + var action = Choose("About SidePulse.NET", [new("Overview", ["about", "info"]), new("Manufacturer website", ["about", "website", "--open"]), new("Project on GitHub", ["about", "github", "--open"]), new("Original project", ["about", "upstream", "--open"]), new("Credits", ["about", "credits"]), new("Libraries and licenses", ["about", "licenses"]), new("Documentation", ["docs", "--open"])]); + return action?.Arguments; + } + if (group == "animations") + { + var action = Choose("Animations", [new("List patterns", ["animations", "list"]), new("Preview pattern"), new("Preview .LED file"), new("Apply pattern"), new("Create / edit custom pattern"), new("Import pattern"), new("Export pattern")]); + if (action is null) return null; + if (action.Arguments is { } direct) return direct; + var model = Pick("LED layout", Enum.GetValues()).ToString().ToLowerInvariant(); + List command; + if (action.Label == "Create / edit custom pattern") command = ["animations", "edit", "--file", Path.GetFullPath(Ask("Pattern file path", "my-pattern.LED")), "--model", model]; + else if (action.Label == "Import pattern") command = ["animations", "import", Ask("Saved pattern name"), "--file", Path.GetFullPath(Ask("Source .LED file")), "--model", model]; + else + { + var verb = action.Label.StartsWith("Apply", StringComparison.Ordinal) ? "apply" : action.Label.StartsWith("Export", StringComparison.Ordinal) ? "export" : "preview"; + command = ["animations", verb]; + if (action.Label == "Preview .LED file") command.AddRange(["--file", Path.GetFullPath(Ask("Source .LED file"))]); + else command.Add(Pick("Pattern", AnimationLibrary.Default.List().Where(p => p.Models.Contains(Enum.Parse(model, true))).Select(p => p.Name))); + command.AddRange(["--model", model]); + command.AddRange(["--brightness", Ask("Brightness percent", "100")]); + if (verb == "apply") command.AddRange(Target()); + if (verb == "export") command.AddRange(["--output", Path.GetFullPath(Ask("Destination .LED file"))]); + } + return Review(command); + } + if (group == "profiles") + { + var action = Pick("Profiles", new[] { "Show", "Assign animation" }); + var command = new List { "profiles", action == "Show" ? "show" : "set", Ask("Profile name", "personal") }; + if (action != "Show") command.AddRange(["--state", Pick("Agent state", Enum.GetValues()).ToString(), "--pattern", Pick("Pattern", AnimationLibrary.Default.List().Select(p => p.Name)), "--brightness", Ask("Profile brightness", "100")]); + return Review(command); + } + if (group == "agents") + { + var action = Choose("Agent hooks", [new("List integrations", ["agents", "list"]), new("Install"), new("Status"), new("Uninstall")]); + if (action is null) return null; + if (action.Arguments is { } direct) return direct; + var command = new List { "agents", action.Label.ToLowerInvariant(), Pick("Agent", Enum.GetValues()).ToString() }; + if (action.Label == "Install") command.AddRange(["--exe", Path.GetFullPath(Ask("Published SidePulse.NET executable", Environment.ProcessPath!))]); + if (AnsiConsole.Confirm("Use an explicit configuration file?", false)) command.AddRange(["--config", Path.GetFullPath(Ask("Configuration path"))]); + if (action.Label != "Status" && AnsiConsole.Confirm("Preview changes only?", true)) command.Add("--dry-run"); + return Review(command); + } + if (group == "host") + { + var action = Choose("Background host", [new("Start"), new("Status", ["host", "status"]), new("Stop", ["host", "stop"]), new("Logs", ["host", "logs"])]); + if (action is null) return null; + if (action.Arguments is { } direct) return direct; + var command = new List { "host", "start" }; command.AddRange(Target()); + if (AnsiConsole.Confirm("Use a saved animation profile?", false)) command.AddRange(["--profile", Ask("Profile name"), "--model", Pick("LED layout", Enum.GetValues()).ToString()]); + return Review(command); + } + if (group == "link") + { + var action = Choose("Phone links", [new("List phones", ["link", "list"]), new("Pair"), new("Default"), new("Rename"), new("Remove")]); + if (action is null) return null; + if (action.Arguments is { } direct) return direct; + var command = new List { "link", action.Label.ToLowerInvariant(), Ask("Phone alias") }; + if (action.Label == "Rename") command.Add(Ask("New alias")); + return Review(command); + } + var state = new List { "state", Pick("Agent state", Enum.GetValues()).ToString() }; + state.AddRange(Target()); return Review(state); + } +} diff --git a/src/SidePulse.Cli/PatternEditor.cs b/src/SidePulse.Cli/PatternEditor.cs new file mode 100644 index 0000000..a920c21 --- /dev/null +++ b/src/SidePulse.Cli/PatternEditor.cs @@ -0,0 +1,108 @@ +using SidePulse.Core; +using Spectre.Console; +using Spectre.Console.Cli; + +namespace SidePulse.Cli; + +public sealed class EditorSettings : CommandSettings +{ + [CommandOption("--file ")] public string? File { get; init; } + [CommandOption("--model ")] public DeviceModel Model { get; init; } = DeviceModel.Dot; + public override ValidationResult Validate() => Enum.IsDefined(Model) ? ValidationResult.Success() : ValidationResult.Error("Choose dot or pro."); +} +public sealed class PatternEditorCommand : AsyncCommand +{ + public override async Task ExecuteAsync(CommandContext context, EditorSettings settings, CancellationToken cancellationToken) + { + if (!TerminalMode.Interactive) throw new ArgumentException("The editor requires an interactive terminal. Use animations import, validate or preview in scripts."); + var path = Path.GetFullPath(settings.File ?? Interactive.Ask("Pattern file path", "my-pattern.LED")); + var original = File.Exists(path) ? File.ReadAllText(path) : null; + var lines = original is not null ? new LedProgram(original).Text.Split('\n').ToList() : new List { "off", "#00e5ff 1.6s pulse", "repeat" }; + var dirty = false; + while (true) + { + var program = new LedProgram(string.Join('\n', lines)); + AnsiConsole.Write(new Panel(new Text(string.Join('\n', lines.Select((line, i) => $"{i + 1,2} {line}")))).Header($"{settings.Model} · {program.ByteCount}/512 bytes · {program.LineCount}/20 lines").Border(BoxBorder.Rounded)); + TerminalMode.Footer(["animations", "edit", "--file", path, "--model", settings.Model.ToString().ToLowerInvariant()]); + var action = Interactive.Choose(dirty ? "Pattern editor · unsaved" : "Pattern editor", [new("Preview"), new("Add step"), new("Edit step"), new("Delete step"), new("Loop settings"), new("Save"), new("Save to library"), new("Back")]); + if (action is null || action.Label == "Back") + { + if (!dirty || AnsiConsole.Confirm("Discard unsaved changes?", false)) return 0; + continue; + } + try + { + if (action.Label == "Preview") + { + Animation.Parse(program, settings.Model); + await PatternPreview.Show(program, settings.Model, 60, 0, false, TerminalMode.Command(["animations", "edit", "--file", path, "--model", settings.Model.ToString().ToLowerInvariant()]), cancellationToken); + continue; + } + if (action.Label is "Save" or "Save to library") + { + Animation.Parse(program, settings.Model); + var current = File.Exists(path) ? File.ReadAllText(path) : null; + if (current != original) throw new IOException("The file changed outside this editor. Reopen it to preserve those changes."); + if (action.Label == "Save to library") + { + var name = Interactive.Ask("Saved pattern name"); + var saved = AnimationLibrary.Default.Save(name, settings.Model, program); + Console.WriteLine(saved); + TerminalMode.Footer(["animations", "import", name, "--file", path, "--model", settings.Model.ToString().ToLowerInvariant()]); + } + // Detect external edits before replacing the file. + AnimationLibrary.WriteFile(path, program.Text + "\n", original is not null); + original = program.Text + "\n"; dirty = false; + TerminalMode.Footer(["animations", "preview", "--file", path, "--model", settings.Model.ToString().ToLowerInvariant()]); + continue; + } + var edited = lines.ToList(); + if (action.Label == "Loop settings") + { + edited.RemoveAll(line => line.TrimStart().StartsWith("repeat", StringComparison.Ordinal)); + var count = Interactive.Ask("Total cycles (0 forever, 1 once)", "0"); + if (!int.TryParse(count, out var cycles) || cycles is < 0 or > 65535) throw new ArgumentException("Cycles must be 0..65535."); + if (cycles != 1) edited.Add(cycles == 0 ? "repeat" : "repeat " + cycles); + } + else if (action.Label == "Add step") + { + var step = BuildStep(settings.Model); + var index = edited.FindIndex(line => line.TrimStart().StartsWith("repeat", StringComparison.Ordinal)); + edited.Insert(index < 0 ? edited.Count : index, step); + } + else + { + var index = Interactive.Pick("Line", Enumerable.Range(1, edited.Count)) - 1; + if (action.Label == "Delete step") edited.RemoveAt(index); + else + { + var method = Interactive.Pick("Edit method", new[] { "Guided step", "Raw LED syntax" }); + edited[index] = method == "Guided step" ? BuildStep(settings.Model) : Interactive.Ask("LED line", edited[index]); + } + } + Animation.Parse(new(string.Join('\n', edited)), settings.Model); + lines = edited; dirty = true; + } + catch (Exception ex) when (ex is ArgumentException or IOException or UnauthorizedAccessException) { Console.Error.WriteLine(ex.Message); } + } + } + private static string BuildStep(DeviceModel model) + { + var type = Interactive.Pick("Step type", new[] { "All LEDs", "Per LED", "Off", "Roll left", "Roll right", "Brightness" }); + if (type == "Brightness") return "brightness " + Interactive.Ask("Brightness 0..255", "128"); + var duration = Interactive.Ask("Duration", "1s"); + var easing = Interactive.Pick("Transition", Animation.Easings); + if (type.StartsWith("Roll", StringComparison.Ordinal)) return $"{(type == "Roll left" ? "roll-left" : "roll-right")} {duration} {easing}"; + var delay = Interactive.Ask("Delay", "0ms"); + if (type == "All LEDs") return $"{Rgb.Parse(Interactive.Ask("Color #RRGGBB", "#00e5ff"))} {duration} {easing} {delay}"; + if (type == "Off") return $"off {duration} {easing} {delay}"; + var segments = new List(); + for (var i = 0; i < (int)model; i++) + { + var color = Interactive.Ask($"LED {i} color (#RRGGBB or hold)", "hold"); + if (color != "hold") segments.Add($"{i}:{Rgb.Parse(color)} {duration} {easing} {delay}"); + } + if (segments.Count == 0) throw new ArgumentException("Choose at least one LED color."); + return string.Join("; ", segments); + } +} diff --git a/src/SidePulse.Cli/Program.cs b/src/SidePulse.Cli/Program.cs index dfcfb7f..e08d40f 100644 --- a/src/SidePulse.Cli/Program.cs +++ b/src/SidePulse.Cli/Program.cs @@ -2,6 +2,11 @@ using Spectre.Console.Cli; using SidePulse.Cli; +args = TerminalMode.Configure(args); +try { args = Interactive.Resolve(args) ?? []; } +catch (Exception ex) { return TerminalMode.Error(ex); } +if (args.Length == 0) return 0; + // Preserve the original foreground shorthand while adding lifecycle subcommands. if (args.Length >= 1 && args[0] == "host" && (args.Length == 1 || args[1].StartsWith('-') && args[1] is not "--help" and not "-h")) args = new[] { "host", "run" }.Concat(args.Skip(1)).ToArray(); @@ -10,7 +15,33 @@ app.Configure(config => { config.SetApplicationName("sidepulse-net"); - config.SetApplicationVersion("0.1.0-alpha.4"); + config.SetApplicationVersion("0.1.0-alpha.5"); + config.AddBranch("animations", animations => + { + animations.SetDescription("Create, validate, preview and send Dot / Pro LED patterns."); + animations.AddCommand("list"); + animations.AddCommand("preview"); + animations.AddCommand("validate"); + animations.AddCommand("apply"); + animations.AddCommand("edit"); + animations.AddCommand("import"); + animations.AddCommand("export"); + }); + config.AddBranch("profiles", profiles => + { + profiles.AddCommand("set"); + profiles.AddCommand("show"); + }); + config.AddBranch("about", about => + { + about.AddCommand("info"); + about.AddCommand("website"); + about.AddCommand("github"); + about.AddCommand("upstream"); + about.AddCommand("credits"); + about.AddCommand("licenses"); + }); + config.AddCommand("docs"); config.AddBranch("link", links => { links.SetDescription("Pair and manage protected iPhone links."); @@ -48,8 +79,8 @@ config.SetExceptionHandler((exception, _) => { // Credential-bearing HTTP exception details are never displayed. - AnsiConsole.MarkupLine("[red]Error:[/] " + Markup.Escape(exception.Message)); - return 1; + return TerminalMode.Error(exception); }); }); -return app.Run(args); +try { return app.Run(args); } +catch (Exception ex) { return TerminalMode.Error(ex); } diff --git a/src/SidePulse.Cli/SidePulse.Cli.csproj b/src/SidePulse.Cli/SidePulse.Cli.csproj index 82d123d..e21c39f 100644 --- a/src/SidePulse.Cli/SidePulse.Cli.csproj +++ b/src/SidePulse.Cli/SidePulse.Cli.csproj @@ -2,7 +2,7 @@ Exe sidepulse-net - 0.1.0-alpha.4 + 0.1.0-alpha.5 Unofficial SidePulse companion MIT @@ -12,4 +12,12 @@ + + + + + + + + diff --git a/src/SidePulse.Cli/TerminalMode.cs b/src/SidePulse.Cli/TerminalMode.cs new file mode 100644 index 0000000..337922c --- /dev/null +++ b/src/SidePulse.Cli/TerminalMode.cs @@ -0,0 +1,67 @@ +using System.Diagnostics; +using System.Text; +using Spectre.Console; + +namespace SidePulse.Cli; + +public static class TerminalMode +{ + public static bool Quiet { get; private set; } + public static bool Json { get; private set; } + public static bool Interactive { get; private set; } + public static bool ColorEnabled { get; private set; } + public static string Shell => OperatingSystem.IsWindows() ? "powershell" : "bash"; + public static string[] Configure(string[] args) + { + // Global flags are deliberately accepted before or after subcommands. + var options = args.TakeWhile(a => a != "--").ToArray(); + Quiet = options.Contains("--quiet"); Json = options.Contains("--json"); + Interactive = !Console.IsInputRedirected && !Console.IsOutputRedirected && !options.Contains("--no-interactive") && !Quiet && !Json && Environment.GetEnvironmentVariable("TERM") != "dumb"; + var noColor = options.Contains("--no-color") || Environment.GetEnvironmentVariable("NO_COLOR") is not null || Console.IsOutputRedirected; + ColorEnabled = !noColor; + if (Quiet && !Json) Console.SetOut(TextWriter.Null); + if (noColor || Quiet) AnsiConsole.Console = AnsiConsole.Create(new AnsiConsoleSettings { Out = new AnsiConsoleOutput(Console.Out), Ansi = Console.IsOutputRedirected || Quiet ? AnsiSupport.No : AnsiSupport.Detect, ColorSystem = ColorSystemSupport.NoColors }); + var literal = false; + return args.Where(a => { if (a == "--") literal = true; return literal || a is not "--quiet" and not "--no-interactive" and not "--no-color"; }).ToArray(); + } + public static int Error(Exception exception) + { + if (Json) Console.Error.WriteLine(System.Text.Json.JsonSerializer.Serialize(new { error = exception.Message })); + else Console.Error.WriteLine("Error: " + exception.Message); + return 1; + } + public static string Quote(string value, string shell) => value.IndexOfAny(['\r', '\n']) >= 0 ? throw new ArgumentException("Multiline values cannot be exported as a single-line command. Use a file instead.") : shell switch + { + "powershell" => "'" + value.Replace("'", "''") + "'", + "bash" => "'" + value.Replace("'", "'\"'\"'") + "'", + // CMD cannot faithfully represent arbitrary arguments with %, !, quotes or newlines. + "cmd" when value.IndexOfAny(['%', '!', '"', '\r', '\n']) >= 0 => throw new ArgumentException("This value cannot safely be exported for CMD. Choose PowerShell instead."), + "cmd" => "\"" + value.TrimEnd('\\') + new string('\\', 2 * (value.Length - value.TrimEnd('\\').Length)) + "\"", + _ => throw new ArgumentException("Choose powershell, bash or cmd.") + }; + public static string Command(IEnumerable args, string? shell = null) + { + shell ??= Shell; + var values = args.Select(a => Quote(a, shell)); + return "sidepulse-net " + string.Join(' ', values); + } + public static void Footer(IEnumerable args, string? shell = null) => AnsiConsole.Write(new Panel(new Text(Command(args, shell))).Header("Script command").Border(BoxBorder.Rounded)); + public static bool Copy(string text) + { + ProcessStartInfo? start = null; + if (OperatingSystem.IsWindows()) start = new("clip.exe"); + else if (OperatingSystem.IsMacOS()) start = new("/usr/bin/pbcopy"); + else if (Environment.GetEnvironmentVariable("WAYLAND_DISPLAY") is not null) start = new("wl-copy"); + else if (Environment.GetEnvironmentVariable("DISPLAY") is not null) { start = new("xclip"); start.ArgumentList.Add("-selection"); start.ArgumentList.Add("clipboard"); } + if (start is null) return false; + start.UseShellExecute = false; start.RedirectStandardInput = true; start.RedirectStandardError = true; start.RedirectStandardOutput = true; + try + { + using var process = Process.Start(start)!; + process.StandardInput.Write(text); process.StandardInput.Close(); + if (!process.WaitForExit(1500)) { process.Kill(true); return false; } + return process.ExitCode == 0; + } + catch (Exception ex) when (ex is System.ComponentModel.Win32Exception or IOException or InvalidOperationException) { return false; } + } +} diff --git a/src/SidePulse.Core/Animation.cs b/src/SidePulse.Core/Animation.cs new file mode 100644 index 0000000..ac4371d --- /dev/null +++ b/src/SidePulse.Core/Animation.cs @@ -0,0 +1,192 @@ +using System.Globalization; +using System.Text.RegularExpressions; + +namespace SidePulse.Core; + +public enum DeviceModel { Dot = 2, Pro = 8 } +public readonly record struct Rgb(byte R, byte G, byte B) +{ + public static Rgb Parse(string value) + { + if (!Regex.IsMatch(value, "^#[0-9a-fA-F]{6}$", RegexOptions.CultureInvariant)) throw new ArgumentException("Expected a #RRGGBB color."); + return new(byte.Parse(value[1..3], NumberStyles.HexNumber), byte.Parse(value[3..5], NumberStyles.HexNumber), byte.Parse(value[5..7], NumberStyles.HexNumber)); + } + public static Rgb Blend(Rgb a, Rgb b, double amount) => new(Channel(a.R, b.R, amount), Channel(a.G, b.G, amount), Channel(a.B, b.B, amount)); + private static byte Channel(byte a, byte b, double amount) => (byte)Math.Clamp(Math.Round(a + (b - a) * amount), 0, 255); + public Rgb Scale(double value) => Blend(default, this, value); + public override string ToString() => $"#{R:x2}{G:x2}{B:x2}"; +} +public sealed record LedTransition(int Index, Rgb Color, double Duration, double Delay, string Easing); +public sealed record AnimationInstruction(IReadOnlyList Transitions, double Duration, int Roll = 0, string Easing = "linear", int? Repeat = null, int? Brightness = null); + +/// Managed interpreter of the upstream LEDS.LED language. Terminal rendering is an approximation, not firmware acknowledgement. +public sealed class Animation +{ + public LedProgram Program { get; } + public DeviceModel Model { get; } + public IReadOnlyList Instructions { get; } + public static readonly string[] Easings = ["linear", "ease", "ease-in", "ease-out", "ease-in-out", "cosine", "pulse", "none"]; + private Animation(LedProgram program, DeviceModel model, IReadOnlyList instructions) => (Program, Model, Instructions) = (program, model, instructions); + public static Animation Parse(LedProgram program, DeviceModel model) + { + if (!Enum.IsDefined(model)) throw new ArgumentException("Choose dot or pro."); + var instructions = new List(); + var number = 0; + var hasStep = false; + foreach (var raw in program.Text.Split('\n')) + { + number++; + var line = raw.Trim(); + if (line.Length == 0 || line.StartsWith(';') || line.StartsWith("//", StringComparison.Ordinal) || line.StartsWith("# ", StringComparison.Ordinal)) continue; + try + { + var words = line.Split((char[]?)null, StringSplitOptions.RemoveEmptyEntries); + if (words[0] == "brightness") + { + if (words.Length != 2 || !int.TryParse(words[1], out var brightness) || brightness is < 0 or > 255) throw new ArgumentException("Brightness must be 0..255."); + instructions.Add(new([], 0, Brightness: brightness)); + } + else if (words[0] == "repeat") + { + if (!hasStep || words.Length > 2) throw new ArgumentException("Repeat must follow an animation step."); + var count = 0; + if (words.Length == 2 && (!int.TryParse(words[1], out count) || count is < 1 or > 65535)) throw new ArgumentException("Repeat count must be 1..65535."); + instructions.Add(new([], 0, Repeat: count)); + } + else if (words[0] is "roll" or "roll-left" or "roll-right") + { + if (words.Length is < 2 or > 3) throw new ArgumentException("Roll requires a duration and optional easing."); + var duration = Time(words[1]); + var easing = words.Length == 3 ? words[2] : "linear"; + if (!Easings.Contains(easing)) throw new ArgumentException("Unknown easing."); + instructions.Add(new([], Math.Max(1000d / 60, duration), words[0] == "roll-left" ? -1 : 1, easing)); + hasStep = true; + } + else + { + var changes = new Dictionary(); + double duration = 1000d / 60; + foreach (var segment in line.Split(';')) + { + var tokens = segment.Split((char[]?)null, StringSplitOptions.RemoveEmptyEntries); + if (tokens.Length == 0) throw new ArgumentException("Empty animation segment."); + var position = 0; + var colors = new List<(int Index, Rgb Color)>(); + var indexed = tokens[0].Contains(':'); + var off = tokens[0] == "off"; + if (off) { position++; for (var i = 0; i < (int)model; i++) colors.Add((i, default)); } + else + { + while (position < tokens.Length && (tokens[position].StartsWith('#') || tokens[position].Contains(':'))) + { + var token = tokens[position++]; + if (indexed) + { + var pair = token.Split(':'); + if (pair.Length != 2 || !int.TryParse(pair[0], NumberStyles.None, CultureInfo.InvariantCulture, out var index) || index is < 0 or > 255) throw new ArgumentException("Invalid LED index."); + colors.Add((index, Rgb.Parse(pair[1]))); + } + else colors.Add((colors.Count, Rgb.Parse(token))); + } + if (colors.Count == 0) throw new ArgumentException("Expected a color, indexed colors, off or roll."); + if (!indexed) + { + if (colors.Count == 1) { var color = colors[0].Color; colors.Clear(); for (var i = 0; i < (int)model; i++) colors.Add((i, color)); } + else for (var i = colors.Count; i < (int)model; i++) colors.Add((i, default)); + } + } + double? milliseconds = null; + var curve = "linear"; + var explicitCurve = false; + double delay = 0; + if (position < tokens.Length && IsTime(tokens[position])) milliseconds = Time(tokens[position++]); + if (position < tokens.Length && Easings.Contains(tokens[position])) { curve = tokens[position++]; explicitCurve = true; } + if (position < tokens.Length && IsTime(tokens[position])) delay = Time(tokens[position++]); + if (position != tokens.Length) throw new ArgumentException("Unexpected timing or easing token."); + var length = milliseconds ?? (explicitCurve ? 330 : 0); + foreach (var color in colors.Where(c => c.Index < (int)model)) changes[color.Index] = new(color.Index, color.Color, length, delay, curve); + duration = Math.Max(duration, length + delay); + } + instructions.Add(new(changes.Values.ToArray(), duration)); + hasStep = true; + } + } + catch (ArgumentException ex) { throw new ArgumentException($"Line {number}: {ex.Message}", ex); } + } + if (!hasStep) throw new ArgumentException("The program has no animation steps."); + return new(program, model, instructions); + } + private static bool IsTime(string value) => Regex.IsMatch(value, @"^(?:[0-9]+ms|[0-9]+(?:\.[0-9]+)?s)$", RegexOptions.CultureInvariant); + private static double Time(string value) + { + if (!IsTime(value)) throw new ArgumentException("Expected integer milliseconds or seconds (for example 250ms or 1.5s)."); + var milliseconds = value.EndsWith("ms", StringComparison.Ordinal); + if (!double.TryParse(value[..(milliseconds ? ^2 : ^1)], NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out var number)) throw new ArgumentException("Invalid duration."); + var result = number * (milliseconds ? 1 : 1000); + if (!double.IsFinite(result) || result > 65535) throw new ArgumentException("Timing exceeds 65535ms."); + return result; + } + internal static double Ease(string easing, double t) => easing switch + { + "none" => 1, + "ease-in" => t * t, + "ease-out" => 1 - (1 - t) * (1 - t), + "ease" or "ease-in-out" => t * t * (3 - 2 * t), + "cosine" => (1 - Math.Cos(t * Math.PI)) / 2, + "pulse" => (1 - Math.Cos(t * 2 * Math.PI)) / 2, + _ => t + }; +} + +public sealed class AnimationPlayer(Animation animation, int brightness = 100) +{ + private readonly Rgb[] colors = new Rgb[(int)animation.Model]; + private Rgb[] start = new Rgb[(int)animation.Model]; + private readonly Dictionary repeats = []; + private int instruction; + private int firmwareBrightness = 255; + private double elapsed; + private bool entered; + public bool Complete => instruction >= animation.Instructions.Count; + public IReadOnlyList Frame => colors.Select(c => c.Scale(firmwareBrightness / 255d * Math.Clamp(brightness, 0, 100) / 100d)).ToArray(); + public void Advance(double milliseconds) + { + if (!double.IsFinite(milliseconds) || milliseconds < 0) throw new ArgumentException("Time must be finite and nonnegative."); + for (var budget = 0; !Complete; budget++) + { + if (budget > 1_000_000) throw new ArgumentException("Simulation time exceeds the instruction budget."); + var step = animation.Instructions[instruction]; + if (step.Brightness is { } value) { firmwareBrightness = value; instruction++; continue; } + if (step.Repeat is { } count) + { + var iteration = repeats.GetValueOrDefault(instruction, 1); + if (count == 0 || iteration < count) { repeats[instruction] = iteration + 1; instruction = 0; } + else { repeats.Remove(instruction); instruction++; } + continue; + } + if (!entered) { start = colors.ToArray(); entered = true; } + var consumed = Math.Min(milliseconds, step.Duration - elapsed); + elapsed += consumed; + milliseconds -= consumed; + if (step.Roll != 0) + { + var offset = Animation.Ease(step.Easing, elapsed / step.Duration) * colors.Length * step.Roll; + for (var i = 0; i < colors.Length; i++) + { + var source = ((i - offset) % colors.Length + colors.Length) % colors.Length; + var left = (int)Math.Floor(source); + colors[i] = Rgb.Blend(start[left], start[(left + 1) % colors.Length], source - left); + } + } + else foreach (var change in step.Transitions) + { + if (elapsed < change.Delay) { colors[change.Index] = start[change.Index]; continue; } + var fraction = change.Duration == 0 ? 1 : Math.Clamp((elapsed - change.Delay) / change.Duration, 0, 1); + colors[change.Index] = Rgb.Blend(start[change.Index], change.Color, Animation.Ease(change.Easing, fraction)); + } + if (elapsed < step.Duration) return; + instruction++; elapsed = 0; entered = false; + if (milliseconds <= 0) return; + } + } +} diff --git a/src/SidePulse.Core/AnimationLibrary.cs b/src/SidePulse.Core/AnimationLibrary.cs new file mode 100644 index 0000000..69ebbba --- /dev/null +++ b/src/SidePulse.Core/AnimationLibrary.cs @@ -0,0 +1,116 @@ +using System.Text.Json; +using System.Text.RegularExpressions; + +namespace SidePulse.Core; + +public sealed record PatternInfo(string Name, string Source, IReadOnlyList Models); +public sealed record AnimationProfile(Dictionary States, int Brightness = 100); + +public sealed class AnimationLibrary(string directory) +{ + private static readonly System.Reflection.Assembly Assembly = typeof(AnimationLibrary).Assembly; + private const string Prefix = "SidePulse.Core.Animations."; + public string DirectoryPath => Path.GetFullPath(directory); + public static AnimationLibrary Default => new(Path.Combine(Path.GetDirectoryName(LinkStore.DefaultPath)!, "animations")); + public static string Name(string name) + { + if (!Regex.IsMatch(name, "^[a-z0-9][a-z0-9_-]{0,39}$", RegexOptions.CultureInvariant)) throw new ArgumentException("Names must contain 1..40 lowercase letters, digits, underscores or hyphens."); + return name; + } + private string FilePath(string name, DeviceModel model) => Path.Combine(DirectoryPath, Name(name) + "." + model.ToString().ToLowerInvariant() + ".LED"); + public IReadOnlyList List() + { + var names = new HashSet(StringComparer.Ordinal); + foreach (var resource in Assembly.GetManifestResourceNames().Where(n => n.StartsWith(Prefix, StringComparison.Ordinal))) + names.Add(Regex.Replace(resource[Prefix.Length..^4], "-[28]$", "")); + if (Directory.Exists(DirectoryPath)) foreach (var file in Directory.EnumerateFiles(DirectoryPath, "*.LED")) + { + var match = Regex.Match(Path.GetFileName(file), @"^([a-z0-9][a-z0-9_-]{0,39})\.(dot|pro)\.LED$"); + if (match.Success) names.Add(match.Groups[1].Value); + } + return names.Order(StringComparer.Ordinal).Select(n => new PatternInfo(n, IsBuiltIn(n) ? "upstream" : "custom", Enum.GetValues().Where(m => Exists(n, m)).ToArray())).ToArray(); + } + private static bool IsBuiltIn(string name) => Assembly.GetManifestResourceNames().Any(n => n == Prefix + name + ".LED" || n == Prefix + name + "-2.LED" || n == Prefix + name + "-8.LED"); + public bool Exists(string name, DeviceModel model) => File.Exists(FilePath(name, model)) || Resource(name, model) is not null; + private static string? Resource(string name, DeviceModel model) + { + Name(name); + var resources = Assembly.GetManifestResourceNames(); + var variant = Prefix + name + $"-{(int)model}.LED"; + return resources.Contains(variant) ? variant : resources.Contains(Prefix + name + ".LED") ? Prefix + name + ".LED" : null; + } + public LedProgram Get(string name, DeviceModel model) + { + Name(name); + if (File.Exists(FilePath(name, model))) return new(File.ReadAllText(FilePath(name, model))); + var resource = Resource(name, model) ?? throw new ArgumentException($"Pattern '{name}' has no {model} variant. Import or create one for this model."); + using var reader = new StreamReader(Assembly.GetManifestResourceStream(resource)!); + return new(reader.ReadToEnd()); + } + public string Save(string name, DeviceModel model, LedProgram program, bool overwrite = false) + { + Name(name); + if (IsBuiltIn(name)) throw new ArgumentException("Choose a new name; built-in patterns cannot be replaced."); + Animation.Parse(program, model); + Directory.CreateDirectory(DirectoryPath); + var path = FilePath(name, model); + WriteFile(path, program.Text + "\n", overwrite); + return path; + } + public string SaveProfile(string name, AnimationProfile profile, bool overwrite = false) + { + Name(name); + if (profile.Brightness is < 0 or > 100 || profile.States.Count == 0 || profile.States.Any(s => !Enum.IsDefined(s.Key))) throw new ArgumentException("Invalid profile."); + foreach (var pattern in profile.States.Values) Name(pattern); + Directory.CreateDirectory(DirectoryPath); + var path = Path.Combine(DirectoryPath, name + ".profile.json"); + WriteFile(path, JsonSerializer.Serialize(profile, new JsonSerializerOptions { WriteIndented = true }) + "\n", overwrite); + return path; + } + public AnimationProfile LoadProfile(string name) + { + var path = Path.Combine(DirectoryPath, Name(name) + ".profile.json"); + var profile = JsonSerializer.Deserialize(File.ReadAllText(path)) ?? throw new ArgumentException("Invalid animation profile."); + if (profile.States is null || profile.Brightness is < 0 or > 100 || profile.States.Any(s => !Enum.IsDefined(s.Key))) throw new ArgumentException("Invalid animation profile."); + foreach (var pattern in profile.States.Values) Name(pattern); + return profile; + } + public static void WriteFile(string path, string text, bool overwrite) + { + // CreateNew prevents accidental clobbering. Replacement uses a sibling atomic move. + var full = Path.GetFullPath(path); + var temp = full + "." + Guid.NewGuid().ToString("N") + ".tmp"; + try { File.WriteAllText(temp, text); File.Move(temp, full, overwrite); } + finally { File.Delete(temp); } + } + public static DeviceModel DetectModel(string? path) + { + var candidate = path ?? DeviceTransport.Resolve(null); + var device = DeviceTransport.Discover().FirstOrDefault(d => d.Path.Equals(candidate, StringComparison.OrdinalIgnoreCase) || Path.GetDirectoryName(d.Path)!.Equals(candidate.TrimEnd(Path.DirectorySeparatorChar), StringComparison.OrdinalIgnoreCase)); + var description = candidate + " " + device?.Label; + if (description.Contains("SidePulseDot", StringComparison.OrdinalIgnoreCase)) return DeviceModel.Dot; + if (description.Contains("SidePulsePro", StringComparison.OrdinalIgnoreCase)) return DeviceModel.Pro; + throw new ArgumentException("Cannot identify the LED layout. Specify --model dot or --model pro."); + } + public static IReadOnlyDictionary ResolveProfile(string? name, DeviceModel? model, string? device) + { + if (name is null) return Enum.GetValues().ToDictionary(s => s, LedProgram.ForState); + var profile = Default.LoadProfile(name); + var layout = model ?? DetectModel(device); + return Enum.GetValues().ToDictionary(s => s, s => + { + var program = WithBrightness(profile.States.TryGetValue(s, out var pattern) ? Default.Get(pattern, layout) : LedProgram.ForState(s), profile.Brightness); + Animation.Parse(program, layout); + return program; + }); + } + public static LedProgram WithBrightness(LedProgram program, int? percent) + { + if (percent is null) return program; + if (percent is < 0 or > 100) throw new ArgumentException("Brightness must be 0..100 percent."); + var multiplier = percent.Value / 100d; + var lines = program.Text.Split('\n').Select(line => Regex.Replace(line, @"^\s*brightness\s+(\d+)\s*$", m => "brightness " + (int)Math.Round(int.Parse(m.Groups[1].Value) * multiplier))).ToList(); + lines.Insert(0, "brightness " + (int)Math.Round(255 * multiplier)); + return new(string.Join('\n', lines)); + } +} diff --git a/src/SidePulse.Core/Animations/amber-pulse.LED b/src/SidePulse.Core/Animations/amber-pulse.LED new file mode 100644 index 0000000..a299d74 --- /dev/null +++ b/src/SidePulse.Core/Animations/amber-pulse.LED @@ -0,0 +1,3 @@ +off +#FF3A00 1.6s pulse +repeat diff --git a/src/SidePulse.Core/Animations/cyan-complete.LED b/src/SidePulse.Core/Animations/cyan-complete.LED new file mode 100644 index 0000000..b45cffb --- /dev/null +++ b/src/SidePulse.Core/Animations/cyan-complete.LED @@ -0,0 +1 @@ +#00E5FF 320ms cosine diff --git a/src/SidePulse.Core/Animations/cyan-roll-2.LED b/src/SidePulse.Core/Animations/cyan-roll-2.LED new file mode 100644 index 0000000..8ae9916 --- /dev/null +++ b/src/SidePulse.Core/Animations/cyan-roll-2.LED @@ -0,0 +1,3 @@ +off 320ms cosine +0:#00E5FF 760ms pulse 0ms; 1:#00E5FF 760ms pulse 260ms +repeat diff --git a/src/SidePulse.Core/Animations/cyan-roll-8.LED b/src/SidePulse.Core/Animations/cyan-roll-8.LED new file mode 100644 index 0000000..c544c9f --- /dev/null +++ b/src/SidePulse.Core/Animations/cyan-roll-8.LED @@ -0,0 +1,3 @@ +off 320ms cosine +0:#00E5FF 760ms pulse 0ms; 1:#00E5FF 760ms pulse 95ms; 2:#00E5FF 760ms pulse 190ms; 3:#00E5FF 760ms pulse 285ms; 4:#00E5FF 760ms pulse 380ms; 5:#00E5FF 760ms pulse 475ms; 6:#00E5FF 760ms pulse 570ms; 7:#00E5FF 760ms pulse 665ms +repeat diff --git a/src/SidePulse.Core/Animations/ember-attention.LED b/src/SidePulse.Core/Animations/ember-attention.LED new file mode 100644 index 0000000..2e51861 --- /dev/null +++ b/src/SidePulse.Core/Animations/ember-attention.LED @@ -0,0 +1,3 @@ +off +#F23819 1.6s pulse +repeat diff --git a/src/SidePulse.Core/Animations/ember-tide-2.LED b/src/SidePulse.Core/Animations/ember-tide-2.LED new file mode 100644 index 0000000..e585978 --- /dev/null +++ b/src/SidePulse.Core/Animations/ember-tide-2.LED @@ -0,0 +1,3 @@ +off 320ms cosine +0:#F23819 760ms pulse 0ms; 1:#F23819 760ms pulse 260ms +repeat diff --git a/src/SidePulse.Core/Animations/ember-tide-8.LED b/src/SidePulse.Core/Animations/ember-tide-8.LED new file mode 100644 index 0000000..b4659d9 --- /dev/null +++ b/src/SidePulse.Core/Animations/ember-tide-8.LED @@ -0,0 +1,3 @@ +off 320ms cosine +0:#F23819 760ms pulse 0ms; 1:#F23819 760ms pulse 95ms; 2:#F23819 760ms pulse 190ms; 3:#F23819 760ms pulse 285ms; 4:#F23819 760ms pulse 380ms; 5:#F23819 760ms pulse 475ms; 6:#F23819 760ms pulse 570ms; 7:#F23819 760ms pulse 665ms +repeat diff --git a/src/SidePulse.Core/Animations/idle-pulse-2.LED b/src/SidePulse.Core/Animations/idle-pulse-2.LED new file mode 100644 index 0000000..6f84fac --- /dev/null +++ b/src/SidePulse.Core/Animations/idle-pulse-2.LED @@ -0,0 +1,3 @@ +off 2s +0:#006060 1:#006060 2s ease +repeat diff --git a/src/SidePulse.Core/Animations/idle-pulse-8.LED b/src/SidePulse.Core/Animations/idle-pulse-8.LED new file mode 100644 index 0000000..3dd0ecb --- /dev/null +++ b/src/SidePulse.Core/Animations/idle-pulse-8.LED @@ -0,0 +1,3 @@ +off 2s +2:#006060 3:#00E5FF 4:#00E5FF 5:#006060 2s ease +repeat diff --git a/src/SidePulse.Core/Animations/kitt-2.LED b/src/SidePulse.Core/Animations/kitt-2.LED new file mode 100644 index 0000000..ff8e62b --- /dev/null +++ b/src/SidePulse.Core/Animations/kitt-2.LED @@ -0,0 +1,4 @@ +off 80ms cosine +0:#00E5FF 320ms pulse 0ms; 1:#00E5FF 320ms pulse 240ms +0:#00E5FF 320ms pulse 0ms +repeat diff --git a/src/SidePulse.Core/Animations/kitt-8.LED b/src/SidePulse.Core/Animations/kitt-8.LED new file mode 100644 index 0000000..da44d5e --- /dev/null +++ b/src/SidePulse.Core/Animations/kitt-8.LED @@ -0,0 +1,4 @@ +off 80ms cosine +0:#00E5FF 320ms pulse 0ms; 1:#00E5FF 320ms pulse 85ms; 2:#00E5FF 320ms pulse 170ms; 3:#00E5FF 320ms pulse 255ms; 4:#00E5FF 320ms pulse 340ms; 5:#00E5FF 320ms pulse 425ms; 6:#00E5FF 320ms pulse 510ms; 7:#00E5FF 320ms pulse 595ms +6:#00E5FF 320ms pulse 0ms; 5:#00E5FF 320ms pulse 85ms; 4:#00E5FF 320ms pulse 170ms; 3:#00E5FF 320ms pulse 255ms; 2:#00E5FF 320ms pulse 340ms; 1:#00E5FF 320ms pulse 425ms; 0:#00E5FF 320ms pulse 510ms +repeat diff --git a/src/SidePulse.Core/Animations/kitt-red-2.LED b/src/SidePulse.Core/Animations/kitt-red-2.LED new file mode 100644 index 0000000..ff88e10 --- /dev/null +++ b/src/SidePulse.Core/Animations/kitt-red-2.LED @@ -0,0 +1,4 @@ +off 80ms cosine +0:#FF1800 320ms pulse 0ms; 1:#FF1800 320ms pulse 240ms +0:#FF1800 320ms pulse 0ms +repeat diff --git a/src/SidePulse.Core/Animations/kitt-red-8.LED b/src/SidePulse.Core/Animations/kitt-red-8.LED new file mode 100644 index 0000000..6fea483 --- /dev/null +++ b/src/SidePulse.Core/Animations/kitt-red-8.LED @@ -0,0 +1,4 @@ +off 80ms cosine +0:#FF1800 320ms pulse 0ms; 1:#FF1800 320ms pulse 85ms; 2:#FF1800 320ms pulse 170ms; 3:#FF1800 320ms pulse 255ms; 4:#FF1800 320ms pulse 340ms; 5:#FF1800 320ms pulse 425ms; 6:#FF1800 320ms pulse 510ms; 7:#FF1800 320ms pulse 595ms +6:#FF1800 320ms pulse 0ms; 5:#FF1800 320ms pulse 85ms; 4:#FF1800 320ms pulse 170ms; 3:#FF1800 320ms pulse 255ms; 2:#FF1800 320ms pulse 340ms; 1:#FF1800 320ms pulse 425ms; 0:#FF1800 320ms pulse 510ms +repeat diff --git a/src/SidePulse.Core/Animations/night-rider-2.LED b/src/SidePulse.Core/Animations/night-rider-2.LED new file mode 100644 index 0000000..fb06d89 --- /dev/null +++ b/src/SidePulse.Core/Animations/night-rider-2.LED @@ -0,0 +1,3 @@ +off +0:#FF1200 360ms pulse;1:#FF1200 360ms pulse 90ms +repeat diff --git a/src/SidePulse.Core/Animations/night-rider-8.LED b/src/SidePulse.Core/Animations/night-rider-8.LED new file mode 100644 index 0000000..a75f6d6 --- /dev/null +++ b/src/SidePulse.Core/Animations/night-rider-8.LED @@ -0,0 +1,4 @@ +off +0:#FF1200 360ms pulse;1:#FF1200 360ms pulse 90ms;2:#FF1200 360ms pulse 180ms;3:#FF1200 360ms pulse 270ms;4:#FF1200 360ms pulse 360ms;5:#FF1200 360ms pulse 450ms;6:#FF1200 360ms pulse 540ms;7:#FF1200 360ms pulse 630ms +6:#FF1200 360ms pulse;5:#FF1200 360ms pulse 90ms;4:#FF1200 360ms pulse 180ms;3:#FF1200 360ms pulse 270ms;2:#FF1200 360ms pulse 360ms;1:#FF1200 360ms pulse 450ms +repeat diff --git a/src/SidePulse.Core/Animations/off.LED b/src/SidePulse.Core/Animations/off.LED new file mode 100644 index 0000000..19c15db --- /dev/null +++ b/src/SidePulse.Core/Animations/off.LED @@ -0,0 +1 @@ +off 1s diff --git a/src/SidePulse.Core/Animations/purple-attention.LED b/src/SidePulse.Core/Animations/purple-attention.LED new file mode 100644 index 0000000..8f615ec --- /dev/null +++ b/src/SidePulse.Core/Animations/purple-attention.LED @@ -0,0 +1,3 @@ +off +#FF00FF 1.6s pulse +repeat diff --git a/src/SidePulse.Core/Animations/purple-tide-2.LED b/src/SidePulse.Core/Animations/purple-tide-2.LED new file mode 100644 index 0000000..4844322 --- /dev/null +++ b/src/SidePulse.Core/Animations/purple-tide-2.LED @@ -0,0 +1,3 @@ +off 320ms cosine +0:#FF00FF 760ms pulse 0ms; 1:#FF00FF 760ms pulse 260ms +repeat diff --git a/src/SidePulse.Core/Animations/purple-tide-8.LED b/src/SidePulse.Core/Animations/purple-tide-8.LED new file mode 100644 index 0000000..a954480 --- /dev/null +++ b/src/SidePulse.Core/Animations/purple-tide-8.LED @@ -0,0 +1,3 @@ +off 320ms cosine +0:#FF00FF 760ms pulse 0ms; 1:#FF00FF 760ms pulse 95ms; 2:#FF00FF 760ms pulse 190ms; 3:#FF00FF 760ms pulse 285ms; 4:#FF00FF 760ms pulse 380ms; 5:#FF00FF 760ms pulse 475ms; 6:#FF00FF 760ms pulse 570ms; 7:#FF00FF 760ms pulse 665ms +repeat diff --git a/src/SidePulse.Core/Animations/solid-green.LED b/src/SidePulse.Core/Animations/solid-green.LED new file mode 100644 index 0000000..58ede71 --- /dev/null +++ b/src/SidePulse.Core/Animations/solid-green.LED @@ -0,0 +1 @@ +#00FF66 320ms cosine diff --git a/src/SidePulse.Core/SidePulse.Core.csproj b/src/SidePulse.Core/SidePulse.Core.csproj index 7d08442..9b44337 100644 --- a/src/SidePulse.Core/SidePulse.Core.csproj +++ b/src/SidePulse.Core/SidePulse.Core.csproj @@ -1,3 +1,6 @@ + + + diff --git a/tests/SidePulse.Tests/AnimationTests.cs b/tests/SidePulse.Tests/AnimationTests.cs new file mode 100644 index 0000000..e5fbebf --- /dev/null +++ b/tests/SidePulse.Tests/AnimationTests.cs @@ -0,0 +1,123 @@ +using SidePulse.Core; +using Xunit; + +namespace SidePulse.Tests; + +public sealed class AnimationTests +{ + [Fact] + public void ColorListsFillOrClearAndIndexedAssignmentsHold() + { + var player = Player("#ff0000\n1:#00ff00\n#0000ff #ffffff", DeviceModel.Pro); + player.Advance(17); + Assert.Equal("#ff0000", player.Frame[0].ToString()); + Assert.Equal("#00ff00", player.Frame[1].ToString()); + player.Advance(34); + Assert.Equal("#0000ff", player.Frame[0].ToString()); + Assert.Equal("#ffffff", player.Frame[1].ToString()); + Assert.Equal("#000000", player.Frame[2].ToString()); + } + [Fact] + public void PulseReturnsToStartWhileDelayedLedWaits() + { + var player = Player("0:#ff0000 1s pulse; 1:#00ff00 1s linear 1s"); + player.Advance(500); + Assert.Equal("#ff0000", player.Frame[0].ToString()); + Assert.Equal("#000000", player.Frame[1].ToString()); + player.Advance(1000); + Assert.Equal("#000000", player.Frame[0].ToString()); + Assert.Equal("#008000", player.Frame[1].ToString()); + player.Advance(500); + Assert.True(player.Complete); + Assert.Equal("#00ff00", player.Frame[1].ToString()); + } + [Fact] + public void LastAssignmentWinsAndIgnoredIndexesStillValidate() + { + var player = Player("0:#ff0000 1s; 0:#0000ff 1s; 7:#00ff00 1s"); + player.Advance(1000); + Assert.Equal("#0000ff", player.Frame[0].ToString()); + Assert.Equal("#000000", player.Frame[1].ToString()); + Assert.Throws(() => Animation.Parse(new("7:#invalid"), DeviceModel.Dot)); + } + [Fact] + public void FiniteRepeatContinuesAndInfiniteRepeatDoesNotComplete() + { + var finite = Player("#ff0000 100ms none\n#00ff00 100ms none\nrepeat 2\noff"); + finite.Advance(350); + Assert.Equal("#00ff00", finite.Frame[0].ToString()); + finite.Advance(100); + Assert.True(finite.Complete); + Assert.Equal("#000000", finite.Frame[0].ToString()); + var infinite = Player("#ff0000 100ms none\nrepeat"); + infinite.Advance(10000); + Assert.False(infinite.Complete); + } + [Fact] + public void RollMovesOneLedAtHalfDotCycleAndReturns() + { + var player = Player("#ff0000 #0000ff\nroll 1s\nrepeat"); + player.Advance(1000d / 60 + 500); + Assert.Equal("#0000ff", player.Frame[0].ToString()); + Assert.Equal("#ff0000", player.Frame[1].ToString()); + player.Advance(500); + Assert.Equal("#ff0000", player.Frame[0].ToString()); + } + [Fact] + public void BrightnessMultipliesWithoutChangingStoredColors() + { + var program = AnimationLibrary.WithBrightness(new("brightness 128\n#ffffff\nbrightness 255\n#ffffff"), 50); + var player = new AnimationPlayer(Animation.Parse(program, DeviceModel.Dot)); + player.Advance(1); + Assert.Equal("#404040", player.Frame[0].ToString()); + player.Advance(50); + Assert.Equal("#808080", player.Frame[0].ToString()); + } + [Theory] + [InlineData("#f00")] + [InlineData("#ffffff 1.5ms")] + [InlineData("#ffffff 66s")] + [InlineData("#ffffff 1s banana")] + [InlineData("brightness 256\noff")] + [InlineData("repeat")] + [InlineData("off\nrepeat 0")] + [InlineData("off\nrepeat -1")] + [InlineData("off; ")] + [InlineData("roll")] + [InlineData("#ff0000 1s linear 1s junk")] + public void InvalidGrammarIsRejected(string text) => Assert.Throws(() => Animation.Parse(new(text), DeviceModel.Dot)); + [Fact] + public void EveryBundledVariantParsesAndPlays() + { + var library = new AnimationLibrary(Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString())); + Assert.True(library.List().Count >= 10); + foreach (var pattern in library.List()) foreach (var model in pattern.Models) + { + var player = new AnimationPlayer(Animation.Parse(library.Get(pattern.Name, model), model)); + player.Advance(5000); + Assert.Equal((int)model, player.Frame.Count); + } + } + [Fact] + public void LibrarySeparatesModelsPreservesExistingFilesAndRejectsTraversal() + { + var directory = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); + var library = new AnimationLibrary(directory); + try + { + library.Save("personal", DeviceModel.Dot, new("#ff0000")); + Assert.False(library.Exists("personal", DeviceModel.Pro)); + Assert.Throws(() => library.Save("personal", DeviceModel.Dot, new("off"))); + Assert.Throws(() => library.Save("off", DeviceModel.Dot, new("off"))); + Assert.Throws(() => library.Get("../escape", DeviceModel.Dot)); + library.Save("personal", DeviceModel.Pro, new("#00ff00")); + Assert.Equal(2, library.List().Single(p => p.Name == "personal").Models.Count); + library.SaveProfile("mine", new(new() { [AgentState.Working] = "personal" }, 40)); + var profile = library.LoadProfile("mine"); + Assert.Equal(40, profile.Brightness); + Assert.Equal("personal", profile.States[AgentState.Working]); + } + finally { if (Directory.Exists(directory)) Directory.Delete(directory, true); } + } + private static AnimationPlayer Player(string text, DeviceModel model = DeviceModel.Dot) => new(Animation.Parse(new(text), model)); +} diff --git a/tests/SidePulse.Tests/SidePulse.Tests.csproj b/tests/SidePulse.Tests/SidePulse.Tests.csproj index a3e4f1a..338ebc7 100644 --- a/tests/SidePulse.Tests/SidePulse.Tests.csproj +++ b/tests/SidePulse.Tests/SidePulse.Tests.csproj @@ -2,6 +2,7 @@ truefalse + all diff --git a/tests/SidePulse.Tests/TerminalTests.cs b/tests/SidePulse.Tests/TerminalTests.cs new file mode 100644 index 0000000..8c1f77b --- /dev/null +++ b/tests/SidePulse.Tests/TerminalTests.cs @@ -0,0 +1,31 @@ +using SidePulse.Cli; +using Xunit; + +namespace SidePulse.Tests; + +public sealed class TerminalTests +{ + [Fact] + public void CommandExportsQuoteLiteralMetacharactersAndRejectMultilineValues() + { + const string value = "Ned's $HOME `whoami` $(id) & file.LED"; + Assert.Equal("'Ned''s $HOME `whoami` $(id) & file.LED'", TerminalMode.Quote(value, "powershell")); + Assert.Equal("'Ned'\"'\"'s $HOME `whoami` $(id) & file.LED'", TerminalMode.Quote(value, "bash")); + Assert.Equal("\"E:\\\\\"", TerminalMode.Quote("E:\\", "cmd")); + Assert.Throws(() => TerminalMode.Quote("%PATH%", "cmd")); + Assert.Throws(() => TerminalMode.Quote("!PATH!", "cmd")); + Assert.Throws(() => TerminalMode.Quote("first\nsecond", "bash")); + Assert.StartsWith("sidepulse-net ", TerminalMode.Command(["animations", "preview", value], "bash")); + } + [Fact] + public void CreditsAndOfflineLicensesAreEmbeddedForEveryRuntimePackage() + { + var dependencies = ProjectInfo.Dependencies; + Assert.Equal(7, dependencies.Count); + Assert.All(dependencies, d => { Assert.False(string.IsNullOrEmpty(d.Version)); Assert.Equal("MIT", d.License); Assert.False(string.IsNullOrEmpty(d.Authors)); }); + Assert.Contains(dependencies, d => d.Name == "Spectre.Console.Ansi"); + Assert.Contains(dependencies, d => d.Name == "System.Drawing.Common"); + Assert.True(ProjectInfo.LicenseResources.Count >= 10); + Assert.All(ProjectInfo.LicenseResources, r => Assert.False(string.IsNullOrWhiteSpace(ProjectInfo.LicenseText(r)))); + } +} diff --git a/tests/SidePulse.Tests/packages.lock.json b/tests/SidePulse.Tests/packages.lock.json index e5c89fe..2a1b783 100644 --- a/tests/SidePulse.Tests/packages.lock.json +++ b/tests/SidePulse.Tests/packages.lock.json @@ -48,11 +48,29 @@ "Newtonsoft.Json": "13.0.3" } }, + "Microsoft.Win32.SystemEvents": { + "type": "Transitive", + "resolved": "6.0.0", + "contentHash": "hqTM5628jSsQiv+HGpiq3WKBl2c8v1KZfby2J6Pr7pEPlK9waPdgEO6b8A/+/xn/yZ9ulv8HuqK71ONy2tg67A==" + }, "Newtonsoft.Json": { "type": "Transitive", "resolved": "13.0.3", "contentHash": "HrC5BXdl00IP9zeV+0Z848QWPAoCr9P3bDEZguI+gkLcBKAOxix/tLEAAHC+UvDNPv4a2d18lOReHMOagPa+zQ==" }, + "Spectre.Console.Ansi": { + "type": "Transitive", + "resolved": "0.57.2", + "contentHash": "Y1+u73shwP+JYHmrkdN6bSt2kaGBEAafhi2nrecczbXdFRey+k7J/WF9YPfcB0rqivv2S8fmif6FSBq9m/AFvw==" + }, + "System.Drawing.Common": { + "type": "Transitive", + "resolved": "6.0.0", + "contentHash": "NfuoKUiP2nUWwKZN6twGqXioIe1zVD0RIj2t976A+czLHr2nY454RwwXs6JU9Htc6mwqL6Dn/nEL3dpVf2jOhg==", + "dependencies": { + "Microsoft.Win32.SystemEvents": "6.0.0" + } + }, "xunit.abstractions": { "type": "Transitive", "resolved": "2.0.3", @@ -93,12 +111,48 @@ "xunit.extensibility.core": "[2.9.3]" } }, + "sidepulse-net": { + "type": "Project", + "dependencies": { + "QRCoder": "[1.8.1, )", + "SidePulse.Core": "[1.0.0, )", + "Spectre.Console": "[0.57.2, )", + "Spectre.Console.Cli": "[0.57.2, )" + } + }, "sidepulse.core": { "type": "Project", "dependencies": { "System.Security.Cryptography.ProtectedData": "[10.0.13, )" } }, + "QRCoder": { + "type": "CentralTransitive", + "requested": "[1.8.1, )", + "resolved": "1.8.1", + "contentHash": "aGfRFpU/IPexAtEOEXCNxC3fMCAqgn6kqALRvXt6LxVAW0VolSDGHiyrY+o2CJgTITOsMpsrsDi7svMJaJ9Vfg==", + "dependencies": { + "System.Drawing.Common": "6.0.0" + } + }, + "Spectre.Console": { + "type": "CentralTransitive", + "requested": "[0.57.2, )", + "resolved": "0.57.2", + "contentHash": "wzsB+P9i6F9G+cFOJxRotCiQWNSzZVAMxi8YMiHlGXXU1JLMXGp7zSSqBMmROZS2bzpK5jk+Saa7Evp8HwqhKg==", + "dependencies": { + "Spectre.Console.Ansi": "0.57.2" + } + }, + "Spectre.Console.Cli": { + "type": "CentralTransitive", + "requested": "[0.57.2, )", + "resolved": "0.57.2", + "contentHash": "EAiwpJXAAvhyyzH6hljVo7z19ahG7WM+zViKEHtUagyPymYfJrsainXDOHzUakBHj6VYEpuaqPAShgqvs1N9aQ==", + "dependencies": { + "Spectre.Console": "0.57.2" + } + }, "System.Security.Cryptography.ProtectedData": { "type": "CentralTransitive", "requested": "[10.0.13, )", diff --git a/third-party/dotnet-packages/microsoft.win32.systemevents/LICENSE.TXT b/third-party/dotnet-packages/microsoft.win32.systemevents/LICENSE.TXT new file mode 100644 index 0000000..984713a --- /dev/null +++ b/third-party/dotnet-packages/microsoft.win32.systemevents/LICENSE.TXT @@ -0,0 +1,23 @@ +The MIT License (MIT) + +Copyright (c) .NET Foundation and Contributors + +All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/third-party/dotnet-packages/microsoft.win32.systemevents/THIRD-PARTY-NOTICES.TXT b/third-party/dotnet-packages/microsoft.win32.systemevents/THIRD-PARTY-NOTICES.TXT new file mode 100644 index 0000000..89c59b2 --- /dev/null +++ b/third-party/dotnet-packages/microsoft.win32.systemevents/THIRD-PARTY-NOTICES.TXT @@ -0,0 +1,939 @@ +.NET Runtime uses third-party libraries or other resources that may be +distributed under licenses different than the .NET Runtime software. + +In the event that we accidentally failed to list a required notice, please +bring it to our attention. Post an issue or email us: + + dotnet@microsoft.com + +The attached notices are provided for information only. + +License notice for ASP.NET +------------------------------- + +Copyright (c) .NET Foundation. All rights reserved. +Licensed under the Apache License, Version 2.0. + +Available at +https://github.com/dotnet/aspnetcore/blob/main/LICENSE.txt + +License notice for Slicing-by-8 +------------------------------- + +http://sourceforge.net/projects/slicing-by-8/ + +Copyright (c) 2004-2006 Intel Corporation - All Rights Reserved + + +This software program is licensed subject to the BSD License, available at +http://www.opensource.org/licenses/bsd-license.html. + + +License notice for Unicode data +------------------------------- + +https://www.unicode.org/license.html + +Copyright © 1991-2020 Unicode, Inc. All rights reserved. +Distributed under the Terms of Use in https://www.unicode.org/copyright.html. + +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Unicode data files and any associated documentation +(the "Data Files") or Unicode software and any associated documentation +(the "Software") to deal in the Data Files or Software +without restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, and/or sell copies of +the Data Files or Software, and to permit persons to whom the Data Files +or Software are furnished to do so, provided that either +(a) this copyright and permission notice appear with all copies +of the Data Files or Software, or +(b) this copyright and permission notice appear in associated +Documentation. + +THE DATA FILES AND SOFTWARE ARE PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE +WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT OF THIRD PARTY RIGHTS. +IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS INCLUDED IN THIS +NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL +DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, +DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER +TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THE DATA FILES OR SOFTWARE. + +Except as contained in this notice, the name of a copyright holder +shall not be used in advertising or otherwise to promote the sale, +use or other dealings in these Data Files or Software without prior +written authorization of the copyright holder. + +License notice for Zlib +----------------------- + +https://github.com/madler/zlib +http://zlib.net/zlib_license.html + +/* zlib.h -- interface of the 'zlib' general purpose compression library + version 1.2.11, January 15th, 2017 + + Copyright (C) 1995-2017 Jean-loup Gailly and Mark Adler + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. + + Jean-loup Gailly Mark Adler + jloup@gzip.org madler@alumni.caltech.edu + +*/ + +License notice for Mono +------------------------------- + +http://www.mono-project.com/docs/about-mono/ + +Copyright (c) .NET Foundation Contributors + +MIT License + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the Software), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +License notice for International Organization for Standardization +----------------------------------------------------------------- + +Portions (C) International Organization for Standardization 1986: + Permission to copy in any form is granted for use with + conforming SGML systems and applications as defined in + ISO 8879, provided this notice is included in all copies. + +License notice for Intel +------------------------ + +"Copyright (c) 2004-2006 Intel Corporation - All Rights Reserved + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this +list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, +this list of conditions and the following disclaimer in the documentation +and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +License notice for Xamarin and Novell +------------------------------------- + +Copyright (c) 2015 Xamarin, Inc (http://www.xamarin.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + +Copyright (c) 2011 Novell, Inc (http://www.novell.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + +Third party notice for W3C +-------------------------- + +"W3C SOFTWARE AND DOCUMENT NOTICE AND LICENSE +Status: This license takes effect 13 May, 2015. +This work is being provided by the copyright holders under the following license. +License +By obtaining and/or copying this work, you (the licensee) agree that you have read, understood, and will comply with the following terms and conditions. +Permission to copy, modify, and distribute this work, with or without modification, for any purpose and without fee or royalty is hereby granted, provided that you include the following on ALL copies of the work or portions thereof, including modifications: +The full text of this NOTICE in a location viewable to users of the redistributed or derivative work. +Any pre-existing intellectual property disclaimers, notices, or terms and conditions. If none exist, the W3C Software and Document Short Notice should be included. +Notice of any changes or modifications, through a copyright statement on the new code or document such as "This software or document includes material copied from or derived from [title and URI of the W3C document]. Copyright © [YEAR] W3C® (MIT, ERCIM, Keio, Beihang)." +Disclaimers +THIS WORK IS PROVIDED "AS IS," AND COPYRIGHT HOLDERS MAKE NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF THE SOFTWARE OR DOCUMENT WILL NOT INFRINGE ANY THIRD PARTY PATENTS, COPYRIGHTS, TRADEMARKS OR OTHER RIGHTS. +COPYRIGHT HOLDERS WILL NOT BE LIABLE FOR ANY DIRECT, INDIRECT, SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF ANY USE OF THE SOFTWARE OR DOCUMENT. +The name and trademarks of copyright holders may NOT be used in advertising or publicity pertaining to the work without specific, written prior permission. Title to copyright in this work will at all times remain with copyright holders." + +License notice for Bit Twiddling Hacks +-------------------------------------- + +Bit Twiddling Hacks + +By Sean Eron Anderson +seander@cs.stanford.edu + +Individually, the code snippets here are in the public domain (unless otherwise +noted) — feel free to use them however you please. The aggregate collection and +descriptions are © 1997-2005 Sean Eron Anderson. The code and descriptions are +distributed in the hope that they will be useful, but WITHOUT ANY WARRANTY and +without even the implied warranty of merchantability or fitness for a particular +purpose. + +License notice for Brotli +-------------------------------------- + +Copyright (c) 2009, 2010, 2013-2016 by the Brotli Authors. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + +compress_fragment.c: +Copyright (c) 2011, Google Inc. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above +copyright notice, this list of conditions and the following disclaimer +in the documentation and/or other materials provided with the +distribution. + * Neither the name of Google Inc. nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +""AS IS"" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +decode_fuzzer.c: +Copyright (c) 2015 The Chromium Authors. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above +copyright notice, this list of conditions and the following disclaimer +in the documentation and/or other materials provided with the +distribution. + * Neither the name of Google Inc. nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +""AS IS"" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." + +License notice for Json.NET +------------------------------- + +https://github.com/JamesNK/Newtonsoft.Json/blob/master/LICENSE.md + +The MIT License (MIT) + +Copyright (c) 2007 James Newton-King + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +License notice for vectorized base64 encoding / decoding +-------------------------------------------------------- + +Copyright (c) 2005-2007, Nick Galbreath +Copyright (c) 2013-2017, Alfred Klomp +Copyright (c) 2015-2017, Wojciech Mula +Copyright (c) 2016-2017, Matthieu Darbois +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + +- Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + +- Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS +IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED +TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A +PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED +TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +License notice for RFC 3492 +--------------------------- + +The punycode implementation is based on the sample code in RFC 3492 + +Copyright (C) The Internet Society (2003). All Rights Reserved. + +This document and translations of it may be copied and furnished to +others, and derivative works that comment on or otherwise explain it +or assist in its implementation may be prepared, copied, published +and distributed, in whole or in part, without restriction of any +kind, provided that the above copyright notice and this paragraph are +included on all such copies and derivative works. However, this +document itself may not be modified in any way, such as by removing +the copyright notice or references to the Internet Society or other +Internet organizations, except as needed for the purpose of +developing Internet standards in which case the procedures for +copyrights defined in the Internet Standards process must be +followed, or as required to translate it into languages other than +English. + +The limited permissions granted above are perpetual and will not be +revoked by the Internet Society or its successors or assigns. + +This document and the information contained herein is provided on an +"AS IS" basis and THE INTERNET SOCIETY AND THE INTERNET ENGINEERING +TASK FORCE DISCLAIMS ALL WARRANTIES, EXPRESS OR IMPLIED, INCLUDING +BUT NOT LIMITED TO ANY WARRANTY THAT THE USE OF THE INFORMATION +HEREIN WILL NOT INFRINGE ANY RIGHTS OR ANY IMPLIED WARRANTIES OF +MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. + +License notice for Algorithm from Internet Draft document "UUIDs and GUIDs" +--------------------------------------------------------------------------- + +Copyright (c) 1990- 1993, 1996 Open Software Foundation, Inc. +Copyright (c) 1989 by Hewlett-Packard Company, Palo Alto, Ca. & +Digital Equipment Corporation, Maynard, Mass. +To anyone who acknowledges that this file is provided "AS IS" +without any express or implied warranty: permission to use, copy, +modify, and distribute this file for any purpose is hereby +granted without fee, provided that the above copyright notices and +this notice appears in all source code copies, and that none of +the names of Open Software Foundation, Inc., Hewlett-Packard +Company, or Digital Equipment Corporation be used in advertising +or publicity pertaining to distribution of the software without +specific, written prior permission. Neither Open Software +Foundation, Inc., Hewlett-Packard Company, Microsoft, nor Digital Equipment +Corporation makes any representations about the suitability of +this software for any purpose. + +Copyright(C) The Internet Society 1997. All Rights Reserved. + +This document and translations of it may be copied and furnished to others, +and derivative works that comment on or otherwise explain it or assist in +its implementation may be prepared, copied, published and distributed, in +whole or in part, without restriction of any kind, provided that the above +copyright notice and this paragraph are included on all such copies and +derivative works.However, this document itself may not be modified in any +way, such as by removing the copyright notice or references to the Internet +Society or other Internet organizations, except as needed for the purpose of +developing Internet standards in which case the procedures for copyrights +defined in the Internet Standards process must be followed, or as required +to translate it into languages other than English. + +The limited permissions granted above are perpetual and will not be revoked +by the Internet Society or its successors or assigns. + +This document and the information contained herein is provided on an "AS IS" +basis and THE INTERNET SOCIETY AND THE INTERNET ENGINEERING TASK FORCE +DISCLAIMS ALL WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO +ANY WARRANTY THAT THE USE OF THE INFORMATION HEREIN WILL NOT INFRINGE ANY +RIGHTS OR ANY IMPLIED WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A +PARTICULAR PURPOSE. + +License notice for Algorithm from RFC 4122 - +A Universally Unique IDentifier (UUID) URN Namespace +---------------------------------------------------- + +Copyright (c) 1990- 1993, 1996 Open Software Foundation, Inc. +Copyright (c) 1989 by Hewlett-Packard Company, Palo Alto, Ca. & +Digital Equipment Corporation, Maynard, Mass. +Copyright (c) 1998 Microsoft. +To anyone who acknowledges that this file is provided "AS IS" +without any express or implied warranty: permission to use, copy, +modify, and distribute this file for any purpose is hereby +granted without fee, provided that the above copyright notices and +this notice appears in all source code copies, and that none of +the names of Open Software Foundation, Inc., Hewlett-Packard +Company, Microsoft, or Digital Equipment Corporation be used in +advertising or publicity pertaining to distribution of the software +without specific, written prior permission. Neither Open Software +Foundation, Inc., Hewlett-Packard Company, Microsoft, nor Digital +Equipment Corporation makes any representations about the +suitability of this software for any purpose." + +License notice for The LLVM Compiler Infrastructure +--------------------------------------------------- + +Developed by: + + LLVM Team + + University of Illinois at Urbana-Champaign + + http://llvm.org + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal with +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: + + * Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimers. + + * Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimers in the + documentation and/or other materials provided with the distribution. + + * Neither the names of the LLVM Team, University of Illinois at + Urbana-Champaign, nor the names of its contributors may be used to + endorse or promote products derived from this Software without specific + prior written permission. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS WITH THE +SOFTWARE. + +License notice for Bob Jenkins +------------------------------ + +By Bob Jenkins, 1996. bob_jenkins@burtleburtle.net. You may use this +code any way you wish, private, educational, or commercial. It's free. + +License notice for Greg Parker +------------------------------ + +Greg Parker gparker@cs.stanford.edu December 2000 +This code is in the public domain and may be copied or modified without +permission. + +License notice for libunwind based code +---------------------------------------- + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +License notice for Printing Floating-Point Numbers (Dragon4) +------------------------------------------------------------ + +/****************************************************************************** + Copyright (c) 2014 Ryan Juckett + http://www.ryanjuckett.com/ + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + + 3. This notice may not be removed or altered from any source + distribution. +******************************************************************************/ + +License notice for Printing Floating-point Numbers (Grisu3) +----------------------------------------------------------- + +Copyright 2012 the V8 project authors. All rights reserved. +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials provided + with the distribution. + * Neither the name of Google Inc. nor the names of its + contributors may be used to endorse or promote products derived + from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +License notice for xxHash +------------------------- + +xxHash Library +Copyright (c) 2012-2014, Yann Collet +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +* Redistributions in binary form must reproduce the above copyright notice, this + list of conditions and the following disclaimer in the documentation and/or + other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +License notice for Berkeley SoftFloat Release 3e +------------------------------------------------ + +https://github.com/ucb-bar/berkeley-softfloat-3 +https://github.com/ucb-bar/berkeley-softfloat-3/blob/master/COPYING.txt + +License for Berkeley SoftFloat Release 3e + +John R. Hauser +2018 January 20 + +The following applies to the whole of SoftFloat Release 3e as well as to +each source file individually. + +Copyright 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018 The Regents of the +University of California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions, and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF +THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +License notice for xoshiro RNGs +-------------------------------- + +Written in 2018 by David Blackman and Sebastiano Vigna (vigna@acm.org) + +To the extent possible under law, the author has dedicated all copyright +and related and neighboring rights to this software to the public domain +worldwide. This software is distributed without any warranty. + +See . + +License for fastmod (https://github.com/lemire/fastmod) and ibm-fpgen (https://github.com/nigeltao/parse-number-fxx-test-data) +-------------------------------------- + + Copyright 2018 Daniel Lemire + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +License notice for The C++ REST SDK +----------------------------------- + +C++ REST SDK + +The MIT License (MIT) + +Copyright (c) Microsoft Corporation + +All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +License notice for MessagePack-CSharp +------------------------------------- + +MessagePack for C# + +MIT License + +Copyright (c) 2017 Yoshifumi Kawai + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +License notice for lz4net +------------------------------------- + +lz4net + +Copyright (c) 2013-2017, Milosz Krajewski + +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + +Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + +Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +License notice for Nerdbank.Streams +----------------------------------- + +The MIT License (MIT) + +Copyright (c) Andrew Arnott + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +License notice for RapidJSON +---------------------------- + +Tencent is pleased to support the open source community by making RapidJSON available. + +Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. + +Licensed under the MIT License (the "License"); you may not use this file except +in compliance with the License. You may obtain a copy of the License at + +http://opensource.org/licenses/MIT + +Unless required by applicable law or agreed to in writing, software distributed +under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR +CONDITIONS OF ANY KIND, either express or implied. See the License for the +specific language governing permissions and limitations under the License. + +License notice for DirectX Math Library +--------------------------------------- + +https://github.com/microsoft/DirectXMath/blob/master/LICENSE + + The MIT License (MIT) + +Copyright (c) 2011-2020 Microsoft Corp + +Permission is hereby granted, free of charge, to any person obtaining a copy of this +software and associated documentation files (the "Software"), to deal in the Software +without restriction, including without limitation the rights to use, copy, modify, +merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice shall be included in all copies +or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF +CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE +OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +License notice for ldap4net +--------------------------- + +The MIT License (MIT) + +Copyright (c) 2018 Alexander Chermyanin + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +License notice for vectorized sorting code +------------------------------------------ + +MIT License + +Copyright (c) 2020 Dan Shechter + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +License notice for musl +----------------------- + +musl as a whole is licensed under the following standard MIT license: + +Copyright © 2005-2020 Rich Felker, et al. + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + +License notice for "Faster Unsigned Division by Constants" +------------------------------ + +Reference implementations of computing and using the "magic number" approach to dividing +by constants, including codegen instructions. The unsigned division incorporates the +"round down" optimization per ridiculous_fish. + +This is free and unencumbered software. Any copyright is dedicated to the Public Domain. + + +License notice for mimalloc +----------------------------------- + +MIT License + +Copyright (c) 2019 Microsoft Corporation, Daan Leijen + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/third-party/dotnet-packages/system.drawing.common/LICENSE.TXT b/third-party/dotnet-packages/system.drawing.common/LICENSE.TXT new file mode 100644 index 0000000..984713a --- /dev/null +++ b/third-party/dotnet-packages/system.drawing.common/LICENSE.TXT @@ -0,0 +1,23 @@ +The MIT License (MIT) + +Copyright (c) .NET Foundation and Contributors + +All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/third-party/dotnet-packages/system.drawing.common/THIRD-PARTY-NOTICES.TXT b/third-party/dotnet-packages/system.drawing.common/THIRD-PARTY-NOTICES.TXT new file mode 100644 index 0000000..89c59b2 --- /dev/null +++ b/third-party/dotnet-packages/system.drawing.common/THIRD-PARTY-NOTICES.TXT @@ -0,0 +1,939 @@ +.NET Runtime uses third-party libraries or other resources that may be +distributed under licenses different than the .NET Runtime software. + +In the event that we accidentally failed to list a required notice, please +bring it to our attention. Post an issue or email us: + + dotnet@microsoft.com + +The attached notices are provided for information only. + +License notice for ASP.NET +------------------------------- + +Copyright (c) .NET Foundation. All rights reserved. +Licensed under the Apache License, Version 2.0. + +Available at +https://github.com/dotnet/aspnetcore/blob/main/LICENSE.txt + +License notice for Slicing-by-8 +------------------------------- + +http://sourceforge.net/projects/slicing-by-8/ + +Copyright (c) 2004-2006 Intel Corporation - All Rights Reserved + + +This software program is licensed subject to the BSD License, available at +http://www.opensource.org/licenses/bsd-license.html. + + +License notice for Unicode data +------------------------------- + +https://www.unicode.org/license.html + +Copyright © 1991-2020 Unicode, Inc. All rights reserved. +Distributed under the Terms of Use in https://www.unicode.org/copyright.html. + +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Unicode data files and any associated documentation +(the "Data Files") or Unicode software and any associated documentation +(the "Software") to deal in the Data Files or Software +without restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, and/or sell copies of +the Data Files or Software, and to permit persons to whom the Data Files +or Software are furnished to do so, provided that either +(a) this copyright and permission notice appear with all copies +of the Data Files or Software, or +(b) this copyright and permission notice appear in associated +Documentation. + +THE DATA FILES AND SOFTWARE ARE PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE +WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT OF THIRD PARTY RIGHTS. +IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS INCLUDED IN THIS +NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL +DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, +DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER +TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THE DATA FILES OR SOFTWARE. + +Except as contained in this notice, the name of a copyright holder +shall not be used in advertising or otherwise to promote the sale, +use or other dealings in these Data Files or Software without prior +written authorization of the copyright holder. + +License notice for Zlib +----------------------- + +https://github.com/madler/zlib +http://zlib.net/zlib_license.html + +/* zlib.h -- interface of the 'zlib' general purpose compression library + version 1.2.11, January 15th, 2017 + + Copyright (C) 1995-2017 Jean-loup Gailly and Mark Adler + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. + + Jean-loup Gailly Mark Adler + jloup@gzip.org madler@alumni.caltech.edu + +*/ + +License notice for Mono +------------------------------- + +http://www.mono-project.com/docs/about-mono/ + +Copyright (c) .NET Foundation Contributors + +MIT License + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the Software), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +License notice for International Organization for Standardization +----------------------------------------------------------------- + +Portions (C) International Organization for Standardization 1986: + Permission to copy in any form is granted for use with + conforming SGML systems and applications as defined in + ISO 8879, provided this notice is included in all copies. + +License notice for Intel +------------------------ + +"Copyright (c) 2004-2006 Intel Corporation - All Rights Reserved + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this +list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, +this list of conditions and the following disclaimer in the documentation +and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +License notice for Xamarin and Novell +------------------------------------- + +Copyright (c) 2015 Xamarin, Inc (http://www.xamarin.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + +Copyright (c) 2011 Novell, Inc (http://www.novell.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + +Third party notice for W3C +-------------------------- + +"W3C SOFTWARE AND DOCUMENT NOTICE AND LICENSE +Status: This license takes effect 13 May, 2015. +This work is being provided by the copyright holders under the following license. +License +By obtaining and/or copying this work, you (the licensee) agree that you have read, understood, and will comply with the following terms and conditions. +Permission to copy, modify, and distribute this work, with or without modification, for any purpose and without fee or royalty is hereby granted, provided that you include the following on ALL copies of the work or portions thereof, including modifications: +The full text of this NOTICE in a location viewable to users of the redistributed or derivative work. +Any pre-existing intellectual property disclaimers, notices, or terms and conditions. If none exist, the W3C Software and Document Short Notice should be included. +Notice of any changes or modifications, through a copyright statement on the new code or document such as "This software or document includes material copied from or derived from [title and URI of the W3C document]. Copyright © [YEAR] W3C® (MIT, ERCIM, Keio, Beihang)." +Disclaimers +THIS WORK IS PROVIDED "AS IS," AND COPYRIGHT HOLDERS MAKE NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF THE SOFTWARE OR DOCUMENT WILL NOT INFRINGE ANY THIRD PARTY PATENTS, COPYRIGHTS, TRADEMARKS OR OTHER RIGHTS. +COPYRIGHT HOLDERS WILL NOT BE LIABLE FOR ANY DIRECT, INDIRECT, SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF ANY USE OF THE SOFTWARE OR DOCUMENT. +The name and trademarks of copyright holders may NOT be used in advertising or publicity pertaining to the work without specific, written prior permission. Title to copyright in this work will at all times remain with copyright holders." + +License notice for Bit Twiddling Hacks +-------------------------------------- + +Bit Twiddling Hacks + +By Sean Eron Anderson +seander@cs.stanford.edu + +Individually, the code snippets here are in the public domain (unless otherwise +noted) — feel free to use them however you please. The aggregate collection and +descriptions are © 1997-2005 Sean Eron Anderson. The code and descriptions are +distributed in the hope that they will be useful, but WITHOUT ANY WARRANTY and +without even the implied warranty of merchantability or fitness for a particular +purpose. + +License notice for Brotli +-------------------------------------- + +Copyright (c) 2009, 2010, 2013-2016 by the Brotli Authors. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + +compress_fragment.c: +Copyright (c) 2011, Google Inc. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above +copyright notice, this list of conditions and the following disclaimer +in the documentation and/or other materials provided with the +distribution. + * Neither the name of Google Inc. nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +""AS IS"" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +decode_fuzzer.c: +Copyright (c) 2015 The Chromium Authors. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above +copyright notice, this list of conditions and the following disclaimer +in the documentation and/or other materials provided with the +distribution. + * Neither the name of Google Inc. nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +""AS IS"" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." + +License notice for Json.NET +------------------------------- + +https://github.com/JamesNK/Newtonsoft.Json/blob/master/LICENSE.md + +The MIT License (MIT) + +Copyright (c) 2007 James Newton-King + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +License notice for vectorized base64 encoding / decoding +-------------------------------------------------------- + +Copyright (c) 2005-2007, Nick Galbreath +Copyright (c) 2013-2017, Alfred Klomp +Copyright (c) 2015-2017, Wojciech Mula +Copyright (c) 2016-2017, Matthieu Darbois +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + +- Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + +- Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS +IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED +TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A +PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED +TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +License notice for RFC 3492 +--------------------------- + +The punycode implementation is based on the sample code in RFC 3492 + +Copyright (C) The Internet Society (2003). All Rights Reserved. + +This document and translations of it may be copied and furnished to +others, and derivative works that comment on or otherwise explain it +or assist in its implementation may be prepared, copied, published +and distributed, in whole or in part, without restriction of any +kind, provided that the above copyright notice and this paragraph are +included on all such copies and derivative works. However, this +document itself may not be modified in any way, such as by removing +the copyright notice or references to the Internet Society or other +Internet organizations, except as needed for the purpose of +developing Internet standards in which case the procedures for +copyrights defined in the Internet Standards process must be +followed, or as required to translate it into languages other than +English. + +The limited permissions granted above are perpetual and will not be +revoked by the Internet Society or its successors or assigns. + +This document and the information contained herein is provided on an +"AS IS" basis and THE INTERNET SOCIETY AND THE INTERNET ENGINEERING +TASK FORCE DISCLAIMS ALL WARRANTIES, EXPRESS OR IMPLIED, INCLUDING +BUT NOT LIMITED TO ANY WARRANTY THAT THE USE OF THE INFORMATION +HEREIN WILL NOT INFRINGE ANY RIGHTS OR ANY IMPLIED WARRANTIES OF +MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. + +License notice for Algorithm from Internet Draft document "UUIDs and GUIDs" +--------------------------------------------------------------------------- + +Copyright (c) 1990- 1993, 1996 Open Software Foundation, Inc. +Copyright (c) 1989 by Hewlett-Packard Company, Palo Alto, Ca. & +Digital Equipment Corporation, Maynard, Mass. +To anyone who acknowledges that this file is provided "AS IS" +without any express or implied warranty: permission to use, copy, +modify, and distribute this file for any purpose is hereby +granted without fee, provided that the above copyright notices and +this notice appears in all source code copies, and that none of +the names of Open Software Foundation, Inc., Hewlett-Packard +Company, or Digital Equipment Corporation be used in advertising +or publicity pertaining to distribution of the software without +specific, written prior permission. Neither Open Software +Foundation, Inc., Hewlett-Packard Company, Microsoft, nor Digital Equipment +Corporation makes any representations about the suitability of +this software for any purpose. + +Copyright(C) The Internet Society 1997. All Rights Reserved. + +This document and translations of it may be copied and furnished to others, +and derivative works that comment on or otherwise explain it or assist in +its implementation may be prepared, copied, published and distributed, in +whole or in part, without restriction of any kind, provided that the above +copyright notice and this paragraph are included on all such copies and +derivative works.However, this document itself may not be modified in any +way, such as by removing the copyright notice or references to the Internet +Society or other Internet organizations, except as needed for the purpose of +developing Internet standards in which case the procedures for copyrights +defined in the Internet Standards process must be followed, or as required +to translate it into languages other than English. + +The limited permissions granted above are perpetual and will not be revoked +by the Internet Society or its successors or assigns. + +This document and the information contained herein is provided on an "AS IS" +basis and THE INTERNET SOCIETY AND THE INTERNET ENGINEERING TASK FORCE +DISCLAIMS ALL WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO +ANY WARRANTY THAT THE USE OF THE INFORMATION HEREIN WILL NOT INFRINGE ANY +RIGHTS OR ANY IMPLIED WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A +PARTICULAR PURPOSE. + +License notice for Algorithm from RFC 4122 - +A Universally Unique IDentifier (UUID) URN Namespace +---------------------------------------------------- + +Copyright (c) 1990- 1993, 1996 Open Software Foundation, Inc. +Copyright (c) 1989 by Hewlett-Packard Company, Palo Alto, Ca. & +Digital Equipment Corporation, Maynard, Mass. +Copyright (c) 1998 Microsoft. +To anyone who acknowledges that this file is provided "AS IS" +without any express or implied warranty: permission to use, copy, +modify, and distribute this file for any purpose is hereby +granted without fee, provided that the above copyright notices and +this notice appears in all source code copies, and that none of +the names of Open Software Foundation, Inc., Hewlett-Packard +Company, Microsoft, or Digital Equipment Corporation be used in +advertising or publicity pertaining to distribution of the software +without specific, written prior permission. Neither Open Software +Foundation, Inc., Hewlett-Packard Company, Microsoft, nor Digital +Equipment Corporation makes any representations about the +suitability of this software for any purpose." + +License notice for The LLVM Compiler Infrastructure +--------------------------------------------------- + +Developed by: + + LLVM Team + + University of Illinois at Urbana-Champaign + + http://llvm.org + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal with +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: + + * Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimers. + + * Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimers in the + documentation and/or other materials provided with the distribution. + + * Neither the names of the LLVM Team, University of Illinois at + Urbana-Champaign, nor the names of its contributors may be used to + endorse or promote products derived from this Software without specific + prior written permission. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS WITH THE +SOFTWARE. + +License notice for Bob Jenkins +------------------------------ + +By Bob Jenkins, 1996. bob_jenkins@burtleburtle.net. You may use this +code any way you wish, private, educational, or commercial. It's free. + +License notice for Greg Parker +------------------------------ + +Greg Parker gparker@cs.stanford.edu December 2000 +This code is in the public domain and may be copied or modified without +permission. + +License notice for libunwind based code +---------------------------------------- + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +License notice for Printing Floating-Point Numbers (Dragon4) +------------------------------------------------------------ + +/****************************************************************************** + Copyright (c) 2014 Ryan Juckett + http://www.ryanjuckett.com/ + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + + 3. This notice may not be removed or altered from any source + distribution. +******************************************************************************/ + +License notice for Printing Floating-point Numbers (Grisu3) +----------------------------------------------------------- + +Copyright 2012 the V8 project authors. All rights reserved. +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials provided + with the distribution. + * Neither the name of Google Inc. nor the names of its + contributors may be used to endorse or promote products derived + from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +License notice for xxHash +------------------------- + +xxHash Library +Copyright (c) 2012-2014, Yann Collet +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +* Redistributions in binary form must reproduce the above copyright notice, this + list of conditions and the following disclaimer in the documentation and/or + other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +License notice for Berkeley SoftFloat Release 3e +------------------------------------------------ + +https://github.com/ucb-bar/berkeley-softfloat-3 +https://github.com/ucb-bar/berkeley-softfloat-3/blob/master/COPYING.txt + +License for Berkeley SoftFloat Release 3e + +John R. Hauser +2018 January 20 + +The following applies to the whole of SoftFloat Release 3e as well as to +each source file individually. + +Copyright 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018 The Regents of the +University of California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions, and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF +THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +License notice for xoshiro RNGs +-------------------------------- + +Written in 2018 by David Blackman and Sebastiano Vigna (vigna@acm.org) + +To the extent possible under law, the author has dedicated all copyright +and related and neighboring rights to this software to the public domain +worldwide. This software is distributed without any warranty. + +See . + +License for fastmod (https://github.com/lemire/fastmod) and ibm-fpgen (https://github.com/nigeltao/parse-number-fxx-test-data) +-------------------------------------- + + Copyright 2018 Daniel Lemire + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +License notice for The C++ REST SDK +----------------------------------- + +C++ REST SDK + +The MIT License (MIT) + +Copyright (c) Microsoft Corporation + +All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +License notice for MessagePack-CSharp +------------------------------------- + +MessagePack for C# + +MIT License + +Copyright (c) 2017 Yoshifumi Kawai + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +License notice for lz4net +------------------------------------- + +lz4net + +Copyright (c) 2013-2017, Milosz Krajewski + +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + +Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + +Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +License notice for Nerdbank.Streams +----------------------------------- + +The MIT License (MIT) + +Copyright (c) Andrew Arnott + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +License notice for RapidJSON +---------------------------- + +Tencent is pleased to support the open source community by making RapidJSON available. + +Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. + +Licensed under the MIT License (the "License"); you may not use this file except +in compliance with the License. You may obtain a copy of the License at + +http://opensource.org/licenses/MIT + +Unless required by applicable law or agreed to in writing, software distributed +under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR +CONDITIONS OF ANY KIND, either express or implied. See the License for the +specific language governing permissions and limitations under the License. + +License notice for DirectX Math Library +--------------------------------------- + +https://github.com/microsoft/DirectXMath/blob/master/LICENSE + + The MIT License (MIT) + +Copyright (c) 2011-2020 Microsoft Corp + +Permission is hereby granted, free of charge, to any person obtaining a copy of this +software and associated documentation files (the "Software"), to deal in the Software +without restriction, including without limitation the rights to use, copy, modify, +merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice shall be included in all copies +or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF +CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE +OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +License notice for ldap4net +--------------------------- + +The MIT License (MIT) + +Copyright (c) 2018 Alexander Chermyanin + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +License notice for vectorized sorting code +------------------------------------------ + +MIT License + +Copyright (c) 2020 Dan Shechter + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +License notice for musl +----------------------- + +musl as a whole is licensed under the following standard MIT license: + +Copyright © 2005-2020 Rich Felker, et al. + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + +License notice for "Faster Unsigned Division by Constants" +------------------------------ + +Reference implementations of computing and using the "magic number" approach to dividing +by constants, including codegen instructions. The unsigned division incorporates the +"round down" optimization per ridiculous_fish. + +This is free and unencumbered software. Any copyright is dedicated to the Public Domain. + + +License notice for mimalloc +----------------------------------- + +MIT License + +Copyright (c) 2019 Microsoft Corporation, Daan Leijen + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/third-party/dotnet-packages/system.security.cryptography.protecteddata/LICENSE.txt b/third-party/dotnet-packages/system.security.cryptography.protecteddata/LICENSE.txt new file mode 100644 index 0000000..984713a --- /dev/null +++ b/third-party/dotnet-packages/system.security.cryptography.protecteddata/LICENSE.txt @@ -0,0 +1,23 @@ +The MIT License (MIT) + +Copyright (c) .NET Foundation and Contributors + +All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/third-party/dotnet-packages/system.security.cryptography.protecteddata/THIRD-PARTY-NOTICES.TXT b/third-party/dotnet-packages/system.security.cryptography.protecteddata/THIRD-PARTY-NOTICES.TXT new file mode 100644 index 0000000..1e194f3 --- /dev/null +++ b/third-party/dotnet-packages/system.security.cryptography.protecteddata/THIRD-PARTY-NOTICES.TXT @@ -0,0 +1,1418 @@ +.NET Runtime uses third-party libraries or other resources that may be +distributed under licenses different than the .NET Runtime software. + +In the event that we accidentally failed to list a required notice, please +bring it to our attention. Post an issue or email us: + + dotnet@microsoft.com + +The attached notices are provided for information only. + +License notice for ASP.NET +------------------------------- + +Copyright (c) .NET Foundation. All rights reserved. +Licensed under the Apache License, Version 2.0. + +Available at +https://github.com/dotnet/aspnetcore/blob/main/LICENSE.txt + +License notice for Slicing-by-8 +------------------------------- + +http://sourceforge.net/projects/slicing-by-8/ + +Copyright (c) 2004-2006 Intel Corporation - All Rights Reserved + + +This software program is licensed subject to the BSD License, available at +http://www.opensource.org/licenses/bsd-license.html. + + +License notice for Unicode data +------------------------------- + +https://www.unicode.org/license.html + +Copyright © 1991-2024 Unicode, Inc. All rights reserved. +Distributed under the Terms of Use in https://www.unicode.org/copyright.html. + +Permission is hereby granted, free of charge, to any person obtaining a +copy of data files and any associated documentation (the "Data Files") or +software and any associated documentation (the "Software") to deal in the +Data Files or Software without restriction, including without limitation +the rights to use, copy, modify, merge, publish, distribute, and/or sell +copies of the Data Files or Software, and to permit persons to whom the +Data Files or Software are furnished to do so, provided that either (a) +this copyright and permission notice appear with all copies of the Data +Files or Software, or (b) this copyright and permission notice appear in +associated Documentation. + +THE DATA FILES AND SOFTWARE ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY +KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF +THIRD PARTY RIGHTS. + +IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS INCLUDED IN THIS NOTICE +BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, +OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, +WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, +ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THE DATA +FILES OR SOFTWARE. + +Except as contained in this notice, the name of a copyright holder shall +not be used in advertising or otherwise to promote the sale, use or other +dealings in these Data Files or Software without prior written +authorization of the copyright holder. + +License notice for zlib-ng +----------------------- + +https://github.com/zlib-ng/zlib-ng/blob/d54e3769be0c522015b784eca2af258b1c026107/LICENSE.md + +(C) 1995-2024 Jean-loup Gailly and Mark Adler + +This software is provided 'as-is', without any express or implied +warranty. In no event will the authors be held liable for any damages +arising from the use of this software. + +Permission is granted to anyone to use this software for any purpose, +including commercial applications, and to alter it and redistribute it +freely, subject to the following restrictions: + +1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + +2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + +3. This notice may not be removed or altered from any source distribution. + +License notice for opentelemetry-dotnet +--------------------------------------- + +https://github.com/open-telemetry/opentelemetry-dotnet/blob/805dd6b4abfa18ef2706d04c30d0ed28dbc2955e/LICENSE.TXT#L1 + +Apache License +Version 2.0, January 2004 +http://www.apache.org/licenses/ + +Copyright The OpenTelemetry Authors + + +License notice for LinuxTracepoints +----------------------------------- + +https://github.com/microsoft/LinuxTracepoints/blob/main/LICENSE + +Copyright (c) Microsoft Corporation. + +MIT License + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE + +License notice for Mono +------------------------------- + +http://www.mono-project.com/docs/about-mono/ + +Copyright (c) .NET Foundation Contributors + +MIT License + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the Software), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +License notice for International Organization for Standardization +----------------------------------------------------------------- + +Portions (C) International Organization for Standardization 1986: + Permission to copy in any form is granted for use with + conforming SGML systems and applications as defined in + ISO 8879, provided this notice is included in all copies. + +License notice for Intel +------------------------ + +"Copyright (c) 2004-2006 Intel Corporation - All Rights Reserved + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this +list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, +this list of conditions and the following disclaimer in the documentation +and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +License notice for Xamarin and Novell +------------------------------------- + +Copyright (c) 2015 Xamarin, Inc (http://www.xamarin.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + +Copyright (c) 2011 Novell, Inc (http://www.novell.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + +Third party notice for W3C +-------------------------- + +"W3C SOFTWARE AND DOCUMENT NOTICE AND LICENSE +Status: This license takes effect 13 May, 2015. +This work is being provided by the copyright holders under the following license. +License +By obtaining and/or copying this work, you (the licensee) agree that you have read, understood, and will comply with the following terms and conditions. +Permission to copy, modify, and distribute this work, with or without modification, for any purpose and without fee or royalty is hereby granted, provided that you include the following on ALL copies of the work or portions thereof, including modifications: +The full text of this NOTICE in a location viewable to users of the redistributed or derivative work. +Any pre-existing intellectual property disclaimers, notices, or terms and conditions. If none exist, the W3C Software and Document Short Notice should be included. +Notice of any changes or modifications, through a copyright statement on the new code or document such as "This software or document includes material copied from or derived from [title and URI of the W3C document]. Copyright © [YEAR] W3C® (MIT, ERCIM, Keio, Beihang)." +Disclaimers +THIS WORK IS PROVIDED "AS IS," AND COPYRIGHT HOLDERS MAKE NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF THE SOFTWARE OR DOCUMENT WILL NOT INFRINGE ANY THIRD PARTY PATENTS, COPYRIGHTS, TRADEMARKS OR OTHER RIGHTS. +COPYRIGHT HOLDERS WILL NOT BE LIABLE FOR ANY DIRECT, INDIRECT, SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF ANY USE OF THE SOFTWARE OR DOCUMENT. +The name and trademarks of copyright holders may NOT be used in advertising or publicity pertaining to the work without specific, written prior permission. Title to copyright in this work will at all times remain with copyright holders." + +License notice for Bit Twiddling Hacks +-------------------------------------- + +Bit Twiddling Hacks + +By Sean Eron Anderson +seander@cs.stanford.edu + +Individually, the code snippets here are in the public domain (unless otherwise +noted) — feel free to use them however you please. The aggregate collection and +descriptions are © 1997-2005 Sean Eron Anderson. The code and descriptions are +distributed in the hope that they will be useful, but WITHOUT ANY WARRANTY and +without even the implied warranty of merchantability or fitness for a particular +purpose. + +License notice for Brotli +-------------------------------------- + +Copyright (c) 2009, 2010, 2013-2016 by the Brotli Authors. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + +compress_fragment.c: +Copyright (c) 2011, Google Inc. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above +copyright notice, this list of conditions and the following disclaimer +in the documentation and/or other materials provided with the +distribution. + * Neither the name of Google Inc. nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +""AS IS"" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +decode_fuzzer.c: +Copyright (c) 2015 The Chromium Authors. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above +copyright notice, this list of conditions and the following disclaimer +in the documentation and/or other materials provided with the +distribution. + * Neither the name of Google Inc. nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +""AS IS"" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." + +License notice for Json.NET +------------------------------- + +https://github.com/JamesNK/Newtonsoft.Json/blob/master/LICENSE.md + +The MIT License (MIT) + +Copyright (c) 2007 James Newton-King + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +License notice for vectorized base64 encoding / decoding +-------------------------------------------------------- + +Copyright (c) 2005-2007, Nick Galbreath +Copyright (c) 2013-2017, Alfred Klomp +Copyright (c) 2015-2017, Wojciech Mula +Copyright (c) 2016-2017, Matthieu Darbois +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + +- Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + +- Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS +IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED +TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A +PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED +TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +License notice for vectorized hex parsing +-------------------------------------------------------- + +Copyright (c) 2022, Geoff Langdale +Copyright (c) 2022, Wojciech Mula +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + +- Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + +- Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS +IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED +TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A +PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED +TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +License notice for RFC 3492 +--------------------------- + +The punycode implementation is based on the sample code in RFC 3492 + +Copyright (C) The Internet Society (2003). All Rights Reserved. + +This document and translations of it may be copied and furnished to +others, and derivative works that comment on or otherwise explain it +or assist in its implementation may be prepared, copied, published +and distributed, in whole or in part, without restriction of any +kind, provided that the above copyright notice and this paragraph are +included on all such copies and derivative works. However, this +document itself may not be modified in any way, such as by removing +the copyright notice or references to the Internet Society or other +Internet organizations, except as needed for the purpose of +developing Internet standards in which case the procedures for +copyrights defined in the Internet Standards process must be +followed, or as required to translate it into languages other than +English. + +The limited permissions granted above are perpetual and will not be +revoked by the Internet Society or its successors or assigns. + +This document and the information contained herein is provided on an +"AS IS" basis and THE INTERNET SOCIETY AND THE INTERNET ENGINEERING +TASK FORCE DISCLAIMS ALL WARRANTIES, EXPRESS OR IMPLIED, INCLUDING +BUT NOT LIMITED TO ANY WARRANTY THAT THE USE OF THE INFORMATION +HEREIN WILL NOT INFRINGE ANY RIGHTS OR ANY IMPLIED WARRANTIES OF +MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. + +Copyright(C) The Internet Society 1997. All Rights Reserved. + +This document and translations of it may be copied and furnished to others, +and derivative works that comment on or otherwise explain it or assist in +its implementation may be prepared, copied, published and distributed, in +whole or in part, without restriction of any kind, provided that the above +copyright notice and this paragraph are included on all such copies and +derivative works.However, this document itself may not be modified in any +way, such as by removing the copyright notice or references to the Internet +Society or other Internet organizations, except as needed for the purpose of +developing Internet standards in which case the procedures for copyrights +defined in the Internet Standards process must be followed, or as required +to translate it into languages other than English. + +The limited permissions granted above are perpetual and will not be revoked +by the Internet Society or its successors or assigns. + +This document and the information contained herein is provided on an "AS IS" +basis and THE INTERNET SOCIETY AND THE INTERNET ENGINEERING TASK FORCE +DISCLAIMS ALL WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO +ANY WARRANTY THAT THE USE OF THE INFORMATION HEREIN WILL NOT INFRINGE ANY +RIGHTS OR ANY IMPLIED WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A +PARTICULAR PURPOSE. + +License notice for Algorithm from RFC 4122 - +A Universally Unique IDentifier (UUID) URN Namespace +---------------------------------------------------- + +Copyright (c) 1990- 1993, 1996 Open Software Foundation, Inc. +Copyright (c) 1989 by Hewlett-Packard Company, Palo Alto, Ca. & +Digital Equipment Corporation, Maynard, Mass. +Copyright (c) 1998 Microsoft. +To anyone who acknowledges that this file is provided "AS IS" +without any express or implied warranty: permission to use, copy, +modify, and distribute this file for any purpose is hereby +granted without fee, provided that the above copyright notices and +this notice appears in all source code copies, and that none of +the names of Open Software Foundation, Inc., Hewlett-Packard +Company, Microsoft, or Digital Equipment Corporation be used in +advertising or publicity pertaining to distribution of the software +without specific, written prior permission. Neither Open Software +Foundation, Inc., Hewlett-Packard Company, Microsoft, nor Digital +Equipment Corporation makes any representations about the +suitability of this software for any purpose." + +License notice for The LLVM Compiler Infrastructure +--------------------------------------------------- + +Developed by: + + LLVM Team + + University of Illinois at Urbana-Champaign + + http://llvm.org + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal with +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: + + * Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimers. + + * Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimers in the + documentation and/or other materials provided with the distribution. + + * Neither the names of the LLVM Team, University of Illinois at + Urbana-Champaign, nor the names of its contributors may be used to + endorse or promote products derived from this Software without specific + prior written permission. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS WITH THE +SOFTWARE. + +License notice for Bob Jenkins +------------------------------ + +By Bob Jenkins, 1996. bob_jenkins@burtleburtle.net. You may use this +code any way you wish, private, educational, or commercial. It's free. + +License notice for Greg Parker +------------------------------ + +Greg Parker gparker@cs.stanford.edu December 2000 +This code is in the public domain and may be copied or modified without +permission. + +License notice for libunwind based code +---------------------------------------- + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +License notice for Printing Floating-Point Numbers (Dragon4) +------------------------------------------------------------ + +/****************************************************************************** + Copyright (c) 2014 Ryan Juckett + http://www.ryanjuckett.com/ + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + + 3. This notice may not be removed or altered from any source + distribution. +******************************************************************************/ + +License notice for Printing Floating-point Numbers (Grisu3) +----------------------------------------------------------- + +Copyright 2012 the V8 project authors. All rights reserved. +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials provided + with the distribution. + * Neither the name of Google Inc. nor the names of its + contributors may be used to endorse or promote products derived + from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +License notice for xxHash +------------------------- + +xxHash - Extremely Fast Hash algorithm +Header File +Copyright (C) 2012-2021 Yann Collet + +BSD 2-Clause License (https://www.opensource.org/licenses/bsd-license.php) + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following disclaimer + in the documentation and/or other materials provided with the + distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +You can contact the author at: + - xxHash homepage: https://www.xxhash.com + - xxHash source repository: https://github.com/Cyan4973/xxHash + +License notice for Berkeley SoftFloat Release 3e +------------------------------------------------ + +https://github.com/ucb-bar/berkeley-softfloat-3 +https://github.com/ucb-bar/berkeley-softfloat-3/blob/master/COPYING.txt + +License for Berkeley SoftFloat Release 3e + +John R. Hauser +2018 January 20 + +The following applies to the whole of SoftFloat Release 3e as well as to +each source file individually. + +Copyright 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018 The Regents of the +University of California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions, and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF +THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +License notice for xoshiro RNGs +-------------------------------- + +Written in 2018 by David Blackman and Sebastiano Vigna (vigna@acm.org) + +To the extent possible under law, the author has dedicated all copyright +and related and neighboring rights to this software to the public domain +worldwide. This software is distributed without any warranty. + +See . + +License for fastmod (https://github.com/lemire/fastmod), ibm-fpgen (https://github.com/nigeltao/parse-number-fxx-test-data) and fastrange (https://github.com/lemire/fastrange) +-------------------------------------- + + Copyright 2018 Daniel Lemire + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +License for sse4-strstr (https://github.com/WojciechMula/sse4-strstr) +-------------------------------------- + + Copyright (c) 2008-2016, Wojciech Mula + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are + met: + + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED + TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A + PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED + TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +License notice for The C++ REST SDK +----------------------------------- + +C++ REST SDK + +The MIT License (MIT) + +Copyright (c) Microsoft Corporation + +All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +License notice for MessagePack-CSharp +------------------------------------- + +MessagePack for C# + +MIT License + +Copyright (c) 2017 Yoshifumi Kawai + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +License notice for lz4net +------------------------------------- + +lz4net + +Copyright (c) 2013-2017, Milosz Krajewski + +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + +Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + +Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +License notice for Nerdbank.Streams +----------------------------------- + +The MIT License (MIT) + +Copyright (c) Andrew Arnott + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +License notice for RapidJSON +---------------------------- + +Tencent is pleased to support the open source community by making RapidJSON available. + +Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. + +Licensed under the MIT License (the "License"); you may not use this file except +in compliance with the License. You may obtain a copy of the License at + +http://opensource.org/licenses/MIT + +Unless required by applicable law or agreed to in writing, software distributed +under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR +CONDITIONS OF ANY KIND, either express or implied. See the License for the +specific language governing permissions and limitations under the License. + +License notice for DirectX Math Library +--------------------------------------- + +https://github.com/microsoft/DirectXMath/blob/master/LICENSE + + The MIT License (MIT) + +Copyright (c) 2011-2020 Microsoft Corp + +Permission is hereby granted, free of charge, to any person obtaining a copy of this +software and associated documentation files (the "Software"), to deal in the Software +without restriction, including without limitation the rights to use, copy, modify, +merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice shall be included in all copies +or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF +CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE +OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +License notice for ldap4net +--------------------------- + +The MIT License (MIT) + +Copyright (c) 2018 Alexander Chermyanin + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +License notice for vectorized sorting code +------------------------------------------ + +MIT License + +Copyright (c) 2020 Dan Shechter + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +License notice for musl +----------------------- + +musl as a whole is licensed under the following standard MIT license: + +Copyright © 2005-2020 Rich Felker, et al. + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + +License notice for "Faster Unsigned Division by Constants" +------------------------------ + +Reference implementations of computing and using the "magic number" approach to dividing +by constants, including codegen instructions. The unsigned division incorporates the +"round down" optimization per ridiculous_fish. + +This is free and unencumbered software. Any copyright is dedicated to the Public Domain. + + +License notice for mimalloc +----------------------------------- + +MIT License + +Copyright (c) 2019 Microsoft Corporation, Daan Leijen + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +License for remote stack unwind (https://github.com/llvm/llvm-project/blob/main/lldb/source/Symbol/CompactUnwindInfo.cpp) +-------------------------------------- + +Copyright 2019 LLVM Project + +Licensed under the Apache License, Version 2.0 (the "License") with LLVM Exceptions; +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +https://llvm.org/LICENSE.txt + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +License notice for Apple header files +------------------------------------- + +Copyright (c) 1980, 1986, 1993 + The Regents of the University of California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. +3. All advertising materials mentioning features or use of this software + must display the following acknowledgement: + This product includes software developed by the University of + California, Berkeley and its contributors. +4. Neither the name of the University nor the names of its contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS +OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY +OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF +SUCH DAMAGE. + +License notice for JavaScript queues +------------------------------------- + +CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED HEREUNDER. + +Statement of Purpose +The laws of most jurisdictions throughout the world automatically confer exclusive Copyright and Related Rights (defined below) upon the creator and subsequent owner(s) (each and all, an "owner") of an original work of authorship and/or a database (each, a "Work"). +Certain owners wish to permanently relinquish those rights to a Work for the purpose of contributing to a commons of creative, cultural and scientific works ("Commons") that the public can reliably and without fear of later claims of infringement build upon, modify, incorporate in other works, reuse and redistribute as freely as possible in any form whatsoever and for any purposes, including without limitation commercial purposes. These owners may contribute to the Commons to promote the ideal of a free culture and the further production of creative, cultural and scientific works, or to gain reputation or greater distribution for their Work in part through the use and efforts of others. +For these and/or other purposes and motivations, and without any expectation of additional consideration or compensation, the person associating CC0 with a Work (the "Affirmer"), to the extent that he or she is an owner of Copyright and Related Rights in the Work, voluntarily elects to apply CC0 to the Work and publicly distribute the Work under its terms, with knowledge of his or her Copyright and Related Rights in the Work and the meaning and intended legal effect of CC0 on those rights. + +1. Copyright and Related Rights. A Work made available under CC0 may be protected by copyright and related or neighboring rights ("Copyright and Related Rights"). Copyright and Related Rights include, but are not limited to, the following: +the right to reproduce, adapt, distribute, perform, display, communicate, and translate a Work; +moral rights retained by the original author(s) and/or performer(s); +publicity and privacy rights pertaining to a person's image or likeness depicted in a Work; +rights protecting against unfair competition in regards to a Work, subject to the limitations in paragraph 4(a), below; +rights protecting the extraction, dissemination, use and reuse of data in a Work; +database rights (such as those arising under Directive 96/9/EC of the European Parliament and of the Council of 11 March 1996 on the legal protection of databases, and under any national implementation thereof, including any amended or successor version of such directive); and +other similar, equivalent or corresponding rights throughout the world based on applicable law or treaty, and any national implementations thereof. +2. Waiver. To the greatest extent permitted by, but not in contravention of, applicable law, Affirmer hereby overtly, fully, permanently, irrevocably and unconditionally waives, abandons, and surrenders all of Affirmer's Copyright and Related Rights and associated claims and causes of action, whether now known or unknown (including existing as well as future claims and causes of action), in the Work (i) in all territories worldwide, (ii) for the maximum duration provided by applicable law or treaty (including future time extensions), (iii) in any current or future medium and for any number of copies, and (iv) for any purpose whatsoever, including without limitation commercial, advertising or promotional purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each member of the public at large and to the detriment of Affirmer's heirs and successors, fully intending that such Waiver shall not be subject to revocation, rescission, cancellation, termination, or any other legal or equitable action to disrupt the quiet enjoyment of the Work by the public as contemplated by Affirmer's express Statement of Purpose. +3. Public License Fallback. Should any part of the Waiver for any reason be judged legally invalid or ineffective under applicable law, then the Waiver shall be preserved to the maximum extent permitted taking into account Affirmer's express Statement of Purpose. In addition, to the extent the Waiver is so judged Affirmer hereby grants to each affected person a royalty-free, non transferable, non sublicensable, non exclusive, irrevocable and unconditional license to exercise Affirmer's Copyright and Related Rights in the Work (i) in all territories worldwide, (ii) for the maximum duration provided by applicable law or treaty (including future time extensions), (iii) in any current or future medium and for any number of copies, and (iv) for any purpose whatsoever, including without limitation commercial, advertising or promotional purposes (the "License"). The License shall be deemed effective as of the date CC0 was applied by Affirmer to the Work. Should any part of the License for any reason be judged legally invalid or ineffective under applicable law, such partial invalidity or ineffectiveness shall not invalidate the remainder of the License, and in such case Affirmer hereby affirms that he or she will not (i) exercise any of his or her remaining Copyright and Related Rights in the Work or (ii) assert any associated claims and causes of action with respect to the Work, in either case contrary to Affirmer's express Statement of Purpose. +4. Limitations and Disclaimers. +a. No trademark or patent rights held by Affirmer are waived, abandoned, surrendered, licensed or otherwise affected by this document. +b. Affirmer offers the Work as-is and makes no representations or warranties of any kind concerning the Work, express, implied, statutory or otherwise, including without limitation warranties of title, merchantability, fitness for a particular purpose, non infringement, or the absence of latent or other defects, accuracy, or the present or absence of errors, whether or not discoverable, all to the greatest extent permissible under applicable law. +c. Affirmer disclaims responsibility for clearing rights of other persons that may apply to the Work or any use thereof, including without limitation any person's Copyright and Related Rights in the Work. Further, Affirmer disclaims responsibility for obtaining any necessary consents, permissions or other rights required for any use of the Work. +d. Affirmer understands and acknowledges that Creative Commons is not a party to this document and has no duty or obligation with respect to this CC0 or use of the Work. + + +License notice for FastFloat algorithm +------------------------------------- +MIT License +Copyright (c) 2021 csFastFloat authors +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +License notice for MsQuic +-------------------------------------- + +Copyright (c) Microsoft Corporation. +Licensed under the MIT License. + +Available at +https://github.com/microsoft/msquic/blob/main/LICENSE + +License notice for m-ou-se/floatconv +------------------------------- + +Copyright (c) 2020 Mara Bos +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +License notice for code from The Practice of Programming +------------------------------- + +Copyright (C) 1999 Lucent Technologies + +Excerpted from 'The Practice of Programming +by Brian W. Kernighan and Rob Pike + +You may use this code for any purpose, as long as you leave the copyright notice and book citation attached. + +Notice for Euclidean Affine Functions and Applications to Calendar +Algorithms +------------------------------- + +Aspects of Date/Time processing based on algorithm described in "Euclidean Affine Functions and Applications to Calendar +Algorithms", Cassio Neri and Lorenz Schneider. https://arxiv.org/pdf/2102.06959.pdf + +License notice for amd/aocl-libm-ose +------------------------------- + +Copyright (C) 2008-2020 Advanced Micro Devices, Inc. All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: +1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. +3. Neither the name of the copyright holder nor the names of its contributors + may be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. +IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, +INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, +OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, +WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +POSSIBILITY OF SUCH DAMAGE. + +License notice for fmtlib/fmt +------------------------------- + +Formatting library for C++ + +Copyright (c) 2012 - present, Victor Zverovich + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +License for Jb Evain +--------------------- + +Copyright (c) 2006 Jb Evain (jbevain@gmail.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included +in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + +--- Optional exception to the license --- + +As an exception, if, as a result of your compiling your source code, portions +of this Software are embedded into a machine-executable object form of such +source code, you may redistribute such embedded portions in such object form +without including the above copyright and permission notices. + + +License for MurmurHash3 +-------------------------------------- + +https://github.com/aappleby/smhasher/blob/master/src/MurmurHash3.cpp + +MurmurHash3 was written by Austin Appleby, and is placed in the public +domain. The author hereby disclaims copyright to this source + +License for Fast CRC Computation +-------------------------------------- + +https://github.com/intel/isa-l/blob/33a2d9484595c2d6516c920ce39a694c144ddf69/crc/crc32_ieee_by4.asm +https://github.com/intel/isa-l/blob/33a2d9484595c2d6516c920ce39a694c144ddf69/crc/crc64_ecma_norm_by8.asm + +Copyright(c) 2011-2015 Intel Corporation All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in + the documentation and/or other materials provided with the + distribution. + * Neither the name of Intel Corporation nor the names of its + contributors may be used to endorse or promote products derived + from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +License for C# Implementation of Fast CRC Computation +----------------------------------------------------- + +https://github.com/SixLabors/ImageSharp/blob/f4f689ce67ecbcc35cebddba5aacb603e6d1068a/src/ImageSharp/Formats/Png/Zlib/Crc32.cs + +Copyright (c) Six Labors. +Licensed under the Apache License, Version 2.0. + +Available at +https://github.com/SixLabors/ImageSharp/blob/f4f689ce67ecbcc35cebddba5aacb603e6d1068a/LICENSE + +License for the Teddy multi-substring searching implementation +-------------------------------------- + +https://github.com/BurntSushi/aho-corasick + +The MIT License (MIT) + +Copyright (c) 2015 Andrew Gallant + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + +License notice for Avx512Vbmi base64 encoding / decoding +-------------------------------------------------------- + +Copyright (c) 2015-2018, Wojciech Muła +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS +IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED +TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A +PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED +TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +-------------------------------------------------------- + +Aspects of base64 encoding / decoding are based on algorithm described in "Base64 encoding and decoding at almost the speed of a memory +copy", Wojciech Muła and Daniel Lemire. https://arxiv.org/pdf/1910.05109.pdf + +License for FormatJS Intl.Segmenter grapheme segmentation algorithm +-------------------------------------------------------------------------- +Available at https://github.com/formatjs/formatjs/blob/58d6a7b398d776ca3d2726d72ae1573b65cc3bef/packages/intl-segmenter/LICENSE.md + +MIT License + +Copyright (c) 2022 FormatJS + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +License for SharpFuzz and related samples +-------------------------------------- + +https://github.com/Metalnem/sharpfuzz +https://github.com/Metalnem/dotnet-fuzzers +https://github.com/Metalnem/libfuzzer-dotnet + +MIT License + +Copyright (c) 2018 Nemanja Mijailovic + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +License for National Institute of Standards and Technology ACVP Data +-------------------------------------------------------------------- +Available at https://github.com/usnistgov/ACVP-Server/blob/85f8742965b2691862079172982683757d8d91db/README.md#License + +NIST-developed software is provided by NIST as a public service. You may use, copy, and distribute copies of the software in any medium, provided that you keep intact this entire notice. You may improve, modify, and create derivative works of the software or any portion of the software, and you may copy and distribute such modifications or works. Modified works should carry a notice stating that you changed the software and should note the date and nature of any such change. Please explicitly acknowledge the National Institute of Standards and Technology as the source of the software. + +NIST-developed software is expressly provided "AS IS." NIST MAKES NO WARRANTY OF ANY KIND, EXPRESS, IMPLIED, IN FACT, OR ARISING BY OPERATION OF LAW, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NON-INFRINGEMENT, AND DATA ACCURACY. NIST NEITHER REPRESENTS NOR WARRANTS THAT THE OPERATION OF THE SOFTWARE WILL BE UNINTERRUPTED OR ERROR-FREE, OR THAT ANY DEFECTS WILL BE CORRECTED. NIST DOES NOT WARRANT OR MAKE ANY REPRESENTATIONS REGARDING THE USE OF THE SOFTWARE OR THE RESULTS THEREOF, INCLUDING BUT NOT LIMITED TO THE CORRECTNESS, ACCURACY, RELIABILITY, OR USEFULNESS OF THE SOFTWARE. + +You are solely responsible for determining the appropriateness of using and distributing the software and you assume all risks associated with its use, including but not limited to the risks and costs of program errors, compliance with applicable laws, damage to or loss of data, programs or equipment, and the unavailability or interruption of operation. This software is not intended to be used in any situation where a failure could cause risk of injury or damage to property. The software developed by NIST employees is not subject to copyright protection within the United States. + From 8210307aca09f673f2eafff9935f0ba6e23ad454 Mon Sep 17 00:00:00 2001 From: Gordon Breuer Date: Fri, 23 Oct 2026 22:41:57 +0200 Subject: [PATCH 14/26] Accept leading JSON mode consistently for script commands --- scripts/animation_smoke.py | 3 ++- src/SidePulse.Cli/TerminalMode.cs | 10 +++++++++- 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/scripts/animation_smoke.py b/scripts/animation_smoke.py index 5fd5423..b63ec41 100644 --- a/scripts/animation_smoke.py +++ b/scripts/animation_smoke.py @@ -21,7 +21,8 @@ def run(*args, code=0): assert not result.stderr, (args, result.stderr) return result - patterns = json.loads(run('animations', 'list', '--json').stdout) + patterns = json.loads(run('--json', 'animations', 'list').stdout) + assert patterns == json.loads(run('animations', 'list', '--json').stdout) assert any(p['Name'] == 'cyan-roll' and p['Models'] == ['Dot', 'Pro'] for p in patterns) frames = json.loads(run('animations', 'preview', 'cyan-roll', '--both', '--at', '500', '--json').stdout) assert [len(f['colors']) for f in frames] == [2, 8] diff --git a/src/SidePulse.Cli/TerminalMode.cs b/src/SidePulse.Cli/TerminalMode.cs index 337922c..9ffe738 100644 --- a/src/SidePulse.Cli/TerminalMode.cs +++ b/src/SidePulse.Cli/TerminalMode.cs @@ -22,7 +22,15 @@ public static string[] Configure(string[] args) if (Quiet && !Json) Console.SetOut(TextWriter.Null); if (noColor || Quiet) AnsiConsole.Console = AnsiConsole.Create(new AnsiConsoleSettings { Out = new AnsiConsoleOutput(Console.Out), Ansi = Console.IsOutputRedirected || Quiet ? AnsiSupport.No : AnsiSupport.Detect, ColorSystem = ColorSystemSupport.NoColors }); var literal = false; - return args.Where(a => { if (a == "--") literal = true; return literal || a is not "--quiet" and not "--no-interactive" and not "--no-color"; }).ToArray(); + var result = args.Where(a => { if (a == "--") literal = true; return literal || a is not "--quiet" and not "--no-interactive" and not "--no-color"; }).ToList(); + // Spectre binds JSON to individual commands; normalize a leading global spelling. + if (result.FirstOrDefault() == "--json") + { + while (result.FirstOrDefault() == "--json") result.RemoveAt(0); + var divider = result.IndexOf("--"); + result.Insert(divider < 0 ? result.Count : divider, "--json"); + } + return result.ToArray(); } public static int Error(Exception exception) { From c96608845728c88b88de6a212f6b2dd145fe3aee Mon Sep 17 00:00:00 2001 From: Gordon Breuer Date: Fri, 23 Oct 2026 22:44:52 +0200 Subject: [PATCH 15/26] Honor plain help output and synchronize terminal save checks --- scripts/animation_smoke.py | 2 +- scripts/terminal_smoke.py | 5 +---- src/SidePulse.Cli/PatternEditor.cs | 1 + src/SidePulse.Cli/Program.cs | 1 + .../THIRD-PARTY-NOTICES.TXT | 1 - 5 files changed, 4 insertions(+), 6 deletions(-) diff --git a/scripts/animation_smoke.py b/scripts/animation_smoke.py index b63ec41..3823140 100644 --- a/scripts/animation_smoke.py +++ b/scripts/animation_smoke.py @@ -11,7 +11,7 @@ def main(executable): executable = str(Path(executable).resolve()) with tempfile.TemporaryDirectory(prefix='sidepulse animations ü ') as temporary: root = Path(temporary) - env = dict(os.environ, SIDEPULSE_NET_HOME=str(root / 'config'), NO_COLOR='1') + env = dict(os.environ, SIDEPULSE_NET_HOME=str(root / 'config'), NO_COLOR='1', FORCE_COLOR='1') def run(*args, code=0): result = subprocess.run([executable, *args], env=env, capture_output=True, text=True, timeout=10) diff --git a/scripts/terminal_smoke.py b/scripts/terminal_smoke.py index f1c011c..50407d1 100644 --- a/scripts/terminal_smoke.py +++ b/scripts/terminal_smoke.py @@ -85,10 +85,7 @@ def finish(self): editor.send(b'\x1b') # back to editor editor.until('Save to library') editor.send(b'\x1b[B' * 5 + b'\r') # save - editor.until('Save to library') - deadline = time.monotonic() + 5 - while not file.exists() and time.monotonic() < deadline: - time.sleep(0.05) + editor.until('Pattern saved:') assert file.exists() and '#00e5ff' in file.read_text(encoding='utf-8') editor.send(b'\x1b') editor.finish() diff --git a/src/SidePulse.Cli/PatternEditor.cs b/src/SidePulse.Cli/PatternEditor.cs index a920c21..e25d4fd 100644 --- a/src/SidePulse.Cli/PatternEditor.cs +++ b/src/SidePulse.Cli/PatternEditor.cs @@ -53,6 +53,7 @@ public override async Task ExecuteAsync(CommandContext context, EditorSetti // Detect external edits before replacing the file. AnimationLibrary.WriteFile(path, program.Text + "\n", original is not null); original = program.Text + "\n"; dirty = false; + Console.WriteLine("Pattern saved: " + path); TerminalMode.Footer(["animations", "preview", "--file", path, "--model", settings.Model.ToString().ToLowerInvariant()]); continue; } diff --git a/src/SidePulse.Cli/Program.cs b/src/SidePulse.Cli/Program.cs index e08d40f..d082457 100644 --- a/src/SidePulse.Cli/Program.cs +++ b/src/SidePulse.Cli/Program.cs @@ -14,6 +14,7 @@ var app = new CommandApp(); app.Configure(config => { + config.ConfigureConsole(AnsiConsole.Console); config.SetApplicationName("sidepulse-net"); config.SetApplicationVersion("0.1.0-alpha.5"); config.AddBranch("animations", animations => diff --git a/third-party/dotnet-packages/system.security.cryptography.protecteddata/THIRD-PARTY-NOTICES.TXT b/third-party/dotnet-packages/system.security.cryptography.protecteddata/THIRD-PARTY-NOTICES.TXT index 1e194f3..38d05d2 100644 --- a/third-party/dotnet-packages/system.security.cryptography.protecteddata/THIRD-PARTY-NOTICES.TXT +++ b/third-party/dotnet-packages/system.security.cryptography.protecteddata/THIRD-PARTY-NOTICES.TXT @@ -1415,4 +1415,3 @@ NIST-developed software is provided by NIST as a public service. You may use, co NIST-developed software is expressly provided "AS IS." NIST MAKES NO WARRANTY OF ANY KIND, EXPRESS, IMPLIED, IN FACT, OR ARISING BY OPERATION OF LAW, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NON-INFRINGEMENT, AND DATA ACCURACY. NIST NEITHER REPRESENTS NOR WARRANTS THAT THE OPERATION OF THE SOFTWARE WILL BE UNINTERRUPTED OR ERROR-FREE, OR THAT ANY DEFECTS WILL BE CORRECTED. NIST DOES NOT WARRANT OR MAKE ANY REPRESENTATIONS REGARDING THE USE OF THE SOFTWARE OR THE RESULTS THEREOF, INCLUDING BUT NOT LIMITED TO THE CORRECTNESS, ACCURACY, RELIABILITY, OR USEFULNESS OF THE SOFTWARE. You are solely responsible for determining the appropriateness of using and distributing the software and you assume all risks associated with its use, including but not limited to the risks and costs of program errors, compliance with applicable laws, damage to or loss of data, programs or equipment, and the unavailability or interruption of operation. This software is not intended to be used in any situation where a failure could cause risk of injury or damage to property. The software developed by NIST employees is not subject to copyright protection within the United States. - From 95d45912734b52010889bc2cf5fc8beb999a560b Mon Sep 17 00:00:00 2001 From: Gordon Breuer Date: Fri, 23 Oct 2026 22:48:23 +0200 Subject: [PATCH 16/26] Keep redirected output plain under CI and drain PTYs during shutdown --- scripts/animation_smoke.py | 2 +- scripts/terminal_smoke.py | 11 ++++++++++- src/SidePulse.Cli/TerminalMode.cs | 2 +- 3 files changed, 12 insertions(+), 3 deletions(-) diff --git a/scripts/animation_smoke.py b/scripts/animation_smoke.py index 3823140..073fe8f 100644 --- a/scripts/animation_smoke.py +++ b/scripts/animation_smoke.py @@ -11,7 +11,7 @@ def main(executable): executable = str(Path(executable).resolve()) with tempfile.TemporaryDirectory(prefix='sidepulse animations ü ') as temporary: root = Path(temporary) - env = dict(os.environ, SIDEPULSE_NET_HOME=str(root / 'config'), NO_COLOR='1', FORCE_COLOR='1') + env = dict(os.environ, SIDEPULSE_NET_HOME=str(root / 'config'), NO_COLOR='1', FORCE_COLOR='1', GITHUB_ACTIONS='true') def run(*args, code=0): result = subprocess.run([executable, *args], env=env, capture_output=True, text=True, timeout=10) diff --git a/scripts/terminal_smoke.py b/scripts/terminal_smoke.py index 50407d1..316d825 100644 --- a/scripts/terminal_smoke.py +++ b/scripts/terminal_smoke.py @@ -52,7 +52,16 @@ def send(self, keys): def finish(self): try: - assert self.process.wait(timeout=10) == 0 + # Keep consuming terminal output while the app clears/redraws on exit. + # macOS PTYs have small buffers; waiting without reading can block it. + deadline = time.monotonic() + 10 + while self.process.poll() is None and time.monotonic() < deadline: + if select.select([self.master], [], [], 0.1)[0]: + try: + self.output += os.read(self.master, 65536) + except OSError: + break + assert self.process.wait(timeout=1) == 0, self.output[-3000:] finally: if self.process.poll() is None: self.process.kill() diff --git a/src/SidePulse.Cli/TerminalMode.cs b/src/SidePulse.Cli/TerminalMode.cs index 9ffe738..3aeed8a 100644 --- a/src/SidePulse.Cli/TerminalMode.cs +++ b/src/SidePulse.Cli/TerminalMode.cs @@ -20,7 +20,7 @@ public static string[] Configure(string[] args) var noColor = options.Contains("--no-color") || Environment.GetEnvironmentVariable("NO_COLOR") is not null || Console.IsOutputRedirected; ColorEnabled = !noColor; if (Quiet && !Json) Console.SetOut(TextWriter.Null); - if (noColor || Quiet) AnsiConsole.Console = AnsiConsole.Create(new AnsiConsoleSettings { Out = new AnsiConsoleOutput(Console.Out), Ansi = Console.IsOutputRedirected || Quiet ? AnsiSupport.No : AnsiSupport.Detect, ColorSystem = ColorSystemSupport.NoColors }); + if (noColor || Quiet) AnsiConsole.Console = AnsiConsole.Create(new AnsiConsoleSettings { Out = new AnsiConsoleOutput(Console.Out), Ansi = Console.IsOutputRedirected || Quiet ? AnsiSupport.No : AnsiSupport.Detect, ColorSystem = ColorSystemSupport.NoColors, Enrichment = new ProfileEnrichment { UseDefaultEnrichers = false } }); var literal = false; var result = args.Where(a => { if (a == "--") literal = true; return literal || a is not "--quiet" and not "--no-interactive" and not "--no-color"; }).ToList(); // Spectre binds JSON to individual commands; normalize a leading global spelling. From 7d97293b03a9931e300156fe915f1a099a38854a Mon Sep 17 00:00:00 2001 From: Gordon Breuer Date: Fri, 23 Oct 2026 23:11:13 +0200 Subject: [PATCH 17/26] Add verified GitHub release updates with staged replacement and rollback --- .github/workflows/dotnet-ci.yml | 6 + .github/workflows/release.yml | 60 +++++++ README.md | 18 ++ docs/wiki/Getting-Started.md | 4 + docs/wiki/Updating.md | 70 ++++++++ docs/wiki/_Sidebar.md | 2 + scripts/package_manifest.py | 27 +++ scripts/release_checksums.py | 19 +++ scripts/update_smoke.py | 56 +++++++ src/SidePulse.Cli/Interactive.cs | 16 +- src/SidePulse.Cli/Program.cs | 12 +- src/SidePulse.Cli/SidePulse.Cli.csproj | 3 +- src/SidePulse.Cli/Updates.cs | 155 +++++++++++++++++ src/SidePulse.Core/Releases.cs | 161 ++++++++++++++++++ src/SidePulse.Core/UpdatePackage.cs | 115 +++++++++++++ src/SidePulse.Core/UpdateTransaction.cs | 112 +++++++++++++ tests/SidePulse.Tests/UpdateTests.cs | 211 ++++++++++++++++++++++++ 17 files changed, 1042 insertions(+), 5 deletions(-) create mode 100644 .github/workflows/release.yml create mode 100644 docs/wiki/Updating.md create mode 100644 scripts/package_manifest.py create mode 100644 scripts/release_checksums.py create mode 100644 scripts/update_smoke.py create mode 100644 src/SidePulse.Cli/Updates.cs create mode 100644 src/SidePulse.Core/Releases.cs create mode 100644 src/SidePulse.Core/UpdatePackage.cs create mode 100644 src/SidePulse.Core/UpdateTransaction.cs create mode 100644 tests/SidePulse.Tests/UpdateTests.cs diff --git a/.github/workflows/dotnet-ci.yml b/.github/workflows/dotnet-ci.yml index 371a2d2..acdd635 100644 --- a/.github/workflows/dotnet-ci.yml +++ b/.github/workflows/dotnet-ci.yml @@ -4,6 +4,7 @@ on: branches: [main] pull_request: workflow_dispatch: + workflow_call: permissions: contents: read concurrency: @@ -115,12 +116,17 @@ jobs: New-Item -ItemType Directory -Force "$destination/third-party/dotnet" | Out-Null Copy-Item "$env:DOTNET_ROOT/LICENSE.txt","$env:DOTNET_ROOT/ThirdPartyNotices.txt" "$destination/third-party/dotnet" Copy-Item docs/wiki/Getting-Started.md $destination + $version = ([xml](Get-Content src/SidePulse.Cli/SidePulse.Cli.csproj -Raw)).Project.PropertyGroup.Version + python scripts/package_manifest.py $destination $rid $version + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } if ($rid -eq $native) { $binary = if ($IsWindows) { 'sidepulse-net.exe' } else { 'sidepulse-net' } python scripts/cli_smoke.py "$destination/$binary" if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } python scripts/animation_smoke.py "$destination/$binary" if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + python scripts/update_smoke.py "$destination/$binary" + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } python scripts/agent_smoke.py "$destination/$binary" if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } } diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..df77ac0 --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,60 @@ +name: Release +on: + push: + tags: ['v*'] + workflow_dispatch: +permissions: + contents: read +concurrency: + group: release-${{ github.ref }} + cancel-in-progress: false +jobs: + validate: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + persist-credentials: false + - name: Require a version tag matching the application + env: + RELEASE_REF: ${{ github.ref }} + run: | + python3 - <<'PY' + import os, re, xml.etree.ElementTree as ET + version = ET.parse('src/SidePulse.Cli/SidePulse.Cli.csproj').findtext('./PropertyGroup/Version') + if os.environ['RELEASE_REF'] != 'refs/tags/v' + version or not re.fullmatch(r'\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?', version): + raise SystemExit('Select/push a vVERSION tag matching the project version; build metadata is not used for release tags.') + PY + build: + needs: validate + uses: ./.github/workflows/dotnet-ci.yml + publish: + needs: build + runs-on: ubuntu-latest + permissions: + contents: write + actions: read + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + persist-credentials: false + - name: Collect tested packages and write checksums + env: + GH_TOKEN: ${{ github.token }} + GH_REPO: ${{ github.repository }} + RELEASE_RUN: ${{ github.run_id }} + run: | + gh run download "$RELEASE_RUN" --pattern 'sidepulse-net-*-preview' --dir release-input + mkdir release-files + find release-input -type f \( -name '*.zip' -o -name '*.tar.gz' \) -exec cp -n {} release-files/ \; + python3 scripts/release_checksums.py release-files + - name: Upload all assets before making the release visible + env: + GH_TOKEN: ${{ github.token }} + GH_REPO: ${{ github.repository }} + RELEASE_TAG: ${{ github.ref_name }} + run: | + flags=() + if [[ "$RELEASE_TAG" == *-* ]]; then flags+=(--prerelease); fi + gh release create "$RELEASE_TAG" --verify-tag --draft --title "SidePulse.NET ${RELEASE_TAG#v}" --generate-notes "${flags[@]}" release-files/* + gh release edit "$RELEASE_TAG" --draft=false "${flags[@]}" diff --git a/README.md b/README.md index 1b09558..9188958 100644 --- a/README.md +++ b/README.md @@ -126,3 +126,21 @@ See [animations](docs/wiki/Animations.md) and [scripting and menus](docs/wiki/Scripting-and-Menus.md). `docs --offline` reads bundled documentation; `about` provides manufacturer/upstream/project links and licensed dependency credits. Browser opening requires `--open`. + +## Verified updates + +```shell +sidepulse-net update check +sidepulse-net update install --prerelease --dry-run +sidepulse-net host stop +sidepulse-net update install --prerelease +sidepulse-net update status +``` + +The updater selects a published GitHub release for the current OS/architecture, +verifies SHA-256, stages the complete distribution and replaces it after the CLI +exits. A backup and startup probe support rollback. Use self-contained packages +with an installation manifest; older previews need one manual upgrade. Stop the +host first and confirm `installed` before restarting it. See +[updating and recovery](docs/wiki/Updating.md). Adding the release workflow does not +publish a release; a matching version tag explicitly triggers publishing. diff --git a/docs/wiki/Getting-Started.md b/docs/wiki/Getting-Started.md index 05bcf15..9d13fcd 100644 --- a/docs/wiki/Getting-Started.md +++ b/docs/wiki/Getting-Started.md @@ -183,3 +183,7 @@ until this preview is validated on your setup. See [[Animations]] for Dot/Pro previews, custom editing and agent profiles, and [[Scripting-and-Menus]] for interactive command building and quiet/JSON output. + +## Updates + +See [[Updating]] for GitHub release checks, verified self-update and recovery. diff --git a/docs/wiki/Updating.md b/docs/wiki/Updating.md new file mode 100644 index 0000000..83dc3be --- /dev/null +++ b/docs/wiki/Updating.md @@ -0,0 +1,70 @@ +# Checking and installing updates + +```sh +sidepulse-net update +sidepulse-net update check --json +sidepulse-net update check --prerelease +sidepulse-net update install --prerelease --dry-run +sidepulse-net host stop +sidepulse-net update install --prerelease +sidepulse-net update status --json +sidepulse-net host start --phone default +``` + +A bare `update` checks only in scripts; in a terminal it offers a cursor menu. +Checks use GitHub public releases without an account/token. Stable releases are +the default. `--prerelease` includes published prereleases and selects the highest +semantic version. Drafts, tags without releases and Actions artifacts are excluded. +A prerelease lookup is bounded to 1,000 releases; rate limits fail with a concise +error. Equal/older versions never downgrade an installation. Missing release assets +or checksums prevent installation. No published release is a normal check result. + +Installation is explicit. The updater chooses the current process architecture +(x64/ARM64), downloads the matching ZIP/tar.gz and `SHA256SUMS`, verifies SHA-256 +before extraction and additionally checks GitHub asset digests when supplied. +It verifies a version/runtime/file-hash manifest and rejects archive traversal, +links, duplicate files, special entries and excessive sizes. Checksums establish +integrity against the published release metadata; they are not independent code +signatures or protection against a compromised publisher account. + +## Replacement and recovery + +Self-update requires a self-contained distribution containing `sidepulse-install.json`. +Source builds, framework-dependent binaries, older previews without that manifest, +modified application files and symlinked installations require manual installation. +The first updater-capable preview is 0.1.0-alpha.6. Older versions must be upgraded +manually once. The install directory and its parent must be writable; the updater +never elevates privileges. Package-manager installations should use that manager. + +Run the command from outside the installation directory. Stop the agent host and +other processes using the installation first. The updater +does not kill processes or change startup registration. Downloading/staging leaves +the current installation intact. A helper copied outside the installation waits +for the calling process to exit, replaces the whole application directory, and +runs the new executable's version check. A failed replacement/probe attempts to +restore the original directory. A per-installation lock prevents concurrent swaps. + +`update install` returning success means **scheduled**, not already installed. +Run `update status` after it exits; wait for `installed` before restarting the host +with its previous target/profile options. Failure/recovery states return exit 1. +The JSON receipt includes target, backup, workspace and state. If interrupted, +status may remain scheduled/applying. Inspect those paths before manual recovery; +never delete the only intact backup. Updating is not a crash-atomic transaction +across the two directory renames. A power failure between them may require restoring +the backup directory manually before the CLI can run again. + +Unknown user-added files are copied into the new directory unless they collide +with a new application-owned file. Avoid editing the installation during updating. +Phone links, profiles and hooks normally live outside it and are not changed. +The complete old installation and temporary download/helper workspace are retained +for recovery. Once installation is confirmed and no helper is running, these +paths may be removed manually to reclaim space. Failed updates preserve evidence. + +## Publishing + +The Release workflow runs on `vVERSION` tags or manual dispatch on such a tag. +The tag must match the project version. It reuses all three native CI jobs and +self-contained smoke checks, collects all six archives, writes `SHA256SUMS`, uploads +a draft release and only then publishes it. Hyphenated versions are prereleases. +No release or tag is created simply by adding this workflow to a branch. Existing +release tags are not overwritten. Review the release notes/assets after publishing. diff --git a/docs/wiki/_Sidebar.md b/docs/wiki/_Sidebar.md index ae14e22..73f1d81 100644 --- a/docs/wiki/_Sidebar.md +++ b/docs/wiki/_Sidebar.md @@ -21,3 +21,5 @@ - [[Animations]] - [[Scripting and menus|Scripting-and-Menus]] + +- [[Updating]] diff --git a/scripts/package_manifest.py b/scripts/package_manifest.py new file mode 100644 index 0000000..fbac505 --- /dev/null +++ b/scripts/package_manifest.py @@ -0,0 +1,27 @@ +"""Describe the owned files of a self-contained distribution, with SHA-256 and modes.""" +import hashlib +import json +from pathlib import Path +import re +import sys + + +def write(directory, runtime, version): + root = Path(directory) + if not re.fullmatch(r'(win|osx|linux)-(x64|arm64)', runtime): + raise ValueError('Unsupported runtime') + manifest = root / 'sidepulse-install.json' + files = [] + for path in sorted(root.rglob('*')): + if path.is_symlink(): + raise ValueError('Distribution contains a symlink') + if path == manifest or path.is_dir(): + continue + files.append({'Path': path.relative_to(root).as_posix(), + 'Sha256': hashlib.sha256(path.read_bytes()).hexdigest(), + 'Mode': path.stat().st_mode & 0o777}) + manifest.write_text(json.dumps({'Format': 1, 'Version': version, 'Runtime': runtime, 'Files': files}, indent=2) + '\n', encoding='utf-8') + + +if __name__ == '__main__': + write(*sys.argv[1:]) diff --git a/scripts/release_checksums.py b/scripts/release_checksums.py new file mode 100644 index 0000000..b5dd053 --- /dev/null +++ b/scripts/release_checksums.py @@ -0,0 +1,19 @@ +"""Write the release checksum list after collecting all six platform archives.""" +import hashlib +from pathlib import Path +import sys + + +def write(directory): + root = Path(directory) + expected = {f'sidepulse-net-{platform}-{arch}' + ('.zip' if platform == 'win' else '.tar.gz') + for platform in ('win', 'linux', 'osx') for arch in ('x64', 'arm64')} + archives = {p.name: p for p in root.iterdir() if p.is_file() and (p.name.endswith('.zip') or p.name.endswith('.tar.gz'))} + if set(archives) != expected: + raise ValueError('Release must contain exactly the six expected runtime archives') + lines = [hashlib.sha256(archives[name].read_bytes()).hexdigest() + ' ' + name for name in sorted(archives)] + (root / 'SHA256SUMS').write_text('\n'.join(lines) + '\n', encoding='utf-8') + + +if __name__ == '__main__': + write(sys.argv[1]) diff --git a/scripts/update_smoke.py b/scripts/update_smoke.py new file mode 100644 index 0000000..93d17f4 --- /dev/null +++ b/scripts/update_smoke.py @@ -0,0 +1,56 @@ +"""Run the actual updater helper against isolated self-contained installs.""" +import hashlib +import json +import os +from pathlib import Path +import shutil +import subprocess +import sys +import tempfile + + +def main(executable): + executable = Path(executable).resolve() + source = executable.parent + shipped = json.loads((source / 'sidepulse-install.json').read_text(encoding='utf-8')) + with tempfile.TemporaryDirectory(prefix='SidePulse updater ü ') as temporary: + root = Path(temporary) + env = dict(os.environ, SIDEPULSE_NET_HOME=str(root / 'state')) + for fail in (False, True): + home = root / ('rollback' if fail else 'success') + target = home / 'installation' + job = home / '.sidepulse-update-smoke' + stage = job / 'stage' + backup = home / 'installation.backup-smoke' + helper = job / 'helper' + # A deliberately incorrect expected version exercises real startup rollback. + for destination in (target, stage, helper): + shutil.copytree(source, destination) + expected = '99.0.0' if fail else shipped['Version'] + if fail: + (stage / 'sidepulse-install.json').write_text(json.dumps(dict(shipped, Version=expected)), encoding='utf-8') + identity = str(target).upper() if os.name == 'nt' else str(target) + key = hashlib.sha256(identity.encode('utf-8')).hexdigest().upper()[:24] + receipt = root / 'state' / 'updates' / (key + '.json') + plan = dict(Target=str(target), Stage=str(stage), Backup=str(backup), Job=str(job), Receipt=str(receipt), + ExpectedManifestHash=hashlib.sha256((target / 'sidepulse-install.json').read_bytes()).hexdigest().upper(), + Version=expected, Runtime=shipped['Runtime'], ParentId=2147483647, ParentStartTicks=0) + plan_path = job / 'plan.json' + plan_path.write_text(json.dumps(plan), encoding='utf-8') + result = subprocess.run([str(helper / executable.name), 'internal-update', '--plan', str(plan_path)], + env=env, capture_output=True, text=True, timeout=75, cwd=job) + assert result.returncode == (1 if fail else 0), (result.returncode, result.stdout, result.stderr) + state = json.loads(receipt.read_text(encoding='utf-8')) + assert state['State'] == ('failed' if fail else 'installed'), state + current = json.loads((target / 'sidepulse-install.json').read_text(encoding='utf-8')) + assert current['Version'] == shipped['Version'] + version = subprocess.run([str(target / executable.name), '--version'], env=env, capture_output=True, text=True, timeout=15) + assert version.returncode == 0 and version.stdout.strip() == shipped['Version'] + status = subprocess.run([str(target / executable.name), 'update', 'status', '--json'], env=env, capture_output=True, text=True, timeout=15) + assert status.returncode == (1 if fail else 0) and json.loads(status.stdout)['State'] == state['State'] + assert (job / 'failed-package').exists() if fail else backup.exists() + print('Native updater ' + ('startup failure rollback' if fail else 'replacement and backup') + ' passed.', flush=True) + + +if __name__ == '__main__': + main(sys.argv[1]) diff --git a/src/SidePulse.Cli/Interactive.cs b/src/SidePulse.Cli/Interactive.cs index 48e151b..ea6e74d 100644 --- a/src/SidePulse.Cli/Interactive.cs +++ b/src/SidePulse.Cli/Interactive.cs @@ -15,16 +15,16 @@ public static class Interactive if (args.Length == 1 && args[0] is "about" or "animations" or "agents" or "link" or "host" or "profiles") return [args[0], "--help"]; return args; } - if (args.Length > 1 || args.Length == 1 && args[0] is not ("about" or "animations" or "agents" or "link" or "host" or "profiles")) return args; + if (args.Length > 1 || args.Length == 1 && args[0] is not ("about" or "animations" or "agents" or "link" or "host" or "profiles" or "update")) return args; var group = args.FirstOrDefault(); while (true) { if (group is null) { - var selected = Choose("SidePulse.NET", [new("Animations"), new("Devices", ["devices"]), new("Display state"), new("Agent hooks"), new("Background host"), new("Phone links"), new("Profiles"), new("Diagnostics", ["doctor"]), new("About")]); + var selected = Choose("SidePulse.NET", [new("Animations"), new("Devices", ["devices"]), new("Display state"), new("Agent hooks"), new("Background host"), new("Phone links"), new("Profiles"), new("Diagnostics", ["doctor"]), new("Updates"), new("About")]); if (selected is null) return null; if (selected.Arguments is { } direct) return direct; - group = selected.Label switch { "Animations" => "animations", "Agent hooks" => "agents", "Background host" => "host", "Phone links" => "link", "Profiles" => "profiles", "About" => "about", _ => "state" }; + group = selected.Label switch { "Animations" => "animations", "Agent hooks" => "agents", "Background host" => "host", "Phone links" => "link", "Profiles" => "profiles", "About" => "about", "Updates" => "update", _ => "state" }; } var command = Build(group); if (command is not null) return command; @@ -86,6 +86,16 @@ private static List Target() } private static string[]? Build(string group) { + if (group == "update") + { + var action = Choose("Updates", [new("Check", ["update", "check"]), new("Install"), new("Status", ["update", "status"])]); + if (action is null) return null; + if (action.Arguments is { } direct) return direct; + var command = new List { "update", "install" }; + if (AnsiConsole.Confirm("Include prereleases?", false)) command.Add("--prerelease"); + if (AnsiConsole.Confirm("Preview the update only?", true)) command.Add("--dry-run"); + return Review(command); + } if (group == "about") { var action = Choose("About SidePulse.NET", [new("Overview", ["about", "info"]), new("Manufacturer website", ["about", "website", "--open"]), new("Project on GitHub", ["about", "github", "--open"]), new("Original project", ["about", "upstream", "--open"]), new("Credits", ["about", "credits"]), new("Libraries and licenses", ["about", "licenses"]), new("Documentation", ["docs", "--open"])]); diff --git a/src/SidePulse.Cli/Program.cs b/src/SidePulse.Cli/Program.cs index d082457..a0aba55 100644 --- a/src/SidePulse.Cli/Program.cs +++ b/src/SidePulse.Cli/Program.cs @@ -7,6 +7,8 @@ catch (Exception ex) { return TerminalMode.Error(ex); } if (args.Length == 0) return 0; +if (args.Length == 1 && args[0] == "update") args = ["update", "check"]; + // Preserve the original foreground shorthand while adding lifecycle subcommands. if (args.Length >= 1 && args[0] == "host" && (args.Length == 1 || args[1].StartsWith('-') && args[1] is not "--help" and not "-h")) args = new[] { "host", "run" }.Concat(args.Skip(1)).ToArray(); @@ -16,7 +18,7 @@ { config.ConfigureConsole(AnsiConsole.Console); config.SetApplicationName("sidepulse-net"); - config.SetApplicationVersion("0.1.0-alpha.5"); + config.SetApplicationVersion(ProjectInfo.Version); config.AddBranch("animations", animations => { animations.SetDescription("Create, validate, preview and send Dot / Pro LED patterns."); @@ -43,6 +45,14 @@ about.AddCommand("licenses"); }); config.AddCommand("docs"); + config.AddBranch("update", update => + { + update.SetDescription("Check GitHub releases and install verified self-contained updates."); + update.AddCommand("check"); + update.AddCommand("install"); + update.AddCommand("status"); + }); + config.AddCommand("internal-update").IsHidden(); config.AddBranch("link", links => { links.SetDescription("Pair and manage protected iPhone links."); diff --git a/src/SidePulse.Cli/SidePulse.Cli.csproj b/src/SidePulse.Cli/SidePulse.Cli.csproj index e21c39f..252636b 100644 --- a/src/SidePulse.Cli/SidePulse.Cli.csproj +++ b/src/SidePulse.Cli/SidePulse.Cli.csproj @@ -2,7 +2,7 @@ Exe sidepulse-net - 0.1.0-alpha.5 + 0.1.0-alpha.6 Unofficial SidePulse companion MIT @@ -17,6 +17,7 @@ + diff --git a/src/SidePulse.Cli/Updates.cs b/src/SidePulse.Cli/Updates.cs new file mode 100644 index 0000000..94d6e4d --- /dev/null +++ b/src/SidePulse.Cli/Updates.cs @@ -0,0 +1,155 @@ +using System.Diagnostics; +using System.Text.Json; +using SidePulse.Core; +using Spectre.Console.Cli; + +namespace SidePulse.Cli; + +public sealed class UpdateSettings : CommandSettings +{ + [CommandOption("--prerelease")] public bool Prerelease { get; init; } + [CommandOption("--json")] public bool Json { get; init; } + [CommandOption("--dry-run")] public bool DryRun { get; init; } +} +public static class Updater +{ + public static string Target + { + get + { + var root = Path.GetFullPath(AppContext.BaseDirectory); + if (root == Path.GetPathRoot(root)) throw new IOException("Self-update cannot replace a filesystem root. Move the application into its own directory first."); + return root.TrimEnd(Path.DirectorySeparatorChar); + } + } + public static void Print(UpdateSettings settings, object data, string text) { if (settings.Json) Output.Print(data); else Console.WriteLine(text); } + public static async Task<(AvailableRelease? Release, UpdateCheck Check)> Check(UpdateSettings settings, CancellationToken cancellationToken) + { + using var client = new HttpClient { Timeout = TimeSpan.FromSeconds(30) }; + var release = await new GitHubReleases(client).Latest(settings.Prerelease, cancellationToken); + return (release, GitHubReleases.Check(release, ProjectInfo.Version, GitHubReleases.RuntimeIdentifier)); + } + public static async Task Probe(string target, string version, CancellationToken cancellationToken) + { + var executable = Path.Combine(target, OperatingSystem.IsWindows() ? "sidepulse-net.exe" : "sidepulse-net"); + using var deadline = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); deadline.CancelAfter(TimeSpan.FromSeconds(15)); + var start = new ProcessStartInfo(executable) { UseShellExecute = false, RedirectStandardOutput = true, RedirectStandardError = true, RedirectStandardInput = true, CreateNoWindow = true, WorkingDirectory = target }; + start.ArgumentList.Add("--version"); + using var process = Process.Start(start) ?? throw new IOException("Could not verify the new executable."); + process.StandardInput.Close(); + var output = process.StandardOutput.ReadToEndAsync(deadline.Token); var errors = process.StandardError.ReadToEndAsync(deadline.Token); + try + { + await process.WaitForExitAsync(deadline.Token); + var reported = (await output).Trim(); await errors; + if (process.ExitCode != 0 || reported != version) throw new IOException("The new executable did not report the selected version."); + } + catch { if (!process.HasExited) process.Kill(true); throw; } + } +} +public sealed class UpdateCheckCommand : AsyncCommand +{ + public override async Task ExecuteAsync(CommandContext context, UpdateSettings settings, CancellationToken cancellationToken) + { + var (_, check) = await Updater.Check(settings, cancellationToken); + var message = check.Available ? $"Update available: {check.Current} -> {check.Latest}. Run update install{(settings.Prerelease ? " --prerelease" : "")} to install." + : check.Latest is null ? "No published releases in the selected channel. Preview Actions artifacts are not releases." + : check.Asset is null ? $"Release {check.Latest} has no checksummed package for {check.Runtime}." : $"Up to date ({check.Current})."; + Updater.Print(settings, check, message); return 0; + } +} +public sealed class UpdateInstallCommand : AsyncCommand +{ + public override async Task ExecuteAsync(CommandContext context, UpdateSettings settings, CancellationToken cancellationToken) + { + using var deadline = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); deadline.CancelAfter(TimeSpan.FromMinutes(5)); + var (release, check) = await Updater.Check(settings, deadline.Token); + if (release is null || new ReleaseVersion(release.Version).CompareTo(new(ProjectInfo.Version)) <= 0) + { Updater.Print(settings, check, release is null ? "No published release in the selected channel." : "Already up to date."); return 0; } + if (!check.Available) throw new IOException("The release is missing a package or SHA256SUMS; update refused."); + if (settings.DryRun) { Updater.Print(settings, new { state = "planned", check }, $"Would download, verify and install {check.Asset} ({check.Latest}) into {Updater.Target}."); return 0; } + var installed = InstallationManifest.Read(Updater.Target); + if (installed.Version != ProjectInfo.Version || installed.Runtime != check.Runtime || Path.GetFileName(Environment.ProcessPath) != (OperatingSystem.IsWindows() ? "sidepulse-net.exe" : "sidepulse-net")) throw new IOException("Self-update requires an unmodified self-contained release installation."); + using var gate = UpdateTransaction.Lock(Updater.Target); + if (UpdateTransaction.Status(Updater.Target)?.State is "prepared" or "scheduled" or "applying" or "recovery-required") throw new IOException("An update is pending or needs recovery. Run update status first."); + if ((await HostControl.Request("status", deadline.Token)).Running) throw new IOException("Stop the agent host with 'sidepulse-net host stop' before updating, then restart it after update status reports installed."); + var working = Path.GetFullPath(Environment.CurrentDirectory).TrimEnd(Path.DirectorySeparatorChar); + if (working.Equals(Updater.Target, OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal) || working.StartsWith(Updater.Target + Path.DirectorySeparatorChar, OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal)) throw new IOException("Run the update from outside the installation directory so its folder can be replaced."); + installed.Verify(Updater.Target, false); + var parent = Path.GetDirectoryName(Updater.Target)!; + var job = Path.Combine(parent, ".sidepulse-update-" + Guid.NewGuid().ToString("N")); + if (OperatingSystem.IsWindows()) Directory.CreateDirectory(job); + else Directory.CreateDirectory(job, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute); + UpdatePlan? plan = null; + try + { + using var client = new HttpClient { Timeout = TimeSpan.FromMinutes(5) }; + var archive = await new GitHubReleases(client).Download(release, check.Runtime, job, deadline.Token); + var stage = Path.Combine(job, "stage"); + await UpdatePackage.Extract(archive, stage, release.Version, check.Runtime, deadline.Token); + using var current = Process.GetCurrentProcess(); + plan = UpdateTransaction.Prepare(Updater.Target, stage, job, release.Version, check.Runtime, current.Id, current.StartTime.ToUniversalTime().Ticks); + var helper = Path.Combine(job, "helper", OperatingSystem.IsWindows() ? "sidepulse-net.exe" : "sidepulse-net"); + var start = new ProcessStartInfo(helper) { UseShellExecute = OperatingSystem.IsWindows(), WindowStyle = ProcessWindowStyle.Hidden, CreateNoWindow = true, + RedirectStandardInput = !OperatingSystem.IsWindows(), RedirectStandardOutput = !OperatingSystem.IsWindows(), RedirectStandardError = !OperatingSystem.IsWindows(), WorkingDirectory = job }; + foreach (var argument in new[] { "internal-update", "--plan", Path.Combine(job, "plan.json") }) start.ArgumentList.Add(argument); + UpdateTransaction.Receipt(plan, "scheduled"); + using var process = Process.Start(start) ?? throw new IOException("Could not launch the update helper."); + if (!OperatingSystem.IsWindows()) process.StandardInput.Close(); + Updater.Print(settings, new { state = "scheduled", version = plan.Version, receipt = plan.Receipt, backup = plan.Backup }, "Verified update scheduled. It will apply after this command exits. Run 'sidepulse-net update status' to confirm before restarting the host."); + return 0; + } + catch + { + if (plan is not null) UpdateTransaction.Receipt(plan, "failed", "Update preparation or helper launch failed; installation was not changed."); + else Directory.Delete(job, true); + throw; + } + } +} +public sealed class UpdateStatusCommand : Command +{ + public override int Execute(CommandContext context, UpdateSettings settings, CancellationToken cancellationToken) + { + var status = UpdateTransaction.Status(Updater.Target); + Updater.Print(settings, (object?)status ?? new { state = "none" }, status is null ? "No recorded update for this installation." : $"{status.State}: {status.Version}\nBackup: {status.Backup}\nWorkspace: {status.Job}" + (status.Error is null ? "" : "\n" + status.Error)); + return status?.State is "failed" or "recovery-required" ? 1 : 0; + } +} +public sealed class ApplyUpdateSettings : CommandSettings +{ + [CommandOption("--plan ")] public string Plan { get; init; } = ""; +} +public sealed class ApplyUpdateCommand : AsyncCommand +{ + public override async Task ExecuteAsync(CommandContext context, ApplyUpdateSettings settings, CancellationToken cancellationToken) + { + UpdatePlan? plan = null; + try + { + if (!OperatingSystem.IsWindows()) HostLogs.Detach(); + plan = JsonSerializer.Deserialize(await File.ReadAllTextAsync(settings.Plan, cancellationToken), InstallationManifest.Json) ?? throw new IOException("Missing update plan."); + UpdateTransaction.Validate(plan); + if (Path.GetFullPath(settings.Plan) != Path.Combine(plan.Job, "plan.json") || Updater.Target != Path.Combine(plan.Job, "helper")) throw new IOException("Update helpers must run from their prepared workspace."); + using var deadline = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); deadline.CancelAfter(TimeSpan.FromSeconds(60)); + try + { + using var parent = Process.GetProcessById(plan.ParentId); + if (parent.StartTime.ToUniversalTime().Ticks == plan.ParentStartTicks) await parent.WaitForExitAsync(deadline.Token); + } + catch (ArgumentException) { /* Parent already exited. No PID is ever killed. */ } + await UpdateTransaction.Apply(plan, (target, token) => Updater.Probe(target, plan.Version, token), deadline.Token); + return 0; + } + catch (Exception) + { + if (plan is not null) + { + UpdateTransaction.Validate(plan); + var existing = UpdateTransaction.Status(plan.Target); + if (existing?.State is not ("failed" or "recovery-required")) UpdateTransaction.Receipt(plan, "failed", "Update helper failed before replacement; check workspace permissions and update status. The backup is retained when present."); + } + return 1; + } + } +} diff --git a/src/SidePulse.Core/Releases.cs b/src/SidePulse.Core/Releases.cs new file mode 100644 index 0000000..2970bb7 --- /dev/null +++ b/src/SidePulse.Core/Releases.cs @@ -0,0 +1,161 @@ +using System.Globalization; +using System.Net; +using System.Numerics; +using System.Runtime.InteropServices; +using System.Security.Cryptography; +using System.Text.Json; +using System.Text.RegularExpressions; + +namespace SidePulse.Core; + +public sealed record ReleaseVersion : IComparable +{ + public string Text { get; } + private readonly BigInteger[] numbers; + private readonly string[] pre; + public bool IsPrerelease => pre.Length != 0; + public ReleaseVersion(string text) + { + var match = Regex.Match(text, @"^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?(?:\+([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?$", RegexOptions.CultureInvariant); + if (!match.Success || text.Length > 128) throw new ArgumentException("Expected a semantic version such as 1.2.3 or 1.2.3-beta.1."); + Text = text; + numbers = Enumerable.Range(1, 3).Select(i => BigInteger.Parse(match.Groups[i].Value, CultureInfo.InvariantCulture)).ToArray(); + pre = match.Groups[4].Success ? match.Groups[4].Value.Split('.') : []; + if (pre.Any(p => p.All(char.IsAsciiDigit) && p.Length > 1 && p[0] == '0')) throw new ArgumentException("Numeric prerelease identifiers cannot have leading zeroes."); + } + public int CompareTo(ReleaseVersion? other) + { + if (other is null) return 1; + for (var i = 0; i < 3; i++) { var result = numbers[i].CompareTo(other.numbers[i]); if (result != 0) return result; } + if (pre.Length == 0 || other.pre.Length == 0) return pre.Length == other.pre.Length ? 0 : pre.Length == 0 ? 1 : -1; + for (var i = 0; i < Math.Min(pre.Length, other.pre.Length); i++) + { + var leftNumeric = pre[i].All(char.IsAsciiDigit); var rightNumeric = other.pre[i].All(char.IsAsciiDigit); + var result = leftNumeric && rightNumeric ? BigInteger.Parse(pre[i], CultureInfo.InvariantCulture).CompareTo(BigInteger.Parse(other.pre[i], CultureInfo.InvariantCulture)) + : leftNumeric != rightNumeric ? leftNumeric ? -1 : 1 : string.CompareOrdinal(pre[i], other.pre[i]); + if (result != 0) return result; + } + return pre.Length.CompareTo(other.pre.Length); + } + public override string ToString() => Text; +} +public sealed record ReleaseAsset(string Name, long Size, string? Digest); +public sealed record AvailableRelease(string Tag, string Version, bool Prerelease, string Url, IReadOnlyList Assets); +public sealed record UpdateCheck(string Current, string? Latest, string Runtime, bool Available, string? Url, string? Asset); + +public sealed class GitHubReleases(HttpClient client) +{ + public const string Repository = "Anheledir/SidePulse.NET"; + public const string ChecksumsName = "SHA256SUMS"; + public const long MaximumArchiveBytes = 512L * 1024 * 1024; + public static string RuntimeIdentifier => (OperatingSystem.IsWindows() ? "win" : OperatingSystem.IsMacOS() ? "osx" : OperatingSystem.IsLinux() ? "linux" : throw new PlatformNotSupportedException("Self-update supports Windows, macOS and Linux.")) + "-" + (RuntimeInformation.ProcessArchitecture switch { Architecture.X64 => "x64", Architecture.Arm64 => "arm64", _ => throw new PlatformNotSupportedException("Self-update supports x64 and ARM64.") }); + public static string AssetName(string runtime) => "sidepulse-net-" + runtime + (runtime.StartsWith("win-", StringComparison.Ordinal) ? ".zip" : ".tar.gz"); + private async Task Get(Uri uri, CancellationToken cancellationToken) + { + using var request = new HttpRequestMessage(HttpMethod.Get, uri); + request.Headers.UserAgent.ParseAdd("SidePulse.NET-updater/1.0"); + request.Headers.Accept.ParseAdd(uri.Host == "api.github.com" ? "application/vnd.github+json" : "application/octet-stream"); + if (uri.Host == "api.github.com") request.Headers.Add("X-GitHub-Api-Version", "2022-11-28"); + var response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken); + if (response.StatusCode is HttpStatusCode.Forbidden or HttpStatusCode.TooManyRequests) { response.Dispose(); throw new IOException("GitHub rate limit or access restriction. Try again later."); } + return response; + } + public async Task Latest(bool includePrerelease, CancellationToken cancellationToken = default) + { + if (!includePrerelease) + { + using var response = await Get(new($"https://api.github.com/repos/{Repository}/releases/latest"), cancellationToken); + if (response.StatusCode == HttpStatusCode.NotFound) return null; + response.EnsureSuccessStatusCode(); + using var json = JsonDocument.Parse(await ReadBounded(response, 4 * 1024 * 1024, cancellationToken)); + return Parse(json.RootElement, false); + } + AvailableRelease? best = null; + for (var page = 1; page <= 10; page++) + { + using var response = await Get(new($"https://api.github.com/repos/{Repository}/releases?per_page=100&page={page}"), cancellationToken); + response.EnsureSuccessStatusCode(); + using var json = JsonDocument.Parse(await ReadBounded(response, 8 * 1024 * 1024, cancellationToken)); + foreach (var element in json.RootElement.EnumerateArray()) + { + var candidate = Parse(element, true); + if (candidate is not null && (best is null || new ReleaseVersion(candidate.Version).CompareTo(new(best.Version)) > 0)) best = candidate; + } + if (json.RootElement.GetArrayLength() < 100) return best; + } + throw new IOException("Release history exceeded the bounded lookup. Check the GitHub releases page manually."); + } + private static AvailableRelease? Parse(JsonElement value, bool includePrerelease) + { + if (value.GetProperty("draft").GetBoolean()) return null; + var tag = value.GetProperty("tag_name").GetString() ?? ""; + var version = tag.StartsWith('v') ? tag[1..] : tag; + ReleaseVersion semantic; + try { semantic = new(version); } catch (ArgumentException) { return null; } + var prerelease = value.GetProperty("prerelease").GetBoolean() || semantic.IsPrerelease; + if (prerelease && !includePrerelease) return null; + var assets = value.GetProperty("assets").EnumerateArray().Select(a => new ReleaseAsset(a.GetProperty("name").GetString()!, a.GetProperty("size").GetInt64(), a.TryGetProperty("digest", out var digest) ? digest.GetString() : null)).ToArray(); + return new(tag, semantic.Text, prerelease, $"https://github.com/{Repository}/releases/tag/{Uri.EscapeDataString(tag)}", assets); + } + public static UpdateCheck Check(AvailableRelease? release, string current, string runtime) + { + var newer = release is not null && new ReleaseVersion(release.Version).CompareTo(new(current)) > 0; + var name = AssetName(runtime); + var supported = release?.Assets.Count(a => a.Name == name) == 1 && release.Assets.Count(a => a.Name == ChecksumsName) == 1; + return new(current, release?.Version, runtime, newer && supported, release?.Url, supported ? name : null); + } + public async Task Download(AvailableRelease release, string runtime, string directory, CancellationToken cancellationToken = default) + { + var name = AssetName(runtime); + var archive = release.Assets.SingleOrDefault(a => a.Name == name) ?? throw new IOException("The release has no package for this runtime."); + var sums = release.Assets.SingleOrDefault(a => a.Name == ChecksumsName) ?? throw new IOException("The release has no SHA256SUMS asset; update refused."); + if (archive.Size is <= 0 or > MaximumArchiveBytes || sums.Size is <= 0 or > 65536) throw new IOException("Release asset size is outside the supported limits."); + using var sumResponse = await Get(AssetUri(release, sums.Name), cancellationToken); + sumResponse.EnsureSuccessStatusCode(); + var sumBytes = await ReadBounded(sumResponse, 65536, cancellationToken); + VerifyDigest(sumBytes, sums.Digest); + var expected = Checksum(System.Text.Encoding.UTF8.GetString(sumBytes), name); + Directory.CreateDirectory(directory); + var destination = Path.Combine(directory, name); + try + { + using var response = await Get(AssetUri(release, name), cancellationToken); + response.EnsureSuccessStatusCode(); + await using (var source = await response.Content.ReadAsStreamAsync(cancellationToken)) + await using (var file = new FileStream(destination, FileMode.CreateNew, FileAccess.Write, FileShare.None)) + { await CopyBounded(source, file, MaximumArchiveBytes, cancellationToken); } + if (new FileInfo(destination).Length != archive.Size) throw new IOException("Download length does not match the release metadata."); + var hash = InstallationManifest.Hash(destination); + if (!hash.Equals(expected, StringComparison.OrdinalIgnoreCase) || archive.Digest is { } digest && !digest.Equals("sha256:" + hash, StringComparison.OrdinalIgnoreCase)) throw new IOException("SHA-256 verification failed; installation was not changed."); + return destination; + } + catch { File.Delete(destination); throw; } + } + private static Uri AssetUri(AvailableRelease release, string asset) => new($"https://github.com/{Repository}/releases/download/{Uri.EscapeDataString(release.Tag)}/{Uri.EscapeDataString(asset)}"); + public static string Checksum(string text, string filename) + { + var matches = text.Replace("\r\n", "\n").Split('\n').Select(line => Regex.Match(line, @"^([a-fA-F0-9]{64}) [ *]([^\r\n]+)$")).Where(m => m.Success && m.Groups[2].Value == filename).ToArray(); + if (matches.Length != 1) throw new IOException("SHA256SUMS must contain exactly one SHA-256 for the selected package."); + return matches[0].Groups[1].Value; + } + private static void VerifyDigest(byte[] bytes, string? digest) + { + if (digest is not null && !digest.Equals("sha256:" + Convert.ToHexString(SHA256.HashData(bytes)), StringComparison.OrdinalIgnoreCase)) throw new IOException("Release checksum-file digest did not match."); + } + private static async Task ReadBounded(HttpResponseMessage response, long maximum, CancellationToken cancellationToken) + { + using var buffer = new MemoryStream(); + await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken); + await CopyBounded(stream, buffer, maximum, cancellationToken); return buffer.ToArray(); + } + public static async Task CopyBounded(Stream source, Stream destination, long maximum, CancellationToken cancellationToken = default) + { + var buffer = new byte[65536]; long total = 0; + while (true) + { + var read = await source.ReadAsync(buffer, cancellationToken); if (read == 0) break; + total += read; if (total > maximum) throw new IOException("Download or extracted file exceeds its size limit."); + await destination.WriteAsync(buffer.AsMemory(0, read), cancellationToken); + } + } +} diff --git a/src/SidePulse.Core/UpdatePackage.cs b/src/SidePulse.Core/UpdatePackage.cs new file mode 100644 index 0000000..15dd185 --- /dev/null +++ b/src/SidePulse.Core/UpdatePackage.cs @@ -0,0 +1,115 @@ +using System.Formats.Tar; +using System.IO.Compression; +using System.Security.Cryptography; +using System.Text.Json; +using System.Text.RegularExpressions; + +namespace SidePulse.Core; + +public sealed record InstalledFile(string Path, string Sha256, int Mode); +public sealed record InstallationManifest(int Format, string Version, string Runtime, IReadOnlyList Files) +{ + public const string Filename = "sidepulse-install.json"; + public static readonly JsonSerializerOptions Json = new() { WriteIndented = true, PropertyNameCaseInsensitive = true }; + public static string Hash(string path) { using var stream = File.OpenRead(path); return Convert.ToHexString(SHA256.HashData(stream)); } + public static string Relative(string path) + { + if (string.IsNullOrEmpty(path) || path.Length > 240 || path.Contains('\\') || path.Contains(':') || path.StartsWith('/') || path.Split('/').Any(p => p is "" or "." or ".." || p.EndsWith(' ') || p.EndsWith('.')) || path.Any(char.IsControl)) throw new IOException("Unsafe path in update package."); + return path; + } + public static string Resolve(string directory, string path) => System.IO.Path.Combine(directory, Relative(path).Replace('/', System.IO.Path.DirectorySeparatorChar)); + public static InstallationManifest Read(string directory) + { + var path = System.IO.Path.Combine(directory, Filename); + if (!File.Exists(path) || new FileInfo(path).Length > 4 * 1024 * 1024) throw new IOException("This installation has no supported update manifest. Install a current self-contained preview/release manually first."); + var manifest = JsonSerializer.Deserialize(File.ReadAllText(path), Json) ?? throw new IOException("Invalid installation manifest."); + _ = new ReleaseVersion(manifest.Version); + if (manifest.Format != 1 || manifest.Runtime is not ("win-x64" or "win-arm64" or "osx-x64" or "osx-arm64" or "linux-x64" or "linux-arm64") || manifest.Files is null || manifest.Files.Count is < 1 or > 10000) throw new IOException("Invalid installation manifest."); + var names = new HashSet(StringComparer.OrdinalIgnoreCase); + foreach (var file in manifest.Files) + { + Relative(file.Path); + if (file.Path.Equals(Filename, StringComparison.OrdinalIgnoreCase) || !names.Add(file.Path) || !Regex.IsMatch(file.Sha256, "^[0-9a-fA-F]{64}$", RegexOptions.CultureInvariant) || file.Mode is < 0 or > 511) throw new IOException("Invalid installation file entry."); + } + var exe = manifest.Runtime.StartsWith("win-", StringComparison.Ordinal) ? "sidepulse-net.exe" : "sidepulse-net"; + if (!names.Contains(exe) || !names.Contains("sidepulse-net.dll") || !names.Contains(manifest.Runtime.StartsWith("win-", StringComparison.Ordinal) ? "hostfxr.dll" : manifest.Runtime.StartsWith("osx-", StringComparison.Ordinal) ? "libhostfxr.dylib" : "libhostfxr.so")) throw new IOException("Self-update requires a complete self-contained application package."); + return manifest; + } + public void Verify(string directory, bool rejectExtras) + { + foreach (var file in Files) + { + var path = Resolve(directory, file.Path); + if (!File.Exists(path) || (File.GetAttributes(path) & FileAttributes.ReparsePoint) != 0 || !Hash(path).Equals(file.Sha256, StringComparison.OrdinalIgnoreCase)) throw new IOException("An installed or staged file failed verification: " + file.Path); + } + var owned = Files.Select(f => f.Path).Append(Filename).ToHashSet(StringComparer.OrdinalIgnoreCase); + foreach (var path in RegularFiles(directory)) + if (rejectExtras && !owned.Contains(System.IO.Path.GetRelativePath(directory, path).Replace('\\', '/'))) throw new IOException("The staged package contains files not listed in its manifest."); + } + public static IEnumerable RegularFiles(string directory) + { + if ((File.GetAttributes(directory) & FileAttributes.ReparsePoint) != 0) throw new IOException("Update directories cannot be symbolic links."); + foreach (var path in Directory.EnumerateFileSystemEntries(directory)) + { + var attributes = File.GetAttributes(path); + if ((attributes & FileAttributes.ReparsePoint) != 0) throw new IOException("Symbolic links are not supported in an updated installation."); + if ((attributes & FileAttributes.Directory) != 0) foreach (var child in RegularFiles(path)) yield return child; + else yield return path; + } + } +} + +public static class UpdatePackage +{ + public static async Task Extract(string archive, string destination, string version, string runtime, CancellationToken cancellationToken = default) + { + if (Directory.Exists(destination)) throw new IOException("Update staging directory already exists."); + Directory.CreateDirectory(destination); + var names = new HashSet(StringComparer.OrdinalIgnoreCase); + long total = 0; var count = 0; + async Task ExtractFile(string name, long length, Stream source) + { + name = InstallationManifest.Relative(name); + if (++count > 10000 || length < 0 || length > 512L * 1024 * 1024 || (total += length) > 1024L * 1024 * 1024 || !names.Add(name)) throw new IOException("Update archive exceeds its limits or contains duplicate paths."); + var path = InstallationManifest.Resolve(destination, name); + Directory.CreateDirectory(Path.GetDirectoryName(path)!); + await using var output = new FileStream(path, FileMode.CreateNew, FileAccess.Write, FileShare.None); + await GitHubReleases.CopyBounded(source, output, length, cancellationToken); + if (output.Length != length) throw new IOException("Extracted file length did not match the archive."); + } + try + { + if (archive.EndsWith(".zip", StringComparison.OrdinalIgnoreCase)) + { + using var zip = ZipFile.OpenRead(archive); + foreach (var entry in zip.Entries) + { + var kind = (entry.ExternalAttributes >> 16) & 0xf000; + if (kind is not (0 or 0x8000 or 0x4000)) throw new IOException("Links and special files are not allowed in update archives."); + if (entry.FullName.EndsWith('/')) { InstallationManifest.Relative(entry.FullName.TrimEnd('/')); continue; } + await using var stream = entry.Open(); await ExtractFile(entry.FullName, entry.Length, stream); + } + } + else if (archive.EndsWith(".tar.gz", StringComparison.OrdinalIgnoreCase)) + { + await using var input = File.OpenRead(archive); + await using var gzip = new GZipStream(input, CompressionMode.Decompress); + await using var reader = new TarReader(gzip); + while (await reader.GetNextEntryAsync(cancellationToken: cancellationToken) is { } entry) + { + var name = entry.Name.StartsWith("./", StringComparison.Ordinal) ? entry.Name[2..] : entry.Name; + if (entry.EntryType == TarEntryType.Directory) { if (name is not ("" or ".")) InstallationManifest.Relative(name.TrimEnd('/')); continue; } + if (entry.EntryType is not (TarEntryType.RegularFile or TarEntryType.V7RegularFile)) throw new IOException("Links and special files are not allowed in update archives."); + await ExtractFile(name, entry.Length, entry.DataStream ?? Stream.Null); + } + } + else throw new IOException("Unsupported update archive format."); + var manifest = InstallationManifest.Read(destination); + if (manifest.Version != version || manifest.Runtime != runtime) throw new IOException("Package version or runtime does not match the selected release."); + manifest.Verify(destination, true); + if (!OperatingSystem.IsWindows()) foreach (var file in manifest.Files) File.SetUnixFileMode(InstallationManifest.Resolve(destination, file.Path), (UnixFileMode)file.Mode); + return manifest; + } + catch { Directory.Delete(destination, true); throw; } + } +} diff --git a/src/SidePulse.Core/UpdateTransaction.cs b/src/SidePulse.Core/UpdateTransaction.cs new file mode 100644 index 0000000..39e1834 --- /dev/null +++ b/src/SidePulse.Core/UpdateTransaction.cs @@ -0,0 +1,112 @@ +using System.Security.Cryptography; +using System.Text; +using System.Text.Json; + +namespace SidePulse.Core; + +public sealed record UpdatePlan(string Target, string Stage, string Backup, string Job, string Receipt, string ExpectedManifestHash, string Version, string Runtime, int ParentId, long ParentStartTicks); +public sealed record UpdateReceipt(string State, string Version, string Target, string Backup, string Job, string? Error = null); +public static class UpdateTransaction +{ + public static string TargetKey(string target) + { + var path = Path.GetFullPath(target).TrimEnd(Path.DirectorySeparatorChar); + if (OperatingSystem.IsWindows()) path = path.ToUpperInvariant(); + return Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(path)))[..24]; + } + public static string ReceiptPath(string target) => Path.Combine(Path.GetDirectoryName(LinkStore.DefaultPath)!, "updates", TargetKey(target) + ".json"); + public static UpdateReceipt? Status(string target) + { + var path = ReceiptPath(target); + if (!File.Exists(path)) return null; + return JsonSerializer.Deserialize(File.ReadAllText(path), InstallationManifest.Json) ?? throw new IOException("Invalid update receipt."); + } + public static void Receipt(UpdatePlan plan, string state, string? error = null) + { + Directory.CreateDirectory(Path.GetDirectoryName(plan.Receipt)!); + AnimationLibrary.WriteFile(plan.Receipt, JsonSerializer.Serialize(new UpdateReceipt(state, plan.Version, plan.Target, plan.Backup, plan.Job, error), InstallationManifest.Json) + "\n", true); + } + public static FileStream Lock(string target) + { + var path = Path.Combine(Path.GetDirectoryName(Path.GetFullPath(target).TrimEnd(Path.DirectorySeparatorChar))!, ".sidepulse-update-" + TargetKey(target) + ".lock"); + return new(path, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None); + } + public static UpdatePlan Prepare(string target, string stage, string job, string version, string runtime, int parentId, long parentStartTicks) + { + target = Path.GetFullPath(target).TrimEnd(Path.DirectorySeparatorChar); + stage = Path.GetFullPath(stage); job = Path.GetFullPath(job); + var current = InstallationManifest.Read(target); + if (current.Runtime != runtime) throw new IOException("Current installation runtime does not match this process."); + current.Verify(target, false); + var next = InstallationManifest.Read(stage); + if (next.Version != version || next.Runtime != runtime) throw new IOException("Staged installation does not match the release."); + next.Verify(stage, true); + var plan = new UpdatePlan(target, stage, target + ".backup-" + Guid.NewGuid().ToString("N"), job, ReceiptPath(target), InstallationManifest.Hash(Path.Combine(target, InstallationManifest.Filename)), version, runtime, parentId, parentStartTicks); + Validate(plan); + // Preserve user-added files, but never overwrite one with a newly owned package path. + var oldFiles = current.Files.Select(f => f.Path).Append(InstallationManifest.Filename).ToHashSet(StringComparer.OrdinalIgnoreCase); + var nextFiles = next.Files.Select(f => f.Path).Append(InstallationManifest.Filename).ToHashSet(StringComparer.OrdinalIgnoreCase); + foreach (var path in InstallationManifest.RegularFiles(target)) + { + var relative = Path.GetRelativePath(target, path).Replace('\\', '/'); + if (oldFiles.Contains(relative)) continue; + if (nextFiles.Contains(relative)) throw new IOException("A new application file would overwrite a user-added file: " + relative); + var destination = InstallationManifest.Resolve(stage, relative); + Directory.CreateDirectory(Path.GetDirectoryName(destination)!); File.Copy(path, destination, false); + } + var helper = Path.Combine(job, "helper"); + Directory.CreateDirectory(helper); + foreach (var file in current.Files) + { + var destination = InstallationManifest.Resolve(helper, file.Path); + Directory.CreateDirectory(Path.GetDirectoryName(destination)!); + File.Copy(InstallationManifest.Resolve(target, file.Path), destination, false); + if (!OperatingSystem.IsWindows()) File.SetUnixFileMode(destination, (UnixFileMode)file.Mode); + } + File.Copy(Path.Combine(target, InstallationManifest.Filename), Path.Combine(helper, InstallationManifest.Filename)); + current.Verify(helper, true); + AnimationLibrary.WriteFile(Path.Combine(job, "plan.json"), JsonSerializer.Serialize(plan, InstallationManifest.Json) + "\n", false); + Receipt(plan, "prepared"); + return plan; + } + public static void Validate(UpdatePlan plan) + { + foreach (var path in new[] { plan.Target, plan.Stage, plan.Backup, plan.Job, plan.Receipt }) if (!Path.IsPathFullyQualified(path)) throw new IOException("Update plan paths must be absolute."); + var parent = Path.GetDirectoryName(plan.Target); + if (string.IsNullOrEmpty(parent) || plan.Target == plan.Job || plan.Target == Path.GetPathRoot(plan.Target) || Path.GetDirectoryName(plan.Job) != parent || Path.GetDirectoryName(plan.Backup) != parent + || plan.Stage != Path.Combine(plan.Job, "stage") || !Path.GetFileName(plan.Job).StartsWith(".sidepulse-update-", StringComparison.Ordinal) + || !plan.Backup.StartsWith(plan.Target + ".backup-", StringComparison.Ordinal) || plan.Receipt != ReceiptPath(plan.Target)) throw new IOException("Invalid update plan layout."); + _ = new ReleaseVersion(plan.Version); + } + public static async Task Apply(UpdatePlan plan, Func probe, CancellationToken cancellationToken = default) + { + Validate(plan); + using var gate = Lock(plan.Target); + if (Directory.Exists(plan.Backup)) throw new IOException("The update backup path already exists."); + if (InstallationManifest.Hash(Path.Combine(plan.Target, InstallationManifest.Filename)) != plan.ExpectedManifestHash) throw new IOException("Installation changed since update preparation."); + var current = InstallationManifest.Read(plan.Target); current.Verify(plan.Target, false); + var next = InstallationManifest.Read(plan.Stage); + if (next.Version != plan.Version || next.Runtime != plan.Runtime) throw new IOException("Staged version/runtime changed."); + next.Verify(plan.Stage, false); + var movedOld = false; var movedNew = false; + try + { + Receipt(plan, "applying"); + Directory.Move(plan.Target, plan.Backup); movedOld = true; + Directory.Move(plan.Stage, plan.Target); movedNew = true; + await probe(plan.Target, cancellationToken); + Receipt(plan, "installed"); + } + catch (Exception) + { + try + { + if (movedNew) Directory.Move(plan.Target, Path.Combine(plan.Job, "failed-package")); + if (movedOld) Directory.Move(plan.Backup, plan.Target); + Receipt(plan, "failed", "Replacement or startup verification failed; the previous installation was restored. Check that no agent host or other process is using the installation."); + } + catch (Exception) { Receipt(plan, "recovery-required", "Automatic rollback failed. Restore the backup directory manually; it has not been deleted."); } + throw; + } + } +} diff --git a/tests/SidePulse.Tests/UpdateTests.cs b/tests/SidePulse.Tests/UpdateTests.cs new file mode 100644 index 0000000..ee78234 --- /dev/null +++ b/tests/SidePulse.Tests/UpdateTests.cs @@ -0,0 +1,211 @@ +using System.Formats.Tar; +using System.IO.Compression; +using System.Net; +using System.Security.Cryptography; +using System.Text; +using System.Text.Json; +using SidePulse.Core; +using Xunit; + +namespace SidePulse.Tests; + +public sealed class UpdateTests +{ + [Theory] + [InlineData("1.0.0-alpha.9", "1.0.0-alpha.10")] + [InlineData("1.0.0-alpha", "1.0.0-alpha.1")] + [InlineData("1.0.0-1", "1.0.0-alpha")] + [InlineData("1.0.0-rc.1", "1.0.0")] + [InlineData("1.9.0", "1.10.0")] + [InlineData("9.0.0", "10.0.0")] + public void VersionsUseSemanticPrecedence(string older, string newer) => Assert.True(new ReleaseVersion(older).CompareTo(new(newer)) < 0); + [Theory] + [InlineData("v1.0.0")] + [InlineData("1.0")] + [InlineData("01.0.0")] + [InlineData("1.0.0-beta.01")] + [InlineData("1.0.0-../../")] + public void InvalidVersionsAreRejected(string version) => Assert.Throws(() => new ReleaseVersion(version)); + [Fact] + public void BuildMetadataDoesNotAffectPrecedence() => Assert.Equal(0, new ReleaseVersion("1.2.3+one").CompareTo(new("1.2.3+two"))); + [Fact] + public async Task EmptyStableChannelIsNormalAndPublicChecksDoNotSendCredentials() + { + var handler = new Handler(request => + { + Assert.Equal("api.github.com", request.RequestUri!.Host); + Assert.Null(request.Headers.Authorization); + Assert.NotEmpty(request.Headers.UserAgent); + return new(HttpStatusCode.NotFound); + }); + using var client = new HttpClient(handler); + Assert.Null(await new GitHubReleases(client).Latest(false)); + } + [Fact] + public async Task PrereleaseSelectionIgnoresDraftsInvalidTagsAndUsesSemanticOrder() + { + var payload = JsonSerializer.Serialize(new[] { Release("v0.2.0-alpha.9"), Release("v0.2.0-alpha.10"), Release("v9.0.0", true), Release("nonsense"), Release("v0.1.0", false, false) }); + using var client = new HttpClient(new Handler(_ => Json(payload))); + var latest = await new GitHubReleases(client).Latest(true); + Assert.Equal("0.2.0-alpha.10", latest!.Version); + Assert.True(GitHubReleases.Check(latest, "0.1.0", "linux-x64").Available); + Assert.False(GitHubReleases.Check(latest, "0.3.0", "linux-x64").Available); + } + [Fact] + public async Task RateLimitFailsClearly() + { + using var client = new HttpClient(new Handler(_ => new(HttpStatusCode.TooManyRequests))); + var error = await Assert.ThrowsAsync(() => new GitHubReleases(client).Latest(false)); + Assert.Contains("rate limit", error.Message); + } + [Fact] + public async Task HashVerificationPrecedesExtractionAndRejectsCorruption() + { + using var temp = new Temp(); + var bytes = Encoding.UTF8.GetBytes("not really a zip; hash verification is independent"); + var asset = "sidepulse-net-win-x64.zip"; + var digest = Convert.ToHexString(SHA256.HashData(bytes)); + var checksum = Encoding.UTF8.GetBytes(digest + " " + asset + "\n"); + var corrupt = false; + using var client = new HttpClient(new Handler(request => + { + Assert.Equal("github.com", request.RequestUri!.Host); + Assert.StartsWith("/Anheledir/SidePulse.NET/releases/download/v1.0.0/", request.RequestUri.AbsolutePath); + return new(HttpStatusCode.OK) { Content = new ByteArrayContent(request.RequestUri.AbsolutePath.EndsWith("SHA256SUMS", StringComparison.Ordinal) ? checksum : corrupt ? Encoding.UTF8.GetBytes(new string('x', bytes.Length)) : bytes) }; + })); + var release = new AvailableRelease("v1.0.0", "1.0.0", false, "ignored", [new(asset, bytes.Length, "sha256:" + digest), new("SHA256SUMS", checksum.Length, "sha256:" + Convert.ToHexString(SHA256.HashData(checksum)))]); + var path = await new GitHubReleases(client).Download(release, "win-x64", temp.Path); + Assert.Equal(bytes, File.ReadAllBytes(path)); File.Delete(path); + corrupt = true; + await Assert.ThrowsAsync(() => new GitHubReleases(client).Download(release, "win-x64", temp.Path)); + Assert.False(File.Exists(path)); + } + [Fact] + public void MissingOrAmbiguousChecksumIsRefused() + { + var hash = new string('a', 64); + Assert.Throws(() => GitHubReleases.Checksum(hash + " other.zip\n", "package.zip")); + Assert.Throws(() => GitHubReleases.Checksum(hash + " package.zip\n" + hash + " *package.zip\n", "package.zip")); + Assert.Equal(hash, GitHubReleases.Checksum(hash + " *package.zip\r\n", "package.zip")); + } + [Theory] + [InlineData("../escaped.txt")] + [InlineData("/absolute.txt")] + [InlineData("C:/absolute.txt")] + [InlineData("sub\\escaped.txt")] + [InlineData("sub/../escaped.txt")] + public async Task ArchivePathsCannotEscapeStaging(string path) + { + using var temp = new Temp(); var archive = System.IO.Path.Combine(temp.Path, "bad.zip"); + using (var zip = ZipFile.Open(archive, ZipArchiveMode.Create)) { using var writer = new StreamWriter(zip.CreateEntry(path).Open()); writer.Write("bad"); } + var stage = System.IO.Path.Combine(temp.Path, "stage"); + await Assert.ThrowsAsync(() => UpdatePackage.Extract(archive, stage, "1.0.0", "linux-x64")); + Assert.False(Directory.Exists(stage)); + Assert.False(File.Exists(System.IO.Path.Combine(temp.Path, "escaped.txt"))); + } + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task ValidArchivesExtractAndVerifyTheirManifest(bool tarFormat) + { + using var fixture = new Installation(); + using var temp = new Temp(); + var archive = System.IO.Path.Combine(temp.Path, tarFormat ? "valid.tar.gz" : "valid.zip"); + if (tarFormat) + { + using var output = File.Create(archive); + using var gzip = new GZipStream(output, CompressionMode.Compress); + TarFile.CreateFromDirectory(fixture.Stage, gzip, false); + } + else ZipFile.CreateFromDirectory(fixture.Stage, archive); + var destination = System.IO.Path.Combine(temp.Path, "extracted"); + var manifest = await UpdatePackage.Extract(archive, destination, "2.0.0", "linux-x64"); + manifest.Verify(destination, true); + Assert.Equal("2.0.0", manifest.Version); + Assert.True(File.Exists(System.IO.Path.Combine(destination, "sidepulse-net"))); + } + [Fact] + public async Task TarLinksAreRejected() + { + using var temp = new Temp(); var archive = System.IO.Path.Combine(temp.Path, "bad.tar.gz"); + using (var output = File.Create(archive)) using (var gzip = new GZipStream(output, CompressionMode.Compress)) using (var tar = new TarWriter(gzip)) tar.WriteEntry(new PaxTarEntry(TarEntryType.SymbolicLink, "link") { LinkName = "../outside" }); + await Assert.ThrowsAsync(() => UpdatePackage.Extract(archive, System.IO.Path.Combine(temp.Path, "stage"), "1.0.0", "linux-x64")); + } + [Fact] + public async Task SuccessfulSwapKeepsBackupAndUserAddedFiles() + { + using var fixture = new Installation(); + File.WriteAllText(System.IO.Path.Combine(fixture.Target, "personal.txt"), "keep me"); + var plan = fixture.Prepare(); + await UpdateTransaction.Apply(plan, (target, _) => { Assert.Equal("2.0.0", InstallationManifest.Read(target).Version); return Task.CompletedTask; }); + Assert.Equal("keep me", File.ReadAllText(System.IO.Path.Combine(fixture.Target, "personal.txt"))); + Assert.Equal("1.0.0", InstallationManifest.Read(plan.Backup).Version); + Assert.Equal("installed", UpdateTransaction.Status(fixture.Target)!.State); + } + [Fact] + public async Task FailedStartupProbeRestoresOriginalBytes() + { + using var fixture = new Installation(); var plan = fixture.Prepare(); + await Assert.ThrowsAsync(() => UpdateTransaction.Apply(plan, (_, _) => throw new IOException("simulated bad new executable"))); + Assert.Equal("1.0.0", InstallationManifest.Read(fixture.Target).Version); + Assert.Equal("failed", UpdateTransaction.Status(fixture.Target)!.State); + Assert.True(Directory.Exists(System.IO.Path.Combine(plan.Job, "failed-package"))); + } + [Fact] + public async Task ChangedCurrentFilesRefuseSwapAndConcurrentLocksFail() + { + using var fixture = new Installation(); var plan = fixture.Prepare(); + using (var gate = UpdateTransaction.Lock(fixture.Target)) await Assert.ThrowsAsync(() => UpdateTransaction.Apply(plan, (_, _) => Task.CompletedTask)); + File.WriteAllText(System.IO.Path.Combine(fixture.Target, "sidepulse-net.dll"), "local change"); + await Assert.ThrowsAsync(() => UpdateTransaction.Apply(plan, (_, _) => Task.CompletedTask)); + Assert.Equal("1.0.0", InstallationManifest.Read(fixture.Target).Version); + } + [Fact] + public void NewOwnedFilesCannotOverwriteUserAddedFiles() + { + using var fixture = new Installation(); + File.WriteAllText(System.IO.Path.Combine(fixture.Target, "custom.txt"), "personal"); + File.WriteAllText(System.IO.Path.Combine(fixture.Stage, "custom.txt"), "new owned file"); + WriteManifest(fixture.Stage, "2.0.0"); + Assert.Throws(() => fixture.Prepare()); + Assert.Equal("personal", File.ReadAllText(System.IO.Path.Combine(fixture.Target, "custom.txt"))); + } + private static object Release(string tag, bool draft = false, bool prerelease = true) => new { tag_name = tag, draft, prerelease, assets = new[] { new { name = "sidepulse-net-linux-x64.tar.gz", size = 10 }, new { name = "SHA256SUMS", size = 100 } } }; + private static HttpResponseMessage Json(string text) => new(HttpStatusCode.OK) { Content = new StringContent(text) }; + private sealed class Handler(Func handler) : HttpMessageHandler + { protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) => Task.FromResult(handler(request)); } + private sealed class Temp : IDisposable + { + public string Path { get; } = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "sidepulse-update-tests-" + Guid.NewGuid().ToString("N")); + public Temp() => Directory.CreateDirectory(Path); + public void Dispose() => Directory.Delete(Path, true); + } + private static void WriteManifest(string directory, string version) + { + var files = Directory.GetFiles(directory).Where(p => System.IO.Path.GetFileName(p) != InstallationManifest.Filename).Select(p => new InstalledFile(System.IO.Path.GetFileName(p), InstallationManifest.Hash(p), 493)).ToArray(); + File.WriteAllText(System.IO.Path.Combine(directory, InstallationManifest.Filename), JsonSerializer.Serialize(new InstallationManifest(1, version, "linux-x64", files), InstallationManifest.Json)); + } + private sealed class Installation : IDisposable + { + private readonly Temp temp = new(); + public string Target { get; } + public string Stage { get; } + private readonly string job; + public Installation() + { + Target = System.IO.Path.Combine(temp.Path, "install"); job = System.IO.Path.Combine(temp.Path, ".sidepulse-update-" + Guid.NewGuid().ToString("N")); Stage = System.IO.Path.Combine(job, "stage"); + foreach (var (directory, version) in new[] { (Target, "1.0.0"), (Stage, "2.0.0") }) + { + Directory.CreateDirectory(directory); + foreach (var name in new[] { "sidepulse-net", "sidepulse-net.dll", "libhostfxr.so" }) File.WriteAllText(System.IO.Path.Combine(directory, name), name + version); + WriteManifest(directory, version); + } + } + public UpdatePlan Prepare() => UpdateTransaction.Prepare(Target, Stage, job, "2.0.0", "linux-x64", 0, 0); + public void Dispose() + { + File.Delete(UpdateTransaction.ReceiptPath(Target)); + temp.Dispose(); + } + } +} From 444767f66cc6ca73f999339ba671923a10d61ffe Mon Sep 17 00:00:00 2001 From: Gordon Breuer Date: Sat, 24 Oct 2026 01:03:37 +0200 Subject: [PATCH 18/26] Preserve installation permissions and canonicalize native updater test paths --- docs/wiki/Updating.md | 4 +++- scripts/update_smoke.py | 10 +++++----- src/SidePulse.Cli/Updates.cs | 9 +++++---- src/SidePulse.Core/UpdateTransaction.cs | 18 +++++++++++++++++- tests/SidePulse.Tests/UpdateTests.cs | 14 ++++++++++++++ 5 files changed, 44 insertions(+), 11 deletions(-) diff --git a/docs/wiki/Updating.md b/docs/wiki/Updating.md index 83dc3be..60a26ec 100644 --- a/docs/wiki/Updating.md +++ b/docs/wiki/Updating.md @@ -54,7 +54,9 @@ across the two directory renames. A power failure between them may require resto the backup directory manually before the CLI can run again. Unknown user-added files are copied into the new directory unless they collide -with a new application-owned file. Avoid editing the installation during updating. +with a new application-owned file. Existing directory access permissions and access +permissions on user-added files are preserved. Avoid editing the installation +during updating. Phone links, profiles and hooks normally live outside it and are not changed. The complete old installation and temporary download/helper workspace are retained for recovery. Once installation is confirmed and no helper is running, these diff --git a/scripts/update_smoke.py b/scripts/update_smoke.py index 93d17f4..5cc805b 100644 --- a/scripts/update_smoke.py +++ b/scripts/update_smoke.py @@ -14,7 +14,7 @@ def main(executable): source = executable.parent shipped = json.loads((source / 'sidepulse-install.json').read_text(encoding='utf-8')) with tempfile.TemporaryDirectory(prefix='SidePulse updater ü ') as temporary: - root = Path(temporary) + root = Path(temporary).resolve() env = dict(os.environ, SIDEPULSE_NET_HOME=str(root / 'state')) for fail in (False, True): home = root / ('rollback' if fail else 'success') @@ -29,9 +29,9 @@ def main(executable): expected = '99.0.0' if fail else shipped['Version'] if fail: (stage / 'sidepulse-install.json').write_text(json.dumps(dict(shipped, Version=expected)), encoding='utf-8') - identity = str(target).upper() if os.name == 'nt' else str(target) - key = hashlib.sha256(identity.encode('utf-8')).hexdigest().upper()[:24] - receipt = root / 'state' / 'updates' / (key + '.json') + initial = subprocess.run([str(target / executable.name), 'update', 'status', '--json'], env=env, capture_output=True, text=True, timeout=15) + assert initial.returncode == 0, (initial.stdout, initial.stderr) + receipt = Path(json.loads(initial.stdout)['receipt']) plan = dict(Target=str(target), Stage=str(stage), Backup=str(backup), Job=str(job), Receipt=str(receipt), ExpectedManifestHash=hashlib.sha256((target / 'sidepulse-install.json').read_bytes()).hexdigest().upper(), Version=expected, Runtime=shipped['Runtime'], ParentId=2147483647, ParentStartTicks=0) @@ -39,7 +39,7 @@ def main(executable): plan_path.write_text(json.dumps(plan), encoding='utf-8') result = subprocess.run([str(helper / executable.name), 'internal-update', '--plan', str(plan_path)], env=env, capture_output=True, text=True, timeout=75, cwd=job) - assert result.returncode == (1 if fail else 0), (result.returncode, result.stdout, result.stderr) + assert result.returncode == (1 if fail else 0), (result.returncode, result.stdout, result.stderr, receipt.read_text(encoding='utf-8') if receipt.exists() else 'no receipt') state = json.loads(receipt.read_text(encoding='utf-8')) assert state['State'] == ('failed' if fail else 'installed'), state current = json.loads((target / 'sidepulse-install.json').read_text(encoding='utf-8')) diff --git a/src/SidePulse.Cli/Updates.cs b/src/SidePulse.Cli/Updates.cs index 94d6e4d..0b3fcd9 100644 --- a/src/SidePulse.Cli/Updates.cs +++ b/src/SidePulse.Cli/Updates.cs @@ -112,7 +112,7 @@ public sealed class UpdateStatusCommand : Command public override int Execute(CommandContext context, UpdateSettings settings, CancellationToken cancellationToken) { var status = UpdateTransaction.Status(Updater.Target); - Updater.Print(settings, (object?)status ?? new { state = "none" }, status is null ? "No recorded update for this installation." : $"{status.State}: {status.Version}\nBackup: {status.Backup}\nWorkspace: {status.Job}" + (status.Error is null ? "" : "\n" + status.Error)); + Updater.Print(settings, (object?)status ?? new { state = "none", receipt = UpdateTransaction.ReceiptPath(Updater.Target) }, status is null ? "No recorded update for this installation." : $"{status.State}: {status.Version}\nBackup: {status.Backup}\nWorkspace: {status.Job}" + (status.Error is null ? "" : "\n" + status.Error)); return status?.State is "failed" or "recovery-required" ? 1 : 0; } } @@ -130,7 +130,8 @@ public override async Task ExecuteAsync(CommandContext context, ApplyUpdate if (!OperatingSystem.IsWindows()) HostLogs.Detach(); plan = JsonSerializer.Deserialize(await File.ReadAllTextAsync(settings.Plan, cancellationToken), InstallationManifest.Json) ?? throw new IOException("Missing update plan."); UpdateTransaction.Validate(plan); - if (Path.GetFullPath(settings.Plan) != Path.Combine(plan.Job, "plan.json") || Updater.Target != Path.Combine(plan.Job, "helper")) throw new IOException("Update helpers must run from their prepared workspace."); + var comparison = OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal; + if (!Path.GetFullPath(settings.Plan).Equals(Path.Combine(plan.Job, "plan.json"), comparison) || !Updater.Target.Equals(Path.Combine(plan.Job, "helper"), comparison)) throw new IOException("Update helpers must run from their prepared workspace."); using var deadline = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); deadline.CancelAfter(TimeSpan.FromSeconds(60)); try { @@ -141,13 +142,13 @@ public override async Task ExecuteAsync(CommandContext context, ApplyUpdate await UpdateTransaction.Apply(plan, (target, token) => Updater.Probe(target, plan.Version, token), deadline.Token); return 0; } - catch (Exception) + catch (Exception ex) { if (plan is not null) { UpdateTransaction.Validate(plan); var existing = UpdateTransaction.Status(plan.Target); - if (existing?.State is not ("failed" or "recovery-required")) UpdateTransaction.Receipt(plan, "failed", "Update helper failed before replacement; check workspace permissions and update status. The backup is retained when present."); + if (existing?.State is not ("failed" or "recovery-required")) UpdateTransaction.Receipt(plan, "failed", "Update helper failed before replacement: " + ex.Message + " The backup is retained when present."); } return 1; } diff --git a/src/SidePulse.Core/UpdateTransaction.cs b/src/SidePulse.Core/UpdateTransaction.cs index 39e1834..aea6e64 100644 --- a/src/SidePulse.Core/UpdateTransaction.cs +++ b/src/SidePulse.Core/UpdateTransaction.cs @@ -53,7 +53,10 @@ public static UpdatePlan Prepare(string target, string stage, string job, string if (nextFiles.Contains(relative)) throw new IOException("A new application file would overwrite a user-added file: " + relative); var destination = InstallationManifest.Resolve(stage, relative); Directory.CreateDirectory(Path.GetDirectoryName(destination)!); File.Copy(path, destination, false); + if (OperatingSystem.IsWindows()) FileSystemAclExtensions.SetAccessControl(new FileInfo(destination), FileSystemAclExtensions.GetAccessControl(new FileInfo(path), System.Security.AccessControl.AccessControlSections.Access)); + else File.SetUnixFileMode(destination, File.GetUnixFileMode(path)); } + PreserveDirectoryAccess(target, stage); var helper = Path.Combine(job, "helper"); Directory.CreateDirectory(helper); foreach (var file in current.Files) @@ -69,13 +72,26 @@ public static UpdatePlan Prepare(string target, string stage, string job, string Receipt(plan, "prepared"); return plan; } + private static void PreserveDirectoryAccess(string source, string destination) + { + foreach (var child in Directory.EnumerateDirectories(source)) + { + if ((File.GetAttributes(child) & FileAttributes.ReparsePoint) != 0) throw new IOException("Symbolic links are not supported in an updated installation."); + var next = Path.Combine(destination, Path.GetFileName(child)); + Directory.CreateDirectory(next); + PreserveDirectoryAccess(child, next); + } + if (OperatingSystem.IsWindows()) FileSystemAclExtensions.SetAccessControl(new DirectoryInfo(destination), FileSystemAclExtensions.GetAccessControl(new DirectoryInfo(source), System.Security.AccessControl.AccessControlSections.Access)); + else File.SetUnixFileMode(destination, File.GetUnixFileMode(source)); + } public static void Validate(UpdatePlan plan) { foreach (var path in new[] { plan.Target, plan.Stage, plan.Backup, plan.Job, plan.Receipt }) if (!Path.IsPathFullyQualified(path)) throw new IOException("Update plan paths must be absolute."); var parent = Path.GetDirectoryName(plan.Target); if (string.IsNullOrEmpty(parent) || plan.Target == plan.Job || plan.Target == Path.GetPathRoot(plan.Target) || Path.GetDirectoryName(plan.Job) != parent || Path.GetDirectoryName(plan.Backup) != parent || plan.Stage != Path.Combine(plan.Job, "stage") || !Path.GetFileName(plan.Job).StartsWith(".sidepulse-update-", StringComparison.Ordinal) - || !plan.Backup.StartsWith(plan.Target + ".backup-", StringComparison.Ordinal) || plan.Receipt != ReceiptPath(plan.Target)) throw new IOException("Invalid update plan layout."); + || !plan.Backup.StartsWith(plan.Target + ".backup-", StringComparison.Ordinal)) throw new IOException("Invalid update plan layout."); + if (!plan.Receipt.Equals(ReceiptPath(plan.Target), OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal)) throw new IOException("Update receipt path does not match the installation."); _ = new ReleaseVersion(plan.Version); } public static async Task Apply(UpdatePlan plan, Func probe, CancellationToken cancellationToken = default) diff --git a/tests/SidePulse.Tests/UpdateTests.cs b/tests/SidePulse.Tests/UpdateTests.cs index ee78234..41585f3 100644 --- a/tests/SidePulse.Tests/UpdateTests.cs +++ b/tests/SidePulse.Tests/UpdateTests.cs @@ -136,9 +136,23 @@ public async Task SuccessfulSwapKeepsBackupAndUserAddedFiles() { using var fixture = new Installation(); File.WriteAllText(System.IO.Path.Combine(fixture.Target, "personal.txt"), "keep me"); + var privateFolder = System.IO.Path.Combine(fixture.Target, "private"); + Directory.CreateDirectory(privateFolder); + File.WriteAllText(System.IO.Path.Combine(privateFolder, "personal.txt"), "private data"); + if (!OperatingSystem.IsWindows()) + { + File.SetUnixFileMode(fixture.Target, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute); + File.SetUnixFileMode(privateFolder, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute); + } var plan = fixture.Prepare(); await UpdateTransaction.Apply(plan, (target, _) => { Assert.Equal("2.0.0", InstallationManifest.Read(target).Version); return Task.CompletedTask; }); Assert.Equal("keep me", File.ReadAllText(System.IO.Path.Combine(fixture.Target, "personal.txt"))); + if (!OperatingSystem.IsWindows()) + { + var privateMode = UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute; + Assert.Equal(privateMode, File.GetUnixFileMode(fixture.Target)); + Assert.Equal(privateMode, File.GetUnixFileMode(System.IO.Path.Combine(fixture.Target, "private"))); + } Assert.Equal("1.0.0", InstallationManifest.Read(plan.Backup).Version); Assert.Equal("installed", UpdateTransaction.Status(fixture.Target)!.State); } From 1839c3d763f4bcaa3762cbc8958c9183742181a8 Mon Sep 17 00:00:00 2001 From: Gordon Breuer Date: Sat, 24 Oct 2026 01:20:08 +0200 Subject: [PATCH 19/26] Review architecture and delivery gates, fix updater and hook defects, add security checks --- .github/workflows/security.yml | 64 ++++++++++++ SECURITY.md | 48 +++++++++ docs/backlog.json | 42 ++++---- docs/decisions/0001-project-boundary.md | 9 +- .../decisions/0002-runtime-and-coexistence.md | 2 +- docs/repository-settings.json | 49 ++++++++++ docs/repository-settings.md | 60 ++++++++++++ docs/reviews/pr-12.md | 98 +++++++++++++++++++ docs/wiki/Project-Setup.md | 9 ++ src/SidePulse.Core/HookInstallation.cs | 23 ++++- src/SidePulse.Core/Releases.cs | 10 +- src/SidePulse.Core/UpdatePackage.cs | 9 +- tests/SidePulse.Tests/AgentTests.cs | 32 ++++++ tests/SidePulse.Tests/UpdateTests.cs | 36 +++++++ 14 files changed, 458 insertions(+), 33 deletions(-) create mode 100644 .github/workflows/security.yml create mode 100644 SECURITY.md create mode 100644 docs/repository-settings.json create mode 100644 docs/repository-settings.md create mode 100644 docs/reviews/pr-12.md diff --git a/.github/workflows/security.yml b/.github/workflows/security.yml new file mode 100644 index 0000000..c979e3a --- /dev/null +++ b/.github/workflows/security.yml @@ -0,0 +1,64 @@ +name: Security +on: + push: + branches: [main] + pull_request: + schedule: + - cron: '43 6 * * 2' + workflow_dispatch: +permissions: + contents: read +concurrency: + group: security-${{ github.ref }} + cancel-in-progress: true +jobs: + codeql: + name: CodeQL (${{ matrix.language }}) + runs-on: ubuntu-latest + timeout-minutes: 30 + permissions: + contents: read + security-events: write + strategy: + fail-fast: false + matrix: + include: + - language: csharp + build-mode: manual + - language: python + build-mode: none + - language: actions + build-mode: none + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + persist-credentials: false + - uses: actions/setup-dotnet@a98b56852c35b8e3190ac28c8c2271da59106c68 # v6 + if: matrix.language == 'csharp' + with: + dotnet-version: 10.0.x + - uses: github/codeql-action/init@9b3254085494b55a0f7c4c2b3d2d52cc712ce370 # v4 + with: + languages: ${{ matrix.language }} + build-mode: ${{ matrix.build-mode }} + - name: Build C# for analysis + if: matrix.language == 'csharp' + run: | + dotnet restore --locked-mode + dotnet build --configuration Release --no-restore --no-incremental + - uses: github/codeql-action/analyze@9b3254085494b55a0f7c4c2b3d2d52cc712ce370 # v4 + with: + category: '/language:${{ matrix.language }}' + dependencies: + name: Dependency review + if: github.event_name == 'pull_request' + runs-on: ubuntu-latest + timeout-minutes: 10 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + persist-credentials: false + - uses: actions/dependency-review-action@a1d282b36b6f3519aa1f3fc636f609c47dddb294 # v5.0.0 + with: + fail-on-severity: high + comment-summary-in-pr: never diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 0000000..b528cbc --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,48 @@ +# Security policy + +SidePulse.NET is an unofficial, independently maintained MIT project. The current +implementation is an unreleased alpha in PR #12. No stable release or response-time +SLA is offered. Security fixes target the latest preview branch and subsequently +the latest published preview; older previews are not maintained independently. + +## Report a vulnerability + +Use [GitHub private vulnerability reporting](https://github.com/Anheledir/SidePulse.NET/security/advisories/new) +when enabled. If that page is unavailable, open an issue requesting a private +reporting channel without publishing exploit details, phone tokens, credentials, +logs containing secrets, or personal data. A maintainer will arrange a private +channel. Private reporting availability is tracked in the repository settings +record; this policy does not imply that it is enabled. + +Please include the commit/version, OS and architecture, affected command, impact, +and a minimal reproduction with redacted sample data. Coordinate publication with +the maintainer. Report upstream firmware, iOS application and bridge-service +vulnerabilities to their maintainers through their published reporting channels. + +## Trust boundaries + +- Hooks execute locally with the agent's existing user permissions. Setup never + approves tools, changes agent trust, or reads conversation transcripts. +- Local IPC is restricted to the current OS user. It is not a boundary against + malicious software already running as that user. All CLI and host instances + should use the same version; rolling mixed-version IPC is not supported. +- Phone credentials use DPAPI, Keychain or Secret Service. There is no plaintext + fallback. Bridge acceptance does not prove that an iPhone displayed a pattern. +- Self-update accepts packages from this project's GitHub releases and verifies + SHA-256 before extraction and each manifest-owned file before replacement. + Checksums from the same publisher detect corruption, not a compromised publisher. + Packages are not independently code-signed. Keep the previous installation backup + until startup and hardware behavior have been checked. +- Use a dedicated application directory. Stop the host and other application + instances, run updates from outside that directory, and avoid editing its files + while an update is pending. User-added files are copied during preparation; + later changes remain in the retained backup and require manual reconciliation. + +## Maintainer controls + +Actions use pinned revisions and read-only permissions by default, with scoped +write permissions for publication and scanning. Weekly Dependabot proposals, +CodeQL and PR dependency review are configured in source. Their effective status, +repository-level controls and any access limitations are documented in +[the settings record](docs/repository-settings.md). Security findings require +triage; a green build is not proof of firmware compatibility or absence of flaws. diff --git a/docs/backlog.json b/docs/backlog.json index 4326474..009c1a8 100644 --- a/docs/backlog.json +++ b/docs/backlog.json @@ -1,79 +1,79 @@ [ { - "title": "M0: Review product concept and compatibility boundaries", + "title": "Investigate firmware, raw USB and platform-specific helpers", "labels": [ "documentation" ], - "body": "Approve terminal workflow, .NET 10 baseline, initial sidepulse-net command, aggregation priorities and explicit platform exclusions. Record decisions before C# scaffolding.\n\nSee docs/wiki/Roadmap.md and docs/wiki/Compatibility.md.\n\nStatus: planned, implementation not started." + "body": "Priority: P3 feasibility research; intentionally outside the preview implementation.\n\n- [ ] Inventory firmware recovery and read-only control protocols against pinned upstream, with licensing and device/firmware matrix.\n- [ ] Assess SPC2/READ2ME and raw USB access separately on Windows/macOS/Linux, including drivers, privilege requirements and exclusive-device access.\n- [ ] Define recovery and interruption tests before firmware writes; require explicit device confirmation and a recoverable test unit.\n- [ ] Assess macOS guards/power helpers and optional MLX classifier as separate platform-specific features, not cross-platform requirements.\n- [ ] Record go/no-go decisions, excluded behavior and safe fallback to mounted-file output.\n\nAcceptance: publish research and transport boundaries before implementing privileged/raw access. Do not bundle drivers, flash firmware or claim parity as part of this review. Dependencies: physical inventory/results from #2/#3.\n\nReviewed against PR #12 (unmerged alpha), 2026-10-23. Checked items mean implemented in that PR, not released or hardware-certified. Evidence: [native CI baseline](https://github.com/Anheledir/SidePulse.NET/actions/runs/40037463280), source and tests in PR #12; [architecture/QA review](https://github.com/Anheledir/SidePulse.NET/blob/implementation/first-preview/docs/reviews/pr-12.md). Keep this issue open until its remaining acceptance criteria are met." }, { - "title": "M1: Port LED language and upstream validation vectors", + "title": "M3: Validate cross-platform releases and verified self-update", "labels": [ "enhancement" ], - "body": "Verify escapes, 512-byte and 20-line limits, LED counts, brightness, invalid input and attributed fixtures against the pinned upstream revision.\n\nSee docs/wiki/Roadmap.md and docs/wiki/Compatibility.md.\n\nStatus: planned, implementation not started." + "body": "Priority: P1 release gate. Status: cross-platform packaging/updater implemented in PR #12; no release published.\n\n- [x] Self-contained Windows/Linux/macOS x64 + ARM64 archives; manifests, bundled licenses, SHA256SUMS publication workflow.\n- [x] Explicit update check/install/status, semantic channel selection, checksums/digests, bounded extraction and file verification.\n- [x] Native Windows x64/Linux x64/macOS ARM64 helper replacement, startup-failure rollback and receipts in CI. Other architectures are cross-built only.\n- [x] Review fixes cover pre-existing download preservation, body timeout and directory-entry limits.\n- [ ] Exercise matching-tag release workflow and inspect all six assets/checksums before announcing a downloadable release. Creating a release is not authorized by this issue review.\n- [ ] Test public install orchestration end to end against a controlled published preview: lookup/download/prepare/helper launch/caller exit/replacement/status. Existing smoke prepares the helper plan directly.\n- [ ] Validate manual install/remove/PATH instructions on clean supported systems; execute remaining architecture packages on native hardware.\n- [ ] Record signing and package-manager decisions; packages are currently unsigned, no installer/package manager exists.\n- [ ] Before adding cleanup or stronger preservation claims, detect user-added file edits between Prepare and Apply; current snapshot is preparation-time and later edits survive only in retained backup.\n\nAcceptance: scheduling is not completion; keep backups and stop host before update. Checksums detect corruption, not compromise of the release publisher. Upgrade from source/old unmanifested builds requires manual install.\n\nReviewed against PR #12 (unmerged alpha), 2026-10-23. Checked items mean implemented in that PR, not released or hardware-certified. Evidence: [native CI baseline](https://github.com/Anheledir/SidePulse.NET/actions/runs/40037463280), source and tests in PR #12; [architecture/QA review](https://github.com/Anheledir/SidePulse.NET/blob/implementation/first-preview/docs/reviews/pr-12.md). Keep this issue open until its remaining acceptance criteria are met." }, { - "title": "M1: Implement writable USB device transport on Windows", + "title": "M2: Port remaining upstream integrations and remote relay", "labels": [ "enhancement" ], - "body": "Discover volumes, select destinations and write/flush programs. Verify a real Dot and removal, read-only and ambiguous-device cases.\n\nSee docs/wiki/Roadmap.md and docs/wiki/Compatibility.md.\n\nStatus: planned, implementation not started." + "body": "Priority: P2 provider expansion and remote design.\n\n- [x] Codex current local lifecycle hooks, Claude Code and Kiro CLI V3 adapters/config generators added in PR #12, alongside Copilot (#6).\n- [x] Provider capability inventory states unsupported subagent/payload cases; root sessions are namespaced.\n- [ ] Record actual installed provider versions and captured redacted event fixtures for Codex, Claude and Kiro; run real waiting/error/completion acceptance separately for each.\n- [ ] Cursor adapter and documented event contract.\n- [ ] Grok adapter and documented event contract.\n- [ ] Junie adapter and documented event contract.\n- [ ] Assess Gemini support before advertising it.\n- [ ] Design authenticated relay and Android support with separate threat model, secrets storage and delivery semantics.\n\nAcceptance: no implied provider parity from generated JSON alone; no paid API dependency or automatic trust changes. Split a provider into its own issue when implementation begins.\n\nReviewed against PR #12 (unmerged alpha), 2026-10-23. Checked items mean implemented in that PR, not released or hardware-certified. Evidence: [native CI baseline](https://github.com/Anheledir/SidePulse.NET/actions/runs/40037463280), source and tests in PR #12; [architecture/QA review](https://github.com/Anheledir/SidePulse.NET/blob/implementation/first-preview/docs/reviews/pr-12.md). Keep this issue open until its remaining acceptance criteria are met." }, { - "title": "M1: Implement phone pairing and bridge delivery", + "title": "M1: Add diagnostics, aliases and explicit migration", "labels": [ "enhancement" ], - "body": "Pair original iOS app, protect credentials, support target selection and separate silent LED updates from visible notifications. Test offline delivery and show only supported acknowledgement levels.\n\nSee docs/wiki/Roadmap.md and docs/wiki/Compatibility.md.\n\nStatus: planned, implementation not started." + "body": "Priority: P2 follow-up, partial implementation.\n\n- [x] Doctor diagnostics, explicit device selection, phone aliases/defaults and host logs.\n- [x] Existing Python configuration is not silently modified or imported.\n- [ ] Add device aliases with ambiguity checks and previewable target resolution.\n- [ ] Implement explicit Python migration/import preview, exact backups, user-selected destinations and rollback evidence.\n- [ ] Test missing drives, inaccessible vaults, invalid hooks and failed bridge delivery with actionable diagnostics.\n\nAcceptance: a dry-run must not create provider/configuration/backup/lock files. Preserve old Python configuration and credentials; never print tokens. Depends on transport and phone behavior in #3/#4.\n\nReviewed against PR #12 (unmerged alpha), 2026-10-23. Checked items mean implemented in that PR, not released or hardware-certified. Evidence: [native CI baseline](https://github.com/Anheledir/SidePulse.NET/actions/runs/40037463280), source and tests in PR #12; [architecture/QA review](https://github.com/Anheledir/SidePulse.NET/blob/implementation/first-preview/docs/reviews/pr-12.md). Keep this issue open until its remaining acceptance criteria are met." }, { - "title": "M1: Implement shared host and session state reduction", + "title": "M1: Design and implement the Spectre terminal experience", "labels": [ "enhancement" ], - "body": "Version current-user IPC, aggregate concurrent sessions, ignore late events, persist minimal restart metadata and serialize outputs. Hooks must not wait on network I/O.\n\nSee docs/wiki/Roadmap.md and docs/wiki/Compatibility.md.\n\nStatus: planned, implementation not started." + "body": "Priority: P2 UX and accessibility. Status: interactive CLI and animation studio implemented in PR #12.\n\n- [x] Root/group cursor menus, guided pattern editor, Dot/Pro Spectre previews, review/copy/export of full single-line commands.\n- [x] --quiet, --json, --no-interactive, redirected IO and NO_COLOR behavior; shell quoting tests; Unix PTY menu/editor/playback smoke.\n- [x] About/docs/credits and offline dependency license texts, explicit website opening without unapproved affiliate IDs.\n- [ ] Implement or explicitly defer the originally proposed continuously refreshed host dashboard (current host renders state snapshots).\n- [ ] Manual Windows Terminal keyboard/clipboard and narrow-screen/no-color accessibility checks; PTY smoke is Unix-only.\n- [ ] Audit JSON schemas across command states, including update status with/without receipts, and document stable script fields.\n\nAcceptance: scripts never enter menus or wait for input; stdout remains usable for machine output and errors go to stderr.\n\nReviewed against PR #12 (unmerged alpha), 2026-10-23. Checked items mean implemented in that PR, not released or hardware-certified. Evidence: [native CI baseline](https://github.com/Anheledir/SidePulse.NET/actions/runs/40037463280), source and tests in PR #12; [architecture/QA review](https://github.com/Anheledir/SidePulse.NET/blob/implementation/first-preview/docs/reviews/pr-12.md). Keep this issue open until its remaining acceptance criteria are met." }, { "title": "M1: Implement Copilot CLI hook integration", "labels": [ "enhancement" ], - "body": "Install/repair/remove dedicated hooks, handle real waiting notifications and turn ends, avoid permission decisions, preserve unrelated hooks and verify a real Windows CLI session.\n\nSee docs/wiki/Roadmap.md and docs/wiki/Compatibility.md.\n\nStatus: planned, implementation not started." + "body": "Priority: P1 real-provider acceptance. Status: integration implemented in PR #12.\n\n- [x] Provider-specific Copilot lifecycle/notification parser and silent Bash/PowerShell wrappers.\n- [x] Dedicated hook ownership, byte-exact backups, dry-run setup/removal and changed-file refusal.\n- [x] QA regression: changed executable reinstall now refuses instead of silently retaining old hooks; uninstall preview creates no lock file.\n- [ ] Verify real Windows Copilot CLI session with recorded version: Working, permission waiting, completion, error and multiple concurrent sessions.\n- [ ] Verify trust prompts, restart requirements and setup/remove alongside unrelated real hooks.\n- [ ] Define repair workflow. Current safe path is explicit uninstall/reinstall; no automatic repair command exists.\n\nAcceptance: do not auto-approve tool use or modify trust/permission settings. Current tests use fixtures/generated wrappers, not a live Copilot session.\n\nReviewed against PR #12 (unmerged alpha), 2026-10-23. Checked items mean implemented in that PR, not released or hardware-certified. Evidence: [native CI baseline](https://github.com/Anheledir/SidePulse.NET/actions/runs/40037463280), source and tests in PR #12; [architecture/QA review](https://github.com/Anheledir/SidePulse.NET/blob/implementation/first-preview/docs/reviews/pr-12.md). Keep this issue open until its remaining acceptance criteria are met." }, { - "title": "M1: Design and implement the Spectre terminal experience", + "title": "M1: Implement shared host and session state reduction", "labels": [ "enhancement" ], - "body": "Prototype live dashboard/menu interaction, compact layout, session/device views, terminal capabilities, keyboard flow and plain/JSON/noninteractive modes.\n\nSee docs/wiki/Roadmap.md and docs/wiki/Compatibility.md.\n\nStatus: planned, implementation not started." + "body": "Priority: P1 lifecycle/compatibility specification. Status: shared host implemented in PR #12.\n\n- [x] Current-user IPC, single-host lease, bounded requests, ACKed control RPC, independent bounded output queue.\n- [x] Provider-namespaced sessions; out-of-order timestamp rejection; Waiting > Working > Error > Done > Idle > Unknown; error survives Stop.\n- [x] Detached start/status/stop/logs and Unix crash recovery exercised in native CI.\n- [ ] Decide and implement explicit IPC protocol version negotiation before supporting mixed CLI/host versions. Currently require same version and stop host for upgrade.\n- [ ] Resolve restart semantics: implementation intentionally starts Unknown and does not persist sessions; original minimal-restart-metadata requirement is deferred, not complete.\n- [ ] Specify retention/recovery for 1,024 live/error sessions and long-lived abandoned sessions; provide an explicit reset/removal policy without inventing agent completion.\n\nAcceptance: hooks remain silent and bounded, never wait for network or change permission decisions. Keep restart/version/retention decisions testable.\n\nReviewed against PR #12 (unmerged alpha), 2026-10-23. Checked items mean implemented in that PR, not released or hardware-certified. Evidence: [native CI baseline](https://github.com/Anheledir/SidePulse.NET/actions/runs/40037463280), source and tests in PR #12; [architecture/QA review](https://github.com/Anheledir/SidePulse.NET/blob/implementation/first-preview/docs/reviews/pr-12.md). Keep this issue open until its remaining acceptance criteria are met." }, { - "title": "M1: Add diagnostics, aliases and explicit migration", + "title": "M1: Implement phone pairing and bridge delivery", "labels": [ "enhancement" ], - "body": "Explain broken integrations/paths and transport failures; add device aliases and import preview/backup without modifying the existing Python port silently.\n\nSee docs/wiki/Roadmap.md and docs/wiki/Compatibility.md.\n\nStatus: planned, implementation not started." + "body": "Priority: P1 iPhone acceptance. Status: pairing and delivery implemented in PR #12.\n\n- [x] QR/SSE pairing, bounded input, token normalization and link aliases/defaults.\n- [x] DPAPI/Keychain/Secret Service protection with fail-closed recovery; native vault CI.\n- [x] Silent bridge delivery and explicit target selection; redacted errors.\n- [ ] Scan the QR with the original TestFlight app and verify token persistence/restart on each desktop OS.\n- [ ] Test offline bridge, network interruption, HTTP errors and phone reconnection; document retry policy (no durable offline queue today).\n- [ ] Demonstrate silent LED update versus any visible notification behavior supported by the app; visible notifications are not implemented as a separate command.\n\nAcceptance: record bridge HTTP acceptance separately from observed phone display. No transport acknowledgement overclaim.\n\nReviewed against PR #12 (unmerged alpha), 2026-10-23. Checked items mean implemented in that PR, not released or hardware-certified. Evidence: [native CI baseline](https://github.com/Anheledir/SidePulse.NET/actions/runs/40037463280), source and tests in PR #12; [architecture/QA review](https://github.com/Anheledir/SidePulse.NET/blob/implementation/first-preview/docs/reviews/pr-12.md). Keep this issue open until its remaining acceptance criteria are met." }, { - "title": "M2: Port remaining upstream integrations and remote relay", + "title": "M1: Validate cross-platform writable USB/SD device transport", "labels": [ "enhancement" ], - "body": "Track Codex, Claude, Cursor, Grok and Junie separately, plus relay and Android. Record payload compatibility and hardware verification per inventory row.\n\nSee docs/wiki/Roadmap.md and docs/wiki/Compatibility.md.\n\nStatus: planned, implementation not started." + "body": "Priority: P1 physical acceptance. Status: cross-platform mounted-file implementation in PR #12.\n\n- [x] Discover mounted LEDS.LED files; explicit selection; ambiguous-device refusal.\n- [x] Write/length/flush to the existing virtual file without rename; simulated file tests.\n- [ ] Record physical Dot and Pro acceptance on Windows, macOS and Linux with device/firmware/OS versions.\n- [ ] Exercise removal during write, read-only media, multiple devices and recovery on real mounts.\n- [ ] Verify Linux mount discovery on actual USB and SD mount layouts; document when --device is required.\n\nAcceptance: report file-write success only, never firmware/display acknowledgement. Read-only USB/SPC2/READ2ME work belongs in #11.\n\nReviewed against PR #12 (unmerged alpha), 2026-10-23. Checked items mean implemented in that PR, not released or hardware-certified. Evidence: [native CI baseline](https://github.com/Anheledir/SidePulse.NET/actions/runs/40037463280), source and tests in PR #12; [architecture/QA review](https://github.com/Anheledir/SidePulse.NET/blob/implementation/first-preview/docs/reviews/pr-12.md). Keep this issue open until its remaining acceptance criteria are met." }, { - "title": "M3: Build verified self-contained Windows releases", + "title": "M1: Port LED language and upstream validation vectors", "labels": [ "enhancement" ], - "body": "Introduce release workflow after real projects/tests exist; produce x64/arm64 artifacts and checksums, verify install/uninstall and document signing/package-manager decisions.\n\nSee docs/wiki/Roadmap.md and docs/wiki/Compatibility.md.\n\nStatus: planned, implementation not started." + "body": "Priority: P1 before firmware-parity claims. Status: partial implementation in PR #12.\n\n- [x] Envelope validation: escapes, NUL rejection, 512 UTF-8 bytes, 20 physical lines.\n- [x] Managed Dot/Pro parser/player: indexed colors, timing, easing, brightness, roll and repeat; bounded simulation.\n- [x] Attributed upstream pattern assets pinned by NOTICE.md; automated parsing/frame tests.\n- [ ] Build an independently derived, attributed upstream/firmware golden vector corpus for timing, repeat boundaries, invalid syntax and model indexing.\n- [ ] Compare real Dot and Pro output against these vectors and record firmware versions/results.\n\nAcceptance: distinguish envelope validation, managed simulation and firmware acceptance. Terminal color/timing is approximate until comparison. No claim of full grammar or firmware parity.\n\nReviewed against PR #12 (unmerged alpha), 2026-10-23. Checked items mean implemented in that PR, not released or hardware-certified. Evidence: [native CI baseline](https://github.com/Anheledir/SidePulse.NET/actions/runs/40037463280), source and tests in PR #12; [architecture/QA review](https://github.com/Anheledir/SidePulse.NET/blob/implementation/first-preview/docs/reviews/pr-12.md). Keep this issue open until its remaining acceptance criteria are met." }, { - "title": "Investigate firmware, raw USB and platform-specific helpers", + "title": "M0: Review product concept and compatibility boundaries", "labels": [ "documentation" ], - "body": "Decide feasibility and safety tests for firmware recovery, read-only USB control, Windows drivers, macOS guards/power helpers and the optional MLX classifier. Do not imply parity before verification.\n\nSee docs/wiki/Roadmap.md and docs/wiki/Compatibility.md.\n\nStatus: planned, implementation not started." + "body": "Priority: complete concept decision.\n\n- [x] Maintainer approved recognizable/simple Spectre terminal design, MIT license and implementation.\n- [x] .NET 10, independent sidepulse-net executable and coexistence with the Python port.\n- [x] Cross-platform scope, provider-namespaced sessions and explicit unsupported transport boundaries.\n- [x] Decisions recorded in docs/decisions/0001 through 0003; implementation proceeds in PR #12.\n\nThe discussion subsequently expanded the Windows-first concept to Windows, macOS and Linux. This closes concept approval only; implementation, physical compatibility and release gates remain in #2–#11.\n\nReview: 2026-10-23. See PR #12 and docs/decisions." } ] diff --git a/docs/decisions/0001-project-boundary.md b/docs/decisions/0001-project-boundary.md index 43f55ee..d4765ee 100644 --- a/docs/decisions/0001-project-boundary.md +++ b/docs/decisions/0001-project-boundary.md @@ -1,14 +1,13 @@ # ADR 0001: Independent .NET companion -Status: proposed, 2026-10-23. +Status: accepted by the maintainer in the project discussion, 2026-10-23. -Build SidePulse.NET as an independently maintained, Windows-first .NET 10 LTS +Build SidePulse.NET as an independently maintained, cross-platform .NET 10 LTS application using Spectre.Console and Spectre.Console.Cli. Preserve compatible wire behavior where feasible, while tracking platform-specific limitations. -The initial repository contains planning and automation only. Do not add C# -application scaffolding until concept review is complete. The working Python port -and its hook add-on remain separate reference implementations. +The concept review is complete and implementation is in PR #12. The working +Python port and its hook add-on remain separate reference implementations. This permits an idiomatic C# architecture without claiming drop-in compatibility for all macOS-specific helpers. Upstream attribution and license retention are diff --git a/docs/decisions/0002-runtime-and-coexistence.md b/docs/decisions/0002-runtime-and-coexistence.md index bc5c22b..ec5078d 100644 --- a/docs/decisions/0002-runtime-and-coexistence.md +++ b/docs/decisions/0002-runtime-and-coexistence.md @@ -1,6 +1,6 @@ # ADR 0002: Shared state owner and explicit migration -Status: proposed, 2026-10-23. +Status: accepted by the maintainer in the project discussion, 2026-10-23. A local background host will own event reduction, per-session state and device outputs. Hook adapters will enqueue small events over authenticated local IPC. diff --git a/docs/repository-settings.json b/docs/repository-settings.json new file mode 100644 index 0000000..f8bd52b --- /dev/null +++ b/docs/repository-settings.json @@ -0,0 +1,49 @@ +{ + "repository": "Anheledir/SidePulse.NET", + "reviewedOn": "2026-10-23", + "implementationPullRequest": 12, + "observed": { + "visibility": "public", + "defaultBranch": "main", + "description": "Unofficial .NET companion for SidePulse with a Spectre.Console terminal UI. Concept stage.", + "homepage": null, + "topics": [], + "hasIssues": true, + "hasWiki": true, + "hasProjects": false, + "deleteBranchOnMerge": true, + "allowMergeCommit": false, + "allowSquashMerge": true, + "allowRebaseMerge": true, + "allowAutoMerge": false + }, + "desired": { + "description": "Unofficial cross-platform SidePulse companion in C# and Spectre.Console: agent status hooks, LED patterns, iPhone pairing and verified updates.", + "homepage": "https://github.com/Anheledir/SidePulse.NET/wiki", + "topics": ["sidepulse", "dotnet", "csharp", "spectre-console", "cli", "cross-platform", "github-copilot", "codex", "claude-code", "kiro", "led"], + "hasProjects": true, + "privateVulnerabilityReporting": true, + "dependabotAlerts": true, + "dependabotSecurityUpdates": true, + "secretScanning": true, + "secretScanningPushProtection": true, + "actionsDefaultTokenPermissions": "read", + "actionsCanApprovePullRequests": false, + "mainRules": { + "requirePullRequest": true, + "requiredApprovals": 0, + "requireConversationResolution": true, + "requireUpToDateBranch": true, + "blockForcePushes": true, + "blockDeletion": true, + "requiredChecksPolicy": "Require Quality, all three native build jobs, CodeQL and dependency review after successful check names are observed." + } + }, + "verificationLimits": { + "repositoryAdministration": "Connector has no repository settings mutation tools.", + "branchProtection": "GET returned 403 Resource not accessible by integration; unknown, not assumed disabled.", + "securityAndAnalysis": "Not exposed by repository response; unknown, not assumed disabled.", + "projects": "Repository Projects feature observed disabled. No project board has been created.", + "appliedRemoteSettings": [] + } +} diff --git a/docs/repository-settings.md b/docs/repository-settings.md new file mode 100644 index 0000000..f7597b6 --- /dev/null +++ b/docs/repository-settings.md @@ -0,0 +1,60 @@ +# Repository configuration record + +Reviewed 2026-10-23. [Machine-readable observed and desired values](repository-settings.json). +This record distinguishes source configuration in PR #12 from effective GitHub +settings. The implementation has not been merged or released. + +## Effective settings observed through GitHub + +The repository is public, with `main` as its default branch. Issues and Wiki are +on; Projects is off. Merged branches are deleted automatically. Squash and rebase +merges are allowed, merge commits and auto-merge are disabled. The description +still says "Concept stage", homepage is empty, and no topics are set. + +The authenticated user has an admin role, but the connected GitHub App excludes +repository administration. Branch-protection reads returned 403; security feature +states were not exposed. These controls are **unknown**, not disabled. No remote +admin settings have been changed in this review. + +## Source configuration + +- Weekly Dependabot updates for NuGet and Actions already exist. +- Security workflow adds C#, Python and Actions CodeQL analysis on PRs, main + pushes and weekly schedule. C# uses an explicit .NET 10 build. Analysis needs + repository code-scanning availability and a successful Actions run. +- PR dependency review fails on newly introduced high/critical advisories. + It does not replace checking existing dependencies or advisory triage. +- All third-party Actions are pinned. Default permissions are `contents: read`; + only jobs that need publication or SARIF upload receive write permissions. +- SECURITY.md supplies reporting guidance and documents updater/IPC trust limits. +- Wiki publishing and upstream review run only from the default branch. + +## Admin changes to apply and verify + +Use the description, homepage and topics in the JSON record. Enable repository +Projects if a board is wanted. A repository feature switch does not create a +GitHub Projects board: create **SidePulse.NET delivery**, with description +"Cross-platform SidePulse.NET delivery, compatibility evidence and release gates", +and Todo, In progress, Validation and Done statuses; add #1 through #11 and PR #12. +Keep unfinished hardware and provider validation in Validation, not Done. + +Enable private vulnerability reporting, Dependabot alerts/security updates, +secret scanning and push protection where available. Check Actions defaults are +read-only and workflow PR approval is off. Retain existing merge choices. + +Protect main with PRs, resolved conversations, current checks, and blocked branch +force-push/deletion. For this personal repository use zero required approvals so +the sole maintainer is not locked out by GitHub's self-approval restriction. +Require exact successful check contexts only after they have run: documentation, +all three native build jobs, CodeQL for C#/Python/Actions, and dependency review. +Do not invent check names or enforce checks that have never completed. + +Record each applied change, observed value and date here and in JSON. If an option +is unavailable, record the actual GitHub limitation rather than claiming success. +Do not create a long-lived PAT merely to work around the connector's admin scope. + +## Reference + +- [GitHub security and analysis settings](https://docs.github.com/en/repositories/managing-your-repositorys-settings-and-features/enabling-features-for-your-repository/managing-security-and-analysis-settings-for-your-repository) +- [CodeQL manual builds](https://docs.github.com/en/code-security/how-tos/find-and-fix-code-vulnerabilities/manage-your-configuration/codeql-for-compiled-languages) +- [Dependency review action](https://github.com/actions/dependency-review-action) diff --git a/docs/reviews/pr-12.md b/docs/reviews/pr-12.md new file mode 100644 index 0000000..6585ed6 --- /dev/null +++ b/docs/reviews/pr-12.md @@ -0,0 +1,98 @@ +# PR #12 architecture and QA review + +Review date: 2026-10-23. Baseline: `444767f66cc6ca73f999339ba671923a10d61ffe`. +Scope: application architecture, credential and IPC boundaries, hook ownership, +terminal/script behavior, animation model, updater transactions, tests, workflows, +all eleven open issues, repository metadata and available security settings. +This is a maintainer-assisted review, not independent approval or a penetration test. + +## Assessment + +The Core/CLI split is appropriate: the transport, reducer, parser and update +transaction can be tested without Spectre or hardware. Native secret adapters +fail closed, hooks remain isolated from network delivery, shared config writes +preserve exact backups, and update replacement verifies both packages and files. +There is useful behavior coverage beyond happy paths, including crash recovery, +modified configuration, corrupt packages and actual startup-probe rollback. + +PR #12 is an alpha implementation with substantial follow-up scope. Do not merge +it under a firmware-parity or production-ready claim. The review found no +confirmed critical vulnerability, but that is not evidence of absence. New +security checks and the review fixes must pass before merge. Hardware/provider +acceptance and the public update/release path remain explicit release gates. + +## Confirmed findings and disposition + +| ID | Priority | Trigger and impact | Disposition / evidence | +|---|---|---|---| +| R1 | P1 data preservation | `GitHubReleases.Download`: an existing package filename makes CreateNew fail, then unconditional cleanup deletes that pre-existing file. | Fixed: cleanup only after this invocation successfully creates the file. Regression reproduced original deletion and now checks original bytes survive. | +| R2 | P2 availability | `Latest` uses ResponseHeadersRead, so HttpClient's timeout ends at headers; a stalled body can hang standalone update check. | Fixed: linked deadline covers metadata bodies and pagination. Regression stalls a stream after headers and uses the client's timeout without caller cancellation. | +| R3 | P2 resource bounds | `UpdatePackage.Extract`: file limits exclude directory-only archive entries, permitting arbitrarily long directory-entry processing within archive size bounds. | Fixed: count all ZIP/tar entries and check cancellation per entry; regression covers 10,001 directories and staging cleanup. Central-directory parsing still precedes the ZIP loop; compressed archive byte limits also apply. | +| R4 | P2 dry-run contract | `HookInstallation.Uninstall(..., true)` creates a lock sidecar before returning preview. | Fixed: preview reads only. Regression deletes the previous lock and verifies no new lock/config changes. Real removal reloads ownership after taking the lock. | +| R5 | P2 correctness | Reinstall with a new executable returns installed while silently keeping old hooks. | Fixed: reconstruct the requested install from the verified original backup, compare hashes and require explicit uninstall/reinstall when it differs. Dedicated/shared provider regressions preserve existing bytes. | +| R6 | P2 compatibility | IPC has no protocol handshake, starts Unknown after restart, and retains up to 1,024 active/error sessions without stale-session reset. | Tracked in #5. Same-version CLI/host is required. Decide version/restart/retention semantics before claiming mixed-version support. | +| R7 | P2 preservation window | User-added files are copied at update preparation; edits before replacement are not recopied. | Tracked in #10 and documented in SECURITY.md. Later edits remain in retained backup; do not claim concurrent-edit preservation. | +| R8 | P1 release evidence | Updater smoke prepares a helper plan directly. It does not exercise the complete public install command against published assets. Tag publication has not run and there is no published release. | Open release gate in #10; controlled published-preview test required before announcing self-update ready for general use. No release/tag created in this review. | +| R9 | P1 compatibility evidence | Simulated LED output and generated agent wrappers are not real firmware, iOS or provider acceptance. | Open criteria in #2/#3/#4/#6/#9 with versioned evidence required. | +| R10 | P2 governance | Metadata says concept stage; homepage/topics empty, Projects disabled. Admin/security values cannot be verified with this GitHub App. | Observed and desired values recorded in repository-settings.json/md. Unknown controls are not called disabled or configured. | + +P1 means fix before merge when it is a reproducible defect (R1), or satisfy before +making the corresponding release/compatibility claim (R8/R9). P2 items are +correctness, resilience or explicit follow-up decisions. No self-approval is given. + +## Architecture and test observations + +- State aggregation is deterministic and provider-namespaced. Error retention and + late-event handling have tests; receipt timestamps and bounded retention still + need a documented operating policy (#5). A static dashboard is not a live one (#7). +- Native protection uses DPAPI or AES-GCM with native-vault keys. Link listing + does not print tokens. Same-user IPC does not defend against compromised local + user processes. No paid provider API or conversation transcript access is needed. +- LED envelope validation is intentionally separate from parser simulation and + physical firmware acknowledgement. Upstream assets are attributed to a pinned + revision. A golden conformance corpus is still missing (#2). +- Hook tests verify merging/ownership/backup behavior and generated wrappers. + Provider versions, event payload drift and real trust prompts need manual checks. +- Shell command export has quoting tests; Unix PTY smoke covers menus/editor. + Windows keyboard/clipboard and narrow-terminal usability remain manual checks. + JSON conventions vary across commands/states; audit before promising a stable + external schema (#7). Runtime errors belong on stderr. +- Updates reject unsupported runtimes, missing checksums, corruption, traversal, + links and manifest mismatches. Installation replacement is two renames, not a + crash-proof filesystem transaction. Backups/manual recovery remain necessary. + Hashes from the same publisher are not independent signature verification. +- Release uses tested native CI and draft-first assets/checksums. Only the publish + job has contents write. Wiki/upstream workflows execute from the default branch. + No pull_request_target execution or permanent token was introduced. + +## Validation record + +- New regression tests first reproduced R1/R3/R4 on the baseline; R2 was confirmed + by reviewing ResponseHeadersRead lifetime and a stalled-body regression; R5 has + shared/dedicated-provider regressions. +- Local Release suite: **96 passed**, 0 failed, 0 skipped. Native vault checks are + opt-in and were not enabled locally. Local host listeners are blocked by this + environment; native host checks require CI. +- `dotnet list package --vulnerable --include-transitive --no-restore --format json` + reported no vulnerable packages in all three projects at review time. This is + an advisory snapshot, not a permanent assurance or a license audit. +- Baseline [native CI](https://github.com/Anheledir/SidePulse.NET/actions/runs/40037463280) + passed 90 tests per OS, native vaults, simulated transports, host/provider + wrappers and self-contained helper replacement/rollback. Those results precede + these fixes. Native executed architectures: Windows x64, Linux x64, macOS ARM64; + the other three packages were cross-built, not executed. +- Post-review native CI, CodeQL, dependency review and documentation checks must + be linked from the PR after the review commit. A workflow file alone is not a + successful security scan. + +## Issue disposition + +#1 is completed because the maintainer already approved the concept and later +explicitly requested implementation/cross-platform support. ADRs now reflect +that decision. #2 through #11 stay open with implemented items, test evidence, +remaining acceptance criteria and priority. #3/#10 titles now reflect all three +platforms. `docs/backlog.json` mirrors the reviewed issue descriptions; it is a +snapshot, not an automatic issue-state synchronizer. + +See [repository settings](../repository-settings.md) for effective configuration, +planned controls, verification limits and the proposed project-board description. diff --git a/docs/wiki/Project-Setup.md b/docs/wiki/Project-Setup.md index 0172333..369fb77 100644 --- a/docs/wiki/Project-Setup.md +++ b/docs/wiki/Project-Setup.md @@ -11,6 +11,7 @@ The repository and wiki are public and use the MIT license. | .NET CI | Restore, build and test a root solution on Windows, Linux and macOS | | Wiki sync | Publish reviewed docs/wiki pages on the default branch | | Upstream watch | Check upstream every Monday at 07:17 UTC and on manual dispatch | +| Security | CodeQL for C#, Python and Actions; PR dependency review blocks new high/critical advisories | | Dependabot | Propose weekly dependency updates | Actions are pinned to upstream commit SHAs. Permissions are read-only by default. @@ -38,3 +39,11 @@ The workflow uses the built-in Actions token with `issues: write`. No extra toke external service or personal reminder is required. GitHub schedules may be delayed; use **Actions → Upstream watch → Run workflow** for an immediate check. Public repositories with no activity may have scheduled workflows disabled by GitHub. + +## Security and repository administration + +[SECURITY.md](https://github.com/Anheledir/SidePulse.NET/blob/implementation/first-preview/SECURITY.md) +explains private reporting and trust boundaries. The +[configuration record](https://github.com/Anheledir/SidePulse.NET/blob/implementation/first-preview/docs/repository-settings.md) +separates observed settings, source configuration and desired admin changes. +Adding a workflow does not prove that repository-level security controls are on. diff --git a/src/SidePulse.Core/HookInstallation.cs b/src/SidePulse.Core/HookInstallation.cs index 21969c6..bc9d46f 100644 --- a/src/SidePulse.Core/HookInstallation.cs +++ b/src/SidePulse.Core/HookInstallation.cs @@ -36,7 +36,16 @@ public InstallationStatus Install(string path, AgentProvider provider, JsonObjec if (existingManifest is not null) { var status = Status(target); - if (status.State == "installed") return status; + if (status.State == "installed") + { + var originalBytes = existingManifest.BeforeHash == "absent" ? null : existingManifest.Backup is { } backupPath ? Read(backupPath) : null; + if (Hash(originalBytes) != existingManifest.BeforeHash) throw new IOException("The original backup is missing or modified. Review it before reinstalling."); + var originalSettings = originalBytes is null ? null : JsonNode.Parse(originalBytes)!.AsObject(); + var requested = HookConfiguration.Merge(provider, originalSettings, generated); + if (Hash(Serialize(requested)) != existingManifest.InstalledHash) + throw new IOException("The requested hooks differ from the installed hooks. Uninstall before reinstalling with a different executable or configuration; no files were changed."); + return status; + } throw new IOException("An existing installation changed or is pending. Review it and uninstall before reinstalling; no files were overwritten."); } var before = Read(target); @@ -48,7 +57,7 @@ public InstallationStatus Install(string path, AgentProvider provider, JsonObjec } catch (Exception ex) when (ex is JsonException or InvalidOperationException) { throw new IOException("Existing configuration must be valid JSON. No files were changed."); } var merged = HookConfiguration.Merge(provider, original, generated); - var after = System.Text.Encoding.UTF8.GetBytes(merged.ToJsonString(new JsonSerializerOptions { WriteIndented = true }) + "\n"); + var after = Serialize(merged); if (dryRun) return new("preview", target, null); Directory.CreateDirectory(Path.GetDirectoryName(target)!); Directory.CreateDirectory(manifestDirectory); @@ -72,10 +81,17 @@ public InstallationStatus Uninstall(string path, bool dryRun) var target = Target(path); var manifest = Load(target); if (manifest is null) return new("not-installed", target, null); + if (dryRun) + { + var preview = Status(target); + if (preview.State == "modified") throw new IOException("Configuration was edited after installation. Review the backup and merge manually; uninstall will not overwrite those changes."); + return preview with { State = "preview-remove" }; + } using var gate = PrivateFile(target + ".sidepulse-net.lock", FileMode.OpenOrCreate); + manifest = Load(target); + if (manifest is null) return new("not-installed", target, null); var status = Status(target); if (status.State == "modified") throw new IOException("Configuration was edited after installation. Review the backup and merge manually; uninstall will not overwrite those changes."); - if (dryRun) return status with { State = "preview-remove" }; if (status.State == "installed") { if (manifest.BeforeHash == "absent") File.Delete(target); @@ -95,6 +111,7 @@ private static FileStream PrivateFile(string path, FileMode mode) if (!OperatingSystem.IsWindows()) options.UnixCreateMode = UnixFileMode.UserRead | UnixFileMode.UserWrite; return new FileStream(path, options); } + private static byte[] Serialize(JsonObject value) => System.Text.Encoding.UTF8.GetBytes(value.ToJsonString(new JsonSerializerOptions { WriteIndented = true }) + "\n"); private static void AtomicWrite(string path, byte[] bytes) { var temporary = path + "." + Guid.NewGuid().ToString("N") + ".tmp"; diff --git a/src/SidePulse.Core/Releases.cs b/src/SidePulse.Core/Releases.cs index 2970bb7..02dfccc 100644 --- a/src/SidePulse.Core/Releases.cs +++ b/src/SidePulse.Core/Releases.cs @@ -62,6 +62,11 @@ private async Task Get(Uri uri, CancellationToken cancellat } public async Task Latest(bool includePrerelease, CancellationToken cancellationToken = default) { + // ResponseHeadersRead completes HttpClient's timeout at the headers. Keep the + // same deadline active while reading every body and release-history page. + using var deadline = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + deadline.CancelAfter(client.Timeout); + cancellationToken = deadline.Token; if (!includePrerelease) { using var response = await Get(new($"https://api.github.com/repos/{Repository}/releases/latest"), cancellationToken); @@ -117,19 +122,20 @@ public async Task Download(AvailableRelease release, string runtime, str var expected = Checksum(System.Text.Encoding.UTF8.GetString(sumBytes), name); Directory.CreateDirectory(directory); var destination = Path.Combine(directory, name); + var created = false; try { using var response = await Get(AssetUri(release, name), cancellationToken); response.EnsureSuccessStatusCode(); await using (var source = await response.Content.ReadAsStreamAsync(cancellationToken)) await using (var file = new FileStream(destination, FileMode.CreateNew, FileAccess.Write, FileShare.None)) - { await CopyBounded(source, file, MaximumArchiveBytes, cancellationToken); } + { created = true; await CopyBounded(source, file, MaximumArchiveBytes, cancellationToken); } if (new FileInfo(destination).Length != archive.Size) throw new IOException("Download length does not match the release metadata."); var hash = InstallationManifest.Hash(destination); if (!hash.Equals(expected, StringComparison.OrdinalIgnoreCase) || archive.Digest is { } digest && !digest.Equals("sha256:" + hash, StringComparison.OrdinalIgnoreCase)) throw new IOException("SHA-256 verification failed; installation was not changed."); return destination; } - catch { File.Delete(destination); throw; } + catch { if (created) File.Delete(destination); throw; } } private static Uri AssetUri(AvailableRelease release, string asset) => new($"https://github.com/{Repository}/releases/download/{Uri.EscapeDataString(release.Tag)}/{Uri.EscapeDataString(asset)}"); public static string Checksum(string text, string filename) diff --git a/src/SidePulse.Core/UpdatePackage.cs b/src/SidePulse.Core/UpdatePackage.cs index 15dd185..7f9dfc5 100644 --- a/src/SidePulse.Core/UpdatePackage.cs +++ b/src/SidePulse.Core/UpdatePackage.cs @@ -66,7 +66,12 @@ public static async Task Extract(string archive, string de if (Directory.Exists(destination)) throw new IOException("Update staging directory already exists."); Directory.CreateDirectory(destination); var names = new HashSet(StringComparer.OrdinalIgnoreCase); - long total = 0; var count = 0; + long total = 0; var count = 0; var entries = 0; + void CountEntry() + { + if (++entries > 10000) throw new IOException("Update archive exceeds its entry limit."); + cancellationToken.ThrowIfCancellationRequested(); + } async Task ExtractFile(string name, long length, Stream source) { name = InstallationManifest.Relative(name); @@ -84,6 +89,7 @@ async Task ExtractFile(string name, long length, Stream source) using var zip = ZipFile.OpenRead(archive); foreach (var entry in zip.Entries) { + CountEntry(); var kind = (entry.ExternalAttributes >> 16) & 0xf000; if (kind is not (0 or 0x8000 or 0x4000)) throw new IOException("Links and special files are not allowed in update archives."); if (entry.FullName.EndsWith('/')) { InstallationManifest.Relative(entry.FullName.TrimEnd('/')); continue; } @@ -97,6 +103,7 @@ async Task ExtractFile(string name, long length, Stream source) await using var reader = new TarReader(gzip); while (await reader.GetNextEntryAsync(cancellationToken: cancellationToken) is { } entry) { + CountEntry(); var name = entry.Name.StartsWith("./", StringComparison.Ordinal) ? entry.Name[2..] : entry.Name; if (entry.EntryType == TarEntryType.Directory) { if (name is not ("" or ".")) InstallationManifest.Relative(name.TrimEnd('/')); continue; } if (entry.EntryType is not (TarEntryType.RegularFile or TarEntryType.V7RegularFile)) throw new IOException("Links and special files are not allowed in update archives."); diff --git a/tests/SidePulse.Tests/AgentTests.cs b/tests/SidePulse.Tests/AgentTests.cs index ced925e..25baef5 100644 --- a/tests/SidePulse.Tests/AgentTests.cs +++ b/tests/SidePulse.Tests/AgentTests.cs @@ -89,6 +89,38 @@ public void InstallationPreviewMergeAndUninstallPreserveUnrelatedSettingsExactly Assert.Equal(original, File.ReadAllText(target)); }); } + [Theory] + [InlineData(AgentProvider.Codex)] + [InlineData(AgentProvider.Copilot)] + public void ReinstallWithADifferentExecutableFailsWithoutChangingFiles(AgentProvider provider) + { + WithDirectory(directory => + { + var target = Path.Combine(directory, "hooks.json"); + var installer = new HookInstallation(Path.Combine(directory, "manifests")); + installer.Install(target, provider, HookConfiguration.Generate(provider, "/old/sidepulse-net", false), false); + var before = File.ReadAllBytes(target); + var error = Assert.Throws(() => installer.Install(target, provider, HookConfiguration.Generate(provider, "/new/sidepulse-net", false), false)); + Assert.Contains("Uninstall", error.Message); + Assert.Equal(before, File.ReadAllBytes(target)); + }); + } + [Fact] + public void UninstallPreviewDoesNotCreateALockFile() + { + WithDirectory(directory => + { + var target = Path.Combine(directory, "hooks.json"); + var installer = new HookInstallation(Path.Combine(directory, "manifests")); + installer.Install(target, AgentProvider.Codex, HookConfiguration.Generate(AgentProvider.Codex, "/tmp/sidepulse-net", false), false); + var before = File.ReadAllBytes(target); + File.Delete(target + ".sidepulse-net.lock"); + Assert.Equal("preview-remove", installer.Uninstall(target, true).State); + Assert.False(File.Exists(target + ".sidepulse-net.lock")); + Assert.Equal(before, File.ReadAllBytes(target)); + Assert.Equal("installed", installer.Status(target).State); + }); + } [Fact] public void UninstallRefusesChangedSettingsAndInvalidInputIsNotOverwritten() { diff --git a/tests/SidePulse.Tests/UpdateTests.cs b/tests/SidePulse.Tests/UpdateTests.cs index 41585f3..b986023 100644 --- a/tests/SidePulse.Tests/UpdateTests.cs +++ b/tests/SidePulse.Tests/UpdateTests.cs @@ -81,6 +81,42 @@ public async Task HashVerificationPrecedesExtractionAndRejectsCorruption() Assert.False(File.Exists(path)); } [Fact] + public async Task DownloadCollisionPreservesTheExistingFile() + { + using var temp = new Temp(); + var name = GitHubReleases.AssetName("win-x64"); + var path = System.IO.Path.Combine(temp.Path, name); + File.WriteAllText(path, "personal file"); + var sums = new string('a', 64) + " " + name + "\n"; + using var client = new HttpClient(new Handler(request => new(HttpStatusCode.OK) + { Content = new StringContent(request.RequestUri!.AbsolutePath.EndsWith("SHA256SUMS", StringComparison.Ordinal) ? sums : "package") })); + var release = new AvailableRelease("v1.0.0", "1.0.0", false, "ignored", [new(name, 7, null), new("SHA256SUMS", sums.Length, null)]); + await Assert.ThrowsAsync(() => new GitHubReleases(client).Download(release, "win-x64", temp.Path)); + Assert.Equal("personal file", File.ReadAllText(path)); + } + [Fact] + public async Task ReleaseBodyReadHonorsCancellationAfterHeaders() + { + using var client = new HttpClient(new Handler(_ => new(HttpStatusCode.OK) { Content = new StreamContent(new WaitingStream()) })) { Timeout = TimeSpan.FromMilliseconds(100) }; + await Assert.ThrowsAnyAsync(() => new GitHubReleases(client).Latest(false)); + } + private sealed class WaitingStream : MemoryStream + { + public override async ValueTask ReadAsync(Memory buffer, CancellationToken cancellationToken = default) + { await Task.Delay(Timeout.Infinite, cancellationToken); return 0; } + } + [Fact] + public async Task DirectoryOnlyArchiveEntriesAreBounded() + { + using var temp = new Temp(); + var archive = System.IO.Path.Combine(temp.Path, "directories.zip"); + using (var zip = ZipFile.Open(archive, ZipArchiveMode.Create)) + for (var i = 0; i <= 10000; i++) zip.CreateEntry($"directory-{i}/"); + var error = await Assert.ThrowsAsync(() => UpdatePackage.Extract(archive, System.IO.Path.Combine(temp.Path, "stage"), "1.0.0", "win-x64")); + Assert.Contains("entry limit", error.Message); + Assert.False(Directory.Exists(System.IO.Path.Combine(temp.Path, "stage"))); + } + [Fact] public void MissingOrAmbiguousChecksumIsRefused() { var hash = new string('a', 64); From c90c97357b56813c42cde4fc867da735b9ba5d14 Mon Sep 17 00:00:00 2001 From: Gordon Breuer Date: Sat, 24 Oct 2026 01:23:31 +0200 Subject: [PATCH 20/26] Record current preview scope and expose CodeQL findings for review --- .github/workflows/security.yml | 13 ++++++++ README.md | 30 +++++++++++-------- .../decisions/0002-runtime-and-coexistence.md | 7 +++-- tests/SidePulse.Tests/UpdateTests.cs | 2 +- 4 files changed, 37 insertions(+), 15 deletions(-) diff --git a/.github/workflows/security.yml b/.github/workflows/security.yml index c979e3a..8fd3e37 100644 --- a/.github/workflows/security.yml +++ b/.github/workflows/security.yml @@ -49,6 +49,19 @@ jobs: - uses: github/codeql-action/analyze@9b3254085494b55a0f7c4c2b3d2d52cc712ce370 # v4 with: category: '/language:${{ matrix.language }}' + output: codeql-results + - name: Summarize scan findings + if: always() + run: | + python3 - <<'PYCODE' + import json + from pathlib import Path + for report in sorted(Path('codeql-results').glob('*.sarif')): + for run in json.loads(report.read_text()).get('runs', []): + for result in run.get('results', []): + locations = [item.get('physicalLocation', {}) for item in result.get('locations', [])] + print(json.dumps({'rule': result.get('ruleId'), 'message': result.get('message'), 'locations': locations})) + PYCODE dependencies: name: Dependency review if: github.event_name == 'pull_request' diff --git a/README.md b/README.md index 9188958..b825170 100644 --- a/README.md +++ b/README.md @@ -10,19 +10,24 @@ SidePulse.NET brings the SidePulse workflow to Windows, macOS and Linux: pair a phone or connect a USB device, enable an agent integration, and see when an agent is working, waiting for input or finished. -## Planned experience +## Preview functionality -- A live terminal dashboard for devices, agent sessions and recent events. -- Fast, silent commands for hooks and scripts, alongside interactive setup. +- Cursor menus, script-command review/copy/export, plain/quiet/JSON output. - Copilot CLI, Codex, Claude Code and Kiro CLI V3 hooks with shared status aggregation. -- USB LED programs, iPhone linking and bridge delivery, animation previews and profiles. -- Reliable session aggregation, device aliases, diagnostics and explicit configuration migration. -- Self-contained Windows, macOS and Linux distributions without a Python dependency. +- Writable USB/SD LED output, iPhone linking and native protected credentials. +- Dot/Pro animation simulation, custom editor, upstream patterns and state profiles. +- Host lifecycle, bounded logs, diagnostics and phone aliases. +- Six self-contained platform/architecture packages and verified-update commands. -The proposed baseline is **C# / .NET 10 LTS**, **Spectre.Console** and +The baseline is **C# / .NET 10 LTS**, **Spectre.Console** and **Spectre.Console.Cli**. Windows, macOS and Linux are supported by the preview; see the [platform matrix](docs/wiki/Platforms.md) for native credential requirements -and architecture-specific validation. +and architecture-specific validation. No release has been published yet. + +Hardware/firmware, real provider sessions and the public release/update flow still +need acceptance evidence. A live dashboard, device aliases, explicit Python +migration, remote relay and read-only transports remain planned. See the +[architecture and QA review](docs/reviews/pr-12.md) and [open issues](https://github.com/Anheledir/SidePulse.NET/issues). ## Documentation @@ -36,10 +41,11 @@ The editable source of truth lives in [docs/wiki](docs/wiki/Home.md). - [Copilot integration](docs/wiki/Copilot-CLI.md) - [Roadmap and acceptance criteria](docs/wiki/Roadmap.md) - [Repository and automation setup](docs/wiki/Project-Setup.md) +- [Security policy](SECURITY.md) and [observed/desired repository settings](docs/repository-settings.md) ## Original project and attribution -This project is inspired by and plans to port functionality from +This project ports selected functionality from [**inteliwear/sidepulse**](https://github.com/inteliwear/sidepulse), created by **Peter Kuhar / InteliWEAR**, and the [SidePulse hardware](https://sidepulse.io/). It is independently maintained and is not an official InteliWEAR product. @@ -60,9 +66,9 @@ dotnet run --project src/SidePulse.Cli -- dashboard The solution contains a portable core, a Spectre.Console CLI and behavioral tests. -Implemented commands: `devices`, `state`, `write`, `dashboard`, `host`, -`hook-config`, `doctor`, `agents list/install/status/uninstall`, host lifecycle -commands and `link pair/list/import/default/rename/remove`. Use `--help` for details and `--dry-run` before sending a program. +Command groups include `devices`, `state`, `write`, `dashboard`, `host`, `agents`, +`link`, `animations`, `profiles`, `about`, `docs` and `update`. Use `--help` for +subcommands and `--dry-run` where supported before changing files or sending a program. The command name `sidepulse-net` coexists with the existing Python port. QR pairing and protected token storage use DPAPI on Windows, Keychain on macOS diff --git a/docs/decisions/0002-runtime-and-coexistence.md b/docs/decisions/0002-runtime-and-coexistence.md index ec5078d..182a4c2 100644 --- a/docs/decisions/0002-runtime-and-coexistence.md +++ b/docs/decisions/0002-runtime-and-coexistence.md @@ -6,8 +6,11 @@ A local background host will own event reduction, per-session state and device outputs. Hook adapters will enqueue small events over authenticated local IPC. The Spectre dashboard and noninteractive commands will use the same state owner. -Windows named pipes scoped to the current user are the preferred initial IPC -transport. Transport details, restart recovery and latency budgets need a prototype. +Current-user .NET named pipes are implemented on all three desktop platforms. +Hooks have a 600ms budget; host control has a two-second deadline. Native CI +exercises host lifecycle and Unix endpoint crash recovery. Protocol negotiation, +session restart persistence and retention policy remain open decisions in #5; +restart currently begins Unknown and CLI/host versions must match. Use `sidepulse-net` as the initial command to coexist with the existing Python `sidepulse`. Offer a `sidepulse` alias only by explicit choice. Store new settings diff --git a/tests/SidePulse.Tests/UpdateTests.cs b/tests/SidePulse.Tests/UpdateTests.cs index b986023..2915858 100644 --- a/tests/SidePulse.Tests/UpdateTests.cs +++ b/tests/SidePulse.Tests/UpdateTests.cs @@ -98,7 +98,7 @@ public async Task DownloadCollisionPreservesTheExistingFile() public async Task ReleaseBodyReadHonorsCancellationAfterHeaders() { using var client = new HttpClient(new Handler(_ => new(HttpStatusCode.OK) { Content = new StreamContent(new WaitingStream()) })) { Timeout = TimeSpan.FromMilliseconds(100) }; - await Assert.ThrowsAnyAsync(() => new GitHubReleases(client).Latest(false)); + await Assert.ThrowsAnyAsync(() => new GitHubReleases(client).Latest(false).WaitAsync(TimeSpan.FromSeconds(3))); } private sealed class WaitingStream : MemoryStream { From f1ada51a836a91e2420e507ac589e195b9990ab5 Mon Sep 17 00:00:00 2001 From: Gordon Breuer Date: Sat, 24 Oct 2026 01:27:07 +0200 Subject: [PATCH 21/26] Harden archive extraction with canonical containment and expand cross-format security tests --- docs/backlog.json | 2 +- docs/repository-settings.json | 33 ++++++++++++++++++- docs/repository-settings.md | 4 +++ docs/reviews/pr-12.md | 15 +++++++-- docs/wiki/Architecture.md | 31 +++++++++++------- src/SidePulse.Core/UpdatePackage.cs | 7 +++- tests/SidePulse.Tests/UpdateTests.cs | 49 +++++++++++++++++++++------- 7 files changed, 111 insertions(+), 30 deletions(-) diff --git a/docs/backlog.json b/docs/backlog.json index 009c1a8..a4ed7a4 100644 --- a/docs/backlog.json +++ b/docs/backlog.json @@ -46,7 +46,7 @@ "labels": [ "enhancement" ], - "body": "Priority: P1 lifecycle/compatibility specification. Status: shared host implemented in PR #12.\n\n- [x] Current-user IPC, single-host lease, bounded requests, ACKed control RPC, independent bounded output queue.\n- [x] Provider-namespaced sessions; out-of-order timestamp rejection; Waiting > Working > Error > Done > Idle > Unknown; error survives Stop.\n- [x] Detached start/status/stop/logs and Unix crash recovery exercised in native CI.\n- [ ] Decide and implement explicit IPC protocol version negotiation before supporting mixed CLI/host versions. Currently require same version and stop host for upgrade.\n- [ ] Resolve restart semantics: implementation intentionally starts Unknown and does not persist sessions; original minimal-restart-metadata requirement is deferred, not complete.\n- [ ] Specify retention/recovery for 1,024 live/error sessions and long-lived abandoned sessions; provide an explicit reset/removal policy without inventing agent completion.\n\nAcceptance: hooks remain silent and bounded, never wait for network or change permission decisions. Keep restart/version/retention decisions testable.\n\nReviewed against PR #12 (unmerged alpha), 2026-10-23. Checked items mean implemented in that PR, not released or hardware-certified. Evidence: [native CI baseline](https://github.com/Anheledir/SidePulse.NET/actions/runs/40037463280), source and tests in PR #12; [architecture/QA review](https://github.com/Anheledir/SidePulse.NET/blob/implementation/first-preview/docs/reviews/pr-12.md). Keep this issue open until its remaining acceptance criteria are met." + "body": "Priority: P1 lifecycle/compatibility specification. Status: shared host implemented in PR #12.\n\n- [x] Current-user IPC, single-host lease, bounded requests, ACKed control RPC, independent bounded output queue.\n- [x] Provider-namespaced sessions; out-of-order timestamp rejection; Waiting > Working > Error > Done > Idle > Unknown; error survives Stop.\n- [x] Detached start/status/stop/logs and Unix crash recovery exercised in native CI.\n- [ ] Decide and implement explicit IPC protocol version negotiation before supporting mixed CLI/host versions. Currently require same version and stop host for upgrade.\n- [ ] Resolve restart semantics: implementation intentionally starts Unknown and does not persist sessions; original minimal-restart-metadata requirement is deferred, not complete.\n- [ ] Specify retention/recovery for 1,024 live/error sessions and long-lived abandoned sessions; provide an explicit reset/removal policy without inventing agent completion.\n- [ ] Define direct-command arbitration: state/write/animation apply currently bypass host serialization and can replace its output; either document manual override semantics or route them through the host.\n\nAcceptance: hooks remain silent and bounded, never wait for network or change permission decisions. Keep restart/version/retention decisions testable.\n\nReviewed against PR #12 (unmerged alpha), 2026-10-23. Checked items mean implemented in that PR, not released or hardware-certified. Evidence: [native CI baseline](https://github.com/Anheledir/SidePulse.NET/actions/runs/40037463280), source and tests in PR #12; [architecture/QA review](https://github.com/Anheledir/SidePulse.NET/blob/implementation/first-preview/docs/reviews/pr-12.md). Keep this issue open until its remaining acceptance criteria are met." }, { "title": "M1: Implement phone pairing and bridge delivery", diff --git a/docs/repository-settings.json b/docs/repository-settings.json index f8bd52b..9950863 100644 --- a/docs/repository-settings.json +++ b/docs/repository-settings.json @@ -20,7 +20,19 @@ "desired": { "description": "Unofficial cross-platform SidePulse companion in C# and Spectre.Console: agent status hooks, LED patterns, iPhone pairing and verified updates.", "homepage": "https://github.com/Anheledir/SidePulse.NET/wiki", - "topics": ["sidepulse", "dotnet", "csharp", "spectre-console", "cli", "cross-platform", "github-copilot", "codex", "claude-code", "kiro", "led"], + "topics": [ + "sidepulse", + "dotnet", + "csharp", + "spectre-console", + "cli", + "cross-platform", + "github-copilot", + "codex", + "claude-code", + "kiro", + "led" + ], "hasProjects": true, "privateVulnerabilityReporting": true, "dependabotAlerts": true, @@ -45,5 +57,24 @@ "securityAndAnalysis": "Not exposed by repository response; unknown, not assumed disabled.", "projects": "Repository Projects feature observed disabled. No project board has been created.", "appliedRemoteSettings": [] + }, + "verifiedPullRequestChecks": { + "commit": "1839c3d763f4bcaa3762cbc8958c9183742181a8", + "nativeCI": "https://github.com/Anheledir/SidePulse.NET/actions/runs/40039097045", + "nativeTestsPerOS": 96, + "quality": "passed", + "dependencyReview": "passed", + "codeQL": "Initial combined check failed: one high-severity cs/zipslip alert. Canonical containment hardening awaits reanalysis.", + "observedCheckNames": [ + "documentation", + "build (windows-latest)", + "build (ubuntu-latest)", + "build (macos-latest)", + "CodeQL (csharp)", + "CodeQL (python)", + "CodeQL (actions)", + "Dependency review", + "CodeQL" + ] } } diff --git a/docs/repository-settings.md b/docs/repository-settings.md index f7597b6..41dc724 100644 --- a/docs/repository-settings.md +++ b/docs/repository-settings.md @@ -26,6 +26,10 @@ admin settings have been changed in this review. It does not replace checking existing dependencies or advisory triage. - All third-party Actions are pinned. Default permissions are `contents: read`; only jobs that need publication or SARIF upload receive write permissions. +- The initial native review-fix CI passed 96 tests per OS and dependency review. + All three CodeQL analyses ran; the combined check reported one high-severity + Zip Slip alert. Canonical containment hardening is being reanalyzed. Scan-job + success alone is not a clean CodeQL result. Check names are recorded in JSON. - SECURITY.md supplies reporting guidance and documents updater/IPC trust limits. - Wiki publishing and upstream review run only from the default branch. diff --git a/docs/reviews/pr-12.md b/docs/reviews/pr-12.md index 6585ed6..37e6e0d 100644 --- a/docs/reviews/pr-12.md +++ b/docs/reviews/pr-12.md @@ -34,6 +34,8 @@ acceptance and the public update/release path remain explicit release gates. | R7 | P2 preservation window | User-added files are copied at update preparation; edits before replacement are not recopied. | Tracked in #10 and documented in SECURITY.md. Later edits remain in retained backup; do not claim concurrent-edit preservation. | | R8 | P1 release evidence | Updater smoke prepares a helper plan directly. It does not exercise the complete public install command against published assets. Tag publication has not run and there is no published release. | Open release gate in #10; controlled published-preview test required before announcing self-update ready for general use. No release/tag created in this review. | | R9 | P1 compatibility evidence | Simulated LED output and generated agent wrappers are not real firmware, iOS or provider acceptance. | Open criteria in #2/#3/#4/#6/#9 with versioned evidence required. | +| R11 | High scanner finding / P1 triage | Initial C# CodeQL reported `cs/zipslip` at ZIP extraction. Existing portable-name validation rejected traversal in tests, so an escape was not reproduced. | Added final canonical full-path containment with a directory-separator boundary, retaining the portable-name checks. Extended tar/ZIP traversal and directory-count tests. No rule suppression or alert dismissal; require a clean rerun. | +| R12 | P2 architecture | Target architecture claimed every writer used the host, but direct state/write/animation commands send independently. | Corrected architecture documentation; #5 now tracks arbitration/manual-override policy. Stop the host for manual device checks. | | R10 | P2 governance | Metadata says concept stage; homepage/topics empty, Projects disabled. Admin/security values cannot be verified with this GitHub App. | Observed and desired values recorded in repository-settings.json/md. Unknown controls are not called disabled or configured. | P1 means fix before merge when it is a reproducible defect (R1), or satisfy before @@ -81,9 +83,16 @@ correctness, resilience or explicit follow-up decisions. No self-approval is giv wrappers and self-contained helper replacement/rollback. Those results precede these fixes. Native executed architectures: Windows x64, Linux x64, macOS ARM64; the other three packages were cross-built, not executed. -- Post-review native CI, CodeQL, dependency review and documentation checks must - be linked from the PR after the review commit. A workflow file alone is not a - successful security scan. +- Review-fix [native CI](https://github.com/Anheledir/SidePulse.NET/actions/runs/40039097045) + passed **96 tests on each OS**, including native updater replacement/rollback. + Quality and dependency review passed. Initial CodeQL scans executed successfully, + but the combined CodeQL check failed with one high-severity `cs/zipslip` alert; + a successful analysis job alone is not a clean security result. +- Canonical containment hardening and additional archive cases are a subsequent + change. The local Release suite now passes **104 tests**, including both archive + formats and sibling-directory traversal cases. Its native tests/security results + must be checked before merge. + No scanner finding has been suppressed or dismissed. ## Issue disposition diff --git a/docs/wiki/Architecture.md b/docs/wiki/Architecture.md index 3a41c47..17b1e95 100644 --- a/docs/wiki/Architecture.md +++ b/docs/wiki/Architecture.md @@ -1,7 +1,8 @@ # Architecture -Status: target architecture. The first preview implements a core library, CLI, -foreground host and current-user IPC. See [[Getting-Started]] for limitations. +Status: implemented preview boundaries plus explicit future decisions. The solution +contains Core and CLI projects, with foreground/detached host commands and +current-user IPC. See [[Getting-Started]] and the PR #12 review for limitations. ## Boundaries @@ -14,9 +15,13 @@ foreground host and current-user IPC. See [[Getting-Started]] for limitations. | CLI | Spectre.Console.Cli commands and Spectre.Console presentation | | Tests | Reducer, protocol, adapter contracts, rendered output and hardware smoke checks | -The UI never owns device transport state. All writers submit intents to one host, -so a background service, dashboard and hook cannot independently overwrite LEDs. -A foreground-only mode should be possible for diagnosis and restricted machines. +Hook-driven output is serialized by the host. Direct `state`, `write` and animation +apply commands send independently and can overwrite a running host's pattern. +They are explicit one-shot operations, not clients of a global output arbiter. +Stop the host before manual device checks. Coordinating direct writers with a +running host remains a decision in #5; do not claim exclusive device ownership. +The Application/Transports rows describe logical responsibilities, not additional +projects; migration, relay and persistence in this table are future work. ## Events and aggregation @@ -25,21 +30,23 @@ last observation. Use explicit lifecycle events and ignore out-of-order events. A finished subagent does not finish its parent session. Cancellation, agent errors, recoverable tool errors and loss of observation remain distinguishable. -Proposed aggregation: waiting for user input takes priority, followed by active +Implemented aggregation: waiting for user input takes priority, followed by active work; show unhandled errors when nothing is actively working; completion only when no tracked session remains active. Idle and unknown are separate states. -The exact policy is a design decision to validate with realistic event traces. +Tests cover the reducer; validate the policy further with real provider traces. ## Local event path Hook adapters enqueue minimal metadata and return quickly. The host handles -network I/O, deduplication, bounded retries and transport diagnostics asynchronously. +network I/O asynchronously through a bounded latest-state queue. Repeated events +can retry delivery; there is no durable retry queue or separate event deduplication. On Windows use current-user-restricted named pipes; do not open a network listener just to receive local hook events. Document protocol versioning and startup races. ## Failure and restart behavior -Persist enough metadata for restart recovery without storing prompts or tool -arguments. After restart, stale work becomes unknown until refreshed by evidence. -Do not infer successful completion from an expired heartbeat. Use bounded queues -and expose dropped events or undelivered outputs in diagnostics. +Restart currently begins Unknown with an empty session table; no session metadata +is persisted. Do not infer successful completion from an expired heartbeat. +Protocol negotiation, restart metadata and session retention are tracked in #5. +The output queue is bounded and can drop older states while keeping the latest. +Undelivered output is logged, but there is no per-session delivery history. diff --git a/src/SidePulse.Core/UpdatePackage.cs b/src/SidePulse.Core/UpdatePackage.cs index 7f9dfc5..da5249a 100644 --- a/src/SidePulse.Core/UpdatePackage.cs +++ b/src/SidePulse.Core/UpdatePackage.cs @@ -76,7 +76,12 @@ async Task ExtractFile(string name, long length, Stream source) { name = InstallationManifest.Relative(name); if (++count > 10000 || length < 0 || length > 512L * 1024 * 1024 || (total += length) > 1024L * 1024 * 1024 || !names.Add(name)) throw new IOException("Update archive exceeds its limits or contains duplicate paths."); - var path = InstallationManifest.Resolve(destination, name); + // Validate the final canonical path as well as the portable manifest name. + // Include the separator so a sibling with the same prefix is never accepted. + var path = Path.GetFullPath(InstallationManifest.Resolve(destination, name)); + var root = Path.GetFullPath(destination).TrimEnd(Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar; + if (!path.StartsWith(root, OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal)) + throw new IOException("Archive entry is outside the staging directory."); Directory.CreateDirectory(Path.GetDirectoryName(path)!); await using var output = new FileStream(path, FileMode.CreateNew, FileAccess.Write, FileShare.None); await GitHubReleases.CopyBounded(source, output, length, cancellationToken); diff --git a/tests/SidePulse.Tests/UpdateTests.cs b/tests/SidePulse.Tests/UpdateTests.cs index 2915858..8d23b91 100644 --- a/tests/SidePulse.Tests/UpdateTests.cs +++ b/tests/SidePulse.Tests/UpdateTests.cs @@ -105,12 +105,21 @@ private sealed class WaitingStream : MemoryStream public override async ValueTask ReadAsync(Memory buffer, CancellationToken cancellationToken = default) { await Task.Delay(Timeout.Infinite, cancellationToken); return 0; } } - [Fact] - public async Task DirectoryOnlyArchiveEntriesAreBounded() + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task DirectoryOnlyArchiveEntriesAreBounded(bool tarFormat) { using var temp = new Temp(); - var archive = System.IO.Path.Combine(temp.Path, "directories.zip"); - using (var zip = ZipFile.Open(archive, ZipArchiveMode.Create)) + var archive = System.IO.Path.Combine(temp.Path, tarFormat ? "directories.tar.gz" : "directories.zip"); + if (tarFormat) + { + using var output = File.Create(archive); + using var gzip = new GZipStream(output, CompressionMode.Compress); + using var tar = new TarWriter(gzip); + for (var i = 0; i <= 10000; i++) tar.WriteEntry(new PaxTarEntry(TarEntryType.Directory, $"directory-{i}/")); + } + else using (var zip = ZipFile.Open(archive, ZipArchiveMode.Create)) for (var i = 0; i <= 10000; i++) zip.CreateEntry($"directory-{i}/"); var error = await Assert.ThrowsAsync(() => UpdatePackage.Extract(archive, System.IO.Path.Combine(temp.Path, "stage"), "1.0.0", "win-x64")); Assert.Contains("entry limit", error.Message); @@ -125,19 +134,35 @@ public void MissingOrAmbiguousChecksumIsRefused() Assert.Equal(hash, GitHubReleases.Checksum(hash + " *package.zip\r\n", "package.zip")); } [Theory] - [InlineData("../escaped.txt")] - [InlineData("/absolute.txt")] - [InlineData("C:/absolute.txt")] - [InlineData("sub\\escaped.txt")] - [InlineData("sub/../escaped.txt")] - public async Task ArchivePathsCannotEscapeStaging(string path) + [InlineData("../escaped.txt", false)] + [InlineData("/absolute.txt", false)] + [InlineData("C:/absolute.txt", false)] + [InlineData("sub\\escaped.txt", false)] + [InlineData("sub/../escaped.txt", false)] + [InlineData("../stage-sibling/escaped.txt", false)] + [InlineData("../escaped.txt", true)] + [InlineData("/absolute.txt", true)] + [InlineData("C:/absolute.txt", true)] + [InlineData("sub\\escaped.txt", true)] + [InlineData("sub/../escaped.txt", true)] + [InlineData("../stage-sibling/escaped.txt", true)] + public async Task ArchivePathsCannotEscapeStaging(string path, bool tarFormat) { - using var temp = new Temp(); var archive = System.IO.Path.Combine(temp.Path, "bad.zip"); - using (var zip = ZipFile.Open(archive, ZipArchiveMode.Create)) { using var writer = new StreamWriter(zip.CreateEntry(path).Open()); writer.Write("bad"); } + using var temp = new Temp(); var archive = System.IO.Path.Combine(temp.Path, tarFormat ? "bad.tar.gz" : "bad.zip"); + if (tarFormat) + { + using var output = File.Create(archive); + using var gzip = new GZipStream(output, CompressionMode.Compress); + using var tar = new TarWriter(gzip); + using var bytes = new MemoryStream(Encoding.UTF8.GetBytes("bad")); + tar.WriteEntry(new PaxTarEntry(TarEntryType.RegularFile, path) { DataStream = bytes }); + } + else using (var zip = ZipFile.Open(archive, ZipArchiveMode.Create)) { using var writer = new StreamWriter(zip.CreateEntry(path).Open()); writer.Write("bad"); } var stage = System.IO.Path.Combine(temp.Path, "stage"); await Assert.ThrowsAsync(() => UpdatePackage.Extract(archive, stage, "1.0.0", "linux-x64")); Assert.False(Directory.Exists(stage)); Assert.False(File.Exists(System.IO.Path.Combine(temp.Path, "escaped.txt"))); + Assert.False(File.Exists(System.IO.Path.Combine(temp.Path, "stage-sibling", "escaped.txt"))); } [Theory] [InlineData(false)] From f23c1fe320665832d462949d6e9e4e2c9fcfe533 Mon Sep 17 00:00:00 2001 From: Gordon Breuer Date: Sat, 24 Oct 2026 01:31:16 +0200 Subject: [PATCH 22/26] Record successful native QA and clean security results for reviewed code --- docs/repository-settings.json | 24 ++++++++++++++++++------ docs/repository-settings.md | 14 +++++++++----- docs/reviews/pr-12.md | 11 ++++++++--- 3 files changed, 35 insertions(+), 14 deletions(-) diff --git a/docs/repository-settings.json b/docs/repository-settings.json index 9950863..53cd034 100644 --- a/docs/repository-settings.json +++ b/docs/repository-settings.json @@ -48,7 +48,18 @@ "requireUpToDateBranch": true, "blockForcePushes": true, "blockDeletion": true, - "requiredChecksPolicy": "Require Quality, all three native build jobs, CodeQL and dependency review after successful check names are observed." + "requiredChecksPolicy": "Require Quality, all three native build jobs, CodeQL and dependency review after successful check names are observed.", + "requiredCheckNames": [ + "documentation", + "build (windows-latest)", + "build (ubuntu-latest)", + "build (macos-latest)", + "CodeQL (csharp)", + "CodeQL (python)", + "CodeQL (actions)", + "Dependency review", + "CodeQL" + ] } }, "verificationLimits": { @@ -59,12 +70,12 @@ "appliedRemoteSettings": [] }, "verifiedPullRequestChecks": { - "commit": "1839c3d763f4bcaa3762cbc8958c9183742181a8", - "nativeCI": "https://github.com/Anheledir/SidePulse.NET/actions/runs/40039097045", - "nativeTestsPerOS": 96, + "commit": "f1ada51a836a91e2420e507ac589e195b9990ab5", + "nativeCI": "https://github.com/Anheledir/SidePulse.NET/actions/runs/40039767890", + "nativeTestsPerOS": 104, "quality": "passed", "dependencyReview": "passed", - "codeQL": "Initial combined check failed: one high-severity cs/zipslip alert. Canonical containment hardening awaits reanalysis.", + "codeQL": "C#, Python and Actions analyses passed; combined CodeQL check reports no new alerts after canonical containment hardening. No suppression or dismissal.", "observedCheckNames": [ "documentation", "build (windows-latest)", @@ -75,6 +86,7 @@ "CodeQL (actions)", "Dependency review", "CodeQL" - ] + ], + "securityRun": "https://github.com/Anheledir/SidePulse.NET/actions/runs/40039767819" } } diff --git a/docs/repository-settings.md b/docs/repository-settings.md index 41dc724..1c6089b 100644 --- a/docs/repository-settings.md +++ b/docs/repository-settings.md @@ -26,10 +26,12 @@ admin settings have been changed in this review. It does not replace checking existing dependencies or advisory triage. - All third-party Actions are pinned. Default permissions are `contents: read`; only jobs that need publication or SARIF upload receive write permissions. -- The initial native review-fix CI passed 96 tests per OS and dependency review. - All three CodeQL analyses ran; the combined check reported one high-severity - Zip Slip alert. Canonical containment hardening is being reanalyzed. Scan-job - success alone is not a clean CodeQL result. Check names are recorded in JSON. +- Final reviewed code `f1ada51` passed 104 tests per OS in + [native CI](https://github.com/Anheledir/SidePulse.NET/actions/runs/40039767890), + including updater replacement/rollback. Quality and dependency review passed. + [All three CodeQL analyses and the combined alert check](https://github.com/Anheledir/SidePulse.NET/actions/runs/40039767819) + passed after canonical containment hardening. The combined result reports no new + alerts. No rule was suppressed or alert dismissed. Exact check names are in JSON. - SECURITY.md supplies reporting guidance and documents updater/IPC trust limits. - Wiki publishing and upstream review run only from the default branch. @@ -50,7 +52,9 @@ Protect main with PRs, resolved conversations, current checks, and blocked branc force-push/deletion. For this personal repository use zero required approvals so the sole maintainer is not locked out by GitHub's self-approval restriction. Require exact successful check contexts only after they have run: documentation, -all three native build jobs, CodeQL for C#/Python/Actions, and dependency review. +all three native build jobs, CodeQL for C#/Python/Actions, the combined `CodeQL` +alert check, and dependency review. Analysis-job success alone does not imply no +security alerts; require the combined alert check as well. Do not invent check names or enforce checks that have never completed. Record each applied change, observed value and date here and in JSON. If an option diff --git a/docs/reviews/pr-12.md b/docs/reviews/pr-12.md index 37e6e0d..bfea9e4 100644 --- a/docs/reviews/pr-12.md +++ b/docs/reviews/pr-12.md @@ -34,7 +34,7 @@ acceptance and the public update/release path remain explicit release gates. | R7 | P2 preservation window | User-added files are copied at update preparation; edits before replacement are not recopied. | Tracked in #10 and documented in SECURITY.md. Later edits remain in retained backup; do not claim concurrent-edit preservation. | | R8 | P1 release evidence | Updater smoke prepares a helper plan directly. It does not exercise the complete public install command against published assets. Tag publication has not run and there is no published release. | Open release gate in #10; controlled published-preview test required before announcing self-update ready for general use. No release/tag created in this review. | | R9 | P1 compatibility evidence | Simulated LED output and generated agent wrappers are not real firmware, iOS or provider acceptance. | Open criteria in #2/#3/#4/#6/#9 with versioned evidence required. | -| R11 | High scanner finding / P1 triage | Initial C# CodeQL reported `cs/zipslip` at ZIP extraction. Existing portable-name validation rejected traversal in tests, so an escape was not reproduced. | Added final canonical full-path containment with a directory-separator boundary, retaining the portable-name checks. Extended tar/ZIP traversal and directory-count tests. No rule suppression or alert dismissal; require a clean rerun. | +| R11 | High scanner finding / P1 triage | Initial C# CodeQL reported `cs/zipslip` at ZIP extraction. Existing portable-name validation rejected traversal in tests, so an escape was not reproduced. | Added final canonical full-path containment with a directory-separator boundary, retaining the portable-name checks. Extended tar/ZIP traversal and directory-count tests. No rule suppression or alert dismissal. The final combined CodeQL check passed with no new alerts. | | R12 | P2 architecture | Target architecture claimed every writer used the host, but direct state/write/animation commands send independently. | Corrected architecture documentation; #5 now tracks arbitration/manual-override policy. Stop the host for manual device checks. | | R10 | P2 governance | Metadata says concept stage; homepage/topics empty, Projects disabled. Admin/security values cannot be verified with this GitHub App. | Observed and desired values recorded in repository-settings.json/md. Unknown controls are not called disabled or configured. | @@ -91,8 +91,13 @@ correctness, resilience or explicit follow-up decisions. No self-approval is giv - Canonical containment hardening and additional archive cases are a subsequent change. The local Release suite now passes **104 tests**, including both archive formats and sibling-directory traversal cases. Its native tests/security results - must be checked before merge. - No scanner finding has been suppressed or dismissed. + passed in [native CI](https://github.com/Anheledir/SidePulse.NET/actions/runs/40039767890): + **104 tests on each OS**, with updater replacement/rollback. The + [security rerun](https://github.com/Anheledir/SidePulse.NET/actions/runs/40039767819) + passed C#/Python/Actions analysis and dependency review; the combined CodeQL + check reports no new alerts. No scanner finding was suppressed or dismissed. + These results apply to `f1ada51`; the following audit-record commit changes + documentation only. Always check the PR head's required checks before merging. ## Issue disposition From 36af1bcbc360bfe086fc1ac6d62610fe07b2fc61 Mon Sep 17 00:00:00 2001 From: Gordon Breuer Date: Sat, 24 Oct 2026 02:12:14 +0200 Subject: [PATCH 23/26] Record applied GitHub security policy, active main rules and delivery board --- SECURITY.md | 6 +- docs/repository-settings.json | 206 ++++++++++++++++++++++++++++++++-- docs/repository-settings.md | 171 +++++++++++++++++----------- docs/reviews/pr-12.md | 6 +- docs/wiki/Project-Setup.md | 11 ++ 5 files changed, 319 insertions(+), 81 deletions(-) diff --git a/SECURITY.md b/SECURITY.md index b528cbc..b0ae8fb 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -8,11 +8,11 @@ the latest published preview; older previews are not maintained independently. ## Report a vulnerability Use [GitHub private vulnerability reporting](https://github.com/Anheledir/SidePulse.NET/security/advisories/new) -when enabled. If that page is unavailable, open an issue requesting a private +(enabled and verified 2026-10-24). If that page is unavailable, open an issue requesting a private reporting channel without publishing exploit details, phone tokens, credentials, logs containing secrets, or personal data. A maintainer will arrange a private -channel. Private reporting availability is tracked in the repository settings -record; this policy does not imply that it is enabled. +channel. Effective settings and subsequent changes are tracked in the repository settings +record. Please include the commit/version, OS and architecture, affected command, impact, and a minimal reproduction with redacted sample data. Coordinate publication with diff --git a/docs/repository-settings.json b/docs/repository-settings.json index 53cd034..ab06230 100644 --- a/docs/repository-settings.json +++ b/docs/repository-settings.json @@ -1,21 +1,55 @@ { "repository": "Anheledir/SidePulse.NET", - "reviewedOn": "2026-10-23", + "reviewedOn": "2026-10-24", "implementationPullRequest": 12, "observed": { "visibility": "public", "defaultBranch": "main", - "description": "Unofficial .NET companion for SidePulse with a Spectre.Console terminal UI. Concept stage.", - "homepage": null, - "topics": [], + "description": "Unofficial cross-platform SidePulse companion in C# and Spectre.Console: agent status hooks, LED patterns, iPhone pairing and verified updates.", + "homepage": "https://github.com/Anheledir/SidePulse.NET/wiki", + "topics": [ + "sidepulse", + "dotnet", + "csharp", + "spectre-console", + "cli", + "cross-platform", + "github-copilot", + "codex", + "claude-code", + "kiro", + "led" + ], "hasIssues": true, "hasWiki": true, - "hasProjects": false, + "hasProjects": true, "deleteBranchOnMerge": true, "allowMergeCommit": false, "allowSquashMerge": true, "allowRebaseMerge": true, - "allowAutoMerge": false + "allowAutoMerge": false, + "privateVulnerabilityReporting": true, + "dependencyGraph": true, + "dependabotAlerts": true, + "dependabotSecurityUpdates": true, + "groupedSecurityUpdates": true, + "malwareAlerts": true, + "secretScanning": true, + "secretScanningPushProtection": true, + "codeQLSetup": "advanced", + "codeScanningSecurityFailureThreshold": "high or higher", + "codeScanningStandardFailureThreshold": "errors", + "releaseImmutability": true, + "wikiCollaboratorsOnly": true, + "webCommitSignoff": true, + "actionsDefaultTokenPermissions": "read", + "actionsCanCreateAndApprovePullRequests": false, + "actionsAllowedSources": "Owner and GitHub-created actions only; Marketplace creators not broadly allowed; no extra allowlist.", + "actionsRequireFullCommitSHA": true, + "forkWorkflowApproval": "all external contributors", + "retentionDays": 90, + "cacheRetentionDays": 7, + "cacheSizeGB": 10 }, "desired": { "description": "Unofficial cross-platform SidePulse companion in C# and Spectre.Console: agent status hooks, LED patterns, iPhone pairing and verified updates.", @@ -63,11 +97,10 @@ } }, "verificationLimits": { - "repositoryAdministration": "Connector has no repository settings mutation tools.", - "branchProtection": "GET returned 403 Resource not accessible by integration; unknown, not assumed disabled.", - "securityAndAnalysis": "Not exposed by repository response; unknown, not assumed disabled.", - "projects": "Repository Projects feature observed disabled. No project board has been created.", - "appliedRemoteSettings": [] + "repositoryAdministration": "The connector lacks admin mutations. Requested settings were applied in the signed-in browser, with fresh GitHub verification for ruleset creation.", + "branchProtection": "Classic branch-protection GET still excluded by integration; active ruleset verified in UI and GET /rulesets/25761788.", + "securityAndAnalysis": "Effective settings verified in browser rather than inferred from the limited repository response.", + "unperformed": "No merge, release, tag, real hardware or real provider acceptance performed." }, "verifiedPullRequestChecks": { "commit": "f1ada51a836a91e2420e507ac589e195b9990ab5", @@ -88,5 +121,156 @@ "CodeQL" ], "securityRun": "https://github.com/Anheledir/SidePulse.NET/actions/runs/40039767819" + }, + "initialObserved": { + "visibility": "public", + "defaultBranch": "main", + "description": "Unofficial .NET companion for SidePulse with a Spectre.Console terminal UI. Concept stage.", + "homepage": null, + "topics": [], + "hasIssues": true, + "hasWiki": true, + "hasProjects": false, + "deleteBranchOnMerge": true, + "allowMergeCommit": false, + "allowSquashMerge": true, + "allowRebaseMerge": true, + "allowAutoMerge": false + }, + "initialObservedOn": "2026-10-23", + "appliedRemoteChanges": [ + { + "setting": "Repository description, homepage and topics", + "result": "Saved and verified with UI plus repository API" + }, + { + "setting": "Projects feature", + "result": "Enabled" + }, + { + "setting": "Dependency malware alerts", + "result": "Enabled and saved" + }, + { + "setting": "Actions source policy", + "result": "Restricted to owner and GitHub-created actions; full commit SHA required" + }, + { + "setting": "Fork workflow approval", + "result": "Required for all external contributors" + }, + { + "setting": "Main delivery checks ruleset", + "result": "Created active, ID 25761788, default branch main, no bypass actors, zero approvals, PR/conversation/current-check requirements, deletion and force-push blocked" + } + ], + "verifiedExistingControls": [ + "Private vulnerability reporting", + "Dependency graph", + "Dependabot alerts and security updates", + "Grouped security updates", + "Secret scanning and push protection", + "Immutable releases", + "Collaborator-only wiki editing", + "Read-only Actions token default", + "Actions PR creation/approval disabled" + ], + "mainRuleset": { + "id": 25761788, + "name": "Main delivery checks", + "url": "https://github.com/Anheledir/SidePulse.NET/settings/rules/25761788", + "enforcement": "active", + "include": [ + "~DEFAULT_BRANCH" + ], + "bypassActors": [], + "requiredApprovals": 0, + "requirePullRequest": true, + "requireConversationResolution": true, + "requireUpToDateBranch": true, + "blockDeletion": true, + "blockForcePushes": true, + "requiredChecks": [ + { + "context": "documentation", + "integrationId": 15368 + }, + { + "context": "build (windows-latest)", + "integrationId": 15368 + }, + { + "context": "build (ubuntu-latest)", + "integrationId": 15368 + }, + { + "context": "build (macos-latest)", + "integrationId": 15368 + }, + { + "context": "CodeQL (csharp)", + "integrationId": 15368 + }, + { + "context": "CodeQL (python)", + "integrationId": 15368 + }, + { + "context": "CodeQL (actions)", + "integrationId": 15368 + }, + { + "context": "Dependency review", + "integrationId": 15368 + }, + { + "context": "CodeQL", + "integrationId": 57789 + } + ], + "existingDisabledRuleset": { + "id": 25757011, + "name": "Main", + "disposition": "Preserved disabled without changes" + } + }, + "project": { + "number": 5, + "name": "SidePulse.NET delivery", + "url": "https://github.com/users/Anheledir/projects/5/views/1", + "visibility": "private", + "linkedRepository": "Anheledir/SidePulse.NET", + "description": "Cross-platform SidePulse.NET delivery, compatibility evidence and release gates.", + "view": "Delivery", + "columns": [ + "Todo", + "In Progress", + "Validation", + "Done" + ], + "items": { + "Todo": [ + 11 + ], + "In Progress": [ + 5, + 7, + 8, + 9 + ], + "Validation": [ + 2, + 3, + 4, + 6, + 10, + 12 + ], + "Done": [ + 1 + ] + }, + "autoImport": "Open issues and pull requests from this repository", + "readme": "Scope, status meanings, validation evidence and attribution documented." } } diff --git a/docs/repository-settings.md b/docs/repository-settings.md index 1c6089b..080e7e1 100644 --- a/docs/repository-settings.md +++ b/docs/repository-settings.md @@ -1,68 +1,111 @@ # Repository configuration record -Reviewed 2026-10-23. [Machine-readable observed and desired values](repository-settings.json). -This record distinguishes source configuration in PR #12 from effective GitHub -settings. The implementation has not been merged or released. - -## Effective settings observed through GitHub - -The repository is public, with `main` as its default branch. Issues and Wiki are -on; Projects is off. Merged branches are deleted automatically. Squash and rebase -merges are allowed, merge commits and auto-merge are disabled. The description -still says "Concept stage", homepage is empty, and no topics are set. - -The authenticated user has an admin role, but the connected GitHub App excludes -repository administration. Branch-protection reads returned 403; security feature -states were not exposed. These controls are **unknown**, not disabled. No remote -admin settings have been changed in this review. - -## Source configuration - -- Weekly Dependabot updates for NuGet and Actions already exist. -- Security workflow adds C#, Python and Actions CodeQL analysis on PRs, main - pushes and weekly schedule. C# uses an explicit .NET 10 build. Analysis needs - repository code-scanning availability and a successful Actions run. -- PR dependency review fails on newly introduced high/critical advisories. - It does not replace checking existing dependencies or advisory triage. -- All third-party Actions are pinned. Default permissions are `contents: read`; - only jobs that need publication or SARIF upload receive write permissions. -- Final reviewed code `f1ada51` passed 104 tests per OS in - [native CI](https://github.com/Anheledir/SidePulse.NET/actions/runs/40039767890), - including updater replacement/rollback. Quality and dependency review passed. - [All three CodeQL analyses and the combined alert check](https://github.com/Anheledir/SidePulse.NET/actions/runs/40039767819) - passed after canonical containment hardening. The combined result reports no new - alerts. No rule was suppressed or alert dismissed. Exact check names are in JSON. -- SECURITY.md supplies reporting guidance and documents updater/IPC trust limits. -- Wiki publishing and upstream review run only from the default branch. - -## Admin changes to apply and verify - -Use the description, homepage and topics in the JSON record. Enable repository -Projects if a board is wanted. A repository feature switch does not create a -GitHub Projects board: create **SidePulse.NET delivery**, with description -"Cross-platform SidePulse.NET delivery, compatibility evidence and release gates", -and Todo, In progress, Validation and Done statuses; add #1 through #11 and PR #12. -Keep unfinished hardware and provider validation in Validation, not Done. - -Enable private vulnerability reporting, Dependabot alerts/security updates, -secret scanning and push protection where available. Check Actions defaults are -read-only and workflow PR approval is off. Retain existing merge choices. - -Protect main with PRs, resolved conversations, current checks, and blocked branch -force-push/deletion. For this personal repository use zero required approvals so -the sole maintainer is not locked out by GitHub's self-approval restriction. -Require exact successful check contexts only after they have run: documentation, -all three native build jobs, CodeQL for C#/Python/Actions, the combined `CodeQL` -alert check, and dependency review. Analysis-job success alone does not imply no -security alerts; require the combined alert check as well. -Do not invent check names or enforce checks that have never completed. - -Record each applied change, observed value and date here and in JSON. If an option -is unavailable, record the actual GitHub limitation rather than claiming success. -Do not create a long-lived PAT merely to work around the connector's admin scope. - -## Reference - -- [GitHub security and analysis settings](https://docs.github.com/en/repositories/managing-your-repositorys-settings-and-features/enabling-features-for-your-repository/managing-security-and-analysis-settings-for-your-repository) +Verified 2026-10-24. [Machine-readable settings and change log](repository-settings.json). +The implementation is in PR #12 and has not been merged or released. + +The GitHub connector excludes administration mutations. The requested admin work +was completed through the signed-in browser; ruleset creation required fresh +GitHub verification. Saved values were checked in the UI, metadata through the +repository API, and the active ruleset through the ruleset API. No PAT was created. + +## Changes applied + +| Setting | Effective value | +|---|---| +| Description | Unofficial cross-platform SidePulse companion in C# and Spectre.Console: agent status hooks, LED patterns, iPhone pairing and verified updates. | +| Homepage | Project wiki | +| Topics | sidepulse, dotnet, csharp, spectre-console, cli, cross-platform, github-copilot, codex, claude-code, kiro, led | +| Projects | Enabled; delivery board created and linked | +| Dependency malware alerts | Enabled | +| Actions sources | Owner and GitHub-created actions only; no broad Marketplace allowance | +| Actions revision policy | Full commit SHA required | +| External fork workflows | Approval required for all external contributors | +| Main protection | Active ruleset 25761788, described below | + +## Verified existing controls + +Private vulnerability reporting, dependency graph, Dependabot alerts/security +updates and grouped security updates were already on. Secret scanning and push +protection were already on. Releases were already immutable. Wiki editing was +already restricted to collaborators. Actions default token access was already +read-only, and Actions creation/approval of pull requests was disabled. + +CodeQL uses advanced setup. Its combined check fails for high-or-higher security +alerts and standard errors. Optional AI Scan and credit-consuming agentic autofix +remain off; existing Copilot Autofix is on. Automatic dependency submission is off. + +The repository remains public, `main` remains default, squash/rebase merges are +allowed, merge commits and auto-merge are off, and merged branches are deleted. +Existing web-commit signoff remains on. General log/artifact retention is 90 days; +preview packages request 14 days in the workflow. Cache retention/size remain +7 days/10 GB. No account, ownership or collaborator permissions were changed. + +## Main delivery checks + +[Active ruleset](https://github.com/Anheledir/SidePulse.NET/settings/rules/25761788) +targets the default branch, currently `main`, with an empty bypass list: + +- Require a pull request, resolved conversations and an up-to-date tested branch. +- Block branch deletion and force pushes. +- Require `documentation`, `build (windows-latest)`, `build (ubuntu-latest)`, + `build (macos-latest)`, `CodeQL (csharp)`, `CodeQL (python)`, `CodeQL (actions)`, + `Dependency review`, and the combined `CodeQL` alert check. +- Bind the combined alert check to GitHub Advanced Security (integration 57789) + and the eight workflow checks to GitHub Actions (integration 15368). +- Require zero approvals for this solo-maintainer project. GitHub prevents + self-approval; the PR/check/conversation requirements still apply. + +The existing **Main** ruleset 25757011 was disabled. It remains untouched and +disabled. Its signed-commit/code-quality/Copilot requirements were not silently +activated. The new rule requires the observed combined CodeQL check rather than +requiring scanning results on both the implementation and the unscanned default +branch, which would block the first implementation merge. + +Future branch-policy changes should preserve the distinction between scan-job +completion and a clean alert result. Required check names were observed in +successful runs, not invented. Repository merge settings still exclude merge +commits even though the ruleset's allowed-method intersection includes them. + +## Delivery project + +[SidePulse.NET delivery](https://github.com/users/Anheledir/projects/5/views/1) +is a private owner project linked to this public repository. It has a Delivery +board, short description and README explaining scope, status meanings, validation +requirements and attribution. It imports open issues and PRs from this repository. + +| Column | Items at verification | +|---|---| +| Todo | #11 | +| In Progress | #5, #7, #8, #9 | +| Validation | #2, #3, #4, #6, #10, PR #12 | +| Done | #1, concept approval only | + +All eleven issues and PR #12 are represented. Incomplete implementation and +physical/provider/release acceptance remain visible instead of marking them done. +The board remains private; repository visibility was not changed. + +## Source configuration and evidence + +Weekly Dependabot updates for NuGet and Actions already exist. PR #12 adds +SECURITY.md, C#/Python/Actions CodeQL on PRs/main/weekly schedule, and PR dependency +review rejecting new high/critical advisories. Third-party Actions are pinned; +workflow permissions are read-only by default with scoped publication/scanning +exceptions. Wiki/upstream publishing runs only from the default branch. + +Reviewed code `f1ada51` passed **104 tests per OS** in +[native CI](https://github.com/Anheledir/SidePulse.NET/actions/runs/40039767890), +including updater replacement and rollback. Quality and dependency review passed. +[Security analysis](https://github.com/Anheledir/SidePulse.NET/actions/runs/40039767819) +passed all three languages; the combined CodeQL check reports no new alerts after +canonical containment hardening. No rule was suppressed or alert dismissed. + +The audit/settings commits change documentation only. Check the PR head's required +checks before merging. Source documentation/wiki/security-policy changes become +default-branch documentation only after merge. Runtime/hardware/provider release +gates remain in the issues and [QA review](reviews/pr-12.md). + +## References + +- [GitHub security settings](https://docs.github.com/en/repositories/managing-your-repositorys-settings-and-features/enabling-features-for-your-repository/managing-security-and-analysis-settings-for-your-repository) - [CodeQL manual builds](https://docs.github.com/en/code-security/how-tos/find-and-fix-code-vulnerabilities/manage-your-configuration/codeql-for-compiled-languages) - [Dependency review action](https://github.com/actions/dependency-review-action) diff --git a/docs/reviews/pr-12.md b/docs/reviews/pr-12.md index bfea9e4..54e1bf9 100644 --- a/docs/reviews/pr-12.md +++ b/docs/reviews/pr-12.md @@ -1,6 +1,6 @@ # PR #12 architecture and QA review -Review date: 2026-10-23. Baseline: `444767f66cc6ca73f999339ba671923a10d61ffe`. +Review dates: 2026-10-23 through 2026-10-24. Baseline: `444767f66cc6ca73f999339ba671923a10d61ffe`. Scope: application architecture, credential and IPC boundaries, hook ownership, terminal/script behavior, animation model, updater transactions, tests, workflows, all eleven open issues, repository metadata and available security settings. @@ -36,7 +36,7 @@ acceptance and the public update/release path remain explicit release gates. | R9 | P1 compatibility evidence | Simulated LED output and generated agent wrappers are not real firmware, iOS or provider acceptance. | Open criteria in #2/#3/#4/#6/#9 with versioned evidence required. | | R11 | High scanner finding / P1 triage | Initial C# CodeQL reported `cs/zipslip` at ZIP extraction. Existing portable-name validation rejected traversal in tests, so an escape was not reproduced. | Added final canonical full-path containment with a directory-separator boundary, retaining the portable-name checks. Extended tar/ZIP traversal and directory-count tests. No rule suppression or alert dismissal. The final combined CodeQL check passed with no new alerts. | | R12 | P2 architecture | Target architecture claimed every writer used the host, but direct state/write/animation commands send independently. | Corrected architecture documentation; #5 now tracks arbitration/manual-override policy. Stop the host for manual device checks. | -| R10 | P2 governance | Metadata says concept stage; homepage/topics empty, Projects disabled. Admin/security values cannot be verified with this GitHub App. | Observed and desired values recorded in repository-settings.json/md. Unknown controls are not called disabled or configured. | +| R10 | P2 governance | Metadata said concept stage, homepage/topics were empty, Projects was disabled, and the existing Main ruleset was disabled. Connector admin scope was insufficient. | Resolved via permitted browser fallback: metadata, malware alerts, Actions restrictions, linked delivery board and active main ruleset applied. Existing security controls verified; full settings recorded in repository-settings.json/md. | P1 means fix before merge when it is a reproducible defect (R1), or satisfy before making the corresponding release/compatibility claim (R8/R9). P2 items are @@ -109,4 +109,4 @@ platforms. `docs/backlog.json` mirrors the reviewed issue descriptions; it is a snapshot, not an automatic issue-state synchronizer. See [repository settings](../repository-settings.md) for effective configuration, -planned controls, verification limits and the proposed project-board description. +applied controls, verification limits and the linked delivery project. diff --git a/docs/wiki/Project-Setup.md b/docs/wiki/Project-Setup.md index 369fb77..364eaee 100644 --- a/docs/wiki/Project-Setup.md +++ b/docs/wiki/Project-Setup.md @@ -47,3 +47,14 @@ explains private reporting and trust boundaries. The [configuration record](https://github.com/Anheledir/SidePulse.NET/blob/implementation/first-preview/docs/repository-settings.md) separates observed settings, source configuration and desired admin changes. Adding a workflow does not prove that repository-level security controls are on. + +## Delivery tracking and protection + +The [delivery board](https://github.com/users/Anheledir/projects/5/views/1) is a +private owner project linked to the repository. Todo, In Progress, Validation and +Done separate unfinished code from outstanding compatibility evidence. All issues +and PR #12 are represented. The active Main delivery checks ruleset requires PRs, +resolved conversations, current native/security checks and blocks force-push and +deletion. The combined CodeQL alert check is required in addition to scan jobs. +The configuration record includes exact applied settings and observed existing +controls, verified 2026-10-24. From e132022fd2401c5ead678da27b5c63635c7018b7 Mon Sep 17 00:00:00 2001 From: Gordon Breuer Date: Sat, 24 Oct 2026 02:13:47 +0200 Subject: [PATCH 24/26] Keep published wiki security links valid after branch cleanup --- docs/wiki/Project-Setup.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/wiki/Project-Setup.md b/docs/wiki/Project-Setup.md index 364eaee..0293e33 100644 --- a/docs/wiki/Project-Setup.md +++ b/docs/wiki/Project-Setup.md @@ -42,9 +42,9 @@ repositories with no activity may have scheduled workflows disabled by GitHub. ## Security and repository administration -[SECURITY.md](https://github.com/Anheledir/SidePulse.NET/blob/implementation/first-preview/SECURITY.md) +[SECURITY.md](https://github.com/Anheledir/SidePulse.NET/blob/main/SECURITY.md) explains private reporting and trust boundaries. The -[configuration record](https://github.com/Anheledir/SidePulse.NET/blob/implementation/first-preview/docs/repository-settings.md) +[configuration record](https://github.com/Anheledir/SidePulse.NET/blob/main/docs/repository-settings.md) separates observed settings, source configuration and desired admin changes. Adding a workflow does not prove that repository-level security controls are on. From a48d6ad9005fe4e84093c18aefc09b95c61bc1fb Mon Sep 17 00:00:00 2001 From: Gordon Breuer Date: Sat, 24 Oct 2026 02:27:16 +0200 Subject: [PATCH 25/26] Add session reset, explicit IPC version and consistent update status JSON --- docs/wiki/Host-Management.md | 14 ++++++++++++++ docs/wiki/Updating.md | 5 +++++ scripts/agent_smoke.py | 3 +++ src/SidePulse.Cli/Hooks.cs | 9 ++++++++- src/SidePulse.Cli/HostManagement.cs | 19 ++++++++++++++++--- src/SidePulse.Cli/Program.cs | 1 + src/SidePulse.Cli/Updates.cs | 2 +- src/SidePulse.Core/Sessions.cs | 4 +++- tests/SidePulse.Tests/CoreTests.cs | 13 +++++++++++++ 9 files changed, 64 insertions(+), 6 deletions(-) diff --git a/docs/wiki/Host-Management.md b/docs/wiki/Host-Management.md index 12e6288..241775b 100644 --- a/docs/wiki/Host-Management.md +++ b/docs/wiki/Host-Management.md @@ -50,3 +50,17 @@ Tests exercise detached start, idempotent start, status snapshots, mixed-provide hook delivery and graceful stop. Foreground tests also reject competing hosts and verify restart after forced termination. These are simulated device tests, not evidence of actual LED or phone receipt. + +## Clearing abandoned sessions + +`sidepulse-net host reset` clears all tracked sessions and queues the Unknown +pattern. Use `--json` for a machine-readable snapshot. This explicitly discards +history; it does not mark tasks successful or stop agent processes. The next agent +event establishes fresh state. A stopped host returns exit code 1. + +IPC messages and host snapshots now carry `ProtocolVersion: 1`. Unknown explicit +versions are rejected; legacy messages without the field are treated as v1. +This does not establish compatibility between arbitrary application versions: +stop the host before upgrades and run matching CLI/host binaries. Restart remains +Unknown with no restored session history; reset provides explicit recovery from +abandoned sessions without a timeout inventing successful completion. diff --git a/docs/wiki/Updating.md b/docs/wiki/Updating.md index 60a26ec..8857c8f 100644 --- a/docs/wiki/Updating.md +++ b/docs/wiki/Updating.md @@ -70,3 +70,8 @@ self-contained smoke checks, collects all six archives, writes `SHA256SUMS`, upl a draft release and only then publishes it. Hyphenated versions are prereleases. No release or tag is created simply by adding this workflow to a branch. Existing release tags are not overwritten. Review the release notes/assets after publishing. + +`update status --json` always exposes the same lower-camel-case fields: `state`, +`version`, `target`, `backup`, `workspace`, `error`, and `receipt`. Missing values +are null; no receipt gives state `none`. Scripts should inspect `state` rather +than infer completion from an install command returning successfully. diff --git a/scripts/agent_smoke.py b/scripts/agent_smoke.py index 4274f5e..e9a825d 100644 --- a/scripts/agent_smoke.py +++ b/scripts/agent_smoke.py @@ -100,6 +100,9 @@ def send(provider, event): time.sleep(0.1) assert status()['State'] == 'Done' assert 'DO-NOT-LOG-THIS' not in run('host', 'logs', '--tail', '10') + cleared = json.loads(run('host', 'reset', '--json')) + assert cleared['ProtocolVersion'] == 1 and cleared['State'] == 'Unknown' and not cleared['Sessions'], cleared + assert not status()['Sessions'] run('host', 'stop', '--json') started = False assert not status()['Running'] diff --git a/src/SidePulse.Cli/Hooks.cs b/src/SidePulse.Cli/Hooks.cs index 2c5cd87..14fc6d8 100644 --- a/src/SidePulse.Cli/Hooks.cs +++ b/src/SidePulse.Cli/Hooks.cs @@ -167,11 +167,18 @@ public override async Task ExecuteAsync(CommandContext context, HostSetting } if (message.Length > LocalPipe.MaximumMessageBytes) continue; using var request = JsonDocument.Parse(message.ToArray()); + if (request.RootElement.TryGetProperty("ProtocolVersion", out var protocol) && (!protocol.TryGetInt32(out var version) || version != 1)) continue; if (request.RootElement.TryGetProperty("Command", out var command)) { var action = command.GetString(); - if (action is "status" or "stop") + if (action is "status" or "stop" or "reset") { + if (action == "reset") + { + sessions.Clear(); + queued = AgentState.Unknown; + outputs.Writer.TryWrite(patterns[AgentState.Unknown]); + } var response = JsonSerializer.SerializeToUtf8Bytes(new HostSnapshot(true, Environment.ProcessId, sessions.State, sessions.Snapshot)); await pipe.WriteAsync(response.Concat(new byte[] { 10 }).ToArray(), deadline.Token); await pipe.FlushAsync(deadline.Token); diff --git a/src/SidePulse.Cli/HostManagement.cs b/src/SidePulse.Cli/HostManagement.cs index d291cbe..b22a4f2 100644 --- a/src/SidePulse.Cli/HostManagement.cs +++ b/src/SidePulse.Cli/HostManagement.cs @@ -9,7 +9,7 @@ namespace SidePulse.Cli; -public sealed record HostSnapshot(bool Running, int? ProcessId, AgentState State, IReadOnlyList Sessions); +public sealed record HostSnapshot(bool Running, int? ProcessId, AgentState State, IReadOnlyList Sessions, int ProtocolVersion = 1); public static class HostControl { public static async Task Request(string command, CancellationToken cancellationToken) @@ -19,13 +19,15 @@ public static async Task Request(string command, CancellationToken using var pipe = new NamedPipeClientStream(".", LocalPipe.Name, PipeDirection.InOut, PipeOptions.Asynchronous | PipeOptions.CurrentUserOnly); try { await pipe.ConnectAsync(deadline.Token); } catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested) { return new(false, null, AgentState.Unknown, []); } - await pipe.WriteAsync(Encoding.UTF8.GetBytes(JsonSerializer.Serialize(new { Command = command }) + "\n"), deadline.Token); + await pipe.WriteAsync(Encoding.UTF8.GetBytes(JsonSerializer.Serialize(new { Command = command, ProtocolVersion = 1 }) + "\n"), deadline.Token); await pipe.FlushAsync(deadline.Token); using var reader = new StreamReader(pipe, Encoding.UTF8); var response = await reader.ReadLineAsync(deadline.Token) ?? throw new IOException("The host closed without a response."); await pipe.WriteAsync(new byte[] { 10 }, deadline.Token); await pipe.FlushAsync(deadline.Token); - return JsonSerializer.Deserialize(response, Output.Json) ?? throw new IOException("Invalid host response."); + var snapshot = JsonSerializer.Deserialize(response, Output.Json) ?? throw new IOException("Invalid host response."); + if (snapshot.ProtocolVersion != 1) throw new IOException("Host protocol mismatch. Stop the old host and use matching CLI/host versions."); + return snapshot; } } public sealed class HostActionSettings : CommandSettings @@ -111,3 +113,14 @@ public override async Task ExecuteAsync(CommandContext context, HostStartSe throw new IOException("Host readiness could not be confirmed. Use host status before retrying."); } } + +public sealed class HostResetCommand : AsyncCommand +{ + public override async Task ExecuteAsync(CommandContext context, HostActionSettings settings, CancellationToken cancellationToken) + { + var result = await HostControl.Request("reset", cancellationToken); + if (settings.Json) Output.Print(result); + else Console.WriteLine(result.Running ? "Session history cleared; status is Unknown until the next agent event." : "Host is not running."); + return result.Running ? 0 : 1; + } +} diff --git a/src/SidePulse.Cli/Program.cs b/src/SidePulse.Cli/Program.cs index a0aba55..8c698cb 100644 --- a/src/SidePulse.Cli/Program.cs +++ b/src/SidePulse.Cli/Program.cs @@ -73,6 +73,7 @@ host.SetDescription("Manage the shared agent host."); host.AddCommand("run").WithDescription("Run in the foreground."); host.AddCommand("start").WithDescription("Start a detached host with bounded local logs."); + host.AddCommand("reset").WithDescription("Clear stale sessions without inventing completion."); host.AddCommand("status").WithDescription("Query the running host and agent sessions."); host.AddCommand("stop").WithDescription("Request graceful shutdown over current-user IPC."); host.AddCommand("logs").WithDescription("Show recent background host log lines."); diff --git a/src/SidePulse.Cli/Updates.cs b/src/SidePulse.Cli/Updates.cs index 0b3fcd9..6d3f25e 100644 --- a/src/SidePulse.Cli/Updates.cs +++ b/src/SidePulse.Cli/Updates.cs @@ -112,7 +112,7 @@ public sealed class UpdateStatusCommand : Command public override int Execute(CommandContext context, UpdateSettings settings, CancellationToken cancellationToken) { var status = UpdateTransaction.Status(Updater.Target); - Updater.Print(settings, (object?)status ?? new { state = "none", receipt = UpdateTransaction.ReceiptPath(Updater.Target) }, status is null ? "No recorded update for this installation." : $"{status.State}: {status.Version}\nBackup: {status.Backup}\nWorkspace: {status.Job}" + (status.Error is null ? "" : "\n" + status.Error)); + Updater.Print(settings, new { state = status?.State ?? "none", version = status?.Version, target = Updater.Target, backup = status?.Backup, workspace = status?.Job, error = status?.Error, receipt = UpdateTransaction.ReceiptPath(Updater.Target) }, status is null ? "No recorded update for this installation." : $"{status.State}: {status.Version}\nBackup: {status.Backup}\nWorkspace: {status.Job}" + (status.Error is null ? "" : "\n" + status.Error)); return status?.State is "failed" or "recovery-required" ? 1 : 0; } } diff --git a/src/SidePulse.Core/Sessions.cs b/src/SidePulse.Core/Sessions.cs index b385d75..49896a1 100644 --- a/src/SidePulse.Core/Sessions.cs +++ b/src/SidePulse.Core/Sessions.cs @@ -2,15 +2,17 @@ namespace SidePulse.Core; -public sealed record SessionEvent(string SessionId, AgentState State, long Timestamp, AgentProvider Provider = AgentProvider.Copilot); +public sealed record SessionEvent(string SessionId, AgentState State, long Timestamp, AgentProvider Provider = AgentProvider.Copilot, int ProtocolVersion = 1); public sealed record SessionView(string Id, AgentState State, long Timestamp, AgentProvider Provider = AgentProvider.Copilot); public sealed class Sessions { private readonly Dictionary sessions = new(); public IReadOnlyList Snapshot => sessions.Values.OrderBy(s => s.Id).ToArray(); + public void Clear() => sessions.Clear(); public bool Apply(SessionEvent item) { + if (item.ProtocolVersion != 1) return false; if (string.IsNullOrWhiteSpace(item.SessionId) || item.SessionId.Length > 256 || item.Timestamp < 0) return false; if (!Enum.IsDefined(item.Provider) || !Enum.IsDefined(item.State)) return false; var key = item.Provider + ":" + item.SessionId; diff --git a/tests/SidePulse.Tests/CoreTests.cs b/tests/SidePulse.Tests/CoreTests.cs index d8b26f1..d9468fe 100644 --- a/tests/SidePulse.Tests/CoreTests.cs +++ b/tests/SidePulse.Tests/CoreTests.cs @@ -7,6 +7,19 @@ namespace SidePulse.Tests; public sealed class CoreTests { + [Fact] + public void ExplicitResetForgetsErrorsAndAllowsFreshEvents() + { + var sessions = new Sessions(); + Assert.False(sessions.Apply(new("future", AgentState.Working, 1, ProtocolVersion: 2))); + sessions.Apply(new("old", AgentState.Error, 100)); + sessions.Clear(); + Assert.Empty(sessions.Snapshot); + Assert.Equal(AgentState.Unknown, sessions.State); + Assert.True(sessions.Apply(new("old", AgentState.Working, 1))); + Assert.Equal(AgentState.Working, sessions.State); + } + [Fact] public void LimitsUseUtf8BytesAndPhysicalLines() { From 125bfbde5d7ddb4eea985ee58b42166e01163652 Mon Sep 17 00:00:00 2001 From: Gordon Breuer Date: Sat, 24 Oct 2026 02:27:55 +0200 Subject: [PATCH 26/26] Validate the public lower-camel update status schema in native smoke --- scripts/update_smoke.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripts/update_smoke.py b/scripts/update_smoke.py index 5cc805b..af867c1 100644 --- a/scripts/update_smoke.py +++ b/scripts/update_smoke.py @@ -47,7 +47,7 @@ def main(executable): version = subprocess.run([str(target / executable.name), '--version'], env=env, capture_output=True, text=True, timeout=15) assert version.returncode == 0 and version.stdout.strip() == shipped['Version'] status = subprocess.run([str(target / executable.name), 'update', 'status', '--json'], env=env, capture_output=True, text=True, timeout=15) - assert status.returncode == (1 if fail else 0) and json.loads(status.stdout)['State'] == state['State'] + assert status.returncode == (1 if fail else 0) and json.loads(status.stdout)['state'] == state['State'] assert (job / 'failed-package').exists() if fail else backup.exists() print('Native updater ' + ('startup failure rollback' if fail else 'replacement and backup') + ' passed.', flush=True)