Compare commits

...

50 Commits

Author SHA1 Message Date
04cea1ca4b Refactor to use streams for PDF handling
Refactored `IPdfDigitalSignatureService` to replace `byte[]` with `Stream` for input and output, improving memory efficiency and scalability. Updated `PdfDigitalSignatureService` implementation to support stream-based operations, including signing, checking, and extracting PDFs.

Modified `SignPdfAsync` to handle multiple signatures sequentially using streams and ensured proper disposal of intermediate streams. Updated `CheckPdfSignatureAsync` and `ExtractOriginalPdfAsync` to use streams, reducing memory overhead.

Refactored `PdfSignatureController` to use streams for file handling, enabling efficient processing of large files. Introduced helper methods for stream handling and enhanced cancellation support. Improved code maintainability by consolidating common logic and reducing duplication.
2026-10-15 11:04:05 +02:00
29108594d9 Update project version to 1.5.0-beta
Updated the `EnvelopeGenerator.Server` project version from `1.4.0-beta` to `1.5.0-beta`.
This includes updates to the file version (from `1.4.0.0` to `1.5.0.0`)
and the assembly version (from `1.4.0.0` to `1.5.0.0`).
2026-10-14 15:11:19 +02:00
51c0f51738 Refactor contact info handling in PDF signing
Replaced the `ContactInfo` property with separate `Email` and `Phone` fields in `PdfSignOptionsDto` and `PdfSignatureCheckItemDto` for better granularity. Updated the `PdfDigitalSignatureService` to handle the new fields, introducing `BuildContactInfo` and `ParseContactInfo` methods for constructing and parsing contact information.

Modified the `PdfSignatureController` to reflect these changes, updating request models and the `SignPdfAsync` method. Updated the `README.md` to document the new structure. These changes improve the clarity and structure of contact information handling.
2026-10-14 15:10:55 +02:00
816bbce9c6 Remove client-side SigningTime handling
The `SigningTime` property has been removed from the `PdfSignOptionsDto` class and related client-side input handling. It is now set automatically on the server side based on the `UseUtcSigningTime` configuration (`UtcNow` or local time).

Updated the `PdfDigitalSignatureService` to always set `SigningTime` server-side, ensuring consistent and deterministic behavior. Removed `SigningTime` from the `PdfSignatureController` and adjusted the logic to exclude it from the `signOptions` object.

Updated the `README.md` to reflect these changes, clarifying that `SigningTime` is now server-side only. These changes improve security and simplify client integration.
2026-10-14 14:49:15 +02:00
5194d638ac Refactor README.md with localized and detailed guidance
The README.md has been extensively restructured to improve clarity, technical depth, and usability. Key changes include:

- Shifted most sections from English to German for localization.
- Consolidated distributed runbooks into a unified reference for PKCS#11/SoftHSM integration.
- Expanded architecture overview with deployment patterns and runtime paths.
- Replaced PKCS#11 basics with detailed setup instructions and troubleshooting tips.
- Updated runtime configuration examples with security best practices.
- Highlighted implemented services, models, and DTOs in the DI setup.
- Added sections on operational challenges, troubleshooting, and monitoring.
- Introduced an API health endpoint and smoke test recommendations.
- Clarified API behavior for signature metadata to ensure deterministic integration.
- Expanded security guidelines, including key rotation and SSH rollback procedures.
- Added a forward-looking section on potential improvements.
- Retained and updated references to official documentation and tools.

These changes aim to provide a comprehensive, structured, and production-aligned guide for developers and engineers.
2026-10-14 14:47:40 +02:00
6b3622b366 Remove test endpoint from PdfSignatureController
Removed the `[HttpGet("sign/test")]` endpoint and its `Test`
method from the `PdfSignatureController`. This method
contained hardcoded Base64 PDF data and predefined signing
options for testing purposes. Eliminated the associated
logic for decoding the Base64 string, creating signing
options, signing the PDF, and returning the signed file.

These changes streamline the controller by removing
unnecessary and potentially insecure functionality,
ensuring cleaner and more production-ready code.
2026-10-14 14:35:58 +02:00
4f8fa9afd8 Rename DefaultApplicationName to ApplicationName
Updated the `Pkcs11Options` class to rename the `DefaultApplicationName` property to `ApplicationName`, clarifying its role as a globally controlled value embedded in PDF signature metadata.

Modified `PdfDigitalSignatureService` to source `ApplicationName` directly from `Pkcs11Options`, removing client-level overrides. Updated `PdfSignatureController` to reflect this change by removing the `ApplicationName` property from `SignOptions`.

Updated `appsettings.json` and `README.md` to reflect the property name change. These changes enforce stricter configuration control, improving metadata consistency and security.
2026-10-14 14:34:59 +02:00
7a36316b7e Standardize CertificationLevel in PDF signing
The `CertificationLevel` property was removed from the `PdfSignatureOptions` class. It is now explicitly set to `PdfSignatureCertificationLevel.FormFillingAndAnnotations` in all instances where `PdfSignatureOptions` is instantiated.

Previously, `CertificationLevel` was nullable and dynamically set from the `request` object or defaulted to `PdfSignatureCertificationLevel.NoCertification`. These changes ensure consistent behavior by standardizing the certification level to `FormFillingAndAnnotations`.
2026-10-14 14:31:54 +02:00
68d9dbdcdf Add UUID and metadata support for PDF signing
Enhanced PDF signing with UUID and metadata handling:
- Added `UUID` and `OriginalDocumentSha256` to `PdfSignOptionsDto` and `PdfSignatureCheckItemDto`.
- Introduced `BusinessReason` to separate metadata from signature reasons.
- Updated `PdfDigitalSignatureService` to embed and parse metadata in signature reasons.
- Improved error handling to include metadata in validation results.
- Updated `PdfSignatureController` to handle `UUID` in signing requests.

Refactored PKCS#11 configuration:
- Replaced `LibraryPath` with `AssetsRootPath` for asset resolution.
- Added `ProxySocket` and `DefaultApplicationName` options.
- Clarified runtime behavior for asset resolution in `README.md`.

Updated documentation and examples to reflect these changes.
2026-10-14 14:24:51 +02:00
7f3d1afcb9 Add SoftHSM SSH and SFTP helper scripts 2026-10-14 13:49:56 +02:00
955ac57a1a Add original revision extraction for signed PDFs 2026-10-14 13:49:46 +02:00
b8a96330c0 Add PKCS#11 startup self-test health reporting 2026-10-14 13:49:38 +02:00
8f2744afc7 add soft hsm lib 2026-10-14 13:11:23 +02:00
c8ddfac8d0 Improve PDF signing and validation logic
Updated `.gitignore` to exclude new files and directories, including `FodyWeavers.xsd` and `appsettings.Secrets.json`.

Refactored `PdfDigitalSignatureService`:
- Improved signing time handling by calculating fallback inline.
- Simplified `SignPdfAsync` by inlining signature building.
- Added `ParseByteRanges` to extract `/ByteRange` values from PDFs.
- Introduced `CoversWholeDocument` to validate document coverage.

Enhanced signature validation:
- Integrated `ParseByteRanges` and `CoversWholeDocument`.
- Streamlined `PdfSignatureCheckItemDto` construction.
- Updated properties to calculate values inline.
- Improved `Unchanged` property to check cryptographic validity and document coverage.

These changes enhance maintainability, readability, and functionality.
2026-10-13 18:52:28 +02:00
1942d78155 Add cryptographic infrastructure and configuration
Integrated cryptographic functionality by adding a reference to `EnvelopeGenerator.Infrastructure.Crypt.csproj`. Updated `Program.cs` to include dependency injection for cryptographic services and load `appsettings.Secrets.json` for sensitive configurations. Added a new `Crypt` section in `appsettings.json` to configure PKCS#11 cryptographic operations, enhancing security and signing capabilities.
2026-10-13 14:53:49 +02:00
f361898ba4 Add PKCS#11-based PDF signing infrastructure
Introduced a cryptographic infrastructure for PDF signing and validation using PKCS#11-based hardware security modules (HSMs) or software tokens. Key changes include:

- Added `PdfDigitalSignatureService` for signing PDFs, multi-signature support, and signature validation.
- Implemented `Pkcs11ExternalSigner` and `Pkcs11PdfSigningRsa` for PKCS#11-based signing with DevExpress PDF infrastructure.
- Added utilities like `Pkcs11SessionRunner`, `Pkcs11InteropBootstrap`, and `Pkcs11ToolBridge` for session management, library initialization, and fallback mechanisms.
- Introduced `Pkcs11Options` for managing PKCS#11 configurations.
- Updated project dependencies to include `DevExpress.Document.Processor`, `System.Security.Cryptography.Pkcs`, and `Pkcs11Interop`.
- Enhanced error handling and fallback support for PKCS#11 operations.

These changes enable robust and extensible PDF signing capabilities with detailed signature metadata extraction and validation.
2026-10-13 14:45:47 +02:00
7766e2ea25 Add PKCS#11 support for PDF signing and validation
Introduced `Pkcs11Options` for configuring PKCS#11 signing workflows, including properties for library path, token selection, and signing metadata. Added `PdfSignOptionsDto` to represent signing options and `PdfSignatureCheckResultDto` with related DTOs for signature validation.

Defined `PdfSignatureCertificationLevel` enum for certification levels. Added `IPdfDigitalSignatureService` interface to support signing and validating PDF signatures. These changes enable robust and extensible handling of digital signatures.
2026-10-13 14:44:06 +02:00
63c60a91b2 Add multi-targeting support for net7.0 and net8.0
Updated the project to support both net7.0 and net8.0 frameworks.
Modified `<TargetFramework>` to `<TargetFrameworks>` and added
conditional `<ItemGroup>` entries for dependencies and project
references specific to each framework. Updated package versions
(e.g., Microsoft.Extensions.DependencyInjection to 9.0.6) and
introduced new dependencies for net8.0, including
Microsoft.EntityFrameworkCore 8.0.17. Added a `<Compile Remove>`
directive for net7.0 to exclude Crypt-related files. Ensured
compatibility and maintained backward support for net7.0.
2026-10-08 10:33:11 +02:00
a5d2c477f6 Add EnvelopeGenerator.Infrastructure.Crypt project
A new project, `EnvelopeGenerator.Infrastructure.Crypt`, has been added to the solution. This project targets `.NET 8.0` and includes several `Microsoft.Extensions` dependencies (e.g., `Configuration.Binder`, `DependencyInjection.Abstractions`, etc.) and the `Pkcs11Interop` package.

The solution file (`EnvelopeGenerator.sln`) has been updated to include the new project, its build configurations, and its nesting under the same parent as `EnvelopeGenerator.Infrastructure.Doc`.
2026-10-08 10:32:48 +02:00
3a71d57619 Enhance FES docs, plans, and SoftHSM integration
Updated README.md for clarity and added official references. Introduced detailed infrastructure and integration plans for FES, including phased implementation, deployment options, and risk mitigations. Added FES workflow diagrams in draw.io and PDF formats. Documented SoftHSM testing process and integration details in ticket.md. Improved alignment with clean architecture principles and production readiness.
2026-10-08 10:31:00 +02:00
73b6c2712c Update ResourceManager references in translation functions
Updated the `TranslateCertificationType` and `TranslateFinalEmailType` functions to use the `ResourceManager` from the `CommonServices.My.Resources.Model` namespace instead of the `Resources.Model` namespace for consistency and improved resource management.
2026-10-08 10:16:22 +02:00
200972c370 Update README with PKCS#11 integration details
Added a detailed README for the `EnvelopeGenerator.Infrastructure.Crypt` project, explaining its purpose, functionality, and integration with PKCS#11-based cryptographic workflows.

Highlights include:
- Overview of the project's role in FES workflows.
- Explanation of SoftHSM and PKCS#11 deployment patterns.
- Mapping of functionality to FES diagram steps 6-8.
- Documentation of service interfaces and DI entry point.
- Configuration guidance with JSON examples and security best practices.
- Instructions for obtaining PKCS#11 values and setting up SoftHSM.
- Checklist for IT handover and environment setup.
- Steps for running cryptographic tests with PowerShell and Linux examples.
- Common failure diagnostics and their meanings.
- Clarification of signing semantics and validation requirements.
- FAQ addressing common questions about SoftHSM and PKCS#11 usage.

This update ensures clear guidance for developers and IT teams to configure and integrate the cryptographic layer effectively.
2026-10-07 13:35:50 +02:00
9f7519941a Improve bootstrap handling in SenderEditorPage
Added a `DxLoadingPanel` to display a loading indicator during the bootstrap process. Introduced the `IsBootstrapLoading` property to track bootstrap progress. Refactored `OnParametersSetAsync` to handle bootstrap tokens more effectively, including redirecting to `/sender` if no token is provided. Updated `TryApplyBootstrapAsync` to adjust navigation behavior when the bootstrap payload is `null`.

Enhanced `OnAfterRenderAsync` to process `_pendingBootstrapToken` more cleanly and removed redundant logic. Simplified navigation and improved code readability and maintainability.
2026-10-06 13:59:39 +02:00
66e58b4a1a Add envelope settings step to wizard
Introduced a new step (step 2) in the `CreateEnvelopeWizardPopup` for configuring envelope settings, including security, reminders, and expiration options.

- Added fields for certification type, final email options, 2FA, access codes, and reminder settings.
- Updated step titles, descriptions, and total steps from 4 to 5.
- Implemented validation logic for the new settings step.
- Added methods to handle changes in settings fields and apply defaults.
- Updated `CreateEnvelopeWizardResult` and `CreateEnvelopeBootstrapPayload` to include new fields.
- Modified `SenderEditorPage` and `SenderPage` to handle new settings.
- Styled the new step with updated CSS for grids, groups, and toggles.
- Refactored state reset logic to initialize new fields.
2026-10-06 12:59:55 +02:00
de9d8c6f37 Add document preview feature to wizard popup
Introduced a document preview feature in the `CreateEnvelopeWizardPopup` component. This includes:

- Injected `PdfRenderService` for rendering PDF pages.
- Replaced document metadata display with a preview card.
- Added `SenderPdfImageEditor` for interactive PDF previews.
- Implemented state management for preview pages and overlays.
- Added fallback logic to estimate PDF page count.
- Enhanced `ResetWizardState` to reset preview-related fields.
- Styled the preview card and wrap with new CSS classes.
- Added placeholder event handlers for editor interactions.
2026-10-06 11:48:03 +02:00
47f48ba12a Add PdfFileDropZone for interactive PDF uploads
Replaced static upload message in `CreateEnvelopeWizardPopup.razor` with a new `PdfFileDropZone` component to enhance user experience. The component supports drag-and-drop functionality, file selection, and dynamic states (e.g., disabled, drag-active).

Introduced `PdfFileDropZone.razor` with customizable parameters such as `Disabled`, `HasDocument`, `UploadText`, and `DragDropHintText`. Added event handling for drag-and-drop interactions and file selection.

Updated `sender-page.css` to include styles for the new component, ensuring seamless integration with the existing layout. Adjusted styles for hover effects, drag-active state, and disabled state.

These changes improve usability and make PDF uploads more intuitive.
2026-10-06 10:31:43 +02:00
60241c9c6d Refactor receiver suggestions filtering logic
Introduced `ReceiverSuggestionFilterHandler` to refine the
filtering of recent receiver suggestions based on name and
email. Added `SuggestionLimit` constant to replace hardcoded
limits and ensure consistency. Updated UI to use the new
`FilteredRecentSuggestions` property, which leverages the
`BuildFilteredRecentSuggestions` method for grouping,
ordering, and limiting suggestions. Adjusted
`OnDocumentSelectedAsync` to use the new constant. Added
necessary `@using` directive for the filter handler.
2026-10-06 09:26:43 +02:00
2a939b4cad Add filtering logic for receiver suggestions
Introduce `ReceiverFilterCriteria` to encapsulate filtering criteria for receivers, including normalization of `FullName` and `EmailAddress`. Add `ReceiverSuggestionFilterHandler` to filter `RecentReceiverSuggestionDto` objects based on the criteria. Includes methods for matching criteria and filtering suggestions.
2026-10-06 09:26:22 +02:00
e89d471c6f Refactor receiver input and improve UI/UX
Replaced receiver list with a tag-based `DxTagBox` for better flexibility and dynamic updates. Updated receiver management logic to synchronize `_receivers` and `_receiverTags`. Enhanced accessibility with ARIA attributes for the suggestion list.

Redesigned the "Add Receiver" button with custom styles, hover effects, and an inline SVG icon. Improved the suggestion list with horizontal scrolling and nowrap styling. Styled tags and added a remove button for each tag.

Increased recent receiver suggestions fetch limit to 20. Added validation to ensure default envelope type selection. Refactored empty state handling and cleaned up redundant code for better maintainability.
2026-10-05 21:58:51 +02:00
ece676fbcf Make Take optional and refactor query handling logic
Updated the `Take` property in `ReadRecentReceiverSuggestionsQuery` to be nullable, allowing for unlimited results when not specified. Refactored the `Handle` method in `ReadRecentReceiverSuggestionsQueryHandler` to conditionally apply the `Take` limit only when provided. Renamed the cancellation token parameter for consistency. Improved code clarity and flexibility by removing redundant operations and dynamically applying the `Take` logic.
2026-10-05 17:06:47 +02:00
fac4ec28a4 Add localization and UI updates for receiver actions
Added new localized strings for "Recently used recipients" and
"Skip" in German, English, and French resource files. Updated
the `CreateEnvelopeWizardPopup.razor` to enhance the "Add
Receiver" button with a primary render style and a new CSS
class. Introduced styles for the button in `sender-page.css`
to improve its appearance with a minimum width, bold font,
and box shadow.
2026-10-05 17:02:12 +02:00
a3b11ed63f Add recent receiver suggestions to wizard
Introduced a feature to display and apply recent receiver
suggestions in the `CreateEnvelopeWizardPopup` component.
Added a new section in step 2 to show recently used receivers,
with loading and state management logic. Updated the
`ReceiverService` to fetch suggestions from the backend API.

Enhanced the UI with new styles for the suggestions section
and improved localization support. Refactored state
management to handle loading, resetting, and applying
suggestions. Minor cleanup and adjustments to ensure proper
state transitions.
2026-10-05 16:53:57 +02:00
5627483589 Make RecentReceiverSuggestionDto immutable; refactor query
Updated RecentReceiverSuggestionDto to use `init` properties,
adding immutability and a new `LastUsedAt` field. Refactored
ReadRecentReceiverSuggestionsQueryHandler to simplify query
logic, remove `IMapper` dependency, and improve determinism
in results. Introduced tie-breaking for duplicate timestamps
and optimized ordering by `LastUsedAt` and `EmailAddress`.
Removed redundant `Include` and mapping steps for clarity.
2026-10-05 16:43:34 +02:00
bf23e88cf8 Add plan for recent receiver suggestions feature
Added a detailed plan document outlining the development of a "recent receiver suggestions" feature for step 3 of the sender wizard. The plan defines team working rules, objectives, functional requirements, and architecture direction across application, server, and client layers.

The implementation is divided into six phases, covering MediatR query creation, API endpoint addition, client integration, UI updates, regression testing, and technical debt tracking. Each phase includes black-box test suggestions to ensure quality and robustness. The plan emphasizes incremental development, user approval, and quality-focused processes.
2026-10-05 15:58:58 +02:00
9435561e78 Add recent receiver suggestions query and DTO
Introduce `RecentReceiverSuggestionDto` to represent recent receiver suggestions with `FullName` and `EmailAddress`.

Add `ReadRecentReceiverSuggestionsQuery` to retrieve recent receiver suggestions scoped by sender username and limited to 3-5 results.

Implement `ReadRecentReceiverSuggestionsQueryHandler` to process the query using Entity Framework Core and AutoMapper.

Update `MappingProfile` to map `EnvelopeReceiver` to `RecentReceiverSuggestionDto`.
2026-10-05 15:55:19 +02:00
db1e91a3f6 Set C# language version to latest in project file
Added the `<LangVersion>` property to `EnvelopeGenerator.Application.csproj` with the value `latest`. This ensures the project uses the most up-to-date C# language features supported by the compiler, enabling access to new enhancements and features as they become available.
2026-10-05 15:32:41 +02:00
0c664c0995 Improve UX, security, and maintainability
- Introduced a DevExpress toast-based notification system using `DxToastProvider` and `IToastNotificationService` for consistent feedback.
- Standardized request-to-domain mapping with AutoMapper/profile conventions or reflection-based mappers, enforced at the Core library level.
- Removed dynamic SQL string composition and migrated to parameterized queries to address SQL injection vulnerabilities. Added CI guardrails to prevent reintroduction.
- Refined UX on `EnvelopeSenderPage.razor` to enforce deterministic row double-click behavior and align row action buttons/tooltips.
- Enabled SPA-style language switching for immediate UI culture updates without page reloads.
- Added sender-scoped caching for "recent receiver suggestions" with short TTL, invalidation hooks, and cross-sender isolation.
2026-10-05 15:20:58 +02:00
5db2f6f1e3 Refactor envelope type selection logic
Removed the placeholder option from the envelope type dropdown to simplify the UI. Introduced a new `GetDefaultEnvelopeTypeId()` method to centralize and enhance the logic for determining the default envelope type. This method prioritizes envelope types with titles containing "Handwritten Signature" if available, improving alignment with user preferences. Updated `_selectedEnvelopeTypeId` initialization to use the new method for better maintainability.
2026-10-05 15:04:09 +02:00
a535e20b0e Add "Next" button translations to localization files
Added a new resource entry for the "Next" button in the
localization files for German (de-DE), English (en-US), and
French (fr-FR). Translations include "Weiter" in German,
"Next" in English, and "Suivant" in French.
2026-10-05 15:01:15 +02:00
bb35a68b1f feat(sender-editor): consume bootstrap payload and auto-save draft
Accept bootstrapToken query parameter and consume one-time payload from sessionStorage-backed service.

Hydrate editor state with title, message, envelope type, receivers, and PDF document from bootstrap data.

Refactor draft save into reusable core flow and trigger non-navigating auto-save after bootstrap is applied.

Prevent stale token replay by clearing query token from URL and handling invalid tokens gracefully.
2026-10-05 14:54:06 +02:00
715add7f51 feat(sender): add create-envelope wizard with bootstrap handoff
Introduce a 4-step modal wizard on SenderPage for creating envelopes.

Validate required fields, support optional skip, receiver management, PDF upload, and keyboard shortcuts.

Persist wizard payload in sessionStorage via token-based bootstrap service and navigate to editor with bootstrapToken.

Register bootstrap storage service in both client and server DI containers and add dedicated sender wizard styling.
2026-10-05 14:53:48 +02:00
621e22701a Add markdown audit and update architecture docs
Added a "Markdown Audit Snapshot" section to document the status, gaps, and recommendations for markdown files in the repository. Included a "Documentation Audit TODO" checklist for tracking updates. Updated the "Active Architecture (Post-Migration)" section to reflect the current Blazor Auto (Server+WASM hybrid) setup. Identified and marked outdated or redundant markdown files for removal or archival. Highlighted the need for periodic synchronization of documentation with implementation progress.
2026-10-05 09:57:56 +02:00
5ef32a2b0c Adjust SenderEditor UI defaults and accordion styling
Changed the `DxAccordionItem` in `SenderEditorPage.razor` to be collapsed by default. Removed unused elements (`sender-settings-chip` and `sender-settings-grid`) from the accordion's content template.

Updated `envelope-viewer.css` to refine the accordion header's appearance: reduced font size, font weight, and padding, and added a `line-height` property for better spacing.
2026-10-02 15:23:57 +02:00
54d16eb3b8 Refactor SenderEditorPage for modernized UI design
Replaced inline styles with reusable CSS classes to improve maintainability, readability, and scalability. Updated the layout and styling of key components, including the action bar, title and message inputs, PDF metadata display, and buttons. Introduced a `DxAccordion` for envelope settings and redesigned the empty state and save result dialog. Added dynamic styling using CSS variables and centralized styles in `envelope-viewer.css`. Removed redundant inline styles and improved overall UI consistency.
2026-10-02 14:59:43 +02:00
ae3264253d Update ILogger type in SenderPage.razor
Changed the `ILogger` dependency injection type parameter from `EnvelopeSenderPage` to `SenderPage` to ensure alignment with the correct class name or intended logging context.
2026-10-02 14:49:38 +02:00
4cbfe52d5b Add localized strings and update localization logic
Added new localized strings to `Model.en.resx`, `Model.fr-FR.resx`,
and `Model.resx` for additional features/settings in English,
French, and German. Updated `SenderEditorPage.razor` to inject
`ModelLocalizer` and modified the `L` function to prioritize
localized strings from `ModelLocalizer` over `UiLocalizer`.
Included `@using EnvelopeGenerator.Domain.Resources` to ensure
access to the `Model` resource file. These changes improve
localization flexibility and maintainability.
2026-10-02 14:46:40 +02:00
27c6b017cd refactor (EnvelopeSenderPage): Rename to SenderPage.razor. 2026-10-02 14:30:11 +02:00
8378c33465 Refactor PDF rendering, UX, and security improvements
Refactored `PdfRenderController.cs` to replace JSON/base64 `byte[]` transport with binary streaming for PDF rendering, improving memory and latency performance for large files.

Introduced a DevExpress toast-based notification system using `DxToastProvider` and `IToastNotificationService` for consistent, actionable feedback.

Standardized request-to-domain mapping with AutoMapper/profile conventions or reflection-based mappers, enforced at the Core library level to reduce drift.

Addressed SQL injection risks by replacing dynamic SQL string composition with parameterized queries, conducted a repo-wide audit, and added CI guardrails.

Improved UX in `EnvelopeSenderPage.razor` by enforcing deterministic row double-click behavior and aligning row action buttons/tooltips.

Implemented SPA-style language switching for immediate UI culture updates without page reloads.

Updated the SQL Server connection string in `appsettings.json`.
2026-10-02 14:04:45 +02:00
c7c4e1194d Force full page reload on language change
Updated the `Navigation.NavigateTo` method in `LanguageControls.razor` to set the `forceLoad` parameter to `true`. This ensures that the application performs a full page reload when the language is changed, improving consistency in language updates.
2026-10-02 13:59:40 +02:00
3b367eff7f Remove EnvelopeSenderEditorPage.razor entirely
The `EnvelopeSenderEditorPage.razor` file was completely removed, including all Razor markup, Blazor components, JavaScript references, CSS styles, and C# code-behind logic.

Key changes:
- Removed the `/sender/editor_legacy` route and all associated imports (`@using`) and dependency injections (`@inject`).
- Deleted the entire HTML structure, including UI elements for PDF editing, signature placement, and receiver management.
- Removed all references to external CSS and JavaScript files.
- Deleted Blazor components like `DxPdfViewer`, `DxPopup`, and `DxTextBox`.
- Removed C# code for state management, lifecycle methods, event handlers, and helper methods.
- Eliminated localization, validation logic, session persistence, and cache management.
- Removed PDF manipulation logic (e.g., placeholder rendering with `PdfSharp`).
- Deleted receiver management logic, including email suggestions and validation.

This change removes the entire functionality of the `EnvelopeSenderEditorPage`, including its UI, backend logic, and external integrations.
2026-10-02 13:39:00 +02:00
69 changed files with 6013 additions and 1496 deletions

1
.gitignore vendored
View File

@@ -370,3 +370,4 @@ FodyWeavers.xsd
/EnvelopeGenerator.Server/EnvelopeGenerator.Server/publish-output /EnvelopeGenerator.Server/EnvelopeGenerator.Server/publish-output
/EnvelopeGenerator.Server/EnvelopeGenerator.Server/tekh_softHSM_test.md /EnvelopeGenerator.Server/EnvelopeGenerator.Server/tekh_softHSM_test.md
/ignore/EnvelopeGenerator.Form /ignore/EnvelopeGenerator.Form
/EnvelopeGenerator.Server/EnvelopeGenerator.Server/appsettings.Secrets.json

View File

