Compare commits

..
Author SHA1 Message Date
Reece ffe29828d2 Update embed and allow form rendering 2025-12-02 18:18:51 +00:00
c2a63cf425 java frontend (#5097)
# Description of Changes

<!--
Please provide a summary of the changes, including:

- What was changed
- Why the change was made
- Any challenges encountered

Closes #(issue_number)
-->

---

## Checklist

### General

- [ ] I have read the [Contribution
Guidelines](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/CONTRIBUTING.md)
- [ ] I have read the [Stirling-PDF Developer
Guide](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/devGuide/DeveloperGuide.md)
(if applicable)
- [ ] I have read the [How to add new languages to
Stirling-PDF](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/devGuide/HowToAddNewLanguage.md)
(if applicable)
- [ ] I have performed a self-review of my own code
- [ ] My changes generate no new warnings

### Documentation

- [ ] I have updated relevant docs on [Stirling-PDF's doc
repo](https://github.com/Stirling-Tools/Stirling-Tools.github.io/blob/main/docs/)
(if functionality has heavily changed)
- [ ] I have read the section [Add New Translation
Tags](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/devGuide/HowToAddNewLanguage.md#add-new-translation-tags)
(for new translation tags only)

### Translations (if applicable)

- [ ] I ran
[`scripts/counter_translation.py`](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/docs/counter_translation.md)

### UI Changes (if applicable)

- [ ] Screenshots or videos demonstrating the UI changes are attached
(e.g., as comments or direct attachments in the PR)

### Testing (if applicable)

- [ ] I have tested my changes locally. Refer to the [Testing
Guide](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/devGuide/DeveloperGuide.md#6-testing)
for more details.

---------

Co-authored-by: Reece <reece@stirlingpdf.com>
Co-authored-by: Reece Browne <74901996+reecebrowne@users.noreply.github.com>
2025-12-02 17:15:29 +00:00
Reece BrowneandGitHub c3456adc2b Print with embed (#5109) 2025-12-02 13:56:28 +00:00
EthanHealy01andGitHub 179b569769 Chore/v2/onboarding flow cleanup (#5065) 2025-12-02 12:40:20 +00:00
Dario Ghunney WareGitHubdependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>LudyEthanHealy01EthanAnthony Stirlingstirlingbot[bot] <195170888+stirlingbot[bot]@users.noreply.github.com>
341adaa07d Grandpa Fix (#5030)
PR to address inactive accounts (invited/pending activation) not being
grandfathered during migration

---------

Signed-off-by: dependabot[bot] <support@github.com>
Signed-off-by: stirlingbot[bot] <stirlingbot[bot]@users.noreply.github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Ludy <Ludy87@users.noreply.github.com>
Co-authored-by: EthanHealy01 <80844253+EthanHealy01@users.noreply.github.com>
Co-authored-by: Ethan <ethan@MacBook-Pro.local>
Co-authored-by: Anthony Stirling <77850077+Frooodle@users.noreply.github.com>
Co-authored-by: stirlingbot[bot] <195170888+stirlingbot[bot]@users.noreply.github.com>
2025-12-02 12:34:38 +00:00
Dario Ghunney WareGitHubdependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>LudyEthanHealy01EthanAnthony Stirlingstirlingbot[bot] <195170888+stirlingbot[bot]@users.noreply.github.com>
feebfe82fa Reduce JWT Logs (#5108)
Removed logging in some areas and changed level from `WARN` -> `DEBUG`
to reduce verbosity

Closes #5089

---------

Signed-off-by: dependabot[bot] <support@github.com>
Signed-off-by: stirlingbot[bot] <stirlingbot[bot]@users.noreply.github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Ludy <Ludy87@users.noreply.github.com>
Co-authored-by: EthanHealy01 <80844253+EthanHealy01@users.noreply.github.com>
Co-authored-by: Ethan <ethan@MacBook-Pro.local>
Co-authored-by: Anthony Stirling <77850077+Frooodle@users.noreply.github.com>
Co-authored-by: stirlingbot[bot] <195170888+stirlingbot[bot]@users.noreply.github.com>
2025-12-02 12:34:17 +00:00
ConnorYohGitHubCopilot Autofix powered by AI <62310815+github-advanced-security[bot]@users.noreply.github.com>
1e72416d55 Added file endpoint for license files and easy upload in admin UI (#5055)
<img width="698" height="240" alt="image"
src="https://github.com/user-attachments/assets/f0161e5f-e2ed-44c1-bdd1-93fab46f756b"
/>

---------

Co-authored-by: Copilot Autofix powered by AI <62310815+github-advanced-security[bot]@users.noreply.github.com>
2025-11-29 19:35:50 +00:00
Anthony StirlingandGitHub 959d14f075 Bump version from 2.0.1 to 2.0.2 2025-11-29 19:29:58 +00:00
8f6fcee428 Fix: Only block export when signatures are placed but not applied (#5084)
Previously, activating signature placement mode would immediately set
signaturesApplied=false, blocking export even when no signatures were
actually placed on the PDF. This caused the "unapplied signatures"
warning to appear incorrectly after clicking "Apply Signatures".

Changes:
- Remove signaturesApplied=false from activateDrawMode and
activateSignaturePlacementMode in SignatureContext
- Add signaturesApplied=false to onAnnotationEvent handler in
SignatureAPIBridge when event.type === 'create'
- Now signatures are only marked as unapplied when actually placed

This ensures:
- Users can activate placement mode without triggering export warning
- Export is only blocked when signatures are actually placed but not
applied
- After applying signatures, users can immediately export without
warning

🤖 Generated with [Claude Code](https://claude.com/claude-code)

# Description of Changes

<!--
Please provide a summary of the changes, including:

- What was changed
- Why the change was made
- Any challenges encountered

Closes #(issue_number)
-->

---

## Checklist

### General

- [ ] I have read the [Contribution
Guidelines](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/CONTRIBUTING.md)
- [ ] I have read the [Stirling-PDF Developer
Guide](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/devGuide/DeveloperGuide.md)
(if applicable)
- [ ] I have read the [How to add new languages to
Stirling-PDF](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/devGuide/HowToAddNewLanguage.md)
(if applicable)
- [ ] I have performed a self-review of my own code
- [ ] My changes generate no new warnings

### Documentation

- [ ] I have updated relevant docs on [Stirling-PDF's doc
repo](https://github.com/Stirling-Tools/Stirling-Tools.github.io/blob/main/docs/)
(if functionality has heavily changed)
- [ ] I have read the section [Add New Translation
Tags](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/devGuide/HowToAddNewLanguage.md#add-new-translation-tags)
(for new translation tags only)

### Translations (if applicable)

- [ ] I ran
[`scripts/counter_translation.py`](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/docs/counter_translation.md)

### UI Changes (if applicable)

- [ ] Screenshots or videos demonstrating the UI changes are attached
(e.g., as comments or direct attachments in the PR)

### Testing (if applicable)

- [ ] I have tested my changes locally. Refer to the [Testing
Guide](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/devGuide/DeveloperGuide.md#6-testing)
for more details.

Co-authored-by: Claude <noreply@anthropic.com>
2025-11-29 19:29:30 +00:00
651f17f1c6 Save signatures to server (#5080)
# Description of Changes

<!--
Please provide a summary of the changes, including:

- What was changed
- Why the change was made
- Any challenges encountered

Closes #(issue_number)
-->

---

## Checklist

### General

- [ ] I have read the [Contribution
Guidelines](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/CONTRIBUTING.md)
- [ ] I have read the [Stirling-PDF Developer
Guide](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/devGuide/DeveloperGuide.md)
(if applicable)
- [ ] I have read the [How to add new languages to
Stirling-PDF](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/devGuide/HowToAddNewLanguage.md)
(if applicable)
- [ ] I have performed a self-review of my own code
- [ ] My changes generate no new warnings

### Documentation

- [ ] I have updated relevant docs on [Stirling-PDF's doc
repo](https://github.com/Stirling-Tools/Stirling-Tools.github.io/blob/main/docs/)
(if functionality has heavily changed)
- [ ] I have read the section [Add New Translation
Tags](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/devGuide/HowToAddNewLanguage.md#add-new-translation-tags)
(for new translation tags only)

### Translations (if applicable)

- [ ] I ran
[`scripts/counter_translation.py`](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/docs/counter_translation.md)

### UI Changes (if applicable)

- [ ] Screenshots or videos demonstrating the UI changes are attached
(e.g., as comments or direct attachments in the PR)

### Testing (if applicable)

- [ ] I have tested my changes locally. Refer to the [Testing
Guide](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/devGuide/DeveloperGuide.md#6-testing)
for more details.

---------

Co-authored-by: Anthony Stirling <77850077+Frooodle@users.noreply.github.com>
2025-11-29 19:29:06 +00:00
Anthony StirlingandGitHub fde449e738 Use frontend translations for OCR language picker (#5051)
## Summary
- revert OCR ui-data endpoint to only expose language codes without
backend labels
- translate OCR language options on the frontend using existing lang.*
keys with locale-aware fallbacks

## Testing
- Not run (not requested)


------
[Codex
Task](https://chatgpt.com/codex/tasks/task_b_6928ae7c85448328a0d2660a0c021b22)
2025-11-29 16:05:15 +00:00
Anthony StirlingandGitHub 85e9121745 desktop fix debian (#5068)
# Description of Changes

<!--
Please provide a summary of the changes, including:

- What was changed
- Why the change was made
- Any challenges encountered

Closes #(issue_number)
-->

---

## Checklist

### General

- [ ] I have read the [Contribution
Guidelines](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/CONTRIBUTING.md)
- [ ] I have read the [Stirling-PDF Developer
Guide](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/devGuide/DeveloperGuide.md)
(if applicable)
- [ ] I have read the [How to add new languages to
Stirling-PDF](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/devGuide/HowToAddNewLanguage.md)
(if applicable)
- [ ] I have performed a self-review of my own code
- [ ] My changes generate no new warnings

### Documentation

- [ ] I have updated relevant docs on [Stirling-PDF's doc
repo](https://github.com/Stirling-Tools/Stirling-Tools.github.io/blob/main/docs/)
(if functionality has heavily changed)
- [ ] I have read the section [Add New Translation
Tags](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/devGuide/HowToAddNewLanguage.md#add-new-translation-tags)
(for new translation tags only)

### Translations (if applicable)

- [ ] I ran
[`scripts/counter_translation.py`](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/docs/counter_translation.md)

### UI Changes (if applicable)

- [ ] Screenshots or videos demonstrating the UI changes are attached
(e.g., as comments or direct attachments in the PR)

### Testing (if applicable)

- [ ] I have tested my changes locally. Refer to the [Testing
Guide](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/devGuide/DeveloperGuide.md#6-testing)
for more details.
2025-11-29 16:04:43 +00:00
Anthony StirlingandGitHub 12f1fd485e Audit viewer making api call when shouldnt (#5069)
# Description of Changes

<!--
Please provide a summary of the changes, including:

- What was changed
- Why the change was made
- Any challenges encountered

Closes #(issue_number)
-->

---

## Checklist

### General

- [ ] I have read the [Contribution
Guidelines](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/CONTRIBUTING.md)
- [ ] I have read the [Stirling-PDF Developer
Guide](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/devGuide/DeveloperGuide.md)
(if applicable)
- [ ] I have read the [How to add new languages to
Stirling-PDF](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/devGuide/HowToAddNewLanguage.md)
(if applicable)
- [ ] I have performed a self-review of my own code
- [ ] My changes generate no new warnings

### Documentation

- [ ] I have updated relevant docs on [Stirling-PDF's doc
repo](https://github.com/Stirling-Tools/Stirling-Tools.github.io/blob/main/docs/)
(if functionality has heavily changed)
- [ ] I have read the section [Add New Translation
Tags](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/devGuide/HowToAddNewLanguage.md#add-new-translation-tags)
(for new translation tags only)

### Translations (if applicable)

- [ ] I ran
[`scripts/counter_translation.py`](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/docs/counter_translation.md)

### UI Changes (if applicable)

- [ ] Screenshots or videos demonstrating the UI changes are attached
(e.g., as comments or direct attachments in the PR)

### Testing (if applicable)

- [ ] I have tested my changes locally. Refer to the [Testing
Guide](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/devGuide/DeveloperGuide.md#6-testing)
for more details.
2025-11-29 16:04:29 +00:00
Anthony StirlingandGitHub b49e8a2355 tauri remote connection fix (#5070)
# Description of Changes

<!--
Please provide a summary of the changes, including:

- What was changed
- Why the change was made
- Any challenges encountered

Closes #(issue_number)
-->

---

## Checklist

### General

- [ ] I have read the [Contribution
Guidelines](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/CONTRIBUTING.md)
- [ ] I have read the [Stirling-PDF Developer
Guide](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/devGuide/DeveloperGuide.md)
(if applicable)
- [ ] I have read the [How to add new languages to
Stirling-PDF](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/devGuide/HowToAddNewLanguage.md)
(if applicable)
- [ ] I have performed a self-review of my own code
- [ ] My changes generate no new warnings

### Documentation

- [ ] I have updated relevant docs on [Stirling-PDF's doc
repo](https://github.com/Stirling-Tools/Stirling-Tools.github.io/blob/main/docs/)
(if functionality has heavily changed)
- [ ] I have read the section [Add New Translation
Tags](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/devGuide/HowToAddNewLanguage.md#add-new-translation-tags)
(for new translation tags only)

### Translations (if applicable)

- [ ] I ran
[`scripts/counter_translation.py`](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/docs/counter_translation.md)

### UI Changes (if applicable)

- [ ] Screenshots or videos demonstrating the UI changes are attached
(e.g., as comments or direct attachments in the PR)

### Testing (if applicable)

- [ ] I have tested my changes locally. Refer to the [Testing
Guide](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/devGuide/DeveloperGuide.md#6-testing)
for more details.
2025-11-29 16:04:19 +00:00
d908bc6785 Swagger fixes (#5071)
# Description of Changes

<!--
Please provide a summary of the changes, including:

- What was changed
- Why the change was made
- Any challenges encountered

Closes #(issue_number)
-->

---

## Checklist

### General

- [ ] I have read the [Contribution
Guidelines](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/CONTRIBUTING.md)
- [ ] I have read the [Stirling-PDF Developer
Guide](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/devGuide/DeveloperGuide.md)
(if applicable)
- [ ] I have read the [How to add new languages to
Stirling-PDF](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/devGuide/HowToAddNewLanguage.md)
(if applicable)
- [ ] I have performed a self-review of my own code
- [ ] My changes generate no new warnings

### Documentation

- [ ] I have updated relevant docs on [Stirling-PDF's doc
repo](https://github.com/Stirling-Tools/Stirling-Tools.github.io/blob/main/docs/)
(if functionality has heavily changed)
- [ ] I have read the section [Add New Translation
Tags](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/devGuide/HowToAddNewLanguage.md#add-new-translation-tags)
(for new translation tags only)

### Translations (if applicable)

- [ ] I ran
[`scripts/counter_translation.py`](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/docs/counter_translation.md)

### UI Changes (if applicable)

- [ ] Screenshots or videos demonstrating the UI changes are attached
(e.g., as comments or direct attachments in the PR)

### Testing (if applicable)

- [ ] I have tested my changes locally. Refer to the [Testing
Guide](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/devGuide/DeveloperGuide.md#6-testing)
for more details.

Co-authored-by: Reece Browne <74901996+reecebrowne@users.noreply.github.com>
2025-11-29 16:03:57 +00:00
Anthony StirlingandGitHub 4ae79d92ae Fix email invite/ allow non auth and table refresh issues (#5076)
# Description of Changes

- Show warning when email invite fails but user is created
  - Auto-refresh user/team tables after modifications
  - Fix invite email URLs to use frontend URL instead of backend
  - Support anonymous SMTP for local development
---

## Checklist

### General

- [ ] I have read the [Contribution
Guidelines](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/CONTRIBUTING.md)
- [ ] I have read the [Stirling-PDF Developer
Guide](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/devGuide/DeveloperGuide.md)
(if applicable)
- [ ] I have read the [How to add new languages to
Stirling-PDF](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/devGuide/HowToAddNewLanguage.md)
(if applicable)
- [ ] I have performed a self-review of my own code
- [ ] My changes generate no new warnings

### Documentation

- [ ] I have updated relevant docs on [Stirling-PDF's doc
repo](https://github.com/Stirling-Tools/Stirling-Tools.github.io/blob/main/docs/)
(if functionality has heavily changed)
- [ ] I have read the section [Add New Translation
Tags](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/devGuide/HowToAddNewLanguage.md#add-new-translation-tags)
(for new translation tags only)

### Translations (if applicable)

- [ ] I ran
[`scripts/counter_translation.py`](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/docs/counter_translation.md)

### UI Changes (if applicable)

- [ ] Screenshots or videos demonstrating the UI changes are attached
(e.g., as comments or direct attachments in the PR)

### Testing (if applicable)

- [ ] I have tested my changes locally. Refer to the [Testing
Guide](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/devGuide/DeveloperGuide.md#6-testing)
for more details.
2025-11-29 16:03:44 +00:00
Balázs SzücsandGitHub 85d9b5b83d feat(viewer): Add interactive link layer with (basic) internal/external navigation support (#5077)
# Description of Changes

Added a new `LinkLayer` component to the PDF viewer that renders
clickable overlays for PDF link annotations, enabling both internal page
navigation and external URL links.

- Created `LinkLayer.tsx` component that extracts link annotations using
the EmbedPDF annotation API with fallback to direct PDF document access
- Implemented scale-aware positioning to maintain accurate link hotspots
at different zoom levels
- Added support for internal navigation (GoTo actions) using smooth
scrolling and external links (URI actions) opening in new tabs
- Integrated accessibility features with proper ARIA labels and keyboard
navigation
- Modified `LocalEmbedPDF.tsx` to always register the annotation plugin
(even when editing is disabled) to enable reading existing link
annotations
- Updated `ReactRoutingController.java` and test formatting for code
style consistency


**Key features:**
- Multi-source annotation detection (annotation API → document API →
page API fallback)
- Navigation lock to prevent race conditions
- React performance optimizations (useMemo, useCallback)
- TypeScript type safety for PDF actions and destinations



This does not address support for Attachment links. Sadly, that does not
seem to be possible with EmbedPDF


<img width="773" height="957" alt="image"
src="https://github.com/user-attachments/assets/8a04d15a-79b5-46b6-af8b-3d27246581a7"
/>
<img width="773" height="957" alt="image"
src="https://github.com/user-attachments/assets/eeb39ca7-a114-4bd5-a4eb-9e8a27331297"
/>
<img width="773" height="957" alt="image"
src="https://github.com/user-attachments/assets/1ee6bba3-d233-4a11-bf1a-1b56696265e1"
/>


<!--
Please provide a summary of the changes, including:

- What was changed
- Why the change was made
- Any challenges encountered

Closes #(issue_number)
-->

---

## Checklist

### General

- [X] I have read the [Contribution
Guidelines](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/CONTRIBUTING.md)
- [ ] I have read the [Stirling-PDF Developer
Guide](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/devGuide/DeveloperGuide.md)
(if applicable)
- [ ] I have read the [How to add new languages to
Stirling-PDF](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/devGuide/HowToAddNewLanguage.md)
(if applicable)
- [X] I have performed a self-review of my own code
- [ ] My changes generate no new warnings

### Documentation

- [ ] I have updated relevant docs on [Stirling-PDF's doc
repo](https://github.com/Stirling-Tools/Stirling-Tools.github.io/blob/main/docs/)
(if functionality has heavily changed)
- [ ] I have read the section [Add New Translation
Tags](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/devGuide/HowToAddNewLanguage.md#add-new-translation-tags)
(for new translation tags only)

### Translations (if applicable)

- [ ] I ran
[`scripts/counter_translation.py`](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/docs/counter_translation.md)

### UI Changes (if applicable)

- [ ] Screenshots or videos demonstrating the UI changes are attached
(e.g., as comments or direct attachments in the PR)

### Testing (if applicable)

- [X] I have tested my changes locally. Refer to the [Testing
Guide](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/devGuide/DeveloperGuide.md#6-testing)
for more details.

Signed-off-by: Balázs Szücs <bszucs1209@gmail.com>
2025-11-29 12:53:26 +00:00
Reece BrowneandGitHub 058a81d554 Improved language select (#5062) 2025-11-28 22:49:23 +00:00
Reece BrowneandGitHub e4c6ce5836 Cookie consent banner and footer on login screen (#5042) 2025-11-28 16:24:10 +00:00
ConnorYohandGitHub 250979e271 Desktop Self-hosted guidance improvements (#5060)
Removed timeout when waiting for backend port to allow for slow backend
spinups



<img width="1185" height="951" alt="image"
src="https://github.com/user-attachments/assets/badaf8e5-611d-44aa-aca2-7c1c906c2019"
/>
<img width="1213" height="1533" alt="image"
src="https://github.com/user-attachments/assets/ce78b67a-07e0-4c23-9087-5de0c5f203c6"
/>
<img width="1207" height="1202" alt="image"
src="https://github.com/user-attachments/assets/c6e5b4c5-9cc3-4973-a634-3b7aa1e1dd34"
/>
2025-11-28 15:55:37 +00:00
199 changed files with 5558 additions and 11062 deletions
+1
View File
@@ -5,6 +5,7 @@ frontend/dist
frontend/build
frontend/.vite
frontend/.tauri
frontend/src-tauri/target
# Gradle build artifacts
.gradle
@@ -180,7 +180,7 @@ jobs:
uses: docker/build-push-action@263435318d21b8e681c14492fe198d362a7d2c83 # v6.18.0
with:
context: .
file: ./Dockerfile
file: ./docker/embedded/Dockerfile
push: true
tags: ${{ secrets.DOCKER_HUB_USERNAME }}/test:pr-${{ needs.check-comment.outputs.pr_number }}
build-args: VERSION_TAG=alpha
+2 -2
View File
@@ -262,7 +262,7 @@ jobs:
strategy:
fail-fast: false
matrix:
docker-rev: ["Dockerfile", "Dockerfile.ultra-lite", "Dockerfile.fat"]
docker-rev: ["docker/embedded/Dockerfile", "docker/embedded/Dockerfile.ultra-lite", "docker/embedded/Dockerfile.fat"]
steps:
- name: Harden Runner
uses: step-security/harden-runner@f4a75cfd619ee5ce8d5b864b0d183aff3c69b55a # v2.13.1
@@ -301,7 +301,7 @@ jobs:
with:
builder: ${{ steps.buildx.outputs.name }}
context: .
file: ./docker/backend/${{ matrix.docker-rev }}
file: ./${{ matrix.docker-rev }}
push: false
cache-from: type=gha
cache-to: type=gha,mode=max
+10 -9
View File
@@ -5,6 +5,7 @@ on:
push:
branches:
- V2-master
- alljavadocker
# cancel in-progress jobs if a new job is triggered
# This is useful to avoid running multiple builds for the same branch if a new commit is pushed
@@ -93,10 +94,10 @@ jobs:
type=raw,value=${{ steps.versionNumber.outputs.versionNumber }}
type=raw,value=latest
- name: Generate tags for latest (V2-demo branch - test)
- name: Generate tags for latest (alljavadocker branch - test)
id: meta-test
uses: docker/metadata-action@c1e51972afc2121e065aed6d45c65596fe445f3f # v5.8.0
if: github.ref == 'refs/heads/V2-demo'
if: github.ref == 'refs/heads/alljavadocker'
with:
images: |
ghcr.io/stirling-tools/stirling-pdf-test
@@ -110,7 +111,7 @@ jobs:
with:
builder: ${{ steps.buildx.outputs.name }}
context: .
file: ./docker/Dockerfile.unified
file: ./docker/embedded/Dockerfile
push: true
cache-from: type=gha
cache-to: type=gha,mode=max
@@ -149,10 +150,10 @@ jobs:
type=raw,value=${{ steps.versionNumber.outputs.versionNumber }}-fat
type=raw,value=latest-fat
- name: Generate tags for latest-fat (V2-demo branch - test)
- name: Generate tags for latest-fat (alljavadocker branch - test)
id: meta-fat-test
uses: docker/metadata-action@c1e51972afc2121e065aed6d45c65596fe445f3f # v5.8.0
if: github.ref == 'refs/heads/V2-demo'
if: github.ref == 'refs/heads/alljavadocker'
with:
images: |
ghcr.io/stirling-tools/stirling-pdf-test
@@ -166,7 +167,7 @@ jobs:
with:
builder: ${{ steps.buildx.outputs.name }}
context: .
file: ./docker/Dockerfile.unified
file: ./docker/embedded/Dockerfile.fat
push: true
cache-from: type=gha
cache-to: type=gha,mode=max
@@ -203,10 +204,10 @@ jobs:
type=raw,value=${{ steps.versionNumber.outputs.versionNumber }}-ultra-lite
type=raw,value=latest-ultra-lite
- name: Generate tags for ultra-lite (V2-demo branch - test)
- name: Generate tags for ultra-lite (alljavadocker branch - test)
id: meta-lite-test
uses: docker/metadata-action@c1e51972afc2121e065aed6d45c65596fe445f3f # v5.8.0
if: github.ref == 'refs/heads/V2-demo'
if: github.ref == 'refs/heads/alljavadocker'
with:
images: |
ghcr.io/stirling-tools/stirling-pdf-test
@@ -220,7 +221,7 @@ jobs:
with:
builder: ${{ steps.buildx.outputs.name }}
context: .
file: ./docker/Dockerfile.unified-lite
file: ./docker/embedded/Dockerfile.ultra-lite
push: true
cache-from: type=gha
cache-to: type=gha,mode=max
+3 -3
View File
@@ -107,7 +107,7 @@ jobs:
with:
builder: ${{ steps.buildx.outputs.name }}
context: .
file: ./Dockerfile
file: ./docker/embedded/Dockerfile
push: true
cache-from: type=gha
cache-to: type=gha,mode=max
@@ -152,7 +152,7 @@ jobs:
if: github.ref != 'refs/heads/main'
with:
context: .
file: ./Dockerfile.ultra-lite
file: ./docker/embedded/Dockerfile.ultra-lite
push: true
cache-from: type=gha
cache-to: type=gha,mode=max
@@ -183,7 +183,7 @@ jobs:
with:
builder: ${{ steps.buildx.outputs.name }}
context: .
file: ./Dockerfile.fat
file: ./docker/embedded/Dockerfile.fat
push: true
cache-from: type=gha
cache-to: type=gha,mode=max
+1 -1
View File
@@ -66,7 +66,7 @@ jobs:
uses: docker/build-push-action@263435318d21b8e681c14492fe198d362a7d2c83 # v6.18.0
with:
context: .
file: ./Dockerfile
file: ./docker/embedded/Dockerfile
push: true
tags: ${{ secrets.DOCKER_HUB_USERNAME }}/test:test-${{ github.sha }}
build-args: VERSION_TAG=${{ steps.versionNumber.outputs.versionNumber }}
+3 -3
View File
@@ -33,16 +33,16 @@ dependencies {
api 'com.googlecode.owasp-java-html-sanitizer:owasp-java-html-sanitizer:20240325.1'
api 'com.fathzer:javaluator:3.0.6'
api 'com.posthog.java:posthog:1.2.0'
api 'org.apache.commons:commons-lang3:3.17.0'
api 'org.apache.commons:commons-lang3:3.19.0'
api 'com.drewnoakes:metadata-extractor:2.19.0' // Image metadata extractor
api 'com.vladsch.flexmark:flexmark-html2md-converter:0.64.8'
api "org.apache.pdfbox:pdfbox:$pdfboxVersion"
api "org.apache.pdfbox:xmpbox:$pdfboxVersion"
api "org.apache.pdfbox:preflight:$pdfboxVersion"
api 'com.github.junrar:junrar:7.5.7' // RAR archive support for CBR files
api 'com.github.junrar:junrar:7.5.5' // RAR archive support for CBR files
api 'jakarta.servlet:jakarta.servlet-api:6.1.0'
api 'org.snakeyaml:snakeyaml-engine:2.10'
api "org.springdoc:springdoc-openapi-starter-webmvc-ui:2.8.14"
api "org.springdoc:springdoc-openapi-starter-webmvc-ui:2.8.13"
api 'jakarta.mail:jakarta.mail-api:2.1.5'
runtimeOnly 'org.eclipse.angus:angus-mail:2.0.5'
}
@@ -22,25 +22,13 @@ import io.swagger.v3.oas.annotations.tags.Tag;
name = "Analysis",
description =
"""
Document analysis and information extraction services for content intelligence and insights.
Read-only inspection of PDFs: page count, page sizes, fonts, form fields, annotations, document properties, and security details.
Use these endpoints to understand what's inside a document without changing it.
This endpoint group provides analytical capabilities to understand document structure,
extract information, and generate insights from PDF content for automated processing.
Common use cases:
• Document inventory management and content audit for compliance verification
• Quality assurance workflows and business intelligence analytics
• Migration planning, accessibility evaluation, and document forensics
Business applications:
• Legal discovery, financial document review, and healthcare records analysis
• Academic research, government processing, and publishing optimization
Operational scenarios:
• Large-scale profiling, migration assessment, and performance optimization
• Automated quality control and content strategy development
Target users: Data analysts, QA teams, administrators, and business intelligence
professionals requiring detailed document insights.
Typical uses:
• Get page counts and dimensions for layout or print rules
• List fonts and annotations to spot compatibility issues
• Inspect form fields before deciding how to fill or modify them
• Pull metadata and security settings for audits or reports
""")
public @interface AnalysisApi {}
@@ -22,25 +22,13 @@ import io.swagger.v3.oas.annotations.tags.Tag;
name = "Convert",
description =
"""
Document format transformation services for cross-platform compatibility and workflow integration.
Convert PDFs to and from other formats (Word, images, HTML, Markdown, PDF/A, CBZ/CBR, EML, etc.).
This group also powers the text-editor / jobId-based editing flow for incremental PDF edits.
This endpoint group enables transformation between various formats, supporting
diverse business workflows and system integrations for mixed document ecosystems.
Common use cases:
• Legacy system integration, document migration, and cross-platform sharing
• Archive standardization, publishing preparation, and content adaptation
• Accessibility compliance and mobile-friendly document preparation
Business applications:
• Enterprise content management, digital publishing, and educational platforms
• Legal document processing, healthcare interoperability, and government standardization
Integration scenarios:
• API-driven pipelines, automated workflow preparation, and batch conversions
• Real-time format adaptation for user requests
Target users: System integrators, content managers, digital archivists, and
organizations requiring flexible document format interoperability.
Typical uses:
• Turn PDFs into Word or text for editing
• Convert office files, images, HTML, or email (EML) into PDFs
• Create PDF/A for long-term archiving
• Export PDFs as images, HTML, CSV, or Markdown for search, analysis, or reuse
""")
public @interface ConvertApi {}
@@ -22,25 +22,13 @@ import io.swagger.v3.oas.annotations.tags.Tag;
name = "Filter",
description =
"""
Document content filtering and search operations for information discovery and organization.
Check basic properties of PDFs before you process them: page count, file size, page size/rotation, and whether they contain text or images.
Use these endpoints as a "pre-check" step to decide what to do with a file next.
This endpoint group enables intelligent content discovery and organization within
document collections for content-based processing and information extraction.
Common use cases:
• Legal discovery, research organization, and compliance auditing
• Content moderation, academic research, and business intelligence
• Quality assurance and content validation workflows
Business applications:
• Contract analysis, financial review, and healthcare records organization
• Government processing, educational curation, and IP protection
Workflow scenarios:
• Large-scale processing, automated classification, and information extraction
• Document preparation for further processing or analysis
Target users: Legal professionals, researchers, compliance officers, and
organizations requiring intelligent document content discovery and organization.
Typical uses:
• Reject files that are too big or too small
• Detect image-only PDFs that should go through OCR
• Ensure a document has enough pages before it enters a workflow
• Check orientation of pages before printing or merging
""")
public @interface FilterApi {}
@@ -22,21 +22,13 @@ import io.swagger.v3.oas.annotations.tags.Tag;
name = "General",
description =
"""
Core PDF processing operations for fundamental document manipulation workflows.
Page-level PDF editing: split, merge, rotate, crop, rearrange, and scale pages.
These endpoints handle most daily "I opened a PDF editor just to…" type tasks.
This endpoint group provides essential PDF functionality that forms the foundation
of most document processing workflows across various industries.
Common use cases:
• Document preparation for archival systems and content organization
• File preparation for distribution, accessibility compliance, and batch processing
• Document consolidation for reporting and legal compliance workflows
Typical applications:
• Content management, publishing workflows, and educational content distribution
• Business process automation and archive management
Target users: Content managers, document processors, and organizations requiring
reliable foundational PDF manipulation capabilities.
Typical uses:
• Split a large PDF into smaller files (by pages, chapters, or size)
• Merge several PDFs into one report or pack
• Rotate or reorder pages before sending or archiving
• Turn a multi-page document into one long scrolling page
""")
public @interface GeneralApi {}
@@ -22,25 +22,15 @@ import io.swagger.v3.oas.annotations.tags.Tag;
name = "Misc",
description =
"""
Specialized utilities and supplementary tools for enhanced document processing workflows.
Tools that don't fit neatly elsewhere: OCR, compress, repair, flatten, extract images, update metadata, add stamps/page numbers/images, and more.
These endpoints help fix problem PDFs and prepare them for sharing, storage, or further processing.
This endpoint group provides utility operations that support core document processing
tasks and address specific workflow needs in real-world scenarios.
Common use cases:
• Document optimization for bandwidth-limited environments and storage cost management
• Document repair, content extraction, and validation for quality assurance
• Accessibility improvement and custom processing for specialized needs
Business applications:
• Web publishing optimization, email attachment management, and archive efficiency
• Mobile compatibility, print production, and legacy document recovery
Operational scenarios:
• Batch processing, quality control, and performance optimization
• Troubleshooting and recovery of problematic documents
Target users: System administrators, document specialists, and organizations requiring
specialized document processing and optimization tools.
Typical uses:
• Repair a damaged PDF or remove blank pages
• Run OCR on scanned PDFs so they become searchable
• Compress large PDFs for email or web download
• Extract embedded images or scans
• Add page numbers, stamps, or overlay an image (e.g. logo, seal)
• Update PDF metadata (title, author, etc.)
""")
public @interface MiscApi {}
@@ -22,25 +22,12 @@ import io.swagger.v3.oas.annotations.tags.Tag;
name = "Pipeline",
description =
"""
Automated document processing workflows for complex multi-stage business operations.
Run several PDF operations in one configured pipeline instead of calling multiple endpoints yourself.
Useful when you always do the same steps in sequence (for example: convert → OCR → compress → watermark).
This endpoint group enables organizations to create sophisticated document processing
workflows that combine multiple operations into streamlined, repeatable processes.
Common use cases:
• Invoice processing, legal document review, and healthcare records standardization
• Government processing, educational content preparation, and publishing automation
• Contract lifecycle management and approval processes
Business applications:
• Automated compliance reporting, large-scale migration, and quality assurance
• Archive preparation, content delivery, and document approval workflows
Operational scenarios:
• Scheduled batch processing and event-driven document processing
• Multi-department coordination and business system integration
Target users: Business process managers, IT automation specialists, and organizations
requiring consistent, repeatable document processing workflows.
Typical uses:
• Process incoming invoices in one go (clean, OCR, compress, stamp, etc.)
• Normalise documents before they enter an archive
• Wrap a complex document flow behind a single API call for your own apps
""")
public @interface PipelineApi {}
@@ -22,25 +22,13 @@ import io.swagger.v3.oas.annotations.tags.Tag;
name = "Security",
description =
"""
Document security and protection services for confidential and sensitive content.
Protect and clean PDFs: passwords, digital signatures, redaction, and sanitizing.
These endpoints help you control who can open a file, what they can do with it, and remove sensitive content when needed.
This endpoint group provides essential security operations for organizations handling
sensitive documents and materials requiring controlled access.
Common use cases:
• Legal confidentiality, healthcare privacy (HIPAA), and financial regulatory compliance
• Government classified handling, corporate IP protection, and educational privacy (FERPA)
• Contract security for business transactions
Business applications:
• Document authentication, confidential sharing, and secure archiving
• Content watermarking, access control, and privacy protection through redaction
Industry scenarios:
• Legal discovery, medical records exchange, financial audit documentation
• Enterprise policy enforcement and data governance
Target users: Legal professionals, healthcare administrators, compliance officers,
government agencies, and enterprises handling sensitive content.
Typical uses:
• Add or remove a password on a PDF
• Redact personal or confidential information (manually or automatically)
• Validate or remove digital signatures
• Sanitize a PDF to strip scripts and embedded content
""")
public @interface SecurityApi {}
@@ -1,14 +0,0 @@
package stirling.software.common.model.api.security;
import java.util.List;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class AddParticipantsRequest {
private List<Long> participantUserIds;
}
@@ -1,48 +0,0 @@
package stirling.software.common.model.api.security;
import java.util.List;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import lombok.EqualsAndHashCode;
import stirling.software.common.model.api.PDFFile;
@Data
@EqualsAndHashCode(callSuper = true)
public class CreateSigningSessionRequest extends PDFFile {
@Schema(description = "Owner email used for activity updates")
private String ownerEmail;
@Schema(
description = "User IDs of participants to invite for signing",
requiredMode = Schema.RequiredMode.REQUIRED)
private List<Long> participantUserIds;
@Schema(description = "Optional message included in notifications")
private String message;
@Schema(description = "Optional due date for reminders (ISO-8601 date)")
private String dueDate;
@Schema(description = "Whether to send notifications immediately")
private Boolean notifyOnCreate;
// Signature appearance settings (owner-controlled, applied to all participants)
@Schema(description = "Whether to show visible signature")
private Boolean showSignature;
@Schema(description = "Page number for signature (1-indexed)")
private Integer pageNumber;
@Schema(description = "Signature reason")
private String reason;
@Schema(description = "Signature location")
private String location;
@Schema(description = "Whether to show Stirling PDF logo in signature")
private Boolean showLogo;
}
@@ -1,17 +0,0 @@
package stirling.software.common.model.api.security;
import java.util.List;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
@Data
public class NotifySigningParticipantsRequest {
@Schema(description = "Participants to notify; defaults to all if omitted")
private List<String> participantEmails;
@Schema(description = "Notification message to deliver")
private String message;
}
@@ -1,50 +0,0 @@
package stirling.software.common.model.api.security;
import org.springframework.web.multipart.MultipartFile;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
@Data
public class ParticipantCertificateRequest {
@Schema(
description = "Certificate type for the participant",
allowableValues = {"PEM", "PKCS12", "PFX", "JKS", "SERVER"},
requiredMode = Schema.RequiredMode.REQUIRED)
private String certType;
@Schema(description = "Password for keystore or private key", format = "password")
private String password;
@Schema(description = "Private key for PEM flow")
private MultipartFile privateKeyFile;
@Schema(description = "Certificate for PEM flow")
private MultipartFile certFile;
@Schema(description = "PKCS12/PFX keystore")
private MultipartFile p12File;
@Schema(description = "JKS keystore")
private MultipartFile jksFile;
@Schema(description = "Display the signature visually")
private Boolean showSignature;
@Schema(description = "Page number for visible signature (1-indexed)")
private Integer pageNumber;
@Schema(description = "Custom signer name override")
private String name;
@Schema(description = "Signing reason")
private String reason;
@Schema(description = "Signing location")
private String location;
@Schema(description = "Show the Stirling PDF logo in the appearance")
private Boolean showLogo;
}
@@ -1,21 +0,0 @@
package stirling.software.common.model.api.security;
import lombok.Builder;
import lombok.Data;
@Data
@Builder
public class ParticipantCertificateSubmission {
private String certType;
private String password;
private byte[] privateKey;
private byte[] certificate;
private byte[] p12Keystore;
private byte[] jksKeystore;
private Boolean showSignature;
private Integer pageNumber;
private String name;
private String reason;
private String location;
private Boolean showLogo;
}
@@ -1,25 +0,0 @@
package stirling.software.common.model.api.security;
import java.time.LocalDateTime;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class ParticipantDTO {
private Long userId;
private String username;
private String displayName;
private ParticipantStatus status;
private LocalDateTime lastUpdated;
// Signature appearance settings (owner-controlled)
private Boolean showSignature;
private Integer pageNumber;
private String reason;
private String location;
private Boolean showLogo;
}
@@ -1,9 +0,0 @@
package stirling.software.common.model.api.security;
public enum ParticipantStatus {
PENDING,
NOTIFIED,
VIEWED,
SIGNED,
DECLINED
}
@@ -1,81 +0,0 @@
package stirling.software.common.model.api.security;
import org.springframework.web.multipart.MultipartFile;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Pattern;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* Request object for signing a document. Combines certificate submission data with optional wet
* signature (visual signature) metadata.
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class SignDocumentRequest {
// Certificate-related fields
@NotNull(message = "Certificate type is required")
@Pattern(
regexp = "SERVER|USER_CERT|UPLOAD|PEM|PKCS12|PFX|JKS",
message = "Invalid certificate type")
private String certType;
private MultipartFile p12File;
private String password;
private MultipartFile privateKeyFile;
private MultipartFile certFile;
// Wet signature metadata fields (optional)
private String wetSignatureType; // "canvas" | "image" | "text"
private String wetSignatureData; // Base64 image data or text
private Integer wetSignaturePage; // Zero-indexed page number
private Double wetSignatureX; // X coordinate in PDF points
private Double wetSignatureY; // Y coordinate in PDF points (top-left origin)
private Double wetSignatureWidth; // Width in PDF points
private Double wetSignatureHeight; // Height in PDF points
/**
* Checks if this request includes wet signature metadata.
*
* @return true if wet signature data is present
*/
public boolean hasWetSignature() {
return wetSignatureType != null
&& wetSignatureData != null
&& wetSignaturePage != null
&& wetSignatureX != null
&& wetSignatureY != null
&& wetSignatureWidth != null
&& wetSignatureHeight != null;
}
/**
* Extracts wet signature metadata into a dedicated DTO.
*
* @return WetSignatureMetadata object if wet signature is present, null otherwise
*/
public WetSignatureMetadata extractWetSignatureMetadata() {
if (!hasWetSignature()) {
return null;
}
WetSignatureMetadata metadata = new WetSignatureMetadata();
metadata.setType(wetSignatureType);
metadata.setData(wetSignatureData);
metadata.setPage(wetSignaturePage);
metadata.setX(wetSignatureX);
metadata.setY(wetSignatureY);
metadata.setWidth(wetSignatureWidth);
metadata.setHeight(wetSignatureHeight);
// Validate the metadata
metadata.validate();
return metadata;
}
}
@@ -1,25 +0,0 @@
package stirling.software.common.model.api.security;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/** DTO for sign request detail (participant view) */
@Data
@NoArgsConstructor
@AllArgsConstructor
public class SignRequestDetailDTO {
private String sessionId;
private String documentName;
private String ownerUsername;
private String message;
private String dueDate;
private String createdAt;
private ParticipantStatus myStatus;
// Signature appearance settings (read-only, configured by owner)
private Boolean showSignature;
private Integer pageNumber;
private String reason;
private String location;
private Boolean showLogo;
}
@@ -1,18 +0,0 @@
package stirling.software.common.model.api.security;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/** DTO for sign request summary (participant view) */
@Data
@NoArgsConstructor
@AllArgsConstructor
public class SignRequestSummaryDTO {
private String sessionId;
private String documentName;
private String ownerUsername;
private String createdAt;
private String dueDate;
private ParticipantStatus myStatus;
}
@@ -1,26 +0,0 @@
package stirling.software.common.model.api.security;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import lombok.Data;
@Data
public class SigningParticipant {
private Long userId; // Database user ID (null for in-memory sessions)
private String email;
private String name;
private ParticipantStatus status = ParticipantStatus.PENDING;
private List<String> notifications = new ArrayList<>();
private String shareToken = UUID.randomUUID().toString();
private String lastUpdated = Instant.now().toString();
private ParticipantCertificateSubmission certificateSubmission;
public void recordNotification(String message) {
notifications.add(message);
lastUpdated = Instant.now().toString();
}
}
@@ -1,26 +0,0 @@
package stirling.software.common.model.api.security;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import lombok.Data;
@Data
public class SigningSession {
private String sessionId = UUID.randomUUID().toString();
private String documentName;
private byte[] originalPdf;
private byte[] signedPdf;
private String ownerEmail;
private String message;
private String dueDate;
private String createdAt = Instant.now().toString();
private String updatedAt = Instant.now().toString();
private List<SigningParticipant> participants = new ArrayList<>();
public void touch() {
updatedAt = Instant.now().toString();
}
}
@@ -1,23 +0,0 @@
package stirling.software.common.model.api.security;
import java.time.LocalDateTime;
import java.util.List;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class SigningSessionDetailDTO {
private String sessionId;
private String documentName;
private String ownerEmail;
private String message;
private String dueDate;
private LocalDateTime createdAt;
private LocalDateTime updatedAt;
private boolean finalized;
private List<ParticipantDTO> participants;
}
@@ -1,19 +0,0 @@
package stirling.software.common.model.api.security;
import java.time.LocalDateTime;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class SigningSessionSummaryDTO {
private String sessionId;
private String documentName;
private LocalDateTime createdAt;
private int participantCount;
private int signedCount;
private boolean finalized;
}
@@ -1,16 +0,0 @@
package stirling.software.common.model.api.security;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class UserSummaryDTO {
private Long userId;
private String username;
private String displayName;
private String teamName;
private boolean enabled;
}
@@ -1,96 +0,0 @@
package stirling.software.common.model.api.security;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Pattern;
import jakarta.validation.constraints.Positive;
import jakarta.validation.constraints.PositiveOrZero;
import jakarta.validation.constraints.Size;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* Data Transfer Object for wet signature (visual signature) metadata. Contains information about a
* signature annotation placed by a participant on the PDF. This data is used to overlay the
* signature on the PDF during finalization.
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class WetSignatureMetadata {
/** Type of wet signature: "canvas" (drawn), "image" (uploaded), or "text" (typed) */
@NotNull(message = "Wet signature type is required")
@Pattern(
regexp = "canvas|image|text",
message = "Wet signature type must be canvas, image, or text")
private String type;
/**
* Base64-encoded image data or text content for the signature. For canvas/image types:
* data:image/png;base64,... format For text type: plain text string
*/
@NotNull(message = "Wet signature data is required")
@Size(max = 5_000_000, message = "Wet signature data exceeds maximum size of 5MB")
private String data;
/** Zero-indexed page number where the signature is placed */
@NotNull(message = "Page number is required")
@PositiveOrZero(message = "Page number must be zero or positive")
private Integer page;
/** X coordinate (in PDF points) of the signature rectangle, measured from left edge */
@NotNull(message = "X coordinate is required")
@PositiveOrZero(message = "X coordinate must be zero or positive")
private Double x;
/**
* Y coordinate (in PDF points) of the signature rectangle, measured from top edge. Note: This
* is UI coordinate system (top-left origin). Will be converted to PDF coordinate system
* (bottom-left origin) during overlay.
*/
@NotNull(message = "Y coordinate is required")
@PositiveOrZero(message = "Y coordinate must be zero or positive")
private Double y;
/** Width of the signature rectangle in PDF points */
@NotNull(message = "Width is required")
@Positive(message = "Width must be positive")
private Double width;
/** Height of the signature rectangle in PDF points */
@NotNull(message = "Height is required")
@Positive(message = "Height must be positive")
private Double height;
/**
* Validates that the wet signature data is properly formatted based on type. For image types,
* ensures data starts with data:image prefix.
*
* @return true if validation passes
* @throws IllegalArgumentException if validation fails
*/
public boolean validate() {
if (type.equals("canvas") || type.equals("image")) {
if (!data.startsWith("data:image/")) {
throw new IllegalArgumentException(
"Image wet signature data must start with data:image/ prefix");
}
}
return true;
}
/**
* Extracts just the base64 data portion from a data URL. Removes the "data:image/png;base64,"
* prefix.
*
* @return pure base64 string without data URL prefix
*/
public String extractBase64Data() {
if (data != null && data.contains(",")) {
return data.substring(data.indexOf(",") + 1);
}
return data;
}
}
@@ -0,0 +1,21 @@
package stirling.software.common.service;
import java.io.IOException;
/**
* Interface for personal signature access (proprietary feature). Implemented only in proprietary
* module to provide authenticated users access to their personal signatures.
*/
public interface PersonalSignatureServiceInterface {
/**
* Get a personal signature from the user's folder. Only checks personal folder, not shared
* folder.
*
* @param username Username of the signature owner
* @param fileName Signature filename
* @return Personal signature image bytes
* @throws IOException If file not found or read error
*/
byte[] getPersonalSignatureBytes(String username, String fileName) throws IOException;
}
@@ -1,155 +0,0 @@
package stirling.software.common.service;
import java.io.IOException;
import java.util.List;
public interface SigningSessionServiceInterface {
/**
* Creates a new signing session
*
* @param request The session creation request
* @param username The username of the session owner (optional, pass null for non-authenticated)
* @return The created session (implementation-specific return type)
*/
Object createSession(Object request, String username) throws IOException;
/**
* Gets a signing session by ID
*
* @param sessionId The session ID
* @return The session object (implementation-specific return type)
*/
Object getSession(String sessionId);
/**
* Lists all sessions for a user
*
* @param username The username
* @return List of session summaries (implementation-specific return type)
*/
List<?> listUserSessions(String username);
/**
* Gets detailed session information with ownership validation
*
* @param sessionId The session ID
* @param username The username for ownership validation
* @return Detailed session object (implementation-specific return type)
*/
Object getSessionDetail(String sessionId, String username);
/**
* Deletes a session
*
* @param sessionId The session ID
* @param username The username for ownership validation
*/
void deleteSession(String sessionId, String username);
/**
* Adds participants to a session
*
* @param sessionId The session ID
* @param request The request containing participant emails and names
* @param username The username for ownership validation
* @return Updated session detail (implementation-specific return type)
*/
Object addParticipants(String sessionId, Object request, String username);
/**
* Removes a participant from a session
*
* @param sessionId The session ID
* @param userId The participant's user ID
* @param username The username for ownership validation
*/
void removeParticipant(String sessionId, Long userId, String username);
/**
* Notifies participants
*
* @param sessionId The session ID
* @param request The notification request
* @return The updated session (implementation-specific return type)
*/
Object notifyParticipants(String sessionId, Object request);
/**
* Attaches a certificate for a participant
*
* @param sessionId The session ID
* @param userId The participant's user ID
* @param request The certificate request
* @return The updated session (implementation-specific return type)
*/
Object attachCertificate(String sessionId, Long userId, Object request) throws IOException;
/**
* Marks a session as finalized
*
* @param sessionId The session ID
* @param signedPdf The final signed PDF bytes
*/
void markSessionFinalized(String sessionId, byte[] signedPdf);
/**
* Gets the PDF for a session with user authentication
*
* @param sessionId The session ID
* @param username The participant's username
* @return The PDF bytes
*/
byte[] getSessionPdf(String sessionId, String username);
/**
* Gets the signed PDF from a finalized session with ownership validation
*
* @param sessionId The session ID
* @param username The username for ownership validation
* @return The signed PDF bytes, or null if not finalized
*/
byte[] getSignedPdf(String sessionId, String username);
/**
* Lists sign requests for a participant
*
* @param username The participant's username
* @return List of sign requests where user is a participant
*/
List<?> listSignRequests(String username);
/**
* Gets sign request detail for a participant
*
* @param sessionId The session ID
* @param username The participant's username
* @return Sign request detail DTO (implementation-specific return type)
*/
Object getSignRequestDetail(String sessionId, String username);
/**
* Declines a sign request
*
* @param sessionId The session ID
* @param username The participant's username
*/
void declineSignRequest(String sessionId, String username);
/**
* Signs a document with optional wet signature metadata
*
* @param sessionId The session ID
* @param username The participant's username
* @param request The sign document request containing certificate and wet signature data
* @throws IOException if certificate processing fails
*/
void signDocument(String sessionId, String username, Object request) throws IOException;
/**
* Checks if this is the database-backed implementation
*
* @return true if database-backed, false if in-memory
*/
boolean isDatabaseBacked();
}
@@ -39,6 +39,7 @@ public class RequestUriUtils {
// Specific static files bundled with the frontend
if (normalizedUri.equals("/robots.txt")
|| normalizedUri.equals("/favicon.ico")
|| normalizedUri.equals("/manifest.json")
|| normalizedUri.equals("/site.webmanifest")
|| normalizedUri.equals("/manifest-classic.json")
|| normalizedUri.equals("/index.html")) {
@@ -159,6 +160,8 @@ public class RequestUriUtils {
|| trimmedUri.startsWith(
"/api/v1/proprietary/ui-data/login") // Login page config (SSO providers +
// enableLogin)
|| trimmedUri.startsWith(
"/api/v1/ui-data/footer-info") // Public footer configuration
|| trimmedUri.startsWith("/v1/api-docs")
|| trimmedUri.startsWith("/api/v1/invite/validate")
|| trimmedUri.startsWith("/api/v1/invite/accept")
@@ -95,7 +95,7 @@ public class InitialSetup {
isNewServer =
existingVersion == null
|| existingVersion.isEmpty()
|| "0.0.0".equals(existingVersion);
|| existingVersion.equals("0.0.0");
String appVersion = "0.0.0";
Resource resource = new ClassPathResource("version.properties");
@@ -21,6 +21,9 @@ public class SpringDocConfig {
"/api/v1/user/**",
"/api/v1/settings/**",
"/api/v1/team/**",
"/api/v1/auth/**",
"/api/v1/invite/**",
"/api/v1/audit/**",
"/api/v1/ui-data/**",
"/api/v1/proprietary/ui-data/**",
"/api/v1/info/**",
@@ -33,7 +36,7 @@ public class SpringDocConfig {
openApi.getInfo()
.title("Stirling PDF - Processing API")
.description(
"API documentation for PDF processing operations including conversion, manipulation, security, and utilities."));
"APIs for converting, editing, securing, and analysing PDF documents. Use these endpoints to automate common PDF tasks (like split, merge, convert, OCR) and plug them into your own apps and backend jobs."));
})
.build();
}
@@ -47,14 +50,17 @@ public class SpringDocConfig {
"/api/v1/admin/**",
"/api/v1/user/**",
"/api/v1/settings/**",
"/api/v1/team/**")
"/api/v1/team/**",
"/api/v1/auth/**",
"/api/v1/invite/**",
"/api/v1/audit/**")
.addOpenApiCustomizer(
openApi -> {
openApi.info(
openApi.getInfo()
.title("Stirling PDF - Admin API")
.title("Stirling PDF - Management API")
.description(
"API documentation for administrative functions, user management, and system configuration."));
"Endpoints for authentication, user management, invitations, audit logging, and system configuration."));
})
.build();
}
@@ -76,7 +82,7 @@ public class SpringDocConfig {
openApi.getInfo()
.title("Stirling PDF - System API")
.description(
"API documentation for system information, UI data, and utility endpoints."));
"System information, UI metadata, job status, and file management endpoints."));
})
.build();
}
@@ -26,7 +26,7 @@ import lombok.extern.slf4j.Slf4j;
import stirling.software.SPDF.model.Dependency;
import stirling.software.SPDF.model.SignatureFile;
import stirling.software.SPDF.service.SignatureService;
import stirling.software.SPDF.service.SharedSignatureService;
import stirling.software.common.annotations.api.UiDataApi;
import stirling.software.common.configuration.InstallationPathConfig;
import stirling.software.common.configuration.RuntimePathConfig;
@@ -40,14 +40,14 @@ import stirling.software.common.util.GeneralUtils;
public class UIDataController {
private final ApplicationProperties applicationProperties;
private final SignatureService signatureService;
private final SharedSignatureService signatureService;
private final UserServiceInterface userService;
private final ResourceLoader resourceLoader;
private final RuntimePathConfig runtimePathConfig;
public UIDataController(
ApplicationProperties applicationProperties,
SignatureService signatureService,
SharedSignatureService signatureService,
@Autowired(required = false) UserServiceInterface userService,
ResourceLoader resourceLoader,
RuntimePathConfig runtimePathConfig) {
@@ -58,6 +58,21 @@ public class UIDataController {
this.runtimePathConfig = runtimePathConfig;
}
@GetMapping("/footer-info")
@Operation(summary = "Get public footer configuration data")
public ResponseEntity<FooterData> getFooterData() {
FooterData data = new FooterData();
data.setAnalyticsEnabled(applicationProperties.getSystem().getEnableAnalytics());
data.setTermsAndConditions(applicationProperties.getLegal().getTermsAndConditions());
data.setPrivacyPolicy(applicationProperties.getLegal().getPrivacyPolicy());
data.setAccessibilityStatement(
applicationProperties.getLegal().getAccessibilityStatement());
data.setCookiePolicy(applicationProperties.getLegal().getCookiePolicy());
data.setImpressum(applicationProperties.getLegal().getImpressum());
return ResponseEntity.ok(data);
}
@GetMapping("/home")
@Operation(summary = "Get home page data")
public ResponseEntity<HomeData> getHomeData() {
@@ -237,6 +252,16 @@ public class UIDataController {
}
// Data classes
@Data
public static class FooterData {
private Boolean analyticsEnabled;
private String termsAndConditions;
private String privacyPolicy;
private String accessibilityStatement;
private String cookiePolicy;
private String impressum;
}
@Data
public static class HomeData {
private boolean showSurveyFromDocker;
@@ -72,7 +72,6 @@ import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import stirling.software.SPDF.config.swagger.StandardPdfResponse;
import stirling.software.SPDF.model.api.security.MultiSignPDFWithCertRequest;
import stirling.software.SPDF.model.api.security.SignPDFWithCertRequest;
import stirling.software.common.annotations.AutoJobPostMapping;
import stirling.software.common.service.CustomPDFDocumentFactory;
@@ -114,7 +113,7 @@ public class CertSignController {
this.serverCertificateService = serverCertificateService;
}
static void sign(
private static void sign(
CustomPDFDocumentFactory pdfDocumentFactory,
MultipartFile input,
OutputStream output,
@@ -150,42 +149,6 @@ public class CertSignController {
}
}
static void sign(
CustomPDFDocumentFactory pdfDocumentFactory,
InputStream input,
OutputStream output,
CreateSignature instance,
Boolean showSignature,
Integer pageNumber,
String name,
String location,
String reason,
Boolean showLogo) {
try (PDDocument doc = pdfDocumentFactory.load(input)) {
PDSignature signature = new PDSignature();
signature.setFilter(PDSignature.FILTER_ADOBE_PPKLITE);
signature.setSubFilter(PDSignature.SUBFILTER_ADBE_PKCS7_DETACHED);
signature.setName(name);
signature.setLocation(location);
signature.setReason(reason);
signature.setSignDate(Calendar.getInstance());
if (Boolean.TRUE.equals(showSignature)) {
SignatureOptions signatureOptions = new SignatureOptions();
signatureOptions.setVisualSignature(
instance.createVisibleSignature(doc, signature, pageNumber, showLogo));
signatureOptions.setPage(pageNumber);
doc.addSignature(signature, instance, signatureOptions);
} else {
doc.addSignature(signature, instance);
}
doc.saveIncremental(output);
} catch (Exception e) {
ExceptionUtils.logException("PDF signing", e);
}
}
@AutoJobPostMapping(
consumes = {
MediaType.MULTIPART_FORM_DATA_VALUE,
@@ -288,143 +251,7 @@ public class CertSignController {
GeneralUtils.generateFilename(pdf.getOriginalFilename(), "_signed.pdf"));
}
@AutoJobPostMapping(
consumes = {
MediaType.MULTIPART_FORM_DATA_VALUE,
MediaType.APPLICATION_FORM_URLENCODED_VALUE
},
value = "/cert-sign/multi")
@StandardPdfResponse
@Operation(
summary = "Sign PDF with multiple Digital Certificates",
description =
"This endpoint accepts a PDF file and multiple digital certificates to"
+ " sequentially sign the document. Input:PDF Output:PDF Type:SISO")
public ResponseEntity<byte[]> multiSignPDFWithCert(
@ModelAttribute MultiSignPDFWithCertRequest request) throws Exception {
if (request.getCertTypes() == null || request.getCertTypes().isEmpty()) {
throw ExceptionUtils.createIllegalArgumentException(
"error.optionsNotSpecified",
"{0} options are not specified",
"certificate types");
}
byte[] currentPdf = request.getFileInput().getBytes();
String originalFilename = request.getFileInput().getOriginalFilename();
for (int i = 0; i < request.getCertTypes().size(); i++) {
String certType = request.getCertTypes().get(i);
KeyStore ks = null;
String keystorePassword = getFromList(request.getPasswords(), i, "");
switch (certType) {
case "PEM":
ks = KeyStore.getInstance("JKS");
ks.load(null);
MultipartFile privateKeyFile =
getFromList(request.getPrivateKeyFiles(), i, null);
MultipartFile certFile = getFromList(request.getCertFiles(), i, null);
if (privateKeyFile == null || certFile == null) {
throw ExceptionUtils.createIllegalArgumentException(
"error.optionsNotSpecified",
"{0} options are not specified",
"certificate and key files for signer " + (i + 1));
}
PrivateKey privateKey =
getPrivateKeyFromPEM(privateKeyFile.getBytes(), keystorePassword);
Certificate cert = (Certificate) getCertificateFromPEM(certFile.getBytes());
ks.setKeyEntry(
"alias",
privateKey,
keystorePassword.toCharArray(),
new Certificate[] {cert});
break;
case "PKCS12":
case "PFX":
MultipartFile p12File = getFromList(request.getP12Files(), i, null);
if (p12File == null) {
throw ExceptionUtils.createIllegalArgumentException(
"error.optionsNotSpecified",
"{0} options are not specified",
"PKCS12/PFX keystore for signer " + (i + 1));
}
ks = KeyStore.getInstance("PKCS12");
ks.load(p12File.getInputStream(), keystorePassword.toCharArray());
break;
case "JKS":
MultipartFile jksfile = getFromList(request.getJksFiles(), i, null);
if (jksfile == null) {
throw ExceptionUtils.createIllegalArgumentException(
"error.optionsNotSpecified",
"{0} options are not specified",
"JKS keystore for signer " + (i + 1));
}
ks = KeyStore.getInstance("JKS");
ks.load(jksfile.getInputStream(), keystorePassword.toCharArray());
break;
case "SERVER":
if (serverCertificateService == null) {
throw ExceptionUtils.createIllegalArgumentException(
"error.serverCertificateNotAvailable",
"Server certificate service is not available in this edition");
}
if (!serverCertificateService.isEnabled()) {
throw ExceptionUtils.createIllegalArgumentException(
"error.serverCertificateDisabled",
"Server certificate feature is disabled");
}
if (!serverCertificateService.hasServerCertificate()) {
throw ExceptionUtils.createIllegalArgumentException(
"error.serverCertificateNotFound",
"No server certificate configured");
}
ks = serverCertificateService.getServerKeyStore();
keystorePassword = serverCertificateService.getServerCertificatePassword();
break;
default:
throw ExceptionUtils.createIllegalArgumentException(
"error.invalidArgument",
"Invalid argument: {0}",
"certificate type: " + certType);
}
CreateSignature createSignature =
new CreateSignature(ks, keystorePassword.toCharArray());
ByteArrayOutputStream baos = new ByteArrayOutputStream();
String signerName = getFromList(request.getNames(), i, "SPDF");
String location = getFromList(request.getLocations(), i, "SPDF");
String reason = getFromList(request.getReasons(), i, "Signed by SPDF");
Boolean showSignature = getFromList(request.getShowSignatures(), i, Boolean.FALSE);
Boolean showLogo = getFromList(request.getShowLogos(), i, Boolean.TRUE);
Integer pageNumber = getFromList(request.getPageNumbers(), i, null);
pageNumber = pageNumber != null ? pageNumber - 1 : null;
sign(
pdfDocumentFactory,
new ByteArrayInputStream(currentPdf),
baos,
createSignature,
showSignature,
pageNumber,
signerName,
location,
reason,
showLogo);
currentPdf = baos.toByteArray();
}
return WebResponseUtils.bytesToWebResponse(
currentPdf, GeneralUtils.generateFilename(originalFilename, "_multi_signed.pdf"));
}
private static <T> T getFromList(List<T> list, int index, T defaultValue) {
if (list == null || list.size() <= index) {
return defaultValue;
}
return list.get(index);
}
public PrivateKey getPrivateKeyFromPEM(byte[] pemBytes, String password)
private PrivateKey getPrivateKeyFromPEM(byte[] pemBytes, String password)
throws IOException, OperatorCreationException, PKCSException {
try (PEMParser pemParser =
new PEMParser(new InputStreamReader(new ByteArrayInputStream(pemBytes)))) {
@@ -446,14 +273,14 @@ public class CertSignController {
}
}
public Certificate getCertificateFromPEM(byte[] pemBytes)
private Certificate getCertificateFromPEM(byte[] pemBytes)
throws IOException, CertificateException {
try (ByteArrayInputStream bis = new ByteArrayInputStream(pemBytes)) {
return CertificateFactory.getInstance("X.509").generateCertificate(bis);
}
}
static class CreateSignature extends CreateSignatureBase {
class CreateSignature extends CreateSignatureBase {
File logoFile;
public CreateSignature(KeyStore keystore, char[] pin)
@@ -1,678 +0,0 @@
package stirling.software.SPDF.controller.api.security;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.security.KeyStore;
import java.security.Principal;
import java.security.PrivateKey;
import java.security.cert.Certificate;
import java.util.List;
import java.util.Locale;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.constraints.NotBlank;
import lombok.extern.slf4j.Slf4j;
import stirling.software.SPDF.config.swagger.StandardPdfResponse;
import stirling.software.SPDF.controller.api.security.CertSignController.CreateSignature;
import stirling.software.SPDF.service.SigningSessionService;
import stirling.software.common.model.api.security.*;
import stirling.software.common.service.CustomPDFDocumentFactory;
import stirling.software.common.service.ServerCertificateServiceInterface;
import stirling.software.common.service.SigningSessionServiceInterface;
import stirling.software.common.util.ExceptionUtils;
import stirling.software.common.util.GeneralUtils;
import stirling.software.common.util.WebResponseUtils;
import stirling.software.proprietary.service.UserServerCertificateService;
@Slf4j
@RestController
@RequestMapping("/api/v1/security")
@Tag(name = "Security", description = "Security APIs")
public class SigningSessionController {
private final SigningSessionService signingSessionService;
private final CustomPDFDocumentFactory pdfDocumentFactory;
private final ServerCertificateServiceInterface serverCertificateServiceInterface;
private final SigningSessionServiceInterface sessionServiceInterface;
private final UserServerCertificateService userServerCertificateService;
public SigningSessionController(
SigningSessionService signingSessionService,
CustomPDFDocumentFactory pdfDocumentFactory,
@Autowired(required = false)
ServerCertificateServiceInterface serverCertificateServiceInterface,
@Autowired(required = false)
List<SigningSessionServiceInterface> signingSessionServices,
@Autowired(required = false)
UserServerCertificateService userServerCertificateService) {
this.signingSessionService = signingSessionService;
this.pdfDocumentFactory = pdfDocumentFactory;
this.serverCertificateServiceInterface = serverCertificateServiceInterface;
this.userServerCertificateService = userServerCertificateService;
// Use database-backed service if available, otherwise fall back to in-memory
this.sessionServiceInterface =
signingSessionServices != null && !signingSessionServices.isEmpty()
? signingSessionServices.stream()
.filter(SigningSessionServiceInterface::isDatabaseBacked)
.findFirst()
.orElse(signingSessionService)
: signingSessionService;
}
@Operation(summary = "List all signing sessions for current user")
@GetMapping(value = "/cert-sign/sessions")
public ResponseEntity<?> listSessions(Principal principal) {
if (principal == null || !sessionServiceInterface.isDatabaseBacked()) {
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("Authentication required");
}
try {
List<?> sessions = sessionServiceInterface.listUserSessions(principal.getName());
return ResponseEntity.ok(sessions);
} catch (Exception e) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body("Error listing sessions");
}
}
@PostMapping(
consumes = {
MediaType.MULTIPART_FORM_DATA_VALUE,
MediaType.APPLICATION_FORM_URLENCODED_VALUE
},
value = "/cert-sign/sessions",
produces = MediaType.APPLICATION_JSON_VALUE)
@Operation(
summary = "Create a shared signing session",
description =
"Starts a collaboration session, distributes share links, and optionally notifies participants."
+ " Input:PDF Output:JSON Type:SISO")
public ResponseEntity<?> createSession(
@ModelAttribute CreateSigningSessionRequest request, Principal principal)
throws Exception {
if (sessionServiceInterface.isDatabaseBacked() && principal != null) {
Object session = sessionServiceInterface.createSession(request, principal.getName());
return ResponseEntity.ok(session);
} else {
SigningSession session = signingSessionService.createSession(request);
return ResponseEntity.ok(session);
}
}
@Operation(summary = "Fetch signing session details")
@GetMapping(value = "/cert-sign/sessions/{sessionId}")
public ResponseEntity<?> getSession(
@PathVariable("sessionId") @NotBlank String sessionId, Principal principal) {
if (sessionServiceInterface.isDatabaseBacked() && principal != null) {
try {
Object session =
sessionServiceInterface.getSessionDetail(sessionId, principal.getName());
return ResponseEntity.ok(session);
} catch (Exception e) {
return ResponseEntity.status(HttpStatus.FORBIDDEN)
.body("Access denied or session not found");
}
} else {
SigningSession session = signingSessionService.getSession(sessionId);
return ResponseEntity.ok(session);
}
}
@Operation(summary = "Delete a signing session")
@DeleteMapping(value = "/cert-sign/sessions/{sessionId}")
public ResponseEntity<?> deleteSession(
@PathVariable("sessionId") @NotBlank String sessionId, Principal principal) {
if (principal == null || !sessionServiceInterface.isDatabaseBacked()) {
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("Authentication required");
}
try {
sessionServiceInterface.deleteSession(sessionId, principal.getName());
return ResponseEntity.noContent().build();
} catch (Exception e) {
return ResponseEntity.status(HttpStatus.FORBIDDEN)
.body("Cannot delete session: " + e.getMessage());
}
}
@Operation(summary = "Add participants to an existing session")
@PostMapping(value = "/cert-sign/sessions/{sessionId}/participants")
public ResponseEntity<?> addParticipants(
@PathVariable("sessionId") @NotBlank String sessionId,
@RequestBody AddParticipantsRequest request,
Principal principal) {
if (principal == null || !sessionServiceInterface.isDatabaseBacked()) {
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("Authentication required");
}
try {
Object session =
sessionServiceInterface.addParticipants(
sessionId, request, principal.getName());
return ResponseEntity.ok(session);
} catch (Exception e) {
return ResponseEntity.status(HttpStatus.FORBIDDEN)
.body("Cannot add participants: " + e.getMessage());
}
}
@Operation(summary = "Remove a participant from a session")
@DeleteMapping(value = "/cert-sign/sessions/{sessionId}/participants/{userId}")
public ResponseEntity<?> removeParticipant(
@PathVariable("sessionId") @NotBlank String sessionId,
@PathVariable("userId") Long userId,
Principal principal) {
if (principal == null || !sessionServiceInterface.isDatabaseBacked()) {
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("Authentication required");
}
try {
sessionServiceInterface.removeParticipant(sessionId, userId, principal.getName());
return ResponseEntity.noContent().build();
} catch (Exception e) {
return ResponseEntity.status(HttpStatus.FORBIDDEN)
.body("Cannot remove participant: " + e.getMessage());
}
}
@Operation(summary = "Get session PDF for participant view")
@GetMapping(value = "/cert-sign/sessions/{sessionId}/pdf")
public ResponseEntity<byte[]> getSessionPdf(
@PathVariable("sessionId") @NotBlank String sessionId, Principal principal) {
if (principal == null || !sessionServiceInterface.isDatabaseBacked()) {
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
}
try {
byte[] pdfBytes = sessionServiceInterface.getSessionPdf(sessionId, principal.getName());
return WebResponseUtils.bytesToWebResponse(pdfBytes, "document.pdf");
} catch (Exception e) {
return ResponseEntity.status(HttpStatus.FORBIDDEN).build();
}
}
@PostMapping(value = "/cert-sign/sessions/{sessionId}/notify")
@Operation(summary = "Notify signing participants about outstanding requests")
public SigningSession notifyParticipants(
@PathVariable("sessionId") @NotBlank String sessionId,
@RequestBody NotifySigningParticipantsRequest request) {
return (SigningSession) sessionServiceInterface.notifyParticipants(sessionId, request);
}
@PostMapping(
value = "/cert-sign/sessions/{sessionId}/participants/{userId}/certificate",
consumes = {
MediaType.MULTIPART_FORM_DATA_VALUE,
MediaType.APPLICATION_FORM_URLENCODED_VALUE
})
@Operation(summary = "Attach certificate details for a specific participant")
public SigningSession attachCertificate(
@PathVariable("sessionId") @NotBlank String sessionId,
@PathVariable("userId") Long userId,
@ModelAttribute ParticipantCertificateRequest request)
throws Exception {
return (SigningSession)
sessionServiceInterface.attachCertificate(sessionId, userId, request);
}
@Operation(summary = "Get signed PDF from finalized session")
@GetMapping(value = "/cert-sign/sessions/{sessionId}/signed-pdf")
@StandardPdfResponse
public ResponseEntity<byte[]> getSignedPdf(
@PathVariable("sessionId") @NotBlank String sessionId, Principal principal) {
if (principal == null || !sessionServiceInterface.isDatabaseBacked()) {
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
}
try {
byte[] signedPdf = sessionServiceInterface.getSignedPdf(sessionId, principal.getName());
if (signedPdf == null) {
return ResponseEntity.status(HttpStatus.NOT_FOUND)
.body("Session not finalized".getBytes());
}
SigningSession session = (SigningSession) sessionServiceInterface.getSession(sessionId);
return WebResponseUtils.bytesToWebResponse(
signedPdf,
GeneralUtils.generateFilename(session.getDocumentName(), "_shared_signed.pdf"));
} catch (Exception e) {
return ResponseEntity.status(HttpStatus.FORBIDDEN).build();
}
}
@PostMapping(value = "/cert-sign/sessions/{sessionId}/finalize")
@Operation(
summary = "Finalize signing session",
description =
"Applies collected certificates in order and returns the signed document.")
@StandardPdfResponse
public ResponseEntity<byte[]> finalizeSession(
@PathVariable("sessionId") @NotBlank String sessionId, Principal principal)
throws Exception {
// Validate ownership if database service is available
if (sessionServiceInterface.isDatabaseBacked() && principal != null) {
try {
sessionServiceInterface.getSessionDetail(sessionId, principal.getName());
} catch (Exception e) {
return ResponseEntity.status(HttpStatus.FORBIDDEN).build();
}
}
SigningSession session = (SigningSession) sessionServiceInterface.getSession(sessionId);
byte[] pdf = session.getOriginalPdf();
// Step 1: Apply wet signatures (visual annotations) FIRST
if (sessionServiceInterface.isDatabaseBacked()) {
try {
pdf = applyWetSignatures(pdf, sessionId);
} catch (Exception e) {
log.error(
"Failed to apply wet signatures for session {}: {}",
sessionId,
e.getMessage());
// Continue with certificate signing even if wet signatures fail
}
}
// Step 2: Apply digital certificates
for (SigningParticipant participant : session.getParticipants()) {
ParticipantCertificateSubmission submission = participant.getCertificateSubmission();
if (submission == null || participant.getStatus() != ParticipantStatus.SIGNED) {
continue;
}
// Skip SERVER certificate type if feature is not available/enabled
if ("SERVER".equalsIgnoreCase(submission.getCertType())) {
if (serverCertificateServiceInterface == null
|| !serverCertificateServiceInterface.isEnabled()
|| !serverCertificateServiceInterface.hasServerCertificate()) {
// Skip this participant - server certificate not available
continue;
}
}
// Handle USER_CERT type - auto-generate if needed
if ("USER_CERT".equalsIgnoreCase(submission.getCertType())) {
if (userServerCertificateService == null
|| !sessionServiceInterface.isDatabaseBacked()) {
log.warn(
"USER_CERT requested but service not available, skipping participant: {}",
participant.getEmail());
continue;
}
}
KeyStore keystore = buildKeystore(submission, participant);
boolean usingServer = "SERVER".equalsIgnoreCase(submission.getCertType());
boolean usingUserCert = "USER_CERT".equalsIgnoreCase(submission.getCertType());
String password;
if (usingServer && serverCertificateServiceInterface != null) {
password = serverCertificateServiceInterface.getServerCertificatePassword();
} else if (usingUserCert && userServerCertificateService != null) {
password = submission.getPassword(); // Password stored in submission for user cert
} else {
password = submission.getPassword();
}
CreateSignature createSignature =
new CreateSignature(
keystore, password != null ? password.toCharArray() : new char[0]);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
CertSignController.sign(
pdfDocumentFactory,
new ByteArrayInputStream(pdf),
baos,
createSignature,
submission.getShowSignature(),
submission.getPageNumber() != null
? Math.max(submission.getPageNumber() - 1, 0)
: null,
StringUtils.defaultIfBlank(participant.getName(), "Shared Signing"),
StringUtils.defaultIfBlank(submission.getLocation(), ""),
StringUtils.defaultIfBlank(submission.getReason(), "Document Signing"),
submission.getShowLogo());
pdf = baos.toByteArray();
}
session.setSignedPdf(pdf);
// Mark session as finalized in database if database service is available
sessionServiceInterface.markSessionFinalized(sessionId, pdf);
// Step 3: Clean up wet signature metadata (GDPR compliance)
if (sessionServiceInterface.isDatabaseBacked()) {
try {
clearWetSignatureMetadata(sessionId);
} catch (Exception e) {
log.error(
"Failed to clear wet signature metadata for session {}: {}",
sessionId,
e.getMessage());
// Don't fail the finalization if cleanup fails
}
}
return WebResponseUtils.bytesToWebResponse(
pdf,
GeneralUtils.generateFilename(session.getDocumentName(), "_shared_signed.pdf"));
}
private KeyStore buildKeystore(
ParticipantCertificateSubmission submission, SigningParticipant participant)
throws Exception {
CertSignController certSignController =
new CertSignController(pdfDocumentFactory, serverCertificateServiceInterface);
String certType = submission.getCertType().toUpperCase(Locale.ROOT);
String password = submission.getPassword();
switch (certType) {
case "USER_CERT":
if (userServerCertificateService == null) {
throw ExceptionUtils.createIllegalArgumentException(
"error.userCertificateNotAvailable",
"User certificate service is not available in this edition");
}
// Get user ID from participant
Long userId = getUserIdFromParticipant(participant);
if (userId == null) {
throw ExceptionUtils.createIllegalArgumentException(
"error.userNotFound", "Cannot determine user ID for participant");
}
// Auto-generate certificate if user doesn't have one
try {
userServerCertificateService.getOrCreateUserCertificate(userId);
KeyStore userKeyStore = userServerCertificateService.getUserKeyStore(userId);
String userPassword =
userServerCertificateService.getUserKeystorePassword(userId);
// Store password in submission for later use
submission.setPassword(userPassword);
return userKeyStore;
} catch (Exception e) {
log.error("Failed to get/create user certificate for user {}", userId, e);
throw ExceptionUtils.createIllegalArgumentException(
"error.userCertificateFailure",
"Failed to get user certificate: " + e.getMessage());
}
case "PEM":
KeyStore pemStore = KeyStore.getInstance("JKS");
pemStore.load(null);
if (submission.getPrivateKey() == null || submission.getCertificate() == null) {
throw ExceptionUtils.createIllegalArgumentException(
"error.optionsNotSpecified",
"{0} options are not specified",
"PEM certificate and key bytes for signer");
}
PrivateKey privateKey =
certSignController.getPrivateKeyFromPEM(
submission.getPrivateKey(), password);
Certificate certificate =
(Certificate)
certSignController.getCertificateFromPEM(
submission.getCertificate());
pemStore.setKeyEntry(
"alias",
privateKey,
password.toCharArray(),
new Certificate[] {certificate});
return pemStore;
case "PKCS12":
case "PFX":
if (submission.getP12Keystore() == null) {
throw ExceptionUtils.createIllegalArgumentException(
"error.optionsNotSpecified",
"{0} options are not specified",
"PKCS12 keystore bytes");
}
KeyStore p12Store = KeyStore.getInstance("PKCS12");
p12Store.load(
new ByteArrayInputStream(submission.getP12Keystore()),
password.toCharArray());
return p12Store;
case "JKS":
if (submission.getJksKeystore() == null) {
throw ExceptionUtils.createIllegalArgumentException(
"error.optionsNotSpecified",
"{0} options are not specified",
"JKS keystore bytes");
}
KeyStore jksStore = KeyStore.getInstance("JKS");
jksStore.load(
new ByteArrayInputStream(submission.getJksKeystore()),
password.toCharArray());
return jksStore;
case "SERVER":
if (serverCertificateServiceInterface == null) {
throw ExceptionUtils.createIllegalArgumentException(
"error.serverCertificateNotAvailable",
"Server certificate service is not available in this edition");
}
if (!serverCertificateServiceInterface.isEnabled()) {
throw ExceptionUtils.createIllegalArgumentException(
"error.serverCertificateDisabled",
"Server certificate feature is disabled");
}
if (!serverCertificateServiceInterface.hasServerCertificate()) {
throw ExceptionUtils.createIllegalArgumentException(
"error.serverCertificateNotFound", "No server certificate configured");
}
return serverCertificateServiceInterface.getServerKeyStore();
default:
throw ExceptionUtils.createIllegalArgumentException(
"error.invalidArgument",
"Invalid argument: {0}",
"certificate type: " + submission.getCertType());
}
}
/**
* Applies wet signatures (visual annotations) to the PDF. This must be done BEFORE applying
* digital certificates.
*
* @param pdfBytes Original PDF bytes
* @param sessionId Session ID
* @return PDF bytes with wet signatures overlaid
* @throws Exception if PDF processing fails
*/
private byte[] applyWetSignatures(byte[] pdfBytes, String sessionId) throws Exception {
// Cast to database service to access wet signature methods
if (!(sessionServiceInterface
instanceof
stirling.software.proprietary.security.service.DatabaseSigningSessionService)) {
return pdfBytes; // Skip if not database service
}
stirling.software.proprietary.security.service.DatabaseSigningSessionService dbService =
(stirling.software.proprietary.security.service.DatabaseSigningSessionService)
sessionServiceInterface;
List<WetSignatureMetadata> wetSignatures = dbService.getAllWetSignatures(sessionId);
if (wetSignatures.isEmpty()) {
return pdfBytes; // No wet signatures to apply
}
// Load PDF document
org.apache.pdfbox.pdmodel.PDDocument document =
pdfDocumentFactory.load(new ByteArrayInputStream(pdfBytes));
try {
for (WetSignatureMetadata wetSig : wetSignatures) {
applyWetSignatureToPage(document, wetSig);
}
// Save modified PDF
ByteArrayOutputStream baos = new ByteArrayOutputStream();
document.save(baos);
return baos.toByteArray();
} finally {
document.close();
}
}
/**
* Applies a single wet signature to the appropriate page of the PDF.
*
* @param document PDF document
* @param wetSig Wet signature metadata
* @throws Exception if image processing or PDF manipulation fails
*/
private void applyWetSignatureToPage(
org.apache.pdfbox.pdmodel.PDDocument document, WetSignatureMetadata wetSig)
throws Exception {
if (wetSig.getPage() >= document.getNumberOfPages()) {
log.warn(
"Wet signature page {} exceeds document pages {}, skipping",
wetSig.getPage(),
document.getNumberOfPages());
return;
}
org.apache.pdfbox.pdmodel.PDPage page = document.getPage(wetSig.getPage());
org.apache.pdfbox.pdmodel.PDPageContentStream contentStream =
new org.apache.pdfbox.pdmodel.PDPageContentStream(
document,
page,
org.apache.pdfbox.pdmodel.PDPageContentStream.AppendMode.APPEND,
true,
true);
try {
// Extract base64 data (remove data:image/png;base64, prefix if present)
String base64Data = wetSig.extractBase64Data();
byte[] imageBytes = java.util.Base64.getDecoder().decode(base64Data);
// Create PDImageXObject from bytes
org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject image =
org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject.createFromByteArray(
document, imageBytes, "signature");
// Convert Y coordinate from UI (top-left) to PDF (bottom-left) coordinate system
float pdfY =
page.getMediaBox().getHeight()
- wetSig.getY().floatValue()
- wetSig.getHeight().floatValue();
// Draw image at specified position
contentStream.drawImage(
image,
wetSig.getX().floatValue(),
pdfY,
wetSig.getWidth().floatValue(),
wetSig.getHeight().floatValue());
} finally {
contentStream.close();
}
}
/**
* Clears wet signature metadata from all participants. Called after successful finalization for
* GDPR compliance.
*
* @param sessionId Session ID
*/
private void clearWetSignatureMetadata(String sessionId) {
if (sessionServiceInterface
instanceof
stirling.software.proprietary.security.service.DatabaseSigningSessionService) {
stirling.software.proprietary.security.service.DatabaseSigningSessionService dbService =
(stirling.software.proprietary.security.service.DatabaseSigningSessionService)
sessionServiceInterface;
dbService.clearWetSignatureMetadata(sessionId);
}
}
/**
* Helper method to get user ID from participant. Returns null if not available (e.g., in-memory
* sessions).
*
* @param participant The signing participant
* @return User ID or null
*/
private Long getUserIdFromParticipant(SigningParticipant participant) {
return participant.getUserId();
}
@Operation(summary = "List sign requests for authenticated user")
@GetMapping(value = "/cert-sign/sign-requests")
public ResponseEntity<?> listSignRequests(Principal principal) {
if (principal == null || !sessionServiceInterface.isDatabaseBacked()) {
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("Authentication required");
}
try {
return ResponseEntity.ok(sessionServiceInterface.listSignRequests(principal.getName()));
} catch (Exception e) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body("Cannot list sign requests: " + e.getMessage());
}
}
@Operation(summary = "Get sign request detail for participant")
@GetMapping(value = "/cert-sign/sign-requests/{sessionId}")
public ResponseEntity<?> getSignRequestDetail(
@PathVariable("sessionId") @NotBlank String sessionId, Principal principal) {
if (principal == null || !sessionServiceInterface.isDatabaseBacked()) {
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("Authentication required");
}
try {
return ResponseEntity.ok(
sessionServiceInterface.getSignRequestDetail(sessionId, principal.getName()));
} catch (Exception e) {
return ResponseEntity.status(HttpStatus.FORBIDDEN)
.body("Access denied or sign request not found: " + e.getMessage());
}
}
@Operation(summary = "Decline a sign request")
@PostMapping(value = "/cert-sign/sign-requests/{sessionId}/decline")
public ResponseEntity<?> declineSignRequest(
@PathVariable("sessionId") @NotBlank String sessionId, Principal principal) {
if (principal == null || !sessionServiceInterface.isDatabaseBacked()) {
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("Authentication required");
}
try {
sessionServiceInterface.declineSignRequest(sessionId, principal.getName());
return ResponseEntity.noContent().build();
} catch (Exception e) {
return ResponseEntity.status(HttpStatus.FORBIDDEN)
.body("Cannot decline sign request: " + e.getMessage());
}
}
@Operation(
summary = "Sign a document with optional wet signature",
description =
"Submits certificate and optional wet signature annotation metadata for a signing session")
@PostMapping(
value = "/cert-sign/sessions/{sessionId}/sign",
consumes = {
MediaType.MULTIPART_FORM_DATA_VALUE,
MediaType.APPLICATION_FORM_URLENCODED_VALUE
})
public ResponseEntity<?> signDocument(
@PathVariable("sessionId") @NotBlank String sessionId,
@ModelAttribute SignDocumentRequest request,
Principal principal) {
if (principal == null || !sessionServiceInterface.isDatabaseBacked()) {
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("Authentication required");
}
try {
sessionServiceInterface.signDocument(sessionId, principal.getName(), request);
return ResponseEntity.noContent().build();
} catch (IllegalArgumentException e) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(e.getMessage());
} catch (Exception e) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body("Cannot sign document: " + e.getMessage());
}
}
}
@@ -25,7 +25,7 @@ import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import stirling.software.SPDF.model.SignatureFile;
import stirling.software.SPDF.service.SignatureService;
import stirling.software.SPDF.service.SharedSignatureService;
import stirling.software.common.configuration.InstallationPathConfig;
import stirling.software.common.configuration.RuntimePathConfig;
import stirling.software.common.service.UserServiceInterface;
@@ -37,13 +37,13 @@ import stirling.software.common.util.GeneralUtils;
@Slf4j
public class GeneralWebController {
private final SignatureService signatureService;
private final SharedSignatureService signatureService;
private final UserServiceInterface userService;
private final ResourceLoader resourceLoader;
private final RuntimePathConfig runtimePathConfig;
public GeneralWebController(
SignatureService signatureService,
SharedSignatureService signatureService,
@Autowired(required = false) UserServiceInterface userService,
ResourceLoader resourceLoader,
RuntimePathConfig runtimePathConfig) {
@@ -1,20 +1,61 @@
package stirling.software.SPDF.controller.web;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import jakarta.servlet.http.HttpServletRequest;
@Controller
public class ReactRoutingController {
@GetMapping(
"/{path:^(?!api|static|robots\\.txt|favicon\\.ico|pipeline|pdfjs|pdfjs-legacy|fonts|images|files|css|js)[^\\.]*$}")
public String forwardRootPaths() {
return "forward:/index.html";
@Value("${server.servlet.context-path:/}")
private String contextPath;
@GetMapping(value = {"/", "/index.html"}, produces = MediaType.TEXT_HTML_VALUE)
public ResponseEntity<String> serveIndexHtml(HttpServletRequest request)
throws IOException {
ClassPathResource resource = new ClassPathResource("static/index.html");
try (InputStream inputStream = resource.getInputStream()) {
String html = new String(inputStream.readAllBytes(), StandardCharsets.UTF_8);
// Replace %BASE_URL% with the actual context path for base href
String baseUrl = contextPath.endsWith("/") ? contextPath : contextPath + "/";
html = html.replace("%BASE_URL%", baseUrl);
// Also rewrite any existing <base> tag (Vite may have baked one in)
html =
html.replaceFirst(
"<base href=\\\"[^\\\"]*\\\"\\s*/?>",
"<base href=\\\"" + baseUrl + "\\\" />");
// Inject context path as a global variable for API calls
String contextPathScript =
"<script>window.STIRLING_PDF_API_BASE_URL = '" + baseUrl + "';</script>";
html = html.replace("</head>", contextPathScript + "</head>");
return ResponseEntity.ok().contentType(MediaType.TEXT_HTML).body(html);
}
}
@GetMapping(
"/{path:^(?!api|static|pipeline|pdfjs|pdfjs-legacy|fonts|images|files|css|js)[^\\.]*}/{subpath:^(?!.*\\.).*$}")
public String forwardNestedPaths() {
return "forward:/index.html";
"/{path:^(?!api|static|robots\\.txt|favicon\\.ico|manifest.*\\.json|pipeline|pdfjs|pdfjs-legacy|fonts|images|files|css|js|assets|locales|modern-logo|classic-logo|Login|og_images|samples)[^\\.]*$}")
public ResponseEntity<String> forwardRootPaths(HttpServletRequest request)
throws IOException {
return serveIndexHtml(request);
}
@GetMapping(
"/{path:^(?!api|static|pipeline|pdfjs|pdfjs-legacy|fonts|images|files|css|js|assets|locales|modern-logo|classic-logo|Login|og_images|samples)[^\\.]*}/{subpath:^(?!.*\\.).*$}")
public ResponseEntity<String> forwardNestedPaths(HttpServletRequest request)
throws IOException {
return serveIndexHtml(request);
}
}
@@ -1,48 +0,0 @@
package stirling.software.SPDF.controller.web;
import java.io.IOException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import stirling.software.SPDF.service.SignatureService;
import stirling.software.common.service.UserServiceInterface;
// @Controller // Disabled - Backend-only mode, no Thymeleaf UI
@RequestMapping("/api/v1/general")
public class SignatureController {
private final SignatureService signatureService;
private final UserServiceInterface userService;
public SignatureController(
SignatureService signatureService,
@Autowired(required = false) UserServiceInterface userService) {
this.signatureService = signatureService;
this.userService = userService;
}
@GetMapping("/sign/{fileName}")
public ResponseEntity<byte[]> getSignature(@PathVariable(name = "fileName") String fileName)
throws IOException {
String username = "NON_SECURITY_USER";
if (userService != null) {
username = userService.getCurrentUsername();
}
// Verify access permission
if (!signatureService.hasAccessToFile(username, fileName)) {
return ResponseEntity.status(HttpStatus.FORBIDDEN).build();
}
byte[] imageBytes = signatureService.getSignatureBytes(username, fileName);
return ResponseEntity.ok()
.contentType( // Adjust based on file type
MediaType.IMAGE_JPEG)
.body(imageBytes);
}
}
@@ -0,0 +1,84 @@
package stirling.software.SPDF.controller.web;
import java.io.IOException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import lombok.extern.slf4j.Slf4j;
import stirling.software.SPDF.service.SharedSignatureService;
import stirling.software.common.service.PersonalSignatureServiceInterface;
import stirling.software.common.service.UserServiceInterface;
/**
* Unified signature image controller that works for both authenticated and unauthenticated users.
* Uses composition pattern: - Core SharedSignatureService (always available): reads shared
* signatures - PersonalSignatureService (proprietary, optional): reads personal signatures For
* authenticated signature management (save/delete), see proprietary SignatureController.
*/
@Slf4j
@RestController
@RequestMapping("/api/v1/general")
public class SignatureImageController {
private final SharedSignatureService sharedSignatureService;
private final PersonalSignatureServiceInterface personalSignatureService;
private final UserServiceInterface userService;
public SignatureImageController(
SharedSignatureService sharedSignatureService,
@Autowired(required = false) PersonalSignatureServiceInterface personalSignatureService,
@Autowired(required = false) UserServiceInterface userService) {
this.sharedSignatureService = sharedSignatureService;
this.personalSignatureService = personalSignatureService;
this.userService = userService;
}
/**
* Get a signature image (works for both authenticated and unauthenticated users). -
* Authenticated with proprietary: tries personal first, then shared - Unauthenticated or
* community: tries shared only
*/
@GetMapping("/signatures/{fileName}")
public ResponseEntity<byte[]> getSignature(@PathVariable(name = "fileName") String fileName) {
try {
byte[] imageBytes = null;
// If proprietary service available and user authenticated, try personal folder first
if (personalSignatureService != null && userService != null) {
try {
String username = userService.getCurrentUsername();
imageBytes =
personalSignatureService.getPersonalSignatureBytes(username, fileName);
} catch (Exception e) {
// Not found in personal folder or not authenticated, will try shared
log.debug("Personal signature not found, trying shared: {}", e.getMessage());
}
}
// If not found in personal (or no personal service), try shared
if (imageBytes == null) {
imageBytes = sharedSignatureService.getSharedSignatureBytes(fileName);
}
// Determine content type from file extension
MediaType contentType = MediaType.IMAGE_PNG; // Default
String lowerFileName = fileName.toLowerCase();
if (lowerFileName.endsWith(".jpg") || lowerFileName.endsWith(".jpeg")) {
contentType = MediaType.IMAGE_JPEG;
}
return ResponseEntity.ok().contentType(contentType).body(imageBytes);
} catch (IOException e) {
log.debug("Signature not found: {}", fileName);
return ResponseEntity.status(HttpStatus.NOT_FOUND).build();
}
}
}
@@ -1,68 +0,0 @@
package stirling.software.SPDF.model.api.security;
import java.util.List;
import org.springframework.web.multipart.MultipartFile;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import lombok.EqualsAndHashCode;
import stirling.software.common.model.api.PDFFile;
@Data
@EqualsAndHashCode(callSuper = true)
public class MultiSignPDFWithCertRequest extends PDFFile {
@Schema(
description = "The list of certificate types for each signer",
allowableValues = {"PEM", "PKCS12", "PFX", "JKS", "SERVER"},
requiredMode = Schema.RequiredMode.REQUIRED)
private List<String> certTypes;
@Schema(
description =
"Private key files for PEM certificates (supports .pem, .der, or .key files)."
+ " Should match the order of certTypes when PEM is selected")
private List<MultipartFile> privateKeyFiles;
@Schema(
description =
"Certificate files for PEM certificates (supports .pem, .der, .crt, or .cer files)."
+ " Should match the order of certTypes when PEM is selected")
private List<MultipartFile> certFiles;
@Schema(
description =
"PKCS12/PFX keystore files. Should match the order of certTypes when PKCS12 or PFX is selected")
private List<MultipartFile> p12Files;
@Schema(
description =
"JKS keystore files. Should match the order of certTypes when JKS is selected")
private List<MultipartFile> jksFiles;
@Schema(description = "Passwords for keystores or private keys", format = "password")
private List<String> passwords;
@Schema(description = "Whether to visually show each signature in the PDF")
private List<Boolean> showSignatures;
@Schema(description = "Reasons for signing, aligned with certTypes")
private List<String> reasons;
@Schema(description = "Locations for signing, aligned with certTypes")
private List<String> locations;
@Schema(description = "Signer names, aligned with certTypes")
private List<String> names;
@Schema(
description =
"Page numbers for visible signatures (1-indexed). Required when showSignature is true for a signer")
private List<Integer> pageNumbers;
@Schema(description = "Whether to show a signature logo for each signer")
private List<Boolean> showLogos;
}
@@ -0,0 +1,18 @@
package stirling.software.SPDF.model.api.signature;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
public class SavedSignatureRequest {
private String id;
private String label;
private String type; // "canvas", "image", "text"
private String scope; // "personal", "shared"
private String dataUrl; // For canvas and image types
private String signerName; // For text type
private String fontFamily; // For text type
private Integer fontSize; // For text type
private String textColor; // For text type
}
@@ -0,0 +1,22 @@
package stirling.software.SPDF.model.api.signature;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class SavedSignatureResponse {
private String id;
private String label;
private String type; // "canvas", "image", "text"
private String scope; // "personal", "shared"
private String dataUrl; // For canvas and image types (or URL to fetch image)
private String signerName; // For text type
private String fontFamily; // For text type
private Integer fontSize; // For text type
private String textColor; // For text type
private Long createdAt;
private Long updatedAt;
}
@@ -0,0 +1,308 @@
package stirling.software.SPDF.service;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import java.util.stream.Stream;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import stirling.software.SPDF.model.SignatureFile;
import stirling.software.SPDF.model.api.signature.SavedSignatureRequest;
import stirling.software.SPDF.model.api.signature.SavedSignatureResponse;
import stirling.software.common.configuration.InstallationPathConfig;
@Service
@Slf4j
public class SharedSignatureService {
private final String SIGNATURE_BASE_PATH;
private final String ALL_USERS_FOLDER = "ALL_USERS";
private final ObjectMapper objectMapper;
public SharedSignatureService() {
SIGNATURE_BASE_PATH = InstallationPathConfig.getSignaturesPath();
this.objectMapper = new ObjectMapper();
}
public boolean hasAccessToFile(String username, String fileName) throws IOException {
validateFileName(fileName);
// Check if file exists in user's personal folder or ALL_USERS folder
Path userPath = Paths.get(SIGNATURE_BASE_PATH, username, fileName);
Path allUsersPath = Paths.get(SIGNATURE_BASE_PATH, ALL_USERS_FOLDER, fileName);
return Files.exists(userPath) || Files.exists(allUsersPath);
}
public List<SignatureFile> getAvailableSignatures(String username) {
List<SignatureFile> signatures = new ArrayList<>();
// Get signatures from user's personal folder
if (StringUtils.hasText(username)) {
Path userFolder = Paths.get(SIGNATURE_BASE_PATH, username);
if (Files.exists(userFolder)) {
try {
signatures.addAll(getSignaturesFromFolder(userFolder, "Personal"));
} catch (IOException e) {
log.error("Error reading user signatures folder", e);
}
}
}
// Get signatures from ALL_USERS folder
Path allUsersFolder = Paths.get(SIGNATURE_BASE_PATH, ALL_USERS_FOLDER);
if (Files.exists(allUsersFolder)) {
try {
signatures.addAll(getSignaturesFromFolder(allUsersFolder, "Shared"));
} catch (IOException e) {
log.error("Error reading shared signatures folder", e);
}
}
return signatures;
}
private List<SignatureFile> getSignaturesFromFolder(Path folder, String category)
throws IOException {
try (Stream<Path> stream = Files.list(folder)) {
return stream.filter(this::isImageFile)
.map(path -> new SignatureFile(path.getFileName().toString(), category))
.toList();
}
}
/**
* Get a signature from the shared (ALL_USERS) folder. This is always available for both
* authenticated and unauthenticated users.
*/
public byte[] getSharedSignatureBytes(String fileName) throws IOException {
validateFileName(fileName);
Path allUsersPath = Paths.get(SIGNATURE_BASE_PATH, ALL_USERS_FOLDER, fileName);
if (!Files.exists(allUsersPath)) {
throw new FileNotFoundException("Shared signature file not found");
}
return Files.readAllBytes(allUsersPath);
}
private boolean isImageFile(Path path) {
String fileName = path.getFileName().toString().toLowerCase();
return fileName.endsWith(".jpg") || fileName.endsWith(".jpeg") || fileName.endsWith(".png");
}
private void validateFileName(String fileName) {
if (fileName.contains("..") || fileName.contains("/") || fileName.contains("\\")) {
throw new IllegalArgumentException("Invalid filename");
}
// Only allow alphanumeric, hyphen, underscore, and dot (for extensions)
if (!fileName.matches("^[a-zA-Z0-9_.-]+$")) {
throw new IllegalArgumentException("Filename contains invalid characters");
}
}
private String validateAndNormalizeExtension(String extension) {
String normalized = extension.toLowerCase().trim();
// Whitelist only safe image extensions
if (normalized.equals("png") || normalized.equals("jpg") || normalized.equals("jpeg")) {
return normalized;
}
throw new IllegalArgumentException("Unsupported image extension: " + extension);
}
private void verifyPathWithinDirectory(Path resolvedPath, Path targetDirectory)
throws IOException {
Path canonicalTarget = targetDirectory.toAbsolutePath().normalize();
Path canonicalResolved = resolvedPath.toAbsolutePath().normalize();
if (!canonicalResolved.startsWith(canonicalTarget)) {
throw new IOException("Resolved path is outside the target directory");
}
}
/** Save a signature as image file */
public SavedSignatureResponse saveSignature(String username, SavedSignatureRequest request)
throws IOException {
validateFileName(request.getId());
// Determine folder based on scope
String scope = request.getScope();
if (scope == null || scope.isEmpty()) {
scope = "personal"; // Default to personal
}
String folderName = "shared".equals(scope) ? ALL_USERS_FOLDER : username;
Path targetFolder = Paths.get(SIGNATURE_BASE_PATH, folderName);
Files.createDirectories(targetFolder);
long timestamp = System.currentTimeMillis();
SavedSignatureResponse response = new SavedSignatureResponse();
response.setId(request.getId());
response.setLabel(request.getLabel());
response.setType(request.getType());
response.setScope(scope);
response.setCreatedAt(timestamp);
response.setUpdatedAt(timestamp);
// Extract and save image data
String dataUrl = request.getDataUrl();
if (dataUrl != null && dataUrl.startsWith("data:image/")) {
// Extract base64 data
String base64Data = dataUrl.substring(dataUrl.indexOf(",") + 1);
byte[] imageBytes = Base64.getDecoder().decode(base64Data);
// Determine and validate file extension from data URL
String mimeType = dataUrl.substring(dataUrl.indexOf(":") + 1, dataUrl.indexOf(";"));
String rawExtension = mimeType.substring(mimeType.indexOf("/") + 1);
String extension = validateAndNormalizeExtension(rawExtension);
// Save image file only
String imageFileName = request.getId() + "." + extension;
Path imagePath = targetFolder.resolve(imageFileName);
// Verify path is within target directory
verifyPathWithinDirectory(imagePath, targetFolder);
Files.write(
imagePath,
imageBytes,
StandardOpenOption.CREATE,
StandardOpenOption.TRUNCATE_EXISTING);
// Store reference to image file
response.setDataUrl("/api/v1/general/sign/" + imageFileName);
}
log.info("Saved signature {} for user {}", request.getId(), username);
return response;
}
/** Get all saved signatures for a user */
public List<SavedSignatureResponse> getSavedSignatures(String username) throws IOException {
List<SavedSignatureResponse> signatures = new ArrayList<>();
// Load personal signatures
Path personalFolder = Paths.get(SIGNATURE_BASE_PATH, username);
if (Files.exists(personalFolder)) {
try (Stream<Path> stream = Files.list(personalFolder)) {
stream.filter(this::isImageFile)
.forEach(
path -> {
try {
String fileName = path.getFileName().toString();
String id =
fileName.substring(0, fileName.lastIndexOf('.'));
SavedSignatureResponse sig = new SavedSignatureResponse();
sig.setId(id);
sig.setLabel(id); // Use ID as label
sig.setType("image"); // Default type
sig.setScope("personal");
sig.setDataUrl("/api/v1/general/sign/" + fileName);
sig.setCreatedAt(
Files.getLastModifiedTime(path).toMillis());
sig.setUpdatedAt(
Files.getLastModifiedTime(path).toMillis());
signatures.add(sig);
} catch (IOException e) {
log.error("Error reading signature file: " + path, e);
}
});
}
}
// Load shared signatures
Path sharedFolder = Paths.get(SIGNATURE_BASE_PATH, ALL_USERS_FOLDER);
if (Files.exists(sharedFolder)) {
try (Stream<Path> stream = Files.list(sharedFolder)) {
stream.filter(this::isImageFile)
.forEach(
path -> {
try {
String fileName = path.getFileName().toString();
String id =
fileName.substring(0, fileName.lastIndexOf('.'));
SavedSignatureResponse sig = new SavedSignatureResponse();
sig.setId(id);
sig.setLabel(id); // Use ID as label
sig.setType("image"); // Default type
sig.setScope("shared");
sig.setDataUrl("/api/v1/general/sign/" + fileName);
sig.setCreatedAt(
Files.getLastModifiedTime(path).toMillis());
sig.setUpdatedAt(
Files.getLastModifiedTime(path).toMillis());
signatures.add(sig);
} catch (IOException e) {
log.error("Error reading signature file: " + path, e);
}
});
}
}
return signatures;
}
/** Delete a saved signature */
public void deleteSignature(String username, String signatureId) throws IOException {
validateFileName(signatureId);
// Try to find and delete image file in personal folder
Path personalFolder = Paths.get(SIGNATURE_BASE_PATH, username);
boolean deleted = false;
if (Files.exists(personalFolder)) {
try (Stream<Path> stream = Files.list(personalFolder)) {
List<Path> matchingFiles =
stream.filter(
path ->
path.getFileName()
.toString()
.startsWith(signatureId + "."))
.toList();
for (Path file : matchingFiles) {
Files.delete(file);
deleted = true;
}
}
}
// Try shared folder if not found in personal
if (!deleted) {
Path sharedFolder = Paths.get(SIGNATURE_BASE_PATH, ALL_USERS_FOLDER);
if (Files.exists(sharedFolder)) {
try (Stream<Path> stream = Files.list(sharedFolder)) {
List<Path> matchingFiles =
stream.filter(
path ->
path.getFileName()
.toString()
.startsWith(signatureId + "."))
.toList();
for (Path file : matchingFiles) {
Files.delete(file);
deleted = true;
}
}
}
}
if (!deleted) {
throw new FileNotFoundException("Signature not found");
}
log.info("Deleted signature {} for user {}", signatureId, username);
}
}
@@ -1,107 +0,0 @@
package stirling.software.SPDF.service;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import stirling.software.SPDF.model.SignatureFile;
import stirling.software.common.configuration.InstallationPathConfig;
@Service
@Slf4j
public class SignatureService {
private final String SIGNATURE_BASE_PATH;
private final String ALL_USERS_FOLDER = "ALL_USERS";
public SignatureService() {
SIGNATURE_BASE_PATH = InstallationPathConfig.getSignaturesPath();
}
public boolean hasAccessToFile(String username, String fileName) throws IOException {
validateFileName(fileName);
// Check if file exists in user's personal folder or ALL_USERS folder
Path userPath = Paths.get(SIGNATURE_BASE_PATH, username, fileName);
Path allUsersPath = Paths.get(SIGNATURE_BASE_PATH, ALL_USERS_FOLDER, fileName);
return Files.exists(userPath) || Files.exists(allUsersPath);
}
public List<SignatureFile> getAvailableSignatures(String username) {
List<SignatureFile> signatures = new ArrayList<>();
// Get signatures from user's personal folder
if (StringUtils.hasText(username)) {
Path userFolder = Paths.get(SIGNATURE_BASE_PATH, username);
if (Files.exists(userFolder)) {
try {
signatures.addAll(getSignaturesFromFolder(userFolder, "Personal"));
} catch (IOException e) {
log.error("Error reading user signatures folder", e);
}
}
}
// Get signatures from ALL_USERS folder
Path allUsersFolder = Paths.get(SIGNATURE_BASE_PATH, ALL_USERS_FOLDER);
if (Files.exists(allUsersFolder)) {
try {
signatures.addAll(getSignaturesFromFolder(allUsersFolder, "Shared"));
} catch (IOException e) {
log.error("Error reading shared signatures folder", e);
}
}
return signatures;
}
private List<SignatureFile> getSignaturesFromFolder(Path folder, String category)
throws IOException {
try (Stream<Path> stream = Files.list(folder)) {
return stream.filter(this::isImageFile)
.map(path -> new SignatureFile(path.getFileName().toString(), category))
.toList();
}
}
public byte[] getSignatureBytes(String username, String fileName) throws IOException {
validateFileName(fileName);
// First try user's personal folder
Path userPath = Paths.get(SIGNATURE_BASE_PATH, username, fileName);
if (Files.exists(userPath)) {
return Files.readAllBytes(userPath);
}
// Then try ALL_USERS folder
Path allUsersPath = Paths.get(SIGNATURE_BASE_PATH, ALL_USERS_FOLDER, fileName);
if (Files.exists(allUsersPath)) {
return Files.readAllBytes(allUsersPath);
}
throw new FileNotFoundException("Signature file not found");
}
private boolean isImageFile(Path path) {
String fileName = path.getFileName().toString().toLowerCase();
return fileName.endsWith(".jpg")
|| fileName.endsWith(".jpeg")
|| fileName.endsWith(".png")
|| fileName.endsWith(".gif");
}
private void validateFileName(String fileName) {
if (fileName.contains("..") || fileName.contains("/") || fileName.contains("\\")) {
throw new IllegalArgumentException("Invalid filename");
}
}
}
@@ -1,214 +0,0 @@
package stirling.software.SPDF.service;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import stirling.software.common.model.api.security.CreateSigningSessionRequest;
import stirling.software.common.model.api.security.NotifySigningParticipantsRequest;
import stirling.software.common.model.api.security.ParticipantCertificateRequest;
import stirling.software.common.model.api.security.ParticipantCertificateSubmission;
import stirling.software.common.model.api.security.ParticipantStatus;
import stirling.software.common.model.api.security.SigningParticipant;
import stirling.software.common.model.api.security.SigningSession;
import stirling.software.common.service.SigningSessionServiceInterface;
import stirling.software.common.util.ExceptionUtils;
@Service
public class SigningSessionService implements SigningSessionServiceInterface {
private final Map<String, SigningSession> sessions = new ConcurrentHashMap<>();
public SigningSession createSession(CreateSigningSessionRequest request) throws IOException {
return createSession(request, null);
}
@Override
public SigningSession createSession(Object requestObj, String username) throws IOException {
// In-memory implementation not supported for user-based signing (requires database)
throw new UnsupportedOperationException(
"User-based signing requires database-backed implementation");
}
public SigningSession getSession(String sessionId) {
SigningSession session = sessions.get(sessionId);
if (session == null) {
throw ExceptionUtils.createIllegalArgumentException(
"error.notFound", "Signing session {0} was not found", sessionId);
}
return session;
}
@Override
public SigningSession notifyParticipants(String sessionId, Object requestObj) {
NotifySigningParticipantsRequest request = (NotifySigningParticipantsRequest) requestObj;
SigningSession session = getSession(sessionId);
List<SigningParticipant> targets = getTargets(session, request.getParticipantEmails());
String message =
StringUtils.defaultIfBlank(
request.getMessage(), "A reminder to review and sign the document.");
for (SigningParticipant participant : targets) {
participant.recordNotification(message);
if (participant.getStatus() == ParticipantStatus.PENDING) {
participant.setStatus(ParticipantStatus.NOTIFIED);
}
}
session.touch();
return session;
}
@Override
public SigningSession attachCertificate(String sessionId, Long userId, Object requestObj)
throws IOException {
// In-memory implementation doesn't support user-based participants
throw new UnsupportedOperationException(
"User-based signing not supported in non-database mode");
}
private void broadcastNotification(SigningSession session, String message) {
for (SigningParticipant participant : session.getParticipants()) {
participant.recordNotification(message);
if (participant.getStatus() == ParticipantStatus.PENDING) {
participant.setStatus(ParticipantStatus.NOTIFIED);
}
}
session.touch();
}
private ParticipantCertificateSubmission toSubmission(ParticipantCertificateRequest request)
throws IOException {
return ParticipantCertificateSubmission.builder()
.certType(request.getCertType())
.password(request.getPassword())
.privateKey(toBytes(request.getPrivateKeyFile()))
.certificate(toBytes(request.getCertFile()))
.p12Keystore(toBytes(request.getP12File()))
.jksKeystore(toBytes(request.getJksFile()))
.showSignature(request.getShowSignature())
.pageNumber(request.getPageNumber())
.name(request.getName())
.reason(request.getReason())
.location(request.getLocation())
.showLogo(request.getShowLogo())
.build();
}
private byte[] toBytes(MultipartFile file) throws IOException {
if (file == null || file.isEmpty()) {
return null;
}
return file.getBytes();
}
private List<SigningParticipant> getTargets(
SigningSession session, List<String> requestedEmails) {
if (requestedEmails == null || requestedEmails.isEmpty()) {
return session.getParticipants();
}
List<SigningParticipant> participants = new ArrayList<>();
for (String email : requestedEmails) {
Optional<SigningParticipant> participant =
session.getParticipants().stream()
.filter(p -> Objects.equals(p.getEmail(), email))
.findFirst();
participant.ifPresent(participants::add);
}
return participants;
}
// Interface methods that are not supported by in-memory implementation
@Override
public List<?> listUserSessions(String username) {
// In-memory implementation doesn't support user filtering
return Collections.emptyList();
}
@Override
public Object getSessionDetail(String sessionId, String username) {
// In-memory implementation doesn't have separate detail view
return getSession(sessionId);
}
@Override
public void deleteSession(String sessionId, String username) {
// In-memory implementation doesn't support deletion
throw new UnsupportedOperationException(
"Session deletion not supported in non-database mode");
}
@Override
public Object addParticipants(String sessionId, Object request, String username) {
// In-memory implementation doesn't support adding participants
throw new UnsupportedOperationException(
"Adding participants not supported in non-database mode");
}
@Override
public void removeParticipant(String sessionId, Long userId, String username) {
// In-memory implementation doesn't support user-based participants
throw new UnsupportedOperationException(
"User-based signing not supported in non-database mode");
}
@Override
public void markSessionFinalized(String sessionId, byte[] signedPdf) {
SigningSession session = getSession(sessionId);
session.setSignedPdf(signedPdf);
}
@Override
public byte[] getSessionPdf(String sessionId, String username) {
// In-memory implementation doesn't support user authentication
throw new UnsupportedOperationException(
"User-based signing not supported in non-database mode");
}
@Override
public byte[] getSignedPdf(String sessionId, String username) {
throw new UnsupportedOperationException(
"getSignedPdf is only available in database-backed mode");
}
@Override
public List<?> listSignRequests(String username) {
// In-memory implementation doesn't support user-based sign requests
return Collections.emptyList();
}
@Override
public Object getSignRequestDetail(String sessionId, String username) {
// In-memory implementation doesn't support user-based signing
throw new UnsupportedOperationException(
"User-based signing not supported in non-database mode");
}
@Override
public void declineSignRequest(String sessionId, String username) {
// In-memory implementation doesn't support user-based signing
throw new UnsupportedOperationException(
"User-based signing not supported in non-database mode");
}
@Override
public void signDocument(String sessionId, String username, Object request) throws IOException {
// In-memory implementation doesn't support user-based signing with wet signatures
throw new UnsupportedOperationException(
"User-based signing not supported in non-database mode");
}
@Override
public boolean isDatabaseBacked() {
return false;
}
}
@@ -37,11 +37,8 @@ spring.datasource.url=jdbc:h2:file:./configs/stirling-pdf-DB-2.3.232;DB_CLOSE_DE
spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.h2.console.enabled=true
spring.h2.console.enabled=false
spring.jpa.hibernate.ddl-auto=update
spring.jpa.properties.hibernate.format_sql=true
logging.level.org.hibernate.SQL=error
logging.level.org.hibernate.type.descriptor.sql.BasicBinder=TRACE
# Defer datasource initialization to ensure that the database is fully set up
# before Hibernate attempts to access it. This is particularly useful when
# using database initialization scripts or tools.
@@ -68,9 +65,3 @@ java.io.tmpdir=${stirling.tempfiles.directory:${java.io.tmpdir}/stirling-pdf}
# V2 features
v2=true
# User personal certificates (per-user signing certificates)
system.userCertificates.enabled=true
system.userCertificates.autoGenerate=true
system.userCertificates.validity=365
system.userCertificates.keySize=2048
@@ -24,8 +24,8 @@
--cc-toggle-on-knob-bg: var(--cc-btn-primary-color);
--cc-toggle-off-knob-bg: var(--cc-btn-primary-color);
--cc-toggle-enabled-icon-color: var(--cc-btn-primary-color);
--cc-toggle-disabled-icon-color: var(--cc-btn-primary-color);
--cc-toggle-enabled-icon-color: var(--cc-btn-primary-color);
--cc-toggle-disabled-icon-color: var(--cc-btn-primary-color);
--cc-toggle-readonly-bg: var(--md-sys-color-surface);
--cc-toggle-readonly-knob-bg: var(--md-sys-color-outline);
@@ -34,10 +34,10 @@
--cc-section-category-border: var(--md-sys-color-outline);
--cc-cookie-category-block-bg: var(--cc-btn-secondary-bg);
--cc-cookie-category-block-border: var(--cc-btn-secondary-bg);
--cc-cookie-category-block-border: var(--cc-btn-secondary-bg);
--cc-cookie-category-block-hover-bg: var(--cc-btn-secondary-bg);
--cc-cookie-category-block-hover-border: var(--cc-btn-secondary-bg);
--cc-cookie-category-expanded-block-bg: var(--cc-btn-secondary-bg);
--cc-cookie-category-expanded-block-hover-bg: var(--cc-toggle-readonly-bg);
@@ -47,7 +47,7 @@
*/
--cc-footer-bg: var(--cc-bg);
--cc-footer-color: var(--cc-primary-color);
--cc-footer-border-color: var(--cc-bg);
--cc-footer-border-color: var(--cc-bg);
}
.cm__body{
max-width: 90% !important;
@@ -81,4 +81,4 @@
/* Lower z-index so cookie banner appears behind onboarding modals */
#cc-main {
z-index: 100 !important;
}
}
@@ -23,7 +23,7 @@ import stirling.software.common.configuration.InstallationPathConfig;
class SignatureServiceTest {
@TempDir Path tempDir;
private SignatureService signatureService;
private SharedSignatureService signatureService;
private Path personalSignatureFolder;
private Path sharedSignatureFolder;
private final String ALL_USERS_FOLDER = "ALL_USERS";
@@ -53,7 +53,7 @@ class SignatureServiceTest {
.thenReturn(tempDir.toString());
// Initialize the service with our temp directory
signatureService = new SignatureService();
signatureService = new SharedSignatureService();
}
}
@@ -165,7 +165,7 @@ class SignatureServiceTest {
}
@Test
void testGetSignatureBytes_PersonalFile() throws IOException {
void testGetSharedSignatureBytes_SharedFile() throws IOException {
// Mock static method for each test
try (MockedStatic<InstallationPathConfig> mockedConfig =
mockStatic(InstallationPathConfig.class)) {
@@ -173,28 +173,8 @@ class SignatureServiceTest {
.when(InstallationPathConfig::getSignaturesPath)
.thenReturn(tempDir.toString());
// Test
byte[] bytes = signatureService.getSignatureBytes(TEST_USER, "personal.png");
// Verify
assertEquals(
"personal signature content",
new String(bytes),
"Should return the correct content for personal file");
}
}
@Test
void testGetSignatureBytes_SharedFile() throws IOException {
// Mock static method for each test
try (MockedStatic<InstallationPathConfig> mockedConfig =
mockStatic(InstallationPathConfig.class)) {
mockedConfig
.when(InstallationPathConfig::getSignaturesPath)
.thenReturn(tempDir.toString());
// Test
byte[] bytes = signatureService.getSignatureBytes(TEST_USER, "shared.jpg");
// Test - core service only reads shared signatures
byte[] bytes = signatureService.getSharedSignatureBytes("shared.jpg");
// Verify
assertEquals(
@@ -205,7 +185,7 @@ class SignatureServiceTest {
}
@Test
void testGetSignatureBytes_FileNotFound() {
void testGetSharedSignatureBytes_FileNotFound() {
// Mock static method for each test
try (MockedStatic<InstallationPathConfig> mockedConfig =
mockStatic(InstallationPathConfig.class)) {
@@ -216,13 +196,13 @@ class SignatureServiceTest {
// Test and verify
assertThrows(
FileNotFoundException.class,
() -> signatureService.getSignatureBytes(TEST_USER, "nonexistent.png"),
() -> signatureService.getSharedSignatureBytes("nonexistent.png"),
"Should throw exception for non-existent files");
}
}
@Test
void testGetSignatureBytes_InvalidFileName() {
void testGetSharedSignatureBytes_InvalidFileName() {
// Mock static method for each test
try (MockedStatic<InstallationPathConfig> mockedConfig =
mockStatic(InstallationPathConfig.class)) {
@@ -233,11 +213,28 @@ class SignatureServiceTest {
// Test and verify
assertThrows(
IllegalArgumentException.class,
() -> signatureService.getSignatureBytes(TEST_USER, "../invalid.png"),
() -> signatureService.getSharedSignatureBytes("../invalid.png"),
"Should throw exception for file names with directory traversal");
}
}
@Test
void testGetSharedSignatureBytes_CannotAccessPersonalFiles() {
// Mock static method for each test
try (MockedStatic<InstallationPathConfig> mockedConfig =
mockStatic(InstallationPathConfig.class)) {
mockedConfig
.when(InstallationPathConfig::getSignaturesPath)
.thenReturn(tempDir.toString());
// Test and verify - core service should NOT be able to read personal files
assertThrows(
FileNotFoundException.class,
() -> signatureService.getSharedSignatureBytes("personal.png"),
"Core service should not have access to personal signatures");
}
}
@Test
void testGetAvailableSignatures_EmptyUsername() throws IOException {
// Mock static method for each test
+1 -1
View File
@@ -57,7 +57,7 @@ dependencies {
implementation 'org.thymeleaf.extras:thymeleaf-extras-springsecurity5:3.1.3.RELEASE'
api 'io.micrometer:micrometer-registry-prometheus'
implementation 'com.unboundid.product.scim2:scim2-sdk-client:4.1.0'
implementation 'com.unboundid.product.scim2:scim2-sdk-client:4.0.0'
api "io.jsonwebtoken:jjwt-api:$jwtVersion"
runtimeOnly "io.jsonwebtoken:jjwt-impl:$jwtVersion"
@@ -0,0 +1,102 @@
package stirling.software.proprietary.controller.api;
import java.io.IOException;
import java.util.List;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import stirling.software.common.annotations.api.UserApi;
import stirling.software.proprietary.model.api.signature.SavedSignatureRequest;
import stirling.software.proprietary.model.api.signature.SavedSignatureResponse;
import stirling.software.proprietary.security.service.UserService;
import stirling.software.proprietary.service.SignatureService;
/**
* Controller for managing user signatures in proprietary/authenticated mode only. Requires user
* authentication and enforces per-user storage limits. All endpoints require authentication
* via @PreAuthorize("isAuthenticated()").
*/
@UserApi
@Slf4j
@RestController
@RequestMapping("/api/v1/proprietary/signatures")
@RequiredArgsConstructor
@PreAuthorize("isAuthenticated()")
public class SignatureController {
private final SignatureService signatureService;
private final UserService userService;
/**
* Save a new signature for the authenticated user. Enforces storage limits and authentication
* requirements.
*/
@PostMapping
public ResponseEntity<SavedSignatureResponse> saveSignature(
@RequestBody SavedSignatureRequest request) {
try {
String username = userService.getCurrentUsername();
// Validate request
if (request.getDataUrl() == null || request.getDataUrl().isEmpty()) {
log.warn("User {} attempted to save signature without dataUrl", username);
return ResponseEntity.badRequest().build();
}
SavedSignatureResponse response = signatureService.saveSignature(username, request);
log.info("User {} saved signature {}", username, request.getId());
return ResponseEntity.ok(response);
} catch (IllegalArgumentException e) {
log.warn("Invalid signature save request: {}", e.getMessage());
return ResponseEntity.badRequest().build();
} catch (IOException e) {
log.error("Failed to save signature", e);
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
}
}
/**
* List all signatures accessible to the authenticated user. Includes both personal and shared
* signatures.
*/
@GetMapping
public ResponseEntity<List<SavedSignatureResponse>> listSignatures() {
try {
String username = userService.getCurrentUsername();
List<SavedSignatureResponse> signatures = signatureService.getSavedSignatures(username);
return ResponseEntity.ok(signatures);
} catch (IOException e) {
log.error("Failed to list signatures for user", e);
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
}
}
/**
* Delete a signature owned by the authenticated user. Users can only delete their own personal
* signatures, not shared ones.
*/
@DeleteMapping("/{signatureId}")
public ResponseEntity<Void> deleteSignature(@PathVariable String signatureId) {
try {
String username = userService.getCurrentUsername();
signatureService.deleteSignature(username, signatureId);
log.info("User {} deleted signature {}", username, signatureId);
return ResponseEntity.noContent().build();
} catch (IOException e) {
log.warn("Failed to delete signature {} for user: {}", signatureId, e.getMessage());
return ResponseEntity.status(HttpStatus.NOT_FOUND).build();
}
}
}
@@ -34,7 +34,19 @@ import stirling.software.proprietary.util.FormUtils;
@RestController
@RequestMapping("/api/v1/form")
@Tag(name = "Forms", description = "PDF form APIs")
@Tag(
name = "Forms",
description =
"""
Work with PDF form fields: read them, fill them, edit them, or remove them.
Treats a PDF as a structured form instead of just flat pages.
Typical uses:
• Inspect which form fields exist in a PDF
• Autofill forms from your own systems (e.g. CRM, ERP)
• Change or delete form fields before sending out a final, non-editable copy
• Unlock read-only form fields when you need to update them
""")
@RequiredArgsConstructor
public class FormFillController {
@@ -1,6 +0,0 @@
package stirling.software.proprietary.model;
public enum CertificateType {
AUTO_GENERATED,
USER_UPLOADED
}
@@ -1,80 +0,0 @@
package stirling.software.proprietary.model;
import java.io.Serializable;
import java.time.LocalDateTime;
import org.hibernate.annotations.CreationTimestamp;
import com.fasterxml.jackson.annotation.JsonIgnore;
import jakarta.persistence.*;
import lombok.*;
@Entity
@Table(name = "participant_certificate_submissions")
@NoArgsConstructor
@Getter
@Setter
@EqualsAndHashCode(onlyExplicitlyIncluded = true)
@ToString(onlyExplicitlyIncluded = true)
public class ParticipantCertificateSubmissionEntity implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
@EqualsAndHashCode.Include
@ToString.Include
private Long id;
@OneToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "participant_id", nullable = false, unique = true)
@JsonIgnore
private SigningParticipantEntity participant;
@Column(name = "cert_type", nullable = false)
private String certType;
@Column(name = "password")
private String password;
@Lob
@Column(name = "private_key", columnDefinition = "bytea")
private byte[] privateKey;
@Lob
@Column(name = "certificate", columnDefinition = "bytea")
private byte[] certificate;
@Lob
@Column(name = "p12_keystore", columnDefinition = "bytea")
private byte[] p12Keystore;
@Lob
@Column(name = "jks_keystore", columnDefinition = "bytea")
private byte[] jksKeystore;
@Column(name = "show_signature")
private Boolean showSignature;
@Column(name = "page_number")
private Integer pageNumber;
@Column(name = "name")
private String name;
@Column(name = "reason")
private String reason;
@Column(name = "location")
private String location;
@Column(name = "show_logo")
private Boolean showLogo;
@CreationTimestamp
@Column(name = "submitted_at", updatable = false)
private LocalDateTime submittedAt;
}
@@ -1,124 +0,0 @@
package stirling.software.proprietary.model;
import java.io.Serializable;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import org.hibernate.annotations.UpdateTimestamp;
import com.fasterxml.jackson.annotation.JsonIgnore;
import jakarta.persistence.*;
import lombok.*;
import stirling.software.common.model.api.security.ParticipantStatus;
import stirling.software.proprietary.security.model.User;
@Entity
@Table(name = "signing_participants")
@NoArgsConstructor
@Getter
@Setter
@EqualsAndHashCode(onlyExplicitlyIncluded = true)
@ToString(onlyExplicitlyIncluded = true)
public class SigningParticipantEntity implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
@EqualsAndHashCode.Include
@ToString.Include
private Long id;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "session_id", nullable = false)
@JsonIgnore
private SigningSessionEntity session;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "user_id", nullable = true)
@JsonIgnore
private User user;
@Column(name = "email")
private String email;
@Column(name = "name")
private String name;
@Enumerated(EnumType.STRING)
@Column(name = "status", nullable = false)
private ParticipantStatus status = ParticipantStatus.PENDING;
@Column(name = "share_token", unique = true, length = 36)
@EqualsAndHashCode.Include
private String shareToken;
// Signature appearance settings (owner-controlled)
@Column(name = "show_signature")
private Boolean showSignature;
@Column(name = "page_number")
private Integer pageNumber;
@Column(name = "reason")
private String reason;
@Column(name = "location")
private String location;
@Column(name = "show_logo")
private Boolean showLogo;
// Wet signature metadata (visual signature placed by participant)
// This data is private to the participant and cleared after finalization
@Column(name = "wet_signature_type", length = 20)
private String wetSignatureType; // "canvas" | "image" | "text"
@Lob
@Column(name = "wet_signature_data", columnDefinition = "TEXT")
private String wetSignatureData; // Base64 image data or text
@Column(name = "wet_signature_page")
private Integer wetSignaturePage;
@Column(name = "wet_signature_x")
private Double wetSignatureX;
@Column(name = "wet_signature_y")
private Double wetSignatureY;
@Column(name = "wet_signature_width")
private Double wetSignatureWidth;
@Column(name = "wet_signature_height")
private Double wetSignatureHeight;
@ElementCollection(fetch = FetchType.LAZY)
@CollectionTable(
name = "participant_notifications",
joinColumns = @JoinColumn(name = "participant_id"))
@Column(name = "notification_message", columnDefinition = "text")
private List<String> notifications = new ArrayList<>();
@UpdateTimestamp
@Column(name = "last_updated")
private LocalDateTime lastUpdated;
@OneToOne(
mappedBy = "participant",
cascade = CascadeType.ALL,
orphanRemoval = true,
fetch = FetchType.LAZY)
@JsonIgnore
private ParticipantCertificateSubmissionEntity certificateSubmission;
public void recordNotification(String message) {
notifications.add(message);
lastUpdated = LocalDateTime.now();
}
}
@@ -1,104 +0,0 @@
package stirling.software.proprietary.model;
import java.io.Serializable;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import org.hibernate.annotations.CreationTimestamp;
import org.hibernate.annotations.UpdateTimestamp;
import com.fasterxml.jackson.annotation.JsonIgnore;
import jakarta.persistence.*;
import lombok.*;
import stirling.software.proprietary.security.model.User;
@Entity
@Table(name = "signing_sessions")
@NoArgsConstructor
@Getter
@Setter
@EqualsAndHashCode(onlyExplicitlyIncluded = true)
@ToString(onlyExplicitlyIncluded = true)
public class SigningSessionEntity implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
@EqualsAndHashCode.Include
@ToString.Include
private Long id;
@Column(name = "session_id", unique = true, nullable = false, length = 36)
@EqualsAndHashCode.Include
@ToString.Include
private String sessionId = UUID.randomUUID().toString();
@Column(name = "document_name", nullable = false)
private String documentName;
@Lob
@Basic(fetch = FetchType.EAGER)
@Column(name = "original_pdf", nullable = false, columnDefinition = "bytea")
@JsonIgnore
private byte[] originalPdf;
@Lob
@Basic(fetch = FetchType.EAGER)
@Column(name = "signed_pdf", columnDefinition = "bytea")
@JsonIgnore
private byte[] signedPdf;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "user_id", nullable = false)
@JsonIgnore
private User user;
@Column(name = "owner_email")
private String ownerEmail;
@Column(name = "message", columnDefinition = "text")
private String message;
@Column(name = "due_date")
private String dueDate;
@Column(name = "is_finalized", nullable = false)
private boolean finalized = false;
@CreationTimestamp
@Column(name = "created_at", updatable = false)
private LocalDateTime createdAt;
@UpdateTimestamp
@Column(name = "updated_at")
private LocalDateTime updatedAt;
@OneToMany(
mappedBy = "session",
cascade = CascadeType.ALL,
orphanRemoval = true,
fetch = FetchType.LAZY)
@JsonIgnore
private List<SigningParticipantEntity> participants = new ArrayList<>();
public void addParticipant(SigningParticipantEntity participant) {
participants.add(participant);
participant.setSession(this);
}
public void removeParticipant(SigningParticipantEntity participant) {
participants.remove(participant);
participant.setSession(null);
}
public void touch() {
this.updatedAt = LocalDateTime.now();
}
}
@@ -1,73 +0,0 @@
package stirling.software.proprietary.model;
import java.io.Serializable;
import java.time.LocalDateTime;
import org.hibernate.annotations.CreationTimestamp;
import org.hibernate.annotations.UpdateTimestamp;
import com.fasterxml.jackson.annotation.JsonIgnore;
import jakarta.persistence.*;
import lombok.*;
import stirling.software.proprietary.security.model.User;
@Entity
@Table(name = "user_server_certificates")
@NoArgsConstructor
@Getter
@Setter
@EqualsAndHashCode(onlyExplicitlyIncluded = true)
@ToString(onlyExplicitlyIncluded = true)
public class UserServerCertificateEntity implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
@EqualsAndHashCode.Include
@ToString.Include
private Long id;
@OneToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "user_id", unique = true, nullable = false)
@JsonIgnore
private User user;
@Lob
@Basic(fetch = FetchType.EAGER)
@Column(name = "keystore_data", nullable = false, columnDefinition = "bytea")
@JsonIgnore
private byte[] keystoreData;
@Column(name = "keystore_password", nullable = false)
@JsonIgnore
private String keystorePassword;
@Enumerated(EnumType.STRING)
@Column(name = "certificate_type", nullable = false, length = 50)
private CertificateType certificateType;
@Column(name = "subject_dn", length = 500)
private String subjectDn;
@Column(name = "issuer_dn", length = 500)
private String issuerDn;
@Column(name = "valid_from")
private LocalDateTime validFrom;
@Column(name = "valid_to")
private LocalDateTime validTo;
@CreationTimestamp
@Column(name = "created_at", updatable = false)
private LocalDateTime createdAt;
@UpdateTimestamp
@Column(name = "updated_at")
private LocalDateTime updatedAt;
}
@@ -0,0 +1,18 @@
package stirling.software.proprietary.model.api.signature;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
public class SavedSignatureRequest {
private String id;
private String label;
private String type; // "canvas", "image", "text"
private String scope; // "personal", "shared"
private String dataUrl; // For canvas and image types
private String signerName; // For text type
private String fontFamily; // For text type
private Integer fontSize; // For text type
private String textColor; // For text type
}
@@ -0,0 +1,22 @@
package stirling.software.proprietary.model.api.signature;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class SavedSignatureResponse {
private String id;
private String label;
private String type; // "canvas", "image", "text"
private String scope; // "personal", "shared"
private String dataUrl; // For canvas and image types (or URL to fetch image)
private String signerName; // For text type
private String fontFamily; // For text type
private Integer fontSize; // For text type
private String textColor; // For text type
private Long createdAt;
private Long updatedAt;
}
@@ -35,15 +35,40 @@ public class MailConfig {
JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
mailSender.setHost(mailProperties.getHost());
mailSender.setPort(mailProperties.getPort());
mailSender.setUsername(mailProperties.getUsername());
mailSender.setPassword(mailProperties.getPassword());
mailSender.setDefaultEncoding("UTF-8");
// Only set username and password if they are provided
String username = mailProperties.getUsername();
String password = mailProperties.getPassword();
boolean hasCredentials =
(username != null && !username.trim().isEmpty())
|| (password != null && !password.trim().isEmpty());
if (username != null && !username.trim().isEmpty()) {
mailSender.setUsername(username);
log.info("SMTP username configured");
} else {
log.info("SMTP username not configured - using anonymous connection");
}
if (password != null && !password.trim().isEmpty()) {
mailSender.setPassword(password);
log.info("SMTP password configured");
} else {
log.info("SMTP password not configured");
}
// Retrieves the JavaMail properties to configure additional SMTP parameters
Properties props = mailSender.getJavaMailProperties();
// Enables SMTP authentication
props.put("mail.smtp.auth", "true");
// Only enable SMTP authentication if credentials are provided
if (hasCredentials) {
props.put("mail.smtp.auth", "true");
log.info("SMTP authentication enabled");
} else {
props.put("mail.smtp.auth", "false");
log.info("SMTP authentication disabled - no credentials provided");
}
// Enables STARTTLS to encrypt the connection if supported by the SMTP server
props.put("mail.smtp.starttls.enable", "true");
@@ -222,11 +222,6 @@ public class SecurityConfiguration {
request -> {
String uri = request.getRequestURI();
// Ignore CSRF for H2 console
if (uri.startsWith("/h2-console")) {
return true;
}
// Ignore CSRF for auth endpoints
if (uri.startsWith("/api/v1/auth/")) {
return true;
@@ -257,9 +252,6 @@ public class SecurityConfiguration {
.csrfTokenRequestHandler(requestHandler));
}
// Allow frames for H2 console
http.headers(headers -> headers.frameOptions(frameOptions -> frameOptions.disable()));
http.sessionManagement(
sessionManagement -> {
if (v2Enabled) {
@@ -316,9 +308,7 @@ public class SecurityConfiguration {
.alwaysRemember(false));
http.authorizeHttpRequests(
authz ->
authz.requestMatchers("/h2-console/**")
.permitAll()
.requestMatchers(
authz.requestMatchers(
req -> {
String uri = req.getRequestURI();
String contextPath = req.getContextPath();
@@ -334,10 +324,14 @@ public class SecurityConfiguration {
.authenticated());
// Handle User/Password Logins
if (securityProperties.isUserPass()) {
// v2: Authentication is handled via API (/api/v1/auth/login), not form login
// We configure form login to handle Spring Security redirects,
// but use /perform_login as the processing URL so /login remains a React route
http.formLogin(
formLogin ->
formLogin
.loginPage("/login")
.loginPage("/login") // Redirect here when unauthenticated
.loginProcessingUrl("/perform_login") // Process form posts here (not /login)
.successHandler(
new CustomAuthenticationSuccessHandler(
loginAttemptService,
@@ -1,22 +1,32 @@
package stirling.software.proprietary.security.controller.api;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.HashMap;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import stirling.software.common.configuration.InstallationPathConfig;
import stirling.software.common.model.ApplicationProperties;
import stirling.software.common.util.GeneralUtils;
import stirling.software.proprietary.security.configuration.ee.KeygenLicenseVerifier;
@@ -242,4 +252,159 @@ public class AdminLicenseController {
.body(Map.of("error", "Failed to retrieve license information"));
}
}
/**
* Upload a license certificate file for offline activation. Accepts .lic or .cert files,
* validates the certificate format, saves to configs directory, and activates the license.
*
* @param file The license certificate file to upload
* @return Response with success status, license type, and file information
*/
@PostMapping(value = "/license-file", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
@Operation(
summary = "Upload license certificate file",
description =
"Upload a license certificate file (.lic, .cert) for offline activation."
+ " Validates the file format and activates the license.")
public ResponseEntity<Map<String, Object>> uploadLicenseFile(
@RequestParam("file") MultipartFile file) {
// Validate file exists
if (file == null || file.isEmpty()) {
return ResponseEntity.badRequest()
.body(Map.of("success", false, "error", "File is empty"));
}
String filename = file.getOriginalFilename();
if (filename == null || filename.trim().isEmpty()) {
return ResponseEntity.badRequest()
.body(Map.of("success", false, "error", "Invalid filename"));
}
// Prevent path traversal and enforce single filename component
if (filename.contains("..") || filename.contains("/") || filename.contains("\\")) {
return ResponseEntity.badRequest()
.body(
Map.of(
"success",
false,
"error",
"Filename must not contain path separators or '..'"));
}
// Validate file extension
if (!isValidLicenseFile(filename)) {
return ResponseEntity.badRequest()
.body(
Map.of(
"success",
false,
"error",
"Invalid file type. Expected .lic or .cert"));
}
// Check file size (max 1MB for license files)
if (file.getSize() > 1_048_576) {
return ResponseEntity.badRequest()
.body(Map.of("success", false, "error", "File too large. Maximum 1MB allowed"));
}
try {
// Validate certificate format by reading content
byte[] fileBytes = file.getBytes();
String content = new String(fileBytes, StandardCharsets.UTF_8);
if (!content.trim().startsWith("-----BEGIN LICENSE FILE-----")) {
return ResponseEntity.badRequest()
.body(
Map.of(
"success",
false,
"error",
"Invalid license certificate format"));
}
// Get config directory and target path
Path configPath = Paths.get(InstallationPathConfig.getConfigPath());
Path targetPath = configPath.resolve(filename).normalize();
// Prevent directory traversal: ensure targetPath is inside configPath
if (!targetPath.startsWith(configPath.normalize().toAbsolutePath())) {
return ResponseEntity.badRequest()
.body(Map.of("success", false, "error", "Invalid file path"));
}
// Backup existing file if present
if (Files.exists(targetPath)) {
Path backupDir = configPath.resolve("backup");
Files.createDirectories(backupDir);
String backupFilename = filename + ".bak." + System.currentTimeMillis();
Path backupPath = backupDir.resolve(backupFilename);
Files.copy(targetPath, backupPath, StandardCopyOption.REPLACE_EXISTING);
log.info("Backed up existing license file to: {}", backupPath);
}
// Write new license file
Files.write(targetPath, fileBytes);
log.info("License file saved to: {}", targetPath);
// assume premium enabled when setting license key
applicationProperties.getPremium().setEnabled(true);
// Update settings with file reference (relative path)
String fileReference = "file:configs/" + filename;
licenseKeyChecker.updateLicenseKey(fileReference);
// Get license status after activation
License license = licenseKeyChecker.getPremiumLicenseEnabledResult();
Map<String, Object> response = new HashMap<>();
response.put("success", true);
response.put("licenseType", license.name());
response.put("filename", filename);
response.put("filePath", "configs/" + filename);
response.put("enabled", applicationProperties.getPremium().isEnabled());
response.put("maxUsers", applicationProperties.getPremium().getMaxUsers());
response.put("message", "License file uploaded and activated");
log.info(
"License file uploaded and activated: filename={}, type={}",
filename,
license.name());
return ResponseEntity.ok(response);
} catch (IOException e) {
log.error("Failed to save license file", e);
return ResponseEntity.internalServerError()
.body(
Map.of(
"success",
false,
"error",
"Failed to save license file: " + e.getMessage()));
} catch (Exception e) {
log.error("Failed to activate license from file", e);
return ResponseEntity.badRequest()
.body(
Map.of(
"success",
false,
"error",
"Failed to activate license: " + e.getMessage()));
}
}
/**
* Validates if the filename has a valid license file extension (.lic or .cert)
*
* @param filename The filename to validate
* @return true if the filename ends with .lic or .cert (case-insensitive)
*/
private boolean isValidLicenseFile(String filename) {
if (filename == null) {
return false;
}
String lower = filename.toLowerCase();
return lower.endsWith(".lic") || lower.endsWith(".cert");
}
}
@@ -1,222 +0,0 @@
package stirling.software.proprietary.security.controller.api;
import java.security.Principal;
import java.util.Optional;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import stirling.software.proprietary.model.UserServerCertificateEntity;
import stirling.software.proprietary.security.database.repository.UserRepository;
import stirling.software.proprietary.security.model.User;
import stirling.software.proprietary.service.UserServerCertificateService;
@RestController
@RequestMapping("/api/v1/user/certificate")
@Slf4j
@Tag(name = "User Certificate", description = "APIs for user personal certificate management")
@RequiredArgsConstructor
public class UserCertificateController {
private final UserServerCertificateService userCertificateService;
private final UserRepository userRepository;
@GetMapping("/info")
@Operation(
summary = "Get user certificate information",
description = "Returns information about the current user's personal certificate")
public ResponseEntity<CertificateInfoResponse> getUserCertificateInfo(Principal principal) {
if (principal == null) {
return ResponseEntity.status(401).build();
}
try {
User user =
userRepository
.findByUsernameIgnoreCase(principal.getName())
.orElseThrow(() -> new IllegalArgumentException("User not found"));
Optional<UserServerCertificateEntity> certOpt =
userCertificateService.getCertificateInfo(user.getId());
if (certOpt.isEmpty()) {
return ResponseEntity.ok(
new CertificateInfoResponse(
false, null, null, null, null, null, null, null));
}
UserServerCertificateEntity cert = certOpt.get();
return ResponseEntity.ok(
new CertificateInfoResponse(
true,
cert.getCertificateType().toString(),
cert.getSubjectDn(),
cert.getIssuerDn(),
cert.getValidFrom() != null ? cert.getValidFrom().toString() : null,
cert.getValidTo() != null ? cert.getValidTo().toString() : null,
cert.getCreatedAt() != null ? cert.getCreatedAt().toString() : null,
cert.getUpdatedAt() != null ? cert.getUpdatedAt().toString() : null));
} catch (Exception e) {
log.error("Failed to get user certificate info", e);
return ResponseEntity.internalServerError().build();
}
}
@PostMapping("/generate")
@Operation(
summary = "Generate new user certificate",
description = "Generate a new self-signed certificate for the current user")
public ResponseEntity<String> generateUserCertificate(Principal principal) {
if (principal == null) {
return ResponseEntity.status(401).build();
}
try {
User user =
userRepository
.findByUsernameIgnoreCase(principal.getName())
.orElseThrow(() -> new IllegalArgumentException("User not found"));
// Delete existing if any
userCertificateService.deleteUserCertificate(user.getId());
// Generate new
userCertificateService.generateUserCertificate(user);
return ResponseEntity.ok("User certificate generated successfully");
} catch (Exception e) {
log.error("Failed to generate user certificate", e);
return ResponseEntity.internalServerError()
.body("Failed to generate certificate: " + e.getMessage());
}
}
@PostMapping("/upload")
@Operation(
summary = "Upload user certificate",
description =
"Upload a custom PKCS12 certificate file to be used as the user's personal certificate")
public ResponseEntity<String> uploadUserCertificate(
Principal principal,
@Parameter(description = "PKCS12 certificate file", required = true)
@RequestParam("file")
MultipartFile file,
@Parameter(description = "Certificate password", required = true)
@RequestParam("password")
String password) {
if (principal == null) {
return ResponseEntity.status(401).build();
}
if (file.isEmpty()) {
return ResponseEntity.badRequest().body("Certificate file cannot be empty");
}
if (!file.getOriginalFilename().toLowerCase().endsWith(".p12")
&& !file.getOriginalFilename().toLowerCase().endsWith(".pfx")) {
return ResponseEntity.badRequest()
.body("Only PKCS12 (.p12 or .pfx) files are supported");
}
try {
User user =
userRepository
.findByUsernameIgnoreCase(principal.getName())
.orElseThrow(() -> new IllegalArgumentException("User not found"));
userCertificateService.uploadUserCertificate(user, file.getInputStream(), password);
return ResponseEntity.ok("User certificate uploaded successfully");
} catch (IllegalArgumentException e) {
log.warn("Invalid certificate upload: {}", e.getMessage());
return ResponseEntity.badRequest().body("Invalid certificate or password");
} catch (Exception e) {
log.error("Failed to upload user certificate", e);
return ResponseEntity.internalServerError().body("Failed to upload certificate");
}
}
@DeleteMapping
@Operation(
summary = "Delete user certificate",
description = "Delete the current user's personal certificate")
public ResponseEntity<String> deleteUserCertificate(Principal principal) {
if (principal == null) {
return ResponseEntity.status(401).build();
}
try {
User user =
userRepository
.findByUsernameIgnoreCase(principal.getName())
.orElseThrow(() -> new IllegalArgumentException("User not found"));
userCertificateService.deleteUserCertificate(user.getId());
return ResponseEntity.ok("User certificate deleted successfully");
} catch (Exception e) {
log.error("Failed to delete user certificate", e);
return ResponseEntity.internalServerError().body("Failed to delete certificate");
}
}
@GetMapping("/download")
@Operation(
summary = "Download user certificate",
description =
"Download the user's public certificate in DER format for validation purposes")
public ResponseEntity<byte[]> downloadUserCertificate(Principal principal) {
if (principal == null) {
return ResponseEntity.status(401).build();
}
try {
User user =
userRepository
.findByUsernameIgnoreCase(principal.getName())
.orElseThrow(() -> new IllegalArgumentException("User not found"));
if (!userCertificateService.hasUserCertificate(user.getId())) {
return ResponseEntity.notFound().build();
}
// Get the KeyStore and extract the public certificate
java.security.KeyStore keyStore = userCertificateService.getUserKeyStore(user.getId());
java.security.cert.X509Certificate cert =
(java.security.cert.X509Certificate)
keyStore.getCertificate(
keyStore.aliases().nextElement()); // Get first alias
byte[] certBytes = cert.getEncoded();
return ResponseEntity.ok()
.header(
HttpHeaders.CONTENT_DISPOSITION,
"attachment; filename=\"user-cert.cer\"")
.contentType(MediaType.valueOf("application/pkix-cert"))
.body(certBytes);
} catch (Exception e) {
log.error("Failed to download user certificate", e);
return ResponseEntity.internalServerError().build();
}
}
// DTO for certificate info response
public record CertificateInfoResponse(
boolean exists,
String type,
String subject,
String issuer,
String validFrom,
String validTo,
String createdAt,
String updatedAt) {}
}
@@ -27,7 +27,6 @@ import lombok.extern.slf4j.Slf4j;
import stirling.software.common.annotations.api.UserApi;
import stirling.software.common.model.ApplicationProperties;
import stirling.software.common.model.api.security.UserSummaryDTO;
import stirling.software.common.model.enumeration.Role;
import stirling.software.common.model.exception.UnsupportedProviderException;
import stirling.software.proprietary.audit.AuditEventType;
@@ -408,7 +407,8 @@ public class UserController {
public ResponseEntity<?> inviteUsers(
@RequestParam(name = "emails", required = true) String emails,
@RequestParam(name = "role", defaultValue = "ROLE_USER") String role,
@RequestParam(name = "teamId", required = false) Long teamId)
@RequestParam(name = "teamId", required = false) Long teamId,
HttpServletRequest request)
throws SQLException, UnsupportedProviderException {
// Check if email invites are enabled
@@ -478,6 +478,9 @@ public class UserController {
}
}
// Build login URL
String loginUrl = buildLoginUrl(request);
int successCount = 0;
int failureCount = 0;
StringBuilder errors = new StringBuilder();
@@ -489,7 +492,7 @@ public class UserController {
continue;
}
InviteResult result = processEmailInvite(email, effectiveTeamId, role);
InviteResult result = processEmailInvite(email, effectiveTeamId, role, loginUrl);
if (result.isSuccess()) {
successCount++;
} else {
@@ -688,15 +691,45 @@ public class UserController {
return ResponseEntity.ok(apiKey);
}
/**
* Helper method to build the login URL from the application configuration or request.
*
* @param request The HTTP request
* @return The login URL
*/
private String buildLoginUrl(HttpServletRequest request) {
String baseUrl;
String configuredFrontendUrl = applicationProperties.getSystem().getFrontendUrl();
if (configuredFrontendUrl != null && !configuredFrontendUrl.trim().isEmpty()) {
// Use configured frontend URL (remove trailing slash if present)
baseUrl =
configuredFrontendUrl.endsWith("/")
? configuredFrontendUrl.substring(0, configuredFrontendUrl.length() - 1)
: configuredFrontendUrl;
} else {
// Fall back to backend URL from request
baseUrl =
request.getScheme()
+ "://"
+ request.getServerName()
+ (request.getServerPort() != 80 && request.getServerPort() != 443
? ":" + request.getServerPort()
: "");
}
return baseUrl + "/login";
}
/**
* Helper method to process a single email invitation.
*
* @param email The email address to invite
* @param teamId The team ID to assign the user to
* @param role The role to assign to the user
* @param loginUrl The URL to the login page
* @return InviteResult containing success status and optional error message
*/
private InviteResult processEmailInvite(String email, Long teamId, String role) {
private InviteResult processEmailInvite(
String email, Long teamId, String role, String loginUrl) {
try {
// Validate email format (basic check)
if (!email.contains("@") || !email.contains(".")) {
@@ -716,7 +749,7 @@ public class UserController {
// Send invite email
try {
emailService.get().sendInviteEmail(email, email, temporaryPassword);
emailService.get().sendInviteEmail(email, email, temporaryPassword, loginUrl);
log.info("Sent invite email to: {}", email);
return InviteResult.success();
} catch (Exception emailEx) {
@@ -783,34 +816,4 @@ public class UserController {
.body("Failed to complete initial setup");
}
}
/**
* List all enabled users for participant selection in signing sessions
*
* @param principal The authenticated user
* @return List of user summaries
*/
@GetMapping("/users")
public ResponseEntity<List<UserSummaryDTO>> listUsers(Principal principal) {
if (principal == null) {
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
}
List<UserSummaryDTO> users =
userRepository.findAll().stream()
.filter(User::isEnabled)
.map(this::toUserSummaryDTO)
.collect(java.util.stream.Collectors.toList());
return ResponseEntity.ok(users);
}
private UserSummaryDTO toUserSummaryDTO(User user) {
return new UserSummaryDTO(
user.getId(),
user.getUsername(),
user.getUsername(), // Use username as displayName
user.getTeam() != null ? user.getTeam().getName() : null,
user.isEnabled());
}
}
@@ -56,6 +56,19 @@ public interface UserRepository extends JpaRepository<User, Long> {
+ "OR LOWER(u.authenticationType) IN ('sso', 'oauth2', 'saml2')")
List<User> findAllSsoUsers();
/**
* Finds SSO users who have never created a session (pending activation) and are not yet
* grandfathered.
*/
@Query(
"SELECT u FROM User u "
+ "LEFT JOIN SessionEntity s ON u.username = s.principalName "
+ "WHERE (u.ssoProvider IS NOT NULL "
+ "OR LOWER(u.authenticationType) IN ('sso', 'oauth2', 'saml2')) "
+ "AND (u.oauthGrandfathered IS NULL OR u.oauthGrandfathered = false) "
+ "AND s.sessionId IS NULL")
List<User> findPendingSsoUsersWithoutSession();
/**
* Counts all SSO users - those with sso_provider set OR authenticationType is sso/oauth2/saml2.
*/
@@ -72,11 +72,6 @@ public class JwtAuthenticationFilter extends OncePerRequestFilter {
filterChain.doFilter(request, response);
return;
}
// Skip H2 console
if (request.getRequestURI().startsWith("/h2-console")) {
filterChain.doFilter(request, response);
return;
}
if (!apiKeyExists(request, response)) {
String jwtToken = jwtService.extractToken(request);
@@ -110,22 +105,18 @@ public class JwtAuthenticationFilter extends OncePerRequestFilter {
}
try {
log.debug("Validating JWT token");
jwtService.validateToken(jwtToken);
log.debug("JWT token validated successfully");
} catch (AuthenticationFailureException e) {
log.warn("JWT validation failed: {}", e.getMessage());
log.debug("JWT validation failed: {}", e.getMessage());
handleAuthenticationFailure(request, response, e);
return;
}
Map<String, Object> claims = jwtService.extractClaims(jwtToken);
String tokenUsername = claims.get("sub").toString();
log.debug("JWT token username: {}", tokenUsername);
try {
authenticate(request, claims);
log.debug("Authentication successful for user: {}", tokenUsername);
} catch (SQLException | UnsupportedProviderException e) {
log.error("Error processing user authentication for user: {}", tokenUsername, e);
handleAuthenticationFailure(
@@ -113,12 +113,6 @@ public class UserAuthenticationFilter extends OncePerRequestFilter {
if (authentication == null || !authentication.isAuthenticated()) {
String contextPath = request.getContextPath();
// Allow H2 console to pass through without authentication
if (requestURI.startsWith("/h2-console")) {
filterChain.doFilter(request, response);
return;
}
// Allow public auth endpoints to pass through without authentication
if (isPublicAuthEndpoint(requestURI, contextPath)) {
filterChain.doFilter(request, response);
@@ -305,7 +299,8 @@ public class UserAuthenticationFilter extends OncePerRequestFilter {
contextPath + "/api/v1/auth/refresh",
contextPath + "/api/v1/auth/me",
contextPath + "/api/v1/invite/validate",
contextPath + "/api/v1/invite/accept"
contextPath + "/api/v1/invite/accept",
contextPath + "/api/v1/ui-data/footer-info"
};
for (String pattern : publicApiPatterns) {
@@ -1,26 +0,0 @@
package stirling.software.proprietary.security.repository;
import java.util.List;
import java.util.Optional;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import stirling.software.proprietary.model.SigningParticipantEntity;
@Repository
public interface SigningParticipantRepository
extends JpaRepository<SigningParticipantEntity, Long> {
Optional<SigningParticipantEntity> findByShareToken(String shareToken);
@Query(
"SELECT p FROM SigningParticipantEntity p WHERE p.session.sessionId = :sessionId AND p.email = :email")
Optional<SigningParticipantEntity> findBySessionIdAndEmail(
@Param("sessionId") String sessionId, @Param("email") String email);
@Query("SELECT p FROM SigningParticipantEntity p WHERE p.session.sessionId = :sessionId")
List<SigningParticipantEntity> findAllBySessionId(@Param("sessionId") String sessionId);
}
@@ -1,43 +0,0 @@
package stirling.software.proprietary.security.repository;
import java.util.List;
import java.util.Optional;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import stirling.software.proprietary.model.SigningSessionEntity;
import stirling.software.proprietary.security.model.User;
@Repository
public interface SigningSessionRepository extends JpaRepository<SigningSessionEntity, Long> {
Optional<SigningSessionEntity> findBySessionId(String sessionId);
@Query(
"SELECT s FROM SigningSessionEntity s WHERE s.user.id = :userId ORDER BY s.createdAt DESC")
List<SigningSessionEntity> findAllByUserIdOrderByCreatedAtDesc(@Param("userId") Long userId);
@Query(
"SELECT s FROM SigningSessionEntity s LEFT JOIN FETCH s.participants WHERE s.sessionId = :sessionId")
Optional<SigningSessionEntity> findBySessionIdWithParticipants(
@Param("sessionId") String sessionId);
@Query(
"SELECT DISTINCT s FROM SigningSessionEntity s "
+ "LEFT JOIN FETCH s.participants p "
+ "LEFT JOIN FETCH p.certificateSubmission "
+ "WHERE s.sessionId = :sessionId")
Optional<SigningSessionEntity> findBySessionIdWithParticipantsAndCertificates(
@Param("sessionId") String sessionId);
@Query(
"SELECT s FROM SigningSessionEntity s WHERE s.user.id = :userId AND s.finalized = false ORDER BY s.createdAt DESC")
List<SigningSessionEntity> findActiveSessionsByUserId(@Param("userId") Long userId);
boolean existsBySessionId(String sessionId);
long countByUserAndFinalizedFalse(User user);
}
@@ -1,23 +0,0 @@
package stirling.software.proprietary.security.repository;
import java.util.Optional;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import stirling.software.proprietary.model.UserServerCertificateEntity;
@Repository
public interface UserServerCertificateRepository
extends JpaRepository<UserServerCertificateEntity, Long> {
@Query("SELECT c FROM UserServerCertificateEntity c WHERE c.user.id = :userId")
Optional<UserServerCertificateEntity> findByUserId(@Param("userId") Long userId);
@Query("SELECT c FROM UserServerCertificateEntity c WHERE c.user.username = :username")
Optional<UserServerCertificateEntity> findByUsername(@Param("username") String username);
boolean existsByUserId(Long userId);
}
@@ -1,845 +0,0 @@
package stirling.software.proprietary.security.service;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import stirling.software.common.model.api.security.*;
import stirling.software.common.service.SigningSessionServiceInterface;
import stirling.software.common.util.ExceptionUtils;
import stirling.software.proprietary.model.ParticipantCertificateSubmissionEntity;
import stirling.software.proprietary.model.SigningParticipantEntity;
import stirling.software.proprietary.model.SigningSessionEntity;
import stirling.software.proprietary.security.database.repository.UserRepository;
import stirling.software.proprietary.security.model.User;
import stirling.software.proprietary.security.repository.SigningParticipantRepository;
import stirling.software.proprietary.security.repository.SigningSessionRepository;
@Service
@Slf4j
@RequiredArgsConstructor
public class DatabaseSigningSessionService implements SigningSessionServiceInterface {
private final SigningSessionRepository sessionRepository;
private final SigningParticipantRepository participantRepository;
private final UserService userService;
private final UserRepository userRepository;
@Override
@Transactional
public SigningSessionDetailDTO createSession(Object requestObj, String username)
throws IOException {
CreateSigningSessionRequest request = (CreateSigningSessionRequest) requestObj;
if (request.getParticipantUserIds() == null || request.getParticipantUserIds().isEmpty()) {
throw ExceptionUtils.createIllegalArgumentException(
"error.optionsNotSpecified",
"{0} options are not specified",
"participant user IDs");
}
User owner =
userService
.findByUsernameIgnoreCase(username)
.orElseThrow(
() ->
ExceptionUtils.createIllegalArgumentException(
"error.notFound", "User {0} not found", username));
byte[] pdfBytes = request.getFileInput().getBytes();
log.info(
"Creating session with PDF: {} bytes from file {}",
pdfBytes != null ? pdfBytes.length : 0,
request.getFileInput().getOriginalFilename());
if (pdfBytes == null || pdfBytes.length == 0) {
throw ExceptionUtils.createIllegalArgumentException(
"error.invalidArgument", "Uploaded PDF is null or empty");
}
SigningSessionEntity session = new SigningSessionEntity();
session.setUser(owner);
session.setDocumentName(request.getFileInput().getOriginalFilename());
session.setOwnerEmail(request.getOwnerEmail());
session.setMessage(request.getMessage());
session.setDueDate(request.getDueDate());
session.setOriginalPdf(pdfBytes);
// Add participants by user ID
for (Long userId : request.getParticipantUserIds()) {
User participantUser =
userRepository
.findById(userId)
.orElseThrow(
() ->
ExceptionUtils.createIllegalArgumentException(
"error.notFound",
"User ID {0} not found",
userId));
SigningParticipantEntity participant = new SigningParticipantEntity();
participant.setUser(participantUser);
participant.setEmail(participantUser.getUsername()); // Keep for audit trail
participant.setName(participantUser.getUsername());
// Apply owner's signature appearance settings
participant.setShowSignature(request.getShowSignature());
participant.setPageNumber(request.getPageNumber());
participant.setReason(request.getReason());
participant.setLocation(request.getLocation());
participant.setShowLogo(request.getShowLogo());
session.addParticipant(participant);
}
if (Boolean.TRUE.equals(request.getNotifyOnCreate())) {
for (SigningParticipantEntity participant : session.getParticipants()) {
participant.recordNotification(
request.getMessage() != null
? request.getMessage()
: "You have been invited to sign a document.");
if (participant.getStatus() == ParticipantStatus.PENDING) {
participant.setStatus(ParticipantStatus.NOTIFIED);
}
}
}
session = sessionRepository.save(session);
return toDetailDTO(session);
}
@Override
@Transactional(readOnly = true)
public List<SigningSessionSummaryDTO> listUserSessions(String username) {
User user =
userService
.findByUsernameIgnoreCase(username)
.orElseThrow(
() ->
ExceptionUtils.createIllegalArgumentException(
"error.notFound", "User {0} not found", username));
List<SigningSessionEntity> sessions =
sessionRepository.findAllByUserIdOrderByCreatedAtDesc(user.getId());
return sessions.stream().map(this::toSummaryDTO).collect(Collectors.toList());
}
@Override
@Transactional(readOnly = true)
public SigningSessionDetailDTO getSessionDetail(String sessionId, String username) {
SigningSessionEntity session = getSessionEntityByIdWithOwnershipCheck(sessionId, username);
return toDetailDTO(session);
}
@Transactional(readOnly = true)
public SigningSession getSession(String sessionId) {
// Use query with participants and certificates fetch for finalization
SigningSessionEntity entity =
sessionRepository
.findBySessionIdWithParticipantsAndCertificates(sessionId)
.orElseThrow(
() ->
ExceptionUtils.createIllegalArgumentException(
"error.notFound",
"Signing session {0} was not found",
sessionId));
// Force LOB loading within transaction
byte[] originalPdf = entity.getOriginalPdf();
byte[] signedPdf = entity.getSignedPdf();
log.debug(
"Loading session {} for signing: originalPdf={} bytes, signedPdf={} bytes, participants={}",
sessionId,
originalPdf != null ? originalPdf.length : 0,
signedPdf != null ? signedPdf.length : 0,
entity.getParticipants().size());
if (originalPdf == null || originalPdf.length == 0) {
log.error("Original PDF is null or empty for session {}", sessionId);
throw ExceptionUtils.createIllegalArgumentException(
"error.notFound", "Original PDF not found for session {0}", sessionId);
}
return toSigningSession(entity);
}
public SigningSessionEntity getSessionEntityById(String sessionId) {
return sessionRepository
.findBySessionIdWithParticipants(sessionId)
.orElseThrow(
() ->
ExceptionUtils.createIllegalArgumentException(
"error.notFound",
"Signing session {0} was not found",
sessionId));
}
private SigningSessionEntity getSessionEntityByIdWithOwnershipCheck(
String sessionId, String username) {
SigningSessionEntity session = getSessionEntityById(sessionId);
validateSessionOwnership(session, username);
return session;
}
@Override
@Transactional
public void deleteSession(String sessionId, String username) {
SigningSessionEntity session = getSessionEntityByIdWithOwnershipCheck(sessionId, username);
if (session.isFinalized()) {
throw ExceptionUtils.createIllegalArgumentException(
"error.invalidArgument", "Cannot delete finalized session", sessionId);
}
sessionRepository.delete(session);
}
@Override
@Transactional
public SigningSessionDetailDTO addParticipants(
String sessionId, Object requestObj, String username) {
AddParticipantsRequest request = (AddParticipantsRequest) requestObj;
if (request.getParticipantUserIds() == null || request.getParticipantUserIds().isEmpty()) {
throw ExceptionUtils.createIllegalArgumentException(
"error.optionsNotSpecified",
"{0} options are not specified",
"participant user IDs");
}
SigningSessionEntity session = getSessionEntityByIdWithOwnershipCheck(sessionId, username);
// Add participants by user ID
for (Long userId : request.getParticipantUserIds()) {
User participantUser =
userRepository
.findById(userId)
.orElseThrow(
() ->
ExceptionUtils.createIllegalArgumentException(
"error.notFound",
"User ID {0} not found",
userId));
SigningParticipantEntity participant = new SigningParticipantEntity();
participant.setUser(participantUser);
participant.setEmail(participantUser.getUsername()); // Keep for audit trail
participant.setName(participantUser.getUsername());
// Copy signature settings from existing participants (or use defaults)
SigningParticipantEntity firstParticipant =
session.getParticipants().isEmpty() ? null : session.getParticipants().get(0);
if (firstParticipant != null) {
participant.setShowSignature(firstParticipant.getShowSignature());
participant.setPageNumber(firstParticipant.getPageNumber());
participant.setReason(firstParticipant.getReason());
participant.setLocation(firstParticipant.getLocation());
participant.setShowLogo(firstParticipant.getShowLogo());
}
session.addParticipant(participant);
}
session = sessionRepository.save(session);
return toDetailDTO(session);
}
@Override
@Transactional
public void removeParticipant(String sessionId, Long userId, String username) {
SigningSessionEntity session = getSessionEntityByIdWithOwnershipCheck(sessionId, username);
SigningParticipantEntity participant =
session.getParticipants().stream()
.filter(p -> p.getUser().getId().equals(userId))
.findFirst()
.orElseThrow(
() ->
ExceptionUtils.createIllegalArgumentException(
"error.notFound",
"Participant with user ID {0} not found",
userId));
if (participant.getStatus() == ParticipantStatus.SIGNED) {
throw ExceptionUtils.createIllegalArgumentException(
"error.invalidArgument",
"Cannot remove participant who has already signed",
userId);
}
session.removeParticipant(participant);
sessionRepository.save(session);
}
@Override
@Transactional
public SigningSession notifyParticipants(String sessionId, Object requestObj) {
NotifySigningParticipantsRequest request = (NotifySigningParticipantsRequest) requestObj;
SigningSessionEntity session = getSessionEntityById(sessionId);
List<SigningParticipantEntity> targets =
getTargetParticipants(session, request.getParticipantEmails());
String message =
StringUtils.defaultIfBlank(
request.getMessage(), "A reminder to review and sign the document.");
for (SigningParticipantEntity participant : targets) {
participant.recordNotification(message);
if (participant.getStatus() == ParticipantStatus.PENDING) {
participant.setStatus(ParticipantStatus.NOTIFIED);
}
}
session.touch();
session = sessionRepository.save(session);
return toSigningSession(session);
}
@Override
@Transactional
public SigningSession attachCertificate(String sessionId, Long userId, Object requestObj)
throws IOException {
ParticipantCertificateRequest request = (ParticipantCertificateRequest) requestObj;
SigningSessionEntity session = getSessionEntityById(sessionId);
SigningParticipantEntity participant =
session.getParticipants().stream()
.filter(p -> p.getUser().getId().equals(userId))
.findFirst()
.orElseThrow(
() ->
ExceptionUtils.createIllegalArgumentException(
"error.notFound",
"Participant with user ID {0} does not exist",
userId));
ParticipantCertificateSubmissionEntity submissionEntity =
toSubmissionEntity(request, participant);
participant.setCertificateSubmission(submissionEntity);
participant.setStatus(ParticipantStatus.SIGNED);
session.touch();
session = sessionRepository.save(session);
return toSigningSession(session);
}
@Override
@Transactional
public void markSessionFinalized(String sessionId, byte[] signedPdf) {
if (signedPdf == null || signedPdf.length == 0) {
log.error("Attempting to save null or empty signed PDF for session {}", sessionId);
throw ExceptionUtils.createIllegalArgumentException(
"error.invalidArgument", "Signed PDF cannot be null or empty", sessionId);
}
SigningSessionEntity session =
sessionRepository
.findBySessionId(sessionId)
.orElseThrow(
() ->
ExceptionUtils.createIllegalArgumentException(
"error.notFound",
"Signing session {0} was not found",
sessionId));
log.info(
"Saving signed PDF for session {}: {} bytes",
sessionId,
signedPdf != null ? signedPdf.length : 0);
session.setSignedPdf(signedPdf);
session.setFinalized(true);
sessionRepository.saveAndFlush(session);
log.info("Signed PDF saved successfully for session {}", sessionId);
}
@Override
@Transactional(readOnly = true)
public byte[] getSessionPdf(String sessionId, String username) {
SigningSessionEntity session = getSessionEntityById(sessionId);
// Validate user is a participant in this session
boolean isParticipant =
session.getParticipants().stream()
.anyMatch(p -> p.getUser().getUsername().equalsIgnoreCase(username));
if (!isParticipant) {
throw ExceptionUtils.createIllegalArgumentException(
"error.unauthorized",
"User {0} is not a participant in session {1}",
username,
sessionId);
}
return session.getOriginalPdf();
}
@Override
@Transactional(readOnly = true)
public byte[] getSignedPdf(String sessionId, String username) {
// Use simple query to fetch session without joins for better LOB loading
SigningSessionEntity session =
sessionRepository
.findBySessionId(sessionId)
.orElseThrow(
() ->
ExceptionUtils.createIllegalArgumentException(
"error.notFound",
"Signing session {0} was not found",
sessionId));
validateSessionOwnership(session, username);
if (!session.isFinalized()) {
throw ExceptionUtils.createIllegalArgumentException(
"error.invalidState", "Session is not finalized", sessionId);
}
byte[] signedPdf = session.getSignedPdf();
if (signedPdf == null || signedPdf.length == 0) {
log.error("Signed PDF is null or empty for session {}", sessionId);
throw ExceptionUtils.createIllegalArgumentException(
"error.notFound", "Signed PDF not found for session {0}", sessionId);
}
return signedPdf;
}
@Override
@Transactional(readOnly = true)
public List<SignRequestSummaryDTO> listSignRequests(String username) {
User user =
userService
.findByUsernameIgnoreCase(username)
.orElseThrow(
() ->
ExceptionUtils.createIllegalArgumentException(
"error.notFound", "User {0} not found", username));
// Find all sessions where user is a participant
List<SigningSessionEntity> sessions =
sessionRepository.findAll().stream()
.filter(
session ->
session.getParticipants().stream()
.anyMatch(
p ->
p.getUser()
.getId()
.equals(user.getId())))
.sorted((a, b) -> b.getCreatedAt().compareTo(a.getCreatedAt()))
.collect(Collectors.toList());
return sessions.stream()
.map(session -> toSignRequestSummaryDTO(session, user.getId()))
.collect(Collectors.toList());
}
@Override
@Transactional(readOnly = true)
public SignRequestDetailDTO getSignRequestDetail(String sessionId, String username) {
SigningSessionEntity session = getSessionEntityById(sessionId);
User user =
userService
.findByUsernameIgnoreCase(username)
.orElseThrow(
() ->
ExceptionUtils.createIllegalArgumentException(
"error.notFound", "User {0} not found", username));
// Find participant matching user
SigningParticipantEntity participant =
session.getParticipants().stream()
.filter(p -> p.getUser().getId().equals(user.getId()))
.findFirst()
.orElseThrow(
() ->
ExceptionUtils.createIllegalArgumentException(
"error.unauthorized",
"User {0} is not a participant in session {1}",
username,
sessionId));
String ownerUsername =
session.getUser() != null
? session.getUser().getUsername()
: session.getOwnerEmail();
return new SignRequestDetailDTO(
session.getSessionId(),
session.getDocumentName(),
ownerUsername,
session.getMessage(),
session.getDueDate(),
session.getCreatedAt().toString(),
participant.getStatus(),
participant.getShowSignature(),
participant.getPageNumber(),
participant.getReason(),
participant.getLocation(),
participant.getShowLogo());
}
@Override
@Transactional
public void declineSignRequest(String sessionId, String username) {
SigningSessionEntity session = getSessionEntityById(sessionId);
User user =
userService
.findByUsernameIgnoreCase(username)
.orElseThrow(
() ->
ExceptionUtils.createIllegalArgumentException(
"error.notFound", "User {0} not found", username));
// Find participant matching user
SigningParticipantEntity participant =
session.getParticipants().stream()
.filter(p -> p.getUser().getId().equals(user.getId()))
.findFirst()
.orElseThrow(
() ->
ExceptionUtils.createIllegalArgumentException(
"error.unauthorized",
"User {0} is not a participant in session {1}",
username,
sessionId));
if (participant.getStatus() == ParticipantStatus.SIGNED) {
throw ExceptionUtils.createIllegalArgumentException(
"error.invalidState",
"Cannot decline - participant has already signed",
sessionId);
}
participant.setStatus(ParticipantStatus.DECLINED);
session.touch();
sessionRepository.save(session);
}
@Override
@Transactional
public void signDocument(String sessionId, String username, Object request) throws IOException {
if (!(request instanceof SignDocumentRequest)) {
throw new IllegalArgumentException("Invalid request type");
}
SignDocumentRequest signRequest = (SignDocumentRequest) request;
SigningSessionEntity session = getSessionEntityById(sessionId);
User user =
userService
.findByUsernameIgnoreCase(username)
.orElseThrow(
() ->
ExceptionUtils.createIllegalArgumentException(
"error.notFound", "User {0} not found", username));
// Find participant matching user
SigningParticipantEntity participant =
session.getParticipants().stream()
.filter(p -> p.getUser().getId().equals(user.getId()))
.findFirst()
.orElseThrow(
() ->
ExceptionUtils.createIllegalArgumentException(
"error.unauthorized",
"User {0} is not a participant in session {1}",
username,
sessionId));
if (participant.getStatus() == ParticipantStatus.SIGNED) {
throw ExceptionUtils.createIllegalArgumentException(
"error.invalidState", "Participant has already signed", sessionId);
}
if (participant.getStatus() == ParticipantStatus.DECLINED) {
throw ExceptionUtils.createIllegalArgumentException(
"error.invalidState", "Cannot sign - participant has declined", sessionId);
}
// Store wet signature metadata if provided
if (signRequest.hasWetSignature()) {
WetSignatureMetadata wetSig = signRequest.extractWetSignatureMetadata();
participant.setWetSignatureType(wetSig.getType());
participant.setWetSignatureData(wetSig.getData());
participant.setWetSignaturePage(wetSig.getPage());
participant.setWetSignatureX(wetSig.getX());
participant.setWetSignatureY(wetSig.getY());
participant.setWetSignatureWidth(wetSig.getWidth());
participant.setWetSignatureHeight(wetSig.getHeight());
}
// Store certificate data (reuse existing attachCertificate logic)
ParticipantCertificateRequest certRequest = new ParticipantCertificateRequest();
certRequest.setCertType(signRequest.getCertType());
certRequest.setPassword(signRequest.getPassword());
certRequest.setP12File(signRequest.getP12File());
certRequest.setPrivateKeyFile(signRequest.getPrivateKeyFile());
certRequest.setCertFile(signRequest.getCertFile());
// Use participant's signature settings from session
certRequest.setShowSignature(participant.getShowSignature());
certRequest.setPageNumber(participant.getPageNumber());
certRequest.setReason(participant.getReason());
certRequest.setLocation(participant.getLocation());
certRequest.setShowLogo(participant.getShowLogo());
// Store certificate submission (same as attachCertificate method)
ParticipantCertificateSubmissionEntity submissionEntity =
toSubmissionEntity(certRequest, participant);
participant.setCertificateSubmission(submissionEntity);
// Mark as signed
participant.setStatus(ParticipantStatus.SIGNED);
session.touch();
sessionRepository.save(session);
}
private void validateSessionOwnership(SigningSessionEntity session, String username) {
if (!session.getUser().getUsername().equalsIgnoreCase(username)) {
throw ExceptionUtils.createIllegalArgumentException(
"error.unauthorized", "You do not have permission to access this session");
}
}
private List<SigningParticipantEntity> getTargetParticipants(
SigningSessionEntity session, List<String> requestedEmails) {
if (requestedEmails == null || requestedEmails.isEmpty()) {
return session.getParticipants();
}
return session.getParticipants().stream()
.filter(p -> requestedEmails.contains(p.getEmail()))
.collect(Collectors.toList());
}
private ParticipantCertificateSubmissionEntity toSubmissionEntity(
ParticipantCertificateRequest request, SigningParticipantEntity participant)
throws IOException {
ParticipantCertificateSubmissionEntity entity =
new ParticipantCertificateSubmissionEntity();
entity.setParticipant(participant);
entity.setCertType(request.getCertType());
entity.setPassword(request.getPassword());
entity.setPrivateKey(toBytes(request.getPrivateKeyFile()));
entity.setCertificate(toBytes(request.getCertFile()));
entity.setP12Keystore(toBytes(request.getP12File()));
entity.setJksKeystore(toBytes(request.getJksFile()));
// Copy signature appearance settings from participant (configured by owner)
entity.setShowSignature(participant.getShowSignature());
entity.setPageNumber(participant.getPageNumber());
entity.setName(participant.getName());
entity.setReason(participant.getReason());
entity.setLocation(participant.getLocation());
entity.setShowLogo(participant.getShowLogo());
return entity;
}
private byte[] toBytes(MultipartFile file) throws IOException {
if (file == null || file.isEmpty()) {
return null;
}
return file.getBytes();
}
private SigningSessionSummaryDTO toSummaryDTO(SigningSessionEntity entity) {
int participantCount = entity.getParticipants().size();
int signedCount =
(int)
entity.getParticipants().stream()
.filter(p -> p.getStatus() == ParticipantStatus.SIGNED)
.count();
return new SigningSessionSummaryDTO(
entity.getSessionId(),
entity.getDocumentName(),
entity.getCreatedAt(),
participantCount,
signedCount,
entity.isFinalized());
}
private SignRequestSummaryDTO toSignRequestSummaryDTO(
SigningSessionEntity entity, Long userId) {
// Find participant matching user to get their status
SigningParticipantEntity participant =
entity.getParticipants().stream()
.filter(p -> p.getUser().getId().equals(userId))
.findFirst()
.orElse(null);
ParticipantStatus myStatus =
participant != null ? participant.getStatus() : ParticipantStatus.PENDING;
String ownerUsername =
entity.getUser() != null ? entity.getUser().getUsername() : entity.getOwnerEmail();
return new SignRequestSummaryDTO(
entity.getSessionId(),
entity.getDocumentName(),
ownerUsername,
entity.getCreatedAt().toString(),
entity.getDueDate(),
myStatus);
}
private SigningSessionDetailDTO toDetailDTO(SigningSessionEntity entity) {
List<ParticipantDTO> participants =
entity.getParticipants().stream()
.map(this::toParticipantDTO)
.collect(Collectors.toList());
return new SigningSessionDetailDTO(
entity.getSessionId(),
entity.getDocumentName(),
entity.getOwnerEmail(),
entity.getMessage(),
entity.getDueDate(),
entity.getCreatedAt(),
entity.getUpdatedAt(),
entity.isFinalized(),
participants);
}
private ParticipantDTO toParticipantDTO(SigningParticipantEntity entity) {
User user = entity.getUser();
return new ParticipantDTO(
user.getId(),
user.getUsername(),
entity.getName() != null ? entity.getName() : user.getUsername(),
entity.getStatus(),
entity.getLastUpdated(),
entity.getShowSignature(),
entity.getPageNumber(),
entity.getReason(),
entity.getLocation(),
entity.getShowLogo());
}
private SigningSession toSigningSession(SigningSessionEntity entity) {
SigningSession session = new SigningSession();
session.setSessionId(entity.getSessionId());
session.setDocumentName(entity.getDocumentName());
session.setOriginalPdf(entity.getOriginalPdf());
session.setSignedPdf(entity.getSignedPdf());
session.setOwnerEmail(entity.getOwnerEmail());
session.setMessage(entity.getMessage());
session.setDueDate(entity.getDueDate());
session.setCreatedAt(entity.getCreatedAt().toString());
session.setUpdatedAt(entity.getUpdatedAt().toString());
List<SigningParticipant> participants =
entity.getParticipants().stream()
.map(this::toSigningParticipant)
.collect(Collectors.toList());
session.setParticipants(participants);
return session;
}
private SigningParticipant toSigningParticipant(SigningParticipantEntity entity) {
SigningParticipant participant = new SigningParticipant();
participant.setUserId(entity.getUser() != null ? entity.getUser().getId() : null);
participant.setEmail(entity.getEmail());
participant.setName(entity.getName());
participant.setStatus(entity.getStatus());
participant.setShareToken(entity.getShareToken());
// Force lazy collection to load by creating a new ArrayList
participant.setNotifications(new ArrayList<>(entity.getNotifications()));
participant.setLastUpdated(entity.getLastUpdated().toString());
if (entity.getCertificateSubmission() != null) {
participant.setCertificateSubmission(
toParticipantCertificateSubmission(entity.getCertificateSubmission()));
}
return participant;
}
private ParticipantCertificateSubmission toParticipantCertificateSubmission(
ParticipantCertificateSubmissionEntity entity) {
return ParticipantCertificateSubmission.builder()
.certType(entity.getCertType())
.password(entity.getPassword())
.privateKey(entity.getPrivateKey())
.certificate(entity.getCertificate())
.p12Keystore(entity.getP12Keystore())
.jksKeystore(entity.getJksKeystore())
.showSignature(entity.getShowSignature())
.pageNumber(entity.getPageNumber())
.name(entity.getName())
.reason(entity.getReason())
.location(entity.getLocation())
.showLogo(entity.getShowLogo())
.build();
}
/**
* Gets all wet signature metadata for participants who have signed. Used during finalization to
* overlay wet signatures on the PDF.
*
* @param sessionId The session ID
* @return List of wet signature metadata for all signed participants
*/
public List<WetSignatureMetadata> getAllWetSignatures(String sessionId) {
SigningSessionEntity session = getSessionEntityById(sessionId);
return session.getParticipants().stream()
.filter(p -> p.getStatus() == ParticipantStatus.SIGNED)
.filter(p -> p.getWetSignatureType() != null)
.map(
p -> {
WetSignatureMetadata meta = new WetSignatureMetadata();
meta.setType(p.getWetSignatureType());
meta.setData(p.getWetSignatureData());
meta.setPage(p.getWetSignaturePage());
meta.setX(p.getWetSignatureX());
meta.setY(p.getWetSignatureY());
meta.setWidth(p.getWetSignatureWidth());
meta.setHeight(p.getWetSignatureHeight());
return meta;
})
.collect(Collectors.toList());
}
/**
* Clears wet signature metadata from all participants after finalization. This is required for
* GDPR compliance and to avoid storing large base64 data.
*
* @param sessionId The session ID
*/
@Transactional
public void clearWetSignatureMetadata(String sessionId) {
SigningSessionEntity session = getSessionEntityById(sessionId);
boolean anyCleared = false;
for (SigningParticipantEntity participant : session.getParticipants()) {
if (participant.getWetSignatureType() != null) {
participant.setWetSignatureType(null);
participant.setWetSignatureData(null);
participant.setWetSignaturePage(null);
participant.setWetSignatureX(null);
participant.setWetSignatureY(null);
participant.setWetSignatureWidth(null);
participant.setWetSignatureHeight(null);
anyCleared = true;
}
}
if (anyCleared) {
log.info("Cleared wet signature metadata for session: {}", sessionId);
sessionRepository.save(session);
}
}
@Override
public boolean isDatabaseBacked() {
return true;
}
}
@@ -115,10 +115,12 @@ public class EmailService {
* @param to The recipient email address
* @param username The username for the new account
* @param temporaryPassword The temporary password
* @param loginUrl The URL to the login page
* @throws MessagingException If there is an issue with creating or sending the email.
*/
@Async
public void sendInviteEmail(String to, String username, String temporaryPassword)
public void sendInviteEmail(
String to, String username, String temporaryPassword, String loginUrl)
throws MessagingException {
String subject = "Welcome to Stirling PDF";
@@ -144,6 +146,14 @@ public class EmailService {
<div style="background-color: #fff3cd; border-left: 4px solid #ffc107; padding: 15px; margin: 20px 0; border-radius: 4px;">
<p style="margin: 0; color: #856404;"><strong>⚠️ Important:</strong> You will be required to change your password upon first login for security reasons.</p>
</div>
<!-- CTA Button -->
<div style="text-align: center; margin: 30px 0;">
<a href="%s" style="display: inline-block; background-color: #007bff; color: #ffffff; padding: 14px 28px; text-decoration: none; border-radius: 5px; font-weight: bold;">Log In to Stirling PDF</a>
</div>
<p style="font-size: 14px; color: #666;">Or copy and paste this link in your browser:</p>
<div style="background-color: #f8f9fa; padding: 12px; margin: 15px 0; border-radius: 4px; word-break: break-all; font-size: 13px; color: #555;">
%s
</div>
<p>Please keep these credentials secure and do not share them with anyone.</p>
<p style="margin-bottom: 0;">— The Stirling PDF Team</p>
</div>
@@ -155,7 +165,7 @@ public class EmailService {
</div>
</body></html>
"""
.formatted(username, temporaryPassword);
.formatted(username, temporaryPassword, loginUrl, loginUrl);
sendPlainEmail(to, subject, body, true);
}
@@ -50,7 +50,6 @@ public class JwtService implements JwtServiceInterface {
KeyPersistenceServiceInterface keyPersistenceService) {
this.v2Enabled = v2Enabled;
this.keyPersistenceService = keyPersistenceService;
log.info("JwtService initialized");
}
@Override
@@ -256,11 +255,9 @@ public class JwtService implements JwtServiceInterface {
String authHeader = request.getHeader("Authorization");
if (authHeader != null && authHeader.startsWith("Bearer ")) {
String token = authHeader.substring(7); // Remove "Bearer " prefix
log.debug("JWT token extracted from Authorization header");
return token;
}
log.debug("No JWT token found in Authorization header");
return null;
}
@@ -283,10 +280,9 @@ public class JwtService implements JwtServiceInterface {
.parse(token)
.getHeader()
.get("kid");
log.debug("Extracted key ID from token: {}", keyId);
return keyId;
} catch (Exception e) {
log.warn("Failed to extract key ID from token header: {}", e.getMessage());
log.debug("Failed to extract key ID from token header: {}", e.getMessage());
return null;
}
}
@@ -55,7 +55,6 @@ public class KeyPairCleanupService {
return;
}
log.info("Removing keys older than retention period");
removeKeys(eligibleKeys);
keyPersistenceService.refreshActiveKeyPair();
}
@@ -778,4 +778,30 @@ public class UserService implements UserServiceInterface {
return updated;
}
/**
* Grandfathers SSO users who have never created a session (invited/pending accounts). These
* users would otherwise be blocked when SSO requires a paid license despite existing before the
* policy change.
*
* @return Number of pending users updated
*/
@Transactional
public int grandfatherPendingSsoUsersWithoutSession() {
List<User> pendingUsers = userRepository.findPendingSsoUsersWithoutSession();
int updated = 0;
for (User user : pendingUsers) {
if (!user.isOauthGrandfathered()) {
user.setOauthGrandfathered(true);
updated++;
}
}
if (updated > 0) {
userRepository.saveAll(pendingUsers);
}
return updated;
}
}
@@ -0,0 +1,299 @@
package stirling.software.proprietary.service;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import java.util.stream.Stream;
import org.springframework.stereotype.Service;
import lombok.extern.slf4j.Slf4j;
import stirling.software.common.configuration.InstallationPathConfig;
import stirling.software.common.service.PersonalSignatureServiceInterface;
import stirling.software.proprietary.model.api.signature.SavedSignatureRequest;
import stirling.software.proprietary.model.api.signature.SavedSignatureResponse;
/**
* Service for managing user signatures with authentication and storage limits. This proprietary
* version enforces per-user quotas and requires authentication. Provides access to personal
* signatures only (shared signatures handled by core service).
*/
@Service
@Slf4j
public class SignatureService implements PersonalSignatureServiceInterface {
private final String SIGNATURE_BASE_PATH;
private final String ALL_USERS_FOLDER = "ALL_USERS";
// Storage limits per user
private static final int MAX_SIGNATURES_PER_USER = 20;
private static final long MAX_SIGNATURE_SIZE_BYTES = 2_000_000; // 2MB per signature
private static final long MAX_TOTAL_USER_STORAGE_BYTES = 20_000_000; // 20MB total per user
public SignatureService() {
SIGNATURE_BASE_PATH = InstallationPathConfig.getSignaturesPath();
}
/**
* Get a personal signature from the user's folder only. Does NOT check shared folder (that's
* handled by core service).
*/
@Override
public byte[] getPersonalSignatureBytes(String username, String fileName) throws IOException {
validateFileName(fileName);
Path userPath = Paths.get(SIGNATURE_BASE_PATH, username, fileName);
if (!Files.exists(userPath)) {
throw new FileNotFoundException("Personal signature not found");
}
return Files.readAllBytes(userPath);
}
/** Save a signature with storage limits enforced. */
public SavedSignatureResponse saveSignature(String username, SavedSignatureRequest request)
throws IOException {
validateFileName(request.getId());
// Determine folder based on scope
String scope = request.getScope();
if (scope == null || scope.isEmpty()) {
scope = "personal"; // Default to personal
}
String folderName = "shared".equals(scope) ? ALL_USERS_FOLDER : username;
Path targetFolder = Paths.get(SIGNATURE_BASE_PATH, folderName);
// Only enforce limits for personal signatures (not shared)
if ("personal".equals(scope)) {
enforceStorageLimits(username, request.getDataUrl());
}
Files.createDirectories(targetFolder);
long timestamp = System.currentTimeMillis();
SavedSignatureResponse response = new SavedSignatureResponse();
response.setId(request.getId());
response.setLabel(request.getLabel());
response.setType(request.getType());
response.setScope(scope);
response.setCreatedAt(timestamp);
response.setUpdatedAt(timestamp);
// Extract and save image data
String dataUrl = request.getDataUrl();
if (dataUrl != null && dataUrl.startsWith("data:image/")) {
// Validate dataUrl size before decoding
if (dataUrl.length() > MAX_SIGNATURE_SIZE_BYTES * 2) {
throw new IllegalArgumentException(
"Signature data too large (max "
+ (MAX_SIGNATURE_SIZE_BYTES / 1024)
+ "KB)");
}
// Extract base64 data
String base64Data = dataUrl.substring(dataUrl.indexOf(",") + 1);
byte[] imageBytes = Base64.getDecoder().decode(base64Data);
// Validate decoded size
if (imageBytes.length > MAX_SIGNATURE_SIZE_BYTES) {
throw new IllegalArgumentException(
"Signature image too large (max "
+ (MAX_SIGNATURE_SIZE_BYTES / 1024)
+ "KB)");
}
// Determine and validate file extension from data URL
String mimeType = dataUrl.substring(dataUrl.indexOf(":") + 1, dataUrl.indexOf(";"));
String rawExtension = mimeType.substring(mimeType.indexOf("/") + 1);
String extension = validateAndNormalizeExtension(rawExtension);
// Save image file
String imageFileName = request.getId() + "." + extension;
Path imagePath = targetFolder.resolve(imageFileName);
// Verify path is within target directory
verifyPathWithinDirectory(imagePath, targetFolder);
Files.write(
imagePath,
imageBytes,
StandardOpenOption.CREATE,
StandardOpenOption.TRUNCATE_EXISTING);
// Store reference to image file (unified endpoint for all signatures)
response.setDataUrl("/api/v1/general/signatures/" + imageFileName);
}
log.info("Saved signature {} for user {} (scope: {})", request.getId(), username, scope);
return response;
}
/** Get all saved signatures for a user (personal + shared). */
public List<SavedSignatureResponse> getSavedSignatures(String username) throws IOException {
List<SavedSignatureResponse> signatures = new ArrayList<>();
// Load personal signatures
Path personalFolder = Paths.get(SIGNATURE_BASE_PATH, username);
if (Files.exists(personalFolder)) {
signatures.addAll(loadSignaturesFromFolder(personalFolder, "personal", true));
}
// Load shared signatures
Path sharedFolder = Paths.get(SIGNATURE_BASE_PATH, ALL_USERS_FOLDER);
if (Files.exists(sharedFolder)) {
signatures.addAll(loadSignaturesFromFolder(sharedFolder, "shared", false));
}
return signatures;
}
/** Delete a signature from user's personal folder. Cannot delete shared signatures. */
public void deleteSignature(String username, String signatureId) throws IOException {
validateFileName(signatureId);
// Only allow deletion from personal folder
Path personalFolder = Paths.get(SIGNATURE_BASE_PATH, username);
boolean deleted = false;
if (Files.exists(personalFolder)) {
try (Stream<Path> stream = Files.list(personalFolder)) {
List<Path> matchingFiles =
stream.filter(
path ->
path.getFileName()
.toString()
.startsWith(signatureId + "."))
.toList();
for (Path file : matchingFiles) {
Files.delete(file);
deleted = true;
log.info("Deleted signature file: {}", file);
}
}
}
if (!deleted) {
throw new FileNotFoundException("Signature not found or cannot be deleted");
}
}
// Private helper methods
private void enforceStorageLimits(String username, String dataUrlToAdd) throws IOException {
Path userFolder = Paths.get(SIGNATURE_BASE_PATH, username);
if (!Files.exists(userFolder)) {
return; // First signature, no limits to check
}
// Count existing signatures
long signatureCount;
try (Stream<Path> stream = Files.list(userFolder)) {
signatureCount = stream.filter(this::isImageFile).count();
}
if (signatureCount >= MAX_SIGNATURES_PER_USER) {
throw new IllegalArgumentException(
"Maximum signatures limit reached (" + MAX_SIGNATURES_PER_USER + ")");
}
// Calculate total storage used
long totalSize = 0;
try (Stream<Path> stream = Files.list(userFolder)) {
totalSize =
stream.filter(this::isImageFile)
.mapToLong(
path -> {
try {
return Files.size(path);
} catch (IOException e) {
return 0;
}
})
.sum();
}
// Estimate new signature size (base64 decodes to ~75% of original)
long estimatedNewSize = (long) (dataUrlToAdd.length() * 0.75);
if (totalSize + estimatedNewSize > MAX_TOTAL_USER_STORAGE_BYTES) {
throw new IllegalArgumentException(
"Storage quota exceeded (max "
+ (MAX_TOTAL_USER_STORAGE_BYTES / 1_000_000)
+ "MB)");
}
}
private List<SavedSignatureResponse> loadSignaturesFromFolder(
Path folder, String scope, boolean isPersonal) throws IOException {
List<SavedSignatureResponse> signatures = new ArrayList<>();
try (Stream<Path> stream = Files.list(folder)) {
stream.filter(this::isImageFile)
.forEach(
path -> {
try {
String fileName = path.getFileName().toString();
String id = fileName.substring(0, fileName.lastIndexOf('.'));
SavedSignatureResponse sig = new SavedSignatureResponse();
sig.setId(id);
sig.setLabel(id);
sig.setType("image");
sig.setScope(scope);
sig.setCreatedAt(Files.getLastModifiedTime(path).toMillis());
sig.setUpdatedAt(Files.getLastModifiedTime(path).toMillis());
// Set unified URL path (works for both personal and shared)
sig.setDataUrl("/api/v1/general/signatures/" + fileName);
signatures.add(sig);
} catch (IOException e) {
log.error("Error reading signature file: " + path, e);
}
});
}
return signatures;
}
private boolean isImageFile(Path path) {
String fileName = path.getFileName().toString().toLowerCase();
return fileName.endsWith(".jpg") || fileName.endsWith(".jpeg") || fileName.endsWith(".png");
}
private void validateFileName(String fileName) {
if (fileName.contains("..") || fileName.contains("/") || fileName.contains("\\")) {
throw new IllegalArgumentException("Invalid filename");
}
if (!fileName.matches("^[a-zA-Z0-9_.-]+$")) {
throw new IllegalArgumentException("Filename contains invalid characters");
}
}
private String validateAndNormalizeExtension(String extension) {
String normalized = extension.toLowerCase().trim();
if (normalized.equals("png") || normalized.equals("jpg") || normalized.equals("jpeg")) {
return normalized;
}
throw new IllegalArgumentException("Unsupported image extension: " + extension);
}
private void verifyPathWithinDirectory(Path resolvedPath, Path targetDirectory)
throws IOException {
Path canonicalTarget = targetDirectory.toAbsolutePath().normalize();
Path canonicalResolved = resolvedPath.toAbsolutePath().normalize();
if (!canonicalResolved.startsWith(canonicalTarget)) {
throw new IOException("Resolved path is outside the target directory");
}
}
}
@@ -192,10 +192,18 @@ public class UserLicenseSettingsService {
+ "They will retain OAuth access even without a paid license. "
+ "New users will require a paid license for OAuth.",
updated);
} else if (grandfatheredCount > 0) {
log.debug(
"OAuth grandfathering already completed: {} users grandfathered",
grandfatheredCount);
}
// Grandfather pending users (invited but never logged in)
// The query filters to non-grandfathered users only, so this is idempotent
if (grandfatheredCount > 0 || oauthUsersCount > 0) {
int pendingUpdated = userService.grandfatherPendingSsoUsersWithoutSession();
if (pendingUpdated > 0) {
log.warn(
"OAuth GRANDFATHERING: Marked {} pending SSO users (no prior sessions) as"
+ " grandfathered.",
pendingUpdated);
}
}
}
}
@@ -1,251 +0,0 @@
package stirling.software.proprietary.service;
import java.io.*;
import java.math.BigInteger;
import java.security.*;
import java.security.cert.Certificate;
import java.security.cert.X509Certificate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.Optional;
import org.bouncycastle.asn1.x500.X500Name;
import org.bouncycastle.asn1.x509.BasicConstraints;
import org.bouncycastle.asn1.x509.ExtendedKeyUsage;
import org.bouncycastle.asn1.x509.Extension;
import org.bouncycastle.asn1.x509.KeyPurposeId;
import org.bouncycastle.asn1.x509.KeyUsage;
import org.bouncycastle.cert.X509CertificateHolder;
import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter;
import org.bouncycastle.cert.jcajce.JcaX509ExtensionUtils;
import org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.operator.ContentSigner;
import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import stirling.software.proprietary.model.CertificateType;
import stirling.software.proprietary.model.UserServerCertificateEntity;
import stirling.software.proprietary.security.database.repository.UserRepository;
import stirling.software.proprietary.security.model.User;
import stirling.software.proprietary.security.repository.UserServerCertificateRepository;
@Service
@Slf4j
@RequiredArgsConstructor
public class UserServerCertificateService {
private static final String KEYSTORE_ALIAS = "stirling-pdf-user-cert";
private static final String DEFAULT_PASSWORD_PREFIX = "stirling-user-cert-";
private static final int VALIDITY_DAYS = 365;
private final UserServerCertificateRepository certificateRepository;
private final UserRepository userRepository;
static {
Security.addProvider(new BouncyCastleProvider());
}
/** Get or create user certificate (auto-generate if not exists) */
@Transactional
public UserServerCertificateEntity getOrCreateUserCertificate(Long userId) throws Exception {
Optional<UserServerCertificateEntity> existing = certificateRepository.findByUserId(userId);
if (existing.isPresent()) {
return existing.get();
}
User user =
userRepository
.findById(userId)
.orElseThrow(() -> new IllegalArgumentException("User not found"));
return generateUserCertificate(user);
}
/** Generate new certificate for user */
@Transactional
public UserServerCertificateEntity generateUserCertificate(User user) throws Exception {
log.info("Generating server certificate for user: {}", user.getUsername());
// Generate key pair
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA", "BC");
keyPairGenerator.initialize(2048, new SecureRandom());
KeyPair keyPair = keyPairGenerator.generateKeyPair();
// Certificate details with username
String username = user.getUsername();
X500Name subject = new X500Name("CN=" + username + ", O=Stirling-PDF User, C=US");
BigInteger serialNumber = BigInteger.valueOf(System.currentTimeMillis());
Date notBefore = new Date();
Date notAfter =
new Date(notBefore.getTime() + ((long) VALIDITY_DAYS * 24 * 60 * 60 * 1000));
// Build certificate
JcaX509v3CertificateBuilder certBuilder =
new JcaX509v3CertificateBuilder(
subject, serialNumber, notBefore, notAfter, subject, keyPair.getPublic());
// Add PDF-specific certificate extensions
JcaX509ExtensionUtils extUtils = new JcaX509ExtensionUtils();
// End-entity certificate, not a CA
certBuilder.addExtension(Extension.basicConstraints, true, new BasicConstraints(false));
// Key usage for PDF digital signatures
certBuilder.addExtension(
Extension.keyUsage,
true,
new KeyUsage(KeyUsage.digitalSignature | KeyUsage.nonRepudiation));
// Extended key usage for document signing
certBuilder.addExtension(
Extension.extendedKeyUsage,
false,
new ExtendedKeyUsage(KeyPurposeId.id_kp_codeSigning));
// Subject Key Identifier
certBuilder.addExtension(
Extension.subjectKeyIdentifier,
false,
extUtils.createSubjectKeyIdentifier(keyPair.getPublic()));
// Authority Key Identifier for self-signed cert
certBuilder.addExtension(
Extension.authorityKeyIdentifier,
false,
extUtils.createAuthorityKeyIdentifier(keyPair.getPublic()));
// Sign certificate
ContentSigner signer =
new JcaContentSignerBuilder("SHA256WithRSA")
.setProvider("BC")
.build(keyPair.getPrivate());
X509CertificateHolder certHolder = certBuilder.build(signer);
X509Certificate cert =
new JcaX509CertificateConverter().setProvider("BC").getCertificate(certHolder);
// Create keystore
KeyStore keyStore = KeyStore.getInstance("PKCS12");
keyStore.load(null, null);
String password = generateUserPassword(user.getId());
keyStore.setKeyEntry(
KEYSTORE_ALIAS,
keyPair.getPrivate(),
password.toCharArray(),
new Certificate[] {cert});
// Store keystore bytes
ByteArrayOutputStream baos = new ByteArrayOutputStream();
keyStore.store(baos, password.toCharArray());
byte[] keystoreBytes = baos.toByteArray();
// Create entity
UserServerCertificateEntity entity = new UserServerCertificateEntity();
entity.setUser(user);
entity.setKeystoreData(keystoreBytes);
entity.setKeystorePassword(password);
entity.setCertificateType(CertificateType.AUTO_GENERATED);
entity.setSubjectDn(cert.getSubjectX500Principal().getName());
entity.setIssuerDn(cert.getIssuerX500Principal().getName());
entity.setValidFrom(
LocalDateTime.ofInstant(cert.getNotBefore().toInstant(), ZoneId.systemDefault()));
entity.setValidTo(
LocalDateTime.ofInstant(cert.getNotAfter().toInstant(), ZoneId.systemDefault()));
return certificateRepository.save(entity);
}
/** Upload user-provided certificate */
@Transactional
public UserServerCertificateEntity uploadUserCertificate(
User user, InputStream p12Stream, String password) throws Exception {
log.info("Uploading user certificate for user: {}", user.getUsername());
// Validate keystore
byte[] keystoreBytes = p12Stream.readAllBytes();
KeyStore keyStore = KeyStore.getInstance("PKCS12");
keyStore.load(new ByteArrayInputStream(keystoreBytes), password.toCharArray());
// Extract certificate info
String alias = keyStore.aliases().nextElement();
X509Certificate cert = (X509Certificate) keyStore.getCertificate(alias);
if (cert == null) {
throw new IllegalArgumentException("No certificate found in keystore");
}
// Create or update entity
UserServerCertificateEntity entity =
certificateRepository
.findByUserId(user.getId())
.orElse(new UserServerCertificateEntity());
entity.setUser(user);
entity.setKeystoreData(keystoreBytes);
entity.setKeystorePassword(password);
entity.setCertificateType(CertificateType.USER_UPLOADED);
entity.setSubjectDn(cert.getSubjectX500Principal().getName());
entity.setIssuerDn(cert.getIssuerX500Principal().getName());
entity.setValidFrom(
LocalDateTime.ofInstant(cert.getNotBefore().toInstant(), ZoneId.systemDefault()));
entity.setValidTo(
LocalDateTime.ofInstant(cert.getNotAfter().toInstant(), ZoneId.systemDefault()));
return certificateRepository.save(entity);
}
/** Get user's KeyStore for signing operations */
@Transactional(readOnly = true)
public KeyStore getUserKeyStore(Long userId) throws Exception {
UserServerCertificateEntity cert =
certificateRepository
.findByUserId(userId)
.orElseThrow(
() -> new IllegalArgumentException("User certificate not found"));
KeyStore keyStore = KeyStore.getInstance("PKCS12");
keyStore.load(
new ByteArrayInputStream(cert.getKeystoreData()),
cert.getKeystorePassword().toCharArray());
return keyStore;
}
/** Get user's keystore password */
@Transactional(readOnly = true)
public String getUserKeystorePassword(Long userId) {
UserServerCertificateEntity cert =
certificateRepository
.findByUserId(userId)
.orElseThrow(
() -> new IllegalArgumentException("User certificate not found"));
return cert.getKeystorePassword();
}
/** Delete user certificate */
@Transactional
public void deleteUserCertificate(Long userId) {
certificateRepository.findByUserId(userId).ifPresent(certificateRepository::delete);
}
/** Check if user has certificate */
@Transactional(readOnly = true)
public boolean hasUserCertificate(Long userId) {
return certificateRepository.findByUserId(userId).isPresent();
}
/** Get certificate info (without keystore data) */
@Transactional(readOnly = true)
public Optional<UserServerCertificateEntity> getCertificateInfo(Long userId) {
return certificateRepository.findByUserId(userId);
}
/** Generate consistent password for user (based on user ID) */
private String generateUserPassword(Long userId) {
return DEFAULT_PASSWORD_PREFIX + userId;
}
}
@@ -1,87 +0,0 @@
-- Migration: Convert shared signing from email-based to user-based participants
-- Date: 2025-12-03
-- Description: Add User FK to signing_participants, signature appearance fields,
-- and create user_server_certificates table
-- ===========================================================================
-- PART 1: Add new columns to signing_participants table
-- ===========================================================================
-- Add user_id FK column (nullable initially for migration)
ALTER TABLE signing_participants ADD COLUMN IF NOT EXISTS user_id BIGINT;
-- Make existing email field nullable (keep for audit trail)
ALTER TABLE signing_participants ALTER COLUMN email DROP NOT NULL;
-- Make share_token nullable (deprecating this field)
ALTER TABLE signing_participants ALTER COLUMN share_token DROP NOT NULL;
-- Add signature appearance columns (owner-controlled)
ALTER TABLE signing_participants ADD COLUMN IF NOT EXISTS show_signature BOOLEAN;
ALTER TABLE signing_participants ADD COLUMN IF NOT EXISTS page_number INTEGER;
ALTER TABLE signing_participants ADD COLUMN IF NOT EXISTS reason VARCHAR(255);
ALTER TABLE signing_participants ADD COLUMN IF NOT EXISTS location VARCHAR(255);
ALTER TABLE signing_participants ADD COLUMN IF NOT EXISTS show_logo BOOLEAN;
-- ===========================================================================
-- PART 2: Migrate existing data
-- ===========================================================================
-- Match existing participants to users based on email = username
-- NOTE: This assumes participants were created with email matching username
UPDATE signing_participants sp
SET user_id = u.user_id
FROM users u
WHERE sp.email = u.username
AND sp.user_id IS NULL;
-- ===========================================================================
-- PART 3: Add constraints
-- ===========================================================================
-- Add Foreign Key constraint to User table
ALTER TABLE signing_participants
ADD CONSTRAINT fk_participant_user
FOREIGN KEY (user_id) REFERENCES users(user_id)
ON DELETE CASCADE;
-- Make user_id non-nullable after migration
ALTER TABLE signing_participants ALTER COLUMN user_id SET NOT NULL;
-- ===========================================================================
-- PART 4: Create user_server_certificates table
-- ===========================================================================
CREATE TABLE IF NOT EXISTS user_server_certificates (
id BIGSERIAL PRIMARY KEY,
user_id BIGINT NOT NULL UNIQUE,
keystore_data BYTEA NOT NULL,
keystore_password VARCHAR(255) NOT NULL,
certificate_type VARCHAR(50) NOT NULL,
subject_dn VARCHAR(500),
issuer_dn VARCHAR(500),
valid_from TIMESTAMP,
valid_to TIMESTAMP,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT fk_user_cert_user FOREIGN KEY (user_id) REFERENCES users(user_id) ON DELETE CASCADE
);
-- Create index on user_id for faster lookups
CREATE INDEX IF NOT EXISTS idx_user_cert_user_id ON user_server_certificates(user_id);
-- ===========================================================================
-- VERIFICATION QUERIES (Run these to verify migration)
-- ===========================================================================
-- Check participants without user mapping
-- SELECT * FROM signing_participants WHERE user_id IS NULL;
-- Check new table structure
-- SELECT column_name, data_type, is_nullable
-- FROM information_schema.columns
-- WHERE table_name = 'signing_participants'
-- ORDER BY ordinal_position;
-- Check user certificates table
-- SELECT * FROM user_server_certificates;
@@ -1,74 +0,0 @@
-- Migration: Add wet signature metadata fields to signing_participants
-- Date: 2025-01-15
-- Description: Add columns to store visual signature annotations placed by participants.
-- This metadata is used to overlay wet signatures on the PDF during finalization
-- and is cleared after the final signed PDF is generated.
-- ===========================================================================
-- Add wet signature metadata columns
-- ===========================================================================
-- Type of wet signature: "canvas" (drawn), "image" (uploaded), "text" (typed)
ALTER TABLE signing_participants ADD COLUMN IF NOT EXISTS wet_signature_type VARCHAR(20);
-- Base64-encoded image data or text content
-- Using TEXT for large base64 image data
ALTER TABLE signing_participants ADD COLUMN IF NOT EXISTS wet_signature_data TEXT;
-- Position and size of the signature on the PDF
ALTER TABLE signing_participants ADD COLUMN IF NOT EXISTS wet_signature_page INTEGER;
ALTER TABLE signing_participants ADD COLUMN IF NOT EXISTS wet_signature_x DOUBLE PRECISION;
ALTER TABLE signing_participants ADD COLUMN IF NOT EXISTS wet_signature_y DOUBLE PRECISION;
ALTER TABLE signing_participants ADD COLUMN IF NOT EXISTS wet_signature_width DOUBLE PRECISION;
ALTER TABLE signing_participants ADD COLUMN IF NOT EXISTS wet_signature_height DOUBLE PRECISION;
-- ===========================================================================
-- Add indexes for common queries
-- ===========================================================================
-- Index for querying participants with wet signatures during finalization
CREATE INDEX IF NOT EXISTS idx_participants_wet_signature
ON signing_participants(session_id, wet_signature_type)
WHERE wet_signature_type IS NOT NULL;
-- ===========================================================================
-- Add comments for documentation
-- ===========================================================================
COMMENT ON COLUMN signing_participants.wet_signature_type IS
'Type of wet signature: canvas, image, or text. NULL if participant has not placed a visual signature.';
COMMENT ON COLUMN signing_participants.wet_signature_data IS
'Base64-encoded image data or text content for the wet signature. Cleared after finalization for GDPR compliance.';
COMMENT ON COLUMN signing_participants.wet_signature_page IS
'Zero-indexed page number where the wet signature is placed.';
COMMENT ON COLUMN signing_participants.wet_signature_x IS
'X coordinate (in PDF points) of the signature rectangle, measured from left edge.';
COMMENT ON COLUMN signing_participants.wet_signature_y IS
'Y coordinate (in PDF points) of the signature rectangle, measured from top edge (UI coordinates, will be converted for PDF).';
COMMENT ON COLUMN signing_participants.wet_signature_width IS
'Width of the signature rectangle in PDF points.';
COMMENT ON COLUMN signing_participants.wet_signature_height IS
'Height of the signature rectangle in PDF points.';
-- ===========================================================================
-- VERIFICATION QUERIES (Run these to verify migration)
-- ===========================================================================
-- Check new column structure
-- SELECT column_name, data_type, is_nullable, column_default
-- FROM information_schema.columns
-- WHERE table_name = 'signing_participants'
-- AND column_name LIKE 'wet_signature%'
-- ORDER BY ordinal_position;
-- Check index creation
-- SELECT indexname, indexdef
-- FROM pg_indexes
-- WHERE tablename = 'signing_participants'
-- AND indexname LIKE '%wet_signature%';
@@ -1,21 +0,0 @@
-- Create user_server_certificates table for storing per-user signing certificates
CREATE TABLE IF NOT EXISTS user_server_certificates (
id BIGSERIAL PRIMARY KEY,
user_id BIGINT NOT NULL UNIQUE,
keystore_data BYTEA NOT NULL,
keystore_password VARCHAR(255) NOT NULL,
certificate_type VARCHAR(50) NOT NULL,
subject_dn VARCHAR(500),
issuer_dn VARCHAR(500),
valid_from TIMESTAMP,
valid_to TIMESTAMP,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT fk_user_cert_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
);
-- Create index for faster lookups by user_id
CREATE INDEX IF NOT EXISTS idx_user_certs_user_id ON user_server_certificates(user_id);
-- Create index for checking certificate expiration
CREATE INDEX IF NOT EXISTS idx_user_certs_valid_to ON user_server_certificates(valid_to);
@@ -2,6 +2,9 @@ package stirling.software.proprietary.service;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.util.Optional;
@@ -198,4 +201,70 @@ class UserLicenseSettingsServiceTest {
assertEquals(5, result, "Should fall back to default 5 users if grandfathered is 0");
}
@Test
void grandfatherExistingOAuthUsers_runsOnlyWhenNoneGrandfathered() {
// With grandfatheredCount == 0, should run grandfathering for all users
when(userService.countOAuthUsers()).thenReturn(10L);
when(userService.countGrandfatheredOAuthUsers()).thenReturn(0L);
when(userService.grandfatherAllOAuthUsers()).thenReturn(10);
when(userService.grandfatherPendingSsoUsersWithoutSession()).thenReturn(0);
service.grandfatherExistingOAuthUsers();
verify(userService, times(1)).grandfatherAllOAuthUsers();
verify(userService, times(1)).grandfatherPendingSsoUsersWithoutSession();
}
@Test
void grandfatherExistingOAuthUsers_skipsMainButRunsPendingWhenSomeAlreadyGrandfathered() {
// V2→V2.1 upgrade: some users already grandfathered, but pending users need to be checked
when(userService.countOAuthUsers()).thenReturn(10L);
when(userService.countGrandfatheredOAuthUsers()).thenReturn(4L);
when(userService.grandfatherPendingSsoUsersWithoutSession()).thenReturn(2);
service.grandfatherExistingOAuthUsers();
verify(userService, never()).grandfatherAllOAuthUsers();
verify(userService, times(1)).grandfatherPendingSsoUsersWithoutSession();
}
@Test
void grandfatherExistingOAuthUsers_stillChecksPendingWhenAllUsersGrandfathered() {
// All active users grandfathered, but still check for pending users
when(userService.countOAuthUsers()).thenReturn(10L);
when(userService.countGrandfatheredOAuthUsers()).thenReturn(10L);
when(userService.grandfatherPendingSsoUsersWithoutSession()).thenReturn(0);
service.grandfatherExistingOAuthUsers();
verify(userService, never()).grandfatherAllOAuthUsers();
verify(userService, times(1)).grandfatherPendingSsoUsersWithoutSession();
}
@Test
void grandfatherExistingOAuthUsers_skipsWhenNoOAuthUsers() {
when(userService.countOAuthUsers()).thenReturn(0L);
when(userService.countGrandfatheredOAuthUsers()).thenReturn(0L);
service.grandfatherExistingOAuthUsers();
verify(userService, never()).grandfatherAllOAuthUsers();
verify(userService, never()).grandfatherPendingSsoUsersWithoutSession();
}
@Test
void grandfatherExistingOAuthUsers_grandfathersPendingUsersOnFirstRun() {
// Pending users (invited but never logged in) should be grandfathered
// during the initial grandfathering run (when grandfatheredCount == 0)
when(userService.countOAuthUsers()).thenReturn(5L);
when(userService.countGrandfatheredOAuthUsers()).thenReturn(0L);
when(userService.grandfatherAllOAuthUsers()).thenReturn(5);
when(userService.grandfatherPendingSsoUsersWithoutSession()).thenReturn(3);
service.grandfatherExistingOAuthUsers();
verify(userService, times(1)).grandfatherAllOAuthUsers();
verify(userService, times(1)).grandfatherPendingSsoUsersWithoutSession();
}
}
+42 -41
View File
@@ -2,22 +2,26 @@ plugins {
id "java"
id "jacoco"
id "io.spring.dependency-management" version "1.1.7"
id "org.springframework.boot" version "3.5.7"
id "org.springframework.boot" version "3.5.6"
id "org.springdoc.openapi-gradle-plugin" version "1.9.0"
id "io.swagger.swaggerhub" version "1.3.2"
id "com.diffplug.spotless" version "8.1.0"
id "com.diffplug.spotless" version "7.2.1"
id "com.github.jk1.dependency-license-report" version "2.9"
//id "nebula.lint" version "19.0.3"
id "org.sonarqube" version "6.3.1.5724"
}
import com.github.jk1.license.render.*
ext {
springBootVersion = "3.5.7"
pdfboxVersion = "3.0.6"
springBootVersion = "3.5.6"
pdfboxVersion = "3.0.5"
imageioVersion = "3.12.0"
lombokVersion = "1.18.42"
bouncycastleVersion = "1.82"
springSecuritySamlVersion = "6.5.6"
springSecuritySamlVersion = "6.5.5"
openSamlVersion = "4.3.2"
commonmarkVersion = "0.27.0"
commonmarkVersion = "0.26.0"
googleJavaFormatVersion = "1.28.0"
junitPlatformVersion = "1.12.2"
}
@@ -51,39 +55,15 @@ repositories {
maven { url = 'https://build.shibboleth.net/maven/releases' }
}
allprojects {
group = 'stirling.software'
version = '2.0.1'
allprojects {
group = 'stirling.software'
version = '2.0.2'
configurations.configureEach {
exclude group: 'commons-logging', module: 'commons-logging'
exclude group: "org.springframework.boot", module: "spring-boot-starter-tomcat"
}
configurations.all {
resolutionStrategy {
force(
'commons-io:commons-io:2.19.0',
'io.micrometer:micrometer-core:1.15.5',
'com.google.zxing:core:3.5.4',
'org.commonmark:commonmark:0.27.0',
'org.commonmark:commonmark-ext-gfm-tables:0.27.0'
)
eachDependency { details ->
if (details.requested.group == 'com.google.code.gson' && details.requested.name == 'gson') {
details.useVersion '2.11.0'
}
if (details.requested.group == 'org.apache.commons' && details.requested.name == 'commons-lang3') {
details.useVersion '3.17.0'
}
if (details.requested.group == 'org.slf4j' && details.requested.name == 'slf4j-api') {
details.useVersion '2.0.13'
}
}
}
}
configurations.configureEach {
exclude group: 'commons-logging', module: 'commons-logging'
exclude group: "org.springframework.boot", module: "spring-boot-starter-tomcat"
}
}
tasks.register('writeVersion', WriteProperties) {
destinationFile = layout.projectDirectory.file('app/common/src/main/resources/version.properties')
@@ -135,8 +115,8 @@ subprojects {
implementation 'io.github.pixee:java-security-toolkit:1.2.2'
//tmp for security bumps
implementation 'ch.qos.logback:logback-core:1.5.21'
implementation 'ch.qos.logback:logback-classic:1.5.21'
implementation 'ch.qos.logback:logback-core:1.5.19'
implementation 'ch.qos.logback:logback-classic:1.5.19'
compileOnly "org.projectlombok:lombok:$lombokVersion"
annotationProcessor "org.projectlombok:lombok:$lombokVersion"
@@ -144,7 +124,7 @@ subprojects {
testRuntimeOnly 'org.mockito:mockito-inline:5.2.0'
testRuntimeOnly "org.junit.platform:junit-platform-launcher:$junitPlatformVersion"
testImplementation platform("com.squareup.okhttp3:okhttp-bom:5.3.1")
testImplementation platform("com.squareup.okhttp3:okhttp-bom:5.1.0")
testImplementation "com.squareup.okhttp3:mockwebserver"
}
@@ -240,6 +220,16 @@ gradle.taskGraph.whenReady { graph ->
}
}
def allProjects = ((subprojects as Set<Project>) + project) as Set<Project>
licenseReport {
projects = allProjects
renderers = [new JsonReportRenderer()]
allowedLicensesFile = project.layout.projectDirectory.file("app/allowed-licenses.json").asFile
outputDir = project.layout.buildDirectory.dir("reports/dependency-license").get().asFile.path
configurations = [ "productionRuntimeClasspath", "runtimeClasspath" ]
}
// Configure the forked spring boot run task to properly delegate to the stirling-pdf module
tasks.named('forkedSpringBootRun') {
dependsOn ':stirling-pdf:bootRun'
@@ -263,6 +253,17 @@ spotless {
}
}
sonar {
properties {
property "sonar.projectKey", "Stirling-Tools_Stirling-PDF"
property "sonar.organization", "stirling-tools"
property "sonar.exclusions", "**/build-wrapper-dump.json, **/src/main/java/org/apache/**, **/src/main/resources/static/pdfjs/**, **/src/main/resources/static/pdfjs-legacy/**, **/src/main/resources/static/js/thirdParty/**"
property "sonar.coverage.exclusions", "**/src/main/java/org/apache/**, **/src/main/resources/static/pdfjs/**, **/src/main/resources/static/pdfjs-legacy/**, **/src/main/resources/static/js/thirdParty/**"
property "sonar.cpd.exclusions", "**/src/main/java/org/apache/**, **/src/main/resources/static/pdfjs/**, **/src/main/resources/static/pdfjs-legacy/**, **/src/main/resources/static/js/thirdParty/**"
}
}
swaggerhubUpload {
// dependsOn = generateOpenApiDocs // Depends on your task generating Swagger docs
api = "Stirling-PDF" // The name of your API on SwaggerHub
@@ -283,7 +284,7 @@ dependencies {
testImplementation 'org.springframework.boot:spring-boot-starter-test'
testRuntimeOnly "org.junit.platform:junit-platform-launcher:$junitPlatformVersion"
testImplementation platform("com.squareup.okhttp3:okhttp-bom:5.3.1")
testImplementation platform("com.squareup.okhttp3:okhttp-bom:5.1.0")
testImplementation "com.squareup.okhttp3:mockwebserver"
}
+138
View File
@@ -0,0 +1,138 @@
# Stirling-PDF Dockerfile - Full version with embedded frontend
# Single JAR contains both frontend and backend
# Stage 1: Build application with embedded frontend
FROM gradle:8.14-jdk21 AS build
# Install Node.js and npm for frontend build
RUN apt-get update && apt-get install -y \
curl \
&& curl -fsSL https://deb.nodesource.com/setup_20.x | bash - \
&& apt-get install -y nodejs \
&& npm --version \
&& node --version \
&& apt-get clean \
&& rm -rf /var/lib/apt/lists/*
# Copy gradle files for dependency resolution
COPY build.gradle .
COPY settings.gradle .
COPY gradlew .
COPY gradle gradle/
COPY app/core/build.gradle core/.
COPY app/common/build.gradle common/.
COPY app/proprietary/build.gradle proprietary/.
RUN ./gradlew build -x spotlessApply -x spotlessCheck -x test -x sonarqube || return 0
# Set working directory
WORKDIR /app
# Copy entire project
COPY . .
# Build JAR with embedded frontend (includes security features controlled at runtime)
RUN DISABLE_ADDITIONAL_FEATURES=false \
STIRLING_PDF_DESKTOP_UI=false \
./gradlew clean build -PbuildWithFrontend=true -x spotlessApply -x spotlessCheck -x test -x sonarqube
# Stage 2: Runtime image
FROM alpine:3.22.1
ARG VERSION_TAG
# Labels
LABEL org.opencontainers.image.title="Stirling-PDF"
LABEL org.opencontainers.image.description="Stirling-PDF with embedded frontend - Full version"
LABEL org.opencontainers.image.source="https://github.com/Stirling-Tools/Stirling-PDF"
LABEL org.opencontainers.image.licenses="MIT"
LABEL org.opencontainers.image.vendor="Stirling-Tools"
LABEL org.opencontainers.image.url="https://www.stirlingpdf.com"
LABEL org.opencontainers.image.documentation="https://docs.stirlingpdf.com"
LABEL maintainer="Stirling-Tools"
LABEL org.opencontainers.image.authors="Stirling-Tools"
LABEL org.opencontainers.image.version="${VERSION_TAG}"
LABEL org.opencontainers.image.keywords="PDF, manipulation, API, Spring Boot, React"
# Copy scripts and fonts
COPY scripts /scripts
COPY app/core/src/main/resources/static/fonts/*.ttf /usr/share/fonts/opentype/noto/
# Copy built JAR from build stage
COPY --from=build /app/app/core/build/libs/*.jar /app.jar
COPY --from=build /app/build/libs/restart-helper.jar /restart-helper.jar
# Environment Variables
ENV VERSION_TAG=$VERSION_TAG \
JAVA_BASE_OPTS="-XX:+UnlockExperimentalVMOptions -XX:MaxRAMPercentage=75 -XX:InitiatingHeapOccupancyPercent=20 -XX:+G1PeriodicGCInvokesConcurrent -XX:G1PeriodicGCInterval=10000 -XX:+UseStringDeduplication -XX:G1PeriodicGCSystemLoadThreshold=70" \
JAVA_CUSTOM_OPTS="" \
HOME=/home/stirlingpdfuser \
PUID=1000 \
PGID=1000 \
UMASK=022 \
PYTHONPATH=/usr/lib/libreoffice/program:/opt/venv/lib/python3.12/site-packages \
UNO_PATH=/usr/lib/libreoffice/program \
URE_BOOTSTRAP=file:///usr/lib/libreoffice/program/fundamentalrc \
PATH=$PATH:/opt/venv/bin \
STIRLING_TEMPFILES_DIRECTORY=/tmp/stirling-pdf \
TMPDIR=/tmp/stirling-pdf \
TEMP=/tmp/stirling-pdf \
TMP=/tmp/stirling-pdf
# Install all dependencies
RUN echo "@main https://dl-cdn.alpinelinux.org/alpine/edge/main" | tee -a /etc/apk/repositories && \
echo "@community https://dl-cdn.alpinelinux.org/alpine/edge/community" | tee -a /etc/apk/repositories && \
echo "@testing https://dl-cdn.alpinelinux.org/alpine/edge/testing" | tee -a /etc/apk/repositories && \
apk upgrade --no-cache -a && \
apk add --no-cache \
ca-certificates \
tzdata \
tini \
bash \
curl \
shadow \
su-exec \
openssl \
openssl-dev \
openjdk21-jre \
# Doc conversion
gcompat \
libc6-compat \
libreoffice \
ghostscript \
fontforge \
# pdftohtml
poppler-utils \
# OCR MY PDF
unpaper \
tesseract-ocr-data-eng \
tesseract-ocr-data-chi_sim \
tesseract-ocr-data-deu \
tesseract-ocr-data-fra \
tesseract-ocr-data-por \
ocrmypdf \
# CV
py3-opencv \
python3 \
py3-pip \
py3-pillow@testing \
py3-pdf2image@testing && \
python3 -m venv /opt/venv && \
/opt/venv/bin/pip install --upgrade pip setuptools && \
/opt/venv/bin/pip install --no-cache-dir --upgrade unoserver weasyprint && \
ln -s /usr/lib/libreoffice/program/uno.py /opt/venv/lib/python3.12/site-packages/ && \
ln -s /usr/lib/libreoffice/program/unohelper.py /opt/venv/lib/python3.12/site-packages/ && \
ln -s /usr/lib/libreoffice/program /opt/venv/lib/python3.12/site-packages/LibreOffice && \
mv /usr/share/tessdata /usr/share/tessdata-original && \
mkdir -p $HOME /configs /logs /customFiles /pipeline/watchedFolders /pipeline/finishedFolders /tmp/stirling-pdf && \
fc-cache -f -v && \
chmod +x /scripts/* && \
# User permissions
addgroup -S stirlingpdfgroup && adduser -S stirlingpdfuser -G stirlingpdfgroup && \
chown -R stirlingpdfuser:stirlingpdfgroup $HOME /scripts /pipeline /usr/share/fonts/opentype/noto /configs /customFiles /tmp/stirling-pdf && \
chown stirlingpdfuser:stirlingpdfgroup /app.jar /restart-helper.jar
EXPOSE 8080/tcp
# Set user and run command
ENTRYPOINT ["tini", "--", "/scripts/init.sh"]
CMD ["sh", "-c", "java -Dfile.encoding=UTF-8 -Djava.io.tmpdir=/tmp/stirling-pdf -jar /app.jar & /opt/venv/bin/unoserver --port 2003 --interface 127.0.0.1"]
+142
View File
@@ -0,0 +1,142 @@
# Stirling-PDF Dockerfile - Fat version with embedded frontend
# Single JAR contains both frontend and backend with extra fonts for air-gapped environments
# Stage 1: Build application with embedded frontend
FROM gradle:8.14-jdk21 AS build
# Install Node.js and npm for frontend build
RUN apt-get update && apt-get install -y \
curl \
&& curl -fsSL https://deb.nodesource.com/setup_20.x | bash - \
&& apt-get install -y nodejs \
&& npm --version \
&& node --version \
&& apt-get clean \
&& rm -rf /var/lib/apt/lists/*
# Copy gradle files for dependency resolution
COPY build.gradle .
COPY settings.gradle .
COPY gradlew .
COPY gradle gradle/
COPY app/core/build.gradle core/.
COPY app/common/build.gradle common/.
COPY app/proprietary/build.gradle proprietary/.
RUN ./gradlew build -x spotlessApply -x spotlessCheck -x test -x sonarqube || return 0
# Set working directory
WORKDIR /app
# Copy entire project
COPY . .
# Build JAR with embedded frontend (includes security features controlled at runtime)
RUN DISABLE_ADDITIONAL_FEATURES=false \
STIRLING_PDF_DESKTOP_UI=false \
./gradlew clean build -PbuildWithFrontend=true -x spotlessApply -x spotlessCheck -x test -x sonarqube
# Stage 2: Runtime image
FROM alpine:3.22.1
ARG VERSION_TAG
# Labels
LABEL org.opencontainers.image.title="Stirling-PDF Fat"
LABEL org.opencontainers.image.description="Stirling-PDF with embedded frontend - Fat version with extra fonts for air-gapped environments"
LABEL org.opencontainers.image.source="https://github.com/Stirling-Tools/Stirling-PDF"
LABEL org.opencontainers.image.licenses="MIT"
LABEL org.opencontainers.image.vendor="Stirling-Tools"
LABEL org.opencontainers.image.url="https://www.stirlingpdf.com"
LABEL org.opencontainers.image.documentation="https://docs.stirlingpdf.com"
LABEL maintainer="Stirling-Tools"
LABEL org.opencontainers.image.authors="Stirling-Tools"
LABEL org.opencontainers.image.version="${VERSION_TAG}"
LABEL org.opencontainers.image.keywords="PDF, manipulation, fat, air-gapped, API, Spring Boot, React"
# Copy scripts and fonts
COPY scripts /scripts
COPY app/core/src/main/resources/static/fonts/*.ttf /usr/share/fonts/opentype/noto/
# Copy built JAR from build stage
COPY --from=build /app/app/core/build/libs/*.jar /app.jar
COPY --from=build /app/build/libs/restart-helper.jar /restart-helper.jar
# Environment Variables
ENV VERSION_TAG=$VERSION_TAG \
JAVA_BASE_OPTS="-XX:+UnlockExperimentalVMOptions -XX:MaxRAMPercentage=75 -XX:InitiatingHeapOccupancyPercent=20 -XX:+G1PeriodicGCInvokesConcurrent -XX:G1PeriodicGCInterval=10000 -XX:+UseStringDeduplication -XX:G1PeriodicGCSystemLoadThreshold=70" \
JAVA_CUSTOM_OPTS="" \
HOME=/home/stirlingpdfuser \
PUID=1000 \
PGID=1000 \
UMASK=022 \
FAT_DOCKER=true \
INSTALL_BOOK_AND_ADVANCED_HTML_OPS=false \
PYTHONPATH=/usr/lib/libreoffice/program:/opt/venv/lib/python3.12/site-packages \
UNO_PATH=/usr/lib/libreoffice/program \
URE_BOOTSTRAP=file:///usr/lib/libreoffice/program/fundamentalrc \
PATH=$PATH:/opt/venv/bin \
STIRLING_TEMPFILES_DIRECTORY=/tmp/stirling-pdf \
TMPDIR=/tmp/stirling-pdf \
TEMP=/tmp/stirling-pdf \
TMP=/tmp/stirling-pdf
# Install all dependencies plus extra fonts for air-gapped environments
RUN echo "@main https://dl-cdn.alpinelinux.org/alpine/edge/main" | tee -a /etc/apk/repositories && \
echo "@community https://dl-cdn.alpinelinux.org/alpine/edge/community" | tee -a /etc/apk/repositories && \
echo "@testing https://dl-cdn.alpinelinux.org/alpine/edge/testing" | tee -a /etc/apk/repositories && \
apk upgrade --no-cache -a && \
apk add --no-cache \
ca-certificates \
tzdata \
tini \
bash \
curl \
shadow \
su-exec \
openssl \
openssl-dev \
openjdk21-jre \
# Doc conversion
gcompat \
libc6-compat \
libreoffice \
ghostscript \
fontforge \
# pdftohtml
poppler-utils \
# OCR MY PDF
unpaper \
tesseract-ocr-data-eng \
tesseract-ocr-data-chi_sim \
tesseract-ocr-data-deu \
tesseract-ocr-data-fra \
tesseract-ocr-data-por \
ocrmypdf \
# Extra fonts for fat version
font-terminus font-dejavu font-noto font-noto-cjk font-awesome font-noto-extra font-liberation font-linux-libertine \
# CV
py3-opencv \
python3 \
py3-pip \
py3-pillow@testing \
py3-pdf2image@testing && \
python3 -m venv /opt/venv && \
/opt/venv/bin/pip install --upgrade pip setuptools && \
/opt/venv/bin/pip install --no-cache-dir --upgrade unoserver weasyprint && \
ln -s /usr/lib/libreoffice/program/uno.py /opt/venv/lib/python3.12/site-packages/ && \
ln -s /usr/lib/libreoffice/program/unohelper.py /opt/venv/lib/python3.12/site-packages/ && \
ln -s /usr/lib/libreoffice/program /opt/venv/lib/python3.12/site-packages/LibreOffice && \
mv /usr/share/tessdata /usr/share/tessdata-original && \
mkdir -p $HOME /configs /logs /customFiles /pipeline/watchedFolders /pipeline/finishedFolders /tmp/stirling-pdf && \
fc-cache -f -v && \
chmod +x /scripts/* && \
# User permissions
addgroup -S stirlingpdfgroup && adduser -S stirlingpdfuser -G stirlingpdfgroup && \
chown -R stirlingpdfuser:stirlingpdfgroup $HOME /scripts /pipeline /usr/share/fonts/opentype/noto /configs /customFiles /tmp/stirling-pdf && \
chown stirlingpdfuser:stirlingpdfgroup /app.jar /restart-helper.jar
EXPOSE 8080/tcp
# Set user and run command
ENTRYPOINT ["tini", "--", "/scripts/init.sh"]
CMD ["sh", "-c", "java -Dfile.encoding=UTF-8 -Djava.io.tmpdir=/tmp/stirling-pdf -jar /app.jar & /opt/venv/bin/unoserver --port 2003 --interface 127.0.0.1"]
+104
View File
@@ -0,0 +1,104 @@
# Stirling-PDF Dockerfile - Ultra-lite version with embedded frontend
# Single JAR contains both frontend and backend with minimal dependencies
# Stage 1: Build application with embedded frontend
FROM gradle:8.14-jdk21 AS build
# Install Node.js and npm for frontend build
RUN apt-get update && apt-get install -y \
curl \
&& curl -fsSL https://deb.nodesource.com/setup_20.x | bash - \
&& apt-get install -y nodejs \
&& npm --version \
&& node --version \
&& apt-get clean \
&& rm -rf /var/lib/apt/lists/*
# Copy gradle files for dependency resolution
COPY build.gradle .
COPY settings.gradle .
COPY gradlew .
COPY gradle gradle/
COPY app/core/build.gradle core/.
COPY app/common/build.gradle common/.
COPY app/proprietary/build.gradle proprietary/.
RUN ./gradlew build -x spotlessApply -x spotlessCheck -x test -x sonarqube || return 0
# Set working directory
WORKDIR /app
# Copy entire project
COPY . .
# Build ultra-lite JAR with embedded frontend (minimal features)
RUN DISABLE_ADDITIONAL_FEATURES=true \
STIRLING_PDF_DESKTOP_UI=false \
./gradlew clean build -PbuildWithFrontend=true -x spotlessApply -x spotlessCheck -x test -x sonarqube
# Stage 2: Runtime image
FROM alpine:3.22.1
ARG VERSION_TAG
# Labels
LABEL org.opencontainers.image.title="Stirling-PDF Ultra-Lite"
LABEL org.opencontainers.image.description="Stirling-PDF with embedded frontend - Ultra-lite version with minimal dependencies"
LABEL org.opencontainers.image.source="https://github.com/Stirling-Tools/Stirling-PDF"
LABEL org.opencontainers.image.licenses="MIT"
LABEL org.opencontainers.image.vendor="Stirling-Tools"
LABEL org.opencontainers.image.url="https://www.stirlingpdf.com"
LABEL org.opencontainers.image.documentation="https://docs.stirlingpdf.com"
LABEL maintainer="Stirling-Tools"
LABEL org.opencontainers.image.authors="Stirling-Tools"
LABEL org.opencontainers.image.version="${VERSION_TAG}"
LABEL org.opencontainers.image.keywords="PDF, manipulation, ultra-lite, API, Spring Boot, React"
# Copy scripts
COPY scripts/init-without-ocr.sh /scripts/init-without-ocr.sh
COPY scripts/installFonts.sh /scripts/installFonts.sh
# Copy built JAR from build stage
COPY --from=build /app/app/core/build/libs/*.jar /app.jar
COPY --from=build /app/build/libs/restart-helper.jar /restart-helper.jar
# Environment Variables
ENV VERSION_TAG=$VERSION_TAG \
JAVA_BASE_OPTS="-XX:+UnlockExperimentalVMOptions -XX:MaxRAMPercentage=75 -XX:InitiatingHeapOccupancyPercent=20 -XX:+G1PeriodicGCInvokesConcurrent -XX:G1PeriodicGCInterval=10000 -XX:+UseStringDeduplication -XX:G1PeriodicGCSystemLoadThreshold=70" \
JAVA_CUSTOM_OPTS="" \
HOME=/home/stirlingpdfuser \
PUID=1000 \
PGID=1000 \
UMASK=022 \
STIRLING_TEMPFILES_DIRECTORY=/tmp/stirling-pdf \
TMPDIR=/tmp/stirling-pdf \
TEMP=/tmp/stirling-pdf \
TMP=/tmp/stirling-pdf \
ENDPOINTS_GROUPS_TO_REMOVE=CLI
# Install minimal dependencies
RUN echo "@main https://dl-cdn.alpinelinux.org/alpine/edge/main" | tee -a /etc/apk/repositories && \
echo "@community https://dl-cdn.alpinelinux.org/alpine/edge/community" | tee -a /etc/apk/repositories && \
echo "@testing https://dl-cdn.alpinelinux.org/alpine/edge/testing" | tee -a /etc/apk/repositories && \
apk upgrade --no-cache -a && \
apk add --no-cache \
ca-certificates \
tzdata \
tini \
bash \
curl \
shadow \
su-exec \
openjdk21-jre && \
mkdir -p $HOME /configs /logs /customFiles /pipeline/watchedFolders /pipeline/finishedFolders /tmp/stirling-pdf && \
mkdir -p /usr/share/fonts/opentype/noto && \
chmod +x /scripts/*.sh && \
# User permissions
addgroup -S stirlingpdfgroup && adduser -S stirlingpdfuser -G stirlingpdfgroup && \
chown -R stirlingpdfuser:stirlingpdfgroup $HOME /scripts /configs /customFiles /pipeline /tmp/stirling-pdf && \
chown stirlingpdfuser:stirlingpdfgroup /app.jar /restart-helper.jar
EXPOSE 8080/tcp
# Set user and run command
ENTRYPOINT ["tini", "--", "/scripts/init-without-ocr.sh"]
CMD ["java", "-Dfile.encoding=UTF-8", "-Djava.io.tmpdir=/tmp/stirling-pdf", "-jar", "/app.jar"]
-7
View File
@@ -1,7 +0,0 @@
# Shared Signing User Stories
- **As a document owner,** I can start a shared signing session by uploading a PDF, listing participant emails (with optional display names), adding a message or due date, and choosing whether to notify everyone immediately so that the collaboration is organized from the outset.
- **As a document owner,** I can retrieve a session to review its participants, share tokens, and current statuses so that I know who has been invited and who has responded.
- **As a document owner,** I can send reminder notifications to all participants or a selected subset with a custom message so that pending signers get nudged to complete their part.
- **As a participant,** I can attach my certificate materials (PEM key + certificate, PKCS#12/PFX, JKS, or the server certificate) along with signature placement details (page number, display name, reason, location, and logo/signature visibility) so that my signature is applied with the right credentials and appearance.
- **As a document owner,** I can finalize the session to apply every collected signature sequentially and download the fully signed PDF so that the collaboration produces a single completed document.
+4 -4
View File
@@ -3,21 +3,21 @@
<head>
<meta charset="UTF-8" />
<base href="%BASE_URL%" />
<link rel="icon" href="/modern-logo/favicon.ico" />
<link rel="icon" href="modern-logo/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="theme-color" content="#000000" />
<meta
name="description"
content="The Free Adobe Acrobat alternative (10M+ Downloads)"
/>
<link rel="apple-touch-icon" href="/modern-logo/logo192.png" />
<link rel="manifest" href="/manifest.json" />
<link rel="apple-touch-icon" href="modern-logo/logo192.png" />
<link rel="manifest" href="manifest.json" />
<title>Stirling PDF</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
<script type="module" src="/src/index.tsx"></script>
<script type="module" src="src/index.tsx"></script>
</body>
</html>
+176 -183
View File
@@ -11,25 +11,26 @@
"dependencies": {
"@atlaskit/pragmatic-drag-and-drop": "^1.7.7",
"@dnd-kit/core": "^6.3.1",
"@embedpdf/core": "^1.4.1",
"@embedpdf/engines": "^1.4.1",
"@embedpdf/plugin-annotation": "^1.4.1",
"@embedpdf/plugin-bookmark": "^1.4.1",
"@embedpdf/plugin-export": "^1.4.1",
"@embedpdf/plugin-history": "^1.4.1",
"@embedpdf/plugin-interaction-manager": "^1.4.1",
"@embedpdf/plugin-loader": "^1.4.1",
"@embedpdf/plugin-pan": "^1.4.1",
"@embedpdf/plugin-render": "^1.4.1",
"@embedpdf/plugin-rotate": "^1.4.1",
"@embedpdf/plugin-scroll": "^1.4.1",
"@embedpdf/plugin-search": "^1.4.1",
"@embedpdf/plugin-selection": "^1.4.1",
"@embedpdf/plugin-spread": "^1.4.1",
"@embedpdf/plugin-thumbnail": "^1.4.1",
"@embedpdf/plugin-tiling": "^1.4.1",
"@embedpdf/plugin-viewport": "^1.4.1",
"@embedpdf/plugin-zoom": "^1.4.1",
"@embedpdf/core": "^1.5.0",
"@embedpdf/engines": "^1.5.0",
"@embedpdf/plugin-annotation": "^1.5.0",
"@embedpdf/plugin-bookmark": "^1.5.0",
"@embedpdf/plugin-export": "^1.5.0",
"@embedpdf/plugin-history": "^1.5.0",
"@embedpdf/plugin-interaction-manager": "^1.5.0",
"@embedpdf/plugin-loader": "^1.5.0",
"@embedpdf/plugin-pan": "^1.5.0",
"@embedpdf/plugin-print": "^1.5.0",
"@embedpdf/plugin-render": "^1.5.0",
"@embedpdf/plugin-rotate": "^1.5.0",
"@embedpdf/plugin-scroll": "^1.5.0",
"@embedpdf/plugin-search": "^1.5.0",
"@embedpdf/plugin-selection": "^1.5.0",
"@embedpdf/plugin-spread": "^1.5.0",
"@embedpdf/plugin-thumbnail": "^1.5.0",
"@embedpdf/plugin-tiling": "^1.5.0",
"@embedpdf/plugin-viewport": "^1.5.0",
"@embedpdf/plugin-zoom": "^1.5.0",
"@emotion/react": "^11.14.0",
"@emotion/styled": "^11.14.1",
"@iconify/react": "^6.0.2",
@@ -455,7 +456,6 @@
}
],
"license": "MIT",
"peer": true,
"engines": {
"node": ">=18"
},
@@ -499,7 +499,6 @@
}
],
"license": "MIT",
"peer": true,
"engines": {
"node": ">=18"
}
@@ -576,14 +575,13 @@
"license": "0BSD"
},
"node_modules/@embedpdf/core": {
"version": "1.4.1",
"resolved": "https://registry.npmjs.org/@embedpdf/core/-/core-1.4.1.tgz",
"integrity": "sha512-TGpxn2CvAKRnOJWJ3bsK+dKBiCp75ehxftRUmv7wAmPomhnG5XrDfoWJungvO+zbbqAwso6PocdeXINVt3hlAw==",
"version": "1.5.0",
"resolved": "https://registry.npmjs.org/@embedpdf/core/-/core-1.5.0.tgz",
"integrity": "sha512-Yrh9XoVaT8cUgzgqpJ7hx5wg6BqQrCFirqqlSwVb+Ly9oNn4fZbR9GycIWmzJOU5XBnaOJjXfQSaDyoNP0woNA==",
"license": "MIT",
"peer": true,
"dependencies": {
"@embedpdf/engines": "1.4.1",
"@embedpdf/models": "1.4.1"
"@embedpdf/engines": "1.5.0",
"@embedpdf/models": "1.5.0"
},
"peerDependencies": {
"preact": "^10.26.4",
@@ -594,13 +592,13 @@
}
},
"node_modules/@embedpdf/engines": {
"version": "1.4.1",
"resolved": "https://registry.npmjs.org/@embedpdf/engines/-/engines-1.4.1.tgz",
"integrity": "sha512-yugIb5OwTI/1VnAaEvSYxAd2DvYBPkV/D7wytagyaOq98o3sqzcY2Q9zHt+LhnawA5KKG1e/FDPjCd4qm8gsvg==",
"version": "1.5.0",
"resolved": "https://registry.npmjs.org/@embedpdf/engines/-/engines-1.5.0.tgz",
"integrity": "sha512-/GzhjHFHWfOaX7vjgFJX/pyq668wYjoda1bZ9MpwF/EF000Wwy2Q0AOhprjldPFz8ASKjwKwqsXmaqrK99yOAQ==",
"license": "MIT",
"dependencies": {
"@embedpdf/models": "1.4.1",
"@embedpdf/pdfium": "1.4.1"
"@embedpdf/models": "1.5.0",
"@embedpdf/pdfium": "1.5.0"
},
"peerDependencies": {
"preact": "^10.26.4",
@@ -611,31 +609,31 @@
}
},
"node_modules/@embedpdf/models": {
"version": "1.4.1",
"resolved": "https://registry.npmjs.org/@embedpdf/models/-/models-1.4.1.tgz",
"integrity": "sha512-2nTg8Q1qpplBvspZJXMCZOA+/OILpfdNRPddlplxZXY/Upx0rzKXx/e6pXWW7AuOgtfGneT4h9tMs3A595/PdQ==",
"version": "1.5.0",
"resolved": "https://registry.npmjs.org/@embedpdf/models/-/models-1.5.0.tgz",
"integrity": "sha512-x/1li3jdag+IzfZkcfRLKLqASLep4v6dgVi3z0JArwaicFra8k1IY2xaVTrwcZyx7pRb/rxvoO9yLHW0Y34NFw==",
"license": "MIT"
},
"node_modules/@embedpdf/pdfium": {
"version": "1.4.1",
"resolved": "https://registry.npmjs.org/@embedpdf/pdfium/-/pdfium-1.4.1.tgz",
"integrity": "sha512-BekKEK4UNCwzj7xOffKn6WpL0FQHxq+mTj2iGI3N7OwAX2J/BO2G+rDOB+lvojQG+Dkpg8uqm427ZKJDRyLgVQ==",
"version": "1.5.0",
"resolved": "https://registry.npmjs.org/@embedpdf/pdfium/-/pdfium-1.5.0.tgz",
"integrity": "sha512-PI32t2U4ThZC907n2Iwr8E5WqmC574G83u3V9ysNFl29N9kasrY9RiLSzU4W/yQvXPjIbpQHBsbMKXLjCFBI9w==",
"license": "MIT"
},
"node_modules/@embedpdf/plugin-annotation": {
"version": "1.4.1",
"resolved": "https://registry.npmjs.org/@embedpdf/plugin-annotation/-/plugin-annotation-1.4.1.tgz",
"integrity": "sha512-d4HibNy6ecyDqx2Y2R8VjaqppSdjNofAJmU6VenOd88wn080sAUqvnkeVJ6ehJH5BoND4ymQrcAkcbVeYK0myA==",
"version": "1.5.0",
"resolved": "https://registry.npmjs.org/@embedpdf/plugin-annotation/-/plugin-annotation-1.5.0.tgz",
"integrity": "sha512-mxEPI6xYwOGaf9fYfoywuj6nwA10eHFPBuN066MzwphDk6DOHJGZ3Vq8zNQBXh20c/Lb25PL718D7MZWxZLUHg==",
"license": "MIT",
"dependencies": {
"@embedpdf/models": "1.4.1",
"@embedpdf/utils": "1.4.1"
"@embedpdf/models": "1.5.0",
"@embedpdf/utils": "1.5.0"
},
"peerDependencies": {
"@embedpdf/core": "1.4.1",
"@embedpdf/plugin-history": "1.4.1",
"@embedpdf/plugin-interaction-manager": "1.4.1",
"@embedpdf/plugin-selection": "1.4.1",
"@embedpdf/core": "1.5.0",
"@embedpdf/plugin-history": "1.5.0",
"@embedpdf/plugin-interaction-manager": "1.5.0",
"@embedpdf/plugin-selection": "1.5.0",
"preact": "^10.26.4",
"react": ">=16.8.0",
"react-dom": ">=16.8.0",
@@ -643,15 +641,15 @@
}
},
"node_modules/@embedpdf/plugin-bookmark": {
"version": "1.4.1",
"resolved": "https://registry.npmjs.org/@embedpdf/plugin-bookmark/-/plugin-bookmark-1.4.1.tgz",
"integrity": "sha512-WnfBJdv+Eq5zsMfwDZ5RlXZMGpvKm/ccL6jlTVwtELBhu3wvhjjbBmZdheEOzHMC3VXMNYDMjCeaXkUG4nWoDA==",
"version": "1.5.0",
"resolved": "https://registry.npmjs.org/@embedpdf/plugin-bookmark/-/plugin-bookmark-1.5.0.tgz",
"integrity": "sha512-s3C9PtVesy5X8Ds/C9TEElFiqfKGRklG/uNPTROpNoolfpi0h7qX2xqqh/9+FzKH2nHjVcPB7Pp432v16h7eRA==",
"license": "MIT",
"dependencies": {
"@embedpdf/models": "1.4.1"
"@embedpdf/models": "1.5.0"
},
"peerDependencies": {
"@embedpdf/core": "1.4.1",
"@embedpdf/core": "1.5.0",
"preact": "^10.26.4",
"react": ">=16.8.0",
"react-dom": ">=16.8.0",
@@ -659,15 +657,15 @@
}
},
"node_modules/@embedpdf/plugin-export": {
"version": "1.4.1",
"resolved": "https://registry.npmjs.org/@embedpdf/plugin-export/-/plugin-export-1.4.1.tgz",
"integrity": "sha512-g89fREFM/zkt2Ai2Q5dWwDkhXgC/JmVyUniaMgm1fTG/MZ0Z05E7f34DUzX/CKcJyVjxEgl6tojBTMeUbm15bA==",
"version": "1.5.0",
"resolved": "https://registry.npmjs.org/@embedpdf/plugin-export/-/plugin-export-1.5.0.tgz",
"integrity": "sha512-luk68mNW9l2X31qk4b02phKaqDl9aDXUAgHVz1EWrgwXQ3Oz9WEdu60utYARYDiepDo3Caadll8RwctYSf/anA==",
"license": "MIT",
"dependencies": {
"@embedpdf/models": "1.4.1"
"@embedpdf/models": "1.5.0"
},
"peerDependencies": {
"@embedpdf/core": "1.4.1",
"@embedpdf/core": "1.5.0",
"preact": "^10.26.4",
"react": ">=16.8.0",
"react-dom": ">=16.8.0",
@@ -676,16 +674,15 @@
}
},
"node_modules/@embedpdf/plugin-history": {
"version": "1.4.1",
"resolved": "https://registry.npmjs.org/@embedpdf/plugin-history/-/plugin-history-1.4.1.tgz",
"integrity": "sha512-5WLDiNMH6tACkLGGv/lJtNsDeozOhSbrh0mjD1btHun8u7Yscu/Vf8tdJRUOsd+nULivo2nQ2NFNKu0OTbVo8w==",
"version": "1.5.0",
"resolved": "https://registry.npmjs.org/@embedpdf/plugin-history/-/plugin-history-1.5.0.tgz",
"integrity": "sha512-p7PTNNaIr4gH3jLwX+eLJe1DeUXgi21kVGN6SRx/pocH8esg4jqoOeD/YiRRZoZnPOiy0jBXVhkPkwSmY7a2hQ==",
"license": "MIT",
"peer": true,
"dependencies": {
"@embedpdf/models": "1.4.1"
"@embedpdf/models": "1.5.0"
},
"peerDependencies": {
"@embedpdf/core": "1.4.1",
"@embedpdf/core": "1.5.0",
"preact": "^10.26.4",
"react": ">=16.8.0",
"react-dom": ">=16.8.0",
@@ -693,16 +690,15 @@
}
},
"node_modules/@embedpdf/plugin-interaction-manager": {
"version": "1.4.1",
"resolved": "https://registry.npmjs.org/@embedpdf/plugin-interaction-manager/-/plugin-interaction-manager-1.4.1.tgz",
"integrity": "sha512-Ng02S9SFIAi9JZS5rI+NXSnZZ1Yk9YYRw4MlN2pig49qOyivZdz0oScZaYxQPewo8ccJkLeghjdeWswOBW/6cA==",
"version": "1.5.0",
"resolved": "https://registry.npmjs.org/@embedpdf/plugin-interaction-manager/-/plugin-interaction-manager-1.5.0.tgz",
"integrity": "sha512-ckHgTfvkW6c5Ta7Mc+Dl9C2foVnvEpqEJ84wyBnqrU0OWbe/jsiPhyKBVeartMGqNI/kVfaQTXupyrKhekAVmg==",
"license": "MIT",
"peer": true,
"dependencies": {
"@embedpdf/models": "1.4.1"
"@embedpdf/models": "1.5.0"
},
"peerDependencies": {
"@embedpdf/core": "1.4.1",
"@embedpdf/core": "1.5.0",
"preact": "^10.26.4",
"react": ">=16.8.0",
"react-dom": ">=16.8.0",
@@ -711,16 +707,15 @@
}
},
"node_modules/@embedpdf/plugin-loader": {
"version": "1.4.1",
"resolved": "https://registry.npmjs.org/@embedpdf/plugin-loader/-/plugin-loader-1.4.1.tgz",
"integrity": "sha512-m3ZOk8JygsLxoa4cZ+0BVB5pfRWuBCg2/gPqjhoFZNKTqAFw4J6HGUrhYKg94GRYe+w1cTJl/NbTBYuU5DOrsA==",
"version": "1.5.0",
"resolved": "https://registry.npmjs.org/@embedpdf/plugin-loader/-/plugin-loader-1.5.0.tgz",
"integrity": "sha512-P4YpIZfaW69etYIjphyaL4cGl2pB14h3OdTE0tRQ2pZYZHFLTvlt4q9B3PVSdhlSrHK5nob7jfLGon2U7xCslg==",
"license": "MIT",
"peer": true,
"dependencies": {
"@embedpdf/models": "1.4.1"
"@embedpdf/models": "1.5.0"
},
"peerDependencies": {
"@embedpdf/core": "1.4.1",
"@embedpdf/core": "1.5.0",
"preact": "^10.26.4",
"react": ">=16.8.0",
"react-dom": ">=16.8.0",
@@ -729,17 +724,17 @@
}
},
"node_modules/@embedpdf/plugin-pan": {
"version": "1.4.1",
"resolved": "https://registry.npmjs.org/@embedpdf/plugin-pan/-/plugin-pan-1.4.1.tgz",
"integrity": "sha512-zmOZJ9dUqXiaV0F5GPf/5WTWf3jAEkiv153Tl3x8HT9Rfff+WQhV48NruCIBAy/T4jVt4aH7D1zt/B/ftvcdkA==",
"version": "1.5.0",
"resolved": "https://registry.npmjs.org/@embedpdf/plugin-pan/-/plugin-pan-1.5.0.tgz",
"integrity": "sha512-EMQ08dHqLkZmFVuLOO6h3AAinFPQoA1r6OlL9z+p0sswq31JAgd4X7+xjYIpI01z/V3+cTzPHzp7qwob5E4tbA==",
"license": "MIT",
"dependencies": {
"@embedpdf/models": "1.4.1"
"@embedpdf/models": "1.5.0"
},
"peerDependencies": {
"@embedpdf/core": "1.4.1",
"@embedpdf/plugin-interaction-manager": "1.4.1",
"@embedpdf/plugin-viewport": "1.4.1",
"@embedpdf/core": "1.5.0",
"@embedpdf/plugin-interaction-manager": "1.5.0",
"@embedpdf/plugin-viewport": "1.5.0",
"preact": "^10.26.4",
"react": ">=16.8.0",
"react-dom": ">=16.8.0",
@@ -747,17 +742,33 @@
"vue": ">=3.2.0"
}
},
"node_modules/@embedpdf/plugin-render": {
"version": "1.4.1",
"resolved": "https://registry.npmjs.org/@embedpdf/plugin-render/-/plugin-render-1.4.1.tgz",
"integrity": "sha512-gKCdNKw6WBHBEpTc2DLBWIWOxzsNnaNbpfeY6C4f2Bum0EO+XW3Hl2oIx1uaRHjIhhnXso1J3QweqelsPwDGwg==",
"node_modules/@embedpdf/plugin-print": {
"version": "1.5.0",
"resolved": "https://registry.npmjs.org/@embedpdf/plugin-print/-/plugin-print-1.5.0.tgz",
"integrity": "sha512-rjorvNxAZfO9X4cFZVU9fHnldMWqMceJGmr3mH+yj7KdHePvNDDP+omyZyZKtxlUZENaeDI2h6k5z0GbhBz6sQ==",
"license": "MIT",
"peer": true,
"dependencies": {
"@embedpdf/models": "1.4.1"
"@embedpdf/models": "1.5.0"
},
"peerDependencies": {
"@embedpdf/core": "1.4.1",
"@embedpdf/core": "1.5.0",
"preact": "^10.26.4",
"react": ">=18.0.0",
"react-dom": ">=18.0.0",
"svelte": ">=5 <6",
"vue": ">=3.2.0"
}
},
"node_modules/@embedpdf/plugin-render": {
"version": "1.5.0",
"resolved": "https://registry.npmjs.org/@embedpdf/plugin-render/-/plugin-render-1.5.0.tgz",
"integrity": "sha512-ywwSj0ByrlkvrJIHKRzqxARkOZriki8VJUC+T4MV8fGyF4CzvCRJyKlPktahFz+VxhoodqTh7lBCib68dH+GvA==",
"license": "MIT",
"dependencies": {
"@embedpdf/models": "1.5.0"
},
"peerDependencies": {
"@embedpdf/core": "1.5.0",
"preact": "^10.26.4",
"react": ">=16.8.0",
"react-dom": ">=16.8.0",
@@ -766,15 +777,15 @@
}
},
"node_modules/@embedpdf/plugin-rotate": {
"version": "1.4.1",
"resolved": "https://registry.npmjs.org/@embedpdf/plugin-rotate/-/plugin-rotate-1.4.1.tgz",
"integrity": "sha512-hVzHkKwMNH3tUhxqJGsj5qTLpYZXbj6E74AEcG0w/fz5FrK7EnofPqt0gRfYmIzxnQGIh+39BRtcp8gmx8UNnw==",
"version": "1.5.0",
"resolved": "https://registry.npmjs.org/@embedpdf/plugin-rotate/-/plugin-rotate-1.5.0.tgz",
"integrity": "sha512-5EmBCsq0VfrE3xWY6ofuVm8S6aK95EbAycRIk1wczcmTdvpsuXZ6P2ZaECUgYMcpZ6uAg4/kGf8X8VVZuCihSQ==",
"license": "MIT",
"dependencies": {
"@embedpdf/models": "1.4.1"
"@embedpdf/models": "1.5.0"
},
"peerDependencies": {
"@embedpdf/core": "1.4.1",
"@embedpdf/core": "1.5.0",
"preact": "^10.26.4",
"react": ">=16.8.0",
"react-dom": ">=16.8.0",
@@ -783,17 +794,16 @@
}
},
"node_modules/@embedpdf/plugin-scroll": {
"version": "1.4.1",
"resolved": "https://registry.npmjs.org/@embedpdf/plugin-scroll/-/plugin-scroll-1.4.1.tgz",
"integrity": "sha512-Y9O+matB4j4fLim5s/jn7qIi+lMC9vmDJRpJhiWe8bvD9oYLP2xfD/DdhFgAjRKcNhPoxC+j8q8QN5BMeGAv2Q==",
"version": "1.5.0",
"resolved": "https://registry.npmjs.org/@embedpdf/plugin-scroll/-/plugin-scroll-1.5.0.tgz",
"integrity": "sha512-RNmTZCZ8X1mA8cw9M7TMDuhO9GtkOalGha2bBL3En3D1IlDRS7PzNNMSMV7eqT7OQICSTltlpJ8p8Qi5esvL/Q==",
"license": "MIT",
"peer": true,
"dependencies": {
"@embedpdf/models": "1.4.1"
"@embedpdf/models": "1.5.0"
},
"peerDependencies": {
"@embedpdf/core": "1.4.1",
"@embedpdf/plugin-viewport": "1.4.1",
"@embedpdf/core": "1.5.0",
"@embedpdf/plugin-viewport": "1.5.0",
"preact": "^10.26.4",
"react": ">=16.8.0",
"react-dom": ">=16.8.0",
@@ -802,16 +812,16 @@
}
},
"node_modules/@embedpdf/plugin-search": {
"version": "1.4.1",
"resolved": "https://registry.npmjs.org/@embedpdf/plugin-search/-/plugin-search-1.4.1.tgz",
"integrity": "sha512-8JG4CbOcUsLuT0vHJJ4cECmu+Yn53EokWFUVXi2Mo/XvHjhrQuWmD7+y6s/qQPEpctFYWmUCXTDAX9ynPud+2Q==",
"version": "1.5.0",
"resolved": "https://registry.npmjs.org/@embedpdf/plugin-search/-/plugin-search-1.5.0.tgz",
"integrity": "sha512-TB5b0H8Iobx/azVUBIlG2ClaKtf0y3/Xi3E/iB8BwvkIE2+g6EGfp8IMXIn8WDXST6bbvJEP31Ab0Ilp6SVkiw==",
"license": "MIT",
"dependencies": {
"@embedpdf/models": "1.4.1"
"@embedpdf/models": "1.5.0"
},
"peerDependencies": {
"@embedpdf/core": "1.4.1",
"@embedpdf/plugin-loader": "1.4.1",
"@embedpdf/core": "1.5.0",
"@embedpdf/plugin-loader": "1.5.0",
"preact": "^10.26.4",
"react": ">=16.8.0",
"react-dom": ">=16.8.0",
@@ -820,18 +830,17 @@
}
},
"node_modules/@embedpdf/plugin-selection": {
"version": "1.4.1",
"resolved": "https://registry.npmjs.org/@embedpdf/plugin-selection/-/plugin-selection-1.4.1.tgz",
"integrity": "sha512-lo5Ytk1PH0PrRKv6zKVupm4t02VGsqIrnSIeP6NO8Ujx0wfqEhj//sqIuO/EwfFVJD8lcQIP9UUo9y8baCrEog==",
"version": "1.5.0",
"resolved": "https://registry.npmjs.org/@embedpdf/plugin-selection/-/plugin-selection-1.5.0.tgz",
"integrity": "sha512-zrxLBAZQoPswDuf9q9DrYaQc6B0Ysc2U1hueTjNH/4+ydfl0BFXZkKR63C2e3YmWtXvKjkoIj0GyPzsiBORLUw==",
"license": "MIT",
"peer": true,
"dependencies": {
"@embedpdf/models": "1.4.1"
"@embedpdf/models": "1.5.0"
},
"peerDependencies": {
"@embedpdf/core": "1.4.1",
"@embedpdf/plugin-interaction-manager": "1.4.1",
"@embedpdf/plugin-viewport": "1.4.1",
"@embedpdf/core": "1.5.0",
"@embedpdf/plugin-interaction-manager": "1.5.0",
"@embedpdf/plugin-viewport": "1.5.0",
"preact": "^10.26.4",
"react": ">=16.8.0",
"react-dom": ">=16.8.0",
@@ -840,16 +849,16 @@
}
},
"node_modules/@embedpdf/plugin-spread": {
"version": "1.4.1",
"resolved": "https://registry.npmjs.org/@embedpdf/plugin-spread/-/plugin-spread-1.4.1.tgz",
"integrity": "sha512-l+SrDVGTiiItkt2cEtzv7V/X5HhmLbYHcQ8CFobGeIKdJtzKS1Nu/JSKqg7Ki7eCNgyPL1yMNfNE92bNKYVN4w==",
"version": "1.5.0",
"resolved": "https://registry.npmjs.org/@embedpdf/plugin-spread/-/plugin-spread-1.5.0.tgz",
"integrity": "sha512-3EU5Cp+fPQSiMjvMR/P2kXxXry/RlnxHLs4JeskAaH95QcqWW3VD+DrHkWSiLFkdhI18rNNGNlMc5RvDGvbXGQ==",
"license": "MIT",
"dependencies": {
"@embedpdf/models": "1.4.1"
"@embedpdf/models": "1.5.0"
},
"peerDependencies": {
"@embedpdf/core": "1.4.1",
"@embedpdf/plugin-loader": "1.4.1",
"@embedpdf/core": "1.5.0",
"@embedpdf/plugin-loader": "1.5.0",
"preact": "^10.26.4",
"react": ">=16.8.0",
"react-dom": ">=16.8.0",
@@ -858,16 +867,16 @@
}
},
"node_modules/@embedpdf/plugin-thumbnail": {
"version": "1.4.1",
"resolved": "https://registry.npmjs.org/@embedpdf/plugin-thumbnail/-/plugin-thumbnail-1.4.1.tgz",
"integrity": "sha512-bN3msjI0PovazgbPK3LyugYVTwIDo0RyBUhBaG42FgJxeY3hmFOWTPgfUH1QF7twHlySnksIvHRFYR3nViryVw==",
"version": "1.5.0",
"resolved": "https://registry.npmjs.org/@embedpdf/plugin-thumbnail/-/plugin-thumbnail-1.5.0.tgz",
"integrity": "sha512-Z2qpyyr5s2M6460KDGu1Vk6rdbQFIoCpnyFAT6e7UaTIKkqJSNpmjqMsBU5PosYCFu/cClpHPvS7tg9/IKAk6g==",
"license": "MIT",
"dependencies": {
"@embedpdf/models": "1.4.1"
"@embedpdf/models": "1.5.0"
},
"peerDependencies": {
"@embedpdf/core": "1.4.1",
"@embedpdf/plugin-render": "1.4.1",
"@embedpdf/core": "1.5.0",
"@embedpdf/plugin-render": "1.5.0",
"preact": "^10.26.4",
"react": ">=16.8.0",
"react-dom": ">=16.8.0",
@@ -876,18 +885,18 @@
}
},
"node_modules/@embedpdf/plugin-tiling": {
"version": "1.4.1",
"resolved": "https://registry.npmjs.org/@embedpdf/plugin-tiling/-/plugin-tiling-1.4.1.tgz",
"integrity": "sha512-wgTfj5T8HV6KP61iiR63DVNrbVp8sPxTqa1Sm+2/D0jY+EPSSCmpt1/qYWiAXd1X+t78foOjCnfbo7fEMn5/pg==",
"version": "1.5.0",
"resolved": "https://registry.npmjs.org/@embedpdf/plugin-tiling/-/plugin-tiling-1.5.0.tgz",
"integrity": "sha512-0Vx9elHNpMM+zv8hEoZXBEm8Q0+4kU52LxOlTYRr1A5FskF836sUct6g1ngwK1bmfbAfpz+62PnYI2EeilDZig==",
"license": "MIT",
"dependencies": {
"@embedpdf/models": "1.4.1"
"@embedpdf/models": "1.5.0"
},
"peerDependencies": {
"@embedpdf/core": "1.4.1",
"@embedpdf/plugin-render": "1.4.1",
"@embedpdf/plugin-scroll": "1.4.1",
"@embedpdf/plugin-viewport": "1.4.1",
"@embedpdf/core": "1.5.0",
"@embedpdf/plugin-render": "1.5.0",
"@embedpdf/plugin-scroll": "1.5.0",
"@embedpdf/plugin-viewport": "1.5.0",
"preact": "^10.26.4",
"react": ">=16.8.0",
"react-dom": ">=16.8.0",
@@ -896,16 +905,15 @@
}
},
"node_modules/@embedpdf/plugin-viewport": {
"version": "1.4.1",
"resolved": "https://registry.npmjs.org/@embedpdf/plugin-viewport/-/plugin-viewport-1.4.1.tgz",
"integrity": "sha512-+TgFHKPCLTBiDYe2DdsmTS37hwQgcZ3dYIc7bE0l5cp+GVwouu1h0MTmjL+90loizeWwCiu10E/zXR6hz+CUaQ==",
"version": "1.5.0",
"resolved": "https://registry.npmjs.org/@embedpdf/plugin-viewport/-/plugin-viewport-1.5.0.tgz",
"integrity": "sha512-G8GDyYRhfehw72+r4qKkydnA5+AU8qH67g01Y12b0DzI0VIzymh/05Z4dK8DsY3jyWPXJfw2hlg5+KDHaMBHgQ==",
"license": "MIT",
"peer": true,
"dependencies": {
"@embedpdf/models": "1.4.1"
"@embedpdf/models": "1.5.0"
},
"peerDependencies": {
"@embedpdf/core": "1.4.1",
"@embedpdf/core": "1.5.0",
"preact": "^10.26.4",
"react": ">=16.8.0",
"react-dom": ">=16.8.0",
@@ -914,19 +922,19 @@
}
},
"node_modules/@embedpdf/plugin-zoom": {
"version": "1.4.1",
"resolved": "https://registry.npmjs.org/@embedpdf/plugin-zoom/-/plugin-zoom-1.4.1.tgz",
"integrity": "sha512-9HocmXnPZxqN06q7kyNAmLjgDHOEW8/8QfgNE3nMpRyNHIgnAjxvsWc9lApgp5ErDPG0cSDt0Cduil6nB3wSBQ==",
"version": "1.5.0",
"resolved": "https://registry.npmjs.org/@embedpdf/plugin-zoom/-/plugin-zoom-1.5.0.tgz",
"integrity": "sha512-LiDkCd5/IXg2CRORl1Yikan2op+AYXSxhHzCFatyBdwzVj+n4y9I74OwCI62Mar8WDAIMyXZDCQxGPToSm+zDw==",
"license": "MIT",
"dependencies": {
"@embedpdf/models": "1.4.1",
"@embedpdf/models": "1.5.0",
"hammerjs": "^2.0.8"
},
"peerDependencies": {
"@embedpdf/core": "1.4.1",
"@embedpdf/plugin-interaction-manager": "1.4.1",
"@embedpdf/plugin-scroll": "1.4.1",
"@embedpdf/plugin-viewport": "1.4.1",
"@embedpdf/core": "1.5.0",
"@embedpdf/plugin-interaction-manager": "1.5.0",
"@embedpdf/plugin-scroll": "1.5.0",
"@embedpdf/plugin-viewport": "1.5.0",
"preact": "^10.26.4",
"react": ">=16.8.0",
"react-dom": ">=16.8.0",
@@ -935,9 +943,9 @@
}
},
"node_modules/@embedpdf/utils": {
"version": "1.4.1",
"resolved": "https://registry.npmjs.org/@embedpdf/utils/-/utils-1.4.1.tgz",
"integrity": "sha512-vvJ51Qsz3PyJWR2YvDMMpJXg4+YqdV7Vn2cusmW9sx+4EnAiBiw0HevEE+FepgFV8k+A0WbwXzmsujDIQJ7R4A==",
"version": "1.5.0",
"resolved": "https://registry.npmjs.org/@embedpdf/utils/-/utils-1.5.0.tgz",
"integrity": "sha512-L6jsAPQPGM8ne+MMFAd5gqXb1RNEgNyh16VvVUVKcVnJlBhwil59nVeEQ0cwPhjF5qVeY6MQDIOjBzJqkgXOYg==",
"license": "MIT",
"peerDependencies": {
"preact": "^10.26.4",
@@ -1056,7 +1064,6 @@
"resolved": "https://registry.npmjs.org/@emotion/react/-/react-11.14.0.tgz",
"integrity": "sha512-O000MLDBDdk/EohJPFUqvnp4qnHeYkVP5B0xEG0D/L7cOKP9kefu2DXn8dj74cQfsEzUqh+sr1RzFqiL1o+PpA==",
"license": "MIT",
"peer": true,
"dependencies": {
"@babel/runtime": "^7.18.3",
"@emotion/babel-plugin": "^11.13.5",
@@ -1100,7 +1107,6 @@
"resolved": "https://registry.npmjs.org/@emotion/styled/-/styled-11.14.1.tgz",
"integrity": "sha512-qEEJt42DuToa3gurlH4Qqc1kVpNq8wO8cJtDzU46TjlzWjDlsVyevtYCRijVq3SrHsROS+gVQ8Fnea108GnKzw==",
"license": "MIT",
"peer": true,
"dependencies": {
"@babel/runtime": "^7.18.3",
"@emotion/babel-plugin": "^11.13.5",
@@ -2131,7 +2137,6 @@
"resolved": "https://registry.npmjs.org/@mantine/core/-/core-8.3.6.tgz",
"integrity": "sha512-paTl+0x+O/QtgMtqVJaG8maD8sfiOdgPmLOyG485FmeGZ1L3KMdEkhxZtmdGlDFsLXhmMGQ57ducT90bvhXX5A==",
"license": "MIT",
"peer": true,
"dependencies": {
"@floating-ui/react": "^0.27.16",
"clsx": "^2.1.1",
@@ -2182,7 +2187,6 @@
"resolved": "https://registry.npmjs.org/@mantine/hooks/-/hooks-8.3.6.tgz",
"integrity": "sha512-liHfaWXHAkLjJy+Bkr29UsCwAoDQ/a64WrM67lksx8F0qqyjR5RQH8zVlhuOjdpQnwtlUkE/YiTvbJiPcoI0bw==",
"license": "MIT",
"peer": true,
"peerDependencies": {
"react": "^18.x || ^19.x"
}
@@ -2250,7 +2254,6 @@
"resolved": "https://registry.npmjs.org/@mui/material/-/material-7.3.5.tgz",
"integrity": "sha512-8VVxFmp1GIm9PpmnQoCoYo0UWHoOrdA57tDL62vkpzEgvb/d71Wsbv4FRg7r1Gyx7PuSo0tflH34cdl/NvfHNQ==",
"license": "MIT",
"peer": true,
"dependencies": {
"@babel/runtime": "^7.28.4",
"@mui/core-downloads-tracker": "^7.3.5",
@@ -3183,7 +3186,6 @@
"resolved": "https://registry.npmjs.org/@stripe/stripe-js/-/stripe-js-7.9.0.tgz",
"integrity": "sha512-ggs5k+/0FUJcIgNY08aZTqpBTtbExkJMYMLSMwyucrhtWexVOEY1KJmhBsxf+E/Q15f5rbwBpj+t0t2AW2oCsQ==",
"license": "MIT",
"peer": true,
"engines": {
"node": ">=12.16"
}
@@ -3302,6 +3304,7 @@
"resolved": "https://registry.npmjs.org/@sveltejs/acorn-typescript/-/acorn-typescript-1.0.6.tgz",
"integrity": "sha512-4awhxtMh4cx9blePWl10HRHj8Iivtqj+2QdDCSMDzxG+XKa9+VCNupQuCuvzEhYPzZSrX+0gC+0lHA/0fFKKQQ==",
"license": "MIT",
"peer": true,
"peerDependencies": {
"acorn": "^8.9.0"
}
@@ -4078,7 +4081,6 @@
"integrity": "sha512-o4PXJQidqJl82ckFaXUeoAW+XysPLauYI43Abki5hABd853iMhitooc6znOnczgbTYmEP6U6/y1ZyKAIsvMKGg==",
"dev": true,
"license": "MIT",
"peer": true,
"dependencies": {
"@babel/code-frame": "^7.10.4",
"@babel/runtime": "^7.12.5",
@@ -4407,7 +4409,6 @@
"resolved": "https://registry.npmjs.org/@types/react/-/react-19.2.2.tgz",
"integrity": "sha512-6mDvHUFSjyT2B2yeNx2nUgMxh9LtOWvkhIU3uePn2I2oyNymUAX1NIsdgviM4CH+JSrp2D2hsMvJOkxY+0wNRA==",
"license": "MIT",
"peer": true,
"dependencies": {
"csstype": "^3.0.2"
}
@@ -4418,7 +4419,6 @@
"integrity": "sha512-9KQPoO6mZCi7jcIStSnlOWn2nEF3mNmyr3rIAsGnAbQKYbRLyqmeSc39EVgtxXVia+LMT8j3knZLAZAh+xLmrw==",
"dev": true,
"license": "MIT",
"peer": true,
"peerDependencies": {
"@types/react": "^19.2.0"
}
@@ -4488,7 +4488,6 @@
"integrity": "sha512-6m1I5RmHBGTnUGS113G04DMu3CpSdxCAU/UvtjNWL4Nuf3MW9tQhiJqRlHzChIkhy6kZSAQmc+I1bcGjE3yNKg==",
"dev": true,
"license": "MIT",
"peer": true,
"dependencies": {
"@typescript-eslint/scope-manager": "8.46.3",
"@typescript-eslint/types": "8.46.3",
@@ -5202,6 +5201,7 @@
"resolved": "https://registry.npmjs.org/@vue/reactivity/-/reactivity-3.5.24.tgz",
"integrity": "sha512-BM8kBhtlkkbnyl4q+HiF5R5BL0ycDPfihowulm02q3WYp2vxgPcJuZO866qa/0u3idbMntKEtVNuAUp5bw4teg==",
"license": "MIT",
"peer": true,
"dependencies": {
"@vue/shared": "3.5.24"
}
@@ -5211,6 +5211,7 @@
"resolved": "https://registry.npmjs.org/@vue/runtime-core/-/runtime-core-3.5.24.tgz",
"integrity": "sha512-RYP/byyKDgNIqfX/gNb2PB55dJmM97jc9wyF3jK7QUInYKypK2exmZMNwnjueWwGceEkP6NChd3D2ZVEp9undQ==",
"license": "MIT",
"peer": true,
"dependencies": {
"@vue/reactivity": "3.5.24",
"@vue/shared": "3.5.24"
@@ -5221,6 +5222,7 @@
"resolved": "https://registry.npmjs.org/@vue/runtime-dom/-/runtime-dom-3.5.24.tgz",
"integrity": "sha512-Z8ANhr/i0XIluonHVjbUkjvn+CyrxbXRIxR7wn7+X7xlcb7dJsfITZbkVOeJZdP8VZwfrWRsWdShH6pngMxRjw==",
"license": "MIT",
"peer": true,
"dependencies": {
"@vue/reactivity": "3.5.24",
"@vue/runtime-core": "3.5.24",
@@ -5233,6 +5235,7 @@
"resolved": "https://registry.npmjs.org/@vue/server-renderer/-/server-renderer-3.5.24.tgz",
"integrity": "sha512-Yh2j2Y4G/0/4z/xJ1Bad4mxaAk++C2v4kaa8oSYTMJBJ00/ndPuxCnWeot0/7/qafQFLh5pr6xeV6SdMcE/G1w==",
"license": "MIT",
"peer": true,
"dependencies": {
"@vue/compiler-ssr": "3.5.24",
"@vue/shared": "3.5.24"
@@ -5259,7 +5262,6 @@
"resolved": "https://registry.npmjs.org/acorn/-/acorn-8.15.0.tgz",
"integrity": "sha512-NZyJarBfL7nWwIq+FDL6Zp/yHEhePMNnnJ0y3qfieCrmNvYct8uvtiV41UvlSe6apAfk0fY1FbWx+NwfmpvtTg==",
"license": "MIT",
"peer": true,
"bin": {
"acorn": "bin/acorn"
},
@@ -5667,6 +5669,7 @@
"resolved": "https://registry.npmjs.org/axobject-query/-/axobject-query-4.1.0.tgz",
"integrity": "sha512-qIj0G9wZbMGNLjLmg1PT6v2mE9AH2zlnADJD/2tC6E00hgmhUOfEB6greHPAfLRSufHqROIUTkw6E+M3lH0PTQ==",
"license": "Apache-2.0",
"peer": true,
"engines": {
"node": ">= 0.4"
}
@@ -5943,7 +5946,6 @@
}
],
"license": "MIT",
"peer": true,
"dependencies": {
"baseline-browser-mapping": "^2.8.19",
"caniuse-lite": "^1.0.30001751",
@@ -6991,8 +6993,7 @@
"resolved": "https://registry.npmjs.org/devtools-protocol/-/devtools-protocol-0.0.1521046.tgz",
"integrity": "sha512-vhE6eymDQSKWUXwwA37NtTTVEzjtGVfDr3pRbsWEQ5onH/Snp2c+2xZHWJJawG/0hCCJLRGt4xVtEVUVILol4w==",
"dev": true,
"license": "BSD-3-Clause",
"peer": true
"license": "BSD-3-Clause"
},
"node_modules/dezalgo": {
"version": "1.0.4",
@@ -7387,7 +7388,6 @@
"integrity": "sha512-BhHmn2yNOFA9H9JmmIVKJmd288g9hrVRDkdoIgRCRuSySRUHH7r/DI6aAXW9T1WwUuY3DFgrcaqB+deURBLR5g==",
"dev": true,
"license": "MIT",
"peer": true,
"dependencies": {
"@eslint-community/eslint-utils": "^4.8.0",
"@eslint-community/regexpp": "^4.12.1",
@@ -7558,7 +7558,6 @@
"integrity": "sha512-whOE1HFo/qJDyX4SnXzP4N6zOWn79WhnCUY/iDR0mPfQZO8wcYE4JClzI2oZrhBnnMUCBCHZhO6VQyoBU95mZA==",
"dev": true,
"license": "MIT",
"peer": true,
"dependencies": {
"@rtsao/scc": "^1.1.0",
"array-includes": "^3.1.9",
@@ -7725,7 +7724,8 @@
"version": "1.2.2",
"resolved": "https://registry.npmjs.org/esm-env/-/esm-env-1.2.2.tgz",
"integrity": "sha512-Epxrv+Nr/CaL4ZcFGPJIYLWFom+YeV1DqMLHJoEd9SYRxNbaFruBwfEX/kkHUJf55j2+TUbmDcmuilbP1TmXHA==",
"license": "MIT"
"license": "MIT",
"peer": true
},
"node_modules/espree": {
"version": "10.4.0",
@@ -7790,6 +7790,7 @@
"resolved": "https://registry.npmjs.org/esrap/-/esrap-2.1.2.tgz",
"integrity": "sha512-DgvlIQeowRNyvLPWW4PT7Gu13WznY288Du086E751mwwbsgr29ytBiYeLzAGIo0qk3Ujob0SDk8TiSaM5WQzNg==",
"license": "MIT",
"peer": true,
"dependencies": {
"@jridgewell/sourcemap-codec": "^1.4.15"
}
@@ -8880,7 +8881,6 @@
}
],
"license": "MIT",
"peer": true,
"dependencies": {
"@babel/runtime": "^7.27.6"
},
@@ -9357,6 +9357,7 @@
"resolved": "https://registry.npmjs.org/is-reference/-/is-reference-3.0.3.tgz",
"integrity": "sha512-ixkJoqQvAP88E6wLydLGGqCJsrFUnqoH6HnaczB8XmDH1oaWU+xxdptvikTgaEhtZ53Ky6YXiBuUI2WXLMCwjw==",
"license": "MIT",
"peer": true,
"dependencies": {
"@types/estree": "^1.0.6"
}
@@ -9677,7 +9678,6 @@
"integrity": "sha512-Pcfm3eZ+eO4JdZCXthW9tCDT3nF4K+9dmeZ+5X39n+Kqz0DDIABRP5CAEOHRFZk8RGuC2efksTJxrjp8EXCunQ==",
"dev": true,
"license": "MIT",
"peer": true,
"dependencies": {
"@acemir/cssom": "^0.9.19",
"@asamuzakjp/dom-selector": "^6.7.3",
@@ -10264,7 +10264,8 @@
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/locate-character/-/locate-character-3.0.0.tgz",
"integrity": "sha512-SW13ws7BjaeJ6p7Q6CO2nchbYEc3X3J6WrmTTDto7yMPqVSZTUyY5Tjbid+Ab8gLnATtygYtiDIJGQRRn2ZOiA==",
"license": "MIT"
"license": "MIT",
"peer": true
},
"node_modules/locate-path": {
"version": "6.0.0",
@@ -11410,7 +11411,6 @@
}
],
"license": "MIT",
"peer": true,
"dependencies": {
"nanoid": "^3.3.11",
"picocolors": "^1.1.1",
@@ -11690,7 +11690,6 @@
"resolved": "https://registry.npmjs.org/preact/-/preact-10.27.2.tgz",
"integrity": "sha512-5SYSgFKSyhCbk6SrXyMpqjb5+MQBgfvEKE/OC+PujcY34sOpqtr+0AZQtPYx5IA6VxynQ7rUPCtKzyovpj9Bpg==",
"license": "MIT",
"peer": true,
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/preact"
@@ -12073,7 +12072,6 @@
"resolved": "https://registry.npmjs.org/react/-/react-19.2.0.tgz",
"integrity": "sha512-tmbWg6W31tQLeB5cdIBOicJDJRR2KzXsV7uSK9iNfLWQ5bIZfxuPEHp7M8wiHyHnn0DD1i7w3Zmin0FtkrwoCQ==",
"license": "MIT",
"peer": true,
"engines": {
"node": ">=0.10.0"
}
@@ -12083,7 +12081,6 @@
"resolved": "https://registry.npmjs.org/react-dom/-/react-dom-19.2.0.tgz",
"integrity": "sha512-UlbRu4cAiGaIewkPyiRGJk0imDN2T3JjieT6spoL2UeSf5od4n5LB/mQ4ejmxhCFT1tYe8IvaFulzynWovsEFQ==",
"license": "MIT",
"peer": true,
"dependencies": {
"scheduler": "^0.27.0"
},
@@ -13595,6 +13592,7 @@
"resolved": "https://registry.npmjs.org/aria-query/-/aria-query-5.3.2.tgz",
"integrity": "sha512-COROpnaoap1E2F000S62r6A60uHZnmlvomhfyT2DlTcrY1OrBKn2UhH7qn5wTC9zMvD0AY7csdPSNwKP+7WiQw==",
"license": "Apache-2.0",
"peer": true,
"engines": {
"node": ">= 0.4"
}
@@ -13803,7 +13801,6 @@
"integrity": "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==",
"dev": true,
"license": "MIT",
"peer": true,
"engines": {
"node": ">=12"
},
@@ -14105,7 +14102,6 @@
"integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==",
"devOptional": true,
"license": "Apache-2.0",
"peer": true,
"bin": {
"tsc": "bin/tsc",
"tsserver": "bin/tsserver"
@@ -14187,7 +14183,6 @@
"dev": true,
"hasInstallScript": true,
"license": "MIT",
"peer": true,
"dependencies": {
"napi-postinstall": "^0.3.0"
},
@@ -14392,7 +14387,6 @@
"integrity": "sha512-BxAKBWmIbrDgrokdGZH1IgkIk/5mMHDreLDmCJ0qpyJaAteP8NvMhkwr/ZCQNqNH97bw/dANTE9PDzqwJghfMQ==",
"dev": true,
"license": "MIT",
"peer": true,
"dependencies": {
"esbuild": "^0.25.0",
"fdir": "^6.5.0",
@@ -14544,7 +14538,6 @@
"integrity": "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==",
"dev": true,
"license": "MIT",
"peer": true,
"engines": {
"node": ">=12"
},
@@ -14558,7 +14551,6 @@
"integrity": "sha512-LUCP5ev3GURDysTWiP47wRRUpLKMOfPh+yKTx3kVIEiu5KOMeqzpnYNsKyOoVrULivR8tLcks4+lga33Whn90A==",
"dev": true,
"license": "MIT",
"peer": true,
"dependencies": {
"@types/chai": "^5.2.2",
"@vitest/expect": "3.2.4",
@@ -15170,7 +15162,8 @@
"version": "1.1.4",
"resolved": "https://registry.npmjs.org/zimmerframe/-/zimmerframe-1.1.4.tgz",
"integrity": "sha512-B58NGBEoc8Y9MWWCQGl/gq9xBCe4IiKM0a2x7GZdQKOW5Exr8S1W24J6OgM1njK8xCRGvAJIL/MxXHf6SkmQKQ==",
"license": "MIT"
"license": "MIT",
"peer": true
},
"node_modules/zod": {
"version": "3.25.76",
+20 -19
View File
@@ -7,25 +7,26 @@
"dependencies": {
"@atlaskit/pragmatic-drag-and-drop": "^1.7.7",
"@dnd-kit/core": "^6.3.1",
"@embedpdf/core": "^1.4.1",
"@embedpdf/engines": "^1.4.1",
"@embedpdf/plugin-annotation": "^1.4.1",
"@embedpdf/plugin-bookmark": "^1.4.1",
"@embedpdf/plugin-export": "^1.4.1",
"@embedpdf/plugin-history": "^1.4.1",
"@embedpdf/plugin-interaction-manager": "^1.4.1",
"@embedpdf/plugin-loader": "^1.4.1",
"@embedpdf/plugin-pan": "^1.4.1",
"@embedpdf/plugin-render": "^1.4.1",
"@embedpdf/plugin-rotate": "^1.4.1",
"@embedpdf/plugin-scroll": "^1.4.1",
"@embedpdf/plugin-search": "^1.4.1",
"@embedpdf/plugin-selection": "^1.4.1",
"@embedpdf/plugin-spread": "^1.4.1",
"@embedpdf/plugin-thumbnail": "^1.4.1",
"@embedpdf/plugin-tiling": "^1.4.1",
"@embedpdf/plugin-viewport": "^1.4.1",
"@embedpdf/plugin-zoom": "^1.4.1",
"@embedpdf/core": "^1.5.0",
"@embedpdf/engines": "^1.5.0",
"@embedpdf/plugin-annotation": "^1.5.0",
"@embedpdf/plugin-bookmark": "^1.5.0",
"@embedpdf/plugin-export": "^1.5.0",
"@embedpdf/plugin-history": "^1.5.0",
"@embedpdf/plugin-interaction-manager": "^1.5.0",
"@embedpdf/plugin-loader": "^1.5.0",
"@embedpdf/plugin-pan": "^1.5.0",
"@embedpdf/plugin-print": "^1.5.0",
"@embedpdf/plugin-render": "^1.5.0",
"@embedpdf/plugin-rotate": "^1.5.0",
"@embedpdf/plugin-scroll": "^1.5.0",
"@embedpdf/plugin-search": "^1.5.0",
"@embedpdf/plugin-selection": "^1.5.0",
"@embedpdf/plugin-spread": "^1.5.0",
"@embedpdf/plugin-thumbnail": "^1.5.0",
"@embedpdf/plugin-tiling": "^1.5.0",
"@embedpdf/plugin-viewport": "^1.5.0",
"@embedpdf/plugin-zoom": "^1.5.0",
"@emotion/react": "^11.14.0",
"@emotion/styled": "^11.14.1",
"@iconify/react": "^6.0.2",
@@ -54,17 +54,17 @@
--cc-secondary-color: #b0b0b0;
--cc-btn-primary-bg: #4dabf7;
--cc-btn-primary-color: #2d2d2d;
--cc-btn-primary-color: #ffffff;
--cc-btn-primary-border-color: #4dabf7;
--cc-btn-primary-hover-bg: #3d3d3d;
--cc-btn-primary-hover-color: #e5e5e5;
--cc-btn-primary-hover-color: #ffffff;
--cc-btn-primary-hover-border-color: #3d3d3d;
--cc-btn-secondary-bg: #3d3d3d;
--cc-btn-secondary-color: #e5e5e5;
--cc-btn-secondary-color: #ffffff;
--cc-btn-secondary-border-color: #3d3d3d;
--cc-btn-secondary-hover-bg: #4dabf7;
--cc-btn-secondary-hover-color: #2d2d2d;
--cc-btn-secondary-hover-color: #ffffff;
--cc-btn-secondary-hover-border-color: #4dabf7;
--cc-separator-border-color: #555555;
@@ -180,4 +180,27 @@
/* Lower z-index so cookie banner appears behind onboarding modals */
#cc-main {
z-index: 100 !important;
}
/* Ensure consent modal text is visible in both themes */
#cc-main .cm {
background: var(--cc-bg) !important;
color: var(--cc-primary-color) !important;
}
#cc-main .cm__title {
color: var(--cc-primary-color) !important;
}
#cc-main .cm__desc {
color: var(--cc-primary-color) !important;
}
#cc-main .cm__footer {
color: var(--cc-primary-color) !important;
}
#cc-main .cm__footer-links a,
#cc-main .cm__link {
color: var(--cc-primary-color) !important;
}
+40 -169
View File
@@ -122,7 +122,6 @@ quickPosition = "Quick Position"
size = "Size"
submit = "Submit"
success = "Success"
errorLabel = "Error"
undoDataMismatch = "Cannot undo: operation data is corrupted"
undoFailed = "Failed to undo operation"
undoQuotaError = "Cannot undo: insufficient storage space"
@@ -719,169 +718,6 @@ tags = "authenticate,PEM,P12,official,encrypt,sign,certificate,PKCS12,JKS,server
title = "Sign with Certificate"
desc = "Signs a PDF with a Certificate/Key (PEM/P12)"
[home.signingWorkflow]
title = "Shared signing"
desc = "Invite collaborators, issue notifications, and manage certificate collection."
tags = "collaborate,share,team,invite,multi,participants,distributed"
[certSign.collab]
stepTitle = "Share for signing"
submit = "Create shared session"
sessionCreated = "Signing session created successfully"
results = "Session summary"
error = "Unable to start shared signing session. Please verify participant emails and try again."
helper = "Invite multiple participants to sign by entering emails. Each invite gets its own tracking token."
emails = "Participant emails"
emailsPlaceholder = "Enter email and press Enter"
names = "Participant names (optional)"
namesPlaceholder = "Enter name and press Enter"
owner = "Your email for updates (optional)"
messageLabel = "Message to include in invitations"
dueDate = "Due date (optional, ISO date)"
notify = "Send notifications immediately"
footer = "After submitting you will get a session summary with per-signer links and can return later to finalize signatures."
participantStatus = "Participant Status"
signed = "Signed"
pending = "Pending"
loadingSession = "Loading session status..."
[certSign.collab.sessionList]
title = "Signing Sessions"
empty = "No signing sessions yet. Upload a PDF to create one."
createNew = "Create New Session"
participantCount = "{0} participants"
signedCount = "{0} of {1} signed"
active = "Active"
finalized = "Finalized"
[certSign.collab.sessionDetail]
title = "Session Details"
participants = "Participants"
addParticipants = "Add Participants"
selectUsers = "Select users..."
addButton = "Add Participants"
removeParticipant = "Remove"
deleteSession = "Delete Session"
deleteConfirm = "Are you sure? This cannot be undone."
backToList = "Back to Sessions"
autoRefresh = "Auto-refreshing every 30s to show latest participant status"
created = "Created"
owner = "Owner"
dueDate = "Due Date"
messageLabel = "Message"
participantsAdded = "Participants added successfully"
addParticipantsError = "Failed to add participants"
participantRemoved = "Participant removed"
removeParticipantError = "Failed to remove participant"
finalized = "Session finalized and PDF downloaded"
finalizeError = "Failed to finalize session"
deleted = "Session deleted"
deleteError = "Failed to delete session"
loadSignedPdf = "Load signed PDF into active files"
loadPdfError = "Failed to load signed PDF"
[certSign.collab.status]
pending = "Pending"
notified = "Notified"
viewed = "Viewed"
signed = "Signed"
declined = "Declined"
[certSign.collab.message]
placeholder = "Please review and sign this document by the due date."
[certSign.collab.participant]
title = "Submit your certificate"
subtitle = "Upload certificate to sign document"
sessionInfo = "Session: {sessionId}"
documentName = "Document: {documentName}"
yourEmail = "Your email: {email}"
status = "Status: {status}"
instructions = "Please upload your certificate files and provide signing details."
certTypeLabel = "Certificate type"
passwordLabel = "Certificate password"
passwordPlaceholder = "Leave empty if no password"
filesLabel = "Certificate files"
appearanceLabel = "Signature appearance"
visibleLabel = "Make signature visible"
pageNumberLabel = "Page number"
reasonLabel = "Reason"
locationLabel = "Location"
nameLabel = "Signer name"
submit = "Submit certificate"
submitSuccess = "Certificate submitted successfully"
submitError = "Failed to submit certificate. Please check your files and try again."
invalidToken = "Invalid or expired session link"
alreadySigned = "You have already submitted your certificate"
loading = "Loading session details..."
[certSign.collab.finalize]
button = "Finalize and load signed PDF"
tooltip = "Apply all collected certificates and load the final signed document"
processing = "Applying signatures..."
success = "Signed PDF added to active files"
error = "Failed to finalize signatures. Some participants may not have submitted certificates."
[certSign.collab.tabs]
mySessions = "My Sessions"
signRequests = "Sign Requests"
[certSign.collab.userSelector]
placeholder = "Select users..."
loadError = "Failed to load users"
noTeam = "No Team"
[certSign.collab.signatureSettings]
title = "Signature Appearance"
description = "Configure how signatures will appear for all participants"
[certSign.collab.signRequests]
empty = "No pending sign requests."
from = "From"
due = "Due"
[certSign.collab.signRequest]
backToList = "Back to Sign Requests"
from = "From"
dueDate = "Due Date"
signatureSettings = "Signature Settings"
signatureInfo = "These settings are configured by the document owner"
certificateChoice = "Certificate Choice"
usePersonalCert = "Use My Personal Certificate"
usePersonalCertDesc = "Auto-generated for your account"
useServerCert = "Use Organization Certificate"
useServerCertDesc = "Shared organization certificate"
uploadCert = "Upload Custom Certificate"
uploadCertDesc = "Use your own PKCS12 certificate"
p12File = "P12/PFX Certificate File"
selectFile = "Select file..."
password = "Certificate Password"
signButton = "Sign Document"
declineButton = "Decline"
signed = "Document signed successfully"
signError = "Failed to sign document"
declined = "Sign request declined"
declineError = "Failed to decline request"
noCertificate = "Please select a certificate file"
noUser = "User not authenticated"
alreadyProcessed = "You have already processed this sign request."
incomplete = "Not all participants have submitted certificates yet"
loading = "Loading sign request..."
addSignature = "Add Your Signature"
message = "Message"
placeSignatureButton = "Place Signature on PDF"
placementActive = "Click PDF to place"
signaturePlaced = "Signature placed on page"
drawSignature = "Draw your signature below"
uploadSignature = "Upload your signature image"
typeSignature = "Type your name to create a signature"
signatureType = "Signature Type"
placementError = "Failed to place signature"
[certSign.collab.signRequest.placeSignature]
title = "Place Signature"
message = "Click on the PDF to place your signature"
[home.repair]
tags = "fix,restore"
title = "Repair"
@@ -2431,8 +2267,16 @@ defaultCanvasLabel = "Drawing signature"
defaultImageLabel = "Uploaded signature"
defaultTextLabel = "Typed signature"
saveButton = "Save signature"
savePersonal = "Save Personal"
saveShared = "Save Shared"
saveUnavailable = "Create a signature first to save it."
noChanges = "Current signature is already saved."
tempStorageTitle = "Temporary browser storage"
tempStorageDescription = "Signatures are stored in your browser only. They will be lost if you clear browser data or switch browsers."
personalHeading = "Personal Signatures"
sharedHeading = "Shared Signatures"
personalDescription = "Only you can see these signatures."
sharedDescription = "All users can see and use these signatures."
[sign.saved.type]
canvas = "Drawing"
@@ -2788,7 +2632,6 @@ stepTitle = "Certificate Files"
[certSign.appearance]
stepTitle = "Signature Appearance"
visibility = "Visibility"
invisible = "Invisible"
visible = "Visible"
@@ -4033,7 +3876,6 @@ singlePageView = "Single Page View"
unknownFile = "Unknown file"
zoomIn = "Zoom In"
zoomOut = "Zoom Out"
resetZoom = "Reset Zoom"
[rightRail]
closeSelected = "Close Selected Files"
@@ -4057,6 +3899,7 @@ toggleSidebar = "Toggle Sidebar"
exportSelected = "Export Selected Pages"
toggleAnnotations = "Toggle Annotations Visibility"
annotationMode = "Toggle Annotation Mode"
print = "Print PDF"
draw = "Draw"
save = "Save"
saveChanges = "Save Changes"
@@ -4674,6 +4517,7 @@ description = "URL or filename to impressum (required in some jurisdictions)"
title = "Premium & Enterprise"
description = "Configure your premium or enterprise license key."
license = "License Configuration"
noInput = "Please provide a license key or file"
[admin.settings.premium.licenseKey]
toggle = "Got a license key or certificate file?"
@@ -4691,6 +4535,26 @@ line1 = "Overwriting your current license key cannot be undone."
line2 = "Your previous license will be permanently lost unless you have backed it up elsewhere."
line3 = "Important: Keep license keys private and secure. Never share them publicly."
[admin.settings.premium.inputMethod]
text = "License Key"
file = "Certificate File"
[admin.settings.premium.file]
label = "License Certificate File"
description = "Upload your .lic or .cert license file from offline purchases"
choose = "Choose License File"
selected = "Selected: {{filename}} ({{size}})"
successMessage = "License file uploaded and activated successfully. No restart required."
[admin.settings.premium.currentLicense]
title = "Active License"
file = "Source: License file ({{path}})"
key = "Source: License key"
type = "Type: {{type}}"
noInput = "Please provide a license key or upload a certificate file"
success = "Success"
[admin.settings.premium.enabled]
label = "Enable Premium Features"
description = "Enable license key checks for pro/enterprise features"
@@ -4775,7 +4639,6 @@ subtitle = "Add files to your storage for easy access across tools"
filesSelected = "files selected"
clearSelection = "Clear Selection"
openInFileEditor = "Open in File Editor"
downloadSelected = "Download Selected"
uploadError = "Failed to upload some files."
failedToOpen = "Failed to open file. It may have been removed from storage."
failedToLoad = "Failed to load file to active set."
@@ -4807,6 +4670,7 @@ googleDriveShort = "Drive"
myFiles = "My Files"
noRecentFiles = "No recent files found"
googleDriveNotAvailable = "Google Drive integration not available"
downloadSelected = "Download Selected"
saveSelected = "Save Selected"
openFiles = "Open Files"
openFile = "Open File"
@@ -5427,7 +5291,7 @@ emailsPlaceholder = "user1@example.com, user2@example.com"
emailsRequired = "At least one email address is required"
submit = "Send Invites"
success = "user(s) invited successfully"
partialSuccess = "Some invites failed"
partialFailure = "Some invites failed"
allFailed = "Failed to invite users"
error = "Failed to send invites"
@@ -5943,7 +5807,7 @@ description = "Sign in with your Stirling account"
[setup.mode.selfhosted]
title = "Self-Hosted Server"
description = "Connect to your own Stirling PDF server"
description = "Connect to your own Stirling PDF server with your personal account"
[setup.saas]
title = "Sign in to Stirling"
@@ -5979,6 +5843,13 @@ submit = "Login"
signInWith = "Sign in with"
oauthPending = "Opening browser for authentication..."
orContinueWith = "Or continue with email"
serverRequirement = "Note: The server must have login enabled."
showInstructions = "How to enable?"
hideInstructions = "Hide instructions"
instructions = "To enable login on your Stirling PDF server:"
instructionsEnvVar = "Set the environment variable:"
instructionsOrYml = "Or in settings.yml:"
instructionsRestart = "Then restart your server for the changes to take effect."
[setup.login.username]
label = "Username"
+2 -2
View File
@@ -11,8 +11,8 @@
{
"identifier": "http:allow-fetch",
"allow": [
{ "url": "http://localhost:*" },
{ "url": "http://127.0.0.1:*" },
{ "url": "http://*" },
{ "url": "http://*:*" },
{ "url": "https://*" }
]
},
+1
View File
@@ -3,6 +3,7 @@ Version=1.0
Type=Application
Name=Stirling-PDF
Comment=Locally hosted web application that allows you to perform various operations on PDF files
Exec=/usr/bin/stirling-pdf
Icon={{icon}}
Terminal=false
MimeType=application/pdf;
+2 -29
View File
@@ -3,8 +3,7 @@ import { AppProviders } from "@app/components/AppProviders";
import { AppLayout } from "@app/components/AppLayout";
import { LoadingFallback } from "@app/components/shared/LoadingFallback";
import HomePage from "@app/pages/HomePage";
import OnboardingTour from "@app/components/onboarding/OnboardingTour";
import ParticipantCertificateSubmission from "@app/pages/ParticipantCertificateSubmission";
import Onboarding from "@app/components/onboarding/Onboarding";
// Import global styles
import "@app/styles/tailwind.css";
@@ -15,38 +14,12 @@ import "@app/styles/index.css";
import "@app/utils/fileIdSafety";
export default function App() {
console.error("HELLOOOOOO")
// Check for participant signing session URL parameters
const queryParams = new URLSearchParams(window.location.search);
const sessionId = queryParams.get('sessionId');
const token = queryParams.get('token');
console.log('App.tsx routing check:', { sessionId, token, search: window.location.search });
// If both sessionId and token are present, show participant submission page
if (sessionId && token) {
console.log('Showing participant submission page');
return (
<Suspense fallback={<LoadingFallback />}>
<AppProviders>
<AppLayout>
<ParticipantCertificateSubmission
sessionId={sessionId}
token={token}
/>
</AppLayout>
</AppProviders>
</Suspense>
);
}
// Otherwise, show normal home page
return (
<Suspense fallback={<LoadingFallback />}>
<AppProviders>
<AppLayout>
<HomePage />
<OnboardingTour />
<Onboarding />
</AppLayout>
</AppProviders>
</Suspense>
@@ -12,7 +12,6 @@ import { AppConfigProvider, AppConfigProviderProps, AppConfigRetryOptions } from
import { RightRailProvider } from "@app/contexts/RightRailContext";
import { ViewerProvider } from "@app/contexts/ViewerContext";
import { SignatureProvider } from "@app/contexts/SignatureContext";
import { OnboardingProvider } from "@app/contexts/OnboardingContext";
import { TourOrchestrationProvider } from "@app/contexts/TourOrchestrationContext";
import { AdminTourOrchestrationProvider } from "@app/contexts/AdminTourOrchestrationContext";
import { PageEditorProvider } from "@app/contexts/PageEditorContext";
@@ -77,7 +76,6 @@ export function AppProviders({ children, appConfigRetryOptions, appConfigProvide
<RainbowThemeProvider>
<ErrorBoundary>
<BannerProvider>
<OnboardingProvider>
<AppConfigProvider
retryOptions={appConfigRetryOptions}
{...appConfigProviderProps}
@@ -113,7 +111,6 @@ export function AppProviders({ children, appConfigRetryOptions, appConfigProvide
</ToolRegistryProvider>
</FileContextProvider>
</AppConfigProvider>
</OnboardingProvider>
</BannerProvider>
</ErrorBoundary>
</RainbowThemeProvider>
@@ -71,16 +71,6 @@ export default function Workbench() {
};
const renderMainContent = () => {
// Check if we're showing a custom workbench first
// Custom workbenches may not require files in FileContext (e.g., sign request workbench)
if (!isBaseWorkbench(currentView)) {
const customView = customWorkbenchViews.find((view) => view.workbenchId === currentView && view.data != null);
if (customView) {
const CustomComponent = customView.component;
return <CustomComponent data={customView.data} />;
}
}
if (activeFiles.length === 0) {
return (
<LandingPage
@@ -1,33 +0,0 @@
import { FLOW_SEQUENCES, type SlideId } from '@app/components/onboarding/onboardingFlowConfig';
export type FlowType = 'login-admin' | 'login-user' | 'no-login' | 'no-login-admin';
export interface FlowConfig {
type: FlowType;
ids: SlideId[];
}
export function resolveFlow(enableLogin: boolean, isAdmin: boolean, selfReportedAdmin: boolean): FlowConfig {
if (!enableLogin) {
return selfReportedAdmin
? {
type: 'no-login-admin',
ids: [...FLOW_SEQUENCES.noLoginBase, ...FLOW_SEQUENCES.noLoginAdmin],
}
: {
type: 'no-login',
ids: FLOW_SEQUENCES.noLoginBase,
};
}
return isAdmin
? {
type: 'login-admin',
ids: FLOW_SEQUENCES.loginAdmin,
}
: {
type: 'login-user',
ids: FLOW_SEQUENCES.loginUser,
};
}

Some files were not shown because too many files have changed in this diff Show More