appstore-precheck 1.18.0 → 1.20.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (70) hide show
  1. package/CHANGELOG.md +256 -0
  2. package/README.md +108 -39
  3. package/bin/cli.js +8 -0
  4. package/package.json +2 -2
  5. package/skills/appstore-precheck/SKILL.md +99 -157
  6. package/skills/appstore-precheck/guidelines-baseline.json +285 -36
  7. package/skills/appstore-precheck/guidelines-fingerprints.json +319 -93
  8. package/skills/appstore-precheck/references/finding-commentary.md +93 -0
  9. package/skills/appstore-precheck/references/methodology.md +81 -26
  10. package/skills/appstore-precheck/references/optional-review.md +56 -0
  11. package/skills/appstore-precheck/references/pierre-deep-review.md +323 -44
  12. package/skills/appstore-precheck/references/review-catalog.json +740 -0
  13. package/skills/appstore-precheck/references/screenshot-vision-review.md +8 -8
  14. package/skills/appstore-precheck/references/simulator-dynamic-review.md +398 -54
  15. package/skills/appstore-precheck/references/typesafe-example.json +239 -0
  16. package/skills/appstore-precheck/references/typesafe.md +216 -0
  17. package/skills/appstore-precheck/scripts/app-discover.sh +138 -0
  18. package/skills/appstore-precheck/scripts/artifact-review.sh +10 -0
  19. package/skills/appstore-precheck/scripts/augment-json.py +29 -0
  20. package/skills/appstore-precheck/scripts/build-run.sh +5 -0
  21. package/skills/appstore-precheck/scripts/coverage-sections.sh +6 -0
  22. package/skills/appstore-precheck/scripts/dynamic-run.sh +400 -0
  23. package/skills/appstore-precheck/scripts/dynamic.sh +329 -0
  24. package/skills/appstore-precheck/scripts/evidence.sh +49 -15
  25. package/skills/appstore-precheck/scripts/findings.sh +76 -26
  26. package/skills/appstore-precheck/scripts/framework-detect.sh +101 -0
  27. package/skills/appstore-precheck/scripts/guideline-cite.sh +4 -1
  28. package/skills/appstore-precheck/scripts/lib/artifact-review.py +518 -0
  29. package/skills/appstore-precheck/scripts/lib/asc-client.py +293 -0
  30. package/skills/appstore-precheck/scripts/lib/build-evidence.py +50 -0
  31. package/skills/appstore-precheck/scripts/lib/build-exec.py +50 -0
  32. package/skills/appstore-precheck/scripts/lib/build-plan.py +106 -0
  33. package/skills/appstore-precheck/scripts/lib/build-plan.sh +15 -0
  34. package/skills/appstore-precheck/scripts/lib/build-run.py +177 -0
  35. package/skills/appstore-precheck/scripts/lib/coverage-run.sh +23 -0
  36. package/skills/appstore-precheck/scripts/lib/coverage-sections.py +244 -0
  37. package/skills/appstore-precheck/scripts/lib/dyn-bundle.sh +185 -0
  38. package/skills/appstore-precheck/scripts/lib/dyn-demo-login.py +111 -0
  39. package/skills/appstore-precheck/scripts/lib/dyn-device.sh +123 -0
  40. package/skills/appstore-precheck/scripts/lib/dyn-explore.py +312 -0
  41. package/skills/appstore-precheck/scripts/lib/dyn-geometry.sh +75 -0
  42. package/skills/appstore-precheck/scripts/lib/dyn-guideline-capture.py +301 -0
  43. package/skills/appstore-precheck/scripts/lib/dyn-guidelines.py +112 -0
  44. package/skills/appstore-precheck/scripts/lib/dyn-guidelines.sh +23 -0
  45. package/skills/appstore-precheck/scripts/lib/dyn-hosts.sh +134 -0
  46. package/skills/appstore-precheck/scripts/lib/dyn-process.py +75 -0
  47. package/skills/appstore-precheck/scripts/lib/dyn-quorum.sh +90 -0
  48. package/skills/appstore-precheck/scripts/lib/dyn-scrub.py +79 -0
  49. package/skills/appstore-precheck/scripts/lib/dyn-signals.sh +120 -0
  50. package/skills/appstore-precheck/scripts/lib/guideline-text.sh +23 -5
  51. package/skills/appstore-precheck/scripts/lib/metadata-review.py +369 -0
  52. package/skills/appstore-precheck/scripts/lib/optin-scan.sh +73 -0
  53. package/skills/appstore-precheck/scripts/lib/optional-records.py +60 -0
  54. package/skills/appstore-precheck/scripts/lib/png-uniform.py +115 -0
  55. package/skills/appstore-precheck/scripts/lib/runtime-blocking.py +26 -0
  56. package/skills/appstore-precheck/scripts/lib/safe_write.py +61 -0
  57. package/skills/appstore-precheck/scripts/lib/scan-guidelines.sh +199 -0
  58. package/skills/appstore-precheck/scripts/lib/static-guidelines.py +341 -0
  59. package/skills/appstore-precheck/scripts/lib/static-reader.py +39 -0
  60. package/skills/appstore-precheck/scripts/metadata-review.sh +4 -0
  61. package/skills/appstore-precheck/scripts/opt-in-review.py +160 -0
  62. package/skills/appstore-precheck/scripts/runtime-review.sh +5 -0
  63. package/skills/appstore-precheck/scripts/scan.sh +132 -21
  64. package/skills/appstore-precheck/scripts/semantic/__init__.py +1 -0
  65. package/skills/appstore-precheck/scripts/semantic/client.py +95 -0
  66. package/skills/appstore-precheck/scripts/semantic/collect.py +165 -0
  67. package/skills/appstore-precheck/scripts/semantic/engine.py +320 -0
  68. package/skills/appstore-precheck/scripts/semantic/questions.py +167 -0
  69. package/skills/appstore-precheck/scripts/semantic/review_v4.py +81 -0
  70. package/skills/appstore-precheck/scripts/semantic-review.py +61 -0