@@ -63,6 +63,36 @@ This section explains every markdown file in the repo: what it contains, why it
--- ---
## Markdown Audit Snapshot (2026-10-05)
The following table summarizes repository markdown files by practical status: completed, partially complete, or removable candidates.
| File | Type | Status | Missing / Gap | Removal Recommendation |
|---|---|---|---|---|
| `AGENTS.md` | Agent onboarding | Partially complete | Route/migration statements can drift from real code over time. | Keep |
| `COPILOT_CONTEXT.md` | Architecture reference | Partially complete | Some route/render details may be out of sync with other docs; needs regular reconciliation. | Keep |
| `FORM_APPLICATION_CONTEXT.md` | Legacy-to-modern feature spec | Partially complete | Large sections still marked not implemented / needs implementation. | Keep |
| `RECEIVER_PDF_VIEWER_CONTEXT.md` | Receiver PDF viewer deep-dive | Partially complete | Long migration plan needs periodic sync with active implementation. | Keep |
| `SENDER_SAVE_EDIT_MIGRATION_PLAN.md` | Sender workflow implementation plan | Partially complete | No explicit implementation progress markers per phase. | Keep (until migration closes) |
| `SENDER_PDF_TOOLBAR_PLAN_EN.md` | Sender PDF toolbar plan | Incomplete | Explicit pending item remains (`Toolbar visual polish`). | Keep (until done) |
| `SENDER_EDITOR_WASM_PDF_EDITOR_IMPLEMENTATION_PLAN_en.md` | Sender editor WASM migration plan | Incomplete | Plan exists but completion/progress tracking is minimal. | Keep (until done) |
| `EnvelopeGenerator.Server/EnvelopeGenerator.Server/README.md` | Deployment guide | Complete (operational) | No critical gap identified. | Keep |
| `envelope-generator-ui/README.md` | Angular scaffold README | Complete but generic | Template text only; low project-specific value. | Removable or replace with project-specific summary |
| `EnvelopeGenerator.Web/wwwroot/lib/typed.js@2.1.0/README.md` | Third-party vendor README | Complete (vendor) | Not project workflow documentation. | Keep with vendor assets |
| `EnvelopeGenerator.Web/wwwroot/lib/jquery-validation/LICENSE.md` | Third-party license | Complete (legal) | No gap. | Keep |
| `EnvelopeGenerator.Server/EnvelopeGenerator.Server/wwwroot/css/open-iconic/README.md` | Third-party vendor README | Complete (vendor) | Not project-specific guidance. | Keep with vendor assets |
| `ignore/EnvelopeGenerator/EnvelopeGenerator.Web/wwwroot/README.md` | Legacy PSPDFKit note | Outdated | Mentions deprecated PSPDFKit-based flow; may mislead if reused. | Removable/archive |
| `ignore/EnvelopeGenerator/EnvelopeGenerator.Web/wwwroot/lib/typed.js@2.1.0/README.md` | Duplicate vendor README | Redundant | Duplicate copy under `ignore/`. | Removable/archive |
| `ignore/EnvelopeGenerator/EnvelopeGenerator.Web/wwwroot/lib/bootstrap-icons/README.md` | Vendor README in archive area | Secondary | Archive-only utility, not active docs. | Removable/archive |
| `ignore/EnvelopeGenerator/EnvelopeGenerator.Web/wwwroot/lib/jquery-validation/LICENSE.md` | Duplicate license in archive area | Redundant | Duplicate copy under `ignore/`. | Removable/archive (if legal policy allows) |
| `ignore/EnvelopeGenerator/EnvelopeGenerator.GeneratorAPI/ClientApp/envelope-generator-ui/README.md` | Duplicate Angular scaffold README | Redundant | Generic template + duplicate in archive path. | Removable/archive |
### Documentation Audit TODO
- [ ] Validate this markdown audit table against the current codebase and update statuses (`complete`, `partial`, `incomplete`, `removable`) when implementation changes land.
---
## Active Architecture (Post-Migration) ## Active Architecture (Post-Migration)
**Frontend:** Blazor Auto (Server+WASM hybrid) **Frontend:** Blazor Auto (Server+WASM hybrid)
@@ -250,6 +280,8 @@ Manual testing workflow:
- Eliminate manual property-by-property request→domain mapping drift (example: `CreateEnvelopeCommandHandler`) by introducing a standardized mapping policy (AutoMapper/profile conventions or reflection/source-generator based mapper) and enforcing it across envelope workflows; this needs to be solved in the shared company Core library level so all services get the same guardrails by default. - Eliminate manual property-by-property request→domain mapping drift (example: `CreateEnvelopeCommandHandler`) by introducing a standardized mapping policy (AutoMapper/profile conventions or reflection/source-generator based mapper) and enforcing it across envelope workflows; this needs to be solved in the shared company Core library level so all services get the same guardrails by default.
- P1 security workstream: remove dynamic SQL string composition/interpolation from active save/create/update paths (`string.Format`, `$"...{input}..."`, `ToSqlParam`) and migrate to parameterized queries only; treat this as a potential SQL injection vulnerability (stability + security risk), execute repo-wide audit, and add CI guardrails to block reintroduction. - P1 security workstream: remove dynamic SQL string composition/interpolation from active save/create/update paths (`string.Format`, `$"...{input}..."`, `ToSqlParam`) and migrate to parameterized queries only; treat this as a potential SQL injection vulnerability (stability + security risk), execute repo-wide audit, and add CI guardrails to block reintroduction.
- Alternative UX design (Server component): in `EnvelopeGenerator.Server/EnvelopeGenerator.Server/Components/Pages/EnvelopeSenderPage.razor`, enforce deterministic row double-click behavior as exactly one action (preview OR edit), and keep row action buttons/tooltips aligned with the same rule to eliminate ambiguous navigation. - Alternative UX design (Server component): in `EnvelopeGenerator.Server/EnvelopeGenerator.Server/Components/Pages/EnvelopeSenderPage.razor`, enforce deterministic row double-click behavior as exactly one action (preview OR edit), and keep row action buttons/tooltips aligned with the same rule to eliminate ambiguous navigation.
- Implement SPA-style language switching so the UI culture updates immediately without a full page reload.
- Implement sender-scoped caching for "recent receiver suggestions" used during envelope creation (wizard/editor flows): cache key should include sender identity, support short TTL + invalidation hooks after successful envelope receiver writes, and prevent cross-sender suggestion leakage.
## Database ## Database

View File

@@ -0,0 +1,99 @@
using EnvelopeGenerator.Application.Common.Enums;
using System.ComponentModel.DataAnnotations;
namespace EnvelopeGenerator.Application.Common.Configurations;
/// <summary>
/// Represents PKCS#11 signing configuration for PDF signing workflows.
/// This options model maps to the <c>Crypt:Pkcs11</c> configuration section.
/// </summary>
public sealed class Pkcs11Options
{
/// <summary>
/// Configuration section path used for binding PKCS#11 options.
/// </summary>
public const string SectionName = "Crypt:Pkcs11";
/// <summary>
/// Optional base directory that contains the <c>pkcs11</c> folder.
/// If null/empty, runtime uses the application base directory.
/// </summary>
public string? AssetsRootPath { get; set; }
/// <summary>
/// Optional numeric slot identifier used to directly select the target token slot.
/// </summary>
public ulong? SlotId { get; set; }
/// <summary>
/// Optional token label used as a fallback token selector when <see cref="SlotId"/> is not provided.
/// </summary>
public string? TokenLabel { get; set; }
/// <summary>
/// Optional PKCS#11 proxy endpoint (for example <c>tcp://host:port</c>).
/// </summary>
public string? ProxySocket { get; set; }
/// <summary>
/// Resolved absolute PKCS#11 proxy module path used at runtime.
/// Computed from <see cref="AssetsRootPath"/> and runtime defaults.
/// </summary>
public string ResolvedLibraryPath { get; private set; } = string.Empty;
/// <summary>
/// Resolved absolute pkcs11-tool path used at runtime.
/// Computed from <see cref="AssetsRootPath"/> and runtime defaults.
/// Can be null when tool fallback is not available.
/// </summary>
public string? ResolvedToolPath { get; private set; }
public void SetResolvedPaths(string resolvedLibraryPath, string? resolvedToolPath)
{
ResolvedLibraryPath = resolvedLibraryPath;
ResolvedToolPath = resolvedToolPath;
}
/// <summary>
/// User PIN used to authenticate to the PKCS#11 token session.
/// </summary>
[Required]
[MinLength(1)]
public required string UserPin { get; set; }
/// <summary>
/// Label of the private key object used to create digital signatures.
/// </summary>
[Required]
[MinLength(1)]
public required string PrivateKeyLabel { get; set; }
/// <summary>
/// Label of the certificate object returned/embedded with the signature.
/// </summary>
[Required]
[MinLength(1)]
public required string CertificateLabel { get; set; }
/// <summary>
/// Optional global default signing reason used when request-level options do not specify a value.
/// </summary>
public string? DefaultReason { get; set; }
/// <summary>
/// Application name embedded into PDF signature metadata.
/// This value is controlled via app settings and is not client-overridable.
/// </summary>
public string? ApplicationName { get; set; }
/// <summary>
/// Controls how fallback signing time is created when request-level options do not specify a value.
/// <c>true</c> uses <see cref="DateTimeOffset.UtcNow"/>, <c>false</c> uses <see cref="DateTimeOffset.Now"/>.
/// </summary>
public bool UseUtcSigningTime { get; set; } = true;
/// <summary>
/// Optional global default certification level used when request-level options do not specify a value.
/// </summary>
public PdfSignatureCertificationLevel? DefaultCertificationLevel { get; set; }
}

View File

@@ -0,0 +1,15 @@
using EnvelopeGenerator.Application.Common.Enums;
namespace EnvelopeGenerator.Application.Common.Dto;
public sealed record PdfSignOptionsDto
{
public string? UUID { get; set; }
public string? Name { get; set; }
public string? Reason { get; set; }
public string? Location { get; set; }
public string? Email { get; set; }
public string? Phone { get; set; }
public string? ApplicationName { get; set; }
public PdfSignatureCertificationLevel? CertificationLevel { get; set; }
}

View File

@@ -0,0 +1,57 @@
namespace EnvelopeGenerator.Application.Common.Dto;
public sealed record PdfSignaturePrincipalDto(
string? CommonName,
string? Organization,
string? Country,
string? Full);
public sealed record PdfSignatureCertificateInfoDto(
PdfSignaturePrincipalDto IssuedTo,
PdfSignaturePrincipalDto IssuedBy,
string? SerialNumber,
DateTimeOffset? ValidFrom,
DateTimeOffset? ValidTo,
bool SelfSigned,
bool Expired,
bool NotYetValid,
bool IsSigner,
int? Version,
string? KeyAlgorithm,
string? SignatureAlgorithm,
string? Pem,
int? KeySizeBits);
public sealed record PdfSignatureCheckItemDto(
bool CoversWholeDoc,
string? Reason,
string? BusinessReason,
string? Location,
string? DeclaredName,
string? ContactInfo,
string? Email,
string? Phone,
string? DigestAlgorithm,
string? SignatureAlgorithm,
string? SignerName,
string? Issuer,
string? SerialNumber,
DateTimeOffset? ValidFrom,
DateTimeOffset? ValidTo,
string ExpiryCheckedAgainst,
IReadOnlyList<PdfSignatureCertificateInfoDto> Certificates,
bool Unchanged,
string? FieldName,
bool IsCryptographicallyValid,
string? SigningTime,
string? Filter,
string? SubFilter,
string? ApplicationName,
string? UUID,
string? OriginalDocumentSha256,
string? MessageDigestHex,
string? Error);
public sealed record PdfSignatureCheckResultDto(
bool Signed,
IReadOnlyList<PdfSignatureCheckItemDto> Signatures);

View File

@@ -0,0 +1,10 @@
namespace EnvelopeGenerator.Application.Common.Dto;
public sealed record Pkcs11SelfTestStatusDto(
bool Completed,
bool Success,
string Mode,
string Summary,
DateTimeOffset? CheckedAtUtc,
string? InteropError,
string? ToolError);

View File

@@ -0,0 +1,10 @@
namespace EnvelopeGenerator.Application.Common.Dto.Receiver;
public class RecentReceiverSuggestionDto
{
public required string FullName { get; init; }
public required string EmailAddress { get; init; }
public required DateTime LastUsedAt { get; init; }
}

View File

@@ -0,0 +1,9 @@
namespace EnvelopeGenerator.Application.Common.Enums;
public enum PdfSignatureCertificationLevel
{
NoCertification = 0,
NoChangesAllowed = 1,
FormFillingAndSigning = 2,
FormFillingAndAnnotations = 3
}

View File

@@ -0,0 +1,47 @@
using EnvelopeGenerator.Application.Common.Dto;
namespace EnvelopeGenerator.Application.Common.Interfaces.Services;
/// <summary>
/// Defines PDF digital-signing operations for the application boundary.
/// </summary>
public interface IPdfDigitalSignatureService
{
/// <summary>
/// Creates a digital signature for the provided PDF bytes and returns
/// a new signed PDF document.
/// </summary>
/// <param name="inputPdf">Source PDF content stream.</param>
/// <param name="outputPdf">Destination stream for signed PDF output.</param>
/// <param name="options">Optional signing options that map to PDF signature metadata fields.</param>
/// <param name="cancellationToken">Cancellation token for cooperative cancellation.</param>
Task SignPdfAsync(Stream inputPdf, Stream outputPdf, PdfSignOptionsDto? options = null, CancellationToken cancellationToken = default);
/// <summary>
/// Applies multiple signatures to the provided PDF in sequence and returns
/// the final signed PDF document.
/// </summary>
/// <param name="inputPdf">Source PDF content stream.</param>
/// <param name="outputPdf">Destination stream for signed PDF output.</param>
/// <param name="optionsList">Ordered signing options; one signature is applied per item.</param>
/// <param name="cancellationToken">Cancellation token for cooperative cancellation.</param>
Task SignPdfAsync(Stream inputPdf, Stream outputPdf, IReadOnlyList<PdfSignOptionsDto> optionsList, CancellationToken cancellationToken = default);
/// <summary>
/// Checks whether the provided PDF contains signature field(s) and whether
/// those signatures are cryptographically valid.
/// </summary>
/// <param name="inputPdf">PDF content stream to inspect.</param>
/// <param name="cancellationToken">Cancellation token for cooperative cancellation.</param>
/// <returns>A structured result containing signature presence and per-signature details.</returns>
Task<PdfSignatureCheckResultDto> CheckPdfSignatureAsync(Stream inputPdf, CancellationToken cancellationToken = default);
/// <summary>
/// Extracts the original signed revision from a signed PDF.
/// For multi-revision files this returns the first signed revision bytes.
/// </summary>
/// <param name="inputPdf">Signed PDF content stream.</param>
/// <param name="outputPdf">Destination stream for original revision output.</param>
/// <param name="cancellationToken">Cancellation token for cooperative cancellation.</param>
Task ExtractOriginalPdfAsync(Stream inputPdf, Stream outputPdf, CancellationToken cancellationToken = default);
}

View File

@@ -0,0 +1,8 @@
using EnvelopeGenerator.Application.Common.Dto;
namespace EnvelopeGenerator.Application.Common.Interfaces.Services;
public interface IPkcs11SelfTestStatusProvider
{
Pkcs11SelfTestStatusDto GetStatus();
}

View File

@@ -4,6 +4,7 @@
<TargetFrameworks>net7.0;net8.0;net9.0</TargetFrameworks> <TargetFrameworks>net7.0;net8.0;net9.0</TargetFrameworks>
<ImplicitUsings>enable</ImplicitUsings> <ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable> <Nullable>enable</Nullable>
<LangVersion>latest</LangVersion>
<GenerateDocumentationFile>true</GenerateDocumentationFile> <GenerateDocumentationFile>true</GenerateDocumentationFile>
<DocumentationFile>bin\$(Configuration)\$(TargetFramework)\$(AssemblyName).xml</DocumentationFile> <DocumentationFile>bin\$(Configuration)\$(TargetFramework)\$(AssemblyName).xml</DocumentationFile>
</PropertyGroup> </PropertyGroup>

View File

@@ -16,5 +16,9 @@ public class MappingProfile : Profile
public MappingProfile() public MappingProfile()
{ {
CreateMap<Receiver, ReceiverDto>(); CreateMap<Receiver, ReceiverDto>();
CreateMap<EnvelopeReceiver, RecentReceiverSuggestionDto>()
.ForMember(dest => dest.FullName, opt => opt.MapFrom(src => src.Name))
.ForMember(dest => dest.EmailAddress, opt => opt.MapFrom(src => src.Receiver.EmailAddress));
} }
} }

View File

@@ -0,0 +1,98 @@
using DigitalData.Core.Abstraction.Application.Repository;
using EnvelopeGenerator.Application.Common.Dto.Receiver;
using EnvelopeGenerator.Domain.Entities;
using MediatR;
using Microsoft.EntityFrameworkCore;
namespace EnvelopeGenerator.Application.EnvelopeReceivers.Queries;
/// <summary>
/// Reads recent receiver suggestions for envelope creation.
/// </summary>
/// <remarks>
/// Sender scope is assigned via chain method to avoid exposing username mutation from API query binding.
/// </remarks>
public record ReadRecentReceiverSuggestionsQuery : IRequest<IReadOnlyList<RecentReceiverSuggestionDto>>
{
/// <summary>
/// Sender username used for scoping suggestion results.
/// </summary>
internal string? Username { get; private init; }
/// <summary>
/// Desired number of results.
/// </summary>
public int? Take { get; init; } = null;
/// <summary>
/// Returns a new query instance scoped to the specified sender username.
/// </summary>
/// <param name="username">Sender username from authenticated claims.</param>
/// <returns>Scoped query instance.</returns>
public ReadRecentReceiverSuggestionsQuery ForSender(string username)
{
return this with { Username = username };
}
}
/// <summary>
/// Handles <see cref="ReadRecentReceiverSuggestionsQuery"/>.
/// </summary>
public class ReadRecentReceiverSuggestionsQueryHandler(IRepository<EnvelopeReceiver> repository)
: IRequestHandler<ReadRecentReceiverSuggestionsQuery, IReadOnlyList<RecentReceiverSuggestionDto>>
{
/// <summary>
/// Retrieves distinct recent receiver suggestions grouped by receiver email.
/// </summary>
/// <param name="request">Suggestion query.</param>
/// <param name="cancel">Cancellation token.</param>
/// <returns>Ordered list of recent receiver suggestions.</returns>
public async Task<IReadOnlyList<RecentReceiverSuggestionDto>> Handle(ReadRecentReceiverSuggestionsQuery request, CancellationToken cancel)
{
var query = repository.Query
.AsNoTracking()
.Where(er => er.Receiver != null);
if (request.Username is not null)
query = query.Where(er => er.Envelope != null && er.Envelope.User.Username == request.Username);
// 1) For each email, compute the latest usage timestamp.
var latestPerEmail = query
.GroupBy(er => er.Receiver!.EmailAddress)
.Select(g => new
{
EmailAddress = g.Key,
LastUsedAt = g.Max(er => er.AddedWhen),
});
// 2) Join back to rows that match the latest timestamp per email.
var latestRows =
from er in query
join latest in latestPerEmail
on new { EmailAddress = er.Receiver!.EmailAddress, LastUsedAt = er.AddedWhen }
equals new { latest.EmailAddress, latest.LastUsedAt }
select new
{
EmailAddress = er.Receiver!.EmailAddress,
FullName = er.Name,
LastUsedAt = er.AddedWhen,
};
// 3) Tie-break: if multiple rows share the same latest timestamp for an email,
// pick a deterministic name via Max(FullName), then order by most recent usage.
var suggestions = latestRows
.GroupBy(x => new { x.EmailAddress, x.LastUsedAt })
.Select(g => new RecentReceiverSuggestionDto
{
EmailAddress = g.Key.EmailAddress,
FullName = g.Max(x => x.FullName) ?? string.Empty,
LastUsedAt = g.Key.LastUsedAt,
})
.OrderByDescending(x => x.LastUsedAt)
.ThenBy(x => x.EmailAddress);
return request.Take is int take
? await suggestions.Take(take).ToListAsync(cancel)
: await suggestions.ToListAsync(cancel);
}
}

View File

@@ -123,6 +123,9 @@
<data name="Back" xml:space="preserve"> <data name="Back" xml:space="preserve">
<value>Zurück</value> <value>Zurück</value>
</data> </data>
<data name="Next" xml:space="preserve">
<value>Weiter</value>
</data>
<data name="AuthenticatorSetup_Prefix" xml:space="preserve"> <data name="AuthenticatorSetup_Prefix" xml:space="preserve">
<value>Klicken Sie auf den</value> <value>Klicken Sie auf den</value>
</data> </data>
@@ -564,6 +567,12 @@
<data name="AddReceiver" xml:space="preserve"> <data name="AddReceiver" xml:space="preserve">
<value>Empfänger hinzufügen</value> <value>Empfänger hinzufügen</value>
</data> </data>
<data name="SenderWizard_RecentReceivers" xml:space="preserve">
<value>Zuletzt verwendete Empfänger</value>
</data>
<data name="Skip" xml:space="preserve">
<value>Überspringen</value>
</data>
<data name="DeleteReceiver" xml:space="preserve"> <data name="DeleteReceiver" xml:space="preserve">
<value>Empfänger löschen</value> <value>Empfänger löschen</value>
</data> </data>

View File

@@ -123,6 +123,9 @@
<data name="Back" xml:space="preserve"> <data name="Back" xml:space="preserve">
<value>Back</value> <value>Back</value>
</data> </data>
<data name="Next" xml:space="preserve">
<value>Next</value>
</data>
<data name="AuthenticatorSetup_Prefix" xml:space="preserve"> <data name="AuthenticatorSetup_Prefix" xml:space="preserve">
<value>Click the</value> <value>Click the</value>
</data> </data>
@@ -564,6 +567,12 @@
<data name="AddReceiver" xml:space="preserve"> <data name="AddReceiver" xml:space="preserve">
<value>Add Receiver</value> <value>Add Receiver</value>
</data> </data>
<data name="SenderWizard_RecentReceivers" xml:space="preserve">
<value>Recently used recipients</value>
</data>
<data name="Skip" xml:space="preserve">
<value>Skip</value>
</data>
<data name="DeleteReceiver" xml:space="preserve"> <data name="DeleteReceiver" xml:space="preserve">
<value>Delete Receiver</value> <value>Delete Receiver</value>
</data> </data>

View File

@@ -123,6 +123,9 @@
<data name="Back" xml:space="preserve"> <data name="Back" xml:space="preserve">
<value>Retour</value> <value>Retour</value>
</data> </data>
<data name="Next" xml:space="preserve">
<value>Suivant</value>
</data>
<data name="AuthenticatorSetup_Prefix" xml:space="preserve"> <data name="AuthenticatorSetup_Prefix" xml:space="preserve">
<value>Cliquez sur</value> <value>Cliquez sur</value>
</data> </data>
@@ -564,6 +567,12 @@
<data name="AddReceiver" xml:space="preserve"> <data name="AddReceiver" xml:space="preserve">
<value>Ajouter un destinataire</value> <value>Ajouter un destinataire</value>
</data> </data>
<data name="SenderWizard_RecentReceivers" xml:space="preserve">
<value>Destinataires recents</value>
</data>
<data name="Skip" xml:space="preserve">
<value>Passer</value>
</data>
<data name="DeleteReceiver" xml:space="preserve"> <data name="DeleteReceiver" xml:space="preserve">
<value>Supprimer le destinataire</value> <value>Supprimer le destinataire</value>
</data> </data>

View File

@@ -276,4 +276,61 @@
<data name="YesWithAttachment" xml:space="preserve"> <data name="YesWithAttachment" xml:space="preserve">
<value>Yes, with Attachment</value> <value>Yes, with Attachment</value>
</data> </data>
<data name="ElectronicSignature" xml:space="preserve">
<value>Electronic Signature</value>
</data>
<data name="EnvelopeType" xml:space="preserve">
<value>Envelope Type</value>
</data>
<data name="Language" xml:space="preserve">
<value>Language</value>
</data>
<data name="CertificationType" xml:space="preserve">
<value>Certification</value>
</data>
<data name="TFAEnabled" xml:space="preserve">
<value>2FA enabled</value>
</data>
<data name="UseAccessCode" xml:space="preserve">
<value>Use Access Code</value>
</data>
<data name="FinalEmailToCreator" xml:space="preserve">
<value>Final Email to Creator</value>
</data>
<data name="FinalEmailToReceivers" xml:space="preserve">
<value>Final Email to Receivers</value>
</data>
<data name="SendReminderEmails" xml:space="preserve">
<value>Send Reminder Emails</value>
</data>
<data name="FirstReminderDays" xml:space="preserve">
<value>First Reminder (Days)</value>
</data>
<data name="ReminderIntervalDays" xml:space="preserve">
<value>Reminder Interval (Days)</value>
</data>
<data name="ExpiresWhenDays" xml:space="preserve">
<value>Expires After (Days)</value>
</data>
<data name="ExpiresWarningWhenDays" xml:space="preserve">
<value>Expiry Warning (Days)</value>
</data>
<data name="SenderEditor_EnvelopeSettings" xml:space="preserve">
<value>Envelope Settings</value>
</data>
<data name="SenderEditor_AdvancedOptional" xml:space="preserve">
<value>Advanced</value>
</data>
<data name="SenderEditor_SelectTemplate" xml:space="preserve">
<value>Select Template</value>
</data>
<data name="SenderEditor_Validation_ReminderInterval" xml:space="preserve">
<value>Please enter a reminder interval greater than 0 days.</value>
</data>
<data name="SenderEditor_Validation_FirstReminder" xml:space="preserve">
<value>Please enter valid days for the first reminder.</value>
</data>
<data name="SenderEditor_Validation_ExpiryWarning" xml:space="preserve">
<value>The expiry warning cannot be after the expiry date.</value>
</data>
</root> </root>

View File

@@ -113,4 +113,61 @@
<data name="MessageInvitationSent" xml:space="preserve"> <data name="MessageInvitationSent" xml:space="preserve">
<value>Invitation envoyee</value> <value>Invitation envoyee</value>
</data> </data>
<data name="ElectronicSignature" xml:space="preserve">
<value>Signature electronique</value>
</data>
<data name="EnvelopeType" xml:space="preserve">
<value>Type d'enveloppe</value>
</data>
<data name="Language" xml:space="preserve">
<value>Langue</value>
</data>
<data name="CertificationType" xml:space="preserve">
<value>Certification</value>
</data>
<data name="TFAEnabled" xml:space="preserve">
<value>2FA active</value>
</data>
<data name="UseAccessCode" xml:space="preserve">
<value>Utiliser un code d'acces</value>
</data>
<data name="FinalEmailToCreator" xml:space="preserve">
<value>E-mail final au createur</value>
</data>
<data name="FinalEmailToReceivers" xml:space="preserve">
<value>E-mail final aux destinataires</value>
</data>
<data name="SendReminderEmails" xml:space="preserve">
<value>Envoyer des e-mails de rappel</value>
</data>
<data name="FirstReminderDays" xml:space="preserve">
<value>Premier rappel (jours)</value>
</data>
<data name="ReminderIntervalDays" xml:space="preserve">
<value>Intervalle de rappel (jours)</value>
</data>
<data name="ExpiresWhenDays" xml:space="preserve">
<value>Expire apres (jours)</value>
</data>
<data name="ExpiresWarningWhenDays" xml:space="preserve">
<value>Avertissement d'expiration (jours)</value>
</data>
<data name="SenderEditor_EnvelopeSettings" xml:space="preserve">
<value>Parametres de l'enveloppe</value>
</data>
<data name="SenderEditor_AdvancedOptional" xml:space="preserve">
<value>Avance</value>
</data>
<data name="SenderEditor_SelectTemplate" xml:space="preserve">
<value>Selectionner un modele</value>
</data>
<data name="SenderEditor_Validation_ReminderInterval" xml:space="preserve">
<value>Veuillez saisir un intervalle de rappel superieur a 0 jour.</value>
</data>
<data name="SenderEditor_Validation_FirstReminder" xml:space="preserve">
<value>Veuillez saisir des jours valides pour le premier rappel.</value>
</data>
<data name="SenderEditor_Validation_ExpiryWarning" xml:space="preserve">
<value>L'avertissement d'expiration ne peut pas etre apres la date d'expiration.</value>
</data>
</root> </root>

View File

@@ -279,4 +279,61 @@
<data name="YesWithAttachment" xml:space="preserve"> <data name="YesWithAttachment" xml:space="preserve">
<value>Ja, mit Anhang</value> <value>Ja, mit Anhang</value>
</data> </data>
<data name="ElectronicSignature" xml:space="preserve">
<value>Elektronische Signatur</value>
</data>
<data name="EnvelopeType" xml:space="preserve">
<value>Umschlagtyp</value>
</data>
<data name="Language" xml:space="preserve">
<value>Sprache</value>
</data>
<data name="CertificationType" xml:space="preserve">
<value>Zertifizierung</value>
</data>
<data name="TFAEnabled" xml:space="preserve">
<value>2FA aktiviert</value>
</data>
<data name="UseAccessCode" xml:space="preserve">
<value>Zugriffscode verwenden</value>
</data>
<data name="FinalEmailToCreator" xml:space="preserve">
<value>Finale E-Mail an Ersteller</value>
</data>
<data name="FinalEmailToReceivers" xml:space="preserve">
<value>Finale E-Mail an Empfänger</value>
</data>
<data name="SendReminderEmails" xml:space="preserve">
<value>Erinnerungs-E-Mails senden</value>
</data>
<data name="FirstReminderDays" xml:space="preserve">
<value>Erste Erinnerung (Tage)</value>
</data>
<data name="ReminderIntervalDays" xml:space="preserve">
<value>Erinnerungsintervall (Tage)</value>
</data>
<data name="ExpiresWhenDays" xml:space="preserve">
<value>Läuft ab nach (Tage)</value>
</data>
<data name="ExpiresWarningWhenDays" xml:space="preserve">
<value>Ablaufwarnung (Tage)</value>
</data>
<data name="SenderEditor_EnvelopeSettings" xml:space="preserve">
<value>Envelope-Einstellungen</value>
</data>
<data name="SenderEditor_AdvancedOptional" xml:space="preserve">
<value>Erweitert</value>
</data>
<data name="SenderEditor_SelectTemplate" xml:space="preserve">
<value>Vorlage auswählen</value>
</data>
<data name="SenderEditor_Validation_ReminderInterval" xml:space="preserve">
<value>Bitte geben Sie ein Erinnerungsintervall größer als 0 Tage ein.</value>
</data>
<data name="SenderEditor_Validation_FirstReminder" xml:space="preserve">
<value>Bitte geben Sie gültige Tage für die erste Erinnerung ein.</value>
</data>
<data name="SenderEditor_Validation_ExpiryWarning" xml:space="preserve">
<value>Die Ablaufwarnung darf nicht nach dem Ablaufdatum liegen.</value>
</data>
</root> </root>

View File

@@ -105,10 +105,10 @@ Public Class frmEnvelopeMainData
End If End If
End Sub End Sub
Private Function TranslateCertificationType(pType As CertificationType) As String Private Function TranslateCertificationType(pType As CertificationType) As String
Return Resources.Model.ResourceManager.GetString(pType.ToString()) Return CommonServices.My.Resources.Model.ResourceManager.GetString(pType.ToString())
End Function End Function
Private Function TranslateFinalEmailType(pType As FinalEmailType) As String Private Function TranslateFinalEmailType(pType As FinalEmailType) As String
Return Resources.Model.ResourceManager.GetString(pType.ToString()) Return CommonServices.My.Resources.Model.ResourceManager.GetString(pType.ToString())
End Function End Function
Private Sub btOK_Click(sender As Object, e As EventArgs) Handles btOK.Click Private Sub btOK_Click(sender As Object, e As EventArgs) Handles btOK.Click

View File

@@ -0,0 +1,26 @@
using EnvelopeGenerator.Application.Common.Configurations;
using EnvelopeGenerator.Application.Common.Interfaces.Services;
using EnvelopeGenerator.Infrastructure.Crypt.Services;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Options;
namespace EnvelopeGenerator.Infrastructure.Crypt.DependencyInjection;
public static class ServiceCollectionExtensions
{
public static IServiceCollection AddCryptInfrastructure(this IServiceCollection services, IConfiguration configuration)
{
services
.AddOptions<Pkcs11Options>()
.Bind(configuration.GetSection(Pkcs11Options.SectionName))
.ValidateDataAnnotations()
.ValidateOnStart();
services.AddSingleton<IPdfDigitalSignatureService, PdfDigitalSignatureService>();
services.AddSingleton<Pkcs11SelfTestStatusStore>();
services.AddSingleton<IPkcs11SelfTestStatusProvider>(sp => sp.GetRequiredService<Pkcs11SelfTestStatusStore>());
services.AddHostedService<Pkcs11StartupSelfTestHostedService>();
return services;
}
}

View File

