appstore-precheck 1.19.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 (58) hide show
  1. package/CHANGELOG.md +46 -0
  2. package/README.md +81 -39
  3. package/package.json +2 -2
  4. package/skills/appstore-precheck/SKILL.md +39 -146
  5. package/skills/appstore-precheck/guidelines-baseline.json +284 -35
  6. package/skills/appstore-precheck/guidelines-fingerprints.json +307 -93
  7. package/skills/appstore-precheck/references/finding-commentary.md +93 -0
  8. package/skills/appstore-precheck/references/methodology.md +56 -19
  9. package/skills/appstore-precheck/references/optional-review.md +56 -0
  10. package/skills/appstore-precheck/references/pierre-deep-review.md +292 -47
  11. package/skills/appstore-precheck/references/review-catalog.json +500 -13
  12. package/skills/appstore-precheck/references/screenshot-vision-review.md +8 -8
  13. package/skills/appstore-precheck/references/simulator-dynamic-review.md +72 -12
  14. package/skills/appstore-precheck/references/typesafe.md +15 -0
  15. package/skills/appstore-precheck/scripts/artifact-review.sh +10 -0
  16. package/skills/appstore-precheck/scripts/augment-json.py +29 -0
  17. package/skills/appstore-precheck/scripts/build-run.sh +5 -0
  18. package/skills/appstore-precheck/scripts/coverage-sections.sh +6 -0
  19. package/skills/appstore-precheck/scripts/dynamic-run.sh +94 -9
  20. package/skills/appstore-precheck/scripts/dynamic.sh +25 -1
  21. package/skills/appstore-precheck/scripts/evidence.sh +8 -3
  22. package/skills/appstore-precheck/scripts/findings.sh +8 -0
  23. package/skills/appstore-precheck/scripts/lib/artifact-review.py +518 -0
  24. package/skills/appstore-precheck/scripts/lib/asc-client.py +293 -0
  25. package/skills/appstore-precheck/scripts/lib/build-evidence.py +50 -0
  26. package/skills/appstore-precheck/scripts/lib/build-exec.py +50 -0
  27. package/skills/appstore-precheck/scripts/lib/build-plan.py +106 -0
  28. package/skills/appstore-precheck/scripts/lib/build-plan.sh +15 -0
  29. package/skills/appstore-precheck/scripts/lib/build-run.py +177 -0
  30. package/skills/appstore-precheck/scripts/lib/coverage-run.sh +23 -0
  31. package/skills/appstore-precheck/scripts/lib/coverage-sections.py +244 -0
  32. package/skills/appstore-precheck/scripts/lib/dyn-demo-login.py +111 -0
  33. package/skills/appstore-precheck/scripts/lib/dyn-device.sh +32 -4
  34. package/skills/appstore-precheck/scripts/lib/dyn-explore.py +312 -0
  35. package/skills/appstore-precheck/scripts/lib/dyn-guideline-capture.py +301 -0
  36. package/skills/appstore-precheck/scripts/lib/dyn-guidelines.py +112 -0
  37. package/skills/appstore-precheck/scripts/lib/dyn-guidelines.sh +23 -0
  38. package/skills/appstore-precheck/scripts/lib/dyn-process.py +75 -0
  39. package/skills/appstore-precheck/scripts/lib/dyn-quorum.sh +28 -30
  40. package/skills/appstore-precheck/scripts/lib/dyn-scrub.py +79 -0
  41. package/skills/appstore-precheck/scripts/lib/dyn-signals.sh +2 -2
  42. package/skills/appstore-precheck/scripts/lib/metadata-review.py +369 -0
  43. package/skills/appstore-precheck/scripts/lib/optin-scan.sh +73 -0
  44. package/skills/appstore-precheck/scripts/lib/optional-records.py +60 -0
  45. package/skills/appstore-precheck/scripts/lib/runtime-blocking.py +26 -0
  46. package/skills/appstore-precheck/scripts/lib/safe_write.py +61 -0
  47. package/skills/appstore-precheck/scripts/lib/scan-guidelines.sh +199 -0
  48. package/skills/appstore-precheck/scripts/lib/static-guidelines.py +341 -0
  49. package/skills/appstore-precheck/scripts/lib/static-reader.py +39 -0
  50. package/skills/appstore-precheck/scripts/metadata-review.sh +4 -0
  51. package/skills/appstore-precheck/scripts/opt-in-review.py +160 -0
  52. package/skills/appstore-precheck/scripts/runtime-review.sh +5 -0
  53. package/skills/appstore-precheck/scripts/scan.sh +56 -23
  54. package/skills/appstore-precheck/scripts/semantic/client.py +3 -1
  55. package/skills/appstore-precheck/scripts/semantic/collect.py +82 -38
  56. package/skills/appstore-precheck/scripts/semantic/engine.py +165 -127
  57. package/skills/appstore-precheck/scripts/semantic/questions.py +5 -1
  58. package/skills/appstore-precheck/scripts/semantic/review_v4.py +81 -0
