Compare commits

..
Author SHA1 Message Date
Connor Yoh 69c4401476 fe(payg): F5 — remove /dev/payg-preview dev route + component
The dev preview was a scaffolding route for iterating on the PAYG plan UI
before real wallet endpoints existed. Now that useWallet calls the real
GET /api/v1/payg/wallet and the upgrade modal is wired end-to-end, the
preview route + component are dead code.

Kept (graceful-degradation paths):
- useWallet.ts buildDevPreviewWallet + localStorage fallback — still
  useful when the /wallet endpoint is unreachable locally
- StripeCheckoutPanel mock-mode placeholder — still used when
  VITE_STRIPE_PUBLISHABLE_KEY is unset
2026-06-09 15:56:34 +01:00
Connor Yoh a24bffdb8e fe(payg): F4 — wrap new PAYG copy in t() + add en-GB TOML keys
PaygFree leader + member, UpgradeModal step 1-3, StripeCheckoutPanel
loading/error/mock states, and the FREE_TIER_EXHAUSTED toast are now
all routed through i18n with English fallbacks. New [payg.*] sections
added to translation.toml: checkout, confirm, error, exhausted, free.*,
signupRequired, stripe.toast, subcaps.editor/toast, upgrade.*. Existing
SignupRequiredBootstrap copy was already wrapped — keys backfilled
into TOML so en-GB loads them at runtime instead of falling back.

paygErrorInterceptor.ts lives outside the React tree so uses
i18n.t() directly (same pattern as backendHealthMonitor).
StripeCheckoutPanel stashes t in a ref so the single-flight effect
deps don't have to include it.

No new TS errors vs baseline (153 pre-existing saas-resolver hits
remain unchanged).
2026-06-09 15:48:55 +01:00
Connor Yoh 9f3b3b174d fe(payg): intercept 402 FEATURE_DEGRADED + 401 SIGNUP_REQUIRED
Classifies the EntitlementGuard's PAYG sentinels in the apiClient
response interceptor before the existing 401/refresh logic and surfaces
appropriate UI:

- 402 FEATURE_DEGRADED → persistent warning toast "You've hit your free
  monthly limit" with a "Go to billing" CTA that opens the Plan tab via
  the existing appConfig:open + appConfig:navigate event bus.
- 401 SIGNUP_REQUIRED → dispatches payg:signupRequired CustomEvent
  carrying the category from the response body. A new top-level
  SignupRequiredBootstrap (mirroring TrialExpiredBootstrap's pattern)
  listens for the event and opens a Mantine modal explaining the free
  500-op/month allowance with a "Sign up free" CTA.

Both paths short-circuit the existing session-refresh / redirect-to-
login logic so anonymous users hitting billable endpoints don't get
bounced to /login when /signup is what they need.

Tests: 12 new unit tests on the classifier + handler (parsing edge
cases, button callback wiring, custom-event dispatch). Existing
apiClient.test.ts still passes — the new path is gated on body.error
sentinels so plain 401s flow through the unchanged refresh path.
2026-06-09 15:09:26 +01:00
Connor Yoh 1de5177f96 fe(payg): same-tab portal redirect + suppressErrorToast on payg mutations
F2 review fixes on useWallet.ts:

- openPortal: switched from window.open(url, "_blank", ...) after an
  await to window.location.assign(url). Browsers treat window.open
  after an awaited promise as non-user-gesture and silently popup-block
  it; the sibling ManageBillingButton already uses same-tab redirect.
  Stripe's customer portal is a full-page experience and returns the
  user to returnUrl on close, so a popup buys us nothing.

- openPortal + updateSubCap: now pass { suppressErrorToast: true } as
  the third axios option. The global response interceptor in
  saas/services/apiClient.ts otherwise shows a generic toast that
  stacks on top of the component-level friendly toast (PORTAL_NOT_
  CONFIGURED on Stripe portal, clamp/validation errors on sub-caps).
  Matches the established pattern in saas/services/userManagementService.ts.
2026-06-09 14:59:16 +01:00
Connor Yoh c3a3c95b7c fe(payg): wire sub-caps editor + Stripe portal button to real BE
useWallet gains updateSubCap (PATCH /api/v1/payg/sub-caps/{userId},
returns effective+clamped so the UI can surface server-side clamping)
and openPortal (POST /api/v1/payg/portal-session, opens the Stripe-
hosted URL in a new tab).

MemberSubCaps now reads from wallet.members[] via a new members prop —
the synthesised 3-row mock only applies when no prop is supplied (dev
preview). Each row has an inline NumberInput editor (Save / Cancel /
Remove cap) with success / clamped / error toasts.

StripePortalLink switches from a static <a href> to a Button that calls
openPortal() with a loading state. On 404 / 503 it shows a friendly
"portal isn't available right now" toast — local dev without the
Supabase edge function configured no longer errors out.
2026-06-09 14:52:48 +01:00
Connor Yoh e6754ede32 fe(payg): delete BE mock controllers, align useWallet shape with real BE
The PaygApiController/PaygApiService mock on this branch is being
superseded by the real backend on payg-c1-cap-entitlement (PR #6574 —
PaygWalletController, served by the wallet_category_summary view +
team_memberships join). Once #6574 lands in main, the mock files would
clash, so they're removed here.

The useWallet Wallet type gains three fields to match the real BE's
WalletSnapshot response: categoryBreakdown (api/ai/automation buckets),
members (per-member sub-cap rows for the leader's dashboard), and recent
(activity feed, V1 = []). Dev preview wallet synthesis populates the
new fields with tier-distinguishable mock values so the design-time
preview still exercises both the free and subscribed visuals.

markSubscribed now swallows 404s from /api/v1/payg/dev/mark-subscribed
since that endpoint disappears with the BE mock. In real-BE mode the
Stripe customer.subscription.created webhook flips the team to
subscribed, so an info-level log + continuing to refetch is the right
move for the FE — no broken modal completion when the dev hook isn't
there.
2026-06-09 14:44:31 +01:00
Connor Yoh 2b11e35530 docs(payg): correct cap-update boundary — cap is application-layer, no Stripe
You'd asked: does cap update really need to touch Stripe? It doesn't.
I was wrong in the prior arch commit calling it a 'stub.' The cap is
permanent in Java.

Stripe has no native hard cap. billing_thresholds.amount_gte is an
early-invoice trigger, not a cut-off. The way you actually cap a
metered subscription is to stop sending meter events — Stripe only
sees what you push. That's an application-layer concern:

  - Cap value lives in wallet_policy.cap_units (Postgres)
  - Before each billable op: gate the meter-payg-units push on
    current_period_spend ≤ cap
  - Hit cap → refuse op, return 402 / DEGRADED state
  - Stripe never knows the cap exists

So PATCH /api/v1/payg/cap is a single SQL UPDATE — no edge function,
no Stripe round-trip. The 'wants to move to update-payg-cap edge fn'
TODO from the prior commit was wrong; removed.

Updated:
- PaygApiController class javadoc — split rationale is about who owns
  the DATA, not who touches Stripe. Java owns app-rule writes
  (wallet_policy, cap, sub-caps); edge fns own Stripe mutations.
- PaygApiController#updateCap section comment — points at the real
  one-line repository write that lands when the mock comes out.
- PaygApiService#updateCap javadoc — same correction.
- PaygApiService class swap-out plan — cap step no longer references
  a non-existent update-payg-cap edge function.

Best practice general rule (recorded in javadoc):
- User-set limits (cap, sub-caps, warn-at %): your DB, your enforcement
- Subscription state, prices, payment methods: Stripe is source of
  truth, mirror via Sync Engine for read perf
- Usage events: push to Stripe, gated by your internal cap check
2026-06-09 10:00:19 +01:00
Connor Yoh e4d8832c27 arch: move Stripe Checkout creation to Supabase edge function
You'd flagged that calling Stripe from Java duplicates the edge function
in PR #300. Fixed.

Java was doing both wallet reads AND creating Stripe Checkout Sessions.
The latter overlaps with `create-payg-team-subscription` (already on
SaaS PR #300, 79 tests, uses Stripe Sync Engine + shared SDK plumbing).
Routing through Java meant:

  - Two Stripe integrations to keep in sync (Java + Deno)
  - Two places for the Stripe secret key to live
  - Useless proxy hop: FE → Java → edge fn → Stripe
  - Doesn't match the existing pattern — usePlans already calls
    `supabase.functions.invoke("stripe-price-lookup", ...)` directly

Now:

  FE → supabase.functions.invoke("create-payg-team-subscription") → Stripe

Java keeps:

  - GET /api/v1/payg/wallet — pure read, no Stripe touch
  - PATCH /api/v1/payg/cap — temporary stub. Cap updates also touch
    Stripe (subscription_item.update with new billing_thresholds), so
    this should move to a new `update-payg-cap` edge function. Marked
    with a clear TODO in the controller javadoc.
  - POST /api/v1/payg/dev/mark-subscribed — dev-only mock side-channel,
    disappears once the real Stripe webhook handler (PR #300) is
    deployed.

Concretely:

  - Removed PaygApiController#createCheckoutSession + CheckoutSessionRequest/Response records
  - Removed PaygApiService#createCheckoutSession + CheckoutSessionResult + createMockClientSecret helper
  - StripeCheckoutPanel now calls supabase.functions.invoke() instead of apiClient.post()
  - Documented the new boundary in both controller + service class javadocs

Verified: dev preview end-to-end flow still works (modal step 1 → step 2 mock placeholder → completion). ./gradlew :saas:compileJava + vite build both clean.
2026-06-09 09:56:04 +01:00
Connor Yoh d3ffc6ebeb review-response: gate dev mark-subscribed, tighten race conditions
Backend (PaygApiController + PaygApiService):
- POST /api/v1/payg/dev/mark-subscribed now requires BOTH
  payg.dev-endpoints.enabled=true (default false) AND ROLE_ADMIN. Returns
  404 when disabled so probes can't enumerate. Marked @Hidden so it stays
  out of the public OpenAPI surface. Closes the "any authenticated user
  can flip their own team to subscribed" hole that would have shipped in
  the prior commit.
- updateCap uses AtomicReference.updateAndGet (CAS) instead of get →
  set so a concurrent markSubscribed can't lose the subscription id.

Frontend (useWallet + StripeCheckoutPanel + Plan + UpgradeModal):
- useWallet: monotonic requestId ref so a slow refetch from tick=N can't
  overwrite a faster one from tick=N+1. Mutations now await the post-
  refetch settle via an in-flight promise ref, so save-button loading
  states drop only once the new state is actually visible.
- useWallet: dev-preview detection requires import.meta.env.DEV AND the
  /dev/ path, so a production tenant with a /dev/ URL prefix can't
  trigger the synthesised fallback.
- StripeCheckoutPanel: same DEV+path gate. onError moved to a ref so it
  doesn't have to live in the effect deps. The single-flight fetchedRef
  now correctly resets per-cap because UpgradeModal keys the panel on
  `co:${effectiveCap}` — editing the cap mid-flow forces a fresh
  Checkout Session for the new amount.
- useRenderCount: hook body fully gated on a module-level IS_DEV const
  so Vite's dead-code-elimination drops the entire counter logic from
  production bundles (only the useRef ref allocation remains, required
  by rules-of-hooks).
- PaygFreeLeader + PaygFreeMember wrapped in React.memo. Plan's
  onUpgraded callback hoisted to useCallback so the prop identity stays
  stable across Plan re-renders (loading/error toggles no longer cascade
  down to the leaves).

Deferred to follow-up commits (noted in PR description):
- isAdmin → real team_memberships.role lookup (currently uses
  ROLE_ADMIN as proxy; correct for now but means most users will land
  in the MEMBER view even if they're a team owner).
- CapEditor's "no cap" toggle (currently only a numeric save).

Verified: ./gradlew :saas:compileJava clean, vite build --mode saas clean.
2026-06-08 22:53:12 +01:00
Connor Yoh b46f65ef8c fe(payg): real useWallet, lazy Stripe Embedded Checkout, confirmation step
End-to-end UI for the new PAYG flow against the backend mock controllers
landed in the previous commit:

- useWallet — calls GET /api/v1/payg/wallet via the shared apiClient (which
  injects the Supabase JWT). Dev preview route synthesises a snapshot
  instead so design iteration stays available. Stable-reference reuse
  optimisation deep-equals each new fetch with the prior snapshot so
  consumers don't re-render on no-op refreshes.

- StripeCheckoutPanel — own module, lazy-imported via React.lazy so the
  Stripe SDK chunk is only fetched when the user reaches step 2. The
  Stripe SDK itself is already pulled into the main bundle by the
  existing TrialExpiredBootstrap / TrialStatusBanner — that chunking is
  out of scope here, but the new modal panel doesn't add extra weight.
  Detects mock-mode (cs_mock_* client_secret OR no VITE_STRIPE_PUBLISHABLE_KEY)
  and renders a friendly placeholder + "Continue with mock subscription"
  button instead of mounting a real iframe with a bad secret.

- UpgradeModal — three sequential panels: cap → checkout (lazy Stripe) →
  confirmation (Welcome to Processor). Cap is held in modal state only;
  nothing reaches the backend until Stripe completes. Backdrop click +
  close button reset the step so reopening starts at cap selection.

- Plan — loading + error states. Passes useWallet's markSubscribed +
  updateCap down to PaygFreeLeader / PaygLeader so completion + cap-save
  trigger a wallet refetch.

- Payg.tsx CapEditor — Save button gains an onSaveCap prop threaded
  through PaygLeader. Currency conversion stays USD-only for V1 (the
  backend's PATCH /cap takes capUsd); non-USD currencies are a follow-up.

- useRenderCount — dev-only render counter. Writes to
  window.__renderCounts so Playwright + manual devtools can assert
  components don't re-render excessively.

- DevPaygPreview — wires its PaygFreeLeader's onUpgraded prop to flip
  the localStorage subscription flag so the dev preview also demos the
  full upgrade cycle (free → modal → subscribed).

Verified: full 3-step modal flow (cap → mock checkout → confirmation)
renders cleanly via the dev preview route. ./gradlew :saas:compileJava
and `vite build --mode saas` both succeed.
2026-06-08 22:46:20 +01:00
Connor Yoh ac33e950b5 be(saas/payg): add /api/v1/payg/{wallet,checkout,cap} controllers (mock)
Adds the three PAYG REST endpoints the new Plan-page UI needs:

  GET   /api/v1/payg/wallet            — subscription state + usage + cap + role
  POST  /api/v1/payg/checkout          — creates a Stripe Checkout Session
  PATCH /api/v1/payg/cap               — updates monthly spend cap

Plus a DEV-ONLY POST /api/v1/payg/dev/mark-subscribed that simulates the
Stripe webhook so the UI can be exercised end-to-end before the real
webhook handler ships.

All endpoints are saas-profile-gated. The service layer is an in-memory
mock keyed by a synthetic team identifier — the real backing tables
(payg_team_extensions.payg_subscription_id + free_tier, payg_meter_event_log)
land in SaaS PR #300 and the Stripe Java SDK isn't on this branch yet.
Each mock returns realistic shapes with a JavaDoc swap-out plan calling
out exactly what changes when the unmerged surfaces land.

Why mock here instead of waiting for PR #300:
- Frontend can iterate against real HTTP round-trips instead of localStorage
- Shapes get exercised before any of it hits prod
- Removing the mock is a service-layer edit, not a controller rewrite

Verified `./gradlew :saas:compileJava` clean.
2026-06-08 22:31:08 +01:00
Connor Yoh c655517ca3 fe(payg): kill old SaaS plan page, branch Plan tab on wallet state
Replaces the legacy multi-tier (Pro / Business / Enterprise + API credit
packs) plan page with the new PAYG plan UI. The Plan tab now internally
branches on (subscription state × team role) and renders one of four views:

  - free + leader     → PaygFreeLeader (upgrade CTA)
  - free + member     → PaygFreeMember (ask-the-owner note)
  - subscribed + L/M  → PaygLeader / PaygMember (Reece's dashboard)

Notable:

- New useWallet() hook (saas/hooks/useWallet.ts). Mock-first: subscription
  state lives in localStorage so the UpgradeModal's onComplete can flip the
  rendered view without a real Stripe round-trip. Role is sourced from
  appConfig.isAdmin (same proxy saasConfigNavSections used before). Swap to
  GET /api/v1/payg/wallet when the endpoint lands.
- PaygFreeLeader gains an optional onUpgraded prop. PlanSection wires it to
  markSubscribed(). Standalone dev-preview keeps the demo alert fallback.
- Drops the duplicate "Pay-as-you-go" nav tab — there is one billing
  surface now, and it's the Plan tab. Removes paygEnabled / isLeader nav
  options (and the related plumbing in AppConfigModal).
- Deletes frontend/editor/src/saas/.../configSections/plan/ (the old
  PlanCard / AvailablePlansSection / ActivePlanSection / ApiPackagesSection
  components). usePlans hook stays — still used by ManageBillingButton +
  TrialStatusBanner.

Verified visually via /dev/payg-preview (screenshots 013–015 in
notes/payg-flow-screenshots/) — all four views render cleanly with the
v2.1 manual-tools framing.
2026-06-08 22:21:32 +01:00
Connor Yoh e99dfb81ae fe(payg): tighten free-tier framing — manual tools vs auto/AI/API
Automation and AI features also have UI surfaces, so the "UI free / not-UI
paid" framing was misleading. Reframed everywhere to be about the type of
work:

- "Manual tools are always free" (viewing, editing, signing, merging,
  splitting, conversion, watermarks, compression, manual OCR)
- "Automation, AI, and API count toward billing" (regardless of where
  they're triggered from)

Also drops the "From $5/month" reassurance because users can set a $0 cap
and pay nothing while still being subscribed; the cap input now accepts
0 and the help text mentions it explicitly.

Touched:
- PaygFree.tsx — module javadoc, header subtitle, CTA reassurance,
  leader + member explainer text, member ask-the-owner note
- UpgradeModal.tsx — promise card, section help, cap input (min={0}),
  billable-list italic footer
2026-06-08 22:06:43 +01:00
Connor Yoh 2faa38c011 PAYG FE: rework promo as PaygFreeLeader/Member; reframe billable scope
Drops the side-by-side card promo (EditorPlanPromo) in favour of two views
that mirror the subscribed PaygLeader/PaygMember dashboards visually. The
free view now feels like an extension of the paid view rather than a
different page, which makes turning on Processor feel like enabling a
switch rather than buying a product.

New billable framing (product call set 2026-06):

  Free, always — anything clicked directly in the Stirling UI:
    viewing, editing, merging, splitting, signing, watermarking,
    compression, conversion, OCR via the interactive UI.

  Counts toward 500/month free tier — and metered above that:
    automation pipelines, AI tools, API calls.

Note: backend design doc + pricing schema don't reflect this yet — FE is
the source of truth in the meantime; backend will catch up.

Components:

  PaygFreeLeader
    - Mirrors PaygLeader: subtitle + role pill header, hero usage card
      showing 62 / 500 free operations with progress bar + "Plenty left"
      status, identical visual language to the subscribed view
    - Below the hero: a gradient-bordered CTA card ("Turn on the Processor
      plan") with three benefit bullets (Automation / AI / API access)
      and footer row containing the CTA button + reassurance copy
    - Bottom: side-by-side explainer cards — "Always free" vs "Counts
      toward 500/month" — using the same colour tokens as the hero
    - CTA opens the existing UpgradeModal

  PaygFreeMember
    - Same header + hero pattern but with team-member pill
    - Replaces the CTA with a lock-icon note explaining the owner can
      enable Processor
    - Same bottom explainer cards but worded for the member viewpoint
      ("Always free for you" / "Shared with the team")

UpgradeModal copy rewrite:

  - Promise card now reads "Everything in the Stirling UI stays free.
    You only pay for what comes from automation pipelines, AI tools, and
    API calls — the things that don't need a person clicking through
    the UI."
  - "Set your monthly spend ceiling" section text updated to
    "Your first 500 automation / AI / API operations every month are free"
  - "What we count toward billing" card now a bulleted list of the three
    billable categories plus an italic line explicitly listing UI tools
    that stay free

Dev preview slots reworked:
  - Was: free / upgrade-modal / active-leader / active-member
  - Now: free-leader / free-member / subscribed-leader / subscribed-member
  - "Upgrade modal" slot removed — the modal now opens from inside
    free-leader, which is the only real entry point

Deleted: EditorPlanPromo.tsx + .css (superseded by PaygFreeLeader).

Screenshots:
  payg-flow-009-free-leader-v1.png  (first cut — stacked header)
  payg-flow-010-free-leader-v2.png  (Mantine Group header, polished CTA)
  payg-flow-011-free-member.png     (member view, lock note instead of CTA)
  payg-flow-012-modal-new-copy.png  (modal with billable framing reworked)
2026-06-08 21:57:07 +01:00
Connor Yoh a15cf5f90d PAYG FE: EditorPlanPromo + UpgradeModal + dev preview route
First visual chunk of the PAYG plan/upgrade flow. Builds on top of Reece's
Payg.tsx (cherry-picked from #6503 into this branch as part of the bundle).

Components:
  - EditorPlanPromo: the page free users see in the Plan slot. Hero anchors
    the "Editing is free, forever" promise; two-card layout shows what they
    get on Editor (current) vs Processor (upgrade); Processor card has a
    gradient border + accent CTA. Reinforcement strip at the bottom restates
    the promise.
  - UpgradeModal: two-step modal inside one frame. Step 1 (cap selection)
    has $10/$25/$50/$100 presets + custom input + no-cap toggle + helper
    card explaining what counts as billable. Step 2 will host Stripe
    Embedded Checkout — currently a placeholder explaining what env vars
    + backend endpoint will activate it. Step indicator transitions
    1-active → 1-done/2-active with colour change. Cap value held in modal
    state, only posted to backend on Checkout success → no side-effects on
    cancel.

Dev preview route (saas/routes/DevPaygPreview.tsx):
  - Gated by import.meta.env.DEV in saas/App.tsx so production tree-shakes
    it out
  - Lets me iterate visually at /dev/payg-preview without going through
    auth + nav config
  - Four slots: free user promo, upgrade modal, subscribed LEADER, subscribed
    MEMBER. The two subscribed slots render Reece's existing Payg.tsx
    (PaygLeader / PaygMember) with mock data so the full surface is visible
  - DELETE before PR ships — flagged in the file's javadoc

Screenshots dropped during iteration:
  payg-flow-002-editor-promo-v1.png   (first cut)
  payg-flow-003-editor-promo-v2.png   (polished)
  payg-flow-004-upgrade-modal-step1.png
  payg-flow-005-upgrade-modal-step2.png
  payg-flow-006-modal-step2-polished.png
  payg-flow-007-full-promo-with-footer.png
  payg-flow-008-leader-dashboard.png

Next commits (same branch, same PR):
  - useWallet() hook wiring Payg.tsx to real /api/v1/payg/wallet endpoint
  - PlanSection.tsx that branches free → EditorPlanPromo / active → PaygLeader/Member
  - Backend Java: wallet endpoint + checkout endpoint + cap endpoint
  - Stripe Embedded Checkout wire-in (placeholder → real iframe)
  - i18n keys for all new copy
  - Remove DevPaygPreview before marking PR ready

No backend changes in this commit — pure visual iteration with mock data.
2026-06-08 21:36:25 +01:00
Connor Yoh e8fd67c004 Remove ?payg=1 demo-override hooks before merge
The PAYG settings screen is mock-only and must stay invisible to users
until the backend wallet endpoint (PR-C3.2) lands and sets
`appConfig.paygEnabled`. The demo overrides bypassed that gate via a URL
query param + localStorage, which would have let anyone with the link see
the mock data.

- AppConfigModal.tsx: drop the `paygOverride` block; `paygEnabled` and
  `isLeader` now derive only from the backend `appConfig` flags.
- proprietary/configNavSections.tsx: drop the cross-flavor `PaygLeader`
  import and the demo block that pushed PAYG into the proprietary nav.
  PAYG is saas-only.
- Payg.tsx: trim the stale comment that justified the relative CSS import
  by referencing the now-removed proprietary demo cross-import.
2026-06-08 21:23:55 +01:00
Connor Yoh b3cae8c0e3 Add missing en-GB translations for PAYG settings screen 2026-06-08 21:23:55 +01:00
ReeceandConnor Yoh 81b7edc84c Add Pay-as-you-go billing & usage settings screen (mock UI) 2026-06-08 21:23:55 +01:00
146 changed files with 7202 additions and 11335 deletions
@@ -1,83 +0,0 @@
#!/usr/bin/env python3
"""Verify Tauri updater .sig files against plugins.updater.pubkey in tauri.conf.json.
Usage: verify-updater-signatures.py <dir-to-scan> [tauri.conf.json]
"""
import binascii
import sys
import json
import base64
import hashlib
from pathlib import Path
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
from cryptography.exceptions import InvalidSignature
ART_ROOT = Path(sys.argv[1])
CONF = Path(
sys.argv[2] if len(sys.argv) > 2 else "frontend/editor/src-tauri/tauri.conf.json"
)
def load_pubkey():
# tauri pubkey = base64 of a minisign .pub file; last line is base64 of
# [2 algo][8 key-id][32 ed25519 public key].
raw = json.loads(CONF.read_text())["plugins"]["updater"]["pubkey"]
blob = base64.b64decode(base64.b64decode(raw).decode().splitlines()[-1])
return blob[2:10], Ed25519PublicKey.from_public_bytes(blob[10:])
def hash_file(path: Path) -> bytes:
h = hashlib.blake2b(digest_size=64)
with path.open("rb") as f:
for chunk in iter(lambda: f.read(1 << 16), b""):
h.update(chunk)
return h.digest()
def verify(artifact: Path, sig_file: Path, keyid_pub, pub) -> str:
# tauri .sig = base64 of a minisign signature file (4 lines).
try:
lines = base64.b64decode(sig_file.read_text()).decode().splitlines()
sig_blob = base64.b64decode(lines[1])
except (binascii.Error, IndexError, UnicodeDecodeError) as e:
return f"FAIL malformed sig ({type(e).__name__})"
algo, keyid, sig = sig_blob[:2], sig_blob[2:10], sig_blob[10:74]
if keyid != keyid_pub:
return f"FAIL key-id mismatch (sig {keyid.hex()} vs pub {keyid_pub.hex()})"
# 'ED' = prehashed (BLAKE2b-512), 'Ed' = legacy (raw message).
msg = hash_file(artifact) if algo == b"ED" else artifact.read_bytes()
try:
pub.verify(sig, msg)
except InvalidSignature:
return f"FAIL signature invalid (algo={algo.decode()})"
# Global signature covers sig + trusted_comment.
gc = "global-sig FAIL"
try:
tc = lines[2].split("trusted comment: ", 1)[1]
pub.verify(base64.b64decode(lines[3]), sig + tc.encode())
gc = "global-sig OK"
except (InvalidSignature, IndexError, binascii.Error):
pass
return f"VALID (algo={algo.decode()}, keyid={keyid.hex()}, {gc})"
keyid_pub, pub = load_pubkey()
print(f"updater pubkey keyid={keyid_pub.hex()}\n")
sigs = sorted(ART_ROOT.rglob("*.sig"))
if not sigs:
print(f"WARN: no .sig files under {ART_ROOT} - nothing to verify")
sys.exit(0)
bad = 0
for sig_file in sigs:
artifact = sig_file.with_suffix("")
if not artifact.exists():
print(f" ? {sig_file.name}: artifact missing")
bad += 1
continue
res = verify(artifact, sig_file, keyid_pub, pub)
print(f" {artifact.name}: {res}")
if not res.startswith("VALID") or "global-sig FAIL" in res:
bad += 1
print(f"\n{'ALL SIGNATURES VALID' if bad == 0 else f'{bad} SIGNATURE(S) FAILED'}")
sys.exit(1 if bad else 0)
@@ -110,8 +110,8 @@ jobs:
NPM_CONFIG_IGNORE_SCRIPTS: "true"
working-directory: frontend
run: |
mkdir -p editor/src/assets
npx --yes license-report --only=prod --output=json > editor/src/assets/3rdPartyLicenses.json
mkdir -p src/assets
npx --yes license-report --only=prod --output=json > src/assets/3rdPartyLicenses.json
- name: Postprocess with project script (BASE version)
if: github.event_name == 'pull_request' && github.event.pull_request.head.repo.fork == true
+48 -138
View File
@@ -588,34 +588,33 @@ jobs:
mkdir -p "$DIST"
cd ./frontend/editor/src-tauri/target
echo "=== tauri bundle artifacts ==="
find . -path "*/bundle/*" \( -name "*.msi" -o -name "*.deb" \
-o -name "*.rpm" -o -name "*.AppImage" -o -name "*.dmg" \
-o -name "*.app.tar.gz" -o -name "*.sig" \) 2>/dev/null | sort || true
echo "=============================="
# createUpdaterArtifacts:true signs the native installers in place;
# each <bundle> ships with a sibling <bundle>.sig consumed by latest.json.
# Find and rename artifacts based on platform
if [ "${{ matrix.platform }}" = "windows-latest" ]; then
# Only ship the MSI installer on Windows. The loose exe and WiX toolset exes
# are not the user-facing installer - the MSI contains the signed inner exe.
find . -name "*.msi" -exec cp {} "$DIST/Stirling-PDF-${{ matrix.name }}.msi" \;
find . -name "*.msi.sig" -exec cp {} "$DIST/Stirling-PDF-${{ matrix.name }}.msi.sig" \;
find . -name "*.msi.zip" -exec cp {} "$DIST/Stirling-PDF-${{ matrix.name }}.msi.zip" \;
find . -name "*.msi.zip.sig" -exec cp {} "$DIST/Stirling-PDF-${{ matrix.name }}.msi.zip.sig" \;
find . -name "*.nsis.zip" -exec cp {} "$DIST/Stirling-PDF-${{ matrix.name }}.nsis.zip" \;
find . -name "*.nsis.zip.sig" -exec cp {} "$DIST/Stirling-PDF-${{ matrix.name }}.nsis.zip.sig" \;
elif [ "${{ matrix.platform }}" = "macos-15" ]; then
# DMG = manual install; .app.tar.gz (+ .sig) = updater payload.
# Raw .app is intentionally not shipped (hundreds of MB of uncompressed input).
find . -name "*.dmg" -exec cp {} "$DIST/Stirling-PDF-${{ matrix.name }}.dmg" \;
find . -name "*.app" -exec cp -r {} "$DIST/Stirling-PDF-${{ matrix.name }}.app" \;
find . -name "*.app.tar.gz" -exec cp {} "$DIST/Stirling-PDF-${{ matrix.name }}.app.tar.gz" \;
find . -name "*.app.tar.gz.sig" -exec cp {} "$DIST/Stirling-PDF-${{ matrix.name }}.app.tar.gz.sig" \;
else
# The raw .AppImage IS its updater payload (signed -> .AppImage.sig),
# not a .tar.gz wrapper - that's only produced under v1Compatible.
find . -name "*.deb" -exec cp {} "$DIST/Stirling-PDF-${{ matrix.name }}.deb" \;
find . -name "*.deb.sig" -exec cp {} "$DIST/Stirling-PDF-${{ matrix.name }}.deb.sig" \;
find . -name "*.rpm" -exec cp {} "$DIST/Stirling-PDF-${{ matrix.name }}.rpm" \;
find . -name "*.rpm.sig" -exec cp {} "$DIST/Stirling-PDF-${{ matrix.name }}.rpm.sig" \;
find . -name "*.AppImage" -exec cp {} "$DIST/Stirling-PDF-${{ matrix.name }}.AppImage" \;
find . -name "*.AppImage.sig" -exec cp {} "$DIST/Stirling-PDF-${{ matrix.name }}.AppImage.sig" \;
find . -name "*.AppImage.tar.gz" -exec cp {} "$DIST/Stirling-PDF-${{ matrix.name }}.AppImage.tar.gz" \;
find . -name "*.AppImage.tar.gz.sig" -exec cp {} "$DIST/Stirling-PDF-${{ matrix.name }}.AppImage.tar.gz.sig" \;
fi
# Copy updater latest.json if generated by tauri-action (rename to be platform-specific).
# Scope strictly to the tauri target tree - a broader find from repo root
# could pick up stray latest.json files and corrupt the release manifest.
find . -name "latest.json" -not -path "*/deps/*" 2>/dev/null | head -1 | xargs -I{} cp {} "$DIST/latest-${{ matrix.name }}.json" 2>/dev/null || true
- name: Upload build artifacts
if: always() && steps.digicert-setup.conclusion != 'failure'
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
@@ -635,16 +634,6 @@ jobs:
with:
egress-policy: audit
# Sparse-check out the verifier + pubkey before the artifact downloads
# so the checkout cannot clobber ./artifacts.
- name: Checkout updater verifier
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
with:
sparse-checkout: |
.github/scripts/verify-updater-signatures.py
frontend/editor/src-tauri/tauri.conf.json
sparse-checkout-cone-mode: false
- name: Download all Tauri artifacts
uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
with:
@@ -672,106 +661,41 @@ jobs:
- name: Display structure of downloaded files
run: ls -R ./artifacts
# tauri-action only emits latest.json when it also publishes the release
# (tagName/releaseId set). We publish separately via action-gh-release,
# so build latest.json here from the per-platform .sig files.
- name: Generate updater latest.json
env:
VERSION: ${{ needs.determine-matrix.outputs.version }}
TAG: v${{ needs.determine-matrix.outputs.version }}
REPO: ${{ github.repository }}
- name: Generate merged updater latest.json
run: |
python3 - << 'PYEOF'
import json, os, sys
from pathlib import Path
from datetime import datetime, timezone
import json, glob, os, sys
VERSION = os.environ['VERSION']
TAG = os.environ['TAG']
REPO = os.environ['REPO']
ART = Path('./artifacts/tauri')
# Tauri updater looks up {os}-{arch}-{installer} (e.g. linux-x86_64-deb)
# before bare {os}-{arch}, so per-format Linux keys let deb/rpm/appimage
# each self-update from their matching file. macOS universal serves both
# arches from the one .app.tar.gz.
PLATFORM_MAP = [
{
'bundles': ['Stirling-PDF-linux-x86_64.deb'],
'targets': ['linux-x86_64-deb'],
},
{
'bundles': ['Stirling-PDF-linux-x86_64.rpm'],
'targets': ['linux-x86_64-rpm'],
},
{
'bundles': ['Stirling-PDF-linux-x86_64.AppImage'],
'targets': ['linux-x86_64-appimage'],
},
{
'bundles': ['Stirling-PDF-windows-x86_64.msi'],
'targets': ['windows-x86_64-msi', 'windows-x86_64'],
},
{
'bundles': ['Stirling-PDF-macos-universal.app.tar.gz'],
'targets': ['darwin-x86_64', 'darwin-aarch64'],
},
]
# rglob() because download-artifact varies layout: one artifact -> flat,
# many -> nested under <artifact-name>/.
def find_signed(name):
for bundle_path in sorted(ART.rglob(name)):
sig_path = bundle_path.with_name(bundle_path.name + '.sig')
if sig_path.exists():
return bundle_path, sig_path
return None
platforms = {}
skipped = []
for entry in PLATFORM_MAP:
picked = None
for name in entry['bundles']:
picked = find_signed(name)
if picked:
break
if not picked:
skipped.append(
f"{entry['targets']} (no signed bundle among "
f"{entry['bundles']} - TAURI_SIGNING_PRIVATE_KEY unset "
f"or createUpdaterArtifacts disabled?)"
)
continue
bundle_path, sig_path = picked
signature = sig_path.read_text(encoding='utf-8').strip()
url = f"https://github.com/{REPO}/releases/download/{TAG}/{bundle_path.name}"
for target in entry['targets']:
platforms[target] = {'signature': signature, 'url': url}
print(f"Added {entry['targets']} from {bundle_path.name}")
if skipped:
print("Skipped platforms:")
for s in skipped:
print(f" - {s}")
if not platforms:
print(
"WARN: no signed updater bundles found - "
"skipping latest.json generation"
)
files = sorted(glob.glob('./artifacts/tauri/**/latest-*.json', recursive=True))
if not files:
print("No latest-*.json files found — skipping latest.json generation")
sys.exit(0)
manifest = {
'version': VERSION,
'notes': f"See https://github.com/{REPO}/releases/tag/{TAG}",
'pub_date': datetime.now(timezone.utc).strftime('%Y-%m-%dT%H:%M:%SZ'),
'platforms': platforms,
}
merged = None
for f in files:
print(f"Merging: {f}")
with open(f) as fh:
data = json.load(fh)
if merged is None:
merged = dict(data)
merged['platforms'] = {}
else:
# Guard against stale artifacts from a rerun bleeding into a new
# release's latest.json. All per-platform files must agree on version.
if merged.get('version') != data.get('version'):
sys.exit(
f"Version mismatch: {merged.get('version')} vs "
f"{data.get('version')} in {f}"
)
for platform, payload in data.get('platforms', {}).items():
if platform in merged['platforms']:
sys.exit(f"Duplicate platform entry for {platform} in {f}")
merged['platforms'][platform] = payload
out = Path('./artifacts/latest.json')
out.write_text(json.dumps(manifest, indent=2) + '\n', encoding='utf-8')
print(f"Generated {out} with platforms: {sorted(platforms.keys())}")
if merged and merged.get('platforms'):
with open('./artifacts/latest.json', 'w') as fh:
json.dump(merged, fh, indent=2)
print(f"Generated latest.json with platforms: {list(merged['platforms'].keys())}")
PYEOF
- name: Upload merged artifacts for review
@@ -781,37 +705,23 @@ jobs:
path: ./artifacts/
retention-days: 7
# Gate publish on valid updater sigs. Runs after the review upload (so
# artifacts survive for debugging) and before action-gh-release.
- name: Verify updater signatures
run: |
python3 -m pip install --quiet 'cryptography==44.0.0'
python3 .github/scripts/verify-updater-signatures.py \
./artifacts/tauri frontend/editor/src-tauri/tauri.conf.json
# workflow_dispatch path requires platform=='all' so a single-platform
# dispatch can't overwrite an existing release's full latest.json with a
# partial one (action-gh-release defaults overwrite_files:true).
# release / V2-master always build the full matrix so no extra guard needed.
# fail_on_unmatched_files makes a missing latest.json or installer fail loudly
# instead of silently shipping a broken auto-update.
- name: Upload binaries to Release
if: (github.event_name == 'workflow_dispatch' && github.event.inputs.test_mode != 'true' && github.event.inputs.platform == 'all') || github.event_name == 'release' || github.ref == 'refs/heads/V2-master'
if: (github.event_name == 'workflow_dispatch' && github.event.inputs.test_mode != 'true') || github.event_name == 'release' || github.ref == 'refs/heads/V2-master'
uses: softprops/action-gh-release@b4309332981a82ec1c5618f44dd2e27cc8bfbfda # v3.0.0
with:
tag_name: v${{ needs.determine-matrix.outputs.version }}
generate_release_notes: true
fail_on_unmatched_files: true
# Installers + updater payloads + manifest. .sig contents are embedded
# in latest.json so the .sig files themselves are not uploaded.
files: |
./artifacts/**/*.jar
./artifacts/**/*.msi
./artifacts/**/*.msi.zip
./artifacts/**/*.nsis.zip
./artifacts/**/*.dmg
./artifacts/**/*.app.tar.gz
./artifacts/**/*.deb
./artifacts/**/*.rpm
./artifacts/**/*.AppImage
./artifacts/**/*.AppImage.tar.gz
./artifacts/latest.json
draft: false
prerelease: false
+1 -3
View File
@@ -57,8 +57,6 @@ app/core/src/main/resources/static/robots.txt
app/core/src/main/resources/static/pdfium/
app/core/src/main/resources/static/pdfjs/
app/core/src/main/resources/static/vendor/
app/core/src/main/resources/static/**/*.gz
app/core/src/main/resources/static/**/*.br
# Note: Keep backend-managed files like fonts/, css/, js/, pdfjs/, etc.
# Gradle
@@ -281,4 +279,4 @@ docs/type3/signatures/
*.playwright-mcp.png
# Local screenshot artifacts from *-screenshots.spec.ts
frontend/editor/screenshots/
frontend/screenshots/
+3 -14
View File
@@ -187,23 +187,12 @@ tasks:
lint:
desc: "Run linting"
deps: [install]
cmds:
- task: lint:eslint
- task: lint:dpdm
lint:eslint:
desc: "Run ESLint linting"
deps: [install]
cmds:
- npx eslint --max-warnings=0
lint:dpdm:
desc: "Run circular import linting"
deps: [install]
cmds:
# Globs so dpdm walks the whole tree. dpdm expands the braces itself, so this is
# Globs (not a bare dir) so dpdm walks the whole tree — `editor/src`
# alone matched only 2 files. dpdm expands the braces itself, so this is
# shell-agnostic. Covers editor, portal, and the shared design system.
- npx dpdm "editor/src/**/*.{ts,tsx}" "portal/src/**/*.{ts,tsx}" "shared/**/*.{ts,tsx}" --circular --no-warning --no-tree --exit-code circular:1
- 'npx dpdm "editor/src/**/*.{ts,tsx}" "portal/src/**/*.{ts,tsx}" "shared/**/*.{ts,tsx}" --circular --no-warning --no-tree --exit-code circular:1'
lint:fix:
desc: "Auto-fix lint issues"
@@ -1,142 +0,0 @@
package stirling.software.SPDF.pdf.parser;
import java.util.ArrayList;
import java.util.List;
/**
* Detects whether a page is one- or two-column from per-line bounding boxes, and classifies an
* X-span into the column it belongs to. Detection is a midpoint vote at {@code pageWidth / 2}.
*
* <p>Capped at two columns by design — sufficient for the redaction target set (single-column
* documents and IEEE-style two-column papers). 3+ column layouts (newspapers, magazines) and
* off-centre gutters (asymmetric two-column) would need a histogram or clustering approach to
* detect the actual gutter X. (future work)
*
* <p>Coordinates are PDFTextStripper screen space (top-left origin, Y increases downward).
*/
public final class PageColumnLayout {
/**
* Slack when checking "crosses a gutter" so single-pixel overshoots don't mark a line as
* spanning.
*/
public static final float SPAN_SLACK_PT = 2f;
/**
* Slack on each side of the page midpoint inside which a line is considered "spanning"
* (covering both columns) rather than belonging to one side.
*/
private static final float MIDPOINT_SLACK_PT = 30f;
/**
* Minimum line width (points) for a line to count toward the two-column tally. Avoids false
* positives where right-aligned dates, page numbers, or short "Link" fragments next to a
* heading look like a second column when they're really just inline metadata.
*/
private static final float MIN_COLUMN_LINE_WIDTH_PT = 100f;
/**
* Minimum number of clearly leftish AND clearly rightish lines (each of width &ge; {@link
* #MIN_COLUMN_LINE_WIDTH_PT}) required to call the page two-column. Anything below this falls
* back to single-column.
*/
private static final int MIN_SIDE_LINES = 3;
private final List<float[]> columns;
private final List<float[]> gutters;
private PageColumnLayout(List<float[]> columns, List<float[]> gutters) {
this.columns = columns;
this.gutters = gutters;
}
/**
* Determines column layout from per-line bounding boxes ({@code [x1, _, x2, _]}). Counts lines
* whose X-midpoint sits clearly left of, or clearly right of, the page midpoint (with {@link
* #MIDPOINT_SLACK_PT} slack each side). If both sides have at least {@link #MIN_SIDE_LINES}
* lines, the page is treated as two-column with the gutter at the page midpoint. Otherwise it's
* single-column.
*
* <p>Cross-column lines must already be split: callers should feed boxes from a line extractor
* that splits same-Y glyphs at large X gaps (see {@code AllTextLineExtractor}). Without that
* split, IEEE-style aligned-baseline 2-column PDFs produce one wide merged box per row and the
* side tallies all end up classified as "spanning", falling to single-column.
*/
public static PageColumnLayout fromLineBoxes(List<float[]> lineBoxes, float pageWidth) {
if (lineBoxes == null || lineBoxes.isEmpty()) {
return new PageColumnLayout(List.of(new float[] {0f, pageWidth}), List.of());
}
float pageMid = pageWidth / 2f;
int left = 0, right = 0;
for (float[] lb : lineBoxes) {
if (lb == null || lb.length < 3) continue;
float width = lb[2] - lb[0];
// Skip narrow lines — dates, page numbers, "Link" labels next to a heading should
// not, on their own, make a single-column doc look two-column.
if (width < MIN_COLUMN_LINE_WIDTH_PT) continue;
float mid = (lb[0] + lb[2]) * 0.5f;
if (mid < pageMid - MIDPOINT_SLACK_PT) left++;
else if (mid > pageMid + MIDPOINT_SLACK_PT) right++;
}
if (left < MIN_SIDE_LINES || right < MIN_SIDE_LINES) {
return new PageColumnLayout(List.of(new float[] {0f, pageWidth}), List.of());
}
float gutterL = pageMid - MIDPOINT_SLACK_PT;
float gutterR = pageMid + MIDPOINT_SLACK_PT;
return new PageColumnLayout(
List.of(new float[] {0f, gutterL}, new float[] {gutterR, pageWidth}),
List.of(new float[] {gutterL, gutterR}));
}
/** All columns, left-to-right, as {@code [leftX, rightX]} pairs. Never empty. */
public List<float[]> columns() {
return columns;
}
/** Gutters between columns, left-to-right, as {@code [leftX, rightX]} pairs. */
public List<float[]> gutters() {
return gutters;
}
public int columnCount() {
return columns.size();
}
/**
* Returns the column index containing the X-midpoint of {@code [x1, x2]}, falling back to the
* closest column if the midpoint sits inside a gutter.
*/
public int columnOf(float x1, float x2) {
float mid = (x1 + x2) * 0.5f;
int best = 0;
float bestDist = Float.MAX_VALUE;
for (int i = 0; i < columns.size(); i++) {
float[] c = columns.get(i);
if (mid >= c[0] && mid <= c[1]) return i;
float dist = mid < c[0] ? c[0] - mid : mid - c[1];
if (dist < bestDist) {
bestDist = dist;
best = i;
}
}
return best;
}
/**
* Returns every column index whose X-range overlaps {@code [x1, x2]} with at least {@link
* #SPAN_SLACK_PT} of intrusion. A normal in-column line returns one index; a line crossing a
* gutter returns two or more.
*/
public int[] columnsCrossing(float x1, float x2) {
List<Integer> hits = new ArrayList<>();
for (int i = 0; i < columns.size(); i++) {
float[] c = columns.get(i);
float overlap = Math.min(x2, c[1]) - Math.max(x1, c[0]);
if (overlap > SPAN_SLACK_PT) hits.add(i);
}
if (hits.isEmpty()) hits.add(columnOf(x1, x2));
int[] out = new int[hits.size()];
for (int i = 0; i < hits.size(); i++) out[i] = hits.get(i);
return out;
}
}
@@ -1,133 +0,0 @@
package stirling.software.SPDF.pdf.parser;
import java.awt.geom.Point2D;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.pdfbox.contentstream.PDFGraphicsStreamEngine;
import org.apache.pdfbox.cos.COSName;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.graphics.image.PDImage;
import org.apache.pdfbox.util.Matrix;
/**
* PDFGraphicsStreamEngine that intercepts {@code drawImage} calls and records each image's bounding
* box in PDF user-space (origin bottom-left, Y up) by transforming the unit square through the
* current transformation matrix (CTM).
*
* <p>Usage:
*
* <pre>{@code
* PageImageLocator locator = new PageImageLocator(page, pageIndex);
* locator.processPage(page);
* List<ImageBox> boxes = locator.getImageBoxes();
* }</pre>
*
* <p>Each {@link ImageBox} carries the 0-based page index and the axis-aligned bounding box {@code
* (x1, y1, x2, y2)} in PDF user-space coordinates.
*/
public final class PageImageLocator extends PDFGraphicsStreamEngine {
/**
* Bounding box of a raster or vector image found on a PDF page.
*
* @param pageIndex 0-based page index
* @param x1 left edge in PDF user-space (origin bottom-left)
* @param y1 bottom edge in PDF user-space
* @param x2 right edge
* @param y2 top edge
*/
public record ImageBox(int pageIndex, float x1, float y1, float x2, float y2) {}
private final int pageIndex;
private final List<ImageBox> imageBoxes = new ArrayList<>();
private final Point2D.Float currentPoint = new Point2D.Float();
/**
* @param page the PDPage to process
* @param pageIndex 0-based index of this page in the document (stored on each returned {@link
* ImageBox})
*/
public PageImageLocator(PDPage page, int pageIndex) {
super(page);
this.pageIndex = pageIndex;
}
/** Returns all image bounding boxes collected during {@link #processPage}. */
public List<ImageBox> getImageBoxes() {
return imageBoxes;
}
@Override
public void drawImage(PDImage pdImage) throws IOException {
Matrix ctm = getGraphicsState().getCurrentTransformationMatrix();
// An image occupies the unit square (0,0)→(1,1) in image space.
// Transform all four corners through the CTM to get the page-space bounding box.
float a = ctm.getScaleX();
float b = ctm.getShearY();
float c = ctm.getShearX();
float d = ctm.getScaleY();
float e = ctm.getTranslateX();
float f = ctm.getTranslateY();
float[] xs = {e, a + e, c + e, a + c + e};
float[] ys = {f, b + f, d + f, b + d + f};
float x1 = Float.MAX_VALUE, y1 = Float.MAX_VALUE;
float x2 = -Float.MAX_VALUE, y2 = -Float.MAX_VALUE;
for (float x : xs) {
x1 = Math.min(x1, x);
x2 = Math.max(x2, x);
}
for (float y : ys) {
y1 = Math.min(y1, y);
y2 = Math.max(y2, y);
}
imageBoxes.add(new ImageBox(pageIndex, x1, y1, x2, y2));
}
// ---------- required abstract methods (no-op for path operations) ----------
@Override
public void appendRectangle(Point2D p0, Point2D p1, Point2D p2, Point2D p3) {}
@Override
public void clip(int windingRule) {}
@Override
public void moveTo(float x, float y) {
currentPoint.setLocation(x, y);
}
@Override
public void lineTo(float x, float y) {
currentPoint.setLocation(x, y);
}
@Override
public void curveTo(float x1, float y1, float x2, float y2, float x3, float y3) {
currentPoint.setLocation(x3, y3);
}
@Override
public Point2D getCurrentPoint() {
return currentPoint;
}
@Override
public void closePath() {}
@Override
public void endPath() {}
@Override
public void strokePath() {}
@Override
public void fillPath(int windingRule) {}
@Override
public void fillAndStrokePath(int windingRule) {}
@Override
public void shadingFill(COSName shadingName) {}
}
@@ -1,48 +0,0 @@
package stirling.software.common.util.propertyeditor;
import java.beans.PropertyEditorSupport;
import java.util.ArrayList;
import java.util.List;
import lombok.extern.slf4j.Slf4j;
import tools.jackson.core.type.TypeReference;
import tools.jackson.databind.DeserializationFeature;
import tools.jackson.databind.ObjectMapper;
import tools.jackson.databind.json.JsonMapper;
/**
* Binds a multipart form value containing a JSON array into a typed {@code List<T>}. Used for
* endpoints that accept structured list parameters via {@code @ModelAttribute} — the form field
* carries the full JSON array as its value and the editor parses it once.
*/
@Slf4j
public class JsonListPropertyEditor<T> extends PropertyEditorSupport {
private static final ObjectMapper OBJECT_MAPPER =
JsonMapper.builder()
.enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY)
.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
.build();
private final TypeReference<? extends List<T>> typeRef;
public JsonListPropertyEditor(TypeReference<? extends List<T>> typeRef) {
this.typeRef = typeRef;
}
@Override
public void setAsText(String text) throws IllegalArgumentException {
if (text == null || text.trim().isEmpty()) {
setValue(new ArrayList<T>());
return;
}
try {
setValue(OBJECT_MAPPER.readValue(text, typeRef));
} catch (Exception e) {
log.error("Failed to parse JSON list value", e);
throw new IllegalArgumentException(
"Expected a JSON array but could not parse: " + e.getMessage());
}
}
}
@@ -1,41 +0,0 @@
package stirling.software.common.util.propertyeditor;
import java.beans.PropertyEditorSupport;
import lombok.extern.slf4j.Slf4j;
import tools.jackson.databind.DeserializationFeature;
import tools.jackson.databind.ObjectMapper;
import tools.jackson.databind.json.JsonMapper;
/**
* Binds a multipart form value containing a JSON object into a typed {@code T}. Companion to {@link
* JsonListPropertyEditor} for single-object nested fields on {@code @ModelAttribute} endpoints.
*/
@Slf4j
public class JsonObjectPropertyEditor<T> extends PropertyEditorSupport {
private static final ObjectMapper OBJECT_MAPPER =
JsonMapper.builder().disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES).build();
private final Class<T> type;
public JsonObjectPropertyEditor(Class<T> type) {
this.type = type;
}
@Override
public void setAsText(String text) throws IllegalArgumentException {
if (text == null || text.trim().isEmpty()) {
setValue(null);
return;
}
try {
setValue(OBJECT_MAPPER.readValue(text, type));
} catch (Exception e) {
log.error("Failed to parse JSON object value", e);
throw new IllegalArgumentException(
"Expected a JSON object but could not parse: " + e.getMessage());
}
}
}
@@ -0,0 +1,53 @@
package stirling.software.common.util.propertyeditor;
import java.beans.PropertyEditorSupport;
import java.util.ArrayList;
import java.util.List;
import lombok.extern.slf4j.Slf4j;
import tools.jackson.databind.DeserializationFeature;
import tools.jackson.databind.JavaType;
import tools.jackson.databind.ObjectMapper;
import tools.jackson.databind.json.JsonMapper;
/**
* Spring property editor that decodes a JSON string into a typed {@link ArrayList}. Used to bind
* complex list parameters (e.g. {@code List<RedactionArea>}, {@code List<EditTextOperation>}) from
* multipart form fields, where Spring's default binding cannot deserialize a JSON array.
*/
@Slf4j
public class StringToArrayListPropertyEditor<T> extends PropertyEditorSupport {
private final ObjectMapper objectMapper =
JsonMapper.builder()
.enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY)
.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
.build();
private final Class<T> elementType;
public StringToArrayListPropertyEditor(Class<T> elementType) {
this.elementType = elementType;
}
@Override
public void setAsText(String text) throws IllegalArgumentException {
if (text == null || text.trim().isEmpty()) {
setValue(new ArrayList<>());
return;
}
try {
JavaType listType =
objectMapper
.getTypeFactory()
.constructCollectionType(ArrayList.class, elementType);
List<T> list = objectMapper.readValue(text, listType);
setValue(list);
} catch (Exception e) {
log.error("Exception while converting {}", e);
throw new IllegalArgumentException(
"Failed to convert java.lang.String to java.util.List");
}
}
}
@@ -1,149 +0,0 @@
package stirling.software.SPDF.pdf.parser;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.ArrayList;
import java.util.List;
import org.junit.jupiter.api.Test;
/** Unit tests for {@link PageColumnLayout} gutter detection and column classification. */
class PageColumnLayoutTest {
private static final float PAGE_WIDTH = 612f; // Letter portrait
// ── single-column ────────────────────────────────────────────────────────────────────────────
@Test
void singleColumn_oneColumnNoGutters() {
List<float[]> lines = List.of(lineBox(72f, 396f));
PageColumnLayout layout = PageColumnLayout.fromLineBoxes(lines, PAGE_WIDTH);
assertThat(layout.columnCount()).isEqualTo(1);
assertThat(layout.gutters()).isEmpty();
}
@Test
void singleColumn_classifyAnchor_returnsZero() {
PageColumnLayout layout =
PageColumnLayout.fromLineBoxes(List.of(lineBox(72f, 396f)), PAGE_WIDTH);
assertThat(layout.columnOf(100f, 200f)).isEqualTo(0);
}
// ── two-column ───────────────────────────────────────────────────────────────────────────────
@Test
void twoColumn_detectsGutter() {
PageColumnLayout layout =
PageColumnLayout.fromLineBoxes(buildTwoColumnLines(3), PAGE_WIDTH);
assertThat(layout.columnCount()).isEqualTo(2);
assertThat(layout.gutters()).hasSize(1);
float[] gutter = layout.gutters().get(0);
// Gutter is centered on pageWidth/2 with PageColumnLayout.MIDPOINT_SLACK_PT slack each
// side.
float pageMid = PAGE_WIDTH / 2f;
assertThat(gutter[0]).isBetween(pageMid - 40f, pageMid - 20f);
assertThat(gutter[1]).isBetween(pageMid + 20f, pageMid + 40f);
}
@Test
void twoColumn_classifyLeftAndRightAnchors() {
PageColumnLayout layout =
PageColumnLayout.fromLineBoxes(buildTwoColumnLines(3), PAGE_WIDTH);
assertThat(layout.columnOf(100f, 200f)).isEqualTo(0);
assertThat(layout.columnOf(380f, 460f)).isEqualTo(1);
}
@Test
void twoColumn_columnsCrossing_leftLineOnlyHitsLeft() {
PageColumnLayout layout =
PageColumnLayout.fromLineBoxes(buildTwoColumnLines(3), PAGE_WIDTH);
assertThat(layout.columnsCrossing(72f, 280f)).containsExactly(0);
assertThat(layout.columnsCrossing(320f, 540f)).containsExactly(1);
}
@Test
void twoColumn_spanningLine_returnsBothColumns() {
List<float[]> lines = new ArrayList<>(buildTwoColumnLines(3));
// Full-width header that crosses pageWidth/2.
lines.add(lineBox(72f, 396f));
PageColumnLayout layout = PageColumnLayout.fromLineBoxes(lines, PAGE_WIDTH);
assertThat(layout.columnsCrossing(72f, 540f)).containsExactly(0, 1);
assertThat(layout.columnsCrossing(72f, 280f)).containsExactly(0);
}
private static List<float[]> buildTwoColumnLines(int rowsPerColumn) {
List<float[]> lines = new ArrayList<>();
for (int i = 0; i < rowsPerColumn; i++) {
lines.add(lineBox(72f, 136f)); // left column body (72..208)
lines.add(lineBox(320f, 220f)); // right column body (320..540)
}
return lines;
}
// ── three-column ─────────────────────────────────────────────────────────────────────────────
@Test
void threeColumn_collapsesToLeftRightSplit() {
// The midpoint-based detector splits the page at pageWidth/2 and treats anything else as
// single-column or spanning. A genuine 3-column layout collapses to 2 columns; the middle
// column's content ends up classified by midpoint as left or right of pageMid.
List<float[]> lines = new ArrayList<>();
for (int i = 0; i < 6; i++) {
lines.add(lineBox(72f, 150f)); // 72..222
lines.add(lineBox(252f, 150f)); // 252..402
lines.add(lineBox(432f, 150f)); // 432..582
}
PageColumnLayout layout = PageColumnLayout.fromLineBoxes(lines, PAGE_WIDTH);
assertThat(layout.columnCount()).isEqualTo(2);
assertThat(layout.gutters()).hasSize(1);
}
// ── empty page ───────────────────────────────────────────────────────────────────────────────
@Test
void emptyPage_singleColumnFallback() {
PageColumnLayout layout = PageColumnLayout.fromLineBoxes(List.of(), PAGE_WIDTH);
assertThat(layout.columnCount()).isEqualTo(1);
assertThat(layout.gutters()).isEmpty();
}
@Test
void onlyShortFragments_singleColumnFallback() {
// Page numbers / decorations — too narrow to vote either side.
List<float[]> lines = List.of(lineBox(300f, 6f));
PageColumnLayout layout = PageColumnLayout.fromLineBoxes(lines, PAGE_WIDTH);
assertThat(layout.columnCount()).isEqualTo(1);
}
// ── narrow gap should not be confused for a gutter ───────────────────────────────────────────
@Test
void narrowInternalGap_doesNotProduceGutter() {
// Both halves sit left of the page midpoint, so no line votes for a right column and
// detection falls back to single-column.
List<float[]> lines = new ArrayList<>();
lines.add(lineBox(72f, 100f));
lines.add(lineBox(180f, 100f));
for (int i = 0; i < 5; i++) {
lines.add(lineBox(72f, 208f));
}
PageColumnLayout layout = PageColumnLayout.fromLineBoxes(lines, PAGE_WIDTH);
assertThat(layout.columnCount()).isEqualTo(1);
}
// ── helpers ──────────────────────────────────────────────────────────────────────────────────
/** Builds a line bounding box {@code [x1, 0, x1+width, 0]}; Y is unused by detection. */
private static float[] lineBox(float x1, float width) {
return new float[] {x1, 0f, x1 + width, 0f};
}
}
@@ -0,0 +1,163 @@
package stirling.software.common.util.propertyeditor;
import static org.junit.jupiter.api.Assertions.*;
import java.util.List;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import stirling.software.common.model.api.security.RedactionArea;
class StringToArrayListPropertyEditorTest {
private StringToArrayListPropertyEditor<RedactionArea> editor;
@BeforeEach
void setUp() {
editor = new StringToArrayListPropertyEditor<>(RedactionArea.class);
}
@Test
void testSetAsText_ValidJson() {
// Arrange
String json =
"[{\"x\":10.5,\"y\":20.5,\"width\":100.0,\"height\":50.0,\"page\":1,\"color\":\"#FF0000\"}]";
// Act
editor.setAsText(json);
Object value = editor.getValue();
// Assert
assertNotNull(value, "Value should not be null");
assertInstanceOf(List.class, value, "Value should be a List");
@SuppressWarnings("unchecked")
List<RedactionArea> list = (List<RedactionArea>) value;
assertEquals(1, list.size(), "List should have 1 entry");
RedactionArea area = list.get(0);
assertEquals(10.5, area.getX(), "X should be 10.5");
assertEquals(20.5, area.getY(), "Y should be 20.5");
assertEquals(100.0, area.getWidth(), "Width should be 100.0");
assertEquals(50.0, area.getHeight(), "Height should be 50.0");
assertEquals(1, area.getPage(), "Page should be 1");
assertEquals("#FF0000", area.getColor(), "Color should be #FF0000");
}
@Test
void testSetAsText_MultipleItems() {
// Arrange
String json =
"["
+ "{\"x\":10.0,\"y\":20.0,\"width\":100.0,\"height\":50.0,\"page\":1,\"color\":\"#FF0000\"},"
+ "{\"x\":30.0,\"y\":40.0,\"width\":200.0,\"height\":150.0,\"page\":2,\"color\":\"#00FF00\"}"
+ "]";
// Act
editor.setAsText(json);
Object value = editor.getValue();
// Assert
assertNotNull(value, "Value should not be null");
assertInstanceOf(List.class, value, "Value should be a List");
@SuppressWarnings("unchecked")
List<RedactionArea> list = (List<RedactionArea>) value;
assertEquals(2, list.size(), "List should have 2 entries");
RedactionArea area1 = list.get(0);
assertEquals(10.0, area1.getX(), "X should be 10.0");
assertEquals(20.0, area1.getY(), "Y should be 20.0");
assertEquals(1, area1.getPage(), "Page should be 1");
RedactionArea area2 = list.get(1);
assertEquals(30.0, area2.getX(), "X should be 30.0");
assertEquals(40.0, area2.getY(), "Y should be 40.0");
assertEquals(2, area2.getPage(), "Page should be 2");
}
@Test
void testSetAsText_EmptyString() {
// Arrange
String json = "";
// Act
editor.setAsText(json);
Object value = editor.getValue();
// Assert
assertNotNull(value, "Value should not be null");
assertInstanceOf(List.class, value, "Value should be a List");
@SuppressWarnings("unchecked")
List<RedactionArea> list = (List<RedactionArea>) value;
assertTrue(list.isEmpty(), "List should be empty");
}
@Test
void testSetAsText_NullString() {
// Act
editor.setAsText(null);
Object value = editor.getValue();
// Assert
assertNotNull(value, "Value should not be null");
assertInstanceOf(List.class, value, "Value should be a List");
@SuppressWarnings("unchecked")
List<RedactionArea> list = (List<RedactionArea>) value;
assertTrue(list.isEmpty(), "List should be empty");
}
@Test
void testSetAsText_SingleItemAsArray() {
// Arrange - note this is a single object, not an array
String json =
"{\"x\":10.0,\"y\":20.0,\"width\":100.0,\"height\":50.0,\"page\":1,\"color\":\"#FF0000\"}";
// Act
editor.setAsText(json);
Object value = editor.getValue();
// Assert
assertNotNull(value, "Value should not be null");
assertInstanceOf(List.class, value, "Value should be a List");
@SuppressWarnings("unchecked")
List<RedactionArea> list = (List<RedactionArea>) value;
assertEquals(1, list.size(), "List should have 1 entry");
RedactionArea area = list.get(0);
assertEquals(10.0, area.getX(), "X should be 10.0");
assertEquals(20.0, area.getY(), "Y should be 20.0");
}
@Test
void testSetAsText_InvalidJson() {
// Arrange
String json = "invalid json";
// Act & Assert
assertThrows(IllegalArgumentException.class, () -> editor.setAsText(json));
}
@Test
void testSetAsText_UnknownProperties() {
// Arrange - this JSON contains properties not in RedactionArea
// With FAIL_ON_UNKNOWN_PROPERTIES disabled, this should ignore the unknown properties
String json = "[{\"invalid\":\"structure\"}]";
// Act
editor.setAsText(json);
Object value = editor.getValue();
// Assert
assertNotNull(value, "Value should not be null");
assertInstanceOf(List.class, value, "Value should be a List");
@SuppressWarnings("unchecked")
List<RedactionArea> list = (List<RedactionArea>) value;
assertEquals(1, list.size(), "List should have 1 entry (empty object)");
}
}
+1 -17
View File
@@ -207,29 +207,13 @@ def resourcesStaticDir = file('src/main/resources/static')
def generatedFrontendPaths = [
'assets',
'index.html',
'index.html.gz',
'index.html.br',
'sw.js',
'sw.js.gz',
'sw.js.br',
'manifest.json.gz',
'manifest.json.br',
'site.webmanifest.gz',
'site.webmanifest.br',
'browserconfig.xml.gz',
'browserconfig.xml.br',
'manifest-classic.json',
'manifest-classic.json.gz',
'manifest-classic.json.br',
'locales',
'Login',
'classic-logo',
'modern-logo',
'og_images',
'samples',
'pdfium',
'vendor',
'pdfjs'
'manifest-classic.json'
]
tasks.register('npmInstall', Exec) {
@@ -13,7 +13,6 @@ import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.resource.EncodedResourceResolver;
import lombok.RequiredArgsConstructor;
@@ -50,16 +49,14 @@ public class WebMvcConfig implements WebMvcConfigurer {
"/sw.js", "/manifest.json", "/site.webmanifest", "/browserconfig.xml")
.addResourceLocations(staticPath, "classpath:/static/")
.setCacheControl(CacheControl.noStore())
.resourceChain(true)
.addResolver(new EncodedResourceResolver());
.resourceChain(true);
// 2. Vite fingerprinted assets (immutable)
// These already have content hashes in filenames (e.g. index-ChAS4tCC.js)
registry.addResourceHandler("/assets/**")
.addResourceLocations(staticPath + "assets/", "classpath:/static/assets/")
.setCacheControl(IMMUTABLE_ONE_YEAR)
.resourceChain(true)
.addResolver(new EncodedResourceResolver());
.resourceChain(true);
// 3. Media and fonts (immutable)
registry.addResourceHandler("/images/**", "/fonts/**")
@@ -69,8 +66,7 @@ public class WebMvcConfig implements WebMvcConfigurer {
staticPath + "fonts/",
"classpath:/static/fonts/")
.setCacheControl(IMMUTABLE_ONE_YEAR)
.resourceChain(true)
.addResolver(new EncodedResourceResolver());
.resourceChain(true);
// 4. Branding and stable non-fingerprinted assets (1 day + SWR)
// Use stale-while-revalidate to improve perceived performance.
@@ -118,27 +114,19 @@ public class WebMvcConfig implements WebMvcConfigurer {
staticPath + "og_images/",
"classpath:/static/og_images/",
staticPath + "Login/",
"classpath:/static/Login/",
staticPath + "icons/",
"classpath:/static/icons/",
staticPath + "modern-logo/",
"classpath:/static/modern-logo/",
staticPath + "classic-logo/",
"classpath:/static/classic-logo/")
"classpath:/static/Login/")
.setCacheControl(
CacheControl.maxAge(Duration.ofDays(1))
.cachePublic()
.staleWhileRevalidate(Duration.ofDays(7)))
.resourceChain(true)
.addResolver(new EncodedResourceResolver());
.resourceChain(true);
// 5. Catch-all (SPA fallback)
// Must check with server to ensure index.html is always fresh.
registry.addResourceHandler("/**")
.addResourceLocations(staticPath, "classpath:/static/")
.setCacheControl(NO_CACHE)
.resourceChain(true)
.addResolver(new EncodedResourceResolver());
.resourceChain(true);
}
@Override
@@ -39,9 +39,7 @@ import stirling.software.common.util.GeneralUtils;
import stirling.software.common.util.TempFile;
import stirling.software.common.util.TempFileManager;
import stirling.software.common.util.WebResponseUtils;
import stirling.software.common.util.propertyeditor.JsonListPropertyEditor;
import tools.jackson.core.type.TypeReference;
import stirling.software.common.util.propertyeditor.StringToArrayListPropertyEditor;
/**
* Find/replace text editing for PDFs. Round-trips through {@link PdfJsonConversionService}: the
@@ -75,7 +73,7 @@ public class EditTextController {
binder.registerCustomEditor(
List.class,
"edits",
new JsonListPropertyEditor<>(new TypeReference<List<EditTextOperation>>() {}));
new StringToArrayListPropertyEditor<>(EditTextOperation.class));
}
@AutoJobPostMapping(
@@ -1,127 +0,0 @@
package stirling.software.SPDF.controller.api.security;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.text.PDFTextStripper;
import org.apache.pdfbox.text.TextPosition;
/**
* PDFTextStripper subclass that collects all text positions and groups them into line-level
* bounding boxes.
*
* <p>Two outputs are maintained in parallel:
*
* <ul>
* <li>{@link #getLineBoxes()} returns {@code [x1, pdfYbottom, x2, pdfYtop]} in PDF user-space
* (origin bottom-left, Y up). This is what existing callers expect.
* <li>{@link #getScreenLineBoxes()} returns {@code [x1, screenYtop, x2, screenYbottom]} computed
* directly from glyph positions without a PDF↔screen round-trip — used by column-aware
* redaction where ulp-level drift in the round-trip caused false rejects against anchors.
* </ul>
*
* <p>Lines are flushed not only on Y jumps but also on large X gaps within the same Y row. That way
* left-column glyphs and right-column glyphs that happen to share a baseline (common in IEEE
* conference templates) get emitted as two distinct line boxes instead of one wide merged box.
*/
final class AllTextLineExtractor extends PDFTextStripper {
/** Min vertical jump (screen Y) before the next glyph is treated as a new line. */
private static final float LINE_Y_TOLERANCE = 3.0f;
/**
* Min horizontal gap (screen X) between consecutive glyphs on the same Y that indicates a
* column boundary. Chosen large enough to not split normal inter-word spacing (~6–10pt for 11pt
* text) but small enough to catch standard column gutters (typically ≥15pt).
*/
private static final float COLUMN_GAP_X = 14f;
private final float pageHeight;
private final List<float[]> lineBoxes = new ArrayList<>();
private final List<float[]> screenLineBoxes = new ArrayList<>();
private final List<TextPosition> currentLine = new ArrayList<>();
private float lastScreenY = Float.NaN;
private float lastGlyphRight = Float.NaN;
AllTextLineExtractor(int pageNumber, float pageHeight) throws IOException {
this.pageHeight = pageHeight;
setStartPage(pageNumber);
setEndPage(pageNumber);
setSortByPosition(true);
}
List<float[]> getLineBoxes() {
return lineBoxes;
}
/**
* Returns line boxes as {@code [x1, screenYtop, x2, screenYbottom]}. {@code screenYtop} is the
* minimum {@code TextPosition.getY() - getHeight()} on the line and {@code screenYbottom} is
* the maximum {@code getY()} (the line's baseline). These values come straight from PDFBox
* without going through {@code pageHeight - …}, so they're stable for ulp-sensitive comparisons
* against anchor screen Ys.
*/
List<float[]> getScreenLineBoxes() {
return screenLineBoxes;
}
@Override
protected void writeString(String text, List<TextPosition> positions) {
for (TextPosition tp : positions) {
// Skip whitespace-only positions (spaces, newline markers, indent characters).
// These have a TextPosition but no visible glyph; including them causes
// space-only "lines" to produce degenerate segments that appear as thin
// black bars after redaction.
String unicode = tp.getUnicode();
if (unicode == null || unicode.isBlank()) {
continue;
}
float screenY = tp.getY();
float screenX = tp.getX();
boolean yJump =
!Float.isNaN(lastScreenY) && Math.abs(screenY - lastScreenY) > LINE_Y_TOLERANCE;
boolean xJump =
!Float.isNaN(lastGlyphRight) && (screenX - lastGlyphRight) > COLUMN_GAP_X;
if (yJump || xJump) {
flushLine();
}
lastScreenY = screenY;
lastGlyphRight = screenX + tp.getWidth();
currentLine.add(tp);
}
}
@Override
protected void endPage(PDPage page) throws IOException {
flushLine();
super.endPage(page);
}
private void flushLine() {
if (currentLine.isEmpty()) {
return;
}
float minX = Float.MAX_VALUE, maxX = -Float.MAX_VALUE;
float minScreenY = Float.MAX_VALUE, maxScreenY = -Float.MAX_VALUE;
for (TextPosition tp : currentLine) {
minX = Math.min(minX, tp.getX());
maxX = Math.max(maxX, tp.getX() + tp.getWidth());
minScreenY = Math.min(minScreenY, tp.getY() - tp.getHeight());
maxScreenY = Math.max(maxScreenY, tp.getY());
}
emitSegment(minX, maxX, minScreenY, maxScreenY);
currentLine.clear();
lastScreenY = Float.NaN;
lastGlyphRight = Float.NaN;
}
private void emitSegment(float minX, float maxX, float minScreenY, float maxScreenY) {
float pdfY1 = pageHeight - maxScreenY; // bottom in PDF coords
float pdfY2 = pageHeight - minScreenY; // top in PDF coords
lineBoxes.add(new float[] {minX, pdfY1, maxX, pdfY2});
screenLineBoxes.add(new float[] {minX, minScreenY, maxX, maxScreenY});
}
}
@@ -1,403 +0,0 @@
package stirling.software.SPDF.controller.api.security;
import java.awt.Color;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.PDPageTree;
import org.apache.pdfbox.pdmodel.common.PDRectangle;
import org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotation;
import org.springframework.stereotype.Service;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import stirling.software.SPDF.model.PDFText;
import stirling.software.SPDF.model.api.security.ManualRedactPdfRequest;
import stirling.software.SPDF.pdf.parser.PageImageLocator;
import stirling.software.common.model.api.security.RedactionArea;
import stirling.software.common.util.GeneralUtils;
import stirling.software.common.util.PdfUtils;
import stirling.software.common.util.TempFile;
import stirling.software.common.util.TempFileManager;
@Service
@Slf4j
@RequiredArgsConstructor
class ManualRedactionService {
private static final float DEFAULT_TEXT_PADDING_MULTIPLIER = 0.6f;
private static final float REDACTION_WIDTH_REDUCTION_FACTOR = 0.9f;
private final TempFileManager tempFileManager;
// -----------------------------------------------------------------------
// Area and page redaction
// -----------------------------------------------------------------------
void redactAreas(List<RedactionArea> redactionAreas, PDDocument document, PDPageTree allPages)
throws IOException {
if (redactionAreas == null || redactionAreas.isEmpty()) {
return;
}
Map<Integer, List<RedactionArea>> redactionsByPage = new HashMap<>();
for (RedactionArea redactionArea : redactionAreas) {
if (redactionArea.getPage() == null
|| redactionArea.getPage() <= 0
|| redactionArea.getHeight() == null
|| redactionArea.getHeight() <= 0.0D
|| redactionArea.getWidth() == null
|| redactionArea.getWidth() <= 0.0D) {
continue;
}
redactionsByPage
.computeIfAbsent(redactionArea.getPage(), k -> new ArrayList<>())
.add(redactionArea);
}
for (Map.Entry<Integer, List<RedactionArea>> entry : redactionsByPage.entrySet()) {
Integer pageNumber = entry.getKey();
List<RedactionArea> areasForPage = entry.getValue();
if (pageNumber > allPages.getCount()) {
continue;
}
PDPage page = allPages.get(pageNumber - 1);
try (PDPageContentStream contentStream =
new PDPageContentStream(
document, page, PDPageContentStream.AppendMode.APPEND, true, true)) {
contentStream.saveGraphicsState();
for (RedactionArea redactionArea : areasForPage) {
Color redactColor = decodeOrDefault(redactionArea.getColor());
contentStream.setNonStrokingColor(redactColor);
float x = redactionArea.getX().floatValue();
float y = redactionArea.getY().floatValue();
float width = redactionArea.getWidth().floatValue();
float height = redactionArea.getHeight().floatValue();
float pdfY = page.getBBox().getHeight() - y - height;
contentStream.addRect(x, pdfY, width, height);
contentStream.fill();
}
contentStream.restoreGraphicsState();
}
}
}
void redactPages(ManualRedactPdfRequest request, PDDocument document, PDPageTree allPages)
throws IOException {
Color redactColor = decodeOrDefault(request.getPageRedactionColor());
List<Integer> pageNumbers = getPageNumbers(request, allPages.getCount());
for (Integer pageNumber : pageNumbers) {
PDPage page = allPages.get(pageNumber);
try (PDPageContentStream contentStream =
new PDPageContentStream(
document, page, PDPageContentStream.AppendMode.APPEND, true, true)) {
contentStream.setNonStrokingColor(redactColor);
PDRectangle box = page.getBBox();
contentStream.addRect(0, 0, box.getWidth(), box.getHeight());
contentStream.fill();
}
}
}
// -----------------------------------------------------------------------
// Overlay drawing
// -----------------------------------------------------------------------
void redactFoundText(
PDDocument document,
List<PDFText> blocks,
float customPadding,
Color redactColor,
boolean isTextRemovalMode)
throws IOException {
var allPages = document.getDocumentCatalog().getPages();
Map<Integer, List<PDFText>> blocksByPage = new HashMap<>();
for (PDFText block : blocks) {
blocksByPage.computeIfAbsent(block.getPageIndex(), k -> new ArrayList<>()).add(block);
}
for (Map.Entry<Integer, List<PDFText>> entry : blocksByPage.entrySet()) {
Integer pageIndex = entry.getKey();
List<PDFText> pageBlocks = entry.getValue();
if (pageIndex >= allPages.getCount()) {
continue;
}
var page = allPages.get(pageIndex);
try (PDPageContentStream contentStream =
new PDPageContentStream(
document, page, PDPageContentStream.AppendMode.APPEND, true, true)) {
contentStream.saveGraphicsState();
try {
contentStream.setNonStrokingColor(redactColor);
PDRectangle pageBox = page.getBBox();
for (PDFText block : pageBlocks) {
float padding =
(block.getY2() - block.getY1()) * DEFAULT_TEXT_PADDING_MULTIPLIER
+ customPadding;
float originalWidth = block.getX2() - block.getX1();
float boxWidth;
float boxX;
if (isTextRemovalMode) {
boxWidth = originalWidth * REDACTION_WIDTH_REDUCTION_FACTOR;
float widthReduction = originalWidth - boxWidth;
boxX = block.getX1() + (widthReduction / 2);
} else {
boxWidth = originalWidth;
boxX = block.getX1();
}
contentStream.addRect(
boxX,
pageBox.getHeight() - block.getY2() - padding,
boxWidth,
block.getY2() - block.getY1() + 2 * padding);
}
contentStream.fill();
} finally {
contentStream.restoreGraphicsState();
}
}
// Remove annotations whose bounding rect overlaps a redacted block, to prevent
// users from hovering over redacted URLs and seeing the underlying destination.
try {
float pageH = page.getBBox().getHeight();
List<PDAnnotation> kept = new ArrayList<>();
for (PDAnnotation ann : page.getAnnotations()) {
PDRectangle ar = ann.getRectangle();
boolean overlaps = false;
if (ar != null) {
for (PDFText block : pageBlocks) {
float padding =
(block.getY2() - block.getY1())
* DEFAULT_TEXT_PADDING_MULTIPLIER
+ customPadding;
float bx1 = block.getX1();
float bx2 = block.getX2();
float by1 = pageH - block.getY2() - padding;
float by2 = pageH - block.getY1() + padding;
if (ar.getLowerLeftX() < bx2
&& ar.getUpperRightX() > bx1
&& ar.getLowerLeftY() < by2
&& ar.getUpperRightY() > by1) {
overlaps = true;
break;
}
}
}
if (!overlaps) {
kept.add(ann);
}
}
page.setAnnotations(kept);
} catch (Exception e) {
log.debug(
"[redact] could not remove annotations on page {}: {}",
pageIndex,
e.getMessage());
}
}
}
void redactImageBoxes(PDDocument document, List<float[]> imageBoxes, Color color)
throws IOException {
Map<Integer, List<float[]>> byPage = new HashMap<>();
for (float[] box : imageBoxes) {
byPage.computeIfAbsent((int) box[0], k -> new ArrayList<>()).add(box);
}
PDPageTree pages = document.getDocumentCatalog().getPages();
for (Map.Entry<Integer, List<float[]>> entry : byPage.entrySet()) {
int pageIdx = entry.getKey();
if (pageIdx < 0 || pageIdx >= pages.getCount()) {
log.warn("[redact/execute] image box references out-of-range page {}", pageIdx);
continue;
}
PDPage page = pages.get(pageIdx);
try (PDPageContentStream cs =
new PDPageContentStream(
document, page, PDPageContentStream.AppendMode.APPEND, true, true)) {
cs.saveGraphicsState();
cs.setNonStrokingColor(color);
for (float[] box : entry.getValue()) {
float x1 = box[1], y1 = box[2], x2 = box[3], y2 = box[4];
cs.addRect(x1, y1, x2 - x1, y2 - y1);
}
cs.fill();
cs.restoreGraphicsState();
}
}
}
// -----------------------------------------------------------------------
// Page element extraction
// -----------------------------------------------------------------------
/**
* Returns bounding boxes for every text line and image on {@code page} in PDF user-space
* coordinates: {@code [x1, y1, x2, y2]} (origin bottom-left, Y increases upward).
*/
List<float[]> extractPageElementBoxes(PDDocument document, PDPage page, int pageIndex)
throws IOException {
List<float[]> boxes = new ArrayList<>();
AllTextLineExtractor textExtractor =
new AllTextLineExtractor(pageIndex + 1, page.getBBox().getHeight());
textExtractor.getText(document);
boxes.addAll(textExtractor.getLineBoxes());
PageImageLocator imgLocator = new PageImageLocator(page, pageIndex);
imgLocator.processPage(page);
for (PageImageLocator.ImageBox imgBox : imgLocator.getImageBoxes()) {
boxes.add(new float[] {imgBox.x1(), imgBox.y1(), imgBox.x2(), imgBox.y2()});
}
return boxes;
}
// -----------------------------------------------------------------------
// Finalization
// -----------------------------------------------------------------------
TempFile finalizeRedaction(
PDDocument document,
Map<Integer, List<PDFText>> allFoundTextsByPage,
String colorString,
float customPadding,
Boolean convertToImage,
boolean isTextRemovalMode)
throws IOException {
List<PDFText> allFoundTexts = new ArrayList<>();
for (List<PDFText> pageTexts : allFoundTextsByPage.values()) {
allFoundTexts.addAll(pageTexts);
}
if (!allFoundTexts.isEmpty()) {
Color redactColor = decodeOrDefault(colorString);
redactFoundText(document, allFoundTexts, customPadding, redactColor, isTextRemovalMode);
cleanDocumentMetadata(document);
}
if (Boolean.TRUE.equals(convertToImage)) {
try (PDDocument convertedPdf = PdfUtils.convertPdfToPdfImage(document)) {
cleanDocumentMetadata(convertedPdf);
TempFile tempOut = tempFileManager.createManagedTempFile(".pdf");
try {
convertedPdf.save(tempOut.getFile());
} catch (IOException e) {
tempOut.close();
throw e;
}
log.info(
"Redaction finalized (image mode): {} pages ➜ {} KB",
convertedPdf.getNumberOfPages(),
tempOut.getFile().length() / 1024);
return tempOut;
}
}
TempFile tempOut = tempFileManager.createManagedTempFile(".pdf");
try {
document.save(tempOut.getFile());
} catch (IOException e) {
tempOut.close();
throw e;
}
log.info(
"Redaction finalized: {} pages ➜ {} KB",
document.getNumberOfPages(),
tempOut.getFile().length() / 1024);
return tempOut;
}
private void cleanDocumentMetadata(PDDocument document) {
try {
var documentInfo = document.getDocumentInformation();
if (documentInfo != null) {
documentInfo.setAuthor(null);
documentInfo.setSubject(null);
documentInfo.setKeywords(null);
documentInfo.setModificationDate(java.util.Calendar.getInstance());
log.debug("Cleaned document metadata for security");
}
if (document.getDocumentCatalog() != null) {
try {
document.getDocumentCatalog().setMetadata(null);
} catch (Exception e) {
log.debug("Could not clear XMP metadata: {}", e.getMessage());
}
}
} catch (Exception e) {
log.warn("Failed to clean document metadata: {}", e.getMessage());
}
}
// -----------------------------------------------------------------------
// Utilities
// -----------------------------------------------------------------------
static Color decodeOrDefault(String hex) {
if (hex == null) {
return Color.BLACK;
}
String colorString = hex.startsWith("#") ? hex : "#" + hex;
try {
return Color.decode(colorString);
} catch (NumberFormatException e) {
return Color.BLACK;
}
}
private List<Integer> getPageNumbers(ManualRedactPdfRequest request, int pagesCount) {
String pageNumbersInput = request.getPageNumbers();
String[] parsedPageNumbers =
pageNumbersInput != null ? pageNumbersInput.split(",") : new String[0];
List<Integer> pageNumbers =
GeneralUtils.parsePageList(parsedPageNumbers, pagesCount, false);
Collections.sort(pageNumbers);
return pageNumbers;
}
}
@@ -1,174 +0,0 @@
package stirling.software.SPDF.controller.api.security;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.text.PDFTextStripper;
import org.apache.pdfbox.text.TextPosition;
import lombok.extern.slf4j.Slf4j;
import stirling.software.SPDF.model.PDFText;
/**
* Scans a PDF document once and matches all provided patterns in a single pass, collecting
* bounding-box positions for every match. Use in place of creating one {@code TextFinder} per
* search term to avoid O(n) full-document scans.
*/
@Slf4j
final class MultiPatternTextFinder extends PDFTextStripper {
private static final long REGEX_MATCH_TIMEOUT_SECONDS = 30;
private static final ExecutorService REGEX_EXECUTOR =
Executors.newVirtualThreadPerTaskExecutor();
private final List<Pattern> patterns;
private final Map<Integer, List<PDFText>> foundTextsByPage = new HashMap<>();
private final List<TextPosition> pageTextPositions = new ArrayList<>();
private final StringBuilder pageTextBuilder = new StringBuilder();
MultiPatternTextFinder(List<Pattern> patterns) throws IOException {
this.patterns = patterns;
this.setWordSeparator(" ");
this.setLineSeparator("\n");
}
Map<Integer, List<PDFText>> getFoundTextsByPage() {
return foundTextsByPage;
}
@Override
protected void startPage(PDPage page) throws IOException {
super.startPage(page);
pageTextPositions.clear();
pageTextBuilder.setLength(0);
}
@Override
protected void writeString(String text, List<TextPosition> textPositions) {
pageTextBuilder.append(text);
pageTextPositions.addAll(textPositions);
}
@Override
protected void writeWordSeparator() {
pageTextBuilder.append(getWordSeparator());
pageTextPositions.add(null);
}
@Override
protected void writeLineSeparator() {
pageTextBuilder.append(getLineSeparator());
pageTextPositions.add(null);
}
@Override
protected void endPage(PDPage page) throws IOException {
String text = pageTextBuilder.toString();
if (!text.isEmpty()) {
int pageIndex = getCurrentPageNo() - 1;
for (Pattern pattern : patterns) {
Matcher matcher = pattern.matcher(text);
while (safeFind(matcher)) {
PDFText pdfText = resolveMatchPosition(matcher, pageIndex);
if (pdfText != null) {
foundTextsByPage
.computeIfAbsent(pageIndex, k -> new ArrayList<>())
.add(pdfText);
}
}
}
}
super.endPage(page);
}
/**
* Wraps a single {@code matcher.find()} call with a {@value #REGEX_MATCH_TIMEOUT_SECONDS}
* second timeout. Prevents pathological regex backtracking from blocking the request
* indefinitely; per-match timeout so fast legitimate scans are unaffected.
*/
private static boolean safeFind(Matcher matcher) throws IOException {
Future<Boolean> future =
REGEX_EXECUTOR.submit((java.util.concurrent.Callable<Boolean>) matcher::find);
try {
return future.get(REGEX_MATCH_TIMEOUT_SECONDS, TimeUnit.SECONDS);
} catch (TimeoutException e) {
future.cancel(true);
throw new IOException(
"Regex match timed out after "
+ REGEX_MATCH_TIMEOUT_SECONDS
+ "s — pattern may cause catastrophic backtracking");
} catch (InterruptedException e) {
future.cancel(true);
Thread.currentThread().interrupt();
throw new IOException("Regex match interrupted", e);
} catch (ExecutionException e) {
Throwable cause = e.getCause();
if (cause instanceof IOException ioEx) throw ioEx;
throw new IOException("Regex match failed: " + cause.getMessage(), cause);
}
}
private PDFText resolveMatchPosition(Matcher matcher, int pageIndex) {
int matchStart = matcher.start();
int matchEnd = matcher.end();
float minX = Float.MAX_VALUE;
float minY = Float.MAX_VALUE;
float maxX = Float.MIN_VALUE;
float maxY = Float.MIN_VALUE;
boolean foundPosition = false;
for (int i = matchStart; i < matchEnd; i++) {
if (i >= pageTextPositions.size()) break;
TextPosition pos = pageTextPositions.get(i);
if (pos != null) {
foundPosition = true;
minX = Math.min(minX, pos.getX());
maxX = Math.max(maxX, pos.getX() + pos.getWidth());
minY = Math.min(minY, pos.getY() - pos.getHeight());
maxY = Math.max(maxY, pos.getY());
}
}
if (!foundPosition && matchStart < pageTextPositions.size()) {
for (int i = Math.max(0, matchStart - 5);
i < Math.min(pageTextPositions.size(), matchEnd + 5);
i++) {
TextPosition pos = pageTextPositions.get(i);
if (pos != null) {
foundPosition = true;
minX = Math.min(minX, pos.getX());
maxX = Math.max(maxX, pos.getX() + pos.getWidth());
minY = Math.min(minY, pos.getY() - pos.getHeight());
maxY = Math.max(maxY, pos.getY());
break;
}
}
}
if (!foundPosition) {
log.warn(
"Found text match '{}' but no valid position data at {}-{}",
matcher.group(),
matchStart,
matchEnd);
return null;
}
return new PDFText(pageIndex, minX, minY, maxX, maxY, matcher.group());
}
}
@@ -1,850 +0,0 @@
package stirling.software.SPDF.controller.api.security;
import java.awt.Color;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
import org.apache.pdfbox.cos.COSName;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.PDPageTree;
import org.apache.pdfbox.pdmodel.PDResources;
import org.apache.pdfbox.pdmodel.common.PDRectangle;
import org.springframework.stereotype.Service;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import stirling.software.SPDF.model.PDFText;
import stirling.software.SPDF.model.api.security.RedactExecuteRequest;
import stirling.software.SPDF.model.api.security.RedactExecuteRequest.ImageBox;
import stirling.software.SPDF.model.api.security.RedactExecuteRequest.RedactStyle;
import stirling.software.SPDF.model.api.security.RedactExecuteRequest.TextRange;
import stirling.software.SPDF.pdf.parser.PageColumnLayout;
import stirling.software.SPDF.pdf.parser.PageImageLocator;
import stirling.software.common.service.CustomPDFDocumentFactory;
import stirling.software.common.util.ExceptionUtils;
import stirling.software.common.util.TempFile;
@Service
@Slf4j
@RequiredArgsConstructor
class RedactExecuteService {
private final CustomPDFDocumentFactory pdfDocumentFactory;
private final ManualRedactionService manualRedactionService;
private final TextRedactionService textRedactionService;
TempFile execute(RedactExecuteRequest request) throws IOException {
RedactStyle style = request.getStyle() != null ? request.getStyle() : new RedactStyle();
List<String> textValues = orEmpty(request.getTextValues());
List<String> regexPatterns = orEmpty(request.getRegexPatterns());
List<Integer> wipePages = orEmpty(request.getWipePages());
List<TextRange> ranges = orEmpty(request.getRanges());
List<ImageBox> imageBoxes = orEmpty(request.getImageBoxes());
boolean hasTargets =
!textValues.isEmpty()
|| !regexPatterns.isEmpty()
|| !wipePages.isEmpty()
|| !ranges.isEmpty()
|| !imageBoxes.isEmpty()
|| request.getRedactImagePages() != null;
if (!hasTargets) {
throw ExceptionUtils.createIllegalArgumentException(
"error.redaction.no.targets", "No redaction targets provided");
}
boolean overlayOnly =
RedactExecuteRequest.RedactionStrategy.OVERLAY_ONLY.equals(style.getStrategy());
boolean imageFinalize =
RedactExecuteRequest.RedactionStrategy.IMAGE_FINALIZE.equals(style.getStrategy());
boolean convertToImage = imageFinalize || style.isConvertToImage();
boolean hasTextOps = !textValues.isEmpty() || !regexPatterns.isEmpty();
log.info(
"[redact/execute] strategy={} textValues={} regexPatterns={} wipePages={} ranges={} imageBoxes={} imagePages={}",
style.getStrategy(),
textValues.size(),
regexPatterns.size(),
wipePages.size(),
ranges.size(),
imageBoxes.size(),
request.getRedactImagePages());
if (request.getFileInput() == null) {
throw ExceptionUtils.createFileNullOrEmptyException();
}
PDDocument document = null;
try {
document = pdfDocumentFactory.load(request.getFileInput());
// Single-pass text scan: collect all text-based targets so we run the PDF
// stripper only once across the entire execute() call rather than once per target.
Map<Integer, List<PDFText>> foundTexts =
hasTextOps ? collectTextMatches(document, request) : new HashMap<>();
int totalMatches = foundTexts.values().stream().mapToInt(List::size).sum();
log.info(
"[redact/execute] scan complete: {} text matches across {} pages",
totalMatches,
foundTexts.size());
// Text removal (content-stream rewriting) — skipped in overlay-only mode.
boolean needsOverlayOnly = overlayOnly;
if (hasTextOps && !foundTexts.isEmpty() && !overlayOnly) {
needsOverlayOnly = applyTextRemoval(document, request);
} else if (overlayOnly) {
log.info(
"[redact/execute] overlay-only mode requested — skipping content-stream rewriting");
}
// Reload fresh document on fallback so we overlay onto clean content.
if (needsOverlayOnly && !foundTexts.isEmpty()) {
log.info("[redact/execute] reloading document for clean overlay pass");
document.close();
document = pdfDocumentFactory.load(request.getFileInput());
foundTexts.clear();
if (hasTextOps) {
foundTexts.putAll(collectTextMatches(document, request));
}
}
// Non-text operations.
Map<Integer, PageColumnLayout> layoutCache = new HashMap<>();
if (!wipePages.isEmpty()) {
applyPageWipe(document, wipePages, style);
}
for (TextRange range : ranges) {
applyRangeRedaction(document, range, style, layoutCache);
}
for (ImageBox box : imageBoxes) {
applyImageBoxRedaction(document, box, style);
}
if (request.getRedactImagePages() != null) {
applyAllImagesRedaction(document, request.getRedactImagePages(), style);
}
return manualRedactionService.finalizeRedaction(
document,
foundTexts,
style.getColor(),
style.getPadding(),
convertToImage,
!needsOverlayOnly);
} catch (Exception e) {
log.error("Execute redaction failed: {}", e.getMessage(), e);
throw new RuntimeException("Failed to perform PDF redaction: " + e.getMessage(), e);
} finally {
if (document != null) {
try {
document.close();
} catch (IOException e) {
log.warn("Failed to close document: {}", e.getMessage());
}
}
}
}
// -----------------------------------------------------------------------
// Single-pass text scan (one stripper pass per execute() call)
// -----------------------------------------------------------------------
/**
* Runs a single PDF text-stripper pass over all text-based targets and returns the merged hit
* map.
*/
private Map<Integer, List<PDFText>> collectTextMatches(
PDDocument document, RedactExecuteRequest request) {
Map<Integer, List<PDFText>> found = new HashMap<>();
String[] terms = cleanStrings(request.getTextValues());
if (terms.length > 0) {
textRedactionService
.findTextToRedact(document, terms, false, false)
.forEach(
(page, hits) ->
found.computeIfAbsent(page, k -> new ArrayList<>())
.addAll(hits));
}
String[] patterns = cleanStrings(request.getRegexPatterns());
if (patterns.length > 0) {
textRedactionService
.findTextToRedact(document, patterns, true, false)
.forEach(
(page, hits) ->
found.computeIfAbsent(page, k -> new ArrayList<>())
.addAll(hits));
}
return found;
}
// -----------------------------------------------------------------------
// Text removal (content-stream rewriting)
// -----------------------------------------------------------------------
/**
* Attempts content-stream text removal for all text/regex targets. Returns {@code true} if the
* document fell back to overlay-only mode.
*/
private boolean applyTextRemoval(PDDocument document, RedactExecuteRequest request) {
try {
boolean fallback = false;
String[] terms = cleanStrings(request.getTextValues());
if (terms.length > 0) {
Map<Integer, List<PDFText>> exactFound =
textRedactionService.findTextToRedact(document, terms, false, false);
if (!exactFound.isEmpty()) {
fallback |=
textRedactionService.performTextReplacement(
document, exactFound, terms, false, false);
}
}
String[] patterns = cleanStrings(request.getRegexPatterns());
if (patterns.length > 0) {
Map<Integer, List<PDFText>> regexFound =
textRedactionService.findTextToRedact(document, patterns, true, false);
if (!regexFound.isEmpty()) {
fallback |=
textRedactionService.performTextReplacement(
document, regexFound, patterns, true, false);
}
}
if (fallback) {
log.warn(
"[redact/execute] font compatibility issue — falling back to overlay-only");
} else {
log.info("[redact/execute] content-stream text removal applied successfully");
}
return fallback;
} catch (Exception e) {
log.warn(
"[redact/execute] text removal failed, falling back to overlay: {}",
e.getMessage());
return true;
}
}
// -----------------------------------------------------------------------
// Per-operation dispatch methods
// -----------------------------------------------------------------------
private void applyPageWipe(PDDocument document, List<Integer> pageNumbers, RedactStyle style)
throws IOException {
List<Integer> pageIndices = toZeroBasedIndices(pageNumbers);
if (pageIndices.isEmpty()) return;
PDPageTree allPages = document.getDocumentCatalog().getPages();
Color pageColor = ManualRedactionService.decodeOrDefault(style.getColor());
Collections.sort(pageIndices);
log.info("[redact/execute] full-page wipe: {} pages ({})", pageIndices.size(), pageIndices);
Map<Integer, List<float[]>> pageElementBoxes = new HashMap<>();
for (Integer idx : pageIndices) {
if (idx >= 0 && idx < allPages.getCount()) {
try {
pageElementBoxes.put(
idx,
manualRedactionService.extractPageElementBoxes(
document, allPages.get(idx), idx));
} catch (Exception e) {
log.warn(
"[redact/execute] element extraction failed for page {}: {}",
idx,
e.getMessage());
}
}
}
for (Integer idx : pageIndices) {
if (idx >= 0 && idx < allPages.getCount()) {
PDPage page = allPages.get(idx);
List<float[]> elementBoxes =
pageElementBoxes.getOrDefault(idx, Collections.emptyList());
page.getCOSObject().removeItem(COSName.CONTENTS);
page.setResources(new PDResources());
try (PDPageContentStream cs = new PDPageContentStream(document, page)) {
cs.setNonStrokingColor(pageColor);
if (elementBoxes.isEmpty()) {
PDRectangle box = page.getBBox();
cs.addRect(0, 0, box.getWidth(), box.getHeight());
} else {
log.info(
"[redact/execute] page {}: drawing {} element boxes",
idx + 1,
elementBoxes.size());
for (float[] r : elementBoxes) {
cs.addRect(r[0], r[1], r[2] - r[0], r[3] - r[1]);
}
}
cs.fill();
}
}
}
}
private void applyRangeRedaction(
PDDocument document,
TextRange range,
RedactStyle style,
Map<Integer, PageColumnLayout> layoutCache)
throws IOException {
String rangeStart = trimOrEmpty(range.startString());
String rangeEnd = trimOrEmpty(range.endString());
log.info("[redact/execute] range redaction: start='{}' end='{}'", rangeStart, rangeEnd);
try {
List<PDFText> blocks = collectRangeBlocks(document, rangeStart, rangeEnd, layoutCache);
if (!blocks.isEmpty()) {
manualRedactionService.redactFoundText(
document,
blocks,
style.getPadding(),
ManualRedactionService.decodeOrDefault(style.getColor()),
false);
} else {
log.warn(
"[redact/execute] range not found: start='{}' end='{}'",
rangeStart,
rangeEnd);
}
} catch (Exception e) {
log.warn("[redact/execute] range redaction failed: {}", e.getMessage());
}
}
private void applyImageBoxRedaction(PDDocument document, ImageBox box, RedactStyle style)
throws IOException {
List<float[]> boxes =
List.of(
new float[] {
(float) box.pageIndex(), box.x1(), box.y1(), box.x2(), box.y2()
});
log.info("[redact/execute] image box overlay on page {}", box.pageIndex());
Color boxColor = ManualRedactionService.decodeOrDefault(style.getColor());
manualRedactionService.redactImageBoxes(document, boxes, boxColor);
}
private void applyAllImagesRedaction(
PDDocument document, List<Integer> pageNumbers, RedactStyle style) throws IOException {
PDPageTree allPages = document.getDocumentCatalog().getPages();
Color imgColor = ManualRedactionService.decodeOrDefault(style.getColor());
List<Integer> imagePageIndices = toZeroBasedIndices(pageNumbers);
if (imagePageIndices.isEmpty()) {
imagePageIndices = new ArrayList<>();
for (int i = 0; i < allPages.getCount(); i++) {
imagePageIndices.add(i);
}
}
List<float[]> detectedBoxes = new ArrayList<>();
for (int pageIdx : imagePageIndices) {
if (pageIdx < 0 || pageIdx >= allPages.getCount()) continue;
try {
PDPage page = allPages.get(pageIdx);
PageImageLocator locator = new PageImageLocator(page, pageIdx);
locator.processPage(page);
for (PageImageLocator.ImageBox ib : locator.getImageBoxes()) {
detectedBoxes.add(new float[] {pageIdx, ib.x1(), ib.y1(), ib.x2(), ib.y2()});
}
} catch (Exception e) {
log.warn(
"[redact/execute] image detection failed for page {}: {}",
pageIdx + 1,
e.getMessage());
}
}
log.info(
"[redact/execute] auto image detection: {} images across {} pages",
detectedBoxes.size(),
imagePageIndices.size());
if (!detectedBoxes.isEmpty()) {
manualRedactionService.redactImageBoxes(document, detectedBoxes, imgColor);
}
}
// -----------------------------------------------------------------------
// Range collection helpers
// -----------------------------------------------------------------------
/**
* Locates {@code startStr} in the document and returns {@link PDFText} blocks for every text
* line and image from that point up to (but NOT including) the line where {@code endStr}
* begins. If {@code endStr} is blank, redacts from {@code startStr} to the end of the document.
*
* <p>Multi-column pages follow reading order: down the start column, jump to the top of the
* next column, continue to the end anchor. Single-column pages reduce to a plain Y-band check.
*/
List<PDFText> collectRangeBlocks(
PDDocument document,
String startStr,
String endStr,
Map<Integer, PageColumnLayout> layoutCache)
throws IOException {
PDPageTree allPages = document.getDocumentCatalog().getPages();
int totalPages = allPages.getCount();
Map<Integer, List<PDFText>> startMatchesByPage = findWithFallbacks(document, startStr);
if (startMatchesByPage.isEmpty()) {
log.warn("[redact/execute] range start not found: '{}'", startStr);
return Collections.emptyList();
}
List<Anchor> starts = toAnchors(document, startMatchesByPage, layoutCache);
starts.sort(READING_ORDER);
log.info(
"[redact/execute] start='{}' matched {} anchor(s): {}",
startStr,
starts.size(),
anchorSummary(starts));
boolean openEnded = (endStr == null || endStr.isBlank());
List<Anchor> ends = new ArrayList<>();
if (!openEnded) {
Map<Integer, List<PDFText>> endMatchesByPage = findWithFallbacks(document, endStr);
if (endMatchesByPage.isEmpty()) {
log.warn(
"[redact/execute] range end '{}' not found in document - skipping range"
+ " (start='{}')",
endStr,
startStr);
return Collections.emptyList();
}
ends = toAnchors(document, endMatchesByPage, layoutCache);
ends.sort(READING_ORDER);
log.info(
"[redact/execute] end='{}' matched {} anchor(s): {}",
endStr,
ends.size(),
anchorSummary(ends));
}
List<PDFText> blocks = new ArrayList<>();
for (Anchor start : starts) {
Anchor end = null;
int endPage;
if (openEnded) {
endPage = totalPages - 1;
} else {
for (Anchor candidate : ends) {
if (READING_ORDER.compare(candidate, start) > 0) {
end = candidate;
break;
}
}
if (end == null) {
log.warn(
"[redact/execute] no end anchor after start at (page={}, col={}, y={}) — skipping",
start.page + 1,
start.col,
start.y);
continue;
}
endPage = end.page;
}
log.info(
"[redact/execute] range pages {}-{}: start='{}' (col {}) end='{}'",
start.page + 1,
endPage + 1,
startStr,
start.col,
openEnded ? "<end of document>" : endStr);
collectBlocksForRange(document, allPages, start, end, openEnded, blocks, layoutCache);
}
log.info(
"[redact/execute] range '{}'→'{}': {} total blocks",
startStr,
openEnded ? "<end of document>" : endStr,
blocks.size());
return blocks;
}
/**
* Collects all redactable content (text line segments and images) between two anchor positions.
*
* <p>Line boxes are cached per page number in {@code lineBoxCache} and reused across range
* iterations within one execute() call, avoiding redundant {@link AllTextLineExtractor} passes.
*/
private void collectBlocksForRange(
PDDocument document,
PDPageTree allPages,
Anchor start,
Anchor end,
boolean openEnded,
List<PDFText> blocks,
Map<Integer, PageColumnLayout> layoutCache)
throws IOException {
int startPage = start.page;
int endPage = openEnded ? allPages.getCount() - 1 : end.page;
int endCol =
openEnded ? layoutFor(document, endPage, layoutCache).columnCount() - 1 : end.col;
float startY = start.y;
// Use bottom of end anchor so the end anchor line itself is included (inclusive range).
float endY = openEnded ? Float.POSITIVE_INFINITY : end.text.getY2();
// Line-box cache: populated lazily per page, reused across range iterations.
// Cannot use computeIfAbsent because AllTextLineExtractor's constructor throws IOException.
Map<Integer, List<float[]>> lineBoxCache = new HashMap<>();
for (int pageIdx = startPage; pageIdx <= endPage; pageIdx++) {
PDPage page = allPages.get(pageIdx);
float pageHeight = page.getBBox().getHeight();
PageColumnLayout layout = layoutFor(document, pageIdx, layoutCache);
List<float[]> screenLineBoxes = lineBoxCache.get(pageIdx);
if (screenLineBoxes == null) {
AllTextLineExtractor textExtractor =
new AllTextLineExtractor(pageIdx + 1, pageHeight);
textExtractor.getText(document);
screenLineBoxes = textExtractor.getScreenLineBoxes();
lineBoxCache.put(pageIdx, screenLineBoxes);
}
for (float[] sb : screenLineBoxes) {
emitColumnSlices(
pageIdx, layout, sb[0], sb[2], sb[1], sb[3], start.col, startPage, startY,
endCol, endPage, endY, blocks);
}
PageImageLocator imgLocator = new PageImageLocator(page, pageIdx);
imgLocator.processPage(page);
for (PageImageLocator.ImageBox ib : imgLocator.getImageBoxes()) {
// ImageBox coordinates are in PDF user-space (Y up); convert to screen-Y (Y down).
float screenY1 = pageHeight - ib.y2();
float screenY2 = pageHeight - ib.y1();
emitColumnSlices(
pageIdx, layout, ib.x1(), ib.x2(), screenY1, screenY2, start.col, startPage,
startY, endCol, endPage, endY, blocks);
}
}
}
/** Emits each per-column sub-box accepted by the reading-order predicate. */
private static void emitColumnSlices(
int pageIdx,
PageColumnLayout layout,
float x1,
float x2,
float yTop,
float yBottom,
int startCol,
int startPage,
float startY,
int endCol,
int endPage,
float endY,
List<PDFText> blocks) {
int[] cols = layout.columnsCrossing(x1, x2);
if (cols.length == 1) {
if (inColumnZone(
pageIdx, cols[0], yTop, yBottom, startPage, startCol, startY, endPage, endCol,
endY)) {
blocks.add(new PDFText(pageIdx, x1, yTop, x2, yBottom, ""));
}
return;
}
for (int col : cols) {
if (!inColumnZone(
pageIdx, col, yTop, yBottom, startPage, startCol, startY, endPage, endCol,
endY)) {
return;
}
}
blocks.add(new PDFText(pageIdx, x1, yTop, x2, yBottom, ""));
}
/**
* Reading-order predicate: true when (col, yBottom) on page {@code pageIdx} sits between the
* start anchor (inclusive) and end anchor (inclusive).
*/
static boolean inColumnZone(
int pageIdx,
int col,
float yTop,
float yBottom,
int startPage,
int startCol,
float startY,
int endPage,
int endCol,
float endY) {
if (pageIdx > startPage && pageIdx < endPage) return true;
if (pageIdx == startPage && pageIdx == endPage) {
if (startCol == endCol) {
return col == startCol && yBottom >= startY && yBottom <= endY;
}
if (startCol < endCol) {
if (col < startCol || col > endCol) return false;
if (col == startCol) return yBottom >= startY;
if (col == endCol) return yBottom <= endY;
return true;
}
return col == startCol && yBottom >= startY;
}
if (pageIdx == startPage) {
if (col == startCol) return yBottom >= startY;
return col > startCol;
}
if (pageIdx == endPage) {
if (col == endCol) return yBottom <= endY;
return col < endCol;
}
return false;
}
/** Lazily builds and caches the column layout for a single page. */
private PageColumnLayout layoutFor(
PDDocument document, int pageIdx, Map<Integer, PageColumnLayout> cache)
throws IOException {
PageColumnLayout cached = cache.get(pageIdx);
if (cached != null) return cached;
PDPage page = document.getDocumentCatalog().getPages().get(pageIdx);
float pageWidth = page.getBBox().getWidth();
float pageHeight = page.getBBox().getHeight();
AllTextLineExtractor extractor = new AllTextLineExtractor(pageIdx + 1, pageHeight);
extractor.getText(document);
PageColumnLayout layout =
PageColumnLayout.fromLineBoxes(extractor.getLineBoxes(), pageWidth);
if (layout.columnCount() > 1) {
float[] g = layout.gutters().get(0);
log.info(
"[redact/execute] page {} layout: 2 cols, gutter x=[{}, {}]",
pageIdx + 1,
g[0],
g[1]);
} else {
log.info("[redact/execute] page {} layout: 1 col (single-column mode)", pageIdx + 1);
}
cache.put(pageIdx, layout);
return layout;
}
private List<Anchor> toAnchors(
PDDocument document,
Map<Integer, List<PDFText>> matchesByPage,
Map<Integer, PageColumnLayout> layoutCache)
throws IOException {
List<Anchor> out = new ArrayList<>();
for (int page : matchesByPage.keySet().stream().sorted().toList()) {
PageColumnLayout layout = layoutFor(document, page, layoutCache);
for (PDFText hit : matchesByPage.get(page)) {
int col = layout.columnOf(hit.getX1(), hit.getX2());
out.add(new Anchor(page, col, hit.getY1(), hit));
}
}
return out;
}
/** Lexicographic ordering by (page, column, screenY). */
private static final Comparator<Anchor> READING_ORDER =
Comparator.comparingInt((Anchor a) -> a.page)
.thenComparingInt(a -> a.col)
.thenComparingDouble(a -> a.y);
private static String anchorSummary(List<Anchor> anchors) {
StringBuilder sb = new StringBuilder();
int max = Math.min(anchors.size(), 5);
for (int i = 0; i < max; i++) {
Anchor a = anchors.get(i);
if (i > 0) sb.append(", ");
sb.append(String.format("(p=%d,c=%d,y=%.1f)", a.page + 1, a.col, a.y));
}
if (anchors.size() > max) sb.append(", …");
return sb.toString();
}
private record Anchor(int page, int col, float y, PDFText text) {}
/**
* Tries progressively more permissive variants: raw (regex then literal), letter-spacing
* collapsed, then a punctuation-tolerant regex over alphanumeric runs.
*/
private Map<Integer, List<PDFText>> findWithFallbacks(PDDocument document, String raw) {
String trimmed = raw.trim();
String collapsed = collapseLetterSpacing(trimmed);
String tolerant = punctuationTolerantRegex(trimmed);
List<Candidate> candidates = new ArrayList<>();
candidates.add(new Candidate(trimmed, true));
candidates.add(new Candidate(trimmed, false));
if (!collapsed.equals(trimmed)) {
candidates.add(new Candidate(collapsed, true));
candidates.add(new Candidate(collapsed, false));
}
if (tolerant != null && !tolerant.equals(trimmed)) {
candidates.add(new Candidate(tolerant, true));
}
// If the anchor spans multiple lines (model provided entire paragraph instead of a short
// phrase), try just the first non-empty line — it's usually sufficient to locate the
// position and avoids mismatches from mid-paragraph text extraction artifacts.
if (trimmed.contains("\n")) {
String firstLine =
Arrays.stream(trimmed.split("\n"))
.map(String::trim)
.filter(s -> !s.isEmpty())
.findFirst()
.orElse(null);
if (firstLine != null && firstLine.length() >= 4) {
String firstLineCollapsed = collapseLetterSpacing(firstLine);
String firstLineTolerant = punctuationTolerantRegex(firstLine);
candidates.add(new Candidate(firstLine, false));
if (!firstLineCollapsed.equals(firstLine)) {
candidates.add(new Candidate(firstLineCollapsed, false));
}
if (firstLineTolerant != null && !firstLineTolerant.equals(firstLine)) {
candidates.add(new Candidate(firstLineTolerant, true));
}
}
}
for (Candidate c : candidates) {
Map<Integer, List<PDFText>> m =
textRedactionService.findTextToRedact(
document, new String[] {c.pattern}, c.useRegex, false);
if (!m.isEmpty()) {
if (!c.pattern.equals(trimmed)) {
log.info(
"[redact/execute] range boundary matched via fallback: '{}' → '{}'",
trimmed,
c.pattern);
}
return m;
}
}
return Collections.emptyMap();
}
private record Candidate(String pattern, boolean useRegex) {}
// -----------------------------------------------------------------------
// Static helpers
// -----------------------------------------------------------------------
/**
* Joins {@code raw}'s alphanumeric runs with {@code \W*} so anchors match across punctuation
* drift. Returns {@code null} when fewer than two tokens exist.
*/
private static String punctuationTolerantRegex(String raw) {
List<String> tokens = new ArrayList<>();
StringBuilder current = new StringBuilder();
for (int i = 0; i < raw.length(); i++) {
char ch = raw.charAt(i);
if (Character.isLetterOrDigit(ch)) {
current.append(ch);
} else if (current.length() > 0) {
tokens.add(current.toString());
current.setLength(0);
}
}
if (current.length() > 0) tokens.add(current.toString());
if (tokens.size() < 2) return null;
StringBuilder out = new StringBuilder();
for (int i = 0; i < tokens.size(); i++) {
if (i > 0) out.append("\\W*");
out.append(Pattern.quote(tokens.get(i)));
}
return out.toString();
}
/**
* Collapses letter-spaced text produced by position-sorted text extraction.
*
* <p>When a PDF text stripper runs with {@code setSortByPosition(true)}, letter-spaced headings
* come out as {@code "T a b l e o f c o n t e n t s"}. This method converts the spaced form
* back to words.
*/
private static String collapseLetterSpacing(String text) {
String[] tokens = text.split(" ", -1);
StringBuilder result = new StringBuilder();
StringBuilder current = new StringBuilder();
for (String token : tokens) {
if (token.isEmpty()) {
if (current.length() > 0) {
if (result.length() > 0) result.append(' ');
result.append(current);
current.setLength(0);
}
} else if (token.length() == 1) {
current.append(token);
} else {
if (current.length() > 0) {
if (result.length() > 0) result.append(' ');
result.append(current);
current.setLength(0);
}
if (result.length() > 0) result.append(' ');
result.append(token);
}
}
if (current.length() > 0) {
if (result.length() > 0) result.append(' ');
result.append(current);
}
return result.toString().trim();
}
private static <T> List<T> orEmpty(List<T> list) {
return list != null ? list : List.of();
}
private static String[] cleanStrings(List<String> input) {
if (input == null || input.isEmpty()) {
return new String[0];
}
return input.stream()
.filter(s -> s != null)
.map(String::trim)
.filter(s -> !s.isEmpty())
.toArray(String[]::new);
}
/**
* Converts 1-based page numbers from the request to the 0-based indices used internally.
* Out-of-range and non-positive values are silently dropped.
*/
private static List<Integer> toZeroBasedIndices(List<Integer> oneBasedPageNumbers) {
if (oneBasedPageNumbers == null || oneBasedPageNumbers.isEmpty()) {
return new ArrayList<>();
}
List<Integer> result = new ArrayList<>();
for (Integer page : oneBasedPageNumbers) {
if (page != null && page > 0) {
result.add(page - 1);
}
}
return result;
}
private static String trimOrEmpty(String s) {
return s == null ? "" : s.trim();
}
}
@@ -1,132 +0,0 @@
package stirling.software.SPDF.model.api.security;
import java.util.ArrayList;
import java.util.List;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import lombok.EqualsAndHashCode;
import stirling.software.common.model.api.PDFFile;
@Data
@EqualsAndHashCode(callSuper = true)
public class RedactExecuteRequest extends PDFFile {
@Schema(
description =
"Exact strings to find and black out. One entry per phrase to redact."
+ " Best for known names, identifiers, and specific text found in the document.")
private List<String> textValues = new ArrayList<>();
@Schema(
description =
"Regex patterns to match and redact. Each match anywhere in the document is blacked out."
+ " Uses Java/PCRE regex syntax. Well-suited for strings that follow known patterns, like"
+ " phone numbers, email addresses, national ID numbers, or"
+ " dates (which can appear with different separators, optional country codes,"
+ " etc.). For fixed known strings such as names, use textValues instead.")
private List<String> regexPatterns = new ArrayList<>();
@Schema(
description =
"1-indexed page numbers to wipe entirely (all content removed from those pages).")
private List<Integer> wipePages = new ArrayList<>();
@Schema(
description =
"Text ranges to redact by specifying a start and end anchor phrase. All"
+ " content between the two phrases (inclusive) is redacted. Anchors"
+ " work best when short and unique. They must appear"
+ " verbatim in the document.")
private List<TextRange> ranges = new ArrayList<>();
@Schema(
description =
"Rectangular areas to black out, each defined by a page number and bounding box coordinates.")
private List<ImageBox> imageBoxes = new ArrayList<>();
@Schema(
description =
"1-indexed page numbers to redact all detected images from. Pass an empty list to redact images from every page. Omit or pass null to skip image redaction entirely.")
private List<Integer> redactImagePages;
@Schema(description = "Redaction style options")
private RedactStyle style = new RedactStyle();
public record TextRange(
@Schema(
description =
"A short, distinctive phrase (5–15 words) that marks where"
+ " redaction begins (inclusive). Must appear verbatim in"
+ " the document — e.g. a section heading or a unique"
+ " sentence fragment.",
requiredMode = Schema.RequiredMode.REQUIRED,
minLength = 1)
String startString,
@Schema(
description =
"A short, distinctive phrase (5–15 words) that marks where"
+ " redaction ends (inclusive). Must appear verbatim in the"
+ " document. Shorter phrases match more reliably.",
requiredMode = Schema.RequiredMode.REQUIRED,
minLength = 1)
String endString) {
public TextRange {
if (endString == null) endString = "";
}
}
public record ImageBox(
@Schema(
description = "0-indexed page number (first page = 0).",
requiredMode = Schema.RequiredMode.REQUIRED)
int pageIndex,
@Schema(
description =
"Left x coordinate of the redaction rectangle in PDF user-space points.",
requiredMode = Schema.RequiredMode.REQUIRED)
float x1,
@Schema(
description =
"Top y coordinate of the redaction rectangle in PDF user-space points.",
requiredMode = Schema.RequiredMode.REQUIRED)
float y1,
@Schema(
description =
"Right x coordinate of the redaction rectangle in PDF user-space points.",
requiredMode = Schema.RequiredMode.REQUIRED)
float x2,
@Schema(
description =
"Bottom y coordinate of the redaction rectangle in PDF user-space points.",
requiredMode = Schema.RequiredMode.REQUIRED)
float y2) {}
public enum RedactionStrategy {
AUTO,
OVERLAY_ONLY,
IMAGE_FINALIZE
}
@Data
public static class RedactStyle {
@Schema(description = "Hex redaction box color", defaultValue = "#000000")
private String color = "#000000";
@Schema(
description = "Extra padding around each box in points",
type = "number",
defaultValue = "0")
private float padding = 0f;
@Schema(description = "Rasterize output to prevent text extraction", defaultValue = "false")
private boolean convertToImage = false;
@Schema(
description = "Execution strategy hint for the redaction pipeline",
defaultValue = "AUTO")
private RedactionStrategy strategy = RedactionStrategy.AUTO;
}
}
@@ -33,7 +33,7 @@ spring.security.filter.dispatcher-types=REQUEST,ERROR
# Response compression
server.compression.enabled=true
server.compression.min-response-size=1024
server.compression.mime-types=application/json,application/xml,text/html,text/plain,text/css,application/javascript,image/svg+xml,application/x-font-ttf,font/opentype,application/vnd.ms-fontobject,font/woff,font/woff2,application/font-woff,application/font-woff2,application/wasm
server.compression.mime-types=application/json,application/xml,text/html,text/plain,text/css,application/javascript,image/svg+xml,application/x-font-ttf,font/opentype,application/vnd.ms-fontobject,font/woff,font/woff2,application/font-woff,application/font-woff2
spring.web.error.path=/error
spring.web.error.whitelabel.enabled=false
@@ -37,6 +37,7 @@ import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.mockito.junit.jupiter.MockitoSettings;
@@ -76,11 +77,8 @@ class RedactControllerTest {
@Mock private CustomPDFDocumentFactory pdfDocumentFactory;
@Mock private TempFileManager tempFileManager;
@Mock private RedactExecuteService redactExecuteService;
private TextRedactionService textRedactionService;
private ManualRedactionService manualRedactionService;
private RedactController redactController;
@InjectMocks private RedactController redactController;
private MockMultipartFile mockPdfFile;
private PDDocument mockDocument;
@@ -203,17 +201,7 @@ class RedactControllerTest {
.save(any(File.class));
doNothing().when(mockDocument).close();
// Build real service instances so tests exercise actual logic
textRedactionService = new TextRedactionService();
manualRedactionService = new ManualRedactionService(tempFileManager);
redactController =
new RedactController(
pdfDocumentFactory,
tempFileManager,
manualRedactionService,
textRedactionService,
redactExecuteService);
// Initialize a real document for unit tests
setupRealDocument();
}
@@ -831,9 +819,9 @@ class RedactControllerTest {
contentStream.newLineAtOffset(50, 750);
contentStream.showText("This is ");
contentStream.newLineAtOffset(-10, 0);
contentStream.newLineAtOffset(-10, 0); // Simulate positioning
contentStream.showText("secret");
contentStream.newLineAtOffset(10, 0);
contentStream.newLineAtOffset(10, 0); // Reset positioning
contentStream.showText(" information");
contentStream.endText();
}
@@ -1017,7 +1005,7 @@ class RedactControllerTest {
contentStream.showText("Original content");
contentStream.endText();
}
return textRedactionService.createTokensWithoutTargetText(
return redactController.createTokensWithoutTargetText(
realDocument, pageForTokenExtraction, Collections.emptySet(), false, false);
}
@@ -1028,28 +1016,28 @@ class RedactControllerTest {
@Test
@DisplayName("Should decode valid hex color with hash")
void decodeValidHexColorWithHash() {
Color result = ManualRedactionService.decodeOrDefault("#FF0000");
Color result = redactController.decodeOrDefault("#FF0000");
assertEquals(Color.RED, result);
}
@Test
@DisplayName("Should decode valid hex color without hash")
void decodeValidHexColorWithoutHash() {
Color result = ManualRedactionService.decodeOrDefault("FF0000");
Color result = redactController.decodeOrDefault("FF0000");
assertEquals(Color.RED, result);
}
@Test
@DisplayName("Should default to black for null color")
void defaultToBlackForNullColor() {
Color result = ManualRedactionService.decodeOrDefault(null);
Color result = redactController.decodeOrDefault(null);
assertEquals(Color.BLACK, result);
}
@Test
@DisplayName("Should default to black for invalid color")
void defaultToBlackForInvalidColor() {
Color result = ManualRedactionService.decodeOrDefault("invalid-color");
Color result = redactController.decodeOrDefault("invalid-color");
assertEquals(Color.BLACK, result);
}
@@ -1061,7 +1049,7 @@ class RedactControllerTest {
})
@DisplayName("Should handle various valid color formats")
void handleVariousValidColorFormats(String colorInput) {
Color result = ManualRedactionService.decodeOrDefault(colorInput);
Color result = redactController.decodeOrDefault(colorInput);
assertNotNull(result);
assertTrue(
result.getRed() >= 0 && result.getRed() <= 255,
@@ -1077,8 +1065,8 @@ class RedactControllerTest {
@Test
@DisplayName("Should handle short hex codes appropriately")
void handleShortHexCodes() {
Color result1 = ManualRedactionService.decodeOrDefault("123");
Color result2 = ManualRedactionService.decodeOrDefault("#12");
Color result1 = redactController.decodeOrDefault("123");
Color result2 = redactController.decodeOrDefault("#12");
assertNotNull(result1);
assertNotNull(result2);
@@ -1106,7 +1094,7 @@ class RedactControllerTest {
Set<String> targetWords = Set.of("confidential");
List<Object> tokens =
textRedactionService.createTokensWithoutTargetText(
redactController.createTokensWithoutTargetText(
realDocument, realPage, targetWords, false, false);
assertNotNull(tokens);
@@ -1127,7 +1115,7 @@ class RedactControllerTest {
Set<String> targetWords = Set.of("secret");
List<Object> tokens =
textRedactionService.createTokensWithoutTargetText(
redactController.createTokensWithoutTargetText(
realDocument, realPage, targetWords, false, false);
assertNotNull(tokens);
@@ -1160,7 +1148,7 @@ class RedactControllerTest {
List<Object> originalTokens = getOriginalTokens();
List<Object> filteredTokens =
textRedactionService.createTokensWithoutTargetText(
redactController.createTokensWithoutTargetText(
realDocument, realPage, targetWords, false, false);
long originalNonTextCount =
@@ -1168,7 +1156,7 @@ class RedactControllerTest {
.filter(
token ->
token instanceof Operator op
&& !textRedactionService.isTextShowingOperator(
&& !redactController.isTextShowingOperator(
op.getName()))
.count();
@@ -1177,7 +1165,7 @@ class RedactControllerTest {
.filter(
token ->
token instanceof Operator op
&& !textRedactionService.isTextShowingOperator(
&& !redactController.isTextShowingOperator(
op.getName()))
.count();
@@ -1196,7 +1184,7 @@ class RedactControllerTest {
Set<String> targetWords = Set.of("\\d{3}-\\d{2}-\\d{4}"); // SSN pattern
List<Object> tokens =
textRedactionService.createTokensWithoutTargetText(
redactController.createTokensWithoutTargetText(
realDocument, realPage, targetWords, true, false);
String reconstructedText = extractTextFromTokens(tokens);
@@ -1212,7 +1200,7 @@ class RedactControllerTest {
Set<String> targetWords = Set.of("test");
List<Object> tokens =
textRedactionService.createTokensWithoutTargetText(
redactController.createTokensWithoutTargetText(
realDocument, realPage, targetWords, false, true);
String reconstructedText = extractTextFromTokens(tokens);
@@ -1229,7 +1217,7 @@ class RedactControllerTest {
Set<String> targetWords = Set.of("sensitive");
List<Object> tokens =
textRedactionService.createTokensWithoutTargetText(
redactController.createTokensWithoutTargetText(
realDocument, realPage, targetWords, false, false);
String reconstructedText = extractTextFromTokens(tokens);
@@ -1243,7 +1231,7 @@ class RedactControllerTest {
void shouldWriteTokensToNewContentStream() throws Exception {
List<Object> tokens = createSampleTokenList();
textRedactionService.writeFilteredContentStream(realDocument, realPage, tokens);
redactController.writeFilteredContentStream(realDocument, realPage, tokens);
assertNotNull(realPage.getContents(), "Page should have content stream");
@@ -1261,7 +1249,7 @@ class RedactControllerTest {
assertDoesNotThrow(
() ->
textRedactionService.writeFilteredContentStream(
redactController.writeFilteredContentStream(
realDocument, realPage, emptyTokens));
assertNotNull(realPage.getContents(), "Page should still have content stream");
@@ -1274,7 +1262,7 @@ class RedactControllerTest {
String originalContent = extractTextFromModifiedPage(realPage);
List<Object> newTokens = createSampleTokenList();
textRedactionService.writeFilteredContentStream(realDocument, realPage, newTokens);
redactController.writeFilteredContentStream(realDocument, realPage, newTokens);
String newContent = extractTextFromModifiedPage(realPage);
assertNotEquals(originalContent, newContent, "Content stream should be replaced");
@@ -1285,7 +1273,7 @@ class RedactControllerTest {
void shouldCreateWidthMatchingPlaceholder() {
String originalText = "confidential";
String placeholder =
textRedactionService.createPlaceholderWithFont(
redactController.createPlaceholderWithFont(
originalText, new PDType1Font(Standard14Fonts.FontName.HELVETICA));
assertEquals(
@@ -1299,7 +1287,7 @@ class RedactControllerTest {
void shouldHandleSpecialCharactersInPlaceholder() {
String originalText = "café naïve";
String placeholder =
textRedactionService.createPlaceholderWithFont(
redactController.createPlaceholderWithFont(
originalText, new PDType1Font(Standard14Fonts.FontName.HELVETICA));
assertEquals(originalText.length(), placeholder.length());
@@ -1315,10 +1303,10 @@ class RedactControllerTest {
Set<String> targetWords = Set.of("secret");
List<Object> filteredTokens =
textRedactionService.createTokensWithoutTargetText(
redactController.createTokensWithoutTargetText(
realDocument, realPage, targetWords, false, false);
textRedactionService.writeFilteredContentStream(realDocument, realPage, filteredTokens);
redactController.writeFilteredContentStream(realDocument, realPage, filteredTokens);
assertNotNull(realPage.getContents());
String finalText = extractTextFromModifiedPage(realPage);
@@ -1334,7 +1322,7 @@ class RedactControllerTest {
Set<String> targetWords = Set.of("confidential");
List<Object> filteredTokens =
textRedactionService.createTokensWithoutTargetText(
redactController.createTokensWithoutTargetText(
realDocument, realPage, targetWords, false, false);
long filteredPositioning =
@@ -1389,7 +1377,7 @@ class RedactControllerTest {
Set<String> targetWords = Set.of("confidential");
List<Object> tokens =
textRedactionService.createTokensWithoutTargetText(
redactController.createTokensWithoutTargetText(
realDocument, realPage, targetWords, false, false);
assertNotNull(tokens);
@@ -1416,12 +1404,14 @@ class RedactControllerTest {
@Test
@DisplayName("Should handle documents with multiple text blocks")
void shouldHandleDocumentsWithMultipleTextBlocks() throws Exception {
// Create a document with multiple text blocks
realPage = new PDPage(PDRectangle.A4);
while (realDocument.getNumberOfPages() > 0) {
realDocument.removePage(0);
}
realDocument.addPage(realPage);
// Create resources
PDResources resources = new PDResources();
resources.put(
COSName.getPDFName("F1"), new PDType1Font(Standard14Fonts.FontName.HELVETICA));
@@ -1,430 +0,0 @@
package stirling.software.SPDF.controller.api.security;
import static org.assertj.core.api.Assertions.assertThat;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.common.PDRectangle;
import org.apache.pdfbox.pdmodel.font.PDType1Font;
import org.apache.pdfbox.pdmodel.font.Standard14Fonts;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import stirling.software.SPDF.model.PDFText;
import stirling.software.SPDF.pdf.parser.PageColumnLayout;
/**
* Integration tests for {@link RedactExecuteService#collectRangeBlocks(PDDocument, String, String,
* Map)}. Each test builds a synthetic PDF (single-column or two-column) with text-positioning that
* matches what a real document would produce, then asserts that the redaction range produces blocks
* confined to the expected X/Y region.
*/
class RedactExecuteServiceTest {
private static final float PAGE_WIDTH = PDRectangle.LETTER.getWidth(); // 612
private static final float PAGE_HEIGHT = PDRectangle.LETTER.getHeight(); // 792
private static final float LEFT_X = 72f;
private static final float RIGHT_X = 330f;
private static final float COL_WIDTH = 220f;
private static final float LINE_HEIGHT = 14f;
private static final float TOP_Y = PAGE_HEIGHT - 80f;
private static final float FONT_SIZE = 11f;
private final RedactExecuteService service =
new RedactExecuteService(null, null, new TextRedactionService());
@Nested
@DisplayName("Single-column documents")
class SingleColumn {
@Test
void redactBetweenMarkers_inclusive() throws IOException {
try (PDDocument doc = buildSingleColumnDoc()) {
Map<Integer, PageColumnLayout> cache = new HashMap<>();
List<PDFText> blocks =
service.collectRangeBlocks(doc, "START-HERE", "STOP-HERE", cache);
assertThat(blocks)
.as("blocks should be produced for single-column range")
.isNotEmpty();
// Blocks are in screen coords (top-left, Y down). START-HERE is drawn at the top
// of the page; STOP-HERE four lines below. Screen Y grows downward, so the
// anchors' screen-Y tops sit roughly around screenTop(0) and screenTop(4).
// The end anchor is inclusive, so blocks may extend to the bottom of line 4.
float screenTopOfStart = screenTopOfLine(0);
float screenBottomOfEnd = screenTopOfLine(4) + LINE_HEIGHT;
for (PDFText block : blocks) {
assertThat(block.getY1())
.as("block top must be at or below the start anchor's top")
.isGreaterThanOrEqualTo(screenTopOfStart - 1f);
assertThat(block.getY2())
.as(
"block bottom must not extend past the end anchor's bottom (end is inclusive)")
.isLessThanOrEqualTo(screenBottomOfEnd + 1f);
assertThat(block.getX2())
.as("block should not extend into a hypothetical right column")
.isLessThan(PAGE_WIDTH / 2f + 50f);
}
}
}
@Test
void missingStartString_noBlocks() throws IOException {
try (PDDocument doc = buildSingleColumnDoc()) {
Map<Integer, PageColumnLayout> cache = new HashMap<>();
List<PDFText> blocks =
service.collectRangeBlocks(doc, "MISSING-START", "STOP-HERE", cache);
assertThat(blocks).isEmpty();
}
}
@Test
void cvStyleHeadingPlusRightAlignedDate_stillTreatedAsSingleColumn() throws IOException {
// CV-style page: single-column body, but each section heading shares its row with a
// right-aligned date. The X-gap splitter emits the heading and the date as separate
// line boxes; this must NOT trip 2-column detection (the date is too narrow to be a
// real column), otherwise the cross-page redaction predicate over-includes wrong
// regions.
try (PDDocument doc = buildCvStyleDoc()) {
Map<Integer, PageColumnLayout> cache = new HashMap<>();
List<PDFText> blocks =
service.collectRangeBlocks(doc, "SECTION-A", "SECTION-C", cache);
assertThat(blocks)
.as("CV-style redaction between section headings must produce blocks")
.isNotEmpty();
PageColumnLayout layout = cache.get(0);
assertThat(layout.columnCount())
.as("CV-style page with heading+date rows must remain single-column")
.isEqualTo(1);
}
}
@Test
void punctuationDriftInAnchors_stillMatchesViaTolerantFallback() throws IOException {
// Simulates the LLM paraphrasing the heading by inserting a colon that isn't in the
// source ("#3 Character substitution" → "#3: Character substitution"). The
// punctuation-tolerant regex fallback should still find the line.
try (PDDocument doc = buildHeadingPdf()) {
Map<Integer, PageColumnLayout> cache = new HashMap<>();
List<PDFText> blocks =
service.collectRangeBlocks(
doc, "#3: Character substitution", "#6: Image resolution", cache);
assertThat(blocks)
.as("anchor with extra punctuation should still resolve via fallback")
.isNotEmpty();
}
}
}
@Nested
@DisplayName("Two-column documents")
class TwoColumn {
@Test
void rangeInLeftColumn_redactsOnlyLeftColumn() throws IOException {
try (PDDocument doc = buildTwoColumnDoc()) {
Map<Integer, PageColumnLayout> cache = new HashMap<>();
List<PDFText> blocks = service.collectRangeBlocks(doc, "L-START", "L-END", cache);
assertThat(blocks).as("left-only range must produce blocks").isNotEmpty();
float gutterMid = (LEFT_X + COL_WIDTH + RIGHT_X) / 2f;
for (PDFText block : blocks) {
float midX = (block.getX1() + block.getX2()) / 2f;
assertThat(midX)
.as("every block must sit in the left column, never the right")
.isLessThan(gutterMid);
}
}
}
@Test
void rangeInRightColumn_redactsOnlyRightColumn() throws IOException {
try (PDDocument doc = buildTwoColumnDoc()) {
Map<Integer, PageColumnLayout> cache = new HashMap<>();
List<PDFText> blocks = service.collectRangeBlocks(doc, "R-START", "R-END", cache);
assertThat(blocks).as("right-only range must produce blocks").isNotEmpty();
float gutterMid = (LEFT_X + COL_WIDTH + RIGHT_X) / 2f;
for (PDFText block : blocks) {
float midX = (block.getX1() + block.getX2()) / 2f;
assertThat(midX)
.as("every block must sit in the right column, never the left")
.isGreaterThan(gutterMid);
}
}
}
@Test
void twoColumnWithTocAbove_pairsAcrossColumns() throws IOException {
// Reproduces magic.pdf-style stacked layout: a multi-line TOC near the top, then a
// 2-column body where the start anchor is in left col (lower screen Y) and the end
// anchor is in right col (higher screen Y). Original pairing failed here because
// end.y < start.y in screen coords.
try (PDDocument doc = buildTwoColumnWithTocDoc()) {
Map<Integer, PageColumnLayout> cache = new HashMap<>();
List<PDFText> blocks =
service.collectRangeBlocks(doc, "BODY-L-3", "BODY-R-1", cache);
assertThat(blocks)
.as("cross-column body redaction must produce blocks despite stacked TOC")
.isNotEmpty();
}
}
@Test
void crossColumnReadingOrder_leftBottomToRightTop_producesBothSides() throws IOException {
// This is the case the original code couldn't handle at all: end Y < start Y.
try (PDDocument doc = buildTwoColumnDoc()) {
Map<Integer, PageColumnLayout> cache = new HashMap<>();
List<PDFText> blocks =
service.collectRangeBlocks(doc, "L-MIDDLE", "R-MIDDLE", cache);
assertThat(blocks)
.as("cross-column range must produce blocks, not be silently dropped")
.isNotEmpty();
float gutterMid = (LEFT_X + COL_WIDTH + RIGHT_X) / 2f;
boolean sawLeft = false;
boolean sawRight = false;
for (PDFText block : blocks) {
float midX = (block.getX1() + block.getX2()) / 2f;
if (midX < gutterMid) sawLeft = true;
else sawRight = true;
}
assertThat(sawLeft).as("left column should contain at least one block").isTrue();
assertThat(sawRight).as("right column should contain at least one block").isTrue();
}
}
}
// ── document fixtures ────────────────────────────────────────────────────────────────────────
/**
* Single-column page laid out as one column starting at LEFT_X. Lines: 0: START-HERE (start
* anchor) 1: line one 2: line two 3: line three 4: STOP-HERE (end anchor) 5: line five (must
* NOT be redacted)
*/
private PDDocument buildSingleColumnDoc() throws IOException {
PDDocument doc = new PDDocument();
PDPage page = new PDPage(PDRectangle.LETTER);
doc.addPage(page);
try (PDPageContentStream cs = new PDPageContentStream(doc, page)) {
cs.setFont(new PDType1Font(Standard14Fonts.FontName.HELVETICA), FONT_SIZE);
String[] lines = {
"START-HERE", "line one", "line two", "line three", "STOP-HERE", "line five"
};
for (int i = 0; i < lines.length; i++) {
cs.beginText();
cs.newLineAtOffset(LEFT_X, yForLine(i));
cs.showText(lines[i]);
cs.endText();
}
}
return doc;
}
/**
* Two-column page. Lines per column, top to bottom: Left: L-TOP, L-START, L-MIDDLE, L-END,
* L-BOTTOM Right: R-TOP, R-MIDDLE, R-START, R-END, R-BOTTOM
*/
private PDDocument buildTwoColumnDoc() throws IOException {
PDDocument doc = new PDDocument();
PDPage page = new PDPage(PDRectangle.LETTER);
doc.addPage(page);
try (PDPageContentStream cs = new PDPageContentStream(doc, page)) {
cs.setFont(new PDType1Font(Standard14Fonts.FontName.HELVETICA), FONT_SIZE);
// Body lines are padded to make each column genuinely wide enough that column
// detection (which ignores narrow lines) treats both sides as real columns.
String fill = " " + "x".repeat(26);
String[] left = {
"L-TOP" + fill,
"L-START" + fill,
"L-MIDDLE" + fill,
"L-END" + fill,
"L-BOTTOM" + fill
};
String[] right = {
"R-TOP" + fill,
"R-MIDDLE" + fill,
"R-START" + fill,
"R-END" + fill,
"R-BOTTOM" + fill
};
for (int i = 0; i < left.length; i++) {
cs.beginText();
cs.newLineAtOffset(LEFT_X, yForLine(i));
cs.showText(left[i]);
cs.endText();
}
// Aligned baselines per row (IEEE template style) — AllTextLineExtractor must split
// these at the column gap rather than merge same-row left+right glyphs into a wide
// box.
for (int i = 0; i < right.length; i++) {
cs.beginText();
cs.newLineAtOffset(RIGHT_X, yForLine(i));
cs.showText(right[i]);
cs.endText();
}
}
return doc;
}
/**
* Single-column page with feature headings: #1..#7 each followed by body text. The PDF text is
* exactly "#3 Character substitution" (no colon) — the test then queries with a colon to
* exercise the punctuation-tolerant fallback.
*/
private PDDocument buildHeadingPdf() throws IOException {
PDDocument doc = new PDDocument();
PDPage page = new PDPage(PDRectangle.LETTER);
doc.addPage(page);
try (PDPageContentStream cs = new PDPageContentStream(doc, page)) {
cs.setFont(new PDType1Font(Standard14Fonts.FontName.HELVETICA), FONT_SIZE);
String[] lines = {
"#1 Auto layout",
"Body about auto layout.",
"#2 Smart selection",
"Body about smart selection.",
"#3 Character substitution",
"Body about character substitution.",
"#4 Rounded borders",
"Body about rounded borders.",
"#5 Auto contrast",
"Body about auto contrast.",
"#6 Image resolution",
"Body about image resolution.",
"#7 Columns",
"Body about columns."
};
for (int i = 0; i < lines.length; i++) {
cs.beginText();
cs.newLineAtOffset(LEFT_X, yForLine(i));
cs.showText(lines[i]);
cs.endText();
}
}
return doc;
}
/**
* Two-column page like {@code magic.pdf}: a few full-width header lines, a 2-column TOC stacked
* on top of the 2-column body, where TOC's right half lives inside what would otherwise be the
* body's gutter. Body left column has BODY-L-1..3, right column has BODY-R-1..3.
*/
private PDDocument buildTwoColumnWithTocDoc() throws IOException {
PDDocument doc = new PDDocument();
PDPage page = new PDPage(PDRectangle.LETTER);
doc.addPage(page);
try (PDPageContentStream cs = new PDPageContentStream(doc, page)) {
cs.setFont(new PDType1Font(Standard14Fonts.FontName.HELVETICA), FONT_SIZE);
// Header — full width, lines 0..1.
for (int i = 0; i < 2; i++) {
cs.beginText();
cs.newLineAtOffset(LEFT_X, yForLine(i));
cs.showText("FULL WIDTH HEADER LINE " + i + " ACROSS BOTH COLUMNS OF THE PAGE");
cs.endText();
}
// TOC, 2 columns of entries. TOC right half sits where the body gutter would be —
// exactly the layout that broke the histogram-based detector on magic.pdf.
float tocLeftX = 101f;
float tocRightX = 230f;
for (int i = 0; i < 5; i++) {
float y = yForLine(3 + i);
cs.beginText();
cs.newLineAtOffset(tocLeftX, y);
cs.showText("TOC entry left " + i);
cs.endText();
cs.beginText();
cs.newLineAtOffset(tocRightX, y);
cs.showText("TOC entry right " + i);
cs.endText();
}
// Body — 2-column with aligned baselines per row (IEEE-style).
String fill = " " + "x".repeat(26);
String[] bodyLeft = {"BODY-L-1" + fill, "BODY-L-2" + fill, "BODY-L-3" + fill};
String[] bodyRight = {"BODY-R-1" + fill, "BODY-R-2" + fill, "BODY-R-3" + fill};
for (int i = 0; i < bodyLeft.length; i++) {
cs.beginText();
cs.newLineAtOffset(LEFT_X, yForLine(10 + i));
cs.showText(bodyLeft[i]);
cs.endText();
cs.beginText();
cs.newLineAtOffset(RIGHT_X, yForLine(10 + i));
cs.showText(bodyRight[i]);
cs.endText();
}
}
return doc;
}
/**
* CV-style page: single-column body with a few section headings, each followed on the same
* baseline by a right-aligned date string. {@link AllTextLineExtractor} will split each
* heading+date row into two line boxes; column detection must reject this as a fake two-column
* layout because the dates are too narrow to be a real column body.
*/
private PDDocument buildCvStyleDoc() throws IOException {
PDDocument doc = new PDDocument();
PDPage page = new PDPage(PDRectangle.LETTER);
doc.addPage(page);
try (PDPageContentStream cs = new PDPageContentStream(doc, page)) {
cs.setFont(new PDType1Font(Standard14Fonts.FontName.HELVETICA), FONT_SIZE);
float dateX = PAGE_WIDTH - 144f; // right-aligned dates near the right margin
// Section A: heading + date, then 3 body lines.
writeAt(cs, LEFT_X, yForLine(0), "SECTION-A");
writeAt(cs, dateX, yForLine(0), "Jan 2020");
writeAt(cs, LEFT_X, yForLine(1), "Body line A1 with enough width to look like body");
writeAt(cs, LEFT_X, yForLine(2), "Body line A2 with enough width to look like body");
writeAt(cs, LEFT_X, yForLine(3), "Body line A3 with enough width to look like body");
// Section B (in the redact range): heading + date + 3 body lines.
writeAt(cs, LEFT_X, yForLine(5), "SECTION-B");
writeAt(cs, dateX, yForLine(5), "Feb 2021");
writeAt(cs, LEFT_X, yForLine(6), "Body line B1 with enough width to look like body");
writeAt(cs, LEFT_X, yForLine(7), "Body line B2 with enough width to look like body");
writeAt(cs, LEFT_X, yForLine(8), "Body line B3 with enough width to look like body");
// Section C (end anchor): heading + date.
writeAt(cs, LEFT_X, yForLine(10), "SECTION-C");
writeAt(cs, dateX, yForLine(10), "Mar 2022");
}
return doc;
}
private static void writeAt(PDPageContentStream cs, float x, float y, String text)
throws IOException {
cs.beginText();
cs.newLineAtOffset(x, y);
cs.showText(text);
cs.endText();
}
/** PDF user-space Y baseline for line index {@code i} (0-based, top to bottom). */
private static float yForLine(int lineIndex) {
return TOP_Y - lineIndex * LINE_HEIGHT;
}
/** Approximate screen-Y of the top of line {@code i} (top-left origin). */
private static float screenTopOfLine(int lineIndex) {
// baseline_pdf → baseline_screen flips against page height; glyph top ≈ baseline - font
// size.
return PAGE_HEIGHT - yForLine(lineIndex) - FONT_SIZE;
}
}
@@ -6,6 +6,7 @@ import java.util.List;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import lombok.Data;
@@ -13,8 +14,9 @@ import lombok.Data;
@Schema(description = "Run an AI workflow")
public class AiWorkflowRequest {
@NotNull
@Schema(description = "The input PDF files")
private List<AiWorkflowFileInput> fileInputs = new ArrayList<>();
private List<AiWorkflowFileInput> fileInputs;
@NotBlank
@Schema(description = "The user message to orchestrate", example = "Summarise these documents")
@@ -18,6 +18,7 @@ import org.springframework.security.core.session.SessionInformation;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.oauth2.core.user.OAuth2User;
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
@@ -33,6 +34,7 @@ import lombok.extern.slf4j.Slf4j;
import stirling.software.common.annotations.api.UserApi;
import stirling.software.common.model.ApplicationProperties;
import stirling.software.common.model.api.security.UserSummaryDTO;
import stirling.software.common.model.enumeration.Role;
import stirling.software.common.model.exception.UnsupportedProviderException;
import stirling.software.proprietary.audit.AuditEventType;
@@ -975,4 +977,34 @@ public class UserController {
.body("Failed to complete initial setup");
}
}
/**
* List all enabled users for selection in signing workflows.
*
* @param principal The authenticated user
* @return List of user summaries
*/
@GetMapping("/users")
public ResponseEntity<List<UserSummaryDTO>> listUsers(Principal principal) {
if (principal == null) {
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
}
List<UserSummaryDTO> users =
userRepository.findAll().stream()
.filter(User::isEnabled)
.map(this::toUserSummaryDTO)
.collect(java.util.stream.Collectors.toList());
return ResponseEntity.ok(users);
}
private UserSummaryDTO toUserSummaryDTO(User user) {
return new UserSummaryDTO(
user.getId(),
user.getUsername(),
user.getUsername(), // Use username as displayName
user.getTeam() != null ? user.getTeam().getName() : null,
user.isEnabled());
}
}
@@ -186,7 +186,10 @@ public class AiWorkflowService {
WorkflowTurnRequest initialRequest = new WorkflowTurnRequest();
initialRequest.setUserMessage(request.getUserMessage().trim());
initialRequest.setFiles(files);
initialRequest.setConversationHistory(new ArrayList<>(request.getConversationHistory()));
initialRequest.setConversationHistory(
request.getConversationHistory() == null
? new ArrayList<>()
: new ArrayList<>(request.getConversationHistory()));
initialRequest.setEnabledEndpoints(endpointResolver.getEnabledEndpointUrls());
listener.onProgress(AiWorkflowProgressEvent.of(AiWorkflowPhase.ANALYZING));
@@ -229,12 +232,6 @@ public class AiWorkflowService {
WorkflowTurnRequest request,
ProgressListener listener)
throws IOException {
if (filesById.isEmpty()) {
return new WorkflowState.Terminal(
cannotContinue(
"No files were uploaded. Please add a PDF to the workbench first."));
}
if (!request.getArtifacts().isEmpty()) {
return new WorkflowState.Terminal(
cannotContinue("AI engine requested content extraction more than once."));
@@ -8,18 +8,13 @@ import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVPrinter;
import org.apache.commons.csv.QuoteMode;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.common.PDRectangle;
import org.apache.pdfbox.text.PDFTextStripper;
import org.apache.pdfbox.text.TextPosition;
import org.springframework.stereotype.Service;
import com.fasterxml.jackson.annotation.JsonIgnore;
@@ -29,7 +24,6 @@ import lombok.Data;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import stirling.software.SPDF.pdf.parser.PageImageLocator;
import stirling.software.SPDF.pdf.parser.PdfIngester;
import stirling.software.SPDF.pdf.parser.PdfModels.ParsedPage;
import stirling.software.SPDF.pdf.parser.PdfModels.RawLine;
@@ -38,7 +32,6 @@ import stirling.software.SPDF.pdf.parser.PdfModels.TextFragment;
import stirling.software.SPDF.pdf.parser.TabulaTableParser;
import stirling.software.common.util.ExceptionUtils;
import stirling.software.common.util.PdfUtils;
import stirling.software.common.util.RegexPatternUtils;
import stirling.software.proprietary.model.api.ai.AiPdfContentType;
import stirling.software.proprietary.model.api.ai.AiWorkflowFileRequest;
import stirling.software.proprietary.model.api.ai.AiWorkflowTextSelection;
@@ -129,7 +122,6 @@ public class PdfContentExtractor {
}
csvStrings.add(sw.toString());
}
return csvStrings;
}
@@ -303,6 +295,7 @@ public class PdfContentExtractor {
private List<AiWorkflowTextSelection> extractPageText(
PDDocument document, List<Integer> selectedPages, int maxCharacters)
throws IOException {
PDFTextStripper textStripper = new PDFTextStripper();
List<AiWorkflowTextSelection> pages = new ArrayList<>();
int remainingCharacters = maxCharacters;
@@ -311,29 +304,10 @@ public class PdfContentExtractor {
break;
}
PDFTextStripper textStripper = new PDFTextStripper();
textStripper.setSortByPosition(true);
textStripper.setStartPage(pageNumber);
textStripper.setEndPage(pageNumber);
String pageText = textStripper.getText(document).trim();
// Prepend page dimensions so the AI agent can reason about absolute coordinates.
PDPage page = document.getPage(pageNumber - 1);
PDRectangle bbox = page.getBBox();
String dimensionHeader =
String.format(
"--- Page dimensions: %.0fx%.0f pts"
+ " (PDF user-space: origin bottom-left, Y up) ---\n",
bbox.getWidth(), bbox.getHeight());
pageText = dimensionHeader + pageText;
// Append image metadata so the AI agent can reason about images spatially.
String imageAnnotation = buildImageAnnotation(document, pageNumber - 1);
if (!imageAnnotation.isEmpty()) {
pageText = pageText + imageAnnotation;
}
if (pageText.isBlank()) {
continue;
}
@@ -353,56 +327,6 @@ public class PdfContentExtractor {
return pages;
}
/**
* Builds a human-readable description of all images on a page to append to page text. Uses PDF
* user-space coordinates (origin bottom-left, Y up) so the AI can reference exact bounding
* boxes when requesting image redaction.
*/
private String buildImageAnnotation(PDDocument document, int pageIndex) {
try {
List<ImageBlock> images = extractImagePositions(document, pageIndex);
if (images.isEmpty()) {
return "";
}
PDPage page = document.getPage(pageIndex);
PDRectangle bbox = page.getBBox();
float pageWidth = bbox.getWidth();
float pageHeight = bbox.getHeight();
StringBuilder sb = new StringBuilder("\n\n--- Images on this page ---");
for (int i = 0; i < images.size(); i++) {
ImageBlock img = images.get(i);
String position = spatialLabel(img, pageWidth, pageHeight);
float w = img.x2() - img.x1();
float h = img.y2() - img.y1();
sb.append(
String.format(
"\nImage %d: position=%s, size=%.0fx%.0f pts,"
+ " bounds=(x1=%.0f, y1=%.0f, x2=%.0f, y2=%.0f)",
i + 1, position, w, h, img.x1(), img.y1(), img.x2(), img.y2()));
}
return sb.toString();
} catch (Exception e) {
log.debug(
"Failed to extract image positions for page {}: {}", pageIndex, e.getMessage());
return "";
}
}
/**
* Returns a human-readable spatial label (e.g. "top-left", "center") for an image based on its
* centre relative to the page dimensions. Coordinates are in PDF user-space (Y up).
*/
private static String spatialLabel(ImageBlock img, float pageWidth, float pageHeight) {
float cx = (img.x1() + img.x2()) / 2f;
float cy = (img.y1() + img.y2()) / 2f;
String horiz = cx < pageWidth / 3f ? "left" : cx < 2 * pageWidth / 3f ? "center" : "right";
// PDF Y increases upward, so higher Y = higher on the page = "top"
String vert = cy > 2 * pageHeight / 3f ? "top" : cy > pageHeight / 3f ? "middle" : "bottom";
return vert + "-" + horiz;
}
private ExtractedFileText buildExtractedFileText(
String fileName, List<AiWorkflowTextSelection> pages) {
ExtractedFileText fileText = new ExtractedFileText();
@@ -423,130 +347,6 @@ public class PdfContentExtractor {
return text.substring(0, end);
}
// -----------------------------------------------------------------------
// Text position finding
// -----------------------------------------------------------------------
/**
* A located text match inside a PDF: 0-based page index and bounding box in PDFBox coordinates
* (origin bottom-left).
*/
public record TextBlock(int pageIndex, float x1, float y1, float x2, float y2) {}
/**
* An image found on a PDF page: 0-based page index and bounding box in PDF user-space
* coordinates (origin bottom-left, Y increases upward).
*/
public record ImageBlock(int pageIndex, float x1, float y1, float x2, float y2) {}
/**
* Extract the bounding boxes of all raster/vector images on the given (0-based) page.
*
* @param document the open PDF
* @param pageIndex 0-based page index
* @return list of located images in document order
*/
public List<ImageBlock> extractImagePositions(PDDocument document, int pageIndex)
throws IOException {
PDPage page = document.getPage(pageIndex);
PageImageLocator locator = new PageImageLocator(page, pageIndex);
locator.processPage(page);
return locator.getImageBoxes().stream()
.map(b -> new ImageBlock(b.pageIndex(), b.x1(), b.y1(), b.x2(), b.y2()))
.toList();
}
/**
* Find all occurrences of {@code pattern} in {@code document} and return their bounding boxes.
*
* @param document the open PDF
* @param pattern the search string or regex
* @param useRegex {@code true} to treat {@code pattern} as a regular expression
* @return list of located matches, in page order
*/
public List<TextBlock> findTextPositions(PDDocument document, String pattern, boolean useRegex)
throws IOException {
LocalTextFinder finder = new LocalTextFinder(pattern, useRegex);
finder.getText(document);
return finder.found;
}
private static final class LocalTextFinder extends PDFTextStripper {
private final String searchTerm;
private final boolean useRegex;
final List<TextBlock> found = new ArrayList<>();
private final List<TextPosition> pagePositions = new ArrayList<>();
private final StringBuilder pageText = new StringBuilder();
LocalTextFinder(String searchTerm, boolean useRegex) throws IOException {
this.searchTerm = searchTerm;
this.useRegex = useRegex;
setWordSeparator(" ");
setLineSeparator("\n");
}
@Override
protected void startPage(PDPage page) throws IOException {
super.startPage(page);
pagePositions.clear();
pageText.setLength(0);
}
@Override
protected void writeString(String text, List<TextPosition> positions) {
pageText.append(text);
pagePositions.addAll(positions);
}
@Override
protected void writeWordSeparator() {
pageText.append(getWordSeparator());
pagePositions.add(null);
}
@Override
protected void writeLineSeparator() {
pageText.append(getLineSeparator());
pagePositions.add(null);
}
@Override
protected void endPage(PDPage page) throws IOException {
String text = pageText.toString();
if (!text.isEmpty() && searchTerm != null && !searchTerm.isBlank()) {
String term = searchTerm.trim();
String regex = useRegex ? term : "\\Q" + term + "\\E";
Pattern pat = RegexPatternUtils.getInstance().createSearchPattern(regex, true);
Matcher matcher = pat.matcher(text);
while (matcher.find()) {
float minX = Float.MAX_VALUE;
float minY = Float.MAX_VALUE;
float maxX = -Float.MAX_VALUE;
float maxY = -Float.MAX_VALUE;
boolean hit = false;
for (int i = matcher.start(); i < matcher.end(); i++) {
if (i < pagePositions.size()) {
TextPosition tp = pagePositions.get(i);
if (tp != null) {
hit = true;
minX = Math.min(minX, tp.getX());
maxX = Math.max(maxX, tp.getX() + tp.getWidth());
minY = Math.min(minY, tp.getY() - tp.getHeight());
maxY = Math.max(maxY, tp.getY());
}
}
}
if (hit) {
found.add(new TextBlock(getCurrentPageNo() - 1, minX, minY, maxX, maxY));
}
}
}
super.endPage(page);
}
}
// --- Types shared with AiWorkflowService (package-private) ---
interface PdfContentResult {
@@ -3,8 +3,6 @@ package stirling.software.proprietary.workflow.controller;
import java.io.IOException;
import java.security.Principal;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
@@ -33,13 +31,9 @@ import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import stirling.software.SPDF.config.swagger.StandardPdfResponse;
import stirling.software.common.model.api.security.UserSummaryDTO;
import stirling.software.common.util.GeneralUtils;
import stirling.software.common.util.WebResponseUtils;
import stirling.software.proprietary.model.Team;
import stirling.software.proprietary.security.database.repository.UserRepository;
import stirling.software.proprietary.security.model.User;
import stirling.software.proprietary.security.service.TeamService;
import stirling.software.proprietary.security.service.UserService;
import stirling.software.proprietary.workflow.dto.CertificateInfo;
import stirling.software.proprietary.workflow.dto.CertificateValidationResponse;
@@ -61,55 +55,10 @@ public class SigningSessionController {
private final WorkflowSessionService workflowSessionService;
private final UserService userService;
private final UserRepository userRepository;
private final SigningFinalizationService signingFinalizationService;
private final CertificateSubmissionValidator certificateSubmissionValidator;
private final ObjectMapper objectMapper = new ObjectMapper();
@Operation(
summary = "List users the caller can invite as cert-sign participants",
description =
"Returns enabled users in the caller's team, excluding the caller and the"
+ " Internal team. Scoped to the caller's team to avoid leaking the"
+ " user directory (GHSA-h2rx-xrhc-5q72).")
@Transactional(readOnly = true)
@GetMapping(value = "/cert-sign/eligible-participants")
public ResponseEntity<List<UserSummaryDTO>> listEligibleParticipants(Principal principal) {
workflowSessionService.ensureSigningEnabled();
if (principal == null) {
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
}
Optional<User> callerOpt = userService.findByUsernameIgnoreCase(principal.getName());
if (callerOpt.isEmpty()) {
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
}
User caller = callerOpt.get();
Team callerTeam = caller.getTeam();
if (callerTeam == null
|| TeamService.INTERNAL_TEAM_NAME.equalsIgnoreCase(callerTeam.getName())) {
return ResponseEntity.ok(List.of());
}
List<UserSummaryDTO> users =
userRepository.findAllByTeam(callerTeam).stream()
.filter(User::isEnabled)
.filter(u -> !u.getId().equals(caller.getId()))
.map(this::toUserSummaryDTO)
.collect(Collectors.toList());
return ResponseEntity.ok(users);
}
private UserSummaryDTO toUserSummaryDTO(User user) {
return new UserSummaryDTO(
user.getId(),
user.getUsername(),
user.getUsername(),
user.getTeam() != null ? user.getTeam().getName() : null,
user.isEnabled());
}
@Operation(summary = "List all signing sessions for current user")
@Transactional(readOnly = true)
@GetMapping(value = "/cert-sign/sessions")
@@ -1,26 +0,0 @@
package stirling.software.saas.payg.charge;
import stirling.software.saas.payg.model.JobSource;
import stirling.software.saas.payg.model.ProcessType;
/**
* Per-call context for {@link JobChargeService#openProcess}. Carries the caller's identity and what
* kind of process this is. Does NOT carry policy fields — the charge service resolves the effective
* policy from {@code PricingPolicyService} so a stale snapshot from the caller can't desync from
* the live policy.
*/
public record ChargeContext(
Long ownerUserId, Long ownerTeamId, JobSource source, ProcessType processType) {
public ChargeContext {
if (ownerUserId == null) {
throw new IllegalArgumentException("ownerUserId is required");
}
if (source == null) {
throw new IllegalArgumentException("source is required");
}
if (processType == null) {
throw new IllegalArgumentException("processType is required");
}
}
}
@@ -1,19 +0,0 @@
package stirling.software.saas.payg.charge;
import java.util.UUID;
/**
* Result of {@link JobChargeService#openProcess}. {@code processId} is the job the caller's tool
* call belongs to (newly opened or joined). {@code units} is what would have been debited had the
* call been in PAYG (live) mode — for OPENED, the actual classification × policy units; for JOINED,
* always 0 since the parent process already paid.
*/
public record ChargeOutcome(UUID processId, int units, Disposition disposition) {
public enum Disposition {
/** Started a new process; {@code units} reflects the would-be charge. */
OPENED,
/** Joined an existing process within window; no incremental charge. */
JOINED
}
}
@@ -1,234 +0,0 @@
package stirling.software.saas.payg.charge;
import java.io.IOException;
import java.nio.file.Path;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.UUID;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import lombok.extern.slf4j.Slf4j;
import stirling.software.saas.payg.docs.DocumentClassifier;
import stirling.software.saas.payg.docs.DocumentMetrics;
import stirling.software.saas.payg.job.JobContext;
import stirling.software.saas.payg.job.JobService;
import stirling.software.saas.payg.job.JoinOrOpenResult;
import stirling.software.saas.payg.job.ProcessingJob;
import stirling.software.saas.payg.model.JobSource;
import stirling.software.saas.payg.model.JobStatus;
import stirling.software.saas.payg.model.ShadowChargeStatus;
import stirling.software.saas.payg.policy.PricingPolicy;
import stirling.software.saas.payg.policy.PricingPolicyService;
import stirling.software.saas.payg.repository.PaygShadowChargeRepository;
import stirling.software.saas.payg.repository.ProcessingJobRepository;
import stirling.software.saas.payg.shadow.PaygShadowCharge;
/**
* Orchestrates a tool call's open-process decision: look up the team's effective policy, resolve
* the step-limit ceiling for this caller surface, delegate the join-or-open decision to {@link
* JobService}, and — when a new process opens — compute the would-be charge and record a {@link
* PaygShadowCharge} row for comparison against the legacy engine.
*
* <p>Shadow mode only: this service never debits the wallet ledger or posts a Stripe meter event.
* The real-charging path lives in a separate follow-up and reuses the same orchestration — only the
* side-effect (shadow row vs ledger entry + Stripe call) differs.
*
* <p>The {@code legacyCreditsCharged} field on the shadow row is set to {@code 0} here. When the
* legacy {@code CreditService} is wired to call this service (separate PR), the legacy debit amount
* becomes available and {@code diffPct} can be computed against it; until then the shadow row
* captures the PAYG units only.
*/
@Service
@Profile("saas")
@Slf4j
public class JobChargeService {
private final JobService jobService;
private final PricingPolicyService policyService;
private final DocumentClassifier classifier;
private final PaygShadowChargeRepository shadowRepository;
private final ProcessingJobRepository jobRepository;
public JobChargeService(
JobService jobService,
PricingPolicyService policyService,
DocumentClassifier classifier,
PaygShadowChargeRepository shadowRepository,
ProcessingJobRepository jobRepository) {
this.jobService = Objects.requireNonNull(jobService, "jobService");
this.policyService = Objects.requireNonNull(policyService, "policyService");
this.classifier = Objects.requireNonNull(classifier, "classifier");
this.shadowRepository = Objects.requireNonNull(shadowRepository, "shadowRepository");
this.jobRepository = Objects.requireNonNull(jobRepository, "jobRepository");
}
/**
* Open a process (or join an existing one) for this tool call. Side effects: persists a {@code
* ProcessingJob} row plus input signatures, and — on OPENED — writes a {@code
* payg_shadow_charge} row carrying the would-be PAYG units.
*/
@Transactional
public ChargeOutcome openProcess(ChargeContext ctx, List<JobInput> inputs) throws IOException {
Objects.requireNonNull(ctx, "ctx");
Objects.requireNonNull(inputs, "inputs");
if (inputs.isEmpty()) {
throw new IllegalArgumentException("inputs must not be empty");
}
PricingPolicy policy = policyService.getEffectivePolicy(ctx.ownerTeamId());
int stepLimit = resolveStepLimit(policy, ctx.source());
JobContext jobCtx =
new JobContext(
ctx.ownerUserId(),
ctx.ownerTeamId(),
ctx.source(),
ctx.processType(),
policy.getId(),
stepLimit);
List<Path> paths = inputs.stream().map(JobInput::path).toList();
JoinOrOpenResult result = jobService.joinOrOpen(jobCtx, paths);
if (result.disposition() == JoinOrOpenResult.Disposition.JOINED) {
return new ChargeOutcome(result.job().getId(), 0, ChargeOutcome.Disposition.JOINED);
}
int units = computeUnits(inputs, policy);
result.job().setDocUnits(units);
recordShadowRow(ctx, result.job().getId(), policy.getId(), units);
return new ChargeOutcome(result.job().getId(), units, ChargeOutcome.Disposition.OPENED);
}
private int resolveStepLimit(PricingPolicy policy, JobSource source) {
Integer fromPolicy =
policy.getStepLimits() == null ? null : policy.getStepLimits().get(source);
if (fromPolicy != null && fromPolicy > 0) {
return fromPolicy;
}
// Defensive default — every JobSource should have an entry per the V12 seed, but a
// hand-edited policy could be missing one. Fall back to the smallest documented limit
// (10 — WEB/API/DESKTOP_APP default) so an admin slip-up never spawns unbounded chains.
log.debug(
"PricingPolicy {} missing stepLimit for source={}; using fallback of 10.",
policy.getId(),
source);
return 10;
}
private int computeUnits(List<JobInput> inputs, PricingPolicy policy) {
List<MultipartFile> multiparts = inputs.stream().map(JobInput::multipart).toList();
// Reuse the temp file the caller already wrote (in PaygChargeInterceptor.preHandle for
// lineage hashing) instead of materialising the same bytes a second time inside the
// classifier. Saves one write + one read per PDF input.
List<Path> paths = inputs.stream().map(JobInput::path).toList();
DocumentMetrics metrics =
multiparts.size() == 1
? classifier.classify(multiparts.get(0), paths.get(0), policy)
: classifier.classify(multiparts, paths, policy);
// Apply the policy-level minChargeUnits floor per design § 3.4. The classifier returns
// raw docUnits with a "non-empty input → ≥1" floor; the charge formula's
// max(min_charge_units, docUnits) layers on top.
return Math.max(policy.getMinChargeUnits(), metrics.docUnits());
}
private void recordShadowRow(
ChargeContext ctx, java.util.UUID jobId, Long policyId, int units) {
PaygShadowCharge row = new PaygShadowCharge();
row.setTeamId(ctx.ownerTeamId());
row.setJobId(jobId);
row.setPolicyId(policyId);
row.setPaygUnits(units);
// No legacy comparison yet — wired when the shadow path is connected to the legacy
// CreditService in the follow-up PR. Until then, diff stays at 0.
row.setLegacyCreditsCharged(0);
row.setDiffPct(0);
row.setStatus(ShadowChargeStatus.CHARGED);
shadowRepository.save(row);
}
/**
* First-step failure on a freshly-opened process: mimic a successful Stripe
* meter_event_adjustment(cancel) by flipping the shadow row to {@link
* ShadowChargeStatus#REFUNDED}, and close the process so a same-input retry can't lineage-join
* into a refunded chain for free work.
*
* <p>Idempotent: re-invoking on an already-REFUNDED row or already-CLOSED process is a silent
* no-op.
*/
@Transactional
public void markFirstStepFailed(UUID jobId, String refundReason) {
Objects.requireNonNull(jobId, "jobId");
LocalDateTime now = LocalDateTime.now();
Optional<PaygShadowCharge> rowOpt = shadowRepository.findFirstByJobIdOrderByIdAsc(jobId);
if (rowOpt.isEmpty()) {
log.debug(
"markFirstStepFailed: no shadow row for job {} (PAYG not active for team?)",
jobId);
} else {
PaygShadowCharge row = rowOpt.get();
if (row.getStatus() != ShadowChargeStatus.REFUNDED) {
row.setStatus(ShadowChargeStatus.REFUNDED);
row.setRefundedAt(now);
row.setRefundReason(trimReason(refundReason));
shadowRepository.save(row);
}
}
ProcessingJob job = jobRepository.findById(jobId).orElse(null);
if (job == null) {
log.warn("markFirstStepFailed: no ProcessingJob with id {}", jobId);
return;
}
if (job.getStatus() == JobStatus.OPEN) {
job.setStatus(JobStatus.CLOSED);
job.setClosedAt(now);
jobRepository.save(job);
}
}
/**
* Mid-chain 5xx on a JOINED step: return the step slot. The {@code lastStepAt} timestamp stays
* advanced (workflow window intentionally remains active for the next retry). No shadow-row
* change — only OPENED-disposition calls wrote a row.
*
* <p>Defensive lower bound: never drives {@code stepCount} below 1 (which would imply we'd
* decremented an already-decremented slot, or were called on a fresh process).
*/
@Transactional
public void decrementStepCount(UUID jobId) {
Objects.requireNonNull(jobId, "jobId");
ProcessingJob job = jobRepository.findById(jobId).orElse(null);
if (job == null) {
log.warn("decrementStepCount: no ProcessingJob with id {}", jobId);
return;
}
int current = job.getStepCount() == null ? 0 : job.getStepCount();
if (current <= 1) {
log.debug(
"decrementStepCount: stepCount already at {} for job {}; no-op",
current,
jobId);
return;
}
job.setStepCount(current - 1);
jobRepository.save(job);
}
private static String trimReason(String reason) {
if (reason == null) {
return null;
}
return reason.length() > 128 ? reason.substring(0, 128) : reason;
}
}
@@ -1,24 +0,0 @@
package stirling.software.saas.payg.charge;
import java.nio.file.Path;
import org.springframework.web.multipart.MultipartFile;
/**
* One input file to a tool call, materialised. {@code path} is the on-disk copy the lineage
* detector hashes; {@code multipart} carries the size + content-type metadata the classifier needs.
* The pair is constructed by the ingress filter (PR-I7a filter) which materialises the request body
* exactly once. Tests construct it from a fixture file plus a {@code MockMultipartFile} wrapping
* the same bytes.
*/
public record JobInput(MultipartFile multipart, Path path) {
public JobInput {
if (multipart == null) {
throw new IllegalArgumentException("multipart is required");
}
if (path == null) {
throw new IllegalArgumentException("path is required");
}
}
}
@@ -4,7 +4,6 @@ import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.Objects;
@@ -49,16 +48,10 @@ public class DefaultDocumentClassifier implements DocumentClassifier {
@Override
public DocumentMetrics classify(MultipartFile file, PricingPolicy policy) {
return classify(file, null, policy);
}
@Override
public DocumentMetrics classify(
MultipartFile file, Path materialisedPath, PricingPolicy policy) {
Objects.requireNonNull(file, "file");
Objects.requireNonNull(policy, "policy");
FileFacts facts = inspect(file, materialisedPath);
FileFacts facts = inspect(file);
long rawUnits = computeRawUnits(facts.pages, facts.bytes, policy);
// toIntExact: fail loud on overflow rather than silently wrapping a billing number.
int units =
@@ -71,35 +64,19 @@ public class DefaultDocumentClassifier implements DocumentClassifier {
@Override
public DocumentMetrics classify(List<MultipartFile> files, PricingPolicy policy) {
return classify(files, null, policy);
}
@Override
public DocumentMetrics classify(
List<MultipartFile> files, List<Path> materialisedPaths, PricingPolicy policy) {
Objects.requireNonNull(files, "files");
Objects.requireNonNull(policy, "policy");
if (files.isEmpty()) {
throw new IllegalArgumentException("files must not be empty");
}
if (materialisedPaths != null && materialisedPaths.size() != files.size()) {
throw new IllegalArgumentException(
"materialisedPaths size ("
+ materialisedPaths.size()
+ ") must equal files size ("
+ files.size()
+ ")");
}
int totalPages = 0;
long totalBytes = 0;
long rawUnitsSum = 0;
String firstContentType = null;
for (int i = 0; i < files.size(); i++) {
MultipartFile file = files.get(i);
Path path = materialisedPaths == null ? null : materialisedPaths.get(i);
FileFacts facts = inspect(file, path);
for (MultipartFile file : files) {
FileFacts facts = inspect(file);
// Sum the *raw* (unclamped) per-file units so the group cap below can actually bind.
// Per-file clamping in this loop would make the group cap a no-op.
rawUnitsSum =
@@ -126,17 +103,11 @@ public class DefaultDocumentClassifier implements DocumentClassifier {
totalUnits);
}
private FileFacts inspect(MultipartFile file, Path materialisedPath) {
private FileFacts inspect(MultipartFile file) {
long bytes = file.getSize();
String contentType =
file.getContentType() != null ? file.getContentType() : DEFAULT_CONTENT_TYPE;
int pages = 0;
if (isPdf(contentType, file.getOriginalFilename())) {
pages =
materialisedPath != null
? readPageCountFromPath(materialisedPath, file.getOriginalFilename())
: readPageCount(file);
}
int pages = isPdf(contentType, file.getOriginalFilename()) ? readPageCount(file) : 0;
return new FileFacts(pages, bytes, contentType);
}
@@ -170,7 +141,9 @@ public class DefaultDocumentClassifier implements DocumentClassifier {
OutputStream out = Files.newOutputStream(temp.getPath())) {
in.transferTo(out);
}
return readPageCountFromPath(temp.getPath(), file.getOriginalFilename());
try (PdfDocument doc = PdfDocument.open(temp.getPath())) {
return doc.pageCount();
}
} catch (IOException | RuntimeException e) {
log.debug(
"Could not read PDF page count for {} ({}); falling back to bytes-only units",
@@ -180,23 +153,6 @@ public class DefaultDocumentClassifier implements DocumentClassifier {
}
}
/**
* Page-count read against an already-materialised file. Used by callers that already wrote the
* bytes to disk (the PAYG interceptor materialises every input for the lineage hash) so we
* avoid a second copy.
*/
private int readPageCountFromPath(Path path, String displayName) {
try (PdfDocument doc = PdfDocument.open(path)) {
return doc.pageCount();
} catch (RuntimeException e) {
log.debug(
"Could not read PDF page count for {} ({}); falling back to bytes-only units",
displayName,
e.getClass().getSimpleName());
return 0;
}
}
private static int saturatedAdd(int a, int b) {
long sum = (long) a + b;
if (sum > Integer.MAX_VALUE) {
@@ -1,6 +1,5 @@
package stirling.software.saas.payg.docs;
import java.nio.file.Path;
import java.util.List;
import org.springframework.web.multipart.MultipartFile;
@@ -12,17 +11,6 @@ import stirling.software.saas.payg.policy.PricingPolicy;
*
* <p>Returns {@code docUnits} with an absolute floor of 1 for non-empty input. {@code
* policy.minChargeUnits} is applied at charge time, not here.
*
* <p>Each overload comes in two flavours:
*
* <ul>
* <li>{@code classify(MultipartFile, ...)} — classifier reads bytes via {@code getInputStream()}
* and writes its own temp file to feed jpdfium (for PDFs). Use when no on-disk copy exists.
* <li>{@code classify(MultipartFile, Path, ...)} — caller has already materialised the bytes to
* {@code Path}; classifier reads page count directly from there without re-writing. Hot-path
* callers (the PAYG interceptor) should use this form since they materialise inputs anyway
* for the lineage hash.
* </ul>
*/
public interface DocumentClassifier {
@@ -34,20 +22,4 @@ public interface DocumentClassifier {
* units, capped at {@code fileUnitCap × files.size()} and floored at 1.
*/
DocumentMetrics classify(List<MultipartFile> files, PricingPolicy policy);
/**
* Same as {@link #classify(MultipartFile, PricingPolicy)} but uses {@code materialisedPath} for
* PDF page-count extraction, avoiding a second copy of the upload bytes to disk. Callers that
* hold an on-disk copy (e.g. the PAYG interceptor materialises every input for the lineage
* hash) should prefer this form.
*/
DocumentMetrics classify(MultipartFile file, Path materialisedPath, PricingPolicy policy);
/**
* Multi-file variant of {@link #classify(MultipartFile, Path, PricingPolicy)}. {@code
* materialisedPaths} must align positionally with {@code files} — entry {@code i} is the
* on-disk copy of {@code files.get(i)}.
*/
DocumentMetrics classify(
List<MultipartFile> files, List<Path> materialisedPaths, PricingPolicy policy);
}
@@ -1,420 +0,0 @@
package stirling.software.saas.payg.filter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
import org.springframework.context.annotation.Profile;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.AsyncHandlerInterceptor;
import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.Timer;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import stirling.software.common.annotations.AutoJobPostMapping;
import stirling.software.common.util.TempFile;
import stirling.software.common.util.TempFileManager;
import stirling.software.proprietary.security.database.repository.UserRepository;
import stirling.software.proprietary.security.model.ApiKeyAuthenticationToken;
import stirling.software.proprietary.security.model.User;
import stirling.software.saas.payg.charge.ChargeContext;
import stirling.software.saas.payg.charge.ChargeOutcome;
import stirling.software.saas.payg.charge.JobChargeService;
import stirling.software.saas.payg.charge.JobInput;
import stirling.software.saas.payg.job.JobService;
import stirling.software.saas.payg.model.JobSource;
import stirling.software.saas.payg.model.JobStepStatus;
import stirling.software.saas.payg.model.ProcessType;
import stirling.software.saas.util.AuthenticationUtils;
/**
* The hot-path PAYG interceptor. Mirrors the {@code UnifiedCreditInterceptor} shape: registered
* after it in {@code PaygWebMvcConfig} so legacy credit-rejection short-circuits before we waste
* work hashing inputs.
*
* <p>{@code preHandle}: gates on {@code @AutoJobPostMapping}, reads the parsed multipart parts,
* materialises each input to a {@code TempFile}, and asks {@link JobChargeService#openProcess} to
* open (or join) a process. The resulting {@link ChargeOutcome} plus input temp-files are stashed
* as request attributes for {@code afterCompletion}.
*
* <p>{@code afterCompletion}: branches on HTTP status — 2xx hashes the response body for OUTPUT
* lineage; 4xx records a step append for audit; 5xx triggers refund-and-close (OPENED) or
* step-quota return (JOINED). Closes all input temp files and the response wrapper at the end.
*
* <p>Fail-open everywhere: any unexpected {@link RuntimeException} is swallowed, logged at WARN,
* and counted on {@code payg.filter.errors}. The customer's tool call always proceeds.
*
* <p>Async controllers ({@code DeferredResult}, {@code CompletableFuture}) are handled
* transparently — {@link AsyncHandlerInterceptor#afterConcurrentHandlingStarted} is a no-op; the
* normal {@code afterCompletion} fires when the async work resolves.
*/
@Slf4j
@Component
@Profile("saas")
public class PaygChargeInterceptor implements AsyncHandlerInterceptor {
static final String ATTR_JOB_ID = PaygChargeInterceptor.class.getName() + ".JOB_ID";
static final String ATTR_DISPOSITION = PaygChargeInterceptor.class.getName() + ".DISPOSITION";
static final String ATTR_INPUT_TEMP_FILES =
PaygChargeInterceptor.class.getName() + ".INPUT_TEMP_FILES";
static final String ATTR_INPUT_BYTES = PaygChargeInterceptor.class.getName() + ".INPUT_BYTES";
static final String ATTR_FAILED = PaygChargeInterceptor.class.getName() + ".FAILED";
static final String ATTR_TOOL_ID = PaygChargeInterceptor.class.getName() + ".TOOL_ID";
private static final String AUTOMATION_HEADER = "X-Stirling-Automation";
private final JobChargeService chargeService;
private final JobService jobService;
private final UserRepository userRepository;
private final TempFileManager tempFileManager;
private final PaygOutputExtractor outputExtractor;
private final PaygFilterProperties properties;
private final Counter errorsCounter;
private final Counter callsOpened;
private final Counter callsJoined;
private final Counter callsShortCircuit;
private final Counter refundsCounter;
private final Timer durationTimer;
public PaygChargeInterceptor(
JobChargeService chargeService,
JobService jobService,
UserRepository userRepository,
TempFileManager tempFileManager,
PaygOutputExtractor outputExtractor,
PaygFilterProperties properties,
MeterRegistry meterRegistry) {
this.chargeService = chargeService;
this.jobService = jobService;
this.userRepository = userRepository;
this.tempFileManager = tempFileManager;
this.outputExtractor = outputExtractor;
this.properties = properties;
this.errorsCounter =
Counter.builder("payg.filter.errors")
.description("PAYG interceptor / filter internal failures")
.register(meterRegistry);
this.callsOpened =
Counter.builder("payg.filter.calls")
.tag("disposition", "OPENED")
.register(meterRegistry);
this.callsJoined =
Counter.builder("payg.filter.calls")
.tag("disposition", "JOINED")
.register(meterRegistry);
this.callsShortCircuit =
Counter.builder("payg.filter.calls")
.tag("disposition", "SHORT_CIRCUIT")
.register(meterRegistry);
this.refundsCounter =
Counter.builder("payg.filter.refunds")
.description("First-step 5xx refunds applied to shadow rows")
.register(meterRegistry);
this.durationTimer =
Timer.builder("payg.filter.duration")
.description("preHandle + afterCompletion wall-clock per request")
.register(meterRegistry);
}
@Override
public boolean preHandle(
HttpServletRequest request, HttpServletResponse response, Object handler) {
Timer.Sample sample = Timer.start();
try {
if (!properties.isEnabled()) {
return true;
}
if (!(handler instanceof HandlerMethod hm)
|| hm.getMethodAnnotation(AutoJobPostMapping.class) == null) {
callsShortCircuit.increment();
return true;
}
try {
doPreHandle(request);
} catch (RuntimeException e) {
log.warn("PAYG preHandle failed; passing through unbilled", e);
errorsCounter.increment();
request.setAttribute(ATTR_FAILED, Boolean.TRUE);
cleanupInputs(request);
}
return true;
} finally {
sample.stop(durationTimer);
}
}
private void doPreHandle(HttpServletRequest request) {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
User currentUser = resolveUser(auth);
if (currentUser == null) {
callsShortCircuit.increment();
return;
}
if (!(request instanceof MultipartHttpServletRequest mreq)) {
callsShortCircuit.increment();
return;
}
MultiValueMap<String, MultipartFile> map = mreq.getMultiFileMap();
List<MultipartFile> nonEmpty = new ArrayList<>();
for (List<MultipartFile> bucket : map.values()) {
for (MultipartFile mp : bucket) {
if (mp.getSize() > 0) {
nonEmpty.add(mp);
}
}
}
if (nonEmpty.isEmpty()) {
callsShortCircuit.increment();
return;
}
List<TempFile> tempFiles = new ArrayList<>(nonEmpty.size());
List<JobInput> inputs = new ArrayList<>(nonEmpty.size());
long totalInputBytes = 0L;
try {
for (MultipartFile mp : nonEmpty) {
TempFile tf = tempFileManager.createManagedTempFile(".upload");
tempFiles.add(tf);
try (InputStream in = mp.getInputStream();
OutputStream out = Files.newOutputStream(tf.getPath())) {
in.transferTo(out);
}
inputs.add(new JobInput(mp, tf.getPath()));
totalInputBytes += mp.getSize();
}
} catch (IOException e) {
for (TempFile tf : tempFiles) {
tf.close();
}
throw new RuntimeException("Failed to materialise multipart input", e);
}
// Publish as an immutable list. preHandle fully populates `tempFiles` before this
// setAttribute, and cleanupInputs / afterCompletion are read-only consumers — exposing
// an unmodifiable view (a) makes the safe-publication guarantee from the container's
// attribute-map synchronization unambiguous to readers on different threads (sync vs
// async-dispatch), and (b) hard-fails any future caller that tries to mutate it.
request.setAttribute(ATTR_INPUT_TEMP_FILES, Collections.unmodifiableList(tempFiles));
request.setAttribute(ATTR_INPUT_BYTES, totalInputBytes);
request.setAttribute(ATTR_TOOL_ID, request.getRequestURI());
ChargeContext ctx =
new ChargeContext(
currentUser.getId(),
currentUser.getTeam() == null ? null : currentUser.getTeam().getId(),
determineSource(request, auth),
ProcessType.SINGLE_TOOL);
ChargeOutcome outcome;
try {
outcome = chargeService.openProcess(ctx, inputs);
} catch (IOException e) {
throw new RuntimeException("openProcess IO failure", e);
}
request.setAttribute(ATTR_JOB_ID, outcome.processId());
request.setAttribute(ATTR_DISPOSITION, outcome.disposition());
if (outcome.disposition() == ChargeOutcome.Disposition.OPENED) {
callsOpened.increment();
} else {
callsJoined.increment();
}
}
@Override
public void afterCompletion(
HttpServletRequest request,
HttpServletResponse response,
Object handler,
Exception ex) {
Timer.Sample sample = Timer.start();
try {
if (Boolean.TRUE.equals(request.getAttribute(ATTR_FAILED))) {
cleanupInputs(request);
closeWrapper(request);
return;
}
UUID jobId = (UUID) request.getAttribute(ATTR_JOB_ID);
if (jobId == null) {
closeWrapper(request);
return;
}
try {
doAfterCompletion(request, response, jobId);
} catch (RuntimeException e) {
log.warn(
"PAYG afterCompletion failed for job {}; lineage may be incomplete",
jobId,
e);
errorsCounter.increment();
} finally {
cleanupInputs(request);
closeWrapper(request);
}
} finally {
sample.stop(durationTimer);
}
}
private void doAfterCompletion(
HttpServletRequest request, HttpServletResponse response, UUID jobId) {
int status = response.getStatus();
ChargeOutcome.Disposition disposition =
(ChargeOutcome.Disposition) request.getAttribute(ATTR_DISPOSITION);
String toolId =
Optional.ofNullable((String) request.getAttribute(ATTR_TOOL_ID)).orElse("unknown");
Long inputBytes = (Long) request.getAttribute(ATTR_INPUT_BYTES);
// Step audit row — appended for every disposition + every outcome class. Done first so a
// refund-and-close still has the failure recorded against the now-CLOSED process.
JobStepStatus stepStatus = status < 400 ? JobStepStatus.OK : JobStepStatus.FAILED;
String errorCode = status >= 400 ? String.valueOf(status) : null;
try {
jobService.appendStep(jobId, toolId, stepStatus, null, inputBytes, errorCode);
} catch (RuntimeException e) {
log.debug("appendStep failed for job {}: {}", jobId, e.getMessage());
}
if (status >= 500) {
if (disposition == ChargeOutcome.Disposition.OPENED) {
chargeService.markFirstStepFailed(jobId, "first-step-5xx:" + status);
refundsCounter.increment();
} else {
chargeService.decrementStepCount(jobId);
}
return;
}
if (status >= 400) {
// 4xx: customer paid for the attempt. No OUTPUT recording, no refund.
return;
}
recordOutputs(request, response, jobId);
}
private void recordOutputs(
HttpServletRequest request, HttpServletResponse response, UUID jobId) {
PaygResponseBodyWrapper wrapper =
(PaygResponseBodyWrapper)
request.getAttribute(PaygResponseBodyWrapperFilter.REQUEST_ATTRIBUTE);
if (wrapper == null) {
return;
}
Long maxBytes = properties.getResponse().getMaxBytes();
if (maxBytes != null && wrapper.bytesWritten() > maxBytes) {
log.debug(
"Response size {} exceeds payg.filter.response.max-bytes={}; skipping OUTPUT recording",
wrapper.bytesWritten(),
maxBytes);
return;
}
Path bodyPath;
try {
bodyPath = wrapper.materialisedPath();
} catch (IOException e) {
log.debug("materialisedPath failed for job {}: {}", jobId, e.getMessage());
return;
}
if (bodyPath == null) {
return;
}
List<PaygOutputExtractor.ExtractedPdf> pdfs =
outputExtractor.extract(response.getContentType(), bodyPath);
try {
for (PaygOutputExtractor.ExtractedPdf pdf : pdfs) {
try {
jobService.recordOutput(jobId, pdf.path());
} catch (IOException e) {
log.debug(
"recordOutput failed for job {} path {}: {}",
jobId,
pdf.path(),
e.getMessage());
}
}
} finally {
for (PaygOutputExtractor.ExtractedPdf pdf : pdfs) {
pdf.close();
}
}
}
@Override
public void afterConcurrentHandlingStarted(
HttpServletRequest request, HttpServletResponse response, Object handler) {
// Async handoff: don't touch state. afterCompletion will fire when the async work resolves.
}
@SuppressWarnings("unchecked")
private void cleanupInputs(HttpServletRequest request) {
Object raw = request.getAttribute(ATTR_INPUT_TEMP_FILES);
if (raw instanceof List<?>) {
for (Object o : (List<Object>) raw) {
if (o instanceof TempFile tf) {
tf.close();
}
}
}
request.removeAttribute(ATTR_INPUT_TEMP_FILES);
}
private void closeWrapper(HttpServletRequest request) {
Object wrapper = request.getAttribute(PaygResponseBodyWrapperFilter.REQUEST_ATTRIBUTE);
if (wrapper instanceof PaygResponseBodyWrapper w) {
w.close();
}
}
private User resolveUser(Authentication auth) {
if (auth == null || !auth.isAuthenticated()) {
return null;
}
if (auth instanceof ApiKeyAuthenticationToken && auth.getPrincipal() instanceof User u) {
return u;
}
try {
String supabaseId = AuthenticationUtils.extractSupabaseId(auth);
if (supabaseId == null) {
return null;
}
UUID supabaseUuid = UUID.fromString(supabaseId);
return userRepository.findBySupabaseId(supabaseUuid).orElse(null);
} catch (RuntimeException e) {
log.debug("PAYG resolveUser failed: {}", e.getMessage());
return null;
}
}
private static JobSource determineSource(HttpServletRequest request, Authentication auth) {
String automationHeader = request.getHeader(AUTOMATION_HEADER);
if (automationHeader != null && "true".equalsIgnoreCase(automationHeader.trim())) {
return JobSource.PIPELINE;
}
if (auth instanceof ApiKeyAuthenticationToken) {
return JobSource.API;
}
return JobSource.WEB;
}
}
@@ -1,44 +0,0 @@
package stirling.software.saas.payg.filter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Component;
import lombok.Getter;
import lombok.Setter;
/**
* Configuration knobs for the PAYG filter + interceptor stack. See {@code PAYG_FILTER_DESIGN.md}
* §16 for the rationale on each default.
*
* <ul>
* <li>{@code payg.filter.enabled} — master kill switch. Restart-required; no
* {@code @RefreshScope}. When {@code false}, the wrapper filter passes through and the
* interceptor short-circuits in {@code preHandle}.
* <li>{@code payg.filter.response.in-memory-threshold-bytes} — the wrapper buffers below this in
* a {@link java.io.ByteArrayOutputStream}; above it spills to a {@code TempFile}.
* <li>{@code payg.filter.response.max-bytes} — optional ceiling. Responses exceeding this skip
* OUTPUT recording in {@code afterCompletion}. {@code null} = unbounded.
* </ul>
*/
@Component
@Profile("saas")
@ConfigurationProperties(prefix = "payg.filter")
@Getter
@Setter
public class PaygFilterProperties {
private boolean enabled = true;
private final Response response = new Response();
@Getter
@Setter
public static class Response {
/** 10 MiB. Tiny responses stay in RAM; large responses spill. */
private long inMemoryThresholdBytes = 10L * 1024L * 1024L;
/** Optional ceiling: when set, OUTPUT recording is skipped past this size. */
private Long maxBytes;
}
}
@@ -1,168 +0,0 @@
package stirling.software.saas.payg.filter;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Objects;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Component;
import lombok.extern.slf4j.Slf4j;
import stirling.software.common.util.TempFile;
import stirling.software.common.util.TempFileManager;
/**
* Extracts the PDF artefacts from a controller's response body for lineage OUTPUT recording. Two
* content-type paths:
*
* <ul>
* <li>{@code application/pdf} — return the response body path verbatim (the wrapper already
* materialised it to disk).
* <li>{@code application/zip} — iterate entries; each that has a {@code .pdf} extension AND
* starts with the {@code %PDF-} magic-byte sequence becomes one extracted {@link Path}.
* </ul>
*
* <p>Anything else yields an empty list — non-PDF responses don't drive lineage matching. Encrypted
* ZIPs, malformed entries, and IO failures log at debug and yield an empty list (per design §15
* fail-open). Nested ZIP-of-ZIPs is intentionally out of scope: only outer-level PDFs are
* extracted.
*
* <p>Each extracted ZIP entry is written to its own {@link TempFile} returned in the result list.
* Callers are responsible for closing those temp files — typically the interceptor closes them in
* the same {@code afterCompletion} that calls this extractor. The whole-response body path is owned
* by the wrapper and is NOT in the returned list when extraction takes the direct-PDF path.
*/
@Slf4j
@Component
@Profile("saas")
public class PaygOutputExtractor {
/** {@code %PDF-} in ASCII. */
private static final byte[] PDF_MAGIC = {0x25, 0x50, 0x44, 0x46, 0x2D};
private static final String ZIP_CONTENT_TYPE = "application/zip";
private static final String PDF_CONTENT_TYPE = "application/pdf";
private final TempFileManager tempFileManager;
public PaygOutputExtractor(TempFileManager tempFileManager) {
this.tempFileManager = Objects.requireNonNull(tempFileManager, "tempFileManager");
}
/**
* Extract PDF paths from {@code bodyPath} according to {@code contentType}. The returned list
* carries {@link ExtractedPdf} records — each wraps a {@link Path} and an indicator of whether
* the caller owns the temp file lifecycle.
*
* @param contentType the response Content-Type header (may be null / parametrised — only the
* base media type is inspected)
* @param bodyPath the on-disk full response body (from the wrapper's {@code materialisedPath})
* @return zero-or-more PDFs extracted from the body. Empty when content type is not PDF/ZIP,
* when extraction failed, when no entries matched, or when {@code bodyPath} is null.
*/
public List<ExtractedPdf> extract(String contentType, Path bodyPath) {
if (bodyPath == null) {
return List.of();
}
String mediaType = stripParameters(contentType);
if (PDF_CONTENT_TYPE.equalsIgnoreCase(mediaType)) {
// Wrapper-owned path. Don't claim ownership.
return List.of(new ExtractedPdf(bodyPath, null));
}
if (ZIP_CONTENT_TYPE.equalsIgnoreCase(mediaType)) {
return extractZip(bodyPath);
}
return List.of();
}
private List<ExtractedPdf> extractZip(Path bodyPath) {
List<ExtractedPdf> results = new ArrayList<>();
try (InputStream rawIn = Files.newInputStream(bodyPath);
ZipInputStream zin = new ZipInputStream(rawIn)) {
ZipEntry entry;
while ((entry = zin.getNextEntry()) != null) {
try {
if (entry.isDirectory()) {
continue;
}
String name = entry.getName();
if (name == null || !name.toLowerCase(Locale.ROOT).endsWith(".pdf")) {
continue;
}
TempFile temp = tempFileManager.createManagedTempFile(".pdf");
Files.copy(zin, temp.getPath(), StandardCopyOption.REPLACE_EXISTING);
if (isPdfMagic(temp.getPath())) {
results.add(new ExtractedPdf(temp.getPath(), temp));
} else {
temp.close();
}
} finally {
zin.closeEntry();
}
}
} catch (IOException | IllegalArgumentException e) {
// ZipException extends IOException; IllegalArgumentException covers ZipEntry
// "MALFORMED" surfaces from zlib. Fail-open: caller still serves the response.
log.debug(
"ZIP unpack failed for response body {} ({}); skipping per-PDF OUTPUT recording",
bodyPath,
e.getClass().getSimpleName());
// Close anything we already opened.
for (ExtractedPdf p : results) {
p.close();
}
return List.of();
}
return results;
}
private boolean isPdfMagic(Path path) {
byte[] head = new byte[PDF_MAGIC.length];
try (InputStream in = Files.newInputStream(path)) {
int read = in.read(head);
if (read != PDF_MAGIC.length) {
return false;
}
for (int i = 0; i < PDF_MAGIC.length; i++) {
if (head[i] != PDF_MAGIC[i]) {
return false;
}
}
return true;
} catch (IOException e) {
log.debug("PDF magic-byte check failed for {}", path, e);
return false;
}
}
private static String stripParameters(String contentType) {
if (contentType == null) {
return null;
}
int semi = contentType.indexOf(';');
return (semi < 0 ? contentType : contentType.substring(0, semi)).trim();
}
/**
* One PDF extracted from the response body. {@link #ownedTempFile} is non-null only when this
* extractor created the temp file (ZIP entries); the {@link #path} for direct-PDF responses
* remains owned by the wrapper.
*/
public record ExtractedPdf(Path path, TempFile ownedTempFile) implements AutoCloseable {
@Override
public void close() {
if (ownedTempFile != null) {
ownedTempFile.close();
}
}
}
}
@@ -1,289 +0,0 @@
package stirling.software.saas.payg.filter;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Objects;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.WriteListener;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpServletResponseWrapper;
import lombok.extern.slf4j.Slf4j;
import stirling.software.common.util.TempFile;
import stirling.software.common.util.TempFileManager;
/**
* Tees the controller's response body so the PAYG interceptor can hash it for OUTPUT lineage
* recording. Writes still flow through to the real client output stream unmodified — the wrapper
* just keeps a parallel copy.
*
* <p>Memory model: bytes accumulate in an in-memory {@link ByteArrayOutputStream} until the
* configured {@code in-memory-threshold-bytes} is crossed; after that the wrapper spills the
* existing buffer plus all subsequent writes to a {@link TempFile} owned by {@link
* TempFileManager}. Tiny responses (error JSONs, small PDFs) stay entirely in RAM with zero disk
* IO; large responses (split-to-ZIP, big compressed PDFs) spill cleanly. See design doc §8.
*
* <p>The interceptor calls {@link #materialisedPath()} from {@code afterCompletion} to get a {@code
* Path} suitable for the lineage detector + ZIP unpack. The wrapper guarantees a Path even if the
* response stayed in memory — it materialises the buffer to a {@link TempFile} on demand so callers
* have a uniform file-based interface.
*
* <p>{@link #close()} closes any {@link TempFile} the wrapper created. Callers MUST invoke close in
* a finally — typically the interceptor's {@code afterCompletion} after it's done hashing.
*
* <p><b>Thread safety:</b> all mutating methods (record paths, materialisedPath, close,
* resetBuffer) synchronize on the wrapper instance. The Servlet spec serialises controller writes
* onto a single dispatch thread, but the {@link jakarta.servlet.AsyncListener#onComplete} callback
* that closes the wrapper for async controllers runs on a container thread distinct from the
* dispatch thread that produced the body. The synchronization makes that handoff safe and also
* guards against future callers (e.g. tests) that might invoke {@link #materialisedPath} or {@link
* #close} from a non-dispatch thread.
*/
@Slf4j
public class PaygResponseBodyWrapper extends HttpServletResponseWrapper implements AutoCloseable {
private final TempFileManager tempFileManager;
private final long inMemoryThresholdBytes;
/** Lazily-created on the first getOutputStream() / getWriter() call. */
private TeeingServletOutputStream teeOut;
private PrintWriter writer;
/**
* In-memory accumulator until the threshold is crossed. Becomes null after spill (helps GC of
* potentially large buffers).
*/
private ByteArrayOutputStream memoryBuffer = new ByteArrayOutputStream();
/** Non-null once we've spilled. Owns the {@link TempFile} below. */
private OutputStream spillStream;
/** Non-null once we've spilled, OR once {@link #materialisedPath()} forced materialisation. */
private TempFile spillFile;
private long bytesWritten;
private boolean spilled;
public PaygResponseBodyWrapper(
HttpServletResponse response,
TempFileManager tempFileManager,
long inMemoryThresholdBytes) {
super(response);
this.tempFileManager = Objects.requireNonNull(tempFileManager, "tempFileManager");
if (inMemoryThresholdBytes < 0) {
throw new IllegalArgumentException(
"inMemoryThresholdBytes must be >= 0, got " + inMemoryThresholdBytes);
}
this.inMemoryThresholdBytes = inMemoryThresholdBytes;
}
@Override
public ServletOutputStream getOutputStream() throws IOException {
if (writer != null) {
// Servlet spec: getOutputStream() and getWriter() are mutually exclusive per request.
throw new IllegalStateException(
"getWriter() was already called on this response; cannot switch to getOutputStream()");
}
if (teeOut == null) {
teeOut = new TeeingServletOutputStream(super.getOutputStream());
}
return teeOut;
}
@Override
public PrintWriter getWriter() throws IOException {
if (teeOut != null) {
throw new IllegalStateException(
"getOutputStream() was already called on this response; cannot switch to getWriter()");
}
if (writer == null) {
String encoding = getCharacterEncoding() != null ? getCharacterEncoding() : "UTF-8";
// Wrap super.getOutputStream() directly with our TeeingServletOutputStream so writes
// through the Writer path also get tee'd. The Writer just adds character→byte encoding.
teeOut = new TeeingServletOutputStream(super.getOutputStream());
writer = new PrintWriter(new OutputStreamWriter(teeOut, encoding));
}
return writer;
}
@Override
public synchronized void resetBuffer() {
super.resetBuffer();
if (memoryBuffer != null) {
memoryBuffer.reset();
}
// If we'd already spilled, the only safe move is to abandon the spill file: the client
// hasn't seen the body yet (otherwise resetBuffer would be illegal), but our tee captured
// bytes we now want to forget.
if (spilled) {
closeSpillQuietly();
spillFile = null;
spillStream = null;
spilled = false;
memoryBuffer = new ByteArrayOutputStream();
}
bytesWritten = 0;
}
/**
* Returns a {@link Path} containing the full response body, or {@code null} if no bytes were
* written. The returned path is owned by this wrapper — do NOT delete or modify it. Use {@link
* #close()} to release.
*
* <p>If the response stayed under the threshold, this materialises the in-memory buffer to a
* {@link TempFile} on demand so the caller always gets a file-based handle (uniform with the
* spilled path).
*/
public synchronized Path materialisedPath() throws IOException {
if (bytesWritten == 0) {
return null;
}
// Flush the writer so any character data lands in the underlying byte stream first.
if (writer != null) {
writer.flush();
}
if (spilled) {
spillStream.flush();
return spillFile.getPath();
}
// Stayed in memory — materialise on demand for a uniform Path-based interface.
if (spillFile == null) {
spillFile = tempFileManager.createManagedTempFile(".body");
Files.write(spillFile.getPath(), memoryBuffer.toByteArray());
}
return spillFile.getPath();
}
public synchronized long bytesWritten() {
return bytesWritten;
}
@Override
public synchronized void close() {
closeSpillQuietly();
}
private void closeSpillQuietly() {
if (spillStream != null) {
try {
spillStream.close();
} catch (IOException e) {
log.debug("Ignoring close error on spill stream: {}", e.getMessage());
}
spillStream = null;
}
if (spillFile != null) {
spillFile.close(); // TempFile.close() deletes the file
spillFile = null;
}
}
/**
* Routes bytes both to the real client output stream AND to our buffer (in-memory or spilled).
* Writes are not re-batched — each call to the delegate corresponds exactly to one call here.
*/
private final class TeeingServletOutputStream extends ServletOutputStream {
private final ServletOutputStream delegate;
TeeingServletOutputStream(ServletOutputStream delegate) {
this.delegate = delegate;
}
@Override
public void write(int b) throws IOException {
delegate.write(b);
recordSingleByte((byte) b);
}
@Override
public void write(byte[] b, int off, int len) throws IOException {
delegate.write(b, off, len);
recordRange(b, off, len);
}
@Override
public void flush() throws IOException {
delegate.flush();
// Read spilled / spillStream under the outer monitor so we observe the publication
// written by spillToDisk() on another thread. The writers (recordSingleByte,
// recordRange, spillToDisk) already mutate these fields under
// synchronized(PaygResponseBodyWrapper.this); without matching locking here the
// JMM permits stale reads (false `spilled`, null `spillStream`) and Aikido AI
// flagged that gap.
synchronized (PaygResponseBodyWrapper.this) {
if (spilled && spillStream != null) {
spillStream.flush();
}
}
}
@Override
public void close() throws IOException {
delegate.close();
synchronized (PaygResponseBodyWrapper.this) {
if (spilled && spillStream != null) {
spillStream.flush();
}
}
}
@Override
public boolean isReady() {
return delegate.isReady();
}
@Override
public void setWriteListener(WriteListener writeListener) {
delegate.setWriteListener(writeListener);
}
}
private synchronized void recordSingleByte(byte b) throws IOException {
if (spilled) {
spillStream.write(b & 0xFF);
} else if (bytesWritten + 1 > inMemoryThresholdBytes) {
spillToDisk();
spillStream.write(b & 0xFF);
} else {
memoryBuffer.write(b & 0xFF);
}
bytesWritten++;
}
private synchronized void recordRange(byte[] b, int off, int len) throws IOException {
if (spilled) {
spillStream.write(b, off, len);
} else if (bytesWritten + len > inMemoryThresholdBytes) {
// This write crosses the threshold. Spill the existing in-memory buffer, then write
// this entire chunk to disk too — we don't bother splitting it for the sake of staying
// exactly at the threshold. Going over by at most one chunk is fine.
spillToDisk();
spillStream.write(b, off, len);
} else {
memoryBuffer.write(b, off, len);
}
bytesWritten += len;
}
private void spillToDisk() throws IOException {
spillFile = tempFileManager.createManagedTempFile(".body");
spillStream = Files.newOutputStream(spillFile.getPath());
memoryBuffer.writeTo(spillStream);
memoryBuffer = null; // help GC of potentially large buffer
spilled = true;
log.debug(
"PaygResponseBodyWrapper spilled to {} after {} bytes (threshold {})",
spillFile.getPath(),
bytesWritten,
inMemoryThresholdBytes);
}
}
@@ -1,138 +0,0 @@
package stirling.software.saas.payg.filter;
import java.io.IOException;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import jakarta.servlet.AsyncEvent;
import jakarta.servlet.AsyncListener;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import stirling.software.common.util.TempFileManager;
/**
* Wraps the {@link HttpServletResponse} with a {@link PaygResponseBodyWrapper} for every request,
* making the response body retrievable by the downstream {@code PaygChargeInterceptor} in {@code
* afterCompletion}. The wrapper is stashed as a request attribute under {@link #REQUEST_ATTRIBUTE}
* so the interceptor can find it.
*
* <p>Pure plumbing — no business logic. When {@code payg.filter.enabled=false} the filter passes
* through unchanged.
*
* <p>Lifecycle: the wrapper is closed in a {@code finally} after the chain returns for sync
* requests; for async controllers ({@code DeferredResult}, {@code CompletableFuture}), close is
* deferred to an {@link AsyncListener} so the wrapper survives the async window. Close is
* idempotent so a defensive call by the interceptor's {@code afterCompletion} is harmless.
*/
@Slf4j
@Component
@Profile("saas")
public class PaygResponseBodyWrapperFilter extends OncePerRequestFilter {
/** Request-attribute key under which the wrapper is exposed to the interceptor. */
public static final String REQUEST_ATTRIBUTE =
PaygResponseBodyWrapperFilter.class.getName() + ".WRAPPER";
private final TempFileManager tempFileManager;
private final PaygFilterProperties properties;
public PaygResponseBodyWrapperFilter(
TempFileManager tempFileManager, PaygFilterProperties properties) {
this.tempFileManager = tempFileManager;
this.properties = properties;
}
@Override
protected void doFilterInternal(
HttpServletRequest request, HttpServletResponse response, FilterChain chain)
throws ServletException, IOException {
if (!properties.isEnabled()) {
chain.doFilter(request, response);
return;
}
PaygResponseBodyWrapper wrapper;
try {
wrapper =
new PaygResponseBodyWrapper(
response,
tempFileManager,
properties.getResponse().getInMemoryThresholdBytes());
} catch (RuntimeException e) {
// Wrapper construction failure: fail-open. Pass through unwrapped — OUTPUT recording
// is lost but the customer's tool call still runs.
log.warn("PaygResponseBodyWrapper construction failed; passing through unwrapped", e);
chain.doFilter(request, response);
return;
}
request.setAttribute(REQUEST_ATTRIBUTE, wrapper);
boolean asyncStarted = false;
try {
chain.doFilter(request, wrapper);
asyncStarted = request.isAsyncStarted();
if (asyncStarted) {
// Async controller: defer attribute removal + close to async dispatch completion.
// The interceptor's afterCompletion fires on the async dispatch and needs the
// wrapper attribute still present at that point. close() is idempotent so a
// defensive call by the interceptor is harmless.
request.getAsyncContext().addListener(new ReleaseOnAsyncComplete(request, wrapper));
}
} finally {
if (!asyncStarted) {
// Sync path: interceptor.afterCompletion has already run inside chain.doFilter.
request.removeAttribute(REQUEST_ATTRIBUTE);
wrapper.close();
}
}
}
/**
* For async dispatches, removes the wrapper attribute and closes the wrapper after the async
* dispatch completes. The Servlet container fires exactly one of {@code onComplete} / {@code
* onError} / {@code onTimeout} per async context lifecycle.
*/
private static final class ReleaseOnAsyncComplete implements AsyncListener {
private final HttpServletRequest request;
private final PaygResponseBodyWrapper wrapper;
ReleaseOnAsyncComplete(HttpServletRequest request, PaygResponseBodyWrapper wrapper) {
this.request = request;
this.wrapper = wrapper;
}
private void release() {
request.removeAttribute(REQUEST_ATTRIBUTE);
wrapper.close();
}
@Override
public void onComplete(AsyncEvent event) {
release();
}
@Override
public void onTimeout(AsyncEvent event) {
release();
}
@Override
public void onError(AsyncEvent event) {
release();
}
@Override
public void onStartAsync(AsyncEvent event) {
// re-dispatch retains the listener — no-op
}
}
}
@@ -1,60 +0,0 @@
package stirling.software.saas.payg.filter;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import lombok.RequiredArgsConstructor;
/**
* Wires the PAYG filter + interceptor into Spring MVC. Two registrations:
*
* <ul>
* <li>{@link PaygResponseBodyWrapperFilter} as a Servlet filter — registered with no explicit
* order so it sits at the end of the Spring filter chain (after all security filters). Pure
* response-wrapping plumbing.
* <li>{@link PaygChargeInterceptor} as a Spring MVC interceptor — registered AFTER {@code
* UnifiedCreditInterceptor} so legacy credit rejections short-circuit before we hash inputs.
* Both intercept {@code /api/**} with the same admin/info/health exclusions as the legacy
* config.
* </ul>
*/
@Configuration
@Profile("saas")
@RequiredArgsConstructor
public class PaygWebMvcConfig implements WebMvcConfigurer {
private final PaygChargeInterceptor paygChargeInterceptor;
@Bean
public FilterRegistrationBean<PaygResponseBodyWrapperFilter>
paygResponseBodyWrapperFilterRegistration(PaygResponseBodyWrapperFilter filter) {
FilterRegistrationBean<PaygResponseBodyWrapperFilter> reg =
new FilterRegistrationBean<>(filter);
reg.addUrlPatterns("/api/*");
return reg;
}
/**
* Interceptor ordering: the legacy {@code UnifiedCreditInterceptor} (registered with default
* order = 0 in {@code CreditInterceptorConfig}) must run BEFORE this one so credit rejections
* short-circuit before we hash inputs. Explicit positive order guarantees this regardless of
* {@code WebMvcConfigurer} bean discovery order.
*/
public static final int INTERCEPTOR_ORDER = 1000;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(paygChargeInterceptor)
.addPathPatterns("/api/**")
.excludePathPatterns(
"/api/v1/credits/**",
"/api/v1/config/**",
"/api/v1/info/**",
"/api/v1/admin/**")
.order(INTERCEPTOR_ORDER);
}
}
@@ -1,37 +0,0 @@
package stirling.software.saas.payg.job;
import stirling.software.saas.payg.model.JobSource;
import stirling.software.saas.payg.model.ProcessType;
/**
* Input to {@link JobService#joinOrOpen}: who owns the request, what process shape it is, which
* policy version applies, and the step-limit ceiling derived from that policy for this caller
* surface. {@code stepLimit} is resolved by the caller (typically {@code JobChargeService}) rather
* than re-fetched here so the service stays free of policy-lookup concerns.
*/
public record JobContext(
Long ownerUserId,
Long ownerTeamId,
JobSource source,
ProcessType processType,
Long policyId,
int stepLimit) {
public JobContext {
if (ownerUserId == null) {
throw new IllegalArgumentException("ownerUserId is required");
}
if (source == null) {
throw new IllegalArgumentException("source is required");
}
if (processType == null) {
throw new IllegalArgumentException("processType is required");
}
if (policyId == null) {
throw new IllegalArgumentException("policyId is required");
}
if (stepLimit <= 0) {
throw new IllegalArgumentException("stepLimit must be > 0");
}
}
}
@@ -1,256 +0,0 @@
package stirling.software.saas.payg.job;
import java.io.IOException;
import java.nio.file.Path;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import lombok.extern.slf4j.Slf4j;
import stirling.software.saas.payg.lineage.HashLineageDetector;
import stirling.software.saas.payg.lineage.LineageMatch;
import stirling.software.saas.payg.lineage.LineageSignature;
import stirling.software.saas.payg.model.ArtifactKind;
import stirling.software.saas.payg.model.JobStatus;
import stirling.software.saas.payg.model.JobStepStatus;
import stirling.software.saas.payg.repository.ProcessingJobRepository;
import stirling.software.saas.payg.repository.ProcessingJobStepRepository;
/**
* Persistence + lineage policy layer for the PAYG process model. The hot-path entry point is {@link
* #joinOrOpen}, which applies the "any-match-joins, newest wins" multi-input rule.
*
* <p>The charge service ({@code JobChargeService}) orchestrates around this — it resolves the
* pricing policy, computes the step-limit ceiling for the current {@code JobSource}, calls {@link
* #joinOrOpen}, and decides whether to record a shadow charge based on the resulting {@link
* JoinOrOpenResult.Disposition}.
*/
@Service
@Profile("saas")
@Slf4j
public class JobService {
private final HashLineageDetector detector;
private final ProcessingJobRepository jobRepository;
private final ProcessingJobStepRepository stepRepository;
private final Duration workflowWindow;
public JobService(
HashLineageDetector detector,
ProcessingJobRepository jobRepository,
ProcessingJobStepRepository stepRepository,
@Value("${payg.lineage.workflow-window:PT5M}") Duration workflowWindow) {
this.detector = Objects.requireNonNull(detector, "detector");
this.jobRepository = Objects.requireNonNull(jobRepository, "jobRepository");
this.stepRepository = Objects.requireNonNull(stepRepository, "stepRepository");
Objects.requireNonNull(workflowWindow, "workflowWindow");
if (workflowWindow.isNegative() || workflowWindow.isZero()) {
throw new IllegalArgumentException(
"payg.lineage.workflow-window must be positive, got " + workflowWindow);
}
this.workflowWindow = workflowWindow;
}
/**
* Decide whether {@code inputs} should join an existing open process or start a new one, and
* persist that decision. Returns the job to attach to plus the disposition.
*
* <p>Rule: hash every input. If any input's signatures match an open process owned by the same
* user within the workflow window, attach to that process. When multiple inputs match different
* processes, the one with the freshest {@code lastStepAt} wins — preserves the
* "most-recent-job-wins" invariant the lineage primitives test for. When the matched process is
* already at its step-limit ceiling, fall through to opening a fresh process; the new job's
* input signatures are still recorded so downstream calls lineage-match to it.
*
* <p>Race note: the read of candidate matches and the subsequent write happen in one
* transaction at default isolation (READ COMMITTED in Postgres). A concurrent admin write or
* another tool call could change the match set between read and commit. For shadow mode the
* resulting diff is a low-grade comparison artefact; tighten isolation when real charging lands
* if it materialises as a real-money issue.
*/
@Transactional
public JoinOrOpenResult joinOrOpen(JobContext ctx, List<Path> inputs) throws IOException {
Objects.requireNonNull(ctx, "ctx");
Objects.requireNonNull(inputs, "inputs");
if (inputs.isEmpty()) {
throw new IllegalArgumentException("inputs must not be empty");
}
// Extract signatures ONCE per input, then reuse for both the lineage lookup and the
// post-decision record() call. Avoids hashing every input twice on the hot path.
Map<Path, Set<LineageSignature>> signaturesByInput = new HashMap<>(inputs.size());
for (Path input : inputs) {
signaturesByInput.put(input, detector.extractSignatures(input));
}
Optional<LineageMatch> bestMatch =
findBestMatch(ctx.ownerUserId(), inputs, signaturesByInput);
if (bestMatch.isPresent()) {
ProcessingJob existing =
jobRepository
.findById(bestMatch.get().jobId())
.orElseThrow(
() ->
new IllegalStateException(
"Lineage match returned jobId="
+ bestMatch.get().jobId()
+ " but no such ProcessingJob row"
+ " exists (stale signature?)"));
if (existing.getStepCount() < ctx.stepLimit()) {
return joinExisting(existing, signaturesByInput);
}
// Step-limit hit: spawn a fresh job. The new job will share input signatures with
// the existing chain so future tool calls still lineage-match into the workflow,
// but the freshest jobLastStepAt wins so they target the new one.
log.debug(
"Job {} hit step limit ({}); spawning new process within workflow.",
existing.getId(),
ctx.stepLimit());
}
return openFresh(ctx, signaturesByInput);
}
/**
* Records {@code outputFile}'s signatures against {@code jobId} as {@code OUTPUT}. Called after
* a tool runs successfully — failed tools don't record outputs. Multi-output tools call this
* once per output.
*/
@Transactional
public void recordOutput(UUID jobId, Path outputFile) throws IOException {
Objects.requireNonNull(jobId, "jobId");
Objects.requireNonNull(outputFile, "outputFile");
detector.record(jobId, outputFile, ArtifactKind.OUTPUT);
}
/** Appends an audit-trail step row after a tool call completes. */
@Transactional
public ProcessingJobStep appendStep(
UUID jobId,
String toolId,
JobStepStatus status,
Integer inputPages,
Long inputBytes,
String errorCode) {
Objects.requireNonNull(jobId, "jobId");
Objects.requireNonNull(toolId, "toolId");
Objects.requireNonNull(status, "status");
ProcessingJobStep step = new ProcessingJobStep();
step.setJobId(jobId);
step.setToolId(toolId);
step.setStatus(status);
LocalDateTime now = LocalDateTime.now();
step.setStartedAt(now);
step.setCompletedAt(now);
step.setInputPages(inputPages);
step.setInputBytes(inputBytes);
step.setErrorCode(errorCode);
return stepRepository.save(step);
}
/**
* Closes a job. Idempotent — closing an already-closed job is a silent no-op returning the
* existing row, so multiple close paths (explicit caller, FE on-unload, stale scheduler) all
* compose safely.
*/
@Transactional
public ProcessingJob close(UUID jobId) {
Objects.requireNonNull(jobId, "jobId");
ProcessingJob job =
jobRepository
.findById(jobId)
.orElseThrow(
() ->
new IllegalArgumentException(
"No ProcessingJob with id " + jobId));
if (job.getStatus() != JobStatus.OPEN) {
return job;
}
job.setStatus(JobStatus.CLOSED);
job.setClosedAt(LocalDateTime.now());
return jobRepository.save(job);
}
/** Returns open jobs whose {@code last_step_at} is older than the workflow window. */
@Transactional(readOnly = true)
public List<ProcessingJob> findStale() {
return jobRepository.findStale(JobStatus.OPEN, LocalDateTime.now().minus(workflowWindow));
}
/**
* Closes all jobs returned by {@link #findStale}. Returns the count closed. Each transition
* goes through {@link #close} semantics (idempotent), so re-running this on an empty stale set
* is safe.
*/
@Transactional
public int closeStale() {
List<ProcessingJob> stale = findStale();
LocalDateTime now = LocalDateTime.now();
for (ProcessingJob j : stale) {
j.setStatus(JobStatus.CLOSED);
j.setClosedAt(now);
}
if (!stale.isEmpty()) {
jobRepository.saveAll(stale);
}
return stale.size();
}
private Optional<LineageMatch> findBestMatch(
Long userId, List<Path> inputs, Map<Path, Set<LineageSignature>> signaturesByInput) {
List<LineageMatch> matches = new ArrayList<>(inputs.size());
for (Path input : inputs) {
detector.detect(userId, signaturesByInput.get(input)).ifPresent(matches::add);
}
return matches.stream().max(Comparator.comparing(LineageMatch::jobLastStepAt));
}
private JoinOrOpenResult joinExisting(
ProcessingJob existing, Map<Path, Set<LineageSignature>> signaturesByInput) {
existing.setStepCount(existing.getStepCount() + 1);
existing.setLastStepAt(LocalDateTime.now());
ProcessingJob saved = jobRepository.save(existing);
recordAllInputs(saved.getId(), signaturesByInput);
return new JoinOrOpenResult(saved, JoinOrOpenResult.Disposition.JOINED);
}
private JoinOrOpenResult openFresh(
JobContext ctx, Map<Path, Set<LineageSignature>> signaturesByInput) {
ProcessingJob fresh = new ProcessingJob();
fresh.setId(UUID.randomUUID());
fresh.setOwnerUserId(ctx.ownerUserId());
fresh.setOwnerTeamId(ctx.ownerTeamId());
fresh.setProcessType(ctx.processType());
fresh.setSource(ctx.source());
fresh.setPolicyId(ctx.policyId());
fresh.setStepCount(1);
LocalDateTime now = LocalDateTime.now();
fresh.setStartedAt(now);
fresh.setLastStepAt(now);
fresh.setStatus(JobStatus.OPEN);
ProcessingJob saved = jobRepository.save(fresh);
recordAllInputs(saved.getId(), signaturesByInput);
return new JoinOrOpenResult(saved, JoinOrOpenResult.Disposition.OPENED);
}
private void recordAllInputs(UUID jobId, Map<Path, Set<LineageSignature>> signaturesByInput) {
for (Set<LineageSignature> signatures : signaturesByInput.values()) {
detector.record(jobId, signatures, ArtifactKind.INPUT);
}
}
}
@@ -1,17 +0,0 @@
package stirling.software.saas.payg.job;
/**
* Output of {@link JobService#joinOrOpen}. {@code OPENED} means the charge layer should compute
* units and record a shadow charge (or, post-shadow, actually debit). {@code JOINED} means the call
* attached to an existing process — no further charge, just an audit-trail step append.
*
* <p>Step-limit overflow on a matched job surfaces as {@code OPENED}: the lineage tree is preserved
* via shared input signatures, but the limit means we start a fresh billable process.
*/
public record JoinOrOpenResult(ProcessingJob job, Disposition disposition) {
public enum Disposition {
OPENED,
JOINED
}
}
@@ -1,36 +0,0 @@
package stirling.software.saas.payg.job;
import org.springframework.context.annotation.Profile;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
/**
* Auto-closes {@code OPEN} jobs whose {@code last_step_at} is older than the workflow window. Runs
* every minute. API users never have to call {@code close()} explicitly — this scheduler is the
* safety net.
*
* <p>Single-fire only at V1: not {@code @SchedulerLock}'d, consistent with the other
* {@code @Scheduled} tasks in {@code :saas} (none of them are guarded against multi-pod
* double-fires today either). Multi-pod cluster-correctness for all schedulers is tracked in design
* § 9 as a separate cleanup. The underlying {@code closeStale()} call is idempotent — duplicate
* firings read an empty stale set on the second pod, no data corruption risk.
*/
@Component
@Profile("saas")
@RequiredArgsConstructor
@Slf4j
public class StaleJobCloser {
private final JobService jobService;
@Scheduled(fixedRateString = "${payg.job.stale-close-interval-ms:60000}")
public void closeStale() {
int closed = jobService.closeStale();
if (closed > 0) {
log.info("StaleJobCloser closed {} job(s) idle past the workflow window.", closed);
}
}
}
@@ -58,45 +58,37 @@ public class DefaultHashLineageDetector implements HashLineageDetector {
@Override
public Optional<LineageMatch> detect(Long userId, Path inputFile) throws IOException {
Objects.requireNonNull(inputFile, "inputFile");
return detect(userId, extractSignatures(inputFile));
}
@Override
public Optional<LineageMatch> detect(Long userId, Set<LineageSignature> signatures) {
Objects.requireNonNull(userId, "userId");
Objects.requireNonNull(signatures, "signatures");
Objects.requireNonNull(inputFile, "inputFile");
Set<LineageSignature> signatures = extractAll(inputFile);
if (signatures.isEmpty()) {
// No extractor produced anything for this content. Treat as no-match.
log.debug("No signatures extracted from {}; lineage check returns empty.", inputFile);
return Optional.empty();
}
return store.findOpenJobForSignatures(userId, signatures, workflowWindow);
}
@Override
public void record(UUID jobId, Path file, ArtifactKind kind) throws IOException {
Objects.requireNonNull(file, "file");
record(jobId, extractSignatures(file), kind);
}
@Override
public void record(UUID jobId, Set<LineageSignature> signatures, ArtifactKind kind) {
Objects.requireNonNull(jobId, "jobId");
Objects.requireNonNull(signatures, "signatures");
Objects.requireNonNull(file, "file");
Objects.requireNonNull(kind, "kind");
Set<LineageSignature> signatures = extractAll(file);
if (signatures.isEmpty()) {
log.debug("No signatures to record for job {} ({}); skipping.", jobId, kind);
log.debug(
"No signatures extracted from {} for job {} ({}); nothing recorded.",
file,
jobId,
kind);
return;
}
store.record(jobId, signatures, kind);
}
@Override
public Set<LineageSignature> extractSignatures(Path file) {
Objects.requireNonNull(file, "file");
return extractAll(file);
}
private Set<LineageSignature> extractAll(Path file) {
Set<LineageSignature> union = new HashSet<>();
for (LineageSignatureExtractor extractor : extractors) {
@@ -3,7 +3,6 @@ package stirling.software.saas.payg.lineage;
import java.io.IOException;
import java.nio.file.Path;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import stirling.software.saas.payg.model.ArtifactKind;
@@ -34,25 +33,4 @@ public interface HashLineageDetector {
/** Records the file's signatures against the given job as either INPUT or OUTPUT. */
void record(UUID jobId, Path file, ArtifactKind kind) throws IOException;
/**
* Pre-computes the signature set for {@code file} so callers can avoid hashing the same bytes
* twice when they need both {@link #detect} and {@link #record} for the same file. Returned set
* may be empty (no extractor recognised the content) — treat as "no signatures to match or
* record" by both consumers.
*/
Set<LineageSignature> extractSignatures(Path file);
/**
* Same as {@link #detect(Long, Path)} but operating on pre-computed signatures. Useful when the
* caller has already extracted them (e.g. via {@link #extractSignatures}) and wants to avoid
* re-hashing. Empty {@code signatures} short-circuits to {@link Optional#empty}.
*/
Optional<LineageMatch> detect(Long userId, Set<LineageSignature> signatures);
/**
* Same as {@link #record(UUID, Path, ArtifactKind)} but operating on pre-computed signatures.
* Empty {@code signatures} is a no-op.
*/
void record(UUID jobId, Set<LineageSignature> signatures, ArtifactKind kind);
}
@@ -1,54 +0,0 @@
package stirling.software.saas.payg.lineage;
import java.time.Duration;
import java.time.Instant;
import java.util.Objects;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Profile;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import lombok.extern.slf4j.Slf4j;
/**
* Deletes {@code job_artifact_hash} rows older than the configured retention window. The workflow
* window is 5 minutes; we keep an extra hour of headroom as a safety margin (covers clock skew,
* in-flight requests, brief outages of this scheduler). Runs hourly.
*
* <p>Like {@link stirling.software.saas.payg.job.StaleJobCloser}, this is not
* {@code @SchedulerLock}'d — duplicate firings on multi-pod deploys would both run a {@code DELETE
* WHERE created_at < cutoff}, the second seeing zero rows to delete. Idempotent, wasted IO at
* worst.
*/
@Component
@Profile("saas")
@Slf4j
public class LineagePruneScheduler {
private final JobLineageStore store;
private final Duration retention;
public LineagePruneScheduler(
JobLineageStore store, @Value("${payg.lineage.retention:PT1H}") Duration retention) {
this.store = Objects.requireNonNull(store, "store");
Objects.requireNonNull(retention, "retention");
if (retention.isNegative() || retention.isZero()) {
throw new IllegalArgumentException(
"payg.lineage.retention must be positive, got " + retention);
}
this.retention = retention;
}
@Scheduled(cron = "${payg.lineage.prune-cron:0 0 * * * *}", zone = "UTC")
public void prune() {
Instant cutoff = Instant.now().minus(retention);
int deleted = store.pruneOlderThan(cutoff);
if (deleted > 0) {
log.info(
"LineagePruneScheduler deleted {} job_artifact_hash row(s) older than {}.",
deleted,
cutoff);
}
}
}
@@ -1,18 +0,0 @@
package stirling.software.saas.payg.model;
/**
* Lifecycle state for a {@code payg_shadow_charge} row. Mimics the Stripe meter_event_adjustment
* (type=cancel) mechanism that real-mode will invoke when a freshly-opened process fails on its
* first step. The reconciliation report's "true net" query is {@code SUM(payg_units) WHERE status =
* 'CHARGED'}.
*/
public enum ShadowChargeStatus {
/** Default at process open; the would-be charge stands. */
CHARGED,
/**
* Set when a 5xx first-step failure was observed in the same request's {@code afterCompletion}.
* Real-mode equivalent is a successful Stripe {@code meter_event_adjustment} posted in the same
* transaction-after-commit hook.
*/
REFUNDED
}
@@ -79,28 +79,19 @@ public class PricingPolicyService {
* {@code is_default = TRUE}. Throws {@link IllegalStateException} if no default exists — the
* seed migration is expected to put one there.
*
* <p>A {@code null} {@code teamId} (admin-created user, deleted team, pre-team-migration
* account) is valid and returns the default policy directly. Throwing here would silently
* exclude the team-less cohort from PAYG via the filter's fail-open path, biasing the
* shadow-vs-legacy reconciliation.
*
* <p>{@link Transactional}({@code readOnly = true}) so the eager-loaded {@code stepLimits} and
* {@code stripePriceIds} collections initialize inside the same session.
*/
@Transactional(readOnly = true)
public PricingPolicy getEffectivePolicy(Long teamId) {
if (teamId == null) {
return loadDefaultPolicy();
}
Objects.requireNonNull(teamId, "teamId");
return byTeamCache.get(teamId, this::loadEffectivePolicy);
}
/** Bypasses the cache. Useful for admin endpoints that want a fresh read after a mutation. */
@Transactional(readOnly = true)
public PricingPolicy getEffectivePolicyUncached(Long teamId) {
if (teamId == null) {
return loadDefaultPolicy();
}
Objects.requireNonNull(teamId, "teamId");
return loadEffectivePolicy(teamId);
}
@@ -252,10 +243,6 @@ public class PricingPolicyService {
teamId,
id);
}
return loadDefaultPolicy();
}
private PricingPolicy loadDefaultPolicy() {
return policyRepository
.findFirstByIsDefaultTrue()
.orElseThrow(
@@ -2,8 +2,6 @@ package stirling.software.saas.payg.repository;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
@@ -21,12 +19,4 @@ public interface PaygShadowChargeRepository extends JpaRepository<PaygShadowChar
+ " ORDER BY s.occurredAt DESC")
List<PaygShadowCharge> findInWindow(
@Param("from") LocalDateTime from, @Param("to") LocalDateTime to);
/**
* The shadow row written when the given process was opened. At most one row per {@code jobId}
* exists by construction — {@code openProcess} writes exactly one row on OPENED and zero on
* JOINED — so callers can treat the result as a single optional. Returns the first row by id
* defensively if a duplicate ever appears.
*/
Optional<PaygShadowCharge> findFirstByJobIdOrderByIdAsc(UUID jobId);
}
@@ -8,8 +8,6 @@ import org.hibernate.annotations.CreationTimestamp;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.EnumType;
import jakarta.persistence.Enumerated;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
@@ -19,16 +17,10 @@ import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import stirling.software.saas.payg.model.ShadowChargeStatus;
/**
* Per-job comparison row written while a team is in {@code PAYG_SHADOW} mode: what the legacy
* engine actually charged vs. what the PAYG engine would have charged. Aggregated daily by the
* shadow-reconciliation report; deletable after promotion.
*
* <p>The {@link #status} column mirrors the eventual Stripe meter_event_adjustment(cancel) flow:
* rows are written {@code CHARGED}; a freshly-opened process whose first step 5xx's is flipped to
* {@code REFUNDED} in the same request's {@code afterCompletion}.
*/
@Entity
@Table(name = "payg_shadow_charge")
@@ -63,18 +55,6 @@ public class PaygShadowCharge implements Serializable {
@Column(name = "diff_pct", nullable = false)
private Integer diffPct;
@Enumerated(EnumType.STRING)
@Column(name = "status", nullable = false, length = 16)
private ShadowChargeStatus status = ShadowChargeStatus.CHARGED;
/** Set when {@link #status} flips to {@link ShadowChargeStatus#REFUNDED}. */
@Column(name = "refunded_at")
private LocalDateTime refundedAt;
/** Free-form reason, e.g. {@code "first-step-5xx:503"}. */
@Column(name = "refund_reason", length = 128)
private String refundReason;
@CreationTimestamp
@Column(name = "occurred_at", nullable = false, updatable = false)
private LocalDateTime occurredAt;
@@ -1,20 +0,0 @@
-- Refund tracking on shadow rows. Shadow models the eventual Stripe meter_event_adjustment(cancel)
-- by flipping status from CHARGED to REFUNDED in the same request's afterCompletion when a
-- freshly-opened process fails with 5xx on its first step.
--
-- Reconciliation report selects SUM(payg_units) WHERE status = 'CHARGED' to get the true net
-- Stripe would bill.
ALTER TABLE payg_shadow_charge
ADD COLUMN IF NOT EXISTS status VARCHAR(16) NOT NULL DEFAULT 'CHARGED',
ADD COLUMN IF NOT EXISTS refunded_at TIMESTAMP,
ADD COLUMN IF NOT EXISTS refund_reason VARCHAR(128);
CREATE INDEX IF NOT EXISTS idx_payg_shadow_status_time
ON payg_shadow_charge (status, occurred_at);
-- Hot-path index for findFirstByJobIdOrderByIdAsc: hit on every 5xx-first-step refund to flip
-- the row to REFUNDED. UNIQUE because at most one shadow row exists per processing_job by
-- construction (openProcess writes exactly one on OPENED, zero on JOINED).
CREATE UNIQUE INDEX IF NOT EXISTS uq_payg_shadow_job_id
ON payg_shadow_charge (job_id);
@@ -1,367 +0,0 @@
package stirling.software.saas.payg.charge;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyList;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.mockito.ArgumentCaptor;
import org.mockito.Mockito;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.multipart.MultipartFile;
import stirling.software.saas.payg.docs.DocumentClassifier;
import stirling.software.saas.payg.docs.DocumentMetrics;
import stirling.software.saas.payg.job.JobContext;
import stirling.software.saas.payg.job.JobService;
import stirling.software.saas.payg.job.JoinOrOpenResult;
import stirling.software.saas.payg.job.ProcessingJob;
import stirling.software.saas.payg.model.JobSource;
import stirling.software.saas.payg.model.JobStatus;
import stirling.software.saas.payg.model.ProcessType;
import stirling.software.saas.payg.model.ShadowChargeStatus;
import stirling.software.saas.payg.policy.PricingPolicy;
import stirling.software.saas.payg.policy.PricingPolicyService;
import stirling.software.saas.payg.repository.PaygShadowChargeRepository;
import stirling.software.saas.payg.repository.ProcessingJobRepository;
import stirling.software.saas.payg.shadow.PaygShadowCharge;
/**
* Exercises {@link JobChargeService} as an orchestrator: policy lookup, step-limit resolution,
* delegate to {@code JobService}, write shadow row when OPENED, skip everything when JOINED.
*/
class JobChargeServiceTest {
private JobService jobService;
private PricingPolicyService policyService;
private DocumentClassifier classifier;
private PaygShadowChargeRepository shadowRepo;
private ProcessingJobRepository jobRepo;
private JobChargeService service;
@BeforeEach
void setUp() {
jobService = Mockito.mock(JobService.class);
policyService = Mockito.mock(PricingPolicyService.class);
classifier = Mockito.mock(DocumentClassifier.class);
shadowRepo = Mockito.mock(PaygShadowChargeRepository.class);
jobRepo = Mockito.mock(ProcessingJobRepository.class);
service = new JobChargeService(jobService, policyService, classifier, shadowRepo, jobRepo);
}
@Test
void openProcess_joinedDisposition_skipsClassifierAndShadowWrite(@TempDir Path tmp)
throws IOException {
// Setup: policy + a JOINED result.
PricingPolicy policy = stubPolicy(/*minCharge*/ 1, Map.of(JobSource.WEB, 10));
when(policyService.getEffectivePolicy(100L)).thenReturn(policy);
ProcessingJob joinedJob = openJob(UUID.randomUUID());
when(jobService.joinOrOpen(any(JobContext.class), anyList()))
.thenReturn(new JoinOrOpenResult(joinedJob, JoinOrOpenResult.Disposition.JOINED));
JobInput in = jobInput(tmp, "in.pdf", "application/pdf");
ChargeOutcome out =
service.openProcess(
new ChargeContext(42L, 100L, JobSource.WEB, ProcessType.SINGLE_TOOL),
List.of(in));
assertThat(out.disposition()).isEqualTo(ChargeOutcome.Disposition.JOINED);
assertThat(out.processId()).isEqualTo(joinedJob.getId());
assertThat(out.units()).isZero();
verify(classifier, never()).classify(any(MultipartFile.class), any());
verify(classifier, never()).classify(anyList(), any());
verify(shadowRepo, never()).save(any());
}
@Test
void openProcess_openedSingleFile_classifiesAndWritesShadowRow(@TempDir Path tmp)
throws IOException {
PricingPolicy policy = stubPolicy(/*minCharge*/ 1, Map.of(JobSource.WEB, 10));
when(policyService.getEffectivePolicy(100L)).thenReturn(policy);
ProcessingJob newJob = openJob(UUID.randomUUID());
when(jobService.joinOrOpen(any(JobContext.class), anyList()))
.thenReturn(new JoinOrOpenResult(newJob, JoinOrOpenResult.Disposition.OPENED));
JobInput in = jobInput(tmp, "in.pdf", "application/pdf");
when(classifier.classify(any(MultipartFile.class), any(Path.class), eq(policy)))
.thenReturn(new DocumentMetrics(50, 1024L, "application/pdf", 4));
ChargeOutcome out =
service.openProcess(
new ChargeContext(42L, 100L, JobSource.WEB, ProcessType.SINGLE_TOOL),
List.of(in));
assertThat(out.disposition()).isEqualTo(ChargeOutcome.Disposition.OPENED);
assertThat(out.units()).isEqualTo(4);
// Single-file path called single-file classifier overload (with Path), not the list one.
verify(classifier, times(1))
.classify(any(MultipartFile.class), any(Path.class), eq(policy));
verify(classifier, never()).classify(anyList(), anyList(), eq(policy));
ArgumentCaptor<PaygShadowCharge> captor = ArgumentCaptor.forClass(PaygShadowCharge.class);
verify(shadowRepo).save(captor.capture());
PaygShadowCharge row = captor.getValue();
assertThat(row.getTeamId()).isEqualTo(100L);
assertThat(row.getJobId()).isEqualTo(newJob.getId());
assertThat(row.getPolicyId()).isEqualTo(policy.getId());
assertThat(row.getPaygUnits()).isEqualTo(4);
// Legacy comparison not wired yet — zeroed until CreditService is wired in the follow-up.
assertThat(row.getLegacyCreditsCharged()).isZero();
assertThat(row.getDiffPct()).isZero();
// Job entity carries the classified docUnits so close-time receipts can render correctly.
assertThat(newJob.getDocUnits()).isEqualTo(4);
}
@Test
void openProcess_openedMultiFile_usesListClassifier(@TempDir Path tmp) throws IOException {
PricingPolicy policy = stubPolicy(/*minCharge*/ 1, Map.of(JobSource.WEB, 10));
when(policyService.getEffectivePolicy(100L)).thenReturn(policy);
ProcessingJob newJob = openJob(UUID.randomUUID());
when(jobService.joinOrOpen(any(JobContext.class), anyList()))
.thenReturn(new JoinOrOpenResult(newJob, JoinOrOpenResult.Disposition.OPENED));
JobInput a = jobInput(tmp, "a.pdf", "application/pdf");
JobInput b = jobInput(tmp, "b.pdf", "application/pdf");
when(classifier.classify(anyList(), anyList(), eq(policy)))
.thenReturn(new DocumentMetrics(100, 2048L, "application/pdf", 7));
ChargeOutcome out =
service.openProcess(
new ChargeContext(42L, 100L, JobSource.WEB, ProcessType.AUTOMATION),
List.of(a, b));
assertThat(out.units()).isEqualTo(7);
verify(classifier, never()).classify(any(MultipartFile.class), any(Path.class), any());
verify(classifier, times(1)).classify(anyList(), anyList(), eq(policy));
}
@Test
void openProcess_minChargeUnitsFloorApplied(@TempDir Path tmp) throws IOException {
// Policy says min 5 units. Classifier returns 2. Expect 5 to be charged.
PricingPolicy policy = stubPolicy(/*minCharge*/ 5, Map.of(JobSource.WEB, 10));
when(policyService.getEffectivePolicy(100L)).thenReturn(policy);
ProcessingJob newJob = openJob(UUID.randomUUID());
when(jobService.joinOrOpen(any(JobContext.class), anyList()))
.thenReturn(new JoinOrOpenResult(newJob, JoinOrOpenResult.Disposition.OPENED));
when(classifier.classify(any(MultipartFile.class), any(Path.class), eq(policy)))
.thenReturn(new DocumentMetrics(10, 1024L, "application/pdf", 2));
ChargeOutcome out =
service.openProcess(
new ChargeContext(42L, 100L, JobSource.WEB, ProcessType.SINGLE_TOOL),
List.of(jobInput(tmp, "in.pdf", "application/pdf")));
assertThat(out.units()).isEqualTo(5);
}
@Test
void openProcess_resolvesStepLimitFromPolicy_perJobSource(@TempDir Path tmp)
throws IOException {
// Different limits per source: WEB=10, PIPELINE=20. Verify the right one is passed.
PricingPolicy policy =
stubPolicy(/*minCharge*/ 1, Map.of(JobSource.WEB, 10, JobSource.PIPELINE, 20));
when(policyService.getEffectivePolicy(100L)).thenReturn(policy);
ProcessingJob newJob = openJob(UUID.randomUUID());
when(jobService.joinOrOpen(any(JobContext.class), anyList()))
.thenReturn(new JoinOrOpenResult(newJob, JoinOrOpenResult.Disposition.OPENED));
when(classifier.classify(any(MultipartFile.class), any(Path.class), eq(policy)))
.thenReturn(new DocumentMetrics(1, 100L, "application/pdf", 1));
service.openProcess(
new ChargeContext(42L, 100L, JobSource.PIPELINE, ProcessType.AUTOMATION),
List.of(jobInput(tmp, "in.pdf", "application/pdf")));
ArgumentCaptor<JobContext> ctxCaptor = ArgumentCaptor.forClass(JobContext.class);
verify(jobService).joinOrOpen(ctxCaptor.capture(), anyList());
assertThat(ctxCaptor.getValue().stepLimit()).isEqualTo(20);
assertThat(ctxCaptor.getValue().source()).isEqualTo(JobSource.PIPELINE);
assertThat(ctxCaptor.getValue().policyId()).isEqualTo(policy.getId());
}
@Test
void openProcess_missingStepLimitForSource_fallsBackToConservativeDefault(@TempDir Path tmp)
throws IOException {
// Policy has no entry for DESKTOP_APP — should fall through to the conservative default
// (10) rather than throwing or treating as unlimited.
PricingPolicy policy = stubPolicy(/*minCharge*/ 1, Map.of(JobSource.WEB, 10));
when(policyService.getEffectivePolicy(100L)).thenReturn(policy);
ProcessingJob newJob = openJob(UUID.randomUUID());
when(jobService.joinOrOpen(any(JobContext.class), anyList()))
.thenReturn(new JoinOrOpenResult(newJob, JoinOrOpenResult.Disposition.OPENED));
when(classifier.classify(any(MultipartFile.class), any(Path.class), eq(policy)))
.thenReturn(new DocumentMetrics(1, 100L, "application/pdf", 1));
service.openProcess(
new ChargeContext(42L, 100L, JobSource.DESKTOP_APP, ProcessType.SINGLE_TOOL),
List.of(jobInput(tmp, "in.pdf", "application/pdf")));
ArgumentCaptor<JobContext> ctxCaptor = ArgumentCaptor.forClass(JobContext.class);
verify(jobService).joinOrOpen(ctxCaptor.capture(), anyList());
assertThat(ctxCaptor.getValue().stepLimit()).isEqualTo(10);
}
@Test
void openProcess_emptyInputs_throws() {
assertThatThrownBy(
() ->
service.openProcess(
new ChargeContext(
42L, 100L, JobSource.WEB, ProcessType.SINGLE_TOOL),
List.of()))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("inputs must not be empty");
}
@Test
void markFirstStepFailed_flipsShadowRowAndClosesProcess() {
UUID jobId = UUID.randomUUID();
PaygShadowCharge row = new PaygShadowCharge();
row.setJobId(jobId);
row.setStatus(ShadowChargeStatus.CHARGED);
when(shadowRepo.findFirstByJobIdOrderByIdAsc(jobId)).thenReturn(java.util.Optional.of(row));
ProcessingJob job = openJob(jobId);
when(jobRepo.findById(jobId)).thenReturn(java.util.Optional.of(job));
service.markFirstStepFailed(jobId, "first-step-5xx:503");
assertThat(row.getStatus()).isEqualTo(ShadowChargeStatus.REFUNDED);
assertThat(row.getRefundedAt()).isNotNull();
assertThat(row.getRefundReason()).isEqualTo("first-step-5xx:503");
assertThat(job.getStatus()).isEqualTo(JobStatus.CLOSED);
assertThat(job.getClosedAt()).isNotNull();
verify(shadowRepo).save(row);
verify(jobRepo).save(job);
}
@Test
void markFirstStepFailed_alreadyRefunded_isNoOp() {
UUID jobId = UUID.randomUUID();
PaygShadowCharge row = new PaygShadowCharge();
row.setJobId(jobId);
row.setStatus(ShadowChargeStatus.REFUNDED);
when(shadowRepo.findFirstByJobIdOrderByIdAsc(jobId)).thenReturn(java.util.Optional.of(row));
ProcessingJob job = openJob(jobId);
job.setStatus(JobStatus.CLOSED);
when(jobRepo.findById(jobId)).thenReturn(java.util.Optional.of(job));
service.markFirstStepFailed(jobId, "first-step-5xx:500");
verify(shadowRepo, never()).save(any());
verify(jobRepo, never()).save(any());
}
@Test
void markFirstStepFailed_noShadowRow_stillClosesProcess() {
UUID jobId = UUID.randomUUID();
when(shadowRepo.findFirstByJobIdOrderByIdAsc(jobId)).thenReturn(java.util.Optional.empty());
ProcessingJob job = openJob(jobId);
when(jobRepo.findById(jobId)).thenReturn(java.util.Optional.of(job));
service.markFirstStepFailed(jobId, "first-step-5xx:503");
assertThat(job.getStatus()).isEqualTo(JobStatus.CLOSED);
verify(jobRepo).save(job);
}
@Test
void markFirstStepFailed_trimsLongRefundReason() {
UUID jobId = UUID.randomUUID();
PaygShadowCharge row = new PaygShadowCharge();
row.setStatus(ShadowChargeStatus.CHARGED);
when(shadowRepo.findFirstByJobIdOrderByIdAsc(jobId)).thenReturn(java.util.Optional.of(row));
when(jobRepo.findById(jobId)).thenReturn(java.util.Optional.empty());
String oversized = "x".repeat(200);
service.markFirstStepFailed(jobId, oversized);
assertThat(row.getRefundReason()).hasSize(128);
}
@Test
void decrementStepCount_decrementsByOne() {
UUID jobId = UUID.randomUUID();
ProcessingJob job = openJob(jobId);
job.setStepCount(3);
when(jobRepo.findById(jobId)).thenReturn(java.util.Optional.of(job));
service.decrementStepCount(jobId);
assertThat(job.getStepCount()).isEqualTo(2);
verify(jobRepo).save(job);
}
@Test
void decrementStepCount_floorAtOne_neverDrivesNegative() {
UUID jobId = UUID.randomUUID();
ProcessingJob job = openJob(jobId);
job.setStepCount(1);
when(jobRepo.findById(jobId)).thenReturn(java.util.Optional.of(job));
service.decrementStepCount(jobId);
assertThat(job.getStepCount()).isEqualTo(1);
verify(jobRepo, never()).save(any());
}
@Test
void decrementStepCount_missingJob_isNoOp() {
UUID jobId = UUID.randomUUID();
when(jobRepo.findById(jobId)).thenReturn(java.util.Optional.empty());
service.decrementStepCount(jobId); // must not throw
verify(jobRepo, never()).save(any());
}
// --- helpers --------------------------------------------------------------------------------
private static PricingPolicy stubPolicy(int minCharge, Map<JobSource, Integer> stepLimits) {
PricingPolicy p = new PricingPolicy();
p.setId(42L);
p.setVersion("v1-test");
p.setEffectiveFrom(LocalDateTime.now());
p.setDocPagesPerUnit(25);
p.setDocBytesPerUnit(5L * 1024 * 1024);
p.setMinChargeUnits(minCharge);
p.setFileUnitCap(1000);
p.setStepLimits(new HashMap<>(stepLimits));
p.setIsDefault(true);
return p;
}
private static ProcessingJob openJob(UUID id) {
ProcessingJob j = new ProcessingJob();
j.setId(id);
j.setStatus(JobStatus.OPEN);
j.setStepCount(1);
j.setStartedAt(LocalDateTime.now());
j.setLastStepAt(LocalDateTime.now());
j.setSource(JobSource.WEB);
j.setProcessType(ProcessType.SINGLE_TOOL);
return j;
}
private static JobInput jobInput(Path tmp, String name, String contentType) throws IOException {
Path p = tmp.resolve(name);
Files.writeString(p, "fixture-" + name);
MultipartFile mp = new MockMultipartFile("file", name, contentType, Files.readAllBytes(p));
return new JobInput(mp, p);
}
}
@@ -1,420 +0,0 @@
package stirling.software.saas.payg.filter;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyList;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
import java.io.IOException;
import java.lang.reflect.Method;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.mock.web.MockMultipartHttpServletRequest;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.method.HandlerMethod;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.simple.SimpleMeterRegistry;
import stirling.software.common.annotations.AutoJobPostMapping;
import stirling.software.common.model.ApplicationProperties;
import stirling.software.common.util.TempFileManager;
import stirling.software.common.util.TempFileRegistry;
import stirling.software.proprietary.security.database.repository.UserRepository;
import stirling.software.proprietary.security.model.User;
import stirling.software.saas.payg.charge.ChargeOutcome;
import stirling.software.saas.payg.charge.JobChargeService;
import stirling.software.saas.payg.job.JobService;
import stirling.software.saas.payg.model.JobStepStatus;
/**
* Pure-Mockito tests for {@link PaygChargeInterceptor}. Real {@link TempFileManager} but mocked
* downstream charge/job services so the test runs without a Spring context.
*/
class PaygChargeInterceptorTest {
private JobChargeService chargeService;
private JobService jobService;
private UserRepository userRepository;
private PaygOutputExtractor outputExtractor;
private PaygFilterProperties properties;
private MeterRegistry meterRegistry;
private TempFileManager tempFileManager;
private PaygChargeInterceptor interceptor;
@BeforeEach
void setUp() {
chargeService = org.mockito.Mockito.mock(JobChargeService.class);
jobService = org.mockito.Mockito.mock(JobService.class);
userRepository = org.mockito.Mockito.mock(UserRepository.class);
outputExtractor = org.mockito.Mockito.mock(PaygOutputExtractor.class);
properties = new PaygFilterProperties();
meterRegistry = new SimpleMeterRegistry();
tempFileManager = new TempFileManager(new TempFileRegistry(), new ApplicationProperties());
interceptor =
new PaygChargeInterceptor(
chargeService,
jobService,
userRepository,
tempFileManager,
outputExtractor,
properties,
meterRegistry);
SecurityContextHolder.clearContext();
}
@Test
void preHandle_filterDisabled_isShortCircuitNoop() throws Exception {
properties.setEnabled(false);
MockHttpServletRequest req = new MockHttpServletRequest();
MockHttpServletResponse res = new MockHttpServletResponse();
boolean cont = interceptor.preHandle(req, res, handlerMethodForFakeController());
assertThat(cont).isTrue();
verifyNoInteractions(chargeService);
}
@Test
void preHandle_handlerNotAnnotated_isShortCircuitNoop() throws Exception {
MockHttpServletRequest req = new MockHttpServletRequest();
MockHttpServletResponse res = new MockHttpServletResponse();
boolean cont = interceptor.preHandle(req, res, handlerMethodForPlain());
assertThat(cont).isTrue();
verifyNoInteractions(chargeService);
}
@Test
void preHandle_noAuth_isShortCircuitNoop() throws Exception {
MockMultipartHttpServletRequest req = newMultipart();
req.addFile(new MockMultipartFile("file", "x.pdf", "application/pdf", "hi".getBytes()));
boolean cont =
interceptor.preHandle(
req, new MockHttpServletResponse(), handlerMethodForFakeController());
assertThat(cont).isTrue();
verifyNoInteractions(chargeService);
}
@Test
void preHandle_noMultipartParts_isShortCircuitNoop() throws Exception {
// Authenticated but no file parts.
authenticateWithUser(makeUser(1L, null));
MockHttpServletRequest req = new MockHttpServletRequest();
boolean cont =
interceptor.preHandle(
req, new MockHttpServletResponse(), handlerMethodForFakeController());
assertThat(cont).isTrue();
verifyNoInteractions(chargeService);
}
@Test
void preHandle_openedDisposition_stashesJobIdAndDisposition() throws Exception {
authenticateWithUser(makeUser(7L, 42L));
UUID jobId = UUID.randomUUID();
when(chargeService.openProcess(any(), anyList()))
.thenReturn(new ChargeOutcome(jobId, 4, ChargeOutcome.Disposition.OPENED));
MockMultipartHttpServletRequest req = newMultipart();
req.addFile(new MockMultipartFile("file", "x.pdf", "application/pdf", "abc".getBytes()));
boolean cont =
interceptor.preHandle(
req, new MockHttpServletResponse(), handlerMethodForFakeController());
assertThat(cont).isTrue();
assertThat(req.getAttribute(PaygChargeInterceptor.ATTR_JOB_ID)).isEqualTo(jobId);
assertThat(req.getAttribute(PaygChargeInterceptor.ATTR_DISPOSITION))
.isEqualTo(ChargeOutcome.Disposition.OPENED);
assertThat(req.getAttribute(PaygChargeInterceptor.ATTR_INPUT_TEMP_FILES)).isNotNull();
assertThat(meterRegistry.counter("payg.filter.calls", "disposition", "OPENED").count())
.isEqualTo(1.0);
}
@Test
void preHandle_chargeServiceThrows_failsOpenAndIncrementsErrorCounter() throws Exception {
authenticateWithUser(makeUser(7L, 42L));
when(chargeService.openProcess(any(), anyList())).thenThrow(new RuntimeException("boom"));
MockMultipartHttpServletRequest req = newMultipart();
req.addFile(new MockMultipartFile("file", "x.pdf", "application/pdf", "abc".getBytes()));
boolean cont =
interceptor.preHandle(
req, new MockHttpServletResponse(), handlerMethodForFakeController());
assertThat(cont).isTrue(); // fail-open
assertThat(req.getAttribute(PaygChargeInterceptor.ATTR_FAILED)).isEqualTo(Boolean.TRUE);
assertThat(meterRegistry.counter("payg.filter.errors").count()).isEqualTo(1.0);
}
@Test
void afterCompletion_2xx_appendsStepAndRecordsOutputs() throws Exception {
authenticateWithUser(makeUser(7L, 42L));
UUID jobId = UUID.randomUUID();
when(chargeService.openProcess(any(), anyList()))
.thenReturn(new ChargeOutcome(jobId, 1, ChargeOutcome.Disposition.OPENED));
MockMultipartHttpServletRequest req = newMultipart();
req.addFile(new MockMultipartFile("file", "x.pdf", "application/pdf", "abc".getBytes()));
MockHttpServletResponse res = new MockHttpServletResponse();
res.setStatus(200);
res.setContentType("application/pdf");
// Install a wrapper as the filter would. Pre-populate it with some bytes so
// materialisedPath returns non-null.
PaygResponseBodyWrapper wrapper = new PaygResponseBodyWrapper(res, tempFileManager, 1024);
wrapper.getOutputStream().write("body".getBytes(StandardCharsets.UTF_8));
req.setAttribute(PaygResponseBodyWrapperFilter.REQUEST_ATTRIBUTE, wrapper);
interceptor.preHandle(req, res, handlerMethodForFakeController());
when(outputExtractor.extract(eq("application/pdf"), any()))
.thenReturn(
List.of(
new PaygOutputExtractor.ExtractedPdf(
wrapper.materialisedPath(), null)));
interceptor.afterCompletion(req, res, handlerMethodForFakeController(), null);
ArgumentCaptor<JobStepStatus> status = ArgumentCaptor.forClass(JobStepStatus.class);
verify(jobService).appendStep(eq(jobId), any(), status.capture(), any(), any(), any());
assertThat(status.getValue()).isEqualTo(JobStepStatus.OK);
verify(jobService).recordOutput(eq(jobId), any());
verify(chargeService, never()).markFirstStepFailed(any(), any());
verify(chargeService, never()).decrementStepCount(any());
}
@Test
void afterCompletion_5xx_opened_callsMarkFirstStepFailed() throws Exception {
authenticateWithUser(makeUser(7L, 42L));
UUID jobId = UUID.randomUUID();
when(chargeService.openProcess(any(), anyList()))
.thenReturn(new ChargeOutcome(jobId, 1, ChargeOutcome.Disposition.OPENED));
MockMultipartHttpServletRequest req = newMultipart();
req.addFile(new MockMultipartFile("file", "x.pdf", "application/pdf", "abc".getBytes()));
MockHttpServletResponse res = new MockHttpServletResponse();
res.setStatus(503);
interceptor.preHandle(req, res, handlerMethodForFakeController());
interceptor.afterCompletion(req, res, handlerMethodForFakeController(), null);
verify(chargeService).markFirstStepFailed(eq(jobId), eq("first-step-5xx:503"));
verify(chargeService, never()).decrementStepCount(any());
verify(jobService, never()).recordOutput(any(), any());
verify(jobService)
.appendStep(eq(jobId), any(), eq(JobStepStatus.FAILED), any(), any(), eq("503"));
assertThat(meterRegistry.counter("payg.filter.refunds").count()).isEqualTo(1.0);
}
@Test
void afterCompletion_5xx_joined_callsDecrementStepCount() throws Exception {
authenticateWithUser(makeUser(7L, 42L));
UUID jobId = UUID.randomUUID();
when(chargeService.openProcess(any(), anyList()))
.thenReturn(new ChargeOutcome(jobId, 0, ChargeOutcome.Disposition.JOINED));
MockMultipartHttpServletRequest req = newMultipart();
req.addFile(new MockMultipartFile("file", "x.pdf", "application/pdf", "abc".getBytes()));
MockHttpServletResponse res = new MockHttpServletResponse();
res.setStatus(500);
interceptor.preHandle(req, res, handlerMethodForFakeController());
interceptor.afterCompletion(req, res, handlerMethodForFakeController(), null);
verify(chargeService).decrementStepCount(jobId);
verify(chargeService, never()).markFirstStepFailed(any(), any());
}
@Test
void afterCompletion_4xx_appendsFailedStepNoRefundNoOutputs() throws Exception {
authenticateWithUser(makeUser(7L, 42L));
UUID jobId = UUID.randomUUID();
when(chargeService.openProcess(any(), anyList()))
.thenReturn(new ChargeOutcome(jobId, 1, ChargeOutcome.Disposition.OPENED));
MockMultipartHttpServletRequest req = newMultipart();
req.addFile(new MockMultipartFile("file", "x.pdf", "application/pdf", "abc".getBytes()));
MockHttpServletResponse res = new MockHttpServletResponse();
res.setStatus(422);
interceptor.preHandle(req, res, handlerMethodForFakeController());
interceptor.afterCompletion(req, res, handlerMethodForFakeController(), null);
verify(chargeService, never()).markFirstStepFailed(any(), any());
verify(chargeService, never()).decrementStepCount(any());
verify(jobService, never()).recordOutput(any(), any());
verify(jobService)
.appendStep(eq(jobId), any(), eq(JobStepStatus.FAILED), any(), any(), eq("422"));
}
@Test
void afterCompletion_preHandleFailedFlag_cleansUpWithoutCharging() throws Exception {
MockMultipartHttpServletRequest req = newMultipart();
req.setAttribute(PaygChargeInterceptor.ATTR_FAILED, Boolean.TRUE);
MockHttpServletResponse res = new MockHttpServletResponse();
interceptor.afterCompletion(req, res, handlerMethodForFakeController(), null);
verifyNoInteractions(chargeService);
verifyNoInteractions(jobService);
}
@Test
void afterCompletion_noJobId_isNoop() throws Exception {
MockMultipartHttpServletRequest req = newMultipart();
MockHttpServletResponse res = new MockHttpServletResponse();
interceptor.afterCompletion(req, res, handlerMethodForFakeController(), null);
verifyNoInteractions(chargeService);
verifyNoInteractions(jobService);
}
@Test
void afterCompletion_maxBytesExceeded_skipsOutputRecording() throws Exception {
properties.getResponse().setMaxBytes(2L);
authenticateWithUser(makeUser(7L, 42L));
UUID jobId = UUID.randomUUID();
when(chargeService.openProcess(any(), anyList()))
.thenReturn(new ChargeOutcome(jobId, 1, ChargeOutcome.Disposition.OPENED));
MockMultipartHttpServletRequest req = newMultipart();
req.addFile(new MockMultipartFile("file", "x.pdf", "application/pdf", "abc".getBytes()));
MockHttpServletResponse res = new MockHttpServletResponse();
res.setStatus(200);
res.setContentType("application/pdf");
PaygResponseBodyWrapper wrapper = new PaygResponseBodyWrapper(res, tempFileManager, 1024);
wrapper.getOutputStream().write("1234567890".getBytes(StandardCharsets.UTF_8));
req.setAttribute(PaygResponseBodyWrapperFilter.REQUEST_ATTRIBUTE, wrapper);
interceptor.preHandle(req, res, handlerMethodForFakeController());
interceptor.afterCompletion(req, res, handlerMethodForFakeController(), null);
verify(outputExtractor, never()).extract(any(), any());
verify(jobService, never()).recordOutput(any(), any());
}
@Test
void preHandle_pipelineHeader_setsJobSourcePipeline() throws Exception {
authenticateWithUser(makeUser(7L, 42L));
UUID jobId = UUID.randomUUID();
when(chargeService.openProcess(any(), anyList()))
.thenReturn(new ChargeOutcome(jobId, 1, ChargeOutcome.Disposition.OPENED));
org.mockito.ArgumentCaptor<stirling.software.saas.payg.charge.ChargeContext> ctxCaptor =
org.mockito.ArgumentCaptor.forClass(
stirling.software.saas.payg.charge.ChargeContext.class);
MockMultipartHttpServletRequest req = newMultipart();
req.addFile(new MockMultipartFile("file", "x.pdf", "application/pdf", "abc".getBytes()));
req.addHeader("X-Stirling-Automation", "true");
interceptor.preHandle(req, new MockHttpServletResponse(), handlerMethodForFakeController());
verify(chargeService).openProcess(ctxCaptor.capture(), anyList());
assertThat(ctxCaptor.getValue().source())
.isEqualTo(stirling.software.saas.payg.model.JobSource.PIPELINE);
}
// --- helpers --------------------------------------------------------------------------------
private MockMultipartHttpServletRequest newMultipart() {
MockMultipartHttpServletRequest r = new MockMultipartHttpServletRequest();
r.setRequestURI("/api/v1/security/test-tool");
return r;
}
private void authenticateWithUser(User user) {
UsernamePasswordAuthenticationToken token =
new UsernamePasswordAuthenticationToken(
"supabase-id-here", null, List.of(new SimpleGrantedAuthority("ROLE_USER")));
SecurityContextHolder.getContext().setAuthentication(token);
// resolveUser does UUID.fromString on the name, so use a real UUID string.
String supabaseId = UUID.randomUUID().toString();
UsernamePasswordAuthenticationToken realToken =
new UsernamePasswordAuthenticationToken(
supabaseId, null, List.of(new SimpleGrantedAuthority("ROLE_USER")));
SecurityContextHolder.getContext().setAuthentication(realToken);
when(userRepository.findBySupabaseId(UUID.fromString(supabaseId)))
.thenReturn(Optional.of(user));
}
private static User makeUser(Long id, Long teamId) {
User user = new User();
try {
// User entity doesn't expose Lombok setters for all fields. Set via reflection.
java.lang.reflect.Field idField = User.class.getDeclaredField("id");
idField.setAccessible(true);
idField.set(user, id);
} catch (ReflectiveOperationException e) {
throw new RuntimeException(e);
}
if (teamId != null) {
stirling.software.proprietary.model.Team team =
new stirling.software.proprietary.model.Team();
team.setId(teamId);
user.setTeam(team);
}
return user;
}
private static HandlerMethod handlerMethodForFakeController() {
try {
Method m = FakeController.class.getDeclaredMethod("handleAuto");
return new HandlerMethod(new FakeController(), m);
} catch (NoSuchMethodException e) {
throw new RuntimeException(e);
}
}
private static HandlerMethod handlerMethodForPlain() {
try {
Method m = FakeController.class.getDeclaredMethod("handlePlain");
return new HandlerMethod(new FakeController(), m);
} catch (NoSuchMethodException e) {
throw new RuntimeException(e);
}
}
static class FakeController {
@AutoJobPostMapping(value = "/x", resourceWeight = 1)
public void handleAuto() {}
public void handlePlain() {}
}
/** Placeholder so AutoCloseable resources flow in some helper methods. */
@SuppressWarnings("unused")
private static void closeQuietly(AutoCloseable c) {
try {
c.close();
} catch (Exception ignored) {
// ignored
}
}
@SuppressWarnings("unused")
private static IOException unused() {
return null;
}
}
@@ -1,120 +0,0 @@
package stirling.software.saas.payg.filter;
import static org.assertj.core.api.Assertions.assertThat;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import stirling.software.common.model.ApplicationProperties;
import stirling.software.common.util.TempFileManager;
import stirling.software.common.util.TempFileRegistry;
class PaygOutputExtractorTest {
private final TempFileManager tempFileManager =
new TempFileManager(new TempFileRegistry(), new ApplicationProperties());
private final PaygOutputExtractor extractor = new PaygOutputExtractor(tempFileManager);
@Test
void pdfContentType_returnsBodyPathVerbatim(@TempDir Path tmp) throws IOException {
Path body = tmp.resolve("body.pdf");
Files.write(body, pdfBytes("hello"));
List<PaygOutputExtractor.ExtractedPdf> out = extractor.extract("application/pdf", body);
assertThat(out).hasSize(1);
assertThat(out.get(0).path()).isEqualTo(body);
assertThat(out.get(0).ownedTempFile()).isNull();
}
@Test
void pdfContentType_withParameters_stillMatches(@TempDir Path tmp) throws IOException {
Path body = tmp.resolve("body.pdf");
Files.write(body, pdfBytes("x"));
List<PaygOutputExtractor.ExtractedPdf> out =
extractor.extract("application/pdf; charset=binary", body);
assertThat(out).hasSize(1);
}
@Test
void zipContentType_extractsOnlyPdfEntriesWithValidMagicBytes(@TempDir Path tmp)
throws IOException {
Path zip = tmp.resolve("out.zip");
try (ZipOutputStream zos = new ZipOutputStream(Files.newOutputStream(zip))) {
writeEntry(zos, "doc1.pdf", pdfBytes("one"));
writeEntry(zos, "doc2.pdf", pdfBytes("two"));
writeEntry(zos, "fake.pdf", "not a pdf at all".getBytes(StandardCharsets.UTF_8));
writeEntry(zos, "notes.txt", "ignored".getBytes(StandardCharsets.UTF_8));
}
List<PaygOutputExtractor.ExtractedPdf> out = extractor.extract("application/zip", zip);
try {
assertThat(out).hasSize(2);
for (PaygOutputExtractor.ExtractedPdf p : out) {
byte[] head = new byte[5];
Files.newInputStream(p.path()).read(head);
assertThat(head).startsWith("%PDF-".getBytes(StandardCharsets.UTF_8));
assertThat(p.ownedTempFile()).isNotNull();
}
} finally {
for (PaygOutputExtractor.ExtractedPdf p : out) {
p.close();
}
}
}
@Test
void nonPdfNonZipContentType_returnsEmpty(@TempDir Path tmp) throws IOException {
Path body = tmp.resolve("body.json");
Files.writeString(body, "{\"error\":\"bad request\"}");
assertThat(extractor.extract("application/json", body)).isEmpty();
assertThat(extractor.extract("text/plain", body)).isEmpty();
assertThat(extractor.extract(null, body)).isEmpty();
}
@Test
void nullBodyPath_returnsEmpty() {
assertThat(extractor.extract("application/pdf", null)).isEmpty();
}
@Test
void corruptZip_failsClosedAndReturnsEmpty(@TempDir Path tmp) throws IOException {
Path corrupt = tmp.resolve("garbage.zip");
Files.write(corrupt, "not a zip file at all".getBytes(StandardCharsets.UTF_8));
// Should NOT throw — fail-open: empty list, response still serves normally.
List<PaygOutputExtractor.ExtractedPdf> out = extractor.extract("application/zip", corrupt);
assertThat(out).isEmpty();
}
@Test
void zipContentType_emptyZip_returnsEmpty(@TempDir Path tmp) throws IOException {
Path zip = tmp.resolve("empty.zip");
try (ZipOutputStream zos = new ZipOutputStream(Files.newOutputStream(zip))) {
// no entries
}
assertThat(extractor.extract("application/zip", zip)).isEmpty();
}
private static void writeEntry(ZipOutputStream zos, String name, byte[] data)
throws IOException {
zos.putNextEntry(new ZipEntry(name));
zos.write(data);
zos.closeEntry();
}
private static byte[] pdfBytes(String payload) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
// Minimal "looks like a PDF" — just the magic-byte prefix + filler. The extractor only
// checks magic bytes, not full PDF validity.
out.write("%PDF-1.4\n".getBytes(StandardCharsets.UTF_8));
out.write(payload.getBytes(StandardCharsets.UTF_8));
return out.toByteArray();
}
}
@@ -1,210 +0,0 @@
package stirling.software.saas.payg.filter;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import org.junit.jupiter.api.Test;
import org.springframework.mock.web.MockHttpServletResponse;
import stirling.software.common.model.ApplicationProperties;
import stirling.software.common.util.TempFileManager;
import stirling.software.common.util.TempFileRegistry;
class PaygResponseBodyWrapperTest {
private final TempFileManager tempFileManager =
new TempFileManager(new TempFileRegistry(), new ApplicationProperties());
@Test
void inMemory_smallWrites_clientReceivesAndPathContainsSameBytes() throws Exception {
MockHttpServletResponse downstream = new MockHttpServletResponse();
try (PaygResponseBodyWrapper wrapper =
new PaygResponseBodyWrapper(downstream, tempFileManager, 1024)) {
wrapper.getOutputStream().write("hello world".getBytes(StandardCharsets.UTF_8));
wrapper.getOutputStream().flush();
assertThat(downstream.getContentAsString()).isEqualTo("hello world");
assertThat(wrapper.bytesWritten()).isEqualTo(11);
Path materialised = wrapper.materialisedPath();
assertThat(materialised).isNotNull();
assertThat(Files.readString(materialised, StandardCharsets.UTF_8))
.isEqualTo("hello world");
}
}
@Test
void spill_crossThresholdMidChunk_capturesEverything() throws Exception {
MockHttpServletResponse downstream = new MockHttpServletResponse();
try (PaygResponseBodyWrapper wrapper =
new PaygResponseBodyWrapper(downstream, tempFileManager, 8)) {
// First write: 5 bytes — fits in memory.
wrapper.getOutputStream().write("HELLO".getBytes(StandardCharsets.UTF_8));
// Second write: 6 bytes — crosses the 8-byte threshold mid-chunk; whole chunk
// ends up on disk per the design (we don't split the crossing chunk).
wrapper.getOutputStream().write(" WORLD".getBytes(StandardCharsets.UTF_8));
wrapper.getOutputStream().flush();
assertThat(downstream.getContentAsString()).isEqualTo("HELLO WORLD");
assertThat(wrapper.bytesWritten()).isEqualTo(11);
Path path = wrapper.materialisedPath();
assertThat(Files.readString(path, StandardCharsets.UTF_8)).isEqualTo("HELLO WORLD");
}
}
@Test
void spill_largeSingleWrite_capturedToDisk() throws Exception {
MockHttpServletResponse downstream = new MockHttpServletResponse();
byte[] payload = new byte[64 * 1024]; // 64 KiB
for (int i = 0; i < payload.length; i++) {
payload[i] = (byte) (i % 251);
}
try (PaygResponseBodyWrapper wrapper =
new PaygResponseBodyWrapper(downstream, tempFileManager, 1024)) {
wrapper.getOutputStream().write(payload);
wrapper.getOutputStream().flush();
assertThat(downstream.getContentAsByteArray()).isEqualTo(payload);
assertThat(wrapper.bytesWritten()).isEqualTo(payload.length);
byte[] disk = Files.readAllBytes(wrapper.materialisedPath());
assertThat(disk).isEqualTo(payload);
}
}
@Test
void writer_pathTeesThroughToBuffer() throws Exception {
MockHttpServletResponse downstream = new MockHttpServletResponse();
downstream.setCharacterEncoding("UTF-8");
try (PaygResponseBodyWrapper wrapper =
new PaygResponseBodyWrapper(downstream, tempFileManager, 1024)) {
PrintWriter writer = wrapper.getWriter();
writer.write("a-string-from-writer");
writer.flush();
assertThat(downstream.getContentAsString()).isEqualTo("a-string-from-writer");
Path path = wrapper.materialisedPath();
assertThat(Files.readString(path, StandardCharsets.UTF_8))
.isEqualTo("a-string-from-writer");
}
}
@Test
void mixingOutputStreamAndWriter_throwsPerServletSpec() throws Exception {
MockHttpServletResponse downstream = new MockHttpServletResponse();
try (PaygResponseBodyWrapper wrapper =
new PaygResponseBodyWrapper(downstream, tempFileManager, 1024)) {
wrapper.getOutputStream();
assertThatThrownBy(wrapper::getWriter).isInstanceOf(IllegalStateException.class);
}
MockHttpServletResponse downstream2 = new MockHttpServletResponse();
try (PaygResponseBodyWrapper wrapper2 =
new PaygResponseBodyWrapper(downstream2, tempFileManager, 1024)) {
wrapper2.getWriter();
assertThatThrownBy(wrapper2::getOutputStream).isInstanceOf(IllegalStateException.class);
}
}
@Test
void noBytesWritten_materialisedPathIsNull() throws Exception {
MockHttpServletResponse downstream = new MockHttpServletResponse();
try (PaygResponseBodyWrapper wrapper =
new PaygResponseBodyWrapper(downstream, tempFileManager, 1024)) {
// Don't touch the output stream.
assertThat(wrapper.materialisedPath()).isNull();
assertThat(wrapper.bytesWritten()).isZero();
}
}
@Test
void resetBuffer_inMemory_clearsAccumulatedBytes() throws Exception {
MockHttpServletResponse downstream = new MockHttpServletResponse();
try (PaygResponseBodyWrapper wrapper =
new PaygResponseBodyWrapper(downstream, tempFileManager, 1024)) {
wrapper.getOutputStream().write("draft".getBytes(StandardCharsets.UTF_8));
wrapper.resetBuffer();
assertThat(wrapper.bytesWritten()).isZero();
assertThat(wrapper.materialisedPath()).isNull();
wrapper.getOutputStream().write("final".getBytes(StandardCharsets.UTF_8));
wrapper.getOutputStream().flush();
assertThat(Files.readString(wrapper.materialisedPath(), StandardCharsets.UTF_8))
.isEqualTo("final");
}
}
@Test
void resetBuffer_afterSpill_dropsSpillFileAndStartsFresh() throws Exception {
MockHttpServletResponse downstream = new MockHttpServletResponse();
try (PaygResponseBodyWrapper wrapper =
new PaygResponseBodyWrapper(downstream, tempFileManager, 4)) {
wrapper.getOutputStream().write("draftover".getBytes(StandardCharsets.UTF_8)); // spill
assertThat(wrapper.bytesWritten()).isEqualTo(9);
wrapper.resetBuffer();
assertThat(wrapper.bytesWritten()).isZero();
assertThat(wrapper.materialisedPath()).isNull();
// Write again — should land in fresh memory, not the dropped spill.
wrapper.getOutputStream().write("ok".getBytes(StandardCharsets.UTF_8));
wrapper.getOutputStream().flush();
assertThat(Files.readString(wrapper.materialisedPath(), StandardCharsets.UTF_8))
.isEqualTo("ok");
}
}
@Test
void close_isIdempotent() throws IOException {
MockHttpServletResponse downstream = new MockHttpServletResponse();
PaygResponseBodyWrapper wrapper =
new PaygResponseBodyWrapper(downstream, tempFileManager, 8);
wrapper.getOutputStream().write("more-than-eight-bytes".getBytes(StandardCharsets.UTF_8));
wrapper.materialisedPath(); // forces flush
wrapper.close();
wrapper.close(); // second call must not throw
}
@Test
void materialisedPath_isStableAcrossCalls_whenInMemory() throws Exception {
MockHttpServletResponse downstream = new MockHttpServletResponse();
try (PaygResponseBodyWrapper wrapper =
new PaygResponseBodyWrapper(downstream, tempFileManager, 1024)) {
wrapper.getOutputStream().write("abc".getBytes(StandardCharsets.UTF_8));
Path first = wrapper.materialisedPath();
Path second = wrapper.materialisedPath();
assertThat(first).isEqualTo(second);
}
}
@Test
void singleByteWrites_areCorrectlyAccountedAcrossThreshold() throws Exception {
MockHttpServletResponse downstream = new MockHttpServletResponse();
try (PaygResponseBodyWrapper wrapper =
new PaygResponseBodyWrapper(downstream, tempFileManager, 3)) {
for (int b : "ABCDE".getBytes(StandardCharsets.UTF_8)) {
wrapper.getOutputStream().write(b);
}
wrapper.getOutputStream().flush();
assertThat(downstream.getContentAsString()).isEqualTo("ABCDE");
assertThat(wrapper.bytesWritten()).isEqualTo(5);
assertThat(Files.readString(wrapper.materialisedPath(), StandardCharsets.UTF_8))
.isEqualTo("ABCDE");
}
}
@Test
void negativeThreshold_rejected() {
assertThatThrownBy(
() ->
new PaygResponseBodyWrapper(
new MockHttpServletResponse(), tempFileManager, -1))
.isInstanceOf(IllegalArgumentException.class);
}
}
@@ -1,394 +0,0 @@
package stirling.software.saas.payg.job;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.mockito.ArgumentCaptor;
import org.mockito.Mockito;
import stirling.software.saas.payg.lineage.HashLineageDetector;
import stirling.software.saas.payg.lineage.LineageMatch;
import stirling.software.saas.payg.model.ArtifactKind;
import stirling.software.saas.payg.model.JobSource;
import stirling.software.saas.payg.model.JobStatus;
import stirling.software.saas.payg.model.ProcessType;
import stirling.software.saas.payg.repository.ProcessingJobRepository;
import stirling.software.saas.payg.repository.ProcessingJobStepRepository;
/**
* Drives {@link JobService} through the multi-input "any-match-joins" lineage policy. Uses a fake
* {@link HashLineageDetector} that pretends each file's signatures are pre-registered with
* particular jobs; persistence goes through mocked repositories.
*/
class JobServiceTest {
private static final Duration WINDOW = Duration.ofMinutes(5);
private FakeDetector detector;
private ProcessingJobRepository jobRepo;
private ProcessingJobStepRepository stepRepo;
private JobService service;
@BeforeEach
void setUp() {
detector = new FakeDetector();
jobRepo = Mockito.mock(ProcessingJobRepository.class);
stepRepo = Mockito.mock(ProcessingJobStepRepository.class);
// save() returns the same instance so the service can introspect post-write state.
when(jobRepo.save(any(ProcessingJob.class))).thenAnswer(inv -> inv.getArgument(0));
when(stepRepo.save(any(ProcessingJobStep.class))).thenAnswer(inv -> inv.getArgument(0));
service = new JobService(detector, jobRepo, stepRepo, WINDOW);
}
@Test
void constructor_rejectsNonPositiveWindow() {
assertThatThrownBy(() -> new JobService(detector, jobRepo, stepRepo, Duration.ZERO))
.isInstanceOf(IllegalArgumentException.class);
assertThatThrownBy(
() ->
new JobService(
detector,
jobRepo,
stepRepo,
Duration.ofMinutes(5).negated()))
.isInstanceOf(IllegalArgumentException.class);
}
@Test
void joinOrOpen_noMatch_opensNewJob(@TempDir Path tmp) throws IOException {
Path input = givenFile(tmp, "in.bin");
// No detector matches.
JoinOrOpenResult result = service.joinOrOpen(ctx(42L, 100L, 10), List.of(input));
assertThat(result.disposition()).isEqualTo(JoinOrOpenResult.Disposition.OPENED);
assertThat(result.job().getOwnerUserId()).isEqualTo(42L);
assertThat(result.job().getOwnerTeamId()).isEqualTo(100L);
assertThat(result.job().getSource()).isEqualTo(JobSource.WEB);
assertThat(result.job().getStatus()).isEqualTo(JobStatus.OPEN);
assertThat(result.job().getStepCount()).isEqualTo(1);
assertThat(result.job().getId()).isNotNull();
// Input was recorded under the new job.
assertThat(detector.recorded(result.job().getId(), input, ArtifactKind.INPUT)).isTrue();
}
@Test
void joinOrOpen_singleMatch_joinsExistingJob(@TempDir Path tmp) throws IOException {
UUID existingId = UUID.randomUUID();
ProcessingJob existing = openJob(existingId, 42L, 3, LocalDateTime.now());
when(jobRepo.findById(existingId)).thenReturn(Optional.of(existing));
Path input = givenFile(tmp, "in.bin");
detector.willMatch(
input, new LineageMatch(existingId, ArtifactKind.INPUT, existing.getLastStepAt()));
JoinOrOpenResult result = service.joinOrOpen(ctx(42L, 100L, 10), List.of(input));
assertThat(result.disposition()).isEqualTo(JoinOrOpenResult.Disposition.JOINED);
assertThat(result.job().getId()).isEqualTo(existingId);
assertThat(result.job().getStepCount()).isEqualTo(4); // 3 -> 4
// Input is recorded under the joined job too — so future calls on the same input still
// lineage-match to it.
assertThat(detector.recorded(existingId, input, ArtifactKind.INPUT)).isTrue();
}
@Test
void joinOrOpen_multiInputAnyMatchJoins(@TempDir Path tmp) throws IOException {
// Inputs A and B; A matches existing job; B is unrelated. Should join A's job.
UUID jobAId = UUID.randomUUID();
ProcessingJob jobA = openJob(jobAId, 42L, 2, LocalDateTime.now());
when(jobRepo.findById(jobAId)).thenReturn(Optional.of(jobA));
Path inA = givenFile(tmp, "a.bin");
Path inB = givenFile(tmp, "b.bin");
detector.willMatch(
inA, new LineageMatch(jobAId, ArtifactKind.OUTPUT, jobA.getLastStepAt()));
// inB has no detector match.
JoinOrOpenResult result = service.joinOrOpen(ctx(42L, 100L, 10), List.of(inA, inB));
assertThat(result.disposition()).isEqualTo(JoinOrOpenResult.Disposition.JOINED);
assertThat(result.job().getId()).isEqualTo(jobAId);
// BOTH inputs recorded under the joined job — inB is now part of jobA's lineage tree.
assertThat(detector.recorded(jobAId, inA, ArtifactKind.INPUT)).isTrue();
assertThat(detector.recorded(jobAId, inB, ArtifactKind.INPUT)).isTrue();
}
@Test
void joinOrOpen_multiMatchPicksNewestByLastStepAt(@TempDir Path tmp) throws IOException {
UUID olderId = UUID.randomUUID();
UUID newerId = UUID.randomUUID();
LocalDateTime older = LocalDateTime.now().minus(Duration.ofMinutes(2));
LocalDateTime newer = LocalDateTime.now();
ProcessingJob olderJob = openJob(olderId, 42L, 1, older);
ProcessingJob newerJob = openJob(newerId, 42L, 1, newer);
when(jobRepo.findById(newerId)).thenReturn(Optional.of(newerJob));
Path inA = givenFile(tmp, "a.bin");
Path inB = givenFile(tmp, "b.bin");
detector.willMatch(inA, new LineageMatch(olderId, ArtifactKind.OUTPUT, older));
detector.willMatch(inB, new LineageMatch(newerId, ArtifactKind.OUTPUT, newer));
JoinOrOpenResult result = service.joinOrOpen(ctx(42L, 100L, 10), List.of(inA, inB));
assertThat(result.disposition()).isEqualTo(JoinOrOpenResult.Disposition.JOINED);
assertThat(result.job().getId()).isEqualTo(newerId);
// Older job was NOT looked up — newest wins purely by lastStepAt comparison from the
// LineageMatch payload, before any DB lookup.
verify(jobRepo, never()).findById(olderId);
}
@Test
void joinOrOpen_stepLimitHit_spawnsNewJob(@TempDir Path tmp) throws IOException {
UUID existingId = UUID.randomUUID();
// stepCount equal to limit (10) → can't append, must spawn new.
ProcessingJob existing = openJob(existingId, 42L, 10, LocalDateTime.now());
when(jobRepo.findById(existingId)).thenReturn(Optional.of(existing));
Path input = givenFile(tmp, "in.bin");
detector.willMatch(
input, new LineageMatch(existingId, ArtifactKind.OUTPUT, existing.getLastStepAt()));
JoinOrOpenResult result = service.joinOrOpen(ctx(42L, 100L, 10), List.of(input));
assertThat(result.disposition()).isEqualTo(JoinOrOpenResult.Disposition.OPENED);
assertThat(result.job().getId()).isNotEqualTo(existingId);
assertThat(result.job().getStepCount()).isEqualTo(1);
// The original job's stepCount must NOT have been incremented (we abandoned it).
assertThat(existing.getStepCount()).isEqualTo(10);
// Input is recorded under the NEW job so subsequent calls lineage-match to it
// (mostRecentMatchWins shifts the chain forward).
assertThat(detector.recorded(result.job().getId(), input, ArtifactKind.INPUT)).isTrue();
}
@Test
void joinOrOpen_emptyInputs_throws() {
assertThatThrownBy(() -> service.joinOrOpen(ctx(42L, 100L, 10), List.of()))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("inputs must not be empty");
}
@Test
void joinOrOpen_matchPointsAtMissingJob_throwsStateException(@TempDir Path tmp)
throws IOException {
UUID staleId = UUID.randomUUID();
when(jobRepo.findById(staleId)).thenReturn(Optional.empty());
Path input = givenFile(tmp, "in.bin");
detector.willMatch(
input, new LineageMatch(staleId, ArtifactKind.OUTPUT, LocalDateTime.now()));
assertThatThrownBy(() -> service.joinOrOpen(ctx(42L, 100L, 10), List.of(input)))
.isInstanceOf(IllegalStateException.class)
.hasMessageContaining("stale signature");
}
@Test
void recordOutput_delegatesToDetector(@TempDir Path tmp) throws IOException {
UUID jobId = UUID.randomUUID();
Path output = givenFile(tmp, "out.bin");
service.recordOutput(jobId, output);
assertThat(detector.recorded(jobId, output, ArtifactKind.OUTPUT)).isTrue();
}
@Test
void close_idempotent() {
UUID jobId = UUID.randomUUID();
ProcessingJob open = openJob(jobId, 42L, 5, LocalDateTime.now());
when(jobRepo.findById(jobId)).thenReturn(Optional.of(open));
ProcessingJob first = service.close(jobId);
assertThat(first.getStatus()).isEqualTo(JobStatus.CLOSED);
assertThat(first.getClosedAt()).isNotNull();
// Re-call: status already CLOSED, should return the same row without saving again.
ProcessingJob second = service.close(jobId);
assertThat(second.getStatus()).isEqualTo(JobStatus.CLOSED);
// save was called exactly once across both close() calls.
verify(jobRepo, times(1)).save(any(ProcessingJob.class));
}
@Test
void close_unknownJob_throws() {
UUID unknown = UUID.randomUUID();
when(jobRepo.findById(unknown)).thenReturn(Optional.empty());
assertThatThrownBy(() -> service.close(unknown))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("No ProcessingJob");
}
@Test
void closeStale_closesAllStaleJobs() {
ProcessingJob a =
openJob(
UUID.randomUUID(),
42L,
1,
LocalDateTime.now().minus(Duration.ofMinutes(10)));
ProcessingJob b =
openJob(
UUID.randomUUID(),
42L,
1,
LocalDateTime.now().minus(Duration.ofMinutes(20)));
when(jobRepo.findStale(eq(JobStatus.OPEN), any(LocalDateTime.class)))
.thenReturn(List.of(a, b));
int closed = service.closeStale();
assertThat(closed).isEqualTo(2);
assertThat(a.getStatus()).isEqualTo(JobStatus.CLOSED);
assertThat(b.getStatus()).isEqualTo(JobStatus.CLOSED);
verify(jobRepo).saveAll(List.of(a, b));
}
@Test
void closeStale_emptyResult_noSave() {
when(jobRepo.findStale(eq(JobStatus.OPEN), any(LocalDateTime.class))).thenReturn(List.of());
assertThat(service.closeStale()).isZero();
verify(jobRepo, never()).saveAll(any());
}
@Test
void appendStep_persistsStepRow() {
UUID jobId = UUID.randomUUID();
ArgumentCaptor<ProcessingJobStep> captor = ArgumentCaptor.forClass(ProcessingJobStep.class);
service.appendStep(
jobId,
"/api/v1/general/split",
stirling.software.saas.payg.model.JobStepStatus.OK,
42,
12_345L,
null);
verify(stepRepo, atLeastOnce()).save(captor.capture());
ProcessingJobStep saved = captor.getValue();
assertThat(saved.getJobId()).isEqualTo(jobId);
assertThat(saved.getToolId()).isEqualTo("/api/v1/general/split");
assertThat(saved.getInputPages()).isEqualTo(42);
assertThat(saved.getInputBytes()).isEqualTo(12_345L);
}
// --- helpers --------------------------------------------------------------------------------
private static JobContext ctx(long userId, long teamId, int stepLimit) {
return new JobContext(
userId, teamId, JobSource.WEB, ProcessType.SINGLE_TOOL, 1L, stepLimit);
}
private static ProcessingJob openJob(
UUID id, long userId, int stepCount, LocalDateTime lastStepAt) {
ProcessingJob j = new ProcessingJob();
j.setId(id);
j.setOwnerUserId(userId);
j.setStatus(JobStatus.OPEN);
j.setStepCount(stepCount);
j.setStartedAt(lastStepAt.minus(Duration.ofMinutes(1)));
j.setLastStepAt(lastStepAt);
j.setProcessType(ProcessType.SINGLE_TOOL);
j.setSource(JobSource.WEB);
j.setPolicyId(1L);
return j;
}
private static Path givenFile(Path tmp, String name) throws IOException {
Path p = tmp.resolve(name);
Files.writeString(p, "fixture-" + name);
return p;
}
/**
* Test double: programmable detector + records observations. Synthesises one signature per
* path; every path seen by extractSignatures is reverse-mapped so the post-dedupe flow
* (extractSignatures → detect/record by signature) keeps the path-based test assertions working
* unchanged.
*/
private static class FakeDetector implements HashLineageDetector {
private final Map<Path, LineageMatch> matches = new HashMap<>();
private final Set<String> observations = new java.util.HashSet<>();
private final Map<stirling.software.saas.payg.lineage.LineageSignature, Path>
pathBySignature = new HashMap<>();
void willMatch(Path input, LineageMatch match) {
matches.put(input, match);
}
boolean recorded(UUID jobId, Path file, ArtifactKind kind) {
return observations.contains(jobId + "|" + file + "|" + kind);
}
private stirling.software.saas.payg.lineage.LineageSignature sigFor(Path file) {
stirling.software.saas.payg.lineage.LineageSignature sig =
new stirling.software.saas.payg.lineage.LineageSignature(
"test", Integer.toHexString(file.toString().hashCode()));
pathBySignature.put(sig, file);
return sig;
}
@Override
public Optional<LineageMatch> detect(Long userId, Path inputFile) {
return Optional.ofNullable(matches.get(inputFile));
}
@Override
public Optional<LineageMatch> detect(
Long userId, Set<stirling.software.saas.payg.lineage.LineageSignature> signatures) {
for (stirling.software.saas.payg.lineage.LineageSignature sig : signatures) {
Path p = pathBySignature.get(sig);
if (p != null && matches.containsKey(p)) {
return Optional.of(matches.get(p));
}
}
return Optional.empty();
}
@Override
public void record(UUID jobId, Path file, ArtifactKind kind) {
observations.add(jobId + "|" + file + "|" + kind);
}
@Override
public void record(
UUID jobId,
Set<stirling.software.saas.payg.lineage.LineageSignature> signatures,
ArtifactKind kind) {
for (stirling.software.saas.payg.lineage.LineageSignature sig : signatures) {
Path p = pathBySignature.get(sig);
if (p != null) {
observations.add(jobId + "|" + p + "|" + kind);
}
}
}
@Override
public Set<stirling.software.saas.payg.lineage.LineageSignature> extractSignatures(
Path file) {
return Set.of(sigFor(file));
}
}
}
@@ -1,35 +0,0 @@
package stirling.software.saas.payg.job;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
/**
* Smoke test for the scheduler wiring. The interesting close logic is exercised in {@link
* JobServiceTest#closeStale_closesAllStaleJobs}; here we just confirm the scheduler bean delegates
* to {@code JobService.closeStale} and tolerates an empty result without erroring.
*/
class StaleJobCloserTest {
@Test
void closeStale_invokesJobService() {
JobService jobService = Mockito.mock(JobService.class);
when(jobService.closeStale()).thenReturn(3);
new StaleJobCloser(jobService).closeStale();
verify(jobService).closeStale();
}
@Test
void closeStale_zeroClosedDoesNotThrow() {
JobService jobService = Mockito.mock(JobService.class);
when(jobService.closeStale()).thenReturn(0);
new StaleJobCloser(jobService).closeStale();
verify(jobService).closeStale();
}
}
@@ -1,52 +0,0 @@
package stirling.software.saas.payg.lineage;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.time.Duration;
import java.time.Instant;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Mockito;
class LineagePruneSchedulerTest {
@Test
void prune_passesNowMinusRetentionToStore() {
JobLineageStore store = Mockito.mock(JobLineageStore.class);
when(store.pruneOlderThan(any(Instant.class))).thenReturn(7);
Duration retention = Duration.ofHours(1);
Instant before = Instant.now();
new LineagePruneScheduler(store, retention).prune();
Instant after = Instant.now();
ArgumentCaptor<Instant> captor = ArgumentCaptor.forClass(Instant.class);
verify(store).pruneOlderThan(captor.capture());
Instant cutoff = captor.getValue();
// cutoff should sit inside [before-retention, after-retention] — bounds the wall-clock
// drift the test itself introduces between the captor and our reference reads.
assertThat(cutoff).isBetween(before.minus(retention), after.minus(retention));
}
@Test
void constructor_rejectsNonPositiveRetention() {
JobLineageStore store = Mockito.mock(JobLineageStore.class);
assertThatThrownBy(() -> new LineagePruneScheduler(store, Duration.ZERO))
.isInstanceOf(IllegalArgumentException.class);
assertThatThrownBy(() -> new LineagePruneScheduler(store, Duration.ofMinutes(5).negated()))
.isInstanceOf(IllegalArgumentException.class);
}
@Test
void prune_zeroDeletedDoesNotThrow() {
JobLineageStore store = Mockito.mock(JobLineageStore.class);
when(store.pruneOlderThan(any(Instant.class))).thenReturn(0);
new LineagePruneScheduler(store, Duration.ofHours(1)).prune();
verify(store).pruneOlderThan(any(Instant.class));
}
}
@@ -98,33 +98,6 @@ class PricingPolicyServiceTest {
.hasMessageContaining("No default pricing_policy row");
}
@Test
void nullTeamId_returnsDefaultPolicyDirectly_noCacheLookup() {
PricingPolicy result = service.getEffectivePolicy(null);
assertThat(result).isEqualTo(defaultPolicy);
verify(extensionsRepo, never()).findById(any());
// Team-less users go straight to the default — no cache pollution either.
assertThat(service.cacheSize()).isZero();
}
@Test
void nullTeamIdUncached_returnsDefaultPolicyDirectly() {
PricingPolicy result = service.getEffectivePolicyUncached(null);
assertThat(result).isEqualTo(defaultPolicy);
verify(extensionsRepo, never()).findById(any());
}
@Test
void nullTeamId_noDefaultExists_throws() {
when(policyRepo.findFirstByIsDefaultTrue()).thenReturn(Optional.empty());
assertThatThrownBy(() -> service.getEffectivePolicy(null))
.isInstanceOf(IllegalStateException.class)
.hasMessageContaining("No default pricing_policy row");
}
@Test
void secondCallHitsCache_noRepoLookup() {
when(extensionsRepo.findById(42L)).thenReturn(Optional.empty());
+1 -1
View File
@@ -86,7 +86,7 @@ class OrchestratorAgent:
system_prompt=(
"You are the top-level orchestrator. "
"Choose exactly one output function that best handles the request. "
"Use delegate_pdf_edit for any requested modification of one or more PDFs. "
"Use delegate_pdf_edit for requested modifications of single or multiple PDFs. "
"Use delegate_pdf_question for questions about the contents of the attached PDFs. "
"Use delegate_user_spec for requests to create or define an agent spec. "
"Use delegate_pdf_review when the user wants the PDF returned with review"
+27 -92
View File
@@ -39,39 +39,11 @@ class PdfEditPlanSelection(ApiModel):
summary: str
class PdfEditNeedContentSelection(ApiModel):
"""LLM-facing variant of need_content: the model signals it needs document content and gives
a reason. File objects are resolved by Python from request.files by matching names, so the
LLM can't fabricate file ids — it only selects by the display names it sees in the prompt.
"""
outcome: Literal["need_content"] = "need_content"
reason: str
file_names: list[str] | None = Field(
default=None,
description=(
"Names of files whose content is needed. "
"Use the exact names shown in the prompt. "
"Omit or leave empty to request content from all files."
),
)
max_pages: int | None = None
max_characters: int | None = None
type PdfEditPlanOutput = (
PdfEditPlanSelection | EditClarificationRequest | EditCannotDoResponse | PdfEditNeedContentSelection
)
type PdfEditPlanOutput = PdfEditPlanSelection | EditClarificationRequest | EditCannotDoResponse | NeedContentResponse
class PdfEditSelectionAgent:
def __init__(
self,
runtime: AppRuntime,
base_system_prompt: str,
*,
allow_need_content: bool,
) -> None:
def __init__(self, runtime: AppRuntime, base_system_prompt: str, *, allow_need_content: bool) -> None:
self.runtime = runtime
output_types: list[type[PdfEditPlanOutput]] = [
PdfEditPlanSelection,
@@ -80,12 +52,11 @@ class PdfEditSelectionAgent:
]
system_prompt = base_system_prompt
if allow_need_content:
output_types.append(PdfEditNeedContentSelection)
output_types.append(NeedContentResponse)
system_prompt += (
" Return need_content when planning a correct answer requires inspecting the actual PDF "
"page text (e.g. 'split after every page that says NEW PAGE', "
"'rotate pages that mention draft'). "
"Set file_names to only the files that need to be read; omit it to read all files."
"'rotate pages that mention draft')."
)
self.agent = Agent(
model=runtime.smart_model,
@@ -130,18 +101,14 @@ class PdfEditParameterSelector:
parameter_result = await self.agent.run(
prompt,
output_type=NativeOutput(parameter_model),
instructions=self._get_operation_instructions(operation_id),
instructions=(
f"Generate only the parameters for the PDF operation `{operation_id.name}`. "
"Do not include fields from any other operation."
),
)
logger.debug("[pdf-edit params %s] output: %s", operation_id.name, Pretty(parameter_result.output))
return parameter_result.output
@staticmethod
def _get_operation_instructions(operation_id: ToolEndpoint) -> str:
return (
f"Generate only the parameters for the PDF operation `{operation_id.name}`. "
"Do not include fields from any other operation."
)
def _build_parameter_prompt(
self,
request: PdfEditRequest,
@@ -206,7 +173,8 @@ class PdfEditAgent:
request.enabled_endpoints,
request.user_message,
)
supported_operations, unavailable_operations = self._classify_operations(request)
supported_operations = self._get_supported_operations(request)
unavailable_operations = self._get_unavailable_operations(supported_operations)
if not supported_operations:
return EditCannotDoResponse(reason="No PDF edit operations are available on this server.")
selection = await self._select_plan(
@@ -215,9 +183,9 @@ class PdfEditAgent:
if isinstance(selection, EditClarificationRequest | EditCannotDoResponse):
logger.info("[pdf-edit] selection -> %s: %s", selection.outcome, Pretty(selection))
return selection
if isinstance(selection, PdfEditNeedContentSelection):
if isinstance(selection, NeedContentResponse):
logger.info("[pdf-edit] selection -> need_content: %s", selection.reason)
return self._build_need_content_response(selection, request)
return self._fill_need_content_defaults(selection, request)
enabled = set(supported_operations)
unsupported = [op for op in selection.operations if op not in enabled]
if unsupported:
@@ -260,9 +228,7 @@ class PdfEditAgent:
) -> PdfEditPlanOutput:
can_request_content = allow_need_content and not has_page_text(request.page_text)
agent = self._build_selection_agent(
supported_operations,
unavailable_operations,
allow_need_content=can_request_content,
supported_operations, unavailable_operations, allow_need_content=can_request_content
)
return await agent.select(self._build_selection_prompt(request, supported_operations, unavailable_operations))
@@ -297,11 +263,9 @@ class PdfEditAgent:
"merging, or extracting pages then re-inserting them). "
"Only return cannot_do when no sequence of the supported operations could achieve the request. "
"Do not produce operation parameters in this stage. "
"Return need_clarification when the request is genuinely ambiguous. "
"Return plan when a reasonable multi-step plan can be created. "
"Never return partial plans. "
"Return need_clarification only when the request is genuinely ambiguous in a way "
"that no reasonable interpretation could produce a correct plan — do not ask to "
"confirm details that are already clear from the user's message."
"Never return partial plans."
),
allow_need_content=allow_need_content,
)
@@ -327,31 +291,13 @@ class PdfEditAgent:
f"Extracted page text:\n{format_page_text(request.page_text)}"
)
# Endpoints that exist on the server and are callable via the direct API or the manual UI,
# but are never offered to the AI agent as a routing option.
#
# Why: REDACT_EXECUTE is the preferred AI-driven redaction route. AUTO_REDACT and REDACT are
# legacy endpoints that remain fully functional for human callers (the manual redact UI, direct
# API consumers, pipelines) but would produce a worse experience if the AI routed to them —
# they accept a simpler, less expressive schema and pre-date the unified operation model.
# Hiding them here channels all AI redaction traffic through REDACT_EXECUTE without disabling
# the legacy endpoints for anyone else.
#
# How to reuse: add an endpoint here whenever a legacy endpoint has a preferred replacement
# that the AI should use exclusively. The endpoint remains live on the server; only the AI
# planner is prevented from selecting it.
_AGENT_HIDDEN_ENDPOINTS: frozenset[ToolEndpoint] = frozenset({ToolEndpoint.AUTO_REDACT, ToolEndpoint.REDACT})
def _get_supported_operations(self, request: PdfEditRequest) -> Iterable[ToolEndpoint]:
return request.enabled_endpoints
def _classify_operations(self, request: PdfEditRequest) -> tuple[list[ToolEndpoint], list[ToolEndpoint]]:
"""Split the universe of operations into (supported, unavailable) from the agent's
point of view. Endpoints in `_AGENT_HIDDEN_ENDPOINTS` are filtered out regardless
of enabled state — they exist on the server but only callers outside the AI
pipeline (the manual redact UI, direct API consumers) can invoke them.
"""
enabled_set = set(request.enabled_endpoints)
supported = [op for op in request.enabled_endpoints if op not in self._AGENT_HIDDEN_ENDPOINTS]
unavailable = [op for op in OPERATIONS if op not in enabled_set and op not in self._AGENT_HIDDEN_ENDPOINTS]
return supported, unavailable
@staticmethod
def _get_unavailable_operations(supported_operations: Iterable[ToolEndpoint]) -> Iterable[ToolEndpoint]:
supported_set = set(supported_operations)
return [op for op in OPERATIONS if op not in supported_set]
@staticmethod
def _get_operations_prompt(operations: Iterable[ToolEndpoint]) -> str:
@@ -380,29 +326,18 @@ class PdfEditAgent:
lines.append(f" {name}")
return "\n".join(lines)
def _build_need_content_response(
def _fill_need_content_defaults(
self,
selection: PdfEditNeedContentSelection,
selection: NeedContentResponse,
request: PdfEditRequest,
) -> NeedContentResponse:
# File objects are resolved here by matching names against request.files so the LLM
# can't fabricate file ids — it selects by display name, Python provides the AiFile.
if selection.file_names:
requested = set(selection.file_names)
files = [f for f in request.files if f.name in requested]
if not files:
# Names didn't match anything; fall back to all files rather than sending nothing.
logger.warning(
"[pdf-edit] need_content file_names %s matched no request files — using all",
selection.file_names,
)
files = request.files
else:
files = request.files
files = selection.files or [
NeedContentFileRequest(file=file, content_types=[PdfContentType.PAGE_TEXT]) for file in request.files
]
return NeedContentResponse(
resume_with=SupportedCapability.PDF_EDIT,
reason=selection.reason,
files=[NeedContentFileRequest(file=file, content_types=[PdfContentType.PAGE_TEXT]) for file in files],
files=files,
max_pages=selection.max_pages or self.runtime.settings.max_pages,
max_characters=selection.max_characters or self.runtime.settings.max_characters,
)
+1 -1
View File
@@ -116,6 +116,7 @@ from .progress import (
)
__all__ = [
"AiFile",
"AgentDraft",
"AgentDraftRequest",
"AgentDraftResponse",
@@ -126,7 +127,6 @@ __all__ = [
"AgentRevisionWorkflowResponse",
"AgentSpec",
"AgentSpecStep",
"AiFile",
"AiToolAgentStep",
"ArtifactKind",
"CannotContinueExecutionAction",
-81
View File
@@ -542,18 +542,6 @@ class HtmlToPdfParams(ApiModel):
zoom: float = Field(1, description="Zoom level for displaying the website. Default is '1'.")
class ImageBox(ApiModel):
"""
Rectangular areas to black out, each defined by a page number and bounding box coordinates.
"""
page_index: int = Field(..., description="0-indexed page number (first page = 0).")
x1: float = Field(..., description="Left x coordinate of the redaction rectangle in PDF user-space points.")
x2: float = Field(..., description="Right x coordinate of the redaction rectangle in PDF user-space points.")
y1: float = Field(..., description="Top y coordinate of the redaction rectangle in PDF user-space points.")
y2: float = Field(..., description="Bottom y coordinate of the redaction rectangle in PDF user-space points.")
class ColorType(StrEnum):
"""
The color type of the output image(s)
@@ -996,27 +984,6 @@ class RearrangePagesParams(ApiModel):
)
class Strategy(StrEnum):
"""
Execution strategy hint for the redaction pipeline
"""
auto = "AUTO"
overlay_only = "OVERLAY_ONLY"
image_finalize = "IMAGE_FINALIZE"
class Style(ApiModel):
"""
Redaction style options
"""
color: str = Field("#000000", description="Hex redaction box color")
convert_to_image: bool = Field(False, description="Rasterize output to prevent text extraction")
padding: float = Field(0, description="Extra padding around each box in points")
strategy: Strategy = Field(Strategy.auto, description="Execution strategy hint for the redaction pipeline")
class RedactionArea(ApiModel):
"""
A list of areas that should be redacted
@@ -1312,23 +1279,6 @@ class SvgToPdfParams(ApiModel):
)
class TextRange(ApiModel):
"""
Text ranges to redact by specifying a start and end anchor phrase. All content between the two phrases (inclusive) is redacted. Anchors work best when short and unique. They must appear verbatim in the document.
"""
end_string: str = Field(
...,
description="A short, distinctive phrase (5–15 words) that marks where redaction ends (inclusive). Must appear verbatim in the document. Shorter phrases match more reliably.",
min_length=1,
)
start_string: str = Field(
...,
description="A short, distinctive phrase (5–15 words) that marks where redaction begins (inclusive). Must appear verbatim in the document — e.g. a section heading or a unique sentence fragment.",
min_length=1,
)
class TimestampPdfParams(ApiModel):
tsa_url: str = Field(
"http://timestamp.digicert.com",
@@ -1396,32 +1346,6 @@ class VectorToPdfParams(ApiModel):
prepress: Prepress = Field(Prepress.boolean_false, description="Apply Ghostscript prepress settings")
class RedactExecuteParams(ApiModel):
image_boxes: list[ImageBox] | None = Field(
None, description="Rectangular areas to black out, each defined by a page number and bounding box coordinates."
)
ranges: list[TextRange] | None = Field(
None,
description="Text ranges to redact by specifying a start and end anchor phrase. All content between the two phrases (inclusive) is redacted. Anchors work best when short and unique. They must appear verbatim in the document.",
)
redact_image_pages: list[int] | None = Field(
None,
description="1-indexed page numbers to redact all detected images from. Pass an empty list to redact images from every page. Omit or pass null to skip image redaction entirely.",
)
regex_patterns: list[str] | None = Field(
None,
description="Regex patterns to match and redact. Each match anywhere in the document is blacked out. Uses Java/PCRE regex syntax. Well-suited for strings that follow known patterns, like phone numbers, email addresses, national ID numbers, or dates (which can appear with different separators, optional country codes, etc.). For fixed known strings such as names, use textValues instead.",
)
style: Style | None = Field(None, description="Redaction style options")
text_values: list[str] | None = Field(
None,
description="Exact strings to find and black out. One entry per phrase to redact. Best for known names, identifiers, and specific text found in the document.",
)
wipe_pages: list[int] | None = Field(
None, description="1-indexed page numbers to wipe entirely (all content removed from those pages)."
)
class RedactParams(ApiModel):
convert_pdf_to_image: bool = Field(False, description="Convert the redacted PDF to an image")
page_numbers: str = Field(
@@ -1496,7 +1420,6 @@ class Model(
| SessionsParams
| ValidateCertificateParams
| RedactParams
| RedactExecuteParams
| RemovePasswordParams
| SanitizePdfParams
| TimestampPdfParams
@@ -1565,7 +1488,6 @@ class Model(
| SessionsParams
| ValidateCertificateParams
| RedactParams
| RedactExecuteParams
| RemovePasswordParams
| SanitizePdfParams
| TimestampPdfParams
@@ -1635,7 +1557,6 @@ type ParamToolModel = (
| SessionsParams
| ValidateCertificateParams
| RedactParams
| RedactExecuteParams
| RemovePasswordParams
| SanitizePdfParams
| TimestampPdfParams
@@ -1706,7 +1627,6 @@ class ToolEndpoint(StrEnum):
SESSIONS = "/api/v1/security/cert-sign/sessions"
VALIDATE_CERTIFICATE = "/api/v1/security/cert-sign/validate-certificate"
REDACT = "/api/v1/security/redact"
REDACT_EXECUTE = "/api/v1/security/redact-execute"
REMOVE_PASSWORD = "/api/v1/security/remove-password"
SANITIZE_PDF = "/api/v1/security/sanitize-pdf"
TIMESTAMP_PDF = "/api/v1/security/timestamp-pdf"
@@ -1775,7 +1695,6 @@ OPERATIONS: dict[ToolEndpoint, ParamToolModelType] = {
ToolEndpoint.SESSIONS: SessionsParams,
ToolEndpoint.VALIDATE_CERTIFICATE: ValidateCertificateParams,
ToolEndpoint.REDACT: RedactParams,
ToolEndpoint.REDACT_EXECUTE: RedactExecuteParams,
ToolEndpoint.REMOVE_PASSWORD: RemovePasswordParams,
ToolEndpoint.SANITIZE_PDF: SanitizePdfParams,
ToolEndpoint.TIMESTAMP_PDF: TimestampPdfParams,
+16 -11
View File
@@ -6,7 +6,7 @@ from dataclasses import dataclass
import pytest
from stirling.agents import PdfEditAgent, PdfEditParameterSelector, PdfEditPlanSelection
from stirling.agents.pdf_edit import PdfEditNeedContentSelection, PdfEditPlanOutput
from stirling.agents.pdf_edit import PdfEditPlanOutput
from stirling.contracts import (
AiFile,
EditCannotDoResponse,
@@ -82,12 +82,12 @@ class StubPdfEditAgent(PdfEditAgent):
if parameter_selector is not None:
self.parameter_selector = parameter_selector
def _classify_operations(self, request: PdfEditRequest) -> tuple[list[ToolEndpoint], list[ToolEndpoint]]:
def _get_supported_operations(self, request: PdfEditRequest) -> Iterable[ToolEndpoint]:
# Tests construct requests without `enabled_endpoints`; pretend everything is enabled
# unless the test explicitly supplies an enabled set.
if not request.enabled_endpoints:
return list(OPERATIONS), []
return super()._classify_operations(request)
if request.enabled_endpoints:
return request.enabled_endpoints
return OPERATIONS
async def _select_plan(
self,
@@ -194,8 +194,12 @@ async def test_pdf_edit_agent_returns_need_content_without_building_plan(runtime
parameter_selector = RecordingParameterSelector()
agent = StubPdfEditAgent(
runtime,
PdfEditNeedContentSelection(
NeedContentResponse(
resume_with=SupportedCapability.PDF_EDIT,
reason="Need page text to locate the NEW PAGE markers.",
files=[],
max_pages=0,
max_characters=0,
),
parameter_selector=parameter_selector,
)
@@ -270,8 +274,8 @@ async def test_pdf_edit_selection_agent_excludes_need_content_from_schema_when_n
can_request = PdfEditSelectionAgent(runtime, "base", allow_need_content=True)
cannot_request = PdfEditSelectionAgent(runtime, "base", allow_need_content=False)
assert PdfEditNeedContentSelection in _agent_output_types(can_request)
assert PdfEditNeedContentSelection not in _agent_output_types(cannot_request)
assert NeedContentResponse in _agent_output_types(can_request)
assert NeedContentResponse not in _agent_output_types(cannot_request)
def _agent_output_types(agent: object) -> list[type]:
@@ -332,7 +336,7 @@ async def test_pdf_edit_agent_supported_operations_defaults_to_empty(
runtime: AppRuntime,
) -> None:
agent = PdfEditAgent(runtime)
supported, _ = agent._classify_operations(PdfEditRequest(user_message="hi"))
supported = agent._get_supported_operations(PdfEditRequest(user_message="hi"))
assert list(supported) == []
@@ -347,7 +351,7 @@ async def test_pdf_edit_agent_supported_operations_uses_provided_list(
enabled_endpoints=[ToolEndpoint.FLATTEN, ToolEndpoint.ROTATE_PDF],
)
supported, _ = agent._classify_operations(request)
supported = agent._get_supported_operations(request)
assert list(supported) == [ToolEndpoint.FLATTEN, ToolEndpoint.ROTATE_PDF]
@@ -368,7 +372,8 @@ def test_pdf_edit_selection_prompt_includes_unavailable_operations(runtime: AppR
user_message="Run OCR.",
enabled_endpoints=[ToolEndpoint.FLATTEN],
)
supported, unavailable = agent._classify_operations(request)
supported = agent._get_supported_operations(request)
unavailable = agent._get_unavailable_operations(supported)
prompt = agent._build_selection_prompt(request, supported, unavailable)
@@ -1526,7 +1526,6 @@ section_title = "Agents"
show_less = "Show less"
start_chat = "Start chatting"
stirling_description = "Your general-purpose PDF assistant"
stirling_running = "Running..."
stirling_full_name = "Stirling General Agent"
stirling_long_description = "General purpose PDF assistant that can run tools, create PDFs and extract insights from your documents."
stirling_name = "Stirling"
@@ -2716,12 +2715,6 @@ title = "Change Permissions"
[changePermissions.tooltip.warning]
text = "To make these permissions unchangeable, use the Add Password tool to set an owner password."
[chat]
resize = "Resize chat panel"
[chat.actions]
copy = "Copy message"
[chat.header]
agentMenu = "Stirling agent options"
clearChat = "Clear chat"
@@ -3139,6 +3132,10 @@ integration = "Integration Configuration"
security = "Security Configuration"
system = "System Configuration"
[config.payg]
label = "Billing & usage"
section = "Pay-as-you-go"
[connectionMode.status]
localOffline = "Offline mode running"
localOnline = "Offline mode running"
@@ -5575,6 +5572,230 @@ bullet3 = "Invalid expressions are ignored"
text = "Keep these guidelines in mind:"
title = "Tips"
[payg]
subtitle = "Pay-as-you-go — you only pay for what you process. Billing period {{start}} – {{end}}."
[payg.activity]
subtitle = "Only AI and automation draw from your budget. Everyday tools are free and aren't listed here."
title = "Recent billable activity"
units = "units"
viewAll = "View all"
[payg.cap]
amount = "Cap amount"
currency = "Currency"
degradeAt = "Limit spend at"
degradeAtDesc = "Set below 100% to leave yourself headroom."
perMonth = "/ month"
preview = "{{money}} ≈ {{units}} documents per month"
previewNote = "At current pricing. Final translation happens server-side on save."
previewShort = "≈ {{units}} documents per month at current pricing."
save = "Update cap"
subtitle = "Set your maximum spend. We convert this to documents using the current price tier."
title = "Monthly spending cap"
warnAt = "Warn me at"
warnAtDesc = "Notify when usage crosses this threshold."
[payg.checkout]
connecting = "Connecting to Stripe…"
errorTitle = "Stripe error"
[payg.checkout.error]
startFailed = "Couldn't start checkout session"
[payg.checkout.mock]
backend = "Backend is in mock mode — no real Stripe session was created."
continue = "Continue with mock subscription"
noKey = "VITE_STRIPE_PUBLISHABLE_KEY is unset. Real iframe mounts here once configured."
title = "Stripe Embedded Checkout (mock mode)"
[payg.confirm]
body = "Your team can now run automation, AI, and API operations beyond the 500/month free allowance."
capValue = "{{symbol}}{{amount}} / month"
noCap = "No cap"
note = "You can change your cap, cancel, or open the Stripe customer portal any time from this page."
summaryLabel = "Monthly ceiling"
title = "Welcome to the Processor plan"
[payg.error]
body = "We couldn't reach the billing service. Refresh the page to try again."
title = "Couldn't load your plan"
[payg.exhausted]
body = "You've used your free 500 operations this month. Upgrade to Processor to keep going."
cta = "Go to billing"
title = "You've hit your free monthly limit"
[payg.free.cta]
benefit1Body = "chain tools, schedule runs, batch process"
benefit1Title = "Automation pipelines"
benefit2Body = "summarise, classify, redact, AI-OCR"
benefit2Title = "AI tools"
benefit3Body = "call any Stirling endpoint programmatically"
benefit3Title = "API access"
button = "Turn on Processor →"
reassurance = "No minimum · Set a $0 cap to test · Cancel anytime"
subtitle = "Unlock more than 500 automation, AI, and API operations per month. Set a monthly ceiling — you stay in control."
title = "Turn on the Processor plan"
[payg.free.explainer]
alwaysFreeBody = "Manual tools — viewing, editing, merging, splitting, signing, watermarks, compression, conversion, manual OCR. Use them as much as you want, no matter where you trigger them from."
alwaysFreeForYouBody = "Manual tools — viewing, editing, merging, splitting, signing, watermarks, compression, conversion, manual OCR. Use them as much as you want, never counted."
alwaysFreeForYouLabel = "Always free for you"
alwaysFreeLabel = "Always free"
countsBody = "Automation pipelines (chained tools, scheduled runs), AI tools (summaries, classification, AI-OCR), and API calls (programmatic access). Above 500 you'll need Processor."
countsLabel = "Counts toward 500/month"
sharedBody = "Automation pipelines, AI tools, and API calls share a single 500/month allowance across the whole team. If it's full, ask your owner to enable Processor."
sharedLabel = "Shared with the team"
[payg.free.header]
subtitle = "Editor plan — manual tools are always free. Pay only for automation, AI & API. Billing period {{period}}."
[payg.free.hero]
capSuffix = "/ {{limit}} free operations"
eyebrow = "This billing period"
metaCategories = "Automation · AI · API requests"
resetsIn = "Resets in {{days}} days"
resetsTomorrow = "Resets tomorrow"
[payg.free.member]
body = "Your team owner can enable the Processor plan and set a monthly ceiling. Until then, manual tools are free for you to use as much as you like — automation, AI, and API access are limited to the team's 500/month free allowance."
title = "Want more than 500 automation, AI, or API operations a month?"
[payg.free.state]
approachingLimit = "Approaching limit"
limitReached = "Limit reached"
plentyLeft = "Plenty left"
[payg.gates]
ai = "AI tools (AI Create, suggestions, AI-OCR)"
automation = "Automations & pipelines"
client = "Browser-only tools (viewer, page editor, file management)"
offsite = "Server tools (compress, OCR, convert, watermark…)"
pauses = "pauses at cap"
subtitle = "Your everyday tools keep working. Only AI and automation pause until the cap resets or is raised."
title = "What happens when the cap is reached"
[payg.member]
askLeader = "Only your team owner can change the cap."
contactLeader = "Ask team owner to raise cap"
editCap = "Edit"
noCap = "· no sub-cap"
setCap = "Set cap"
units = "units"
[payg.role]
leader = "Team owner"
member = "Member"
[payg.signupRequired]
body = "Stirling PDF gives every signed-up account 500 free operations per month — enough to keep most workflows humming without paying a cent. You're currently using Stirling as a guest, which doesn't include billable tools like AI, automations, or hosted processing."
cancel = "Not now"
cta = "Sign up free"
subtext = "Creating an account is free and takes a few seconds. No credit card required."
title = "Sign up to use {{category}}"
[payg.signupRequired.category]
ai = "AI features"
api = "this tool"
automation = "automations"
default = "this feature"
[payg.state]
degraded = "Cap reached"
full = "Healthy"
warned = "Approaching cap"
[payg.stripe]
open = "Open billing portal"
subtitle = "Receipts, invoices, payment method, billing currency."
title = "Manage billing in Stripe"
[payg.stripe.toast.unavailable]
body = "Billing portal isn't available right now. Try again in a moment."
title = "Billing portal unavailable"
[payg.subcaps]
subtitle = "Optional: cap individual teammates so one person can't drain the team budget."
title = "Per-member sub-caps"
[payg.subcaps.editor]
label = "Sub-cap for {{name}}"
remove = "Remove cap"
[payg.subcaps.toast.clamped]
body = "Clamped to team cap of {{units}} documents."
title = "Sub-cap clamped"
[payg.subcaps.toast.error]
body = "Please try again in a moment."
title = "Couldn't update sub-cap"
[payg.subcaps.toast.saved]
title = "Sub-cap updated"
[payg.upgrade]
closeAria = "Close"
[payg.upgrade.button]
back = "← Back"
cancel = "Cancel"
continue = "Continue →"
finish = "Finish"
[payg.upgrade.cap]
customPlaceholder = "Or enter your own amount ($0 keeps it free)"
help = "We'll never charge above this. Your first 500 automation / AI / API operations every month are free. Set $0 if you want to keep everything free while testing."
noCapHint = "You can still cancel anytime from the customer portal."
noCapLabel = "No cap — I'll manage spend manually"
perMonthSuffix = "/ month"
presetsAria = "Monthly cap preset"
title = "Set your monthly spend ceiling"
[payg.upgrade.checkout]
capLabel = "Monthly ceiling:"
capValue = "{{symbol}}{{amount}} / month"
edit = "Edit"
help = "Stripe handles your card details. Stirling never sees them."
loading = "Loading checkout…"
noCap = "No cap"
title = "Add your payment method"
[payg.upgrade.footer]
capHint = "You can change your cap any time later."
checkoutHint = "Card details handled by Stripe — never touched by Stirling."
confirmHint = "Your wallet will refresh automatically in a moment."
[payg.upgrade.help]
aiBody = "summarise, classify, redact, AI-OCR"
aiTitle = "AI tools"
apiBody = "programmatic access to any Stirling endpoint"
apiTitle = "API calls"
automationBody = "chained tools or scheduled runs that don't need clicks"
automationTitle = "Automation pipelines"
footnote = "Manual tools — viewing, editing, merging, splitting, watermarking, compressing, manual OCR — are always free, even past 500. The distinction is the type of work, not where you click."
title = "What we count toward billing"
[payg.upgrade.promise]
body = "You only pay for automation pipelines, AI tools, and API calls — the work that goes beyond a single click. Edit, merge, split, sign, compress as much as you want, no charge."
highlight = "Manual tools stay free, always."
[payg.upgrade.steps]
cap = "Set monthly ceiling"
payment = "Add payment method"
[payg.upgrade.title]
confirm = "You're subscribed"
default = "Upgrade to Processor plan"
[payg.usage]
credit = "{{amount}} account credit"
docs = "documents"
resetsIn = "Resets in {{days}} days"
resetsTomorrow = "Resets tomorrow"
spent = "{{spend}} of {{cap}} used"
thisPeriod = "This billing period"
[payment]
autoClose = "This window will close automatically..."
billingPeriod = "Billing Period"
@@ -8151,12 +8372,6 @@ label = "Select a TSA server"
[timestampPdf.steps]
settings = "Settings"
[time.relative]
daysAgo = "{{count}}d ago"
hoursAgo = "{{count}}h ago"
justNow = "just now"
minutesAgo = "{{count}}m ago"
[tool]
endpointUnavailable = "This tool is unavailable on your server."
endpointUnavailableClickable = "Not available in this mode. Click to sign in."
+1 -1
View File
@@ -225,7 +225,7 @@ export type MaterialSymbolIcon = ${usedIcons.map((icon) => `'${icon}'`).join(" |
export interface IconSet {
prefix: string;
icons: Record<string, unknown>;
icons: Record<string, any>;
width?: number;
height?: number;
}
+1 -2
View File
@@ -23,9 +23,8 @@
},
"bundle": {
"active": true,
"createUpdaterArtifacts": true,
"publisher": "Stirling PDF Inc.",
"targets": ["deb", "rpm", "appimage", "dmg", "app", "msi"],
"targets": ["deb", "rpm", "appimage", "dmg", "msi"],
"icon": [
"icons/icon.png",
"icons/icon.icns",
@@ -13,8 +13,10 @@ export function useAgentsEnabled(): boolean {
}
/**
* Whether the agent chat panel is currently open. Core builds have no chat,
* Whether the agent chat overlay is currently open. Core builds have no chat,
* so this always returns false. Proprietary builds bridge to the ChatContext.
* Used by {@code RightSidebar} so the fullscreen tool picker can yield to the
* chat overlay just like it yields to a selected tool.
*/
export function useAgentChatOpen(): boolean {
return false;
@@ -33,6 +35,14 @@ export function AgentsCollapsedButton(_props: { onExpand: () => void }) {
return null;
}
/**
* Full-rail chat overlay rendered inside {@code ToolPanel}. Covers the panel
* (including the search bar) when an agent conversation is active.
*/
export function AgentsChatOverlay() {
return null;
}
/**
* Agents card rendered inside the fullscreen tool picker. Matches the visual
* language of the fullscreen category cards (gradient border, title, items).
@@ -1,18 +0,0 @@
/**
* Core stub for the chat context.
* The real implementation lives in proprietary/components/chat/ChatContext.tsx
* and shadows this via the @app/* alias cascade in proprietary builds.
*/
export function useChat() {
return {
messages: [] as never[],
isOpen: false,
isLoading: false,
progress: null,
toggleOpen: () => {},
setOpen: (_open: boolean) => {},
sendMessage: async (_content: string) => {},
clearChat: () => {},
};
}
@@ -1,14 +0,0 @@
/**
* Core stub for the chat panel.
* The real implementation lives in proprietary/components/chat/ChatPanel.tsx
* and shadows this via the @app/* alias cascade in proprietary builds.
*/
export interface ChatPanelProps {
onBack: () => void;
backLabel: string;
}
export function ChatPanel(_props: ChatPanelProps) {
return null;
}
@@ -44,10 +44,13 @@ export default function Footer({
// Default URLs
const defaultTermsUrl = "https://www.stirling.com/terms";
const defaultPrivacyUrl = "https://www.stirling.com/privacy";
const defaultAccessibilityUrl = "https://www.stirling.com/accessibility";
// Use provided URLs or fall back to defaults
const finalTermsUrl = finalTermsAndConditions || defaultTermsUrl;
const finalPrivacyUrl = finalPrivacyPolicy || defaultPrivacyUrl;
const finalAccessibilityUrl =
finalAccessibilityStatement || defaultAccessibilityUrl;
// Helper to check if a value is valid (not null/undefined/empty string)
const isValidLink = (link?: string) => link && link.trim().length > 0;
@@ -118,16 +121,14 @@ export default function Footer({
>
{t("footer.issues", "GitHub")}
</a>
{isValidLink(finalAccessibilityStatement) && (
<a
className="footer-link px-3"
target="_blank"
rel="noopener noreferrer"
href={finalAccessibilityStatement}
>
{t("legal.accessibility", "Accessibility")}
</a>
)}
<a
className="footer-link px-3"
target="_blank"
rel="noopener noreferrer"
href={finalAccessibilityUrl}
>
{t("legal.accessibility", "Accessibility")}
</a>
{isValidLink(finalCookiePolicy) && (
<a
className="footer-link px-3"
@@ -36,9 +36,7 @@ const UserSelector = ({
useEffect(() => {
const fetchUsers = async () => {
try {
const response = await apiClient.get(
"/api/v1/security/cert-sign/eligible-participants",
);
const response = await apiClient.get("/api/v1/user/users");
console.log("Users API response:", response.data);
const fetchedUsers = response.data || [];
@@ -451,10 +451,6 @@ const GeneralSection: React.FC<GeneralSectionProps> = ({
},
]}
maw={360}
comboboxProps={{
withinPortal: true,
zIndex: Z_INDEX_OVER_CONFIG_MODAL,
}}
/>
</Stack>
)}
@@ -30,6 +30,7 @@ export const VALID_NAV_KEYS = [
"adminEndpoints",
"adminStorageSharing",
"help",
"payg",
] as const;
// Derive the type from the array
@@ -10,6 +10,7 @@
font-size: 0.875rem;
line-height: 1.5;
pointer-events: auto;
z-index: 9999;
transition:
opacity 100ms ease-out,
transform 100ms ease-out;
@@ -1,4 +1,4 @@
import { useMemo, useState, useRef, useCallback } from "react";
import { useMemo, useState } from "react";
import { ActionIcon } from "@mantine/core";
import { useTranslation } from "react-i18next";
import { useRainbowThemeContext } from "@app/components/shared/RainbowThemeProvider";
@@ -9,12 +9,11 @@ import { useIsMobile } from "@app/hooks/useIsMobile";
import ToolPanel from "@app/components/tools/ToolPanel";
import ToolSearch from "@app/components/tools/toolPicker/ToolSearch";
import {
AgentsChatOverlay,
AgentsCollapsedButton,
AgentsSection,
useAgentsEnabled,
} from "@app/components/agents/AgentsPanel";
import { useChat } from "@app/components/chat/ChatContext";
import { ChatPanel } from "@app/components/chat/ChatPanel";
import { useFavoriteToolItems } from "@app/hooks/tools/useFavoriteToolItems";
import { useToolSections } from "@app/hooks/useToolSections";
import type { SubcategoryGroup } from "@app/hooks/useToolSections";
@@ -33,10 +32,6 @@ import {
import { useToolPanelGeometry } from "@app/hooks/tools/useToolPanelGeometry";
import "@app/components/tools/ToolPanel.css";
const DEFAULT_CHAT_WIDTH_PX = 18.5 * 16; // 18.5rem in px
const MIN_CHAT_WIDTH_PX = 240;
const MAX_CHAT_WIDTH_PX = 720;
/**
* Right-side rail wrapping the tool panel.
*
@@ -91,57 +86,6 @@ export default function RightSidebar() {
const [allToolsView, setAllToolsView] = useState(false);
const { isOpen: isChatOpen, setOpen: setChatOpen } = useChat();
const [chatWidthPx, setChatWidthPx] = useState(DEFAULT_CHAT_WIDTH_PX);
const [isChatDragging, setIsChatDragging] = useState(false);
const chatDragState = useRef<{ startX: number; startWidth: number } | null>(
null,
);
const handleChatClose = useCallback(() => {
withViewTransition(() => setChatOpen(false));
setChatWidthPx(DEFAULT_CHAT_WIDTH_PX);
}, [setChatOpen]);
const handleResizeChatPointerDown = useCallback(
(e: React.PointerEvent<HTMLDivElement>) => {
e.preventDefault();
chatDragState.current = { startX: e.clientX, startWidth: chatWidthPx };
setIsChatDragging(true);
document.body.style.cursor = "col-resize";
document.body.style.userSelect = "none";
const onMove = (ev: PointerEvent) => {
if (!chatDragState.current) return;
const delta = chatDragState.current.startX - ev.clientX;
setChatWidthPx(
Math.max(
MIN_CHAT_WIDTH_PX,
Math.min(
MAX_CHAT_WIDTH_PX,
chatDragState.current.startWidth + delta,
),
),
);
};
const cleanup = () => {
chatDragState.current = null;
setIsChatDragging(false);
document.body.style.removeProperty("cursor");
document.body.style.removeProperty("user-select");
window.removeEventListener("pointermove", onMove);
window.removeEventListener("pointerup", cleanup);
window.removeEventListener("pointercancel", cleanup);
};
window.addEventListener("pointermove", onMove);
window.addEventListener("pointerup", cleanup);
window.addEventListener("pointercancel", cleanup);
},
[chatWidthPx],
);
const handleShowAllTools = () => {
withViewTransition(() => setAllToolsView(true));
};
@@ -203,7 +147,6 @@ export default function RightSidebar() {
const computedWidth = () => {
if (isMobile) return "100%";
if (isChatOpen) return `${chatWidthPx}px`;
if (!isPanelVisible) return "3.5rem";
return "18.5rem";
};
@@ -239,39 +182,15 @@ export default function RightSidebar() {
ref={toolPanelRef}
data-sidebar="tool-panel"
data-tour={fullscreenExpanded ? undefined : "tool-panel"}
className={`tool-panel flex flex-col ${fullscreenExpanded ? "tool-panel--fullscreen-active" : isChatOpen ? "" : "overflow-hidden"} bg-[var(--bg-toolbar)] border-l border-[var(--border-subtle)] transition-all duration-300 ease-out ${
className={`tool-panel flex flex-col ${fullscreenExpanded ? "tool-panel--fullscreen-active" : "overflow-hidden"} bg-[var(--bg-toolbar)] border-l border-[var(--border-subtle)] transition-all duration-300 ease-out ${
isRainbowMode ? rainbowStyles.rainbowPaper : ""
} ${isMobile ? "h-full border-r-0" : "h-screen"} ${fullscreenExpanded ? "tool-panel--fullscreen" : ""}`}
style={{
width: computedWidth(),
padding: "0",
...(isChatDragging ? { transition: "none" } : {}),
}}
>
{!fullscreenExpanded && isChatOpen && (
<div
style={{
height: "100%",
width: "100%",
display: "flex",
flexDirection: "column",
}}
>
<div
className="agents-takeover__resize-handle"
onPointerDown={handleResizeChatPointerDown}
role="separator"
aria-label={t("chat.resize", "Resize chat panel")}
aria-orientation="vertical"
/>
<ChatPanel
onBack={handleChatClose}
backLabel={t("agents.back_to_tools", "Back to tools")}
/>
</div>
)}
{!fullscreenExpanded && !isChatOpen && !isPanelVisible && !isMobile && (
{!fullscreenExpanded && !isPanelVisible && !isMobile && (
<div className="tool-panel__collapsed-strip">
<div className="tool-panel__collapsed-top">
<ActionIcon
@@ -315,7 +234,7 @@ export default function RightSidebar() {
</div>
)}
{!fullscreenExpanded && !isChatOpen && isPanelVisible && (
{!fullscreenExpanded && isPanelVisible && (
<div
/* Fixed width matches the expanded panel width so the inner content is
laid out at its final size from the moment it mounts. The outer
@@ -404,6 +323,7 @@ export default function RightSidebar() {
onToolSelect={handleToolSelectWithTransition}
compact={agentsEnabled && !allToolsView}
/>
<AgentsChatOverlay />
</div>
)}
@@ -33,7 +33,6 @@ import { useViewer } from "@app/contexts/ViewerContext";
import { useToolWorkflow } from "@app/contexts/ToolWorkflowContext";
import { useAnnotation as useAnnotationContext } from "@app/contexts/AnnotationContext";
import LocalIcon from "@app/components/shared/LocalIcon";
import { compareEntriesByVisualOrder } from "@app/components/viewer/commentsSidebarOrder";
const SIDEBAR_WIDTH = "18rem";
@@ -363,9 +362,9 @@ export function CommentsSidebar({
const all = getSidebarAnnotationsWithRepliesGroupedByPage(state) ?? {};
const filtered: typeof all = {};
for (const [page, entries] of Object.entries(all)) {
const commentEntries = entries
.filter((e) => isCommentAnnotation(e.annotation.object))
.sort(compareEntriesByVisualOrder);
const commentEntries = entries.filter((e) =>
isCommentAnnotation(e.annotation.object),
);
if (commentEntries.length > 0) {
filtered[Number(page)] = commentEntries;
}
@@ -64,16 +64,15 @@ async function extractPageMeasureScales(
// Parse a Measure dict into a MeasureScale, or return null if malformed.
const parseScale = (measureObj: unknown) => {
if (!(measureObj instanceof PDFDict)) return null;
// @cantoo/pdf-lib ships without individual .d.ts files so instanceof can't narrow `unknown`
const m = measureObj as PDFDict;
const rObj = m.lookup(PDFName.of("R"));
const rObj = measureObj.lookup(PDFName.of("R"));
const ratioLabel =
rObj instanceof PDFString || rObj instanceof PDFHexString
? rObj.decodeText()
: "";
// D = distance array, X = x-axis fallback
let fmtArray = m.lookup(PDFName.of("D"));
if (!(fmtArray instanceof PDFArray)) fmtArray = m.lookup(PDFName.of("X"));
let fmtArray = measureObj.lookup(PDFName.of("D"));
if (!(fmtArray instanceof PDFArray))
fmtArray = measureObj.lookup(PDFName.of("X"));
if (!(fmtArray instanceof PDFArray)) return null;
const firstFmt = fmtArray.lookup(0);
if (!(firstFmt instanceof PDFDict)) return null;
@@ -89,7 +89,7 @@ import { RedactionAPIBridge } from "@app/components/viewer/RedactionAPIBridge";
import { DocumentPermissionsAPIBridge } from "@app/components/viewer/DocumentPermissionsAPIBridge";
import { DocumentReadyWrapper } from "@app/components/viewer/DocumentReadyWrapper";
import { ActiveDocumentProvider } from "@app/components/viewer/ActiveDocumentContext";
import { pdfiumWasmUrl } from "@app/services/wasmPrecompiler";
import { absoluteWithBasePath } from "@app/constants/app";
import { FormFieldOverlay } from "@app/tools/formFill/FormFieldOverlay";
import { ButtonAppearanceOverlay } from "@app/tools/formFill/ButtonAppearanceOverlay";
import SignatureFieldOverlay from "@app/components/viewer/SignatureFieldOverlay";
@@ -296,7 +296,7 @@ export function LocalEmbedPDF({
// Initialize the engine with the React hook - use local WASM for offline support
const { engine, isLoading, error } = usePdfiumEngine({
wasmUrl: pdfiumWasmUrl,
wasmUrl: absoluteWithBasePath("/pdfium/pdfium.wasm"),
});
// Early return if no file or URL provided
@@ -1,101 +0,0 @@
import { describe, expect, it } from "vitest";
import { compareEntriesByVisualOrder } from "@app/components/viewer/commentsSidebarOrder";
function entry(id: string, x: number, y: number) {
return {
annotation: {
object: {
id,
rect: { origin: { x, y }, size: { width: 50, height: 12 } },
},
},
};
}
function ids(list: Array<{ annotation: { object: { id: string } } }>): string {
return list.map((e) => e.annotation.object.id).join(",");
}
describe("compareEntriesByVisualOrder", () => {
it("sorts a scrambled page back into top-to-bottom / left-to-right reading order", () => {
// EmbedPDF rects are viewport (top-left origin, y grows downward).
// Reading order on the page: A (top-left) → B (top-right, same row)
// → C (middle) → D (bottom). Storage order is D, C, A, B.
const A = entry("A", 100, 100);
const B = entry("B", 400, 100);
const C = entry("C", 100, 250);
const D = entry("D", 100, 400);
const out = [D, C, A, B].sort(compareEntriesByVisualOrder);
expect(ids(out)).toBe("A,B,C,D");
});
it("sorts entries on the same row by x ascending", () => {
const left = entry("L", 100, 200);
const mid = entry("M", 250, 200);
const right = entry("R", 400, 200);
const out = [right, left, mid].sort(compareEntriesByVisualOrder);
expect(ids(out)).toBe("L,M,R");
});
it("treats sub-pixel y differences as the same row", () => {
// Two annotations whose y differs by less than the SAME_ROW_EPSILON_PX
// tolerance should tie-break by x, not by the noisy y.
const a = entry("a", 100, 100.0);
const b = entry("b", 400, 100.3);
const out = [b, a].sort(compareEntriesByVisualOrder);
expect(ids(out)).toBe("a,b");
});
it("places entries without a rect at the end and preserves their order", () => {
const A = entry("A", 100, 100);
const D = entry("D", 100, 400);
const noRectX = { annotation: { object: { id: "X" } } };
const noRectY = { annotation: { object: { id: "Y" } } };
const out = [noRectX, A, noRectY, D].sort(compareEntriesByVisualOrder);
expect(ids(out)).toBe("A,D,X,Y");
});
it("returns 0 when both entries are missing a rect", () => {
const noRectX = { annotation: { object: { id: "X" } } };
const noRectY = { annotation: { object: { id: "Y" } } };
expect(compareEntriesByVisualOrder(noRectX, noRectY)).toBe(0);
expect(compareEntriesByVisualOrder(noRectY, noRectX)).toBe(0);
});
it("treats a missing rect origin as { x: 0, y: 0 }", () => {
const noOrigin = {
annotation: { object: { id: "noOrigin", rect: {} } },
} as unknown as ReturnType<typeof entry>;
const farDown = entry("farDown", 0, 999);
const out = [farDown, noOrigin].sort(compareEntriesByVisualOrder);
expect(ids(out)).toBe("noOrigin,farDown");
});
it("handles the multi-page case by sorting each page independently", () => {
// Simulates the byPage useMemo: each page is sorted on its own array.
const pages: Record<number, ReturnType<typeof entry>[]> = {
1: [
entry("p1-D", 100, 400),
entry("p1-B", 400, 100),
entry("p1-C", 100, 250),
entry("p1-A", 100, 100),
],
2: [
entry("p2-B", 400, 100),
entry("p2-A", 100, 100),
entry("p2-C", 100, 250),
],
3: [entry("p3-A", 100, 100)],
};
const sorted: Record<number, string> = {};
for (const [page, entries] of Object.entries(pages)) {
sorted[Number(page)] = ids(entries.sort(compareEntriesByVisualOrder));
}
expect(sorted).toEqual({
1: "p1-A,p1-B,p1-C,p1-D",
2: "p2-A,p2-B,p2-C",
3: "p3-A",
});
});
});
@@ -1,37 +0,0 @@
/**
* Compare two sidebar entries by visual position so the list matches the
* top-to-bottom / left-to-right reading order on the page.
*
* EmbedPDF exposes annotation rects in viewport coordinates (top-left origin,
* y grows downward), so the smaller `origin.y` comes first. A small epsilon on
* the y comparison treats items on the same row as a tie so they fall back to
* x-order. Entries without a rect sort to the end while preserving relative
* order (Array.prototype.sort is stable in modern engines).
*/
export interface CommentEntryLike {
annotation: {
object: {
id?: string;
rect?: {
origin?: { x?: number; y?: number };
};
};
};
}
const SAME_ROW_EPSILON_PX = 0.5;
export function compareEntriesByVisualOrder(
a: CommentEntryLike,
b: CommentEntryLike,
): number {
const ra = a.annotation?.object?.rect;
const rb = b.annotation?.object?.rect;
if (!ra && !rb) return 0;
if (!ra) return 1;
if (!rb) return -1;
const dy = (ra.origin?.y ?? 0) - (rb.origin?.y ?? 0);
if (Math.abs(dy) > SAME_ROW_EPSILON_PX) return dy;
return (ra.origin?.x ?? 0) - (rb.origin?.x ?? 0);
}
@@ -21,7 +21,6 @@ import {
StirlingFileStub,
} from "@app/types/fileContext";
import { FILE_EVENTS } from "@app/services/errorUtils";
import { zipFileService } from "@app/services/zipFileService";
import { getFilenameWithoutExtension } from "@app/utils/fileUtils";
import {
createChildStub,
@@ -275,36 +274,29 @@ export const useToolOperation = <TParams>(
responseType: "blob",
});
const responseBlob: Blob = response.data;
const contentTypeHeader = response.headers?.["content-type"];
// Multi-file responses are typically ZIP files that need extraction, but some may return single PDFs
if (config.responseHandler) {
// Use custom responseHandler for multi-file (handles ZIP extraction)
processedFiles = await config.responseHandler(
responseBlob,
response.data,
filesForAPI,
);
} else if (
await zipFileService.isZipResponse(
responseBlob,
typeof contentTypeHeader === "string"
? contentTypeHeader
: undefined,
)
response.data.type === "application/pdf" ||
(response.headers &&
response.headers["content-type"] === "application/pdf")
) {
processedFiles = await extractZipFiles(responseBlob);
} else {
// Single PDF response (e.g. split with merge option) - add prefix to first original filename
const filename = `${config.filePrefix}${filesForAPI[0]?.name || "document.pdf"}`;
processedFiles = [
new File([responseBlob], filename, { type: "application/pdf" }),
];
const singleFile = new File([response.data], filename, {
type: "application/pdf",
});
processedFiles = [singleFile];
} else {
// Default: assume ZIP response for multi-file endpoints
// Note: extractZipFiles will check preferences.autoUnzip setting
processedFiles = await extractZipFiles(response.data);
}
if (processedFiles.length === 0) {
throw new Error(
"The server processed the request but returned no files.",
);
}
// Assume all inputs succeeded together unless server provided an error earlier
successSourceIds = validFiles.map((f) => f.fileId);
break;
@@ -4,7 +4,6 @@
*/
import { loadScript } from "@app/utils/scriptLoader";
import { Z_INDEX_OVER_FILE_MANAGER_MODAL } from "@app/styles/zIndex";
const SCOPES = "https://www.googleapis.com/auth/drive.readonly";
const SESSION_STORAGE_ID = "googleDrivePickerAccessToken";
@@ -203,10 +202,6 @@ class GoogleDrivePickerService {
.addView(view2)
.setCallback((data: any) => this.pickerCallback(data, resolve, reject));
(builder as unknown as { setZIndex(z: number): void }).setZIndex(
Z_INDEX_OVER_FILE_MANAGER_MODAL,
);
if (options.multiple) {
builder.enableFeature(window.google.picker.Feature.MULTISELECT_ENABLED);
}
@@ -12,34 +12,9 @@
* `getSignatures`, `saveAsCopy`, …) wrap the `PdfEngine` interface so callers
* never have to deal with raw pointers or Tasks.
*/
import {
init,
type WrappedPdfiumModule,
type PdfiumModule,
} from "@embedpdf/pdfium";
import {
pdfiumWasmModulePromise,
startEagerWasmCompilation,
pdfiumWasmUrl,
} from "@app/services/wasmPrecompiler";
import { init, type WrappedPdfiumModule } from "@embedpdf/pdfium";
import type { FormField, WidgetCoordinates } from "@app/tools/formFill/types";
interface ExtendedPdfiumRuntime {
HEAPU8: Uint8Array;
HEAPF32: Float32Array;
}
interface PdfiumModuleOverrides extends Partial<PdfiumModule> {
locateFile?: (url: string, scriptDirectory?: string) => string;
instantiateWasm?: (
imports: WebAssembly.Imports,
successCallback: (
instance: WebAssembly.Instance,
module: WebAssembly.Module,
) => void,
) => void;
}
// PDF form field type constants (matching PDFium C API FPDF_FORMFIELD_* values)
const FPDF_FORMFIELD_UNKNOWN = 0;
const FPDF_FORMFIELD_PUSHBUTTON = 1;
@@ -71,7 +46,8 @@ let _module: WrappedPdfiumModule | null = null;
* Resolve the absolute WASM URL using the same pattern as LocalEmbedPDF.
*/
function wasmUrl(): string {
return pdfiumWasmUrl;
const base = (import.meta as any).env?.BASE_URL ?? "/";
return `${base}pdfium/pdfium.wasm`.replace(/\/\//g, "/");
}
/**
@@ -83,47 +59,9 @@ function wasmUrl(): string {
export async function getPdfiumModule(): Promise<WrappedPdfiumModule> {
if (_module) return _module;
if (!_initPromise) {
// Ensure eager compilation has started if PDF service is requested before idle timeout
startEagerWasmCompilation();
const overrides: PdfiumModuleOverrides = {
_initPromise = init({
locateFile: () => wasmUrl(),
};
// Eagerly reuse pre-compiled WASM module from app boot if available
overrides.instantiateWasm = (
imports: WebAssembly.Imports,
successCallback: (
instance: WebAssembly.Instance,
module: WebAssembly.Module,
) => void,
) => {
pdfiumWasmModulePromise
.then((wasmModule) => {
if (wasmModule) {
return WebAssembly.instantiate(wasmModule, imports).then(
(instance) => {
successCallback(instance, wasmModule);
},
);
} else {
throw new Error("No pre-compiled WASM module found");
}
})
.catch((err: unknown) => {
console.warn(
"Eager WebAssembly instantiation failed, falling back to streaming compilation:",
err,
);
WebAssembly.instantiateStreaming(fetch(wasmUrl()), imports).then(
(result) => {
successCallback(result.instance, result.module);
},
);
});
};
_initPromise = init(overrides as Partial<PdfiumModule>).then((m) => {
} as any).then((m) => {
// Call PDFiumExt_Init to ensure extensions (form fill etc.) are set up
try {
m.PDFiumExt_Init();
@@ -172,9 +110,9 @@ export function readAnnotRectAdjusted(
annotPtr: number,
rectBuf: number,
): boolean {
const ext = m.EPDFAnnot_GetRect;
const ext = (m as any).EPDFAnnot_GetRect;
if (typeof ext === "function") {
return ext(annotPtr, rectBuf);
return ext.call(m, annotPtr, rectBuf);
}
return m.FPDFAnnot_GetRect(annotPtr, rectBuf);
}
@@ -248,13 +186,15 @@ export function readEffectivePageBox(
let result: PageBox | null = null;
try {
// CropBox is the effective visible area
if (m.FPDFPage_GetCropBox(pagePtr, buf, buf + 4, buf + 8, buf + 12)) {
if (
(m as any).FPDFPage_GetCropBox(pagePtr, buf, buf + 4, buf + 8, buf + 12)
) {
result = read();
}
// Fall back to MediaBox
if (
!result &&
m.FPDFPage_GetMediaBox(pagePtr, buf, buf + 4, buf + 8, buf + 12)
(m as any).FPDFPage_GetMediaBox(pagePtr, buf, buf + 4, buf + 8, buf + 12)
) {
result = read();
}
@@ -286,7 +226,7 @@ function copyToWasmHeap(
bytes: Uint8Array,
ptr: number,
): void {
(m.pdfium as typeof m.pdfium & ExtendedPdfiumRuntime).HEAPU8.set(bytes, ptr);
new Uint8Array((m.pdfium.wasmExports as any).memory.buffer).set(bytes, ptr);
}
/**
@@ -1398,13 +1338,9 @@ async function renderWidgetAppearance(
formEnvPtr: number,
dpr: number,
): Promise<ImageData | null> {
const pdfiumWasm = m.pdfium as any;
const matrixPtr = m.pdfium.wasmExports.malloc(6 * 4);
const pdfiumRuntime = m.pdfium as typeof m.pdfium & ExtendedPdfiumRuntime;
const matrixView = new Float32Array(
pdfiumRuntime.HEAPF32.buffer,
matrixPtr,
6,
);
const matrixView = new Float32Array(pdfiumWasm.HEAPF32.buffer, matrixPtr, 6);
const sx = wDev / pdfW;
const sy = hDev / pdfH;
matrixView.set([sx, 0, 0, -sy, -sx * annotLeft, sy * annotTop]);
@@ -1428,7 +1364,7 @@ async function renderWidgetAppearance(
let imageData: ImageData | null = null;
if (ok) {
const rgba = new Uint8ClampedArray(
pdfiumRuntime.HEAPU8.subarray(heapPtr, heapPtr + bytes),
pdfiumWasm.HEAPU8.buffer.slice(heapPtr, heapPtr + bytes),
);
let hasVisible = false;
for (let i = 3; i < rgba.length; i += 4) {
@@ -1481,7 +1417,7 @@ async function renderWidgetAppearance(
m.FPDFBitmap_Destroy(bmp2);
const rgba2 = new Uint8ClampedArray(
pdfiumRuntime.HEAPU8.subarray(heap2, heap2 + bytes),
pdfiumWasm.HEAPU8.buffer.slice(heap2, heap2 + bytes),
);
let hasVisible2 = false;
for (let i = 3; i < rgba2.length; i += 4) {
@@ -1624,6 +1560,8 @@ export async function renderSignatureFieldAppearances(
const hDev = Math.max(1, Math.round(pdfH * dpr));
const stride = wDev * 4;
const bytes = stride * hDev;
const pdfiumWasm = m.pdfium as any;
const heapPtr = m.pdfium.wasmExports.malloc(bytes);
const bitmapPtr = m.FPDFBitmap_CreateEx(
wDev,
@@ -1639,10 +1577,8 @@ export async function renderSignatureFieldAppearances(
const sx = wDev / pdfW;
const sy = hDev / pdfH;
const matrixPtr = m.pdfium.wasmExports.malloc(6 * 4);
const pdfiumRuntime = m.pdfium as typeof m.pdfium &
ExtendedPdfiumRuntime;
const matrixView = new Float32Array(
pdfiumRuntime.HEAPF32.buffer,
pdfiumWasm.HEAPF32.buffer,
matrixPtr,
6,
);
@@ -1667,7 +1603,7 @@ export async function renderSignatureFieldAppearances(
if (ok) {
const rgba = new Uint8ClampedArray(
pdfiumRuntime.HEAPU8.subarray(heapPtr, heapPtr + bytes),
pdfiumWasm.HEAPU8.buffer.slice(heapPtr, heapPtr + bytes),
);
let hasVisible = false;
for (let i = 3; i < rgba.length; i += 4) {
@@ -1727,7 +1663,7 @@ export async function renderSignatureFieldAppearances(
m.FPDFBitmap_Destroy(bmp2);
const rgba2 = new Uint8ClampedArray(
pdfiumRuntime.HEAPU8.subarray(heap2, heap2 + bytes),
pdfiumWasm.HEAPU8.buffer.slice(heap2, heap2 + bytes),
);
let hasVisible2 = false;
for (let i = 3; i < rgba2.length; i += 4) {
@@ -1,54 +0,0 @@
import { BASE_PATH } from "@app/constants/app";
import pdfiumWasmAssetUrl from "@embedpdf/pdfium/pdfium.wasm?url";
const getWasmUrl = (): string => {
if (
pdfiumWasmAssetUrl.startsWith("http://") ||
pdfiumWasmAssetUrl.startsWith("https://") ||
pdfiumWasmAssetUrl.startsWith("//")
) {
return pdfiumWasmAssetUrl;
}
const origin = typeof window !== "undefined" ? window.location.origin : "";
if (import.meta.env.DEV) {
return `${origin}${BASE_PATH}/pdfium/pdfium.wasm`;
}
const cleanAssetUrl = pdfiumWasmAssetUrl
.replace(/^\.\//, "")
.replace(/^\//, "");
return `${origin}${BASE_PATH}/${cleanAssetUrl}`;
};
export const pdfiumWasmUrl = getWasmUrl();
let resolvePromise: (module: WebAssembly.Module | null) => void;
let compilationStarted = false;
export const pdfiumWasmModulePromise = new Promise<WebAssembly.Module | null>(
(resolve) => {
resolvePromise = resolve;
},
);
export function startEagerWasmCompilation(): void {
if (compilationStarted) return;
compilationStarted = true;
if (
typeof WebAssembly === "object" &&
typeof WebAssembly.compileStreaming === "function"
) {
WebAssembly.compileStreaming(fetch(pdfiumWasmUrl))
.then(resolvePromise)
.catch((err) => {
console.warn(
"Eager WASM compilation failed or not supported in this environment:",
err,
);
resolvePromise(null);
});
} else {
resolvePromise(null);
}
}
@@ -1,122 +0,0 @@
import { describe, expect, test } from "vitest";
import { zipFileService } from "@app/services/zipFileService";
// jsdom's Blob.slice(...).arrayBuffer() returns an empty buffer in this
// version, so a real Blob would never reach the magic-byte branch under test.
// Duck-type the parts isZipResponse actually touches.
function fakeBlob(bytes: number[], type = ""): Blob {
const u8 = new Uint8Array(bytes);
const slice = (start: number, end?: number) =>
fakeBlob(Array.from(u8.slice(start, end)), type);
return {
size: u8.byteLength,
type,
slice,
arrayBuffer: async () =>
u8.buffer.slice(u8.byteOffset, u8.byteOffset + u8.byteLength),
} as unknown as Blob;
}
const PDF_BYTES = [0x25, 0x50, 0x44, 0x46, 0x2d, 0x31, 0x2e, 0x37]; // "%PDF-1.7"
describe("zipFileService.isZipResponse", () => {
describe("signature is authoritative", () => {
test("PK\\x03\\x04 -> ZIP", async () => {
expect(
await zipFileService.isZipResponse(
fakeBlob([0x50, 0x4b, 0x03, 0x04, 0x00, 0x00]),
),
).toBe(true);
});
test("PK\\x05\\x06 (empty archive) -> ZIP", async () => {
expect(
await zipFileService.isZipResponse(fakeBlob([0x50, 0x4b, 0x05, 0x06])),
).toBe(true);
});
test("PK\\x07\\x08 (spanned marker) -> ZIP", async () => {
expect(
await zipFileService.isZipResponse(fakeBlob([0x50, 0x4b, 0x07, 0x08])),
).toBe(true);
});
test("%PDF signature overrides a ZIP Content-Type", async () => {
expect(
await zipFileService.isZipResponse(
fakeBlob(PDF_BYTES),
"application/zip",
),
).toBe(false);
});
});
// Bug-trigger Content-Types: previously misrouted PDFs into ZIP extraction.
describe("bug-trigger Content-Types must not misroute a PDF", () => {
test('"application/pdf;charset=UTF-8" + %PDF -> NOT ZIP', async () => {
expect(
await zipFileService.isZipResponse(
fakeBlob(PDF_BYTES),
"application/pdf;charset=UTF-8",
),
).toBe(false);
});
test('"application/octet-stream" + %PDF -> NOT ZIP', async () => {
expect(
await zipFileService.isZipResponse(
fakeBlob(PDF_BYTES),
"application/octet-stream",
),
).toBe(false);
});
test('"APPLICATION/PDF" + %PDF -> NOT ZIP', async () => {
expect(
await zipFileService.isZipResponse(
fakeBlob(PDF_BYTES),
"APPLICATION/PDF",
),
).toBe(false);
});
});
describe("Content-Type fallback when signature is inconclusive", () => {
const UNKNOWN_BYTES = [0xff, 0xff, 0xff, 0xff];
test('unknown bytes + "application/zip" -> ZIP', async () => {
expect(
await zipFileService.isZipResponse(
fakeBlob(UNKNOWN_BYTES),
"application/zip",
),
).toBe(true);
});
test('unknown bytes + "application/x-zip-compressed" -> ZIP', async () => {
expect(
await zipFileService.isZipResponse(
fakeBlob(UNKNOWN_BYTES),
"application/x-zip-compressed",
),
).toBe(true);
});
test('unknown bytes + "application/json" -> NOT ZIP', async () => {
expect(
await zipFileService.isZipResponse(
fakeBlob(UNKNOWN_BYTES),
"application/json",
),
).toBe(false);
});
test("unknown bytes, no hint, blob.type 'application/zip' -> ZIP", async () => {
expect(
await zipFileService.isZipResponse(
fakeBlob(UNKNOWN_BYTES, "application/zip"),
),
).toBe(true);
});
});
});
@@ -303,37 +303,6 @@ export class ZipFileService {
return hasValidType || hasValidExtension;
}
// Signature-first ZIP detection for HTTP response bodies. Content-Type alone
// is unreliable: proxies and some backends ship merged PDFs as
// "application/pdf;charset=UTF-8" or "application/octet-stream", which an
// exact-equality check would misroute into ZIP extraction.
public async isZipResponse(
blob: Blob,
contentTypeHint?: string,
): Promise<boolean> {
try {
const sig = new Uint8Array(await blob.slice(0, 4).arrayBuffer());
if (
sig[0] === 0x50 &&
sig[1] === 0x4b &&
(sig[2] === 0x03 || sig[2] === 0x05 || sig[2] === 0x07)
) {
return true;
}
if (
sig[0] === 0x25 &&
sig[1] === 0x50 &&
sig[2] === 0x44 &&
sig[3] === 0x46
) {
return false;
}
} catch {
// Unreadable blob - fall back to Content-Type.
}
return (contentTypeHint || blob.type || "").toLowerCase().includes("zip");
}
/**
* Check if a filename indicates a PDF file
*/
+5
View File
@@ -0,0 +1,5 @@
// jest-dom adds custom jest matchers for asserting on DOM nodes.
// allows you to do things like:
// expect(element).toHaveTextContent(/react/i)
// learn more: https://github.com/testing-library/jest-dom
import "@testing-library/jest-dom";
+2 -2
View File
@@ -99,12 +99,12 @@ Object.defineProperty(globalThis, "crypto", {
subtle: {
digest: vi
.fn()
.mockImplementation(async (_algorithm: string, _data: BufferSource) => {
.mockImplementation(async (_algorithm: string, _data: any) => {
// Always return the mock hash buffer regardless of input
return mockHashBuffer.slice();
}),
},
getRandomValues: vi.fn().mockImplementation((array: Uint8Array) => {
getRandomValues: vi.fn().mockImplementation((array: any) => {
// Mock getRandomValues if needed
for (let i = 0; i < array.length; i++) {
array[i] = Math.floor(Math.random() * 256);
+1 -1
View File
@@ -515,7 +515,7 @@
/* 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: rgba(255, 255, 255, 0.08);
--border-subtle: #2a2f36;
--border-default: #3a4047;
--border-strong: #4b5563;
--hover-bg: #374151;
+1 -1
View File
@@ -12,7 +12,7 @@ export const Z_INDEX_OVER_FILE_MANAGER_MODAL = 1300;
export const Z_INDEX_AUTOMATE_MODAL = 1100;
// Dropdowns/Popovers inside automation modals need to be above the modal
export const Z_INDEX_AUTOMATE_DROPDOWN = 1150;
export const Z_INDEX_AUTOMATE_DROPDOWN = 1200;
// page editor Zindexes
export const Z_INDEX_HOVER_ACTION_MENU = 100;
@@ -1,106 +0,0 @@
import { test, expect } from "@app/tests/helpers/stub-test-base";
import path from "path";
const ANNOTATED_PDF = path.join(
__dirname,
"../test-fixtures/annotations_out_of_order.pdf",
);
/**
* Regression test for https://github.com/Stirling-Tools/Stirling-PDF/issues/6439
*
* The fixture PDF (3 pages) has 4 text annotations per page stored in
* deliberately scrambled object order (D, B, C, A). With the sort applied,
* the Comments sidebar must list them in top-to-bottom / left-to-right
* reading order on every page: A, B, C, D.
*/
test.describe("Comments sidebar - annotation reading order", () => {
test("annotations on each page are listed in visual reading order", async ({
page,
}) => {
await page.goto("/read");
await page.waitForLoadState("domcontentloaded");
// Upload the test fixture via the hidden file input (avoids the native
// file picker dialog).
await page
.locator('[data-testid="file-input"]')
.first()
.setInputFiles(ANNOTATED_PDF);
// Sanity-check that the page indicator reflects a 3-page document.
await expect(page.getByText(/\/\s*3/)).toBeVisible({ timeout: 30_000 });
// Open the Comments sidebar via the WorkbenchBar button.
const commentsBtn = page
.getByRole("button", { name: /^Comments$/i })
.first();
if (
!(await commentsBtn.isVisible({ timeout: 10_000 }).catch(() => false))
) {
test.skip(true, "Comments button not visible on this build");
return;
}
await commentsBtn.click();
// Pull the rendered order out of the sidebar. Each comment card is
// identified by `data-comment-card="${pageIndex}_${annotationId}"`.
// The annotation `contents` text (e.g. "Annotation A on page 1") is
// rendered inside the card and is the most reliable label to read.
await expect
.poll(
async () => {
return await page.evaluate(() => {
const cards = Array.from(
document.querySelectorAll<HTMLElement>("[data-comment-card]"),
);
return cards
.map((c) => {
const key = c.getAttribute("data-comment-card") || "";
const pageIndex = Number(key.split("_")[0]);
const text = (c.innerText || "").replace(/\s+/g, " ");
const m = text.match(
/Annotation\s+([ABCD])\s+on\s+page\s+(\d+)/i,
);
return m
? { pageIndex, label: m[1].toUpperCase(), text }
: { pageIndex, label: "?", text: text.slice(0, 80) };
})
.filter((e) => e.label !== "?");
});
},
{ timeout: 30_000, message: "waiting for 12 comment cards" },
)
.toHaveLength(12);
const entries = await page.evaluate(() => {
const cards = Array.from(
document.querySelectorAll<HTMLElement>("[data-comment-card]"),
);
return cards
.map((c) => {
const key = c.getAttribute("data-comment-card") || "";
const pageIndex = Number(key.split("_")[0]);
const text = (c.innerText || "").replace(/\s+/g, " ");
const m = text.match(/Annotation\s+([ABCD])\s+on\s+page\s+(\d+)/i);
return m && pageIndex === Number(m[2]) - 1
? { pageIndex, label: m[1].toUpperCase() }
: null;
})
.filter((e): e is { pageIndex: number; label: string } => e !== null);
});
// Group labels by page in the order they appear in the sidebar.
const byPage: Record<number, string[]> = {};
for (const { pageIndex, label } of entries) {
(byPage[pageIndex] ||= []).push(label);
}
// Each of the 3 pages must show A, B, C, D in that order.
expect(byPage).toEqual({
0: ["A", "B", "C", "D"],
1: ["A", "B", "C", "D"],
2: ["A", "B", "C", "D"],
});
});
});
@@ -1,7 +1,6 @@
import { test, expect } from "@app/tests/helpers/stub-test-base";
import type { Page, Route } from "@playwright/test";
import path from "node:path";
import { DATABASE_CONFIGS } from "@app/services/indexedDBManager";
/** Screenshot review of /files surfaces; dumps PNGs to screenshots/files-page. */
@@ -13,91 +12,62 @@ interface SeedFile {
}
async function seedFiles(page: Page, files: SeedFile[]): Promise<void> {
// Build the server-side view from the cloud entries so reconcileServerFiles
// sees them as still-existing on the server (otherwise they get detached
// and the cloud cards vanish before the screenshot is taken).
const serverFiles = files
.filter((f) => f.remoteStorageId != null)
.map((f) => ({
id: f.remoteStorageId,
fileName: f.name,
contentType: "application/pdf",
sizeBytes: 1024,
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString(),
owner: "testuser",
ownedByCurrentUser: true,
accessRole: "owner",
shareLinks: [],
filePurpose: "generic",
folderId: null,
}));
await page.route("**/api/v1/storage/files", (route: Route) =>
route.fulfill({ json: serverFiles }),
);
await page.addInitScript(
({ records, dbVersion }) => {
const open = window.indexedDB.open("stirling-pdf-files", dbVersion);
open.onupgradeneeded = (event) => {
const db = (event.target as IDBOpenDBRequest).result;
// Create both `files` and `folders` stores on this DB.
if (!db.objectStoreNames.contains("files")) {
const store = db.createObjectStore("files", { keyPath: "id" });
store.createIndex("name", "name", { unique: false });
store.createIndex("folderId", "folderId", { unique: false });
store.createIndex("originalFileId", "originalFileId", {
unique: false,
});
}
if (!db.objectStoreNames.contains("folders")) {
const fStore = db.createObjectStore("folders", { keyPath: "id" });
fStore.createIndex("parentFolderId", "parentFolderId", {
unique: false,
});
fStore.createIndex("name", "name", { unique: false });
}
};
open.onsuccess = () => {
const db = open.result;
// Yield the connection if the app ever needs to upgrade, and drop it
// once the writes commit, so the seed never blocks the app's open.
db.onversionchange = () => db.close();
const tx = db.transaction("files", "readwrite");
const store = tx.objectStore("files");
const now = Date.now();
for (const f of records) {
store.put({
id: f.id,
fileId: f.id,
quickKey: f.id,
name: f.name,
type: "application/pdf",
size: 1024,
lastModified: now,
createdAt: now,
data: new ArrayBuffer(8),
thumbnail: null,
isLeaf: true,
versionNumber: 1,
originalFileId: f.id,
parentFileId: null,
toolHistory: [],
folderId: f.folderId ?? null,
remoteStorageId: f.remoteStorageId,
remoteStorageUpdatedAt: f.remoteStorageId ? now : null,
remoteOwnerUsername: f.remoteStorageId ? "testuser" : null,
remoteOwnedByCurrentUser: f.remoteStorageId ? true : null,
remoteAccessRole: f.remoteStorageId ? "owner" : null,
remoteSharedViaLink: false,
remoteHasShareLinks: false,
remoteShareToken: null,
});
}
tx.oncomplete = () => db.close();
};
},
{ records: files, dbVersion: DATABASE_CONFIGS.FILES.version },
);
await page.addInitScript((records) => {
const open = window.indexedDB.open("stirling-pdf-files", 4);
open.onupgradeneeded = (event) => {
const db = (event.target as IDBOpenDBRequest).result;
// Create both `files` and `folders` stores on this DB.
if (!db.objectStoreNames.contains("files")) {
const store = db.createObjectStore("files", { keyPath: "id" });
store.createIndex("name", "name", { unique: false });
store.createIndex("folderId", "folderId", { unique: false });
store.createIndex("originalFileId", "originalFileId", {
unique: false,
});
}
if (!db.objectStoreNames.contains("folders")) {
const fStore = db.createObjectStore("folders", { keyPath: "id" });
fStore.createIndex("parentFolderId", "parentFolderId", {
unique: false,
});
fStore.createIndex("name", "name", { unique: false });
}
};
open.onsuccess = () => {
const db = open.result;
const tx = db.transaction("files", "readwrite");
const store = tx.objectStore("files");
const now = Date.now();
for (const f of records) {
store.put({
id: f.id,
fileId: f.id,
quickKey: f.id,
name: f.name,
type: "application/pdf",
size: 1024,
lastModified: now,
createdAt: now,
data: new ArrayBuffer(8),
thumbnail: null,
isLeaf: true,
versionNumber: 1,
originalFileId: f.id,
parentFileId: null,
toolHistory: [],
folderId: f.folderId ?? null,
remoteStorageId: f.remoteStorageId,
remoteStorageUpdatedAt: f.remoteStorageId ? now : null,
remoteOwnerUsername: f.remoteStorageId ? "testuser" : null,
remoteOwnedByCurrentUser: f.remoteStorageId ? true : null,
remoteAccessRole: f.remoteStorageId ? "owner" : null,
remoteSharedViaLink: false,
remoteHasShareLinks: false,
remoteShareToken: null,
});
}
};
}, files);
}
async function stubStorageApis(
@@ -171,10 +141,8 @@ test.describe("Files page screenshots", () => {
{ id: "cloud-c", name: "cloud-c.pdf", remoteStorageId: 1001 },
]);
await page.goto("/files", { waitUntil: "domcontentloaded" });
await expect(
page.locator(".files-page-card:not(.files-page-skeleton-card)").first(),
).toBeVisible({
timeout: 10_000,
await expect(page.locator(".files-page-card").first()).toBeVisible({
timeout: 5_000,
});
await settle(page);
await page.screenshot({ path: shotPath("03_subtoolbar_with_files") });
@@ -186,10 +154,8 @@ test.describe("Files page screenshots", () => {
{ id: "alpha", name: "alpha.pdf", remoteStorageId: null },
]);
await page.goto("/files", { waitUntil: "domcontentloaded" });
await expect(
page.locator(".files-page-card:not(.files-page-skeleton-card)").first(),
).toBeVisible({
timeout: 10_000,
await expect(page.locator(".files-page-card").first()).toBeVisible({
timeout: 5_000,
});
const card = page
.locator(".files-page-card:not(.is-folder)")
@@ -208,10 +174,8 @@ test.describe("Files page screenshots", () => {
{ id: "cloud-c", name: "cloud-c.pdf", remoteStorageId: 1001 },
]);
await page.goto("/files", { waitUntil: "domcontentloaded" });
await expect(
page.locator(".files-page-card:not(.files-page-skeleton-card)").first(),
).toBeVisible({
timeout: 10_000,
await expect(page.locator(".files-page-card").first()).toBeVisible({
timeout: 5_000,
});
const card = page
.locator(".files-page-card:not(.is-folder)")
@@ -229,10 +193,8 @@ test.describe("Files page screenshots", () => {
{ id: "alpha", name: "alpha.pdf", remoteStorageId: null },
]);
await page.goto("/files", { waitUntil: "domcontentloaded" });
await expect(
page.locator(".files-page-card:not(.files-page-skeleton-card)").first(),
).toBeVisible({
timeout: 10_000,
await expect(page.locator(".files-page-card").first()).toBeVisible({
timeout: 5_000,
});
await page
.locator(".files-page-card:not(.is-folder)")
@@ -251,10 +213,8 @@ test.describe("Files page screenshots", () => {
{ id: "alpha", name: "alpha.pdf", remoteStorageId: null },
]);
await page.goto("/files", { waitUntil: "domcontentloaded" });
await expect(
page.locator(".files-page-card:not(.files-page-skeleton-card)").first(),
).toBeVisible({
timeout: 10_000,
await expect(page.locator(".files-page-card").first()).toBeVisible({
timeout: 5_000,
});
const card = page
.locator(".files-page-card:not(.is-folder)")
@@ -274,10 +234,8 @@ test.describe("Files page screenshots", () => {
{ id: "alpha", name: "alpha.pdf", remoteStorageId: null },
]);
await page.goto("/files", { waitUntil: "domcontentloaded" });
await expect(
page.locator(".files-page-card:not(.files-page-skeleton-card)").first(),
).toBeVisible({
timeout: 10_000,
await expect(page.locator(".files-page-card").first()).toBeVisible({
timeout: 5_000,
});
const card = page
.locator(".files-page-card:not(.is-folder)")
@@ -305,10 +263,8 @@ test.describe("Files page screenshots", () => {
]);
await page.setViewportSize({ width: 900, height: 700 });
await page.goto("/files", { waitUntil: "domcontentloaded" });
await expect(
page.locator(".files-page-card:not(.files-page-skeleton-card)").first(),
).toBeVisible({
timeout: 10_000,
await expect(page.locator(".files-page-card").first()).toBeVisible({
timeout: 5_000,
});
await settle(page);
await page.screenshot({ path: shotPath("09_subtoolbar_narrow_viewport") });
@@ -342,10 +298,8 @@ test.describe("Files page screenshots", () => {
{ times: 5 },
);
await page.goto("/files", { waitUntil: "domcontentloaded" });
await expect(
page.locator(".files-page-card:not(.files-page-skeleton-card)").first(),
).toBeVisible({
timeout: 10_000,
await expect(page.locator(".files-page-card").first()).toBeVisible({
timeout: 5_000,
});
const card = page
.locator(".files-page-card:not(.is-folder)")
@@ -395,10 +349,8 @@ test.describe("Files page screenshots", () => {
{ id: "bravo", name: "bravo.pdf", remoteStorageId: null },
]);
await page.goto("/files", { waitUntil: "domcontentloaded" });
await expect(
page.locator(".files-page-card:not(.files-page-skeleton-card)").first(),
).toBeVisible({
timeout: 10_000,
await expect(page.locator(".files-page-card").first()).toBeVisible({
timeout: 5_000,
});
await settle(page);
await page.screenshot({ path: shotPath("12_dark_subtoolbar_with_files") });
@@ -411,10 +363,8 @@ test.describe("Files page screenshots", () => {
{ id: "alpha", name: "alpha.pdf", remoteStorageId: null },
]);
await page.goto("/files", { waitUntil: "domcontentloaded" });
await expect(
page.locator(".files-page-card:not(.files-page-skeleton-card)").first(),
).toBeVisible({
timeout: 10_000,
await expect(page.locator(".files-page-card").first()).toBeVisible({
timeout: 5_000,
});
const card = page
.locator(".files-page-card:not(.is-folder)")
@@ -462,10 +412,8 @@ test.describe("Files page screenshots", () => {
{ id: "bravo", name: "bravo.pdf", remoteStorageId: null },
]);
await page.goto("/files", { waitUntil: "domcontentloaded" });
await expect(
page.locator(".files-page-card:not(.files-page-skeleton-card)").first(),
).toBeVisible({
timeout: 10_000,
await expect(page.locator(".files-page-card").first()).toBeVisible({
timeout: 5_000,
});
await settle(page);
await page.screenshot({ path: shotPath("16_rtl_subtoolbar_with_files") });
@@ -478,10 +426,8 @@ test.describe("Files page screenshots", () => {
{ id: "alpha", name: "alpha.pdf", remoteStorageId: null },
]);
await page.goto("/files", { waitUntil: "domcontentloaded" });
await expect(
page.locator(".files-page-card:not(.files-page-skeleton-card)").first(),
).toBeVisible({
timeout: 10_000,
await expect(page.locator(".files-page-card").first()).toBeVisible({
timeout: 5_000,
});
const card = page
.locator(".files-page-card:not(.is-folder)")
@@ -505,10 +451,8 @@ test.describe("Files page screenshots", () => {
{ id: "alpha", name: "alpha.pdf", remoteStorageId: null },
]);
await page.goto("/files", { waitUntil: "domcontentloaded" });
await expect(
page.locator(".files-page-card:not(.files-page-skeleton-card)").first(),
).toBeVisible({
timeout: 10_000,
await expect(page.locator(".files-page-card").first()).toBeVisible({
timeout: 5_000,
});
await page
.locator(".files-page-card:not(.is-folder)")
@@ -528,10 +472,8 @@ test.describe("Files page screenshots", () => {
{ id: "alpha", name: "alpha.pdf", remoteStorageId: null },
]);
await page.goto("/files", { waitUntil: "domcontentloaded" });
await expect(
page.locator(".files-page-card:not(.files-page-skeleton-card)").first(),
).toBeVisible({
timeout: 10_000,
await expect(page.locator(".files-page-card").first()).toBeVisible({
timeout: 5_000,
});
await page
.locator(".files-page-card:not(.is-folder)")
@@ -603,10 +545,8 @@ test.describe("Files page screenshots", () => {
]);
await page.setViewportSize({ width: 500, height: 900 });
await page.goto("/files", { waitUntil: "domcontentloaded" });
await expect(
page.locator(".files-page-card:not(.files-page-skeleton-card)").first(),
).toBeVisible({
timeout: 10_000,
await expect(page.locator(".files-page-card").first()).toBeVisible({
timeout: 5_000,
});
await settle(page);
await page.screenshot({ path: shotPath("10_subtoolbar_phone_hidden") });
@@ -1,6 +1,5 @@
import { test, expect } from "@app/tests/helpers/stub-test-base";
import type { Page, Route } from "@playwright/test";
import { DATABASE_CONFIGS } from "@app/services/indexedDBManager";
/** Stubbed coverage for the /files page UI invariants. */
@@ -35,70 +34,63 @@ async function seedFiles(page: Page, files: SeedFile[]): Promise<void> {
await page.route("**/api/v1/storage/files", (route: Route) =>
route.fulfill({ json: serverFiles }),
);
await page.addInitScript(
({ records, dbVersion }) => {
const open = window.indexedDB.open("stirling-pdf-files", dbVersion);
open.onupgradeneeded = (event) => {
const db = (event.target as IDBOpenDBRequest).result;
// Create both `files` and `folders` stores on this DB.
if (!db.objectStoreNames.contains("files")) {
const store = db.createObjectStore("files", { keyPath: "id" });
store.createIndex("name", "name", { unique: false });
store.createIndex("folderId", "folderId", { unique: false });
store.createIndex("originalFileId", "originalFileId", {
unique: false,
});
}
if (!db.objectStoreNames.contains("folders")) {
const fStore = db.createObjectStore("folders", { keyPath: "id" });
fStore.createIndex("parentFolderId", "parentFolderId", {
unique: false,
});
fStore.createIndex("name", "name", { unique: false });
}
};
open.onsuccess = () => {
const db = open.result;
// Yield the connection if the app ever needs to upgrade, and drop it
// once the writes commit, so the seed never blocks the app's open.
db.onversionchange = () => db.close();
const tx = db.transaction("files", "readwrite");
const store = tx.objectStore("files");
const now = Date.now();
for (const f of records) {
store.put({
id: f.id,
fileId: f.id,
quickKey: f.id,
name: f.name,
type: "application/pdf",
size: 1024,
lastModified: now,
createdAt: now,
// Placeholder; opening would need real bytes.
data: new ArrayBuffer(8),
thumbnail: null,
isLeaf: true,
versionNumber: f.versionNumber ?? 1,
originalFileId: f.id,
parentFileId: null,
toolHistory: f.toolHistory ?? [],
folderId: null,
remoteStorageId: f.remoteStorageId,
remoteStorageUpdatedAt: f.remoteStorageId ? now : null,
remoteOwnerUsername: f.remoteStorageId ? "testuser" : null,
remoteOwnedByCurrentUser: f.remoteStorageId ? true : null,
remoteAccessRole: f.remoteStorageId ? "owner" : null,
remoteSharedViaLink: false,
remoteHasShareLinks: false,
remoteShareToken: null,
});
}
tx.oncomplete = () => db.close();
};
},
{ records: files, dbVersion: DATABASE_CONFIGS.FILES.version },
);
await page.addInitScript((records) => {
const open = window.indexedDB.open("stirling-pdf-files", 4);
open.onupgradeneeded = (event) => {
const db = (event.target as IDBOpenDBRequest).result;
// Create both `files` and `folders` stores on this DB.
if (!db.objectStoreNames.contains("files")) {
const store = db.createObjectStore("files", { keyPath: "id" });
store.createIndex("name", "name", { unique: false });
store.createIndex("folderId", "folderId", { unique: false });
store.createIndex("originalFileId", "originalFileId", {
unique: false,
});
}
if (!db.objectStoreNames.contains("folders")) {
const fStore = db.createObjectStore("folders", { keyPath: "id" });
fStore.createIndex("parentFolderId", "parentFolderId", {
unique: false,
});
fStore.createIndex("name", "name", { unique: false });
}
};
open.onsuccess = () => {
const db = open.result;
const tx = db.transaction("files", "readwrite");
const store = tx.objectStore("files");
const now = Date.now();
for (const f of records) {
store.put({
id: f.id,
fileId: f.id,
quickKey: f.id,
name: f.name,
type: "application/pdf",
size: 1024,
lastModified: now,
createdAt: now,
// Placeholder; opening would need real bytes.
data: new ArrayBuffer(8),
thumbnail: null,
isLeaf: true,
versionNumber: f.versionNumber ?? 1,
originalFileId: f.id,
parentFileId: null,
toolHistory: f.toolHistory ?? [],
folderId: null,
remoteStorageId: f.remoteStorageId,
remoteStorageUpdatedAt: f.remoteStorageId ? now : null,
remoteOwnerUsername: f.remoteStorageId ? "testuser" : null,
remoteOwnedByCurrentUser: f.remoteStorageId ? true : null,
remoteAccessRole: f.remoteStorageId ? "owner" : null,
remoteSharedViaLink: false,
remoteHasShareLinks: false,
remoteShareToken: null,
});
}
};
}, files);
}
/** Stub the storage + config endpoints hit on mount. */
@@ -128,16 +120,12 @@ async function stubStorageApis(
);
}
/** Navigate to /files and wait for at least one real (non-skeleton) card.
* `.files-page-card` also matches the loading-state skeleton placeholders, and
* their parent grid carries `aria-busy="true"` which intercepts pointer events
* -- so waiting for any `.files-page-card` races the skeleton→real transition
* and causes flaky timeouts on slower CI runners. */
/** Navigate to /files and wait for at least one seeded card. */
async function gotoFilesPage(page: Page): Promise<void> {
await page.goto("/files", { waitUntil: "domcontentloaded" });
await expect(
page.locator(".files-page-card:not(.files-page-skeleton-card)").first(),
).toBeVisible({ timeout: 10_000 });
await expect(page.locator(".files-page-card").first()).toBeVisible({
timeout: 5_000,
});
}
test.describe("Files page", () => {
@@ -104,6 +104,9 @@ test.describe("2. Main Dashboard / Home Page", () => {
await expect(page.getByText("GitHub").first()).toBeVisible({
timeout: 10000,
});
await expect(page.getByText("Accessibility").first()).toBeVisible({
timeout: 10000,
});
const githubLink = page
.locator('a[href*="github.com/Stirling-Tools/Stirling-PDF"]')
@@ -1,71 +0,0 @@
import type { Page, Route } from "@playwright/test";
import { test, expect } from "@app/tests/helpers/stub-test-base";
import {
uploadFiles,
switchToEditorIfViewerMode,
runToolAndWaitForReview,
} from "@app/tests/helpers/ui-helpers";
import path from "path";
import fs from "fs";
// Regression coverage: the merge endpoint used to misroute a PDF into JSZip
// when the Content-Type wasn't an exact `application/pdf`, producing a bogus
// `result.zip` instead of the merged file. The UI fix uses signature-based
// detection - %PDF wins regardless of Content-Type.
const FIXTURES_DIR = path.join(__dirname, "../test-fixtures");
const SAMPLE_PDF = path.join(FIXTURES_DIR, "sample.pdf");
const SAMPLE_PDF_BYTES = fs.readFileSync(SAMPLE_PDF);
async function mockMergeWithContentType(page: Page, contentType: string) {
await page.route("**/api/v1/general/merge-pdfs", (route: Route) =>
route.fulfill({
status: 200,
contentType,
headers: {
"Content-Disposition": 'attachment; filename="merged_unsigned.pdf"',
},
body: SAMPLE_PDF_BYTES,
}),
);
}
async function runMergeAndOpenReview(page: Page) {
await page.goto("/merge");
await uploadFiles(page, [SAMPLE_PDF, SAMPLE_PDF]);
await switchToEditorIfViewerMode(page);
await runToolAndWaitForReview(page);
}
test.describe("Merge multi-file response detection", () => {
test('"application/pdf;charset=UTF-8" -> merged PDF, not result.zip', async ({
page,
}) => {
await mockMergeWithContentType(page, "application/pdf;charset=UTF-8");
await runMergeAndOpenReview(page);
const review = page.locator('[data-testid="review-panel-container"]');
await expect(review).toBeVisible();
await expect(review.getByText(/result\.zip/i)).toHaveCount(0);
});
test('"application/octet-stream" -> merged PDF, not result.zip', async ({
page,
}) => {
await mockMergeWithContentType(page, "application/octet-stream");
await runMergeAndOpenReview(page);
const review = page.locator('[data-testid="review-panel-container"]');
await expect(review).toBeVisible();
await expect(review.getByText(/result\.zip/i)).toHaveCount(0);
});
test('"APPLICATION/PDF" -> merged PDF, not result.zip', async ({ page }) => {
await mockMergeWithContentType(page, "APPLICATION/PDF");
await runMergeAndOpenReview(page);
const review = page.locator('[data-testid="review-panel-container"]');
await expect(review).toBeVisible();
await expect(review.getByText(/result\.zip/i)).toHaveCount(0);
});
});
@@ -1,285 +0,0 @@
%PDF-1.3
%âãÏÓ
1 0 obj
<<
/PageMode /UseNone
/Pages 2 0 R
/Type /Catalog
>>
endobj
2 0 obj
<<
/Count 3
/Kids [ 3 0 R 8 0 R 10 0 R ]
/Type /Pages
>>
endobj
3 0 obj
<<
/Contents 4 0 R
/MediaBox [ 0 0 612 792 ]
/Parent 2 0 R
/Resources <<
/Font 5 0 R
/ProcSet [ /PDF /Text /ImageB /ImageC /ImageI ]
>>
/Rotate 0
/Trans <<
>>
/Type /Page
/Annots [ 13 0 R 14 0 R 15 0 R 16 0 R ]
>>
endobj
4 0 obj
<<
/Filter [ /ASCII85Decode /FlateDecode ]
/Length 202
>>
stream
Gasc=3tHos'F!Ec?ZAOh&UQ#o*6#tZi,D1%Q)C=AR/[+f8<JTCd[L^oq9HYV@35sY;ZS=WF!6VJQ_5ac^fR&Z)fc6WqHQo8:H>tCS[9WW$NBF!'qbR)!j@'#^38Q_"QI*7quN4(FLQ.GdUWCN)r43J.(@;D;^Xe(<A1$Dd`Bh2V5hZ/[TM[fF!p8pg)-skh$`ZZ=bp)N~>
endstream
endobj
5 0 obj
<<
/F1 6 0 R
/F2 7 0 R
>>
endobj
6 0 obj
<<
/BaseFont /Helvetica
/Encoding /WinAnsiEncoding
/Name /F1
/Subtype /Type1
/Type /Font
>>
endobj
7 0 obj
<<
/BaseFont /Helvetica-Bold
/Encoding /WinAnsiEncoding
/Name /F2
/Subtype /Type1
/Type /Font
>>
endobj
8 0 obj
<<
/Contents 9 0 R
/MediaBox [ 0 0 612 792 ]
/Parent 2 0 R
/Resources <<
/Font 5 0 R
/ProcSet [ /PDF /Text /ImageB /ImageC /ImageI ]
>>
/Rotate 0
/Trans <<
>>
/Type /Page
/Annots [ 17 0 R 18 0 R 19 0 R 20 0 R ]
>>
endobj
9 0 obj
<<
/Filter [ /ASCII85Decode /FlateDecode ]
/Length 202
>>
stream
Gasc=3tHos'F!Ec?ZAOh&UQ#o*6#tZi,D1%Q)C=AR/[+f8<JTCd[L^oq9HYV@35sY;ZS=WF!6VJQ_5ac^fR&Z)fc6WqHQo8:H>tCS[9WW$NBF!'p&Ik"^_0&I-o!H#fM'Mp]E;/k\f2lV9&f&2nGEs;/VRhVG;T/Wa7sfV3.NC93%2=D6_;Vk>'SkZnYb_],0<?>V]=U~>
endstream
endobj
10 0 obj
<<
/Contents 11 0 R
/MediaBox [ 0 0 612 792 ]
/Parent 2 0 R
/Resources <<
/Font 5 0 R
/ProcSet [ /PDF /Text /ImageB /ImageC /ImageI ]
>>
/Rotate 0
/Trans <<
>>
/Type /Page
/Annots [ 21 0 R 22 0 R 23 0 R 24 0 R ]
>>
endobj
11 0 obj
<<
/Filter [ /ASCII85Decode /FlateDecode ]
/Length 204
>>
stream
Gasc=3tHos'F!Ec?ZAOh&UOmO*6#tZi,D1%Q%p2kM<Y&$KbR[G+hd,ZP4.1!&GFN@589262J3(_E!;-:(js/V]ci`8[*L%Pacr!ifLe4,XPdH(FbqLH^VHllT<B7q$%ZV7#JWds)r7XNZ8-\*rC/`p36EY?AEMsNWLjQ3^GL-+@&[muU+M]ll.j[t]/E-ZJ+phW!aaY^rr~>
endstream
endobj
12 0 obj
<<
/Author (anonymous)
/CreationDate (D\07220260601133935\05301\04700\047)
/Creator (ReportLab PDF Library \055 www\056reportlab\056com)
/Keywords ()
/ModDate (D\07220260601133935\05301\04700\047)
/Producer (ReportLab PDF Library \055 www\056reportlab\056com)
/Subject (unspecified)
/Title (untitled)
/Trapped /False
>>
endobj
13 0 obj
<<
/Subtype /Text
/Rect [ 100 286 116 308 ]
/Contents (Annotation D on page 1)
/Open false
/Flags 0
/P 3 0 R
>>
endobj
14 0 obj
<<
/Subtype /Text
/Rect [ 380 686 396 708 ]
/Contents (Annotation B on page 1)
/Open false
/Flags 0
/P 3 0 R
>>
endobj
15 0 obj
<<
/Subtype /Text
/Rect [ 100 486 116 508 ]
/Contents (Annotation C on page 1)
/Open false
/Flags 0
/P 3 0 R
>>
endobj
16 0 obj
<<
/Subtype /Text
/Rect [ 100 686 116 708 ]
/Contents (Annotation A on page 1)
/Open false
/Flags 0
/P 3 0 R
>>
endobj
17 0 obj
<<
/Subtype /Text
/Rect [ 100 286 116 308 ]
/Contents (Annotation D on page 2)
/Open false
/Flags 0
/P 8 0 R
>>
endobj
18 0 obj
<<
/Subtype /Text
/Rect [ 380 686 396 708 ]
/Contents (Annotation B on page 2)
/Open false
/Flags 0
/P 8 0 R
>>
endobj
19 0 obj
<<
/Subtype /Text
/Rect [ 100 486 116 508 ]
/Contents (Annotation C on page 2)
/Open false
/Flags 0
/P 8 0 R
>>
endobj
20 0 obj
<<
/Subtype /Text
/Rect [ 100 686 116 708 ]
/Contents (Annotation A on page 2)
/Open false
/Flags 0
/P 8 0 R
>>
endobj
21 0 obj
<<
/Subtype /Text
/Rect [ 100 286 116 308 ]
/Contents (Annotation D on page 3)
/Open false
/Flags 0
/P 10 0 R
>>
endobj
22 0 obj
<<
/Subtype /Text
/Rect [ 380 686 396 708 ]
/Contents (Annotation B on page 3)
/Open false
/Flags 0
/P 10 0 R
>>
endobj
23 0 obj
<<
/Subtype /Text
/Rect [ 100 486 116 508 ]
/Contents (Annotation C on page 3)
/Open false
/Flags 0
/P 10 0 R
>>
endobj
24 0 obj
<<
/Subtype /Text
/Rect [ 100 686 116 708 ]
/Contents (Annotation A on page 3)
/Open false
/Flags 0
/P 10 0 R
>>
endobj
xref
0 25
0000000000 65535 f
0000000015 00000 n
0000000083 00000 n
0000000155 00000 n
0000000384 00000 n
0000000677 00000 n
0000000718 00000 n
0000000825 00000 n
0000000937 00000 n
0000001166 00000 n
0000001459 00000 n
0000001690 00000 n
0000001986 00000 n
0000002322 00000 n
0000002450 00000 n
0000002578 00000 n
0000002706 00000 n
0000002834 00000 n
0000002962 00000 n
0000003090 00000 n
0000003218 00000 n
0000003346 00000 n
0000003475 00000 n
0000003604 00000 n
0000003733 00000 n
trailer
<<
/Size 25
/Root 1 0 R
/Info 12 0 R
/ID [ <f0cdd00ba65dc098aa8b749db481bf6a> <f0cdd00ba65dc098aa8b749db481bf6a> ]
>>
startxref
3862
%%EOF

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