mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-27 23:27:31 +00:00
b8dffdbb13
Opening a document that was stored for offline use fetched it from the server first and only fell back to the stored copy when the request rejected. On a weak or stalled connection the request never rejects, so a boarding pass already on the phone could spin indefinitely. With a stored copy, the live download now gets five seconds, request and body together; after that the stored copy is served and the download is aborted. A connection that breaks while the body arrives serves the copy as well. An HTTP error that comes back in time still surfaces over the copy, and without a stored copy the download waits as long as it always did. The test file is now formatted and leaves the format baseline.
194 lines
7.7 KiB
TypeScript
194 lines
7.7 KiB
TypeScript
import { getCachedBlob } from '../db/offlineDb'
|
|
import { isEffectivelyOffline } from '../sync/networkMode'
|
|
import { isIosStandalone } from './iosDevice'
|
|
import { isNativeApp } from '../native/platform'
|
|
import { fileNameFromUrl, openNativeFile, shareFile } from '../native/nativeFiles'
|
|
import { reportNativeFailure } from '../native/reportFailure'
|
|
|
|
// MIME types safe to open inline (will not execute script in any browser).
|
|
// Everything else (text/html, image/svg+xml, text/javascript, …) is forced to
|
|
// download so a maliciously-named upload cannot run code in the TREK origin.
|
|
const SAFE_INLINE_TYPES = new Set([
|
|
'application/pdf',
|
|
'image/png',
|
|
'image/jpeg',
|
|
'image/gif',
|
|
'image/webp',
|
|
'image/avif',
|
|
'image/bmp',
|
|
'image/tiff',
|
|
])
|
|
|
|
/**
|
|
* Asserts that `url` is a relative same-origin path so that
|
|
* `credentials: 'include'` cannot be used to send the session cookie to an
|
|
* external host (e.g. if an attacker somehow controls the `url` value).
|
|
*/
|
|
function assertRelativeUrl(url: string): void {
|
|
if (!url.startsWith('/') || url.startsWith('//') || url.startsWith('/\\')) {
|
|
throw new Error(`Refusing to fetch non-relative URL: ${url}`)
|
|
}
|
|
}
|
|
|
|
function triggerAnchorDownload(blobUrl: string, filename?: string): void {
|
|
const a = document.createElement('a')
|
|
a.href = blobUrl
|
|
if (filename) a.download = filename
|
|
document.body.appendChild(a)
|
|
a.click()
|
|
setTimeout(() => { URL.revokeObjectURL(blobUrl); a.remove() }, 100)
|
|
}
|
|
|
|
// How long a live download may take before a copy stored for offline use is
|
|
// served instead. Without a stored copy the live download keeps going as long
|
|
// as it takes, since there is nothing better to show.
|
|
const STORED_COPY_WAIT_MS = 5000
|
|
|
|
// A network failure (the request or the body read rejected) serves the stored
|
|
// copy when there is one. After our own abort the stored copy is already being
|
|
// served, so the error only has to end this read.
|
|
async function storedCopyOr(url: string, err: unknown, signal: AbortSignal): Promise<Blob> {
|
|
if (signal.aborted) throw err
|
|
const cached = await getCachedBlob(url)
|
|
if (cached) return cached
|
|
throw err
|
|
}
|
|
|
|
async function readLive(url: string, signal: AbortSignal): Promise<Blob> {
|
|
let resp: Response
|
|
try {
|
|
resp = await fetch(url, { credentials: 'include', signal })
|
|
} catch (err) {
|
|
// Genuine network failure: the fetch itself rejected (offline, or a flaky
|
|
// link even though navigator.onLine is true). Serve the pre-downloaded copy.
|
|
return storedCopyOr(url, err, signal)
|
|
}
|
|
// The server answered: a non-ok status (401/403/404/…) is a real error and must
|
|
// surface, not be masked by a stale cached copy.
|
|
if (!resp.ok) throw new Error(resp.status === 401 ? 'Unauthorized' : `HTTP ${resp.status}`)
|
|
try {
|
|
return await resp.blob()
|
|
} catch (err) {
|
|
// The connection broke while the body was still arriving.
|
|
return storedCopyOr(url, err, signal)
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Resolves a protected file to a Blob, preferring the live server but falling
|
|
* back to the offline cache (pre-downloaded by the trip sync manager). This is
|
|
* what lets attachments open in a PWA / airplane mode. When offline we go
|
|
* straight to the cache; when online we fetch live and fall back if the
|
|
* network fails, which also covers flaky links where navigator.onLine still
|
|
* reports true ("sometimes it works, sometimes it doesn't"). A stalled link
|
|
* never rejects, so once the live download has run for STORED_COPY_WAIT_MS the
|
|
* stored copy, if there is one, is served and the download aborted. The cache
|
|
* is only read then, so a quick HTTP error still surfaces on its own.
|
|
*/
|
|
async function getFileBlob(url: string): Promise<Blob> {
|
|
assertRelativeUrl(url)
|
|
if (typeof navigator !== 'undefined' && isEffectivelyOffline()) {
|
|
const cached = await getCachedBlob(url)
|
|
if (cached) return cached
|
|
throw new Error('File not available offline')
|
|
}
|
|
// A controller and a timer rather than AbortSignal.timeout, which Safari only
|
|
// has from 16 on.
|
|
const live = new AbortController()
|
|
let settled = false
|
|
let timer: ReturnType<typeof setTimeout> | undefined
|
|
const storedAfterWait = new Promise<Blob>((resolve) => {
|
|
timer = setTimeout(() => {
|
|
void getCachedBlob(url).then((cached) => {
|
|
// Nothing stored: keep waiting on the live download, as before.
|
|
if (!cached || settled) return
|
|
resolve(cached)
|
|
live.abort()
|
|
})
|
|
}, STORED_COPY_WAIT_MS)
|
|
})
|
|
try {
|
|
return await Promise.race([readLive(url, live.signal), storedAfterWait])
|
|
} finally {
|
|
settled = true
|
|
clearTimeout(timer)
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Triggers a browser download for an in-memory Blob (CSV export, generated
|
|
* report, …). Use this instead of hand-rolling the anchor: Firefox ignores a
|
|
* click on an anchor that is not in the document, and revoking the object URL
|
|
* in the same tick can abort the download in other browsers.
|
|
*/
|
|
export function downloadBlob(blob: Blob, filename: string): void {
|
|
if (isNativeApp()) {
|
|
shareFile(blob, filename).catch(reportNativeFailure)
|
|
return
|
|
}
|
|
const blobUrl = URL.createObjectURL(blob)
|
|
triggerAnchorDownload(blobUrl, filename)
|
|
}
|
|
|
|
/**
|
|
* Fetches a protected file using cookie auth (credentials: include) and
|
|
* triggers a browser download. Works inside PWA standalone mode because the
|
|
* fetch stays in the PWA's WebView rather than handing off to the system
|
|
* browser (which would lose the session cookie). Falls back to the offline
|
|
* cache when the network is unavailable.
|
|
*/
|
|
export async function downloadFile(url: string, filename?: string): Promise<void> {
|
|
const blob = await getFileBlob(url)
|
|
if (isNativeApp()) return shareFile(blob, filename ?? fileNameFromUrl(url))
|
|
const blobUrl = URL.createObjectURL(blob)
|
|
triggerAnchorDownload(blobUrl, filename)
|
|
}
|
|
|
|
/**
|
|
* Fetches a protected file using cookie auth and opens it in a new tab as a
|
|
* blob URL. The blob URL is same-origin to the PWA context so no system
|
|
* browser handoff occurs, fixing the auth error in PWA standalone mode.
|
|
*
|
|
* Only PDFs and raster images are opened inline. All other MIME types
|
|
* (including text/html and image/svg+xml which can execute script) are forced
|
|
* to download so that an uploaded file cannot run code in the TREK origin.
|
|
*
|
|
* Uses a synthetic <a target="_blank" rel="noopener noreferrer"> click rather
|
|
* than window.open(). window.open() called with the "noreferrer"/"noopener"
|
|
* window feature returns null per spec, which previously made the popup-block
|
|
* fallback trigger a download in the *current* tab on top of the new-tab open
|
|
* — i.e. the file opened twice. The anchor approach avoids that ambiguity:
|
|
* the new tab is opened by the browser's normal link-handling path, and no
|
|
* spurious in-page download is triggered.
|
|
*/
|
|
export async function openFile(url: string, filename?: string): Promise<void> {
|
|
const blob = await getFileBlob(url)
|
|
// A blob tab has nowhere to open inside the app: the system's viewer shows it,
|
|
// or the share sheet where the app has none.
|
|
if (isNativeApp()) return openNativeFile(blob, filename ?? fileNameFromUrl(url))
|
|
const blobUrl = URL.createObjectURL(blob)
|
|
|
|
// Force download for MIME types that can execute script when rendered inline
|
|
if (!SAFE_INLINE_TYPES.has(blob.type)) {
|
|
triggerAnchorDownload(blobUrl, filename)
|
|
return
|
|
}
|
|
|
|
// iOS PWA: target="_blank" hands off to Safari, which cannot reach a blob URL
|
|
// sandboxed to the installed app's WebView.
|
|
if (isIosStandalone()) {
|
|
triggerAnchorDownload(blobUrl, filename)
|
|
return
|
|
}
|
|
|
|
const a = document.createElement('a')
|
|
a.href = blobUrl
|
|
a.target = '_blank'
|
|
a.rel = 'noopener noreferrer'
|
|
document.body.appendChild(a)
|
|
a.click()
|
|
// Keep the blob URL alive long enough for the new tab to load it, then
|
|
// clean up the DOM node and revoke the URL.
|
|
setTimeout(() => { URL.revokeObjectURL(blobUrl); a.remove() }, 30_000)
|
|
}
|