#!/usr/bin/env node
// Find pages in a sitemap that declare no og:image or share one declared image URL.
// Reads static metadata with the local myog-checker CLI (one page at a time).
// It compares declared image URLs only: it never fetches or compares image files.
//
// Setup (Node.js 22.19.0 or later):
//   npm install myog-checker@0.1.1 htmlparser2@10.0.0
//   node og-image-sitemap-audit.mjs https://example.com/sitemap.xml
//   node og-image-sitemap-audit.mjs ./dist/sitemap.xml --max-pages 50 --json
//
// Run it only against sites you own or are allowed to test.
// MIT License. https://myog.social/articles/find-pages-sharing-default-og-image
import { spawn } from "node:child_process"
import { lookup } from "node:dns/promises"
import { realpathSync } from "node:fs"
import { readFile } from "node:fs/promises"
import { createRequire } from "node:module"
import { BlockList, isIP } from "node:net"
import { pathToFileURL } from "node:url"
import { parseArgs } from "node:util"

import { Parser } from "htmlparser2"

export const LIMITS = {
  defaultMaxPages: 100,
  maxPages: 1000,
  defaultDelayMS: 500,
  maxSitemapBytes: 10 * 1024 * 1024,
  maxLocsPerSitemap: 50_000,
  maxChildSitemaps: 25,
  sitemapTimeoutMS: 15_000,
  maxSitemapRedirects: 3,
  checkerTimeoutMS: 20_000,
  maxCheckerOutputBytes: 256 * 1024,
  maxListedPagesPerGroup: 20,
}

const HELP = `Usage: node og-image-sitemap-audit.mjs <sitemap-url-or-file> [options]

Groups sitemap pages by the og:image URL each page declares, using the local
myog-checker CLI. Reports pages with no image URL and image URLs shared by
two or more pages. It does not fetch, compare or validate image files.

Options:
  --max-pages <n>    Pages to check (default ${LIMITS.defaultMaxPages}, max ${LIMITS.maxPages})
  --delay-ms <n>     Pause between page checks (default ${LIMITS.defaultDelayMS})
  --host <hostname>  Page hostname to check (default: the sitemap URL's host, or
                     the first <loc> host for a local file)
  --json             Print one JSON report to stdout
  --strict           Exit 3 when any page is missing an image or shares one
  --checker-cli <p>  Path to myog-checker's dist/cli.js (default: installed package)
  -h, --help         Show help

Exit codes: 0 report printed, 1 sitemap or setup failure, 2 bad arguments,
3 findings with --strict.`

export class AuditError extends Error {}

// Separate lists: Node's BlockList also matches IPv4 addresses against IPv4-mapped
// IPv6 rules, so one shared list containing ::ffff:0:0/96 would block every IPv4 address.
const blockedIPv4 = new BlockList()
for (const [network, prefix] of [
  ["0.0.0.0", 8],
  ["10.0.0.0", 8],
  ["100.64.0.0", 10],
  ["127.0.0.0", 8],
  ["169.254.0.0", 16],
  ["172.16.0.0", 12],
  ["192.0.0.0", 24],
  ["192.168.0.0", 16],
  ["198.18.0.0", 15],
  ["224.0.0.0", 3],
]) {
  blockedIPv4.addSubnet(network, prefix, "ipv4")
}
const blockedIPv6 = new BlockList()
for (const [network, prefix] of [
  ["::", 127],
  ["::ffff:0:0", 96],
  ["64:ff9b::", 96],
  ["fc00::", 7],
  ["fe80::", 10],
  ["ff00::", 8],
]) {
  blockedIPv6.addSubnet(network, prefix, "ipv6")
}

export function isBlockedAddress(address) {
  const family = isIP(address)
  if (family === 4) {
    return blockedIPv4.check(address, "ipv4")
  }
  return family === 0 || blockedIPv6.check(address, "ipv6")
}

// Rejects obvious local targets for the sitemap requests this script makes.
// Page checks go through myog-checker's own DNS-checked public-address policy.
export function parsePublicURL(value) {
  let url
  try {
    url = new URL(value)
  } catch {
    throw new AuditError(`Not a valid URL: ${value}`)
  }
  const hostname = url.hostname.replace(/^\[|\]$/g, "").toLowerCase()
  if (!["http:", "https:"].includes(url.protocol) || url.username || url.password || url.port) {
    throw new AuditError(`Only public http(s) URLs on default ports without credentials: ${value}`)
  }
  if (
    hostname === "localhost" ||
    [".localhost", ".local", ".internal", ".home.arpa"].some((suffix) =>
      hostname.endsWith(suffix)
    ) ||
    (isIP(hostname) !== 0 && isBlockedAddress(hostname))
  ) {
    throw new AuditError(`Refusing a local or reserved host: ${hostname}`)
  }
  url.hash = ""
  return url
}

