Skip to content

fix: restrict service worker scope to Mainsail routes - #2524

Open
jothan wants to merge 2 commits into
mainsail-crew:developfrom
jothan:sw-scope
Open

fix: restrict service worker scope to Mainsail routes#2524
jothan wants to merge 2 commits into
mainsail-crew:developfrom
jothan:sw-scope

Conversation

@jothan

@jothan jothan commented Jun 11, 2026

Copy link
Copy Markdown

Description

This patch makes sure the service worker only handles requests directed towards Mainsail.

Core issue:

Without being logged in, my authelia setup redirects the Mainsail URL to the login page:

https://kepler.x2a.org/ 302 found -> https://kepler.x2a.org/authelia?rd=https%3A%2F%2Fkepler.x2a.org%2F

The service worker would cache the login page with the root URL as its path. After login, being redirected back to the root url I would get a grey Authelia page coming out of the Mainsail service worker instead of getting the Mainsail UI.

The approach taken is two-pronged:

  • Make sure non-Mainsail requests are sent to the server directly (accessing /spoolman without a refresh tends to serve the mainsail UI).
  • Avoid caching redirects (a 302 can be passed as code 200 if the destination URL returns 200). Testing revealed that simply using CacheableResponsePlugin was not enough to prevent this behavior.

Starting from an empty / clean state, I have manually confirmed that redirected URLs are not cached by the WebWorker. It might be required to manually clear caches after applying this patch to get the full benefits. My phone browser ended up in this weird state and through remote chrome debugging, I was able to finally confirm that I was hitting an old cache (this is why this PR stayed a draft for a couple of days).

Related Tickets & Documents

None found

Mobile & Desktop Screenshots/Recordings

Not a visual change.

[optional] Are there any post-deployment tasks we need to perform?

🤖 This Pull Request was created with the help of brain.

@jothan
jothan force-pushed the sw-scope branch 3 times, most recently from cf3302d to ded7780 Compare June 11, 2026 04:02
@jothan jothan changed the title feat: restrict service worker scope to Mainsail routes fix: restrict service worker scope to Mainsail routes Jun 11, 2026
@jothan
jothan marked this pull request as ready for review June 18, 2026 03:01
@coderabbitai

coderabbitai Bot commented Jun 18, 2026

Copy link
Copy Markdown

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: b2d580a5-8419-4134-9aa7-48c12a0f44ee

📥 Commits

Reviewing files that changed from the base of the PR and between d78ae11 and befbfe1.

📒 Files selected for processing (1)
  • vite.config.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • vite.config.ts

📝 Walkthrough

Walkthrough

The Vite PWA Workbox configuration in vite.config.ts receives two additions: a navigateFallbackAllowlist array of regexes restricting SPA navigation fallback to specific app routes and /, and a cacheWillUpdate plugin on the /config.json runtime cache entry that returns null for absent or redirected responses.

Changes

PWA Service Worker Configuration

Layer / File(s) Summary
Navigation fallback allowlist
vite.config.ts
Introduces navigateFallbackAllowlist in the Workbox config so the service worker navigation fallback applies only to declared app paths and /.
/config.json cache update guard
vite.config.ts
Adds a plugins entry with a cacheWillUpdate hook that skips caching when the response is missing or a redirect, preventing bad responses from polluting the runtime cache.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~5 minutes

Poem

A bunny hopped through routes one day,
Only the right paths could enter, hooray! 🐇
And /config.json? No sneaky redirect shall stay,
null is returned if you misbehave.
The cache is tidy, the PWA brave! 🌟

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately describes the main change: restricting service worker scope to Mainsail routes, which matches the core objective of preventing cache poisoning from non-Mainsail requests.
Description check ✅ Passed The description is directly related to the changeset, explaining the cache poisoning issue with Authelia redirects and the two-pronged approach implemented to fix it.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (2)
vite.config.ts (2)

53-55: 💤 Low value

Consider adding a comment to document the allowlisted routes.

The regex pattern correctly restricts the service worker's navigation fallback to specific Mainsail routes, but a brief comment explaining that these are the app's client-side routes would improve maintainability.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@vite.config.ts` around lines 53 - 55, The navigateFallbackAllowlist
configuration lacks documentation explaining its purpose and the routes it
covers. Add a brief comment above the navigateFallbackAllowlist property (or on
the same line) to document that the regex pattern restricts the service worker's
navigation fallback to specific Mainsail client-side routes such as allPrinters,
cam, console, heightmap, files, viewer, history, timelapse, config, and
settings, along with their sub-routes. This will improve maintainability and
help future developers understand why these specific routes are allowlisted.

66-73: Replace new Function() with a standard arrow function for better type safety and adherence to documented patterns.

The new Function() with as any type assertion is not the documented pattern for vite-plugin-pwa. Official Workbox and vite-plugin-pwa documentation uses a standard arrow function:

plugins: [
    {
        cacheWillUpdate: async ({ response }) => {
            return response && !response.redirected ? response : null
        },
    },
],

This approach provides proper TypeScript typing, improves readability, and follows the pattern used in all official examples.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@vite.config.ts` around lines 66 - 73, The cacheWillUpdate property in the
plugins configuration is using the new Function() constructor with an as any
type assertion instead of the documented pattern, which reduces type safety and
readability. Replace this with a standard async arrow function that directly
takes the destructured response parameter and returns the conditional result.
This will provide proper TypeScript typing without type assertions and follow
the official vite-plugin-pwa and Workbox documentation patterns.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@vite.config.ts`:
- Around line 53-55: The navigateFallbackAllowlist configuration lacks
documentation explaining its purpose and the routes it covers. Add a brief
comment above the navigateFallbackAllowlist property (or on the same line) to
document that the regex pattern restricts the service worker's navigation
fallback to specific Mainsail client-side routes such as allPrinters, cam,
console, heightmap, files, viewer, history, timelapse, config, and settings,
along with their sub-routes. This will improve maintainability and help future
developers understand why these specific routes are allowlisted.
- Around line 66-73: The cacheWillUpdate property in the plugins configuration
is using the new Function() constructor with an as any type assertion instead of
the documented pattern, which reduces type safety and readability. Replace this
with a standard async arrow function that directly takes the destructured
response parameter and returns the conditional result. This will provide proper
TypeScript typing without type assertions and follow the official
vite-plugin-pwa and Workbox documentation patterns.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 3086560a-07c7-4df1-84bb-280abc9f98a2

📥 Commits

Reviewing files that changed from the base of the PR and between f21548a and d78ae11.

📒 Files selected for processing (1)
  • vite.config.ts

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant