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
43 changes: 16 additions & 27 deletions .github/workflows/build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -14,23 +14,36 @@ permissions:
env:
DOTNET_VERSION: "10.0.x"
PROJECT_PATH: "NetSpeed/NetSpeed.csproj"
LIBRESPEED_VERSION: "1.0.13"

jobs:
tests:
name: Unit tests (Linux)
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v5

- name: Setup .NET
uses: actions/setup-dotnet@v4
with:
dotnet-version: ${{ env.DOTNET_VERSION }}

- name: Run NetSpeed.Core tests
run: dotnet test tests/NetSpeed.Core.Tests/NetSpeed.Core.Tests.csproj -c Release

debug:
name: Debug ${{ matrix.platform }}
runs-on: windows-2025
needs: tests

strategy:
fail-fast: false
matrix:
include:
- platform: x64
runtime: win-x64
librespeed_arch: amd64
- platform: ARM64
runtime: win-arm64
librespeed_arch: arm64

steps:
- name: Checkout repository
Expand All @@ -47,30 +60,6 @@ jobs:
dotnet restore "${{ env.PROJECT_PATH }}" -p:NuGetAuditMode=all -warnaserror:NU1901,NU1902,NU1903,NU1904
if ($LASTEXITCODE -ne 0) { throw "dotnet restore failed." }

- name: Download and verify LibreSpeed CLI
shell: pwsh
run: |
$version = "${{ env.LIBRESPEED_VERSION }}"
$arch = "${{ matrix.librespeed_arch }}"
$file = "librespeed-cli_${version}_windows_${arch}.zip"
$baseUrl = "https://github.com/librespeed/speedtest-cli/releases/download/v${version}"

Invoke-WebRequest -Uri "$baseUrl/$file" -OutFile $file
Invoke-WebRequest -Uri "$baseUrl/checksums.txt" -OutFile "checksums.txt"

$checksumLine = Get-Content "checksums.txt" | Where-Object { $_ -match [regex]::Escape($file) } | Select-Object -First 1
if (-not $checksumLine) { throw "Checksum for $file not found." }

$expected = ($checksumLine -split '\s+')[0].Trim().ToLowerInvariant()
$actual = (Get-FileHash -Path $file -Algorithm SHA256).Hash.ToLowerInvariant()
if ($expected -ne $actual) { throw "LibreSpeed CLI checksum mismatch." }

$target = "NetSpeed\ThirdParty\LibreSpeed"
Remove-Item -Path $target -Recurse -Force -ErrorAction SilentlyContinue
New-Item -ItemType Directory -Force -Path $target | Out-Null
Expand-Archive -Path $file -DestinationPath $target -Force
Invoke-WebRequest -Uri "https://raw.githubusercontent.com/librespeed/speedtest-cli/v${version}/LICENSE" -OutFile "$target\LICENSE-LGPL-3.0.txt"

- name: Build Debug MSIX
shell: pwsh
run: |
Expand Down
33 changes: 6 additions & 27 deletions .github/workflows/release.yml
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ permissions:
env:
DOTNET_VERSION: "10.0.x"
PROJECT_PATH: "NetSpeed/NetSpeed.csproj"
LIBRESPEED_VERSION: "1.0.13"

jobs:
release:
Expand All @@ -27,10 +26,8 @@ jobs:
include:
- platform: x64
runtime: win-x64
librespeed_arch: amd64
- platform: ARM64
runtime: win-arm64
librespeed_arch: arm64

steps:
- name: Checkout repository
Expand All @@ -48,35 +45,17 @@ jobs:
with:
dotnet-version: ${{ env.DOTNET_VERSION }}

- name: Restore and audit NuGet packages
- name: Run NetSpeed.Core tests
shell: pwsh
run: |
dotnet restore "${{ env.PROJECT_PATH }}" -p:NuGetAuditMode=all -warnaserror:NU1901,NU1902,NU1903,NU1904
if ($LASTEXITCODE -ne 0) { throw "dotnet restore failed." }
dotnet test tests/NetSpeed.Core.Tests/NetSpeed.Core.Tests.csproj -c Release
if ($LASTEXITCODE -ne 0) { throw "Unit tests failed." }

- name: Download and verify LibreSpeed CLI
- name: Restore and audit NuGet packages
shell: pwsh
run: |
$version = "${{ env.LIBRESPEED_VERSION }}"
$arch = "${{ matrix.librespeed_arch }}"
$file = "librespeed-cli_${version}_windows_${arch}.zip"
$baseUrl = "https://github.com/librespeed/speedtest-cli/releases/download/v${version}"

