Apple platform development toolkit — build, deploy, debug, device management for Xcode projects; Apple Developer Portal automation via Safari (Sign In / OAuth setup, and agreement acceptance to unblock notarization when the Program License Agreement updates)

version
1.2.0

Install

/plugin install che-apple-dev@psychquant-claude-plugins

Run it inside Claude Code after adding the marketplace with /plugin marketplace add PsychQuant/psychquant-claude-plugins.

Contents

Discovered from source

Skills 5

Apple Agreement Accept — unblock notarization

When Apple updates the Apple Developer Program License Agreement, notarization stops with HTTP 403 "A required agreement is missing or has expired" until the account holder accepts the new version. The Developer ID certificate and the keychain notary profile are fine — only the legal agreement is stale. This skill drives the acceptance via Safari (which holds the logged-in developer session), then resumes the release.

The single most important gotcha: after you accept, notarytool's 403 can persist for several minutes (Apple's notary service caches agreement status and lags the portal). Poll — do not conclude failure on the first 403. This nearly caused a false "you must fix it manually" verdict during the discovery run.

Step 0 — Triage the error (don't guess)

xcrun notarytool history --keychain-profile "$NOTARY_PROFILE" 2>&1 | head -3
OutputMeaningAction
Successfully received submission history.Agreements fineNothing to do — go straight to the release
HTTP status code: 403 ... required agreement ... missing or has expiredAgreement staleThis skill
HTTP status code: 401 ... Invalid credentialsApp-specific password / API key revoked or expiredNOT this skill — user re-runs xcrun notarytool store-credentials <profile> (user-only; never echo the password)

Only continue past Step 0 on a 403 agreement error.

Step 1 — Open the developer account + check login

safari-browser open "https://developer.apple.com/account"
sleep 3
safari-browser documents | grep -i apple.com
  • URL ends at developer.apple.com/account (title "Account - Apple Developer") → logged in, continue.
  • URL is idmsa.apple.com/IDMSWebAuth/signin... → not logged in. Login (Apple ID + password + 2FA) is user-only — ask the user to log in in that Safari tab, then continue. Never handle the Apple password or 2FA code.

Step 2 — Find the agreement banner (use JS, not just snapshot)

The "Review agreement" banner is rendered async by an SPA and is effectively one-shot: it shows on the first post-login load and often will NOT re-render on reloads after you've entered the review flow once. snapshot -i / get text can miss it — query the live DOM instead:

safari-browser js --url-endswith "/account" '
(function(){
  var out=[];
  document.querySelectorAll("button,a,[role=button]").forEach(function(e){
    var t=(e.innerText||e.textContent||"").trim();
    if(/review agreement|agree/i.test(t)&&t.length<40)out.push(e.tagName+"["+t+"]");
  });
  var hasBanner=/program license agreement has been updated|regain access/i.test(document.body.innerText||"");
  return "banner="+hasBanner+" | "+(out.join(" ;; ")||"NONE");
})()'
  • Banner present + a "Review agreement" control → Step 3.
  • Banner gone but notarytool still 403 → Step 5 (re-trigger), or the agreement may already be accepted and only propagation is pending (Step 4).

Step 3 — Review → Agree

  1. Click "Review agreement" (grab a fresh ref each time — refs shift):
    REF=$(safari-browser snapshot -i --url-endswith "/account" | grep -i '"Review agreement"' | grep -oE '@e[0-9]+' | head -1)
    safari-browser click "$REF" --url-endswith "/account"
    sleep 3
    
    This lands on developer.apple.com/account/agree/<token>/terms with an Agree button. (Acceptance per Apple's own terms = clicking "Agree"; the only checkboxes on the page are marketing email opt-ins — leave them unchecked.)
  2. Transparency / consent: this is a legal acceptance on the user's behalf. Surface which agreement (read the page heading) and confirm before clicking Agree via AskUserQuestion — UNLESS the user has already explicitly authorized you to accept it.
  3. Click Agree (verify the ref is non-empty first — an empty ref silently no-ops):
    AREF=$(safari-browser snapshot -i --url "developer.apple.com/account/agree" | grep -iE '"Agree"' | grep -i submit | grep -oE '@e[0-9]+' | head -1)
    [ -n "$AREF" ] && safari-browser click "$AREF" --url "developer.apple.com/account/agree"
    

Step 4 — Poll notarytool until the 403 clears (THE gotcha)

Acceptance propagates to the notary service with a lag. Poll, don't give up:

for i in $(seq 1 10); do
  if xcrun notarytool history --keychain-profile "$NOTARY_PROFILE" 2>&1 | grep -q "Successfully received"; then
    echo "✅ agreement effective — notarization unblocked"; break
  fi
  echo "still 403 (propagation lag), retry $i/10..."; sleep 45
done

A reliable secondary signal that the portal side is satisfied: the Certificates page loads without an agreement gate (developer.apple.com/account/resources/certificates/list).

Step 5 — If the banner won't surface

  • Hit a gated resource to re-trigger the acceptance interstitial: safari-browser open "https://developer.apple.com/account/resources/certificates/list" then re-check Step 2's JS. (If Certificates loads cleanly with no gate, the portal agreement is likely already satisfied → it's a Step 4 propagation lag, keep polling.)
  • Re-login (log out / back in) re-triggers the first-load banner — user-only.
  • Multi-tab --url ambiguity: repeated safari-browser open spawns duplicate tabs; --url developer.apple.com/account then matches several and errors. Use --url-endswith "/account", or safari-browser close --url "..." --first-match to collapse duplicates first.

Step 6 — Resume the release

Once Step 4 shows "Successfully received", continue where the release left off:

export DEVELOPER_ID="<sha1>"; export NOTARY_PROFILE="<profile>"
make release-signed VERSION=vX.Y.Z   # build → sign → notarize → tag → upload

Iron rules

  • Never handle the Apple ID password or 2FA — login is user-only.
  • Confirm before the Agree click unless the user explicitly authorized acceptance — it is an irreversible legal action.
  • Never do an unsigned/ad-hoc release to "work around" this — on macOS 26 an ad-hoc binary cannot trigger TCC grants and breaks Full Disk Access for users. The agreement must be accepted so notarization can complete.
  • Poll for propagation (Step 4) — a single 403 right after acceptance is not failure.

Apple OAuth Setup

Automate Apple Sign In for Web configuration via Safari + AppleScript. Covers the full chain: App ID → Services ID → Key (.p8) → JWT client secret.

Prerequisites

  • Apple Developer Program (paid, $99/year) — Personal Team won't work
  • Safari logged into developer.apple.com (user handles 2FA manually)
  • Python 3 with PyJWT for JWT generation (pip install pyjwt)

Overview

Apple Sign In for Web requires four things registered on Apple Developer Portal:

  1. App ID — with Sign In with Apple capability enabled
  2. Services ID — the client_id for web OAuth
  3. Key (.p8 file) — used to generate JWT client secrets
  4. JWT client secret — what your OAuth backend (Supabase, etc.) actually uses

Step 1: Open Apple Developer Portal

tell application "Safari" to activate
tell application "Safari" to open location "https://developer.apple.com/account"

Wait for user to complete login + 2FA, then verify:

tell application "Safari" to do JavaScript "document.title" in front document

Should contain "Account - Apple Developer" or similar.

Step 2: Get Team Info

# From Xcode provisioning
defaults read com.apple.dt.Xcode IDEProvisioningTeams 2>/dev/null
# Or from signing identity
security find-identity -v -p codesigning 2>/dev/null

Note the Team ID (10-character alphanumeric like 6W377FS7BS).

Step 3: Create App ID

Navigate to register App ID:

tell application "Safari" to set URL of front document to "https://developer.apple.com/account/resources/identifiers/add/bundleId"

Select "App IDs" → "App" type → Continue. Then fill the form:

// Fill Description and Bundle ID using native setter (framework-safe)
(function() {
  var setter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value").set;

  var desc = document.getElementById("description");
  setter.call(desc, "YOUR_APP_NAME");
  desc.dispatchEvent(new InputEvent("input", {bubbles: true, inputType: "insertText"}));
  desc.dispatchEvent(new Event("change", {bubbles: true}));

  var ident = document.getElementById("identifier");
  setter.call(ident, "com.yourdomain.appname");
  ident.dispatchEvent(new InputEvent("input", {bubbles: true, inputType: "insertText"}));
  ident.dispatchEvent(new Event("change", {bubbles: true}));
})();

Enable Sign In with Apple in the capabilities list:

(function() {
  var checkboxes = document.querySelectorAll("input[type=checkbox]");
  for (var i = 0; i < checkboxes.length; i++) {
    var row = checkboxes[i].closest("tr, li, div");
    if (row && row.textContent.includes("Sign In with Apple")) {
      checkboxes[i].click();
      return "enabled";
    }
  }
  return "not found";
})();

Click Continue → Register.

Step 4: Create Services ID

Navigate:

tell application "Safari" to set URL of front document to "https://developer.apple.com/account/resources/identifiers/add/serviceId"

On the type selection page, select "Services IDs" (radio index 1 in ul.form-radio-list):

(function() {
  var lis = document.querySelectorAll("ul.form-radio-list > li");
  var radio = lis[1].querySelector("input[type=radio]"); // Services IDs
  radio.click();
})();

Click Continue, then fill:

  • Description: e.g. "My App Sign In with Apple"
  • Identifier: e.g. "com.yourdomain.auth" (this becomes the OAuth client_id)

Register, then click into the new Services ID to edit. Enable Sign In with Apple checkbox, click Configure.

Configure Web Authentication

The Configure dialog uses a React Select dropdown for Primary App ID:

// Open the dropdown
(function() {
  var input = document.getElementById("react-select-2-input");
  input.focus();
  input.dispatchEvent(new KeyboardEvent("keydown", {bubbles: true, key: "ArrowDown", keyCode: 40}));
})();

Then select the first option:

(function() {
  var option = document.getElementById("react-select-2-option-0");
  if (option) { option.click(); return option.textContent.trim(); }
  return "no option";
})();

Fill domain and return URL (the native setter + InputEvent pattern is required because the form uses a JS framework):

(function() {
  var setter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value").set;

  var domain = document.getElementById("domainsInput");
  setter.call(domain, "YOUR_SUPABASE_REF.supabase.co");
  domain.dispatchEvent(new InputEvent("input", {bubbles: true, inputType: "insertText"}));
  domain.dispatchEvent(new Event("change", {bubbles: true}));

  var urls = document.getElementById("urlsInput");
  setter.call(urls, "https://YOUR_SUPABASE_REF.supabase.co/auth/v1/callback");
  urls.dispatchEvent(new InputEvent("input", {bubbles: true, inputType: "insertText"}));
  urls.dispatchEvent(new Event("change", {bubbles: true}));
})();

Click Next → Done → Continue → Save.

Step 5: Create Key (.p8)

Navigate:

tell application "Safari" to set URL of front document to "https://developer.apple.com/account/resources/authkeys/add"

Fill key name, enable Sign In with Apple, Configure (select App ID via React Select as above), then Continue → Register.

Download the Key

The download page appears once. Click Download — Safari will show a permission dialog "要允許在 developer.apple.com 上下載嗎?". Handle it with AppleScript:

tell application "System Events"
  tell process "Safari"
    set allElems to entire contents of window 1
    repeat with elem in allElems
      try
        if class of elem is button and name of elem is "允許" then
          click elem
          exit repeat
        end if
      end try
    end repeat
  end tell
end tell

Important: Standard sheet or group traversal won't find this button — entire contents is required.

Verify download:

ls -lt ~/Downloads/AuthKey_*.p8 | head -1

Backup the key:

mkdir -p ~/.appstoreconnect/private_keys/
cp ~/Downloads/AuthKey_KEYID.p8 ~/.appstoreconnect/private_keys/

If Download Missed

If the download page shows "Downloaded" but the file isn't there, click Done, go to Keys list, click the key name to view details — the Download button is still available from the detail page.

Step 6: Generate JWT Client Secret

Apple OAuth backends (Supabase, Firebase, etc.) need a JWT client secret generated from the .p8 key. This JWT expires every 6 months — set a reminder to regenerate.

python3 -c "
import jwt, time

with open('PATH_TO_P8_FILE', 'r') as f:
    private_key = f.read()

headers = {'kid': 'KEY_ID', 'alg': 'ES256'}
payload = {
    'iss': 'TEAM_ID',
    'iat': int(time.time()),
    'exp': int(time.time()) + 86400 * 180,  # 6 months
    'aud': 'https://appleid.apple.com',
    'sub': 'SERVICES_ID'  # e.g. com.yourdomain.auth
}
print(jwt.encode(payload, private_key, algorithm='ES256', headers=headers))
"

Replace:

  • PATH_TO_P8_FILE — path to the downloaded .p8 key
  • KEY_ID — from the Keys page (10-character ID)
  • TEAM_ID — your Apple Developer Team ID
  • SERVICES_ID — the Services ID identifier (e.g. com.yourdomain.auth)

Step 7: Configure OAuth Backend

Supabase

Navigate to Supabase Dashboard → Authentication → Providers → Apple. Use Safari AppleScript to fill the fields:

The provider accordion rows have class cursor-pointer:

// Click Apple row to expand
(function() {
  var rows = document.querySelectorAll("div.cursor-pointer");
  for (var i = 0; i < rows.length; i++) {
    if (rows[i].textContent.includes("Apple")) {
      rows[i].click();
      return "expanded";
    }
  }
})();

Enable the toggle and fill credentials:

(function() {
  // Enable toggle
  var toggle = document.getElementById("EXTERNAL_APPLE_ENABLED");
  if (toggle) toggle.click();

  var setter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value").set;

  // Client ID = Services ID
  var clientId = document.getElementById("EXTERNAL_APPLE_CLIENT_ID");
  setter.call(clientId, "SERVICES_ID");
  clientId.dispatchEvent(new InputEvent("input", {bubbles: true, inputType: "insertText"}));
  clientId.dispatchEvent(new Event("change", {bubbles: true}));

  // Secret = JWT from Step 6
  var secret = document.getElementById("EXTERNAL_APPLE_SECRET");
  setter.call(secret, "JWT_CLIENT_SECRET");
  secret.dispatchEvent(new InputEvent("input", {bubbles: true, inputType: "insertText"}));
  secret.dispatchEvent(new Event("change", {bubbles: true}));
})();

Click Save. Verify the toast says "Successfully updated settings" and Apple shows "Enabled".

Common Issues

ProblemSolution
"No App ID is available" in Services ID configCreate an App ID with Sign In with Apple enabled first (Step 3)
Safari download dialog blocks .p8 downloadUse entire contents AppleScript pattern (Step 5)
Unsupported provider: provider is not enabledApple provider not enabled in Supabase Dashboard
JWT generation fails with No module named 'jwt'pip install pyjwt (not pip install jwt)
Personal Team shown in XcodeNeed paid Apple Developer Program ($99/year)
React Select dropdown won't openFocus input first, dispatch ArrowDown KeyboardEvent
Form values don't persist after settingUse Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value").set + InputEvent, not direct .value =

Credential Summary Template

After setup, save this info for future reference:

Team ID:        ___________
App ID:         com.________
Services ID:    com.________  (this is the OAuth client_id)
Key ID:         ___________
Key backup:     ~/.appstoreconnect/private_keys/AuthKey_KEYID.p8
JWT expires:    YYYY-MM-DD (6 months from generation)

Build & Deploy

One-step build and deploy for Xcode projects.

Execution Steps

Step 1: Detect Project

# Find project.yml (xcodegen) or .xcodeproj
ls project.yml *.xcodeproj 2>/dev/null

If project.yml exists, run xcodegen generate first.

Step 2: Determine Target

Ask if ambiguous:

  • macOS app: build Release → copy to /Applications/ → restart
  • iOS device: build Debug → install via devicectl → launch

Step 3: Build

# macOS
xcodebuild build -project <proj> -scheme <scheme> -configuration Release -destination 'platform=macOS' 2>&1 | grep -E '(error:|warning:|BUILD)'

# iOS device
xcodebuild build -project <proj> -scheme <scheme> -configuration Debug -destination 'generic/platform=iOS' 2>&1 | grep -E '(error:|warning:|BUILD)'

If build fails, show errors and stop.

Step 4: Deploy

macOS
pkill -9 -f <process_name> 2>/dev/null
sleep 1
cp -R "<built_products_dir>/<app>.app" /Applications/
nohup /Applications/<app>.app/Contents/MacOS/<binary> > /dev/null 2>&1 &
iOS Device
# Get device UDID
xcrun xctrace list devices 2>&1 | grep -E 'iPad|iPhone'

# Install + launch
xcrun devicectl device install app --device <udid> "<app_path>" 2>&1
xcrun devicectl device process launch --device <udid> --terminate-existing <bundle_id> 2>&1

Step 5: Verify

Confirm process is running:

ps aux | grep <app_name> | grep -v grep

Report: build time, deploy target, status.

Debug Crash

Deploy iOS app with console capture to diagnose crashes.

When to Use

  • App crashes/閃退 on device
  • Need to see print() output from device
  • Swift fatal errors (misaligned pointer, force unwrap, etc.)
  • Need crash backtrace without full Xcode debugger

Execution Steps

Step 1: Build Debug

xcodebuild build -project <proj> -scheme <scheme> -configuration Debug -destination 'generic/platform=iOS' 2>&1 | grep -E '(error:|BUILD)'

Step 2: Install on Device

xcrun devicectl device install app --device <udid> "<app_path>" 2>&1

Step 3: Launch with Console Capture

This is the key step — --console captures all stdout/stderr:

xcrun devicectl device process launch \
  --device <udid> \
  --terminate-existing \
  --console \
  <bundle_id> 2>&1

The command blocks until the app exits. If the app crashes, the output includes:

  • Fatal error: <message> — Swift runtime errors
  • App terminated due to signal N — crash signals (6=SIGABRT, 11=SIGSEGV, 15=SIGTERM)
  • All print() output from the app

Step 4: Analyze Output

Common crash patterns:

OutputCauseFix
load from misaligned raw pointerUnsafeRawPointer.load with unaligned offsetUse byte-by-byte read
Thread 1: EXC_BAD_ACCESSUse-after-free or null pointerCheck object lifetime
signal 9 (SIGKILL)OOM — system killed for memoryReduce allocations, check for leaks
signal 6 (SIGABRT)Assertion failedCheck guard/precondition
No crash output, app just diesJetsam (memory)Check GPU texture allocation

Step 5: Check Crash Logs (if console doesn't show enough)

# Local crash reports
find ~/Library/Logs/DiagnosticReports -name "*<app>*" -type f | xargs ls -t | head -3

# Read latest
head -100 "<latest_crash_log>"

Step 6: Report

Show:

  • Crash message (if any)
  • Signal number and meaning
  • Relevant print() output before crash
  • Suggested fix

Device Management

Manage connected Apple devices and their apps.

Commands

List Devices

xcrun xctrace list devices 2>&1

Shows: device name, OS version, UDID, online/offline status.

Launch App on Device

xcrun devicectl device process launch \
  --device <udid> \
  --terminate-existing \
  <bundle_id> 2>&1

Add --console to capture stdout/stderr (see debug-crash skill).

Kill App on Device

xcrun devicectl device process launch \
  --device <udid> \
  --terminate-existing \
  <bundle_id> 2>&1
# Then immediately terminate — the --terminate-existing kills the old process

Kill Mac Process

pkill -9 -f <process_name>

Reset TCC Permissions

# Reset Screen Recording permission
tccutil reset ScreenCapture <bundle_id>

# Reset Accessibility
tccutil reset Accessibility <bundle_id>

# Reset all for bundle
tccutil reset All <bundle_id>

Check TCC Status

sqlite3 ~/Library/Application\ Support/com.apple.TCC/TCC.db \
  "SELECT service, auth_value FROM access WHERE client='<bundle_id>'"
auth_valueMeaning
0Denied
2Allowed
3Limited

Common Device Issues

ProblemSolution
"device was not unlocked"Unlock iPad/iPhone, then retry
"unable to launch"Check bundle ID is correct, app is installed
Screen Recording keeps askingApp binary changed — copy to stable path like /Applications/
No devices shownCheck USB cable, trust dialog on device

Sponsors

Details

Marketplace
PsychQuant/psychquant-claude-plugins
Source
plugins/che-apple-dev
Author
Che Cheng
Category
Development

More from PsychQuant/psychquant-claude-plugins

All 42