Skip to content

DeepSeek Harness Tauri 桌面版 | Only 8mb installer, zero environment setup, preset plugins, Windows / macOS / Linux.

feat(ci): submit external TestFlight review and enable automatic notifications

idealclover28d2abd46659
diff --git a/.github/scripts/ios-beta-review.py b/.github/scripts/ios-beta-review.py
new file mode 100644
index 00000000..eba40963
--- /dev/null
+++ b/.github/scripts/ios-beta-review.py
@@ -0,0 +1,257 @@
+import base64
+import json
+import os
+from pathlib import Path
+import re
+import subprocess
+import sys
+import time
+import urllib.error
+import urllib.parse
+import urllib.request
+
+
+HOST = 'https://api.appstoreconnect.apple.com'
+BUNDLE_ID = 'com.dshtauri.dshbridge'
+ACTIVE = {'WAITING_FOR_BETA_REVIEW', 'IN_BETA_REVIEW', 'BETA_APPROVED', 'READY_FOR_BETA_TESTING', 'IN_BETA_TESTING'}
+SUBMITTED = {'WAITING_FOR_REVIEW', 'IN_REVIEW', 'APPROVED'}
+
+
+def require(condition, message):
+ if not condition:
+ raise ValueError(message)
+
+
+def resource_id(value):
+ require(isinstance(value, str) and re.fullmatch(r'[A-Za-z0-9-]+', value), 'Invalid Apple resource identifier')
+ return value
+
+
+def api_url(path):
+ url = HOST + path if path.startswith('/') else path
+ parsed = urllib.parse.urlsplit(url)
+ require(parsed.scheme == 'https' and parsed.netloc == 'api.appstoreconnect.apple.com' and parsed.path.startswith('/v1/') and not parsed.fragment, 'Refusing untrusted Apple API URL')
+ return url
+
+
+class NoRedirect(urllib.request.HTTPRedirectHandler):
+ def redirect_request(self, req, fp, code, msg, headers, newurl):
+ raise ValueError('Refusing Apple API redirect')
+
+
+class ApiError(ValueError):
+ def __init__(self, status):
+ self.status = status
+ message = f'Apple API HTTP {status}; response omitted to protect account information'
+ if status == 403:
+ message += '; Beta review operations may require an App Manager team API key; ask the account administrator, do not change permissions automatically'
+ super().__init__(message)
+
+
+class Client:
+ def __init__(self, key_path, key_id, issuer, timeout=1800):
+ require(re.fullmatch(r'[A-Z0-9]{10}', key_id or ''), 'Invalid API key ID')
+ require(re.fullmatch(r'[A-Fa-f0-9-]{36}', issuer or ''), 'Invalid API issuer ID')
+ require(0 < timeout <= 1800, 'Processing timeout must be at most 30 minutes')
+ self.key_path, self.key_id, self.issuer = key_path, key_id, issuer
+ self.deadline = time.monotonic() + timeout
+ self.opener = urllib.request.build_opener(NoRedirect())
+
+ def token(self):
+ def encode(value):
+ return base64.urlsafe_b64encode(value).rstrip(b'=')
+
+ now = int(time.time())
+ header = encode(json.dumps({'alg': 'ES256', 'kid': self.key_id, 'typ': 'JWT'}).encode())
+ claims = encode(json.dumps({'iss': self.issuer, 'iat': now, 'exp': now + 300, 'aud': 'appstoreconnect-v1'}).encode())
+ message = header + b'.' + claims
+ result = subprocess.run(['openssl', 'dgst', '-sha256', '-sign', str(self.key_path)], input=message, capture_output=True, timeout=15)
+ require(result.returncode == 0, 'Unable to sign Apple API token; details suppressed')
+ sig = result.stdout
+ require(len(sig) >= 8 and sig[0] == 0x30 and sig[1] == len(sig) - 2 and sig[2] == 2, 'Invalid ES256 signature encoding')
+ end = 4 + sig[3]
+ require(end + 2 < len(sig) and sig[end] == 2 and end + 2 + sig[end + 1] == len(sig), 'Invalid ES256 signature components')
+ r = int.from_bytes(sig[4:end], 'big').to_bytes(32, 'big')
+ s = int.from_bytes(sig[end + 2:], 'big').to_bytes(32, 'big')
+ return (message + b'.' + encode(r + s)).decode()
+
+ def pause(self, seconds):
+ remaining = self.deadline - time.monotonic()
+ require(remaining > 0, 'Timed out waiting for the exact uploaded build; rerun review without uploading another build')
+ time.sleep(min(seconds, remaining))
+
+ def request(self, path, method='GET', payload=None):
+ url = api_url(path)
+ for attempt in range(3):
+ remaining = self.deadline - time.monotonic()
+ require(remaining > 0, 'Apple API operation exceeded the 30-minute deadline')
+ req = urllib.request.Request(url, method=method, headers={'Authorization': 'Bearer ' + self.token(), 'Content-Type': 'application/json'}, data=json.dumps(payload).encode() if payload is not None else None)
+ try:
+ with self.opener.open(req, timeout=min(30, remaining)) as response:
+ body = response.read()
+ return json.loads(body) if body else {}
+ except urllib.error.HTTPError as error:
+ status = error.code
+ error.close()
+ if method == 'GET' and (status == 429 or 500 <= status <= 599) and attempt < 2:
+ self.pause(5 * (attempt + 1))
+ continue
+ raise ApiError(status) from None
+ except (urllib.error.URLError, TimeoutError):
+ if method == 'GET' and attempt < 2:
+ self.pause(5 * (attempt + 1))
+ continue
+ raise ValueError('Apple API transport failed; mutation outcome may be unknown, rerun safely after checking Apple state') from None
+ raise ValueError('Apple API retry budget exhausted')
+
+ def collection(self, path):
+ results, seen = [], set()
+ while path:
+ url = api_url(path)
+ require(url not in seen and len(seen) < 20, 'Apple API pagination exceeded safe bounds')
+ seen.add(url)
+ page = self.request(url)
+ require(isinstance(page.get('data'), list), 'Expected Apple resource collection')
+ results.extend(page['data'])
+ path = page.get('links', {}).get('next')
+ return results
+
+
+def query(path, **filters):
+ return '/v1/' + path + '?' + urllib.parse.urlencode(filters)
+
+
+def preflight(client, group_id):
+ apps = client.collection(query('apps', **{'filter[bundleId]': BUNDLE_ID, 'limit': 2}))
+ require(len(apps) == 1 and apps[0]['attributes'].get('bundleId') == BUNDLE_ID, 'Expected exactly one matching app')
+ app_id = resource_id(apps[0]['id'])
+ group = client.request(f'/v1/betaGroups/{resource_id(group_id)}?include=app')['data']
+ require(group['id'] == group_id and group['attributes'].get('isInternalGroup') is False, 'Configured group must be external')
+ require(group.get('relationships', {}).get('app', {}).get('data', {}).get('id') == app_id, 'Beta group belongs to another app')
+ detail = client.request(f'/v1/apps/{app_id}/betaAppReviewDetail')['data']['attributes']
+ required = ('contactFirstName', 'contactLastName', 'contactPhone', 'contactEmail')
+ require(all(isinstance(detail.get(key), str) and detail[key].strip() for key in required), 'Complete Beta review contact fields in App Store Connect')
+ require(isinstance(detail.get('demoAccountRequired'), bool), 'Set Beta review demo-account requirement in App Store Connect')
+ if detail['demoAccountRequired']:
+ require(all(isinstance(detail.get(key), str) and detail[key].strip() for key in ('demoAccountName', 'demoAccountPassword')), 'Complete required Beta review demo-account credentials in App Store Connect')
+ localizations = client.collection(query('betaAppLocalizations', **{'filter[app]': app_id, 'limit': 200}))
+ require(any(item['attributes'].get('locale') == 'zh-Hans' and all(isinstance(item['attributes'].get(key), str) and item['attributes'][key].strip() for key in ('description', 'feedbackEmail')) for item in localizations), 'Complete zh-Hans Beta app description and feedback email in App Store Connect')
+ return app_id
+
+
+def exact_build(client, app_id, marketing, number):
+ page = client.request(query('builds', **{'filter[app]': app_id, 'filter[version]': number, 'filter[preReleaseVersion.version]': marketing, 'filter[processingState]': 'PROCESSING,FAILED,INVALID,VALID', 'include': 'app,preReleaseVersion', 'limit': 200}))
+ require(not page.get('links', {}).get('next'), 'Ambiguous exact-build response pagination')
+ included = {(item['type'], item['id']): item for item in page.get('included', [])}
+ matches = []
+ for build in page['data']:
+ attributes = build['attributes']
+ relations = build.get('relationships', {})
+ prerelease = relations.get('preReleaseVersion', {}).get('data')
+ if attributes.get('version') != number or relations.get('app', {}).get('data', {}).get('id') != app_id:
+ continue
+ require(prerelease is not None, 'Exact build is missing its marketing version relationship')
+ version = included.get((prerelease['type'], prerelease['id']))
+ require(version is not None, 'Exact build marketing version was not included')
+ if version['attributes'].get('version') == marketing and version['attributes'].get('platform') == 'IOS':
+ matches.append(build)
+ require(len(matches) <= 1, 'Multiple builds match the exact iOS marketing and build number')
+ return matches[0] if matches else None
+
+
+def wait_for_build(client, app_id, marketing, number, check=False):
+ for _ in range(61):
+ build = exact_build(client, app_id, marketing, number)
+ if build:
+ attributes = build['attributes']
+ require(attributes.get('expired') is not True, 'Uploaded build is expired')
+ state = attributes.get('processingState')
+ require(state not in ('FAILED', 'INVALID'), 'Apple rejected build processing; inspect App Store Connect before retrying')
+ if state == 'VALID':
+ return build
+ require(state == 'PROCESSING', 'Unknown Apple build processing state')
+ require(not check, 'Exact uploaded build is not yet VALID; check mode made no changes')
+ client.pause(30)
+ raise ValueError('Timed out waiting for the exact uploaded build')
+
+
+def review_state(client, build_id, wait=False):
+ for attempt in range(61):
+ detail = client.request(f'/v1/builds/{build_id}/buildBetaDetail')['data']
+ state = detail['attributes'].get('externalBuildState')
+ if state != 'PROCESSING' or not wait:
+ break
+ require(attempt < 60, 'Timed out waiting for external Beta processing')
+ client.pause(30)
+ require(state not in ('MISSING_EXPORT_COMPLIANCE', 'IN_EXPORT_COMPLIANCE_REVIEW'), 'Resolve export compliance in App Store Connect; this tool does not declare encryption compliance')
+ require(state in ACTIVE | {'READY_FOR_BETA_SUBMISSION'}, 'Build is not eligible for Beta review; inspect external testing state in App Store Connect')
+ submissions = client.collection(query('betaAppReviewSubmissions', **{'filter[build]': build_id, 'limit': 200}))
+ require(all(item['attributes'].get('betaReviewState') in SUBMITTED for item in submissions), 'Existing Beta review was rejected or has an unknown state; inspect App Store Connect')
+ return detail, state, bool(submissions)
+
+
+def submit(client, group_id, marketing, number, source_sha, check=False):
+ require(re.fullmatch(r'\d+\.\d+\.\d+', marketing or ''), 'Invalid marketing version')
+ require(re.fullmatch(r'\d+(?:\.\d+){0,2}', number or ''), 'Invalid build number')
+ require(re.fullmatch(r'[0-9a-f]{40}', source_sha or ''), 'SOURCE_SHA must be an immutable official commit')
+ app_id = preflight(client, group_id)
+ build = wait_for_build(client, app_id, marketing, number, check)
+ build_id = resource_id(build['id'])
+ detail, state, submitted = review_state(client, build_id, wait=not check)
+ if check:
+ return f'Preflight passed for {marketing} ({number}); no Apple resources changed'
+ if state == 'READY_FOR_BETA_SUBMISSION' and not submitted:
+ whats_new = f'请测试主机发现、扫码连接、会话交互及 iPad 横竖屏\n版本:{marketing} ({number})\nhttps://github.com/dsh-tauri/deepseek-harness-desktop/commit/{source_sha}'
+ locales = client.collection(query('betaBuildLocalizations', **{'filter[build]': build_id, 'limit': 200}))
+ matches = [item for item in locales if item['attributes'].get('locale') == 'zh-Hans']
+ require(len(matches) <= 1, 'Duplicate zh-Hans build localizations')
+ if matches:
+ if matches[0]['attributes'].get('whatsNew') != whats_new:
+ identifier = resource_id(matches[0]['id'])
+ client.request(f'/v1/betaBuildLocalizations/{identifier}', 'PATCH', {'data': {'type': 'betaBuildLocalizations', 'id': identifier, 'attributes': {'whatsNew': whats_new}}})
+ else:
+ client.request('/v1/betaBuildLocalizations', 'POST', {'data': {'type': 'betaBuildLocalizations', 'attributes': {'locale': 'zh-Hans', 'whatsNew': whats_new}, 'relationships': {'build': {'data': {'type': 'builds', 'id': build_id}}}}})
+ if detail['attributes'].get('autoNotifyEnabled') is not True:
+ identifier = resource_id(detail['id'])
+ client.request(f'/v1/buildBetaDetails/{identifier}', 'PATCH', {'data': {'type': 'buildBetaDetails', 'id': identifier, 'attributes': {'autoNotifyEnabled': True}}})
+ if state == 'READY_FOR_BETA_SUBMISSION' and not submitted:
+ try:
+ client.request('/v1/betaAppReviewSubmissions', 'POST', {'data': {'type': 'betaAppReviewSubmissions', 'relationships': {'build': {'data': {'type': 'builds', 'id': build_id}}}}})
+ except ApiError as error:
+ if error.status != 409:
+ raise
+ _, current, exists = review_state(client, build_id)
+ require(current in ACTIVE or exists, 'Apple rejected review submission; no duplicate submission attempted')
+ groups = client.collection(f'/v1/builds/{build_id}/betaGroups?limit=200')
+ if not any(item['id'] == group_id for item in groups):
+ client.request(f'/v1/builds/{build_id}/relationships/betaGroups', 'POST', {'data': [{'type': 'betaGroups', 'id': group_id}]})
+ final, final_state, final_submitted = review_state(client, build_id)
+ require(final['attributes'].get('autoNotifyEnabled') is True, 'Apple did not retain automatic tester notification setting')
+ require(final_state in ACTIVE or final_submitted, 'Apple has not confirmed Beta review submission; rerun this step safely')
+ return f'Beta review configured for {marketing} ({number}); Apple automatic notification enabled for the existing external group after approval. No notification delivery is claimed.'
+
+
+def main():
+ require(sys.argv[1:] in ([], ['--check']), 'Only --check is supported')
+ key_id = os.environ.get('APP_STORE_CONNECT_KEY_ID', '')
+ root = Path(os.environ['SIGNING_ROOT']).resolve()
+ require(root.is_dir(), 'Signing root is unavailable')
+ require(re.fullmatch(r'[A-Z0-9]{10}', key_id), 'Invalid API key ID')
+ key = root / 'private_keys' / f'AuthKey_{key_id}.p8'
+ require(key.is_file() and not key.is_symlink() and key.resolve().is_relative_to(root), 'API private key must reside inside the signing root')
+ client = Client(key, key_id, os.environ.get('APP_STORE_CONNECT_ISSUER_ID', ''))
+ result = submit(client, os.environ.get('TESTFLIGHT_BETA_GROUP_ID', ''), os.environ.get('IOS_VERSION', ''), os.environ.get('BUILD_NUMBER', ''), os.environ.get('SOURCE_SHA', ''), check=bool(sys.argv[1:]))
+ print(result)
+ if os.environ.get('GITHUB_STEP_SUMMARY'):
+ with open(os.environ['GITHUB_STEP_SUMMARY'], 'a') as stream:
+ stream.write(result + '\n')
+
+
+if __name__ == '__main__':
+ try:
+ main()
+ except (ValueError, KeyError, OSError, subprocess.TimeoutExpired):
+ error = sys.exc_info()[1]
+ message = str(error) if isinstance(error, ValueError) else 'Beta review configuration or local signing operation failed; sensitive details omitted'
+ print(f'::error::{message}', file=sys.stderr)
+ raise SystemExit(1)
diff --git a/.github/scripts/test_ios_beta_review.py b/.github/scripts/test_ios_beta_review.py
new file mode 100644
index 00000000..1b376ae6
--- /dev/null
+++ b/.github/scripts/test_ios_beta_review.py
@@ -0,0 +1,396 @@
+import base64
+import copy
+import importlib.util
+import io
+import json
+from pathlib import Path
+import random
+import subprocess
+import unittest
+from unittest.mock import Mock, patch
+import urllib.error
+import urllib.parse
+
+
+spec = importlib.util.spec_from_file_location('ios_beta_review', Path(__file__).with_name('ios-beta-review.py'))
+helper = importlib.util.module_from_spec(spec)
+spec.loader.exec_module(helper)
+SHA = 'a' * 40
+
+
+class FakeApple:
+ def __init__(self):
+ self.writes = []
+ self.pauses = []
+ self.processing = ['VALID']
+ self.state = 'READY_FOR_BETA_SUBMISSION'
+ self.submissions = []
+ self.auto_notify = False
+ self.groups = []
+ self.locales = []
+ self.internal = False
+ self.group_app = 'app1'
+ self.expired = False
+ self.contact = {'contactFirstName': 'Test', 'contactLastName': 'Reviewer', 'contactPhone': '+100000000', 'contactEmail': '[email protected]', 'demoAccountRequired': False}
+ self.app_locale = {'locale': 'zh-Hans', 'description': 'Fixture description', 'feedbackEmail': '[email protected]'}
+ self.permission_error = None
+ self.conflict = False
+ self.raced_submission = False
+ self.builds_override = None
+ self.beta_processing = []
+
+ def pause(self, seconds):
+ self.pauses.append(seconds)
+
+ def collection(self, path):
+ result = self.request(path)
+ if not isinstance(result.get('data'), list):
+ raise AssertionError('Expected collection route')
+ return result['data']
+
+ def request(self, path, method='GET', payload=None):
+ parsed = urllib.parse.urlsplit(path)
+ route = parsed.path
+ query = urllib.parse.parse_qs(parsed.query)
+ if method != 'GET':
+ self.writes.append((route, method, copy.deepcopy(payload)))
+ if self.permission_error:
+ raise helper.ApiError(self.permission_error)
+ attributes = payload['data'].get('attributes', {}) if isinstance(payload['data'], dict) else {}
+ if route.startswith('/v1/betaBuildLocalizations'):
+ if method == 'POST':
+ self.locales = [{'id': 'locale1', 'attributes': attributes}]
+ else:
+ self.locales[0]['attributes'].update(attributes)
+ elif route == '/v1/buildBetaDetails/detail1':
+ self.auto_notify = attributes['autoNotifyEnabled']
+ elif route == '/v1/betaAppReviewSubmissions':
+ if self.conflict:
+ if self.raced_submission:
+ self.submissions = [{'id': 'submission1', 'attributes': {'betaReviewState': 'WAITING_FOR_REVIEW'}}]
+ raise helper.ApiError(409)
+ self.submissions = [{'id': 'submission1', 'attributes': {'betaReviewState': 'WAITING_FOR_REVIEW'}}]
+ self.state = 'WAITING_FOR_BETA_REVIEW'
+ elif route == '/v1/builds/build1/relationships/betaGroups':
+ if not self.submissions and self.state not in helper.ACTIVE:
+ raise AssertionError('Group association must follow submission or approval')
+ self.groups = [{'id': 'group1'}]
+ else:
+ raise AssertionError('Unexpected mutation route')
+ return {}
+ if route == '/v1/apps':
+ assert query['filter[bundleId]'] == ['com.dshtauri.dshbridge']
+ return {'data': [{'id': 'app1', 'attributes': {'bundleId': helper.BUNDLE_ID}}]}
+ if route == '/v1/betaGroups/group1':
+ return {'data': {'id': 'group1', 'attributes': {'isInternalGroup': self.internal}, 'relationships': {'app': {'data': {'id': self.group_app}}}}}
+ if route == '/v1/apps/app1/betaAppReviewDetail':
+ return {'data': {'attributes': self.contact}}
+ if route == '/v1/betaAppLocalizations':
+ return {'data': [{'id': 'app-locale1', 'attributes': self.app_locale}]}
+ if route == '/v1/builds':
+ assert query['filter[app]'] == ['app1']
+ assert query['filter[version]'] == ['2140.81.36']
+ assert query['filter[preReleaseVersion.version]'] == ['0.24.0']
+ if self.builds_override is not None:
+ return copy.deepcopy(self.builds_override)
+ state = self.processing.pop(0) if len(self.processing) > 1 else self.processing[0]
+ return self.build_page(state)
+ if route == '/v1/builds/build1/buildBetaDetail':
+ state = self.beta_processing.pop(0) if self.beta_processing else self.state
+ return {'data': {'id': 'detail1', 'attributes': {'externalBuildState': state, 'autoNotifyEnabled': self.auto_notify}}}
+ if route == '/v1/betaAppReviewSubmissions':
+ assert query['filter[build]'] == ['build1']
+ return {'data': copy.deepcopy(self.submissions)}
+ if route == '/v1/betaBuildLocalizations':
+ return {'data': copy.deepcopy(self.locales)}
+ if route == '/v1/builds/build1/betaGroups':
+ return {'data': copy.deepcopy(self.groups)}
+ raise AssertionError('Unexpected read route: ' + route)
+
+ def build_page(self, state='VALID'):
+ if state is None:
+ return {'data': []}
+ return {'data': [{'id': 'build1', 'attributes': {'version': '2140.81.36', 'processingState': state, 'expired': self.expired}, 'relationships': {'app': {'data': {'id': 'app1'}}, 'preReleaseVersion': {'data': {'type': 'preReleaseVersions', 'id': 'version1'}}}}], 'included': [{'type': 'preReleaseVersions', 'id': 'version1', 'attributes': {'version': '0.24.0', 'platform': 'IOS'}}]}
+
+
+class SubmitTests(unittest.TestCase):
+ def setUp(self):
+ self.api = FakeApple()
+
+ def submit(self, check=False):
+ return helper.submit(self.api, 'group1', '0.24.0', '2140.81.36', SHA, check)
+
+ def test_submit_orders_metadata_auto_notify_review_then_group(self):
+ result = self.submit()
+ self.assertEqual([(path, method) for path, method, _ in self.api.writes], [
+ ('/v1/betaBuildLocalizations', 'POST'),
+ ('/v1/buildBetaDetails/detail1', 'PATCH'),
+ ('/v1/betaAppReviewSubmissions', 'POST'),
+ ('/v1/builds/build1/relationships/betaGroups', 'POST'),
+ ])
+ payload = self.api.writes[0][2]['data']
+ self.assertEqual(payload['attributes']['locale'], 'zh-Hans')
+ self.assertEqual(payload['relationships']['build']['data']['id'], 'build1')
+ self.assertEqual(payload['attributes']['whatsNew'], '请测试主机发现、扫码连接、会话交互及 iPad 横竖屏\n版本:0.24.0 (2140.81.36)\nhttps://github.com/dsh-tauri/deepseek-harness-desktop/commit/' + SHA)
+ self.assertEqual(self.api.writes[1][2]['data']['attributes'], {'autoNotifyEnabled': True})
+ self.assertEqual(self.api.writes[-1][2], {'data': [{'type': 'betaGroups', 'id': 'group1'}]})
+ self.assertIn('No notification delivery is claimed', result)
+
+ def test_repeated_run_does_not_duplicate_review_or_group(self):
+ self.submit()
+ self.api.writes.clear()
+ self.submit()
+ self.assertEqual(self.api.writes, [])
+
+ def test_existing_localization_is_patched_instead_of_duplicated(self):
+ self.api.locales = [{'id': 'locale1', 'attributes': {'locale': 'zh-Hans', 'whatsNew': 'old'}}]
+ self.submit()
+ self.assertEqual(self.api.writes[0][:2], ('/v1/betaBuildLocalizations/locale1', 'PATCH'))
+
+ def test_active_external_states_do_not_resubmit_review(self):
+ for state in ('WAITING_FOR_BETA_REVIEW', 'IN_BETA_REVIEW', 'BETA_APPROVED', 'READY_FOR_BETA_TESTING', 'IN_BETA_TESTING'):
+ with self.subTest(state=state):
+ self.api = FakeApple()
+ self.api.state = state
+ self.submit()
+ self.assertNotIn('/v1/betaAppReviewSubmissions', [item[0] for item in self.api.writes])
+ self.assertTrue(self.api.auto_notify)
+ self.assertEqual(self.api.groups, [{'id': 'group1'}])
+
+ def test_already_testing_build_preserves_reviewed_metadata_and_notifications(self):
+ self.api.state = 'IN_BETA_TESTING'
+ self.api.auto_notify = True
+ self.api.groups = [{'id': 'group1'}]
+ self.api.locales = [{'id': 'locale1', 'attributes': {'locale': 'zh-Hans', 'whatsNew': 'Previously approved notes'}}]
+ self.submit()
+ self.assertEqual(self.api.writes, [])
+ self.assertEqual(self.api.locales[0]['attributes']['whatsNew'], 'Previously approved notes')
+
+ def test_valid_build_waits_for_external_processing_without_real_sleep(self):
+ self.api.beta_processing = ['PROCESSING', 'PROCESSING']
+ self.submit()
+ self.assertEqual(self.api.pauses, [30, 30])
+ self.api = FakeApple()
+ self.api.state = 'PROCESSING'
+ with self.assertRaisesRegex(ValueError, 'Timed out'):
+ self.submit()
+ self.assertEqual(len(self.api.pauses), 60)
+ self.assertFalse(self.api.writes)
+
+ def test_submission_resource_prevents_duplicate_despite_stale_build_state(self):
+ for state in ('WAITING_FOR_REVIEW', 'IN_REVIEW', 'APPROVED'):
+ with self.subTest(state=state):
+ self.api = FakeApple()
+ self.api.submissions = [{'id': 's1', 'attributes': {'betaReviewState': state}}]
+ self.submit()
+ self.assertNotIn('/v1/betaAppReviewSubmissions', [item[0] for item in self.api.writes])
+
+ def test_conflict_is_only_treated_as_idempotent_with_submission_evidence(self):
+ self.api.conflict = True
+ with self.assertRaisesRegex(ValueError, 'rejected review submission'):
+ self.submit()
+ self.assertFalse(self.api.groups)
+ self.api = FakeApple()
+ self.api.conflict = self.api.raced_submission = True
+ self.submit()
+ self.assertEqual(self.api.groups, [{'id': 'group1'}])
+
+ def test_external_group_must_belong_to_app(self):
+ self.api.group_app = 'other-app'
+ with self.assertRaisesRegex(ValueError, 'another app'):
+ self.submit()
+ self.assertFalse(self.api.writes)
+
+ def test_internal_group_is_rejected_without_mutation(self):
+ self.api.internal = True
+ with self.assertRaisesRegex(ValueError, 'external'):
+ self.submit()
+ self.assertFalse(self.api.writes)
+
+ def test_read_only_check_never_changes_apple_state(self):
+ self.assertIn('no Apple resources changed', self.submit(check=True))
+ self.assertFalse(self.api.writes)
+ self.assertFalse(self.api.pauses)
+
+ def test_check_of_processing_build_does_not_sleep(self):
+ self.api.processing = ['PROCESSING']
+ with self.assertRaisesRegex(ValueError, 'not yet VALID'):
+ self.submit(check=True)
+ self.assertFalse(self.api.writes)
+ self.assertFalse(self.api.pauses)
+
+ def test_processing_wait_targets_exact_build_and_is_bounded(self):
+ self.api.processing = [None, 'PROCESSING', 'VALID']
+ self.submit()
+ self.assertEqual(self.api.pauses, [30, 30])
+ self.api = FakeApple()
+ self.api.processing = ['PROCESSING']
+ with self.assertRaisesRegex(ValueError, 'Timed out'):
+ self.submit()
+ self.assertLessEqual(len(self.api.pauses), 61)
+ self.assertFalse(self.api.writes)
+
+ def test_terminal_processing_and_expired_builds_fail_without_mutation(self):
+ for state in ('FAILED', 'INVALID'):
+ with self.subTest(state=state):
+ self.api = FakeApple()
+ self.api.processing = [state]
+ with self.assertRaisesRegex(ValueError, 'rejected build processing'):
+ self.submit()
+ self.assertFalse(self.api.writes)
+ self.api = FakeApple()
+ self.api.expired = True
+ with self.assertRaisesRegex(ValueError, 'expired'):
+ self.submit()
+ self.assertFalse(self.api.writes)
+
+ def test_missing_compliance_rejected_and_unknown_states_fail_closed(self):
+ for state in ('MISSING_EXPORT_COMPLIANCE', 'IN_EXPORT_COMPLIANCE_REVIEW', 'BETA_REJECTED', 'EXPIRED', 'PROCESSING_EXCEPTION', 'SURPRISE'):
+ with self.subTest(state=state):
+ self.api = FakeApple()
+ self.api.state = state
+ with self.assertRaises(ValueError):
+ self.submit()
+ self.assertFalse(self.api.writes)
+
+ def test_missing_required_contacts_or_localization_fail_without_mutation(self):
+ for field in ('contactFirstName', 'contactLastName', 'contactPhone', 'contactEmail'):
+ with self.subTest(field=field):
+ self.api = FakeApple()
+ self.api.contact[field] = ''
+ with self.assertRaisesRegex(ValueError, 'contact'):
+ self.submit()
+ self.assertFalse(self.api.writes)
+ self.api = FakeApple()
+ self.api.app_locale.pop('feedbackEmail')
+ with self.assertRaisesRegex(ValueError, 'feedback email'):
+ self.submit()
+
+ def test_no_demo_account_does_not_require_optional_notes_or_privacy_url(self):
+ self.submit()
+ self.assertTrue(self.api.writes)
+
+ def test_required_demo_account_credentials_are_not_fabricated(self):
+ self.api.contact['demoAccountRequired'] = True
+ with self.assertRaisesRegex(ValueError, 'demo-account credentials'):
+ self.submit()
+ self.assertFalse(self.api.writes)
+
+ def test_403_requests_app_manager_without_permission_mutations(self):
+ self.api.permission_error = 403
+ with self.assertRaisesRegex(helper.ApiError, 'App Manager'):
+ self.submit()
+ self.assertEqual(len(self.api.writes), 1)
+
+ def test_exact_build_selection_rejects_wrong_marketing_platform_number_and_app(self):
+ for field in ('marketing', 'platform', 'number', 'app'):
+ with self.subTest(field=field):
+ page = self.api.build_page()
+ if field == 'marketing':
+ page['included'][0]['attributes']['version'] = '9.0.0'
+ elif field == 'platform':
+ page['included'][0]['attributes']['platform'] = 'MAC_OS'
+ elif field == 'number':
+ page['data'][0]['attributes']['version'] = '9999'
+ else:
+ page['data'][0]['relationships']['app']['data']['id'] = 'wrong'
+ self.api.builds_override = page
+ self.assertIsNone(helper.exact_build(self.api, 'app1', '0.24.0', '2140.81.36'))
+ self.api.builds_override = self.api.build_page()
+ self.api.builds_override['data'].append(copy.deepcopy(self.api.builds_override['data'][0]))
+ with self.assertRaisesRegex(ValueError, 'Multiple builds'):
+ helper.exact_build(self.api, 'app1', '0.24.0', '2140.81.36')
+
+ def test_invalid_source_commit_is_rejected_before_any_mutation(self):
+ with self.assertRaisesRegex(ValueError, 'SOURCE_SHA'):
+ helper.submit(self.api, 'group1', '0.24.0', '2140.81.36', 'main')
+ self.assertFalse(self.api.writes)
+
+
+class HttpTests(unittest.TestCase):
+ def setUp(self):
+ self.now = 0
+ self.monotonic = patch.object(helper.time, 'monotonic', side_effect=lambda: self.now)
+ self.monotonic.start()
+ self.addCleanup(self.monotonic.stop)
+ self.client = helper.Client(Path('/fixture/key.p8'), 'ABCDEFGHIJ', '11111111-1111-1111-1111-111111111111', timeout=60)
+ self.client.token = Mock(return_value='fake-token-not-a-secret')
+ self.client.opener = Mock()
+
+ def response(self, value):
+ response = Mock()
+ response.read.return_value = json.dumps(value).encode()
+ response.__enter__ = Mock(return_value=response)
+ response.__exit__ = Mock(return_value=False)
+ return response
+
+ def advance(self, seconds):
+ self.now += seconds
+
+ def test_foreign_hosts_credentials_fragments_and_http_are_rejected_before_token(self):
+ for url in ('https://evil.invalid/v1/apps', 'http://api.appstoreconnect.apple.com/v1/apps', 'https://api.appstoreconnect.apple.com.evil.invalid/v1/apps', 'https://[email protected]/v1/apps', 'https://api.appstoreconnect.apple.com:443/v1/apps', '/v1/apps#fragment'):
+ with self.subTest(url=url), self.assertRaisesRegex(ValueError, 'untrusted'):
+ self.client.request(url)
+ self.client.token.assert_not_called()
+ self.client.opener.open.assert_not_called()
+
+ def test_redirect_is_denied_instead_of_forwarding_bearer(self):
+ with self.assertRaisesRegex(ValueError, 'redirect'):
+ helper.NoRedirect().redirect_request(None, None, 302, '', {}, 'https://evil.invalid')
+
+ def test_get_rate_limit_and_transient_errors_retry_with_bounded_delay(self):
+ self.client.opener.open.side_effect = [urllib.error.HTTPError('https://api.appstoreconnect.apple.com/v1/apps', 429, 'PII must not appear', {}, io.BytesIO(b'secret body')), urllib.error.URLError('secret connection detail'), self.response({'data': []})]
+ with patch.object(helper.time, 'sleep', side_effect=self.advance):
+ self.assertEqual(self.client.request('/v1/apps'), {'data': []})
+ self.assertEqual(self.now, 15)
+ self.assertEqual(self.client.token.call_count, 3)
+
+ def test_post_is_not_blindly_retried_on_ambiguous_failure(self):
+ self.client.opener.open.side_effect = urllib.error.HTTPError('https://api.appstoreconnect.apple.com/v1/apps', 503, 'sensitive', {}, io.BytesIO(b'private'))
+ with self.assertRaises(helper.ApiError) as context:
+ self.client.request('/v1/betaAppReviewSubmissions', 'POST', {'data': {}})
+ self.assertNotIn('sensitive', str(context.exception))
+ self.assertNotIn('private', str(context.exception))
+ self.assertEqual(self.client.opener.open.call_count, 1)
+
+ def test_get_retry_budget_and_deadline_are_finite(self):
+ self.client.opener.open.side_effect = urllib.error.URLError('sensitive')
+ with patch.object(helper.time, 'sleep', side_effect=self.advance), self.assertRaisesRegex(ValueError, 'transport failed'):
+ self.client.request('/v1/apps')
+ self.assertEqual(self.client.opener.open.call_count, 3)
+ self.now = 61
+ with self.assertRaisesRegex(ValueError, 'deadline'):
+ self.client.request('/v1/apps')
+ self.assertEqual(self.client.opener.open.call_count, 3)
+
+ def test_pagination_rejects_cross_host_next_links(self):
+ self.client.opener.open.return_value = self.response({'data': [], 'links': {'next': 'https://evil.invalid/v1/apps'}})
+ with self.assertRaisesRegex(ValueError, 'untrusted'):
+ self.client.collection('/v1/apps')
+ self.assertEqual(self.client.opener.open.call_count, 1)
+
+ def test_pagination_rejects_cycles(self):
+ self.client.opener.open.return_value = self.response({'data': [], 'links': {'next': '/v1/apps'}})
+ with self.assertRaisesRegex(ValueError, 'pagination'):
+ self.client.collection('/v1/apps')
+ self.assertEqual(self.client.opener.open.call_count, 1)
+
+ def test_jwt_signs_via_openssl_and_regenerates_short_lived_claims(self):
+ client = helper.Client(Path('/fixture/key.p8'), 'ABCDEFGHIJ', '11111111-1111-1111-1111-111111111111')
+ signature = bytes.fromhex('3006020101020102')
+ with patch.object(helper.subprocess, 'run', return_value=subprocess.CompletedProcess([], 0, signature, b'')) as command, patch.object(helper.time, 'time', side_effect=[1000, 1301]):
+ tokens = [client.token(), client.token()]
+ claims = [json.loads(base64.urlsafe_b64decode(token.split('.')[1] + '==')) for token in tokens]
+ self.assertEqual([value['iat'] for value in claims], [1000, 1301])
+ self.assertEqual([value['exp'] for value in claims], [1300, 1601])
+ self.assertEqual(claims[0]['aud'], 'appstoreconnect-v1')
+ self.assertEqual(command.call_args.args[0], ['openssl', 'dgst', '-sha256', '-sign', '/fixture/key.p8'])
+ self.assertEqual(len(base64.urlsafe_b64decode(tokens[0].split('.')[2] + '==')), 64)
+
+
+if __name__ == '__main__':
+ suite = unittest.defaultTestLoader.loadTestsFromModule(__import__(__name__))
+ cases = [case for group in suite for case in group]
+ random.Random(2026).shuffle(cases)
+ result = unittest.TextTestRunner(verbosity=2).run(unittest.TestSuite(cases))
+ raise SystemExit(not result.wasSuccessful())
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index a91bd679..0f7e7e3f 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -87,8 +87,8 @@ jobs:
node node_modules/vitest/vitest.mjs run --project unit test/appimage-host-libs.test.ts --sequence.shuffle --sequence.seed="$seed"
done
- - name: Test iOS signing guards without credentials
- run: python3 -m unittest discover -s .github/scripts -p 'test_ios_testflight.py' -v
+ - name: Test iOS signing and Beta review guards without credentials
+ run: python3 -m unittest discover -s .github/scripts -p 'test_ios_*.py' -v
- name: Install alpha.3 core for desktop admission regression
run: npm install --prefix "$RUNNER_TEMP/dsh-cli-admission" --no-audit --no-fund @deepseek-ai/[email protected]
diff --git a/.github/workflows/release-testflight.yml b/.github/workflows/release-testflight.yml
index b09fec27..170461b1 100644
--- a/.github/workflows/release-testflight.yml
+++ b/.github/workflows/release-testflight.yml
@@ -206,9 +206,18 @@ jobs:
--apiKey "$APP_STORE_CONNECT_KEY_ID" --apiIssuer "$APP_STORE_CONNECT_ISSUER_ID"
{
echo "Uploaded signed IPA for $VERSION ($BUILD_NUMBER), commit $SOURCE_SHA."
- echo 'App Store Connect processing, compliance and TestFlight review/tester assignment remain Apple-side steps.'
+ echo 'Upload accepted; optional external Beta review automation runs next.'
} >> "$GITHUB_STEP_SUMMARY"
+ - name: Submit external Beta review and enable automatic tester notifications
+ if: vars.IOS_BETA_REVIEW_ENABLED == 'true'
+ timeout-minutes: 35
+ env:
+ APP_STORE_CONNECT_KEY_ID: ${{ secrets.APP_STORE_CONNECT_KEY_ID }}
+ APP_STORE_CONNECT_ISSUER_ID: ${{ secrets.APP_STORE_CONNECT_ISSUER_ID }}
+ TESTFLIGHT_BETA_GROUP_ID: ${{ vars.TESTFLIGHT_BETA_GROUP_ID }}
+ run: python3 .github/scripts/ios-beta-review.py
+
- name: Always remove temporary signing material
if: always()
run: |
diff --git a/docs/TESTFLIGHT.zh.md b/docs/TESTFLIGHT.zh.md
index 2f4f7887..57b3782e 100644
--- a/docs/TESTFLIGHT.zh.md
+++ b/docs/TESTFLIGHT.zh.md
@@ -23,7 +23,7 @@
1. 在“钥匙串访问 → 我的证书”找到 Apple Distribution 证书,展开后必须能看到私钥,导出为带密码的 `.p12`。只有 `.cer` 文件不够。若已有有效证书,不必重新生成或撤销。
2. 在 Apple Developer 的 Certificates, Identifiers & Profiles 中,确认 App ID 为 `com.dshtauri.dshbridge`。当前应用声明 Push Notifications entitlement,描述文件需支持相应能力。
3. 在 Apple Developer 门户手动创建 App Store Connect 分发描述文件,选择该 App ID 和刚导出的 Apple Distribution 证书。CI 使用手动签名,不能使用 Xcode 自动生成的 `iOS Team Store Provisioning Profile`(`IsXcodeManaged=true`),即使它能在本机通过自动签名上传。Development / Ad Hoc / Enterprise 描述文件也不能代替它。苹果描述文件可同时列出 iOS、xrOS、visionOS,包含 iOS 即可。
-4. 在 App Store Connect → Users and Access → Integrations → App Store Connect API 创建团队 API Key,赋予上传所需权限(通常 Developer 足够;按团队权限策略配置)。保存 `.p8`、Key ID、Issuer ID;私钥只能下载一次。这里不使用个人 API Key。
+4. 在 App Store Connect → Users and Access → Integrations → App Store Connect API 创建团队 API Key,仅上传时通常 Developer 足够;启用外部 Beta 自动送审时使用 App Manager(App 管理),按团队权限策略配置。保存 `.p8`、Key ID、Issuer ID;私钥只能下载一次。这里不使用个人 API Key。
5. 确认 App Store Connect 中已有相同 Bundle ID 的 iOS 应用记录,且开发者会员、协议均有效。
## GitHub 配置
@@ -67,9 +67,28 @@ gh workflow run release-testflight.yml --repo dsh-tauri/deepseek-harness-desktop
- 每次运行重新生成 iOS 构建号:将自 2020-01-01 UTC 起的 10 秒计数拆成最多 4、2、2 位的三段数字,共用串行并发组,并在生成后持有完整的 10 秒窗口,避免同一次任务重跑复用编号;此编码上限在 2051 年。首次接入时确认苹果后台没有人为设置过更大的构建号,不能混用其他不协调的编号方案。预发布版本会规范化为三段数字营销版本,例如 `0.24.0-beta.1` 对应 `0.24.0`。仓库版本文件不会被 CI 提交回去。
- 仅可发布包含签名脚本的提交;不要用新流程回放不含脚本的历史 tag。保留原有历史版本发布方式。
- IPA 是 App Store 分发签名包,用于 TestFlight / App Store,不是任意设备可直接侧载的 Ad Hoc 包。
-- 上传成功仅代表苹果接收,仍需等待处理;处理完成后在 TestFlight 中分配内部测试组。外部测试还可能需要 Beta 审核。流程不自动提交 App Store 审核或正式上架,也不自动添加测试员。
+- 上传成功仅代表苹果接收,仍需等待处理;外部 Beta 审核自动化可单独开启,见下一节。流程不提交 App Store 正式审核或自动上架,不添加测试员,也不修改公开邀请链接。
- 部分预编译框架可能缺少 dSYM;此前本机上传已有此类非阻断警告。保留符号产物便于后续排查,不能把“上传成功”当作真机验收通过。
+## 自动外部 Beta 审核与通知
+
+在成功上传后,`ios-beta-review.py` 最多等待约 30 分钟查到本次应用、营销版本和构建号完全匹配的有效构建,不会选取“最新构建”代替目标。通过预检查后写入中文测试说明、开启 `buildBetaDetails.autoNotifyEnabled`、按状态提交外部 Beta 审核,并关联明确指定的外部测试组。审核完成后的通知由苹果执行,CI 不等待数小时或数天的人工审核;送审成功不代表审核已通过或通知已发出。
+
+需要以下仓库级 Variables,顺序是先配置目标组再启用:
+
+```bash
+gh variable set TESTFLIGHT_BETA_GROUP_ID --body e699950f-b4ce-4a0c-a1df-1da6866326bd --repo dsh-tauri/deepseek-harness-desktop
+gh variable set IOS_BETA_REVIEW_ENABLED --body true --repo dsh-tauri/deepseek-harness-desktop
+```
+
+该 ID 为用户确认的 `Beta` 外部测试组;其现有公开邀请链接保持不变,组内通过链接加入的测试员同样可获得新构建。关闭 `IOS_BETA_REVIEW_ENABLED` 只停止后续自动送审,不取消已提交审核或已交给苹果的通知设置。
+
+测试说明模板为“请测试主机发现、扫码连接、会话交互及 iPad 横竖屏”,并附本次版本、构建号和官方源码提交链接。审核联系人、Beta 应用说明、反馈邮箱及所需合规信息由 App Store Connect 后台维护;脚本不编造演示账号、隐私政策链接或加密合规声明。DSH Mobile 依赖桌面服务,没有可访问的演示服务或清楚的操作说明可能影响审核。
+
+已处于审核中、已批准或正在外部测试的目标构建不会重复送审;被拒绝或缺失合规信息时直接报出需要人工处理的状态,不通过重试规避审核。苹果限制同一版本同时在审的构建数量,且有每日 Beta 送审限额,遇到此类限制不会撤销其他构建的审核。
+
+官方要求参考:[邀请外部测试员](https://developer.apple.com/help/app-store-connect/test-a-beta-version/invite-external-testers/)。需要 App Manager、Admin 或账户持有人权限;只给 Developer 的上传密钥可能在送审或测试组管理接口返回 403。替换密钥时同步更新 `.p8`、Key ID 与 Issuer ID,验证成功前不要撤销旧密钥。
+
## 验证边界
本地可验证工作流结构、脚本语法和配置校验逻辑。真正的证书导入、苹果认证、IPA 导出与上传必须在补齐密钥后的官方 macOS runner 首跑验证;没有这些凭据时,不能声称签名 CI 已运行通过。
diff --git a/docs/specs/native.md b/docs/specs/native.md
index 8c2ecca9..c162f280 100644
--- a/docs/specs/native.md
+++ b/docs/specs/native.md
@@ -194,6 +194,7 @@ src-native/
* 上述 unsigned IPA 不含分发签名,不能直接安装或提交 App Store,需自行签名。预发布完整版本保留在资产名中,iOS `CFBundleShortVersionString` 使用三段数字核心版本。
* `release-testflight.yml` 为独立的官方仓库签名与自动上传任务,由 `release-native.yml` 的 `prepare` 成功后调用,仓库 Variable `IOS_TESTFLIGHT_ENABLED=true` 开启;不改变原有 APK / unsigned IPA 的发布依赖。也可从官方 `main` 手动运行,签名任务使用仓库级 Secrets,不依赖独立 Environment,仅构建官方 `main` 历史中的提交。
* iOS 沿用 `APPLE_TEAM_ID`,新增 Apple Distribution 证书、App Store 描述文件和 App Store Connect 团队 API Key;不能拿 macOS Developer ID 证书替代。密钥清单、启用步骤及上传边界见 [TestFlight 签名发布](../TESTFLIGHT.zh.md)。
+* `IOS_BETA_REVIEW_ENABLED=true` 可在成功上传后自动等待本次准确版本与构建号处理完成,提交外部 Beta 审核并关联 `TESTFLIGHT_BETA_GROUP_ID` 指定的外部组;使用 App Manager 团队 API Key。`buildBetaDetails.autoNotifyEnabled` 交由苹果在批准后通知,不等待人工审核,不创建测试员、不改变公开邀请链接,也不代填账号或合规声明;此开关独立于签名上传。
---
diff --git a/test/mobile-release-workflows.test.ts b/test/mobile-release-workflows.test.ts
index 50dad68d..47bf0644 100644
--- a/test/mobile-release-workflows.test.ts
+++ b/test/mobile-release-workflows.test.ts
@@ -142,6 +142,22 @@ describe('mobile release workflow contracts', () => {
expect(section(release, 'build-ios', 2)).not.toContain('secrets:')
})
+ it('gates external Beta review after upload and before credential cleanup', () => {
+ const signed = readSource('.github/workflows/release-testflight.yml')
+ const upload = signed.indexOf('- name: Upload the same IPA to App Store Connect')
+ const review = signed.indexOf('- name: Submit external Beta review and enable automatic tester notifications')
+ const cleanup = signed.indexOf('- name: Always remove temporary signing material')
+ expect(upload).toBeGreaterThan(-1)
+ expect(review).toBeGreaterThan(upload)
+ expect(cleanup).toBeGreaterThan(review)
+ const step = signed.slice(review, cleanup)
+ expect(step).toContain('if: vars.IOS_BETA_REVIEW_ENABLED == \'true\'')
+ expect(step).toContain('timeout-minutes: 35')
+ expect(step).toContain(`TESTFLIGHT_BETA_GROUP_ID: \${{ vars.TESTFLIGHT_BETA_GROUP_ID }}`)
+ expect(step).toContain('run: python3 .github/scripts/ios-beta-review.py')
+ expect(readSource('.github/workflows/ci.yml')).toContain('-p \'test_ios_*.py\'')
+ })
+
it('pins TestFlight to the locally verified Xcode toolchain on macOS 26', () => {
const signed = readSource('.github/workflows/release-testflight.yml')
expect(signed).toContain('runs-on: macos-26')