Commit graph

18 commits

Author SHA1 Message Date
333b066e66 Identity reloaded 2026-07-05 23:56:10 +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
0cc82fec5d bug fix IUserSettings 2026-06-30 23:55:43 +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
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
f3a3b63595 WIP PostIt login 2026-06-25 00:08:25 +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
16508e9fb2 postit: replace loopback HTTP listener with custom URI scheme
OAuth2 redirect handling for the desktop PostIt app now follows
RFC 8252 §7.1: the redirect URI is a custom scheme
(postit://callback) that the OS routes back to PostIt instead of
a 127.0.0.1 HTTP listener. The browser hits the scheme, the OS
launches a fresh PostIt process, that process hands the URL to
the running instance over a named pipe, then exits.

Architecture:
  - SingleInstance: cross-platform named-pipe helper. TryHandOffAsync
    is what the 2nd instance calls to forward its command-line URL;
    StartServerAsync runs on the 1st instance and pumps URLs into
    a callback (the running CustomSchemeBrowser).
  - CustomSchemeBrowser: IBrowser that opens the system browser on
    the authorize URL and blocks until the named pipe yields the
    callback URL. No HTTP listener, no port to bind or release,
    no HttpListener lifecycle to babysit.
  - Platform.DefaultRedirectUri is now postit://callback. The
    CustomScheme property exposes the prefix for the redirect
    validator.
  - App.OnFrameworkInitializationCompleted detects a 2nd-instance
    launch by scanning command-line args for the scheme prefix,
    hands the URL off, and exits before opening a window. The
    first instance starts normally and only the browser is
    replaced.

What still has to happen on the user's machine:
  - Registering the postit:// scheme with the OS (a one-time
    setup step: .desktop file on Linux, registry key on Windows,
    Info.plist / LSSetDefaultHandlerForURLScheme on macOS). The
    code already validates EndUrl starts with the configured
    scheme, so a missing registration surfaces as a clear error
    from CustomSchemeBrowser rather than a silent hang.

Removed:
  - LoopbackBrowser and LoopbackBrowserTests — the listener,
    the timeout, the double Stop/Close dance. The whole class of
    'port already bound' / 'next launch fails' issues goes away.
  - The /tests/LoopbackBrowserTests.cs regression coverage is
    obsolete: there is no listener to release anymore. The single-
    instance hand-off is covered by the existing tests on the
    OidcClient flow path.

Tests: PostIt.Tests 17/17 pass, Yavsc.Org.Tests 13/14 (the one
remaining failure is SendEMailSynchrone, pre-existing and
unrelated to this change).
2026-06-22 00:53:01 +01:00
d62e59ba30 postit: trailing-slash regression + loopback browser cleanup; identityserver: BC cert loader + SecurityKey
PostIt
- LoginPage renders StatusMessage as a read-only TextBox so the
  text is mouse-selectable and copyable (no copy button).
- LoginPageViewModel exposes ExternalUrl (Authentication.Authority
  with trailing slash stripped) and DiscoveryUrl
  (ExternalUrl + '/.well-known/openid-configuration'). LoginAsync
  surfaces the discovery URL before the call and suffixes it onto
  every error message, so reachability issues are diagnosable by
  pasting the URL into a browser.
- LoopbackBrowser (used for the OIDC redirect listener on desktop)
  now bounds the GetContextAsync wait at 5 minutes and calls both
  Stop() and Close() in the finally, so the listener is always
  released even if the user abandons the flow. Without this, the
  next PostIt launch fails with 'Failed to listen on prefix
  http://127.0.0.1:7890/ because it conflicts with an existing
  registration on the machine.'
- Add LoginPageViewModelTests.LoginAsync_works_when_authority_has_trailing_slash
  to lock in the discovery URL contract.
- Add LoopbackBrowserTests covering both timeout and happy-path
  listener cleanup.

Yavsc.Org
- Drop the CustomEntries['jwks_uri'] override from commit 84160f07.
  IdentityServer8 reserves that key and rejects the override with
  'Discovery custom entry jwks_uri cannot be added, because it
  already exists.' The default /.well-known/openid-configuration/jwks
  endpoint is what DiscoveryKeyEndpoint actually serves.