@@ -0,0 +1,35 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="DevExpress.Document.Processor" Version="25.2.3" />
<PackageReference Include="Microsoft.Extensions.Configuration.Binder" Version="9.0.6" />
<PackageReference Include="Microsoft.Extensions.Configuration.Abstractions" Version="9.0.6" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="9.0.6" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="9.0.6" />
<PackageReference Include="Microsoft.Extensions.Hosting.Abstractions" Version="9.0.6" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="9.0.6" />
<PackageReference Include="Microsoft.Extensions.Options" Version="9.0.6" />
<PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="9.0.6" />
<PackageReference Include="Microsoft.Extensions.Options.DataAnnotations" Version="9.0.6" />
<PackageReference Include="System.Security.Cryptography.Pkcs" Version="9.0.6" />
<PackageReference Include="Pkcs11Interop" Version="5.3.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\EnvelopeGenerator.Application\EnvelopeGenerator.Application.csproj" />
</ItemGroup>
<ItemGroup>
<None Include="resources\pkcs11\**\*">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
<TargetPath>pkcs11\%(RecursiveDir)%(Filename)%(Extension)</TargetPath>
</None>
</ItemGroup>
</Project>

View File

@@ -0,0 +1,384 @@
# EnvelopeGenerator.Infrastructure.Crypt
Umfassende technische Dokumentation der PKCS#11/SoftHSM-Integration fuer `EnvelopeGenerator`.
Dieses Dokument konsolidiert und ersetzt die verteilten Runbooks aus:
- `pkcs11-proxy-production/README.md`
- `pkcs11-proxy-production/SSH_TEMP_ACCESS_MUST_DO.md`
- aeltere Abschnitte in diesem README
Zielgruppe: Senior Developer, Platform Engineers, DevOps, Security Owner.
---
## 1. Architekturueberblick
### 1.1 Ziel
`EnvelopeGenerator.Infrastructure.Crypt` stellt die kryptographische Infrastruktur fuer PDF-Signaturen bereit:
- Signaturerzeugung mit Schluesseln in SoftHSM/PKCS#11
- Zertifikat-Auslese aus Token
- Signaturpruefung auf PDF-Ebene
- Health/Startup-Selbsttest fuer Betriebsfaehigkeit
### 1.2 Topologie (aktueller Betriebsmodus)
Der aktuell implementierte Produktions-nahe Pfad ist:
1. Linux hostet SoftHSM + `pkcs11-daemon` (Proxy-Server).
2. Windows hostet `EnvelopeGenerator.Server`.
3. Windows laedt ein Windows-kompatibles Proxy-PKCS#11-Modul (`libpkcs11-proxy.dll`).
4. PKCS#11-Operationen werden ueber Socket (`PKCS11_PROXY_SOCKET`) an Linux weitergeleitet.
Wichtig:
- Ein Windows-Prozess kann **kein Linux `.so`** direkt laden.
- Private Keys verbleiben im Token (nicht exportierbar).
### 1.3 Laufzeitpfade in der Anwendung
`Pkcs11InteropBootstrap` loest Assets relativ zu `Crypt:Pkcs11:AssetsRootPath` auf:
- Modul: `pkcs11\windows\proxy\libpkcs11-proxy.dll`
- Tool-Fallback: `pkcs11\windows\opensc\tools\pkcs11-tool.exe`
Wenn `AssetsRootPath` leer ist, wird `AppContext.BaseDirectory` verwendet.
---
## 2. Linux-Seite: SoftHSM + Proxy Setup
### 2.1 Basispakete
Beispiel (Debian/Ubuntu):
```bash
sudo apt-get update && sudo apt-get install -y softhsm2 opensc p11-kit libengine-pkcs11-openssl
```
### 2.2 SoftHSM-Modulpfad pruefen
```bash
ldconfig -p | grep softhsm
find /usr -name "libsofthsm2.so" 2>/dev/null
```
### 2.3 Token initialisieren
```bash
softhsm2-util --show-slots
softhsm2-util --init-token --slot <uninitialized-slot> --label CompanyProdToken --so-pin <so-pin> --pin <user-pin>
softhsm2-util --show-slots
```
Hinweis: Nach `--init-token` wird der Slot i. d. R. neu zugewiesen.
### 2.4 Schluesselpaar erzeugen
```bash
pkcs11-tool --module /usr/lib/softhsm/libsofthsm2.so \
--slot <slot-id> --login --pin <user-pin> \
--keypairgen --key-type rsa:3072 --label company-sign-key-v1 --id 01
```
### 2.5 Zertifikat importieren
```bash
pkcs11-tool --module /usr/lib/softhsm/libsofthsm2.so \
--slot <slot-id> --login --pin <user-pin> \
--write-object ./company-sign-cert-v1.der --type cert --id 01 --label company-sign-cert-v1
```
### 2.6 Objektzustand verifizieren
```bash
pkcs11-tool --module /usr/lib/softhsm/libsofthsm2.so --slot <slot-id> --login --pin <user-pin> --list-objects
pkcs11-tool --module /usr/lib/softhsm/libsofthsm2.so --slot <slot-id> --login --pin <user-pin> --list-objects --type cert
```
### 2.7 Proxy-Daemon endpoint stabilisieren
Ein wiederkehrendes Betriebsproblem war ein zufaelliger/local-only Listener. Fix:
```bash
sudo mkdir -p /etc/systemd/system/pkcs11-proxy.service.d
printf "[Service]\nEnvironment=PKCS11_DAEMON_SOCKET=tcp://0.0.0.0:5657\n" | sudo tee /etc/systemd/system/pkcs11-proxy.service.d/override.conf
sudo systemctl daemon-reload
sudo systemctl restart pkcs11-proxy.service
```
Pruefung:
```bash
systemctl show pkcs11-proxy.service -p Environment --no-pager
ss -ltnp | grep 5657
```
---
## 3. Web-API/Server-Seite: Installation und Asset-Bereitstellung
### 3.1 Bezugsquellen der Windows-Artefakte
Fuer den Proxy-Betrieb werden auf Windows benoetigt:
1. Proxy-PKCS#11-DLL (`libpkcs11-proxy.dll`)
2. Abhaengige Runtime-DLLs (z. B. MinGW runtime, je nach Build)
3. `pkcs11-tool.exe` + zugehoerige OpenSC-DLLs fuer Fallback
Beschaffung:
- Build aus derselben `pkcs11-proxy`-Codebasis/Commit wie Linux-Daemon (Kompatibilitaet sicherstellen)
- oder kontrolliert bereitgestellte, intern freigegebene Binaries
### 3.2 Empfohlene Ablage im Repo
Bundled Assets liegen unter:
- `EnvelopeGenerator.Infrastructure.Crypt/resources/pkcs11/windows/proxy/`
- `EnvelopeGenerator.Infrastructure.Crypt/resources/pkcs11/windows/opensc/tools/`
- `EnvelopeGenerator.Infrastructure.Crypt/resources/pkcs11/windows/opensc/pkcs11/`
Diese werden beim Build in den Output kopiert (siehe `.csproj`-Copy-Regeln).
### 3.3 Deployment-Muster
Es gibt zwei gueltige Wege:
1. **Bundled (Dev/QA, schnelle Reproduzierbarkeit)**
- Assets werden mit dem Build ausgeliefert.
- `AssetsRootPath = null` -> Aufloesung via `AppContext.BaseDirectory`.
2. **Zentraler Asset-Root (Prod, betriebliche Kontrolle)**
- Assets in zentralem Pfad (z. B. `E:\DataFiles\Digital Data\EnvelopeGenerator`).
- `AssetsRootPath` in `appsettings.json` auf diesen Root setzen.
### 3.4 Anwendungskonfiguration (`Crypt:Pkcs11`)
Beispiel:
```json
{
"Crypt": {
"Pkcs11": {
"AssetsRootPath": "E:\\DataFiles\\Digital Data\\EnvelopeGenerator",
"SlotId": 2021549410,
"TokenLabel": "CompanyProdToken",
"ProxySocket": "tcp://172.24.12.64:5657",
"UserPin": "<secret>",
"PrivateKeyLabel": "company-sign-key-v1",
"CertificateLabel": "company-sign-cert-v1",
"ApplicationName": "signFLOW",
"DefaultReason": null,
"UseUtcSigningTime": true,
"DefaultCertificationLevel": "NoCertification"
}
}
}
```
Sicherheitsregel:
- `UserPin` niemals in versionierte Dateien einchecken.
- Secrets nur in Secret Store / nicht versionierte `appsettings.Secrets.json` / Vault.
---
## 4. Implementierte Services, Modelle, DTOs
### 4.1 DI und Startverhalten
- `AddCryptInfrastructure(...)` in `DependencyInjection/ServiceCollectionExtensions.cs`
- bindet `Pkcs11Options`
- registriert `IPdfDigitalSignatureService`
- registriert Startup-Self-Test Hosted Service
### 4.2 Konfigurationsmodell
- `Pkcs11Options` (`EnvelopeGenerator.Application/Common/Configurations/Pkcs11Options.cs`)
- `AssetsRootPath`, `SlotId`, `TokenLabel`, `ProxySocket`
- `UserPin`, `PrivateKeyLabel`, `CertificateLabel`
- `ApplicationName`, `DefaultReason`, `UseUtcSigningTime`, `DefaultCertificationLevel`
- `ResolvedLibraryPath`, `ResolvedToolPath` (Runtime-resolved)
### 4.3 Kernservices
1. `PdfDigitalSignatureService`
- Signiert PDF via DevExpress `PdfDeferredSignatureBuilder`
- Nutzt `Pkcs11ExternalSigner` fuer externe Signatur
- Erzwingt `ApplicationName` aus Config (nicht client-overridable)
- Erweitert `Reason` um strukturiertes Metaformat:
- `SFMETA:v1;doc=<uuid>;sha256=<hash>`
- Parse beim Verify und Mapping in DTO
2. `Pkcs11InteropBootstrap`
- Loest Modul-/Toolpfade auf
- Setzt `PKCS11_PROXY_SOCKET`/`PKCS11_DAEMON_SOCKET`
- PATH-Ergaenzung fuer native Abhaengigkeiten
- Warmup via `pkcs11-tool -L`
3. `Pkcs11SessionRunner`
- Interop Library-Load mit mehreren Init-Modi (Fallback-Reihenfolge)
- Slot-Resolution (`SlotId`/`TokenLabel`)
- Session Login/Logout
4. `Pkcs11ToolBridge`
- Fallback via Prozessaufruf von `pkcs11-tool`
- Cert read und DigestInfo-Signatur
5. `Pkcs11StartupSelfTestHostedService`
- Fuehrt beim Start Interop-Probe aus
- Fallback-Probe bei Interop-Fehler
- Schreibt strukturierten Status
### 4.4 Wichtige Interfaces/DTOs
- `IPdfDigitalSignatureService`
- `SignPdfAsync(...)`, `CheckPdfSignatureAsync(...)`, `ExtractOriginalPdfAsync(...)`
- `IPkcs11SelfTestStatusProvider`
- `PdfSignOptionsDto`
- `UUID`, `Reason`, `Name`, `Location`, `Email`, `Phone`, `CertificationLevel`
- `PdfSignatureCheckResultDto` / `PdfSignatureCheckItemDto`
- inklusive `BusinessReason`, `UUID`, `OriginalDocumentSha256`
- `Pkcs11SelfTestStatusDto`
---
## 5. Betriebserfahrungen und Challenges
### 5.1 Interop vs Tool-Verhalten
Beobachtetes Muster in der realen Umgebung:
- `pkcs11-tool` konnte erfolgreich auf Token zugreifen und signieren.
- `Pkcs11Interop` scheiterte mit `CKR_FUNCTION_NOT_SUPPORTED` bzw. fehlendem `C_Initialize` Pointer in bestimmten Modi.
Konsequenz:
- Architektur wurde auf **interop-first + controlled tool-fallback** erweitert.
- Health-Endpunkt differenziert Modus (`interop`, `pkcs11-tool`, `failed`).
### 5.2 Typische Fehlbilder
- `CKR_DEVICE_ERROR` bei Socket-/Proxy-Problemen
- `CRYPT_PROVIDER_UNAVAILABLE` bei Pfad/ABI/Dependency-Mismatch
- `CRYPT_SLOT_NOT_FOUND` bei Slot-/Label-Mismatch
- `CKR_PIN_INCORRECT` bei PIN-Fehler
- 307 Redirects bei HTTP/HTTPS-Mix in manuellen Tests
### 5.3 Plattformfallen
- MSVC vs MinGW Build-Unterschiede fuer Proxy-Client
- fehlende Laufzeit-DLLs (`PATH`/Side-by-side)
- Architektur-Mismatch x86 vs x64
- Daemon-Bindings nicht stabil (random localhost port statt fixed endpoint)
---
## 6. Health, Monitoring und Verifikation
### 6.1 API Health
- Endpoint: `GET /api/health/crypt`
- Liefert:
- `success`, `mode`, `summary`, `interopError`, `toolError`, `checkedAtUtc`
Empfehlung:
- In Monitoring aufnehmen und bei `mode=pkcs11-tool` ueber laengere Zeit Warnung triggern.
### 6.2 Smoke-Test (empfohlen vor Release)
1. `GET /api/health/crypt` -> `success=true`
2. `POST /api/PdfSignature/sign` mit Test-PDF
3. `POST /api/PdfSignature/is-signed`
4. Pruefen:
- `signed=true`
- `allSignaturesCryptographicallyValid=true`
- `UUID`/`OriginalDocumentSha256` korrekt gemappt
---
## 7. Sicherheits- und Betriebsrichtlinien
### 7.1 Geheimnisse
- PIN, SO-PIN, Root-Creds niemals in Doku/Screenshots/Repo.
- Nach Troubleshooting: Credentials rotieren.
### 7.2 Temporare SSH-Freigaben zwingend rueckbauen
Wenn SSH temporaer geoeffnet wurde, MUSS danach Rollback erfolgen:
```bash
sudo systemctl disable --now ssh && sudo ufw delete allow from 172.24.10.11 to any port 22 proto tcp && sudo ufw status verbose && sudo systemctl status ssh --no-pager
```
Optional harte Bereinigung:
```bash
sudo apt-get purge -y openssh-server && sudo apt-get autoremove -y
```
### 7.3 Schluesselrotation
- Neue Labels (`...-v2`) anlegen
- App umkonfigurieren
- Sign/Verify Regression testen
- Altmaterial erst nach Freigabe entfernen
---
## 8. API-Verhalten bei Signaturmetadaten
Aktueller Standard:
- `UUID` kommt aus Sign-Input (nullable string). Wenn ungeltig/leer -> neue Guid wird erzeugt.
- `Reason` wird intern angereichert mit strukturiertem Meta (`SFMETA:v1`).
- `ApplicationName` ist rein serverseitig aus `appsettings` gesetzt.
- `SigningTime` ist rein serverseitig und wird automatisch gesetzt (`UseUtcSigningTime=true` => `UtcNow`, sonst lokale Zeit).
- `CertificationLevel` wird im Controller serverseitig gesetzt (`FormFillingAndAnnotations`), nicht vom Client.
Damit ist das Verhalten deterministisch und manipulationsaermer fuer Integrationsclients.
---
## 9. Troubleshooting-Checkliste (praxisnah)
1. Erreichbarkeit Linux Proxy:
- `Test-NetConnection <linux-host> -Port 5657`
2. Token sichtbar?
- `pkcs11-tool --module <dll> -L -v`
3. Zertifikat lesbar?
- `--read-object --type cert --label <cert-label>`
4. Signatur technisch moeglich?
- `--sign -m SHA256-RSA-PKCS ...`
5. App-Health check:
- `/api/health/crypt`
6. App-sign/verify end-to-end:
- `/api/PdfSignature/sign` + `/api/PdfSignature/is-signed`
Wenn Interop scheitert, aber Tool funktioniert:
- Betrieb bleibt verfuegbar (Fallback),
- aber Incident/Bug fuer Interop-Kompatibilitaet erfassen.
---
## 10. Ausblick / empfohlene Verbesserungen
1. Binary Transport statt Base64 bei grossen PDFs in Render/Sign-Pipelines.
2. Persistente Metriken fuer Fallback-Quote (`interop` vs `tool`).
3. Zertifikatskette/OCSP/CRL Validierung als optionales Policy-Modul.
4. CI-Pruefung auf unsichere SQL-Muster (parallel zum Security-Workstream).
5. Standardisierte Toast/UX-Rueckmeldungen fuer Signierfehler in UI.
---
## 11. Referenzen
- SoftHSMv2: `https://github.com/softhsm/SoftHSMv2`
- OpenSC / pkcs11-tool: `https://github.com/OpenSC/OpenSC/wiki/Using-pkcs11-tool-and-OpenSSL`
- PKCS#11 Standard: `https://www.oasis-open.org/committees/pkcs11/`

View File

@@ -0,0 +1,617 @@
using EnvelopeGenerator.Application.Common.Configurations;
using EnvelopeGenerator.Application.Common.Dto;
using EnvelopeGenerator.Application.Common.Enums;
using EnvelopeGenerator.Application.Common.Interfaces.Services;
using DevExpress.Office.DigitalSignatures;
using DevExpress.Pdf;
using Microsoft.Extensions.Options;
using System.Formats.Asn1;
using System.Security.Cryptography.Pkcs;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Text.RegularExpressions;
namespace EnvelopeGenerator.Infrastructure.Crypt.Services;
public sealed class PdfDigitalSignatureService(IOptions<Pkcs11Options> options) : IPdfDigitalSignatureService
{
private static readonly Regex SignatureReasonMetaRegex = new(@"\|\s*SFMETA:v1;doc=(?<doc>[0-9a-fA-F-]{36});sha256=(?<sha>[A-Fa-f0-9]{64})$", RegexOptions.CultureInvariant | RegexOptions.Compiled);
public async Task SignPdfAsync(Stream inputPdf, Stream outputPdf, PdfSignOptionsDto? optionsModel = null, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(inputPdf);
ArgumentNullException.ThrowIfNull(outputPdf);
cancellationToken.ThrowIfCancellationRequested();
var (workingInput, ownsWorkingInput) = await EnsureSeekableInputAsync(inputPdf, cancellationToken);
try
{
workingInput.Position = 0;
var sourceHashHex = Convert.ToHexString(await SHA256.HashDataAsync(workingInput, cancellationToken));
workingInput.Position = 0;
var pkcs11Options = options.Value;
var request = optionsModel ?? new PdfSignOptionsDto();
var uuid = ResolveUuid(request.UUID);
var reasonWithMeta = BuildReasonWithMeta(request.Reason ?? pkcs11Options.DefaultReason, uuid, sourceHashHex);
using var signer = new PdfDocumentSigner(workingInput);
var digestCalculator = new DigestCalculator(HashAlgorithmType.SHA256);
var signerInfo = new ExternalSignerInfo(PdfSignatureType.Pkcs7, 32768, digestCalculator);
var signatureFieldInfo = new PdfSignatureFieldInfo(1)
{
Name = $"Sig_{DateTimeOffset.UtcNow:yyyyMMddHHmmss}"
};
var builder = new PdfDeferredSignatureBuilder(signerInfo, signatureFieldInfo)
{
Name = request.Name ?? pkcs11Options.CertificateLabel,
Reason = reasonWithMeta,
Location = request.Location,
ContactInfo = BuildContactInfo(request.Email, request.Phone),
SigningTime = pkcs11Options.UseUtcSigningTime ? DateTimeOffset.UtcNow : DateTimeOffset.Now,
ApplicationName = pkcs11Options.ApplicationName,
CertificationLevel = ToDevExpressCertificationLevel(request.CertificationLevel)
?? ToDevExpressCertificationLevel(pkcs11Options.DefaultCertificationLevel)
?? PdfCertificationLevel.NoCertification
};
var deferredSigner = signer.SignDeferred(builder);
var externalSigner = new Pkcs11ExternalSigner(pkcs11Options);
deferredSigner.Sign(outputPdf, externalSigner.BuildSignature(deferredSigner.HashValue, digestCalculator.AlgorithmOid));
}
finally
{
if (ownsWorkingInput)
await workingInput.DisposeAsync();
}
}
public async Task SignPdfAsync(Stream inputPdf, Stream outputPdf, IReadOnlyList<PdfSignOptionsDto> optionsList, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(inputPdf);
ArgumentNullException.ThrowIfNull(outputPdf);
ArgumentNullException.ThrowIfNull(optionsList);
cancellationToken.ThrowIfCancellationRequested();
if (optionsList.Count == 0)
{
await inputPdf.CopyToAsync(outputPdf, cancellationToken);
return;
}
var (currentInput, ownsCurrentInput) = await EnsureSeekableInputAsync(inputPdf, cancellationToken);
try
{
for (var i = 0; i < optionsList.Count; i++)
{
cancellationToken.ThrowIfCancellationRequested();
var isLast = i == optionsList.Count - 1;
if (isLast)
{
await SignPdfAsync(currentInput, outputPdf, optionsList[i], cancellationToken);
continue;
}
var intermediateOutput = new MemoryStream();
await SignPdfAsync(currentInput, intermediateOutput, optionsList[i], cancellationToken);
if (ownsCurrentInput)
await currentInput.DisposeAsync();
intermediateOutput.Position = 0;
currentInput = intermediateOutput;
ownsCurrentInput = true;
}
}
finally
{
if (ownsCurrentInput)
await currentInput.DisposeAsync();
}
}
public async Task<PdfSignatureCheckResultDto> CheckPdfSignatureAsync(Stream inputPdf, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(inputPdf);
cancellationToken.ThrowIfCancellationRequested();
var pdfBytes = await ReadAllBytesAsync(inputPdf, cancellationToken);
using var pdfStream = new MemoryStream(pdfBytes);
using var signer = new PdfDocumentSigner(pdfStream);
var signatures = signer.GetSignatureInfo();
var byteRanges = ParseByteRanges(pdfBytes);
if (signatures is null || signatures.Count == 0)
{
return new PdfSignatureCheckResultDto(
Signed: false,
Signatures: []);
}
var items = new List<PdfSignatureCheckItemDto>(signatures.Count);
for (var i = 0; i < signatures.Count; i++)
{
var signature = signatures[i];
try
{
var pkcs7 = signer.GetPdfPkcs7Signature(signature.FieldName);
bool valid = pkcs7.VerifySignature();
var byteRange = i < byteRanges.Count ? byteRanges[i] : null;
var coversWholeDocument = CoversWholeDocument(byteRange, pdfBytes.LongLength);
var certificate = pkcs7.GetSignatureCertificate();
var issuedTo = ParsePrincipal(certificate?.Subject);
var issuedBy = ParsePrincipal(certificate?.Issuer);
var reasonMeta = ParseReasonMeta(signature.Reason);
var contact = ParseContactInfo(signature.ContactInfo);
items.Add(new PdfSignatureCheckItemDto(
CoversWholeDoc: coversWholeDocument,
Reason: signature.Reason,
BusinessReason: reasonMeta.BusinessReason,
Location: signature.Location,
DeclaredName: signature.SignerName,
ContactInfo: signature.ContactInfo,
Email: contact.Email,
Phone: contact.Phone,
DigestAlgorithm: InferDigestAlgorithm(certificate),
SignatureAlgorithm: InferSignatureAlgorithm(certificate),
SignerName: issuedTo.CommonName ?? signature.SignerName,
Issuer: issuedBy.Full,
SerialNumber: ToColonSerial(certificate?.SerialNumber),
ValidFrom: certificate is null ? null : new DateTimeOffset(certificate.NotBefore).ToUniversalTime(),
ValidTo: certificate is null ? null : new DateTimeOffset(certificate.NotAfter).ToUniversalTime(),
ExpiryCheckedAgainst: "now",
Certificates: [BuildCertificateInfo(certificate, DateTimeOffset.UtcNow)],
Unchanged: valid && coversWholeDocument,
FieldName: signature.FieldName,
IsCryptographicallyValid: valid,
SigningTime: signature.SigningTime?.ToUniversalTime().ToString("O"),
Filter: signature.Filter,
SubFilter: signature.SubFilter,
ApplicationName: null,
UUID: reasonMeta.UUID,
OriginalDocumentSha256: reasonMeta.OriginalDocumentSha256,
MessageDigestHex: TryExtractMessageDigestHex(signature.Contents),
Error: null));
}
catch (Exception ex)
{
var reasonMeta = ParseReasonMeta(signature.Reason);
var contact = ParseContactInfo(signature.ContactInfo);
items.Add(new PdfSignatureCheckItemDto(
CoversWholeDoc: false,
Reason: signature.Reason,
BusinessReason: reasonMeta.BusinessReason,
Location: signature.Location,
DeclaredName: signature.SignerName,
ContactInfo: signature.ContactInfo,
Email: contact.Email,
Phone: contact.Phone,
DigestAlgorithm: null,
SignatureAlgorithm: null,
SignerName: signature.SignerName,
Issuer: null,
SerialNumber: null,
ValidFrom: null,
ValidTo: null,
ExpiryCheckedAgainst: "now",
Certificates: [],
Unchanged: false,
FieldName: signature.FieldName,
IsCryptographicallyValid: false,
SigningTime: signature.SigningTime?.ToUniversalTime().ToString("O"),
Filter: signature.Filter,
SubFilter: signature.SubFilter,
ApplicationName: null,
UUID: reasonMeta.UUID,
OriginalDocumentSha256: reasonMeta.OriginalDocumentSha256,
MessageDigestHex: null,
Error: ex.Message));
}
}
return new PdfSignatureCheckResultDto(
Signed: true,
Signatures: items);
}
public async Task ExtractOriginalPdfAsync(Stream inputPdf, Stream outputPdf, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(inputPdf);
ArgumentNullException.ThrowIfNull(outputPdf);
cancellationToken.ThrowIfCancellationRequested();
var pdfBytes = await ReadAllBytesAsync(inputPdf, cancellationToken);
var byteRanges = ParseByteRanges(pdfBytes);
if (byteRanges.Count == 0)
{
await outputPdf.WriteAsync(pdfBytes, cancellationToken);
return;
}
var revisionLength = byteRanges
.Select(GetSignedRevisionLength)
.Where(x => x > 0)
.DefaultIfEmpty(pdfBytes.LongLength)
.Min();
if (revisionLength > pdfBytes.LongLength)
throw new InvalidOperationException("Invalid ByteRange in signed PDF.");
await outputPdf.WriteAsync(pdfBytes.AsMemory(0, (int)revisionLength), cancellationToken);
}
private static async Task<(Stream Stream, bool OwnsStream)> EnsureSeekableInputAsync(Stream input, CancellationToken cancellationToken)
{
if (input.CanSeek)
{
input.Position = 0;
return (input, false);
}
var buffered = new MemoryStream();
await input.CopyToAsync(buffered, cancellationToken);
buffered.Position = 0;
return (buffered, true);
}
private static async Task<byte[]> ReadAllBytesAsync(Stream input, CancellationToken cancellationToken)
{
if (input is MemoryStream memory && memory.TryGetBuffer(out var buffer))
return buffer.AsSpan(0, (int)memory.Length).ToArray();
if (input.CanSeek)
input.Position = 0;
using var ms = new MemoryStream();
await input.CopyToAsync(ms, cancellationToken);
return ms.ToArray();
}
private static PdfSignatureCertificateInfoDto BuildCertificateInfo(X509Certificate2? certificate, DateTimeOffset now)
{
if (certificate is null)
{
return new PdfSignatureCertificateInfoDto(
IssuedTo: new PdfSignaturePrincipalDto(null, null, null, null),
IssuedBy: new PdfSignaturePrincipalDto(null, null, null, null),
SerialNumber: null,
ValidFrom: null,
ValidTo: null,
SelfSigned: false,
Expired: false,
NotYetValid: false,
IsSigner: true,
Version: null,
KeyAlgorithm: null,
SignatureAlgorithm: null,
Pem: null,
KeySizeBits: null);
}
var issuedTo = ParsePrincipal(certificate.Subject);
var issuedBy = ParsePrincipal(certificate.Issuer);
var validFrom = new DateTimeOffset(certificate.NotBefore).ToUniversalTime();
var validTo = new DateTimeOffset(certificate.NotAfter).ToUniversalTime();
return new PdfSignatureCertificateInfoDto(
IssuedTo: issuedTo,
IssuedBy: issuedBy,
SerialNumber: ToColonSerial(certificate.SerialNumber),
ValidFrom: validFrom,
ValidTo: validTo,
SelfSigned: string.Equals(certificate.Subject, certificate.Issuer, StringComparison.OrdinalIgnoreCase),
Expired: validTo < now,
NotYetValid: validFrom > now,
IsSigner: true,
Version: certificate.Version,
KeyAlgorithm: certificate.PublicKey.Oid?.FriendlyName ?? certificate.PublicKey.Oid?.Value,
SignatureAlgorithm: certificate.SignatureAlgorithm.FriendlyName ?? certificate.SignatureAlgorithm.Value,
Pem: ToPem(certificate.RawData),
KeySizeBits: TryGetKeySize(certificate));
}
private static int? TryGetKeySize(X509Certificate2 certificate)
{
try
{
return certificate.PublicKey.Key.KeySize;
}
catch
{
return null;
}
}
private static string? InferDigestAlgorithm(X509Certificate2? certificate)
{
if (certificate?.SignatureAlgorithm is null)
return null;
var source = (certificate.SignatureAlgorithm.FriendlyName ?? certificate.SignatureAlgorithm.Value ?? string.Empty).ToUpperInvariant();
if (source.Contains("SHA512", StringComparison.Ordinal)) return "SHA-512";
if (source.Contains("SHA384", StringComparison.Ordinal)) return "SHA-384";
if (source.Contains("SHA256", StringComparison.Ordinal)) return "SHA-256";
if (source.Contains("SHA1", StringComparison.Ordinal)) return "SHA-1";
return certificate.SignatureAlgorithm.FriendlyName ?? certificate.SignatureAlgorithm.Value;
}
private static string? InferSignatureAlgorithm(X509Certificate2? certificate)
{
var oidName = certificate?.PublicKey.Oid?.FriendlyName?.ToUpperInvariant();
if (oidName is not null && oidName.Contains("RSA", StringComparison.Ordinal))
return "RSA";
if (oidName is not null && oidName.Contains("ECDSA", StringComparison.Ordinal))
return "ECDSA";
return certificate?.PublicKey.Oid?.FriendlyName ?? certificate?.PublicKey.Oid?.Value;
}
private static PdfSignaturePrincipalDto ParsePrincipal(string? dn)
{
if (string.IsNullOrWhiteSpace(dn))
return new PdfSignaturePrincipalDto(null, null, null, dn);
string? commonName = null;
string? organization = null;
string? country = null;
foreach (var part in dn.Split(',', StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries))
{
var equalsIndex = part.IndexOf('=');
if (equalsIndex <= 0 || equalsIndex >= part.Length - 1)
continue;
var key = part[..equalsIndex].Trim();
var value = part[(equalsIndex + 1)..].Trim();
if (key.Equals("CN", StringComparison.OrdinalIgnoreCase)) commonName = value;
else if (key.Equals("O", StringComparison.OrdinalIgnoreCase)) organization = value;
else if (key.Equals("C", StringComparison.OrdinalIgnoreCase)) country = value;
}
return new PdfSignaturePrincipalDto(commonName, organization, country, dn);
}
private static PdfCertificationLevel? ToDevExpressCertificationLevel(PdfSignatureCertificationLevel? value)
{
return value is null ? null : (PdfCertificationLevel)(int)value.Value;
}
private static string? ToColonSerial(string? raw)
{
if (string.IsNullOrWhiteSpace(raw))
return null;
var normalized = raw.Replace(":", string.Empty, StringComparison.Ordinal).Trim();
if (normalized.Length % 2 != 0)
return normalized;
return string.Join(':', Enumerable.Range(0, normalized.Length / 2).Select(i => normalized.Substring(i * 2, 2).ToUpperInvariant()));
}
private static string ToPem(byte[] der)
{
var base64 = Convert.ToBase64String(der, Base64FormattingOptions.InsertLineBreaks);
var sb = new StringBuilder();
sb.AppendLine("-----BEGIN CERTIFICATE-----");
sb.AppendLine(base64);
sb.Append("-----END CERTIFICATE-----");
return sb.ToString();
}
private static string? TryExtractMessageDigestHex(byte[]? signatureContents)
{
if (signatureContents is null || signatureContents.Length == 0)
return null;
try
{
var cms = new SignedCms();
cms.Decode(signatureContents);
var signerInfo = cms.SignerInfos.Count > 0 ? cms.SignerInfos[0] : null;
if (signerInfo is null)
return null;
foreach (CryptographicAttributeObject attr in signerInfo.SignedAttributes)
{
if (!string.Equals(attr.Oid?.Value, "1.2.840.113549.1.9.4", StringComparison.Ordinal))
continue;
foreach (var value in attr.Values)
{
var octets = TryReadOctetString(value.RawData);
if (octets is not null && octets.Length > 0)
return Convert.ToHexString(octets);
}
}
}
catch
{
return null;
}
return null;
}
private static byte[]? TryReadOctetString(byte[] rawData)
{
try
{
var reader = new AsnReader(rawData, AsnEncodingRules.BER);
var octets = reader.ReadOctetString();
if (reader.HasData)
return null;
return octets;
}
catch
{
return null;
}
}
private static List<long[]> ParseByteRanges(byte[] pdfBytes)
{
var text = Encoding.Latin1.GetString(pdfBytes);
var matches = Regex.Matches(text, @"/ByteRange\s*\[(?<values>[\d\s]+)\]", RegexOptions.CultureInvariant);
var ranges = new List<long[]>(matches.Count);
foreach (Match match in matches)
{
var raw = match.Groups["values"].Value;
var parts = raw.Split((char[]?)null, StringSplitOptions.RemoveEmptyEntries);
var values = new long[parts.Length];
var ok = true;
for (var i = 0; i < parts.Length; i++)
{
if (!long.TryParse(parts[i], out values[i]))
{
ok = false;
break;
}
}
if (ok && values.Length >= 4 && values.Length % 2 == 0)
ranges.Add(values);
}
return ranges;
}
private static bool CoversWholeDocument(long[]? byteRange, long fileLength)
{
if (byteRange is null || byteRange.Length < 4 || byteRange.Length % 2 != 0)
return false;
if (byteRange[0] != 0)
return false;
long previousEnd = -1;
for (var i = 0; i < byteRange.Length; i += 2)
{
var start = byteRange[i];
var length = byteRange[i + 1];
if (start < 0 || length < 0)
return false;
var end = start + length;
if (previousEnd > start)
return false;
previousEnd = end;
}
return previousEnd == fileLength;
}
private static long GetSignedRevisionLength(long[] byteRange)
{
if (byteRange.Length < 2)
return -1;
var start = byteRange[^2];
var length = byteRange[^1];
if (start < 0 || length < 0)
return -1;
return start + length;
}
private static string ResolveUuid(string? uuid)
{
return Guid.TryParse(uuid, out var parsed)
? parsed.ToString()
: Guid.NewGuid().ToString();
}
private static string BuildReasonWithMeta(string? businessReason, string uuid, string sourceHashHex)
{
var trimmedReason = string.IsNullOrWhiteSpace(businessReason) ? null : businessReason.Trim();
var prefix = string.IsNullOrWhiteSpace(trimmedReason) ? string.Empty : trimmedReason + " ";
return $"{prefix}| SFMETA:v1;doc={uuid};sha256={sourceHashHex}";
}
private static string? BuildContactInfo(string? email, string? phone)
{
var normalizedEmail = string.IsNullOrWhiteSpace(email) ? null : email.Trim();
var normalizedPhone = string.IsNullOrWhiteSpace(phone) ? null : phone.Trim();
if (normalizedEmail is null && normalizedPhone is null)
return null;
if (normalizedEmail is null)
return $"tel:{normalizedPhone}";
if (normalizedPhone is null)
return $"mailto:{normalizedEmail}";
return $"mailto:{normalizedEmail};tel:{normalizedPhone}";
}
private static (string? Email, string? Phone) ParseContactInfo(string? contactInfo)
{
if (string.IsNullOrWhiteSpace(contactInfo))
return (null, null);
string? email = null;
string? phone = null;
foreach (var part in contactInfo.Split(';', StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries))
{
if (part.StartsWith("mailto:", StringComparison.OrdinalIgnoreCase))
{
email = part[7..].Trim();
continue;
}
if (part.StartsWith("tel:", StringComparison.OrdinalIgnoreCase))
{
phone = part[4..].Trim();
continue;
}
if (email is null && part.Contains('@', StringComparison.Ordinal))
{
email = part.Trim();
continue;
}
if (phone is null)
phone = part.Trim();
}
return (
string.IsNullOrWhiteSpace(email) ? null : email,
string.IsNullOrWhiteSpace(phone) ? null : phone);
}
private static (string? BusinessReason, string? UUID, string? OriginalDocumentSha256) ParseReasonMeta(string? reason)
{
if (string.IsNullOrWhiteSpace(reason))
return (reason, null, null);
var match = SignatureReasonMetaRegex.Match(reason);
if (!match.Success)
return (reason, null, null);
var businessReason = reason[..match.Index].Trim();
if (string.IsNullOrWhiteSpace(businessReason))
businessReason = null;
return (
businessReason,
match.Groups["doc"].Value,
match.Groups["sha"].Value.ToUpperInvariant());
}
}

