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,111 @@
1
+ #!/usr/bin/env python3
2
+ """Run one opt-in demo login attempt without writing credentials to reports."""
3
+ import importlib.util
4
+ import json
5
+ import os
6
+ import pathlib
7
+ import re
8
+ import subprocess
9
+ import sys
10
+ import tempfile
11
+
12
+
13
+ _spec = importlib.util.spec_from_file_location("dyn_process", pathlib.Path(__file__).with_name("dyn-process.py"))
14
+ _process = importlib.util.module_from_spec(_spec)
15
+ _spec.loader.exec_module(_process)
16
+ _scrub_spec = importlib.util.spec_from_file_location('dyn_scrub', pathlib.Path(__file__).with_name('dyn-scrub.py'))
17
+ _scrub = importlib.util.module_from_spec(_scrub_spec)
18
+ _scrub_spec.loader.exec_module(_scrub)
19
+
20
+
21
+
22
+ MAESTRO_EXPR = "${"
23
+
24
+
25
+ def hierarchy(udid, dirname, env):
26
+ result = _process.run(["maestro", "--device", udid, "hierarchy"],
27
+ stdout=subprocess.PIPE, stderr=subprocess.DEVNULL,
28
+ timeout=45, cwd=dirname, env=env)
29
+ if result.returncode:
30
+ raise ValueError("Hierarchy unavailable")
31
+ tree = json.loads(result.stdout.decode("utf-8", "replace"))
32
+ # Selectors stay in memory; redact values without erasing secure-field labels.
33
+ values = set()
34
+ def visit(obj):
35
+ if isinstance(obj, dict):
36
+ attrs = obj.get("attributes", {})
37
+ if isinstance(attrs, dict):
38
+ values.update(_scrub.scrub_text(v.strip()) for k, v in attrs.items()
39
+ if k in ("text", "accessibilityText") and isinstance(v, str))
40
+ for child in obj.get("children", []):
41
+ visit(child)
42
+ elif isinstance(obj, list):
43
+ for child in obj:
44
+ visit(child)
45
+ visit(tree)
46
+ return values
47
+
48
+
49
+ def settings(bundle):
50
+ keys = {'user': ('USERNAME', ''), 'password': ('PASSWORD', ''), 'success': ('SUCCESS_TEXT', ''),
51
+ 'failure': ('FAILURE_TEXT', ''), 'user_field': ('USER_FIELD', 'Email'),
52
+ 'password_field': ('PASSWORD_FIELD', 'Password'), 'submit': ('SUBMIT', 'Sign In')}
53
+ values = {key: os.getenv('PRECHECK_DEMO_' + name, default) for key, (name, default) in keys.items()}
54
+ if not all(values.values()):
55
+ raise ValueError('demo credentials or selectors unavailable')
56
+ if os.getenv('PRECHECK_DEMO_AUTHORIZED_TEST') != '1' or os.getenv('PRECHECK_DEMO_ENVIRONMENT') not in ('test', 'sandbox'):
57
+ raise ValueError('demo login requires an authorized test/sandbox environment')
58
+ if any(MAESTRO_EXPR in value for value in list(values.values()) + [bundle]):
59
+ raise ValueError('demo values contain a Maestro expression; login not attempted')
60
+ return values
61
+
62
+
63
+ def flow(bundle, values):
64
+ return ('appId: ' + json.dumps(bundle) + '\n---\n' +
65
+ '- tapOn: ' + json.dumps('^' + re.escape(values['user_field']) + '$') + '\n' +
66
+ '- inputText: ' + json.dumps(values['user']) + '\n' +
67
+ '- tapOn: ' + json.dumps('^' + re.escape(values['password_field']) + '$') + '\n' +
68
+ '- inputText: ' + json.dumps(values['password']) + '\n' +
69
+ '- tapOn: ' + json.dumps('^' + re.escape(values['submit']) + '$') + '\n')
70
+
71
+
72
+ def drive(udid, bundle, values, dirname):
73
+ path = pathlib.Path(dirname) / 'login.yaml'; path.write_text(flow(bundle, values)); path.chmod(0o600)
74
+ env = dict(os.environ, MAESTRO_CLI_NO_ANALYTICS='1')
75
+ before = hierarchy(udid, dirname, env)
76
+ controls = {values['user_field'], values['password_field'], values['submit']}
77
+ if len(before) < 4 or not controls.issubset(before) or values['success'] in before or values['success'] == values['failure']:
78
+ return 'SKIP\tlogin start state/selectors are ambiguous or unavailable'
79
+ command = ['maestro', '--device', udid, 'test', '--debug-output', str(path.parent / 'debug'),
80
+ '--test-output-dir', str(path.parent / 'output'), str(path)]
81
+ result = _process.run(command, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=45, cwd=dirname, env=env)
82
+ if result.returncode:
83
+ return 'SKIP\tMaestro could not drive login; selectors or driver unavailable'
84
+ after = hierarchy(udid, dirname, env)
85
+ if len(after) < 4 or (values['success'] in after and values['failure'] in after):
86
+ return 'SKIP\tlogin postcondition ambiguous or accessibility evidence insufficient'
87
+ if values['success'] in after:
88
+ return 'PASS\tdemo start/action/new success selector observed; backend scope requires review'
89
+ if values['failure'] in after:
90
+ return 'FINDING\texplicit login rejection observed after the submitted demo attempt'
91
+ return 'SKIP\tneither success nor failure selector observed'
92
+
93
+
94
+ def attempt(udid, bundle):
95
+ try:
96
+ values = settings(bundle)
97
+ with tempfile.TemporaryDirectory(prefix='precheck-demo-') as temporary:
98
+ os.chmod(temporary, 0o700)
99
+ return drive(udid, bundle, values, temporary)
100
+ except (OSError, subprocess.SubprocessError, ValueError):
101
+ return 'SKIP\tdemo prerequisites, driver or hierarchy unavailable; no conclusion'
102
+
103
+
104
+ def main():
105
+ if len(sys.argv) != 3:
106
+ return 'SKIP\tinternal demo driver arguments missing'
107
+ return attempt(*sys.argv[1:])
108
+
109
+
110
+ if __name__ == '__main__':
111
+ print(main())
@@ -0,0 +1,123 @@
1
+ #!/usr/bin/env bash
2
+ # lib/dyn-device.sh — the throwaway-device lifecycle of the Phase 6 runner, one
3
+ # `xcrun simctl` verb per function. Sourced by dynamic-run.sh. Bash 3.2.
4
+ #
5
+ # DEVICE POLICY (SECURITY.md): this tier only ever boots, erases or deletes a device
6
+ # it CREATED in the same run. A user-supplied UDID is used for launching only —
7
+ # never erased, never reset, never deleted (see dynamic-run.sh --udid).
8
+ #
9
+ # DETERMINISM: every repeat starts from an erased device with the same status bar
10
+ # (9:41, full battery and bars), all privacy grants reset, and the app freshly
11
+ # installed, so a FINDING cannot be an artefact of the previous repeat.
12
+ #
13
+ # DRY RUN: with DYN_DRY_RUN=1 every simctl call is recorded as "PLAN: <command>" and
14
+ # nothing runs; value-returning helpers hand back placeholders. That is what the CI
15
+ # test pins (order, repeat count, delete-only-what-we-created) without a simulator.
16
+ # Plan lines go to DYN_PLAN_FILE when set (callers redirect stdout/stderr of the real
17
+ # commands, which would otherwise swallow them), else to stderr.
18
+
19
+ : "${DYN_DRY_RUN:=0}"
20
+ : "${DYN_PLAN_FILE:=}"
21
+
22
+ # dyn_plan <text> — record one planned step.
23
+ dyn_plan() {
24
+ if [[ -n "$DYN_PLAN_FILE" ]]; then printf 'PLAN: %s\n' "$1" >> "$DYN_PLAN_FILE"; else printf 'PLAN: %s\n' "$1" >&2; fi
25
+ }
26
+
27
+ # dyn_cmd <argv…> — run, or record the plan.
28
+ dyn_cmd() {
29
+ if [[ "$DYN_DRY_RUN" == 1 ]]; then dyn_plan "$*"; return 0; fi
30
+ "$@"
31
+ }
32
+
33
+ # Per-step wall-clock caps for teardown and the simulator UI calls. A cap is enforced by
34
+ # lib/dyn-process.py (its own process group, up to 15s of TERM grace on top), so the four
35
+ # teardown steps of two devices stay inside ~120s (4 x (15s + 15s grace)) even if CoreSimulator wedges.
36
+ : "${DYN_TEARDOWN_STEP_TIMEOUT:=15}"
37
+ : "${DYN_UI_TIMEOUT:=20}"
38
+ DYN_DEVICE_LIB_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
39
+
40
+ # dyn_cmd_bounded <secs> <argv…> — dyn_cmd with a wall-clock cap (124 on expiry).
41
+ dyn_cmd_bounded() {
42
+ local secs="$1"; shift
43
+ if [[ "$DYN_DRY_RUN" == 1 ]]; then dyn_plan "$*"; return 0; fi
44
+ python3 "$DYN_DEVICE_LIB_DIR/dyn-process.py" --timeout "$secs" -- "$@"
45
+ }
46
+
47
+ # dyn_pick_runtime -> the newest available iOS runtime identifier.
48
+ dyn_pick_runtime() {
49
+ [[ "$DYN_DRY_RUN" == 1 ]] && { echo "com.apple.CoreSimulator.SimRuntime.iOS-PLAN"; return 0; }
50
+ xcrun simctl list runtimes -j 2>/dev/null \
51
+ | jq -r '[.runtimes[] | select(.platform=="iOS" and .isAvailable)] | sort_by(.version) | last | .identifier // empty'
52
+ }
53
+
54
+ # dyn_pick_device_type iphone|ipad -> the newest numbered iPhone, or the newest 11-inch iPad Pro.
55
+ dyn_pick_device_type() {
56
+ local fam="${1:-iphone}"
57
+ [[ "$DYN_DRY_RUN" == 1 ]] && { echo "com.apple.CoreSimulator.SimDeviceType.${fam}-PLAN"; return 0; }
58
+ case "$fam" in
59
+ ipad) xcrun simctl list devicetypes -j 2>/dev/null | jq -r '
60
+ [.devicetypes[] | select(.productFamily=="iPad") | select(.name | test("^iPad Pro 11-inch"))] | last | .identifier // empty' ;;
61
+ *) xcrun simctl list devicetypes -j 2>/dev/null | jq -r '
62
+ [.devicetypes[] | select(.productFamily=="iPhone") | select(.name | test("^iPhone [0-9]+$"))]
63
+ | sort_by(.name | capture("(?<n>[0-9]+)").n | tonumber) | last | .identifier // empty' ;;
64
+ esac
65
+ }
66
+
67
+ # dyn_device_create <name> <device-type> <runtime> -> udid (stdout), or "" on failure.
68
+ dyn_device_create() {
69
+ if [[ "$DYN_DRY_RUN" == 1 ]]; then
70
+ dyn_plan "xcrun simctl create $1 $2 $3"
71
+ [[ -z "${DYN_OWNED_LEDGER:-}" ]] || printf '%s\n' "UDID-PLAN-${1##*-}" >> "$DYN_OWNED_LEDGER"
72
+ echo "UDID-PLAN-${1##*-}"; return 0
73
+ fi
74
+ local created
75
+ created="$(xcrun simctl create "$1" "$2" "$3" 2>/dev/null)" || return 1
76
+ if [[ -n "${DYN_OWNED_LEDGER:-}" && -n "$created" ]]; then printf '%s\n' "$created" >> "$DYN_OWNED_LEDGER"; fi
77
+ printf '%s\n' "$created"
78
+ }
79
+
80
+ # dyn_device_boot <udid> — boot and wait until the device is usable.
81
+ dyn_device_boot() {
82
+ dyn_cmd xcrun simctl boot "$1" >/dev/null 2>&1 || true # "already booted" is fine
83
+ dyn_cmd xcrun simctl bootstatus "$1" -b >/dev/null 2>&1
84
+ }
85
+
86
+ # dyn_device_prepare <udid> — deterministic status bar + every privacy grant reset.
87
+ dyn_device_prepare() {
88
+ dyn_cmd xcrun simctl status_bar "$1" override --time 9:41 --batteryLevel 100 --batteryState charged --wifiBars 3 --cellularBars 4 >/dev/null 2>&1 || true
89
+ dyn_cmd xcrun simctl privacy "$1" reset all >/dev/null 2>&1 || true
90
+ }
91
+
92
+ # dyn_device_erase <udid> — shut down and wipe (only for a device this run created).
93
+ dyn_device_erase() {
94
+ dyn_cmd xcrun simctl shutdown "$1" >/dev/null 2>&1 || true
95
+ dyn_cmd xcrun simctl erase "$1" >/dev/null 2>&1
96
+ }
97
+
98
+ # dyn_device_install <udid> <app-path> -> 0 on success; stderr from simctl is kept for the SKIP line.
99
+ dyn_device_install() { dyn_cmd xcrun simctl install "$1" "$2"; }
100
+
101
+ # dyn_device_container <udid> <bundle-id> -> the installed .app path, or "".
102
+ dyn_device_container() {
103
+ if [[ "$DYN_DRY_RUN" == 1 ]]; then dyn_plan "xcrun simctl get_app_container $1 $2 app"; echo ""; return 0; fi
104
+ xcrun simctl get_app_container "$1" "$2" app 2>/dev/null
105
+ }
106
+
107
+ # dyn_device_teardown <udid> — shutdown + delete. ONLY for a device this run created.
108
+ dyn_device_teardown() {
109
+ [[ -n "${1:-}" ]] || return 0
110
+ if [[ -n "${DYN_OWNED_LEDGER:-}" ]]; then
111
+ [[ ! -L "$DYN_OWNED_LEDGER" ]] && dyn_ledger_has "$DYN_OWNED_LEDGER" "$1" || return 0
112
+ fi
113
+ dyn_cmd_bounded "$DYN_TEARDOWN_STEP_TIMEOUT" xcrun simctl shutdown "$1" >/dev/null 2>&1 || true
114
+ dyn_cmd_bounded "$DYN_TEARDOWN_STEP_TIMEOUT" xcrun simctl delete "$1" >/dev/null 2>&1
115
+ }
116
+
117
+ # dyn_device_appearance <udid> light|dark ; dyn_device_content_size <udid> <size>
118
+ dyn_device_appearance() { dyn_cmd xcrun simctl ui "$1" appearance "$2" >/dev/null 2>&1 || true; }
119
+ dyn_device_content_size() { dyn_cmd xcrun simctl ui "$1" content_size "$2" >/dev/null 2>&1 || true; }
120
+
121
+ # dyn_ledger_has <file> <line> — exact whole-line membership; a missing file has nothing.
122
+ dyn_ledger_has() { [[ -f "$1" ]] && grep -qxF -- "$2" "$1"; }
123
+
@@ -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,75 @@
1
+ #!/usr/bin/env bash
2
+ # lib/dyn-geometry.sh — layout heuristics over a Maestro view hierarchy (JSON), for
3
+ # the dark-mode, Dynamic Type and iPad observations (dyn-dark-mode, dyn-dynamic-type,
4
+ # dyn-ipad-layout; guidelines 4.0 / 2.4.1). Pure jq over a file: testable on CI with
5
+ # recorded hierarchies, no device needed. Sourced by dynamic-run.sh. Bash 3.2.
6
+ #
7
+ # The hierarchy is what `maestro hierarchy` prints: a tree of {attributes:{text,
8
+ # accessibilityText, bounds:"[x1,y1][x2,y2]", …}, children:[…]}. The label a control
9
+ # exposes lives in `accessibilityText`, not `text` — matchers read both.
10
+ #
11
+ # Three heuristics, all judgment-call (a clipped frame is a hint, not a rejection):
12
+ # clipped a labelled node whose bounds leave the screen rectangle
13
+ # zero_size a labelled node with an empty rectangle (text that cannot be seen)
14
+ # overlap two labelled LEAF nodes whose rectangles overlap by more than half of
15
+ # the smaller one (a price row drawn over another at XXXL text size)
16
+ # A degenerate tree (<= 3 nodes) is SKIP: Flutter and Compose Multiplatform expose no
17
+ # semantics to Maestro on a perfectly healthy screen, so nothing can be judged.
18
+
19
+ # dyn_geometry_report <hierarchy.json> <screen_w> <screen_h> -> JSON
20
+ # {nodes, degenerate, clipped:[label…], zero_size:[label…], overlap:[[a,b]…]}
21
+ dyn_geometry_report() {
22
+ local file="$1" w="${2:-0}" h="${3:-0}"
23
+ [[ -f "$file" ]] || { echo '{"nodes":0,"degenerate":true,"clipped":[],"zero_size":[],"overlap":[],"error":"no hierarchy file"}'; return 0; }
24
+ jq -c --argjson W "$w" --argjson H "$h" '
25
+ def lbl: ((.attributes.accessibilityText // "") as $a | (.attributes.text // "") as $t
26
+ | if $a != "" then $a else $t end);
27
+ def rect: (.attributes.bounds // "" | capture("\\[(?<x1>-?[0-9]+),(?<y1>-?[0-9]+)\\]\\[(?<x2>-?[0-9]+),(?<y2>-?[0-9]+)\\]")?
28
+ | {x1:(.x1|tonumber), y1:(.y1|tonumber), x2:(.x2|tonumber), y2:(.y2|tonumber)});
29
+ def leaf: ((.children // []) | length) == 0;
30
+ [.. | objects | select(has("attributes"))] as $nodes
31
+ | ($nodes | length) as $n
32
+ | [$nodes[] | select(lbl != "") | select(rect != null) | {label: lbl, r: rect, leaf: leaf}] as $labelled
33
+ # Screen rectangle: the size given by the caller, else the bounds of the root node (the Maestro root
34
+ # is the full screen), else no clipping judgement at all.
35
+ | (if ($W > 0 and $H > 0) then {w:$W, h:$H}
36
+ else (($nodes[0] // {}) | rect) as $root | (if $root == null then null else {w:$root.x2, h:$root.y2} end) end) as $scr
37
+ | ($scr != null and $scr.w > 0 and $scr.h > 0) as $screen
38
+ | {nodes: $n,
39
+ degenerate: ($n <= 3),
40
+ clipped: [$labelled[] | select($screen) | select(.r.x1 < -1 or .r.y1 < -1 or .r.x2 > $scr.w + 1 or .r.y2 > $scr.h + 1) | .label],
41
+ zero_size: [$labelled[] | select(.r.x2 - .r.x1 <= 0 or .r.y2 - .r.y1 <= 0) | .label],
42
+ overlap: ([$labelled[] | select(.leaf) | select(.r.x2 - .r.x1 > 0 and .r.y2 - .r.y1 > 0)] as $L
43
+ | [range(0; $L|length) as $i | range($i + 1; $L|length) as $j
44
+ | $L[$i] as $a | $L[$j] as $b
45
+ | (([$a.r.x2, $b.r.x2] | min) - ([$a.r.x1, $b.r.x1] | max)) as $iw
46
+ | (([$a.r.y2, $b.r.y2] | min) - ([$a.r.y1, $b.r.y1] | max)) as $ih
47
+ | select($iw > 0 and $ih > 0)
48
+ | (($a.r.x2 - $a.r.x1) * ($a.r.y2 - $a.r.y1)) as $aa
49
+ | (($b.r.x2 - $b.r.x1) * ($b.r.y2 - $b.r.y1)) as $ab
50
+ | select(($iw * $ih) > 0.5 * ([$aa, $ab] | min))
51
+ | [$a.label, $b.label]])}
52
+ ' "$file" 2>/dev/null || echo '{"nodes":0,"degenerate":true,"clipped":[],"zero_size":[],"overlap":[],"error":"hierarchy is not JSON"}'
53
+ }
54
+
55
+ # dyn_geometry_line <report-json> <guideline> <rule-id> <context> [<screenshot>]
56
+ # -> one transcript line. Degenerate -> SKIP; any heuristic hit -> FINDING; else PASS.
57
+ dyn_geometry_line() {
58
+ local rep="$1" guideline="$2" id="$3" ctx="$4" shot="${5:-}"
59
+ local n c z o first
60
+ n="$(jq -r .nodes <<<"$rep")"
61
+ if [[ "$(jq -r .degenerate <<<"$rep")" == "true" ]]; then
62
+ printf 'DYNAMIC-SKIP: %s [%s] — %s: accessibility tree has %s node(s) (degenerate: Flutter/Compose expose no semantics to Maestro); layout cannot be judged from the tree%s\n' \
63
+ "$guideline" "$id" "$ctx" "$n" "${shot:+ — judge the screenshot by eye: $shot}"
64
+ return 0
65
+ fi
66
+ c="$(jq -r '.clipped|length' <<<"$rep")"; z="$(jq -r '.zero_size|length' <<<"$rep")"; o="$(jq -r '.overlap|length' <<<"$rep")"
67
+ if (( c + z + o > 0 )); then
68
+ first="$(jq -r '[(.clipped[]? | "clipped: \(.)"), (.zero_size[]? | "zero-size: \(.)"), (.overlap[]? | "overlap: \(.[0]) / \(.[1])")] | .[0:3] | join("; ")' <<<"$rep")"
69
+ printf 'DYNAMIC-FINDING: %s [%s] — %s: %s clipped, %s zero-size, %s overlapping labelled frame(s) in a %s-node tree (%s)%s\n' \
70
+ "$guideline" "$id" "$ctx" "$c" "$z" "$o" "$n" "$first" "${shot:+; screenshot $shot}"
71
+ return 0
72
+ fi
73
+ printf 'DYNAMIC-PASS: %s [%s] — %s: no clipped, zero-size or overlapping labelled frame in a %s-node tree%s\n' \
74
+ "$guideline" "$id" "$ctx" "$n" "${shot:+; screenshot $shot}"
75
+ }