Skip to content

Instantly share code, notes, and snippets.

@janpreet
Created July 26, 2026 11:33
Show Gist options
  • Select an option

  • Save janpreet/be9f37d013a3f810ee5195328bf65868 to your computer and use it in GitHub Desktop.

Select an option

Save janpreet/be9f37d013a3f810ee5195328bf65868 to your computer and use it in GitHub Desktop.
App Store Connect API helpers: check which account you're authenticated as, seed App Review contact details (fastlane #20538 workaround), and verify store state after a deploy

App Store Connect API helpers (plain Ruby, no gems)

Three small scripts I wrote while moving two unreleased apps from one Apple developer account to another. They exist because the store tooling can report success without having changed anything, so it is worth reading the store state back rather than trusting an exit code.

Write-up: https://janpreet.com/moving-apps-between-apple-accounts

Stdlib only (openssl, net/http, json, base64), so they run on a stock macOS Ruby with no Gemfile and no bundle exec.

Setup

Create an App Store Connect API key under Users and Access > Integrations > App Store Connect API with the App Manager role, and download the .p8 (you get exactly one download). Then:

export ASC_KEY_ID=ABCD123456                              # 10-char key id
export ASC_ISSUER_ID=00000000-0000-0000-0000-000000000000 # differs per account
export ASC_KEY_P8=~/keys/AuthKey_ABCD123456.p8
# or, instead of the path, the same base64 blob you'd put in a CI secret:
# export ASC_KEY_CONTENT=$(base64 -i AuthKey_ABCD123456.p8 | tr -d '\n')

Credentials are only ever read from the environment.

asc_whoami.rb

Which account are these credentials actually for? Run this before debugging anything else.

$ ruby asc_whoami.rb
2 app(s) visible to these credentials:
  My First App    com.example.firstapp    id=1234567890
  My Second App   com.example.secondapp   id=1234567891

After moving apps between accounts, a tool that "cannot find" an app has usually authenticated perfectly, as the wrong identity. Seeing the app list is faster than reading the failure.

asc_seed_review_details.rb

Works around fastlane#20538: the first deliver against a brand new app record dies with [!] No data, because the version's review detail does not exist yet and Apple returns an empty payload instead of an empty object.

Creating the review detail once per version fixes it permanently. It is also just faster than typing the same four fields into four version pages.

REVIEW_FIRST_NAME="Jane" REVIEW_LAST_NAME="Doe" \
REVIEW_PHONE="+1 5550100" REVIEW_EMAIL="review@example.com" \
ruby asc_seed_review_details.rb com.example.firstapp

Pass --dry-run to list the versions it would touch. With no bundle ids it does every app the credentials can see. Creates or updates in place, so it is safe to re-run.

asc_verify_store_state.rb

Reads back the fields a store deploy claims to have set: age rating, Kids Category age band, the privacy policy URL per locale, and builds per platform.

$ ruby asc_verify_store_state.rb
My First App  (com.example.firstapp)
  state=PREPARE_FOR_SUBMISSION  ageRating="FOUR_PLUS"
  age rating non-defaults: {"kidsAgeBand"=>"FIVE_AND_UNDER"}
  en-US: privacyPolicyUrl="https://example.com/privacy/"
  IOS 1.0.0 build 1: VALID  uploaded 2026-01-01T00:00:00-08:00
  TV_OS 1.0 build 2: VALID  uploaded 2026-01-01T00:00:00-08:00

An empty privacy URL is flagged with <-- EMPTY, and the age rating line shows only the values that are not at their harmless default, so the answers that matter do not scroll past in a wall of NONE.

This script is the reason I caught two problems: a lane that printed "applied privacy URL" while silently skipping it, and a Kids age band that was set correctly and then quietly cleared by a later run of the same lane. Both looked like success from the outside.

