Skip to content

A full-featured download manager.

15.9 KB
Raw Blame
import { createHash, randomBytes, timingSafeEqual } from 'node:crypto'
import type {
  ClientPairingCapabilities,
  OperatorStatus,
} from '@shared/schemas/operator-auth'
import { changeOperatorTokenSchema } from '@shared/schemas/operator-token'
import type { FastifyInstance, FastifyReply, FastifyRequest } from 'fastify'

/**
 * Operator auth for the server-shell control plane (Spec 9).
 *
 * The Fastify app serves the OPERATOR control plane (`/rpc/*`, `/api/*`,
 * `/rpc/events`) — distinct from the agent API on the bridge (`/mdxp`). Anyone
 * who reaches `:8080` must NOT be able to drive the instance or, critically,
 * approve a device-code pairing (which mints an agent token). The operator is
 * "the machine owner" — proven by the independently provisioned operator
 * token (`MOTRIX_OPERATOR_TOKEN` or `<dataDir>/operator-token`). The browser
 * proves it once via `POST /rpc/auth/login` and gets an httpOnly,
 * SameSite=Strict session cookie; host scripts may instead send
 * `Authorization: Bearer <operatorToken>`.
 *
 * The gate is DENY-BY-DEFAULT with a small public allow-list — NOT scoped to
 * `/rpc/*` — because the actionable surface also includes `/api/tasks/*`.
 */

const COOKIE = 'mtx_op'
const SESSION_TTL_MS = 7 * 24 * 60 * 60 * 1000
const LOGIN_WINDOW_MS = 60_000
const LOGIN_MAX = 20

export interface OperatorAuthOptions {
  clientPairing?: ClientPairingCapabilities
  /**
   * The operator (machine-owner) secret that authorizes the control plane.
   * Provisioned INDEPENDENTLY of the bridge (Spec 9 / F1) — it is NOT the agent
   * `/mdxp` localToken, so a leaked operator credential grants no agent access
   * and the control plane never depends on the (non-fatal) bridge bootstrap.
   */
  operatorToken: string
  tokenSource?: 'file' | 'env'
  persistToken?: (token: string) => Promise<void>
  /** Public operator URL advertised by MOTRIX_PUBLIC_URL. Cookie-authenticated
   * event WebSockets must present this exact URL origin; scripts using Bearer
   * authentication remain independent of browser Origin semantics. */
  publicUrl?: string
  onEventSocketRejected?: (detail: {
    reason: 'unauthorized' | 'origin-mismatch'
    expectedOrigin: string | null
    presentedOrigin: string | null
  }) => void
  /** Injectable clock (tests). */
  now?: () => number
}

function sha256(s: string): Buffer {
  return createHash('sha256').update(s).digest()
}

/** Constant-time compare immune to length differences (hash both → fixed len,
 *  so `timingSafeEqual` never throws on a length mismatch). */
function safeEqual(a: string, b: string): boolean {
  return timingSafeEqual(sha256(a), sha256(b))
}

function parseCookies(header: string | undefined): Record<string, string> {
  const out: Record<string, string> = {}
  if (!header) return out
  for (const part of header.split(';')) {
    const i = part.indexOf('=')
    if (i === -1) continue
    const k = part.slice(0, i).trim()
    if (k) out[k] = part.slice(i + 1).trim()
  }
  return out
}

function bearerToken(req: FastifyRequest): string | null {
  const h = req.headers.authorization
  if (typeof h !== 'string') return null
  if (h.startsWith('Bearer ')) return h.slice(7)
  if (h.startsWith('Basic ')) {
    const decoded = Buffer.from(h.slice(6), 'base64').toString('utf8')
    if (decoded.startsWith(':')) return decoded.slice(1)
  }
  return null
}

function isSecure(req: FastifyRequest): boolean {
  return (
    req.headers['x-forwarded-proto'] === 'https' || req.protocol === 'https'
  )
}

function isWebSocketUpgrade(req: FastifyRequest): boolean {
  return String(req.headers.upgrade ?? '').toLowerCase() === 'websocket'
}

function configuredPublicOrigin(value: string | undefined): string | null {
  if (value === undefined) return null
  try {
    const parsed = new URL(value)
    if (
      (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') ||
      parsed.username !== '' ||
      parsed.password !== ''
    ) {
      return null
    }
    return parsed.origin
  } catch {
    return null
  }
}

function expectedBrowserOrigin(
  req: FastifyRequest,
  publicOrigin: string | null
): string | null {
  return (
    publicOrigin ??
    (() => {
      const host = req.headers.host
      if (typeof host !== 'string' || host.length === 0) return null
      try {
        return new URL(`${isSecure(req) ? 'https' : 'http'}://${host}`).origin
      } catch {
        return null
      }
    })()
  )
}

function exactBrowserOrigin(
  req: FastifyRequest,
  publicOrigin: string | null,
  presented = req.headers.origin
): boolean {
  if (typeof presented !== 'string' || presented.length === 0) return false
  const expected = expectedBrowserOrigin(req, publicOrigin)
  return expected !== null && presented === expected
}

/** Deny a request. A normal `reply.send()` does NOT yield a clean HTTP response
 *  on a WebSocket UPGRADE request (the client just hangs), so for an upgrade we
 *  hijack and write a raw status line so the `ws` client gets `unexpected-response`. */
function deny(
  req: FastifyRequest,
  reply: FastifyReply,
  code: number,
  message: string
): FastifyReply | undefined {
  const isUpgrade = isWebSocketUpgrade(req)
  if (isUpgrade) {
    reply.hijack()
    const text =
      code === 429
        ? 'Too Many Requests'
        : code === 403
          ? 'Forbidden'
          : 'Unauthorized'
    req.raw.socket.write(
      `HTTP/1.1 ${code} ${text}\r\nConnection: close\r\nContent-Length: 0\r\n\r\n`
    )
    req.raw.socket.destroy()
    return undefined
  }
  return reply.code(code).send({ error: message })
}

/** Public (no-auth) routes. Everything else requires the operator. The login
 *  endpoint is self-protected (it requires the localToken in its body). */
function isPublic(method: string, url: string): boolean {
  const path = url.split('?')[0]
  if (method === 'GET' && path === '/healthz') return true
  if (method === 'POST' && path === '/rpc/auth/login') return true
  if (method === 'GET' && path === '/rpc/auth/status') return true
  // Static SPA shell + assets: any GET that is not under /rpc or /api. The
  // unlock screen must load before the operator can authenticate; the bundle
  // carries no privileged data.
  if (
    method === 'GET' &&
    !path.startsWith('/rpc/') &&
    !path.startsWith('/api/')
  ) {
    return true
  }
  return false
}

export interface SessionSocket {
  close(code: number, reason: string): void
  send(data: string, callback: (error?: Error) => void): void
}

export interface OperatorSessionPolicy {
  principal(
    req: FastifyRequest
  ): { id: string; eligible(): boolean } | undefined
  bindSocket(
    req: FastifyRequest,
    socket: SessionSocket
  ): {
    eligible: () => boolean
    dispose: () => void
  }
}

export function registerOperatorAuth(
  app: FastifyInstance,
  opts: OperatorAuthOptions
): OperatorSessionPolicy {
  const now = opts.now ?? Date.now
  let operatorToken = opts.operatorToken
  let generation = 0
  let rotation: Promise<unknown> = Promise.resolve()
  const publicOrigin = configuredPublicOrigin(opts.publicUrl)
  const sessions = new Map<string, number>() // sessionId -> expiresAt
  const sessionSockets = new Map<string, Set<SessionSocket>>()
  const bearerSockets = new Set<SessionSocket>()
  const revoke = (id: string): void => {
    sessions.delete(id)
    const sockets = sessionSockets.get(id)
    sessionSockets.delete(id)
    for (const socket of sockets ?? []) socket.close(4401, 'Session expired')
  }
  // Weak custom credentials need throttling before comparison, including direct
  // HTTP credentials. Bound memory and use the socket IP (not forwarded headers).
  const failures = new Map<string, { count: number; until: number }>()
  const limited = (req: FastifyRequest): boolean => {
    for (const [ip, entry] of failures) {
      if (entry.until <= now()) failures.delete(ip)
    }
    const entry = failures.get(req.ip)
    return entry ? entry.count >= LOGIN_MAX : failures.size >= 256
  }
  const verify = (req: FastifyRequest, token: string): boolean => {
    if (limited(req)) return false
    if (token && safeEqual(token, operatorToken)) {
      failures.delete(req.ip)
      return true
    }
    const entry = failures.get(req.ip) ?? {
      count: 0,
      until: now() + LOGIN_WINDOW_MS,
    }
    entry.count += 1
    failures.set(req.ip, entry)
    return false
  }

  const validSession = (id: string | undefined, renew = true): boolean => {
    if (!id) return false
    const exp = sessions.get(id)
    if (!exp) return false
    if (now() >= exp) {
      revoke(id)
      return false
    }
    if (renew) sessions.set(id, now() + SESSION_TTL_MS)
    return true
  }

  const authenticate = (req: FastifyRequest): 'bearer' | 'cookie' | null => {
    const tok = bearerToken(req)
    if (tok && verify(req, tok)) return 'bearer'
    return validSession(parseCookies(req.headers.cookie)[COOKIE])
      ? 'cookie'
      : null
  }

  // ── deny-by-default gate ────────────────────────────────────────────────
  app.addHook('onRequest', async (req, reply) => {
    const path = req.url.split('?')[0]
    if (path.startsWith('/rpc/') || path.startsWith('/api/')) {
      // Operator responses can contain live pairing codes, task metadata, and
      // other machine-owner state. Keep them out of browser/proxy caches even
      // when the request is rejected or the caller used Bearer auth.
      reply.header('cache-control', 'no-store')
      reply.header('pragma', 'no-cache')
    }
    if (isPublic(req.method, req.url)) return
    const authentication = authenticate(req)
    // CSRF defense-in-depth on mutations: reject a present-but-cross-origin
    // Origin. SameSite=Strict is the primary defense; non-browser callers omit
    // Origin and authenticate by Bearer.
    if (req.method !== 'GET') {
      const origin = req.headers.origin
      if (typeof origin === 'string' && origin.length > 0) {
        let sameOrigin = false
        try {
          sameOrigin = new URL(origin).host === req.headers.host
        } catch {
          sameOrigin = false
        }
        if (!sameOrigin) {
          return deny(req, reply, 403, 'cross-origin forbidden')
        }
      }
    }
    if (authentication === null) {
      if (isWebSocketUpgrade(req))
        opts.onEventSocketRejected?.({
          reason: 'unauthorized',
          expectedOrigin: expectedBrowserOrigin(req, publicOrigin),
          presentedOrigin: configuredPublicOrigin(req.headers.origin),
        })
      return deny(req, reply, limited(req) ? 429 : 401, 'unauthorized')
    }
    if (
      isWebSocketUpgrade(req) &&
      authentication === 'cookie' &&
      !exactBrowserOrigin(req, publicOrigin)
    ) {
      opts.onEventSocketRejected?.({
        reason: 'origin-mismatch',
        expectedOrigin: expectedBrowserOrigin(req, publicOrigin),
        presentedOrigin: configuredPublicOrigin(req.headers.origin),
      })
      return deny(req, reply, 403, 'cross-origin forbidden')
    }
  })

  // ── auth routes ─────────────────────────────────────────────────────────
  app.post<{ Body: { token?: string } }>(
    '/rpc/auth/login',
    async (req, reply) => {
      const t = now()
      const token = typeof req.body?.token === 'string' ? req.body.token : ''
      if (limited(req))
        return reply.code(429).send({ error: 'too many attempts' })
      if (verify(req, token)) {
        const id = randomBytes(32).toString('base64url')
        sessions.set(id, t + SESSION_TTL_MS)
        const flags = [
          `${COOKIE}=${id}`,
          'HttpOnly',
          'SameSite=Strict',
          'Path=/',
          `Max-Age=${Math.floor(SESSION_TTL_MS / 1000)}`,
        ]
        if (isSecure(req)) flags.push('Secure')
        reply.header('set-cookie', flags.join('; '))
        return { ok: true }
      }
      return reply.code(401).send({ error: 'invalid token' })
    }
  )

  app.post('/rpc/auth/token', { bodyLimit: 16_384 }, async (req, reply) => {
    // Cookie mutations require an exact Origin. CLI requests use HTTP auth.
    if (
      authenticate(req) !== 'bearer' &&
      !exactBrowserOrigin(req, publicOrigin)
    ) {
      return reply.code(403).send({ ok: false, reason: 'incorrectToken' })
    }
    const parsed = changeOperatorTokenSchema.safeParse(req.body)
    if (!parsed.success)
      return reply.code(400).send({ ok: false, reason: 'invalid' })
    const change = async () => {
      if (opts.tokenSource !== 'file' || !opts.persistToken) {
        return reply.code(409).send({ ok: false, reason: 'managed' })
      }
      if (limited(req))
        return reply.code(429).send({ ok: false, reason: 'rateLimited' })
      if (!verify(req, parsed.data.currentToken)) {
        return reply.code(403).send({ ok: false, reason: 'incorrectToken' })
      }
      try {
        await opts.persistToken(parsed.data.newToken)
      } catch {
        return reply.code(503).send({ ok: false, reason: 'unavailable' })
      }
      operatorToken = parsed.data.newToken
      generation += 1
      const keep = parseCookies(req.headers.cookie)[COOKIE]
      for (const id of sessions.keys()) if (id !== keep) revoke(id)
      for (const socket of bearerSockets) socket.close(4401, 'Session expired')
      bearerSockets.clear()
      return reply.send({ ok: true })
    }
    // Recheck the old credential inside the queue, so simultaneous changes
    // cannot both succeed and silently replace the first caller's new token.
    const pending = rotation.then(change)
    rotation = pending.catch(() => {})
    return pending
  })

  app.get('/rpc/auth/status', async (req): Promise<OperatorStatus> => {
    const mode = authenticate(req)
    const browserOrigin = req.headers['x-motrix-web-origin']
    return {
      authed: mode !== null,
      mode: mode ?? 'unauthenticated',
      canLogout: mode === 'cookie',
      ...(mode !== null && opts.tokenSource
        ? { tokenSource: opts.tokenSource }
        : {}),
      ...(mode !== null && opts.clientPairing
        ? { clientPairing: opts.clientPairing }
        : {}),
      // Diagnostic only: this caller-supplied header never authorizes a request.
      ...(mode !== null && typeof browserOrigin === 'string'
        ? {
            eventOriginMatches: exactBrowserOrigin(
              req,
              publicOrigin,
              browserOrigin
            ),
          }
        : {}),
    }
  })

  app.post('/rpc/auth/logout', async (req, reply) => {
    const id = parseCookies(req.headers.cookie)[COOKIE]
    if (authenticate(req) === 'cookie' && id) revoke(id)
    reply.header(
      'set-cookie',
      `${COOKIE}=; HttpOnly; SameSite=Strict; Path=/; Max-Age=0`
    )
    return { ok: true }
  })

  return {
    principal(req) {
      const mode = authenticate(req)
      const issuedGeneration = generation
      if (mode === 'bearer')
        return {
          id: `bearer:${sha256(operatorToken).toString('hex')}`,
          eligible: () => issuedGeneration === generation,
        }
      const id = parseCookies(req.headers.cookie)[COOKIE]
      if (mode !== 'cookie' || !id) return undefined
      return {
        id: `session:${sha256(id).toString('hex')}`,
        eligible: () => validSession(id, false),
      }
    },
    bindSocket(req, socket) {
      const mode = authenticate(req)
      const issuedGeneration = generation
      if (mode === 'bearer') bearerSockets.add(socket)
      const id =
        mode === 'cookie' ? parseCookies(req.headers.cookie)[COOKIE] : undefined
      if (id) {
        const sockets = sessionSockets.get(id) ?? new Set<SessionSocket>()
        sockets.add(socket)
        sessionSockets.set(id, sockets)
      }
      return {
        eligible: () =>
          (mode === 'bearer' && issuedGeneration === generation) ||
          (mode === 'cookie' && validSession(id, false)),
        dispose: () => {
          bearerSockets.delete(socket)
          if (!id) return
          const sockets = sessionSockets.get(id)
          sockets?.delete(socket)
          if (sockets?.size === 0) sessionSockets.delete(id)
        },
      }
    },
  }
}