async function assertPublicDNS(hostname) {
  if (isIP(hostname) !== 0) {
    return
  }
  let addresses
  try {
    addresses = await lookup(hostname, { all: true, verbatim: true })
  } catch {
    throw new AuditError(`Could not resolve ${hostname}`)
  }
  if (addresses.length === 0 || addresses.some(({ address }) => isBlockedAddress(address))) {
    throw new AuditError(`${hostname} resolves to a local or reserved address`)
  }
}

async function readLimitedBody(response) {
  const reader = response.body?.getReader()
  const chunks = []
  let size = 0
  while (reader) {
    const { done, value } = await reader.read()
    if (done) {
      break
    }
    size += value.byteLength
    if (size > LIMITS.maxSitemapBytes) {
      await reader.cancel()
      throw new AuditError(`Sitemap is larger than ${LIMITS.maxSitemapBytes} bytes`)
    }
    chunks.push(value)
  }
  return Buffer.concat(chunks)
}

export async function fetchSitemap(url) {
  let current = parsePublicURL(url)
  const originalHost = current.hostname
  for (let redirects = 0; ; redirects += 1) {
    await assertPublicDNS(current.hostname)
    const response = await fetch(current, {
      redirect: "manual",
      headers: { accept: "application/xml, text/xml;q=0.9, */*;q=0.1" },
      signal: AbortSignal.timeout(LIMITS.sitemapTimeoutMS),
    }).catch((error) => {
      throw new AuditError(
        error?.name === "TimeoutError"
          ? `Sitemap request timed out: ${current.href}`
          : `Could not fetch ${current.href}`
      )
    })
    if (response.status >= 300 && response.status < 400) {
      await response.body?.cancel()
      const location = response.headers.get("location")
      if (!location || redirects >= LIMITS.maxSitemapRedirects) {
        throw new AuditError(`Too many or invalid sitemap redirects from ${url}`)
      }
      current = parsePublicURL(new URL(location, current).href)
      if (current.hostname !== originalHost) {
        throw new AuditError(
          `Sitemap redirected to ${current.href}; run the script with that URL instead`
        )
      }
      continue
    }
    if (!response.ok) {
      await response.body?.cancel()
      throw new AuditError(`Sitemap request returned HTTP ${response.status}: ${current.href}`)
    }
    const body = await readLimitedBody(response).catch((error) => {
      throw error instanceof AuditError ? error : new AuditError(`Could not read ${current.href}`)
    })
    return decodeSitemap(body)
  }
}

function decodeSitemap(bytes) {
  if (bytes[0] === 0x1f && bytes[1] === 0x8b) {
    throw new AuditError(
      "Gzip-compressed sitemap files are not supported; pass the uncompressed XML"
    )
  }
  return bytes.toString("utf8")
}

export async function readSitemapFile(path) {
  let bytes
  try {
    bytes = await readFile(path)
  } catch {
    throw new AuditError(`Could not read ${path}`)
  }
  if (bytes.byteLength > LIMITS.maxSitemapBytes) {
    throw new AuditError(`Sitemap is larger than ${LIMITS.maxSitemapBytes} bytes`)
  }
  return decodeSitemap(bytes)
}

// Structured XML parse: <urlset><url><loc> or <sitemapindex><sitemap><loc>.
// Child elements must use the root's prefix, so extensions such as <image:loc>
// are ignored. Unclosed elements (a truncated file) and other roots are rejected.
export function parseSitemap(xml) {
  const stack = []
  const locs = []
  let root = ""
  let prefix = ""
  let text = ""
  let malformed = false
  let tooMany = false
  let ending = false
  const parser = new Parser(
    {
      onopentag(name) {
        if (stack.length === 0 && !root) {
          prefix = name.includes(":") ? name.slice(0, name.indexOf(":") + 1) : ""
          root = name.slice(prefix.length)
        }
        stack.push(name)
        text = ""
      },
      ontext(chunk) {
        text += chunk
      },
      onclosetag(name, isImplied) {
        // Self-closing tags such as <xhtml:link/> also report isImplied; only closes
        // forced by the end of input mean the file was truncated.
        if (isImplied && ending) {
          malformed = true
        }
        const parent = stack.at(-2)
        const entry = root === "urlset" ? "url" : "sitemap"
        if (name === `${prefix}loc` && stack.length === 3 && parent === `${prefix}${entry}`) {
          if (locs.length >= LIMITS.maxLocsPerSitemap) {
            tooMany = true
          } else if (text.trim()) {
            locs.push(text.trim())
          }
        }
        stack.pop()
        text = ""
      },
    },
    { xmlMode: true, decodeEntities: true }
  )
  parser.write(xml)
  ending = true
  parser.end()
  if (malformed || stack.length > 0) {
    throw new AuditError("Sitemap XML is malformed (unclosed elements)")
  }
  if (root !== "urlset" && root !== "sitemapindex") {
    throw new AuditError("Not a sitemap: expected a <urlset> or <sitemapindex> root element")
  }
  return { kind: root === "urlset" ? "urlset" : "index", locs, truncated: tooMany }
}

