← back to Sanderson Onboard

scripts/reauth.sh

40 lines

#!/bin/bash
# Headed re-login for the SDG trade portal when the daily cadence flags NEEDS_REAUTH.
#
# TK-10400: the daily harvest now runs through the PERSISTENT openclaw real-Chrome session
# (harvest_trade_openclaw.sh), NOT bundled puppeteer. So re-auth MUST log into that same
# openclaw session — logging into puppeteer's old ROOT/chrome-profile is theater (it never
# touches the session the harvester uses, so the next cron run re-flags NEEDS_REAUTH).
# This opens the SDG login page IN the openclaw Chrome and waits for Steve to sign in there;
# the cookie then persists in the openclaw profile across daily runs until it naturally expires.
set -uo pipefail
export PATH="$HOME/.npm-global/bin:/opt/homebrew/bin:$PATH"
ROOT="$(cd "$(dirname "$0")/.." && pwd)"; DATA="$ROOT/data"
BASE="https://trade.sandersondesigngroup.com/us"

if ! openclaw browser status 2>/dev/null | grep -q "running: true"; then
  echo "openclaw browser is not running. Start it first (openclaw browser start), then rerun this."
  exit 1
fi

echo "Opening the SDG trade login in the openclaw Chrome window — log in there."
openclaw browser open "$BASE/login" >/dev/null 2>&1
sleep 4

find_target(){ openclaw browser tabs --json 2>/dev/null | node -e 'let s="";process.stdin.on("data",d=>s+=d).on("end",()=>{try{const j=JSON.parse(s);const t=(j.tabs||[]).find(x=>x.type==="page"&&/trade\.sandersondesigngroup\.com/.test(x.url||""));process.stdout.write(t?t.targetId:"");}catch(e){}})'; }
SAND="$(find_target)"
[ -z "$SAND" ] && { echo "Could not find/open the SDG tab in openclaw. Open $BASE/login manually in the openclaw window, log in, then rerun."; exit 1; }

echo "Waiting up to 5 min for a logged-in session (openclaw target $SAND)..."
for i in $(seq 1 100); do
  sleep 3
  IN="$(openclaw browser evaluate --timeout 20000 --target-id "$SAND" --fn "() => { const q=document.querySelector('a[href*=\"logout\" i],a[href*=\"signout\" i],a[href*=\"account\" i]'); const h=(document.body.innerText||'').slice(0,3000).toLowerCase(); return (q||h.includes('my account')||h.includes('quick order')||h.includes('sign out'))?'YES':'NO'; }" 2>/dev/null | tr -d '[:space:]"')"
  if [ "$IN" = "YES" ]; then
    rm -f "$DATA/NEEDS_REAUTH"
    echo "LOGGED IN — openclaw session persisted; NEEDS_REAUTH cleared. Daily cadence will resume."
    exit 0
  fi
done
echo "Timed out waiting for login. If you did log in, the daily run will detect it; otherwise rerun this."
exit 1