View File

@@ -0,0 +1,43 @@
using System.Security.Cryptography;
namespace EnvelopeGenerator.Infrastructure.Crypt.Services;
internal static class Pkcs11DigestInfoBuilder
{
public static byte[] Build(byte[] hash, HashAlgorithmName hashAlgorithm)
{
byte[] prefix = hashAlgorithm.Name switch
{
"SHA256" =>
[
0x30, 0x31,
0x30, 0x0d,
0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01,
0x05, 0x00,
0x04, 0x20
],
"SHA384" =>
[
0x30, 0x41,
0x30, 0x0d,
0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x02,
0x05, 0x00,
0x04, 0x30
],
"SHA512" =>
[
0x30, 0x51,
0x30, 0x0d,
0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x03,
0x05, 0x00,
0x04, 0x40
],
_ => throw new NotSupportedException($"Hash algorithm '{hashAlgorithm.Name}' is not supported.")
};
var digestInfo = new byte[prefix.Length + hash.Length];
Buffer.BlockCopy(prefix, 0, digestInfo, 0, prefix.Length);
Buffer.BlockCopy(hash, 0, digestInfo, prefix.Length, hash.Length);
return digestInfo;
}
}

View File

@@ -0,0 +1,49 @@
using EnvelopeGenerator.Application.Common.Configurations;
using DevExpress.Office.DigitalSignatures;
using DevExpress.Pdf;
namespace EnvelopeGenerator.Infrastructure.Crypt.Services;
internal sealed class Pkcs11ExternalSigner(Pkcs11Options options) : Pkcs7SignerBase
{
private readonly Pkcs11PdfSigningRsa rsa = new(options);
private readonly DigestCalculator digestCalculator = new(HashAlgorithmType.SHA256);
private readonly IReadOnlyList<byte[]> certificates = [ReadCertificateBytesWithFallback(options)];
protected override IDigestCalculator DigestCalculator => digestCalculator;
protected override string SigningAlgorithmOID => "1.2.840.113549.1.1.1";
protected override IEnumerable<byte[]> GetCertificates() => certificates;
protected override byte[] SignDigest(byte[] digest)
{
return rsa.SignHash(digest, System.Security.Cryptography.HashAlgorithmName.SHA256, System.Security.Cryptography.RSASignaturePadding.Pkcs1);
}
private static byte[] ReadCertificateBytesWithFallback(Pkcs11Options options)
{
try
{
return Pkcs11SessionRunner.Run(options, session =>
{
var attrs = new List<Net.Pkcs11Interop.HighLevelAPI.IObjectAttribute>
{
session.Factories.ObjectAttributeFactory.Create(Net.Pkcs11Interop.Common.CKA.CKA_CLASS, Net.Pkcs11Interop.Common.CKO.CKO_CERTIFICATE),
session.Factories.ObjectAttributeFactory.Create(Net.Pkcs11Interop.Common.CKA.CKA_LABEL, options.CertificateLabel)
};
var handles = session.FindAllObjects(attrs);
if (handles.Count == 0)
throw new InvalidOperationException($"Certificate '{options.CertificateLabel}' not found in token.");
var values = session.GetAttributeValue(handles[0], new List<Net.Pkcs11Interop.Common.CKA> { Net.Pkcs11Interop.Common.CKA.CKA_VALUE });
return values[0].GetValueAsByteArray();
});
}
catch when (Pkcs11ToolBridge.IsAvailable(options))
{
return Pkcs11ToolBridge.ReadCertificateBytes(options);
}
}
}

View File