Invoke-WebRequest -Uri "$baseUrl/$file" -OutFile $file
Invoke-WebRequest -Uri "$baseUrl/checksums.txt" -OutFile "checksums.txt"

$checksumLine = Get-Content "checksums.txt" | Where-Object { $_ -match [regex]::Escape($file) } | Select-Object -First 1
if (-not $checksumLine) { throw "Checksum for $file not found." }

$expected = ($checksumLine -split '\s+')[0].Trim().ToLowerInvariant()
$actual = (Get-FileHash -Path $file -Algorithm SHA256).Hash.ToLowerInvariant()
if ($expected -ne $actual) { throw "LibreSpeed CLI checksum mismatch." }

$target = "NetSpeed\ThirdParty\LibreSpeed"
Remove-Item -Path $target -Recurse -Force -ErrorAction SilentlyContinue
New-Item -ItemType Directory -Force -Path $target | Out-Null
Expand-Archive -Path $file -DestinationPath $target -Force
Invoke-WebRequest -Uri "https://raw.githubusercontent.com/librespeed/speedtest-cli/v${version}/LICENSE" -OutFile "$target\LICENSE-LGPL-3.0.txt"
dotnet restore "${{ env.PROJECT_PATH }}" -p:NuGetAuditMode=all -warnaserror:NU1901,NU1902,NU1903,NU1904
if ($LASTEXITCODE -ne 0) { throw "dotnet restore failed." }

- name: Validate signing configuration
shell: pwsh
Expand Down
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,5 @@ artifacts/
release-*/
certs/
*.pfx
NetSpeed/ThirdParty/LibreSpeed/librespeed-cli.exe
AppPackages/
**/AppPackages/
17 changes: 17 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,22 @@
# Changelog

## 0.2.0 - 2026-11-27

- New speed-test engine based on **Measurement Lab (M-Lab)**, written in C# with no external executables:
- Locate API v2 server discovery with access tokens; candidates ranked by measured round-trip time.
- **MSAK throughput1** with 4 parallel TCP streams for fast connections; automatic fallback to **ndt7** when MSAK has no capacity or refuses the test.
- Download and upload of 10 seconds each. The headline value excludes the first 2 seconds (TCP ramp-up); the full-phase average is shown as well.
- Upload speed from the server's own counters, as the ndt7 specification recommends.
- Idle latency and jitter from TCP handshakes; latency under load during download and upload; bufferbloat grade.
- Live Mbps while the test runs, a Cancel command, and a **Copy result** command (without the IP address).
- First-run notice explaining that M-Lab publishes test results, including the public IP address, as open data; consent is stored locally and can be withdrawn.
- Local limit of 40 tests per 24 hours, as required by the M-Lab Acceptable Use Policy for interactive users.
- Clear error messages for no capacity, busy servers, timeouts and network errors.
- New platform-independent `NetSpeed.Core` library and cross-platform unit tests, run in CI.
- New `PRIVACY.md`. Removed `SECURITY.md`, `THIRD_PARTY_NOTICES.md`, `PROJECT_INFO.txt` and `scripts/Install-Package.ps1`.
- Developer shown as `g_`.
- **Removed** LibreSpeed CLI, its LGPL notice and `scripts/Prepare-LibreSpeed.ps1`. The package no longer contains third-party executables.

## 0.1.1 - 2026-08-23

- Fixed LibreSpeed CLI 1.0.13 result parsing. The CLI returns a JSON array even when a single server is tested.
Expand Down
3 changes: 3 additions & 0 deletions Directory.Packages.props
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
</PropertyGroup>
<ItemGroup>
<PackageVersion Include="Microsoft.CommandPalette.Extensions" Version="0.11.260520004" />
<PackageVersion Include="Microsoft.NET.Test.Sdk" Version="17.14.1" />
<PackageVersion Include="Microsoft.CodeAnalysis.NetAnalyzers" Version="9.0.0-preview.24508.2" />
<PackageVersion Include="Microsoft.Web.WebView2" Version="1.0.3719.77" />
<PackageVersion Include="Microsoft.Windows.CsWin32" Version="0.3.183" />
Expand All @@ -14,5 +15,7 @@
<PackageVersion Include="Shmuelie.WinRTServer" Version="2.1.1" />
<PackageVersion Include="StyleCop.Analyzers" Version="1.2.0-beta.556" />
<PackageVersion Include="System.Text.Json" Version="9.0.8" />
<PackageVersion Include="xunit" Version="2.9.3" />
<PackageVersion Include="xunit.runner.visualstudio" Version="3.1.4" />
</ItemGroup>
</Project>
2 changes: 1 addition & 1 deletion LICENSE
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
MIT License

