Commit graph

771 commits

Author SHA1 Message Date
6ac264fa2c tests 2026-07-06 00:47:35 +01:00
c08ff81776 fixes the startup 2026-07-06 00:14:22 +01:00
333b066e66 Identity reloaded 2026-07-05 23:56:10 +01:00
ef0f5ddcac refacto FrontmatterParser 2026-07-04 22:58:29 +01:00
7b3a236bcc refacto query status 2026-07-04 22:35:53 +01:00
ee6cb34c23 renaming Reviewed 2026-07-04 22:25:59 +01:00
c74ac71b5d layouts 2026-07-04 20:09:58 +01:00
bce6280750 titres 2026-07-04 20:03:56 +01:00
c8894c4220 gives titles 2026-07-04 19:57:03 +01:00
34b4203cd1 Ui fixes 2026-07-04 19:49:48 +01:00
17838bc78e fixes 2026-07-04 18:46:24 +01:00
a0342ea988 Revert "search all user by email at forgotten password"
This reverts commit 406e2ff03a.
2026-07-04 17:29:49 +01:00
406e2ff03a search all user by email at forgotten password 2026-07-04 17:24:12 +01:00
742da7c3f0 Activity moderated 2026-07-04 17:11:43 +01:00
90dfe9c13f drop the deigner.cs 2026-07-04 16:06:02 +01:00
Lum
f4eb14d083 feat(api): POST /api/bill/estimate/{id}/sign — JSON signature capture
Adds a new JSON-bodied signature endpoint as a sibling of the
legacy PNG-based prosign/clisign routes. The legacy flow stays
intact: the TeX invoice templates (Bill_tex.cshtml,
Estimate_tex.cshtml) still consume the sign-{billingCode}-{id}.png
files the old endpoints write, and the new endpoint writes to a
distinct /signatures/ tree under UserFilesDirName. A future
migration commit will regenerate PNGs from the JSON payload and
decommission the PNG flow.

Scope
- New Signature entity (Yavsc.Server/Models/Billing/Signature.cs)
  with FK to Estimate, FK to ApplicationUser (Signer), Type
  (Pro/Client) enum, CoordinateMax (default 10_000), int[] Strokes
  (native Npgsql mapping), CapturedAtUtc, FilePath. Multiple
  versions per (EstimateId, Type) are allowed; the controller
  reads the most recent.
- New Estimate.Signatures nav collection (InverseProperty) so the
  composite index covers both sides of the relation.
- New DbSet<Signature> Signatures + composite index
  (EstimateId, Type, CapturedAtUtc DESC) in ApplicationDbContext
  OnModelCreating. DeleteBehavior.Cascade on Estimate deletion
  cleans up signatures automatically.
- New EstimateSignatureFileHelper (Server/Helpers) with
  ReceiveEstimateSignatureAsync(user, estimateId, type, payload).
  Writes a yavsc.signature/v1 JSON envelope to
  UserFilesDirName/{user}/signatures/sign-{type}-{estimateId}-{ticks}.json.
  Quota update lives in the controller, not the helper, because
  the helper has no DbContext access.
- New endpoint POST /api/bill/estimate/{id:long}/sign on
  BillingController. Authz is body-driven (the bearer token is the
  PostIt OAuth client, not the end user, so signerUserId is in
  the JSON body, validated against Estimate.OwnerId/ClientId).
  Returns 201 Created with the new Signature's metadata.

Plumbing
- SignatureSubmission (body type) lives next to BillingController
  in the same file — small enough to keep colocated.
- The legacy prosign/clisign routes are untouched. They keep
  the IFormFile PNG contract; the new endpoint is the JSON
  counterpart.

Tests
- New EstimateSignatureFileHelperTests in Yavsc.Org.Tests
  (8 tests, all green): filename format incl. lowercase type and
  ticks, envelope v1 round-trip (parsed via JsonDocument, not
  text matching), null payload rejected, non-positive
  estimateId rejected. Disk side effects are isolated to a
  per-test temp root via AbstractFileSystemHelpers.UserFilesDirName.
- Yavsc.Org.Tests full suite: 29/29 green.
- PostIt.Tests: 57/57 green (untouched by this commit).
- Builds: Yavsc.Server, Yavsc.Api, Yavsc.Org, Yavsc.Org.Tests
  all compile clean.

