Add OBS podcast ingestion and account withdrawal privacy controls

Support scoped RTMPS publishing through MediaMTX, authenticated replay, resource accounting and PostIt activation/revocation. Close withdrawn accounts, erase managed files and purge eligible payment residues after one year. Include migrations, documentation and regression tests.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
This commit is contained in:
Paul Schneider 2026-11-08 07:43:15 +00:00
commit b157dce4e4
Signed by: notazof
GPG key ID: AD4B9B545FBD7D12
54 changed files with 12996 additions and 50 deletions

View file

@ -5,6 +5,10 @@
### Added
* [Podcasts/OBS/PostIt] Add opt-in MediaMTX RTMPS ingestion for programmed emissions, activated explicitly from PostIt with one-time scoped, expiring and revocable keys. Start on publisher connection, remux H.264/AAC into the existing authenticated segments and MP4 replay workflow, bound concurrency/duration/buffering, enforce consumption and effective disk quotas, account storage with deletion refunds, and report owner-only ingest errors. Add relay configuration, installation instructions and real synthetic RTMP/RTMPS-to-replay regressions, including active revocation.
* [Yavsc/PostIt/Privacy] Close and pseudonymize withdrawn accounts, cancel PayPal subscriptions before confirming withdrawal, erase managed personal files, avatars and podcasts, and reject old sessions across hosts. Purge eligible technical payment residues one year after effective withdrawal automatically and through a confirmed administrator-only PostIt action; preserve accounting records separately. Clarify the privacy policy, recipients, third-party integrations, withdrawal failures and deployment responsibilities. Make the unique email constraint mutable to support pseudonymization without deleting accounting identities.
* [Yavsc/API/Blogs/PostIt] Refund tracked storage points when personal files are deleted or replaced, and when generated PDFs are replaced. Persist per-file accounting receipts, preserve them on rename, reject refunds for untracked legacy files, and allow deletion at the consumption limit without refunding API/CPU/transfer costs. Update CGU and installation instructions.
* [Yavsc/PostIt/PayPal] Add monthly Découverte (EUR 1 excluding VAT) and Premium (EUR 2 excluding VAT) resource subscriptions, charged at EUR 1.20 / EUR 2.40 including 20% VAT. Confirmed monthly PayPal payments erase up to one / three default quotas, carry two thirds of unused monthly credit without expiry, and preserve historical counters. Add persistent idempotent payment credits, refund reconciliation, authenticated Web subscription/cancellation pages, verified REST webhooks, PostIt links and balances, migration and updated CGU.

View file

@ -78,6 +78,42 @@ these Windows runtime behaviours.
## Resource consumption and CGU
### Account withdrawal and payment retention
Apply the `AccountWithdrawal` migration before deploying all three hosts. It adds
withdrawal timestamps and replaces the immutable alternate email key with a
required unique email index, preserving uniqueness while allowing pseudonymization.
Do not run the withdrawal flow until every host uses the matching backend.
Yavsc.Org must have write/delete access to the same managed volumes as API/Blogs:
`Site:UserFilesRoot`, `Site:Avatars` and `Podcast:RootPath`.
Use absolute paths shared across processes; defaults relative to application
directories are not shared automatically. Accounting files under `Site:Bills`
are not erased by withdrawal. Symbolic links in managed user directories are
refused rather than followed.
The account is blocked before cancellation/erasure, and withdrawal is only
confirmed when these operations and pseudonymization succeed. On an explicit
failure, an administrator must fix the cause and retry the existing administrative
withdrawal action. Ensure no live upload/encoding operation is still writing to
the user's volumes during withdrawal; drain such operations before retrying.
The Org hosted worker purges eligible technical payment records at startup and
checks at most every minute, with an earlier wake-up for a known anniversary.
Monitor errors and service availability: scheduled processing
cannot ensure an exact wall-clock deletion while the host is stopped. At least
one Org instance must run, and an external operations process must enforce the
one-year retention deadline during prolonged downtime. PostIt administrators can
also confirm and run `POST /api/v1/administration/payment-residues/purge`.
The report counts accounts, subscriptions, monthly payments, donations and legacy
PayPal payments. Active accounts and unfinished withdrawals are never purged.
No new subscription credits may be granted after withdrawal begins.
Invoice payments, invoices and other legal accounting records are excluded.
Define and publish the actual accounting, logs and backup retention policy for
the deployment, verify configured providers and international-transfer safeguards,
and prevent withdrawn data from being reactivated by backup restoration.
Configure the **same** `ResourceUsage` section on Yavsc.Api, Yavsc.Blogs and
Yavsc.Org. API and Blogs must also use the same application database.
All three hosts and configuration templates inherit the backend defaults
@ -252,6 +288,100 @@ or PayPal account eligibility.
## Podcast live broadcasts and replays
### OBS Studio for planned emissions
Deploy MediaMTX **v1.21.3** beside the **single Yavsc.Api media instance** and
FFmpeg on that API host. The generated configuration in
[`contrib/mediamtx-podcasts.yml`](contrib/mediamtx-podcasts.yml) enables only the
OBS publishing paths, RTMPS for publishers and private RTMP/control listeners.
Adjust its `authHTTPAddress` to the API's internal HTTP listener; this listener
must accept the local authentication callback without redirecting it to HTTPS.
Alternatively, use an internal HTTPS URL with a valid certificate.
Install the RTMPS TLS certificate and key at the configured paths. Keep the
control API and internal RTMP ports on loopback (or an isolated authenticated network),
never on the public Internet. Do not enable anonymous HLS/RTMP reads on the relay.
MediaMTX must not record independent copies: Yavsc owns storage and retention.
Apply the `PodcastObsIngestion` migration on the shared database. Configure
`Podcast:Obs` on **Yavsc.Api only**, for example:
```json
{
"Podcast": {
"Obs": {
"Enabled": true,
"ServerUrl": "rtmps://obs.example.org:1936",
"RelayApiUrl": "http://127.0.0.1:9997/",
"RelayReadUrl": "rtmp://127.0.0.1:1935/",
"RelayUser": "yavsc",
"ActivationMinutes": 30,
"MaxDurationMinutes": 120,
"MaxConcurrentBroadcasts": 2
}
}
}
```
Set `Podcast__Obs__RelayPassword` through the deployment's secret mechanism to
a random password of at least 32 characters. It authenticates Yavsc's private
reader/control client, not OBS users. Keep process arguments and credentials
accessible only to the service administrator. The public RTMPS URL must have
no `/live` suffix: the stream key includes the full `obs/<emission-id>` path.
Plain RTMP for the public OBS URL requires the explicit `AllowUnencryptedRtmp: true` option and should
only be used for local testing or inside a VPN. Limit publisher network bitrate
at the relay/network level as well as configuring OBS; application quotas are
checked on completed media segments, not on every incoming RTMP packet.
In PostIt:
1. Prepare an emission and select it.
2. Choose **Activer OBS / renouveler la cle**.
3. In OBS, select **Parametres > Stream > Service : Personnalise**, then copy
the displayed server and stream key. Use **H.264 video**, **AAC audio**,
a **2-second keyframe interval** and a bitrate producing segments below 8 MiB.
4. Start streaming in OBS before the activation expires. The actual emission
starts when the publisher connects, even if the scheduled date is later.
No camera capture in PostIt is required; PostIt may be closed afterwards.
5. Stop OBS or choose **Revoquer OBS et arreter le diffuseur** in PostIt.
Committed segments remain available and the normal MP4 worker prepares replay.
Keys are scoped to one emission, stored only as SHA-256 hashes, displayed once,
rotated on each activation and erased after completion. PostIt never persists
them; navigation/logout clears the displayed key but does not revoke a running
external emission. Revocation is available at the consumption limit.
After disconnect, restart or timeout, the emission ends rather than silently
resuming under a new publisher: prepare a new emission for another broadcast.
The worker polls the authenticated relay once a second and starts bounded FFmpeg
remuxing tasks. It rejects ended, deleted, revoked or withdrawn accounts and caps
concurrent captures and duration (the lower of planned duration and configured
maximum). MediaMTX also receives a session expiry from authentication, so the
publisher is disconnected at that maximum lifetime even if the API stops.
Committed segments are charged as transferred and stored MiB under the same
consumption rule; their storage receipts are refunded on podcast deletion.
OBS storage counts towards the user's effective disk quota and the existing
podcast media limits. Pending capture files are monitored and bounded; enforcement
can overshoot by one polling interval of incoming data. Processing errors are
reported in the owner-only OBS status endpoint, without exposing keys or FFmpeg
diagnostics. Monitor scan/cleanup failures and do not restore old activation keys
from backups. A prolonged relay/API outage requires operational intervention.
The normal API listens/authenticates playback; OBS stream credentials never grant
listener access. If the relay is separately hosted, include it in the deployment's
privacy/provider information.
For the real media regression, set `YAVSC_TEST_MEDIAMTX` to the installed MediaMTX
v1.21.3 executable and run:
```bash
dotnet test --project src/test/Yavsc.Api.Tests/Yavsc.Api.Tests.csproj --filter-class '*PodcastObsTests'
```
The test launches loopback-only listeners, generates synthetic H.264/AAC media
with FFmpeg, verifies RTMP/RTMPS authentication, revocation during streaming,
AAC audio, HLS segments, MP4 replay and refund,
then stops its own processes and removes its temporary files.
PostIt Desktop's home page provides **Podcasts : directs et replays**.
Install LibVLC 3 with the `livehttp`, MPEG-TS, x264 and AAC plugins on the
Desktop machine. Windows capture uses DirectShow; Linux uses V4L2 and the
@ -274,7 +404,8 @@ replays; only the broadcaster can upload, complete or delete their podcast.
Media is not anonymous and no access token is included in a playback URL.
Configure Yavsc.Api's `Podcast` section (or environment variables such as
`Podcast__RootPath`). No database migration is needed. Install **FFmpeg 5+
`Podcast__RootPath`). The base media store needs no database migration;
planned emissions and OBS require their migrations documented above. Install **FFmpeg 5+
on the API server** (with `concatf`, MPEG-TS, MP4 and AAC bitstream-filter
support; for Debian/Ubuntu: `apt-get install ffmpeg`). The API runtime stage
in the main Dockerfile includes it. Only stream-copy remuxing is performed,
@ -305,7 +436,10 @@ Defaults allow 8 MiB per segment (also the HTTP endpoint's hard limit),
1 GiB retained per owner, 7,200 segments per episode and 100 episodes per
owner. At the target two-second segment duration, this is roughly four hours
per episode; the byte quota can be reached earlier. Podcast quotas are
separate from the legacy user-files `DiskQuota`. Deleting an ended podcast
separate from the legacy user-files `DiskQuota` for native HTTP capture.
OBS source segments also count towards the user's effective disk quota and
instrumented consumption; the additional MP4 is counted only by `MaxOwnerBytes`.
Deleting an ended podcast
releases its podcast quota. Reverse proxies must allow an 8 MiB PUT body
and forward Authorization, Range and Content-Range on every API request/response.
The retained MPEG-TS **and** the additional MP4 count toward `MaxOwnerBytes`.

View file

@ -0,0 +1,26 @@
# MediaMTX v1.21.3. Run beside the single Yavsc.Api media host.
# Replace the auth URL port and TLS certificate paths for the deployment.
logLevel: warn
authMethod: http
authHTTPAddress: http://127.0.0.1:5103/api/v1/podcasts/relay/auth
authHTTPExclude: []
api: true
apiAddress: 127.0.0.1:9997
rtsp: false
rtmp: true
rtmpEncryption: optional
rtmpAddress: 127.0.0.1:1935
rtmpsAddress: :1936
rtmpServerKey: /etc/yavsc/obs/server.key
rtmpServerCert: /etc/yavsc/obs/server.crt
hls: false
webrtc: false
srt: false
playback: false
pathDefaults:
source: publisher
overridePublisher: false
maxReaders: 1
record: false
paths:
"~^obs/[0-9a-f]{32}$":

View file

@ -15,6 +15,31 @@ namespace PostIt.Tests;
public class AdministrationToolsTests
{
[Fact]
public async Task Payment_purge_requires_confirmation_reports_counts_and_clears_on_logout()
{
await using var profile = new AdministrationAccessTests.ProfileTransport("Administrator");
var session = new SessionStatusViewModel { Api = profile };
await session.RefreshAsync();
await using var transport = new AdminTransport();
var vm = new AdministrationPageViewModel(null, session: session,
administrationClient: new AdministrationApiClient(transport, () => "https://example.invalid/api/v1"));
await vm.PurgePaymentResiduesCommand.ExecuteAsync(null);
Assert.Empty(transport.Paths);
vm.ConfirmDestructiveAction = true;
await vm.PurgePaymentResiduesCommand.ExecuteAsync(null);
Assert.Contains("POST https://example.invalid/api/v1/administration/payment-residues/purge", transport.Paths);
Assert.Contains("2 compte(s)", vm.PaymentPurgeReport);
Assert.False(vm.ConfirmDestructiveAction);
session.Api = null;
session.Refresh();
transport.Paths.Clear();
vm.ConfirmDestructiveAction = true;
await vm.PurgePaymentResiduesCommand.ExecuteAsync(null);
Assert.Empty(transport.Paths);
Assert.Empty(vm.PaymentPurgeReport);
}
[AvaloniaTheory]
[InlineData(400, 800)]
[InlineData(800, 400)]
@ -207,6 +232,8 @@ public class AdministrationToolsTests
: await PendingSecret.Task;
else if (typeof(T) == typeof(ImportResult))
result = new ImportResult(0, 0, 0);
else if (typeof(T) == typeof(PaymentResiduePurgeResult))
result = new PaymentResiduePurgeResult(2, 3, 4, 1, 1);
else
throw new NotSupportedException(typeof(T).Name);
return JsonSerializer.Deserialize<T>(JsonSerializer.Serialize(result))!;

View file

@ -9,6 +9,78 @@ namespace PostIt.Tests;
public sealed class PodcastScheduleTests
{
[AvaloniaFact]
public async Task Late_obs_credentials_are_not_displayed_after_selection_changes_or_navigation()
{
var path = Path.Combine(Path.GetTempPath(), $"postit-obs-late-{Guid.NewGuid():N}.json");
var store = new TokenStore(path);
store.Save(new RefreshTokenRecord("test-access", "test-refresh", DateTimeOffset.UtcNow.AddHours(1), null));
try
{
await using var api = new ScheduleApi(store, path + ".settings");
var session = new SessionStatusViewModel { Api = api };
session.Refresh();
var vm = new PodcastsPageViewModel(new PodcastApiClient(api, () => "https://api.example/"), api, session);
await vm.ActivateAsync();
vm.SelectedPodcast = api.Plan;
api.PendingActivation = new(TaskCreationOptions.RunContinuationsAsynchronously);
var activation = vm.ActivateObsCommand.ExecuteAsync(null);
vm.SelectedPodcast = api.Plan with { Id = Guid.NewGuid() };
vm.SelectedPodcast = api.Plan;
api.PendingActivation.SetResult(new("rtmps://obs.example:1936", "secret", DateTimeOffset.UtcNow.AddMinutes(30)));
await activation;
Assert.Empty(vm.ObsStreamKey);
api.PendingActivation = new(TaskCreationOptions.RunContinuationsAsynchronously);
activation = vm.ActivateObsCommand.ExecuteAsync(null);
await vm.DeactivateAsync();
api.PendingActivation.SetResult(new("rtmps://obs.example:1936", "secret", DateTimeOffset.UtcNow.AddMinutes(30)));
await activation;
Assert.Empty(vm.ObsStreamKey);
}
finally { File.Delete(path); File.Delete(path + ".settings"); }
}
[AvaloniaFact]
public async Task Obs_activation_is_owned_displays_credentials_and_clears_them_on_navigation_and_revocation()
{
var path = Path.Combine(Path.GetTempPath(), $"postit-obs-{Guid.NewGuid():N}.json");
var store = new TokenStore(path);
store.Save(new RefreshTokenRecord("test-access", "test-refresh", DateTimeOffset.UtcNow.AddHours(1), null));
try
{
await using var api = new ScheduleApi(store, path + ".settings");
var session = new SessionStatusViewModel { Api = api };
session.Refresh();
var vm = new PodcastsPageViewModel(new PodcastApiClient(api, () => "https://api.example/"), api, session);
await vm.ActivateAsync();
vm.SelectedPodcast = api.Plan;
Assert.True(vm.ActivateObsCommand.CanExecute(null));
await vm.ActivateObsCommand.ExecuteAsync(null);
Assert.Equal("rtmps://obs.example:1936", vm.ObsServerUrl);
Assert.Equal("obs/stream-secret", vm.ObsStreamKey);
Assert.False(vm.IsBroadcasting);
api.Settings.Save();
Assert.DoesNotContain("stream-secret", await File.ReadAllTextAsync(path + ".settings"));
vm.SelectedPodcast = api.Plan with { Id = Guid.NewGuid(), OwnerId = "other" };
Assert.Empty(vm.ObsStreamKey);
Assert.False(vm.ActivateObsCommand.CanExecute(null));
vm.SelectedPodcast = api.Plan;
await vm.ActivateObsCommand.ExecuteAsync(null);
await vm.DeactivateAsync();
Assert.Empty(vm.ObsStreamKey);
Assert.True(api.ObsEnabled);
await vm.ActivateAsync();
vm.SelectedPodcast = api.Plan;
await vm.ActivateObsCommand.ExecuteAsync(null);
await vm.DeactivateObsCommand.ExecuteAsync(null);
Assert.False(api.ObsEnabled);
Assert.Empty(vm.ObsStreamKey);
Assert.EndsWith("/obs", api.RevokedPath);
await vm.DeactivateAsync();
}
finally { File.Delete(path); File.Delete(path + ".settings"); }
}
[AvaloniaFact]
public async Task Preparation_and_editing_send_schedule_and_optional_announcement_without_capture()
{
@ -62,18 +134,33 @@ public sealed class PodcastScheduleTests
finally { File.Delete(tokenPath); File.Delete(tokenPath + ".settings"); }
}
private sealed class ScheduleApi(TokenStore store, string settingsPath) : YavscApiClient(new Settings(settingsPath), store)
private sealed class ScheduleApi(TokenStore store, string settingsPath)
: YavscApiClient(new Settings(settingsPath), store), IYavscApiClient
{
public PodcastResponse Plan { get; private set; } = new(Guid.NewGuid(), "Concert", "owner", "Owner",
DateTimeOffset.UtcNow, DateTimeOffset.UtcNow, PodcastState.Planned, 0, 0, 0);
DateTimeOffset.UtcNow, DateTimeOffset.UtcNow, PodcastState.Planned, 0, 0, 0) { FlowId = 1 };
public bool ObsEnabled { get; private set; }
public string? RevokedPath { get; private set; }
public PreparePodcastRequest? Saved { get; set; }
public string? SavedPath { get; private set; }
public HttpMethod? SavedMethod { get; private set; }
public TaskCompletionSource<PodcastObsCredentials>? PendingActivation { get; set; }
public override Task<T> CallAsync<T>(HttpMethod method, string path, object? body = null, CancellationToken ct = default)
public override async Task<T> CallAsync<T>(HttpMethod method, string path, object? body = null, CancellationToken ct = default)
{
object response;
if (path.EndsWith("/account/me", StringComparison.Ordinal)) response = new Me { UserId = "owner" };
else if (path.EndsWith("/obs", StringComparison.Ordinal))
{
if (method == HttpMethod.Post)
{
ObsEnabled = true;
response = PendingActivation is null
? new PodcastObsCredentials("rtmps://obs.example:1936", "obs/stream-secret", DateTimeOffset.UtcNow.AddMinutes(30))
: await PendingActivation.Task;
}
else response = new PodcastObsStatus(ObsEnabled, DateTimeOffset.UtcNow.AddMinutes(30), null);
}
else if (method == HttpMethod.Get) response = new List<PodcastResponse> { Plan };
else
{
@ -87,7 +174,16 @@ public sealed class PodcastScheduleTests
};
response = Plan;
}
return Task.FromResult((T)response);
return (T)response;
}
Task IYavscApiClient.CallAsync(HttpMethod method, string path, object? body, CancellationToken ct)
{
Assert.Equal(HttpMethod.Delete, method);
Assert.EndsWith("/obs", path);
ObsEnabled = false;
RevokedPath = path;
return Task.CompletedTask;
}
}
}