@@ -0,0 +1,369 @@
1
+ import argparse
2
+ import base64
3
+ import http.client
4
+ import ipaddress
5
+ import importlib.util
6
+ import json
7
+ import os
8
+ import pathlib
9
+ import shutil
10
+ import socket
11
+ import ssl
12
+ import subprocess
13
+ import sys
14
+ import time
15
+ import urllib.error
16
+ import urllib.parse
17
+ import urllib.request
18
+
19
+ SPEC = importlib.util.spec_from_file_location('asc_client', pathlib.Path(__file__).with_name('asc-client.py'))
20
+ CLIENT = importlib.util.module_from_spec(SPEC); SPEC.loader.exec_module(CLIENT)
21
+ ApiError, ASC, collect_asc = CLIENT.ApiError, CLIENT.ASC, CLIENT.collect_asc
22
+ attrs, one, relation = CLIENT.attrs, CLIENT.one, CLIENT.relation
23
+ CHECKS = (
24
+ "meta-age-rating", "meta-review-notes", "meta-demo-account",
25
+ "meta-iap-review-notes", "meta-iap-screenshot", "meta-privacy-url",
26
+ "meta-support-url", "meta-category", "meta-price", "meta-storefront",
27
+ "meta-screenshots",
28
+ )
29
+
30
+ def record(check_id, status, reason, evidence=None):
31
+ return {"check_id": check_id, "status": status, "evidence_class": "metadata",
32
+ "reason": reason, "evidence": evidence or []}
33
+
34
+ def local_text(root, relative):
35
+ try:
36
+ path = root / relative
37
+ if path.is_file() and path.stat().st_size <= 64 * 1024:
38
+ return path.read_text(encoding="utf-8").strip()
39
+ except (OSError, UnicodeError):
40
+ return None
41
+ return None
42
+
43
+ def local_review(root, name):
44
+ value = local_text(root, "review_information/" + name + ".txt")
45
+ if value is not None:
46
+ return value
47
+ legacy = {"notes": "review_notes", "demo_user": "review_demo_user",
48
+ "demo_password": "review_demo_password"}.get(name)
49
+ return local_text(root, "review_information/" + legacy + ".txt") if legacy else None
50
+
51
+ def local_urls(root, name):
52
+ locales = [x for x in root.iterdir() if x.is_dir() and x.name not in {"review_information", "trade_representative_contact_information", "default"}] if root.is_dir() else []
53
+ return [local_text(loc, name + ".txt") for loc in locales]
54
+
55
+ def valid_url(value):
56
+ if not isinstance(value, str):
57
+ return False
58
+ parsed = urllib.parse.urlparse(value.strip())
59
+ return parsed.scheme in ("https", "http") and bool(parsed.hostname) and not parsed.username and not parsed.password
60
+
61
+ def checked_addresses(host, port):
62
+ """Resolve once and return the address records only if every answer is global."""
63
+ try:
64
+ infos = socket.getaddrinfo(host, port, type=socket.SOCK_STREAM)
65
+ addresses = [ipaddress.ip_address(x[4][0]) for x in infos]
66
+ nat64 = ipaddress.ip_network("64:ff9b::/96")
67
+ if infos and all(address.is_global and address not in nat64 for address in addresses):
68
+ return infos
69
+ except (OSError, ValueError):
70
+ pass
71
+ return []
72
+
73
+ def public_url(value):
74
+ """Cheap pre-check (used to vet redirect targets); the connection itself re-validates."""
75
+ return valid_url(value) and bool(checked_addresses(urllib.parse.urlparse(value).hostname, None))
76
+
77
+ def connect_pinned(host, port, timeout):
78
+ """Connect to an address from the SAME lookup that was validated.
79
+
80
+ Resolving here, checking the answers, and dialling one of those answers closes the
81
+ DNS-rebinding window: no second lookup can return a private address between the
82
+ check and the connect. The hostname is kept for the Host header and TLS SNI.
83
+ """
84
+ last_error = OSError("URL host does not resolve to a public address")
85
+ for family, socktype, proto, _canonical, sockaddr in checked_addresses(host, port):
86
+ sock = socket.socket(family, socktype, proto)
87
+ try:
88
+ if timeout is not None and timeout is not getattr(socket, "_GLOBAL_DEFAULT_TIMEOUT", None):
89
+ sock.settimeout(timeout)
90
+ sock.connect(sockaddr)
91
+ return sock
92
+ except OSError as error:
93
+ sock.close()
94
+ last_error = error
95
+ raise last_error
96
+
97
+ class PinnedHTTPConnection(http.client.HTTPConnection):
98
+ def connect(self):
99
+ self.sock = connect_pinned(self.host, self.port, self.timeout)
100
+
101
+ class PinnedHTTPSConnection(http.client.HTTPSConnection):
102
+ def connect(self):
103
+ sock = connect_pinned(self.host, self.port, self.timeout)
104
+ self.sock = self._context.wrap_socket(sock, server_hostname=self.host)
105
+
106
+ class PinnedHTTPHandler(urllib.request.HTTPHandler):
107
+ def http_open(self, request):
108
+ return self.do_open(PinnedHTTPConnection, request)
109
+
110
+ class PinnedHTTPSHandler(urllib.request.HTTPSHandler):
111
+ def https_open(self, request):
112
+ return self.do_open(PinnedHTTPSConnection, request, context=ssl.create_default_context())
113
+
114
+ class SafeRedirect(urllib.request.HTTPRedirectHandler):
115
+ def redirect_request(self, request, fp, code, msg, headers, newurl):
116
+ if not public_url(newurl):
117
+ raise urllib.error.URLError("Unsafe redirect")
118
+ return super().redirect_request(request, fp, code, msg, headers, newurl)
119
+
120
+ def head_reachable(value):
121
+ if not valid_url(value):
122
+ return False
123
+ request = urllib.request.Request(value, method="HEAD", headers={"User-Agent": "appstore-precheck/metadata-review"})
124
+ # Environment proxies are disabled on purpose: a proxy would resolve the name
125
+ # itself, so the address we validated would not be the one contacted.
126
+ opener = urllib.request.build_opener(urllib.request.ProxyHandler({}), PinnedHTTPHandler,
127
+ PinnedHTTPSHandler, SafeRedirect)
128
+ try:
129
+ with opener.open(request, timeout=8) as response:
130
+ return 200 <= response.status < 400
131
+ except (urllib.error.URLError, http.client.HTTPException, OSError, ValueError):
132
+ return False
133
+
134
+ def unavailable(check_id, source, reason):
135
+ return record(check_id, "SKIP" if source else "NOT_RUN", reason)
136
+
137
+ def local_metadata_dir(args):
138
+ if args.metadata_dir:
139
+ return pathlib.Path(args.metadata_dir)
140
+ repo = pathlib.Path(args.repo)
141
+ for path in (repo / "fastlane" / "metadata", repo / "ios" / "fastlane" / "metadata"):
142
+ if path.is_dir():
143
+ return path
144
+ return repo / "fastlane" / "metadata"
145
+
146
+ def review_part_0(args, asc, metadata, results):
147
+ local, asc_on = metadata.is_dir(), asc is not None
148
+ screenshots = metadata.parent / "screenshots"
149
+ age = asc.get("age") if asc_on else None
150
+ if isinstance(age, ApiError):
151
+ results.append(unavailable(CHECKS[0], True, "Age rating declaration could not be read from App Store Connect"))
152
+ elif asc_on and any(value is not None for value in attrs(one(age)).values()):
153
+ results.append(record(CHECKS[0], "NEEDS_REVIEW", "Age rating declaration responses are present; present, unverified"))
154
+ elif asc_on and isinstance(asc.get("info"), ApiError):
155
+ results.append(unavailable(CHECKS[0], True, "App info could not be read from App Store Connect"))
156
+ elif asc_on:
157
+ results.append(record(CHECKS[0], "NEEDS_REVIEW", "Age rating declaration is absent or empty"))
158
+ else:
159
+ results.append(unavailable(CHECKS[0], False, "Age rating declaration needs opt-in App Store Connect access"))
160
+
161
+
162
+
163
+ def review_part_1(args, asc, metadata, results):
164
+ local, asc_on = metadata.is_dir(), asc is not None
165
+ screenshots = metadata.parent / "screenshots"
166
+ review_data = asc.get("review") if asc_on else None
167
+ notes = attrs(one(review_data)).get("notes") if asc_on and not isinstance(review_data, ApiError) else (None if asc_on else local_review(metadata, "notes"))
168
+ if isinstance(review_data, ApiError) and notes is None:
169
+ results.append(unavailable(CHECKS[1], True, "App Review details could not be read"))
170
+ elif notes is None and not local and not asc_on:
171
+ results.append(unavailable(CHECKS[1], False, "No fastlane metadata or App Store Connect review details"))
172
+ else:
173
+ results.append(record(CHECKS[1], "NEEDS_REVIEW",
174
+ "App Review notes are present; present, unverified" if notes else "App Review notes are empty or absent"))
175
+
176
+ required = args.login_required or (attrs(one(review_data)).get("demoAccountRequired") is True if asc_on and not isinstance(review_data, ApiError) else False)
177
+ user = attrs(one(review_data)).get("demoAccountName") if asc_on and not isinstance(review_data, ApiError) else (None if asc_on else local_review(metadata, "demo_user"))
178
+ password = attrs(one(review_data)).get("demoAccountPassword") if asc_on and not isinstance(review_data, ApiError) else (None if asc_on else local_review(metadata, "demo_password"))
179
+ if isinstance(review_data, ApiError) and user is None and password is None:
180
+ results.append(unavailable(CHECKS[2], True, "Demo account fields could not be read"))
181
+ elif not required and not user and not password:
182
+ results.append(unavailable(CHECKS[2], bool(asc_on or local), "Login requirement unknown; demo account applicability needs review"))
183
+ else:
184
+ results.append(record(CHECKS[2], "NEEDS_REVIEW",
185
+ "Demo account fields are both present; present, unverified" if user and password else "Demo account name or password is missing"))
186
+
187
+
188
+
189
+ def review_part_2(args, asc, metadata, results):
190
+ local, asc_on = metadata.is_dir(), asc is not None
191
+ screenshots = metadata.parent / "screenshots"
192
+ products = asc.get("purchases") if asc_on else None
193
+ subs = asc.get("subscriptions") if asc_on else None
194
+ if isinstance(products, ApiError) or isinstance(subs, ApiError):
195
+ for check_id in CHECKS[3:5]:
196
+ results.append(unavailable(check_id, True, "In-app purchase resources could not be read"))
197
+ elif asc_on and isinstance(products, list) and isinstance(subs, list):
198
+ all_products = products + subs
199
+ if not all_products:
200
+ for check_id in CHECKS[3:5]:
201
+ results.append(unavailable(check_id, True, "No in-app purchases were returned; applicability not established"))
202
+ else:
203
+ notes_ok = all(bool(attrs(x).get("reviewNote")) for x in all_products)
204
+ results.append(record(CHECKS[3], "NEEDS_REVIEW",
205
+ "Review notes are present for returned purchases; present, unverified" if notes_ok else "At least one purchase lacks review notes"))
206
+ shots = asc.get("iap_screenshots")
207
+ if not isinstance(shots, list) or any(isinstance(x, ApiError) for x in shots):
208
+ results.append(unavailable(CHECKS[4], True, "Purchase review screenshots could not all be read"))
209
+ else:
210
+ shots_ok = len(shots) == len(all_products) and all(one(x) for x in shots)
211
+ results.append(record(CHECKS[4], "NEEDS_REVIEW",
212
+ "Review screenshots are present for returned purchases; present, unverified" if shots_ok else "At least one purchase lacks a review screenshot"))
213
+ else:
214
+ for check_id in CHECKS[3:5]:
215
+ results.append(unavailable(check_id, False, "Purchase review metadata needs opt-in App Store Connect access"))
216
+
217
+
218
+
219
+ def review_part_3(args, asc, metadata, results):
220
+ local, asc_on = metadata.is_dir(), asc is not None
221
+ screenshots = metadata.parent / "screenshots"
222
+ info_locs = asc.get("info_localizations") if asc_on else None
223
+ version_locs = asc.get("version_localizations") if asc_on else None
224
+ url_sources = (
225
+ (CHECKS[5], info_locs, "privacyPolicyUrl", local_urls(metadata, "privacy_url")),
226
+ (CHECKS[6], version_locs, "supportUrl", local_urls(metadata, "support_url")),
227
+ )
228
+ for check_id, remote, field, local_values in url_sources:
229
+ if isinstance(remote, list):
230
+ values = [attrs(x).get(field) for x in remote]
231
+ else:
232
+ values = [] if asc_on else local_values
233
+ if isinstance(remote, ApiError) and not values:
234
+ results.append(unavailable(check_id, True, "Store URL fields could not be read"))
235
+ elif not values and not local and not asc_on:
236
+ results.append(unavailable(check_id, False, "Store URL fields unavailable"))
237
+ elif not values or not all(valid_url(x) for x in values):
238
+ results.append(record(check_id, "NEEDS_REVIEW", "A required localized URL is absent or invalid"))
239
+ elif args.check_urls and not all(head_reachable(x) for x in values):
240
+ results.append(record(check_id, "NEEDS_REVIEW", "An opt-in HEAD request did not confirm URL reachability"))
241
+ else:
242
+ results.append(record(check_id, "PASS", "Localized URL fields are present and well-formed" +
243
+ ("; HEAD reachability confirmed" if args.check_urls else "; reachability not checked")))
244
+
245
+
246
+
247
+ def review_part_4(args, asc, metadata, results):
248
+ local, asc_on = metadata.is_dir(), asc is not None
249
+ screenshots = metadata.parent / "screenshots"
250
+ info = asc.get("info") if asc_on else None
251
+ category = relation(info, "primaryCategory") if isinstance(info, dict) else None
252
+ if not category and not asc_on:
253
+ category = local_text(metadata, "primary_category.txt")
254
+ if isinstance(info, ApiError) and category is None:
255
+ results.append(unavailable(CHECKS[7], True, "Primary category could not be read"))
256
+ elif not local and not asc_on:
257
+ results.append(unavailable(CHECKS[7], False, "Primary category metadata unavailable"))
258
+ else:
259
+ results.append(record(CHECKS[7], "PASS" if category else "NEEDS_REVIEW",
260
+ "Primary category is set" if category else "Primary category is absent"))
261
+
262
+
263
+
264
+ def review_part_5(args, asc, metadata, results):
265
+ local, asc_on = metadata.is_dir(), asc is not None
266
+ screenshots = metadata.parent / "screenshots"
267
+ for check_id, key in ((CHECKS[8], "price"), (CHECKS[9], "availability")):
268
+ value = asc.get(key) if asc_on else None
269
+ if isinstance(value, ApiError):
270
+ results.append(unavailable(check_id, True, "Store pricing or availability could not be read"))
271
+ elif not asc_on:
272
+ results.append(unavailable(check_id, False, "Pricing and storefront need opt-in App Store Connect access"))
273
+ elif check_id == CHECKS[8]:
274
+ schedule = one(value)
275
+ ok = bool(schedule and relation(schedule, "baseTerritory") and relation(schedule, "manualPrices"))
276
+ results.append(record(check_id, "PASS" if ok else "NEEDS_REVIEW",
277
+ "Price schedule, base territory, and manual price are configured" if ok else "Price schedule or base price configuration is absent"))
278
+ else:
279
+ territories = asc.get("territories")
280
+ if isinstance(territories, ApiError):
281
+ results.append(unavailable(check_id, True, "Territory availability could not be read"))
282
+ else:
283
+ ok = isinstance(territories, list) and any(attrs(x).get("available") is True for x in territories)
284
+ results.append(record(check_id, "PASS" if ok else "NEEDS_REVIEW",
285
+ "At least one storefront is marked available" if ok else "No available storefront was confirmed"))
286
+
287
+
288
+
289
+ def review_part_6(args, asc, metadata, results):
290
+ local, asc_on = metadata.is_dir(), asc is not None
291
+ screenshots = metadata.parent / "screenshots"
292
+ version_locs = asc.get("version_localizations") if asc_on else None
293
+ remote_shots = asc.get("screenshots") if asc_on else None
294
+ if isinstance(remote_shots, list) and remote_shots:
295
+ if any(isinstance(x, ApiError) for x in remote_shots):
296
+ results.append(unavailable(CHECKS[10], True, "Store screenshots could not all be read"))
297
+ else:
298
+ ok = any(isinstance(x, list) and x for x in remote_shots)
299
+ results.append(record(CHECKS[10], "PASS" if ok else "NEEDS_REVIEW",
300
+ "Store screenshots are present" if ok else "Store screenshot sets contain no images"))
301
+ elif isinstance(version_locs, list):
302
+ results.append(record(CHECKS[10], "NEEDS_REVIEW", "Store screenshots are absent from returned localizations"))
303
+ elif asc_on:
304
+ results.append(unavailable(CHECKS[10], True, "Store screenshots could not be read for selected version"))
305
+ else:
306
+ images = [x for x in screenshots.rglob("*") if x.is_file() and x.suffix.lower() in (".png", ".jpg", ".jpeg")] if screenshots.is_dir() else []
307
+ if images:
308
+ results.append(record(CHECKS[10], "PASS", "Local fastlane screenshots are present"))
309
+ elif screenshots.is_dir():
310
+ results.append(record(CHECKS[10], "NEEDS_REVIEW", "Local fastlane screenshot directory has no images"))
311
+ else:
312
+ results.append(unavailable(CHECKS[10], asc_on, "No readable store screenshot source"))
313
+
314
+
315
+
316
+ def review(args, asc):
317
+ metadata, results = local_metadata_dir(args), []
318
+ for check in (review_part_0, review_part_1, review_part_2, review_part_3, review_part_4, review_part_5, review_part_6):
319
+ check(args, asc, metadata, results)
320
+ if [row['check_id'] for row in results] != list(CHECKS):
321
+ raise ValueError('metadata review produced an incomplete check collection')
322
+ return results
323
+
324
+
325
+ def arguments(argv):
326
+ parser = argparse.ArgumentParser(description='Read-only metadata review')
327
+ parser.add_argument('--repo', default='.')
328
+ for name in ('metadata-dir', 'asc-app-id', 'asc-version-id', 'asc-info-id', 'bundle-id', 'version', 'build-number', 'asc-fixture', 'out'):
329
+ parser.add_argument('--' + name)
330
+ parser.add_argument('--login-required', action='store_true')
331
+ parser.add_argument('--check-urls', action='store_true')
332
+ args = parser.parse_args(argv)
333
+ if args.asc_fixture and (not args.asc_app_id or os.environ.get('APPSTORE_PRECHECK_TEST_MODE') != '1'):
334
+ parser.error('--asc-fixture requires --asc-app-id and APPSTORE_PRECHECK_TEST_MODE=1')
335
+ if args.out:
336
+ output = pathlib.Path(args.out).resolve()
337
+ for root in (pathlib.Path(args.repo).resolve(), local_metadata_dir(args).resolve()):
338
+ if output == root or root in output.parents:
339
+ parser.error('output must be outside read-only metadata inputs')
340
+ return args
341
+
342
+
343
+ def main(argv=None):
344
+ args = arguments(argv); asc, error, api = None, None, None
345
+ if args.asc_app_id:
346
+ try:
347
+ fixture = json.loads(pathlib.Path(args.asc_fixture).read_text()) if args.asc_fixture else None
348
+ api = ASC(fixture)
349
+ asc = collect_asc(api, args.asc_app_id, args.asc_version_id, args.asc_info_id, args.bundle_id, args.version, args.build_number)
350
+ except (ApiError, OSError, ValueError, UnicodeError) as exc:
351
+ error = ' '.join(str(exc).split())[:300]
352
+ asc = {key: ApiError(error) for key in ('age', 'info', 'review', 'purchases', 'subscriptions', 'info_localizations', 'version_localizations', 'price', 'availability', 'screenshots')}
353
+ finally:
354
+ if api is not None:
355
+ api.token = None
356
+ results = review(args, asc)
357
+ payload = {'schema_version': 1, 'results': results, 'asc_error': error,
358
+ 'summary': {s: sum(r['status'] == s for r in results) for s in ('PASS', 'NEEDS_REVIEW', 'SKIP', 'NOT_RUN')},
359
+ 'limitations': ['Presence is not accuracy, successful login, or a regional payment exemption.']}
360
+ encoded = json.dumps(payload, indent=2) + '\n'
361
+ if args.out:
362
+ spec = importlib.util.spec_from_file_location('safe_write', pathlib.Path(__file__).with_name('safe_write.py'))
363
+ writer = importlib.util.module_from_spec(spec); spec.loader.exec_module(writer)
364
+ writer.write_text(args.out, encoded)
365
+ sys.stdout.write(encoded); return 0
366
+
367
+
368
+ if __name__ == '__main__':
369
+ raise SystemExit(main())
@@ -0,0 +1,73 @@
1
+ #!/usr/bin/env bash
2
+ # Explicit optional-tier wiring, isolated from default finding emission.
3
+ optin_trust() {
4
+ if [[ "${APPSTORE_PRECHECK_TRUST_CONFIG:-}" == 1 ]]; then
5
+ if [[ "$OPT_BUILD" != 1 && -z "$OPT_APP" && "$(cfg_bool '.dynamic.build')" == true ]]; then OPT_BUILD=1; fi
6
+ if [[ ( "$OPT_BUILD" == 1 || -n "$OPT_APP" ) && "$OPT_NO_RUNTIME" != 1 && "$(cfg_bool '.dynamic.demoLogin')" == true ]]; then OPT_DEMO=1; fi
7
+ fi
8
+ }
9
+
10
+ optin_validate() {
11
+ [[ "$OPT_BUILD" != 1 || -z "$OPT_APP" ]] || { echo 'scan.sh: choose --build or --app' >&2; return 64; }
12
+ if [[ "$OPT_DEMO" == 1 || "$OPT_DYN_BLOCK" == 1 ]]; then
13
+ [[ "$OPT_NO_RUNTIME" != 1 && ( "$OPT_BUILD" == 1 || -n "$OPT_APP" ) ]] || { echo 'scan.sh: runtime flags need --build/--app and cannot use --no-runtime' >&2; return 64; }
14
+ fi
15
+ [[ -n "$OPT_OUT" ]] || return 0
16
+ python3 - "$OPT_OUT" "$ROOT" <<'PY'
17
+ from pathlib import Path
18
+ import sys
19
+ out, repo = [Path(p).resolve() for p in sys.argv[1:]]
20
+ if out == repo or repo in out.parents or (out.exists() and not out.is_dir()):
21
+ print('scan.sh: --out must be a directory outside the project', file=sys.stderr)
22
+ raise SystemExit(64)
23
+ PY
24
+ }
25
+
26
+ optin_run() {
27
+ [[ "$OPT_BUILD" == 1 || -n "$OPT_APP" || "$OPT_METADATA" == 1 ]] || return 0
28
+ if ! command -v python3 >/dev/null 2>&1; then
29
+ set_rule 'opt-in-review'; skip 'opt-in review — Python 3 required'; return 0
30
+ fi
31
+ if [[ -z "$OPT_OUT" ]]; then
32
+ OPT_TEMP="$(mktemp -d "${TMPDIR:-/tmp}/precheck-review.XXXXXX")"; OPT_OUT="$OPT_TEMP"
33
+ fi
34
+ local args=( --repo "$ROOT" --out-dir "$OPT_OUT" ) status=0 line
35
+ [[ "$OPT_BUILD" == 1 ]] && args+=( --build )
36
+ [[ -n "$OPT_APP" ]] && args+=( --app "$OPT_APP" )
37
+ [[ "$OPT_METADATA" == 1 ]] && args+=( --metadata )
38
+ [[ "$OPT_NO_RUNTIME" == 1 ]] && args+=( --no-runtime )
39
+ [[ "$OPT_DEMO" == 1 ]] && args+=( --demo-login )
40
+ [[ "$OPT_DYN_BLOCK" == 1 ]] && args+=( --dynamic-blocking )
41
+ [[ "$OPT_DRY" == 1 ]] && args+=( --dry-run )
42
+ [[ "$OPT_URLS" == 1 ]] && args+=( --check-urls )
43
+ [[ -n "$OPT_ASC" ]] && args+=( --asc-app-id "$OPT_ASC" )
44
+ [[ -n "$OPT_ASC_VERSION" ]] && args+=( --asc-version-id "$OPT_ASC_VERSION" )
45
+ [[ -n "$OPT_ASC_INFO" ]] && args+=( --asc-info-id "$OPT_ASC_INFO" )
46
+ python3 -B "$SCRIPT_DIR/opt-in-review.py" "${args[@]}" >/dev/null || status=$?
47
+ if (( status != 0 )); then
48
+ [[ "$OPT_DYN_BLOCK" == 1 && "$status" == 2 ]] && return 64
49
+ set_rule 'opt-in-review'; skip 'opt-in review — runner unavailable; no optional conclusions imported'; return 0
50
+ fi
51
+ OPT_RAN_OK=1
52
+ [[ "$FORMAT" != text ]] || printf 'OPT-IN: report — %s/summary.json\n' "$OPT_OUT"
53
+ if [[ "$OPT_DYN_BLOCK" == 1 ]] && ! command -v jq >/dev/null 2>&1; then
54
+ set_rule 'dynamic-blocking'; skip 'dynamic blocking — jq unavailable; no blocking conclusions imported'; return 0
55
+ fi
56
+ if [[ "$OPT_DYN_BLOCK" == 1 ]]; then
57
+ while IFS= read -r line; do
58
+ [[ -n "$line" ]] || continue
59
+ set_rule 'dynamic-blocking'; fail "$line"
60
+ done < <(jq -r '.blocking[]' "$OPT_OUT/summary.json")
61
+ fi
62
+ }
63
+
64
+ optin_render_json() {
65
+ if [[ "$OPT_RAN_OK" == 1 ]]; then
66
+ python3 -B "$SCRIPT_DIR/augment-json.py" --opt-summary "$OPT_OUT/summary.json"
67
+ else cat; fi
68
+ }
69
+
70
+ optin_cleanup() {
71
+ rm -f "$FINDINGS_TMP"
72
+ if [[ -n "$OPT_TEMP" && ( "$OPT_RAN_OK" != 1 || "$FORMAT" == sarif ) ]]; then rm -rf -- "$OPT_TEMP"; fi
73
+ }
@@ -0,0 +1,60 @@
1
+ """Status aggregation harvested without obligations/registry dependencies."""
2
+ MAX_POINTER = 500
3
+ VALID_STATUSES = frozenset({"NOT_RUN", "SKIP", "PASS", "REVIEW_REQUIRED", "WARN", "FINDING"})
4
+ DEFECT_RANK = {"REVIEW_REQUIRED": 1, "WARN": 2, "FINDING": 3}
5
+
6
+ def single_line(value, fallback):
7
+ """Collapse a free-text reason to one line within the report pointer limit."""
8
+ text = " ".join(str(value or "").split())
9
+ return (text or fallback)[:MAX_POINTER]
10
+
11
+ def record(checks, check_id, status, reason="", evidence=""):
12
+ result = {"status": status}
13
+ if status in {"PASS", "FINDING", "WARN"}:
14
+ result["evidence"] = single_line(evidence, "review:" + check_id)
15
+ elif status in {"SKIP", "NOT_RUN", "REVIEW_REQUIRED"}:
16
+ result["reason"] = single_line(reason, "Evidence was insufficient")
17
+ checks[check_id] = result
18
+
19
+ def normalize(status):
20
+ return {"NEEDS_REVIEW": "REVIEW_REQUIRED"}.get(status, status)
21
+
22
+ def merge_status(previous, status):
23
+ """Order-independent aggregate of results sharing one check id.
24
+
25
+ A defect (FINDING > WARN > REVIEW_REQUIRED) dominates. PASS survives only when
26
+ every sibling passed: a PASS next to a SKIP/NOT_RUN sibling means part of the
27
+ check never ran, so the aggregate needs review instead of reading as clean.
28
+ """
29
+ if previous is None or previous == status:
30
+ return status
31
+ worst = max(previous, status, key=lambda value: DEFECT_RANK.get(value, 0))
32
+ if DEFECT_RANK.get(worst, 0):
33
+ return worst
34
+ return "REVIEW_REQUIRED" if "PASS" in (previous, status) else "SKIP"
35
+
36
+ def merge_result(checks, check_id, status, reason, evidence):
37
+ previous = checks.get(check_id)
38
+ merged = merge_status(previous["status"] if previous else None, status)
39
+ if merged == status:
40
+ record(checks, check_id, status, reason, evidence)
41
+ elif merged != previous["status"]:
42
+ gap = reason if status != "PASS" else previous.get("reason", "")
43
+ record(checks, check_id, merged, "Partial evidence: a sibling check did not run (" +
44
+ single_line(gap, "no reason given") + ")", evidence)
45
+
46
+ def import_records(checks, rows, evidence):
47
+ errors = []
48
+ if not isinstance(rows, list):
49
+ return ["Optional result collection must be a list"]
50
+ for row in rows:
51
+ if not isinstance(row, dict) or not isinstance(row.get("check_id"), str) or not row["check_id"]:
52
+ errors.append("Malformed optional result ignored")
53
+ continue
54
+ raw_status = row.get("status")
55
+ status = normalize(raw_status) if isinstance(raw_status, str) else None
56
+ if status not in VALID_STATUSES:
57
+ errors.append("Invalid optional result status ignored")
58
+ continue
59
+ merge_result(checks, row["check_id"], status, row.get("reason", ""), evidence + "#" + row["check_id"])
60
+ return errors
@@ -0,0 +1,115 @@
1
+ #!/usr/bin/env python3
2
+ """png-uniform.py — is a screenshot a single flat colour?
3
+
4
+ One of the four launch-health signals of the Phase 6 dynamic tier (D1): a black or
5
+ white full-frame screenshot is a hung splash or a dead process, whatever the process
6
+ table says. Pure standard library (zlib + struct): no Pillow, no ImageMagick, so it
7
+ runs on a stock macOS python3 and on the ubuntu CI runner alike.
8
+
9
+ Handles the PNGs `xcrun simctl io <udid> screenshot` writes: 8-bit RGB / RGBA,
10
+ non-interlaced. Anything else exits 2 ("could not be read"): the caller records the
11
+ signal as unreadable, never as healthy.
12
+
13
+ Usage: png-uniform.py <file.png>
14
+ stdout: "uniform" | "varied <sampled-distinct-colours>"
15
+ exit: 0 decoded, 2 unreadable / unsupported
16
+ """
17
+ import struct
18
+ import sys
19
+ import zlib
20
+
21
+ SIG = b"\x89PNG\r\n\x1a\n"
22
+ # Sample every Nth pixel on every Nth row: enough to see a spinner or a text line,
23
+ # cheap on a 1179x2556 frame.
24
+ STRIDE = 8
25
+ # "Uniform" tolerates a status bar: the dominant colour must cover >= 99% of samples.
26
+ DOMINANT = 0.99
27
+
28
+
29
+ def chunks(data):
30
+ pos = len(SIG)
31
+ while pos + 8 <= len(data):
32
+ length, typ = struct.unpack(">I4s", data[pos:pos + 8])
33
+ yield typ, data[pos + 8:pos + 8 + length]
34
+ pos += 12 + length
35
+
36
+
37
+ def unfilter(raw, width, height, bpp):
38
+ stride = width * bpp
39
+ out = bytearray()
40
+ prev = bytearray(stride)
41
+ pos = 0
42
+ for _ in range(height):
43
+ ftype = raw[pos]
44
+ line = bytearray(raw[pos + 1:pos + 1 + stride])
45
+ pos += 1 + stride
46
+ for i in range(stride):
47
+ a = line[i - bpp] if i >= bpp else 0
48
+ b = prev[i]
49
+ c = prev[i - bpp] if i >= bpp else 0
50
+ if ftype == 1:
51
+ line[i] = (line[i] + a) & 0xFF
52
+ elif ftype == 2:
53
+ line[i] = (line[i] + b) & 0xFF
54
+ elif ftype == 3:
55
+ line[i] = (line[i] + ((a + b) >> 1)) & 0xFF
56
+ elif ftype == 4:
57
+ p = a + b - c
58
+ pa, pb, pc = abs(p - a), abs(p - b), abs(p - c)
59
+ pred = a if pa <= pb and pa <= pc else (b if pb <= pc else c)
60
+ line[i] = (line[i] + pred) & 0xFF
61
+ elif ftype != 0:
62
+ raise ValueError("unknown filter %d" % ftype)
63
+ out += line
64
+ prev = line
65
+ return bytes(out), stride
66
+
67
+
68
+ def main(path):
69
+ with open(path, "rb") as fh:
70
+ data = fh.read()
71
+ if not data.startswith(SIG):
72
+ return 2
73
+ width = height = None
74
+ idat = b""
75
+ for typ, body in chunks(data):
76
+ if typ == b"IHDR":
77
+ width, height, depth, ctype, _, _, interlace = struct.unpack(">IIBBBBB", body)
78
+ if depth != 8 or ctype not in (2, 6) or interlace != 0:
79
+ return 2
80
+ bpp = 3 if ctype == 2 else 4
81
+ elif typ == b"IDAT":
82
+ idat += body
83
+ elif typ == b"IEND":
84
+ break
85
+ if width is None or not idat:
86
+ return 2
87
+ try:
88
+ pixels, stride = unfilter(zlib.decompress(idat), width, height, bpp)
89
+ except (zlib.error, ValueError, IndexError):
90
+ return 2
91
+ counts = {}
92
+ total = 0
93
+ for y in range(0, height, STRIDE):
94
+ row = y * stride
95
+ for x in range(0, width, STRIDE):
96
+ px = pixels[row + x * bpp:row + x * bpp + 3]
97
+ counts[px] = counts.get(px, 0) + 1
98
+ total += 1
99
+ if total == 0:
100
+ return 2
101
+ top = max(counts.values())
102
+ if top / float(total) >= DOMINANT:
103
+ print("uniform")
104
+ else:
105
+ print("varied %d" % len(counts))
106
+ return 0
107
+
108
+
109
+ if __name__ == "__main__":
110
+ if len(sys.argv) != 2:
111
+ sys.exit(2)
112
+ try:
113
+ sys.exit(main(sys.argv[1]))
114
+ except (OSError, struct.error):
115
+ sys.exit(2)
@@ -0,0 +1,26 @@
1
+ """Allowlisted opt-in escalation from three fresh, observed runtime failures."""
2
+ import json
3
+ from pathlib import Path
4
+ import re
5
+
6
+
7
+ def blocking(out):
8
+ try:
9
+ report = json.loads((Path(out) / 'run.json').read_text())
10
+ transcript = (Path(out) / 'transcript.txt').read_text().splitlines()
11
+ except (OSError, ValueError):
12
+ return []
13
+ if (report.get('dry_run') is not False or report.get('fresh_erases') != 3 or report.get('repeats') != 3
14
+ or not report.get('device', {}).get('created_by_this_run')):
15
+ return []
16
+ result = []
17
+ for rule, field, evidence, message in (
18
+ ('dyn-launch', 'launch', r'process gone|app crash in log', 'App crashed on three fresh simulator launches'),
19
+ ('dyn-demo-login', 'demo_login', r'explicit login rejection', 'Demo login was rejected on three fresh attempts'),
20
+ ):
21
+ if report.get(field) != {'pass': 0, 'finding': 3, 'skip': 0}:
22
+ continue
23
+ pattern = r'^DYNAMIC-FINDING: 2\.1 \[' + rule + r'\] — quorum 3/3: .*fresh erase verified'
24
+ if any(re.search(pattern, line) and re.search(evidence, line) for line in transcript):
25
+ result.append('2.1 [' + rule + '] ' + message + '; opt-in dynamic blocking')
26
+ return result