Skip to content

added service worket to set COOP AND COEP headers#2

Merged
airen1986 merged 4 commits intomainfrom
feature/pr-setup
Mar 11, 2026
Merged

added service worket to set COOP AND COEP headers#2
airen1986 merged 4 commits intomainfrom
feature/pr-setup

Conversation

@airen1986
Copy link
Owner

@airen1986 airen1986 commented Mar 11, 2026

Summary by CodeRabbit

  • New Features
    • Adds a best-effort service worker that injects cross-origin isolation headers for same-origin requests to improve resource loading and security.
    • Service worker registration is non-blocking—attempted at startup, tolerates failures, and will refresh when needed so the app remains functional if isolation cannot be established.

@coderabbitai
Copy link

coderabbitai bot commented Mar 11, 2026

Warning

Rate limit exceeded

@airen1986 has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 4 minutes and 7 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 016721ca-c1ae-433e-82d3-6923dea3c2a0

📥 Commits

Reviewing files that changed from the base of the PR and between f2eb940 and e0f3e50.

📒 Files selected for processing (1)
  • src/page_assets/index/js/main.js
📝 Walkthrough

Walkthrough

Adds a best-effort Cross-Origin-Isolation shim: a service worker at /sw-coi.js that injects missing COOP/COEP/CORP headers into same-origin GET responses, and registration logic in the app startup that attempts to register the worker and continues if registration fails.

Changes

Cohort / File(s) Summary
Service Worker Registration
src/page_assets/index/js/main.js
Adds registerCoiServiceWorker() to register /sw-coi.js at root scope, await readiness, reload if not cross-origin isolated, and call it before init(). Registration failures are ignored.
COI Header Injection Service Worker
src/public/sw-coi.js
New file: service worker implements install (skipWaiting), activate (clients.claim), and fetch handler that proxies same-origin GET responses and injects missing Cross-Origin-Opener-Policy: same-origin, Cross-Origin-Embedder-Policy: require-corp, and Cross-Origin-Resource-Policy: same-origin headers; skips opaque responses and returns 503 on network errors.
Lint globals
eslint.config.js
Adds Response as a readonly global in ESLint configuration languageOptions.globals.

Sequence Diagram

sequenceDiagram
    participant Browser as Browser/App
    participant SW as COI Service Worker
    participant Network as Network

    Browser->>SW: register('/sw-coi.js', {scope: '/'})
    SW-->>Browser: registration ready
    Browser->>Browser: check cross-origin isolation
    alt not cross-origin isolated
        Browser->>Browser: reload page
    end

    Browser->>Network: GET (same-origin)
    Network-->>SW: fetch intercepted
    SW->>Network: fetch original request
    Network-->>SW: original Response
    SW->>SW: proxy response, inject COOP/COEP/CORP if missing
    SW-->>Browser: modified Response
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Poem

🐰 I hopped in code with nimble paws,
A tiny worker fixing laws,
I patch the headers, snug and tight,
So origins sleep safe at night,
Hop, deploy — we did it right! 🥕

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title contains a typo ('worket' instead of 'worker') and is slightly vague about the full scope of changes, but it does accurately describe the main purpose of adding a service worker to set COOP and COEP headers.

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

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch feature/pr-setup

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.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

🧹 Nitpick comments (2)
src/public/sw-coi.js (1)

29-36: Consider adding error handling for network failures.

If fetch(request) throws (e.g., network offline), the error propagates up and the service worker fails the request. While this is standard behavior, you may want explicit error handling to fall back gracefully or provide clearer diagnostics.