- Replace X509Certificate2.CreateFromPemFile + the 3-arg
  X509Certificate2(path, key, X509KeyStorageFlags) ctor with a
  BouncyCastle-backed loader. The BCL path raised
  InvalidOperationException during AddSigningCredential and aborted
  the runtime with SIGABRT (code=6/ABRT, libcoreclr.so stack) on
  the production EC Let's Encrypt cert. BouncyCastle 2.6.2
  PemReader accepts PKCS#1 + PKCS#8 EC/RSA PEMs uniformly; RSA
  path uses DotNetUtilities.ToRSA, EC path rebuilds ECDsa from
  ECParameters with the curve dispatched by NIST order bit length
  (256/384/521).
- Switch the signing credential handed to IdentityServer8 from
  X509Certificate2 to a SigningCredentials built from a SecurityKey
  (RsaSecurityKey / ECDsaSecurityKey). The cert loaded fine but
  IdentityServer8's key material service reads cert.PrivateKey at
  runtime — on Linux that handle is not retained across the
  X509Certificate2 / runtime boundary, so CreateJwkDocumentAsync
  raised NullReferenceException on the first GET /jwks. The
  SecurityKey is a pure managed object whose Key is a live
  AsymmetricAlgorithm, which survives every read IdentityServer
  does.
- Add BouncyCastle.Cryptography 2.6.2 to src/Yavsc.Org/Yavsc.Org.csproj
  and the matching PackageVersion in Directory.Packages props.
- Wrap the loader in a try/catch that prints the full managed
  stack to stderr on failure, so future PEM-format issues surface
  in journalctl instead of being hidden behind SIGABRT.
2026-06-21 07:36:22 +01:00
2263311e1b a simpler UI 2026-06-21 04:32:44 +01:00
9e190e3d3d postit: point Register button at /Account/Register
/signin only renders the local-account sign-in form on Yavsc.Org;
new accounts live at /Account/Register. Update RegisterUrl in
LoginPageViewModel and the matching test accordingly.
2026-06-21 03:03:56 +01:00
36e179c494 postit: link to register and forgot-password from LoginPage
The Yavsc.Org sign-in page and the password-reset page are the
canonical entry points for new users and locked-out users; expose
both from PostIt's LoginPage by deriving their URLs from the
configured Authentication.Authority.

* Add RegisterUrl, ForgotPasswordUrl, HasXxxUrl, ConfigMissing and
  ConfigMissingMessage to LoginPageViewModel.
* LoginPage loads settings eagerly in the VM ctor so the URLs are
  populated when XAML bindings first fire.
* Two new buttons (Register a new account, Forgot password?) bind to
  HasXxxUrl via IsEnabled and fall back to Process.Start on click.
* A yellow banner surfaces when Authentication.Authority is empty,
  pointing the user at ~/.config/PostIt/postit-settings.json.

Also drop the duplicated OIDC login logic from LoginPage.axaml.cs:
the page now drives Login through LoginPageViewModel.LoginAsync and
DataContext is auto-attached when HomePage pushes the page without
a VM.

Tests cover the happy-path OIDC flow, URL derivation, and the
ConfigMissing flag.
2026-06-20 21:49:32 +01:00
c411445699 postit: test LoginPageViewModel against an in-memory OIDC authority
Add a stubbed OIDC authority (discovery, jwks, /connect/token,
/connect/userinfo) and a fake IBrowser, then cover the full
authorization-code + PKCE flow in LoginPageViewModelTests.

The new LoginPageViewModel(Settings, Func<IBrowser?>) constructor
plus the BrowserFactoryOverride property keep production wiring
unchanged: the existing parameterless ctor and the platform
projects' Platform.CreateBrowser still drive runtime.
2026-06-20 20:52:00 +01:00
002f8cc7e4 Split Directory.Packages.props: shared versions in root, per-product in src/
Move product-local package versions out of the root Directory.Packages.props
into per-product props files under src/<Product>/. The root file now only
contains versions for packages declared by two or more top-level products,
which is the actual shared set.