@@ -0,0 +1,119 @@
using EnvelopeGenerator.Application.Common.Configurations;
namespace EnvelopeGenerator.Infrastructure.Crypt.Services;
internal static class Pkcs11InteropBootstrap
{
private static readonly object Sync = new();
private static bool Initialized;
private const string ProxyRelativePath = "pkcs11\\windows\\proxy\\libpkcs11-proxy.dll";
private const string ToolRelativePath = "pkcs11\\windows\\opensc\\tools\\pkcs11-tool.exe";
public static void EnsureLoaded(Pkcs11Options options)
{
if (Initialized)
return;
lock (Sync)
{
if (Initialized)
return;
var libraryPath = ResolveLibraryPath(options);
var toolPath = ResolveToolPath(options);
options.SetResolvedPaths(libraryPath, toolPath);
EnsureNativeDependencySearchPath(options.ResolvedLibraryPath);
if (!string.IsNullOrWhiteSpace(options.ProxySocket))
{
Environment.SetEnvironmentVariable("PKCS11_PROXY_SOCKET", options.ProxySocket);
Environment.SetEnvironmentVariable("PKCS11_DAEMON_SOCKET", options.ProxySocket);
}
if (!string.IsNullOrWhiteSpace(options.ResolvedToolPath))
{
var toolDir = Path.GetDirectoryName(options.ResolvedToolPath);
if (!string.IsNullOrWhiteSpace(toolDir))
EnsurePathContains(toolDir);
}
WarmupWithPkcs11Tool(options);
Initialized = true;
}
}
private static string ResolveLibraryPath(Pkcs11Options options)
{
var assetsRoot = string.IsNullOrWhiteSpace(options.AssetsRootPath)
? AppContext.BaseDirectory
: options.AssetsRootPath;
var resolved = Path.Combine(assetsRoot, ProxyRelativePath);
if (File.Exists(resolved))
return resolved;
throw new FileNotFoundException($"PKCS#11 proxy module not found. Checked path: {resolved}", resolved);
}
private static string? ResolveToolPath(Pkcs11Options options)
{
var assetsRoot = string.IsNullOrWhiteSpace(options.AssetsRootPath)
? AppContext.BaseDirectory
: options.AssetsRootPath;
var resolved = Path.Combine(assetsRoot, ToolRelativePath);
if (File.Exists(resolved))
return resolved;
return null;
}
private static void WarmupWithPkcs11Tool(Pkcs11Options options)
{
if (string.IsNullOrWhiteSpace(options.ResolvedToolPath))
return;
if (!File.Exists(options.ResolvedToolPath))
return;
var process = new System.Diagnostics.Process
{
StartInfo = new System.Diagnostics.ProcessStartInfo
{
FileName = options.ResolvedToolPath,
Arguments = $"--module \"{options.ResolvedLibraryPath}\" -L",
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardError = true,
CreateNoWindow = true
}
};
process.Start();
process.WaitForExit(15000);
}
private static void EnsureNativeDependencySearchPath(string libraryPath)
{
var directory = Path.GetDirectoryName(libraryPath);
if (string.IsNullOrWhiteSpace(directory))
return;
EnsurePathContains(directory);
}
private static void EnsurePathContains(string directory)
{
var currentPath = Environment.GetEnvironmentVariable("PATH") ?? string.Empty;
var entries = currentPath.Split(';', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
if (entries.Any(p => string.Equals(p, directory, StringComparison.OrdinalIgnoreCase)))
return;
var updatedPath = string.IsNullOrWhiteSpace(currentPath)
? directory
: directory + ";" + currentPath;
Environment.SetEnvironmentVariable("PATH", updatedPath);
}
}

View File

@@ -0,0 +1,64 @@
using EnvelopeGenerator.Application.Common.Configurations;
using Net.Pkcs11Interop.Common;
using Net.Pkcs11Interop.HighLevelAPI;
using System.Security.Cryptography;
namespace EnvelopeGenerator.Infrastructure.Crypt.Services;
internal sealed class Pkcs11PdfSigningRsa(Pkcs11Options options) : RSA
{
public override int KeySize
{
get => KeySizeValue;
set => KeySizeValue = value;
}
public override KeySizes[] LegalKeySizes => [new(1024, 8192, 8)];
public override string? KeyExchangeAlgorithm => "RSA";
public override string SignatureAlgorithm => "RSA";
public override byte[] SignHash(byte[] hash, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding)
{
if (padding != RSASignaturePadding.Pkcs1)
throw new NotSupportedException("Only RSA PKCS#1 v1.5 padding is supported.");
byte[] digestInfo = Pkcs11DigestInfoBuilder.Build(hash, hashAlgorithm);
try
{
return Pkcs11SessionRunner.Run(options, session =>
{
var attrs = new List<IObjectAttribute>
{
session.Factories.ObjectAttributeFactory.Create(CKA.CKA_CLASS, CKO.CKO_PRIVATE_KEY),
session.Factories.ObjectAttributeFactory.Create(CKA.CKA_LABEL, options.PrivateKeyLabel)
};
var handles = session.FindAllObjects(attrs);
if (handles.Count == 0)
throw new InvalidOperationException($"Private key '{options.PrivateKeyLabel}' not found in token.");
var mechanism = session.Factories.MechanismFactory.Create(CKM.CKM_RSA_PKCS);
return session.Sign(mechanism, handles[0], digestInfo);
});
}
catch when (Pkcs11ToolBridge.IsAvailable(options))
{
return Pkcs11ToolBridge.SignDigestInfo(options, digestInfo);
}
}
public override bool VerifyHash(byte[] hash, byte[] signature, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding)
=> throw new NotSupportedException();
public override byte[] Decrypt(byte[] data, RSAEncryptionPadding padding)
=> throw new NotSupportedException();
public override byte[] Encrypt(byte[] data, RSAEncryptionPadding padding)
=> throw new NotSupportedException();
public override RSAParameters ExportParameters(bool includePrivateParameters)
=> throw new NotSupportedException();
public override void ImportParameters(RSAParameters parameters)
=> throw new NotSupportedException();
}

View File

@@ -0,0 +1,24 @@
using EnvelopeGenerator.Application.Common.Dto;
using EnvelopeGenerator.Application.Common.Interfaces.Services;
using System.Threading;
namespace EnvelopeGenerator.Infrastructure.Crypt.Services;
internal sealed class Pkcs11SelfTestStatusStore : IPkcs11SelfTestStatusProvider
{
private Pkcs11SelfTestStatusDto _status = new(
Completed: false,
Success: false,
Mode: "pending",
Summary: "PKCS#11 startup self-test has not run yet.",
CheckedAtUtc: null,
InteropError: null,
ToolError: null);
public Pkcs11SelfTestStatusDto GetStatus() => Volatile.Read(ref _status);
public void SetStatus(Pkcs11SelfTestStatusDto status)
{
Volatile.Write(ref _status, status);
}
}

View File

@@ -0,0 +1,124 @@
using EnvelopeGenerator.Application.Common.Configurations;
using Net.Pkcs11Interop.Common;
using Net.Pkcs11Interop.HighLevelAPI;
namespace EnvelopeGenerator.Infrastructure.Crypt.Services;
internal static class Pkcs11SessionRunner
{
public static T Run<T>(Pkcs11Options options, Func<ISession, T> action)
{
Pkcs11InteropBootstrap.EnsureLoaded(options);
var factories = new Pkcs11InteropFactories();
using var pkcs11 = LoadLibraryWithFallback(factories, options.ResolvedLibraryPath, options.ProxySocket);
var slot = ResolveSlot(pkcs11.GetSlotList(SlotsType.WithTokenPresent), options);
using var session = slot.OpenSession(SessionType.ReadOnly);
session.Login(CKU.CKU_USER, options.UserPin);
try
{
return action(session);
}
finally
{
session.Logout();
}
}
private static IPkcs11Library LoadLibraryWithFallback(Pkcs11InteropFactories factories, string libraryPath, string? proxySocket)
{
List<Exception> errors = [];
foreach (string candidate in BuildLibraryCandidates(libraryPath))
{
try
{
return factories.Pkcs11LibraryFactory.LoadPkcs11Library(factories, candidate, AppType.MultiThreaded);
}
catch (Exception ex)
{
errors.Add(new InvalidOperationException($"{candidate} | MultiThreaded+WithFunctionList", ex));
}
try
{
return factories.Pkcs11LibraryFactory.LoadPkcs11Library(factories, candidate, AppType.SingleThreaded);
}
catch (Exception ex)
{
errors.Add(new InvalidOperationException($"{candidate} | SingleThreaded+WithFunctionList", ex));
}
try
{
return factories.Pkcs11LibraryFactory.LoadPkcs11Library(factories, candidate, AppType.MultiThreaded, InitType.WithoutFunctionList);
}
catch (Exception ex)
{
errors.Add(new InvalidOperationException($"{candidate} | MultiThreaded+WithoutFunctionList", ex));
}
try
{
return factories.Pkcs11LibraryFactory.LoadPkcs11Library(factories, candidate, AppType.SingleThreaded, InitType.WithoutFunctionList);
}
catch (Exception ex)
{
errors.Add(new InvalidOperationException($"{candidate} | SingleThreaded+WithoutFunctionList", ex));
}
}
var socketInfo = string.IsNullOrWhiteSpace(proxySocket) ? "<empty>" : proxySocket;
throw new AggregateException($"Unable to initialize PKCS#11 library '{libraryPath}' with any supported initialization mode. PKCS11_PROXY_SOCKET={socketInfo}", errors);
}
private static IEnumerable<string> BuildLibraryCandidates(string configuredPath)
{
var unique = new HashSet<string>(StringComparer.OrdinalIgnoreCase)
{
configuredPath
};
var directory = Path.GetDirectoryName(configuredPath);
if (!string.IsNullOrWhiteSpace(directory))
{
string[] alternates =
[
"client.dll",
"pkcs11-proxy.dll",
"libpkcs11-proxy.dll"
];
foreach (var fileName in alternates)
{
var candidate = Path.Combine(directory, fileName);
if (File.Exists(candidate))
unique.Add(candidate);
}
}
return unique;
}
private static ISlot ResolveSlot(IEnumerable<ISlot> slots, Pkcs11Options options)
{
if (options.SlotId.HasValue)
{
var bySlotId = slots.FirstOrDefault(s => s.SlotId == options.SlotId.Value);
if (bySlotId is not null)
return bySlotId;
}
if (!string.IsNullOrWhiteSpace(options.TokenLabel))
{
var byTokenLabel = slots.FirstOrDefault(s =>
string.Equals(s.GetTokenInfo().Label?.Trim(), options.TokenLabel.Trim(), StringComparison.Ordinal));
if (byTokenLabel is not null)
return byTokenLabel;
}
throw new InvalidOperationException("Unable to resolve PKCS#11 slot. Check Crypt:Pkcs11:SlotId / TokenLabel.");
}
}

View File

@@ -0,0 +1,112 @@
using EnvelopeGenerator.Application.Common.Configurations;
using EnvelopeGenerator.Application.Common.Dto;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Net.Pkcs11Interop.Common;
using Net.Pkcs11Interop.HighLevelAPI;
using System.Security.Cryptography;
namespace EnvelopeGenerator.Infrastructure.Crypt.Services;
internal sealed class Pkcs11StartupSelfTestHostedService(
IOptions<Pkcs11Options> options,
Pkcs11SelfTestStatusStore statusStore,
ILogger<Pkcs11StartupSelfTestHostedService> logger) : IHostedService
{
public Task StartAsync(CancellationToken cancellationToken)
{
var pkcs11 = options.Value;
try
{
RunInteropProbe(pkcs11);
statusStore.SetStatus(new Pkcs11SelfTestStatusDto(
Completed: true,
Success: true,
Mode: "interop",
Summary: "PKCS#11 startup self-test succeeded via interop.",
CheckedAtUtc: DateTimeOffset.UtcNow,
InteropError: null,
ToolError: null));
logger.LogInformation("PKCS#11 startup self-test succeeded (mode=interop, library={LibraryPath}, proxy={ProxySocket}).", pkcs11.ResolvedLibraryPath, pkcs11.ProxySocket);
return Task.CompletedTask;
}
catch (Exception interopEx) when (Pkcs11ToolBridge.IsAvailable(pkcs11))
{
try
{
RunToolProbe(pkcs11);
statusStore.SetStatus(new Pkcs11SelfTestStatusDto(
Completed: true,
Success: true,
Mode: "pkcs11-tool",
Summary: "PKCS#11 interop failed, tool fallback succeeded.",
CheckedAtUtc: DateTimeOffset.UtcNow,
InteropError: interopEx.Message,
ToolError: null));
logger.LogWarning(interopEx, "PKCS#11 interop self-test failed, but tool fallback is healthy (mode=pkcs11-tool, tool={ToolPath}).", pkcs11.ResolvedToolPath);
return Task.CompletedTask;
}
catch (Exception toolEx)
{
statusStore.SetStatus(new Pkcs11SelfTestStatusDto(
Completed: true,
Success: false,
Mode: "failed",
Summary: "PKCS#11 startup self-test failed for both interop and tool fallback.",
CheckedAtUtc: DateTimeOffset.UtcNow,
InteropError: interopEx.Message,
ToolError: toolEx.Message));
logger.LogError(toolEx, "PKCS#11 startup self-test failed for both interop and tool fallback. library={LibraryPath}, proxy={ProxySocket}, tool={ToolPath}", pkcs11.ResolvedLibraryPath, pkcs11.ProxySocket, pkcs11.ResolvedToolPath);
return Task.CompletedTask;
}
}
catch (Exception ex)
{
statusStore.SetStatus(new Pkcs11SelfTestStatusDto(
Completed: true,
Success: false,
Mode: "failed",
Summary: "PKCS#11 startup self-test failed via interop and no tool fallback is available.",
CheckedAtUtc: DateTimeOffset.UtcNow,
InteropError: ex.Message,
ToolError: null));
logger.LogError(ex, "PKCS#11 startup self-test failed (mode=interop, no fallback available). library={LibraryPath}, proxy={ProxySocket}", pkcs11.ResolvedLibraryPath, pkcs11.ProxySocket);
return Task.CompletedTask;
}
}
public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask;
private static void RunInteropProbe(Pkcs11Options options)
{
Pkcs11SessionRunner.Run(options, session =>
{
EnsureObjectExists(session, CKO.CKO_CERTIFICATE, options.CertificateLabel, "certificate");
EnsureObjectExists(session, CKO.CKO_PRIVATE_KEY, options.PrivateKeyLabel, "private key");
return true;
});
}
private static void RunToolProbe(Pkcs11Options options)
{
_ = Pkcs11ToolBridge.ReadCertificateBytes(options);
var testDigest = SHA256.HashData([1, 2, 3, 4]);
var digestInfo = Pkcs11DigestInfoBuilder.Build(testDigest, HashAlgorithmName.SHA256);
_ = Pkcs11ToolBridge.SignDigestInfo(options, digestInfo);
}
private static void EnsureObjectExists(ISession session, CKO objectClass, string label, string objectType)
{
var attrs = new List<IObjectAttribute>
{
session.Factories.ObjectAttributeFactory.Create(CKA.CKA_CLASS, objectClass),
session.Factories.ObjectAttributeFactory.Create(CKA.CKA_LABEL, label)
};
var handles = session.FindAllObjects(attrs);
if (handles.Count == 0)
throw new InvalidOperationException($"PKCS#11 {objectType} '{label}' not found in token.");
}
}

View File

@@ -0,0 +1,147 @@
using EnvelopeGenerator.Application.Common.Configurations;
using System.Diagnostics;
using System.Security.Cryptography;
namespace EnvelopeGenerator.Infrastructure.Crypt.Services;
internal static class Pkcs11ToolBridge
{
public static bool IsAvailable(Pkcs11Options options)
{
return !string.IsNullOrWhiteSpace(options.ResolvedToolPath) && File.Exists(options.ResolvedToolPath);
}
public static byte[] ReadCertificateBytes(Pkcs11Options options)
{
EnsureAvailable(options);
var outputFile = Path.Combine(Path.GetTempPath(), $"pkcs11-cert-{Guid.NewGuid():N}.der");
try
{
var args = CreateBaseArgs(options);
args.Add("--read-object");
args.Add("--type");
args.Add("cert");
args.Add("--label");
args.Add(options.CertificateLabel);
args.Add("--output-file");
args.Add(outputFile);
Execute(options, args);
return File.ReadAllBytes(outputFile);
}
finally
{
DeleteIfExists(outputFile);
}
}
public static byte[] SignDigestInfo(Pkcs11Options options, byte[] digestInfo)
{
EnsureAvailable(options);
var inputFile = Path.Combine(Path.GetTempPath(), $"pkcs11-sign-in-{Guid.NewGuid():N}.bin");
var outputFile = Path.Combine(Path.GetTempPath(), $"pkcs11-sign-out-{Guid.NewGuid():N}.bin");
try
{
File.WriteAllBytes(inputFile, digestInfo);
var args = CreateBaseArgs(options);
args.Add("--sign");
args.Add("--mechanism");
args.Add("RSA-PKCS");
args.Add("--type");
args.Add("privkey");
args.Add("--label");
args.Add(options.PrivateKeyLabel);
args.Add("--input-file");
args.Add(inputFile);
args.Add("--output-file");
args.Add(outputFile);
Execute(options, args);
return File.ReadAllBytes(outputFile);
}
finally
{
DeleteIfExists(inputFile);
DeleteIfExists(outputFile);
}
}
private static List<string> CreateBaseArgs(Pkcs11Options options)
{
var args = new List<string>
{
"--module",
options.ResolvedLibraryPath,
"--login",
"--pin",
options.UserPin
};
if (options.SlotId.HasValue)
{
args.Add("--slot");
args.Add(options.SlotId.Value.ToString());
}
else if (!string.IsNullOrWhiteSpace(options.TokenLabel))
{
args.Add("--token-label");
args.Add(options.TokenLabel);
}
return args;
}
private static void Execute(Pkcs11Options options, IReadOnlyList<string> arguments)
{
var process = new Process
{
StartInfo = new ProcessStartInfo
{
FileName = options.ResolvedToolPath!,
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardError = true,
CreateNoWindow = true
}
};
foreach (var argument in arguments)
process.StartInfo.ArgumentList.Add(argument);
if (!string.IsNullOrWhiteSpace(options.ProxySocket))
{
process.StartInfo.Environment["PKCS11_PROXY_SOCKET"] = options.ProxySocket;
process.StartInfo.Environment["PKCS11_DAEMON_SOCKET"] = options.ProxySocket;
}
process.Start();
string stdOut = process.StandardOutput.ReadToEnd();
string stdErr = process.StandardError.ReadToEnd();
if (!process.WaitForExit(30000))
{
try { process.Kill(entireProcessTree: true); } catch { }
throw new TimeoutException($"pkcs11-tool timed out. Args: {string.Join(' ', process.StartInfo.ArgumentList)}");
}
if (process.ExitCode != 0)
throw new InvalidOperationException($"pkcs11-tool failed with exit code {process.ExitCode}. StdOut: {stdOut} StdErr: {stdErr}");
}
private static void EnsureAvailable(Pkcs11Options options)
{
if (!IsAvailable(options))
throw new InvalidOperationException("pkcs11-tool is not available at resolved pkcs11 assets path.");
}
private static void DeleteIfExists(string path)
{
if (File.Exists(path))
File.Delete(path);
}
}

View File

@@ -0,0 +1,301 @@
# FES Signature Infrastructure Plan
## 1. Goal
Build a reusable and modular cryptography infrastructure in `EnvelopeGenerator.Infrastructure.Crypt` to support FES (Advanced Electronic Signature) workflows.
This module must:
- use PKCS#11 providers (SoftHSMv2 first, real HSM later),
- stay independent from UI/API concerns,
- expose clean interfaces to `Application` layer use-cases,
- support future extensions (timestamping, certificate chain validation, multiple key algorithms).
---
## 2. Context and Constraints
1. SoftHSMv2 is **not** a REST service. It is a PKCS#11 module loaded as a native library.
2. `EnvelopeGenerator.Server` is presentation only; cryptographic implementation belongs to infrastructure.
3. Clean Architecture boundaries must be respected:
- `Application` depends on abstractions.
- `Infrastructure.Crypt` implements abstractions.
4. Initial target framework is `net8.0`.
5. We need production-ready behavior, not only PoC signing.
---
## 3. High-Level Design
## 3.1 Architecture slice
- **Application layer (contracts/use-cases):**
- request signing hash/document,
- request certificate/public key material,
- request verification,
- consume signature evidence result.
- **Infrastructure.Crypt layer (this project):**
- PKCS#11 session handling,
- key/certificate object discovery,
- hash signing operations,
- local cryptographic verification,
- certificate parsing helpers,
- error normalization.
## 3.2 Provider model
Define provider-agnostic APIs and add one concrete provider first:
- `Pkcs11SignatureProvider` (primary)
- future providers:
- `RemoteSigningProvider` (if a dedicated signing gateway is introduced)
- `MockSignatureProvider` (for deterministic test scenarios)
---
## 4. Deliverables (Phase by Phase)
## Phase 0 - Contracts and Domain Language
Create neutral models and interfaces in `Infrastructure.Crypt` (or shared abstractions if needed later):
- `SigningAlgorithm` (enum/value object)
- `Pkcs11ProviderOptions`
- `KeyLocator` (label/id/slot/token selectors)
- `SignHashRequest`
- `SignHashResult`
- `VerifySignatureRequest`
- `VerifySignatureResult`
- `CertificateDescriptor`
- `SignatureEvidence` (technical evidence payload)
Interfaces:
- `ISignatureProvider`
- `ICertificateProvider`
- `ISignatureVerifier`
- `ICryptographicHealthCheck`
Acceptance criteria:
- no dependency on ASP.NET types,
- no UI/API naming leakage,
- all model names are business-neutral.
## Phase 1 - PKCS#11 Core Adapter (SoftHSM-ready)
Implement:
- `Pkcs11LibraryLoader`
- `Pkcs11SessionFactory`
- `Pkcs11ObjectFinder`
- `Pkcs11SignatureProvider`
- `Pkcs11CertificateProvider`
Capabilities:
1. load module path from options (`libsofthsm2.so` or proxy module when required),
2. enumerate slots/tokens,
3. open read-write session,
4. login with user pin,
5. find private key by label/id,
6. sign digest with selected mechanism,
7. read certificate object by label/id.
Acceptance criteria:
- deterministic disposal of sessions,
- no leaked native handles,
- detailed typed errors (not raw exception strings only).
## Phase 2 - Verification and Certificate Utilities
Implement:
- `DefaultSignatureVerifier`
- `X509CertificateParser`
- optional `CertificateChainValidator` (toggleable)
Capabilities:
1. verify signature using returned certificate/public key,
2. expose certificate metadata (`thumbprint`, `subject`, `issuer`, `notBefore`, `notAfter`),
3. map validation failures into stable error codes.
Acceptance criteria:
- same request yields same verification outcome,
- invalid signature returns structured negative result.
## Phase 3 - Evidence Builder
Implement:
- `SignatureEvidenceBuilder`
Evidence payload should contain:
- transaction/correlation id,
- algorithm,
- hash metadata,
- key locator snapshot (safe subset),
- certificate fingerprint and subject,
- sign timestamp (UTC),
- verification outcome,
- provider type (`PKCS11`).
Acceptance criteria:
- no secret values in evidence (pin, private key id internals),
- evidence serializable for storage/audit.
## Phase 4 - Dependency Injection Module
Implement:
- `CryptInfrastructureDependencyInjection` extension methods
Methods:
- `AddCryptInfrastructure(...)`
- `AddPkcs11Provider(...)`
Acceptance criteria:
- one-line registration from composition root,
- options validation on startup.
## Phase 5 - Test Suite (`EnvelopeGenerator.Tests`)
Add test categories for `net8.0`:
1. `Unit`:
- request validation,
- algorithm mapping,
- evidence building,
- error mapping.
2. `Integration` (conditional/manual profile):
- SoftHSM slot listing,
- login,
- sign hash,
- verify,
- certificate read.
Acceptance criteria:
- unit tests run in CI without native SoftHSM,
- integration tests run when module path + pins are provided via environment variables.
---
## 5. Proposed Project Structure
```text
EnvelopeGenerator.Infrastructure.Crypt/
Abstractions/
ISignatureProvider.cs
ICertificateProvider.cs
ISignatureVerifier.cs
ICryptographicHealthCheck.cs
Models/
SigningAlgorithm.cs
SignHashRequest.cs
SignHashResult.cs
VerifySignatureRequest.cs
VerifySignatureResult.cs
SignatureEvidence.cs
CertificateDescriptor.cs
KeyLocator.cs
Options/
Pkcs11ProviderOptions.cs
Pkcs11/
Pkcs11LibraryLoader.cs
Pkcs11SessionFactory.cs
Pkcs11ObjectFinder.cs
Pkcs11SignatureProvider.cs
Pkcs11CertificateProvider.cs
Verification/
DefaultSignatureVerifier.cs
X509CertificateParser.cs
Evidence/
SignatureEvidenceBuilder.cs
DependencyInjection/
CryptInfrastructureDependencyInjection.cs
Exceptions/
CryptographicOperationException.cs
Pkcs11ProviderException.cs
```
---
## 6. Configuration Strategy
Use options (bound from host config) with environment override support:
- `Crypt:Provider = PKCS11`
- `Crypt:Pkcs11:AssetsRootPath` (base path that contains bundled `pkcs11` assets)
- `Crypt:Pkcs11:SlotId` or token selectors
- `Crypt:Pkcs11:UserPin` (from secret store/env, not plain committed value)
- `Crypt:Pkcs11:PrivateKeyLabel`
- `Crypt:Pkcs11:CertificateLabel`
- `Crypt:Pkcs11:LoginType`
Validation rules:
- resolved module path must exist under configured/default assets root,
- at least one key locator required,
- pin required for signing operations.
---
## 7. Error Model
Define stable error codes to prevent provider-specific leakage:
- `CRYPT_PROVIDER_UNAVAILABLE`
- `CRYPT_SLOT_NOT_FOUND`
- `CRYPT_LOGIN_FAILED`
- `CRYPT_KEY_NOT_FOUND`
- `CRYPT_CERT_NOT_FOUND`
- `CRYPT_SIGN_FAILED`
- `CRYPT_VERIFY_FAILED`
Map low-level exceptions to these codes with safe diagnostics.
---
## 8. Non-Functional Requirements
1. **Security:** never log pins or raw private key handles.
2. **Reliability:** deterministic cleanup (`IDisposable`/`IAsyncDisposable`).
3. **Observability:** structured logs with correlation id.
4. **Performance:** avoid repeated login per operation when a safe session strategy is available.
5. **Extensibility:** algorithm/provider mapping must be open for extension.
---
## 9. Implementation Order (Small Tasks)
1. Add models + interfaces.
2. Add options + validators.
3. Add PKCS#11 low-level loader/session wrappers.
4. Implement `Pkcs11SignatureProvider` for hash signing.
5. Implement certificate retrieval.
6. Implement verifier.
7. Implement evidence builder.
8. Add DI registration extension.
9. Add unit tests.
10. Add optional integration tests (SoftHSM profile).
---
## 10. Definition of Done
Done means:
1. `Infrastructure.Crypt` exposes generic cryptographic services usable by Application use-cases.
2. SoftHSM-backed PKCS#11 sign/verify path works in integration tests.
3. All sensitive configuration is externalized.
4. Structured error codes are returned for expected failure scenarios.
5. Documentation exists for host registration and required settings.

View File

@@ -0,0 +1,228 @@
# FES (Advanced Electronic Signature) Summary and Integration Plan - EN
This document summarizes the shared diagram flow (`Ablauf SignFlow Unternehmenszertifikat`) and provides a small-step integration plan for the `EnvelopeGenerator` solution.
---
## 1) Simplified flow summary
Flow logic:
1. The sender uploads a document and defines signers.
2. If a valid company certificate already exists in HSM, it is used with the company key pair.
3. If no valid company certificate exists, CA issuance/renewal flow is required.
4. The signer receives an e-mail with a signing link.
5. The signer completes SMS OTP (2FA) and performs UI signature interaction.
6. Backend computes the hash for the current signing stage and sends it to HSM.
7. HSM signs the hash with the private key and returns signature + certificate context.
8. Backend embeds digital signature and certificate into PDF and writes audit trail.
9. After all signers complete, the final artifact is archived.
10. The final signed document is distributed to signers.
Important: The visible UI signature is not yet the legal electronic signature. The legal signature is produced in backend+HSM steps.
---
## 2) Relation to current codebase (as-is)
- `EnvelopeGenerator.Server` is the presentation layer host (Blazor + API hosting).
- Business flow is handled in `Application` via MediatR pipelines.
- Current receiver flow is centered around UI overlay/signature capture.
- Missing FES core: PKCS#11 hash-sign-verify + certificate-based PDF embedding pipeline.
Critical deployment fact:
- `EnvelopeGenerator.Server` is planned to run on Windows.
- SoftHSM is currently planned to run on Linux.
- A Windows process cannot directly load Linux PKCS#11 module (`libsofthsm2.so`).
- Therefore, architecture must include a compatibility bridge (service or proxy) unless HSM/SoftHSM is local to Windows.
Conclusion: FES is not a replacement of the current flow; it is a cryptographic hardening layer behind it.
---
## 3) Why SoftHSM tests are foundational
The tests defined in `SOFTHSM_TEST_KILAVUZU_TR.md` are the technical prerequisite for FES:
- `slots/login` -> HSM connectivity and authentication
- `certificate` -> certificate retrieval path
- `sign` -> hash signing with private key
- `verify` -> signature and certificate consistency validation
Without these tests passing, diagram steps 6-8 should not go live.
---
## 4) Target architecture (clean architecture aligned)
### Deployment topology options (must choose one)
1. **Linux signing service (recommended)**
- Windows `EnvelopeGenerator.Server` calls Linux signing API over HTTPS.
- Linux signing service performs PKCS#11 operations against SoftHSM.
- Private keys never leave Linux/HSM boundary.
2. **PKCS#11 proxy bridge**
- Windows host loads a Windows PKCS#11 proxy client DLL.
- Proxy forwards PKCS#11 operations to Linux side connected to SoftHSM.
3. **Windows-local SoftHSM (dev/test)**
- SoftHSM also installed on Windows and used locally.
- Useful for local testing, not preferred production topology.
Decision note:
- For production-critical FES, choose option 1 by default unless enterprise HSM policy requires option 2.
- Keep option 3 for development convenience only.
### Layer responsibilities
- `EnvelopeGenerator.Server`:
- API endpoints, auth orchestration, input validation.
- FES branch routing: standard-sign path vs external signing-service/proxy path.
- No private-key material handling.
- `EnvelopeGenerator.Application`:
- Use cases such as `SignWithHsmCommand`.
- MediatR pipeline orchestration for status/history/audit.
- FES evidence model aggregation (ip/email/phone/user-agent/otp proof/timestamps).
- `EnvelopeGenerator.Infrastructure`:
- Implementations for `IPkcs11Service`, `IPdfSignatureService`, `ITimestampService`.
- Pkcs11Interop integration and cryptographic operations.
- Optional client for Linux signing service if topology option 1 is selected.
- `Domain`:
- Signature evidence and audit-trail models.
---
## 5) Small-step integration plan
## Phase 0 - Scope and contracts
1. Finalize signing algorithms (for example `SHA256_RSA_PKCS`).
2. Confirm strategy: company certificate vs signer-specific certificate.
3. Freeze mandatory audit fields:
- identity, OTP proof, IP, user-agent, transaction id, timestamps, hash metadata.
4. Freeze deployment topology decision:
- option 1 (Linux signing service), option 2 (PKCS#11 proxy), or option 3 (Windows-local SoftHSM).
5. Define production host mapping:
- where `EnvelopeGenerator.Server` runs,
- where HSM/SoftHSM runs,
- where certificate lifecycle is managed.
Deliverable: Technical decision record (ADR-style markdown).
## Phase 1 - PKCS#11 connector (infrastructure)
1. Define `IPkcs11Service` interface.
2. Add `Pkcs11Interop` implementation.
3. Add config model:
- library path, slot, token label, key label, certificate label.
4. Ensure secure secret handling for PIN.
5. Ensure host-compatible module loading:
- Windows server must load Windows DLL,
- Linux server must load Linux `.so`.
Deliverable: Testable PKCS#11 service with health/slot/login/sign/verify capabilities.
## Phase 1.5 - Cross-host bridge implementation
1. If option 1 selected:
- implement Linux signing service API contract (`/sign`, `/certificate`, `/health`),
- implement authenticated HTTP client in `EnvelopeGenerator.Server`.
2. If option 2 selected:
- install/configure PKCS#11 proxy client DLL on Windows,
- install/configure proxy server on Linux and bind to SoftHSM.
Deliverable: Windows-to-Linux signing communication path proven end-to-end.
## Phase 2 - Application use case
1. Add `SignDocumentHashCommand` (or equivalent).
2. Pipeline flow:
- compute/receive hash,
- sign with HSM,
- attach certificate context,
- verify,
- produce evidence object.
3. Add resilient error mapping and retry strategy.
Deliverable: HSM signing use case in Application layer.
## Phase 3 - PDF signature embedding
1. Implement PDF signature embedding via `IPdfSignatureService`.
2. Build signer-specific audit-trail pages.
3. Append all audit pages to final PDF artifact.
Deliverable: Signed PDF with certificate context and audit trail pages.
## Phase 4 - Presentation/API integration
1. Integrate FES option into submit flow (feature flag guarded).
2. Add operational endpoints:
- HSM health/check
- signature evidence query (restricted roles)
3. Keep DTOs safe; avoid exposing sensitive cryptographic material.
4. In `SignatureController.Submit`, add FES branch that sends signing payload + audit context to selected signing backend.
Deliverable: API-level orchestration with minimal UI disruption.
## Phase 5 - Audit, archive, distribution
1. Persist signature evidence records.
2. Include hash/cert metadata in archival package.
3. Add signed artifact reference to distribution e-mails.
Deliverable: Alignment with diagram steps 9-10.
## Phase 6 - Testing and operations
1. Postman collection + Newman automation.
2. Positive/negative matrix:
- wrong pin, wrong slot, missing cert, expired cert, HSM timeout.
3. Observability:
- structured logs, correlation id, latency metrics.
Deliverable: Production readiness checklist.
---
## 6) Transition strategy from test API to production flow
1. Keep `/api/pkcs11-test/*` only for non-production.
2. In production, use the same internal services through business endpoints only.
3. Roll out by feature flag:
- `FesEnabled=false` initially
- pilot sender group
- full rollout
4. Keep explicit environment matrix:
- local dev (option 3),
- integration/staging (option 1 or 2),
- production (option 1 or 2 only).
---
## 7) Risks and mitigations
- Certificate expiry risk -> proactive monitoring and renewal alerting.
- HSM connectivity risk -> retry policy, circuit breaker, fallback queue.
- PIN/secret exposure risk -> vault-backed secrets and rotation policy.
- Verification failure risk -> block PDF sealing and move envelope to technical hold state.
- Cross-host connectivity risk -> mTLS/JWT auth + timeout/retry/circuit breaker + health probe.
---
## 8) Short done checklist
- [ ] PKCS#11 service interface + implementation
- [ ] Application command + pipeline behaviors
- [ ] PDF signature embedding
- [ ] Audit-trail generation
- [ ] API integration + feature flag
- [ ] Postman/Newman regression suite
- [ ] Operational runbook and alerting rules

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,84 @@
10/6/26, 10:46 PM
Test SoftHSM : SWINFRA-54
Projects / Infrastruktur Software / Issues /
Enter search…
SWINFRA-54
All…
Created by Marvin Kamm 3 months ago
Visible to issue readers 1
Updated by Matthias Dewald about 1 month ago
# **Test SoftHSM**
Project Priorität Status **SWI** Infrastruktur Softwa H Hoch O Offen re… Bearbeiter Fälligkeit Projekteinfluss MD _ ? ? Matthias Dewald Kein fälligkeit Kein projektbezug Boards No visible boards
Bitte eine Test-VM mit der Software SoftHSM bereitstellen.
Laut Info von @Henning Emrich soll die Installation unter Debian Linux deutlich einfacher sein, als unter Windows. Bitte prüfen.
@Hakan Tek & @OlgunR
Sollen bitte die API Ansteuerung testen
FYI
@Marlon Schreiber @Jan-Ulrich Hoss @Henning Emrich @Hakan Tek @OlgunR
**Attachments** 1
Files Attached to Comments
**PDF**
Ablauf SignFlow Un ternehme… 83 kB
MD _ **Matthias Dewald** Commented 3 months ago Ist für Dienstag 30.6 10:00 Uhr Eingeplant
HT **Hakan Tek** Commented 3 months ago
Für die Integration auf der .NET-Seite können wir die Pkcs11Interop-Bibliothek und die entsprechende DevExpress-Infrastruktur verwenden. @OlgunR, falls du noch weitere Vorschläge hast, füge sie bitte hinzu. @Marvin Kamm, @Henning Emrich, @Matthias Dewald, um mit den Tests beginnen zu können, benötigen wir die entsprechenden Verbindungsdaten für SoftHSM (Slot-ID, PIN, Bibliothekspfad usw.).
FYI
@Marlon Schreiber @Jan-Ulrich Hoss
bugtracker.dd:8080/issue/SWINFRA-54/Test-SoftHSM
1/2
10/6/26, 10:46 PM
Test SoftHSM : SWINFRA-54
MD
## **Matthias Dewald** Commented 3 months ago
Hallo zusammen, SoftHSM ist auf der 172.24.12.64 installiert:
Der Proxy läuft auf Port 5657 und erwartet Verbindungen über die Proxy-Bibliothek (libpkcs11-proxy.so)
@Hakan Tek Bitte testen
MD
## **Matthias Dewald** Commented about 1 month ago
Ablauf SignFlow Unternehmenszertifikat.drawio.pdf
**PDF**
Ablauf SignFlow Un ternehme… 83 kB
bugtracker.dd:8080/issue/SWINFRA-54/Test-SoftHSM
2/2

View File

@@ -0,0 +1,22 @@
namespace EnvelopeGenerator.Server.Client.Components.Sender;
public sealed record CreateEnvelopeWizardResult(
string Title,
string Message,
int? EnvelopeTypeId,
string Language,
bool UseAccessCode,
bool TFAEnabled,
int CertificationType,
int FinalEmailToCreator,
int FinalEmailToReceivers,
bool SendReminderEmails,
int FirstReminderDays,
int ReminderIntervalDays,
int ExpiresWhenDays,
int ExpiresWarningWhenDays,
IReadOnlyList<CreateEnvelopeWizardReceiver> Receivers,
byte[]? DocumentBytes,
string? DocumentFileName);
public sealed record CreateEnvelopeWizardReceiver(string FullName, string EmailAddress);

View File

@@ -0,0 +1,104 @@
@using Microsoft.AspNetCore.Components.Forms
<div class="sender-pdf-dropzone @DropZoneClass">
<div class="sender-pdf-dropzone__content">
<div class="sender-pdf-dropzone__title">@CurrentActionText</div>
@if (!string.IsNullOrWhiteSpace(DragDropHintText))
{
<div class="sender-pdf-dropzone__hint">@DragDropHintText</div>
}
</div>
<InputFile OnChange="OnFileSelectedAsync"
accept="@Accept"
disabled="@Disabled"
@ondragenter="OnDragEnter"
@ondragleave="OnDragLeave"
@ondragover="OnDragOver"
@ondrop="OnDrop"
class="sender-pdf-dropzone__input" />
</div>
@code {
[Parameter]
public bool Disabled { get; set; }
[Parameter]
public bool HasDocument { get; set; }
[Parameter]
public string Accept { get; set; } = ".pdf";
[Parameter]
public string UploadText { get; set; } = "PDF hochladen";
[Parameter]
public string ReplaceText { get; set; } = "PDF ersetzen";
[Parameter]
public string DragDropHintText { get; set; } = "Datei hierhin ziehen oder klicken";
[Parameter]
public EventCallback<InputFileChangeEventArgs> FileSelected { get; set; }
private int _dragDepth;
private bool _isDragActive;
private string CurrentActionText => HasDocument ? ReplaceText : UploadText;
private string DropZoneClass
{
get
{
if (Disabled)
return "sender-pdf-dropzone--disabled";
return _isDragActive ? "sender-pdf-dropzone--drag-active" : string.Empty;
}
}
private void OnDragEnter(DragEventArgs _)
{
if (Disabled)
return;
_dragDepth++;
_isDragActive = true;
}
private void OnDragLeave(DragEventArgs _)
{
if (Disabled)
return;
_dragDepth = Math.Max(0, _dragDepth - 1);
if (_dragDepth == 0)
_isDragActive = false;
}
private void OnDragOver(DragEventArgs _)
{
if (Disabled)
return;
_isDragActive = true;
}
private void OnDrop(DragEventArgs _)
{
_dragDepth = 0;
_isDragActive = false;
}
private async Task OnFileSelectedAsync(InputFileChangeEventArgs args)
{
_dragDepth = 0;
_isDragActive = false;
if (Disabled)
return;
if (FileSelected.HasDelegate)
await FileSelected.InvokeAsync(args);
}
}

View File

@@ -0,0 +1,25 @@
namespace EnvelopeGenerator.Server.Client.Components.Sender.ReceiverSuggestionFilter;
public readonly record struct ReceiverFilterCriteria
{
public readonly string FullName;
public readonly string EmailAddress;
public ReceiverFilterCriteria(string? fullName = "", string? emailAddress = "")
{
FullName = Normalize(fullName);
EmailAddress = Normalize(emailAddress);
}
public readonly bool Matches(ReceiverFilterCriteria criteria)
=> FullName.Contains(criteria.FullName, StringComparison.Ordinal)
&& EmailAddress.Contains(criteria.EmailAddress, StringComparison.Ordinal);
private static string Normalize(string? text)
{
if (string.IsNullOrWhiteSpace(text))
return string.Empty;
return string.Concat(text.Where(c => !char.IsWhiteSpace(c))).ToLowerInvariant();
}
}

View File

@@ -0,0 +1,26 @@
using EnvelopeGenerator.Application.Common.Dto.Receiver;
namespace EnvelopeGenerator.Server.Client.Components.Sender.ReceiverSuggestionFilter;
public class ReceiverSuggestionFilterHandler(IEnumerable<RecentReceiverSuggestionDto> suggestions)
{
private readonly IReadOnlyList<Entry> _entries = suggestions
.Where(x => !string.IsNullOrWhiteSpace(x.FullName) && !string.IsNullOrWhiteSpace(x.EmailAddress))
.Select(x => new Entry(new ReceiverFilterCriteria(x.FullName, x.EmailAddress), x))
.ToList();
private readonly record struct Entry(ReceiverFilterCriteria Criteria, RecentReceiverSuggestionDto Suggestion);
public IEnumerable<RecentReceiverSuggestionDto> Filter(ReceiverFilterCriteria criteria)
{
return _entries
.Where(x => x.Criteria.Matches(criteria))
.Select(x => x.Suggestion);
}
public IEnumerable<RecentReceiverSuggestionDto> Filter(string fullName, string emailAddress)
{
var criteria = new ReceiverFilterCriteria(fullName, emailAddress);
return Filter(criteria);
}
}

View File

@@ -80,7 +80,7 @@
_selected = option; _selected = option;
_isOpen = false; _isOpen = false;
await LocalizationService.SetLanguageAsync(option.Code); await LocalizationService.SetLanguageAsync(option.Code);
Navigation.NavigateTo(Navigation.Uri, forceLoad: false); Navigation.NavigateTo(Navigation.Uri, forceLoad: true);
} }
private sealed record LanguageOption(string Code, string FlagClass, string ShortName); private sealed record LanguageOption(string Code, string FlagClass, string ShortName);

View File

