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,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()
@@ -0,0 +1,112 @@
1
+ #!/usr/bin/env python3
2
+ """Conservative D12-D17 observations; incomplete evidence always abstains.
3
+
4
+ Capture and MusicKit checks establish positive observations only. Missing visual
5
+ or OS evidence is never proof that a warning or authorization was omitted.
6
+ """
7
+ import argparse
8
+ import json
9
+ from pathlib import Path
10
+ import statistics
11
+
12
+ RULES = {'dyn-cpu-idle': '2.4.2', 'dyn-capture-indicator': '2.5.14',
13
+ 'dyn-musickit-auth': '4.5.2', 'dyn-miniapp-index': '4.7.4',
14
+ 'dyn-miniapp-rating-label': '4.7.5', 'dyn-location-timing': '5.1.5'}
15
+
16
+
17
+ def evaluate(rule, obs):
18
+ if not isinstance(obs, dict):
19
+ return 'SKIP', 'Malformed observation'
20
+ if not obs.get('applicable'):
21
+ return 'SKIP', 'No applicable shipped or source signal was established'
22
+ if not obs.get('usable'):
23
+ return 'SKIP', obs.get('reason', 'Missing, timed-out or degenerate observation')
24
+ if rule == 'dyn-cpu-idle':
25
+ samples = obs.get('samples', [])
26
+ if not obs.get('pid_verified') or obs.get('idle_seconds', 0) < 20 or len(samples) != 3:
27
+ return 'SKIP', 'Need a verified app process and three samples after 20 idle seconds'
28
+ if any(not isinstance(x, (int, float)) or isinstance(x, bool) or not 0 <= x <= 10000 for x in samples):
29
+ return 'SKIP', 'CPU samples are invalid'
30
+ median = statistics.median(samples)
31
+ return ('FINDING' if median > 40 else 'PASS'), 'Observed idle process CPU median %.1f%% (advisory)' % median
32
+ if rule == 'dyn-miniapp-index':
33
+ if obs.get('directory_heading') and obs.get('directory_unavailable'):
34
+ return 'FINDING', 'Observed mini-app directory explicitly reported unavailable; scope is this screen'
35
+ if obs.get('directory_heading') and obs.get('visible_items', 0):
36
+ return 'PASS', 'Mini-app directory and entries observed on the captured screen'
37
+ return 'SKIP', 'Partial exploration cannot establish absence of a directory'
38
+ if rule == 'dyn-miniapp-rating-label':
39
+ total = obs.get('fully_visible_items', 0)
40
+ if not obs.get('directory_heading') or not total:
41
+ return 'SKIP', 'No fully visible mini-app entries with readable geometry were captured'
42
+ missing = total - obs.get('rated_items', 0)
43
+ return ('FINDING' if missing > 0 else 'PASS'), '%d/%d fully visible entries lacked an accessible age label; inspect screenshots' % (missing, total)
44
+ if rule == 'dyn-location-timing':
45
+ if obs.get('os_prompt') != 'location':
46
+ return 'SKIP', 'No location alert with verified OS ownership and alert class was captured'
47
+ if obs.get('prompt_phase') == 'launch' and obs.get('app_context_observed'):
48
+ return 'FINDING', 'OS location permission appeared before any user action; app purpose and request justification were not assessed (timing observation only)'
49
+ if obs.get('prompt_phase') == 'action' and obs.get('location_context'):
50
+ return 'PASS', 'OS location permission followed an explicit location action'
51
+ return 'SKIP', 'Location prompt observed, but its request context is ambiguous'
52
+ return observe_only(rule, obs)
53
+
54
+
55
+ def observe_only(rule, obs):
56
+ if rule == 'dyn-musickit-auth':
57
+ if obs.get('flow_triggered') and obs.get('os_prompt') == 'music':
58
+ return 'PASS', 'OS media-library authorization alert observed after an explicit music action'
59
+ return 'SKIP', 'Music authorization absence is inconclusive; library access was not independently established'
60
+ if rule == 'dyn-capture-indicator':
61
+ required = ('flow_triggered', 'new_indicator_frame', 'status_indicator', 'screenshots_verified')
62
+ if all(obs.get(k) for k in required):
63
+ return 'PASS', 'New app recording frame and OS status indicator observed with before/after screenshots'
64
+ return 'SKIP', 'Recording indicators require OS status-bar geometry and a new labelled app frame; missing evidence needs vision review'
65
+ return 'SKIP', 'Unknown check'
66
+
67
+
68
+ def aggregate(repeats, rule):
69
+ ids = [r.get('repeat') for r in repeats]
70
+ valid = all(isinstance(x, int) and not isinstance(x, bool) and x > 0 for x in ids)
71
+ valid = valid and all(r.get('fresh') is True and isinstance(r.get('observations'), dict) for r in repeats)
72
+ if len(repeats) < 3 or not valid or len(set(ids)) != len(ids):
73
+ return 'SKIP', 'Need at least three distinct observations on freshly erased owned devices'
74
+ votes = [evaluate(rule, r.get('observations', {}).get(rule, {})) for r in repeats]
75
+ kinds = [v[0] for v in votes]
76
+ if len(set(kinds)) == 1 and kinds[0] != 'SKIP':
77
+ return kinds[0], 'quorum %d/%d; fresh erase verified; %s' % (len(votes), len(votes), votes[-1][1])
78
+ return 'SKIP', 'No unanimous complete observations (PASS=%d FINDING=%d SKIP=%d); %s' % (kinds.count('PASS'), kinds.count('FINDING'), kinds.count('SKIP'), votes[-1][1])
79
+
80
+
81
+ def read_repeats(path, expected):
82
+ if path.is_dir():
83
+ repeats = []
84
+ for number in range(1, expected + 1):
85
+ try:
86
+ record = json.loads((path / ('repeat-%d.json' % number)).read_text())
87
+ if not isinstance(record, dict) or record.get('repeat') != number:
88
+ raise ValueError('invalid repeat')
89
+ except (OSError, ValueError):
90
+ record = {'repeat': number, 'fresh': False, 'observations': {}}
91
+ repeats.append(record)
92
+ return repeats
93
+ try:
94
+ records = json.loads(path.read_text())
95
+ return records if isinstance(records, list) and all(isinstance(r, dict) for r in records) else []
96
+ except (OSError, ValueError):
97
+ return []
98
+
99
+
100
+ def main():
101
+ parser = argparse.ArgumentParser()
102
+ parser.add_argument('observations', type=Path)
103
+ parser.add_argument('--expected', type=int, default=0)
104
+ args = parser.parse_args()
105
+ repeats = read_repeats(args.observations, args.expected)
106
+ for rule, guideline in RULES.items():
107
+ kind, message = aggregate(repeats, rule)
108
+ print('DYNAMIC-%s: %s [%s] — %s' % (kind, guideline, rule, message))
109
+
110
+
111
+ if __name__ == '__main__':
112
+ main()
@@ -0,0 +1,23 @@
1
+ #!/usr/bin/env bash
2
+ # Additional observations are collected only after a verified owned fresh erase.
3
+ # Dependencies: HERE, UDID/BID/INSTALLED/EXE/REPO, OUT and the runner's emit helper.
4
+ dyn_extended_capture() {
5
+ local folder="$DYN_EXT_DIR/repeat-$1" pid="" tree="$OUT/hierarchy-$1.json"
6
+ mkdir "$folder" || return 0
7
+ [[ -f "$DYN_EXT_DIR/pid-$1.txt" ]] && pid="$(cat "$DYN_EXT_DIR/pid-$1.txt")"
8
+ [[ "${LAST_SIGNALS##*,}" != unread ]] || tree="$folder/unavailable.json"
9
+ python3 -B "$HERE/lib/dyn-process.py" --timeout 240 --grace 1 -- \
10
+ python3 -B "$HERE/lib/dyn-guideline-capture.py" \
11
+ --udid "$UDID" --bundle-id "$BID" --app "$INSTALLED" --executable "$EXE" \
12
+ --pid "$pid" --initial-tree "$tree" --repo "$REPO" \
13
+ --out "$folder" --repeat "$1" --fresh-owned > "$DYN_EXT_DIR/repeat-$1.json" 2> "$DYN_EXT_DIR/repeat-$1.stderr.log" || {
14
+ printf 'Additional observation collector failed; see %s\n' "$DYN_EXT_DIR/repeat-$1.stderr.log" >&2
15
+ }
16
+ }
17
+
18
+ dyn_extended_report() {
19
+ local line
20
+ while IFS= read -r line; do emit "$line"; done < <(
21
+ python3 -B "$HERE/lib/dyn-guidelines.py" "$DYN_EXT_DIR" --expected "$REPEATS"
22
+ )
23
+ }
@@ -0,0 +1,134 @@
1
+ #!/usr/bin/env bash
2
+ # lib/dyn-hosts.sh — which hosts the running app contacted, and whether the ones that
3
+ # belong to known ad / attribution vendors are declared in NSPrivacyTrackingDomains
4
+ # (dyn-hosts-contacted, guideline 5.1.2 parity). Pure text over captured files; the
5
+ # capture itself (log stream with SIMCTL_CHILD_CFNETWORK_DIAGNOSTICS=3, or the opt-in
6
+ # tcpdump pktap) is dynamic-run.sh's job. Sourced by dynamic-run.sh. Bash 3.2.
7
+ #
8
+ # LIMITS, stated up front:
9
+ # * CFNetwork diagnostics see URLSession / NSURLConnection traffic. Flutter's Dart
10
+ # HttpClient and some Go / Rust networking stacks bypass CFNetwork entirely, so
11
+ # the log-based capture MISSES them; the runner records that as a SKIP reason
12
+ # unless --pktap was given (sudo tcpdump on the pktap interface sees DNS for
13
+ # every process). Default off: it needs sudo.
14
+ # * The vendor→domain catalogue below mirrors the §16 tracking-SDK list in scan.sh
15
+ # and goes stale the same way (MAINTENANCE.md, quarterly). A host that matches
16
+ # no vendor is reported, not judged.
17
+
18
+ # dyn_hosts_from_log <log-file> -> unique lower-cased hostnames, one per line.
19
+ # Reads URL hosts ("request https://host/…") and "connected to host:port" lines.
20
+ dyn_hosts_from_log() {
21
+ local f="$1"
22
+ [[ -f "$f" ]] || return 0
23
+ {
24
+ grep -oE 'https?://[A-Za-z0-9._-]+' "$f" 2>/dev/null | sed -E 's#https?://##'
25
+ grep -oE 'connected to [A-Za-z0-9._-]+' "$f" 2>/dev/null | sed -E 's/connected to //'
26
+ } | tr 'A-Z' 'a-z' | grep -E '^[a-z0-9._-]+$' | grep -E '\.' | sort -u # a host has a dot (or is an IPv4 literal)
27
+ }
28
+
29
+ # dyn_hosts_from_tcpdump_text <text-file> -> hostnames from DNS queries ("A? host.").
30
+ dyn_hosts_from_tcpdump_text() {
31
+ local f="$1"
32
+ [[ -f "$f" ]] || return 0
33
+ grep -oE ' (A|AAAA|HTTPS)\? [A-Za-z0-9._-]+\.' "$f" 2>/dev/null \
34
+ | sed -E 's/^ (A|AAAA|HTTPS)\? //; s/\.$//' | tr 'A-Z' 'a-z' | sort -u
35
+ }
36
+
37
+ # dyn_tracking_domain_catalogue -> "<vendor><TAB><domain-suffix>" lines. Suffix
38
+ # match: a contacted host equals the suffix or ends in ".<suffix>".
39
+ dyn_tracking_domain_catalogue() {
40
+ cat <<'EOF'
41
+ AppsFlyer appsflyer.com
42
+ AppsFlyer appsflyersdk.com
43
+ Adjust adjust.com
44
+ Adjust adj.st
45
+ Branch branch.io
46
+ Branch app.link
47
+ Google Ads doubleclick.net
48
+ Google Ads googleadservices.com
49
+ Google Ads googlesyndication.com
50
+ Google Ads admob.com
51
+ Meta Audience Network / FB SDK graph.facebook.com
52
+ AppLovin applovin.com
53
+ AppLovin applvn.com
54
+ ironSource ironsrc.com
55
+ ironSource ironsource.com
56
+ Unity Ads unityads.unity3d.com
57
+ Vungle vungle.com
58
+ Chartboost chartboost.com
59
+ InMobi inmobi.com
60
+ Mintegral mintegral.com
61
+ Pangle pangle.io
62
+ Pangle pangleglobal.com
63
+ Singular singular.net
64
+ Kochava kochava.com
65
+ Tenjin tenjin.io
66
+ Tenjin tenjin.com
67
+ EOF
68
+ }
69
+
70
+ # _dyn_host_matches <host> <suffix> -> 0 when host == suffix or host ends in .suffix
71
+ _dyn_host_matches() { [[ "$1" == "$2" || "$1" == *".$2" ]]; }
72
+
73
+ # dyn_declared_tracking_domains <PrivacyInfo.xcprivacy|""> -> declared domains, one per line.
74
+ # Uses lib/dyn-bundle.sh's plist reader when it is loaded (dynamic-run.sh sources both);
75
+ # standalone, a minimal tag-per-line XML fallback of the same shape.
76
+ dyn_declared_tracking_domains() {
77
+ local f="${1:-}"
78
+ [[ -n "$f" && -f "$f" ]] || return 0
79
+ if command -v dyn_plist_array_strings >/dev/null 2>&1; then
80
+ dyn_plist_array_strings "$f" NSPrivacyTrackingDomains
81
+ else
82
+ sed 's/>/>\
83
+ /g' "$f" | sed -E 's/^[[:space:]]+//' | grep -v '^$' | awk 'on && /<\/array>/ { exit } on && /<\/string>/ { sub(/<\/string>.*/, ""); print; next } $0 == "NSPrivacyTrackingDomains</key>" { on = 1 }'
84
+ fi | tr 'A-Z' 'a-z'
85
+ }
86
+
87
+ # dyn_hosts_parity <hosts-file> <PrivacyInfo.xcprivacy|""> -> JSON
88
+ # {contacted:[…], tracking:[{host,vendor,declared}], declared:[…], undeclared:[…]}
89
+ dyn_hosts_parity() {
90
+ local hosts="$1" privacy="${2:-}" host vendor suffix declared d hit tmp
91
+ tmp="$(mktemp)"
92
+ dyn_declared_tracking_domains "$privacy" > "$tmp.decl"
93
+ : > "$tmp.track"
94
+ while IFS= read -r host; do
95
+ [[ -n "$host" ]] || continue
96
+ while IFS="$(printf '\t')" read -r vendor suffix; do
97
+ [[ -n "$suffix" ]] || continue
98
+ _dyn_host_matches "$host" "$suffix" || continue
99
+ declared=false
100
+ while IFS= read -r d; do [[ -n "$d" ]] && _dyn_host_matches "$host" "$d" && declared=true; done < "$tmp.decl"
101
+ printf '%s\t%s\t%s\n' "$host" "$vendor" "$declared" >> "$tmp.track"
102
+ break
103
+ done < <(dyn_tracking_domain_catalogue)
104
+ done < "$hosts"
105
+ jq -n -c --rawfile hosts "$hosts" --rawfile decl "$tmp.decl" --rawfile track "$tmp.track" '
106
+ ($hosts | split("\n") | map(select(. != ""))) as $c
107
+ | ($decl | split("\n") | map(select(. != ""))) as $d
108
+ | ($track | split("\n") | map(select(. != "")) | map(split("\t") | {host:.[0], vendor:.[1], declared:(.[2]=="true")})) as $t
109
+ | {contacted:$c, declared:$d, tracking:$t, undeclared:[$t[] | select(.declared|not) | .host]}'
110
+ hit=$?
111
+ rm -f "$tmp" "$tmp.decl" "$tmp.track"
112
+ return $hit
113
+ }
114
+
115
+ # dyn_hosts_line <parity-json> <source-note> -> one transcript line for dyn-hosts-contacted.
116
+ dyn_hosts_line() {
117
+ local rep="$1" note="${2:-}" n u t
118
+ n="$(jq -r '.contacted|length' <<<"$rep")"; t="$(jq -r '.tracking|length' <<<"$rep")"; u="$(jq -r '.undeclared|length' <<<"$rep")"
119
+ if (( n == 0 )); then
120
+ printf 'DYNAMIC-SKIP: 5.1.2 [dyn-hosts-contacted] — no host observed in the capture window%s\n' "${note:+ ($note)}"
121
+ return 0
122
+ fi
123
+ if (( u > 0 )); then
124
+ printf 'DYNAMIC-FINDING: 5.1.2 [dyn-hosts-contacted] — %s host(s) contacted; %s belong to known ad/attribution vendors and %s of those are NOT in NSPrivacyTrackingDomains: %s%s\n' \
125
+ "$n" "$t" "$u" "$(jq -r '[.tracking[] | select(.declared|not) | "\(.host) (\(.vendor))"] | join(", ")' <<<"$rep")" "${note:+ ($note)}"
126
+ return 0
127
+ fi
128
+ if (( t > 0 )); then
129
+ printf 'DYNAMIC-PASS: 5.1.2 [dyn-hosts-contacted] — %s host(s) contacted; %s known ad/attribution host(s), all declared in NSPrivacyTrackingDomains%s\n' "$n" "$t" "${note:+ ($note)}"
130
+ return 0
131
+ fi
132
+ printf 'DYNAMIC-PASS: 5.1.2 [dyn-hosts-contacted] — %s host(s) contacted, none matches a known ad/attribution vendor: %s%s\n' \
133
+ "$n" "$(jq -r '.contacted | .[0:6] | join(", ")' <<<"$rep")" "${note:+ ($note)}"
134
+ }
@@ -0,0 +1,75 @@
1
+ #!/usr/bin/env python3
2
+ """Bounded POSIX driver process groups; terminate descendants on cancel/deadline."""
3
+ import argparse
4
+ import os
5
+ import signal
6
+ import subprocess
7
+ import sys
8
+
9
+
10
+ DEFAULT_GRACE = 15
11
+
12
+
13
+ def stop(proc, grace=DEFAULT_GRACE):
14
+ """TERM the whole group, wait ``grace`` seconds for cleanup, then KILL it."""
15
+ try:
16
+ os.killpg(proc.pid, signal.SIGTERM)
17
+ except ProcessLookupError:
18
+ return
19
+ try:
20
+ proc.wait(timeout=grace)
21
+ except subprocess.TimeoutExpired:
22
+ pass
23
+ # The group leader may exit while its child ignores TERM.
24
+ try:
25
+ os.killpg(proc.pid, signal.SIGKILL)
26
+ except ProcessLookupError:
27
+ pass
28
+ proc.wait()
29
+
30
+
31
+ def run(argv, timeout, grace=DEFAULT_GRACE, **kwargs):
32
+ try:
33
+ proc = subprocess.Popen(argv, start_new_session=True, **kwargs)
34
+ except FileNotFoundError as exc:
35
+ error = str(exc) if kwargs.get('text') else str(exc).encode()
36
+ return subprocess.CompletedProcess(argv, 127, '' if kwargs.get('text') else b'', error)
37
+ previous = {}
38
+ def cancelled(signum, _frame):
39
+ raise InterruptedError(signum, 'Driver cancelled')
40
+ try:
41
+ for sig in (signal.SIGINT, signal.SIGTERM):
42
+ previous[sig] = signal.signal(sig, cancelled)
43
+ stdout, stderr = proc.communicate(timeout=timeout)
44
+ return subprocess.CompletedProcess(argv, proc.returncode, stdout, stderr)
45
+ except BaseException:
46
+ # Do not let a second cancellation interrupt artifact/device cleanup.
47
+ for sig in previous:
48
+ signal.signal(sig, signal.SIG_IGN)
49
+ stop(proc, grace)
50
+ raise
51
+ finally:
52
+ for sig, handler in previous.items():
53
+ signal.signal(sig, handler)
54
+
55
+
56
+ def main():
57
+ parser = argparse.ArgumentParser()
58
+ parser.add_argument('--timeout', type=float, required=True)
59
+ parser.add_argument('--grace', type=float, default=DEFAULT_GRACE,
60
+ help='seconds between TERM and KILL when the deadline expires')
61
+ parser.add_argument('command', nargs=argparse.REMAINDER)
62
+ args = parser.parse_args()
63
+ argv = args.command[1:] if args.command[:1] == ['--'] else args.command
64
+ if args.timeout <= 0 or args.grace <= 0 or not argv:
65
+ parser.error('positive deadline, grace and command required')
66
+ try:
67
+ return run(argv, args.timeout, args.grace).returncode
68
+ except subprocess.TimeoutExpired:
69
+ return 124
70
+ except InterruptedError:
71
+ return 143
72
+
73
+
74
+ if __name__ == '__main__':
75
+ sys.exit(main())