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
5 changes: 3 additions & 2 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -99,9 +99,10 @@ Avalonia 12. Use the `avalonia-docs` MCP before reaching for an API from memory.
## Security

The number arrives from a `tel:` link, which any web page or document can produce: it is
**hostile input**. It reaches the phone only after `TelUri` has reduced it to `0-9 * #` and a
**hostile input**. It reaches the phone only after `TelUri` has reduced it to digits and a
length cap — never a `;`, `\r`, `\n` or letter, which would let a link append its own AT
commands. A security fix gets a test that replays the attack. Dialling always goes through the
commands, and never `*` or `#`, which on a landline would let it set up call forwarding
(`*21*<number>#`) at the exchange. A security fix gets a test that replays the attack. Dialling always goes through the
confirm window; nothing dials silently.

## Tests
Expand Down
24 changes: 24 additions & 0 deletions src/Waehlhilfe.AppLogic/DialMessages.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
using Waehlhilfe.Modem;

namespace Waehlhilfe.AppLogic;

/// <summary>What the Lagebuchführer reads after a dial or a connection test.</summary>
public static class DialMessages
{
public static string For(DialResult result, string portName) => result switch
{
DialResult.Dialled => "Gewählt. Gespräch am Telefon führen.",
DialResult.Answered => "Telefon antwortet. Alles bereit.",
DialResult.PortNotSet => "Kein Telefon eingerichtet – in Wählhilfe den Bluetooth-Port wählen.",
DialResult.PortMissing => $"Port {portName} nicht gefunden. Ist das Telefon mit diesem PC gekoppelt?",
DialResult.PortBusy => $"Port {portName} ist belegt oder gesperrt – läuft noch ein Anruf, oder nutzt ein anderes Programm den Port?",
DialResult.NoResponse => "Telefon antwortet nicht. Bluetooth am Telefon eingeschaltet? Ist es mit diesem PC als Audiogerät verbunden, diese Verbindung trennen.",
DialResult.Rejected => "Das Telefon hat die Wahl abgelehnt.",
DialResult.LineBusy => "Besetzt.",
DialResult.NoCarrier => "Keine Verbindung zustande gekommen.",
DialResult.NoDialTone => "Kein Freizeichen – ist die Telefonleitung angeschlossen?",
_ => "Unbekannte Antwort vom Telefon.",
};

public static bool IsError(DialResult result) => result is not (DialResult.Dialled or DialResult.Answered);
}
12 changes: 12 additions & 0 deletions src/Waehlhilfe.AppLogic/ISettingsStore.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
using Waehlhilfe.Domain;

namespace Waehlhilfe.AppLogic;

public interface ISettingsStore
{
/// <summary>The saved settings, or <see cref="DialSettings.Default"/> when there are none or they are unreadable.</summary>
DialSettings Load();

/// <exception cref="IOException">The settings could not be written.</exception>
void Save(DialSettings settings);
}
13 changes: 13 additions & 0 deletions src/Waehlhilfe.AppLogic/ITelHandlerRegistration.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
namespace Waehlhilfe.AppLogic;

/// <summary>Whether the OS opens <c>tel:</c> links with Wählhilfe, and the way to make it so.</summary>
public interface ITelHandlerRegistration
{
bool IsDefaultHandler();

/// <summary>
/// Makes Wählhilfe the handler, or opens the OS dialog where the user does — Windows lets
/// no program set it on its own. Throws when neither is possible.
/// </summary>
Task MakeDefaultAsync(CancellationToken cancellationToken = default);
}
80 changes: 80 additions & 0 deletions src/Waehlhilfe.AppLogic/JsonSettingsStore.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
using System.Text.Json;
using Waehlhilfe.Domain;

namespace Waehlhilfe.AppLogic;

/// <summary>The settings as a small JSON file in the user's profile.</summary>
public sealed class JsonSettingsStore : ISettingsStore
{
/// <summary>A settings file is well under a kilobyte; anything this size was not written by Wählhilfe.</summary>
public const int MaxFileBytes = 16 * 1024;

private static readonly JsonSerializerOptions Options = new(JsonSerializerDefaults.Web) { WriteIndented = true };

private readonly string _path;

public JsonSettingsStore(string path)
{
ArgumentException.ThrowIfNullOrWhiteSpace(path);
_path = path;
}

/// <summary>
/// <c>%APPDATA%\Waehlhilfe</c> on Windows, <c>~/Library/Application Support/Waehlhilfe</c> on
/// macOS, <c>$XDG_CONFIG_HOME/Waehlhilfe</c> on Linux.
/// </summary>
public static string DefaultPath()
{
var folder = OperatingSystem.IsMacOS()
? Environment.SpecialFolder.LocalApplicationData
: Environment.SpecialFolder.ApplicationData;
return Path.Join(Environment.GetFolderPath(folder), "Waehlhilfe", "settings.json");
}

public DialSettings Load()
{
try
{
var file = new FileInfo(_path);
if (!file.Exists || file.Length > MaxFileBytes)
{
return DialSettings.Default;
}

var stored = JsonSerializer.Deserialize<StoredSettings>(File.ReadAllText(_path), Options);
if (stored is null)
{
return DialSettings.Default;
}

// A hand-edited value gets no further than the settings window would let it.
var defaults = DialSettings.Default;
return new DialSettings(
stored.PortName ?? defaults.PortName,
DialSettings.IsValidHomeCountryCode(stored.HomeCountryCode) ? stored.HomeCountryCode : defaults.HomeCountryCode,
DialSettings.IsValidOutsideLinePrefix(stored.OutsideLinePrefix) ? stored.OutsideLinePrefix : defaults.OutsideLinePrefix);
}
catch (Exception e) when (e is JsonException or IOException or UnauthorizedAccessException)
{
return DialSettings.Default;
}
}

public void Save(DialSettings settings)
{
ArgumentNullException.ThrowIfNull(settings);
var directory = Path.GetDirectoryName(_path);
if (!string.IsNullOrEmpty(directory))
{
Directory.CreateDirectory(directory);
}

// Write beside, then replace, so a crash mid-write never leaves half a file.
var temporary = _path + ".tmp";
var stored = new StoredSettings(settings.PortName, settings.HomeCountryCode, settings.OutsideLinePrefix);
File.WriteAllText(temporary, JsonSerializer.Serialize(stored, Options));
File.Move(temporary, _path, overwrite: true);
}

private sealed record StoredSettings(string? PortName, string? HomeCountryCode, string? OutsideLinePrefix);
}
133 changes: 133 additions & 0 deletions src/Waehlhilfe.AppLogic/ViewModels/DialViewModel.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
using System.Diagnostics.CodeAnalysis;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using Waehlhilfe.Domain;
using Waehlhilfe.Modem;

