← back to Charge And Explore

scripts/register-when-ready.sh

56 lines

#!/bin/bash
# Poll Tesla partner-token endpoint until the app's audience activates, then
# fire the one-time partner_accounts registration and verify it.
# Registration POST pre-approved by Steve (email "Go dust2026" + "Fix for me", 2026-08-01, TK-10111).
set -u
cd "$(dirname "$0")/.." || exit 1
set -a; source .env; set +a

DOMAIN="chargeandexplore.agentabrams.com"
LOG="data/register-when-ready.log"
INTERVAL=300          # 5 min
MAX_TRIES=144         # 12 hours
mkdir -p data

say() { echo "[$(date '+%Y-%m-%d %H:%M:%S')] $*" | tee -a "$LOG"; }

get_token() { # $1 = token endpoint
  # NOTE (2026-08-01, REGISTRATION COMPLETE): never send an `audience` param.
  # With both NA+EU regions selected, Tesla stores the app's allowed audience as
  # ONE space-joined string ("...na... ...eu..."), so any single-region audience
  # fails invalid_audience. Omitting the param returns a token valid for both.
  curl -s -X POST "$1" \
    -H 'Content-Type: application/x-www-form-urlencoded' \
    --data-urlencode grant_type=client_credentials \
    --data-urlencode "client_id=$TESLA_CLIENT_ID" \
    --data-urlencode "client_secret=$TESLA_CLIENT_SECRET" \
    --data-urlencode "scope=openid vehicle_device_data"
}

for i in $(seq 1 "$MAX_TRIES"); do
  for EP in https://auth.tesla.com/oauth2/v3/token https://fleet-auth.prd.vn.cloud.tesla.com/oauth2/v3/token; do
    RESP=$(get_token "$EP")
    TOKEN=$(echo "$RESP" | python3 -c 'import sys,json;print(json.load(sys.stdin).get("access_token",""))' 2>/dev/null)
    if [ -n "$TOKEN" ]; then
      say "TOKEN OK via $EP (attempt $i) — firing partner registration"
      REG=$(curl -s -w '\n%{http_code}' -X POST "$TESLA_AUDIENCE/api/1/partner_accounts" \
        -H "Authorization: Bearer $TOKEN" -H 'Content-Type: application/json' \
        -d "{\"domain\":\"$DOMAIN\"}")
      CODE=$(echo "$REG" | tail -1); BODY=$(echo "$REG" | sed '$d')
      say "REGISTRATION HTTP $CODE: $BODY"
      VER=$(curl -s "$TESLA_AUDIENCE/api/1/partner_accounts/public_key?domain=$DOMAIN" \
        -H "Authorization: Bearer $TOKEN")
      say "VERIFY public_key: $VER"
      if [ "$CODE" = "200" ] || [ "$CODE" = "201" ]; then
        say "SUCCESS — partner registration complete"; exit 0
      else
        say "REGISTRATION FAILED after token success"; exit 2
      fi
    fi
  done
  ERR=$(echo "$RESP" | python3 -c 'import sys,json;print(json.load(sys.stdin).get("error","?"))' 2>/dev/null)
  [ $((i % 6)) -eq 1 ] && say "attempt $i/$MAX_TRIES: still $ERR"
  sleep "$INTERVAL"
done
say "TIMEOUT — audience never activated within 12h"; exit 3