function sameHostPageURL(value, hostname) {
  try {
    const url = parsePublicURL(value)
    return url.hostname === hostname ? url.href : null
  } catch {
    return null
  }
}

// Reads one sitemap, or one sitemap index and up to maxChildSitemaps children.
// Nested indexes are not followed.
export async function collectPageURLs({
  source,
  maxPages,
  host,
  fetchSitemapText = fetchSitemap,
  readSitemapText = readSitemapFile,
}) {
  const sourceIsURL = /^https?:\/\//i.test(source)
  const notes = []
  const first = parseSitemap(
    sourceIsURL ? await fetchSitemapText(source) : await readSitemapText(source)
  )
  if (first.truncated) {
    notes.push(`Read only the first ${LIMITS.maxLocsPerSitemap} <loc> entries of a sitemap.`)
  }
  const firstLoc = first.locs.length ? safeHostname(first.locs[0]) : ""
  const hostname = (
    host || (sourceIsURL ? parsePublicURL(source).hostname : firstLoc)
  ).toLowerCase()
  if (!hostname) {
    throw new AuditError("The sitemap has no <loc> entries")
  }

  let urlsets = [first]
  if (first.kind === "index") {
    const children = first.locs
      .filter((loc) => safeHostname(loc) === hostname)
      .map((loc) => new URL(loc).href)
    if (children.length < first.locs.length) {
      notes.push(`Child sitemaps skipped on other hosts: ${first.locs.length - children.length}`)
    }
    if (children.length > LIMITS.maxChildSitemaps) {
      notes.push(`Read the first ${LIMITS.maxChildSitemaps} of ${children.length} child sitemaps.`)
    }
    urlsets = []
    let collected = 0
    for (const child of children.slice(0, LIMITS.maxChildSitemaps)) {
      if (collected >= maxPages) {
        break
      }
      let parsed
      try {
        parsed = parseSitemap(await fetchSitemapText(child))
      } catch (error) {
        notes.push(`Skipped child sitemap ${child}: ${error.message}`)
        continue
      }
      if (parsed.kind === "index") {
        notes.push(`Skipped nested sitemap index ${child}.`)
        continue
      }
      if (parsed.truncated) {
        notes.push(`Read only the first ${LIMITS.maxLocsPerSitemap} <loc> entries of ${child}.`)
      }
      urlsets.push(parsed)
      collected += parsed.locs.length
    }
  }

  const pages = new Set()
  let skippedOtherHost = 0
  let available = 0
  for (const { locs } of urlsets) {
    for (const loc of locs) {
      const pageURL = sameHostPageURL(loc, hostname)
      if (!pageURL) {
        skippedOtherHost += 1
      } else if (!pages.has(pageURL)) {
        available += 1
        if (pages.size < maxPages) {
          pages.add(pageURL)
        }
      }
    }
  }
  if (skippedOtherHost) {
    notes.push(`<loc> entries skipped (not public URLs on ${hostname}): ${skippedOtherHost}`)
  }
  if (available > pages.size) {
    notes.push(`Checked the first ${pages.size} of ${available} unique page URLs (--max-pages).`)
  }
  return { hostname, pageURLs: [...pages], notes }
}

function safeHostname(value) {
  try {
    return new URL(value).hostname.toLowerCase()
  } catch {
    return ""
  }
}

export function resolveCheckerCLI() {
  try {
    return createRequire(import.meta.url).resolve("myog-checker/dist/cli.js")
  } catch {
    throw new AuditError(
      "myog-checker is not installed here. Run: npm install myog-checker@0.1.1 htmlparser2@10.0.0"
    )
  }
}