💡 Optional: Add try-catch for network errors
   event.respondWith(
     (async () => {
-      const networkResponse = await fetch(request);
+      let networkResponse;
+      try {
+        networkResponse = await fetch(request);
+      } catch {
+        // Network error - let the browser handle it normally
+        return fetch(request);
+      }

       // Do not attempt to rewrite opaque or redirected responses.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/public/sw-coi.js` around lines 29 - 36, Wrap the fetch(request) call
inside the async handler passed to event.respondWith in a try-catch so network
failures are handled explicitly: catch exceptions from fetch(request) and return
a fallback Response or a cached response (or a descriptive error Response)
instead of letting the error bubble; update the logic around networkResponse
(the variable returned by fetch) so the opaque/opaqueredirect check only runs
when networkResponse was obtained successfully and ensure the catch block logs
or reports the error for diagnostics.
src/page_assets/index/js/main.js (1)

18-20: Consider auto-reload strategy for first-visit COI activation.

registerCoiServiceWorker() is called without await, and init() runs immediately. This is fine for startup performance, but there's a timing consideration: service workers cannot intercept the navigation that registered them, so crossOriginIsolated won't be true until the next page load.

On first visit in production (without server-side headers from vite), OPFS will be unavailable until the user refreshes. If guaranteed COI on first visit is needed, consider checking and reloading:

💡 Auto-reload pattern for first-visit COI
 async function registerCoiServiceWorker() {
 	if (!('serviceWorker' in navigator)) return;
+	
+	// Already isolated - no need to register shim
+	if (window.crossOriginIsolated) return;

 	try {
 		await navigator.serviceWorker.register('/sw-coi.js', { scope: '/' });
 		await navigator.serviceWorker.ready;
+		// SW active but page loaded without COI headers - reload to apply
+		if (!window.crossOriginIsolated) {
+			window.location.reload();
+		}
 	} catch {
 		// Ignore registration failures; app can still run without SW header shim.
 	}
 }

 // Start the app
-registerCoiServiceWorker();
-init();
+registerCoiServiceWorker().then(() => init());

Note: If the current "best-effort" behavior is intentional (avoiding surprise reloads), the existing implementation is acceptable—just be aware OPFS won't work on first visit without server-side headers.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/page_assets/index/js/main.js` around lines 18 - 20, The app currently
calls registerCoiServiceWorker() without awaiting and immediately runs init(),
which means crossOriginIsolated may not be true on first visit; update the
startup in main.js to wait for the COI registration/activation result from
registerCoiServiceWorker() (or have it return a status/promise), then check
crossOriginIsolated and, if registration succeeded but crossOriginIsolated is
still false, trigger a single reload to let the newly-active COI headers take
effect before calling init(); use the existing registerCoiServiceWorker() return
value and the crossOriginIsolated global to decide whether to reload once, then
call init() after reload or when COI is active.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@src/page_assets/index/js/main.js`:
- Around line 18-20: The app currently calls registerCoiServiceWorker() without
awaiting and immediately runs init(), which means crossOriginIsolated may not be
true on first visit; update the startup in main.js to wait for the COI
registration/activation result from registerCoiServiceWorker() (or have it
return a status/promise), then check crossOriginIsolated and, if registration
succeeded but crossOriginIsolated is still false, trigger a single reload to let
the newly-active COI headers take effect before calling init(); use the existing
registerCoiServiceWorker() return value and the crossOriginIsolated global to
decide whether to reload once, then call init() after reload or when COI is
active.

In `@src/public/sw-coi.js`:
- Around line 29-36: Wrap the fetch(request) call inside the async handler
passed to event.respondWith in a try-catch so network failures are handled
explicitly: catch exceptions from fetch(request) and return a fallback Response
or a cached response (or a descriptive error Response) instead of letting the
error bubble; update the logic around networkResponse (the variable returned by
fetch) so the opaque/opaqueredirect check only runs when networkResponse was
obtained successfully and ensure the catch block logs or reports the error for
diagnostics.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 46665dab-248e-4631-8253-c4c554ba8d4a

📥 Commits

Reviewing files that changed from the base of the PR and between e3d0935 and e1b8a05.

📒 Files selected for processing (2)
  • src/page_assets/index/js/main.js
  • src/public/sw-coi.js

@airen1986 airen1986 self-assigned this Mar 11, 2026
@airen1986
Copy link
Owner Author

add serviceworkers

@airen1986 airen1986 closed this Mar 11, 2026
@airen1986 airen1986 reopened this Mar 11, 2026
@airen1986 airen1986 merged commit 97e770a into main Mar 11, 2026
3 checks passed
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