@@ -0,0 +1,312 @@
1
+ #!/usr/bin/env python3
2
+ """Bounded Maestro accessibility exploration and conservative runtime review.
3
+
4
+ Python 3.8+ stdlib. The offline --screens mode is the portable fixture interface.
5
+ Live mode only operates on a simulator owned by the caller; it never erases or deletes.
6
+ """
7
+ import argparse
8
+ import collections
9
+ import hashlib
10
+ import importlib.util
11
+ import json
12
+ import os
13
+ import pathlib
14
+ import re
15
+ import subprocess
16
+ import sys
17
+ import time
18
+ import tempfile
19
+
20
+ RULES = {
21
+ "dyn-account-deletion": "5.1.1(v)",
22
+ "dyn-siwa-parity": "4.8",
23
+ "dyn-restore-response": "3.1.1",
24
+ "dyn-paywall-disclosure": "3.1.2",
25
+ "dyn-permission-purpose": "5.1.1",
26
+ "dyn-ugc-safety": "1.2",
27
+ "dyn-login-wall": "5.1.1(v)",
28
+ "dyn-external-payment": "3.1.1",
29
+ "dyn-placeholder": "2.1",
30
+ "dyn-navigation-crash": "2.1",
31
+ "dyn-layout-review": "4.0",
32
+ "dyn-host-privacy": "5.1.2",
33
+ "dyn-bundle-drift": "2.1",
34
+ }
35
+ PATTERNS = {
36
+ "login": r"\b(log[ -]?in|sign[ -]?in|email|password|continue with apple)\b",
37
+ "paywall": r"\b(subscri\w*|paywall|purchase|free trial|restore purchases)\b",
38
+ "settings": r"\b(settings|preferences|profile)\b",
39
+ "account": r"\b(account|delete account|deactivate account)\b",
40
+ "permission": r"\b(allow|permission|camera|photos|location|microphone|tracking)\b",
41
+ "ugc": r"\b(post|comment|feed|report|block user|filter)\b",
42
+ "webview": r"\b(browser|webview|open in safari)\b",
43
+ "external_link": r"\b(https?://|privacy policy|terms of use|support|external link)\b",
44
+ }
45
+ DESTRUCTIVE = re.compile(
46
+ r"\b(delete|remove|purchase|buy|subscribe|submit|send|sign out|log out|erase|post|pay|checkout|report|block|allow|accept|agree|confirm|yes|follow|like|share|invite|reset|clear|unsubscribe|cancel|deactivate|transfer|order|donate|restore|continue|sign in|log in|login)\b",
47
+ re.I,
48
+ )
49
+ ACTION_WORDS = re.compile(
50
+ r"\b(open|show|view|next|settings|profile|account|menu|more|help)\b",
51
+ re.I,
52
+ )
53
+ _spec = importlib.util.spec_from_file_location("dyn_process", pathlib.Path(__file__).with_name("dyn-process.py"))
54
+ _process = importlib.util.module_from_spec(_spec)
55
+ _spec.loader.exec_module(_process)
56
+ # Maestro evaluates ${...} as JavaScript inside string parameters and documents no escape,
57
+ # so a value carrying the marker is refused rather than mangled.
58
+ MAESTRO_EXPR = "${"
59
+ SECRET_WORDS = re.compile(r"password|token|secret|credential|api.?key", re.I)
60
+
61
+
62
+ def attrs(node):
63
+ return node.get("attributes", {}) if isinstance(node, dict) else {}
64
+
65
+
66
+ def walk(node):
67
+ if isinstance(node, dict):
68
+ if "attributes" in node:
69
+ yield attrs(node)
70
+ for child in node.get("children", []):
71
+ yield from walk(child)
72
+ elif isinstance(node, list):
73
+ for child in node:
74
+ yield from walk(child)
75
+
76
+
77
+ def label(a):
78
+ values = [a.get(k) for k in ("accessibilityText", "text", "contentDescription", "label", "id")]
79
+ return next((str(v).strip() for v in values if isinstance(v, str) and v.strip()), "")
80
+
81
+
82
+ def safe_label(value):
83
+ value = _scrub.scrub_text(value)
84
+ if SECRET_WORDS.search(value):
85
+ return "[redacted control]"
86
+ return value[:120]
87
+
88
+
89
+ _scrub_spec = importlib.util.spec_from_file_location('dyn_scrub', pathlib.Path(__file__).with_name('dyn-scrub.py'))
90
+ _scrub = importlib.util.module_from_spec(_scrub_spec)
91
+ _scrub_spec.loader.exec_module(_scrub)
92
+ scrub_tree = _scrub.scrub_tree
93
+
94
+
95
+ def summarize(tree, name, screenshot=None, timestamp=None):
96
+ nodes = list(walk(tree))
97
+ labels = [label(a) for a in nodes]
98
+ labels = [x for x in labels if x]
99
+ text = "\n".join(labels)
100
+ interactive = []
101
+ for a in nodes:
102
+ value = label(a)
103
+ if value and (a.get("clickable") is True or ACTION_WORDS.search(value)):
104
+ interactive.append({"label": safe_label(value), "safe_to_tap": False})
105
+ return {
106
+ "screen": name,
107
+ "title": safe_label(labels[0]) if labels else "",
108
+ "node_count": len(nodes),
109
+ "degenerate": len(nodes) <= 3 or not labels,
110
+ "actions": interactive,
111
+ "patterns": sorted(k for k, rx in PATTERNS.items() if re.search(rx, text, re.I)),
112
+ "labels": [safe_label(x) for x in labels],
113
+ "hierarchy": name + ".json",
114
+ "screenshot": screenshot,
115
+ "observed_at": timestamp,
116
+ }
117
+
118
+
119
+ def record(check_id, status, reason, evidence=None):
120
+ return {"check_id": check_id, "guideline": RULES[check_id], "status": status,
121
+ "reason": reason, "evidence_class": "runtime", "evidence": evidence or []}
122
+
123
+
124
+ def evaluate(screens, context):
125
+ result = []
126
+ good = [s for s in screens if not s["degenerate"]]
127
+ labels = "\n".join(x for s in good for x in s["labels"])
128
+ if not screens:
129
+ return [record(k, "NOT_RUN", "No runtime screen was captured") for k in RULES]
130
+ if not good:
131
+ return [record(k, "SKIP", "Accessibility trees contain no usable semantics; inspect screenshots") for k in RULES]
132
+ def seen(rx):
133
+ return bool(re.search(rx, labels, re.I))
134
+ def review(k, reason):
135
+ result.append(record(k, "REVIEW_REQUIRED", reason, [s["hierarchy"] for s in good]))
136
+ def skip(k, reason):
137
+ result.append(record(k, "SKIP", reason))
138
+
139
+ if seen(r"\b(delete|deactivate) (my )?account\b"):
140
+ review("dyn-account-deletion", "Deletion entry was visible; verify end-to-end completion and retention disclosures")
141
+ elif seen(r"\b(account|settings|profile)\b"):
142
+ review("dyn-account-deletion", "Account/settings was visible but no deletion entry was captured; explore authenticated screens")
143
+ else:
144
+ skip("dyn-account-deletion", "No authenticated account screen was observed")
145
+ if seen(r"sign in with apple|continue with apple"):
146
+ review("dyn-siwa-parity", "Apple sign-in control observed; compare terms with other identity providers")
147
+ elif seen(r"(?:sign in|continue) with (?!apple\b|email\b|password\b|passkey\b|phone\b|your\b)[\w-]+"):
148
+ review("dyn-siwa-parity", "Third-party sign-in observed without Apple control on captured screens; assess entitlement exceptions")
149
+ else:
150
+ skip("dyn-siwa-parity", "No third-party sign-in choice was observed")
151
+ if seen(r"restore purchases"):
152
+ review("dyn-restore-response", "Restore control observed; tap response requires a StoreKit-capable review run")
153
+ else:
154
+ skip("dyn-restore-response", "No purchase screen was observed")
155
+ if any("paywall" in s["patterns"] for s in good):
156
+ review("dyn-paywall-disclosure", "Paywall content captured; inspect price, billing interval, terms, and privacy links together")
157
+ else:
158
+ skip("dyn-paywall-disclosure", "No paywall screen was observed")
159
+ evaluate_remaining(result, good, context, seen, review, skip)
160
+ return result
161
+
162
+
163
+ def evaluate_remaining(result, good, context, seen, review, skip):
164
+ if any("permission" in s["patterns"] for s in good):
165
+ review("dyn-permission-purpose", "Permission-related content captured; compare purpose explanation with OS prompt timing")
166
+ else:
167
+ skip("dyn-permission-purpose", "No permission request was triggered")
168
+ if any("ugc" in s["patterns"] for s in good):
169
+ review("dyn-ugc-safety", "UGC surface captured; inspect filtering, reporting, blocking, and response paths")
170
+ else:
171
+ skip("dyn-ugc-safety", "No user-generated content surface was observed")
172
+ if any("login" in s["patterns"] for s in good):
173
+ review("dyn-login-wall", "Login screen captured; determine whether account creation is necessary for core use")
174
+ else:
175
+ skip("dyn-login-wall", "No registration wall was observed")
176
+ if seen(r"\b(pay (on|with)|external payment|visit (our )?website|checkout)\b"):
177
+ review("dyn-external-payment", "Possible external payment direction captured; assess storefront and entitlement context")
178
+ else:
179
+ skip("dyn-external-payment", "No external payment direction was observed")
180
+ if seen(r"lorem ipsum|placeholder|coming soon|todo\b"):
181
+ review("dyn-placeholder", "Placeholder-like copy captured in %d scanned screen(s); inspect shipped context" % len(good))
182
+ else:
183
+ result.append(record("dyn-placeholder", "REVIEW_REQUIRED", "%d screen(s) scanned; unvisited screens and visual content remain unreviewed" % len(good),
184
+ [s["hierarchy"] for s in good]))
185
+ skip("dyn-navigation-crash", "Screen inventory alone cannot establish crash health; use three fresh device repeats")
186
+ review("dyn-layout-review", "Review screenshots at dark mode, large type, and iPad size")
187
+ if context.get("hosts") and context.get("privacy_manifest"):
188
+ review("dyn-host-privacy", "Observed hosts and privacy manifest supplied; classify data purpose before judging consistency")
189
+ else:
190
+ skip("dyn-host-privacy", "Host capture or installed privacy manifest was unavailable")
191
+ if context.get("installed_bundle") and context.get("source_bundle"):
192
+ review("dyn-bundle-drift", "Installed and source bundles supplied; compare shipped declarations and build configuration")
193
+ else:
194
+ skip("dyn-bundle-drift", "Installed bundle or source bundle was unavailable")
195
+ return result
196
+
197
+
198
+ def command(argv, timeout, cwd=None):
199
+ result = _process.run(argv, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True,
200
+ timeout=timeout, cwd=cwd)
201
+ if result.returncode:
202
+ raise subprocess.CalledProcessError(result.returncode, argv)
203
+ return result.stdout
204
+
205
+
206
+ def safe_to_tap(value, allowed):
207
+ return bool(value and MAESTRO_EXPR not in value and not DESTRUCTIVE.search(value)
208
+ and not SECRET_WORDS.search(value) and not value.startswith('[redacted')
209
+ and (allowed is None or value in allowed))
210
+
211
+
212
+ def navigation_allowlist(authorization):
213
+ if authorization is None:
214
+ return None
215
+ if not isinstance(authorization, dict) or not isinstance(authorization.get('selectors'), list):
216
+ raise ValueError('navigation allowlist must contain selectors')
217
+ if any(not isinstance(x, str) or not x or MAESTRO_EXPR in x for x in authorization['selectors']):
218
+ raise ValueError('invalid navigation selector')
219
+ return set(authorization['selectors'])
220
+
221
+
222
+ def navigate(udid, bundle_id, path, out, deadline):
223
+ with tempfile.TemporaryDirectory(prefix='.maestro-navigation-', dir=str(out)) as temporary:
224
+ private = pathlib.Path(temporary)
225
+ flow = private / 'navigation-flow.yaml'
226
+ content = 'appId: ' + json.dumps(bundle_id) + '\n---\n- launchApp:\n clearState: false\n'
227
+ content += ''.join('- tapOn:\n text: ' + json.dumps('^' + re.escape(label) + '$') + '\n' for label in path)
228
+ flow.write_text(content)
229
+ flow.chmod(0o600)
230
+ command(['maestro', '--device', udid, 'test', '--debug-output', str(private / 'debug'),
231
+ '--test-output-dir', str(private / 'output'), str(flow)],
232
+ min(45, max(.01, deadline-time.monotonic())), cwd=out)
233
+
234
+
235
+ def capture_screen(udid, out, name, deadline, authenticated=False, allowed=None):
236
+ raw = command(['maestro', '--device', udid, 'hierarchy'], min(45, max(.01, deadline-time.monotonic())), cwd=out)
237
+ tree = scrub_tree(json.loads(raw), authenticated=authenticated, allowed=allowed)
238
+ (out / (name + '.json')).write_text(json.dumps(tree, indent=2))
239
+ png = None if authenticated else name + '.png'
240
+ try:
241
+ if png:
242
+ command(['xcrun', 'simctl', 'io', udid, 'screenshot', '--type=png', str(out / png)], min(15, max(.01, deadline-time.monotonic())), cwd=out)
243
+ except (OSError, subprocess.SubprocessError):
244
+ png = None
245
+ screen = summarize(tree, name, png, time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime()))
246
+ return screen, hashlib.sha256(json.dumps(tree, sort_keys=True).encode()).hexdigest()
247
+
248
+
249
+ def live_explore(udid, bundle_id, out, max_screens, seconds, authorization=None, authenticated=False):
250
+ if not udid or not bundle_id or MAESTRO_EXPR in bundle_id:
251
+ raise ValueError('non-evaluated bundle id and owned device required')
252
+ allowed = navigation_allowlist(authorization)
253
+ if authenticated and not allowed:
254
+ raise ValueError("authenticated exploration requires an explicit navigation allowlist")
255
+ deadline = time.monotonic() + seconds
256
+ todo, visited, screens = collections.deque([()]), set(), []
257
+ while todo and len(screens) < max_screens and time.monotonic() < deadline:
258
+ path = todo.popleft()
259
+ try:
260
+ if path:
261
+ navigate(udid, bundle_id, path, out, deadline)
262
+ screen, signature = capture_screen(udid, out, 'screen-%03d' % len(screens), deadline, authenticated, allowed)
263
+ if signature in visited:
264
+ continue
265
+ visited.add(signature); screen['path'] = list(path)
266
+ for action in screen['actions']:
267
+ action['safe_to_tap'] = safe_to_tap(action['label'], allowed)
268
+ screens.append(screen)
269
+ if len(path) < 4:
270
+ for action in screen['actions']:
271
+ if action['safe_to_tap'] and action['label'] not in path:
272
+ todo.append(path + (action['label'],))
273
+ except (OSError, subprocess.SubprocessError, ValueError):
274
+ continue
275
+ return screens
276
+
277
+
278
+ def main():
279
+ parser = argparse.ArgumentParser(description=__doc__)
280
+ parser.add_argument('--screens', type=pathlib.Path)
281
+ parser.add_argument('--out', required=True, type=pathlib.Path)
282
+ parser.add_argument('--repo', type=pathlib.Path)
283
+ parser.add_argument('--udid'); parser.add_argument('--bundle-id')
284
+ parser.add_argument('--authorized-navigation', type=pathlib.Path)
285
+ parser.add_argument('--authenticated', action='store_true')
286
+ parser.add_argument('--max-screens', type=int, default=25)
287
+ parser.add_argument('--seconds', type=int, default=360)
288
+ args = parser.parse_args()
289
+ if bool(args.screens) == bool(args.udid) or not 1 <= args.max_screens <= 25 or not 1 <= args.seconds <= 360:
290
+ parser.error('choose screens or owned device and bounded budgets')
291
+ out = args.out.resolve()
292
+ if args.repo and (out == args.repo.resolve() or args.repo.resolve() in out.parents):
293
+ parser.error('--out must be outside --repo')
294
+ out.mkdir(parents=True, exist_ok=True)
295
+ if args.screens:
296
+ screens = []
297
+ for path in sorted(args.screens.glob('*.json'))[:args.max_screens]:
298
+ try:
299
+ screens.append(summarize(json.loads(path.read_text()), path.stem))
300
+ except (OSError, ValueError):
301
+ continue
302
+ else:
303
+ authorization = json.loads(args.authorized_navigation.read_text()) if args.authorized_navigation else None
304
+ screens = live_explore(args.udid, args.bundle_id, out, args.max_screens, args.seconds, authorization, args.authenticated)
305
+ report = {'schema_version': 1, 'screens': screens, 'checks': evaluate(screens, {}),
306
+ 'screen_budget': args.max_screens, 'time_budget_seconds': args.seconds}
307
+ (out / 'screen-inventory.json').write_text(json.dumps(report, indent=2) + '\n')
308
+ print(json.dumps(report)); return 0
309
+
310
+
311
+ if __name__ == '__main__':
312
+ raise SystemExit(main())
@@ -0,0 +1,301 @@
1
+ #!/usr/bin/env python3
2
+ """Bounded, read-only collectors for six guideline observations on an owned device.
3
+
4
+ No build, package install, permission acceptance, credentials or arbitrary labels.
5
+ The caller establishes the fresh erase; this helper never creates/deletes devices.
6
+ """
7
+ import argparse
8
+ import importlib.util
9
+ import hashlib
10
+ import json
11
+ import os
12
+ from pathlib import Path
13
+ import plistlib
14
+ import re
15
+ import subprocess
16
+ import tempfile
17
+ import time
18
+
19
+ LIB = Path(__file__).resolve().parent
20
+ spec = importlib.util.spec_from_file_location('dyn_process', LIB / 'dyn-process.py')
21
+ process = importlib.util.module_from_spec(spec)
22
+ spec.loader.exec_module(process)
23
+ ACTIONS = {'capture': ('Start recording', 'Record video'),
24
+ 'music': ('Play music', 'Open Apple Music library'),
25
+ 'location': ('Use my location', 'Find nearby'),
26
+ 'miniapp': ('Browse mini apps', 'Open mini apps', 'Mini apps')}
27
+ SKIP_DIRS = {'.git', 'Pods', 'node_modules', 'build', 'DerivedData', '.build', '.planning', 'vendor'}
28
+
29
+
30
+ def command(argv, timeout=10):
31
+ try:
32
+ result = process.run(argv, timeout=timeout, grace=1, text=True,
33
+ stdout=subprocess.PIPE, stderr=subprocess.PIPE)
34
+ return result.stdout if result.returncode == 0 else ''
35
+ except (OSError, subprocess.TimeoutExpired, InterruptedError):
36
+ return ''
37
+
38
+
39
+ def walk(tree, owner=''):
40
+ if isinstance(tree, list):
41
+ for item in tree:
42
+ yield from walk(item, owner)
43
+ elif isinstance(tree, dict):
44
+ attrs = tree.get('attributes', {})
45
+ owner = attrs.get('packageName') or attrs.get('bundleId') or owner
46
+ if attrs:
47
+ yield tree, dict(attrs, _owner=owner)
48
+ for child in tree.get('children', []):
49
+ yield from walk(child, owner)
50
+
51
+
52
+ def label(attrs):
53
+ return next((attrs[k] for k in ('accessibilityText', 'text', 'label')
54
+ if isinstance(attrs.get(k), str) and attrs[k].strip()), '')
55
+
56
+
57
+ def frame(attrs):
58
+ value = attrs.get('bounds', '')
59
+ if isinstance(value, str):
60
+ match = re.fullmatch(r'\[(-?\d+),(-?\d+)\]\[(-?\d+),(-?\d+)\]', value)
61
+ if match:
62
+ x, y, right, bottom = map(int, match.groups())
63
+ return (x, y, right, bottom) if right > x and bottom > y else None
64
+ return None
65
+
66
+
67
+ def inside(inner, outer):
68
+ return bool(inner and outer and inner[0] >= outer[0] and inner[1] >= outer[1]
69
+ and inner[2] <= outer[2] and inner[3] <= outer[3])
70
+
71
+
72
+ def os_prompt(nodes):
73
+ for node in nodes:
74
+ for branch, attrs in walk(node):
75
+ if attrs.get('_owner') not in ('com.apple.springboard', 'com.apple.SpringBoard'):
76
+ continue
77
+ kind = attrs.get('type', attrs.get('class', ''))
78
+ if kind not in ('XCUIElementTypeAlert', 'UIAAlert'):
79
+ continue
80
+ text = ' '.join(label(a) for _, a in walk(branch)).lower()
81
+ if 'location' in text and ('allow' in text or 'access' in text):
82
+ return 'location'
83
+ if ('apple music' in text or 'media library' in text) and ('allow' in text or 'access' in text):
84
+ return 'music'
85
+ return ''
86
+
87
+
88
+ def directory_facts(nodes, bounds, labels):
89
+ heading = any(re.fullmatch(r'(mini[ -]?apps?|mini[ -]?games?|plugins?)', x, re.I) for x in labels)
90
+ cells = [(n, a) for n, a in nodes if a.get('type', a.get('class')) in ('XCUIElementTypeCell', 'UIATableCell')]
91
+ cells = [(n, a) for n, a in cells if any(label(child) for _, child in walk(n))]
92
+ visible = [(n, a) for n, a in cells if inside(frame(a), bounds)]
93
+ rated = sum(any(re.fullmatch(r'(?:Ages?\s*)?(?:4|9|12|13|16|17|18)\+|Rated\s+(?:E|E10\+|T|M|AO)', label(a), re.I)
94
+ for _, a in walk(n)) for n, _ in visible)
95
+ unavailable = any(re.search(r'mini[ -]?app (?:directory|index|list) (?:is )?unavailable', x, re.I) for x in labels)
96
+ return {'directory_heading': heading, 'directory_unavailable': unavailable,
97
+ 'visible_items': len(cells), 'fully_visible_items': len(visible), 'rated_items': rated}
98
+
99
+
100
+ def context_facts(nodes):
101
+ app_nodes = [(n, a) for n, a in nodes if a.get('_owner') not in ('com.apple.springboard', 'com.apple.SpringBoard')]
102
+ signature = [(label(a), frame(a), a.get('type', a.get('class', '')), a.get('_owner', '')) for _, a in app_nodes]
103
+ return {'context_signature': hashlib.sha256(json.dumps(signature, sort_keys=True).encode()).hexdigest(),
104
+ 'app_owners': sorted({a['_owner'] for _, a in app_nodes if a.get('_owner')})}
105
+
106
+
107
+ def screen_facts(tree):
108
+ nodes = list(walk(tree))
109
+ labels = [label(a) for _, a in nodes if label(a)]
110
+ bounds = frame(nodes[0][1]) if nodes else None
111
+ facts = {'usable': len(nodes) >= 4 and len(labels) >= 3,
112
+ 'os_prompt': os_prompt([tree]), 'labels': labels,
113
+ 'app_context_observed': sum(bool(label(a)) for _, a in nodes if a.get('_owner') not in ('com.apple.springboard', 'com.apple.SpringBoard')) >= 3,
114
+ 'location_context': any(re.search(r'nearby|your location|current location|locate me|navigation|map', label(a), re.I) for _, a in nodes if a.get('_owner') not in ('com.apple.springboard', 'com.apple.SpringBoard'))}
115
+ facts.update(directory_facts(nodes, bounds, labels))
116
+ facts.update(context_facts(nodes))
117
+ frames = {(label(a), frame(a)) for _, a in nodes if frame(a) and a.get('_owner') not in ('com.apple.springboard', 'com.apple.SpringBoard')}
118
+ facts['recording_frames'] = {item for item in frames if re.fullmatch(r'Recording(?: \d{1,2}:\d{2})?|Stop recording', item[0], re.I)}
119
+ facts['status_indicator'] = any(a.get('_owner') in ('com.apple.springboard', 'com.apple.SpringBoard')
120
+ and a.get('type', a.get('class')) in ('XCUIElementTypeStatusBar', 'UIAStatusBar')
121
+ and any(re.search(r'recording|camera in use|microphone in use', label(child), re.I)
122
+ and inside(frame(child), frame(a)) for _, child in walk(n))
123
+ for n, a in nodes)
124
+ return facts
125
+
126
+
127
+ def load_tree(path):
128
+ try:
129
+ return json.loads(Path(path).read_text())
130
+ except (OSError, ValueError):
131
+ return {}
132
+
133
+
134
+ def safe_action(value):
135
+ return isinstance(value, str) and '${' not in value and value in sum((list(x) for x in ACTIONS.values()), [])
136
+
137
+
138
+ def hierarchy(udid):
139
+ raw = command(['maestro', '--device', udid, 'hierarchy'], 15)
140
+ try:
141
+ return json.loads(raw)
142
+ except (ValueError, TypeError):
143
+ return {}
144
+
145
+
146
+ def tap(udid, bundle, text):
147
+ if not safe_action(text) or '${' in bundle:
148
+ return False
149
+ with tempfile.TemporaryDirectory(prefix='precheck-observe-flow-') as temp:
150
+ flow = Path(temp) / 'flow.yaml'
151
+ flow.write_text('appId: %s\n---\n- tapOn:\n text: %s\n' % (json.dumps(bundle), json.dumps(text)))
152
+ flow.chmod(0o600)
153
+ try:
154
+ result = process.run(['maestro', '--device', udid, 'test', '--debug-output', temp,
155
+ '--test-output-dir', temp, str(flow)], 20, grace=1,
156
+ stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
157
+ return result.returncode == 0
158
+ except (OSError, subprocess.TimeoutExpired, InterruptedError):
159
+ return False
160
+
161
+
162
+ def screenshot(udid, path):
163
+ try:
164
+ result = process.run(['xcrun', 'simctl', 'io', udid, 'screenshot', '--type=png', str(path)],
165
+ 10, grace=1, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
166
+ return result.returncode == 0 and path.read_bytes()[:8] == b'\x89PNG\r\n\x1a\n'
167
+ except (OSError, subprocess.TimeoutExpired, InterruptedError):
168
+ return False
169
+
170
+
171
+ def source_signal(repo):
172
+ if not repo:
173
+ return False
174
+ count = 0
175
+ for folder, dirs, files in os.walk(repo, followlinks=False):
176
+ dirs[:] = [d for d in dirs if d not in SKIP_DIRS and not Path(folder, d).is_symlink()]
177
+ for name in files:
178
+ path = Path(folder, name)
179
+ if path.suffix not in ('.swift', '.m', '.mm') or path.is_symlink():
180
+ continue
181
+ count += 1
182
+ if count > 1000:
183
+ return False
184
+ try:
185
+ with path.open('rb') as handle:
186
+ text = handle.read(262144).decode('utf-8', errors='ignore')
187
+ except OSError:
188
+ continue
189
+ if all(re.search(rx, text) for rx in ('WKScriptMessageHandler', 'evaluateJavaScript', r'https?://')):
190
+ return True
191
+ return False
192
+
193
+
194
+ def applicability(app, repo):
195
+ try:
196
+ with (Path(app) / 'Info.plist').open('rb') as handle:
197
+ info = plistlib.load(handle)
198
+ except (OSError, ValueError, plistlib.InvalidFileException):
199
+ return {}
200
+ if not isinstance(info, dict):
201
+ return {}
202
+ exe = info.get('CFBundleExecutable', '')
203
+ valid_exe = isinstance(exe, str) and bool(exe) and '/' not in exe and exe not in ('.', '..')
204
+ links = command(['otool', '-L', str(Path(app) / exe)]) if valid_exe else ''
205
+ return {'capture': bool(re.search(r'/(ReplayKit|AVFoundation)\.framework/', links)),
206
+ 'music': bool(re.search(r'/MusicKit\.framework/', links)),
207
+ 'location': any(k.startswith('NSLocation') and k.endswith('UsageDescription') for k in info),
208
+ 'miniapp': source_signal(repo)}
209
+
210
+
211
+ def cpu_observation(pid, app, executable):
212
+ obs = {'applicable': True, 'usable': False}
213
+ if not str(pid).isdigit() or not executable or '/' in executable:
214
+ return obs
215
+ expected = str(Path(app).resolve() / executable)
216
+ actual = command(['ps', '-p', str(pid), '-o', 'comm=']).strip()
217
+ if actual != expected:
218
+ obs['reason'] = 'Process identity did not match the installed executable; CPU was not sampled'
219
+ return obs
220
+ time.sleep(20)
221
+ samples = []
222
+ for _ in range(3):
223
+ if command(['ps', '-p', str(pid), '-o', 'comm=']).strip() != expected:
224
+ return obs
225
+ try:
226
+ samples.append(float(command(['ps', '-p', str(pid), '-o', '%cpu=']).strip()))
227
+ except ValueError:
228
+ return obs
229
+ time.sleep(0.5)
230
+ obs.update(usable=True, pid_verified=True, idle_seconds=20, samples=samples)
231
+ return obs
232
+
233
+
234
+ def action_observation(args, mode, initial):
235
+ before = screen_facts(hierarchy(args.udid))
236
+ candidates = [s for s in ACTIONS[mode] if s in before['labels']]
237
+ result = {'applicable': True, 'usable': before['usable'], 'flow_triggered': False}
238
+ if not before['usable'] or not candidates:
239
+ return result
240
+ if before['context_signature'] != initial.get('context_signature') or before['app_owners'] != [args.bundle_id]:
241
+ result.update(usable=False, reason='App context changed or ownership is unverified; action was not attempted')
242
+ return result
243
+ pre = args.out / (mode + '-before.png')
244
+ post = args.out / (mode + '-after.png')
245
+ pre_ok = screenshot(args.udid, pre) if mode == 'capture' else False
246
+ if not tap(args.udid, args.bundle_id, candidates[0]):
247
+ result['usable'] = False
248
+ return result
249
+ time.sleep(1)
250
+ after = screen_facts(hierarchy(args.udid))
251
+ if any(owner != args.bundle_id for owner in after['app_owners']) or (not after['app_owners'] and not after['os_prompt']):
252
+ result.update(usable=False, reason='Post-action app context is unverified or belongs to another app')
253
+ return result
254
+ result.update({k: v for k, v in after.items() if k not in ('labels', 'recording_frames')})
255
+ result.update(flow_triggered=True, prompt_phase='action', location_context=mode == 'location')
256
+ if mode == 'capture':
257
+ result['new_indicator_frame'] = bool(after['recording_frames'] - before['recording_frames'])
258
+ result['screenshots_verified'] = pre_ok and screenshot(args.udid, post)
259
+ return result
260
+
261
+
262
+ def observe(args):
263
+ signals = applicability(args.app, args.repo)
264
+ initial = screen_facts(load_tree(args.initial_tree))
265
+ result = {'dyn-cpu-idle': cpu_observation(args.pid, args.app, args.executable)}
266
+ modes = {'capture': 'dyn-capture-indicator', 'music': 'dyn-musickit-auth',
267
+ 'miniapp': 'dyn-miniapp-index', 'location': 'dyn-location-timing'}
268
+ for mode, rule in modes.items():
269
+ if not signals.get(mode):
270
+ result[rule] = {'applicable': False}
271
+ elif not initial['usable']:
272
+ result[rule] = {'applicable': True, 'usable': False}
273
+ elif mode == 'location' and initial['os_prompt'] == 'location':
274
+ result[rule] = dict(initial, applicable=True, prompt_phase='launch')
275
+ elif mode == 'miniapp' and initial['directory_heading']:
276
+ result[rule] = dict(initial, applicable=True)
277
+ else:
278
+ result[rule] = action_observation(args, mode, initial)
279
+ result[rule].pop('labels', None)
280
+ result[rule].pop('recording_frames', None)
281
+ result['dyn-miniapp-rating-label'] = dict(result['dyn-miniapp-index'])
282
+ return result
283
+
284
+
285
+ def main():
286
+ parser = argparse.ArgumentParser()
287
+ for name in ('udid', 'bundle-id', 'app', 'pid', 'executable', 'initial-tree'):
288
+ parser.add_argument('--' + name, required=True)
289
+ parser.add_argument('--repeat', type=int, required=True)
290
+ parser.add_argument('--fresh-owned', action='store_true')
291
+ parser.add_argument('--repo', default='')
292
+ parser.add_argument('--out', type=Path, required=True)
293
+ args = parser.parse_args()
294
+ if '${' in args.bundle_id or not args.out.is_dir() or args.out.is_symlink():
295
+ parser.error('safe bundle id and private output directory required')
296
+ print(json.dumps({'repeat': args.repeat, 'fresh': args.fresh_owned,
297
+ 'observations': observe(args)}, sort_keys=True))
298
+
299
+
300
+ if __name__ == '__main__':
301
+ main()