// One child process per page: the CLI checks one URL per run.
export function runChecker({ checkerCLI, pageURL }) {
  return new Promise((resolve) => {
    const child = spawn(process.execPath, [checkerCLI, "check", pageURL, "--json"], {
      stdio: ["ignore", "pipe", "ignore"],
    })
    let output = ""
    let size = 0
    let failure = ""
    const timer = setTimeout(() => {
      failure = "checker_timeout"
      child.kill("SIGKILL")
    }, LIMITS.checkerTimeoutMS)
    child.stdout.setEncoding("utf8").on("data", (chunk) => {
      size += Buffer.byteLength(chunk)
      if (size > LIMITS.maxCheckerOutputBytes) {
        failure = "checker_output_too_large"
        child.kill("SIGKILL")
      } else {
        output += chunk
      }
    })
    child.on("error", () => {
      failure ||= "checker_not_started"
    })
    child.on("close", () => {
      clearTimeout(timer)
      if (failure) {
        resolve({ ok: false, code: failure })
        return
      }
      try {
        const result = JSON.parse(output)
        if (result?.schemaVersion !== 1 || typeof result.ok !== "boolean") {
          resolve({ ok: false, code: "checker_unexpected_output" })
        } else if (!result.ok) {
          resolve({ ok: false, code: String(result.error?.code ?? "checker_failed") })
        } else {
          resolve({ ok: true, result })
        }
      } catch {
        resolve({ ok: false, code: "checker_invalid_json" })
      }
    })
  })
}

function imageSource(tags) {
  if (tags["og:image"] || tags["og:image:url"] || tags["og:image:secure_url"]) {
    return "og:image"
  }
  return tags["twitter:image"] ? "twitter:image" : "none"
}

// myog-checker replaces query strings with ?REDACTED, so two image URLs that
// differ only in their query cannot be told apart and are reported separately.
export function groupPages(pageResults) {
  const failed = []
  const httpErrors = []
  const missing = []
  const byImage = new Map()
  const queryRedacted = new Map()
  for (const page of pageResults) {
    if (!page.check.ok) {
      failed.push({ url: page.url, code: page.check.code })
      continue
    }
    const { http, metadata, tags } = page.check.result
    if (http.statusCode >= 400) {
      httpErrors.push({ url: page.url, statusCode: http.statusCode })
      continue
    }
    if (!metadata.imageURL) {
      missing.push({ url: page.url })
      continue
    }
    const entry = { url: page.url, source: imageSource(tags) }
    const target = metadata.imageURL.endsWith("?REDACTED") ? queryRedacted : byImage
    target.set(metadata.imageURL, [...(target.get(metadata.imageURL) ?? []), entry])
  }
  const sortGroups = (groups) =>
    [...groups.entries()]
      .map(([imageURL, pages]) => ({ imageURL, pages }))
      .sort((a, b) => b.pages.length - a.pages.length || a.imageURL.localeCompare(b.imageURL))
  const groups = sortGroups(byImage)
  const redactedGroups = sortGroups(queryRedacted)
  // A redacted URL used by one page still has its own path, so it is unique.
  const uniqueRedacted = redactedGroups.filter((group) => group.pages.length === 1)
  return {
    checked: pageResults.length,
    shared: groups.filter((group) => group.pages.length > 1),
    unique: groups.filter((group) => group.pages.length === 1).length + uniqueRedacted.length,
    missing,
    queryRedacted: redactedGroups.filter((group) => group.pages.length > 1),
    twitterOnly: [...groups, ...redactedGroups]
      .flatMap((group) => group.pages)
      .filter((page) => page.source === "twitter:image")
      .map((page) => page.url),
    httpErrors,
    failed,
  }
}

function sleep(ms) {
  return new Promise((resolve) => setTimeout(resolve, ms))
}

export async function runAudit({ pageURLs, checkerCLI, delayMS, onProgress = () => {} }) {
  const pageResults = []
  for (const [index, url] of pageURLs.entries()) {
    if (index > 0 && delayMS > 0) {
      await sleep(delayMS)
    }
    onProgress({ index, total: pageURLs.length, url })
    pageResults.push({ url, check: await runChecker({ checkerCLI, pageURL: url }) })
  }
  return groupPages(pageResults)
}

function listPages(pages, describe = (page) => page.url) {
  const shown = pages.slice(0, LIMITS.maxListedPagesPerGroup).map((page) => `    ${describe(page)}`)
  const hidden = pages.length - shown.length
  return hidden > 0 ? [...shown, `    ...and ${hidden} more`] : shown
}

function countPages(groups) {
  return groups.reduce((sum, group) => sum + group.pages.length, 0)
}