Out of scope
- EF migration: the Signatures table doesn't exist in the
  database yet. The migration is intentionally a separate
  commit so the generated SQL can be reviewed against the
  composite index and the int[] column type before it touches
  any prod database. Until the migration lands, the new
  endpoint will 500 on SaveChanges; the [DEV] button in
  PostIt is the only call site, so this is acceptable.
- SignalR handler that opens the signature page on a
  'devis received' push — commit 4.
2026-07-04 15:47:55 +01:00
1d26cbdf3d refacto chathub 2026-07-04 15:28:07 +01:00
Lum
b939c403f6 feat(postit): signature capture page (dev entry, file persistence)
Builds on b0495514 (SignaturePadControl + SignaturePadData) with a
full Avalonia page that captures signatures, renders them as Polylines,
and persists the wire-format payload to ~/.local/share/PostIt/signatures
as JSON v1.

Scope
- New SignaturePage (axaml + code-behind) hosts the render-agnostic
  control: a fixed-size Border is the hit-test surface, an overlaid
  Canvas is rebuilt on every RedrawRequested from the Strokes buffer.
- SignaturePageViewModel wraps the control: exposes StrokeCount /
  PointCount / StatusMessage, Clear and CaptureAsync commands, and
  Attach/Detach for view-lifetime ownership.
- CaptureAsync writes a JSON envelope { format, coordinateMax,
  capturedAtUtc, strokes, strokeCount } to
  LocalApplicationData/PostIt/signatures/signature-yyyyMMdd-HHmmssfff.json.
  This is a stop-gap; the production transport will be
  POST /api/signature/{devisId} on Yavsc.Api (commit 3+).
- Entry point is a [DEV] button on MainPage that pushes the page
  onto the NavigationPage. The production trigger is a SignalR push
  from Yavsc.Org ("devis received, sign here") landing on a hub
  handler — the button and its Click handler are explicitly marked
  dev-only and tracked for removal in the same commit that wires
  the SignalR handler.

Plumbing
- App.axaml.cs: SignaturePage and SignaturePageViewModel registered
  as Transient in the DI container.
- ViewLocator: routes SignaturePageViewModel to SignaturePage.
- SignaturePadData: adds PointCount (sum of pairs across strokes),
  used by the VM status bar and the test surface.

Tests (57/57 green, 9 new in this commit)
- SignaturePageViewModelTests: constructors and dimension validation,
  Attach/Detach idempotence, StrokeCompleted and Clear propagate to
  the VM, CaptureAsync on empty buffer is a no-op, CaptureAsync on a
  non-empty buffer writes a v1 envelope with the expected
  structure (parsed back via JsonDocument, not text matching), and
  creates the destination directory if missing.
- All previously-green tests (48) remain green.

Out of scope
- POST /api/signature endpoint on Yavsc.Api (commit 3).
- SignalR handler that opens the page on a "devis received" push.
- Rasterization: this commit only proves capture and persistence;
  the visible ink is a Polyline reconstruction, not a PNG, by
  design (per the wire-format decision in commit 1).

Note on SignaturePadData
- The PointCount property was added after b0495514 landed. It is
  folded into this commit rather than amending b0495514 to keep
  the existing history readable; the change is mechanical and
  tested by the new SignaturePageViewModelTests.
2026-07-04 15:11:22 +01:00
b049551448 a Signature Pad 2026-07-04 14:43:39 +01:00
ec54108cf0 presentation 2026-07-01 00:13:57 +01:00
0cc82fec5d bug fix IUserSettings 2026-06-30 23:55:43 +01:00
0965caaf40 fixes and renaming 2026-06-30 23:32:05 +01:00
1751145be8 Exploiting GitVersion 2026-06-28 14:11:26 +01:00
Lum
0617fc6bda postit: make Settings thread-safe and route PropertyChanged through UI dispatcher
The postit://callback re-launch crashed Avalonia inside
DataValidationErrors.SetErrors with 'The calling thread cannot
access this object because a different thread owns it'. Two
Settings instances raced on PropertyChanged: one was the DI
singleton registered by App.OnFrameworkInitializationCompleted,
the other was a freshly-constructed fallback in
LoginPageViewModel() and LoginPage.axaml.cs's DataContext-null
branch. Avalonia's binding sink caught the cross-thread
notification and crashed before the LoginPage could render.

Fix at three layers:

1. Settings: lock the mutation gate so concurrent Load() /
   ApplyJson() callers cannot tear reads; override
   OnPropertyChanged to marshal every notification onto the
   Avalonia UI thread via a new UiDispatcher helper (no more
   cross-thread SetErrors). Add BindToServiceProvider /
   RequireCurrent so production code paths cannot silently
   allocate a second instance.

2. LoginPageViewModel(): resolve the canonical Settings from
   the DI container (Settings.RequireCurrent) instead of
   new Settings(). The cross-thread crash is now caught loudly
   with a clear 'Settings.Current is not bound' error if
   something instantiates the VM outside a bound App.

3. HomePage.axaml.cs and LoginPage.axaml.cs: resolve the
   next view-model and BlogApiClient through App.Services
   instead of constructing them with 'new'. Same instance
   tree as the rest of the app; the postit://callback race
   disappears by construction.

MainPageViewModel and HomePageViewModel keep their existing
'?? new Settings()' fallback for test friendliness, but the
fallback is now harmless because Settings itself is
thread-safe.

Adds two regression tests in SettingsLoadTests covering
concurrent Load+mutate and concurrent idempotent Load.
2026-06-28 13:33:06 +01:00
bd3dba0089 refactor(postit): rewrite MainPage layout in Grid
- ContentPage now stretches to fill the window
- root StackPanel replaced by a 3-row Grid (Auto, *, Auto)
  so the post list absorbs the middle band and the detail
  panel sits below
- detail panel inner StackPanel replaced by a Grid (Auto,
  Auto, Auto, *, Auto) so the AvaloniaEdit TextEditor fills
  all remaining width and height; MinHeight=320 keeps a
  sane floor on tiny windows
2026-06-28 01:47:12 +01:00
2f7df74000 petit refacto 2026-06-28 01:43:39 +01:00
fd6d6ab2d8 postit: change MainPage base class from NavigationPage to ContentPage
HomePage.OnLoginClick does Navigation.PushAsync(new MainPage
{ ... }). NavigationPage.PushAsync only accepts a Page (or
Page subclass), not a MultiPage. MainPage was declared as

  public partial class MainPage : NavigationPage

in MainPage.axaml.cs and the root of MainPage.axaml was

  <NavigationPage ...>

which means 'new MainPage()' produced a MultiPage, not a
Page. PushAsync against a MultiPage argument does not route
through the standard Page push path; the visible result is
that the login succeeds, LoginSucceeded fires, but the UI
stays on LoginPage — the user is left looking at the
post-login state without any navigation.

The XAML content of MainPage (a StackPanel with the post
CRUD UI, a ListBox, a TextEditor) does not need the
multi-page container semantics — it's a single screen.
Switch both the code-behind base class and the XAML root
element to ContentPage so that MainPage is what
PushAsync expects.
2026-06-28 01:13:08 +01:00
4e8402e766 postit: drop ConfigureAwait(false) after interactive login
LoginAsync uses ConfigureAwait(false) on the await of
LoginInteractiveCoreAsync. Since the surrounding code is
already executing on the UI thread (it was reached via a
RelayCommand that the UI dispatcher dispatched), the
ConfigureAwait drops the SynchronizationContext, and the
subsequent setters — IsBusy, AccessToken, StatusMessage,
LoginSuccess, and the LoginSucceeded?.Invoke() — run on a
thread-pool worker.

The downstream effects are all UI-bound: PropertyChanged
events fire, the BindingEngine republishes them as
AvaloniaObject.SetValue calls, and SetValue calls
Dispatcher.VerifyAccess. VerifyAccess throws because the
AvaloniaObject was created on the UI thread (owned by it)
and the SetValue is being attempted from a thread-pool
worker. Avalonia 11.12 throws SynchronousException through
DispatcherOperation.InvokeCore instead of dispatching back,
so the X11 message loop crashes the process with
System.InvalidOperationException: 'The calling thread cannot
access this object because a different thread owns it.'

Reproduced with the freshly installed postit_1.0.0-1_amd64.deb
package on a Debian 13 host — the .NET runtime loaded the
app, Avalonia started the X11 message loop, the operator
clicked 'Se connecter', the OIDC flow reached the post-login
phase, and the post-await setter chain crashed the process.

Drop ConfigureAwait(false) so the await captures the UI
thread SynchronizationContext and the setters resume on the
UI thread. The inner LoginInteractiveCoreAsync still uses
ConfigureAwait(false) for its own await, which is fine —
the inner method does not touch observables, only mutates
Platform.CreateBrowser and awaits the OIDC roundtrip, so it
can run anywhere.
2026-06-28 01:05:02 +01:00
4566223a2c tests: feed WebServerFixture a Smtp config so Authenticate fires
The EMaillingTests.SendEMailSynchrone smoke test asserts the
recording fake observed this exact call sequence on a successful
send:

  Connect, Authenticate, Send, Disconnect

