A free and open source instant messaging and VoIP chat app built for friends, groups, and communities.
feat(app): verify chunks and refetch corrupted ones (#3721)
Hampusc687470367ad
diff --git a/fluxer_app/index.html b/fluxer_app/index.htmlindex 9da9379fa..76ff88eb4 100644--- a/fluxer_app/index.html+++ b/fluxer_app/index.html@@ -27,6 +27,7 @@<script data-cfasync="false" nonce="{{CSP_NONCE_PLACEHOLDER}}">(function(){try{var t=localStorage.getItem('theme');if(t){document.documentElement.classList.add('theme-'+t)}}catch{}})()</script><script data-cfasync="false" nonce="{{CSP_NONCE_PLACEHOLDER}}">(function(){try{var z=localStorage.getItem('fluxer:accessibility:zoom-preboot');if(z){var p=parseInt(z,10);if(p>=50&&p<=200){document.documentElement.style.setProperty('--custom-zoom',String(p))}}}catch{}})()</script><script data-cfasync="false" nonce="{{CSP_NONCE_PLACEHOLDER}}">(function(){try{if(window.electron||typeof WebSocket!=='function'||typeof fetch!=='function')return;var P=location.pathname;if(P==='/'||P.indexOf('/migrate/')===0||P.indexOf('/oauth2/')===0)return;var LS=localStorage;if(LS.getItem('fluxer:gateway:preboot:session')!=='1')return;var h=JSON.parse(LS.getItem('fluxer:preboot:network')||'null');if(!h||h.v!==1||typeof h.a!=='string'||h.a!==LS.getItem('fluxer:auth:active-account-key'))return;var X={startedAt:Date.now(),discovery:null,gateway:null};window.__FLUXER_PREBOOT_NETWORK__=X;if(typeof h.d==='string'&&/^https?:\/\//.test(h.d)){var r=fetch(h.d,{method:'GET',headers:{Accept:'application/json'},redirect:'error',credentials:'omit',cache:'no-store',referrerPolicy:'no-referrer'});r.catch(function(){});X.discovery={url:h.d,response:r}}if(typeof h.g==='string'&&/^wss?:\/\//.test(h.g)){var u=new URL(h.g);u.searchParams.set('v','1');u.searchParams.set('encoding','json');u.searchParams.set('compress','zstd-stream');u.searchParams.set('stream','1');var ws=new WebSocket(u.toString());ws.binaryType='arraybuffer';var g={url:u.toString(),socket:ws,open:false,messages:[]};ws.onopen=function(){g.open=true};ws.onmessage=function(e){g.messages.push(e)};ws.onclose=ws.onerror=function(){if(X.gateway===g)X.gateway=null};X.gateway=g;setTimeout(function(){if(X.gateway===g){X.gateway=null;try{ws.close(1000,'Preboot gateway unclaimed')}catch(e){}}},30000)}}catch(e){}})()</script>+<script data-cfasync="false" nonce="{{CSP_NONCE_PLACEHOLDER}}">(function(){try{var T={},M=2;function Q(u,n){return u+(u.indexOf('?')<0?'?':'&')+'r='+n+'-'+Math.random().toString(36).slice(2,10)}window.addEventListener('error',function(e){var el=e.target;if(!el||!el.hasAttribute||!el.hasAttribute('data-fluxer-entry')||!el.integrity)return;var tag=el.tagName,at=tag==='SCRIPT'?'src':tag==='LINK'?'href':null;if(!at)return;var o=el.getAttribute('data-fluxer-src')||el.getAttribute(at);if(!o)return;var n=(T[o]||0)+1;if(n>M)return;T[o]=n;try{console.warn('[ChunkIntegrity] A file failed to load or failed its integrity check. Fetching a fresh copy.',o)}catch(x){}var c=document.createElement(tag),i,a;for(i=0;i<el.attributes.length;i++){a=el.attributes[i];c.setAttribute(a.name,a.value)}c.setAttribute('data-fluxer-src',o);c.setAttribute(at,Q(o,n));var go=function(){var p=el.parentNode||document.head;p.insertBefore(c,el.nextSibling);if(el.parentNode)el.parentNode.removeChild(el)};if(typeof fetch==='function'){fetch(o,{cache:'reload',mode:'cors',credentials:'omit',integrity:el.integrity}).then(go,go)}else{go()}},true)}catch(e){}})()</script></head><body><div id="root"></div>diff --git a/fluxer_app/rspack.config.mjs b/fluxer_app/rspack.config.mjsindex 4b552d2b5..c767d3096 100644--- a/fluxer_app/rspack.config.mjs+++ b/fluxer_app/rspack.config.mjs@@ -1,5 +1,6 @@// SPDX-License-Identifier: AGPL-3.0-or-later+import {createHash} from 'node:crypto';import {existsSync, readdirSync} from 'node:fs';import path, {dirname} from 'node:path';import {fileURLToPath} from 'node:url';@@ -9,6 +10,7 @@ import {DefinePlugin,HtmlRspackPlugin,LightningCssMinimizerRspackPlugin,+ SubresourceIntegrityPlugin,SwcJsMinimizerRspackPlugin,sources,} from '@rspack/core';@@ -33,7 +35,7 @@ const BOOT_PRELOAD_FONT_FILES = [];const BOOT_LOW_PRIORITY_FONT_FILES = ['FluxerSans/FluxerSans-Medium.woff2'];const AUTH_ENTRY_DOCUMENT = 'auth-index.html';-const ENTRY_STYLESHEET_LINK_PATTERN = /<link href="([^"]+\.css)" rel="stylesheet">/gu;+const ENTRY_STYLESHEET_LINK_PATTERN = /<link\b(?=[^>]*\brel="stylesheet")[^>]*\bhref="([^"]+\.css)"[^>]*>/gu;const CSS_URL_PATTERN = /url\(\s*['"]?([^'")]+)/gu;const DESKTOP_MODULE_ASSET_SOURCES = [{@@ -149,7 +151,28 @@ function mirrorCacheGroups(groups) {return mirrored;}-function bootPreloadPlugin() {+const ENTRY_RECOVERY_ATTRIBUTE = 'data-fluxer-entry';++function subresourceIntegrity(source) {+ return `sha384-${createHash('sha384').update(source).digest('base64')}`;+}++function entryRecoveryMarkerPlugin() {+ return {+ apply(compiler) {+ compiler.hooks.thisCompilation.tap('EntryRecoveryMarkerPlugin', (compilation) => {+ HtmlRspackPlugin.getCompilationHooks(compilation).alterAssetTags.tap('EntryRecoveryMarkerPlugin', (data) => {+ for (const tag of [...data.assetTags.scripts, ...data.assetTags.styles]) {+ tag.attributes = {...tag.attributes, [ENTRY_RECOVERY_ATTRIBUTE]: ''};+ }+ return data;+ });+ });+ },+ };+}++function bootPreloadPlugin({withIntegrity}) {return {apply(compiler) {compiler.hooks.thisCompilation.tap('BootPreloadPlugin', (compilation) => {@@ -181,13 +204,26 @@ function bootPreloadPlugin() {}}const ordered = [...files];+ const integrityAttributes = (file) => {+ if (!withIntegrity) {+ return '';+ }+ const source = compilation.getAsset(file)?.source.buffer();+ return source == null ? '' : ` crossorigin integrity="${subresourceIntegrity(source)}"`;+ };const links = [...ordered.filter((file) => file.endsWith('.css'))- .map((file) => `<link rel="preload" as="style" fetchpriority="low" href="${base}${file}">`),+ .map(+ (file) =>+ `<link rel="preload" as="style" fetchpriority="low" href="${base}${file}"${integrityAttributes(file)}>`,+ ),...ordered.filter((file) => file.endsWith('.js'))- .map((file) => `<link rel="preload" as="script" fetchpriority="low" href="${base}${file}">`),+ .map(+ (file) =>+ `<link rel="preload" as="script" fetchpriority="low" href="${base}${file}"${integrityAttributes(file)}>`,+ ),].join('');if (links === '') {return;@@ -463,6 +499,7 @@ export default () => {publicPath,workerPublicPath: '/',workerChunkLoading: false,+ crossOriginLoading: isProduction && !isDesktopRenderer ? 'anonymous' : false,filename: jsFilename,chunkFilename: jsFilename,cssFilename: isProduction ? 'assets/[contenthash:16].css' : devCssName,@@ -672,8 +709,12 @@ export default () => {nodeAssertStrictSchemePlugin(),fontPreloadPlugin(),rocketLoaderOptOutPlugin(),- ...(isProduction ? [bootPreloadPlugin()] : []),+ ...(isProduction ? [bootPreloadPlugin({withIntegrity: !isDesktopRenderer})] : []),+ ...(isProduction && !isDesktopRenderer ? [entryRecoveryMarkerPlugin()] : []),...(isProduction && !isDesktopRenderer ? [authEntryDocumentPlugin()] : []),+ ...(isProduction && !isDesktopRenderer+ ? [new SubresourceIntegrityPlugin({hashFuncNames: ['sha384'], enabled: true})]+ : []),new HtmlRspackPlugin({template: path.join(ROOT_DIR, 'index.html'),filename: 'index.html',diff --git a/fluxer_app/src/features/platform/utils/ChunkIntegrityRecovery.ts b/fluxer_app/src/features/platform/utils/ChunkIntegrityRecovery.tsnew file mode 100644index 000000000..c2c4d920b--- /dev/null+++ b/fluxer_app/src/features/platform/utils/ChunkIntegrityRecovery.ts@@ -0,0 +1,109 @@+// SPDX-License-Identifier: AGPL-3.0-or-later++import {Logger} from '@app/features/platform/utils/AppLogger';+import {isBrowserOffline, isLazyModuleLoadError} from '@app/features/platform/utils/LazyModuleLoader';++type ChunkId = string | number;++interface ChunkRuntime {+ e: (chunkId: ChunkId) => Promise<unknown>;+ u: (chunkId: ChunkId) => string;+ k?: (chunkId: ChunkId) => string;+ p: string;+ sriHashes?: Record<string, string>;+ sriCssHashes?: Record<string, string>;+}++declare const __webpack_require__: ChunkRuntime;++const MAX_RECOVERY_ATTEMPTS = 2;++const logger = new Logger('ChunkIntegrity');+const reportedFiles = new Set<string>();+const recoveryAttempts = new Map<string, number>();++let installed = false;++function withRecoveryQuery(url: string, attempt: number): string {+ if (attempt === 0) {+ return url;+ }+ const separator = url.includes('?') ? '&' : '?';+ return `${url}${separator}r=${attempt}-${Math.random().toString(36).slice(2, 10)}`;+}++function reportFailedFile(url: string): void {+ if (reportedFiles.has(url)) {+ return;+ }+ reportedFiles.add(url);+ logger.warn('A file failed to load or failed its integrity check. Fetching a fresh copy.', url);+}++async function refreshCachedCopy(url: string, integrity: string): Promise<void> {+ try {+ const response = await fetch(url, {cache: 'reload', mode: 'cors', credentials: 'omit', integrity});+ await response.arrayBuffer();+ } catch {}+}++function chunkFiles(+ runtime: ChunkRuntime,+ baseJsUrl: ChunkRuntime['u'],+ baseCssUrl: ChunkRuntime['k'],+ chunkId: ChunkId,+) {+ const key = String(chunkId);+ const files: Array<{url: string; integrity: string}> = [];+ const jsIntegrity = runtime.sriHashes?.[key];+ if (jsIntegrity) {+ files.push({url: runtime.p + baseJsUrl(chunkId), integrity: jsIntegrity});+ }+ const cssIntegrity = runtime.sriCssHashes?.[key];+ if (cssIntegrity && baseCssUrl) {+ files.push({url: runtime.p + baseCssUrl(chunkId), integrity: cssIntegrity});+ }+ return files;+}++export function installChunkIntegrityRecovery(): void {+ if (installed || typeof __webpack_require__ === 'undefined') {+ return;+ }+ const runtime = __webpack_require__;+ if (runtime.sriHashes == null) {+ return;+ }+ installed = true;+ const loadChunk = runtime.e;+ const baseJsUrl = runtime.u;+ const baseCssUrl = runtime.k;+ const attemptOf = (chunkId: ChunkId) => recoveryAttempts.get(String(chunkId)) ?? 0;+ runtime.u = (chunkId) => withRecoveryQuery(baseJsUrl(chunkId), attemptOf(chunkId));+ if (baseCssUrl) {+ runtime.k = (chunkId) => withRecoveryQuery(baseCssUrl(chunkId), attemptOf(chunkId));+ }+ runtime.e = async (chunkId) => {+ for (;;) {+ try {+ return await loadChunk(chunkId);+ } catch (error) {+ const attempt = attemptOf(chunkId);+ if (attempt >= MAX_RECOVERY_ATTEMPTS || !isLazyModuleLoadError(error) || isBrowserOffline()) {+ throw error;+ }+ const files = chunkFiles(runtime, baseJsUrl, baseCssUrl, chunkId);+ const request = (error as {request?: unknown}).request;+ if (typeof request === 'string' && request !== '') {+ reportFailedFile(request);+ } else {+ for (const file of files) {+ reportFailedFile(file.url);+ }+ }+ await Promise.all(files.map((file) => refreshCachedCopy(file.url, file.integrity)));+ recoveryAttempts.set(String(chunkId), attempt + 1);+ }+ }+ };+}diff --git a/fluxer_app/src/index.tsx b/fluxer_app/src/index.tsxindex f6e8680dd..2b1f84982 100644--- a/fluxer_app/src/index.tsx+++ b/fluxer_app/src/index.tsx@@ -21,6 +21,7 @@ import {installRuntimeConfigEffects} from '@app/features/app/state/RuntimeConfigimport {captureAccountHandoffFromLocation} from '@app/features/auth/state/AccountHandoffCapture';import {installImageRetention} from '@app/features/messaging/utils/ImageRetention';import {Logger} from '@app/features/platform/utils/AppLogger';+import {installChunkIntegrityRecovery} from '@app/features/platform/utils/ChunkIntegrityRecovery';import {loadLazyModule} from '@app/features/platform/utils/LazyModuleLoader';import {installUnhandledRejectionReporter} from '@app/features/platform/utils/UnhandledRejectionReporter';import {captureCustomCssOffFromLocation} from '@app/features/theme_settings/state/CustomCssOff';@@ -33,6 +34,7 @@ captureAccountHandoffFromLocation();captureCustomCssOffFromLocation();installBrowserStorageAccessProtection();installUnhandledRejectionReporter();+installChunkIntegrityRecovery();configure({disableErrorBoundaries: true, enforceActions: 'observed'});