# Minimal App Store Connect API client: ES256 JWT + a tiny request helper.
# No gems beyond Ruby's stdlib, so it runs anywhere Ruby does (including a
# stock macOS ruby) without a Gemfile.
#
# Credentials come from the environment, never from the source:
# ASC_KEY_ID 10-char key id (App Store Connect > Users and Access > Integrations)
# ASC_ISSUER_ID issuer UUID (same page; differs per account)
# ASC_KEY_P8 path to AuthKey_<KEYID>.p8
# or, instead of ASC_KEY_P8:
# ASC_KEY_CONTENT base64 of the .p8 (what you'd store in a CI secret)
require 'openssl'
require 'base64'
require 'json'
require 'net/http'
module ASC
HOST = 'api.appstoreconnect.apple.com'
def self.env!(name)
ENV[name].to_s.empty? ? abort("missing env var #{name}") : ENV[name]
end
def self.private_key
if (b64 = ENV['ASC_KEY_CONTENT']) && !b64.to_s.empty?
OpenSSL::PKey::EC.new(Base64.decode64(b64))
else
OpenSSL::PKey::EC.new(File.read(File.expand_path(env!('ASC_KEY_P8'))))
end
end
# ES256 JWT. Apple wants a raw r||s signature, while OpenSSL hands back
# DER, so the ASN.1 sequence is unpacked and each half padded to 32 bytes.
def self.token
b64 = ->(s) { Base64.urlsafe_encode64(s).delete('=') }
header = b64.({ alg: 'ES256', kid: env!('ASC_KEY_ID'), typ: 'JWT' }.to_json)
payload = b64.({ iss: env!('ASC_ISSUER_ID'),
exp: Time.now.to_i + 600,
aud: 'appstoreconnect-v1' }.to_json)
der = private_key.sign(OpenSSL::Digest::SHA256.new, "#{header}.#{payload}")
raw = OpenSSL::ASN1.decode(der).value.map { |v| v.value.to_s(2).rjust(32, "\x00") }.join
"#{header}.#{payload}.#{b64.(raw)}"
end
# Returns [status_code, parsed_body]. Never raises on a non-2xx so callers
# can report Apple's own error details, which are usually the useful part.
def self.request(method, path, body = nil)
uri = URI("https://#{HOST}#{path}")
klass = { get: Net::HTTP::Get, post: Net::HTTP::Post,
patch: Net::HTTP::Patch, delete: Net::HTTP::Delete }.fetch(method)
req = klass.new(uri, 'Authorization' => "Bearer #{token}",
'Content-Type' => 'application/json')
req.body = body.to_json if body
res = Net::HTTP.start(uri.host, 443, use_ssl: true) { |h| h.request(req) }
[res.code.to_i, (JSON.parse(res.body) rescue {})]
end
def self.errors(body)
body['errors'].to_a.map { |e| e['detail'] || e['title'] }.join('; ')
end
# Every app the credentials can see. Handy as a first check: if this lists
# the wrong apps, you are authenticated against the wrong account.
def self.apps
code, body = request(:get, '/v1/apps?limit=200&fields[apps]=name,bundleId,sku')
abort "GET /v1/apps failed (HTTP #{code}): #{errors(body)}" unless code == 200
body['data'].to_a
end
# App ids for the given bundle ids (or all apps when none are given).
def self.resolve(bundle_ids)
all = apps
return all if bundle_ids.empty?
bundle_ids.map do |bid|
app = all.find { |a| a.dig('attributes', 'bundleId') == bid }
abort "no app found for bundle id #{bid} in this account" unless app
app
end
end
end
#!/usr/bin/env ruby
# Work around fastlane issue #20538: the first `deliver` against a brand new
# app record dies with `[!] No data` because the version's review detail does
# not exist yet, and Apple returns an empty payload rather than an empty
# object. Creating the review detail once per version makes it behave.
#
# Also just faster than filling the same four fields on four version pages.
#
# REVIEW_FIRST_NAME="Jane" REVIEW_LAST_NAME="Doe" \
# REVIEW_PHONE="+1 5550100" REVIEW_EMAIL="review@example.com" \
# ruby asc_seed_review_details.rb [bundle.id ...] [--dry-run]
#
# With no bundle ids it does every app the credentials can see.
require_relative 'asc_api'
dry = ARGV.delete('--dry-run')
attrs = {
contactFirstName: ASC.env!('REVIEW_FIRST_NAME'),
contactLastName: ASC.env!('REVIEW_LAST_NAME'),
contactPhone: ASC.env!('REVIEW_PHONE'),
contactEmail: ASC.env!('REVIEW_EMAIL'),
demoAccountRequired: false
}
ASC.resolve(ARGV).each do |app|
name = app.dig('attributes', 'name')
code, body = ASC.request(:get, "/v1/apps/#{app['id']}/appStoreVersions" \
'?limit=50&fields[appStoreVersions]=versionString,platform,appStoreState')
abort "listing versions of #{name} failed (HTTP #{code}): #{ASC.errors(body)}" unless code == 200
body['data'].to_a.each do |version|
at = version['attributes']
label = format('%-16s %-6s %-5s %s', name, at['platform'], at['versionString'], at['appStoreState'])
if dry
puts "DRY #{label}"
next
end
# Create, or update in place when the detail already exists.
_, existing = ASC.request(:get, "/v1/appStoreVersions/#{version['id']}/appStoreReviewDetail")
id = existing.dig('data', 'id')
code, resp =
if id
ASC.request(:patch, "/v1/appStoreReviewDetails/#{id}",
data: { type: 'appStoreReviewDetails', id: id, attributes: attrs })
else
ASC.request(:post, '/v1/appStoreReviewDetails',
data: { type: 'appStoreReviewDetails', attributes: attrs,
relationships: { appStoreVersion: {
data: { type: 'appStoreVersions', id: version['id'] } } } })
end
ok = [200, 201].include?(code)
puts "#{ok ? 'OK ' : 'FAIL'} #{label} -> HTTP #{code}#{ok ? '' : " #{ASC.errors(resp)}"}"
end
end
#!/usr/bin/env ruby
# Read store state back out of App Store Connect, because a store deploy's
# exit code tells you the tool finished, not that the store changed.
#
# This exists because a lane of mine printed "applied age rating, privacy URL"
# while having silently skipped the privacy URL: `deliver` only diffs App Info
# metadata against real locale directories, so a `default/` copy was dropped
# with "No changes to localized App Info detected. Skipping upload."
#
# ruby asc_verify_store_state.rb [bundle.id ...]
require_relative 'asc_api'
ASC.resolve(ARGV).each do |app|
at = app['attributes']
puts "#{at['name']} (#{at['bundleId']})"
code, body = ASC.request(:get, "/v1/apps/#{app['id']}/appInfos?include=ageRatingDeclaration")
if code != 200
puts " ! appInfos failed (HTTP #{code}): #{ASC.errors(body)}"
next
end
body['data'].to_a.each do |info|
ia = info['attributes']
puts " state=#{ia['appStoreState']} ageRating=#{ia['appStoreAgeRating'].inspect}"
decl = body['included'].to_a.find { |x| x['type'] == 'ageRatingDeclarations' }
if decl
# Show only what is NOT at its harmless default, so the interesting
# answers stand out instead of scrolling past 30 "NONE" lines.
set = decl['attributes'].reject { |_, v| v.nil? || v == false || v.to_s.upcase == 'NONE' }
puts " age rating non-defaults: #{set.empty? ? '(all NONE/false)' : set.inspect}"
end
lcode, locs = ASC.request(:get, "/v1/appInfos/#{info['id']}/appInfoLocalizations" \
'?fields[appInfoLocalizations]=locale,privacyPolicyUrl')
if lcode == 200
locs['data'].to_a.each do |loc|
la = loc['attributes']
url = la['privacyPolicyUrl']
flag = url.to_s.empty? ? ' <-- EMPTY' : ''
puts " #{la['locale']}: privacyPolicyUrl=#{url.inspect}#{flag}"
end
end
end
# Builds per platform, so you can confirm an upload really landed rather
# than trusting "Successfully uploaded" (which is true but says nothing
# about processing).
pcode, pres = ASC.request(:get, "/v1/preReleaseVersions?filter[app]=#{app['id']}" \
'&limit=50&fields[preReleaseVersions]=version,platform')
if pcode == 200
pres['data'].to_a.each do |pv|
pa = pv['attributes']
bcode, builds = ASC.request(:get, "/v1/preReleaseVersions/#{pv['id']}/builds" \
'?limit=10&fields[builds]=version,processingState,uploadedDate,expired')
list = bcode == 200 ? builds['data'].to_a : []
if list.empty?
puts " #{pa['platform']} #{pa['version']}: no builds yet"
else
list.each do |b|
ba = b['attributes']
puts " #{pa['platform']} #{pa['version']} build #{ba['version']}: " \
"#{ba['processingState']}#{ba['expired'] ? ' (expired)' : ''} uploaded #{ba['uploadedDate']}"
end
end
end
end
puts
end
#!/usr/bin/env ruby
# Which account am I actually talking to? Run this before blaming anything
# else. After moving apps between developer accounts, a tool that "cannot
# find" an app has usually authenticated fine, as the wrong identity.
#
# ruby asc_whoami.rb
require_relative 'asc_api'
apps = ASC.apps
puts "#{apps.size} app(s) visible to these credentials:"
apps.each do |a|
at = a['attributes']
puts format(' %-28s %-34s id=%s', at['name'], at['bundleId'], a['id'])
end
puts '(empty list = valid key, but no apps -- almost always the wrong account)' if apps.empty?
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment