#!/bin/bash # Log splitter for monitor-unauthorized # Extracts unauthorized WebSocket connection entries from the gateway log # into a dedicated log file for efficient incremental processing. # # Usage: # bash log-splitter.sh — extract recent entries (batch mode) # bash log-splitter.sh --full — re-extract from entire log (rebuild) # # Filters for log lines containing: # - "forwardedFor" AND ("unauthorized" OR "pairing-required") # # Output: /tmp/openclaw/unauthorized-connections.log # Each line is a valid JSON object extracted from the gateway log. set -e GATEWAY_LOG="/tmp/openclaw/openclaw.log" UNAUTH_LOG="/tmp/openclaw/unauthorized-connections.log" STATE_DIR="/home/node/.openclaw/workspace-security/memory" OFFSET_FILE="$STATE_DIR/unauth-splitter-offset" mkdir -p "$STATE_DIR" touch "$UNAUTH_LOG" FULL_MODE=false [ "${1:-}" = "--full" ] && FULL_MODE=true if [ ! -f "$GATEWAY_LOG" ]; then echo '{"error":"Gateway log not found","log":"'"$GATEWAY_LOG"'"}' >&2 exit 1 fi FILE_SIZE=$(stat -c%s "$GATEWAY_LOG") # Determine where to start reading LAST_OFFSET=0 if [ -f "$OFFSET_FILE" ] && [ "$FULL_MODE" != "true" ]; then LAST_OFFSET=$(cat "$OFFSET_FILE") fi # If file shrank (log rotation), reset if [ "$LAST_OFFSET" -gt "$FILE_SIZE" ]; then LAST_OFFSET=0 fi BYTES_NEW=$((FILE_SIZE - LAST_OFFSET)) if [ "$BYTES_NEW" -le 0 ]; then echo "$FILE_SIZE" > "$OFFSET_FILE" echo '{"new_lines":0,"total_lines":'$(wc -l < "$UNAUTH_LOG" | tr -d ' ')'}' exit 0 fi # Extract unauthorized connection lines from new bytes # Filter: must have forwardedFor AND be unauthorized/pairing-required NEW_LINES=0 TMPFILE=$(mktemp) trap "rm -f $TMPFILE" EXIT tail -c +"$((LAST_OFFSET + 1))" "$GATEWAY_LOG" \ | grep '"forwardedFor"' \ | grep -E '"unauthorized"|"pairing-required"' \ > "$TMPFILE" 2>/dev/null || true NEW_LINES=$(wc -l < "$TMPFILE" | tr -d ' ') if [ "$NEW_LINES" -gt 0 ]; then cat "$TMPFILE" >> "$UNAUTH_LOG" fi # Save new offset echo "$FILE_SIZE" > "$OFFSET_FILE" TOTAL_LINES=$(wc -l < "$UNAUTH_LOG" | tr -d ' ') echo "{\"new_lines\":$NEW_LINES,\"total_lines\":$TOTAL_LINES}"