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.
- package/CHANGELOG.md +256 -0
- package/README.md +108 -39
- package/bin/cli.js +8 -0
- package/package.json +2 -2
- package/skills/appstore-precheck/SKILL.md +99 -157
- package/skills/appstore-precheck/guidelines-baseline.json +285 -36
- package/skills/appstore-precheck/guidelines-fingerprints.json +319 -93
- package/skills/appstore-precheck/references/finding-commentary.md +93 -0
- package/skills/appstore-precheck/references/methodology.md +81 -26
- package/skills/appstore-precheck/references/optional-review.md +56 -0
- package/skills/appstore-precheck/references/pierre-deep-review.md +323 -44
- package/skills/appstore-precheck/references/review-catalog.json +740 -0
- package/skills/appstore-precheck/references/screenshot-vision-review.md +8 -8
- package/skills/appstore-precheck/references/simulator-dynamic-review.md +398 -54
- package/skills/appstore-precheck/references/typesafe-example.json +239 -0
- package/skills/appstore-precheck/references/typesafe.md +216 -0
- package/skills/appstore-precheck/scripts/app-discover.sh +138 -0
- package/skills/appstore-precheck/scripts/artifact-review.sh +10 -0
- package/skills/appstore-precheck/scripts/augment-json.py +29 -0
- package/skills/appstore-precheck/scripts/build-run.sh +5 -0
- package/skills/appstore-precheck/scripts/coverage-sections.sh +6 -0
- package/skills/appstore-precheck/scripts/dynamic-run.sh +400 -0
- package/skills/appstore-precheck/scripts/dynamic.sh +329 -0
- package/skills/appstore-precheck/scripts/evidence.sh +49 -15
- package/skills/appstore-precheck/scripts/findings.sh +76 -26
- package/skills/appstore-precheck/scripts/framework-detect.sh +101 -0
- package/skills/appstore-precheck/scripts/guideline-cite.sh +4 -1
- package/skills/appstore-precheck/scripts/lib/artifact-review.py +518 -0
- package/skills/appstore-precheck/scripts/lib/asc-client.py +293 -0
- package/skills/appstore-precheck/scripts/lib/build-evidence.py +50 -0
- package/skills/appstore-precheck/scripts/lib/build-exec.py +50 -0
- package/skills/appstore-precheck/scripts/lib/build-plan.py +106 -0
- package/skills/appstore-precheck/scripts/lib/build-plan.sh +15 -0
- package/skills/appstore-precheck/scripts/lib/build-run.py +177 -0
- package/skills/appstore-precheck/scripts/lib/coverage-run.sh +23 -0
- package/skills/appstore-precheck/scripts/lib/coverage-sections.py +244 -0
- package/skills/appstore-precheck/scripts/lib/dyn-bundle.sh +185 -0
- package/skills/appstore-precheck/scripts/lib/dyn-demo-login.py +111 -0
- package/skills/appstore-precheck/scripts/lib/dyn-device.sh +123 -0
- package/skills/appstore-precheck/scripts/lib/dyn-explore.py +312 -0
- package/skills/appstore-precheck/scripts/lib/dyn-geometry.sh +75 -0
- package/skills/appstore-precheck/scripts/lib/dyn-guideline-capture.py +301 -0
- package/skills/appstore-precheck/scripts/lib/dyn-guidelines.py +112 -0
- package/skills/appstore-precheck/scripts/lib/dyn-guidelines.sh +23 -0
- package/skills/appstore-precheck/scripts/lib/dyn-hosts.sh +134 -0
- package/skills/appstore-precheck/scripts/lib/dyn-process.py +75 -0
- package/skills/appstore-precheck/scripts/lib/dyn-quorum.sh +90 -0
- package/skills/appstore-precheck/scripts/lib/dyn-scrub.py +79 -0
- package/skills/appstore-precheck/scripts/lib/dyn-signals.sh +120 -0
- package/skills/appstore-precheck/scripts/lib/guideline-text.sh +23 -5
- package/skills/appstore-precheck/scripts/lib/metadata-review.py +369 -0
- package/skills/appstore-precheck/scripts/lib/optin-scan.sh +73 -0
- package/skills/appstore-precheck/scripts/lib/optional-records.py +60 -0
- package/skills/appstore-precheck/scripts/lib/png-uniform.py +115 -0
- package/skills/appstore-precheck/scripts/lib/runtime-blocking.py +26 -0
- package/skills/appstore-precheck/scripts/lib/safe_write.py +61 -0
- package/skills/appstore-precheck/scripts/lib/scan-guidelines.sh +199 -0
- package/skills/appstore-precheck/scripts/lib/static-guidelines.py +341 -0
- package/skills/appstore-precheck/scripts/lib/static-reader.py +39 -0
- package/skills/appstore-precheck/scripts/metadata-review.sh +4 -0
- package/skills/appstore-precheck/scripts/opt-in-review.py +160 -0
- package/skills/appstore-precheck/scripts/runtime-review.sh +5 -0
- package/skills/appstore-precheck/scripts/scan.sh +132 -21
- package/skills/appstore-precheck/scripts/semantic/__init__.py +1 -0
- package/skills/appstore-precheck/scripts/semantic/client.py +95 -0
- package/skills/appstore-precheck/scripts/semantic/collect.py +165 -0
- package/skills/appstore-precheck/scripts/semantic/engine.py +320 -0
- package/skills/appstore-precheck/scripts/semantic/questions.py +167 -0
- package/skills/appstore-precheck/scripts/semantic/review_v4.py +81 -0
- package/skills/appstore-precheck/scripts/semantic-review.py +61 -0
|
@@ -0,0 +1,293 @@
|
|
|
1
|
+
import argparse
|
|
2
|
+
import base64
|
|
3
|
+
import http.client
|
|
4
|
+
import ipaddress
|
|
5
|
+
import importlib.util
|
|
6
|
+
import json
|
|
7
|
+
import os
|
|
8
|
+
import pathlib
|
|
9
|
+
import shutil
|
|
10
|
+
import socket
|
|
11
|
+
import ssl
|
|
12
|
+
import subprocess
|
|
13
|
+
import sys
|
|
14
|
+
import time
|
|
15
|
+
import urllib.error
|
|
16
|
+
import urllib.parse
|
|
17
|
+
import urllib.request
|
|
18
|
+
|
|
19
|
+
API_BASE = "https://api.appstoreconnect.apple.com"
|
|
20
|
+
|
|
21
|
+
class ApiError(Exception):
|
|
22
|
+
"""An unavailable, unauthorized, incomplete, or malformed API response."""
|
|
23
|
+
|
|
24
|
+
def b64url(raw):
|
|
25
|
+
return base64.urlsafe_b64encode(raw).rstrip(b"=").decode("ascii")
|
|
26
|
+
|
|
27
|
+
def der_to_jose(raw):
|
|
28
|
+
"""Convert OpenSSL ECDSA DER signature to the 64-byte JWT R||S format."""
|
|
29
|
+
def length(offset):
|
|
30
|
+
if offset >= len(raw):
|
|
31
|
+
raise ApiError("JWT signature encoding unavailable")
|
|
32
|
+
n = raw[offset]
|
|
33
|
+
if n < 128:
|
|
34
|
+
return n, offset + 1
|
|
35
|
+
width = n & 127
|
|
36
|
+
if not width or width > 2 or offset + 1 + width > len(raw):
|
|
37
|
+
raise ApiError("JWT signature encoding unavailable")
|
|
38
|
+
return int.from_bytes(raw[offset + 1:offset + 1 + width], "big"), offset + 1 + width
|
|
39
|
+
|
|
40
|
+
if not raw or raw[0] != 0x30:
|
|
41
|
+
raise ApiError("JWT signature encoding unavailable")
|
|
42
|
+
total, at = length(1)
|
|
43
|
+
if at + total != len(raw):
|
|
44
|
+
raise ApiError("JWT signature encoding unavailable")
|
|
45
|
+
values = []
|
|
46
|
+
for _ in range(2):
|
|
47
|
+
if at >= len(raw) or raw[at] != 0x02:
|
|
48
|
+
raise ApiError("JWT signature encoding unavailable")
|
|
49
|
+
size, at = length(at + 1)
|
|
50
|
+
value = int.from_bytes(raw[at:at + size], "big")
|
|
51
|
+
at += size
|
|
52
|
+
if value <= 0 or value >= (1 << 256):
|
|
53
|
+
raise ApiError("JWT signature encoding unavailable")
|
|
54
|
+
values.append(value.to_bytes(32, "big"))
|
|
55
|
+
if at != len(raw):
|
|
56
|
+
raise ApiError("JWT signature encoding unavailable")
|
|
57
|
+
return b"".join(values)
|
|
58
|
+
|
|
59
|
+
def make_jwt(key_id, issuer_id, key_path):
|
|
60
|
+
if not shutil.which("openssl"):
|
|
61
|
+
raise ApiError("openssl unavailable; install OpenSSL to inspect App Store Connect")
|
|
62
|
+
if not pathlib.Path(key_path).is_file():
|
|
63
|
+
raise ApiError("ASC_KEY_PATH file unavailable")
|
|
64
|
+
now = int(time.time())
|
|
65
|
+
header = {"alg": "ES256", "kid": key_id, "typ": "JWT"}
|
|
66
|
+
payload = {"iss": issuer_id, "iat": now, "exp": now + 600,
|
|
67
|
+
"aud": "appstoreconnect-v1"}
|
|
68
|
+
compact = ".".join(b64url(json.dumps(x, separators=(",", ":")).encode("utf-8"))
|
|
69
|
+
for x in (header, payload))
|
|
70
|
+
try:
|
|
71
|
+
signed = subprocess.run(["openssl", "dgst", "-sha256", "-sign", key_path],
|
|
72
|
+
input=compact.encode("ascii"), stdout=subprocess.PIPE,
|
|
73
|
+
stderr=subprocess.DEVNULL, timeout=10, check=False)
|
|
74
|
+
except (OSError, subprocess.TimeoutExpired):
|
|
75
|
+
raise ApiError("JWT signing unavailable")
|
|
76
|
+
if signed.returncode != 0:
|
|
77
|
+
raise ApiError("JWT signing unavailable")
|
|
78
|
+
return compact + "." + b64url(der_to_jose(signed.stdout))
|
|
79
|
+
|
|
80
|
+
class ASC:
|
|
81
|
+
def __init__(self, fixture=None):
|
|
82
|
+
if fixture is not None and (not isinstance(fixture, dict) or not isinstance(fixture.get("responses"), dict)):
|
|
83
|
+
raise ApiError("Fixture API response collection malformed")
|
|
84
|
+
self.fixture = fixture
|
|
85
|
+
self.token = None
|
|
86
|
+
self.responses = {}
|
|
87
|
+
self.deadline = time.monotonic() + 120
|
|
88
|
+
if fixture is None:
|
|
89
|
+
key_id = os.environ.get("ASC_KEY_ID")
|
|
90
|
+
issuer_id = os.environ.get("ASC_ISSUER_ID")
|
|
91
|
+
key_path = os.environ.get("ASC_KEY_PATH")
|
|
92
|
+
if not all((key_id, issuer_id, key_path)):
|
|
93
|
+
raise ApiError("ASC_KEY_ID, ASC_ISSUER_ID, and ASC_KEY_PATH are required")
|
|
94
|
+
self.token = make_jwt(key_id, issuer_id, key_path)
|
|
95
|
+
|
|
96
|
+
def get(self, path):
|
|
97
|
+
if time.monotonic() >= self.deadline:
|
|
98
|
+
raise ApiError("App Store Connect collection deadline exceeded")
|
|
99
|
+
value = self._get(path)
|
|
100
|
+
self.responses[path] = value
|
|
101
|
+
return value
|
|
102
|
+
|
|
103
|
+
def _get(self, path):
|
|
104
|
+
if not path.startswith("/v1/") and not path.startswith("/v2/"):
|
|
105
|
+
raise ApiError("Unsupported App Store Connect resource")
|
|
106
|
+
if self.fixture is not None:
|
|
107
|
+
value = self.fixture.get("responses", {}).get(path)
|
|
108
|
+
if not isinstance(value, dict):
|
|
109
|
+
raise ApiError("Fixture API resource unavailable")
|
|
110
|
+
if value.get("fixture_error") in ("authorization", "timeout"):
|
|
111
|
+
raise ApiError("App Store Connect request unavailable")
|
|
112
|
+
return value
|
|
113
|
+
request = urllib.request.Request(API_BASE + path,
|
|
114
|
+
headers={"Authorization": "Bearer " + self.token,
|
|
115
|
+
"Accept": "application/json"}, method="GET")
|
|
116
|
+
try:
|
|
117
|
+
with urllib.request.build_opener(NoRedirect()).open(request, timeout=max(0.1, min(12, self.deadline - time.monotonic()))) as response:
|
|
118
|
+
if response.status != 200:
|
|
119
|
+
raise ApiError("App Store Connect request unavailable")
|
|
120
|
+
raw = response.read(4 * 1024 * 1024 + 1)
|
|
121
|
+
if len(raw) > 4 * 1024 * 1024:
|
|
122
|
+
raise ApiError("App Store Connect response too large")
|
|
123
|
+
value = json.loads(raw.decode("utf-8"))
|
|
124
|
+
if not isinstance(value, dict):
|
|
125
|
+
raise ValueError("not an object")
|
|
126
|
+
return value
|
|
127
|
+
except (urllib.error.URLError, OSError, ValueError, UnicodeError):
|
|
128
|
+
raise ApiError("App Store Connect request unavailable")
|
|
129
|
+
|
|
130
|
+
def items(self, path):
|
|
131
|
+
result = []
|
|
132
|
+
next_path = path
|
|
133
|
+
seen = set()
|
|
134
|
+
for _ in range(10):
|
|
135
|
+
if next_path in seen:
|
|
136
|
+
raise ApiError("App Store Connect pagination cycle")
|
|
137
|
+
seen.add(next_path)
|
|
138
|
+
value = self.get(next_path)
|
|
139
|
+
data = value.get("data")
|
|
140
|
+
if not isinstance(data, list) or any(not isinstance(x, dict) for x in data):
|
|
141
|
+
raise ApiError("App Store Connect list unavailable")
|
|
142
|
+
result.extend(data)
|
|
143
|
+
links = value.get("links")
|
|
144
|
+
next_url = links.get("next") if isinstance(links, dict) else None
|
|
145
|
+
if not next_url:
|
|
146
|
+
total = value.get("meta", {}).get("paging", {}).get("total") if isinstance(value.get("meta"), dict) and isinstance(value.get("meta", {}).get("paging"), dict) else None
|
|
147
|
+
if total is not None and (type(total) is not int or total != len(result)):
|
|
148
|
+
raise ApiError("App Store Connect list incomplete")
|
|
149
|
+
return result
|
|
150
|
+
if not isinstance(next_url, str):
|
|
151
|
+
raise ApiError("Malformed App Store Connect pagination URL")
|
|
152
|
+
parsed = urllib.parse.urlparse(next_url)
|
|
153
|
+
if parsed.scheme != "https" or parsed.netloc != "api.appstoreconnect.apple.com" or parsed.path != path.split("?", 1)[0] or parsed.fragment:
|
|
154
|
+
raise ApiError("Unexpected App Store Connect pagination URL")
|
|
155
|
+
next_path = parsed.path + ("?" + parsed.query if parsed.query else "")
|
|
156
|
+
raise ApiError("App Store Connect list exceeded page budget")
|
|
157
|
+
|
|
158
|
+
def safe(api, method, path):
|
|
159
|
+
try:
|
|
160
|
+
return getattr(api, method)(path)
|
|
161
|
+
except ApiError as exc:
|
|
162
|
+
return exc
|
|
163
|
+
|
|
164
|
+
class NoRedirect(urllib.request.HTTPRedirectHandler):
|
|
165
|
+
def redirect_request(self, request, fp, code, msg, headers, newurl):
|
|
166
|
+
raise urllib.error.URLError("App Store Connect redirect refused")
|
|
167
|
+
|
|
168
|
+
def one(data):
|
|
169
|
+
return data.get("data") if isinstance(data, dict) else None
|
|
170
|
+
|
|
171
|
+
def attrs(item):
|
|
172
|
+
value = item.get("attributes") if isinstance(item, dict) else None
|
|
173
|
+
return value if isinstance(value, dict) else {}
|
|
174
|
+
|
|
175
|
+
def relation(item, name):
|
|
176
|
+
relationships = item.get("relationships") if isinstance(item, dict) else None
|
|
177
|
+
value = relationships.get(name) if isinstance(relationships, dict) else None
|
|
178
|
+
return value.get("data") if isinstance(value, dict) else None
|
|
179
|
+
|
|
180
|
+
def identifier(item):
|
|
181
|
+
return item.get("id") if isinstance(item, dict) else None
|
|
182
|
+
|
|
183
|
+
def encode_id(value):
|
|
184
|
+
return urllib.parse.quote(str(value), safe="")
|
|
185
|
+
|
|
186
|
+
def collect_info(api, app, out, info_id=None, version_id=None, bundle_id=None, version_string=None, build_number=None):
|
|
187
|
+
infos = safe(api, "items", app + "/appInfos")
|
|
188
|
+
if isinstance(infos, ApiError):
|
|
189
|
+
out["info"] = infos
|
|
190
|
+
else:
|
|
191
|
+
matches = [x for x in infos if identifier(x) == info_id] if info_id else infos
|
|
192
|
+
info = matches[0] if len(matches) == 1 and identifier(matches[0]) else None
|
|
193
|
+
out["info"] = info or ApiError("App info selection missing or ambiguous")
|
|
194
|
+
# Capture every info localization for conservative whole-listing name proof.
|
|
195
|
+
for candidate in infos:
|
|
196
|
+
if identifier(candidate):
|
|
197
|
+
safe(api, "items", "/v1/appInfos/" + encode_id(identifier(candidate)) + "/appInfoLocalizations")
|
|
198
|
+
if info:
|
|
199
|
+
path = "/v1/appInfos/" + encode_id(identifier(info))
|
|
200
|
+
out["age"] = safe(api, "get", path + "/ageRatingDeclaration")
|
|
201
|
+
out["info_localizations"] = safe(api, "items", path + "/appInfoLocalizations")
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
def collect_version(api, app, out, info_id=None, version_id=None, bundle_id=None, version_string=None, build_number=None):
|
|
205
|
+
versions = safe(api, "items", app + "/appStoreVersions")
|
|
206
|
+
if isinstance(versions, ApiError):
|
|
207
|
+
out["version"] = versions
|
|
208
|
+
else:
|
|
209
|
+
ios = [x for x in versions if attrs(x).get("platform") == "IOS"]
|
|
210
|
+
matches = [x for x in ios if (not version_id or identifier(x) == version_id) and
|
|
211
|
+
(not version_string or attrs(x).get("versionString") == version_string)]
|
|
212
|
+
version = matches[0] if len(matches) == 1 and identifier(matches[0]) else None
|
|
213
|
+
out["version"] = version or ApiError("App Store version selection missing or ambiguous")
|
|
214
|
+
out["selection_status"] = "SELECTED" if version else "UNRESOLVED"
|
|
215
|
+
if bundle_id and attrs(one(out["app"])).get("bundleId") != bundle_id:
|
|
216
|
+
version = None
|
|
217
|
+
out["version"] = ApiError("Bundle identity mismatch or unavailable")
|
|
218
|
+
out["selection_status"] = "UNRESOLVED"
|
|
219
|
+
if version:
|
|
220
|
+
path = "/v1/appStoreVersions/" + encode_id(identifier(version))
|
|
221
|
+
out["build"] = safe(api, "get", path + "/build")
|
|
222
|
+
if build_number and attrs(one(out["build"])).get("version") != build_number:
|
|
223
|
+
out["version"] = ApiError("Build identity mismatch or unavailable")
|
|
224
|
+
out["selection_status"] = "UNRESOLVED"
|
|
225
|
+
out["review"] = ApiError("Build selection unavailable")
|
|
226
|
+
out["version_localizations"] = ApiError("Build selection unavailable")
|
|
227
|
+
out["screenshots"] = ApiError("Build selection unavailable")
|
|
228
|
+
else:
|
|
229
|
+
out["review"] = safe(api, "get", path + "/appStoreReviewDetail")
|
|
230
|
+
locs = safe(api, "items", path + "/appStoreVersionLocalizations")
|
|
231
|
+
out["version_localizations"] = locs
|
|
232
|
+
if isinstance(locs, list):
|
|
233
|
+
screenshots = []
|
|
234
|
+
for loc in locs:
|
|
235
|
+
loc_id = identifier(loc)
|
|
236
|
+
if not loc_id:
|
|
237
|
+
continue
|
|
238
|
+
sets = safe(api, "items", "/v1/appStoreVersionLocalizations/" + encode_id(loc_id) + "/appScreenshotSets")
|
|
239
|
+
if isinstance(sets, ApiError):
|
|
240
|
+
screenshots.append(sets)
|
|
241
|
+
else:
|
|
242
|
+
for image_set in sets:
|
|
243
|
+
set_id = identifier(image_set)
|
|
244
|
+
if set_id:
|
|
245
|
+
screenshots.append(safe(api, "items", "/v1/appScreenshotSets/" + encode_id(set_id) + "/appScreenshots"))
|
|
246
|
+
out["screenshots"] = screenshots
|
|
247
|
+
if isinstance(out.get("version"), ApiError):
|
|
248
|
+
for key in ("review", "version_localizations", "screenshots"):
|
|
249
|
+
out[key] = ApiError("App Store version or build selection unavailable")
|
|
250
|
+
|
|
251
|
+
|
|
252
|
+
def collect_products(api, app, out, info_id=None, version_id=None, bundle_id=None, version_string=None, build_number=None):
|
|
253
|
+
purchases = safe(api, "items", app + "/inAppPurchasesV2")
|
|
254
|
+
groups = safe(api, "items", app + "/subscriptionGroups")
|
|
255
|
+
if isinstance(groups, list):
|
|
256
|
+
subscriptions = []
|
|
257
|
+
for group in groups:
|
|
258
|
+
gid = identifier(group)
|
|
259
|
+
if gid:
|
|
260
|
+
items = safe(api, "items", "/v1/subscriptionGroups/" + encode_id(gid) + "/subscriptions")
|
|
261
|
+
if isinstance(items, ApiError):
|
|
262
|
+
subscriptions = items
|
|
263
|
+
break
|
|
264
|
+
subscriptions.extend(items)
|
|
265
|
+
out["subscriptions"] = subscriptions
|
|
266
|
+
else:
|
|
267
|
+
out["subscriptions"] = groups
|
|
268
|
+
out["purchases"] = purchases
|
|
269
|
+
if isinstance(purchases, list) and isinstance(out["subscriptions"], list):
|
|
270
|
+
shots = []
|
|
271
|
+
for product in purchases:
|
|
272
|
+
pid = identifier(product)
|
|
273
|
+
if pid:
|
|
274
|
+
shots.append(safe(api, "get", "/v2/inAppPurchases/" + encode_id(pid) + "/appStoreReviewScreenshot"))
|
|
275
|
+
for product in out["subscriptions"]:
|
|
276
|
+
pid = identifier(product)
|
|
277
|
+
if pid:
|
|
278
|
+
shots.append(safe(api, "get", "/v1/subscriptions/" + encode_id(pid) + "/appStoreReviewScreenshot"))
|
|
279
|
+
out["iap_screenshots"] = shots
|
|
280
|
+
|
|
281
|
+
|
|
282
|
+
def collect_asc(api, app_id, version_id=None, info_id=None, bundle_id=None, version_string=None, build_number=None):
|
|
283
|
+
app = '/v1/apps/' + encode_id(app_id)
|
|
284
|
+
out = {'app': safe(api, 'get', app)}
|
|
285
|
+
collect_info(api, app, out, info_id=info_id)
|
|
286
|
+
collect_version(api, app, out, version_id=version_id, bundle_id=bundle_id, version_string=version_string, build_number=build_number)
|
|
287
|
+
collect_products(api, app, out)
|
|
288
|
+
out['price'] = safe(api, 'get', app + '/appPriceSchedule')
|
|
289
|
+
out['availability'] = safe(api, 'get', app + '/appAvailabilityV2')
|
|
290
|
+
available = one(out['availability'])
|
|
291
|
+
if available and identifier(available):
|
|
292
|
+
out['territories'] = safe(api, 'items', '/v2/appAvailabilities/' + encode_id(identifier(available)) + '/territoryAvailabilities')
|
|
293
|
+
return out
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
"""Small local source-integrity report; no distribution attestation."""
|
|
2
|
+
import hashlib
|
|
3
|
+
import json
|
|
4
|
+
import os
|
|
5
|
+
import stat
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
PRUNE = {'.git', 'node_modules', 'Pods', 'build', 'DerivedData', '.build', '.dart_tool',
|
|
10
|
+
'__pycache__', '.gradle', '.kotlin', '.idea'}
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def file_digest(path):
|
|
14
|
+
fd = os.open(str(path), os.O_RDONLY | os.O_NONBLOCK | os.O_NOFOLLOW)
|
|
15
|
+
with os.fdopen(fd, 'rb') as stream:
|
|
16
|
+
if not stat.S_ISREG(os.fstat(stream.fileno()).st_mode):
|
|
17
|
+
return None
|
|
18
|
+
digest = hashlib.sha256()
|
|
19
|
+
for chunk in iter(lambda: stream.read(1024 * 1024), b''):
|
|
20
|
+
digest.update(chunk)
|
|
21
|
+
return digest.hexdigest()
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def snapshot(root):
|
|
25
|
+
result = {}
|
|
26
|
+
for base, dirs, files in os.walk(root, followlinks=False):
|
|
27
|
+
dirs[:] = sorted(d for d in dirs if d not in PRUNE)
|
|
28
|
+
for name in sorted(files + [d for d in dirs if (Path(base) / d).is_symlink()]):
|
|
29
|
+
path = Path(base) / name
|
|
30
|
+
mode = path.lstat().st_mode
|
|
31
|
+
if stat.S_ISLNK(mode):
|
|
32
|
+
digest = hashlib.sha256(os.readlink(path).encode()).hexdigest()
|
|
33
|
+
elif stat.S_ISREG(mode):
|
|
34
|
+
digest = file_digest(path)
|
|
35
|
+
else:
|
|
36
|
+
continue
|
|
37
|
+
if digest is not None:
|
|
38
|
+
result[path.relative_to(root).as_posix()] = digest
|
|
39
|
+
return result
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def finish(repo, before, out, configuration, app):
|
|
43
|
+
unchanged = before == snapshot(repo)
|
|
44
|
+
report = {'source_unchanged': unchanged, 'configuration': configuration,
|
|
45
|
+
'app': str(app) if app else None, 'distribution': 'simulator',
|
|
46
|
+
'signed_distribution_verified': False, 'physical_device_verified': False,
|
|
47
|
+
'source_snapshot_scope': 'Regular files and symlink text; special files excluded.',
|
|
48
|
+
'source_snapshot_excluded_directories': sorted(PRUNE)}
|
|
49
|
+
(out / 'build-provenance.json').write_text(json.dumps(report, indent=2) + '\n')
|
|
50
|
+
return unchanged
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
"""Bounded build subprocesses with isolated environment and retained diagnostics.
|
|
2
|
+
|
|
3
|
+
Adapted from the allowlisted build-exec.py process-group and environment pattern.
|
|
4
|
+
"""
|
|
5
|
+
import os
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
import signal
|
|
8
|
+
import subprocess
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def environment(home):
|
|
12
|
+
home = Path(home)
|
|
13
|
+
env = {'PATH': os.environ.get('PATH', '/usr/bin:/bin'), 'HOME': str(home),
|
|
14
|
+
'CFFIXED_USER_HOME': str(home), 'TMPDIR': str(home / 'tmp'), 'CI': '1',
|
|
15
|
+
'COCOAPODS_DISABLE_STATS': '1', 'EXPO_NO_TELEMETRY': '1',
|
|
16
|
+
'npm_config_cache': str(home / '.npm'), 'PUB_CACHE': str(home / '.pub-cache'),
|
|
17
|
+
'GRADLE_USER_HOME': str(home / '.gradle'), 'LANG': 'C.UTF-8'}
|
|
18
|
+
(home / 'tmp').mkdir(parents=True, exist_ok=True)
|
|
19
|
+
for key in ('DEVELOPER_DIR', 'GEM_PATH'):
|
|
20
|
+
if key in os.environ:
|
|
21
|
+
env[key] = os.environ[key]
|
|
22
|
+
return env
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def kill_group(proc):
|
|
26
|
+
try:
|
|
27
|
+
os.killpg(proc.pid, signal.SIGKILL)
|
|
28
|
+
except ProcessLookupError:
|
|
29
|
+
pass
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def execute(command, cwd, home, log, timeout):
|
|
33
|
+
proc = None
|
|
34
|
+
try:
|
|
35
|
+
proc = subprocess.Popen(command, cwd=cwd, env=environment(home), stdout=subprocess.PIPE,
|
|
36
|
+
stderr=subprocess.STDOUT, start_new_session=True)
|
|
37
|
+
output, _ = proc.communicate(timeout=timeout)
|
|
38
|
+
code = proc.returncode
|
|
39
|
+
except subprocess.TimeoutExpired:
|
|
40
|
+
kill_group(proc); output, _ = proc.communicate(); code = 124
|
|
41
|
+
except FileNotFoundError as exc:
|
|
42
|
+
output, code = str(exc).encode(), 127
|
|
43
|
+
except BaseException:
|
|
44
|
+
if proc is not None:
|
|
45
|
+
kill_group(proc); proc.wait()
|
|
46
|
+
raise
|
|
47
|
+
fd = os.open(str(log), os.O_WRONLY | os.O_CREAT | os.O_APPEND | os.O_NOFOLLOW, 0o600)
|
|
48
|
+
with os.fdopen(fd, 'ab') as stream:
|
|
49
|
+
stream.write(output)
|
|
50
|
+
return code, output.decode('utf-8', 'replace')
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
"""Resolve an unambiguous build input and copy without live source symlinks."""
|
|
2
|
+
import fnmatch
|
|
3
|
+
import os
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
import shutil
|
|
6
|
+
import subprocess
|
|
7
|
+
|
|
8
|
+
EXCLUDED = {'.git', 'node_modules', 'Pods', 'build', 'DerivedData', '.build', '.dart_tool',
|
|
9
|
+
'__pycache__', '.gradle', '.kotlin', '.idea'}
|
|
10
|
+
SECRETS = ('.env*', '.npmrc', '.netrc', '*.pem', '*.key', '*.jks', '*.keystore',
|
|
11
|
+
'key.properties', '.sentryclirc', '*Secrets*.xcconfig', '*asc-key*.json',
|
|
12
|
+
'*.p8', '*.p12', '*.mobileprovision', '.appstore-precheck.json',
|
|
13
|
+
'id_rsa*', 'id_ed25519*', '.git-credentials', '*.keychain-db',
|
|
14
|
+
'credentials*.json', 'service-account*.json')
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def excluded(path):
|
|
18
|
+
return (path.name in EXCLUDED or any(fnmatch.fnmatch(path.name, pattern) for pattern in SECRETS)
|
|
19
|
+
or ('review_information' in path.parts and
|
|
20
|
+
(path.name.startswith('demo_') or 'password' in path.name.lower())))
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def projects(repo):
|
|
24
|
+
found = []
|
|
25
|
+
for base, dirs, files in os.walk(repo):
|
|
26
|
+
dirs[:] = sorted(d for d in dirs if not excluded(Path(base) / d))
|
|
27
|
+
for name in list(dirs):
|
|
28
|
+
if name.endswith(('.xcworkspace', '.xcodeproj')):
|
|
29
|
+
found.append(str((Path(base) / name).relative_to(repo))); dirs.remove(name)
|
|
30
|
+
# An ordinary CocoaPods workspace and its sibling project are one build choice.
|
|
31
|
+
workspaces = [p for p in found if p.endswith('.xcworkspace')]
|
|
32
|
+
if len(workspaces) == 1:
|
|
33
|
+
sibling = workspaces[0][:-len('.xcworkspace')] + '.xcodeproj'
|
|
34
|
+
found = [p for p in found if p != sibling]
|
|
35
|
+
return sorted(found) or (['Package.swift'] if (repo / 'Package.swift').is_file() else [])
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def flutter_target_allowed(target, repo):
|
|
39
|
+
caches = [Path.home() / '.pub-cache']
|
|
40
|
+
if os.environ.get('PUB_CACHE'):
|
|
41
|
+
caches.append(Path(os.environ['PUB_CACHE']).expanduser())
|
|
42
|
+
for cache in caches:
|
|
43
|
+
cache = cache.resolve()
|
|
44
|
+
if cache in (Path('/'), Path.home().resolve(), repo) or repo in cache.parents or cache in repo.parents:
|
|
45
|
+
continue
|
|
46
|
+
if cache in target.parents:
|
|
47
|
+
parts = target.relative_to(cache).parts
|
|
48
|
+
if len(parts) >= 2 and parts[0] in ('hosted', 'git'):
|
|
49
|
+
return True
|
|
50
|
+
sdk_roots = []
|
|
51
|
+
if os.environ.get('FLUTTER_ROOT'):
|
|
52
|
+
sdk_roots.append(Path(os.environ['FLUTTER_ROOT']).expanduser())
|
|
53
|
+
executable = shutil.which('flutter')
|
|
54
|
+
if executable:
|
|
55
|
+
sdk_roots.append(Path(executable).resolve().parent.parent)
|
|
56
|
+
for sdk in sdk_roots:
|
|
57
|
+
sdk = sdk.resolve()
|
|
58
|
+
if sdk in (Path('/'), Path.home().resolve(), repo) or repo in sdk.parents or sdk in repo.parents:
|
|
59
|
+
continue
|
|
60
|
+
if sdk in target.parents and (sdk / 'bin/flutter').is_file() and (sdk / 'packages/flutter/pubspec.yaml').is_file():
|
|
61
|
+
return True
|
|
62
|
+
return False
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def allowed_link(path, repo):
|
|
66
|
+
rel = path.relative_to(repo)
|
|
67
|
+
if any(rel.parts[i:i + 2] == ('ios', '.symlinks') for i in range(len(rel.parts) - 2)):
|
|
68
|
+
return flutter_target_allowed(path.resolve(), repo.resolve())
|
|
69
|
+
if '.xcframework/' in rel.as_posix() and rel.as_posix().endswith('/Versions/Current'):
|
|
70
|
+
return path.resolve().parent == path.parent.resolve()
|
|
71
|
+
return False
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def checked_links(repo):
|
|
75
|
+
links = []
|
|
76
|
+
for base, dirs, files in os.walk(repo, followlinks=False):
|
|
77
|
+
dirs[:] = [d for d in dirs if not excluded(Path(base) / d)]
|
|
78
|
+
for name in dirs + files:
|
|
79
|
+
path = Path(base) / name
|
|
80
|
+
if excluded(path) or not path.is_symlink():
|
|
81
|
+
continue
|
|
82
|
+
if not allowed_link(path, repo) or not path.exists():
|
|
83
|
+
raise ValueError('unsupported or broken source symlink: ' + str(path.relative_to(repo)))
|
|
84
|
+
target = path.resolve()
|
|
85
|
+
if target.is_dir() and any(p.is_symlink() for p in target.rglob('*')):
|
|
86
|
+
raise ValueError('nested symlinks in materialized input: ' + str(path.relative_to(repo)))
|
|
87
|
+
links.append(path)
|
|
88
|
+
return links
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def copy_inputs(repo, destination):
|
|
92
|
+
links = checked_links(repo)
|
|
93
|
+
command = ['rsync', '-a']
|
|
94
|
+
for pattern in sorted(EXCLUDED) + list(SECRETS):
|
|
95
|
+
command += ['--exclude=' + pattern]
|
|
96
|
+
command += ['--exclude=review_information/demo_*', '--exclude=review_information/*[Pp][Aa][Ss][Ss][Ww][Oo][Rr][Dd]*']
|
|
97
|
+
command += ['--exclude=/' + p.relative_to(repo).as_posix() for p in links]
|
|
98
|
+
destination.mkdir(parents=True, exist_ok=True)
|
|
99
|
+
subprocess.run(command + ['--', str(repo) + '/', str(destination) + '/'], check=True, capture_output=True)
|
|
100
|
+
for path in links:
|
|
101
|
+
target = destination / path.relative_to(repo)
|
|
102
|
+
target.parent.mkdir(parents=True, exist_ok=True)
|
|
103
|
+
if path.is_dir():
|
|
104
|
+
shutil.copytree(path.resolve(), target, ignore=lambda base, names: [n for n in names if excluded(Path(base) / n)])
|
|
105
|
+
else:
|
|
106
|
+
shutil.copy2(path.resolve(), target)
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
#!/usr/bin/env bash
|
|
2
|
+
# Bash entry point retained for build-plan consumers; never chooses the first candidate.
|
|
3
|
+
build_project() {
|
|
4
|
+
python3 - "$1" "$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" <<'PY'
|
|
5
|
+
import importlib.util, sys
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
spec = importlib.util.spec_from_file_location('build_plan', Path(sys.argv[2]) / 'build-plan.py')
|
|
8
|
+
module = importlib.util.module_from_spec(spec); spec.loader.exec_module(module)
|
|
9
|
+
found = module.projects(Path(sys.argv[1]))
|
|
10
|
+
if len(found) != 1:
|
|
11
|
+
print('SKIP: ambiguous build candidates: ' + ', '.join(found), file=sys.stderr)
|
|
12
|
+
raise SystemExit(3)
|
|
13
|
+
print(found[0])
|
|
14
|
+
PY
|
|
15
|
+
}
|