MailSender.SendEmailAsync only calls Authenticate when
smtpSettings.UserName is non-null (src/Yavsc.Server/Services/
MailSender.cs line 89). WebServerFixture built the host without
a Smtp config — so UserName resolved to null, Authenticate was
skipped, and the recording captured only:

  Connect, Send, Disconnect

Pre-existing breakage, not introduced by recent work; the
fixture had been loading from .env indirectly (probably never,
or before a refactor that stopped doing so).

Feed the test host a fake SMTP config via the same
AddInMemoryCollection the fixture already uses for
ConnectionStrings:

  Smtp:Host     = smtp.test.local
  Smtp:Port     = 465
  Smtp:UserName = test-user
  Smtp:Password = test-pass

UserName non-null means MailSender now exercises the Authenticate
branch, which the recording captures. Tests in the Yavsc.Org.Tests
suite: 21/21 green (was 20/21 with SendEMailSynchrone failing).
2026-06-27 21:16:03 +01:00
aaf71bf91c tests: smoke tests for Account and Blog BCs
Two tests, two bounded contexts (BCs as enumerated in
doc/ddd-exploration-2026-06-14.md):

  - AccountSmokeTests : GET /signin
    YavscConstants.SigninPath = "~/signin"
    Routing + Razor + IdentityServer + EF + DI all wired.

  - BlogSmokeTests : GET /BlogSpot/Index
    BlogSpotController (note the capital S) under
    Controllers/Communicating/. No class-level [Route], so
    conventional /{controller}/{action} applies.

Both use TestWebApplicationFactory<Program> + the EF InMemory
provider wired by WebServerFixture.SetupHost, so they boot the
production HTTP pipeline without sockets, certs or a real DB.

Closes the 'Tests d'integration smoke par BC' item of Jalon 0
in ROADMAP.md (Yavsc.Api / Yavsc.Blogs coverage to come).
2026-06-27 21:03:16 +01:00
b56277c153 tests: add SmokeTestBase helper for HTTP smoke assertions
Smoke tests for the Jalon 0 'Tests d'integration smoke par BC'
item need a small helper to:
- issue a GET on an in-memory test server (HttpClient built by
  TestWebApplicationFactory<Program>);
- assert that the response is 2xx (page served), 3xx (redirect
  to login) or 401/403 (anonymous rejected). Anything else —
  404 route missing, 5xx server crash, connection refused —
  fails the test.

This commit only introduces the base class. Subsequent commits
add the per-BC smoke tests (Account, Blog, etc.).
2026-06-27 20:52:08 +01:00
234c837937 drop baked-in Kestrel:Endpoints:Https from Yavsc.Blogs / Yavsc.Api
Both appsettings-blogs.json and appsettings-api.json shipped a
Kestrel:Endpoints:Https block pointing at https://localhost:3003
and https://localhost:3004 respectively. These are leftover dev
templates that don't match the production ports (5004/5005 for
Blogs, 5002/5003 for Api) and crash Kestrel at startup when no
cert is configured for those URLs.

