|
| 1 | +/** |
| 2 | + * @fileoverview Authentication Service Worker (Development Version) |
| 3 | + * Intercepts /api/view requests and rewrites them to a configurable base URL with auth token. |
| 4 | + * Required for browser-native requests (img, video, audio) that cannot send custom headers. |
| 5 | + * This version is used in development to proxy requests to staging/test environments. |
| 6 | + * Default base URL: https://testcloud.comfy.org (configurable via SET_BASE_URL message) |
| 7 | + */ |
| 8 | + |
| 9 | +/** |
| 10 | + * @typedef {Object} AuthHeader |
| 11 | + * @property {string} Authorization - Bearer token for authentication |
| 12 | + */ |
| 13 | + |
| 14 | +/** |
| 15 | + * @typedef {Object} CachedAuth |
| 16 | + * @property {AuthHeader|null} header |
| 17 | + * @property {number} expiresAt - Timestamp when cache expires |
| 18 | + */ |
| 19 | + |
| 20 | +const CACHE_TTL_MS = 50 * 60 * 1000 // 50 minutes (Firebase tokens expire in 1 hour) |
| 21 | + |
| 22 | +/** @type {CachedAuth|null} */ |
| 23 | +let authCache = null |
| 24 | + |
| 25 | +/** @type {Promise<AuthHeader|null>|null} */ |
| 26 | +let authRequestInFlight = null |
| 27 | + |
| 28 | +/** @type {string} */ |
| 29 | +let baseUrl = 'https://testcloud.comfy.org' |
| 30 | + |
| 31 | +self.addEventListener('message', (event) => { |
| 32 | + if (event.data.type === 'INVALIDATE_AUTH_HEADER') { |
| 33 | + authCache = null |
| 34 | + authRequestInFlight = null |
| 35 | + } |
| 36 | + |
| 37 | + if (event.data.type === 'SET_BASE_URL') { |
| 38 | + baseUrl = event.data.baseUrl |
| 39 | + console.log('[Auth DEV SW] Base URL set to:', baseUrl) |
| 40 | + } |
| 41 | +}) |
| 42 | + |
| 43 | +self.addEventListener('fetch', (event) => { |
| 44 | + const url = new URL(event.request.url) |
| 45 | + |
| 46 | + if ( |
| 47 | + !url.pathname.startsWith('/api/view') && |
| 48 | + !url.pathname.startsWith('/api/viewvideo') |
| 49 | + ) { |
| 50 | + return |
| 51 | + } |
| 52 | + |
| 53 | + event.respondWith( |
| 54 | + (async () => { |
| 55 | + try { |
| 56 | + // Rewrite URL to use configured base URL (default: stagingcloud.comfy.org) |
| 57 | + const originalUrl = new URL(event.request.url) |
| 58 | + const rewrittenUrl = new URL( |
| 59 | + originalUrl.pathname + originalUrl.search, |
| 60 | + baseUrl |
| 61 | + ) |
| 62 | + |
| 63 | + const authHeader = await getAuthHeader() |
| 64 | + |
| 65 | + // With mode: 'no-cors', Authorization headers are stripped by the browser |
| 66 | + // So we add the token to the URL as a query parameter instead |
| 67 | + if (authHeader && authHeader.Authorization) { |
| 68 | + const token = authHeader.Authorization.replace('Bearer ', '') |
| 69 | + rewrittenUrl.searchParams.set('token', token) |
| 70 | + } |
| 71 | + |
| 72 | + // Cross-origin request requires no-cors mode |
| 73 | + // - mode: 'no-cors' allows cross-origin fetches without CORS headers |
| 74 | + // - Returns opaque response, which works fine for images/videos/audio |
| 75 | + // - Auth token is sent via query parameter since headers are stripped in no-cors mode |
| 76 | + // - Server may return redirect to GCS, which will be followed automatically |
| 77 | + return fetch(rewrittenUrl, { |
| 78 | + method: 'GET', |
| 79 | + redirect: 'follow', |
| 80 | + mode: 'no-cors' |
| 81 | + }) |
| 82 | + } catch (error) { |
| 83 | + console.error('[Auth DEV SW] Request failed:', error) |
| 84 | + const originalUrl = new URL(event.request.url) |
| 85 | + const rewrittenUrl = new URL( |
| 86 | + originalUrl.pathname + originalUrl.search, |
| 87 | + baseUrl |
| 88 | + ) |
| 89 | + return fetch(rewrittenUrl, { |
| 90 | + mode: 'no-cors', |
| 91 | + redirect: 'follow' |
| 92 | + }) |
| 93 | + } |
| 94 | + })() |
| 95 | + ) |
| 96 | +}) |
| 97 | + |
| 98 | +/** |
| 99 | + * Gets auth header from cache or requests from main thread |
| 100 | + * @returns {Promise<AuthHeader|null>} |
| 101 | + */ |
| 102 | +async function getAuthHeader() { |
| 103 | + // Return cached value if valid |
| 104 | + if (authCache && authCache.expiresAt > Date.now()) { |
| 105 | + return authCache.header |
| 106 | + } |
| 107 | + |
| 108 | + // Clear expired cache |
| 109 | + if (authCache) { |
| 110 | + authCache = null |
| 111 | + } |
| 112 | + |
| 113 | + // Deduplicate concurrent requests |
| 114 | + if (authRequestInFlight) { |
| 115 | + return authRequestInFlight |
| 116 | + } |
| 117 | + |
| 118 | + authRequestInFlight = requestAuthHeaderFromMainThread() |
| 119 | + const header = await authRequestInFlight |
| 120 | + authRequestInFlight = null |
| 121 | + |
| 122 | + // Cache the result |
| 123 | + if (header) { |
| 124 | + authCache = { |
| 125 | + header, |
| 126 | + expiresAt: Date.now() + CACHE_TTL_MS |
| 127 | + } |
| 128 | + } |
| 129 | + |
| 130 | + return header |
| 131 | +} |
| 132 | + |
| 133 | +/** |
| 134 | + * Requests auth header from main thread via MessageChannel |
| 135 | + * @returns {Promise<AuthHeader|null>} |
| 136 | + */ |
| 137 | +async function requestAuthHeaderFromMainThread() { |
| 138 | + const clients = await self.clients.matchAll() |
| 139 | + if (clients.length === 0) { |
| 140 | + return null |
| 141 | + } |
| 142 | + |
| 143 | + const messageChannel = new MessageChannel() |
| 144 | + |
| 145 | + return new Promise((resolve) => { |
| 146 | + let timeoutId |
| 147 | + |
| 148 | + messageChannel.port1.onmessage = (event) => { |
| 149 | + clearTimeout(timeoutId) |
| 150 | + resolve(event.data.authHeader) |
| 151 | + } |
| 152 | + |
| 153 | + timeoutId = setTimeout(() => { |
| 154 | + console.error( |
| 155 | + '[Auth DEV SW] Timeout waiting for auth header from main thread' |
| 156 | + ) |
| 157 | + resolve(null) |
| 158 | + }, 1000) |
| 159 | + |
| 160 | + clients[0].postMessage({ type: 'REQUEST_AUTH_HEADER' }, [ |
| 161 | + messageChannel.port2 |
| 162 | + ]) |
| 163 | + }) |
| 164 | +} |
| 165 | + |
| 166 | +self.addEventListener('activate', (event) => { |
| 167 | + event.waitUntil(self.clients.claim()) |
| 168 | +}) |
0 commit comments