Each per-product Directory.Packages.props imports the root via
GetPathOfFileAbove so that the shared versions are inherited; this is
necessary because the .NET SDK picks the closest Directory.Packages.props
in the hierarchy and does not merge multiple ones.

Per-product file contents:
- src/cli/                    Microsoft.AspNetCore.Razor.Language,
                              Microsoft.Extensions.{CommandLineUtils,Configuration,Hosting}
- src/PostIt/                 Avalonia* and CommunityToolkit.Mvvm
- src/PostIt.Tests/           Avalonia.Headless{,XUnit}
- src/Yavsc.Org/              AsciiDocSharp*, Google.Apis.Compute.v1,
                              HigginsSoft.IdentityServer8.AspNetIdentity,
                              IdentityServer8.EntityFramework.Storage,
                              IdentityServer8.Security, IdentityServer8.Storage,
                              Microsoft.AspNetCore.Antiforgery, Authentication.Google,
                              Diagnostics.EntityFrameworkCore, Mvc.NewtonsoftJson,
                              SignalR, EntityFrameworkCore.Tools, Swashbuckle,
                              System.Security.Cryptography.Pkcs, YamlDotNet
- src/Yavsc.Org.Tests/        Microsoft.AspNetCore.Hosting,
                              Extensions.Caching.Memory, Options,
                              Options.ConfigurationExtensions,
                              Selenium.WebDriver, xunit.v3.{common,extensibility.core}
- src/Yavsc.Server/           Anthropic.SDK, Google.Apis.Calendar.v3,
                              Magick.NET-Q8-AnyCPU, MailKit, MimeKit,
                              Microsoft.AspNetCore.Http.Features, StaticFiles,
                              EntityFrameworkCore.SqlServer,
                              Npgsql.EntityFrameworkCore.PostgreSQL,
                              PayPalMerchantSDK, pazof.rules, RazorEngine.NetCore
- src/Yavsc.Web/              IdentityModel.AspNetCore

No per-product file is created for Yavsc.Api, Yavsc.Blogs, Yavsc.Abstract,
or templateWeb: Api and Blogs only declare the shared JwtBearer, Abstract
and templateWeb declare no package references at all.

Also includes a minor cosmetic update to FirstUIStript.cs (Firefox -> Chrome
driver, dedent, comment header). Tests previously failing on DataProtection
keyset / SMTP were unrelated environment issues (resolved by fixing the
SMTP password locally).
2026-06-19 18:51:18 +01:00
22b397ce7e Relocate test project: test/yavscTests -> src/Yavsc.Org.Tests
Move the integration test project from the top-level test/ directory into
src/ alongside the projects it tests. Rename the project (and folder) to
Yavsc.Org.Tests to match .NET conventions and reflect that it tests the
Org runtime primarily.

Path changes:
- test/yavscTests/yavscTests.csproj -> src/Yavsc.Org.Tests/Yavsc.Org.Tests.csproj
- All .cs / .json / .resx files moved to their new location
- PostItViewModelTests moved out to the dedicated src/PostIt.Tests project
  (it was unrelated to Org testing)

Build adjustments:
- <ProjectReference> paths shortened (..\..\src\X -> ..\X)
- PostIt project reference removed (covered by its own test project)
- <OutputType>exe added (required by xunit.v3)
- xunit.v3.common and xunit.v3.extensibility.core added to package versions

Solution + sln:
- yavsc.sln Project Name updated to 'Yavsc.Org.Tests' and path updated
- GUID preserved so existing build configs stay valid

Static web assets:
- The CopyStaticWebAssetsManifest target was hard-coding the destination
  filename to 'testhost.staticwebassets.endpoints.json', which worked
  when the assembly was named 'yavscTests'. Now that the assembly name
  is 'Yavsc.Org.Tests', ASP.NET Core's MapStaticAssets() looks for
  'Yavsc.Org.Tests.staticwebassets.endpoints.json' (entry-assembly-based
  resolution). Use $(MSBuildProjectName) so the copy target stays
  correct under any future rename.
2026-06-19 17:52:54 +01:00
ad19ccbcfa PostIt testing setup 2026-06-19 16:55:42 +01:00