namespace Waehlhilfe.AppLogic.ViewModels;

/// <summary>
/// The confirm window a <c>tel:</c> click opens. Nothing is dialled until the Lagebuchführer
/// confirms: a link can come from any page or document, and a call is not something a page may
/// place on its own.
/// </summary>
public sealed partial class DialViewModel : ObservableObject
{
/// <summary>Long enough to read „Gewählt“, short enough not to stand in the way.</summary>
public static readonly TimeSpan CloseDelay = TimeSpan.FromSeconds(2);

/// <summary>
/// How long after opening the window ignores a confirm. A link can arrive while the
/// Lagebuchführer types elsewhere; the window takes focus, and an Enter meant for another
/// program must not place the call.
/// </summary>
public static readonly TimeSpan ArmDelay = TimeSpan.FromSeconds(1);

private readonly IDialer _dialer;
private readonly TimeProvider _time;
private readonly string _portName;
private readonly DialNumber? _number;
private CancellationTokenSource? _dialing;
private bool _armed;

[ObservableProperty]
[NotifyCanExecuteChangedFor(nameof(DialCommand))]
private bool _isBusy;

[ObservableProperty]
private string _status;

[ObservableProperty]
private bool _isError;

public DialViewModel(string? link, DialSettings settings, IDialer dialer, TimeProvider? time = null)
{
ArgumentNullException.ThrowIfNull(settings);
ArgumentNullException.ThrowIfNull(dialer);
_dialer = dialer;
_time = time ?? TimeProvider.System;
_portName = settings.PortName;

if (TelUri.TryParse(link, out var uri))
{
_number = DialNumber.From(uri, settings);
}

Number = _number?.Digits ?? string.Empty;
(_status, _isError) = _number is null
? ("Kein gültiger tel:-Link – es wird nicht gewählt.", true)
: string.IsNullOrWhiteSpace(_portName)
? (DialMessages.For(DialResult.PortNotSet, _portName), true)
: ("Über das Telefon wählen?", false);
_ = ArmAfterDelayAsync();
}

public event EventHandler? CloseRequested;

/// <summary>The digits that will follow <c>ATD</c>; empty for a link that was refused.</summary>
public string Number { get; }

public bool CanDial => _number is not null && !string.IsNullOrWhiteSpace(_portName);

private bool CanStartDial() => CanDial && _armed && !IsBusy;

[RelayCommand(CanExecute = nameof(CanStartDial))]
[SuppressMessage("Design", "CA1031", Justification = "Any failure of the dial surfaces in Status; the window stays open to show it.")]
private async Task DialAsync()
{
if (!CanStartDial() || _number is null)
{
return;
}

using var dialing = new CancellationTokenSource();
_dialing = dialing;
IsBusy = true;
IsError = false;
Status = "Wähle …";
try
{
var result = await _dialer.DialAsync(_portName, _number, dialing.Token);
Status = DialMessages.For(result, _portName);
IsError = DialMessages.IsError(result);
if (!IsError)
{
_ = CloseAfterDelayAsync();
}
}
catch (OperationCanceledException)
{
Status = "Abgebrochen.";
}
catch (Exception)
{
Status = "Wählen fehlgeschlagen. Telefon und Bluetooth prüfen.";
IsError = true;
}
finally
{
_dialing = null;
IsBusy = false;
}
}

[RelayCommand]
private void Cancel()
{
_dialing?.Cancel();
CloseRequested?.Invoke(this, EventArgs.Empty);
}

private async Task ArmAfterDelayAsync()
{
await Task.Delay(ArmDelay, _time);
_armed = true;
DialCommand.NotifyCanExecuteChanged();
}

private async Task CloseAfterDelayAsync()
{
await Task.Delay(CloseDelay, _time);
CloseRequested?.Invoke(this, EventArgs.Empty);
}
}
Loading
Loading