@@ -6,6 +6,7 @@
@using EnvelopeGenerator.Application.Envelopes.Commands @using EnvelopeGenerator.Application.Envelopes.Commands
@using EnvelopeGenerator.Application.Resources @using EnvelopeGenerator.Application.Resources
@using EnvelopeGenerator.Domain.Constants @using EnvelopeGenerator.Domain.Constants
@using EnvelopeGenerator.Domain.Resources
@using EnvelopeGenerator.Server.Client.Components.PdfEditor @using EnvelopeGenerator.Server.Client.Components.PdfEditor
@using EnvelopeGenerator.Server.Client.Services @using EnvelopeGenerator.Server.Client.Services
@using Microsoft.AspNetCore.WebUtilities @using Microsoft.AspNetCore.WebUtilities
@@ -20,76 +21,71 @@
@inject ReceiverService ReceiverService @inject ReceiverService ReceiverService
@inject EnvelopeService EnvelopeService @inject EnvelopeService EnvelopeService
@inject EnvelopeTypeService EnvelopeTypeService @inject EnvelopeTypeService EnvelopeTypeService
@inject CreateEnvelopeBootstrapStorageService CreateEnvelopeBootstrapStorageService
@inject AuthService AuthService @inject AuthService AuthService
@inject IStringLocalizer<Resource> UiLocalizer @inject IStringLocalizer<Resource> UiLocalizer
@inject IStringLocalizer<Model> ModelLocalizer
<link href="_content/DevExpress.Blazor.Themes/blazing-berry.bs5.min.css" rel="stylesheet" /> <link href="_content/DevExpress.Blazor.Themes/blazing-berry.bs5.min.css" rel="stylesheet" />
<link href="_content/DevExpress.Blazor.Viewer/css/dx-blazor-viewer-components.bs5.css" rel="stylesheet" /> <link href="_content/DevExpress.Blazor.Viewer/css/dx-blazor-viewer-components.bs5.css" rel="stylesheet" />
<link href="@AppVersion.GetVersionedUrl("css/envelope-viewer.css")" rel="stylesheet" /> <link href="@AppVersion.GetVersionedUrl("css/envelope-viewer.css")" rel="stylesheet" />
<script src="@AppVersion.GetVersionedUrl("js/envelope-editor.js")"></script> <script src="@AppVersion.GetVersionedUrl("js/envelope-editor.js")"></script>
<DxLoadingPanel Visible="@IsBootstrapLoading"
IsContentBlocked="true"
ApplyBackgroundShading="true"
IndicatorAreaVisible="true"
Text='@L("SenderEditor_BootstrapLoadingHint", "Der Umschlag wird vorbereitet und die Daten werden uebernommen.")'>
<div class="envelope-viewer-layout"> <div class="envelope-viewer-layout">
@* ── Action Bar ── *@ @* ── Action Bar ── *@
<div class="envelope-action-bar"> <div class="envelope-action-bar">
<div class="envelope-action-bar__inner" <div class="envelope-action-bar__inner sender-editor-action-inner">
style="flex-direction: row; align-items: center; padding: 0.35rem 1.5rem; gap: 0.75rem;">
@* Left: Title + meta inputs + receivers *@ @* Left: Title + meta inputs + receivers *@
<div style="flex: 1; min-width: 0; display: flex; flex-direction: column; align-items: stretch; gap: 0.5rem;"> <div class="sender-editor-main-column">
@* ── Title & Message inputs ── *@ @* ── Title & Message inputs ── *@
<div style="display: flex; align-items: flex-start; gap: 0.5rem; flex-wrap: wrap;"> <div class="sender-editor-meta-row">
@* Titel *@ @* Titel *@
<div style="display: flex; flex-direction: column; gap: 0.2rem; flex: 1 1 180px; min-width: 140px;"> <div class="sender-editor-input-field sender-editor-input-field--title">
<label style="font-size: 0.65rem; font-weight: 600; color: #6b7280; <label class="sender-editor-label">
text-transform: uppercase; letter-spacing: 0.05em;"> @L("Title", "Titel") <span class="sender-editor-required-asterisk">*</span>
@L("Title", "Titel") <span style="color:#dc2626;">*</span>
</label> </label>
<input type="text" <input type="text"
value="@_envelopeTitle" value="@_envelopeTitle"
@oninput="e => _envelopeTitle = e.Value?.ToString() ?? string.Empty" @oninput="e => _envelopeTitle = e.Value?.ToString() ?? string.Empty"
placeholder='@L("SenderEditor_Title_Placeholder", "z.B. Arbeitsvertrag 2025")' placeholder='@L("SenderEditor_Title_Placeholder", "z.B. Arbeitsvertrag 2025")'
maxlength="120" maxlength="120"
style="font-size: 0.78rem; font-weight: 500; color: #1f2937; class="sender-editor-text-input @(_titleTouched && string.IsNullOrWhiteSpace(_envelopeTitle) ? "sender-editor-text-input--invalid" : string.Empty)" />
border: 1px solid #d1d5db; border-radius: 5px;
padding: 0.3rem 0.55rem; outline: none; width: 100%;
background: #fff;
@(_titleTouched && string.IsNullOrWhiteSpace(_envelopeTitle) ? "border-color:#dc2626;" : "")" />
@if (_titleTouched && string.IsNullOrWhiteSpace(_envelopeTitle)) @if (_titleTouched && string.IsNullOrWhiteSpace(_envelopeTitle))
{ {
<span style="font-size:0.6rem;color:#dc2626;">@L("RequiredField", "Pflichtfeld")</span> <span class="sender-editor-required-text">@L("RequiredField", "Pflichtfeld")</span>
} }
</div> </div>
@* Nachricht *@ @* Nachricht *@
<div style="display: flex; flex-direction: column; gap: 0.2rem; flex: 2 1 260px; min-width: 180px;"> <div class="sender-editor-input-field sender-editor-input-field--message">
<label style="font-size: 0.65rem; font-weight: 600; color: #6b7280; <label class="sender-editor-label">
text-transform: uppercase; letter-spacing: 0.05em;"> @L("Message", "Nachricht") <span class="sender-editor-optional">(@L("Optional", "optional"))</span>
@L("Message", "Nachricht") <span style="color:#6b7280;font-weight:400;">(@L("Optional", "optional"))</span>
</label> </label>
<input type="text" <input type="text"
value="@_envelopeMessage" value="@_envelopeMessage"
@oninput="e => _envelopeMessage = e.Value?.ToString() ?? string.Empty" @oninput="e => _envelopeMessage = e.Value?.ToString() ?? string.Empty"
placeholder='@L("SenderEditor_Message_Placeholder", "Bitte unterzeichnen Sie das beigefügte Dokument.")' placeholder='@L("SenderEditor_Message_Placeholder", "Bitte unterzeichnen Sie das beigefügte Dokument.")'
maxlength="500" maxlength="500"
style="font-size: 0.78rem; color: #1f2937; class="sender-editor-text-input" />
border: 1px solid #d1d5db; border-radius: 5px;
padding: 0.3rem 0.55rem; outline: none; width: 100%;
background: #fff;" />
</div> </div>
@* PDF filename badge *@ @* PDF filename badge *@
@if (_pdfLoaded) @if (_pdfLoaded)
{ {
<div style="display:flex;align-items:flex-end;gap:0.4rem;padding-bottom:0.05rem;flex-shrink:0;"> <div class="sender-editor-file-meta">
<span style="font-size: 0.7rem; color: #6b7280;">@_fileName</span> <span class="sender-editor-file-name">@_fileName</span>
@if (_signatureFields.Count > 0) @if (_signatureFields.Count > 0)
{ {
<span style="display: inline-flex; align-items: center; padding: 0.125rem 0.4rem; <span class="sender-editor-signature-count">
background: #ede9fe; border-radius: 0.25rem; color: #6d28d9;
font-weight: 500; font-size: 0.7rem; white-space: nowrap;">
@_signatureFields.Count @L("SenderEditor_SignatureField", "Signaturfeld")@(_signatureFields.Count != 1 ? "er" : "") @_signatureFields.Count @L("SenderEditor_SignatureField", "Signaturfeld")@(_signatureFields.Count != 1 ? "er" : "")
</span> </span>
} }
@@ -97,18 +93,18 @@
} }
</div> </div>
<details style="border:1px solid #dbe5ef;border-radius:8px;background:#f9fbfd;"> <div class="sender-settings-shell">
<summary style="cursor:pointer;list-style:none;display:flex;align-items:center;justify-content:space-between;padding:0.55rem 0.7rem;font-size:0.74rem;font-weight:700;color:#1f2937;text-transform:uppercase;letter-spacing:0.04em;"> <DxAccordion ExpandMode="AccordionExpandMode.SingleOrNone" CssClass="sender-settings-accordion">
<span>@L("SenderEditor_EnvelopeSettings", "Envelope-Einstellungen")</span> <Items>
<span style="font-size:0.66rem;color:#64748b;font-weight:600;">@L("SenderEditor_AdvancedOptional", "Erweitert")</span> <DxAccordionItem Text='@L("SenderEditor_EnvelopeSettings", "Envelope-Einstellungen")' Expanded="false">
</summary> <ContentTemplate>
<div class="sender-settings-body">
<div style="padding:0 0.7rem 0.7rem;display:grid;grid-template-columns:repeat(auto-fit,minmax(180px,1fr));gap:0.45rem;"> <div class="sender-settings-grid">
<div style="display:flex;flex-direction:column;gap:0.2rem;"> <div class="sender-settings-field">
<label style="font-size:0.65rem;font-weight:600;color:#64748b;">@L("EnvelopeType", "Umschlagtyp")</label> <label class="sender-settings-label">@L("EnvelopeType", "Umschlagtyp")</label>
<select value="@(_selectedEnvelopeTypeId?.ToString() ?? string.Empty)" <select value="@(_selectedEnvelopeTypeId?.ToString() ?? string.Empty)"
@onchange="OnEnvelopeTypeChanged" @onchange="OnEnvelopeTypeChanged"
style="font-size:0.78rem;border:1px solid #d1d5db;border-radius:5px;padding:0.3rem 0.45rem;background:#fff;"> class="sender-settings-select">
<option value="">@L("SenderEditor_SelectTemplate", "Vorlage auswählen")</option> <option value="">@L("SenderEditor_SelectTemplate", "Vorlage auswählen")</option>
@foreach (var type in _envelopeTypes) @foreach (var type in _envelopeTypes)
{ {
@@ -117,10 +113,9 @@
</select> </select>
</div> </div>
<div style="display:flex;flex-direction:column;gap:0.2rem;"> <div class="sender-settings-field">
<label style="font-size:0.65rem;font-weight:600;color:#64748b;">@L("Language", "Sprache")</label> <label class="sender-settings-label">@L("Language", "Sprache")</label>
<select @bind="_language" <select @bind="_language" class="sender-settings-select">
style="font-size:0.78rem;border:1px solid #d1d5db;border-radius:5px;padding:0.3rem 0.45rem;background:#fff;">
<option value="de">Deutsch (de)</option> <option value="de">Deutsch (de)</option>
<option value="en">English (en)</option> <option value="en">English (en)</option>
<option value="de-DE">Deutsch (de-DE)</option> <option value="de-DE">Deutsch (de-DE)</option>
@@ -128,75 +123,77 @@
</select> </select>
</div> </div>
<div style="display:flex;flex-direction:column;gap:0.2rem;"> <div class="sender-settings-field">
<label style="font-size:0.65rem;font-weight:600;color:#64748b;">@L("CertificationType", "Zertifizierung")</label> <label class="sender-settings-label">@L("CertificationType", "Zertifizierung")</label>
<select @bind="_certificationType" <select @bind="_certificationType" class="sender-settings-select">
style="font-size:0.78rem;border:1px solid #d1d5db;border-radius:5px;padding:0.3rem 0.45rem;background:#fff;">
<option value="1">@L("AdvancedElectronicSignature", "Advanced Electronic Signature")</option> <option value="1">@L("AdvancedElectronicSignature", "Advanced Electronic Signature")</option>
<option value="2">@L("ElectronicSignature", "Electronic Signature")</option> <option value="2">@L("ElectronicSignature", "Electronic Signature")</option>
<option value="3">@L("QualifiedSignature", "Qualified Signature")</option> <option value="3">@L("QualifiedSignature", "Qualified Signature")</option>
</select> </select>
</div> </div>
<div style="display:flex;flex-direction:column;gap:0.3rem;justify-content:flex-end;padding-bottom:0.25rem;"> <div class="sender-settings-toggles">
<label style="display:flex;align-items:center;gap:0.45rem;font-size:0.74rem;color:#1f2937;"> <label class="sender-settings-toggle">
<input type="checkbox" checked="@_tfaEnabled" @onchange="OnTfaChanged" /> <input type="checkbox" checked="@_tfaEnabled" @onchange="OnTfaChanged" />
@L("TFAEnabled", "2FA aktiviert") @L("TFAEnabled", "2FA aktiviert")
</label> </label>
<label style="display:flex;align-items:center;gap:0.45rem;font-size:0.74rem;color:#1f2937;"> <label class="sender-settings-toggle">
<input type="checkbox" checked="@_useAccessCode" @onchange="OnUseAccessCodeChanged" disabled="@_tfaEnabled" /> <input type="checkbox" checked="@_useAccessCode" @onchange="OnUseAccessCodeChanged" disabled="@_tfaEnabled" />
@L("UseAccessCode", "Zugriffscode verwenden") @L("UseAccessCode", "Zugriffscode verwenden")
</label> </label>
</div> </div>
<div style="display:flex;flex-direction:column;gap:0.2rem;"> <div class="sender-settings-field">
<label style="font-size:0.65rem;font-weight:600;color:#64748b;">@L("FinalEmailToCreator", "Finale E-Mail an Ersteller")</label> <label class="sender-settings-label">@L("FinalEmailToCreator", "Finale E-Mail an Ersteller")</label>
<select @bind="_finalEmailToCreator" <select @bind="_finalEmailToCreator" class="sender-settings-select">
style="font-size:0.78rem;border:1px solid #d1d5db;border-radius:5px;padding:0.3rem 0.45rem;background:#fff;">
<option value="0">@L("No", "Nein")</option> <option value="0">@L("No", "Nein")</option>
<option value="1">@L("Yes", "Ja")</option> <option value="1">@L("Yes", "Ja")</option>
<option value="2">@L("YesWithAttachment", "Ja, mit Anhang")</option> <option value="2">@L("YesWithAttachment", "Ja, mit Anhang")</option>
</select> </select>
</div> </div>
<div style="display:flex;flex-direction:column;gap:0.2rem;"> <div class="sender-settings-field">
<label style="font-size:0.65rem;font-weight:600;color:#64748b;">@L("FinalEmailToReceivers", "Finale E-Mail an Empfänger")</label> <label class="sender-settings-label">@L("FinalEmailToReceivers", "Finale E-Mail an Empfänger")</label>
<select @bind="_finalEmailToReceivers" <select @bind="_finalEmailToReceivers" class="sender-settings-select">
style="font-size:0.78rem;border:1px solid #d1d5db;border-radius:5px;padding:0.3rem 0.45rem;background:#fff;">
<option value="0">@L("No", "Nein")</option> <option value="0">@L("No", "Nein")</option>
<option value="1">@L("Yes", "Ja")</option> <option value="1">@L("Yes", "Ja")</option>
<option value="2">@L("YesWithAttachment", "Ja, mit Anhang")</option> <option value="2">@L("YesWithAttachment", "Ja, mit Anhang")</option>
</select> </select>
</div> </div>
<div style="display:flex;flex-direction:column;gap:0.3rem;justify-content:flex-end;padding-bottom:0.25rem;"> <div class="sender-settings-toggles sender-settings-toggles--single">
<label style="display:flex;align-items:center;gap:0.45rem;font-size:0.74rem;color:#1f2937;"> <label class="sender-settings-toggle">
<input type="checkbox" checked="@_sendReminderEmails" @onchange="OnSendReminderEmailsChanged" /> <input type="checkbox" checked="@_sendReminderEmails" @onchange="OnSendReminderEmailsChanged" />
@L("SendReminderEmails", "Erinnerungs-E-Mails senden") @L("SendReminderEmails", "Erinnerungs-E-Mails senden")
</label> </label>
</div> </div>
<div style="display:flex;flex-direction:column;gap:0.2rem;"> <div class="sender-settings-field">
<label style="font-size:0.65rem;font-weight:600;color:#64748b;">@L("FirstReminderDays", "Erste Erinnerung (Tage)")</label> <label class="sender-settings-label">@L("FirstReminderDays", "Erste Erinnerung (Tage)")</label>
<InputNumber @bind-Value="_firstReminderDays" class="form-control form-control-sm" disabled="@(!_sendReminderEmails)" /> <InputNumber @bind-Value="_firstReminderDays" class="form-control form-control-sm sender-settings-number" disabled="@(!_sendReminderEmails)" />
</div> </div>
<div style="display:flex;flex-direction:column;gap:0.2rem;"> <div class="sender-settings-field">
<label style="font-size:0.65rem;font-weight:600;color:#64748b;">@L("ReminderIntervalDays", "Erinnerungsintervall (Tage)")</label> <label class="sender-settings-label">@L("ReminderIntervalDays", "Erinnerungsintervall (Tage)")</label>
<InputNumber @bind-Value="_reminderIntervalDays" class="form-control form-control-sm" disabled="@(!_sendReminderEmails)" /> <InputNumber @bind-Value="_reminderIntervalDays" class="form-control form-control-sm sender-settings-number" disabled="@(!_sendReminderEmails)" />
</div> </div>
<div style="display:flex;flex-direction:column;gap:0.2rem;"> <div class="sender-settings-field">
<label style="font-size:0.65rem;font-weight:600;color:#64748b;">@L("ExpiresWhenDays", "Läuft ab nach (Tage)")</label> <label class="sender-settings-label">@L("ExpiresWhenDays", "Läuft ab nach (Tage)")</label>
<InputNumber @bind-Value="_expiresWhenDays" class="form-control form-control-sm" /> <InputNumber @bind-Value="_expiresWhenDays" class="form-control form-control-sm sender-settings-number" />
</div> </div>
<div style="display:flex;flex-direction:column;gap:0.2rem;"> <div class="sender-settings-field">
<label style="font-size:0.65rem;font-weight:600;color:#64748b;">@L("ExpiresWarningWhenDays", "Ablaufwarnung (Tage)")</label> <label class="sender-settings-label">@L("ExpiresWarningWhenDays", "Ablaufwarnung (Tage)")</label>
<InputNumber @bind-Value="_expiresWarningWhenDays" class="form-control form-control-sm" /> <InputNumber @bind-Value="_expiresWarningWhenDays" class="form-control form-control-sm sender-settings-number" />
</div> </div>
</div> </div>
</details> </div>
</ContentTemplate>
</DxAccordionItem>
</Items>
</DxAccordion>
</div>
<div class="sender-receivers-panel"> <div class="sender-receivers-panel">
<div class="sender-receivers-panel__header"> <div class="sender-receivers-panel__header">
@@ -226,8 +223,7 @@
<div class="sender-receivers-list"> <div class="sender-receivers-list">
@foreach (var receiver in _receivers) @foreach (var receiver in _receivers)
{ {
<div class="sender-receiver-chip" <div class="sender-receiver-chip" style="--receiver-color:@receiver.Color;">
style="border-left: 3px solid @receiver.Color;">
<div class="sender-receiver-chip__body"> <div class="sender-receiver-chip__body">
<div class="sender-receiver-chip__name">@receiver.FullName</div> <div class="sender-receiver-chip__name">@receiver.FullName</div>
<div class="sender-receiver-chip__email">@receiver.Email</div> <div class="sender-receiver-chip__email">@receiver.Email</div>
@@ -237,10 +233,10 @@
} }
</div> </div>
<button class="pdf-toolbar__btn pdf-toolbar__btn--signature-change sender-toolbar-action-btn sender-toolbar-action-btn--compact <button class="pdf-toolbar__btn pdf-toolbar__btn--signature-change sender-toolbar-action-btn sender-toolbar-action-btn--compact sender-receiver-chip__place-btn
@(_pendingReceiverForPlacement?.Id == receiver.Id ? "pdf-toolbar__btn--signature-change-active" : "")" @(_pendingReceiverForPlacement?.Id == receiver.Id ? "sender-receiver-chip__place-btn--active" : "sender-receiver-chip__place-btn--idle")"
@onclick="() => ActivatePlacementForReceiver(receiver)" @onclick="() => ActivatePlacementForReceiver(receiver)"
style="@(_pendingReceiverForPlacement?.Id == receiver.Id ? $"background:{receiver.Color};color:#fff;border-color:{receiver.Color};" : $"color:{receiver.Color};border-color:{receiver.Color};")" style="--receiver-color:@receiver.Color;"
title='@L("SenderEditor_PlaceSignatureField", "Signaturfeld platzieren")'> title='@L("SenderEditor_PlaceSignatureField", "Signaturfeld platzieren")'>
<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" fill="currentColor" viewBox="0 0 16 16"> <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" fill="currentColor" viewBox="0 0 16 16">
<path d="M12.146.146a.5.5 0 0 1 .708 0l3 3a.5.5 0 0 1 0 .708l-10 10a.5.5 0 0 1-.168.11l-5 2a.5.5 0 0 1-.65-.65l2-5a.5.5 0 0 1 .11-.168l10-10z" /> <path d="M12.146.146a.5.5 0 0 1 .708 0l3 3a.5.5 0 0 1 0 .708l-10 10a.5.5 0 0 1-.168.11l-5 2a.5.5 0 0 1-.65-.65l2-5a.5.5 0 0 1 .11-.168l10-10z" />
@@ -255,7 +251,7 @@
</div> </div>
@* Right: Buttons *@ @* Right: Buttons *@
<div style="display: flex; align-items: center; gap: 0.5rem; flex-shrink: 0;"> <div class="sender-editor-actions">
<button class="pdf-toolbar__btn pdf-toolbar__btn--reset" <button class="pdf-toolbar__btn pdf-toolbar__btn--reset"
@onclick="Cancel" @onclick="Cancel"
@@ -264,14 +260,12 @@
</button> </button>
@* PDF Upload *@ @* PDF Upload *@
<label class="pdf-toolbar__btn" <label class="pdf-toolbar__btn sender-editor-upload-btn @((!_isPageReady || _isPdfUploadInProgress) ? "sender-editor-upload-btn--disabled" : string.Empty)"
title='@L("UploadPdf", "PDF hochladen")' title='@L("UploadPdf", "PDF hochladen")'
style="cursor: @((_isPageReady && !_isPdfUploadInProgress) ? "pointer" : "not-allowed"); >
opacity:@((_isPageReady && !_isPdfUploadInProgress) ? "1" : "0.6");
display: inline-flex; align-items: center; gap: 0.3rem; padding: 0.3rem 0.75rem; font-size: 0.75rem; font-weight: 500;">
@if (_isPdfUploadInProgress) @if (_isPdfUploadInProgress)
{ {
<span class="spinner-border spinner-border-sm" role="status" style="width:0.8rem;height:0.8rem;border-width:2px;"></span> <span class="spinner-border spinner-border-sm sender-editor-spinner" role="status"></span>
} }
else else
{ {
@@ -299,7 +293,7 @@
<InputFile OnChange="OnPdfFileSelectedAsync" <InputFile OnChange="OnPdfFileSelectedAsync"
accept=".pdf" accept=".pdf"
disabled="@(!_isPageReady || _isPdfUploadInProgress)" disabled="@(!_isPageReady || _isPdfUploadInProgress)"
style="display: none;" /> class="sender-editor-hidden-input" />
</label> </label>
@if (_pdfLoaded && _signatureFields.Count > 0) @if (_pdfLoaded && _signatureFields.Count > 0)
@@ -320,8 +314,7 @@
title='@L("Save", "Speichern")'> title='@L("Save", "Speichern")'>
@if (_isSaving) @if (_isSaving)
{ {
<span class="spinner-border spinner-border-sm me-1" role="status" <span class="spinner-border spinner-border-sm me-1 sender-editor-spinner" role="status"></span>
style="width:0.8rem;height:0.8rem;border-width:2px;"></span>
} }
else else
{ {
@@ -336,12 +329,10 @@
<button class="pdf-toolbar__btn pdf-toolbar__btn--success" <button class="pdf-toolbar__btn pdf-toolbar__btn--success"
@onclick="SendAsync" @onclick="SendAsync"
disabled="@_isSaving" disabled="@_isSaving"
title='@L("SendEnvelope", "Umschlag senden")' title='@L("SendEnvelope", "Umschlag senden")'>
style="background: linear-gradient(135deg,#059669,#047857); color:#fff; border-radius:6px; padding:0.3rem 0.75rem; font-size:0.75rem; font-weight:600; border:none;">
@if (_isSaving) @if (_isSaving)
{ {
<span class="spinner-border spinner-border-sm me-1" role="status" <span class="spinner-border spinner-border-sm me-1 sender-editor-spinner" role="status"></span>
style="width:0.8rem;height:0.8rem;border-width:2px;"></span>
} }
else else
{ {
@@ -357,11 +348,9 @@
@* Placement mode hint bar *@ @* Placement mode hint bar *@
@if (_pendingReceiverForPlacement is not null) @if (_pendingReceiverForPlacement is not null)
{ {
<div style="background: @_pendingReceiverForPlacement.Color; color: white; font-size: 0.75rem; font-weight: 500; <div class="sender-editor-placement-hint" style="--placement-color:@_pendingReceiverForPlacement.Color;">
padding: 0.3rem 1.5rem; text-align: center; letter-spacing: 0.01em;">
📌 @L("SenderEditor_ClickDocumentFor", "Klicken Sie auf die Stelle im Dokument für") <strong>@_pendingReceiverForPlacement.FullName</strong>. 📌 @L("SenderEditor_ClickDocumentFor", "Klicken Sie auf die Stelle im Dokument für") <strong>@_pendingReceiverForPlacement.FullName</strong>.
&nbsp;<button @onclick="CancelPlacement" &nbsp;<button @onclick="CancelPlacement" class="sender-editor-placement-cancel">
style="background:none;border:none;color:white;cursor:pointer;font-size:0.75rem;text-decoration:underline;padding:0;">
@L("Cancel", "Abbrechen") @L("Cancel", "Abbrechen")
</button> </button>
</div> </div>
@@ -369,30 +358,25 @@
</div> </div>
@* ── Content ── *@ @* ── Content ── *@
<div class="envelope-content" style="padding: 0; overflow: hidden;"> <div class="envelope-content sender-editor-content">
@if (!_pdfLoaded) @if (!_pdfLoaded)
{ {
@* Empty state *@ @* Empty state *@
<div class="d-flex justify-content-center align-items-center h-100"> <div class="d-flex justify-content-center align-items-center h-100">
<div class="text-center" style="max-width: 420px;"> <div class="text-center sender-editor-empty-state">
<div style="width: 72px; height: 72px; background: rgba(255,255,255,0.15); <div class="sender-editor-empty-state__icon-wrap">
border-radius: 50%; display: flex; align-items: center;
justify-content: center; margin: 0 auto 1.25rem;">
<svg xmlns="http://www.w3.org/2000/svg" width="36" height="36" fill="white" viewBox="0 0 16 16"> <svg xmlns="http://www.w3.org/2000/svg" width="36" height="36" fill="white" viewBox="0 0 16 16">
<path d="M14 4.5V14a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V2a2 2 0 0 1 2-2h5.5L14 4.5zm-3 0A1.5 1.5 0 0 1 9.5 3V1H4a1 1 0 0 0-1 1v12a1 1 0 0 0 1 1h8a1 1 0 0 0 1-1V4.5h-2z" /> <path d="M14 4.5V14a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V2a2 2 0 0 1 2-2h5.5L14 4.5zm-3 0A1.5 1.5 0 0 1 9.5 3V1H4a1 1 0 0 0-1 1v12a1 1 0 0 0 1 1h8a1 1 0 0 0 1-1V4.5h-2z" />
</svg> </svg>
</div> </div>
<h5 class="text-white mb-2">@L("SenderEditor_NoDocumentLoaded", "Kein Dokument geladen")</h5> <h5 class="text-white mb-2">@L("SenderEditor_NoDocumentLoaded", "Kein Dokument geladen")</h5>
<p class="text-white mb-4" style="opacity: 0.75; font-size: 0.85rem;"> <p class="text-white mb-4 sender-editor-empty-state__description">
@L("SenderEditor_UploadPdfToPlaceFields", "Laden Sie eine PDF-Datei hoch, um Signaturfelder zu platzieren.") @L("SenderEditor_UploadPdfToPlaceFields", "Laden Sie eine PDF-Datei hoch, um Signaturfelder zu platzieren.")
</p> </p>
<label class="btn btn-light btn-sm" <label class="btn btn-light btn-sm sender-editor-empty-state__upload @((!_isPageReady || _isPdfUploadInProgress) ? "sender-editor-empty-state__upload--disabled" : string.Empty)">
style="cursor: @((_isPageReady && !_isPdfUploadInProgress) ? "pointer" : "not-allowed");
opacity:@((_isPageReady && !_isPdfUploadInProgress) ? "1" : "0.8");
font-weight: 500;">
@if (_isPdfUploadInProgress) @if (_isPdfUploadInProgress)
{ {
<span class="spinner-border spinner-border-sm me-1" role="status" style="width:0.8rem;height:0.8rem;border-width:2px;"></span> <span class="spinner-border spinner-border-sm me-1 sender-editor-spinner" role="status"></span>
} }
else else
{ {
@@ -420,7 +404,7 @@
<InputFile OnChange="OnPdfFileSelectedAsync" <InputFile OnChange="OnPdfFileSelectedAsync"
accept=".pdf" accept=".pdf"
disabled="@(!_isPageReady || _isPdfUploadInProgress)" disabled="@(!_isPageReady || _isPdfUploadInProgress)"
style="display: none;" /> class="sender-editor-hidden-input" />
</label> </label>
</div> </div>
</div> </div>
@@ -447,6 +431,7 @@
} }
</div> </div>
</div> </div>
</DxLoadingPanel>
<DxPopup @bind-Visible="_receiverPopupVisible" <DxPopup @bind-Visible="_receiverPopupVisible"
HeaderText='@L("AddReceiver", "Empfänger hinzufügen")' HeaderText='@L("AddReceiver", "Empfänger hinzufügen")'
@@ -544,18 +529,17 @@
<BodyContentTemplate> <BodyContentTemplate>
@if (_saveErrorMessage is null) @if (_saveErrorMessage is null)
{ {
<div style="display:flex;align-items:flex-start;gap:1rem;padding:0.5rem 0;"> <div class="sender-editor-save-result">
<div style="flex-shrink:0;width:40px;height:40px;background:#d1fae5;border-radius:50%; <div class="sender-editor-save-result__icon sender-editor-save-result__icon--success">
display:flex;align-items:center;justify-content:center;">
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" fill="#065f46" viewBox="0 0 16 16"> <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" fill="#065f46" viewBox="0 0 16 16">
<path d="M13.854 3.646a.5.5 0 0 1 0 .708l-7 7a.5.5 0 0 1-.708 0l-3.5-3.5a.5.5 0 1 1 .708-.708L6.5 10.293l6.646-6.647a.5.5 0 0 1 .708 0z" /> <path d="M13.854 3.646a.5.5 0 0 1 0 .708l-7 7a.5.5 0 0 1-.708 0l-3.5-3.5a.5.5 0 1 1 .708-.708L6.5 10.293l6.646-6.647a.5.5 0 0 1 .708 0z" />
</svg> </svg>
</div> </div>
<div> <div>
<p style="margin:0 0 0.4rem;font-weight:600;color:#1f2937;font-size:0.95rem;"> <p class="sender-editor-save-result__title">
@_saveSuccessTitle @_saveSuccessTitle
</p> </p>
<p style="margin:0;color:#6b7280;font-size:0.85rem;line-height:1.5;"> <p class="sender-editor-save-result__message">
@_saveSuccessBody @_saveSuccessBody
</p> </p>
</div> </div>
@@ -563,19 +547,18 @@
} }
else else
{ {
<div style="display:flex;align-items:flex-start;gap:1rem;padding:0.5rem 0;"> <div class="sender-editor-save-result">
<div style="flex-shrink:0;width:40px;height:40px;background:#fee2e2;border-radius:50%; <div class="sender-editor-save-result__icon sender-editor-save-result__icon--error">
display:flex;align-items:center;justify-content:center;">
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" fill="#991b1b" viewBox="0 0 16 16"> <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" fill="#991b1b" viewBox="0 0 16 16">
<path d="M8 15A7 7 0 1 1 8 1a7 7 0 0 1 0 14zm0 1A8 8 0 1 0 8 0a8 8 0 0 0 0 16z" /> <path d="M8 15A7 7 0 1 1 8 1a7 7 0 0 1 0 14zm0 1A8 8 0 1 0 8 0a8 8 0 0 0 0 16z" />
<path d="M7.002 11a1 1 0 1 1 2 0 1 1 0 0 1-2 0zM7.1 4.995a.905.905 0 1 1 1.8 0l-.35 3.507a.552.552 0 0 1-1.1 0L7.1 4.995z" /> <path d="M7.002 11a1 1 0 1 1 2 0 1 1 0 0 1-2 0zM7.1 4.995a.905.905 0 1 1 1.8 0l-.35 3.507a.552.552 0 0 1-1.1 0L7.1 4.995z" />
</svg> </svg>
</div> </div>
<div> <div>
<p style="margin:0 0 0.4rem;font-weight:600;color:#1f2937;font-size:0.95rem;"> <p class="sender-editor-save-result__title">
@L("SenderEditor_ErrorCreatingEnvelope", "Fehler beim Erstellen des Umschlags") @L("SenderEditor_ErrorCreatingEnvelope", "Fehler beim Erstellen des Umschlags")
</p> </p>
<p style="margin:0;color:#6b7280;font-size:0.85rem;line-height:1.5;word-break:break-word;"> <p class="sender-editor-save-result__message sender-editor-save-result__message--break">
@_saveErrorMessage @_saveErrorMessage
</p> </p>
</div> </div>
@@ -583,30 +566,25 @@
} }
</BodyContentTemplate> </BodyContentTemplate>
<FooterContentTemplate> <FooterContentTemplate>
<div style="display:flex;gap:0.5rem;justify-content:flex-end;width:100%;padding:0.5rem 0;"> <div class="sender-editor-save-actions">
@if (_saveErrorMessage is null) @if (_saveErrorMessage is null)
{ {
<button class="btn btn-outline-secondary" <button class="btn btn-outline-secondary sender-editor-save-actions__secondary"
@onclick="() => _savePopupVisible = false" @onclick="() => _savePopupVisible = false">
style="border-radius:6px;padding:0.5rem 1.25rem;font-weight:500;">
@L("Close", "Schließen") @L("Close", "Schließen")
</button> </button>
@if (_saveNavigateToDashboard) @if (_saveNavigateToDashboard)
{ {
<button class="btn btn-primary" <button class="btn btn-primary sender-editor-save-actions__primary" @onclick="GoToDashboard">
@onclick="GoToDashboard"
style="background:linear-gradient(135deg,#059669,#047857);border:none;border-radius:6px;
padding:0.5rem 1.5rem;font-weight:600;color:#fff;">
@L("SenderEditor_ToOverview", "Zur Übersicht") @L("SenderEditor_ToOverview", "Zur Übersicht")
</button> </button>
} }
} }
else else
{ {
<button class="btn btn-outline-secondary" <button class="btn btn-outline-secondary sender-editor-save-actions__secondary"
@onclick="() => _savePopupVisible = false" @onclick="() => _savePopupVisible = false">
style="border-radius:6px;padding:0.5rem 1.25rem;font-weight:500;">
@L("Close", "Schließen") @L("Close", "Schließen")
</button> </button>
} }
@@ -618,6 +596,9 @@
[SupplyParameterFromQuery(Name = "envelopeId")] [SupplyParameterFromQuery(Name = "envelopeId")]
public int? EnvelopeId { get; set; } public int? EnvelopeId { get; set; }
[SupplyParameterFromQuery(Name = "bootstrapToken")]
public string? BootstrapToken { get; set; }
// ── Constants ── // ── Constants ──
// Signature field size in PDF points (fixed): 1.77" × 1.96" // Signature field size in PDF points (fixed): 1.77" × 1.96"
const double SigWidthPt = 1.77 * 72; // 127.44 pt const double SigWidthPt = 1.77 * 72; // 127.44 pt
@@ -638,6 +619,8 @@
int? _loadedEnvelopeId; int? _loadedEnvelopeId;
int? _editingEnvelopeId; int? _editingEnvelopeId;
bool _isLoadingEnvelopeForEdit; bool _isLoadingEnvelopeForEdit;
bool _bootstrapApplied;
string? _pendingBootstrapToken;
List<SignatureFieldDraft> _signatureFields = []; List<SignatureFieldDraft> _signatureFields = [];
ReceiverDraft? _pendingReceiverForPlacement; // Set when user clicks "Signatur hinzufügen" ReceiverDraft? _pendingReceiverForPlacement; // Set when user clicks "Signatur hinzufügen"
@@ -658,6 +641,7 @@
string _saveSuccessTitle = "Vorgang erfolgreich abgeschlossen."; string _saveSuccessTitle = "Vorgang erfolgreich abgeschlossen.";
string _saveSuccessBody = string.Empty; string _saveSuccessBody = string.Empty;
bool _saveNavigateToDashboard = false; bool _saveNavigateToDashboard = false;
bool _saveDraftAfterBootstrap;
// ── Envelope metadata ── // ── Envelope metadata ──
string _envelopeTitle = string.Empty; string _envelopeTitle = string.Empty;
@@ -692,6 +676,7 @@
static readonly System.ComponentModel.DataAnnotations.EmailAddressAttribute ReceiverEmailValidator = new(); static readonly System.ComponentModel.DataAnnotations.EmailAddressAttribute ReceiverEmailValidator = new();
bool IsEditMode => EnvelopeId.HasValue && EnvelopeId.Value > 0; bool IsEditMode => EnvelopeId.HasValue && EnvelopeId.Value > 0;
bool IsBootstrapLoading => !IsEditMode && !_bootstrapApplied;
// ── Lifecycle ── // ── Lifecycle ──
@@ -732,19 +717,115 @@
return; return;
} }
if (IsEditMode) if (IsEditMode || _bootstrapApplied)
return;
if (string.IsNullOrWhiteSpace(BootstrapToken))
{
NavigationManager.NavigateTo("/sender", replace: true);
return; return;
} }
protected override Task OnAfterRenderAsync(bool firstRender) _pendingBootstrapToken = BootstrapToken;
}
async Task TryApplyBootstrapAsync(string token)
{
var payload = await CreateEnvelopeBootstrapStorageService.ConsumeAsync(token);
_bootstrapApplied = true;
if (payload is null)
{
NavigationManager.NavigateTo("/sender", replace: true);
return;
}
_envelopeTitle = payload.Title ?? string.Empty;
_envelopeMessage = payload.Message ?? string.Empty;
_selectedEnvelopeTypeId = payload.EnvelopeTypeId;
_language = string.IsNullOrWhiteSpace(payload.Language) ? "de-DE" : payload.Language;
_useAccessCode = payload.UseAccessCode;
_tfaEnabled = payload.TFAEnabled;
_certificationType = payload.CertificationType;
_finalEmailToCreator = payload.FinalEmailToCreator;
_finalEmailToReceivers = payload.FinalEmailToReceivers;
_sendReminderEmails = payload.SendReminderEmails;
_firstReminderDays = payload.FirstReminderDays;
_reminderIntervalDays = payload.ReminderIntervalDays;
_expiresWhenDays = payload.ExpiresWhenDays;
_expiresWarningWhenDays = payload.ExpiresWarningWhenDays;
NormalizeSettings();
_receivers = payload.Receivers
.Select((receiver, index) => new ReceiverDraft(
Guid.NewGuid(),
receiver.FullName,
receiver.EmailAddress,
string.Empty,
ReceiverPalette[index % ReceiverPalette.Length]))
.ToList();
_originalPdfBytes = payload.DocumentBytes;
_fileName = string.IsNullOrWhiteSpace(payload.DocumentFileName) ? "document.pdf" : payload.DocumentFileName;
_pdfLoaded = _originalPdfBytes is { Length: > 0 };
_signatureFields.Clear();
_pendingReceiverForPlacement = null;
_saveDraftAfterBootstrap = true;
if (_pdfLoaded && _originalPdfBytes is not null)
{
try
{
_pagePreviews = (await PdfRenderService.RenderPagesAsync(_originalPdfBytes))
.OrderBy(p => p.PageNumber)
.ToList();
}
catch (Exception ex)
{
Logger.LogWarning(ex, "Failed to render bootstrap PDF previews.");
_pagePreviews = [];
}
_pageCount = _pagePreviews.Count > 0
? _pagePreviews.Count
: EstimatePdfPageCount(_originalPdfBytes) ?? 1;
}
else
{
_pagePreviews = [];
_pageCount = 0;
}
}
protected override async Task OnAfterRenderAsync(bool firstRender)
{ {
if (firstRender) if (firstRender)
{ {
_isPageReady = true; _isPageReady = true;
StateHasChanged(); await InvokeAsync(StateHasChanged);
}
if (!OperatingSystem.IsBrowser())
return;
if (!IsEditMode && !_bootstrapApplied && !string.IsNullOrWhiteSpace(_pendingBootstrapToken))
{
var token = _pendingBootstrapToken;
_pendingBootstrapToken = null;
await TryApplyBootstrapAsync(token);
await InvokeAsync(StateHasChanged);
return;
}
if (_saveDraftAfterBootstrap && !_isSaving)
{
_saveDraftAfterBootstrap = false;
await SaveDraftAndStayOnEditorAsync();
return;
} }
return Task.CompletedTask;
} }
async Task LoadEnvelopeForEditAsync(int envelopeId) async Task LoadEnvelopeForEditAsync(int envelopeId)
@@ -1137,12 +1218,17 @@
} }
async Task SaveDraftAsync() async Task SaveDraftAsync()
{
await SaveDraftCoreAsync(navigateToDashboard: true);
}
async Task<int?> SaveDraftCoreAsync(bool navigateToDashboard)
{ {
if (!ValidateSettings(out var settingsError)) if (!ValidateSettings(out var settingsError))
{ {
_saveErrorMessage = settingsError; _saveErrorMessage = settingsError;
_savePopupVisible = true; _savePopupVisible = true;
return; return null;
} }
_isSaving = true; _isSaving = true;
@@ -1163,25 +1249,37 @@
_loadedEnvelopeId = result.Id; _loadedEnvelopeId = result.Id;
_editingEnvelopeId = result.Id; _editingEnvelopeId = result.Id;
if (previousEnvelopeId != result.Id) if (navigateToDashboard)
{
NavigationManager.NavigateTo("/sender", forceLoad: false);
}
else if (previousEnvelopeId != result.Id)
{ {
NavigationManager.NavigateTo($"/sender/editor?envelopeId={result.Id}", forceLoad: false); NavigationManager.NavigateTo($"/sender/editor?envelopeId={result.Id}", forceLoad: false);
} }
NavigationManager.NavigateTo("/sender", forceLoad: false); return result.Id;
} }
catch (Exception ex) catch (Exception ex)
{ {
Logger.LogError(ex, "[SenderEditor] Failed to save draft"); Logger.LogError(ex, "[SenderEditor] Failed to save draft");
_saveErrorMessage = ex.Message; _saveErrorMessage = ex.Message;
_savePopupVisible = true; _savePopupVisible = true;
return null;
} }
finally finally
{ {
_isSaving = false; _isSaving = false;
await InvokeAsync(StateHasChanged);
} }
} }
async Task SaveDraftAndStayOnEditorAsync()
{
Logger.LogInformation("[SenderEditor] Trigger bootstrap draft save.");
await SaveDraftCoreAsync(navigateToDashboard: false);
}
// ── Send envelope ── // ── Send envelope ──
async Task SendAsync() async Task SendAsync()
{ {
@@ -1586,7 +1684,11 @@
string L(string key, string fallback) string L(string key, string fallback)
{ {
var value = UiLocalizer[key]; var modelValue = ModelLocalizer[key];
return value.ResourceNotFound ? fallback : value.Value; if (!modelValue.ResourceNotFound)
return modelValue.Value;
var uiValue = UiLocalizer[key];
return uiValue.ResourceNotFound ? fallback : uiValue.Value;
} }
} }

View File

@@ -9,15 +9,18 @@
@using EnvelopeGenerator.Application.Common.Dto.History @using EnvelopeGenerator.Application.Common.Dto.History
@using EnvelopeGenerator.Application.Resources @using EnvelopeGenerator.Application.Resources
@using EnvelopeGenerator.Domain.Resources @using EnvelopeGenerator.Domain.Resources
@using EnvelopeGenerator.Server.Client.Components.Sender
@using Microsoft.Extensions.Localization @using Microsoft.Extensions.Localization
@inject EnvelopeGenerator.Server.Client.Services.EnvelopeService EnvelopeService @inject EnvelopeGenerator.Server.Client.Services.EnvelopeService EnvelopeService
@inject EnvelopeGenerator.Server.Client.Services.DocumentService DocumentService @inject EnvelopeGenerator.Server.Client.Services.DocumentService DocumentService
@inject EnvelopeGenerator.Server.Client.Services.PdfRenderService PdfRenderService @inject EnvelopeGenerator.Server.Client.Services.PdfRenderService PdfRenderService
@inject EnvelopeGenerator.Server.Client.Services.EnvelopeTypeService EnvelopeTypeService
@inject EnvelopeGenerator.Server.Client.Services.AuthService AuthService @inject EnvelopeGenerator.Server.Client.Services.AuthService AuthService
@inject EnvelopeGenerator.Server.Client.Services.ThemeService ThemeService @inject EnvelopeGenerator.Server.Client.Services.ThemeService ThemeService
@inject EnvelopeGenerator.Server.Client.Services.UserPreferencesService UserPreferencesService @inject EnvelopeGenerator.Server.Client.Services.UserPreferencesService UserPreferencesService
@inject EnvelopeGenerator.Server.Client.Services.CustomImagesService CustomImagesService @inject EnvelopeGenerator.Server.Client.Services.CustomImagesService CustomImagesService
@inject ILogger<EnvelopeSenderPage> Logger @inject EnvelopeGenerator.Server.Client.Services.CreateEnvelopeBootstrapStorageService CreateEnvelopeBootstrapStorageService
@inject ILogger<SenderPage> Logger
@inject NavigationManager Navigation @inject NavigationManager Navigation
@inject IJSRuntime JSRuntime @inject IJSRuntime JSRuntime
@inject AppVersionService AppVersion @inject AppVersionService AppVersion
@@ -414,6 +417,11 @@
</div> </div>
<CreateEnvelopeWizardPopup Visible="@_createWizardVisible"
VisibleChanged="OnCreateWizardVisibleChangedAsync"
EnvelopeTypes="@_envelopeTypes"
StartEditorRequested="StartEditorFromWizardAsync" />
@* ── PDF Vorschau Popup ────────────────────────────────────────────────── *@ @* ── PDF Vorschau Popup ────────────────────────────────────────────────── *@
<DxPopup @bind-Visible="@_previewVisible" <DxPopup @bind-Visible="@_previewVisible"
HeaderText="@($"{L("Preview", "Vorschau")} — {_selectedEnvelope?.Title} (#{_selectedEnvelope?.Id})")" HeaderText="@($"{L("Preview", "Vorschau")} — {_selectedEnvelope?.Title} (#{_selectedEnvelope?.Id})")"
@@ -567,6 +575,9 @@
private string _deleteReason = string.Empty; private string _deleteReason = string.Empty;
private string? _deleteErrorMessage; private string? _deleteErrorMessage;
private bool _createWizardVisible = false;
private IReadOnlyList<EnvelopeTypeDto> _envelopeTypes = [];
// Stable keys used to store/restore each tab's layout in UserPreferences.GridLayouts // Stable keys used to store/restore each tab's layout in UserPreferences.GridLayouts
private const string GridKeyActive = "sender.active-envelopes"; private const string GridKeyActive = "sender.active-envelopes";
private const string GridKeyCompleted = "sender.completed-envelopes"; private const string GridKeyCompleted = "sender.completed-envelopes";
@@ -596,6 +607,16 @@
_appLogo = logos.App; _appLogo = logos.App;
_companyLogo = logos.Company; _companyLogo = logos.Company;
try
{
_envelopeTypes = (await EnvelopeTypeService.GetAsync()).ToList();
}
catch (Exception ex)
{
Logger.LogWarning(ex, "Failed to load envelope types for create wizard.");
_envelopeTypes = [];
}
await LoadEnvelopesAsync(); await LoadEnvelopesAsync();
} }
@@ -693,7 +714,40 @@
void CreateEnvelope() void CreateEnvelope()
{ {
Navigation.NavigateTo("/sender/editor"); _createWizardVisible = true;
}
Task OnCreateWizardVisibleChangedAsync(bool visible)
{
_createWizardVisible = visible;
return Task.CompletedTask;
}
async Task StartEditorFromWizardAsync(CreateEnvelopeWizardResult result)
{
var payload = new CreateEnvelopeBootstrapPayload(
Title: result.Title,
Message: result.Message,
EnvelopeTypeId: result.EnvelopeTypeId,
Language: result.Language,
UseAccessCode: result.UseAccessCode,
TFAEnabled: result.TFAEnabled,
CertificationType: result.CertificationType,
FinalEmailToCreator: result.FinalEmailToCreator,
FinalEmailToReceivers: result.FinalEmailToReceivers,
SendReminderEmails: result.SendReminderEmails,
FirstReminderDays: result.FirstReminderDays,
ReminderIntervalDays: result.ReminderIntervalDays,
ExpiresWhenDays: result.ExpiresWhenDays,
ExpiresWarningWhenDays: result.ExpiresWarningWhenDays,
Receivers: result.Receivers
.Select(x => new CreateEnvelopeBootstrapReceiver(x.FullName, x.EmailAddress))
.ToList(),
DocumentBytes: result.DocumentBytes,
DocumentFileName: result.DocumentFileName);
var token = await CreateEnvelopeBootstrapStorageService.StoreAsync(payload);
Navigation.NavigateTo($"/sender/editor?bootstrapToken={token}");
} }
void EditEnvelope() void EditEnvelope()

View File

@@ -45,6 +45,7 @@ builder.Services.AddScoped<EnvelopeTypeService>();
builder.Services.AddScoped<LocalizationService>(); builder.Services.AddScoped<LocalizationService>();
builder.Services.AddScoped<ReceiverService>(); builder.Services.AddScoped<ReceiverService>();
builder.Services.AddScoped<PdfRenderService>(); builder.Services.AddScoped<PdfRenderService>();
builder.Services.AddScoped<CreateEnvelopeBootstrapStorageService>();
// UI Preferences & Theme // UI Preferences & Theme
builder.Services.AddScoped<UserPreferencesService>(); builder.Services.AddScoped<UserPreferencesService>();

View File

@@ -0,0 +1,64 @@
using System.Text.Json;
using Microsoft.JSInterop;
namespace EnvelopeGenerator.Server.Client.Services;
public sealed class CreateEnvelopeBootstrapStorageService(IJSRuntime jsRuntime)
{
private const string StorageKeyPrefix = "sender.createEnvelope.bootstrap.";
private static readonly JsonSerializerOptions JsonOptions = new(JsonSerializerDefaults.Web);
public async Task<string> StoreAsync(CreateEnvelopeBootstrapPayload payload)
{
var token = Guid.NewGuid().ToString("N");
var key = BuildStorageKey(token);
var json = JsonSerializer.Serialize(payload, JsonOptions);
await jsRuntime.InvokeVoidAsync("sessionStorage.setItem", key, json);
return token;
}
public async Task<CreateEnvelopeBootstrapPayload?> ConsumeAsync(string? token)
{
if (string.IsNullOrWhiteSpace(token))
return null;
var key = BuildStorageKey(token);
var raw = await jsRuntime.InvokeAsync<string?>("sessionStorage.getItem", key);
await jsRuntime.InvokeVoidAsync("sessionStorage.removeItem", key);
if (string.IsNullOrWhiteSpace(raw))
return null;
try
{
return JsonSerializer.Deserialize<CreateEnvelopeBootstrapPayload>(raw, JsonOptions);
}
catch
{
return null;
}
}
private static string BuildStorageKey(string token) => $"{StorageKeyPrefix}{token}";
}
public sealed record CreateEnvelopeBootstrapPayload(
string Title,
string Message,
int? EnvelopeTypeId,
string Language,
bool UseAccessCode,
bool TFAEnabled,
int CertificationType,
int FinalEmailToCreator,
int FinalEmailToReceivers,
bool SendReminderEmails,
int FirstReminderDays,
int ReminderIntervalDays,
int ExpiresWhenDays,
int ExpiresWarningWhenDays,
IReadOnlyList<CreateEnvelopeBootstrapReceiver> Receivers,
byte[]? DocumentBytes,
string? DocumentFileName);
public sealed record CreateEnvelopeBootstrapReceiver(string FullName, string EmailAddress);

View File

@@ -1,5 +1,6 @@
using System.Net.Http.Json; using System.Net.Http.Json;
using System.Text.Json; using System.Text.Json;
using EnvelopeGenerator.Application.Common.Dto.Receiver;
namespace EnvelopeGenerator.Server.Client.Services; namespace EnvelopeGenerator.Server.Client.Services;
@@ -26,4 +27,21 @@ public class ReceiverService(IHttpClientFactory httpClientFactory)
var emails = await response.Content.ReadFromJsonAsync<List<string>>(JsonOptions, cancel); var emails = await response.Content.ReadFromJsonAsync<List<string>>(JsonOptions, cancel);
return emails ?? []; return emails ?? [];
} }
/// <summary>
/// Fetches recent receiver suggestions for the authenticated sender.
/// Calls GET /api/EnvelopeReceiver/recent-suggestions?take={take}.
/// </summary>
public async Task<IReadOnlyList<RecentReceiverSuggestionDto>> GetRecentReceiverSuggestionsAsync(int take = 20, CancellationToken cancel = default)
{
using var http = httpClientFactory.CreateClient("EnvelopeGenerator.Server");
var url = $"/api/EnvelopeReceiver/recent-suggestions?take={take}";
var response = await http.GetAsync(url, cancel);
if (!response.IsSuccessStatusCode)
return [];
var suggestions = await response.Content.ReadFromJsonAsync<List<RecentReceiverSuggestionDto>>(JsonOptions, cancel);
return suggestions ?? [];
}
} }