docker-compose.yaml now sets ASPNETCORE_URLS explicitly per
service runtime (http://+:5000/5002/5004 + ASPNETCORE_HTTPS_PORT=empty),
which is the authoritative source for the binding. The baked
Kestrel block in the appsettings overrides nothing useful and
just blocks HTTP-only startup.

Search confirms no source code references localhost:3003/3004
(grep across src/*.{cs,json,axaml,cshtml} returns only the two
lines we just deleted), so removing the block is safe.
2026-06-27 17:36:57 +01:00
4034c39905 Front matters 2026-06-27 13:30:28 +01:00
514549c5f9 postit: traceable OIDC login UX + session persistence + 2nd-instance early exit
- OidcLoginPhase enum + IProgress<OidcLoginPhase> on
  YavscApiClient.LoginInteractiveAsync, surfaced in the UI as
  PhaseLabel (FR). Lets operators see where the flow actually
  stalls, in particular whether the postit://callback ever arrives
  on the running instance.
- YavscApiClient.TrySilentLoginAsync: silent refresh at boot.
  Returns false (and purges the store) when the refresh token is
  rejected by the OP.
- App.OnFrameworkInitializationCompleted auto-routes: HomePage is
  the navigation root; on Opened the app calls TrySilentLoginAsync
  and pushes MainPage if a session is restored. Logout pops back
  to HomePage via the new persistent SessionStatusBanner (Connecté
  / Déconnecté + Logout button).
- PostIt.Desktop.Program.Main now detects the postit://callback
  URL BEFORE Avalonia boots, hands it off via SingleInstance, and
  exits. Stops the 2nd PostIt instance from flashing its own
  MainWindow while the 1st instance is still waiting on the named
  pipe. The check in App.OnFrameworkInitializationCompleted is
  kept as belt-and-braces defence-in-depth.
- SchemeUrlDetector: pure platform-independent detector extracted
  for unit testing.
- Tests: 7 new SchemeUrlDetectorTests + 5 new phase / silent
  refresh tests in YavscApiClientTests.
2026-06-27 12:47:52 +01:00
ee2c8452ac Navigation and DI 2026-06-26 01:45:21 +01:00
e526b050ed Add the missing Redirect.cshtml view used by LoadingPage helper
AccountController.Signin (and ExternalController / ConsentController)
return this.LoadingPage("Redirect", model.ReturnUrl) when the OIDC
client is a native one (e.g. PostIt, with a custom-scheme redirect
URI). The LoadingPage extension in Yavsc.Extensions renders
controller.View("Redirect", …), so a /Views/Shared/Redirect.cshtml
must exist.

The file was missing, and the absence surfaced as a 500 on
POST /signin once the login itself succeeded — the user authenticated
fine, Identity.Application signed in, but the response body never
rendered and the POST returned InvalidOperationException
('The view Redirect was not found'). This is what broke the PostIt
flow after the seed/IdentityResource fixes landed.

The view is the standard IdentityServer quickstart loading page: a
meta-refresh that redirects the embedded browser to the OIDC
client's callback URI (postit://callback). Localizer strings are
used so the page is translatable like the rest of the auth UI.
2026-06-26 00:21:58 +01:00
847557318f code cleanup 2026-06-25 23:55:52 +01:00
8fdd56d33a Test the seed 2026-06-25 23:27:47 +01:00
571977f81b Fix LINQ translation in EnsureDefaultApplicationScopes
EF Core was throwing at startup with:

  System.InvalidOperationException: The LINQ expression
  '[ApiResourceScopeSpecification,...].Any(s => s.ResourceName == r.Name)'
  could not be translated.

The cause: Constants.ApiResourcesScopes is a static readonly C# array,
not an IQueryable, but it was used directly inside a Where clause on an
IQueryable<ApiResource>. EF tried to translate the closure over
Constants.ApiResourcesScopes into a SQL sub-query, which is not a
supported operation.

Materialise the wanted resource names into a HashSet before letting EF
see the Where — the collection is small (5 entries) so there's no
performance reason to push it down. After this fix,
EnsureDefaultApplicationScopes runs to completion at startup and
the seed actually has a chance of doing its job (assuming the rows
aren't already present).
2026-06-25 23:20:43 +01:00
68eb24ba44 Don't seed openid/profile/offline_access as ApiScopes
IdentityServer8 refuses to start when an IdentityResource and an
ApiScope share the same Name — it throws

  Found identity scopes and API scopes that use the same names.
  This is an invalid configuration. Scopes found: openid, profile

and the host crashes before serving any request.

Constants.BuildInApiScopes has historically listed 'openid',
'profile' and 'offline_access' alongside the application scopes
(admin, moderation, performer, client). The IdentityResource
counterparts are seeded separately via
IdentityResources.OpenId().ToEntity() /
IdentityResources.Profile().ToEntity() in
EnsureDefaultApplicationScopes, so listing them again in
BuildInApiScopes produces a duplicate 'openid' / 'profile' once
that seeder is wired into MigrateDatabase and starts running on
every restart (commit be334a69). 'offline_access' is handled
directly by IdentityServer8 (DefaultResourceValidator has a
special-case branch for it) and never needs an ApiScope row.

Trim BuildInApiScopes to application scopes only. The live
ConfigurationDb already contains both IdentityResources and
ApiScopes for the same names from earlier hand-rolled SQL
bootstrap, so the duplicate-name check fires the moment the
process tries to enumerate its resources at startup.
2026-06-25 23:11:16 +01:00
bbfaa039de Set explicit defaults on seeded ApiScopes and ApiResources
The previous commit (be334a69) relied on C# defaults to populate
the Postgres NOT NULL columns Enabled, Required, Emphasize,
ShowInDiscoveryDocument (on ApiScopes) and Created (on
ApiResources). Both tables declare these columns NOT NULL without
a database default, so EF Core ends up shipping C# defaults
(false / DateTime.MinValue) that violate the constraints or
silently disable the seeded rows.

Concretely, if we deployed be334a69 as-is:

- ApiScopes.Enabled = false -> the scope is invisible to
  DefaultResourceValidator, exactly the bug we're fixing.
- ApiResources.Created = DateTime.MinValue (0001-01-01) ->
  Postgres rejects the INSERT with
  'null value in column Created violates not-null constraint'.

Set the values explicitly so the seeder produces the same state
whether it runs once or a hundred times, fresh database or not.
2026-06-25 21:30:56 +01:00
be334a69dc Seed ApiResources + ApiResourceScopes, run seeder on every startup
The previous commit (37440171) added ApiScope rows for the
application scopes (admin, moderation, performer, client, blogs).
It was a partial fix: an ApiScope alone is not a valid scope from
DefaultResourceValidator's point of view. The validator only
recognises a scope if it can find an ApiResource that exposes it
(via ApiResourceScopes). Without that link, /connect/authorize
rejects the request with 'Scope X not found in store', even
though the scope row exists. This is what killed the PostIt login
in production.

This commit:

1. Extends Constants.ApiResourcesScopes with ResourceName +
   ResourceDisplayName. Topology: one ApiResource per scope
   ('admin' resource exposes 'admin' scope, 'blogs' resource
   exposes 'blogs' scope, etc.) — keeps each scope's audience
   specific if/when we split products across separate audiences.

2. Ensures EnsureDefaultApplicationScopes also inserts the
   matching ApiResource rows (deduped on Name) and ApiResourceScope
   rows linking each resource to its scope. Idempotent: missing
   rows are added, nothing is removed.

3. Removes the b.UseSeeding(...) call inside AddConfigurationStore.
   EF Core's UseSeeding callback only fires when the database is
   empty, so on a live ConfigurationDb (which already had Clients
   and ClientScopes) it never ran — that is why the previous commit
   had no visible effect on production. The seeder is now invoked
   explicitly from MigrateDatabase via SeedConfigurationDatabase,
   which resolves ConfigurationDbContext from the DI and runs
   EnsureDefaultConfiguration on every startup, regardless of
   whether the database was fresh.

   Seeding failures are caught and logged (best-effort) so a
   misconfigured seeder cannot prevent the host from booting.

Live data on yavsc.pschneider.fr is still missing the
ApiResource/ApiResourceScope rows; a one-shot SQL or a redeploy
with this commit is needed before PostIt can log in. Production
fix to follow.
2026-06-25 21:28:13 +01:00
e76259cca2 Richer Client/Details view for admin triage
The previous Details view was a sketch: a handful of fields, a
half-broken <dt>/<dd> pairing around FrontChannelLogoutUri, and
nothing about token lifetimes, security flags, or collection sizes.
For an admin trying to understand what a given OIDC client actually
does (and why a login flow fails), that meant bouncing between the
list page and the edit page to read off half a dozen scalars.

The new view surfaces the same property surface as Edit.cshtml, but
read-only:

- Two-column layout: Identity + Security on the left, Tokens + Logout
  on the right. Security flags render as a Bootstrap 3 label
  (green/grey) so an admin can spot at a glance whether PKCE, consent,
  offline access, etc. are on or off.
- Lifetimes are formatted in human units (5 min, 2 h, 30 d) instead of
  raw seconds. Zero / unset is rendered as 'default' or '—' to avoid
  the silent-zero footgun.
- Enum-valued columns (AccessTokenType, RefreshTokenUsage,
  RefreshTokenExpiration) are rendered as their integer value since
  that's the on-disk representation in IdentityServer8.
- The Collections list is mirrored from Edit.cshtml so every nested
  editor (scopes, grant types, redirect URIs, CORS origins, IdP
  restrictions, claims, properties, secrets) is one click away.
- Secrets get a structured table: type, description, created/expiration
  timestamps, and a status badge (active / expires soon / expired /
  no expiry). Secret values are never displayed — only the freshly
  generated one, via the existing RegenerateSecret flow — and the
  note is repeated here so the table can't be misread.
- Footer promoted from inline links to a button bar (Edit, Regenerate
  secret, Back to List) for clearer call-to-action.

The ClientSecret property surface was confirmed by decompiling
IdentityServer8.EntityFramework.Storage 8.0.5: Expiration is
DateTime? (null = no expiry), Created is DateTime (default UtcNow).
No MinValue sentinel — previous draft's handling was wrong and has
been replaced by a single DateOrDash(DateTime?) helper.
2026-06-25 20:57:56 +01:00
3744017127 Seed ApiScopes for ApiResourcesScopes, align PostIt client
EnsureDefaultApplicationScopes was inserting every entry of
Constants.ApiResourcesScopes (admin, moderation, performer, client,
blogs) into the IdentityResources table, as Profile-derived rows.
That made them visible to /connect/discovery's scopes_supported
under the identity section, but no API resource would ever issue a
token bearing them — IdentityServer then rejected clients that
requested any of these scopes with 'invalid_scope' at the token
endpoint.

The most visible casualty was PostIt, a public PKCE client whose
postit-settings.json asks for scope=openid profile offline_access
blogs. 'blogs' is the scope that gates the Yavsc.Blogs deployment
(blogs.pschneider.fr), so the login flow died at the token step.

Fix:

- Constants.ApiResourcesScopes entries are now seeded as ApiScope
  rows (with Name + DisplayName). IdentityResources stays limited
  to the actual OpenID Connect profile (openid, profile).
- EnsureDefaultConfiguration gains an idempotent
  AlignPostItClientScopes pass that adds any missing scope from
  PostItScopes to the existing 'postit' client's AllowedScopes.
  Nothing is removed — manual revocation stays manual.

Existing live databases pick up both changes on next startup:
missing ApiScope rows are inserted, and the postit client's
ClientScope rows catch up.
2026-06-25 20:46:58 +01:00
99f4361e2d Api Resources seed 2026-06-25 20:22:41 +01:00
f3a3b63595 WIP PostIt login 2026-06-25 00:08:25 +01:00
18ce58e84a postit: drop 127.0.0.1:7890 loopback redirect from production defaults
The custom URI scheme (postit://callback) is now the only production
redirect on desktop. The loopback listener at 127.0.0.1:7890 is dead
since the previous scheme-handler refactor; this commit removes it
from every place that could pick it as a default.

Changes:
- Settings.RedirectUri now defaults to DefaultDesktopRedirectUri
  (postit://callback) instead of DefaultLoopbackRedirectUri.
- Settings.ApplyJson falls back to DefaultDesktopRedirectUri when
  the user settings file omits the RedirectUri field (was
  DefaultLoopbackRedirectUri before).
- postit-settings sample.json: RedirectUri flipped to postit://callback
  so anyone copying the sample gets a working config.
- DefaultLoopbackRedirectUri kept as a legacy constant (now
  documented as test-only); OidcStubAuthority / FakeAuthorizingBrowser
  continue to use it as a test fixture.
- The doc on RedirectUri now describes the custom-scheme path and
  references AndroidRedirectUri for mobile.

Reminder for the operator: also remove the matching
http://127.0.0.1:7890/ entry from the Yavsc.Org server's allowed
redirect URIs (see src/Yavsc.Org/Extensions/HostingExtensions.cs)
since no client uses it any more.

Tests: 21/21 still green. No code path now sends anything to port 7890
in production.
2026-06-23 21:30:56 +01:00
f96d84dc5b postit: wire BlogApiClient through YavscApiClient and unify auth
BlogApiClient is a thin DTO↔path mapper on top of YavscApiClient:
- No more HttpClient, no more accessToken constructor argument.
- Single responsibility: turn Yavsc.Blogs endpoint paths into typed
  BlogPost payloads and back, while YavscApiClient owns auth +
  refresh + JSON shape.
- Default path prefix is 'api/blog', overridable for tests.

MainPageViewModel and App.axaml.cs are now free of any direct
OidcClient / IBrowser / BearerToken plumbing. The MainPage receives
a fully-configured BlogApiClient (which holds a YavscApiClient, which
holds a TokenStore) at construction. The duplicate LoginAsync method
on MainPageViewModel is gone; the LoginPage is the single entry point
for the interactive PKCE flow.

PlatformBootstrap.Desktop no longer overrides the redirect URI to
loopback. PostIt runs the postit://callback custom scheme
(SingleInstance hand-off) as the production path on desktop; the
loopback constant stays for tests and for platforms that cannot
register a custom scheme.

Settings.cs: DefaultLoopbackRedirectUri is now documented as a
fallback; DefaultDesktopRedirectUri ('postit://callback') is
introduced as the canonical desktop default.

TokenStore.Load() tolerates an empty file (returns null) so
first-launch races and stubbed test fixtures don't blow up the
constructor.

YavscApiClient:
- HasValidSession is exposed for warm-start UI logic.
- CurrentAccessToken / CurrentIdToken are exposed so the LoginPage
  ViewModel can mirror the result onto its observable properties.
- CallAsync<T> is now virtual (and the class is no longer sealed)
  to allow stubbing in PostItViewModelTests.

Tests (PostIt.Tests):
- YavscApiClientTests covers the silent refresh path (cache the
  token, mark it expired, observe a new Bearer in the API server),
  the 401 → refresh → retry path (forceFirstRequest on the stub),
  HasValidSession after login, and the throw-when-no-token guard.
- OidcStubAuthority now mints a refresh_token in the token response
  so YavscApiClient.RefreshTokenAsync can hit /connect/token in
  tests.
- PostItViewModelTests uses a ThrowingYavscApiClient / StubYavscApiClient
  pair instead of the old HttpClient injection point, matching the
  new constructor shape.

dotnet test: 21/21 green. dotnet build: 0 errors.
2026-06-23 21:25:17 +01:00
Lum
d091f2c663 postit: persistent token store + silent refresh on YavscApiClient
Move TokenSource.cs and YavscApiClient.cs into PostIt/Services/ under
the PostIt.Services namespace so they sit next to CustomSchemeBrowser
and SingleInstance.

YavscApiClient:
- Take Settings + TokenStore in the constructor; BaseAddress now comes
  from settings.ApiUrl (defaults to https://blogs.pschneider.fr/api/v1/)
  instead of being hard-coded to yavsc.org.
- Compute access-token expiry from IdentityModel's AccessTokenExpiration
  (TimeSpan / DateTimeOffset / int) with a JWT 'exp' claim fallback,
  then a 23h default. Fixes the original .AccessTokenExpiration.Second
  bug that made tokens expire immediately.
- Use IdentityModel.OidcClient 6.0's RefreshTokenAsync(refreshToken,
  cancellationToken:) — the named parameter is 'cancellationToken',
  not 'ct' as previously written.
- Wrap HttpClient in a BearerTokenHandler that injects the access
  token on every outbound request; serialise the refresh path with a
  SemaphoreSlim so concurrent callers don't all rotate the same
  refresh token (which Auth0 invalidates on first use).
- 401 from the server triggers a single forced refresh + retry.
- RefreshFailedException is permanent when Auth0 rejects the refresh
  token (revoked / rotation-theft detected / expired): TokenStore is
  purged and the caller must re-run LoginInteractiveAsync.
- Expose HasValidSession for warm-start skip of the LoginPage.

TokenStore writes the JSON bundle with 0600 on POSIX. Future hardening
will route it through libsecret / DPAPI.

LoginPageViewModel becomes a thin coordinator: it builds (or reuses)
a YavscApiClient and delegates to LoginInteractiveAsync. The legacy
Password / UserEmail / RememberMe fields stay but are marked
[Obsolete] since the PKCE flow is interactive and IdP-collected.

Test hooks preserved: BrowserFactoryOverride, SettingsLoadOverride,
ApiClientOverride.

Builds clean (0 errors). No Auth0Avalonia package reference needed:
Platform.CreateBrowser + CustomSchemeBrowser is the right shape for
PostIt's per-platform redirection.
2026-06-23 21:04:08 +01:00
2dec799d71 Introduce Yavsc.Interfaces.ISmtpClient and a recording test fake
Narrow ISmtpClient to the four operations MailSender actually uses,
behind a Yavsc.Interfaces.ISmtpClientFactory. Production wires
MailKitSmtpClient (SmtpClientFactory); tests wire a recording fake
(RecordingSmtpClientFactory). The fake is pre-registered in
WebServerFixture so SMTP calls are short-circuited; the EMailling
test now asserts the Connect -> Authenticate -> Send -> Disconnect
sequence. Yavsc.Abstract stays free of MailKit/MimeKit.
2026-06-22 02:09:02 +01:00