Skip to content

Real-time network monitor + outbound firewall — see & block every connection. Privacy-first, local-first, Rust fleet agent, SIEM exports, 8 languages. / Moniteur réseau temps réel + pare-feu sortant, agent de flotte Rust, exports SIEM. 100 % local.

5.9 KB
Raw Blame
/**
 * Snitch — API endpoint helpers + auth token plumbing.
 *
 * EN: Under Electron the app is loaded from file://, so there is no dev-server
 *     proxy — all backend calls use the absolute loopback URL.
 *     In dev/browser mode we rely on the Vite proxy and relative URLs.
 *
 *     AUTH: every request needs the API token. Resolution order:
 *       1. window.snitch.getToken()  — Electron preload bridge (IPC)
 *       2. ?token= URL param         — Docker/browser first open
 *       3. sessionStorage            — survives reloads in the same tab
 *       4. window.prompt()           — last-resort manual entry
 *     The resolved promise is cached — only ONE prompt can ever appear.
 *
 * FR: Sous Electron, l'app est chargée depuis file://, donc pas de proxy de
 *     dev-server — tous les appels backend utilisent l'URL loopback absolue.
 *     En mode dev/navigateur on s'appuie sur le proxy Vite avec des URL
 *     relatives.
 *
 *     AUTH : chaque requête exige le jeton API. Ordre de résolution :
 *       1. window.snitch.getToken()  — pont preload Electron (IPC)
 *       2. paramètre ?token= d'URL   — première ouverture Docker/navigateur
 *       3. sessionStorage            — survit aux rechargements de l'onglet
 *       4. window.prompt()           — saisie manuelle en dernier recours
 *     La promesse résolue est mise en cache — une SEULE invite peut apparaître.
 */
// EN: `typeof window` guard — Vitest (Node) imports this module without a
//     DOM; everything that touches `window` lazily stays inside functions.
// FR: Garde `typeof window` — Vitest (Node) importe ce module sans DOM ;
//     tout ce qui touche `window` paresseusement reste dans des fonctions.
const isElectron = typeof window !== 'undefined' && window.location.protocol === 'file:'

// EN: Backend port — Electron picks a FREE port at launch and exposes it via
//     the preload bridge (window.snitch.getPort()). Browsers/Docker use the
//     page origin (same-origin deployment) or the vite proxy. Falls back to
//     8000 only for compatibility.
// FR: Port du backend — Electron choisit un port LIBRE au lancement et
//     l'expose via le pont preload (window.snitch.getPort()). Navigateur/
//     Docker utilisent l'origine de la page (déploiement same-origin) ou le
//     proxy vite. Repli 8000 uniquement pour compatibilité.
let _portPromise = null
export function getApiPort() {
  if (_portPromise) return _portPromise
  _portPromise = (async () => {
    if (window.snitch?.getPort) return await window.snitch.getPort()
    if (isElectron) return 8000
    return window.location.port || (window.location.protocol === 'https:' ? 443 : 80)
  })()
  return _portPromise
}

// EN: ws/wss follows the page scheme — a deployment behind an HTTPS proxy
//     must not attempt a plaintext ws://.
// FR: ws/wss suit le schéma de la page — un déploiement derrière un proxy
//     HTTPS ne doit pas tenter un ws:// en clair.
const wsScheme = (typeof window !== 'undefined' && window.location.protocol === 'https:') ? 'wss' : 'ws'

export async function apiBase() {
  if (isElectron) return `http://127.0.0.1:${await getApiPort()}`
  return ''
}

export async function wsBase() {
  if (isElectron) return `${wsScheme}://127.0.0.1:${await getApiPort()}/ws`
  return `${wsScheme}://${window.location.host}/ws`
}

export const API_BASE = isElectron ? 'http://127.0.0.1:8000' : ''
export const WS_URL   = isElectron
  ? `${wsScheme}://127.0.0.1:8000/ws`
  : typeof window !== 'undefined'
    ? `${wsScheme}://${window.location.host}/ws`
    : ''

let _tokenPromise = null

/**
 * EN: Resolve the API token once — see module docstring for the order.
 * FR: Résoudre le jeton API une fois — voir le docstring du module pour
 *     l'ordre.
 */
export function getToken() {
  if (_tokenPromise) return _tokenPromise
  _tokenPromise = (async () => {
    // EN: Electron — the token never touches the URL or the DOM.
    // FR: Electron — le jeton ne touche jamais l'URL ni le DOM.
    if (window.snitch?.getToken) {
      return await window.snitch.getToken()
    }
    const fromUrl = new URLSearchParams(window.location.search).get('token')
    if (fromUrl) {
      sessionStorage.setItem('snitch_token', fromUrl)
      // EN: Strip the token from the address bar so it cannot linger in
      //     browser history — the stored copy keeps auth working.
      // FR: Retirer le jeton de la barre d'adresse pour qu'il ne reste pas
      //     dans l'historique du navigateur — la copie stockée suffit.
      const clean = new URL(window.location.href)
      clean.searchParams.delete('token')
      window.history.replaceState(null, '', clean)
      return fromUrl
    }
    const stored = sessionStorage.getItem('snitch_token')
    if (stored) return stored
    const manual = window.prompt('Snitch API token / Jeton API Snitch :')
    if (manual) {
      const t = manual.trim()
      sessionStorage.setItem('snitch_token', t)
      return t
    }
    return null
  })()
  return _tokenPromise
}

/**
 * EN: Headers for an authenticated fetch — merges X-Snitch-Token into `extra`.
 * FR: En-têtes pour un fetch authentifié — fusionne X-Snitch-Token dans `extra`.
 */
export async function authHeaders(extra = {}) {
  const token = await getToken()
  return token ? { ...extra, 'X-Snitch-Token': token } : extra
}

/**
 * EN: WebSocket URL with the token as a query param — the browser WS API
 *     can't set headers, so ?token= is the transport.
 * FR: URL WebSocket avec le jeton en paramètre de requête — l'API WS du
 *     navigateur ne peut pas poser d'en-têtes, donc ?token= fait le transport.
 */
export async function wsUrlWithToken(base) {
  const token = await getToken()
  // EN: `base` may be a function (async wsBase) or a legacy static string.
  // FR: `base` peut être une fonction (wsBase async) ou une chaîne statique.
  const url = typeof base === 'function' ? await base() : base
  return token ? `${url}?token=${encodeURIComponent(token)}` : url
}