View File

@@ -112,6 +112,20 @@ public class EnvelopeReceiverController : ControllerBase
return name is null ? NotFound() : Ok(name); return name is null ? NotFound() : Ok(name);
} }
/// <summary>
/// Returns recent receiver suggestions for the authenticated sender.
/// </summary>
/// <param name="query">Suggestion query options (take 3..5 is applied in handler).</param>
/// <param name="cancel">Cancellation token.</param>
/// <returns>List of recent distinct receiver suggestions.</returns>
[Authorize(AuthenticationSchemes = AuthScheme.Sender)]
[HttpGet("recent-suggestions")]
public async Task<IActionResult> GetRecentSuggestions([FromQuery] ReadRecentReceiverSuggestionsQuery query, CancellationToken cancel)
{
var result = await _mediator.Send(query.ForSender(User.GetUsername()), cancel);
return Ok(result);
}
/// <summary> /// <summary>
/// Datenübertragungsobjekt mit Informationen zu Umschlägen, Empfängern und Unterschriften. /// Datenübertragungsobjekt mit Informationen zu Umschlägen, Empfängern und Unterschriften.
/// </summary> /// </summary>

View File

@@ -0,0 +1,18 @@
using EnvelopeGenerator.Application.Common.Interfaces.Services;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace EnvelopeGenerator.Server.Controllers;
[ApiController]
[Route("api/[controller]")]
public class HealthController(IPkcs11SelfTestStatusProvider pkcs11StatusProvider) : ControllerBase
{
[AllowAnonymous]
[HttpGet("crypt")]
public IActionResult GetCryptHealth()
{
var status = pkcs11StatusProvider.GetStatus();
return Ok(status);
}
}

View File

@@ -0,0 +1,78 @@
using EnvelopeGenerator.Application.Common.Dto;
using EnvelopeGenerator.Application.Common.Enums;
using EnvelopeGenerator.Application.Common.Interfaces.Services;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace EnvelopeGenerator.Server.Controllers;
[ApiController]
[Route("api/[controller]")]
public class PdfSignatureController(IPdfDigitalSignatureService signatureService) : ControllerBase
{
public sealed class SignPdfForm
{
public IFormFile? File { get; set; }
public string? UUID { get; set; }
public string? Name { get; set; }
public string? Reason { get; set; }
public string? Location { get; set; }
public string? Email { get; set; }
public string? Phone { get; set; }
}
public sealed class CheckPdfSignatureForm
{
public IFormFile? File { get; set; }
}
[AllowAnonymous]
[HttpPost("sign")]
[Consumes("multipart/form-data")]
public async Task<IActionResult> Sign([FromForm] SignPdfForm request, CancellationToken cancel)
{
var file = request.File;
if (file is null || file.Length == 0)
return BadRequest("PDF file is required.");
if (!file.FileName.EndsWith(".pdf", StringComparison.OrdinalIgnoreCase))
return BadRequest("Only PDF files are supported.");
var signOptions = new PdfSignOptionsDto
{
UUID = request.UUID,
Name = request.Name,
Reason = request.Reason,
Location = request.Location,
Email = request.Email,
Phone = request.Phone,
CertificationLevel = PdfSignatureCertificationLevel.FormFillingAndAnnotations
};
await using var input = file.OpenReadStream();
await using var output = new MemoryStream();
await signatureService.SignPdfAsync(input, output, signOptions, cancel);
output.Position = 0;
var fileName = Path.GetFileNameWithoutExtension(file.FileName);
return File(output, "application/pdf", $"{fileName}-signed.pdf");
}
[AllowAnonymous]
[HttpPost("is-signed")]
[Consumes("multipart/form-data")]
public async Task<IActionResult> IsSigned([FromForm] CheckPdfSignatureForm request, CancellationToken cancel)
{
var file = request.File;
if (file is null || file.Length == 0)
return BadRequest("PDF file is required.");
if (!file.FileName.EndsWith(".pdf", StringComparison.OrdinalIgnoreCase))
return BadRequest("Only PDF files are supported.");
await using var input = file.OpenReadStream();
var result = await signatureService.CheckPdfSignatureAsync(input, cancel);
return Ok(result);
}
}

View File

@@ -10,9 +10,9 @@
<Authors>Digital Data GmbH</Authors> <Authors>Digital Data GmbH</Authors>
<Company>Digital Data GmbH</Company> <Company>Digital Data GmbH</Company>
<Product>EnvelopeGenerator.Server</Product> <Product>EnvelopeGenerator.Server</Product>
<Version>1.4.0-beta</Version> <Version>1.5.0-beta</Version>
<FileVersion>1.4.0.0</FileVersion> <FileVersion>1.5.0.0</FileVersion>
<AssemblyVersion>1.4.0.0</AssemblyVersion> <AssemblyVersion>1.5.0.0</AssemblyVersion>
<Copyright>Copyright © 2026 Digital Data GmbH. All rights reserved.</Copyright> <Copyright>Copyright © 2026 Digital Data GmbH. All rights reserved.</Copyright>
<DocumentationFile>bin\$(Configuration)\$(TargetFramework)\$(AssemblyName).xml</DocumentationFile> <DocumentationFile>bin\$(Configuration)\$(TargetFramework)\$(AssemblyName).xml</DocumentationFile>
</PropertyGroup> </PropertyGroup>
@@ -22,6 +22,7 @@
<ProjectReference Include="..\..\EnvelopeGenerator.Application\EnvelopeGenerator.Application.csproj" /> <ProjectReference Include="..\..\EnvelopeGenerator.Application\EnvelopeGenerator.Application.csproj" />
<ProjectReference Include="..\..\EnvelopeGenerator.Domain\EnvelopeGenerator.Domain.csproj" /> <ProjectReference Include="..\..\EnvelopeGenerator.Domain\EnvelopeGenerator.Domain.csproj" />
<ProjectReference Include="..\..\EnvelopeGenerator.Infrastructure.Doc\EnvelopeGenerator.Infrastructure.Doc.csproj" /> <ProjectReference Include="..\..\EnvelopeGenerator.Infrastructure.Doc\EnvelopeGenerator.Infrastructure.Doc.csproj" />
<ProjectReference Include="..\..\EnvelopeGenerator.Infrastructure.Crypt\EnvelopeGenerator.Infrastructure.Crypt.csproj" />
<ProjectReference Include="..\..\EnvelopeGenerator.Infrastructure\EnvelopeGenerator.Infrastructure.csproj" /> <ProjectReference Include="..\..\EnvelopeGenerator.Infrastructure\EnvelopeGenerator.Infrastructure.csproj" />
<ProjectReference Include="..\..\EnvelopeGenerator.PdfEditor\EnvelopeGenerator.PdfEditor.csproj" /> <ProjectReference Include="..\..\EnvelopeGenerator.PdfEditor\EnvelopeGenerator.PdfEditor.csproj" />
</ItemGroup> </ItemGroup>

View File

@@ -28,6 +28,7 @@ using EnvelopeGenerator.Server;
using DigitalData.EmailProfilerDispatcher; using DigitalData.EmailProfilerDispatcher;
using EnvelopeGenerator.Application.Common.Interfaces.Doc; using EnvelopeGenerator.Application.Common.Interfaces.Doc;
using EnvelopeGenerator.Infrastructure.Doc; using EnvelopeGenerator.Infrastructure.Doc;
using EnvelopeGenerator.Infrastructure.Crypt.DependencyInjection;
var logger = LogManager.Setup().LoadConfigurationFromAppSettings().GetCurrentClassLogger(); var logger = LogManager.Setup().LoadConfigurationFromAppSettings().GetCurrentClassLogger();
logger.Info("EnvelopeGenerator.Server logging initialized!"); logger.Info("EnvelopeGenerator.Server logging initialized!");
@@ -38,6 +39,7 @@ try
// Load YARP configuration from yarp.json // Load YARP configuration from yarp.json
builder.Configuration.AddJsonFile("yarp.json", optional: true, reloadOnChange: true); builder.Configuration.AddJsonFile("yarp.json", optional: true, reloadOnChange: true);
builder.Configuration.AddJsonFile("appsettings.Secrets.json", optional: true, reloadOnChange: true);
builder.Logging.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace); builder.Logging.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace);
@@ -346,6 +348,7 @@ try
builder.Services.AddScoped<EnvelopeGenerator.Server.Client.Services.ReceiverService>(); builder.Services.AddScoped<EnvelopeGenerator.Server.Client.Services.ReceiverService>();
builder.Services.AddScoped<EnvelopeGenerator.Server.Client.Services.PdfRenderService>(); builder.Services.AddScoped<EnvelopeGenerator.Server.Client.Services.PdfRenderService>();
builder.Services.AddScoped<EnvelopeGenerator.Server.Client.Services.EnvelopeTypeService>(); builder.Services.AddScoped<EnvelopeGenerator.Server.Client.Services.EnvelopeTypeService>();
builder.Services.AddScoped<EnvelopeGenerator.Server.Client.Services.CreateEnvelopeBootstrapStorageService>();
// Business Services (Server specific) // Business Services (Server specific)
builder.Services.AddScoped<DocumentService>(); builder.Services.AddScoped<DocumentService>();
@@ -355,6 +358,7 @@ try
builder.Services.AddScoped<SignatureService>(); builder.Services.AddScoped<SignatureService>();
builder.Services.AddScoped<SignatureCacheService>(); builder.Services.AddScoped<SignatureCacheService>();
builder.Services.AddDocInfrastructure(); builder.Services.AddDocInfrastructure();
builder.Services.AddCryptInfrastructure(config);
builder.Services.AddScoped<EnvelopeGenerator.Application.Common.Interfaces.Services.IEnvelopeMailService, EnvelopeGenerator.Application.Services.EnvelopeMailService>(); builder.Services.AddScoped<EnvelopeGenerator.Application.Common.Interfaces.Services.IEnvelopeMailService, EnvelopeGenerator.Application.Services.EnvelopeMailService>();
builder.Services.AddSingleton<AppVersionService>(); builder.Services.AddSingleton<AppVersionService>();

View File