View file

@ -113,6 +113,17 @@ public partial class AdministrationPageViewModel
throw new InvalidOperationException("Cochez la confirmation avant cette opération destructive.");
}
[RelayCommand]
private Task PurgePaymentResiduesAsync() => RunOperationAsync(async client =>
{
RequireConfirmation();
var result = await client.PurgePaymentResiduesAsync();
RequireAccess();
PaymentPurgeReport = $"{result.Users} compte(s), {result.Subscriptions} abonnement(s), {result.Payments} mensualité(s), {result.Donations} don(s), {result.LegacyPayments} paiement(s) historique(s) purgés.";
});
[ObservableProperty] public partial string PaymentPurgeReport { get; set; } = "";
partial void OnSelectedClientChanged(AdministrationClient? value)
{
ClientFields = AdministrationFieldViewModel.From(value?.Settings ?? new ClientSettings());

View file

@ -156,6 +156,7 @@ public partial class AdministrationPageViewModel : ViewModelBase
private void ClearAdministrationData()
{
PaymentPurgeReport = "";
Users.Clear();
UsageOverview.Clear();
SelectedUser = null;

View file

@ -35,6 +35,11 @@ public partial class PodcastsPageViewModel : ViewModelBase
private Control? _capturePreview;
private bool _restoringPreferences;
private bool _keepScreenOnDuringCapture;
private Guid? _obsPodcastId;
private int _obsVersion;
[ObservableProperty] public partial string ObsServerUrl { get; set; } = "";
[ObservableProperty] public partial string ObsStreamKey { get; set; } = "";
[ObservableProperty] public partial string ObsStatus { get; set; } = "";
private IDisposable? _screenAwake;
public bool SupportsCaptureScreenAwake => OperatingSystem.IsAndroid();
public bool KeepScreenOnDuringCapture
@ -165,6 +170,7 @@ public partial class PodcastsPageViewModel : ViewModelBase
set
{
if (!SetProperty(ref _selected, value)) return;
if (_obsPodcastId != value?.Id) ClearObsCredentials();
if (value is { State: PodcastState.Planned } && value.OwnerId == _ownerId)
{
_title = value.Title;
@ -192,6 +198,8 @@ public partial class PodcastsPageViewModel : ViewModelBase
public IAsyncRelayCommand FinishCommand { get; }
public IAsyncRelayCommand DeleteCommand { get; }
public IAsyncRelayCommand RetryReplayCommand { get; }
public IAsyncRelayCommand ActivateObsCommand { get; }
public IAsyncRelayCommand DeactivateObsCommand { get; }
public override bool CanNavigateNext { get => false; protected set { } }
public override bool CanNavigatePrevious { get => !IsBroadcasting; protected set { } }
@ -201,6 +209,12 @@ public partial class PodcastsPageViewModel : ViewModelBase
_api = api;
_session = session;
RefreshCommand = new AsyncRelayCommand(RefreshAsync, () => !IsBusy);
ActivateObsCommand = new AsyncRelayCommand(ActivateObsAsync,
() => !IsBusy && !IsCapturing && _session.IsLoggedIn
&& SelectedPodcast is { State: PodcastState.Planned } p && p.OwnerId == _ownerId);
DeactivateObsCommand = new AsyncRelayCommand(DeactivateObsAsync,
() => !IsBusy && !IsBroadcasting && _session.IsLoggedIn
&& SelectedPodcast is { FlowId: not null } p && p.OwnerId == _ownerId);
DetectDevicesCommand = new RelayCommand(DetectDevices, () => CanBroadcast && !IsCapturing && !IsBusy);
PreviewCommand = new AsyncRelayCommand(StartPreviewAsync,
() => CanBroadcast && !IsCapturing && !IsBusy && _session.IsLoggedIn && SelectedCamera is not null);
@ -273,6 +287,8 @@ public partial class PodcastsPageViewModel : ViewModelBase
FinishCommand.NotifyCanExecuteChanged();
DeleteCommand.NotifyCanExecuteChanged();
RetryReplayCommand.NotifyCanExecuteChanged();
ActivateObsCommand.NotifyCanExecuteChanged();
DeactivateObsCommand.NotifyCanExecuteChanged();
OnPropertyChanged(nameof(CanNavigatePrevious));
}
@ -282,10 +298,18 @@ public partial class PodcastsPageViewModel : ViewModelBase
try
{
var profileUrl = new Uri(new Uri(_api.Settings.ApiUrl.TrimEnd('/') + "/"), "account/me");
_ownerId = (await _api.CallAsync<Me>(HttpMethod.Get, profileUrl.AbsoluteUri)).UserId;
var ownerId = (await _api.CallAsync<Me>(HttpMethod.Get, profileUrl.AbsoluteUri)).UserId;
if (_ownerId != ownerId) ClearObsCredentials();
_ownerId = ownerId;
var podcasts = await _client.ListAsync();
Podcasts.Clear();
foreach (var podcast in podcasts) Podcasts.Add(podcast);
if (SelectedPodcast is { FlowId: not null } selected && selected.OwnerId == _ownerId)
{
var obs = await _client.ObsStatusAsync(selected.Id);
ObsStatus = obs.Error ?? (obs.Enabled ? "Entree OBS activee. Le direct commence a la connexion du diffuseur." : "Entree OBS desactivee.");
if (!obs.Enabled) ClearObsCredentials(clearStatus: false);
}
Status = "Directs et replays reserves aux utilisateurs connectes.";
}
catch (Exception ex) { Status = $"Chargement impossible : {ex.Message}"; }
@ -322,6 +346,8 @@ public partial class PodcastsPageViewModel : ViewModelBase
public async Task ActivateAsync()
{
_session.LogoutCompleted -= ClearObsOnLogout;
_session.LogoutCompleted += ClearObsOnLogout;
_restoringPreferences = true;
try
{
@ -343,11 +369,69 @@ public partial class PodcastsPageViewModel : ViewModelBase
public async Task DeactivateAsync()
{
_session.LogoutCompleted -= ClearObsOnLogout;
ClearObsCredentials();
_pageCancellation.Cancel();
await StopPreviewAsync();
if (_broadcaster is not null) await StopAsync();
}
private void ClearObsOnLogout()
{
ClearObsCredentials();
_ownerId = null;
SelectedPodcast = null;
UpdateCommands();
}
private void ClearObsCredentials(bool clearStatus = true)
{
ObsServerUrl = "";
ObsStreamKey = "";
_obsPodcastId = null;
_obsVersion++;
if (clearStatus) ObsStatus = "";
}
private async Task ActivateObsAsync()
{
IsBusy = true;
try
{
var podcast = SelectedPodcast ?? throw new InvalidOperationException("Selectionnez une emission programmee.");
var owner = _ownerId;
ClearObsCredentials();
var version = _obsVersion;
var token = _pageCancellation.Token;
var credentials = await _client.ActivateObsAsync(podcast.Id, token);
token.ThrowIfCancellationRequested();
if (_obsVersion != version || !_session.IsLoggedIn || _ownerId != owner || SelectedPodcast?.Id != podcast.Id)
throw new InvalidOperationException("La session ou l'emission a change ; les identifiants OBS ne seront pas affiches.");
_obsPodcastId = podcast.Id;
ObsServerUrl = credentials.ServerUrl;
ObsStreamKey = credentials.StreamKey;
ObsStatus = $"Connectez OBS avant {credentials.ExpiresAt.ToLocalTime():g}. Cette cle remplace toute cle precedente.";
}
catch (Exception ex) { Status = $"Activation OBS impossible : {ex.Message}"; }
finally { IsBusy = false; }
}
private async Task DeactivateObsAsync()
{
IsBusy = true;
try
{
var podcast = SelectedPodcast ?? throw new InvalidOperationException("Selectionnez une emission.");
await _client.DeactivateObsAsync(podcast.Id);
ClearObsCredentials();
ObsStatus = "Cle revoquee et diffuseur deconnecte. Le replay est finalise apres l'arret de la reception.";
await RefreshAsync();
}
catch (Exception ex) { Status = $"Desactivation OBS impossible : {ex.Message}"; }
finally { IsBusy = false; }
}
private void DetectDevices()
{
_restoringPreferences = true;

View file

@ -77,6 +77,9 @@
TextWrapping="Wrap"/>
<CheckBox Content="Je confirme la prochaine suppression, exclusion, régénération ou import."
IsChecked="{Binding ConfirmDestructiveAction, Mode=TwoWay}"/>
<Button Content="Purger les paiements résiduels des comptes retirés depuis un an"
Command="{Binding PurgePaymentResiduesCommand}" IsEnabled="{Binding !IsBusy}"/>
<TextBlock Text="{Binding PaymentPurgeReport}" TextWrapping="Wrap"/>
</StackPanel>
<TabControl Grid.Row="2" IsEnabled="{Binding !IsBusy}">

View file

@ -97,6 +97,22 @@
</WrapPanel>
</StackPanel>
<Button Content="Arreter et publier le replay" Command="{Binding StopCommand}" />
<StackPanel Spacing="8">
<TextBlock Text="Diffuser l'emission programmee avec OBS Studio" FontWeight="SemiBold" />
<TextBlock Text="Selectionnez votre emission puis activez OBS. Dans OBS : service Personnalise, video H.264, audio AAC, images cles toutes les 2 secondes. Le direct commence lorsque OBS se connecte, pas a l'heure prevue."
TextWrapping="Wrap" />
<WrapPanel>
<Button Content="Activer OBS / renouveler la cle" Command="{Binding ActivateObsCommand}" Margin="0,0,8,8" />
<Button Content="Revoquer OBS et arreter le diffuseur" Command="{Binding DeactivateObsCommand}" />
</WrapPanel>
<TextBlock Text="Serveur OBS" />
<TextBox Text="{Binding ObsServerUrl, Mode=OneWay}" IsReadOnly="True" />
<TextBlock Text="Cle de stream (secrete : ne pas partager)" />
<TextBox Text="{Binding ObsStreamKey, Mode=OneWay}" IsReadOnly="True" />
<TextBlock Text="{Binding ObsStatus}" TextWrapping="Wrap" />
<TextBlock Text="Les identifiants ne sont pas sauvegardes dans PostIt. Quitter la page masque la cle, mais n'arrete pas OBS : utilisez la revocation ou arretez OBS."
TextWrapping="Wrap" />
</StackPanel>
<CheckBox Content="Garder l'ecran allume pendant l'apercu camera et le direct"
IsVisible="{Binding SupportsCaptureScreenAwake}"
IsChecked="{Binding KeepScreenOnDuringCapture, Mode=TwoWay}" />

View file

@ -0,0 +1,5 @@
namespace Yavsc.Abstract.Administration;
/// <summary>Reports technical subscription records purged for withdrawn accounts.</summary>
/// <summary>Counts accounts and technical payment records erased by the retention purge, excluding accounting documents.</summary>
public sealed record PaymentResiduePurgeResult(int Users, int Subscriptions, int Payments, int Donations = 0, int LegacyPayments = 0);

View file

@ -57,3 +57,24 @@ public sealed record PodcastSegmentResponse(int Sequence, double DurationSeconds
/// <summary>The ordered, committed segments of a live broadcast or replay.</summary>
public sealed record PodcastManifestResponse(
PodcastResponse Podcast, IReadOnlyList<PodcastSegmentResponse> Segments);
/// <summary>One-time OBS connection credentials for an activated planned emission.</summary>
public sealed record PodcastObsCredentials(string ServerUrl, string StreamKey, DateTimeOffset ExpiresAt);
/// <summary>Owner-only state of the external broadcasting activation.</summary>
public sealed record PodcastObsStatus(bool Enabled, DateTimeOffset? ExpiresAt, string? Error);
/// <summary>MediaMTX external authentication request; credentials are never logged or echoed.</summary>
public sealed record PodcastRelayAuthentication
{
public string User { get; init; } = "";
public string Password { get; init; } = "";
public string Action { get; init; } = "";
public string Path { get; init; } = "";
public string Protocol { get; init; } = "";
public string Query { get; init; } = "";
public string Id { get; init; } = "";
}
/// <summary>Maximum lifetime of an authenticated media relay session.</summary>
public sealed record PodcastRelayAuthorization(DateTimeOffset? ExpireAt);

View file

@ -19,6 +19,8 @@ public sealed class AdministrationApiClient(IYavscApiClient api, Func<string> ba
=> api.CallAsync<List<AdministrationRole>>(HttpMethod.Get, Path("roles"), ct: ct);
public Task EnsureRolesAsync(CancellationToken ct = default)
=> api.CallAsync(HttpMethod.Post, Path("roles/ensure"), ct: ct);
public Task<PaymentResiduePurgeResult> PurgePaymentResiduesAsync(CancellationToken ct = default)
=> api.CallAsync<PaymentResiduePurgeResult>(HttpMethod.Post, Path("payment-residues/purge"), ct: ct);
public Task<List<RoleMember>> GetRoleMembersAsync(string roleId, CancellationToken ct = default)
=> api.CallAsync<List<RoleMember>>(HttpMethod.Get, Path($"roles/{Escape(roleId)}/members"), ct: ct);
public Task SetRoleMembershipAsync(string roleId, string userId, bool member, CancellationToken ct = default)

View file

@ -28,6 +28,15 @@ public sealed class PodcastApiClient(IYavscApiClient api, Func<string> baseAddre
public Task<PodcastResponse> StartAsync(Guid id, CancellationToken ct = default)
=> api.CallAsync<PodcastResponse>(HttpMethod.Post, Absolute($"{Prefix}/{id}/start"), ct: ct);
public Task<PodcastObsCredentials> ActivateObsAsync(Guid id, CancellationToken ct = default)
=> api.CallAsync<PodcastObsCredentials>(HttpMethod.Post, Absolute($"{Prefix}/{id}/obs"), ct: ct);
public Task<PodcastObsStatus> ObsStatusAsync(Guid id, CancellationToken ct = default)
=> api.CallAsync<PodcastObsStatus>(HttpMethod.Get, Absolute($"{Prefix}/{id}/obs"), ct: ct);
public Task DeactivateObsAsync(Guid id, CancellationToken ct = default)
=> api.CallAsync(HttpMethod.Delete, Absolute($"{Prefix}/{id}/obs"), ct: ct);
public Task<PodcastManifestResponse> GetAsync(Guid id, CancellationToken ct = default)
=> api.CallAsync<PodcastManifestResponse>(HttpMethod.Get, Absolute($"{Prefix}/{id}"), ct: ct);

View file

@ -8,6 +8,12 @@
@scopeId = 1
@templateId = REPLACE_WITH_MAILING_CRITERION
### Purge payment residues after the effective withdrawal's one-year anniversary
# 200: { users, subscriptions, payments, donations, legacyPayments }
# 401: no token; 403: token without Administrator role.
POST {{root}}/payment-residues/purge
Authorization: Bearer {{token}}
### Protected OpenAPI document (development only)
GET {{baseUrl}}/openapi/administration.json
Authorization: Bearer {{token}}

View file

@ -20,6 +20,13 @@ namespace Yavsc.ApiControllers.Administration;
[ServiceFilter(typeof(AdministrationExceptionFilter))]
public sealed class SiteAdministrationApiController(IAdministrationService service) : ControllerBase
{
[HttpPost("payment-residues/purge"), EndpointSummary("Purger les paiements techniques des comptes retires depuis au moins un an")]
[ProducesResponseType<PaymentResiduePurgeResult>(200)]
[Yavsc.Server.Helpers.ResourceUsageExempt]
public async Task<ActionResult<PaymentResiduePurgeResult>> PurgePaymentResidues(
[FromServices] Yavsc.Server.Helpers.IPaymentResidueService residues, CancellationToken ct)
=> Ok(await residues.PurgeAsync(ct));
[HttpGet("summary"), EndpointSummary("Statistiques du site et informations du logiciel")]
[ProducesResponseType<AdministrationSummary>(200)]
public async Task<ActionResult<AdministrationSummary>> Summary(CancellationToken ct)

View file

@ -90,10 +90,14 @@ public sealed class PodcastController(ILiveProcessor processor, IPodcastSchedule
/// <summary>Ends the broadcast and schedules preparation of its MP4 replay.</summary>
[HttpPost("{id:guid}/complete")]
[ProducesResponseType<PodcastResponse>(StatusCodes.Status200OK)]
public async Task<ActionResult<PodcastResponse>> Complete(Guid id, CancellationToken ct)
public async Task<ActionResult<PodcastResponse>> Complete(Guid id,
[FromServices] IPodcastObsService obs, CancellationToken ct)
{
var ownerId = User.GetUserId();
if (string.IsNullOrWhiteSpace(ownerId)) return Unauthorized();
if ((await schedule.GetAsync(id, ownerId, ct)).Podcast.FlowId is not null
&& (await obs.StatusAsync(id, ownerId, ct)).Enabled)
await obs.DeactivateAsync(id, ownerId, ct);
await processor.CompleteAsync(id, ownerId, ct);
return Ok((await schedule.GetAsync(id, ownerId, ct)).Podcast);
}

View file

@ -0,0 +1,57 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Yavsc.Abstract.Streaming;
using Yavsc.Api.Middleware;
using Yavsc.Api.Services;
using Yavsc.Server.Helpers;
namespace Yavsc.ApiControllers;
[ApiController, ApiExplorerSettings(GroupName = "podcasts")]
[Authorize(Policy = "ApiScope")]
[Route(Constants.APIPrefix + "/podcasts")]
[TypeFilter(typeof(PodcastExceptionFilter))]
[ResponseCache(NoStore = true, Location = ResponseCacheLocation.None)]
public sealed class PodcastObsController(IPodcastObsService obs) : ControllerBase
{
[HttpPost("{id:guid}/obs"), EndpointSummary("Activer OBS pour une emission programmee et obtenir une cle a usage limite")]
[ProducesResponseType<PodcastObsCredentials>(200)]
[ProducesResponseType<ProblemDetails>(403)]
[ProducesResponseType<ProblemDetails>(404)]
[ProducesResponseType<ProblemDetails>(409)]
[ProducesResponseType<ProblemDetails>(429)]
[ProducesResponseType<ProblemDetails>(413)]
[ProducesResponseType<ProblemDetails>(503)]
public async Task<ActionResult<PodcastObsCredentials>> Activate(Guid id, CancellationToken ct)
=> Ok(await obs.ActivateAsync(id, User.GetUserId(), ct));
[HttpGet("{id:guid}/obs"), EndpointSummary("Consulter l'activation OBS et les erreurs de reception, sans exposer la cle")]
[ProducesResponseType<PodcastObsStatus>(200)]
[ProducesResponseType<ProblemDetails>(403)]
[ProducesResponseType<ProblemDetails>(404)]
public async Task<ActionResult<PodcastObsStatus>> Status(Guid id, CancellationToken ct)
=> Ok(await obs.StatusAsync(id, User.GetUserId(), ct));
[HttpDelete("{id:guid}/obs"), EndpointSummary("Revoquer la cle OBS et deconnecter le diffuseur")]
[ProducesResponseType(204)]
[ProducesResponseType<ProblemDetails>(403)]
[ProducesResponseType<ProblemDetails>(404)]
[ProducesResponseType<ProblemDetails>(503)]
[ResourceUsageRelief]
public async Task<IActionResult> Deactivate(Guid id, CancellationToken ct)
{
await obs.DeactivateAsync(id, User.GetUserId(), ct);
return NoContent();
}
[AllowAnonymous, HttpPost("relay/auth")]
[RequestSizeLimit(4096), ResourceUsageExempt]
[EndpointSummary("Authentification externe MediaMTX : publication avec cle, lecture interne et administration privees")]
[ProducesResponseType<PodcastRelayAuthorization>(200)]
[ProducesResponseType(401)]
public async Task<IActionResult> Authenticate(PodcastRelayAuthentication request, CancellationToken ct)
{
var authorization = await obs.AuthenticateAsync(request, ct);
return authorization is null ? Unauthorized() : Ok(authorization);
}
}

View file

@ -81,3 +81,18 @@ Authorization: Bearer {{token}}
### OpenAPI in development (requires an Administrator token)
GET {{baseUrl}}/openapi/podcasts.json
Authorization: Bearer {{token}}
### Activate OBS for an owned planned podcast (returns a one-time secret)
POST {{baseUrl}}/api/v1/podcasts/{{id}}/obs
Authorization: Bearer {{token}}
### OBS activation status (never returns the stream key)
GET {{baseUrl}}/api/v1/podcasts/{{id}}/obs
Authorization: Bearer {{token}}
### Revoke OBS and disconnect its publisher (allowed at consumption limit)
DELETE {{baseUrl}}/api/v1/podcasts/{{id}}/obs
Authorization: Bearer {{token}}
# Activation: 403 other owner/closed account, 404 missing emission,
# 409 already started, 413 disk full, 429 consumption limit, 503 OBS disabled.
# relay/auth is called by MediaMTX, not by the end-user.

View file

@ -153,6 +153,7 @@ internal class Program
.UseRouting()
.UseAuthentication()
.UseCors("default")
.UseMiddleware<WithdrawnAccountMiddleware>()
.UseAuthorization()
.UseMiddleware<ResourceUsageTelemetryMiddleware>();
app.MapIdentityApi<ApplicationUser>().RequireAuthorization("ApiScope");

View file

@ -1,4 +1,5 @@
using Yavsc.ApiControllers.Administration;
using Microsoft.Extensions.DependencyInjection.Extensions;
namespace Yavsc.Api.Services;
@ -9,6 +10,8 @@ public static class AdministrationServiceCollectionExtensions
services.AddHttpContextAccessor();
services.AddScoped<IAdministrationService, AdministrationService>();
services.AddScoped<AdministrationExceptionFilter>();
services.TryAddSingleton(TimeProvider.System);
services.AddScoped<Yavsc.Server.Helpers.IPaymentResidueService, Yavsc.Server.Helpers.PaymentResidueService>();
services.AddOpenApi(Constants.Administration, options =>
options.ShouldInclude = description => description.GroupName == Constants.Administration);
return services;

View file

@ -0,0 +1,33 @@
namespace Yavsc.Api.Services;
public sealed class PodcastObsOptions
{
public bool Enabled { get; set; }
public string ServerUrl { get; set; } = "";
public string RelayApiUrl { get; set; } = "http://127.0.0.1:9997/";
public string RelayReadUrl { get; set; } = "rtmp://127.0.0.1:1935/";
public string RelayUser { get; set; } = "yavsc";
public string RelayPassword { get; set; } = "";
public int ActivationMinutes { get; set; } = 30;
public int MaxDurationMinutes { get; set; } = 120;
public int MaxConcurrentBroadcasts { get; set; } = 2;
public bool AllowUnencryptedRtmp { get; set; }
public void Validate()
{
if (!Enabled) return;
if (!Uri.TryCreate(ServerUrl, UriKind.Absolute, out var server)
|| (server.Scheme != "rtmps" && !(AllowUnencryptedRtmp && server.Scheme == "rtmp"))
|| server.UserInfo.Length != 0 || server.Query.Length != 0 || server.Fragment.Length != 0
|| server.AbsolutePath is not ("" or "/")
|| !Uri.TryCreate(RelayApiUrl, UriKind.Absolute, out var api) || api.Scheme is not ("http" or "https")
|| api.UserInfo.Length != 0 || api.Query.Length != 0 || api.Fragment.Length != 0
|| !Uri.TryCreate(RelayReadUrl, UriKind.Absolute, out var read) || read.Scheme != "rtmp"
|| read.UserInfo.Length != 0 || read.Query.Length != 0 || read.Fragment.Length != 0
|| read.AbsolutePath is not ("" or "/")
|| RelayPassword.Length < 32 || string.IsNullOrWhiteSpace(RelayUser)
|| ActivationMinutes is < 1 or > 1440 || MaxDurationMinutes is < 1 or > 1440
|| MaxConcurrentBroadcasts is < 1 or > 16)
throw new InvalidOperationException("Invalid Podcast:Obs relay configuration. Use RTMPS, private relay addresses and a random password of at least 32 characters.");
}
}

View file

@ -0,0 +1,62 @@
#nullable enable
using System.Net;
using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;
using Microsoft.Extensions.Options;
namespace Yavsc.Api.Services;
public sealed record PodcastObsPublisher(Guid PodcastId, Guid ConnectionId, bool Secure);
public interface IPodcastObsRelay
{
Task<IReadOnlyList<PodcastObsPublisher>> PublishersAsync(CancellationToken ct);
Task KickAsync(Guid id, CancellationToken ct, Guid? connectionId = null);
}
public sealed class PodcastObsRelay(HttpClient http, IOptions<PodcastObsOptions> options) : IPodcastObsRelay
{
private HttpRequestMessage Request(HttpMethod method, string path)
{
var settings = options.Value;
settings.Validate();
var request = new HttpRequestMessage(method, new Uri(new Uri(settings.RelayApiUrl.TrimEnd('/') + "/"), path));
request.Headers.Authorization = new AuthenticationHeaderValue("Basic",
Convert.ToBase64String(Encoding.UTF8.GetBytes($"{settings.RelayUser}:{settings.RelayPassword}")));
return request;
}
public async Task<IReadOnlyList<PodcastObsPublisher>> PublishersAsync(CancellationToken ct)
{
var publishers = new List<PodcastObsPublisher>();
var page = 0;
while (true)
{
using var request = Request(HttpMethod.Get, $"v3/paths/list?itemsPerPage=100&page={page}");
using var response = await http.SendAsync(request, ct);
response.EnsureSuccessStatusCode();
using var document = await JsonDocument.ParseAsync(await response.Content.ReadAsStreamAsync(ct), cancellationToken: ct);
foreach (var item in document.RootElement.GetProperty("items").EnumerateArray())
if (item.GetProperty("ready").GetBoolean()
&& PodcastObsService.TryId(item.GetProperty("name").GetString() ?? "", out var id)
&& item.TryGetProperty("source", out var source) && source.ValueKind == JsonValueKind.Object
&& source.GetProperty("type").GetString() is "rtmpConn" or "rtmpsConn"
&& Guid.TryParse(source.GetProperty("id").GetString(), out var connection))
publishers.Add(new(id, connection, source.GetProperty("type").GetString() == "rtmpsConn"));
if (++page >= document.RootElement.GetProperty("pageCount").GetInt32()) break;
}
return publishers;
}
public async Task KickAsync(Guid id, CancellationToken ct, Guid? connectionId = null)
{
foreach (var publisher in (await PublishersAsync(ct)).Where(p => p.PodcastId == id
&& (!connectionId.HasValue || p.ConnectionId == connectionId)))
{
using var request = Request(HttpMethod.Post, $"v3/{(publisher.Secure ? "rtmps" : "rtmp")}/conns/kick/{publisher.ConnectionId}");
using var response = await http.SendAsync(request, ct);
if (response.StatusCode != HttpStatusCode.NotFound) response.EnsureSuccessStatusCode();
}
}
}

View file

@ -0,0 +1,158 @@
#nullable enable
using System.Security.Cryptography;
using System.Text;
using Microsoft.AspNetCore.WebUtilities;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options;
using Yavsc.Abstract.Streaming;
using Yavsc.Models;
using Yavsc.Models.Streaming;
using Yavsc.Server.Helpers;
using Yavsc.Services;
using Yavsc.Settings;
namespace Yavsc.Api.Services;
public interface IPodcastObsService
{
Task<PodcastObsCredentials> ActivateAsync(Guid id, string ownerId, CancellationToken ct);
Task<PodcastObsStatus> StatusAsync(Guid id, string ownerId, CancellationToken ct);
Task DeactivateAsync(Guid id, string ownerId, CancellationToken ct);
Task<PodcastRelayAuthorization?> AuthenticateAsync(PodcastRelayAuthentication request, CancellationToken ct);
}
public sealed class PodcastObsService(ApplicationDbContext db, IOptions<PodcastObsOptions> options,
IOptions<ResourceUsageOptions> usageOptions, IPodcastObsRelay relay, TimeProvider clock,
ILogger<PodcastObsService> logger) : IPodcastObsService
{
private PodcastObsOptions Settings()
{
var value = options.Value;
if (!value.Enabled) throw new PodcastException(503, "L'entree OBS n'est pas configuree sur cette instance.");
value.Validate();
return value;
}
public Task<PodcastObsCredentials> ActivateAsync(Guid id, string ownerId, CancellationToken ct)
=> ResourceUsageTracker.WithUserLockAsync(db, ownerId, async () =>
{
var settings = Settings();
var flow = await OwnedAsync(id, ownerId, ct);
if (flow.StartedAt is not null)
throw new PodcastException(409, "Cette emission a deja demarre. Preparez une nouvelle emission.");
if (flow.Owner.WithdrawalRequestedAt is not null)
throw new PodcastException(403, "Le compte est ferme.");
if (await QuotaReachedAsync(ownerId, ct))
throw new PodcastException(429, "Le seuil de consommation est atteint.");
if (flow.Owner.DiskUsage >= flow.Owner.GetEffectiveDiskQuota(clock.GetUtcNow()))
throw new PodcastException(413, "Le quota disque est atteint.");
var key = Convert.ToHexString(RandomNumberGenerator.GetBytes(32)).ToLowerInvariant();
flow.ObsKeyHash = Hash(key);
flow.ObsEnabledUntil = clock.GetUtcNow().AddMinutes(settings.ActivationMinutes);
flow.ObsConnectionId = null;
flow.ObsLastError = null;
await db.SaveChangesAsync(ct);
return new PodcastObsCredentials(settings.ServerUrl.TrimEnd('/'),
$"obs/{id:N}?key={key}", flow.ObsEnabledUntil.Value);
}, ct);
public async Task<PodcastObsStatus> StatusAsync(Guid id, string ownerId, CancellationToken ct)
{
var flow = await OwnedAsync(id, ownerId, ct, tracking: false);
return new(flow.ObsKeyHash is not null &&
(flow.StartedAt is not null || flow.ObsEnabledUntil > clock.GetUtcNow()),
flow.ObsEnabledUntil, flow.ObsLastError);
}
public async Task DeactivateAsync(Guid id, string ownerId, CancellationToken ct)
{
var connectionId = await ResourceUsageTracker.WithUserLockAsync(db, ownerId, async () =>
{
var flow = await OwnedAsync(id, ownerId, ct);
var connection = flow.ObsConnectionId;
flow.ObsKeyHash = null;
flow.ObsEnabledUntil = null;
flow.ObsConnectionId = null;
await db.SaveChangesAsync(ct);
return connection;
}, ct);
if (connectionId.HasValue) await relay.KickAsync(id, ct, connectionId);
}
public async Task<PodcastRelayAuthorization?> AuthenticateAsync(PodcastRelayAuthentication request, CancellationToken ct)
{
var settings = Settings();
if (request.User == settings.RelayUser && EqualSecret(request.Password, settings.RelayPassword))
{
if (request.Action == "api" || request.Action == "read" && request.Protocol == "rtmp" && TryId(request.Path, out _))
return new(null);
}
if (request.Action == "publish" && request.Protocol == "rtmp" && TryId(request.Path, out var id))
{
var query = QueryHelpers.ParseQuery(request.Query ?? "");
if (query.TryGetValue("key", out var keys) && keys.Count == 1 && keys[0] is { Length: 64 } key
&& Guid.TryParse(request.Id, out var connectionId))
{
var flow = await db.LiveFlow.AsNoTracking().Include(f => f.Owner)
.SingleOrDefaultAsync(f => f.PodcastId == id && !f.PodcastDeleted, ct);
if (flow is not null)
return await ResourceUsageTracker.WithUserLockAsync<PodcastRelayAuthorization?>(db, flow.OwnerId, async () =>
{
var current = await db.LiveFlow.Include(f => f.Owner).SingleAsync(f => f.PodcastId == id, ct);
await db.Entry(current).ReloadAsync(ct);
await db.Entry(current.Owner).ReloadAsync(ct);
if (current is { StartedAt: null, ObsKeyHash: not null, PodcastDeleted: false }
&& (current.ObsConnectionId is null || current.ObsConnectionId == connectionId)
&& current.ObsEnabledUntil > clock.GetUtcNow() && current.Owner.WithdrawalRequestedAt is null
&& EqualSecret(Hash(key), current.ObsKeyHash)
&& !await QuotaReachedAsync(current.OwnerId, ct)
&& current.Owner.DiskUsage < current.Owner.GetEffectiveDiskQuota(clock.GetUtcNow()))
{
current.ObsConnectionId = connectionId;
await db.SaveChangesAsync(ct);
return new(clock.GetUtcNow().AddMinutes(Math.Min(current.PlannedDurationMinutes ?? 1, settings.MaxDurationMinutes)));
}
logger.LogWarning("OBS publication refused for emission {PodcastId}", id);
return null;
}, ct);
}
}
logger.LogWarning("OBS relay authentication refused for action {Action}", request.Action is "publish" or "read" or "api" ? request.Action : "other");
return null;
}
private async Task<bool> QuotaReachedAsync(string ownerId, CancellationToken ct)
{
var record = await db.ResourceUsageRecords.AsNoTracking().Where(r => r.UserId == ownerId)
.OrderByDescending(r => r.RecordedAtUtc).ThenByDescending(r => r.Id).FirstOrDefaultAsync(ct);
var policy = usageOptions.Value;
var gross = record is null ? 0m : policy.Calculate(record.ApiCalls, record.CpuSeconds, record.BandwidthMb, record.StorageMb);
return ResourceUsageCredit.NetConsumption(gross, record?.CreditPoints ?? 0m) >= policy.GetLimit(ownerId);
}
private async Task<LiveFlow> OwnedAsync(Guid id, string ownerId, CancellationToken ct, bool tracking = true)
{
var query = db.LiveFlow.Include(f => f.Owner).AsQueryable();
if (!tracking) query = query.AsNoTracking();
var flow = await query.SingleOrDefaultAsync(f => f.PodcastId == id && !f.PodcastDeleted, ct)
?? throw new PodcastException(404, "Emission introuvable.");
if (tracking)
{
await db.Entry(flow).ReloadAsync(ct);
await db.Entry(flow.Owner).ReloadAsync(ct);
}
if (flow.OwnerId != ownerId) throw new PodcastException(403, "Seul l'auteur peut activer OBS.");
return flow;
}
internal static bool TryId(string? path, out Guid id)
{
id = default;
return path is not null && path.StartsWith("obs/", StringComparison.Ordinal) && Guid.TryParseExact(path[4..], "N", out id);
}
private static string Hash(string value) => Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(value)));
private static bool EqualSecret(string? actual, string expected)
=> actual is not null && CryptographicOperations.FixedTimeEquals(Encoding.UTF8.GetBytes(actual), Encoding.UTF8.GetBytes(expected));
}

View file

@ -0,0 +1,267 @@
#nullable enable
using System.Diagnostics;
using System.Globalization;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options;
using Yavsc.Models;
using Yavsc.Server.Helpers;
using Yavsc.Services;
using Yavsc.Settings;
namespace Yavsc.Api.Services;
public sealed class PodcastObsWorker(IServiceScopeFactory scopes, IOptions<PodcastObsOptions> options,
ILogger<PodcastObsWorker> logger) : BackgroundService
{
private sealed record Capture(CancellationTokenSource Cancellation, Task Task);
private readonly Dictionary<Guid, Capture> captures = new();
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
if (!options.Value.Enabled) return;
options.Value.Validate();
try
{
while (!stoppingToken.IsCancellationRequested)
{
try
{
using var scope = scopes.CreateScope();
var relay = scope.ServiceProvider.GetRequiredService<IPodcastObsRelay>();
var db = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
foreach (var pair in captures.Where(c => c.Value.Task.IsCompleted).ToArray())
{
captures.Remove(pair.Key);
pair.Value.Cancellation.Dispose();
await pair.Value.Task;
}
foreach (var publisher in await relay.PublishersAsync(stoppingToken))
{
var flow = await db.LiveFlow.AsNoTracking().Include(f => f.Owner)
.SingleOrDefaultAsync(f => f.PodcastId == publisher.PodcastId, stoppingToken);
var allowed = flow is { PodcastDeleted: false, ObsKeyHash: not null }
&& flow.ObsConnectionId == publisher.ConnectionId
&& flow.Owner.WithdrawalRequestedAt is null;
if (!allowed)
{
if (captures.TryGetValue(publisher.PodcastId, out var running)) running.Cancellation.Cancel();
await relay.KickAsync(publisher.PodcastId, stoppingToken, publisher.ConnectionId);
continue;
}
if (captures.ContainsKey(publisher.PodcastId)) continue;
if (flow!.StartedAt is not null || flow.ObsEnabledUntil <= DateTimeOffset.UtcNow
|| captures.Count >= options.Value.MaxConcurrentBroadcasts)
{
await relay.KickAsync(publisher.PodcastId, stoppingToken, publisher.ConnectionId);
await FailActivationAsync(publisher.PodcastId, publisher.ConnectionId, "Emission deja demarree, activation expiree ou capacite OBS atteinte.", stoppingToken);
continue;
}
var cancellation = CancellationTokenSource.CreateLinkedTokenSource(stoppingToken);
captures.Add(publisher.PodcastId, new(cancellation,
CaptureAsync(publisher.PodcastId, flow.OwnerId, publisher.ConnectionId, cancellation.Token)));
}
}
catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested) { break; }
catch (Exception ex)
{
logger.LogError(ex, "OBS relay scan failed; retrying");
}
await Task.Delay(TimeSpan.FromSeconds(1), stoppingToken);
}
}
catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested) { }
finally
{
foreach (var capture in captures.Values) capture.Cancellation.Cancel();
await Task.WhenAll(captures.Values.Select(c => c.Task));
foreach (var capture in captures.Values) capture.Cancellation.Dispose();
}
}
private async Task CaptureAsync(Guid id, string ownerId, Guid connectionId, CancellationToken ct)
{
using var scope = scopes.CreateScope();
var services = scope.ServiceProvider;
var db = services.GetRequiredService<ApplicationDbContext>();
var processor = services.GetRequiredService<ILiveProcessor>();
var relay = services.GetRequiredService<IPodcastObsRelay>();
var media = services.GetRequiredService<IOptions<PodcastOptions>>().Value;
var directory = Path.Combine(media.RootPath, "obs-capture-" + id.ToString("N"));
string? error = null;
var started = false;
try
{
Directory.CreateDirectory(directory);
var podcast = await services.GetRequiredService<IPodcastScheduleService>().StartAsync(id, ownerId, ct, connectionId);
started = true;
using var deadline = CancellationTokenSource.CreateLinkedTokenSource(ct);
deadline.CancelAfter(TimeSpan.FromMinutes(Math.Min(podcast.PlannedDurationMinutes ?? 1, options.Value.MaxDurationMinutes)));
await ReceiveAsync(id, ownerId, connectionId, directory, db, processor, media, services, deadline.Token);
}
catch (OperationCanceledException)
{
logger.LogInformation("OBS capture {PodcastId} stopped or reached its duration limit", id);
}
catch (Exception ex)
{
// FFmpeg diagnostics and request URLs can contain credentials: never persist or log them.
error = ex is PodcastException or ResourceUsageLimitException ? ex.Message : "Reception OBS impossible. Verifiez le relais, FFmpeg et l'encodage H.264/AAC.";
logger.LogError("OBS capture {PodcastId} failed ({ErrorType})", id, ex.GetType().Name);
}
finally
{
try
{
using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(20));
await relay.KickAsync(id, timeout.Token, connectionId);
db.ChangeTracker.Clear();
var flow = await db.LiveFlow.Include(f => f.Owner).SingleOrDefaultAsync(f => f.PodcastId == id, timeout.Token);
if (flow is not null)
{
if (flow.ObsKeyHash is null && flow.ObsConnectionId is null) error = null;
if (started && flow.Owner.WithdrawalRequestedAt is null)
await processor.CompleteAsync(id, ownerId, timeout.Token);
if (flow.ObsConnectionId == connectionId || flow.ObsKeyHash is null)
{
flow.ObsKeyHash = null;
flow.ObsEnabledUntil = null;
flow.ObsConnectionId = null;
flow.ObsLastError = error;
}
await db.SaveChangesAsync(timeout.Token);
}
}
catch (Exception ex)
{
logger.LogError("OBS capture {PodcastId} cleanup failed ({ErrorType}); operator intervention required", id, ex.GetType().Name);
await FailActivationAsync(id, connectionId, "Finalisation OBS impossible ; intervention de l'administration requise.", CancellationToken.None);
}
if (Directory.Exists(directory)) Directory.Delete(directory, recursive: true);
}
}
private async Task ReceiveAsync(Guid id, string ownerId, Guid connectionId, string directory, ApplicationDbContext db,
ILiveProcessor processor, PodcastOptions media, IServiceProvider services, CancellationToken ct)
{
var settings = options.Value;
var input = new UriBuilder(new Uri(new Uri(settings.RelayReadUrl.TrimEnd('/') + "/"), $"obs/{id:N}"))
{ Query = $"user={Uri.EscapeDataString(settings.RelayUser)}&pass={Uri.EscapeDataString(settings.RelayPassword)}" };
var start = new ProcessStartInfo(media.FfmpegPath)
{
UseShellExecute = false, RedirectStandardOutput = true, RedirectStandardError = true,
CreateNoWindow = true, WorkingDirectory = directory
};
foreach (var argument in new[]
{
"-nostdin", "-hide_banner", "-loglevel", "error", "-rw_timeout", "15000000",
"-i", input.Uri.AbsoluteUri, "-map", "0:v:0", "-map", "0:a:0?", "-c", "copy",
"-f", "segment", "-segment_format", "mpegts", "-segment_time", "2",
"-segment_list", "pipe:1", "-segment_list_type", "csv", "segment-%08d.ts"
}) start.ArgumentList.Add(argument);
using var process = Process.Start(start) ?? throw new IOException("FFmpeg could not start.");
var diagnostics = DrainAsync(process.StandardError);
using var monitoring = CancellationTokenSource.CreateLinkedTokenSource(ct);
var guard = GuardBufferAsync(directory, media.MaxSegmentBytes, monitoring.Token);
var next = 0;
var total = 0L;
var revoked = false;
try
{
while (true)
{
using var idle = CancellationTokenSource.CreateLinkedTokenSource(ct);
idle.CancelAfter(TimeSpan.FromSeconds(20));
var read = process.StandardOutput.ReadLineAsync(idle.Token).AsTask();
if (await Task.WhenAny(read, guard) == guard) await guard;
var line = await read;
if (line is null) break;
var fields = line.Split(',');
if (fields.Length != 3 || fields[0] != $"segment-{next:D8}.ts"
|| !double.TryParse(fields[1], CultureInfo.InvariantCulture, out var begin)
|| !double.TryParse(fields[2], CultureInfo.InvariantCulture, out var end)
|| !double.IsFinite(end - begin) || end - begin <= 0 || end - begin > 15)
throw new PodcastException(400, "Segments OBS invalides ; configurez H.264/AAC et des images cles toutes les deux secondes.");
var path = Path.Combine(directory, fields[0]);
var bytes = new FileInfo(path).Length;
if (bytes == 0 || bytes > media.MaxSegmentBytes)
throw new PodcastException(413, "Segment OBS trop volumineux ; reduisez le debit et l'intervalle des images cles.");
total = checked(total + bytes);
await ResourceUsageTracker.RecordStorageAsync(db, ownerId, ownerId, $"podcast/{id:N}", total, ct,
write: async () =>
{
var user = await db.Users.SingleAsync(u => u.Id == ownerId, ct);
await db.Entry(user).ReloadAsync(ct);
var flow = await db.LiveFlow.SingleAsync(f => f.PodcastId == id, ct);
await db.Entry(flow).ReloadAsync(ct);
if (user.WithdrawalRequestedAt is not null || flow.ObsKeyHash is null
|| flow.ObsConnectionId != connectionId || flow.PodcastDeleted)
{
revoked = true;
throw new OperationCanceledException("OBS activation revoked or account closed.", ct);
}
if (bytes > user.GetEffectiveDiskQuota(DateTimeOffset.UtcNow) - user.DiskUsage)
throw new PodcastException(413, "Quota disque atteint.");
await using var stream = File.OpenRead(path);
await processor.AppendAsync(id, ownerId, next, end - begin, stream, ct);
user.DiskUsage = checked(user.DiskUsage + bytes);
},
policy: services.GetRequiredService<IOptions<ResourceUsageOptions>>().Value,
bandwidthMb: (decimal)bytes / (1024m * 1024m));
File.Delete(path);
next++;
}
await process.WaitForExitAsync(ct);
if (process.ExitCode != 0 || next == 0) throw new IOException("FFmpeg ingest failed or produced no media.");
}
catch (OperationCanceledException) when (!ct.IsCancellationRequested && !revoked)
{
throw new PodcastException(408, "Aucun segment OBS recu depuis vingt secondes ; verifiez l'encodeur et la connexion.");
}
finally
{
if (!process.HasExited) process.Kill(entireProcessTree: true);
await process.WaitForExitAsync(CancellationToken.None);
await diagnostics;
monitoring.Cancel();
try { await guard; }
catch (OperationCanceledException) when (monitoring.IsCancellationRequested) { }
}
}
private static async Task GuardBufferAsync(string directory, int maxSegmentBytes, CancellationToken ct)
{
while (true)
{
var pending = 0L;
foreach (var path in Directory.EnumerateFiles(directory, "*.ts"))
{
var file = new FileInfo(path);
if (!file.Exists) continue;
var bytes = file.Length;
if (bytes > maxSegmentBytes || (pending += bytes) > 64L * 1024 * 1024)
throw new PodcastException(413, "Capture OBS trop volumineuse ou stockage trop lent ; reduisez le debit.");
}
await Task.Delay(100, ct);
}
}
private static async Task DrainAsync(StreamReader reader)
{
var buffer = new char[1024];
while (await reader.ReadAsync(buffer) != 0) { }
}
private async Task FailActivationAsync(Guid id, Guid connectionId, string message, CancellationToken ct)
{
using var scope = scopes.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
var flow = await db.LiveFlow.SingleOrDefaultAsync(f => f.PodcastId == id, ct);
if (flow is null || flow.ObsKeyHash is not null && flow.ObsConnectionId != connectionId) return;
flow.ObsKeyHash = null;
flow.ObsEnabledUntil = null;
flow.ObsConnectionId = null;
flow.ObsLastError = message;
await db.SaveChangesAsync(ct);
}
}

View file

@ -12,7 +12,7 @@ namespace Yavsc.Api.Services;
public interface IPodcastScheduleService
{
Task<PodcastResponse> PrepareAsync(string ownerId, PreparePodcastRequest request, Guid? id, CancellationToken ct);
Task<PodcastResponse> StartAsync(Guid id, string ownerId, CancellationToken ct);
Task<PodcastResponse> StartAsync(Guid id, string ownerId, CancellationToken ct, Guid? obsConnectionId = null);
Task<IReadOnlyList<PodcastResponse>> ListAsync(string ownerId, CancellationToken ct);
Task<PodcastManifestResponse> GetAsync(Guid id, string ownerId, CancellationToken ct);
Task<IReadOnlyList<PodcastAnnouncementResponse>> AnnouncementsAsync(CancellationToken ct);
@ -35,6 +35,8 @@ public sealed class PodcastScheduleService(ApplicationDbContext db, ILiveProcess
try
{
var flow = id.HasValue ? await OwnedAsync(id.Value, ownerId, ct) : null;
if (flow?.ObsKeyHash is not null)
throw new PodcastException(409, "Desactivez l'entree OBS avant de modifier l'emission.");
if (flow != null && (flow.StartedAt != null
|| (await processor.ListAsync(ct)).Any(p => p.Id == id)))
throw new PodcastException(409, "Une emission demarree ne peut plus etre reprogrammee.");
@ -63,21 +65,33 @@ public sealed class PodcastScheduleService(ApplicationDbContext db, ILiveProcess
finally { Gate.Release(); }
}
public async Task<PodcastResponse> StartAsync(Guid id, string ownerId, CancellationToken ct)
public async Task<PodcastResponse> StartAsync(Guid id, string ownerId, CancellationToken ct, Guid? obsConnectionId = null)
{
await Gate.WaitAsync(ct);
try
{
var flow = await OwnedAsync(id, ownerId, ct);
var existing = (await processor.ListAsync(ct)).SingleOrDefault(p => p.Id == id);
if (existing != null && existing.State != PodcastState.Live)
throw new PodcastException(409, "Cette emission est terminee. Preparez une nouvelle emission.");
if (flow.StartedAt != null && existing == null)
throw new PodcastException(404, "Les medias de cette emission sont introuvables.");
var podcast = await processor.CreateAsync(ownerId, flow.Owner.UserName ?? ownerId, flow.Title, ct, id);
flow.StartedAt ??= podcast.CreatedAt;
await db.SaveChangesAsync(ct);
return Enrich(podcast, flow);
return await Yavsc.Server.Helpers.ResourceUsageTracker.WithUserLockAsync(db, ownerId, async () =>
{
var flow = await OwnedAsync(id, ownerId, ct);
await db.Entry(flow).ReloadAsync(ct);
await db.Entry(flow.Owner).ReloadAsync(ct);
if (flow.Owner.WithdrawalRequestedAt is not null)
throw new PodcastException(403, "Le compte est ferme.");
if (obsConnectionId.HasValue && (flow.ObsConnectionId != obsConnectionId
|| flow.ObsKeyHash is null || flow.ObsEnabledUntil <= DateTimeOffset.UtcNow))
throw new OperationCanceledException("OBS connection revoked or activation expired.", ct);
if (!obsConnectionId.HasValue && flow.ObsKeyHash is not null)
throw new PodcastException(409, "Desactivez OBS avant de demarrer une capture PostIt.");
var existing = (await processor.ListAsync(ct)).SingleOrDefault(p => p.Id == id);
if (existing != null && existing.State != PodcastState.Live)
throw new PodcastException(409, "Cette emission est terminee. Preparez une nouvelle emission.");
if (flow.StartedAt != null && existing == null)
throw new PodcastException(404, "Les medias de cette emission sont introuvables.");
var podcast = await processor.CreateAsync(ownerId, flow.Owner.UserName ?? ownerId, flow.Title, ct, id);
flow.StartedAt ??= podcast.CreatedAt;
await db.SaveChangesAsync(ct);
return Enrich(podcast, flow);
}, ct);
}
finally { Gate.Release(); }
}
@ -130,10 +144,24 @@ public sealed class PodcastScheduleService(ApplicationDbContext db, ILiveProcess
var flow = await db.LiveFlow.SingleOrDefaultAsync(f => f.PodcastId == id, ct);
if (flow == null) { await processor.DeleteAsync(id, ownerId, ct); return; }
if (flow.OwnerId != ownerId) throw new PodcastException(403, "Seul l'auteur peut supprimer ce podcast.");
if (flow.ObsKeyHash is not null)
throw new PodcastException(409, "Desactivez l'entree OBS avant de supprimer l'emission.");
var podcast = (await processor.ListAsync(ct)).SingleOrDefault(p => p.Id == id);
if (podcast?.State == PodcastState.Live)
throw new PodcastException(409, "Terminez le direct avant de le supprimer.");
if (podcast != null) await processor.DeleteAsync(id, ownerId, ct);
var storage = await db.ResourceStorageRecords.AsNoTracking()
.SingleOrDefaultAsync(r => r.UserId == ownerId && r.Path == $"podcast/{id:N}", ct);
if (storage is not null)
{
await Yavsc.Server.Helpers.ResourceUsageTracker.RecordStorageAsync(db, ownerId,
flow.OwnerId, storage.Path, 0, ct, write: async () =>
{
var owner = await db.Users.SingleAsync(u => u.Id == ownerId, ct);
await db.Entry(owner).ReloadAsync(ct);
owner.DiskUsage = Math.Max(0, owner.DiskUsage - storage.Bytes);
});
}
flow.PodcastDeleted = true;
await db.SaveChangesAsync(ct);
}

View file

@ -7,6 +7,11 @@ public static class PodcastServiceCollectionExtensions
public static IServiceCollection AddPodcasts(this IServiceCollection services, IConfiguration configuration)
{
services.Configure<PodcastOptions>(configuration.GetSection("Podcast"));
services.Configure<PodcastObsOptions>(configuration.GetSection("Podcast:Obs"));
services.AddScoped<IPodcastObsService, PodcastObsService>();
services.AddHttpClient<IPodcastObsRelay, PodcastObsRelay>(client => client.Timeout = TimeSpan.FromSeconds(10))
.ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler { AllowAutoRedirect = false });
services.AddHostedService<PodcastObsWorker>();
services.AddSingleton<ILiveProcessor, LiveProcessor>();
services.AddScoped<IPodcastScheduleService, PodcastScheduleService>();
services.AddSingleton<IPodcastReplayRemuxer, FfmpegPodcastReplayRemuxer>();

View file

@ -102,6 +102,7 @@ internal class Program
.UseRouting()
.UseAuthentication()
.UseCors("default")
.UseMiddleware<WithdrawnAccountMiddleware>()
.UseAuthorization()
.UseMiddleware<ResourceUsageTelemetryMiddleware>()
;

View file

@ -1049,10 +1049,12 @@ IHtmlLocalizerFactory htmlLocalizerFactory,
return View(new UnregisterViewModel { UserId = id, ReturnUrl = returnUrl });
}
[HttpPost, Authorize("AdministratorOnly")]
public async Task<IActionResult> AdminDelete(UnregisterViewModel model)
[HttpPost, Authorize("AdministratorOnly"), ValidateAntiForgeryToken]
public async Task<IActionResult> AdminDelete(UnregisterViewModel model,
[FromServices] Yavsc.Web.Services.IAccountWithdrawalService withdrawal)
{
var result = await DeleteUser(model.UserId);
if (!ModelState.IsValid) return BadRequest(ModelState);
var result = await DeleteUser(model.UserId, withdrawal);
if (!result.Succeeded)
{
@ -1062,14 +1064,16 @@ IHtmlLocalizerFactory htmlLocalizerFactory,
return View();
}
[HttpPost, Authorize]
public async Task<IActionResult> Delete(UnregisterViewModel model)
[HttpPost, Authorize, ValidateAntiForgeryToken]
public async Task<IActionResult> Delete(UnregisterViewModel model,
[FromServices] Yavsc.Web.Services.IAccountWithdrawalService withdrawal)
{
if (!ModelState.IsValid)
{
return View(model);
}
var result = await DeleteUser(model.UserId);
if (model.UserId != User.GetUserId()) return Forbid();
var result = await DeleteUser(User.GetUserId(), withdrawal);
if (!result.Succeeded)
{
@ -1080,20 +1084,30 @@ IHtmlLocalizerFactory htmlLocalizerFactory,
return RedirectToAction("Index", "Home");
}
async Task<IdentityResult> DeleteUser(string userId)
async Task<IdentityResult> DeleteUser(string userId, Yavsc.Web.Services.IAccountWithdrawalService withdrawal)
{
ApplicationUser user = await _userManager.FindByIdAsync(userId);
_dbContext.DeviceDeclaration.RemoveRange(_dbContext.DeviceDeclaration.Where(g => g.DeviceOwnerId == userId));
return await _userManager.DeleteAsync(user);
try
{
await withdrawal.WithdrawAsync(userId, HttpContext.RequestAborted);
return IdentityResult.Success;
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or HttpRequestException
or Yavsc.Web.Services.SubscriptionOperationException or DbUpdateException or InvalidOperationException)
{
_logger.LogError(ex, "Account withdrawal failed for {UserId}", userId);
return IdentityResult.Failed(new IdentityError
{
Code = "WithdrawalFailed",
Description = "Le retrait n'a pas pu etre termine. Contactez l'administration pour reprendre l'effacement."
});
}
}
private void AddErrors(IdentityResult result)
{
foreach (var error in result.Errors)
{
ModelState.AddModelError(string.Empty, _localizer[error.Code]);
ModelState.AddModelError(string.Empty, error.Code == "WithdrawalFailed" ? error.Description : _localizer[error.Code]);
}
}

View file

@ -96,6 +96,10 @@ public static class HostingExtensions
.ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler { AllowAutoRedirect = false });
services.AddScoped<Yavsc.Web.Services.IResourceSubscriptionService, Yavsc.Web.Services.ResourceSubscriptionService>();
services.TryAddSingleton(TimeProvider.System);
services.AddScoped<IPaymentResidueService, PaymentResidueService>();
services.AddScoped<Yavsc.Web.Services.IAccountWithdrawalService, Yavsc.Web.Services.AccountWithdrawalService>();
services.Configure<Yavsc.Services.PodcastOptions>(builder.Configuration.GetSection("Podcast"));
services.AddHostedService<Yavsc.Web.Services.PaymentResiduePurgeWorker>();
services.AddSession();
@ -1067,6 +1071,7 @@ public static class HostingExtensions
app.UseSwaggerUI();
app.UseRouting();
app.UseAuthentication();
app.UseMiddleware<WithdrawnAccountMiddleware>();
app.UseIdentityServer();
app.UseAuthorization();
app.UseCors("default");

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,43 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Yavsc.Migrations
{
/// <inheritdoc />
public partial class AccountWithdrawal : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropUniqueConstraint(name: "AK_AspNetUsers_Email", table: "AspNetUsers");
migrationBuilder.CreateIndex(name: "IX_AspNetUsers_Email", table: "AspNetUsers", column: "Email", unique: true);
migrationBuilder.AddColumn<DateTimeOffset>(
name: "WithdrawalRequestedAt",
table: "AspNetUsers",
type: "timestamp with time zone",
nullable: true);
migrationBuilder.AddColumn<DateTimeOffset>(
name: "WithdrawnAt",
table: "AspNetUsers",
type: "timestamp with time zone",
nullable: true);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropIndex(name: "IX_AspNetUsers_Email", table: "AspNetUsers");
migrationBuilder.AddUniqueConstraint(name: "AK_AspNetUsers_Email", table: "AspNetUsers", column: "Email");
migrationBuilder.DropColumn(
name: "WithdrawalRequestedAt",
table: "AspNetUsers");
migrationBuilder.DropColumn(
name: "WithdrawnAt",
table: "AspNetUsers");
}
}
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,61 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Yavsc.Migrations
{
/// <inheritdoc />
public partial class PodcastObsIngestion : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<Guid>(
name: "ObsConnectionId",
table: "LiveFlow",
type: "uuid",
nullable: true);
migrationBuilder.AddColumn<DateTimeOffset>(
name: "ObsEnabledUntil",
table: "LiveFlow",
type: "timestamp with time zone",
nullable: true);
migrationBuilder.AddColumn<string>(
name: "ObsKeyHash",
table: "LiveFlow",
type: "character varying(64)",
maxLength: 64,
nullable: true);
migrationBuilder.AddColumn<string>(
name: "ObsLastError",
table: "LiveFlow",
type: "character varying(512)",
maxLength: 512,
nullable: true);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "ObsConnectionId",
table: "LiveFlow");
migrationBuilder.DropColumn(
name: "ObsEnabledUntil",
table: "LiveFlow");
migrationBuilder.DropColumn(
name: "ObsKeyHash",
table: "LiveFlow");
migrationBuilder.DropColumn(
name: "ObsLastError",
table: "LiveFlow");
}
}
}

View file

@ -1218,9 +1218,16 @@ namespace Yavsc.Migrations
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.Property<DateTimeOffset?>("WithdrawalRequestedAt")
.HasColumnType("timestamp with time zone");
b.Property<DateTimeOffset?>("WithdrawnAt")
.HasColumnType("timestamp with time zone");
b.HasKey("Id");
b.HasAlternateKey("Email");
b.HasIndex("Email")
.IsUnique();
b.HasIndex("NormalizedEmail")
.HasDatabaseName("EmailIndex");
@ -3200,6 +3207,20 @@ namespace Yavsc.Migrations
b.Property<string>("MediaType")
.HasColumnType("text");
b.Property<Guid?>("ObsConnectionId")
.HasColumnType("uuid");
b.Property<DateTimeOffset?>("ObsEnabledUntil")
.HasColumnType("timestamp with time zone");
b.Property<string>("ObsKeyHash")
.HasMaxLength(64)
.HasColumnType("character varying(64)");
b.Property<string>("ObsLastError")
.HasMaxLength(512)
.HasColumnType("character varying(512)");
b.Property<string>("OwnerId")
.IsRequired()
.HasColumnType("text");

View file

@ -0,0 +1,208 @@
#nullable enable
using System.Text.Json;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options;
using Yavsc.Models;
using Yavsc.Server.Helpers;
using Yavsc.Services;
namespace Yavsc.Web.Services;
public interface IAccountWithdrawalService
{
Task WithdrawAsync(string userId, CancellationToken ct);
}
public sealed class AccountWithdrawalService(ApplicationDbContext db, UserManager<ApplicationUser> users,
IPayPalSubscriptionGateway paypal, IOptions<SiteSettings> site, IOptions<PodcastOptions> podcasts,
TimeProvider clock, ILogger<AccountWithdrawalService> logger) : IAccountWithdrawalService
{
public async Task WithdrawAsync(string userId, CancellationToken ct)
{
var user = await users.FindByIdAsync(userId)
?? throw new SubscriptionOperationException(404, "Compte introuvable.");
if (user.WithdrawnAt is not null) return;
var userName = user.UserName ?? throw new InvalidOperationException("Withdrawal requires a storage owner name.");
var personalDirectory = Child(site.Value.UserFilesRoot, userName);
var avatarFiles = new[] { ".png", ".s.png", ".xs.png" }.Select(ext => Child(site.Value.Avatars, userName + ext)).ToArray();
var started = await ResourceUsageTracker.WithUserLockAsync(db, userId, async () =>
{
await db.Entry(user).ReloadAsync(ct);
if (user.WithdrawnAt is not null) return false;
user.WithdrawalRequestedAt ??= clock.GetUtcNow();
user.LockoutEnabled = true;
user.LockoutEnd = DateTimeOffset.MaxValue;
user.SecurityStamp = Guid.NewGuid().ToString();
await db.SaveChangesAsync(ct);
return true;
}, ct);
if (!started) return;
var subscriptions = await db.ResourceSubscriptions.Where(s => s.UserId == userId).ToListAsync(ct);
foreach (var subscription in subscriptions)
{
if (subscription.State is "CANCELLED" or "EXPIRED") continue;
if (subscription.PayPalId is null)
{
if (subscription.State == "CREATING")
throw new SubscriptionOperationException(409, "Une creation PayPal doit etre rapprochee avant de confirmer le retrait.");
}
else
{
var remote = await paypal.GetAsync(subscription.PayPalId, ct);
if (remote.State is not ("CANCELLED" or "EXPIRED"))
await paypal.CancelAsync(subscription.PayPalId, ct);
}
subscription.State = "CANCELLED";
subscription.NextBillingAt = null;
await db.SaveChangesAsync(ct);
}
DeleteDirectory(personalDirectory);
foreach (var path in avatarFiles)
{
RejectLink(path);
if (Directory.Exists(Path.GetDirectoryName(path))) File.Delete(path);
}
await DeletePodcastsAsync(userId, ct);
await ResourceUsageTracker.WithUserLockAsync(db, userId, async () =>
{
await db.Entry(user).ReloadAsync(ct);
if (user.WithdrawnAt is not null) return true;
db.DeviceDeclaration.RemoveRange(await db.DeviceDeclaration.Where(d => d.DeviceOwnerId == userId).ToListAsync(ct));
db.UserLogins.RemoveRange(await db.UserLogins.Where(d => d.UserId == userId).ToListAsync(ct));
db.UserTokens.RemoveRange(await db.UserTokens.Where(d => d.UserId == userId).ToListAsync(ct));
db.UserClaims.RemoveRange(await db.UserClaims.Where(d => d.UserId == userId).ToListAsync(ct));
db.UserRoles.RemoveRange(await db.UserRoles.Where(d => d.UserId == userId).ToListAsync(ct));
db.BankIdentity.RemoveRange(await db.BankIdentity.Where(d => d.UserId == userId).ToListAsync(ct));
db.Contact.RemoveRange(await db.Contact.Where(d => d.OwnerId == userId || d.UserId == userId).ToListAsync(ct));
db.ResourceUsageRecords.RemoveRange(await db.ResourceUsageRecords.Where(d => d.UserId == userId).ToListAsync(ct));
db.ResourceStorageRecords.RemoveRange(await db.ResourceStorageRecords.Where(d => d.UserId == userId).ToListAsync(ct));
var posts = await db.BlogSpot.Where(p => p.AuthorId == userId).ToListAsync(ct);
foreach (var post in posts)
{
post.Title = "Contenu retire";
post.Article = null;
post.Photo = null;
}
var comments = await db.Comment.Where(p => p.AuthorId == userId).ToListAsync(ct);
foreach (var comment in comments) comment.Article = "Contenu retire";
var performer = await db.Performers.SingleOrDefaultAsync(p => p.PerformerId == userId, ct);
if (performer is not null)
{
performer.Active = false;
performer.AcceptNotifications = false;
performer.AcceptPublicContact = false;
performer.UseGeoLocalizationToReduceDistanceWithClients = false;
performer.WebSite = "";
performer.DonationPayPalEmail = null;
}
var flows = await db.LiveFlow.Where(f => f.OwnerId == userId).ToListAsync(ct);
foreach (var flow in flows)
{
flow.Title = "Contenu retire";
flow.Pitch = "";
flow.PublicAnnouncement = "";
flow.DifferedFileName = "";
flow.PodcastDeleted = true;
flow.ObsKeyHash = null;
flow.ObsEnabledUntil = null;
flow.ObsConnectionId = null;
flow.ObsLastError = null;
}
var fileIds = await db.UploadedFiles.Where(f => f.OwnerId == userId
|| db.BlogAttachedFiles.Any(a => a.FileId == f.Id && a.Post.AuthorId == userId))
.Select(f => f.Id).ToListAsync(ct);
var files = await db.UploadedFiles.Where(f => fileIds.Contains(f.Id)).ToListAsync(ct);
foreach (var file in files)
{
file.Path = "";
file.Length = 0;
file.ContentType = "application/octet-stream";
}
user.UserName = "withdrawn-" + Guid.NewGuid().ToString("N");
user.NormalizedUserName = user.UserName.ToUpperInvariant();
user.Email = user.UserName + "@invalid.invalid";
user.NormalizedEmail = user.Email.ToUpperInvariant();
user.EmailConfirmed = false;
user.FullName = null;
user.PhoneNumber = null;
user.PhoneNumberConfirmed = false;
user.PasswordHash = null;
user.TwoFactorEnabled = false;
user.PostalAddressId = null;
user.DedicatedGoogleCalendar = null;
user.Avatar = Constants.DefaultAvatar;
user.AllowMonthlyEmail = false;
user.DiskUsage = 0;
user.PremiumDiskQuotaUntil = null;
user.DiscoveryDiskQuotaUntil = null;
user.WithdrawnAt = clock.GetUtcNow();
await db.SaveChangesAsync(ct);
return true;
}, ct);
logger.LogInformation("Account withdrawal completed, files erased and identity pseudonymized");
}
private async Task DeletePodcastsAsync(string userId, CancellationToken ct)
{
var root = Path.GetFullPath(podcasts.Value.RootPath);
if (!Directory.Exists(root)) return;
RejectLink(root);
foreach (var directory in Directory.EnumerateDirectories(root))
{
if (!Guid.TryParseExact(Path.GetFileName(directory), "N", out _)) continue;
RejectLink(directory);
var index = Path.Combine(directory, "index.json");
RejectLink(index);
if (!File.Exists(index)) continue;
await using var stream = File.OpenRead(index);
using var document = await JsonDocument.ParseAsync(stream, cancellationToken: ct);
var podcast = document.RootElement.GetProperty("Manifest").GetProperty("Podcast");
var owner = podcast.GetProperty("OwnerId").GetString();
if (owner == userId)
{
if (podcast.TryGetProperty("State", out var state) && state.GetString() == "Live"
|| podcast.TryGetProperty("Replay", out var replay) && replay.ValueKind == JsonValueKind.Object
&& replay.TryGetProperty("State", out var replayState) && replayState.GetString() == "Processing")
throw new SubscriptionOperationException(409, "Un podcast est encore en direct ou en cours de conversion ; attendre son arret avant de reprendre le retrait.");
await stream.DisposeAsync();
DeleteDirectory(directory);
}
}
}
private static string Child(string root, string name)
{
if (string.IsNullOrWhiteSpace(root) || string.IsNullOrWhiteSpace(name) || name != Path.GetFileName(name)
|| name is "." or ".." || name.Contains('\\'))
throw new InvalidOperationException("Invalid withdrawal storage configuration or user path.");
var fullRoot = Path.GetFullPath(root);
RejectLink(fullRoot);
var child = Path.GetFullPath(Path.Combine(fullRoot, name));
if (!child.StartsWith(fullRoot.TrimEnd(Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar, StringComparison.Ordinal))
throw new InvalidOperationException("Withdrawal path escapes its storage root.");
return child;
}
private static void RejectLink(string path)
{
if ((File.Exists(path) || Directory.Exists(path)) && File.GetAttributes(path).HasFlag(FileAttributes.ReparsePoint))
throw new IOException("Withdrawal refuses symbolic links in managed storage.");
}
private static void DeleteDirectory(string path)
{
if (!Directory.Exists(path)) return;
RejectLink(path);
foreach (var entry in Directory.EnumerateFileSystemEntries(path))
{
RejectLink(entry);
if (Directory.Exists(entry)) DeleteDirectory(entry);
else File.Delete(entry);
}
Directory.Delete(path);
}
}

View file

@ -0,0 +1,38 @@
using Yavsc.Server.Helpers;
namespace Yavsc.Web.Services;
public sealed class PaymentResiduePurgeWorker(IServiceScopeFactory scopes,
ILogger<PaymentResiduePurgeWorker> logger) : BackgroundService
{
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
var delay = TimeSpan.FromMinutes(1);
try
{
using var scope = scopes.CreateScope();
var residues = scope.ServiceProvider.GetRequiredService<IPaymentResidueService>();
await residues.PurgeAsync(stoppingToken);
var clock = scope.ServiceProvider.GetRequiredService<TimeProvider>();
var now = clock.GetUtcNow();
var expiry = await residues.GetNextExpiryAsync(stoppingToken);
if (expiry is not null)
{
var until = expiry.Value - now;
if (until < delay) delay = until > TimeSpan.Zero ? until : TimeSpan.Zero;
}
}
catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested)
{
return;
}
catch (Exception ex)
{
logger.LogError(ex, "Automatic payment residue purge failed; retrying in one minute");
}
await Task.Delay(delay, stoppingToken);
}
}
}

View file

@ -38,6 +38,7 @@ public sealed class ResourceSubscriptionService(ApplicationDbContext db, IPayPal
throw new SubscriptionOperationException(400, "Pack inconnu.");
return ResourceUsageTracker.WithUserLockAsync(db, userId, async () =>
{
await RequireActiveAccountAsync(userId, ct);
var existing = await db.ResourceSubscriptions.Where(s => s.UserId == userId
&& s.State != "CANCELLED" && s.State != "EXPIRED").SingleOrDefaultAsync(ct);
if (existing is not null)
@ -69,6 +70,7 @@ public sealed class ResourceSubscriptionService(ApplicationDbContext db, IPayPal
public Task BindAsync(ResourceSubscription subscription, PayPalSubscriptionDetails remote, CancellationToken ct)
=> ResourceUsageTracker.WithUserLockAsync(db, subscription.UserId, async () =>
{
await RequireActiveAccountAsync(subscription.UserId, ct, allowPendingWithdrawal: true);
await db.Entry(subscription).ReloadAsync(ct);
CheckBinding(subscription, remote);
subscription.PayPalId = remote.Id;
@ -87,6 +89,7 @@ public sealed class ResourceSubscriptionService(ApplicationDbContext db, IPayPal
var transactions = await paypal.TransactionsAsync(remote.Id, subscription.CreatedAt, clock.GetUtcNow(), ct);
await ResourceUsageTracker.WithUserLockAsync(db, subscription.UserId, async () =>
{
await RequireActiveAccountAsync(subscription.UserId, ct);
await db.Entry(subscription).ReloadAsync(ct);
CheckBinding(subscription, remote);
subscription.State = remote.State;
@ -174,4 +177,11 @@ public sealed class ResourceSubscriptionService(ApplicationDbContext db, IPayPal
|| remote.State is not ("APPROVAL_PENDING" or "APPROVED" or "ACTIVE" or "SUSPENDED" or "CANCELLED" or "EXPIRED"))
throw new SubscriptionOperationException(409, "L'abonnement PayPal ne correspond pas au compte et au pack attendus.");
}
private async Task RequireActiveAccountAsync(string userId, CancellationToken ct, bool allowPendingWithdrawal = false)
{
if (await db.Users.AnyAsync(u => u.Id == userId &&
(u.WithdrawnAt != null || !allowPendingWithdrawal && u.WithdrawalRequestedAt != null), ct))
throw new SubscriptionOperationException(409, "Le compte est retire ; aucun nouveau credit ne peut etre attribue.");
}
}

View file

@ -8,8 +8,13 @@
<div class="row">
<div class="col-md-8">
<p>
Cette action est <strong>immédiate et irréversible</strong>. Toutes les données
associées à votre compte seront supprimées, et vous serez déconnecté.
Cette action ferme définitivement votre compte et vous déconnecte. Le retrait est confirmé
après résiliation des abonnements et suppression de vos fichiers personnels, avatars et podcasts.
Vos identifiants sont effacés ou pseudonymisés. En cas d'erreur, le compte est bloqué et
l'administration doit reprendre l'effacement ; aucun retrait réussi n'est annoncé.
Les données techniques de paiement restent conservées jusqu'à un an après le retrait effectif.
Les pièces comptables relèvent d'une conservation légale distincte.
Consultez la <a asp-controller="Home" asp-action="Privacy">politique de confidentialité</a>.
</p>
<form asp-controller="Account" asp-action="Delete" method="post" class="form-horizontal" role="form">

View file

@ -1,16 +1,120 @@
@{
ViewBag.Title = Localizer["Home"];
ViewBag.Title = "Confidentialité et protection des données";
}
<markdown>
# La confidentialité
# Confidentialité et protection des données
À aucun moment, aucune adresse postale,
aucune adresse e-mail ni aucun numéro de téléphone
ne sont transmis à personne. Seul le système
son [possesseur ou l'administration](/Home/Contact) ont accès
à ces informations.
Dernière mise à jour : 8 novembre 2026.
De plus, le droit de retrait est permanent
et sa [mise en oeuvre est immédiate](/Account/Delete).
## Responsable et contact
L'exploitant de Yavsc, identifié sur la [page de contact](/Home/Contact),
est votre interlocuteur pour les traitements de données et l'exercice de vos droits.
Cette politique concerne Yavsc et son client PostIt.
## Données et utilisation
Le service traite les identifiants du compte, coordonnées renseignées, préférences,
contenus publiés, fichiers, échanges nécessaires aux prestations, données techniques
de connexion et de consommation, et références des abonnements et paiements.
Ces données servent à fournir le service, authentifier les utilisateurs, gérer les
prestations et paiements, protéger la plateforme et comptabiliser les ressources.
Le fonctionnement du service repose sur l'exécution du contrat ; la sécurité relève
de l'intérêt légitime de l'exploitant et les obligations comptables de la loi.
Les fonctions optionnelles fondées sur un consentement peuvent être désactivées.
## Accès et transmissions
La confidentialité ne signifie pas qu'aucune donnée n'est transmise :
* Le titulaire du compte et les administrateurs habilités accèdent aux informations
nécessaires à leur rôle. L'accès administratif sert au support et à l'exploitation.
* Les contenus publiés sont accessibles selon leur visibilité et leurs autorisations.
Les parties à une demande, un devis ou une prestation peuvent recevoir les
coordonnées et pièces nécessaires à cette relation ; elles ne sont pas réservées
exclusivement à l'administration.
* PostIt et les autres clients OAuth/OIDC autorisés reçoivent les informations prévues
par leurs autorisations : identifiant, nom de compte, adresse e-mail et rôles
lorsque l'accès au profil leur est accordé.
* Lors d'un appel direct avec PostIt, l'adresse réseau que vous acceptez de communiquer
et les paramètres de connexion sont partagés avec l'interlocuteur pour établir
la liaison. L'audio et, si activée, la vidéo sont transmis aux participants ;
les diffusions de podcasts transmettent aussi les médias aux personnes autorisées.
Pour une émission diffusée avec OBS ou un autre encodeur externe, le relais média
configuré reçoit le flux, l'adresse réseau du diffuseur et une clé technique
limitée à l'émission. Cette clé permet de diffuser, pas d'accéder aux données
du compte ni de regarder les podcasts ; elle peut être révoquée dans PostIt.
* Les prestataires d'hébergement et de messagerie traitent les données nécessaires
au stockage, au fonctionnement et à l'acheminement des messages.
* PayPal reçoit les informations nécessaires au paiement et à l'abonnement :
formule, montant, devise, références et identifiant technique de rapprochement.
Pour les dons, l'adresse PayPal du destinataire est aussi utilisée. Les données
que vous fournissez directement à PayPal relèvent également de sa propre politique.
Yavsc ne stocke pas votre numéro de carte bancaire pour ces abonnements.
* Si vous choisissez une connexion externe, notamment Google, ce fournisseur
intervient dans l'authentification. Les intégrations de calendrier et de notification,
lorsqu'elles sont configurées et utilisées, transmettent les données nécessaires
à leur fonction aux fournisseurs correspondants.
* Si la modération par Claude est activée sur cette instance, le contenu soumis
et son contexte sont transmis à Anthropic pour cette modération.
* Des données peuvent être communiquées aux autorités lorsqu'une obligation légale
l'impose. Leur publication ou transmission à d'autres utilisateurs dépend aussi
des fonctions et autorisations que vous utilisez.
Certains fournisseurs peuvent traiter les données hors de l'Union européenne.
L'exploitant doit vérifier les lieux de traitement et garanties contractuelles
applicables aux fournisseurs effectivement activés ; leurs coordonnées et ces
garanties peuvent être demandées via la page de contact.
## Retrait et fichiers
Vous pouvez [demander le retrait de votre compte](/Account/Delete).
Le compte est bloqué dès le début du traitement. Le retrait effectif n'est confirmé
qu'après arrêt des abonnements et effacement des fichiers personnels, avatars,
pièces jointes personnelles/de blog et podcasts sur les volumes gérés par le service.
Les contenus de profil et publications du compte sont effacés ou neutralisés,
ses moyens de connexion sont supprimés et son identité est pseudonymisée.
Une ligne technique peut rester nécessaire aux relations avec les documents conservés ;
elle ne permet plus de se connecter.
Une erreur d'effacement ou de résiliation est signalée : le retrait n'est pas annoncé
comme réussi et l'administration doit reprendre le traitement.
La suppression sur le service ne supprime pas les copies téléchargées par d'autres
personnes ni les données détenues indépendamment par les prestataires.
## Paiements et conservation
Par exception au retrait ordinaire, les données techniques PayPal, abonnements,
mensualités et dons nécessaires au rapprochement restent conservées pendant
au maximum **un an à compter du retrait effectif**. Cette limite ne repart pas à
chaque paiement ou notification.
Les résidus arrivés à échéance sont purgés automatiquement ; une action réservée
aux administrateurs dans PostIt permet également de lancer la purge des données
éligibles. Les comptes actifs et les retraits non finalisés ne sont pas concernés.
L'exploitant doit surveiller ce traitement et corriger tout incident ou arrêt
du service empêchant la purge à échéance.
**Les factures, pièces comptables et informations nécessaires aux obligations légales
ne relèvent pas de cette limite d'un an.** Elles sont conservées selon les délais
légaux applicables, avec accès limité aux besoins comptables et légaux.
Les sauvegardes et journaux d'exploitation font l'objet d'une politique distincte :
leur durée et les mesures empêchant la réactivation de données retirées doivent
être précisées par l'exploitant selon le déploiement réel.
## Cookies, stockage local et droits
Yavsc utilise des cookies nécessaires à la connexion, à la session et à la protection
des formulaires. PostIt conserve localement les éléments nécessaires à sa session ;
la déconnexion et l'effacement des données locales doivent aussi être réalisés sur
les appareils que vous utilisez.
Vous pouvez demander l'accès, la rectification, l'effacement, la limitation,
l'opposition et, lorsque applicable, la portabilité de vos données, ainsi que retirer
un consentement sans affecter les traitements antérieurs. Contactez l'exploitant
via la [page de contact](/Home/Contact). Vous pouvez également introduire une
réclamation auprès de la [CNIL](https://www.cnil.fr/).
La [règle de consommation et les abonnements](/Home/CGU) sont décrits séparément.
</markdown>

View file

@ -0,0 +1,72 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using Yavsc.Abstract.Administration;
using Yavsc.Models;
namespace Yavsc.Server.Helpers;
public interface IPaymentResidueService
{
Task<PaymentResiduePurgeResult> PurgeAsync(CancellationToken ct);
Task<DateTimeOffset?> GetNextExpiryAsync(CancellationToken ct);
}
public sealed class PaymentResidueService(ApplicationDbContext db, TimeProvider clock,
ILogger<PaymentResidueService> logger) : IPaymentResidueService
{
private IQueryable<ApplicationUser> AccountsWithResidues()
=> db.Users.AsNoTracking().Where(u => u.WithdrawnAt != null
&& (db.ResourceSubscriptions.Any(s => s.UserId == u.Id)
|| db.PayPalPayment.Any(p => p.ExecutorId == u.Id)
|| db.PerformerDonations.Any(d => d.DonorId == u.Id || d.PerformerId == u.Id)));
public async Task<DateTimeOffset?> GetNextExpiryAsync(CancellationToken ct)
{
var dates = await AccountsWithResidues().Select(u => u.WithdrawnAt).ToListAsync(ct);
return dates.Select(d => d?.AddYears(1)).Min();
}
public async Task<PaymentResiduePurgeResult> PurgeAsync(CancellationToken ct)
{
var now = clock.GetUtcNow();
var candidates = await AccountsWithResidues()
.Select(u => new { u.Id, u.WithdrawnAt }).ToListAsync(ct);
var ids = candidates.Where(u => u.WithdrawnAt!.Value.AddYears(1) <= now).Select(u => u.Id);
var users = 0;
var subscriptions = 0;
var payments = 0;
var donations = 0;
var legacyPayments = 0;
foreach (var id in ids)
{
var count = await ResourceUsageTracker.WithUserLockAsync(db, id, async () =>
{
var owner = await db.Users.AsNoTracking().SingleAsync(u => u.Id == id, ct);
if (owner.WithdrawnAt is null || owner.WithdrawnAt.Value.AddYears(1) > now)
throw new InvalidOperationException("Withdrawal retention deadline changed during purge.");
var rows = await db.ResourceSubscriptions.Where(s => s.UserId == id).ToListAsync(ct);
var rowIds = rows.Select(s => s.Id).ToArray();
var receipts = await db.ResourceSubscriptionPayments.Where(p => rowIds.Contains(p.SubscriptionId)).ToListAsync(ct);
var donationRows = await db.PerformerDonations.Where(p => p.DonorId == id || p.PerformerId == id).ToListAsync(ct);
var legacy = await db.PayPalPayment.Include(p => p.Links).Where(p => p.ExecutorId == id).ToListAsync(ct);
foreach (var payment in legacy)
if (payment.Links is not null) db.HyperLink.RemoveRange(payment.Links);
db.PerformerDonations.RemoveRange(donationRows);
db.PayPalPayment.RemoveRange(legacy);
db.ResourceSubscriptionPayments.RemoveRange(receipts);
await db.SaveChangesAsync(ct);
db.ResourceSubscriptions.RemoveRange(rows);
await db.SaveChangesAsync(ct);
return (Subscriptions: rows.Count, Payments: receipts.Count, Donations: donationRows.Count, LegacyPayments: legacy.Count);
}, ct);
if (count.Subscriptions != 0 || count.Payments != 0 || count.Donations != 0 || count.LegacyPayments != 0) users++;
subscriptions += count.Subscriptions;
payments += count.Payments;
donations += count.Donations;
legacyPayments += count.LegacyPayments;
}
logger.LogInformation("Purged payment residues: {Users} withdrawn accounts, {Subscriptions} subscriptions, {Payments} receipts, {Donations} donations, {LegacyPayments} legacy payments",
users, subscriptions, payments, donations, legacyPayments);
return new(users, subscriptions, payments, donations, legacyPayments);
}
}

View file

@ -1,26 +1,50 @@
#nullable enable
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.Extensions.Logging;
using Yavsc.Models;
using Yavsc.Settings;
namespace Yavsc.Server.Helpers;
public sealed class ResourceUsageLimitException() : InvalidOperationException("Le seuil de consommation est atteint.")
{
}
public static class ResourceUsageTracker
{
private static readonly SemaphoreSlim LocalGate = new(1, 1);
public static Task RecordStorageAsync(ApplicationDbContext db, string userId, string userName,
string path, long bytes, CancellationToken cancellationToken = default)
string path, long bytes, CancellationToken cancellationToken = default,
Func<Task>? write = null, ResourceUsageOptions? policy = null, decimal bandwidthMb = 0m)
{
ArgumentNullException.ThrowIfNull(db);
ArgumentException.ThrowIfNullOrWhiteSpace(userId);
ArgumentException.ThrowIfNullOrWhiteSpace(path);
ArgumentOutOfRangeException.ThrowIfNegative(bytes);
ArgumentOutOfRangeException.ThrowIfNegative(bandwidthMb);
return WithUserLockAsync(db, userId, async () =>
{
if (await IsWithdrawingAsync(db, userId, cancellationToken))
throw new InvalidOperationException("Storage accounting is closed for this withdrawn account.");
var stored = await db.ResourceStorageRecords.FindAsync([userId, path], cancellationToken);
if (stored is not null) await db.Entry(stored).ReloadAsync(cancellationToken);
var delta = bytes - (stored?.Bytes ?? 0L);
if (write is not null)
{
if (policy is null && (delta > 0 || bandwidthMb > 0m))
throw new ArgumentException("Storage admission requires a resource policy.", nameof(policy));
if (policy is not null && await UpdateCoreAsync(db, userId, userName, 0m, 0, 0m, bandwidthMb, userId,
Constants.ResourceUsageDefaultCurrency, policy, Math.Max(0L, delta), cancellationToken) is null)
{
db.GetService<ILoggerFactory>().CreateLogger("ResourceUsageTracker")
.LogWarning("Storage admission refused at resource threshold for {UserId}", userId);
throw new ResourceUsageLimitException();
}
await write();
}
if (stored is null && bytes > 0)
db.ResourceStorageRecords.Add(new ResourceStorageRecord { UserId = userId, Path = path, Bytes = bytes });
else if (stored is not null)
@ -100,6 +124,7 @@ public static class ResourceUsageTracker
decimal bandwidthMb, string? actorUserId, string currency, ResourceUsageOptions? policy,
long anticipatedStorageBytes, CancellationToken cancellationToken)
{
if (await IsWithdrawingAsync(dbContext, userId, cancellationToken)) return null;
var effectiveActor = string.IsNullOrWhiteSpace(actorUserId) ? userId : actorUserId;
var now = DateTime.UtcNow;
var storageMb = (decimal)storageBytes / (1024m * 1024m);
@ -151,6 +176,15 @@ public static class ResourceUsageTracker
return record;
}
private static async Task<bool> IsWithdrawingAsync(ApplicationDbContext db, string userId, CancellationToken ct)
{
if (!await db.Users.AsNoTracking().AnyAsync(u => u.Id == userId && u.WithdrawalRequestedAt != null, ct))
return false;
db.GetService<ILoggerFactory>().CreateLogger("ResourceUsageTracker")
.LogWarning("Refused resource accounting for withdrawn account {UserId}", userId);
return true;
}
public static async Task<T> WithUserLockAsync<T>(ApplicationDbContext dbContext, string userId,
Func<Task<T>> action, CancellationToken cancellationToken)
{

View file

@ -0,0 +1,24 @@
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Yavsc.Models;
namespace Yavsc.Server.Helpers;
public sealed class WithdrawnAccountMiddleware(RequestDelegate next)
{
public async Task InvokeAsync(HttpContext context, ApplicationDbContext db)
{
var id = context.User.GetUserId();
if (!string.IsNullOrWhiteSpace(id) && await db.Users.AsNoTracking()
.AnyAsync(u => u.Id == id && u.WithdrawalRequestedAt != null, context.RequestAborted))
{
context.Response.StatusCode = StatusCodes.Status401Unauthorized;
await context.Response.WriteAsJsonAsync(new Microsoft.AspNetCore.Mvc.ProblemDetails
{
Status = 401, Title = "Compte ferme", Detail = "Ce compte fait l'objet d'un retrait et ne peut plus etre utilise."
}, context.RequestAborted);
return;
}
await next(context);
}
}

View file

@ -146,7 +146,8 @@ namespace Yavsc.Models
builder.Entity<ApplicationUser>().Property(u => u.Avatar).HasDefaultValue(Constants.DefaultAvatar);
builder.Entity<ApplicationUser>().Property(u => u.DiskQuota).HasDefaultValue(Constants.DefaultFSQ);
builder.Entity<ResourceStorageRecord>().HasKey(r => new { r.UserId, r.Path });
builder.Entity<ApplicationUser>().HasAlternateKey(u => u.Email);
builder.Entity<ApplicationUser>().Property(u => u.Email).IsRequired();
builder.Entity<ApplicationUser>().HasIndex(u => u.Email).IsUnique();
builder.Entity<BlackListed>().HasOne<ApplicationUser>(bl => bl.User);
builder.Entity<BlackListed>().HasOne<ApplicationUser>(bl => bl.Owner);
builder.Entity<UserActivity>().HasKey(u => new { u.DoesCode, u.UserId });

View file

@ -95,6 +95,10 @@ namespace Yavsc.Models
public long DiskQuota { get; set; } = Constants.DefaultFSQ;
[JsonIgnore, System.Text.Json.Serialization.JsonIgnore]
public DateTimeOffset? WithdrawalRequestedAt { get; set; }
[JsonIgnore, System.Text.Json.Serialization.JsonIgnore]
public DateTimeOffset? WithdrawnAt { get; set; }
[JsonIgnore, System.Text.Json.Serialization.JsonIgnore]
public DateTimeOffset? PremiumDiskQuotaUntil { get; set; }
[JsonIgnore, System.Text.Json.Serialization.JsonIgnore]
public DateTimeOffset? DiscoveryDiskQuotaUntil { get; set; }

View file

@ -15,6 +15,14 @@ namespace Yavsc.Models.Streaming
public DateTimeOffset? PreparedAt { get; set; }
public DateTimeOffset? StartedAt { get; set; }
public bool PodcastDeleted { get; set; }
[MaxLength(64), System.Text.Json.Serialization.JsonIgnore, Newtonsoft.Json.JsonIgnore]
public string? ObsKeyHash { get; set; }
[System.Text.Json.Serialization.JsonIgnore, Newtonsoft.Json.JsonIgnore]
public DateTimeOffset? ObsEnabledUntil { get; set; }
[System.Text.Json.Serialization.JsonIgnore, Newtonsoft.Json.JsonIgnore]
public Guid? ObsConnectionId { get; set; }
[MaxLength(512), System.Text.Json.Serialization.JsonIgnore, Newtonsoft.Json.JsonIgnore]
public string? ObsLastError { get; set; }
[Key(), DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Display(Name="FlowIdLabel", ResourceType=typeof(LiveFlow))]

View file

@ -74,7 +74,7 @@ namespace Yavsc.Services
var subjectId = GetSubjectId(context.Subject);
if (subjectId == null) return;
var user = await _userManager.FindByIdAsync(subjectId);
if (user == null) return;
if (user == null || user.WithdrawalRequestedAt is not null) return;
context.IssuedClaims = await GetClaimsFromUserAsync(context, user);
}
@ -87,7 +87,7 @@ namespace Yavsc.Services
return;
}
var user = await _userManager.FindByIdAsync(subjectId);
context.IsActive = user != null;
context.IsActive = user != null && user.WithdrawalRequestedAt is null;
}
private static string? GetSubjectId(ClaimsPrincipal claimsPrincipal)

View file

@ -0,0 +1,348 @@
using System.Diagnostics;
using System.Net;
using System.Net.Sockets;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text.Json;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Yavsc.Abstract.Streaming;
using Yavsc.Api.Services;
using Yavsc.Models;
using Yavsc.Server.Helpers;
using Yavsc.Services;
using Yavsc.Settings;
namespace Yavsc.Api.Test;
public sealed class PodcastObsTests : IDisposable
{
private static CancellationToken Ct => TestContext.Current.CancellationToken;
private readonly string root = Path.Combine(Path.GetTempPath(), "yavsc-obs-" + Guid.NewGuid().ToString("N"));
private readonly SqliteConnection connection;
private readonly ServiceProvider provider;
private readonly PodcastObsOptions settings = new()
{
Enabled = true, ServerUrl = "rtmps://obs.example.test:1936",
RelayPassword = new string('x', 48), MaxDurationMinutes = 1
};
private readonly Clock clock = new();
private sealed class Clock : TimeProvider
{
public DateTimeOffset Now { get; set; } = DateTimeOffset.UtcNow;
public override DateTimeOffset GetUtcNow() => Now;
}
public PodcastObsTests()
{
var connectionString = $"Data Source=obs-{Guid.NewGuid():N};Mode=Memory;Cache=Shared;Default Timeout=30";
connection = new SqliteConnection(connectionString);
connection.Open();
var services = new ServiceCollection();
services.AddLogging(logging => logging.AddConsole().AddFilter("Microsoft.EntityFrameworkCore", LogLevel.Warning));
services.AddDbContext<ApplicationDbContext>(o => o.UseSqlite(connectionString));
services.AddSingleton<TimeProvider>(clock);
services.AddSingleton<IOptions<PodcastObsOptions>>(Options.Create(settings));
services.AddSingleton<IOptions<PodcastOptions>>(Options.Create(new PodcastOptions { RootPath = root }));
services.AddSingleton<IOptions<ResourceUsageOptions>>(Options.Create(new ResourceUsageOptions()));
services.AddSingleton<ILiveProcessor, LiveProcessor>();
services.AddScoped<IPodcastScheduleService, PodcastScheduleService>();
services.AddScoped<IPodcastObsService, PodcastObsService>();
services.AddHttpClient<IPodcastObsRelay, PodcastObsRelay>(c => c.Timeout = TimeSpan.FromSeconds(5));
provider = services.BuildServiceProvider();
using var scope = provider.CreateScope();
scope.ServiceProvider.GetRequiredService<ApplicationDbContext>().Database.EnsureCreated();
}
private async Task<PodcastResponse> PlanAsync(IServiceProvider services)
{
var db = services.GetRequiredService<ApplicationDbContext>();
db.Users.Add(new() { Id = "owner", UserName = "owner", Email = "owner@example.test" });
await db.SaveChangesAsync(Ct);
return await services.GetRequiredService<IPodcastScheduleService>().PrepareAsync("owner", new()
{
Title = "OBS programme", ScheduledStartAt = clock.Now.AddDays(7), PlannedDurationMinutes = 1
}, null, Ct);
}
private static PodcastRelayAuthentication Publish(PodcastObsCredentials credentials)
{
var split = credentials.StreamKey.Split('?');
return new() { Action = "publish", Protocol = "rtmp", Path = split[0], Query = split[1], Id = Guid.NewGuid().ToString() };
}
[Fact]
public async Task Activation_is_owned_rotatable_expiring_and_never_persists_the_plain_key()
{
using var scope = provider.CreateScope();
var plan = await PlanAsync(scope.ServiceProvider);
var obs = scope.ServiceProvider.GetRequiredService<IPodcastObsService>();
var denied = await Assert.ThrowsAsync<PodcastException>(() => obs.ActivateAsync(plan.Id, "other", Ct));
Assert.Equal(403, denied.StatusCode);
var credentials = await obs.ActivateAsync(plan.Id, "owner", Ct);
Assert.Equal(settings.ServerUrl, credentials.ServerUrl);
Assert.Equal(clock.Now.AddMinutes(30), credentials.ExpiresAt);
var request = Publish(credentials);
var flow = await scope.ServiceProvider.GetRequiredService<ApplicationDbContext>().LiveFlow.SingleAsync(Ct);
Assert.DoesNotContain(request.Query[4..], flow.ObsKeyHash!);
Assert.NotNull(await obs.AuthenticateAsync(request, Ct));
Assert.Null(await obs.AuthenticateAsync(request with { Id = Guid.NewGuid().ToString() }, Ct));
Assert.Null(await obs.AuthenticateAsync(request with { Path = "obs/" + Guid.NewGuid().ToString("N") }, Ct));
Assert.Null(await obs.AuthenticateAsync(request with { Query = request.Query + "&" + request.Query }, Ct));
var renewed = await obs.ActivateAsync(plan.Id, "owner", Ct);
Assert.Null(await obs.AuthenticateAsync(request, Ct));
Assert.NotNull(await obs.AuthenticateAsync(Publish(renewed), Ct));
clock.Now = renewed.ExpiresAt;
Assert.Null(await obs.AuthenticateAsync(Publish(renewed), Ct));
Assert.False((await obs.StatusAsync(plan.Id, "owner", Ct)).Enabled);
}
[Fact]
public async Task Publisher_cannot_read_media_or_control_relay_and_closed_accounts_cannot_publish()
{
using var scope = provider.CreateScope();
var plan = await PlanAsync(scope.ServiceProvider);
var obs = scope.ServiceProvider.GetRequiredService<IPodcastObsService>();
var publish = Publish(await obs.ActivateAsync(plan.Id, "owner", Ct));
Assert.Null(await obs.AuthenticateAsync(publish with { Action = "read", Protocol = "rtsp" }, Ct));
Assert.Null(await obs.AuthenticateAsync(publish with { Action = "api" }, Ct));
Assert.NotNull(await obs.AuthenticateAsync(new()
{ Action = "api", User = settings.RelayUser, Password = settings.RelayPassword }, Ct));
Assert.NotNull(await obs.AuthenticateAsync(new()
{ Action = "read", Protocol = "rtmp", Path = publish.Path, User = settings.RelayUser, Password = settings.RelayPassword }, Ct));
Assert.Null(await obs.AuthenticateAsync(new()
{ Action = "read", Protocol = "hls", Path = publish.Path, User = settings.RelayUser, Password = settings.RelayPassword }, Ct));
var db = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
(await db.Users.SingleAsync(Ct)).WithdrawalRequestedAt = clock.Now;
await db.SaveChangesAsync(Ct);
Assert.Null(await obs.AuthenticateAsync(publish, Ct));
}
[Fact]
public async Task Activation_blocks_exhausted_quotas_and_direct_capture_cannot_steal_an_armed_emission()
{
using var scope = provider.CreateScope();
var services = scope.ServiceProvider;
var plan = await PlanAsync(services);
var obs = services.GetRequiredService<IPodcastObsService>();
var db = services.GetRequiredService<ApplicationDbContext>();
var owner = await db.Users.SingleAsync(Ct);
owner.DiskUsage = owner.DiskQuota;
await db.SaveChangesAsync(Ct);
Assert.Equal(413, (await Assert.ThrowsAsync<PodcastException>(() => obs.ActivateAsync(plan.Id, "owner", Ct))).StatusCode);
owner.DiskUsage = 0;
await db.SaveChangesAsync(Ct);
await obs.ActivateAsync(plan.Id, "owner", Ct);
Assert.Equal(409, (await Assert.ThrowsAsync<PodcastException>(() =>
services.GetRequiredService<IPodcastScheduleService>().StartAsync(plan.Id, "owner", Ct))).StatusCode);
await ResourceUsageTracker.RecordAsync(db, "owner", "owner", cpuSeconds: 20000, cancellationToken: Ct);
Assert.Equal(429, (await Assert.ThrowsAsync<PodcastException>(() => obs.ActivateAsync(plan.Id, "owner", Ct))).StatusCode);
}
[Fact]
public void Public_transport_must_be_encrypted_unless_explicitly_opted_out()
{
settings.ServerUrl = "rtmp://obs.example.test:1935";
Assert.Throws<InvalidOperationException>(settings.Validate);
settings.AllowUnencryptedRtmp = true;
settings.Validate();
settings.ServerUrl = "rtmp://obs.example.test/live";
Assert.Throws<InvalidOperationException>(settings.Validate);
}
[Theory]
[InlineData(false, false)]
[InlineData(true, false)]
[InlineData(true, true)]
public async Task Real_rtmp_publisher_becomes_authenticated_HLS_and_MP4_with_storage_refund(bool revoke, bool secure)
{
var binary = Environment.GetEnvironmentVariable("YAVSC_TEST_MEDIAMTX");
if (string.IsNullOrWhiteSpace(binary)) Assert.Skip("Set YAVSC_TEST_MEDIAMTX to the MediaMTX v1.21.3 binary to run the real OBS-compatible media test.");
var apiPort = FreePort();
var rtmpPort = FreePort();
var rtmpsPort = FreePort();
var authPort = FreePort();
settings.ServerUrl = secure ? $"rtmps://127.0.0.1:{rtmpsPort}" : $"rtmp://127.0.0.1:{rtmpPort}";
settings.AllowUnencryptedRtmp = !secure;
settings.RelayApiUrl = $"http://127.0.0.1:{apiPort}/";
settings.RelayReadUrl = $"rtmp://127.0.0.1:{rtmpPort}/";
Directory.CreateDirectory(root);
var tlsConfig = "";
if (secure)
{
using var key = RSA.Create(2048);
var request = new CertificateRequest("CN=localhost", key, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
using var certificate = request.CreateSelfSigned(DateTimeOffset.UtcNow.AddMinutes(-1), DateTimeOffset.UtcNow.AddHours(1));
var keyPath = Path.Combine(root, "server.key");
var certPath = Path.Combine(root, "server.crt");
await File.WriteAllTextAsync(keyPath, key.ExportPkcs8PrivateKeyPem(), Ct);
await File.WriteAllTextAsync(certPath, certificate.ExportCertificatePem(), Ct);
tlsConfig = $"rtmpEncryption: optional\nrtmpsAddress: 127.0.0.1:{rtmpsPort}\n"
+ $"rtmpServerKey: {JsonSerializer.Serialize(keyPath)}\nrtmpServerCert: {JsonSerializer.Serialize(certPath)}";
}
var config = Path.Combine(root, "mediamtx.yml");
await File.WriteAllTextAsync(config, $$"""
logLevel: warn
authMethod: http
authHTTPAddress: http://127.0.0.1:{{authPort}}/auth
authHTTPExclude: []
api: true
apiAddress: 127.0.0.1:{{apiPort}}
rtsp: false
rtmpAddress: 127.0.0.1:{{rtmpPort}}
{{tlsConfig}}
hls: false
webrtc: false
srt: false
playback: false
pathDefaults:
overridePublisher: false
maxReaders: 1
paths:
"~^obs/[0-9a-f]{32}$":
""", Ct);
var builder = WebApplication.CreateBuilder();
builder.WebHost.UseUrls($"http://127.0.0.1:{authPort}");
await using var app = builder.Build();
app.MapPost("/auth", async (PodcastRelayAuthentication request) =>
{
using var scope = provider.CreateScope();
var result = await scope.ServiceProvider.GetRequiredService<IPodcastObsService>().AuthenticateAsync(request, Ct);
return result is null ? Results.Unauthorized() : Results.Ok(result);
});
await app.StartAsync(Ct);
using var relayProcess = StartProcess(binary!, config);
var relayOutput = relayProcess.StandardOutput.ReadToEndAsync();
var relayErrors = relayProcess.StandardError.ReadToEndAsync();
var worker = new PodcastObsWorker(provider.GetRequiredService<IServiceScopeFactory>(), Options.Create(settings),
provider.GetRequiredService<ILogger<PodcastObsWorker>>());
Process? publisher = null;
Task<string>? publisherErrors = null;
try
{
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(Ct);
timeout.CancelAfter(TimeSpan.FromSeconds(75));
using var scope = provider.CreateScope();
var services = scope.ServiceProvider;
var plan = await PlanAsync(services);
var credentials = await services.GetRequiredService<IPodcastObsService>().ActivateAsync(plan.Id, "owner", Ct);
using var http = new HttpClient();
// Probe the listener independently of media authorization before starting the publisher.
await WaitAsync(async () =>
{
try { using var response = await http.GetAsync(settings.RelayApiUrl, timeout.Token); return true; }
catch (HttpRequestException) { return false; }
}, timeout.Token);
await worker.StartAsync(Ct);
publisher = StartProcess("ffmpeg", "-nostdin", "-hide_banner", "-loglevel", "error", "-re",
"-f", "lavfi", "-i", "testsrc=size=160x120:rate=10", "-re", "-f", "lavfi", "-i", "sine=frequency=440:sample_rate=48000",
"-t", "20", "-c:v", "libx264", "-pix_fmt", "yuv420p", "-preset", "ultrafast", "-g", "20",
"-c:a", "aac", "-b:v", "180k", "-b:a", "32k", "-f", "flv", $"{credentials.ServerUrl}/{credentials.StreamKey}");
publisherErrors = publisher.StandardError.ReadToEndAsync();
var processor = services.GetRequiredService<ILiveProcessor>();
if (revoke)
{
await WaitAsync(async () => (await processor.ListAsync(timeout.Token))
.Any(p => p.Id == plan.Id && p.SegmentCount >= 2), timeout.Token);
await services.GetRequiredService<IPodcastObsService>().DeactivateAsync(plan.Id, "owner", timeout.Token);
}
await WaitAsync(async () =>
{
if (!revoke && publisher.HasExited && publisher.ExitCode != 0)
throw new InvalidOperationException("Synthetic publisher failed: " +
(await publisherErrors).Replace(credentials.StreamKey, "[redacted]", StringComparison.Ordinal));
var status = await services.GetRequiredService<IPodcastObsService>().StatusAsync(plan.Id, "owner", timeout.Token);
if (status.Error is not null) throw new InvalidOperationException(status.Error);
return (await processor.ListAsync(timeout.Token)).Any(p =>
p.Id == plan.Id && p.State == PodcastState.Completed && p.SegmentCount > 0);
}, timeout.Token);
var manifest = await processor.GetAsync(plan.Id, Ct);
Assert.True(manifest.Podcast.DurationSeconds >= (revoke ? 2 : 8));
Assert.True(manifest.Podcast.Bytes > 0);
using (var probe = StartProcess("ffprobe", "-v", "error", "-show_streams", "-of", "json",
Path.Combine(root, plan.Id.ToString("N"), "00000000.ts")))
{
var probeOutput = await probe.StandardOutput.ReadToEndAsync(Ct);
var probeError = await probe.StandardError.ReadToEndAsync(Ct);
await probe.WaitForExitAsync(Ct);
Assert.Equal(0, probe.ExitCode);
using var probeDocument = JsonDocument.Parse(probeOutput);
var audio = Assert.Single(probeDocument.RootElement.GetProperty("streams").EnumerateArray(),
s => s.GetProperty("codec_type").GetString() == "audio");
Assert.Equal("aac", audio.GetProperty("codec_name").GetString());
Assert.True(string.IsNullOrEmpty(probeError), probeError);
Assert.Equal("48000", audio.GetProperty("sample_rate").GetString());
}
var db = services.GetRequiredService<ApplicationDbContext>();
var receipt = await db.ResourceStorageRecords.AsNoTracking().SingleAsync(Ct);
Assert.Equal(manifest.Podcast.Bytes, receipt.Bytes);
var user = await db.Users.AsNoTracking().SingleAsync(Ct);
Assert.Equal(receipt.Bytes, user.DiskUsage);
var usage = await db.ResourceUsageRecords.AsNoTracking().SingleAsync(Ct);
Assert.Equal((decimal)receipt.Bytes / (1024m * 1024m), usage.StorageMb);
Assert.True(usage.BandwidthMb >= usage.StorageMb);
if (!revoke) Assert.Equal(usage.StorageMb, usage.BandwidthMb);
Assert.False((await services.GetRequiredService<IPodcastObsService>().StatusAsync(plan.Id, "owner", Ct)).Enabled);
Assert.Null((await services.GetRequiredService<IPodcastObsService>().StatusAsync(plan.Id, "owner", Ct)).Error);
Assert.True(await processor.PrepareNextReplayAsync(new FfmpegPodcastReplayRemuxer(
services.GetRequiredService<IOptions<PodcastOptions>>()), Ct));
Assert.Equal(PodcastReplayState.Ready, (await processor.GetAsync(plan.Id, Ct)).Podcast.Replay?.State);
db.ChangeTracker.Clear();
await services.GetRequiredService<IPodcastScheduleService>().DeleteAsync(plan.Id, "owner", Ct);
Assert.Empty(db.ResourceStorageRecords);
Assert.Equal(0, (await db.Users.AsNoTracking().SingleAsync(Ct)).DiskUsage);
var refunded = await db.ResourceUsageRecords.AsNoTracking().SingleAsync(Ct);
Assert.Equal(0m, refunded.StorageMb);
Assert.Equal(usage.BandwidthMb, refunded.BandwidthMb);
}
finally
{
await worker.StopAsync(CancellationToken.None);
worker.Dispose();
if (publisher is not null)
{
if (!publisher.HasExited) publisher.Kill(entireProcessTree: true);
await publisher.WaitForExitAsync(CancellationToken.None);
await publisherErrors!;
publisher.Dispose();
}
if (!relayProcess.HasExited) relayProcess.Kill(entireProcessTree: true);
await relayProcess.WaitForExitAsync(CancellationToken.None);
await relayOutput;
await relayErrors;
await app.StopAsync(CancellationToken.None);
}
}
private static int FreePort()
{
using var listener = new TcpListener(IPAddress.Loopback, 0);
listener.Start();
return ((IPEndPoint)listener.LocalEndpoint).Port;
}
private static Process StartProcess(string file, params string[] args)
{
var start = new ProcessStartInfo(file) { UseShellExecute = false, RedirectStandardError = true, RedirectStandardOutput = true };
foreach (var arg in args) start.ArgumentList.Add(arg);
return Process.Start(start) ?? throw new IOException("Could not start test media process.");
}
private static async Task WaitAsync(Func<Task<bool>> condition, CancellationToken ct)
{
while (!await condition()) await Task.Delay(200, ct);
}
public void Dispose()
{
provider.Dispose();
connection.Dispose();
if (Directory.Exists(root)) Directory.Delete(root, recursive: true);
}
}

View file

@ -62,6 +62,15 @@ public sealed class PodcastScheduleTests(ApiWebServerFixture fixture) : IClassFi
Assert.NotNull(plan.FlowId);
Assert.Equal(request.ScheduledStartAt, plan.ScheduledStartAt);
Assert.Equal(90, plan.PlannedDurationMinutes);
using var obsStatus = await owner.GetAsync(path + "/obs", Ct);
Assert.Equal(HttpStatusCode.OK, obsStatus.StatusCode);
Assert.True(obsStatus.Headers.CacheControl?.NoStore);
var status = await obsStatus.Content.ReadFromJsonAsync<PodcastObsStatus>(Ct);
Assert.False(status!.Enabled);
using var obsDenied = await other.GetAsync(path + "/obs", Ct);
Assert.Equal(HttpStatusCode.Forbidden, obsDenied.StatusCode);
using var obsAnonymous = await anonymous.GetAsync(path + "/obs", Ct);
Assert.Equal(HttpStatusCode.Unauthorized, obsAnonymous.StatusCode);
using (var scope = fixture.Services.CreateScope())
{
var flow = await scope.ServiceProvider.GetRequiredService<ApplicationDbContext>().LiveFlow

View file

@ -38,6 +38,7 @@ public sealed class SiteAdministrationApiTests(ApiWebServerFixture fixture) : IC
var document = await http.GetFromJsonAsync<JsonElement>("/openapi/administration.json");
Assert.True(document.GetProperty("paths").TryGetProperty(Root + "/clients", out _));
Assert.True(document.GetProperty("paths").TryGetProperty(Root + "/transfer", out _));
Assert.True(document.GetProperty("paths").TryGetProperty(Root + "/payment-residues/purge", out _));
using var moderator = Client("Moderator");
Assert.Equal(HttpStatusCode.Forbidden, (await moderator.GetAsync("/openapi/administration.json")).StatusCode);
}
@ -64,7 +65,8 @@ public sealed class SiteAdministrationApiTests(ApiWebServerFixture fixture) : IC
(HttpMethod.Get, "mailing-criteria"), (HttpMethod.Get, "mailing-templates"),
(HttpMethod.Get, "mailing-templates/template"), (HttpMethod.Post, "mailing-templates"),
(HttpMethod.Put, "mailing-templates/template"), (HttpMethod.Delete, "mailing-templates/template"),
(HttpMethod.Get, "transfer"), (HttpMethod.Post, "transfer")
(HttpMethod.Get, "transfer"), (HttpMethod.Post, "transfer"),
(HttpMethod.Post, "payment-residues/purge")
};
foreach (var route in routes)
{
@ -72,6 +74,22 @@ public sealed class SiteAdministrationApiTests(ApiWebServerFixture fixture) : IC
using var response = await http.SendAsync(request, TestContext.Current.CancellationToken);
Assert.Equal(expected, response.StatusCode);
}
}
[Fact]
public async Task Administrator_can_purge_eligible_payment_residues_with_typed_report()
{
using var http = Client();
using var response = await http.PostAsync($"{Root}/payment-residues/purge", null, TestContext.Current.CancellationToken);
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
var report = await response.Content.ReadFromJsonAsync<PaymentResiduePurgeResult>(TestContext.Current.CancellationToken);
Assert.NotNull(report);
Assert.True(report.Users >= 0);
Assert.True(report.LegacyPayments >= 0);
using var payload = JsonDocument.Parse(await response.Content.ReadAsStringAsync(TestContext.Current.CancellationToken));
Assert.Equal(new[] { "donations", "legacyPayments", "payments", "subscriptions", "users" },
payload.RootElement.EnumerateObject().Select(p => p.Name).Order().ToArray());
}
[Fact]

View file

@ -39,6 +39,21 @@ public sealed class ResourceSubscriptionControllerTests : IClassFixture<Resource
db.SaveChanges();
}
[Fact]
public async Task Withdrawal_requires_antiforgery_and_cannot_target_another_account()
{
using var client = _factory.SignedInClient();
using var missingToken = await client.PostAsync("/Account/Delete", new FormUrlEncodedContent(
new Dictionary<string, string> { ["UserId"] = "listener" }), Ct);
Assert.Equal(HttpStatusCode.BadRequest, missingToken.StatusCode);
using var tampered = await PostAsync(client, "/Account/Delete", new() { ["UserId"] = "author" });
Assert.Equal(HttpStatusCode.Redirect, tampered.StatusCode);
Assert.Contains("AccessDenied", tampered.Headers.Location?.ToString());
using var scope = _factory.Services.CreateScope();
Assert.Null((await scope.ServiceProvider.GetRequiredService<ApplicationDbContext>()
.Users.SingleAsync(u => u.Id == "author", Ct)).WithdrawalRequestedAt);
}
[Fact]
public async Task Subscription_management_requires_login_and_all_mutations_require_antiforgery()
{

View file

@ -8,6 +8,25 @@ namespace Yavsc.Org.Tests.Controllers;
public sealed class ResourceUsageTermsTests
{
[Fact]
public async Task Privacy_describes_withdrawal_payment_exception_and_actual_recipients()
{
using var factory = new TestWebApplicationFactory();
using var client = factory.CreateClient();
var response = await client.GetAsync("/Home/Privacy", TestContext.Current.CancellationToken);
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
var html = await response.Content.ReadAsStringAsync(TestContext.Current.CancellationToken);
Assert.Contains("un an", html);
Assert.Contains("retrait effectif", html);
Assert.Contains("comptables", html);
Assert.Contains("PayPal", html);
Assert.Contains("Anthropic", html);
Assert.Contains("OAuth", html);
Assert.Contains("PostIt", html);
Assert.DoesNotContain("Aucune information", html);
Assert.DoesNotContain("mise en œuvre immédiate", html);
}
[Fact]
public async Task Public_terms_describe_the_configured_rule_and_are_linked_from_the_footer()
{

View file

@ -0,0 +1,298 @@
using System.Text.Json;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Yavsc.Models;
using Yavsc.Models.Payment;
using Yavsc.Server.Helpers;
using Yavsc.Services;
using Yavsc.Web.Services;
namespace Yavsc.Server.Tests;
public sealed class AccountWithdrawalTests : IDisposable
{
private readonly string root = Path.Combine(Path.GetTempPath(), "yavsc-withdrawal-" + Guid.NewGuid().ToString("N"));
private static CancellationToken Ct => TestContext.Current.CancellationToken;
private sealed class Clock : TimeProvider
{
public DateTimeOffset Now { get; set; } = new(2026, 11, 8, 12, 0, 0, TimeSpan.Zero);
public override DateTimeOffset GetUtcNow() => Now;
}
private sealed class Gateway : IPayPalSubscriptionGateway
{
public bool FailCancellation { get; set; }
public int CancelCount { get; set; }
public Task CancelAsync(string id, CancellationToken ct)
{
if (FailCancellation) throw new HttpRequestException("Payment service unavailable");
CancelCount++;
return Task.CompletedTask;
}
public Task<PayPalSubscriptionDetails> GetAsync(string id, CancellationToken ct)
=> Task.FromResult(new PayPalSubscriptionDetails(id, "", "", "ACTIVE", null, null, null));
public Task<PayPalSubscriptionDetails> CreateAsync(ResourceSubscription s, string r, string c, CancellationToken ct)
=> throw new NotSupportedException();
public Task<IReadOnlyList<PayPalSubscriptionTransaction>> TransactionsAsync(string id, DateTimeOffset f, DateTimeOffset t, CancellationToken ct)
=> throw new NotSupportedException();
public Task VerifyWebhookAsync(JsonElement n, IReadOnlyDictionary<string, string> h, CancellationToken ct)
=> throw new NotSupportedException();
}
private ServiceProvider Provider(Clock clock, Gateway gateway, Microsoft.Data.Sqlite.SqliteConnection? connection = null)
{
var services = new ServiceCollection();
services.AddLogging();
var databaseName = Guid.NewGuid().ToString();
services.AddDbContext<ApplicationDbContext>(o =>
{
if (connection is null) o.UseInMemoryDatabase(databaseName);
else o.UseSqlite(connection);
});
services.AddIdentityCore<ApplicationUser>().AddEntityFrameworkStores<ApplicationDbContext>();
services.AddSingleton<TimeProvider>(clock);
services.AddSingleton<IPayPalSubscriptionGateway>(gateway);
services.Configure<SiteSettings>(o =>
{
o.UserFilesRoot = Path.Combine(root, "files");
o.Avatars = Path.Combine(root, "avatars");
});
services.Configure<PodcastOptions>(o => o.RootPath = Path.Combine(root, "podcasts"));
services.AddScoped<IAccountWithdrawalService, AccountWithdrawalService>();
services.AddScoped<IPaymentResidueService, PaymentResidueService>();
return services.BuildServiceProvider();
}
private static async Task<ApplicationUser> SeedAsync(ApplicationDbContext db, string id = "alice")
{
var user = new ApplicationUser
{
Id = id, UserName = id, Email = id + "@example.test", FullName = "Full name",
PasswordHash = "old", PhoneNumber = "123", SecurityStamp = "old"
};
db.Users.Add(user);
await db.SaveChangesAsync(Ct);
return user;
}
[Fact]
public async Task Withdrawal_erases_files_revokes_identity_retains_payments_and_is_idempotent()
{
var clock = new Clock();
var gateway = new Gateway();
using var provider = Provider(clock, gateway);
using var scope = provider.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
var user = await SeedAsync(db);
var subscription = new ResourceSubscription { UserId = user.Id, Id = Guid.NewGuid(), State = "ACTIVE", PayPalId = "I-TEST" };
db.ResourceSubscriptions.Add(subscription);
db.ResourceSubscriptionPayments.Add(new() { Id = "PAY-1", SubscriptionId = subscription.Id });
await db.SaveChangesAsync(Ct);
var directory = Path.Combine(root, "files", "alice");
Directory.CreateDirectory(directory);
await File.WriteAllTextAsync(Path.Combine(directory, "personal.txt"), "private", Ct);
Directory.CreateDirectory(Path.Combine(root, "avatars"));
await File.WriteAllTextAsync(Path.Combine(root, "avatars", "alice.png"), "avatar", Ct);
var podcast = Path.Combine(root, "podcasts", Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(podcast);
await File.WriteAllTextAsync(Path.Combine(podcast, "index.json"),
"""{"Manifest":{"Podcast":{"OwnerId":"alice"}}}""", Ct);
var other = Path.Combine(root, "files", "bob");
Directory.CreateDirectory(other);
await File.WriteAllTextAsync(Path.Combine(other, "keep.txt"), "other", Ct);
var service = scope.ServiceProvider.GetRequiredService<IAccountWithdrawalService>();
await service.WithdrawAsync(user.Id, Ct);
Assert.False(Directory.Exists(directory));
Assert.False(Directory.Exists(podcast));
Assert.False(File.Exists(Path.Combine(root, "avatars", "alice.png")));
Assert.True(File.Exists(Path.Combine(other, "keep.txt")));
Assert.Equal(clock.Now, user.WithdrawnAt);
Assert.Null(user.PasswordHash);
Assert.Null(user.PhoneNumber);
Assert.Null(user.FullName);
Assert.EndsWith("@invalid.invalid", user.Email);
Assert.Equal(DateTimeOffset.MaxValue, user.LockoutEnd);
Assert.Equal("CANCELLED", subscription.State);
Assert.Single(db.ResourceSubscriptionPayments);
await ResourceUsageTracker.RecordAsync(db, user.Id, "alice", apiCalls: 1m, cancellationToken: Ct);
Assert.Empty(db.ResourceUsageRecords);
var subscriptionService = new ResourceSubscriptionService(db, gateway,
Options.Create(new Yavsc.Settings.ResourceSubscriptionOptions()),
Options.Create(new Yavsc.Settings.ResourceUsageOptions()), clock);
var denied = await Assert.ThrowsAsync<SubscriptionOperationException>(() =>
subscriptionService.PrepareAsync(user.Id, "Discovery", Ct));
Assert.Equal(409, denied.StatusCode);
clock.Now = clock.Now.AddMonths(1);
var withdrawalTime = user.WithdrawnAt;
await service.WithdrawAsync(user.Id, Ct);
Assert.Equal(withdrawalTime, user.WithdrawnAt);
Assert.Equal(1, gateway.CancelCount);
}
[Fact]
public async Task Withdrawal_refuses_live_podcast_and_can_finish_when_recording_is_stopped()
{
using var provider = Provider(new Clock(), new Gateway());
using var scope = provider.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
var user = await SeedAsync(db);
var podcast = Path.Combine(root, "podcasts", Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(podcast);
var index = Path.Combine(podcast, "index.json");
await File.WriteAllTextAsync(index, """{"Manifest":{"Podcast":{"OwnerId":"alice","State":"Live"}}}""", Ct);
var service = scope.ServiceProvider.GetRequiredService<IAccountWithdrawalService>();
await Assert.ThrowsAsync<SubscriptionOperationException>(() => service.WithdrawAsync(user.Id, Ct));
Assert.True(Directory.Exists(podcast));
Assert.Null(user.WithdrawnAt);
await File.WriteAllTextAsync(index, """{"Manifest":{"Podcast":{"OwnerId":"alice","State":"Completed"}}}""", Ct);
await service.WithdrawAsync(user.Id, Ct);
Assert.False(Directory.Exists(podcast));
}
[Fact]
public async Task Withdrawal_refuses_symbolic_links_without_deleting_other_users_files()
{
using var provider = Provider(new Clock(), new Gateway());
using var scope = provider.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
var user = await SeedAsync(db);
var other = Path.Combine(root, "files", "bob");
Directory.CreateDirectory(other);
await File.WriteAllTextAsync(Path.Combine(other, "keep.txt"), "other", Ct);
Directory.CreateSymbolicLink(Path.Combine(root, "files", "alice"), other);
await Assert.ThrowsAsync<IOException>(() =>
scope.ServiceProvider.GetRequiredService<IAccountWithdrawalService>().WithdrawAsync(user.Id, Ct));
Assert.True(File.Exists(Path.Combine(other, "keep.txt")));
Assert.Null(user.WithdrawnAt);
}
[Fact]
public async Task Failed_payment_cancellation_blocks_account_without_claiming_withdrawal_and_can_be_retried()
{
var gateway = new Gateway { FailCancellation = true };
using var provider = Provider(new Clock(), gateway);
using var scope = provider.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
var user = await SeedAsync(db);
db.ResourceSubscriptions.Add(new() { Id = Guid.NewGuid(), UserId = user.Id, PayPalId = "I-TEST", State = "ACTIVE" });
await db.SaveChangesAsync(Ct);
var service = scope.ServiceProvider.GetRequiredService<IAccountWithdrawalService>();
await Assert.ThrowsAsync<HttpRequestException>(() => service.WithdrawAsync(user.Id, Ct));
Assert.NotNull(user.WithdrawalRequestedAt);
Assert.Null(user.WithdrawnAt);
gateway.FailCancellation = false;
await service.WithdrawAsync(user.Id, Ct);
Assert.NotNull(user.WithdrawnAt);
}
[Fact]
public async Task Invalid_owner_path_never_deletes_a_storage_root()
{
using var provider = Provider(new Clock(), new Gateway());
using var scope = provider.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
var user = await SeedAsync(db);
user.UserName = "..";
await db.SaveChangesAsync(Ct);
Directory.CreateDirectory(root);
await Assert.ThrowsAsync<InvalidOperationException>(() =>
scope.ServiceProvider.GetRequiredService<IAccountWithdrawalService>().WithdrawAsync(user.Id, Ct));
Assert.True(Directory.Exists(root));
Assert.Null(user.WithdrawnAt);
}
[Fact]
public async Task Purge_applies_exact_anniversary_including_leap_day_and_preserves_active_and_pending_accounts()
{
var clock = new Clock { Now = new(2025, 2, 28, 12, 0, 0, TimeSpan.Zero) };
using var provider = Provider(clock, new Gateway());
using var scope = provider.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
var eligible = await SeedAsync(db, "eligible");
eligible.WithdrawnAt = new(2024, 2, 29, 12, 0, 0, TimeSpan.Zero);
var young = await SeedAsync(db, "young");
young.WithdrawnAt = new(2024, 2, 29, 12, 0, 1, TimeSpan.Zero);
var pending = await SeedAsync(db, "pending");
pending.WithdrawalRequestedAt = clock.Now.AddYears(-2);
await SeedAsync(db, "active");
foreach (var userId in new[] { "eligible", "young", "pending", "active" })
{
var subscription = new ResourceSubscription { Id = Guid.NewGuid(), UserId = userId };
db.ResourceSubscriptions.Add(subscription);
db.ResourceSubscriptionPayments.Add(new() { Id = "PAY-" + userId, SubscriptionId = subscription.Id });
}
db.PerformerDonations.Add(new()
{
Id = Guid.NewGuid(), DonorId = eligible.Id, PerformerId = "active",
RecipientEmail = "recipient@example.test", Amount = 1m
});
db.InvoicePayments.Add(new() { CommandId = 1, Reference = "accounting-kept", Amount = 1m });
await db.SaveChangesAsync(Ct);
var service = scope.ServiceProvider.GetRequiredService<IPaymentResidueService>();
var result = await service.PurgeAsync(Ct);
Assert.Equal(new Yavsc.Abstract.Administration.PaymentResiduePurgeResult(1, 1, 1, 1), result);
Assert.Single(db.InvoicePayments);
Assert.Empty(db.PerformerDonations);
Assert.Equal(clock.Now.AddSeconds(1), await service.GetNextExpiryAsync(Ct));
Assert.Equal(3, await db.ResourceSubscriptions.CountAsync(Ct));
Assert.Equal(3, await db.ResourceSubscriptionPayments.CountAsync(Ct));
Assert.Equal(new Yavsc.Abstract.Administration.PaymentResiduePurgeResult(0, 0, 0), await service.PurgeAsync(Ct));
}
[Fact]
public async Task Relational_purge_removes_legacy_payment_links_without_deleting_account_identities()
{
using var connection = new Microsoft.Data.Sqlite.SqliteConnection("Data Source=:memory:");
await connection.OpenAsync(Ct);
var clock = new Clock();
using var provider = Provider(clock, new Gateway(), connection);
using var scope = provider.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
await db.Database.EnsureCreatedAsync(Ct);
var user = await SeedAsync(db);
user.WithdrawnAt = clock.Now.AddYears(-1);
db.PayPalPayment.Add(new()
{
CreationToken = "technical-token", ExecutorId = user.Id, State = "SUCCESS",
Links = [new() { HRef = "https://example.test/payment", Method = "GET" }]
});
await db.SaveChangesAsync(Ct);
var report = await scope.ServiceProvider.GetRequiredService<IPaymentResidueService>().PurgeAsync(Ct);
Assert.Equal(1, report.LegacyPayments);
Assert.Empty(db.PayPalPayment);
Assert.Empty(db.HyperLink);
Assert.Single(db.Users);
Assert.Equal(0, (await scope.ServiceProvider.GetRequiredService<IPaymentResidueService>().PurgeAsync(Ct)).Users);
Assert.Null(await scope.ServiceProvider.GetRequiredService<IPaymentResidueService>().GetNextExpiryAsync(Ct));
}
[Fact]
public async Task Old_authenticated_session_is_refused_even_before_withdrawal_completion()
{
using var provider = Provider(new Clock(), new Gateway());
using var scope = provider.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
var user = await SeedAsync(db);
user.WithdrawalRequestedAt = DateTimeOffset.UtcNow;
await db.SaveChangesAsync(Ct);
var context = new DefaultHttpContext
{
User = new(new System.Security.Claims.ClaimsIdentity([new("sub", user.Id)], "Bearer"))
};
context.Response.Body = new MemoryStream();
var middleware = new WithdrawnAccountMiddleware(_ => throw new InvalidOperationException("Must not execute"));
await middleware.InvokeAsync(context, db);
Assert.Equal(401, context.Response.StatusCode);
}
public void Dispose()
{
if (Directory.Exists(root)) Directory.Delete(root, recursive: true);
}
}

View file

@ -41,6 +41,37 @@ public sealed class ResourceUsageTests
Response = { Body = new MemoryStream() }
};
[Fact]
public async Task Instrumented_storage_admits_before_writing_and_refunds_disk_under_the_same_lock()
{
using var provider = NewProvider(o => o.DefaultLimit = 0.4m);
using var scope = provider.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
var ct = TestContext.Current.CancellationToken;
const long mib = 1024 * 1024;
var user = new ApplicationUser { Id = "alice", UserName = "alice", Email = "alice@example.test" };
db.Users.Add(user);
await db.SaveChangesAsync(ct);
var policy = scope.ServiceProvider.GetRequiredService<IOptions<ResourceUsageOptions>>().Value;
await ResourceUsageTracker.RecordStorageAsync(db, user.Id, user.UserName!, "podcast/test", mib, ct,
write: () => { user.DiskUsage += mib; return Task.CompletedTask; }, policy: policy, bandwidthMb: 1m);
Assert.Equal(mib, user.DiskUsage);
Assert.Equal(mib, (await db.ResourceStorageRecords.SingleAsync(ct)).Bytes);
var wrote = false;
await Assert.ThrowsAsync<ResourceUsageLimitException>(() =>
ResourceUsageTracker.RecordStorageAsync(db, user.Id, user.UserName!, "podcast/test", 2 * mib, ct,
write: () => { wrote = true; return Task.CompletedTask; }, policy: policy, bandwidthMb: 1m));
Assert.False(wrote);
Assert.Equal(mib, (await db.ResourceStorageRecords.SingleAsync(ct)).Bytes);
await ResourceUsageTracker.RecordStorageAsync(db, user.Id, user.UserName!, "podcast/test", 0, ct,
write: () => { user.DiskUsage -= mib; return Task.CompletedTask; });
Assert.Equal(0, user.DiskUsage);
Assert.Empty(db.ResourceStorageRecords);
var usage = await db.ResourceUsageRecords.SingleAsync(ct);
Assert.Equal(0m, usage.StorageMb);
Assert.Equal(1m, usage.BandwidthMb);
}
[Fact]
public void Configured_formula_uses_exact_decimal_points()
{