Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 10 additions & 3 deletions docs/wiki/Getting-Started.md
Original file line number Diff line number Diff line change
Expand Up @@ -85,8 +85,14 @@ On Debian/Ubuntu, install `libsecret-tools`; desktop sessions commonly provide t
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.
The first linked phone becomes the default. Without target options, state, write,
animation apply and host delivery use exactly one mounted USB device; if none is
found, they use the saved default phone (or the only saved phone). For example,
`sidepulse-net state working` works with a paired default phone and no USB device.
Multiple mounted devices require an explicit target. Multiple phones without a
default require `--phone` or `link default <alias>`. Explicit `--device`, `--phone`
and `--token-env` always take precedence. A failed selection, credential read or
delivery never retries on a different output.

```powershell
sidepulse-net link rename iphone personal
Expand All @@ -98,7 +104,8 @@ 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 default link clears the saved default. Automatic delivery can use the
only remaining phone; with multiple remaining phones, choose a new default.
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
Expand Down
14 changes: 8 additions & 6 deletions src/SidePulse.Cli/Commands.cs
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ public override int Execute(CommandContext context, DevicesSettings settings, Ca
public class TargetSettings : CommandSettings
{
[CommandOption("--device <PATH>")]
[Description("Mounted directory or existing LEDS.LED path. Auto-selects a single discovered device.")]
[Description("Mounted directory or existing LEDS.LED path. Auto uses one USB device, then the saved default phone.")]
public string? Device { get; init; }
[CommandOption("--token-env <NAME>")]
[Description("Environment variable holding an iPhone push token. Selects phone delivery.")]
Expand All @@ -68,20 +68,22 @@ public static class Delivery
public static async Task Send(TargetSettings settings, LedProgram program, CancellationToken cancellationToken)
{
if (settings.DryRun) return;
if (settings.Phone is { } alias)
var target = OutputTarget.Resolve(settings.Device, settings.Phone, settings.TokenEnvironment,
DeviceTransport.Discover, () => File.Exists(LinkStore.DefaultPath) ? PhoneStores.Open().List() : []);
if (target.Transport == OutputTransport.Phone)
{
var phone = PhoneStores.Open().Get(alias);
var phone = PhoneStores.Open().Get(target.Value);
using var client = new HttpClient { Timeout = TimeSpan.FromSeconds(10) };
await new PhoneBridge(client).SendAsync(phone.Token, program, cancellationToken);
}
else if (settings.TokenEnvironment is { } variable)
else if (target.Transport == OutputTransport.TokenEnvironment)
{
var token = Environment.GetEnvironmentVariable(variable);
var token = Environment.GetEnvironmentVariable(target.Value);
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);
else DeviceTransport.Write(target.Value, program);
}
public static void Receipt(TargetSettings settings, LedProgram program)
{
Expand Down
27 changes: 27 additions & 0 deletions src/SidePulse.Core/OutputTarget.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
namespace SidePulse.Core;

public enum OutputTransport { Device, Phone, TokenEnvironment }
public sealed record OutputTarget(OutputTransport Transport, string Value)
{
public static OutputTarget Resolve(string? device, string? phone, string? tokenEnvironment,
Func<IReadOnlyList<Device>> devices, Func<IReadOnlyList<PhoneSummary>> phones)
{
if (new[] { device, phone, tokenEnvironment }.Count(value => value is not null) > 1)
throw new ArgumentException("Choose one of --device, --token-env or --phone.");
if (new[] { device, phone, tokenEnvironment }.Any(value => value is not null && string.IsNullOrWhiteSpace(value)))
throw new ArgumentException("An explicit output must not be empty. Supply a device path, phone alias or token environment variable name.");
if (device is not null) return new(OutputTransport.Device, device);
if (phone is not null) return new(OutputTransport.Phone, phone);
if (tokenEnvironment is not null) return new(OutputTransport.TokenEnvironment, tokenEnvironment);

var mounted = devices();
if (mounted.Count > 1) throw new IOException("Multiple devices found. Select one with --device or --phone.");
if (mounted.Count == 1) return new(OutputTransport.Device, mounted[0].Path);

var saved = phones();
var selected = saved.SingleOrDefault(item => item.IsDefault) ?? (saved.Count == 1 ? saved[0] : null);
if (selected is not null) return new(OutputTransport.Phone, selected.Alias);
if (saved.Count > 1) throw new IOException("Multiple phones found without a default. Use --phone or link default <alias>.");
throw new IOException("No output found. Connect SidePulse, use --device, pair a phone with link pair, or use --token-env.");
}
}
95 changes: 95 additions & 0 deletions tests/SidePulse.Tests/OutputTargetTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
using SidePulse.Cli;
using SidePulse.Core;
using Xunit;

namespace SidePulse.Tests;

public sealed class OutputTargetTests
{
private static PhoneSummary Phone(string alias, bool isDefault = false) => new(alias, alias, DateTimeOffset.UnixEpoch, isDefault);

[Theory]
[InlineData("mount", null, null, OutputTransport.Device)]
[InlineData(null, "missing-phone", null, OutputTransport.Phone)]
[InlineData(null, null, "MISSING_TOKEN", OutputTransport.TokenEnvironment)]
public void ExplicitTargetsNeverDiscoverOrReadSavedCredentials(string? device, string? phone, string? token, OutputTransport transport)
{
var target = OutputTarget.Resolve(device, phone, token,
() => throw new InvalidOperationException("Discovery must not run"),
() => throw new InvalidOperationException("Credentials must not be read"));
Assert.Equal(transport, target.Transport);
Assert.Equal(device ?? phone ?? token, target.Value);
}

[Fact]
public void EmptyExplicitOutputCannotBecomeAutomaticDeviceDiscovery()
{
Assert.Throws<ArgumentException>(() => OutputTarget.Resolve(" ", null, null,
() => throw new InvalidOperationException("Discovery must not run"), () => []));
Assert.Throws<ArgumentException>(() => OutputTarget.Resolve(null, "", null, () => [], () => []));
Assert.Throws<ArgumentException>(() => OutputTarget.Resolve(null, null, " ", () => [], () => []));
}

[Fact]
public void OneMountedDeviceWinsWithoutAccessingPhoneStorage()
{
var target = OutputTarget.Resolve(null, null, null, () => [new("mounted/LEDS.LED", "SidePulse")],
() => throw new IOException("Locked vault"));
Assert.Equal(new(OutputTransport.Device, "mounted/LEDS.LED"), target);
}

[Fact]
public void NoUsbUsesTheDefaultPhoneOrTheOnlySavedPhone()
{
Assert.Equal(new(OutputTransport.Phone, "chosen"), OutputTarget.Resolve(null, null, null, () => [],
() => [Phone("other"), Phone("chosen", true)]));
Assert.Equal(new(OutputTransport.Phone, "only"), OutputTarget.Resolve(null, null, null, () => [],
() => [Phone("only")]));
}

[Fact]
public void AmbiguousUsbDoesNotFallBackToThePhone()
{
var error = Assert.Throws<IOException>(() => OutputTarget.Resolve(null, null, null,
() => [new("one/LEDS.LED", "one"), new("two/LEDS.LED", "two")],
() => throw new InvalidOperationException("Do not select a phone")));
Assert.Contains("Multiple devices", error.Message);
}

[Fact]
public void AmbiguousPhonesAndMissingOutputsHaveActionableErrors()
{
Assert.Contains("link default", Assert.Throws<IOException>(() => OutputTarget.Resolve(null, null, null,
() => [], () => [Phone("one"), Phone("two")])).Message);
Assert.Contains("link pair", Assert.Throws<IOException>(() => OutputTarget.Resolve(null, null, null,
() => [], () => [])).Message);
Assert.Contains("Locked vault", Assert.Throws<IOException>(() => OutputTarget.Resolve(null, null, null,
() => [], () => throw new IOException("Locked vault"))).Message);
Assert.Throws<ArgumentException>(() => OutputTarget.Resolve("mount", "phone", null,
() => [], () => []));
}

[Fact]
public async Task DryRunSkipsUnavailableExplicitOutputsAndLiveDeviceWritesStillWork()
{
var directory = Path.Combine(Path.GetTempPath(), "SidePulse output ü " + Guid.NewGuid());
Directory.CreateDirectory(directory);
var path = Path.Combine(directory, "LEDS.LED");
try
{
var program = LedProgram.ForState(AgentState.Working);
await Delivery.Send(new() { Device = path, DryRun = true }, program, CancellationToken.None);
await Delivery.Send(new() { Phone = "not-linked", DryRun = true }, program, CancellationToken.None);
await Delivery.Send(new() { TokenEnvironment = "SIDEPULSE_TEST_MISSING_TOKEN", DryRun = true }, program, CancellationToken.None);
await Delivery.Send(new() { DryRun = true }, program, CancellationToken.None);
Assert.Empty(Directory.GetFiles(directory));
await File.WriteAllTextAsync(path, "off");
await Delivery.Send(new() { Device = directory }, program, CancellationToken.None);
Assert.Equal(program.Text, await File.ReadAllTextAsync(path));
await Assert.ThrowsAsync<IOException>(() => Delivery.Send(new() { Device = Path.Combine(directory, "missing", "LEDS.LED") },
program, CancellationToken.None));
Assert.Equal(program.Text, await File.ReadAllTextAsync(path));
}
finally { Directory.Delete(directory, true); }
}
}
Loading