export function formatReport({ hostname, notes, report }) {
  const lines = [
    `Pages checked on ${hostname}: ${report.checked}`,
    `  Sharing an image URL: ${countPages(report.shared)}`,
    `  Shared image URLs: ${report.shared.length}`,
    `  With a unique image URL: ${report.unique}`,
    `  With no image URL: ${report.missing.length}`,
    `  Not compared (query-string image URLs): ${countPages(report.queryRedacted)}`,
    `  HTTP errors: ${report.httpErrors.length}`,
    `  Failed checks: ${report.failed.length}`,
  ]
  for (const group of report.shared) {
    lines.push(
      "",
      `Shared by ${group.pages.length} pages: ${group.imageURL}`,
      ...listPages(group.pages)
    )
  }
  if (report.missing.length) {
    lines.push("", "No og:image or twitter:image:", ...listPages(report.missing))
  }
  for (const group of report.queryRedacted) {
    lines.push(
      "",
      `Cannot compare (query string redacted by the checker), ${group.pages.length} pages: ${group.imageURL}`,
      ...listPages(group.pages)
    )
  }
  if (report.twitterOnly.length) {
    lines.push(
      "",
      "Image from twitter:image only (no og:image tag):",
      ...listPages(report.twitterOnly.map((url) => ({ url })))
    )
  }
  if (report.httpErrors.length) {
    lines.push(
      "",
      "HTTP errors (not grouped):",
      ...listPages(report.httpErrors, (page) => `${page.statusCode} ${page.url}`)
    )
  }
  if (report.failed.length) {
    lines.push(
      "",
      "Checks that failed (not grouped):",
      ...listPages(report.failed, (page) => `${page.code} ${page.url}`)
    )
  }
  if (notes.length) {
    lines.push("", "Notes:", ...notes.map((note) => `  ${note}`))
  }
  lines.push(
    "",
    "Image files were not fetched. A shared URL can still serve different bytes, and a unique URL can still be broken."
  )
  return lines.join("\n")
}

function parseOptions(args) {
  const { values, positionals } = parseArgs({
    args,
    allowPositionals: true,
    strict: true,
    options: {
      "max-pages": { type: "string" },
      "delay-ms": { type: "string" },
      host: { type: "string" },
      json: { type: "boolean" },
      strict: { type: "boolean" },
      "checker-cli": { type: "string" },
      help: { type: "boolean", short: "h" },
    },
  })
  const maxPages = Number(values["max-pages"] ?? LIMITS.defaultMaxPages)
  const delayMS = Number(values["delay-ms"] ?? LIMITS.defaultDelayMS)
  if (values.help) {
    return { help: true }
  }
  if (
    positionals.length !== 1 ||
    !Number.isInteger(maxPages) ||
    maxPages < 1 ||
    maxPages > LIMITS.maxPages ||
    !Number.isInteger(delayMS) ||
    delayMS < 0 ||
    delayMS > 60_000
  ) {
    throw new TypeError("invalid arguments")
  }
  return { source: positionals[0], maxPages, delayMS, ...values }
}

async function main() {
  let options
  try {
    options = parseOptions(process.argv.slice(2))
  } catch {
    console.error(`Invalid arguments.\n\n${HELP}`)
    process.exitCode = 2
    return
  }
  if (options.help) {
    console.log(HELP)
    return
  }
  try {
    const checkerCLI = options["checker-cli"] ?? resolveCheckerCLI()
    const { hostname, pageURLs, notes } = await collectPageURLs({
      source: options.source,
      maxPages: options.maxPages,
      host: options.host,
    })
    if (pageURLs.length === 0) {
      throw new AuditError(
        [
          `No page URLs on ${hostname} in the sitemap. If pages use another hostname (for example www.), pass --host.`,
          ...notes,
        ].join("\n")
      )
    }
    const report = await runAudit({
      pageURLs,
      checkerCLI,
      delayMS: options.delayMS,
      onProgress: ({ index, total }) => {
        if (process.stderr.isTTY) {
          process.stderr.write(`\rChecking ${index + 1}/${total}`)
        }
      },
    })
    if (process.stderr.isTTY) {
      process.stderr.write("\n")
    }
    console.log(
      options.json
        ? JSON.stringify({ hostname, notes, ...report }, null, 2)
        : formatReport({ hostname, notes, report })
    )
    if (options.strict && (report.shared.length || report.missing.length)) {
      process.exitCode = 3
    }
  } catch (error) {
    if (!(error instanceof AuditError)) {
      throw error
    }
    console.error(`Error: ${error.message}`)
    process.exitCode = 1
  }
}

if (process.argv[1] && import.meta.url === pathToFileURL(realpathSync(process.argv[1])).href) {
  await main()
}
