#!/bin/bash
# phone-home-check.sh
# Psychosonic Lab, experiment 01: does it phone home?
#
# Two checks you can run on your own Mac, with tools that ship with macOS.
# Nothing here sends anything anywhere, and it needs no sudo.
#
#   ./phone-home-check.sh entitlements /Applications/Bibliome.app [more .app paths]
#       What the app's signature allows it to do on a network. The main app and
#       every executable bundled inside it are listed, because a helper can hold
#       an entitlement the main app does not.
#
#   ./phone-home-check.sh watch /Applications/Bibliome.app 120 out.csv
#       Samples the app's open sockets (and those of its helpers) every half
#       second for 120 seconds and writes every distinct endpoint it saw.
#       Run your workload while it samples: index a folder, ask a question.
#
# Read the limits before trusting a quiet result. The page that goes with this
# script lists them: https://psychosonicconsulting.com/lab/phone-home

set -u

usage() {
  sed -n '2,22p' "$0" | sed 's/^# \{0,1\}//'
  exit 2
}

plist_value() { /usr/libexec/PlistBuddy -c "Print :$2" "$1" 2>/dev/null; }

# Prints one tab-separated row for one piece of signed code:
#   code  version  build  network.client  network.server  inherits_sandbox  icloud  testflight
# An app bundle gets its version and build. A loose executable inside it gets "-".
entitlement_row() {
  local target="$1" label="$2" info ent ver build client server icloud inherit beta
  info="$target/Contents/Info.plist"
  if [ -f "$info" ]; then
    ver=$(plist_value "$info" CFBundleShortVersionString); [ -n "$ver" ] || ver="-"
    build=$(plist_value "$info" CFBundleVersion);          [ -n "$build" ] || build="-"
  else
    ver="-"; build="-"
  fi
  ent=$(codesign -d --entitlements :- "$target" 2>/dev/null)
  has() { printf '%s' "$ent" | tr -d '\n\t ' | grep -q "<key>$1</key><true/>" && echo yes || echo no; }
  client=$(has com.apple.security.network.client)
  server=$(has com.apple.security.network.server)
  # A helper that holds com.apple.security.inherit runs inside its parent's sandbox
  # and has no network rights of its own to declare.
  inherit=$(has com.apple.security.inherit)
  # iCloud is a list of container ids, not a true/false entitlement, and the
  # system (not the app) does the transfer. It is listed because a socket sample
  # of the app would never see that traffic.
  printf '%s' "$ent" | grep -q "com.apple.developer.icloud-container-identifiers" && icloud=yes || icloud=no
  beta=$(has beta-reports-active)
  printf '%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\n' "$label" "$ver" "$build" "$client" "$server" "$inherit" "$icloud" "$beta"
}