@@ -4,6 +4,12 @@
"Default": "Information", "Default": "Information",
"Microsoft.AspNetCore": "Warning" "Microsoft.AspNetCore": "Warning"
} }
}
,
"Crypt": {
"Pkcs11": {
"AssetsRootPath": null
}
}, },
"AuthClientParams": { "AuthClientParams": {
"Url": "http://172.24.12.39:9090/auth-hub", "Url": "http://172.24.12.39:9090/auth-hub",

View File

@@ -55,6 +55,21 @@
"MainCanvasEnableHiDPI": true, "MainCanvasEnableHiDPI": true,
"ZoomStepPercentage": 5 "ZoomStepPercentage": 5
}, },
"Crypt": {
"Pkcs11": {
"AssetsRootPath": "E:\\DataFiles\\Digital Data\\EnvelopeGenerator",
"SlotId": 2021549410,
"TokenLabel": "CompanyProdToken",
"ProxySocket": "tcp://172.24.12.64:5657",
"UserPin": "",
"PrivateKeyLabel": "company-sign-key-v1",
"CertificateLabel": "company-sign-cert-v1",
"DefaultReason": null,
"ApplicationName": "signFLOW",
"UseUtcSigningTime": true,
"DefaultCertificationLevel": "NoCertification"
}
},
"PSPDFKitLicenseKey": "SXCtGGY9XA-31OGUXQK-r7c6AkdLGPm2ljuyDr1qu0kkhLvydg-Do-fxpNUF4Rq3fS_xAnZRNFRHbXpE6sQ2BMcCSVTcXVJO6tPviexjpiT-HnrDEySlUERJnnvh-tmeOWprxS6BySPnSILkmaVQtUfOIUS-cUbvvEYHTvQBKbSF8di4XHQFyfv49ihr51axm3NVV3AXwh2EiKL5C5XdqBZ4sQ4O7vXBjM2zvxdPxlxdcNYmiU83uAzw7B83O_jubPzya4CdUHh_YH7Nlp2gP56MeG1Sw2JhMtfG3Rj14Sg4ctaeL9p6AEWca5dDjJ2li5tFIV2fQSsw6A_cowLu0gtMm5i8IfJXeIcQbMC2-0wGv1oe9hZYJvFMdzhTM_FiejM0agemxt3lJyzuyP8zbBSOgp7Si6A85krLWPZptyZBTG7pp7IHboUHfPMxCXqi-zMsqewOJtQBE2mjntU-lPryKnssOpMPfswwQX7QSkJYV5EMqNmEhQX6mEkp2wcqFzMC7bJQew1aO4pOpvChUaMvb1vgRek0HxLag0nwQYX2YrYGh7F_xXJs-8HNwJe8H0-eW4x4faayCgM5rB5772CCCsD9ThZcvXFrjNHHLGJ8WuBUFm6LArvSfFQdii_7j-_sqHMpeKZt26NFgivj1A==", "PSPDFKitLicenseKey": "SXCtGGY9XA-31OGUXQK-r7c6AkdLGPm2ljuyDr1qu0kkhLvydg-Do-fxpNUF4Rq3fS_xAnZRNFRHbXpE6sQ2BMcCSVTcXVJO6tPviexjpiT-HnrDEySlUERJnnvh-tmeOWprxS6BySPnSILkmaVQtUfOIUS-cUbvvEYHTvQBKbSF8di4XHQFyfv49ihr51axm3NVV3AXwh2EiKL5C5XdqBZ4sQ4O7vXBjM2zvxdPxlxdcNYmiU83uAzw7B83O_jubPzya4CdUHh_YH7Nlp2gP56MeG1Sw2JhMtfG3Rj14Sg4ctaeL9p6AEWca5dDjJ2li5tFIV2fQSsw6A_cowLu0gtMm5i8IfJXeIcQbMC2-0wGv1oe9hZYJvFMdzhTM_FiejM0agemxt3lJyzuyP8zbBSOgp7Si6A85krLWPZptyZBTG7pp7IHboUHfPMxCXqi-zMsqewOJtQBE2mjntU-lPryKnssOpMPfswwQX7QSkJYV5EMqNmEhQX6mEkp2wcqFzMC7bJQew1aO4pOpvChUaMvb1vgRek0HxLag0nwQYX2YrYGh7F_xXJs-8HNwJe8H0-eW4x4faayCgM5rB5772CCCsD9ThZcvXFrjNHHLGJ8WuBUFm6LArvSfFQdii_7j-_sqHMpeKZt26NFgivj1A==",
"Content-Security-Policy": [ // The first format parameter {0} will be replaced by the nonce value. "Content-Security-Policy": [ // The first format parameter {0} will be replaced by the nonce value.
"default-src 'self'", "default-src 'self'",

View File

@@ -1002,6 +1002,108 @@ body.resizing {
border: 1px solid rgba(126, 34, 206, 0.12); border: 1px solid rgba(126, 34, 206, 0.12);
} }
.sender-settings-shell {
border-radius: 12px;
overflow: hidden;
}
.sender-settings-accordion {
border: 1px solid #dbe5ef;
border-radius: 12px;
background: linear-gradient(135deg, #ffffff 0%, #f8fbff 100%);
}
.sender-settings-accordion .dxbl-accordion-item {
border: none;
}
.sender-settings-accordion .dxbl-accordion-item-header {
text-transform: uppercase;
letter-spacing: 0.04em;
font-size: 0.66rem;
font-weight: 600;
color: #1f2937;
padding: 0.38rem 0.62rem;
background: rgba(124, 58, 237, 0.04);
line-height: 1.15;
}
.sender-settings-body {
display: flex;
flex-direction: column;
gap: 0.65rem;
padding: 0.25rem 0.7rem 0.7rem;
}
.sender-settings-chip {
align-self: flex-start;
font-size: 0.66rem;
font-weight: 700;
color: #5b21b6;
background: rgba(126, 34, 206, 0.1);
border: 1px solid rgba(126, 34, 206, 0.15);
border-radius: 999px;
padding: 0.12rem 0.5rem;
}
.sender-settings-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
gap: 0.5rem;
}
.sender-settings-field {
display: flex;
flex-direction: column;
gap: 0.2rem;
}
.sender-settings-label {
font-size: 0.65rem;
font-weight: 700;
color: #64748b;
letter-spacing: 0.01em;
}
.sender-settings-select,
.sender-settings-number {
font-size: 0.78rem;
border: 1px solid #d1d5db;
border-radius: 6px;
padding: 0.3rem 0.45rem;
background: #fff;
min-height: 32px;
color: #1f2937;
}
.sender-settings-number:focus,
.sender-settings-select:focus {
border-color: rgba(126, 34, 206, 0.45);
box-shadow: 0 0 0 2px rgba(126, 34, 206, 0.12);
outline: none;
}
.sender-settings-toggles {
display: flex;
flex-direction: column;
justify-content: flex-end;
gap: 0.3rem;
padding-bottom: 0.1rem;
}
.sender-settings-toggle {
display: inline-flex;
align-items: center;
gap: 0.45rem;
font-size: 0.74rem;
color: #1f2937;
min-height: 32px;
}
.sender-settings-toggles--single {
justify-content: center;
}
.sender-receivers-panel__header { .sender-receivers-panel__header {
display: flex; display: flex;
align-items: center; align-items: center;
@@ -1119,9 +1221,275 @@ body.resizing {
border-radius: 12px; border-radius: 12px;
background: rgba(255, 255, 255, 0.88); background: rgba(255, 255, 255, 0.88);
border: 1px solid rgba(126, 34, 206, 0.12); border: 1px solid rgba(126, 34, 206, 0.12);
border-left: 3px solid var(--receiver-color, #7c3aed);
box-shadow: 0 6px 16px rgba(15, 23, 42, 0.06); box-shadow: 0 6px 16px rgba(15, 23, 42, 0.06);
} }
.sender-receiver-chip__place-btn--idle {
color: var(--receiver-color, #7c3aed);
border-color: var(--receiver-color, #7c3aed);
}
.sender-receiver-chip__place-btn--active {
background: var(--receiver-color, #7c3aed);
color: #ffffff;
border-color: var(--receiver-color, #7c3aed);
}
.sender-editor-action-inner {
flex-direction: row;
align-items: center;
padding: 0.35rem 1.5rem;
gap: 0.75rem;
}
.sender-editor-main-column {
flex: 1;
min-width: 0;
display: flex;
flex-direction: column;
align-items: stretch;
gap: 0.5rem;
}
.sender-editor-meta-row {
display: flex;
align-items: flex-start;
gap: 0.5rem;
flex-wrap: wrap;
}
.sender-editor-input-field {
display: flex;
flex-direction: column;
gap: 0.2rem;
}
.sender-editor-input-field--title {
flex: 1 1 180px;
min-width: 140px;
}
.sender-editor-input-field--message {
flex: 2 1 260px;
min-width: 180px;
}
.sender-editor-label {
font-size: 0.65rem;
font-weight: 600;
color: #6b7280;
text-transform: uppercase;
letter-spacing: 0.05em;
}
.sender-editor-required-asterisk {
color: #dc2626;
}
.sender-editor-optional {
color: #6b7280;
font-weight: 400;
}
.sender-editor-text-input {
font-size: 0.78rem;
color: #1f2937;
border: 1px solid #d1d5db;
border-radius: 5px;
padding: 0.3rem 0.55rem;
outline: none;
width: 100%;
background: #fff;
}
.sender-editor-text-input--invalid {
border-color: #dc2626;
}
.sender-editor-required-text {
font-size: 0.6rem;
color: #dc2626;
}
.sender-editor-file-meta {
display: flex;
align-items: flex-end;
gap: 0.4rem;
padding-bottom: 0.05rem;
flex-shrink: 0;
}
.sender-editor-file-name {
font-size: 0.7rem;
color: #6b7280;
}
.sender-editor-signature-count {
display: inline-flex;
align-items: center;
padding: 0.125rem 0.4rem;
background: #ede9fe;
border-radius: 0.25rem;
color: #6d28d9;
font-weight: 500;
font-size: 0.7rem;
white-space: nowrap;
}
.sender-editor-actions {
display: flex;
align-items: center;
gap: 0.5rem;
flex-shrink: 0;
}
.sender-editor-upload-btn {
display: inline-flex;
align-items: center;
gap: 0.3rem;
padding: 0.3rem 0.75rem;
font-size: 0.75rem;
font-weight: 500;
cursor: pointer;
}
.sender-editor-upload-btn--disabled {
cursor: not-allowed;
opacity: 0.6;
}
.sender-editor-hidden-input {
display: none;
}
.sender-editor-spinner {
width: 0.8rem;
height: 0.8rem;
border-width: 2px;
}
.sender-editor-placement-hint {
background: var(--placement-color, #7c3aed);
color: #ffffff;
font-size: 0.75rem;
font-weight: 500;
padding: 0.3rem 1.5rem;
text-align: center;
letter-spacing: 0.01em;
}
.sender-editor-placement-cancel {
background: none;
border: none;
color: #ffffff;
cursor: pointer;
font-size: 0.75rem;
text-decoration: underline;
padding: 0;
}
.sender-editor-content {
padding: 0;
overflow: hidden;
}
.sender-editor-empty-state {
max-width: 420px;
}
.sender-editor-empty-state__icon-wrap {
width: 72px;
height: 72px;
background: rgba(255, 255, 255, 0.15);
border-radius: 50%;
display: flex;
align-items: center;
justify-content: center;
margin: 0 auto 1.25rem;
}
.sender-editor-empty-state__description {
opacity: 0.75;
font-size: 0.85rem;
}
.sender-editor-empty-state__upload {
font-weight: 500;
cursor: pointer;
}
.sender-editor-empty-state__upload--disabled {
cursor: not-allowed;
opacity: 0.8;
}
.sender-editor-save-result {
display: flex;
align-items: flex-start;
gap: 1rem;
padding: 0.5rem 0;
}
.sender-editor-save-result__icon {
flex-shrink: 0;
width: 40px;
height: 40px;
border-radius: 50%;
display: flex;
align-items: center;
justify-content: center;
}
.sender-editor-save-result__icon--success {
background: #d1fae5;
}
.sender-editor-save-result__icon--error {
background: #fee2e2;
}
.sender-editor-save-result__title {
margin: 0 0 0.4rem;
font-weight: 600;
color: #1f2937;
font-size: 0.95rem;
}
.sender-editor-save-result__message {
margin: 0;
color: #6b7280;
font-size: 0.85rem;
line-height: 1.5;
}
.sender-editor-save-result__message--break {
word-break: break-word;
}
.sender-editor-save-actions {
display: flex;
gap: 0.5rem;
justify-content: flex-end;
width: 100%;
padding: 0.5rem 0;
}
.sender-editor-save-actions__secondary {
border-radius: 6px;
padding: 0.5rem 1.25rem;
font-weight: 500;
}
.sender-editor-save-actions__primary {
background: linear-gradient(135deg, #059669, #047857);
border: none;
border-radius: 6px;
padding: 0.5rem 1.5rem;
font-weight: 600;
color: #fff;
}
.sender-receiver-chip__body { .sender-receiver-chip__body {
min-width: 0; min-width: 0;
flex: 1; flex: 1;

View File

@@ -1094,3 +1094,557 @@
[data-sf-theme="blazing-dark"] .sender-preview-error-msg { [data-sf-theme="blazing-dark"] .sender-preview-error-msg {
color: rgba(255, 255, 255, 0.50); color: rgba(255, 255, 255, 0.50);
} }
.sender-create-wizard {
display: flex;
flex-direction: column;
gap: 1rem;
padding: 0.25rem 0;
outline: none;
}
.sender-create-wizard-popup .dxbl-popup-content {
max-height: min(78vh, 760px);
overflow: auto;
}
.sender-create-wizard-popup .dxbl-popup-footer {
position: sticky;
bottom: 0;
background: rgba(255, 255, 255, 0.96);
backdrop-filter: blur(6px);
z-index: 2;
}
.sender-create-wizard__progress {
position: relative;
display: grid;
grid-template-columns: repeat(4, minmax(0, 1fr));
align-items: center;
gap: 0.5rem;
}
.sender-create-wizard__progress-track {
position: absolute;
left: 12px;
right: 12px;
top: 50%;
height: 2px;
transform: translateY(-50%);
background: rgba(126, 34, 206, 0.18);
z-index: 0;
}
.sender-create-wizard__step {
position: relative;
z-index: 1;
display: flex;
justify-content: center;
}
.sender-create-wizard__step-index {
width: 24px;
height: 24px;
border-radius: 999px;
display: inline-flex;
align-items: center;
justify-content: center;
font-size: 0.78rem;
font-weight: 700;
color: #64748b;
background: #f8fafc;
border: 1px solid rgba(126, 34, 206, 0.25);
}
.sender-create-wizard__step--active .sender-create-wizard__step-index {
color: #ffffff;
background: linear-gradient(135deg, #7e22ce 0%, #2a5298 100%);
border-color: transparent;
box-shadow: 0 0 0 3px rgba(126, 34, 206, 0.15);
}
.sender-create-wizard__step--done .sender-create-wizard__step-index {
color: #ffffff;
background: #2a5298;
border-color: transparent;
}
.sender-create-wizard__meta {
display: flex;
flex-direction: column;
gap: 0.25rem;
}
.sender-create-wizard__title {
font-size: 1rem;
font-weight: 700;
color: #1f2937;
}
.sender-create-wizard__description {
font-size: 0.875rem;
color: #64748b;
line-height: 1.4;
}
.sender-create-wizard__stage {
border: 1px solid rgba(126, 34, 206, 0.12);
border-radius: 10px;
background: rgba(126, 34, 206, 0.04);
padding: 0.85rem 0.95rem;
}
.sender-create-wizard__stage p {
margin: 0;
color: #334155;
font-size: 0.9rem;
}
.sender-create-wizard__footer {
width: 100%;
display: flex;
justify-content: flex-end;
gap: 0.5rem;
}
@media (max-width: 640px) {
.sender-create-wizard__footer {
flex-wrap: wrap;
}
.sender-create-wizard__footer .dxbl-btn {
flex: 1 1 calc(50% - 0.5rem);
}
}
.sender-create-wizard__validation {
border: 1px solid rgba(220, 38, 38, 0.24);
background: rgba(254, 226, 226, 0.9);
color: #991b1b;
border-radius: 8px;
padding: 0.6rem 0.75rem;
font-size: 0.85rem;
}
.sender-create-wizard__form-grid {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 0.9rem;
}
.sender-create-wizard__field {
display: flex;
flex-direction: column;
gap: 0.35rem;
}
.sender-create-wizard__field--full {
grid-column: 1 / -1;
}
.sender-create-wizard__settings-grid {
display: grid;
gap: 0.8rem;
}
.sender-create-wizard__settings-group {
border: 1px solid rgba(148, 163, 184, 0.34);
border-radius: 10px;
background: rgba(248, 250, 252, 0.86);
padding: 0.8rem;
}
.sender-create-wizard__settings-title {
font-size: 0.8rem;
font-weight: 800;
color: #334155;
margin-bottom: 0.6rem;
}
.sender-create-wizard__settings-toggles {
display: flex;
flex-wrap: wrap;
gap: 0.55rem 1.1rem;
}
.sender-create-wizard__settings-toggle {
display: inline-flex;
align-items: center;
gap: 0.4rem;
font-size: 0.82rem;
font-weight: 600;
color: #334155;
}
.sender-create-wizard__label {
font-size: 0.82rem;
font-weight: 700;
color: #334155;
}
.sender-create-wizard__required {
color: #dc2626;
}
.sender-create-wizard__optional {
color: #64748b;
font-weight: 600;
}
.sender-create-wizard__select {
min-height: 38px;
border: 1px solid rgba(126, 34, 206, 0.25);
border-radius: 8px;
padding: 0.45rem 0.55rem;
background: #ffffff;
color: #1f2937;
}
.sender-create-wizard__receiver-actions {
display: flex;
justify-content: flex-end;
}
.sender-create-wizard__add-receiver-btn {
display: inline-flex;
align-items: center;
justify-content: center;
gap: 0.4rem;
min-height: 36px;
min-width: 220px;
font-weight: 700;
font-size: 0.84rem;
border: 1px solid rgba(14, 116, 144, 0.28);
border-radius: 8px;
background: rgba(236, 254, 255, 0.95);
color: #0f766e;
box-shadow: 0 6px 14px rgba(14, 116, 144, 0.15);
padding: 0.45rem 0.9rem;
}
.sender-create-wizard__add-receiver-btn:hover:not(:disabled) {
background: rgba(207, 250, 254, 1);
color: #0f766e;
}
.sender-create-wizard__add-receiver-btn:disabled {
opacity: 0.58;
cursor: not-allowed;
}
.sender-create-wizard__suggestions {
display: flex;
flex-direction: column;
gap: 0.45rem;
}
.sender-create-wizard__suggestions-title {
font-size: 0.8rem;
font-weight: 700;
color: #475569;
}
.sender-create-wizard__suggestion-list {
display: flex;
flex-wrap: nowrap;
overflow-x: auto;
overflow-y: hidden;
white-space: nowrap;
gap: 0.45rem;
padding-bottom: 0.25rem;
}
.sender-create-wizard__suggestion-item {
display: flex;
flex: 0 0 auto;
flex-direction: column;
align-items: flex-start;
gap: 0.12rem;
border: 1px solid rgba(14, 116, 144, 0.22);
border-radius: 999px;
background: rgba(236, 254, 255, 0.85);
color: #0f172a;
padding: 0.35rem 0.7rem;
min-width: 0;
}
.sender-create-wizard__receiver-tagbox-wrap {
display: flex;
flex-direction: column;
gap: 0.35rem;
}
.sender-create-wizard__receiver-tagbox {
width: 100%;
}
.sender-create-wizard__receiver-tag {
display: inline-flex;
align-items: center;
gap: 0.4rem;
padding: 0.18rem 0.45rem;
border-radius: 999px;
background: rgba(236, 254, 255, 0.95);
border: 1px solid rgba(14, 116, 144, 0.25);
}
.sender-create-wizard__receiver-tag-name {
font-weight: 700;
}
.sender-create-wizard__receiver-tag-email {
color: #64748b;
font-size: 0.78rem;
}
.sender-create-wizard__receiver-tag-remove {
border: 0;
background: transparent;
color: #0f766e;
font-size: 0.76rem;
font-weight: 700;
line-height: 1;
padding: 0;
width: 1rem;
height: 1rem;
cursor: pointer;
}
.sender-create-wizard__tagbox-empty {
height: 0;
padding: 0;
margin: 0;
}
.sender-create-wizard__suggestion-item:disabled {
opacity: 0.58;
}
.sender-create-wizard__suggestion-name {
font-size: 0.77rem;
font-weight: 700;
line-height: 1.1;
}
.sender-create-wizard__suggestion-email {
font-size: 0.72rem;
color: #155e75;
line-height: 1.1;
}
.sender-create-wizard__receiver-list {
display: flex;
flex-direction: column;
gap: 0.5rem;
}
.sender-create-wizard__receiver-item {
display: flex;
align-items: center;
justify-content: space-between;
border: 1px solid rgba(126, 34, 206, 0.18);
border-radius: 8px;
padding: 0.55rem 0.7rem;
background: rgba(248, 250, 252, 0.95);
gap: 0.75rem;
}
.sender-create-wizard__receiver-name {
font-size: 0.86rem;
font-weight: 700;
color: #1f2937;
}
.sender-create-wizard__receiver-email {
font-size: 0.79rem;
color: #64748b;
}
.sender-create-wizard__receiver-remove {
border: 1px solid rgba(220, 38, 38, 0.2);
border-radius: 6px;
background: rgba(220, 38, 38, 0.08);
color: #b91c1c;
font-size: 0.78rem;
font-weight: 700;
padding: 0.25rem 0.55rem;
}
.sender-create-wizard__upload-stage {
display: flex;
flex-direction: column;
gap: 0.75rem;
}
.sender-create-wizard__upload-btn {
display: inline-flex;
align-items: center;
justify-content: center;
border: 1px solid rgba(126, 34, 206, 0.28);
border-radius: 8px;
padding: 0.55rem 0.9rem;
background: rgba(126, 34, 206, 0.08);
color: #4c1d95;
font-size: 0.84rem;
font-weight: 700;
width: fit-content;
cursor: pointer;
}
.sender-create-wizard__upload-btn--disabled {
opacity: 0.55;
cursor: not-allowed;
}
.sender-create-wizard__hidden-input {
display: none;
}
.sender-pdf-dropzone {
position: relative;
display: flex;
align-items: center;
justify-content: center;
min-height: 92px;
border: 1px dashed rgba(100, 116, 139, 0.5);
border-radius: 8px;
background: rgba(248, 250, 252, 0.9);
color: #334155;
cursor: pointer;
transition: border-color 120ms ease, background-color 120ms ease, box-shadow 120ms ease;
}
.sender-pdf-dropzone:hover {
border-color: rgba(126, 34, 206, 0.45);
background: rgba(241, 245, 249, 0.95);
}
.sender-pdf-dropzone--drag-active {
border-color: rgba(16, 185, 129, 0.75);
background: linear-gradient(180deg, rgba(16, 185, 129, 0.14), rgba(16, 185, 129, 0.08));
box-shadow: 0 0 0 3px rgba(16, 185, 129, 0.16);
}
.sender-pdf-dropzone--disabled {
opacity: 0.55;
cursor: not-allowed;
}
.sender-pdf-dropzone__content {
text-align: center;
display: grid;
gap: 0.2rem;
padding: 0.75rem 0.9rem;
}
.sender-pdf-dropzone__title {
font-size: 0.86rem;
font-weight: 700;
}
.sender-pdf-dropzone__hint {
font-size: 0.78rem;
color: #64748b;
}
.sender-pdf-dropzone__input {
position: absolute;
inset: 0;
width: 100%;
height: 100%;
opacity: 0;
cursor: pointer;
}
.sender-pdf-dropzone--disabled .sender-pdf-dropzone__input {
cursor: not-allowed;
}
.sender-create-wizard__document-meta {
border: 1px solid rgba(16, 185, 129, 0.3);
border-radius: 8px;
background: rgba(16, 185, 129, 0.08);
padding: 0.55rem 0.7rem;
}
.sender-create-wizard__document-preview-card {
display: flex;
flex-direction: column;
gap: 0.65rem;
}
.sender-create-wizard__document-preview-wrap {
border: 1px solid rgba(148, 163, 184, 0.38);
border-radius: 10px;
background: rgba(248, 250, 252, 0.96);
height: 320px;
overflow: hidden;
}
.sender-create-wizard__document-preview-wrap .sender-image-editor-shell {
height: 100%;
}
.sender-create-wizard__document-preview-wrap .sender-image-editor {
min-height: 0;
}
.sender-create-wizard__document-name {
color: #064e3b;
font-size: 0.85rem;
font-weight: 700;
}
.sender-create-wizard__document-size {
color: #065f46;
font-size: 0.77rem;
}
.sender-create-wizard__empty-list {
border: 1px dashed rgba(100, 116, 139, 0.4);
border-radius: 8px;
padding: 0.6rem 0.75rem;
color: #475569;
font-size: 0.83rem;
background: rgba(248, 250, 252, 0.8);
}
@media (max-width: 760px) {
.sender-create-wizard-popup .dxbl-popup {
width: 96vw !important;
max-width: 96vw !important;
}
.sender-create-wizard__progress {
gap: 0.35rem;
}
.sender-create-wizard__title {
font-size: 0.93rem;
}
.sender-create-wizard__description {
font-size: 0.81rem;
}
.sender-create-wizard__form-grid {
grid-template-columns: 1fr;
}
.sender-create-wizard__receiver-item {
flex-direction: column;
align-items: flex-start;
}
.sender-create-wizard__receiver-remove {
width: 100%;
}
.sender-pdf-dropzone {
width: 100%;
}
.sender-create-wizard__upload-btn {
width: 100%;
}
}

View File

@@ -0,0 +1 @@
sftp -P 22 root@172.24.12.64

View File

@@ -0,0 +1 @@
ssh root@172.24.12.64

View File

@@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk"> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup> <PropertyGroup>
<TargetFramework>net7.0</TargetFramework> <TargetFrameworks>net7.0;net8.0</TargetFrameworks>
<ImplicitUsings>enable</ImplicitUsings> <ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable> <Nullable>enable</Nullable>
@@ -17,7 +17,7 @@
</Content> </Content>
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup Condition="'$(TargetFramework)' == 'net7.0'">
<PackageReference Include="Bogus" Version="35.6.3" /> <PackageReference Include="Bogus" Version="35.6.3" />
<PackageReference Include="coverlet.collector" Version="6.0.0" /> <PackageReference Include="coverlet.collector" Version="6.0.0" />
<PackageReference Include="DigitalData.Core.Abstraction.Application" Version="1.6.0" /> <PackageReference Include="DigitalData.Core.Abstraction.Application" Version="1.6.0" />
@@ -28,13 +28,39 @@
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="7.0.20" /> <PackageReference Include="Microsoft.EntityFrameworkCore" Version="7.0.20" />
<PackageReference Include="Microsoft.EntityFrameworkCore.InMemory" Version="7.0.20" /> <PackageReference Include="Microsoft.EntityFrameworkCore.InMemory" Version="7.0.20" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="7.0.20" /> <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="7.0.20" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="9.0.5" /> <PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="9.0.6" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="9.0.6" />
<PackageReference Include="Microsoft.Identity.Client" Version="4.82.1" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.8.0" />
<PackageReference Include="NUnit" Version="3.14.0" />
<PackageReference Include="NUnit.Analyzers" Version="3.9.0" />
<PackageReference Include="NUnit3TestAdapter" Version="4.5.0" />
<PackageReference Include="SixLabors.ImageSharp" Version="3.1.12" />
</ItemGroup>
<ItemGroup Condition="'$(TargetFramework)' == 'net8.0'">
<PackageReference Include="Bogus" Version="35.6.3" />
<PackageReference Include="coverlet.collector" Version="6.0.0" />
<PackageReference Include="DigitalData.Core.Abstraction.Application" Version="1.6.0" />
<PackageReference Include="DigitalData.Core.Abstractions" Version="4.3.0" />
<PackageReference Include="DigitalData.Core.API" Version="2.2.1" />
<PackageReference Include="DigitalData.Core.Application" Version="3.4.0" />
<PackageReference Include="HtmlSanitizer" Version="9.0.892" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="8.0.17" />
<PackageReference Include="Microsoft.EntityFrameworkCore.InMemory" Version="8.0.17" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Relational" Version="8.0.17" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="8.0.17">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="8.0.17" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="9.0.6" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="9.0.6" />
<PackageReference Include="Microsoft.Identity.Client" Version="4.82.1" /> <PackageReference Include="Microsoft.Identity.Client" Version="4.82.1" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.8.0" /> <PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.8.0" />
<PackageReference Include="NUnit" Version="3.14.0" /> <PackageReference Include="NUnit" Version="3.14.0" />
<PackageReference Include="NUnit.Analyzers" Version="3.9.0" /> <PackageReference Include="NUnit.Analyzers" Version="3.9.0" />
<PackageReference Include="NUnit3TestAdapter" Version="4.5.0" /> <PackageReference Include="NUnit3TestAdapter" Version="4.5.0" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="9.0.5" />
<PackageReference Include="SixLabors.ImageSharp" Version="3.1.12" /> <PackageReference Include="SixLabors.ImageSharp" Version="3.1.12" />
</ItemGroup> </ItemGroup>
@@ -43,6 +69,19 @@
<ProjectReference Include="..\EnvelopeGenerator.Infrastructure\EnvelopeGenerator.Infrastructure.csproj" /> <ProjectReference Include="..\EnvelopeGenerator.Infrastructure\EnvelopeGenerator.Infrastructure.csproj" />
</ItemGroup> </ItemGroup>
<ItemGroup Condition="'$(TargetFramework)' == 'net8.0'">
<ProjectReference Include="..\EnvelopeGenerator.Infrastructure.Crypt\EnvelopeGenerator.Infrastructure.Crypt.csproj" />
</ItemGroup>
<ItemGroup Condition="'$(TargetFramework)' == 'net7.0'">
<Compile Remove="Application\Crypt\**\*.cs" />
</ItemGroup>
<ItemGroup Condition="'$(TargetFramework)' == 'net8.0'">
<PackageReference Include="Microsoft.Extensions.Configuration.Binder" Version="9.0.6" />
<PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="9.0.6" />
</ItemGroup>
<ItemGroup> <ItemGroup>
<Using Include="NUnit.Framework" /> <Using Include="NUnit.Framework" />
</ItemGroup> </ItemGroup>

View File

@@ -40,7 +40,9 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EnvelopeGenerator.Dependenc
EndProject EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "EnvelopeGenerator.Server", "EnvelopeGenerator.Server", "{BF1700D5-592E-4FFA-84E8-5480E289A1F0}" Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "EnvelopeGenerator.Server", "EnvelopeGenerator.Server", "{BF1700D5-592E-4FFA-84E8-5480E289A1F0}"
ProjectSection(SolutionItems) = preProject ProjectSection(SolutionItems) = preProject
EnvelopeGenerator.Server\cnn_ssh_soft_hsm.bat = EnvelopeGenerator.Server\cnn_ssh_soft_hsm.bat
EnvelopeGenerator.Server\publish.bat = EnvelopeGenerator.Server\publish.bat EnvelopeGenerator.Server\publish.bat = EnvelopeGenerator.Server\publish.bat
EnvelopeGenerator.Server\cnn_sftp_soft_hsm.bat = EnvelopeGenerator.Server\cnn_sftp_soft_hsm.bat
SENDER_SAVE_EDIT_MIGRATION_PLAN.md = SENDER_SAVE_EDIT_MIGRATION_PLAN.md SENDER_SAVE_EDIT_MIGRATION_PLAN.md = SENDER_SAVE_EDIT_MIGRATION_PLAN.md
EndProjectSection EndProjectSection
EndProject EndProject
@@ -54,6 +56,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EnvelopeGenerator.Service",
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EnvelopeGenerator.Infrastructure.Doc", "EnvelopeGenerator.Infrastructure.Doc\EnvelopeGenerator.Infrastructure.Doc.csproj", "{3B6EFE8D-F1EE-4666-87A0-9F90149CC61A}" Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EnvelopeGenerator.Infrastructure.Doc", "EnvelopeGenerator.Infrastructure.Doc\EnvelopeGenerator.Infrastructure.Doc.csproj", "{3B6EFE8D-F1EE-4666-87A0-9F90149CC61A}"
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EnvelopeGenerator.Infrastructure.Crypt", "EnvelopeGenerator.Infrastructure.Crypt\EnvelopeGenerator.Infrastructure.Crypt.csproj", "{B33A3B17-A4F8-4307-9C51-DDFE1B292DE7}"
EndProject
Global Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU Debug|Any CPU = Debug|Any CPU
@@ -120,6 +124,10 @@ Global
{3B6EFE8D-F1EE-4666-87A0-9F90149CC61A}.Debug|Any CPU.Build.0 = Debug|Any CPU {3B6EFE8D-F1EE-4666-87A0-9F90149CC61A}.Debug|Any CPU.Build.0 = Debug|Any CPU
{3B6EFE8D-F1EE-4666-87A0-9F90149CC61A}.Release|Any CPU.ActiveCfg = Release|Any CPU {3B6EFE8D-F1EE-4666-87A0-9F90149CC61A}.Release|Any CPU.ActiveCfg = Release|Any CPU
{3B6EFE8D-F1EE-4666-87A0-9F90149CC61A}.Release|Any CPU.Build.0 = Release|Any CPU {3B6EFE8D-F1EE-4666-87A0-9F90149CC61A}.Release|Any CPU.Build.0 = Release|Any CPU
{B33A3B17-A4F8-4307-9C51-DDFE1B292DE7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{B33A3B17-A4F8-4307-9C51-DDFE1B292DE7}.Debug|Any CPU.Build.0 = Debug|Any CPU
{B33A3B17-A4F8-4307-9C51-DDFE1B292DE7}.Release|Any CPU.ActiveCfg = Release|Any CPU
{B33A3B17-A4F8-4307-9C51-DDFE1B292DE7}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection EndGlobalSection
GlobalSection(SolutionProperties) = preSolution GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE HideSolutionNode = FALSE
@@ -144,6 +152,7 @@ Global
{83ED2617-B398-4859-8F59-B38F8807E83E} = {9943209E-1744-4944-B1BA-4F87FC1A0EEB} {83ED2617-B398-4859-8F59-B38F8807E83E} = {9943209E-1744-4944-B1BA-4F87FC1A0EEB}
{6B87FB5F-F4EA-45BE-A218-385DC2CE8E80} = {E3C758DC-914D-4B7E-8457-0813F1FDB0CB} {6B87FB5F-F4EA-45BE-A218-385DC2CE8E80} = {E3C758DC-914D-4B7E-8457-0813F1FDB0CB}
{3B6EFE8D-F1EE-4666-87A0-9F90149CC61A} = {02EA681E-C7D8-13C7-8484-4AC65E1B71E8} {3B6EFE8D-F1EE-4666-87A0-9F90149CC61A} = {02EA681E-C7D8-13C7-8484-4AC65E1B71E8}
{B33A3B17-A4F8-4307-9C51-DDFE1B292DE7} = {02EA681E-C7D8-13C7-8484-4AC65E1B71E8}
EndGlobalSection EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {73E60370-756D-45AD-A19A-C40A02DACCC7} SolutionGuid = {73E60370-756D-45AD-A19A-C40A02DACCC7}