Copyright (c) 2026 Michele Gentilini
Copyright (c) 2026 g_

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
Expand Down
157 changes: 157 additions & 0 deletions NetSpeed.Core/LocalStateStore.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,157 @@
using System.Text.Json;
using System.Text.Json.Serialization;

namespace NetSpeed.Core;

public sealed class LocalState
{
/// <summary>Version of the data-policy notice the user accepted; 0 = never.</summary>
public int ConsentVersion { get; set; }

public DateTimeOffset? ConsentedAt { get; set; }

/// <summary>Start times of recent tests, for the local fair-use limit.</summary>
public List<DateTimeOffset> RecentTests { get; set; } = [];
}

[JsonSourceGenerationOptions(WriteIndented = true)]
[JsonSerializable(typeof(LocalState))]
internal sealed partial class LocalStateJsonContext : JsonSerializerContext
{
}

/// <summary>
/// Persists the user's consent to the M-Lab data policy and enforces the M-Lab AUP limit for
/// interactive users (no more than 40 tests per day, applied as a rolling 24-hour window).
/// Everything stays on this device.
/// </summary>
public sealed class LocalStateStore
{
/// <summary>Bump when the consent text changes materially, to ask again.</summary>
public const int CurrentConsentVersion = 1;

public const int MaxTestsPerDay = 40;

private static readonly TimeSpan Window = TimeSpan.FromHours(24);

private readonly string _path;
private readonly TimeProvider _time;
private readonly Lock _gate = new();
private LocalState _state;

public LocalStateStore(string path, TimeProvider? timeProvider = null)
{
_path = path ?? throw new ArgumentNullException(nameof(path));
_time = timeProvider ?? TimeProvider.System;
_state = Load(path);
}

/// <summary>Default location: %LOCALAPPDATA%\NetSpeed\state.json (virtualised per package under MSIX).</summary>
public static string DefaultPath => Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "NetSpeed", "state.json");

public bool HasConsent
{
get
{
lock (_gate)
{
return _state.ConsentVersion >= CurrentConsentVersion;
}
}
}

public void GrantConsent()
{
lock (_gate)
{
_state.ConsentVersion = CurrentConsentVersion;
_state.ConsentedAt = _time.GetUtcNow();
Save();
}
}

public void RevokeConsent()
{
lock (_gate)
{
_state.ConsentVersion = 0;
_state.ConsentedAt = null;
Save();
}
}

/// <summary>Tests still allowed in the current 24-hour window.</summary>
public int RemainingTests
{
get
{
lock (_gate)
{
Prune();
return Math.Max(0, MaxTestsPerDay - _state.RecentTests.Count);
}
}
}

/// <summary>Records a test start if the limit allows it.</summary>
public bool TryRegisterTest()
{
lock (_gate)
{
Prune();
if (_state.RecentTests.Count >= MaxTestsPerDay)
{
return false;
}

_state.RecentTests.Add(_time.GetUtcNow());
Save();
return true;
}
}

private void Prune()
{
DateTimeOffset cutoff = _time.GetUtcNow() - Window;
_state.RecentTests.RemoveAll(t => t <= cutoff);
}

private static LocalState Load(string path)
{
try
{
if (File.Exists(path))
{
using FileStream stream = File.OpenRead(path);
return JsonSerializer.Deserialize(stream, LocalStateJsonContext.Default.LocalState) ?? new LocalState();
}
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or JsonException)
{
// A corrupt or unreadable file means "no consent yet": the user will simply be asked again.
}

return new LocalState();
}

private void Save()
{
try
{
string? directory = Path.GetDirectoryName(_path);
if (!string.IsNullOrEmpty(directory))
{
Directory.CreateDirectory(directory);
}

string temp = _path + ".tmp";
File.WriteAllText(temp, JsonSerializer.Serialize(_state, LocalStateJsonContext.Default.LocalState));
File.Move(temp, _path, overwrite: true);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
// Best effort: the in-memory state still applies for this session.
}
}
}
Loading
Loading