cmd_entitlements() {
  [ $# -ge 1 ] || usage
  printf 'code\tversion\tbuild\tnetwork.client\tnetwork.server\tinherits_sandbox\ticloud\ttestflight_build\n'
  local app base f
  for app in "$@"; do
    [ -d "$app" ] || { echo "not found: $app" >&2; continue; }
    app="${app%/}"
    base=$(dirname "$app")
    entitlement_row "$app" "${app#$base/}"
    # Every executable bundled inside: helpers, extensions, XPC services, an
    # interpreter. A helper can hold an entitlement the main app does not. The
    # main executable is already covered by the app's own row.
    find "$app/Contents" -type f -perm +111 -not -name '*.dylib' -not -name '*.so' -not -name '*.a' \
         2>/dev/null | sort | while read -r f; do
      file -b "$f" | grep -q 'Mach-O.*executable' || continue
      [ "$f" = "$app/Contents/MacOS/$(basename "$app" .app)" ] && continue
      entitlement_row "$f" "${f#$base/}"
    done
  done
}

# The app's own processes: its main executable, its XPC services and extensions,
# and every child of those. Deliberately NOT every process whose command line
# mentions the bundle. A connector script that another program (an AI app, say)
# launches out of the bundle is that program's process, and counting it here
# would blame the app for the other program's traffic.
app_pids() {
  local app="$1" roots all frontier next p kids
  roots=$(pgrep -f "$app/Contents/(MacOS|XPCServices|PlugIns)/" 2>/dev/null | tr '\n' ' ')
  all="$roots"; frontier="$roots"
  while [ -n "${frontier// /}" ]; do
    next=""
    for p in $frontier; do
      kids=$(pgrep -P "$p" 2>/dev/null | tr '\n' ' ')
      next="$next $kids"
    done
    frontier=$(echo $next)
    all="$all $frontier"
  done
  echo $all | tr ' ' '\n' | sort -un | tr '\n' ' '
}

cmd_watch() {
  [ $# -ge 3 ] || usage
  local app="$1" seconds="$2" out="$3"
  [ -d "$app" ] || { echo "not found: $app" >&2; exit 1; }
  local raw; raw=$(mktemp -t phonehome)
  local started; started=$(date +%s)
  local now pids lines
  echo "watching $app for ${seconds}s. Run your workload now." >&2
  while :; do
    now=$(date +%s)
    [ $((now - started)) -ge "$seconds" ] && break
    pids=$(app_pids "$app")
    if [ -n "${pids// /}" ]; then
      lines=$(lsof -nP -i -a -p "$(echo $pids | tr ' ' ',')" 2>/dev/null | tail -n +2)
      if [ -n "$lines" ]; then
        printf '%s\n' "$lines" | awk -v t="$((now - started))" '{print t "\t" $0}' >> "$raw"
      fi
    fi
    sleep 0.5
  done

  # Reduce the samples to one row per distinct endpoint and classify it.
  awk -F'\t' '
    function cls(addr,   a, o) {
      gsub(/^\[|\]$/, "", addr)
      if (addr == "*" || addr == "") return "any"
      if (addr ~ /^127\./ || addr == "::1") return "loopback"
      if (addr ~ /^10\./ || addr ~ /^192\.168\./ || addr ~ /^172\.(1[6-9]|2[0-9]|3[01])\./) return "private"
      if (addr ~ /^169\.254\./ || addr ~ /^[fF][eE]80:/) return "link-local"
      if (addr ~ /^22[4-9]\./ || addr ~ /^23[0-9]\./ || addr ~ /^[fF][fF]/) return "multicast"
      if (addr ~ /^[fF][cCdD]/) return "private"
      return "PUBLIC"
    }
    function host(ep,   h) {
      h = ep; sub(/:([0-9]+|\*)$/, "", h); return h
    }
    {
      t = $1; n = split($2, f, /[ ]+/)
      proc = f[1]; pid = f[2]; type = f[5]; proto = ""
      for (i = 1; i <= n; i++) if (f[i] == "TCP" || f[i] == "UDP") proto = f[i]
      name = ""; state = ""
      for (i = 9; i <= n; i++) {
        if (f[i] ~ /^\(/) state = f[i]
        else name = (name == "" ? f[i] : name " " f[i])
      }
      if (proto == "") next
      # A socket that is closed or was never bound is not a connection or a listener.
      if (state == "(CLOSED)" || name == "*:*") next
      if (index(name, "->")) {
        split(name, e, "->"); kind = "connect"; local = e[1]; remote = e[2]
        c = cls(host(remote))
      } else {
        kind = "listen"; local = name; remote = "-"; c = cls(host(local))
        if (c == "any") c = "any-interface"
      }
      key = proc "|" proto "|" kind "|" local "|" remote
      if (kind == "connect") key = proc "|" proto "|" kind "|" "-" "|" remote
      if (!(key in seen)) { seen[key] = 1; order[++m] = key; first[key] = t; klass[key] = c }
    }
    END {
      print "process,protocol,kind,local,remote,class,first_seen_s"
      for (i = 1; i <= m; i++) {
        k = order[i]; split(k, p, "|")
        printf "%s,%s,%s,%s,%s,%s,%s\n", p[1], p[2], p[3], p[4], p[5], klass[k], first[k]
      }
    }' "$raw" > "$out"
  rm -f "$raw"

  local rows public
  rows=$(($(wc -l < "$out") - 1))
  public=$(awk -F, 'NR>1 && $6=="PUBLIC"' "$out" | wc -l | tr -d ' ')
  echo "distinct endpoints seen: $rows" >&2
  echo "to a PUBLIC address:     $public" >&2
  echo "written to $out" >&2
  if [ -z "$(app_pids "$app" | tr -d ' ')" ]; then
    echo "note: no running process was found for this app at the end of the run." >&2
    echo "      an empty result is only meaningful if the app was running throughout." >&2
  fi
}

case "${1:-}" in
  entitlements) shift; cmd_entitlements "$@" ;;
  watch)        shift; cmd_watch "$@" ;;
  *)            usage ;;
esac
