mirror of
https://github.com/Stirling-Tools/Stirling-PDF.git
synced 2026-09-03 05:10:16 +03:00
Compare commits
39
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a243056c3e | ||
|
|
aa6ac5c7a3 | ||
|
|
71ef9dcde8 | ||
|
|
b9d3a3128b | ||
|
|
0bf35a98c0 | ||
|
|
10d9127d29 | ||
|
|
fa2eb67124 | ||
|
|
86d4a34476 | ||
|
|
74c53001cf | ||
|
|
ad8830b645 | ||
|
|
de93a1b5e2 | ||
|
|
8476d3cdec | ||
|
|
94fbc74271 | ||
|
|
5c319f13cb | ||
|
|
7aeec93032 | ||
|
|
ddc0baa41d | ||
|
|
8094765bab | ||
|
|
2265e48b32 | ||
|
|
b10fc1b2de | ||
|
|
866e56728d | ||
|
|
e560ee4cc4 | ||
|
|
7cccee4c34 | ||
|
|
934ad180cb | ||
|
|
9aaf417303 | ||
|
|
cc1c6bc9e3 | ||
|
|
732a602503 | ||
|
|
e5c6ceedc5 | ||
|
|
a2dd0298dc | ||
|
|
789be2d351 | ||
|
|
d0d197f09f | ||
|
|
8f5344ec7d | ||
|
|
62e5e28039 | ||
|
|
d7c130fca9 | ||
|
|
4d8a86ad28 | ||
|
|
030f9f541e | ||
|
|
921bdac4b7 | ||
|
|
120678260a | ||
|
|
cb45fb159a | ||
|
|
a8b2957b74 |
@@ -32,7 +32,7 @@ vs `main`. Flags: `--html` (also emit a rendered HTML twin), `--no-screens`.
|
||||
- Read the PR description / commit messages for stated intent. Do **not** invent
|
||||
history or motivation that isn't evidenced (state current behavior in present tense).
|
||||
- Classify touched files by layer:
|
||||
- **Frontend**: tools (`frontend/editor/src/core/components/tools/*` or `.../core/tools/*`),
|
||||
- **Frontend**: tools (`frontend/src/editor/core/components/tools/*` or `.../core/tools/*`),
|
||||
hooks (`core/hooks/tools/*`, `useToolOperation`), contexts, routes, i18n
|
||||
(`public/locales/en-US`).
|
||||
- **Java backend**: controllers (`.../controller/api/...`), services, models, config.
|
||||
|
||||
@@ -53,11 +53,11 @@ gh pr diff <pr> --name-only # or: git diff --name-only <base>...HEAD
|
||||
Map changed frontend files to URLs generically:
|
||||
- **Tools**: a changed `components/tools/<toolDir>/…` or `hooks/tools/<tool>/…` →
|
||||
toolId → URL via the repo's own rule `getToolUrlPath` in
|
||||
[toolsTaxonomy.ts:200](frontend/editor/src/core/data/toolsTaxonomy.ts): `/` + the
|
||||
[toolsTaxonomy.ts:200](frontend/src/editor/core/data/toolsTaxonomy.ts): `/` + the
|
||||
id kebab-cased (`addPageNumbers` → `/add-page-numbers`).
|
||||
- **Pages/routes**: changed `filesPage/*` → `/files`, etc.
|
||||
- `--all`: enumerate every tool in the registry instead of just changed ones.
|
||||
Write `frontend/editor/screenshots/ui-diff/targets.json` =
|
||||
Write `frontend/screenshots/ui-diff/targets.json` =
|
||||
`[{ "id":"compress", "url":"/compress", "name":"Compress" }]`. This is what makes
|
||||
it generic - the spec never names a tool.
|
||||
|
||||
@@ -69,12 +69,12 @@ the full viewport - or the `--scope` container if given). Ensure the harness is
|
||||
(node_modules + icons).
|
||||
```
|
||||
# after = current head
|
||||
cd frontend/editor && PR_SHOT_SIDE=after PR_SHOT_THEME=light \
|
||||
cd frontend && PR_SHOT_SIDE=after PR_SHOT_THEME=light \
|
||||
npx playwright test --project=stubbed ui-before-after.spec.ts
|
||||
# before = base, in an isolated worktree (copy the spec + targets.json in)
|
||||
git worktree add ../ba-base origin/<baseRefName> # or the merge-base
|
||||
# set up its frontend, copy spec + screenshots/ui-diff/targets.json across, then:
|
||||
cd ../ba-base/frontend/editor && PR_SHOT_SIDE=before PR_SHOT_THEME=light \
|
||||
cd ../ba-base/frontend && PR_SHOT_SIDE=before PR_SHOT_THEME=light \
|
||||
npx playwright test --project=stubbed ui-before-after.spec.ts
|
||||
# copy its screenshots/ui-diff/before/ back next to after/. Repeat with
|
||||
# PR_SHOT_THEME=dark if --theme includes dark. Remove worktree when done.
|
||||
@@ -82,7 +82,7 @@ cd ../ba-base/frontend/editor && PR_SHOT_SIDE=before PR_SHOT_THEME=light \
|
||||
|
||||
### 4. Auto-diff (surface what changed)
|
||||
```
|
||||
cd frontend/editor && node <skill>/diff-shots.mjs \
|
||||
cd frontend && node <skill>/diff-shots.mjs \
|
||||
screenshots/ui-diff/before screenshots/ui-diff/after screenshots/ui-diff
|
||||
```
|
||||
Produces `diff-report.json` classifying each view `unchanged | changed | added |
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
// unchanged | changed | added | removed, and CROP each changed pair to the
|
||||
// affected region (bounding box of differing pixels + padding) - unless the
|
||||
// change spans most of the page, in which case the full frame is kept.
|
||||
// Run from frontend/editor (so deps resolve):
|
||||
// Run from frontend (so deps resolve):
|
||||
// node <skill>/diff-shots.mjs <beforeDir> <afterDir> [outDir]
|
||||
// Env:
|
||||
// DIFF_THRESHOLD min fraction of differing pixels to count as changed (default 0.001)
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
// Render each .tab-section of a montage HTML into its own PNG (the PR-ready image).
|
||||
// Run from frontend/editor (so @playwright/test resolves):
|
||||
// Run from frontend (so @playwright/test resolves):
|
||||
// node <skill>/shoot-sections.mjs <montage.html> <outDir>
|
||||
import path from "node:path";
|
||||
import { pathToFileURL } from "node:url";
|
||||
|
||||
@@ -28,13 +28,13 @@ current branch diff. Flags: `--fix`, `--theme light|dark|both` (default both),
|
||||
## What this repo gives you (use it, don't reinvent)
|
||||
|
||||
- **Stubbed Playwright project** = backend-free screenshots via `page.route()` mocks.
|
||||
Reference implementation: `frontend/editor/src/core/tests/stubbed/files-page-screenshots.spec.ts`.
|
||||
Reference implementation: `frontend/src/editor/core/tests/stubbed/files-page-screenshots.spec.ts`.
|
||||
It already shows the light / **dark** / **RTL** passes, JWT seeding, IndexedDB
|
||||
seeding, and dumping PNGs to a `screenshots/<area>/` folder. Copy its shape.
|
||||
- Helpers: `frontend/editor/src/core/tests/helpers/ui-helpers.ts`
|
||||
- Helpers: `frontend/src/editor/core/tests/helpers/ui-helpers.ts`
|
||||
(`uploadFiles`, `openSettings`, `waitForModalOpen`, `dismissTourTooltip`, …)
|
||||
and the `stub-test-base` fixtures (`autoGoto`, `seedJwt`, `viewport`).
|
||||
- Config: `frontend/editor/playwright.config.ts` (run from `frontend/editor/`).
|
||||
- Config: `frontend/playwright.config.ts` (run from `frontend/`).
|
||||
- Report template: [report-template.html](report-template.html) - self-contained,
|
||||
one big image at a time, a global light/dark slider that flips every shot,
|
||||
thumbnail rail, prev/next + arrow keys, and a Findings tab.
|
||||
@@ -54,13 +54,13 @@ current branch diff. Flags: `--fix`, `--theme light|dark|both` (default both),
|
||||
Worktrees have no `node_modules` and no generated icons. From repo root:
|
||||
```
|
||||
cd frontend && npm ci # or junction main's node_modules (see memory)
|
||||
cd frontend/editor && node scripts/generate-icons.js
|
||||
cd frontend && node scripts/generate-icons.js
|
||||
```
|
||||
Kill any stale dev server first (it serves old modules):
|
||||
`Get-NetTCPConnection -LocalPort 5173 -State Listen | %{ Stop-Process -Id $_.OwningProcess -Force }`
|
||||
|
||||
### 3. Write the capture spec
|
||||
Create `frontend/editor/src/core/tests/stubbed/<feature>-walkthrough.spec.ts`,
|
||||
Create `frontend/src/editor/core/tests/stubbed/<feature>-walkthrough.spec.ts`,
|
||||
modeled on `files-page-screenshots.spec.ts`. For each enumerated view:
|
||||
- stub the APIs it needs, drive the UI to that state, wait on a real locator
|
||||
(not a fixed sleep), `await settle(page)` for Mantine portals, then
|
||||
@@ -71,7 +71,7 @@ modeled on `files-page-screenshots.spec.ts`. For each enumerated view:
|
||||
- Name shots `NN_<view>_<theme>.png` so light/dark pair up by suffix.
|
||||
- Prefer **stable test-ids** over translated accessible names (RTL/i18n breaks text locators).
|
||||
|
||||
Run it: `cd frontend/editor && npx playwright test --project=stubbed <feature>-walkthrough.spec.ts`.
|
||||
Run it: `cd frontend && npx playwright test --project=stubbed <feature>-walkthrough.spec.ts`.
|
||||
Add `--project=stubbed-firefox`/`-webkit` only if cross-browser layout matters.
|
||||
|
||||
### 4. Build the report
|
||||
|
||||
+4
-4
@@ -26,16 +26,16 @@ version_builds/
|
||||
node_modules/
|
||||
**/node_modules/
|
||||
frontend/node_modules/
|
||||
frontend/editor/dist/
|
||||
frontend/editor/playwright-report/
|
||||
frontend/dist/
|
||||
frontend/playwright-report/
|
||||
.npm/
|
||||
.yarn/
|
||||
|
||||
# Tauri/desktop builds
|
||||
src-tauri/target/
|
||||
src-tauri/dist/
|
||||
frontend/editor/src-tauri/target/
|
||||
frontend/editor/src-tauri/dist/
|
||||
frontend/src-tauri/target/
|
||||
frontend/src-tauri/dist/
|
||||
|
||||
# IDE and editor
|
||||
.idea/
|
||||
|
||||
+10
-10
@@ -92,12 +92,12 @@ frontend: &frontend
|
||||
# job on changes to any of these.
|
||||
tauri: &tauri
|
||||
- *ci
|
||||
- frontend/editor/src-tauri/**
|
||||
- frontend/editor/src/desktop/**
|
||||
- frontend/editor/tsconfig.desktop.vite.json
|
||||
- frontend/src-tauri/**
|
||||
- frontend/src/editor/desktop/**
|
||||
- frontend/tsconfig.desktop.vite.json
|
||||
- frontend/package.json
|
||||
- frontend/package-lock.json
|
||||
- frontend/editor/vite.config.ts
|
||||
- frontend/vite.config.ts
|
||||
- .github/workflows/tauri-build.yml
|
||||
- Taskfile.yml
|
||||
- .taskfiles/desktop.yml
|
||||
@@ -121,9 +121,9 @@ engine: &engine
|
||||
generated-models: &generated-models
|
||||
- *ci
|
||||
- *openapi
|
||||
- frontend/editor/scripts/generate-tool-api-types.mts
|
||||
- frontend/editor/src/core/types/toolApiTypes.ts
|
||||
- frontend/editor/src/core/types/toolIO.ts
|
||||
- frontend/scripts/generate-tool-api-types.mts
|
||||
- frontend/src/editor/core/types/toolApiTypes.ts
|
||||
- frontend/src/editor/core/types/toolIO.ts
|
||||
- engine/scripts/generate_tool_models.py
|
||||
- engine/src/stirling/models/tool_models.py
|
||||
- engine/src/stirling/models/tool_io.py
|
||||
@@ -135,7 +135,7 @@ licenses-frontend: &licenses-frontend
|
||||
- ".github/workflows/frontend-backend-licenses-update.yml"
|
||||
- "frontend/package.json"
|
||||
- "frontend/package-lock.json"
|
||||
- "frontend/editor/scripts/generate-licenses.js"
|
||||
- "frontend/scripts/generate-licenses.js"
|
||||
|
||||
licenses-backend: &licenses-backend
|
||||
- ".github/workflows/frontend-backend-licenses-update.yml"
|
||||
@@ -146,8 +146,8 @@ licenses-backend: &licenses-backend
|
||||
proprietary: &proprietary
|
||||
- *ci
|
||||
- app/proprietary/**
|
||||
- frontend/editor/src/proprietary/**
|
||||
- frontend/editor/src/core/tests/enterprise/**
|
||||
- frontend/src/editor/proprietary/**
|
||||
- frontend/src/editor/core/tests/enterprise/**
|
||||
- testing/compose/docker-compose-keycloak-oauth.yml
|
||||
- testing/compose/docker-compose-keycloak-saml.yml
|
||||
- testing/compose/keycloak-realm-oauth.json
|
||||
|
||||
@@ -128,9 +128,9 @@ updates:
|
||||
|
||||
- package-ecosystem: cargo
|
||||
directories:
|
||||
- /frontend/editor/src-tauri
|
||||
- /frontend/editor/src-tauri/thumbnail-handler
|
||||
- /frontend/editor/src-tauri/provisioner
|
||||
- /frontend/src-tauri
|
||||
- /frontend/src-tauri/thumbnail-handler
|
||||
- /frontend/src-tauri/provisioner
|
||||
schedule:
|
||||
interval: "weekly"
|
||||
cooldown:
|
||||
|
||||
@@ -51,7 +51,7 @@ labels:
|
||||
|
||||
- label: 'Translation'
|
||||
files:
|
||||
- 'frontend/editor/public/locales/[a-zA-Z]{2}-[a-zA-Z\-]{2,7}/translation.toml'
|
||||
- 'frontend/public/locales/[a-zA-Z]{2}-[a-zA-Z\-]{2,7}/translation.toml'
|
||||
- 'scripts/ignore_translation.toml'
|
||||
- 'scripts/remove_translation_keys.sh'
|
||||
- 'scripts/replace_translation_line.sh'
|
||||
@@ -70,8 +70,8 @@ labels:
|
||||
|
||||
- label: 'Tauri'
|
||||
files:
|
||||
- 'frontend/editor/src-tauri/**'
|
||||
- 'frontend/editor/src-tauri/.*'
|
||||
- 'frontend/src-tauri/**'
|
||||
- 'frontend/src-tauri/.*'
|
||||
|
||||
- label: 'engine'
|
||||
files:
|
||||
|
||||
@@ -13,7 +13,7 @@ Usage:
|
||||
"""
|
||||
|
||||
# Sample for Windows:
|
||||
# python .github/scripts/check_language_toml.py --reference-file frontend/editor/public/locales/en-US/translation.toml --branch "" --files frontend/editor/public/locales/de-DE/translation.toml frontend/editor/public/locales/fr-FR/translation.toml
|
||||
# python .github/scripts/check_language_toml.py --reference-file frontend/public/locales/en-US/translation.toml --branch "" --files frontend/public/locales/de-DE/translation.toml frontend/public/locales/fr-FR/translation.toml
|
||||
|
||||
import argparse
|
||||
import glob
|
||||
@@ -308,7 +308,7 @@ def check_for_differences(reference_file, file_list, branch, actor):
|
||||
report.append("## ❌ Overall Check Status: **_Failed_**")
|
||||
report.append("")
|
||||
report.append(
|
||||
f"@{actor} please check your translation if it conforms to the standard. Follow the format of [en-US/translation.toml](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/frontend/editor/public/locales/en-US/translation.toml)"
|
||||
f"@{actor} please check your translation if it conforms to the standard. Follow the format of [en-US/translation.toml](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/frontend/public/locales/en-US/translation.toml)"
|
||||
)
|
||||
else:
|
||||
report.append("## ✅ Overall Check Status: **_Success_**")
|
||||
|
||||
@@ -14,9 +14,7 @@ from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
|
||||
from cryptography.exceptions import InvalidSignature
|
||||
|
||||
ART_ROOT = Path(sys.argv[1])
|
||||
CONF = Path(
|
||||
sys.argv[2] if len(sys.argv) > 2 else "frontend/editor/src-tauri/tauri.conf.json"
|
||||
)
|
||||
CONF = Path(sys.argv[2] if len(sys.argv) > 2 else "frontend/src-tauri/tauri.conf.json")
|
||||
|
||||
|
||||
def load_pubkey():
|
||||
|
||||
@@ -211,10 +211,16 @@ jobs:
|
||||
java-version: "25"
|
||||
distribution: "temurin"
|
||||
|
||||
- name: Setup Gradle
|
||||
uses: gradle/actions/setup-gradle@3f131e8634966bd73d06cc69884922b02e6faf92 # v6.2.0
|
||||
- name: Cache Gradle User Home
|
||||
uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
|
||||
with:
|
||||
gradle-version: 9.6.1
|
||||
path: |
|
||||
~/.gradle/caches
|
||||
~/.gradle/wrapper
|
||||
key: gradle-${{ runner.os }}-${{ runner.arch }}-jdk-25-${{ hashFiles('gradle/wrapper/gradle-wrapper.properties', 'gradle/libs.versions.toml', 'settings.gradle', 'build.gradle', 'app/**/build.gradle', 'gradle/**/*.gradle') }}
|
||||
restore-keys: |
|
||||
gradle-${{ runner.os }}-${{ runner.arch }}-jdk-25-
|
||||
gradle-${{ runner.os }}-${{ runner.arch }}-
|
||||
|
||||
- name: Install Task
|
||||
uses: go-task/setup-task@01a4adf9db2d14c1de7a560f09170b6e0df736aa # v2.1.0
|
||||
|
||||
@@ -40,20 +40,16 @@ jobs:
|
||||
java-version: ${{ matrix.jdk-version }}
|
||||
distribution: "temurin"
|
||||
|
||||
- name: Cache Gradle dependency artifacts
|
||||
- name: Cache Gradle User Home
|
||||
uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
|
||||
with:
|
||||
path: |
|
||||
~/.gradle/caches
|
||||
~/.gradle/wrapper
|
||||
~/.gradle/caches/modules-2/files-2.1
|
||||
~/.gradle/caches/modules-2/metadata-2.*
|
||||
key: gradle-deps-${{ runner.os }}-jdk-${{ matrix.jdk-version }}-${{ hashFiles('**/gradle/wrapper/gradle-wrapper.properties', '**/*.gradle', '**/*.gradle.kts', 'settings.gradle', 'settings.gradle.kts', 'gradle/libs.versions.toml') }}
|
||||
|
||||
- name: Setup Gradle
|
||||
uses: gradle/actions/setup-gradle@3f131e8634966bd73d06cc69884922b02e6faf92 # v6.2.0
|
||||
with:
|
||||
gradle-version: 9.6.1
|
||||
cache-disabled: true
|
||||
key: gradle-${{ runner.os }}-${{ runner.arch }}-jdk-${{ matrix.jdk-version }}-${{ hashFiles('gradle/wrapper/gradle-wrapper.properties', 'gradle/libs.versions.toml', 'settings.gradle', 'build.gradle', 'app/**/build.gradle', 'gradle/**/*.gradle') }}
|
||||
restore-keys: |
|
||||
gradle-${{ runner.os }}-${{ runner.arch }}-jdk-${{ matrix.jdk-version }}-
|
||||
gradle-${{ runner.os }}-${{ runner.arch }}-
|
||||
|
||||
- name: Install Task
|
||||
uses: go-task/setup-task@01a4adf9db2d14c1de7a560f09170b6e0df736aa # v2.1.0
|
||||
|
||||
@@ -60,6 +60,16 @@ jobs:
|
||||
with:
|
||||
java-version: "25"
|
||||
distribution: "temurin"
|
||||
- name: Cache Gradle User Home
|
||||
uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
|
||||
with:
|
||||
path: |
|
||||
~/.gradle/caches
|
||||
~/.gradle/wrapper
|
||||
key: gradle-${{ runner.os }}-${{ runner.arch }}-jdk-25-${{ hashFiles('gradle/wrapper/gradle-wrapper.properties', 'gradle/libs.versions.toml', 'settings.gradle', 'build.gradle', 'app/**/build.gradle', 'gradle/**/*.gradle') }}
|
||||
restore-keys: |
|
||||
gradle-${{ runner.os }}-${{ runner.arch }}-jdk-25-
|
||||
gradle-${{ runner.os }}-${{ runner.arch }}-
|
||||
- name: Set up Node.js
|
||||
uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0
|
||||
with:
|
||||
@@ -284,7 +294,7 @@ jobs:
|
||||
if: always()
|
||||
working-directory: frontend
|
||||
run: >
|
||||
npx tsx editor/scripts/report-flaky-tests.mts
|
||||
npx tsx scripts/report-flaky-tests.mts
|
||||
"${{ github.workspace }}/frontend/playwright-report/results-oauth.json"
|
||||
"${{ github.workspace }}/frontend/playwright-report/results-saml.json"
|
||||
"${{ github.workspace }}/frontend/playwright-report/results-feature.json"
|
||||
|
||||
@@ -60,8 +60,43 @@ jobs:
|
||||
with:
|
||||
filters: .github/config/.files.yaml
|
||||
|
||||
build:
|
||||
gradle-cache-prime:
|
||||
name: Prime shared Gradle cache
|
||||
needs: [files-changed]
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 15
|
||||
steps:
|
||||
- name: Harden the runner (Audit all outbound calls)
|
||||
uses: step-security/harden-runner@bf7454d06d71f1098171f2acdf0cd4708d7b5920 # v2.20.0
|
||||
with:
|
||||
egress-policy: audit
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
|
||||
- name: Set up JDK 25
|
||||
uses: actions/setup-java@be666c2fcd27ec809703dec50e508c2fdc7f6654 # v5.2.0
|
||||
with:
|
||||
java-version: "25"
|
||||
distribution: "temurin"
|
||||
- name: Cache Gradle User Home
|
||||
uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
|
||||
with:
|
||||
path: |
|
||||
~/.gradle/caches
|
||||
~/.gradle/wrapper
|
||||
key: gradle-${{ runner.os }}-${{ runner.arch }}-jdk-25-${{ hashFiles('gradle/wrapper/gradle-wrapper.properties', 'gradle/libs.versions.toml', 'settings.gradle', 'build.gradle', 'app/**/build.gradle', 'gradle/**/*.gradle') }}
|
||||
restore-keys: |
|
||||
gradle-${{ runner.os }}-${{ runner.arch }}-jdk-25-
|
||||
gradle-${{ runner.os }}-${{ runner.arch }}-
|
||||
- name: Resolve backend dependencies
|
||||
run: ./gradlew :stirling-pdf:classes -PnoSpotless --no-daemon
|
||||
env:
|
||||
STIRLING_FLAVOR: saas
|
||||
MAVEN_USER: ${{ secrets.MAVEN_USER }}
|
||||
MAVEN_PASSWORD: ${{ secrets.MAVEN_PASSWORD }}
|
||||
MAVEN_PUBLIC_URL: ${{ secrets.MAVEN_PUBLIC_URL }}
|
||||
|
||||
build:
|
||||
needs: [files-changed, gradle-cache-prime]
|
||||
permissions:
|
||||
actions: read
|
||||
contents: read
|
||||
@@ -76,7 +111,7 @@ jobs:
|
||||
# works after Hibernate's ddl-auto=update migrates the schema. Gated on
|
||||
# the `project` filter so doc-only PRs skip this ~5-minute job.
|
||||
if: needs.files-changed.outputs.project == 'true'
|
||||
needs: [files-changed]
|
||||
needs: [files-changed, gradle-cache-prime]
|
||||
permissions:
|
||||
contents: read
|
||||
uses: ./.github/workflows/db-migration-test.yml
|
||||
@@ -84,7 +119,7 @@ jobs:
|
||||
|
||||
check-generateOpenApiDocs:
|
||||
if: needs.files-changed.outputs.openapi == 'true'
|
||||
needs: [files-changed]
|
||||
needs: [files-changed, gradle-cache-prime]
|
||||
permissions:
|
||||
contents: read
|
||||
uses: ./.github/workflows/check-openapi.yml
|
||||
@@ -120,7 +155,7 @@ jobs:
|
||||
|
||||
playwright-e2e-live:
|
||||
if: needs.files-changed.outputs.frontend == 'true'
|
||||
needs: [files-changed]
|
||||
needs: [files-changed, gradle-cache-prime]
|
||||
permissions:
|
||||
contents: read
|
||||
uses: ./.github/workflows/e2e-live.yml
|
||||
@@ -128,7 +163,7 @@ jobs:
|
||||
|
||||
playwright-e2e-enterprise:
|
||||
if: needs.files-changed.outputs.proprietary == 'true'
|
||||
needs: [files-changed]
|
||||
needs: [files-changed, gradle-cache-prime]
|
||||
permissions:
|
||||
contents: read
|
||||
uses: ./.github/workflows/build-enterprise.yml
|
||||
@@ -136,7 +171,7 @@ jobs:
|
||||
|
||||
check-licence:
|
||||
if: needs.files-changed.outputs.build == 'true'
|
||||
needs: [files-changed, build]
|
||||
needs: [files-changed, build, gradle-cache-prime]
|
||||
permissions:
|
||||
contents: read
|
||||
uses: ./.github/workflows/check-licence.yml
|
||||
@@ -144,7 +179,7 @@ jobs:
|
||||
|
||||
docker-compose-tests:
|
||||
if: needs.files-changed.outputs.project == 'true'
|
||||
needs: [files-changed]
|
||||
needs: [files-changed, gradle-cache-prime]
|
||||
permissions:
|
||||
actions: write
|
||||
contents: read
|
||||
@@ -156,7 +191,7 @@ jobs:
|
||||
|
||||
test-build-docker-images:
|
||||
if: github.event_name == 'pull_request' && needs.files-changed.outputs.project == 'true'
|
||||
needs: [files-changed, build, check-generateOpenApiDocs, check-licence]
|
||||
needs: [files-changed, build, check-generateOpenApiDocs, check-licence, gradle-cache-prime]
|
||||
permissions:
|
||||
contents: read
|
||||
packages: read
|
||||
@@ -199,7 +234,7 @@ jobs:
|
||||
# frontend filter, so a CSS-only PR does not pay for a backend build.
|
||||
generated-models:
|
||||
if: needs.files-changed.outputs.generated-models == 'true'
|
||||
needs: [files-changed]
|
||||
needs: [files-changed, gradle-cache-prime]
|
||||
permissions:
|
||||
contents: read
|
||||
pull-requests: write
|
||||
|
||||
@@ -42,10 +42,16 @@ jobs:
|
||||
java-version: "25"
|
||||
distribution: "temurin"
|
||||
|
||||
- name: Setup Gradle
|
||||
uses: gradle/actions/setup-gradle@3f131e8634966bd73d06cc69884922b02e6faf92 # v6.2.0
|
||||
- name: Cache Gradle User Home
|
||||
uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
|
||||
with:
|
||||
gradle-version: 9.6.0
|
||||
path: |
|
||||
~/.gradle/caches
|
||||
~/.gradle/wrapper
|
||||
key: gradle-${{ runner.os }}-${{ runner.arch }}-jdk-25-${{ hashFiles('gradle/wrapper/gradle-wrapper.properties', 'gradle/libs.versions.toml', 'settings.gradle', 'build.gradle', 'app/**/build.gradle', 'gradle/**/*.gradle') }}
|
||||
restore-keys: |
|
||||
gradle-${{ runner.os }}-${{ runner.arch }}-jdk-25-
|
||||
gradle-${{ runner.os }}-${{ runner.arch }}-
|
||||
|
||||
- name: Set up Node
|
||||
uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0
|
||||
|
||||
@@ -26,20 +26,16 @@ jobs:
|
||||
java-version: "25"
|
||||
distribution: "temurin"
|
||||
|
||||
- name: Cache Gradle dependency artifacts
|
||||
- name: Cache Gradle User Home
|
||||
uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
|
||||
with:
|
||||
path: |
|
||||
~/.gradle/caches
|
||||
~/.gradle/wrapper
|
||||
~/.gradle/caches/modules-2/files-2.1
|
||||
~/.gradle/caches/modules-2/metadata-2.*
|
||||
key: gradle-deps-${{ runner.os }}-jdk-25-${{ hashFiles('**/gradle/wrapper/gradle-wrapper.properties', '**/*.gradle', '**/*.gradle.kts', 'settings.gradle', 'settings.gradle.kts', 'gradle/libs.versions.toml') }}
|
||||
|
||||
- name: Setup Gradle
|
||||
uses: gradle/actions/setup-gradle@3f131e8634966bd73d06cc69884922b02e6faf92 # v6.2.0
|
||||
with:
|
||||
gradle-version: 9.6.1
|
||||
cache-disabled: true
|
||||
key: gradle-${{ runner.os }}-${{ runner.arch }}-jdk-25-${{ hashFiles('gradle/wrapper/gradle-wrapper.properties', 'gradle/libs.versions.toml', 'settings.gradle', 'build.gradle', 'app/**/build.gradle', 'gradle/**/*.gradle') }}
|
||||
restore-keys: |
|
||||
gradle-${{ runner.os }}-${{ runner.arch }}-jdk-25-
|
||||
gradle-${{ runner.os }}-${{ runner.arch }}-
|
||||
|
||||
- name: Install Task
|
||||
uses: go-task/setup-task@01a4adf9db2d14c1de7a560f09170b6e0df736aa # v2.1.0
|
||||
|
||||
@@ -27,20 +27,16 @@ jobs:
|
||||
java-version: "25"
|
||||
distribution: "temurin"
|
||||
|
||||
- name: Cache Gradle dependency artifacts
|
||||
- name: Cache Gradle User Home
|
||||
uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
|
||||
with:
|
||||
path: |
|
||||
~/.gradle/caches
|
||||
~/.gradle/wrapper
|
||||
~/.gradle/caches/modules-2/files-2.1
|
||||
~/.gradle/caches/modules-2/metadata-2.*
|
||||
key: gradle-deps-${{ runner.os }}-jdk-25-${{ hashFiles('**/gradle/wrapper/gradle-wrapper.properties', '**/*.gradle', '**/*.gradle.kts', 'settings.gradle', 'settings.gradle.kts', 'gradle/libs.versions.toml') }}
|
||||
|
||||
- name: Setup Gradle
|
||||
uses: gradle/actions/setup-gradle@3f131e8634966bd73d06cc69884922b02e6faf92 # v6.2.0
|
||||
with:
|
||||
gradle-version: 9.6.1
|
||||
cache-disabled: true
|
||||
key: gradle-${{ runner.os }}-${{ runner.arch }}-jdk-25-${{ hashFiles('gradle/wrapper/gradle-wrapper.properties', 'gradle/libs.versions.toml', 'settings.gradle', 'build.gradle', 'app/**/build.gradle', 'gradle/**/*.gradle') }}
|
||||
restore-keys: |
|
||||
gradle-${{ runner.os }}-${{ runner.arch }}-jdk-25-
|
||||
gradle-${{ runner.os }}-${{ runner.arch }}-
|
||||
|
||||
- name: Install Task
|
||||
uses: go-task/setup-task@01a4adf9db2d14c1de7a560f09170b6e0df736aa # v2.1.0
|
||||
|
||||
@@ -6,7 +6,7 @@ on:
|
||||
pull_request_target:
|
||||
types: [opened, synchronize, reopened]
|
||||
paths:
|
||||
- "frontend/editor/public/locales/*/translation.toml"
|
||||
- "frontend/public/locales/*/translation.toml"
|
||||
- ".github/scripts/check_language_toml.py"
|
||||
- ".github/workflows/check_toml.yml"
|
||||
|
||||
@@ -76,7 +76,7 @@ jobs:
|
||||
exit 1
|
||||
fi
|
||||
# Get changed files and filter for TOML translation files
|
||||
gh pr view ${{ steps.get-pr-data.outputs.pr_number }} --json files -q ".files[].path" | grep -E '^frontend/editor/public/locales/[a-zA-Z-]+/translation\.toml$' > changed_files.txt || echo "No matching TOML files found in PR"
|
||||
gh pr view ${{ steps.get-pr-data.outputs.pr_number }} --json files -q ".files[].path" | grep -E '^frontend/public/locales/[a-zA-Z-]+/translation\.toml$' > changed_files.txt || echo "No matching TOML files found in PR"
|
||||
# Check if any files were found
|
||||
if [ ! -s changed_files.txt ]; then
|
||||
echo "No TOML translation files changed in this PR"
|
||||
@@ -166,12 +166,12 @@ jobs:
|
||||
|
||||
// Determine reference file
|
||||
let referenceFilePath;
|
||||
if (changedFiles.includes("frontend/editor/public/locales/en-US/translation.toml")) {
|
||||
if (changedFiles.includes("frontend/public/locales/en-US/translation.toml")) {
|
||||
console.log("Using PR branch reference file.");
|
||||
const { data: fileContent } = await github.rest.repos.getContent({
|
||||
owner: prRepoOwner,
|
||||
repo: prRepoName,
|
||||
path: "frontend/editor/public/locales/en-US/translation.toml",
|
||||
path: "frontend/public/locales/en-US/translation.toml",
|
||||
ref: branch,
|
||||
});
|
||||
|
||||
@@ -183,7 +183,7 @@ jobs:
|
||||
const { data: fileContent } = await github.rest.repos.getContent({
|
||||
owner: repoOwner,
|
||||
repo: repoName,
|
||||
path: "frontend/editor/public/locales/en-US/translation.toml",
|
||||
path: "frontend/public/locales/en-US/translation.toml",
|
||||
ref: "main",
|
||||
});
|
||||
|
||||
|
||||
@@ -46,20 +46,16 @@ jobs:
|
||||
java-version: "25"
|
||||
distribution: "temurin"
|
||||
|
||||
- name: Cache Gradle dependency artifacts
|
||||
- name: Cache Gradle User Home
|
||||
uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
|
||||
with:
|
||||
path: |
|
||||
~/.gradle/caches
|
||||
~/.gradle/wrapper
|
||||
~/.gradle/caches/modules-2/files-2.1
|
||||
~/.gradle/caches/modules-2/metadata-2.*
|
||||
key: gradle-deps-${{ runner.os }}-jdk-25-${{ hashFiles('**/gradle/wrapper/gradle-wrapper.properties', '**/*.gradle', '**/*.gradle.kts', 'settings.gradle', 'settings.gradle.kts', 'gradle/libs.versions.toml') }}
|
||||
|
||||
- name: Setup Gradle
|
||||
uses: gradle/actions/setup-gradle@3f131e8634966bd73d06cc69884922b02e6faf92 # v6.2.0
|
||||
with:
|
||||
gradle-version: 9.6.1
|
||||
cache-disabled: true
|
||||
key: gradle-${{ runner.os }}-${{ runner.arch }}-jdk-25-${{ hashFiles('gradle/wrapper/gradle-wrapper.properties', 'gradle/libs.versions.toml', 'settings.gradle', 'build.gradle', 'app/**/build.gradle', 'gradle/**/*.gradle') }}
|
||||
restore-keys: |
|
||||
gradle-${{ runner.os }}-${{ runner.arch }}-jdk-25-
|
||||
gradle-${{ runner.os }}-${{ runner.arch }}-
|
||||
|
||||
- name: Set up Python
|
||||
uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0
|
||||
@@ -81,7 +77,7 @@ jobs:
|
||||
# Each lands as a sibling dir under coverage-execs/, with the .exec
|
||||
# files preserving their original relative paths.
|
||||
- name: Download all .exec artifacts
|
||||
uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v6.0.0
|
||||
uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
|
||||
with:
|
||||
pattern: jacoco-exec-*
|
||||
path: coverage-execs/
|
||||
@@ -206,7 +202,7 @@ jobs:
|
||||
# absence on backend-only runs by skipping the download entirely
|
||||
# when the producer job was not part of this workflow run.
|
||||
if: inputs.frontend-validation-result == 'success'
|
||||
uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v6.0.0
|
||||
uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
|
||||
with:
|
||||
name: frontend-coverage
|
||||
path: matrix-inputs/vitest/
|
||||
@@ -216,7 +212,7 @@ jobs:
|
||||
# e2e-live uploads the artifact with a stable name. Skip the
|
||||
# download entirely when the producer job did not run.
|
||||
if: inputs.playwright-e2e-live-result == 'success'
|
||||
uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v6.0.0
|
||||
uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
|
||||
with:
|
||||
name: playwright-frontend-coverage
|
||||
path: matrix-inputs/playwright/
|
||||
|
||||
@@ -30,23 +30,19 @@ jobs:
|
||||
java-version: 25
|
||||
distribution: temurin
|
||||
|
||||
- name: Cache Gradle dependency artifacts
|
||||
- name: Cache Gradle User Home
|
||||
uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
|
||||
with:
|
||||
path: |
|
||||
~/.gradle/caches
|
||||
~/.gradle/wrapper
|
||||
~/.gradle/caches/modules-2/files-2.1
|
||||
~/.gradle/caches/modules-2/metadata-2.*
|
||||
key: gradle-deps-${{ runner.os }}-jdk-25-${{ hashFiles('**/gradle/wrapper/gradle-wrapper.properties', '**/*.gradle', '**/*.gradle.kts', 'settings.gradle', 'settings.gradle.kts', 'gradle/libs.versions.toml') }}
|
||||
key: gradle-${{ runner.os }}-${{ runner.arch }}-jdk-25-${{ hashFiles('gradle/wrapper/gradle-wrapper.properties', 'gradle/libs.versions.toml', 'settings.gradle', 'build.gradle', 'app/**/build.gradle', 'gradle/**/*.gradle') }}
|
||||
restore-keys: |
|
||||
gradle-${{ runner.os }}-${{ runner.arch }}-jdk-25-
|
||||
gradle-${{ runner.os }}-${{ runner.arch }}-
|
||||
|
||||
- name: Setup Gradle
|
||||
uses: gradle/actions/setup-gradle@3f131e8634966bd73d06cc69884922b02e6faf92 # v6.2.0
|
||||
with:
|
||||
gradle-version: 9.6.1
|
||||
cache-disabled: true
|
||||
|
||||
# No `-PnoSpotless` here yet because the upstream cache layer matches the
|
||||
# backend build's; reuse keeps cold-cache cost identical.
|
||||
# Keep the normal formatting path here so this smoke test exercises the
|
||||
# same Gradle configuration as the backend build.
|
||||
- name: Build Stirling-PDF JAR
|
||||
env:
|
||||
MAVEN_USER: ${{ secrets.MAVEN_USER }}
|
||||
|
||||
@@ -38,20 +38,16 @@ jobs:
|
||||
java-version: "25"
|
||||
distribution: "temurin"
|
||||
|
||||
- name: Cache Gradle dependency artifacts
|
||||
- name: Cache Gradle User Home
|
||||
uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
|
||||
with:
|
||||
path: |
|
||||
~/.gradle/caches
|
||||
~/.gradle/wrapper
|
||||
~/.gradle/caches/modules-2/files-2.1
|
||||
~/.gradle/caches/modules-2/metadata-2.*
|
||||
key: gradle-deps-${{ runner.os }}-jdk-25-${{ hashFiles('**/gradle/wrapper/gradle-wrapper.properties', '**/*.gradle', '**/*.gradle.kts', 'settings.gradle', 'settings.gradle.kts', 'gradle/libs.versions.toml') }}
|
||||
|
||||
- name: Setup Gradle
|
||||
uses: gradle/actions/setup-gradle@3f131e8634966bd73d06cc69884922b02e6faf92 # v6.2.0
|
||||
with:
|
||||
gradle-version: 9.6.1
|
||||
cache-disabled: true
|
||||
key: gradle-${{ runner.os }}-${{ runner.arch }}-jdk-25-${{ hashFiles('gradle/wrapper/gradle-wrapper.properties', 'gradle/libs.versions.toml', 'settings.gradle', 'build.gradle', 'app/**/build.gradle', 'gradle/**/*.gradle') }}
|
||||
restore-keys: |
|
||||
gradle-${{ runner.os }}-${{ runner.arch }}-jdk-25-
|
||||
gradle-${{ runner.os }}-${{ runner.arch }}-
|
||||
|
||||
# When the PR changes the base image, test.sh builds it locally
|
||||
# (stirling-pdf-base:local) into the daemon image store. A buildx
|
||||
|
||||
@@ -25,21 +25,16 @@ jobs:
|
||||
with:
|
||||
java-version: "25"
|
||||
distribution: "temurin"
|
||||
# Same cache layer as backend-build.yml. Without it every run resolved the
|
||||
# whole classpath cold and eventually got HTTP 429 from Maven Central.
|
||||
- name: Cache Gradle dependency artifacts
|
||||
- name: Cache Gradle User Home
|
||||
uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
|
||||
with:
|
||||
path: |
|
||||
~/.gradle/caches
|
||||
~/.gradle/wrapper
|
||||
~/.gradle/caches/modules-2/files-2.1
|
||||
~/.gradle/caches/modules-2/metadata-2.*
|
||||
key: gradle-deps-${{ runner.os }}-jdk-25-${{ hashFiles('**/gradle/wrapper/gradle-wrapper.properties', '**/*.gradle', '**/*.gradle.kts', 'settings.gradle', 'settings.gradle.kts', 'gradle/libs.versions.toml') }}
|
||||
- name: Setup Gradle
|
||||
uses: gradle/actions/setup-gradle@3f131e8634966bd73d06cc69884922b02e6faf92 # v6.2.0
|
||||
with:
|
||||
gradle-version: 9.6.1
|
||||
cache-disabled: true
|
||||
key: gradle-${{ runner.os }}-${{ runner.arch }}-jdk-25-${{ hashFiles('gradle/wrapper/gradle-wrapper.properties', 'gradle/libs.versions.toml', 'settings.gradle', 'build.gradle', 'app/**/build.gradle', 'gradle/**/*.gradle') }}
|
||||
restore-keys: |
|
||||
gradle-${{ runner.os }}-${{ runner.arch }}-jdk-25-
|
||||
gradle-${{ runner.os }}-${{ runner.arch }}-
|
||||
# Gradle does not retry 429s, and a cold cache resolving the buildscript
|
||||
# classpath is exactly where Maven Central rate-limits us. Retry it here,
|
||||
# where a failure is cheap, instead of inside the backgrounded bootRun.
|
||||
@@ -98,7 +93,7 @@ jobs:
|
||||
# ::warning:: annotations + a job summary; never fails the job.
|
||||
if: always()
|
||||
working-directory: frontend
|
||||
run: npx tsx editor/scripts/report-flaky-tests.mts "$PLAYWRIGHT_JSON_OUTPUT_FILE"
|
||||
run: npx tsx scripts/report-flaky-tests.mts "$PLAYWRIGHT_JSON_OUTPUT_FILE"
|
||||
env:
|
||||
PLAYWRIGHT_JSON_OUTPUT_FILE: ${{ github.workspace }}/frontend/playwright-report/results.json
|
||||
- name: Generate JaCoCo report from e2e:live .exec
|
||||
@@ -235,8 +230,8 @@ jobs:
|
||||
run: |
|
||||
echo "::group::Playwright output dirs"
|
||||
# Playwright anchors its default outputDir + HTML report to the
|
||||
# nearest package.json, which is frontend/ (frontend/editor has
|
||||
# none), so artifacts land under frontend/, not frontend/editor/.
|
||||
# nearest package.json, which is frontend/ (frontend has
|
||||
# none), so artifacts land under frontend/, not frontend/.
|
||||
ls -la frontend/playwright-report 2>/dev/null \
|
||||
|| echo "no playwright-report at frontend/"
|
||||
ls -la frontend/test-results 2>/dev/null \
|
||||
@@ -251,7 +246,7 @@ jobs:
|
||||
# test-results/ holds the per-test trace.zip (with browser console
|
||||
# logs) + screenshots/video; playwright-report/ is the HTML report.
|
||||
# Both live under frontend/ (Playwright anchors them to the nearest
|
||||
# package.json, which is frontend/; frontend/editor has none).
|
||||
# package.json, which is frontend/; frontend has none).
|
||||
path: |
|
||||
frontend/playwright-report/
|
||||
frontend/test-results/
|
||||
|
||||
@@ -43,7 +43,7 @@ jobs:
|
||||
# ::warning:: annotations + a job summary; never fails the job.
|
||||
if: always()
|
||||
working-directory: frontend
|
||||
run: npx tsx editor/scripts/report-flaky-tests.mts "$PLAYWRIGHT_JSON_OUTPUT_FILE"
|
||||
run: npx tsx scripts/report-flaky-tests.mts "$PLAYWRIGHT_JSON_OUTPUT_FILE"
|
||||
env:
|
||||
PLAYWRIGHT_JSON_OUTPUT_FILE: ${{ github.workspace }}/frontend/playwright-report/results.json
|
||||
- name: Upload Playwright report
|
||||
|
||||
@@ -113,31 +113,31 @@ jobs:
|
||||
NPM_CONFIG_IGNORE_SCRIPTS: "true"
|
||||
working-directory: frontend
|
||||
run: |
|
||||
mkdir -p editor/src/assets
|
||||
npx --yes license-report --only=prod --output=json > editor/src/assets/3rdPartyLicenses.json
|
||||
mkdir -p src/assets
|
||||
npx --yes license-report --only=prod --output=json > src/assets/3rdPartyLicenses.json
|
||||
|
||||
- name: Postprocess with project script (BASE version)
|
||||
if: github.event_name == 'pull_request' && github.event.pull_request.head.repo.fork == true
|
||||
env:
|
||||
PR_IS_FORK: "true"
|
||||
run: |
|
||||
node base/frontend/editor/scripts/generate-licenses.js \
|
||||
--input frontend/editor/src/assets/3rdPartyLicenses.json
|
||||
node base/frontend/scripts/generate-licenses.js \
|
||||
--input frontend/src/assets/3rdPartyLicenses.json
|
||||
|
||||
- name: Copy postprocessed artifacts back (fork PRs)
|
||||
if: github.event_name == 'pull_request' && github.event.pull_request.head.repo.fork == true
|
||||
run: |
|
||||
mkdir -p frontend/editor/src/assets
|
||||
if [ -f "base/frontend/editor/src/assets/3rdPartyLicenses.json" ]; then
|
||||
cp base/frontend/editor/src/assets/3rdPartyLicenses.json frontend/editor/src/assets/3rdPartyLicenses.json
|
||||
mkdir -p frontend/src/assets
|
||||
if [ -f "base/frontend/src/assets/3rdPartyLicenses.json" ]; then
|
||||
cp base/frontend/src/assets/3rdPartyLicenses.json frontend/src/assets/3rdPartyLicenses.json
|
||||
fi
|
||||
if [ -f "base/frontend/editor/src/assets/license-warnings.json" ]; then
|
||||
cp base/frontend/editor/src/assets/license-warnings.json frontend/editor/src/assets/license-warnings.json
|
||||
if [ -f "base/frontend/src/assets/license-warnings.json" ]; then
|
||||
cp base/frontend/src/assets/license-warnings.json frontend/src/assets/license-warnings.json
|
||||
fi
|
||||
|
||||
- name: Check for license warnings
|
||||
run: |
|
||||
if [ -f "frontend/editor/src/assets/license-warnings.json" ]; then
|
||||
if [ -f "frontend/src/assets/license-warnings.json" ]; then
|
||||
echo "LICENSE_WARNINGS_EXIST=true" >> $GITHUB_ENV
|
||||
else
|
||||
echo "LICENSE_WARNINGS_EXIST=false" >> $GITHUB_ENV
|
||||
@@ -185,10 +185,10 @@ jobs:
|
||||
echo ""
|
||||
if [ "${LICENSE_WARNINGS_EXIST}" = "true" ]; then
|
||||
echo "❌ **Failed** – incompatible or unknown licenses found."
|
||||
if [ -f "frontend/editor/src/assets/license-warnings.json" ]; then
|
||||
if [ -f "frontend/src/assets/license-warnings.json" ]; then
|
||||
echo ""
|
||||
echo "### Warnings"
|
||||
jq -r '.warnings[] | "- \(.message)"' frontend/editor/src/assets/license-warnings.json || true
|
||||
jq -r '.warnings[] | "- \(.message)"' frontend/src/assets/license-warnings.json || true
|
||||
fi
|
||||
else
|
||||
echo "✅ **Passed** – no license warnings detected."
|
||||
@@ -214,7 +214,7 @@ jobs:
|
||||
const fs = require('fs');
|
||||
let warningDetails = '';
|
||||
try {
|
||||
const warnings = JSON.parse(fs.readFileSync('frontend/editor/src/assets/license-warnings.json', 'utf8'));
|
||||
const warnings = JSON.parse(fs.readFileSync('frontend/src/assets/license-warnings.json', 'utf8'));
|
||||
warningDetails = warnings.warnings.map(w => `- ${w.message}`).join('\n');
|
||||
} catch (e) {
|
||||
warningDetails = 'Unable to read warning details';
|
||||
@@ -254,7 +254,7 @@ jobs:
|
||||
- name: Commit changes (Push only)
|
||||
if: github.event_name == 'push'
|
||||
run: |
|
||||
git add frontend/editor/src/assets/3rdPartyLicenses.json
|
||||
git add frontend/src/assets/3rdPartyLicenses.json
|
||||
# Note: Do NOT commit license-warnings.json - it's only for PR review
|
||||
git diff --staged --quiet || echo "CHANGES_DETECTED=true" >> $GITHUB_ENV
|
||||
|
||||
@@ -272,7 +272,7 @@ jobs:
|
||||
|
||||
The following licenses may require review for corporate compatibility:
|
||||
|
||||
$(cat frontend/editor/src/assets/license-warnings.json | jq -r '.warnings[].message')
|
||||
$(cat frontend/src/assets/license-warnings.json | jq -r '.warnings[].message')
|
||||
|
||||
Please review these licenses to ensure they are acceptable for your use case."
|
||||
fi
|
||||
@@ -350,10 +350,16 @@ jobs:
|
||||
java-version: "25"
|
||||
distribution: "temurin"
|
||||
|
||||
- name: Setup Gradle
|
||||
uses: gradle/actions/setup-gradle@3f131e8634966bd73d06cc69884922b02e6faf92 # v6.2.0
|
||||
- name: Cache Gradle User Home
|
||||
uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
|
||||
with:
|
||||
gradle-version: 9.6.1
|
||||
path: |
|
||||
~/.gradle/caches
|
||||
~/.gradle/wrapper
|
||||
key: gradle-${{ runner.os }}-${{ runner.arch }}-jdk-25-${{ hashFiles('gradle/wrapper/gradle-wrapper.properties', 'gradle/libs.versions.toml', 'settings.gradle', 'build.gradle', 'app/**/build.gradle', 'gradle/**/*.gradle') }}
|
||||
restore-keys: |
|
||||
gradle-${{ runner.os }}-${{ runner.arch }}-jdk-25-
|
||||
gradle-${{ runner.os }}-${{ runner.arch }}-
|
||||
|
||||
- name: Install Task
|
||||
uses: go-task/setup-task@01a4adf9db2d14c1de7a560f09170b6e0df736aa # v2.1.0
|
||||
|
||||
@@ -130,19 +130,19 @@ jobs:
|
||||
run: |
|
||||
python scripts/coverage-summary.py \
|
||||
--title "Frontend Vitest coverage" \
|
||||
--vitest frontend/editor/coverage/coverage-summary.json \
|
||||
--vitest frontend/coverage/coverage-summary.json \
|
||||
--github-step-summary
|
||||
- name: Upload vitest coverage report
|
||||
if: always()
|
||||
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
|
||||
with:
|
||||
name: frontend-coverage
|
||||
path: frontend/editor/coverage/
|
||||
path: frontend/coverage/
|
||||
retention-days: 7
|
||||
if-no-files-found: warn
|
||||
- name: Upload frontend build artifacts
|
||||
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
|
||||
with:
|
||||
name: frontend-build
|
||||
path: frontend/editor/dist/
|
||||
path: frontend/dist/
|
||||
retention-days: 3
|
||||
|
||||
@@ -12,13 +12,14 @@ on:
|
||||
- "true"
|
||||
- "false"
|
||||
platform:
|
||||
description: "Platform to build (windows, macos, linux, or all)"
|
||||
description: "Platform to build (windows, windows-arm64, macos, linux, or all)"
|
||||
required: true
|
||||
default: "all"
|
||||
type: choice
|
||||
options:
|
||||
- all
|
||||
- windows
|
||||
- windows-arm64
|
||||
- macos
|
||||
- linux
|
||||
sign:
|
||||
@@ -56,20 +57,16 @@ jobs:
|
||||
java-version: "25"
|
||||
distribution: "temurin"
|
||||
|
||||
- name: Cache Gradle dependencies
|
||||
- name: Cache Gradle User Home
|
||||
uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
|
||||
with:
|
||||
path: |
|
||||
~/.gradle/caches
|
||||
~/.gradle/wrapper
|
||||
key: gradle-${{ runner.os }}-${{ hashFiles('**/gradle/wrapper/gradle-wrapper.properties') }}
|
||||
key: gradle-${{ runner.os }}-${{ runner.arch }}-jdk-25-${{ hashFiles('gradle/wrapper/gradle-wrapper.properties', 'gradle/libs.versions.toml', 'settings.gradle', 'build.gradle', 'app/**/build.gradle', 'gradle/**/*.gradle') }}
|
||||
restore-keys: |
|
||||
gradle-${{ runner.os }}-
|
||||
|
||||
- name: Setup Gradle
|
||||
uses: gradle/actions/setup-gradle@3f131e8634966bd73d06cc69884922b02e6faf92 # v6.2.0
|
||||
with:
|
||||
gradle-version: 9.6.1
|
||||
gradle-${{ runner.os }}-${{ runner.arch }}-jdk-25-
|
||||
gradle-${{ runner.os }}-${{ runner.arch }}-
|
||||
|
||||
- name: Install Task
|
||||
uses: go-task/setup-task@01a4adf9db2d14c1de7a560f09170b6e0df736aa # v2.1.0
|
||||
@@ -87,24 +84,35 @@ jobs:
|
||||
- name: Determine build matrix
|
||||
id: set-matrix
|
||||
run: |
|
||||
# windows-arm64: NSIS only (WiX MSI has no arm64 support in Tauri) and no
|
||||
# JPDFium natives yet - flip to windows-arm64 once JPDFium ships them.
|
||||
WINDOWS='{"platform":"windows-latest","args":"--target x86_64-pc-windows-msvc","name":"windows-x86_64","jpdfium_platforms":"windows-x64"}'
|
||||
WINDOWS_ARM64='{"platform":"windows-11-arm","args":"--target aarch64-pc-windows-msvc --bundles nsis","name":"windows-arm64","jpdfium_platforms":"none"}'
|
||||
MACOS='{"platform":"macos-15","args":"--target universal-apple-darwin","name":"macos-universal","jpdfium_platforms":"darwin-arm64,darwin-x64"}'
|
||||
LINUX='{"platform":"ubuntu-22.04","args":"","name":"linux-x86_64","jpdfium_platforms":"linux-x64"}'
|
||||
ALL="$WINDOWS,$WINDOWS_ARM64,$MACOS,$LINUX"
|
||||
|
||||
if [ "${{ github.event_name }}" = "workflow_dispatch" ]; then
|
||||
case "${{ github.event.inputs.platform }}" in
|
||||
"windows")
|
||||
echo 'matrix={"include":[{"platform":"windows-latest","args":"--target x86_64-pc-windows-msvc","name":"windows-x86_64","jpdfium_platforms":"windows-x64"}]}' >> $GITHUB_OUTPUT
|
||||
echo "matrix={\"include\":[$WINDOWS,$WINDOWS_ARM64]}" >> $GITHUB_OUTPUT
|
||||
;;
|
||||
"windows-arm64")
|
||||
echo "matrix={\"include\":[$WINDOWS_ARM64]}" >> $GITHUB_OUTPUT
|
||||
;;
|
||||
"macos")
|
||||
echo 'matrix={"include":[{"platform":"macos-15","args":"--target universal-apple-darwin","name":"macos-universal","jpdfium_platforms":"darwin-arm64,darwin-x64"}]}' >> $GITHUB_OUTPUT
|
||||
echo "matrix={\"include\":[$MACOS]}" >> $GITHUB_OUTPUT
|
||||
;;
|
||||
"linux")
|
||||
echo 'matrix={"include":[{"platform":"ubuntu-22.04","args":"","name":"linux-x86_64","jpdfium_platforms":"linux-x64"}]}' >> $GITHUB_OUTPUT
|
||||
echo "matrix={\"include\":[$LINUX]}" >> $GITHUB_OUTPUT
|
||||
;;
|
||||
*)
|
||||
echo 'matrix={"include":[{"platform":"windows-latest","args":"--target x86_64-pc-windows-msvc","name":"windows-x86_64","jpdfium_platforms":"windows-x64"},{"platform":"macos-15","args":"--target universal-apple-darwin","name":"macos-universal","jpdfium_platforms":"darwin-arm64,darwin-x64"},{"platform":"ubuntu-22.04","args":"","name":"linux-x86_64","jpdfium_platforms":"linux-x64"}]}' >> $GITHUB_OUTPUT
|
||||
echo "matrix={\"include\":[$ALL]}" >> $GITHUB_OUTPUT
|
||||
;;
|
||||
esac
|
||||
else
|
||||
# For push/release events, build all platforms
|
||||
echo 'matrix={"include":[{"platform":"windows-latest","args":"--target x86_64-pc-windows-msvc","name":"windows-x86_64","jpdfium_platforms":"windows-x64"},{"platform":"macos-15","args":"--target universal-apple-darwin","name":"macos-universal","jpdfium_platforms":"darwin-arm64,darwin-x64"},{"platform":"ubuntu-22.04","args":"","name":"linux-x86_64","jpdfium_platforms":"linux-x64"}]}' >> $GITHUB_OUTPUT
|
||||
echo "matrix={\"include\":[$ALL]}" >> $GITHUB_OUTPUT
|
||||
fi
|
||||
|
||||
build-jars:
|
||||
@@ -139,10 +147,16 @@ jobs:
|
||||
java-version: "25"
|
||||
distribution: "temurin"
|
||||
|
||||
- name: Setup Gradle
|
||||
uses: gradle/actions/setup-gradle@3f131e8634966bd73d06cc69884922b02e6faf92 # v6.2.0
|
||||
- name: Cache Gradle User Home
|
||||
uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
|
||||
with:
|
||||
gradle-version: 9.6.1
|
||||
path: |
|
||||
~/.gradle/caches
|
||||
~/.gradle/wrapper
|
||||
key: gradle-${{ runner.os }}-${{ runner.arch }}-jdk-25-${{ hashFiles('gradle/wrapper/gradle-wrapper.properties', 'gradle/libs.versions.toml', 'settings.gradle', 'build.gradle', 'app/**/build.gradle', 'gradle/**/*.gradle') }}
|
||||
restore-keys: |
|
||||
gradle-${{ runner.os }}-${{ runner.arch }}-jdk-25-
|
||||
gradle-${{ runner.os }}-${{ runner.arch }}-
|
||||
|
||||
- name: Setup Node.js
|
||||
if: matrix.variant.build_frontend == true
|
||||
@@ -236,16 +250,23 @@ jobs:
|
||||
if: matrix.platform == 'macos-15'
|
||||
run: echo "X64_JAVA_HOME=$JAVA_HOME" >> "$GITHUB_ENV"
|
||||
|
||||
# Temurin has no windows-aarch64 JDK 25 yet; Microsoft OpenJDK does.
|
||||
- name: Set up JDK 25
|
||||
uses: actions/setup-java@be666c2fcd27ec809703dec50e508c2fdc7f6654 # v5.2.0
|
||||
with:
|
||||
java-version: "25"
|
||||
distribution: "temurin"
|
||||
distribution: ${{ matrix.platform == 'windows-11-arm' && 'microsoft' || 'temurin' }}
|
||||
|
||||
- name: Setup Gradle
|
||||
uses: gradle/actions/setup-gradle@3f131e8634966bd73d06cc69884922b02e6faf92 # v6.2.0
|
||||
- name: Cache Gradle User Home
|
||||
uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
|
||||
with:
|
||||
gradle-version: 9.6.1
|
||||
path: |
|
||||
~/.gradle/caches
|
||||
~/.gradle/wrapper
|
||||
key: gradle-${{ runner.os }}-${{ runner.arch }}-jdk-25-${{ hashFiles('gradle/wrapper/gradle-wrapper.properties', 'gradle/libs.versions.toml', 'settings.gradle', 'build.gradle', 'app/**/build.gradle', 'gradle/**/*.gradle') }}
|
||||
restore-keys: |
|
||||
gradle-${{ runner.os }}-${{ runner.arch }}-jdk-25-
|
||||
gradle-${{ runner.os }}-${{ runner.arch }}-
|
||||
|
||||
- name: Install Task
|
||||
uses: go-task/setup-task@01a4adf9db2d14c1de7a560f09170b6e0df736aa # v2.1.0
|
||||
@@ -271,7 +292,7 @@ jobs:
|
||||
# DigiCert KeyLocker Setup (Cloud HSM)
|
||||
- name: Setup DigiCert KeyLocker
|
||||
id: digicert-setup
|
||||
if: ${{ matrix.platform == 'windows-latest' && env.SM_API_KEY != '' && (github.event_name == 'release' || (github.event_name == 'workflow_dispatch' && github.event.inputs.sign != 'false') || github.ref == 'refs/heads/V2-master') }}
|
||||
if: ${{ startsWith(matrix.platform, 'windows') && env.SM_API_KEY != '' && (github.event_name == 'release' || (github.event_name == 'workflow_dispatch' && github.event.inputs.sign != 'false') || github.ref == 'refs/heads/V2-master') }}
|
||||
uses: digicert/ssm-code-signing@1d820463733701cf1484c7eb5d7d24a15ca2c454 # v1.2.1
|
||||
env:
|
||||
SM_API_KEY: ${{ secrets.SM_API_KEY }}
|
||||
@@ -281,7 +302,7 @@ jobs:
|
||||
SM_HOST: ${{ secrets.SM_HOST }}
|
||||
|
||||
- name: Setup DigiCert KeyLocker Certificate
|
||||
if: ${{ matrix.platform == 'windows-latest' && env.SM_API_KEY != '' && (github.event_name == 'release' || (github.event_name == 'workflow_dispatch' && github.event.inputs.sign != 'false') || github.ref == 'refs/heads/V2-master') }}
|
||||
if: ${{ startsWith(matrix.platform, 'windows') && env.SM_API_KEY != '' && (github.event_name == 'release' || (github.event_name == 'workflow_dispatch' && github.event.inputs.sign != 'false') || github.ref == 'refs/heads/V2-master') }}
|
||||
shell: pwsh
|
||||
run: |
|
||||
Write-Host "Setting up DigiCert KeyLocker environment..."
|
||||
@@ -316,7 +337,7 @@ jobs:
|
||||
|
||||
# Traditional PFX Certificate Import (fallback if KeyLocker not configured)
|
||||
- name: Import Windows Code Signing Certificate
|
||||
if: ${{ matrix.platform == 'windows-latest' && env.SM_API_KEY == '' && (github.event_name == 'release' || (github.event_name == 'workflow_dispatch' && github.event.inputs.sign != 'false') || github.ref == 'refs/heads/V2-master') }}
|
||||
if: ${{ startsWith(matrix.platform, 'windows') && env.SM_API_KEY == '' && (github.event_name == 'release' || (github.event_name == 'workflow_dispatch' && github.event.inputs.sign != 'false') || github.ref == 'refs/heads/V2-master') }}
|
||||
env:
|
||||
WINDOWS_CERTIFICATE: ${{ secrets.WINDOWS_CERTIFICATE }}
|
||||
WINDOWS_CERTIFICATE_PASSWORD: ${{ secrets.WINDOWS_CERTIFICATE_PASSWORD }}
|
||||
@@ -384,7 +405,7 @@ jobs:
|
||||
# Without this, signCommand failures are opaque (Tauri captures but drops
|
||||
# smctl's stderr) - running these loudly surfaces auth/env/keypair issues.
|
||||
- name: Preflight smctl
|
||||
if: ${{ matrix.platform == 'windows-latest' && env.SM_API_KEY != '' && (github.event_name == 'release' || (github.event_name == 'workflow_dispatch' && github.event.inputs.sign != 'false') || github.ref == 'refs/heads/V2-master') }}
|
||||
if: ${{ startsWith(matrix.platform, 'windows') && env.SM_API_KEY != '' && (github.event_name == 'release' || (github.event_name == 'workflow_dispatch' && github.event.inputs.sign != 'false') || github.ref == 'refs/heads/V2-master') }}
|
||||
shell: pwsh
|
||||
env:
|
||||
KEYPAIR_ALIAS: ${{ secrets.SM_KEYPAIR_ALIAS }}
|
||||
@@ -415,12 +436,12 @@ jobs:
|
||||
# smctl reads SM_HOST, SM_API_KEY, SM_CLIENT_CERT_FILE, SM_CLIENT_CERT_PASSWORD
|
||||
# from env (set by prior DigiCert setup step). No --config-file needed.
|
||||
- name: Configure Windows code signing
|
||||
if: ${{ matrix.platform == 'windows-latest' && env.SM_API_KEY != '' && (github.event_name == 'release' || (github.event_name == 'workflow_dispatch' && github.event.inputs.sign != 'false') || github.ref == 'refs/heads/V2-master') }}
|
||||
if: ${{ startsWith(matrix.platform, 'windows') && env.SM_API_KEY != '' && (github.event_name == 'release' || (github.event_name == 'workflow_dispatch' && github.event.inputs.sign != 'false') || github.ref == 'refs/heads/V2-master') }}
|
||||
shell: bash
|
||||
env:
|
||||
KEYPAIR_ALIAS: ${{ secrets.SM_KEYPAIR_ALIAS }}
|
||||
run: |
|
||||
cat > ./frontend/editor/src-tauri/tauri.windows.conf.json <<EOF
|
||||
cat > ./frontend/src-tauri/tauri.windows.conf.json <<EOF
|
||||
{
|
||||
"bundle": {
|
||||
"windows": {
|
||||
@@ -433,7 +454,7 @@ jobs:
|
||||
}
|
||||
EOF
|
||||
echo "Generated tauri.windows.conf.json (alias masked):"
|
||||
sed "s/${KEYPAIR_ALIAS}/***/g" ./frontend/editor/src-tauri/tauri.windows.conf.json
|
||||
sed "s/${KEYPAIR_ALIAS}/***/g" ./frontend/src-tauri/tauri.windows.conf.json
|
||||
|
||||
- name: Import release GPG signing key (Linux)
|
||||
if: matrix.platform == 'ubuntu-22.04' && env.RELEASE_GPG_PRIVATE_KEY != '' && (github.event_name == 'release' || (github.event_name == 'workflow_dispatch' && github.event.inputs.sign != 'false') || github.ref == 'refs/heads/V2-master')
|
||||
@@ -481,11 +502,59 @@ jobs:
|
||||
SM_CODE_SIGNING_CERT_SHA1_HASH: ${{ secrets.SM_CODE_SIGNING_CERT_SHA1_HASH }}
|
||||
CI: true
|
||||
with:
|
||||
projectPath: ./frontend/editor
|
||||
projectPath: ./frontend
|
||||
tauriScript: npx tauri
|
||||
args: ${{ matrix.args }}
|
||||
updaterJsonKeepUniversal: true
|
||||
|
||||
# Bundled libwayland conflicts with the host's on some distros (Fedora
|
||||
# Wayland: EGL_BAD_PARAMETER, blank window - #6878). Repack without it,
|
||||
# then regenerate the updater .sig (repack invalidates the original) and
|
||||
# GPG-sign again when release signing is on.
|
||||
- name: Strip bundled Wayland libs from AppImage
|
||||
if: matrix.platform == 'ubuntu-22.04'
|
||||
continue-on-error: true
|
||||
env:
|
||||
TAURI_SIGNING_PRIVATE_KEY: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY }}
|
||||
TAURI_SIGNING_PRIVATE_KEY_PASSWORD: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY_PASSWORD }}
|
||||
GPG_SIGN: ${{ (env.RELEASE_GPG_PRIVATE_KEY != '' && (github.event_name == 'release' || (github.event_name == 'workflow_dispatch' && github.event.inputs.sign != 'false') || github.ref == 'refs/heads/V2-master')) && '1' || '0' }}
|
||||
SIGN_KEY: ${{ vars.RELEASE_GPG_FINGERPRINT }}
|
||||
APPIMAGETOOL_SIGN_PASSPHRASE: ${{ secrets.RELEASE_GPG_PASSPHRASE }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
AI=$(find "$PWD/frontend/src-tauri/target" -name "*.AppImage" | head -1)
|
||||
if [ -z "$AI" ]; then echo "No AppImage found - skipping"; exit 0; fi
|
||||
chmod +x "$AI"
|
||||
WORK=$(mktemp -d)
|
||||
(cd "$WORK" && "$AI" --appimage-extract >/dev/null)
|
||||
if ! ls "$WORK/squashfs-root/usr/lib/"libwayland-* >/dev/null 2>&1; then
|
||||
echo "No bundled libwayland - nothing to strip"
|
||||
rm -rf "$WORK"
|
||||
exit 0
|
||||
fi
|
||||
rm -f "$WORK/squashfs-root/usr/lib/"libwayland-*
|
||||
curl -fsSL -o "$WORK/appimagetool" \
|
||||
https://github.com/AppImage/appimagetool/releases/download/continuous/appimagetool-x86_64.AppImage
|
||||
# Pinned checksum: never execute an unverified downloaded binary. On
|
||||
# mismatch (upstream rebuilt continuous) the step aborts and the
|
||||
# original AppImage ships unchanged - update the pin deliberately.
|
||||
echo "a6d71e2b6cd66f8e8d16c37ad164658985e0cf5fcaa950c90a482890cb9d13e0 $WORK/appimagetool" | sha256sum -c -
|
||||
chmod +x "$WORK/appimagetool"
|
||||
SIGN_ARGS=()
|
||||
if [ "$GPG_SIGN" = "1" ] && [ -n "${SIGN_KEY:-}" ]; then
|
||||
SIGN_ARGS=(--sign --sign-key "$SIGN_KEY")
|
||||
fi
|
||||
"$WORK/appimagetool" --appimage-extract-and-run "${SIGN_ARGS[@]}" "$WORK/squashfs-root" "$AI.new"
|
||||
# Updater payload signature must match the repacked bytes. The CLI
|
||||
# reads the key/password from env - never pass secrets as argv.
|
||||
if [ -n "${TAURI_SIGNING_PRIVATE_KEY:-}" ]; then
|
||||
(cd frontend && npx tauri signer sign "$AI.new")
|
||||
mv "$AI.new.sig" "$AI.sig"
|
||||
fi
|
||||
mv "$AI.new" "$AI"
|
||||
rm -rf "$WORK"
|
||||
echo "Stripped bundled libwayland from $(basename "$AI")"
|
||||
|
||||
- name: Clear release GPG key from runner keyring (Linux)
|
||||
if: always() && matrix.platform == 'ubuntu-22.04' && env.RELEASE_GPG_PRIVATE_KEY != '' && (github.event_name == 'release' || (github.event_name == 'workflow_dispatch' && github.event.inputs.sign != 'false') || github.ref == 'refs/heads/V2-master')
|
||||
env:
|
||||
@@ -502,14 +571,35 @@ jobs:
|
||||
# artifact. Tauri signs a COPY when bundling into the MSI and leaves the raw
|
||||
# cargo output unsigned, so checking it produces false negatives.
|
||||
- name: Verify Windows Code Signature
|
||||
if: ${{ matrix.platform == 'windows-latest' && env.SM_API_KEY != '' && (github.event_name == 'release' || (github.event_name == 'workflow_dispatch' && github.event.inputs.sign != 'false') || github.ref == 'refs/heads/V2-master') }}
|
||||
if: ${{ startsWith(matrix.platform, 'windows') && env.SM_API_KEY != '' && (github.event_name == 'release' || (github.event_name == 'workflow_dispatch' && github.event.inputs.sign != 'false') || github.ref == 'refs/heads/V2-master') }}
|
||||
timeout-minutes: 15
|
||||
shell: pwsh
|
||||
run: |
|
||||
# arm64 ships an NSIS installer, not an MSI. Tauri's signCommand signs the
|
||||
# inner exe before packing and the setup exe after, so verifying the setup
|
||||
# exe is the arm64 equivalent of the MSI + inner-exe check below.
|
||||
if ("${{ matrix.platform }}" -eq "windows-11-arm") {
|
||||
$setupExes = Get-ChildItem -Path "./frontend/src-tauri/target" -Filter "*-setup.exe" -Recurse -File
|
||||
if ($setupExes.Count -eq 0) {
|
||||
Write-Host "[ERROR] No NSIS installer found under target/"
|
||||
exit 1
|
||||
}
|
||||
foreach ($exe in $setupExes) {
|
||||
$sig = Get-AuthenticodeSignature -FilePath $exe.FullName
|
||||
Write-Host "NSIS installer: $($exe.Name) Status=$($sig.Status), Signer=$($sig.SignerCertificate.Subject)"
|
||||
if ($sig.Status -ne "Valid") {
|
||||
Write-Host "[ERROR] NSIS installer is not signed"
|
||||
exit 1
|
||||
}
|
||||
}
|
||||
Write-Host "[SUCCESS] NSIS installer is properly signed"
|
||||
exit 0
|
||||
}
|
||||
|
||||
$allSigned = $true
|
||||
|
||||
# Check MSI installer (outer wrapper - what users download)
|
||||
$msiFiles = Get-ChildItem -Path "./frontend/editor/src-tauri/target" -Filter "*.msi" -Recurse -File
|
||||
$msiFiles = Get-ChildItem -Path "./frontend/src-tauri/target" -Filter "*.msi" -Recurse -File
|
||||
if ($msiFiles.Count -eq 0) {
|
||||
Write-Host "[ERROR] No MSI found under target/"
|
||||
exit 1
|
||||
@@ -569,7 +659,7 @@ jobs:
|
||||
# but drops stderr when the command exits non-zero, making failures opaque.
|
||||
# The real errors live in smctl's log files - surface them here for debugging.
|
||||
- name: Dump smctl logs on failure
|
||||
if: ${{ failure() && matrix.platform == 'windows-latest' && env.SM_API_KEY != '' }}
|
||||
if: ${{ failure() && startsWith(matrix.platform, 'windows') && env.SM_API_KEY != '' }}
|
||||
shell: pwsh
|
||||
run: |
|
||||
$logDir = "$env:USERPROFILE\.signingmanager\logs"
|
||||
@@ -592,7 +682,7 @@ jobs:
|
||||
# Absolute dist path so the cd below can't break the copy targets.
|
||||
DIST="$GITHUB_WORKSPACE/dist"
|
||||
mkdir -p "$DIST"
|
||||
cd ./frontend/editor/src-tauri/target
|
||||
cd ./frontend/src-tauri/target
|
||||
|
||||
echo "=== tauri bundle artifacts ==="
|
||||
find . -path "*/bundle/*" \( -name "*.msi" -o -name "*.deb" \
|
||||
@@ -605,6 +695,11 @@ jobs:
|
||||
if [ "${{ matrix.platform }}" = "windows-latest" ]; then
|
||||
find . -name "*.msi" -exec cp {} "$DIST/Stirling-PDF-${{ matrix.name }}.msi" \;
|
||||
find . -name "*.msi.sig" -exec cp {} "$DIST/Stirling-PDF-${{ matrix.name }}.msi.sig" \;
|
||||
elif [ "${{ matrix.platform }}" = "windows-11-arm" ]; then
|
||||
# arm64 ships the NSIS installer (WiX MSI has no arm64 support in Tauri).
|
||||
# The setup exe is also its own updater payload (-> sibling .sig).
|
||||
find . -name "*-setup.exe" -exec cp {} "$DIST/Stirling-PDF-${{ matrix.name }}-setup.exe" \;
|
||||
find . -name "*-setup.exe.sig" -exec cp {} "$DIST/Stirling-PDF-${{ matrix.name }}-setup.exe.sig" \;
|
||||
elif [ "${{ matrix.platform }}" = "macos-15" ]; then
|
||||
# DMG = manual install; .app.tar.gz (+ .sig) = updater payload.
|
||||
# Raw .app is intentionally not shipped (hundreds of MB of uncompressed input).
|
||||
@@ -648,7 +743,7 @@ jobs:
|
||||
with:
|
||||
sparse-checkout: |
|
||||
.github/scripts/verify-updater-signatures.py
|
||||
frontend/editor/src-tauri/tauri.conf.json
|
||||
frontend/src-tauri/tauri.conf.json
|
||||
sparse-checkout-cone-mode: false
|
||||
|
||||
- name: Download all Tauri artifacts
|
||||
@@ -719,6 +814,10 @@ jobs:
|
||||
'bundles': ['Stirling-PDF-windows-x86_64.msi'],
|
||||
'targets': ['windows-x86_64-msi', 'windows-x86_64'],
|
||||
},
|
||||
{
|
||||
'bundles': ['Stirling-PDF-windows-arm64-setup.exe'],
|
||||
'targets': ['windows-aarch64-nsis', 'windows-aarch64'],
|
||||
},
|
||||
{
|
||||
'bundles': ['Stirling-PDF-macos-universal.app.tar.gz'],
|
||||
'targets': ['darwin-x86_64', 'darwin-aarch64'],
|
||||
@@ -793,7 +892,7 @@ jobs:
|
||||
run: |
|
||||
python3 -m pip install --quiet 'cryptography==44.0.0'
|
||||
python3 .github/scripts/verify-updater-signatures.py \
|
||||
./artifacts/tauri frontend/editor/src-tauri/tauri.conf.json
|
||||
./artifacts/tauri frontend/src-tauri/tauri.conf.json
|
||||
|
||||
# workflow_dispatch path requires platform=='all' so a single-platform
|
||||
# dispatch can't overwrite an existing release's full latest.json with a
|
||||
@@ -803,7 +902,7 @@ jobs:
|
||||
# instead of silently shipping a broken auto-update.
|
||||
- name: Upload binaries to Release
|
||||
if: (github.event_name == 'workflow_dispatch' && github.event.inputs.test_mode != 'true' && github.event.inputs.platform == 'all') || github.event_name == 'release' || github.ref == 'refs/heads/V2-master'
|
||||
uses: softprops/action-gh-release@b4309332981a82ec1c5618f44dd2e27cc8bfbfda # v3.0.0
|
||||
uses: softprops/action-gh-release@3d0d9888cb7fd7b750713d6e236d1fcb99157228 # v3.0.2
|
||||
with:
|
||||
tag_name: v${{ needs.determine-matrix.outputs.version }}
|
||||
# Don't regenerate/append notes on re-runs, and don't force this into the
|
||||
@@ -817,6 +916,7 @@ jobs:
|
||||
files: |
|
||||
./artifacts/**/*.jar
|
||||
./artifacts/**/*.msi
|
||||
./artifacts/**/*-setup.exe
|
||||
./artifacts/**/*.dmg
|
||||
./artifacts/**/*.app.tar.gz
|
||||
./artifacts/**/*.deb
|
||||
|
||||
@@ -65,20 +65,16 @@ jobs:
|
||||
java-version: "25"
|
||||
distribution: "temurin"
|
||||
|
||||
- name: Cache Gradle dependencies
|
||||
- name: Cache Gradle User Home
|
||||
uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
|
||||
with:
|
||||
path: |
|
||||
~/.gradle/caches
|
||||
~/.gradle/wrapper
|
||||
key: gradle-${{ runner.os }}-${{ hashFiles('**/gradle/wrapper/gradle-wrapper.properties') }}
|
||||
key: gradle-${{ runner.os }}-${{ runner.arch }}-jdk-25-${{ hashFiles('gradle/wrapper/gradle-wrapper.properties', 'gradle/libs.versions.toml', 'settings.gradle', 'build.gradle', 'app/**/build.gradle', 'gradle/**/*.gradle') }}
|
||||
restore-keys: |
|
||||
gradle-${{ runner.os }}-
|
||||
|
||||
- name: Setup Gradle
|
||||
uses: gradle/actions/setup-gradle@3f131e8634966bd73d06cc69884922b02e6faf92 # v6.2.0
|
||||
with:
|
||||
gradle-version: 9.6.1
|
||||
gradle-${{ runner.os }}-${{ runner.arch }}-jdk-25-
|
||||
gradle-${{ runner.os }}-${{ runner.arch }}-
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
id: buildx
|
||||
|
||||
@@ -39,10 +39,16 @@ jobs:
|
||||
java-version: "25"
|
||||
distribution: "temurin"
|
||||
|
||||
- name: Setup Gradle
|
||||
uses: gradle/actions/setup-gradle@3f131e8634966bd73d06cc69884922b02e6faf92 # v6.2.0
|
||||
- name: Cache Gradle User Home
|
||||
uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
|
||||
with:
|
||||
gradle-version: 9.6.1
|
||||
path: |
|
||||
~/.gradle/caches
|
||||
~/.gradle/wrapper
|
||||
key: gradle-${{ runner.os }}-${{ runner.arch }}-jdk-25-${{ hashFiles('gradle/wrapper/gradle-wrapper.properties', 'gradle/libs.versions.toml', 'settings.gradle', 'build.gradle', 'app/**/build.gradle', 'gradle/**/*.gradle') }}
|
||||
restore-keys: |
|
||||
gradle-${{ runner.os }}-${{ runner.arch }}-jdk-25-
|
||||
gradle-${{ runner.os }}-${{ runner.arch }}-
|
||||
|
||||
- name: Generate Swagger documentation
|
||||
run: ./gradlew :stirling-pdf:generateOpenApiDocs
|
||||
|
||||
@@ -84,12 +84,12 @@ jobs:
|
||||
body: |
|
||||
Auto-generated by ${{ steps.setup-bot.outputs.app-slug }}[bot].
|
||||
|
||||
Regenerates `frontend/editor/src/portal/generated/docsManifest.json`
|
||||
Regenerates `frontend/src/processor/proprietary/generated/docsManifest.json`
|
||||
from the Stirling docs repo via `npm run docs:sync`.
|
||||
labels: |
|
||||
Documentation
|
||||
github-actions
|
||||
Front End
|
||||
add-paths: frontend/editor/src/portal/generated/docsManifest.json
|
||||
add-paths: frontend/src/processor/proprietary/generated/docsManifest.json
|
||||
delete-branch: true
|
||||
sign-commits: true
|
||||
|
||||
@@ -12,7 +12,7 @@ on:
|
||||
- "app/proprietary/build.gradle"
|
||||
- "gradle/spotless.gradle"
|
||||
- "README.md"
|
||||
- "frontend/editor/public/locales/*/translation.toml"
|
||||
- "frontend/public/locales/*/translation.toml"
|
||||
- "app/core/src/main/resources/static/3rdPartyLicenses.json"
|
||||
- "scripts/ignore_translation.toml"
|
||||
|
||||
@@ -72,7 +72,7 @@ jobs:
|
||||
|
||||
- name: Sync translation TOML files
|
||||
run: |
|
||||
python .github/scripts/check_language_toml.py --reference-file "frontend/editor/public/locales/en-US/translation.toml" --branch main
|
||||
python .github/scripts/check_language_toml.py --reference-file "frontend/public/locales/en-US/translation.toml" --branch main
|
||||
|
||||
- name: Sort translation TOML files
|
||||
run: |
|
||||
@@ -80,7 +80,7 @@ jobs:
|
||||
|
||||
- name: Commit translation files
|
||||
run: |
|
||||
git add frontend/editor/public/locales/*/translation.toml
|
||||
git add frontend/public/locales/*/translation.toml
|
||||
git diff --staged --quiet || git commit -m ":memo: Sync translation files (TOML)" || echo "No changes detected"
|
||||
|
||||
- name: Sync README.md
|
||||
@@ -110,7 +110,7 @@ jobs:
|
||||
This Pull Request was automatically generated to synchronize updates to translation files and documentation. Below are the details of the changes made:
|
||||
|
||||
#### **1. Synchronization of Translation Files**
|
||||
- Updated translation files (`frontend/editor/public/locales/*/translation.toml`) to reflect changes in the reference file `en-US/translation.toml`.
|
||||
- Updated translation files (`frontend/public/locales/*/translation.toml`) to reflect changes in the reference file `en-US/translation.toml`.
|
||||
- Ensured consistency and synchronization across all supported language files.
|
||||
- Highlighted any missing or incomplete translations.
|
||||
- **Format**: TOML
|
||||
@@ -135,5 +135,5 @@ jobs:
|
||||
sign-commits: true
|
||||
add-paths: |
|
||||
README.md
|
||||
frontend/editor/public/locales/*/translation.toml
|
||||
frontend/public/locales/*/translation.toml
|
||||
scripts/ignore_translation.toml
|
||||
|
||||
@@ -12,7 +12,7 @@ on:
|
||||
workflow_call:
|
||||
inputs:
|
||||
platform:
|
||||
description: "Platform to build (windows, macos, linux, windows-macos, or all)."
|
||||
description: "Platform to build (windows, windows-arm64, macos, linux, windows-macos, or all)."
|
||||
required: false
|
||||
type: string
|
||||
default: "all"
|
||||
@@ -29,13 +29,14 @@ on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
platform:
|
||||
description: "Platform to build (windows, macos, linux, windows-macos, or all)"
|
||||
description: "Platform to build (windows, windows-arm64, macos, linux, windows-macos, or all)"
|
||||
required: true
|
||||
default: "all"
|
||||
type: choice
|
||||
options:
|
||||
- all
|
||||
- windows
|
||||
- windows-arm64
|
||||
- macos
|
||||
- linux
|
||||
- windows-macos
|
||||
@@ -73,15 +74,19 @@ jobs:
|
||||
PLATFORM: ${{ inputs.platform }}
|
||||
run: |
|
||||
WINDOWS='{"platform":"windows-latest","args":"--target x86_64-pc-windows-msvc","name":"windows-x86_64","jpdfium_platforms":"windows-x64"}'
|
||||
# ARM64: NSIS only (WiX MSI has no arm64 support in Tauri) and no JPDFium
|
||||
# natives yet - flip jpdfium_platforms to windows-arm64 once JPDFium ships it.
|
||||
WINDOWS_ARM64='{"platform":"windows-11-arm","args":"--target aarch64-pc-windows-msvc --bundles nsis","name":"windows-arm64","jpdfium_platforms":"none"}'
|
||||
MACOS='{"platform":"macos-15","args":"--target universal-apple-darwin","name":"macos-universal","jpdfium_platforms":"darwin-arm64,darwin-x64"}'
|
||||
LINUX='{"platform":"ubuntu-22.04","args":"","name":"linux-x86_64","jpdfium_platforms":"linux-x64"}'
|
||||
|
||||
case "$PLATFORM" in
|
||||
windows) ENTRIES=("$WINDOWS") ;;
|
||||
windows) ENTRIES=("$WINDOWS" "$WINDOWS_ARM64") ;;
|
||||
windows-arm64) ENTRIES=("$WINDOWS_ARM64") ;;
|
||||
macos) ENTRIES=("$MACOS") ;;
|
||||
linux) ENTRIES=("$LINUX") ;;
|
||||
windows-macos) ENTRIES=("$WINDOWS" "$MACOS") ;;
|
||||
*) ENTRIES=("$WINDOWS" "$MACOS" "$LINUX") ;;
|
||||
*) ENTRIES=("$WINDOWS" "$WINDOWS_ARM64" "$MACOS" "$LINUX") ;;
|
||||
esac
|
||||
|
||||
# Drop macOS entries when Apple certificate secret is unavailable
|
||||
@@ -147,7 +152,7 @@ jobs:
|
||||
- name: Cache Rust build
|
||||
uses: Swatinem/rust-cache@c19371144df3bb44fab255c43d04cbc2ab54d1c4 # v2.9.1
|
||||
with:
|
||||
workspaces: frontend/editor/src-tauri
|
||||
workspaces: frontend/src-tauri
|
||||
# Stable key shared across workflows so the nightly warmer.
|
||||
# rust-cache still appends OS + rustc + Cargo.lock.
|
||||
shared-key: tauri-${{ matrix.name }}
|
||||
@@ -167,16 +172,23 @@ jobs:
|
||||
if: matrix.platform == 'macos-15'
|
||||
run: echo "X64_JAVA_HOME=$JAVA_HOME" >> "$GITHUB_ENV"
|
||||
|
||||
# Temurin has no windows-aarch64 JDK 25 yet; Microsoft OpenJDK does.
|
||||
- name: Set up JDK 25
|
||||
uses: actions/setup-java@be666c2fcd27ec809703dec50e508c2fdc7f6654 # v5.2.0
|
||||
with:
|
||||
java-version: "25"
|
||||
distribution: "temurin"
|
||||
distribution: ${{ matrix.platform == 'windows-11-arm' && 'microsoft' || 'temurin' }}
|
||||
|
||||
- name: Setup Gradle
|
||||
uses: gradle/actions/setup-gradle@3f131e8634966bd73d06cc69884922b02e6faf92 # v6.2.0
|
||||
- name: Cache Gradle User Home
|
||||
uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
|
||||
with:
|
||||
gradle-version: 9.6.1
|
||||
path: |
|
||||
~/.gradle/caches
|
||||
~/.gradle/wrapper
|
||||
key: gradle-${{ runner.os }}-${{ runner.arch }}-jdk-25-${{ hashFiles('gradle/wrapper/gradle-wrapper.properties', 'gradle/libs.versions.toml', 'settings.gradle', 'build.gradle', 'app/**/build.gradle', 'gradle/**/*.gradle') }}
|
||||
restore-keys: |
|
||||
gradle-${{ runner.os }}-${{ runner.arch }}-jdk-25-
|
||||
gradle-${{ runner.os }}-${{ runner.arch }}-
|
||||
|
||||
- name: Setup Task
|
||||
uses: go-task/setup-task@01a4adf9db2d14c1de7a560f09170b6e0df736aa # v2.1.0
|
||||
@@ -203,7 +215,7 @@ jobs:
|
||||
# DigiCert KeyLocker Setup (Cloud HSM)
|
||||
- name: Setup DigiCert KeyLocker
|
||||
id: digicert-setup
|
||||
if: ${{ inputs.sign && matrix.platform == 'windows-latest' && env.SM_API_KEY != '' && github.ref == 'refs/heads/main' }}
|
||||
if: ${{ inputs.sign && startsWith(matrix.platform, 'windows') && env.SM_API_KEY != '' && github.ref == 'refs/heads/main' }}
|
||||
uses: digicert/ssm-code-signing@1d820463733701cf1484c7eb5d7d24a15ca2c454 # v1.2.1
|
||||
env:
|
||||
SM_API_KEY: ${{ secrets.SM_API_KEY }}
|
||||
@@ -213,7 +225,7 @@ jobs:
|
||||
SM_HOST: ${{ secrets.SM_HOST }}
|
||||
|
||||
- name: Setup DigiCert KeyLocker Certificate
|
||||
if: ${{ inputs.sign && matrix.platform == 'windows-latest' && env.SM_API_KEY != '' && github.ref == 'refs/heads/main' }}
|
||||
if: ${{ inputs.sign && startsWith(matrix.platform, 'windows') && env.SM_API_KEY != '' && github.ref == 'refs/heads/main' }}
|
||||
shell: pwsh
|
||||
run: |
|
||||
Write-Host "Setting up DigiCert KeyLocker environment..."
|
||||
@@ -248,7 +260,7 @@ jobs:
|
||||
|
||||
# Traditional PFX Certificate Import (fallback if KeyLocker not configured)
|
||||
- name: Import Windows Code Signing Certificate
|
||||
if: ${{ inputs.sign && matrix.platform == 'windows-latest' && env.SM_API_KEY == '' && github.ref == 'refs/heads/main' }}
|
||||
if: ${{ inputs.sign && startsWith(matrix.platform, 'windows') && env.SM_API_KEY == '' && github.ref == 'refs/heads/main' }}
|
||||
env:
|
||||
WINDOWS_CERTIFICATE: ${{ secrets.WINDOWS_CERTIFICATE }}
|
||||
WINDOWS_CERTIFICATE_PASSWORD: ${{ secrets.WINDOWS_CERTIFICATE_PASSWORD }}
|
||||
@@ -323,7 +335,7 @@ jobs:
|
||||
ls -la /usr/bin/hd* || echo "No hd* tools found"
|
||||
|
||||
- name: Preflight smctl
|
||||
if: ${{ inputs.sign && matrix.platform == 'windows-latest' && env.SM_API_KEY != '' && github.ref == 'refs/heads/main' }}
|
||||
if: ${{ inputs.sign && startsWith(matrix.platform, 'windows') && env.SM_API_KEY != '' && github.ref == 'refs/heads/main' }}
|
||||
shell: pwsh
|
||||
env:
|
||||
KEYPAIR_ALIAS: ${{ secrets.SM_KEYPAIR_ALIAS }}
|
||||
@@ -336,12 +348,12 @@ jobs:
|
||||
if ($LASTEXITCODE -ne 0) { Write-Host "[WARN] smctl windows certsync returned non-zero - continuing" }
|
||||
|
||||
- name: Configure Windows code signing
|
||||
if: ${{ inputs.sign && matrix.platform == 'windows-latest' && env.SM_API_KEY != '' && github.ref == 'refs/heads/main' }}
|
||||
if: ${{ inputs.sign && startsWith(matrix.platform, 'windows') && env.SM_API_KEY != '' && github.ref == 'refs/heads/main' }}
|
||||
shell: bash
|
||||
env:
|
||||
KEYPAIR_ALIAS: ${{ secrets.SM_KEYPAIR_ALIAS }}
|
||||
run: |
|
||||
cat > ./frontend/editor/src-tauri/tauri.windows.conf.json <<EOF
|
||||
cat > ./frontend/src-tauri/tauri.windows.conf.json <<EOF
|
||||
{
|
||||
"bundle": {
|
||||
"windows": {
|
||||
@@ -400,7 +412,7 @@ jobs:
|
||||
SM_CODE_SIGNING_CERT_SHA1_HASH: ${{ secrets.SM_CODE_SIGNING_CERT_SHA1_HASH }}
|
||||
CI: true
|
||||
with:
|
||||
projectPath: ./frontend/editor
|
||||
projectPath: ./frontend
|
||||
tauriScript: npx tauri
|
||||
# Linux: build deb+rpm only here (deb-only on minimal smoke builds).
|
||||
# AppImage runs in its own continue-on-error step below so its
|
||||
@@ -420,7 +432,7 @@ jobs:
|
||||
VITE_SAAS_BACKEND_API_URL: ${{ secrets.VITE_SAAS_BACKEND_API_URL || 'https://api.stirlingpdf.com' }}
|
||||
CI: true
|
||||
with:
|
||||
projectPath: ./frontend/editor
|
||||
projectPath: ./frontend
|
||||
tauriScript: npx tauri
|
||||
# Linux: build deb+rpm only here (deb-only on minimal smoke builds).
|
||||
# AppImage runs in its own continue-on-error step below so its
|
||||
@@ -448,10 +460,41 @@ jobs:
|
||||
VITE_SAAS_BACKEND_API_URL: ${{ secrets.VITE_SAAS_BACKEND_API_URL || 'https://api.stirlingpdf.com' }}
|
||||
CI: true
|
||||
with:
|
||||
projectPath: ./frontend/editor
|
||||
projectPath: ./frontend
|
||||
tauriScript: npx tauri
|
||||
args: --bundles appimage
|
||||
|
||||
# Bundled libwayland conflicts with the host's on some distros (Fedora
|
||||
# Wayland: EGL_BAD_PARAMETER, blank window - #6878). The AppImage
|
||||
# ecosystem excludelist agrees these libs must come from the system.
|
||||
- name: Strip bundled Wayland libs from AppImage
|
||||
if: matrix.platform == 'ubuntu-22.04' && !inputs.minimal
|
||||
continue-on-error: true
|
||||
run: |
|
||||
set -euo pipefail
|
||||
AI=$(find "$PWD/frontend/src-tauri/target" -name "*.AppImage" | head -1)
|
||||
if [ -z "$AI" ]; then echo "No AppImage found - skipping"; exit 0; fi
|
||||
chmod +x "$AI"
|
||||
WORK=$(mktemp -d)
|
||||
(cd "$WORK" && "$AI" --appimage-extract >/dev/null)
|
||||
if ! ls "$WORK/squashfs-root/usr/lib/"libwayland-* >/dev/null 2>&1; then
|
||||
echo "No bundled libwayland - nothing to strip"
|
||||
rm -rf "$WORK"
|
||||
exit 0
|
||||
fi
|
||||
rm -f "$WORK/squashfs-root/usr/lib/"libwayland-*
|
||||
curl -fsSL -o "$WORK/appimagetool" \
|
||||
https://github.com/AppImage/appimagetool/releases/download/continuous/appimagetool-x86_64.AppImage
|
||||
# Pinned checksum: never execute an unverified downloaded binary. On
|
||||
# mismatch (upstream rebuilt continuous) the step aborts and the
|
||||
# original AppImage ships unchanged - update the pin deliberately.
|
||||
echo "a6d71e2b6cd66f8e8d16c37ad164658985e0cf5fcaa950c90a482890cb9d13e0 $WORK/appimagetool" | sha256sum -c -
|
||||
chmod +x "$WORK/appimagetool"
|
||||
"$WORK/appimagetool" --appimage-extract-and-run "$WORK/squashfs-root" "$AI.new"
|
||||
mv "$AI.new" "$AI"
|
||||
rm -rf "$WORK"
|
||||
echo "Stripped bundled libwayland from $(basename "$AI")"
|
||||
|
||||
- name: Clear release GPG key from runner keyring (Linux)
|
||||
if: always() && inputs.sign && matrix.platform == 'ubuntu-22.04' && env.RELEASE_GPG_PRIVATE_KEY != '' && github.ref == 'refs/heads/main'
|
||||
env:
|
||||
@@ -466,7 +509,7 @@ jobs:
|
||||
if: env.SIGN_BUNDLE == 'true' && matrix.platform == 'macos-15'
|
||||
run: |
|
||||
echo "🔍 Verifying notarization status..."
|
||||
cd ./frontend/editor/src-tauri/target
|
||||
cd ./frontend/src-tauri/target
|
||||
DMG_FILE=$(find . -name "*.dmg" | head -1)
|
||||
if [ -n "$DMG_FILE" ]; then
|
||||
echo "Found DMG: $DMG_FILE"
|
||||
@@ -483,13 +526,16 @@ jobs:
|
||||
# Absolute dist path so the cd below can't break the copy targets.
|
||||
DIST="$GITHUB_WORKSPACE/dist"
|
||||
mkdir -p "$DIST"
|
||||
cd ./frontend/editor/src-tauri/target
|
||||
cd ./frontend/src-tauri/target
|
||||
|
||||
# Find and rename artifacts based on platform
|
||||
if [ "${{ matrix.platform }}" = "windows-latest" ]; then
|
||||
# Only ship the MSI installer. The loose exe and WiX toolset exes
|
||||
# are not the user-facing installer - the MSI contains the signed inner exe.
|
||||
find . -name "*.msi" -exec cp {} "$DIST/Stirling-PDF-${{ matrix.name }}.msi" \;
|
||||
elif [ "${{ matrix.platform }}" = "windows-11-arm" ]; then
|
||||
# arm64 ships the NSIS installer (WiX MSI has no arm64 support in Tauri).
|
||||
find . -name "*-setup.exe" -exec cp {} "$DIST/Stirling-PDF-${{ matrix.name }}-setup.exe" \;
|
||||
elif [ "${{ matrix.platform }}" = "macos-15" ]; then
|
||||
find . -name "*.dmg" -exec cp {} "$DIST/Stirling-PDF-${{ matrix.name }}.dmg" \;
|
||||
else
|
||||
@@ -501,9 +547,28 @@ jobs:
|
||||
# Verify the MSI AND the inner exe extracted from it are signed.
|
||||
# The inner exe is what gets installed on users' machines and what AV scans.
|
||||
- name: Verify Windows Code Signature
|
||||
if: inputs.sign && matrix.platform == 'windows-latest' && env.SM_API_KEY != '' && github.ref == 'refs/heads/main'
|
||||
if: inputs.sign && startsWith(matrix.platform, 'windows') && env.SM_API_KEY != '' && github.ref == 'refs/heads/main'
|
||||
shell: pwsh
|
||||
run: |
|
||||
# arm64 ships an NSIS installer, not an MSI. Tauri's signCommand signs the
|
||||
# inner exe before packing and the setup exe after, so verifying the setup
|
||||
# exe is the arm64 equivalent of the MSI + inner-exe check below.
|
||||
if ("${{ matrix.platform }}" -eq "windows-11-arm") {
|
||||
$exePath = "./dist/Stirling-PDF-${{ matrix.name }}-setup.exe"
|
||||
if (-not (Test-Path $exePath)) {
|
||||
Write-Host "[ERROR] NSIS installer not found at $exePath"
|
||||
exit 1
|
||||
}
|
||||
$sig = Get-AuthenticodeSignature -FilePath $exePath
|
||||
Write-Host "NSIS installer: Status=$($sig.Status), Signer=$($sig.SignerCertificate.Subject)"
|
||||
if ($sig.Status -ne "Valid") {
|
||||
Write-Host "[ERROR] NSIS installer is not signed"
|
||||
exit 1
|
||||
}
|
||||
Write-Host "[SUCCESS] NSIS installer is properly signed"
|
||||
exit 0
|
||||
}
|
||||
|
||||
$allSigned = $true
|
||||
$msiPath = "./dist/Stirling-PDF-${{ matrix.name }}.msi"
|
||||
|
||||
@@ -549,7 +614,7 @@ jobs:
|
||||
Write-Host "[SUCCESS] MSI and inner exe are properly signed"
|
||||
|
||||
- name: Dump smctl logs on failure
|
||||
if: ${{ failure() && matrix.platform == 'windows-latest' && env.SM_API_KEY != '' }}
|
||||
if: ${{ failure() && startsWith(matrix.platform, 'windows') && env.SM_API_KEY != '' }}
|
||||
shell: pwsh
|
||||
run: |
|
||||
$logDir = "$env:USERPROFILE\.signingmanager\logs"
|
||||
@@ -573,10 +638,10 @@ jobs:
|
||||
- name: Verify build artifacts
|
||||
shell: bash
|
||||
run: |
|
||||
cd ./frontend/editor/src-tauri/target
|
||||
cd ./frontend/src-tauri/target
|
||||
|
||||
# Check for expected artifacts based on platform
|
||||
if [ "${{ matrix.platform }}" = "windows-latest" ]; then
|
||||
if [ "${{ matrix.platform }}" = "windows-latest" ] || [ "${{ matrix.platform }}" = "windows-11-arm" ]; then
|
||||
echo "Checking for Windows artifacts..."
|
||||
find . -name "*.exe" -o -name "*.msi" | head -5
|
||||
if [ $(find . -name "*.exe" | wc -l) -eq 0 ]; then
|
||||
@@ -604,7 +669,7 @@ jobs:
|
||||
- name: Test artifact sizes
|
||||
shell: bash
|
||||
run: |
|
||||
cd ./frontend/editor/src-tauri/target
|
||||
cd ./frontend/src-tauri/target
|
||||
echo "Artifact sizes for ${{ matrix.name }}:"
|
||||
find . -name "*.exe" -o -name "*.dmg" -o -name "*.deb" -o -name "*.rpm" -o -name "*.AppImage" -o -name "*.msi" | while read file; do
|
||||
if [ -f "$file" ]; then
|
||||
@@ -655,6 +720,7 @@ jobs:
|
||||
// Map of expected artifact names to display info
|
||||
const artifactMap = {
|
||||
'Stirling-PDF-windows-x86_64': { icon: '🪟', platform: 'Windows x64', files: '.exe, .msi' },
|
||||
'Stirling-PDF-windows-arm64': { icon: '🪟', platform: 'Windows ARM64', files: '-setup.exe (NSIS)' },
|
||||
'Stirling-PDF-macos-universal': { icon: '🍎', platform: 'macOS Universal', files: '.dmg' },
|
||||
'Stirling-PDF-linux-x86_64': { icon: '🐧', platform: 'Linux x64', files: '.deb, .rpm, .AppImage' }
|
||||
};
|
||||
|
||||
@@ -84,20 +84,16 @@ jobs:
|
||||
java-version: "25"
|
||||
distribution: "temurin"
|
||||
|
||||
- name: Cache Gradle dependency artifacts
|
||||
- name: Cache Gradle User Home
|
||||
uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
|
||||
with:
|
||||
path: |
|
||||
~/.gradle/caches
|
||||
~/.gradle/wrapper
|
||||
~/.gradle/caches/modules-2/files-2.1
|
||||
~/.gradle/caches/modules-2/metadata-2.*
|
||||
key: gradle-deps-${{ runner.os }}-jdk-25-${{ hashFiles('**/gradle/wrapper/gradle-wrapper.properties', '**/*.gradle', '**/*.gradle.kts', 'settings.gradle', 'settings.gradle.kts', 'gradle/libs.versions.toml') }}
|
||||
|
||||
- name: Setup Gradle
|
||||
uses: gradle/actions/setup-gradle@3f131e8634966bd73d06cc69884922b02e6faf92 # v6.2.0
|
||||
with:
|
||||
gradle-version: 9.6.1
|
||||
cache-disabled: true
|
||||
key: gradle-${{ runner.os }}-${{ runner.arch }}-jdk-25-${{ hashFiles('gradle/wrapper/gradle-wrapper.properties', 'gradle/libs.versions.toml', 'settings.gradle', 'build.gradle', 'app/**/build.gradle', 'gradle/**/*.gradle') }}
|
||||
restore-keys: |
|
||||
gradle-${{ runner.os }}-${{ runner.arch }}-jdk-25-
|
||||
gradle-${{ runner.os }}-${{ runner.arch }}-
|
||||
|
||||
- name: Install Task
|
||||
uses: go-task/setup-task@01a4adf9db2d14c1de7a560f09170b6e0df736aa # v2.1.0
|
||||
|
||||
@@ -38,10 +38,16 @@ jobs:
|
||||
java-version: "25"
|
||||
distribution: "temurin"
|
||||
|
||||
- name: Setup Gradle
|
||||
uses: gradle/actions/setup-gradle@3f131e8634966bd73d06cc69884922b02e6faf92 # v6.2.0
|
||||
- name: Cache Gradle User Home
|
||||
uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
|
||||
with:
|
||||
gradle-version: 9.6.1
|
||||
path: |
|
||||
~/.gradle/caches
|
||||
~/.gradle/wrapper
|
||||
key: gradle-${{ runner.os }}-${{ runner.arch }}-jdk-25-${{ hashFiles('gradle/wrapper/gradle-wrapper.properties', 'gradle/libs.versions.toml', 'settings.gradle', 'build.gradle', 'app/**/build.gradle', 'gradle/**/*.gradle') }}
|
||||
restore-keys: |
|
||||
gradle-${{ runner.os }}-${{ runner.arch }}-jdk-25-
|
||||
gradle-${{ runner.os }}-${{ runner.arch }}-
|
||||
|
||||
- name: Build with Gradle
|
||||
run: ./gradlew build
|
||||
|
||||
+7
-4
@@ -22,6 +22,9 @@ pipeline/
|
||||
customFiles/
|
||||
configs/
|
||||
watchedFolders/
|
||||
# The rule above targets the app's runtime watched-folders working dir, but it
|
||||
# also matches this frontend source component dir; keep the source tracked.
|
||||
!frontend/src/editor/proprietary/components/watchedFolders/
|
||||
clientWebUI/
|
||||
# Scratch dir used by local fixture-regeneration runs (see
|
||||
# app/proprietary/src/test/resources/db-migration-fixtures/README.md).
|
||||
@@ -171,7 +174,7 @@ app/proprietary/build
|
||||
common/build
|
||||
proprietary/build
|
||||
stirling-pdf/build
|
||||
frontend/editor/src-tauri/provisioner/target
|
||||
frontend/src-tauri/provisioner/target
|
||||
|
||||
# Byte-compiled / optimized / DLL files
|
||||
__pycache__/
|
||||
@@ -222,7 +225,7 @@ out/
|
||||
*.asc
|
||||
|
||||
# Allow test fixture certificates (synthetic, no real credentials)
|
||||
!frontend/editor/src/core/tests/test-fixtures/certs/**
|
||||
!frontend/src/editor/core/tests/test-fixtures/certs/**
|
||||
|
||||
# SSH Keys
|
||||
*.pub
|
||||
@@ -264,7 +267,7 @@ node_modules/
|
||||
*compact*.json
|
||||
test_batch.json
|
||||
*.backup.*.json
|
||||
frontend/editor/public/locales/*/translation.backup*.json
|
||||
frontend/public/locales/*/translation.backup*.json
|
||||
|
||||
# Development/build artifacts
|
||||
.gradle-cache/
|
||||
@@ -289,4 +292,4 @@ docs/type3/signatures/
|
||||
*.playwright-mcp.png
|
||||
|
||||
# Local screenshot artifacts from *-screenshots.spec.ts
|
||||
frontend/editor/screenshots/
|
||||
frontend/screenshots/
|
||||
|
||||
+2
-2
@@ -15,10 +15,10 @@ testing/compose/validate-mcp-test.sh:curl-auth-header:92
|
||||
testing/compose/validate-mcp-test.sh:curl-auth-header:116
|
||||
|
||||
# Storybook example showing curl with a fake Bearer token placeholder (sk_live_a3f8...).
|
||||
frontend/editor/src/proprietary/ui/CodeBlock.stories.tsx:curl-auth-header:5
|
||||
frontend/src/editor/proprietary/ui/CodeBlock.stories.tsx:curl-auth-header:5
|
||||
|
||||
# Truncated placeholder API key in portal docs example (sk_live_8f2c...e10) - not a real secret.
|
||||
frontend/editor/src/portal/components/docs/GettingStartedSection.tsx:generic-api-key:30
|
||||
frontend/src/processor/proprietary/components/docs/GettingStartedSection.tsx:generic-api-key:30
|
||||
|
||||
# False positive: generic-api-key matches the Java type name "X509Certificate"
|
||||
# in a method signature (CreateSignatureBase.resolveSignatureAlgorithm) - not a secret.
|
||||
|
||||
+1
-1
@@ -1,5 +1,5 @@
|
||||
{
|
||||
"ignoredFiles": [
|
||||
"frontend/editor/src-tauri/icons/icon.png"
|
||||
"frontend/src-tauri/icons/icon.png"
|
||||
]
|
||||
}
|
||||
|
||||
@@ -146,6 +146,7 @@ tasks:
|
||||
|
||||
swagger:
|
||||
desc: "Generate OpenAPI docs"
|
||||
run: once
|
||||
cmds:
|
||||
- cmd: cmd /c ".\gradlew.bat :stirling-pdf:copySwaggerDoc"
|
||||
platforms: [windows]
|
||||
|
||||
+8
-18
@@ -22,6 +22,7 @@ vars:
|
||||
linux-amd64) echo "linux-x64";;
|
||||
linux-arm64) echo "linux-arm64";;
|
||||
windows-amd64) echo "windows-x64";;
|
||||
windows-arm64) echo "none";; # no JPDFium windows-arm64 natives published yet
|
||||
*) echo "all";;
|
||||
esac
|
||||
fi
|
||||
@@ -38,7 +39,6 @@ tasks:
|
||||
provisioner:
|
||||
desc: "Build installer provisioner"
|
||||
platforms: [windows]
|
||||
dir: editor
|
||||
cmds:
|
||||
- node scripts/build-provisioner.mjs
|
||||
|
||||
@@ -46,55 +46,48 @@ tasks:
|
||||
desc: "Start Tauri desktop dev mode"
|
||||
deps: [prepare]
|
||||
ignore_error: true
|
||||
dir: editor
|
||||
cmds:
|
||||
- npx tauri dev --no-watch
|
||||
|
||||
build:
|
||||
desc: "Build Tauri desktop app (production)"
|
||||
deps: [prepare]
|
||||
dir: editor
|
||||
cmds:
|
||||
- npx tauri build
|
||||
|
||||
build:dev:
|
||||
desc: "Build Tauri desktop app (dev, no bundling)"
|
||||
deps: [prepare]
|
||||
dir: editor
|
||||
cmds:
|
||||
- npx tauri build --no-bundle
|
||||
|
||||
build:dev:mac:
|
||||
desc: "Build Tauri desktop .app bundle (macOS)"
|
||||
deps: [prepare]
|
||||
dir: editor
|
||||
cmds:
|
||||
- npx tauri build --bundles app --config '{"bundle":{"createUpdaterArtifacts":false}}'
|
||||
|
||||
build:dev:windows:
|
||||
desc: "Build Tauri desktop NSIS installer (Windows)"
|
||||
deps: [prepare]
|
||||
dir: editor
|
||||
cmds:
|
||||
- npx tauri build --bundles nsis --config '{"bundle":{"createUpdaterArtifacts":false}}'
|
||||
|
||||
build:dev:linux:
|
||||
desc: "Build Tauri desktop AppImage (Linux)"
|
||||
deps: [prepare]
|
||||
dir: editor
|
||||
cmds:
|
||||
- npx tauri build --bundles appimage --config '{"bundle":{"createUpdaterArtifacts":false}}'
|
||||
|
||||
test:
|
||||
desc: "Run Tauri/Cargo tests"
|
||||
deps: [prepare]
|
||||
dir: editor/src-tauri
|
||||
dir: src-tauri
|
||||
cmds:
|
||||
- cargo test
|
||||
|
||||
clean:
|
||||
desc: "Clean Tauri/Cargo build artifacts"
|
||||
dir: editor
|
||||
cmds:
|
||||
- task: jlink:clean
|
||||
- cd src-tauri && cargo clean
|
||||
@@ -116,7 +109,6 @@ tasks:
|
||||
|
||||
jlink:verify:
|
||||
desc: "Fail the build if the bundled JRE is older than the app JAR requires"
|
||||
dir: editor
|
||||
env:
|
||||
REQUIRED_JAVA: "{{.REQUIRED_JAVA}}"
|
||||
cmds:
|
||||
@@ -134,15 +126,15 @@ tasks:
|
||||
platforms: [windows]
|
||||
- cmd: ./gradlew bootJar --no-daemon -PjpdfiumPlatforms={{.JPDFIUM_PLATFORMS}}
|
||||
platforms: [linux, darwin]
|
||||
- mkdir -p frontend/editor/src-tauri/libs
|
||||
- cp app/core/build/libs/stirling-pdf-*.jar frontend/editor/src-tauri/libs/
|
||||
- mkdir -p frontend/src-tauri/libs
|
||||
- cp app/core/build/libs/stirling-pdf-*.jar frontend/src-tauri/libs/
|
||||
status:
|
||||
- test -f frontend/editor/src-tauri/libs/stirling-pdf-*.jar
|
||||
- test -f frontend/src-tauri/libs/stirling-pdf-*.jar
|
||||
|
||||
jlink:runtime:
|
||||
desc: "Create custom JRE with jlink"
|
||||
deps: [jlink:jar]
|
||||
dir: editor/src-tauri
|
||||
dir: src-tauri
|
||||
cmds:
|
||||
- rm -rf runtime/jre
|
||||
- mkdir -p runtime
|
||||
@@ -194,15 +186,14 @@ tasks:
|
||||
# `desktop:build` run `jlink:clean` first to force a fresh build.
|
||||
- cmd: chmod -R u+w runtime/jre
|
||||
platforms: [linux, darwin]
|
||||
# Escape the $ so Task's shell doesn't expand $_/$false to empty before PowerShell sees them.
|
||||
- cmd: powershell -NoProfile -Command "Get-ChildItem -Recurse runtime/jre | ForEach-Object { \$_.IsReadOnly = \$false }"
|
||||
- cmd: powershell -NoProfile -Command "Get-ChildItem -Recurse runtime/jre | ForEach-Object { $_.IsReadOnly = $false }"
|
||||
platforms: [windows]
|
||||
status:
|
||||
- test -f runtime/jre/release
|
||||
|
||||
jlink:clean:
|
||||
desc: "Remove JLink runtime and bundled JARs"
|
||||
dir: editor/src-tauri
|
||||
dir: src-tauri
|
||||
cmds:
|
||||
- rm -rf libs runtime
|
||||
|
||||
@@ -215,7 +206,6 @@ tasks:
|
||||
desc: "Create universal (arm64+x86_64) JRE for the macOS Tauri build"
|
||||
deps: [jlink:jar]
|
||||
platforms: [darwin]
|
||||
dir: editor
|
||||
env:
|
||||
JLINK_MODULES: "{{.JLINK_MODULES}}"
|
||||
OUTPUT_DIR: src-tauri/runtime/jre
|
||||
|
||||
+5
-5
@@ -3,14 +3,14 @@ version: '3'
|
||||
tasks:
|
||||
install:
|
||||
desc: "Install Playwright browsers"
|
||||
dir: frontend/editor
|
||||
dir: frontend
|
||||
deps: [ ':frontend:install' ]
|
||||
cmds:
|
||||
- npx playwright install {{.CLI_ARGS}} --with-deps
|
||||
|
||||
stubbed:
|
||||
desc: "Run stubbed E2E tests"
|
||||
dir: frontend/editor
|
||||
dir: frontend
|
||||
deps: [ ':frontend:prepare' ]
|
||||
cmds:
|
||||
- npx playwright test --project=stubbed {{.CLI_ARGS}}
|
||||
@@ -82,7 +82,7 @@ tasks:
|
||||
live:runner:
|
||||
internal: true
|
||||
deps: [ ':frontend:prepare' ]
|
||||
dir: frontend/editor
|
||||
dir: frontend
|
||||
vars:
|
||||
BASE_DIR: '{{.ROOT_DIR}}/.test-state/playwright'
|
||||
cmds:
|
||||
@@ -151,14 +151,14 @@ tasks:
|
||||
up first with:
|
||||
task e2e:oauth:up
|
||||
task e2e:saml:up
|
||||
dir: frontend/editor
|
||||
dir: frontend
|
||||
deps: [ ':frontend:prepare' ]
|
||||
cmds:
|
||||
- npx playwright test --project=enterprise {{.CLI_ARGS}}
|
||||
|
||||
cross-browser:
|
||||
desc: "Run stubbed E2E tests on Chromium, Firefox, and WebKit"
|
||||
dir: frontend/editor
|
||||
dir: frontend
|
||||
deps: [ ':frontend:prepare' ]
|
||||
cmds:
|
||||
- npx playwright test --project=stubbed --project=stubbed-firefox --project=stubbed-webkit {{.CLI_ARGS}}
|
||||
|
||||
+49
-49
@@ -3,7 +3,7 @@ version: '3'
|
||||
# Tasks operate from the workspace root (frontend/). Editor commands pass
|
||||
# `editor` as the vite project root (positional after `build` / before the
|
||||
# mode flag) or use `--project editor/...` for tsc — so the editor lives
|
||||
# under frontend/editor/ without each task needing a cd.
|
||||
# under frontend/ without each task needing a cd.
|
||||
|
||||
tasks:
|
||||
install:
|
||||
@@ -26,34 +26,34 @@ tasks:
|
||||
vars:
|
||||
MODE: '{{.MODE | default ""}}'
|
||||
cmds:
|
||||
- npx tsx editor/scripts/setup-env.mts{{if .MODE}} --{{.MODE}}{{end}}
|
||||
- npx tsx scripts/setup-env.mts{{if .MODE}} --{{.MODE}}{{end}}
|
||||
sources:
|
||||
- editor/scripts/setup-env.mts
|
||||
- scripts/setup-env.mts
|
||||
generates:
|
||||
- editor/.env.local
|
||||
- editor/.env{{if .MODE}}.{{.MODE}}{{end}}.local
|
||||
- .env.local
|
||||
- .env{{if .MODE}}.{{.MODE}}{{end}}.local
|
||||
|
||||
prepare:icons:
|
||||
internal: true
|
||||
run: once
|
||||
deps: [install]
|
||||
cmds:
|
||||
- node editor/scripts/generate-icons.js
|
||||
- node scripts/generate-icons.js
|
||||
|
||||
prepare:og:
|
||||
internal: true
|
||||
run: when_changed
|
||||
desc: "Regenerate OG/social-preview metadata from the tool registry"
|
||||
cmds:
|
||||
- node editor/scripts/generate-og-metadata.mjs
|
||||
- node scripts/generate-og-metadata.mjs
|
||||
sources:
|
||||
- editor/src/core/types/toolId.ts
|
||||
- editor/src/core/utils/urlMapping.ts
|
||||
- editor/src/core/data/useTranslatedToolRegistry.tsx
|
||||
- editor/public/og_images/*.png
|
||||
- src/editor/core/types/toolId.ts
|
||||
- src/editor/core/utils/urlMapping.ts
|
||||
- src/editor/core/data/useTranslatedToolRegistry.tsx
|
||||
- public/og_images/*.png
|
||||
generates:
|
||||
- editor/src/core/data/ogImageMap.json
|
||||
- editor/public/og-metadata.json
|
||||
- src/editor/core/data/ogImageMap.json
|
||||
- public/og-metadata.json
|
||||
|
||||
prepare:
|
||||
desc: "Set up dev environment"
|
||||
@@ -88,7 +88,7 @@ tasks:
|
||||
sh: >-
|
||||
{{if eq OS "windows"}}powershell -NoProfile -Command '$root = git rev-parse --show-toplevel 2>$null; if (-not $root) { $root = (Get-Location).Path }; Split-Path -Leaf $root'{{else}}basename "$(git rev-parse --show-toplevel 2>/dev/null || pwd)"{{end}}
|
||||
cmds:
|
||||
- npx vite editor --mode {{.MODE}} --port {{.PORT}}{{if .OPEN}} --open{{end}}
|
||||
- npx vite --mode {{.MODE}} --port {{.PORT}}{{if .OPEN}} --open{{end}}
|
||||
|
||||
dev:
|
||||
desc: "Start frontend dev server"
|
||||
@@ -143,13 +143,13 @@ tasks:
|
||||
desc: "Production build (default mode)"
|
||||
deps: [prepare]
|
||||
cmds:
|
||||
- npx vite build editor
|
||||
- npx vite build
|
||||
|
||||
build:core:
|
||||
desc: "Build for core mode"
|
||||
deps: [prepare]
|
||||
cmds:
|
||||
- npx vite build editor --mode core
|
||||
- npx vite build --mode core
|
||||
|
||||
build:proprietary:
|
||||
desc: "Build for proprietary mode"
|
||||
@@ -157,7 +157,7 @@ tasks:
|
||||
vars:
|
||||
PREVIEW: '{{.PREVIEW | default ""}}'
|
||||
cmds:
|
||||
- '{{if .PREVIEW}}VITE_BUILD_FOR_PREVIEW=1 {{end}}npx vite build editor --mode proprietary'
|
||||
- '{{if .PREVIEW}}VITE_BUILD_FOR_PREVIEW=1 {{end}}npx vite build --mode proprietary'
|
||||
|
||||
build:saas:
|
||||
desc: "Build for SaaS mode"
|
||||
@@ -165,7 +165,7 @@ tasks:
|
||||
- task: prepare
|
||||
vars: { MODE: saas }
|
||||
cmds:
|
||||
- npx vite build editor --mode saas
|
||||
- npx vite build --mode saas
|
||||
|
||||
build:desktop:
|
||||
desc: "Build for desktop mode"
|
||||
@@ -173,13 +173,13 @@ tasks:
|
||||
- task: prepare
|
||||
vars: { MODE: desktop }
|
||||
cmds:
|
||||
- npx vite build editor --mode desktop
|
||||
- npx vite build --mode desktop
|
||||
|
||||
build:prototypes:
|
||||
desc: "Build for prototypes mode"
|
||||
deps: [prepare]
|
||||
cmds:
|
||||
- npx vite build editor --mode prototypes
|
||||
- npx vite build --mode prototypes
|
||||
|
||||
|
||||
storybook:
|
||||
@@ -272,23 +272,23 @@ tasks:
|
||||
# Covers the whole editor tree, including the portal/processor layer and
|
||||
# public/css. Vendored CSS and build output are excluded via ignoreFiles
|
||||
# in stylelint.config.mjs.
|
||||
- npx stylelint "editor/**/*.css"
|
||||
- npx stylelint "src/**/*.css"
|
||||
|
||||
lint:colors:
|
||||
desc: "Enforce theme tokens — no hardcoded colours or raw primitives in components"
|
||||
aliases: [lint:colours]
|
||||
deps: [install]
|
||||
cmds:
|
||||
- node editor/scripts/lint/theme-lint.mjs
|
||||
- node editor/scripts/lint/theme-lint.mjs css-colors
|
||||
- node editor/scripts/lint/theme-lint.mjs code-colors
|
||||
- node editor/scripts/lint/theme-lint.mjs no-primitives
|
||||
- node scripts/lint/theme-lint.mjs
|
||||
- node scripts/lint/theme-lint.mjs css-colors
|
||||
- node scripts/lint/theme-lint.mjs code-colors
|
||||
- node scripts/lint/theme-lint.mjs no-primitives
|
||||
|
||||
contrast:
|
||||
desc: "Report low-contrast theme token pairs (warning only, never blocks)"
|
||||
deps: [install]
|
||||
cmds:
|
||||
- node editor/scripts/lint/theme-lint.mjs contrast
|
||||
- node scripts/lint/theme-lint.mjs contrast
|
||||
|
||||
lint:eslint:
|
||||
desc: "Run ESLint linting"
|
||||
@@ -302,7 +302,7 @@ tasks:
|
||||
cmds:
|
||||
# Globs so dpdm walks the whole tree. dpdm expands the braces itself, so this is
|
||||
# shell-agnostic. Covers the whole editor tree, including the portal layer.
|
||||
- npx dpdm "editor/src/**/*.{ts,tsx}" --circular --no-warning --no-tree --exit-code circular:1
|
||||
- npx dpdm "src/**/*.{ts,tsx}" --circular --no-warning --no-tree --exit-code circular:1
|
||||
|
||||
lint:fix:
|
||||
desc: "Auto-fix lint issues"
|
||||
@@ -343,14 +343,14 @@ tasks:
|
||||
deps: [prepare]
|
||||
cmds:
|
||||
- task: typecheck:_run
|
||||
vars: { PROJECT: editor/src/core/tsconfig.json }
|
||||
vars: { PROJECT: src/editor/core/tsconfig.json }
|
||||
|
||||
typecheck:proprietary:
|
||||
desc: "Typecheck proprietary build variant"
|
||||
deps: [prepare]
|
||||
cmds:
|
||||
- task: typecheck:_run
|
||||
vars: { PROJECT: editor/src/proprietary/tsconfig.json }
|
||||
vars: { PROJECT: src/editor/proprietary/tsconfig.json }
|
||||
|
||||
typecheck:saas:
|
||||
desc: "Typecheck SaaS build variant"
|
||||
@@ -359,7 +359,7 @@ tasks:
|
||||
vars: { MODE: saas }
|
||||
cmds:
|
||||
- task: typecheck:_run
|
||||
vars: { PROJECT: editor/src/saas/tsconfig.json }
|
||||
vars: { PROJECT: src/editor/saas/tsconfig.json }
|
||||
|
||||
typecheck:desktop:
|
||||
desc: "Typecheck desktop build variant"
|
||||
@@ -368,35 +368,35 @@ tasks:
|
||||
vars: { MODE: desktop }
|
||||
cmds:
|
||||
- task: typecheck:_run
|
||||
vars: { PROJECT: editor/src/desktop/tsconfig.json }
|
||||
vars: { PROJECT: src/editor/desktop/tsconfig.json }
|
||||
|
||||
typecheck:cloud:
|
||||
desc: "Typecheck cloud shared layer (standalone)"
|
||||
deps: [prepare]
|
||||
cmds:
|
||||
- task: typecheck:_run
|
||||
vars: { PROJECT: editor/src/cloud/tsconfig.json }
|
||||
vars: { PROJECT: src/editor/cloud/tsconfig.json }
|
||||
|
||||
typecheck:scripts:
|
||||
desc: "Typecheck scripts"
|
||||
deps: [prepare]
|
||||
cmds:
|
||||
- task: typecheck:_run
|
||||
vars: { PROJECT: editor/scripts/tsconfig.json }
|
||||
vars: { PROJECT: scripts/tsconfig.json }
|
||||
|
||||
typecheck:prototypes:
|
||||
desc: "Typecheck prototypes build variant"
|
||||
deps: [prepare]
|
||||
cmds:
|
||||
- task: typecheck:_run
|
||||
vars: { PROJECT: editor/src/prototypes/tsconfig.json }
|
||||
vars: { PROJECT: src/editor/prototypes/tsconfig.json }
|
||||
|
||||
typecheck:portal:
|
||||
desc: "Typecheck developer portal build variant"
|
||||
deps: [install]
|
||||
cmds:
|
||||
- task: typecheck:_run
|
||||
vars: { PROJECT: editor/src/portal/tsconfig.json }
|
||||
vars: { PROJECT: src/processor/proprietary/tsconfig.json }
|
||||
|
||||
typecheck:storybook:
|
||||
desc: "Typecheck Storybook config and stories"
|
||||
@@ -433,7 +433,7 @@ tasks:
|
||||
og:check:
|
||||
desc: "Fail if committed OG/social-preview metadata is out of date"
|
||||
cmds:
|
||||
- node editor/scripts/generate-og-metadata.mjs --check
|
||||
- node scripts/generate-og-metadata.mjs --check
|
||||
|
||||
check:all:
|
||||
desc: "Full CI quality gate"
|
||||
@@ -461,13 +461,13 @@ tasks:
|
||||
desc: "Run editor tests"
|
||||
deps: [prepare]
|
||||
cmds:
|
||||
- npx vitest run --root editor
|
||||
- npx vitest run --root .
|
||||
|
||||
test:watch:
|
||||
desc: "Run tests in watch mode"
|
||||
deps: [prepare]
|
||||
cmds:
|
||||
- npx vitest --watch --root editor
|
||||
- npx vitest --watch --root .
|
||||
|
||||
test:coverage:
|
||||
desc: "Run tests with coverage (one-shot; CI-friendly)."
|
||||
@@ -478,12 +478,12 @@ tasks:
|
||||
# coverage-summary.py helper consumes; html/text are kept for humans.
|
||||
#
|
||||
# reportsDirectory is pinned to ./coverage relative to vitest's root
|
||||
# (--root editor), so output lands at frontend/editor/coverage/. The
|
||||
# (--root .), so output lands at frontend/coverage/. The
|
||||
# CI upload step reads from that path. An earlier attempt with
|
||||
# `./editor/coverage` double-nested into frontend/editor/editor/coverage;
|
||||
# `./editor/coverage` double-nested into frontend/coverage;
|
||||
# pinning future-proofs against vitest changing the default.
|
||||
- >
|
||||
npx vitest run --root editor --coverage
|
||||
npx vitest run --root . --coverage
|
||||
--coverage.provider=v8
|
||||
--coverage.reporter=text-summary
|
||||
--coverage.reporter=json-summary
|
||||
@@ -498,25 +498,25 @@ tasks:
|
||||
desc: "Generate tool API types from the Java OpenAPI spec"
|
||||
deps: [install, ":backend:swagger"]
|
||||
cmds:
|
||||
- npx tsx editor/scripts/generate-tool-api-types.mts --spec ../SwaggerDoc.json --output editor/src/core/types/toolApiTypes.ts --io-output editor/src/core/types/toolIO.ts
|
||||
- npx tsx scripts/generate-tool-api-types.mts --spec ../SwaggerDoc.json --output src/editor/core/types/toolApiTypes.ts --io-output src/editor/core/types/toolIO.ts
|
||||
sources:
|
||||
- editor/scripts/generate-tool-api-types.mts
|
||||
- scripts/generate-tool-api-types.mts
|
||||
- ../SwaggerDoc.json
|
||||
generates:
|
||||
- editor/src/core/types/toolApiTypes.ts
|
||||
- editor/src/core/types/toolIO.ts
|
||||
- src/editor/core/types/toolApiTypes.ts
|
||||
- src/editor/core/types/toolIO.ts
|
||||
|
||||
tool-models:check:
|
||||
desc: "Fail if committed tool API types are out of date"
|
||||
deps: [install, ":backend:swagger"]
|
||||
cmds:
|
||||
- npx tsx editor/scripts/generate-tool-api-types.mts --spec ../SwaggerDoc.json --output editor/src/core/types/toolApiTypes.ts --io-output editor/src/core/types/toolIO.ts --check
|
||||
- npx tsx scripts/generate-tool-api-types.mts --spec ../SwaggerDoc.json --output src/editor/core/types/toolApiTypes.ts --io-output src/editor/core/types/toolIO.ts --check
|
||||
|
||||
licenses:generate:
|
||||
desc: "Generate frontend license report"
|
||||
deps: [install]
|
||||
cmds:
|
||||
- node editor/scripts/generate-licenses.js
|
||||
- node scripts/generate-licenses.js
|
||||
|
||||
# ============================================================
|
||||
# Clean
|
||||
@@ -525,7 +525,7 @@ tasks:
|
||||
clean:
|
||||
desc: "Clean build artifacts and caches"
|
||||
cmds:
|
||||
- cmd: powershell rm -Recurse -Force -ErrorAction SilentlyContinue node_modules/.vite, editor/dist, dist
|
||||
- cmd: powershell rm -Recurse -Force -ErrorAction SilentlyContinue node_modules/.vite, dist, dist
|
||||
platforms: [windows]
|
||||
- cmd: rm -rf node_modules/.vite editor/dist dist
|
||||
- cmd: rm -rf node_modules/.vite dist dist
|
||||
platforms: [linux, darwin]
|
||||
|
||||
@@ -21,7 +21,7 @@ vars:
|
||||
':(exclude).devcontainer/*'
|
||||
':(exclude)app/core/src/main/resources/*'
|
||||
':(exclude)app/proprietary/src/main/resources/*'
|
||||
':(exclude)frontend/editor/public/vendor/*'
|
||||
':(exclude)frontend/public/vendor/*'
|
||||
':(exclude)*Dockerfile*'
|
||||
':(exclude)*pdfjs*'
|
||||
':(exclude)*thirdParty*'
|
||||
@@ -39,7 +39,7 @@ vars:
|
||||
':(exclude)*.min.*'
|
||||
':(exclude)*diff.js'
|
||||
':(exclude).github/workflows/*'
|
||||
LOCALE_TOML: 'frontend/editor/public/locales/*/translation.toml'
|
||||
LOCALE_TOML: 'frontend/public/locales/*/translation.toml'
|
||||
|
||||
# gitleaks is pinned + checksum-verified by scripts/pre-commit/install_gitleaks.py,
|
||||
# which owns the version and caches the binary here.
|
||||
|
||||
+6
-6
@@ -10,14 +10,14 @@ When adding tools, follow this systematic approach using the established pattern
|
||||
|
||||
Create these files in the correct directories:
|
||||
```
|
||||
frontend/editor/src/hooks/tools/[toolName]/
|
||||
frontend/src/hooks/tools/[toolName]/
|
||||
├── use[ToolName]Parameters.ts # Parameter definitions and validation
|
||||
└── use[ToolName]Operation.ts # Tool operation logic using useToolOperation
|
||||
|
||||
frontend/editor/src/components/tools/[toolName]/
|
||||
frontend/src/components/tools/[toolName]/
|
||||
└── [ToolName]Settings.tsx # Settings UI component (if needed)
|
||||
|
||||
frontend/editor/src/tools/
|
||||
frontend/src/tools/
|
||||
└── [ToolName].tsx # Main tool component
|
||||
```
|
||||
|
||||
@@ -128,7 +128,7 @@ export default [ToolName] as ToolComponent;
|
||||
## 3. Register Tool in System
|
||||
Update these files to register your new tool:
|
||||
|
||||
**Tool Registry** (`frontend/editor/src/data/useTranslatedToolRegistry.tsx`):
|
||||
**Tool Registry** (`frontend/src/data/useTranslatedToolRegistry.tsx`):
|
||||
1. Add imports at the top:
|
||||
```typescript
|
||||
import [ToolName] from "../tools/[ToolName]";
|
||||
@@ -155,7 +155,7 @@ import [ToolName]Settings from "../components/tools/[toolName]/[ToolName]Setting
|
||||
## 4. Add Tooltips (Optional but Recommended)
|
||||
Create user-friendly tooltips to help non-technical users understand your tool. **Use simple, clear language - avoid technical jargon:**
|
||||
|
||||
**Tooltip Hook** (`frontend/editor/src/components/tooltips/use[ToolName]Tips.ts`):
|
||||
**Tooltip Hook** (`frontend/src/components/tooltips/use[ToolName]Tips.ts`):
|
||||
```typescript
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { TooltipContent } from '../../types/tips';
|
||||
@@ -202,7 +202,7 @@ const [ToolName] = (props: BaseToolProps) => {
|
||||
## 5. Add Translations
|
||||
Update translation files. **Important: Only update `en-US` files** - other languages are handled separately.
|
||||
|
||||
**File to update:** `frontend/editor/public/locales/en-US/translation.toml`
|
||||
**File to update:** `frontend/public/locales/en-US/translation.toml`
|
||||
|
||||
**Required Translation Keys**:
|
||||
```toml
|
||||
|
||||
@@ -139,10 +139,10 @@ The project structure is defined in `engine/pyproject.toml`. Any new dependencie
|
||||
|
||||
#### Environment Variables
|
||||
- All `VITE_*` variables must be declared in the appropriate committed env file:
|
||||
- `frontend/editor/.env` — core and shared vars (base, loaded in every mode)
|
||||
- `frontend/editor/.env.proprietary` — proprietary-only vars, e.g. the admin portal's SaaS/account-link keys (layered on top of `.env` in proprietary mode)
|
||||
- `frontend/editor/.env.saas` — SaaS-only vars (layered on top of `.env` in SaaS mode)
|
||||
- `frontend/editor/.env.desktop` — desktop (Tauri)-only vars (layered on top of `.env` in desktop mode)
|
||||
- `frontend/.env` — core and shared vars (base, loaded in every mode)
|
||||
- `frontend/.env.proprietary` — proprietary-only vars, e.g. the admin portal's SaaS/account-link keys (layered on top of `.env` in proprietary mode)
|
||||
- `frontend/.env.saas` — SaaS-only vars (layered on top of `.env` in SaaS mode)
|
||||
- `frontend/.env.desktop` — desktop (Tauri)-only vars (layered on top of `.env` in desktop mode)
|
||||
- These files are committed to Git and must not contain private keys
|
||||
- Local overrides (API keys, machine-specific settings) go in uncommitted sibling `.env.local` / `.env.saas.local` / `.env.desktop.local` files — Vite automatically layers them on top
|
||||
- Never use `|| 'hardcoded-fallback'` inline — put defaults in the committed env files
|
||||
@@ -153,9 +153,9 @@ The project structure is defined in `engine/pyproject.toml`. Any new dependencie
|
||||
#### Import Paths - CRITICAL
|
||||
**ALWAYS use `@app/*` for imports.** Do not use `@core/*` or `@proprietary/*` unless explicitly wrapping/extending a lower layer implementation.
|
||||
|
||||
For a broader explanation of the frontend layering and override architecture, read @frontend/editor/DeveloperGuide.md
|
||||
For a broader explanation of the frontend layering and override architecture, read @frontend/DeveloperGuide.md
|
||||
|
||||
Before touching colours or theming (tokens, dark mode, accent colours), read @frontend/editor/src/core/theme/README.md — it explains the palette/`--c-*` token system and the rule that literal colours live only in `primitives.css`.
|
||||
Before touching colours or theming (tokens, dark mode, accent colours), read @frontend/src/editor/core/theme/README.md — it explains the palette/`--c-*` token system and the rule that literal colours live only in `primitives.css`.
|
||||
|
||||
```typescript
|
||||
// ✅ CORRECT - Use @app/* for all imports
|
||||
@@ -270,7 +270,7 @@ Frontend designed for **stateful document processing**:
|
||||
- No file reloading between tools - performance critical for large PDFs (up to 100GB+)
|
||||
|
||||
#### FileContext - Central State Management
|
||||
**Location**: `frontend/editor/src/core/contexts/FileContext.tsx`
|
||||
**Location**: `frontend/src/editor/core/contexts/FileContext.tsx`
|
||||
- **Active files**: Currently loaded PDFs and their variants
|
||||
- **Tool navigation**: Current mode (viewer/pageEditor/fileEditor/toolName)
|
||||
- **Memory management**: PDF document cleanup, blob URL lifecycle, Web Worker management
|
||||
@@ -295,7 +295,7 @@ Without cleanup: browser crashes with memory leaks.
|
||||
|
||||
**Architecture**: Modular hook-based system with clear separation of concerns:
|
||||
|
||||
- **useToolOperation** (`frontend/editor/src/core/hooks/tools/shared/useToolOperation.ts`): Main orchestrator hook
|
||||
- **useToolOperation** (`frontend/src/editor/core/hooks/tools/shared/useToolOperation.ts`): Main orchestrator hook
|
||||
- Coordinates all tool operations with consistent interface
|
||||
- Integrates with FileContext for operation tracking
|
||||
- Handles validation, error handling, and UI state management
|
||||
@@ -383,7 +383,7 @@ return useToolOperation({
|
||||
### Frontend Directory Structure
|
||||
The frontend is organized with a clear separation of concerns:
|
||||
|
||||
- **`frontend/editor/src/core/`**: Main application code (shared, production-ready components)
|
||||
- **`frontend/src/editor/core/`**: Main application code (shared, production-ready components)
|
||||
- **`core/components/`**: React components organized by feature
|
||||
- `core/components/tools/`: Individual PDF tool implementations
|
||||
- `core/components/viewer/`: PDF viewer components
|
||||
@@ -401,17 +401,17 @@ The frontend is organized with a clear separation of concerns:
|
||||
- **`core/data/`**: Static data (tool taxonomy, etc.)
|
||||
- **`core/services/`**: Business logic services (PDF processing, storage, etc.)
|
||||
|
||||
- **`frontend/editor/src/desktop/`**: Desktop-specific (Tauri) code
|
||||
- **`frontend/editor/src/proprietary/`**: Proprietary/licensed features
|
||||
- **`frontend/editor/src-tauri/`**: Tauri (Rust) native desktop application code
|
||||
- **`frontend/editor/public/`**: Static assets served directly
|
||||
- **`frontend/src/editor/desktop/`**: Desktop-specific (Tauri) code
|
||||
- **`frontend/src/editor/proprietary/`**: Proprietary/licensed features
|
||||
- **`frontend/src-tauri/`**: Tauri (Rust) native desktop application code
|
||||
- **`frontend/public/`**: Static assets served directly
|
||||
- `public/locales/`: Translation JSON files
|
||||
|
||||
### Component Architecture
|
||||
- **Static Assets**: CSS, JS, and resources in `src/main/resources/static/` (legacy) + `frontend/editor/public/` (modern)
|
||||
- **Static Assets**: CSS, JS, and resources in `src/main/resources/static/` (legacy) + `frontend/public/` (modern)
|
||||
- **Internationalization**:
|
||||
- Backend: `messages_*.properties` files
|
||||
- Frontend: JSON files in `frontend/editor/public/locales/` (converted from .properties)
|
||||
- Frontend: JSON files in `frontend/public/locales/` (converted from .properties)
|
||||
- Conversion Script: `scripts/convert_properties_to_json.py`
|
||||
|
||||
### Configuration Modes
|
||||
@@ -436,7 +436,7 @@ The frontend is organized with a clear separation of concerns:
|
||||
4. **Code Style**: Spotless enforces Google Java Format automatically (`task backend:format`)
|
||||
5. **Translations**:
|
||||
- Backend: Use helper scripts in `/scripts` for multi-language updates
|
||||
- Frontend: Update JSON files in `frontend/editor/public/locales/` or use conversion script
|
||||
- Frontend: Update JSON files in `frontend/public/locales/` or use conversion script
|
||||
6. **Documentation**: API docs auto-generated and available at `/swagger-ui/index.html`
|
||||
|
||||
## Frontend Architecture Status
|
||||
@@ -454,7 +454,7 @@ The frontend is organized with a clear separation of concerns:
|
||||
## Translation Rules
|
||||
|
||||
- **CRITICAL**: Always update translations in `en-US` only - all other languages (including `en-GB`) are handled separately
|
||||
- Translation files are located in `frontend/editor/public/locales/`
|
||||
- Translation files are located in `frontend/public/locales/`
|
||||
- After changing any translation file, run `task pre-commit:fix`
|
||||
|
||||
## Important Notes
|
||||
|
||||
+1
-1
@@ -21,7 +21,7 @@ This project uses [Task](https://taskfile.dev/) as a unified command runner. Aft
|
||||
|
||||
1. Install the `task` CLI: https://taskfile.dev/installation/
|
||||
2. Run `task install` to install all dependencies
|
||||
3. Run `task dev` to start backend + frontend
|
||||
3. Run `task dev` to start backend + frontend or `task desktop:dev` to start the desktop application
|
||||
4. Run `task check` before submitting a PR
|
||||
|
||||
Run `task --list` to see all available commands.
|
||||
|
||||
+1
-1
@@ -458,7 +458,7 @@ For Stirling 2.0, new features are built as React components:
|
||||
|
||||
1. **Create the React Component:**
|
||||
```typescript
|
||||
// frontend/editor/src/tools/NewTool.tsx
|
||||
// frontend/src/tools/NewTool.tsx
|
||||
import { useState } from 'react';
|
||||
import { Button, FileInput, Container } from '@mantine/core';
|
||||
|
||||
|
||||
@@ -10,20 +10,18 @@ if that directory exists, is licensed under the license defined in "app/propriet
|
||||
if that directory exists, is licensed under the license defined in "app/saas/LICENSE".
|
||||
* All content that resides under the "engine/" directory of this repository,
|
||||
if that directory exists, is licensed under the license defined in "engine/LICENSE".
|
||||
* All content that resides under the "frontend/editor/src/proprietary/" directory of this repository,
|
||||
if that directory exists, is licensed under the license defined in "frontend/editor/src/proprietary/LICENSE".
|
||||
* All content that resides under the "frontend/editor/src/desktop/" directory of this repository,
|
||||
if that directory exists, is licensed under the license defined in "frontend/editor/src/desktop/LICENSE".
|
||||
* All content that resides under the "frontend/editor/src/saas/" directory of this repository,
|
||||
if that directory exists, is licensed under the license defined in "frontend/editor/src/saas/LICENSE".
|
||||
* All content that resides under the "frontend/editor/src/cloud/" directory of this repository,
|
||||
if that directory exists, is licensed under the license defined in "frontend/editor/src/cloud/LICENSE".
|
||||
* All content that resides under the "frontend/editor/src/prototypes/" directory of this repository,
|
||||
if that directory exists, is licensed under the license defined in "frontend/editor/src/prototypes/LICENSE".
|
||||
* All content that resides under the "frontend/editor/src/portal/" directory of this repository,
|
||||
if that directory exists, is licensed under the license defined in "frontend/editor/src/portal/LICENSE".
|
||||
* All content that resides under the "frontend/editor/src/portal-saas/" directory of this repository,
|
||||
if that directory exists, is licensed under the license defined in "frontend/editor/src/portal-saas/LICENSE".
|
||||
* All content that resides under the "frontend/src/editor/proprietary/" directory of this repository,
|
||||
if that directory exists, is licensed under the license defined in "frontend/src/editor/proprietary/LICENSE".
|
||||
* All content that resides under the "frontend/src/editor/desktop/" directory of this repository,
|
||||
if that directory exists, is licensed under the license defined in "frontend/src/editor/desktop/LICENSE".
|
||||
* All content that resides under the "frontend/src/editor/saas/" directory of this repository,
|
||||
if that directory exists, is licensed under the license defined in "frontend/src/editor/saas/LICENSE".
|
||||
* All content that resides under the "frontend/src/editor/cloud/" directory of this repository,
|
||||
if that directory exists, is licensed under the license defined in "frontend/src/editor/cloud/LICENSE".
|
||||
* All content that resides under the "frontend/src/editor/prototypes/" directory of this repository,
|
||||
if that directory exists, is licensed under the license defined in "frontend/src/editor/prototypes/LICENSE".
|
||||
* All content that resides under the "frontend/src/processor/" directory of this repository,
|
||||
if that directory exists, is licensed under the license defined in "frontend/src/processor/LICENSE".
|
||||
* Content outside of the above mentioned directories or restrictions above is
|
||||
available under the MIT License as defined below.
|
||||
|
||||
|
||||
+1
-1
@@ -86,7 +86,7 @@ If you're using Tauri's built-in updater feature:
|
||||
|
||||
## Configuration Files
|
||||
|
||||
### 1. Tauri Configuration (frontend/editor/src-tauri/tauri.conf.json)
|
||||
### 1. Tauri Configuration (frontend/src-tauri/tauri.conf.json)
|
||||
|
||||
The Windows signing configuration is already set up:
|
||||
|
||||
|
||||
@@ -156,6 +156,14 @@
|
||||
"moduleName": ".*",
|
||||
"moduleLicense": "GNU GENERAL PUBLIC LICENSE, Version 2 + Classpath Exception"
|
||||
},
|
||||
{
|
||||
"moduleName": ".*",
|
||||
"moduleLicense": "GNU Lesser Public License"
|
||||
},
|
||||
{
|
||||
"moduleName": ".*",
|
||||
"moduleLicense": "The GNU Lesser General Public License"
|
||||
},
|
||||
{
|
||||
"moduleName": "com.martiansoftware:jsap",
|
||||
"moduleLicense": "LGPL"
|
||||
@@ -224,14 +232,6 @@
|
||||
"moduleName": "com.google.re2j:re2j",
|
||||
"moduleLicense": "Go License"
|
||||
},
|
||||
{
|
||||
"moduleName": "com.hubspot:algebra",
|
||||
"moduleLicense": null
|
||||
},
|
||||
{
|
||||
"moduleName": "com.hubspot.immutables:immutables-exceptions",
|
||||
"moduleLicense": null
|
||||
},
|
||||
{
|
||||
"moduleName": ".*",
|
||||
"moduleLicense": "UnRar License"
|
||||
|
||||
+13
-7
@@ -16,7 +16,7 @@ dependencies {
|
||||
api "org.apache.pdfbox:pdfbox-io:$pdfboxVersion"
|
||||
api "org.apache.pdfbox:xmpbox:$pdfboxVersion"
|
||||
api "org.apache.pdfbox:preflight:$pdfboxVersion"
|
||||
api 'com.github.junrar:junrar:7.6.0' // RAR archive support for CBR files
|
||||
api 'com.github.junrar:junrar:8.0.0' // RAR archive support for CBR files
|
||||
api 'jakarta.servlet:jakarta.servlet-api:6.1.0'
|
||||
api 'org.snakeyaml:snakeyaml-engine:3.0.1'
|
||||
api "org.springdoc:springdoc-openapi-starter-webmvc-ui:3.0.3"
|
||||
@@ -36,18 +36,24 @@ dependencies {
|
||||
|
||||
api "com.stirling:jpdfium:${jpdfiumVersion}"
|
||||
|
||||
// -PjpdfiumPlatforms=all|<csv of linux-x64,linux-arm64,darwin-x64,darwin-arm64,windows-x64>
|
||||
// -PjpdfiumPlatforms=all|none|<csv of linux-x64,linux-arm64,darwin-x64,darwin-arm64,windows-x64>
|
||||
// 'none' skips natives entirely (windows-arm64 builds, until JPDFium ships that platform).
|
||||
def jpdfiumPlatformsProp = (project.findProperty('jpdfiumPlatforms') ?: 'all').toString().trim()
|
||||
def jpdfiumAllPlatforms = ['linux-x64', 'linux-arm64', 'darwin-x64', 'darwin-arm64', 'windows-x64']
|
||||
def jpdfiumPlatforms = jpdfiumPlatformsProp == 'all'
|
||||
? jpdfiumAllPlatforms
|
||||
: jpdfiumPlatformsProp.split(',').collect { it.trim() }.findAll { it }
|
||||
def jpdfiumPlatforms
|
||||
if (jpdfiumPlatformsProp == 'all') {
|
||||
jpdfiumPlatforms = jpdfiumAllPlatforms
|
||||
} else if (jpdfiumPlatformsProp == 'none') {
|
||||
jpdfiumPlatforms = []
|
||||
} else {
|
||||
jpdfiumPlatforms = jpdfiumPlatformsProp.split(',').collect { it.trim() }.findAll { it }
|
||||
}
|
||||
def jpdfiumInvalid = jpdfiumPlatforms.findAll { !jpdfiumAllPlatforms.contains(it) }
|
||||
if (jpdfiumInvalid) {
|
||||
throw new GradleException("Unknown jpdfiumPlatforms value(s): ${jpdfiumInvalid.join(', ')}. " +
|
||||
"Valid: ${jpdfiumAllPlatforms.join(', ')} or 'all'.")
|
||||
"Valid: ${jpdfiumAllPlatforms.join(', ')}, 'all' or 'none'.")
|
||||
}
|
||||
logger.lifecycle("JPDFium native platforms: ${jpdfiumPlatforms.join(', ')}")
|
||||
logger.lifecycle("JPDFium native platforms: ${jpdfiumPlatforms ? jpdfiumPlatforms.join(', ') : 'none'}")
|
||||
jpdfiumPlatforms.each { platform ->
|
||||
runtimeOnly "com.stirling:jpdfium-natives-${platform}:${jpdfiumVersion}"
|
||||
}
|
||||
|
||||
@@ -983,7 +983,7 @@ public class PdfMarkdownConverter {
|
||||
ordered.sort(Comparator.comparingDouble((Line l) -> l.y).reversed());
|
||||
StringBuilder sb = new StringBuilder();
|
||||
for (Line l : ordered) {
|
||||
if (sb.length() > 0) {
|
||||
if (!sb.isEmpty()) {
|
||||
sb.append(' ');
|
||||
}
|
||||
sb.append(l.text);
|
||||
|
||||
@@ -19,6 +19,7 @@ import org.springframework.stereotype.Service;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
import org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody;
|
||||
|
||||
import jakarta.annotation.PreDestroy;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
@@ -63,6 +64,21 @@ public class JobExecutorService {
|
||||
"Job executor configured with effective timeout of {} ms", this.effectiveTimeoutMs);
|
||||
}
|
||||
|
||||
/** Stop the service-owned executor when the application context is closed or restarted. */
|
||||
@PreDestroy
|
||||
public void shutdown() {
|
||||
log.debug("Shutting down job executor");
|
||||
executor.shutdown();
|
||||
try {
|
||||
if (!executor.awaitTermination(5, TimeUnit.SECONDS)) {
|
||||
executor.shutdownNow();
|
||||
}
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
executor.shutdownNow();
|
||||
}
|
||||
}
|
||||
|
||||
public ResponseEntity<?> runJobGeneric(boolean async, Supplier<Object> work) {
|
||||
return runJobGeneric(async, work, -1);
|
||||
}
|
||||
|
||||
+15
-13
@@ -225,19 +225,21 @@ public class MobileScannerService {
|
||||
Path sessionDir = getSafeSessionDirectory(sessionId);
|
||||
if (Files.exists(sessionDir)) {
|
||||
// Delete all files in session directory
|
||||
Files.walk(sessionDir)
|
||||
.sorted(
|
||||
(a, b) ->
|
||||
-a.compareTo(b)) // Reverse order to delete files before
|
||||
// directory
|
||||
.forEach(
|
||||
path -> {
|
||||
try {
|
||||
Files.deleteIfExists(path);
|
||||
} catch (IOException e) {
|
||||
log.warn("Failed to delete file: {}", path, e);
|
||||
}
|
||||
});
|
||||
try (var paths = Files.walk(sessionDir)) {
|
||||
paths.sorted(
|
||||
(a, b) ->
|
||||
-a.compareTo(
|
||||
b)) // Reverse order to delete files before
|
||||
// directory
|
||||
.forEach(
|
||||
path -> {
|
||||
try {
|
||||
Files.deleteIfExists(path);
|
||||
} catch (IOException e) {
|
||||
log.warn("Failed to delete file: {}", path, e);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
log.info("Deleted session: {}", sessionId);
|
||||
} catch (IllegalArgumentException e) {
|
||||
|
||||
@@ -48,6 +48,10 @@ public class TaskManager {
|
||||
@Value("${stirling.jobResultExpiryMinutes:30}")
|
||||
private int jobResultExpiryMinutes = 30;
|
||||
|
||||
/** Maximum age of a task that never reached a terminal state. */
|
||||
@Value("${stirling.job.pendingExpiryMinutes:1440}")
|
||||
private int pendingJobExpiryMinutes = 1440;
|
||||
|
||||
private final FileStorage fileStorage;
|
||||
private final JobStore jobStore;
|
||||
private final ClusterBackplane clusterBackplane;
|
||||
@@ -332,19 +336,32 @@ public class TaskManager {
|
||||
}
|
||||
LocalDateTime expiryThreshold =
|
||||
LocalDateTime.now().minus(jobResultExpiryMinutes, ChronoUnit.MINUTES);
|
||||
LocalDateTime pendingExpiryThreshold =
|
||||
LocalDateTime.now().minus(pendingJobExpiryMinutes, ChronoUnit.MINUTES);
|
||||
int removedCount = 0;
|
||||
|
||||
try {
|
||||
for (Map.Entry<String, JobResult> entry : jobResults.entrySet()) {
|
||||
JobResult result = entry.getValue();
|
||||
|
||||
// Remove completed jobs that are older than the expiry threshold
|
||||
if (result.isComplete()
|
||||
&& result.getCompletedAt() != null
|
||||
&& result.getCompletedAt().isBefore(expiryThreshold)) {
|
||||
boolean expiredCompletedJob =
|
||||
result.isComplete()
|
||||
&& result.getCompletedAt() != null
|
||||
&& result.getCompletedAt().isBefore(expiryThreshold);
|
||||
boolean abandonedPendingJob =
|
||||
!result.isComplete()
|
||||
&& result.getCreatedAt() != null
|
||||
&& result.getCreatedAt().isBefore(pendingExpiryThreshold);
|
||||
|
||||
// Remove old terminal results and abandoned pending jobs. Without the second
|
||||
// branch, a client that starts a task and never completes it keeps its result in
|
||||
// memory forever.
|
||||
if (expiredCompletedJob || abandonedPendingJob) {
|
||||
|
||||
// Clean up file results
|
||||
cleanupJobFiles(result, entry.getKey());
|
||||
if (expiredCompletedJob) {
|
||||
cleanupJobFiles(result, entry.getKey());
|
||||
}
|
||||
|
||||
// Remove the job result
|
||||
jobResults.remove(entry.getKey());
|
||||
|
||||
@@ -941,7 +941,7 @@ public class GeneralUtils {
|
||||
}
|
||||
|
||||
// If no MAC address found, use hostname as fallback
|
||||
if (sb.length() == 0) {
|
||||
if (sb.isEmpty()) {
|
||||
String hostname = InetAddress.getLocalHost().getHostName();
|
||||
sb.append(hostname != null ? hostname : "unknown-host");
|
||||
log.warn("No MAC address found, using hostname for fingerprint generation");
|
||||
|
||||
@@ -1,17 +1,22 @@
|
||||
package stirling.software.common.util;
|
||||
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.regex.Pattern;
|
||||
import java.util.regex.PatternSyntaxException;
|
||||
|
||||
import com.google.common.cache.Cache;
|
||||
import com.google.common.cache.CacheBuilder;
|
||||
import com.google.common.util.concurrent.UncheckedExecutionException;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
|
||||
@Slf4j
|
||||
public final class RegexPatternUtils {
|
||||
|
||||
private static final RegexPatternUtils INSTANCE = new RegexPatternUtils();
|
||||
private final ConcurrentHashMap<PatternKey, Pattern> patternCache = new ConcurrentHashMap<>();
|
||||
private static final long MAX_CACHED_PATTERNS = 512;
|
||||
private final Cache<PatternKey, Pattern> patternCache =
|
||||
CacheBuilder.newBuilder().maximumSize(MAX_CACHED_PATTERNS).build();
|
||||
|
||||
private static final String WHITESPACE_REGEX = "\\s++";
|
||||
private static final String EXTENSION_REGEX = "\\.(?:[^.]*+)?$";
|
||||
@@ -51,7 +56,7 @@ public final class RegexPatternUtils {
|
||||
throw new IllegalArgumentException("Regex pattern cannot be null");
|
||||
}
|
||||
|
||||
return patternCache.computeIfAbsent(new PatternKey(regex, 0), this::compilePattern);
|
||||
return getOrCompile(new PatternKey(regex, 0));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -77,7 +82,7 @@ public final class RegexPatternUtils {
|
||||
throw new IllegalArgumentException("Regex pattern cannot be null");
|
||||
}
|
||||
|
||||
return patternCache.computeIfAbsent(new PatternKey(regex, flags), this::compilePattern);
|
||||
return getOrCompile(new PatternKey(regex, flags));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -98,7 +103,7 @@ public final class RegexPatternUtils {
|
||||
* @return true if pattern is cached, false otherwise
|
||||
*/
|
||||
public boolean isCached(String regex, int flags) {
|
||||
return regex != null && patternCache.containsKey(new PatternKey(regex, flags));
|
||||
return regex != null && patternCache.getIfPresent(new PatternKey(regex, flags)) != null;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -107,7 +112,7 @@ public final class RegexPatternUtils {
|
||||
* @return number of patterns currently cached
|
||||
*/
|
||||
public int getCacheSize() {
|
||||
return patternCache.size();
|
||||
return (int) patternCache.size();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -115,7 +120,7 @@ public final class RegexPatternUtils {
|
||||
* useful for testing or memory cleanup in long-running applications.
|
||||
*/
|
||||
public void clearCache() {
|
||||
patternCache.clear();
|
||||
patternCache.invalidateAll();
|
||||
log.debug("Regex pattern cache cleared");
|
||||
}
|
||||
|
||||
@@ -141,13 +146,32 @@ public final class RegexPatternUtils {
|
||||
return false;
|
||||
}
|
||||
PatternKey key = new PatternKey(regex, flags);
|
||||
boolean removed = patternCache.remove(key) != null;
|
||||
boolean removed = patternCache.getIfPresent(key) != null;
|
||||
patternCache.invalidate(key);
|
||||
if (removed) {
|
||||
log.debug("Removed regex pattern from cache: {} (flags: {})", regex, flags);
|
||||
}
|
||||
return removed;
|
||||
}
|
||||
|
||||
private Pattern getOrCompile(PatternKey key) {
|
||||
try {
|
||||
return patternCache.get(key, () -> compilePattern(key));
|
||||
} catch (UncheckedExecutionException e) {
|
||||
Throwable cause = e.getCause();
|
||||
if (cause instanceof PatternSyntaxException patternSyntaxException) {
|
||||
throw patternSyntaxException;
|
||||
}
|
||||
throw e;
|
||||
} catch (java.util.concurrent.ExecutionException e) {
|
||||
Throwable cause = e.getCause();
|
||||
if (cause instanceof PatternSyntaxException patternSyntaxException) {
|
||||
throw patternSyntaxException;
|
||||
}
|
||||
throw new IllegalStateException("Failed to compile regex pattern", cause);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Internal method to compile a pattern and handle errors consistently.
|
||||
*
|
||||
|
||||
@@ -154,7 +154,7 @@ class PdfMarkdownConverterTest {
|
||||
|| isTableSeparatorRow(line)) {
|
||||
continue;
|
||||
}
|
||||
if (sb.length() > 0) {
|
||||
if (!sb.isEmpty()) {
|
||||
sb.append('\n');
|
||||
}
|
||||
sb.append(line);
|
||||
|
||||
@@ -57,7 +57,7 @@ dependencies {
|
||||
// veraPDF still uses javax.xml.bind, not the new jakarta namespace
|
||||
implementation 'javax.xml.bind:jaxb-api:2.3.1'
|
||||
implementation 'com.sun.xml.bind:jaxb-impl:2.3.9'
|
||||
implementation 'com.sun.xml.bind:jaxb-core:4.0.7'
|
||||
implementation 'com.sun.xml.bind:jaxb-core:4.0.9'
|
||||
|
||||
// CVE-2022-25647: Explicit gson to prevent unsafe deserialization (tabula would pull 2.8.7)
|
||||
implementation "com.google.code.gson:gson:${gsonVersion}"
|
||||
@@ -156,7 +156,7 @@ if (buildWithPortal) {
|
||||
}
|
||||
// Workspace root holds package.json and node_modules (shared across editor /
|
||||
// future portal). Editor-specific paths (src, public, dist, tauri) live one
|
||||
// level deeper under frontend/editor/.
|
||||
// level deeper under frontend/.
|
||||
|
||||
// Vite mode: -PprototypesMode > -PfrontendMode > enableSaas > disableAdditional > proprietary.
|
||||
def frontendModeOverride = project.findProperty('frontendMode')?.toString()?.toLowerCase()
|
||||
@@ -176,11 +176,11 @@ def frontendBuildTask = "frontend:build:${frontendMode}"
|
||||
|
||||
// Workspace root holds package.json and node_modules (shared across editor /
|
||||
// future portal). Editor-specific paths (src, public, dist, tauri) live one
|
||||
// level deeper under frontend/editor/. When the portal lands as an embedded
|
||||
// level deeper under frontend/. When the portal lands as an embedded
|
||||
// app, add a sibling frontendPortalDir / frontendPortalDistDir alongside.
|
||||
def frontendDir = file('../../frontend')
|
||||
def frontendEditorDir = file('../../frontend/editor')
|
||||
def frontendEditorDistDir = file('../../frontend/editor/dist')
|
||||
def frontendEditorDir = file('../../frontend')
|
||||
def frontendEditorDistDir = file('../../frontend/dist')
|
||||
def resourcesStaticDir = file('src/main/resources/static')
|
||||
def generatedFrontendPaths = [
|
||||
'assets',
|
||||
|
||||
@@ -321,7 +321,7 @@ public class ExternalAppDepConfig {
|
||||
new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8))) {
|
||||
String line;
|
||||
while ((line = br.readLine()) != null) {
|
||||
if (sb.length() > 0) sb.append('\n');
|
||||
if (!sb.isEmpty()) sb.append('\n');
|
||||
sb.append(line);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -130,7 +130,7 @@ public class UIDataController {
|
||||
objectMapper.readValue(
|
||||
config, new TypeReference<Map<String, Object>>() {});
|
||||
String name = (String) jsonContent.get("name");
|
||||
if (name == null || name.length() < 1) {
|
||||
if (name == null || name.isEmpty()) {
|
||||
String filename =
|
||||
jsonFiles
|
||||
.get(pipelineConfigs.indexOf(config))
|
||||
|
||||
-28
@@ -61,7 +61,6 @@ import stirling.software.common.model.api.PDFFile;
|
||||
import stirling.software.common.model.tool.ToolFormat;
|
||||
import stirling.software.common.model.tool.ToolIO;
|
||||
import stirling.software.common.service.CustomPDFDocumentFactory;
|
||||
import stirling.software.common.util.ExceptionUtils;
|
||||
import stirling.software.common.util.RegexPatternUtils;
|
||||
import stirling.software.common.util.WebResponseUtils;
|
||||
|
||||
@@ -270,25 +269,6 @@ public class GetInfoOnPDF {
|
||||
}
|
||||
}
|
||||
|
||||
private static void validatePdfFile(MultipartFile file) {
|
||||
if (file == null || file.isEmpty()) {
|
||||
throw new IllegalArgumentException("PDF file is required");
|
||||
}
|
||||
|
||||
if (file.getSize() > MAX_FILE_SIZE) {
|
||||
throw ExceptionUtils.createIllegalArgumentException(
|
||||
"error.fileSizeLimit",
|
||||
"File size ({0} bytes) exceeds maximum allowed size ({1} bytes)",
|
||||
file.getSize(),
|
||||
MAX_FILE_SIZE);
|
||||
}
|
||||
|
||||
String contentType = file.getContentType();
|
||||
if (contentType != null && !"application/pdf".equals(contentType)) {
|
||||
log.warn("File content type is {}, expected application/pdf", contentType);
|
||||
}
|
||||
}
|
||||
|
||||
private static ResponseEntity<byte[]> createErrorResponse(String errorMessage) {
|
||||
try {
|
||||
ObjectNode errorNode = objectMapper.createObjectNode();
|
||||
@@ -1104,14 +1084,6 @@ public class GetInfoOnPDF {
|
||||
public ResponseEntity<byte[]> getPdfInfo(@ModelAttribute PDFFile request) throws IOException {
|
||||
MultipartFile inputFile = request.getFileInput();
|
||||
|
||||
// Validate input
|
||||
try {
|
||||
validatePdfFile(inputFile);
|
||||
} catch (IllegalArgumentException e) {
|
||||
log.error("Invalid PDF file: {}", e.getMessage());
|
||||
return createErrorResponse("Invalid PDF file: " + e.getMessage());
|
||||
}
|
||||
|
||||
List<PDFVerificationResult> verificationResults = null;
|
||||
try {
|
||||
verificationResults = veraPDFService.validatePDF(inputFile.getInputStream());
|
||||
|
||||
+4
-4
@@ -124,15 +124,15 @@ public class PasswordController {
|
||||
StandardProtectionPolicy spp =
|
||||
new StandardProtectionPolicy(ownerPassword, password, ap);
|
||||
|
||||
if ((ownerPassword != null && ownerPassword.length() > 0)
|
||||
|| (password != null && password.length() > 0)) {
|
||||
if ((ownerPassword != null && !ownerPassword.isEmpty())
|
||||
|| (password != null && !password.isEmpty())) {
|
||||
spp.setEncryptionKeyLength(keyLength);
|
||||
}
|
||||
spp.setPermissions(ap);
|
||||
document.protect(spp);
|
||||
|
||||
if ((ownerPassword == null || ownerPassword.length() == 0)
|
||||
&& (password == null || password.length() == 0))
|
||||
if ((ownerPassword == null || ownerPassword.isEmpty())
|
||||
&& (password == null || password.isEmpty()))
|
||||
return WebResponseUtils.pdfDocToWebResponse(
|
||||
document,
|
||||
GeneralUtils.generateFilename(
|
||||
|
||||
+9
-9
@@ -760,12 +760,12 @@ class RedactExecuteService {
|
||||
char ch = raw.charAt(i);
|
||||
if (Character.isLetterOrDigit(ch)) {
|
||||
current.append(ch);
|
||||
} else if (current.length() > 0) {
|
||||
} else if (!current.isEmpty()) {
|
||||
tokens.add(current.toString());
|
||||
current.setLength(0);
|
||||
}
|
||||
}
|
||||
if (current.length() > 0) tokens.add(current.toString());
|
||||
if (!current.isEmpty()) tokens.add(current.toString());
|
||||
if (tokens.size() < 2) return null;
|
||||
StringBuilder out = new StringBuilder();
|
||||
for (int i = 0; i < tokens.size(); i++) {
|
||||
@@ -788,25 +788,25 @@ class RedactExecuteService {
|
||||
StringBuilder current = new StringBuilder();
|
||||
for (String token : tokens) {
|
||||
if (token.isEmpty()) {
|
||||
if (current.length() > 0) {
|
||||
if (result.length() > 0) result.append(' ');
|
||||
if (!current.isEmpty()) {
|
||||
if (!result.isEmpty()) result.append(' ');
|
||||
result.append(current);
|
||||
current.setLength(0);
|
||||
}
|
||||
} else if (token.length() == 1) {
|
||||
current.append(token);
|
||||
} else {
|
||||
if (current.length() > 0) {
|
||||
if (result.length() > 0) result.append(' ');
|
||||
if (!current.isEmpty()) {
|
||||
if (!result.isEmpty()) result.append(' ');
|
||||
result.append(current);
|
||||
current.setLength(0);
|
||||
}
|
||||
if (result.length() > 0) result.append(' ');
|
||||
if (!result.isEmpty()) result.append(' ');
|
||||
result.append(token);
|
||||
}
|
||||
}
|
||||
if (current.length() > 0) {
|
||||
if (result.length() > 0) result.append(' ');
|
||||
if (!current.isEmpty()) {
|
||||
if (!result.isEmpty()) result.append(' ');
|
||||
result.append(current);
|
||||
}
|
||||
return result.toString().trim();
|
||||
|
||||
@@ -251,7 +251,7 @@ public class MetricsController {
|
||||
|
||||
// For GET requests, validate if we have a list of valid endpoints
|
||||
final boolean validateGetEndpoints =
|
||||
endpointInspector.getValidGetEndpoints().size() != 0;
|
||||
!endpointInspector.getValidGetEndpoints().isEmpty();
|
||||
if ("GET".equals(method)
|
||||
&& validateGetEndpoints
|
||||
&& !endpointInspector.isValidGetEndpoint(uri)) {
|
||||
@@ -292,7 +292,7 @@ public class MetricsController {
|
||||
|
||||
// For GET requests, validate if we have a list of valid endpoints
|
||||
final boolean validateGetEndpoints =
|
||||
endpointInspector.getValidGetEndpoints().size() != 0;
|
||||
!endpointInspector.getValidGetEndpoints().isEmpty();
|
||||
if ("GET".equals(method)
|
||||
&& validateGetEndpoints
|
||||
&& !endpointInspector.isValidGetEndpoint(uri)) {
|
||||
@@ -332,7 +332,7 @@ public class MetricsController {
|
||||
|
||||
// For GET requests, validate if we have a list of valid endpoints
|
||||
final boolean validateGetEndpoints =
|
||||
endpointInspector.getValidGetEndpoints().size() != 0;
|
||||
!endpointInspector.getValidGetEndpoints().isEmpty();
|
||||
if ("GET".equals(method)
|
||||
&& validateGetEndpoints
|
||||
&& !endpointInspector.isValidGetEndpoint(uri)) {
|
||||
|
||||
+89
@@ -5,17 +5,26 @@ import java.io.InputStream;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.core.Ordered;
|
||||
import org.springframework.core.io.ClassPathResource;
|
||||
import org.springframework.core.io.FileSystemResource;
|
||||
import org.springframework.core.io.Resource;
|
||||
import org.springframework.http.CacheControl;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.http.converter.StringHttpMessageConverter;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.servlet.function.RouterFunction;
|
||||
import org.springframework.web.servlet.function.RouterFunctions;
|
||||
import org.springframework.web.servlet.function.ServerResponse;
|
||||
import org.springframework.web.servlet.function.support.RouterFunctionMapping;
|
||||
import org.springframework.web.util.HtmlUtils;
|
||||
import org.springframework.web.util.JavaScriptUtils;
|
||||
|
||||
@@ -32,6 +41,33 @@ public class ReactRoutingController {
|
||||
private static final Pattern BASE_HREF_PATTERN =
|
||||
Pattern.compile("<base href=\\\"[^\\\"]*\\\"\\s*/?>");
|
||||
|
||||
// First path segments owned by the backend or static assets, never SPA routes.
|
||||
// Mirrors the exclusion regexes on forwardRootPaths/forwardNestedPaths below.
|
||||
private static final Set<String> NON_SPA_FIRST_SEGMENTS =
|
||||
Set.of(
|
||||
"api",
|
||||
"static",
|
||||
"pipeline",
|
||||
"pdfjs",
|
||||
"pdfjs-legacy",
|
||||
"pdfium",
|
||||
"vendor",
|
||||
"fonts",
|
||||
"images",
|
||||
"css",
|
||||
"js",
|
||||
"assets",
|
||||
"locales",
|
||||
"modern-logo",
|
||||
"classic-logo",
|
||||
"Login",
|
||||
"og_images",
|
||||
"samples");
|
||||
|
||||
// After the annotated controllers (order 0), before the resource chain
|
||||
// (LOWEST_PRECEDENCE - 1).
|
||||
private static final int SPA_FALLBACK_ORDER = Ordered.LOWEST_PRECEDENCE - 2;
|
||||
|
||||
@Value("${server.servlet.context-path:/}")
|
||||
private String contextPath;
|
||||
|
||||
@@ -256,6 +292,59 @@ public class ReactRoutingController {
|
||||
return serveIndexHtml(request);
|
||||
}
|
||||
|
||||
// The regex mappings above only cover 1- and 2-segment paths (Spring path variables cannot
|
||||
// span '/'), so deep SPA links like /processor/pipelines/new 404d on direct navigation.
|
||||
//
|
||||
// Registered as its own mapping rather than exposed as a bare RouterFunction @Bean:
|
||||
// Spring's own RouterFunctionMapping is ordered -1, ahead of the annotated controllers at
|
||||
// order 0, so a plain bean would shadow every dot-free backend route the denylist below
|
||||
// does not name (/v1/api-docs, /error, /actuator, ...). LOWEST_PRECEDENCE - 2 puts it after
|
||||
// the controllers and before the resource chain (LOWEST_PRECEDENCE - 1), which is the only
|
||||
// position where a catch-all fallback is safe.
|
||||
@Bean
|
||||
public RouterFunctionMapping spaDeepLinkFallbackMapping() {
|
||||
RouterFunction<ServerResponse> fallback =
|
||||
RouterFunctions.route(
|
||||
request -> {
|
||||
HttpServletRequest servletRequest = request.servletRequest();
|
||||
return "GET".equals(servletRequest.getMethod())
|
||||
&& isSpaFallbackRoute(
|
||||
stripContextPath(
|
||||
servletRequest.getContextPath(),
|
||||
servletRequest.getRequestURI()));
|
||||
},
|
||||
request ->
|
||||
ServerResponse.ok()
|
||||
.cacheControl(CacheControl.noCache().mustRevalidate())
|
||||
.contentType(MediaType.TEXT_HTML)
|
||||
.body(serveIndexHtml(request.servletRequest()).getBody()));
|
||||
RouterFunctionMapping mapping = new RouterFunctionMapping(fallback);
|
||||
mapping.setOrder(SPA_FALLBACK_ORDER);
|
||||
mapping.setMessageConverters(
|
||||
List.of(new StringHttpMessageConverter(StandardCharsets.UTF_8)));
|
||||
return mapping;
|
||||
}
|
||||
|
||||
// Dot-free paths only, so requests for real files still fall through to the resource
|
||||
// handlers. This is a denylist, so it is only safe because the mapping above runs after
|
||||
// the annotated controllers - see spaDeepLinkFallbackMapping.
|
||||
static boolean isSpaFallbackRoute(String path) {
|
||||
if (path == null || path.isEmpty() || "/".equals(path) || path.indexOf('.') >= 0) {
|
||||
return false;
|
||||
}
|
||||
String[] segments = (path.startsWith("/") ? path.substring(1) : path).split("/");
|
||||
return segments.length > 0
|
||||
&& !segments[0].isEmpty()
|
||||
&& !NON_SPA_FIRST_SEGMENTS.contains(segments[0]);
|
||||
}
|
||||
|
||||
private static String stripContextPath(String contextPath, String uri) {
|
||||
if (contextPath != null && !contextPath.isBlank() && uri.startsWith(contextPath)) {
|
||||
return uri.substring(contextPath.length());
|
||||
}
|
||||
return uri;
|
||||
}
|
||||
|
||||
private String buildFallbackHtml() {
|
||||
String baseUrl = contextPath.endsWith("/") ? contextPath : contextPath + "/";
|
||||
|
||||
|
||||
@@ -237,12 +237,12 @@ public class HardwareKeyStoreService {
|
||||
combined.append(env);
|
||||
}
|
||||
if (prop != null && !prop.isBlank()) {
|
||||
if (combined.length() > 0) {
|
||||
if (!combined.isEmpty()) {
|
||||
combined.append(java.io.File.pathSeparator);
|
||||
}
|
||||
combined.append(prop);
|
||||
}
|
||||
if (combined.length() == 0) {
|
||||
if (combined.isEmpty()) {
|
||||
return List.of();
|
||||
}
|
||||
return Arrays.stream(combined.toString().split("[,;" + java.io.File.pathSeparator + "]"))
|
||||
|
||||
-15
@@ -264,21 +264,6 @@ class GetInfoOnPDFMoreTest {
|
||||
@DisplayName("error handling")
|
||||
class Errors {
|
||||
|
||||
@Test
|
||||
@DisplayName("empty file input yields an error response")
|
||||
void emptyFile() throws Exception {
|
||||
MockMultipartFile mf =
|
||||
new MockMultipartFile("fileInput", "x.pdf", "application/pdf", new byte[0]);
|
||||
PDFFile request = new PDFFile();
|
||||
request.setFileInput(mf);
|
||||
ResponseEntity<byte[]> resp = getInfoOnPDF.getPdfInfo(request);
|
||||
// createErrorResponse returns HTTP 200 with a JSON body carrying an "error" field.
|
||||
assertThat(resp.getBody()).isNotNull();
|
||||
JsonNode body = om.readTree(resp.getBody());
|
||||
assertThat(body.has("error")).isTrue();
|
||||
assertThat(body.get("error").asText("")).contains("Invalid");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("veraPDF failure is swallowed and a report is still produced")
|
||||
void veraPdfFailureSwallowed() throws Exception {
|
||||
|
||||
-76
@@ -556,24 +556,6 @@ class GetInfoOnPDFTest {
|
||||
@DisplayName("Validation and Error Handling Tests")
|
||||
class ValidationErrorTests {
|
||||
|
||||
@Test
|
||||
@DisplayName("Should reject null file")
|
||||
void testValidation_NullFile() throws IOException {
|
||||
PDFFile request = new PDFFile();
|
||||
request.setFileInput(null);
|
||||
|
||||
ResponseEntity<byte[]> response = getInfoOnPDF.getPdfInfo(request);
|
||||
|
||||
Assertions.assertEquals(
|
||||
HttpStatus.OK, response.getStatusCode()); // Returns error JSON with 200
|
||||
String jsonResponse = new String(response.getBody(), StandardCharsets.UTF_8);
|
||||
JsonNode jsonNode = objectMapper.readTree(jsonResponse);
|
||||
|
||||
Assertions.assertTrue(jsonNode.has("error"));
|
||||
Assertions.assertTrue(
|
||||
jsonNode.get("error").asText("").contains("PDF file is required"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Should reject empty file")
|
||||
void testValidation_EmptyFile() throws IOException {
|
||||
@@ -591,64 +573,6 @@ class GetInfoOnPDFTest {
|
||||
|
||||
Assertions.assertTrue(jsonNode.has("error"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Should reject file that exceeds max size")
|
||||
void testValidation_TooLargeFile() throws IOException {
|
||||
MultipartFile largeFile =
|
||||
new MultipartFile() {
|
||||
@Override
|
||||
public String getName() {
|
||||
return "file";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getOriginalFilename() {
|
||||
return "large.pdf";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getContentType() {
|
||||
return MediaType.APPLICATION_PDF_VALUE;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isEmpty() {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public long getSize() {
|
||||
// Report 101 MB without allocating memory
|
||||
return 101L * 1024L * 1024L;
|
||||
}
|
||||
|
||||
@Override
|
||||
public byte[] getBytes() {
|
||||
return new byte[0];
|
||||
}
|
||||
|
||||
@Override
|
||||
public java.io.InputStream getInputStream() {
|
||||
return java.io.InputStream.nullInputStream();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void transferTo(java.io.File dest) throws IllegalStateException {}
|
||||
};
|
||||
|
||||
PDFFile request = new PDFFile();
|
||||
request.setFileInput(largeFile);
|
||||
|
||||
ResponseEntity<byte[]> response = getInfoOnPDF.getPdfInfo(request);
|
||||
|
||||
String jsonResponse = new String(response.getBody(), StandardCharsets.UTF_8);
|
||||
JsonNode jsonNode = objectMapper.readTree(jsonResponse);
|
||||
|
||||
Assertions.assertTrue(jsonNode.has("error"));
|
||||
Assertions.assertTrue(
|
||||
jsonNode.get("error").asText("").contains("exceeds maximum allowed size"));
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
|
||||
+89
@@ -4,12 +4,24 @@ import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.Mockito.mock;
|
||||
|
||||
import java.lang.reflect.Field;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.core.Ordered;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.http.converter.StringHttpMessageConverter;
|
||||
import org.springframework.mock.web.MockHttpServletRequest;
|
||||
import org.springframework.web.servlet.function.EntityResponse;
|
||||
import org.springframework.web.servlet.function.HandlerFunction;
|
||||
import org.springframework.web.servlet.function.RouterFunction;
|
||||
import org.springframework.web.servlet.function.ServerRequest;
|
||||
import org.springframework.web.servlet.function.ServerResponse;
|
||||
import org.springframework.web.servlet.function.support.RouterFunctionMapping;
|
||||
import org.springframework.web.util.ServletRequestPathUtils;
|
||||
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
|
||||
@@ -175,6 +187,83 @@ class ReactRoutingControllerTest {
|
||||
assertNotNull(response.getBody());
|
||||
}
|
||||
|
||||
// --- deep-link SPA fallback (router function) ---
|
||||
|
||||
@Test
|
||||
void isSpaFallbackRoute_acceptsDeepSpaPaths() {
|
||||
assertTrue(ReactRoutingController.isSpaFallbackRoute("/processor/pipelines/new"));
|
||||
assertTrue(ReactRoutingController.isSpaFallbackRoute("/processor/pipelines/123/runs/456"));
|
||||
assertTrue(ReactRoutingController.isSpaFallbackRoute("/workflow/sign/some-token"));
|
||||
assertTrue(ReactRoutingController.isSpaFallbackRoute("/processor/pipelines/new/"));
|
||||
// "pipelines" must not be swallowed by the "pipeline" exclusion
|
||||
assertTrue(ReactRoutingController.isSpaFallbackRoute("/pipelines"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void isSpaFallbackRoute_rejectsBackendStaticAndFilePaths() {
|
||||
assertFalse(ReactRoutingController.isSpaFallbackRoute("/api/v1/some/endpoint"));
|
||||
assertFalse(ReactRoutingController.isSpaFallbackRoute("/pipeline"));
|
||||
assertFalse(ReactRoutingController.isSpaFallbackRoute("/pipeline/anything"));
|
||||
assertFalse(ReactRoutingController.isSpaFallbackRoute("/assets/deep/path"));
|
||||
assertFalse(ReactRoutingController.isSpaFallbackRoute("/processor/pipelines/file.js"));
|
||||
assertFalse(ReactRoutingController.isSpaFallbackRoute("/branding/sub/logo.png"));
|
||||
assertFalse(ReactRoutingController.isSpaFallbackRoute("/"));
|
||||
assertFalse(ReactRoutingController.isSpaFallbackRoute(""));
|
||||
assertFalse(ReactRoutingController.isSpaFallbackRoute(null));
|
||||
}
|
||||
|
||||
@Test
|
||||
void spaDeepLinkFallback_servesIndexForDeepRoute() throws Exception {
|
||||
controller.init();
|
||||
RouterFunction<ServerResponse> router = routerOf(controller.spaDeepLinkFallbackMapping());
|
||||
|
||||
ServerRequest deepRequest = serverRequest("GET", "/processor/pipelines/new");
|
||||
Optional<HandlerFunction<ServerResponse>> handler = router.route(deepRequest);
|
||||
assertTrue(handler.isPresent());
|
||||
|
||||
ServerResponse response = handler.get().handle(deepRequest);
|
||||
assertEquals(HttpStatus.OK, response.statusCode());
|
||||
assertInstanceOf(EntityResponse.class, response);
|
||||
Object body = ((EntityResponse<?>) response).entity();
|
||||
assertTrue(body.toString().contains("Stirling PDF"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void spaDeepLinkFallback_ignoresApiFilesAndNonGet() {
|
||||
controller.init();
|
||||
RouterFunction<ServerResponse> router = routerOf(controller.spaDeepLinkFallbackMapping());
|
||||
|
||||
assertTrue(router.route(serverRequest("GET", "/api/v1/policies/run")).isEmpty());
|
||||
assertTrue(router.route(serverRequest("GET", "/branding/sub/logo.png")).isEmpty());
|
||||
assertTrue(router.route(serverRequest("POST", "/processor/pipelines/new")).isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void spaDeepLinkFallback_runsAfterControllersAndBeforeResources() {
|
||||
controller.init();
|
||||
int order = controller.spaDeepLinkFallbackMapping().getOrder();
|
||||
|
||||
// A catch-all denylist is only safe below every annotated controller; Spring's own
|
||||
// RouterFunctionMapping sits at -1, which would shadow /v1/api-docs, /error and friends.
|
||||
assertTrue(order > 0, "SPA fallback must run after annotated controllers");
|
||||
assertTrue(
|
||||
order < Ordered.LOWEST_PRECEDENCE - 1,
|
||||
"SPA fallback must run before the static-resource chain");
|
||||
}
|
||||
|
||||
private static RouterFunction<ServerResponse> routerOf(RouterFunctionMapping mapping) {
|
||||
@SuppressWarnings("unchecked")
|
||||
RouterFunction<ServerResponse> router =
|
||||
(RouterFunction<ServerResponse>) mapping.getRouterFunction();
|
||||
return router;
|
||||
}
|
||||
|
||||
private static ServerRequest serverRequest(String method, String uri) {
|
||||
MockHttpServletRequest servletRequest = new MockHttpServletRequest(method, uri);
|
||||
ServletRequestPathUtils.parseAndCache(servletRequest);
|
||||
return ServerRequest.create(servletRequest, List.of(new StringHttpMessageConverter()));
|
||||
}
|
||||
|
||||
// --- context path handling ---
|
||||
|
||||
@Test
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"com.hubspot.immutables:immutables-exceptions:1.9": {
|
||||
"name": "The Apache License, Version 2.0",
|
||||
"url": "http://www.apache.org/licenses/LICENSE-2.0.txt",
|
||||
"projectUrl": "https://github.com/HubSpot/hubspot-immutables/tree/58628096ac99b286fe4f8bfe12aa3cff0f0589d3"
|
||||
},
|
||||
"com.hubspot:algebra:1.5": {
|
||||
"name": "The Apache License, Version 2.0",
|
||||
"url": "http://www.apache.org/licenses/LICENSE-2.0.txt",
|
||||
"projectUrl": "https://github.com/HubSpot/algebra/tree/5d42983fd3a26539df9ba2cbeac32a1bddce0494"
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -2,7 +2,7 @@ package stirling.software.proprietary.access.model;
|
||||
|
||||
/** Types of resources whose access can be gated by {@link ResourceGrant}. */
|
||||
public enum ResourceType {
|
||||
// The admin portal / processor (frontend/editor/src/portal). Singleton resource (empty
|
||||
// The admin portal / processor (frontend/src/processor/proprietary). Singleton resource (empty
|
||||
// resourceId).
|
||||
PORTAL,
|
||||
// A stored S3/MCP/API integration configuration.
|
||||
|
||||
+26
-4
@@ -2,6 +2,7 @@ package stirling.software.proprietary.config;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.Executor;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
|
||||
import org.slf4j.MDC;
|
||||
@@ -12,10 +13,15 @@ import org.springframework.core.task.support.TaskExecutorAdapter;
|
||||
import org.springframework.scheduling.annotation.EnableAsync;
|
||||
import org.springframework.security.concurrent.DelegatingSecurityContextExecutor;
|
||||
|
||||
import jakarta.annotation.PreDestroy;
|
||||
|
||||
@Configuration
|
||||
@EnableAsync
|
||||
public class AsyncConfig {
|
||||
|
||||
private ExecutorService auditExecutorService;
|
||||
private ExecutorService aiStreamExecutorService;
|
||||
|
||||
/**
|
||||
* MDC context-propagating task decorator. Copies MDC context from the caller thread to the
|
||||
* virtual thread executing the task.
|
||||
@@ -44,8 +50,8 @@ public class AsyncConfig {
|
||||
|
||||
@Bean(name = "auditExecutor")
|
||||
public Executor auditExecutor() {
|
||||
TaskExecutorAdapter adapter =
|
||||
new TaskExecutorAdapter(Executors.newVirtualThreadPerTaskExecutor());
|
||||
auditExecutorService = Executors.newVirtualThreadPerTaskExecutor();
|
||||
TaskExecutorAdapter adapter = new TaskExecutorAdapter(auditExecutorService);
|
||||
adapter.setTaskDecorator(new MDCContextTaskDecorator());
|
||||
return adapter;
|
||||
}
|
||||
@@ -53,9 +59,25 @@ public class AsyncConfig {
|
||||
/** Propagates the request's SecurityContext onto background AI-orchestration threads. */
|
||||
@Bean(name = "aiStreamExecutor")
|
||||
public Executor aiStreamExecutor() {
|
||||
TaskExecutorAdapter adapter =
|
||||
new TaskExecutorAdapter(Executors.newVirtualThreadPerTaskExecutor());
|
||||
aiStreamExecutorService = Executors.newVirtualThreadPerTaskExecutor();
|
||||
TaskExecutorAdapter adapter = new TaskExecutorAdapter(aiStreamExecutorService);
|
||||
adapter.setTaskDecorator(new MDCContextTaskDecorator());
|
||||
return new DelegatingSecurityContextExecutor(adapter);
|
||||
}
|
||||
|
||||
/**
|
||||
* Close the underlying executors because the exposed Spring adapters do not own their
|
||||
* lifecycle.
|
||||
*/
|
||||
@PreDestroy
|
||||
void shutdown() {
|
||||
shutdownExecutor(auditExecutorService);
|
||||
shutdownExecutor(aiStreamExecutorService);
|
||||
}
|
||||
|
||||
private void shutdownExecutor(ExecutorService executor) {
|
||||
if (executor != null) {
|
||||
executor.shutdownNow();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+17
@@ -16,6 +16,8 @@ import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.web.client.RestClientResponseException;
|
||||
|
||||
import jakarta.annotation.PreDestroy;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
|
||||
@@ -79,6 +81,21 @@ public class PolicyEngine {
|
||||
|
||||
private final ExecutorService asyncExecutor = ExecutorFactory.newVirtualThreadExecutor();
|
||||
|
||||
/** Stop the service-owned executor when the application context is closed or restarted. */
|
||||
@PreDestroy
|
||||
void shutdown() {
|
||||
log.debug("Shutting down policy engine executor");
|
||||
asyncExecutor.shutdown();
|
||||
try {
|
||||
if (!asyncExecutor.awaitTermination(5, java.util.concurrent.TimeUnit.SECONDS)) {
|
||||
asyncExecutor.shutdownNow();
|
||||
}
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
asyncExecutor.shutdownNow();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Submit a pipeline to run asynchronously. The handle's run id scopes a {@link TaskManager} job
|
||||
* (status/notes/results observable via the job endpoints); its future resolves when the run
|
||||
|
||||
+1
-1
@@ -199,7 +199,7 @@ public class UserController {
|
||||
return ResponseEntity.status(HttpStatus.CONFLICT)
|
||||
.body(Map.of("error", "usernameExists", "message", "Username already exists"));
|
||||
}
|
||||
if (newUsername != null && newUsername.length() > 0) {
|
||||
if (newUsername != null && !newUsername.isEmpty()) {
|
||||
try {
|
||||
userService.changeUsername(user, newUsername);
|
||||
} catch (IllegalArgumentException e) {
|
||||
|
||||
+1
-1
@@ -205,7 +205,7 @@ public class UserService implements UserServiceInterface {
|
||||
User user =
|
||||
findByUsernameIgnoreCase(username)
|
||||
.orElseThrow(() -> new UsernameNotFoundException("User not found"));
|
||||
if (user.getApiKey() == null || user.getApiKey().length() == 0) {
|
||||
if (user.getApiKey() == null || user.getApiKey().isEmpty()) {
|
||||
user = addApiKeyToUser(username);
|
||||
}
|
||||
return user.getApiKey();
|
||||
|
||||
+1
-1
@@ -224,7 +224,7 @@ public class PortalInfraAuditService {
|
||||
if (word.isEmpty()) {
|
||||
continue;
|
||||
}
|
||||
if (sb.length() > 0) {
|
||||
if (!sb.isEmpty()) {
|
||||
sb.append(' ');
|
||||
}
|
||||
String lower = word.toLowerCase(Locale.ROOT);
|
||||
|
||||
+2
-2
@@ -515,7 +515,7 @@ public class UserLicenseSettingsService {
|
||||
appendIfPresent(builder, applicationProperties.getAutomaticallyGenerated().getUUID());
|
||||
appendIfPresent(builder, applicationProperties.getPremium().getKey());
|
||||
|
||||
if (builder.length() == 0) {
|
||||
if (builder.isEmpty()) {
|
||||
builder.append(DEFAULT_INTEGRITY_SECRET);
|
||||
}
|
||||
|
||||
@@ -524,7 +524,7 @@ public class UserLicenseSettingsService {
|
||||
|
||||
private void appendIfPresent(StringBuilder builder, String value) {
|
||||
if (value != null && !value.isBlank()) {
|
||||
if (builder.length() > 0) {
|
||||
if (!builder.isEmpty()) {
|
||||
builder.append(SIGNATURE_SEPARATOR);
|
||||
}
|
||||
builder.append(value);
|
||||
|
||||
+5
@@ -7,12 +7,14 @@ import java.util.concurrent.TimeUnit;
|
||||
|
||||
import org.springframework.scheduling.annotation.Scheduled;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
|
||||
import stirling.software.proprietary.storage.model.StorageCleanupEntry;
|
||||
import stirling.software.proprietary.storage.provider.StorageProvider;
|
||||
import stirling.software.proprietary.storage.repository.FileShareAccessRepository;
|
||||
import stirling.software.proprietary.storage.repository.FileShareRepository;
|
||||
import stirling.software.proprietary.storage.repository.StorageCleanupEntryRepository;
|
||||
|
||||
@@ -25,6 +27,7 @@ public class StorageCleanupService {
|
||||
|
||||
private final StorageProvider storageProvider;
|
||||
private final StorageCleanupEntryRepository cleanupEntryRepository;
|
||||
private final FileShareAccessRepository fileShareAccessRepository;
|
||||
private final FileShareRepository fileShareRepository;
|
||||
|
||||
@Scheduled(fixedDelay = 1, timeUnit = TimeUnit.DAYS)
|
||||
@@ -62,12 +65,14 @@ public class StorageCleanupService {
|
||||
}
|
||||
|
||||
@Scheduled(fixedDelay = 1, timeUnit = TimeUnit.DAYS)
|
||||
@Transactional
|
||||
public void cleanupExpiredShareLinks() {
|
||||
List<stirling.software.proprietary.storage.model.FileShare> expired =
|
||||
fileShareRepository.findByExpiresAtBeforeAndShareTokenNotNull(LocalDateTime.now());
|
||||
if (expired.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
expired.forEach(fileShareAccessRepository::deleteByFileShare);
|
||||
fileShareRepository.deleteAll(expired);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,6 +6,11 @@ dependencies {
|
||||
implementation project(':common')
|
||||
implementation project(':proprietary')
|
||||
|
||||
// Markdown -> HTML for rendering versioned legal documents (agreement) to PDF via the
|
||||
// shared FileToPdf/WeasyPrint path in :common. Same library the core Markdown-to-PDF tool uses.
|
||||
implementation "org.commonmark:commonmark:$commonmarkVersion"
|
||||
implementation "org.commonmark:commonmark-ext-gfm-tables:$commonmarkVersion"
|
||||
|
||||
api 'org.springframework.boot:spring-boot-starter-security'
|
||||
api 'org.springframework.boot:spring-boot-starter-data-jpa'
|
||||
api 'org.springframework.boot:spring-boot-starter-oauth2-resource-server'
|
||||
|
||||
@@ -20,7 +20,8 @@ import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
|
||||
"stirling.software.saas.ai.repository",
|
||||
"stirling.software.saas.payg.repository",
|
||||
"stirling.software.saas.payg.bundle",
|
||||
"stirling.software.saas.procurement.repository"
|
||||
"stirling.software.saas.procurement.repository",
|
||||
"stirling.software.saas.legal"
|
||||
})
|
||||
@EntityScan({
|
||||
"stirling.software.saas.accountlink",
|
||||
@@ -28,6 +29,7 @@ import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
|
||||
"stirling.software.saas.billing.model",
|
||||
"stirling.software.saas.ai.model",
|
||||
"stirling.software.saas.payg",
|
||||
"stirling.software.saas.procurement.model"
|
||||
"stirling.software.saas.procurement.model",
|
||||
"stirling.software.saas.legal"
|
||||
})
|
||||
public class SaasJpaConfig {}
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
package stirling.software.saas.legal;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
import org.hibernate.annotations.CreationTimestamp;
|
||||
|
||||
import jakarta.persistence.Column;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.GeneratedValue;
|
||||
import jakarta.persistence.GenerationType;
|
||||
import jakarta.persistence.Id;
|
||||
import jakarta.persistence.Table;
|
||||
|
||||
import lombok.Getter;
|
||||
import lombok.NoArgsConstructor;
|
||||
import lombok.Setter;
|
||||
|
||||
/**
|
||||
* An append-only record that a user accepted a versioned legal document at a particular moment in
|
||||
* the product. Distinct from a signed agreement (which is a negotiated, signature-bearing artifact,
|
||||
* see {@code ProcurementAgreementSignature}); this captures the lighter clickwrap consents — the
|
||||
* EULA accepted at trial start and at quote generation — with the exact document version, so what
|
||||
* was agreed is auditable even after the document versions up.
|
||||
*/
|
||||
@Entity
|
||||
@Table(name = "legal_consent")
|
||||
@NoArgsConstructor
|
||||
@Getter
|
||||
@Setter
|
||||
public class LegalConsent implements Serializable {
|
||||
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
@Column(name = "consent_id")
|
||||
private Long consentId;
|
||||
|
||||
@Column(name = "team_id")
|
||||
private Long teamId;
|
||||
|
||||
@Column(name = "user_id")
|
||||
private Long userId;
|
||||
|
||||
@Column(name = "document_id", nullable = false, length = 64)
|
||||
private String documentId;
|
||||
|
||||
@Column(name = "document_version", nullable = false, length = 32)
|
||||
private String documentVersion;
|
||||
|
||||
// Where in the product the consent was given: "trial", "quote", etc.
|
||||
@Column(name = "context", nullable = false, length = 32)
|
||||
private String context;
|
||||
|
||||
@Column(name = "signer_ip", length = 64)
|
||||
private String signerIp;
|
||||
|
||||
@CreationTimestamp
|
||||
@Column(name = "consented_at", nullable = false, updatable = false)
|
||||
private LocalDateTime consentedAt;
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
package stirling.software.saas.legal;
|
||||
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
|
||||
public interface LegalConsentRepository extends JpaRepository<LegalConsent, Long> {}
|
||||
@@ -0,0 +1,47 @@
|
||||
package stirling.software.saas.legal;
|
||||
|
||||
import org.springframework.context.annotation.Profile;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
|
||||
/** Records clickwrap consents to versioned legal documents (see {@link LegalConsent}). */
|
||||
@Slf4j
|
||||
@Service
|
||||
@Profile("saas")
|
||||
@RequiredArgsConstructor
|
||||
public class LegalConsentService {
|
||||
|
||||
private final LegalDocumentRegistry registry;
|
||||
private final LegalConsentRepository consents;
|
||||
|
||||
/**
|
||||
* Record that the given user accepted the current version of {@code documentId} in {@code
|
||||
* context} (e.g. "trial", "quote"). No-op for an unknown document. Best-effort: callers treat a
|
||||
* failure as non-fatal so it never blocks the flow the consent accompanies.
|
||||
*/
|
||||
@Transactional
|
||||
public void record(Long teamId, Long userId, String documentId, String context, String ip) {
|
||||
LegalDocumentMeta meta = registry.meta(documentId).orElse(null);
|
||||
if (meta == null) {
|
||||
log.warn("[legal] consent for unknown document '{}' ignored", documentId);
|
||||
return;
|
||||
}
|
||||
LegalConsent consent = new LegalConsent();
|
||||
consent.setTeamId(teamId);
|
||||
consent.setUserId(userId);
|
||||
consent.setDocumentId(meta.id());
|
||||
consent.setDocumentVersion(meta.version());
|
||||
consent.setContext(context);
|
||||
consent.setSignerIp(ip);
|
||||
consents.save(consent);
|
||||
log.info(
|
||||
"[legal] consent recorded team={} doc={} v{} context={}",
|
||||
teamId,
|
||||
meta.id(),
|
||||
meta.version(),
|
||||
context);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
package stirling.software.saas.legal;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
import org.springframework.context.annotation.Profile;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.security.access.prepost.PreAuthorize;
|
||||
import org.springframework.security.core.Authentication;
|
||||
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 io.swagger.v3.oas.annotations.Hidden;
|
||||
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
|
||||
import stirling.software.proprietary.model.TeamMembership;
|
||||
import stirling.software.proprietary.security.database.repository.UserRepository;
|
||||
import stirling.software.proprietary.security.model.User;
|
||||
import stirling.software.proprietary.security.repository.TeamMembershipRepository;
|
||||
import stirling.software.saas.util.AuthenticationUtils;
|
||||
|
||||
/**
|
||||
* Serves the versioned legal documents (EULA, SLA exhibit, subprocessors) for in-product viewing,
|
||||
* and records the lighter clickwrap consents. The enterprise agreement itself is served + signed
|
||||
* through the procurement controller, since it needs a quote to fill its Order Form.
|
||||
*/
|
||||
@Slf4j
|
||||
@Hidden
|
||||
@RestController
|
||||
@RequestMapping("/api/v1/legal")
|
||||
@Profile("saas")
|
||||
@RequiredArgsConstructor
|
||||
public class LegalController {
|
||||
|
||||
private final LegalDocumentRegistry registry;
|
||||
private final LegalConsentService consents;
|
||||
private final TeamMembershipRepository memberRepo;
|
||||
private final UserRepository userRepository;
|
||||
|
||||
/** A legal document rendered for viewing: registry metadata + the static markdown body. */
|
||||
public record LegalDocumentResponse(
|
||||
String docId,
|
||||
String version,
|
||||
String versionLabel,
|
||||
String displayName,
|
||||
String effectiveDate,
|
||||
String status,
|
||||
String markdown) {}
|
||||
|
||||
public record ConsentRequest(String documentId, String context) {}
|
||||
|
||||
/** Fetch a legal document's current version as markdown. 404 for an unknown document. */
|
||||
@GetMapping("/{docId}")
|
||||
@PreAuthorize("isAuthenticated()")
|
||||
public ResponseEntity<LegalDocumentResponse> document(@PathVariable String docId) {
|
||||
return registry.meta(docId)
|
||||
.<ResponseEntity<LegalDocumentResponse>>map(
|
||||
meta ->
|
||||
ResponseEntity.ok(
|
||||
new LegalDocumentResponse(
|
||||
meta.id(),
|
||||
meta.version(),
|
||||
meta.versionLabel(),
|
||||
meta.displayName(),
|
||||
meta.effectiveDate(),
|
||||
meta.status(),
|
||||
registry.staticMarkdown(docId))))
|
||||
.orElseGet(() -> ResponseEntity.notFound().build());
|
||||
}
|
||||
|
||||
/**
|
||||
* Record a clickwrap consent (e.g. the EULA accepted at trial start or quote generation).
|
||||
* Best-effort — a teamless caller still returns 200 so the accompanying flow is never blocked.
|
||||
*/
|
||||
@PostMapping("/consent")
|
||||
@PreAuthorize("isAuthenticated()")
|
||||
public ResponseEntity<Void> consent(
|
||||
@RequestBody ConsentRequest request, Authentication auth, HttpServletRequest http) {
|
||||
if (request == null || request.documentId() == null || request.context() == null) {
|
||||
return ResponseEntity.badRequest().build();
|
||||
}
|
||||
Optional<TeamMembership> membership = primaryMembership(auth);
|
||||
Long teamId = membership.map(m -> m.getTeam().getId()).orElse(null);
|
||||
Long userId = membership.map(m -> m.getUser().getId()).orElse(null);
|
||||
// Best-effort for real: consent is audit metadata, not an authorisation gate, so a failed
|
||||
// write must not fail the trial start or quote generation this call accompanies. Previously
|
||||
// that only held because the caller happened to swallow the 500.
|
||||
try {
|
||||
consents.record(
|
||||
teamId, userId, request.documentId(), request.context(), clientIp(http));
|
||||
} catch (RuntimeException e) {
|
||||
log.warn(
|
||||
"[legal] consent not recorded doc={} context={}: {}",
|
||||
request.documentId(),
|
||||
request.context(),
|
||||
e.getMessage());
|
||||
}
|
||||
return ResponseEntity.ok().build();
|
||||
}
|
||||
|
||||
private Optional<TeamMembership> primaryMembership(Authentication auth) {
|
||||
User user;
|
||||
try {
|
||||
user = AuthenticationUtils.getCurrentUser(auth, userRepository);
|
||||
} catch (SecurityException e) {
|
||||
return Optional.empty();
|
||||
}
|
||||
return memberRepo.findPrimaryMembership(user.getId()).stream().findFirst();
|
||||
}
|
||||
|
||||
/**
|
||||
* Best guess at the caller's address, for the audit record.
|
||||
*
|
||||
* <p>Informational only, and must stay that way: the first {@code X-Forwarded-For} hop is set
|
||||
* by the client, so a stored address is trivially spoofable and is not evidence of where a
|
||||
* consent or signature came from. Treat it as a hint when reconstructing events, never as
|
||||
* proof.
|
||||
*/
|
||||
private static String clientIp(HttpServletRequest request) {
|
||||
String forwarded = request.getHeader("X-Forwarded-For");
|
||||
if (forwarded != null && !forwarded.isBlank()) {
|
||||
return forwarded.split(",")[0].trim();
|
||||
}
|
||||
return request.getRemoteAddr();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package stirling.software.saas.legal;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* One legal document's registry entry, as declared in {@code legal/manifest.json}. Immutable
|
||||
* snapshot loaded at startup by {@link LegalDocumentRegistry}.
|
||||
*
|
||||
* <p>{@code parts} lists the pieces, in render order, that make up the document. A plain entry
|
||||
* (e.g. {@code "msa.md"}) is a static markdown file under {@code legal/<id>/<version>/}; an entry
|
||||
* prefixed with {@code "@"} (e.g. {@code "@order-form"}) is a dynamic section that a document
|
||||
* assembler generates at render time.
|
||||
*/
|
||||
public record LegalDocumentMeta(
|
||||
String id,
|
||||
String label,
|
||||
String displayName,
|
||||
String version,
|
||||
String effectiveDate,
|
||||
String status,
|
||||
List<String> parts) {
|
||||
|
||||
/** Fully-qualified version label shown to users and stored on signatures, e.g. "SEA v0.9.1". */
|
||||
public String versionLabel() {
|
||||
return label + " v" + version;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
package stirling.software.saas.legal;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import org.springframework.core.io.ClassPathResource;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
|
||||
import jakarta.annotation.PostConstruct;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
|
||||
/**
|
||||
* Loads the versioned legal-document registry from {@code legal/manifest.json} on startup and
|
||||
* serves document metadata + rendered markdown from the classpath.
|
||||
*
|
||||
* <p>Publishing a new version of any document is a content-only change: drop the markdown under
|
||||
* {@code legal/<id>/<newVersion>/} and bump that document's {@code version} in the manifest — no
|
||||
* code change. Signatures pin the exact {@code {id, version, contentHash}} they were signed against
|
||||
* (see the procurement agreement flow), so historical documents stay reproducible.
|
||||
*
|
||||
* <p>Token slots of the form <code>{{name}}</code> in the markdown are filled at render time. This
|
||||
* registry fills the document-level common tokens ({@code version}, {@code version_date}, {@code
|
||||
* subprocessor_url}, {@code eula_url}); callers that need per-quote tokens (the enterprise
|
||||
* agreement's Order Form) fill the rest.
|
||||
*/
|
||||
@Slf4j
|
||||
@Service
|
||||
public class LegalDocumentRegistry {
|
||||
|
||||
private static final String MANIFEST = "legal/manifest.json";
|
||||
private static final Pattern TOKEN = Pattern.compile("\\{\\{\\s*([a-zA-Z0-9_]+)\\s*}}");
|
||||
|
||||
private final ObjectMapper objectMapper = new ObjectMapper();
|
||||
|
||||
private final Map<String, LegalDocumentMeta> documents = new LinkedHashMap<>();
|
||||
private String subprocessorUrl = "";
|
||||
private String eulaUrl = "";
|
||||
|
||||
@PostConstruct
|
||||
void load() throws IOException {
|
||||
JsonNode root;
|
||||
try (InputStream in = new ClassPathResource(MANIFEST).getInputStream()) {
|
||||
root = objectMapper.readTree(in);
|
||||
}
|
||||
subprocessorUrl = root.path("subprocessorUrl").asText("");
|
||||
eulaUrl = root.path("eulaUrl").asText("");
|
||||
JsonNode docs = root.path("documents");
|
||||
docs.fieldNames()
|
||||
.forEachRemaining(
|
||||
id -> {
|
||||
JsonNode d = docs.get(id);
|
||||
List<String> parts =
|
||||
objectMapper.convertValue(
|
||||
d.path("parts"),
|
||||
objectMapper
|
||||
.getTypeFactory()
|
||||
.constructCollectionType(
|
||||
List.class, String.class));
|
||||
documents.put(
|
||||
id,
|
||||
new LegalDocumentMeta(
|
||||
id,
|
||||
d.path("label").asText(id),
|
||||
d.path("displayName").asText(id),
|
||||
d.path("version").asText("0"),
|
||||
d.path("effectiveDate").asText(""),
|
||||
d.path("status").asText("draft"),
|
||||
parts == null ? List.of() : parts));
|
||||
});
|
||||
log.info("[legal] loaded {} document(s) from {}", documents.size(), MANIFEST);
|
||||
}
|
||||
|
||||
public Optional<LegalDocumentMeta> meta(String docId) {
|
||||
return Optional.ofNullable(documents.get(docId));
|
||||
}
|
||||
|
||||
public String subprocessorUrl() {
|
||||
return subprocessorUrl;
|
||||
}
|
||||
|
||||
public String eulaUrl() {
|
||||
return eulaUrl;
|
||||
}
|
||||
|
||||
/** Document-level tokens available to every document (before any per-quote tokens). */
|
||||
public Map<String, String> commonTokens(LegalDocumentMeta meta) {
|
||||
Map<String, String> t = new LinkedHashMap<>();
|
||||
t.put("version", meta.version());
|
||||
t.put("version_date", meta.effectiveDate());
|
||||
t.put("subprocessor_url", subprocessorUrl);
|
||||
t.put("eula_url", eulaUrl);
|
||||
return t;
|
||||
}
|
||||
|
||||
/** Read one static markdown part of a document from the classpath. */
|
||||
public String readPart(LegalDocumentMeta meta, String partFile) {
|
||||
String path = "legal/" + meta.id() + "/" + meta.version() + "/" + partFile;
|
||||
try (InputStream in = new ClassPathResource(path).getInputStream()) {
|
||||
return new String(in.readAllBytes(), StandardCharsets.UTF_8);
|
||||
} catch (IOException e) {
|
||||
throw new IllegalStateException("Missing legal document part: " + path, e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The concatenated static parts of a document (dynamic {@code @}-parts skipped), with only the
|
||||
* common tokens filled. Use for fully-static documents (EULA, SLA, subprocessors).
|
||||
*/
|
||||
public String staticMarkdown(String docId) {
|
||||
LegalDocumentMeta meta =
|
||||
meta(docId)
|
||||
.orElseThrow(
|
||||
() -> new IllegalArgumentException("Unknown document: " + docId));
|
||||
Map<String, String> tokens = commonTokens(meta);
|
||||
StringBuilder sb = new StringBuilder();
|
||||
for (String part : meta.parts()) {
|
||||
if (part.startsWith("@")) continue; // dynamic section — not part of the static body
|
||||
if (sb.length() > 0) sb.append("\n\n");
|
||||
sb.append(fill(readPart(meta, part), tokens));
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
/** Replace {@code {{token}}} slots; unknown tokens are left intact so gaps are visible. */
|
||||
public static String fill(String markdown, Map<String, String> tokens) {
|
||||
Matcher m = TOKEN.matcher(markdown);
|
||||
StringBuilder out = new StringBuilder();
|
||||
while (m.find()) {
|
||||
String key = m.group(1);
|
||||
String value = tokens.get(key);
|
||||
m.appendReplacement(
|
||||
out,
|
||||
value == null
|
||||
? Matcher.quoteReplacement(m.group(0))
|
||||
: Matcher.quoteReplacement(value));
|
||||
}
|
||||
m.appendTail(out);
|
||||
return out.toString();
|
||||
}
|
||||
}
|
||||
@@ -34,17 +34,22 @@ import lombok.Setter;
|
||||
@Entity
|
||||
@Table(
|
||||
name = "payg_prepaid_bundle",
|
||||
// Declared here for ddl-auto (fresh schemas) and to document intent. The authoritative creator
|
||||
// in production is the Supabase CLI migration 20260720000000_payg_prepaid_bundle, which builds
|
||||
// Declared here for ddl-auto (fresh schemas) and to document intent. The authoritative
|
||||
// creator
|
||||
// in production is the Supabase CLI migration 20260720000000_payg_prepaid_bundle, which
|
||||
// builds
|
||||
// the partial forms (WHERE units_remaining > 0 / WHERE stripe_ref IS NOT NULL). Flyway was
|
||||
// retired for SaaS (#7100), so there is no migration twin — names match the CLI migration.
|
||||
indexes = {
|
||||
// Hot-path FIFO draw lookup — findDrawableForUpdate runs a locked read on every billable
|
||||
// charge past the free grant; without it that degrades to a locked scan as the table grows.
|
||||
// Hot-path FIFO draw lookup — findDrawableForUpdate runs a locked read on every
|
||||
// billable
|
||||
// charge past the free grant; without it that degrades to a locked scan as the table
|
||||
// grows.
|
||||
@Index(
|
||||
name = "idx_payg_prepaid_bundle_team_expiry",
|
||||
columnList = "team_id, expires_at"),
|
||||
// One pool per Stripe payment — the idempotency guard so a redelivered invoice.paid can't
|
||||
// One pool per Stripe payment — the idempotency guard so a redelivered invoice.paid
|
||||
// can't
|
||||
// credit the same purchase twice.
|
||||
@Index(
|
||||
name = "uq_payg_prepaid_bundle_stripe_ref",
|
||||
|
||||
+240
-7
@@ -22,6 +22,8 @@ import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
|
||||
import io.swagger.v3.oas.annotations.Hidden;
|
||||
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
|
||||
import stirling.software.common.model.enumeration.TeamRole;
|
||||
@@ -30,6 +32,8 @@ import stirling.software.proprietary.security.database.repository.UserRepository
|
||||
import stirling.software.proprietary.security.model.User;
|
||||
import stirling.software.proprietary.security.repository.TeamMembershipRepository;
|
||||
import stirling.software.saas.procurement.config.ProcurementConfigurationProperties;
|
||||
import stirling.software.saas.procurement.legal.AgreementSigning;
|
||||
import stirling.software.saas.procurement.model.ProcurementAgreementSignature;
|
||||
import stirling.software.saas.procurement.model.ProcurementDeal;
|
||||
import stirling.software.saas.procurement.model.ProcurementQuote;
|
||||
import stirling.software.saas.procurement.model.QuoteDetails;
|
||||
@@ -178,7 +182,17 @@ public class ProcurementController {
|
||||
String taxId) {}
|
||||
|
||||
/** Trial setup captured before the trial starts: deployment target + seat count. */
|
||||
public record StartTrialRequest(String deployment, int users) {}
|
||||
/**
|
||||
* Setup step 2 collects the buying entity; all of it is optional so an older client still
|
||||
* starts.
|
||||
*/
|
||||
public record StartTrialRequest(
|
||||
String deployment,
|
||||
int users,
|
||||
String businessName,
|
||||
String contactName,
|
||||
String contactEmail,
|
||||
String inviteEmails) {}
|
||||
|
||||
public record SnapshotResponse(
|
||||
Long dealId,
|
||||
@@ -190,8 +204,33 @@ public class ProcurementController {
|
||||
int trialExtensionsUsed,
|
||||
boolean licensed,
|
||||
String licenseKey,
|
||||
// Version label of the signed agreement PDF available for download, else null.
|
||||
String agreementSignedVersion,
|
||||
// Buying entity captured at trial setup; null on deals started before that step.
|
||||
String businessName,
|
||||
String contactName,
|
||||
String contactEmail,
|
||||
QuoteResponse latestQuote) {}
|
||||
|
||||
/** The filled agreement for review: registry metadata + the rendered markdown body. */
|
||||
public record AgreementDocumentResponse(
|
||||
String docId,
|
||||
String version,
|
||||
String versionLabel,
|
||||
String displayName,
|
||||
String effectiveDate,
|
||||
String status,
|
||||
String markdown) {}
|
||||
|
||||
/** Buyer-supplied signing inputs from the agreement stage. */
|
||||
public record SignAgreementRequest(
|
||||
String customerLegalName,
|
||||
String signatoryName,
|
||||
String signatoryTitle,
|
||||
boolean authorityConfirmed) {}
|
||||
|
||||
public record SignAgreementResponse(Long signatureId, String versionLabel, boolean pdfStored) {}
|
||||
|
||||
// ---- endpoints ----------------------------------------------------------
|
||||
|
||||
/**
|
||||
@@ -213,7 +252,8 @@ public class ProcurementController {
|
||||
}
|
||||
|
||||
private static final SnapshotResponse EMPTY_SNAPSHOT =
|
||||
new SnapshotResponse(null, null, null, 0, null, null, 0, false, null, null);
|
||||
new SnapshotResponse(
|
||||
null, null, null, 0, null, null, 0, false, null, null, null, null, null, null);
|
||||
|
||||
/**
|
||||
* Download the offline / air-gapped licence file (.lic) for the team — available for an
|
||||
@@ -239,6 +279,15 @@ public class ProcurementController {
|
||||
.orElseGet(() -> ResponseEntity.notFound().build());
|
||||
}
|
||||
|
||||
/** Mark the account as looking at enterprise. Idempotent; never disturbs an existing deal. */
|
||||
@PostMapping("/interest")
|
||||
@PreAuthorize("isAuthenticated()")
|
||||
public ResponseEntity<SnapshotResponse> recordInterest(Authentication auth) {
|
||||
Long teamId = requireLeader(auth);
|
||||
if (teamId == null) return ResponseEntity.status(HttpStatus.FORBIDDEN).build();
|
||||
return ResponseEntity.ok(toSnapshot(procurement.recordInterest(teamId), true));
|
||||
}
|
||||
|
||||
@PostMapping("/trial/start")
|
||||
@PreAuthorize("isAuthenticated()")
|
||||
public ResponseEntity<SnapshotResponse> startTrial(
|
||||
@@ -248,8 +297,30 @@ public class ProcurementController {
|
||||
// Body is optional so an older client (no setup step) still starts a cloud trial.
|
||||
String deployment = request != null ? request.deployment() : null;
|
||||
int seats = request != null ? request.users() : 0;
|
||||
return ResponseEntity.ok(
|
||||
toSnapshot(procurement.startTrial(teamId, deployment, seats), true));
|
||||
ProcurementDeal deal;
|
||||
try {
|
||||
deal =
|
||||
procurement.startTrial(
|
||||
teamId,
|
||||
deployment,
|
||||
seats,
|
||||
request != null ? request.businessName() : null,
|
||||
request != null ? request.contactName() : null,
|
||||
request != null ? request.contactEmail() : null,
|
||||
request != null ? request.inviteEmails() : null);
|
||||
} catch (IllegalStateException e) {
|
||||
// Past the trial the deal holds a committed licence; restarting would replace it.
|
||||
log.warn("[procurement] trial start rejected team={}: {}", teamId, e.getMessage());
|
||||
return ResponseEntity.status(HttpStatus.CONFLICT).build();
|
||||
}
|
||||
// After the trial exists, so a rejected invite can never stop it starting.
|
||||
if (request != null) {
|
||||
procurement.sendTrialInvites(
|
||||
teamId,
|
||||
primaryMembership(auth).map(TeamMembership::getUser).orElse(null),
|
||||
request.inviteEmails());
|
||||
}
|
||||
return ResponseEntity.ok(toSnapshot(deal, true));
|
||||
}
|
||||
|
||||
@PostMapping("/trial/extend")
|
||||
@@ -270,8 +341,17 @@ public class ProcurementController {
|
||||
@RequestBody QuoteRequest request, Authentication auth) {
|
||||
Long teamId = requireLeader(auth);
|
||||
if (teamId == null) return ResponseEntity.status(HttpStatus.FORBIDDEN).build();
|
||||
return ResponseEntity.ok(
|
||||
toQuote(procurement.buildQuote(teamId, request.toConfig(), request.toDetails())));
|
||||
try {
|
||||
return ResponseEntity.ok(
|
||||
toQuote(
|
||||
procurement.buildQuote(
|
||||
teamId, request.toConfig(), request.toDetails())));
|
||||
} catch (IllegalStateException e) {
|
||||
// Below the minimum deal size, or the deal is already live. A client error, not a
|
||||
// fault.
|
||||
log.warn("[procurement] quote rejected team={}: {}", teamId, e.getMessage());
|
||||
return ResponseEntity.status(HttpStatus.CONFLICT).build();
|
||||
}
|
||||
}
|
||||
|
||||
// Issue + accept are Supabase edge functions (they own Stripe): issue-procurement-quote turns a
|
||||
@@ -293,6 +373,111 @@ public class ProcurementController {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The filled Stirling Enterprise Agreement (MSA + Order Form + DPA) for the team's current
|
||||
* quote, as markdown, for the buyer to review before signing. 404 when there's no quote yet.
|
||||
*/
|
||||
@GetMapping("/agreement/document")
|
||||
@PreAuthorize("isAuthenticated()")
|
||||
public ResponseEntity<AgreementDocumentResponse> agreementDocument(Authentication auth) {
|
||||
Long teamId = requireLeader(auth);
|
||||
if (teamId == null) return ResponseEntity.status(HttpStatus.FORBIDDEN).build();
|
||||
return procurement
|
||||
.agreementDocument(teamId)
|
||||
.<ResponseEntity<AgreementDocumentResponse>>map(
|
||||
a ->
|
||||
ResponseEntity.ok(
|
||||
new AgreementDocumentResponse(
|
||||
a.docId(),
|
||||
a.version(),
|
||||
a.versionLabel(),
|
||||
a.displayName(),
|
||||
a.effectiveDate(),
|
||||
a.status(),
|
||||
a.markdown())))
|
||||
.orElseGet(() -> ResponseEntity.notFound().build());
|
||||
}
|
||||
|
||||
/**
|
||||
* Record a signed agreement: capture the typed legal name / signatory / title / authority, pin
|
||||
* the exact document version + content hash + variable snapshot, and store the rendered PDF
|
||||
* (best-effort). The caller then proceeds to accept the quote as before.
|
||||
*/
|
||||
@PostMapping("/agreement/sign")
|
||||
@PreAuthorize("isAuthenticated()")
|
||||
public ResponseEntity<SignAgreementResponse> signAgreement(
|
||||
@RequestBody SignAgreementRequest request,
|
||||
Authentication auth,
|
||||
HttpServletRequest http) {
|
||||
Long teamId = requireLeader(auth);
|
||||
if (teamId == null) return ResponseEntity.status(HttpStatus.FORBIDDEN).build();
|
||||
if (request == null
|
||||
|| request.signatoryName() == null
|
||||
|| request.signatoryName().isBlank()
|
||||
|| !request.authorityConfirmed()) {
|
||||
return ResponseEntity.badRequest().build();
|
||||
}
|
||||
try {
|
||||
ProcurementAgreementSignature sig =
|
||||
procurement.signAgreement(
|
||||
teamId,
|
||||
new AgreementSigning(
|
||||
request.customerLegalName(),
|
||||
request.signatoryName(),
|
||||
request.signatoryTitle(),
|
||||
request.authorityConfirmed()),
|
||||
clientIp(http));
|
||||
return ResponseEntity.ok(
|
||||
new SignAgreementResponse(
|
||||
sig.getSignatureId(), sig.getDocumentLabel(), sig.getPdf() != null));
|
||||
} catch (IllegalStateException e) {
|
||||
return ResponseEntity.status(HttpStatus.CONFLICT).build();
|
||||
}
|
||||
}
|
||||
|
||||
/** Download the stored signed-agreement PDF for the team. 404 if none was rendered/stored. */
|
||||
@GetMapping("/agreement/signature/pdf")
|
||||
@PreAuthorize("isAuthenticated()")
|
||||
public ResponseEntity<byte[]> signaturePdf(Authentication auth) {
|
||||
Long teamId = requireLeader(auth);
|
||||
if (teamId == null) return ResponseEntity.status(HttpStatus.FORBIDDEN).build();
|
||||
return procurement
|
||||
.signedAgreementPdf(teamId)
|
||||
.<ResponseEntity<byte[]>>map(
|
||||
pdf ->
|
||||
ResponseEntity.ok()
|
||||
.header(
|
||||
HttpHeaders.CONTENT_DISPOSITION,
|
||||
"attachment;"
|
||||
+ " filename=\"stirling-enterprise-agreement.pdf\"")
|
||||
.contentType(MediaType.APPLICATION_PDF)
|
||||
.body(pdf))
|
||||
.orElseGet(() -> ResponseEntity.notFound().build());
|
||||
}
|
||||
|
||||
/**
|
||||
* Download the current (unsigned) agreement as a PDF — the document shown at the sign step. 404
|
||||
* when there's no quote yet or the render runtime is unavailable.
|
||||
*/
|
||||
@GetMapping("/agreement/document/pdf")
|
||||
@PreAuthorize("isAuthenticated()")
|
||||
public ResponseEntity<byte[]> agreementDocumentPdf(Authentication auth) {
|
||||
Long teamId = requireLeader(auth);
|
||||
if (teamId == null) return ResponseEntity.status(HttpStatus.FORBIDDEN).build();
|
||||
return procurement
|
||||
.agreementDocumentPdf(teamId)
|
||||
.<ResponseEntity<byte[]>>map(
|
||||
pdf ->
|
||||
ResponseEntity.ok()
|
||||
.header(
|
||||
HttpHeaders.CONTENT_DISPOSITION,
|
||||
"attachment;"
|
||||
+ " filename=\"stirling-enterprise-agreement.pdf\"")
|
||||
.contentType(MediaType.APPLICATION_PDF)
|
||||
.body(pdf))
|
||||
.orElseGet(() -> ResponseEntity.notFound().build());
|
||||
}
|
||||
|
||||
/**
|
||||
* Provision on accept: upgrade the team's licence to the committed annual term, valid
|
||||
* immediately. Called server-side by the accept edge function (ROLE_ADMIN via X-API-Key) once
|
||||
@@ -311,9 +496,38 @@ public class ProcurementController {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Go live once payment settles: advance the deal to active and re-affirm the annual licence.
|
||||
* Called server-side by the {@code invoice.paid} webhook (ROLE_ADMIN via X-API-Key), alongside
|
||||
* {@code /provision}, which runs earlier at accept and deliberately leaves the stage alone.
|
||||
*
|
||||
* <p>Answers 200 when the team has no deal at all, rather than erroring: a committed
|
||||
* subscription can be closed directly in Stripe by sales with no portal deal behind it, and a
|
||||
* non-2xx would have Stripe retry a webhook that can never succeed.
|
||||
*
|
||||
* <p>{@code invoiceId} is what makes this idempotent without swallowing renewals: the same
|
||||
* invoice twice is a redelivery, a different one is next year's payment and has to re-issue the
|
||||
* licence. Optional so an older caller still works, at the cost of that distinction.
|
||||
*/
|
||||
@PostMapping("/activate")
|
||||
@PreAuthorize("hasRole('ADMIN')")
|
||||
public ResponseEntity<Void> activate(
|
||||
@RequestParam("teamId") long teamId,
|
||||
@RequestParam(value = "invoiceId", required = false) String invoiceId) {
|
||||
try {
|
||||
procurement.markLive(teamId, invoiceId);
|
||||
} catch (IllegalStateException e) {
|
||||
log.info(
|
||||
"[procurement] activate skipped, no deal for team={}: {}",
|
||||
teamId,
|
||||
e.getMessage());
|
||||
}
|
||||
return ResponseEntity.ok().build();
|
||||
}
|
||||
|
||||
/**
|
||||
* Demo/manual stand-in for the {@code invoice.paid} webhook: mark the deal live (issue the
|
||||
* annual licence, advance to active). The real go-live is webhook-driven once payment settles.
|
||||
* annual licence, advance to active). Production go-live runs through {@code /activate}.
|
||||
*/
|
||||
@PostMapping("/go-live")
|
||||
@PreAuthorize("isAuthenticated()")
|
||||
@@ -360,6 +574,21 @@ public class ProcurementController {
|
||||
.orElse(null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Best-effort client IP for the signature record: first X-Forwarded-For hop, else the peer.
|
||||
*
|
||||
* <p>Informational only. That header is client-set, so {@code signer_ip} is spoofable and is
|
||||
* not evidence of where a signature came from — the document hash and version are what make the
|
||||
* record trustworthy. Treat the address as a hint, never as proof.
|
||||
*/
|
||||
private static String clientIp(HttpServletRequest request) {
|
||||
String forwarded = request.getHeader("X-Forwarded-For");
|
||||
if (forwarded != null && !forwarded.isBlank()) {
|
||||
return forwarded.split(",")[0].trim();
|
||||
}
|
||||
return request.getRemoteAddr();
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the snapshot for a deal. {@code includeLicenseKey} is true only for the team leader; a
|
||||
* member sees {@code licensed} but not the key itself (see {@link #snapshot}). Mutation
|
||||
@@ -381,6 +610,10 @@ public class ProcurementController {
|
||||
deal.getTrialExtensionsUsed(),
|
||||
deal.getLicenseRef() != null,
|
||||
includeLicenseKey ? deal.getLicenseRef() : null,
|
||||
procurement.signedAgreementLabel(deal.getDealId()).orElse(null),
|
||||
deal.getBusinessName(),
|
||||
deal.getContactName(),
|
||||
deal.getContactEmail(),
|
||||
latest);
|
||||
}
|
||||
|
||||
|
||||
+13
@@ -30,4 +30,17 @@ public class ProcurementConfigurationProperties {
|
||||
* /go-live is a stand-in for the invoice.paid webhook and would let a leader activate unpaid.
|
||||
*/
|
||||
private boolean demoControlsEnabled = false;
|
||||
|
||||
/**
|
||||
* Smallest annual fee, in minor units, that may be quoted. The pricing curve has no natural
|
||||
* floor — a small enough committed volume rounds the meter to zero — and every registered user
|
||||
* is the leader of their own team, so without this any signup could price a $0 enterprise
|
||||
* quote, accept it, and be provisioned a committed licence. 12_000_00 is USD 12,000/yr, the
|
||||
* self-hosted deploy fee, chosen so the floor cannot sit below a line item the quote itself can
|
||||
* contain.
|
||||
*
|
||||
* <p>This is a commercial number, not a technical one: set it to whatever the smallest
|
||||
* enterprise deal you will actually sign is. Zero disables the check.
|
||||
*/
|
||||
private long minAnnualNetMinor = 12_000_00L;
|
||||
}
|
||||
|
||||
+278
@@ -0,0 +1,278 @@
|
||||
package stirling.software.saas.procurement.legal;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
|
||||
import stirling.software.saas.legal.LegalDocumentMeta;
|
||||
import stirling.software.saas.legal.LegalDocumentRegistry;
|
||||
import stirling.software.saas.procurement.model.ProcurementQuote;
|
||||
import stirling.software.saas.procurement.pricing.ProcurementPricingService;
|
||||
import stirling.software.saas.procurement.pricing.QuoteConfig;
|
||||
import stirling.software.saas.procurement.pricing.QuoteLineItem;
|
||||
|
||||
/**
|
||||
* Builds the full Stirling Enterprise Agreement for a specific quote: the static MSA (Part A) and
|
||||
* DPA (Part C) from the {@link LegalDocumentRegistry}, with the dynamic Order Form (Part B)
|
||||
* generated from the quote and slotted where the manifest's {@code @order-form} part sits.
|
||||
*
|
||||
* <p>Only the Order Form varies per deal; the MSA and DPA bodies are rendered verbatim with token
|
||||
* substitution. The set of values used is returned as {@code variablesJson} so a signature can pin
|
||||
* exactly what was rendered.
|
||||
*/
|
||||
@Slf4j
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class AgreementAssembler {
|
||||
|
||||
public static final String DOC_ID = "enterprise-agreement";
|
||||
|
||||
private static final DateTimeFormatter DATE =
|
||||
DateTimeFormatter.ofPattern("MMMM d, yyyy", Locale.US);
|
||||
private static final String BLANK = "\\_\\_\\_\\_\\_\\_\\_\\_\\_\\_";
|
||||
|
||||
private final LegalDocumentRegistry registry;
|
||||
private final ProcurementPricingService pricing;
|
||||
private final ObjectMapper objectMapper = new ObjectMapper();
|
||||
|
||||
/**
|
||||
* Render the agreement for a quote. {@code signing} is null for a preview (before signing) —
|
||||
* the effective date and signature block then read as blanks / "On signature".
|
||||
*/
|
||||
public AssembledAgreement assemble(ProcurementQuote quote, AgreementSigning signing) {
|
||||
LegalDocumentMeta meta =
|
||||
registry.meta(DOC_ID)
|
||||
.orElseThrow(
|
||||
() ->
|
||||
new IllegalStateException(
|
||||
"Enterprise agreement not registered"));
|
||||
|
||||
Map<String, String> tokens = tokens(quote, signing, meta);
|
||||
|
||||
StringBuilder md = new StringBuilder();
|
||||
for (String part : meta.parts()) {
|
||||
if (md.length() > 0) md.append("\n\n");
|
||||
if ("@order-form".equals(part)) {
|
||||
md.append(LegalDocumentRegistry.fill(orderForm(quote, tokens), tokens));
|
||||
} else {
|
||||
md.append(LegalDocumentRegistry.fill(registry.readPart(meta, part), tokens));
|
||||
}
|
||||
}
|
||||
|
||||
String variablesJson;
|
||||
try {
|
||||
variablesJson = objectMapper.writeValueAsString(tokens);
|
||||
} catch (Exception e) {
|
||||
variablesJson = "{}";
|
||||
}
|
||||
|
||||
return new AssembledAgreement(
|
||||
meta.id(),
|
||||
meta.version(),
|
||||
meta.versionLabel(),
|
||||
meta.displayName(),
|
||||
meta.effectiveDate(),
|
||||
meta.status(),
|
||||
md.toString(),
|
||||
variablesJson);
|
||||
}
|
||||
|
||||
private Map<String, String> tokens(
|
||||
ProcurementQuote quote, AgreementSigning signing, LegalDocumentMeta meta) {
|
||||
QuoteConfig cfg = toConfig(quote);
|
||||
boolean signed = signing != null;
|
||||
|
||||
String legalName =
|
||||
signed && notBlank(signing.customerLegalName())
|
||||
? signing.customerLegalName().trim()
|
||||
: (notBlank(quote.getBusinessName())
|
||||
? quote.getBusinessName().trim()
|
||||
: "Customer");
|
||||
|
||||
Map<String, String> t = new LinkedHashMap<>(registry.commonTokens(meta));
|
||||
t.put("effective_date", signed ? LocalDate.now().format(DATE) : "On signature");
|
||||
t.put("customer_legal_name", cell(legalName));
|
||||
t.put("quote_ref", nz(quote.getQuoteNumber()));
|
||||
t.put("deployment", ProcurementPricingService.deploymentName(quote.getDeployment()));
|
||||
t.put("committed_pdfs_yr", String.format(Locale.US, "%,d", Math.max(0, quote.getVolume())));
|
||||
t.put("posture", ProcurementPricingService.postureName(quote.getIntensity()));
|
||||
t.put("processes_per_pdf", String.valueOf(Math.max(1, quote.getIntensity())));
|
||||
t.put("rate_per_pdf", String.format(Locale.US, "$%.4f", pricing.effectiveRatePerPdf(cfg)));
|
||||
t.put("term_years", String.valueOf(quote.getTermYears()));
|
||||
t.put("term_discount_pct", pricing.termDiscountPct(quote.getTermYears()) + "%");
|
||||
t.put("sla_tier", slaTier(quote.getServiceLevel()));
|
||||
t.put("annual_fee_y1", money(quote.getAnnualNetMinor()));
|
||||
t.put("contract_total", money(quote.getTcvMinor()));
|
||||
t.put("elected_or_not", quote.isIndemnification() ? "Elected" : "Not elected");
|
||||
t.put("po_number", notBlank(quote.getPoNumber()) ? cell(quote.getPoNumber()) : "—");
|
||||
t.put(
|
||||
"customer_signatory",
|
||||
signed && notBlank(signing.signatoryName())
|
||||
? cell(signing.signatoryName())
|
||||
: BLANK);
|
||||
t.put(
|
||||
"customer_signatory_title",
|
||||
signed && notBlank(signing.signatoryTitle())
|
||||
? cell(signing.signatoryTitle())
|
||||
: BLANK);
|
||||
return t;
|
||||
}
|
||||
|
||||
/**
|
||||
* Make a buyer-supplied value safe to slot into a markdown table cell.
|
||||
*
|
||||
* <p>An unescaped {@code |} or newline splits the cell and breaks the Order Form's table. That
|
||||
* matters beyond appearance: this markdown is what gets hashed into the signature record, so a
|
||||
* value that restructures the table means the SHA-256 we keep as proof covers a document
|
||||
* reading differently from the one the signatory saw.
|
||||
*/
|
||||
private static String cell(String raw) {
|
||||
return raw.trim().replace("|", "\\|").replaceAll("\\s*\\R+\\s*", " ");
|
||||
}
|
||||
|
||||
/** Part B — the Order Form. Generated from the quote; the only per-deal section. */
|
||||
private String orderForm(ProcurementQuote quote, Map<String, String> t) {
|
||||
String date = t.get("effective_date");
|
||||
String signatory = t.get("customer_signatory");
|
||||
String signatoryTitle = t.get("customer_signatory_title");
|
||||
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.append("## Part B — Order Form · {{quote_ref}}\n\n");
|
||||
sb.append("| Term | Value |\n| --- | --- |\n");
|
||||
row(sb, "Customer", "{{customer_legal_name}}");
|
||||
row(sb, "Subscription", "Enterprise · {{deployment}}");
|
||||
row(sb, "Purchase order", "{{po_number}}");
|
||||
row(sb, "Committed Volume", "{{committed_pdfs_yr}} PDFs / year at the {{posture}} posture");
|
||||
row(sb, "Committed rate", "{{rate_per_pdf}} per PDF");
|
||||
row(sb, "Service level", "{{sla_tier}} (per SLA Exhibit)");
|
||||
row(
|
||||
sb,
|
||||
"Term",
|
||||
"{{term_years}} year(s) · term discount {{term_discount_pct}} on committed processing");
|
||||
row(sb, "Itemized services", itemizedServices(quote));
|
||||
row(sb, "Annual Fee (year 1)", "{{annual_fee_y1}}");
|
||||
row(sb, "Total (paid in advance)", "{{contract_total}}");
|
||||
row(sb, "Escalator", "+3% at each anniversary during the Term");
|
||||
row(
|
||||
sb,
|
||||
"Payment",
|
||||
"Full {{term_years}}-year term invoiced in advance on acceptance · net 30 · ACH,"
|
||||
+ " wire, or check");
|
||||
row(sb, "Overage", "Committed rate, billed quarterly in arrears");
|
||||
row(
|
||||
sb,
|
||||
"Data schedule",
|
||||
"First 25 MB per file included; each additional 25 MB or part thereof (decimal MB,"
|
||||
+ " rounded up per file, measured once at ingestion) draws down 1 PDF Process."
|
||||
+ " Frozen for the Term (MSA §3.5).");
|
||||
row(
|
||||
sb,
|
||||
"Drawdown schedule",
|
||||
"{{posture}}: {{processes_per_pdf}} PDF Processes per PDF (MSA §3.3, frozen for the Term)");
|
||||
row(
|
||||
sb,
|
||||
"Enhanced IP Protection",
|
||||
"{{elected_or_not}} — extends §7.3 to patent claims at the §8.2 super-cap");
|
||||
row(sb, "Standard terms", "SSO, SCIM, RBAC, and audit logs included.");
|
||||
|
||||
sb.append(
|
||||
"\n**Itemized services menu (include as elected):** Self-hosted deployment $12,000/yr"
|
||||
+ " · Air-gapped deployment $36,000/yr · Dedicated SE/CSM $30,000/yr · Enhanced IP"
|
||||
+ " Protection (patent coverage, Section 7.3) 5% of committed processing fees ·"
|
||||
+ " Onboarding & training $7,500 one-time · Quarterly business reviews $8,000/yr."
|
||||
+ " Baseline IP indemnification (copyright, trademark, trade secret) is included at"
|
||||
+ " no charge.\n\n");
|
||||
sb.append(
|
||||
"**Signatures.** By signing, each signatory represents they have authority to bind"
|
||||
+ " their Party. Signatures delivered electronically or in counterparts are"
|
||||
+ " effective as originals.\n\n");
|
||||
sb.append("| Provider | Customer |\n| --- | --- |\n");
|
||||
sb.append("| Stirling PDF, Inc. | {{customer_legal_name}} |\n");
|
||||
sb.append("| Name: Matt Joseph | Name: ").append(signatory).append(" |\n");
|
||||
sb.append("| Title: CEO | Title: ").append(signatoryTitle).append(" |\n");
|
||||
sb.append("| Date: ").append(date).append(" | Date: ").append(date).append(" |\n");
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* The elected add-on lines, taken from the quote's stored breakdown (excludes the base meter).
|
||||
*/
|
||||
private String itemizedServices(ProcurementQuote quote) {
|
||||
List<QuoteLineItem> lines = parseLineItems(quote.getLineItemsJson());
|
||||
List<String> elected = new ArrayList<>();
|
||||
for (QuoteLineItem li : lines) {
|
||||
if (li.key().equals("usage")
|
||||
|| li.key().equals("seats")
|
||||
|| li.key().equals("multi-year")) {
|
||||
continue;
|
||||
}
|
||||
String suffix = li.kind() == QuoteLineItem.Kind.ONE_TIME ? " (one-time)" : "/yr";
|
||||
elected.add(li.label() + " " + money(li.amountMinor()) + suffix);
|
||||
}
|
||||
return elected.isEmpty() ? "None elected" : String.join(" · ", elected);
|
||||
}
|
||||
|
||||
private List<QuoteLineItem> parseLineItems(String json) {
|
||||
if (json == null || json.isBlank()) return List.of();
|
||||
try {
|
||||
return objectMapper.readValue(
|
||||
json,
|
||||
objectMapper
|
||||
.getTypeFactory()
|
||||
.constructCollectionType(List.class, QuoteLineItem.class));
|
||||
} catch (Exception e) {
|
||||
log.warn("[legal] could not parse quote line items for the order form", e);
|
||||
return List.of();
|
||||
}
|
||||
}
|
||||
|
||||
private static QuoteConfig toConfig(ProcurementQuote q) {
|
||||
int users = q.getSeats() == null ? 0 : q.getSeats();
|
||||
return new QuoteConfig(
|
||||
q.getVolume(),
|
||||
users,
|
||||
q.getIntensity(),
|
||||
q.getSizeMult(),
|
||||
q.getDeployment(),
|
||||
q.getTermYears(),
|
||||
q.getServiceLevel(),
|
||||
q.isIndemnification(),
|
||||
q.isTraining(),
|
||||
q.isQbr(),
|
||||
q.getCurrency());
|
||||
}
|
||||
|
||||
private static void row(StringBuilder sb, String term, String value) {
|
||||
sb.append("| ").append(term).append(" | ").append(value).append(" |\n");
|
||||
}
|
||||
|
||||
private static String slaTier(String serviceLevel) {
|
||||
if ("dedicated".equalsIgnoreCase(serviceLevel)) return "Dedicated";
|
||||
if ("priority".equalsIgnoreCase(serviceLevel)) return "Priority";
|
||||
return "Standard";
|
||||
}
|
||||
|
||||
/** Minor units (cents) → whole-dollar display; the quote figures are whole dollars. */
|
||||
private static String money(long minor) {
|
||||
return String.format(Locale.US, "$%,d", minor / 100L);
|
||||
}
|
||||
|
||||
private static boolean notBlank(String s) {
|
||||
return s != null && !s.isBlank();
|
||||
}
|
||||
|
||||
private static String nz(String s) {
|
||||
return s == null ? "" : s;
|
||||
}
|
||||
}
|
||||
+71
@@ -0,0 +1,71 @@
|
||||
package stirling.software.saas.procurement.legal;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.List;
|
||||
|
||||
import org.commonmark.Extension;
|
||||
import org.commonmark.ext.gfm.tables.TablesExtension;
|
||||
import org.commonmark.node.Node;
|
||||
import org.commonmark.parser.Parser;
|
||||
import org.commonmark.renderer.html.HtmlRenderer;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
|
||||
import stirling.software.common.configuration.RuntimePathConfig;
|
||||
import stirling.software.common.service.CustomPDFDocumentFactory;
|
||||
import stirling.software.common.util.CustomHtmlSanitizer;
|
||||
import stirling.software.common.util.FileToPdf;
|
||||
import stirling.software.common.util.TempFileManager;
|
||||
|
||||
/**
|
||||
* Renders an assembled agreement's markdown to a PDF, dogfooding Stirling's own conversion path:
|
||||
* commonmark (markdown → HTML) then {@link FileToPdf#convertHtmlToPdf} (HTML → PDF via WeasyPrint),
|
||||
* the same pipeline as the product's Markdown-to-PDF tool.
|
||||
*
|
||||
* <p>The signed PDF is a stored artifact, but it must never block signing: {@link #tryRender}
|
||||
* returns {@code null} if the conversion runtime (WeasyPrint) is unavailable, so the signature is
|
||||
* still recorded and the buyer keeps the on-the-fly download.
|
||||
*/
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class AgreementPdfRenderer {
|
||||
|
||||
private final RuntimePathConfig runtimePathConfig;
|
||||
private final TempFileManager tempFileManager;
|
||||
private final CustomHtmlSanitizer customHtmlSanitizer;
|
||||
private final CustomPDFDocumentFactory pdfDocumentFactory;
|
||||
|
||||
private static final List<Extension> EXTENSIONS = List.of(TablesExtension.create());
|
||||
|
||||
/** Render to PDF, or return null if the conversion runtime isn't available. */
|
||||
public byte[] tryRender(String markdown) {
|
||||
try {
|
||||
return render(markdown);
|
||||
} catch (Exception e) {
|
||||
org.slf4j.LoggerFactory.getLogger(AgreementPdfRenderer.class)
|
||||
.warn(
|
||||
"[legal] agreement PDF render unavailable; recording signature without a"
|
||||
+ " stored PDF: {}",
|
||||
e.getMessage());
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private byte[] render(String markdown) throws Exception {
|
||||
Parser parser = Parser.builder().extensions(EXTENSIONS).build();
|
||||
Node document = parser.parse(markdown);
|
||||
HtmlRenderer renderer = HtmlRenderer.builder().extensions(EXTENSIONS).build();
|
||||
String html = renderer.render(document);
|
||||
|
||||
byte[] pdfBytes =
|
||||
FileToPdf.convertHtmlToPdf(
|
||||
runtimePathConfig.getWeasyPrintPath(),
|
||||
null,
|
||||
html.getBytes(StandardCharsets.UTF_8),
|
||||
"agreement.html",
|
||||
tempFileManager,
|
||||
customHtmlSanitizer);
|
||||
return pdfDocumentFactory.createNewBytesBasedOnOldDocument(pdfBytes);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package stirling.software.saas.procurement.legal;
|
||||
|
||||
/**
|
||||
* The buyer-supplied inputs captured at the moment of signing the enterprise agreement: the legal
|
||||
* entity name, the signatory's typed name and title, and their representation of authority to bind.
|
||||
* Null when the agreement is rendered for preview (before signing).
|
||||
*/
|
||||
public record AgreementSigning(
|
||||
String customerLegalName,
|
||||
String signatoryName,
|
||||
String signatoryTitle,
|
||||
boolean authorityConfirmed) {}
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
package stirling.software.saas.procurement.legal;
|
||||
|
||||
/**
|
||||
* A rendered enterprise agreement: the full markdown the buyer sees (MSA + Order Form + DPA, tokens
|
||||
* filled), plus the registry metadata that pins it. {@code variablesJson} is the exact set of
|
||||
* Order-Form values as rendered, stored alongside a signature so the document is reproducible.
|
||||
*/
|
||||
public record AssembledAgreement(
|
||||
String docId,
|
||||
String version,
|
||||
String versionLabel,
|
||||
String displayName,
|
||||
String effectiveDate,
|
||||
String status,
|
||||
String markdown,
|
||||
String variablesJson) {}
|
||||
+86
@@ -0,0 +1,86 @@
|
||||
package stirling.software.saas.procurement.model;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
import org.hibernate.annotations.CreationTimestamp;
|
||||
|
||||
import jakarta.persistence.Column;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.GeneratedValue;
|
||||
import jakarta.persistence.GenerationType;
|
||||
import jakarta.persistence.Id;
|
||||
import jakarta.persistence.Table;
|
||||
|
||||
import lombok.Getter;
|
||||
import lombok.NoArgsConstructor;
|
||||
import lombok.Setter;
|
||||
|
||||
/**
|
||||
* An immutable record of a signed enterprise agreement. Each signature pins the exact legal
|
||||
* document it was signed against — {@code documentId} + {@code documentVersion} + a SHA-256 {@code
|
||||
* contentHash} of the rendered markdown — plus the Order-Form variable snapshot and the typed
|
||||
* signatory details, so the agreement stays reproducible even after the templates version up. The
|
||||
* rendered PDF is stored when the conversion runtime is available.
|
||||
*/
|
||||
@Entity
|
||||
@Table(name = "procurement_agreement_signature")
|
||||
@NoArgsConstructor
|
||||
@Getter
|
||||
@Setter
|
||||
public class ProcurementAgreementSignature implements Serializable {
|
||||
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
@Column(name = "signature_id")
|
||||
private Long signatureId;
|
||||
|
||||
@Column(name = "deal_id", nullable = false)
|
||||
private Long dealId;
|
||||
|
||||
@Column(name = "quote_id", nullable = false)
|
||||
private Long quoteId;
|
||||
|
||||
// Which legal document, and which version of it, was signed.
|
||||
@Column(name = "document_id", nullable = false, length = 64)
|
||||
private String documentId;
|
||||
|
||||
@Column(name = "document_version", nullable = false, length = 32)
|
||||
private String documentVersion;
|
||||
|
||||
@Column(name = "document_label", length = 64)
|
||||
private String documentLabel;
|
||||
|
||||
// SHA-256 (hex) of the exact rendered agreement markdown the buyer accepted.
|
||||
@Column(name = "content_hash", nullable = false, length = 64)
|
||||
private String contentHash;
|
||||
|
||||
// The Order-Form variable values as rendered, so the document can be reproduced.
|
||||
@Column(name = "variables_json", columnDefinition = "text")
|
||||
private String variablesJson;
|
||||
|
||||
@Column(name = "customer_legal_name", length = 255)
|
||||
private String customerLegalName;
|
||||
|
||||
@Column(name = "signatory_name", nullable = false, length = 255)
|
||||
private String signatoryName;
|
||||
|
||||
@Column(name = "signatory_title", length = 255)
|
||||
private String signatoryTitle;
|
||||
|
||||
@Column(name = "authority_confirmed", nullable = false)
|
||||
private boolean authorityConfirmed;
|
||||
|
||||
@Column(name = "signer_ip", length = 64)
|
||||
private String signerIp;
|
||||
|
||||
// The rendered PDF artifact; null when the conversion runtime was unavailable at signing.
|
||||
@Column(name = "pdf")
|
||||
private byte[] pdf;
|
||||
|
||||
@CreationTimestamp
|
||||
@Column(name = "signed_at", nullable = false, updatable = false)
|
||||
private LocalDateTime signedAt;
|
||||
}
|
||||
@@ -34,6 +34,13 @@ public class ProcurementDeal implements Serializable {
|
||||
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
/**
|
||||
* Interest, before any commitment: the account asked about enterprise but has not started a
|
||||
* trial. Kept as a real stage so intent survives a refresh, so the enterprise surface is only
|
||||
* shown to accounts that asked for it, and so drop-off at the cheapest step is measurable.
|
||||
*/
|
||||
public static final String STAGE_EXPLORING = "exploring";
|
||||
|
||||
public static final String STAGE_TRIAL = "trial";
|
||||
public static final String STAGE_QUOTE = "quote";
|
||||
public static final String STAGE_AGREEMENT = "security";
|
||||
@@ -69,12 +76,38 @@ public class ProcurementDeal implements Serializable {
|
||||
@Column(name = "trial_extensions_used", nullable = false)
|
||||
private int trialExtensionsUsed;
|
||||
|
||||
// Captured at trial setup, so the buying entity is known before any quote exists — the quote's
|
||||
// own copies seed from these and may then diverge (a deal can change hands mid-cycle).
|
||||
// Nullable: trials started before this step, and older clients, supply none.
|
||||
@Column(name = "business_name", length = 255)
|
||||
private String businessName;
|
||||
|
||||
@Column(name = "contact_name", length = 255)
|
||||
private String contactName;
|
||||
|
||||
@Column(name = "contact_email", length = 320)
|
||||
private String contactEmail;
|
||||
|
||||
// Addresses the buyer named at setup. Kept as the record of what was asked for; the invitations
|
||||
// themselves go out through the team-invite path when the trial starts.
|
||||
@Column(name = "invite_emails", length = 2000)
|
||||
private String inviteEmails;
|
||||
|
||||
@Column(name = "license_ref", length = 128)
|
||||
private String licenseRef;
|
||||
|
||||
@Column(name = "subscription_id", length = 255)
|
||||
private String subscriptionId;
|
||||
|
||||
/**
|
||||
* The last Stripe invoice whose payment was applied to this deal. Distinguishes a redelivered
|
||||
* {@code invoice.paid} for a payment already handled from a genuine renewal, which has to
|
||||
* re-issue: the committed licence expires term years from issue, so a renewal that doesn't
|
||||
* re-issue leaves the licence lapsing after the customer has paid.
|
||||
*/
|
||||
@Column(name = "last_paid_invoice_id", length = 255)
|
||||
private String lastPaidInvoiceId;
|
||||
|
||||
@Column(name = "accepted_quote_id")
|
||||
private Long acceptedQuoteId;
|
||||
|
||||
|
||||
+5
-1
@@ -47,7 +47,11 @@ public class ProcurementQuote implements Serializable {
|
||||
@Column(name = "deal_id", nullable = false)
|
||||
private Long dealId;
|
||||
|
||||
@Column(name = "quote_number", nullable = false, length = 64)
|
||||
/**
|
||||
* Stripe's quote number, the deal's one buyer-facing reference. Null until the quote is issued:
|
||||
* Stripe assigns it at finalisation, and the issue edge function writes it back then.
|
||||
*/
|
||||
@Column(name = "quote_number", length = 64)
|
||||
private String quoteNumber;
|
||||
|
||||
@Column(name = "status", nullable = false, length = 24)
|
||||
|
||||
+43
-6
@@ -60,12 +60,7 @@ public class ProcurementPricingService {
|
||||
rates.discountPerDoubling()
|
||||
* (Math.log(runVol / (double) RUN_CURVE_KNEE) / LOG2))
|
||||
: 0.0;
|
||||
double rate = Math.max(rates.floorRatePerRun(), rates.listRatePerRun() * (1.0 - volDisc));
|
||||
// File-size multiplier (D93): larger, image-heavy PDFs cost more OCR/compute/storage. Folds
|
||||
// into the per-run rate after the floor, so it flows through the meter, TCV and renewal.
|
||||
// QuoteConfig has already snapped it to a known tier, so a tampered request can't sneak a
|
||||
// cheaper factor in.
|
||||
rate *= cfg.sizeMult();
|
||||
double rate = perRunRate(cfg, rates);
|
||||
double termDisc = rates.termDiscount(cfg.termYears());
|
||||
|
||||
// The meter is a whole-dollar figure (the quote reads in dollars), then minor units.
|
||||
@@ -160,6 +155,48 @@ public class ProcurementPricingService {
|
||||
return new QuoteBreakdown(lines, annualNet, tcv, renewalAnnual, cfg.currency());
|
||||
}
|
||||
|
||||
/**
|
||||
* The per-run rate after the committed-volume curve, the half-cent floor, and the file-size
|
||||
* multiplier — the same value {@link #price} meters against. Extracted so read-only callers
|
||||
* (the Order Form) can quote it without re-deriving the curve.
|
||||
*/
|
||||
private static double perRunRate(QuoteConfig cfg, PricingRates rates) {
|
||||
long runVol = Math.max(0, cfg.volume()) * (long) Math.max(1, cfg.intensity());
|
||||
double volDisc =
|
||||
runVol > RUN_CURVE_KNEE
|
||||
? Math.min(
|
||||
0.5,
|
||||
rates.discountPerDoubling()
|
||||
* (Math.log(runVol / (double) RUN_CURVE_KNEE) / LOG2))
|
||||
: 0.0;
|
||||
return Math.max(rates.floorRatePerRun(), rates.listRatePerRun() * (1.0 - volDisc))
|
||||
* cfg.sizeMult();
|
||||
}
|
||||
|
||||
/**
|
||||
* The effective per-PDF rate at the chosen posture, in dollars (4-decimal quote figure). This
|
||||
* is what the Order Form and quote copy speak in — never the per-run rate. Read-only; does not
|
||||
* affect billing.
|
||||
*/
|
||||
public double effectiveRatePerPdf(QuoteConfig cfg) {
|
||||
return perRunRate(cfg, PricingRates.defaults()) * Math.max(1, cfg.intensity());
|
||||
}
|
||||
|
||||
/** The multi-year term discount as a whole-percent figure for the Order Form (0.05 → 5). */
|
||||
public int termDiscountPct(int termYears) {
|
||||
return (int) Math.round(PricingRates.defaults().termDiscount(termYears) * 100.0);
|
||||
}
|
||||
|
||||
/** Buyer-facing posture name (Essentials / Governed / Regulated) for the given intensity. */
|
||||
public static String postureName(int intensity) {
|
||||
return postureLabel(intensity);
|
||||
}
|
||||
|
||||
/** Buyer-facing deployment name (Stirling Cloud / Self-hosted / Air-gapped). */
|
||||
public static String deploymentName(String deployment) {
|
||||
return deploymentLabel(deployment);
|
||||
}
|
||||
|
||||
/** The default CPI escalator (fraction) applied to the annual fee on each post-term renewal. */
|
||||
public double cpiEscalator() {
|
||||
return PricingRates.defaults().cpiEscalator();
|
||||
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
package stirling.software.saas.procurement.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 stirling.software.saas.procurement.model.ProcurementAgreementSignature;
|
||||
|
||||
public interface ProcurementAgreementSignatureRepository
|
||||
extends JpaRepository<ProcurementAgreementSignature, Long> {
|
||||
|
||||
Optional<ProcurementAgreementSignature> findFirstByDealIdOrderBySignedAtDesc(Long dealId);
|
||||
|
||||
Optional<ProcurementAgreementSignature> findFirstByQuoteIdOrderBySignedAtDesc(Long quoteId);
|
||||
|
||||
/**
|
||||
* Version labels of a deal's signatures, newest first. Projects just the label column so the
|
||||
* frequently-polled snapshot never loads the PDF bytes. A signature means the agreement is
|
||||
* signed; the PDF is resolved (stored or re-rendered) at download time.
|
||||
*/
|
||||
@Query(
|
||||
"SELECT s.documentLabel FROM ProcurementAgreementSignature s"
|
||||
+ " WHERE s.dealId = :dealId"
|
||||
+ " ORDER BY s.signedAt DESC")
|
||||
List<String> findSignedLabels(@Param("dealId") Long dealId);
|
||||
}
|
||||
+371
-19
@@ -5,7 +5,6 @@ import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
|
||||
import org.springframework.context.annotation.Profile;
|
||||
import org.springframework.stereotype.Service;
|
||||
@@ -20,16 +19,24 @@ import stirling.software.common.model.enumeration.TeamRole;
|
||||
import stirling.software.proprietary.model.TeamMembership;
|
||||
import stirling.software.proprietary.security.repository.TeamMembershipRepository;
|
||||
import stirling.software.saas.procurement.config.ProcurementConfigurationProperties;
|
||||
import stirling.software.saas.procurement.legal.AgreementAssembler;
|
||||
import stirling.software.saas.procurement.legal.AgreementPdfRenderer;
|
||||
import stirling.software.saas.procurement.legal.AgreementSigning;
|
||||
import stirling.software.saas.procurement.legal.AssembledAgreement;
|
||||
import stirling.software.saas.procurement.license.EnterpriseLicenseService;
|
||||
import stirling.software.saas.procurement.license.LicenseEntitlements;
|
||||
import stirling.software.saas.procurement.model.ProcurementAgreementSignature;
|
||||
import stirling.software.saas.procurement.model.ProcurementDeal;
|
||||
import stirling.software.saas.procurement.model.ProcurementQuote;
|
||||
import stirling.software.saas.procurement.model.QuoteDetails;
|
||||
import stirling.software.saas.procurement.pricing.ProcurementPricingService;
|
||||
import stirling.software.saas.procurement.pricing.QuoteBreakdown;
|
||||
import stirling.software.saas.procurement.pricing.QuoteConfig;
|
||||
import stirling.software.saas.procurement.repository.ProcurementAgreementSignatureRepository;
|
||||
import stirling.software.saas.procurement.repository.ProcurementDealRepository;
|
||||
import stirling.software.saas.procurement.repository.ProcurementQuoteRepository;
|
||||
import stirling.software.saas.service.SaasTeamService;
|
||||
import stirling.software.saas.util.LogRedactionUtils;
|
||||
|
||||
/**
|
||||
* Orchestrates a linked team's procurement journey: start a (mock-licensed) trial, build a
|
||||
@@ -52,6 +59,12 @@ public class ProcurementService {
|
||||
private final EnterpriseLicenseService licenses;
|
||||
private final ProcurementConfigurationProperties config;
|
||||
private final TeamMembershipRepository memberRepo;
|
||||
private final AgreementAssembler agreementAssembler;
|
||||
private final AgreementPdfRenderer agreementPdfRenderer;
|
||||
private final ProcurementAgreementSignatureRepository signatureRepo;
|
||||
// Trial-setup invitations run through the team-invite path, with its seat, role and
|
||||
// rate-limit rules rather than a second implementation here.
|
||||
private final SaasTeamService teams;
|
||||
|
||||
public ProcurementService(
|
||||
ProcurementDealRepository dealRepo,
|
||||
@@ -59,13 +72,21 @@ public class ProcurementService {
|
||||
ProcurementPricingService pricing,
|
||||
EnterpriseLicenseService licenses,
|
||||
ProcurementConfigurationProperties config,
|
||||
TeamMembershipRepository memberRepo) {
|
||||
TeamMembershipRepository memberRepo,
|
||||
AgreementAssembler agreementAssembler,
|
||||
AgreementPdfRenderer agreementPdfRenderer,
|
||||
ProcurementAgreementSignatureRepository signatureRepo,
|
||||
SaasTeamService teams) {
|
||||
this.dealRepo = dealRepo;
|
||||
this.quoteRepo = quoteRepo;
|
||||
this.pricing = pricing;
|
||||
this.licenses = licenses;
|
||||
this.config = config;
|
||||
this.memberRepo = memberRepo;
|
||||
this.agreementAssembler = agreementAssembler;
|
||||
this.agreementPdfRenderer = agreementPdfRenderer;
|
||||
this.signatureRepo = signatureRepo;
|
||||
this.teams = teams;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -89,11 +110,45 @@ public class ProcurementService {
|
||||
return dealRepo.findByTeamId(teamId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Starting a trial is only legitimate before one exists, while the buyer is still exploring, or
|
||||
* to restart within the trial itself. A null stage is a deal that has just been constructed.
|
||||
*
|
||||
* <p>Package-private so the policy can be tested without the service's ten dependencies. Adding
|
||||
* a later stage here would let a leader replace a paying customer's committed licence.
|
||||
*/
|
||||
static boolean canStartTrial(String stage) {
|
||||
return stage == null
|
||||
|| ProcurementDeal.STAGE_EXPLORING.equals(stage)
|
||||
|| ProcurementDeal.STAGE_TRIAL.equals(stage);
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public List<ProcurementQuote> quotesForDeal(Long dealId) {
|
||||
return quoteRepo.findByDealIdOrderByCreatedAtDesc(dealId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Record that the account is looking at enterprise. Creates the deal at {@code exploring} when
|
||||
* there is none; an existing deal is returned untouched, so this can never walk a live deal
|
||||
* backwards or restart a trial.
|
||||
*/
|
||||
@Transactional
|
||||
public ProcurementDeal recordInterest(Long teamId) {
|
||||
return dealRepo.findByTeamId(teamId)
|
||||
.orElseGet(
|
||||
() -> {
|
||||
ProcurementDeal deal = new ProcurementDeal(teamId);
|
||||
deal.setStage(ProcurementDeal.STAGE_EXPLORING);
|
||||
ProcurementDeal saved = dealRepo.save(deal);
|
||||
log.info(
|
||||
"[procurement] interest recorded team={} deal={}",
|
||||
teamId,
|
||||
saved.getDealId());
|
||||
return saved;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Start (or restart) the free trial for a team: issue a mock trial licence and stamp the trial
|
||||
* window on the deal. No Stripe: a no-card trial has no subscription; the entitlement is the
|
||||
@@ -101,10 +156,40 @@ public class ProcurementService {
|
||||
* ({@code cloud}/{@code selfhost}/{@code airgap}) and seat count are captured here so the quote
|
||||
* builder opens seeded to their environment; both are still editable when the quote is built.
|
||||
*/
|
||||
@Transactional
|
||||
public ProcurementDeal startTrial(Long teamId, String deployment, int seats) {
|
||||
return startTrial(teamId, deployment, seats, null, null, null, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Start (or restart) the trial, capturing the buying entity if the setup step collected it.
|
||||
* Blank details are ignored rather than written, so a re-run without them keeps what is there.
|
||||
*
|
||||
* <p>Only from before the trial or during it. Past that, {@code licenseRef} points at the
|
||||
* committed annual licence, and this method would replace it with a fresh 14-day trial key
|
||||
* while Stripe kept billing — the same hazard {@link #extendTrial} guards against, one step
|
||||
* worse because it re-issues rather than re-dates. It would also rewind the stage and reset the
|
||||
* extension counter.
|
||||
*
|
||||
* <p>The transaction is declared here rather than on the 3-arg overload: that one only
|
||||
* delegates, and Spring's proxy cannot intercept a self-invocation, so an annotation there does
|
||||
* nothing for either path. This is the method the controller calls, and it reaches out to
|
||||
* Keygen between the read and the write.
|
||||
*/
|
||||
@Transactional
|
||||
public ProcurementDeal startTrial(
|
||||
Long teamId,
|
||||
String deployment,
|
||||
int seats,
|
||||
String businessName,
|
||||
String contactName,
|
||||
String contactEmail,
|
||||
String inviteEmails) {
|
||||
ProcurementDeal deal =
|
||||
dealRepo.findByTeamId(teamId).orElseGet(() -> new ProcurementDeal(teamId));
|
||||
if (!canStartTrial(deal.getStage())) {
|
||||
throw new IllegalStateException(
|
||||
"Trial cannot be started from stage " + deal.getStage());
|
||||
}
|
||||
LocalDateTime now = LocalDateTime.now();
|
||||
LocalDateTime ends = now.plusDays(config.getTrialDurationDays());
|
||||
deal.setStage(ProcurementDeal.STAGE_TRIAL);
|
||||
@@ -113,6 +198,10 @@ public class ProcurementService {
|
||||
deal.setTrialStartedAt(now);
|
||||
deal.setTrialEndsAt(ends);
|
||||
deal.setTrialExtensionsUsed(0);
|
||||
if (isNotBlank(businessName)) deal.setBusinessName(businessName.trim());
|
||||
if (isNotBlank(contactName)) deal.setContactName(contactName.trim());
|
||||
if (isNotBlank(contactEmail)) deal.setContactEmail(contactEmail.trim());
|
||||
if (isNotBlank(inviteEmails)) deal.setInviteEmails(inviteEmails.trim());
|
||||
deal.setLicenseRef(licenses.issueTrialLicense(teamId, leaderEmail(teamId), ends));
|
||||
deal = dealRepo.save(deal);
|
||||
log.info(
|
||||
@@ -128,6 +217,45 @@ public class ProcurementService {
|
||||
/**
|
||||
* Constrain a caller-supplied deployment to the known set; anything else falls back to cloud.
|
||||
*/
|
||||
/**
|
||||
* Send the invitations named at trial setup. Best-effort per address: a rejection (already a
|
||||
* member, an invitee with their own paid plan, the hourly rate limit) must not fail the trial,
|
||||
* so each is logged and skipped rather than propagated.
|
||||
*
|
||||
* <p>Note the first accepted invitation converts a personal team into a shared one with
|
||||
* unlimited seats — that is {@code inviteUserToTeam}'s own rule, and naming teammates here is
|
||||
* the buyer asking for exactly that.
|
||||
*/
|
||||
public void sendTrialInvites(
|
||||
Long teamId, stirling.software.proprietary.security.model.User inviter, String emails) {
|
||||
if (inviter == null || !isNotBlank(emails)) return;
|
||||
for (String raw : emails.split("[,;\s]+")) {
|
||||
String email = raw.trim();
|
||||
if (email.isEmpty()) continue;
|
||||
try {
|
||||
teams.inviteUserToTeam(teamId, email, inviter);
|
||||
// Redacted: an invitee list is third-party PII, and these logs are the one place it
|
||||
// would otherwise be written in full. LogRedactionUtils is what the rest of the
|
||||
// SaaS
|
||||
// module uses for the same reason.
|
||||
log.info(
|
||||
"[procurement] trial invite sent team={} to={}",
|
||||
teamId,
|
||||
LogRedactionUtils.redactEmail(email));
|
||||
} catch (Exception e) {
|
||||
log.warn(
|
||||
"[procurement] trial invite skipped team={} to={}: {}",
|
||||
teamId,
|
||||
LogRedactionUtils.redactEmail(email),
|
||||
e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean isNotBlank(String value) {
|
||||
return value != null && !value.isBlank();
|
||||
}
|
||||
|
||||
private static String normalizeDeployment(String deployment) {
|
||||
if (deployment == null) return "cloud";
|
||||
String d = deployment.trim().toLowerCase(Locale.ROOT);
|
||||
@@ -172,16 +300,32 @@ public class ProcurementService {
|
||||
}
|
||||
// (Re)building a quote returns the deal to the quote stage and drops any prior acceptance,
|
||||
// so a rebuild from security/payment can't leave a stale stage or accepted-quote pointer.
|
||||
QuoteBreakdown breakdown = pricing.price(cfg);
|
||||
// Enforced before anything is persisted, and server-side rather than in the builder: the
|
||||
// pricing curve has no natural floor (a small enough committed volume rounds the meter to
|
||||
// zero) and every registered user leads their own team, so without this any signup could
|
||||
// price a $0 enterprise quote, accept it, and be provisioned a committed licence.
|
||||
long floor = config.getMinAnnualNetMinor();
|
||||
if (floor > 0 && breakdown.annualNetMinor() < floor) {
|
||||
throw new IllegalStateException(
|
||||
"Quoted annual fee "
|
||||
+ breakdown.annualNetMinor()
|
||||
+ " is below the minimum enterprise deal size "
|
||||
+ floor);
|
||||
}
|
||||
|
||||
deal.setStage(ProcurementDeal.STAGE_QUOTE);
|
||||
deal.setAcceptedQuoteId(null);
|
||||
deal = dealRepo.save(deal);
|
||||
|
||||
QuoteBreakdown breakdown = pricing.price(cfg);
|
||||
|
||||
ProcurementQuote quote = new ProcurementQuote();
|
||||
quote.setDealId(deal.getDealId());
|
||||
quote.setQuoteNumber(nextQuoteNumber(deal.getDealId()));
|
||||
// Priced but not yet issued: the edge fn creates the Stripe Quote and flips this to SENT.
|
||||
// No quote number here: the deal's one reference is Stripe's, and Stripe does not assign it
|
||||
// until the quote is finalised. The edge fn creates the Stripe Quote, flips this to SENT,
|
||||
// and
|
||||
// writes the number back. Nothing displays a reference in between — the builder only shows
|
||||
// one
|
||||
// for an issued quote, and the agreement is not assembled until after issue.
|
||||
quote.setStatus(ProcurementQuote.STATUS_DRAFT);
|
||||
quote.setCurrency(cfg.currency());
|
||||
quote.setVolume(cfg.volume());
|
||||
@@ -210,10 +354,11 @@ public class ProcurementService {
|
||||
quote.setLineItemsJson(writeLineItems(breakdown));
|
||||
quote.setValidUntil(LocalDate.now().plusDays(30));
|
||||
quote = quoteRepo.save(quote);
|
||||
// Logged by id, not reference: a draft has no reference until Stripe issues it.
|
||||
log.info(
|
||||
"[procurement] quote built team={} quote={} annualNet={} tcv={}",
|
||||
teamId,
|
||||
quote.getQuoteNumber(),
|
||||
quote.getQuoteId(),
|
||||
quote.getAnnualNetMinor(),
|
||||
quote.getTcvMinor());
|
||||
return quote;
|
||||
@@ -241,6 +386,164 @@ public class ProcurementService {
|
||||
return deal;
|
||||
}
|
||||
|
||||
/** The quote a team is currently transacting on: its accepted quote, else the most recent. */
|
||||
@Transactional(readOnly = true)
|
||||
public Optional<ProcurementQuote> currentQuote(Long teamId) {
|
||||
return dealRepo.findByTeamId(teamId)
|
||||
.flatMap(
|
||||
deal -> {
|
||||
if (deal.getAcceptedQuoteId() != null) {
|
||||
Optional<ProcurementQuote> accepted =
|
||||
quoteRepo.findById(deal.getAcceptedQuoteId());
|
||||
if (accepted.isPresent()) return accepted;
|
||||
}
|
||||
return quoteRepo
|
||||
.findByDealIdOrderByCreatedAtDesc(deal.getDealId())
|
||||
.stream()
|
||||
.findFirst();
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* The filled enterprise agreement for a team's current quote, rendered for review (unsigned).
|
||||
*/
|
||||
@Transactional(readOnly = true)
|
||||
public Optional<AssembledAgreement> agreementDocument(Long teamId) {
|
||||
return currentQuote(teamId).map(q -> agreementAssembler.assemble(q, null));
|
||||
}
|
||||
|
||||
/**
|
||||
* The current (unsigned) agreement rendered to PDF, for download at the sign step. Empty when
|
||||
* there's no quote yet or the render runtime is unavailable. The signed PDF (with the signature
|
||||
* block filled) is a separate artifact recorded at signing (see {@link #latestSignature}).
|
||||
*/
|
||||
@Transactional(readOnly = true)
|
||||
public Optional<byte[]> agreementDocumentPdf(Long teamId) {
|
||||
return currentQuote(teamId)
|
||||
.map(q -> agreementAssembler.assemble(q, null))
|
||||
.map(a -> agreementPdfRenderer.tryRender(a.markdown()));
|
||||
}
|
||||
|
||||
/**
|
||||
* Record a signed enterprise agreement: assemble the final document, hash it, render + store
|
||||
* the PDF (best-effort), and persist an immutable signature pinned to the exact document
|
||||
* version. Does not itself accept the quote into a subscription — the caller proceeds to accept
|
||||
* as before.
|
||||
*
|
||||
* <p>Deliberately not {@code @Transactional}: rendering the PDF shells out to WeasyPrint, and
|
||||
* holding the deal's row lock across an external process buys nothing here. The only write is a
|
||||
* single insert, which {@code save} makes atomic on its own.
|
||||
*/
|
||||
public ProcurementAgreementSignature signAgreement(
|
||||
Long teamId, AgreementSigning signing, String signerIp) {
|
||||
ProcurementDeal deal =
|
||||
dealRepo.findByTeamId(teamId)
|
||||
.orElseThrow(() -> new IllegalStateException("No deal for team " + teamId));
|
||||
ProcurementQuote quote =
|
||||
currentQuote(teamId)
|
||||
.orElseThrow(
|
||||
() ->
|
||||
new IllegalStateException(
|
||||
"No quote to sign for team " + teamId));
|
||||
|
||||
// Signing is only meaningful against an issued quote at the agreement stage. Without this a
|
||||
// direct API call could record a signature over a draft (whose quote_ref is still empty),
|
||||
// or
|
||||
// re-sign a deal that has already moved on.
|
||||
if (!ProcurementDeal.STAGE_AGREEMENT.equals(deal.getStage())) {
|
||||
throw new IllegalStateException(
|
||||
"Deal is not at the agreement stage for team " + teamId);
|
||||
}
|
||||
if (!ProcurementQuote.STATUS_SENT.equals(quote.getStatus())) {
|
||||
throw new IllegalStateException("Quote is not issued for team " + teamId);
|
||||
}
|
||||
|
||||
AssembledAgreement assembled = agreementAssembler.assemble(quote, signing);
|
||||
|
||||
ProcurementAgreementSignature sig = new ProcurementAgreementSignature();
|
||||
sig.setDealId(deal.getDealId());
|
||||
sig.setQuoteId(quote.getQuoteId());
|
||||
sig.setDocumentId(assembled.docId());
|
||||
sig.setDocumentVersion(assembled.version());
|
||||
sig.setDocumentLabel(assembled.versionLabel());
|
||||
sig.setContentHash(sha256(assembled.markdown()));
|
||||
sig.setVariablesJson(assembled.variablesJson());
|
||||
sig.setCustomerLegalName(signing.customerLegalName());
|
||||
sig.setSignatoryName(signing.signatoryName());
|
||||
sig.setSignatoryTitle(signing.signatoryTitle());
|
||||
sig.setAuthorityConfirmed(signing.authorityConfirmed());
|
||||
sig.setSignerIp(signerIp);
|
||||
sig.setPdf(agreementPdfRenderer.tryRender(assembled.markdown()));
|
||||
sig = signatureRepo.save(sig);
|
||||
log.info(
|
||||
"[procurement] agreement signed team={} quote={} doc={} pdf={}",
|
||||
teamId,
|
||||
quote.getQuoteId(),
|
||||
assembled.versionLabel(),
|
||||
sig.getPdf() != null);
|
||||
return sig;
|
||||
}
|
||||
|
||||
/** The latest recorded signature for a team's deal, if any (for the signed-PDF download). */
|
||||
@Transactional(readOnly = true)
|
||||
public Optional<ProcurementAgreementSignature> latestSignature(Long teamId) {
|
||||
return dealRepo.findByTeamId(teamId)
|
||||
.flatMap(
|
||||
deal ->
|
||||
signatureRepo.findFirstByDealIdOrderBySignedAtDesc(
|
||||
deal.getDealId()));
|
||||
}
|
||||
|
||||
/**
|
||||
* The version label of the deal's latest signed agreement, if any. Used to surface the
|
||||
* "download signed agreement" action once a signature exists; the snapshot polls this, so it
|
||||
* deliberately avoids loading the PDF bytes.
|
||||
*
|
||||
* <p>Deliberately not conditional on a stored PDF: download re-renders from the pinned document
|
||||
* version on demand, so the action works whether or not the render succeeded at signing time.
|
||||
*/
|
||||
@Transactional(readOnly = true)
|
||||
public Optional<String> signedAgreementLabel(Long dealId) {
|
||||
return signatureRepo.findSignedLabels(dealId).stream().findFirst();
|
||||
}
|
||||
|
||||
/**
|
||||
* The signed agreement as a PDF for download: the artifact stored at signing, or — if the
|
||||
* render runtime was unavailable then — re-rendered now from the signature's details. Empty
|
||||
* when the team has no signature or the render runtime is still unavailable.
|
||||
*/
|
||||
@Transactional(readOnly = true)
|
||||
public Optional<byte[]> signedAgreementPdf(Long teamId) {
|
||||
return latestSignature(teamId)
|
||||
.flatMap(
|
||||
sig -> {
|
||||
if (sig.getPdf() != null) return Optional.of(sig.getPdf());
|
||||
return quoteRepo
|
||||
.findById(sig.getQuoteId())
|
||||
.map(
|
||||
q ->
|
||||
agreementAssembler.assemble(
|
||||
q,
|
||||
new AgreementSigning(
|
||||
sig.getCustomerLegalName(),
|
||||
sig.getSignatoryName(),
|
||||
sig.getSignatoryTitle(),
|
||||
sig.isAuthorityConfirmed())))
|
||||
.map(a -> agreementPdfRenderer.tryRender(a.markdown()));
|
||||
});
|
||||
}
|
||||
|
||||
private static String sha256(String s) {
|
||||
try {
|
||||
byte[] digest =
|
||||
java.security.MessageDigest.getInstance("SHA-256")
|
||||
.digest(s.getBytes(java.nio.charset.StandardCharsets.UTF_8));
|
||||
return java.util.HexFormat.of().formatHex(digest);
|
||||
} catch (java.security.NoSuchAlgorithmException e) {
|
||||
throw new IllegalStateException("SHA-256 unavailable", e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Provision on accept: upgrade the team's licence to the committed annual term (valid
|
||||
* immediately), so the buyer can get going the moment they accept — before the invoice is paid.
|
||||
@@ -260,22 +563,58 @@ public class ProcurementService {
|
||||
}
|
||||
|
||||
/**
|
||||
* Mark the deal fully live (advance to the active stage) once payment settles. In production
|
||||
* this is the {@code invoice.paid} webhook; here it's the demo/manual stand-in. Re-affirms the
|
||||
* Mark the deal fully live (advance to the active stage) once payment settles — driven by the
|
||||
* {@code invoice.paid} webhook, and by the demo control when those are enabled. Re-affirms the
|
||||
* annual licence in case provisioning didn't run at accept.
|
||||
*
|
||||
* <p>Idempotent per invoice rather than per stage, which matters because {@code invoice.paid}
|
||||
* carries two different meanings. Stripe redelivers events, so the <em>same</em> invoice
|
||||
* arriving twice must do nothing. But the renewal payment a year later is also an {@code
|
||||
* invoice.paid}, and the committed licence expires term years from issue — so a
|
||||
* <em>different</em> invoice has to re-issue, moving the expiry out, or the customer's licence
|
||||
* lapses after they have paid. Keying on the stage alone couldn't tell those apart and treated
|
||||
* every renewal as a duplicate.
|
||||
*
|
||||
* @param paidInvoiceId the Stripe invoice that was paid, or null when the caller has no invoice
|
||||
* to identify the payment by (the demo control). Null keeps the old conservative behaviour:
|
||||
* a live deal short-circuits, since there is nothing to tell a renewal from a repeat.
|
||||
*/
|
||||
@Transactional
|
||||
public ProcurementDeal markLive(Long teamId) {
|
||||
public ProcurementDeal markLive(Long teamId, String paidInvoiceId) {
|
||||
ProcurementDeal deal =
|
||||
dealRepo.findByTeamId(teamId)
|
||||
.orElseThrow(() -> new IllegalStateException("No deal for team " + teamId));
|
||||
if (ProcurementDeal.STAGE_LIVE.equals(deal.getStage())
|
||||
&& (paidInvoiceId == null || paidInvoiceId.equals(deal.getLastPaidInvoiceId()))) {
|
||||
log.debug(
|
||||
"[procurement] invoice.paid already applied team={} deal={} invoice={}",
|
||||
teamId,
|
||||
deal.getDealId(),
|
||||
paidInvoiceId);
|
||||
return deal;
|
||||
}
|
||||
boolean renewal = ProcurementDeal.STAGE_LIVE.equals(deal.getStage());
|
||||
deal.setLicenseRef(issueOrUpgradeAnnual(deal));
|
||||
if (paidInvoiceId != null) deal.setLastPaidInvoiceId(paidInvoiceId);
|
||||
deal.setStage(ProcurementDeal.STAGE_LIVE);
|
||||
deal = dealRepo.save(deal);
|
||||
log.info("[procurement] deal live team={} deal={}", teamId, deal.getDealId());
|
||||
log.info(
|
||||
"[procurement] deal live team={} deal={} renewal={} invoice={}",
|
||||
teamId,
|
||||
deal.getDealId(),
|
||||
renewal,
|
||||
paidInvoiceId);
|
||||
return deal;
|
||||
}
|
||||
|
||||
/**
|
||||
* Go live with no invoice reference — the demo control. See {@link #markLive(Long, String)}.
|
||||
*/
|
||||
@Transactional
|
||||
public ProcurementDeal markLive(Long teamId) {
|
||||
return markLive(teamId, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Issue or upgrade the committed annual licence from the deal's accepted (else latest) quote,
|
||||
* stamping the full entitlement snapshot onto it and upgrading the trial licence in place when
|
||||
@@ -327,15 +666,34 @@ public class ProcurementService {
|
||||
* before paying — that's bounded: the trial licence carries {@code expiry = trialEndsAt}, so
|
||||
* the file the verifier accepts self-expires at trial end. The buyer must re-download after
|
||||
* provisioning to get the committed-term file (the portal warns about this).
|
||||
*
|
||||
* <p>Once a quote exists, the quote's deployment decides — not the deal's. They are two
|
||||
* different values: the deal's is chosen free at trial setup, the quote's is the one carrying
|
||||
* the air-gap deploy fee. Reading the deal's here meant selecting air-gapped in the trial and
|
||||
* then buying a cloud quote still yielded the offline file, and after provisioning it was
|
||||
* checked out against the committed annual licence — so the self-expiry above no longer bounded
|
||||
* it.
|
||||
*/
|
||||
@Transactional(readOnly = true)
|
||||
public Optional<String> offlineLicenseFile(Long teamId) {
|
||||
ProcurementDeal deal = dealRepo.findByTeamId(teamId).orElse(null);
|
||||
if (deal == null || deal.getLicenseRef() == null) return Optional.empty();
|
||||
if (!"airgap".equalsIgnoreCase(deal.getDeployment())) return Optional.empty();
|
||||
if (!"airgap".equalsIgnoreCase(entitledDeployment(deal))) return Optional.empty();
|
||||
return Optional.of(licenses.checkOutLicenseFile(deal.getLicenseRef()));
|
||||
}
|
||||
|
||||
/**
|
||||
* The deployment the team is actually entitled to: the priced quote's once one exists,
|
||||
* otherwise the trial's self-selected target. Paid entitlements must follow what was quoted.
|
||||
*/
|
||||
private String entitledDeployment(ProcurementDeal deal) {
|
||||
ProcurementQuote quote = currentQuote(deal.getTeamId()).orElse(null);
|
||||
if (quote != null && quote.getDeployment() != null && !quote.getDeployment().isBlank()) {
|
||||
return quote.getDeployment();
|
||||
}
|
||||
return deal.getDeployment();
|
||||
}
|
||||
|
||||
/**
|
||||
* Reset a team's procurement: delete the deal (quotes + activity cascade). For
|
||||
* re-demos/testing.
|
||||
@@ -346,12 +704,6 @@ public class ProcurementService {
|
||||
log.info("[procurement] deal reset team={}", teamId);
|
||||
}
|
||||
|
||||
private String nextQuoteNumber(Long dealId) {
|
||||
int seq = quoteRepo.findByDealIdOrderByCreatedAtDesc(dealId).size() + 1;
|
||||
String token = UUID.randomUUID().toString().substring(0, 4).toUpperCase(Locale.ROOT);
|
||||
return String.format(Locale.ROOT, "QT-%s-%04d", token, seq);
|
||||
}
|
||||
|
||||
private String writeLineItems(QuoteBreakdown breakdown) {
|
||||
try {
|
||||
return OBJECT_MAPPER.writeValueAsString(breakdown.lineItems());
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
## Part C — Data Processing Addendum
|
||||
|
||||
This DPA forms part of the Agreement and applies where Provider processes Personal Data on Customer's behalf.
|
||||
|
||||
### C1. Roles; scope; instructions
|
||||
|
||||
Customer is the controller (or a processor on behalf of its own controllers); Provider is a processor (or subprocessor, as applicable). Provider processes Personal Data only on Customer's documented instructions — including processing initiated by Customer's users, policies, pipelines, and API calls — unless required by law (in which case Provider informs Customer unless legally prohibited). **Provider will inform Customer without undue delay if, in Provider's opinion, an instruction infringes the GDPR, UK GDPR, or other applicable data-protection law.** Customer is responsible for the lawfulness of the Personal Data it submits and the instructions it gives; Customer's rights under this DPA include instruction, audit (C9), objection to subprocessors (C5), assistance (C6), and return or deletion of data (C10).
|
||||
|
||||
### C2. Details of processing
|
||||
|
||||
**Subject matter/nature:** PDF processing and governance (classification, redaction, routing, retention, conversion, signing, extraction, AI-assisted analysis). **Duration:** the Term plus the deletion period. **Categories of data:** any Personal Data contained in Customer files and metadata (names, contact details, identifiers, financial or health data if present in Customer files), account data of Customer users. **Data subjects:** Customer's employees, users, customers, and other persons appearing in Customer files. **Sensitive data:** may be present in Customer files at Customer's discretion; Customer is responsible for the lawful basis.
|
||||
|
||||
### C3. Confidentiality; personnel
|
||||
|
||||
Provider ensures persons authorized to process Personal Data are bound by confidentiality and receive security training. Zero-standing-access applies: content access is just-in-time, logged, and audited (MSA Section 4.2).
|
||||
|
||||
### C4. Security measures (Annex II summary)
|
||||
|
||||
Encryption in transit (TLS 1.2+) and at rest (AES-256); zero-standing-access with audited JIT elevation; role-based access control; SSO/SCIM; tenant isolation; vulnerability management and penetration testing; audit logging of processing events (including file name, hash, size, and operations); backup and recovery. For Self-hosted and Air-gapped deployments, Customer operates the runtime environment and is responsible for infrastructure-level controls; Provider's measures apply to license/metering services and support access.
|
||||
|
||||
### C5. Subprocessors
|
||||
|
||||
Customer generally authorizes the subprocessors listed at {{subprocessor_url}}: cloud infrastructure (Amazon Web Services), payment processing (Stripe, as independent controller for payment data), email delivery (Google), account infrastructure (Supabase), product telemetry (PostHog, EU-hosted; pseudonymous usage events, never file content), and AI model providers: **Anthropic** (Claude models — receives prompts and the document text or excerpts needed for the requested AI feature) and **Voyage AI** (embedding models — receives extracted text excerpts solely to generate embeddings where Customer enables Ingestion/RAG features). AI features are optional and may be disabled; where used, AI providers receive only the content needed for the requested feature. **Whole Customer files are never transmitted to any AI provider.** Neither AI provider trains on Customer data (verified against the signed provider agreements, Jul 10, 2026). Provider gives thirty (30) days' notice of new subprocessors; Customer may object on reasonable data-protection grounds, and if unresolved, may terminate the affected Services with a pro-rata refund. **Provider imposes data-protection obligations on each subprocessor by written contract that are at least as protective as this DPA, and remains fully responsible to Customer for each subprocessor's performance.**
|
||||
|
||||
### C6. Data subject requests; assistance
|
||||
|
||||
Taking into account the nature of the processing, Provider provides reasonable assistance (including through the Processor's search, redaction, and audit tools) for Customer's obligations under GDPR Articles 32–36: security of processing, breach notification to authorities and data subjects, data protection impact assessments, and prior consultations with supervisory authorities, as well as responses to data subject requests. Provider forwards requests received directly to Customer and does not respond except as legally required. **Provider makes available to Customer all information necessary to demonstrate compliance with this DPA and allows for and contributes to audits, including inspections, per Section C9.**
|
||||
|
||||
### C7. Breach notification
|
||||
|
||||
Per MSA Section 5.3: without undue delay after becoming aware of a Personal Data Breach, and in any event within forty-eight (48) hours of awareness, with information provided in phases as available — including the nature of the breach, categories and approximate volumes affected, likely consequences, and measures taken or proposed.
|
||||
|
||||
### C8. International transfers
|
||||
|
||||
Where Personal Data subject to GDPR/UK GDPR is transferred to countries without adequacy, the Parties incorporate the EU Standard Contractual Clauses (Commission Decision 2021/914): **Module 2** (controller-to-processor) where Customer is a controller, and **Module 3** (processor-to-processor) where Customer acts as a processor, with the following selections — Clause 7 (docking): included; Clause 9(a): Option 2 (general written authorization, 30 days' notice per C5); Clause 11(a) optional language: not used; Clause 17: the law of Ireland; Clause 18: the courts of Ireland; competent supervisory authority: the Irish Data Protection Commission (per Annex I.C). Annex I (parties, description of transfer: as per Section C2), Annex II (technical and organizational measures: as per Section C4), and Annex III (subprocessors: as per Section C5 and {{subprocessor_url}}) are completed by reference to this DPA. For UK transfers, the UK International Data Transfer Addendum applies with its Tables completed by reference to the foregoing. Provider is not certified under the EU-U.S. Data Privacy Framework; the SCCs are the transfer mechanism.
|
||||
|
||||
**Note:** Provider does not currently offer contractual EU data residency for Stirling Cloud; residency is achieved via Self-hosted or Air-gapped deployment.
|
||||
|
||||
### C9. Audits
|
||||
|
||||
Provider's security reports and documentation (Section 5.1) are the ordinary means of demonstrating compliance. Customer may additionally audit — by itself or a mandated auditor — once per year on thirty (30) days' notice, and at any time where: (a) a security incident affecting Customer Personal Data has occurred; (b) provided documentation reveals a material deficiency; (c) a competent supervisory authority requires it; or (d) Customer reasonably suspects material noncompliance with this DPA. Audits are conducted during business hours, under confidentiality, at Customer's cost, with reasonable notice, without unreasonable interference with Provider's operations, and without access to other customers' data.
|
||||
|
||||
### C10. Return & deletion
|
||||
|
||||
On termination, at Customer's choice, Provider returns Customer file content and Personal Data (export of Customer files and the governed-record metadata) and/or deletes them — from live systems within thirty (30) days and from backups within ninety (90) days — except as retention is required by law, and certifies deletion on request. Where Customer uses HYOK, key destruction by Customer renders content cryptographically inaccessible immediately.
|
||||
|
||||
### C11. CCPA/CPRA
|
||||
|
||||
Provider is a "service provider" under the CCPA/CPRA. Provider: (a) processes Personal Information only for the business purposes specified in this Agreement — providing, securing, metering, and supporting the Services described in Section C2; (b) shall not sell or share Personal Information; (c) shall not retain, use, or disclose it for any purpose other than those business purposes, or outside the direct business relationship between the Parties; (d) shall not combine it with Personal Information received from other sources, except as permitted by CCPA regulations for the business purposes; (e) provides the same level of privacy protection required of businesses by the CCPA; (f) will notify Customer if it determines it can no longer meet its CCPA obligations; (g) grants Customer the right, upon reasonable notice, to take reasonable and appropriate steps to ensure Provider's use of Personal Information is consistent with Customer's obligations, and to stop and remediate any unauthorized use; and (h) flows these requirements down to its subprocessors per Section C5. Provider certifies that it understands these restrictions and will comply with them.
|
||||
|
||||
### C12. Liability
|
||||
|
||||
Liability under this DPA is subject to the MSA's limitations (Section 8).
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user