Compare commits

..
Author SHA1 Message Date
Anthony Stirling 0a8b7f4e83 on push test 2025-11-25 20:50:26 +00:00
Anthony Stirling 2f106473df update 2025-11-25 20:42:38 +00:00
Anthony Stirling 1aa4950178 new translations 2025-11-25 20:11:37 +00:00
46 changed files with 720 additions and 1457 deletions
+552 -197
View File
@@ -1,4 +1,4 @@
name: Test Installers Build
name: Multi-OS Tauri Releases
on:
workflow_dispatch:
@@ -6,7 +6,23 @@ on:
test_mode:
description: "Run in test mode (skip release step)"
required: false
default: "false"
default: "true"
type: choice
options:
- "true"
- "false"
platform:
description: "Platform to build (windows, macos, linux, or all)"
required: true
default: "all"
type: choice
options:
- all
- windows
- macos
- linux
push:
branches: [main, V2, V2-demo]
release:
types: [created]
@@ -14,41 +30,50 @@ permissions:
contents: read
jobs:
read_versions:
determine-matrix:
runs-on: ubuntu-latest
outputs:
matrix: ${{ steps.set-matrix.outputs.matrix }}
version: ${{ steps.versionNumber.outputs.versionNumber }}
versionMac: ${{ steps.versionNumberMac.outputs.versionNumberMac }}
steps:
- name: Harden Runner
uses: step-security/harden-runner@f4a75cfd619ee5ce8d5b864b0d183aff3c69b55a # v2.13.1
with:
egress-policy: audit
- uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # v5.0.0
- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
- name: Set up JDK
uses: actions/setup-java@dded0888837ed1f317902acf8a20df0ad188d165 # v5.0.0
with:
distribution: 'temurin'
java-version: '21'
# ✅ Get version from Gradle
- name: Get version number
id: versionNumber
run: |
VERSION=$(./gradlew printVersion --quiet | tail -1)
VERSION=$(grep "^version =" build.gradle | awk -F'"' '{print $2}')
echo "versionNumber=$VERSION" >> $GITHUB_OUTPUT
# ✅ Get Mac-specific version from Gradle
- name: Get version number mac
id: versionNumberMac
- name: Determine build matrix
id: set-matrix
run: |
VERSION_MAC=$(./gradlew printMacVersion --quiet | tail -1)
echo "versionNumberMac=$VERSION_MAC" >> $GITHUB_OUTPUT
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"}]}' >> $GITHUB_OUTPUT
;;
"macos")
echo 'matrix={"include":[{"platform":"macos-15","args":"--target aarch64-apple-darwin","name":"macos-aarch64"},{"platform":"macos-15-intel","args":"--target x86_64-apple-darwin","name":"macos-x86_64"}]}' >> $GITHUB_OUTPUT
;;
"linux")
echo 'matrix={"include":[{"platform":"ubuntu-22.04","args":"","name":"linux-x86_64"}]}' >> $GITHUB_OUTPUT
;;
*)
echo 'matrix={"include":[{"platform":"windows-latest","args":"--target x86_64-pc-windows-msvc","name":"windows-x86_64"},{"platform":"macos-15","args":"--target aarch64-apple-darwin","name":"macos-aarch64"},{"platform":"macos-15-intel","args":"--target x86_64-apple-darwin","name":"macos-x86_64"},{"platform":"ubuntu-22.04","args":"","name":"linux-x86_64"}]}' >> $GITHUB_OUTPUT
;;
esac
else
# For release events, build all platforms
echo 'matrix={"include":[{"platform":"windows-latest","args":"--target x86_64-pc-windows-msvc","name":"windows-x86_64"},{"platform":"macos-15","args":"--target aarch64-apple-darwin","name":"macos-aarch64"},{"platform":"macos-15-intel","args":"--target x86_64-apple-darwin","name":"macos-x86_64"},{"platform":"ubuntu-22.04","args":"","name":"linux-x86_64"}]}' >> $GITHUB_OUTPUT
fi
build-portable:
needs: read_versions
build-jars:
needs: determine-matrix
runs-on: ubuntu-latest
strategy:
matrix:
@@ -64,10 +89,10 @@ jobs:
with:
egress-policy: audit
- uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # v5.0.0
- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
- name: Set up JDK 21
uses: actions/setup-java@dded0888837ed1f317902acf8a20df0ad188d165 # v5.0.0
uses: actions/setup-java@c5195efecf7bdfc987ee8bae7a71cb8b11521c00 # v4.7.1
with:
java-version: "21"
distribution: "temurin"
@@ -76,36 +101,405 @@ jobs:
with:
gradle-version: 8.14
- name: Generate jar (Disable Security=${{ matrix.disable_security }})
run: ./gradlew clean createExe
- name: Build JAR
run: ./gradlew clean build -x spotlessApply -x spotlessCheck -x test -x sonarqube
env:
DISABLE_ADDITIONAL_FEATURES: ${{ matrix.disable_security }}
STIRLING_PDF_DESKTOP_UI: false
- name: Rename binaries
- name: Rename JAR
run: |
mkdir ./binaries
mv ./build/launch4j/Stirling-PDF.exe ./binaries/win-Stirling-PDF-portable-Server${{ matrix.file_suffix }}.exe
mv ./app/core/build/libs/stirling-pdf-${{ needs.read_versions.outputs.version }}.jar ./binaries/Stirling-PDF${{ matrix.file_suffix }}.jar
mkdir -p ./jar-dist
cp app/core/build/libs/stirling-pdf-${{ needs.determine-matrix.outputs.version }}.jar ./jar-dist/Stirling-PDF${{ matrix.file_suffix }}.jar
- name: Upload JAR artifacts
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
with:
name: jar${{ matrix.file_suffix }}
path: ./jar-dist/*.jar
retention-days: 1
build:
needs: determine-matrix
strategy:
fail-fast: false
matrix: ${{ fromJson(needs.determine-matrix.outputs.matrix) }}
runs-on: ${{ matrix.platform }}
env:
SM_API_KEY: ${{ secrets.SM_API_KEY }}
WINDOWS_CERTIFICATE: ${{ secrets.WINDOWS_CERTIFICATE }}
steps:
- name: Harden Runner
uses: step-security/harden-runner@002fdce3c6a235733a90a27c80493a3241e56863 # v2.12.1
with:
egress-policy: audit
- name: Checkout repository
uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
- name: Install dependencies (ubuntu only)
if: matrix.platform == 'ubuntu-22.04'
run: |
sudo apt-get update
sudo apt-get install -y libgtk-3-dev libwebkit2gtk-4.0-dev libwebkit2gtk-4.1-dev libappindicator3-dev librsvg2-dev patchelf libjavascriptcoregtk-4.0-dev libsoup2.4-dev libjavascriptcoregtk-4.1-dev libsoup-3.0-dev
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: 20
cache: 'npm'
cache-dependency-path: frontend/package-lock.json
- name: Setup Rust
uses: dtolnay/rust-toolchain@stable
with:
toolchain: stable
targets: ${{ (matrix.platform == 'macos-15' || matrix.platform == 'macos-15-intel') && 'aarch64-apple-darwin,x86_64-apple-darwin' || '' }}
- name: Set up JDK 21
uses: actions/setup-java@c5195efecf7bdfc987ee8bae7a71cb8b11521c00 # v4.7.1
with:
java-version: "21"
distribution: "temurin"
- name: Build Java backend with JLink
working-directory: ./
shell: bash
run: |
chmod +x ./gradlew
echo "🔧 Building Stirling-PDF JAR..."
./gradlew clean build -x spotlessApply -x spotlessCheck -x test -x sonarqube
# Find the built JAR
STIRLING_JAR=$(ls app/core/build/libs/stirling-pdf-*.jar | head -n 1)
echo "✅ Built JAR: $STIRLING_JAR"
# Create Tauri directories
mkdir -p ./frontend/src-tauri/libs
mkdir -p ./frontend/src-tauri/runtime
# Copy JAR to Tauri libs
cp "$STIRLING_JAR" ./frontend/src-tauri/libs/
echo "✅ JAR copied to Tauri libs"
# Analyze JAR dependencies for jlink modules
echo "🔍 Analyzing JAR dependencies..."
if command -v jdeps &> /dev/null; then
DETECTED_MODULES=$(jdeps --print-module-deps --ignore-missing-deps "$STIRLING_JAR" 2>/dev/null || echo "")
if [ -n "$DETECTED_MODULES" ]; then
echo "📋 jdeps detected modules: $DETECTED_MODULES"
MODULES="$DETECTED_MODULES,java.compiler,java.instrument,java.management,java.naming,java.net.http,java.prefs,java.rmi,java.scripting,java.security.jgss,java.security.sasl,java.sql,java.transaction.xa,java.xml.crypto,jdk.crypto.ec,jdk.crypto.cryptoki,jdk.unsupported"
else
echo "⚠️ jdeps analysis failed, using predefined modules"
MODULES="java.base,java.compiler,java.desktop,java.instrument,java.logging,java.management,java.naming,java.net.http,java.prefs,java.rmi,java.scripting,java.security.jgss,java.security.sasl,java.sql,java.transaction.xa,java.xml,java.xml.crypto,jdk.crypto.ec,jdk.crypto.cryptoki,jdk.unsupported"
fi
else
echo "⚠️ jdeps not available, using predefined modules"
MODULES="java.base,java.compiler,java.desktop,java.instrument,java.logging,java.management,java.naming,java.net.http,java.prefs,java.rmi,java.scripting,java.security.jgss,java.security.sasl,java.sql,java.transaction.xa,java.xml,java.xml.crypto,jdk.crypto.ec,jdk.crypto.cryptoki,jdk.unsupported"
fi
# Create custom JRE with jlink
echo "🔧 Creating custom JRE with jlink..."
echo "📋 Using modules: $MODULES"
# Remove any existing JRE
rm -rf ./frontend/src-tauri/runtime/jre
# Create the custom JRE
jlink \
--add-modules "$MODULES" \
--strip-debug \
--compress=2 \
--no-header-files \
--no-man-pages \
--output ./frontend/src-tauri/runtime/jre
if [ ! -d "./frontend/src-tauri/runtime/jre" ]; then
echo "❌ Failed to create JLink runtime"
exit 1
fi
# Test the bundled runtime
if [ -f "./frontend/src-tauri/runtime/jre/bin/java" ]; then
RUNTIME_VERSION=$(./frontend/src-tauri/runtime/jre/bin/java --version 2>&1 | head -n 1)
echo "✅ Custom JRE created successfully: $RUNTIME_VERSION"
else
echo "❌ Custom JRE executable not found"
exit 1
fi
# Calculate runtime size
RUNTIME_SIZE=$(du -sh ./frontend/src-tauri/runtime/jre | cut -f1)
echo "📊 Custom JRE size: $RUNTIME_SIZE"
env:
DISABLE_ADDITIONAL_FEATURES: true
- name: Install frontend dependencies
working-directory: ./frontend
run: npm install
# 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' }}
uses: digicert/ssm-code-signing@v1.1.0
env:
SM_API_KEY: ${{ secrets.SM_API_KEY }}
SM_CLIENT_CERT_FILE_B64: ${{ secrets.SM_CLIENT_CERT_FILE_B64 }}
SM_CLIENT_CERT_PASSWORD: ${{ secrets.SM_CLIENT_CERT_PASSWORD }}
SM_KEYPAIR_ALIAS: ${{ secrets.SM_KEYPAIR_ALIAS }}
SM_HOST: ${{ secrets.SM_HOST }}
- name: Setup DigiCert KeyLocker Certificate
if: ${{ matrix.platform == 'windows-latest' && env.SM_API_KEY != '' && github.event_name == 'release' }}
shell: pwsh
run: |
Write-Host "Setting up DigiCert KeyLocker environment..."
# Decode client certificate
$certBytes = [Convert]::FromBase64String("${{ secrets.SM_CLIENT_CERT_FILE_B64 }}")
$certPath = "D:\Certificate_pkcs12.p12"
[IO.File]::WriteAllBytes($certPath, $certBytes)
# Set environment variables
echo "SM_CLIENT_CERT_FILE=D:\Certificate_pkcs12.p12" >> $env:GITHUB_ENV
echo "SM_HOST=${{ secrets.SM_HOST }}" >> $env:GITHUB_ENV
echo "SM_API_KEY=${{ secrets.SM_API_KEY }}" >> $env:GITHUB_ENV
echo "SM_CLIENT_CERT_PASSWORD=${{ secrets.SM_CLIENT_CERT_PASSWORD }}" >> $env:GITHUB_ENV
echo "SM_KEYPAIR_ALIAS=${{ secrets.SM_KEYPAIR_ALIAS }}" >> $env:GITHUB_ENV
# Get PKCS11 config path from DigiCert action
$pkcs11Config = $env:PKCS11_CONFIG
if ($pkcs11Config) {
Write-Host "Found PKCS11_CONFIG: $pkcs11Config"
echo "PKCS11_CONFIG=$pkcs11Config" >> $env:GITHUB_ENV
} else {
Write-Host "PKCS11_CONFIG not set by DigiCert action, using default path"
$defaultPath = "C:\Users\RUNNER~1\AppData\Local\Temp\smtools-windows-x64\pkcs11properties.cfg"
if (Test-Path $defaultPath) {
Write-Host "Found config at default path: $defaultPath"
echo "PKCS11_CONFIG=$defaultPath" >> $env:GITHUB_ENV
} else {
Write-Host "Warning: Could not find PKCS11 config file"
}
}
# 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' }}
env:
WINDOWS_CERTIFICATE: ${{ secrets.WINDOWS_CERTIFICATE }}
WINDOWS_CERTIFICATE_PASSWORD: ${{ secrets.WINDOWS_CERTIFICATE_PASSWORD }}
shell: powershell
run: |
if ($env:WINDOWS_CERTIFICATE) {
Write-Host "Importing Windows Code Signing Certificate..."
# Decode base64 certificate and save to file
$certBytes = [Convert]::FromBase64String($env:WINDOWS_CERTIFICATE)
$certPath = Join-Path $env:RUNNER_TEMP "certificate.pfx"
[IO.File]::WriteAllBytes($certPath, $certBytes)
# Import certificate to CurrentUser\My store
$cert = Import-PfxCertificate -FilePath $certPath -CertStoreLocation Cert:\CurrentUser\My -Password (ConvertTo-SecureString -String $env:WINDOWS_CERTIFICATE_PASSWORD -AsPlainText -Force)
# Extract and set thumbprint as environment variable
$thumbprint = $cert.Thumbprint
Write-Host "Certificate imported with thumbprint: $thumbprint"
echo "WINDOWS_CERTIFICATE_THUMBPRINT=$thumbprint" >> $env:GITHUB_ENV
# Clean up certificate file
Remove-Item $certPath
Write-Host "Windows certificate import completed."
} else {
Write-Host "⚠️ WINDOWS_CERTIFICATE secret not set - building unsigned binary"
}
- name: Import Apple Developer Certificate
if: (matrix.platform == 'macos-15' || matrix.platform == 'macos-15-intel') && github.event_name == 'release'
env:
APPLE_CERTIFICATE: ${{ secrets.APPLE_CERTIFICATE }}
APPLE_CERTIFICATE_PASSWORD: ${{ secrets.APPLE_CERTIFICATE_PASSWORD }}
run: |
echo "Importing Apple Developer Certificate..."
echo $APPLE_CERTIFICATE | base64 --decode > certificate.p12
# Create temporary keychain
KEYCHAIN_PATH=$RUNNER_TEMP/app-signing.keychain-db
KEYCHAIN_PASSWORD=$(openssl rand -base64 32)
security create-keychain -p "$KEYCHAIN_PASSWORD" $KEYCHAIN_PATH
security set-keychain-settings -lut 21600 $KEYCHAIN_PATH
security unlock-keychain -p "$KEYCHAIN_PASSWORD" $KEYCHAIN_PATH
# Import certificate
security import certificate.p12 -P "$APPLE_CERTIFICATE_PASSWORD" -A -t cert -f pkcs12 -k $KEYCHAIN_PATH
security list-keychain -d user -s $KEYCHAIN_PATH
security set-key-partition-list -S apple-tool:,apple: -k "$KEYCHAIN_PASSWORD" $KEYCHAIN_PATH
# Clean up
rm certificate.p12
- name: Verify Certificate
if: (matrix.platform == 'macos-15' || matrix.platform == 'macos-15-intel') && github.event_name == 'release'
run: |
echo "Verifying Apple Developer Certificate..."
KEYCHAIN_PATH=$RUNNER_TEMP/app-signing.keychain-db
CERT_INFO=$(security find-identity -v -p codesigning $KEYCHAIN_PATH | grep "Developer ID Application")
echo "Certificate Info: $CERT_INFO"
CERT_ID=$(echo "$CERT_INFO" | awk -F'"' '{print $2}')
echo "Certificate ID: $CERT_ID"
echo "APPLE_SIGNING_IDENTITY=$CERT_ID" >> $GITHUB_ENV
echo "Certificate imported successfully."
- name: Build Tauri app
uses: tauri-apps/tauri-action@v0
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
APPLE_CERTIFICATE: ${{ secrets.APPLE_CERTIFICATE }}
APPLE_CERTIFICATE_PASSWORD: ${{ secrets.APPLE_CERTIFICATE_PASSWORD }}
APPLE_SIGNING_IDENTITY: ${{ env.APPLE_SIGNING_IDENTITY }}
APPLE_ID: ${{ secrets.APPLE_ID }}
APPLE_PASSWORD: ${{ secrets.APPLE_ID_PASSWORD }}
APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}
APPIMAGETOOL_SIGN_PASSPHRASE: ${{ secrets.APPIMAGETOOL_SIGN_PASSPHRASE }}
TAURI_SIGNING_PRIVATE_KEY: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY }}
TAURI_SIGNING_PRIVATE_KEY_PASSWORD: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY_PASSWORD }}
VITE_SUPABASE_PUBLISHABLE_DEFAULT_KEY: ${{ secrets.VITE_SUPABASE_PUBLISHABLE_DEFAULT_KEY }}
VITE_SAAS_SERVER_URL: ${{ secrets.VITE_SAAS_SERVER_URL }}
# Only enable Windows signing in Tauri when on release
SIGN: ${{ github.event_name == 'release' && (env.SM_API_KEY == '' && env.WINDOWS_CERTIFICATE != '') && '1' || '0' }}
CI: true
with:
projectPath: ./frontend
tauriScript: npx tauri
args: ${{ matrix.args }}
# Sign with DigiCert KeyLocker (post-build)
- name: Sign Windows binaries with DigiCert KeyLocker
if: ${{ matrix.platform == 'windows-latest' && env.SM_API_KEY != '' && github.event_name == 'release' }}
shell: pwsh
run: |
Write-Host "=== DigiCert KeyLocker Signing ==="
# Test smctl connectivity first
Write-Host "Testing smctl connection..."
$healthCheck = & smctl healthcheck 2>&1
if ($LASTEXITCODE -eq 0) {
Write-Host "[SUCCESS] Connected to DigiCert KeyLocker"
} else {
Write-Host "[ERROR] Failed to connect to DigiCert KeyLocker"
Write-Host $healthCheck
exit 1
}
Write-Host ""
# Sync certificates to Windows certificate store
Write-Host "Syncing certificates to Windows certificate store..."
$syncOutput = & smctl windows certsync 2>&1
Write-Host "Cert sync result: $syncOutput"
Write-Host ""
# Find only the files we need to sign
$filesToSign = @()
# Main application executable
$mainExe = Get-ChildItem -Path "./frontend/src-tauri/target/x86_64-pc-windows-msvc/release" -Filter "stirling-pdf.exe" -File -ErrorAction SilentlyContinue
if ($mainExe) { $filesToSign += $mainExe }
# MSI installer
$msiFiles = Get-ChildItem -Path "./frontend/src-tauri/target" -Filter "*.msi" -Recurse -File
$filesToSign += $msiFiles
if ($filesToSign.Count -eq 0) {
Write-Host "[ERROR] No files found to sign"
exit 1
}
Write-Host "Found $($filesToSign.Count) files to sign:"
foreach ($f in $filesToSign) { Write-Host " - $($f.Name)" }
Write-Host ""
$signedCount = 0
foreach ($file in $filesToSign) {
Write-Host "Signing: $($file.Name)"
# Get PKCS11 config file path
$pkcs11Config = $env:PKCS11_CONFIG
if (-not $pkcs11Config) {
Write-Host "[ERROR] PKCS11_CONFIG environment variable not set"
exit 1
}
Write-Host "Using PKCS11 config: $pkcs11Config"
# Try signing with certificate fingerprint first (if available)
$fingerprint = "${{ secrets.SM_CODE_SIGNING_CERT_SHA1_HASH }}"
if ($fingerprint -and $fingerprint -ne "") {
Write-Host "Attempting to sign with certificate fingerprint..."
$output = & smctl sign --fingerprint "$fingerprint" --input "$($file.FullName)" --config-file "$pkcs11Config" --verbose 2>&1
$exitCode = $LASTEXITCODE
} else {
Write-Host "No fingerprint provided, using keypair alias..."
$output = & smctl sign --keypair-alias "${{ secrets.SM_KEYPAIR_ALIAS }}" --input "$($file.FullName)" --config-file "$pkcs11Config" --verbose 2>&1
$exitCode = $LASTEXITCODE
}
Write-Host "Exit code: $exitCode"
Write-Host "Output: $output"
if ($output -match "FAILED" -or $output -match "error" -or $output -match "Error") {
Write-Host "[ERROR] Signing failed for $($file.Name)"
exit 1
}
if ($exitCode -ne 0) {
Write-Host "[ERROR] Failed to sign $($file.Name)"
Write-Host "Full error output:"
Write-Host $output
exit 1
}
$signedCount++
Write-Host "[SUCCESS] Signed: $($file.Name)"
Write-Host ""
}
Write-Host "=== Summary ==="
Write-Host "[SUCCESS] Signed $signedCount/$($filesToSign.Count) files successfully"
- name: Rename artifacts
shell: bash
run: |
mkdir -p ./dist
cd ./frontend/src-tauri/target
# Find and rename artifacts based on platform
if [ "${{ matrix.platform }}" = "windows-latest" ]; then
find . -name "*.exe" -exec cp {} "../../../dist/Stirling-PDF-${{ matrix.name }}.exe" \;
find . -name "*.msi" -exec cp {} "../../../dist/Stirling-PDF-${{ matrix.name }}.msi" \;
elif [ "${{ matrix.platform }}" = "macos-15" ] || [ "${{ matrix.platform }}" = "macos-15-intel" ]; then
find . -name "*.dmg" -exec cp {} "../../../dist/Stirling-PDF-${{ matrix.name }}.dmg" \;
find . -name "*.app" -exec cp -r {} "../../../dist/Stirling-PDF-${{ matrix.name }}.app" \;
else
find . -name "*.deb" -exec cp {} "../../../dist/Stirling-PDF-${{ matrix.name }}.deb" \;
find . -name "*.AppImage" -exec cp {} "../../../dist/Stirling-PDF-${{ matrix.name }}.AppImage" \;
fi
- name: Upload build artifacts
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
with:
name: Stirling-PDF-${{ matrix.name }}
path: ./dist/*
retention-days: 1
if-no-files-found: error
name: stirling${{ matrix.file_suffix }}-binaries
path: |
./binaries/*
sign_verify-portable:
needs: [build-portable, read_versions]
sign_verify_jars:
needs: build-jars
runs-on: ubuntu-latest
if: success()
strategy:
matrix:
disable_security: [true, false]
include:
- disable_security: false
file_suffix: "with-login-"
file_suffix: "-with-login"
- disable_security: true
file_suffix: ""
steps:
@@ -114,188 +508,136 @@ jobs:
with:
egress-policy: audit
- name: Download build artifacts
- name: Download JAR artifacts
uses: actions/download-artifact@634f93cb2916e3fdff6788551b99b062d0335ce0 # v5.0.0
with:
name: stirling-${{ matrix.file_suffix }}binaries
- name: Display structure of downloaded files
run: ls -R
- name: Upload signed artifacts
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
with:
retention-days: 1
if-no-files-found: error
name: stirling-${{ matrix.file_suffix }}signed
path: |
./*
!cosign.*
build-installers:
needs: read_versions
strategy:
matrix:
include:
- os: windows-latest
platform: win-
- os: macos-latest
platform: mac-
# - os: ubuntu-latest
# platform: linux-
runs-on: ${{ matrix.os }}
permissions:
contents: write
steps:
- name: Harden Runner
uses: step-security/harden-runner@f4a75cfd619ee5ce8d5b864b0d183aff3c69b55a # v2.13.1
with:
egress-policy: audit
- uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # v5.0.0
- name: Set up JDK 21
uses: actions/setup-java@dded0888837ed1f317902acf8a20df0ad188d165 # v5.0.0
with:
java-version: "21"
distribution: "temurin"
- uses: gradle/actions/setup-gradle@4d9f0ba0025fe599b4ebab900eb7f3a1d93ef4c2 # v5.0.0
with:
gradle-version: 8.14
# Install Windows dependencies
- name: Install WiX Toolset
if: matrix.os == 'windows-latest'
run: |
curl -L -o wix.exe https://github.com/wixtoolset/wix3/releases/download/wix3141rtm/wix314.exe
.\wix.exe /install /quiet
# Build installer
- name: Build Installer
run: ./gradlew build jpackage -x test --info
env:
DISABLE_ADDITIONAL_FEATURES: true
STIRLING_PDF_DESKTOP_UI: true
BROWSER_OPEN: true
- name: Set up JDK (x86_64)
if: matrix.os == 'macos-latest'
run: |
curl -L -o jdk.tar.gz https://cdn.azul.com/zulu/bin/zulu17.56.15-ca-jdk17.0.14-macosx_x64.tar.gz
mkdir -p zulu17
tar -xzf jdk.tar.gz -C zulu17 --strip-components=1
echo "JAVA_HOME=$PWD/zulu17" >> $GITHUB_ENV
echo "$PWD/zulu17/bin" >> $GITHUB_PATH
- name: Verify JDK architecture
if: matrix.os == 'macos-latest'
run: file $JAVA_HOME/bin/java
- name: Build project and run jpackage (x86_64)
if: matrix.os == 'macos-latest'
run: arch -x86_64 ./gradlew jpackageMacX64
# Rename and collect artifacts based on OS
- name: Prepare artifacts
id: prepare
shell: bash
run: |
ls -lah ./build/jpackage/
mkdir ./binaries
if [ "${{ matrix.os }}" = "windows-latest" ]; then
mv "./build/jpackage/Stirling PDF-${{ needs.read_versions.outputs.version }}.exe" "./binaries/Stirling-PDF-win-installer.exe"
elif [ "${{ matrix.os }}" = "macos-latest" ]; then
mv "./build/jpackage/Stirling PDF-${{ needs.read_versions.outputs.versionMac }}.dmg" "./binaries/Stirling-PDF-mac-installer.dmg"
mv "./build/jpackage/x86_64/Stirling PDF (x86_64)-${{ needs.read_versions.outputs.versionMac }}.dmg" "./binaries/Stirling-PDF-mac-x86_64-installer.dmg"
else
mv "./build/jpackage/stirling-pdf_${{ needs.read_versions.outputs.version }}-1_amd64.deb" "./binaries/Stirling-PDF-linux-installer.deb"
fi
- name: Display structure of downloaded files
run: ls -R ./binaries
- name: Upload build artifacts
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
with:
retention-days: 1
if-no-files-found: error
name: ${{ matrix.platform }}binaries
path: |
./binaries/*
sign_verify:
needs: [read_versions, build-installers]
strategy:
matrix:
include:
- os: windows-latest
platform: win-
- os: macos-latest
platform: mac-
# - os: ubuntu-latest
# platform: linux-
runs-on: ubuntu-latest
steps:
- name: Harden Runner
uses: step-security/harden-runner@f4a75cfd619ee5ce8d5b864b0d183aff3c69b55a # v2.13.1
with:
egress-policy: audit
- name: Download build artifacts
uses: actions/download-artifact@634f93cb2916e3fdff6788551b99b062d0335ce0 # v5.0.0
with:
name: ${{ matrix.platform }}binaries
name: jar${{ matrix.file_suffix }}
- name: Display structure of downloaded files
run: ls -R
- name: Install Cosign
if: matrix.os == 'windows-latest'
uses: sigstore/cosign-installer@d7543c93d881b35a8faa02e8e3605f69b7a1ce62 # v3.10.0
- name: Generate key pair
if: matrix.os == 'windows-latest'
run: cosign generate-key-pair
- name: Sign and generate attestations
if: matrix.os == 'windows-latest'
- name: Sign and generate attestations for JAR
shell: bash
run: |
cosign sign-blob \
--key ./cosign.key \
--yes \
--output-signature ./Stirling-PDF-win-installer.exe.sig \
./Stirling-PDF-win-installer.exe
for file in *.jar; do
if [ -f "$file" ]; then
echo "Signing: $file"
cosign attest-blob \
--predicate - \
--key ./cosign.key \
--yes \
--output-attestation ./Stirling-PDF-win-installer.exe.intoto.jsonl \
./Stirling-PDF-win-installer.exe
# Sign the artifact
cosign sign-blob \
--key ./cosign.key \
--yes \
--output-signature "${file}.sig" \
"$file"
cosign verify-blob \
--key ./cosign.pub \
--signature ./Stirling-PDF-win-installer.exe.sig \
./Stirling-PDF-win-installer.exe
# Generate attestation
cosign attest-blob \
--predicate - \
--key ./cosign.key \
--yes \
--output-attestation "${file}.intoto.jsonl" \
"$file"
# Verify the signature
cosign verify-blob \
--key ./cosign.pub \
--signature "${file}.sig" \
"$file"
echo "✅ Signed and verified: $file"
fi
done
- name: Upload signed JAR artifacts
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
with:
name: jar${{ matrix.file_suffix }}-signed
path: |
*
!cosign.key
!cosign.pub
retention-days: 1
sign_verify:
needs: build
runs-on: ubuntu-latest
if: success()
strategy:
fail-fast: false
matrix:
name: [windows-x86_64, macos-aarch64, macos-x86_64, linux-x86_64]
steps:
- name: Harden Runner
uses: step-security/harden-runner@f4a75cfd619ee5ce8d5b864b0d183aff3c69b55a # v2.13.1
with:
egress-policy: audit
- name: Download build artifacts
uses: actions/download-artifact@634f93cb2916e3fdff6788551b99b062d0335ce0 # v5.0.0
with:
name: Stirling-PDF-${{ matrix.name }}
- name: Display structure of downloaded files
run: ls -R
- name: Install Cosign
uses: sigstore/cosign-installer@d7543c93d881b35a8faa02e8e3605f69b7a1ce62 # v3.10.0
- name: Generate key pair
run: cosign generate-key-pair
- name: Sign and generate attestations
shell: bash
run: |
# Sign all artifacts for this platform
for file in *; do
if [ -f "$file" ] && [[ ! "$file" =~ \.(sig|intoto\.jsonl)$ ]]; then
echo "Signing: $file"
# Sign the artifact
cosign sign-blob \
--key ./cosign.key \
--yes \
--output-signature "${file}.sig" \
"$file"
# Generate attestation
cosign attest-blob \
--predicate - \
--key ./cosign.key \
--yes \
--output-attestation "${file}.intoto.jsonl" \
"$file"
# Verify the signature
cosign verify-blob \
--key ./cosign.pub \
--signature "${file}.sig" \
"$file"
echo "✅ Signed and verified: $file"
fi
done
- name: Upload signed artifacts
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
with:
retention-days: 1
if-no-files-found: error
name: ${{ matrix.platform }}signed
name: Stirling-PDF-${{ matrix.name }}-signed
path: |
./Stirling-PDF-${{ matrix.platform }}installer.*
./Stirling-PDF-${{ matrix.platform }}x86_64-installer.*
!cosign.*
*
!cosign.key
!cosign.pub
retention-days: 1
create-release:
if: github.event_name != 'workflow_dispatch' || github.event.inputs.test_mode != 'true'
needs: [read_versions, sign_verify, sign_verify-portable]
if: (github.event_name == 'workflow_dispatch' && github.event.inputs.test_mode != 'true') || github.event_name == 'release'
needs: [determine-matrix, build, sign_verify, sign_verify_jars]
runs-on: ubuntu-latest
permissions:
contents: write
@@ -305,14 +647,27 @@ jobs:
with:
egress-policy: audit
- name: Download signed artifacts
- name: Download all signed Tauri artifacts
uses: actions/download-artifact@634f93cb2916e3fdff6788551b99b062d0335ce0 # v5.0.0
with:
pattern: Stirling-PDF-*-signed
path: ./artifacts
- name: Download all signed JAR artifacts
uses: actions/download-artifact@634f93cb2916e3fdff6788551b99b062d0335ce0 # v5.0.0
with:
pattern: jar*-signed
path: ./artifacts/jars
- name: Display structure of downloaded files
run: ls -R
- name: Upload binaries, attestations and signatures to Release and create GitHub Release
run: ls -R ./artifacts
- name: Upload binaries, attestations and signatures to Release
uses: softprops/action-gh-release@62c96d0c4e8a889135c1f3a25910db8dbe0e85f7 # v2.3.4
with:
tag_name: v${{ needs.read_versions.outputs.version }}
tag_name: v${{ needs.determine-matrix.outputs.version }}
generate_release_notes: true
files: |
./*signed/*
./artifacts/**/*
draft: false
prerelease: false
@@ -42,7 +42,7 @@ public class WebMvcConfig implements WebMvcConfigurer {
// Tauri v1 uses tauri://localhost, v2 uses http(s)://tauri.localhost
logger.info("Tauri mode detected - enabling CORS for Tauri protocols (v1 and v2)");
registry.addMapping("/**")
.allowedOriginPatterns(
.allowedOrigins(
"tauri://localhost",
"http://tauri.localhost",
"https://tauri.localhost")
@@ -397,8 +397,7 @@ public class ProprietaryUIDataController {
Map<Long, Date> teamLastRequest = new HashMap<>();
for (Object[] result : teamActivities) {
Long teamId = (Long) result[0];
Instant instant = (Instant) result[1];
Date lastActivity = instant != null ? Date.from(instant) : null;
Date lastActivity = (Date) result[1];
teamLastRequest.put(teamId, lastActivity);
}
@@ -442,8 +441,7 @@ public class ProprietaryUIDataController {
Map<String, Date> userLastRequest = new HashMap<>();
for (Object[] result : userSessions) {
String username = (String) result[0];
Instant instant = (Instant) result[1];
Date lastRequest = instant != null ? Date.from(instant) : null;
Date lastRequest = (Date) result[1];
userLastRequest.put(username, lastRequest);
}
@@ -238,12 +238,6 @@ public class CustomLogoutSuccessHandler extends SimpleUrlLogoutSuccessHandler {
path = "errorOAuth=oAuth2AutoCreateDisabled";
} else if (request.getParameter("oAuth2AdminBlockedUser") != null) {
path = "errorOAuth=oAuth2AdminBlockedUser";
} else if (request.getParameter("oAuth2RequiresLicense") != null) {
path = "errorOAuth=oAuth2RequiresLicense";
} else if (request.getParameter("saml2RequiresLicense") != null) {
path = "errorOAuth=saml2RequiresLicense";
} else if (request.getParameter("maxUsersReached") != null) {
path = "errorOAuth=maxUsersReached";
} else if (request.getParameter("userIsDisabled") != null) {
path = "errorOAuth=userIsDisabled";
} else if ((errorMessage = request.getParameter("error")) != null) {
@@ -62,7 +62,6 @@ public class InitialSecuritySetup {
private void initializeUserLicenseSettings() {
licenseSettingsService.initializeGrandfatheredCount();
licenseSettingsService.updateLicenseMaxUsers();
licenseSettingsService.grandfatherExistingOAuthUsers();
}
private void configureJWTSettings() {
@@ -23,7 +23,7 @@ public class PremiumEndpointAspect {
public Object checkPremiumAccess(ProceedingJoinPoint joinPoint) throws Throwable {
if (!runningProOrHigher) {
throw new ResponseStatusException(
HttpStatus.FORBIDDEN, "This endpoint requires a Server or Enterprise license");
HttpStatus.FORBIDDEN, "This endpoint requires a Pro or higher license");
}
return joinPoint.proceed();
}
@@ -84,8 +84,6 @@ public class SecurityConfiguration {
private final GrantedAuthoritiesMapper oAuth2userAuthoritiesMapper;
private final RelyingPartyRegistrationRepository saml2RelyingPartyRegistrations;
private final OpenSaml4AuthenticationRequestResolver saml2AuthenticationRequestResolver;
private final stirling.software.proprietary.service.UserLicenseSettingsService
licenseSettingsService;
public SecurityConfiguration(
PersistentLoginRepository persistentLoginRepository,
@@ -105,9 +103,7 @@ public class SecurityConfiguration {
@Autowired(required = false)
RelyingPartyRegistrationRepository saml2RelyingPartyRegistrations,
@Autowired(required = false)
OpenSaml4AuthenticationRequestResolver saml2AuthenticationRequestResolver,
stirling.software.proprietary.service.UserLicenseSettingsService
licenseSettingsService) {
OpenSaml4AuthenticationRequestResolver saml2AuthenticationRequestResolver) {
this.userDetailsService = userDetailsService;
this.userService = userService;
this.loginEnabledValue = loginEnabledValue;
@@ -124,11 +120,10 @@ public class SecurityConfiguration {
this.oAuth2userAuthoritiesMapper = oAuth2userAuthoritiesMapper;
this.saml2RelyingPartyRegistrations = saml2RelyingPartyRegistrations;
this.saml2AuthenticationRequestResolver = saml2AuthenticationRequestResolver;
this.licenseSettingsService = licenseSettingsService;
}
@Bean
public static PasswordEncoder passwordEncoder() {
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@@ -359,8 +354,7 @@ public class SecurityConfiguration {
loginAttemptService,
securityProperties.getOauth2(),
userService,
jwtService,
licenseSettingsService))
jwtService))
.failureHandler(new CustomOAuth2AuthenticationFailureHandler())
// Add existing Authorities from the database
.userInfoEndpoint(
@@ -401,8 +395,7 @@ public class SecurityConfiguration {
loginAttemptService,
securityProperties.getSaml2(),
userService,
jwtService,
licenseSettingsService))
jwtService))
.failureHandler(
new CustomSaml2AuthenticationFailureHandler())
.authenticationRequestResolver(
@@ -32,8 +32,7 @@ public class EEAppConfig {
@Bean(name = "runningProOrHigher")
@Primary
public boolean runningProOrHigher() {
License license = licenseKeyChecker.getPremiumLicenseEnabledResult();
return license == License.SERVER || license == License.ENTERPRISE;
return licenseKeyChecker.getPremiumLicenseEnabledResult() != License.NORMAL;
}
@Profile("security")
@@ -30,7 +30,7 @@ public class KeygenLicenseVerifier {
public enum License {
NORMAL,
SERVER,
PRO,
ENTERPRISE
}
@@ -76,7 +76,7 @@ public class KeygenLicenseVerifier {
log.info("Detected certificate-based license. Processing...");
boolean isValid = verifyCertificateLicense(licenseKeyOrCert, context);
if (isValid) {
license = context.isEnterpriseLicense ? License.ENTERPRISE : License.SERVER;
license = context.isEnterpriseLicense ? License.ENTERPRISE : License.PRO;
} else {
license = License.NORMAL;
}
@@ -84,7 +84,7 @@ public class KeygenLicenseVerifier {
log.info("Detected JWT-style license key. Processing...");
boolean isValid = verifyJWTLicense(licenseKeyOrCert, context);
if (isValid) {
license = context.isEnterpriseLicense ? License.ENTERPRISE : License.SERVER;
license = context.isEnterpriseLicense ? License.ENTERPRISE : License.PRO;
} else {
license = License.NORMAL;
}
@@ -92,7 +92,7 @@ public class KeygenLicenseVerifier {
log.info("Detected standard license key. Processing...");
boolean isValid = verifyStandardLicense(licenseKeyOrCert, context);
if (isValid) {
license = context.isEnterpriseLicense ? License.ENTERPRISE : License.SERVER;
license = context.isEnterpriseLicense ? License.ENTERPRISE : License.PRO;
} else {
license = License.NORMAL;
}
@@ -261,23 +261,10 @@ public class KeygenLicenseVerifier {
// Extract metadata
JSONObject metadataObj = attributesObj.optJSONObject("metadata");
if (metadataObj != null) {
// Check if this is an old license (no planType) with isEnterprise flag
context.isEnterpriseLicense = metadataObj.optBoolean("isEnterprise", false);
// Extract user count - default based on license type
// Old licenses: Only had isEnterprise flag
// New licenses: Have planType field with "server" or "enterprise"
int users = metadataObj.optInt("users", context.isEnterpriseLicense ? 1 : 0);
// SERVER license (isEnterprise=false, users=0) = unlimited
// ENTERPRISE license (isEnterprise=true, users>0) = limited seats
if (!context.isEnterpriseLicense && users == 0) {
log.info("SERVER license detected with unlimited users");
} else if (context.isEnterpriseLicense && users > 0) {
log.info("ENTERPRISE license allows for {} users", users);
}
int users = metadataObj.optInt("users", 1);
applicationProperties.getPremium().setMaxUsers(users);
log.info("License allows for {} users", users);
context.isEnterpriseLicense = metadataObj.optBoolean("isEnterprise", false);
}
// Check license status if available
@@ -444,31 +431,28 @@ public class KeygenLicenseVerifier {
}
// Extract max users and isEnterprise from policy or metadata
int users = policyObj.optInt("users", 1);
context.isEnterpriseLicense = policyObj.optBoolean("isEnterprise", false);
int users = policyObj.optInt("users", -1);
if (users == -1) {
// Try to get users from metadata if not at policy level
if (users > 0) {
applicationProperties.getPremium().setMaxUsers(users);
log.info("License allows for {} users", users);
} else {
// Try to get users from metadata if present
Object metadataObj = policyObj.opt("metadata");
if (metadataObj instanceof JSONObject metadata) {
context.isEnterpriseLicense =
metadata.optBoolean("isEnterprise", context.isEnterpriseLicense);
users = metadata.optInt("users", context.isEnterpriseLicense ? 1 : 0);
users = metadata.optInt("users", 1);
applicationProperties.getPremium().setMaxUsers(users);
log.info("License allows for {} users (from metadata)", users);
// Check for isEnterprise flag in metadata
context.isEnterpriseLicense = metadata.optBoolean("isEnterprise", false);
} else {
// Default based on license type
users = context.isEnterpriseLicense ? 1 : 0;
// Default value
applicationProperties.getPremium().setMaxUsers(1);
log.info("Using default of 1 user for license");
}
}
// SERVER license (isEnterprise=false, users=0) = unlimited
// ENTERPRISE license (isEnterprise=true, users>0) = limited seats
if (!context.isEnterpriseLicense && users == 0) {
log.info("SERVER license detected with unlimited users");
} else if (context.isEnterpriseLicense && users > 0) {
log.info("ENTERPRISE license allows for {} users", users);
}
applicationProperties.getPremium().setMaxUsers(users);
}
return true;
@@ -600,7 +584,17 @@ public class KeygenLicenseVerifier {
context.maxMachines);
}
// Extract isEnterprise flag first
// Extract user count, default to 1 if not specified
int users =
jsonResponse
.path("data")
.path("attributes")
.path("metadata")
.path("users")
.asInt(1);
applicationProperties.getPremium().setMaxUsers(users);
// Extract isEnterprise flag
context.isEnterpriseLicense =
jsonResponse
.path("data")
@@ -609,24 +603,6 @@ public class KeygenLicenseVerifier {
.path("isEnterprise")
.asBoolean(false);
// Extract user count - default based on license type
int users =
jsonResponse
.path("data")
.path("attributes")
.path("metadata")
.path("users")
.asInt(context.isEnterpriseLicense ? 1 : 0);
// SERVER license (isEnterprise=false, users=0) = unlimited
// ENTERPRISE license (isEnterprise=true, users>0) = limited seats
if (!context.isEnterpriseLicense && users == 0) {
log.info("SERVER license detected with unlimited users");
} else if (context.isEnterpriseLicense && users > 0) {
log.info("ENTERPRISE license allows for {} users", users);
}
applicationProperties.getPremium().setMaxUsers(users);
log.debug(applicationProperties.toString());
} else {
@@ -68,8 +68,8 @@ public class LicenseKeyChecker {
premiumEnabledResult = licenseService.verifyLicense(licenseKey);
if (License.ENTERPRISE == premiumEnabledResult) {
log.info("License key is Enterprise.");
} else if (License.SERVER == premiumEnabledResult) {
log.info("License key is Server.");
} else if (License.PRO == premiumEnabledResult) {
log.info("License key is Pro.");
} else {
log.info("License key is invalid, defaulting to non pro license.");
}
@@ -87,19 +87,6 @@ public class UserController {
.body(Map.of("error", "Password is required"));
}
if (licenseSettingsService.wouldExceedLimit(1)) {
long availableSlots = licenseSettingsService.getAvailableUserSlots();
int maxAllowed = licenseSettingsService.calculateMaxAllowedUsers();
return ResponseEntity.status(HttpStatus.BAD_REQUEST)
.body(
Map.of(
"error",
"Maximum number of users reached. Allowed: "
+ maxAllowed
+ ", Available slots: "
+ availableSlots));
}
Team team = teamRepository.findByName(TeamService.DEFAULT_TEAM_NAME).orElse(null);
User user =
userService.saveUser(
@@ -39,28 +39,4 @@ public interface UserRepository extends JpaRepository<User, Long> {
long countByTeam(Team team);
List<User> findAllByTeam(Team team);
// OAuth grandfathering queries
long countBySsoProviderIsNotNull();
long countByOauthGrandfatheredTrue();
List<User> findAllBySsoProviderIsNotNull();
/**
* Finds all SSO users - those with sso_provider set OR authenticationType is sso/oauth2/saml2.
* This catches V1 users who were created via SSO but never signed in (sso_provider is null).
*/
@Query(
"SELECT u FROM User u WHERE u.ssoProvider IS NOT NULL "
+ "OR LOWER(u.authenticationType) IN ('sso', 'oauth2', 'saml2')")
List<User> findAllSsoUsers();
/**
* Counts all SSO users - those with sso_provider set OR authenticationType is sso/oauth2/saml2.
*/
@Query(
"SELECT COUNT(u) FROM User u WHERE u.ssoProvider IS NOT NULL "
+ "OR LOWER(u.authenticationType) IN ('sso', 'oauth2', 'saml2')")
long countSsoUsers();
}
@@ -71,9 +71,6 @@ public class User implements UserDetails, Serializable {
@Column(name = "sso_provider")
private String ssoProvider;
@Column(name = "oauth_grandfathered")
private Boolean oauthGrandfathered = false;
@OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL, mappedBy = "user")
private Set<Authority> authorities = new HashSet<>();
@@ -138,12 +135,4 @@ public class User implements UserDetails, Serializable {
public boolean hasPassword() {
return this.password != null && !this.password.isEmpty();
}
public boolean isOauthGrandfathered() {
return oauthGrandfathered != null && oauthGrandfathered;
}
public void setOauthGrandfathered(boolean oauthGrandfathered) {
this.oauthGrandfathered = oauthGrandfathered;
}
}
@@ -50,8 +50,6 @@ public class CustomOAuth2AuthenticationSuccessHandler
private final ApplicationProperties.Security.OAUTH2 oauth2Properties;
private final UserService userService;
private final JwtServiceInterface jwtService;
private final stirling.software.proprietary.service.UserLicenseSettingsService
licenseSettingsService;
@Override
@Audited(type = AuditEventType.USER_LOGIN, level = AuditLevel.BASIC)
@@ -68,25 +66,6 @@ public class CustomOAuth2AuthenticationSuccessHandler
username = detailsUser.getUsername();
}
boolean userExists = userService.usernameExistsIgnoreCase(username);
// Check if user is eligible for OAuth (grandfathered or system has paid license)
if (userExists) {
stirling.software.proprietary.security.model.User user =
userService.findByUsernameIgnoreCase(username).orElse(null);
if (user != null && !licenseSettingsService.isOAuthEligible(user)) {
// User is not grandfathered and no paid license - block OAuth login
response.sendRedirect(
request.getContextPath() + "/logout?oAuth2RequiresLicense=true");
return;
}
} else if (!licenseSettingsService.isOAuthEligible(null)) {
// No existing user and no paid license -> block auto creation
response.sendRedirect(request.getContextPath() + "/logout?oAuth2RequiresLicense=true");
return;
}
// Get the saved request
HttpSession session = request.getSession(false);
String contextPath = request.getContextPath();
@@ -112,7 +91,7 @@ public class CustomOAuth2AuthenticationSuccessHandler
.sendRedirect(request, response, "/logout?userIsDisabled=true");
return;
}
if (userExists
if (userService.usernameExistsIgnoreCase(username)
&& userService.hasPassword(username)
&& (!userService.isAuthenticationTypeByUsername(username, SSO)
|| !userService.isAuthenticationTypeByUsername(username, OAUTH2))
@@ -127,10 +106,6 @@ public class CustomOAuth2AuthenticationSuccessHandler
response.sendRedirect(contextPath + "/logout?oAuth2AdminBlockedUser=true");
return;
}
if (!userExists && licenseSettingsService.wouldExceedLimit(1)) {
response.sendRedirect(contextPath + "/logout?maxUsersReached=true");
return;
}
if (principal instanceof OAuth2User oAuth2User) {
// Extract SSO provider information from OAuth2User
String ssoProviderId = oAuth2User.getAttribute("sub"); // OIDC ID
@@ -49,8 +49,6 @@ public class CustomSaml2AuthenticationSuccessHandler
private ApplicationProperties.Security.SAML2 saml2Properties;
private UserService userService;
private final JwtServiceInterface jwtService;
private final stirling.software.proprietary.service.UserLicenseSettingsService
licenseSettingsService;
@Override
@Audited(type = AuditEventType.USER_LOGIN, level = AuditLevel.BASIC)
@@ -65,26 +63,6 @@ public class CustomSaml2AuthenticationSuccessHandler
String username = saml2Principal.name();
log.debug("Authenticated principal found for user: {}", username);
boolean userExists = userService.usernameExistsIgnoreCase(username);
// Check if user is eligible for SAML (grandfathered or system has paid license)
if (userExists) {
stirling.software.proprietary.security.model.User user =
userService.findByUsernameIgnoreCase(username).orElse(null);
if (user != null && !licenseSettingsService.isOAuthEligible(user)) {
// User is not grandfathered and no paid license - block SAML login
response.sendRedirect(
request.getContextPath() + "/logout?saml2RequiresLicense=true");
return;
}
} else if (!licenseSettingsService.isOAuthEligible(null)) {
// No existing user and no paid license -> block auto creation
response.sendRedirect(
request.getContextPath() + "/logout?saml2RequiresLicense=true");
return;
}
HttpSession session = request.getSession(false);
String contextPath = request.getContextPath();
SavedRequest savedRequest =
@@ -118,6 +96,7 @@ public class CustomSaml2AuthenticationSuccessHandler
"Your account has been locked due to too many failed login attempts.");
}
boolean userExists = userService.usernameExistsIgnoreCase(username);
boolean hasPassword = userExists && userService.hasPassword(username);
boolean isSSOUser =
userExists && userService.isAuthenticationTypeByUsername(username, SSO);
@@ -150,10 +129,6 @@ public class CustomSaml2AuthenticationSuccessHandler
contextPath + "/login?errorOAuth=oAuth2AdminBlockedUser");
return;
}
if (!userExists && licenseSettingsService.wouldExceedLimit(1)) {
response.sendRedirect(contextPath + "/logout?maxUsersReached=true");
return;
}
// Extract SSO provider information from SAML2 assertion
String ssoProviderId = saml2Principal.nameId();
@@ -734,48 +734,4 @@ public class UserService implements UserServiceInterface {
public void saveAll(List<User> users) {
userRepository.saveAll(users);
}
/**
* Counts the number of OAuth/SAML users. Includes users with sso_provider set OR
* authenticationType is sso/oauth2/saml2 (catches V1 users who never signed in).
*
* @return Count of OAuth users
*/
public long countOAuthUsers() {
return userRepository.countSsoUsers();
}
/**
* Counts the number of OAuth users who are grandfathered.
*
* @return Count of grandfathered OAuth users
*/
public long countGrandfatheredOAuthUsers() {
return userRepository.countByOauthGrandfatheredTrue();
}
/**
* Grandfathers all existing OAuth/SAML users. This marks all users with an SSO provider as
* grandfathered, allowing them to keep OAuth access even without a paid license.
*
* @return Number of users updated
*/
@Transactional
public int grandfatherAllOAuthUsers() {
List<User> ssoUsers = userRepository.findAllSsoUsers();
int updated = 0;
for (User user : ssoUsers) {
if (!user.isOauthGrandfathered()) {
user.setOauthGrandfathered(true);
updated++;
}
}
if (updated > 0) {
userRepository.saveAll(ssoUsers);
}
return updated;
}
}
@@ -69,7 +69,7 @@ public class ServerCertificateService implements ServerCertificateServiceInterfa
private boolean hasProOrEnterpriseAccess() {
License license = licenseKeyChecker.getPremiumLicenseEnabledResult();
return license == License.SERVER || license == License.ENTERPRISE;
return license == License.PRO || license == License.ENTERPRISE;
}
public boolean isEnabled() {
@@ -10,7 +10,6 @@ import java.util.UUID;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@@ -19,8 +18,6 @@ import lombok.extern.slf4j.Slf4j;
import stirling.software.common.model.ApplicationProperties;
import stirling.software.proprietary.model.UserLicenseSettings;
import stirling.software.proprietary.security.configuration.ee.KeygenLicenseVerifier.License;
import stirling.software.proprietary.security.configuration.ee.LicenseKeyChecker;
import stirling.software.proprietary.security.repository.UserLicenseSettingsRepository;
import stirling.software.proprietary.security.service.UserService;
@@ -48,7 +45,6 @@ public class UserLicenseSettingsService {
private final UserLicenseSettingsRepository settingsRepository;
private final UserService userService;
private final ApplicationProperties applicationProperties;
private final ObjectProvider<LicenseKeyChecker> licenseKeyChecker;
/**
* Gets the current user license settings, creating them if they don't exist.
@@ -155,7 +151,7 @@ public class UserLicenseSettingsService {
UserLicenseSettings settings = getOrCreateSettings();
int licenseMaxUsers = 0;
if (hasPaidLicense()) {
if (applicationProperties.getPremium().isEnabled()) {
licenseMaxUsers = applicationProperties.getPremium().getMaxUsers();
}
@@ -166,40 +162,6 @@ public class UserLicenseSettingsService {
}
}
/**
* Grandfathers existing OAuth users on first run. This is a one-time migration that marks all
* existing OAuth/SAML users as grandfathered, allowing them to keep OAuth access even without a
* paid license.
*
* <p>New users created after this migration will NOT be grandfathered and will require a paid
* license to use OAuth.
*/
@Transactional
public void grandfatherExistingOAuthUsers() {
UserLicenseSettings settings = getOrCreateSettings();
// Check if we've already run this migration
if (settings.getId() != null && settings.isGrandfatheringLocked()) {
// Migration should happen at the same time as grandfathering is locked
long oauthUsersCount = userService.countOAuthUsers();
long grandfatheredCount = userService.countGrandfatheredOAuthUsers();
if (oauthUsersCount > 0 && grandfatheredCount == 0) {
// We have OAuth users but none are grandfathered - this is first run after upgrade
int updated = userService.grandfatherAllOAuthUsers();
log.warn(
"OAuth GRANDFATHERING: Marked {} existing OAuth/SAML users as grandfathered. "
+ "They will retain OAuth access even without a paid license. "
+ "New users will require a paid license for OAuth.",
updated);
} else if (grandfatheredCount > 0) {
log.debug(
"OAuth grandfathering already completed: {} users grandfathered",
grandfatheredCount);
}
}
}
/**
* Validates and enforces the integrity of license settings. This ensures that even if someone
* manually modifies the database, the grandfathering rules are still enforced.
@@ -279,15 +241,12 @@ public class UserLicenseSettingsService {
* <p>Logic:
*
* <ul>
* <li>Grandfathered limit = max(5, existing user count at V1→V2 migration)
* <li>No license: Uses grandfathered limit only
* <li>SERVER license (maxUsers=0): Unlimited users (Integer.MAX_VALUE)
* <li>ENTERPRISE license (maxUsers>0): License seats only (NO grandfathering added)
* <li>Grandfathered limit = max(5, existing user count at initialization)
* <li>If premium enabled: total limit = grandfathered limit + license maxUsers
* <li>If premium disabled: total limit = grandfathered limit
* </ul>
*
* <p>IMPORTANT: Paid licenses REPLACE the limit, they don't add to grandfathering.
*
* @return Maximum number of users allowed (Integer.MAX_VALUE for unlimited)
* @return Maximum number of users allowed
*/
public int calculateMaxAllowedUsers() {
validateSettingsIntegrity();
@@ -300,52 +259,20 @@ public class UserLicenseSettingsService {
grandfatheredLimit = DEFAULT_USER_LIMIT;
}
// No license: use grandfathered limit
if (!hasPaidLicense()) {
log.debug("No license: using grandfathered limit of {}", grandfatheredLimit);
return grandfatheredLimit;
int totalLimit = grandfatheredLimit;
if (applicationProperties.getPremium().isEnabled()) {
totalLimit = grandfatheredLimit + settings.getLicenseMaxUsers();
}
int licenseMaxUsers = settings.getLicenseMaxUsers();
// SERVER license (maxUsers=0): unlimited users
if (licenseMaxUsers == 0) {
log.debug("SERVER license: unlimited users allowed");
return Integer.MAX_VALUE;
}
// ENTERPRISE license (maxUsers>0): license seats only (replaces grandfathering)
log.debug(
"ENTERPRISE license: {} seats (grandfathered {} not added)",
licenseMaxUsers,
grandfatheredLimit);
return licenseMaxUsers;
}
"Calculated max allowed users: {} (grandfathered: {}, license: {}, premium enabled: {})",
totalLimit,
grandfatheredLimit,
settings.getLicenseMaxUsers(),
applicationProperties.getPremium().isEnabled());
/**
* Checks if a user is eligible to use OAuth/SAML authentication.
*
* <p>A user is eligible if:
*
* <ul>
* <li>They are grandfathered for OAuth (existing user before policy change), OR
* <li>The system has an ENTERPRISE license (SSO is enterprise-only)
* </ul>
*
* @param user The user to check
* @return true if the user can use OAuth/SAML
*/
public boolean isOAuthEligible(stirling.software.proprietary.security.model.User user) {
// Grandfathered users always have OAuth access
if (user != null && user.isOauthGrandfathered()) {
log.debug("User {} is grandfathered for OAuth", user.getUsername());
return true;
}
// Users can use OAuth/SAML only if system has ENTERPRISE license
boolean hasEnterpriseLicense = hasEnterpriseLicense();
log.debug("OAuth eligibility check: hasEnterpriseLicense={}", hasEnterpriseLicense);
return hasEnterpriseLicense;
return totalLimit;
}
/**
@@ -481,28 +408,4 @@ public class UserLicenseSettingsService {
throw new IllegalStateException("Invalid key for grandfathered user signature", e);
}
}
private boolean hasPaidLicense() {
LicenseKeyChecker checker = licenseKeyChecker.getIfAvailable();
if (checker == null) {
return false;
}
License license = checker.getPremiumLicenseEnabledResult();
return license == License.SERVER || license == License.ENTERPRISE;
}
/**
* Checks if the system has an ENTERPRISE license. Used for enterprise-only features like SSO
* (OAuth/SAML).
*
* @return true if ENTERPRISE license is active
*/
private boolean hasEnterpriseLicense() {
LicenseKeyChecker checker = licenseKeyChecker.getIfAvailable();
if (checker == null) {
return false;
}
License license = checker.getPremiumLicenseEnabledResult();
return license == License.ENTERPRISE;
}
}
@@ -103,9 +103,6 @@ class CustomLogoutSuccessHandlerTest {
when(request.getParameter("errorOAuth")).thenReturn(null);
when(request.getParameter("oAuth2AutoCreateDisabled")).thenReturn(null);
when(request.getParameter("oAuth2AdminBlockedUser")).thenReturn(null);
when(request.getParameter("oAuth2RequiresLicense")).thenReturn(null);
when(request.getParameter("saml2RequiresLicense")).thenReturn(null);
when(request.getParameter("maxUsersReached")).thenReturn(null);
when(request.getParameter(error)).thenReturn("true");
when(request.getScheme()).thenReturn("http");
when(request.getServerName()).thenReturn("localhost");
@@ -211,9 +208,6 @@ class CustomLogoutSuccessHandlerTest {
when(request.getParameter("errorOAuth")).thenReturn(null);
when(request.getParameter("oAuth2AutoCreateDisabled")).thenReturn(null);
when(request.getParameter("oAuth2AdminBlockedUser")).thenReturn(null);
when(request.getParameter("oAuth2RequiresLicense")).thenReturn(null);
when(request.getParameter("saml2RequiresLicense")).thenReturn(null);
when(request.getParameter("maxUsersReached")).thenReturn(null);
when(request.getParameter("userIsDisabled")).thenReturn(null);
when(request.getParameter("error")).thenReturn("!@$!@£" + error + "£$%^*$");
when(request.getScheme()).thenReturn("http");
@@ -243,9 +237,6 @@ class CustomLogoutSuccessHandlerTest {
when(request.getParameter("errorOAuth")).thenReturn(null);
when(request.getParameter("oAuth2AutoCreateDisabled")).thenReturn(null);
when(request.getParameter("oAuth2AdminBlockedUser")).thenReturn(null);
when(request.getParameter("oAuth2RequiresLicense")).thenReturn(null);
when(request.getParameter("saml2RequiresLicense")).thenReturn(null);
when(request.getParameter("maxUsersReached")).thenReturn(null);
when(request.getParameter("userIsDisabled")).thenReturn(null);
when(request.getParameter("error")).thenReturn(null);
when(request.getParameter(error)).thenReturn("true");
@@ -44,13 +44,13 @@ class LicenseKeyCheckerTest {
ApplicationProperties props = new ApplicationProperties();
props.getPremium().setEnabled(true);
props.getPremium().setKey("abc");
when(verifier.verifyLicense("abc")).thenReturn(License.SERVER);
when(verifier.verifyLicense("abc")).thenReturn(License.PRO);
LicenseKeyChecker checker =
new LicenseKeyChecker(verifier, props, userLicenseSettingsService);
checker.init();
assertEquals(License.SERVER, checker.getPremiumLicenseEnabledResult());
assertEquals(License.PRO, checker.getPremiumLicenseEnabledResult());
verify(verifier).verifyLicense("abc");
}
@@ -1,201 +0,0 @@
package stirling.software.proprietary.service;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.when;
import java.util.Optional;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.mockito.junit.jupiter.MockitoSettings;
import org.mockito.quality.Strictness;
import org.springframework.beans.factory.ObjectProvider;
import stirling.software.common.model.ApplicationProperties;
import stirling.software.proprietary.model.UserLicenseSettings;
import stirling.software.proprietary.security.configuration.ee.KeygenLicenseVerifier.License;
import stirling.software.proprietary.security.configuration.ee.LicenseKeyChecker;
import stirling.software.proprietary.security.repository.UserLicenseSettingsRepository;
import stirling.software.proprietary.security.service.UserService;
@ExtendWith(MockitoExtension.class)
@MockitoSettings(strictness = Strictness.LENIENT)
class UserLicenseSettingsServiceTest {
@Mock private UserLicenseSettingsRepository settingsRepository;
@Mock private UserService userService;
@Mock private ApplicationProperties applicationProperties;
@Mock private ApplicationProperties.Premium premium;
@Mock private LicenseKeyChecker licenseKeyChecker;
@Mock private ObjectProvider<LicenseKeyChecker> licenseKeyCheckerProvider;
private UserLicenseSettingsService service;
private UserLicenseSettings mockSettings;
@BeforeEach
void setUp() {
mockSettings = new UserLicenseSettings();
mockSettings.setId(1L);
mockSettings.setGrandfatheredUserCount(80);
mockSettings.setGrandfatheringLocked(true);
mockSettings.setIntegritySalt("test-salt");
mockSettings.setGrandfatheredUserSignature("80:test-signature");
when(applicationProperties.getPremium()).thenReturn(premium);
when(settingsRepository.findSettings()).thenReturn(Optional.of(mockSettings));
when(userService.getTotalUsersCount()).thenReturn(80L);
when(settingsRepository.save(any(UserLicenseSettings.class)))
.thenAnswer(invocation -> invocation.getArgument(0));
when(licenseKeyChecker.getPremiumLicenseEnabledResult()).thenReturn(License.NORMAL);
when(licenseKeyCheckerProvider.getIfAvailable()).thenReturn(licenseKeyChecker);
// Create service with overridden validateSettingsIntegrity to bypass signature validation
service =
new UserLicenseSettingsService(
settingsRepository,
userService,
applicationProperties,
licenseKeyCheckerProvider) {
@Override
public void validateSettingsIntegrity() {
// Override to do nothing in tests - avoid HMAC signature validation
// complexity
}
};
}
@Test
void noLicense_returnsGrandfatheredLimit() {
// No license active
when(premium.isEnabled()).thenReturn(false);
when(licenseKeyChecker.getPremiumLicenseEnabledResult()).thenReturn(License.NORMAL);
int result = service.calculateMaxAllowedUsers();
assertEquals(80, result, "Should return grandfathered user count when no license");
}
@Test
void serverLicense_returnsUnlimited() {
// SERVER license with users=0
when(premium.isEnabled()).thenReturn(true);
when(licenseKeyChecker.getPremiumLicenseEnabledResult()).thenReturn(License.SERVER);
mockSettings.setLicenseMaxUsers(0);
int result = service.calculateMaxAllowedUsers();
assertEquals(Integer.MAX_VALUE, result, "SERVER license should return unlimited users");
}
@Test
void enterpriseLicense_returnsLicenseSeatsOnly() {
// ENTERPRISE license with 5 seats
when(premium.isEnabled()).thenReturn(true);
when(licenseKeyChecker.getPremiumLicenseEnabledResult()).thenReturn(License.ENTERPRISE);
mockSettings.setLicenseMaxUsers(5);
int result = service.calculateMaxAllowedUsers();
assertEquals(
5,
result,
"ENTERPRISE license should return license seats only (NOT grandfathered + seats)");
}
@Test
void enterpriseLicense_ignoresGrandfathering() {
// ENTERPRISE with 20 seats, grandfathered was 80
when(premium.isEnabled()).thenReturn(true);
when(licenseKeyChecker.getPremiumLicenseEnabledResult()).thenReturn(License.ENTERPRISE);
mockSettings.setLicenseMaxUsers(20);
mockSettings.setGrandfatheredUserCount(80); // This should be ignored
int result = service.calculateMaxAllowedUsers();
assertEquals(
20,
result,
"ENTERPRISE license should ignore grandfathering and use license seats only");
}
@Test
void freshInstall_noLicense_returnsFive() {
// Fresh install with default 5 users grandfathered
mockSettings.setGrandfatheredUserCount(5);
when(premium.isEnabled()).thenReturn(false);
int result = service.calculateMaxAllowedUsers();
assertEquals(5, result, "Fresh install with no license should return 5 users");
}
@Test
void freshInstall_serverLicense_returnsUnlimited() {
// Fresh install with SERVER license
mockSettings.setGrandfatheredUserCount(5);
when(premium.isEnabled()).thenReturn(true);
when(licenseKeyChecker.getPremiumLicenseEnabledResult()).thenReturn(License.SERVER);
mockSettings.setLicenseMaxUsers(0);
int result = service.calculateMaxAllowedUsers();
assertEquals(
Integer.MAX_VALUE,
result,
"Fresh install with SERVER license should return unlimited");
}
@Test
void freshInstall_enterpriseLicense_returnsLicenseSeats() {
// Fresh install with ENTERPRISE 10 seats
mockSettings.setGrandfatheredUserCount(5);
when(premium.isEnabled()).thenReturn(true);
when(licenseKeyChecker.getPremiumLicenseEnabledResult()).thenReturn(License.ENTERPRISE);
mockSettings.setLicenseMaxUsers(10);
int result = service.calculateMaxAllowedUsers();
assertEquals(
10, result, "Fresh install with ENTERPRISE license should return license seats");
}
@Test
void v1MigrationWith80Users_noLicense_returns80() {
// V1→V2 migration with 80 users, no paid license
mockSettings.setGrandfatheredUserCount(80);
when(premium.isEnabled()).thenReturn(false);
int result = service.calculateMaxAllowedUsers();
assertEquals(80, result, "V1→V2 migration should preserve 80 grandfathered users");
}
@Test
void v1MigrationWith80Users_thenEnterpriseWith5Seats_returns5() {
// V1→V2 with 80 users, then buy ENTERPRISE 5 seats
mockSettings.setGrandfatheredUserCount(80);
when(premium.isEnabled()).thenReturn(true);
when(licenseKeyChecker.getPremiumLicenseEnabledResult()).thenReturn(License.ENTERPRISE);
mockSettings.setLicenseMaxUsers(5);
int result = service.calculateMaxAllowedUsers();
assertEquals(
5, result, "ENTERPRISE 5 seats should override grandfathered 80 users (not 85)");
}
@Test
void zeroGrandfathered_fallsBackToDefault() {
// Edge case: grandfathered is 0 (should not happen)
mockSettings.setGrandfatheredUserCount(0);
when(premium.isEnabled()).thenReturn(false);
int result = service.calculateMaxAllowedUsers();
assertEquals(5, result, "Should fall back to default 5 users if grandfathered is 0");
}
}
+5 -18
View File
@@ -40,11 +40,6 @@
"discardChanges": "Discard & Leave",
"applyAndContinue": "Save & Leave",
"exportAndContinue": "Export & Continue",
"backendStartup": {
"notFoundTitle": "Backend not found",
"retry": "Retry",
"unreachable": "The application cannot currently connect to the backend. Verify the backend status and network connectivity, then try again."
},
"zipWarning": {
"title": "Large ZIP File",
"message": "This ZIP contains {{count}} files. Extract anyway?",
@@ -68,7 +63,7 @@
},
"settingsOpened": {
"title": "Settings Opened",
"message": "In Windows Settings, search for 'PDF' and select Stirling PDF as your default app"
"message": "Please select Stirling PDF in your system settings"
},
"error": {
"title": "Error",
@@ -3478,9 +3473,6 @@
"ssoSignIn": "Login via Single Sign-on",
"oAuth2AutoCreateDisabled": "OAUTH2 Auto-Create User Disabled",
"oAuth2AdminBlockedUser": "Registration or logging in of non-registered users is currently blocked. Please contact the administrator.",
"oAuth2RequiresLicense": "OAuth/SSO login requires a paid license (Server or Enterprise). Please contact the administrator to upgrade your plan.",
"saml2RequiresLicense": "SAML login requires a paid license (Server or Enterprise). Please contact the administrator to upgrade your plan.",
"maxUsersReached": "Maximum number of users reached for your current license. Please contact the administrator to upgrade your plan or add more seats.",
"oauth2RequestNotFound": "Authorization request not found",
"oauth2InvalidUserInfoResponse": "Invalid User Info Response",
"oauth2invalidRequest": "Invalid Request",
@@ -3895,17 +3887,14 @@
"actualSize": "Actual Size"
},
"viewer": {
"cannotPreviewFile": "Cannot Preview File",
"dualPageView": "Dual Page View",
"firstPage": "First Page",
"lastPage": "Last Page",
"nextPage": "Next Page",
"onlyPdfSupported": "The viewer only supports PDF files. This file appears to be a different format.",
"previousPage": "Previous Page",
"singlePageView": "Single Page View",
"unknownFile": "Unknown file",
"nextPage": "Next Page",
"zoomIn": "Zoom In",
"zoomOut": "Zoom Out"
"zoomOut": "Zoom Out",
"singlePageView": "Single Page View",
"dualPageView": "Dual Page View"
},
"rightRail": {
"closeSelected": "Close Selected Files",
@@ -4697,9 +4686,7 @@
"download": "Download",
"delete": "Delete",
"unsupported": "Unsupported",
"active": "Active",
"addToUpload": "Add to Upload",
"closeFile": "Close File",
"deleteAll": "Delete All",
"loadingFiles": "Loading files...",
"noFiles": "No files available",
+14 -79
View File
@@ -4250,7 +4250,6 @@ dependencies = [
"tokio",
"url",
"urlencoding",
"windows 0.58.0",
]
[[package]]
@@ -4438,7 +4437,7 @@ dependencies = [
"tao-macros",
"unicode-segmentation",
"url",
"windows 0.61.3",
"windows",
"windows-core 0.61.2",
"windows-version",
"x11-dl",
@@ -4515,7 +4514,7 @@ dependencies = [
"webkit2gtk",
"webview2-com",
"window-vibrancy",
"windows 0.61.3",
"windows",
]
[[package]]
@@ -4684,7 +4683,7 @@ dependencies = [
"tauri-plugin",
"thiserror 2.0.17",
"url",
"windows 0.61.3",
"windows",
"zbus",
]
@@ -4762,7 +4761,7 @@ dependencies = [
"url",
"webkit2gtk",
"webview2-com",
"windows 0.61.3",
"windows",
]
[[package]]
@@ -4788,7 +4787,7 @@ dependencies = [
"url",
"webkit2gtk",
"webview2-com",
"windows 0.61.3",
"windows",
"wry",
]
@@ -5625,10 +5624,10 @@ checksum = "d4ba622a989277ef3886dd5afb3e280e3dd6d974b766118950a08f8f678ad6a4"
dependencies = [
"webview2-com-macros",
"webview2-com-sys",
"windows 0.61.3",
"windows",
"windows-core 0.61.2",
"windows-implement 0.60.2",
"windows-interface 0.59.3",
"windows-implement",
"windows-interface",
]
[[package]]
@@ -5649,7 +5648,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "36695906a1b53a3bf5c4289621efedac12b73eeb0b89e7e1a89b517302d5d75c"
dependencies = [
"thiserror 2.0.17",
"windows 0.61.3",
"windows",
"windows-core 0.61.2",
]
@@ -5699,16 +5698,6 @@ dependencies = [
"windows-version",
]
[[package]]
name = "windows"
version = "0.58.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dd04d41d93c4992d421894c18c8b43496aa748dd4c081bac0dc93eb0489272b6"
dependencies = [
"windows-core 0.58.0",
"windows-targets 0.52.6",
]
[[package]]
name = "windows"
version = "0.61.3"
@@ -5731,27 +5720,14 @@ dependencies = [
"windows-core 0.61.2",
]
[[package]]
name = "windows-core"
version = "0.58.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6ba6d44ec8c2591c134257ce647b7ea6b20335bf6379a27dac5f1641fcf59f99"
dependencies = [
"windows-implement 0.58.0",
"windows-interface 0.58.0",
"windows-result 0.2.0",
"windows-strings 0.1.0",
"windows-targets 0.52.6",
]
[[package]]
name = "windows-core"
version = "0.61.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c0fdd3ddb90610c7638aa2b3a3ab2904fb9e5cdbecc643ddb3647212781c4ae3"
dependencies = [
"windows-implement 0.60.2",
"windows-interface 0.59.3",
"windows-implement",
"windows-interface",
"windows-link 0.1.3",
"windows-result 0.3.4",
"windows-strings 0.4.2",
@@ -5763,8 +5739,8 @@ version = "0.62.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb"
dependencies = [
"windows-implement 0.60.2",
"windows-interface 0.59.3",
"windows-implement",
"windows-interface",
"windows-link 0.2.1",
"windows-result 0.4.1",
"windows-strings 0.5.1",
@@ -5781,17 +5757,6 @@ dependencies = [
"windows-threading",
]
[[package]]
name = "windows-implement"
version = "0.58.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2bbd5b46c938e506ecbce286b6628a02171d56153ba733b6c741fc627ec9579b"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.108",
]
[[package]]
name = "windows-implement"
version = "0.60.2"
@@ -5803,17 +5768,6 @@ dependencies = [
"syn 2.0.108",
]
[[package]]
name = "windows-interface"
version = "0.58.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "053c4c462dc91d3b1504c6fe5a726dd15e216ba718e84a0e46a88fbe5ded3515"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.108",
]
[[package]]
name = "windows-interface"
version = "0.59.3"
@@ -5858,15 +5812,6 @@ dependencies = [
"windows-strings 0.4.2",
]
[[package]]
name = "windows-result"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1d1043d8214f791817bab27572aaa8af63732e11bf84aa21a45a78d6c317ae0e"
dependencies = [
"windows-targets 0.52.6",
]
[[package]]
name = "windows-result"
version = "0.3.4"
@@ -5885,16 +5830,6 @@ dependencies = [
"windows-link 0.2.1",
]
[[package]]
name = "windows-strings"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4cd9b125c486025df0eabcb585e62173c6c9eddcec5d117d3b6e8c30e2ee4d10"
dependencies = [
"windows-result 0.2.0",
"windows-targets 0.52.6",
]
[[package]]
name = "windows-strings"
version = "0.4.2"
@@ -6317,7 +6252,7 @@ dependencies = [
"webkit2gtk",
"webkit2gtk-sys",
"webview2-com",
"windows 0.61.3",
"windows",
"windows-core 0.61.2",
"windows-version",
"x11-dl",
-8
View File
@@ -45,11 +45,3 @@ rand = "0.8"
[target.'cfg(target_os = "macos")'.dependencies]
core-foundation = "0.10"
core-services = "1.0"
[target.'cfg(target_os = "windows")'.dependencies]
windows = { version = "0.58", features = [
"Win32_Foundation",
"Win32_System_Com",
"Win32_UI_Shell",
"Win32_System_ApplicationInstallationAndServicing",
] }
+35 -66
View File
@@ -1,5 +1,8 @@
use crate::utils::add_log;
#[cfg(any(target_os = "windows", target_os = "linux"))]
use std::process::Command;
/// Check if Stirling PDF is the default PDF handler
#[tauri::command]
pub fn is_default_pdf_handler() -> Result<bool, String> {
@@ -48,80 +51,50 @@ pub fn set_as_default_pdf_handler() -> Result<String, String> {
#[cfg(target_os = "windows")]
fn check_default_windows() -> Result<bool, String> {
use windows::core::HSTRING;
use windows::Win32::Foundation::RPC_E_CHANGED_MODE;
use windows::Win32::System::Com::{
CoCreateInstance, CoInitializeEx, CoUninitialize, CLSCTX_INPROC_SERVER,
COINIT_APARTMENTTHREADED,
};
use windows::Win32::UI::Shell::{
IApplicationAssociationRegistration, ApplicationAssociationRegistration,
ASSOCIATIONTYPE, ASSOCIATIONLEVEL,
};
use std::os::windows::process::CommandExt;
const CREATE_NO_WINDOW: u32 = 0x08000000;
unsafe {
// Initialize COM for this thread
let hr = CoInitializeEx(None, COINIT_APARTMENTTHREADED);
// RPC_E_CHANGED_MODE means COM is already initialized, which is fine
if hr.is_err() && hr != RPC_E_CHANGED_MODE {
return Err(format!("Failed to initialize COM: {:?}", hr));
}
// Query the default handler for .pdf extension
let output = Command::new("cmd")
.args(["/C", "assoc .pdf"])
.creation_flags(CREATE_NO_WINDOW)
.output()
.map_err(|e| format!("Failed to check default app: {}", e))?;
let result = (|| -> Result<bool, String> {
// Create the IApplicationAssociationRegistration instance
let reg: IApplicationAssociationRegistration =
CoCreateInstance(&ApplicationAssociationRegistration, None, CLSCTX_INPROC_SERVER)
.map_err(|e| format!("Failed to create COM instance: {}", e))?;
let assoc = String::from_utf8_lossy(&output.stdout);
add_log(format!("Windows PDF association: {}", assoc.trim()));
// Query the current default handler for .pdf extension
let extension = HSTRING::from(".pdf");
// Get the ProgID for .pdf files
if let Some(prog_id) = assoc.trim().strip_prefix(".pdf=") {
// Query what application handles this ProgID
let output = Command::new("cmd")
.args(["/C", &format!("ftype {}", prog_id)])
.creation_flags(CREATE_NO_WINDOW)
.output()
.map_err(|e| format!("Failed to query file type: {}", e))?;
let default_app = reg.QueryCurrentDefault(
&extension,
ASSOCIATIONTYPE(0), // AT_FILEEXTENSION
ASSOCIATIONLEVEL(1), // AL_EFFECTIVE - gets the effective default (user or machine level)
)
.map_err(|e| format!("Failed to query current default: {}", e))?;
let ftype = String::from_utf8_lossy(&output.stdout);
add_log(format!("Windows file type: {}", ftype.trim()));
// Convert PWSTR to String
let default_str = default_app.to_string()
.map_err(|e| format!("Failed to convert default app string: {}", e))?;
add_log(format!("Windows PDF handler ProgID: {}", default_str));
// Check if it contains "Stirling" (case-insensitive)
// Note: This checks the ProgID registered by the installer
let is_default = default_str.to_lowercase().contains("stirling");
Ok(is_default)
})();
// Clean up COM
CoUninitialize();
result
// Check if it contains "Stirling" or our app name
let is_default = ftype.to_lowercase().contains("stirling");
Ok(is_default)
} else {
Ok(false)
}
}
#[cfg(target_os = "windows")]
fn set_default_windows() -> Result<String, String> {
use std::process::Command;
// Windows 10+ approach: Open Settings app directly to default apps
// This is more reliable than COM APIs which require pre-registration
// ms-settings:defaultapps opens the default apps settings page
let result = Command::new("cmd")
// On Windows 10+, we need to open the Default Apps settings
// as programmatic setting requires a signed installer
Command::new("cmd")
.args(["/C", "start", "ms-settings:defaultapps"])
.output()
.map_err(|e| format!("Failed to open Windows Settings: {}", e))?;
.spawn()
.map_err(|e| format!("Failed to open default apps settings: {}", e))?;
if result.status.success() {
add_log("Opened Windows default apps settings".to_string());
Ok("opened_dialog".to_string())
} else {
let error = String::from_utf8_lossy(&result.stderr);
add_log(format!("Failed to open settings: {}", error));
Err(format!("Failed to open default apps settings: {}", error))
}
add_log("Opened Windows Default Apps settings".to_string());
Ok("opened_settings".to_string())
}
// ============================================================================
@@ -211,8 +184,6 @@ fn set_default_macos() -> Result<String, String> {
#[cfg(target_os = "linux")]
fn check_default_linux() -> Result<bool, String> {
use std::process::Command;
// Use xdg-mime to check the default application for PDF files
let output = Command::new("xdg-mime")
.args(["query", "default", "application/pdf"])
@@ -229,8 +200,6 @@ fn check_default_linux() -> Result<bool, String> {
#[cfg(target_os = "linux")]
fn set_default_linux() -> Result<String, String> {
use std::process::Command;
// Use xdg-mime to set the default application for PDF files
let result = Command::new("xdg-mime")
.args(["default", "stirling-pdf.desktop", "application/pdf"])
@@ -12,7 +12,6 @@ import { FileManagerProvider } from '@app/contexts/FileManagerContext';
import { Z_INDEX_FILE_MANAGER_MODAL } from '@app/styles/zIndex';
import { isGoogleDriveConfigured } from '@app/services/googleDrivePickerService';
import { loadScript } from '@app/utils/scriptLoader';
import { useAllFiles } from '@app/contexts/FileContext';
interface FileManagerProps {
selectedTool?: Tool | null;
@@ -26,9 +25,6 @@ const FileManager: React.FC<FileManagerProps> = ({ selectedTool }) => {
const { loadRecentFiles, handleRemoveFile, loading } = useFileManager();
// Get active file IDs from FileContext to show which files are already loaded
const { fileIds: activeFileIds } = useAllFiles();
// File management handlers
const isFileSupported = useCallback((fileName: string) => {
if (!selectedTool?.supportedFormats) return true;
@@ -179,7 +175,6 @@ const FileManager: React.FC<FileManagerProps> = ({ selectedTool }) => {
modalHeight={modalHeight}
refreshRecentFiles={refreshRecentFiles}
isLoading={loading}
activeFileIds={activeFileIds}
>
{isMobile ? <MobileLayout /> : <DesktopLayout />}
</FileManagerProvider>
@@ -30,7 +30,6 @@ const FileListArea: React.FC<FileListAreaProps> = ({
onDownloadSingle,
isFileSupported,
isLoading,
activeFileIds,
} = useFileManagerContext();
const { t } = useTranslation();
@@ -56,7 +55,6 @@ const FileListArea: React.FC<FileListAreaProps> = ({
// All files in filteredFiles are now leaf files only
const historyFiles = loadedHistoryFiles.get(file.id) || [];
const isExpanded = expandedFileIds.has(file.id);
const isActive = activeFileIds.includes(file.id);
return (
<React.Fragment key={file.id}>
@@ -70,7 +68,6 @@ const FileListArea: React.FC<FileListAreaProps> = ({
onDoubleClick={() => onFileDoubleClick(file)}
isHistoryFile={false} // All files here are leaf files
isLatestVersion={true} // All files here are the latest versions
isActive={isActive}
/>
<FileHistoryGroup
@@ -6,7 +6,6 @@ import DownloadIcon from '@mui/icons-material/Download';
import HistoryIcon from '@mui/icons-material/History';
import RestoreIcon from '@mui/icons-material/Restore';
import UnarchiveIcon from '@mui/icons-material/Unarchive';
import CloseIcon from '@mui/icons-material/Close';
import { useTranslation } from 'react-i18next';
import { getFileSize, getFileDate } from '@app/utils/fileUtils';
import { FileId, StirlingFileStub } from '@app/types/fileContext';
@@ -15,7 +14,6 @@ import { zipFileService } from '@app/services/zipFileService';
import ToolChain from '@app/components/shared/ToolChain';
import { Z_INDEX_OVER_FILE_MANAGER_MODAL } from '@app/styles/zIndex';
import { PrivateContent } from '@app/components/shared/PrivateContent';
import { useFileManagement } from '@app/contexts/FileContext';
interface FileListItemProps {
file: StirlingFileStub;
@@ -28,7 +26,6 @@ interface FileListItemProps {
isLast?: boolean;
isHistoryFile?: boolean; // Whether this is a history file (indented)
isLatestVersion?: boolean; // Whether this is the latest version (shows chevron)
isActive?: boolean; // Whether this file is currently loaded in FileContext
}
const FileListItem: React.FC<FileListItemProps> = ({
@@ -40,14 +37,12 @@ const FileListItem: React.FC<FileListItemProps> = ({
onDownload,
onDoubleClick,
isHistoryFile = false,
isLatestVersion = false,
isActive = false
isLatestVersion = false
}) => {
const [isHovered, setIsHovered] = useState(false);
const [isMenuOpen, setIsMenuOpen] = useState(false);
const { t } = useTranslation();
const {expandedFileIds, onToggleExpansion, onUnzipFile } = useFileManagerContext();
const { removeFiles } = useFileManagement();
// Check if this is a ZIP file
const isZipFile = zipFileService.isZipFileStub(file);
@@ -66,10 +61,8 @@ const FileListItem: React.FC<FileListItemProps> = ({
<Box
p="sm"
style={{
cursor: isHistoryFile || isActive ? 'default' : 'pointer',
backgroundColor: isActive
? 'var(--file-active-bg)'
: isSelected
cursor: isHistoryFile ? 'default' : 'pointer',
backgroundColor: isSelected
? 'var(--mantine-color-gray-1)'
: (shouldShowHovered ? 'var(--mantine-color-gray-1)' : 'var(--bg-file-list)'),
opacity: isSupported ? 1 : 0.5,
@@ -81,7 +74,7 @@ const FileListItem: React.FC<FileListItemProps> = ({
paddingLeft: isHistoryFile ? '2rem' : '0.75rem', // Indent history files
borderLeft: isHistoryFile ? '3px solid var(--mantine-color-blue-4)' : 'none' // Visual indicator for history
}}
onClick={isHistoryFile || isActive ? undefined : (e) => onSelect(e.shiftKey)}
onClick={isHistoryFile ? undefined : (e) => onSelect(e.shiftKey)}
onDoubleClick={onDoubleClick}
onMouseEnter={() => setIsHovered(true)}
onMouseLeave={() => setIsHovered(false)}
@@ -91,16 +84,14 @@ const FileListItem: React.FC<FileListItemProps> = ({
<Box>
{/* Checkbox for regular files only */}
<Checkbox
checked={isActive || isSelected}
checked={isSelected}
onChange={() => {}} // Handled by parent onClick
size="sm"
pl="sm"
pr="xs"
disabled={isActive}
color={isActive ? "green" : undefined}
styles={{
input: {
cursor: isActive ? 'not-allowed' : 'pointer'
cursor: 'pointer'
}
}}
/>
@@ -112,19 +103,6 @@ const FileListItem: React.FC<FileListItemProps> = ({
<Text size="sm" fw={500} truncate style={{ flex: 1 }}>
<PrivateContent>{file.name}</PrivateContent>
</Text>
{isActive && (
<Badge
size="xs"
variant="light"
style={{
backgroundColor: 'var(--file-active-badge-bg)',
color: 'var(--file-active-badge-fg)',
border: '1px solid var(--file-active-badge-border)'
}}
>
{t('fileManager.active', 'Active')}
</Badge>
)}
<Badge size="xs" variant="light" color={"blue"}>
v{currentVersion}
</Badge>
@@ -173,22 +151,6 @@ const FileListItem: React.FC<FileListItemProps> = ({
</Menu.Target>
<Menu.Dropdown>
{/* Close file option for active files */}
{isActive && (
<>
<Menu.Item
leftSection={<CloseIcon style={{ fontSize: 16 }} />}
onClick={(e) => {
e.stopPropagation();
removeFiles([file.id]);
}}
>
{t('fileManager.closeFile', 'Close File')}
</Menu.Item>
<Menu.Divider />
</>
)}
{onDownload && (
<Menu.Item
leftSection={<DownloadIcon style={{ fontSize: 16 }} />}
@@ -41,8 +41,6 @@ import { HistoryAPIBridge } from '@app/components/viewer/HistoryAPIBridge';
import type { SignatureAPI, HistoryAPI } from '@app/components/viewer/viewerTypes';
import { ExportAPIBridge } from '@app/components/viewer/ExportAPIBridge';
import { BookmarkAPIBridge } from '@app/components/viewer/BookmarkAPIBridge';
import { isPdfFile } from '@app/utils/fileUtils';
import { useTranslation } from 'react-i18next';
interface LocalEmbedPDFProps {
file?: File | Blob;
@@ -54,7 +52,6 @@ interface LocalEmbedPDFProps {
}
export function LocalEmbedPDF({ file, url, enableAnnotations = false, onSignatureAdded, signatureApiRef, historyApiRef }: LocalEmbedPDFProps) {
const { t } = useTranslation();
const [pdfUrl, setPdfUrl] = useState<string | null>(null);
const [, setAnnotations] = useState<Array<{id: string, pageIndex: number, rect: any}>>([]);
@@ -174,29 +171,6 @@ export function LocalEmbedPDF({ file, url, enableAnnotations = false, onSignatur
);
}
// Check if the file is actually a PDF
if (file && !isPdfFile(file)) {
const fileName = 'name' in file ? file.name : t('viewer.unknownFile');
return (
<Center h="100%" w="100%">
<Stack align="center" gap="md">
<div style={{ fontSize: '48px' }}>📄</div>
<Text size="lg" fw={600} c="dimmed">
{t('viewer.cannotPreviewFile')}
</Text>
<Text c="dimmed" size="sm" style={{ textAlign: 'center', maxWidth: '400px' }}>
{t('viewer.onlyPdfSupported')}
</Text>
<PrivateContent>
<Text c="dimmed" size="xs" style={{ fontFamily: 'monospace' }}>
{fileName}
</Text>
</PrivateContent>
</Stack>
</Center>
);
}
if (isLoading || !engine || !pdfUrl) {
return <ToolLoadingFallback toolName="PDF Engine" />;
}
@@ -51,7 +51,6 @@ describe('AppConfigContext', () => {
expect(apiClient.get).toHaveBeenCalledWith('/api/v1/config/app-config', {
suppressErrorToast: true,
skipAuthRedirect: true,
});
});
@@ -283,7 +282,6 @@ describe('AppConfigContext', () => {
await waitFor(() => {
expect(apiClient.get).toHaveBeenCalledWith('/api/v1/config/app-config', {
suppressErrorToast: true,
skipAuthRedirect: true,
});
});
});
@@ -87,8 +87,7 @@ export const AppConfigProvider: React.FC<AppConfigProviderProps> = ({
const isBlockingMode = bootstrapMode === 'blocking';
const [config, setConfig] = useState<AppConfig | null>(initialConfig);
const [error, setError] = useState<string | null>(null);
// Track how many times we've attempted to fetch. useRef avoids re-renders that can trigger loops.
const fetchCountRef = React.useRef(0);
const [fetchCount, setFetchCount] = useState(0);
const [hasResolvedConfig, setHasResolvedConfig] = useState(Boolean(initialConfig) && !isBlockingMode);
const [loading, setLoading] = useState(!hasResolvedConfig);
@@ -97,14 +96,11 @@ export const AppConfigProvider: React.FC<AppConfigProviderProps> = ({
const fetchConfig = useCallback(async (force = false) => {
// Prevent duplicate fetches unless forced
if (!force && fetchCountRef.current > 0) {
if (!force && fetchCount > 0) {
console.debug('[AppConfig] Already fetched, skipping');
return;
}
// Mark that we've attempted a fetch to prevent repeated auto-fetch loops
fetchCountRef.current += 1;
const shouldBlockUI = !hasResolvedConfig || isBlockingMode;
if (shouldBlockUI) {
setLoading(true);
@@ -116,6 +112,7 @@ export const AppConfigProvider: React.FC<AppConfigProviderProps> = ({
const testConfig = getSimulatedAppConfig();
if (testConfig) {
setConfig(testConfig);
setFetchCount((prev) => prev + 1);
setHasResolvedConfig(true);
setLoading(false);
return;
@@ -131,17 +128,12 @@ export const AppConfigProvider: React.FC<AppConfigProviderProps> = ({
// apiClient automatically adds JWT header if available via interceptors
// Always suppress error toast - we handle 401 errors locally
const response = await apiClient.get<AppConfig>(
'/api/v1/config/app-config',
{
suppressErrorToast: true,
skipAuthRedirect: true,
} as any,
);
const response = await apiClient.get<AppConfig>('/api/v1/config/app-config', { suppressErrorToast: true });
const data = response.data;
console.debug('[AppConfig] Config fetched successfully:', data);
setConfig(data);
setFetchCount(prev => prev + 1);
setHasResolvedConfig(true);
setLoading(false);
return; // Success - exit function
@@ -178,7 +170,7 @@ export const AppConfigProvider: React.FC<AppConfigProviderProps> = ({
}
setLoading(false);
}, [hasResolvedConfig, isBlockingMode, maxRetries, initialDelay]);
}, [fetchCount, hasResolvedConfig, isBlockingMode, maxRetries, initialDelay]);
useEffect(() => {
// Skip config fetch on auth pages (/login, /signup, /auth/callback, /invite/*)
@@ -217,13 +209,11 @@ export const AppConfigProvider: React.FC<AppConfigProviderProps> = ({
return () => window.removeEventListener('jwt-available', handleJwtAvailable);
}, [fetchConfig]);
const refetch = useCallback(() => fetchConfig(true), [fetchConfig]);
const value: AppConfigContextValue = {
config,
loading,
error,
refetch,
refetch: () => fetchConfig(true),
};
return (
@@ -20,7 +20,6 @@ interface FileManagerContextValue {
fileGroups: Map<FileId, StirlingFileStub[]>;
loadedHistoryFiles: Map<FileId, StirlingFileStub[]>;
isLoading: boolean;
activeFileIds: FileId[];
// Handlers
onSourceChange: (source: 'recent' | 'local' | 'drive') => void;
@@ -64,7 +63,6 @@ interface FileManagerProviderProps {
modalHeight: string;
refreshRecentFiles: () => Promise<void>;
isLoading: boolean;
activeFileIds: FileId[];
}
export const FileManagerProvider: React.FC<FileManagerProviderProps> = ({
@@ -79,7 +77,6 @@ export const FileManagerProvider: React.FC<FileManagerProviderProps> = ({
modalHeight,
refreshRecentFiles,
isLoading,
activeFileIds,
}) => {
const [activeSource, setActiveSource] = useState<'recent' | 'local' | 'drive'>('recent');
const [selectedFileIds, setSelectedFileIds] = useState<FileId[]>([]);
@@ -621,7 +618,6 @@ export const FileManagerProvider: React.FC<FileManagerProviderProps> = ({
fileGroups,
loadedHistoryFiles,
isLoading,
activeFileIds,
// Handlers
onSourceChange: handleSourceChange,
@@ -658,7 +654,6 @@ export const FileManagerProvider: React.FC<FileManagerProviderProps> = ({
fileGroups,
loadedHistoryFiles,
isLoading,
activeFileIds,
handleSourceChange,
handleLocalFileClick,
handleFileSelect,
@@ -1,86 +0,0 @@
import { useCallback, useEffect, useState } from 'react';
import { BASE_PATH } from '@app/constants/app';
type BackendStatus = 'up' | 'starting' | 'down';
interface BackendProbeState {
status: BackendStatus;
loginDisabled: boolean;
loading: boolean;
}
/**
* Lightweight backend probe that avoids global axios interceptors.
* Used on auth screens to decide whether to show login, anonymous mode, or a backend-starting message.
*/
export function useBackendProbe() {
const [state, setState] = useState<BackendProbeState>({
status: 'starting',
loginDisabled: false,
loading: true,
});
const probe = useCallback(async () => {
const statusUrl = `${BASE_PATH || ''}/api/v1/info/status`;
const loginUrl = `${BASE_PATH || ''}/api/v1/proprietary/ui-data/login`;
const next: BackendProbeState = {
status: 'starting',
loginDisabled: false,
loading: false,
};
try {
const res = await fetch(statusUrl, { method: 'GET', cache: 'no-store' });
if (res.ok) {
const data = await res.json().catch(() => null);
if (data && data.status === 'UP') {
next.status = 'up';
setState(next);
return next;
}
next.status = 'starting';
} else if (res.status === 404 || res.status === 503) {
next.status = 'starting';
} else {
next.status = 'down';
}
} catch {
next.status = 'down';
}
// Fallback: proprietary login endpoint to detect disabled login and backend availability
try {
const res = await fetch(loginUrl, { method: 'GET', cache: 'no-store' });
if (res.ok) {
next.status = 'up';
const data = await res.json().catch(() => null);
if (data && data.enableLogin === false) {
next.loginDisabled = true;
}
} else if (res.status === 404) {
// Endpoint missing usually means login disabled
next.status = 'up';
next.loginDisabled = true;
} else if (res.status === 503) {
next.status = 'starting';
} else {
next.status = 'down';
}
} catch {
// keep previous inferred state (down/starting)
}
setState(next);
return next;
}, []);
useEffect(() => {
void probe();
}, [probe]);
return {
...state,
probe,
};
}
+4 -12
View File
@@ -88,7 +88,6 @@ const SPECIAL_SUPPRESS_MS = 1500; // brief window to suppress generic duplicate
* Returns true if the error should be suppressed (deduplicated), false otherwise
*/
export async function handleHttpError(error: any): Promise<boolean> {
const skipAuthRedirect = error?.config?.skipAuthRedirect === true;
// Check if this error should skip the global toast (component will handle it)
if (error?.config?.suppressErrorToast === true) {
return false; // Don't show global toast, but continue rejection
@@ -106,19 +105,12 @@ export async function handleHttpError(error: any): Promise<boolean> {
pathname.includes('/invite/');
// If not on auth page, redirect to login with expired session message
if (!isAuthPage && !skipAuthRedirect) {
if (!isAuthPage) {
console.debug('[httpErrorHandler] 401 detected, redirecting to login');
// Store the current location so we can redirect back after login
const currentLocation = window.location.pathname + window.location.search;
// Redirect to login with state (only show expired when a JWT existed)
let hadStoredJwt = false;
try {
hadStoredJwt = Boolean(localStorage.getItem('stirling_jwt'));
} catch {
// ignore storage access failures
}
const expiredPrefix = hadStoredJwt ? 'expired=true&' : '';
window.location.href = `/login?${expiredPrefix}from=${encodeURIComponent(currentLocation)}`;
// Redirect to login with state
window.location.href = `/login?expired=true&from=${encodeURIComponent(currentLocation)}`;
return true; // Suppress toast since we're redirecting
}
@@ -181,4 +173,4 @@ export async function handleHttpError(error: any): Promise<boolean> {
}
return false; // Error was handled with toast, continue normal rejection
}
}
+4 -4
View File
@@ -101,8 +101,8 @@ export class UpdateService {
async getUpdateSummary(currentVersion: string, machineInfo: MachineInfo): Promise<UpdateSummary | null> {
// Map Java License enum to API types
let type = 'normal';
if (machineInfo.licenseType === 'SERVER') {
type = 'server';
if (machineInfo.licenseType === 'PRO') {
type = 'pro';
} else if (machineInfo.licenseType === 'ENTERPRISE') {
type = 'enterprise';
}
@@ -133,8 +133,8 @@ export class UpdateService {
async getFullUpdateInfo(currentVersion: string, machineInfo: MachineInfo): Promise<FullUpdateInfo | null> {
// Map Java License enum to API types
let type = 'normal';
if (machineInfo.licenseType === 'SERVER') {
type = 'server';
if (machineInfo.licenseType === 'PRO') {
type = 'pro';
} else if (machineInfo.licenseType === 'ENTERPRISE') {
type = 'enterprise';
}
-12
View File
@@ -12,12 +12,6 @@
/* Inline highlights in summary */
--spdf-compare-inline-removed-bg: rgba(255, 59, 48, 0.25);
--spdf-compare-inline-added-bg: rgba(52, 199, 89, 0.25);
/* File Manager active file colors */
--file-active-bg: rgba(59, 130, 246, 0.1); /* Transparent blue for active file background */
--file-active-badge-bg: rgba(34, 197, 94, 0.15); /* Transparent green for active badge */
--file-active-badge-fg: #15803d; /* Green text for active badge */
--file-active-badge-border: rgba(34, 197, 94, 0.3); /* Green border for active badge */
}
/* CSS variables for Tailwind + Mantine integration */
@@ -164,9 +158,6 @@
--text-primary: #111827;
--text-secondary: #4b5563;
--text-muted: #6b7280;
/* Always-dark text (for use on light backgrounds like alerts) - does not change in dark mode */
--text-always-dark: #1f2937;
--text-always-dark-muted: #6b7280;
--border-subtle: #e5e7eb;
--border-default: #E2E8F0;
--border-strong: #9ca3af;
@@ -443,9 +434,6 @@
--text-primary: #f9fafb;
--text-secondary: #d1d5db;
--text-muted: #9ca3af;
/* Always-dark text (for use on light backgrounds like alerts) - does not change in dark mode */
--text-always-dark: #1f2937;
--text-always-dark-muted: #6b7280;
--border-subtle: #2A2F36;
--border-default: #3A4047;
--border-strong: #4b5563;
-87
View File
@@ -1,87 +0,0 @@
import { describe, it, expect } from 'vitest';
import { isPdfFile, detectFileExtension, formatFileSize } from '@app/utils/fileUtils';
describe('fileUtils', () => {
describe('isPdfFile', () => {
it('should return true for PDF files with correct MIME type', () => {
const pdfFile = new File(['content'], 'document.pdf', { type: 'application/pdf' });
expect(isPdfFile(pdfFile)).toBe(true);
});
it('should return true for PDF files with .pdf extension even without MIME type', () => {
const pdfFile = new File(['content'], 'document.pdf', { type: '' });
expect(isPdfFile(pdfFile)).toBe(true);
});
it('should return false for non-PDF files', () => {
const txtFile = new File(['content'], 'document.txt', { type: 'text/plain' });
expect(isPdfFile(txtFile)).toBe(false);
});
it('should return false for image files', () => {
const imageFile = new File(['content'], 'image.png', { type: 'image/png' });
expect(isPdfFile(imageFile)).toBe(false);
});
it('should return false for null', () => {
expect(isPdfFile(null)).toBe(false);
});
it('should return false for undefined', () => {
expect(isPdfFile(undefined)).toBe(false);
});
it('should handle file-like objects with name and type', () => {
const fileLike = { name: 'test.pdf', type: 'application/pdf' };
expect(isPdfFile(fileLike)).toBe(true);
});
it('should handle file-like objects with PDF extension but no type', () => {
const fileLike = { name: 'test.pdf', type: '' };
expect(isPdfFile(fileLike)).toBe(true);
});
});
describe('detectFileExtension', () => {
it('should detect PDF extension', () => {
expect(detectFileExtension('document.pdf')).toBe('pdf');
});
it('should detect extension in uppercase', () => {
expect(detectFileExtension('document.PDF')).toBe('pdf');
});
it('should return empty string for files without extension', () => {
expect(detectFileExtension('document')).toBe('');
});
it('should handle multiple dots in filename', () => {
expect(detectFileExtension('my.document.pdf')).toBe('pdf');
});
it('should normalize jpeg to jpg', () => {
expect(detectFileExtension('image.jpeg')).toBe('jpg');
});
});
describe('formatFileSize', () => {
it('should format bytes', () => {
expect(formatFileSize(0)).toBe('0 B');
expect(formatFileSize(500)).toBe('500 B');
});
it('should format kilobytes', () => {
expect(formatFileSize(1024)).toBe('1 KB');
expect(formatFileSize(2048)).toBe('2 KB');
});
it('should format megabytes', () => {
expect(formatFileSize(1024 * 1024)).toBe('1 MB');
expect(formatFileSize(5 * 1024 * 1024)).toBe('5 MB');
});
it('should format gigabytes', () => {
expect(formatFileSize(1024 * 1024 * 1024)).toBe('1 GB');
});
});
});
-23
View File
@@ -51,26 +51,3 @@ export function detectFileExtension(filename: string): string {
return extension;
}
/**
* Checks if a file is a PDF based on extension and MIME type
* @param file - File or file-like object with name and type properties
* @returns true if the file appears to be a PDF
*/
export function isPdfFile(file: { name?: string; type?: string } | File | Blob | null | undefined): boolean {
if (!file) return false;
const name = 'name' in file ? file.name : undefined;
const type = file.type;
// Check MIME type first (most reliable)
if (type === 'application/pdf') return true;
// Check file extension as fallback
if (name) {
const ext = detectFileExtension(name);
if (ext === 'pdf') return true;
}
return false;
}
+2 -2
View File
@@ -33,11 +33,11 @@ export const useDefaultApp = () => {
body: t('defaultApp.success.message', 'Stirling PDF is now your default PDF editor'),
});
setIsDefault(true);
} else if (result === 'opened_dialog') {
} else if (result === 'opened_settings') {
alert({
alertType: 'neutral',
title: t('defaultApp.settingsOpened.title', 'Settings Opened'),
body: t('defaultApp.settingsOpened.message', 'Please select Stirling PDF in the file association dialogue'),
body: t('defaultApp.settingsOpened.message', 'Please select Stirling PDF in your system settings'),
});
}
} catch (error) {
@@ -88,7 +88,8 @@ export function useEndpointEnabled(endpoint: string): {
try {
setError(null);
const response = await apiClient.get<boolean>(`/api/v1/config/endpoint-enabled?endpoint=${encodeURIComponent(endpoint)}`, {
const response = await apiClient.get<boolean>('/api/v1/config/endpoint-enabled', {
params: { endpoint },
suppressErrorToast: true,
});
@@ -22,10 +22,10 @@ export const defaultAppService = {
* Set or prompt to set Stirling PDF as default PDF handler
* Returns a status string indicating what happened
*/
async setAsDefaultPdfHandler(): Promise<'set_successfully' | 'opened_dialog' | 'error'> {
async setAsDefaultPdfHandler(): Promise<'set_successfully' | 'opened_settings' | 'error'> {
try {
const result = await invoke<string>('set_as_default_pdf_handler');
return result as 'set_successfully' | 'opened_dialog';
return result as 'set_successfully' | 'opened_settings';
} catch (error) {
console.error('[DefaultApp] Failed to set default handler:', error);
return 'error';
+2 -2
View File
@@ -12,8 +12,8 @@ import posthog from 'posthog-js';
import { PostHogProvider } from 'posthog-js/react';
import { BASE_PATH } from '@app/constants/app';
posthog.init('phc_VOdeYnlevc2T63m3myFGjeBlRcIusRgmhfx6XL5a1iz', {
api_host: 'https://eu.i.posthog.com',
posthog.init(import.meta.env.VITE_PUBLIC_POSTHOG_KEY, {
api_host: import.meta.env.VITE_PUBLIC_POSTHOG_HOST,
defaults: '2025-05-24',
capture_exceptions: true, // This enables capturing exceptions using Error Tracking, set to false if you don't want this
debug: false,
+6 -80
View File
@@ -1,15 +1,11 @@
import { useState, useEffect } from 'react'
import { Navigate, useLocation, useNavigate } from 'react-router-dom'
import { Navigate, useLocation } from 'react-router-dom'
import { useAuth } from '@app/auth/UseSession'
import { useAppConfig } from '@app/contexts/AppConfigContext'
import HomePage from '@app/pages/HomePage'
// Login component is used via routing, not directly imported
import FirstLoginModal from '@app/components/shared/FirstLoginModal'
import { accountService } from '@app/services/accountService'
import { useBackendProbe } from '@app/hooks/useBackendProbe'
import AuthLayout from '@app/routes/authShared/AuthLayout'
import LoginHeader from '@app/routes/login/LoginHeader'
import { useTranslation } from 'react-i18next'
/**
* Landing component - Smart router based on authentication status
@@ -20,36 +16,13 @@ import { useTranslation } from 'react-i18next'
*/
export default function Landing() {
const { session, loading: authLoading, refreshSession } = useAuth();
const { config, loading: configLoading, refetch } = useAppConfig();
const backendProbe = useBackendProbe();
const { config, loading: configLoading } = useAppConfig();
const location = useLocation();
const navigate = useNavigate();
const { t } = useTranslation();
const [isFirstLogin, setIsFirstLogin] = useState(false);
const [checkingFirstLogin, setCheckingFirstLogin] = useState(false);
const [username, setUsername] = useState('');
const loading = authLoading || configLoading || backendProbe.loading;
// Periodically probe while backend isn't up so the screen can auto-advance when it comes online
useEffect(() => {
if (backendProbe.status === 'up' || backendProbe.loginDisabled) {
return;
}
const tick = async () => {
const result = await backendProbe.probe();
if (result.status === 'up') {
await refetch();
if (result.loginDisabled) {
navigate('/', { replace: true });
}
}
};
const intervalId = window.setInterval(() => {
void tick();
}, 5000);
return () => window.clearInterval(intervalId);
}, [backendProbe.status, backendProbe.loginDisabled, backendProbe.probe, navigate, refetch]);
const loading = authLoading || configLoading;
// Check if user needs to change password on first login
useEffect(() => {
@@ -73,12 +46,6 @@ export default function Landing() {
checkFirstLogin()
}, [session, config])
useEffect(() => {
if (backendProbe.status === 'up') {
void refetch();
}
}, [backendProbe.status, refetch]);
const handlePasswordChanged = async () => {
// After password change, backend logs out the user
// Refresh session to detect logout and redirect to login
@@ -91,7 +58,7 @@ export default function Landing() {
pathname: location.pathname,
loading,
hasSession: !!session,
loginEnabled: config?.enableLogin === true && !backendProbe.loginDisabled,
loginEnabled: config?.enableLogin,
});
// Show loading while checking auth and config
@@ -109,50 +76,11 @@ export default function Landing() {
}
// If login is disabled, show app directly (anonymous mode)
if (config?.enableLogin === false || backendProbe.loginDisabled) {
if (config?.enableLogin === false) {
console.debug('[Landing] Login disabled - showing app in anonymous mode');
return <HomePage />;
}
// If backend is not up yet and user is not authenticated, show a branded status screen
if (!session && backendProbe.status !== 'up') {
const backendTitle = t('backendStartup.notFoundTitle', 'Backend not found');
const handleRetry = async () => {
const result = await backendProbe.probe();
if (result.status === 'up') {
await refetch();
navigate('/', { replace: true });
}
};
return (
<AuthLayout>
<LoginHeader title={backendTitle} />
<div
className="auth-section"
style={{
padding: '1.5rem',
marginTop: '1rem',
borderRadius: '0.75rem',
backgroundColor: 'rgba(37, 99, 235, 0.08)',
border: '1px solid rgba(37, 99, 235, 0.2)',
}}
>
<p style={{ margin: '0 0 0.75rem 0', color: 'rgba(15, 23, 42, 0.8)' }}>
{t('backendStartup.unreachable')}
</p>
<button
type="button"
onClick={handleRetry}
className="auth-cta-button px-4 py-[0.75rem] rounded-[0.625rem] text-base font-semibold mt-5 border-0 cursor-pointer"
style={{ width: 'fit-content' }}
>
{t('backendStartup.retry', 'Retry')}
</button>
</div>
</AuthLayout>
);
}
// If we have a session, show the main app
if (session) {
return (
@@ -169,7 +97,5 @@ export default function Landing() {
// No session - redirect to login page
// This ensures the URL always shows /login when not authenticated
return (config?.enableLogin === true && !backendProbe.loginDisabled)
? <Navigate to="/login" replace state={{ from: location }} />
: <HomePage />;
return <Navigate to="/login" replace state={{ from: location }} />;
}
+2 -22
View File
@@ -40,20 +40,6 @@ vi.mock('@app/hooks/useDocumentMeta', () => ({
global.fetch = vi.fn();
const mockNavigate = vi.fn();
const mockBackendProbeState = {
status: 'up' as const,
loginDisabled: false,
loading: false,
};
const mockProbe = vi.fn().mockResolvedValue(mockBackendProbeState);
vi.mock('@app/hooks/useBackendProbe', () => ({
useBackendProbe: () => ({
...mockBackendProbeState,
probe: mockProbe,
}),
}));
vi.mock('react-router-dom', async () => {
const actual = await vi.importActual('react-router-dom');
return {
@@ -72,10 +58,6 @@ const TestWrapper = ({ children }: { children: React.ReactNode }) => (
describe('Login', () => {
beforeEach(() => {
vi.clearAllMocks();
mockBackendProbeState.status = 'up';
mockBackendProbeState.loginDisabled = false;
mockBackendProbeState.loading = false;
mockProbe.mockResolvedValue(mockBackendProbeState);
// Default auth state - not logged in
vi.mocked(useAuth).mockReturnValue({
@@ -348,15 +330,13 @@ describe('Login', () => {
</TestWrapper>
);
return waitFor(() => {
waitFor(() => {
const emailInput = document.getElementById('email') as HTMLInputElement;
expect(emailInput.value).toBe(email);
});
});
it('should redirect to home when login disabled', async () => {
mockBackendProbeState.loginDisabled = true;
mockProbe.mockResolvedValueOnce({ status: 'up', loginDisabled: true, loading: false });
vi.mocked(fetch).mockResolvedValueOnce({
ok: true,
json: async () => ({
@@ -374,7 +354,7 @@ describe('Login', () => {
);
await waitFor(() => {
expect(mockNavigate).toHaveBeenCalledWith('/', { replace: true });
expect(mockNavigate).toHaveBeenCalledWith('/');
});
});
+10 -97
View File
@@ -1,13 +1,11 @@
import { useEffect, useState } from 'react';
import { Navigate, useNavigate, useSearchParams } from 'react-router-dom';
import { useNavigate, useSearchParams } from 'react-router-dom';
import { Text, Stack, Alert } from '@mantine/core';
import { springAuth } from '@app/auth/springAuthClient';
import { useAuth } from '@app/auth/UseSession';
import { useAppConfig } from '@app/contexts/AppConfigContext';
import { useTranslation } from 'react-i18next';
import { useDocumentMeta } from '@app/hooks/useDocumentMeta';
import AuthLayout from '@app/routes/authShared/AuthLayout';
import { useBackendProbe } from '@app/hooks/useBackendProbe';
// Import login components
import LoginHeader from '@app/routes/login/LoginHeader';
@@ -22,41 +20,18 @@ export default function Login() {
const navigate = useNavigate();
const [searchParams] = useSearchParams();
const { session, loading } = useAuth();
const { refetch } = useAppConfig();
const { t } = useTranslation();
const [isSigningIn, setIsSigningIn] = useState(false);
const [error, setError] = useState<string | null>(null);
const [successMessage, setSuccessMessage] = useState<string | null>(null);
const [showEmailForm, setShowEmailForm] = useState(false);
const [email, setEmail] = useState(() => searchParams.get('email') ?? '');
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [enabledProviders, setEnabledProviders] = useState<string[]>([]);
const [hasSSOProviders, setHasSSOProviders] = useState(false);
const [_enableLogin, setEnableLogin] = useState<boolean | null>(null);
const backendProbe = useBackendProbe();
const [isFirstTimeSetup, setIsFirstTimeSetup] = useState(false);
const [showDefaultCredentials, setShowDefaultCredentials] = useState(false);
const loginDisabled = backendProbe.loginDisabled === true || _enableLogin === false;
// Periodically probe while backend isn't up so the screen can auto-advance when it comes online
useEffect(() => {
if (backendProbe.status === 'up' || backendProbe.loginDisabled) {
return;
}
const tick = async () => {
const result = await backendProbe.probe();
if (result.status === 'up') {
await refetch();
if (loginDisabled) {
navigate('/', { replace: true });
}
}
};
const intervalId = window.setInterval(() => {
void tick();
}, 5000);
return () => window.clearInterval(intervalId);
}, [backendProbe.status, backendProbe.loginDisabled, backendProbe.probe, refetch, navigate, loginDisabled]);
// Redirect immediately if user has valid session (JWT already validated by AuthProvider)
useEffect(() => {
@@ -66,21 +41,6 @@ export default function Login() {
}
}, [session, loading, navigate]);
// If backend reports login is disabled, redirect to home (anonymous mode)
useEffect(() => {
if (backendProbe.loginDisabled) {
// Slight delay to allow state updates before redirecting
const id = setTimeout(() => navigate('/', { replace: true }), 0);
return () => clearTimeout(id);
}
}, [backendProbe.loginDisabled, navigate]);
useEffect(() => {
if (backendProbe.status === 'up') {
void refetch();
}
}, [backendProbe.status, refetch]);
// Fetch enabled SSO providers and login config from backend
useEffect(() => {
const fetchProviders = async () => {
@@ -113,11 +73,8 @@ export default function Login() {
console.error('[Login] Failed to fetch enabled providers:', err);
}
};
if (backendProbe.status === 'up' || backendProbe.loginDisabled) {
fetchProviders();
}
}, [navigate, backendProbe.status, backendProbe.loginDisabled]);
fetchProviders();
}, [navigate]);
// Update hasSSOProviders and showEmailForm when enabledProviders changes
useEffect(() => {
@@ -177,55 +134,11 @@ export default function Login() {
ogUrl: `${window.location.origin}${window.location.pathname}`
});
// If login is disabled, short-circuit to home (avoids rendering the form after retry)
if (loginDisabled) {
return <Navigate to="/" replace />;
}
// Show logged in state if authenticated
if (session && !loading) {
return <LoggedInState />;
}
// If backend isn't ready yet, show a lightweight status screen instead of the form
if (backendProbe.status !== 'up' && !loginDisabled) {
const backendTitle = t('backendStartup.notFoundTitle', 'Backend not found');
const handleRetry = async () => {
const result = await backendProbe.probe();
if (result.status === 'up') {
await refetch();
navigate('/', { replace: true });
}
};
return (
<AuthLayout>
<LoginHeader title={backendTitle} />
<div
className="auth-section"
style={{
padding: '1.5rem',
marginTop: '1rem',
borderRadius: '0.75rem',
backgroundColor: 'rgba(37, 99, 235, 0.08)',
border: '1px solid rgba(37, 99, 235, 0.2)',
}}
>
<p style={{ margin: '0 0 0.75rem 0', color: 'rgba(15, 23, 42, 0.8)' }}>
{t('backendStartup.unreachable')}
</p>
<button
type="button"
onClick={handleRetry}
className="auth-cta-button px-4 py-[0.75rem] rounded-[0.625rem] text-base font-semibold mt-5 border-0 cursor-pointer"
style={{ width: 'fit-content' }}
>
{t('backendStartup.retry', 'Retry')}
</button>
</div>
</AuthLayout>
);
}
const signInWithProvider = async (provider: 'github' | 'google' | 'apple' | 'azure' | 'keycloak' | 'oidc') => {
try {
setIsSigningIn(true);
@@ -362,16 +275,16 @@ export default function Login() {
mt="xl"
>
<Stack gap="xs" align="center">
<Text size="sm" fw={600} ta="center" style={{ color: 'var(--text-always-dark)' }}>
<Text size="sm" fw={600} ta="center">
{t('login.defaultCredentials', 'Default Login Credentials')}
</Text>
<Text size="sm" ta="center" style={{ color: 'var(--text-always-dark)' }}>
<Text component="span" fw={600} style={{ color: 'var(--text-always-dark)' }}>{t('login.username', 'Username')}:</Text> admin
<Text size="sm" ta="center">
<Text component="span" fw={600}>{t('login.username', 'Username')}:</Text> admin
</Text>
<Text size="sm" ta="center" style={{ color: 'var(--text-always-dark)' }}>
<Text component="span" fw={600} style={{ color: 'var(--text-always-dark)' }}>{t('login.password', 'Password')}:</Text> stirling
<Text size="sm" ta="center">
<Text component="span" fw={600}>{t('login.password', 'Password')}:</Text> stirling
</Text>
<Text size="xs" ta="center" mt="xs" style={{ color: 'var(--text-always-dark-muted)' }}>
<Text size="xs" c="dimmed" ta="center" mt="xs">
{t('login.changePasswordWarning', 'Please change your password after logging in for the first time')}
</Text>
</Stack>
@@ -70,7 +70,7 @@ export interface LicenseKeyResponse {
}
export interface LicenseInfo {
licenseType: 'NORMAL' | 'SERVER' | 'ENTERPRISE';
licenseType: 'NORMAL' | 'PRO' | 'ENTERPRISE';
enabled: boolean;
maxUsers: number;
hasKey: boolean;
@@ -496,8 +496,8 @@ export const mapLicenseToTier = (licenseInfo: LicenseInfo | null): 'free' | 'ser
return 'free';
}
// SERVER type (unlimited users) = Server tier
if (licenseInfo.licenseType === 'SERVER') {
// PRO type (no seats) = Server tier
if (licenseInfo.licenseType === 'PRO') {
return 'server';
}