Skip to content

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

feat(ci): sign iOS releases and upload to TestFlight

idealclover587ff70311fe
diff --git a/.github/scripts/ios-testflight.py b/.github/scripts/ios-testflight.py
new file mode 100644
index 00000000..29a66aed
--- /dev/null
+++ b/.github/scripts/ios-testflight.py
@@ -0,0 +1,203 @@
+import base64
+import datetime as dt
+import hashlib
+import json
+import os
+from pathlib import Path
+import plistlib
+import re
+import shutil
+import subprocess
+import sys
+import tempfile
+import zipfile
+
+
+EPOCH = 1577836800
+BUNDLE_ID = 'com.dshtauri.dshbridge'
+
+
+def require(condition, message):
+ if not condition:
+ raise ValueError(message)
+
+
+def build_number(timestamp):
+ ticks = (int(timestamp) - EPOCH) // 10
+ require(10000 <= ticks <= 99999999, 'Build timestamp exceeds the 4.2.2 version range')
+ return f'{ticks // 10000}.{ticks // 100 % 100}.{ticks % 100}'
+
+
+def validate_profile(profile, team, now, identities):
+ entitlements = profile.get('Entitlements', {})
+ require(profile.get('TeamIdentifier') == [team], 'Profile team mismatch')
+ require(entitlements.get('com.apple.developer.team-identifier') == team, 'Entitlement team mismatch')
+ prefixes = profile.get('ApplicationIdentifierPrefix', [])
+ require(len(prefixes) == 1 and isinstance(prefixes[0], str), 'Invalid app identifier prefix')
+ require(entitlements.get('application-identifier') == f'{prefixes[0]}.{BUNDLE_ID}', 'Profile app ID mismatch')
+ require(profile.get('ExpirationDate', dt.datetime.min) > now, 'Provisioning profile expired')
+ require(profile.get('Platform') == ['iOS'], 'Profile is not for iOS')
+ require('ProvisionedDevices' not in profile and not profile.get('ProvisionsAllDevices'), 'Profile must use App Store distribution')
+ require(entitlements.get('get-task-allow') is False, 'Profile must disallow debugging')
+ require(entitlements.get('beta-reports-active') is True, 'Profile must support TestFlight')
+ require(entitlements.get('aps-environment') == 'production', 'Profile must support production push notifications')
+ require(re.fullmatch(r'[A-Fa-f0-9-]{36}', profile.get('UUID', '')), 'Invalid profile UUID')
+ certificates = {hashlib.sha1(cert).hexdigest().upper() for cert in profile.get('DeveloperCertificates', [])}
+ matches = certificates.intersection(identities)
+ require(len(matches) == 1, 'Profile must match exactly one imported distribution signing identity')
+ return matches.pop()
+
+
+def decode_secret(value):
+ return base64.b64decode(''.join(value.split()), validate=True)
+
+
+def run(*args):
+ result = subprocess.run(args, check=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
+ require(result.returncode == 0, f'{args[0]} {args[1]} failed (output suppressed to protect credentials)')
+ return result.stdout
+
+
+def emit(values):
+ with open(os.environ['GITHUB_ENV'], 'a') as stream:
+ for key, value in values.items():
+ require('\n' not in str(value) and '\r' not in str(value), 'Invalid environment value')
+ stream.write(f'{key}={value}\n')
+
+
+def install():
+ os.umask(0o077)
+ for name in ('APPLE_TEAM_ID', 'IOS_DISTRIBUTION_CERTIFICATE', 'IOS_DISTRIBUTION_CERTIFICATE_PASSWORD', 'IOS_PROVISIONING_PROFILE', 'APP_STORE_CONNECT_API_KEY', 'APP_STORE_CONNECT_KEY_ID', 'APP_STORE_CONNECT_ISSUER_ID'):
+ require(bool(os.environ.get(name)), f'Missing required secret: {name}')
+ team = os.environ['APPLE_TEAM_ID']
+ key_id = os.environ['APP_STORE_CONNECT_KEY_ID']
+ issuer = os.environ['APP_STORE_CONNECT_ISSUER_ID']
+ require(re.fullmatch(r'[A-Z0-9]{10}', team), 'Invalid Apple team ID')
+ require(re.fullmatch(r'[A-Z0-9]{10}', key_id), 'Invalid App Store Connect key ID')
+ require(re.fullmatch(r'[a-fA-F0-9-]{36}', issuer), 'Invalid App Store Connect issuer ID')
+ root = Path(tempfile.mkdtemp(prefix='ios-testflight-', dir=Path(os.environ['RUNNER_TEMP']).resolve()))
+ emit({'SIGNING_ROOT': root})
+ keychain = root / 'signing.keychain-db'
+ profile_file = root / 'distribution.mobileprovision'
+ certificate = root / 'distribution.p12'
+ certificate.write_bytes(decode_secret(os.environ['IOS_DISTRIBUTION_CERTIFICATE']))
+ profile_file.write_bytes(decode_secret(os.environ['IOS_PROVISIONING_PROFILE']))
+ profile = plistlib.loads(run('security', 'cms', '-D', '-i', str(profile_file)))
+ search_list = run('security', 'list-keychains', '-d', 'user').decode()
+ original = re.findall(r'"([^"\n]+)"', search_list)
+ (root / 'keychains.json').write_text(json.dumps(original))
+ password = base64.b64encode(os.urandom(32)).decode()
+ run('security', 'create-keychain', '-p', password, str(keychain))
+ run('security', 'set-keychain-settings', '-lut', '21600', str(keychain))
+ run('security', 'unlock-keychain', '-p', password, str(keychain))
+ run('security', 'import', str(certificate), '-k', str(keychain), '-P', os.environ['IOS_DISTRIBUTION_CERTIFICATE_PASSWORD'], '-T', '/usr/bin/codesign', '-T', '/usr/bin/security')
+ run('security', 'set-key-partition-list', '-S', 'apple-tool:,apple:,codesign:', '-k', password, str(keychain))
+ identity_output = run('security', 'find-identity', '-v', '-p', 'codesigning', str(keychain)).decode()
+ identities = set(re.findall(r'\b([A-F0-9]{40}) "(?:Apple Distribution|iPhone Distribution):[^"\n]+"', identity_output))
+ identity = validate_profile(profile, team, dt.datetime.now(dt.timezone.utc).replace(tzinfo=None), identities)
+ run('security', 'list-keychains', '-d', 'user', '-s', *original, str(keychain))
+ profile_dir = Path.home() / 'Library/Developer/Xcode/UserData/Provisioning Profiles'
+ profile_dir.mkdir(parents=True, exist_ok=True)
+ destination = profile_dir / f'{root.name}.mobileprovision'
+ require(not destination.exists(), 'Temporary provisioning profile already exists')
+ emit({'INSTALLED_PROFILE': destination})
+ with destination.open('xb') as stream:
+ stream.write(profile_file.read_bytes())
+ key_dir = root / 'private_keys'
+ key_dir.mkdir()
+ api_key = os.environ['APP_STORE_CONNECT_API_KEY']
+ require(api_key.startswith('-----BEGIN PRIVATE KEY-----') and '-----END PRIVATE KEY-----' in api_key, 'API key must be raw p8 content')
+ (key_dir / f'AuthKey_{key_id}.p8').write_text(api_key)
+ options = {
+ 'method': 'app-store-connect', 'destination': 'export', 'teamID': team,
+ 'signingStyle': 'manual', 'signingCertificate': identity,
+ 'provisioningProfiles': {BUNDLE_ID: profile['UUID']},
+ 'manageAppVersionAndBuildNumber': False, 'stripSwiftSymbols': True,
+ 'uploadSymbols': False,
+ }
+ (root / 'ExportOptions.plist').write_bytes(plistlib.dumps(options))
+ emit({'SIGNING_IDENTITY': identity, 'PROFILE_UUID': profile['UUID'], 'SIGNING_TEAM': team})
+
+
+def verify():
+ root = Path(os.environ['SIGNING_ROOT'])
+ ipas = list((root / 'export').glob('*.ipa'))
+ require(len(ipas) == 1, 'Expected one exported signed IPA')
+ unpacked = root / 'verified'
+ run('ditto', '-x', '-k', str(ipas[0]), str(unpacked))
+ apps = list((unpacked / 'Payload').glob('*.app'))
+ require(len(apps) == 1, 'Expected one IPA app')
+ app = apps[0]
+ info = plistlib.loads((app / 'Info.plist').read_bytes())
+ require(info['CFBundleIdentifier'] == BUNDLE_ID, 'Exported bundle ID mismatch')
+ require(info['CFBundleShortVersionString'] == os.environ['IOS_VERSION'], 'Exported marketing version mismatch')
+ require(info['CFBundleVersion'] == os.environ['BUILD_NUMBER'], 'Exported build number mismatch')
+ require(info['CFBundleSupportedPlatforms'] == ['iPhoneOS'], 'Expected a device app')
+ require((app / info['CFBundleExecutable']).stat().st_size > 0, 'Missing native executable')
+ require((app / 'main.jsbundle').stat().st_size > 0, 'Missing embedded JavaScript bundle')
+ config = json.loads((app / 'EXConstants.bundle/app.config').read_text())
+ require(config['version'] == os.environ['IOS_VERSION'], 'Embedded Expo version mismatch')
+ require(config['ios']['bundleIdentifier'] == BUNDLE_ID, 'Embedded Expo identifier mismatch')
+ require(config['ios']['buildNumber'] == os.environ['BUILD_NUMBER'], 'Embedded Expo build number mismatch')
+ require(config['extra']['thirdPartyNotices'] == Path('THIRD_PARTY_NOTICES.md').read_text(), 'Missing third-party notices')
+ run('codesign', '--verify', '--deep', '--strict', str(app))
+ run('codesign', '-d', '--extract-certificates', str(root / 'signed-cert-'), str(app))
+ leaf_hash = hashlib.sha1((root / 'signed-cert-0').read_bytes()).hexdigest().upper()
+ require(leaf_hash == os.environ['SIGNING_IDENTITY'], 'Exported signing certificate mismatch')
+ profile = plistlib.loads(run('security', 'cms', '-D', '-i', str(app / 'embedded.mobileprovision')))
+ validate_profile(profile, os.environ['SIGNING_TEAM'], dt.datetime.now(dt.timezone.utc).replace(tzinfo=None), {leaf_hash})
+ entitlements = plistlib.loads(run('codesign', '-d', '--entitlements', ':-', str(app)))
+ require(entitlements.get('get-task-allow') is False, 'Signed app allows debugging')
+ require(entitlements.get('com.apple.developer.team-identifier') == os.environ['SIGNING_TEAM'], 'Signed app team mismatch')
+ require(entitlements.get('application-identifier') == profile['Entitlements']['application-identifier'], 'Signed app identifier mismatch')
+ require(entitlements.get('beta-reports-active') is True, 'Signed app lacks TestFlight entitlement')
+ require(entitlements.get('aps-environment') == 'production', 'Signed app lacks production push entitlement')
+ with zipfile.ZipFile(ipas[0]) as ipa:
+ require(ipa.testzip() is None, 'Corrupt exported IPA')
+ deliverables = root / 'artifact'
+ deliverables.mkdir()
+ name = f'Deepseek.Harness.iOS_{os.environ["VERSION"]}_{os.environ["BUILD_NUMBER"]}_signed.ipa'
+ shutil.copyfile(ipas[0], deliverables / name)
+ symbols = root / 'DSH.xcarchive/dSYMs'
+ require(symbols.is_dir() and any(symbols.glob('*.dSYM')), 'Archive must contain release debug symbols')
+ run('ditto', '-c', '-k', '--keepParent', str(symbols), str(deliverables / 'dSYMs.zip'))
+ emit({'IPA_PATH': deliverables / name})
+
+
+def cleanup():
+ value = os.environ.get('SIGNING_ROOT')
+ if not value:
+ return
+ root = Path(value)
+ temp = Path(os.environ['RUNNER_TEMP']).resolve()
+ require(root.is_absolute() and root.parent == temp and root.name.startswith('ios-testflight-') and not root.is_symlink(), 'Refusing unsafe signing cleanup path')
+ if not root.exists():
+ return
+ profile_value = os.environ.get('INSTALLED_PROFILE')
+ if profile_value:
+ expected = Path.home() / 'Library/Developer/Xcode/UserData/Provisioning Profiles' / f'{root.name}.mobileprovision'
+ profile = Path(profile_value)
+ require(profile == expected and profile.resolve() == expected, 'Refusing unsafe profile cleanup path')
+ profile.unlink(missing_ok=True)
+ failures = []
+ original = root / 'keychains.json'
+ if original.exists():
+ try:
+ run('security', 'list-keychains', '-d', 'user', '-s', *json.loads(original.read_text()))
+ except ValueError as error:
+ failures.append(str(error))
+ keychain = root / 'signing.keychain-db'
+ if keychain.exists():
+ try:
+ run('security', 'delete-keychain', str(keychain))
+ except ValueError as error:
+ failures.append(str(error))
+ require(root.resolve() == root, 'Refusing redirected signing cleanup path')
+ shutil.rmtree(root)
+ require(not failures, '; '.join(failures))
+
+
+if __name__ == '__main__':
+ commands = {'install': install, 'verify': verify, 'cleanup': cleanup}
+ require(len(sys.argv) == 2 and sys.argv[1] in commands, 'Expected install, verify or cleanup')
+ commands[sys.argv[1]]()
diff --git a/.github/scripts/test_ios_testflight.py b/.github/scripts/test_ios_testflight.py
new file mode 100644
index 00000000..7ee9f838
--- /dev/null
+++ b/.github/scripts/test_ios_testflight.py
@@ -0,0 +1,159 @@
+import copy
+import datetime as dt
+import hashlib
+import importlib.util
+import os
+from pathlib import Path
+import random
+import tempfile
+import unittest
+from unittest.mock import patch
+
+
+spec = importlib.util.spec_from_file_location('ios_testflight', Path(__file__).with_name('ios-testflight.py'))
+helper = importlib.util.module_from_spec(spec)
+spec.loader.exec_module(helper)
+
+
+class SecretTests(unittest.TestCase):
+ def test_wrapped_base64_decodes_identically(self):
+ self.assertEqual(helper.decode_secret(' Zm\n l4dH\r\nVy ZQ==\t'), b'fixture')
+
+ def test_invalid_base64_is_rejected(self):
+ with self.assertRaises(ValueError):
+ helper.decode_secret('Zm!4dHVyZQ==')
+
+
+class VersionTests(unittest.TestCase):
+ def test_timestamp_uses_ten_second_ticks_and_numeric_components(self):
+ self.assertEqual(helper.build_number(1767225600), '1893.88.80')
+ self.assertEqual(helper.build_number(1767225610), '1893.88.81')
+
+ def test_component_rollover_preserves_numeric_order(self):
+ self.assertEqual(helper.build_number(helper.EPOCH + 199990), '1.99.99')
+ self.assertEqual(helper.build_number(helper.EPOCH + 200000), '2.0.0')
+
+ def test_apple_component_upper_bound_is_enforced(self):
+ self.assertEqual(helper.build_number(helper.EPOCH + 999999990), '9999.99.99')
+ for timestamp in (helper.EPOCH, helper.EPOCH - 1, helper.EPOCH + 1000000000):
+ with self.subTest(timestamp=timestamp), self.assertRaisesRegex(ValueError, 'range'):
+ helper.build_number(timestamp)
+
+
+class ProfileTests(unittest.TestCase):
+ def setUp(self):
+ self.now = dt.datetime(2026, 1, 1)
+ self.identity = hashlib.sha1(b'fixture-certificate').hexdigest().upper()
+ self.profile = {
+ 'TeamIdentifier': ['ABCDEFGHIJ'],
+ 'ApplicationIdentifierPrefix': ['OLDPREFIX1'],
+ 'UUID': '12345678-1234-1234-1234-123456789abc',
+ 'Platform': ['iOS'],
+ 'ExpirationDate': dt.datetime(2027, 1, 1),
+ 'DeveloperCertificates': [b'fixture-certificate'],
+ 'Entitlements': {
+ 'com.apple.developer.team-identifier': 'ABCDEFGHIJ',
+ 'application-identifier': 'OLDPREFIX1.com.dshtauri.dshbridge',
+ 'get-task-allow': False,
+ 'beta-reports-active': True,
+ 'aps-environment': 'production',
+ },
+ }
+
+ def validate(self, profile=None, identities=None):
+ return helper.validate_profile(self.profile if profile is None else profile, 'ABCDEFGHIJ', self.now, {self.identity} if identities is None else identities)
+
+ def test_valid_profile_allows_legacy_app_identifier_prefix(self):
+ self.assertEqual(self.validate(), self.identity)
+
+ def test_rejects_wrong_team_app_platform_expiry_and_distribution(self):
+ cases = [
+ ('TeamIdentifier', ['OTHERTEAM1']),
+ ('ApplicationIdentifierPrefix', []),
+ ('UUID', '../profile'),
+ ('Platform', ['OSX']),
+ ('ExpirationDate', self.now),
+ ('ProvisionedDevices', []),
+ ('ProvisionsAllDevices', True),
+ ('DeveloperCertificates', []),
+ ]
+ for key, value in cases:
+ with self.subTest(key=key), self.assertRaises(ValueError):
+ profile = copy.deepcopy(self.profile)
+ profile[key] = value
+ self.validate(profile)
+
+ def test_rejects_development_wildcard_or_missing_entitlements(self):
+ cases = [
+ ('get-task-allow', True), ('get-task-allow', None),
+ ('beta-reports-active', False),
+ ('aps-environment', 'development'), ('aps-environment', None),
+ ('application-identifier', 'OLDPREFIX1.*'),
+ ('application-identifier', 'OLDPREFIX1.com.other.app'),
+ ('com.apple.developer.team-identifier', 'OTHERTEAM1'),
+ ]
+ for key, value in cases:
+ with self.subTest(key=key, value=value), self.assertRaises(ValueError):
+ profile = copy.deepcopy(self.profile)
+ profile['Entitlements'][key] = value
+ self.validate(profile)
+
+ def test_requires_matching_imported_certificate(self):
+ with self.assertRaisesRegex(ValueError, 'exactly one'):
+ self.validate(identities={'0' * 40})
+
+ def test_rejects_ambiguous_imported_certificates(self):
+ self.profile['DeveloperCertificates'].append(b'another-certificate')
+ other = hashlib.sha1(b'another-certificate').hexdigest().upper()
+ with self.assertRaisesRegex(ValueError, 'exactly one'):
+ self.validate(identities={self.identity, other})
+
+
+class CleanupTests(unittest.TestCase):
+ def test_absent_signing_root_is_noop(self):
+ with patch.dict(os.environ, {}, clear=True):
+ helper.cleanup()
+
+ def test_cleanup_only_removes_its_owned_temp_directory(self):
+ with tempfile.TemporaryDirectory() as temporary:
+ temp = Path(temporary).resolve()
+ owned = temp / 'ios-testflight-fixture'
+ owned.mkdir()
+ (owned / 'secret.p8').write_text('fixture')
+ unrelated = temp / 'unrelated'
+ unrelated.write_text('preserve')
+ with patch.dict(os.environ, {'RUNNER_TEMP': str(temp), 'SIGNING_ROOT': str(owned)}, clear=True):
+ helper.cleanup()
+ self.assertFalse(owned.exists())
+ self.assertEqual(unrelated.read_text(), 'preserve')
+
+ def test_cleanup_refuses_parent_unowned_relative_and_redirected_paths(self):
+ with tempfile.TemporaryDirectory() as temporary:
+ temp = Path(temporary).resolve()
+ unrelated = temp / 'unrelated'
+ unrelated.mkdir()
+ link = temp / 'ios-testflight-link'
+ link.symlink_to(unrelated, target_is_directory=True)
+ for root in (str(temp), str(unrelated), 'ios-testflight-relative', str(link)):
+ with self.subTest(root=root), patch.dict(os.environ, {'RUNNER_TEMP': str(temp), 'SIGNING_ROOT': root}, clear=True), self.assertRaisesRegex(ValueError, 'unsafe'):
+ helper.cleanup()
+ self.assertTrue(unrelated.exists())
+
+ def test_cleanup_refuses_unrelated_profile_path(self):
+ with tempfile.TemporaryDirectory() as temporary:
+ temp = Path(temporary).resolve()
+ owned = temp / 'ios-testflight-fixture'
+ owned.mkdir()
+ unrelated = temp / 'profile.mobileprovision'
+ unrelated.write_text('preserve')
+ with patch.dict(os.environ, {'RUNNER_TEMP': str(temp), 'SIGNING_ROOT': str(owned), 'INSTALLED_PROFILE': str(unrelated)}, clear=True), self.assertRaisesRegex(ValueError, 'profile cleanup'):
+ helper.cleanup()
+ self.assertEqual(unrelated.read_text(), 'preserve')
+
+
+if __name__ == '__main__':
+ suite = unittest.defaultTestLoader.loadTestsFromModule(__import__(__name__))
+ tests = [case for group in suite for case in group]
+ random.Random(2026).shuffle(tests)
+ result = unittest.TextTestRunner(verbosity=2).run(unittest.TestSuite(tests))
+ raise SystemExit(not result.wasSuccessful())
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 8879a556..01de1531 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -56,6 +56,9 @@ jobs:
- name: Install dependencies
run: pnpm install --frozen-lockfile
+ - name: Test iOS signing guards without credentials
+ run: python3 -m unittest discover -s .github/scripts -p 'test_ios_testflight.py' -v
+
- name: Type check sources before generating declarations
run: pnpm run typecheck
diff --git a/.github/workflows/release-native.yml b/.github/workflows/release-native.yml
index 36f302eb..05b50288 100644
--- a/.github/workflows/release-native.yml
+++ b/.github/workflows/release-native.yml
@@ -129,6 +129,25 @@ jobs:
with:
source_ref: ${{ needs.prepare.outputs.source_ref }}
+ testflight:
+ name: Sign iOS IPA and upload TestFlight
+ needs: prepare
+ if: >-
+ github.repository == 'dsh-tauri/deepseek-harness-desktop' &&
+ vars.IOS_TESTFLIGHT_ENABLED == 'true' &&
+ needs.prepare.outputs.should_build == 'true'
+ uses: ./.github/workflows/release-testflight.yml
+ with:
+ source_ref: ${{ needs.prepare.outputs.source_ref }}
+ secrets:
+ APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}
+ IOS_DISTRIBUTION_CERTIFICATE: ${{ secrets.IOS_DISTRIBUTION_CERTIFICATE }}
+ IOS_DISTRIBUTION_CERTIFICATE_PASSWORD: ${{ secrets.IOS_DISTRIBUTION_CERTIFICATE_PASSWORD }}
+ IOS_PROVISIONING_PROFILE: ${{ secrets.IOS_PROVISIONING_PROFILE }}
+ APP_STORE_CONNECT_API_KEY: ${{ secrets.APP_STORE_CONNECT_API_KEY }}
+ APP_STORE_CONNECT_KEY_ID: ${{ secrets.APP_STORE_CONNECT_KEY_ID }}
+ APP_STORE_CONNECT_ISSUER_ID: ${{ secrets.APP_STORE_CONNECT_ISSUER_ID }}
+
publish:
name: Publish Mobile Assets
needs: [prepare, build, build-ios]
diff --git a/.github/workflows/release-testflight.yml b/.github/workflows/release-testflight.yml
new file mode 100644
index 00000000..9d9bdb34
--- /dev/null
+++ b/.github/workflows/release-testflight.yml
@@ -0,0 +1,206 @@
+name: Release iOS TestFlight
+
+on:
+ workflow_call:
+ inputs:
+ source_ref:
+ description: Immutable upstream main-ancestor commit SHA to release
+ required: true
+ type: string
+ secrets:
+ APPLE_TEAM_ID:
+ required: false
+ IOS_DISTRIBUTION_CERTIFICATE:
+ required: false
+ IOS_DISTRIBUTION_CERTIFICATE_PASSWORD:
+ required: false
+ IOS_PROVISIONING_PROFILE:
+ required: false
+ APP_STORE_CONNECT_API_KEY:
+ required: false
+ APP_STORE_CONNECT_KEY_ID:
+ required: false
+ APP_STORE_CONNECT_ISSUER_ID:
+ required: false
+ workflow_dispatch:
+
+permissions:
+ contents: read
+
+concurrency:
+ group: ios-testflight-distribution
+ cancel-in-progress: false
+
+jobs:
+ release:
+ if: >-
+ github.repository == 'dsh-tauri/deepseek-harness-desktop' &&
+ (inputs.source_ref != '' || github.ref == 'refs/heads/main')
+ name: Sign and upload iOS TestFlight
+ runs-on: macos-latest
+ timeout-minutes: 120
+ defaults:
+ run:
+ shell: bash
+ env:
+ CI: '1'
+ LANG: en_US.UTF-8
+ LC_ALL: en_US.UTF-8
+ steps:
+ - name: Checkout trusted upstream main
+ uses: actions/checkout@v7
+ with:
+ repository: dsh-tauri/deepseek-harness-desktop
+ ref: main
+ fetch-depth: 0
+ persist-credentials: false
+
+ - name: Validate and checkout immutable official source
+ env:
+ SOURCE_REF: ${{ inputs.source_ref }}
+ EVENT_NAME: ${{ github.event_name }}
+ DISPATCH_SHA: ${{ github.sha }}
+ run: |
+ set -euo pipefail
+ if [[ -z "$SOURCE_REF" ]]; then
+ [[ "$EVENT_NAME" == workflow_dispatch ]] || { echo '::error::source_ref is required'; exit 1; }
+ SOURCE_REF="$DISPATCH_SHA"
+ fi
+ [[ "$SOURCE_REF" =~ ^[0-9a-f]{40}$ ]] || { echo '::error::source_ref must be a full immutable commit SHA'; exit 1; }
+ [[ "$(git cat-file -t "$SOURCE_REF")" == commit ]]
+ git merge-base --is-ancestor "$SOURCE_REF" refs/remotes/origin/main
+ git checkout --detach "$SOURCE_REF"
+ [[ "$(git rev-parse HEAD)" == "$SOURCE_REF" ]]
+ echo "SOURCE_SHA=$SOURCE_REF" >> "$GITHUB_ENV"
+
+ - name: Setup Xcode
+ uses: ./.github/actions/setup-xcode
+
+ - name: Setup Node.js and pnpm
+ uses: ./.github/actions/setup-node-pnpm
+
+ - name: Install dependencies
+ run: pnpm install --frozen-lockfile
+
+ - name: Normalize marketing version and stamp unique build before prebuild
+ run: |
+ set -euo pipefail
+ BUILD_NUMBER="$(python3 - <<'PY'
+ import runpy, time
+ helper = runpy.run_path('.github/scripts/ios-testflight.py')
+ print(helper['build_number'](time.time()))
+ PY
+ )"
+ export BUILD_NUMBER
+ node --input-type=commonjs <<'NODE'
+ const fs = require('node:fs');
+ const semver = require('semver');
+ const app = JSON.parse(fs.readFileSync('app.json', 'utf8'));
+ const version = JSON.parse(fs.readFileSync('package.json', 'utf8')).version;
+ if (app.expo.version !== version) throw new Error('app.json and package.json versions must match');
+ const parsed = semver.parse(version);
+ if (!parsed || `${parsed.version}${parsed.build.length ? '+' + parsed.build.join('.') : ''}` !== version) throw new Error('Version must be canonical SemVer');
+ if (app.expo.ios?.bundleIdentifier !== 'com.dshtauri.dshbridge') throw new Error('Unexpected iOS bundle ID');
+ const marketing = `${parsed.major}.${parsed.minor}.${parsed.patch}`;
+ app.expo.version = marketing;
+ app.expo.ios.buildNumber = process.env.BUILD_NUMBER;
+ fs.writeFileSync('app.json', `${JSON.stringify(app, null, 2)}\n`);
+ fs.appendFileSync(process.env.GITHUB_ENV, `VERSION=${version}\nIOS_VERSION=${marketing}\nBUILD_NUMBER=${process.env.BUILD_NUMBER}\n`);
+ NODE
+ echo 'Build number: 10-second ticks since 2020-01-01 UTC, split 4.2.2; serialized jobs hold a full tick for reruns (valid through 2051-09-09).' >> "$GITHUB_STEP_SUMMARY"
+ sleep 10
+
+ - name: Generate iOS project
+ run: pnpm exec expo prebuild --platform ios --no-install
+
+ - name: Install CocoaPods dependencies
+ working-directory: ios
+ run: |
+ set -euo pipefail
+ pod install
+ ruby -S gem install --user-install --no-document xcodeproj --version 1.27.0
+ ruby -e "gem 'xcodeproj', '= 1.27.0'; require 'xcodeproj'"
+
+ - name: Install and validate temporary distribution credentials
+ env:
+ APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}
+ IOS_DISTRIBUTION_CERTIFICATE: ${{ secrets.IOS_DISTRIBUTION_CERTIFICATE }}
+ IOS_DISTRIBUTION_CERTIFICATE_PASSWORD: ${{ secrets.IOS_DISTRIBUTION_CERTIFICATE_PASSWORD }}
+ IOS_PROVISIONING_PROFILE: ${{ secrets.IOS_PROVISIONING_PROFILE }}
+ APP_STORE_CONNECT_API_KEY: ${{ secrets.APP_STORE_CONNECT_API_KEY }}
+ APP_STORE_CONNECT_KEY_ID: ${{ secrets.APP_STORE_CONNECT_KEY_ID }}
+ APP_STORE_CONNECT_ISSUER_ID: ${{ secrets.APP_STORE_CONNECT_ISSUER_ID }}
+ run: python3 .github/scripts/ios-testflight.py install
+
+ - name: Configure signing only on the application target
+ run: |
+ set -euo pipefail
+ ruby <<'RUBY'
+ gem 'xcodeproj', '= 1.27.0'
+ require 'xcodeproj'
+ projects = Dir.glob('ios/*.xcodeproj')
+ abort 'Expected one generated app project' unless projects.length == 1
+ project = Xcodeproj::Project.open(projects.first)
+ targets = project.targets.select { |target| target.product_type == 'com.apple.product-type.application' }
+ abort 'Expected one app target without extensions' unless targets.length == 1 && project.targets.none? { |target| target.product_type == 'com.apple.product-type.app-extension' }
+ targets.first.build_configurations.each do |config|
+ settings = config.build_settings
+ settings['CODE_SIGN_STYLE'] = 'Manual'
+ settings['DEVELOPMENT_TEAM'] = ENV.fetch('SIGNING_TEAM')
+ settings['CODE_SIGN_IDENTITY'] = ENV.fetch('SIGNING_IDENTITY')
+ settings['CODE_SIGN_IDENTITY[sdk=iphoneos*]'] = ENV.fetch('SIGNING_IDENTITY')
+ settings['PROVISIONING_PROFILE_SPECIFIER'] = ENV.fetch('PROFILE_UUID')
+ settings['PROVISIONING_PROFILE_SPECIFIER[sdk=iphoneos*]'] = ENV.fetch('PROFILE_UUID')
+ end
+ project.save
+ RUBY
+
+ - name: Archive signed device Release app once
+ run: |
+ set -euo pipefail
+ workspaces=(ios/*.xcworkspace)
+ [[ ${#workspaces[@]} -eq 1 && -d "${workspaces[0]}" ]] || { echo '::error::Expected one generated workspace'; exit 1; }
+ scheme="$(basename "${workspaces[0]}" .xcworkspace)"
+ xcodebuild -workspace "${workspaces[0]}" -scheme "$scheme" \
+ -configuration Release -sdk iphoneos -destination 'generic/platform=iOS' \
+ -derivedDataPath "$SIGNING_ROOT/derived-data" \
+ -archivePath "$SIGNING_ROOT/DSH.xcarchive" archive
+
+ - name: Export signed App Store IPA without rebuilding
+ run: |
+ set -euo pipefail
+ xcodebuild -exportArchive -archivePath "$SIGNING_ROOT/DSH.xcarchive" \
+ -exportOptionsPlist "$SIGNING_ROOT/ExportOptions.plist" \
+ -exportPath "$SIGNING_ROOT/export"
+
+ - name: Verify IPA bundle, JavaScript, signature and distribution profile
+ run: python3 .github/scripts/ios-testflight.py verify
+
+ - name: Preserve verified signed IPA before upload
+ uses: actions/upload-artifact@v6
+ with:
+ name: ios-testflight-${{ env.VERSION }}-${{ env.BUILD_NUMBER }}
+ path: ${{ env.SIGNING_ROOT }}/artifact/
+ if-no-files-found: error
+ retention-days: 14
+
+ - name: Upload the same IPA to App Store Connect
+ env:
+ APP_STORE_CONNECT_KEY_ID: ${{ secrets.APP_STORE_CONNECT_KEY_ID }}
+ APP_STORE_CONNECT_ISSUER_ID: ${{ secrets.APP_STORE_CONNECT_ISSUER_ID }}
+ run: |
+ set -euo pipefail
+ export API_PRIVATE_KEYS_DIR="$SIGNING_ROOT/private_keys"
+ xcrun altool --upload-app --type ios --file "$IPA_PATH" \
+ --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.'
+ } >> "$GITHUB_STEP_SUMMARY"
+
+ - name: Always remove temporary signing material
+ if: always()
+ run: |
+ if [[ -n "${SIGNING_ROOT:-}" ]]; then
+ python3 .github/scripts/ios-testflight.py cleanup
+ fi
diff --git a/docs/TESTFLIGHT.zh.md b/docs/TESTFLIGHT.zh.md
new file mode 100644
index 00000000..d056603f
--- /dev/null
+++ b/docs/TESTFLIGHT.zh.md
@@ -0,0 +1,73 @@
+# 官方仓库 TestFlight 签名发布
+
+## 现有配置与需要补充的内容
+
+配置目标是 `dsh-tauri/deepseek-harness-desktop`,不是个人 fork。检查时,官方仓库只有 `APPLE_CERTIFICATE`、`APPLE_CERTIFICATE_PASSWORD`、`APPLE_ID`、`APPLE_PASSWORD`、`APPLE_TEAM_ID` 这五个仓库级 Secrets,尚未配置环境或 Variables。这里只读取了名称,GitHub 不允许读取已有 Secret 的明文值。
+
+现有 macOS 流程使用证书及 Apple ID 完成签名、公证;iOS 的 App Store 分发不是 macOS 公证。保留原有 macOS Secrets,不要替换它们。
+
+| Secret | 操作 |
+| --- | --- |
+| `APPLE_TEAM_ID` | 复用现有值,需与 iOS 证书、描述文件及 App Store Connect 团队一致 |
+| `IOS_DISTRIBUTION_CERTIFICATE` | 新增,包含私钥的 Apple Distribution `.p12` 文件的 Base64;不要使用 Developer ID Application 证书 |
+| `IOS_DISTRIBUTION_CERTIFICATE_PASSWORD` | 新增,导出 `.p12` 时设置的密码 |
+| `IOS_PROVISIONING_PROFILE` | 新增,`com.dshtauri.dshbridge` 对应的 App Store Connect 分发 `.mobileprovision` 的 Base64 |
+| `APP_STORE_CONNECT_API_KEY` | 新增,App Store Connect 团队 API Key 下载的 `.p8` 原始文本,不是 Base64 |
+| `APP_STORE_CONNECT_KEY_ID` | 新增,上述 API Key 的 Key ID |
+| `APP_STORE_CONNECT_ISSUER_ID` | 新增,团队 API Key 页面的 Issuer ID |
+
+不要将证书、私钥、密码或描述文件提交到 Git,也不要粘贴到聊天、Issue、日志中。
+
+## 苹果后台准备
+
+1. 在“钥匙串访问 → 我的证书”找到 Apple Distribution 证书,展开后必须能看到私钥,导出为带密码的 `.p12`。只有 `.cer` 文件不够。若已有有效证书,不必重新生成或撤销。
+2. 在 Apple Developer 的 Certificates, Identifiers & Profiles 中,确认 App ID 为 `com.dshtauri.dshbridge`。当前应用声明 Push Notifications entitlement,描述文件需支持相应能力。
+3. 创建 App Store Connect 分发描述文件,选择该 App ID 和刚导出的 Apple Distribution 证书。Development / Ad Hoc / Enterprise 描述文件不能代替它。
+4. 在 App Store Connect → Users and Access → Integrations → App Store Connect API 创建团队 API Key,赋予上传所需权限(通常 Developer 足够;按团队权限策略配置)。保存 `.p8`、Key ID、Issuer ID;私钥只能下载一次。这里不使用个人 API Key。
+5. 确认 App Store Connect 中已有相同 Bundle ID 的 iOS 应用记录,且开发者会员、协议均有效。
+
+## GitHub 配置
+
+使用官方仓库 Settings → Secrets and variables → Actions 下的 Repository secrets,不依赖独立 Environment。自动发布由现有移动端发行流程调用,手动 TestFlight 工作流只能从 `main` 启动,构建提交还须通过官方 main 历史校验。仓库级密钥没有 Environment 审批和部署分支限制,务必保护 main 与工作流修改权限;工作流内的检查不能替代仓库访问控制。
+
+以下命令将新增密钥放到仓库级 Secrets。命令中的文件名均为示例,请替换为本机实际文件;不要开启 shell 的 `set -x`。示例使用 macOS 的 `base64 -i`:
+
+```bash
+base64 -i distribution.p12 | gh secret set IOS_DISTRIBUTION_CERTIFICATE --repo dsh-tauri/deepseek-harness-desktop
+base64 -i app-store.mobileprovision | gh secret set IOS_PROVISIONING_PROFILE --repo dsh-tauri/deepseek-harness-desktop
+gh secret set IOS_DISTRIBUTION_CERTIFICATE_PASSWORD --repo dsh-tauri/deepseek-harness-desktop
+gh secret set APP_STORE_CONNECT_API_KEY --repo dsh-tauri/deepseek-harness-desktop < AuthKey_EXAMPLE.p8
+gh secret set APP_STORE_CONNECT_KEY_ID --repo dsh-tauri/deepseek-harness-desktop
+gh secret set APP_STORE_CONNECT_ISSUER_ID --repo dsh-tauri/deepseek-harness-desktop
+```
+
+未传入值的命令会交互式询问;不要把密码写在命令行参数中。`APPLE_TEAM_ID` 沿用现有仓库级 Secret。管理 Secrets 与创建 Environment 的权限不同,应以实际 API 返回结果为准。
+
+合入工作流并配置好密钥后,开启仓库级 Variable:
+
+```bash
+gh variable set IOS_TESTFLIGHT_ENABLED --body true --repo dsh-tauri/deepseek-harness-desktop
+```
+
+关闭此开关会停止后续自动 TestFlight 任务,不改变原有 APK / unsigned IPA 发布。手动运行不依赖此开关,可用于首次验证,但仍受官方仓库、main 分支和可信提交校验约束。
+
+## 触发与产物
+
+- 桌面正式发版成功后,现有 `Release Mobile Apps (Native)` 解析发行提交;新增独立 TestFlight 任务签名并上传该提交。
+- 原有 Android 和 unsigned iOS 任务保持不变,GitHub Release 的既有资产不因 TestFlight 上传失败而被阻止。
+- 手动试跑命令:
+
+```bash
+gh workflow run release-testflight.yml --repo dsh-tauri/deepseek-harness-desktop --ref main
+```
+
+- 只允许官方仓库执行;输入提交必须是官方 `main` 历史中的完整 SHA,不能给任意 PR / fork 代码提供签名凭据。
+- 每次运行重新生成 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 审核或正式上架,也不自动添加测试员。
+- 部分预编译框架可能缺少 dSYM;此前本机上传已有此类非阻断警告。保留符号产物便于后续排查,不能把“上传成功”当作真机验收通过。
+
+## 验证边界
+
+本地可验证工作流结构、脚本语法和配置校验逻辑。真正的证书导入、苹果认证、IPA 导出与上传必须在补齐密钥后的官方 macOS runner 首跑验证;没有这些凭据时,不能声称签名 CI 已运行通过。
diff --git a/docs/specs/native.md b/docs/specs/native.md
index 601a3b7d..8c2ecca9 100644
--- a/docs/specs/native.md
+++ b/docs/specs/native.md
@@ -191,7 +191,9 @@ src-native/
* 本仓库根依赖由共享 catalog 固定,`react` / `react-dom` / `typescript` 与 Expo 57 期望版本不一致,`expo install --check` 在本机与 CI 上必然非零退出,因此**不**把它当门禁;原生兼容性以 `prebuild` + Gradle 编译为准。
* `build-ios.yml` 用 Expo prebuild、CocoaPods 与真机 Release 构建生成未签名 IPA,复用输入 `source_ref` 指向发布提交;`build-ios-test.yml` 仅手动调用,不随 CI 打包。
* iOS 资产名为 `Deepseek.Harness.iOS_<version>_unsigned.ipa`,artifact 为 `ios-ipa-<version>`;`bundleIdentifier` 为 `com.dshtauri.dshbridge`。构建校验非空内嵌 JS bundle 与第三方声明,不依赖 Metro。
-* IPA 不含分发签名,不能直接安装或提交 App Store,需自行签名。预发布完整版本保留在资产名中,iOS `CFBundleShortVersionString` 使用三段数字核心版本。
+* 上述 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)。
---
diff --git a/test/mobile-release-workflows.test.ts b/test/mobile-release-workflows.test.ts
index c2713c82..5d4701b2 100644
--- a/test/mobile-release-workflows.test.ts
+++ b/test/mobile-release-workflows.test.ts
@@ -119,6 +119,29 @@ describe('mobile release workflow contracts', () => {
expect(publish).toContain('gh release upload "$RELEASE_TAG"')
})
+ it('isolates TestFlight signing from unsigned mobile release assets', () => {
+ const job = section(release, 'testflight', 2)
+ expect(job).toContain('github.repository == \'dsh-tauri/deepseek-harness-desktop\'')
+ expect(job).toContain('vars.IOS_TESTFLIGHT_ENABLED == \'true\'')
+ expect(job).toContain('needs.prepare.outputs.should_build == \'true\'')
+ expect(job).toContain('uses: ./.github/workflows/release-testflight.yml')
+ expect(job).toContain(`source_ref: \${{ needs.prepare.outputs.source_ref }}`)
+ const secrets = [
+ 'APPLE_TEAM_ID',
+ 'IOS_DISTRIBUTION_CERTIFICATE',
+ 'IOS_DISTRIBUTION_CERTIFICATE_PASSWORD',
+ 'IOS_PROVISIONING_PROFILE',
+ 'APP_STORE_CONNECT_API_KEY',
+ 'APP_STORE_CONNECT_KEY_ID',
+ 'APP_STORE_CONNECT_ISSUER_ID',
+ ]
+ for (const name of secrets)
+ expect(job).toContain(`${name}: \${{ secrets.${name} }}`)
+ expect(section(release, 'publish', 2)).toContain('needs: [prepare, build, build-ios]')
+ expect(section(release, 'publish', 2)).not.toContain('needs.testflight')
+ expect(section(release, 'build-ios', 2)).not.toContain('secrets:')
+ })
+
it('keeps the native version synchronized with the desktop version', () => {
expect(JSON.parse(readSource('app.json')).expo.version).toBe(JSON.parse(readSource('package.json')).version)
expect(bumpConfig.files).toContain('app.json')