Skip to content

~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.

4.8 KB
Raw Blame
/**
 * Safe fetch wrapper with URL validation.
 * Blocks external URLs that haven't been validated.
 * Requires url-validator.js to be loaded first.
 */
async function safeFetch(url, options = {}) {
    // Internal URLs starting with '/' are safe
    if (!url.startsWith('/')) {
        if (!URLValidator.isSafeUrl(url)) {
            throw new Error(`Blocked unsafe URL: ${url}`);
        }
    }
    return fetch(url, options);
}

/**
 * Auth-aware variant of safeFetch for our own API endpoints.
 *
 * Recovers an explicitly rejected CSRF check once for eligible writes within
 * the page's original login. A 401 from an internal URL navigates to login,
 * so callers that inspect response.status share the same re-authentication
 * behavior. That redirect returns a never-resolving Promise (the page is
 * navigating away), matching fetchWithErrorHandling's behavior.
 *
 * The "which 401s redirect" decision and the login-URL construction are reused
 * from api.js (window.api) so there is a single definition shared with
 * fetchWithErrorHandling — no duplicated/drifting logic.
 *
 * Do NOT use on /auth/* endpoints — those handle their own 401 states.
 */
async function safeFetchWithAuth(url, options = {}) {
    const response = typeof window.api?.fetchWithCsrfRecovery === 'function'
        ? await window.api.fetchWithCsrfRecovery(url, options, safeFetch)
        : await safeFetch(url, options);
    if (response.status === 401 && window.api.shouldRedirectToLoginOn401(url)) {
        window.api.redirectToLogin();
        return new Promise(() => {}); // never resolves; page is navigating away
    }
    return response;
}

/**
 * Structured HTTP error raised by safeFetchJson. Carries status,
 * Retry-After (in seconds where the server provides one), and the
 * parsed body when JSON, so callers can branch on 429 vs 500 vs 4xx
 * and surface a user-meaningful message ("rate limit reached, try
 * again in 30s") instead of a generic "Failed to ...".
 */
class HTTPError extends Error {
    constructor({ status, statusText, retryAfter, body, url }) {
        // Flask-era endpoints commonly returned `{ error }`, while FastAPI
        // uses `{ detail }` for HTTPException responses. Preserve the server's
        // useful message across both envelopes during the migration.
        const detail = body?.error || body?.detail || statusText || `HTTP ${status}`;
        super(detail);
        this.name = 'HTTPError';
        this.status = status;
        this.statusText = statusText;
        this.retryAfter = retryAfter;
        this.body = body;
        this.url = url;
    }
}

function _parseRetryAfter(headerValue) {
    if (!headerValue) {
        return null;
    }
    const secs = Number(headerValue);
    if (Number.isFinite(secs) && secs >= 0) {
        return secs;
    }
    // RFC 7231 also allows an HTTP-date; convert to relative seconds.
    const when = Date.parse(headerValue);
    if (!Number.isNaN(when)) {
        const delta = Math.max(0, Math.round((when - Date.now()) / 1000));
        return delta;
    }
    return null;
}

/**
 * Wrapper around safeFetch that:
 *   - throws an HTTPError on any non-2xx response (so callers can stop
 *     blindly calling `.json()` on error pages that don't return JSON),
 *   - exposes Retry-After on the thrown error for 429 backoff handling,
 *   - parses the response as JSON for 2xx.
 *
 * Migration path: existing call sites that wrap `await safeFetch(...)`
 * + `await resp.json()` + manual `data.success` checks can switch to
 * `await safeFetchJson(...)` and catch HTTPError instead.
 *
 * For endpoints that should redirect to login on an expired session,
 * compose with the auth-aware variant by passing safeFetchWithAuth's
 * result semantics — or call safeFetchWithAuth directly when a JSON
 * envelope isn't needed.
 */
async function safeFetchJson(url, options = {}) {
    const response = await safeFetch(url, options);
    if (!response.ok) {
        let body;
        try {
            // Some error responses are JSON, some are HTML/text.
            const ct = response.headers.get('content-type') || '';
            body = ct.includes('application/json') ? await response.json() : null;
        } catch (_e) {
            body = null;
        }
        throw new HTTPError({
            status: response.status,
            statusText: response.statusText,
            retryAfter: _parseRetryAfter(response.headers.get('Retry-After')),
            body,
            url,
        });
    }
    return response.json();
}

// Export for Node.js testing
if (typeof module !== 'undefined' && module.exports) {
    module.exports = { safeFetch, safeFetchWithAuth, safeFetchJson, HTTPError };
}

// Make the helpers available globally for browser usage
if (typeof window !== 'undefined') {
    window.safeFetch = safeFetch;
    window.safeFetchWithAuth = safeFetchWithAuth;
    window.safeFetchJson = safeFetchJson;
    window.HTTPError = HTTPError;
}