diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS
new file mode 100644
index 0000000000..baadc36f3e
--- /dev/null
+++ b/.github/CODEOWNERS
@@ -0,0 +1,2 @@
+# Request the three developers for all changes; one approval is required.
+* @ben-kaufman @cakesoft-utkarsh @Parsh
diff --git a/.github/native/.gitignore b/.github/native/.gitignore
new file mode 100644
index 0000000000..ecb842d705
--- /dev/null
+++ b/.github/native/.gitignore
@@ -0,0 +1 @@
+.generated/
diff --git a/.github/native/android_startup_diagnosis.py b/.github/native/android_startup_diagnosis.py
new file mode 100644
index 0000000000..487cb040b1
--- /dev/null
+++ b/.github/native/android_startup_diagnosis.py
@@ -0,0 +1,274 @@
+"""Read-only Android startup facts. No raw device or application text escapes."""
+from pathlib import Path
+import re
+import shutil
+import subprocess
+
+APP = 'io.hexawallet.keeper.development'
+LIMIT = 256 * 1024
+TYPES = ('TypeError', 'SyntaxError', 'ReferenceError', 'RangeError', 'EvalError',
+ 'URIError', 'AggregateError', 'TransformError', 'UnableToResolveError',
+ 'InternalError', 'RuntimeException', 'IllegalStateException',
+ 'IllegalArgumentException', 'NullPointerException', 'SecurityException',
+ 'UnsatisfiedLinkError', 'NoClassDefFoundError', 'ClassNotFoundException',
+ 'OutOfMemoryError', 'Error')
+FAULTS = {
+ 'JS_TYPE_ERROR': r'\bTypeError\b|undefined is not a function',
+ 'JS_SYNTAX_ERROR': r'\bSyntaxError\b',
+ 'JS_REFERENCE_ERROR': r'\bReferenceError\b',
+ 'JS_RANGE_ERROR': r'\bRangeError\b',
+ 'MODULE_RESOLUTION_ERROR': r'Unable to resolve module|\bUnableToResolveError\b',
+ 'TRANSFORM_ERROR': r'\bTransformError\b',
+ 'APP_NOT_REGISTERED': r'has not been registered',
+ 'NATIVE_MODULE_UNAVAILABLE': r'TurboModuleRegistry\.getEnforcing|requireNativeComponent|native module cannot be null',
+ 'NATIVE_LIBRARY_LOAD_ERROR': r'\bUnsatisfiedLinkError\b|dlopen failed|could not load library',
+ 'NATIVE_FATAL_SIGNAL': r'Fatal signal \d+\b',
+ 'JAVA_FATAL_EXCEPTION': r'FATAL EXCEPTION:',
+ 'MEMORY_EXHAUSTION': r'\bOutOfMemoryError\b|out of memory',
+ 'TRANSPORT_ERROR': r'\b(?:EADDRINUSE|ECONNREFUSED|ECONNRESET)\b',
+ 'FILESYSTEM_ERROR': r'\b(?:ENOENT|EACCES|ENOSPC)\b',
+ 'WORKER_HEAP_EXHAUSTION': r'JavaScript heap out of memory|Reached heap limit|Ineffective mark-compacts',
+ 'PROCESS_KILLED_MARKER': r'\bSIGKILL\b|worker process.*terminated|worker.*killed',
+}
+EXIT_REASONS = {0: 'UNKNOWN', 1: 'EXIT_SELF', 2: 'SIGNALED', 3: 'LOW_MEMORY',
+ 4: 'JAVA_CRASH', 5: 'NATIVE_CRASH', 6: 'ANR', 7: 'INITIALIZATION_FAILURE',
+ 8: 'PERMISSION_CHANGE', 9: 'EXCESSIVE_RESOURCE_USAGE',
+ 10: 'USER_REQUESTED', 11: 'USER_STOPPED', 12: 'DEPENDENCY_DIED',
+ 13: 'OTHER', 14: 'FREEZER', 15: 'PACKAGE_STATE_CHANGE', 16: 'PACKAGE_UPDATED'}
+
+
+def safe_error(error):
+ name = type(error).__name__
+ return name if name in {'OSError', 'FileNotFoundError', 'PermissionError',
+ 'TimeoutExpired', 'ValueError', 'TypeError'} else 'OTHER_ERROR'
+
+
+def bounded(path, private):
+ if path.is_symlink() or not path.resolve().is_relative_to(private.resolve()):
+ raise ValueError('Expected a private regular file.')
+ size = path.stat().st_size
+ with path.open('rb') as source:
+ prefix = source.read(LIMIT)
+ tail = b''
+ if size > LIMIT:
+ source.seek(max(LIMIT, size - LIMIT))
+ tail = source.read(LIMIT)
+ truncated = size > len(prefix) + len(tail)
+ if truncated:
+ prefix = prefix.rsplit(b'\n', 1)[0] if b'\n' in prefix else b''
+ tail = tail.split(b'\n', 1)[1] if b'\n' in tail else b''
+ return (prefix + (b'\n' if truncated else b'') + tail).decode(errors='replace'), {
+ 'bytes_observed': size, 'bytes_read': len(prefix) + len(tail),
+ 'input_truncated': truncated, 'read_scope': 'PREFIX_AND_TAIL' if truncated else 'FULL'}
+
+
+def faults(payload):
+ return {'exception_types': [kind for kind in TYPES if re.search(r'\b' + kind + r'\b', payload)],
+ 'fault_categories': [name for name, pattern in FAULTS.items()
+ if re.search(pattern, payload, re.IGNORECASE)]}
+
+
+def processes(payload, usable=True):
+ lines = [line.strip() for line in payload.splitlines() if line.strip()]
+ result = {'state': 'UNKNOWN', 'matching_process_count': None, 'parsed_records': 0,
+ 'unparsed_records': 0}
+ owned = set()
+ seen = set()
+ if not usable or not lines or lines[0].split() != ['PID', 'NAME']:
+ return result, owned
+ for line in lines[1:]:
+ match = re.fullmatch(r'([1-9]\d*)\s+(\S+)', line)
+ if not match or int(match[1]) in seen:
+ result['unparsed_records'] += 1
+ continue
+ seen.add(int(match[1]))
+ result['parsed_records'] += 1
+ if match[2] == APP or match[2].startswith(APP + ':'):
+ owned.add(int(match[1]))
+ if result['unparsed_records'] == 0 and result['parsed_records'] > 0:
+ result.update(state='PRESENT' if owned else 'ABSENT', matching_process_count=len(owned))
+ else:
+ owned.clear() # Malformed inventory cannot establish process attribution.
+ return result, owned
+
+
+def foreground(payload, usable=True):
+ relations = set()
+ parsed, unparsed = 0, 0
+ if usable:
+ for line in payload.splitlines():
+ if not re.search(r'\b(?:topResumedActivity|mResumedActivity)\s*[:=]', line):
+ continue
+ if re.search(r'[:=]\s*(?:null|None)\s*$', line):
+ relations.add('NONE')
+ parsed += 1
+ elif match := re.search(r'ActivityRecord\{.*?\bu\d+\s+([A-Za-z0-9_.]+)/(?:[^\s}]+)', line):
+ relations.add('OWN_APP' if match[1] == APP else 'OTHER_APP')
+ parsed += 1
+ else:
+ unparsed += 1
+ return {'relation': next(iter(relations)) if len(relations) == 1 and not unparsed else 'UNKNOWN',
+ 'parsed_records': parsed, 'unparsed_records': unparsed,
+ 'scope': 'RESUMED_ACTIVITY_ONLY_NOT_WINDOW_VISIBILITY'}
+
+
+def exit_history(payload, usable=True):
+ reasons = []
+ matched = 0
+ if usable:
+ for line in payload.splitlines():
+ match = re.search(r'\bprocess=(\S+)\s+reason=(\d+)\s', line)
+ if match and (match[1] == APP or match[1].startswith(APP + ':')):
+ matched += 1
+ reason = EXIT_REASONS.get(int(match[2]), 'UNRECOGNIZED_REASON')
+ if reason not in reasons:
+ reasons.append(reason)
+ return {'matching_records': matched, 'reason_categories': reasons,
+ 'parse_status': 'PARSED' if matched else 'UNKNOWN',
+ 'freshness': 'UNKNOWN', 'scope': 'APP_HISTORY_NOT_PROOF_OF_CURRENT_FAILURE_CAUSE'}
+
+
+def android_log(payload, owned):
+ result = {'parsed_error_records': 0, 'own_error_records': 0, 'unclassified_own_error_records': 0,
+ 'unparsed_nonempty_lines': 0, 'exception_types': [], 'fault_categories': [],
+ 'attribution': 'CURRENT_OWN_PID_MATCH_HISTORY_FRESHNESS_UNKNOWN' if owned
+ else 'UNKNOWN_NO_CURRENT_OWN_PROCESS'}
+ pattern = r'^\d{2}-\d{2} \d{2}:\d{2}:\d{2}\.\d+\s+(\d+)\s+\d+\s+[EF]\s+[^:]+:\s*(.*)$'
+ for line in payload.splitlines():
+ match = re.match(pattern, line)
+ if not match:
+ if line.strip() and not line.startswith('--------- beginning of '):
+ result['unparsed_nonempty_lines'] += 1
+ continue
+ result['parsed_error_records'] += 1
+ if int(match[1]) not in owned:
+ continue
+ result['own_error_records'] += 1
+ observed = faults(match[2])
+ if not any(observed.values()):
+ result['unclassified_own_error_records'] += 1
+ for key in observed:
+ result[key] = list(dict.fromkeys(result[key] + observed[key]))
+ return result
+
+
+def metro(payload):
+ selected = []
+ headers, remaining = 0, 0
+ for raw in payload.splitlines():
+ line = re.sub(r'\x1b\[[0-9;]*[A-Za-z]', '', raw).strip()
+ if re.match(r'^(?:ERROR\b|FATAL ERROR:|(?:\w*Error):|Unable to resolve module)', line, re.IGNORECASE):
+ headers += 1
+ remaining = 4
+ elif remaining:
+ remaining -= 1
+ else:
+ continue
+ if re.match(r'^(?:(?:>\s*)?\d+\s*\||\^|at\s)', line):
+ continue
+ selected.append(line)
+ return {'observed_error_headers': headers, 'scanned_error_context_lines': len(selected),
+ 'unclassified_error_context_lines': sum(not faults(line)['fault_categories'] for line in selected),
+ **faults('\n'.join(selected)), 'scope': 'ERROR_MARKERS_NOT_BUNDLE_OR_STARTUP_ACCEPTANCE'}
+
+
+def host_memory(root=Path('/')):
+ result = {'scope': 'HOST_SNAPSHOT_AND_HISTORICAL_CGROUP_EVENTS_NOT_FAILURE_CAUSE',
+ 'meminfo': {'lookup_status': 'UNKNOWN'}, 'cgroup': {}}
+
+ def small(path):
+ with path.open('rb') as source:
+ value = source.read(8193)
+ if len(value) > 8192:
+ raise ValueError('Memory record exceeded size limit.')
+ return value.decode('ascii').strip()
+
+ try:
+ payload = small(root / 'proc/meminfo')
+ matches = re.findall(r'^(MemTotal|MemAvailable|SwapTotal|SwapFree):\s+(\d+) kB$', payload, re.MULTILINE)
+ fields = dict(matches)
+ recognized = sum(bool(re.match(r'^(?:MemTotal|MemAvailable|SwapTotal|SwapFree)\b', line))
+ for line in payload.splitlines())
+ if len(fields) == len(matches) == recognized == 4:
+ result['meminfo'] = {'lookup_status': 'SUCCESS',
+ 'bytes': {name: int(value) * 1024 for name, value in fields.items()}}
+ except Exception as error:
+ result['meminfo']['error_type'] = safe_error(error)
+ for name in ['memory.current', 'memory.max', 'memory.events']:
+ observed = {'lookup_status': 'UNKNOWN'}
+ try:
+ value = small(root / 'sys/fs/cgroup' / name)
+ if name == 'memory.events':
+ matches = re.findall(r'^(oom|oom_kill) (\d+)$', value, re.MULTILINE)
+ events = dict(matches)
+ recognized = sum(bool(re.match(r'^(?:oom|oom_kill)\b', line)) for line in value.splitlines())
+ if len(events) == len(matches) == recognized == 2:
+ observed = {'lookup_status': 'SUCCESS', 'counts': {k: int(v) for k, v in events.items()}}
+ elif value.isascii() and value.isdecimal():
+ observed = {'lookup_status': 'SUCCESS', 'bytes': int(value)}
+ elif name == 'memory.max' and value == 'max':
+ observed = {'lookup_status': 'SUCCESS', 'limit': 'UNLIMITED'}
+ except Exception as error:
+ observed['error_type'] = safe_error(error)
+ result['cgroup'][name] = observed
+ return result
+
+
+def collect(private, device):
+ private = Path(private)
+ if not re.fullmatch(r'emulator-\d+', device):
+ raise ValueError('Expected the owned emulator selector.')
+ work = private / 'android-startup-diagnosis'
+ work.mkdir(mode=0o700)
+ result = {'diagnostic_only': True, 'cause': 'UNDETERMINED', 'host_memory': host_memory(), 'commands': [],
+ 'collection_errors': [], 'cleanup_status': 'UNKNOWN'}
+
+ def capture(label, arguments):
+ path = work / (label + '.log')
+ facts = {'label': label, 'lookup_status': 'UNKNOWN', 'exit_code': None,
+ 'bytes_observed': None, 'bytes_read': 0, 'input_truncated': None, 'read_scope': 'NOT_READ'}
+ payload = ''
+ try:
+ with path.open('xb') as output:
+ proc = subprocess.run(['adb', '-s', device, *arguments], stdout=output,
+ stderr=subprocess.STDOUT, timeout=15, check=False)
+ facts['exit_code'] = proc.returncode
+ payload, observed = bounded(path, private)
+ facts.update(observed)
+ if proc.returncode == 0:
+ facts['lookup_status'] = 'SUCCESS'
+ else:
+ payload = ''
+ except Exception as error:
+ facts['error_type'] = safe_error(error)
+ payload = ''
+ finally:
+ path.unlink(missing_ok=True)
+ result['commands'].append(facts)
+ return payload, facts.get('lookup_status') == 'SUCCESS' and not facts.get('input_truncated', True)
+
+ try:
+ payload, usable = capture('processes', ['shell', 'ps', '-A', '-o', 'PID,NAME'])
+ result['processes'], owned = processes(payload, usable)
+ payload, usable = capture('foreground', ['shell', 'dumpsys', 'activity', 'activities'])
+ result['foreground_activity'] = foreground(payload, usable)
+ payload, usable = capture('exit-history', ['shell', 'dumpsys', 'activity', 'exit-info', APP])
+ result['exit_history'] = exit_history(payload, usable)
+ payload, _ = capture('runtime-errors', ['logcat', '-d', '-b', 'main', '-b', 'crash',
+ '-t', '1200', '-v', 'threadtime', '*:E'])
+ result['runtime_errors'] = android_log(payload, owned)
+ result['runtime_errors'].update(
+ lookup_status=result['commands'][-1]['lookup_status'],
+ input_truncated=result['commands'][-1]['input_truncated'])
+ try:
+ payload, observed = bounded(private / 'metro.log', private)
+ result['metro'] = {'lookup_status': 'SUCCESS', **observed, **metro(payload)}
+ except Exception as error:
+ result['collection_errors'].append({'stage': 'metro', 'error_type': safe_error(error)})
+ finally:
+ try:
+ shutil.rmtree(work)
+ result['cleanup_status'] = 'DELETED'
+ except Exception as error:
+ result['collection_errors'].append({'stage': 'cleanup', 'error_type': safe_error(error)})
+ return result
diff --git a/.github/native/canonical_metadata.py b/.github/native/canonical_metadata.py
new file mode 100644
index 0000000000..c61c143b14
--- /dev/null
+++ b/.github/native/canonical_metadata.py
@@ -0,0 +1,35 @@
+#!/usr/bin/env python3
+"""Read one bounded metadata.json member without extracting paths or echoing errors."""
+import io
+import stat
+import sys
+import zipfile
+
+
+def read_metadata(raw):
+ if len(raw) > 1048576:
+ raise ValueError('archive size')
+ with zipfile.ZipFile(io.BytesIO(raw)) as archive:
+ members = archive.infolist()
+ if len(members) != 1:
+ raise ValueError('single metadata file required')
+ member = members[0]
+ mode = member.external_attr >> 16
+ if (member.filename != 'metadata.json' or member.flag_bits & 1 or
+ stat.S_ISLNK(mode) or not 0 < member.file_size <= 524288):
+ raise ValueError('metadata member rejected')
+ with archive.open(member) as source:
+ result = source.read(524289)
+ if len(result) != member.file_size:
+ raise ValueError('metadata size mismatch')
+ return result
+
+
+if __name__ == '__main__':
+ try:
+ with open(sys.argv[1], 'rb') as source:
+ result = read_metadata(source.read(1048577))
+ sys.stdout.buffer.write(result)
+ except Exception:
+ sys.stderr.write('Canonical metadata archive rejected.\n')
+ raise SystemExit(1)
diff --git a/.github/native/canonical_native.cjs b/.github/native/canonical_native.cjs
new file mode 100644
index 0000000000..ebee18cb53
--- /dev/null
+++ b/.github/native/canonical_native.cjs
@@ -0,0 +1,237 @@
+'use strict';
+// Read-only canonical provenance/receipts. Never signs, posts statuses or approves release.
+const crypto = require('node:crypto');
+const fs = require('node:fs');
+const os = require('node:os');
+const path = require('node:path');
+const { execFileSync } = require('node:child_process');
+const { REQUIRED, acceptance } = require('./release_acceptance.cjs');
+const { publicCompanionChecks } = require('./public_companion_receipts.cjs');
+const REPOSITORY = 'KeeperCommunity/bitcoin-keeper';
+const REPOSITORY_ID = 470904030;
+const WORKFLOW = '.github/workflows/keeper-canonical-native.yml';
+const WORKER = '.github/workflows/keeper-canonical-native-platform.yml';
+const APP_ID = 15368;
+const SHA = /^[a-f0-9]{40}$/;
+const digest = bytes => crypto.createHash('sha256').update(bytes).digest('hex');
+const demand = (condition, code) => { if (!condition) throw new Error(code); };
+const artifactName = (platform, request) => `keeper-canonical-native-${platform}-${request.sourceSha}-${request.runId}-${request.attempt}`;
+const attestationName = request => `keeper-canonical-native-attestation-${request.sourceSha}-${request.runId}-${request.attempt}`;
+
+function requestFromEnvironment(context, env) {
+ const request = { sourceSha: env.KEEPER_SOURCE_SHA, workflowSha: env.GITHUB_WORKFLOW_SHA,
+ workflowRef: env.GITHUB_WORKFLOW_REF, pin: env.KEEPER_CANONICAL_NATIVE_DRIVER_SHA,
+ runId: Number(env.GITHUB_RUN_ID), attempt: Number(env.GITHUB_RUN_ATTEMPT) };
+ demand(context.eventName === 'workflow_dispatch' && context.ref === 'refs/heads/sprint' &&
+ `${context.repo.owner}/${context.repo.repo}` === REPOSITORY, 'CANONICAL_DISPATCH_REF_REQUIRED');
+ demand(SHA.test(request.sourceSha || '') && request.sourceSha === context.sha &&
+ request.workflowSha === request.sourceSha && request.pin === request.sourceSha &&
+ request.workflowRef === `${REPOSITORY}/${WORKFLOW}@refs/heads/sprint`, 'INSTALLED_DRIVER_PIN_REQUIRED');
+ demand(Number.isSafeInteger(request.runId) && request.runId === context.runId && request.runId > 0 &&
+ Number.isSafeInteger(request.attempt) && request.attempt > 0, 'EXACT_RUN_ATTEMPT_REQUIRED');
+ return request;
+}
+
+function githubApp(check) {
+ return check?.app?.id === APP_ID && check.app.slug === 'github-actions';
+}
+
+function pinReaderFromEnvironment(github, env) {
+ const token = env.KEEPER_CANONICAL_PIN_READ_TOKEN;
+ // The collector spawns the bounded ZIP reader. Do not pass this credential to
+ // that subprocess or to subsequent tooling through the process environment.
+ delete env.KEEPER_CANONICAL_PIN_READ_TOKEN;
+ demand(typeof token === 'string' && token.trim().length > 0, 'LIVE_DRIVER_PIN_IDENTITY_REQUIRED');
+ // Keep the normal GITHUB_TOKEN client for Actions/checks/contents. This
+ // repository-selected Variables:read identity is used only for the live pin.
+ return new github.constructor({ auth: token });
+}
+
+async function origin(github, context, request, { admission = false, pinReader } = {}) {
+ demand(typeof pinReader?.rest?.actions?.getRepoVariable === 'function', 'LIVE_DRIVER_PIN_IDENTITY_REQUIRED');
+ const args = context.repo;
+ const [repository, branch, workflow, run, pin] = await Promise.all([
+ github.rest.repos.get(args).then(r => r.data),
+ github.rest.repos.getBranch({ ...args, branch: 'sprint' }).then(r => r.data),
+ github.rest.actions.getWorkflow({ ...args, workflow_id: path.basename(WORKFLOW) }).then(r => r.data),
+ github.rest.actions.getWorkflowRun({ ...args, run_id: request.runId }).then(r => r.data),
+ pinReader.rest.actions.getRepoVariable({ ...args, name: 'KEEPER_CANONICAL_NATIVE_DRIVER_SHA',
+ headers: { 'cache-control': 'no-cache' } }).then(r => r.data)
+ .catch(() => { throw new Error('LIVE_DRIVER_PIN_REVOKED_OR_UNREADABLE'); }),
+ ]);
+ demand(pin?.name === 'KEEPER_CANONICAL_NATIVE_DRIVER_SHA' && pin.value === request.sourceSha && pin.value === request.pin,
+ 'LIVE_DRIVER_PIN_REVOKED_OR_UNREADABLE');
+ demand(repository.id === REPOSITORY_ID && repository.full_name === REPOSITORY && repository.default_branch === 'sprint', 'REPOSITORY_MISMATCH');
+ demand(branch.protected === true && branch.commit?.sha === request.sourceSha, 'CANONICAL_HEAD_MOVED_OR_UNPROTECTED');
+ demand(workflow.path === WORKFLOW && workflow.state === 'active', 'CANONICAL_WORKFLOW_NOT_INSTALLED');
+ demand(run.id === request.runId && run.run_attempt === request.attempt && run.workflow_id === workflow.id &&
+ run.event === 'workflow_dispatch' && run.path?.split('@')[0] === WORKFLOW &&
+ run.head_sha === request.sourceSha && run.head_branch === 'sprint' &&
+ run.head_repository?.id === REPOSITORY_ID && run.head_repository.full_name === REPOSITORY &&
+ Array.isArray(run.pull_requests) && run.pull_requests.length === 0 &&
+ (run.status === 'in_progress' || (run.status === 'completed' && run.conclusion === 'success')),
+ 'CANONICAL_RUN_MISMATCH');
+ const suite = (await github.rest.checks.getSuite({ ...args, check_suite_id: run.check_suite_id })).data;
+ demand(githubApp(suite) && suite.head_sha === request.sourceSha && suite.id === run.check_suite_id, 'FORGED_ACTIONS_APP');
+ const listing = (await github.rest.actions.listWorkflowRuns({ ...args, workflow_id: workflow.id,
+ branch: 'sprint', event: 'workflow_dispatch', head_sha: request.sourceSha, per_page: 100 })).data;
+ demand(Number.isSafeInteger(listing.total_count) && listing.total_count <= 100 &&
+ listing.total_count === listing.workflow_runs?.length &&
+ listing.workflow_runs.every(item => item.head_sha === request.sourceSha) &&
+ Math.max(...listing.workflow_runs.map(item => item.id)) === request.runId,
+ 'NEWER_OR_INCOMPLETE_CANONICAL_RUNS');
+ if (admission) {
+ const active = await Promise.all(['in_progress', 'queued', 'waiting', 'pending', 'requested'].map(async status =>
+ (await github.rest.actions.listWorkflowRunsForRepo({ ...args, status, per_page: 100 })).data));
+ const nativePaths = [WORKFLOW, '.github/workflows/keeper-hosted-native.yml',
+ '.github/workflows/keeper-native-diagnostic.yml', '.github/workflows/keeper-release-acceptance.yml',
+ '.github/workflows/keeper-one-time-native.yml', '.github/workflows/keeper-one-time-native-diagnostic.yml',
+ '.github/workflows/android-diagnostic-build.yml', '.github/workflows/keeper-protected-release-workers.yml'];
+ for (const page of active) {
+ demand(page.total_count <= 100 && page.total_count === page.workflow_runs?.length, 'CAPACITY_OBSERVATION_INCOMPLETE');
+ demand(!page.workflow_runs.some(item => item.id !== request.runId && nativePaths.includes(item.path?.split('@')[0])),
+ 'ANOTHER_NATIVE_RUN_ACTIVE_OR_QUEUED');
+ }
+ }
+ return { run, workflow };
+}
+
+function requiredSteps(platform) {
+ return ['Verify canonical installed source', 'Record runner and toolchain', 'Install immutable native dependencies',
+ 'Build development app', ...(platform === 'IOS' ? ['Check disposable iOS driver readiness',
+ 'Run disposable startup smoke', 'Run disposable native persistence probe',
+ 'Run R5 production worker native scenarios', 'Measure full-product startup wallet and Retry flows']
+ : ['Run Android startup persistence worker and product flows'])];
+}
+
+async function platformJobs(github, context, request, run) {
+ const jobs = await github.paginate(github.rest.actions.listJobsForWorkflowRunAttempt,
+ { ...context.repo, run_id: request.runId, attempt_number: request.attempt, per_page: 100 });
+ const result = {};
+ for (const platform of ['IOS', 'ANDROID']) {
+ const matches = jobs.filter(job => job.name === `${platform.toLowerCase()} / Canonical ${platform} build and features`);
+ demand(matches.length === 1, 'CANONICAL_PLATFORM_JOB_MISSING_OR_AMBIGUOUS');
+ const job = matches[0];
+ demand(job.run_id === request.runId && job.run_attempt === request.attempt && job.head_sha === request.sourceSha &&
+ job.status === 'completed' && job.conclusion === 'success', 'CANONICAL_PLATFORM_NOT_EXACT_SUCCESS');
+ for (const name of requiredSteps(platform)) {
+ const steps = job.steps?.filter(step => step.name === name) ?? [];
+ demand(steps.length === 1 && steps[0].status === 'completed' && steps[0].conclusion === 'success', 'CANONICAL_REQUIRED_STEP_NOT_SUCCESS');
+ }
+ const match = job.check_run_url?.match(/^https:\/\/api\.github\.com\/repos\/KeeperCommunity\/bitcoin-keeper\/check-runs\/([0-9]+)$/);
+ demand(match, 'CANONICAL_JOB_CHECK_LINK_INVALID');
+ const check = (await github.rest.checks.get({ ...context.repo, check_run_id: Number(match[1]) })).data;
+ demand(check.id === Number(match[1]) && check.name === job.name && githubApp(check) &&
+ check.head_sha === request.sourceSha && check.check_suite?.id === run.check_suite_id &&
+ check.status === 'completed' && check.conclusion === 'success', 'CANONICAL_JOB_CHECK_UNTRUSTED');
+ result[platform] = job;
+ }
+ return result;
+}
+
+function validateMetadata(metadata, request, platform) {
+ const apps = { IOS: 'io.hexawallet.hexakeeper.dev', ANDROID: 'io.hexawallet.keeper.development' };
+ demand(metadata.schema === 1 && metadata.platform === platform && metadata.source_sha === request.sourceSha &&
+ metadata.workflow_sha === request.workflowSha && metadata.workflow_ref === request.workflowRef &&
+ metadata.run_id === String(request.runId) && metadata.run_attempt === String(request.attempt) &&
+ metadata.app_id === apps[platform] && metadata.diagnostic_only === false, 'CANONICAL_RECEIPT_IDENTITY_MISMATCH');
+ const status = value => value === 'PASS' ? 'PASS' : 'NOT VERIFIED';
+ const checks = {
+ 'native-build': { status: status(metadata.build), scope: 'development native build' },
+ 'startup': { status: status(metadata.smoke), scope: 'ordinary app passcode startup smoke' },
+ 'native-storage': { status: status(metadata.native_probe), scope: 'CI entrypoint native Realm/MMKV process persistence' },
+ 'production-worker-controls': { status: status(metadata.r5_features), scope: 'CI-extracted production workers; synthetic boundaries are not complete application UI' },
+ 'five-product-observations': { status: 'NOT VERIFIED', scope: 'ordinary app debug UI observations; no release performance budget' },
+ 'controlled-setup-disconnect-retry': { status: 'NOT VERIFIED', scope: 'ordinary app loopback disconnect before commit; not physical WAN offline' },
+ 'installed-version-history': { status: 'NOT VERIFIED', scope: 'native installed tuple and retained initial history; not stale-history recovery' },
+ 'key-management-discoverability': { status: 'NOT VERIFIED', scope: 'ordinary app Keys Manage Keys entry and return' },
+ 'unused-key-and-pin-ui': { status: 'NOT VERIFIED', scope: 'unused Mobile Key delete cancel wrong PIN and cold persistence; not live-Vault references or physical biometrics' },
+ };
+ const samples = metadata.product_ui?.samples;
+ if (metadata.product_ui?.status === 'PASS' && metadata.product_ui.requested_samples === 5 &&
+ Array.isArray(samples) && samples.length === 5 && samples.every((sample, index) =>
+ sample.sample === index + 1 && sample.status === 'PASS' && sample.create_new_app_calls === 1 &&
+ sample.visible_wallet_count_before_relaunch === 1 && sample.visible_wallet_count_after_relaunch === 1 &&
+ ['startup_to_passcode_ms', 'start_new_to_ready_ms'].every(key =>
+ Number.isFinite(sample.raw_durations?.[key]) && sample.raw_durations[key] >= 0))) {
+ checks['five-product-observations'].status = 'PASS';
+ if (samples.every(sample => sample.installed_version_header_and_initial_history === 'PASS'))
+ checks['installed-version-history'].status = 'PASS';
+ if (samples.every(sample => sample.key_management_entry_and_exit === 'PASS'))
+ checks['key-management-discoverability'].status = 'PASS';
+ }
+ const retry = metadata.product_ui?.controlled_disconnect_retry;
+ if (retry?.status === 'PASS' && retry.scenario === 'CONTROLLED_DISCONNECT_BEFORE_COMMIT_NOT_WAN_OFFLINE' &&
+ retry.performance_sample === false && retry.create_new_app_calls === 2 &&
+ retry.transport_requests_dropped_without_commit === 1 && retry.acknowledged_create_responses === 1 &&
+ retry.unexpected_create_attempts === 0 && retry.visible_wallet_count_after_relaunch === 1)
+ checks['controlled-setup-disconnect-retry'].status = 'PASS';
+ const key = metadata.product_ui?.key_management_ui;
+ if (key?.status === 'PASS' && key.entrypoint === 'index.js' && key.network === 'TESTNET' &&
+ key.scenario === 'UNUSED_MOBILE_KEY_UI_DELETE_AND_NATIVE_PIN' && key.new_account_requests_during_key_flow === 0 &&
+ key.visible_eligible_keys_after_deletion === 0 && key.unrelated_visible_wallet_count_after_relaunch === 1)
+ checks['unused-key-and-pin-ui'].status = 'PASS';
+ const parent = acceptance({ trusted: checks['native-build'].status === 'PASS' && checks.startup.status === 'PASS' &&
+ checks['native-storage'].status === 'PASS', ios: 'success', android: 'success' });
+ const cases = REQUIRED.map(id => ({ id, status: parent.cases.find(item => item.id === id)?.status ?? 'NOT IMPLEMENTED' }));
+ Object.assign(checks, publicCompanionChecks(metadata, platform));
+ // Parent obligations remain explicit. Scoped companion UI does not establish
+ // private bytes, protocol/account isolation, WAN offline, recovery or a budget.
+ return { cases, executed_checks: checks };
+}
+
+async function collect(github, context, request, output, readZip, { pinReader } = {}) {
+ fs.rmSync(path.join(output, 'keeper-canonical-native-attestation.json'), { force: true });
+ const { run } = await origin(github, context, request, { pinReader });
+ await platformJobs(github, context, request, run);
+ const page = (await github.rest.actions.listWorkflowRunArtifacts({ ...context.repo, run_id: request.runId, per_page: 100 })).data;
+ demand(page.total_count <= 100 && page.total_count === page.artifacts?.length, 'CANONICAL_ARTIFACT_LIST_INCOMPLETE');
+ const platforms = {};
+ for (const platform of ['IOS', 'ANDROID']) {
+ const matches = page.artifacts.filter(item => item.name === artifactName(platform, request));
+ demand(matches.length === 1, 'CANONICAL_ARTIFACT_MISSING_OR_AMBIGUOUS');
+ const artifact = matches[0];
+ demand(!artifact.expired && artifact.size_in_bytes > 0 && artifact.size_in_bytes <= 1048576 &&
+ artifact.workflow_run?.id === request.runId && artifact.workflow_run.head_sha === request.sourceSha &&
+ /^sha256:[a-f0-9]{64}$/.test(artifact.digest || ''), 'CANONICAL_ARTIFACT_IDENTITY_INVALID');
+ const archive = Buffer.from((await github.rest.actions.downloadArtifact({ ...context.repo,
+ artifact_id: artifact.id, archive_format: 'zip' })).data);
+ demand(archive.length <= 1048576 && archive.length === artifact.size_in_bytes &&
+ `sha256:${digest(archive)}` === artifact.digest, 'CANONICAL_ARTIFACT_DIGEST_INVALID');
+ const current = (await github.rest.actions.getArtifact({ ...context.repo, artifact_id: artifact.id })).data;
+ demand(current.id === artifact.id && current.name === artifact.name && !current.expired &&
+ current.digest === artifact.digest && current.size_in_bytes === artifact.size_in_bytes &&
+ current.workflow_run?.id === request.runId && current.workflow_run.head_sha === request.sourceSha,
+ 'CANONICAL_ARTIFACT_EXPIRED_OR_CHANGED');
+ const raw = readZip(archive);
+ const metadata = JSON.parse(raw.toString('utf8'));
+ platforms[platform] = { conclusion: 'success', artifact_id: artifact.id,
+ receipt_sha256: digest(raw), ...validateMetadata(metadata, request, platform) };
+ }
+ // Recheck after every download; moved heads, new runs or rerun attempts invalidate this collector.
+ await origin(github, context, request, { pinReader });
+ const commit = (await github.rest.git.getCommit({ ...context.repo, commit_sha: request.sourceSha })).data;
+ demand(commit.sha === request.sourceSha && SHA.test(commit.tree?.sha || ''), 'CANONICAL_SOURCE_TREE_UNVERIFIED');
+ const complete = Object.values(platforms).every(item => item.cases.length === REQUIRED.length &&
+ item.cases.every(test => test.status === 'PASS') && Object.values(item.executed_checks).every(test => test.status === 'PASS'));
+ const result = { schema: 1, kind: 'keeper-canonical-native', repository: REPOSITORY,
+ source_sha: request.sourceSha, source_tree: commit.tree.sha, workflow_sha: request.workflowSha,
+ workflow_path: WORKFLOW, run_id: request.runId, run_attempt: request.attempt,
+ selected_route: 'canonical-hosted-native', platforms, feature_matrix_complete: complete };
+ fs.mkdirSync(output, { recursive: true });
+ fs.writeFileSync(path.join(output, complete ? 'keeper-canonical-native-attestation.json' :
+ 'keeper-canonical-native-readiness.json'), JSON.stringify(result, null, 2) + '\n');
+ demand(complete, 'CANONICAL_REQUIRED_APP_MATRIX_INCOMPLETE');
+ return result;
+}
+
+function readMetadataZip(archive) {
+ const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'keeper-canonical-receipt-'));
+ try {
+ const file = path.join(directory, 'receipt.zip'); fs.writeFileSync(file, archive, { mode: 0o600 });
+ return execFileSync('python3', [path.join(__dirname, 'canonical_metadata.py'), file], { maxBuffer: 524288 });
+ } finally { fs.rmSync(directory, { recursive: true, force: true }); }
+}
+module.exports = { REPOSITORY, REPOSITORY_ID, WORKFLOW, WORKER, APP_ID, requestFromEnvironment,
+ pinReaderFromEnvironment, origin, requiredSteps, platformJobs, validateMetadata, collect,
+ artifactName, attestationName, readMetadataZip };
diff --git a/.github/native/contract-tools/package-lock.json b/.github/native/contract-tools/package-lock.json
new file mode 100644
index 0000000000..255413586f
--- /dev/null
+++ b/.github/native/contract-tools/package-lock.json
@@ -0,0 +1,28 @@
+{
+ "name": "keeper-native-contract-tools",
+ "version": "1.0.0",
+ "lockfileVersion": 3,
+ "requires": true,
+ "packages": {
+ "": {
+ "name": "keeper-native-contract-tools",
+ "version": "1.0.0",
+ "dependencies": {
+ "typescript": "5.0.4"
+ }
+ },
+ "node_modules/typescript": {
+ "version": "5.0.4",
+ "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.0.4.tgz",
+ "integrity": "sha512-cW9T5W9xY37cc+jfEnaUvX91foxtHkza3Nw3wkoF4sSlKn0MONdkdEndig/qPBWXNkmplh3NzayQzCiHM4/hqw==",
+ "license": "Apache-2.0",
+ "bin": {
+ "tsc": "bin/tsc",
+ "tsserver": "bin/tsserver"
+ },
+ "engines": {
+ "node": ">=12.20"
+ }
+ }
+ }
+}
diff --git a/.github/native/contract-tools/package.json b/.github/native/contract-tools/package.json
new file mode 100644
index 0000000000..215add3f49
--- /dev/null
+++ b/.github/native/contract-tools/package.json
@@ -0,0 +1,8 @@
+{
+ "name": "keeper-native-contract-tools",
+ "version": "1.0.0",
+ "private": true,
+ "dependencies": {
+ "typescript": "5.0.4"
+ }
+}
diff --git a/.github/native/credential_arm.js b/.github/native/credential_arm.js
new file mode 100644
index 0000000000..feb36b8ceb
--- /dev/null
+++ b/.github/native/credential_arm.js
@@ -0,0 +1,2 @@
+import { registerFixture } from './credential_fixture';
+registerFixture('arm');
diff --git a/.github/native/credential_fixture.js b/.github/native/credential_fixture.js
new file mode 100644
index 0000000000..c703855e0e
--- /dev/null
+++ b/.github/native/credential_fixture.js
@@ -0,0 +1,26 @@
+// Alternate fixture entrypoint only; ordinary app source is never patched.
+import React, { useEffect, useState } from 'react';
+import { AppRegistry, SafeAreaView, Text } from 'react-native';
+import * as Keychain from 'react-native-keychain';
+import config from 'react-native-config';
+import { Storage } from '../../src/storage';
+import { name as appName } from '../../app.json';
+import { runFixture } from './credential_fixture_core';
+// Selected by the two fixed entry wrappers, never by production app state.
+export function registerFixture(phase) {
+ let attempt;
+ function CredentialFixture() {
+ const [stage, setStage] = useState('running');
+ useEffect(() => {
+ let active = true;
+ if (!attempt) attempt = runFixture({ phase, Keychain, storage: Storage, config,
+ development: __DEV__ }).catch(() => 'failed');
+ attempt.then((value) => { if (active) setStage(value); });
+ return () => { active = false; };
+ }, []);
+ return
+ Keeper disposable credential fixture {stage}
+ ;
+ }
+ AppRegistry.registerComponent(appName, () => CredentialFixture);
+}
diff --git a/.github/native/credential_fixture.yaml b/.github/native/credential_fixture.yaml
new file mode 100644
index 0000000000..37a89a4c14
--- /dev/null
+++ b/.github/native/credential_fixture.yaml
@@ -0,0 +1,11 @@
+appId: ${APP_ID}
+name: Device-only credential fixture phase
+---
+- launchApp
+- extendedWaitUntil:
+ visible:
+ id: credential-fixture-${FIXTURE_STAGE}
+ timeout: 60000
+- assertNotVisible:
+ id: credential-fixture-failed
+- stopApp
diff --git a/.github/native/credential_fixture_core.js b/.github/native/credential_fixture_core.js
new file mode 100644
index 0000000000..b986c35552
--- /dev/null
+++ b/.github/native/credential_fixture_core.js
@@ -0,0 +1,71 @@
+/* CI-only fixture. Secret bytes remain in native Keychain or this process. */
+const BACKUP_SERVICE = 'keeper-ci-malformed-credential-recovery-v1';
+const MALFORMED = '{"keeperCiMalformedCredential":';
+class FixtureFailure extends Error {
+ constructor(code) { super(code); this.code = code; }
+}
+function check(value, code) { if (!value) throw new FixtureFailure(code); }
+function owner(storage) {
+ const root = JSON.parse(storage.getString('persist:root'));
+ const accounts = JSON.parse(root.account).allAccounts;
+ const current = JSON.parse(root.storage).appId;
+ check(Array.isArray(accounts) && accounts.length === 1, 'sole-account-required');
+ const account = accounts[0];
+ check(account.isDefault === true && account.accountIdentifier === '' &&
+ typeof account.appId === 'string' && account.appId.length > 0 &&
+ account.appId === current && typeof account.realmId === 'string' && account.realmId.length > 0 &&
+ typeof account.hash === 'string' && account.hash.length > 0, 'default-owner-required');
+ return { appId: account.appId, realmId: account.realmId, hash: account.hash };
+}
+function validOriginal(value, current, username) {
+ check(value && value.username === username && typeof value.password === 'string', 'credential-required');
+ const parsed = JSON.parse(value.password);
+ check(parsed && parsed.hash === current.hash && typeof parsed.enc_key === 'string' &&
+ parsed.enc_key.length > 0, 'matching-credential-required');
+}
+async function runFixture({ phase, Keychain, storage, config, development }) {
+ check(development === true && config.ENVIRONMENT === 'DEVELOPMENT' &&
+ config.RELAY === 'http://127.0.0.1:8765/' &&
+ config.ENC_KEY_STORAGE_IDENTIFIER === 'KEEPER-HOSTED-DISPOSABLE', 'disposable-build-required');
+ check(phase === 'arm' || phase === 'restore', 'phase-rejected');
+ const current = owner(storage);
+ const defaultOptions = { service: undefined };
+ const backupOptions = { service: BACKUP_SERVICE, accessible: Keychain.ACCESSIBLE.WHEN_UNLOCKED };
+ const username = config.ENC_KEY_STORAGE_IDENTIFIER;
+ if (phase === 'arm') {
+ // Successfully empty is never labelled a read fault or turned into a test account.
+ check((await Keychain.getGenericPassword({ service: BACKUP_SERVICE })) === false, 'backup-already-present');
+ const original = await Keychain.getGenericPassword(defaultOptions);
+ validOriginal(original, current, username);
+ const payload = JSON.stringify({ schema: 1, owner: current,
+ original: { username: original.username, password: original.password } });
+ check(await Keychain.setGenericPassword(username, payload, backupOptions), 'backup-write-failed');
+ const saved = await Keychain.getGenericPassword({ service: BACKUP_SERVICE });
+ check(saved && saved.username === username && saved.password === payload, 'backup-readback-failed');
+ check(await Keychain.setGenericPassword(username, MALFORMED,
+ { ...defaultOptions, accessible: Keychain.ACCESSIBLE.WHEN_UNLOCKED }), 'malformed-write-failed');
+ const malformed = await Keychain.getGenericPassword(defaultOptions);
+ check(malformed && malformed.username === username && malformed.password === MALFORMED,
+ 'malformed-readback-failed');
+ return 'armed';
+ }
+ const saved = await Keychain.getGenericPassword({ service: BACKUP_SERVICE });
+ check(saved && saved.username === username, 'backup-required');
+ const payload = JSON.parse(saved.password);
+ check(payload && payload.schema === 1 && JSON.stringify(payload.owner) === JSON.stringify(current),
+ 'backup-owner-mismatch');
+ validOriginal(payload.original, current, username);
+ const malformed = await Keychain.getGenericPassword(defaultOptions);
+ check(malformed && malformed.username === username && malformed.password === MALFORMED,
+ 'restore-source-changed');
+ check(await Keychain.setGenericPassword(payload.original.username, payload.original.password,
+ { ...defaultOptions, accessible: Keychain.ACCESSIBLE.WHEN_UNLOCKED }), 'restore-write-failed');
+ const restored = await Keychain.getGenericPassword(defaultOptions);
+ check(restored && restored.username === payload.original.username &&
+ restored.password === payload.original.password, 'restore-readback-failed');
+ check(await Keychain.resetGenericPassword({ service: BACKUP_SERVICE }), 'backup-cleanup-failed');
+ check((await Keychain.getGenericPassword({ service: BACKUP_SERVICE })) === false,
+ 'backup-cleanup-readback-failed');
+ return 'restored';
+}
+module.exports = { BACKUP_SERVICE, MALFORMED, FixtureFailure, runFixture };
diff --git a/.github/native/credential_metro.cjs b/.github/native/credential_metro.cjs
new file mode 100644
index 0000000000..b9c2f3686e
--- /dev/null
+++ b/.github/native/credential_metro.cjs
@@ -0,0 +1,21 @@
+// Only the owned hosted runner starts this config, while the ordinary app is stopped.
+const path = require('node:path');
+const base = require('../../metro.config');
+const phase = process.env.KEEPER_CREDENTIAL_FIXTURE_PHASE;
+if (!['arm', 'restore'].includes(phase)) throw new Error('CREDENTIAL_FIXTURE_PHASE_REQUIRED');
+const enhance = base.server?.enhanceMiddleware;
+module.exports = {
+ ...base,
+ projectRoot: path.resolve(__dirname, '../..'),
+ server: {
+ ...base.server,
+ enhanceMiddleware(middleware, server) {
+ const inner = enhance ? enhance(middleware, server) : middleware;
+ return (req, res, next) => {
+ req.url = req.url.replace(/^\/index\.(bundle|map)(?=\?|$)/,
+ `/.github/native/credential_${phase}.$1`);
+ return inner(req, res, next);
+ };
+ },
+ },
+};
diff --git a/.github/native/credential_restore.js b/.github/native/credential_restore.js
new file mode 100644
index 0000000000..714e28e026
--- /dev/null
+++ b/.github/native/credential_restore.js
@@ -0,0 +1,2 @@
+import { registerFixture } from './credential_fixture';
+registerFixture('restore');
diff --git a/.github/native/driver_diagnosis.py b/.github/native/driver_diagnosis.py
new file mode 100644
index 0000000000..ad7db34b7f
--- /dev/null
+++ b/.github/native/driver_diagnosis.py
@@ -0,0 +1,403 @@
+#!/usr/bin/env python3
+"""Setup-only iOS driver diagnosis; export fixed facts, never private log text.
+
+This deliberately keeps the pinned Maestro and existing hierarchy launch path.
+There is no Keeper install/build, dependency install, functional correction or
+timeout change. Capture happens before hosted_native.driver deletes its device.
+"""
+
+import hashlib
+import http.client
+import io
+import json
+from concurrent.futures import ThreadPoolExecutor, TimeoutError as FutureTimeoutError
+import os
+from pathlib import Path
+import plistlib
+import re
+import socket
+import subprocess
+import sys
+import time
+import zipfile
+
+import hosted_native as native
+
+
+LIMIT = 1024 * 1024
+POLL_SNAPSHOT_SECONDS = 60
+RUNNER_ID = 'dev.mobile.maestro-driver-iosUITests.xctrunner'
+RUNNER_NAME = 'maestro-driver-iosUITests-Runner'
+CATEGORIES = {
+ 'DYLD_LIBRARY_MISSING': r'library not loaded:|reason: tried:|image not found',
+ 'DYLD_SYMBOL_MISSING': r'symbol not found:|symbol missing|missing symbol',
+ 'DYLD_INCOMPATIBLE_LIBRARY': r'incompatible library version|incompatible architecture|wrong architecture',
+ 'DYLD_LIBRPAC_REFERENCE': r'library not loaded:.*librpac|reason: tried:.*librpac',
+ 'DYLD_SWIFT_COMPATIBILITY_REFERENCE': r'library not loaded:.*swiftcompatibility|reason: tried:.*swiftcompatibility',
+ 'TEST_BUNDLE_LOAD_FAILED': r'failed to load (?:the )?test bundle|could not load (?:the )?test bundle|bundle.*couldn.t be loaded',
+ 'TEST_RUNNER_LAUNCH_FAILED': r'failed to launch|could not launch|application failed to launch|failed to start test runner',
+ 'TEST_RUNNER_INSTALL_FAILED': r'failed to install|could not install|applicationverificationfailed|installd.*error',
+ 'TEST_MANAGER_CONNECTION_FAILED': r'failed to establish.*connection|failed to connect to testmanagerd|lost connection to the test manager',
+ 'TEST_RUNNER_WAIT_TIMEOUT': r'timed out waiting for.*(?:test runner|testing process|testmanagerd)|test runner.*failed to initialize',
+ 'RUNTIME_OR_DEPLOYMENT_MISMATCH': r'requires (?:ios|a newer version)|minimum.*(?:ios|deployment)|built for.*(?:newer|later)|unsupported os version',
+ 'XCODE_COMPONENT_MISSING': r'xcode.*(?:component|platform).*(?:missing|not installed)|unable to find.*(?:platform|runtime)',
+ 'DESTINATION_UNAVAILABLE': r'unable to find a destination|ineligible destinations|device.*(?:not available|unavailable|disconnected)',
+ 'CODE_SIGNING_FAILED': r'code sign(?:ing)?.*(?:failed|error)|invalid code signature|codesign.*failed',
+ 'PERMISSION_DENIED': r'permission denied|operation not permitted|not authorized',
+ 'DISK_SPACE_EXHAUSTED': r'no space left on device|not enough (?:free )?(?:disk )?space',
+ 'PROCESS_CRASHED': r'exception type:|termination reason:|crashed thread:|"exception"\s*:\s*\{|"termination"\s*:\s*\{',
+ 'XCODE_TEST_EXECUTE_FAILED': r'\*\* test execute failed \*\*',
+ 'XCODE_TEST_FAILED': r'\*\* test failed \*\*|testing failed:',
+ 'XCODE_TEST_STARTED': r'test suite .* started|testing started|test case .* started',
+ 'XCODE_TEST_SUCCEEDED': r'\*\* test (?:execute )?succeeded \*\*',
+ 'DRIVER_SERVER_STARTED': r'(?:server|listening).*(?:7001|22087)|server started|server is running',
+ 'XCODE_COMMAND_INVOCATION': r'^Command line invocation:',
+ 'XCODE_USER_DEFAULTS': r'^User defaults from command line:',
+ 'XCODE_DESTINATION_PREPARATION': r'Preparing.*destination|Preparing.*simulator|destination.*prepar',
+ 'XCODE_RESULT_BUNDLE': r'Test session results, code coverage, and logs:',
+ 'LICENSE_NOT_ACCEPTED': r'license.*(?:not accepted|agree)|requires.*license',
+ 'FIRST_LAUNCH_REQUIRED': r'first launch.*(?:required|not complete)|runFirstLaunch|install.*additional components',
+ 'ERROR_DOMAIN_CORE_SIMULATOR': r'com\.apple\.CoreSimulator\.SimError',
+ 'ERROR_DOMAIN_DVT_DEVICE': r'DVTDevice\w*ErrorDomain|DVTiPhoneSimulator\w*ErrorDomain',
+ 'ERROR_DOMAIN_IDE_TEST': r'IDETest\w*ErrorDomain|IDEXCTest\w*ErrorDomain',
+ 'ERROR_DOMAIN_XPC': r'NSXPCConnection\w*ErrorDomain|NSCocoaErrorDomain[^\n]{0,80}Code=409[79]',
+}
+
+STACK_MARKERS = {
+ 'XPC_SYNC_WAIT': r'xpc_connection_send_message_with_reply_sync',
+ 'MACH_WAIT': r'mach_msg|mach_msg2_trap',
+ 'DISPATCH_WAIT': r'dispatch_sync|dispatch_semaphore_wait|dispatch_group_wait',
+ 'CORE_SIMULATOR': r'CoreSimulator|SimDevice|SimServiceContext',
+ 'CORE_DEVICE': r'CoreDevice|CoreDeviceService',
+ 'DVT_DEVICE': r'DVTDevice|DVTiPhoneSimulator|DVTPlatform',
+ 'DVT_PLUGIN': r'DVTPlugIn|DVTPlugInManager',
+ 'IDE_TEST': r'IDETest|IDEXCTest|XCTest',
+ 'DEVICE_INSTALL': r'installApplication|installApp|installBundle',
+ 'DESTINATION_LOOKUP': r'findDestination|resolveDestination|availableDestinations|eligibleDestinations',
+ 'LOCK_WAIT': r'__psynch_mutexwait|__ulock_wait|pthread_mutex_lock',
+}
+
+
+def classify(payload):
+ return [name for name, pattern in CATEGORIES.items()
+ if re.search(pattern, payload, re.IGNORECASE | re.MULTILINE)]
+
+
+def safe_error(error):
+ return type(error).__name__ if type(error).__name__ in {
+ 'OSError', 'FileNotFoundError', 'PermissionError', 'TimeoutExpired',
+ 'ValueError', 'TypeError', 'KeyError', 'BadZipFile', 'InvalidFileException',
+ 'ConnectionRefusedError', 'TimeoutError', 'RemoteDisconnected',
+ } else 'OTHER_ERROR'
+
+
+def bounded(path):
+ if path.is_symlink() or not path.resolve().is_relative_to(native.PRIVATE.resolve()):
+ raise ValueError('Expected a private regular log.')
+ size = path.stat().st_size
+ with path.open('rb') as source:
+ payload = source.read(LIMIT)
+ return payload.decode('utf-8', errors='replace'), {
+ 'bytes': size, 'prefix_bytes': len(payload), 'truncated': size > LIMIT,
+ 'prefix_sha256': hashlib.sha256(payload).hexdigest(),
+ 'categories': classify(payload.decode('utf-8', errors='replace')),
+ }
+
+
+def capture(args, label, timeout=20):
+ """Keep output private; return bounded text only to in-process classifiers."""
+ path = native.PRIVATE / ('driver-diagnosis-' + label + '.log')
+ result = {'label': label}
+ try:
+ with path.open('wb') as output:
+ proc = subprocess.Popen(args, stdout=output, stderr=subprocess.STDOUT,
+ start_new_session=True)
+ try:
+ result['exit_code'] = proc.wait(timeout=timeout)
+ except subprocess.TimeoutExpired:
+ import signal
+ os.killpg(proc.pid, signal.SIGKILL)
+ proc.wait()
+ result['exit_code'] = 124
+ payload, facts = bounded(path)
+ result.update(facts)
+ return payload, result
+ except Exception as error:
+ result['error_type'] = safe_error(error)
+ return '', result
+
+
+def numeric(value):
+ value = str(value)
+ return value if re.fullmatch(r'\d+(?:\.\d+){0,3}', value) else None
+
+
+def version(value):
+ return tuple(int(piece) for piece in value.split('.')) if value else ()
+
+
+def process_inventory_known(payload, result):
+ rows = [line for line in payload.splitlines() if line.strip()]
+ return (bool(rows) and result.get('exit_code') == 0 and not result.get('truncated', False) and
+ all(re.fullmatch(r'\s*\d+\s+\S+\s+\S.*', line) for line in rows))
+
+
+def bundled_runner(metadata=None):
+ """Read exact checksum-verified release JAR metadata without extracting code."""
+ jars = list((native.PRIVATE / 'maestro').rglob('maestro-ios-driver.jar'))
+ if len(jars) != 1:
+ raise ValueError('Expected one pinned iOS driver JAR.')
+ result = {'jar_sha256': hashlib.sha256(jars[0].read_bytes()).hexdigest(), 'bundles': []}
+ with zipfile.ZipFile(jars[0]) as jar:
+ name = 'driver-iPhoneSimulator/Debug-iphonesimulator/maestro-driver-iosUITests-Runner.zip'
+ if jar.getinfo(name).file_size > 64 * 1024 * 1024:
+ raise ValueError('Unexpected bundled runner size.')
+ with zipfile.ZipFile(io.BytesIO(jar.read(name))) as runner:
+ names = {
+ 'runner': RUNNER_NAME + '.app/Info.plist',
+ 'test_bundle': RUNNER_NAME + '.app/PlugIns/maestro-driver-iosUITests.xctest/Info.plist',
+ }
+ for kind, name in names.items():
+ if runner.getinfo(name).file_size > LIMIT:
+ raise ValueError('Unexpected bundled plist size.')
+ data = plistlib.loads(runner.read(name))
+ sdk = re.fullmatch(r'iphonesimulator(\d+(?:\.\d+){0,2})(?:\.internal)?',
+ str(data.get('DTSDKName', '')))
+ result['bundles'].append({
+ 'kind': kind, 'xcode_numeric': numeric(data.get('DTXcode')),
+ 'sdk_version': sdk.group(1) if sdk else None,
+ 'minimum_os_version': numeric(data.get('MinimumOSVersion')),
+ })
+ selected_sdk = numeric((metadata if metadata is not None else native.read()).get('toolchain', {}).get('sdk'))
+ result['selected_sdk_version'] = selected_sdk
+ for item in result['bundles']:
+ item['built_with_newer_sdk_than_selected'] = (
+ version(item['sdk_version']) > version(selected_sdk)) if selected_sdk and item['sdk_version'] else None
+ item['minimum_os_exceeds_selected_sdk'] = (
+ version(item['minimum_os_version']) > version(selected_sdk)) if selected_sdk and item['minimum_os_version'] else None
+ return result
+
+
+def baseline(device):
+ """Check existing simulator app-service readiness before Maestro touches it."""
+ facts = {'scope': 'Read-only simulator controls before hierarchy command.', 'commands': []}
+ ps, result = capture(['ps', '-axo', 'pid=,stat=,args='], 'baseline-processes', 10)
+ facts['commands'].append(result)
+ frontend = [line for line in ps.splitlines() if '/Simulator.app/Contents/MacOS/Simulator' in line]
+ known = process_inventory_known(ps, result)
+ facts['simulator_frontend_process_count'] = len(frontend) if known else None
+ selected = os.environ.get('DEVELOPER_DIR', '')
+ # Export only a boolean comparison, never the process arguments or path.
+ facts['selected_simulator_frontend_running'] = any(
+ selected + '/Applications/Simulator.app/Contents/MacOS/Simulator' in line for line in frontend
+ ) if selected and known else None
+ for args, label in [
+ (['xcrun', 'simctl', 'listapps', device], 'baseline-listapps'),
+ (['xcrun', 'simctl', 'get_app_container', device, 'com.apple.Preferences', 'app'],
+ 'baseline-preferences-container'),
+ ]:
+ _, result = capture(args, label, 10)
+ facts['commands'].append(result)
+ return facts
+
+
+def collect(device, metadata=None):
+ facts = {'scope': 'Before owned simulator cleanup; driver setup only.',
+ 'collection_errors': [], 'commands': [], 'logs': []}
+ metadata = metadata if metadata is not None else native.read()
+
+ def command(args, label, timeout=20):
+ payload, result = capture(args, label, timeout)
+ facts['commands'].append(result)
+ return payload, result
+
+ try:
+ facts['bundled_runner'] = bundled_runner(metadata)
+ except Exception as error:
+ facts['collection_errors'].append({'stage': 'bundled_runner', 'error_type': safe_error(error)})
+
+ ps, process_result = command(['ps', '-axo', 'pid=,stat=,args='], 'processes')
+ owned = [line for line in ps.splitlines()
+ if 'xcodebuild' in line and device in line and 'test-without-building' in line]
+ processes_known = process_inventory_known(ps, process_result)
+ facts['owned_xcodebuild_process_count'] = len(owned) if processes_known else None
+ facts['owned_xcodebuild_alive'] = bool(owned) if processes_known else None
+ facts['owned_xcodebuild_zombie_count'] = sum(
+ len(line.split(None, 2)) >= 2 and 'Z' in line.split(None, 2)[1] for line in owned) if processes_known else None
+ pids = [int(line.split()[0]) for line in owned if re.match(r'^\s*\d+\s', line)] if processes_known else []
+ # Sample only the exact owned-device xcodebuild; never all runner processes.
+ if len(pids) == 1:
+ sample_path = native.PRIVATE / 'driver-xcodebuild.sample'
+ command(['sample', str(pids[0]), '3', '1', '-file', str(sample_path)], 'xcodebuild-sample', 15)
+ try:
+ payload, result = bounded(sample_path)
+ result['stack_categories'] = [name for name, pattern in STACK_MARKERS.items()
+ if re.search(pattern, payload, re.IGNORECASE)]
+ facts['xcodebuild_sample'] = result
+ except Exception as error:
+ facts['collection_errors'].append({'stage': 'xcodebuild_sample', 'error_type': safe_error(error)})
+
+ command(['xcodebuild', '-checkFirstLaunchStatus'], 'xcode-first-launch-status', 20)
+ command(['xcrun', 'simctl', 'spawn', device, '/usr/bin/true'], 'simulator-spawn-control', 10)
+ command(['xcrun', 'simctl', 'listapps', device], 'simulator-listapps', 20)
+ command(['log', 'show', '--style', 'compact', '--last', '5m', '--predicate',
+ 'process == "xcodebuild" OR process == "CoreSimulatorService"'], 'host-xcode-simulator-events', 25)
+
+ _, container = command(['xcrun', 'simctl', 'get_app_container', device, RUNNER_ID, 'app'], 'runner-installed')
+ # Generic simctl failures do not establish that an app is absent.
+ facts['runner_installed'] = True if container.get('exit_code') == 0 else None
+ launchctl, launch_result = command(['xcrun', 'simctl', 'spawn', device, 'launchctl', 'list'], 'runner-running')
+ runner_lines = [line for line in launchctl.splitlines() if RUNNER_ID in line]
+ launch_rows = [line for line in launchctl.splitlines() if line.strip()]
+ launch_known = (bool(launch_rows) and launch_result.get('exit_code') == 0 and not launch_result.get('truncated', False) and
+ all(re.fullmatch(r'\s*(?:\d+|-)\s+-?\d+\s+\S+\s*', line)
+ or re.fullmatch(r'\s*PID\s+Status\s+Label\s*', line) for line in launch_rows))
+ facts['runner_launchctl_entries'] = len(runner_lines) if launch_known else None
+ facts['runner_running'] = any(re.match(r'^\s*[1-9]\d*\s', line) for line in runner_lines) if launch_known else None
+ facts['runner_last_exit_codes'] = [int(match.group(1)) for line in runner_lines
+ if (match := re.match(r'^\s*(?:\d+|-)\s+(-?\d+)\s', line))][:4] if launch_known else []
+
+ paths = []
+ for index, entry in enumerate(metadata['commands'], 1):
+ if entry['label'] == 'Check disposable iOS driver readiness':
+ paths.append(('hierarchy-command', native.PRIVATE / ('command-%03d.log' % index)))
+ state = native.PRIVATE / 'maestro-preflight-state' / 'maestro' / 'tests'
+ for pattern, kind in [('**/maestro.log', 'maestro'), ('**/xctest_runner_*.log', 'xctest')]:
+ paths.extend((kind, path) for path in sorted(state.glob(pattern))[:4])
+ port = None
+ for kind, path in paths[:9]:
+ try:
+ payload, result = bounded(path)
+ facts['logs'].append({'kind': kind, **result})
+ match = re.search(r'Running XcUITest with `xcodebuild test-without-building` with (\d+) and config:', payload)
+ if match and 0 < int(match.group(1)) <= 65535:
+ port = int(match.group(1))
+ except Exception as error:
+ facts['collection_errors'].append({'stage': kind, 'error_type': safe_error(error)})
+ facts['driver_port'] = port
+ if port is not None:
+ try:
+ with socket.create_connection(('127.0.0.1', port), timeout=2):
+ facts['driver_tcp_connects'] = True
+ except OSError:
+ facts['driver_tcp_connects'] = False
+ conn = http.client.HTTPConnection('127.0.0.1', port, timeout=3)
+ try:
+ conn.request('GET', '/status')
+ facts['driver_status_http_code'] = conn.getresponse().status
+ except Exception as error:
+ facts['driver_status_error_type'] = safe_error(error)
+ finally:
+ conn.close()
+
+ predicate = 'process == "' + RUNNER_NAME + '" OR process == "testmanagerd"'
+ command(['xcrun', 'simctl', 'spawn', device, 'log', 'show', '--style', 'compact',
+ '--last', '5m', '--predicate', predicate], 'simulator-runner-events', 25)
+ crash_dirs = [Path.home() / 'Library/Logs/DiagnosticReports',
+ Path.home() / 'Library/Developer/CoreSimulator/Devices' / device / 'data/Library/Logs/CrashReporter']
+ crash_count = 0
+ for directory in crash_dirs:
+ if not directory.is_dir() or directory.is_symlink():
+ continue
+ for path in sorted(directory.glob('*'), key=lambda item: item.name):
+ if crash_count >= 8:
+ break
+ if not path.is_file() or path.is_symlink() or not path.name.startswith((RUNNER_NAME, 'testmanagerd', 'xctest')):
+ continue
+ try:
+ if time.time() - path.stat().st_mtime > 600:
+ continue
+ with path.open('rb') as source:
+ payload = source.read(LIMIT)
+ facts.setdefault('recent_crash_reports', []).append({
+ 'prefix_bytes': len(payload), 'truncated': path.stat().st_size > LIMIT,
+ 'categories': classify(payload.decode('utf-8', errors='replace')),
+ })
+ crash_count += 1
+ except Exception as error:
+ facts['collection_errors'].append({'stage': 'crash_report', 'error_type': safe_error(error)})
+ return facts
+
+
+def run():
+ if native.PLATFORM != 'IOS' or os.environ.get('KEEPER_DIAGNOSTIC') != 'true':
+ raise ValueError('Expected explicit iOS diagnostic environment.')
+ os.environ['MAESTRO_CLI_NO_ANALYTICS'] = '1'
+ native.record()
+ native.install_maestro()
+ original = native.command
+
+ def observed(args, label, **kwargs):
+ if label != 'Check disposable iOS driver readiness':
+ return original(args, label, **kwargs)
+ # Device is supplied by the unchanged owned-device driver path.
+ device = args[args.index('--device') + 1]
+ if not re.fullmatch(r'[A-Fa-f0-9]{8}(?:-[A-Fa-f0-9]{4}){3}-[A-Fa-f0-9]{12}', device):
+ raise ValueError('Expected owned simulator UUID.')
+ metadata = native.read()
+ # command() appends exactly this entry when its worker starts. Keep the
+ # index locally so collection never races its metadata file writes.
+ metadata['commands'].append({'label': label})
+ baseline_facts = {'collection_errors': []}
+ try:
+ baseline_facts = baseline(device)
+ except Exception as error:
+ baseline_facts['collection_errors'].append({'stage': 'baseline', 'error_type': safe_error(error)})
+ facts = {'collection_errors': []}
+
+ def snapshot(phase, future):
+ started_while_running = not future.done()
+ try:
+ result = collect(device, metadata)
+ except Exception as error:
+ result = {'collection_errors': [{'stage': 'pre_cleanup', 'error_type': safe_error(error)}]}
+ result.update(snapshot_phase=phase,
+ hierarchy_running_before_collection=started_while_running,
+ hierarchy_running_after_collection=not future.done())
+ return result
+
+ primary_failed = False
+ try:
+ with ThreadPoolExecutor(max_workers=1) as executor:
+ future = executor.submit(original, args, label, **kwargs)
+ try:
+ result = future.result(timeout=POLL_SNAPSHOT_SECONDS)
+ except FutureTimeoutError:
+ # Sample the owned xcodebuild before Maestro's exception
+ # cleanup can delete its test products and derived data.
+ facts = snapshot('DURING_DRIVER_POLLING' if not future.done() else 'AFTER_DRIVER_COMMAND', future)
+ return future.result()
+ except Exception:
+ facts = snapshot('AFTER_DRIVER_COMMAND', future)
+ raise
+ else:
+ facts = snapshot('AFTER_DRIVER_COMMAND', future)
+ return result
+ except Exception:
+ primary_failed = True
+ raise
+ finally:
+ # Executor exit waits for the bounded original command. Persist only
+ # now, after command() has finished its own metadata writes.
+ facts['baseline'] = baseline_facts
+ try:
+ data = native.read()
+ data['driver_diagnosis'] = facts
+ native.save(data)
+ except Exception:
+ if not primary_failed:
+ raise RuntimeError('Driver diagnostic receipt failed.') from None
+
+ native.command = observed
+ try:
+ native.run_phase('driver')
+ finally:
+ native.command = original
+
+
+if __name__ == '__main__':
+ try:
+ run()
+ except Exception:
+ print('iOS driver diagnosis failed; inspect fixed metadata categories.', file=sys.stderr)
+ sys.exit(1)
diff --git a/.github/native/history_fixture.yaml b/.github/native/history_fixture.yaml
new file mode 100644
index 0000000000..21a0a24ecf
--- /dev/null
+++ b/.github/native/history_fixture.yaml
@@ -0,0 +1,9 @@
+appId: ${APP_ID}
+name: Controlled native history fixture stage
+---
+- launchApp
+- extendedWaitUntil:
+ visible:
+ id: ${EXPECTED_FIXTURE_ID}
+ timeout: 60000
+- stopApp
diff --git a/.github/native/history_product.yaml b/.github/native/history_product.yaml
new file mode 100644
index 0000000000..ee45e8e12f
--- /dev/null
+++ b/.github/native/history_product.yaml
@@ -0,0 +1,47 @@
+# Normal index.js. Controlled Realm history fixture; account version is unchanged.
+appId: ${APP_ID}
+name: Current history observation after ordinary cold login
+---
+- launchApp
+- extendedWaitUntil:
+ visible: Enter your passcode
+ timeout: 60000
+- repeat:
+ times: 4
+ commands:
+ - tapOn:
+ id: key_1
+- tapOn: Proceed
+- extendedWaitUntil:
+ visible:
+ id: home_visible_wallet_count_1
+ timeout: 60000
+- assertVisible: Mobile Wallet
+- tapOn:
+ id: home_tab_more
+- scrollUntilVisible:
+ element:
+ id: btn_setting_App Settings
+ direction: DOWN
+ timeout: 30000
+- tapOn:
+ id: btn_setting_App Settings
+- extendedWaitUntil:
+ visible:
+ id: btn_setting_Version History
+ timeout: 30000
+- tapOn:
+ id: btn_setting_Version History
+- extendedWaitUntil:
+ visible:
+ id: text_installedAppVersionLabel
+ text: Installed app version
+ timeout: 30000
+- assertVisible:
+ id: text_installedAppVersion
+ text: ${EXPECTED_INSTALLED_REGEX}
+- assertVisible: Current installation observed
+- assertVisible:
+ text: ${EXPECTED_HISTORY_REGEX}
+- assertNotVisible: Upgraded from.*
+- stopApp
diff --git a/.github/native/history_restore.js b/.github/native/history_restore.js
new file mode 100644
index 0000000000..dde0f75ca1
--- /dev/null
+++ b/.github/native/history_restore.js
@@ -0,0 +1,2 @@
+import { registerFixture } from './version_history_fixture';
+registerFixture('restore');
diff --git a/.github/native/history_restore_metro.cjs b/.github/native/history_restore_metro.cjs
new file mode 100644
index 0000000000..b1cfff05c2
--- /dev/null
+++ b/.github/native/history_restore_metro.cjs
@@ -0,0 +1,15 @@
+// Fixed CI-only entrypoint. Never selected by the ordinary production runner.
+const path = require('node:path');
+const base = require('../../metro.config');
+const enhance = base.server?.enhanceMiddleware;
+module.exports = {
+ ...base, projectRoot: path.resolve(__dirname, '../..'),
+ server: { ...base.server, enhanceMiddleware(middleware, server) {
+ const inner = enhance ? enhance(middleware, server) : middleware;
+ return (req, res, next) => {
+ req.url = req.url.replace(/^\/index\.(bundle|map)(?=\?|$)/,
+ '/.github/native/history_restore.$1');
+ return inner(req, res, next);
+ };
+ } },
+};
diff --git a/.github/native/history_seed_empty.js b/.github/native/history_seed_empty.js
new file mode 100644
index 0000000000..7ca99cd608
--- /dev/null
+++ b/.github/native/history_seed_empty.js
@@ -0,0 +1,2 @@
+import { registerFixture } from './version_history_fixture';
+registerFixture('seed_empty');
diff --git a/.github/native/history_seed_empty_metro.cjs b/.github/native/history_seed_empty_metro.cjs
new file mode 100644
index 0000000000..ee52bcbecd
--- /dev/null
+++ b/.github/native/history_seed_empty_metro.cjs
@@ -0,0 +1,15 @@
+// Fixed CI-only entrypoint. Never selected by the ordinary production runner.
+const path = require('node:path');
+const base = require('../../metro.config');
+const enhance = base.server?.enhanceMiddleware;
+module.exports = {
+ ...base, projectRoot: path.resolve(__dirname, '../..'),
+ server: { ...base.server, enhanceMiddleware(middleware, server) {
+ const inner = enhance ? enhance(middleware, server) : middleware;
+ return (req, res, next) => {
+ req.url = req.url.replace(/^\/index\.(bundle|map)(?=\?|$)/,
+ '/.github/native/history_seed_empty.$1');
+ return inner(req, res, next);
+ };
+ } },
+};
diff --git a/.github/native/history_seed_stale.js b/.github/native/history_seed_stale.js
new file mode 100644
index 0000000000..06b6fe74b2
--- /dev/null
+++ b/.github/native/history_seed_stale.js
@@ -0,0 +1,2 @@
+import { registerFixture } from './version_history_fixture';
+registerFixture('seed_stale');
diff --git a/.github/native/history_seed_stale_metro.cjs b/.github/native/history_seed_stale_metro.cjs
new file mode 100644
index 0000000000..aeca577b73
--- /dev/null
+++ b/.github/native/history_seed_stale_metro.cjs
@@ -0,0 +1,15 @@
+// Fixed CI-only entrypoint. Never selected by the ordinary production runner.
+const path = require('node:path');
+const base = require('../../metro.config');
+const enhance = base.server?.enhanceMiddleware;
+module.exports = {
+ ...base, projectRoot: path.resolve(__dirname, '../..'),
+ server: { ...base.server, enhanceMiddleware(middleware, server) {
+ const inner = enhance ? enhance(middleware, server) : middleware;
+ return (req, res, next) => {
+ req.url = req.url.replace(/^\/index\.(bundle|map)(?=\?|$)/,
+ '/.github/native/history_seed_stale.$1');
+ return inner(req, res, next);
+ };
+ } },
+};
diff --git a/.github/native/history_verify_empty_first.js b/.github/native/history_verify_empty_first.js
new file mode 100644
index 0000000000..f4635c1605
--- /dev/null
+++ b/.github/native/history_verify_empty_first.js
@@ -0,0 +1,2 @@
+import { registerFixture } from './version_history_fixture';
+registerFixture('verify_empty_first');
diff --git a/.github/native/history_verify_empty_first_metro.cjs b/.github/native/history_verify_empty_first_metro.cjs
new file mode 100644
index 0000000000..44e0466a9f
--- /dev/null
+++ b/.github/native/history_verify_empty_first_metro.cjs
@@ -0,0 +1,15 @@
+// Fixed CI-only entrypoint. Never selected by the ordinary production runner.
+const path = require('node:path');
+const base = require('../../metro.config');
+const enhance = base.server?.enhanceMiddleware;
+module.exports = {
+ ...base, projectRoot: path.resolve(__dirname, '../..'),
+ server: { ...base.server, enhanceMiddleware(middleware, server) {
+ const inner = enhance ? enhance(middleware, server) : middleware;
+ return (req, res, next) => {
+ req.url = req.url.replace(/^\/index\.(bundle|map)(?=\?|$)/,
+ '/.github/native/history_verify_empty_first.$1');
+ return inner(req, res, next);
+ };
+ } },
+};
diff --git a/.github/native/history_verify_empty_repeat.js b/.github/native/history_verify_empty_repeat.js
new file mode 100644
index 0000000000..00d02f7610
--- /dev/null
+++ b/.github/native/history_verify_empty_repeat.js
@@ -0,0 +1,2 @@
+import { registerFixture } from './version_history_fixture';
+registerFixture('verify_empty_repeat');
diff --git a/.github/native/history_verify_empty_repeat_metro.cjs b/.github/native/history_verify_empty_repeat_metro.cjs
new file mode 100644
index 0000000000..d940701829
--- /dev/null
+++ b/.github/native/history_verify_empty_repeat_metro.cjs
@@ -0,0 +1,15 @@
+// Fixed CI-only entrypoint. Never selected by the ordinary production runner.
+const path = require('node:path');
+const base = require('../../metro.config');
+const enhance = base.server?.enhanceMiddleware;
+module.exports = {
+ ...base, projectRoot: path.resolve(__dirname, '../..'),
+ server: { ...base.server, enhanceMiddleware(middleware, server) {
+ const inner = enhance ? enhance(middleware, server) : middleware;
+ return (req, res, next) => {
+ req.url = req.url.replace(/^\/index\.(bundle|map)(?=\?|$)/,
+ '/.github/native/history_verify_empty_repeat.$1');
+ return inner(req, res, next);
+ };
+ } },
+};
diff --git a/.github/native/history_verify_restored.js b/.github/native/history_verify_restored.js
new file mode 100644
index 0000000000..03fa848bcd
--- /dev/null
+++ b/.github/native/history_verify_restored.js
@@ -0,0 +1,2 @@
+import { registerFixture } from './version_history_fixture';
+registerFixture('verify_restored');
diff --git a/.github/native/history_verify_restored_metro.cjs b/.github/native/history_verify_restored_metro.cjs
new file mode 100644
index 0000000000..5ff8b87336
--- /dev/null
+++ b/.github/native/history_verify_restored_metro.cjs
@@ -0,0 +1,15 @@
+// Fixed CI-only entrypoint. Never selected by the ordinary production runner.
+const path = require('node:path');
+const base = require('../../metro.config');
+const enhance = base.server?.enhanceMiddleware;
+module.exports = {
+ ...base, projectRoot: path.resolve(__dirname, '../..'),
+ server: { ...base.server, enhanceMiddleware(middleware, server) {
+ const inner = enhance ? enhance(middleware, server) : middleware;
+ return (req, res, next) => {
+ req.url = req.url.replace(/^\/index\.(bundle|map)(?=\?|$)/,
+ '/.github/native/history_verify_restored.$1');
+ return inner(req, res, next);
+ };
+ } },
+};
diff --git a/.github/native/history_verify_stale_first.js b/.github/native/history_verify_stale_first.js
new file mode 100644
index 0000000000..ed24dd862b
--- /dev/null
+++ b/.github/native/history_verify_stale_first.js
@@ -0,0 +1,2 @@
+import { registerFixture } from './version_history_fixture';
+registerFixture('verify_stale_first');
diff --git a/.github/native/history_verify_stale_first_metro.cjs b/.github/native/history_verify_stale_first_metro.cjs
new file mode 100644
index 0000000000..b682b42781
--- /dev/null
+++ b/.github/native/history_verify_stale_first_metro.cjs
@@ -0,0 +1,15 @@
+// Fixed CI-only entrypoint. Never selected by the ordinary production runner.
+const path = require('node:path');
+const base = require('../../metro.config');
+const enhance = base.server?.enhanceMiddleware;
+module.exports = {
+ ...base, projectRoot: path.resolve(__dirname, '../..'),
+ server: { ...base.server, enhanceMiddleware(middleware, server) {
+ const inner = enhance ? enhance(middleware, server) : middleware;
+ return (req, res, next) => {
+ req.url = req.url.replace(/^\/index\.(bundle|map)(?=\?|$)/,
+ '/.github/native/history_verify_stale_first.$1');
+ return inner(req, res, next);
+ };
+ } },
+};
diff --git a/.github/native/history_verify_stale_repeat.js b/.github/native/history_verify_stale_repeat.js
new file mode 100644
index 0000000000..057050ee9a
--- /dev/null
+++ b/.github/native/history_verify_stale_repeat.js
@@ -0,0 +1,2 @@
+import { registerFixture } from './version_history_fixture';
+registerFixture('verify_stale_repeat');
diff --git a/.github/native/history_verify_stale_repeat_metro.cjs b/.github/native/history_verify_stale_repeat_metro.cjs
new file mode 100644
index 0000000000..9c347d3dbc
--- /dev/null
+++ b/.github/native/history_verify_stale_repeat_metro.cjs
@@ -0,0 +1,15 @@
+// Fixed CI-only entrypoint. Never selected by the ordinary production runner.
+const path = require('node:path');
+const base = require('../../metro.config');
+const enhance = base.server?.enhanceMiddleware;
+module.exports = {
+ ...base, projectRoot: path.resolve(__dirname, '../..'),
+ server: { ...base.server, enhanceMiddleware(middleware, server) {
+ const inner = enhance ? enhance(middleware, server) : middleware;
+ return (req, res, next) => {
+ req.url = req.url.replace(/^\/index\.(bundle|map)(?=\?|$)/,
+ '/.github/native/history_verify_stale_repeat.$1');
+ return inner(req, res, next);
+ };
+ } },
+};
diff --git a/.github/native/hosted_native.py b/.github/native/hosted_native.py
new file mode 100644
index 0000000000..dd537e8292
--- /dev/null
+++ b/.github/native/hosted_native.py
@@ -0,0 +1,1259 @@
+#!/usr/bin/env python3
+"""Disposable hosted smoke harness; only allowlisted metadata leaves the runner.
+
+Native and Maestro output stays under RUNNER_TEMP, never in an uploaded glob.
+The gate trusts protected workflow/job provenance, never this writable artifact.
+"""
+
+import hashlib
+import importlib.util
+import json
+import math
+import os
+from pathlib import Path
+import platform
+import re
+import shutil
+import signal
+import subprocess
+import sys
+import tempfile
+import time
+from types import SimpleNamespace
+import urllib.request
+import xml.etree.ElementTree as ET
+
+
+ROOT = Path(__file__).resolve().parents[2]
+PLATFORM = os.environ.get('KEEPER_NATIVE_PLATFORM', '')
+PRIVATE = Path(os.environ.get('RUNNER_TEMP', tempfile.gettempdir())) / 'keeper-native-private'
+EVIDENCE = ROOT / 'artifacts' / 'native' / PLATFORM.lower() / 'metadata.json'
+MAESTRO_VERSION = 'cli-2.11.0'
+MAESTRO_SHA256 = '5384593cb4e7a106489e75a821d157dd43f4e438df6bc308b72e82c685e1283a'
+APP_IDS = {'IOS': 'io.hexawallet.hexakeeper.dev', 'ANDROID': 'io.hexawallet.keeper.development'}
+
+
+def save(data):
+ EVIDENCE.parent.mkdir(parents=True, exist_ok=True)
+ EVIDENCE.write_text(json.dumps(data, indent=2) + '\n')
+
+
+def read():
+ return json.loads(EVIDENCE.read_text())
+
+
+def failure_details(log):
+ """Classify observed tool failures; never return any part of a log line.
+
+ Redaction cannot recognize arbitrary wallet, user or application text. Each
+ result must come from this fixed vocabulary, including the fallback.
+ """
+ categories = (
+ (r'lockfile needs to be updated|could not find compatible versions|^The sandbox is not in sync',
+ 'DEPENDENCY_LOCK_MISMATCH'),
+ (r'no space left on device', 'DISK_SPACE_EXHAUSTED'),
+ (r'command not found', 'REQUIRED_TOOL_UNAVAILABLE'),
+ (r'requires a higher minimum deployment target', 'IOS_DEPLOYMENT_TARGET_UNSUPPORTED'),
+ (r'^e: ', 'KOTLIN_COMPILER_ERROR'),
+ (r'^\[!\]', 'COCOAPODS_ERROR'),
+ (r'^FAILURE:|^A problem occurred|^Execution failed', 'BUILD_FAILURE'),
+ (r'^Could not ', 'DEPENDENCY_OR_TOOL_FAILURE'),
+ (r'\berror:|^error |^> (?!Task\b)|^Caused by:', 'TOOL_ERROR'),
+ )
+ selected = []
+ for raw in log.splitlines():
+ line = re.sub(r'\x1b\[[0-9;]*[A-Za-z]', '', raw).strip()
+ if re.match(r'^\d+\s*\|', line):
+ continue
+ for pattern, category in categories:
+ if re.search(pattern, line, re.IGNORECASE):
+ if category not in selected:
+ selected.append(category)
+ break
+ return selected
+
+
+def maestro_failure_details(log):
+ """Retain only fixed command labels, selectors and tool failure categories."""
+ selected = []
+ for raw in log.splitlines():
+ line = re.sub(r'\x1b\[[0-9;]*[A-Za-z]', '', raw).strip()
+ if line.endswith('FAILED'):
+ if line.startswith(('Launch app', 'Clear state', 'Stop app')) and any(app in line for app in APP_IDS.values()):
+ selected.append('Maestro app launch/stop command FAILED')
+ elif line.startswith(('Assert', 'Wait')) and 'Create a passcode' in line:
+ selected.append('Maestro assertion: Create a passcode visible FAILED')
+ elif line.startswith(('Assert', 'Wait')) and 'Confirm your passcode' in line:
+ selected.append('Maestro assertion: Confirm your passcode state FAILED')
+ elif line.startswith('Tap on'):
+ match = re.search(r'\bkey_[1-4]\b', line)
+ if match:
+ selected.append('Maestro tap %s FAILED' % match.group())
+ elif line.startswith(('Assertion is false:', 'Element not found:')):
+ # Emit only a category and fixed selector; even a first-line suffix
+ # can contain a hierarchy or arbitrary device text.
+ category = 'assertion failed' if line.startswith('Assertion is false:') else 'element not found'
+ for target in ['Create a passcode', 'Confirm your passcode', 'key_1', 'key_2', 'key_3', 'key_4']:
+ if target in line:
+ selected.append('Maestro %s: %s' % (category, target))
+ break
+ elif line.startswith(('Unable to launch app', 'Failed to launch app')):
+ selected.append('Maestro app launch failed')
+ elif line.startswith(('Unable to connect', 'Failed to connect')):
+ selected.append('Maestro connection failed')
+ elif line.startswith('Failed to start'):
+ selected.append('Maestro driver start failed')
+ elif line.startswith(('No devices found', 'No connected devices', 'Unable to find device')):
+ selected.append('Maestro device unavailable')
+ if len(selected) >= 10:
+ break
+ return list(dict.fromkeys(selected))[:10]
+
+
+def android_startup_errors(log):
+ categories = {'AndroidRuntime': 'ANDROID_RUNTIME_ERROR',
+ 'ReactNativeJS': 'REACT_NATIVE_JS_ERROR', 'ReactNative': 'REACT_NATIVE_ERROR'}
+ selected = []
+ for line in log.splitlines():
+ match = re.match(r'^[EF]/(AndroidRuntime|ReactNativeJS|ReactNative)\s*\(\s*\d+\):\s*(.*)', line)
+ if not match:
+ continue
+ tag, message = match.groups()
+ if re.search(r'(?:FATAL EXCEPTION|Caused by:|\b[\w.$]*(?:Exception|Error)\b|'
+ r'Invariant Violation|Unable to load script|Could not)', message):
+ if categories[tag] not in selected:
+ selected.append(categories[tag])
+ return selected
+
+
+def metro_startup_errors(log):
+ selected = []
+ for raw in log.splitlines():
+ line = re.sub(r'\x1b\[[0-9;]*[A-Za-z]', '', raw).strip()
+ if re.match(r'^(?:error\b|(?:Syntax|Type|Reference)Error:|Unable to resolve module)', line, re.IGNORECASE):
+ category = 'METRO_ERROR'
+ for marker, known in [('Unable to resolve module', 'METRO_MODULE_RESOLUTION_ERROR'),
+ ('SyntaxError:', 'METRO_SYNTAX_ERROR'),
+ ('TypeError:', 'METRO_TYPE_ERROR'),
+ ('ReferenceError:', 'METRO_REFERENCE_ERROR')]:
+ if marker.lower() in line.lower():
+ category = known
+ break
+ if category not in selected:
+ selected.append(category)
+ return selected
+
+
+def metro_startup_progress(log):
+ # Metro's TerminalReporter uses the same bare BUNDLE line for done and
+ # failed builds. Count observed markers without inferring completion.
+ lines = [re.sub(r'\x1b\[[0-9;]*[A-Za-z]', '', line).strip() for line in log.splitlines()]
+ bundles = sum(bool(re.match(r'^BUNDLE\s', line)) for line in lines)
+ prebundles = sum(bool(re.match(r'^PREBUNDLE\s', line)) for line in lines)
+ return {'bundle_marker_observed': bundles > 0, 'bundle_marker_count': bundles,
+ 'prebundle_marker_count': prebundles}
+
+
+def private_log_prefix(path):
+ """Read launch-time output, discarding a partially truncated final record."""
+ limit = 1024 * 1024
+ with path.open('rb') as source:
+ payload = source.read(limit + 1)
+ truncated = len(payload) > limit
+ payload = payload[:limit]
+ if truncated:
+ payload = payload.rsplit(b'\n', 1)[0] + b'\n' if b'\n' in payload else b''
+ return payload.decode(errors='replace'), truncated
+
+
+def ios_startup_diagnostics(payload, executable):
+ if not re.fullmatch(r'[A-Za-z0-9_][A-Za-z0-9_.-]*', executable):
+ raise ValueError('Unsafe iOS executable selector.')
+ # log(1) compact: ISO timestamp, abbreviated type, process[PID:TID], message.
+ # Only prefixed own-process records qualify; never retain continuation lines.
+ pattern = re.compile(r'^\d{4}-\d{2}-\d{2}[ T]\d{2}:\d{2}:\d{2}(?:\.\d+)?'
+ r'(?:[+-]\d{2}:?\d{2}|Z)?\s+(\S+)\s+'
+ r'([A-Za-z0-9_.-]+)\[\d+:[A-Fa-f0-9x]+\]\s+(.*)$')
+ selected = []
+ matched = 0
+ for line in payload.splitlines():
+ match = pattern.match(line)
+ if not match:
+ continue
+ severity, process, message = match.groups()
+ if process != executable:
+ continue
+ matched += 1
+ if severity.lower() in ['e', 'f', 'er', 'ft', 'error', 'fault'] or re.search(
+ r'(?:\b(?:error|exception|fatal)\b|\b[\w.$]*(?:Exception|Error)\b)',
+ message, re.IGNORECASE):
+ if not selected:
+ selected.append('IOS_STARTUP_ERROR')
+ return {'format': 'compact', 'matching_process_records': matched,
+ 'errors': selected}
+
+
+def startup_hierarchy_signals(directory):
+ """Classify fixed public startup selectors; never export hierarchy content."""
+ # Maestro cli-2.11.0 writes standalone TreeNode snapshots in this layout.
+ flags = ['createPIN', 'confirmPIN', 'RNredbox', 'noScriptURL',
+ 'developmentServerError', 'unableLoadScript']
+ result = {flag: False for flag in flags}
+ result.update({'snapshot_count': 0, 'parse_error_types': []})
+ redbox_ids = {'redbox-error', 'redbox-dismiss', 'redbox-reload', 'rn_redbox_stack',
+ 'rn_redbox_dismiss_button', 'rn_redbox_reload_button', 'catalyst_redbox_title'}
+ fixed_messages = {'noScriptURL': 'No script URL provided.',
+ 'developmentServerError': 'Could not connect to development server.',
+ 'unableLoadScript': 'Unable to load script.'}
+ for index, path in enumerate(directory.glob('**/screen-hierarchy/step-*.json')):
+ try:
+ if index >= 8:
+ raise ValueError('Hierarchy snapshot count exceeded limit.')
+ result['snapshot_count'] += 1
+ if path.is_symlink() or not path.resolve().is_relative_to(directory.resolve()):
+ raise ValueError('Hierarchy snapshot must remain in private output.')
+ with path.open('rb') as source:
+ payload = source.read(1024 * 1024 + 1)
+ if len(payload) > 1024 * 1024:
+ raise ValueError('Hierarchy snapshot exceeded byte limit.')
+ pending = [json.loads(payload)]
+ snapshot = {flag: False for flag in flags}
+ nodes = 0
+ while pending:
+ node = pending.pop()
+ nodes += 1
+ if nodes > 10000:
+ raise ValueError('Hierarchy snapshot exceeded node limit.')
+ if not isinstance(node, dict):
+ raise TypeError('Unexpected hierarchy node format.')
+ attributes = node.get('attributes') or {}
+ children = node.get('children') or []
+ if not isinstance(attributes, dict) or not isinstance(children, list):
+ raise TypeError('Unexpected hierarchy attributes or children format.')
+ # iOS StaticText often exposes only accessibilityText. Android
+ # resource IDs include the package prefix before :id/.
+ identifier = attributes.get('resource-id', '')
+ if isinstance(identifier, str) and identifier.rsplit(':id/', 1)[-1] in redbox_ids:
+ snapshot['RNredbox'] = True
+ for key in ['accessibilityText', 'text', 'title', 'value']:
+ value = attributes.get(key)
+ if not isinstance(value, str):
+ continue
+ snapshot['createPIN'] |= value.strip() == 'Create a passcode'
+ snapshot['confirmPIN'] |= value.strip() == 'Confirm your passcode'
+ for flag, message in fixed_messages.items():
+ snapshot[flag] |= message in value
+ if len(pending) + len(children) + nodes > 10000:
+ raise ValueError('Hierarchy snapshot exceeded node limit.')
+ pending.extend(children)
+ for flag in flags:
+ result[flag] |= snapshot[flag]
+ except Exception as error:
+ kind = type(error).__name__
+ if kind not in result['parse_error_types']:
+ result['parse_error_types'].append(kind)
+ if index >= 8:
+ break
+ return result
+
+
+def maestro_preflight_diagnostics(directory=None, command_label='Assert startup and disposable passcode transition'):
+ """Export fixed cli-2.11.0 driver markers, never subprocess error text."""
+ markers = {
+ 'runner_install_started': '[Start] Install XCUITest runner on',
+ 'runner_install_launch_returned': '[Done] Install XCUITest runner on',
+ 'status_check_started': '[Start] Perform XCUITest driver status check on',
+ 'status_response_received': '[Done] Perform XCUITest driver status check on',
+ 'status_check_failed': '[Failed] Perform XCUITest driver status check on',
+ 'driver_startup_timeout': 'iOS driver not ready in time, consider increasing timeout by configuring MAESTRO_DRIVER_STARTUP_TIMEOUT env variable',
+ 'prebuilt_driver_selected': 'Installing pre built driver without xcodebuild',
+ 'xcodebuild_driver_selected': 'Installing driver with xcodebuild',
+ 'xctestrun_config_missing': 'xctestrun config does not exist',
+ 'ui_test_runner_missing': 'ui test runner does not exist',
+ 'xcode_test_execute_failed': '** TEST EXECUTE FAILED **',
+ 'xcode_test_failed': '** TEST FAILED **',
+ 'xcode_testing_failed': 'Testing failed:',
+ }
+ # The install/status "Done" markers precede readiness evaluation; they do
+ # not prove that the runner installed successfully or became ready.
+ result = {name: False for name in markers}
+ result.update({'host_port_unavailable': False, 'requested_device_disconnected': False,
+ 'exception_types': [], 'logs_read': 0, 'truncated_logs': 0,
+ 'log_limit_reached': False, 'collection_error_types': []})
+ known_types = ['IOSDriverTimeoutException', 'FileNotFoundException', 'CliError',
+ 'IllegalStateException', 'IOException', 'ConnectException',
+ 'SocketTimeoutException', 'TimeoutException', 'RuntimeException',
+ 'UnknownHostException', 'SSLHandshakeException']
+ paths = []
+ for index, entry in enumerate(read()['commands'], 1):
+ if entry['label'] == command_label:
+ paths.append(PRIVATE / ('command-%03d.log' % index))
+ directory = directory if directory is not None else PRIVATE / 'maestro-output'
+ if not directory.resolve().is_relative_to(PRIVATE.resolve()):
+ raise ValueError('Maestro diagnostic directory must remain private.')
+ for pattern in ['**/maestro.log', '**/xctest_runner_*.log']:
+ for path in directory.glob(pattern):
+ paths.append(path)
+ if len(paths) > 6:
+ break
+ if len(paths) > 6:
+ break
+ for path in paths[:6]:
+ try:
+ if path.is_symlink() or not path.resolve().is_relative_to(PRIVATE.resolve()):
+ raise ValueError('Maestro log must remain in private output.')
+ payload, truncated = private_log_prefix(path)
+ result['logs_read'] += 1
+ result['truncated_logs'] += int(truncated)
+ for name, marker in markers.items():
+ result[name] |= marker in payload
+ for line in payload.splitlines():
+ result['host_port_unavailable'] |= ('Requested driver host port ' in line
+ and ' is not available' in line)
+ result['requested_device_disconnected'] |= (' was requested, but it is not connected.' in line)
+ for kind in known_types:
+ if re.search(r'(? 6
+ return result
+
+
+def record_startup_failure(report, device):
+ """Collect bounded diagnostics before destroying this job's fresh app state."""
+ details = {'scope': 'Fresh startup only; no account or persisted PIN created.',
+ 'collection_errors': []}
+
+ def collect(name, action):
+ try:
+ details[name] = action()
+ except Exception as error:
+ details['collection_errors'].append({'stage': name, 'error_type': type(error).__name__})
+
+ def private_text(path):
+ # No raw logs/reports are copied to the artifact directory.
+ with path.open('rb') as source:
+ source.seek(0, os.SEEK_END)
+ source.seek(max(0, source.tell() - 1024 * 1024))
+ return source.read().decode(errors='replace')
+
+ def maestro_details():
+ result = {'failed_commands': [], 'testcase_failures': [], 'report': 'MISSING'}
+ for index, entry in enumerate(read()['commands'], 1):
+ if entry['label'] == 'Assert startup and disposable passcode transition':
+ result['failed_commands'] = maestro_failure_details(private_text(PRIVATE / ('command-%03d.log' % index)))
+ if report.exists():
+ if report.stat().st_size > 1024 * 1024:
+ raise RuntimeError('Maestro report exceeded diagnostic size limit.')
+ suite = ET.parse(report).getroot()
+ result['report'] = 'PRESENT'
+ result['testcase_statuses'] = [case.get('status') if case.get('status') in
+ ['SUCCESS', 'ERROR', 'WARNING', 'SKIPPED'] else 'UNKNOWN'
+ for case in list(suite.iter('testcase'))[:10]]
+ for failure in list(suite.iter('failure'))[:10]:
+ # Pinned Maestro JUnit stores failure.message separately from UI hierarchy.
+ first_line = ''.join(failure.itertext()).splitlines()[:1]
+ result['testcase_failures'].extend(maestro_failure_details('\n'.join(first_line)))
+ return result
+
+ collect('maestro', maestro_details)
+ collect('maestro_preflight', maestro_preflight_diagnostics)
+ collect('hierarchy_signals', lambda: startup_hierarchy_signals(PRIVATE / 'maestro-output'))
+ collect('metro_errors', lambda: metro_startup_errors(private_text(PRIVATE / 'metro.log')))
+ collect('metro_progress', lambda: metro_startup_progress(private_log_prefix(PRIVATE / 'metro.log')[0]))
+ if PLATFORM == 'ANDROID' and device:
+ def android_details():
+ args = ['adb', '-s', device, 'logcat', '-d', '-t', '300', '-v', 'brief',
+ 'AndroidRuntime:E', 'ReactNativeJS:E', 'ReactNative:E', '*:S']
+ path = PRIVATE / 'android-startup-errors.log'
+ with path.open('wb') as output:
+ try:
+ result = subprocess.run(args, stdout=output, stderr=subprocess.STDOUT,
+ timeout=20, check=False)
+ code = result.returncode
+ except subprocess.TimeoutExpired:
+ code = 124
+ return {'command': args, 'exit_code': code,
+ 'errors': android_startup_errors(private_text(path)) if code == 0 else []}
+ collect('android_errors', android_details)
+ def android_runtime_details():
+ spec = importlib.util.spec_from_file_location(
+ 'android_startup_diagnosis', Path(__file__).with_name('android_startup_diagnosis.py'))
+ module = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(module)
+ return module.collect(PRIVATE, device)
+ collect('android_runtime_diagnosis', android_runtime_details)
+ elif PLATFORM == 'IOS' and device:
+ def ios_details():
+ executable = read()['built_artifact']['executable']
+ if not re.fullmatch(r'[A-Za-z0-9_][A-Za-z0-9_.-]*', executable):
+ raise ValueError('Unsafe iOS executable selector.')
+ predicate = ('process == "%s" AND (messageType == "error" OR messageType == "fault" '
+ 'OR eventMessage CONTAINS[c] "error" OR eventMessage CONTAINS[c] "exception" '
+ 'OR eventMessage CONTAINS[c] "fatal")') % executable
+ args = ['xcrun', 'simctl', 'spawn', device, 'log', 'show', '--style', 'compact',
+ '--last', '10m', '--predicate', predicate]
+ path = PRIVATE / 'ios-startup-errors.log'
+ # Keep log/xcrun notices private and separate from compact records.
+ with path.open('wb') as output, (PRIVATE / 'ios-startup-errors-stderr.log').open('wb') as stderr:
+ try:
+ result = subprocess.run(args, stdout=output, stderr=stderr,
+ timeout=25, check=False)
+ code = result.returncode
+ except subprocess.TimeoutExpired:
+ code = 124
+ result = {'command': args, 'exit_code': code, 'errors': []}
+ if code == 0:
+ try:
+ payload, truncated = private_log_prefix(path)
+ result.update(ios_startup_diagnostics(payload, executable))
+ result['input_truncated'] = truncated
+ except (ValueError, TypeError) as error:
+ result['parse_error'] = type(error).__name__
+ return result
+ collect('ios_errors', ios_details)
+ data = read()
+ data['startup_diagnostics'] = details
+ save(data)
+ print('Bounded startup diagnostics: ' + json.dumps(details), flush=True)
+
+
+def command(args, label, timeout=120, cwd=ROOT, capture=False, error_details=True):
+ """Record exact nonsecret argv and status; keep all process output private."""
+ PRIVATE.mkdir(parents=True, exist_ok=True)
+ data = read()
+ entry = {'label': label, 'command': args, 'timeout_seconds': timeout}
+ data['commands'].append(entry)
+ save(data)
+ started = time.monotonic()
+ output_file = PRIVATE / ('command-%03d.log' % len(data['commands']))
+ print(label, flush=True)
+ try:
+ with output_file.open('wb') as output:
+ proc = subprocess.Popen(args, cwd=cwd, stdout=output, stderr=subprocess.STDOUT,
+ start_new_session=True)
+ try:
+ code = proc.wait(timeout=timeout)
+ except subprocess.TimeoutExpired:
+ os.killpg(proc.pid, signal.SIGKILL)
+ proc.wait()
+ code = 124
+ except OSError:
+ code = 127
+ entry['exit_code'] = code
+ entry['duration_seconds'] = round(time.monotonic() - started, 1)
+ if code:
+ # Fixed diagnostics expose install blockers without publishing arbitrary logs.
+ log = output_file.read_text(errors='replace') if output_file.exists() else ''
+ known = {
+ 'lockfile needs to be updated': 'Manifest and yarn.lock are inconsistent; repair the lockfile separately.',
+ 'could not find compatible versions': 'The native dependency lock is incompatible with the manifest.',
+ 'no space left on device': 'The hosted runner ran out of disk space.',
+ 'command not found': 'A required native tool is unavailable.',
+ 'requires a higher minimum deployment target': 'A pod requires a higher iOS deployment target.',
+ }
+ entry['diagnostic'] = next((message for needle, message in known.items()
+ if needle in log.lower()), 'Inspect this command locally; raw output remains private to the runner.')
+ # Keep the schema-1 field name for consumers; values are now fixed
+ # categories, never redacted excerpts or arbitrary exception messages.
+ entry['redacted_tool_errors'] = failure_details(log) if error_details else []
+ for line in entry['redacted_tool_errors']:
+ print(line, flush=True)
+ save(data)
+ raise RuntimeError('%s failed (exit %s). %s' % (label, code, entry['diagnostic']))
+ save(data)
+ return output_file.read_text(errors='replace').strip() if capture else None
+
+
+def record():
+ source = subprocess.check_output(['git', 'rev-parse', 'HEAD'], cwd=ROOT, text=True).strip()
+ if source != os.environ.get('KEEPER_SOURCE_SHA'):
+ raise RuntimeError('Checkout does not match the exact requested PR head.')
+ save({
+ 'schema': 1, 'platform': PLATFORM, 'source_sha': source,
+ 'diagnostic_only': os.environ.get('KEEPER_DIAGNOSTIC') == 'true',
+ 'workflow_ref': os.environ.get('GITHUB_WORKFLOW_REF'),
+ 'workflow_sha': os.environ.get('GITHUB_WORKFLOW_SHA'),
+ 'run_id': os.environ.get('GITHUB_RUN_ID'), 'run_attempt': os.environ.get('GITHUB_RUN_ATTEMPT'),
+ 'runner': {key: os.environ.get(key) for key in
+ ['RUNNER_OS', 'RUNNER_ARCH', 'ImageOS', 'ImageVersion']},
+ 'os': platform.platform(), 'commands': [], 'build': 'NOT RUN', 'smoke': 'NOT RUN', 'native_probe': 'NOT RUN', 'r5_features': 'NOT RUN',
+ 'hardware': 'NOT RUN', 'signing': 'NOT RUN', 'app_id': APP_IDS[PLATFORM],
+ 'smoke_scope': 'Fresh install; render Create a passcode; type four disposable digits; assert Confirm your passcode; stop before persisting credentials.',
+ 'startup_timing_scope': 'Bounded cold development bundle/startup allowance; no release performance acceptance.',
+ 'artifact_policy': 'Metadata only. No raw logs, screenshots, app binaries, simulator data or credentials.',
+ })
+ versions = {
+ 'node': command(['node', '--version'], 'Record Node version', capture=True),
+ 'java': command(['java', '-version'], 'Record Java version', capture=True),
+ }
+ if PLATFORM == 'IOS':
+ versions['xcode'] = command(['xcodebuild', '-version'], 'Record Xcode version', capture=True)
+ versions['sdk'] = command(['xcrun', '--sdk', 'iphonesimulator', '--show-sdk-version'],
+ 'Record iOS Simulator SDK', capture=True)
+ else:
+ versions['expected_sdk_build'] = 'compileSdk=36; buildTools=35.0.0; NDK=27.1.12297006'
+ versions['expected_emulator_target'] = 'Android API 35; google_apis; x86_64; pixel_6'
+ data = read()
+ data['toolchain'] = versions
+ save(data)
+ disk_preflight('initial')
+
+
+def fixtures():
+ # Empty values would fall back to real development services in config.ts.
+ overlays = ['.env.ci', 'firebase.json']
+ (ROOT / '.env.ci').write_text('''ENVIRONMENT=DEVELOPMENT
+RELAY=http://127.0.0.1:8765/
+SIGNING_SERVER_TESTNET=https://127.0.0.1:9/
+SIGNING_SERVER_MAINNET=https://127.0.0.1:9/
+CHANNEL_URL=https://127.0.0.1:9/
+SENTRY_DNS=https://public@127.0.0.1:9/1
+ENC_KEY_STORAGE_IDENTIFIER=KEEPER-HOSTED-DISPOSABLE
+''')
+ (ROOT / 'firebase.json').write_text(json.dumps({'react-native': {
+ 'app_data_collection_default_enabled': False,
+ 'analytics_auto_collection_enabled': False,
+ 'analytics_collection_deactivated': True,
+ 'messaging_auto_init_enabled': False,
+ }}) + '\n')
+ if PLATFORM == 'IOS':
+ import plistlib
+ for path, bundle in [('ios/GoogleService-Info.plist', 'io.hexawallet.keeper'),
+ ('ios/GoogleServices/dev/GoogleService-Info.plist', APP_IDS['IOS'])]:
+ overlays.append(path)
+ with (ROOT / path).open('wb') as output:
+ plistlib.dump({'API_KEY': 'AIzaSy' + '0' * 33, 'GCM_SENDER_ID': '123456789012',
+ 'PLIST_VERSION': '1', 'BUNDLE_ID': bundle,
+ 'PROJECT_ID': 'keeper-disposable-ci',
+ 'GOOGLE_APP_ID': '1:123456789012:ios:0000000000000000000000',
+ 'IS_GCM_ENABLED': False, 'IS_ANALYTICS_ENABLED': False,
+ 'IS_ADS_ENABLED': False, 'IS_SIGNIN_ENABLED': False}, output)
+ else:
+ overlays.append('android/app/google-services.json')
+ (ROOT / 'android/app/google-services.json').write_text(json.dumps({
+ 'project_info': {'project_number': '123456789012', 'project_id': 'keeper-disposable-ci'},
+ 'client': [{'client_info': {'mobilesdk_app_id': '1:123456789012:android:0000000000000000',
+ 'android_client_info': {'package_name': APP_IDS['ANDROID']}},
+ 'api_key': [{'current_key': 'AIzaSy' + '0' * 33}]}],
+ 'configuration_version': '1',
+ }) + '\n')
+ data = read()
+ data['configuration'] = 'Synthetic Firebase project; DEVELOPMENT/testnet; loopback-only configured services; no production secrets.'
+ data['configuration_overlays'] = [{'path': path, 'sha256': hashlib.sha256((ROOT / path).read_bytes()).hexdigest()}
+ for path in overlays]
+ save(data)
+
+
+def install_maestro():
+ archive = PRIVATE / 'maestro.zip'
+ url = 'https://github.com/mobile-dev-inc/Maestro/releases/download/%s/maestro.zip' % MAESTRO_VERSION
+ command(['curl', '--fail', '--location', '--silent', '--show-error', '--max-time', '120',
+ '--output', str(archive), url], 'Download pinned Maestro', timeout=130)
+ if hashlib.sha256(archive.read_bytes()).hexdigest() != MAESTRO_SHA256:
+ raise RuntimeError('Maestro archive checksum mismatch.')
+ # unzip preserves executable modes for the bundled native iOS driver;
+ # Python ZipFile extraction would silently strip those modes.
+ command(['unzip', '-q', str(archive), '-d', str(PRIVATE / 'maestro')],
+ 'Extract verified Maestro including native executable modes', timeout=120)
+ candidates = list((PRIVATE / 'maestro').rglob('bin/maestro'))
+ if len(candidates) != 1:
+ raise RuntimeError('Unexpected Maestro archive layout.')
+ data = read()
+ data['maestro'] = {'version': MAESTRO_VERSION, 'sha256': MAESTRO_SHA256, 'binary': str(candidates[0])}
+ save(data)
+
+
+def android_sdk_metadata(sdk, component):
+ properties = (sdk / component / 'source.properties').read_text()
+ values = dict((key.strip(), value.strip()) for line in properties.splitlines()
+ if '=' in line for key, value in [line.split('=', 1)])
+ if not values.get('Pkg.Revision'):
+ raise RuntimeError('Android SDK component %s has no Pkg.Revision metadata.' % component)
+ return {key: value for key, value in values.items()
+ if key in ['Pkg.Revision', 'AndroidVersion.ApiLevel']}
+
+
+def prepare():
+ disk_preflight('before_dependencies')
+ command(['npm', 'install', '--global', 'yarn@1.22.22', '--ignore-scripts'], 'Install pinned Yarn', timeout=180)
+ command(['yarn', 'install', '--frozen-lockfile', '--ignore-scripts', '--non-interactive'],
+ 'Install immutable JavaScript dependencies', timeout=900)
+ command(['node_modules/.bin/patch-package', '--error-on-fail'], 'Apply repository dependency patches', timeout=180)
+ original_manifest = (ROOT / 'package.json').read_bytes()
+ command(['node', '.github/native/nodeify.cjs'],
+ 'Apply committed Node compatibility whitelist without installing dependencies', timeout=180)
+ installed_manifest = (ROOT / 'package.json').read_bytes()
+ original = json.loads(original_manifest)
+ installed = json.loads(installed_manifest)
+ for key in ['browser', 'react-native', 'browserify']:
+ original.pop(key, None)
+ installed.pop(key, None)
+ if original != installed:
+ raise RuntimeError('Node compatibility setup changed fields beyond module mappings.')
+ data = read()
+ data['nodeify_overlay'] = {
+ 'path': 'package.json', 'before_sha256': hashlib.sha256(original_manifest).hexdigest(),
+ 'after_sha256': hashlib.sha256(installed_manifest).hexdigest(),
+ 'diff_sha256': hashlib.sha256(subprocess.check_output(['git', 'diff', 'HEAD', '--', 'package.json'], cwd=ROOT)).hexdigest(),
+ 'allowed_fields': ['browser', 'react-native', 'browserify'],
+ }
+ save(data)
+ command(['git', 'diff', '--exit-code', 'HEAD', '--', 'yarn.lock', 'ios/Podfile.lock'],
+ 'Verify dependency locks remain immutable')
+ fixtures()
+ install_maestro()
+ if PLATFORM == 'IOS':
+ command(['gem', 'install', 'cocoapods', '--version', '1.16.2', '--no-document'],
+ 'Install pinned CocoaPods', timeout=300)
+ if os.environ.get('KEEPER_POD_LOCK_REPAIR') == '1':
+ # Diagnostic bootstrap only. A candidate lock is reviewed/committed,
+ # then a separate strict deployment run must build and test the app.
+ command(['pod', 'update', 'NitroIap', 'NitroModules', 'openiap', '--no-repo-update'],
+ 'Generate targeted CocoaPods lock candidate (not validation)',
+ timeout=900, cwd=ROOT / 'ios')
+ shutil.copyfile(ROOT / 'ios/Podfile.lock', EVIDENCE.parent / 'Podfile.lock.candidate')
+ raise RuntimeError('Pod lock candidate generated for review; no native validation performed.')
+ command(['pod', 'install', '--deployment'], 'Install immutable CocoaPods dependencies',
+ timeout=900, cwd=ROOT / 'ios')
+ # Existing PBX build phases hardcode this path. Adapt the disposable host,
+ # preserving the app project and the source commit being tested.
+ command(['sudo', 'mkdir', '-p', '/opt/homebrew/bin'], 'Prepare existing Xcode Node path')
+ command(['sudo', 'ln', '-sf', shutil.which('node'), '/opt/homebrew/bin/node'],
+ 'Connect existing Xcode Node path to pinned Node')
+ else:
+ command(['sdkmanager', 'platforms;android-36', 'build-tools;35.0.0', 'ndk;27.1.12297006'],
+ 'Install pinned Android build SDK and NDK', timeout=600)
+ sdk = Path(os.environ.get('ANDROID_HOME', os.environ.get('ANDROID_SDK_ROOT', '')))
+ observed = {}
+ for component in ['platforms/android-36', 'build-tools/35.0.0', 'ndk/27.1.12297006']:
+ observed[component] = android_sdk_metadata(sdk, component)
+ data = read()
+ data['toolchain']['observed_android_sdk'] = observed
+ save(data)
+ if (ROOT / 'package.json').read_bytes() != installed_manifest:
+ raise RuntimeError('Native installation unexpectedly rewrote the installed manifest.')
+ command(['git', 'diff', '--exit-code', 'HEAD', '--', 'yarn.lock', 'ios/Podfile.lock'],
+ 'Verify native installation did not rewrite locks')
+
+
+def artifact_identity():
+ if PLATFORM == 'IOS':
+ import plistlib
+ bundle = PRIVATE / 'DerivedData/Build/Products/Debug-iphonesimulator/hexa_keeper_dev.app'
+ with (bundle / 'Info.plist').open('rb') as source:
+ executable = plistlib.load(source)['CFBundleExecutable']
+ binary = bundle / executable
+ tree = hashlib.sha256()
+ for file in sorted(path for path in bundle.rglob('*') if path.is_file()):
+ tree.update(str(file.relative_to(bundle)).encode() + b'\0')
+ tree.update(hashlib.sha256(file.read_bytes()).digest())
+ return {'path': str(bundle), 'executable': executable,
+ 'executable_sha256': hashlib.sha256(binary.read_bytes()).hexdigest(),
+ 'bundle_tree_sha256': tree.hexdigest()}
+ apk = ROOT / 'android/app/build/outputs/apk/development/debug/app-development-debug.apk'
+ return {'path': str(apk.relative_to(ROOT)), 'sha256': hashlib.sha256(apk.read_bytes()).hexdigest()}
+
+
+def _file_sha256(path):
+ digest = hashlib.sha256()
+ with path.open('rb') as source:
+ for block in iter(lambda: source.read(1024 * 1024), b''):
+ digest.update(block)
+ return digest.hexdigest()
+
+
+def _bundle_inventory(bundle):
+ """Private typed tree; internal links must remain inside this bundle."""
+ import plistlib
+ if bundle.is_symlink() or not bundle.is_dir():
+ raise ValueError('Invalid app bundle.')
+ root = bundle.resolve(strict=True)
+ with (bundle / 'Info.plist').open('rb') as source:
+ info = plistlib.load(source)
+ executable = info['CFBundleExecutable']
+ if (info['CFBundleIdentifier'] != APP_IDS['IOS'] or
+ not re.fullmatch(r'[A-Za-z0-9_][A-Za-z0-9_.-]*', executable)):
+ raise ValueError('Unexpected app identity.')
+ tree = {}
+ for entry in sorted(bundle.rglob('*')):
+ if not entry.resolve(strict=True).is_relative_to(root):
+ raise ValueError('Bundle entry escaped app.')
+ if entry.is_symlink():
+ value = ['link', os.readlink(entry)]
+ elif entry.is_file():
+ value = ['file', _file_sha256(entry)]
+ elif entry.is_dir():
+ value = ['directory']
+ else:
+ raise ValueError('Unsupported bundle entry.')
+ tree[entry.relative_to(bundle).as_posix()] = value
+ if tree.get(executable, [None])[0] != 'file':
+ raise ValueError('Missing regular app executable.')
+ return tree, executable
+
+
+def verify_installed_artifact(device):
+ """Attest owned installed bytes, never installation argv or app assertions."""
+ data = read()
+ data['installed_artifact_verified'] = False
+ data['installed_artifact_scope'] = 'NOT VERIFIED: installed bytes require full comparison.'
+ data.pop('installed_artifact', None)
+ save(data)
+ try:
+ expected = data['built_artifact']
+ if PLATFORM == 'IOS':
+ uuid = r'[A-Fa-f0-9]{8}(?:-[A-Fa-f0-9]{4}){3}-[A-Fa-f0-9]{12}'
+ if not re.fullmatch(uuid, device):
+ raise ValueError('Expected owned simulator UUID.')
+ built = PRIVATE / 'DerivedData/Build/Products/Debug-iphonesimulator/hexa_keeper_dev.app'
+ original, executable = _bundle_inventory(built)
+ installed = Path(command(['xcrun', 'simctl', 'get_app_container', device, APP_IDS['IOS'], 'app'],
+ 'Locate owned installed app bundle', capture=True, error_details=False))
+ base = Path.home() / 'Library/Developer/CoreSimulator/Devices' / device / 'data/Containers/Bundle/Application'
+ if (not installed.is_absolute() or installed.name != built.name or
+ not re.fullmatch(uuid, installed.parent.name) or
+ installed.parent.parent.resolve() != base.resolve() or
+ installed.resolve(strict=True).parent.parent != base.resolve()):
+ raise ValueError('Unexpected installed app container.')
+ actual, installed_executable = _bundle_inventory(installed)
+ if original != actual or executable != installed_executable:
+ raise ValueError('Installed bundle differs; no installer normalization is accepted.')
+ result = {'method': 'FULL_SIMULATOR_BUNDLE_TREE_AND_EXECUTABLE_SHA256',
+ 'inventory_sha256': hashlib.sha256(json.dumps(original, sort_keys=True).encode()).hexdigest(),
+ 'executable_sha256': actual[executable][1]}
+ elif PLATFORM == 'ANDROID':
+ if not re.fullmatch(r'emulator-[0-9]+', device):
+ raise ValueError('Expected owned emulator serial.')
+ listing = command(['adb', '-s', device, 'shell', 'pm', 'path', APP_IDS['ANDROID']],
+ 'Locate exact installed development package', capture=True, error_details=False)
+ pattern = (r'package:(/data/app/(?:~~[A-Za-z0-9_=-]+/)?' + re.escape(APP_IDS['ANDROID']) +
+ r'-[A-Za-z0-9_=-]+/base\.apk)')
+ match = re.fullmatch(pattern, listing)
+ if not match:
+ raise ValueError('Expected one exact base APK; split or unexpected paths rejected.')
+ built = ROOT / 'android/app/build/outputs/apk/development/debug/app-development-debug.apk'
+ if built.is_symlink() or not built.is_file():
+ raise ValueError('Invalid built APK.')
+ PRIVATE.mkdir(parents=True, exist_ok=True)
+ with tempfile.TemporaryDirectory(prefix='installed-artifact-', dir=PRIVATE) as temporary:
+ pulled = Path(temporary) / 'base.apk'
+ # Package paths and pulled bytes stay private, including tool output.
+ copied = subprocess.run(['adb', '-s', device, 'pull', match[1], str(pulled)],
+ stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
+ timeout=120, check=False)
+ if (copied.returncode or pulled.is_symlink() or not pulled.is_file() or
+ pulled.stat().st_size != built.stat().st_size or _file_sha256(pulled) != expected['sha256']):
+ raise ValueError('Installed APK bytes differ or are unavailable.')
+ result = {'method': 'SINGLE_INSTALLED_BASE_APK_SHA256', 'sha256': expected['sha256']}
+ else:
+ raise ValueError('Unsupported artifact platform.')
+ if artifact_identity() != expected:
+ raise ValueError('Built artifact changed during installed comparison.')
+ except Exception:
+ raise RuntimeError('Installed artifact bytes were not verified; no equivalence claimed.') from None
+ data = read()
+ data.update(installed_artifact_verified=True, installed_artifact=result,
+ installed_artifact_scope='Full installed artifact byte comparison; no installer transformations accepted.')
+ save(data)
+ return result
+
+
+def wait_for_simulator_app_services(device):
+ """Boot completion alone did not establish app-service responsiveness."""
+ if PLATFORM != 'IOS':
+ raise ValueError('Simulator app-service readiness is iOS-only.')
+ spec = importlib.util.spec_from_file_location('simulator_readiness', Path(__file__).with_name('simulator_readiness.py'))
+ readiness = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(readiness)
+ return readiness.wait_for_app_services(SimpleNamespace(PRIVATE=PRIVATE, read=read, save=save),
+ device, timeout=120)
+
+
+def driver():
+ """Fail early on iOS driver setup without installing or crediting the app."""
+ if PLATFORM != 'IOS':
+ raise ValueError('The disposable driver preflight is iOS-only.')
+ state = PRIVATE / 'maestro-preflight-state'
+ os.environ['XDG_STATE_HOME'] = str(state)
+ details = {'scope': 'DRIVER PREFLIGHT/setup only; no app build, install or UI credit.',
+ 'result': 'FAIL', 'cleanup_errors': []}
+ device = None
+ original_error = None
+ label = 'Check disposable iOS driver readiness'
+ try:
+ created = command(['xcrun', 'simctl', 'create', 'Keeper-driver-preflight-ci',
+ 'com.apple.CoreSimulator.SimDeviceType.iPhone-16',
+ 'com.apple.CoreSimulator.SimRuntime.iOS-18-5'],
+ 'Create owned driver-preflight simulator', timeout=120, capture=True)
+ if not re.fullmatch(r'[A-Fa-f0-9]{8}(?:-[A-Fa-f0-9]{4}){3}-[A-Fa-f0-9]{12}', created):
+ raise ValueError('simctl create did not return an owned simulator UUID.')
+ device = created
+ command(['xcrun', 'simctl', 'boot', device], 'Boot owned driver-preflight simulator', timeout=120)
+ command(['xcrun', 'simctl', 'bootstatus', device, '-b'],
+ 'Wait for driver-preflight simulator boot', timeout=240)
+ wait_for_simulator_app_services(device)
+ command([read()['maestro']['binary'], '--platform', 'ios', '--device', device, 'hierarchy'],
+ label, timeout=300, error_details=False)
+ details['result'] = 'PASS'
+ except Exception as error:
+ original_error = error
+ details['error_type'] = type(error).__name__
+ raise
+ finally:
+ if device:
+ for action in ['shutdown', 'delete']:
+ try:
+ subprocess.run(['xcrun', 'simctl', action, device], stdout=subprocess.DEVNULL,
+ stderr=subprocess.DEVNULL, timeout=30, check=True)
+ except Exception as error:
+ details['cleanup_errors'].append({'action': action, 'error_type': type(error).__name__})
+ try:
+ details['diagnostics'] = maestro_preflight_diagnostics(state / 'maestro/tests', label)
+ except Exception as error:
+ details['diagnostics'] = {'collection_error_types': [type(error).__name__]}
+ if details['cleanup_errors']:
+ details['result'] = 'FAIL'
+ try:
+ data = read()
+ data['driver_preflight'] = details
+ save(data)
+ except Exception:
+ if original_error is None:
+ raise RuntimeError('Driver-preflight receipt failed.') from None
+ if details['cleanup_errors'] and original_error is None:
+ raise RuntimeError('Owned driver-preflight simulator cleanup failed.')
+
+
+def disk_preflight(stage):
+ free = shutil.disk_usage(ROOT).free
+ minimum = 12 * 1024 ** 3
+ data = read()
+ data.setdefault('disk_preflight', []).append({
+ 'stage': stage, 'free_bytes': free, 'minimum_free_bytes': minimum,
+ 'result': 'PASS' if free >= minimum else 'FAIL',
+ })
+ save(data)
+ if free < minimum:
+ raise RuntimeError('Insufficient disposable-runner disk reserve; no cache or user data was removed.')
+
+
+def build():
+ disk_preflight('before_native_build')
+ if PLATFORM == 'IOS':
+ architecture = platform.machine()
+ if architecture not in ['arm64', 'x86_64']:
+ raise RuntimeError('Unsupported hosted iOS simulator architecture: %s' % architecture)
+ data = read()
+ data.setdefault('toolchain', {})['ios_simulator_architecture'] = architecture
+ save(data)
+ command(['xcodebuild', '-workspace', 'ios/hexa_keeper.xcworkspace', '-scheme', 'hexa_keeper_dev',
+ '-configuration', 'Debug', '-sdk', 'iphonesimulator', '-destination', 'generic/platform=iOS Simulator',
+ '-derivedDataPath', str(PRIVATE / 'DerivedData'), 'CODE_SIGNING_ALLOWED=NO',
+ 'CODE_SIGNING_REQUIRED=NO', 'ARCHS=' + architecture, 'ONLY_ACTIVE_ARCH=YES', 'build'],
+ 'Build unsigned development simulator app', timeout=2400)
+ else:
+ observed = command(['./gradlew', '--version'], 'Record actual Gradle and JVM version',
+ capture=True, cwd=ROOT / 'android')
+ data = read()
+ data['toolchain']['gradle'] = observed
+ save(data)
+ command(['./gradlew', ':app:assembleDevelopmentDebug', '--no-daemon', '--max-workers=2',
+ '-PreactNativeArchitectures=x86_64'], 'Build debug-key-only development APK',
+ timeout=2100, cwd=ROOT / 'android')
+ data = read()
+ data['built_artifact'] = artifact_identity()
+ data['build'] = 'PASS'
+ save(data)
+
+
+def warm_metro_bundle(suite='startup'):
+ """Bound cold development bundling before starting either disposable app."""
+ bundle_platform = {'IOS': 'ios', 'ANDROID': 'android'}.get(PLATFORM)
+ if bundle_platform is None:
+ raise ValueError('Unsupported native bundle platform.')
+ url = 'http://127.0.0.1:8081/index.bundle?platform=%s&dev=true&minify=false' % bundle_platform
+ body = PRIVATE / ('%s-development-warmup.bundle' % bundle_platform)
+ details = {'scope': 'Development bundle setup only; not native or UI evidence.',
+ 'platform': bundle_platform, 'url': url, 'timeout_seconds': 240,
+ 'result': 'FAIL', 'http_status': None}
+ started = time.monotonic()
+ try:
+ status = command(['curl', '--fail', '--silent', '--show-error', '--max-time', '240',
+ '--output', str(body), '--write-out', '%{http_code}', url],
+ 'Warm %s development bundle (setup only)' % PLATFORM, timeout=250, capture=True)
+ if re.fullmatch(r'\d{3}', status):
+ details['http_status'] = int(status)
+ if status != '200' or not body.is_file() or body.stat().st_size == 0:
+ raise RuntimeError('Development bundle warmup did not return a nonempty HTTP 200 body.')
+ digest = hashlib.sha256()
+ with body.open('rb') as source:
+ for chunk in iter(lambda: source.read(1024 * 1024), b''):
+ digest.update(chunk)
+ details.update({'result': 'PASS', 'bytes': body.stat().st_size, 'sha256': digest.hexdigest()})
+ finally:
+ details['duration_seconds'] = round(time.monotonic() - started, 1)
+ data = read()
+ data['metro_warmup' if suite == 'startup' else suite + '_bundle'] = details
+ save(data)
+
+
+R5_SCENARIOS = [
+ 'production-setup-offline-retry-native-counts',
+ 'production-deletion-retained-native-references',
+ 'production-deletion-native-rollback',
+ 'production-worker-stale-session-rejection',
+ 'native-worker-process-relaunch-counts',
+]
+R5_LIMITS = [
+ 'controlled-transport-no-backend-acceptance',
+ 'synthetic-wallet-generation-no-crypto-acceptance',
+ 'injected-dispatch-selection-no-login-acceptance',
+ 'no-product-ui-navigation-pin-or-biometric-acceptance',
+ 'probe-and-worker-timings-not-product-startup-ux',
+]
+R5_SOURCES = {
+ 'src/utils/utilities.ts': ['getAccountFromSigner', 'getKeyUID'],
+ 'src/store/sagas/storage.ts': ['setupKeeperAppWorker'],
+ 'src/store/sagas/wallets.ts': ['currentWalletAccountId', 'assertWalletAccount', 'deleteSigningDeviceWorker'],
+ 'src/store/sagas/bhr.ts': ['currentBackupAppId', 'deleteAppImageEntityWorker'],
+ 'src/services/backup/transport.ts': ['observeBackupAccount', 'currentBackupAccountSession', 'clearVerifiedRemoteRevision'],
+}
+
+
+def validate_r5_feature_evidence(raw):
+ if not isinstance(raw, str) or len(raw.encode()) > 65536:
+ raise ValueError('Feature evidence absent or oversized.')
+ def invalid_constant(value):
+ raise ValueError('Non-finite feature measurement.')
+ payload = json.loads(raw, parse_constant=invalid_constant)
+ if (type(payload.get('schema')) is not int or payload.get('schema') != 1 or payload.get('scope') != 'production-worker-native-storage'
+ or payload.get('status') != 'PASS' or payload.get('stage') != 'pass'
+ or payload.get('scenarios') != [{'id': item, 'status': 'PASS'} for item in R5_SCENARIOS]
+ or payload.get('limits') != R5_LIMITS):
+ raise ValueError('Feature scenario evidence is incomplete or outside reviewed scope.')
+ measurements = payload.get('measurements')
+ if not isinstance(measurements, list) or len(measurements) != 5:
+ raise ValueError('Five raw helper measurements are required.')
+ for iteration, row in enumerate(measurements, 1):
+ if not isinstance(row, dict) or set(row) != {'iteration', 'probe_ready_ms', 'setup_first_wallet_ms'} or type(row['iteration']) is not int or row['iteration'] != iteration:
+ raise ValueError('Invalid feature measurement shape.')
+ for field in ['probe_ready_ms', 'setup_first_wallet_ms']:
+ value = row[field]
+ if type(value) not in [int, float] or not math.isfinite(value) or not 0 <= value <= 600000:
+ raise ValueError('Invalid bounded feature measurement.')
+ sources = payload.get('source_functions')
+ expected = []
+ for path, names in R5_SOURCES.items():
+ committed = subprocess.check_output(['git', 'show', 'HEAD:' + path], cwd=ROOT)
+ if (ROOT / path).read_bytes() != committed:
+ raise ValueError('Feature production source differs from committed candidate.')
+ expected.append({'path': path, 'sha256': hashlib.sha256(committed).hexdigest(), 'names': names})
+ if sources != expected:
+ raise ValueError('Feature workers do not match exact-candidate production source.')
+ # Export only fixed scope/status, public source digests and bounded numbers.
+ # Never forward arbitrary payload fields or native failure messages.
+ return {'schema': 1, 'scope': 'production-worker-native-storage', 'status': 'PASS',
+ 'scenarios': payload['scenarios'], 'measurements': measurements,
+ 'limits': R5_LIMITS, 'source_functions': sources}
+
+
+def collect_r5_feature_evidence(device):
+ filename = 'keeper-r5-native-evidence.json'
+ if PLATFORM == 'IOS':
+ container = Path(command(['xcrun', 'simctl', 'get_app_container', device, APP_IDS[PLATFORM], 'data'],
+ 'Locate disposable feature evidence', capture=True))
+ path = container / 'Documents' / filename
+ if path.stat().st_size > 65536:
+ raise ValueError('Oversized native feature evidence.')
+ raw = path.read_text()
+ else:
+ raw = command(['adb', '-s', device, 'exec-out', 'run-as', APP_IDS[PLATFORM],
+ 'head', '-c', '65537', 'files/' + filename],
+ 'Read bounded disposable feature evidence', capture=True, error_details=False)
+ return validate_r5_feature_evidence(raw)
+
+
+def smoke(suite='startup'):
+ if suite not in ['startup', 'probe', 'features']:
+ raise ValueError('Unknown disposable native suite.')
+ is_probe = suite == 'probe'
+ is_features = suite == 'features'
+ result_key = 'r5_features' if is_features else 'native_probe' if is_probe else 'smoke'
+ if (is_probe or is_features) and read()['smoke'] != 'PASS':
+ raise RuntimeError('The real app startup smoke must pass before module probes.')
+ if read()['build'] != 'PASS':
+ raise RuntimeError('A successful native build is required before smoke testing.')
+ if artifact_identity() != read()['built_artifact']:
+ raise RuntimeError('Built artifact changed before the disposable startup smoke.')
+ if is_features:
+ command(['git', 'diff', '--exit-code', 'HEAD', '--', *R5_SOURCES],
+ 'Verify committed R5 worker source before extraction', error_details=False)
+ command(['node', '.github/native/r5_prepare.cjs'], 'Prepare exact-source R5 production worker probe', timeout=60, error_details=False)
+ report = PRIVATE / ('features-junit.xml' if is_features else 'probe-junit.xml' if is_probe else 'smoke-junit.xml')
+ report.unlink(missing_ok=True)
+ metro_output = (PRIVATE / 'metro.log').open('wb')
+ metro_args = ['node', 'node_modules/react-native/cli.js', 'start', '--port', '8081']
+ startup_observer = None
+ startup_capture = None
+ startup_context = SimpleNamespace(PRIVATE=PRIVATE, PLATFORM=PLATFORM)
+ metro_env = os.environ.copy()
+ try:
+ if is_probe or is_features:
+ metro_args += ['--config', str(ROOT / ('.github/native/r5_metro.cjs' if is_features else '.github/native/release_metro.cjs'))]
+ elif PLATFORM == 'ANDROID':
+ # Observation retains the normal entrypoint/resolver/transformer and
+ # response body. Only fixed facts leave the disposable launch window.
+ spec = importlib.util.spec_from_file_location('startup_diagnosis', Path(__file__).with_name('startup_diagnosis.py'))
+ startup_observer = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(startup_observer)
+ observer_path = PRIVATE / 'startup-observer.jsonl'
+ observer_path.unlink(missing_ok=True)
+ metro_env['KEEPER_STARTUP_OBSERVER_PATH'] = str(observer_path)
+ metro_args += ['--config', str(ROOT / '.github/native/startup_observer.cjs'),
+ '--custom-log-reporter-path', str(ROOT / '.github/native/startup_reporter.cjs')]
+ metro = subprocess.Popen(metro_args,
+ cwd=ROOT, stdout=metro_output, stderr=subprocess.STDOUT, start_new_session=True,
+ env=metro_env)
+ except Exception:
+ try:
+ metro_output.close()
+ except Exception:
+ pass
+ raise
+ device = None
+ startup_error = None
+ try:
+ for _ in range(60):
+ if metro.poll() is not None:
+ raise RuntimeError('Metro exited before the disposable smoke.')
+ try:
+ with urllib.request.urlopen('http://127.0.0.1:8081/status', timeout=2) as response:
+ if b'packager-status:running' in response.read():
+ break
+ except OSError:
+ time.sleep(1)
+ else:
+ raise RuntimeError('Metro did not become ready within 60 attempts.')
+ warm_metro_bundle(suite)
+ if PLATFORM == 'IOS':
+ device = command(['xcrun', 'simctl', 'create', 'Keeper-disposable-ci',
+ 'com.apple.CoreSimulator.SimDeviceType.iPhone-16',
+ 'com.apple.CoreSimulator.SimRuntime.iOS-18-5'],
+ 'Create fresh iPhone 16 iOS 18.5 simulator', capture=True)
+ if not re.fullmatch(r'[A-Fa-f0-9]{8}(?:-[A-Fa-f0-9]{4}){3}-[A-Fa-f0-9]{12}', device):
+ raise ValueError('Expected owned simulator UUID before installation.')
+ command(['xcrun', 'simctl', 'boot', device], 'Boot disposable simulator')
+ command(['xcrun', 'simctl', 'bootstatus', device, '-b'], 'Wait for simulator boot', timeout=240)
+ wait_for_simulator_app_services(device)
+ install_args = ['xcrun', 'simctl', 'install', device,
+ str(PRIVATE / 'DerivedData/Build/Products/Debug-iphonesimulator/hexa_keeper_dev.app')]
+ if not (is_probe or is_features):
+ spec = importlib.util.spec_from_file_location('install_diagnosis', Path(__file__).with_name('install_diagnosis.py'))
+ installer = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(installer)
+ installer.observe(SimpleNamespace(PRIVATE=PRIVATE, ROOT=ROOT, read=read, save=save, command=command),
+ device, install_args, 'Install unsigned development app', timeout=120)
+ else:
+ command(install_args, 'Install unsigned development app', timeout=120)
+ descriptor = 'iPhone 16; iOS 18.5'
+ else:
+ sdk = Path(os.environ.get('ANDROID_HOME', os.environ.get('ANDROID_SDK_ROOT', '')))
+ # Query the installed SDK package without loading emulator GUI libraries
+ # on the headless host. The emulator runner already booted this image.
+ emulator_version = android_sdk_metadata(sdk, 'emulator')
+ adb_version = command(['adb', 'version'], 'Record actual adb version', capture=True)
+ data = read()
+ data['toolchain']['emulator'] = {'source': 'emulator/source.properties', **emulator_version}
+ data['toolchain']['adb'] = adb_version
+ save(data)
+ device = command(['adb', 'get-serialno'], 'Identify fresh emulator', capture=True)
+ if not re.fullmatch(r'emulator-[0-9]+', device):
+ raise ValueError('Expected owned emulator before installation.')
+ command(['adb', '-s', device, 'reverse', 'tcp:8081', 'tcp:8081'], 'Connect emulator to Metro')
+ command(['adb', '-s', device, 'install', '-r',
+ 'android/app/build/outputs/apk/development/debug/app-development-debug.apk'],
+ 'Install development debug APK', timeout=120)
+ descriptor = command(['adb', '-s', device, 'shell', 'getprop', 'ro.build.fingerprint'],
+ 'Record Android emulator image', capture=True)
+ data = read()
+ data['device'] = {'id': device, 'image': descriptor, 'fresh_disposable_state': True}
+ data['install_succeeded'] = True
+ save(data)
+ verify_installed_artifact(device)
+ data = read()
+ if startup_observer:
+ try:
+ startup_capture = startup_observer.start(startup_context, device)
+ except Exception:
+ data['startup_observation_capture'] = 'UNAVAILABLE'
+ save(data)
+ command([data['maestro']['binary'], '--device', device, 'test', '--env', 'APP_ID=' + APP_IDS[PLATFORM],
+ '--flatten-debug-output', '--debug-output', str(PRIVATE / 'maestro-output'),
+ '--format', 'junit', '--output', str(report), '--test-output-dir', str(PRIVATE / 'maestro-output'),
+ '.github/native/r5_features.yaml' if is_features else '.github/native/release_probe.yaml' if is_probe else '.github/native/startup.yaml'],
+ 'Assert R5 production workers over native storage' if is_features else 'Assert native persistence across process launches' if is_probe else
+ 'Assert startup and disposable passcode transition', timeout=660 if is_features else 300 if is_probe else 420,
+ error_details=not (is_probe or is_features))
+ cases = successful_junit(report)
+ if artifact_identity() != read()['built_artifact']:
+ raise RuntimeError('Built artifact changed during native execution.')
+ verify_installed_artifact(device)
+ data = read()
+ data[result_key] = 'PASS'
+ data[result_key + '_test_cases'] = cases
+ if is_features:
+ data['r5_feature_evidence'] = collect_r5_feature_evidence(device)
+ if is_probe:
+ data['probe_scope'] = ('CI-only Metro entrypoint; actual encrypted Realm/current schemas and production MMKV; '
+ 'three process launches, rollback, wrong-key rejection, targeted primitive deletion, '
+ 'separate database files and cleanup. NOT app key deletion, account isolation, '
+ 'setup/recovery or release performance acceptance.')
+ save(data)
+ except Exception as original_error:
+ startup_error = original_error
+ try:
+ if not (is_probe or is_features):
+ record_startup_failure(report, device)
+ else:
+ data = read()
+ data[result_key] = 'FAIL'
+ data['probe_diagnostics'] = 'Native module or worker probe failed; raw output retained only on ephemeral runner.'
+ save(data)
+ except Exception as error:
+ # Diagnostics never replace the original failed native/UI result.
+ try:
+ data = read()
+ data['startup_diagnostics'] = {'collection_errors': [
+ {'stage': 'collector', 'error_type': type(error).__name__}]}
+ save(data)
+ except Exception:
+ pass
+ raise
+ finally:
+ # Receipt I/O is never allowed to skip owned-resource disposal or hide
+ # the original native failure. Retain only fixed cleanup labels.
+ cleanup_errors = []
+ updates = {}
+
+ def cleanup(label, action):
+ try:
+ action()
+ except Exception:
+ cleanup_errors.append(label)
+
+ if startup_observer:
+ try:
+ updates['startup_observation'] = startup_observer.collect(startup_context, device, startup_capture) if device else {'scope': 'App launch NOT RUN; no owned device.'}
+ except Exception:
+ updates['startup_observation'] = {'collection_errors': ['collector']}
+ cleanup('startup_capture', lambda: startup_observer.stop(startup_capture))
+ if 'startup_capture' in cleanup_errors:
+ updates['startup_observation_cleanup'] = 'FAIL'
+
+ def stop_metro():
+ if metro.poll() is None:
+ os.killpg(metro.pid, signal.SIGTERM)
+ try:
+ metro.wait(timeout=10)
+ except subprocess.TimeoutExpired:
+ os.killpg(metro.pid, signal.SIGKILL)
+ metro.wait(timeout=10)
+
+ cleanup('metro_process', stop_metro)
+ cleanup('metro_output', metro_output.close)
+ if device and PLATFORM == 'IOS':
+ for action in ['shutdown', 'delete']:
+ cleanup('device_' + action, lambda action=action: subprocess.run(
+ ['xcrun', 'simctl', action, device], stdout=subprocess.DEVNULL,
+ stderr=subprocess.DEVNULL, timeout=30, check=True))
+ elif device:
+ cleanup('device_uninstall', lambda: subprocess.run(
+ ['adb', '-s', device, 'uninstall', APP_IDS[PLATFORM]], stdout=subprocess.DEVNULL,
+ stderr=subprocess.DEVNULL, timeout=30, check=True))
+ if startup_observer:
+ # Purge only this observer's raw files; other phases still need the
+ # shared private build/tool directories on the ephemeral runner.
+ for name in ['startup-logcat.log', 'startup-observer.jsonl', 'startup-foreground.log']:
+ cleanup('private_' + name.split('.')[0], lambda name=name: (PRIVATE / name).unlink(missing_ok=True))
+ if startup_error is not None or cleanup_errors:
+ updates[result_key] = 'FAIL'
+ if cleanup_errors:
+ updates['startup_cleanup_errors'] = cleanup_errors.copy()
+ try:
+ data = read()
+ data.update(updates)
+ save(data)
+ except Exception:
+ cleanup_errors.append('metadata')
+ # A transient write failure may allow one best-effort FAIL receipt.
+ # A permanently unavailable receipt still causes a failing phase.
+ try:
+ data = read()
+ data.update(updates)
+ data.update({result_key: 'FAIL', 'startup_cleanup_errors': cleanup_errors.copy()})
+ save(data)
+ except Exception:
+ pass
+ if cleanup_errors and startup_error is None:
+ raise RuntimeError('Startup cleanup or receipt failed; subsequent probes cannot run.') from None
+
+
+def successful_junit(report):
+ if not report.is_file() or report.stat().st_size > 1024 * 1024:
+ raise RuntimeError('Missing or oversized native JUnit report.')
+ root = ET.parse(report).getroot()
+ for suite in root.iter():
+ if suite.tag in ['testsuite', 'testsuites']:
+ for attribute in ['failures', 'errors', 'skipped', 'disabled']:
+ if int(suite.get(attribute, '0')) != 0:
+ raise RuntimeError('Native JUnit declares unsuccessful cases.')
+ cases = list(root.iter('testcase'))
+ if not cases or any(list(root.iter(tag)) for tag in ['failure', 'error', 'skipped']) or any(
+ case.get('status', 'SUCCESS').upper() != 'SUCCESS' for case in cases):
+ raise RuntimeError('Maestro did not produce a complete successful native report.')
+ return len(cases)
+
+
+def probe():
+ smoke('probe')
+
+
+def features():
+ smoke('features')
+
+
+def main():
+ if PLATFORM not in APP_IDS or len(sys.argv) != 2 or sys.argv[1] not in ['record', 'prepare', 'driver', 'build', 'smoke', 'probe', 'features']:
+ raise RuntimeError('Expected a hosted platform and record|prepare|driver|build|smoke|probe|features.')
+ os.environ.update({'ENVFILE': '.env.ci', 'RCT_NO_LAUNCH_PACKAGER': '1',
+ 'RCT_NEW_ARCH_ENABLED': '1', 'MAESTRO_CLI_NO_ANALYTICS': '1'})
+ run_phase(sys.argv[1])
+
+
+def run_phase(phase):
+ try:
+ globals()[phase]()
+ except Exception:
+ try:
+ if EVIDENCE.exists():
+ evidence = read()
+ evidence['failed_phase'] = phase
+ if phase in ['build', 'smoke', 'probe', 'features']:
+ evidence['r5_features' if phase == 'features' else 'native_probe' if phase == 'probe' else phase] = 'FAIL'
+ save(evidence)
+ except Exception:
+ pass
+ raise
+
+
+if __name__ == '__main__':
+ try:
+ main()
+ except Exception:
+ # Unexpected exceptions can contain private paths or process output too.
+ print('Hosted native validation failed; inspect phase status and fixed diagnostic categories.', file=sys.stderr)
+ sys.exit(1)
diff --git a/.github/native/install_diagnosis.py b/.github/native/install_diagnosis.py
new file mode 100644
index 0000000000..ea1df541f6
--- /dev/null
+++ b/.github/native/install_diagnosis.py
@@ -0,0 +1,249 @@
+"""Observe one unchanged simulator install; export only fixed, bounded facts.
+
+The caller supplies its live harness context. This module never imports another
+hosted_native instance, changes the install deadline, retries, opens Simulator,
+or changes simulator/app services. Raw process/log output stays private.
+"""
+
+from concurrent.futures import ThreadPoolExecutor, TimeoutError as FutureTimeoutError
+import hashlib
+import math
+import os
+from pathlib import Path
+import re
+import signal
+import shutil
+import subprocess
+import time
+
+
+SNAPSHOT_SECONDS = 60
+LIMIT = 1024 * 1024
+APP_ID = 'io.hexawallet.hexakeeper.dev'
+DOMAINS = {
+ 'CORE_SIMULATOR': 'com.apple.CoreSimulator.SimError',
+ 'MOBILE_INSTALLATION': 'MIInstallerErrorDomain',
+ 'INSTALL_COORDINATION': 'IXErrorDomain',
+ 'USER_PRESENTABLE_INSTALL': 'IXUserPresentableErrorDomain',
+ 'LAUNCH_SERVICES': 'LSApplicationWorkspaceErrorDomain',
+ 'COCOA': 'NSCocoaErrorDomain',
+ 'POSIX': 'NSPOSIXErrorDomain',
+}
+CATEGORIES = {
+ 'INSTALL_FAILED': r'failed to install|could not install|installation failed',
+ 'BUNDLE_VALIDATION_FAILED': r'bundle.*(?:invalid|validation failed)|invalid.*(?:bundle|executable)',
+ 'SIGNATURE_VERIFICATION_FAILED': r'applicationverificationfailed|invalid code signature|signature.*(?:invalid|verification failed)',
+ 'SERVICE_CONNECTION_FAILED': r'connection.*(?:invalidated|interrupted|refused|timed out)|failed to connect|service.*not available',
+ 'CONTAINER_SERVICE_FAILED': r'(?:container|containermanager).*\b(?:error|failed|unavailable)\b',
+ 'PERMISSION_DENIED': r'permission denied|operation not permitted|not authorized',
+ 'DISK_SPACE_EXHAUSTED': r'no space left on device|not enough (?:free )?(?:disk )?space',
+ 'RESOURCE_BUSY': r'resource busy|device busy|another installation.*in progress',
+ 'DEVICE_NOT_BOOTED': r'device.*(?:not booted|shutdown|unavailable)|invalid device state',
+ 'INSTALL_COORDINATION_REFERENCE': r'(?:install coordination|IXCoordinator|IXSClient|IXClient)',
+}
+STACK_MARKERS = {
+ 'CORE_SIMULATOR': r'CoreSimulator|SimDevice|SimServiceContext',
+ 'MOBILE_INSTALLATION': r'MobileInstallation|MIClient|installApplication|installBundle',
+ 'INSTALL_COORDINATION': r'InstallCoordination|IXCoordinator|IXSClient|IXClient',
+ 'CONTAINER_SERVICE': r'MobileContainerManager|MCMClient|containermanager',
+ 'LAUNCH_SERVICES': r'LaunchServices|LSApplication|_LSServer',
+ 'SIGNATURE_VERIFICATION': r'MISValidate|SecStaticCode|AMFI',
+ 'XPC_SYNC_WAIT': r'xpc_connection_send_message_with_reply_sync',
+ 'MACH_WAIT': r'mach_msg|mach_msg2_trap',
+ 'DISPATCH_WAIT': r'dispatch_sync|dispatch_semaphore_wait|dispatch_group_wait',
+ 'LOCK_WAIT': r'__psynch_mutexwait|__ulock_wait|pthread_mutex_lock',
+}
+
+
+def _error(error):
+ name = type(error).__name__
+ return name if name in {'RuntimeError', 'OSError', 'ValueError', 'TypeError',
+ 'FileNotFoundError', 'PermissionError', 'TimeoutExpired'} else 'OTHER_ERROR'
+
+
+def _classify(payload):
+ categories = [name for name, pattern in CATEGORIES.items()
+ if re.search(pattern, payload, re.IGNORECASE)]
+ codes = {}
+ for name, domain in DOMAINS.items():
+ matches = re.findall(r'Domain\s*=\s*' + re.escape(domain) + r'\s+Code\s*=\s*(-?\d+)\b',
+ payload, re.IGNORECASE)
+ values = list(dict.fromkeys(int(value) for value in matches if len(value) <= 6
+ and -65535 <= int(value) <= 65535))[:4]
+ if values:
+ codes[name] = values
+ return {'categories': categories, 'error_domain_codes': codes}
+
+
+def _bounded(context, path):
+ if path.is_symlink() or not path.resolve().is_relative_to(Path(context.PRIVATE).resolve()):
+ raise ValueError('Expected private diagnostic file.')
+ size_before = path.stat().st_size
+ with path.open('rb') as source:
+ payload = source.read(LIMIT)
+ size_after = path.stat().st_size
+ text = payload.decode(errors='replace')
+ return text, {'bytes': size_after, 'prefix_bytes': len(payload),
+ 'truncated': size_after > len(payload), 'grew_during_read': size_after != size_before,
+ 'prefix_sha256': hashlib.sha256(payload).hexdigest(), **_classify(text)}
+
+
+def _capture(context, args, label, prefix, timeout):
+ path = Path(context.PRIVATE) / (prefix + '-' + label + '.log')
+ facts = {'label': label}
+ started = time.monotonic()
+ try:
+ if path.is_symlink():
+ raise ValueError('Expected private diagnostic output.')
+ with path.open('wb') as output:
+ proc = subprocess.Popen(args, stdout=output, stderr=subprocess.STDOUT, start_new_session=True)
+ try:
+ facts['exit_code'] = proc.wait(timeout=timeout)
+ except subprocess.TimeoutExpired:
+ os.killpg(proc.pid, signal.SIGKILL)
+ proc.wait()
+ facts['exit_code'] = 124
+ payload, result = _bounded(context, path)
+ facts.update(result)
+ return payload, facts
+ except Exception as error:
+ facts['error_type'] = _error(error)
+ return '', facts
+ finally:
+ facts['duration_seconds'] = round(time.monotonic() - started, 2)
+
+
+def _baseline(context, device, prefix):
+ facts = {'commands': [], 'resource_errors': []}
+ try:
+ facts['disk_free_bytes'] = shutil.disk_usage(context.PRIVATE).free
+ except Exception as error:
+ facts['resource_errors'].append({'stage': 'disk', 'error_type': _error(error)})
+ try:
+ values = os.getloadavg()
+ if len(values) != 3 or not all(math.isfinite(value) for value in values):
+ raise ValueError('Expected finite host load observations.')
+ facts['host_load_1_5_15m'] = [round(value, 2) for value in values]
+ except Exception as error:
+ facts['resource_errors'].append({'stage': 'host_load', 'error_type': _error(error)})
+ for args, label in [
+ (['xcrun', 'simctl', 'listapps', device], 'baseline-listapps'),
+ (['xcrun', 'simctl', 'get_app_container', device, 'com.apple.Preferences', 'app'],
+ 'baseline-preferences-container'),
+ ]:
+ _, result = _capture(context, args, label, prefix, 5)
+ facts['commands'].append(result)
+ return facts
+
+
+def _collect(context, device, prefix, command_log):
+ facts = {'commands': [], 'collection_errors': []}
+
+ def command(args, label, timeout):
+ payload, result = _capture(context, args, label, prefix, timeout)
+ facts['commands'].append(result)
+ return payload, result
+
+ ps, result = command(['ps', '-axo', 'pid=,stat=,args='], 'processes', 3)
+ pattern = re.compile(r'^\s*(\d+)\s+(\S+)\s+(.*)$')
+ owned = []
+ for line in ps.splitlines():
+ match = pattern.match(line)
+ if match and re.search(r'(?:^|[/\s])simctl\s+install\s+' + re.escape(device) + r'(?=\s|$)', match[3]):
+ owned.append((int(match[1]), match[2]))
+ known = result.get('exit_code') == 0
+ facts['owned_install_process_count'] = len(owned) if known else None
+ facts['owned_install_running'] = any('Z' not in state for _, state in owned) if known else None
+ if len(owned) == 1 and 'Z' not in owned[0][1]:
+ sample_path = Path(context.PRIVATE) / (prefix + '-install.sample')
+ command(['sample', str(owned[0][0]), '3', '1', '-file', str(sample_path)], 'install-sample', 8)
+ try:
+ payload, result = _bounded(context, sample_path)
+ result['stack_categories'] = [name for name, marker in STACK_MARKERS.items()
+ if re.search(marker, payload, re.IGNORECASE)]
+ facts['install_sample'] = result
+ except Exception as error:
+ facts['collection_errors'].append({'stage': 'install_sample', 'error_type': _error(error)})
+ launchctl, result = command(['xcrun', 'simctl', 'spawn', device, 'launchctl', 'list'], 'simulator-services', 4)
+ facts['services'] = {}
+ for name, identifier in [('installd', 'com.apple.mobile.installd'), ('appinstalld', 'com.apple.appinstalld'),
+ ('lsd', 'com.apple.lsd')]:
+ rows = [line.split() for line in launchctl.splitlines() if line.split()[-1:] == [identifier]]
+ facts['services'][name] = {
+ 'entries': len(rows) if result.get('exit_code') == 0 else None,
+ 'running': any(row[0].isdigit() and int(row[0]) > 0 for row in rows)
+ if result.get('exit_code') == 0 else None,
+ }
+ host_predicate = '(process == "CoreSimulatorService" OR process == "simctl") AND eventMessage CONTAINS "' + device + '"'
+ command(['log', 'show', '--style', 'compact', '--last', '3m', '--predicate', host_predicate], 'owned-host-events', 5)
+ command(['xcrun', 'simctl', 'spawn', device, 'log', 'show', '--style', 'compact', '--last', '3m',
+ '--predicate', 'process == "installd" OR process == "appinstalld" OR process == "lsd"'],
+ 'simulator-install-events', 8)
+ try:
+ _, facts['install_command_output'] = _bounded(context, command_log)
+ except Exception as error:
+ facts['collection_errors'].append({'stage': 'install_command_output', 'error_type': _error(error)})
+ return facts
+
+
+def observe(context, device, args, label, timeout=120):
+ """Call context.command once with the original install argv and deadline.
+
+ Missing observation persistence blocks this diagnostic path after an install
+ succeeds. It cannot replace an original install exception or grant UI credit.
+ """
+ if (not re.fullmatch(r'[A-Fa-f0-9]{8}(?:-[A-Fa-f0-9]{4}){3}-[A-Fa-f0-9]{12}', device)
+ or list(args[:4]) != ['xcrun', 'simctl', 'install', device] or len(args) != 5):
+ raise ValueError('Expected the owned simulator app install command.')
+ index = len(context.read()['commands']) + 1
+ prefix = 'install-diagnosis-%03d' % index
+ command_log = Path(context.PRIVATE) / ('command-%03d.log' % index)
+ facts = {'scope': 'Read-only install observation; no UI or installed-byte acceptance.',
+ 'command_index': index, 'collection_errors': []}
+ original_error = None
+ try:
+ try:
+ facts['baseline'] = _baseline(context, device, prefix)
+ except Exception as error:
+ facts['collection_errors'].append({'stage': 'baseline', 'error_type': _error(error)})
+ with ThreadPoolExecutor(max_workers=1) as executor:
+ future = executor.submit(context.command, args, label, timeout=timeout)
+ try:
+ result = future.result(timeout=SNAPSHOT_SECONDS)
+ except FutureTimeoutError:
+ pass
+ except Exception as error:
+ original_error = error
+ else:
+ facts['command_returned'] = True
+ facts['snapshot_phase'] = 'DURING_INSTALL' if not future.done() else 'AFTER_INSTALL_COMMAND'
+ facts['install_running_before_collection'] = not future.done()
+ try:
+ facts['snapshot'] = _collect(context, device, prefix, command_log)
+ except Exception as error:
+ facts['collection_errors'].append({'stage': 'snapshot', 'error_type': _error(error)})
+ facts['install_running_after_collection'] = not future.done()
+ try:
+ result = future.result()
+ except Exception as error:
+ original_error = error
+ facts['command_error_type'] = _error(error)
+ raise
+ else:
+ facts['command_returned'] = True
+ return result
+ finally:
+ try:
+ _, lookup = _capture(context, ['xcrun', 'simctl', 'get_app_container', device, APP_ID, 'app'],
+ 'post-install-container', prefix, 5)
+ code = lookup.get('exit_code')
+ lookup['state'] = 'SUCCESS' if code == 0 else 'TIMEOUT' if code == 124 else 'ERROR' if code is None else 'FAIL'
+ facts['post_install_lookup'] = lookup
+ data = context.read()
+ data.setdefault('install_diagnoses', []).append(facts)
+ context.save(data)
+ except Exception:
+ if original_error is None:
+ raise RuntimeError('Bounded install diagnostics could not be saved.') from None
+ # Never replace the original install failure with a collector error.
+ print('Bounded install diagnostics could not be saved.', flush=True)
diff --git a/.github/native/nodeify.cjs b/.github/native/nodeify.cjs
new file mode 100644
index 0000000000..d24127bf11
--- /dev/null
+++ b/.github/native/nodeify.cjs
@@ -0,0 +1,33 @@
+#!/usr/bin/env node
+'use strict';
+
+const path = require('node:path');
+
+// Match setup.sh's existing polyfills without invoking its dependency installer.
+// The unfiltered --hack command selects every core shim, including packages this
+// app does not depend on, and makes valid imports such as constants unresolvable.
+const SHIMS = Object.freeze([
+ 'buffer', 'events', 'process', 'stream', 'inherits', 'path', 'assert', 'crypto',
+]);
+
+function runNodeify(root = path.resolve(__dirname, '../..')) {
+ if (process.cwd() !== root) {
+ throw new Error('Run native Node compatibility preparation from the repository root.');
+ }
+ const cli = require.resolve('rn-nodeify/cmd.js', { paths: [root] });
+ const coreList = require.resolve(path.join(path.dirname(cli), 'coreList.js'));
+ require(coreList);
+ require.cache[coreList].exports = [...SHIMS];
+ const originalArguments = process.argv;
+ try {
+ // No --install flag: the pinned upstream CLI can apply its existing module
+ // and file compatibility fixes, but cannot enter installShims().
+ process.argv = [process.execPath, cli, '--hack'];
+ require(cli);
+ } finally {
+ process.argv = originalArguments;
+ }
+}
+
+module.exports = { runNodeify, SHIMS };
+if (require.main === module) runNodeify();
diff --git a/.github/native/product_credential_acceptance.py b/.github/native/product_credential_acceptance.py
new file mode 100644
index 0000000000..a9f5b49f46
--- /dev/null
+++ b/.github/native/product_credential_acceptance.py
@@ -0,0 +1,193 @@
+"""Malformed native-credential companion. No standalone device or account setup.
+
+The parent owns the device, normal Metro process, disposable backend and eventual
+device erasure. switch_entrypoint accepts arm/restore/product, stops that app and
+Metro group, and starts the corresponding committed config. It must return only
+after the selected bundle is warm. PRODUCT means the ordinary index.js bundle.
+"""
+import importlib.util
+import json
+import os
+from pathlib import Path
+import re
+import shutil
+import subprocess
+import threading
+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
+
+PORT = 8767
+STAGES = ('malformed_startup_blocked', 'retry_remains_blocked', 'malformed_cold_start_blocked',
+ 'restored_login_available', 'restored_wallet_preserved', 'restored_cold_wallet_preserved')
+
+
+class Receipt:
+ def __init__(self):
+ self.lock = threading.Lock()
+ self.completed = []
+ self.phases = []
+
+ def phase(self, value):
+ with self.lock:
+ expected = ['armed', 'restored']
+ if len(self.phases) >= 2 or value != expected[len(self.phases)]:
+ raise RuntimeError('PRODUCT_CREDENTIAL_PHASE_ORDER')
+ if value == 'restored' and self.completed != list(STAGES[:3]):
+ raise RuntimeError('PRODUCT_CREDENTIAL_BLOCKING_CHECKS_REQUIRED')
+ self.phases.append(value)
+
+ def mark(self, stage):
+ with self.lock:
+ required = ['armed'] if len(self.completed) < 3 else ['armed', 'restored']
+ if (self.phases != required or len(self.completed) >= len(STAGES) or
+ stage != STAGES[len(self.completed)]):
+ return False
+ self.completed.append(stage)
+ return True
+
+ def snapshot(self, passed=False):
+ with self.lock:
+ if passed and (self.completed != list(STAGES) or self.phases != ['armed', 'restored']):
+ raise RuntimeError('PRODUCT_CREDENTIAL_INCOMPLETE')
+ return {'status': 'PASS' if passed else 'FAIL', 'completed_stages': list(self.completed),
+ 'fixture_phases': list(self.phases), 'entrypoint_under_test': 'index.js',
+ 'scenario': 'ACTUAL_KEYCHAIN_CONTROLLED_MALFORMED_JSON',
+ 'native_credential_api': 'react-native-keychain',
+ 'original_credential_exported': False,
+ 'backup_service_removed_after_verified_restore': passed,
+ 'visible_wallet_count_after_recovery_and_cold_login': 1 if passed else None,
+ 'successfully_empty_store': 'REJECTED_FIXTURE_PRECONDITION_NOT_A_READ_ERROR',
+ 'retry_scope': 'User taps Retry while malformed value persists; blocking UI remains. Native read-call count is not instrumented.',
+ 'os_keychain_denial_or_hardware_read_fault': 'NOT RUN',
+ 'same_process_retry_after_external_repair': 'NOT RUN',
+ 'physical_devices': 'NOT RUN', 'backend_compatibility': 'NOT TESTED'}
+
+
+def make_server(receipt, port=PORT):
+ class Handler(BaseHTTPRequestHandler):
+ def log_message(self, *_):
+ pass
+
+ def reply(self, status):
+ self.send_response(status)
+ self.send_header('Content-Length', '0')
+ self.end_headers()
+
+ def do_POST(self):
+ try:
+ length = int(self.headers.get('Content-Length', '0'))
+ if self.path != '/metric' or not 0 < length <= 128:
+ self.close_connection = True
+ return self.reply(422)
+ metric = json.loads(self.rfile.read(length))
+ if (isinstance(metric, dict) and set(metric) == {'stage'} and
+ receipt.mark(metric['stage'])):
+ return self.reply(200)
+ except (ValueError, TypeError):
+ pass
+ self.reply(422)
+
+ def do_GET(self):
+ self.reply(405)
+
+ class Server(ThreadingHTTPServer):
+ allow_reuse_address = False
+ daemon_threads = True
+ return Server(('127.0.0.1', port), Handler)
+
+
+def run_companion(h, data, device, private, backend_receipt, switch_entrypoint):
+ if (os.environ.get('GITHUB_ACTIONS') != 'true' or
+ os.environ.get('RUNNER_ENVIRONMENT') != 'github-hosted' or
+ h.PLATFORM not in ('IOS', 'ANDROID') or
+ not re.fullmatch(r'emulator-[0-9]+' if h.PLATFORM == 'ANDROID' else
+ r'[A-Fa-f0-9]{8}(?:-[A-Fa-f0-9]{4}){3}-[A-Fa-f0-9]{12}', device)):
+ raise RuntimeError('PRODUCT_CREDENTIAL_OWNED_HOSTED_DEVICE_REQUIRED')
+ actual = subprocess.check_output(['git', 'rev-parse', 'HEAD'], cwd=h.ROOT, text=True).strip()
+ if (data['build'] != 'PASS' or actual != data['source_sha'] or
+ actual != os.environ.get('KEEPER_SOURCE_SHA') or
+ h.artifact_identity() != data['built_artifact']):
+ raise RuntimeError('PRODUCT_CREDENTIAL_EXACT_BUILD_REQUIRED')
+ if subprocess.run(['git', 'diff', '--quiet', 'HEAD', '--', '.github/native', 'src',
+ 'index.js', 'App.tsx', 'metro.config.js', 'babel.config.js'],
+ cwd=h.ROOT, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL).returncode:
+ raise RuntimeError('PRODUCT_CREDENTIAL_COMMITTED_SOURCE_REQUIRED')
+ before = backend_receipt.snapshot(passed=True)
+ if (before.get('sample') != 6 or before.get('status') != 'PASS' or
+ before.get('scenario') != 'CONTROLLED_DISCONNECT_BEFORE_COMMIT_NOT_WAN_OFFLINE' or
+ before.get('create_new_app_calls') != 2 or
+ before.get('visible_wallet_count_after_relaunch') != 1 or
+ h.read().get('product_key_ui', {}).get('status') != 'PASS'):
+ raise RuntimeError('PRODUCT_CREDENTIAL_PRIOR_DISPOSABLE_UI_REQUIRED')
+ spec = importlib.util.spec_from_file_location('product_key_acceptance',
+ Path(__file__).with_name('product_key_acceptance.py'))
+ helper = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(helper)
+ receipt = Receipt()
+ output = Path(private) / 'credential-ui'
+ output.mkdir(mode=0o700)
+ result = receipt.snapshot()
+ result['status'] = 'RUNNING'
+ server = None
+
+ def save():
+ current = h.read()
+ current['product_credential_ui'] = result
+ h.save(current)
+
+ def flow(filename, stage=None):
+ folder = output / (filename.removesuffix('.yaml') + ('-' + stage if stage else ''))
+ folder.mkdir()
+ report = folder / 'junit.xml'
+ arguments = [data['maestro']['binary'], '--device', device, 'test',
+ '--env', 'APP_ID=' + h.APP_IDS[h.PLATFORM]]
+ if stage:
+ arguments += ['--env', 'FIXTURE_STAGE=' + stage]
+ h.command([*arguments, '--flatten-debug-output', '--debug-output', str(folder),
+ '--test-output-dir', str(folder), '--format', 'junit', '--output', str(report),
+ '.github/native/' + filename], 'Disposable credential acceptance phase',
+ timeout=240, error_details=False)
+ h.successful_junit(report)
+
+ try:
+ save()
+ installed_before = helper.installed_proof(h, device)
+ if h.PLATFORM == 'ANDROID':
+ h.command(['adb', '-s', device, 'reverse', 'tcp:8767', 'tcp:8767'],
+ 'Connect owned credential receipt endpoint', error_details=False)
+ server = make_server(receipt)
+ threading.Thread(target=server.serve_forever, daemon=True).start()
+ switch_entrypoint('arm')
+ flow('credential_fixture.yaml', 'armed')
+ receipt.phase('armed')
+ switch_entrypoint('product')
+ flow('product_credential_blocked.yaml')
+ switch_entrypoint('restore')
+ flow('credential_fixture.yaml', 'restored')
+ receipt.phase('restored')
+ switch_entrypoint('product')
+ flow('product_credential_recovered.yaml')
+ if h.artifact_identity() != data['built_artifact']:
+ raise RuntimeError('PRODUCT_CREDENTIAL_ARTIFACT_CHANGED')
+ installed_after = helper.installed_proof(h, device)
+ if installed_after != installed_before:
+ raise RuntimeError('PRODUCT_CREDENTIAL_INSTALLED_BYTES_CHANGED')
+ after = backend_receipt.snapshot(passed=True)
+ if after['create_new_app_calls'] != before['create_new_app_calls']:
+ raise RuntimeError('PRODUCT_CREDENTIAL_UNEXPECTED_ACCOUNT_SETUP')
+ result = receipt.snapshot(passed=True)
+ result.update(new_account_requests_during_credential_flow=0,
+ installed_artifact_verified=True, installed_artifact=installed_after)
+ except Exception as error:
+ result = receipt.snapshot()
+ result['failure_category'] = type(error).__name__
+ raise
+ finally:
+ operations = []
+ if server:
+ operations += [('server-shutdown', server.shutdown), ('server-close', server.server_close)]
+ # On any failure the parent destroys this owned device, including its
+ # test-only backup service. Do not inspect, pull or print Keychain files.
+ operations.append(('private-output', lambda: shutil.rmtree(output)))
+ helper.finalize_companion(result, save, operations, 'failure_category' in result,
+ 'PRODUCT_CREDENTIAL_CLEANUP_FAILED')
+ return result
diff --git a/.github/native/product_credential_blocked.yaml b/.github/native/product_credential_blocked.yaml
new file mode 100644
index 0000000000..d36ef4ab70
--- /dev/null
+++ b/.github/native/product_credential_blocked.yaml
@@ -0,0 +1,41 @@
+# Ordinary index.js after a separate device-only malformed Keychain write.
+appId: ${APP_ID}
+name: Normal app blocks malformed credentials and Retry cannot create an account
+---
+- launchApp
+- extendedWaitUntil:
+ visible: Unable to check your passcode. Please try again.
+ timeout: 60000
+- assertVisible: Something went wrong
+- assertNotVisible: Create a passcode
+- assertNotVisible: Enter your passcode
+- assertNotVisible:
+ id: home_visible_wallet_count_1
+- runScript:
+ file: product_credential_metric.js
+ env:
+ STAGE: malformed_startup_blocked
+- tapOn: Retry
+- extendedWaitUntil:
+ visible: Unable to check your passcode. Please try again.
+ timeout: 30000
+- assertNotVisible: Create a passcode
+- assertNotVisible: Enter your passcode
+- assertNotVisible:
+ id: home_visible_wallet_count_1
+- runScript:
+ file: product_credential_metric.js
+ env:
+ STAGE: retry_remains_blocked
+- stopApp
+- launchApp
+- extendedWaitUntil:
+ visible: Unable to check your passcode. Please try again.
+ timeout: 60000
+- assertNotVisible: Create a passcode
+- assertNotVisible: Enter your passcode
+- runScript:
+ file: product_credential_metric.js
+ env:
+ STAGE: malformed_cold_start_blocked
+- stopApp
diff --git a/.github/native/product_credential_metric.js b/.github/native/product_credential_metric.js
new file mode 100644
index 0000000000..fa89cd335e
--- /dev/null
+++ b/.github/native/product_credential_metric.js
@@ -0,0 +1,6 @@
+// Fixed stages only. No credential bytes, identifiers, PINs or screenshots.
+const reply = http.post('http://127.0.0.1:8767/metric', {
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ stage: STAGE }),
+});
+if (reply.status !== 200) throw new Error('PRODUCT_CREDENTIAL_METRIC_REJECTED');
diff --git a/.github/native/product_credential_recovered.yaml b/.github/native/product_credential_recovered.yaml
new file mode 100644
index 0000000000..9bd2c91747
--- /dev/null
+++ b/.github/native/product_credential_recovered.yaml
@@ -0,0 +1,51 @@
+# Original device-only Keychain value restored; ordinary index.js is mandatory.
+appId: ${APP_ID}
+name: Normal app recovers the same disposable wallet after credential restoration
+---
+- launchApp
+- extendedWaitUntil:
+ visible: Enter your passcode
+ timeout: 60000
+- assertNotVisible: Create a passcode
+- assertNotVisible: Unable to check your passcode. Please try again.
+- runScript:
+ file: product_credential_metric.js
+ env:
+ STAGE: restored_login_available
+- repeat:
+ times: 4
+ commands:
+ - tapOn:
+ id: key_1
+- tapOn: Proceed
+- extendedWaitUntil:
+ visible:
+ id: home_visible_wallet_count_1
+ timeout: 60000
+- assertVisible: Mobile Wallet
+- runScript:
+ file: product_credential_metric.js
+ env:
+ STAGE: restored_wallet_preserved
+- stopApp
+- launchApp
+- extendedWaitUntil:
+ visible: Enter your passcode
+ timeout: 60000
+- assertNotVisible: Create a passcode
+- repeat:
+ times: 4
+ commands:
+ - tapOn:
+ id: key_1
+- tapOn: Proceed
+- extendedWaitUntil:
+ visible:
+ id: home_visible_wallet_count_1
+ timeout: 60000
+- assertVisible: Mobile Wallet
+- runScript:
+ file: product_credential_metric.js
+ env:
+ STAGE: restored_cold_wallet_preserved
+- stopApp
diff --git a/.github/native/product_first_wallet.yaml b/.github/native/product_first_wallet.yaml
new file mode 100644
index 0000000000..d2f409f235
--- /dev/null
+++ b/.github/native/product_first_wallet.yaml
@@ -0,0 +1,166 @@
+# Full packaged app, ordinary index.js/production reducers/sagas/Realm. PIN1111
+# belongs only to the runner-created disposable installation. Never reveal seeds.
+appId: ${APP_ID}
+name: Full app startup first wallet and cold persistence
+---
+- runScript:
+ file: product_metric.js
+ env:
+ STAGE: startup_start
+- launchApp:
+ permissions:
+ all: deny
+- extendedWaitUntil:
+ visible: Create a passcode
+ timeout: 180000
+- runScript:
+ file: product_metric.js
+ env:
+ STAGE: startup_ready
+- runFlow: product_prepare_pin.yaml
+- runScript:
+ file: product_metric.js
+ env:
+ STAGE: wallet_start
+- tapOn:
+ id: view_startNewTile
+- extendedWaitUntil:
+ visible: Next
+ timeout: 180000
+- runScript:
+ file: product_metric.js
+ env:
+ STAGE: wallet_ready
+- tapOn: Next
+- extendedWaitUntil:
+ visible: Protect Your Recovery Key
+ timeout: 30000
+- tapOn: Skip for Now
+- extendedWaitUntil:
+ visible: Continue Without Backup?
+ timeout: 30000
+- tapOn: Skip Backup
+- extendedWaitUntil:
+ visible:
+ id: home_visible_wallet_count_1
+ timeout: 30000
+- assertVisible: Mobile Wallet
+- runScript:
+ file: product_metric.js
+ env:
+ STAGE: home_ready
+- stopApp
+- runScript:
+ file: product_metric.js
+ env:
+ STAGE: relaunch_start
+- launchApp
+- extendedWaitUntil:
+ visible: Enter your passcode
+ timeout: 60000
+- runScript:
+ file: product_metric.js
+ env:
+ STAGE: relaunch_login
+- repeat:
+ times: 4
+ commands:
+ - tapOn:
+ id: key_1
+- tapOn: Proceed
+- extendedWaitUntil:
+ visible:
+ id: home_visible_wallet_count_1
+ timeout: 60000
+- assertVisible: Mobile Wallet
+- runScript:
+ file: product_metric.js
+ env:
+ STAGE: relaunch_home
+- tapOn:
+ id: home_tab_more
+- tapOn:
+ id: home_tab_wallets
+- extendedWaitUntil:
+ visible:
+ id: home_visible_wallet_count_1
+ timeout: 30000
+- assertVisible: Mobile Wallet
+- tapOn:
+ id: home_tab_more
+- scrollUntilVisible:
+ element:
+ id: btn_setting_App Settings
+ direction: DOWN
+ timeout: 30000
+- tapOn:
+ id: btn_setting_App Settings
+- extendedWaitUntil:
+ visible:
+ id: btn_setting_Version History
+ timeout: 30000
+- tapOn:
+ id: btn_setting_Version History
+- extendedWaitUntil:
+ visible:
+ id: text_installedAppVersionLabel
+ text: Installed app version
+ timeout: 30000
+- assertVisible:
+ id: text_installedAppVersion
+ text: ${EXPECTED_INSTALLED_REGEX}
+- assertVisible:
+ id: view_VersionHistoryList
+- assertVisible: Initially installed
+- assertVisible:
+ text: ${EXPECTED_HISTORY_REGEX}
+- runScript:
+ file: product_metric.js
+ env:
+ STAGE: version_history_verified
+- tapOn:
+ id: btn_back
+- extendedWaitUntil:
+ visible:
+ id: btn_setting_Version History
+ timeout: 30000
+- tapOn:
+ id: btn_back
+- tapOn:
+ id: home_tab_keys
+- extendedWaitUntil:
+ visible:
+ id: manage_keys_actions
+ timeout: 30000
+- tapOn:
+ id: manage_keys_actions
+- extendedWaitUntil:
+ visible:
+ id: header_title
+ text: Manage Keys
+ timeout: 30000
+# The only fresh signer is Recovery Key, excluded by DeleteKeys' production
+# filters. Check safe discovery/back navigation; never create a deletion intent.
+- assertNotVisible: Delete
+- tapOn:
+ id: btn_back
+- extendedWaitUntil:
+ visible:
+ id: manage_keys_actions
+ timeout: 30000
+- runScript:
+ file: product_metric.js
+ env:
+ STAGE: key_management_entry_verified
+- tapOn:
+ id: home_tab_wallets
+- extendedWaitUntil:
+ visible:
+ id: home_visible_wallet_count_1
+ timeout: 30000
+- assertVisible: Mobile Wallet
+- runScript:
+ file: product_metric.js
+ env:
+ STAGE: navigation_verified
+- stopApp
diff --git a/.github/native/product_history_acceptance.py b/.github/native/product_history_acceptance.py
new file mode 100644
index 0000000000..3f18aeebbd
--- /dev/null
+++ b/.github/native/product_history_acceptance.py
@@ -0,0 +1,123 @@
+"""Controlled stale/empty native Realm histories, followed by ordinary app login.
+
+This companion is deliberately separate from first-wallet measurements. The
+runner owns Metro/app switching, the exact installed artifact, and the device.
+Fixture entries change VersionHistory only; normal index.js performs observation.
+"""
+import importlib.util
+import os
+from pathlib import Path
+import shutil
+import subprocess
+
+PHASES = (
+ 'history_seed_stale', 'stale_first_ui', 'history_verify_stale_first',
+ 'stale_repeat_ui', 'history_verify_stale_repeat', 'history_seed_empty',
+ 'empty_first_ui', 'history_verify_empty_first', 'empty_repeat_ui',
+ 'history_verify_empty_repeat', 'history_restore', 'history_verify_restored',
+)
+
+
+def run_companion(h, data, device, private, backend_receipt, switch_entrypoint):
+ if (os.environ.get('GITHUB_ACTIONS') != 'true' or
+ os.environ.get('RUNNER_ENVIRONMENT') != 'github-hosted' or
+ h.PLATFORM not in ['IOS', 'ANDROID'] or
+ (h.PLATFORM == 'ANDROID' and not device.startswith('emulator-'))):
+ raise RuntimeError('PRODUCT_HISTORY_OWNED_HOSTED_DEVICE_REQUIRED')
+ actual = subprocess.check_output(['git', 'rev-parse', 'HEAD'], cwd=h.ROOT, text=True).strip()
+ if (data['build'] != 'PASS' or actual != data['source_sha'] or
+ actual != os.environ.get('KEEPER_SOURCE_SHA') or
+ h.artifact_identity() != data['built_artifact']):
+ raise RuntimeError('PRODUCT_HISTORY_EXACT_BUILD_REQUIRED')
+ if subprocess.run(['git', 'diff', '--quiet', 'HEAD', '--', '.github/native', 'src',
+ 'index.js', 'App.tsx', 'metro.config.js', 'babel.config.js', 'release/version.json'],
+ cwd=h.ROOT, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL).returncode:
+ raise RuntimeError('PRODUCT_HISTORY_COMMITTED_SOURCE_REQUIRED')
+ before = backend_receipt.snapshot(passed=True)
+ if (before.get('status') != 'PASS' or before.get('sample') != 6 or
+ before.get('scenario') != 'CONTROLLED_DISCONNECT_BEFORE_COMMIT_NOT_WAN_OFFLINE' or
+ before.get('create_new_app_calls') != 2 or
+ before.get('visible_wallet_count_after_relaunch') != 1):
+ raise RuntimeError('PRODUCT_HISTORY_DISPOSABLE_RETRY_FIXTURE_REQUIRED')
+ spec = importlib.util.spec_from_file_location(
+ 'product_key_acceptance', Path(__file__).with_name('product_key_acceptance.py'))
+ key_ui = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(key_ui)
+ measure_spec = importlib.util.spec_from_file_location(
+ 'product_measurements', Path(__file__).with_name('product_measurements.py'))
+ measurements = importlib.util.module_from_spec(measure_spec)
+ measure_spec.loader.exec_module(measurements)
+ import json
+ expected = measurements.version_expectation(
+ json.loads((h.ROOT / 'release/version.json').read_text()), h.PLATFORM)
+ output = Path(private) / 'history-ui'
+ output.mkdir(mode=0o700)
+ result = {'status': 'RUNNING', 'completed_stages': [], 'stage_evidence': [],
+ 'scenario': 'CONTROLLED_STALE_AND_EMPTY_NATIVE_VERSION_HISTORY',
+ 'product_entrypoint': 'index.js', 'network': 'TESTNET',
+ 'fixture_scope': 'Actual encrypted native Realm histories only; unchanged KeeperApp and shared version. Not an authentic historical installation or migration test.',
+ 'credentials_exported': False, 'physical_devices': 'NOT RUN',
+ 'performance_sample': False}
+
+ def save():
+ state = h.read()
+ state['product_version_history_ui'] = result
+ h.save(state)
+
+ try:
+ save()
+ installed = key_ui.installed_proof(h, device)
+ for stage in PHASES:
+ fixture = stage.startswith('history_')
+ switch_entrypoint(stage if fixture else 'product')
+ if key_ui.installed_proof(h, device) != installed:
+ raise RuntimeError('PRODUCT_HISTORY_INSTALLED_BYTES_CHANGED')
+ flow = 'history_fixture.yaml' if fixture else 'history_product.yaml'
+ args = [data['maestro']['binary'], '--device', device, 'test',
+ '--env', 'APP_ID=' + h.APP_IDS[h.PLATFORM]]
+ if fixture:
+ args += ['--env', 'EXPECTED_FIXTURE_ID=history-fixture-' + stage[8:] + '-pass']
+ else:
+ args += ['--env', 'EXPECTED_INSTALLED_REGEX=' + expected['installed_regex'],
+ '--env', 'EXPECTED_HISTORY_REGEX=' + expected['history_regex']]
+ report = output / 'junit.xml'
+ report.unlink(missing_ok=True)
+ args += ['--flatten-debug-output', '--debug-output', str(output),
+ '--test-output-dir', str(output), '--format', 'junit', '--output', str(report),
+ '.github/native/' + flow]
+ h.command(args, 'Native controlled history fixture' if fixture else
+ 'Normal cold-login current history observation', timeout=300, error_details=False)
+ h.successful_junit(report)
+ if (h.artifact_identity() != data['built_artifact'] or
+ key_ui.installed_proof(h, device) != installed):
+ raise RuntimeError('PRODUCT_HISTORY_EXACT_INSTALLED_ARTIFACT_CHANGED')
+ result['completed_stages'].append(stage)
+ result['stage_evidence'].append({'stage': stage, 'status': 'PASS',
+ 'installed_artifact_verified': True, 'installed_artifact': installed})
+ save()
+ # Never retain UI hierarchy, PIN input, app ID or screenshot output.
+ shutil.rmtree(output)
+ output.mkdir(mode=0o700)
+ after = backend_receipt.snapshot(passed=True)
+ if after['create_new_app_calls'] != before['create_new_app_calls']:
+ raise RuntimeError('PRODUCT_HISTORY_UNEXPECTED_ACCOUNT_SETUP')
+ switch_entrypoint('product')
+ if (h.artifact_identity() != data['built_artifact'] or
+ key_ui.installed_proof(h, device) != installed):
+ raise RuntimeError('PRODUCT_HISTORY_FINAL_INSTALLED_ARTIFACT_CHANGED')
+ result.update(status='PASS', original_history_restored=True,
+ stale_initial_and_recovery_dates_preserved=True,
+ stale_current_observation_count=1, empty_current_observation_count=1,
+ repeat_login_observation_date_unchanged=True,
+ account_version_unchanged=True, visible_wallet_count=1,
+ new_account_requests_during_history_flow=0,
+ installed_artifact_verified=True, installed_artifact=installed)
+ except Exception as error:
+ result['status'] = 'FAIL'
+ result['failure_category'] = type(error).__name__
+ raise
+ finally:
+ key_ui.finalize_companion(result, save,
+ [('private-output', lambda: shutil.rmtree(output))], 'failure_category' in result,
+ 'PRODUCT_HISTORY_CLEANUP_FAILED')
+ return result
diff --git a/.github/native/product_key_acceptance.py b/.github/native/product_key_acceptance.py
new file mode 100644
index 0000000000..1ab2707a4c
--- /dev/null
+++ b/.github/native/product_key_acceptance.py
@@ -0,0 +1,219 @@
+"""Normal-app unused-key/PIN companion on the product runner's owned device.
+
+No standalone device selector or fixture/database/credential injection is exposed.
+This runs after the five healthy samples and separate setup Retry fixture, while
+the same ordinary Metro process and disposable backend responder remain alive.
+"""
+import json
+import os
+from pathlib import Path
+import re
+import shutil
+import subprocess
+import threading
+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
+
+PORT = 8766
+STAGES = (
+ 'existing_disposable_home_verified', 'empty_deletion_entry_verified',
+ 'unused_mobile_key_created', 'delete_confirmation_scoped',
+ 'cancelled_confirmation_preserved_key', 'wrong_deletion_pin_rejected',
+ 'unused_mobile_key_deleted', 'unrelated_wallet_preserved',
+ 'cold_wrong_login_pin_rejected', 'deletion_persisted_after_relaunch',
+ 'final_wallet_verified',
+)
+
+
+def finalize_companion(result, save, operations, primary_failed, failure_code):
+ """Visit every owned cleanup boundary and never replace a primary failure."""
+ failures = []
+
+ def failed(stage, error):
+ category = type(error).__name__
+ if category not in {'OSError', 'RuntimeError', 'FileNotFoundError',
+ 'PermissionError', 'TimeoutError', 'TimeoutExpired'}:
+ category = 'OTHER_ERROR'
+ failures.append((stage, category))
+ result.update(status='FAIL', cleanup='FAILED',
+ cleanup_failure_category=failures[0][1],
+ cleanup_failure_categories=sorted({kind for _, kind in failures}),
+ cleanup_failure_stages=sorted({name for name, _ in failures}))
+
+ for stage, operation in operations:
+ try:
+ operation()
+ except Exception as error:
+ failed(stage, error)
+ # Private UI output is disposed before any final receipt is persisted. If
+ # writing itself fails, record that fixed failure and make one best effort
+ # to persist FAIL; an earlier RUNNING receipt cannot become a stale PASS.
+ try:
+ save()
+ except Exception as error:
+ failed('evidence-save', error)
+ try:
+ save()
+ except Exception as retry_error:
+ failed('evidence-save', retry_error)
+ if failures and not primary_failed:
+ raise RuntimeError(failure_code)
+
+
+def installed_proof(h, device):
+ proof = h.verify_installed_artifact(device)
+ method, hashes = {
+ 'ANDROID': ('SINGLE_INSTALLED_BASE_APK_SHA256', ['sha256']),
+ 'IOS': ('FULL_SIMULATOR_BUNDLE_TREE_AND_EXECUTABLE_SHA256',
+ ['inventory_sha256', 'executable_sha256']),
+ }[h.PLATFORM]
+ metadata = h.read()
+ if (not isinstance(proof, dict) or set(proof) != {'method', *hashes} or
+ proof['method'] != method or
+ any(not isinstance(proof[field], str) or not re.fullmatch(r'[a-f0-9]{64}', proof[field])
+ for field in hashes) or metadata.get('installed_artifact_verified') is not True or
+ metadata.get('installed_artifact') != proof):
+ metadata['installed_artifact_verified'] = False
+ metadata.pop('installed_artifact', None)
+ h.save(metadata)
+ raise RuntimeError('PRODUCT_UI_INSTALLED_BYTE_PROOF_REQUIRED')
+ return proof
+
+
+class Receipt:
+ def __init__(self):
+ self.lock = threading.Lock()
+ self.completed = []
+
+ def mark(self, stage):
+ with self.lock:
+ if len(self.completed) >= len(STAGES) or stage != STAGES[len(self.completed)]:
+ return False
+ self.completed.append(stage)
+ return True
+
+ def snapshot(self, passed=False):
+ with self.lock:
+ if passed and self.completed != list(STAGES):
+ raise RuntimeError('PRODUCT_KEY_UI_INCOMPLETE')
+ return {'status': 'PASS' if passed else 'FAIL',
+ 'completed_stages': list(self.completed),
+ 'entrypoint': 'index.js', 'network': 'TESTNET',
+ 'scenario': 'UNUSED_MOBILE_KEY_UI_DELETE_AND_NATIVE_PIN',
+ 'visible_eligible_keys_after_deletion': 0 if passed else None,
+ 'unrelated_visible_wallet_count_after_relaunch': 1 if passed else None,
+ 'referenced_vault_ui': 'NOT IMPLEMENTED',
+ 'credential_store_read_fault': 'NOT RUN',
+ 'physical_biometrics': 'NOT RUN',
+ 'protected_backup_deletion': 'NOT TESTED',
+ 'recovery_key_preservation': 'Not selected or exported; excluded by production deletion filters.'}
+
+
+def make_server(receipt, port=PORT):
+ class Handler(BaseHTTPRequestHandler):
+ def log_message(self, *_):
+ pass
+
+ def reply(self, status):
+ self.send_response(status)
+ self.send_header('Content-Length', '0')
+ self.end_headers()
+
+ def do_POST(self):
+ try:
+ length = int(self.headers.get('Content-Length', '0'))
+ if self.path != '/metric' or not 0 < length <= 128:
+ self.close_connection = True
+ return self.reply(422)
+ metric = json.loads(self.rfile.read(length))
+ if (isinstance(metric, dict) and set(metric) == {'stage'} and
+ receipt.mark(metric['stage'])):
+ return self.reply(200)
+ except (ValueError, TypeError):
+ pass
+ self.reply(422)
+
+ def do_GET(self):
+ self.reply(405)
+
+ class Server(ThreadingHTTPServer):
+ allow_reuse_address = False
+ daemon_threads = True
+
+ return Server(('127.0.0.1', port), Handler)
+
+
+def run_companion(h, data, device, private, backend_receipt):
+ if (os.environ.get('GITHUB_ACTIONS') != 'true' or
+ os.environ.get('RUNNER_ENVIRONMENT') != 'github-hosted' or
+ h.PLATFORM not in ['IOS', 'ANDROID'] or
+ (h.PLATFORM == 'ANDROID' and not device.startswith('emulator-'))):
+ raise RuntimeError('PRODUCT_KEY_UI_OWNED_HOSTED_DEVICE_REQUIRED')
+ actual = subprocess.check_output(['git', 'rev-parse', 'HEAD'], cwd=h.ROOT, text=True).strip()
+ if (data['build'] != 'PASS' or actual != data['source_sha'] or
+ actual != os.environ.get('KEEPER_SOURCE_SHA') or
+ h.artifact_identity() != data['built_artifact']):
+ raise RuntimeError('PRODUCT_KEY_UI_EXACT_BUILD_REQUIRED')
+ if subprocess.run(['git', 'diff', '--quiet', 'HEAD', '--', '.github/native', 'src',
+ 'index.js', 'App.tsx', 'metro.config.js', 'babel.config.js'],
+ cwd=h.ROOT, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL).returncode:
+ raise RuntimeError('PRODUCT_KEY_UI_COMMITTED_SOURCE_REQUIRED')
+ # Do not adopt another installation or turn this companion into account setup.
+ before = backend_receipt.snapshot(passed=True)
+ if (before.get('status') != 'PASS' or before.get('sample') != 6 or
+ before.get('scenario') != 'CONTROLLED_DISCONNECT_BEFORE_COMMIT_NOT_WAN_OFFLINE' or
+ before.get('create_new_app_calls') != 2 or
+ before.get('visible_wallet_count_after_relaunch') != 1):
+ raise RuntimeError('PRODUCT_KEY_UI_DISPOSABLE_RETRY_FIXTURE_REQUIRED')
+ output = Path(private) / 'key-ui'
+ output.mkdir(mode=0o700)
+ report = output / 'junit.xml'
+ receipt = Receipt()
+ result = receipt.snapshot()
+ result['status'] = 'RUNNING'
+ server = None
+
+ def save():
+ current = h.read()
+ current['product_key_ui'] = result
+ h.save(current)
+
+ try:
+ save()
+ installed_before = installed_proof(h, device)
+ server = make_server(receipt)
+ thread = threading.Thread(target=server.serve_forever, daemon=True)
+ thread.start()
+ h.command([data['maestro']['binary'], '--device', device, 'test',
+ '--env', 'APP_ID=' + h.APP_IDS[h.PLATFORM], '--flatten-debug-output',
+ '--debug-output', str(output), '--test-output-dir', str(output),
+ '--format', 'junit', '--output', str(report),
+ '.github/native/product_key_acceptance.yaml'],
+ 'Normal-app unused-key deletion and native PIN rejection',
+ timeout=720, error_details=False)
+ h.successful_junit(report)
+ if h.artifact_identity() != data['built_artifact']:
+ raise RuntimeError('PRODUCT_KEY_UI_ARTIFACT_CHANGED')
+ installed_after = installed_proof(h, device)
+ if installed_after != installed_before:
+ raise RuntimeError('PRODUCT_KEY_UI_INSTALLED_BYTES_CHANGED')
+ after = backend_receipt.snapshot(passed=True)
+ if after['create_new_app_calls'] != before['create_new_app_calls']:
+ raise RuntimeError('PRODUCT_KEY_UI_UNEXPECTED_ACCOUNT_SETUP')
+ result = receipt.snapshot(passed=True)
+ result['new_account_requests_during_key_flow'] = 0
+ result['installed_artifact_verified'] = True
+ result['installed_artifact'] = installed_after
+ except Exception as error:
+ result = receipt.snapshot()
+ result['failure_category'] = type(error).__name__
+ raise
+ finally:
+ operations = []
+ if server:
+ operations += [('server-shutdown', server.shutdown), ('server-close', server.server_close)]
+ # Maestro output can contain transient screenshots/hierarchy/PIN actions;
+ # retain no such files. The parent also deletes this suite's process logs.
+ operations.append(('private-output', lambda: shutil.rmtree(output)))
+ finalize_companion(result, save, operations, 'failure_category' in result,
+ 'PRODUCT_KEY_UI_CLEANUP_FAILED')
+ return result
diff --git a/.github/native/product_key_acceptance.yaml b/.github/native/product_key_acceptance.yaml
new file mode 100644
index 0000000000..e13240e0cd
--- /dev/null
+++ b/.github/native/product_key_acceptance.yaml
@@ -0,0 +1,246 @@
+# Ordinary app entrypoint, current native credentials/reducers/sagas/Realm.
+# Runs only on the task-owned disposable one-wallet account from retry fixture6.
+# Do not open seed/QR/export screens, opt into backup, fund or sign anything.
+appId: ${APP_ID}
+name: Normal app unused key deletion PIN rejection and cold persistence
+---
+- launchApp
+- extendedWaitUntil:
+ visible: Enter your passcode
+ timeout: 60000
+- repeat:
+ times: 4
+ commands:
+ - tapOn:
+ id: key_1
+- tapOn: Proceed
+- extendedWaitUntil:
+ visible:
+ id: home_visible_wallet_count_1
+ timeout: 60000
+- assertVisible: Mobile Wallet
+- runScript:
+ file: product_key_metric.js
+ env:
+ STAGE: existing_disposable_home_verified
+- tapOn:
+ id: home_tab_keys
+- extendedWaitUntil:
+ visible:
+ id: manage_keys_actions
+ timeout: 30000
+- tapOn:
+ id: manage_keys_actions
+- extendedWaitUntil:
+ visible:
+ id: header_title
+ text: Manage Keys
+ timeout: 30000
+- assertVisible: All the keys are hidden
+- assertNotVisible: Delete
+- runScript:
+ file: product_key_metric.js
+ env:
+ STAGE: empty_deletion_entry_verified
+- tapOn:
+ id: btn_back
+- tapOn:
+ id: keys_add_key
+- extendedWaitUntil:
+ visible: Add a software key
+ timeout: 30000
+- tapOn: Add a software key
+- extendedWaitUntil:
+ visible:
+ id: btn_MY_KEEPER
+ timeout: 30000
+- tapOn:
+ id: btn_MY_KEEPER
+- extendedWaitUntil:
+ visible: Setting up Mobile Key \(Hot\)
+ timeout: 30000
+- tapOn: Proceed
+- extendedWaitUntil:
+ visible: Confirm passcode to generate key
+ timeout: 30000
+- assertVisible:
+ id: modal_passcode_verify
+- repeat:
+ times: 4
+ commands:
+ - tapOn:
+ id: key_1
+- tapOn: Proceed
+- extendedWaitUntil:
+ visible: Mobile Key Added Successfully!
+ timeout: 60000
+- assertNotVisible:
+ id: seed_item_0
+- tapOn: Cancel
+- extendedWaitUntil:
+ visible:
+ id: manage_keys_actions
+ timeout: 30000
+- tapOn:
+ id: manage_keys_actions
+- extendedWaitUntil:
+ visible:
+ id: btnDelete
+ timeout: 30000
+- assertVisible: Mobile Key
+- runScript:
+ file: product_key_metric.js
+ env:
+ STAGE: unused_mobile_key_created
+- tapOn:
+ id: btnDelete
+- extendedWaitUntil:
+ visible: Confirm passcode to delete key
+ timeout: 30000
+- assertVisible:
+ id: modal_passcode_verify
+- runScript:
+ file: product_key_metric.js
+ env:
+ STAGE: delete_confirmation_scoped
+# A cancelled partially entered confirmation must preserve the eligible key.
+- repeat:
+ times: 3
+ commands:
+ - tapOn:
+ id: key_1
+- tapOn:
+ id: btn_close_modal
+- extendedWaitUntil:
+ visible:
+ id: btnDelete
+ timeout: 30000
+- assertVisible: Mobile Key
+- assertNotVisible: Key Deleted Successfully
+- runScript:
+ file: product_key_metric.js
+ env:
+ STAGE: cancelled_confirmation_preserved_key
+- tapOn:
+ id: btnDelete
+- extendedWaitUntil:
+ visible:
+ id: modal_passcode_verify
+ timeout: 30000
+# The only created account uses PIN1111. PIN0000 must be rejected natively.
+- repeat:
+ times: 4
+ commands:
+ - tapOn:
+ id: key_0
+- tapOn: Proceed
+- extendedWaitUntil:
+ visible: Incorrect Passcode, Try Again!
+ timeout: 30000
+- assertVisible:
+ id: modal_passcode_verify
+- assertNotVisible: Key Deleted Successfully
+- runScript:
+ file: product_key_metric.js
+ env:
+ STAGE: wrong_deletion_pin_rejected
+- repeat:
+ times: 4
+ commands:
+ - tapOn:
+ id: key_1
+- extendedWaitUntil:
+ visible:
+ id: btn_primaryText
+ enabled: true
+ timeout: 10000
+- tapOn: Proceed
+- extendedWaitUntil:
+ visible: Key Deleted Successfully
+ timeout: 60000
+- assertVisible: Your Key has been deleted successfully. You will have to add the Key again
+- runScript:
+ file: product_key_metric.js
+ env:
+ STAGE: unused_mobile_key_deleted
+- tapOn: Continue
+- extendedWaitUntil:
+ visible: All the keys are hidden
+ timeout: 30000
+- assertNotVisible: Delete
+- assertNotVisible: Mobile Key
+- tapOn:
+ id: btn_back
+- tapOn:
+ id: home_tab_wallets
+- extendedWaitUntil:
+ visible:
+ id: home_visible_wallet_count_1
+ timeout: 30000
+- assertVisible: Mobile Wallet
+- runScript:
+ file: product_key_metric.js
+ env:
+ STAGE: unrelated_wallet_preserved
+- stopApp
+- launchApp
+- extendedWaitUntil:
+ visible: Enter your passcode
+ timeout: 60000
+- repeat:
+ times: 4
+ commands:
+ - tapOn:
+ id: key_0
+- tapOn: Proceed
+- extendedWaitUntil:
+ visible: Incorrect Passcode, Try Again!
+ timeout: 30000
+- assertNotVisible:
+ id: home_visible_wallet_count_1
+- runScript:
+ file: product_key_metric.js
+ env:
+ STAGE: cold_wrong_login_pin_rejected
+- repeat:
+ times: 4
+ commands:
+ - tapOn:
+ id: key_1
+- tapOn: Proceed
+- extendedWaitUntil:
+ visible:
+ id: home_visible_wallet_count_1
+ timeout: 60000
+- assertVisible: Mobile Wallet
+- tapOn:
+ id: home_tab_keys
+- extendedWaitUntil:
+ visible:
+ id: manage_keys_actions
+ timeout: 30000
+- tapOn:
+ id: manage_keys_actions
+- extendedWaitUntil:
+ visible: All the keys are hidden
+ timeout: 30000
+- assertNotVisible: Delete
+- assertNotVisible: Mobile Key
+- runScript:
+ file: product_key_metric.js
+ env:
+ STAGE: deletion_persisted_after_relaunch
+- tapOn:
+ id: btn_back
+- tapOn:
+ id: home_tab_wallets
+- extendedWaitUntil:
+ visible:
+ id: home_visible_wallet_count_1
+ timeout: 30000
+- assertVisible: Mobile Wallet
+- runScript:
+ file: product_key_metric.js
+ env:
+ STAGE: final_wallet_verified
+- stopApp
diff --git a/.github/native/product_key_metric.js b/.github/native/product_key_metric.js
new file mode 100644
index 0000000000..5e8af4f221
--- /dev/null
+++ b/.github/native/product_key_metric.js
@@ -0,0 +1,6 @@
+// Maestro runs this on the host. Export fixed stage names only, never app data.
+const reply = http.post('http://127.0.0.1:8766/metric', {
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ stage: STAGE }),
+});
+if (reply.status !== 200) throw new Error('PRODUCT_KEY_METRIC_REJECTED');
diff --git a/.github/native/product_measurements.py b/.github/native/product_measurements.py
new file mode 100644
index 0000000000..f89c5a1186
--- /dev/null
+++ b/.github/native/product_measurements.py
@@ -0,0 +1,498 @@
+#!/usr/bin/env python3
+"""Five full-product UI samples and one separate controlled Retry fixture.
+
+Requires the hosted_native.py foundation and its successful exact-source build.
+Normal Metro entrypoint is mandatory. The loopback responder is a controlled
+createNewApp transport fixture, NEVER evidence of Relay compatibility.
+"""
+import importlib.util
+import hashlib
+import json
+import os
+from pathlib import Path
+import re
+import shutil
+import socket
+import subprocess
+import tempfile
+import threading
+import time
+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
+
+STAGES = ('startup_start', 'startup_ready', 'wallet_start', 'wallet_ready',
+ 'home_ready', 'relaunch_start', 'relaunch_login', 'relaunch_home',
+ 'version_history_verified', 'key_management_entry_verified', 'navigation_verified')
+RETRY_STAGES = ('retry_fixture_start', 'retry_error_visible', 'retry_submit', 'retry_home_ready',
+ 'retry_relaunch_start', 'retry_relaunch_login', 'retry_relaunch_home')
+PORT = 8765
+SAMPLE_COUNT = 5
+PIN_MARKERS = ('confirm_passcode_visible', 'confirmation_digits_tapped', 'create_tapped',
+ 'continue_visible', 'continue_tapped', 'cancel_visible', 'cancel_tapped',
+ 'skip_visible', 'skip_tapped', 'start_new_visible')
+
+
+def native_module(name):
+ if name not in ('product_metro', 'product_credential_acceptance',
+ 'product_history_acceptance', 'product_vault_acceptance'):
+ raise RuntimeError('PRODUCT_UI_FIXED_COMPANION_REQUIRED')
+ spec = importlib.util.spec_from_file_location(name, Path(__file__).with_name(name + '.py'))
+ module = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(module)
+ return module
+
+
+def run_post_key_companions(h, data, device, private, receipt, metro, installed_proof, result):
+ """Ordering preserves the original one-account/one-wallet fixture until Vault."""
+ for slot, name in (('credential_errors_ui', 'product_credential_acceptance'),
+ ('version_history_ui', 'product_history_acceptance'),
+ ('vault_references_ui', 'product_vault_acceptance')):
+ metro.ensure_product()
+ companion = native_module(name)
+ argument = installed_proof if name == 'product_vault_acceptance' else metro.switch
+ result[slot] = companion.run_companion(h, data, device, private, receipt, argument)
+ metro.ensure_product()
+
+
+def android_failure_observation(private, device):
+ """Best-effort fixed runtime facts; never replace the sample's failure."""
+ scope = 'Failed sample runtime only; no current product Metro log is supplied. Cause remains undetermined.'
+ try:
+ spec = importlib.util.spec_from_file_location('product_android_failure_diagnosis',
+ Path(__file__).with_name('android_startup_diagnosis.py'))
+ module = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(module)
+ return {'status': 'COLLECTED', 'scope': scope, 'facts': module.collect(private, device)}
+ except Exception:
+ return {'status': 'UNAVAILABLE', 'scope': scope}
+
+
+class Receipt:
+ """Fixed vocabulary and numbers only; never store a request body/identifier."""
+ def __init__(self):
+ self.lock = threading.Lock()
+ self.reset(1)
+
+ def reset(self, sample, retry=False):
+ with self.lock:
+ self.sample, self.times = sample, []
+ self.create_calls, self.blocked_calls = 0, 0
+ self.retry, self.stages = retry, RETRY_STAGES if retry else STAGES
+ self.dropped, self.acknowledged, self.unexpected = 0, 0, 0
+ self.pin_marker_count = 0
+
+ def create_attempt(self):
+ with self.lock:
+ self.create_calls += 1
+ if self.retry and self.create_calls == 1:
+ self.dropped += 1
+ return False
+ if self.retry and self.stages[len(self.times) - 1] != 'retry_submit':
+ self.unexpected += 1
+ self.acknowledged += 1
+ return True
+
+ def mark(self, stage):
+ with self.lock:
+ if len(self.times) >= len(self.stages) or stage != self.stages[len(self.times)]:
+ return False
+ if self.retry and stage in ('retry_error_visible', 'retry_submit') and (
+ self.create_calls, self.dropped, self.acknowledged, self.unexpected) != (1, 1, 0, 0):
+ return False
+ self.times.append(time.monotonic_ns())
+ return True
+
+ def mark_pin(self, marker):
+ """Record a fixed prefix independently of performance/backend state."""
+ with self.lock:
+ if (type(marker) is not str or self.pin_marker_count >= len(PIN_MARKERS)
+ or marker != PIN_MARKERS[self.pin_marker_count]):
+ return False
+ self.pin_marker_count += 1
+ return True
+
+ def snapshot(self, passed=False):
+ with self.lock:
+ pin_progress = {
+ 'scope': 'Host marker acknowledgements only; missing markers do not identify an app defect.',
+ 'completed_markers': list(PIN_MARKERS[:self.pin_marker_count]),
+ 'next_marker': PIN_MARKERS[self.pin_marker_count] if self.pin_marker_count < len(PIN_MARKERS) else None,
+ 'complete': self.pin_marker_count == len(PIN_MARKERS),
+ }
+ if self.retry:
+ if passed and (len(self.times) != len(RETRY_STAGES) or
+ (self.create_calls, self.dropped, self.acknowledged, self.unexpected) != (2, 1, 1, 0)):
+ raise RuntimeError('PRODUCT_UI_RETRY_INCOMPLETE_OR_UNEXPECTED_REQUEST')
+ stages = list(RETRY_STAGES[:len(self.times)])
+ return {'sample': self.sample, 'status': 'PASS' if passed else 'FAIL',
+ 'scenario': 'CONTROLLED_DISCONNECT_BEFORE_COMMIT_NOT_WAN_OFFLINE',
+ 'completed_stages': stages, 'create_new_app_calls': self.create_calls,
+ 'pin_onboarding_progress': pin_progress,
+ 'transport_requests_dropped_without_commit': self.dropped,
+ 'acknowledged_create_responses': self.acknowledged,
+ 'unexpected_create_attempts': self.unexpected,
+ 'other_backend_calls_rejected': self.blocked_calls,
+ 'visible_wallet_count_before_relaunch': 1 if 'retry_home_ready' in stages else None,
+ 'visible_wallet_count_after_relaunch': 1 if 'retry_relaunch_home' in stages else None,
+ 'performance_sample': False}
+ if passed and (len(self.times) != len(STAGES) or self.create_calls != 1):
+ raise RuntimeError('PRODUCT_UI_INCOMPLETE_OR_DUPLICATE_SETUP')
+ stamps = dict(zip(STAGES, self.times))
+ pairs = {
+ 'startup_to_passcode_ms': ('startup_start', 'startup_ready'),
+ 'start_new_to_ready_ms': ('wallet_start', 'wallet_ready'),
+ 'start_new_to_home_ms': ('wallet_start', 'home_ready'),
+ 'cold_relaunch_to_login_ms': ('relaunch_start', 'relaunch_login'),
+ 'cold_relaunch_to_authenticated_home_ms': ('relaunch_start', 'relaunch_home'),
+ }
+ durations = {name: round((stamps[end] - stamps[start]) / 1_000_000, 3)
+ for name, (start, end) in pairs.items() if end in stamps and start in stamps}
+ return {'sample': self.sample, 'status': 'PASS' if passed else 'FAIL',
+ 'completed_stages': list(STAGES[:len(self.times)]), 'raw_durations': durations,
+ 'pin_onboarding_progress': pin_progress,
+ 'create_new_app_calls': self.create_calls, 'other_backend_calls_rejected': self.blocked_calls,
+ 'visible_wallet_count_before_relaunch': 1 if 'home_ready' in stamps else None,
+ 'visible_wallet_count_after_relaunch': 1 if 'relaunch_home' in stamps else None,
+ 'installed_version_header_and_initial_history': 'PASS' if 'version_history_verified' in stamps else 'NOT RUN',
+ 'key_management_entry_and_exit': 'PASS' if 'key_management_entry_verified' in stamps else 'NOT RUN',
+ 'more_wallets_navigation': 'PASS' if 'navigation_verified' in stamps else 'NOT RUN'}
+
+
+def make_server(receipt, port=PORT):
+ class Handler(BaseHTTPRequestHandler):
+ def log_message(self, *_):
+ pass
+
+ def reply(self, status, value):
+ raw = json.dumps(value).encode()
+ self.send_response(status)
+ self.send_header('Content-Type', 'application/json')
+ self.send_header('Content-Length', str(len(raw)))
+ self.end_headers()
+ self.wfile.write(raw)
+
+ def do_POST(self):
+ try:
+ length = int(self.headers.get('Content-Length', '0'))
+ if self.path == '/pin-progress' and not 0 < length <= 128:
+ self.close_connection = True
+ return self.reply(413, {'error': 'FIXED_PIN_PROGRESS_REJECTED'})
+ if not 0 < length <= 8192:
+ self.close_connection = True
+ return self.reply(413, {'error': 'FIXTURE_BODY_REJECTED'})
+ # createNewApp carries disposable public identifiers/FCM data.
+ # Discard without parsing, logging, echoing or retaining them.
+ raw = self.rfile.read(length)
+ if self.path == '/createNewApp':
+ if not receipt.create_attempt():
+ # Controlled transport failure only: no account storage
+ # or simulated server commit exists in this responder.
+ self.close_connection = True
+ try:
+ self.connection.shutdown(socket.SHUT_RDWR)
+ except OSError:
+ pass
+ self.connection.close()
+ return
+ return self.reply(200, {'created': True})
+ if self.path == '/pin-progress':
+ def unique_object(pairs):
+ if len(pairs) != len({key for key, _ in pairs}):
+ raise ValueError('Duplicate fields')
+ return dict(pairs)
+ try:
+ marker = json.loads(raw, object_pairs_hook=unique_object)
+ if (type(marker) is dict and set(marker) == {'marker'} and
+ receipt.mark_pin(marker['marker'])):
+ return self.reply(200, {'accepted': True})
+ except (ValueError, TypeError):
+ pass
+ return self.reply(422, {'error': 'FIXED_PIN_PROGRESS_REJECTED'})
+ if self.path == '/metric' and length <= 128:
+ metric = json.loads(raw)
+ if (isinstance(metric, dict) and set(metric) == {'stage'} and
+ receipt.mark(metric['stage'])):
+ return self.reply(200, {'accepted': True})
+ return self.reply(422, {'error': 'FIXED_METRIC_REJECTED'})
+ except (ValueError, TypeError):
+ return self.reply(422, {'error': 'FIXED_METRIC_REJECTED'})
+ with receipt.lock:
+ receipt.blocked_calls += 1
+ self.reply(503, {'error': 'DISPOSABLE_FIXTURE_UNSUPPORTED_ROUTE'})
+
+ def do_GET(self):
+ with receipt.lock:
+ receipt.blocked_calls += 1
+ self.reply(503, {'error': 'DISPOSABLE_FIXTURE_UNSUPPORTED_ROUTE'})
+
+ class Server(ThreadingHTTPServer):
+ allow_reuse_address = False
+ daemon_threads = True
+
+ return Server(('127.0.0.1', port), Handler)
+
+
+def verify_package_overlay(original_bytes, installed_bytes, overlay):
+ """Accept only the foundation's exact recorded module-mapping overlay."""
+ allowed = ['browser', 'react-native', 'browserify']
+ if (not isinstance(overlay, dict) or overlay.get('path') != 'package.json' or
+ overlay.get('allowed_fields') != allowed or
+ overlay.get('before_sha256') != hashlib.sha256(original_bytes).hexdigest() or
+ overlay.get('after_sha256') != hashlib.sha256(installed_bytes).hexdigest()):
+ raise RuntimeError('PRODUCT_UI_PACKAGE_OVERLAY_UNRECORDED')
+ try:
+ original, installed = json.loads(original_bytes), json.loads(installed_bytes)
+ if not isinstance(original, dict) or not isinstance(installed, dict):
+ raise ValueError('Expected manifest objects')
+ for field in allowed:
+ original.pop(field, None)
+ installed.pop(field, None)
+ if original != installed:
+ raise ValueError('Protected manifest fields changed')
+ except (ValueError, TypeError, UnicodeError):
+ raise RuntimeError('PRODUCT_UI_PACKAGE_PROTECTED_FIELDS_CHANGED') from None
+
+
+def version_expectation(manifest, platform):
+ field = {'IOS': 'iosBuildNumber', 'ANDROID': 'androidVersionCode'}.get(platform)
+ version = manifest.get('version')
+ build = manifest.get(field)
+ if (field is None or not isinstance(version, str) or
+ not re.fullmatch(r'[0-9]+\.[0-9]+\.[0-9]+', version) or
+ type(build) is not int or not 0 < build <= 2100000000):
+ raise RuntimeError('PRODUCT_UI_SOURCE_VERSION_INVALID')
+ escaped = version.replace('.', r'\.')
+ return {'version': version, 'build': build,
+ 'installed_regex': '^' + escaped + r' \(' + str(build) + r'\)$',
+ 'history_regex': '^' + escaped + r'\(' + str(build) + r'\)$'}
+
+
+def run(h):
+ if (os.environ.get('GITHUB_ACTIONS') != 'true' or
+ os.environ.get('RUNNER_ENVIRONMENT') != 'github-hosted'):
+ raise RuntimeError('PRODUCT_UI_DISPOSABLE_HOSTED_RUNNER_REQUIRED')
+ data = h.read()
+ first_private_command = len(data.get('commands', [])) + 1
+ actual_source = subprocess.check_output(['git', 'rev-parse', 'HEAD'], cwd=h.ROOT, text=True).strip()
+ if (data['build'] != 'PASS' or data['source_sha'] != os.environ.get('KEEPER_SOURCE_SHA') or
+ actual_source != data['source_sha'] or h.artifact_identity() != data['built_artifact']):
+ raise RuntimeError('PRODUCT_UI_EXACT_BUILD_REQUIRED')
+ source_paths = ['.github/native', 'src', 'index.js', 'App.tsx', 'App.js', 'shim.js',
+ 'AndroidFontFix.js', 'metro.config.js', 'babel.config.js', 'app.json',
+ 'react-native.config.js', 'tsconfig.json', 'yarn.lock', 'release/version.json']
+ if subprocess.run(['git', 'diff', '--quiet', 'HEAD', '--', *source_paths],
+ cwd=h.ROOT, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL).returncode:
+ raise RuntimeError('PRODUCT_UI_COMMITTED_SOURCE_REQUIRED')
+ verify_package_overlay(
+ subprocess.check_output(['git', 'show', 'HEAD:package.json'], cwd=h.ROOT),
+ (h.ROOT / 'package.json').read_bytes(), data.get('nodeify_overlay'))
+ expected_version = version_expectation(json.loads((h.ROOT / 'release/version.json').read_text()), h.PLATFORM)
+ expected_environment = {
+ 'ENVIRONMENT': 'DEVELOPMENT', 'RELAY': 'http://127.0.0.1:8765/',
+ 'SIGNING_SERVER_TESTNET': 'https://127.0.0.1:9/',
+ 'SIGNING_SERVER_MAINNET': 'https://127.0.0.1:9/',
+ 'CHANNEL_URL': 'https://127.0.0.1:9/',
+ 'SENTRY_DNS': 'https://public@127.0.0.1:9/1',
+ 'ENC_KEY_STORAGE_IDENTIFIER': 'KEEPER-HOSTED-DISPOSABLE',
+ }
+ environment_lines = (h.ROOT / '.env.ci').read_text().splitlines()
+ if (len(environment_lines) != len(expected_environment) or
+ dict(line.split('=', 1) for line in environment_lines) != expected_environment):
+ raise RuntimeError('PRODUCT_UI_LOOPBACK_BUILD_REQUIRED')
+ private = Path(tempfile.mkdtemp(prefix='keeper-product-ui-', dir=h.PRIVATE))
+ private.chmod(0o700)
+ receipt = Receipt()
+ server, device = None, None
+ metro_tools = native_module('product_metro')
+ metro = metro_tools.OwnedMetro(h, private)
+ reverse_ports = set()
+ # Only app/test-specific data created here is removed. Never touch shared
+ # caches, another worktree, an existing iOS simulator or a real phone.
+ result = {'status': 'RUNNING', 'samples': [], 'requested_samples': SAMPLE_COUNT,
+ 'controlled_disconnect_retry': {'status': 'NOT RUN', 'performance_sample': False},
+ 'entrypoint': 'index.js', 'network': 'TESTNET', 'backend': 'CONTROLLED_LOOPBACK_CREATE_ONLY',
+ 'expected_installed_version': expected_version['version'],
+ 'expected_installed_build': expected_version['build'],
+ 'version_history_scope': 'Initial samples inspect the installed native tuple and initial row; controlled stale/empty cases have a separate companion receipt. Authentic historical migration is not tested.',
+ 'key_management_scope': 'Discoverable Keys→Manage Keys screen entry and back navigation only; no eligible disposable signer, deletion confirmation or seed view.',
+ 'backend_compatibility': 'NOT TESTED', 'physical_devices': 'NOT RUN',
+ 'r5_release_acceptance': 'NOT ESTABLISHED; these are scoped diagnostic companions.',
+ 'performance_scope': 'Development app with warm Metro bundle; cold process/UI timing includes Maestro driver overhead. Not release-build performance.',
+ 'count_scope': 'Actual rendered visible wallet list; disposable one-wallet account, not hidden/archived wallet counts.',
+ 'network_scope': 'Fresh production Splash selects Testnet for DEVELOPMENT. Account backend is loopback fixture; signing/channel/Sentry endpoints blocked. Public Testnet Electrum connectivity may fail or connect; no faucet, funded wallet, send, signing or backup opt-in.'}
+
+ def save():
+ current = h.read()
+ current['product_ui'] = result
+ h.save(current)
+
+ try:
+ save()
+ server = make_server(receipt)
+ thread = threading.Thread(target=server.serve_forever, daemon=True)
+ thread.start()
+ # Only this manager starts/records the ordinary or fixed fixture Metro.
+ metro.start('product', initial=True)
+ if h.PLATFORM == 'IOS':
+ device = h.command(['xcrun', 'simctl', 'create', 'Keeper-product-ui-disposable',
+ 'com.apple.CoreSimulator.SimDeviceType.iPhone-16',
+ 'com.apple.CoreSimulator.SimRuntime.iOS-18-5'],
+ 'Create task-owned product UI simulator', capture=True)
+ h.command(['xcrun', 'simctl', 'boot', device], 'Boot product UI simulator')
+ h.command(['xcrun', 'simctl', 'bootstatus', device, '-b'], 'Wait for product UI simulator', timeout=240)
+ h.wait_for_simulator_app_services(device)
+ artifact = str(h.PRIVATE / 'DerivedData/Build/Products/Debug-iphonesimulator/hexa_keeper_dev.app')
+ result['device'] = {'profile': 'iPhone 16', 'runtime': 'iOS 18.5', 'kind': 'SIMULATOR'}
+ else:
+ device = h.command(['adb', 'get-serialno'], 'Select disposable CI emulator', capture=True)
+ if not device.startswith('emulator-'):
+ raise RuntimeError('PRODUCT_UI_REAL_ANDROID_DEVICE_REJECTED')
+ for port in ('8081', str(PORT)):
+ h.command(['adb', '-s', device, 'reverse', 'tcp:' + port, 'tcp:' + port],
+ 'Connect disposable emulator to local fixture')
+ reverse_ports.add(port)
+ artifact = str(h.ROOT / 'android/app/build/outputs/apk/development/debug/app-development-debug.apk')
+ result['device'] = {'kind': 'EMULATOR', 'image': h.command(
+ ['adb', '-s', device, 'shell', 'getprop', 'ro.build.fingerprint'],
+ 'Record actual product UI emulator image', capture=True)}
+ app = h.APP_IDS[h.PLATFORM]
+ spec = importlib.util.spec_from_file_location(
+ 'product_key_acceptance', Path(__file__).with_name('product_key_acceptance.py'))
+ key_companion = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(key_companion)
+ for sample in range(1, SAMPLE_COUNT + 2):
+ retry_fixture = sample == SAMPLE_COUNT + 1
+ receipt.reset(sample, retry=retry_fixture)
+ output = private / ('sample-%d' % sample)
+ output.mkdir()
+ report = output / 'junit.xml'
+ if h.PLATFORM == 'IOS':
+ # Uninstall plus reset of this newly-created simulator's
+ # keychain prevents prior sample credentials persisting.
+ subprocess.run(['xcrun', 'simctl', 'uninstall', device, app],
+ stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=30, check=False)
+ h.command(['xcrun', 'simctl', 'keychain', device, 'reset'], 'Reset task-owned simulator credentials')
+ h.command(['xcrun', 'simctl', 'install', device, artifact], 'Install exact product UI app', timeout=120)
+ else:
+ h.command(['adb', '-s', device, 'install', '-r', artifact], 'Install exact product UI APK', timeout=120)
+ h.command(['adb', '-s', device, 'shell', 'pm', 'clear', app], 'Clear only disposable development app')
+ try:
+ installed_before = key_companion.installed_proof(h, device)
+ h.command([data['maestro']['binary'], '--device', device, 'test',
+ '--env', 'APP_ID=' + app,
+ '--env', 'EXPECTED_INSTALLED_REGEX=' + expected_version['installed_regex'],
+ '--env', 'EXPECTED_HISTORY_REGEX=' + expected_version['history_regex'],
+ '--flatten-debug-output',
+ '--debug-output', str(output), '--test-output-dir', str(output),
+ '--format', 'junit', '--output', str(report),
+ '.github/native/product_retry.yaml' if retry_fixture else
+ '.github/native/product_first_wallet.yaml'],
+ 'Full-product controlled disconnect and Retry fixture' if retry_fixture else
+ 'Full-product first-wallet and relaunch UI sample', timeout=600, error_details=False)
+ h.successful_junit(report)
+ if h.artifact_identity() != data['built_artifact']:
+ raise RuntimeError('PRODUCT_UI_ARTIFACT_CHANGED')
+ installed_after = key_companion.installed_proof(h, device)
+ if installed_before != installed_after:
+ raise RuntimeError('PRODUCT_UI_INSTALLED_BYTES_CHANGED')
+ outcome = receipt.snapshot(passed=True)
+ outcome['installed_artifact_verified'] = True
+ outcome['installed_artifact'] = installed_after
+ if retry_fixture:
+ result['controlled_disconnect_retry'] = outcome
+ else:
+ result['samples'].append(outcome)
+ except Exception:
+ outcome = receipt.snapshot()
+ if h.PLATFORM == 'ANDROID':
+ outcome['android_runtime_diagnostic'] = android_failure_observation(output, device)
+ if retry_fixture:
+ result['controlled_disconnect_retry'] = outcome
+ else:
+ result['samples'].append(outcome)
+ raise
+ finally:
+ # Maestro can capture automatic failure diagnostics. Keep no
+ # screenshots, hierarchy, PIN actions or app output artifacts.
+ shutil.rmtree(output, ignore_errors=True)
+ save()
+ # Separate normal-app UI companion; never part of the five latency
+ # samples or the controlled setup-disconnect receipt vocabulary.
+ # The facade grants switching only after the matching successful
+ # JUnit from a committed allowlisted flow whose final command is stopApp.
+ flow_harness = metro_tools.StoppedFlowHarness(h, data, device, private, metro, reverse_ports)
+ result['key_management_ui'] = key_companion.run_companion(flow_harness, data, device, private, receipt)
+ result['key_management_scope'] = (
+ 'Normal-app unused Mobile Key creation/deletion, cancellation, wrong PIN rejection, '
+ 'correct PIN retry, cold deletion persistence and unrelated wallet retention. '
+ 'Physical biometrics remain unverified; the following receipts have separate scopes.')
+ run_post_key_companions(flow_harness, data, device, private, receipt,
+ metro, key_companion.installed_proof, result)
+ result['version_history_scope'] = (
+ 'Installed native tuple/initial row plus controlled stale/empty actual native Realm histories, '
+ 'ordinary cold-login observation/provenance/date/idempotence and exact restoration. '
+ 'Authentic historical installation and migration remain unverified.')
+ save()
+ result['status'] = 'PASS'
+ except Exception as error:
+ result['status'] = 'FAIL'
+ result['failure_category'] = type(error).__name__ # never raw error text
+ raise
+ finally:
+ # Save original outcome before best-effort disposal so a cleanup issue
+ # cannot erase a native failure or the completed raw numeric samples.
+ original_failed = result['status'] == 'FAIL'
+ cleanup_errors = []
+
+ def attempt(operation):
+ try:
+ operation()
+ except Exception as cleanup_error:
+ cleanup_errors.append(type(cleanup_error).__name__)
+ result.update(status='FAIL', cleanup='FAILED',
+ cleanup_failure_categories=sorted(set(cleanup_errors)))
+
+ result['companion_metro_switches'] = list(metro.events)
+ attempt(save)
+ # Stop/reap every recorded child before device and private-log removal,
+ # including the newest child when its readiness/warmup failed.
+ attempt(metro.close)
+ if server:
+ attempt(server.shutdown)
+ attempt(server.server_close)
+
+ def cleanup(args):
+ def execute():
+ if subprocess.run(args, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
+ timeout=30, check=False).returncode:
+ raise RuntimeError('PRODUCT_UI_DISPOSABLE_CLEANUP_COMMAND_FAILED')
+ attempt(execute)
+
+ if device and h.PLATFORM == 'IOS':
+ for action in ('shutdown', 'delete'):
+ cleanup(['xcrun', 'simctl', action, device])
+ elif device and device.startswith('emulator-'):
+ cleanup(['adb', '-s', device, 'uninstall', h.APP_IDS[h.PLATFORM]])
+ for port in sorted(reverse_ports):
+ cleanup(['adb', '-s', device, 'reverse', '--remove', 'tcp:' + port])
+ attempt(lambda: shutil.rmtree(private))
+ # Foundation command metadata is safe/nonsecret; its process logs from
+ # this suite are not retained even on the ephemeral runner.
+ def remove_command_logs():
+ for index in range(first_private_command, len(h.read().get('commands', [])) + 1):
+ (h.PRIVATE / ('command-%03d.log' % index)).unlink(missing_ok=True)
+ attempt(remove_command_logs)
+ attempt(save)
+ if cleanup_errors and not original_failed:
+ raise RuntimeError('PRODUCT_UI_DISPOSABLE_CLEANUP_FAILED')
+
+
+if __name__ == '__main__':
+ import sys
+ if sys.argv[1:] != ['run']:
+ raise SystemExit('Expected run; hosted exact-source build prerequisite required.')
+ spec = importlib.util.spec_from_file_location('hosted_native', Path(__file__).with_name('hosted_native.py'))
+ foundation = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(foundation)
+ if foundation.PLATFORM not in foundation.APP_IDS:
+ raise SystemExit('Expected hosted IOS or ANDROID platform.')
+ run(foundation)
diff --git a/.github/native/product_metric.js b/.github/native/product_metric.js
new file mode 100644
index 0000000000..e98170a706
--- /dev/null
+++ b/.github/native/product_metric.js
@@ -0,0 +1,6 @@
+// Host-side Maestro script. Send fixed stage labels only, never hierarchy/app data.
+const reply = http.post('http://127.0.0.1:8765/metric', {
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ stage: STAGE }),
+});
+if (reply.status !== 200) throw new Error('PRODUCT_METRIC_REJECTED');
diff --git a/.github/native/product_metro.py b/.github/native/product_metro.py
new file mode 100644
index 0000000000..b5e4cfd383
--- /dev/null
+++ b/.github/native/product_metro.py
@@ -0,0 +1,198 @@
+"""Owned process/bundle switching; setup and host contracts supply no native PASS."""
+import os
+from pathlib import Path
+import signal
+import socket
+import subprocess
+import time
+import urllib.request
+
+PHASE_CONFIGS = {'product': None, 'arm': 'credential_metro.cjs', 'restore': 'credential_metro.cjs',
+ **{name: name + '_metro.cjs' for name in (
+ 'history_seed_stale', 'history_verify_stale_first', 'history_verify_stale_repeat',
+ 'history_seed_empty', 'history_verify_empty_first', 'history_verify_empty_repeat',
+ 'history_restore', 'history_verify_restored')}}
+FLOW_PHASES = {
+ 'product_key_acceptance.yaml': ('product',),
+ 'credential_fixture.yaml': ('arm', 'restore'),
+ 'product_credential_blocked.yaml': ('product',),
+ 'product_credential_recovered.yaml': ('product',),
+ 'history_fixture.yaml': tuple(p for p in PHASE_CONFIGS if p.startswith('history_')),
+ 'history_product.yaml': ('product',),
+ 'product_vault_acceptance.yaml': ('product',),
+}
+
+
+class OwnedMetro:
+ def __init__(self, h, private):
+ self.h, self.private = h, Path(private)
+ self.process, self.phase = None, None
+ self.owned, self.reaped, self.events = [], set(), []
+ self.app_stopped = False
+
+ @staticmethod
+ def port_occupied():
+ try:
+ with socket.create_connection(('127.0.0.1', 8081), timeout=0.2):
+ return True
+ except OSError:
+ return False
+
+ def stop(self, process):
+ if process not in self.owned:
+ raise RuntimeError('PRODUCT_METRO_UNOWNED_PROCESS')
+ if process in self.reaped:
+ return
+ # Every handle originates below with start_new_session=True. No PID or
+ # process handle can be supplied by a device selector or external caller.
+ try:
+ os.killpg(process.pid, signal.SIGTERM)
+ except ProcessLookupError:
+ pass
+ try:
+ process.wait(timeout=10)
+ except subprocess.TimeoutExpired:
+ try:
+ os.killpg(process.pid, signal.SIGKILL)
+ except ProcessLookupError:
+ pass
+ process.wait(timeout=10)
+ # The leader can exit before an inherited worker closes its listener.
+ # This is the same task-owned session, never a discovered foreign PID.
+ try:
+ os.killpg(process.pid, signal.SIGKILL)
+ except ProcessLookupError:
+ pass
+ self.reaped.add(process)
+
+ def close(self):
+ failed = False
+ for process in reversed(self.owned):
+ try:
+ self.stop(process)
+ except Exception:
+ failed = True
+ if failed:
+ raise RuntimeError('PRODUCT_METRO_OWNED_CLEANUP_FAILED')
+
+ def start(self, phase, initial=False):
+ if phase not in PHASE_CONFIGS:
+ raise RuntimeError('PRODUCT_METRO_PHASE_REJECTED')
+ if initial:
+ if self.owned or phase != 'product':
+ raise RuntimeError('PRODUCT_METRO_INITIAL_PRODUCT_REQUIRED')
+ elif not self.app_stopped:
+ raise RuntimeError('PRODUCT_METRO_STOPPED_JUNIT_REQUIRED')
+ config = PHASE_CONFIGS[phase]
+ if config:
+ path = self.h.ROOT / '.github/native' / config
+ if path.is_symlink() or not path.is_file():
+ raise RuntimeError('PRODUCT_METRO_FIXED_CONFIG_REQUIRED')
+ if self.process:
+ self.stop(self.process)
+ # Wait briefly for the just-terminated owned listener to close. Never
+ # adopt or kill a foreign listener or delete a cache to free this port.
+ for _ in range(20 if self.process else 1):
+ if not self.port_occupied():
+ break
+ time.sleep(0.1)
+ else:
+ raise RuntimeError('PRODUCT_METRO_PORT_OCCUPIED')
+ environment = os.environ.copy()
+ environment.pop('KEEPER_CREDENTIAL_FIXTURE_PHASE', None)
+ if phase in ('arm', 'restore'):
+ environment['KEEPER_CREDENTIAL_FIXTURE_PHASE'] = phase
+ args = ['node', 'node_modules/react-native/cli.js', 'start', '--port', '8081']
+ if config:
+ args += ['--config', str(path)]
+ event = {'phase': phase, 'status': 'FAIL', 'scope': 'BUNDLE_SETUP_ONLY'}
+ self.events.append(event)
+ with (self.private / ('metro-%02d.log' % len(self.events))).open('wb') as log:
+ process = subprocess.Popen(args, cwd=self.h.ROOT, env=environment, stdout=log,
+ stderr=subprocess.STDOUT, start_new_session=True)
+ # Retain the latest handle before any readiness/warmup can fail.
+ self.process = process
+ self.owned.append(process)
+ self.phase, self.app_stopped = phase, False
+ for _ in range(60):
+ if process.poll() is not None:
+ raise RuntimeError('PRODUCT_METRO_CHILD_EXITED')
+ try:
+ with urllib.request.urlopen('http://127.0.0.1:8081/status', timeout=2) as reply:
+ if reply.status == 200 and reply.read(128).strip() == b'packager-status:running':
+ break
+ except OSError:
+ pass
+ time.sleep(1)
+ else:
+ raise RuntimeError('PRODUCT_METRO_NOT_READY')
+ self.h.warm_metro_bundle('startup' if initial else 'product_ui_' + phase)
+ if process.poll() is not None:
+ raise RuntimeError('PRODUCT_METRO_CHILD_EXITED_AFTER_WARMUP')
+ event['status'] = 'PASS'
+
+ def switch(self, phase):
+ self.start(phase)
+
+ def ensure_product(self):
+ if self.phase != 'product':
+ self.switch('product')
+ if self.process is None or self.process.poll() is not None:
+ raise RuntimeError('PRODUCT_METRO_ORDINARY_APP_REQUIRED')
+
+
+class StoppedFlowHarness:
+ """Only reviewed stopApp flows with matching successful JUnit grant a switch.
+
+ The coordinator creates this after discovering its disposable device. This
+ is not a standalone device/account entrypoint or an OS process inspection.
+ """
+ def __init__(self, h, data, device, private, metro, reverse_ports):
+ self.h, self.data, self.device, self.private = h, data, device, Path(private).resolve()
+ self.metro, self.reverse_ports, self.pending = metro, reverse_ports, None
+
+ def __getattr__(self, name):
+ return getattr(self.h, name)
+
+ def command(self, args, label, **kwargs):
+ reverse = ['adb', '-s', self.device, 'reverse', 'tcp:8767', 'tcp:8767']
+ if args == reverse and self.h.PLATFORM == 'ANDROID':
+ value = self.h.command(args, label, **kwargs)
+ self.reverse_ports.add('8767')
+ return value
+ self.metro.app_stopped, self.pending = False, None
+ name = Path(args[-1]).name
+ if (args[:4] != [self.data['maestro']['binary'], '--device', self.device, 'test'] or
+ args[-1] != '.github/native/' + name or name not in FLOW_PHASES or
+ self.metro.phase not in FLOW_PHASES[name] or kwargs.get('error_details') is not False or
+ 'APP_ID=' + self.h.APP_IDS[self.h.PLATFORM] not in args):
+ raise RuntimeError('PRODUCT_METRO_REVIEWED_FLOW_REQUIRED')
+ flow = self.h.ROOT / args[-1]
+ if flow.is_symlink() or not flow.read_text().rstrip().endswith('- stopApp'):
+ raise RuntimeError('PRODUCT_METRO_FINAL_STOP_APP_REQUIRED')
+ paths = []
+ for flag in ('--output', '--debug-output', '--test-output-dir'):
+ if args.count(flag) != 1:
+ raise RuntimeError('PRODUCT_METRO_PRIVATE_OUTPUT_REQUIRED')
+ path = Path(args[args.index(flag) + 1])
+ if path.is_symlink() or not path.resolve().is_relative_to(self.private):
+ raise RuntimeError('PRODUCT_METRO_PRIVATE_OUTPUT_REQUIRED')
+ paths.append(path)
+ if args.count('--format') != 1 or args[args.index('--format') + 1] != 'junit':
+ raise RuntimeError('PRODUCT_METRO_JUNIT_FORMAT_REQUIRED')
+ report = paths[0]
+ report.unlink(missing_ok=True)
+ value = self.h.command(args, label, **kwargs)
+ if report.is_symlink() or not report.resolve().is_relative_to(self.private):
+ raise RuntimeError('PRODUCT_METRO_PRIVATE_JUNIT_REQUIRED')
+ self.pending = report.resolve()
+ return value
+
+ def successful_junit(self, report):
+ if (Path(report).is_symlink() or not Path(report).resolve().is_relative_to(self.private) or
+ self.pending != Path(report).resolve()):
+ raise RuntimeError('PRODUCT_METRO_MATCHING_JUNIT_REQUIRED')
+ self.pending = None
+ value = self.h.successful_junit(report)
+ self.metro.app_stopped = True
+ return value
diff --git a/.github/native/product_pin_metric.js b/.github/native/product_pin_metric.js
new file mode 100644
index 0000000000..e10d8137c7
--- /dev/null
+++ b/.github/native/product_pin_metric.js
@@ -0,0 +1,16 @@
+// Optional host-side progress only. Never send PINs, app text or exceptions.
+const pinMarkers = [
+ 'confirm_passcode_visible', 'confirmation_digits_tapped', 'create_tapped',
+ 'continue_visible', 'continue_tapped', 'cancel_visible', 'cancel_tapped',
+ 'skip_visible', 'skip_tapped', 'start_new_visible',
+];
+if (typeof MARKER === 'string' && pinMarkers.indexOf(MARKER) >= 0) {
+ try {
+ http.post('http://127.0.0.1:8765/pin-progress', {
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ marker: MARKER }),
+ });
+ } catch (ignored) {
+ // Missing progress is retained as incomplete; existing UI acceptance decides.
+ }
+}
diff --git a/.github/native/product_prepare_pin.yaml b/.github/native/product_prepare_pin.yaml
new file mode 100644
index 0000000000..8d4e5d5810
--- /dev/null
+++ b/.github/native/product_prepare_pin.yaml
@@ -0,0 +1,72 @@
+appId: ${APP_ID}
+---
+- repeat:
+ times: 4
+ commands:
+ - tapOn:
+ id: key_1
+- assertVisible: Confirm your passcode
+- runScript:
+ file: product_pin_metric.js
+ env:
+ MARKER: confirm_passcode_visible
+- repeat:
+ times: 4
+ commands:
+ - tapOn:
+ id: key_1
+- runScript:
+ file: product_pin_metric.js
+ env:
+ MARKER: confirmation_digits_tapped
+- tapOn: Create
+- runScript:
+ file: product_pin_metric.js
+ env:
+ MARKER: create_tapped
+- extendedWaitUntil:
+ visible: Continue
+ timeout: 30000
+- runScript:
+ file: product_pin_metric.js
+ env:
+ MARKER: continue_visible
+- tapOn: Continue
+- runScript:
+ file: product_pin_metric.js
+ env:
+ MARKER: continue_tapped
+- extendedWaitUntil:
+ visible: Cancel
+ timeout: 30000
+- runScript:
+ file: product_pin_metric.js
+ env:
+ MARKER: cancel_visible
+- tapOn: Cancel
+- runScript:
+ file: product_pin_metric.js
+ env:
+ MARKER: cancel_tapped
+- extendedWaitUntil:
+ visible:
+ id: btn_skip
+ timeout: 30000
+- runScript:
+ file: product_pin_metric.js
+ env:
+ MARKER: skip_visible
+- tapOn:
+ id: btn_skip
+- runScript:
+ file: product_pin_metric.js
+ env:
+ MARKER: skip_tapped
+- extendedWaitUntil:
+ visible:
+ id: view_startNewTile
+ timeout: 30000
+- runScript:
+ file: product_pin_metric.js
+ env:
+ MARKER: start_new_visible
diff --git a/.github/native/product_retry.yaml b/.github/native/product_retry.yaml
new file mode 100644
index 0000000000..cd2b5e235f
--- /dev/null
+++ b/.github/native/product_retry.yaml
@@ -0,0 +1,87 @@
+# Sixth fresh fixture, outside all five performance samples. First HTTP body is
+# read then disconnected before any server commit; only explicit UI Retry succeeds.
+appId: ${APP_ID}
+name: Full app controlled setup disconnect Retry and cold persistence
+---
+- runScript:
+ file: product_metric.js
+ env:
+ STAGE: retry_fixture_start
+- launchApp:
+ permissions:
+ all: deny
+- extendedWaitUntil:
+ visible: Create a passcode
+ timeout: 180000
+- runFlow: product_prepare_pin.yaml
+- tapOn:
+ id: view_startNewTile
+- extendedWaitUntil:
+ visible: '^Something went wrong$'
+ timeout: 60000
+- assertVisible: '^Please check your internet connection and try again\.$'
+- assertVisible: '^Retry$'
+- assertNotVisible:
+ text: '^Something went wrong$'
+ index: 1
+- assertNotVisible: '^Next$'
+- runScript:
+ file: product_metric.js
+ env:
+ STAGE: retry_error_visible
+- runScript:
+ file: product_metric.js
+ env:
+ STAGE: retry_submit
+- tapOn: '^Retry$'
+- extendedWaitUntil:
+ visible: '^Next$'
+ timeout: 180000
+- assertNotVisible: '^Something went wrong$'
+- tapOn: '^Next$'
+- extendedWaitUntil:
+ visible: Protect Your Recovery Key
+ timeout: 30000
+- tapOn: Skip for Now
+- extendedWaitUntil:
+ visible: Continue Without Backup?
+ timeout: 30000
+- tapOn: Skip Backup
+- extendedWaitUntil:
+ visible:
+ id: home_visible_wallet_count_1
+ timeout: 30000
+- assertVisible: Mobile Wallet
+- runScript:
+ file: product_metric.js
+ env:
+ STAGE: retry_home_ready
+- stopApp
+- runScript:
+ file: product_metric.js
+ env:
+ STAGE: retry_relaunch_start
+- launchApp
+- extendedWaitUntil:
+ visible: Enter your passcode
+ timeout: 60000
+- runScript:
+ file: product_metric.js
+ env:
+ STAGE: retry_relaunch_login
+- repeat:
+ times: 4
+ commands:
+ - tapOn:
+ id: key_1
+- tapOn: Proceed
+- extendedWaitUntil:
+ visible:
+ id: home_visible_wallet_count_1
+ timeout: 60000
+- assertVisible: Mobile Wallet
+- runScript:
+ file: product_metric.js
+ env:
+ STAGE: retry_relaunch_home
+- stopApp
diff --git a/.github/native/product_vault_acceptance.py b/.github/native/product_vault_acceptance.py
new file mode 100644
index 0000000000..99e5adb476
--- /dev/null
+++ b/.github/native/product_vault_acceptance.py
@@ -0,0 +1,195 @@
+"""Real normal-app Vault reference UI companion, scheduled by product runner.
+
+No device discovery, database/credential injection, build, standalone CLI or
+native scheduling entrypoint. The coordinator owns the existing Metro/device.
+"""
+import importlib.util
+import json
+import os
+from pathlib import Path
+import shutil
+import subprocess
+import threading
+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
+
+PORT = 8769
+STAGES = (
+ 'predecessor_fixture_verified', 'native_mobile_and_public_seed_created',
+ 'real_two_of_two_vault_created', 'visible_reference_blocks_mobile_deletion',
+ 'hidden_reference_blocks_without_name_after_relaunch',
+ 'vault_unhidden_with_correct_native_pin',
+ 'zero_balance_rotation_retained_original_archive',
+ 'archived_only_mobile_logically_archived',
+ 'archived_vault_reinstated_after_cold_restart',
+ 'retained_mobile_key_is_protected_again',
+ 'unrelated_wallet_preserved_final_count_three',
+)
+
+
+class Receipt:
+ def __init__(self):
+ self.lock = threading.Lock()
+ self.completed = []
+
+ def mark(self, stage):
+ with self.lock:
+ if len(self.completed) >= len(STAGES) or stage != STAGES[len(self.completed)]:
+ return False
+ self.completed.append(stage)
+ return True
+
+ def snapshot(self, passed=False):
+ with self.lock:
+ if passed and self.completed != list(STAGES):
+ raise RuntimeError('PRODUCT_VAULT_UI_INCOMPLETE')
+ return {
+ 'status': 'PASS' if passed else 'FAIL',
+ 'completed_stages': list(self.completed),
+ 'entrypoint': 'index.js', 'network': 'TESTNET',
+ 'scenario': 'NORMAL_UI_TWO_OF_TWO_MOBILE_PUBLIC_SEED_VAULT_REFERENCES',
+ 'seed_fixture_origin': 'PUBLIC_BIP39_REFERENCE_VECTORS_DERIVED_BY_APP',
+ 'mobile_key_origin': 'NORMAL_MY_KEEPER_GENERATION_WITH_NATIVE_PIN',
+ 'visible_reference_ui': 'PASS' if passed else 'NOT ESTABLISHED',
+ 'hidden_reference_ui': 'PASS' if passed else 'NOT ESTABLISHED',
+ 'archived_only_key_semantics': (
+ 'LOGICAL_ARCHIVE_AND_REINSTATE_VERIFIED' if passed else 'NOT ESTABLISHED'),
+ 'archived_signer_record_retention_ui': 'PASS' if passed else 'NOT ESTABLISHED',
+ 'native_private_material_exactness': 'NOT DIRECTLY INSPECTED BY UI',
+ 'unrelated_mobile_wallet_retained': True if passed else None,
+ 'final_visible_wallet_count': 3 if passed else None,
+ 'final_visible_wallet_composition': (
+ 'ONE_MOBILE_WALLET_AND_TWO_REAL_VAULTS' if passed else None),
+ 'physical_biometrics': 'NOT RUN',
+ 'hardware_device_checks': 'NOT RUN',
+ 'backend_compatibility': 'NOT TESTED BY LOOPBACK_UI_FIXTURE',
+ 'protected_backup': 'DISABLED_FOR_DISPOSABLE_FIXTURE',
+ 'release_readiness': 'NOT ESTABLISHED',
+ }
+
+
+def make_server(receipt, port=PORT):
+ class Handler(BaseHTTPRequestHandler):
+ def log_message(self, *_):
+ pass
+
+ def reply(self, status):
+ self.send_response(status)
+ self.send_header('Content-Length', '0')
+ self.end_headers()
+
+ def do_POST(self):
+ try:
+ length = int(self.headers.get('Content-Length', '0'))
+ if self.path != '/metric' or not 0 < length <= 128:
+ self.close_connection = True
+ return self.reply(422)
+ metric = json.loads(self.rfile.read(length))
+ if (isinstance(metric, dict) and set(metric) == {'stage'} and
+ receipt.mark(metric['stage'])):
+ return self.reply(200)
+ except (ValueError, TypeError):
+ pass
+ self.reply(422)
+
+ def do_GET(self):
+ self.reply(405)
+
+ class Server(ThreadingHTTPServer):
+ allow_reuse_address = False
+ daemon_threads = True
+
+ return Server(('127.0.0.1', port), Handler)
+
+
+def run_companion(h, data, device, private, backend_receipt, installed_proof):
+ """Called only after successful existing key UI on the same fixture/device.
+
+ installed_proof is the reviewed product_key_acceptance.installed_proof helper;
+ the source-owned parent must pass that existing helper without replacement.
+ """
+ if (os.environ.get('GITHUB_ACTIONS') != 'true' or
+ os.environ.get('RUNNER_ENVIRONMENT') != 'github-hosted' or
+ h.PLATFORM not in ['IOS', 'ANDROID'] or
+ (h.PLATFORM == 'ANDROID' and not device.startswith('emulator-'))):
+ raise RuntimeError('PRODUCT_VAULT_UI_OWNED_HOSTED_DEVICE_REQUIRED')
+ actual = subprocess.check_output(['git', 'rev-parse', 'HEAD'], cwd=h.ROOT, text=True).strip()
+ if (data['build'] != 'PASS' or actual != data['source_sha'] or
+ actual != os.environ.get('KEEPER_SOURCE_SHA') or
+ h.artifact_identity() != data['built_artifact']):
+ raise RuntimeError('PRODUCT_VAULT_UI_EXACT_BUILD_REQUIRED')
+ if subprocess.run(['git', 'diff', '--quiet', 'HEAD', '--', '.github/native', 'src',
+ 'index.js', 'App.tsx', 'metro.config.js', 'babel.config.js'],
+ cwd=h.ROOT, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL).returncode:
+ raise RuntimeError('PRODUCT_VAULT_UI_COMMITTED_SOURCE_REQUIRED')
+ before = backend_receipt.snapshot(passed=True)
+ predecessor = h.read().get('product_key_ui', {})
+ if (before.get('status') != 'PASS' or before.get('sample') != 6 or
+ before.get('scenario') != 'CONTROLLED_DISCONNECT_BEFORE_COMMIT_NOT_WAN_OFFLINE' or
+ before.get('create_new_app_calls') != 2 or
+ before.get('visible_wallet_count_after_relaunch') != 1 or
+ predecessor.get('status') != 'PASS' or
+ predecessor.get('scenario') != 'UNUSED_MOBILE_KEY_UI_DELETE_AND_NATIVE_PIN' or
+ predecessor.get('visible_eligible_keys_after_deletion') != 0 or
+ predecessor.get('unrelated_visible_wallet_count_after_relaunch') != 1 or
+ predecessor.get('new_account_requests_during_key_flow') != 0 or
+ predecessor.get('installed_artifact_verified') is not True):
+ raise RuntimeError('PRODUCT_VAULT_UI_COMPLETED_DISPOSABLE_PREDECESSOR_REQUIRED')
+ spec = importlib.util.spec_from_file_location('product_key_acceptance',
+ Path(__file__).with_name('product_key_acceptance.py'))
+ key_ui = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(key_ui)
+ output = Path(private) / 'vault-ui'
+ output.mkdir(mode=0o700)
+ report = output / 'junit.xml'
+ receipt = Receipt()
+ result = receipt.snapshot()
+ result['status'] = 'RUNNING'
+ server = None
+
+ def save():
+ current = h.read()
+ current['product_vault_ui'] = result
+ h.save(current)
+
+ try:
+ save()
+ installed_before = installed_proof(h, device)
+ if predecessor.get('installed_artifact') != installed_before:
+ raise RuntimeError('PRODUCT_VAULT_UI_PREDECESSOR_INSTALLATION_CHANGED')
+ server = make_server(receipt)
+ thread = threading.Thread(target=server.serve_forever, daemon=True)
+ thread.start()
+ h.command([data['maestro']['binary'], '--device', device, 'test',
+ '--env', 'APP_ID=' + h.APP_IDS[h.PLATFORM], '--flatten-debug-output',
+ '--debug-output', str(output), '--test-output-dir', str(output),
+ '--format', 'junit', '--output', str(report),
+ '.github/native/product_vault_acceptance.yaml'],
+ 'Normal-app genuine Vault visible hidden and archived key references',
+ timeout=1800, error_details=False)
+ h.successful_junit(report)
+ if h.artifact_identity() != data['built_artifact']:
+ raise RuntimeError('PRODUCT_VAULT_UI_ARTIFACT_CHANGED')
+ installed_after = installed_proof(h, device)
+ if installed_after != installed_before:
+ raise RuntimeError('PRODUCT_VAULT_UI_INSTALLED_BYTES_CHANGED')
+ after = backend_receipt.snapshot(passed=True)
+ if after['create_new_app_calls'] != before['create_new_app_calls']:
+ raise RuntimeError('PRODUCT_VAULT_UI_UNEXPECTED_ACCOUNT_SETUP')
+ result = receipt.snapshot(passed=True)
+ result['new_account_requests_during_vault_flow'] = 0
+ result['installed_artifact_verified'] = True
+ result['installed_artifact'] = installed_after
+ except Exception as error:
+ result = receipt.snapshot()
+ result['failure_category'] = type(error).__name__
+ raise
+ finally:
+ operations = []
+ if server:
+ operations += [('server-shutdown', server.shutdown), ('server-close', server.server_close)]
+ # Failure diagnostics can contain PIN actions and app hierarchy. Visit
+ # disposal even when another boundary fails, then persist safe evidence.
+ operations.append(('private-output', lambda: shutil.rmtree(output)))
+ key_ui.finalize_companion(result, save, operations, 'failure_category' in result,
+ 'PRODUCT_VAULT_UI_CLEANUP_FAILED')
+ return result
diff --git a/.github/native/product_vault_acceptance.yaml b/.github/native/product_vault_acceptance.yaml
new file mode 100644
index 0000000000..ba54e35141
--- /dev/null
+++ b/.github/native/product_vault_acceptance.yaml
@@ -0,0 +1,380 @@
+# Ordinary index.js and real app PIN/Realm/sagas; no state or key injection.
+# Runs after product_key_acceptance on the same owned Testnet installation.
+# All seed input below is deliberately PUBLIC BIP39 reference-test input.
+appId: ${APP_ID}
+name: Real visible hidden and archived Vault Mobile key references
+---
+- runFlow:
+ file: product_vault_login.yaml
+ env:
+ WALLET_COUNT: '1'
+- tapOn:
+ id: home_tab_keys
+- tapOn:
+ id: manage_keys_actions
+- extendedWaitUntil:
+ visible: All the keys are hidden
+ timeout: 30000
+- assertNotVisible:
+ id: btnDelete
+- runScript:
+ file: product_vault_metric.js
+ env:
+ STAGE: predecessor_fixture_verified
+- tapOn:
+ id: btn_back
+- tapOn:
+ id: keys_add_key
+- tapOn: Add a software key
+- extendedWaitUntil:
+ visible:
+ id: btn_MY_KEEPER
+ timeout: 30000
+- tapOn:
+ id: btn_MY_KEEPER
+- extendedWaitUntil:
+ visible: Setting up Mobile Key \(Hot\)
+ timeout: 30000
+- tapOn: Proceed
+- extendedWaitUntil:
+ visible: Confirm passcode to generate key
+ timeout: 30000
+- runFlow: product_vault_pin.yaml
+- extendedWaitUntil:
+ visible: Mobile Key Added Successfully!
+ timeout: 60000
+- assertNotVisible:
+ id: seed_item_0
+- tapOn: Cancel
+- tapOn:
+ id: keys_add_key
+- tapOn: Add a software key
+- runFlow:
+ file: product_vault_public_seed.yaml
+ env:
+ PUBLIC_WORDS: abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about
+- runScript:
+ file: product_vault_metric.js
+ env:
+ STAGE: native_mobile_and_public_seed_created
+- tapOn:
+ id: home_tab_wallets
+- tapOn:
+ id: wallets_add_wallet
+- tapOn: Create Wallet
+- extendedWaitUntil:
+ visible: Select your wallet type
+ timeout: 30000
+- tapOn: Select custom setup.*
+- extendedWaitUntil:
+ visible: Create a Custom Wallet
+ timeout: 30000
+# Default2-of3 -> real2-of2, never a Mobile1-of1 hot-wallet substitute.
+- tapOn:
+ id: btn_decreaseValue
+ index: 0
+- tapOn: Confirm
+- tapOn: Proceed
+- extendedWaitUntil:
+ visible: Select 2 keys for your wallet
+ timeout: 30000
+- tapOn:
+ id: btn_Mobile Key
+- tapOn:
+ id: btn_Seed Key
+- tapOn: Proceed
+- extendedWaitUntil:
+ visible:
+ id: input_input_wallet_name
+ timeout: 30000
+- tapOn:
+ id: input_input_wallet_name
+- inputText: R5 Reference Vault
+- hideKeyboard
+- assertVisible: Mobile Key
+- assertVisible: Seed Key
+- tapOn: Create Your Wallet
+- extendedWaitUntil:
+ visible: Wallet Created Successfully
+ timeout: 120000
+- assertVisible: 2-of-2
+- tapOn: View Wallet
+# Normal creation asks for a tip after2seconds. Decline, never open SendTip.
+- extendedWaitUntil:
+ visible: No Thanks
+ timeout: 15000
+- tapOn: No Thanks
+- assertVisible: R5 Reference Vault
+- tapOn:
+ id: wallet_details_back
+- extendedWaitUntil:
+ visible:
+ id: home_visible_wallet_count_2
+ timeout: 30000
+- assertVisible: Mobile Wallet
+- assertVisible: R5 Reference Vault
+- runScript:
+ file: product_vault_metric.js
+ env:
+ STAGE: real_two_of_two_vault_created
+- tapOn:
+ id: home_tab_keys
+- tapOn:
+ id: manage_keys_actions
+# Exactly one visible Mobile key. Scope its action by the safe type-only row.
+- assertVisible: Mobile Key
+- tapOn:
+ id: btnDelete
+ childOf:
+ id: manage_key_type_MY_KEEPER
+- extendedWaitUntil:
+ visible: Key Used in Wallet
+ timeout: 30000
+- assertVisible: R5 Reference Vault
+- assertVisible: This key cannot be deleted because it is used by the wallet below.
+- assertNotVisible: Confirm passcode to delete key
+- assertNotVisible:
+ id: modal_passcode_verify
+- runScript:
+ file: product_vault_metric.js
+ env:
+ STAGE: visible_reference_blocks_mobile_deletion
+- tapOn: Back
+- tapOn:
+ id: btn_back
+- tapOn:
+ id: home_tab_wallets
+- tapOn: R5 Reference Vault
+- tapOn:
+ id: wallet_details_settings
+- scrollUntilVisible:
+ element: Hide wallet
+ direction: DOWN
+ timeout: 30000
+- tapOn: Hide wallet
+- extendedWaitUntil:
+ visible:
+ id: home_visible_wallet_count_1
+ timeout: 30000
+- assertVisible: Mobile Wallet
+- assertNotVisible: R5 Reference Vault
+- stopApp
+- runFlow:
+ file: product_vault_login.yaml
+ env:
+ WALLET_COUNT: '1'
+- assertNotVisible: R5 Reference Vault
+- tapOn:
+ id: home_tab_keys
+- tapOn:
+ id: manage_keys_actions
+- assertVisible: Mobile Key
+- tapOn:
+ id: btnDelete
+ childOf:
+ id: manage_key_type_MY_KEEPER
+- extendedWaitUntil:
+ visible: Key Used in Wallet
+ timeout: 30000
+- assertVisible: Keep this key until the wallet no longer needs it. Hiding a wallet does not remove its key references.
+- assertNotVisible: R5 Reference Vault
+- assertNotVisible: This key cannot be deleted because it is used by the wallet below.
+- assertNotVisible:
+ id: modal_passcode_verify
+- runScript:
+ file: product_vault_metric.js
+ env:
+ STAGE: hidden_reference_blocks_without_name_after_relaunch
+- tapOn: View Vault
+- extendedWaitUntil:
+ visible: Show hidden wallets
+ timeout: 30000
+- tapOn: Show hidden wallets
+- extendedWaitUntil:
+ visible:
+ id: modal_passcode_verify
+ timeout: 30000
+- runFlow: product_vault_pin.yaml
+- extendedWaitUntil:
+ visible: R5 Reference Vault
+ timeout: 30000
+# This is the only hidden row; Mobile Wallet remained visible throughout.
+- tapOn:
+ id: btnUnhide
+- extendedWaitUntil:
+ visible:
+ id: modal_passcode_verify
+ timeout: 30000
+- runFlow: product_vault_pin.yaml
+- extendedWaitUntil:
+ notVisible:
+ id: btnUnhide
+ timeout: 30000
+- stopApp
+- runFlow:
+ file: product_vault_login.yaml
+ env:
+ WALLET_COUNT: '2'
+- assertVisible: R5 Reference Vault
+- runScript:
+ file: product_vault_metric.js
+ env:
+ STAGE: vault_unhidden_with_correct_native_pin
+- tapOn: R5 Reference Vault
+- tapOn: More\s+Options
+- tapOn: Manage Keys
+- extendedWaitUntil:
+ visible:
+ id: btn_Mobile Key
+ timeout: 30000
+- tapOn:
+ id: btn_Mobile Key
+- scrollUntilVisible:
+ element: Change Key
+ direction: DOWN
+ timeout: 30000
+- tapOn: Change Key
+- tapOn:
+ id: btn_add_new_key
+- tapOn: Add a software key
+- runFlow:
+ file: product_vault_public_seed.yaml
+ env:
+ PUBLIC_WORDS: legal winner thank year wave sausage worth useful legal winner thank yellow
+# A is already the retained co-signer; B is the second imported public Seed.
+- tapOn:
+ id: btn_Seed Key
+ index: 1
+- tapOn: Replace Key
+# Nonzero original balance takes a send/migration path, which this suite
+# never follows. Only zero-balance archival reaches this confirmation.
+- extendedWaitUntil:
+ visible: Key Replaced Successfully
+ timeout: 120000
+- tapOn: View Wallet
+- assertVisible: R5 Reference Vault
+- tapOn:
+ id: wallet_details_settings
+- scrollUntilVisible:
+ element: Archived wallet versions
+ direction: DOWN
+ timeout: 30000
+- tapOn: Archived wallet versions
+- extendedWaitUntil:
+ visible:
+ id: header_title
+ text: Archived Vaults
+ timeout: 30000
+- tapOn: R5 Reference Vault
+- tapOn: More\s+Options
+- assertVisible: Reinstate
+- runScript:
+ file: product_vault_metric.js
+ env:
+ STAGE: zero_balance_rotation_retained_original_archive
+- stopApp
+- runFlow:
+ file: product_vault_login.yaml
+ env:
+ WALLET_COUNT: '2'
+- tapOn:
+ id: home_tab_keys
+- tapOn:
+ id: manage_keys_actions
+- assertVisible: Mobile Key
+- tapOn:
+ id: btnDelete
+ childOf:
+ id: manage_key_type_MY_KEEPER
+- extendedWaitUntil:
+ visible: Confirm passcode to delete key
+ timeout: 30000
+- assertNotVisible: Key Used in Wallet
+- runFlow: product_vault_pin.yaml
+- extendedWaitUntil:
+ visible: Key Deleted Successfully
+ timeout: 60000
+- tapOn: Continue
+- extendedWaitUntil:
+ notVisible: Mobile Key
+ timeout: 30000
+- assertVisible: Seed Key
+- runScript:
+ file: product_vault_metric.js
+ env:
+ STAGE: archived_only_mobile_logically_archived
+- stopApp
+- runFlow:
+ file: product_vault_login.yaml
+ env:
+ WALLET_COUNT: '2'
+- tapOn:
+ id: home_tab_keys
+- tapOn:
+ id: manage_keys_actions
+- assertNotVisible: Mobile Key
+- tapOn:
+ id: btn_back
+- tapOn:
+ id: home_tab_wallets
+- tapOn: R5 Reference Vault
+- tapOn:
+ id: wallet_details_settings
+- scrollUntilVisible:
+ element: Archived wallet versions
+ direction: DOWN
+ timeout: 30000
+- tapOn: Archived wallet versions
+- tapOn: R5 Reference Vault
+- tapOn: More\s+Options
+- tapOn: Reinstate
+# The callback is delayed by300ms. Wait for dispatch before stopping the app;
+# the toast alone is not acceptance, so require the cold counts/key checks next.
+- extendedWaitUntil:
+ visible: Vault reinstated successfully
+ timeout: 30000
+# The worker atomically refuses reinstatement if a signer record is missing.
+# Verify the actual result after a cold restart, not merely its optimistic toast.
+- stopApp
+- runFlow:
+ file: product_vault_login.yaml
+ env:
+ WALLET_COUNT: '3'
+- runScript:
+ file: product_vault_metric.js
+ env:
+ STAGE: archived_vault_reinstated_after_cold_restart
+- tapOn:
+ id: home_tab_keys
+- tapOn:
+ id: manage_keys_actions
+- assertVisible: Mobile Key
+- tapOn:
+ id: btnDelete
+ childOf:
+ id: manage_key_type_MY_KEEPER
+- extendedWaitUntil:
+ visible: Key Used in Wallet
+ timeout: 30000
+- assertVisible: R5 Reference Vault
+- assertNotVisible:
+ id: modal_passcode_verify
+- runScript:
+ file: product_vault_metric.js
+ env:
+ STAGE: retained_mobile_key_is_protected_again
+- tapOn: Back
+- tapOn:
+ id: btn_back
+- tapOn:
+ id: home_tab_wallets
+- extendedWaitUntil:
+ visible:
+ id: home_visible_wallet_count_3
+ timeout: 30000
+- assertVisible: Mobile Wallet
+- runScript:
+ file: product_vault_metric.js
+ env:
+ STAGE: unrelated_wallet_preserved_final_count_three
+- stopApp
diff --git a/.github/native/product_vault_login.yaml b/.github/native/product_vault_login.yaml
new file mode 100644
index 0000000000..fa7383a345
--- /dev/null
+++ b/.github/native/product_vault_login.yaml
@@ -0,0 +1,12 @@
+appId: ${APP_ID}
+---
+- launchApp
+- extendedWaitUntil:
+ visible: Enter your passcode
+ timeout: 60000
+- runFlow: product_vault_pin.yaml
+- extendedWaitUntil:
+ visible:
+ id: home_visible_wallet_count_${WALLET_COUNT}
+ timeout: 60000
+- assertVisible: Mobile Wallet
diff --git a/.github/native/product_vault_metric.js b/.github/native/product_vault_metric.js
new file mode 100644
index 0000000000..5034086523
--- /dev/null
+++ b/.github/native/product_vault_metric.js
@@ -0,0 +1,6 @@
+// Fixed host-side receipts only. Never send names, fingerprints or app data.
+const reply = http.post('http://127.0.0.1:8769/metric', {
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ stage: STAGE }),
+});
+if (reply.status !== 200) throw new Error('PRODUCT_VAULT_METRIC_REJECTED');
diff --git a/.github/native/product_vault_pin.yaml b/.github/native/product_vault_pin.yaml
new file mode 100644
index 0000000000..5516280de6
--- /dev/null
+++ b/.github/native/product_vault_pin.yaml
@@ -0,0 +1,9 @@
+# Only the runner-owned disposable account uses PIN1111.
+appId: ${APP_ID}
+---
+- repeat:
+ times: 4
+ commands:
+ - tapOn:
+ id: key_1
+- tapOn: Proceed
diff --git a/.github/native/product_vault_public_seed.yaml b/.github/native/product_vault_public_seed.yaml
new file mode 100644
index 0000000000..d1567155ec
--- /dev/null
+++ b/.github/native/product_vault_public_seed.yaml
@@ -0,0 +1,54 @@
+# Public BIP39 reference vectors, never generated private wallet material.
+# Caller opens the ordinary software-key list. Import is explicit; Create is
+# never selected. The app derives fingerprints, paths and xpubs itself.
+appId: ${APP_ID}
+---
+- scrollUntilVisible:
+ element:
+ id: btn_SEED_WORDS
+ direction: DOWN
+ timeout: 30000
+- tapOn:
+ id: btn_SEED_WORDS
+- extendedWaitUntil:
+ visible: Add a Seed Key
+ timeout: 30000
+- tapOn: Import
+- extendedWaitUntil:
+ visible: Import a Seed Key
+ timeout: 30000
+- tapOn: Proceed
+- extendedWaitUntil:
+ visible: Enter Seed Words
+ timeout: 30000
+- evalScript: ${output.publicWords = PUBLIC_WORDS.split(' '); output.wordIndex = 0}
+- repeat:
+ times: 12
+ commands:
+ - scrollUntilVisible:
+ element:
+ id: input_seedWord${output.wordIndex + 1}
+ direction: DOWN
+ timeout: 30000
+ - tapOn:
+ id: input_seedWord${output.wordIndex + 1}
+ - inputText: ${output.publicWords[output.wordIndex]}
+ - extendedWaitUntil:
+ visible:
+ id: btn_suggested_${output.publicWords[output.wordIndex]}
+ timeout: 10000
+ - tapOn:
+ id: btn_suggested_${output.publicWords[output.wordIndex]}
+ - evalScript: ${output.wordIndex += 1}
+- tapOn: Next
+- extendedWaitUntil:
+ visible: Remember Seed Words\?
+ timeout: 30000
+# Only the public xpubs are retained for these fixtures.
+- tapOn: Skip
+- extendedWaitUntil:
+ visible: Seed key Added Successfully!
+ timeout: 60000
+- assertNotVisible:
+ id: seed_item_0
+- tapOn: Cancel
diff --git a/.github/native/public_companion_receipts.cjs b/.github/native/public_companion_receipts.cjs
new file mode 100644
index 0000000000..4ae062d327
--- /dev/null
+++ b/.github/native/public_companion_receipts.cjs
@@ -0,0 +1,120 @@
+'use strict';
+// Pure public receipt validation. This module grants no parent acceptance or
+// authorization. SHA/run/attempt/App/artifact provenance belongs to the caller.
+const SCOPES = Object.freeze({
+ 'controlled-credential-json-ui': 'controlled malformed native Keychain JSON blocking Retry and restored cold login; not OS denial or physical biometrics',
+ 'controlled-version-history-ui': 'controlled stale/empty native Realm history observation and restoration; not authentic historical installation or migration',
+ 'vault-reference-and-logical-archive-ui': 'normal UI real Vault visible/hidden references and logical archive/reinstate; no private-byte inspection or protected-backup acceptance',
+});
+const CREDENTIAL_STAGES = Object.freeze(['malformed_startup_blocked', 'retry_remains_blocked', 'malformed_cold_start_blocked',
+ 'restored_login_available', 'restored_wallet_preserved', 'restored_cold_wallet_preserved']);
+const HISTORY_STAGES = Object.freeze(['history_seed_stale', 'stale_first_ui', 'history_verify_stale_first', 'stale_repeat_ui',
+ 'history_verify_stale_repeat', 'history_seed_empty', 'empty_first_ui', 'history_verify_empty_first', 'empty_repeat_ui',
+ 'history_verify_empty_repeat', 'history_restore', 'history_verify_restored']);
+const VAULT_STAGES = Object.freeze(['predecessor_fixture_verified', 'native_mobile_and_public_seed_created',
+ 'real_two_of_two_vault_created', 'visible_reference_blocks_mobile_deletion', 'hidden_reference_blocks_without_name_after_relaunch',
+ 'vault_unhidden_with_correct_native_pin', 'zero_balance_rotation_retained_original_archive', 'archived_only_mobile_logically_archived',
+ 'archived_vault_reinstated_after_cold_restart', 'retained_mobile_key_is_protected_again', 'unrelated_wallet_preserved_final_count_three']);
+const CREDENTIAL = Object.freeze({
+ status: 'PASS', entrypoint_under_test: 'index.js', scenario: 'ACTUAL_KEYCHAIN_CONTROLLED_MALFORMED_JSON',
+ native_credential_api: 'react-native-keychain', original_credential_exported: false,
+ backup_service_removed_after_verified_restore: true, visible_wallet_count_after_recovery_and_cold_login: 1,
+ successfully_empty_store: 'REJECTED_FIXTURE_PRECONDITION_NOT_A_READ_ERROR',
+ retry_scope: 'User taps Retry while malformed value persists; blocking UI remains. Native read-call count is not instrumented.',
+ os_keychain_denial_or_hardware_read_fault: 'NOT RUN', same_process_retry_after_external_repair: 'NOT RUN',
+ physical_devices: 'NOT RUN', backend_compatibility: 'NOT TESTED', new_account_requests_during_credential_flow: 0,
+});
+const HISTORY = Object.freeze({
+ status: 'PASS', scenario: 'CONTROLLED_STALE_AND_EMPTY_NATIVE_VERSION_HISTORY', product_entrypoint: 'index.js', network: 'TESTNET',
+ fixture_scope: 'Actual encrypted native Realm histories only; unchanged KeeperApp and shared version. Not an authentic historical installation or migration test.',
+ credentials_exported: false, physical_devices: 'NOT RUN', performance_sample: false, original_history_restored: true,
+ stale_initial_and_recovery_dates_preserved: true, stale_current_observation_count: 1, empty_current_observation_count: 1,
+ repeat_login_observation_date_unchanged: true, account_version_unchanged: true, visible_wallet_count: 1,
+ new_account_requests_during_history_flow: 0,
+});
+const VAULT = Object.freeze({
+ status: 'PASS', entrypoint: 'index.js', network: 'TESTNET', scenario: 'NORMAL_UI_TWO_OF_TWO_MOBILE_PUBLIC_SEED_VAULT_REFERENCES',
+ seed_fixture_origin: 'PUBLIC_BIP39_REFERENCE_VECTORS_DERIVED_BY_APP', mobile_key_origin: 'NORMAL_MY_KEEPER_GENERATION_WITH_NATIVE_PIN',
+ visible_reference_ui: 'PASS', hidden_reference_ui: 'PASS', archived_only_key_semantics: 'LOGICAL_ARCHIVE_AND_REINSTATE_VERIFIED',
+ archived_signer_record_retention_ui: 'PASS', native_private_material_exactness: 'NOT DIRECTLY INSPECTED BY UI',
+ unrelated_mobile_wallet_retained: true, final_visible_wallet_count: 3,
+ final_visible_wallet_composition: 'ONE_MOBILE_WALLET_AND_TWO_REAL_VAULTS', physical_biometrics: 'NOT RUN',
+ hardware_device_checks: 'NOT RUN', backend_compatibility: 'NOT TESTED BY LOOPBACK_UI_FIXTURE',
+ protected_backup: 'DISABLED_FOR_DISPOSABLE_FIXTURE', release_readiness: 'NOT ESTABLISHED', new_account_requests_during_vault_flow: 0,
+});
+const demand = value => { if (!value) throw new Error('PUBLIC_COMPANION_RECEIPT_INCOMPLETE'); };
+const exactKeys = (value, keys) => value && !Array.isArray(value) &&
+ Object.keys(value).sort().join('|') === [...keys].sort().join('|');
+const ordered = (value, expected) => Array.isArray(value) && value.length === expected.length &&
+ expected.every((item, index) => value[index] === item);
+
+function installedBytes(value, platform, expected) {
+ const [method, hashes] = platform === 'IOS' ?
+ ['FULL_SIMULATOR_BUNDLE_TREE_AND_EXECUTABLE_SHA256', ['inventory_sha256', 'executable_sha256']] :
+ ['SINGLE_INSTALLED_BASE_APK_SHA256', ['sha256']];
+ const proof = value?.installed_artifact;
+ demand(['IOS', 'ANDROID'].includes(platform) && value?.installed_artifact_verified === true &&
+ exactKeys(proof, ['method', ...hashes]) && proof.method === method &&
+ hashes.every(name => typeof proof[name] === 'string' && /^[a-f0-9]{64}$/.test(proof[name])) &&
+ (!expected || (proof.method === expected.method && hashes.every(name => proof[name] === expected[name]))));
+ return proof;
+}
+
+function validateRow(value, fields, stages, platform, proof, history = false) {
+ demand(exactKeys(value, [...Object.keys(fields), 'completed_stages', 'installed_artifact_verified', 'installed_artifact',
+ ...(history ? ['stage_evidence'] : fields === CREDENTIAL ? ['fixture_phases'] : [])]) &&
+ Object.entries(fields).every(([name, expected]) => value[name] === expected) && ordered(value.completed_stages, stages));
+ installedBytes(value, platform, proof);
+ if (fields === CREDENTIAL) demand(ordered(value.fixture_phases, ['armed', 'restored']));
+ if (history) {
+ demand(Array.isArray(value.stage_evidence) && value.stage_evidence.length === stages.length);
+ value.stage_evidence.forEach((row, index) => {
+ demand(exactKeys(row, ['stage', 'status', 'installed_artifact_verified', 'installed_artifact']) &&
+ row.stage === stages[index] && row.status === 'PASS');
+ installedBytes(row, platform, proof);
+ });
+ }
+}
+
+function contextProof(metadata, platform) {
+ const proof = installedBytes(metadata, platform);
+ const binary = platform === 'IOS' ? 'executable_sha256' : 'sha256';
+ demand(metadata.built_artifact?.[binary] === proof[binary] && metadata.product_ui?.status === 'PASS' &&
+ ['build', 'smoke', 'native_probe', 'r5_features'].every(name => metadata[name] === 'PASS'));
+ // Validate the exact source-owned switching receipt, including final normal
+ // product restoration. These are bundle-setup observations, not extra UI.
+ const phases = ['product', 'arm', 'product', 'restore', 'product',
+ ...HISTORY_STAGES.map(stage => stage.startsWith('history_') ? stage : 'product'), 'product'];
+ const switches = metadata.product_ui.companion_metro_switches;
+ demand(Array.isArray(switches) && switches.length === phases.length && switches.every((row, index) =>
+ exactKeys(row, ['phase', 'status', 'scope']) && row.phase === phases[index] && row.status === 'PASS' && row.scope === 'BUNDLE_SETUP_ONLY'));
+ return proof;
+}
+
+function publicCompanionChecks(metadata, platform) {
+ const checks = Object.fromEntries(Object.entries(SCOPES).map(([id, scope]) => [id, { status: 'NOT VERIFIED', scope }]));
+ let proof;
+ try { proof = contextProof(metadata, platform); } catch { return checks; }
+ const rows = [
+ ['controlled-credential-json-ui', 'product_credential_ui', 'credential_errors_ui', CREDENTIAL, CREDENTIAL_STAGES],
+ ['controlled-version-history-ui', 'product_version_history_ui', 'version_history_ui', HISTORY, HISTORY_STAGES],
+ ['vault-reference-and-logical-archive-ui', 'product_vault_ui', 'vault_references_ui', VAULT, VAULT_STAGES],
+ ];
+ for (const [id, root, nested, fields, stages] of rows) {
+ try {
+ // Both receipts independently satisfy the same exact public schema;
+ // there are no free-form fields to hide stale or contradictory results.
+ validateRow(metadata[root], fields, stages, platform, proof, fields === HISTORY);
+ validateRow(metadata.product_ui[nested], fields, stages, platform, proof, fields === HISTORY);
+ checks[id].status = 'PASS';
+ } catch { /* Preserve independently verified subsets without parent credit. */ }
+ }
+ return checks;
+}
+
+function validatePublicCompanions(metadata, platform) {
+ const checks = publicCompanionChecks(metadata, platform);
+ demand(Object.values(checks).every(row => row.status === 'PASS'));
+ return checks;
+}
+module.exports = { SCOPES, validatePublicCompanions, publicCompanionChecks };
diff --git a/.github/native/r5_features.js b/.github/native/r5_features.js
new file mode 100644
index 0000000000..ade865c7aa
--- /dev/null
+++ b/.github/native/r5_features.js
@@ -0,0 +1,86 @@
+// CI-only entrypoint: never imported by the production app entrypoint.
+import 'react-native-get-random-values';
+import React, { useEffect, useState } from 'react';
+import { AppRegistry, SafeAreaView, Text } from 'react-native';
+import Realm from 'realm';
+import RNFS from 'react-native-fs';
+import DeviceInfo from 'react-native-device-info';
+import { runSaga } from 'redux-saga';
+import * as effects from 'redux-saga/effects';
+import schema from '../../src/storage/realm/schema';
+import * as storage from '../../src/storage';
+import * as enums from '../../src/services/wallets/enums';
+import * as subscription from '../../src/models/enums/SubscriptionTier';
+import { RealmSchema } from '../../src/storage/realm/enum';
+import { name as appName } from '../../app.json';
+import { createWorkers, provenance } from './.generated/r5_workers';
+import { runFeatures, FeatureFailure, SCENARIOS, LIMITS } from './r5_features_core';
+
+const startedAt = performance.now();
+let attempt;
+function FeatureProbe() {
+ const [stage, setStage] = useState('running');
+ useEffect(() => {
+ let active = true;
+ if (!attempt) {
+ attempt = (async () => {
+ let result;
+ let failure;
+ try {
+ if (!__DEV__) throw new FeatureFailure('development-only');
+ result = await runFeatures({
+ Realm,
+ schema,
+ storage,
+ createWorkers,
+ effects,
+ runSaga,
+ enums,
+ subscription,
+ RealmSchema,
+ DeviceInfo,
+ now: () => performance.now(),
+ startedAt,
+ });
+ } catch (error) {
+ failure = error instanceof FeatureFailure ? error.code : 'native-exception';
+ result = {
+ stage: 'failed',
+ measurements: [],
+ scenarios: SCENARIOS.map((id) => ({ id, status: 'FAIL' })),
+ };
+ }
+ const evidence = {
+ schema: 1,
+ scope: 'production-worker-native-storage',
+ status:
+ result.stage === 'pass' ? 'PASS' : result.stage === 'failed' ? 'FAIL' : 'IN PROGRESS',
+ stage: result.stage,
+ scenarios: result.scenarios,
+ measurements: result.measurements,
+ limits: LIMITS,
+ source_functions: provenance,
+ ...(failure ? { failure } : {}),
+ };
+ await RNFS.writeFile(
+ `${RNFS.DocumentDirectoryPath}/keeper-r5-native-evidence.json`,
+ JSON.stringify(evidence),
+ 'utf8'
+ );
+ return result.stage;
+ })().catch(() => 'failed');
+ }
+ attempt.then((value) => {
+ if (active) setStage(value);
+ });
+ return () => {
+ active = false;
+ };
+ }, []);
+ return (
+
+ Keeper R5 native worker probe {stage}
+
+ );
+}
+AppRegistry.registerComponent(appName, () => FeatureProbe);
diff --git a/.github/native/r5_features.md b/.github/native/r5_features.md
new file mode 100644
index 0000000000..95c1b581a1
--- /dev/null
+++ b/.github/native/r5_features.md
@@ -0,0 +1,15 @@
+# R5 production-worker native witness
+
+This isolated diagnostic adds native storage evidence to the R5 worker regressions. It never replaces the ordinary application entrypoint. Select `r5_metro.cjs` only in a disposable development simulator/emulator job, after running `node .github/native/r5_prepare.cjs`.
+
+The preparation script extracts the current candidate's unchanged setup and deletion worker definitions, signer identity functions and account-session observer. It records the SHA-256 of every containing source module and fails if a selected definition disappears or becomes ambiguous. The generated module is ignored by Git; it is regenerated from the checked-out candidate before Metro starts. The native entrypoint imports the actual current Realm schemas, Realm, MMKV, Redux Saga and native DeviceInfo.
+
+The six-process Maestro flow runs five independent disposable cases and then verifies their persisted counts. Each case tests the production setup worker's offline/error/retry decisions and preservation of its one native wallet; the production deletion workers' live, hidden, canary and archived reference checks; native transaction rollback when a later deletion target is absent; and rejection after an A → B → A session change. Another encrypted Realm remains untouched. The last process reopens all five pairs of files, verifies exact wallet/key counts, and removes the fixtures and its MMKV marker.
+
+The test adapters deliberately control Relay responses, wallet/key generation, dispatch, database selection and the backup local-commit boundary. They persist invalid public sentinel records, with no valid seed, private key, address, network call or remote backup confirmation. These checks cover production worker behavior over native storage. They do **not** establish product navigation, concealed UI, PIN/biometric behavior, account login, cryptographic derivation, genuine protected-backup protocol compatibility, old-schema migration or release readiness. Keep those acceptance rows open until their own executable checks pass.
+
+`keeper-r5-native-evidence.json` contains only fixed scenario/status/limitation identifiers, source paths/hashes/function names and five raw timing pairs. `probe_ready_ms` measures this alternate probe's preparation; `setup_first_wallet_ms` measures the controlled worker's first native synthetic-wallet write. Neither is the full app's cold-start or first-wallet UX latency. The separate full-product measurement flow must supply those user-facing measurements. Native host orchestration must validate this JSON and the unchanged installed artifact identity; a Maestro result alone is insufficient.
+
+Initial source package: based on `c1c4b803039b61b940373c4dc9d08473cf25e042` (core `77b72da29ac5f2cdf3f51c9a0e9f3fd1c2af7238` plus 5.1). Approximately 7.5k changed code/test tokens, two related worker scenario areas. No producer branch, app/native dependency input or release configuration changed.
+
+Actual local checks: six host-only extraction/schema/phase/limitation contract tests PASS; Babel transforms PASS; formatting and whitespace PASS. No native application build or simulator/emulator run was performed for this initial commit. Run the integrated exact candidate through both hosted platforms before assigning native PASS. Physical-device and independent security review evidence remain separate.
diff --git a/.github/native/r5_features.yaml b/.github/native/r5_features.yaml
new file mode 100644
index 0000000000..f517b6ed75
--- /dev/null
+++ b/.github/native/r5_features.yaml
@@ -0,0 +1,35 @@
+appId: ${APP_ID}
+name: Production R5 workers over disposable native storage across six processes
+---
+- launchApp:
+ clearState: true
+ permissions:
+ all: deny
+- extendedWaitUntil:
+ visible:
+ id: r5-features-next
+ timeout: 90000
+- assertNotVisible:
+ id: r5-features-failed
+- repeat:
+ times: 4
+ commands:
+ - stopApp
+ - launchApp:
+ clearState: false
+ - extendedWaitUntil:
+ visible:
+ id: r5-features-next
+ timeout: 90000
+ - assertNotVisible:
+ id: r5-features-failed
+- stopApp
+- launchApp:
+ clearState: false
+- extendedWaitUntil:
+ visible:
+ id: r5-features-pass
+ timeout: 90000
+- assertNotVisible:
+ id: r5-features-failed
+- stopApp
diff --git a/.github/native/r5_features_core.js b/.github/native/r5_features_core.js
new file mode 100644
index 0000000000..d75d8ec490
--- /dev/null
+++ b/.github/native/r5_features_core.js
@@ -0,0 +1,401 @@
+// CI-only production-worker/native-storage witness. All transport, generation,
+// dispatch and database selection adapters below are explicit test boundaries.
+// This is not product UI, cryptography, backend or account-login acceptance.
+const PHASE = 'keeper-r5-worker-native-phase-v1';
+const SCENARIOS = Object.freeze([
+ 'production-setup-offline-retry-native-counts',
+ 'production-deletion-retained-native-references',
+ 'production-deletion-native-rollback',
+ 'production-worker-stale-session-rejection',
+ 'native-worker-process-relaunch-counts',
+]);
+const LIMITS = Object.freeze([
+ 'controlled-transport-no-backend-acceptance',
+ 'synthetic-wallet-generation-no-crypto-acceptance',
+ 'injected-dispatch-selection-no-login-acceptance',
+ 'no-product-ui-navigation-pin-or-biometric-acceptance',
+ 'probe-and-worker-timings-not-product-startup-ux',
+]);
+class FeatureFailure extends Error {
+ constructor(code) {
+ super(code);
+ this.code = code;
+ }
+}
+function check(value, code) {
+ if (!value) throw new FeatureFailure(code);
+}
+
+// Build invalid public sentinel records from the *actual current* Realm schema.
+// Required links are instantiated, arrays stay empty, optional fields omitted.
+// No key-generation path or valid seed is used by this probe.
+function recordBuilder(schema) {
+ const schemas = new Map(schema.map((item) => [item.name, item]));
+ function value(type, depth) {
+ if (depth > 15) throw new FeatureFailure('schema-depth');
+ if (typeof type === 'object') {
+ if (Object.hasOwn(type, 'default')) return type.default;
+ if (type.optional) return undefined;
+ if (type.type === 'list' || type.type === 'set') return [];
+ if (type.type === 'dictionary') return {};
+ return value(type.objectType || type.type, depth + 1);
+ }
+ if (type.endsWith('?')) return undefined;
+ if (type.endsWith('[]')) return [];
+ if (schemas.has(type)) return record(type, {}, depth + 1);
+ if (type === 'string') return '';
+ if (['int', 'float', 'double'].includes(type)) return 0;
+ if (type === 'bool') return false;
+ if (type === 'date') return new Date(0);
+ if (type === 'data') return new ArrayBuffer(0);
+ if (type === 'mixed') return null;
+ throw new FeatureFailure('unsupported-schema-property');
+ }
+ function record(name, overrides = {}, depth = 0) {
+ const item = schemas.get(name);
+ if (!item) throw new FeatureFailure('schema-missing');
+ const result = {};
+ for (const [key, type] of Object.entries(item.properties)) {
+ const field = value(type, depth + 1);
+ if (field !== undefined) result[key] = field;
+ }
+ return Object.assign(result, overrides);
+ }
+ return record;
+}
+
+async function runFeatures({
+ Realm,
+ schema,
+ storage,
+ createWorkers,
+ effects,
+ runSaga,
+ enums,
+ RealmSchema,
+ subscription,
+ DeviceInfo,
+ now,
+ startedAt,
+}) {
+ const make = recordBuilder(schema);
+ const directory = Realm.defaultPath.slice(0, Realm.defaultPath.lastIndexOf('/') + 1);
+ check(directory, 'native-directory-missing');
+ const config = (iteration, suffix) => ({
+ path: `${directory}keeper-r5-worker-${iteration}-${suffix}.realm`,
+ schema,
+ schemaVersion: 1,
+ encryptionKey: new Uint8Array(64).fill(suffix === 'a' ? 17 : 18),
+ });
+ let saved;
+ try {
+ saved = JSON.parse(storage.getString(PHASE) || '{"iteration":0,"measurements":[]}');
+ } catch {
+ throw new FeatureFailure('invalid-phase');
+ }
+ check(
+ Number.isInteger(saved.iteration) &&
+ saved.iteration >= 0 &&
+ saved.iteration <= 5 &&
+ Array.isArray(saved.measurements) &&
+ saved.measurements.length === saved.iteration,
+ 'invalid-phase'
+ );
+ // Every process verifies the previous process's committed wallet/key counts.
+ for (let index = 1; index <= saved.iteration; index += 1) {
+ for (const suffix of ['a', 'b']) {
+ const prior = await Realm.open(config(index, suffix));
+ try {
+ check(prior.objects('Wallet').length === (suffix === 'a' ? 1 : 0), 'relaunch-wallet-count');
+ check(prior.objects('Signer').length === (suffix === 'a' ? 2 : 0), 'relaunch-signer-count');
+ check(prior.objects('Vault').length === 0, 'relaunch-vault-count');
+ } finally {
+ prior.close();
+ }
+ }
+ }
+ if (saved.iteration === 5) {
+ for (let index = 1; index <= 5; index += 1) {
+ Realm.deleteFile(config(index, 'a'));
+ Realm.deleteFile(config(index, 'b'));
+ }
+ storage.deleteItem(PHASE);
+ return {
+ stage: 'pass',
+ measurements: saved.measurements,
+ scenarios: SCENARIOS.map((id) => ({ id, status: 'PASS' })),
+ };
+ }
+ const iteration = saved.iteration + 1;
+ let a;
+ let b;
+ try {
+ a = await Realm.open(config(iteration, 'a'));
+ b = await Realm.open(config(iteration, 'b'));
+ check(
+ a.objects('KeeperApp').length === 0 && b.objects('KeeperApp').length === 0,
+ 'fixture-not-fresh'
+ );
+ const appA = 'keeper-ci-r5-account-a';
+ const appB = 'keeper-ci-r5-account-b';
+ const appRecord = (id) =>
+ make('KeeperApp', {
+ id,
+ publicId: 'CI-NOT-A-PUBLIC-KEY',
+ primaryMnemonic: 'CI INVALID NOT A MNEMONIC',
+ primarySeed: 'CI INVALID NOT A SEED',
+ imageEncryptionKey: 'CI INVALID NOT A KEY',
+ networkType: 'TESTNET',
+ version: 'CI',
+ });
+ a.write(() => a.create('KeeperApp', appRecord(appA)));
+ b.write(() => b.create('KeeperApp', appRecord(appB)));
+ let active = a;
+ const state = {
+ settings: { bitcoinNetworkType: 'TESTNET', loginMethod: 'PIN' },
+ storage: { appId: appA, appCreated: false },
+ account: { allAccounts: [] },
+ };
+ const actions = [];
+ const action = (name) => (payload) => ({ type: name, payload });
+ const dispatch = (item) => {
+ actions.push(item);
+ if (item.type === 'setAppId') state.storage.appId = item.payload;
+ if (item.type === 'setAppCreated') state.storage.appCreated = item.payload;
+ if (item.type === 'addAccount') state.account.allAccounts = [{ appId: item.payload }];
+ return item;
+ };
+ const dbManager = {
+ getObjectByIndex: (name) => active.objects(name)[0],
+ getCollection: (name) => Array.from(active.objects(name)),
+ createObject: (name, object) => {
+ active.write(() => active.create(name, object, Realm.UpdateMode.All));
+ return true;
+ },
+ };
+ let online = false;
+ let allowKey = false;
+ let generationCount = 0;
+ let firstWalletAt;
+ const signer = (fingerprint) =>
+ make('Signer', {
+ id: `${fingerprint}0T`,
+ masterFingerprint: fingerprint,
+ type: 'SEED_WORDS',
+ networkType: 'TESTNET',
+ signerXpubs: {
+ P2WPKH: [{ xpub: `CI INVALID XPUB ${fingerprint}`, derivationPath: "m/84'/1'/0'" }],
+ },
+ });
+ const recovery = signer('C1C1C1C1');
+ const deps = {
+ ...effects,
+ RealmSchema,
+ ...enums,
+ ...subscription,
+ DeviceInfo,
+ dbManager,
+ realm: { getDatabase: () => active },
+ store: { getState: () => state, dispatch },
+ getJSONFromRealmObject: (item) => (item.toJSON ? item.toJSON() : item),
+ Relay: { createNewApp: async () => ({ created: online }) },
+ WalletUtilities: { getDerivationPath: () => "m/84'/1'/0'" },
+ setupRecoveryKeySigningKey: () => recovery,
+ addNewWalletsWorker: function* () {
+ generationCount += 1;
+ dbManager.createObject(
+ 'Wallet',
+ make('Wallet', {
+ id: 'keeper-ci-r5-mobile-wallet',
+ type: 'DEFAULT',
+ networkType: 'TESTNET',
+ entityKind: 'WALLET',
+ scriptType: 'P2WPKH',
+ derivationDetails: make('WalletDerivationDetails', {
+ instanceNum: 0,
+ xDerivationPath: "m/84'/1'/0'",
+ mnemonic: 'CI INVALID',
+ }),
+ specs: make('WalletSpecs', { xpub: 'CI INVALID XPUB' }),
+ })
+ );
+ firstWalletAt = now();
+ return true;
+ },
+ addSigningDeviceWorker: function* () {
+ if (allowKey) dbManager.createObject('Signer', recovery);
+ return allowKey;
+ },
+ LoginMethod: { BIOMETRIC: 'BIOMETRIC' },
+ beginBackupLocalOperation: (appId, _origin, session) => ({
+ appId,
+ session,
+ database: active,
+ }),
+ commitBackupLocalOperation: (operation, write) => {
+ if (
+ operation.database !== active ||
+ operation.appId !== state.storage.appId ||
+ operation.session !== workers.currentBackupAccountSession()
+ )
+ return { committed: false };
+ try {
+ active.write(() => write(active));
+ return { committed: true };
+ } catch {
+ return { committed: false };
+ }
+ },
+ // Deliberately no remote request and no Verified/backup-confirmed assertion.
+ queueCommittedBackupWorker: function* () {
+ return { updated: true, backupPending: true };
+ },
+ captureError: () => undefined,
+ uaiType: { SIGNING_DEVICES_HEALTH_CHECK: 'health' },
+ };
+ for (const name of [
+ 'setAppId',
+ 'addAccount',
+ 'updateDefaultWalletCreatedByAppId',
+ 'setAppCreated',
+ 'resetRealyWalletState',
+ 'loadConciergeUser',
+ 'loadConciergeTickets',
+ 'setBiometricEnabledAppId',
+ 'setAppCreationError',
+ 'uaiChecks',
+ 'showDeletingKeyModal',
+ 'hideDeletingKeyModal',
+ 'showKeyDeletedSuccessModal',
+ 'relaySignersUpdateFail',
+ ])
+ deps[name] = action(name);
+ const workers = createWorkers(deps);
+ workers.observeBackupAccount(appA);
+ const run = (name, args) =>
+ runSaga({ getState: () => state, dispatch }, workers[name], args).toPromise();
+ const setup = () =>
+ run('setupKeeperAppWorker', { payload: { appName: 'CI disposable', fcmToken: '' } });
+ const readyAt = now();
+ await setup();
+ check(
+ a.objects('Wallet').length === 0 && state.storage.appCreated === false,
+ 'offline-setup-ready'
+ );
+ online = true;
+ const setupAt = now();
+ await setup();
+ check(
+ a.objects('Wallet').length === 1 && state.storage.appCreated === false,
+ 'key-failure-ready'
+ );
+ allowKey = true;
+ await setup();
+ check(
+ a.objects('Wallet').length === 1 && generationCount === 1 && state.storage.appCreated,
+ 'retry-wallet-duplicate'
+ );
+ check(
+ a.objects('Signer').length === 1 && state.account.allAccounts.length === 1,
+ 'retry-account-duplicate'
+ );
+ check(Number.isFinite(firstWalletAt) && firstWalletAt >= setupAt, 'first-wallet-clock');
+
+ const target = signer('D1D1D1D1');
+ const unrelated = signer('E1E1E1E1');
+ dbManager.createObject('Signer', target);
+ dbManager.createObject('Signer', unrelated);
+ const request = (signers) => ({
+ payload: { signers },
+ originAppId: appA,
+ originBackupAccountSession: workers.currentBackupAccountSession(),
+ });
+ for (const kind of ['active', 'hidden', 'canary', 'archived']) {
+ dbManager.createObject(
+ 'Vault',
+ make('Vault', {
+ id: 'keeper-ci-r5-reference',
+ entityKind: 'VAULT',
+ type: kind === 'canary' ? 'CANARY' : 'DEFAULT',
+ networkType: 'TESTNET',
+ archived: kind === 'archived',
+ presentationData: {
+ name: 'CI concealed sentinel',
+ description: '',
+ visibility: kind === 'hidden' ? 'HIDDEN' : 'DEFAULT',
+ },
+ signers: [
+ make('VaultSigner', {
+ masterFingerprint: target.masterFingerprint,
+ xpub: 'CI INVALID VAULT XPUB',
+ xfp: target.masterFingerprint,
+ derivationPath: "m/48'/1'/0'/2'",
+ }),
+ ],
+ })
+ );
+ check(
+ (await run('deleteSigningDeviceWorker', request([target]))) === false,
+ 'retained-reference-accepted'
+ );
+ check(
+ a.objectForPrimaryKey('Signer', target.id) && a.objectForPrimaryKey('Signer', unrelated.id),
+ 'retained-reference-deleted'
+ );
+ active.write(() => active.delete(active.objects('Vault')));
+ }
+ // Missing later target must roll back an earlier native deletion atomically.
+ const missing = signer('F1F1F1F1');
+ check(
+ (await run('deleteSigningDeviceWorker', request([target, missing]))) === false,
+ 'partial-delete-accepted'
+ );
+ check(a.objectForPrimaryKey('Signer', target.id), 'partial-delete-not-rolled-back');
+ const stale = request([target]);
+ active = b;
+ state.storage.appId = appB;
+ workers.observeBackupAccount(appB);
+ active = a;
+ state.storage.appId = appA;
+ workers.observeBackupAccount(appA);
+ check((await run('deleteSigningDeviceWorker', stale)) === false, 'stale-session-accepted');
+ check(a.objectForPrimaryKey('Signer', target.id), 'stale-session-mutated');
+ check(
+ (await run('deleteSigningDeviceWorker', request([target]))) === true,
+ 'unreferenced-delete-rejected'
+ );
+ check(
+ !a.objectForPrimaryKey('Signer', target.id) && a.objectForPrimaryKey('Signer', unrelated.id),
+ 'targeted-delete-wrong-record'
+ );
+ check(
+ b.objects('Wallet').length === 0 && b.objects('Signer').length === 0,
+ 'other-native-account-mutated'
+ );
+ const measurement = {
+ iteration,
+ probe_ready_ms: readyAt - startedAt,
+ setup_first_wallet_ms: firstWalletAt - setupAt,
+ };
+ check(
+ Object.values(measurement).every(Number.isFinite) &&
+ measurement.probe_ready_ms >= 0 &&
+ measurement.setup_first_wallet_ms >= 0,
+ 'invalid-clock-measurement'
+ );
+ const measurements = [...saved.measurements, measurement];
+ storage.setItem(PHASE, JSON.stringify({ iteration, measurements }));
+ return {
+ stage: 'next',
+ measurements,
+ scenarios: SCENARIOS.map((id) => ({
+ id,
+ status: id === 'native-worker-process-relaunch-counts' ? 'NOT RUN' : 'PASS',
+ })),
+ };
+ } finally {
+ if (a && !a.isClosed) a.close();
+ if (b && !b.isClosed) b.close();
+ }
+}
+module.exports = { runFeatures, recordBuilder, FeatureFailure, PHASE, SCENARIOS, LIMITS };
diff --git a/.github/native/r5_metro.cjs b/.github/native/r5_metro.cjs
new file mode 100644
index 0000000000..f77b6328f8
--- /dev/null
+++ b/.github/native/r5_metro.cjs
@@ -0,0 +1,21 @@
+// Only the disposable native-worker job selects this alternate entrypoint.
+const path = require('node:path');
+const base = require('../../metro.config');
+const enhance = base.server?.enhanceMiddleware;
+module.exports = {
+ ...base,
+ projectRoot: path.resolve(__dirname, '../..'),
+ server: {
+ ...base.server,
+ enhanceMiddleware(middleware, server) {
+ const inner = enhance ? enhance(middleware, server) : middleware;
+ return (req, res, next) => {
+ req.url = req.url.replace(
+ /^\/index\.(bundle|map)(?=\?|$)/,
+ '/.github/native/r5_features.$1'
+ );
+ return inner(req, res, next);
+ };
+ },
+ },
+};
diff --git a/.github/native/r5_prepare.cjs b/.github/native/r5_prepare.cjs
new file mode 100644
index 0000000000..dba8198209
--- /dev/null
+++ b/.github/native/r5_prepare.cjs
@@ -0,0 +1,127 @@
+// Build-time extraction of unchanged production workers for a CI-only native probe.
+// No eval, source rewriting or production entrypoint changes occur in the app.
+const fs = require('node:fs');
+const path = require('node:path');
+const crypto = require('node:crypto');
+const ts = require('typescript');
+const ROOT = path.resolve(__dirname, '../..');
+const SELECTION = Object.freeze({
+ 'src/utils/utilities.ts': ['getAccountFromSigner', 'getKeyUID'],
+ 'src/store/sagas/storage.ts': ['setupKeeperAppWorker'],
+ 'src/store/sagas/wallets.ts': [
+ 'currentWalletAccountId',
+ 'assertWalletAccount',
+ 'deleteSigningDeviceWorker',
+ ],
+ 'src/store/sagas/bhr.ts': ['currentBackupAppId', 'deleteAppImageEntityWorker'],
+ 'src/services/backup/transport.ts': [
+ 'observeBackupAccount',
+ 'currentBackupAccountSession',
+ 'clearVerifiedRemoteRevision',
+ ],
+});
+const DEPENDENCIES = [
+ 'call',
+ 'put',
+ 'select',
+ 'dbManager',
+ 'realm',
+ 'store',
+ 'RealmSchema',
+ 'SignerType',
+ 'NetworkType',
+ 'XpubTypes',
+ 'WalletType',
+ 'DerivationPurpose',
+ 'getJSONFromRealmObject',
+ 'beginBackupLocalOperation',
+ 'commitBackupLocalOperation',
+ 'queueCommittedBackupWorker',
+ 'captureError',
+ 'uaiType',
+ 'uaiChecks',
+ 'showDeletingKeyModal',
+ 'hideDeletingKeyModal',
+ 'showKeyDeletedSuccessModal',
+ 'relaySignersUpdateFail',
+ 'Relay',
+ 'WalletUtilities',
+ 'setupRecoveryKeySigningKey',
+ 'addNewWalletsWorker',
+ 'addSigningDeviceWorker',
+ 'SubscriptionTier',
+ 'AppSubscriptionLevel',
+ 'DeviceInfo',
+ 'setAppId',
+ 'addAccount',
+ 'updateDefaultWalletCreatedByAppId',
+ 'setAppCreated',
+ 'resetRealyWalletState',
+ 'loadConciergeUser',
+ 'loadConciergeTickets',
+ 'LoginMethod',
+ 'setBiometricEnabledAppId',
+ 'setAppCreationError',
+];
+
+function extract(file, names) {
+ const source = fs.readFileSync(file, 'utf8');
+ const parsed = ts.createSourceFile(file, source, ts.ScriptTarget.Latest, true);
+ const found = new Map();
+ for (const statement of parsed.statements) {
+ if (
+ ts.isFunctionDeclaration(statement) &&
+ statement.name &&
+ names.includes(statement.name.text)
+ ) {
+ if (found.has(statement.name.text)) throw new Error('Duplicate selected function');
+ found.set(statement.name.text, statement.getText(parsed).replace(/^export\s+/, ''));
+ } else if (ts.isVariableStatement(statement)) {
+ for (const declaration of statement.declarationList.declarations) {
+ if (ts.isIdentifier(declaration.name) && names.includes(declaration.name.text)) {
+ if (found.has(declaration.name.text)) throw new Error('Duplicate selected variable');
+ found.set(declaration.name.text, `const ${declaration.getText(parsed)};`);
+ }
+ }
+ }
+ }
+ if (found.size !== names.length) throw new Error('Production probe selection changed');
+ return {
+ source: names.map((name) => found.get(name)).join('\n'),
+ sha256: crypto.createHash('sha256').update(source).digest('hex'),
+ };
+}
+
+function prepare(root = ROOT) {
+ const sources = [];
+ const provenance = [];
+ for (const [relative, names] of Object.entries(SELECTION)) {
+ const extracted = extract(path.join(root, relative), names);
+ sources.push(extracted.source);
+ provenance.push({ path: relative, sha256: extracted.sha256, names });
+ }
+ const input = `function createWorkers(deps) {
+ const { ${DEPENDENCIES.join(',')} } = deps;
+ let activeAccount; let accountSession = 0; let lastDiagnostic;
+ const verifiedRemoteRevisions = new Map(); const baselineEpochs = new Map();
+ ${sources.join('\n')}
+ return { setupKeeperAppWorker, deleteSigningDeviceWorker, deleteAppImageEntityWorker,
+ getKeyUID, observeBackupAccount, currentBackupAccountSession };
+ }
+ module.exports = { createWorkers, provenance: ${JSON.stringify(provenance)} };`;
+ const result = ts.transpileModule(input, {
+ reportDiagnostics: true,
+ compilerOptions: { target: ts.ScriptTarget.ES2020, module: ts.ModuleKind.CommonJS },
+ });
+ if (result.diagnostics.some((d) => d.category === ts.DiagnosticCategory.Error))
+ throw new Error('Probe extraction syntax failed');
+ const directory = path.join(root, '.github/native/.generated');
+ fs.mkdirSync(directory, { recursive: true });
+ fs.writeFileSync(path.join(directory, 'r5_workers.js'), result.outputText);
+ return provenance;
+}
+if (require.main === module) {
+ prepare();
+ process.stdout.write('R5 production worker extraction prepared\n');
+}
+module.exports = { prepare, extract, SELECTION, DEPENDENCIES };
diff --git a/.github/native/release_acceptance.cjs b/.github/native/release_acceptance.cjs
new file mode 100644
index 0000000000..da53bd7e14
--- /dev/null
+++ b/.github/native/release_acceptance.cjs
@@ -0,0 +1,32 @@
+// Common release obligations. Extend with real executable scenarios, never status-only waivers.
+// Native module checks are deliberately distinct from app-account or feature acceptance.
+const REQUIRED = Object.freeze([
+ 'native-build-and-startup',
+ 'native-realm-mmkv-process-persistence',
+ 'key-deletion-live-reference-and-privacy',
+ 'setup-offline-retry-relaunch-no-duplicates',
+ 'app-account-session-isolation',
+ 'normal-page-runtime-and-recovery-regression',
+ 'cold-start-and-first-wallet-performance',
+]);
+function acceptance({ trusted, ios, android }) {
+ const executed = trusted === true && ios === 'success' && android === 'success';
+ const cases = REQUIRED.map((id, index) => ({
+ id,
+ status: index < 2 ? (executed ? 'PASS' : 'NOT VERIFIED') : 'NOT IMPLEMENTED',
+ scope: index === 1 ? 'CI entrypoint; actual native storage, not application account isolation' :
+ index > 1 ? 'Requires reviewed app scenarios on the exact combined candidate' :
+ 'Unsigned simulator / development debug-key emulator; narrow passcode smoke',
+ }));
+ return { release_ready: false, phase_a: 'BLOCKED', cases,
+ signing: 'NOT IMPLEMENTED / NOT VERIFIED (separate Phase B)',
+ physical: 'NOT RUN (authorized tester and exact distributed artifact required)' };
+}
+function markdown(result) {
+ return '# Keeper Phase A release acceptance: BLOCKED\n\n' +
+ 'This check cannot approve a release. Startup and native module probes do not cover the app matrix.\n\n' +
+ '| Required scenario | Result | Scope |\n| --- | --- | --- |\n' +
+ result.cases.map(c => `| ${c.id} | ${c.status} | ${c.scope} |`).join('\n') +
+ `\n\nSigning/distribution: ${result.signing}.\n\nPhysical: ${result.physical}.\n`;
+}
+module.exports = { REQUIRED, acceptance, markdown };
diff --git a/.github/native/release_evidence.cjs b/.github/native/release_evidence.cjs
new file mode 100644
index 0000000000..542f6dff95
--- /dev/null
+++ b/.github/native/release_evidence.cjs
@@ -0,0 +1,48 @@
+// Read-only Actions provenance. Writable PR assertions/artifacts supply no credit.
+async function evidence(github, context, { ios, android, attempt }) {
+ const pr = context.payload.pull_request;
+ const { owner, repo } = context.repo;
+ const repository = owner + '/' + repo;
+ if (ios !== 'success' || android !== 'success' || context.eventName !== 'pull_request' ||
+ !pr || pr.number === 7045 || pr.base.ref !== 'sprint' ||
+ pr.head.repo?.full_name !== repository || pr.base.repo?.full_name !== repository ||
+ !pr.head.repo.id || !pr.base.repo.id || !/^[a-f0-9]{40}$/.test(pr.head.sha) ||
+ !Number.isSafeInteger(attempt) || attempt < 1) return false;
+ try {
+ const runs = await github.paginate(github.rest.actions.listWorkflowRuns, {
+ owner, repo, workflow_id: 'keeper-release-acceptance.yml',
+ head_sha: pr.head.sha, event: 'pull_request', per_page: 100,
+ });
+ const run = runs.sort((a, b) => b.id - a.id)[0];
+ if (!run || run.id !== context.runId || run.run_attempt !== attempt ||
+ run.path !== '.github/workflows/keeper-release-acceptance.yml' ||
+ run.event !== 'pull_request' || run.head_sha !== pr.head.sha ||
+ run.head_branch !== pr.head.ref || run.head_repository?.full_name !== repository ||
+ run.head_repository?.id !== pr.head.repo.id ||
+ (!['in_progress', 'completed'].includes(run.status) ||
+ (run.status === 'completed' && !['success', 'failure'].includes(run.conclusion)))) return false;
+ const linked = run.pull_requests?.find(item => item.number === pr.number);
+ if (!linked || linked.head?.sha !== pr.head.sha || linked.head?.ref !== pr.head.ref ||
+ linked.head?.repo?.id !== pr.head.repo.id || linked.base?.ref !== 'sprint' ||
+ linked.base?.sha !== pr.base.sha || linked.base?.repo?.id !== pr.base.repo.id) return false;
+ const jobs = await github.paginate(github.rest.actions.listJobsForWorkflowRunAttempt, {
+ owner, repo, run_id: run.id, attempt_number: attempt, per_page: 100,
+ });
+ return ['IOS', 'ANDROID'].every(platform => {
+ const matches = jobs.filter(job => job.name ===
+ `${platform.toLowerCase()} / Native ${platform} build and probes`);
+ if (matches.length !== 1) return false;
+ const job = matches[0];
+ if (job.head_sha !== pr.head.sha || job.run_id !== run.id || job.run_attempt !== attempt ||
+ job.status !== 'completed' || job.conclusion !== 'success') return false;
+ const steps = ['Build development app', ...(platform === 'IOS'
+ ? ['Run disposable startup smoke', 'Run disposable native persistence probe']
+ : ['Run Android startup and native persistence probes'])];
+ return steps.every(name => {
+ const found = job.steps?.filter(step => step.name === name) ?? [];
+ return found.length === 1 && found[0].status === 'completed' && found[0].conclusion === 'success';
+ });
+ });
+ } catch { return false; }
+}
+module.exports = { evidence };
diff --git a/.github/native/release_metro.cjs b/.github/native/release_metro.cjs
new file mode 100644
index 0000000000..df8c39ad61
--- /dev/null
+++ b/.github/native/release_metro.cjs
@@ -0,0 +1,19 @@
+// CI-only entrypoint for native module persistence. No product source is rewritten.
+const path = require('node:path');
+const base = require('../../metro.config');
+const enhance = base.server?.enhanceMiddleware;
+module.exports = {
+ ...base,
+ projectRoot: path.resolve(__dirname, '../..'),
+ server: {
+ ...base.server,
+ enhanceMiddleware(middleware, server) {
+ const inner = enhance ? enhance(middleware, server) : middleware;
+ return (req, res, next) => {
+ req.url = req.url.replace(/^\/index\.(bundle|map)(?=\?|$)/,
+ '/.github/native/release_probe.$1');
+ return inner(req, res, next);
+ };
+ },
+ },
+};
diff --git a/.github/native/release_preflight.cjs b/.github/native/release_preflight.cjs
new file mode 100644
index 0000000000..b95377b4ea
--- /dev/null
+++ b/.github/native/release_preflight.cjs
@@ -0,0 +1,58 @@
+// Unprivileged PR bootstrap check, not a release authorization or commit-status writer.
+const WORKFLOWS = [
+ '.github/workflows/keeper-hosted-native.yml',
+ '.github/workflows/keeper-release-acceptance.yml',
+ '.github/workflows/keeper-native-platform.yml',
+];
+const NATIVE_FILES = [
+ 'hosted_native.py', 'nodeify.cjs', 'startup.yaml', 'release_preflight.cjs',
+ 'release_acceptance.cjs', 'release_evidence.cjs', 'release_metro.cjs', 'release_probe.js',
+ 'release_probe_core.js', 'release_probe.yaml',
+].map(name => '.github/native/' + name);
+function fingerprint(tree) {
+ if (tree.truncated) throw new Error('Truncated CI tree');
+ const entries = tree.tree.filter(e => WORKFLOWS.includes(e.path) || e.path.startsWith('.github/native/'));
+ if (![...WORKFLOWS, ...NATIVE_FILES].every(p => entries.some(e => e.path === p && e.type === 'blob' && ['100644', '100755'].includes(e.mode)))) {
+ throw new Error('Reviewed Phase A / #7060 infrastructure is not installed');
+ }
+ return JSON.stringify(entries.map(e => [e.path, e.mode, e.type, e.sha])
+ .sort((a, b) => a[0].localeCompare(b[0])));
+}
+async function preflight(github, context) {
+ const original = context.payload.pull_request;
+ if (context.eventName !== 'pull_request' || !original || original.number === 7045) {
+ return { trusted: false, reason: 'Outside Phase A scope; frozen R4 excluded' };
+ }
+ const { owner, repo } = context.repo;
+ const { data: pr } = await github.rest.pulls.get({ owner, repo, pull_number: original.number });
+ const repository = owner + '/' + repo;
+ if (pr.base.ref !== 'sprint' || pr.head.repo?.full_name !== repository ||
+ pr.base.repo?.full_name !== repository || pr.head.sha !== original.head.sha ||
+ pr.head.ref !== original.head.ref || !/^[a-f0-9]{40}$/.test(pr.head.sha) ||
+ !pr.head.repo.id || pr.head.repo.id !== original.head.repo?.id ||
+ !pr.base.repo.id || pr.base.repo.id !== original.base.repo?.id ||
+ original.base.ref !== 'sprint') {
+ return { trusted: false, reason: 'Exact current same-repository PR provenance is unavailable' };
+ }
+ try {
+ const snapshots = await Promise.all([pr.head.sha, pr.base.sha, original.base.sha].map(async ref => {
+ const { data } = await github.rest.git.getTree({ owner, repo, tree_sha: ref, recursive: '1' });
+ return fingerprint(data);
+ }));
+ if (!snapshots.every(value => value === snapshots[0])) {
+ return { trusted: false, reason: 'CI differs from current or run base; review/install before native acceptance' };
+ }
+ // Re-read after API work so a concurrent push cannot supply current-head credit.
+ const { data: latest } = await github.rest.pulls.get({ owner, repo, pull_number: original.number });
+ if (latest.head.sha !== pr.head.sha || latest.base.sha !== pr.base.sha ||
+ latest.base.ref !== pr.base.ref || latest.head.ref !== pr.head.ref ||
+ latest.head.repo?.id !== pr.head.repo.id || latest.base.repo?.id !== pr.base.repo.id ||
+ latest.head.repo?.full_name !== repository || latest.base.repo?.full_name !== repository) {
+ return { trusted: false, reason: 'PR source/base changed during provenance verification' };
+ }
+ return { trusted: true, reason: 'Exact-head CI matches both protected base snapshots' };
+ } catch {
+ return { trusted: false, reason: 'Reviewed Phase A / #7060 infrastructure unavailable; no native credit' };
+ }
+}
+module.exports = { WORKFLOWS, NATIVE_FILES, fingerprint, preflight };
diff --git a/.github/native/release_probe.js b/.github/native/release_probe.js
new file mode 100644
index 0000000000..827687c28d
--- /dev/null
+++ b/.github/native/release_probe.js
@@ -0,0 +1,38 @@
+// Alternative Metro entrypoint, used only by the disposable release acceptance job.
+// The production app entrypoint and bundle remain unchanged on disk.
+import 'react-native-get-random-values';
+import React, { useEffect, useState } from 'react';
+import { AppRegistry, SafeAreaView, Text } from 'react-native';
+import Realm from 'realm';
+import schema from '../../src/storage/realm/schema';
+import * as storage from '../../src/storage';
+import { name as appName } from '../../app.json';
+import { runProbe, ProbeFailure } from './release_probe_core';
+
+// No app services, Sentry, account creation, keychain, migrations or network imports.
+let attempt;
+function ReleaseProbe() {
+ const [result, setResult] = useState({ stage: 'running', code: '' });
+ useEffect(() => {
+ let active = true;
+ // A remount must not advance the persistence phase in the same JS process.
+ if (!attempt) {
+ attempt = __DEV__
+ ? runProbe({ Realm, schema, storage }).then(
+ (stage) => ({ stage, code: '' }),
+ (error) => ({ stage: 'failed', code: error instanceof ProbeFailure ? error.code : 'native-exception' })
+ )
+ : Promise.resolve({ stage: 'failed', code: 'development-only' });
+ }
+ attempt.then((value) => { if (active) setResult(value); });
+ return () => { active = false; };
+ }, []);
+ return (
+
+ Keeper native probe {result.stage}
+ {result.code}
+
+ );
+}
+
+AppRegistry.registerComponent(appName, () => ReleaseProbe);
diff --git a/.github/native/release_probe.yaml b/.github/native/release_probe.yaml
new file mode 100644
index 0000000000..bc9fad6f5a
--- /dev/null
+++ b/.github/native/release_probe.yaml
@@ -0,0 +1,32 @@
+appId: ${APP_ID}
+name: Disposable native module persistence across process relaunch
+---
+- launchApp:
+ clearState: true
+ permissions:
+ all: deny
+- extendedWaitUntil:
+ visible:
+ id: native-probe-seeded
+ timeout: 60000
+- assertNotVisible:
+ id: native-probe-failed
+- stopApp
+- launchApp:
+ clearState: false
+- extendedWaitUntil:
+ visible:
+ id: native-probe-mutated
+ timeout: 60000
+- assertNotVisible:
+ id: native-probe-failed
+- stopApp
+- launchApp:
+ clearState: false
+- extendedWaitUntil:
+ visible:
+ id: native-probe-pass
+ timeout: 60000
+- assertNotVisible:
+ id: native-probe-failed
+- stopApp
diff --git a/.github/native/release_probe_core.js b/.github/native/release_probe_core.js
new file mode 100644
index 0000000000..c9903e122e
--- /dev/null
+++ b/.github/native/release_probe_core.js
@@ -0,0 +1,144 @@
+/* CI-only native persistence acceptance. No accounts, network or fundable keys. */
+const PHASE_KEY = 'keeper-ci-release-probe-v1-phase';
+const MARKER_KEY = 'keeper-ci-release-probe-v1-marker';
+const PRIMARY = 'keeper-ci-synthetic-wallet';
+const OTHER = 'keeper-ci-synthetic-unrelated-wallet';
+const ROLLBACK = 'keeper-ci-synthetic-rolled-back-wallet';
+const SCHEMA_VERSION = 1; // Fresh current schema only; never an upgrade/migration claim.
+
+class ProbeFailure extends Error {
+ constructor(code) {
+ super(code);
+ this.code = code;
+ }
+}
+
+function check(condition, code) {
+ if (!condition) throw new ProbeFailure(code);
+}
+
+function wallet(id, name) {
+ return {
+ id,
+ entityKind: 'WALLET',
+ type: 'DEFAULT',
+ networkType: 'TESTNET',
+ scriptType: 'P2WPKH',
+ // Invalid public sentinel, deliberately unusable as an account/key fixture.
+ specs: {
+ xpub: 'CI-SYNTHETIC-NOT-A-KEY',
+ nextFreeAddressIndex: 0,
+ nextFreeChangeAddressIndex: 0,
+ totalExternalAddresses: 0,
+ confirmedUTXOs: [],
+ unconfirmedUTXOs: [],
+ balances: { confirmed: 0, unconfirmed: 0 },
+ transactions: [],
+ hasNewUpdates: false,
+ lastSynched: 0,
+ },
+ presentationData: { name, description: 'Disposable CI fixture', visibility: 'DEFAULT' },
+ };
+}
+
+// Realm and storage are the actual native modules in release_probe.js.
+// Injection exists solely to test failure/phase orchestration on non-native hosts.
+async function runProbe({ Realm, schema, storage }) {
+ const phase = storage.getString(PHASE_KEY);
+ check(phase === undefined || phase === 'seeded' || phase === 'mutated', 'invalid-phase');
+ const directory = Realm.defaultPath.slice(0, Realm.defaultPath.lastIndexOf('/') + 1);
+ check(directory.length > 0, 'missing-native-directory');
+ // Published constants encrypt synthetic disposable data, never product secrets.
+ const config = (suffix, keyByte = 7) => ({
+ path: `${directory}keeper-ci-release-probe-v1-${suffix}.realm`,
+ schema,
+ schemaVersion: SCHEMA_VERSION,
+ encryptionKey: new Uint8Array(64).fill(keyByte),
+ });
+ const aConfig = config('a');
+ const bConfig = config('b', 8);
+ let a;
+ let b;
+ try {
+ a = await Realm.open(aConfig);
+ b = await Realm.open(bConfig);
+ const get = (realm, id) => realm.objectForPrimaryKey('Wallet', id);
+ if (phase === undefined) {
+ check(a.objects('Wallet').length === 0 && b.objects('Wallet').length === 0, 'fixture-not-fresh');
+ a.write(() => {
+ a.create('Wallet', wallet(PRIMARY, 'CI primary'));
+ a.create('Wallet', wallet(OTHER, 'CI unrelated'));
+ });
+ b.write(() => b.create('Wallet', wallet(PRIMARY, 'CI separate database')));
+ storage.setItem(MARKER_KEY, 'synthetic-marker-v1');
+ storage.setItem(PHASE_KEY, 'seeded');
+ return 'seeded';
+ }
+
+ check(storage.getString(MARKER_KEY) === 'synthetic-marker-v1', 'mmkv-marker-not-persisted');
+ check(get(a, OTHER)?.presentationData.name === 'CI unrelated', 'unrelated-wallet-not-persisted');
+ const otherSpecs = get(a, OTHER).specs;
+ check(otherSpecs.xpub === 'CI-SYNTHETIC-NOT-A-KEY'
+ && otherSpecs.balances.confirmed === 0 && otherSpecs.balances.unconfirmed === 0
+ && otherSpecs.confirmedUTXOs.length === 0 && otherSpecs.transactions.length === 0,
+ 'embedded-wallet-state-not-persisted');
+ check(get(b, PRIMARY)?.presentationData.name === 'CI separate database', 'separate-file-not-persisted');
+ check(a.objects('Wallet').length === (phase === 'seeded' ? 2 : 1), 'unexpected-primary-record-count');
+ check(b.objects('Wallet').length === 1, 'unexpected-separate-record-count');
+
+ if (phase === 'seeded') {
+ check(get(a, PRIMARY)?.presentationData.name === 'CI primary', 'primary-wallet-not-persisted');
+ const aborted = new Error('intentional-synthetic-transaction-abort');
+ let rolledBack = false;
+ try {
+ a.write(() => {
+ a.create('Wallet', wallet(ROLLBACK, 'CI rollback'));
+ throw aborted;
+ });
+ } catch (error) {
+ if (error !== aborted) throw error;
+ rolledBack = true;
+ }
+ check(rolledBack && !get(a, ROLLBACK), 'transaction-rollback-failed');
+
+ // Close the correct-key handle first so rejection checks persisted file encryption.
+ a.close();
+ a = undefined;
+ let rejected = false;
+ let wrongKeyRealm;
+ try {
+ wrongKeyRealm = await Realm.open(config('a', 9));
+ } catch {
+ rejected = true;
+ } finally {
+ if (wrongKeyRealm) wrongKeyRealm.close();
+ }
+ check(rejected, 'wrong-encryption-key-accepted');
+ a = await Realm.open(aConfig);
+ check(get(a, PRIMARY)?.presentationData.name === 'CI primary', 'correct-key-reopen-failed');
+ // Deliberately only Realm deletion semantics; no claim about product key deletion.
+ a.write(() => a.delete(get(a, PRIMARY)));
+ check(!get(a, PRIMARY) && get(a, OTHER), 'targeted-wallet-delete-failed');
+ storage.setItem(PHASE_KEY, 'mutated');
+ return 'mutated';
+ }
+
+ check(!get(a, PRIMARY) && !get(a, ROLLBACK), 'delete-or-rollback-not-persisted');
+ a.close();
+ b.close();
+ a = undefined;
+ b = undefined;
+ Realm.deleteFile(aConfig);
+ Realm.deleteFile(bConfig);
+ storage.deleteItem(MARKER_KEY);
+ storage.deleteItem(PHASE_KEY);
+ check(storage.getString(MARKER_KEY) === undefined && storage.getString(PHASE_KEY) === undefined,
+ 'fixture-cleanup-failed');
+ return 'pass';
+ } finally {
+ if (a) a.close();
+ if (b) b.close();
+ }
+}
+
+module.exports = { runProbe, ProbeFailure, PHASE_KEY, MARKER_KEY, PRIMARY, OTHER, ROLLBACK };
diff --git a/.github/native/simulator_readiness.py b/.github/native/simulator_readiness.py
new file mode 100644
index 0000000000..bc75c9b95f
--- /dev/null
+++ b/.github/native/simulator_readiness.py
@@ -0,0 +1,101 @@
+"""Bounded read-only readiness for the simulator app-service query surface.
+
+A completed simulator boot does not establish that listapps can respond. This
+gate requires its successful exit before the caller starts installation or the
+driver. It retries only that read-only query; no output, app/driver operation,
+frontend launch or service configuration is retained or changed here.
+"""
+
+import math
+import re
+import subprocess
+import time
+
+
+MAX_WINDOW_SECONDS = 120
+QUERY_SECONDS = 5
+POLL_SECONDS = 1
+
+
+def _error_type(error):
+ name = type(error).__name__
+ return name if name in {'OSError', 'FileNotFoundError', 'PermissionError'} else 'OTHER_ERROR'
+
+
+def _query(device, timeout):
+ started = time.monotonic()
+ attempt = {}
+ try:
+ result = subprocess.run(['xcrun', 'simctl', 'listapps', device],
+ stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
+ timeout=timeout, check=False)
+ code = result.returncode
+ if not isinstance(code, int) or isinstance(code, bool):
+ attempt.update(state='ERROR', error_type='INVALID_EXIT_STATUS')
+ else:
+ attempt.update(state='SUCCESS' if code == 0 else 'FAIL', exit_code=code)
+ except subprocess.TimeoutExpired:
+ # TimeoutExpired can embed arbitrary subprocess output or argv. Export
+ # neither; run() terminates and reaps its own timed-out query process.
+ attempt['state'] = 'TIMEOUT'
+ except Exception as error:
+ attempt.update(state='ERROR', error_type=_error_type(error))
+ attempt['duration_seconds'] = round(time.monotonic() - started, 3)
+ return attempt
+
+
+def wait_for_app_services(context, device, timeout=MAX_WINDOW_SECONDS):
+ """Require one successful listapps response within the bounded deadline.
+
+ context supplies read()/save() from the active harness instance. The caller
+ invokes this between commands, so metadata writes cannot race an app build,
+ install or driver. A missing receipt also fails closed.
+ """
+ if (not isinstance(device, str)
+ or not re.fullmatch(r'[A-Fa-f0-9]{8}(?:-[A-Fa-f0-9]{4}){3}-[A-Fa-f0-9]{12}', device)):
+ raise ValueError('Expected an owned simulator UUID.')
+ if (not isinstance(timeout, (int, float)) or isinstance(timeout, bool)
+ or not math.isfinite(timeout) or timeout <= 0 or timeout > MAX_WINDOW_SECONDS):
+ raise ValueError('Expected a positive readiness window of at most 120 seconds.')
+ try:
+ initial = context.read()
+ except Exception:
+ raise RuntimeError('Simulator app-service readiness evidence could not be read.') from None
+ record = {
+ 'scope': 'Read-only simulator app-service readiness; no app, driver or UI credit.',
+ 'criterion': 'SIMCTL_LISTAPPS_EXIT_ZERO', 'result': 'FAIL',
+ 'after_command_index': len(initial.get('commands', [])),
+ 'timeout_seconds': timeout, 'query_timeout_seconds': QUERY_SECONDS, 'attempts': [],
+ }
+ started = time.monotonic()
+ deadline = started + timeout
+ while True:
+ remaining = deadline - time.monotonic()
+ if remaining <= 0:
+ break
+ attempt = _query(device, min(QUERY_SECONDS, remaining))
+ record['attempts'].append(attempt)
+ if attempt['state'] == 'SUCCESS':
+ # Scheduling delays must not turn a response first observed after
+ # the bounded window into a timely readiness receipt.
+ if time.monotonic() <= deadline:
+ record['result'] = 'PASS'
+ else:
+ attempt['observed_after_deadline'] = True
+ break
+ if attempt['state'] == 'ERROR':
+ break
+ remaining = deadline - time.monotonic()
+ if remaining <= 0:
+ break
+ time.sleep(min(POLL_SECONDS, remaining))
+ record['duration_seconds'] = round(time.monotonic() - started, 3)
+ try:
+ data = context.read()
+ data.setdefault('simulator_app_service_readiness', []).append(record)
+ context.save(data)
+ except Exception:
+ raise RuntimeError('Simulator app-service readiness evidence could not be saved.') from None
+ if record['result'] != 'PASS':
+ raise RuntimeError('Simulator app services did not respond successfully within the readiness window.')
+ return record
diff --git a/.github/native/startup.yaml b/.github/native/startup.yaml
new file mode 100644
index 0000000000..1dc9396374
--- /dev/null
+++ b/.github/native/startup.yaml
@@ -0,0 +1,22 @@
+# Intentionally stop before persisting a PIN or generating any recovery material.
+appId: ${APP_ID}
+name: Disposable startup and passcode input
+---
+- launchApp:
+ clearState: true
+ permissions:
+ all: deny
+- extendedWaitUntil:
+ visible: Create a passcode
+ timeout: 180000
+- assertNotVisible: Confirm your passcode
+- tapOn:
+ id: key_1
+- tapOn:
+ id: key_2
+- tapOn:
+ id: key_3
+- tapOn:
+ id: key_4
+- assertVisible: Confirm your passcode
+- stopApp
diff --git a/.github/native/startup_diagnosis.py b/.github/native/startup_diagnosis.py
new file mode 100644
index 0000000000..ac90ebd45e
--- /dev/null
+++ b/.github/native/startup_diagnosis.py
@@ -0,0 +1,182 @@
+"""Private launch-window capture and fixed Android startup facts only."""
+import json
+import os
+import re
+import subprocess
+import time
+
+APP = 'io.hexawallet.keeper.development'
+LOGBOX_IDS = {'redbox-error', 'redbox-dismiss', 'redbox-reload', 'rn_redbox_stack', 'catalyst_redbox_title'}
+CATEGORIES = {
+ 'JS_TYPE': r'\bTypeError\b', 'JS_REFERENCE': r'\bReferenceError\b', 'JS_SYNTAX': r'\bSyntaxError\b',
+ 'JS_RANGE': r'\bRangeError\b', 'JS_INVARIANT': r'Invariant Violation|has not been registered',
+ 'MODULE_RESOLUTION': r'Unable to resolve module|Cannot find module',
+ 'NATIVE_MODULE_MISSING': r'TurboModuleRegistry.*could not be found|Native module cannot be null|Cannot find native module',
+ 'NATIVE_LIBRARY_LOAD': r'UnsatisfiedLinkError|dlopen failed|couldn.t find DSO',
+ 'BUNDLE_DOWNLOAD_FAILED': r'DebugServerException|Unable to load script|development server returned response error|Could not connect to development server',
+ 'CLEARTEXT_BLOCKED': r'CLEARTEXT communication.*not permitted',
+ 'CONNECTION_FAILED': r'ECONNREFUSED|Connection refused|SocketTimeoutException',
+ 'HOST_EXCEPTION': r'handleHostException|ReactNoCrashSoftException|Exception in native call',
+ 'FATAL_EXCEPTION': r'FATAL EXCEPTION|Fatal signal',
+ 'APP_ANR': r'ANR in ' + re.escape(APP),
+}
+
+
+def categories(text):
+ return [name for name, pattern in CATEGORIES.items() if re.search(pattern, text, re.IGNORECASE)]
+
+
+def _device(native, device):
+ if native.PLATFORM != 'ANDROID' or not re.fullmatch(r'emulator-\d+', device):
+ raise ValueError('Expected owned Android emulator.')
+
+
+def _read(native, path):
+ if path.is_symlink() or not path.resolve().is_relative_to(native.PRIVATE.resolve()):
+ raise ValueError('Expected private diagnostic file.')
+ with path.open('rb') as source:
+ prefix = source.read(512 * 1024)
+ source.seek(0, os.SEEK_END)
+ size = source.tell()
+ source.seek(max(len(prefix), size - 512 * 1024))
+ tail = source.read(512 * 1024)
+ return (prefix + (b'\n' if size > 1024 * 1024 else b'') + tail).decode(errors='replace'), size > 1024 * 1024
+
+
+class Capture:
+ def __init__(self, process, output, started_ms):
+ self.process, self.output, self.started_ms = process, output, started_ms
+
+
+def start(native, device):
+ _device(native, device)
+ native.PRIVATE.mkdir(parents=True, exist_ok=True)
+ started_ms = int(time.time() * 1000)
+ output = (native.PRIVATE / 'startup-logcat.log').open('wb')
+ tags = ['AndroidRuntime:V', 'ReactNativeJS:V', 'ReactNative:V', 'ReactHost:V',
+ 'unknown:ReactHost:V', 'unknown:ReactNative:V', 'unknown:BridgelessReact:V',
+ 'ActivityManager:V', 'ActivityTaskManager:V', '*:S']
+ try:
+ process = subprocess.Popen(['adb', '-s', device, 'logcat', '-T', '1', '-v', 'brief',
+ '-b', 'main', '-b', 'system', '-b', 'crash', *tags],
+ stdout=output, stderr=subprocess.STDOUT, start_new_session=True)
+ return Capture(process, output, started_ms)
+ except Exception:
+ output.close()
+ raise
+
+
+def stop(handle):
+ if handle is None:
+ return
+ try:
+ if handle.process.poll() is None:
+ handle.process.terminate()
+ try:
+ handle.process.wait(timeout=3)
+ except subprocess.TimeoutExpired:
+ handle.process.kill()
+ handle.process.wait(timeout=5)
+ finally:
+ handle.output.close()
+
+
+def hierarchy(native, directory):
+ flags = {'credential_error': False, 'retry': False, 'logbox_controls': False,
+ 'redbox_resource': False, 'loading': False, 'snapshot_count': 0}
+ for path in list(directory.glob('**/screen-hierarchy/step-*.json'))[:8]:
+ text, truncated = _read(native, path)
+ if truncated:
+ continue
+ pending = [json.loads(text)]
+ count, dismiss, minimize = 0, False, False
+ while pending:
+ node = pending.pop()
+ count += 1
+ if count > 10000 or not isinstance(node, dict):
+ raise ValueError('Invalid bounded hierarchy.')
+ attrs = node.get('attributes') or {}
+ if not isinstance(attrs, dict) or not isinstance(node.get('children', []), list):
+ raise ValueError('Invalid hierarchy shape.')
+ resource = attrs.get('resource-id', '')
+ flags['redbox_resource'] |= isinstance(resource, str) and resource.rsplit(':id/', 1)[-1] in LOGBOX_IDS
+ for key in ['text', 'accessibilityText', 'title', 'value']:
+ value = attrs.get(key)
+ flags['credential_error'] |= value == 'Unable to check your passcode. Please try again.'
+ flags['retry'] |= value == 'Retry'
+ flags['loading'] |= value in ['please wait', 'loading']
+ dismiss |= value == 'Dismiss'
+ minimize |= value == 'Minimize'
+ pending.extend(node.get('children', []))
+ flags['snapshot_count'] += 1
+ flags['logbox_controls'] |= dismiss and minimize
+ return flags
+
+
+def collect(native, device, handle=None):
+ _device(native, device)
+ started_ms = handle.started_ms if handle is not None else None
+ facts = {'scope': 'Owned emulator launch window; fixed facts only.', 'collection_errors': []}
+ def collect_one(name, action):
+ try:
+ facts[name] = action()
+ except Exception:
+ facts['collection_errors'].append(name)
+ def logcat():
+ text, truncated = _read(native, native.PRIVATE / 'startup-logcat.log')
+ return {'categories': categories(text), 'input_truncated': truncated,
+ 'launch_window_started_ms': started_ms}
+ def observer():
+ # Fixed rows are regenerated, never forwarded from a writable JSON file.
+ text, truncated = _read(native, native.PRIVATE / 'startup-observer.jsonl')
+ rows, invalid = [], 0
+ for line in text.splitlines()[:1024]:
+ if not line.strip():
+ continue
+ try:
+ row = json.loads(line)
+ when = row.get('time_ms')
+ if type(when) is not int or when < 0 or when > 10**14:
+ raise ValueError('Invalid timestamp.')
+ result = {'stage': 'UNKNOWN' if started_ms is None else 'APP_WINDOW' if when >= started_ms else 'BEFORE_APP'}
+ kind = row.get('kind')
+ if (kind == 'BUILD' and row.get('event') in ['bundle_build_started', 'bundle_build_done', 'bundle_build_failed']) or (kind == 'ERROR' and row.get('event') in ['bundling_error', 'initialize_failed', 'transformer_load_failed', 'hmr_client_error', 'cache_read_error', 'cache_write_error', 'worker_stderr_chunk']):
+ result.update(kind=kind, event=row['event'])
+ result['error_type'] = row.get('error_type') if row.get('error_type') in ['SyntaxError', 'TypeError', 'ReferenceError', 'RangeError', 'TransformError', 'UnableToResolveError', 'ResolutionError', 'AmbiguousModuleResolutionError', 'NotFoundError', 'ResourceNotFoundError', 'GraphNotFoundError', 'RevisionNotFoundError', 'OTHER', None] else 'OTHER'
+ result['categories'] = [item for item in ['MODULE_RESOLUTION', 'SYNTAX', 'TYPE', 'REFERENCE', 'MEMORY', 'TRANSFORM', 'CONNECTION'] if item in row.get('categories', [])]
+ elif kind in ['REQUEST', 'RESPONSE'] and row.get('request') in ['ENTRY_BUNDLE', 'SPLIT_BUNDLE', 'SYMBOLICATE']:
+ result.update(kind=kind, request=row['request'])
+ if kind == 'REQUEST':
+ options = row.get('options', {})
+ result['options'] = {key: options.get(key) if type(options.get(key)) is bool or options.get(key) in [None, 'OTHER'] else 'OTHER' for key in ['dev', 'lazy', 'minify', 'modulesOnly', 'runModule', 'excludeSource']}
+ for key, allowed in {'platform': ['android', 'ios'], 'sourcePaths': ['url-server', 'absolute'], 'engine': ['hermes', 'jsc'], 'app': ['EXPECTED']}.items():
+ result['options'][key] = options.get(key) if options.get(key) in [*allowed, None] else 'OTHER'
+ else:
+ code = row.get('outer_http_status')
+ result['outer_http_status'] = code if type(code) is int and 100 <= code <= 599 else None
+ else:
+ raise ValueError('Invalid observation kind.')
+ rows.append(result)
+ except Exception:
+ invalid += 1
+ return {'rows': rows[:512], 'input_truncated': truncated, 'invalid_rows': invalid,
+ 'scope': 'Outer HTTP status only; multipart terminal status is not observed.'}
+ def process():
+ proc = subprocess.run(['adb', '-s', device, 'shell', 'pidof', APP], capture_output=True, timeout=10)
+ present = proc.returncode == 0 and bool(re.fullmatch(rb'\s*\d+(?:\s+\d+)*\s*', proc.stdout))
+ return {'exit_code': proc.returncode, 'alive': True if present else None,
+ 'scope': 'Positive observation only; failed or malformed queries do not establish absence.'}
+ def foreground():
+ path = native.PRIVATE / 'startup-foreground.log'
+ with path.open('wb') as output:
+ proc = subprocess.run(['adb', '-s', device, 'shell', 'dumpsys', 'activity', 'activities'], stdout=output, stderr=subprocess.STDOUT, timeout=10)
+ text, truncated = _read(native, path)
+ present = proc.returncode == 0 and not truncated and any(
+ re.search(r'\b(?:mResumedActivity|topResumedActivity)\s*[:=]', line) and
+ (match := re.search(r'ActivityRecord\{.*?\bu\d+\s+([A-Za-z0-9_.]+)/[^\s}]+', line)) and
+ match[1] == APP for line in text.splitlines())
+ return {'exit_code': proc.returncode, 'own_app_resumed': True if present else None,
+ 'input_truncated': truncated, 'scope': 'Positive observation only; absence is not inferred.'}
+ for name, action in [('logcat', logcat), ('metro', observer), ('hierarchy', lambda: hierarchy(native, native.PRIVATE / 'maestro-output')), ('process', process), ('foreground', foreground)]:
+ collect_one(name, action)
+ return facts
diff --git a/.github/native/startup_observer.cjs b/.github/native/startup_observer.cjs
new file mode 100644
index 0000000000..5f428e51f8
--- /dev/null
+++ b/.github/native/startup_observer.cjs
@@ -0,0 +1,37 @@
+'use strict';
+
+// Observe the normal Metro configuration. Never alter requests or response bodies.
+const config = require('../../metro.config.js');
+const { record: emit } = require('./startup_reporter.cjs');
+const bool = (value) => value == null ? null : value === 'true' ? true : value === 'false' ? false : 'OTHER';
+const enumeration = (value, allowed) => value == null ? null : allowed.includes(value) ? value : 'OTHER';
+const originalEnhance = config.server && config.server.enhanceMiddleware;
+function enhanceMiddleware(middleware, server) {
+ const inner = originalEnhance ? originalEnhance.call(config.server, middleware, server) : middleware;
+ return function observe(req, res, next) {
+ try {
+ const url = new URL(req.url, 'http://127.0.0.1');
+ const kind = url.pathname === '/index.bundle' ? 'ENTRY_BUNDLE' : url.pathname.endsWith('.bundle') ? 'SPLIT_BUNDLE' : url.pathname === '/symbolicate' ? 'SYMBOLICATE' : null;
+ if (kind) {
+ const query = url.searchParams;
+ const options = {};
+ for (const key of ['dev', 'lazy', 'minify', 'modulesOnly', 'runModule', 'excludeSource']) options[key] = bool(query.get(key));
+ options.platform = enumeration(query.get('platform'), ['android', 'ios']);
+ options.sourcePaths = enumeration(query.get('sourcePaths'), ['url-server', 'absolute']);
+ options.engine = enumeration(query.get('transform.engine'), ['hermes', 'jsc']);
+ options.app = query.has('app') ? query.get('app') === 'io.hexawallet.keeper.development' ? 'EXPECTED' : 'OTHER' : null;
+ const started = Date.now();
+ emit({ kind: 'REQUEST', request: kind, options });
+ res.once('finish', () => {
+ const duration = Date.now() - started;
+ emit({ kind: 'RESPONSE', request: kind,
+ outer_http_status: Number.isInteger(res.statusCode) && res.statusCode >= 100 && res.statusCode <= 599 ? res.statusCode : null,
+ duration_ms: duration >= 0 && duration <= 600000 ? duration : null,
+ });
+ });
+ }
+ } catch (_) { /* Request observation is optional. */ }
+ return inner.call(this, req, res, next);
+ };
+}
+module.exports = { ...config, server: { ...config.server, enhanceMiddleware } };
diff --git a/.github/native/startup_reporter.cjs b/.github/native/startup_reporter.cjs
new file mode 100644
index 0000000000..2ce585a0dc
--- /dev/null
+++ b/.github/native/startup_reporter.cjs
@@ -0,0 +1,59 @@
+'use strict';
+
+// Supported React Native CLI custom reporter; forward its normal TerminalReporter.
+const fs = require('node:fs');
+const os = require('node:os');
+const path = require('node:path');
+const output = path.join(process.env.RUNNER_TEMP || os.tmpdir(), 'keeper-native-private', 'startup-observer.jsonl');
+let rows = 0;
+function emit(row) {
+ if (process.env.KEEPER_STARTUP_OBSERVER_PATH !== output || rows >= 512) return;
+ try {
+ fs.appendFileSync(output, JSON.stringify({ time_ms: Date.now(), ...row }) + '\n', { mode: 0o600 });
+ rows += 1;
+ } catch (_) { /* Observation cannot change Metro behavior. */ }
+}
+const enumeration = (value, allowed) => value == null ? null : allowed.includes(value) ? value : 'OTHER';
+function failure(error) {
+ const message = String(error && error.message || '');
+ return {
+ error_type: enumeration(error && (error.type || error.name), ['SyntaxError', 'TypeError', 'ReferenceError', 'RangeError', 'TransformError', 'UnableToResolveError', 'ResolutionError', 'AmbiguousModuleResolutionError', 'NotFoundError', 'ResourceNotFoundError', 'GraphNotFoundError', 'RevisionNotFoundError']),
+ categories: [
+ ['MODULE_RESOLUTION', /unable to resolve|cannot find module|module not found/i],
+ ['SYNTAX', /syntaxerror|unexpected token|syntax error/i],
+ ['TYPE', /typeerror/i], ['REFERENCE', /referenceerror/i],
+ ['MEMORY', /heap out of memory|allocation failed/i],
+ ['TRANSFORM', /transformerror|transform failed|babel.*error/i],
+ ['CONNECTION', /econnrefused|connection refused|socket hang up/i],
+ ].filter(([, pattern]) => pattern.test(message)).map(([name]) => name),
+ };
+}
+class StartupReporter {
+ constructor(terminal) {
+ // Resolve from the app's CLI plugin, matching runServer even with nested Metros.
+ const { createRequire } = require('node:module');
+ const fromReactNative = createRequire(require.resolve('react-native/package.json'));
+ const fromCLI = createRequire(fromReactNative.resolve('@react-native/community-cli-plugin/package.json'));
+ const { TerminalReporter } = fromCLI('metro');
+ this.original = new TerminalReporter(terminal);
+ }
+ update(event) {
+ try {
+ if (['bundle_build_started', 'bundle_build_done', 'bundle_build_failed'].includes(event.type)) {
+ const details = event.bundleDetails || {};
+ emit({ kind: 'BUILD', event: event.type,
+ platform: enumeration(details.platform, ['android', 'ios']),
+ dev: typeof details.dev === 'boolean' ? details.dev : null,
+ minify: typeof details.minify === 'boolean' ? details.minify : null,
+ });
+ } else if (['bundling_error', 'initialize_failed', 'transformer_load_failed', 'hmr_client_error', 'cache_read_error', 'cache_write_error'].includes(event.type)) {
+ emit({ kind: 'ERROR', event: event.type, ...failure(event.error) });
+ } else if (event.type === 'worker_stderr_chunk') {
+ emit({ kind: 'ERROR', event: event.type, ...failure({ message: event.chunk }) });
+ }
+ } catch (_) { /* Do not interfere with reporting. */ }
+ return this.original.update(event);
+ }
+ static record(row) { emit(row); }
+}
+module.exports = StartupReporter;
diff --git a/.github/native/version_history_fixture.js b/.github/native/version_history_fixture.js
new file mode 100644
index 0000000000..2309f35aa2
--- /dev/null
+++ b/.github/native/version_history_fixture.js
@@ -0,0 +1,31 @@
+// Selected only by fixed hosted fixture configurations, never normal index.js.
+import React, { useEffect, useState } from 'react';
+import { AppRegistry, SafeAreaView, Text } from 'react-native';
+import Realm from 'realm';
+import * as Keychain from 'react-native-keychain';
+import { createMMKV } from 'react-native-mmkv';
+import cryptoJS from 'crypto-js';
+import DeviceInfo from 'react-native-device-info';
+import config from 'react-native-config';
+import schema from '../../src/storage/realm/schema';
+import { Storage } from '../../src/storage';
+import { name as appName } from '../../app.json';
+const { runFixture } = require('./version_history_fixture_core');
+export function registerFixture(phase) {
+ let attempt;
+ function HistoryFixture() {
+ const [stage, setStage] = useState('running');
+ useEffect(() => {
+ let active = true;
+ if (!attempt) attempt = runFixture({ phase, storage: Storage,
+ fixtureStorage: createMMKV({ id: 'keeper-ci-version-history-v1' }), Keychain, cryptoJS,
+ Realm, schema, DeviceInfo, config, development: __DEV__ }).catch(() => 'failed');
+ attempt.then((result) => { if (active) setStage(result); });
+ return () => { active = false; };
+ }, []);
+ return
+ Keeper controlled history fixture {stage}
+ ;
+ }
+ AppRegistry.registerComponent(appName, () => HistoryFixture);
+}
diff --git a/.github/native/version_history_fixture_core.js b/.github/native/version_history_fixture_core.js
new file mode 100644
index 0000000000..8a8c7ffcca
--- /dev/null
+++ b/.github/native/version_history_fixture_core.js
@@ -0,0 +1,128 @@
+/* CI-only controlled history fixture. No credentials or identifiers leave the device. */
+const BACKUP_KEY = 'version-history-original-v1';
+const PHASES = ['seed_stale', 'verify_stale_first', 'verify_stale_repeat', 'seed_empty',
+ 'verify_empty_first', 'verify_empty_repeat', 'restore', 'verify_restored'];
+const STALE = [
+ { version: '2.6.2(600)', title: 'Recovered Wallet', date: '2026-01-02T03:04:05.000Z' },
+ { version: '2.6.3(619)', title: 'Initially installed', date: '2026-02-03T04:05:06.000Z' },
+];
+class FixtureFailure extends Error { constructor(code) { super(code); this.code = code; } }
+function check(value, code) { if (!value) throw new FixtureFailure(code); }
+function sorted(rows) { return rows.map((r) => ({ ...r })).sort((a,b) => a.version.localeCompare(b.version)); }
+function rowsOf(db) { return sorted(Array.from(db.objects('VersionHistory'), (r) => ({
+ version: r.version, title: r.title, date: r.date, releaseNote: r.releaseNote ?? null,
+}))); }
+function normalized(rows) { return sorted(rows.map((r) => ({ ...r, releaseNote: r.releaseNote ?? null }))); }
+function same(a,b) { return JSON.stringify(a) === JSON.stringify(b); }
+function owner(storage) {
+ const root = JSON.parse(storage.getString('persist:root'));
+ const accounts = JSON.parse(root.account).allAccounts;
+ const state = JSON.parse(root.storage);
+ check(Array.isArray(accounts) && accounts.length === 1, 'sole-account-required');
+ const a = accounts[0];
+ check(a.isDefault === true && a.accountIdentifier === '' && a.realmId === 'keeper.realm' &&
+ typeof a.appId === 'string' && !!a.appId && a.appId === state.appId &&
+ typeof a.hash === 'string' && !!a.hash, 'default-owner-required');
+ return { appId: a.appId, realmId: a.realmId, hash: a.hash, sharedVersion: state.appVersion };
+}
+function replaceHistory(db, rows) {
+ db.write(() => {
+ db.delete(db.objects('VersionHistory'));
+ rows.forEach((r) => db.create('VersionHistory', r));
+ });
+ check(same(rowsOf(db), normalized(rows)), 'history-write-readback-failed');
+}
+async function runFixture({ phase, storage, fixtureStorage, Keychain, cryptoJS, Realm, schema,
+ DeviceInfo, config, development, now = () => Date.now() }) {
+ check(development === true && config.ENVIRONMENT === 'DEVELOPMENT' &&
+ config.RELAY === 'http://127.0.0.1:8765/' &&
+ config.ENC_KEY_STORAGE_IDENTIFIER === 'KEEPER-HOSTED-DISPOSABLE', 'disposable-build-required');
+ check(PHASES.includes(phase), 'phase-rejected');
+ const current = owner(storage);
+ const version = DeviceInfo.getVersion(), build = DeviceInfo.getBuildNumber();
+ check(version === '2.6.4' && /^(620|627)$/.test(build) && current.sharedVersion === version,
+ 'expected-current-installed-version-required');
+ const key = `${version}(${build})`;
+ const credential = await Keychain.getGenericPassword({ service: undefined });
+ check(credential && credential.username === config.ENC_KEY_STORAGE_IDENTIFIER,
+ 'fixture-credential-required');
+ const parsed = JSON.parse(credential.password);
+ check(parsed.hash === current.hash && parsed.hash === cryptoJS.SHA512('1111').toString(cryptoJS.enc.Hex) &&
+ typeof parsed.enc_key === 'string' && !!parsed.enc_key, 'matching-disposable-pin-required');
+ const clearKey = cryptoJS.AES.decrypt(parsed.enc_key, parsed.hash).toString(cryptoJS.enc.Utf8);
+ check(/^[a-f0-9]{64}$/.test(clearKey), 'valid-native-realm-key-required');
+ const encryptionKey = Uint8Array.from(clearKey, (c) => c.codePointAt(0));
+ // A missing database is rejected before open; this helper never creates an account.
+ check(await Realm.schemaVersion(current.realmId, encryptionKey) === 109, 'existing-schema-required');
+ const db = await Realm.open({ path: current.realmId, encryptionKey, schema, schemaVersion: 109 });
+ try {
+ const apps = Array.from(db.objects('KeeperApp'));
+ const walletIds = Array.from(db.objects('Wallet'), (w) => w.id).sort();
+ check(apps.length === 1 && apps[0].id === current.appId && apps[0].version === version &&
+ walletIds.length === 1 && db.objects('Vault').length === 0, 'owned-current-account-required');
+ const identity = { ...current, version, build, walletIds };
+ let saved = fixtureStorage.getString(BACKUP_KEY);
+ if (phase === 'seed_stale') {
+ check(saved === undefined, 'history-backup-already-present');
+ const original = rowsOf(db);
+ check(original.length === 1 && original[0].version === key &&
+ original[0].title === 'Initially installed' && Number.isFinite(Date.parse(original[0].date)),
+ 'initial-disposable-history-required');
+ saved = { schema: 1, identity, original, phase: 'stale_seeded', seededAt: now() };
+ fixtureStorage.set(BACKUP_KEY, JSON.stringify(saved));
+ check(same(JSON.parse(fixtureStorage.getString(BACKUP_KEY)), saved), 'backup-readback-failed');
+ replaceHistory(db, STALE);
+ return 'pass';
+ }
+ check(typeof saved === 'string', 'history-backup-required');
+ saved = JSON.parse(saved);
+ check(saved.schema === 1 && same(saved.identity, identity), 'history-owner-changed');
+ check(Array.isArray(saved.original) && saved.original.length === 1 &&
+ saved.original[0].version === key && saved.original[0].title === 'Initially installed' &&
+ Number.isFinite(Date.parse(saved.original[0].date)) &&
+ same(saved.original, normalized(saved.original)), 'original-history-backup-invalid');
+ if (phase === 'restore') {
+ replaceHistory(db, saved.original);
+ saved.phase = 'restored';
+ } else if (phase === 'verify_restored') {
+ check(saved.phase === 'restored' && same(rowsOf(db), saved.original), 'restored-history-required');
+ fixtureStorage.remove(BACKUP_KEY);
+ check(fixtureStorage.getString(BACKUP_KEY) === undefined, 'history-backup-cleanup-failed');
+ return 'pass';
+ } else if (phase === 'seed_empty') {
+ check(saved.phase === 'stale_repeat_verified', 'stale-relaunch-verification-required');
+ check(same(rowsOf(db), saved.lastVerifiedRows), 'verified-history-changed-before-empty-fixture');
+ saved.seededAt = now();
+ replaceHistory(db, []);
+ saved.phase = 'empty_seeded';
+ delete saved.observationDate;
+ } else {
+ const stale = phase.startsWith('verify_stale_');
+ const repeat = phase.endsWith('_repeat');
+ const scenario = stale ? 'stale' : 'empty';
+ check(saved.phase === `${scenario}_${repeat ? 'first_verified' : 'seeded'}`,
+ 'history-phase-order-required');
+ const observed = rowsOf(db);
+ const row = observed.find((r) => r.version === key);
+ check(row && row.title === 'Current installation observed' &&
+ Number.isFinite(Date.parse(row.date)) && row.releaseNote === null, 'observation-required');
+ check(same(observed.filter((r) => r.version !== key), normalized(stale ? STALE : [])),
+ 'provenance-mutated-or-fabricated-upgrade');
+ if (repeat) check(row.date === saved.observationDate, 'observation-date-changed-on-relaunch');
+ else {
+ const observedAt = Date.parse(row.date), verifiedAt = now();
+ // Production Date.toString() has second precision. Keep the actual
+ // device clock window; an arbitrary old or future date is not evidence.
+ check(Number.isFinite(saved.seededAt) && Number.isFinite(verifiedAt) &&
+ observedAt >= saved.seededAt - 1500 && observedAt <= verifiedAt + 1500,
+ 'observation-outside-device-clock-window');
+ saved.observationDate = row.date;
+ }
+ saved.phase = `${scenario}_${repeat ? 'repeat' : 'first'}_verified`;
+ saved.lastVerifiedRows = observed;
+ }
+ fixtureStorage.set(BACKUP_KEY, JSON.stringify(saved));
+ return 'pass';
+ } finally { db.close(); }
+}
+module.exports = { BACKUP_KEY, PHASES, STALE, FixtureFailure, runFixture };
diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md
new file mode 100644
index 0000000000..91cd9f43e4
--- /dev/null
+++ b/.github/pull_request_template.md
@@ -0,0 +1,35 @@
+## Problem and change
+
+
+
+Issue:
+OpenSpec change / archived proposal:
+Target branch:
+
+## Test results
+
+
+
+| Check / scenario | Platform | Passed / failed / blocked / not run | Evidence or reason |
+| --- | --- | --- | --- |
+| | | | |
+
+## Review considerations
+
+
+
+- [ ] The diff excludes local secrets, wallet data and generated build/dependency files.
+- [ ] Test failures and untested behavior are recorded above.
+- [ ] The issue/spec and implementation describe the same scope.
+
+Keeper maintainers own security review, acceptance, merging and official releases.
+Passing checks does not constitute approval.
+
+## Signoff
+
+- Copilot review findings:
+- Developer approval:
+- Product owner signoff:
diff --git a/.github/scripts/044-android-metadata-policy.json b/.github/scripts/044-android-metadata-policy.json
new file mode 100644
index 0000000000..86038ddf93
--- /dev/null
+++ b/.github/scripts/044-android-metadata-policy.json
@@ -0,0 +1 @@
+{"derived_public_literals":[".github/native/credential_fixture.yaml",".github/native/history_fixture.yaml",".github/native/history_product.yaml",".github/native/product_credential_blocked.yaml",".github/native/product_credential_recovered.yaml",".github/native/product_first_wallet.yaml",".github/native/product_key_acceptance.yaml",".github/native/product_retry.yaml",".github/native/product_vault_acceptance.yaml","EXPECTED_FIXTURE_ID=history-fixture-restore-pass","EXPECTED_FIXTURE_ID=history-fixture-seed_empty-pass","EXPECTED_FIXTURE_ID=history-fixture-seed_stale-pass","EXPECTED_FIXTURE_ID=history-fixture-verify_empty_first-pass","EXPECTED_FIXTURE_ID=history-fixture-verify_empty_repeat-pass","EXPECTED_FIXTURE_ID=history-fixture-verify_restored-pass","EXPECTED_FIXTURE_ID=history-fixture-verify_stale_first-pass","EXPECTED_FIXTURE_ID=history-fixture-verify_stale_repeat-pass","FIXTURE_STAGE=armed","FIXTURE_STAGE=restored","private_startup-foreground","private_startup-logcat","private_startup-observer"],"historical_decoded_file_sha256":"547eaeced710034b606d6be7ca512be4536729fd41d95ba631a3577d412aae85","historical_metadata_sha256":"8471b48f7637923ae2576f17a25c95898ed9bfac445ff1cbcda816cfa6a7f70a","historical_zip_sha256":"4d464ef5f8faa7de4f02292e683f0dad8242544843610da9371f2c675dc183f0","producer_sha256":{".github/native/hosted_native.py":"d84f434818531a6ecaacd7f78271249e7f28e04950961f764d8e4edba5c96392",".github/native/startup_diagnosis.py":"1d38c3dbc9feaa9b38702104b65b54f6d6a641cf24a9458238e9604c82da893a",".github/native/startup_failure_receipts.py":"17b8c41595a838fb49b6630548b713959363d59e54c687cb5b58fc3dc7278a24",".github/native/android_startup_diagnosis.py":"3faa81bf91839c2bcebc35b8f4889f25ffb0bb7bbfc8224cceda05746a7dd0b8",".github/native/onboarding_failure_receipts.py":"4f3765c0f1211037bcc810a5ddd02f3d638314cc8cc28bf400dba8ac812b099d",".github/native/product_measurements.py":"a7ef5d2bdc676b0a30d702ce905cf8835f59b608826d373273d278f42616b65b",".github/native/product_failure_diagnosis.py":"d6555e7391301ae1c52d606c6a8cd0ccc65d08025cbca59fcd528e753510e601",".github/native/maestro_failure_snapshot.py":"07c9c2f5ccd06418159e0010f3ab1a092e3c0092c53b839ddcc5cbc4aa90c16a",".github/native/product_metro.py":"aafb62713b71741062d03a7b1919db365efc72d9f02bcacd7a91a21384ead356",".github/native/product_key_acceptance.py":"d644d1874fcd6e7df0af864d4cc54ac253e487d9adf7760bcca2e9886aedf6bb",".github/native/product_credential_acceptance.py":"756dc01908df98f9ea3a49f74c33666a6076c2aa5859bf1950f9d9f71b2e5bd2",".github/native/product_history_acceptance.py":"c6bb5e70fcc25e51f603b4d80bf44bf91e158c27aff9d5770f6ea11bbaed2a6a",".github/native/product_vault_acceptance.py":"133c3b53356fd7c8ee692e7abc179a55584564f5ed54c3647d78549568b31258"},"public_literals":["","\t","\n","\r"," \\("," is not available"," is visible"," was requested, but it is not connected.","\"","%s failed (exit %s). %s","%s-development-warmup.bundle","%{http_code}","(?:FATAL EXCEPTION|Caused by:|\\b[\\w.$]*(?:Exception|Error)\\b|Invariant Violation|Unable to load script|Could not)","(?:\\b(?:error|exception|fatal)\\b|\\b[\\w.$]*(?:Exception|Error)\\b)","(?\\d{4}-\\d{2}-\\d{2}[ T]\\d{2}:\\d{2}:\\d{2}(?:\\.\\d{1,9})?(?:[+-]\\d{2}:?\\d{2}|Z)?)\\s+(?P[A-Za-z]+)\\s+(?P[A-Za-z0-9_.-]{1,128})\\[(?P[1-9]\\d{0,9}):(?:0x)?[A-Fa-f0-9]{1,16}\\]\\s+(?P.*)","([1-9]\\d*)\\s+(\\S+)","*","** TEST EXECUTE FAILED **","** TEST FAILED **","**/maestro.log","**/screen-hierarchy/step-*.json","**/xctest_runner_*.log","*:E","*:S","+00:00","-","- stopApp","--","--------- beginning of ","--config","--custom-log-reporter-path","--debug-output","--deployment","--device","--env","--error-on-fail","--exit-code","--fail","--flatten-debug-output","--format","--frozen-lockfile","--global","--ignore-scripts","--last","--location","--max-time","--max-workers=2","--no-daemon","--no-document","--no-repo-update","--non-interactive","--output","--platform","--port","--predicate","--quiet","--remove","--sdk","--show-error","--show-sdk-version","--silent","--style","--test-output-dir","--version","--write-out","-A","-PreactNativeArchitectures=x86_64","-T","-[A-Za-z0-9_=-]+/base\\.apk)","-b","-c","-configuration","-d","-derivedDataPath","-destination","-o","-p","-pass","-q","-r","-s","-scheme","-sdk","-sf","-t","-v","-version","-workspace",".","./gradlew",".env.ci",".github/native",".github/native/",".github/native/credential_fixture.yaml",".github/native/history_fixture.yaml",".github/native/history_product.yaml",".github/native/nodeify.cjs",".github/native/product_credential_blocked.yaml",".github/native/product_credential_recovered.yaml",".github/native/product_first_wallet.yaml",".github/native/product_key_acceptance.yaml",".github/native/product_retry.yaml",".github/native/product_vault_acceptance.yaml",".github/native/r5_features.yaml",".github/native/r5_metro.cjs",".github/native/r5_prepare.cjs",".github/native/release_metro.cjs",".github/native/release_probe.yaml",".github/native/startup.yaml",".github/native/startup_observer.cjs",".github/native/startup_reporter.cjs",".log",".py",".yaml","/","/createNewApp","/home/runner/work/_temp/keeper-native-private/android-development-warmup.bundle","/home/runner/work/_temp/keeper-native-private/features-junit.xml","/home/runner/work/_temp/keeper-native-private/keeper-product-ui-4x6to7ap/sample-1","/home/runner/work/_temp/keeper-native-private/keeper-product-ui-4x6to7ap/sample-1/junit.xml","/home/runner/work/_temp/keeper-native-private/maestro","/home/runner/work/_temp/keeper-native-private/maestro-output","/home/runner/work/_temp/keeper-native-private/maestro.zip","/home/runner/work/_temp/keeper-native-private/maestro/maestro/bin/maestro","/home/runner/work/_temp/keeper-native-private/probe-junit.xml","/home/runner/work/_temp/keeper-native-private/smoke-junit.xml","/home/runner/work/bitcoin-keeper/bitcoin-keeper/android/app/build/outputs/apk/development/debug/app-development-debug.apk","/metric","/opt/homebrew/bin","/opt/homebrew/bin/node","/pin-progress","0","0497b2aaeb76372a6f21721f28ebd42ec2877155a090580b23ace2e017fab6a8","1","1.16.2","10m","120","1200","123456789012","127.0.0.1","1:123456789012:android:0000000000000000","1:123456789012:ios:0000000000000000000000","1f084ee4486709e0066034a452349df897eb2434","2","2.6.4","200","20261012.334.1","22ba1d5bbf45ab23c7db661a0635096b2a19878cbc0817c0eb1bfeebd8f24920","23f14e01f3437c213f1443c3167d96022f3a43bc","240","27.1.12297006","300","35.0.0","36","36059f89937d744ff83d61c12bd3779b70dc7dd2ac745e18e6d4b7dc04e8dbac","37.2.12","39846002094","417a11a4dd6a3a190dacfbe0679df3133712e96b987430faa4923bfc2b4dca6a","437e920b9dd0015fdd6d283dd037a63178bfcde8a1599d3620bb4266d8345127","5384593cb4e7a106489e75a821d157dd43f4e438df6bc308b72e82c685e1283a","548fd95fa62f675f0b42340e72a5e2558f33cff9272207f4523962531124d702","65537","6d30c9d4599aa0b5a2b0176e8563d787e9d4c3f17b6016c8590afbbf3f29186a","744dfbc11d1aa4baed230bfd6bf110c50db2e8e68a4ecb6b42c4507e7993fafa","7ff1e0b1c9022b1f06c70b340be044ba641c8718d1708ea650a04b5eb3bd8347","8081","8767","88a35d8dc409c63d70459295112c6a9484f6b14bbff75b3e23965c31f700ef0e",":",":app:assembleDevelopmentDebug",":id/"," (?!Task\\b)|^Caused by:","\\bkey_[1-4]\\b","\\bprocess=(\\S+)\\s+reason=(\\d+)\\s","\\d{3}","\\x1b\\[[0-9;]*[A-Za-z]","^","^(?:(?:>\\s*)?\\d+\\s*\\||\\^|at\\s)","^(?:ERROR\\b|FATAL ERROR:|(?:\\w*Error):|Unable to resolve module)","^(?:ERROR\\b|FATAL ERROR:|\\w*Error:|Unable to resolve module)","^(?:MemTotal|MemAvailable|SwapTotal|SwapFree)\\b","^(?:error\\b|(?:Syntax|Type|Reference)Error:|Unable to resolve module)","^(?:oom|oom_kill)\\b","^(MemTotal|MemAvailable|SwapTotal|SwapFree):\\s+(\\d+) kB$","^(oom|oom_kill) (\\d+)$","^BUNDLE\\s","^Could not ","^FAILURE:|^A problem occurred|^Execution failed","^PREBUNDLE\\s","^[EF]/(AndroidRuntime|ReactNativeJS|ReactNative)\\s*\\(\\s*\\d+\\):\\s*(.*)","^\\[!\\]","^\\d+\\s*\\|","^\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}\\.\\d+\\s+(\\d+)\\s+\\d+\\s+[EF]\\s+[^:]+:\\s*(.*)$","^\\d{4}-","^e: ","__main__","_bundle","_metro.cjs","_test_cases","a","absolute","accepted","accessibilityText","account_version_unchanged","acknowledged_create_responses","action","activities","activity","adb","after_sha256","alive","allow_control","allowed_fields","analytics_auto_collection_enabled","analytics_collection_deactivated","android","android-startup-diagnosis","android-startup-errors.log","android/app/build/outputs/apk/development/debug/app-development-debug.apk","android/app/google-services.json","androidVersionCode","android_client_info","android_errors","android_runtime_diagnosis","android_runtime_diagnostic","android_startup_diagnosis","android_startup_diagnosis.py","api_key","app","app.json","app_data_collection_default_enabled","app_id","app_settings","application/json","archived_only_key_semantics","archived_only_mobile_logically_archived","archived_signer_record_retention_ui","archived_vault_reinstated_after_cold_restart","arm","arm64","armed","artifact_policy","artifacts","ascii","assertWalletAccount","assertion failed","attributes","attribution","babel.config.js","backend","backend_compatibility","backup_service_removed_after_verified_restore","base.apk","before_dependencies","before_native_build","before_sha256","bin/maestro","binary","binding_state","boot","bootstatus","bottom","bounds","brief","browser","browserify","btn_AppSettingsIcon","btn_skip","build","build-tools/35.0.0","build-tools;35.0.0","built_artifact","bundle_build_done","bundle_build_failed","bundle_build_started","bundle_marker_count","bundle_marker_observed","bundle_tree_sha256","bundling_error","bytes","bytes_appended","bytes_observed","bytes_read","bytes_scanned","c64954ef892c8782324afcda57f69e510bab33649a47baaf702daf51eeae919a","cache_read_error","cache_write_error","cancel_tapped","cancel_visible","cancelled_confirmation_preserved_key","capture","capture_output","catalyst_redbox_title","categories","category_record_counts","cause","cgroup","check","children","classified_error_records","cleanup","cleanup_errors","cleanup_failure_categories","cleanup_failure_category","cleanup_failure_stages","cleanup_status","clear","clearVerifiedRemoteRevision","cli-2.11.0","clickable","client","client_info","cocoapods","cold_relaunch_to_authenticated_home_ms","cold_relaunch_to_login_ms","cold_wrong_login_pin_rejected","collection_error_types","collection_errors","collector","com.apple.CoreSimulator.SimDeviceType.iPhone-16","com.apple.CoreSimulator.SimRuntime.iOS-18-5","command","command not found","command-%03d.log","commands","compact","companion_metro_switches","compileSdk=36; buildTools=35.0.0; NDK=27.1.12297006","complete","complete_lines","completed_markers","completed_stages","configuration","configuration_overlays","configuration_version","confirmPIN","confirm_passcode","confirm_passcode_visible","confirmation_digits_tapped","conflicts","consumer_marker_limit","continue_tapped","continue_visible","controlled-transport-no-backend-acceptance","controlled_disconnect_retry","could not find compatible versions","count_scope","counts","coverage","crash","create","createPIN","create_new_app_calls","create_passcode","create_tapped","created","credential-ui","credential_error","credential_errors_ui","credential_fixture.yaml","credential_metro.cjs","credential_store_read_fault","credentials_exported","curl","currentBackupAccountSession","currentBackupAppId","currentWalletAccountId","current_key","cwd","d","daemon","data","data/Containers/Bundle/Application","db","debug","default","delete","deleteAppImageEntityWorker","deleteSigningDeviceWorker","delete_confirmation_scoped","deletion_persisted_after_relaunch","dev","developmentServerError","device","device_","device_uninstall","df","diagnostic","diagnostic_marker_records","diagnostic_only","diagnostics","diff","diff_sha256","dir","directory","disabled","disk_preflight","dismiss_control","dont_allow_control","driver","driver_preflight","driver_startup_timeout","dumpsys","duplicate_records","duration_seconds","e","e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855","e867f5ec8e96a16afc83d2c355f798b292e2335c0e97591fc7521bf68c5fe726","ef18f4962decfa11fb69825ff7b983fd086c243b5d2bbe4ed55f6aa5a4a68169","element not found","empty_current_observation_count","empty_deletion_entry_verified","empty_first_ui","empty_repeat_ui","emulator","emulator-","emulator-5554","emulator-[0-9]+","emulator-\\d+","emulator/source.properties","enabled","engine","entrypoint","entrypoint_under_test","env","er","error","error_details","error_headers","error_records","error_type","errors","event","evidence-save","exact_resource_id_count","exception_types","excludeSource","exec-out","executable","executable_sha256","exist_ok","existing_disposable_home_verified","exit-history","exit-info","exit_code","exit_history","expected_emulator_target","expected_installed_build","expected_installed_version","expected_sdk_build","export_row_limit","export_truncated","exported_rows","f","facts","failed_assertion","failed_assertion_snapshot","failed_commands","failed_phase","failed_selector","failure","failure_category","failure_kind","failure_observation","failures","fault","fault_categories","features","features-junit.xml","features_bundle","file","files/","final_visible_wallet_composition","final_visible_wallet_count","final_wallet_verified","firebase.json","fixture_phases","fixture_scope","flags","flush","focused","foreground","foreground_activity","foreign_pid_records","format","free_bytes","fresh_disposable_state","freshness","ft","full_input","gem","generic/platform=iOS Simulator","get-serialno","getAccountFromSigner","getKeyUID","get_app_container","getprop","git","github-hosted","google/sdk_gphone64_x86_64/emu64xa:15/AE3A.240806.043/12960925:userdebug/dev-keys","gradle","growth_detected","handleHostException|ReactNoCrashSoftException|Exception in native call","hardware","hardware_device_checks","has not been registered","head","hermes","hermes.*(?:exception|fatal|error|failed)|(?:exception|fatal|error).*hermes","hexa_keeper_dev","hidden_reference_blocks_without_name_after_relaunch","hidden_reference_ui","hierarchy","hierarchy_signals","history-ui","history_","history_fixture.yaml","history_product.yaml","history_regex","history_restore","history_seed_empty","history_seed_stale","history_verify_empty_first","history_verify_empty_repeat","history_verify_restored","history_verify_stale_first","history_verify_stale_repeat","hmr_client_error","home_ready","host_memory","host_port_unavailable","hosted_native","hosted_native.py","http://127.0.0.1:8081/index.bundle?platform=%s&dev=true&minify=false","http://127.0.0.1:8081/index.bundle?platform=android&dev=true&minify=false","http://127.0.0.1:8081/status","http://127.0.0.1:8765/","http_status","https://127.0.0.1:9/","https://github.com/mobile-dev-inc/Maestro/releases/download/%s/maestro.zip","https://github.com/mobile-dev-inc/Maestro/releases/download/cli-2.11.0/maestro.zip","https://public@127.0.0.1:9/1","i","iOS 18.5","iOS driver not ready in time, consider increasing timeout by configuring MAESTRO_DRIVER_STARTUP_TIMEOUT env variable","iPhone 16","iPhone 16; iOS 18.5","id","id: ","ignore_errors","image","indent","index.js","info","initial","initialize_failed","injected-dispatch-selection-no-login-acceptance","input_byte_limit","input_limit_exceeded","input_truncated","input_usable","install","install_diagnosis","install_diagnosis.py","install_succeeded","installed-artifact-","installed_artifact","installed_artifact_scope","installed_artifact_verified","installed_regex","installed_version_header_and_initial_history","invalid_records","invalid_rows","invalid_text_records","inventory_sha256","io.hexawallet.hexakeeper.dev","io.hexawallet.keeper","io.hexawallet.keeper.development","io.hexawallet.keeper.development:id/","ios","ios-startup-errors-stderr.log","ios-startup-errors.log","ios/GoogleService-Info.plist","ios/GoogleServices/dev/GoogleService-Info.plist","ios/Podfile.lock","ios/hexa_keeper.xcworkspace","iosBuildNumber","ios_errors","ios_simulator_architecture","iphonesimulator","iteration","java","jsc","junit","junit.xml","keeper-disposable-ci","keeper-native-private","keeper-product-ui-","keeper-r5-native-evidence.json","key-ui","key_1","key_2","key_3","key_4","key_management_entry_and_exit","key_management_entry_verified","key_management_scope","key_management_ui","keychain","kind","label","launch_window_started_ms","lazy","left","limit","limits","line_scan_limit","line_scan_truncated","lines_scanned","link","ln","loading","lockfile needs to be updated","lockfile needs to be updated|could not find compatible versions|^The sandbox is not in sync","log","log_limit_reached","logbox_controls","logbox_counter","logbox_error_header","logbox_syntax_footer","logbox_warning_header","logcat","login","logs_read","lookup_status","maestro","maestro-output","maestro-preflight-state","maestro.zip","maestro/tests","maestro_preflight","main","malformed_cold_start_blocked","malformed_marker_records","malformed_record_lines","malformed_startup_blocked","marker","marker_limit_reached","marker_records","matching_process_count","matching_process_records","matching_records","max","measurements","meminfo","memory.current","memory.events","memory.max","message","messaging_auto_init_enabled","metadata","metadata.json","method","metro","metro-%02d.log","metro.config.js","metro.log","metro_errors","metro_output","metro_process","metro_progress","metro_warmup","minify","minimize_control","minimum_free_bytes","missing_ok","mkdir","mobile_key_origin","mobilesdk_app_id","mode","modulesOnly","more_wallets_navigation","names","native","native-worker-process-relaunch-counts","native_credential_api","native_mobile_and_public_seed_created","native_private_material_exactness","native_probe","native_probe_test_cases","navigation_verified","ndk/27.1.12297006","ndk;27.1.12297006","network","network_scope","new_account_requests_during_credential_flow","new_account_requests_during_history_flow","new_account_requests_during_key_flow","new_account_requests_during_vault_flow","next_marker","no space left on device","no-product-ui-navigation-pin-or-biometric-acceptance","noScriptURL","node","node_count","node_modules/.bin/patch-package","node_modules/react-native/cli.js","nodeify_overlay","notification_permission_controls","notification_prompt_phrase","npm","object_pairs_hook","observation_state","observeBackupAccount","observed_android_sdk","observed_error_headers","onboarding_boundary_observation","onboarding_skip","openiap","openjdk version \"17.0.20.1\" 2026-08-18\nOpenJDK Runtime Environment Temurin-17.0.20.1+1 (build 17.0.20.1+1)\nOpenJDK 64-Bit Server VM Temurin-17.0.20.1+1 (build 17.0.20.1+1, mixed mode, sharing)","options","original_credential_exported","original_history_restored","os","os_keychain_denial_or_hardware_read_fault","other_backend_calls_rejected","out of memory|heap limit|heap out of memory","outer_http_status","oversized_record_lines","own_app_resumed","own_error_records","owned_marker_records","ownership_usable","package.json","package:(/data/app/(?:~~[A-Za-z0-9_=-]+/)?","package_name","parents","parse_constant","parse_error","parse_error_types","parse_status","parsed_error_records","parsed_records","partial_end","partial_records","partial_start","pass","passed","path","performance_sample","performance_scope","phase","physical_biometrics","physical_devices","pid","pidof","pin_onboarding_progress","platform","platforms/android-36","platforms;android-36","please wait","pm","pod","prebuilt_driver_selected","prebundle_marker_count","predecessor_fixture_verified","prefix","prepare","private-output","private_","private_startup-foreground","private_startup-logcat","private_startup-observer","probe","probe-and-worker-timings-not-product-startup-ux","probe-junit.xml","probe_bundle","probe_diagnostics","probe_ready_ms","probe_scope","proc/meminfo","process","process == \"%s\" AND (messageType == \"error\" OR messageType == \"fault\" OR eventMessage CONTAINS[c] \"error\" OR eventMessage CONTAINS[c] \"exception\" OR eventMessage CONTAINS[c] \"fatal\")","process_state","processes","producer_limit_may_be_reached","producer_per_stage_limit","producer_row_limit","producer_total_limit","product","product_android_failure_diagnosis","product_credential_acceptance","product_credential_blocked.yaml","product_credential_recovered.yaml","product_credential_ui","product_entrypoint","product_failure_diagnosis","product_first_wallet.yaml","product_history_acceptance","product_key_acceptance","product_key_acceptance.py","product_key_acceptance.yaml","product_key_ui","product_measurements","product_measurements.py","product_metro","product_retry.yaml","product_ui","product_ui_","product_vault_acceptance","product_vault_acceptance.yaml","product_vault_ui","product_version_history_ui","production-deletion-native-rollback","production-deletion-retained-native-references","production-setup-offline-retry-native-counts","production-worker-native-storage","production-worker-stale-session-rejection","profile","project_id","project_info","project_number","protected_backup","protected_backup_deletion","ps","pull","query_status","r5_feature_evidence","r5_features","r5_features_test_cases","r5_release_acceptance","raw_durations","rb","react-native","react-native-keychain","react-native.config.js","read","read_scope","real_two_of_two_vault_created","reason","reason_categories","record","record_limit_reached","recover_tile","recovery_key_preservation","redacted_tool_errors","redbox-dismiss","redbox-error","redbox-reload","redbox_resource","referenced_vault_ui","rejected_snapshots","relation","relaunch_home","relaunch_login","relaunch_start","release/version.json","release_readiness","repeat_login_observation_date_unchanged","replace","replacement_character_observed","report","request","requested_device_disconnected","requested_samples","requires a higher minimum deployment target","reset","resource-id","restore","restored","restored_cold_wallet_preserved","restored_login_available","restored_wallet_preserved","result","retained_mobile_key_is_protected_again","retry","retry_error_visible","retry_fixture_start","retry_home_ready","retry_relaunch_home","retry_relaunch_login","retry_relaunch_start","retry_remains_blocked","retry_scope","retry_submit","rev-parse","reverse","right","rn_redbox_dismiss_button","rn_redbox_reload_button","rn_redbox_stack","ro.build.fingerprint","rows","run","run-as","runModule","run_attempt","run_id","runner","runner_install_launch_returned","runner_install_started","runtime","runtime-errors","runtime_errors","same_process_retry_after_external_repair","sample","sample-%d","samples","save","scan_limit_reached","scan_record_limit","scanned_error_context_lines","scanned_records","scenario","scenarios","schema","scope","sdk","sdkmanager","seed_fixture_origin","selected","selector","sequence_number","server-close","server-shutdown","setupKeeperAppWorker","setup_first_wallet_ms","severity","sha256","shell","shim.js","show","shutdown","signing","simctl","simctl create did not return an owned simulator UUID.","simulator_readiness","simulator_readiness.py","skip","skip_tapped","skip_visible","skipped","smoke","smoke-junit.xml","smoke_scope","smoke_test_cases","snapshot_count","snapshot_limit_exceeded","sort_keys","source","source.properties","sourcePaths","source_functions","source_sha","spawn","src","src/services/backup/transport.ts","src/store/sagas/bhr.ts","src/store/sagas/storage.ts","src/store/sagas/wallets.ts","src/utils/utilities.ts","stage","stage_evidence","stages","stale_current_observation_count","stale_first_ui","stale_initial_and_recovery_dates_preserved","stale_repeat_ui","start","start_new_session","start_new_text","start_new_tile","start_new_to_home_ms","start_new_to_ready_ms","start_new_visible","startup","startup-foreground.log","startup-logcat.log","startup-observer.jsonl","startup_capture","startup_cleanup_errors","startup_diagnosis","startup_diagnosis.py","startup_diagnostics","startup_observation","startup_observation_capture","startup_observation_cleanup","startup_ready","startup_start","startup_timing_scope","startup_to_passcode_ms","state","status","status_check_failed","status_check_started","status_response_received","stderr","stdout","strict","successfully_empty_store","sudo","synthetic-wallet-generation-no-crypto-acceptance","sys/fs/cgroup","system","tap_coordinates","target","tcp:","tcp:8081","tcp:8765","tcp:8767","test","testcase","testcase_failures","testcase_statuses","testsuite","testsuites","text","threadtime","time_ms","timeout","timeout_seconds","timestamp","title","toolchain","top","transformer_load_failed","transport_requests_dropped_without_commit","true","truncated_logs","tsconfig.json","ubuntu24","ui test runner does not exist","ui_test_runner_missing","unableLoadScript","unclassified_error_context_lines","unclassified_error_headers","unclassified_error_records","unclassified_own_error_records","unexpected_create_attempts","uninstall","unknown:BridgelessReact:V","unknown:ReactHost:V","unknown:ReactNative:V","unparsed_nonempty_lines","unparsed_records","unrelated_mobile_wallet_retained","unrelated_visible_wallet_count_after_relaunch","unrelated_wallet_preserved","unrelated_wallet_preserved_final_count_three","unsupported_marker_records","unused_mobile_key_created","unused_mobile_key_deleted","unzip","update","url","url-server","utf-8","utf-8-sig","v22.23.3","valid_records","valid_rows_in_scanned_input","value","vault-ui","vault_references_ui","vault_unhidden_with_correct_native_pin","version","version_history_scope","version_history_ui","version_history_verified","view_recoverTile","view_startNewTile","visible_eligible_keys_after_deletion","visible_reference_blocks_mobile_deletion","visible_reference_ui","visible_to_user","visible_wallet_count","visible_wallet_count_after_recovery_and_cold_login","visible_wallet_count_after_relaunch","visible_wallet_count_before_relaunch","wallet_ready","wallet_start","wb","welcome","welcome_back","worker_stderr_chunk","workflow_ref","workflow_sha","would like to send you notifications","wrong_deletion_pin_rejected","x86_64","xb","xcode","xcode_test_execute_failed","xcode_test_failed","xcode_testing_failed","xcodebuild","xcodebuild_driver_selected","xcrun","xctestrun config does not exist","xctestrun_config_missing","yarn","yarn.lock","yarn@1.22.22","zero_balance_rotation_retained_original_archive","\ufffd"],"source_sha":"044ebb6ea2d465f6a70e9116e3feac5a604cd696","source_tree":"4856035ece888230674e061c53115de3d6f025ed","app_boundary_sha256":{"src/storage/startup-failure-observer.ts":"385d6524515a90535f53cdba91ceaa186b6405f7d8baeb41a69af12205c63ca9","src/storage/secure-store.ts":"6cf606da180e606c42a2d9a2e0af5dfa6949e4cf7c53d01198e1bebec7f61bb4","src/screens/Splash/SplashScreen.tsx":"e6b646f0730fdb7841127d6ae7803aa08205a767d5a6751c186f68816b350452","src/utils/onboarding-boundary-observer.ts":"19956a67f03339c560ead93a050176ce6d5d00ae34c935b23359f9c6218f8247","src/screens/Splash/OnBoardingSlides.tsx":"5dca510a91478ca24b4390e7de9c0a31012650e14cae8f0c9969ef4da438f819","src/screens/NewKeeperAppScreen/NewKeeperAppScreen.tsx":"9a95098c06e061e3242db6206a9ab2be3ed675b788c57c1bfcf8ffa0b7a91dd1"}}
diff --git a/.github/scripts/044-ios-metadata-policy.json b/.github/scripts/044-ios-metadata-policy.json
new file mode 100644
index 0000000000..d041aab84b
--- /dev/null
+++ b/.github/scripts/044-ios-metadata-policy.json
@@ -0,0 +1 @@
+{"derived_public_literals":[".github/native/credential_fixture.yaml",".github/native/history_fixture.yaml",".github/native/history_product.yaml",".github/native/product_credential_blocked.yaml",".github/native/product_credential_recovered.yaml",".github/native/product_first_wallet.yaml",".github/native/product_key_acceptance.yaml",".github/native/product_retry.yaml",".github/native/product_vault_acceptance.yaml","APP_ID=io.hexawallet.hexakeeper.dev","EXPECTED_FIXTURE_ID=history-fixture-restore-pass","EXPECTED_FIXTURE_ID=history-fixture-seed_empty-pass","EXPECTED_FIXTURE_ID=history-fixture-seed_stale-pass","EXPECTED_FIXTURE_ID=history-fixture-verify_empty_first-pass","EXPECTED_FIXTURE_ID=history-fixture-verify_empty_repeat-pass","EXPECTED_FIXTURE_ID=history-fixture-verify_restored-pass","EXPECTED_FIXTURE_ID=history-fixture-verify_stale_first-pass","EXPECTED_FIXTURE_ID=history-fixture-verify_stale_repeat-pass","EXPECTED_HISTORY_REGEX=^2\\.6\\.4\\(620\\)$","EXPECTED_INSTALLED_REGEX=^2\\.6\\.4 \\(620\\)$","FIXTURE_STAGE=armed","FIXTURE_STAGE=restored","^2\\.6\\.4 \\(620\\)$","^2\\.6\\.4\\(620\\)$","native_probe_test_cases","private_startup-foreground","private_startup-logcat","private_startup-observer","r5_features_test_cases","smoke_test_cases"],"historical_metadata_representation":"normalized JSON, not original ZIP/member bytes","historical_metadata_sha256":"b0d8b6c6bbec9ef6dd4eb71f0c4f5d90a66086ee5bbb9bbf23163b8c95429923","historical_policy_sha256":"ab720280a30f521ff0aed139f376bdabcba295632d3081b6dbeb21fb5e9a830c","literal_provenance":"13-producer AST strings/keywords; historical iOS; finite CLI/suite fields","producer_sha256":{".github/native/android_startup_diagnosis.py":"3faa81bf91839c2bcebc35b8f4889f25ffb0bb7bbfc8224cceda05746a7dd0b8",".github/native/hosted_native.py":"d84f434818531a6ecaacd7f78271249e7f28e04950961f764d8e4edba5c96392",".github/native/maestro_failure_snapshot.py":"07c9c2f5ccd06418159e0010f3ab1a092e3c0092c53b839ddcc5cbc4aa90c16a",".github/native/onboarding_failure_receipts.py":"4f3765c0f1211037bcc810a5ddd02f3d638314cc8cc28bf400dba8ac812b099d",".github/native/product_credential_acceptance.py":"756dc01908df98f9ea3a49f74c33666a6076c2aa5859bf1950f9d9f71b2e5bd2",".github/native/product_failure_diagnosis.py":"d6555e7391301ae1c52d606c6a8cd0ccc65d08025cbca59fcd528e753510e601",".github/native/product_history_acceptance.py":"c6bb5e70fcc25e51f603b4d80bf44bf91e158c27aff9d5770f6ea11bbaed2a6a",".github/native/product_key_acceptance.py":"d644d1874fcd6e7df0af864d4cc54ac253e487d9adf7760bcca2e9886aedf6bb",".github/native/product_measurements.py":"a7ef5d2bdc676b0a30d702ce905cf8835f59b608826d373273d278f42616b65b",".github/native/product_metro.py":"aafb62713b71741062d03a7b1919db365efc72d9f02bcacd7a91a21384ead356",".github/native/product_vault_acceptance.py":"133c3b53356fd7c8ee692e7abc179a55584564f5ed54c3647d78549568b31258",".github/native/startup_diagnosis.py":"1d38c3dbc9feaa9b38702104b65b54f6d6a641cf24a9458238e9604c82da893a",".github/native/startup_failure_receipts.py":"17b8c41595a838fb49b6630548b713959363d59e54c687cb5b58fc3dc7278a24"},"public_literals":["","\t","\n","\r"," \\("," is not available"," is visible"," was requested, but it is not connected.","\"","%s failed (exit %s). %s","%s-development-warmup.bundle","%{http_code}","(0|-?[1-9][0-9]{0,5})","(?:0[1-9]|1[0-2])-(?:0[1-9]|[12][0-9]|3[01]) (?:[01][0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9]\\.[0-9]{3} +([1-9][0-9]{0,9}) +([1-9][0-9]{0,9}) +E +ReactNativeJS: (.*)","(?:0|-?[1-9][0-9]{0,9})","(?:0|[1-9][0-9]{0,14})","(?:FATAL EXCEPTION|Caused by:|\\b[\\w.$]*(?:Exception|Error)\\b|Invariant Violation|Unable to load script|Could not)","(?:\\b(?:error|exception|fatal)\\b|\\b[\\w.$]*(?:Exception|Error)\\b)","(?:^|[/\\s])simctl\\s+install\\s+","(?:container|containermanager).*\\b(?:error|failed|unavailable)\\b","(?:install coordination|IXCoordinator|IXSClient|IXClient)","(?\\d{4}-\\d{2}-\\d{2}[ T]\\d{2}:\\d{2}:\\d{2}(?:\\.\\d{1,9})?(?:[+-]\\d{2}:?\\d{2}|Z)?)\\s+(?P[A-Za-z]+)\\s+(?P[A-Za-z0-9_.-]{1,128})\\[(?P[1-9]\\d{0,9}):(?:0x)?[A-Fa-f0-9]{1,16}\\]\\s+(?P.*)","([1-9]\\d*)\\s+(\\S+)","(process == \"CoreSimulatorService\" OR process == \"simctl\") AND eventMessage CONTAINS \"","(v[0-9]{1,4})\\|([A-Z][A-Z0-9_]{0,63})","*","** TEST EXECUTE FAILED **","** TEST FAILED **","**/maestro.log","**/screen-hierarchy/step-*.json","**/xctest_runner_*.log","*:E","*:S","+00:00",",","-","- stopApp","--","--------- beginning of ","--config","--custom-log-reporter-path","--debug-output","--deployment","--device","--env","--error-on-fail","--exit-code","--fail","--flatten-debug-output","--format","--frozen-lockfile","--global","--ignore-scripts","--last","--location","--max-time","--max-workers=2","--no-daemon","--no-document","--no-repo-update","--non-interactive","--output","--platform","--port","--predicate","--quiet","--remove","--sdk","--show-error","--show-sdk-version","--silent","--style","--test-output-dir","--version","--write-out","-A","-PreactNativeArchitectures=x86_64","-T","-[A-Za-z0-9_=-]+/base\\.apk)","-axo","-b","-c","-configuration","-d","-derivedDataPath","-destination","-file","-install.sample","-o","-p","-pass","-q","-r","-s","-scheme","-sdk","-sf","-t","-v","-version","-workspace",".","..","./gradlew",".env.ci",".github/native",".github/native/",".github/native/credential_fixture.yaml",".github/native/history_fixture.yaml",".github/native/history_product.yaml",".github/native/nodeify.cjs",".github/native/product_credential_blocked.yaml",".github/native/product_credential_recovered.yaml",".github/native/product_first_wallet.yaml",".github/native/product_key_acceptance.yaml",".github/native/product_retry.yaml",".github/native/product_vault_acceptance.yaml",".github/native/r5_features.yaml",".github/native/r5_metro.cjs",".github/native/r5_prepare.cjs",".github/native/release_metro.cjs",".github/native/release_probe.yaml",".github/native/startup.yaml",".github/native/startup_observer.cjs",".github/native/startup_reporter.cjs",".log",".py",".yaml","/","/Users/runner/hostedtoolcache/node/22.23.3/arm64/bin/node","/Users/runner/work/_temp/keeper-native-private/DerivedData","/Users/runner/work/_temp/keeper-native-private/DerivedData/Build/Products/Debug-iphonesimulator/hexa_keeper_dev.app","/Users/runner/work/_temp/keeper-native-private/ios-development-warmup.bundle","/Users/runner/work/_temp/keeper-native-private/maestro","/Users/runner/work/_temp/keeper-native-private/maestro-output","/Users/runner/work/_temp/keeper-native-private/maestro.zip","/Users/runner/work/_temp/keeper-native-private/maestro/maestro/bin/maestro","/Users/runner/work/_temp/keeper-native-private/smoke-junit.xml","/createNewApp","/metric","/opt/homebrew/bin","/opt/homebrew/bin/node","/pin-progress","0","0497b2aaeb76372a6f21721f28ebd42ec2877155a090580b23ace2e017fab6a8","1","1.16.2","10m","120","1200","123456789012","127.0.0.1","18.5","1:123456789012:android:0000000000000000","1:123456789012:ios:0000000000000000000000","1f084ee4486709e0066034a452349df897eb2434","200","20260907.0337.1","22ef01b796c2fd1dfd29553915ba10c99f89f0212f82aca052cd74a73e38e59d","23f14e01f3437c213f1443c3167d96022f3a43bc","240","2576e14246d1a52bc122edd56925603c20cad3e51c563f1ca01752d53185025c","3","300","39846002094","3m","437e920b9dd0015fdd6d283dd037a63178bfcde8a1599d3620bb4266d8345127","4f19863902bad018cb0e75a32eece966a93d589f1946adcd2cecb4179e9725f3","5384593cb4e7a106489e75a821d157dd43f4e438df6bc308b72e82c685e1283a","65537","6d30c9d4599aa0b5a2b0176e8563d787e9d4c3f17b6016c8590afbbf3f29186a","71335e478813602f32c1d51df317913e1cf68e12aba5977be99d00956065413d","7c09ba8d5ff1dd2168b9b6101a91e9881a4abcb2365331df0780ee1280c019e7","8081","8560AC52-E179-4A94-A071-52E85351EAF4","858409cf396536ebdf30850c46f3a2481ff1f141733817d57c0662e68d05d4e1","8767","89f43f0d5907d8e45f260156238b3cb433076c84c3dee2dd4884b456e438629c","99414832-4502-4DCD-A80E-4DC9D6B458C7","9f56fca152030dba9e8ee76dee4fc8967ab667507b5878f0f9ab819d55b6b9a6",":",":app:assembleDevelopmentDebug",":id/"," (?!Task\\b)|^Caused by:","\\bkey_[1-4]\\b","\\bprocess=(\\S+)\\s+reason=(\\d+)\\s","\\d{3}","\\s+Code\\s*=\\s*(-?\\d+)\\b","\\x1b\\[[0-9;]*[A-Za-z]","^","^(?:(?:>\\s*)?\\d+\\s*\\||\\^|at\\s)","^(?:ERROR\\b|FATAL ERROR:|(?:\\w*Error):|Unable to resolve module)","^(?:ERROR\\b|FATAL ERROR:|\\w*Error:|Unable to resolve module)","^(?:MemTotal|MemAvailable|SwapTotal|SwapFree)\\b","^(?:error\\b|(?:Syntax|Type|Reference)Error:|Unable to resolve module)","^(?:oom|oom_kill)\\b","^(MemTotal|MemAvailable|SwapTotal|SwapFree):\\s+(\\d+) kB$","^(oom|oom_kill) (\\d+)$","^2\\.6\\.4 \\(620\\)$","^2\\.6\\.4\\(620\\)$","^BUNDLE\\s","^Could not ","^FAILURE:|^A problem occurred|^Execution failed","^PREBUNDLE\\s","^[EF]/(AndroidRuntime|ReactNativeJS|ReactNative)\\s*\\(\\s*\\d+\\):\\s*(.*)","^\\[!\\]","^\\d+\\s*\\|","^\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}\\.\\d+\\s+(\\d+)\\s+\\d+\\s+[EF]\\s+[^:]+:\\s*(.*)$","^\\d{4}-","^\\s*(\\d+)\\s+(\\S+)\\s+(.*)$","^e: ","__main__","__psynch_mutexwait|__ulock_wait|pthread_mutex_lock","_bundle","_metro.cjs","_test_cases","a","a2d63b0ed820a22b936a4a2e46c6d9581270118e45279855d6915471089b5653","absolute","accepted","accessibilityText","account_version_unchanged","acknowledged_create_responses","action","activities","activity","adb","after_command_index","after_sha256","alive","allow_control","allowed_fields","analytics_auto_collection_enabled","analytics_collection_deactivated","android","android-startup-diagnosis","android-startup-errors.log","android/app/build/outputs/apk/development/debug/app-development-debug.apk","android/app/google-services.json","androidVersionCode","android_client_info","android_errors","android_runtime_diagnosis","android_runtime_diagnostic","android_startup_diagnosis","android_startup_diagnosis.py","api_key","app","app.json","app_data_collection_default_enabled","app_id","app_settings","appinstalld","application/json","applicationverificationfailed|invalid code signature|signature.*(?:invalid|verification failed)","archived_only_key_semantics","archived_only_mobile_logically_archived","archived_signer_record_retention_ui","archived_vault_reinstated_after_cold_restart","arm","arm64","armed","artifact_policy","artifacts","ascii","assertConditionCommand","assertWalletAccount","assertion failed","attempts","attributes","attribution","b17ae0c6b5c0ef6d7c717e0941ee8d5fdf9f43cf4321f37379e520ebe5c90af3","b389643cb05e0064e7d51f3dfb0bba6f91d5ff391e970060c3bc5a1111fd17dd","b5e958cf0b45ac3edcb87a72c6c892652582b08f90247205810b570fc4780d79","babel.config.js","backend","backend_compatibility","backup_service_removed_after_verified_restore","baffb93e8a4d08ec3be61d9e38d0741c0e9f4637339ce15199f138a3979b9981","base.apk","baseline","baseline-listapps","baseline-preferences-container","before_dependencies","before_native_build","before_sha256","bin/maestro","binary","binding_state","boot","bootstatus","bottom","bounds","brief","browser","browserify","btn_AppSettingsIcon","btn_skip","build","build-tools/35.0.0","build-tools;35.0.0","built_artifact","bundle.*(?:invalid|validation failed)|invalid.*(?:bundle|executable)","bundle_build_done","bundle_build_failed","bundle_build_started","bundle_marker_count","bundle_marker_observed","bundle_tree_sha256","bundling_error","bytes","bytes_appended","bytes_observed","bytes_read","bytes_scanned","cache_read_error","cache_write_error","cancel_tapped","cancel_visible","cancelled_confirmation_preserved_key","capture","capture_output","catalyst_redbox_title","categories","category_record_counts","cause","cgroup","check","checked","children","classified_error_records","cleanup","cleanup_errors","cleanup_failure_categories","cleanup_failure_category","cleanup_failure_stages","cleanup_status","clear","clearVerifiedRemoteRevision","cli-2.11.0","clickable","client","client_info","cocoapods","code","cold_relaunch_to_authenticated_home_ms","cold_relaunch_to_login_ms","cold_wrong_login_pin_rejected","collection_error_types","collection_errors","collector","com.apple.CoreSimulator.SimDeviceType.iPhone-16","com.apple.CoreSimulator.SimError","com.apple.CoreSimulator.SimRuntime.iOS-18-5","com.apple.Preferences","com.apple.appinstalld","com.apple.lsd","com.apple.mobile.installd","command","command not found","command-%03d.log","command_error_type","command_index","command_returned","commands","commands.json","compact","companion_metro_switches","compileSdk=36; buildTools=35.0.0; NDK=27.1.12297006","complete","complete_lines","completed_markers","completed_stages","condition","configuration","configuration_overlays","configuration_version","confirmPIN","confirm_passcode","confirm_passcode_visible","confirmation_digits_tapped","conflicts","connection.*(?:invalidated|interrupted|refused|timed out)|failed to connect|service.*not available","consumer_marker_limit","continue_tapped","continue_visible","controlled-transport-no-backend-acceptance","controlled_disconnect_retry","could not find compatible versions","count_scope","counts","coverage","crash","create","createPIN","create_new_app_calls","create_passcode","create_tapped","created","credential-ui","credential_error","credential_errors_ui","credential_fixture.yaml","credential_metro.cjs","credential_store_read_fault","credentials_exported","criterion","curl","currentBackupAccountSession","currentBackupAppId","currentWalletAccountId","current_key","cwd","d","daemon","data","data/Containers/Bundle/Application","db","debug","debugMessage","default","delete","deleteAppImageEntityWorker","deleteSigningDeviceWorker","delete_confirmation_scoped","deletion_persisted_after_relaunch","depth","dev","developmentServerError","device","device.*(?:not booted|shutdown|unavailable)|invalid device state","device_","device_uninstall","df","diagnostic","diagnostic_marker_records","diagnostic_only","diagnostics","diff","diff_sha256","dir","directory","disabled","disk","disk_free_bytes","disk_preflight","dismiss_control","dispatch_sync|dispatch_semaphore_wait|dispatch_group_wait","dont_allow_control","driver","driver_preflight","driver_startup_timeout","dumpsys","duplicate_records","duration","duration_seconds","e","e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855","element not found","empty_current_observation_count","empty_deletion_entry_verified","empty_first_ui","empty_repeat_ui","emulator","emulator-","emulator-[0-9]+","emulator-\\d+","emulator/source.properties","enabled","engine","entries","entrypoint","entrypoint_under_test","env","er","error","error_details","error_domain_codes","error_headers","error_name","error_records","error_type","errors","evaluatedCommand","event","evidence-save","exact_resource_id_count","exception_types","excludeSource","exec-out","executable","executable_sha256","exist_ok","existing_disposable_home_verified","exit-history","exit-info","exit_code","exit_history","expected_emulator_target","expected_installed_build","expected_installed_version","expected_sdk_build","export_row_limit","export_truncated","exported_rows","f","facts","failed to install|could not install|installation failed","failed_assertion","failed_assertion_snapshot","failed_commands","failed_phase","failed_selector","failure","failure_category","failure_kind","failure_observation","failures","false","fault","fault_categories","features","features-junit.xml","file","files/","final_visible_wallet_composition","final_visible_wallet_count","final_wallet_verified","firebase.json","fixture_phases","fixture_scope","flags","flush","focused","follow_symlinks","foreground","foreground_activity","foreign_pid_records","foreign_process_markers","format","free_bytes","fresh_disposable_state","freshness","ft","full_input","gem","generic/platform=iOS Simulator","get-serialno","getAccountFromSigner","getKeyUID","get_app_container","getprop","git","github-hosted","gradle","grew_during_read","growth_detected","handleHostException|ReactNoCrashSoftException|Exception in native call","hardware","hardware_device_checks","has not been registered","head","hermes","hermes.*(?:exception|fatal|error|failed)|(?:exception|fatal|error).*hermes","hexa_keeper_dev","hidden_reference_blocks_without_name_after_relaunch","hidden_reference_ui","hierarchy","hierarchy_signals","history-ui","history_","history_fixture.yaml","history_product.yaml","history_regex","history_restore","history_seed_empty","history_seed_stale","history_verify_empty_first","history_verify_empty_repeat","history_verify_restored","history_verify_stale_first","history_verify_stale_repeat","hmr_client_error","home_ready","host_load","host_load_1_5_15m","host_memory","host_port_unavailable","hosted_native","hosted_native.py","http://127.0.0.1:8081/index.bundle?platform=%s&dev=true&minify=false","http://127.0.0.1:8081/index.bundle?platform=ios&dev=true&minify=false","http://127.0.0.1:8081/status","http://127.0.0.1:8765/","http_status","https://127.0.0.1:9/","https://github.com/mobile-dev-inc/Maestro/releases/download/%s/maestro.zip","https://github.com/mobile-dev-inc/Maestro/releases/download/cli-2.11.0/maestro.zip","https://public@127.0.0.1:9/1","i","iOS 18.5","iOS driver not ready in time, consider increasing timeout by configuring MAESTRO_DRIVER_STARTUP_TIMEOUT env variable","iPhone 16","iPhone 16; iOS 18.5","id","id: ","idRegex","ignore_errors","image","indent","index.js","info","initial","initialize_failed","injected-dispatch-selection-no-login-acceptance","input_byte_limit","input_limit_exceeded","input_partial","input_truncated","input_usable","install","install-diagnosis-%03d","install-sample","install_command_output","install_diagnoses","install_diagnosis","install_diagnosis.py","install_running_after_collection","install_running_before_collection","install_sample","install_succeeded","installd","installed-artifact-","installed_artifact","installed_artifact_scope","installed_artifact_verified","installed_regex","installed_version_header_and_initial_history","invalid_compact_markers","invalid_record_fields","invalid_records","invalid_rows","invalid_text_records","inventory_sha256","io.hexawallet.hexakeeper.dev","io.hexawallet.keeper","io.hexawallet.keeper.development","io.hexawallet.keeper.development:id/","io.hexawallet.keeper.development:id/btn_skip","ios","ios-startup-errors-stderr.log","ios-startup-errors.log","ios/GoogleService-Info.plist","ios/GoogleServices/dev/GoogleService-Info.plist","ios/Podfile.lock","ios/hexa_keeper.xcworkspace","iosBuildNumber","ios_errors","ios_simulator_architecture","iphonesimulator","iteration","java","jsc","junit","junit.xml","keeper-disposable-ci","keeper-native-private","keeper-product-ui-","keeper-r5-native-evidence.json","key-ui","key_1","key_2","key_3","key_4","key_management_entry_and_exit","key_management_entry_verified","key_management_scope","key_management_ui","keychain","kind","label","launch_window_started_ms","launchctl","lazy","left","limit","limit_reached","limits","line_scan_limit","line_scan_truncated","lines_scanned","link","list","listapps","ln","loading","lockfile needs to be updated","lockfile needs to be updated|could not find compatible versions|^The sandbox is not in sync","log","log_limit_reached","logbox_controls","logbox_counter","logbox_error_header","logbox_syntax_footer","logbox_warning_header","logcat","login","logs_read","lookup_status","lsd","macOS","macOS-15.7.9-arm64-arm-64bit-Mach-O","mach_msg|mach_msg2_trap","macos15","maestro","maestro-output","maestro-preflight-state","maestro.zip","maestro/tests","maestro_failure_snapshot","maestro_failure_snapshot.py","maestro_preflight","main","malformed_cold_start_blocked","malformed_marker_records","malformed_markers","malformed_record_lines","malformed_startup_blocked","marker","marker_limit_reached","marker_records","marker_records_seen","matching_process_count","matching_process_records","matching_records","max","max_workers","measurements","meminfo","memory.current","memory.events","memory.max","message","messaging_auto_init_enabled","metadata","metadata.json","method","metro","metro-%02d.log","metro.config.js","metro.log","metro_errors","metro_output","metro_process","metro_progress","metro_warmup","minify","minimize_control","minimum_free_bytes","missing_ok","mkdir","mobile_key_origin","mobilesdk_app_id","mode","modulesOnly","more_wallets_navigation","names","native","native-worker-process-relaunch-counts","native_credential_api","native_mobile_and_public_seed_created","native_private_material_exactness","native_probe","native_probe_test_cases","navigation_verified","ndk/27.1.12297006","ndk;27.1.12297006","network","network_scope","new_account_requests_during_credential_flow","new_account_requests_during_history_flow","new_account_requests_during_key_flow","new_account_requests_during_vault_flow","next_marker","no space left on device","no space left on device|not enough (?:free )?(?:disk )?space","no-product-ui-navigation-pin-or-biometric-acceptance","noScriptURL","node","node_count","node_modules/.bin/patch-package","node_modules/react-native/cli.js","nodeify_overlay","notification_permission_controls","notification_prompt_phrase","npm","object_pairs_hook","observation_state","observeBackupAccount","observed_after_deadline","observed_android_sdk","observed_error_headers","onboarding_boundary_observation","onboarding_failure_receipts","onboarding_failure_receipts.py","onboarding_skip","openiap","openjdk version \"17.0.20.1\" 2026-08-18\nOpenJDK Runtime Environment Temurin-17.0.20.1+1 (build 17.0.20.1+1)\nOpenJDK 64-Bit Server VM Temurin-17.0.20.1+1 (build 17.0.20.1+1, mixed mode, sharing)","optional","options","original_credential_exported","original_history_restored","os","os_keychain_denial_or_hardware_read_fault","other_backend_calls_rejected","out of memory|heap limit|heap out of memory","outcome","outer_http_status","outside_window_markers","oversized_record_lines","own_app_resumed","own_error_records","own_process_count","own_process_count_capped","owned-host-events","owned_install_process_count","owned_install_running","owned_marker_records","ownership_usable","package.json","package:(/data/app/(?:~~[A-Za-z0-9_=-]+/)?","package_name","parents","parse_constant","parse_error","parse_error_types","parse_status","parsed_error_records","parsed_records","partial_end","partial_records","partial_start","pass","passed","path","performance_sample","performance_scope","permission denied|operation not permitted|not authorized","phase","physical_biometrics","physical_devices","pid","pid=,stat=,args=","pidof","pin_onboarding_progress","platform","platforms/android-36","platforms;android-36","please wait","pm","pod","post-install-container","post_install_lookup","prebuilt_driver_selected","prebundle_marker_count","predecessor_fixture_verified","prefix","prefix_bytes","prefix_sha256","prepare","private-output","private_","private_startup-foreground","private_startup-logcat","private_startup-observer","probe","probe-and-worker-timings-not-product-startup-ux","probe-junit.xml","probe_diagnostics","probe_ready_ms","probe_scope","proc/meminfo","process","process == \"%s\" AND (messageType == \"error\" OR messageType == \"fault\" OR eventMessage CONTAINS[c] \"error\" OR eventMessage CONTAINS[c] \"exception\" OR eventMessage CONTAINS[c] \"fatal\")","process == \"hexa_keeper_dev\" AND (messageType == \"error\" OR messageType == \"fault\" OR eventMessage CONTAINS[c] \"error\" OR eventMessage CONTAINS[c] \"exception\" OR eventMessage CONTAINS[c] \"fatal\")","process == \"installd\" OR process == \"appinstalld\" OR process == \"lsd\"","process_state","processes","producer_limit_may_be_reached","producer_per_stage_limit","producer_row_limit","producer_total_limit","product","product_android_failure_diagnosis","product_credential_acceptance","product_credential_blocked.yaml","product_credential_recovered.yaml","product_credential_ui","product_entrypoint","product_failure_diagnosis","product_first_wallet.yaml","product_history_acceptance","product_key_acceptance","product_key_acceptance.py","product_key_acceptance.yaml","product_key_ui","product_measurements","product_measurements.py","product_metro","product_retry.yaml","product_ui","product_ui_","product_vault_acceptance","product_vault_acceptance.yaml","product_vault_ui","product_version_history_ui","production-deletion-native-rollback","production-deletion-retained-native-references","production-setup-offline-retry-native-counts","production-worker-native-storage","production-worker-stale-session-rejection","profile","project_id","project_info","project_number","protected_backup","protected_backup_deletion","ps","pull","query_status","query_timeout_seconds","r5_feature_evidence","r5_features","r5_features_test_cases","r5_release_acceptance","raw_durations","rb","react-native","react-native-keychain","react-native.config.js","read","read_scope","real_two_of_two_vault_created","reason","reason_categories","reasons","record","record_limit_reached","records","recover_tile","recovery_key_preservation","redacted_tool_errors","redbox-dismiss","redbox-error","redbox-reload","redbox_resource","referenced_vault_ui","rejected_snapshots","relation","relaunch_home","relaunch_login","relaunch_start","release/version.json","release_readiness","repeat_login_observation_date_unchanged","replace","replacement_character_observed","report","request","requested_device_disconnected","requested_samples","requires a higher minimum deployment target","reset","resource busy|device busy|another installation.*in progress","resource-id","resource_errors","restore","restored","restored_cold_wallet_preserved","restored_login_available","restored_wallet_preserved","result","retained_mobile_key_is_protected_again","retry","retry_error_visible","retry_fixture_start","retry_home_ready","retry_relaunch_home","retry_relaunch_login","retry_relaunch_start","retry_remains_blocked","retry_scope","retry_submit","rev-parse","reverse","right","rn_redbox_dismiss_button","rn_redbox_reload_button","rn_redbox_stack","ro.build.fingerprint","rows","run","run-as","runModule","run_attempt","run_id","runner","runner_install_launch_returned","runner_install_started","running","runtime","runtime-errors","runtime_errors","same_process_retry_after_external_repair","sample","sample-%d","samples","save","scan_limit_reached","scan_record_limit","scanned_error_context_lines","scanned_records","scenario","scenarios","schema","scope","screen-hierarchy/step-([0-9]{3,6})(?:-[A-Za-z0-9_.-]{1,40})?\\.json","sdk","sdkmanager","seed_fixture_origin","selected","selector","sequenceNumber","sequence_number","server-close","server-shutdown","services","setupKeeperAppWorker","setup_first_wallet_ms","severity","sha256","shell","shim.js","show","shutdown","signing","simctl","simctl create did not return an owned simulator UUID.","simulator-install-events","simulator-services","simulator_app_service_readiness","simulator_readiness","simulator_readiness.py","skip","skip_tapped","skip_visible","skipped","smoke","smoke-junit.xml","smoke_scope","smoke_test_cases","snapshot","snapshot_count","snapshot_limit_exceeded","snapshot_phase","sort_keys","source","source.properties","sourcePaths","source_functions","source_sha","spawn","src","src/services/backup/transport.ts","src/store/sagas/bhr.ts","src/store/sagas/storage.ts","src/store/sagas/wallets.ts","src/utils/utilities.ts","stack_categories","stage","stage_evidence","stages","stale_current_observation_count","stale_first_ui","stale_initial_and_recovery_dates_preserved","stale_repeat_ui","start","start_new_session","start_new_text","start_new_tile","start_new_to_home_ms","start_new_to_ready_ms","start_new_visible","started_ms","startup","startup-foreground.log","startup-logcat.log","startup-observer.jsonl","startup_capture","startup_cleanup_errors","startup_diagnosis","startup_diagnosis.py","startup_diagnostics","startup_failure_receipt","startup_failure_receipts","startup_failure_receipts.py","startup_observation","startup_observation_capture","startup_observation_cleanup","startup_ready","startup_start","startup_timing_scope","startup_to_passcode_ms","state","status","status_check_failed","status_check_started","status_response_received","stderr","stdout","strict","successfully_empty_store","sudo","synthetic-wallet-generation-no-crypto-acceptance","sys/fs/cgroup","system","tap_coordinates","target","tcp:","tcp:8081","tcp:8767","test","testcase","testcase_failures","testcase_statuses","testsuite","testsuites","text","threadtime","time_ms","timeout","timeout_seconds","timestamp","title","toolchain","top","transformer_load_failed","transport_requests_dropped_without_commit","true","truncated","truncated_logs","tsconfig.json","type","ui test runner does not exist","ui_test_runner_missing","unableLoadScript","unclassified_error_context_lines","unclassified_error_headers","unclassified_error_records","unclassified_own_error_records","unexpected_create_attempts","uninstall","unknown:BridgelessReact:V","unknown:ReactHost:V","unknown:ReactNative:V","unparsed_nonempty_lines","unparsed_records","unrelated_mobile_wallet_retained","unrelated_visible_wallet_count_after_relaunch","unrelated_wallet_preserved","unrelated_wallet_preserved_final_count_three","unsupported_marker_records","unused_mobile_key_created","unused_mobile_key_deleted","unzip","update","url","url-server","usable","utf-8","utf-8-sig","v1","v22.23.3","valid_records","valid_rows_in_scanned_input","value","vault-ui","vault_references_ui","vault_unhidden_with_correct_native_pin","version","version_history_scope","version_history_ui","version_history_verified","view_recoverTile","view_startNewTile","visible","visible_eligible_keys_after_deletion","visible_reference_blocks_mobile_deletion","visible_reference_ui","visible_to_user","visible_wallet_count","visible_wallet_count_after_recovery_and_cold_login","visible_wallet_count_after_relaunch","visible_wallet_count_before_relaunch","wallet_ready","wallet_start","wb","welcome","welcome_back","window","window_relation","worker_stderr_chunk","workflow_ref","workflow_sha","would like to send you notifications","wrong_deletion_pin_rejected","x86_64","xb","xcode","xcode_test_execute_failed","xcode_test_failed","xcode_testing_failed","xcodebuild","xcodebuild_driver_selected","xcrun","xctestrun config does not exist","xctestrun_config_missing","xpc_connection_send_message_with_reply_sync","yarn","yarn.lock","yarn@1.22.22","zero_balance_rotation_retained_original_archive","|","\ufffd","\ufffd\u2028\u2029"],"source_sha":"044ebb6ea2d465f6a70e9116e3feac5a604cd696"}
diff --git a/.github/scripts/current-android-metadata-policy.json b/.github/scripts/current-android-metadata-policy.json
new file mode 100644
index 0000000000..386e25cd67
--- /dev/null
+++ b/.github/scripts/current-android-metadata-policy.json
@@ -0,0 +1,1841 @@
+{
+ "derived_public_literals": [
+ ".github/native/credential_fixture.yaml",
+ ".github/native/history_fixture.yaml",
+ ".github/native/history_product.yaml",
+ ".github/native/product_credential_blocked.yaml",
+ ".github/native/product_credential_recovered.yaml",
+ ".github/native/product_first_wallet.yaml",
+ ".github/native/product_key_acceptance.yaml",
+ ".github/native/product_retry.yaml",
+ ".github/native/product_vault_acceptance.yaml",
+ "EXPECTED_FIXTURE_ID=history-fixture-restore-pass",
+ "EXPECTED_FIXTURE_ID=history-fixture-seed_empty-pass",
+ "EXPECTED_FIXTURE_ID=history-fixture-seed_stale-pass",
+ "EXPECTED_FIXTURE_ID=history-fixture-verify_empty_first-pass",
+ "EXPECTED_FIXTURE_ID=history-fixture-verify_empty_repeat-pass",
+ "EXPECTED_FIXTURE_ID=history-fixture-verify_restored-pass",
+ "EXPECTED_FIXTURE_ID=history-fixture-verify_stale_first-pass",
+ "EXPECTED_FIXTURE_ID=history-fixture-verify_stale_repeat-pass",
+ "FIXTURE_STAGE=armed",
+ "FIXTURE_STAGE=restored",
+ "private_startup-foreground",
+ "private_startup-logcat",
+ "private_startup-observer"
+ ],
+ "historical_decoded_file_sha256": "547eaeced710034b606d6be7ca512be4536729fd41d95ba631a3577d412aae85",
+ "historical_metadata_sha256": "8471b48f7637923ae2576f17a25c95898ed9bfac445ff1cbcda816cfa6a7f70a",
+ "historical_zip_sha256": "4d464ef5f8faa7de4f02292e683f0dad8242544843610da9371f2c675dc183f0",
+ "producer_sha256": {
+ ".github/native/android_startup_diagnosis.py": "c077aaa2bc5fdf10efff0181df3c3d0afec0b16caa8e94b117b5073e36ad85ad",
+ ".github/native/hosted_native.py": "d3079b1ebb92a5bde93f49fbe8bd1c22297eb9d5751588077d80fe60117a67ed",
+ ".github/native/product_credential_acceptance.py": "756dc01908df98f9ea3a49f74c33666a6076c2aa5859bf1950f9d9f71b2e5bd2",
+ ".github/native/product_failure_diagnosis.py": "68f1e6bb4fd9e0db26f213cf02ebb287dd916b8596f33c8d5632ed52764b8f25",
+ ".github/native/product_history_acceptance.py": "c6bb5e70fcc25e51f603b4d80bf44bf91e158c27aff9d5770f6ea11bbaed2a6a",
+ ".github/native/product_key_acceptance.py": "d644d1874fcd6e7df0af864d4cc54ac253e487d9adf7760bcca2e9886aedf6bb",
+ ".github/native/product_measurements.py": "3e6453a590e4b339548182f8d1d6b2f2be5b164e4dae5106e501244ccdef38b0",
+ ".github/native/product_metro.py": "aafb62713b71741062d03a7b1919db365efc72d9f02bcacd7a91a21384ead356",
+ ".github/native/product_vault_acceptance.py": "133c3b53356fd7c8ee692e7abc179a55584564f5ed54c3647d78549568b31258",
+ ".github/native/startup_diagnosis.py": "1d38c3dbc9feaa9b38702104b65b54f6d6a641cf24a9458238e9604c82da893a"
+ },
+ "public_literals": [
+ "",
+ "\t",
+ "\n",
+ "\r",
+ " \\(",
+ " is not available",
+ " is visible",
+ " was requested, but it is not connected.",
+ "\"",
+ "%s failed (exit %s). %s",
+ "%s-development-warmup.bundle",
+ "%{http_code}",
+ "(?:FATAL EXCEPTION|Caused by:|\\b[\\w.$]*(?:Exception|Error)\\b|Invariant Violation|Unable to load script|Could not)",
+ "(?:\\b(?:error|exception|fatal)\\b|\\b[\\w.$]*(?:Exception|Error)\\b)",
+ "(?\\d{4}-\\d{2}-\\d{2}[ T]\\d{2}:\\d{2}:\\d{2}(?:\\.\\d{1,9})?(?:[+-]\\d{2}:?\\d{2}|Z)?)\\s+(?P[A-Za-z]+)\\s+(?P[A-Za-z0-9_.-]{1,128})\\[(?P[1-9]\\d{0,9}):(?:0x)?[A-Fa-f0-9]{1,16}\\]\\s+(?P.*)",
+ "([1-9]\\d*)\\s+(\\S+)",
+ "*",
+ "** TEST EXECUTE FAILED **",
+ "** TEST FAILED **",
+ "**/maestro.log",
+ "**/screen-hierarchy/step-*.json",
+ "**/xctest_runner_*.log",
+ "*:E",
+ "*:S",
+ "+00:00",
+ "-",
+ "- stopApp",
+ "--",
+ "--------- beginning of ",
+ "--config",
+ "--custom-log-reporter-path",
+ "--debug-output",
+ "--deployment",
+ "--device",
+ "--env",
+ "--error-on-fail",
+ "--exit-code",
+ "--fail",
+ "--flatten-debug-output",
+ "--format",
+ "--frozen-lockfile",
+ "--global",
+ "--ignore-scripts",
+ "--last",
+ "--location",
+ "--max-time",
+ "--max-workers=2",
+ "--no-daemon",
+ "--no-document",
+ "--no-repo-update",
+ "--non-interactive",
+ "--output",
+ "--platform",
+ "--port",
+ "--predicate",
+ "--quiet",
+ "--remove",
+ "--sdk",
+ "--show-error",
+ "--show-sdk-version",
+ "--silent",
+ "--style",
+ "--test-output-dir",
+ "--version",
+ "--write-out",
+ "-A",
+ "-PreactNativeArchitectures=x86_64",
+ "-T",
+ "-[A-Za-z0-9_=-]+/base\\.apk)",
+ "-b",
+ "-c",
+ "-configuration",
+ "-d",
+ "-derivedDataPath",
+ "-destination",
+ "-o",
+ "-p",
+ "-pass",
+ "-q",
+ "-r",
+ "-s",
+ "-scheme",
+ "-sdk",
+ "-sf",
+ "-t",
+ "-v",
+ "-version",
+ "-workspace",
+ ".",
+ "./gradlew",
+ ".env.ci",
+ ".github/native",
+ ".github/native/",
+ ".github/native/credential_fixture.yaml",
+ ".github/native/history_fixture.yaml",
+ ".github/native/history_product.yaml",
+ ".github/native/nodeify.cjs",
+ ".github/native/product_credential_blocked.yaml",
+ ".github/native/product_credential_recovered.yaml",
+ ".github/native/product_first_wallet.yaml",
+ ".github/native/product_key_acceptance.yaml",
+ ".github/native/product_retry.yaml",
+ ".github/native/product_vault_acceptance.yaml",
+ ".github/native/r5_features.yaml",
+ ".github/native/r5_metro.cjs",
+ ".github/native/r5_prepare.cjs",
+ ".github/native/release_metro.cjs",
+ ".github/native/release_probe.yaml",
+ ".github/native/startup.yaml",
+ ".github/native/startup_observer.cjs",
+ ".github/native/startup_reporter.cjs",
+ ".log",
+ ".py",
+ ".yaml",
+ "/",
+ "/createNewApp",
+ "/home/runner/work/_temp/keeper-native-private/android-development-warmup.bundle",
+ "/home/runner/work/_temp/keeper-native-private/features-junit.xml",
+ "/home/runner/work/_temp/keeper-native-private/keeper-product-ui-4x6to7ap/sample-1",
+ "/home/runner/work/_temp/keeper-native-private/keeper-product-ui-4x6to7ap/sample-1/junit.xml",
+ "/home/runner/work/_temp/keeper-native-private/maestro",
+ "/home/runner/work/_temp/keeper-native-private/maestro-output",
+ "/home/runner/work/_temp/keeper-native-private/maestro.zip",
+ "/home/runner/work/_temp/keeper-native-private/maestro/maestro/bin/maestro",
+ "/home/runner/work/_temp/keeper-native-private/probe-junit.xml",
+ "/home/runner/work/_temp/keeper-native-private/smoke-junit.xml",
+ "/home/runner/work/bitcoin-keeper/bitcoin-keeper/android/app/build/outputs/apk/development/debug/app-development-debug.apk",
+ "/metric",
+ "/opt/homebrew/bin",
+ "/opt/homebrew/bin/node",
+ "/pin-progress",
+ "0",
+ "0497b2aaeb76372a6f21721f28ebd42ec2877155a090580b23ace2e017fab6a8",
+ "1",
+ "1.16.2",
+ "10m",
+ "120",
+ "1200",
+ "123456789012",
+ "127.0.0.1",
+ "1:123456789012:android:0000000000000000",
+ "1:123456789012:ios:0000000000000000000000",
+ "1f084ee4486709e0066034a452349df897eb2434",
+ "2",
+ "2.6.4",
+ "200",
+ "20261012.334.1",
+ "22ba1d5bbf45ab23c7db661a0635096b2a19878cbc0817c0eb1bfeebd8f24920",
+ "23f14e01f3437c213f1443c3167d96022f3a43bc",
+ "240",
+ "27.1.12297006",
+ "300",
+ "35.0.0",
+ "36",
+ "36059f89937d744ff83d61c12bd3779b70dc7dd2ac745e18e6d4b7dc04e8dbac",
+ "37.2.12",
+ "39846002094",
+ "417a11a4dd6a3a190dacfbe0679df3133712e96b987430faa4923bfc2b4dca6a",
+ "437e920b9dd0015fdd6d283dd037a63178bfcde8a1599d3620bb4266d8345127",
+ "5384593cb4e7a106489e75a821d157dd43f4e438df6bc308b72e82c685e1283a",
+ "548fd95fa62f675f0b42340e72a5e2558f33cff9272207f4523962531124d702",
+ "65537",
+ "6d30c9d4599aa0b5a2b0176e8563d787e9d4c3f17b6016c8590afbbf3f29186a",
+ "744dfbc11d1aa4baed230bfd6bf110c50db2e8e68a4ecb6b42c4507e7993fafa",
+ "7ff1e0b1c9022b1f06c70b340be044ba641c8718d1708ea650a04b5eb3bd8347",
+ "8081",
+ "8767",
+ "88a35d8dc409c63d70459295112c6a9484f6b14bbff75b3e23965c31f700ef0e",
+ ":",
+ ":app:assembleDevelopmentDebug",
+ ":id/",
+ " (?!Task\\b)|^Caused by:",
+ "\\bkey_[1-4]\\b",
+ "\\bprocess=(\\S+)\\s+reason=(\\d+)\\s",
+ "\\d{3}",
+ "\\x1b\\[[0-9;]*[A-Za-z]",
+ "^",
+ "^(?:(?:>\\s*)?\\d+\\s*\\||\\^|at\\s)",
+ "^(?:ERROR\\b|FATAL ERROR:|(?:\\w*Error):|Unable to resolve module)",
+ "^(?:ERROR\\b|FATAL ERROR:|\\w*Error:|Unable to resolve module)",
+ "^(?:MemTotal|MemAvailable|SwapTotal|SwapFree)\\b",
+ "^(?:error\\b|(?:Syntax|Type|Reference)Error:|Unable to resolve module)",
+ "^(?:oom|oom_kill)\\b",
+ "^(MemTotal|MemAvailable|SwapTotal|SwapFree):\\s+(\\d+) kB$",
+ "^(oom|oom_kill) (\\d+)$",
+ "^BUNDLE\\s",
+ "^Could not ",
+ "^FAILURE:|^A problem occurred|^Execution failed",
+ "^PREBUNDLE\\s",
+ "^[EF]/(AndroidRuntime|ReactNativeJS|ReactNative)\\s*\\(\\s*\\d+\\):\\s*(.*)",
+ "^\\[!\\]",
+ "^\\d+\\s*\\|",
+ "^\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}\\.\\d+\\s+(\\d+)\\s+\\d+\\s+[EF]\\s+[^:]+:\\s*(.*)$",
+ "^\\d{4}-",
+ "^e: ",
+ "__main__",
+ "_bundle",
+ "_metro.cjs",
+ "_test_cases",
+ "a",
+ "absolute",
+ "accepted",
+ "accessibilityText",
+ "account_version_unchanged",
+ "acknowledged_create_responses",
+ "action",
+ "activities",
+ "activity",
+ "adb",
+ "after_sha256",
+ "alive",
+ "allow_control",
+ "allowed_fields",
+ "analytics_auto_collection_enabled",
+ "analytics_collection_deactivated",
+ "android",
+ "android-startup-diagnosis",
+ "android-startup-errors.log",
+ "android/app/build/outputs/apk/development/debug/app-development-debug.apk",
+ "android/app/google-services.json",
+ "androidVersionCode",
+ "android_client_info",
+ "android_errors",
+ "android_runtime_diagnosis",
+ "android_runtime_diagnostic",
+ "android_startup_diagnosis",
+ "android_startup_diagnosis.py",
+ "api_key",
+ "app",
+ "app.json",
+ "app_data_collection_default_enabled",
+ "app_id",
+ "app_settings",
+ "application/json",
+ "archived_only_key_semantics",
+ "archived_only_mobile_logically_archived",
+ "archived_signer_record_retention_ui",
+ "archived_vault_reinstated_after_cold_restart",
+ "arm",
+ "arm64",
+ "armed",
+ "artifact_policy",
+ "artifacts",
+ "ascii",
+ "assertWalletAccount",
+ "assertion failed",
+ "attributes",
+ "attribution",
+ "babel.config.js",
+ "backend",
+ "backend_compatibility",
+ "backup_service_removed_after_verified_restore",
+ "base.apk",
+ "before_dependencies",
+ "before_native_build",
+ "before_sha256",
+ "bin/maestro",
+ "binary",
+ "boot",
+ "bootstatus",
+ "brief",
+ "browser",
+ "browserify",
+ "btn_AppSettingsIcon",
+ "btn_skip",
+ "build",
+ "build-tools/35.0.0",
+ "build-tools;35.0.0",
+ "built_artifact",
+ "bundle_build_done",
+ "bundle_build_failed",
+ "bundle_build_started",
+ "bundle_marker_count",
+ "bundle_marker_observed",
+ "bundle_tree_sha256",
+ "bundling_error",
+ "bytes",
+ "bytes_appended",
+ "bytes_observed",
+ "bytes_read",
+ "bytes_scanned",
+ "c64954ef892c8782324afcda57f69e510bab33649a47baaf702daf51eeae919a",
+ "cache_read_error",
+ "cache_write_error",
+ "cancel_tapped",
+ "cancel_visible",
+ "cancelled_confirmation_preserved_key",
+ "capture",
+ "capture_output",
+ "catalyst_redbox_title",
+ "categories",
+ "category_record_counts",
+ "cause",
+ "cgroup",
+ "check",
+ "children",
+ "classified_error_records",
+ "cleanup",
+ "cleanup_errors",
+ "cleanup_failure_categories",
+ "cleanup_failure_category",
+ "cleanup_failure_stages",
+ "cleanup_status",
+ "clear",
+ "clearVerifiedRemoteRevision",
+ "cli-2.11.0",
+ "client",
+ "client_info",
+ "cocoapods",
+ "cold_relaunch_to_authenticated_home_ms",
+ "cold_relaunch_to_login_ms",
+ "cold_wrong_login_pin_rejected",
+ "collection_error_types",
+ "collection_errors",
+ "collector",
+ "com.apple.CoreSimulator.SimDeviceType.iPhone-16",
+ "com.apple.CoreSimulator.SimRuntime.iOS-18-5",
+ "command",
+ "command not found",
+ "command-%03d.log",
+ "commands",
+ "compact",
+ "companion_metro_switches",
+ "compileSdk=36; buildTools=35.0.0; NDK=27.1.12297006",
+ "complete",
+ "complete_lines",
+ "completed_markers",
+ "completed_stages",
+ "configuration",
+ "configuration_overlays",
+ "configuration_version",
+ "confirmPIN",
+ "confirm_passcode",
+ "confirm_passcode_visible",
+ "confirmation_digits_tapped",
+ "continue_tapped",
+ "continue_visible",
+ "controlled-transport-no-backend-acceptance",
+ "controlled_disconnect_retry",
+ "could not find compatible versions",
+ "count_scope",
+ "counts",
+ "coverage",
+ "crash",
+ "create",
+ "createPIN",
+ "create_new_app_calls",
+ "create_passcode",
+ "create_tapped",
+ "created",
+ "credential-ui",
+ "credential_error",
+ "credential_errors_ui",
+ "credential_fixture.yaml",
+ "credential_metro.cjs",
+ "credential_store_read_fault",
+ "credentials_exported",
+ "curl",
+ "currentBackupAccountSession",
+ "currentBackupAppId",
+ "currentWalletAccountId",
+ "current_key",
+ "cwd",
+ "d",
+ "daemon",
+ "data",
+ "data/Containers/Bundle/Application",
+ "db",
+ "debug",
+ "default",
+ "delete",
+ "deleteAppImageEntityWorker",
+ "deleteSigningDeviceWorker",
+ "delete_confirmation_scoped",
+ "deletion_persisted_after_relaunch",
+ "dev",
+ "developmentServerError",
+ "device",
+ "device_",
+ "device_uninstall",
+ "df",
+ "diagnostic",
+ "diagnostic_only",
+ "diagnostics",
+ "diff",
+ "diff_sha256",
+ "dir",
+ "directory",
+ "disabled",
+ "disk_preflight",
+ "dismiss_control",
+ "dont_allow_control",
+ "driver",
+ "driver_preflight",
+ "driver_startup_timeout",
+ "dumpsys",
+ "duration_seconds",
+ "e",
+ "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
+ "e867f5ec8e96a16afc83d2c355f798b292e2335c0e97591fc7521bf68c5fe726",
+ "ef18f4962decfa11fb69825ff7b983fd086c243b5d2bbe4ed55f6aa5a4a68169",
+ "element not found",
+ "empty_current_observation_count",
+ "empty_deletion_entry_verified",
+ "empty_first_ui",
+ "empty_repeat_ui",
+ "emulator",
+ "emulator-",
+ "emulator-5554",
+ "emulator-[0-9]+",
+ "emulator-\\d+",
+ "emulator/source.properties",
+ "engine",
+ "entrypoint",
+ "entrypoint_under_test",
+ "env",
+ "er",
+ "error",
+ "error_details",
+ "error_headers",
+ "error_records",
+ "error_type",
+ "errors",
+ "event",
+ "evidence-save",
+ "exception_types",
+ "excludeSource",
+ "exec-out",
+ "executable",
+ "executable_sha256",
+ "exist_ok",
+ "existing_disposable_home_verified",
+ "exit-history",
+ "exit-info",
+ "exit_code",
+ "exit_history",
+ "expected_emulator_target",
+ "expected_installed_build",
+ "expected_installed_version",
+ "expected_sdk_build",
+ "export_row_limit",
+ "export_truncated",
+ "exported_rows",
+ "f",
+ "facts",
+ "failed_commands",
+ "failed_phase",
+ "failed_selector",
+ "failure",
+ "failure_category",
+ "failure_kind",
+ "failure_observation",
+ "failures",
+ "fault",
+ "fault_categories",
+ "features",
+ "features-junit.xml",
+ "features_bundle",
+ "file",
+ "files/",
+ "final_visible_wallet_composition",
+ "final_visible_wallet_count",
+ "final_wallet_verified",
+ "firebase.json",
+ "fixture_phases",
+ "fixture_scope",
+ "flags",
+ "flush",
+ "foreground",
+ "foreground_activity",
+ "format",
+ "free_bytes",
+ "fresh_disposable_state",
+ "freshness",
+ "ft",
+ "gem",
+ "generic/platform=iOS Simulator",
+ "get-serialno",
+ "getAccountFromSigner",
+ "getKeyUID",
+ "get_app_container",
+ "getprop",
+ "git",
+ "github-hosted",
+ "google/sdk_gphone64_x86_64/emu64xa:15/AE3A.240806.043/12960925:userdebug/dev-keys",
+ "gradle",
+ "growth_detected",
+ "handleHostException|ReactNoCrashSoftException|Exception in native call",
+ "hardware",
+ "hardware_device_checks",
+ "has not been registered",
+ "head",
+ "hermes",
+ "hermes.*(?:exception|fatal|error|failed)|(?:exception|fatal|error).*hermes",
+ "hexa_keeper_dev",
+ "hidden_reference_blocks_without_name_after_relaunch",
+ "hidden_reference_ui",
+ "hierarchy",
+ "hierarchy_signals",
+ "history-ui",
+ "history_",
+ "history_fixture.yaml",
+ "history_product.yaml",
+ "history_regex",
+ "history_restore",
+ "history_seed_empty",
+ "history_seed_stale",
+ "history_verify_empty_first",
+ "history_verify_empty_repeat",
+ "history_verify_restored",
+ "history_verify_stale_first",
+ "history_verify_stale_repeat",
+ "hmr_client_error",
+ "home_ready",
+ "host_memory",
+ "host_port_unavailable",
+ "hosted_native",
+ "hosted_native.py",
+ "http://127.0.0.1:8081/index.bundle?platform=%s&dev=true&minify=false",
+ "http://127.0.0.1:8081/index.bundle?platform=android&dev=true&minify=false",
+ "http://127.0.0.1:8081/status",
+ "http://127.0.0.1:8765/",
+ "http_status",
+ "https://127.0.0.1:9/",
+ "https://github.com/mobile-dev-inc/Maestro/releases/download/%s/maestro.zip",
+ "https://github.com/mobile-dev-inc/Maestro/releases/download/cli-2.11.0/maestro.zip",
+ "https://public@127.0.0.1:9/1",
+ "i",
+ "iOS 18.5",
+ "iOS driver not ready in time, consider increasing timeout by configuring MAESTRO_DRIVER_STARTUP_TIMEOUT env variable",
+ "iPhone 16",
+ "iPhone 16; iOS 18.5",
+ "id",
+ "id: ",
+ "ignore_errors",
+ "image",
+ "indent",
+ "index.js",
+ "info",
+ "initial",
+ "initialize_failed",
+ "injected-dispatch-selection-no-login-acceptance",
+ "input_truncated",
+ "install",
+ "install_diagnosis",
+ "install_diagnosis.py",
+ "install_succeeded",
+ "installed-artifact-",
+ "installed_artifact",
+ "installed_artifact_scope",
+ "installed_artifact_verified",
+ "installed_regex",
+ "installed_version_header_and_initial_history",
+ "invalid_records",
+ "invalid_rows",
+ "inventory_sha256",
+ "io.hexawallet.hexakeeper.dev",
+ "io.hexawallet.keeper",
+ "io.hexawallet.keeper.development",
+ "io.hexawallet.keeper.development:id/",
+ "ios",
+ "ios-startup-errors-stderr.log",
+ "ios-startup-errors.log",
+ "ios/GoogleService-Info.plist",
+ "ios/GoogleServices/dev/GoogleService-Info.plist",
+ "ios/Podfile.lock",
+ "ios/hexa_keeper.xcworkspace",
+ "iosBuildNumber",
+ "ios_errors",
+ "ios_simulator_architecture",
+ "iphonesimulator",
+ "iteration",
+ "java",
+ "jsc",
+ "junit",
+ "junit.xml",
+ "keeper-disposable-ci",
+ "keeper-native-private",
+ "keeper-product-ui-",
+ "keeper-r5-native-evidence.json",
+ "key-ui",
+ "key_1",
+ "key_2",
+ "key_3",
+ "key_4",
+ "key_management_entry_and_exit",
+ "key_management_entry_verified",
+ "key_management_scope",
+ "key_management_ui",
+ "keychain",
+ "kind",
+ "label",
+ "launch_window_started_ms",
+ "lazy",
+ "limit",
+ "limits",
+ "line_scan_limit",
+ "line_scan_truncated",
+ "lines_scanned",
+ "link",
+ "ln",
+ "loading",
+ "lockfile needs to be updated",
+ "lockfile needs to be updated|could not find compatible versions|^The sandbox is not in sync",
+ "log",
+ "log_limit_reached",
+ "logbox_controls",
+ "logbox_counter",
+ "logbox_error_header",
+ "logbox_syntax_footer",
+ "logbox_warning_header",
+ "logcat",
+ "login",
+ "logs_read",
+ "lookup_status",
+ "maestro",
+ "maestro-output",
+ "maestro-preflight-state",
+ "maestro.zip",
+ "maestro/tests",
+ "maestro_preflight",
+ "main",
+ "malformed_cold_start_blocked",
+ "malformed_record_lines",
+ "malformed_startup_blocked",
+ "marker",
+ "matching_process_count",
+ "matching_process_records",
+ "matching_records",
+ "max",
+ "measurements",
+ "meminfo",
+ "memory.current",
+ "memory.events",
+ "memory.max",
+ "message",
+ "messaging_auto_init_enabled",
+ "metadata",
+ "metadata.json",
+ "method",
+ "metro",
+ "metro-%02d.log",
+ "metro.config.js",
+ "metro.log",
+ "metro_errors",
+ "metro_output",
+ "metro_process",
+ "metro_progress",
+ "metro_warmup",
+ "minify",
+ "minimize_control",
+ "minimum_free_bytes",
+ "missing_ok",
+ "mkdir",
+ "mobile_key_origin",
+ "mobilesdk_app_id",
+ "mode",
+ "modulesOnly",
+ "more_wallets_navigation",
+ "names",
+ "native",
+ "native-worker-process-relaunch-counts",
+ "native_credential_api",
+ "native_mobile_and_public_seed_created",
+ "native_private_material_exactness",
+ "native_probe",
+ "native_probe_test_cases",
+ "navigation_verified",
+ "ndk/27.1.12297006",
+ "ndk;27.1.12297006",
+ "network",
+ "network_scope",
+ "new_account_requests_during_credential_flow",
+ "new_account_requests_during_history_flow",
+ "new_account_requests_during_key_flow",
+ "new_account_requests_during_vault_flow",
+ "next_marker",
+ "no space left on device",
+ "no-product-ui-navigation-pin-or-biometric-acceptance",
+ "noScriptURL",
+ "node",
+ "node_count",
+ "node_modules/.bin/patch-package",
+ "node_modules/react-native/cli.js",
+ "nodeify_overlay",
+ "notification_permission_controls",
+ "notification_prompt_phrase",
+ "npm",
+ "object_pairs_hook",
+ "observation_state",
+ "observeBackupAccount",
+ "observed_android_sdk",
+ "observed_error_headers",
+ "onboarding_skip",
+ "openiap",
+ "openjdk version \"17.0.20.1\" 2026-08-18\nOpenJDK Runtime Environment Temurin-17.0.20.1+1 (build 17.0.20.1+1)\nOpenJDK 64-Bit Server VM Temurin-17.0.20.1+1 (build 17.0.20.1+1, mixed mode, sharing)",
+ "options",
+ "original_credential_exported",
+ "original_history_restored",
+ "os",
+ "os_keychain_denial_or_hardware_read_fault",
+ "other_backend_calls_rejected",
+ "out of memory|heap limit|heap out of memory",
+ "outer_http_status",
+ "oversized_record_lines",
+ "own_app_resumed",
+ "own_error_records",
+ "package.json",
+ "package:(/data/app/(?:~~[A-Za-z0-9_=-]+/)?",
+ "package_name",
+ "parents",
+ "parse_constant",
+ "parse_error",
+ "parse_error_types",
+ "parse_status",
+ "parsed_error_records",
+ "parsed_records",
+ "partial_end",
+ "partial_start",
+ "pass",
+ "passed",
+ "path",
+ "performance_sample",
+ "performance_scope",
+ "phase",
+ "physical_biometrics",
+ "physical_devices",
+ "pid",
+ "pidof",
+ "pin_onboarding_progress",
+ "platform",
+ "platforms/android-36",
+ "platforms;android-36",
+ "please wait",
+ "pm",
+ "pod",
+ "prebuilt_driver_selected",
+ "prebundle_marker_count",
+ "predecessor_fixture_verified",
+ "prefix",
+ "prepare",
+ "private-output",
+ "private_",
+ "private_startup-foreground",
+ "private_startup-logcat",
+ "private_startup-observer",
+ "probe",
+ "probe-and-worker-timings-not-product-startup-ux",
+ "probe-junit.xml",
+ "probe_bundle",
+ "probe_diagnostics",
+ "probe_ready_ms",
+ "probe_scope",
+ "proc/meminfo",
+ "process",
+ "process == \"%s\" AND (messageType == \"error\" OR messageType == \"fault\" OR eventMessage CONTAINS[c] \"error\" OR eventMessage CONTAINS[c] \"exception\" OR eventMessage CONTAINS[c] \"fatal\")",
+ "process_state",
+ "processes",
+ "producer_limit_may_be_reached",
+ "producer_row_limit",
+ "product",
+ "product_android_failure_diagnosis",
+ "product_credential_acceptance",
+ "product_credential_blocked.yaml",
+ "product_credential_recovered.yaml",
+ "product_credential_ui",
+ "product_entrypoint",
+ "product_failure_diagnosis",
+ "product_first_wallet.yaml",
+ "product_history_acceptance",
+ "product_key_acceptance",
+ "product_key_acceptance.py",
+ "product_key_acceptance.yaml",
+ "product_key_ui",
+ "product_measurements",
+ "product_measurements.py",
+ "product_metro",
+ "product_retry.yaml",
+ "product_ui",
+ "product_ui_",
+ "product_vault_acceptance",
+ "product_vault_acceptance.yaml",
+ "product_vault_ui",
+ "product_version_history_ui",
+ "production-deletion-native-rollback",
+ "production-deletion-retained-native-references",
+ "production-setup-offline-retry-native-counts",
+ "production-worker-native-storage",
+ "production-worker-stale-session-rejection",
+ "profile",
+ "project_id",
+ "project_info",
+ "project_number",
+ "protected_backup",
+ "protected_backup_deletion",
+ "ps",
+ "pull",
+ "query_status",
+ "r5_feature_evidence",
+ "r5_features",
+ "r5_features_test_cases",
+ "r5_release_acceptance",
+ "raw_durations",
+ "rb",
+ "react-native",
+ "react-native-keychain",
+ "react-native.config.js",
+ "read",
+ "read_scope",
+ "real_two_of_two_vault_created",
+ "reason_categories",
+ "record",
+ "record_limit_reached",
+ "recover_tile",
+ "recovery_key_preservation",
+ "redacted_tool_errors",
+ "redbox-dismiss",
+ "redbox-error",
+ "redbox-reload",
+ "redbox_resource",
+ "referenced_vault_ui",
+ "rejected_snapshots",
+ "relation",
+ "relaunch_home",
+ "relaunch_login",
+ "relaunch_start",
+ "release/version.json",
+ "release_readiness",
+ "repeat_login_observation_date_unchanged",
+ "replace",
+ "replacement_character_observed",
+ "report",
+ "request",
+ "requested_device_disconnected",
+ "requested_samples",
+ "requires a higher minimum deployment target",
+ "reset",
+ "resource-id",
+ "restore",
+ "restored",
+ "restored_cold_wallet_preserved",
+ "restored_login_available",
+ "restored_wallet_preserved",
+ "result",
+ "retained_mobile_key_is_protected_again",
+ "retry",
+ "retry_error_visible",
+ "retry_fixture_start",
+ "retry_home_ready",
+ "retry_relaunch_home",
+ "retry_relaunch_login",
+ "retry_relaunch_start",
+ "retry_remains_blocked",
+ "retry_scope",
+ "retry_submit",
+ "rev-parse",
+ "reverse",
+ "rn_redbox_dismiss_button",
+ "rn_redbox_reload_button",
+ "rn_redbox_stack",
+ "ro.build.fingerprint",
+ "rows",
+ "run",
+ "run-as",
+ "runModule",
+ "run_attempt",
+ "run_id",
+ "runner",
+ "runner_install_launch_returned",
+ "runner_install_started",
+ "runtime",
+ "runtime-errors",
+ "runtime_errors",
+ "same_process_retry_after_external_repair",
+ "sample",
+ "sample-%d",
+ "samples",
+ "save",
+ "scan_limit_reached",
+ "scanned_error_context_lines",
+ "scenario",
+ "scenarios",
+ "schema",
+ "scope",
+ "sdk",
+ "sdkmanager",
+ "seed_fixture_origin",
+ "server-close",
+ "server-shutdown",
+ "setupKeeperAppWorker",
+ "setup_first_wallet_ms",
+ "severity",
+ "sha256",
+ "shell",
+ "shim.js",
+ "show",
+ "shutdown",
+ "signing",
+ "simctl",
+ "simctl create did not return an owned simulator UUID.",
+ "simulator_readiness",
+ "simulator_readiness.py",
+ "skip_tapped",
+ "skip_visible",
+ "skipped",
+ "smoke",
+ "smoke-junit.xml",
+ "smoke_scope",
+ "smoke_test_cases",
+ "snapshot_count",
+ "snapshot_limit_exceeded",
+ "sort_keys",
+ "source",
+ "source.properties",
+ "sourcePaths",
+ "source_functions",
+ "source_sha",
+ "spawn",
+ "src",
+ "src/services/backup/transport.ts",
+ "src/store/sagas/bhr.ts",
+ "src/store/sagas/storage.ts",
+ "src/store/sagas/wallets.ts",
+ "src/utils/utilities.ts",
+ "stage",
+ "stage_evidence",
+ "stale_current_observation_count",
+ "stale_first_ui",
+ "stale_initial_and_recovery_dates_preserved",
+ "stale_repeat_ui",
+ "start",
+ "start_new_session",
+ "start_new_text",
+ "start_new_tile",
+ "start_new_to_home_ms",
+ "start_new_to_ready_ms",
+ "start_new_visible",
+ "startup",
+ "startup-foreground.log",
+ "startup-logcat.log",
+ "startup-observer.jsonl",
+ "startup_capture",
+ "startup_cleanup_errors",
+ "startup_diagnosis",
+ "startup_diagnosis.py",
+ "startup_diagnostics",
+ "startup_observation",
+ "startup_observation_capture",
+ "startup_observation_cleanup",
+ "startup_ready",
+ "startup_start",
+ "startup_timing_scope",
+ "startup_to_passcode_ms",
+ "state",
+ "status",
+ "status_check_failed",
+ "status_check_started",
+ "status_response_received",
+ "stderr",
+ "stdout",
+ "strict",
+ "successfully_empty_store",
+ "sudo",
+ "synthetic-wallet-generation-no-crypto-acceptance",
+ "sys/fs/cgroup",
+ "system",
+ "target",
+ "tcp:",
+ "tcp:8081",
+ "tcp:8765",
+ "tcp:8767",
+ "test",
+ "testcase",
+ "testcase_failures",
+ "testcase_statuses",
+ "testsuite",
+ "testsuites",
+ "text",
+ "threadtime",
+ "time_ms",
+ "timeout",
+ "timeout_seconds",
+ "timestamp",
+ "title",
+ "toolchain",
+ "transformer_load_failed",
+ "transport_requests_dropped_without_commit",
+ "true",
+ "truncated_logs",
+ "tsconfig.json",
+ "ubuntu24",
+ "ui test runner does not exist",
+ "ui_test_runner_missing",
+ "unableLoadScript",
+ "unclassified_error_context_lines",
+ "unclassified_error_headers",
+ "unclassified_error_records",
+ "unclassified_own_error_records",
+ "unexpected_create_attempts",
+ "uninstall",
+ "unknown:BridgelessReact:V",
+ "unknown:ReactHost:V",
+ "unknown:ReactNative:V",
+ "unparsed_nonempty_lines",
+ "unparsed_records",
+ "unrelated_mobile_wallet_retained",
+ "unrelated_visible_wallet_count_after_relaunch",
+ "unrelated_wallet_preserved",
+ "unrelated_wallet_preserved_final_count_three",
+ "unused_mobile_key_created",
+ "unused_mobile_key_deleted",
+ "unzip",
+ "update",
+ "url",
+ "url-server",
+ "utf-8",
+ "utf-8-sig",
+ "v22.23.3",
+ "valid_records",
+ "valid_rows_in_scanned_input",
+ "value",
+ "vault-ui",
+ "vault_references_ui",
+ "vault_unhidden_with_correct_native_pin",
+ "version",
+ "version_history_scope",
+ "version_history_ui",
+ "version_history_verified",
+ "view_recoverTile",
+ "view_startNewTile",
+ "visible_eligible_keys_after_deletion",
+ "visible_reference_blocks_mobile_deletion",
+ "visible_reference_ui",
+ "visible_wallet_count",
+ "visible_wallet_count_after_recovery_and_cold_login",
+ "visible_wallet_count_after_relaunch",
+ "visible_wallet_count_before_relaunch",
+ "wallet_ready",
+ "wallet_start",
+ "wb",
+ "welcome",
+ "welcome_back",
+ "worker_stderr_chunk",
+ "workflow_ref",
+ "workflow_sha",
+ "would like to send you notifications",
+ "wrong_deletion_pin_rejected",
+ "x86_64",
+ "xb",
+ "xcode",
+ "xcode_test_execute_failed",
+ "xcode_test_failed",
+ "xcode_testing_failed",
+ "xcodebuild",
+ "xcodebuild_driver_selected",
+ "xcrun",
+ "xctestrun config does not exist",
+ "xctestrun_config_missing",
+ "yarn",
+ "yarn.lock",
+ "yarn@1.22.22",
+ "zero_balance_rotation_retained_original_archive",
+ "\ufffd"
+ ],
+ "source_sha": "1bc34890cb8618b2fffd446a63924974e0fe15b5"
+}
diff --git a/.github/scripts/current-ios-metadata-policy.json b/.github/scripts/current-ios-metadata-policy.json
new file mode 100644
index 0000000000..fa79db43db
--- /dev/null
+++ b/.github/scripts/current-ios-metadata-policy.json
@@ -0,0 +1,1253 @@
+{
+ "historical_metadata_sha256": "b0d8b6c6bbec9ef6dd4eb71f0c4f5d90a66086ee5bbb9bbf23163b8c95429923",
+ "producer_sha256": {
+ ".github/native/hosted_native.py": "d3079b1ebb92a5bde93f49fbe8bd1c22297eb9d5751588077d80fe60117a67ed",
+ ".github/native/install_diagnosis.py": "b34697a12e82b101f2face151dc7ab90758f87505706a9de4911e0e530ee6cde",
+ ".github/native/simulator_readiness.py": "ddc8dfa4d2099d1dfffd92bef55160fb60fe7e0e275b53d2d25f1816453c789f",
+ ".github/native/startup_diagnosis.py": "1d38c3dbc9feaa9b38702104b65b54f6d6a641cf24a9458238e9604c82da893a"
+ },
+ "public_literals": [
+ "\t",
+ "\n",
+ "\r",
+ " is not available",
+ " was requested, but it is not connected.",
+ "\"",
+ "%s failed (exit %s). %s",
+ "%s-development-warmup.bundle",
+ "%{http_code}",
+ "(?:FATAL EXCEPTION|Caused by:|\\b[\\w.$]*(?:Exception|Error)\\b|Invariant Violation|Unable to load script|Could not)",
+ "(?:\\b(?:error|exception|fatal)\\b|\\b[\\w.$]*(?:Exception|Error)\\b)",
+ "(?:^|[/\\s])simctl\\s+install\\s+",
+ "(?:container|containermanager).*\\b(?:error|failed|unavailable)\\b",
+ "(?:install coordination|IXCoordinator|IXSClient|IXClient)",
+ "(?\\d{4}-\\d{2}-\\d{2}[ T]\\d{2}:\\d{2}:\\d{2}(?:\\.\\d{1,9})?(?:[+-]\\d{2}:?\\d{2}|Z)?)\\s+(?P[A-Za-z]+)\\s+(?P[A-Za-z0-9_.-]{1,128})\\[(?P[1-9]\\d{0,9}):(?:0x)?[A-Fa-f0-9]{1,16}\\]\\s+(?P.*)",
+ "(process == \"CoreSimulatorService\" OR process == \"simctl\") AND eventMessage CONTAINS \"",
+ "*",
+ "** TEST EXECUTE FAILED **",
+ "** TEST FAILED **",
+ "**/maestro.log",
+ "**/screen-hierarchy/step-*.json",
+ "**/xctest_runner_*.log",
+ "*:S",
+ "+00:00",
+ "-",
+ "--",
+ "--config",
+ "--custom-log-reporter-path",
+ "--debug-output",
+ "--deployment",
+ "--device",
+ "--env",
+ "--error-on-fail",
+ "--exit-code",
+ "--fail",
+ "--flatten-debug-output",
+ "--format",
+ "--frozen-lockfile",
+ "--global",
+ "--ignore-scripts",
+ "--last",
+ "--location",
+ "--max-time",
+ "--max-workers=2",
+ "--no-daemon",
+ "--no-document",
+ "--no-repo-update",
+ "--non-interactive",
+ "--output",
+ "--platform",
+ "--port",
+ "--predicate",
+ "--sdk",
+ "--show-error",
+ "--show-sdk-version",
+ "--silent",
+ "--style",
+ "--test-output-dir",
+ "--version",
+ "--write-out",
+ "-PreactNativeArchitectures=x86_64",
+ "-T",
+ "-[A-Za-z0-9_=-]+/base\\.apk)",
+ "-axo",
+ "-b",
+ "-c",
+ "-configuration",
+ "-d",
+ "-derivedDataPath",
+ "-destination",
+ "-file",
+ "-install.sample",
+ "-p",
+ "-q",
+ "-r",
+ "-s",
+ "-scheme",
+ "-sdk",
+ "-sf",
+ "-t",
+ "-v",
+ "-version",
+ "-workspace",
+ ".",
+ "./gradlew",
+ ".env.ci",
+ ".github/native/nodeify.cjs",
+ ".github/native/r5_features.yaml",
+ ".github/native/r5_metro.cjs",
+ ".github/native/r5_prepare.cjs",
+ ".github/native/release_metro.cjs",
+ ".github/native/release_probe.yaml",
+ ".github/native/startup.yaml",
+ ".github/native/startup_observer.cjs",
+ ".github/native/startup_reporter.cjs",
+ ".log",
+ "/Users/runner/hostedtoolcache/node/22.23.3/arm64/bin/node",
+ "/Users/runner/work/_temp/keeper-native-private/DerivedData",
+ "/Users/runner/work/_temp/keeper-native-private/DerivedData/Build/Products/Debug-iphonesimulator/hexa_keeper_dev.app",
+ "/Users/runner/work/_temp/keeper-native-private/ios-development-warmup.bundle",
+ "/Users/runner/work/_temp/keeper-native-private/maestro",
+ "/Users/runner/work/_temp/keeper-native-private/maestro-output",
+ "/Users/runner/work/_temp/keeper-native-private/maestro.zip",
+ "/Users/runner/work/_temp/keeper-native-private/maestro/maestro/bin/maestro",
+ "/Users/runner/work/_temp/keeper-native-private/smoke-junit.xml",
+ "/opt/homebrew/bin",
+ "/opt/homebrew/bin/node",
+ "0",
+ "0497b2aaeb76372a6f21721f28ebd42ec2877155a090580b23ace2e017fab6a8",
+ "1",
+ "1.16.2",
+ "10m",
+ "120",
+ "123456789012",
+ "18.5",
+ "1:123456789012:android:0000000000000000",
+ "1:123456789012:ios:0000000000000000000000",
+ "1f084ee4486709e0066034a452349df897eb2434",
+ "200",
+ "20260907.0337.1",
+ "22ef01b796c2fd1dfd29553915ba10c99f89f0212f82aca052cd74a73e38e59d",
+ "23f14e01f3437c213f1443c3167d96022f3a43bc",
+ "240",
+ "2576e14246d1a52bc122edd56925603c20cad3e51c563f1ca01752d53185025c",
+ "3",
+ "300",
+ "39846002094",
+ "3m",
+ "437e920b9dd0015fdd6d283dd037a63178bfcde8a1599d3620bb4266d8345127",
+ "4f19863902bad018cb0e75a32eece966a93d589f1946adcd2cecb4179e9725f3",
+ "5384593cb4e7a106489e75a821d157dd43f4e438df6bc308b72e82c685e1283a",
+ "65537",
+ "6d30c9d4599aa0b5a2b0176e8563d787e9d4c3f17b6016c8590afbbf3f29186a",
+ "71335e478813602f32c1d51df317913e1cf68e12aba5977be99d00956065413d",
+ "7c09ba8d5ff1dd2168b9b6101a91e9881a4abcb2365331df0780ee1280c019e7",
+ "8081",
+ "8560AC52-E179-4A94-A071-52E85351EAF4",
+ "858409cf396536ebdf30850c46f3a2481ff1f141733817d57c0662e68d05d4e1",
+ "89f43f0d5907d8e45f260156238b3cb433076c84c3dee2dd4884b456e438629c",
+ "99414832-4502-4DCD-A80E-4DC9D6B458C7",
+ "9f56fca152030dba9e8ee76dee4fc8967ab667507b5878f0f9ab819d55b6b9a6",
+ ":app:assembleDevelopmentDebug",
+ ":id/",
+ "=",
+ "A pod requires a higher iOS deployment target.",
+ "A required native tool is unavailable.",
+ "A successful native build is required before smoke testing.",
+ "AFTER_INSTALL_COMMAND",
+ "AIzaSy",
+ "ANDROID",
+ "ANDROID_HOME",
+ "ANDROID_RUNTIME_ERROR",
+ "ANDROID_SDK_ROOT",
+ "ANR in ",
+ "API_KEY",
+ "APP_ANR",
+ "APP_ID=",
+ "APP_ID=io.hexawallet.hexakeeper.dev",
+ "APP_WINDOW",
+ "ARCHS=",
+ "ARCHS=arm64",
+ "ARM64",
+ "ATS_BLOCKED",
+ "ActivityManager:V",
+ "ActivityRecord\\{.*?\\bu\\d+\\s+([A-Za-z0-9_.]+)/[^\\s}]+",
+ "ActivityTaskManager:V",
+ "AmbiguousModuleResolutionError",
+ "Android API 35; google_apis; x86_64; pixel_6",
+ "Android SDK component %s has no Pkg.Revision metadata.",
+ "AndroidRuntime",
+ "AndroidRuntime:E",
+ "AndroidRuntime:V",
+ "AndroidVersion.ApiLevel",
+ "App Transport Security.*(?:blocked|requires)|NSURLErrorDomain.*-1022\\b",
+ "App launch NOT RUN; no owned device.",
+ "Apply committed Node compatibility whitelist without installing dependencies",
+ "Apply repository dependency patches",
+ "Assert",
+ "Assert R5 production workers over native storage",
+ "Assert native persistence across process launches",
+ "Assert startup and disposable passcode transition",
+ "Assertion is false:",
+ "Attest owned installed bytes, never installation argv or app assertions.",
+ "BEFORE_APP",
+ "BOUNDED_INPUT_ONLY",
+ "BUILD",
+ "BUILD_FAILURE",
+ "BUNDLE_DOWNLOAD_FAILED",
+ "BUNDLE_ID",
+ "BUNDLE_LOAD",
+ "BUNDLE_VALIDATION_FAILED",
+ "Boot completion alone did not establish app-service responsiveness.",
+ "Boot disposable simulator",
+ "Boot owned driver-preflight simulator",
+ "Bound cold development bundling before starting either disposable app.",
+ "Bounded cold development bundle/startup allowance; no release performance acceptance.",
+ "Bounded install diagnostics could not be saved.",
+ "Bounded read-only readiness for the simulator app-service query surface.\n\nA completed simulator boot does not establish that listapps can respond. This\ngate requires its successful exit before the caller starts installation or the\ndriver. It retries only that read-only query; no output, app/driver operation,\nfrontend launch or service configuration is retained or changed here.\n",
+ "Bounded startup diagnostics: ",
+ "Build debug-key-only development APK",
+ "Build unsigned development simulator app",
+ "Built artifact changed before the disposable startup smoke.",
+ "Built artifact changed during installed comparison.",
+ "Built artifact changed during native execution.",
+ "Bundle entry escaped app.",
+ "CFBundleExecutable",
+ "CFBundleIdentifier",
+ "CI-only Metro entrypoint; actual encrypted Realm/current schemas and production MMKV; three process launches, rollback, wrong-key rejection, targeted primitive deletion, separate database files and cleanup. NOT app key deletion, account isolation, setup/recovery or release performance acceptance.",
+ "CLEARTEXT communication.*not permitted",
+ "CLEARTEXT_BLOCKED",
+ "COCOA",
+ "COCOAPODS_ERROR",
+ "CODE_SIGNING_ALLOWED=NO",
+ "CODE_SIGNING_REQUIRED=NO",
+ "CONNECTION",
+ "CONNECTION_FAILED",
+ "CONTAINER_SERVICE",
+ "CONTAINER_SERVICE_FAILED",
+ "CORE_SIMULATOR",
+ "Call context.command once with the original install argv and deadline.\n\n Missing observation persistence blocks this diagnostic path after an install\n succeeds. It cannot replace an original install exception or grant UI credit.\n ",
+ "Check disposable iOS driver readiness",
+ "Checkout does not match the exact requested PR head.",
+ "Classify fixed public startup selectors; never export hierarchy content.",
+ "Classify observed tool failures; never return any part of a log line.\n\n Redaction cannot recognize arbitrary wallet, user or application text. Each\n result must come from this fixed vocabulary, including the fallback.\n ",
+ "Clear state",
+ "CliError",
+ "Collect bounded diagnostics before destroying this job's fresh app state.",
+ "Confirm your passcode",
+ "Connect emulator to Metro",
+ "Connect existing Xcode Node path to pinned Node",
+ "ConnectException",
+ "Console Error",
+ "Console Warning",
+ "CoreSimulator|SimDevice|SimServiceContext",
+ "Could not connect to development server.",
+ "Create a passcode",
+ "Create fresh iPhone 16 iOS 18.5 simulator",
+ "Create owned driver-preflight simulator",
+ "DEPENDENCY_LOCK_MISMATCH",
+ "DEPENDENCY_OR_TOOL_FAILURE",
+ "DEVICE_NOT_BOOTED",
+ "DISK_SPACE_EXHAUSTED",
+ "DISPATCH_WAIT",
+ "DRIVER PREFLIGHT/setup only; no app build, install or UI credit.",
+ "DURING_INSTALL",
+ "Debug",
+ "DebugServerException|Unable to load script|development server returned response error|Could not connect to development server",
+ "DerivedData",
+ "DerivedData/Build/Products/Debug-iphonesimulator/hexa_keeper_dev.app",
+ "Development bundle setup only; not native or UI evidence.",
+ "Development bundle warmup did not return a nonempty HTTP 200 body.",
+ "Dismiss",
+ "Disposable hosted smoke harness; only allowlisted metadata leaves the runner.\n\nNative and Maestro output stays under RUNNER_TEMP, never in an uploaded glob.\nThe gate trusts protected workflow/job provenance, never this writable artifact.\n",
+ "Documents",
+ "Domain\\s*=\\s*",
+ "Download pinned Maestro",
+ "Driver-preflight receipt failed.",
+ "ECONNREFUSED|Connection refused|NSURLErrorDomain.*-(?:1001|1003|1004|1009)\\b|The Internet connection appears to be offline",
+ "ECONNREFUSED|Connection refused|SocketTimeoutException",
+ "ENTRY_BUNDLE",
+ "ENVFILE",
+ "ENVIRONMENT=DEVELOPMENT\nRELAY=http://127.0.0.1:8765/\nSIGNING_SERVER_TESTNET=https://127.0.0.1:9/\nSIGNING_SERVER_MAINNET=https://127.0.0.1:9/\nCHANNEL_URL=https://127.0.0.1:9/\nSENTRY_DNS=https://public@127.0.0.1:9/1\nENC_KEY_STORAGE_IDENTIFIER=KEEPER-HOSTED-DISPOSABLE\n",
+ "ERROR",
+ "EXPECTED",
+ "Element not found:",
+ "Enter your passcode",
+ "Expected a hosted platform and record|prepare|driver|build|smoke|probe|features.",
+ "Expected a positive readiness window of at most 120 seconds.",
+ "Expected an owned simulator UUID.",
+ "Expected compact log text.",
+ "Expected finite host load observations.",
+ "Expected one exact base APK; split or unexpected paths rejected.",
+ "Expected owned disposable device selector.",
+ "Expected owned emulator before installation.",
+ "Expected owned emulator serial.",
+ "Expected owned simulator UUID before installation.",
+ "Expected owned simulator UUID.",
+ "Expected private diagnostic file.",
+ "Expected private diagnostic output.",
+ "Expected the owned simulator app install command.",
+ "Export fixed cli-2.11.0 driver markers, never subprocess error text.",
+ "Extract verified Maestro including native executable modes",
+ "FAIL",
+ "FAILED",
+ "FATAL EXCEPTION|Fatal signal",
+ "FATAL_EXCEPTION",
+ "FULL_SIMULATOR_BUNDLE_TREE_AND_EXECUTABLE_SHA256",
+ "Fail early on iOS driver setup without installing or crediting the app.",
+ "Failed to compile",
+ "Failed to connect",
+ "Failed to launch app",
+ "Failed to start",
+ "Feature evidence absent or oversized.",
+ "Feature production source differs from committed candidate.",
+ "Feature scenario evidence is incomplete or outside reviewed scope.",
+ "Feature workers do not match exact-candidate production source.",
+ "FileNotFoundError",
+ "FileNotFoundException",
+ "Five raw helper measurements are required.",
+ "Fixed markers in prefixed own-process records; marker presence is not failure-cause or crash proof.",
+ "Fresh install; render Create a passcode; type four disposable digits; assert Confirm your passcode; stop before persisting credentials.",
+ "Fresh startup only; no account or persisted PIN created.",
+ "Full installed artifact byte comparison; no installer transformations accepted.",
+ "GCM_SENDER_ID",
+ "GITHUB_RUN_ATTEMPT",
+ "GITHUB_RUN_ID",
+ "GITHUB_WORKFLOW_REF",
+ "GITHUB_WORKFLOW_SHA",
+ "GOOGLE_APP_ID",
+ "Generate targeted CocoaPods lock candidate (not validation)",
+ "GraphNotFoundError",
+ "HEAD",
+ "HEAD:",
+ "HERMES_EXCEPTION",
+ "HOST_EXCEPTION",
+ "Hierarchy snapshot count exceeded limit.",
+ "Hierarchy snapshot exceeded byte limit.",
+ "Hierarchy snapshot exceeded node limit.",
+ "Hierarchy snapshot must remain in private output.",
+ "Hosted native validation failed; inspect phase status and fixed diagnostic categories.",
+ "INSTALL_COORDINATION",
+ "INSTALL_COORDINATION_REFERENCE",
+ "INSTALL_FAILED",
+ "INVALID_EXIT_STATUS",
+ "IOException",
+ "IOS",
+ "IOSDriverTimeoutException",
+ "IOS_DEPLOYMENT_TARGET_UNSUPPORTED",
+ "IOS_STARTUP_ERROR",
+ "IS_ADS_ENABLED",
+ "IS_ANALYTICS_ENABLED",
+ "IS_GCM_ENABLED",
+ "IS_SIGNIN_ENABLED",
+ "IXErrorDomain",
+ "IXUserPresentableErrorDomain",
+ "Identify fresh emulator",
+ "IllegalStateException",
+ "ImageOS",
+ "ImageVersion",
+ "Incomplete bounded hierarchy snapshot.",
+ "Info.plist",
+ "Inspect this command locally; raw output remains private to the runner.",
+ "Install development debug APK",
+ "Install immutable CocoaPods dependencies",
+ "Install immutable JavaScript dependencies",
+ "Install pinned Android build SDK and NDK",
+ "Install pinned CocoaPods",
+ "Install pinned Yarn",
+ "Install unsigned development app",
+ "InstallCoordination|IXCoordinator|IXSClient|IXClient",
+ "Installed APK bytes differ or are unavailable.",
+ "Installed artifact bytes were not verified; no equivalence claimed.",
+ "Installed bundle differs; no installer normalization is accepted.",
+ "Installing driver with xcodebuild",
+ "Installing pre built driver without xcodebuild",
+ "Insufficient disposable-runner disk reserve; no cache or user data was removed.",
+ "Invalid app bundle.",
+ "Invalid bounded feature measurement.",
+ "Invalid bounded hierarchy.",
+ "Invalid built APK.",
+ "Invalid feature measurement shape.",
+ "Invalid hierarchy shape.",
+ "Invalid observation categories.",
+ "Invalid observation kind.",
+ "Invalid observation shape.",
+ "Invalid request options shape.",
+ "Invalid timestamp.",
+ "Invariant Violation|has not been registered",
+ "JS_INVARIANT",
+ "JS_RANGE",
+ "JS_REFERENCE",
+ "JS_SYNTAX",
+ "JS_TYPE",
+ "KEEPER_DIAGNOSTIC",
+ "KEEPER_NATIVE_PLATFORM",
+ "KEEPER_POD_LOCK_REPAIR",
+ "KEEPER_SOURCE_SHA",
+ "KEEPER_STARTUP_OBSERVER_PATH",
+ "KOTLIN_COMPILER_ERROR",
+ "Keeper-disposable-ci",
+ "Keeper-driver-preflight-ci",
+ "KeeperCommunity/bitcoin-keeper/.github/workflows/keeper-native-diagnostic.yml@refs/pull/7107/merge",
+ "LAUNCH_SERVICES",
+ "LOCK_WAIT",
+ "LSApplicationWorkspaceErrorDomain",
+ "Launch app",
+ "LaunchServices|LSApplication|_LSServer",
+ "Library not loaded|Symbol not found|dyld.*(?:not found|failed|error)",
+ "Library/Developer/CoreSimulator/Devices",
+ "Locate disposable feature evidence",
+ "Locate exact installed development package",
+ "Locate owned installed app bundle",
+ "Log [1-9]\\d* of [1-9]\\d*",
+ "MACH_WAIT",
+ "MAESTRO_CLI_NO_ANALYTICS",
+ "MEMORY",
+ "METRO_ERROR",
+ "METRO_MODULE_RESOLUTION_ERROR",
+ "METRO_REFERENCE_ERROR",
+ "METRO_SYNTAX_ERROR",
+ "METRO_TYPE_ERROR",
+ "MIInstallerErrorDomain",
+ "MISSING",
+ "MISValidate|SecStaticCode|AMFI",
+ "MOBILE_INSTALLATION",
+ "MODULE_RESOLUTION",
+ "Maestro %s: %s",
+ "Maestro app launch failed",
+ "Maestro app launch/stop command FAILED",
+ "Maestro archive checksum mismatch.",
+ "Maestro assertion failed: Create a passcode",
+ "Maestro assertion: Confirm your passcode state FAILED",
+ "Maestro assertion: Create a passcode visible FAILED",
+ "Maestro connection failed",
+ "Maestro device unavailable",
+ "Maestro diagnostic directory must remain private.",
+ "Maestro did not produce a complete successful native report.",
+ "Maestro driver start failed",
+ "Maestro log must remain in private output.",
+ "Maestro report exceeded diagnostic size limit.",
+ "Maestro tap %s FAILED",
+ "Manifest and yarn.lock are inconsistent; repair the lockfile separately.",
+ "Metadata only. No raw logs, screenshots, app binaries, simulator data or credentials.",
+ "Metro did not become ready within 60 attempts.",
+ "Metro exited before the disposable smoke.",
+ "Minimize",
+ "Missing or oversized native JUnit report.",
+ "Missing regular app executable.",
+ "MobileContainerManager|MCMClient|containermanager",
+ "MobileInstallation|MIClient|installApplication|installBundle",
+ "NATIVE_LIBRARY",
+ "NATIVE_LIBRARY_LOAD",
+ "NATIVE_MODULE",
+ "NATIVE_MODULE_MISSING",
+ "NOT RUN",
+ "NOT VERIFIED: installed bytes require full comparison.",
+ "NSCocoaErrorDomain",
+ "NSPOSIXErrorDomain",
+ "Native JUnit declares unsuccessful cases.",
+ "Native installation unexpectedly rewrote the installed manifest.",
+ "Native module or worker probe failed; raw output retained only on ephemeral runner.",
+ "NitroIap",
+ "NitroModules",
+ "No connected devices",
+ "No devices found",
+ "No script URL provided.",
+ "No script URL provided|No bundle URL present|Unable to load script|(?:Could not|Failed to) load bundle|Could not connect to development server",
+ "Node compatibility setup changed fields beyond module mappings.",
+ "Non-finite feature measurement.",
+ "Not queried; Metro and hierarchy do not establish process state.",
+ "NotFoundError",
+ "OBJC_EXCEPTION",
+ "ONLY_ACTIVE_ARCH=YES",
+ "OSError",
+ "OTHER",
+ "OTHER_ERROR",
+ "OWN_RECORDS_OBSERVED",
+ "Observe one unchanged simulator install; export only fixed, bounded facts.\n\nThe caller supplies its live harness context. This module never imports another\nhosted_native instance, changes the install deadline, retries, opens Simulator,\nor changes simulator/app services. Raw process/log output stays private.\n",
+ "Outer HTTP status only; multipart terminal status is not observed.",
+ "Oversized native feature evidence.",
+ "Owned driver-preflight simulator cleanup failed.",
+ "Owned emulator launch window; fixed facts only.",
+ "Owned simulator startup window; fixed observations, not app-process or cause proof.",
+ "PARSED",
+ "PARTIAL",
+ "PARTIAL_OR_CAPPED",
+ "PASS",
+ "PERMISSION_DENIED",
+ "PLATFORM",
+ "PLIST_VERSION",
+ "POSIX",
+ "PRESENT",
+ "PRIVATE",
+ "PROJECT_ID",
+ "PermissionError",
+ "Pkg.Revision",
+ "Pod lock candidate generated for review; no native validation performed.",
+ "Podfile.lock.candidate",
+ "Positive observation only; absence is not inferred.",
+ "Positive observation only; failed or malformed queries do not establish absence.",
+ "Prepare exact-source R5 production worker probe",
+ "Prepare existing Xcode Node path",
+ "Private startup observations; no raw device or application text escapes.",
+ "Private typed tree; internal links must remain inside this bundle.",
+ "RCT_NEW_ARCH_ENABLED",
+ "RCT_NO_LAUNCH_PACKAGER",
+ "REACT_FATAL",
+ "REACT_NATIVE_ERROR",
+ "REACT_NATIVE_JS_ERROR",
+ "REFERENCE",
+ "REQUEST",
+ "REQUIRED_TOOL_UNAVAILABLE",
+ "RESOURCE_BUSY",
+ "RESPONSE",
+ "RNredbox",
+ "ROOT",
+ "ROWS_OBSERVED",
+ "RUNNER_ARCH",
+ "RUNNER_OS",
+ "RUNNER_TEMP",
+ "RangeError",
+ "ReactHost:V",
+ "ReactNative",
+ "ReactNative:E",
+ "ReactNative:V",
+ "ReactNativeJS",
+ "ReactNativeJS:E",
+ "ReactNativeJS:V",
+ "Read bounded disposable feature evidence",
+ "Read launch-time output, discarding a partially truncated final record.",
+ "Read-only install observation; no UI or installed-byte acceptance.",
+ "Read-only simulator app-service readiness; no app, driver or UI credit.",
+ "Record Android emulator image",
+ "Record Java version",
+ "Record Node version",
+ "Record Xcode version",
+ "Record actual Gradle and JVM version",
+ "Record actual adb version",
+ "Record exact nonsecret argv and status; keep all process output private.",
+ "Record iOS Simulator SDK",
+ "ReferenceError",
+ "ReferenceError:",
+ "Render Error",
+ "Requested driver host port ",
+ "Require one successful listapps response within the bounded deadline.\n\n context supplies read()/save() from the active harness instance. The caller\n invokes this between commands, so metadata writes cannot race an app build,\n install or driver. A missing receipt also fails closed.\n ",
+ "ResolutionError",
+ "ResourceNotFoundError",
+ "Retain only fixed command labels, selectors and tool failure categories.",
+ "Retry",
+ "RevisionNotFoundError",
+ "RuntimeError",
+ "RuntimeException",
+ "SERVICE_CONNECTION_FAILED",
+ "SIGNATURE_VERIFICATION",
+ "SIGNATURE_VERIFICATION_FAILED",
+ "SIMCTL_LISTAPPS_EXIT_ZERO",
+ "SINGLE_INSTALLED_BASE_APK_SHA256",
+ "SKIPPED",
+ "SNAPSHOTS_PARSED",
+ "SPLIT_BUNDLE",
+ "SSLHandshakeException",
+ "SUCCESS",
+ "SYMBOLICATE",
+ "SYNTAX",
+ "Simulator app services did not respond successfully within the readiness window.",
+ "Simulator app-service readiness evidence could not be read.",
+ "Simulator app-service readiness evidence could not be saved.",
+ "Simulator app-service readiness is iOS-only.",
+ "SocketTimeoutException",
+ "Startup cleanup or receipt failed; subsequent probes cannot run.",
+ "Stop app",
+ "Syntax Error",
+ "SyntaxError",
+ "SyntaxError:",
+ "Synthetic Firebase project; DEVELOPMENT/testnet; loopback-only configured services; no production secrets.",
+ "TIMEOUT",
+ "TOOL_ERROR",
+ "TRANSFORM",
+ "TYPE",
+ "Tap on",
+ "Testing failed:",
+ "The disposable driver preflight is iOS-only.",
+ "The hosted runner ran out of disk space.",
+ "The native dependency lock is incompatible with the manifest.",
+ "The real app startup smoke must pass before module probes.",
+ "This error cannot be dismissed.",
+ "TimeoutException",
+ "TimeoutExpired",
+ "TransformError",
+ "TurboModuleRegistry.*could not be found|Native module cannot be null|Cannot find native module",
+ "TypeError",
+ "TypeError:",
+ "UNAVAILABLE",
+ "UNDETERMINED",
+ "UNKNOWN",
+ "USER_PRESENTABLE_INSTALL",
+ "Unable to check your passcode. Please try again.",
+ "Unable to connect",
+ "Unable to find device",
+ "Unable to launch app",
+ "Unable to load script.",
+ "Unable to resolve module",
+ "Unable to resolve module|Cannot find module",
+ "UnableToResolveError",
+ "Uncaught Error",
+ "Unexpected Maestro archive layout.",
+ "Unexpected app identity.",
+ "Unexpected hierarchy attributes or children format.",
+ "Unexpected hierarchy node format.",
+ "Unexpected installed app container.",
+ "Unknown disposable native suite.",
+ "UnknownHostException",
+ "Unsafe iOS executable selector.",
+ "UnsatisfiedLinkError|dlopen failed|couldn.t find DSO",
+ "Unsupported artifact platform.",
+ "Unsupported bundle entry.",
+ "Unsupported hosted iOS simulator architecture: %s",
+ "Unsupported native bundle platform.",
+ "ValueError",
+ "Verify committed R5 worker source before extraction",
+ "Verify dependency locks remain immutable",
+ "Verify native installation did not rewrite locks",
+ "WARNING",
+ "Wait",
+ "Wait for driver-preflight simulator boot",
+ "Wait for simulator boot",
+ "Warm %s development bundle (setup only)",
+ "Warm IOS development bundle (setup only)",
+ "Welcome Back",
+ "XDG_STATE_HOME",
+ "XPC_SYNC_WAIT",
+ "Xcode 16.4\nBuild version 16F6",
+ "Z",
+ "[A-Fa-f0-9]{8}(?:-[A-Fa-f0-9]{4}){3}-[A-Fa-f0-9]{12}",
+ "[A-Za-z0-9_][A-Za-z0-9_.-]*",
+ "[A-Za-z0-9_][A-Za-z0-9_.-]{0,127}",
+ "[Done] Install XCUITest runner on",
+ "[Done] Perform XCUITest driver status check on",
+ "[Failed] Perform XCUITest driver status check on",
+ "[Start] Install XCUITest runner on",
+ "[Start] Perform XCUITest driver status check on",
+ "\\b(?:mResumedActivity|topResumedActivity)\\s*[:=]",
+ "\\bNS(?:InvalidArgument|InternalInconsistency|Range|Generic|Malloc)?Exception\\b|terminating app due to uncaught exception",
+ "\\bRCTFatal\\b|Unhandled JS Exception|\\bRCTExceptionsManager\\b|Exception in HostFunction",
+ "\\bRangeError\\b",
+ "\\bReferenceError\\b",
+ "\\bSyntaxError\\b",
+ "\\bTypeError\\b",
+ "\\berror:|^error |^> (?!Task\\b)|^Caused by:",
+ "\\bkey_[1-4]\\b",
+ "\\d{3}",
+ "\\s+Code\\s*=\\s*(-?\\d+)\\b",
+ "\\x1b\\[[0-9;]*[A-Za-z]",
+ "^(?:error\\b|(?:Syntax|Type|Reference)Error:|Unable to resolve module)",
+ "^BUNDLE\\s",
+ "^Could not ",
+ "^FAILURE:|^A problem occurred|^Execution failed",
+ "^PREBUNDLE\\s",
+ "^[EF]/(AndroidRuntime|ReactNativeJS|ReactNative)\\s*\\(\\s*\\d+\\):\\s*(.*)",
+ "^\\[!\\]",
+ "^\\d+\\s*\\|",
+ "^\\d{4}-",
+ "^\\s*(\\d+)\\s+(\\S+)\\s+(.*)$",
+ "^e: ",
+ "__main__",
+ "__psynch_mutexwait|__ulock_wait|pthread_mutex_lock",
+ "_bundle",
+ "_test_cases",
+ "a",
+ "a2d63b0ed820a22b936a4a2e46c6d9581270118e45279855d6915471089b5653",
+ "absolute",
+ "accessibilityText",
+ "action",
+ "activities",
+ "activity",
+ "adb",
+ "after_command_index",
+ "after_sha256",
+ "alive",
+ "allowed_fields",
+ "analytics_auto_collection_enabled",
+ "analytics_collection_deactivated",
+ "android",
+ "android-startup-errors.log",
+ "android/app/build/outputs/apk/development/debug/app-development-debug.apk",
+ "android/app/google-services.json",
+ "android_client_info",
+ "android_errors",
+ "android_runtime_diagnosis",
+ "android_startup_diagnosis",
+ "android_startup_diagnosis.py",
+ "api_key",
+ "app",
+ "app_data_collection_default_enabled",
+ "app_id",
+ "appinstalld",
+ "applicationverificationfailed|invalid code signature|signature.*(?:invalid|verification failed)",
+ "arm64",
+ "artifact_policy",
+ "artifacts",
+ "assertWalletAccount",
+ "assertion failed",
+ "attempts",
+ "attributes",
+ "b17ae0c6b5c0ef6d7c717e0941ee8d5fdf9f43cf4321f37379e520ebe5c90af3",
+ "b389643cb05e0064e7d51f3dfb0bba6f91d5ff391e970060c3bc5a1111fd17dd",
+ "b5e958cf0b45ac3edcb87a72c6c892652582b08f90247205810b570fc4780d79",
+ "baffb93e8a4d08ec3be61d9e38d0741c0e9f4637339ce15199f138a3979b9981",
+ "base.apk",
+ "baseline",
+ "baseline-listapps",
+ "baseline-preferences-container",
+ "before_dependencies",
+ "before_native_build",
+ "before_sha256",
+ "bin/maestro",
+ "binary",
+ "boot",
+ "bootstatus",
+ "brief",
+ "browser",
+ "browserify",
+ "build",
+ "build-tools/35.0.0",
+ "build-tools;35.0.0",
+ "built_artifact",
+ "bundle.*(?:invalid|validation failed)|invalid.*(?:bundle|executable)",
+ "bundle_build_done",
+ "bundle_build_failed",
+ "bundle_build_started",
+ "bundle_marker_count",
+ "bundle_marker_observed",
+ "bundle_tree_sha256",
+ "bundling_error",
+ "bytes",
+ "cache_read_error",
+ "cache_write_error",
+ "capture",
+ "capture_output",
+ "catalyst_redbox_title",
+ "categories",
+ "category_record_counts",
+ "cause",
+ "check",
+ "children",
+ "classified_error_records",
+ "cleanup_errors",
+ "clearVerifiedRemoteRevision",
+ "cli-2.11.0",
+ "client",
+ "client_info",
+ "cocoapods",
+ "collection_error_types",
+ "collection_errors",
+ "collector",
+ "com.apple.CoreSimulator.SimDeviceType.iPhone-16",
+ "com.apple.CoreSimulator.SimError",
+ "com.apple.CoreSimulator.SimRuntime.iOS-18-5",
+ "com.apple.Preferences",
+ "com.apple.appinstalld",
+ "com.apple.lsd",
+ "com.apple.mobile.installd",
+ "command",
+ "command not found",
+ "command-%03d.log",
+ "command_error_type",
+ "command_index",
+ "command_returned",
+ "commands",
+ "compact",
+ "compileSdk=36; buildTools=35.0.0; NDK=27.1.12297006",
+ "configuration",
+ "configuration_overlays",
+ "configuration_version",
+ "confirmPIN",
+ "connection.*(?:invalidated|interrupted|refused|timed out)|failed to connect|service.*not available",
+ "controlled-transport-no-backend-acceptance",
+ "could not find compatible versions",
+ "coverage",
+ "crash",
+ "create",
+ "createPIN",
+ "credential_error",
+ "criterion",
+ "curl",
+ "currentBackupAccountSession",
+ "currentBackupAppId",
+ "currentWalletAccountId",
+ "current_key",
+ "cwd",
+ "d",
+ "data",
+ "data/Containers/Bundle/Application",
+ "db",
+ "debug",
+ "default",
+ "delete",
+ "deleteAppImageEntityWorker",
+ "deleteSigningDeviceWorker",
+ "dev",
+ "developmentServerError",
+ "device",
+ "device.*(?:not booted|shutdown|unavailable)|invalid device state",
+ "device_",
+ "device_uninstall",
+ "df",
+ "diagnostic",
+ "diagnostic_only",
+ "diagnostics",
+ "diff",
+ "diff_sha256",
+ "dir",
+ "directory",
+ "disabled",
+ "disk",
+ "disk_free_bytes",
+ "disk_preflight",
+ "dispatch_sync|dispatch_semaphore_wait|dispatch_group_wait",
+ "driver",
+ "driver_preflight",
+ "driver_startup_timeout",
+ "dumpsys",
+ "duration_seconds",
+ "e",
+ "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
+ "element not found",
+ "emulator",
+ "emulator-[0-9]+",
+ "emulator-\\d+",
+ "emulator/source.properties",
+ "engine",
+ "entries",
+ "env",
+ "er",
+ "error",
+ "error_details",
+ "error_domain_codes",
+ "error_records",
+ "error_type",
+ "errors",
+ "event",
+ "exception_types",
+ "excludeSource",
+ "exec-out",
+ "executable",
+ "executable_sha256",
+ "exist_ok",
+ "exit_code",
+ "expected_emulator_target",
+ "expected_sdk_build",
+ "export_row_limit",
+ "export_truncated",
+ "exported_rows",
+ "f",
+ "failed to install|could not install|installation failed",
+ "failed_commands",
+ "failed_phase",
+ "failure",
+ "failures",
+ "fault",
+ "features",
+ "features-junit.xml",
+ "file",
+ "files/",
+ "firebase.json",
+ "flush",
+ "foreground",
+ "format",
+ "free_bytes",
+ "fresh_disposable_state",
+ "ft",
+ "gem",
+ "generic/platform=iOS Simulator",
+ "get-serialno",
+ "getAccountFromSigner",
+ "getKeyUID",
+ "get_app_container",
+ "getprop",
+ "git",
+ "gradle",
+ "grew_during_read",
+ "handleHostException|ReactNoCrashSoftException|Exception in native call",
+ "hardware",
+ "head",
+ "hermes",
+ "hermes.*(?:exception|fatal|error|failed)|(?:exception|fatal|error).*hermes",
+ "hexa_keeper_dev",
+ "hierarchy",
+ "hierarchy_signals",
+ "hmr_client_error",
+ "host_load",
+ "host_load_1_5_15m",
+ "host_port_unavailable",
+ "http://127.0.0.1:8081/index.bundle?platform=%s&dev=true&minify=false",
+ "http://127.0.0.1:8081/index.bundle?platform=ios&dev=true&minify=false",
+ "http://127.0.0.1:8081/status",
+ "http_status",
+ "https://github.com/mobile-dev-inc/Maestro/releases/download/%s/maestro.zip",
+ "https://github.com/mobile-dev-inc/Maestro/releases/download/cli-2.11.0/maestro.zip",
+ "i",
+ "iOS driver not ready in time, consider increasing timeout by configuring MAESTRO_DRIVER_STARTUP_TIMEOUT env variable",
+ "iPhone 16; iOS 18.5",
+ "id",
+ "image",
+ "indent",
+ "info",
+ "initial",
+ "initialize_failed",
+ "injected-dispatch-selection-no-login-acceptance",
+ "input_truncated",
+ "install",
+ "install-diagnosis-%03d",
+ "install-sample",
+ "install_command_output",
+ "install_diagnoses",
+ "install_diagnosis",
+ "install_diagnosis.py",
+ "install_running_after_collection",
+ "install_running_before_collection",
+ "install_sample",
+ "install_succeeded",
+ "installd",
+ "installed-artifact-",
+ "installed_artifact",
+ "installed_artifact_scope",
+ "installed_artifact_verified",
+ "invalid_rows",
+ "inventory_sha256",
+ "io.hexawallet.hexakeeper.dev",
+ "io.hexawallet.keeper",
+ "io.hexawallet.keeper.development",
+ "ios",
+ "ios-startup-errors-stderr.log",
+ "ios-startup-errors.log",
+ "ios/GoogleService-Info.plist",
+ "ios/GoogleServices/dev/GoogleService-Info.plist",
+ "ios/Podfile.lock",
+ "ios/hexa_keeper.xcworkspace",
+ "ios_errors",
+ "ios_simulator_architecture",
+ "iphonesimulator",
+ "iteration",
+ "java",
+ "jsc",
+ "junit",
+ "keeper-disposable-ci",
+ "keeper-native-private",
+ "keeper-r5-native-evidence.json",
+ "key_1",
+ "key_2",
+ "key_3",
+ "key_4",
+ "kind",
+ "label",
+ "launch_window_started_ms",
+ "launchctl",
+ "lazy",
+ "limits",
+ "line_scan_limit",
+ "line_scan_truncated",
+ "lines_scanned",
+ "link",
+ "list",
+ "listapps",
+ "ln",
+ "loading",
+ "lockfile needs to be updated",
+ "lockfile needs to be updated|could not find compatible versions|^The sandbox is not in sync",
+ "log",
+ "log_limit_reached",
+ "logbox_controls",
+ "logbox_counter",
+ "logbox_error_header",
+ "logbox_syntax_footer",
+ "logbox_warning_header",
+ "logcat",
+ "login",
+ "logs_read",
+ "lsd",
+ "macOS",
+ "macOS-15.7.9-arm64-arm-64bit-Mach-O",
+ "mach_msg|mach_msg2_trap",
+ "macos15",
+ "maestro",
+ "maestro-output",
+ "maestro-preflight-state",
+ "maestro.zip",
+ "maestro/tests",
+ "maestro_preflight",
+ "main",
+ "malformed_record_lines",
+ "matching_process_records",
+ "max_workers",
+ "measurements",
+ "message",
+ "messaging_auto_init_enabled",
+ "metadata",
+ "metadata.json",
+ "method",
+ "metro",
+ "metro.log",
+ "metro_errors",
+ "metro_output",
+ "metro_process",
+ "metro_progress",
+ "metro_warmup",
+ "minify",
+ "minimum_free_bytes",
+ "missing_ok",
+ "mkdir",
+ "mobilesdk_app_id",
+ "modulesOnly",
+ "names",
+ "native",
+ "native-worker-process-relaunch-counts",
+ "native_probe",
+ "ndk/27.1.12297006",
+ "ndk;27.1.12297006",
+ "no space left on device",
+ "no space left on device|not enough (?:free )?(?:disk )?space",
+ "no-product-ui-navigation-pin-or-biometric-acceptance",
+ "noScriptURL",
+ "node",
+ "node_modules/.bin/patch-package",
+ "node_modules/react-native/cli.js",
+ "nodeify_overlay",
+ "npm",
+ "observation_state",
+ "observeBackupAccount",
+ "observed_after_deadline",
+ "observed_android_sdk",
+ "openiap",
+ "openjdk version \"17.0.20.1\" 2026-08-18\nOpenJDK Runtime Environment Temurin-17.0.20.1+1 (build 17.0.20.1+1)\nOpenJDK 64-Bit Server VM Temurin-17.0.20.1+1 (build 17.0.20.1+1, mixed mode, sharing)",
+ "options",
+ "os",
+ "outer_http_status",
+ "oversized_record_lines",
+ "own_app_resumed",
+ "owned-host-events",
+ "owned_install_process_count",
+ "owned_install_running",
+ "package.json",
+ "package:(/data/app/(?:~~[A-Za-z0-9_=-]+/)?",
+ "package_name",
+ "parents",
+ "parse_constant",
+ "parse_error",
+ "parse_error_types",
+ "parse_status",
+ "pass",
+ "path",
+ "permission denied|operation not permitted|not authorized",
+ "pid",
+ "pid=,stat=,args=",
+ "pidof",
+ "platform",
+ "platforms/android-36",
+ "platforms;android-36",
+ "please wait",
+ "pm",
+ "pod",
+ "post-install-container",
+ "post_install_lookup",
+ "prebuilt_driver_selected",
+ "prebundle_marker_count",
+ "prefix",
+ "prefix_bytes",
+ "prefix_sha256",
+ "prepare",
+ "private_",
+ "probe",
+ "probe-and-worker-timings-not-product-startup-ux",
+ "probe-junit.xml",
+ "probe_diagnostics",
+ "probe_ready_ms",
+ "probe_scope",
+ "process",
+ "process == \"%s\" AND (messageType == \"error\" OR messageType == \"fault\" OR eventMessage CONTAINS[c] \"error\" OR eventMessage CONTAINS[c] \"exception\" OR eventMessage CONTAINS[c] \"fatal\")",
+ "process == \"hexa_keeper_dev\" AND (messageType == \"error\" OR messageType == \"fault\" OR eventMessage CONTAINS[c] \"error\" OR eventMessage CONTAINS[c] \"exception\" OR eventMessage CONTAINS[c] \"fatal\")",
+ "process == \"installd\" OR process == \"appinstalld\" OR process == \"lsd\"",
+ "processes",
+ "producer_limit_may_be_reached",
+ "producer_row_limit",
+ "production-deletion-native-rollback",
+ "production-deletion-retained-native-references",
+ "production-setup-offline-retry-native-counts",
+ "production-worker-native-storage",
+ "production-worker-stale-session-rejection",
+ "project_id",
+ "project_info",
+ "project_number",
+ "ps",
+ "pull",
+ "query_status",
+ "query_timeout_seconds",
+ "r5_feature_evidence",
+ "r5_features",
+ "rb",
+ "react-native",
+ "read",
+ "record",
+ "record_limit_reached",
+ "redacted_tool_errors",
+ "redbox-dismiss",
+ "redbox-error",
+ "redbox-reload",
+ "redbox_resource",
+ "replace",
+ "replacement_character_observed",
+ "report",
+ "request",
+ "requested_device_disconnected",
+ "requires a higher minimum deployment target",
+ "resource busy|device busy|another installation.*in progress",
+ "resource-id",
+ "resource_errors",
+ "result",
+ "retry",
+ "rev-parse",
+ "reverse",
+ "rn_redbox_dismiss_button",
+ "rn_redbox_reload_button",
+ "rn_redbox_stack",
+ "ro.build.fingerprint",
+ "rows",
+ "run-as",
+ "runModule",
+ "run_attempt",
+ "run_id",
+ "runner",
+ "runner_install_launch_returned",
+ "runner_install_started",
+ "running",
+ "sample",
+ "save",
+ "scan_limit_reached",
+ "scenarios",
+ "schema",
+ "scope",
+ "sdk",
+ "sdkmanager",
+ "services",
+ "setupKeeperAppWorker",
+ "setup_first_wallet_ms",
+ "severity",
+ "sha256",
+ "shell",
+ "show",
+ "shutdown",
+ "signing",
+ "simctl",
+ "simctl create did not return an owned simulator UUID.",
+ "simulator-install-events",
+ "simulator-services",
+ "simulator_app_service_readiness",
+ "simulator_readiness",
+ "simulator_readiness.py",
+ "skipped",
+ "smoke",
+ "smoke-junit.xml",
+ "smoke_scope",
+ "snapshot",
+ "snapshot_count",
+ "snapshot_phase",
+ "sort_keys",
+ "source",
+ "source.properties",
+ "sourcePaths",
+ "source_functions",
+ "source_sha",
+ "spawn",
+ "src/services/backup/transport.ts",
+ "src/store/sagas/bhr.ts",
+ "src/store/sagas/storage.ts",
+ "src/store/sagas/wallets.ts",
+ "src/utils/utilities.ts",
+ "stack_categories",
+ "stage",
+ "start",
+ "start_new_session",
+ "startup",
+ "startup-foreground.log",
+ "startup-logcat.log",
+ "startup-observer.jsonl",
+ "startup_capture",
+ "startup_cleanup_errors",
+ "startup_diagnosis",
+ "startup_diagnosis.py",
+ "startup_diagnostics",
+ "startup_observation",
+ "startup_observation_capture",
+ "startup_observation_cleanup",
+ "startup_timing_scope",
+ "state",
+ "status",
+ "status_check_failed",
+ "status_check_started",
+ "status_response_received",
+ "stderr",
+ "stdout",
+ "strict",
+ "sudo",
+ "synthetic-wallet-generation-no-crypto-acceptance",
+ "system",
+ "tcp:8081",
+ "test",
+ "testcase",
+ "testcase_failures",
+ "testcase_statuses",
+ "testsuite",
+ "testsuites",
+ "text",
+ "time_ms",
+ "timeout",
+ "timeout_seconds",
+ "timestamp",
+ "title",
+ "toolchain",
+ "transformer_load_failed",
+ "true",
+ "truncated",
+ "truncated_logs",
+ "ui test runner does not exist",
+ "ui_test_runner_missing",
+ "unableLoadScript",
+ "unclassified_error_records",
+ "uninstall",
+ "unknown:BridgelessReact:V",
+ "unknown:ReactHost:V",
+ "unknown:ReactNative:V",
+ "unzip",
+ "update",
+ "url",
+ "url-server",
+ "utf-8",
+ "v22.23.3",
+ "valid_rows_in_scanned_input",
+ "value",
+ "version",
+ "wb",
+ "welcome_back",
+ "worker_stderr_chunk",
+ "workflow_ref",
+ "workflow_sha",
+ "x86_64",
+ "xcode",
+ "xcode_test_execute_failed",
+ "xcode_test_failed",
+ "xcode_testing_failed",
+ "xcodebuild",
+ "xcodebuild_driver_selected",
+ "xcrun",
+ "xctestrun config does not exist",
+ "xctestrun_config_missing",
+ "xpc_connection_send_message_with_reply_sync",
+ "yarn",
+ "yarn.lock",
+ "yarn@1.22.22",
+ "\ufffd"
+ ],
+ "source_sha": "1bc34890cb8618b2fffd446a63924974e0fe15b5"
+}
diff --git a/.github/scripts/read-044-android-artifact.cjs b/.github/scripts/read-044-android-artifact.cjs
new file mode 100644
index 0000000000..39e57ef6ef
--- /dev/null
+++ b/.github/scripts/read-044-android-artifact.cjs
@@ -0,0 +1,95 @@
+'use strict';
+// Prepared fixed transport; unavailable job/artifact bindings reject before I/O.
+const assert = require('node:assert/strict');
+const crypto = require('node:crypto');
+const fs = require('node:fs');
+const path = require('node:path');
+const { execFileSync } = require('node:child_process');
+const OWNER = 'KeeperCommunity', REPO = 'bitcoin-keeper';
+const RUN = 39873063291;
+const JOB = null;
+const SOURCE = '044ebb6ea2d465f6a70e9116e3feac5a604cd696';
+const WORKFLOW = '5a7b0c5da0a38197f6dd675ff424f3ba3f441d02';
+// Bind only after observing the actual completed Android job and artifact APIs.
+const ARTIFACT = null, ZIP_SIZE = null, DIGEST = null;
+const RUN_CONCLUSION = null, NATIVE_CONCLUSION = null, BUILD_CONCLUSION = null, PROBES_CONCLUSION = null;
+const NAME = `keeper-diagnostic-native-ANDROID-${SOURCE}-${RUN}-1`;
+
+async function run({ github, context, core }) {
+ let owned, primary = false, output;
+ try {
+ // Check the finite selection before API, filesystem or decoder operations.
+ assert.ok(Number.isSafeInteger(JOB) && JOB > 0);
+ assert.ok(Number.isSafeInteger(ARTIFACT) && ARTIFACT > 0);
+ assert.ok(Number.isSafeInteger(ZIP_SIZE) && ZIP_SIZE > 0 && ZIP_SIZE <= 1024 * 1024 + 4096);
+ assert.match(DIGEST ?? '', /^[a-f0-9]{64}$/);
+ assert.ok(['success', 'failure'].includes(RUN_CONCLUSION));
+ assert.ok(['success', 'failure'].includes(NATIVE_CONCLUSION));
+ assert.ok(['success', 'failure', 'skipped'].includes(BUILD_CONCLUSION));
+ assert.ok(['success', 'failure', 'skipped'].includes(PROBES_CONCLUSION));
+ assert.equal(context.repo.owner, OWNER); assert.equal(context.repo.repo, REPO);
+ assert.equal(context.eventName, 'push');
+ assert.equal(context.ref, 'refs/heads/codex/r5-044-artifact-readout-preparation-20261023');
+ const args = { owner: OWNER, repo: REPO, request: { timeout: 30000 } };
+ const [r, j, a] = await Promise.all([
+ github.rest.actions.getWorkflowRun({ ...args, run_id: RUN }),
+ github.rest.actions.getJobForWorkflowRun({ ...args, job_id: JOB }),
+ github.rest.actions.getArtifact({ ...args, artifact_id: ARTIFACT }),
+ ]);
+ assert.equal(r.data.id, RUN); assert.equal(r.data.run_attempt, 1);
+ assert.equal(r.data.repository.id, 470904030); assert.equal(r.data.head_repository.id, 470904030);
+ assert.equal(r.data.head_sha, SOURCE); assert.equal(r.data.event, 'pull_request');
+ assert.equal(r.data.head_branch, 'codex/r5-startup-credential-failure-observation-20261022');
+ assert.equal(r.data.path, '.github/workflows/keeper-native-diagnostic.yml');
+ assert.equal(r.data.status, 'completed'); assert.equal(r.data.conclusion, RUN_CONCLUSION);
+ assert.deepEqual(r.data.referenced_workflows, [{
+ path: `${OWNER}/${REPO}/.github/workflows/keeper-native-platform.yml@${WORKFLOW}`,
+ ref: 'refs/pull/7131/merge', sha: WORKFLOW,
+ }]);
+ assert.equal(j.data.run_attempt, 1);
+ assert.equal(j.data.id, JOB); assert.equal(j.data.run_id, RUN); assert.equal(j.data.head_sha, SOURCE);
+ assert.equal(j.data.status, 'completed'); assert.equal(j.data.conclusion, NATIVE_CONCLUSION);
+ for (const [name, conclusion] of [['Build development app', BUILD_CONCLUSION],
+ ['Run Android startup and native persistence probes', PROBES_CONCLUSION],
+ ['Retain safe Phase A evidence', 'success']]) {
+ const steps = j.data.steps.filter(step => step.name === name);
+ assert.equal(steps.length, 1); assert.equal(steps[0].status, 'completed');
+ assert.equal(steps[0].conclusion, conclusion);
+ }
+ assert.equal(a.data.id, ARTIFACT); assert.equal(a.data.name, NAME);
+ assert.equal(a.data.expired, false); assert.equal(a.data.size_in_bytes, ZIP_SIZE);
+ assert.equal(a.data.digest, `sha256:${DIGEST}`);
+ assert.equal(a.data.workflow_run.id, RUN); assert.equal(a.data.workflow_run.head_sha, SOURCE);
+ assert.equal(a.data.workflow_run.repository_id, 470904030);
+ assert.equal(a.data.workflow_run.head_repository_id, 470904030);
+ const download = await github.rest.actions.downloadArtifact({ ...args, artifact_id: ARTIFACT, archive_format: 'zip' });
+ const bytes = Buffer.from(download.data);
+ assert.equal(bytes.length, ZIP_SIZE);
+ assert.equal(crypto.createHash('sha256').update(bytes).digest('hex'), DIGEST);
+ const temp = process.env.RUNNER_TEMP;
+ assert.ok(temp && path.isAbsolute(temp));
+ assert.equal(fs.realpathSync(temp), path.resolve(temp));
+ const filename = path.join(temp, 'r5-044-android-fixed.zip');
+ const descriptor = fs.openSync(filename, 'wx', 0o600); owned = filename;
+ try { fs.writeFileSync(descriptor, bytes); }
+ finally { fs.closeSync(descriptor); }
+ output = execFileSync('python3', ['-B', '.github/scripts/read-044-android-artifact.py'],
+ { encoding: 'utf8', timeout: 30000, maxBuffer: 2 * 1024 * 1024, stdio: ['ignore', 'pipe', 'pipe'] });
+ assert.equal(output, 'FIXED_044_ANDROID_ARTIFACT_ZIP_BASE64_BEGIN\n' + bytes.toString('base64') +
+ '\nFIXED_044_ANDROID_ARTIFACT_ZIP_BASE64_END\n');
+ } catch (_) {
+ primary = true;
+ throw new Error('FIXED_NATIVE_ARTIFACT_READOUT_FAILED');
+ } finally {
+ if (owned) {
+ try { fs.unlinkSync(owned); }
+ catch (_) {
+ try { core.warning('FIXED_NATIVE_ARTIFACT_PRIVATE_CLEANUP_FAILED'); } catch (_) { /* retain primary */ }
+ if (!primary) throw new Error('FIXED_NATIVE_ARTIFACT_PRIVATE_CLEANUP_FAILED');
+ }
+ }
+ }
+ try { core.info(output.trim()); }
+ catch (_) { throw new Error('FIXED_NATIVE_ARTIFACT_READOUT_FAILED'); }
+}
+module.exports = { run };
diff --git a/.github/scripts/read-044-android-artifact.py b/.github/scripts/read-044-android-artifact.py
new file mode 100644
index 0000000000..921214d79a
--- /dev/null
+++ b/.github/scripts/read-044-android-artifact.py
@@ -0,0 +1,414 @@
+#!/usr/bin/env python3
+"""Validate one immutable metadata ZIP and transport its original bytes only."""
+import base64
+import hashlib
+import io
+import json
+import math
+import os
+from pathlib import Path
+import re
+import stat
+import struct
+import sys
+import unicodedata
+import zipfile
+import zlib
+
+SOURCE = '044ebb6ea2d465f6a70e9116e3feac5a604cd696'
+WORKFLOW = '5a7b0c5da0a38197f6dd675ff424f3ba3f441d02'
+WORKFLOW_REF = 'KeeperCommunity/bitcoin-keeper/.github/workflows/keeper-native-diagnostic.yml@refs/pull/7131/merge'
+RUN, ATTEMPT = '39873063291', '1'
+# Completed Android job/artifact/conclusions have not been observed.
+# These explicit unavailable bindings reject before API or input access.
+JOB = ARTIFACT = ZIP_SHA256 = ZIP_SIZE = None
+RUN_CONCLUSION = NATIVE_CONCLUSION = BUILD_CONCLUSION = PROBES_CONCLUSION = None
+LIMIT = 1024 * 1024
+MAX_COMMANDS = 512
+POLICY_SHA256 = 'f42cc4bacbfa28e4a69f1795384a773cba57dc6323a98cc9ac2e3dd4ec6ac3e7'
+BEGIN = 'FIXED_044_ANDROID_ARTIFACT_ZIP_BASE64_BEGIN'
+END = 'FIXED_044_ANDROID_ARTIFACT_ZIP_BASE64_END'
+ROOT_KEYS = frozenset(('schema', 'platform', 'source_sha', 'diagnostic_only', 'workflow_ref',
+ 'workflow_sha', 'run_id', 'run_attempt', 'runner', 'os', 'commands', 'build', 'smoke',
+ 'native_probe', 'r5_features', 'hardware', 'signing', 'app_id', 'smoke_scope',
+ 'startup_timing_scope', 'artifact_policy', 'toolchain', 'disk_preflight', 'nodeify_overlay',
+ 'configuration', 'configuration_overlays', 'maestro', 'built_artifact', 'metro_warmup',
+ 'probe_bundle', 'features_bundle', 'device', 'install_succeeded',
+ 'installed_artifact_verified', 'installed_artifact_scope', 'installed_artifact',
+ 'startup_diagnostics', 'startup_observation_capture', 'failed_phase', 'startup_observation',
+ 'startup_observation_cleanup', 'startup_cleanup_errors', 'disposable_cleanup', 'cleanup_failures',
+ 'probe_diagnostics', 'probe_scope', 'smoke_test_cases', 'native_probe_test_cases',
+ 'r5_features_test_cases', 'r5_feature_evidence', 'product_ui', 'product_key_ui',
+ 'product_credential_ui', 'product_version_history_ui', 'product_vault_ui'))
+FORBIDDEN_KEYS = frozenset(('raw', 'raw_logs', 'raw_output', 'log', 'logs', 'stdout', 'stderr',
+ 'screenshot', 'screenshots', 'hierarchy', 'password', 'pin', 'seed', 'mnemonic',
+ 'credentials', 'private_key', 'token', 'sas', 'authorization', 'attributes', 'children',
+ 'text', 'accessibilitytext', 'title', 'value', 'resource-id'))
+STARTUP_FLAGS = frozenset(('credential_error', 'retry', 'logbox_controls', 'redbox_resource', 'loading'))
+PRODUCT_FLAGS = frozenset(('onboarding_skip', 'start_new_tile', 'recover_tile', 'app_settings',
+ 'start_new_text', 'welcome', 'create_passcode', 'confirm_passcode', 'login', 'welcome_back',
+ 'credential_error', 'retry', 'dismiss_control', 'minimize_control', 'allow_control',
+ 'dont_allow_control', 'logbox_error_header', 'logbox_warning_header', 'logbox_counter',
+ 'logbox_controls', 'logbox_syntax_footer', 'notification_prompt_phrase',
+ 'notification_permission_controls'))
+PRODUCT_HIERARCHY_SCOPE = 'ANY_RETAINED_SNAPSHOT_NOT_FINAL_ROUTE_OR_VISIBILITY_PROOF'
+BOUNDARY_PATHS = frozenset((('startup_diagnostics', 'android_runtime_diagnosis'),
+ ('product_ui', 'samples', 'android_runtime_diagnostic', 'facts'),
+ ('product_ui', 'controlled_disconnect_retry', 'android_runtime_diagnostic', 'facts')))
+SNAPSHOT_PATHS = frozenset((('product_ui', 'samples'),
+ ('product_ui', 'controlled_disconnect_retry')))
+BOUNDARY_STAGES = frozenset(('ONBOARDING_EFFECT', 'SKIP_PRESS', 'SKIP_RESET_RETURNED',
+ 'SKIP_RESET_THROWN', 'NEW_KEEPER_EFFECT'))
+SKIP_FLAGS = frozenset(('clickable', 'enabled', 'focused', 'selected'))
+SNAPSHOT_SCOPE = 'POST_FAILED_ASSERT_OUTCOME_NOT_TAP_TIME'
+PUBLIC_PATTERNS = tuple(re.compile(pattern) for pattern in (
+ r'[a-f0-9]{40}(?:[a-f0-9]{24})?',
+ r'[A-F0-9]{8}(?:-[A-F0-9]{4}){3}-[A-F0-9]{12}',
+ r'[0-9]{1,20}',
+ r'[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}(?:\.[0-9]{1,6})?',
+ r'[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}(?:\.[0-9]{1,6})?(?:Z|\+00:00)',
+ r'[0-9]{8}\.[0-9]{4}\.[0-9]{1,2}',
+ r'emulator-[0-9]{1,8}',
+ # Source-owned mkdtemp name, six samples and fixed companion output names.
+ r'/home/runner/work/_temp/keeper-native-private/keeper-product-ui-[a-z0-9_]{8}/'
+ r'(?:sample-[1-6]|key-ui|history-ui|vault-ui|credential-ui/'
+ r'(?:credential_fixture-(?:armed|restored)|product_credential_(?:blocked|recovered)))'
+ r'(?:/junit\.xml)?',
+))
+
+
+def rejected():
+ raise ValueError('Artifact rejected.')
+
+
+def pairs(items):
+ result = {}
+ for key, value in items:
+ if key in result:
+ rejected()
+ result[key] = value
+ return result
+
+
+def finite(value):
+ value = float(value)
+ if not math.isfinite(value):
+ rejected()
+ return value
+
+
+def public_literals():
+ raw = Path(__file__).with_name('044-android-metadata-policy.json').read_bytes()
+ if len(raw) > 65536 or hashlib.sha256(raw).hexdigest() != POLICY_SHA256:
+ rejected()
+ policy = json.loads(raw, object_pairs_hook=pairs)
+ if policy['source_sha'] != SOURCE:
+ rejected()
+ return frozenset(policy['public_literals']) | {SOURCE, WORKFLOW, WORKFLOW_REF, RUN, ATTEMPT}
+
+
+def validate_hierarchy(value, product=False):
+ # These are exported fixed flags, never a TreeNode/UI attribute tree.
+ if value is None:
+ return
+ if type(value) is not dict:
+ rejected()
+ if not product:
+ if (set(value) != STARTUP_FLAGS | {'snapshot_count'} or
+ type(value['snapshot_count']) is not int or not 0 <= value['snapshot_count'] <= 8 or
+ any(value[name] is not None and type(value[name]) is not bool for name in STARTUP_FLAGS)):
+ rejected()
+ return
+ fields = {'state', 'snapshot_count', 'node_count', 'rejected_snapshots',
+ 'snapshot_limit_exceeded', 'scope', 'flags'}
+ if (set(value) != fields or value['scope'] != PRODUCT_HIERARCHY_SCOPE or
+ value['state'] not in ('UNKNOWN', 'COMPLETE', 'PARTIAL') or
+ any(type(value[name]) is not int or not 0 <= value[name] <= maximum for name, maximum in
+ (('snapshot_count', 8), ('node_count', 80000), ('rejected_snapshots', 8))) or
+ type(value['snapshot_limit_exceeded']) is not bool or type(value['flags']) is not dict or
+ set(value['flags']) != PRODUCT_FLAGS or
+ any(flag is not None and type(flag) is not bool for flag in value['flags'].values())):
+ rejected()
+
+
+def integer(value, minimum, maximum):
+ return type(value) is int and minimum <= value <= maximum
+
+
+def validate_boundary(value):
+ fallback = {'state': 'UNKNOWN', 'scope': 'OPTIONAL_DEV_MARKER_PARSER_UNAVAILABLE',
+ 'cause': 'UNDETERMINED', 'freshness': 'GUEST_CLOCK_UNVERIFIED'}
+ if type(value) is not dict:
+ rejected()
+ if value == fallback and set(value) == set(fallback):
+ return
+ constants = {'schema': 1, 'scope': 'DEV_MARKERS_NOT_ROUTE_TAP_DELIVERY_OR_CAUSE_PROOF',
+ 'cause': 'UNDETERMINED', 'freshness': 'GUEST_CLOCK_UNVERIFIED',
+ 'coverage': 'POSITIVE_ONLY_MISSING_STAGES_UNKNOWN', 'producer_per_stage_limit': 4,
+ 'producer_total_limit': 20, 'consumer_marker_limit': 64,
+ 'input_byte_limit': 524288, 'scan_record_limit': 10000}
+ booleans = {'input_usable', 'full_input', 'ownership_usable', 'input_limit_exceeded',
+ 'record_limit_reached', 'marker_limit_reached'}
+ counters = {'marker_records', 'owned_marker_records', 'foreign_pid_records',
+ 'duplicate_records', 'malformed_marker_records', 'unsupported_marker_records',
+ 'invalid_text_records'}
+ fields = set(constants) | booleans | counters | {
+ 'state', 'stages', 'scanned_records', 'partial_records'}
+ if (set(value) != fields or
+ any(type(value[key]) is not type(item) or value[key] != item
+ for key, item in constants.items()) or
+ value['state'] not in ('UNKNOWN', 'OBSERVED', 'PARTIAL') or
+ any(type(value[key]) is not bool for key in booleans) or
+ any(not integer(value[key], 0, 64) for key in counters) or
+ not integer(value['scanned_records'], 0, 10000) or
+ not integer(value['partial_records'], 0, 1) or
+ type(value['stages']) is not dict or set(value['stages']) != BOUNDARY_STAGES or
+ any(flag is not None and flag is not True for flag in value['stages'].values())):
+ rejected()
+
+
+def validate_snapshot(value):
+ fallback = {'schema': 1, 'binding_state': 'UNKNOWN', 'reason': 'COLLECTOR_UNAVAILABLE',
+ 'scope': SNAPSHOT_SCOPE}
+ if type(value) is not dict:
+ rejected()
+ if (set(value) == set(fallback) and
+ all(type(value[key]) is type(item) and value[key] == item
+ for key, item in fallback.items())):
+ return
+ fields = {'schema', 'binding_state', 'reason', 'scope', 'failed_assertion',
+ 'node_count', 'skip', 'tap_coordinates', 'visible_to_user'}
+ if (set(value) != fields or type(value['schema']) is not int or value['schema'] != 1 or
+ value['scope'] != SNAPSHOT_SCOPE or
+ value['binding_state'] not in ('UNKNOWN', 'BOUND') or
+ value['reason'] != ('FAILED_ASSERTION_OUTCOME' if value['binding_state'] == 'BOUND'
+ else 'UNBOUND_FAILED_ASSERTION') or
+ value['tap_coordinates'] != 'NOT_RECORDED' or value['visible_to_user'] != 'NOT_RECORDED'):
+ rejected()
+ assertion, count = value['failed_assertion'], value['node_count']
+ if value['binding_state'] == 'BOUND':
+ if (type(assertion) is not dict or set(assertion) != {'kind', 'selector', 'sequence_number'} or
+ assertion['kind'] != 'ASSERT_VISIBLE' or assertion['selector'] != 'start_new_tile' or
+ not integer(assertion['sequence_number'], 0, 2047) or not integer(count, 1, 10000)):
+ rejected()
+ elif assertion is not None or count is not None:
+ rejected()
+ skip = value['skip']
+ if (type(skip) is not dict or set(skip) != SKIP_FLAGS | {
+ 'state', 'exact_resource_id_count', 'bounds', 'conflicts'} or
+ skip['state'] not in ('UNKNOWN', 'ABSENT', 'UNIQUE_VALID_BOUNDS') or
+ type(skip['conflicts']) is not dict or set(skip['conflicts']) != SKIP_FLAGS or
+ any(flag is not None and type(flag) is not bool for flag in
+ [*(skip[key] for key in SKIP_FLAGS), *skip['conflicts'].values()]) or
+ skip['exact_resource_id_count'] is not None and not integer(
+ skip['exact_resource_id_count'], 0, count if count is not None else 10000)):
+ rejected()
+ if value['binding_state'] == 'UNKNOWN' and skip['exact_resource_id_count'] is not None:
+ rejected()
+ if skip['state'] == 'UNIQUE_VALID_BOUNDS':
+ bounds = skip['bounds']
+ if (skip['exact_resource_id_count'] != 1 or type(bounds) is not dict or
+ set(bounds) != {'left', 'top', 'right', 'bottom'} or
+ any(not integer(item, -100000, 100000) for item in bounds.values()) or
+ bounds['right'] <= bounds['left'] or bounds['bottom'] <= bounds['top'] or
+ any(skip['conflicts'][key] is True and skip[key] is not None for key in SKIP_FLAGS)):
+ rejected()
+ elif (skip['bounds'] is not None or any(skip[key] is not None for key in SKIP_FLAGS) or
+ any(item is not None for item in skip['conflicts'].values()) or
+ skip['state'] == 'ABSENT' and skip['exact_resource_id_count'] != 0):
+ rejected()
+
+
+def validate_metadata(data, expected=None):
+ """No reconstruction: accept reviewed public vocabulary or reject the whole ZIP."""
+ identity = {'schema': 1, 'source_sha': SOURCE, 'workflow_sha': WORKFLOW,
+ 'workflow_ref': WORKFLOW_REF, 'run_id': RUN, 'run_attempt': ATTEMPT,
+ 'platform': 'ANDROID', 'diagnostic_only': True} if expected is None else expected
+ if (type(data) is not dict or not set(data) <= ROOT_KEYS or
+ any(type(data.get(key)) is not type(value) or data.get(key) != value
+ for key, value in identity.items())):
+ rejected()
+ for key in ('build', 'smoke', 'native_probe', 'r5_features', 'hardware', 'signing'):
+ if key in data and data[key] not in ('PASS', 'FAIL', 'NOT RUN', 'RUNNING', 'UNKNOWN', None):
+ rejected()
+ for key in ('runner', 'toolchain', 'maestro', 'built_artifact', 'device',
+ 'installed_artifact', 'startup_diagnostics', 'driver_preflight', 'startup_observation'):
+ if key in data and data[key] is not None and type(data[key]) is not dict:
+ rejected()
+ if 'commands' in data and (type(data['commands']) is not list or len(data['commands']) > MAX_COMMANDS):
+ rejected()
+ fields = {'label', 'command', 'timeout_seconds', 'exit_code', 'duration_seconds'}
+ for row in data.get('commands', []):
+ if (type(row) is not dict or not fields <= set(row) or
+ not set(row) <= fields | {'diagnostic', 'redacted_tool_errors'} or
+ type(row['label']) is not str or type(row['command']) is not list or
+ not 1 <= len(row['command']) <= 64 or
+ any(type(argument) is not str for argument in row['command'])):
+ rejected()
+ literals = public_literals()
+ nodes = 0
+
+ def walk(value, depth=0, path=()):
+ nonlocal nodes
+ nodes += 1
+ if depth > 24 or nodes > 25000:
+ rejected()
+ if type(value) is dict:
+ if len(value) > 256:
+ rejected()
+ for key, item in value.items():
+ safe_hierarchy = key == 'hierarchy' and path in (('startup_observation',),
+ ('product_ui', 'samples', 'failure_observation'),
+ ('product_ui', 'controlled_disconnect_retry', 'failure_observation'))
+ safe_sdk_key = path == ('toolchain', 'observed_android_sdk') and key in (
+ 'platforms/android-36', 'build-tools/35.0.0', 'ndk/27.1.12297006')
+ if (type(key) is not str or not (safe_sdk_key or
+ re.fullmatch(r'[A-Za-z_][A-Za-z0-9_.-]{0,80}', key)) or
+ key not in literals or
+ key.lower() in FORBIDDEN_KEYS and not safe_hierarchy):
+ rejected()
+ if safe_hierarchy:
+ validate_hierarchy(item, product=path != ('startup_observation',))
+ if key == 'onboarding_boundary_observation':
+ if path not in BOUNDARY_PATHS:
+ rejected()
+ validate_boundary(item)
+ elif key == 'failed_assertion_snapshot':
+ if path not in SNAPSHOT_PATHS:
+ rejected()
+ validate_snapshot(item)
+ elif key == 'diagnostic_marker_records':
+ if (path not in {(*parent, 'runtime_errors') for parent in BOUNDARY_PATHS} or
+ not integer(item, 0, 524288)):
+ rejected()
+ walk(item, depth + 1, (*path, key))
+ elif type(value) is list:
+ if len(value) > 1024:
+ rejected()
+ for item in value:
+ walk(item, depth + 1, path)
+ elif type(value) is str:
+ if (any((unicodedata.category(char) in ('Cc', 'Cf', 'Zl', 'Zp') and char not in '\n\t')
+ for char in value) or len(value) > 4096 or value not in literals and
+ not any(pattern.fullmatch(value) for pattern in PUBLIC_PATTERNS)):
+ rejected()
+ elif type(value) in (int, float):
+ if not math.isfinite(value) or abs(value) > 2 ** 53 - 1:
+ rejected()
+ elif value is not None and type(value) is not bool:
+ rejected()
+ walk(data)
+
+
+def canonical_payload(blob, entry, start_dir, comment):
+ """Every original byte belongs to one ordinary ZIP entry, directory or EOCD."""
+ if (comment or entry.comment or entry.extra or entry.header_offset != 0 or
+ entry.flag_bits not in (0, 8) or entry.compress_size > LIMIT + 4096):
+ rejected()
+ local = struct.unpack_from('<4s5H3I2H', blob)
+ signature, version, flags, method, mtime, mdate, crc, compressed, size, namesize, extrasize = local
+ name = b'android/metadata.json'
+ if (signature != b'PK\x03\x04' or version != 20 or flags != entry.flag_bits or
+ method != entry.compress_type or namesize != len(name) or extrasize or
+ blob[30:30 + namesize] != name):
+ rejected()
+ begin = 30 + namesize
+ end = begin + entry.compress_size
+ if flags == 8:
+ if (crc, compressed, size) != (0, 0, 0):
+ rejected()
+ if struct.unpack_from('<4s3I', blob, end) != (b'PK\x07\x08', entry.CRC, entry.compress_size, entry.file_size):
+ rejected()
+ central = end + 16
+ else:
+ if (crc, compressed, size) != (entry.CRC, entry.compress_size, entry.file_size):
+ rejected()
+ central = end
+ # No hidden gaps, extra fields, comments, second entries, prefix or suffix.
+ fields = struct.unpack_from('<4s6H3I5H2I', blob, central)
+ if (start_dir != central or fields[0] != b'PK\x01\x02' or fields[2:10] !=
+ (version, flags, method, mtime, mdate, entry.CRC, entry.compress_size, entry.file_size) or
+ fields[10:15] != (len(name), 0, 0, 0, 0) or fields[16] != 0 or
+ blob[central + 46:central + 46 + len(name)] != name):
+ rejected()
+ directory_size = 46 + len(name)
+ finish = central + directory_size
+ if (len(blob) != finish + 22 or struct.unpack_from('<4s4H2IH', blob, finish) !=
+ (b'PK\x05\x06', 0, 0, 1, 1, directory_size, central, 0)):
+ rejected()
+ payload = blob[begin:end]
+ if method == zipfile.ZIP_DEFLATED:
+ inflater = zlib.decompressobj(-15)
+ raw = inflater.decompress(payload, LIMIT + 1)
+ if not inflater.eof or inflater.unused_data or inflater.unconsumed_tail:
+ rejected()
+ else:
+ raw = payload
+ if len(raw) != entry.file_size or zlib.crc32(raw) != entry.CRC:
+ rejected()
+ return raw
+
+
+def validate_archive(blob, expected=None):
+ if type(blob) is not bytes or len(blob) > LIMIT + 4096:
+ rejected()
+ with zipfile.ZipFile(io.BytesIO(blob)) as archive:
+ members = archive.infolist()
+ if len(members) != 1:
+ rejected()
+ entry = members[0]
+ if (entry.filename != 'android/metadata.json' or entry.orig_filename != entry.filename or
+ entry.flag_bits & 1 or stat.S_IFMT(entry.external_attr >> 16) not in (0, stat.S_IFREG) or
+ entry.file_size > LIMIT or entry.compress_type not in (zipfile.ZIP_STORED, zipfile.ZIP_DEFLATED)):
+ rejected()
+ raw = canonical_payload(blob, entry, archive.start_dir, archive.comment)
+ if len(raw) > LIMIT or len(raw) != entry.file_size:
+ rejected()
+ data = json.loads(raw, object_pairs_hook=pairs, parse_float=finite, parse_constant=lambda _: rejected())
+ validate_metadata(data, expected)
+
+
+def require_binding():
+ # Unavailable constants cannot select or read any input. Replace only from
+ # the actual completed selected job/artifact, never a requested outcome.
+ if (type(JOB) is not str or not re.fullmatch(r'[1-9][0-9]{0,19}', JOB) or
+ type(ARTIFACT) is not str or not re.fullmatch(r'[1-9][0-9]{0,19}', ARTIFACT) or
+ type(ZIP_SHA256) is not str or not re.fullmatch(r'[a-f0-9]{64}', ZIP_SHA256) or
+ type(ZIP_SIZE) is not int or not 0 < ZIP_SIZE <= LIMIT + 4096 or
+ RUN_CONCLUSION not in ('success', 'failure') or
+ NATIVE_CONCLUSION not in ('success', 'failure') or
+ BUILD_CONCLUSION not in ('success', 'failure', 'skipped') or
+ PROBES_CONCLUSION not in ('success', 'failure', 'skipped')):
+ rejected()
+
+
+def checked_bytes(path):
+ require_binding()
+ with os.fdopen(os.open(path, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK), 'rb') as source:
+ info = os.fstat(source.fileno())
+ if not stat.S_ISREG(info.st_mode) or stat.S_IMODE(info.st_mode) != 0o600 or info.st_size != ZIP_SIZE:
+ rejected()
+ blob = source.read(ZIP_SIZE + 1)
+ if len(blob) != ZIP_SIZE or hashlib.sha256(blob).hexdigest() != ZIP_SHA256:
+ rejected()
+ validate_archive(blob)
+ return blob
+
+
+def main(argv=None):
+ try:
+ if sys.argv[1:] if argv is None else argv:
+ rejected()
+ require_binding()
+ blob = checked_bytes(Path(os.environ['RUNNER_TEMP']) / 'r5-044-android-fixed.zip')
+ except Exception:
+ print('FIXED_044_ANDROID_ARTIFACT_BYTE_READOUT_FAILED')
+ return 1
+ print(BEGIN)
+ print(base64.b64encode(blob).decode('ascii'))
+ print(END)
+ return 0
+
+
+if __name__ == '__main__':
+ raise SystemExit(main())
diff --git a/.github/scripts/read-044-ios-artifact.cjs b/.github/scripts/read-044-ios-artifact.cjs
new file mode 100644
index 0000000000..313e1d7089
--- /dev/null
+++ b/.github/scripts/read-044-ios-artifact.cjs
@@ -0,0 +1,97 @@
+'use strict';
+// Finite metadata-only byte transport; no native worker or artifact selector input.
+const assert = require('node:assert/strict');
+const crypto = require('node:crypto');
+const fs = require('node:fs');
+const path = require('node:path');
+const { execFileSync } = require('node:child_process');
+const OWNER = 'KeeperCommunity', REPO = 'bitcoin-keeper';
+const RUN = 39873063291, JOB = 120151926152;
+const SOURCE = '044ebb6ea2d465f6a70e9116e3feac5a604cd696';
+const WORKFLOW = '5a7b0c5da0a38197f6dd675ff424f3ba3f441d02';
+// Exact completed iOS job/artifact API and upload facts; Android may continue.
+const ARTIFACT = 12469536083, ZIP_SIZE = 7232, DIGEST = 'e244015128d4aa72e1e1c8be3072bc70d506ba11a804067448122d1318621caf';
+const NATIVE_CONCLUSION = 'failure', STEP_CONCLUSIONS = ['success', 'failure', 'skipped', 'skipped', 'skipped'];
+const STEPS = ['Build development app', 'Run disposable startup smoke',
+ 'Run disposable native persistence probe', 'Run R5 production worker native scenarios',
+ 'Measure five full-product startup and first-wallet runs'];
+const CONCLUSIONS = ['success', 'failure', 'skipped'];
+const NAME = `keeper-diagnostic-native-IOS-${SOURCE}-${RUN}-1`;
+
+async function run({ github, context, core }) {
+ let owned, primary = false, output;
+ try {
+ assert.ok(Number.isSafeInteger(ARTIFACT) && ARTIFACT > 0);
+ assert.ok(Number.isSafeInteger(ZIP_SIZE) && ZIP_SIZE > 0 && ZIP_SIZE <= 1024 * 1024 + 4096);
+ assert.match(DIGEST ?? '', /^[a-f0-9]{64}$/);
+ assert.ok(['success', 'failure'].includes(NATIVE_CONCLUSION));
+ assert.ok(Array.isArray(STEP_CONCLUSIONS) && STEP_CONCLUSIONS.length === STEPS.length &&
+ STEPS.every((_, index) => CONCLUSIONS.includes(STEP_CONCLUSIONS[index])));
+ assert.equal(context.repo.owner, OWNER); assert.equal(context.repo.repo, REPO);
+ assert.equal(context.eventName, 'push');
+ assert.equal(context.ref, 'refs/heads/codex/r5-044-artifact-readout-preparation-20261023');
+ const args = { owner: OWNER, repo: REPO, request: { timeout: 30000 } };
+ const [r, j, a] = await Promise.all([
+ github.rest.actions.getWorkflowRun({ ...args, run_id: RUN }),
+ github.rest.actions.getJobForWorkflowRun({ ...args, job_id: JOB }),
+ github.rest.actions.getArtifact({ ...args, artifact_id: ARTIFACT }),
+ ]);
+ assert.equal(r.data.id, RUN); assert.equal(r.data.run_attempt, 1);
+ assert.equal(r.data.repository.id, 470904030); assert.equal(r.data.head_repository.id, 470904030);
+ assert.equal(r.data.head_sha, SOURCE); assert.equal(r.data.event, 'pull_request');
+ assert.equal(r.data.head_branch, 'codex/r5-startup-credential-failure-observation-20261022');
+ assert.equal(r.data.path, '.github/workflows/keeper-native-diagnostic.yml');
+ // Only this completed iOS job is needed; Android may continue untouched.
+ assert.ok((r.data.status === 'in_progress' && r.data.conclusion === null) ||
+ (r.data.status === 'completed' && ['success', 'failure'].includes(r.data.conclusion)));
+ assert.deepEqual(r.data.referenced_workflows, [{
+ path: `${OWNER}/${REPO}/.github/workflows/keeper-native-platform.yml@${WORKFLOW}`,
+ ref: 'refs/pull/7131/merge', sha: WORKFLOW,
+ }]);
+ assert.equal(j.data.id, JOB); assert.equal(j.data.run_id, RUN); assert.equal(j.data.run_attempt, 1);
+ assert.equal(j.data.head_sha, SOURCE); assert.equal(j.data.status, 'completed');
+ assert.equal(j.data.conclusion, NATIVE_CONCLUSION);
+ for (const [index, name] of STEPS.entries()) {
+ const steps = j.data.steps.filter(step => step.name === name);
+ assert.equal(steps.length, 1); assert.equal(steps[0].status, 'completed');
+ assert.equal(steps[0].conclusion, STEP_CONCLUSIONS[index]);
+ }
+ const upload = j.data.steps.filter(step => step.name === 'Retain safe Phase A evidence');
+ assert.equal(upload.length, 1); assert.equal(upload[0].status, 'completed');
+ assert.equal(upload[0].conclusion, 'success');
+ assert.equal(a.data.id, ARTIFACT); assert.equal(a.data.name, NAME);
+ assert.equal(a.data.expired, false); assert.equal(a.data.size_in_bytes, ZIP_SIZE);
+ assert.equal(a.data.digest, `sha256:${DIGEST}`);
+ assert.equal(a.data.workflow_run.id, RUN); assert.equal(a.data.workflow_run.head_sha, SOURCE);
+ assert.equal(a.data.workflow_run.repository_id, 470904030);
+ assert.equal(a.data.workflow_run.head_repository_id, 470904030);
+ const download = await github.rest.actions.downloadArtifact({ ...args, artifact_id: ARTIFACT, archive_format: 'zip' });
+ const bytes = Buffer.from(download.data);
+ assert.equal(bytes.length, ZIP_SIZE);
+ assert.equal(crypto.createHash('sha256').update(bytes).digest('hex'), DIGEST);
+ const temp = process.env.RUNNER_TEMP;
+ assert.ok(temp && path.isAbsolute(temp)); assert.equal(fs.realpathSync(temp), path.resolve(temp));
+ const filename = path.join(temp, 'r5-044-ios-fixed.zip');
+ const descriptor = fs.openSync(filename, 'wx', 0o600); owned = filename;
+ try { fs.writeFileSync(descriptor, bytes); }
+ finally { fs.closeSync(descriptor); }
+ output = execFileSync('python3', ['-B', '.github/scripts/read-044-ios-artifact.py'],
+ { encoding: 'utf8', timeout: 30000, maxBuffer: 2 * 1024 * 1024, stdio: ['ignore', 'pipe', 'pipe'] });
+ assert.equal(output, 'FIXED_044_IOS_ARTIFACT_ZIP_BASE64_BEGIN\n' + bytes.toString('base64') +
+ '\nFIXED_044_IOS_ARTIFACT_ZIP_BASE64_END\n');
+ } catch (_) {
+ primary = true;
+ throw new Error('FIXED_NATIVE_ARTIFACT_READOUT_FAILED');
+ } finally {
+ if (owned) {
+ try { fs.unlinkSync(owned); }
+ catch (_) {
+ try { core.warning('FIXED_NATIVE_ARTIFACT_PRIVATE_CLEANUP_FAILED'); } catch (_) { /* retain primary */ }
+ if (!primary) throw new Error('FIXED_NATIVE_ARTIFACT_PRIVATE_CLEANUP_FAILED');
+ }
+ }
+ }
+ try { core.info(output.trim()); }
+ catch (_) { throw new Error('FIXED_NATIVE_ARTIFACT_READOUT_FAILED'); }
+}
+module.exports = { run };
diff --git a/.github/scripts/read-044-ios-artifact.py b/.github/scripts/read-044-ios-artifact.py
new file mode 100644
index 0000000000..72f960b196
--- /dev/null
+++ b/.github/scripts/read-044-ios-artifact.py
@@ -0,0 +1,416 @@
+#!/usr/bin/env python3
+"""Validate one immutable metadata ZIP and transport its original bytes only."""
+import base64
+import hashlib
+import io
+import json
+import math
+import os
+from pathlib import Path
+import re
+import stat
+import struct
+import sys
+import unicodedata
+import zipfile
+import zlib
+
+SOURCE = '044ebb6ea2d465f6a70e9116e3feac5a604cd696'
+WORKFLOW = '5a7b0c5da0a38197f6dd675ff424f3ba3f441d02'
+WORKFLOW_REF = 'KeeperCommunity/bitcoin-keeper/.github/workflows/keeper-native-diagnostic.yml@refs/pull/7131/merge'
+RUN, ATTEMPT, JOB = '39873063291', '1', '120151926152'
+# Exact completed iOS job/artifact API and upload facts.
+ARTIFACT = '12469536083'
+ZIP_SHA256 = 'e244015128d4aa72e1e1c8be3072bc70d506ba11a804067448122d1318621caf'
+ZIP_SIZE = 7232
+NATIVE_CONCLUSION = 'failure'
+STEP_CONCLUSIONS = ('success', 'failure', 'skipped', 'skipped', 'skipped')
+CONCLUSIONS = ('success', 'failure', 'skipped')
+LIMIT = 1024 * 1024
+MAX_COMMANDS = 512
+POLICY_SHA256 = 'c306f9da5cb3395b705c0e034a591b65d983bd05bf96a04855fb495665492d96'
+BEGIN = 'FIXED_044_IOS_ARTIFACT_ZIP_BASE64_BEGIN'
+END = 'FIXED_044_IOS_ARTIFACT_ZIP_BASE64_END'
+ROOT_KEYS = frozenset(('schema', 'platform', 'source_sha', 'diagnostic_only', 'workflow_ref',
+ 'workflow_sha', 'run_id', 'run_attempt', 'runner', 'os', 'commands', 'build', 'smoke',
+ 'native_probe', 'r5_features', 'hardware', 'signing', 'app_id', 'smoke_scope',
+ 'startup_timing_scope', 'artifact_policy', 'toolchain', 'disk_preflight', 'nodeify_overlay',
+ 'configuration', 'configuration_overlays', 'maestro', 'built_artifact', 'metro_warmup',
+ 'simulator_app_service_readiness', 'driver_preflight', 'install_diagnoses',
+ 'probe_bundle', 'features_bundle', 'device', 'install_succeeded',
+ 'installed_artifact_verified', 'installed_artifact_scope', 'installed_artifact',
+ 'startup_diagnostics', 'startup_observation_capture', 'failed_phase', 'startup_observation',
+ 'startup_observation_cleanup', 'startup_cleanup_errors', 'disposable_cleanup', 'cleanup_failures',
+ 'probe_diagnostics', 'probe_scope', 'smoke_test_cases', 'native_probe_test_cases',
+ 'r5_features_test_cases', 'r5_feature_evidence', 'product_ui', 'product_key_ui',
+ 'product_credential_ui', 'product_version_history_ui', 'product_vault_ui'))
+FORBIDDEN_KEYS = frozenset(('raw', 'raw_logs', 'raw_output', 'log', 'logs', 'stdout', 'stderr',
+ 'screenshot', 'screenshots', 'hierarchy', 'password', 'pin', 'seed', 'mnemonic',
+ 'credentials', 'private_key', 'token', 'sas', 'authorization', 'attributes', 'children',
+ 'text', 'accessibilitytext', 'title', 'value', 'resource-id'))
+STARTUP_FLAGS = frozenset(('credential_error', 'retry', 'logbox_controls', 'redbox_resource', 'loading',
+ 'login', 'welcome_back', 'logbox_error_header', 'logbox_warning_header',
+ 'logbox_syntax_footer', 'logbox_counter'))
+PRODUCT_FLAGS = frozenset(('onboarding_skip', 'start_new_tile', 'recover_tile', 'app_settings',
+ 'start_new_text', 'welcome', 'create_passcode', 'confirm_passcode', 'login', 'welcome_back',
+ 'credential_error', 'retry', 'dismiss_control', 'minimize_control', 'allow_control',
+ 'dont_allow_control', 'logbox_error_header', 'logbox_warning_header', 'logbox_counter',
+ 'logbox_controls', 'logbox_syntax_footer', 'notification_prompt_phrase',
+ 'notification_permission_controls'))
+PRODUCT_HIERARCHY_SCOPE = 'ANY_RETAINED_SNAPSHOT_NOT_FINAL_ROUTE_OR_VISIBILITY_PROOF'
+PUBLIC_PATTERNS = tuple(re.compile(pattern) for pattern in (
+ r'[a-f0-9]{40}(?:[a-f0-9]{24})?',
+ r'[A-F0-9]{8}(?:-[A-F0-9]{4}){3}-[A-F0-9]{12}',
+ r'[0-9]{1,20}',
+ r'[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}(?:\.[0-9]{1,6})?',
+ r'[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}(?:\.[0-9]{1,6})?(?:Z|\+00:00)',
+ r'[0-9]{8}\.[0-9]{4}\.[0-9]{1,2}',
+ # Source-owned mkdtemp name, six samples and fixed companion output names.
+ r'/Users/runner/work/_temp/keeper-native-private/keeper-product-ui-[a-z0-9_]{8}/'
+ r'(?:sample-[1-6]|key-ui|history-ui|vault-ui|credential-ui/'
+ r'(?:credential_fixture-(?:armed|restored)|product_credential_(?:blocked|recovered)))'
+ r'(?:/junit\.xml)?',
+))
+
+
+def rejected():
+ raise ValueError('Artifact rejected.')
+
+
+def pairs(items):
+ result = {}
+ for key, value in items:
+ if key in result:
+ rejected()
+ result[key] = value
+ return result
+
+
+def finite(value):
+ value = float(value)
+ if not math.isfinite(value):
+ rejected()
+ return value
+
+
+def public_literals():
+ raw = Path(__file__).with_name('044-ios-metadata-policy.json').read_bytes()
+ if len(raw) > 65536 or hashlib.sha256(raw).hexdigest() != POLICY_SHA256:
+ rejected()
+ policy = json.loads(raw, object_pairs_hook=pairs)
+ if policy['source_sha'] != SOURCE:
+ rejected()
+ return frozenset(policy['public_literals']) | {SOURCE, WORKFLOW, WORKFLOW_REF, RUN, ATTEMPT, JOB}
+
+
+def validate_hierarchy(value, product=False):
+ # These are exported fixed flags, never a TreeNode/UI attribute tree.
+ if value is None:
+ return
+ if type(value) is not dict:
+ rejected()
+ if not product:
+ if (set(value) != STARTUP_FLAGS | {'snapshot_count', 'observation_state'} or
+ value['observation_state'] not in ('UNKNOWN', 'SNAPSHOTS_PARSED') or
+ type(value['snapshot_count']) is not int or not 0 <= value['snapshot_count'] <= 8 or
+ any(value[name] is not None and type(value[name]) is not bool for name in STARTUP_FLAGS)):
+ rejected()
+ return
+ fields = {'state', 'snapshot_count', 'node_count', 'rejected_snapshots',
+ 'snapshot_limit_exceeded', 'scope', 'flags'}
+ if (set(value) != fields or value['scope'] != PRODUCT_HIERARCHY_SCOPE or
+ value['state'] not in ('UNKNOWN', 'COMPLETE', 'PARTIAL') or
+ any(type(value[name]) is not int or not 0 <= value[name] <= maximum for name, maximum in
+ (('snapshot_count', 8), ('node_count', 80000), ('rejected_snapshots', 8))) or
+ type(value['snapshot_limit_exceeded']) is not bool or type(value['flags']) is not dict or
+ set(value['flags']) != PRODUCT_FLAGS or
+ any(flag is not None and type(flag) is not bool for flag in value['flags'].values())):
+ rejected()
+
+
+def bounded_int(value, minimum, maximum):
+ return type(value) is int and minimum <= value <= maximum
+
+
+def validate_startup_receipt(value):
+ if value is None:
+ return
+ base = {'schema', 'status', 'records', 'cause', 'reasons', 'scope'}
+ scope = 'OPTIONAL_ORIGINAL_STARTUP_MARKERS_NOT_CAUSE_OR_ACCEPTANCE'
+ if (type(value) is not dict or type(value.get('schema')) is not int or value['schema'] != 1 or
+ value.get('cause') != 'UNDETERMINED' or value.get('scope') != scope):
+ rejected()
+ if set(value) == base:
+ if (value['status'] != 'UNKNOWN' or value['records'] != [] or
+ value['reasons'] not in (['COLLECTOR_UNAVAILABLE'], ['QUERY_UNAVAILABLE'])):
+ rejected()
+ return
+ counters = {'marker_records_seen', 'duplicate_records', 'malformed_markers',
+ 'invalid_compact_markers', 'invalid_record_fields', 'foreign_process_markers', 'outside_window_markers'}
+ flags = {'own_process_count_capped', 'limit_reached', 'input_partial'}
+ reasons = {'MISSING_WINDOW', 'INVALID_WINDOW', 'NO_MARKER_OBSERVED', 'INVALID_COMPACT_RECORD',
+ 'INVALID_RECORD_FIELDS', 'MALFORMED_MARKER', 'UNSUPPORTED_FRAMING', 'FOREIGN_PROCESS_MARKER',
+ 'OUTSIDE_WINDOW', 'MULTIPLE_OWN_PIDS', 'DUPLICATE_MARKER', 'MULTIPLE_MARKERS',
+ 'OBSERVATION_LIMIT', 'PARTIAL_INPUT'}
+ if (set(value) != base | counters | flags | {'window', 'own_process_count'} or
+ value['status'] not in ('UNKNOWN', 'AMBIGUOUS', 'OBSERVED') or
+ value['window'] not in ('UNKNOWN', 'INVALID', 'BOUNDED') or
+ any(not bounded_int(value[key], 0, 32) for key in counters) or
+ any(type(value[key]) is not bool for key in flags) or
+ not bounded_int(value['own_process_count'], 0, 2) or
+ type(value['reasons']) is not list or len(value['reasons']) > len(reasons) or
+ any(type(item) is not str or item not in reasons for item in value['reasons']) or
+ len(set(value['reasons'])) != len(value['reasons']) or
+ type(value['records']) is not list or len(value['records']) > 32):
+ rejected()
+ phases = ('ACCOUNT_STATE', 'NATIVE_CREDENTIAL_READ', 'CREDENTIAL_JSON', 'NAVIGATION')
+ names = ('Error', 'TypeError', 'SyntaxError', 'ReferenceError', 'RangeError', 'EvalError',
+ 'URIError', 'AggregateError', 'OTHER', 'UNKNOWN')
+ for row in value['records']:
+ if (type(row) is not dict or set(row) != {'phase', 'outcome', 'error_name', 'code', 'window_relation'} or
+ row['phase'] not in phases or row['outcome'] not in ('THREW', 'REJECTED') or
+ row['error_name'] not in names or row['window_relation'] != 'IN_WINDOW' or
+ row['outcome'] == 'REJECTED' and row['phase'] != 'NATIVE_CREDENTIAL_READ' or
+ row['code'] is not None and (not bounded_int(row['code'], -2147483648, 2147483647) or
+ (row['phase'], row['outcome']) != ('NATIVE_CREDENTIAL_READ', 'REJECTED'))):
+ rejected()
+
+
+def validate_snapshot(value):
+ if value is None:
+ return
+ base = {'schema', 'binding_state', 'reason', 'scope'}
+ scope = 'POST_FAILED_ASSERT_OUTCOME_NOT_TAP_TIME'
+ if (type(value) is not dict or type(value.get('schema')) is not int or value['schema'] != 1 or
+ value.get('scope') != scope):
+ rejected()
+ if set(value) == base:
+ if value['binding_state'] != 'UNKNOWN' or value['reason'] != 'COLLECTOR_UNAVAILABLE':
+ rejected()
+ return
+ if (set(value) != base | {'failed_assertion', 'node_count', 'skip', 'tap_coordinates', 'visible_to_user'} or
+ value['binding_state'] not in ('UNKNOWN', 'BOUND') or
+ value['reason'] not in ('UNBOUND_FAILED_ASSERTION', 'FAILED_ASSERTION_OUTCOME', 'UNAVAILABLE') or
+ value['tap_coordinates'] != 'NOT_RECORDED' or value['visible_to_user'] != 'NOT_RECORDED'):
+ rejected()
+ assertion, nodes, item = value['failed_assertion'], value['node_count'], value['skip']
+ if assertion is not None and (type(assertion) is not dict or
+ set(assertion) != {'kind', 'selector', 'sequence_number'} or
+ assertion['kind'] != 'ASSERT_VISIBLE' or assertion['selector'] != 'start_new_tile' or
+ not bounded_int(assertion['sequence_number'], 0, 2047)):
+ rejected()
+ if nodes is not None and not bounded_int(nodes, 1, 10000):
+ rejected()
+ flags = {'clickable', 'enabled', 'focused', 'selected'}
+ if (type(item) is not dict or set(item) != flags | {'state', 'exact_resource_id_count', 'bounds', 'conflicts'} or
+ item['state'] not in ('UNKNOWN', 'ABSENT', 'UNIQUE_VALID_BOUNDS') or
+ item['exact_resource_id_count'] is not None and not bounded_int(item['exact_resource_id_count'], 0, 10000) or
+ any(item[key] is not None and type(item[key]) is not bool for key in flags) or
+ type(item['conflicts']) is not dict or set(item['conflicts']) != flags or
+ any(flag is not None and type(flag) is not bool for flag in item['conflicts'].values())):
+ rejected()
+ bounds = item['bounds']
+ if bounds is not None and (type(bounds) is not dict or set(bounds) != {'left', 'top', 'right', 'bottom'} or
+ any(not bounded_int(number, -100000, 100000) for number in bounds.values()) or
+ bounds['right'] <= bounds['left'] or bounds['bottom'] <= bounds['top']):
+ rejected()
+ if value['binding_state'] == 'BOUND':
+ if assertion is None or nodes is None or item['exact_resource_id_count'] is None or item['exact_resource_id_count'] > nodes:
+ rejected()
+ elif assertion is not None or nodes is not None or item['exact_resource_id_count'] is not None:
+ rejected()
+ if item['state'] == 'UNIQUE_VALID_BOUNDS':
+ if (item['exact_resource_id_count'] != 1 or bounds is None or
+ any(type(flag) is not bool for flag in item['conflicts'].values())):
+ rejected()
+ elif (bounds is not None or any(item[key] is not None for key in flags) or
+ any(flag is not None for flag in item['conflicts'].values())):
+ rejected()
+ if item['state'] == 'ABSENT' and item['exact_resource_id_count'] != 0:
+ rejected()
+
+
+def validate_metadata(data, expected=None):
+ """No reconstruction: accept reviewed public vocabulary or reject the whole ZIP."""
+ identity = {'schema': 1, 'source_sha': SOURCE, 'workflow_sha': WORKFLOW,
+ 'workflow_ref': WORKFLOW_REF, 'run_id': RUN, 'run_attempt': ATTEMPT,
+ 'platform': 'IOS', 'diagnostic_only': True} if expected is None else expected
+ if (type(data) is not dict or not set(data) <= ROOT_KEYS or
+ any(type(data.get(key)) is not type(value) or data.get(key) != value
+ for key, value in identity.items())):
+ rejected()
+ for key in ('build', 'smoke', 'native_probe', 'r5_features', 'hardware', 'signing'):
+ if key in data and data[key] not in ('PASS', 'FAIL', 'NOT RUN', 'RUNNING', 'UNKNOWN', None):
+ rejected()
+ for key in ('runner', 'toolchain', 'maestro', 'built_artifact', 'device',
+ 'installed_artifact', 'startup_diagnostics', 'driver_preflight', 'startup_observation'):
+ if key in data and data[key] is not None and type(data[key]) is not dict:
+ rejected()
+ if 'commands' in data and (type(data['commands']) is not list or len(data['commands']) > MAX_COMMANDS):
+ rejected()
+ fields = {'label', 'command', 'timeout_seconds', 'exit_code', 'duration_seconds'}
+ for row in data.get('commands', []):
+ if (type(row) is not dict or not fields <= set(row) or
+ not set(row) <= fields | {'diagnostic', 'redacted_tool_errors'} or
+ type(row['label']) is not str or type(row['command']) is not list or
+ not 1 <= len(row['command']) <= 64 or
+ any(type(argument) is not str for argument in row['command'])):
+ rejected()
+ literals = public_literals()
+ nodes = 0
+
+ def walk(value, depth=0, path=()):
+ nonlocal nodes
+ nodes += 1
+ if depth > 24 or nodes > 25000:
+ rejected()
+ if type(value) is dict:
+ if len(value) > 256:
+ rejected()
+ for key, item in value.items():
+ safe_hierarchy = key == 'hierarchy' and path in (('startup_observation',),
+ ('product_ui', 'samples', 'failure_observation'),
+ ('product_ui', 'controlled_disconnect_retry', 'failure_observation'))
+ if (type(key) is not str or not re.fullmatch(r'[A-Za-z_][A-Za-z0-9_.-]{0,80}', key) or
+ key not in literals or
+ key.lower() in FORBIDDEN_KEYS and not safe_hierarchy):
+ rejected()
+ if safe_hierarchy:
+ validate_hierarchy(item, product=path != ('startup_observation',))
+ if key == 'startup_failure_receipt':
+ if path != ('startup_diagnostics', 'ios_errors'):
+ rejected()
+ validate_startup_receipt(item)
+ if key == 'failed_assertion_snapshot':
+ if path not in (('product_ui', 'samples'), ('product_ui', 'controlled_disconnect_retry')):
+ rejected()
+ validate_snapshot(item)
+ if key == 'onboarding_boundary_observation':
+ rejected() # This producer attaches Android-only receipts.
+ walk(item, depth + 1, (*path, key))
+ elif type(value) is list:
+ if len(value) > 1024:
+ rejected()
+ for item in value:
+ walk(item, depth + 1, path)
+ elif type(value) is str:
+ if (any((unicodedata.category(char) in ('Cc', 'Cf', 'Zl', 'Zp') and char not in '\n\t')
+ for char in value) or len(value) > 4096 or value not in literals and
+ not any(pattern.fullmatch(value) for pattern in PUBLIC_PATTERNS)):
+ rejected()
+ elif type(value) in (int, float):
+ if not math.isfinite(value) or abs(value) > 2 ** 53 - 1:
+ rejected()
+ elif value is not None and type(value) is not bool:
+ rejected()
+ walk(data)
+
+
+def canonical_payload(blob, entry, start_dir, comment):
+ """Every original byte belongs to one ordinary ZIP entry, directory or EOCD."""
+ if (comment or entry.comment or entry.extra or entry.header_offset != 0 or
+ entry.flag_bits not in (0, 8) or entry.compress_size > LIMIT + 4096):
+ rejected()
+ local = struct.unpack_from('<4s5H3I2H', blob)
+ signature, version, flags, method, mtime, mdate, crc, compressed, size, namesize, extrasize = local
+ name = b'ios/metadata.json'
+ if (signature != b'PK\x03\x04' or version != 20 or flags != entry.flag_bits or
+ method != entry.compress_type or namesize != len(name) or extrasize or
+ blob[30:30 + namesize] != name):
+ rejected()
+ begin = 30 + namesize
+ end = begin + entry.compress_size
+ if flags == 8:
+ if (crc, compressed, size) != (0, 0, 0):
+ rejected()
+ if struct.unpack_from('<4s3I', blob, end) != (b'PK\x07\x08', entry.CRC, entry.compress_size, entry.file_size):
+ rejected()
+ central = end + 16
+ else:
+ if (crc, compressed, size) != (entry.CRC, entry.compress_size, entry.file_size):
+ rejected()
+ central = end
+ # No hidden gaps, extra fields, comments, second entries, prefix or suffix.
+ fields = struct.unpack_from('<4s6H3I5H2I', blob, central)
+ if (start_dir != central or fields[0] != b'PK\x01\x02' or fields[2:10] !=
+ (version, flags, method, mtime, mdate, entry.CRC, entry.compress_size, entry.file_size) or
+ fields[10:15] != (len(name), 0, 0, 0, 0) or fields[16] != 0 or
+ blob[central + 46:central + 46 + len(name)] != name):
+ rejected()
+ directory_size = 46 + len(name)
+ finish = central + directory_size
+ if (len(blob) != finish + 22 or struct.unpack_from('<4s4H2IH', blob, finish) !=
+ (b'PK\x05\x06', 0, 0, 1, 1, directory_size, central, 0)):
+ rejected()
+ payload = blob[begin:end]
+ if method == zipfile.ZIP_DEFLATED:
+ inflater = zlib.decompressobj(-15)
+ raw = inflater.decompress(payload, LIMIT + 1)
+ if not inflater.eof or inflater.unused_data or inflater.unconsumed_tail:
+ rejected()
+ else:
+ raw = payload
+ if len(raw) != entry.file_size or zlib.crc32(raw) != entry.CRC:
+ rejected()
+ return raw
+
+
+def validate_archive(blob, expected=None):
+ if type(blob) is not bytes or len(blob) > LIMIT + 4096:
+ rejected()
+ with zipfile.ZipFile(io.BytesIO(blob)) as archive:
+ members = archive.infolist()
+ if len(members) != 1:
+ rejected()
+ entry = members[0]
+ if (entry.filename != 'ios/metadata.json' or entry.orig_filename != entry.filename or
+ entry.flag_bits & 1 or stat.S_IFMT(entry.external_attr >> 16) not in (0, stat.S_IFREG) or
+ entry.file_size > LIMIT or entry.compress_type not in (zipfile.ZIP_STORED, zipfile.ZIP_DEFLATED)):
+ rejected()
+ raw = canonical_payload(blob, entry, archive.start_dir, archive.comment)
+ if len(raw) > LIMIT or len(raw) != entry.file_size:
+ rejected()
+ data = json.loads(raw, object_pairs_hook=pairs, parse_float=finite, parse_constant=lambda _: rejected())
+ validate_metadata(data, expected)
+
+
+def require_binding():
+ # All unavailable bindings fail before file/policy reads.
+ if (type(ARTIFACT) is not str or not re.fullmatch(r'[1-9][0-9]{0,19}', ARTIFACT) or
+ type(ZIP_SHA256) is not str or not re.fullmatch(r'[a-f0-9]{64}', ZIP_SHA256) or
+ type(ZIP_SIZE) is not int or not 0 < ZIP_SIZE <= LIMIT + 4096 or
+ NATIVE_CONCLUSION not in ('success', 'failure') or type(STEP_CONCLUSIONS) is not tuple or
+ len(STEP_CONCLUSIONS) != 5 or any(value not in CONCLUSIONS for value in STEP_CONCLUSIONS)):
+ rejected()
+
+
+def checked_bytes(path):
+ require_binding()
+ with os.fdopen(os.open(path, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK), 'rb') as source:
+ info = os.fstat(source.fileno())
+ if not stat.S_ISREG(info.st_mode) or stat.S_IMODE(info.st_mode) != 0o600 or info.st_size != ZIP_SIZE:
+ rejected()
+ blob = source.read(ZIP_SIZE + 1)
+ if len(blob) != ZIP_SIZE or hashlib.sha256(blob).hexdigest() != ZIP_SHA256:
+ rejected()
+ validate_archive(blob)
+ return blob
+
+
+def main(argv=None):
+ try:
+ if sys.argv[1:] if argv is None else argv:
+ rejected()
+ require_binding()
+ blob = checked_bytes(Path(os.environ['RUNNER_TEMP']) / 'r5-044-ios-fixed.zip')
+ except Exception:
+ print('FIXED_044_IOS_ARTIFACT_BYTE_READOUT_FAILED')
+ return 1
+ print(BEGIN)
+ print(base64.b64encode(blob).decode('ascii'))
+ print(END)
+ return 0
+
+
+if __name__ == '__main__':
+ raise SystemExit(main())
diff --git a/.github/scripts/read-23f-android-artifact.py b/.github/scripts/read-23f-android-artifact.py
new file mode 100644
index 0000000000..f1c12d0b70
--- /dev/null
+++ b/.github/scripts/read-23f-android-artifact.py
@@ -0,0 +1,238 @@
+#!/usr/bin/env python3
+"""Finite diagnostic readout of one pinned artifact; never acceptance evidence."""
+import hashlib
+import io
+import json
+import math
+import os
+from pathlib import Path
+import re
+import stat
+import sys
+import zipfile
+
+SOURCE = '23f14e01f3437c213f1443c3167d96022f3a43bc'
+WORKFLOW = '1f084ee4486709e0066034a452349df897eb2434'
+WORKFLOW_REF = 'KeeperCommunity/bitcoin-keeper/.github/workflows/keeper-native-diagnostic.yml@refs/pull/7107/merge'
+RUN, ATTEMPT, ARTIFACT = '39846002094', '1', '12458149136'
+ZIP_SHA256 = '4d464ef5f8faa7de4f02292e683f0dad8242544843610da9371f2c675dc183f0'
+ZIP_SIZE, LIMIT = 8395, 1024 * 1024
+STAGES = ('startup_start', 'startup_ready', 'wallet_start', 'wallet_ready', 'home_ready',
+ 'relaunch_start', 'relaunch_login', 'relaunch_home', 'version_history_verified',
+ 'key_management_entry_verified', 'navigation_verified')
+RETRY = ('retry_fixture_start', 'retry_error_visible', 'retry_submit', 'retry_home_ready',
+ 'retry_relaunch_start', 'retry_relaunch_login', 'retry_relaunch_home')
+PIN = ('confirm_passcode_visible', 'confirmation_digits_tapped', 'create_tapped', 'continue_visible',
+ 'continue_tapped', 'cancel_visible', 'cancel_tapped', 'skip_visible', 'skip_tapped', 'start_new_visible')
+DURATIONS = ('startup_to_passcode_ms', 'start_new_to_ready_ms', 'start_new_to_home_ms',
+ 'cold_relaunch_to_login_ms', 'cold_relaunch_to_authenticated_home_ms')
+SCENARIOS = ('production-setup-offline-retry-native-counts', 'production-deletion-retained-native-references',
+ 'production-deletion-native-rollback', 'production-worker-stale-session-rejection',
+ 'native-worker-process-relaunch-counts')
+TYPES = ('TypeError', 'SyntaxError', 'ReferenceError', 'RangeError', 'EvalError', 'URIError',
+ 'AggregateError', 'TransformError', 'UnableToResolveError', 'InternalError', 'RuntimeException',
+ 'IllegalStateException', 'IllegalArgumentException', 'NullPointerException', 'SecurityException',
+ 'UnsatisfiedLinkError', 'NoClassDefFoundError', 'ClassNotFoundException', 'OutOfMemoryError', 'Error')
+FAULTS = ('JS_TYPE_ERROR', 'JS_SYNTAX_ERROR', 'JS_REFERENCE_ERROR', 'JS_RANGE_ERROR',
+ 'MODULE_RESOLUTION_ERROR', 'TRANSFORM_ERROR', 'APP_NOT_REGISTERED', 'NATIVE_MODULE_UNAVAILABLE',
+ 'NATIVE_LIBRARY_LOAD_ERROR', 'NATIVE_FATAL_SIGNAL', 'JAVA_FATAL_EXCEPTION', 'MEMORY_EXHAUSTION',
+ 'TRANSPORT_ERROR', 'FILESYSTEM_ERROR', 'WORKER_HEAP_EXHAUSTION', 'PROCESS_KILLED_MARKER')
+SOURCES = (
+ ('signer_identity', 'src/utils/utilities.ts', ['getAccountFromSigner', 'getKeyUID'], 'c64954ef892c8782324afcda57f69e510bab33649a47baaf702daf51eeae919a'),
+ ('storage_worker', 'src/store/sagas/storage.ts', ['setupKeeperAppWorker'], 'ef18f4962decfa11fb69825ff7b983fd086c243b5d2bbe4ed55f6aa5a4a68169'),
+ ('wallet_worker', 'src/store/sagas/wallets.ts', ['currentWalletAccountId', 'assertWalletAccount', 'deleteSigningDeviceWorker'], '88a35d8dc409c63d70459295112c6a9484f6b14bbff75b3e23965c31f700ef0e'),
+ ('backup_worker', 'src/store/sagas/bhr.ts', ['currentBackupAppId', 'deleteAppImageEntityWorker'], '548fd95fa62f675f0b42340e72a5e2558f33cff9272207f4523962531124d702'),
+ ('backup_transport', 'src/services/backup/transport.ts', ['observeBackupAccount', 'currentBackupAccountSession', 'clearVerifiedRemoteRevision'], '22ba1d5bbf45ab23c7db661a0635096b2a19878cbc0817c0eb1bfeebd8f24920'))
+
+
+def obj(value):
+ return value if type(value) is dict else {}
+
+
+def enum(value, allowed=('PASS', 'FAIL', 'NOT RUN', 'RUNNING')):
+ return value if type(value) is str and value in allowed else 'UNKNOWN'
+
+
+def number(value, maximum=1000000):
+ return value if type(value) in (int, float) and 0 <= value <= maximum and math.isfinite(value) else None
+
+
+def boolean(value):
+ return value if type(value) is bool else None
+
+
+def count(value, maximum=1000000):
+ return value if type(value) is int and 0 <= value <= maximum else None
+
+
+def digest(value):
+ return value if type(value) is str and re.fullmatch('[a-f0-9]{64}', value) else None
+
+
+def failure(value):
+ return enum(value, ('RuntimeError', 'AssertionError', 'OSError', 'ValueError', 'TypeError',
+ 'TimeoutExpired', 'TimeoutError', 'FileNotFoundError', 'PermissionError', 'OTHER_ERROR'))
+
+
+def prefix(value, vocabulary):
+ return value if type(value) is list and len(value) <= len(vocabulary) and value == list(vocabulary[:len(value)]) else None
+
+
+def fixed_list(value, vocabulary):
+ selected = {item for item in value[:64] if type(item) is str and item in vocabulary} if type(value) is list else set()
+ return [item for item in vocabulary if item in selected]
+
+
+def proof(value, built, verified):
+ value = obj(value)
+ found = digest(value.get('sha256'))
+ matches = (found == built and built is not None) if found and value.get('method') == 'SINGLE_INSTALLED_BASE_APK_SHA256' and verified is True else None
+ return {'method': enum(value.get('method'), ('SINGLE_INSTALLED_BASE_APK_SHA256',)),
+ 'installed_byte_proof_matches_built': matches}
+
+
+def commands(value):
+ labels = {'build_apk': 'Build debug-key-only development APK',
+ 'startup_ui': 'Assert startup and disposable passcode transition',
+ 'persistence_ui': 'Assert native persistence across process launches',
+ 'workers_ui': 'Assert R5 production workers over native storage',
+ 'product_ui': 'Full-product first-wallet and relaunch UI sample'}
+ rows = value[:1000] if type(value) is list else []
+ return {key: [{'exit_code': count(row.get('exit_code'), 255),
+ 'duration_seconds': number(row.get('duration_seconds'), 7200),
+ 'timeout_seconds': number(row.get('timeout_seconds'), 7200)}
+ for row in rows if type(row) is dict and row.get('label') == label][:5]
+ for key, label in labels.items()}
+
+
+def sample(value, built, retry=False):
+ value = obj(value)
+ stages = prefix(value.get('completed_stages'), RETRY if retry else STAGES)
+ progress = obj(value.get('pin_onboarding_progress'))
+ pins = prefix(progress.get('completed_markers'), PIN)
+ next_pin = PIN[len(pins)] if pins is not None and len(pins) < len(PIN) else None
+ result = {'sample': count(value.get('sample'), 6), 'reported_status': enum(value.get('status')),
+ 'completed_stages': stages or [], 'stage_prefix_valid': stages is not None,
+ 'raw_durations': {name: number(obj(value.get('raw_durations')).get(name), 3600000) for name in DURATIONS},
+ 'pin_progress': {'completed_markers': pins or [], 'prefix_valid': pins is not None,
+ 'next_marker': next_pin if pins is not None and progress.get('next_marker') == next_pin else 'UNKNOWN',
+ 'complete': boolean(progress.get('complete')) if pins is not None and progress.get('complete') == (len(pins) == len(PIN)) else None},
+ 'installed_apk': proof(value.get('installed_artifact'), built, value.get('installed_artifact_verified'))}
+ for field in ('create_new_app_calls', 'other_backend_calls_rejected', 'visible_wallet_count_before_relaunch',
+ 'visible_wallet_count_after_relaunch', 'transport_requests_dropped_without_commit',
+ 'acknowledged_create_responses', 'unexpected_create_attempts'):
+ result[field] = count(value.get(field))
+ runtime = obj(value.get('android_runtime_diagnostic'))
+ facts = obj(runtime.get('facts'))
+ errors = obj(facts.get('runtime_errors'))
+ result['android_runtime'] = {'collection_status': enum(runtime.get('status'), ('COLLECTED', 'UNAVAILABLE')),
+ 'process_state': enum(obj(facts.get('processes')).get('state'), ('PRESENT', 'ABSENT', 'UNKNOWN')),
+ 'matching_process_count': count(obj(facts.get('processes')).get('matching_process_count')),
+ 'foreground_relation': enum(obj(facts.get('foreground_activity')).get('relation'), ('OWN_APP', 'OTHER_APP', 'NONE', 'UNKNOWN')),
+ 'error_counts': {field: count(errors.get(field)) for field in ('parsed_error_records', 'own_error_records', 'unclassified_own_error_records', 'unparsed_nonempty_lines')},
+ 'exception_types': fixed_list(errors.get('exception_types'), TYPES),
+ 'fault_categories': fixed_list(errors.get('fault_categories'), FAULTS),
+ 'attribution': enum(errors.get('attribution'), ('CURRENT_OWN_PID_MATCH_HISTORY_FRESHNESS_UNKNOWN', 'UNKNOWN_NO_CURRENT_OWN_PROCESS')),
+ 'input_truncated': boolean(errors.get('input_truncated')),
+ 'cleanup': enum(facts.get('cleanup_status'), ('DELETED', 'UNKNOWN')), 'cause': 'UNDETERMINED'}
+ return result
+
+
+def _decode(blob):
+ """Decode bounded semantic fixtures too; the CLI additionally pins ZIP bytes."""
+ if type(blob) is not bytes or len(blob) > LIMIT + 4096:
+ raise ValueError('Artifact rejected.')
+ with zipfile.ZipFile(io.BytesIO(blob)) as archive:
+ members = archive.infolist()
+ if len(members) != 1:
+ raise ValueError('Artifact rejected.')
+ entry = members[0]
+ if (entry.filename != 'android/metadata.json' or entry.orig_filename != entry.filename or
+ entry.flag_bits & 1 or stat.S_IFMT(entry.external_attr >> 16) not in (0, stat.S_IFREG) or
+ entry.file_size > LIMIT or entry.compress_type not in (zipfile.ZIP_STORED, zipfile.ZIP_DEFLATED)):
+ raise ValueError('Artifact rejected.')
+ with archive.open(entry) as source:
+ raw = source.read(LIMIT + 1)
+ if len(raw) > LIMIT or len(raw) != entry.file_size:
+ raise ValueError('Artifact rejected.')
+ def pairs(items):
+ result = {}
+ for key, value in items:
+ if key in result:
+ raise ValueError('Artifact rejected.')
+ result[key] = value
+ return result
+ def finite(value):
+ value = float(value)
+ if not math.isfinite(value):
+ raise ValueError('Artifact rejected.')
+ return value
+ def reject(_):
+ raise ValueError('Artifact rejected.')
+ data = json.loads(raw, object_pairs_hook=pairs, parse_float=finite, parse_constant=reject)
+ expected = {'schema': 1, 'source_sha': SOURCE, 'workflow_sha': WORKFLOW, 'workflow_ref': WORKFLOW_REF,
+ 'run_id': RUN, 'run_attempt': ATTEMPT, 'platform': 'ANDROID', 'diagnostic_only': True}
+ if type(data) is not dict or any(type(data.get(key)) is not type(value) or data.get(key) != value for key, value in expected.items()):
+ raise ValueError('Artifact rejected.')
+ built = digest(obj(data.get('built_artifact')).get('sha256'))
+ product = obj(data.get('product_ui'))
+ samples = product.get('samples', [])
+ if type(samples) is not list or len(samples) > 5:
+ raise ValueError('Artifact rejected.')
+ workers = obj(data.get('r5_feature_evidence'))
+ functions = workers.get('source_functions')
+ expected_sources = [{'path': path, 'names': names, 'sha256': sha} for _, path, names, sha in SOURCES]
+ source_bound = type(functions) is list and functions == expected_sources
+ scenarios = workers.get('scenarios')
+ fixed_scenarios = {name: enum(obj(scenarios[index]).get('status')) if type(scenarios) is list and len(scenarios) == 5 and obj(scenarios[index]).get('id') == name else 'UNKNOWN' for index, name in enumerate(SCENARIOS)}
+ result = {'tag': 'SAFE_R5_ANDROID_READOUT', 'source_sha': SOURCE, 'workflow_sha': WORKFLOW,
+ 'run_id': RUN, 'run_attempt': ATTEMPT, 'artifact_id': ARTIFACT, 'diagnostic_only': True,
+ 'readout_only': True, 'authorization_eligible': False, 'trusted_native_acceptance': False,
+ 'release_acceptance': 'NOT ESTABLISHED', 'cause': 'UNDETERMINED',
+ 'reported_phases': {key: enum(data.get(key)) for key in ('build', 'smoke', 'native_probe', 'r5_features', 'hardware', 'signing')},
+ 'fixed_command_receipts': commands(data.get('commands')),
+ 'installed_apk': proof(data.get('installed_artifact'), built, data.get('installed_artifact_verified')),
+ 'workers': {'reported_status': enum(workers.get('status')), 'reported_scenarios': fixed_scenarios,
+ 'scope': 'SCOPED_WORKER_RECEIPT_NOT_PRODUCT_OR_RELEASE_ACCEPTANCE',
+ 'committed_sources_verified': source_bound,
+ 'source_sha256': {label: sha if source_bound else None for label, _, _, sha in SOURCES}},
+ 'product': {'reported_status': enum(product.get('status')), 'failure_category': failure(product.get('failure_category')),
+ 'requested_samples': count(product.get('requested_samples'), 5), 'reported_samples': len(samples),
+ 'samples': [sample(value, built) for value in samples],
+ 'retry': sample(product.get('controlled_disconnect_retry'), built, True),
+ 'companions': {key: enum(obj(product.get(key)).get('status')) for key in ('key_management_ui', 'credential_errors_ui', 'version_history_ui', 'vault_references_ui')},
+ 'cleanup': enum(product.get('cleanup'), ('FAILED',)),
+ 'cleanup_failure_categories': sorted({failure(value) for value in product.get('cleanup_failure_categories', [])[:16]}) if type(product.get('cleanup_failure_categories', [])) is list else ['UNKNOWN']}}
+ return result
+
+
+def decode(blob):
+ try:
+ return _decode(blob)
+ except Exception:
+ raise ValueError('Artifact rejected.') from None
+
+
+def main(argv=None):
+ try:
+ arguments = sys.argv[1:] if argv is None else argv
+ if arguments:
+ raise ValueError('Artifact rejected.')
+ path = Path(os.environ['RUNNER_TEMP']) / 'r5-23f-android-fixed.zip'
+ with os.fdopen(os.open(path, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK), 'rb') as source:
+ info = os.fstat(source.fileno())
+ if not stat.S_ISREG(info.st_mode) or stat.S_IMODE(info.st_mode) != 0o600 or info.st_size != ZIP_SIZE:
+ raise ValueError('Artifact rejected.')
+ blob = source.read(ZIP_SIZE + 1)
+ if len(blob) != ZIP_SIZE or hashlib.sha256(blob).hexdigest() != ZIP_SHA256:
+ raise ValueError('Artifact rejected.')
+ result = decode(blob)
+ except Exception:
+ print('FIXED_ANDROID_ARTIFACT_READOUT_FAILED')
+ return 1
+ print('SAFE_R5_ANDROID_READOUT ' + json.dumps(result, sort_keys=True, allow_nan=False))
+ return 0
+
+
+if __name__ == '__main__':
+ raise SystemExit(main())
diff --git a/.github/scripts/read-23f-native-artifact.cjs b/.github/scripts/read-23f-native-artifact.cjs
new file mode 100644
index 0000000000..5174f8bc9e
--- /dev/null
+++ b/.github/scripts/read-23f-native-artifact.cjs
@@ -0,0 +1,80 @@
+'use strict';
+// Retrieve one existing diagnostic receipt. No native/release/provider operation.
+const assert = require('node:assert/strict');
+const crypto = require('node:crypto');
+const fs = require('node:fs');
+const path = require('node:path');
+const { execFileSync } = require('node:child_process');
+const OWNER = 'KeeperCommunity', REPO = 'bitcoin-keeper';
+const RUN = 39846002094, JOB = 120075215316, ARTIFACT = 12458149136;
+const SOURCE = '23f14e01f3437c213f1443c3167d96022f3a43bc';
+const WORKFLOW = '1f084ee4486709e0066034a452349df897eb2434';
+const DIGEST = '4d464ef5f8faa7de4f02292e683f0dad8242544843610da9371f2c675dc183f0';
+const NAME = `keeper-diagnostic-native-ANDROID-${SOURCE}-${RUN}-1`;
+
+async function run({ github, context, core }) {
+ let owned, primary = false, output;
+ try {
+ assert.equal(context.repo.owner, OWNER); assert.equal(context.repo.repo, REPO);
+ assert.equal(context.eventName, 'push');
+ assert.equal(context.ref, 'refs/heads/codex/r5-23f-artifact-readout');
+ const args = { owner: OWNER, repo: REPO, request: { timeout: 30000 } };
+ const [r, j, a] = await Promise.all([
+ github.rest.actions.getWorkflowRun({ ...args, run_id: RUN }),
+ github.rest.actions.getJobForWorkflowRun({ ...args, job_id: JOB }),
+ github.rest.actions.getArtifact({ ...args, artifact_id: ARTIFACT }),
+ ]);
+ assert.equal(r.data.id, RUN); assert.equal(r.data.run_attempt, 1);
+ assert.equal(r.data.repository.id, 470904030); assert.equal(r.data.head_repository.id, 470904030);
+ assert.equal(r.data.head_sha, SOURCE); assert.equal(r.data.event, 'pull_request');
+ assert.equal(r.data.head_branch, 'codex/r5-native-acceptance-20261022');
+ assert.equal(r.data.path, '.github/workflows/keeper-native-diagnostic.yml');
+ assert.equal(r.data.status, 'completed'); assert.equal(r.data.conclusion, 'failure');
+ assert.deepEqual(r.data.referenced_workflows, [{
+ path: `${OWNER}/${REPO}/.github/workflows/keeper-native-platform.yml@${WORKFLOW}`,
+ ref: 'refs/pull/7107/merge', sha: WORKFLOW,
+ }]);
+ assert.equal(j.data.id, JOB); assert.equal(j.data.run_id, RUN); assert.equal(j.data.head_sha, SOURCE);
+ assert.equal(j.data.status, 'completed'); assert.equal(j.data.conclusion, 'failure');
+ for (const [name, conclusion] of [['Build development app', 'success'],
+ ['Run Android startup and native persistence probes', 'failure'], ['Retain safe Phase A evidence', 'success']]) {
+ const steps = j.data.steps.filter(step => step.name === name);
+ assert.equal(steps.length, 1); assert.equal(steps[0].status, 'completed');
+ assert.equal(steps[0].conclusion, conclusion);
+ }
+ assert.equal(a.data.id, ARTIFACT); assert.equal(a.data.name, NAME);
+ assert.equal(a.data.expired, false); assert.equal(a.data.size_in_bytes, 8395);
+ assert.equal(a.data.digest, `sha256:${DIGEST}`);
+ assert.equal(a.data.workflow_run.id, RUN); assert.equal(a.data.workflow_run.head_sha, SOURCE);
+ assert.equal(a.data.workflow_run.repository_id, 470904030);
+ assert.equal(a.data.workflow_run.head_repository_id, 470904030);
+ const download = await github.rest.actions.downloadArtifact({ ...args, artifact_id: ARTIFACT, archive_format: 'zip' });
+ const bytes = Buffer.from(download.data);
+ assert.equal(bytes.length, 8395);
+ assert.equal(crypto.createHash('sha256').update(bytes).digest('hex'), DIGEST);
+ const temp = process.env.RUNNER_TEMP;
+ assert.ok(temp && path.isAbsolute(temp));
+ assert.equal(fs.realpathSync(temp), path.resolve(temp));
+ const filename = path.join(temp, 'r5-23f-android-fixed.zip');
+ const descriptor = fs.openSync(filename, 'wx', 0o600); owned = filename;
+ try { fs.writeFileSync(descriptor, bytes); }
+ finally { fs.closeSync(descriptor); }
+ output = execFileSync('python3', ['-B', '.github/scripts/read-23f-android-artifact.py'],
+ { encoding: 'utf8', timeout: 30000, maxBuffer: 1024 * 1024, stdio: ['ignore', 'pipe', 'pipe'] });
+ assert.ok(output.startsWith('SAFE_R5_ANDROID_READOUT '));
+ } catch (_) {
+ primary = true;
+ throw new Error('FIXED_NATIVE_ARTIFACT_READOUT_FAILED');
+ } finally {
+ if (owned) {
+ try { fs.unlinkSync(owned); }
+ catch (_) {
+ try { core.warning('FIXED_NATIVE_ARTIFACT_PRIVATE_CLEANUP_FAILED'); } catch (_) { /* retain primary */ }
+ if (!primary) throw new Error('FIXED_NATIVE_ARTIFACT_PRIVATE_CLEANUP_FAILED');
+ }
+ }
+ }
+ try { core.info(output.trim()); } // Only the reviewed reconstructed Python receipt.
+ catch (_) { throw new Error('FIXED_NATIVE_ARTIFACT_READOUT_FAILED'); }
+}
+module.exports = { run };
diff --git a/.github/scripts/read-7158-android-startup-artifact.cjs b/.github/scripts/read-7158-android-startup-artifact.cjs
new file mode 100644
index 0000000000..ba34c49578
--- /dev/null
+++ b/.github/scripts/read-7158-android-startup-artifact.cjs
@@ -0,0 +1,126 @@
+'use strict';
+// One finite metadata projection; no native worker, release authority or selector input.
+const assert = require('node:assert/strict');
+const crypto = require('node:crypto');
+const fs = require('node:fs');
+const path = require('node:path');
+const { execFileSync } = require('node:child_process');
+const OWNER = 'KeeperCommunity', REPO = 'bitcoin-keeper';
+const RUN = 40085793409, JOB = 120848340201;
+const SOURCE = '3f4e8127e3698accd3760a4a039448964a5285a4';
+const WORKFLOW = 'f83a9a8b182dd8276a732ee2b6338fb6f845640a', NATIVE_HEAD_BRANCH = 'codex/r5-android-skip-target-20261024', WORKFLOW_PULL_REF = 'refs/pull/7158/merge', RUN_CONCLUSION = 'failure';
+// Exact terminal Android job/artifact API and upload facts.
+const ARTIFACT = 12557603923, ZIP_SIZE = 6451, DIGEST = 'f3553f9632eff7bd25f2315c8fb0e5429132455ea0af7d5293d4e4c7cfd8fd40';
+const NATIVE_CONCLUSION = 'failure', STEP_CONCLUSIONS = ['success', 'failure'];
+const STEPS = ['Build development app', 'Run Android startup and native persistence probes'];
+const CONCLUSIONS = ['success', 'failure', 'skipped'];
+const NAME = `keeper-diagnostic-native-ANDROID-${SOURCE}-${RUN}-1`;
+
+async function run({ github, context, core }) {
+ let owned, primary = false, output, stage = 'SELECTION';
+ try {
+ assert.match(WORKFLOW ?? '', /^[a-f0-9]{40}$/);
+ assert.ok(typeof NATIVE_HEAD_BRANCH === 'string' && /^codex\/[a-z0-9-]+$/.test(NATIVE_HEAD_BRANCH));
+ assert.match(WORKFLOW_PULL_REF ?? '', /^refs\/pull\/[1-9][0-9]*\/merge$/);
+ assert.ok(['success', 'failure'].includes(RUN_CONCLUSION));
+ assert.ok(Number.isSafeInteger(ARTIFACT) && ARTIFACT > 0);
+ assert.ok(Number.isSafeInteger(ZIP_SIZE) && ZIP_SIZE > 0 && ZIP_SIZE <= 1024 * 1024 + 4096);
+ assert.match(DIGEST ?? '', /^[a-f0-9]{64}$/);
+ assert.ok(['success', 'failure'].includes(NATIVE_CONCLUSION));
+ assert.ok(Array.isArray(STEP_CONCLUSIONS) && STEP_CONCLUSIONS.length === STEPS.length &&
+ STEPS.every((_, index) => CONCLUSIONS.includes(STEP_CONCLUSIONS[index])));
+ assert.equal(context.repo.owner, OWNER); assert.equal(context.repo.repo, REPO);
+ assert.equal(context.eventName, 'push');
+ assert.equal(context.ref, 'refs/heads/codex/r5-7158-android-startup-readout-r2-20261024');
+ const args = { owner: OWNER, repo: REPO, request: { timeout: 30000 } };
+ const admit = async () => {
+ stage = 'API_LOOKUP';
+ const [r, j, a] = await Promise.all([
+ github.rest.actions.getWorkflowRun({ ...args, run_id: RUN }),
+ github.rest.actions.getJobForWorkflowRun({ ...args, job_id: JOB }),
+ github.rest.actions.getArtifact({ ...args, artifact_id: ARTIFACT }),
+ ]);
+ stage = 'RUN_BINDING';
+ assert.equal(r.data.id, RUN); assert.equal(r.data.run_attempt, 1);
+ assert.equal(r.data.repository.id, 470904030); assert.equal(r.data.head_repository.id, 470904030);
+ assert.equal(r.data.head_sha, SOURCE); assert.equal(r.data.event, 'pull_request');
+ assert.equal(r.data.head_branch, NATIVE_HEAD_BRANCH);
+ assert.equal(r.data.path, '.github/workflows/keeper-native-diagnostic.yml');
+ assert.equal(r.data.status, 'completed'); assert.equal(r.data.conclusion, RUN_CONCLUSION);
+ assert.deepEqual(r.data.referenced_workflows, [{
+ path: `${OWNER}/${REPO}/.github/workflows/keeper-native-platform.yml@${WORKFLOW}`,
+ ref: WORKFLOW_PULL_REF, sha: WORKFLOW,
+ }]);
+ stage = 'JOB_BINDING';
+ assert.equal(j.data.id, JOB); assert.equal(j.data.run_id, RUN); assert.equal(j.data.run_attempt, 1);
+ assert.equal(j.data.head_sha, SOURCE); assert.equal(j.data.status, 'completed');
+ assert.equal(j.data.conclusion, NATIVE_CONCLUSION);
+ for (const [index, name] of STEPS.entries()) {
+ const steps = j.data.steps.filter(step => step.name === name);
+ assert.equal(steps.length, 1); assert.equal(steps[0].status, 'completed');
+ assert.equal(steps[0].conclusion, STEP_CONCLUSIONS[index]);
+ }
+ const upload = j.data.steps.filter(step => step.name === 'Retain safe Phase A evidence');
+ assert.equal(upload.length, 1); assert.equal(upload[0].status, 'completed');
+ assert.equal(upload[0].conclusion, 'success');
+ stage = 'ARTIFACT_BINDING';
+ assert.equal(a.data.id, ARTIFACT); assert.equal(a.data.name, NAME);
+ assert.equal(a.data.expired, false); assert.equal(a.data.size_in_bytes, ZIP_SIZE);
+ assert.equal(a.data.digest, `sha256:${DIGEST}`);
+ assert.equal(a.data.workflow_run.id, RUN); assert.equal(a.data.workflow_run.head_sha, SOURCE);
+ assert.equal(a.data.workflow_run.repository_id, 470904030);
+ assert.equal(a.data.workflow_run.head_repository_id, 470904030);
+ };
+ await admit();
+ stage = 'DOWNLOAD';
+ const download = await github.rest.actions.downloadArtifact({ ...args, artifact_id: ARTIFACT, archive_format: 'zip' });
+ const bytes = Buffer.from(download.data);
+ assert.equal(bytes.length, ZIP_SIZE);
+ assert.equal(crypto.createHash('sha256').update(bytes).digest('hex'), DIGEST);
+ stage = 'PRIVATE_FILE';
+ const temp = process.env.RUNNER_TEMP;
+ assert.ok(temp && path.isAbsolute(temp)); assert.equal(fs.realpathSync(temp), path.resolve(temp));
+ const filename = path.join(temp, 'r5-7158-android-startup-fixed.zip');
+ const descriptor = fs.openSync(filename, 'wx', 0o600); owned = filename;
+ try { fs.writeFileSync(descriptor, bytes); }
+ finally { fs.closeSync(descriptor); }
+ stage = 'DECODE';
+ try {
+ output = execFileSync('python3', ['-B', '.github/scripts/read-7158-android-startup-artifact.py'],
+ { encoding: 'utf8', timeout: 30000, maxBuffer: 2 * 1024 * 1024, stdio: ['ignore', 'pipe', 'pipe'] });
+ } catch (error) {
+ const match = /^STARTUP_7158_ANDROID_OBSERVATION_READOUT_FAILED:(SELECTION|PRIVATE_FILE|KERNEL|ZIP_IDENTITY|ZIP_LAYOUT|JSON|ROOT_KEYS|STARTUP|PROJECTED_METADATA)\n$/.exec(String(error.stdout ?? ''));
+ if (match) stage = 'DECODE_' + match[1];
+ throw error;
+ }
+ stage = 'PROJECTION_FRAME';
+ const lines = output.trim().split('\n');
+ assert.equal(lines.length, 3);
+ assert.equal(lines[0], 'STARTUP_7158_ANDROID_OBSERVATIONS_BEGIN');
+ assert.equal(lines[2], 'STARTUP_7158_ANDROID_OBSERVATIONS_END');
+ const projection = JSON.parse(lines[1]);
+ assert.deepEqual(Object.keys(projection).sort(), ['schema', 'scope', 'original_zip_sha256', 'metadata_sha256', 'observations'].sort());
+ assert.equal(projection.schema, 1);
+ assert.equal(projection.scope, 'OBSERVATIONS_ONLY_NOT_NATIVE_ACCEPTANCE_OR_CAUSE');
+ assert.equal(projection.original_zip_sha256, DIGEST);
+ assert.match(projection.metadata_sha256, /^[a-f0-9]{64}$/);
+ assert.equal(projection.observations.source_sha, SOURCE);
+ assert.equal(projection.observations.run_id, String(RUN));
+ assert.equal(projection.observations.run_attempt, '1');
+ await admit(); // Recheck official immutable source/workflow/job/attempt/artifact before releasing output.
+ } catch (_) {
+ primary = true;
+ throw new Error('FIXED_NATIVE_ARTIFACT_READOUT_FAILED_' + stage);
+ } finally {
+ if (owned) {
+ try { fs.unlinkSync(owned); }
+ catch (_) {
+ try { core.warning('FIXED_NATIVE_ARTIFACT_PRIVATE_CLEANUP_FAILED'); } catch (_) { /* retain primary */ }
+ if (!primary) throw new Error('FIXED_NATIVE_ARTIFACT_PRIVATE_CLEANUP_FAILED');
+ }
+ }
+ }
+ try { core.info(output.trim()); }
+ catch (_) { throw new Error('FIXED_NATIVE_ARTIFACT_READOUT_FAILED'); }
+}
+module.exports = { run };
diff --git a/.github/scripts/read-7158-android-startup-artifact.py b/.github/scripts/read-7158-android-startup-artifact.py
new file mode 100644
index 0000000000..d4ab793b12
--- /dev/null
+++ b/.github/scripts/read-7158-android-startup-artifact.py
@@ -0,0 +1,149 @@
+#!/usr/bin/env python3
+"""Project fixed 7158 Android startup failure facts using the unchanged 044 kernel."""
+import hashlib
+import importlib.util
+import io
+import json
+import os
+from pathlib import Path
+import stat
+import zipfile
+
+ROOT = Path(__file__).parent
+KERNEL_SHA256 = '1e9fc4370d733041fb5a48dc8c022e3461decafbf970ba030e90784208aed1d9'
+SOURCE = '3f4e8127e3698accd3760a4a039448964a5285a4'
+WORKFLOW = 'f83a9a8b182dd8276a732ee2b6338fb6f845640a'
+WORKFLOW_REF = 'KeeperCommunity/bitcoin-keeper/.github/workflows/keeper-native-diagnostic.yml@refs/pull/7158/merge'
+RUN, ATTEMPT = '40085793409', '1'
+ZIP_SIZE = 6451
+DIGEST = 'f3553f9632eff7bd25f2315c8fb0e5429132455ea0af7d5293d4e4c7cfd8fd40'
+SCOPE = 'OBSERVATIONS_ONLY_NOT_NATIVE_ACCEPTANCE_OR_CAUSE'
+PHASE = 'SELECTION'
+FIELDS = frozenset(('schema', 'source_sha', 'workflow_sha', 'workflow_ref', 'run_id', 'run_attempt',
+ 'platform', 'diagnostic_only', 'build', 'smoke', 'native_probe', 'r5_features', 'hardware', 'signing',
+ 'app_id', 'install_succeeded', 'installed_artifact_verified', 'failed_phase',
+ 'startup_diagnostics', 'startup_observation_capture',
+ 'startup_observation_cleanup'))
+OBSERVER_FIELDS = frozenset(('scope', 'collection_errors', 'logcat', 'metro', 'process', 'foreground'))
+METRO_BOOLEAN_FIELDS = frozenset(('row_limit_reached', 'emitter_cap_observed'))
+MAESTRO_TESTCASE_FAILURE = 'Maestro assertion failed: Create a passcode'
+MAESTRO_FAILURE_PATH = ('startup_diagnostics', 'maestro', 'testcase_failures')
+
+
+def require_binding():
+ import re
+ if (type(WORKFLOW) is not str or not re.fullmatch(r'[a-f0-9]{40}', WORKFLOW) or
+ type(WORKFLOW_REF) is not str or not re.fullmatch(
+ r'KeeperCommunity/bitcoin-keeper/\.github/workflows/keeper-native-diagnostic\.yml@refs/pull/[1-9][0-9]*/merge', WORKFLOW_REF) or
+ type(ZIP_SIZE) is not int or not 0 < ZIP_SIZE <= 1024 * 1024 + 4096 or
+ type(DIGEST) is not str or not re.fullmatch(r'[a-f0-9]{64}', DIGEST)):
+ raise ValueError('Exact completed artifact bindings unavailable.')
+
+
+def project(blob):
+ global PHASE
+ PHASE = 'SELECTION'
+ require_binding()
+ PHASE = 'KERNEL'
+ source = ROOT / 'read-044-android-artifact.py'
+ if hashlib.sha256(source.read_bytes()).hexdigest() != KERNEL_SHA256:
+ raise ValueError('Fixed kernel changed.')
+ spec = importlib.util.spec_from_file_location('fixed_044_android_kernel', source)
+ kernel = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(kernel)
+ literals = kernel.public_literals() # Original hash-checked policy remains unchanged.
+ kernel.SOURCE, kernel.WORKFLOW, kernel.WORKFLOW_REF = SOURCE, WORKFLOW, WORKFLOW_REF
+ kernel.RUN, kernel.ATTEMPT = RUN, ATTEMPT
+ kernel.public_literals = lambda: literals | {'onboarding-markers', 'row_limit_reached',
+ 'emitter_cap_observed', MAESTRO_TESTCASE_FAILURE, SOURCE, WORKFLOW, WORKFLOW_REF, RUN, ATTEMPT}
+ PHASE = 'ZIP_IDENTITY'
+ if type(blob) is not bytes or len(blob) != ZIP_SIZE or hashlib.sha256(blob).hexdigest() != DIGEST:
+ kernel.rejected()
+ PHASE = 'ZIP_LAYOUT'
+ with zipfile.ZipFile(io.BytesIO(blob)) as archive:
+ members = archive.infolist()
+ if len(members) != 1:
+ kernel.rejected()
+ entry = members[0]
+ if (entry.filename != 'android/metadata.json' or entry.orig_filename != entry.filename or
+ entry.flag_bits & 1 or stat.S_IFMT(entry.external_attr >> 16) not in (0, stat.S_IFREG) or
+ entry.file_size > kernel.LIMIT or entry.compress_type not in (zipfile.ZIP_STORED, zipfile.ZIP_DEFLATED)):
+ kernel.rejected()
+ raw = kernel.canonical_payload(blob, entry, archive.start_dir, archive.comment)
+ PHASE = 'JSON'
+ data = json.loads(raw, object_pairs_hook=kernel.pairs, parse_float=kernel.finite,
+ parse_constant=lambda _: kernel.rejected())
+ PHASE = 'ROOT_KEYS'
+ if type(data) is not dict or not set(data) <= kernel.ROOT_KEYS:
+ kernel.rejected()
+ projected = {key: value for key, value in data.items() if key in FIELDS}
+ PHASE = 'STARTUP'
+ if (data.get('build') != 'PASS' or data.get('smoke') != 'FAIL' or
+ data.get('native_probe') != 'NOT RUN' or data.get('r5_features') != 'NOT RUN' or
+ data.get('product_ui') is not None or
+ type(data.get('startup_diagnostics')) is not dict or
+ type(data.get('startup_observation')) is not dict):
+ kernel.rejected()
+ projected['startup_observation'] = {key: value for key, value in
+ data['startup_observation'].items() if key in OBSERVER_FIELDS}
+ if 'maestro' in projected['startup_diagnostics']:
+ maestro = projected['startup_diagnostics']['maestro']
+ if type(maestro) is not dict:
+ kernel.rejected()
+ if 'testcase_failures' in maestro:
+ failures = maestro['testcase_failures']
+ if (type(failures) is not list or len(failures) > 10 or
+ any(type(item) is not str or item != MAESTRO_TESTCASE_FAILURE for item in failures)):
+ kernel.rejected()
+ pending = [(projected, ())]
+ nodes = 0
+ while pending:
+ value, path = pending.pop()
+ nodes += 1
+ if nodes > 25000 or len(path) > 24:
+ kernel.rejected()
+ if type(value) is dict:
+ for key, item in value.items():
+ if key in METRO_BOOLEAN_FIELDS and (
+ path != ('startup_observation', 'metro') or type(item) is not bool):
+ kernel.rejected()
+ pending.append((item, (*path, key)))
+ elif type(value) is list:
+ pending.extend((item, path) for item in value)
+ elif value == MAESTRO_TESTCASE_FAILURE and path != MAESTRO_FAILURE_PATH:
+ kernel.rejected()
+ if 'metro' in projected['startup_observation'] and type(
+ projected['startup_observation']['metro']) is not dict:
+ kernel.rejected()
+ PHASE = 'PROJECTED_METADATA'
+ kernel.validate_metadata(projected)
+ return {'schema': 1, 'scope': SCOPE, 'original_zip_sha256': DIGEST,
+ 'metadata_sha256': hashlib.sha256(raw).hexdigest(), 'observations': projected}
+
+
+def main(argv=None):
+ global PHASE
+ PHASE = 'SELECTION'
+ try:
+ require_binding()
+ if argv:
+ raise ValueError('No selectors.')
+ PHASE = 'PRIVATE_FILE'
+ path = Path(os.environ['RUNNER_TEMP']) / 'r5-7158-android-startup-fixed.zip'
+ with os.fdopen(os.open(path, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK), 'rb') as source:
+ info = os.fstat(source.fileno())
+ if not stat.S_ISREG(info.st_mode) or stat.S_IMODE(info.st_mode) != 0o600 or info.st_size != ZIP_SIZE:
+ raise ValueError('Invalid private file.')
+ result = project(source.read(ZIP_SIZE + 1))
+ except Exception:
+ print('STARTUP_7158_ANDROID_OBSERVATION_READOUT_FAILED:' + PHASE)
+ return 1
+ print('STARTUP_7158_ANDROID_OBSERVATIONS_BEGIN')
+ print(json.dumps(result, sort_keys=True, separators=(',', ':')))
+ print('STARTUP_7158_ANDROID_OBSERVATIONS_END')
+ return 0
+
+
+if __name__ == '__main__':
+ import sys
+ raise SystemExit(main(sys.argv[1:]))
diff --git a/.github/scripts/read-bea-android-artifact.cjs b/.github/scripts/read-bea-android-artifact.cjs
new file mode 100644
index 0000000000..607970df97
--- /dev/null
+++ b/.github/scripts/read-bea-android-artifact.cjs
@@ -0,0 +1,126 @@
+'use strict';
+// One finite metadata projection; no native worker, release authority or selector input.
+const assert = require('node:assert/strict');
+const crypto = require('node:crypto');
+const fs = require('node:fs');
+const path = require('node:path');
+const { execFileSync } = require('node:child_process');
+const OWNER = 'KeeperCommunity', REPO = 'bitcoin-keeper';
+const RUN = 40078818062, JOB = 120835800614;
+const SOURCE = 'bea6056724dd75d1db99f4ce394ba4896edd10bf';
+const WORKFLOW = 'fbb97bfe160e4b17d52bdf67aacc3f16aeb22f99', NATIVE_HEAD_BRANCH = 'codex/r5-native-failure-continuation-20261024', WORKFLOW_PULL_REF = 'refs/pull/7154/merge', RUN_CONCLUSION = 'failure';
+// Exact terminal Android job/artifact API and upload facts.
+const ARTIFACT = 12556810367, ZIP_SIZE = 9632, DIGEST = 'c653b9d73044a8cc67cc098ff561d5a42f0a11d49013ae88dfa9edf5bf69df1b';
+const NATIVE_CONCLUSION = 'failure', STEP_CONCLUSIONS = ['success', 'failure'];
+const STEPS = ['Build development app', 'Run Android startup and native persistence probes'];
+const CONCLUSIONS = ['success', 'failure', 'skipped'];
+const NAME = `keeper-diagnostic-native-ANDROID-${SOURCE}-${RUN}-1`;
+
+async function run({ github, context, core }) {
+ let owned, primary = false, output, stage = 'SELECTION';
+ try {
+ assert.match(WORKFLOW ?? '', /^[a-f0-9]{40}$/);
+ assert.ok(typeof NATIVE_HEAD_BRANCH === 'string' && /^codex\/[a-z0-9-]+$/.test(NATIVE_HEAD_BRANCH));
+ assert.match(WORKFLOW_PULL_REF ?? '', /^refs\/pull\/[1-9][0-9]*\/merge$/);
+ assert.ok(['success', 'failure'].includes(RUN_CONCLUSION));
+ assert.ok(Number.isSafeInteger(ARTIFACT) && ARTIFACT > 0);
+ assert.ok(Number.isSafeInteger(ZIP_SIZE) && ZIP_SIZE > 0 && ZIP_SIZE <= 1024 * 1024 + 4096);
+ assert.match(DIGEST ?? '', /^[a-f0-9]{64}$/);
+ assert.ok(['success', 'failure'].includes(NATIVE_CONCLUSION));
+ assert.ok(Array.isArray(STEP_CONCLUSIONS) && STEP_CONCLUSIONS.length === STEPS.length &&
+ STEPS.every((_, index) => CONCLUSIONS.includes(STEP_CONCLUSIONS[index])));
+ assert.equal(context.repo.owner, OWNER); assert.equal(context.repo.repo, REPO);
+ assert.equal(context.eventName, 'push');
+ assert.equal(context.ref, 'refs/heads/codex/r5-bea-android-artifact-readout-20261024');
+ const args = { owner: OWNER, repo: REPO, request: { timeout: 30000 } };
+ const admit = async () => {
+ stage = 'API_LOOKUP';
+ const [r, j, a] = await Promise.all([
+ github.rest.actions.getWorkflowRun({ ...args, run_id: RUN }),
+ github.rest.actions.getJobForWorkflowRun({ ...args, job_id: JOB }),
+ github.rest.actions.getArtifact({ ...args, artifact_id: ARTIFACT }),
+ ]);
+ stage = 'RUN_BINDING';
+ assert.equal(r.data.id, RUN); assert.equal(r.data.run_attempt, 1);
+ assert.equal(r.data.repository.id, 470904030); assert.equal(r.data.head_repository.id, 470904030);
+ assert.equal(r.data.head_sha, SOURCE); assert.equal(r.data.event, 'pull_request');
+ assert.equal(r.data.head_branch, NATIVE_HEAD_BRANCH);
+ assert.equal(r.data.path, '.github/workflows/keeper-native-diagnostic.yml');
+ assert.equal(r.data.status, 'completed'); assert.equal(r.data.conclusion, RUN_CONCLUSION);
+ assert.deepEqual(r.data.referenced_workflows, [{
+ path: `${OWNER}/${REPO}/.github/workflows/keeper-native-platform.yml@${WORKFLOW}`,
+ ref: WORKFLOW_PULL_REF, sha: WORKFLOW,
+ }]);
+ stage = 'JOB_BINDING';
+ assert.equal(j.data.id, JOB); assert.equal(j.data.run_id, RUN); assert.equal(j.data.run_attempt, 1);
+ assert.equal(j.data.head_sha, SOURCE); assert.equal(j.data.status, 'completed');
+ assert.equal(j.data.conclusion, NATIVE_CONCLUSION);
+ for (const [index, name] of STEPS.entries()) {
+ const steps = j.data.steps.filter(step => step.name === name);
+ assert.equal(steps.length, 1); assert.equal(steps[0].status, 'completed');
+ assert.equal(steps[0].conclusion, STEP_CONCLUSIONS[index]);
+ }
+ const upload = j.data.steps.filter(step => step.name === 'Retain safe Phase A evidence');
+ assert.equal(upload.length, 1); assert.equal(upload[0].status, 'completed');
+ assert.equal(upload[0].conclusion, 'success');
+ stage = 'ARTIFACT_BINDING';
+ assert.equal(a.data.id, ARTIFACT); assert.equal(a.data.name, NAME);
+ assert.equal(a.data.expired, false); assert.equal(a.data.size_in_bytes, ZIP_SIZE);
+ assert.equal(a.data.digest, `sha256:${DIGEST}`);
+ assert.equal(a.data.workflow_run.id, RUN); assert.equal(a.data.workflow_run.head_sha, SOURCE);
+ assert.equal(a.data.workflow_run.repository_id, 470904030);
+ assert.equal(a.data.workflow_run.head_repository_id, 470904030);
+ };
+ await admit();
+ stage = 'DOWNLOAD';
+ const download = await github.rest.actions.downloadArtifact({ ...args, artifact_id: ARTIFACT, archive_format: 'zip' });
+ const bytes = Buffer.from(download.data);
+ assert.equal(bytes.length, ZIP_SIZE);
+ assert.equal(crypto.createHash('sha256').update(bytes).digest('hex'), DIGEST);
+ stage = 'PRIVATE_FILE';
+ const temp = process.env.RUNNER_TEMP;
+ assert.ok(temp && path.isAbsolute(temp)); assert.equal(fs.realpathSync(temp), path.resolve(temp));
+ const filename = path.join(temp, 'r5-bea-android-fixed.zip');
+ const descriptor = fs.openSync(filename, 'wx', 0o600); owned = filename;
+ try { fs.writeFileSync(descriptor, bytes); }
+ finally { fs.closeSync(descriptor); }
+ stage = 'DECODE';
+ try {
+ output = execFileSync('python3', ['-B', '.github/scripts/read-bea-android-artifact.py'],
+ { encoding: 'utf8', timeout: 30000, maxBuffer: 2 * 1024 * 1024, stdio: ['ignore', 'pipe', 'pipe'] });
+ } catch (error) {
+ const match = /^BEA_ANDROID_OBSERVATION_READOUT_FAILED:(SELECTION|PRIVATE_FILE|KERNEL|ZIP_IDENTITY|ZIP_LAYOUT|JSON|ROOT_KEYS|PRODUCT|PROJECTED_METADATA)\n$/.exec(String(error.stdout ?? ''));
+ if (match) stage = 'DECODE_' + match[1];
+ throw error;
+ }
+ stage = 'PROJECTION_FRAME';
+ const lines = output.trim().split('\n');
+ assert.equal(lines.length, 3);
+ assert.equal(lines[0], 'BEA_ANDROID_OBSERVATIONS_BEGIN');
+ assert.equal(lines[2], 'BEA_ANDROID_OBSERVATIONS_END');
+ const projection = JSON.parse(lines[1]);
+ assert.deepEqual(Object.keys(projection).sort(), ['schema', 'scope', 'original_zip_sha256', 'metadata_sha256', 'observations'].sort());
+ assert.equal(projection.schema, 1);
+ assert.equal(projection.scope, 'OBSERVATIONS_ONLY_NOT_NATIVE_ACCEPTANCE_OR_CAUSE');
+ assert.equal(projection.original_zip_sha256, DIGEST);
+ assert.match(projection.metadata_sha256, /^[a-f0-9]{64}$/);
+ assert.equal(projection.observations.source_sha, SOURCE);
+ assert.equal(projection.observations.run_id, String(RUN));
+ assert.equal(projection.observations.run_attempt, '1');
+ await admit(); // Recheck official immutable source/workflow/job/attempt/artifact before releasing output.
+ } catch (_) {
+ primary = true;
+ throw new Error('FIXED_NATIVE_ARTIFACT_READOUT_FAILED_' + stage);
+ } finally {
+ if (owned) {
+ try { fs.unlinkSync(owned); }
+ catch (_) {
+ try { core.warning('FIXED_NATIVE_ARTIFACT_PRIVATE_CLEANUP_FAILED'); } catch (_) { /* retain primary */ }
+ if (!primary) throw new Error('FIXED_NATIVE_ARTIFACT_PRIVATE_CLEANUP_FAILED');
+ }
+ }
+ }
+ try { core.info(output.trim()); }
+ catch (_) { throw new Error('FIXED_NATIVE_ARTIFACT_READOUT_FAILED'); }
+}
+module.exports = { run };
diff --git a/.github/scripts/read-bea-android-artifact.py b/.github/scripts/read-bea-android-artifact.py
new file mode 100644
index 0000000000..35a7207840
--- /dev/null
+++ b/.github/scripts/read-bea-android-artifact.py
@@ -0,0 +1,118 @@
+#!/usr/bin/env python3
+"""Project fixed bea Android failure facts using the unchanged 044 kernel."""
+import hashlib
+import importlib.util
+import io
+import json
+import os
+from pathlib import Path
+import stat
+import zipfile
+
+ROOT = Path(__file__).parent
+KERNEL_SHA256 = '1e9fc4370d733041fb5a48dc8c022e3461decafbf970ba030e90784208aed1d9'
+SOURCE = 'bea6056724dd75d1db99f4ce394ba4896edd10bf'
+WORKFLOW = 'fbb97bfe160e4b17d52bdf67aacc3f16aeb22f99'
+WORKFLOW_REF = 'KeeperCommunity/bitcoin-keeper/.github/workflows/keeper-native-diagnostic.yml@refs/pull/7154/merge'
+RUN, ATTEMPT = '40078818062', '1'
+ZIP_SIZE = 9632
+DIGEST = 'c653b9d73044a8cc67cc098ff561d5a42f0a11d49013ae88dfa9edf5bf69df1b'
+PRODUCT_STATUS = 'FAIL'
+SCOPE = 'OBSERVATIONS_ONLY_NOT_NATIVE_ACCEPTANCE_OR_CAUSE'
+PHASE = 'SELECTION'
+FIELDS = frozenset(('schema', 'source_sha', 'workflow_sha', 'workflow_ref', 'run_id', 'run_attempt',
+ 'platform', 'diagnostic_only', 'build', 'smoke', 'native_probe', 'r5_features', 'hardware', 'signing',
+ 'app_id', 'install_succeeded', 'installed_artifact_verified'))
+SAMPLE_FIELDS = frozenset(('sample', 'status', 'completed_stages', 'pin_onboarding_progress',
+ 'create_new_app_calls', 'other_backend_calls_rejected', 'failure_observation',
+ 'failed_assertion_snapshot', 'android_runtime_diagnostic'))
+
+
+def require_binding():
+ import re
+ if (type(WORKFLOW) is not str or not re.fullmatch(r'[a-f0-9]{40}', WORKFLOW) or
+ type(WORKFLOW_REF) is not str or not re.fullmatch(
+ r'KeeperCommunity/bitcoin-keeper/\.github/workflows/keeper-native-diagnostic\.yml@refs/pull/[1-9][0-9]*/merge', WORKFLOW_REF) or
+ type(ZIP_SIZE) is not int or not 0 < ZIP_SIZE <= 1024 * 1024 + 4096 or
+ type(DIGEST) is not str or not re.fullmatch(r'[a-f0-9]{64}', DIGEST) or
+ PRODUCT_STATUS not in ('PASS', 'FAIL')):
+ raise ValueError('Exact completed artifact bindings unavailable.')
+
+
+def project(blob):
+ global PHASE
+ PHASE = 'SELECTION'
+ require_binding()
+ PHASE = 'KERNEL'
+ source = ROOT / 'read-044-android-artifact.py'
+ if hashlib.sha256(source.read_bytes()).hexdigest() != KERNEL_SHA256:
+ raise ValueError('Fixed kernel changed.')
+ spec = importlib.util.spec_from_file_location('fixed_044_android_kernel', source)
+ kernel = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(kernel)
+ literals = kernel.public_literals() # Original hash-checked policy remains unchanged.
+ kernel.SOURCE, kernel.WORKFLOW, kernel.WORKFLOW_REF = SOURCE, WORKFLOW, WORKFLOW_REF
+ kernel.RUN, kernel.ATTEMPT = RUN, ATTEMPT
+ kernel.public_literals = lambda: literals | {'onboarding-markers', SOURCE, WORKFLOW, WORKFLOW_REF, RUN, ATTEMPT}
+ PHASE = 'ZIP_IDENTITY'
+ if type(blob) is not bytes or len(blob) != ZIP_SIZE or hashlib.sha256(blob).hexdigest() != DIGEST:
+ kernel.rejected()
+ PHASE = 'ZIP_LAYOUT'
+ with zipfile.ZipFile(io.BytesIO(blob)) as archive:
+ members = archive.infolist()
+ if len(members) != 1:
+ kernel.rejected()
+ entry = members[0]
+ if (entry.filename != 'android/metadata.json' or entry.orig_filename != entry.filename or
+ entry.flag_bits & 1 or stat.S_IFMT(entry.external_attr >> 16) not in (0, stat.S_IFREG) or
+ entry.file_size > kernel.LIMIT or entry.compress_type not in (zipfile.ZIP_STORED, zipfile.ZIP_DEFLATED)):
+ kernel.rejected()
+ raw = kernel.canonical_payload(blob, entry, archive.start_dir, archive.comment)
+ PHASE = 'JSON'
+ data = json.loads(raw, object_pairs_hook=kernel.pairs, parse_float=kernel.finite,
+ parse_constant=lambda _: kernel.rejected())
+ PHASE = 'ROOT_KEYS'
+ if type(data) is not dict or not set(data) <= kernel.ROOT_KEYS:
+ kernel.rejected()
+ projected = {key: value for key, value in data.items() if key in FIELDS}
+ PHASE = 'PRODUCT'
+ product = data.get('product_ui')
+ if (type(product) is not dict or product.get('status') != PRODUCT_STATUS or
+ type(product.get('samples')) is not list or not 1 <= len(product['samples']) <= 6 or
+ any(type(sample) is not dict for sample in product['samples'])):
+ kernel.rejected()
+ projected['product_ui'] = {key: product[key] for key in ('status', 'failure_category') if key in product}
+ projected['product_ui']['samples'] = [{key: value for key, value in sample.items() if key in SAMPLE_FIELDS}
+ for sample in product['samples']]
+ PHASE = 'PROJECTED_METADATA'
+ kernel.validate_metadata(projected)
+ return {'schema': 1, 'scope': SCOPE, 'original_zip_sha256': DIGEST,
+ 'metadata_sha256': hashlib.sha256(raw).hexdigest(), 'observations': projected}
+
+
+def main(argv=None):
+ global PHASE
+ PHASE = 'SELECTION'
+ try:
+ require_binding()
+ if argv:
+ raise ValueError('No selectors.')
+ PHASE = 'PRIVATE_FILE'
+ path = Path(os.environ['RUNNER_TEMP']) / 'r5-bea-android-fixed.zip'
+ with os.fdopen(os.open(path, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK), 'rb') as source:
+ info = os.fstat(source.fileno())
+ if not stat.S_ISREG(info.st_mode) or stat.S_IMODE(info.st_mode) != 0o600 or info.st_size != ZIP_SIZE:
+ raise ValueError('Invalid private file.')
+ result = project(source.read(ZIP_SIZE + 1))
+ except Exception:
+ print('BEA_ANDROID_OBSERVATION_READOUT_FAILED:' + PHASE)
+ return 1
+ print('BEA_ANDROID_OBSERVATIONS_BEGIN')
+ print(json.dumps(result, sort_keys=True, separators=(',', ':')))
+ print('BEA_ANDROID_OBSERVATIONS_END')
+ return 0
+
+
+if __name__ == '__main__':
+ import sys
+ raise SystemExit(main(sys.argv[1:]))
diff --git a/.github/scripts/read-current-android-artifact.cjs b/.github/scripts/read-current-android-artifact.cjs
new file mode 100644
index 0000000000..329444655f
--- /dev/null
+++ b/.github/scripts/read-current-android-artifact.cjs
@@ -0,0 +1,92 @@
+'use strict';
+// Read-only transport of the exact completed Android artifact selected below.
+const assert = require('node:assert/strict');
+const crypto = require('node:crypto');
+const fs = require('node:fs');
+const path = require('node:path');
+const { execFileSync } = require('node:child_process');
+const OWNER = 'KeeperCommunity', REPO = 'bitcoin-keeper';
+const RUN = 39858617273, JOB = 120125972406;
+const SOURCE = '1bc34890cb8618b2fffd446a63924974e0fe15b5';
+const WORKFLOW = '3c44ab6412a8118b183273c402dd08136db05b28';
+// Bind only from the actual completed Android job and immutable artifact APIs.
+const ARTIFACT = 12466091444, ZIP_SIZE = 8950, DIGEST = '5c3210a6b0af7bf9ea0cddb61fd1494714e8cfac0db8385960fb6390f92aa545';
+const NATIVE_CONCLUSION = 'failure', BUILD_CONCLUSION = 'success', PROBES_CONCLUSION = 'failure';
+const NAME = `keeper-diagnostic-native-ANDROID-${SOURCE}-${RUN}-1`;
+
+async function run({ github, context, core }) {
+ let owned, primary = false, output;
+ try {
+ // Check the finite selection before API, filesystem or decoder operations.
+ assert.ok(Number.isSafeInteger(ARTIFACT) && ARTIFACT > 0);
+ assert.ok(Number.isSafeInteger(ZIP_SIZE) && ZIP_SIZE > 0 && ZIP_SIZE <= 1024 * 1024 + 4096);
+ assert.match(DIGEST ?? '', /^[a-f0-9]{64}$/);
+ assert.equal(NATIVE_CONCLUSION, 'failure');
+ assert.equal(BUILD_CONCLUSION, 'success');
+ assert.equal(PROBES_CONCLUSION, 'failure');
+ assert.equal(context.repo.owner, OWNER); assert.equal(context.repo.repo, REPO);
+ assert.equal(context.eventName, 'push');
+ assert.equal(context.ref, 'refs/heads/codex/r5-current-android-artifact-byte-readout-20261022');
+ const args = { owner: OWNER, repo: REPO, request: { timeout: 30000 } };
+ const [r, j, a] = await Promise.all([
+ github.rest.actions.getWorkflowRun({ ...args, run_id: RUN }),
+ github.rest.actions.getJobForWorkflowRun({ ...args, job_id: JOB }),
+ github.rest.actions.getArtifact({ ...args, artifact_id: ARTIFACT }),
+ ]);
+ assert.equal(r.data.id, RUN); assert.equal(r.data.run_attempt, 1);
+ assert.equal(r.data.repository.id, 470904030); assert.equal(r.data.head_repository.id, 470904030);
+ assert.equal(r.data.head_sha, SOURCE); assert.equal(r.data.event, 'pull_request');
+ assert.equal(r.data.head_branch, 'codex/r5-ios-startup-diagnosis-20261022');
+ assert.equal(r.data.path, '.github/workflows/keeper-native-diagnostic.yml');
+ assert.equal(r.data.status, 'completed'); assert.equal(r.data.conclusion, 'failure');
+ assert.deepEqual(r.data.referenced_workflows, [{
+ path: `${OWNER}/${REPO}/.github/workflows/keeper-native-platform.yml@${WORKFLOW}`,
+ ref: 'refs/pull/7116/merge', sha: WORKFLOW,
+ }]);
+ assert.equal(j.data.run_attempt, 1);
+ assert.equal(j.data.id, JOB); assert.equal(j.data.run_id, RUN); assert.equal(j.data.head_sha, SOURCE);
+ assert.equal(j.data.status, 'completed'); assert.equal(j.data.conclusion, NATIVE_CONCLUSION);
+ for (const [name, conclusion] of [['Build development app', BUILD_CONCLUSION],
+ ['Run Android startup and native persistence probes', PROBES_CONCLUSION],
+ ['Retain safe Phase A evidence', 'success']]) {
+ const steps = j.data.steps.filter(step => step.name === name);
+ assert.equal(steps.length, 1); assert.equal(steps[0].status, 'completed');
+ assert.equal(steps[0].conclusion, conclusion);
+ }
+ assert.equal(a.data.id, ARTIFACT); assert.equal(a.data.name, NAME);
+ assert.equal(a.data.expired, false); assert.equal(a.data.size_in_bytes, ZIP_SIZE);
+ assert.equal(a.data.digest, `sha256:${DIGEST}`);
+ assert.equal(a.data.workflow_run.id, RUN); assert.equal(a.data.workflow_run.head_sha, SOURCE);
+ assert.equal(a.data.workflow_run.repository_id, 470904030);
+ assert.equal(a.data.workflow_run.head_repository_id, 470904030);
+ const download = await github.rest.actions.downloadArtifact({ ...args, artifact_id: ARTIFACT, archive_format: 'zip' });
+ const bytes = Buffer.from(download.data);
+ assert.equal(bytes.length, ZIP_SIZE);
+ assert.equal(crypto.createHash('sha256').update(bytes).digest('hex'), DIGEST);
+ const temp = process.env.RUNNER_TEMP;
+ assert.ok(temp && path.isAbsolute(temp));
+ assert.equal(fs.realpathSync(temp), path.resolve(temp));
+ const filename = path.join(temp, 'r5-current-android-fixed.zip');
+ const descriptor = fs.openSync(filename, 'wx', 0o600); owned = filename;
+ try { fs.writeFileSync(descriptor, bytes); }
+ finally { fs.closeSync(descriptor); }
+ output = execFileSync('python3', ['-B', '.github/scripts/read-current-android-artifact.py'],
+ { encoding: 'utf8', timeout: 30000, maxBuffer: 2 * 1024 * 1024, stdio: ['ignore', 'pipe', 'pipe'] });
+ assert.equal(output, 'FIXED_ANDROID_ARTIFACT_ZIP_BASE64_BEGIN\n' + bytes.toString('base64') +
+ '\nFIXED_ANDROID_ARTIFACT_ZIP_BASE64_END\n');
+ } catch (_) {
+ primary = true;
+ throw new Error('FIXED_NATIVE_ARTIFACT_READOUT_FAILED');
+ } finally {
+ if (owned) {
+ try { fs.unlinkSync(owned); }
+ catch (_) {
+ try { core.warning('FIXED_NATIVE_ARTIFACT_PRIVATE_CLEANUP_FAILED'); } catch (_) { /* retain primary */ }
+ if (!primary) throw new Error('FIXED_NATIVE_ARTIFACT_PRIVATE_CLEANUP_FAILED');
+ }
+ }
+ }
+ try { core.info(output.trim()); }
+ catch (_) { throw new Error('FIXED_NATIVE_ARTIFACT_READOUT_FAILED'); }
+}
+module.exports = { run };
diff --git a/.github/scripts/read-current-android-artifact.py b/.github/scripts/read-current-android-artifact.py
new file mode 100644
index 0000000000..55016498e5
--- /dev/null
+++ b/.github/scripts/read-current-android-artifact.py
@@ -0,0 +1,304 @@
+#!/usr/bin/env python3
+"""Validate one immutable metadata ZIP and transport its original bytes only."""
+import base64
+import hashlib
+import io
+import json
+import math
+import os
+from pathlib import Path
+import re
+import stat
+import struct
+import sys
+import unicodedata
+import zipfile
+import zlib
+
+SOURCE = '1bc34890cb8618b2fffd446a63924974e0fe15b5'
+WORKFLOW = '3c44ab6412a8118b183273c402dd08136db05b28'
+WORKFLOW_REF = 'KeeperCommunity/bitcoin-keeper/.github/workflows/keeper-native-diagnostic.yml@refs/pull/7116/merge'
+RUN, ATTEMPT, JOB = '39858617273', '1', '120125972406'
+# Immutable artifact and completed-job conclusions observed through the API.
+ARTIFACT = '12466091444'
+ZIP_SHA256 = '5c3210a6b0af7bf9ea0cddb61fd1494714e8cfac0db8385960fb6390f92aa545'
+ZIP_SIZE = 8950
+NATIVE_CONCLUSION = 'failure'
+BUILD_CONCLUSION = 'success'
+PROBES_CONCLUSION = 'failure'
+LIMIT = 1024 * 1024
+MAX_COMMANDS = 512
+POLICY_SHA256 = '68a022c4548babf23d95ae1c19f23077eb6b176127efbce9187bd4b5a6ab0a93'
+BEGIN = 'FIXED_ANDROID_ARTIFACT_ZIP_BASE64_BEGIN'
+END = 'FIXED_ANDROID_ARTIFACT_ZIP_BASE64_END'
+ROOT_KEYS = frozenset(('schema', 'platform', 'source_sha', 'diagnostic_only', 'workflow_ref',
+ 'workflow_sha', 'run_id', 'run_attempt', 'runner', 'os', 'commands', 'build', 'smoke',
+ 'native_probe', 'r5_features', 'hardware', 'signing', 'app_id', 'smoke_scope',
+ 'startup_timing_scope', 'artifact_policy', 'toolchain', 'disk_preflight', 'nodeify_overlay',
+ 'configuration', 'configuration_overlays', 'maestro', 'built_artifact', 'metro_warmup',
+ 'probe_bundle', 'features_bundle', 'device', 'install_succeeded',
+ 'installed_artifact_verified', 'installed_artifact_scope', 'installed_artifact',
+ 'startup_diagnostics', 'startup_observation_capture', 'failed_phase', 'startup_observation',
+ 'startup_observation_cleanup', 'startup_cleanup_errors', 'disposable_cleanup', 'cleanup_failures',
+ 'probe_diagnostics', 'probe_scope', 'smoke_test_cases', 'native_probe_test_cases',
+ 'r5_features_test_cases', 'r5_feature_evidence', 'product_ui', 'product_key_ui',
+ 'product_credential_ui', 'product_version_history_ui', 'product_vault_ui'))
+FORBIDDEN_KEYS = frozenset(('raw', 'raw_logs', 'raw_output', 'log', 'logs', 'stdout', 'stderr',
+ 'screenshot', 'screenshots', 'hierarchy', 'password', 'pin', 'seed', 'mnemonic',
+ 'credentials', 'private_key', 'token', 'sas', 'authorization', 'attributes', 'children',
+ 'text', 'accessibilitytext', 'title', 'value', 'resource-id'))
+STARTUP_FLAGS = frozenset(('credential_error', 'retry', 'logbox_controls', 'redbox_resource', 'loading'))
+PRODUCT_FLAGS = frozenset(('onboarding_skip', 'start_new_tile', 'recover_tile', 'app_settings',
+ 'start_new_text', 'welcome', 'create_passcode', 'confirm_passcode', 'login', 'welcome_back',
+ 'credential_error', 'retry', 'dismiss_control', 'minimize_control', 'allow_control',
+ 'dont_allow_control', 'logbox_error_header', 'logbox_warning_header', 'logbox_counter',
+ 'logbox_controls', 'logbox_syntax_footer', 'notification_prompt_phrase',
+ 'notification_permission_controls'))
+PRODUCT_HIERARCHY_SCOPE = 'ANY_RETAINED_SNAPSHOT_NOT_FINAL_ROUTE_OR_VISIBILITY_PROOF'
+PUBLIC_PATTERNS = tuple(re.compile(pattern) for pattern in (
+ r'[a-f0-9]{40}(?:[a-f0-9]{24})?',
+ r'[A-F0-9]{8}(?:-[A-F0-9]{4}){3}-[A-F0-9]{12}',
+ r'[0-9]{1,20}',
+ r'[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}(?:\.[0-9]{1,6})?',
+ r'[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}(?:\.[0-9]{1,6})?(?:Z|\+00:00)',
+ r'[0-9]{8}\.[0-9]{4}\.[0-9]{1,2}',
+ r'emulator-[0-9]{1,8}',
+ # Source-owned mkdtemp name, six samples and fixed companion output names.
+ r'/home/runner/work/_temp/keeper-native-private/keeper-product-ui-[a-z0-9_]{8}/'
+ r'(?:sample-[1-6]|key-ui|history-ui|vault-ui|credential-ui/'
+ r'(?:credential_fixture-(?:armed|restored)|product_credential_(?:blocked|recovered)))'
+ r'(?:/junit\.xml)?',
+))
+
+
+def rejected():
+ raise ValueError('Artifact rejected.')
+
+
+def pairs(items):
+ result = {}
+ for key, value in items:
+ if key in result:
+ rejected()
+ result[key] = value
+ return result
+
+
+def finite(value):
+ value = float(value)
+ if not math.isfinite(value):
+ rejected()
+ return value
+
+
+def public_literals():
+ raw = Path(__file__).with_name('current-android-metadata-policy.json').read_bytes()
+ if len(raw) > 65536 or hashlib.sha256(raw).hexdigest() != POLICY_SHA256:
+ rejected()
+ policy = json.loads(raw, object_pairs_hook=pairs)
+ if policy['source_sha'] != SOURCE:
+ rejected()
+ return frozenset(policy['public_literals']) | {SOURCE, WORKFLOW, WORKFLOW_REF, RUN, ATTEMPT, JOB}
+
+
+def validate_hierarchy(value, product=False):
+ # These are exported fixed flags, never a TreeNode/UI attribute tree.
+ if value is None:
+ return
+ if type(value) is not dict:
+ rejected()
+ if not product:
+ if (set(value) != STARTUP_FLAGS | {'snapshot_count'} or
+ type(value['snapshot_count']) is not int or not 0 <= value['snapshot_count'] <= 8 or
+ any(value[name] is not None and type(value[name]) is not bool for name in STARTUP_FLAGS)):
+ rejected()
+ return
+ fields = {'state', 'snapshot_count', 'node_count', 'rejected_snapshots',
+ 'snapshot_limit_exceeded', 'scope', 'flags'}
+ if (set(value) != fields or value['scope'] != PRODUCT_HIERARCHY_SCOPE or
+ value['state'] not in ('UNKNOWN', 'COMPLETE', 'PARTIAL') or
+ any(type(value[name]) is not int or not 0 <= value[name] <= maximum for name, maximum in
+ (('snapshot_count', 8), ('node_count', 80000), ('rejected_snapshots', 8))) or
+ type(value['snapshot_limit_exceeded']) is not bool or type(value['flags']) is not dict or
+ set(value['flags']) != PRODUCT_FLAGS or
+ any(flag is not None and type(flag) is not bool for flag in value['flags'].values())):
+ rejected()
+
+
+def validate_metadata(data, expected=None):
+ """No reconstruction: accept reviewed public vocabulary or reject the whole ZIP."""
+ identity = {'schema': 1, 'source_sha': SOURCE, 'workflow_sha': WORKFLOW,
+ 'workflow_ref': WORKFLOW_REF, 'run_id': RUN, 'run_attempt': ATTEMPT,
+ 'platform': 'ANDROID', 'diagnostic_only': True} if expected is None else expected
+ if (type(data) is not dict or not set(data) <= ROOT_KEYS or
+ any(type(data.get(key)) is not type(value) or data.get(key) != value
+ for key, value in identity.items())):
+ rejected()
+ for key in ('build', 'smoke', 'native_probe', 'r5_features', 'hardware', 'signing'):
+ if key in data and data[key] not in ('PASS', 'FAIL', 'NOT RUN', 'RUNNING', 'UNKNOWN', None):
+ rejected()
+ for key in ('runner', 'toolchain', 'maestro', 'built_artifact', 'device',
+ 'installed_artifact', 'startup_diagnostics', 'driver_preflight', 'startup_observation'):
+ if key in data and data[key] is not None and type(data[key]) is not dict:
+ rejected()
+ if 'commands' in data and (type(data['commands']) is not list or len(data['commands']) > MAX_COMMANDS):
+ rejected()
+ fields = {'label', 'command', 'timeout_seconds', 'exit_code', 'duration_seconds'}
+ for row in data.get('commands', []):
+ if (type(row) is not dict or not fields <= set(row) or
+ not set(row) <= fields | {'diagnostic', 'redacted_tool_errors'} or
+ type(row['label']) is not str or type(row['command']) is not list or
+ not 1 <= len(row['command']) <= 64 or
+ any(type(argument) is not str for argument in row['command'])):
+ rejected()
+ literals = public_literals()
+ nodes = 0
+
+ def walk(value, depth=0, path=()):
+ nonlocal nodes
+ nodes += 1
+ if depth > 24 or nodes > 25000:
+ rejected()
+ if type(value) is dict:
+ if len(value) > 256:
+ rejected()
+ for key, item in value.items():
+ safe_hierarchy = key == 'hierarchy' and path in (('startup_observation',),
+ ('product_ui', 'samples', 'failure_observation'),
+ ('product_ui', 'controlled_disconnect_retry', 'failure_observation'))
+ safe_sdk_key = path == ('toolchain', 'observed_android_sdk') and key in (
+ 'platforms/android-36', 'build-tools/35.0.0', 'ndk/27.1.12297006')
+ if (type(key) is not str or not (safe_sdk_key or
+ re.fullmatch(r'[A-Za-z_][A-Za-z0-9_.-]{0,80}', key)) or
+ key not in literals or
+ key.lower() in FORBIDDEN_KEYS and not safe_hierarchy):
+ rejected()
+ if safe_hierarchy:
+ validate_hierarchy(item, product=path != ('startup_observation',))
+ walk(item, depth + 1, (*path, key))
+ elif type(value) is list:
+ if len(value) > 1024:
+ rejected()
+ for item in value:
+ walk(item, depth + 1, path)
+ elif type(value) is str:
+ if (any((unicodedata.category(char) in ('Cc', 'Cf', 'Zl', 'Zp') and char not in '\n\t')
+ for char in value) or len(value) > 4096 or value not in literals and
+ not any(pattern.fullmatch(value) for pattern in PUBLIC_PATTERNS)):
+ rejected()
+ elif type(value) in (int, float):
+ if not math.isfinite(value) or abs(value) > 2 ** 53 - 1:
+ rejected()
+ elif value is not None and type(value) is not bool:
+ rejected()
+ walk(data)
+
+
+def canonical_payload(blob, entry, start_dir, comment):
+ """Every original byte belongs to one ordinary ZIP entry, directory or EOCD."""
+ if (comment or entry.comment or entry.extra or entry.header_offset != 0 or
+ entry.flag_bits not in (0, 8) or entry.compress_size > LIMIT + 4096):
+ rejected()
+ local = struct.unpack_from('<4s5H3I2H', blob)
+ signature, version, flags, method, mtime, mdate, crc, compressed, size, namesize, extrasize = local
+ name = b'android/metadata.json'
+ if (signature != b'PK\x03\x04' or version != 20 or flags != entry.flag_bits or
+ method != entry.compress_type or namesize != len(name) or extrasize or
+ blob[30:30 + namesize] != name):
+ rejected()
+ begin = 30 + namesize
+ end = begin + entry.compress_size
+ if flags == 8:
+ if (crc, compressed, size) != (0, 0, 0):
+ rejected()
+ if struct.unpack_from('<4s3I', blob, end) != (b'PK\x07\x08', entry.CRC, entry.compress_size, entry.file_size):
+ rejected()
+ central = end + 16
+ else:
+ if (crc, compressed, size) != (entry.CRC, entry.compress_size, entry.file_size):
+ rejected()
+ central = end
+ # No hidden gaps, extra fields, comments, second entries, prefix or suffix.
+ fields = struct.unpack_from('<4s6H3I5H2I', blob, central)
+ if (start_dir != central or fields[0] != b'PK\x01\x02' or fields[2:10] !=
+ (version, flags, method, mtime, mdate, entry.CRC, entry.compress_size, entry.file_size) or
+ fields[10:15] != (len(name), 0, 0, 0, 0) or fields[16] != 0 or
+ blob[central + 46:central + 46 + len(name)] != name):
+ rejected()
+ directory_size = 46 + len(name)
+ finish = central + directory_size
+ if (len(blob) != finish + 22 or struct.unpack_from('<4s4H2IH', blob, finish) !=
+ (b'PK\x05\x06', 0, 0, 1, 1, directory_size, central, 0)):
+ rejected()
+ payload = blob[begin:end]
+ if method == zipfile.ZIP_DEFLATED:
+ inflater = zlib.decompressobj(-15)
+ raw = inflater.decompress(payload, LIMIT + 1)
+ if not inflater.eof or inflater.unused_data or inflater.unconsumed_tail:
+ rejected()
+ else:
+ raw = payload
+ if len(raw) != entry.file_size or zlib.crc32(raw) != entry.CRC:
+ rejected()
+ return raw
+
+
+def validate_archive(blob, expected=None):
+ if type(blob) is not bytes or len(blob) > LIMIT + 4096:
+ rejected()
+ with zipfile.ZipFile(io.BytesIO(blob)) as archive:
+ members = archive.infolist()
+ if len(members) != 1:
+ rejected()
+ entry = members[0]
+ if (entry.filename != 'android/metadata.json' or entry.orig_filename != entry.filename or
+ entry.flag_bits & 1 or stat.S_IFMT(entry.external_attr >> 16) not in (0, stat.S_IFREG) or
+ entry.file_size > LIMIT or entry.compress_type not in (zipfile.ZIP_STORED, zipfile.ZIP_DEFLATED)):
+ rejected()
+ raw = canonical_payload(blob, entry, archive.start_dir, archive.comment)
+ if len(raw) > LIMIT or len(raw) != entry.file_size:
+ rejected()
+ data = json.loads(raw, object_pairs_hook=pairs, parse_float=finite, parse_constant=lambda _: rejected())
+ validate_metadata(data, expected)
+
+
+def require_binding():
+ # This finite conclusion tuple must match the completed selected job.
+ if (type(ARTIFACT) is not str or not re.fullmatch(r'[1-9][0-9]{0,19}', ARTIFACT) or
+ type(ZIP_SHA256) is not str or not re.fullmatch(r'[a-f0-9]{64}', ZIP_SHA256) or
+ type(ZIP_SIZE) is not int or not 0 < ZIP_SIZE <= LIMIT + 4096 or
+ (NATIVE_CONCLUSION, BUILD_CONCLUSION, PROBES_CONCLUSION) !=
+ ('failure', 'success', 'failure')):
+ rejected()
+
+
+def checked_bytes(path):
+ require_binding()
+ with os.fdopen(os.open(path, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK), 'rb') as source:
+ info = os.fstat(source.fileno())
+ if not stat.S_ISREG(info.st_mode) or stat.S_IMODE(info.st_mode) != 0o600 or info.st_size != ZIP_SIZE:
+ rejected()
+ blob = source.read(ZIP_SIZE + 1)
+ if len(blob) != ZIP_SIZE or hashlib.sha256(blob).hexdigest() != ZIP_SHA256:
+ rejected()
+ validate_archive(blob)
+ return blob
+
+
+def main(argv=None):
+ try:
+ if sys.argv[1:] if argv is None else argv:
+ rejected()
+ require_binding()
+ blob = checked_bytes(Path(os.environ['RUNNER_TEMP']) / 'r5-current-android-fixed.zip')
+ except Exception:
+ print('FIXED_ANDROID_ARTIFACT_BYTE_READOUT_FAILED')
+ return 1
+ print(BEGIN)
+ print(base64.b64encode(blob).decode('ascii'))
+ print(END)
+ return 0
+
+
+if __name__ == '__main__':
+ raise SystemExit(main())
diff --git a/.github/scripts/read-current-ios-artifact.cjs b/.github/scripts/read-current-ios-artifact.cjs
new file mode 100644
index 0000000000..8f1b636e98
--- /dev/null
+++ b/.github/scripts/read-current-ios-artifact.cjs
@@ -0,0 +1,83 @@
+'use strict';
+// Transport one immutable reviewed metadata-only ZIP after validation. No native/release/provider operation.
+const assert = require('node:assert/strict');
+const crypto = require('node:crypto');
+const fs = require('node:fs');
+const path = require('node:path');
+const { execFileSync } = require('node:child_process');
+const OWNER = 'KeeperCommunity', REPO = 'bitcoin-keeper';
+const RUN = 39858617273, JOB = 120103187854, ARTIFACT = 12462694619;
+const SOURCE = '1bc34890cb8618b2fffd446a63924974e0fe15b5';
+const WORKFLOW = '3c44ab6412a8118b183273c402dd08136db05b28';
+const DIGEST = '550142809a0faf812741a586630b17d6f458b2b6c935b5bab4b00f84da67c84f';
+const NAME = `keeper-diagnostic-native-IOS-${SOURCE}-${RUN}-1`;
+
+async function run({ github, context, core }) {
+ let owned, primary = false, output;
+ try {
+ assert.equal(context.repo.owner, OWNER); assert.equal(context.repo.repo, REPO);
+ assert.equal(context.eventName, 'push');
+ assert.equal(context.ref, 'refs/heads/codex/r5-current-ios-artifact-byte-readout-20261022');
+ const args = { owner: OWNER, repo: REPO, request: { timeout: 30000 } };
+ const [r, j, a] = await Promise.all([
+ github.rest.actions.getWorkflowRun({ ...args, run_id: RUN }),
+ github.rest.actions.getJobForWorkflowRun({ ...args, job_id: JOB }),
+ github.rest.actions.getArtifact({ ...args, artifact_id: ARTIFACT }),
+ ]);
+ assert.equal(r.data.id, RUN); assert.equal(r.data.run_attempt, 1);
+ assert.equal(r.data.repository.id, 470904030); assert.equal(r.data.head_repository.id, 470904030);
+ assert.equal(r.data.head_sha, SOURCE); assert.equal(r.data.event, 'pull_request');
+ assert.equal(r.data.head_branch, 'codex/r5-ios-startup-diagnosis-20261022');
+ assert.equal(r.data.path, '.github/workflows/keeper-native-diagnostic.yml');
+ assert.ok((r.data.status === 'in_progress' && r.data.conclusion === null) ||
+ (r.data.status === 'completed' && r.data.conclusion === 'failure')); // Android may continue.
+ assert.deepEqual(r.data.referenced_workflows, [{
+ path: `${OWNER}/${REPO}/.github/workflows/keeper-native-platform.yml@${WORKFLOW}`,
+ ref: 'refs/pull/7116/merge', sha: WORKFLOW,
+ }]);
+ assert.equal(j.data.run_attempt, 1);
+ assert.equal(j.data.id, JOB); assert.equal(j.data.run_id, RUN); assert.equal(j.data.head_sha, SOURCE);
+ assert.equal(j.data.status, 'completed'); assert.equal(j.data.conclusion, 'failure');
+ for (const [name, conclusion] of [['Build development app', 'success'],
+ ['Run disposable startup smoke', 'failure'], ['Retain safe Phase A evidence', 'success']]) {
+ const steps = j.data.steps.filter(step => step.name === name);
+ assert.equal(steps.length, 1); assert.equal(steps[0].status, 'completed');
+ assert.equal(steps[0].conclusion, conclusion);
+ }
+ assert.equal(a.data.id, ARTIFACT); assert.equal(a.data.name, NAME);
+ assert.equal(a.data.expired, false); assert.equal(a.data.size_in_bytes, 6884);
+ assert.equal(a.data.digest, `sha256:${DIGEST}`);
+ assert.equal(a.data.workflow_run.id, RUN); assert.equal(a.data.workflow_run.head_sha, SOURCE);
+ assert.equal(a.data.workflow_run.repository_id, 470904030);
+ assert.equal(a.data.workflow_run.head_repository_id, 470904030);
+ const download = await github.rest.actions.downloadArtifact({ ...args, artifact_id: ARTIFACT, archive_format: 'zip' });
+ const bytes = Buffer.from(download.data);
+ assert.equal(bytes.length, 6884);
+ assert.equal(crypto.createHash('sha256').update(bytes).digest('hex'), DIGEST);
+ const temp = process.env.RUNNER_TEMP;
+ assert.ok(temp && path.isAbsolute(temp));
+ assert.equal(fs.realpathSync(temp), path.resolve(temp));
+ const filename = path.join(temp, 'r5-current-ios-fixed.zip');
+ const descriptor = fs.openSync(filename, 'wx', 0o600); owned = filename;
+ try { fs.writeFileSync(descriptor, bytes); }
+ finally { fs.closeSync(descriptor); }
+ output = execFileSync('python3', ['-B', '.github/scripts/read-current-ios-artifact.py'],
+ { encoding: 'utf8', timeout: 30000, maxBuffer: 1024 * 1024, stdio: ['ignore', 'pipe', 'pipe'] });
+ assert.equal(output, 'FIXED_IOS_ARTIFACT_ZIP_BASE64_BEGIN\n' + bytes.toString('base64') +
+ '\nFIXED_IOS_ARTIFACT_ZIP_BASE64_END\n');
+ } catch (_) {
+ primary = true;
+ throw new Error('FIXED_NATIVE_ARTIFACT_READOUT_FAILED');
+ } finally {
+ if (owned) {
+ try { fs.unlinkSync(owned); }
+ catch (_) {
+ try { core.warning('FIXED_NATIVE_ARTIFACT_PRIVATE_CLEANUP_FAILED'); } catch (_) { /* retain primary */ }
+ if (!primary) throw new Error('FIXED_NATIVE_ARTIFACT_PRIVATE_CLEANUP_FAILED');
+ }
+ }
+ }
+ try { core.info(output.trim()); } // Original validated metadata ZIP bytes; never decoded metadata or native logs.
+ catch (_) { throw new Error('FIXED_NATIVE_ARTIFACT_READOUT_FAILED'); }
+}
+module.exports = { run };
diff --git a/.github/scripts/read-current-ios-artifact.py b/.github/scripts/read-current-ios-artifact.py
new file mode 100644
index 0000000000..2e39ff748c
--- /dev/null
+++ b/.github/scripts/read-current-ios-artifact.py
@@ -0,0 +1,247 @@
+#!/usr/bin/env python3
+"""Validate one immutable metadata ZIP and transport its original bytes only."""
+import base64
+import hashlib
+import io
+import json
+import math
+import os
+from pathlib import Path
+import re
+import stat
+import struct
+import sys
+import unicodedata
+import zipfile
+import zlib
+
+SOURCE = '1bc34890cb8618b2fffd446a63924974e0fe15b5'
+WORKFLOW = '3c44ab6412a8118b183273c402dd08136db05b28'
+WORKFLOW_REF = 'KeeperCommunity/bitcoin-keeper/.github/workflows/keeper-native-diagnostic.yml@refs/pull/7116/merge'
+RUN, ATTEMPT, ARTIFACT = '39858617273', '1', '12462694619'
+ZIP_SHA256 = '550142809a0faf812741a586630b17d6f458b2b6c935b5bab4b00f84da67c84f'
+ZIP_SIZE, LIMIT = 6884, 1024 * 1024
+POLICY_SHA256 = 'ab720280a30f521ff0aed139f376bdabcba295632d3081b6dbeb21fb5e9a830c'
+BEGIN = 'FIXED_IOS_ARTIFACT_ZIP_BASE64_BEGIN'
+END = 'FIXED_IOS_ARTIFACT_ZIP_BASE64_END'
+ROOT_KEYS = frozenset(('schema', 'platform', 'source_sha', 'diagnostic_only', 'workflow_ref',
+ 'workflow_sha', 'run_id', 'run_attempt', 'runner', 'os', 'commands', 'build', 'smoke',
+ 'native_probe', 'r5_features', 'hardware', 'signing', 'app_id', 'smoke_scope',
+ 'startup_timing_scope', 'artifact_policy', 'toolchain', 'disk_preflight', 'nodeify_overlay',
+ 'configuration', 'configuration_overlays', 'maestro', 'simulator_app_service_readiness',
+ 'driver_preflight', 'built_artifact', 'metro_warmup', 'install_diagnoses', 'device',
+ 'install_succeeded', 'installed_artifact_verified', 'installed_artifact_scope',
+ 'installed_artifact', 'startup_diagnostics', 'startup_observation_capture', 'failed_phase',
+ 'startup_observation', 'startup_observation_cleanup', 'startup_cleanup_errors',
+ 'disposable_cleanup', 'cleanup_failures'))
+FORBIDDEN_KEYS = frozenset(('raw', 'raw_logs', 'raw_output', 'log', 'logs', 'stdout', 'stderr',
+ 'screenshot', 'screenshots', 'hierarchy', 'password', 'pin', 'seed', 'mnemonic',
+ 'credentials', 'private_key', 'token', 'sas', 'authorization'))
+PUBLIC_PATTERNS = tuple(re.compile(pattern) for pattern in (
+ r'[a-f0-9]{40}(?:[a-f0-9]{24})?',
+ r'[A-F0-9]{8}(?:-[A-F0-9]{4}){3}-[A-F0-9]{12}',
+ r'[0-9]{1,20}',
+ r'[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}(?:\.[0-9]{1,6})?',
+ r'[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}(?:\.[0-9]{1,6})?(?:Z|\+00:00)',
+ r'[0-9]{8}\.[0-9]{4}\.[0-9]{1,2}',
+))
+
+
+def rejected():
+ raise ValueError('Artifact rejected.')
+
+
+def pairs(items):
+ result = {}
+ for key, value in items:
+ if key in result:
+ rejected()
+ result[key] = value
+ return result
+
+
+def finite(value):
+ value = float(value)
+ if not math.isfinite(value):
+ rejected()
+ return value
+
+
+def public_literals():
+ raw = Path(__file__).with_name('current-ios-metadata-policy.json').read_bytes()
+ if len(raw) > 65536 or hashlib.sha256(raw).hexdigest() != POLICY_SHA256:
+ rejected()
+ policy = json.loads(raw, object_pairs_hook=pairs)
+ if policy['source_sha'] != SOURCE:
+ rejected()
+ return frozenset(policy['public_literals']) | {SOURCE, WORKFLOW, WORKFLOW_REF, RUN, ATTEMPT,
+ 'private_startup-logcat', 'private_startup-observer', 'private_startup-foreground'}
+
+
+def validate_metadata(data, expected=None):
+ """No reconstruction: accept reviewed public vocabulary or reject the whole ZIP."""
+ identity = {'schema': 1, 'source_sha': SOURCE, 'workflow_sha': WORKFLOW,
+ 'workflow_ref': WORKFLOW_REF, 'run_id': RUN, 'run_attempt': ATTEMPT,
+ 'platform': 'IOS', 'diagnostic_only': True} if expected is None else expected
+ if (type(data) is not dict or not set(data) <= ROOT_KEYS or
+ any(type(data.get(key)) is not type(value) or data.get(key) != value
+ for key, value in identity.items())):
+ rejected()
+ for key in ('build', 'smoke', 'native_probe', 'r5_features', 'hardware', 'signing'):
+ if key in data and data[key] not in ('PASS', 'FAIL', 'NOT RUN', 'RUNNING', 'UNKNOWN', None):
+ rejected()
+ for key in ('runner', 'toolchain', 'maestro', 'built_artifact', 'device',
+ 'installed_artifact', 'startup_diagnostics', 'driver_preflight', 'startup_observation'):
+ if key in data and data[key] is not None and type(data[key]) is not dict:
+ rejected()
+ if 'commands' in data and (type(data['commands']) is not list or len(data['commands']) > 100):
+ rejected()
+ fields = {'label', 'command', 'timeout_seconds', 'exit_code', 'duration_seconds'}
+ for row in data.get('commands', []):
+ if (type(row) is not dict or not fields <= set(row) or
+ not set(row) <= fields | {'diagnostic', 'redacted_tool_errors'} or
+ type(row['label']) is not str or type(row['command']) is not list or
+ not 1 <= len(row['command']) <= 64 or
+ any(type(argument) is not str for argument in row['command'])):
+ rejected()
+ literals = public_literals()
+ nodes = 0
+
+ def walk(value, depth=0, path=()):
+ nonlocal nodes
+ nodes += 1
+ if depth > 24 or nodes > 25000:
+ rejected()
+ if type(value) is dict:
+ if len(value) > 256:
+ rejected()
+ for key, item in value.items():
+ safe_hierarchy = key == 'hierarchy' and path == ('startup_observation',)
+ if (type(key) is not str or not re.fullmatch(r'[A-Za-z_][A-Za-z0-9_-]{0,80}', key) or
+ key not in literals or
+ key.lower() in FORBIDDEN_KEYS and not safe_hierarchy):
+ rejected()
+ if safe_hierarchy:
+ flags = {'credential_error', 'retry', 'logbox_controls', 'redbox_resource', 'loading',
+ 'login', 'welcome_back', 'logbox_error_header', 'logbox_warning_header',
+ 'logbox_syntax_footer', 'logbox_counter'}
+ if (type(item) is not dict or set(item) != flags | {'observation_state', 'snapshot_count'} or
+ item['observation_state'] not in ('UNKNOWN', 'SNAPSHOTS_PARSED') or
+ type(item['snapshot_count']) is not int or not 0 <= item['snapshot_count'] <= 8 or
+ any(item[name] is not None and type(item[name]) is not bool for name in flags)):
+ rejected()
+ walk(item, depth + 1, (*path, key))
+ elif type(value) is list:
+ if len(value) > 1024:
+ rejected()
+ for item in value:
+ walk(item, depth + 1, path)
+ elif type(value) is str:
+ if (any((unicodedata.category(char) in ('Cc', 'Cf', 'Zl', 'Zp') and char not in '\n\t')
+ for char in value) or len(value) > 4096 or value not in literals and
+ not any(pattern.fullmatch(value) for pattern in PUBLIC_PATTERNS)):
+ rejected()
+ elif type(value) in (int, float):
+ if not math.isfinite(value) or abs(value) > 2 ** 53 - 1:
+ rejected()
+ elif value is not None and type(value) is not bool:
+ rejected()
+ walk(data)
+
+
+def canonical_payload(blob, entry, start_dir, comment):
+ """Every original byte belongs to one ordinary ZIP entry, directory or EOCD."""
+ if (comment or entry.comment or entry.extra or entry.header_offset != 0 or
+ entry.flag_bits not in (0, 8) or entry.compress_size > LIMIT + 4096):
+ rejected()
+ local = struct.unpack_from('<4s5H3I2H', blob)
+ signature, version, flags, method, mtime, mdate, crc, compressed, size, namesize, extrasize = local
+ name = b'ios/metadata.json'
+ if (signature != b'PK\x03\x04' or version != 20 or flags != entry.flag_bits or
+ method != entry.compress_type or namesize != len(name) or extrasize or
+ blob[30:30 + namesize] != name):
+ rejected()
+ begin = 30 + namesize
+ end = begin + entry.compress_size
+ if flags == 8:
+ if (crc, compressed, size) != (0, 0, 0):
+ rejected()
+ if struct.unpack_from('<4s3I', blob, end) != (b'PK\x07\x08', entry.CRC, entry.compress_size, entry.file_size):
+ rejected()
+ central = end + 16
+ else:
+ if (crc, compressed, size) != (entry.CRC, entry.compress_size, entry.file_size):
+ rejected()
+ central = end
+ # No hidden gaps, extra fields, comments, second entries, prefix or suffix.
+ fields = struct.unpack_from('<4s6H3I5H2I', blob, central)
+ if (start_dir != central or fields[0] != b'PK\x01\x02' or fields[2:10] !=
+ (version, flags, method, mtime, mdate, entry.CRC, entry.compress_size, entry.file_size) or
+ fields[10:15] != (len(name), 0, 0, 0, 0) or fields[16] != 0 or
+ blob[central + 46:central + 46 + len(name)] != name):
+ rejected()
+ directory_size = 46 + len(name)
+ finish = central + directory_size
+ if (len(blob) != finish + 22 or struct.unpack_from('<4s4H2IH', blob, finish) !=
+ (b'PK\x05\x06', 0, 0, 1, 1, directory_size, central, 0)):
+ rejected()
+ payload = blob[begin:end]
+ if method == zipfile.ZIP_DEFLATED:
+ inflater = zlib.decompressobj(-15)
+ raw = inflater.decompress(payload, LIMIT + 1)
+ if not inflater.eof or inflater.unused_data or inflater.unconsumed_tail:
+ rejected()
+ else:
+ raw = payload
+ if len(raw) != entry.file_size or zlib.crc32(raw) != entry.CRC:
+ rejected()
+ return raw
+
+
+def validate_archive(blob, expected=None):
+ if type(blob) is not bytes or len(blob) > LIMIT + 4096:
+ rejected()
+ with zipfile.ZipFile(io.BytesIO(blob)) as archive:
+ members = archive.infolist()
+ if len(members) != 1:
+ rejected()
+ entry = members[0]
+ if (entry.filename != 'ios/metadata.json' or entry.orig_filename != entry.filename or
+ entry.flag_bits & 1 or stat.S_IFMT(entry.external_attr >> 16) not in (0, stat.S_IFREG) or
+ entry.file_size > LIMIT or entry.compress_type not in (zipfile.ZIP_STORED, zipfile.ZIP_DEFLATED)):
+ rejected()
+ raw = canonical_payload(blob, entry, archive.start_dir, archive.comment)
+ if len(raw) > LIMIT or len(raw) != entry.file_size:
+ rejected()
+ data = json.loads(raw, object_pairs_hook=pairs, parse_float=finite, parse_constant=lambda _: rejected())
+ validate_metadata(data, expected)
+
+
+def checked_bytes(path):
+ with os.fdopen(os.open(path, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK), 'rb') as source:
+ info = os.fstat(source.fileno())
+ if not stat.S_ISREG(info.st_mode) or stat.S_IMODE(info.st_mode) != 0o600 or info.st_size != ZIP_SIZE:
+ rejected()
+ blob = source.read(ZIP_SIZE + 1)
+ if len(blob) != ZIP_SIZE or hashlib.sha256(blob).hexdigest() != ZIP_SHA256:
+ rejected()
+ validate_archive(blob)
+ return blob
+
+
+def main(argv=None):
+ try:
+ if sys.argv[1:] if argv is None else argv:
+ rejected()
+ blob = checked_bytes(Path(os.environ['RUNNER_TEMP']) / 'r5-current-ios-fixed.zip')
+ except Exception:
+ print('FIXED_IOS_ARTIFACT_BYTE_READOUT_FAILED')
+ return 1
+ print(BEGIN)
+ print(base64.b64encode(blob).decode('ascii'))
+ print(END)
+ return 0
+
+
+if __name__ == '__main__':
+ raise SystemExit(main())
diff --git a/.github/scripts/read-d270-android-artifact.cjs b/.github/scripts/read-d270-android-artifact.cjs
new file mode 100644
index 0000000000..0dea666a69
--- /dev/null
+++ b/.github/scripts/read-d270-android-artifact.cjs
@@ -0,0 +1,122 @@
+'use strict';
+// One finite metadata projection; no native worker, release authority or selector input.
+const assert = require('node:assert/strict');
+const crypto = require('node:crypto');
+const fs = require('node:fs');
+const path = require('node:path');
+const { execFileSync } = require('node:child_process');
+const OWNER = 'KeeperCommunity', REPO = 'bitcoin-keeper';
+const RUN = 40065599904, JOB = 120796675691;
+const SOURCE = 'd27007078808617a97ee460b592eefb44e7e5325';
+const WORKFLOW = 'f5f20e6d959109cdc2e0096099992d72307255bf';
+// Exact terminal Android job/artifact API and upload facts.
+const ARTIFACT = 12551461839, ZIP_SIZE = 9596, DIGEST = 'b9182e02a33b7e0568d73654b42d61f66bce8e425d65a6960aa0f4f2194ee13a';
+const NATIVE_CONCLUSION = 'failure', STEP_CONCLUSIONS = ['success', 'failure'];
+const STEPS = ['Build development app', 'Run Android startup and native persistence probes'];
+const CONCLUSIONS = ['success', 'failure', 'skipped'];
+const NAME = `keeper-diagnostic-native-ANDROID-${SOURCE}-${RUN}-1`;
+
+async function run({ github, context, core }) {
+ let owned, primary = false, output, stage = 'SELECTION';
+ try {
+ assert.ok(Number.isSafeInteger(ARTIFACT) && ARTIFACT > 0);
+ assert.ok(Number.isSafeInteger(ZIP_SIZE) && ZIP_SIZE > 0 && ZIP_SIZE <= 1024 * 1024 + 4096);
+ assert.match(DIGEST ?? '', /^[a-f0-9]{64}$/);
+ assert.ok(['success', 'failure'].includes(NATIVE_CONCLUSION));
+ assert.ok(Array.isArray(STEP_CONCLUSIONS) && STEP_CONCLUSIONS.length === STEPS.length &&
+ STEPS.every((_, index) => CONCLUSIONS.includes(STEP_CONCLUSIONS[index])));
+ assert.equal(context.repo.owner, OWNER); assert.equal(context.repo.repo, REPO);
+ assert.equal(context.eventName, 'push');
+ assert.equal(context.ref, 'refs/heads/codex/r5-d270-android-artifact-readout-20261024');
+ const args = { owner: OWNER, repo: REPO, request: { timeout: 30000 } };
+ const admit = async () => {
+ stage = 'API_LOOKUP';
+ const [r, j, a] = await Promise.all([
+ github.rest.actions.getWorkflowRun({ ...args, run_id: RUN }),
+ github.rest.actions.getJobForWorkflowRun({ ...args, job_id: JOB }),
+ github.rest.actions.getArtifact({ ...args, artifact_id: ARTIFACT }),
+ ]);
+ stage = 'RUN_BINDING';
+ assert.equal(r.data.id, RUN); assert.equal(r.data.run_attempt, 1);
+ assert.equal(r.data.repository.id, 470904030); assert.equal(r.data.head_repository.id, 470904030);
+ assert.equal(r.data.head_sha, SOURCE); assert.equal(r.data.event, 'pull_request');
+ assert.equal(r.data.head_branch, 'codex/r5-native-acceptance-20261024');
+ assert.equal(r.data.path, '.github/workflows/keeper-native-diagnostic.yml');
+ assert.equal(r.data.status, 'completed'); assert.equal(r.data.conclusion, 'failure');
+ assert.deepEqual(r.data.referenced_workflows, [{
+ path: `${OWNER}/${REPO}/.github/workflows/keeper-native-platform.yml@${WORKFLOW}`,
+ ref: 'refs/pull/7149/merge', sha: WORKFLOW,
+ }]);
+ stage = 'JOB_BINDING';
+ assert.equal(j.data.id, JOB); assert.equal(j.data.run_id, RUN); assert.equal(j.data.run_attempt, 1);
+ assert.equal(j.data.head_sha, SOURCE); assert.equal(j.data.status, 'completed');
+ assert.equal(j.data.conclusion, NATIVE_CONCLUSION);
+ for (const [index, name] of STEPS.entries()) {
+ const steps = j.data.steps.filter(step => step.name === name);
+ assert.equal(steps.length, 1); assert.equal(steps[0].status, 'completed');
+ assert.equal(steps[0].conclusion, STEP_CONCLUSIONS[index]);
+ }
+ const upload = j.data.steps.filter(step => step.name === 'Retain safe Phase A evidence');
+ assert.equal(upload.length, 1); assert.equal(upload[0].status, 'completed');
+ assert.equal(upload[0].conclusion, 'success');
+ stage = 'ARTIFACT_BINDING';
+ assert.equal(a.data.id, ARTIFACT); assert.equal(a.data.name, NAME);
+ assert.equal(a.data.expired, false); assert.equal(a.data.size_in_bytes, ZIP_SIZE);
+ assert.equal(a.data.digest, `sha256:${DIGEST}`);
+ assert.equal(a.data.workflow_run.id, RUN); assert.equal(a.data.workflow_run.head_sha, SOURCE);
+ assert.equal(a.data.workflow_run.repository_id, 470904030);
+ assert.equal(a.data.workflow_run.head_repository_id, 470904030);
+ };
+ await admit();
+ stage = 'DOWNLOAD';
+ const download = await github.rest.actions.downloadArtifact({ ...args, artifact_id: ARTIFACT, archive_format: 'zip' });
+ const bytes = Buffer.from(download.data);
+ assert.equal(bytes.length, ZIP_SIZE);
+ assert.equal(crypto.createHash('sha256').update(bytes).digest('hex'), DIGEST);
+ stage = 'PRIVATE_FILE';
+ const temp = process.env.RUNNER_TEMP;
+ assert.ok(temp && path.isAbsolute(temp)); assert.equal(fs.realpathSync(temp), path.resolve(temp));
+ const filename = path.join(temp, 'r5-d270-android-fixed.zip');
+ const descriptor = fs.openSync(filename, 'wx', 0o600); owned = filename;
+ try { fs.writeFileSync(descriptor, bytes); }
+ finally { fs.closeSync(descriptor); }
+ stage = 'DECODE';
+ try {
+ output = execFileSync('python3', ['-B', '.github/scripts/read-d270-android-artifact.py'],
+ { encoding: 'utf8', timeout: 30000, maxBuffer: 2 * 1024 * 1024, stdio: ['ignore', 'pipe', 'pipe'] });
+ } catch (error) {
+ const match = /^D270_ANDROID_OBSERVATION_READOUT_FAILED:(PRIVATE_FILE|KERNEL|ZIP_IDENTITY|ZIP_LAYOUT|JSON|ROOT_KEYS|PRODUCT|PROJECTED_METADATA)\n$/.exec(String(error.stdout ?? ''));
+ if (match) stage = 'DECODE_' + match[1];
+ throw error;
+ }
+ stage = 'PROJECTION_FRAME';
+ const lines = output.trim().split('\n');
+ assert.equal(lines.length, 3);
+ assert.equal(lines[0], 'D270_ANDROID_OBSERVATIONS_BEGIN');
+ assert.equal(lines[2], 'D270_ANDROID_OBSERVATIONS_END');
+ const projection = JSON.parse(lines[1]);
+ assert.deepEqual(Object.keys(projection).sort(), ['schema', 'scope', 'original_zip_sha256', 'metadata_sha256', 'observations'].sort());
+ assert.equal(projection.schema, 1);
+ assert.equal(projection.scope, 'OBSERVATIONS_ONLY_NOT_NATIVE_ACCEPTANCE_OR_CAUSE');
+ assert.equal(projection.original_zip_sha256, DIGEST);
+ assert.match(projection.metadata_sha256, /^[a-f0-9]{64}$/);
+ assert.equal(projection.observations.source_sha, SOURCE);
+ assert.equal(projection.observations.run_id, String(RUN));
+ assert.equal(projection.observations.run_attempt, '1');
+ await admit(); // Recheck official immutable source/workflow/job/attempt/artifact before releasing output.
+ } catch (_) {
+ primary = true;
+ throw new Error('FIXED_NATIVE_ARTIFACT_READOUT_FAILED_' + stage);
+ } finally {
+ if (owned) {
+ try { fs.unlinkSync(owned); }
+ catch (_) {
+ try { core.warning('FIXED_NATIVE_ARTIFACT_PRIVATE_CLEANUP_FAILED'); } catch (_) { /* retain primary */ }
+ if (!primary) throw new Error('FIXED_NATIVE_ARTIFACT_PRIVATE_CLEANUP_FAILED');
+ }
+ }
+ }
+ try { core.info(output.trim()); }
+ catch (_) { throw new Error('FIXED_NATIVE_ARTIFACT_READOUT_FAILED'); }
+}
+module.exports = { run };
diff --git a/.github/scripts/read-d270-android-artifact.py b/.github/scripts/read-d270-android-artifact.py
new file mode 100644
index 0000000000..9a5a1ced1c
--- /dev/null
+++ b/.github/scripts/read-d270-android-artifact.py
@@ -0,0 +1,102 @@
+#!/usr/bin/env python3
+"""Project fixed d270 Android failure facts using the unchanged 044 kernel."""
+import hashlib
+import importlib.util
+import io
+import json
+import os
+from pathlib import Path
+import stat
+import zipfile
+
+ROOT = Path(__file__).parent
+KERNEL_SHA256 = '1e9fc4370d733041fb5a48dc8c022e3461decafbf970ba030e90784208aed1d9'
+SOURCE = 'd27007078808617a97ee460b592eefb44e7e5325'
+WORKFLOW = 'f5f20e6d959109cdc2e0096099992d72307255bf'
+WORKFLOW_REF = 'KeeperCommunity/bitcoin-keeper/.github/workflows/keeper-native-diagnostic.yml@refs/pull/7149/merge'
+RUN, ATTEMPT = '40065599904', '1'
+ZIP_SIZE = 9596
+DIGEST = 'b9182e02a33b7e0568d73654b42d61f66bce8e425d65a6960aa0f4f2194ee13a'
+SCOPE = 'OBSERVATIONS_ONLY_NOT_NATIVE_ACCEPTANCE_OR_CAUSE'
+PHASE = 'PRIVATE_FILE'
+FIELDS = frozenset(('schema', 'source_sha', 'workflow_sha', 'workflow_ref', 'run_id', 'run_attempt',
+ 'platform', 'diagnostic_only', 'build', 'smoke', 'native_probe', 'r5_features', 'hardware', 'signing',
+ 'app_id', 'install_succeeded', 'installed_artifact_verified'))
+SAMPLE_FIELDS = frozenset(('sample', 'status', 'completed_stages', 'pin_onboarding_progress',
+ 'create_new_app_calls', 'other_backend_calls_rejected', 'failure_observation',
+ 'failed_assertion_snapshot', 'android_runtime_diagnostic'))
+
+
+def project(blob):
+ global PHASE
+ PHASE = 'KERNEL'
+ source = ROOT / 'read-044-android-artifact.py'
+ if hashlib.sha256(source.read_bytes()).hexdigest() != KERNEL_SHA256:
+ raise ValueError('Fixed kernel changed.')
+ spec = importlib.util.spec_from_file_location('fixed_044_android_kernel', source)
+ kernel = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(kernel)
+ literals = kernel.public_literals() # Original hash-checked policy remains unchanged.
+ kernel.SOURCE, kernel.WORKFLOW, kernel.WORKFLOW_REF = SOURCE, WORKFLOW, WORKFLOW_REF
+ kernel.RUN, kernel.ATTEMPT = RUN, ATTEMPT
+ kernel.public_literals = lambda: literals | {SOURCE, WORKFLOW, WORKFLOW_REF, RUN, ATTEMPT}
+ PHASE = 'ZIP_IDENTITY'
+ if type(blob) is not bytes or len(blob) != ZIP_SIZE or hashlib.sha256(blob).hexdigest() != DIGEST:
+ kernel.rejected()
+ PHASE = 'ZIP_LAYOUT'
+ with zipfile.ZipFile(io.BytesIO(blob)) as archive:
+ members = archive.infolist()
+ if len(members) != 1:
+ kernel.rejected()
+ entry = members[0]
+ if (entry.filename != 'android/metadata.json' or entry.orig_filename != entry.filename or
+ entry.flag_bits & 1 or stat.S_IFMT(entry.external_attr >> 16) not in (0, stat.S_IFREG) or
+ entry.file_size > kernel.LIMIT or entry.compress_type not in (zipfile.ZIP_STORED, zipfile.ZIP_DEFLATED)):
+ kernel.rejected()
+ raw = kernel.canonical_payload(blob, entry, archive.start_dir, archive.comment)
+ PHASE = 'JSON'
+ data = json.loads(raw, object_pairs_hook=kernel.pairs, parse_float=kernel.finite,
+ parse_constant=lambda _: kernel.rejected())
+ PHASE = 'ROOT_KEYS'
+ if type(data) is not dict or not set(data) <= kernel.ROOT_KEYS:
+ kernel.rejected()
+ projected = {key: value for key, value in data.items() if key in FIELDS}
+ PHASE = 'PRODUCT'
+ product = data.get('product_ui')
+ if (type(product) is not dict or product.get('status') != 'FAIL' or
+ type(product.get('samples')) is not list or not 1 <= len(product['samples']) <= 6 or
+ any(type(sample) is not dict for sample in product['samples'])):
+ kernel.rejected()
+ projected['product_ui'] = {key: product[key] for key in ('status', 'failure_category') if key in product}
+ projected['product_ui']['samples'] = [{key: value for key, value in sample.items() if key in SAMPLE_FIELDS}
+ for sample in product['samples']]
+ PHASE = 'PROJECTED_METADATA'
+ kernel.validate_metadata(projected)
+ return {'schema': 1, 'scope': SCOPE, 'original_zip_sha256': DIGEST,
+ 'metadata_sha256': hashlib.sha256(raw).hexdigest(), 'observations': projected}
+
+
+def main(argv=None):
+ global PHASE
+ PHASE = 'PRIVATE_FILE'
+ try:
+ if argv:
+ raise ValueError('No selectors.')
+ path = Path(os.environ['RUNNER_TEMP']) / 'r5-d270-android-fixed.zip'
+ with os.fdopen(os.open(path, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK), 'rb') as source:
+ info = os.fstat(source.fileno())
+ if not stat.S_ISREG(info.st_mode) or stat.S_IMODE(info.st_mode) != 0o600 or info.st_size != ZIP_SIZE:
+ raise ValueError('Invalid private file.')
+ result = project(source.read(ZIP_SIZE + 1))
+ except Exception:
+ print('D270_ANDROID_OBSERVATION_READOUT_FAILED:' + PHASE)
+ return 1
+ print('D270_ANDROID_OBSERVATIONS_BEGIN')
+ print(json.dumps(result, sort_keys=True, separators=(',', ':')))
+ print('D270_ANDROID_OBSERVATIONS_END')
+ return 0
+
+
+if __name__ == '__main__':
+ import sys
+ raise SystemExit(main(sys.argv[1:]))
diff --git a/.github/scripts/read-d270-ios-artifact.cjs b/.github/scripts/read-d270-ios-artifact.cjs
new file mode 100644
index 0000000000..a90b1a5990
--- /dev/null
+++ b/.github/scripts/read-d270-ios-artifact.cjs
@@ -0,0 +1,126 @@
+'use strict';
+// One finite metadata projection; no native worker, release authority or selector input.
+const assert = require('node:assert/strict');
+const crypto = require('node:crypto');
+const fs = require('node:fs');
+const path = require('node:path');
+const { execFileSync } = require('node:child_process');
+const OWNER = 'KeeperCommunity', REPO = 'bitcoin-keeper';
+const RUN = 40065599904, JOB = 120788067210;
+const SOURCE = 'd27007078808617a97ee460b592eefb44e7e5325';
+const WORKFLOW = 'f5f20e6d959109cdc2e0096099992d72307255bf';
+// Exact completed iOS job/artifact API and upload facts; Android may continue.
+const ARTIFACT = 12550480968, ZIP_SIZE = 7339, DIGEST = '5891036cd8225b97c7edaff9bc057e2c70a8f8720e8f9def3ef0369de043d032';
+const NATIVE_CONCLUSION = 'failure', STEP_CONCLUSIONS = ['success', 'failure', 'skipped', 'skipped', 'skipped'];
+const STEPS = ['Build development app', 'Run disposable startup smoke',
+ 'Run disposable native persistence probe', 'Run R5 production worker native scenarios',
+ 'Measure five full-product startup and first-wallet runs'];
+const CONCLUSIONS = ['success', 'failure', 'skipped'];
+const NAME = `keeper-diagnostic-native-IOS-${SOURCE}-${RUN}-1`;
+
+async function run({ github, context, core }) {
+ let owned, primary = false, output, stage = 'SELECTION';
+ try {
+ assert.ok(Number.isSafeInteger(ARTIFACT) && ARTIFACT > 0);
+ assert.ok(Number.isSafeInteger(ZIP_SIZE) && ZIP_SIZE > 0 && ZIP_SIZE <= 1024 * 1024 + 4096);
+ assert.match(DIGEST ?? '', /^[a-f0-9]{64}$/);
+ assert.ok(['success', 'failure'].includes(NATIVE_CONCLUSION));
+ assert.ok(Array.isArray(STEP_CONCLUSIONS) && STEP_CONCLUSIONS.length === STEPS.length &&
+ STEPS.every((_, index) => CONCLUSIONS.includes(STEP_CONCLUSIONS[index])));
+ assert.equal(context.repo.owner, OWNER); assert.equal(context.repo.repo, REPO);
+ assert.equal(context.eventName, 'push');
+ assert.equal(context.ref, 'refs/heads/codex/r5-d270-ios-artifact-readout-20261024');
+ const args = { owner: OWNER, repo: REPO, request: { timeout: 30000 } };
+ const admit = async () => {
+ stage = 'API_LOOKUP';
+ const [r, j, a] = await Promise.all([
+ github.rest.actions.getWorkflowRun({ ...args, run_id: RUN }),
+ github.rest.actions.getJobForWorkflowRun({ ...args, job_id: JOB }),
+ github.rest.actions.getArtifact({ ...args, artifact_id: ARTIFACT }),
+ ]);
+ stage = 'RUN_BINDING';
+ assert.equal(r.data.id, RUN); assert.equal(r.data.run_attempt, 1);
+ assert.equal(r.data.repository.id, 470904030); assert.equal(r.data.head_repository.id, 470904030);
+ assert.equal(r.data.head_sha, SOURCE); assert.equal(r.data.event, 'pull_request');
+ assert.equal(r.data.head_branch, 'codex/r5-native-acceptance-20261024');
+ assert.equal(r.data.path, '.github/workflows/keeper-native-diagnostic.yml');
+ // Only this completed iOS job is needed; Android may continue untouched.
+ assert.ok((r.data.status === 'in_progress' && r.data.conclusion === null) ||
+ (r.data.status === 'completed' && ['success', 'failure'].includes(r.data.conclusion)));
+ assert.deepEqual(r.data.referenced_workflows, [{
+ path: `${OWNER}/${REPO}/.github/workflows/keeper-native-platform.yml@${WORKFLOW}`,
+ ref: 'refs/pull/7149/merge', sha: WORKFLOW,
+ }]);
+ stage = 'JOB_BINDING';
+ assert.equal(j.data.id, JOB); assert.equal(j.data.run_id, RUN); assert.equal(j.data.run_attempt, 1);
+ assert.equal(j.data.head_sha, SOURCE); assert.equal(j.data.status, 'completed');
+ assert.equal(j.data.conclusion, NATIVE_CONCLUSION);
+ for (const [index, name] of STEPS.entries()) {
+ const steps = j.data.steps.filter(step => step.name === name);
+ assert.equal(steps.length, 1); assert.equal(steps[0].status, 'completed');
+ assert.equal(steps[0].conclusion, STEP_CONCLUSIONS[index]);
+ }
+ const upload = j.data.steps.filter(step => step.name === 'Retain safe Phase A evidence');
+ assert.equal(upload.length, 1); assert.equal(upload[0].status, 'completed');
+ assert.equal(upload[0].conclusion, 'success');
+ stage = 'ARTIFACT_BINDING';
+ assert.equal(a.data.id, ARTIFACT); assert.equal(a.data.name, NAME);
+ assert.equal(a.data.expired, false); assert.equal(a.data.size_in_bytes, ZIP_SIZE);
+ assert.equal(a.data.digest, `sha256:${DIGEST}`);
+ assert.equal(a.data.workflow_run.id, RUN); assert.equal(a.data.workflow_run.head_sha, SOURCE);
+ assert.equal(a.data.workflow_run.repository_id, 470904030);
+ assert.equal(a.data.workflow_run.head_repository_id, 470904030);
+ };
+ await admit();
+ stage = 'DOWNLOAD';
+ const download = await github.rest.actions.downloadArtifact({ ...args, artifact_id: ARTIFACT, archive_format: 'zip' });
+ const bytes = Buffer.from(download.data);
+ assert.equal(bytes.length, ZIP_SIZE);
+ assert.equal(crypto.createHash('sha256').update(bytes).digest('hex'), DIGEST);
+ stage = 'PRIVATE_FILE';
+ const temp = process.env.RUNNER_TEMP;
+ assert.ok(temp && path.isAbsolute(temp)); assert.equal(fs.realpathSync(temp), path.resolve(temp));
+ const filename = path.join(temp, 'r5-d270-ios-fixed.zip');
+ const descriptor = fs.openSync(filename, 'wx', 0o600); owned = filename;
+ try { fs.writeFileSync(descriptor, bytes); }
+ finally { fs.closeSync(descriptor); }
+ stage = 'DECODE';
+ try {
+ output = execFileSync('python3', ['-B', '.github/scripts/read-d270-ios-artifact.py'],
+ { encoding: 'utf8', timeout: 30000, maxBuffer: 2 * 1024 * 1024, stdio: ['ignore', 'pipe', 'pipe'] });
+ } catch (error) {
+ const match = /^D270_IOS_OBSERVATION_READOUT_FAILED:(PRIVATE_FILE|KERNEL|ZIP_IDENTITY|ZIP_LAYOUT|JSON|ROOT_KEYS|SIGNATURE_POLICY|IDENTITY|STARTUP_DIAGNOSTICS|STARTUP_OBSERVATION|DRIVER|INSTALLED|SIGNATURE|PROJECTED_METADATA)\n$/.exec(String(error.stdout ?? ''));
+ if (match) stage = 'DECODE_' + match[1];
+ throw error;
+ }
+ stage = 'PROJECTION_FRAME';
+ const lines = output.trim().split('\n');
+ assert.equal(lines.length, 3);
+ assert.equal(lines[0], 'D270_IOS_OBSERVATIONS_BEGIN');
+ assert.equal(lines[2], 'D270_IOS_OBSERVATIONS_END');
+ const projection = JSON.parse(lines[1]);
+ assert.deepEqual(Object.keys(projection).sort(), ['schema', 'scope', 'original_zip_sha256', 'metadata_sha256', 'observations'].sort());
+ assert.equal(projection.schema, 1);
+ assert.equal(projection.scope, 'OBSERVATIONS_ONLY_NOT_NATIVE_ACCEPTANCE_OR_CAUSE');
+ assert.equal(projection.original_zip_sha256, DIGEST);
+ assert.match(projection.metadata_sha256, /^[a-f0-9]{64}$/);
+ assert.equal(projection.observations.source_sha, SOURCE);
+ assert.equal(projection.observations.run_id, String(RUN));
+ assert.equal(projection.observations.run_attempt, '1');
+ await admit(); // Recheck official immutable source/workflow/job/attempt/artifact before releasing output.
+ } catch (_) {
+ primary = true;
+ throw new Error('FIXED_NATIVE_ARTIFACT_READOUT_FAILED_' + stage);
+ } finally {
+ if (owned) {
+ try { fs.unlinkSync(owned); }
+ catch (_) {
+ try { core.warning('FIXED_NATIVE_ARTIFACT_PRIVATE_CLEANUP_FAILED'); } catch (_) { /* retain primary */ }
+ if (!primary) throw new Error('FIXED_NATIVE_ARTIFACT_PRIVATE_CLEANUP_FAILED');
+ }
+ }
+ }
+ try { core.info(output.trim()); }
+ catch (_) { throw new Error('FIXED_NATIVE_ARTIFACT_READOUT_FAILED'); }
+}
+module.exports = { run };
diff --git a/.github/scripts/read-d270-ios-artifact.py b/.github/scripts/read-d270-ios-artifact.py
new file mode 100644
index 0000000000..ffbb78d32f
--- /dev/null
+++ b/.github/scripts/read-d270-ios-artifact.py
@@ -0,0 +1,133 @@
+#!/usr/bin/env python3
+"""Project reviewed observations from one original ZIP using the fixed 044 kernel."""
+import hashlib
+import importlib.util
+import io
+import json
+import os
+from pathlib import Path
+import stat
+import zipfile
+
+ROOT = Path(__file__).parent
+KERNEL_SHA256 = 'c2dd21633de27f44d2bd8c7ef50907384094d64d67060852339e97af42821abf'
+SOURCE = 'd27007078808617a97ee460b592eefb44e7e5325'
+WORKFLOW = 'f5f20e6d959109cdc2e0096099992d72307255bf'
+WORKFLOW_REF = 'KeeperCommunity/bitcoin-keeper/.github/workflows/keeper-native-diagnostic.yml@refs/pull/7149/merge'
+RUN, ATTEMPT = '40065599904', '1'
+ZIP_SIZE = 7339
+DIGEST = '5891036cd8225b97c7edaff9bc057e2c70a8f8720e8f9def3ef0369de043d032'
+SCOPE = 'OBSERVATIONS_ONLY_NOT_NATIVE_ACCEPTANCE_OR_CAUSE'
+STARTUP_SCOPE = 'Owned simulator launch window; fixed facts only; cause UNKNOWN.'
+HIERARCHY_SCOPE = 'ANY_RETAINED_SNAPSHOT_NOT_FINAL_ROUTE_OR_VISIBILITY_PROOF'
+PHASE = 'PRIVATE_FILE'
+FIELDS = frozenset(('schema', 'source_sha', 'workflow_sha', 'workflow_ref', 'run_id', 'run_attempt',
+ 'platform', 'diagnostic_only', 'build', 'smoke', 'native_probe', 'r5_features', 'hardware', 'signing',
+ 'app_id', 'install_succeeded', 'installed_artifact_verified', 'installed_artifact',
+ 'startup_diagnostics', 'startup_observation', 'driver_preflight', 'simulator_app_service_readiness',
+ 'failed_phase', 'startup_observation_capture', 'startup_observation_cleanup',
+ 'startup_cleanup_errors', 'cleanup_failures', 'disposable_cleanup'))
+ADDITIONAL_LITERALS = frozenset(('--info', 'CONNECTION_ERROR', 'EXCEPTION_MARKER', 'FATAL_MARKER',
+ 'HERMES_ERROR', 'JS_EXCEPTION', 'NATIVE_EXCEPTION', 'SCRIPT_LOAD_ERROR', 'SCRIPT_URL_MISSING',
+ 'PREFIXED_OWN_PROCESS_MARKERS_ONLY_NOT_CAUSE_OR_ACCEPTANCE', 'ios_simulator_signature',
+ 'verified', 'ADHOC_SIMULATOR_ONLY_NOT_RELEASE_SIGNING', 'bundle_id', 'entitlements_sha256',
+ 'embedded_code_count', STARTUP_SCOPE))
+
+
+def project(blob):
+ global PHASE
+ PHASE = 'KERNEL'
+ source = ROOT / 'read-044-ios-artifact.py'
+ if hashlib.sha256(source.read_bytes()).hexdigest() != KERNEL_SHA256:
+ raise ValueError('Fixed kernel changed.')
+ spec = importlib.util.spec_from_file_location('fixed_044_kernel', source)
+ kernel = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(kernel)
+ literals = kernel.public_literals() # Original hash-checked 044 policy remains unchanged.
+ kernel.SOURCE, kernel.WORKFLOW, kernel.WORKFLOW_REF = SOURCE, WORKFLOW, WORKFLOW_REF
+ kernel.RUN, kernel.ATTEMPT = RUN, ATTEMPT
+ kernel.public_literals = lambda: literals | ADDITIONAL_LITERALS | {SOURCE, WORKFLOW, WORKFLOW_REF, RUN, ATTEMPT}
+ old_hierarchy = kernel.validate_hierarchy
+
+ def current_hierarchy(value, product=False):
+ if product:
+ return old_hierarchy(value, product=True)
+ if type(value) is not dict or value.get('scope') != HIERARCHY_SCOPE:
+ kernel.rejected()
+ # Current d270 adds this fixed conservative scope. Keep it in output;
+ # apply the unchanged 044 flag/type/bound checks to its original fields.
+ return old_hierarchy({key: item for key, item in value.items() if key != 'scope'})
+
+ kernel.validate_hierarchy = current_hierarchy
+ PHASE = 'ZIP_IDENTITY'
+ if type(blob) is not bytes or len(blob) != ZIP_SIZE or hashlib.sha256(blob).hexdigest() != DIGEST:
+ kernel.rejected()
+ PHASE = 'ZIP_LAYOUT'
+ with zipfile.ZipFile(io.BytesIO(blob)) as archive:
+ members = archive.infolist()
+ if len(members) != 1:
+ kernel.rejected()
+ entry = members[0]
+ if (entry.filename != 'ios/metadata.json' or entry.orig_filename != entry.filename or
+ entry.flag_bits & 1 or stat.S_IFMT(entry.external_attr >> 16) not in (0, stat.S_IFREG) or
+ entry.file_size > kernel.LIMIT or entry.compress_type not in (zipfile.ZIP_STORED, zipfile.ZIP_DEFLATED)):
+ kernel.rejected()
+ raw = kernel.canonical_payload(blob, entry, archive.start_dir, archive.comment)
+ PHASE = 'JSON'
+ data = json.loads(raw, object_pairs_hook=kernel.pairs, parse_float=kernel.finite,
+ parse_constant=lambda _: kernel.rejected())
+ PHASE = 'ROOT_KEYS'
+ if type(data) is not dict or not set(data) <= kernel.ROOT_KEYS:
+ kernel.rejected()
+ projected = {key: value for key, value in data.items() if key in FIELDS}
+ PHASE = 'SIGNATURE_POLICY'
+ signature = data.get('toolchain', {}).get('ios_simulator_signature')
+ if (type(signature) is not dict or set(signature) != {'verified', 'scope', 'bundle_id',
+ 'entitlements_sha256', 'embedded_code_count'} or signature['verified'] is not True or
+ signature['scope'] != 'ADHOC_SIMULATOR_ONLY_NOT_RELEASE_SIGNING' or
+ signature['bundle_id'] != 'io.hexawallet.hexakeeper.dev' or
+ not kernel.re.fullmatch(r'[a-f0-9]{64}', signature['entitlements_sha256']) or
+ not kernel.bounded_int(signature['embedded_code_count'], 0, 128)):
+ kernel.rejected()
+ projected['toolchain'] = {'ios_simulator_signature': signature}
+ observation = projected.get('startup_observation')
+ PHASE = 'STARTUP_OBSERVATION'
+ if observation is not None and (type(observation) is not dict or observation.get('scope') != STARTUP_SCOPE):
+ kernel.rejected()
+ identity = {key: projected.get(key) for key in ('schema', 'source_sha', 'workflow_sha', 'workflow_ref',
+ 'run_id', 'run_attempt', 'platform', 'diagnostic_only')}
+ for key, value in projected.items():
+ PHASE = {'startup_diagnostics': 'STARTUP_DIAGNOSTICS', 'startup_observation': 'STARTUP_OBSERVATION',
+ 'driver_preflight': 'DRIVER', 'installed_artifact': 'INSTALLED',
+ 'toolchain': 'SIGNATURE'}.get(key, 'IDENTITY')
+ kernel.validate_metadata(dict(identity, **{key: value}))
+ PHASE = 'PROJECTED_METADATA'
+ kernel.validate_metadata(projected)
+ return {'schema': 1, 'scope': SCOPE, 'original_zip_sha256': DIGEST,
+ 'metadata_sha256': hashlib.sha256(raw).hexdigest(), 'observations': projected}
+
+
+def main(argv=None):
+ global PHASE
+ PHASE = 'PRIVATE_FILE'
+ try:
+ if argv:
+ raise ValueError('No selectors.')
+ path = Path(os.environ['RUNNER_TEMP']) / 'r5-d270-ios-fixed.zip'
+ with os.fdopen(os.open(path, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK), 'rb') as source:
+ info = os.fstat(source.fileno())
+ if not stat.S_ISREG(info.st_mode) or stat.S_IMODE(info.st_mode) != 0o600 or info.st_size != ZIP_SIZE:
+ raise ValueError('Invalid private file.')
+ result = project(source.read(ZIP_SIZE + 1))
+ except Exception:
+ print('D270_IOS_OBSERVATION_READOUT_FAILED:' + PHASE)
+ return 1
+ print('D270_IOS_OBSERVATIONS_BEGIN')
+ print(json.dumps(result, sort_keys=True, separators=(',', ':')))
+ print('D270_IOS_OBSERVATIONS_END')
+ return 0
+
+
+if __name__ == '__main__':
+ import sys
+ raise SystemExit(main(sys.argv[1:]))
diff --git a/.github/scripts/verify-ci-source.cjs b/.github/scripts/verify-ci-source.cjs
new file mode 100644
index 0000000000..2c36d29985
--- /dev/null
+++ b/.github/scripts/verify-ci-source.cjs
@@ -0,0 +1,131 @@
+'use strict';
+
+// A source receipt, not native acceptance or release authorization.
+const assert = require('node:assert/strict');
+const fs = require('node:fs');
+const crypto = require('node:crypto');
+const path = require('node:path');
+const { execFileSync } = require('node:child_process');
+const SHA = /^[a-f0-9]{40}$/;
+const PAIRED_RELAY_SHA = '838049e537e07eb646a2a0393eb969fba43d0739';
+const MANUAL_CONTRACTS = /^KeeperCommunity\/bitcoin-keeper\/\.github\/workflows\/keeper-(?:release-preparation-contracts|ruby-lock-contracts)\.yml@refs\/(?:heads|tags)\/[^\s]+$/;
+
+function gitAt(directory, args, binary = false) {
+ return execFileSync('git', ['--no-replace-objects', '--no-optional-locks', '-C', directory, ...args], {
+ encoding: binary ? undefined : 'utf8', stdio: ['ignore', 'pipe', 'pipe'],
+ timeout: 30000, maxBuffer: 16 * 1024 * 1024,
+ });
+}
+
+// Read HEAD's immutable tree, never the index or a checkout-authored manifest.
+// Git status remains useful for added/staged files but index flags can hide edits.
+function verifyRawCheckout(root, commit) {
+ assert.match(commit ?? '', SHA, 'An exact raw source commit is required');
+ const directory = path.resolve(root);
+ assert.equal(fs.realpathSync(directory), directory, 'Checkout alias rejected');
+ assert.ok(fs.lstatSync(directory).isDirectory(), 'Expected checkout directory');
+ const git = (...args) => gitAt(directory, args).trim();
+ assert.equal(path.resolve(git('rev-parse', '--show-toplevel')), directory, 'Expected checkout root');
+ assert.equal(git('rev-parse', 'HEAD'), commit, 'Raw checkout commit changed');
+ const tree = git('rev-parse', `${commit}^{tree}`);
+ assert.match(tree, SHA);
+ const listing = gitAt(directory, ['ls-tree', '-r', '-z', '--full-tree', commit], true);
+ const decoded = listing.toString('utf8');
+ assert.ok(Buffer.from(decoded, 'utf8').equals(listing), 'Unsupported Git path encoding');
+ const records = decoded.split('\0');
+ assert.equal(records.pop(), '', 'Incomplete raw source tree');
+ assert.ok(records.length > 0, 'Empty raw source tree');
+ const seen = new Set();
+ for (const record of records) {
+ const split = record.indexOf('\t');
+ assert.ok(split > 0, 'Invalid raw source tree entry');
+ const header = /^([0-9]{6}) blob ([a-f0-9]{40})$/.exec(record.slice(0, split));
+ assert.ok(header && ['100644', '100755'].includes(header[1]), 'Expected regular tracked Git blob');
+ const relative = record.slice(split + 1);
+ assert.ok(relative && !path.isAbsolute(relative) &&
+ !relative.split('/').some(part => !part || part === '.' || part === '..'), 'Invalid tracked source path');
+ assert.ok(!seen.has(relative), 'Duplicate tracked source path');
+ seen.add(relative);
+ const filename = path.join(directory, relative);
+ const before = fs.lstatSync(filename);
+ assert.ok(before.isFile(), 'Expected regular tracked source file');
+ assert.equal(fs.realpathSync(filename), filename, 'Tracked source alias rejected');
+ // Do not follow a final symlink swapped in after the path check. Verify the
+ // descriptor still belongs to the checked regular path before/after reading.
+ const fd = fs.openSync(filename, fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW | fs.constants.O_NONBLOCK);
+ let bytes, opened;
+ try {
+ opened = fs.fstatSync(fd);
+ assert.ok(opened.isFile(), 'Expected regular source descriptor');
+ assert.equal(opened.dev, before.dev, 'Tracked source replaced');
+ assert.equal(opened.ino, before.ino, 'Tracked source replaced');
+ bytes = fs.readFileSync(fd);
+ const after = fs.fstatSync(fd);
+ assert.equal(after.size, bytes.length, 'Tracked source changed while reading');
+ assert.equal(after.mtimeMs, opened.mtimeMs, 'Tracked source changed while reading');
+ } finally {
+ fs.closeSync(fd);
+ }
+ const final = fs.lstatSync(filename);
+ assert.ok(final.isFile(), 'Expected regular tracked source file');
+ assert.equal(fs.realpathSync(filename), filename, 'Tracked source alias rejected');
+ assert.equal(final.dev, opened.dev, 'Tracked source replaced');
+ assert.equal(final.ino, opened.ino, 'Tracked source replaced');
+ assert.equal(final.size, bytes.length, 'Tracked source changed while reading');
+ assert.equal(final.mtimeMs, opened.mtimeMs, 'Tracked source changed while reading');
+ const oid = crypto.createHash('sha1').update(`blob ${bytes.length}\0`).update(bytes).digest('hex');
+ assert.equal(oid, header[2], 'Raw source differs from its Git blob');
+ // Git records owner execute (0100), not group or other execute permissions.
+ assert.equal((final.mode & 0o100) !== 0, header[1] === '100755', 'Tracked source owner execute mode changed');
+ }
+ assert.equal(git('rev-parse', 'HEAD'), commit, 'Raw checkout commit changed');
+ return { tree, files: records.length };
+}
+
+function verifySource({ root = process.cwd(), env = process.env, event, allowPairedRelay = false,
+ allowContractDispatch = false } = {}) {
+ const manual = env.GITHUB_EVENT_NAME === 'workflow_dispatch' && allowContractDispatch === true;
+ assert.ok(['pull_request', 'push'].includes(env.GITHUB_EVENT_NAME) || manual, 'Unsupported CI source event');
+ if (manual) {
+ // This opt-in checks source only on two existing offline contract routes.
+ // It does not admit native/canonical dispatch or authorize any operation.
+ assert.ok(!allowPairedRelay && MANUAL_CONTRACTS.test(env.GITHUB_WORKFLOW_REF || ''), 'Unsupported manual contract route');
+ }
+ const payload = event ?? JSON.parse(fs.readFileSync(env.GITHUB_EVENT_PATH, 'utf8'));
+ const expected = env.GITHUB_EVENT_NAME === 'pull_request' ? payload.pull_request?.head?.sha : env.GITHUB_SHA;
+ assert.match(expected ?? '', SHA, 'An exact event source commit is required');
+ const git = (...args) => gitAt(root, args).trim();
+ const actual = git('rev-parse', 'HEAD');
+ assert.equal(actual, expected, 'Checked-out source differs from the event source commit');
+ // Reject added source too. Only the matrix job owns a separate fixed Relay
+ // checkout; it is independently checked rather than hidden by a broad ignore.
+ const status = git('status', '--porcelain', '--untracked-files=normal');
+ assert.equal(status.split('\n').filter(line => line &&
+ !(allowPairedRelay && line === '?? .ci-relay/')).length, 0, 'Source changed during CI');
+ if (allowPairedRelay) {
+ const relay = path.join(root, '.ci-relay');
+ assert.equal(fs.lstatSync(relay).isSymbolicLink(), false, 'Paired checkout alias rejected');
+ assert.equal(fs.realpathSync(relay), path.resolve(relay), 'Paired checkout alias rejected');
+ assert.equal(git('-C', relay, 'rev-parse', 'HEAD'), PAIRED_RELAY_SHA, 'Unexpected paired Relay source');
+ assert.equal(git('-C', relay, 'status', '--porcelain', '--untracked-files=normal'), '', 'Paired Relay source changed');
+ verifyRawCheckout(relay, PAIRED_RELAY_SHA);
+ }
+ const { tree } = verifyRawCheckout(root, actual);
+ return { schema: 1, source_sha: actual, source_tree: tree, event: env.GITHUB_EVENT_NAME,
+ run_id: env.GITHUB_RUN_ID ?? null, run_attempt: env.GITHUB_RUN_ATTEMPT ?? null,
+ workflow_sha: env.GITHUB_WORKFLOW_SHA ?? null,
+ scope: 'Source identity only; no native, security or release acceptance.' };
+}
+
+if (require.main === module) {
+ try {
+ const args = process.argv.slice(2);
+ assert.ok(args.length === 0 || (args.length === 1 && ['--paired-relay', '--contract-dispatch'].includes(args[0])), 'Unexpected source option');
+ console.log(JSON.stringify(verifySource({ allowPairedRelay: args[0] === '--paired-relay',
+ allowContractDispatch: args[0] === '--contract-dispatch' })));
+ } catch (_) {
+ console.error('CI_SOURCE_IDENTITY_FAILED');
+ process.exitCode = 1;
+ }
+}
+module.exports = { verifySource, verifyRawCheckout };
diff --git a/.github/tests/044-android-artifact-readout.test.cjs b/.github/tests/044-android-artifact-readout.test.cjs
new file mode 100644
index 0000000000..5d548d0cab
--- /dev/null
+++ b/.github/tests/044-android-artifact-readout.test.cjs
@@ -0,0 +1,150 @@
+'use strict';
+// Offline API/transport controls; no network, artifact download or native action.
+const assert = require('node:assert/strict');
+const crypto = require('node:crypto');
+const fs = require('node:fs');
+const path = require('node:path');
+const test = require('node:test');
+const vm = require('node:vm');
+const SCRIPT = path.join(__dirname, '../scripts/read-044-android-artifact.cjs');
+const SOURCE = '044ebb6ea2d465f6a70e9116e3feac5a604cd696';
+const WORKFLOW = '5a7b0c5da0a38197f6dd675ff424f3ba3f441d02';
+const PAYLOAD = Buffer.from('OFFLINE_SYNTHETIC_METADATA_ZIP_BYTES');
+const DIGEST = crypto.createHash('sha256').update(PAYLOAD).digest('hex');
+const SELECTION = 'const ARTIFACT = null, ZIP_SIZE = null, DIGEST = null;';
+const CONCLUSIONS = 'const RUN_CONCLUSION = null, NATIVE_CONCLUSION = null, BUILD_CONCLUSION = null, PROBES_CONCLUSION = null;';
+
+function fixture(options = {}) {
+ const context = { repo: { owner: 'KeeperCommunity', repo: 'bitcoin-keeper' },
+ eventName: 'push', ref: 'refs/heads/codex/r5-044-artifact-readout-preparation-20261023' };
+ const runData = { id: 39873063291, run_attempt: 1, repository: { id: 470904030 },
+ head_repository: { id: 470904030 }, head_sha: SOURCE, event: 'pull_request',
+ head_branch: 'codex/r5-startup-credential-failure-observation-20261022', path: '.github/workflows/keeper-native-diagnostic.yml',
+ status: 'completed', conclusion: 'failure', referenced_workflows: [{
+ path: `KeeperCommunity/bitcoin-keeper/.github/workflows/keeper-native-platform.yml@${WORKFLOW}`,
+ ref: 'refs/pull/7131/merge', sha: WORKFLOW }] };
+ const jobData = { id: 999, run_id: 39873063291, run_attempt: 1, head_sha: SOURCE,
+ status: 'completed', conclusion: 'failure',
+ steps: [['Build development app', 'success'],
+ ['Run Android startup and native persistence probes', 'failure'],
+ ['Retain safe Phase A evidence', 'success']].map(([name, conclusion]) => ({ name, conclusion, status: 'completed' })) };
+ const artifact = { id: 991, name: `keeper-diagnostic-native-ANDROID-${SOURCE}-39873063291-1`,
+ expired: false, size_in_bytes: PAYLOAD.length,
+ digest: 'sha256:' + DIGEST, workflow_run: {
+ id: 39873063291, head_sha: SOURCE, repository_id: 470904030, head_repository_id: 470904030 } };
+ const calls = [], events = [], output = [], actions = {};
+ for (const [name, data] of [['getWorkflowRun', runData], ['getJobForWorkflowRun', jobData], ['getArtifact', artifact]]) {
+ actions[name] = async args => { calls.push([name, args]); return { data }; };
+ }
+ actions.downloadArtifact = async args => { calls.push(['downloadArtifact', args]); return { data: options.payload ?? PAYLOAD }; };
+ const inputs = { github: { rest: { actions } }, context, core: {
+ info(value) { events.push('info'); if (options.info) throw new Error('PRIVATE_SENTINEL'); output.push(value); },
+ warning(value) { events.push('warning'); if (options.warning) throw new Error('PRIVATE_SENTINEL'); output.push(value); } } };
+ let text = fs.readFileSync(SCRIPT, 'utf8');
+ assert.ok(text.includes(SELECTION) && text.includes(CONCLUSIONS), 'Preparation must retain unavailable selection constants');
+ if (!options.unavailable) text = text.replace('const JOB = null;', 'const JOB = 999;')
+ .replace(SELECTION, `const ARTIFACT = 991, ZIP_SIZE = ${PAYLOAD.length}, DIGEST = '${DIGEST}';`)
+ .replace(CONCLUSIONS, "const RUN_CONCLUSION = 'failure', NATIVE_CONCLUSION = 'failure', BUILD_CONCLUSION = 'success', PROBES_CONCLUSION = 'failure';");
+ if (options.sourceChange) text = options.sourceChange(text);
+ const api = { module: { exports: {} }, Buffer, process: { env: { RUNNER_TEMP: '/owned' } }, require(name) {
+ if (name === 'node:assert/strict') return { ...assert, deepEqual(actual, expected) {
+ assert.deepEqual(JSON.parse(JSON.stringify(actual)), JSON.parse(JSON.stringify(expected)));
+ } };
+ if (name === 'node:crypto') return crypto;
+ if (name === 'node:path') return path;
+ if (name === 'node:fs') return {
+ realpathSync: value => value,
+ openSync(filename, flags, mode) { assert.equal(filename, '/owned/r5-044-android-fixed.zip'); assert.equal(flags, 'wx'); assert.equal(mode, 0o600); events.push('open'); return 42; },
+ writeFileSync(fd, bytes) { assert.equal(fd, 42); assert.deepEqual(bytes, PAYLOAD); events.push('write'); if (options.write) throw new Error('PRIVATE_SENTINEL'); },
+ closeSync(fd) { assert.equal(fd, 42); events.push('close'); if (options.close) throw new Error('PRIVATE_SENTINEL'); },
+ unlinkSync(filename) { assert.equal(filename, '/owned/r5-044-android-fixed.zip'); events.push('unlink'); if (options.unlink) throw new Error('PRIVATE_SENTINEL'); },
+ };
+ if (name === 'node:child_process') return { execFileSync(command, args, settings) {
+ assert.equal(command, 'python3'); assert.deepEqual(Array.from(args), ['-B', '.github/scripts/read-044-android-artifact.py']);
+ assert.equal(settings.timeout, 30000); events.push('decoder');
+ if (options.decoder) throw new Error('PRIVATE_SENTINEL');
+ return options.wrongOutput ? 'PRIVATE_SENTINEL' :
+ `FIXED_044_ANDROID_ARTIFACT_ZIP_BASE64_BEGIN\n${PAYLOAD.toString('base64')}\nFIXED_044_ANDROID_ARTIFACT_ZIP_BASE64_END\n`;
+ } };
+ throw new Error('Unexpected synthetic import');
+ } };
+ vm.runInNewContext(text, api);
+ return { context, runData, jobData, artifact, calls, events, output, inputs,
+ invoke: () => api.module.exports.run(inputs) };
+}
+
+test('unavailable real Android selection rejects before API, filesystem or logging', async () => {
+ const f = fixture({ unavailable: true });
+ await assert.rejects(f.invoke, /^Error: FIXED_NATIVE_ARTIFACT_READOUT_FAILED$/);
+ assert.deepEqual(f.calls, []); assert.deepEqual(f.events, []); assert.deepEqual(f.output, []);
+ const text = fs.readFileSync(SCRIPT, 'utf8');
+ assert.ok(text.includes('const RUN = 39873063291;') && text.includes('const JOB = null;'));
+});
+
+test('synthetic bound route reads only exact Android job/artifact and deletes before original-byte log', async () => {
+ const f = fixture(); await f.invoke();
+ assert.deepEqual(f.calls.map(([name]) => name), ['getWorkflowRun', 'getJobForWorkflowRun', 'getArtifact', 'downloadArtifact']);
+ assert.equal(f.calls[1][1].job_id, 999);
+ assert.equal(f.calls[3][1].artifact_id, 991);
+ assert.ok(f.events.indexOf('close') < f.events.indexOf('unlink'));
+ assert.ok(f.events.indexOf('unlink') < f.events.indexOf('info'));
+ const lines = f.output[0].split('\n');
+ assert.deepEqual(Buffer.from(lines[1], 'base64'), PAYLOAD);
+ assert.equal(lines[0], 'FIXED_044_ANDROID_ARTIFACT_ZIP_BASE64_BEGIN');
+ assert.equal(lines[2], 'FIXED_044_ANDROID_ARTIFACT_ZIP_BASE64_END');
+});
+
+test('partial or wrong finite selection fails before any API/filesystem operation', async () => {
+ for (const [before, after] of [["const JOB = 999", "const JOB = null"], ["const ARTIFACT = 991", "const ARTIFACT = null"],
+ [`ZIP_SIZE = ${PAYLOAD.length}`, 'ZIP_SIZE = null'], [`DIGEST = '${DIGEST}'`, 'DIGEST = null'],
+ ["RUN_CONCLUSION = 'failure'", "RUN_CONCLUSION = null"],
+ ["NATIVE_CONCLUSION = 'failure'", "NATIVE_CONCLUSION = null"],
+ ["BUILD_CONCLUSION = 'success'", "BUILD_CONCLUSION = null"],
+ ["PROBES_CONCLUSION = 'failure'", "PROBES_CONCLUSION = null"]]) {
+ const f = fixture({ sourceChange: text => { assert.ok(text.includes(before)); return text.replace(before, after); } });
+ await assert.rejects(f.invoke, /^Error: FIXED_NATIVE_ARTIFACT_READOUT_FAILED$/);
+ assert.deepEqual(f.calls, []); assert.deepEqual(f.events, []); assert.deepEqual(f.output, []);
+ }
+});
+
+test('foreign, stale, unknown or incomplete provenance never downloads bytes', async () => {
+ for (const change of [f => f.context.repo.owner = 'foreign', f => f.context.eventName = 'workflow_dispatch',
+ f => f.context.ref = 'refs/heads/sprint', f => f.runData.run_attempt++, f => f.runData.head_sha = '0'.repeat(40),
+ f => f.runData.repository.id++, f => f.runData.head_repository.id++, f => f.runData.status = 'queued',
+ f => { f.runData.status = 'in_progress'; f.runData.conclusion = null; },
+ f => f.runData.conclusion = 'success', f => f.runData.referenced_workflows = [],
+ f => f.runData.referenced_workflows[0].sha = SOURCE, f => f.jobData.id++, f => f.jobData.run_id++,
+ f => f.jobData.run_attempt++, f => f.jobData.status = 'in_progress', f => f.jobData.conclusion = 'success',
+ f => f.jobData.steps[0].conclusion = 'failure', f => f.jobData.steps[1].conclusion = 'success',
+ f => f.jobData.steps[2].conclusion = 'failure', f => f.jobData.steps.push(f.jobData.steps[2]),
+ f => f.artifact.id++, f => f.artifact.name += '-foreign', f => f.artifact.expired = true,
+ f => f.artifact.size_in_bytes++, f => f.artifact.digest = 'sha256:' + '0'.repeat(64),
+ f => f.artifact.workflow_run.id++, f => f.artifact.workflow_run.head_repository_id++]) {
+ const f = fixture(); change(f);
+ await assert.rejects(f.invoke, /^Error: FIXED_NATIVE_ARTIFACT_READOUT_FAILED$/);
+ assert.equal(f.calls.some(([name]) => name === 'downloadArtifact'), false);
+ assert.deepEqual(f.events, []); assert.deepEqual(f.output, []);
+ }
+});
+
+test('wrong size or digest bytes fail before owned-file creation or logging', async () => {
+ for (const payload of [Buffer.from('PRIVATE_SENTINEL'), Buffer.alloc(PAYLOAD.length)]) {
+ const f = fixture({ payload });
+ await assert.rejects(f.invoke, /^Error: FIXED_NATIVE_ARTIFACT_READOUT_FAILED$/);
+ assert.deepEqual(f.events, []); assert.deepEqual(f.output, []);
+ }
+});
+
+test('write, close, decoder, cleanup and logger failures retain fixed errors and purge ordering', async () => {
+ for (const options of [{ write: true, unlink: true, warning: true }, { close: true },
+ { decoder: true, unlink: true, warning: true }, { wrongOutput: true },
+ { unlink: true, warning: true }, { info: true }]) {
+ const f = fixture(options);
+ await assert.rejects(f.invoke, options.unlink && !options.write && !options.decoder ?
+ /^Error: FIXED_NATIVE_ARTIFACT_PRIVATE_CLEANUP_FAILED$/ : /^Error: FIXED_NATIVE_ARTIFACT_READOUT_FAILED$/);
+ assert.equal(f.events.filter(value => value === 'unlink').length, 1);
+ if (options.info) assert.ok(f.events.indexOf('unlink') < f.events.indexOf('info'));
+ else assert.equal(f.events.includes('info'), false);
+ assert.equal(JSON.stringify(f.output).includes('PRIVATE_SENTINEL'), false);
+ }
+});
diff --git a/.github/tests/044-ios-artifact-readout.test.cjs b/.github/tests/044-ios-artifact-readout.test.cjs
new file mode 100644
index 0000000000..6260e95ed8
--- /dev/null
+++ b/.github/tests/044-ios-artifact-readout.test.cjs
@@ -0,0 +1,130 @@
+'use strict';
+// Fabricated API and byte transport only; no current artifact/native operation.
+const assert = require('node:assert/strict');
+const crypto = require('node:crypto');
+const fs = require('node:fs');
+const path = require('node:path');
+const test = require('node:test');
+const vm = require('node:vm');
+const SCRIPT = path.join(__dirname, '../scripts/read-044-ios-artifact.cjs');
+const SOURCE = '044ebb6ea2d465f6a70e9116e3feac5a604cd696';
+const WORKFLOW = '5a7b0c5da0a38197f6dd675ff424f3ba3f441d02';
+const PAYLOAD = Buffer.from('OFFLINE_SYNTHETIC_METADATA_ZIP_BYTES');
+const DIGEST = crypto.createHash('sha256').update(PAYLOAD).digest('hex');
+const SELECTION = "const ARTIFACT = 12469536083, ZIP_SIZE = 7232, DIGEST = 'e244015128d4aa72e1e1c8be3072bc70d506ba11a804067448122d1318621caf';";
+const OUTCOME = "const NATIVE_CONCLUSION = 'failure', STEP_CONCLUSIONS = ['success', 'failure', 'skipped', 'skipped', 'skipped'];";
+
+function fixture(options = {}) {
+ const context = { repo: { owner: 'KeeperCommunity', repo: 'bitcoin-keeper' },
+ eventName: 'push', ref: 'refs/heads/codex/r5-044-artifact-readout-preparation-20261023' };
+ const runData = { id: 39873063291, run_attempt: 1, repository: { id: 470904030 },
+ head_repository: { id: 470904030 }, head_sha: SOURCE, event: 'pull_request',
+ head_branch: 'codex/r5-startup-credential-failure-observation-20261022',
+ path: '.github/workflows/keeper-native-diagnostic.yml', status: 'in_progress', conclusion: null,
+ referenced_workflows: [{path: `KeeperCommunity/bitcoin-keeper/.github/workflows/keeper-native-platform.yml@${WORKFLOW}`,
+ ref: 'refs/pull/7131/merge', sha: WORKFLOW}] };
+ const jobData = { id: 120151926152, run_id: 39873063291, run_attempt: 1, head_sha: SOURCE,
+ status: 'completed', conclusion: 'failure', steps: [
+ ['Build development app', 'success'], ['Run disposable startup smoke', 'failure'],
+ ['Run disposable native persistence probe', 'skipped'], ['Run R5 production worker native scenarios', 'skipped'],
+ ['Measure five full-product startup and first-wallet runs', 'skipped'], ['Retain safe Phase A evidence', 'success']
+ ].map(([name, conclusion]) => ({name, conclusion, status: 'completed'})) };
+ const artifact = {id: options.production ? 12469536083 : 991,
+ name: `keeper-diagnostic-native-IOS-${SOURCE}-39873063291-1`, expired: false,
+ size_in_bytes: options.production ? 7232 : PAYLOAD.length,
+ digest: 'sha256:' + (options.production ? 'e244015128d4aa72e1e1c8be3072bc70d506ba11a804067448122d1318621caf' : DIGEST), workflow_run: {
+ id: 39873063291, head_sha: SOURCE, repository_id: 470904030, head_repository_id: 470904030}};
+ const calls = [], events = [], output = [], actions = {};
+ for (const [name, data] of [['getWorkflowRun', runData], ['getJobForWorkflowRun', jobData], ['getArtifact', artifact]]) {
+ actions[name] = async args => { calls.push([name, args]); return {data}; };
+ }
+ actions.downloadArtifact = async args => {calls.push(['downloadArtifact', args]); return {data: options.payload ?? PAYLOAD};};
+ const inputs = {github: {rest: {actions}}, context, core: {
+ info(value) {events.push('info'); if (options.info) throw Error('PRIVATE_SENTINEL'); output.push(value);},
+ warning(value) {events.push('warning'); if (options.warning) throw Error('PRIVATE_SENTINEL'); output.push(value);}}};
+ let source = fs.readFileSync(SCRIPT, 'utf8');
+ assert.ok(source.includes(SELECTION) && source.includes(OUTCOME));
+ if (!options.production) source = source.replace(SELECTION,
+ `const ARTIFACT = 991, ZIP_SIZE = ${PAYLOAD.length}, DIGEST = '${DIGEST}';`);
+ if (options.edit) source = options.edit(source);
+ const api = {module: {exports: {}}, Buffer, process: {env: {RUNNER_TEMP: '/owned'}}, require(name) {
+ if (name === 'node:assert/strict') return {...assert, deepEqual(a,b) {assert.deepEqual(JSON.parse(JSON.stringify(a)), JSON.parse(JSON.stringify(b)));}};
+ if (name === 'node:crypto') return crypto;
+ if (name === 'node:path') return path;
+ if (name === 'node:fs') return {realpathSync: x => x,
+ openSync(file, flags, mode) {assert.equal(file, '/owned/r5-044-ios-fixed.zip'); assert.equal(flags, 'wx'); assert.equal(mode, 0o600); events.push('open'); return 42;},
+ writeFileSync(fd, bytes) {assert.equal(fd,42); assert.deepEqual(bytes,PAYLOAD); events.push('write'); if(options.write) throw Error('PRIVATE_SENTINEL');},
+ closeSync(fd) {assert.equal(fd,42); events.push('close'); if(options.close) throw Error('PRIVATE_SENTINEL');},
+ unlinkSync() {events.push('unlink'); if(options.unlink) throw Error('PRIVATE_SENTINEL');}};
+ if (name === 'node:child_process') return {execFileSync(command,args,settings) {
+ assert.equal(command,'python3'); assert.deepEqual(Array.from(args),['-B','.github/scripts/read-044-ios-artifact.py']);
+ assert.equal(settings.timeout,30000); events.push('decoder'); if(options.decoder) throw Error('PRIVATE_SENTINEL');
+ return options.wrongOutput ? 'PRIVATE_SENTINEL' : `FIXED_044_IOS_ARTIFACT_ZIP_BASE64_BEGIN\n${PAYLOAD.toString('base64')}\nFIXED_044_IOS_ARTIFACT_ZIP_BASE64_END\n`;}};
+ throw Error('Unexpected test import');
+ }};
+ vm.runInNewContext(source,api);
+ return {context,runData,jobData,artifact,calls,events,output,inputs,invoke:()=>api.module.exports.run(inputs)};
+}
+
+test('exact observed production selection reaches only its archive and rejects wrong digest before file/log', async()=>{
+ const f=fixture({production:true,payload:Buffer.alloc(7232)});
+ await assert.rejects(f.invoke,/FIXED_NATIVE_ARTIFACT_READOUT_FAILED/);
+ assert.deepEqual(f.calls.map(([name])=>name),['getWorkflowRun','getJobForWorkflowRun','getArtifact','downloadArtifact']);
+ assert.equal(f.calls[2][1].artifact_id,12469536083); assert.equal(f.calls[3][1].artifact_id,12469536083);
+ assert.deepEqual(f.events,[]); assert.deepEqual(f.output,[]);
+});
+
+test('every incomplete observed binding fails before API/filesystem', async()=>{
+ for(const [before,after] of [["ARTIFACT = 12469536083","ARTIFACT = null"], ['ZIP_SIZE = 7232','ZIP_SIZE = null'],
+ ["DIGEST = 'e244015128d4aa72e1e1c8be3072bc70d506ba11a804067448122d1318621caf'",'DIGEST = null'], ["NATIVE_CONCLUSION = 'failure'",'NATIVE_CONCLUSION = null'],
+ ["STEP_CONCLUSIONS = ['success', 'failure', 'skipped', 'skipped', 'skipped']",'STEP_CONCLUSIONS = null'],
+ ["STEP_CONCLUSIONS = ['success', 'failure', 'skipped', 'skipped', 'skipped']", "STEP_CONCLUSIONS = ['success', , 'skipped', 'skipped', 'skipped']"],
+ ["STEP_CONCLUSIONS = ['success', 'failure', 'skipped', 'skipped', 'skipped']", "STEP_CONCLUSIONS = ['success', undefined, 'skipped', 'skipped', 'skipped']"],
+ ["STEP_CONCLUSIONS = ['success', 'failure', 'skipped', 'skipped', 'skipped']", "STEP_CONCLUSIONS = ['success', null, 'skipped', 'skipped', 'skipped']"]]) {
+ const f=fixture({production:true,edit:s=>{assert.ok(s.includes(before)); return s.replace(before,after);}});
+ await assert.rejects(f.invoke,/FIXED_NATIVE_ARTIFACT_READOUT_FAILED/);
+ assert.deepEqual(f.calls,[]); assert.deepEqual(f.events,[]); assert.deepEqual(f.output,[]);
+ }
+});
+
+test('synthetic completed iOS job can be read while Android continues and purge precedes exact-byte output',async()=>{
+ for(const completed of [false,true]) {
+ const f=fixture(); if(completed) Object.assign(f.runData,{status:'completed',conclusion:'failure'});
+ await f.invoke(); assert.equal(f.calls.filter(([name])=>name==='getJobForWorkflowRun').length,1);
+ assert.equal(f.calls[1][1].job_id,120151926152);
+ assert.ok(f.events.indexOf('close'){
+ for(const change of [f=>f.context.eventName='workflow_dispatch',f=>f.context.repo.owner='foreign',f=>f.context.ref='refs/heads/sprint',
+ f=>f.runData.id++,f=>f.runData.run_attempt++,f=>f.runData.head_sha=WORKFLOW,f=>f.runData.repository.id++,
+ f=>f.runData.head_repository.id++,f=>f.runData.status='queued',f=>f.runData.referenced_workflows=[],
+ f=>f.runData.referenced_workflows[0].sha=SOURCE,f=>f.jobData.id++,f=>f.jobData.run_attempt++,f=>f.jobData.run_id++,
+ f=>f.jobData.status='in_progress',f=>f.jobData.conclusion='success',f=>f.jobData.steps[0].conclusion='failure',
+ f=>f.jobData.steps[5].conclusion='failure',f=>f.jobData.steps.push(f.jobData.steps[5]),f=>f.artifact.id++,
+ f=>f.artifact.name+='foreign',f=>f.artifact.size_in_bytes++,f=>f.artifact.expired=true,
+ f=>f.artifact.digest='sha256:'+'0'.repeat(64),f=>f.artifact.workflow_run.id++,f=>f.artifact.workflow_run.head_sha=WORKFLOW]) {
+ const f=fixture({production:true}); change(f); await assert.rejects(f.invoke,/FIXED_NATIVE_ARTIFACT_READOUT_FAILED/);
+ assert.equal(f.calls.some(([name])=>name==='downloadArtifact'),false); assert.deepEqual(f.events,[]); assert.deepEqual(f.output,[]);
+ }
+});
+
+test('wrong ZIP size or digest fails before any filesystem or log operation',async()=>{
+ for(const payload of [Buffer.from('PRIVATE_SENTINEL'),Buffer.alloc(PAYLOAD.length)]) {
+ const f=fixture({payload}); await assert.rejects(f.invoke,/FIXED_NATIVE_ARTIFACT_READOUT_FAILED/);
+ assert.deepEqual(f.events,[]); assert.deepEqual(f.output,[]);
+ }
+});
+
+test('decoder write close cleanup and logging errors stay fixed and preserve purge ordering',async()=>{
+ for(const options of [{write:true,unlink:true,warning:true},{close:true},{decoder:true,unlink:true,warning:true},
+ {wrongOutput:true},{unlink:true,warning:true},{info:true}]) {
+ const f=fixture(options); await assert.rejects(f.invoke,options.unlink&&!options.write&&!options.decoder ?
+ /FIXED_NATIVE_ARTIFACT_PRIVATE_CLEANUP_FAILED/:/FIXED_NATIVE_ARTIFACT_READOUT_FAILED/);
+ assert.equal(f.events.filter(x=>x==='unlink').length,1);
+ if(options.info) assert.ok(f.events.indexOf('unlink') ({ name, conclusion, status: 'completed' })) };
+ const artifact = { id: 12458149136, name: `keeper-diagnostic-native-ANDROID-${SOURCE}-39846002094-1`,
+ expired: false, size_in_bytes: 8395, digest: `sha256:${DIGEST}`, workflow_run: {
+ id: 39846002094, head_sha: SOURCE, repository_id: 470904030, head_repository_id: 470904030 } };
+ const calls = [], output = [];
+ const actions = {};
+ for (const [name, data] of [['getWorkflowRun', runData], ['getJobForWorkflowRun', jobData], ['getArtifact', artifact]]) {
+ actions[name] = async args => { calls.push([name, args]); return { data }; };
+ }
+ actions.downloadArtifact = async args => { calls.push(['downloadArtifact', args]); return { data: Buffer.from('PRIVATE_SENTINEL') }; };
+ const inputs = { github: { rest: { actions } }, context,
+ core: { info: value => output.push(value), warning: value => output.push(value) } };
+ return { context, runData, jobData, artifact, calls, output, inputs, invoke: () => run(inputs) };
+}
+
+test('valid API provenance reaches only the fixed archive; unverified bytes emit no receipt', async () => {
+ const f = fixture();
+ await assert.rejects(f.invoke, /^Error: FIXED_NATIVE_ARTIFACT_READOUT_FAILED$/);
+ assert.deepEqual(f.calls.at(-1), ['downloadArtifact', {
+ owner: 'KeeperCommunity', repo: 'bitcoin-keeper', request: { timeout: 30000 },
+ artifact_id: 12458149136, archive_format: 'zip' }]);
+ assert.deepEqual(f.output, []);
+});
+
+test('actual private-file finally retains primary even when decoder, unlink and logger all fail', async () => {
+ for (const options of [{}, { decoder: true, unlink: true, warning: true },
+ { unlink: true, warning: true }, { write: true, unlink: true, warning: true }]) {
+ const f = fixture(), events = [];
+ f.inputs.github.rest.actions.downloadArtifact = async () => ({ data: Buffer.alloc(8395) });
+ const api = { module: { exports: {} }, Buffer, process: { env: { RUNNER_TEMP: '/owned' } }, require(name) {
+ if (name === 'node:assert/strict') return { ...assert, deepEqual(actual, expected, message) {
+ // The source runs in a separate VM realm; compare its API JSON by value.
+ assert.deepEqual(JSON.parse(JSON.stringify(actual)), JSON.parse(JSON.stringify(expected)), message);
+ } };
+ if (name === 'node:path') return path;
+ if (name === 'node:crypto') return { createHash: () => ({ update() { return this; }, digest: () => DIGEST }) };
+ if (name === 'node:fs') return { realpathSync: x => x,
+ openSync(filename, flags, mode) { assert.equal(filename, '/owned/r5-23f-android-fixed.zip'); assert.equal(flags, 'wx'); assert.equal(mode, 0o600); events.push('open'); return 42; },
+ writeFileSync(fd) { assert.equal(fd, 42); events.push('write'); if (options.write) throw new Error('PRIVATE_SENTINEL'); },
+ closeSync(fd) { assert.equal(fd, 42); events.push('close'); },
+ unlinkSync() { events.push('unlink'); if (options.unlink) throw new Error('PRIVATE_SENTINEL'); } };
+ if (name === 'node:child_process') return { execFileSync(command, args, settings) {
+ assert.equal(command, 'python3'); assert.deepEqual(Array.from(args), ['-B', '.github/scripts/read-23f-android-artifact.py']);
+ assert.equal(settings.timeout, 30000); events.push('decoder');
+ if (options.decoder) throw new Error('PRIVATE_SENTINEL'); return 'SAFE_R5_ANDROID_READOUT {}\n'; } };
+ throw new Error('Unexpected synthetic import');
+ } };
+ vm.runInNewContext(fs.readFileSync(path.join(__dirname, '../scripts/read-23f-native-artifact.cjs'), 'utf8'), api);
+ f.inputs.core = { info() { events.push('info'); }, warning() { events.push('warning'); if (options.warning) throw new Error('PRIVATE_SENTINEL'); } };
+ const action = () => api.module.exports.run(f.inputs);
+ if (options.decoder || options.write) await assert.rejects(action, /^Error: FIXED_NATIVE_ARTIFACT_READOUT_FAILED$/);
+ else if (options.unlink) await assert.rejects(action, /^Error: FIXED_NATIVE_ARTIFACT_PRIVATE_CLEANUP_FAILED$/);
+ else await action();
+ assert.equal(events.filter(x => x === 'unlink').length, 1);
+ assert.ok(events.indexOf('close') < events.indexOf('unlink'));
+ if (!options.decoder && !options.write && !options.unlink) assert.ok(events.indexOf('unlink') < events.indexOf('info'));
+ else assert.equal(events.includes('info'), false);
+ }
+});
+
+test('foreign context cannot make any API request', async () => {
+ for (const change of [f => f.context.repo.owner = 'foreign', f => f.context.repo.repo = 'foreign',
+ f => f.context.eventName = 'workflow_dispatch', f => f.context.ref = 'refs/heads/sprint']) {
+ const f = fixture(); change(f);
+ await assert.rejects(f.invoke, /FIXED_NATIVE_ARTIFACT_READOUT_FAILED/);
+ assert.deepEqual(f.calls, []); assert.deepEqual(f.output, []);
+ }
+});
+
+test('stale, cross-source, foreign, missing and failed-upload metadata reject before archive download', async () => {
+ for (const change of [
+ f => f.runData.id++, f => f.runData.run_attempt++, f => f.runData.head_sha = '0'.repeat(40),
+ f => f.runData.head_repository.id++, f => f.runData.event = 'push',
+ f => f.runData.path = '.github/workflows/other.yml', f => f.runData.status = 'in_progress',
+ f => f.runData.referenced_workflows[0].sha = SOURCE, f => f.runData.referenced_workflows = [],
+ f => f.jobData.run_id++, f => f.jobData.head_sha = WORKFLOW,
+ f => f.jobData.steps[2].conclusion = 'failure', f => f.jobData.steps.push(f.jobData.steps[2]),
+ f => f.artifact.id++, f => f.artifact.name += '-foreign', f => f.artifact.expired = true,
+ f => f.artifact.size_in_bytes++, f => f.artifact.digest = 'sha256:' + '0'.repeat(64),
+ f => f.artifact.workflow_run.id++, f => f.artifact.workflow_run.head_sha = WORKFLOW,
+ ]) {
+ const f = fixture(); change(f);
+ await assert.rejects(f.invoke, /FIXED_NATIVE_ARTIFACT_READOUT_FAILED/);
+ assert.equal(f.calls.some(([name]) => name === 'downloadArtifact'), false);
+ assert.deepEqual(f.output, []);
+ }
+});
diff --git a/.github/tests/7158-android-startup-readout.test.cjs b/.github/tests/7158-android-startup-readout.test.cjs
new file mode 100644
index 0000000000..a9668e53fc
--- /dev/null
+++ b/.github/tests/7158-android-startup-readout.test.cjs
@@ -0,0 +1,166 @@
+'use strict';
+// Fabricated API and byte transport only; no current artifact/native operation.
+const assert = require('node:assert/strict');
+const crypto = require('node:crypto');
+const fs = require('node:fs');
+const path = require('node:path');
+const test = require('node:test');
+const vm = require('node:vm');
+const SCRIPT = path.join(__dirname, '../scripts/read-7158-android-startup-artifact.cjs');
+const SOURCE = '3f4e8127e3698accd3760a4a039448964a5285a4';
+const WORKFLOW = 'a'.repeat(40);
+const BINDINGS = "const WORKFLOW = 'f83a9a8b182dd8276a732ee2b6338fb6f845640a', NATIVE_HEAD_BRANCH = 'codex/r5-android-skip-target-20261024', WORKFLOW_PULL_REF = 'refs/pull/7158/merge', RUN_CONCLUSION = 'failure';";
+const PAYLOAD = Buffer.from('OFFLINE_SYNTHETIC_METADATA_ZIP_BYTES');
+const DIGEST = crypto.createHash('sha256').update(PAYLOAD).digest('hex');
+const SELECTION = "const ARTIFACT = 12557603923, ZIP_SIZE = 6451, DIGEST = 'f3553f9632eff7bd25f2315c8fb0e5429132455ea0af7d5293d4e4c7cfd8fd40';";
+const OUTCOME = "const NATIVE_CONCLUSION = 'failure', STEP_CONCLUSIONS = ['success', 'failure'];";
+
+function fixture(options = {}) {
+ const observedWorkflow = options.production ? 'f83a9a8b182dd8276a732ee2b6338fb6f845640a' : WORKFLOW;
+ const context = { repo: { owner: 'KeeperCommunity', repo: 'bitcoin-keeper' },
+ eventName: 'push', ref: 'refs/heads/codex/r5-7158-android-startup-readout-r2-20261024' };
+ const runData = { id: 40085793409, run_attempt: 1, repository: { id: 470904030 },
+ head_repository: { id: 470904030 }, head_sha: SOURCE, event: 'pull_request',
+ head_branch: options.production ? 'codex/r5-android-skip-target-20261024' : 'codex/fixed-native-fixture',
+ path: '.github/workflows/keeper-native-diagnostic.yml', status: 'completed', conclusion: 'failure',
+ referenced_workflows: [{path: `KeeperCommunity/bitcoin-keeper/.github/workflows/keeper-native-platform.yml@${observedWorkflow}`,
+ ref: options.production ? 'refs/pull/7158/merge' : 'refs/pull/9999/merge', sha: observedWorkflow}] };
+ const jobData = { id: 120848340201, run_id: 40085793409, run_attempt: 1, head_sha: SOURCE,
+ status: 'completed', conclusion: 'failure', steps: [
+ ['Build development app', 'success'], ['Run Android startup and native persistence probes', 'failure'], ['Retain safe Phase A evidence', 'success']
+ ].map(([name, conclusion]) => ({name, conclusion, status: 'completed'})) };
+ const artifact = {id: options.production ? 12557603923 : 991,
+ name: `keeper-diagnostic-native-ANDROID-${SOURCE}-40085793409-1`, expired: false,
+ size_in_bytes: options.production ? 6451 : PAYLOAD.length,
+ digest: 'sha256:' + (options.production ? 'f3553f9632eff7bd25f2315c8fb0e5429132455ea0af7d5293d4e4c7cfd8fd40' : DIGEST), workflow_run: {
+ id: 40085793409, head_sha: SOURCE, repository_id: 470904030, head_repository_id: 470904030}};
+ const calls = [], events = [], output = [], actions = {};
+ for (const [name, data] of [['getWorkflowRun', runData], ['getJobForWorkflowRun', jobData], ['getArtifact', artifact]]) {
+ actions[name] = async args => { calls.push([name, args]); return {data}; };
+ }
+ actions.downloadArtifact = async args => {calls.push(['downloadArtifact', args]); if(options.after) options.after({runData,jobData,artifact}); return {data: options.payload ?? PAYLOAD};};
+ const inputs = {github: {rest: {actions}}, context, core: {
+ info(value) {events.push('info'); if (options.info) throw Error('PRIVATE_SENTINEL'); output.push(value);},
+ warning(value) {events.push('warning'); if (options.warning) throw Error('PRIVATE_SENTINEL'); output.push(value);}}};
+ let source = fs.readFileSync(SCRIPT, 'utf8');
+ assert.ok(source.includes(SELECTION) && source.includes(OUTCOME));
+ if (!options.production) source = source.replace(SELECTION,
+ `const ARTIFACT = 991, ZIP_SIZE = ${PAYLOAD.length}, DIGEST = '${DIGEST}';`).replace(BINDINGS,
+ `const WORKFLOW = '${WORKFLOW}', NATIVE_HEAD_BRANCH = 'codex/fixed-native-fixture', WORKFLOW_PULL_REF = 'refs/pull/9999/merge', RUN_CONCLUSION = 'failure';`).replace(OUTCOME,
+ "const NATIVE_CONCLUSION = 'failure', STEP_CONCLUSIONS = ['success', 'failure'];");
+ if (options.edit) source = options.edit(source);
+ const api = {module: {exports: {}}, Buffer, process: {env: {RUNNER_TEMP: '/owned'}}, require(name) {
+ if (name === 'node:assert/strict') return {...assert, deepEqual(a,b) {assert.deepEqual(JSON.parse(JSON.stringify(a)), JSON.parse(JSON.stringify(b)));}};
+ if (name === 'node:crypto') return crypto;
+ if (name === 'node:path') return path;
+ if (name === 'node:fs') return {realpathSync: x => x,
+ openSync(file, flags, mode) {assert.equal(file, '/owned/r5-7158-android-startup-fixed.zip'); assert.equal(flags, 'wx'); assert.equal(mode, 0o600); events.push('open'); return 42;},
+ writeFileSync(fd, bytes) {assert.equal(fd,42); assert.deepEqual(bytes,PAYLOAD); events.push('write'); if(options.write) throw Error('PRIVATE_SENTINEL');},
+ closeSync(fd) {assert.equal(fd,42); events.push('close'); if(options.close) throw Error('PRIVATE_SENTINEL');},
+ unlinkSync() {events.push('unlink'); if(options.unlink) throw Error('PRIVATE_SENTINEL');}};
+ if (name === 'node:child_process') return {execFileSync(command,args,settings) {
+ assert.equal(command,'python3'); assert.deepEqual(Array.from(args),['-B','.github/scripts/read-7158-android-startup-artifact.py']);
+ assert.equal(settings.timeout,30000); events.push('decoder'); if(options.decoder) {
+ const error = Error('PRIVATE_SENTINEL'); error.stdout = options.decoderOutput; throw error;
+ }
+ return options.wrongOutput ? 'PRIVATE_SENTINEL' : 'STARTUP_7158_ANDROID_OBSERVATIONS_BEGIN\n' + JSON.stringify({schema:1,scope:'OBSERVATIONS_ONLY_NOT_NATIVE_ACCEPTANCE_OR_CAUSE',original_zip_sha256:DIGEST,metadata_sha256:'a'.repeat(64),observations:{source_sha:SOURCE,run_id:'40085793409',run_attempt:'1'}}) + '\nSTARTUP_7158_ANDROID_OBSERVATIONS_END\n';}};
+ throw Error('Unexpected test import');
+ }};
+ vm.runInNewContext(source,api);
+ return {context,runData,jobData,artifact,calls,events,output,inputs,invoke:()=>api.module.exports.run(inputs)};
+}
+
+test('unavailable terminal selection rejects before API filesystem decoder or logging', async()=>{
+ const f=fixture({production:true,edit:s=>s.replace("WORKFLOW = 'f83a9a8b182dd8276a732ee2b6338fb6f845640a'", 'WORKFLOW = null')});
+ await assert.rejects(f.invoke,/FIXED_NATIVE_ARTIFACT_READOUT_FAILED_SELECTION/);
+ assert.deepEqual(f.calls,[]); assert.deepEqual(f.events,[]); assert.deepEqual(f.output,[]);
+});
+
+test('exact observed production bindings select only original artifact and reject bad bytes before file or output',async()=>{
+ const f=fixture({production:true,payload:Buffer.alloc(6451)});
+ await assert.rejects(f.invoke,/FIXED_NATIVE_ARTIFACT_READOUT_FAILED_DOWNLOAD/);
+ assert.deepEqual(f.calls.map(([name])=>name),['getWorkflowRun','getJobForWorkflowRun','getArtifact','downloadArtifact']);
+ assert.equal(f.calls[2][1].artifact_id,12557603923); assert.equal(f.calls[3][1].artifact_id,12557603923);
+ assert.deepEqual(f.events,[]); assert.deepEqual(f.output,[]);
+});
+
+test('every incomplete observed binding fails before API/filesystem', async()=>{
+ for(const [before,after] of [[`WORKFLOW = '${WORKFLOW}'`, 'WORKFLOW = null'],
+ ["NATIVE_HEAD_BRANCH = 'codex/fixed-native-fixture'", 'NATIVE_HEAD_BRANCH = null'],
+ ["WORKFLOW_PULL_REF = 'refs/pull/9999/merge'", 'WORKFLOW_PULL_REF = null'],
+ ["RUN_CONCLUSION = 'failure'", 'RUN_CONCLUSION = null'],
+ ["ARTIFACT = 991","ARTIFACT = null"], [`ZIP_SIZE = ${PAYLOAD.length}`,'ZIP_SIZE = null'],
+ [`DIGEST = '${DIGEST}'`,'DIGEST = null'], ["NATIVE_CONCLUSION = 'failure'",'NATIVE_CONCLUSION = null'],
+ ["STEP_CONCLUSIONS = ['success', 'failure']",'STEP_CONCLUSIONS = null'],
+ ["STEP_CONCLUSIONS = ['success', 'failure']", "STEP_CONCLUSIONS = ['success', ,]"],
+ ["STEP_CONCLUSIONS = ['success', 'failure']", "STEP_CONCLUSIONS = ['success', undefined]"],
+ ["STEP_CONCLUSIONS = ['success', 'failure']", "STEP_CONCLUSIONS = ['success', null]"]]) {
+ const f=fixture({edit:s=>{assert.ok(s.includes(before)); return s.replace(before,after);}});
+ await assert.rejects(f.invoke,/FIXED_NATIVE_ARTIFACT_READOUT_FAILED/);
+ assert.deepEqual(f.calls,[]); assert.deepEqual(f.events,[]); assert.deepEqual(f.output,[]);
+ }
+});
+
+test('synthetic terminal job binds exact outcomes and purge precedes projection output',async()=>{
+ for(const completed of [false,true]) {
+ const f=fixture(); if(completed) Object.assign(f.runData,{status:'completed',conclusion:'failure'});
+ await f.invoke(); assert.equal(f.calls.filter(([name])=>name==='getJobForWorkflowRun').length,2);
+ assert.equal(f.calls[1][1].job_id,120848340201);
+ assert.ok(f.events.indexOf('close'){
+ for(const change of [f=>f.context.eventName='workflow_dispatch',f=>f.context.repo.owner='foreign',f=>f.context.ref='refs/heads/sprint',
+ f=>f.runData.id++,f=>f.runData.run_attempt++,f=>f.runData.head_sha=WORKFLOW,f=>f.runData.repository.id++,
+ f=>f.runData.head_repository.id++,f=>f.runData.status='queued',f=>f.runData.referenced_workflows=[],
+ f=>f.runData.referenced_workflows[0].sha=SOURCE,f=>f.jobData.id++,f=>f.jobData.run_attempt++,f=>f.jobData.run_id++,
+ f=>f.jobData.status='in_progress',f=>f.jobData.conclusion='success',f=>f.jobData.steps[0].conclusion='failure',
+ f=>f.jobData.steps[2].conclusion='failure',f=>f.jobData.steps.push(f.jobData.steps[2]),f=>f.artifact.id++,
+ f=>f.artifact.name+='foreign',f=>f.artifact.size_in_bytes++,f=>f.artifact.expired=true,
+ f=>f.artifact.digest='sha256:'+'0'.repeat(64),f=>f.artifact.workflow_run.id++,f=>f.artifact.workflow_run.head_sha=WORKFLOW]) {
+ const f=fixture(); change(f); await assert.rejects(f.invoke,/FIXED_NATIVE_ARTIFACT_READOUT_FAILED/);
+ assert.equal(f.calls.some(([name])=>name==='downloadArtifact'),false); assert.deepEqual(f.events,[]); assert.deepEqual(f.output,[]);
+ }
+});
+
+test('wrong ZIP size or digest fails before any filesystem or log operation',async()=>{
+ for(const payload of [Buffer.from('PRIVATE_SENTINEL'),Buffer.alloc(PAYLOAD.length)]) {
+ const f=fixture({payload}); await assert.rejects(f.invoke,/FIXED_NATIVE_ARTIFACT_READOUT_FAILED/);
+ assert.deepEqual(f.events,[]); assert.deepEqual(f.output,[]);
+ }
+});
+
+test('decoder write close cleanup and logging errors stay fixed and preserve purge ordering',async()=>{
+ for(const options of [{write:true,unlink:true,warning:true},{close:true},{decoder:true,unlink:true,warning:true},
+ {wrongOutput:true},{unlink:true,warning:true},{info:true}]) {
+ const f=fixture(options); await assert.rejects(f.invoke,options.unlink&&!options.write&&!options.decoder ?
+ /FIXED_NATIVE_ARTIFACT_PRIVATE_CLEANUP_FAILED/:/FIXED_NATIVE_ARTIFACT_READOUT_FAILED/);
+ assert.equal(f.events.filter(x=>x==='unlink').length,1);
+ if(options.info) assert.ok(f.events.indexOf('unlink'){
+ for(const after of [v=>v.runData.run_attempt++,v=>v.jobData.head_sha='0'.repeat(40),v=>v.artifact.expired=true]) {
+ const f=fixture({after});
+ await assert.rejects(f.invoke,/FIXED_NATIVE_ARTIFACT_READOUT_FAILED/);
+ assert.equal(f.events.includes('info'),false);
+ assert.equal(f.events.filter(x=>x==='unlink').length,1);
+ }
+});
+
+test('decoder diagnostics admit only fixed stage labels without private output',async()=>{
+ for(const [decoderOutput,stage] of [
+ ['STARTUP_7158_ANDROID_OBSERVATION_READOUT_FAILED:STARTUP\n','DECODE_STARTUP'],
+ ['STARTUP_7158_ANDROID_OBSERVATION_READOUT_FAILED:PRIVATE_SENTINEL\n','DECODE'],
+ ['PRIVATE_SENTINEL','DECODE']]) {
+ const f=fixture({decoder:true,decoderOutput});
+ await assert.rejects(f.invoke,error=>error.message==='FIXED_NATIVE_ARTIFACT_READOUT_FAILED_'+stage);
+ assert.deepEqual(f.output,[]);
+ assert.equal(f.events.filter(x=>x==='unlink').length,1);
+ }
+});
diff --git a/.github/tests/bea-android-artifact-readout.test.cjs b/.github/tests/bea-android-artifact-readout.test.cjs
new file mode 100644
index 0000000000..aac1121b60
--- /dev/null
+++ b/.github/tests/bea-android-artifact-readout.test.cjs
@@ -0,0 +1,166 @@
+'use strict';
+// Fabricated API and byte transport only; no current artifact/native operation.
+const assert = require('node:assert/strict');
+const crypto = require('node:crypto');
+const fs = require('node:fs');
+const path = require('node:path');
+const test = require('node:test');
+const vm = require('node:vm');
+const SCRIPT = path.join(__dirname, '../scripts/read-bea-android-artifact.cjs');
+const SOURCE = 'bea6056724dd75d1db99f4ce394ba4896edd10bf';
+const WORKFLOW = 'a'.repeat(40);
+const BINDINGS = "const WORKFLOW = 'fbb97bfe160e4b17d52bdf67aacc3f16aeb22f99', NATIVE_HEAD_BRANCH = 'codex/r5-native-failure-continuation-20261024', WORKFLOW_PULL_REF = 'refs/pull/7154/merge', RUN_CONCLUSION = 'failure';";
+const PAYLOAD = Buffer.from('OFFLINE_SYNTHETIC_METADATA_ZIP_BYTES');
+const DIGEST = crypto.createHash('sha256').update(PAYLOAD).digest('hex');
+const SELECTION = "const ARTIFACT = 12556810367, ZIP_SIZE = 9632, DIGEST = 'c653b9d73044a8cc67cc098ff561d5a42f0a11d49013ae88dfa9edf5bf69df1b';";
+const OUTCOME = "const NATIVE_CONCLUSION = 'failure', STEP_CONCLUSIONS = ['success', 'failure'];";
+
+function fixture(options = {}) {
+ const observedWorkflow = options.production ? 'fbb97bfe160e4b17d52bdf67aacc3f16aeb22f99' : WORKFLOW;
+ const context = { repo: { owner: 'KeeperCommunity', repo: 'bitcoin-keeper' },
+ eventName: 'push', ref: 'refs/heads/codex/r5-bea-android-artifact-readout-20261024' };
+ const runData = { id: 40078818062, run_attempt: 1, repository: { id: 470904030 },
+ head_repository: { id: 470904030 }, head_sha: SOURCE, event: 'pull_request',
+ head_branch: options.production ? 'codex/r5-native-failure-continuation-20261024' : 'codex/fixed-native-fixture',
+ path: '.github/workflows/keeper-native-diagnostic.yml', status: 'completed', conclusion: 'failure',
+ referenced_workflows: [{path: `KeeperCommunity/bitcoin-keeper/.github/workflows/keeper-native-platform.yml@${observedWorkflow}`,
+ ref: options.production ? 'refs/pull/7154/merge' : 'refs/pull/9999/merge', sha: observedWorkflow}] };
+ const jobData = { id: 120835800614, run_id: 40078818062, run_attempt: 1, head_sha: SOURCE,
+ status: 'completed', conclusion: 'failure', steps: [
+ ['Build development app', 'success'], ['Run Android startup and native persistence probes', 'failure'], ['Retain safe Phase A evidence', 'success']
+ ].map(([name, conclusion]) => ({name, conclusion, status: 'completed'})) };
+ const artifact = {id: options.production ? 12556810367 : 991,
+ name: `keeper-diagnostic-native-ANDROID-${SOURCE}-40078818062-1`, expired: false,
+ size_in_bytes: options.production ? 9632 : PAYLOAD.length,
+ digest: 'sha256:' + (options.production ? 'c653b9d73044a8cc67cc098ff561d5a42f0a11d49013ae88dfa9edf5bf69df1b' : DIGEST), workflow_run: {
+ id: 40078818062, head_sha: SOURCE, repository_id: 470904030, head_repository_id: 470904030}};
+ const calls = [], events = [], output = [], actions = {};
+ for (const [name, data] of [['getWorkflowRun', runData], ['getJobForWorkflowRun', jobData], ['getArtifact', artifact]]) {
+ actions[name] = async args => { calls.push([name, args]); return {data}; };
+ }
+ actions.downloadArtifact = async args => {calls.push(['downloadArtifact', args]); if(options.after) options.after({runData,jobData,artifact}); return {data: options.payload ?? PAYLOAD};};
+ const inputs = {github: {rest: {actions}}, context, core: {
+ info(value) {events.push('info'); if (options.info) throw Error('PRIVATE_SENTINEL'); output.push(value);},
+ warning(value) {events.push('warning'); if (options.warning) throw Error('PRIVATE_SENTINEL'); output.push(value);}}};
+ let source = fs.readFileSync(SCRIPT, 'utf8');
+ assert.ok(source.includes(SELECTION) && source.includes(OUTCOME));
+ if (!options.production) source = source.replace(SELECTION,
+ `const ARTIFACT = 991, ZIP_SIZE = ${PAYLOAD.length}, DIGEST = '${DIGEST}';`).replace(BINDINGS,
+ `const WORKFLOW = '${WORKFLOW}', NATIVE_HEAD_BRANCH = 'codex/fixed-native-fixture', WORKFLOW_PULL_REF = 'refs/pull/9999/merge', RUN_CONCLUSION = 'failure';`).replace(OUTCOME,
+ "const NATIVE_CONCLUSION = 'failure', STEP_CONCLUSIONS = ['success', 'failure'];");
+ if (options.edit) source = options.edit(source);
+ const api = {module: {exports: {}}, Buffer, process: {env: {RUNNER_TEMP: '/owned'}}, require(name) {
+ if (name === 'node:assert/strict') return {...assert, deepEqual(a,b) {assert.deepEqual(JSON.parse(JSON.stringify(a)), JSON.parse(JSON.stringify(b)));}};
+ if (name === 'node:crypto') return crypto;
+ if (name === 'node:path') return path;
+ if (name === 'node:fs') return {realpathSync: x => x,
+ openSync(file, flags, mode) {assert.equal(file, '/owned/r5-bea-android-fixed.zip'); assert.equal(flags, 'wx'); assert.equal(mode, 0o600); events.push('open'); return 42;},
+ writeFileSync(fd, bytes) {assert.equal(fd,42); assert.deepEqual(bytes,PAYLOAD); events.push('write'); if(options.write) throw Error('PRIVATE_SENTINEL');},
+ closeSync(fd) {assert.equal(fd,42); events.push('close'); if(options.close) throw Error('PRIVATE_SENTINEL');},
+ unlinkSync() {events.push('unlink'); if(options.unlink) throw Error('PRIVATE_SENTINEL');}};
+ if (name === 'node:child_process') return {execFileSync(command,args,settings) {
+ assert.equal(command,'python3'); assert.deepEqual(Array.from(args),['-B','.github/scripts/read-bea-android-artifact.py']);
+ assert.equal(settings.timeout,30000); events.push('decoder'); if(options.decoder) {
+ const error = Error('PRIVATE_SENTINEL'); error.stdout = options.decoderOutput; throw error;
+ }
+ return options.wrongOutput ? 'PRIVATE_SENTINEL' : 'BEA_ANDROID_OBSERVATIONS_BEGIN\n' + JSON.stringify({schema:1,scope:'OBSERVATIONS_ONLY_NOT_NATIVE_ACCEPTANCE_OR_CAUSE',original_zip_sha256:DIGEST,metadata_sha256:'a'.repeat(64),observations:{source_sha:SOURCE,run_id:'40078818062',run_attempt:'1'}}) + '\nBEA_ANDROID_OBSERVATIONS_END\n';}};
+ throw Error('Unexpected test import');
+ }};
+ vm.runInNewContext(source,api);
+ return {context,runData,jobData,artifact,calls,events,output,inputs,invoke:()=>api.module.exports.run(inputs)};
+}
+
+test('unavailable terminal selection rejects before API filesystem decoder or logging', async()=>{
+ const f=fixture({production:true,edit:s=>s.replace("WORKFLOW = 'fbb97bfe160e4b17d52bdf67aacc3f16aeb22f99'", 'WORKFLOW = null')});
+ await assert.rejects(f.invoke,/FIXED_NATIVE_ARTIFACT_READOUT_FAILED_SELECTION/);
+ assert.deepEqual(f.calls,[]); assert.deepEqual(f.events,[]); assert.deepEqual(f.output,[]);
+});
+
+test('exact observed production bindings select only original artifact and reject bad bytes before file or output',async()=>{
+ const f=fixture({production:true,payload:Buffer.alloc(9632)});
+ await assert.rejects(f.invoke,/FIXED_NATIVE_ARTIFACT_READOUT_FAILED_DOWNLOAD/);
+ assert.deepEqual(f.calls.map(([name])=>name),['getWorkflowRun','getJobForWorkflowRun','getArtifact','downloadArtifact']);
+ assert.equal(f.calls[2][1].artifact_id,12556810367); assert.equal(f.calls[3][1].artifact_id,12556810367);
+ assert.deepEqual(f.events,[]); assert.deepEqual(f.output,[]);
+});
+
+test('every incomplete observed binding fails before API/filesystem', async()=>{
+ for(const [before,after] of [[`WORKFLOW = '${WORKFLOW}'`, 'WORKFLOW = null'],
+ ["NATIVE_HEAD_BRANCH = 'codex/fixed-native-fixture'", 'NATIVE_HEAD_BRANCH = null'],
+ ["WORKFLOW_PULL_REF = 'refs/pull/9999/merge'", 'WORKFLOW_PULL_REF = null'],
+ ["RUN_CONCLUSION = 'failure'", 'RUN_CONCLUSION = null'],
+ ["ARTIFACT = 991","ARTIFACT = null"], [`ZIP_SIZE = ${PAYLOAD.length}`,'ZIP_SIZE = null'],
+ [`DIGEST = '${DIGEST}'`,'DIGEST = null'], ["NATIVE_CONCLUSION = 'failure'",'NATIVE_CONCLUSION = null'],
+ ["STEP_CONCLUSIONS = ['success', 'failure']",'STEP_CONCLUSIONS = null'],
+ ["STEP_CONCLUSIONS = ['success', 'failure']", "STEP_CONCLUSIONS = ['success', ,]"],
+ ["STEP_CONCLUSIONS = ['success', 'failure']", "STEP_CONCLUSIONS = ['success', undefined]"],
+ ["STEP_CONCLUSIONS = ['success', 'failure']", "STEP_CONCLUSIONS = ['success', null]"]]) {
+ const f=fixture({edit:s=>{assert.ok(s.includes(before)); return s.replace(before,after);}});
+ await assert.rejects(f.invoke,/FIXED_NATIVE_ARTIFACT_READOUT_FAILED/);
+ assert.deepEqual(f.calls,[]); assert.deepEqual(f.events,[]); assert.deepEqual(f.output,[]);
+ }
+});
+
+test('synthetic terminal job binds exact outcomes and purge precedes projection output',async()=>{
+ for(const completed of [false,true]) {
+ const f=fixture(); if(completed) Object.assign(f.runData,{status:'completed',conclusion:'failure'});
+ await f.invoke(); assert.equal(f.calls.filter(([name])=>name==='getJobForWorkflowRun').length,2);
+ assert.equal(f.calls[1][1].job_id,120835800614);
+ assert.ok(f.events.indexOf('close'){
+ for(const change of [f=>f.context.eventName='workflow_dispatch',f=>f.context.repo.owner='foreign',f=>f.context.ref='refs/heads/sprint',
+ f=>f.runData.id++,f=>f.runData.run_attempt++,f=>f.runData.head_sha=WORKFLOW,f=>f.runData.repository.id++,
+ f=>f.runData.head_repository.id++,f=>f.runData.status='queued',f=>f.runData.referenced_workflows=[],
+ f=>f.runData.referenced_workflows[0].sha=SOURCE,f=>f.jobData.id++,f=>f.jobData.run_attempt++,f=>f.jobData.run_id++,
+ f=>f.jobData.status='in_progress',f=>f.jobData.conclusion='success',f=>f.jobData.steps[0].conclusion='failure',
+ f=>f.jobData.steps[2].conclusion='failure',f=>f.jobData.steps.push(f.jobData.steps[2]),f=>f.artifact.id++,
+ f=>f.artifact.name+='foreign',f=>f.artifact.size_in_bytes++,f=>f.artifact.expired=true,
+ f=>f.artifact.digest='sha256:'+'0'.repeat(64),f=>f.artifact.workflow_run.id++,f=>f.artifact.workflow_run.head_sha=WORKFLOW]) {
+ const f=fixture(); change(f); await assert.rejects(f.invoke,/FIXED_NATIVE_ARTIFACT_READOUT_FAILED/);
+ assert.equal(f.calls.some(([name])=>name==='downloadArtifact'),false); assert.deepEqual(f.events,[]); assert.deepEqual(f.output,[]);
+ }
+});
+
+test('wrong ZIP size or digest fails before any filesystem or log operation',async()=>{
+ for(const payload of [Buffer.from('PRIVATE_SENTINEL'),Buffer.alloc(PAYLOAD.length)]) {
+ const f=fixture({payload}); await assert.rejects(f.invoke,/FIXED_NATIVE_ARTIFACT_READOUT_FAILED/);
+ assert.deepEqual(f.events,[]); assert.deepEqual(f.output,[]);
+ }
+});
+
+test('decoder write close cleanup and logging errors stay fixed and preserve purge ordering',async()=>{
+ for(const options of [{write:true,unlink:true,warning:true},{close:true},{decoder:true,unlink:true,warning:true},
+ {wrongOutput:true},{unlink:true,warning:true},{info:true}]) {
+ const f=fixture(options); await assert.rejects(f.invoke,options.unlink&&!options.write&&!options.decoder ?
+ /FIXED_NATIVE_ARTIFACT_PRIVATE_CLEANUP_FAILED/:/FIXED_NATIVE_ARTIFACT_READOUT_FAILED/);
+ assert.equal(f.events.filter(x=>x==='unlink').length,1);
+ if(options.info) assert.ok(f.events.indexOf('unlink'){
+ for(const after of [v=>v.runData.run_attempt++,v=>v.jobData.head_sha='0'.repeat(40),v=>v.artifact.expired=true]) {
+ const f=fixture({after});
+ await assert.rejects(f.invoke,/FIXED_NATIVE_ARTIFACT_READOUT_FAILED/);
+ assert.equal(f.events.includes('info'),false);
+ assert.equal(f.events.filter(x=>x==='unlink').length,1);
+ }
+});
+
+test('decoder diagnostics admit only fixed stage labels without private output',async()=>{
+ for(const [decoderOutput,stage] of [
+ ['BEA_ANDROID_OBSERVATION_READOUT_FAILED:PRODUCT\n','DECODE_PRODUCT'],
+ ['BEA_ANDROID_OBSERVATION_READOUT_FAILED:PRIVATE_SENTINEL\n','DECODE'],
+ ['PRIVATE_SENTINEL','DECODE']]) {
+ const f=fixture({decoder:true,decoderOutput});
+ await assert.rejects(f.invoke,error=>error.message==='FIXED_NATIVE_ARTIFACT_READOUT_FAILED_'+stage);
+ assert.deepEqual(f.output,[]);
+ assert.equal(f.events.filter(x=>x==='unlink').length,1);
+ }
+});
diff --git a/.github/tests/canonical-native.test.cjs b/.github/tests/canonical-native.test.cjs
new file mode 100644
index 0000000000..3d2f73cc65
--- /dev/null
+++ b/.github/tests/canonical-native.test.cjs
@@ -0,0 +1,255 @@
+const assert = require('node:assert/strict');
+const { test } = require('node:test');
+const fs = require('node:fs');
+const os = require('node:os');
+const path = require('node:path');
+const crypto = require('node:crypto');
+const driver = require('../native/canonical_native.cjs');
+const { attach: attachPublicCompanions } = require('./fixtures/public-companions.cjs');
+const hash = value => crypto.createHash('sha256').update(value).digest('hex');
+
+function fixture() {
+ const source = 'a'.repeat(40), repository = driver.REPOSITORY;
+ const context = { eventName: 'workflow_dispatch', ref: 'refs/heads/sprint', sha: source, runId: 400,
+ repo: { owner: 'KeeperCommunity', repo: 'bitcoin-keeper' } };
+ const env = { KEEPER_SOURCE_SHA: source, GITHUB_WORKFLOW_SHA: source, KEEPER_CANONICAL_NATIVE_DRIVER_SHA: source,
+ GITHUB_WORKFLOW_REF: `${repository}/${driver.WORKFLOW}@refs/heads/sprint`, GITHUB_RUN_ID: '400', GITHUB_RUN_ATTEMPT: '2' };
+ const request = driver.requestFromEnvironment(context, env);
+ const state = { context, env, request, calls: [], branchReads: 0,
+ repository: { id: driver.REPOSITORY_ID, full_name: repository, default_branch: 'sprint' },
+ pin: { name: 'KEEPER_CANONICAL_NATIVE_DRIVER_SHA', value: source },
+ branch: { protected: true, commit: { sha: source } }, workflow: { id: 30, path: driver.WORKFLOW, state: 'active' },
+ run: { id: 400, run_attempt: 2, workflow_id: 30, event: 'workflow_dispatch', path: driver.WORKFLOW,
+ head_sha: source, head_branch: 'sprint', head_repository: { id: driver.REPOSITORY_ID, full_name: repository },
+ pull_requests: [], status: 'in_progress', check_suite_id: 77 },
+ suite: { id: 77, app: { id: 15368, slug: 'github-actions' }, head_sha: source }, active: [] };
+ state.jobs = ['IOS', 'ANDROID'].map((platform, index) => ({
+ name: `${platform.toLowerCase()} / Canonical ${platform} build and features`, run_id: 400, run_attempt: 2,
+ head_sha: source, status: 'completed', conclusion: 'success',
+ check_run_url: `https://api.github.com/repos/${repository}/check-runs/${90 + index}`,
+ steps: driver.requiredSteps(platform).map(name => ({ name, status: 'completed', conclusion: 'success' })),
+ }));
+ state.metadata = Object.fromEntries(['IOS', 'ANDROID'].map(platform => [platform, {
+ schema: 1, platform, source_sha: source, workflow_sha: source, workflow_ref: env.GITHUB_WORKFLOW_REF,
+ run_id: '400', run_attempt: '2', diagnostic_only: false,
+ app_id: platform === 'IOS' ? 'io.hexawallet.hexakeeper.dev' : 'io.hexawallet.keeper.development',
+ build: 'PASS', smoke: 'PASS', native_probe: 'PASS', r5_features: 'PASS', private_field: 'PRIVATE_SENTINEL',
+ product_ui: { status: 'PASS', requested_samples: 5, controlled_disconnect_retry: { status: 'PASS' },
+ samples: [1, 2, 3, 4, 5].map(sample => ({ sample, status: 'PASS', create_new_app_calls: 1,
+ visible_wallet_count_before_relaunch: 1, visible_wallet_count_after_relaunch: 1,
+ raw_durations: { startup_to_passcode_ms: 120, start_new_to_ready_ms: 500 } })) },
+ }]));
+ for (const platform of ['IOS', 'ANDROID']) attachPublicCompanions(state.metadata[platform], platform);
+ state.archives = Object.values(state.metadata).map(value => Buffer.from(JSON.stringify(value)));
+ state.artifacts = ['IOS', 'ANDROID'].map((platform, index) => ({ id: 101 + index,
+ name: driver.artifactName(platform, request), expired: false, size_in_bytes: state.archives[index].length,
+ digest: `sha256:${hash(state.archives[index])}`, workflow_run: { id: 400, head_sha: source } }));
+ const wrap = (name, fn) => async args => { state.calls.push(name); return { data: await fn(args) }; };
+ state.github = { rest: {
+ repos: { get: wrap('repository', () => state.repository), getBranch: wrap('branch', () => {
+ state.branchReads++; return state.moveAfterRead && state.branchReads > 1 ? { ...state.branch, commit: { sha: 'b'.repeat(40) } } : state.branch;
+ }) },
+ actions: { getWorkflow: wrap('workflow', args => {
+ assert.equal(args.workflow_id, 'keeper-canonical-native.yml'); return state.workflow;
+ }), getWorkflowRun: wrap('run', () => state.run),
+ listWorkflowRuns: wrap('runs', () => ({ total_count: state.newerRun ? 2 : 1, workflow_runs: state.newerRun ? [state.run, { ...state.run, id: 401 }] : [state.run] })),
+ getRepoVariable: () => { throw new Error('DEFAULT_GITHUB_TOKEN_CANNOT_READ_VARIABLES'); },
+ listWorkflowRunsForRepo: wrap('capacity', args => {
+ state.capacityStatuses ??= []; state.capacityStatuses.push(args.status);
+ const selected = state.waitingOnly ? args.status === 'waiting' ? state.active : [] : state.active;
+ return { total_count: selected.length, workflow_runs: selected };
+ }),
+ listJobsForWorkflowRunAttempt: () => {},
+ listWorkflowRunArtifacts: wrap('artifacts', () => ({ total_count: state.artifacts.length, artifacts: state.artifacts })),
+ getArtifact: wrap('artifact-current', args => ({ ...state.artifacts[args.artifact_id - 101],
+ ...(state.expireAfterDownload ? { expired: true } : {}) })),
+ downloadArtifact: wrap('download', args => {
+ state.downloaded = true;
+ if (state.staleAfterDownload) state.run = { ...state.run, run_attempt: 3 };
+ return state.archives[args.artifact_id - 101];
+ }) },
+ checks: { getSuite: wrap('suite', () => state.suite), get: wrap('check', args => ({
+ id: state.checkId ?? args.check_run_id,
+ name: state.checkName ?? state.jobs[args.check_run_id - 90]?.name,
+ app: state.checkApp || { id: 15368, slug: 'github-actions' }, head_sha: source,
+ check_suite: { id: 77 }, status: 'completed', conclusion: 'success' })) },
+ git: { getCommit: wrap('tree', () => ({ sha: source, tree: { sha: 'c'.repeat(40) } })) },
+ }, paginate: async () => state.jobs };
+ state.pinReader = { rest: { actions: { getRepoVariable: wrap('pin', args => {
+ assert.deepEqual(args, { ...context.repo, name: 'KEEPER_CANONICAL_NATIVE_DRIVER_SHA',
+ headers: { 'cache-control': 'no-cache' } });
+ if (state.pinUnavailable || (state.credentialRevokedAfterDownload && state.downloaded))
+ throw Object.assign(new Error('Resource not accessible'), { status: state.pinUnavailable || 401 });
+ return state.pinAfterDownload && state.downloaded ? { ...state.pin, value: '' } : state.pin;
+ }) } } };
+ return state;
+}
+
+function origin(f, options = {}) {
+ return driver.origin(f.github, f.context, f.request, { pinReader: f.pinReader, ...options });
+}
+
+function collect(f, output) {
+ return driver.collect(f.github, f.context, f.request, output, raw => raw, { pinReader: f.pinReader });
+}
+
+test('dedicated pin identity is mandatory and removed from child-process environment', () => {
+ const instances = [];
+ class Octokit {
+ constructor(options) { instances.push(options); }
+ }
+ const github = new Octokit({ auth: 'default-token' });
+ const env = { KEEPER_CANONICAL_PIN_READ_TOKEN: 'variables-read-token', GITHUB_TOKEN: 'default-token' };
+ const reader = driver.pinReaderFromEnvironment(github, env);
+ assert.ok(reader instanceof Octokit);
+ assert.notEqual(reader, github);
+ assert.deepEqual(instances, [{ auth: 'default-token' }, { auth: 'variables-read-token' }]);
+ assert.deepEqual(env, { GITHUB_TOKEN: 'default-token' });
+ for (const token of [undefined, null, '', ' ']) {
+ const missing = { KEEPER_CANONICAL_PIN_READ_TOKEN: token, GITHUB_TOKEN: 'default-token' };
+ assert.throws(() => driver.pinReaderFromEnvironment(github, missing), /LIVE_DRIVER_PIN_IDENTITY_REQUIRED/);
+ assert.equal(Object.hasOwn(missing, 'KEEPER_CANONICAL_PIN_READ_TOKEN'), false);
+ }
+});
+
+test('default Variables denial cannot block the separate reader or supply a fallback', async () => {
+ const f = fixture();
+ await origin(f);
+ assert.equal(f.calls.filter(call => call === 'pin').length, 1);
+ for (const pinReader of [undefined, null, {}, { rest: { actions: {} } }]) {
+ await assert.rejects(driver.origin(f.github, f.context, f.request, { pinReader }), /LIVE_DRIVER_PIN_IDENTITY_REQUIRED/);
+ }
+});
+
+test('only pinned immutable manual canonical source is admitted', () => {
+ const f = fixture(); assert.equal(f.request.sourceSha, f.context.sha);
+ for (const change of [x => { x.env.KEEPER_CANONICAL_NATIVE_DRIVER_SHA = ''; },
+ x => { x.context.eventName = 'pull_request'; }, x => { x.context.ref = 'refs/heads/untrusted'; },
+ x => { x.env.GITHUB_WORKFLOW_SHA = 'b'.repeat(40); }, x => { x.env.GITHUB_RUN_ATTEMPT = '0'; },
+ x => { x.env.GITHUB_WORKFLOW_REF = 'other'; }]) {
+ const bad = fixture(); change(bad); assert.throws(() => driver.requestFromEnvironment(bad.context, bad.env));
+ }
+});
+test('actual Actions app and exact current protected source/run/attempt are required', async () => {
+ await origin(fixture());
+ for (const change of [x => { x.suite.app.id = 999; }, x => { x.run.id++; },
+ x => { x.run.run_attempt--; }, x => { x.run.head_sha = 'b'.repeat(40); },
+ x => { x.run.path = '.github/workflows/forged.yml'; }, x => { x.workflow.state = 'disabled_manually'; },
+ x => { x.run.head_repository.id = 9; }, x => { x.branch.protected = false; },
+ x => { x.branch.commit.sha = 'b'.repeat(40); }, x => { x.newerRun = true; },
+ x => { x.run.event = 'pull_request'; }, x => { x.run.pull_requests.push({ number: 7058 }); }]) {
+ const f = fixture(); change(f); await assert.rejects(origin(f));
+ }
+});
+test('capacity admission rejects other native runs without cancelling them', async () => {
+ const f = fixture();
+ for (const path of ['keeper-hosted-native.yml', 'keeper-one-time-native.yml', 'keeper-one-time-native-diagnostic.yml']) {
+ f.active = [{ id: 99, path: '.github/workflows/' + path }];
+ await assert.rejects(origin(f, { admission: true }), /ANOTHER_NATIVE/);
+ assert.equal(f.active[0].id, 99);
+ }
+ f.active = [{ id: 98, path: '.github/workflows/test.yml' }];
+ await origin(f, { admission: true });
+ assert.deepEqual([...new Set(f.capacityStatuses)].sort(), ['in_progress', 'pending', 'queued', 'requested', 'waiting']);
+});
+test('waiting native capacity fails closed', async () => {
+ const f = fixture(); f.waitingOnly = true; f.active = [{ id: 99, path: driver.WORKFLOW }];
+ await assert.rejects(origin(f, { admission: true }), /ANOTHER_NATIVE_RUN_ACTIVE_OR_QUEUED/);
+});
+test('revoked, malformed and unreadable live Variables pins fail closed', async () => {
+ for (const change of [x => { x.pin.value = ''; }, x => { x.pin.value = 'b'.repeat(40); },
+ x => { x.pin.name = 'other'; }, x => { x.pin = null; }, x => { x.pin = {}; }, x => { x.pinUnavailable = 401; },
+ x => { x.pinUnavailable = 403; }, x => { x.pinUnavailable = 404; },
+ x => { x.pinUnavailable = 500; }]) {
+ const f = fixture(); change(f);
+ await assert.rejects(origin(f, { admission: true }), /LIVE_DRIVER_PIN_REVOKED_OR_UNREADABLE/);
+ }
+});
+test('missing/skipped/duplicate/stale platform jobs or forged check apps cannot pass', async () => {
+ for (const change of [x => { x.jobs.pop(); }, x => { x.jobs.push(x.jobs[0]); },
+ x => { x.jobs[0].run_attempt = 1; }, x => { x.jobs[0].conclusion = 'skipped'; },
+ x => { x.jobs[0].steps[0].conclusion = 'skipped'; }, x => { x.jobs[0].steps.pop(); },
+ x => { x.checkApp = { id: 4, slug: 'github-actions' }; },
+ x => { x.checkId = 999; }, x => { x.checkName = 'other job'; }]) {
+ const f = fixture(); change(f); await assert.rejects(driver.platformJobs(f.github, f.context, f.request, f.run));
+ }
+});
+test('receipt identity rejects another source/platform/app/workflow/run attempt', () => {
+ for (const change of [x => { x.source_sha = 'b'.repeat(40); }, x => { x.platform = 'ANDROID'; },
+ x => { x.app_id = 'io.production.app'; }, x => { x.workflow_ref = 'other'; },
+ x => { x.run_attempt = '1'; }, x => { x.run_id = '401'; }, x => { x.diagnostic_only = true; }]) {
+ const f = fixture(), metadata = structuredClone(f.metadata.IOS); change(metadata);
+ assert.throws(() => driver.validateMetadata(metadata, f.request, 'IOS'));
+ }
+});
+test('real implemented observations stay discoverable without clearing parent obligations', () => {
+ const f = fixture(), result = driver.validateMetadata(f.metadata.IOS, f.request, 'IOS');
+ assert.equal(result.executed_checks['five-product-observations'].status, 'PASS');
+ assert.equal(result.executed_checks['production-worker-controls'].status, 'PASS');
+ assert.equal(result.cases.filter(item => item.status === 'NOT IMPLEMENTED').length, 5);
+ for (const name of ['controlled-credential-json-ui', 'controlled-version-history-ui', 'vault-reference-and-logical-archive-ui'])
+ assert.equal(result.executed_checks[name].status, 'PASS');
+});
+test('canonical public subsets retain exact receipt identity and missing evidence never gets a pass', () => {
+ for (const platform of ['IOS', 'ANDROID']) {
+ const f = fixture(), metadata = f.metadata[platform];
+ delete metadata.product_ui.credential_errors_ui;
+ metadata.product_version_history_ui.original_history_restored = false;
+ metadata.product_ui.vault_references_ui.installed_artifact_verified = false;
+ const result = driver.validateMetadata(metadata, f.request, platform);
+ for (const name of ['controlled-credential-json-ui', 'controlled-version-history-ui', 'vault-reference-and-logical-archive-ui'])
+ assert.equal(result.executed_checks[name].status, 'NOT VERIFIED');
+ assert.equal(result.cases.filter(item => item.status === 'NOT IMPLEMENTED').length, 5);
+ for (const [key, value] of [['source_sha', 'b'.repeat(40)], ['run_attempt', '1'], ['workflow_sha', 'b'.repeat(40)]]) {
+ const stale = attachPublicCompanions(structuredClone(f.metadata[platform]), platform);
+ stale[key] = value;
+ assert.throws(() => driver.validateMetadata(stale, f.request, platform), /IDENTITY_MISMATCH/);
+ }
+ }
+});
+test('artifact names, digests and current-attempt provenance are independently checked', async () => {
+ for (const change of [x => { x.artifacts[0].name = x.artifacts[0].name.replace('-2', '-1'); },
+ x => { x.artifacts[0].digest = `sha256:${'0'.repeat(64)}`; }, x => { x.artifacts[0].expired = true; },
+ x => { x.artifacts[0].workflow_run.id = 399; }, x => { x.artifacts[0].size_in_bytes++; },
+ x => { x.expireAfterDownload = true; }]) {
+ const f = fixture(), output = fs.mkdtempSync(path.join(os.tmpdir(), 'canonical-test-'));
+ try { change(f); await assert.rejects(collect(f, output)); }
+ finally { fs.rmSync(output, { recursive: true, force: true }); }
+ }
+});
+test('complete native subsets emit bounded BLOCKED readiness and no reusable attestation', async () => {
+ const f = fixture(), output = fs.mkdtempSync(path.join(os.tmpdir(), 'canonical-test-'));
+ try {
+ fs.writeFileSync(path.join(output, 'keeper-canonical-native-attestation.json'), 'stale');
+ await assert.rejects(collect(f, output), /MATRIX_INCOMPLETE/);
+ assert.equal(f.calls.filter(call => call === 'pin').length, 2, 'pin read both before and after downloads');
+ assert.equal(fs.existsSync(path.join(output, 'keeper-canonical-native-attestation.json')), false);
+ const raw = fs.readFileSync(path.join(output, 'keeper-canonical-native-readiness.json'), 'utf8');
+ const result = JSON.parse(raw); assert.equal(result.feature_matrix_complete, false);
+ assert.equal(Object.keys(result.platforms.IOS.executed_checks).length, 12);
+ for (const name of ['controlled-credential-json-ui', 'controlled-version-history-ui', 'vault-reference-and-logical-archive-ui'])
+ assert.equal(result.platforms.IOS.executed_checks[name].status, 'PASS');
+ assert.equal(result.platforms.IOS.cases.filter(item => item.status === 'NOT IMPLEMENTED').length, 5);
+ assert.equal(result.platforms.IOS.receipt_sha256, hash(f.archives[0]));
+ assert.equal(raw.includes('PRIVATE_SENTINEL'), false);
+ } finally { fs.rmSync(output, { recursive: true, force: true }); }
+});
+test('collector rejects missing reader and deletes an old positive artifact before any API read', async () => {
+ const f = fixture(), output = fs.mkdtempSync(path.join(os.tmpdir(), 'canonical-test-'));
+ try {
+ fs.writeFileSync(path.join(output, 'keeper-canonical-native-attestation.json'), 'stale');
+ await assert.rejects(driver.collect(f.github, f.context, f.request, output, raw => raw), /LIVE_DRIVER_PIN_IDENTITY_REQUIRED/);
+ assert.deepEqual(f.calls, []);
+ assert.equal(fs.existsSync(path.join(output, 'keeper-canonical-native-attestation.json')), false);
+ } finally { fs.rmSync(output, { recursive: true, force: true }); }
+});
+test('head movement and stale rerun after platform artifact download invalidate collection', async () => {
+ for (const change of [x => { x.moveAfterRead = true; }, x => { x.staleAfterDownload = true; },
+ x => { x.pinAfterDownload = true; }, x => { x.credentialRevokedAfterDownload = true; }]) {
+ const f = fixture(), output = fs.mkdtempSync(path.join(os.tmpdir(), 'canonical-test-'));
+ try { change(f); await assert.rejects(collect(f, output));
+ assert.equal(fs.existsSync(path.join(output, 'keeper-canonical-native-attestation.json')), false);
+ assert.equal(fs.existsSync(path.join(output, 'keeper-canonical-native-readiness.json')), false); }
+ finally { fs.rmSync(output, { recursive: true, force: true }); }
+ }
+});
diff --git a/.github/tests/ci-raw-source.test.cjs b/.github/tests/ci-raw-source.test.cjs
new file mode 100644
index 0000000000..4722b13895
--- /dev/null
+++ b/.github/tests/ci-raw-source.test.cjs
@@ -0,0 +1,185 @@
+'use strict';
+const assert = require('node:assert/strict');
+const fs = require('node:fs');
+const os = require('node:os');
+const path = require('node:path');
+const { execFileSync, spawnSync } = require('node:child_process');
+const test = require('node:test');
+const { verifySource, verifyRawCheckout } = require('../scripts/verify-ci-source.cjs');
+
+function fixture(t, kind = 'app') {
+ const base = fs.mkdtempSync(path.join(os.tmpdir(), 'keeper-raw-source-'));
+ t.after(() => fs.rmSync(base, { recursive: true, force: true }));
+ const app = path.join(base, 'app');
+ fs.mkdirSync(app);
+ const root = kind === 'app' ? app : path.join(app, '.ci-relay');
+ fs.mkdirSync(root, { recursive: true });
+ const git = (...args) => execFileSync('git', args, {
+ cwd: root, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'],
+ }).trim();
+ git('init', '--quiet');
+ git('config', 'user.email', 'disposable-source@example.invalid');
+ git('config', 'user.name', 'Disposable raw source control');
+ fs.mkdirSync(path.join(root, 'src'));
+ fs.writeFileSync(path.join(root, 'src/source.js'), 'module.exports = "original";\n');
+ fs.writeFileSync(path.join(root, 'src/run.sh'), '#!/bin/sh\nexit 0\n', { mode: 0o755 });
+ fs.writeFileSync(path.join(root, 'binary.bin'), Buffer.from([0, 255, 1, 13, 10]));
+ fs.writeFileSync(path.join(root, 'space\ttab\nline-☃.txt'), 'unusual Git path\n');
+ fs.writeFileSync(path.join(root, '.gitignore'), 'ignored-output/\n');
+ git('add', '.'); git('commit', '--quiet', '-m', 'disposable candidate');
+ return { base, root, git, kind, head: git('rev-parse', 'HEAD') };
+}
+function check(f, root = f.root) {
+ return f.kind === 'app' ? verifySource({ root, event: { pull_request: { head: { sha: f.head } } },
+ env: { GITHUB_EVENT_NAME: 'pull_request', GITHUB_RUN_ID: '123', GITHUB_RUN_ATTEMPT: '2' } }) :
+ verifyRawCheckout(root, f.head);
+}
+function hidden(f, flag, paths = ['src/source.js']) {
+ f.git('update-index', flag, '--', ...paths);
+}
+function cleanStatus(f) { assert.equal(f.git('status', '--porcelain', '--untracked-files=normal'), ''); }
+function commit(f) { f.git('add', '.'); f.git('commit', '--quiet', '-m', 'changed disposable candidate'); f.head = f.git('rev-parse', 'HEAD'); }
+
+for (const kind of ['app', 'paired Relay raw primitive']) {
+ test(`${kind}: clean bytes include binary and NUL-delimited unusual paths`, t => {
+ const f = fixture(t, kind);
+ cleanStatus(f);
+ assert.equal(verifyRawCheckout(f.root, f.head).files, 5);
+ check(f);
+ if (kind === 'app') assert.deepEqual(Object.keys(check(f)),
+ ['schema', 'source_sha', 'source_tree', 'event', 'run_id', 'run_attempt', 'workflow_sha', 'scope']);
+ });
+ for (const flag of ['--assume-unchanged', '--skip-worktree']) {
+ test(`${kind}: ${flag} cannot hide a same-length tracked edit or change index flags`, t => {
+ const f = fixture(t, kind); hidden(f, flag);
+ const filename = path.join(f.root, 'src/source.js'), before = fs.statSync(filename);
+ const bytes = fs.readFileSync(filename);
+ fs.writeFileSync(filename, 'module.exports = "tampered";\n');
+ assert.equal(fs.statSync(filename).size, bytes.length);
+ fs.utimesSync(filename, before.atime, before.mtime);
+ cleanStatus(f);
+ const index = fs.readFileSync(path.join(f.root, '.git/index'));
+ assert.throws(() => check(f), /Raw source differs/);
+ assert.deepEqual(fs.readFileSync(path.join(f.root, '.git/index')), index);
+ });
+ test(`${kind}: ${flag} cannot hide a changed binary input`, t => {
+ const f = fixture(t, kind); hidden(f, flag, ['binary.bin']);
+ fs.writeFileSync(path.join(f.root, 'binary.bin'), Buffer.from([0, 254, 1, 13, 10]));
+ cleanStatus(f);
+ assert.throws(() => check(f), /Raw source differs/);
+ });
+ test(`${kind}: ${flag} cannot hide a deleted tracked input`, t => {
+ const f = fixture(t, kind); hidden(f, flag);
+ fs.unlinkSync(path.join(f.root, 'src/source.js'));
+ cleanStatus(f);
+ assert.throws(() => check(f), /ENOENT/);
+ });
+ test(`${kind}: ${flag} cannot replace a tracked file with a directory`, t => {
+ const f = fixture(t, kind); hidden(f, flag);
+ fs.unlinkSync(path.join(f.root, 'src/source.js'));
+ fs.mkdirSync(path.join(f.root, 'src/source.js'));
+ cleanStatus(f);
+ assert.throws(() => check(f), /regular tracked source/);
+ });
+ test(`${kind}: ${flag} cannot substitute a symlink with even the exact expected bytes`, t => {
+ const f = fixture(t, kind); hidden(f, flag);
+ const filename = path.join(f.root, 'src/source.js'), alternate = path.join(f.base, 'same-bytes.js');
+ fs.writeFileSync(alternate, fs.readFileSync(filename));
+ fs.unlinkSync(filename); fs.symlinkSync(alternate, filename);
+ cleanStatus(f);
+ assert.throws(() => check(f), /regular tracked source|alias rejected/);
+ });
+ test(`${kind}: parent directory alias is rejected by raw checking with ${flag}`, t => {
+ const f = fixture(t, kind); hidden(f, flag, ['src/source.js', 'src/run.sh']);
+ const directory = path.join(f.root, 'src'), alternate = path.join(f.base, 'same-directory');
+ fs.renameSync(directory, alternate); fs.symlinkSync(alternate, directory, 'dir');
+ // Git already exposes this directory substitution as added source. Check
+ // raw path admission independently rather than claiming status hid it.
+ assert.equal(f.git('status', '--porcelain'), '?? src');
+ assert.throws(() => verifyRawCheckout(f.root, f.head), /alias rejected/);
+ if (kind === 'app') assert.throws(() => check(f), /Source changed/);
+ });
+ }
+ for (const [relative, expectedExecutable] of [['src/source.js', false], ['src/run.sh', true]]) {
+ for (const mode of [0o644, 0o645, 0o654, 0o655, 0o744, 0o745, 0o754, 0o755]) {
+ test(`${kind}: ${relative} owner-only Git execute mode ${mode.toString(8)}`, t => {
+ const f = fixture(t, kind);
+ // Only this throwaway repository hides mode changes from status.
+ f.git('config', 'core.filemode', 'false');
+ fs.chmodSync(path.join(f.root, relative), mode);
+ cleanStatus(f);
+ if (((mode & 0o100) !== 0) === expectedExecutable) check(f);
+ else assert.throws(() => check(f), /owner execute mode changed/);
+ });
+ }
+ }
+ test(`${kind}: an actual path replacement during delegated reading cannot pass`, t => {
+ const f = fixture(t, kind), filename = path.join(f.root, 'src/source.js');
+ const inode = fs.statSync(filename).ino, originalRead = fs.readFileSync;
+ let replaced = false;
+ t.mock.method(fs, 'readFileSync', function (input, ...args) {
+ const bytes = originalRead.call(this, input, ...args);
+ if (!replaced && typeof input === 'number' && fs.fstatSync(input).ino === inode) {
+ replaced = true;
+ fs.renameSync(filename, path.join(f.base, 'replaced-original'));
+ fs.writeFileSync(filename, bytes);
+ }
+ return bytes;
+ });
+ assert.throws(() => check(f), /Tracked source replaced/);
+ assert.equal(replaced, true);
+ });
+ test(`${kind}: local replacement refs cannot substitute the pinned commit's raw tree`, t => {
+ const f = fixture(t, kind), original = f.head;
+ fs.writeFileSync(path.join(f.root, 'src/source.js'), 'module.exports = "tampered";\n');
+ commit(f);
+ const replacement = f.head;
+ f.git('replace', original, replacement);
+ f.git('update-ref', 'HEAD', original);
+ f.head = original;
+ cleanStatus(f);
+ assert.throws(() => check(f), /Source changed|Raw source differs/);
+ });
+ test(`${kind}: a checkout-root symlink cannot earn a source receipt`, t => {
+ const f = fixture(t, kind), alias = path.join(f.base, 'checkout-alias');
+ fs.symlinkSync(f.root, alias, 'dir');
+ assert.throws(() => check(f, alias), /Checkout alias rejected/);
+ });
+ test(`${kind}: committed symlink entries are rejected even with clean status`, t => {
+ const f = fixture(t, kind), filename = path.join(f.root, 'src/source.js');
+ fs.unlinkSync(filename); fs.symlinkSync('../binary.bin', filename); commit(f); cleanStatus(f);
+ assert.throws(() => check(f), /regular tracked Git blob/);
+ });
+ test(`${kind}: gitlink entries cannot omit a nested source tree`, t => {
+ const f = fixture(t, kind);
+ // A genuine initialized nested repository avoids a missing-submodule
+ // deletion being caught by status before raw Git entry admission.
+ execFileSync('git', ['clone', '--quiet', '--no-hardlinks', f.root, path.join(f.root, 'vendor')],
+ { stdio: ['ignore', 'pipe', 'pipe'] });
+ f.git('update-index', '--add', '--cacheinfo', `160000,${f.head},vendor`);
+ f.git('commit', '--quiet', '-m', 'disposable unsupported gitlink'); f.head = f.git('rev-parse', 'HEAD');
+ cleanStatus(f);
+ assert.throws(() => check(f), /regular tracked Git blob/);
+ });
+}
+
+test('ignored generated output keeps its existing allowance and is never treated as tracked source', t => {
+ const f = fixture(t);
+ fs.mkdirSync(path.join(f.root, 'ignored-output'));
+ fs.writeFileSync(path.join(f.root, 'ignored-output/result.txt'), 'generated output');
+ cleanStatus(f); check(f);
+});
+
+test('a failed raw-source CLI prints no edited bytes, path, environment value or receipt', t => {
+ const f = fixture(t); hidden(f, '--assume-unchanged');
+ fs.writeFileSync(path.join(f.root, 'src/source.js'), 'PRIVATE_RAW_SENTINEL'); cleanStatus(f);
+ const event = path.join(f.base, 'event.json');
+ fs.writeFileSync(event, JSON.stringify({ pull_request: { head: { sha: f.head } } }));
+ const result = spawnSync(process.execPath, [path.resolve(__dirname, '../scripts/verify-ci-source.cjs')], {
+ cwd: f.root, encoding: 'utf8', env: { PATH: process.env.PATH, GITHUB_EVENT_NAME: 'pull_request',
+ GITHUB_EVENT_PATH: event, PRIVATE_ENV_SENTINEL: 'never-export-this' },
+ });
+ assert.equal(result.status, 1);
+ assert.equal(result.stdout, '');
+ assert.equal(result.stderr, 'CI_SOURCE_IDENTITY_FAILED\n');
+});
diff --git a/.github/tests/ci-source-identity.test.cjs b/.github/tests/ci-source-identity.test.cjs
new file mode 100644
index 0000000000..4a5b0fdfb8
--- /dev/null
+++ b/.github/tests/ci-source-identity.test.cjs
@@ -0,0 +1,93 @@
+'use strict';
+const assert = require('node:assert/strict');
+const fs = require('node:fs');
+const os = require('node:os');
+const path = require('node:path');
+const { execFileSync } = require('node:child_process');
+const test = require('node:test');
+const { verifySource } = require('../scripts/verify-ci-source.cjs');
+
+function fixture(t) {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'keeper-ci-source-'));
+ t.after(() => fs.rmSync(root, { recursive: true, force: true }));
+ const git = (...args) => execFileSync('git', args, { cwd: root, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();
+ git('init', '--quiet');
+ git('config', 'user.email', 'disposable-ci@example.invalid');
+ git('config', 'user.name', 'Disposable source control');
+ fs.writeFileSync(path.join(root, 'source.txt'), 'immutable input\n');
+ git('add', '.'); git('commit', '--quiet', '-m', 'candidate');
+ const head = git('rev-parse', 'HEAD');
+ return { root, git, head, env: { GITHUB_EVENT_NAME: 'pull_request', GITHUB_RUN_ID: '123', GITHUB_RUN_ATTEMPT: '2' },
+ event: { pull_request: { head: { sha: head } } } };
+}
+
+test('actual clean event head emits its exact commit and tree without secret environment data', t => {
+ const f = fixture(t);
+ const r = verifySource({ ...f, env: { ...f.env, PRIVATE_SENTINEL: 'never-export-this' } });
+ assert.equal(r.source_sha, f.head);
+ assert.equal(r.source_tree, f.git('rev-parse', 'HEAD^{tree}'));
+ assert.equal(r.run_attempt, '2');
+ assert.equal(JSON.stringify(r).includes('never-export-this'), false);
+});
+
+test('a different commit is rejected even when it has the exact same source tree', t => {
+ const f = fixture(t);
+ f.git('commit', '--allow-empty', '--quiet', '-m', 'synthetic merge stand-in');
+ assert.equal(f.git('rev-parse', 'HEAD^{tree}'), f.git('rev-parse', `${f.head}^{tree}`));
+ assert.throws(() => verifySource(f), /differs from the event source/);
+});
+
+test('tracked staged or unstaged changes cannot retain a source pass', t => {
+ const f = fixture(t);
+ fs.appendFileSync(path.join(f.root, 'source.txt'), 'changed\n');
+ assert.throws(() => verifySource(f), /Source changed/);
+ f.git('add', '.');
+ assert.throws(() => verifySource(f), /Source changed/);
+});
+
+test('added nonignored source and counterfeit or aliased paired checkouts are rejected', t => {
+ const f = fixture(t);
+ fs.mkdirSync(path.join(f.root, 'src'));
+ fs.writeFileSync(path.join(f.root, 'src/extra.js'), 'module.exports = true;\n');
+ assert.throws(() => verifySource(f), /Source changed/);
+ fs.rmSync(path.join(f.root, 'src'), { recursive: true });
+ const relay = path.join(f.root, '.ci-relay');
+ fs.mkdirSync(relay);
+ f.git('-C', relay, 'init', '--quiet');
+ f.git('-C', relay, 'config', 'user.email', 'disposable-ci@example.invalid');
+ f.git('-C', relay, 'config', 'user.name', 'Disposable paired control');
+ f.git('-C', relay, 'commit', '--allow-empty', '--quiet', '-m', 'wrong paired source');
+ assert.throws(() => verifySource(f), /Source changed/);
+ assert.throws(() => verifySource({ ...f, allowPairedRelay: true }), /Unexpected paired Relay source/);
+ fs.rmSync(relay, { recursive: true });
+ fs.symlinkSync(os.tmpdir(), relay, 'dir');
+ assert.throws(() => verifySource({ ...f, allowPairedRelay: true }), /Source changed|alias rejected/);
+});
+
+test('push uses its event commit while invalid or absent PR heads and other events fail closed', t => {
+ const f = fixture(t);
+ assert.equal(verifySource({ ...f, env: { ...f.env, GITHUB_EVENT_NAME: 'push', GITHUB_SHA: f.head } }).source_sha, f.head);
+ for (const sha of [undefined, '', 'refs/heads/sprint', 'a'.repeat(39), 'A'.repeat(40)])
+ assert.throws(() => verifySource({ ...f, event: { pull_request: { head: { sha } } } }), /exact event source/);
+ assert.throws(() => verifySource({ ...f, env: { ...f.env, GITHUB_EVENT_NAME: 'pull_request_target' } }), /Unsupported/);
+});
+
+test('all three CI jobs select the event head and verify source before setup, after setup and after checks', () => {
+ const source = fs.readFileSync(path.resolve(__dirname, '../workflows/test.yml'), 'utf8');
+ const chunks = source.split(/\n (?:lint|test|automatic-backup-genuine):\n/).slice(1);
+ assert.equal(chunks.length, 3);
+ for (const chunk of chunks) {
+ assert.match(chunk, /ref: \$\{\{ github\.event\.pull_request\.head\.sha \|\| github\.sha \}\}/);
+ assert.equal((chunk.match(/node \.github\/scripts\/verify-ci-source\.cjs/g) || []).length, 3);
+ const first = chunk.indexOf('node .github/scripts/verify-ci-source.cjs');
+ const install = chunk.search(/Install (?:Keeper )?dependencies/);
+ const last = chunk.lastIndexOf('node .github/scripts/verify-ci-source.cjs');
+ assert.ok(first < install && last > install);
+ assert.match(chunk, /name: Verify exact source after checks\n\s+if: always\(\)/);
+ const finalCheck = chunk.lastIndexOf('name: Verify exact source after checks');
+ assert.ok(finalCheck > chunk.lastIndexOf('name: Test Android reproducibility tools'));
+ if (chunk.includes('name: Automatic backup native Realm and Relay'))
+ assert.equal((chunk.match(/verify-ci-source\.cjs --paired-relay/g) || []).length, 3);
+ else assert.equal(chunk.includes('--paired-relay'), false);
+ }
+});
diff --git a/.github/tests/credential_fixture.test.cjs b/.github/tests/credential_fixture.test.cjs
new file mode 100644
index 0000000000..8cb79a7415
--- /dev/null
+++ b/.github/tests/credential_fixture.test.cjs
@@ -0,0 +1,132 @@
+/* Fake adapters validate fixture safety only. No native acceptance credit. */
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const { BACKUP_SERVICE, MALFORMED, runFixture } = require('../native/credential_fixture_core');
+const config = { ENVIRONMENT: 'DEVELOPMENT', RELAY: 'http://127.0.0.1:8765/',
+ ENC_KEY_STORAGE_IDENTIFIER: 'KEEPER-HOSTED-DISPOSABLE' };
+const secret = 'PRIVATE_SECRET_SENTINEL';
+function fixture() {
+ const account = { isDefault: true, accountIdentifier: '', appId: 'disposable',
+ realmId: 'owned.realm', hash: 'disposable-hash' };
+ const root = { account: JSON.stringify({ allAccounts: [account] }),
+ storage: JSON.stringify({ appId: account.appId }) };
+ const original = { username: config.ENC_KEY_STORAGE_IDENTIFIER,
+ password: JSON.stringify({ hash: account.hash, enc_key: secret, other: 'preserve-exact-bytes' }) };
+ const values = new Map([[undefined, structuredClone(original)]]);
+ const writes = [];
+ const storage = { getString: (key) => key === 'persist:root' ? JSON.stringify(root) : undefined };
+ const Keychain = { ACCESSIBLE: { WHEN_UNLOCKED: 'WHEN_UNLOCKED' },
+ async getGenericPassword({ service }) { return values.get(service) || false; },
+ async setGenericPassword(username, password, options) {
+ writes.push(options.service); values.set(options.service, { username, password }); return true;
+ },
+ async resetGenericPassword({ service }) { return values.delete(service); } };
+ return { account, root, original, values, writes, Keychain, storage,
+ run: (phase, extra = {}) => runFixture({ phase, Keychain, storage, config,
+ development: true, ...extra }) };
+}
+test('arm stores exact secret bytes only in Keychain and restore removes the verified backup', async () => {
+ const f = fixture();
+ const rootBefore = JSON.stringify(f.root);
+ assert.equal(await f.run('arm'), 'armed');
+ assert.equal(f.values.get(undefined).password, MALFORMED);
+ assert.deepEqual(f.writes, [BACKUP_SERVICE, undefined]);
+ assert.equal(await f.run('restore'), 'restored');
+ assert.deepEqual(f.values.get(undefined), f.original);
+ assert.equal(f.values.has(BACKUP_SERVICE), false);
+ assert.equal(JSON.stringify(f.root), rootBefore, 'fixture never mutates persisted app/account state');
+});
+test('successfully empty Keychain is rejected without writes and never called an error fixture', async () => {
+ const f = fixture(); f.values.delete(undefined);
+ await assert.rejects(f.run('arm'), /credential-required/);
+ assert.deepEqual(f.writes, []);
+});
+test('native Keychain rejection propagates without exporting its error or writing new credentials', async () => {
+ const f = fixture();
+ f.Keychain.getGenericPassword = async () => { throw new Error(secret); };
+ await assert.rejects(f.run('arm'));
+ assert.deepEqual(f.writes, []);
+ // The native UI wrapper catches every exception and displays fixed "failed" only.
+ const wrapper = require('node:fs').readFileSync(require('node:path').join(__dirname,
+ '../native/credential_fixture.js'), 'utf8');
+ assert.match(wrapper, /\.catch\(\(\) => 'failed'\)/);
+ assert.doesNotMatch(wrapper, /console\.|writeFile|fetch\(|JSON\.stringify/);
+});
+test('non-disposable build, unapproved phase, non-default and multiple owners are refused before writes', async () => {
+ const cases = [
+ (f) => f.run('arm', { development: false }),
+ (f) => f.run('arm', { config: { ...config, RELAY: 'https://production.invalid/' } }),
+ (f) => f.run('arm', { config: { ...config, ENC_KEY_STORAGE_IDENTIFIER: 'OTHER' } }),
+ (f) => f.run('unknown'),
+ (f) => { f.account.accountIdentifier = 'another'; f.root.account = JSON.stringify({ allAccounts: [f.account] }); return f.run('arm'); },
+ (f) => { f.root.account = JSON.stringify({ allAccounts: [f.account, f.account] }); return f.run('arm'); },
+ (f) => { f.root.storage = JSON.stringify({ appId: 'another' }); return f.run('arm'); },
+ ];
+ for (const attempt of cases) { const f = fixture(); await assert.rejects(attempt(f)); assert.deepEqual(f.writes, []); }
+});
+test('unknown prior backup and wrong account credential are never overwritten', async () => {
+ const f = fixture(); f.values.set(BACKUP_SERVICE, { username: 'other', password: secret });
+ await assert.rejects(f.run('arm'), /backup-already-present/);
+ assert.equal(f.values.get(BACKUP_SERVICE).password, secret);
+ assert.deepEqual(f.writes, []);
+ f.values.delete(BACKUP_SERVICE);
+ f.values.set(undefined, { ...f.original, password: JSON.stringify({ hash: 'other', enc_key: secret }) });
+ await assert.rejects(f.run('arm'), /matching-credential-required/);
+ assert.deepEqual(f.writes, []);
+});
+test('backup write/readback failure never corrupts the original', async () => {
+ for (const option of ['write', 'readback']) {
+ const f = fixture();
+ if (option === 'write') f.Keychain.setGenericPassword = async () => false;
+ else {
+ const get = f.Keychain.getGenericPassword;
+ f.Keychain.getGenericPassword = async (options) => options.service === BACKUP_SERVICE &&
+ f.values.has(BACKUP_SERVICE) ? { username: 'wrong', password: secret } : get(options);
+ }
+ await assert.rejects(f.run('arm'));
+ assert.deepEqual(f.values.get(undefined), f.original);
+ }
+});
+test('restore refuses account switches or changed credentials without overwriting them', async () => {
+ const f = fixture(); await f.run('arm');
+ f.root.account = JSON.stringify({ allAccounts: [{ ...f.account, realmId: 'another.realm' }] });
+ await assert.rejects(f.run('restore'), /backup-owner-mismatch/);
+ assert.equal(f.values.get(undefined).password, MALFORMED);
+ f.root.account = JSON.stringify({ allAccounts: [f.account] });
+ f.values.set(undefined, { username: f.original.username, password: 'CHANGED' });
+ await assert.rejects(f.run('restore'), /restore-source-changed/);
+ assert.equal(f.values.get(undefined).password, 'CHANGED');
+});
+test('restore readback and backup cleanup failures cannot emit restored', async () => {
+ for (const option of ['write', 'readback', 'cleanup', 'cleanup-readback']) {
+ const f = fixture(); await f.run('arm');
+ if (option === 'write') f.Keychain.setGenericPassword = async () => false;
+ if (option === 'readback') f.Keychain.setGenericPassword = async () => true;
+ if (option === 'cleanup') f.Keychain.resetGenericPassword = async () => false;
+ if (option === 'cleanup-readback') f.Keychain.resetGenericPassword = async () => true;
+ await assert.rejects(f.run('restore'));
+ }
+});
+test('alternate Metro config accepts only the two fixed fixture phases and leaves other requests alone', () => {
+ const fs = require('node:fs');
+ const path = require('node:path');
+ const vm = require('node:vm');
+ const filename = path.join(__dirname, '../native/credential_metro.cjs');
+ const source = fs.readFileSync(filename, 'utf8');
+ function load(phase) {
+ const context = { module: { exports: {} }, __dirname: path.dirname(filename),
+ process: { env: { KEEPER_CREDENTIAL_FIXTURE_PHASE: phase } },
+ require: (name) => name === 'node:path' ? path : {} };
+ vm.runInNewContext(source, context);
+ return context.module.exports;
+ }
+ for (const value of [undefined, 'product', '../index', 'arm?other']) assert.throws(() => load(value));
+ for (const phase of ['arm', 'restore']) {
+ const wrapped = load(phase).server.enhanceMiddleware((request) => request.url);
+ assert.equal(wrapped({ url: '/index.bundle?platform=ios' }),
+ `/.github/native/credential_${phase}.bundle?platform=ios`);
+ assert.equal(wrapped({ url: '/index.map' }), `/.github/native/credential_${phase}.map`);
+ assert.equal(wrapped({ url: '/index.bundle.other' }), '/index.bundle.other');
+ assert.equal(wrapped({ url: '/status' }), '/status');
+ }
+});
diff --git a/.github/tests/current-android-artifact-readout.test.cjs b/.github/tests/current-android-artifact-readout.test.cjs
new file mode 100644
index 0000000000..e51ce8014c
--- /dev/null
+++ b/.github/tests/current-android-artifact-readout.test.cjs
@@ -0,0 +1,151 @@
+'use strict';
+// Offline API/transport controls; no network, artifact download or native action.
+const assert = require('node:assert/strict');
+const crypto = require('node:crypto');
+const fs = require('node:fs');
+const path = require('node:path');
+const test = require('node:test');
+const vm = require('node:vm');
+const SCRIPT = path.join(__dirname, '../scripts/read-current-android-artifact.cjs');
+const SOURCE = '1bc34890cb8618b2fffd446a63924974e0fe15b5';
+const WORKFLOW = '3c44ab6412a8118b183273c402dd08136db05b28';
+const PAYLOAD = Buffer.from('OFFLINE_SYNTHETIC_METADATA_ZIP_BYTES');
+const DIGEST = crypto.createHash('sha256').update(PAYLOAD).digest('hex');
+const SELECTION = "const ARTIFACT = 12466091444, ZIP_SIZE = 8950, DIGEST = '5c3210a6b0af7bf9ea0cddb61fd1494714e8cfac0db8385960fb6390f92aa545';";
+const CONCLUSIONS = "const NATIVE_CONCLUSION = 'failure', BUILD_CONCLUSION = 'success', PROBES_CONCLUSION = 'failure';";
+
+function fixture(options = {}) {
+ const context = { repo: { owner: 'KeeperCommunity', repo: 'bitcoin-keeper' },
+ eventName: 'push', ref: 'refs/heads/codex/r5-current-android-artifact-byte-readout-20261022' };
+ const runData = { id: 39858617273, run_attempt: 1, repository: { id: 470904030 },
+ head_repository: { id: 470904030 }, head_sha: SOURCE, event: 'pull_request',
+ head_branch: 'codex/r5-ios-startup-diagnosis-20261022', path: '.github/workflows/keeper-native-diagnostic.yml',
+ status: 'completed', conclusion: 'failure', referenced_workflows: [{
+ path: `KeeperCommunity/bitcoin-keeper/.github/workflows/keeper-native-platform.yml@${WORKFLOW}`,
+ ref: 'refs/pull/7116/merge', sha: WORKFLOW }] };
+ const jobData = { id: 120125972406, run_id: 39858617273, run_attempt: 1, head_sha: SOURCE,
+ status: 'completed', conclusion: 'failure',
+ steps: [['Build development app', 'success'],
+ ['Run Android startup and native persistence probes', 'failure'],
+ ['Retain safe Phase A evidence', 'success']].map(([name, conclusion]) => ({ name, conclusion, status: 'completed' })) };
+ const artifact = { id: options.production ? 12466091444 : 991, name: `keeper-diagnostic-native-ANDROID-${SOURCE}-39858617273-1`,
+ expired: false, size_in_bytes: options.production ? 8950 : PAYLOAD.length,
+ digest: 'sha256:' + (options.production ? '5c3210a6b0af7bf9ea0cddb61fd1494714e8cfac0db8385960fb6390f92aa545' : DIGEST), workflow_run: {
+ id: 39858617273, head_sha: SOURCE, repository_id: 470904030, head_repository_id: 470904030 } };
+ const calls = [], events = [], output = [], actions = {};
+ for (const [name, data] of [['getWorkflowRun', runData], ['getJobForWorkflowRun', jobData], ['getArtifact', artifact]]) {
+ actions[name] = async args => { calls.push([name, args]); return { data }; };
+ }
+ actions.downloadArtifact = async args => { calls.push(['downloadArtifact', args]); return { data: options.payload ?? PAYLOAD }; };
+ const inputs = { github: { rest: { actions } }, context, core: {
+ info(value) { events.push('info'); if (options.info) throw new Error('PRIVATE_SENTINEL'); output.push(value); },
+ warning(value) { events.push('warning'); if (options.warning) throw new Error('PRIVATE_SENTINEL'); output.push(value); } } };
+ let text = fs.readFileSync(SCRIPT, 'utf8');
+ assert.ok(text.includes(SELECTION) && text.includes(CONCLUSIONS), 'Production selection must match the observed finite receipt');
+ if (!options.production) text = text.replace(SELECTION,
+ `const ARTIFACT = 991, ZIP_SIZE = ${PAYLOAD.length}, DIGEST = '${DIGEST}';`);
+ if (options.sourceChange) text = options.sourceChange(text);
+ const api = { module: { exports: {} }, Buffer, process: { env: { RUNNER_TEMP: '/owned' } }, require(name) {
+ if (name === 'node:assert/strict') return { ...assert, deepEqual(actual, expected) {
+ assert.deepEqual(JSON.parse(JSON.stringify(actual)), JSON.parse(JSON.stringify(expected)));
+ } };
+ if (name === 'node:crypto') return crypto;
+ if (name === 'node:path') return path;
+ if (name === 'node:fs') return {
+ realpathSync: value => value,
+ openSync(filename, flags, mode) { assert.equal(filename, '/owned/r5-current-android-fixed.zip'); assert.equal(flags, 'wx'); assert.equal(mode, 0o600); events.push('open'); return 42; },
+ writeFileSync(fd, bytes) { assert.equal(fd, 42); assert.deepEqual(bytes, PAYLOAD); events.push('write'); if (options.write) throw new Error('PRIVATE_SENTINEL'); },
+ closeSync(fd) { assert.equal(fd, 42); events.push('close'); if (options.close) throw new Error('PRIVATE_SENTINEL'); },
+ unlinkSync(filename) { assert.equal(filename, '/owned/r5-current-android-fixed.zip'); events.push('unlink'); if (options.unlink) throw new Error('PRIVATE_SENTINEL'); },
+ };
+ if (name === 'node:child_process') return { execFileSync(command, args, settings) {
+ assert.equal(command, 'python3'); assert.deepEqual(Array.from(args), ['-B', '.github/scripts/read-current-android-artifact.py']);
+ assert.equal(settings.timeout, 30000); events.push('decoder');
+ if (options.decoder) throw new Error('PRIVATE_SENTINEL');
+ return options.wrongOutput ? 'PRIVATE_SENTINEL' :
+ `FIXED_ANDROID_ARTIFACT_ZIP_BASE64_BEGIN\n${PAYLOAD.toString('base64')}\nFIXED_ANDROID_ARTIFACT_ZIP_BASE64_END\n`;
+ } };
+ throw new Error('Unexpected synthetic import');
+ } };
+ vm.runInNewContext(text, api);
+ return { context, runData, jobData, artifact, calls, events, output, inputs,
+ invoke: () => api.module.exports.run(inputs) };
+}
+
+test('exact production receipt admits offline API facts but rejects wrong bytes before file/log output', async () => {
+ const f = fixture({ production: true, payload: Buffer.alloc(8950) });
+ await assert.rejects(f.invoke, /^Error: FIXED_NATIVE_ARTIFACT_READOUT_FAILED$/);
+ assert.deepEqual(f.calls.map(([name]) => name), ['getWorkflowRun', 'getJobForWorkflowRun', 'getArtifact', 'downloadArtifact']);
+ assert.equal(f.calls[2][1].artifact_id, 12466091444);
+ assert.equal(f.calls[3][1].artifact_id, 12466091444);
+ assert.deepEqual(f.events, []); assert.deepEqual(f.output, []);
+ const workflow = fs.readFileSync(path.join(__dirname, '../workflows/r5-current-android-artifact-readout.yml'), 'utf8');
+ assert.ok(workflow.includes("if: ${{ github.repository == 'KeeperCommunity/bitcoin-keeper' && github.event_name == 'push' && github.ref == 'refs/heads/codex/r5-current-android-artifact-byte-readout-20261022' }}"));
+});
+
+test('synthetic bound route reads only exact Android job/artifact and deletes before original-byte log', async () => {
+ const f = fixture(); await f.invoke();
+ assert.deepEqual(f.calls.map(([name]) => name), ['getWorkflowRun', 'getJobForWorkflowRun', 'getArtifact', 'downloadArtifact']);
+ assert.equal(f.calls[1][1].job_id, 120125972406);
+ assert.equal(f.calls[3][1].artifact_id, 991);
+ assert.ok(f.events.indexOf('close') < f.events.indexOf('unlink'));
+ assert.ok(f.events.indexOf('unlink') < f.events.indexOf('info'));
+ const lines = f.output[0].split('\n');
+ assert.deepEqual(Buffer.from(lines[1], 'base64'), PAYLOAD);
+ assert.equal(lines[0], 'FIXED_ANDROID_ARTIFACT_ZIP_BASE64_BEGIN');
+ assert.equal(lines[2], 'FIXED_ANDROID_ARTIFACT_ZIP_BASE64_END');
+});
+
+test('partial or wrong finite selection fails before any API/filesystem operation', async () => {
+ for (const [before, after] of [["const ARTIFACT = 991", "const ARTIFACT = null"],
+ [`ZIP_SIZE = ${PAYLOAD.length}`, 'ZIP_SIZE = null'], [`DIGEST = '${DIGEST}'`, 'DIGEST = null'],
+ ["NATIVE_CONCLUSION = 'failure'", "NATIVE_CONCLUSION = 'success'"],
+ ["BUILD_CONCLUSION = 'success'", "BUILD_CONCLUSION = 'failure'"],
+ ["PROBES_CONCLUSION = 'failure'", "PROBES_CONCLUSION = 'success'"]]) {
+ const f = fixture({ sourceChange: text => { assert.ok(text.includes(before)); return text.replace(before, after); } });
+ await assert.rejects(f.invoke, /^Error: FIXED_NATIVE_ARTIFACT_READOUT_FAILED$/);
+ assert.deepEqual(f.calls, []); assert.deepEqual(f.events, []); assert.deepEqual(f.output, []);
+ }
+});
+
+test('foreign, stale, unknown or incomplete provenance never downloads bytes', async () => {
+ for (const change of [f => f.context.repo.owner = 'foreign', f => f.context.eventName = 'workflow_dispatch',
+ f => f.context.ref = 'refs/heads/sprint', f => f.runData.run_attempt++, f => f.runData.head_sha = '0'.repeat(40),
+ f => f.runData.repository.id++, f => f.runData.head_repository.id++, f => f.runData.status = 'queued',
+ f => { f.runData.status = 'in_progress'; f.runData.conclusion = null; },
+ f => f.runData.conclusion = 'success', f => f.runData.referenced_workflows = [],
+ f => f.runData.referenced_workflows[0].sha = SOURCE, f => f.jobData.id++, f => f.jobData.run_id++,
+ f => f.jobData.run_attempt++, f => f.jobData.status = 'in_progress', f => f.jobData.conclusion = 'success',
+ f => f.jobData.steps[0].conclusion = 'failure', f => f.jobData.steps[1].conclusion = 'success',
+ f => f.jobData.steps[2].conclusion = 'failure', f => f.jobData.steps.push(f.jobData.steps[2]),
+ f => f.artifact.id++, f => f.artifact.name += '-foreign', f => f.artifact.expired = true,
+ f => f.artifact.size_in_bytes++, f => f.artifact.digest = 'sha256:' + '0'.repeat(64),
+ f => f.artifact.workflow_run.id++, f => f.artifact.workflow_run.head_repository_id++]) {
+ const f = fixture({ production: true, payload: Buffer.alloc(8950) }); change(f);
+ await assert.rejects(f.invoke, /^Error: FIXED_NATIVE_ARTIFACT_READOUT_FAILED$/);
+ assert.equal(f.calls.some(([name]) => name === 'downloadArtifact'), false);
+ assert.deepEqual(f.events, []); assert.deepEqual(f.output, []);
+ }
+});
+
+test('wrong size or digest bytes fail before owned-file creation or logging', async () => {
+ for (const payload of [Buffer.from('PRIVATE_SENTINEL'), Buffer.alloc(PAYLOAD.length)]) {
+ const f = fixture({ payload });
+ await assert.rejects(f.invoke, /^Error: FIXED_NATIVE_ARTIFACT_READOUT_FAILED$/);
+ assert.deepEqual(f.events, []); assert.deepEqual(f.output, []);
+ }
+});
+
+test('write, close, decoder, cleanup and logger failures retain fixed errors and purge ordering', async () => {
+ for (const options of [{ write: true, unlink: true, warning: true }, { close: true },
+ { decoder: true, unlink: true, warning: true }, { wrongOutput: true },
+ { unlink: true, warning: true }, { info: true }]) {
+ const f = fixture(options);
+ await assert.rejects(f.invoke, options.unlink && !options.write && !options.decoder ?
+ /^Error: FIXED_NATIVE_ARTIFACT_PRIVATE_CLEANUP_FAILED$/ : /^Error: FIXED_NATIVE_ARTIFACT_READOUT_FAILED$/);
+ assert.equal(f.events.filter(value => value === 'unlink').length, 1);
+ if (options.info) assert.ok(f.events.indexOf('unlink') < f.events.indexOf('info'));
+ else assert.equal(f.events.includes('info'), false);
+ assert.equal(JSON.stringify(f.output).includes('PRIVATE_SENTINEL'), false);
+ }
+});
diff --git a/.github/tests/current-ios-artifact-readout.test.cjs b/.github/tests/current-ios-artifact-readout.test.cjs
new file mode 100644
index 0000000000..4c94a08b6e
--- /dev/null
+++ b/.github/tests/current-ios-artifact-readout.test.cjs
@@ -0,0 +1,127 @@
+'use strict';
+const assert = require('node:assert/strict');
+const test = require('node:test');
+const fs = require('node:fs');
+const path = require('node:path');
+const vm = require('node:vm');
+const { run } = require('../scripts/read-current-ios-artifact.cjs');
+const SOURCE = '1bc34890cb8618b2fffd446a63924974e0fe15b5';
+const WORKFLOW = '3c44ab6412a8118b183273c402dd08136db05b28';
+const DIGEST = '550142809a0faf812741a586630b17d6f458b2b6c935b5bab4b00f84da67c84f';
+
+function fixture() {
+ const context = { repo: { owner: 'KeeperCommunity', repo: 'bitcoin-keeper' },
+ eventName: 'push', ref: 'refs/heads/codex/r5-current-ios-artifact-byte-readout-20261022' };
+ const runData = { id: 39858617273, run_attempt: 1, repository: { id: 470904030 },
+ head_repository: { id: 470904030 }, head_sha: SOURCE, event: 'pull_request',
+ head_branch: 'codex/r5-ios-startup-diagnosis-20261022', path: '.github/workflows/keeper-native-diagnostic.yml',
+ status: 'completed', conclusion: 'failure', referenced_workflows: [{
+ path: `KeeperCommunity/bitcoin-keeper/.github/workflows/keeper-native-platform.yml@${WORKFLOW}`,
+ ref: 'refs/pull/7116/merge', sha: WORKFLOW }] };
+ const jobData = { id: 120103187854, run_id: 39858617273, head_sha: SOURCE, run_attempt: 1, status: 'completed', conclusion: 'failure',
+ steps: [['Build development app', 'success'], ['Run disposable startup smoke', 'failure'],
+ ['Retain safe Phase A evidence', 'success']].map(([name, conclusion]) => ({ name, conclusion, status: 'completed' })) };
+ const artifact = { id: 12462694619, name: `keeper-diagnostic-native-IOS-${SOURCE}-39858617273-1`,
+ expired: false, size_in_bytes: 6884, digest: `sha256:${DIGEST}`, workflow_run: {
+ id: 39858617273, head_sha: SOURCE, repository_id: 470904030, head_repository_id: 470904030 } };
+ const calls = [], output = [];
+ const actions = {};
+ for (const [name, data] of [['getWorkflowRun', runData], ['getJobForWorkflowRun', jobData], ['getArtifact', artifact]]) {
+ actions[name] = async args => { calls.push([name, args]); return { data }; };
+ }
+ actions.downloadArtifact = async args => { calls.push(['downloadArtifact', args]); return { data: Buffer.from('PRIVATE_SENTINEL') }; };
+ const inputs = { github: { rest: { actions } }, context,
+ core: { info: value => output.push(value), warning: value => output.push(value) } };
+ return { context, runData, jobData, artifact, calls, output, inputs, invoke: () => run(inputs) };
+}
+
+test('valid API provenance reaches only the fixed archive; unverified bytes emit no receipt', async () => {
+ const f = fixture();
+ await assert.rejects(f.invoke, /^Error: FIXED_NATIVE_ARTIFACT_READOUT_FAILED$/);
+ assert.deepEqual(f.calls.at(-1), ['downloadArtifact', {
+ owner: 'KeeperCommunity', repo: 'bitcoin-keeper', request: { timeout: 30000 },
+ artifact_id: 12462694619, archive_format: 'zip' }]);
+ assert.deepEqual(f.output, []);
+});
+
+test('completed iOS job is readable while the current whole run and Android remain in progress', async () => {
+ const f = fixture();
+ f.runData.status = 'in_progress'; f.runData.conclusion = null;
+ await assert.rejects(f.invoke, /^Error: FIXED_NATIVE_ARTIFACT_READOUT_FAILED$/); // Deliberately wrong ZIP.
+ assert.equal(f.calls.filter(([name]) => name === 'downloadArtifact').length, 1);
+ assert.equal(f.calls.filter(([name]) => name === 'getJobForWorkflowRun').length, 1);
+ assert.deepEqual(f.output, []);
+});
+
+test('correct-length wrong-digest bytes fail before creating or logging any private file', async () => {
+ const f = fixture();
+ f.inputs.github.rest.actions.downloadArtifact = async () => ({ data: Buffer.alloc(6884) });
+ await assert.rejects(f.invoke, /^Error: FIXED_NATIVE_ARTIFACT_READOUT_FAILED$/);
+ assert.deepEqual(f.output, []);
+});
+
+test('actual private-file finally retains primary even when decoder, unlink and logger all fail', async () => {
+ for (const options of [{}, { decoder: true, unlink: true, warning: true },
+ { unlink: true, warning: true }, { write: true, unlink: true, warning: true }, { info: true }]) {
+ const f = fixture(), events = [];
+ f.inputs.github.rest.actions.downloadArtifact = async () => ({ data: Buffer.alloc(6884) });
+ const api = { module: { exports: {} }, Buffer, process: { env: { RUNNER_TEMP: '/owned' } }, require(name) {
+ if (name === 'node:assert/strict') return { ...assert, deepEqual(actual, expected, message) {
+ // The source runs in a separate VM realm; compare its API JSON by value.
+ assert.deepEqual(JSON.parse(JSON.stringify(actual)), JSON.parse(JSON.stringify(expected)), message);
+ } };
+ if (name === 'node:path') return path;
+ if (name === 'node:crypto') return { createHash: () => ({ update() { return this; }, digest: () => DIGEST }) };
+ if (name === 'node:fs') return { realpathSync: x => x,
+ openSync(filename, flags, mode) { assert.equal(filename, '/owned/r5-current-ios-fixed.zip'); assert.equal(flags, 'wx'); assert.equal(mode, 0o600); events.push('open'); return 42; },
+ writeFileSync(fd) { assert.equal(fd, 42); events.push('write'); if (options.write) throw new Error('PRIVATE_SENTINEL'); },
+ closeSync(fd) { assert.equal(fd, 42); events.push('close'); },
+ unlinkSync() { events.push('unlink'); if (options.unlink) throw new Error('PRIVATE_SENTINEL'); } };
+ if (name === 'node:child_process') return { execFileSync(command, args, settings) {
+ assert.equal(command, 'python3'); assert.deepEqual(Array.from(args), ['-B', '.github/scripts/read-current-ios-artifact.py']);
+ assert.equal(settings.timeout, 30000); events.push('decoder');
+ if (options.decoder) throw new Error('PRIVATE_SENTINEL');
+ return 'FIXED_IOS_ARTIFACT_ZIP_BASE64_BEGIN\n' + Buffer.alloc(6884).toString('base64') + '\nFIXED_IOS_ARTIFACT_ZIP_BASE64_END\n'; } };
+ throw new Error('Unexpected synthetic import');
+ } };
+ vm.runInNewContext(fs.readFileSync(path.join(__dirname, '../scripts/read-current-ios-artifact.cjs'), 'utf8'), api);
+ f.inputs.core = { info() { events.push('info'); if (options.info) throw new Error('PRIVATE_SENTINEL'); }, warning() { events.push('warning'); if (options.warning) throw new Error('PRIVATE_SENTINEL'); } };
+ const action = () => api.module.exports.run(f.inputs);
+ if (options.decoder || options.write || options.info) await assert.rejects(action, /^Error: FIXED_NATIVE_ARTIFACT_READOUT_FAILED$/);
+ else if (options.unlink) await assert.rejects(action, /^Error: FIXED_NATIVE_ARTIFACT_PRIVATE_CLEANUP_FAILED$/);
+ else await action();
+ assert.equal(events.filter(x => x === 'unlink').length, 1);
+ assert.ok(events.indexOf('close') < events.indexOf('unlink'));
+ if (!options.decoder && !options.write && !options.unlink) assert.ok(events.indexOf('unlink') < events.indexOf('info'));
+ else assert.equal(events.includes('info'), false);
+ }
+});
+
+test('foreign context cannot make any API request', async () => {
+ for (const change of [f => f.context.repo.owner = 'foreign', f => f.context.repo.repo = 'foreign',
+ f => f.context.eventName = 'workflow_dispatch', f => f.context.ref = 'refs/heads/sprint']) {
+ const f = fixture(); change(f);
+ await assert.rejects(f.invoke, /FIXED_NATIVE_ARTIFACT_READOUT_FAILED/);
+ assert.deepEqual(f.calls, []); assert.deepEqual(f.output, []);
+ }
+});
+
+test('stale, cross-source, foreign, missing and failed-upload metadata reject before archive download', async () => {
+ for (const change of [
+ f => f.runData.id++, f => f.runData.run_attempt++, f => f.runData.head_sha = '0'.repeat(40),
+ f => f.runData.head_repository.id++, f => f.runData.event = 'push',
+ f => f.runData.path = '.github/workflows/other.yml', f => f.runData.status = 'queued', f => f.runData.conclusion = 'success',
+ f => f.jobData.run_attempt++, f => f.jobData.status = 'in_progress',
+ f => f.runData.referenced_workflows[0].sha = SOURCE, f => f.runData.referenced_workflows = [],
+ f => f.jobData.run_id++, f => f.jobData.head_sha = WORKFLOW,
+ f => f.jobData.steps[2].conclusion = 'failure', f => f.jobData.steps.push(f.jobData.steps[2]),
+ f => f.artifact.id++, f => f.artifact.name += '-foreign', f => f.artifact.expired = true,
+ f => f.artifact.size_in_bytes++, f => f.artifact.digest = 'sha256:' + '0'.repeat(64),
+ f => f.artifact.workflow_run.id++, f => f.artifact.workflow_run.head_sha = WORKFLOW,
+ ]) {
+ const f = fixture(); change(f);
+ await assert.rejects(f.invoke, /FIXED_NATIVE_ARTIFACT_READOUT_FAILED/);
+ assert.equal(f.calls.some(([name]) => name === 'downloadArtifact'), false);
+ assert.deepEqual(f.output, []);
+ }
+});
diff --git a/.github/tests/d270-android-artifact-readout.test.cjs b/.github/tests/d270-android-artifact-readout.test.cjs
new file mode 100644
index 0000000000..5f892bd4da
--- /dev/null
+++ b/.github/tests/d270-android-artifact-readout.test.cjs
@@ -0,0 +1,152 @@
+'use strict';
+// Fabricated API and byte transport only; no current artifact/native operation.
+const assert = require('node:assert/strict');
+const crypto = require('node:crypto');
+const fs = require('node:fs');
+const path = require('node:path');
+const test = require('node:test');
+const vm = require('node:vm');
+const SCRIPT = path.join(__dirname, '../scripts/read-d270-android-artifact.cjs');
+const SOURCE = 'd27007078808617a97ee460b592eefb44e7e5325';
+const WORKFLOW = 'f5f20e6d959109cdc2e0096099992d72307255bf';
+const PAYLOAD = Buffer.from('OFFLINE_SYNTHETIC_METADATA_ZIP_BYTES');
+const DIGEST = crypto.createHash('sha256').update(PAYLOAD).digest('hex');
+const SELECTION = "const ARTIFACT = 12551461839, ZIP_SIZE = 9596, DIGEST = 'b9182e02a33b7e0568d73654b42d61f66bce8e425d65a6960aa0f4f2194ee13a';";
+const OUTCOME = "const NATIVE_CONCLUSION = 'failure', STEP_CONCLUSIONS = ['success', 'failure'];";
+
+function fixture(options = {}) {
+ const context = { repo: { owner: 'KeeperCommunity', repo: 'bitcoin-keeper' },
+ eventName: 'push', ref: 'refs/heads/codex/r5-d270-android-artifact-readout-20261024' };
+ const runData = { id: 40065599904, run_attempt: 1, repository: { id: 470904030 },
+ head_repository: { id: 470904030 }, head_sha: SOURCE, event: 'pull_request',
+ head_branch: 'codex/r5-native-acceptance-20261024',
+ path: '.github/workflows/keeper-native-diagnostic.yml', status: 'completed', conclusion: 'failure',
+ referenced_workflows: [{path: `KeeperCommunity/bitcoin-keeper/.github/workflows/keeper-native-platform.yml@${WORKFLOW}`,
+ ref: 'refs/pull/7149/merge', sha: WORKFLOW}] };
+ const jobData = { id: 120796675691, run_id: 40065599904, run_attempt: 1, head_sha: SOURCE,
+ status: 'completed', conclusion: 'failure', steps: [
+ ['Build development app', 'success'], ['Run Android startup and native persistence probes', 'failure'], ['Retain safe Phase A evidence', 'success']
+ ].map(([name, conclusion]) => ({name, conclusion, status: 'completed'})) };
+ const artifact = {id: options.production ? 12551461839 : 991,
+ name: `keeper-diagnostic-native-ANDROID-${SOURCE}-40065599904-1`, expired: false,
+ size_in_bytes: options.production ? 9596 : PAYLOAD.length,
+ digest: 'sha256:' + (options.production ? 'b9182e02a33b7e0568d73654b42d61f66bce8e425d65a6960aa0f4f2194ee13a' : DIGEST), workflow_run: {
+ id: 40065599904, head_sha: SOURCE, repository_id: 470904030, head_repository_id: 470904030}};
+ const calls = [], events = [], output = [], actions = {};
+ for (const [name, data] of [['getWorkflowRun', runData], ['getJobForWorkflowRun', jobData], ['getArtifact', artifact]]) {
+ actions[name] = async args => { calls.push([name, args]); return {data}; };
+ }
+ actions.downloadArtifact = async args => {calls.push(['downloadArtifact', args]); if(options.after) options.after({runData,jobData,artifact}); return {data: options.payload ?? PAYLOAD};};
+ const inputs = {github: {rest: {actions}}, context, core: {
+ info(value) {events.push('info'); if (options.info) throw Error('PRIVATE_SENTINEL'); output.push(value);},
+ warning(value) {events.push('warning'); if (options.warning) throw Error('PRIVATE_SENTINEL'); output.push(value);}}};
+ let source = fs.readFileSync(SCRIPT, 'utf8');
+ assert.ok(source.includes(SELECTION) && source.includes(OUTCOME));
+ if (!options.production) source = source.replace(SELECTION,
+ `const ARTIFACT = 991, ZIP_SIZE = ${PAYLOAD.length}, DIGEST = '${DIGEST}';`);
+ if (options.edit) source = options.edit(source);
+ const api = {module: {exports: {}}, Buffer, process: {env: {RUNNER_TEMP: '/owned'}}, require(name) {
+ if (name === 'node:assert/strict') return {...assert, deepEqual(a,b) {assert.deepEqual(JSON.parse(JSON.stringify(a)), JSON.parse(JSON.stringify(b)));}};
+ if (name === 'node:crypto') return crypto;
+ if (name === 'node:path') return path;
+ if (name === 'node:fs') return {realpathSync: x => x,
+ openSync(file, flags, mode) {assert.equal(file, '/owned/r5-d270-android-fixed.zip'); assert.equal(flags, 'wx'); assert.equal(mode, 0o600); events.push('open'); return 42;},
+ writeFileSync(fd, bytes) {assert.equal(fd,42); assert.deepEqual(bytes,PAYLOAD); events.push('write'); if(options.write) throw Error('PRIVATE_SENTINEL');},
+ closeSync(fd) {assert.equal(fd,42); events.push('close'); if(options.close) throw Error('PRIVATE_SENTINEL');},
+ unlinkSync() {events.push('unlink'); if(options.unlink) throw Error('PRIVATE_SENTINEL');}};
+ if (name === 'node:child_process') return {execFileSync(command,args,settings) {
+ assert.equal(command,'python3'); assert.deepEqual(Array.from(args),['-B','.github/scripts/read-d270-android-artifact.py']);
+ assert.equal(settings.timeout,30000); events.push('decoder'); if(options.decoder) {
+ const error = Error('PRIVATE_SENTINEL'); error.stdout = options.decoderOutput; throw error;
+ }
+ return options.wrongOutput ? 'PRIVATE_SENTINEL' : 'D270_ANDROID_OBSERVATIONS_BEGIN\n' + JSON.stringify({schema:1,scope:'OBSERVATIONS_ONLY_NOT_NATIVE_ACCEPTANCE_OR_CAUSE',original_zip_sha256:DIGEST,metadata_sha256:'a'.repeat(64),observations:{source_sha:SOURCE,run_id:'40065599904',run_attempt:'1'}}) + '\nD270_ANDROID_OBSERVATIONS_END\n';}};
+ throw Error('Unexpected test import');
+ }};
+ vm.runInNewContext(source,api);
+ return {context,runData,jobData,artifact,calls,events,output,inputs,invoke:()=>api.module.exports.run(inputs)};
+}
+
+test('exact observed production selection reaches only its archive and rejects wrong digest before file/log', async()=>{
+ const f=fixture({production:true,payload:Buffer.alloc(9596)});
+ await assert.rejects(f.invoke,/FIXED_NATIVE_ARTIFACT_READOUT_FAILED/);
+ assert.deepEqual(f.calls.map(([name])=>name),['getWorkflowRun','getJobForWorkflowRun','getArtifact','downloadArtifact']);
+ assert.equal(f.calls[2][1].artifact_id,12551461839); assert.equal(f.calls[3][1].artifact_id,12551461839);
+ assert.deepEqual(f.events,[]); assert.deepEqual(f.output,[]);
+});
+
+test('every incomplete observed binding fails before API/filesystem', async()=>{
+ for(const [before,after] of [["ARTIFACT = 12551461839","ARTIFACT = null"], ['ZIP_SIZE = 9596','ZIP_SIZE = null'],
+ ["DIGEST = 'b9182e02a33b7e0568d73654b42d61f66bce8e425d65a6960aa0f4f2194ee13a'",'DIGEST = null'], ["NATIVE_CONCLUSION = 'failure'",'NATIVE_CONCLUSION = null'],
+ ["STEP_CONCLUSIONS = ['success', 'failure']",'STEP_CONCLUSIONS = null'],
+ ["STEP_CONCLUSIONS = ['success', 'failure']", "STEP_CONCLUSIONS = ['success', ,]"],
+ ["STEP_CONCLUSIONS = ['success', 'failure']", "STEP_CONCLUSIONS = ['success', undefined]"],
+ ["STEP_CONCLUSIONS = ['success', 'failure']", "STEP_CONCLUSIONS = ['success', null]"]]) {
+ const f=fixture({production:true,edit:s=>{assert.ok(s.includes(before)); return s.replace(before,after);}});
+ await assert.rejects(f.invoke,/FIXED_NATIVE_ARTIFACT_READOUT_FAILED/);
+ assert.deepEqual(f.calls,[]); assert.deepEqual(f.events,[]); assert.deepEqual(f.output,[]);
+ }
+});
+
+test('synthetic terminal job binds exact outcomes and purge precedes projection output',async()=>{
+ for(const completed of [false,true]) {
+ const f=fixture(); if(completed) Object.assign(f.runData,{status:'completed',conclusion:'failure'});
+ await f.invoke(); assert.equal(f.calls.filter(([name])=>name==='getJobForWorkflowRun').length,2);
+ assert.equal(f.calls[1][1].job_id,120796675691);
+ assert.ok(f.events.indexOf('close'){
+ for(const change of [f=>f.context.eventName='workflow_dispatch',f=>f.context.repo.owner='foreign',f=>f.context.ref='refs/heads/sprint',
+ f=>f.runData.id++,f=>f.runData.run_attempt++,f=>f.runData.head_sha=WORKFLOW,f=>f.runData.repository.id++,
+ f=>f.runData.head_repository.id++,f=>f.runData.status='queued',f=>f.runData.referenced_workflows=[],
+ f=>f.runData.referenced_workflows[0].sha=SOURCE,f=>f.jobData.id++,f=>f.jobData.run_attempt++,f=>f.jobData.run_id++,
+ f=>f.jobData.status='in_progress',f=>f.jobData.conclusion='success',f=>f.jobData.steps[0].conclusion='failure',
+ f=>f.jobData.steps[2].conclusion='failure',f=>f.jobData.steps.push(f.jobData.steps[2]),f=>f.artifact.id++,
+ f=>f.artifact.name+='foreign',f=>f.artifact.size_in_bytes++,f=>f.artifact.expired=true,
+ f=>f.artifact.digest='sha256:'+'0'.repeat(64),f=>f.artifact.workflow_run.id++,f=>f.artifact.workflow_run.head_sha=WORKFLOW]) {
+ const f=fixture({production:true}); change(f); await assert.rejects(f.invoke,/FIXED_NATIVE_ARTIFACT_READOUT_FAILED/);
+ assert.equal(f.calls.some(([name])=>name==='downloadArtifact'),false); assert.deepEqual(f.events,[]); assert.deepEqual(f.output,[]);
+ }
+});
+
+test('wrong ZIP size or digest fails before any filesystem or log operation',async()=>{
+ for(const payload of [Buffer.from('PRIVATE_SENTINEL'),Buffer.alloc(PAYLOAD.length)]) {
+ const f=fixture({payload}); await assert.rejects(f.invoke,/FIXED_NATIVE_ARTIFACT_READOUT_FAILED/);
+ assert.deepEqual(f.events,[]); assert.deepEqual(f.output,[]);
+ }
+});
+
+test('decoder write close cleanup and logging errors stay fixed and preserve purge ordering',async()=>{
+ for(const options of [{write:true,unlink:true,warning:true},{close:true},{decoder:true,unlink:true,warning:true},
+ {wrongOutput:true},{unlink:true,warning:true},{info:true}]) {
+ const f=fixture(options); await assert.rejects(f.invoke,options.unlink&&!options.write&&!options.decoder ?
+ /FIXED_NATIVE_ARTIFACT_PRIVATE_CLEANUP_FAILED/:/FIXED_NATIVE_ARTIFACT_READOUT_FAILED/);
+ assert.equal(f.events.filter(x=>x==='unlink').length,1);
+ if(options.info) assert.ok(f.events.indexOf('unlink'){
+ for(const after of [v=>v.runData.run_attempt++,v=>v.jobData.head_sha='0'.repeat(40),v=>v.artifact.expired=true]) {
+ const f=fixture({after});
+ await assert.rejects(f.invoke,/FIXED_NATIVE_ARTIFACT_READOUT_FAILED/);
+ assert.equal(f.events.includes('info'),false);
+ assert.equal(f.events.filter(x=>x==='unlink').length,1);
+ }
+});
+
+test('decoder diagnostics admit only fixed stage labels without private output',async()=>{
+ for(const [decoderOutput,stage] of [
+ ['D270_ANDROID_OBSERVATION_READOUT_FAILED:PRODUCT\n','DECODE_PRODUCT'],
+ ['D270_ANDROID_OBSERVATION_READOUT_FAILED:PRIVATE_SENTINEL\n','DECODE'],
+ ['PRIVATE_SENTINEL','DECODE']]) {
+ const f=fixture({decoder:true,decoderOutput});
+ await assert.rejects(f.invoke,error=>error.message==='FIXED_NATIVE_ARTIFACT_READOUT_FAILED_'+stage);
+ assert.deepEqual(f.output,[]);
+ assert.equal(f.events.filter(x=>x==='unlink').length,1);
+ }
+});
diff --git a/.github/tests/d270-ios-artifact-readout.test.cjs b/.github/tests/d270-ios-artifact-readout.test.cjs
new file mode 100644
index 0000000000..b15776b272
--- /dev/null
+++ b/.github/tests/d270-ios-artifact-readout.test.cjs
@@ -0,0 +1,154 @@
+'use strict';
+// Fabricated API and byte transport only; no current artifact/native operation.
+const assert = require('node:assert/strict');
+const crypto = require('node:crypto');
+const fs = require('node:fs');
+const path = require('node:path');
+const test = require('node:test');
+const vm = require('node:vm');
+const SCRIPT = path.join(__dirname, '../scripts/read-d270-ios-artifact.cjs');
+const SOURCE = 'd27007078808617a97ee460b592eefb44e7e5325';
+const WORKFLOW = 'f5f20e6d959109cdc2e0096099992d72307255bf';
+const PAYLOAD = Buffer.from('OFFLINE_SYNTHETIC_METADATA_ZIP_BYTES');
+const DIGEST = crypto.createHash('sha256').update(PAYLOAD).digest('hex');
+const SELECTION = "const ARTIFACT = 12550480968, ZIP_SIZE = 7339, DIGEST = '5891036cd8225b97c7edaff9bc057e2c70a8f8720e8f9def3ef0369de043d032';";
+const OUTCOME = "const NATIVE_CONCLUSION = 'failure', STEP_CONCLUSIONS = ['success', 'failure', 'skipped', 'skipped', 'skipped'];";
+
+function fixture(options = {}) {
+ const context = { repo: { owner: 'KeeperCommunity', repo: 'bitcoin-keeper' },
+ eventName: 'push', ref: 'refs/heads/codex/r5-d270-ios-artifact-readout-20261024' };
+ const runData = { id: 40065599904, run_attempt: 1, repository: { id: 470904030 },
+ head_repository: { id: 470904030 }, head_sha: SOURCE, event: 'pull_request',
+ head_branch: 'codex/r5-native-acceptance-20261024',
+ path: '.github/workflows/keeper-native-diagnostic.yml', status: 'in_progress', conclusion: null,
+ referenced_workflows: [{path: `KeeperCommunity/bitcoin-keeper/.github/workflows/keeper-native-platform.yml@${WORKFLOW}`,
+ ref: 'refs/pull/7149/merge', sha: WORKFLOW}] };
+ const jobData = { id: 120788067210, run_id: 40065599904, run_attempt: 1, head_sha: SOURCE,
+ status: 'completed', conclusion: 'failure', steps: [
+ ['Build development app', 'success'], ['Run disposable startup smoke', 'failure'],
+ ['Run disposable native persistence probe', 'skipped'], ['Run R5 production worker native scenarios', 'skipped'],
+ ['Measure five full-product startup and first-wallet runs', 'skipped'], ['Retain safe Phase A evidence', 'success']
+ ].map(([name, conclusion]) => ({name, conclusion, status: 'completed'})) };
+ const artifact = {id: options.production ? 12550480968 : 991,
+ name: `keeper-diagnostic-native-IOS-${SOURCE}-40065599904-1`, expired: false,
+ size_in_bytes: options.production ? 7339 : PAYLOAD.length,
+ digest: 'sha256:' + (options.production ? '5891036cd8225b97c7edaff9bc057e2c70a8f8720e8f9def3ef0369de043d032' : DIGEST), workflow_run: {
+ id: 40065599904, head_sha: SOURCE, repository_id: 470904030, head_repository_id: 470904030}};
+ const calls = [], events = [], output = [], actions = {};
+ for (const [name, data] of [['getWorkflowRun', runData], ['getJobForWorkflowRun', jobData], ['getArtifact', artifact]]) {
+ actions[name] = async args => { calls.push([name, args]); return {data}; };
+ }
+ actions.downloadArtifact = async args => {calls.push(['downloadArtifact', args]); if(options.after) options.after({runData,jobData,artifact}); return {data: options.payload ?? PAYLOAD};};
+ const inputs = {github: {rest: {actions}}, context, core: {
+ info(value) {events.push('info'); if (options.info) throw Error('PRIVATE_SENTINEL'); output.push(value);},
+ warning(value) {events.push('warning'); if (options.warning) throw Error('PRIVATE_SENTINEL'); output.push(value);}}};
+ let source = fs.readFileSync(SCRIPT, 'utf8');
+ assert.ok(source.includes(SELECTION) && source.includes(OUTCOME));
+ if (!options.production) source = source.replace(SELECTION,
+ `const ARTIFACT = 991, ZIP_SIZE = ${PAYLOAD.length}, DIGEST = '${DIGEST}';`);
+ if (options.edit) source = options.edit(source);
+ const api = {module: {exports: {}}, Buffer, process: {env: {RUNNER_TEMP: '/owned'}}, require(name) {
+ if (name === 'node:assert/strict') return {...assert, deepEqual(a,b) {assert.deepEqual(JSON.parse(JSON.stringify(a)), JSON.parse(JSON.stringify(b)));}};
+ if (name === 'node:crypto') return crypto;
+ if (name === 'node:path') return path;
+ if (name === 'node:fs') return {realpathSync: x => x,
+ openSync(file, flags, mode) {assert.equal(file, '/owned/r5-d270-ios-fixed.zip'); assert.equal(flags, 'wx'); assert.equal(mode, 0o600); events.push('open'); return 42;},
+ writeFileSync(fd, bytes) {assert.equal(fd,42); assert.deepEqual(bytes,PAYLOAD); events.push('write'); if(options.write) throw Error('PRIVATE_SENTINEL');},
+ closeSync(fd) {assert.equal(fd,42); events.push('close'); if(options.close) throw Error('PRIVATE_SENTINEL');},
+ unlinkSync() {events.push('unlink'); if(options.unlink) throw Error('PRIVATE_SENTINEL');}};
+ if (name === 'node:child_process') return {execFileSync(command,args,settings) {
+ assert.equal(command,'python3'); assert.deepEqual(Array.from(args),['-B','.github/scripts/read-d270-ios-artifact.py']);
+ assert.equal(settings.timeout,30000); events.push('decoder'); if(options.decoder) {
+ const error = Error('PRIVATE_SENTINEL'); error.stdout = options.decoderOutput; throw error;
+ }
+ return options.wrongOutput ? 'PRIVATE_SENTINEL' : 'D270_IOS_OBSERVATIONS_BEGIN\n' + JSON.stringify({schema:1,scope:'OBSERVATIONS_ONLY_NOT_NATIVE_ACCEPTANCE_OR_CAUSE',original_zip_sha256:DIGEST,metadata_sha256:'a'.repeat(64),observations:{source_sha:SOURCE,run_id:'40065599904',run_attempt:'1'}}) + '\nD270_IOS_OBSERVATIONS_END\n';}};
+ throw Error('Unexpected test import');
+ }};
+ vm.runInNewContext(source,api);
+ return {context,runData,jobData,artifact,calls,events,output,inputs,invoke:()=>api.module.exports.run(inputs)};
+}
+
+test('exact observed production selection reaches only its archive and rejects wrong digest before file/log', async()=>{
+ const f=fixture({production:true,payload:Buffer.alloc(7339)});
+ await assert.rejects(f.invoke,/FIXED_NATIVE_ARTIFACT_READOUT_FAILED/);
+ assert.deepEqual(f.calls.map(([name])=>name),['getWorkflowRun','getJobForWorkflowRun','getArtifact','downloadArtifact']);
+ assert.equal(f.calls[2][1].artifact_id,12550480968); assert.equal(f.calls[3][1].artifact_id,12550480968);
+ assert.deepEqual(f.events,[]); assert.deepEqual(f.output,[]);
+});
+
+test('every incomplete observed binding fails before API/filesystem', async()=>{
+ for(const [before,after] of [["ARTIFACT = 12550480968","ARTIFACT = null"], ['ZIP_SIZE = 7339','ZIP_SIZE = null'],
+ ["DIGEST = '5891036cd8225b97c7edaff9bc057e2c70a8f8720e8f9def3ef0369de043d032'",'DIGEST = null'], ["NATIVE_CONCLUSION = 'failure'",'NATIVE_CONCLUSION = null'],
+ ["STEP_CONCLUSIONS = ['success', 'failure', 'skipped', 'skipped', 'skipped']",'STEP_CONCLUSIONS = null'],
+ ["STEP_CONCLUSIONS = ['success', 'failure', 'skipped', 'skipped', 'skipped']", "STEP_CONCLUSIONS = ['success', , 'skipped', 'skipped', 'skipped']"],
+ ["STEP_CONCLUSIONS = ['success', 'failure', 'skipped', 'skipped', 'skipped']", "STEP_CONCLUSIONS = ['success', undefined, 'skipped', 'skipped', 'skipped']"],
+ ["STEP_CONCLUSIONS = ['success', 'failure', 'skipped', 'skipped', 'skipped']", "STEP_CONCLUSIONS = ['success', null, 'skipped', 'skipped', 'skipped']"]]) {
+ const f=fixture({production:true,edit:s=>{assert.ok(s.includes(before)); return s.replace(before,after);}});
+ await assert.rejects(f.invoke,/FIXED_NATIVE_ARTIFACT_READOUT_FAILED/);
+ assert.deepEqual(f.calls,[]); assert.deepEqual(f.events,[]); assert.deepEqual(f.output,[]);
+ }
+});
+
+test('synthetic completed iOS job can be read while Android continues and purge precedes exact-byte output',async()=>{
+ for(const completed of [false,true]) {
+ const f=fixture(); if(completed) Object.assign(f.runData,{status:'completed',conclusion:'failure'});
+ await f.invoke(); assert.equal(f.calls.filter(([name])=>name==='getJobForWorkflowRun').length,2);
+ assert.equal(f.calls[1][1].job_id,120788067210);
+ assert.ok(f.events.indexOf('close'){
+ for(const change of [f=>f.context.eventName='workflow_dispatch',f=>f.context.repo.owner='foreign',f=>f.context.ref='refs/heads/sprint',
+ f=>f.runData.id++,f=>f.runData.run_attempt++,f=>f.runData.head_sha=WORKFLOW,f=>f.runData.repository.id++,
+ f=>f.runData.head_repository.id++,f=>f.runData.status='queued',f=>f.runData.referenced_workflows=[],
+ f=>f.runData.referenced_workflows[0].sha=SOURCE,f=>f.jobData.id++,f=>f.jobData.run_attempt++,f=>f.jobData.run_id++,
+ f=>f.jobData.status='in_progress',f=>f.jobData.conclusion='success',f=>f.jobData.steps[0].conclusion='failure',
+ f=>f.jobData.steps[5].conclusion='failure',f=>f.jobData.steps.push(f.jobData.steps[5]),f=>f.artifact.id++,
+ f=>f.artifact.name+='foreign',f=>f.artifact.size_in_bytes++,f=>f.artifact.expired=true,
+ f=>f.artifact.digest='sha256:'+'0'.repeat(64),f=>f.artifact.workflow_run.id++,f=>f.artifact.workflow_run.head_sha=WORKFLOW]) {
+ const f=fixture({production:true}); change(f); await assert.rejects(f.invoke,/FIXED_NATIVE_ARTIFACT_READOUT_FAILED/);
+ assert.equal(f.calls.some(([name])=>name==='downloadArtifact'),false); assert.deepEqual(f.events,[]); assert.deepEqual(f.output,[]);
+ }
+});
+
+test('wrong ZIP size or digest fails before any filesystem or log operation',async()=>{
+ for(const payload of [Buffer.from('PRIVATE_SENTINEL'),Buffer.alloc(PAYLOAD.length)]) {
+ const f=fixture({payload}); await assert.rejects(f.invoke,/FIXED_NATIVE_ARTIFACT_READOUT_FAILED/);
+ assert.deepEqual(f.events,[]); assert.deepEqual(f.output,[]);
+ }
+});
+
+test('decoder write close cleanup and logging errors stay fixed and preserve purge ordering',async()=>{
+ for(const options of [{write:true,unlink:true,warning:true},{close:true},{decoder:true,unlink:true,warning:true},
+ {wrongOutput:true},{unlink:true,warning:true},{info:true}]) {
+ const f=fixture(options); await assert.rejects(f.invoke,options.unlink&&!options.write&&!options.decoder ?
+ /FIXED_NATIVE_ARTIFACT_PRIVATE_CLEANUP_FAILED/:/FIXED_NATIVE_ARTIFACT_READOUT_FAILED/);
+ assert.equal(f.events.filter(x=>x==='unlink').length,1);
+ if(options.info) assert.ok(f.events.indexOf('unlink'){
+ for(const after of [v=>v.runData.run_attempt++,v=>v.jobData.head_sha='0'.repeat(40),v=>v.artifact.expired=true]) {
+ const f=fixture({after});
+ await assert.rejects(f.invoke,/FIXED_NATIVE_ARTIFACT_READOUT_FAILED/);
+ assert.equal(f.events.includes('info'),false);
+ assert.equal(f.events.filter(x=>x==='unlink').length,1);
+ }
+});
+
+test('decoder diagnostics admit only fixed stage labels without private output',async()=>{
+ for(const [decoderOutput,stage] of [
+ ['D270_IOS_OBSERVATION_READOUT_FAILED:STARTUP_OBSERVATION\n','DECODE_STARTUP_OBSERVATION'],
+ ['D270_IOS_OBSERVATION_READOUT_FAILED:PRIVATE_SENTINEL\n','DECODE'],
+ ['PRIVATE_SENTINEL','DECODE']]) {
+ const f=fixture({decoder:true,decoderOutput});
+ await assert.rejects(f.invoke,error=>error.message==='FIXED_NATIVE_ARTIFACT_READOUT_FAILED_'+stage);
+ assert.deepEqual(f.output,[]);
+ assert.equal(f.events.filter(x=>x==='unlink').length,1);
+ }
+});
diff --git a/.github/tests/fixtures/public-companions.cjs b/.github/tests/fixtures/public-companions.cjs
new file mode 100644
index 0000000000..a8298ae5c5
--- /dev/null
+++ b/.github/tests/fixtures/public-companions.cjs
@@ -0,0 +1,34 @@
+'use strict';
+// Compatibility fixtures come from the actual Python producer runners with
+// their existing fake native/process boundaries, not validator constants.
+const { execFileSync } = require('node:child_process');
+const path = require('node:path');
+const original = JSON.parse(execFileSync('python3', ['-B', path.join(__dirname, 'public_companions.py')],
+ { encoding: 'utf8', maxBuffer: 65536 }));
+function attach(metadata, platform) {
+ // These predecessor phases are explicitly synthetic fixture inputs. Actual
+ // producer compatibility below exercises companions only, never native work.
+ for (const name of ['build', 'smoke', 'native_probe', 'r5_features'])
+ if (!Object.hasOwn(metadata, name)) metadata[name] = 'PASS';
+ const proof = metadata.installed_artifact || (platform === 'IOS' ?
+ { method: 'FULL_SIMULATOR_BUNDLE_TREE_AND_EXECUTABLE_SHA256', inventory_sha256: 'd'.repeat(64), executable_sha256: 'e'.repeat(64) } :
+ { method: 'SINGLE_INSTALLED_BASE_APK_SHA256', sha256: 'f'.repeat(64) });
+ metadata.installed_artifact_verified = true;
+ metadata.installed_artifact = structuredClone(proof);
+ metadata.built_artifact ||= platform === 'IOS' ? { executable_sha256: proof.executable_sha256 } : { sha256: proof.sha256 };
+ metadata.product_ui ||= { status: 'PASS' };
+ metadata.product_ui.companion_metro_switches = original.switches.map(phase => ({ phase, status: 'PASS', scope: 'BUNDLE_SETUP_ONLY' }));
+ for (const [name, root, nested] of [
+ ['credential', 'product_credential_ui', 'credential_errors_ui'],
+ ['history', 'product_version_history_ui', 'version_history_ui'],
+ ['vault', 'product_vault_ui', 'vault_references_ui'],
+ ]) {
+ const row = structuredClone(original.receipts[name]);
+ row.installed_artifact = structuredClone(proof);
+ for (const stage of row.stage_evidence || []) stage.installed_artifact = structuredClone(proof);
+ metadata[root] = row;
+ metadata.product_ui[nested] = structuredClone(row);
+ }
+ return metadata;
+}
+module.exports = { attach };
diff --git a/.github/tests/fixtures/public_companions.py b/.github/tests/fixtures/public_companions.py
new file mode 100644
index 0000000000..92cb454bbd
--- /dev/null
+++ b/.github/tests/fixtures/public_companions.py
@@ -0,0 +1,25 @@
+"""Real producer output at fake host boundaries; never native acceptance."""
+import importlib.util
+import json
+from pathlib import Path
+
+directory = Path(__file__).resolve().parents[1]
+receipts, switches = {}, ['product']
+for name in ['credential', 'history', 'vault']:
+ path = directory / ('test_product_' + name + '_acceptance.py')
+ spec = importlib.util.spec_from_file_location('public_fixture_' + name, path)
+ module = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(module)
+ case = module.RunnerTests()
+ try:
+ output = case.exercise()
+ value = output[0]
+ assert isinstance(value, dict) and value['status'] == 'PASS'
+ receipts[name] = value
+ if name == 'credential':
+ switches.extend(output[2]['switches'])
+ if name == 'history':
+ switches.extend(output[3])
+ finally:
+ case.doCleanups()
+print(json.dumps({'receipts': receipts, 'switches': switches}))
diff --git a/.github/tests/keeper-local-validation.test.cjs b/.github/tests/keeper-local-validation.test.cjs
index 3de7d79945..36d0c74595 100644
--- a/.github/tests/keeper-local-validation.test.cjs
+++ b/.github/tests/keeper-local-validation.test.cjs
@@ -15,6 +15,12 @@ const runWorkflow = new (Object.getPrototypeOf(async function () {}).constructor
);
const sha = 'b78b480eb4223390b2d17073387f9887d2e35f95';
+const baseSha = 'a'.repeat(40);
+const runBaseSha = 'c'.repeat(40);
+const repository = 'KeeperCommunity/bitcoin-keeper';
+const repositoryId = 470904030;
+const headRef = 'codex/example-change';
+const nativeWorkflowPath = '.github/workflows/keeper-hosted-native.yml';
const prNumber = 7045;
const comment = (body, login) => ({ body, user: { login } });
const handoff = (head = sha, checks = 'IOS, ANDROID, HARDWARE') => comment(
@@ -41,27 +47,105 @@ Real devices/signers: ${overrides.hardware || 'NOT RUN / POST-RELEASE by owner d
'local-writer'
);
+const hostedRun = (overrides = {}) => ({
+ id: 90,
+ workflow_id: 123,
+ path: nativeWorkflowPath,
+ head_sha: sha,
+ head_branch: headRef,
+ head_repository: { full_name: repository, id: repositoryId },
+ repository: { full_name: repository, id: repositoryId },
+ event: 'pull_request',
+ status: 'completed',
+ conclusion: 'success',
+ run_attempt: 2,
+ html_url: `https://github.com/${repository}/actions/runs/90`,
+ pull_requests: [{
+ number: prNumber,
+ head: { sha, ref: headRef, repo: { id: repositoryId } },
+ base: { sha: runBaseSha, ref: 'sprint', repo: { id: repositoryId } }
+ }],
+ ...overrides
+});
+const hostedJob = (platform, overrides = {}) => ({
+ name: platform === 'IOS' ? 'Hosted iOS simulator' : 'Hosted Android emulator',
+ head_sha: sha,
+ run_id: 90,
+ run_attempt: 2,
+ status: 'completed',
+ conclusion: 'success',
+ steps: ['Build development app', 'Run disposable startup smoke'].map(name => ({
+ name, status: 'completed', conclusion: 'success'
+ })),
+ ...overrides
+});
+const trustedTree = () => ({
+ truncated: false,
+ tree: [
+ { path: nativeWorkflowPath, mode: '100644', type: 'blob', sha: '1'.repeat(40) },
+ { path: '.github/native', mode: '040000', type: 'tree', sha: '2'.repeat(40) },
+ { path: '.github/native/smoke.yaml', mode: '100644', type: 'blob', sha: '3'.repeat(40) },
+ { path: '.github/native/build.sh', mode: '100755', type: 'blob', sha: '4'.repeat(40) },
+ { path: 'src/App.tsx', mode: '100644', type: 'blob', sha: '5'.repeat(40) }
+ ]
+});
+const hostedOptions = (overrides = {}) => ({
+ runs: [hostedRun()], jobs: [hostedJob('IOS'), hostedJob('ANDROID')], ...overrides
+});
+
async function evaluate(comments, options = {}) {
const filesRoute = () => {};
const commentsRoute = () => {};
+ const runsRoute = () => {};
+ const jobsRoute = () => {};
const statuses = [];
const failures = [];
+ const warnings = [];
+ const calls = [];
+ const pullsRequested = [];
+ let pullReads = 0;
const github = {
- paginate: async route => {
+ paginate: async (route, args) => {
+ calls.push({ route, args });
if (route === filesRoute) return options.files || [{ filename: 'src/App.tsx' }];
if (route === commentsRoute) return comments;
+ if (route === runsRoute) {
+ if (options.runsError) throw new Error(options.runsError);
+ return [...(options.runsByWorkflow?.[args.workflow_id] || options.runs || [])];
+ }
+ if (route === jobsRoute) {
+ if (options.jobsError) throw new Error(options.jobsError);
+ return options.jobsByRun?.[args.run_id] || options.jobs || [];
+ }
throw new Error('Unexpected paginate route');
},
rest: {
pulls: {
- get: async () => ({ data: {
- base: { ref: 'sprint' },
- head: { sha: options.head || sha },
- body: '', user: { login: 'cloud-writer' },
- html_url: 'https://github.com/KeeperCommunity/bitcoin-keeper/pull/7045'
- } }),
+ get: async ({ pull_number }) => {
+ pullsRequested.push(pull_number);
+ pullReads += 1;
+ const result = {
+ base: { ref: options.baseRef || 'sprint', sha: baseSha,
+ repo: { full_name: repository, id: repositoryId } },
+ head: { sha: pullReads > 1 && options.afterHead ? options.afterHead : options.head || sha,
+ ref: headRef, repo: options.headRepository || { full_name: repository, id: repositoryId } },
+ body: options.body || '', user: { login: 'cloud-writer' },
+ draft: options.draft ?? false,
+ labels: options.labels ?? [{ name: 'keeper/legacy-native' }],
+ html_url: `https://github.com/${repository}/pull/${pull_number}`
+ };
+ if (pullReads > 1) options.afterMutation?.(result);
+ return { data: result };
+ },
listFiles: filesRoute
},
+ actions: { listWorkflowRuns: runsRoute, listJobsForWorkflowRunAttempt: jobsRoute },
+ git: {
+ getTree: async ({ tree_sha }) => {
+ if (options.treeErrors?.includes(tree_sha)) throw new Error('Tree unavailable');
+ return { data: options.trees?.[tree_sha] || trustedTree() };
+ }
+ },
issues: { listComments: commentsRoute },
repos: {
getCollaboratorPermissionLevel: async ({ username }) => ({ data: {
@@ -74,11 +158,14 @@ async function evaluate(comments, options = {}) {
}
};
const context = { repo: { owner: 'KeeperCommunity', repo: 'bitcoin-keeper' },
- issue: { number: prNumber }, payload: {} };
- const core = { info: () => {}, warning: () => {}, setFailed: text => failures.push(text) };
+ issue: { number: prNumber }, payload: {}, ...options.context };
+ const core = { info: () => {}, warning: text => warnings.push(text),
+ setFailed: text => failures.push(text) };
await runWorkflow(github, context, core);
- assert.equal(statuses.length, 1);
- return { status: statuses[0], failures };
+ assert.equal(statuses.length, options.afterHead || options.baseRef ? 0 : 1);
+ return { status: statuses[0], statuses, failures, warnings, calls, pullsRequested,
+ runsCalls: calls.filter(c => c.route === runsRoute),
+ jobsCalls: calls.filter(c => c.route === jobsRoute) };
}
test('current requirements still fail without an owner decision', async () => {
@@ -158,3 +245,403 @@ test('a new PR head invalidates both handoff and owner decision', async () => {
assert.equal(status.state, 'failure');
assert.equal(status.description, 'Trusted Cloud handoff for current SHA required');
});
+
+test('trusted exact-head hosted smoke passes both platforms without a local attestation', async () => {
+ const result = await evaluate([handoff(sha, 'IOS, ANDROID')], hostedOptions());
+ assert.equal(result.status.state, 'success');
+ assert.match(result.status.description, /hosted IOS, ANDROID/);
+ assert.equal(result.status.sha, sha);
+ assert.equal(result.failures.length, 0);
+ assert.deepEqual(result.runsCalls[0].args, {
+ owner: 'KeeperCommunity', repo: 'bitcoin-keeper', workflow_id: 'keeper-hosted-native.yml',
+ head_sha: sha, event: 'pull_request', per_page: 100
+ });
+ assert.equal(result.jobsCalls[0].args.attempt_number, 2);
+});
+
+test('successful hosted Android can combine with local iOS when hosted iOS fails', async () => {
+ const { status } = await evaluate([
+ handoff(sha, 'IOS, ANDROID'), report({ android: 'NOT RUN' })
+ ], hostedOptions({
+ runs: [hostedRun({ conclusion: 'failure' })],
+ jobs: [hostedJob('IOS', { conclusion: 'failure' }), hostedJob('ANDROID')]
+ }));
+ assert.equal(status.state, 'success');
+ assert.match(status.description, /hosted ANDROID/);
+});
+
+test('one platform success cannot satisfy the other platform', async () => {
+ const { status } = await evaluate([handoff(sha, 'IOS, ANDROID')], hostedOptions({
+ jobs: [hostedJob('ANDROID')]
+ }));
+ assert.equal(status.state, 'failure');
+ assert.match(status.description, /IOS/);
+});
+
+test('hosted platform passes do not satisfy physical hardware checks', async () => {
+ const { status } = await evaluate([handoff()], hostedOptions());
+ assert.equal(status.state, 'failure');
+ assert.equal(status.description, 'Missing local PASS: HARDWARE');
+});
+
+test('hosted passes can fill unrun platforms while exact owner rules defer hardware', async () => {
+ const { status } = await evaluate([handoff(), decision(),
+ report({ ios: 'NOT RUN', android: 'NOT RUN' })], hostedOptions());
+ assert.equal(status.state, 'success');
+ assert.match(status.description, /hosted IOS, ANDROID; owner-deferred HARDWARE/);
+});
+
+test('hosted success cannot waive hardware failures or remove later-report requirements', async () => {
+ for (const comments of [
+ [handoff(), decision()],
+ [handoff(), report(), decision()],
+ [handoff(), decision(), report({ hardware: 'FAIL: incorrect signer address' })],
+ [handoff(), decision({}, 'other-writer'), report()]
+ ]) {
+ const { status } = await evaluate(comments, hostedOptions());
+ assert.equal(status.state, 'failure');
+ assert.match(status.description, /HARDWARE/);
+ }
+});
+
+test('latest trusted local failure or blocked report cannot be hidden by hosted passes', async () => {
+ for (const state of ['LOCAL_FAILED', 'BLOCKED']) {
+ const { status } = await evaluate([handoff(sha, 'IOS, ANDROID'),
+ report(), report({ state })], hostedOptions());
+ assert.equal(status.state, 'failure');
+ assert.equal(status.description, 'Latest local validation is not LOCAL_PASSED');
+ }
+});
+
+test('explicit local platform failures cannot be relabeled as passed by hosted results', async () => {
+ for (const failedField of ['ios', 'android']) {
+ const { status } = await evaluate([handoff(sha, 'IOS, ANDROID'),
+ report({ [failedField]: 'FAIL: reproducible startup crash' })], hostedOptions());
+ assert.equal(status.state, 'failure', failedField);
+ }
+});
+
+test('hosted passes still require a trusted current-head Cloud handoff', async () => {
+ for (const comments of [[], [handoff('d'.repeat(40), 'IOS, ANDROID')],
+ [comment(handoff(sha, 'IOS, ANDROID').body, 'read-only-user')]]) {
+ const result = await evaluate(comments, hostedOptions());
+ assert.equal(result.status.state, 'failure');
+ assert.equal(result.runsCalls.length, 0);
+ }
+});
+
+test('reject hosted runs with stale, wrong, missing or untrusted identity metadata', async () => {
+ const badRuns = [
+ { head_sha: 'd'.repeat(40) },
+ { head_branch: 'other-branch' },
+ { head_repository: { full_name: 'attacker/bitcoin-keeper', id: 1 } },
+ { path: '.github/workflows/build-only.yml' },
+ { event: 'push' },
+ { event: 'pull_request_target' },
+ { pull_requests: [] },
+ { pull_requests: [{ ...hostedRun().pull_requests[0], number: prNumber + 1 }] },
+ { pull_requests: [{ ...hostedRun().pull_requests[0],
+ head: { sha: 'd'.repeat(40), ref: headRef, repo: { id: repositoryId } } }] },
+ { pull_requests: [{ ...hostedRun().pull_requests[0],
+ base: { ref: 'sprint', repo: { id: repositoryId } } }] },
+ { run_attempt: 0 },
+ { run_attempt: '2' }
+ ];
+ for (const change of badRuns) {
+ const { status } = await evaluate([handoff(sha, 'IOS, ANDROID')],
+ hostedOptions({ runs: [hostedRun(change)] }));
+ assert.equal(status.state, 'failure', JSON.stringify(change));
+ }
+});
+
+test('reject hosted evidence whose recorded PR association has wrong refs or repositories', async () => {
+ const original = hostedRun().pull_requests[0];
+ for (const change of [
+ { base: { ...original.base, ref: 'dev' } },
+ { base: { ...original.base, repo: { id: 1 } } },
+ { head: { ...original.head, ref: 'other-branch' } },
+ { head: { ...original.head, repo: { id: 1 } } }
+ ]) {
+ const { status } = await evaluate([handoff(sha, 'IOS, ANDROID')],
+ hostedOptions({ runs: [hostedRun({ pull_requests: [{ ...original, ...change }] })] }));
+ assert.equal(status.state, 'failure', JSON.stringify(change));
+ }
+});
+
+test('fork-hosted runs retain local fallback but cannot supply trusted hosted evidence', async () => {
+ const options = hostedOptions({ headRepository: { full_name: 'contributor/bitcoin-keeper', id: 1 } });
+ const hostedOnly = await evaluate([handoff(sha, 'IOS, ANDROID')], options);
+ assert.equal(hostedOnly.status.state, 'failure');
+ const local = await evaluate([handoff(sha, 'IOS, ANDROID'), report()], options);
+ assert.equal(local.status.state, 'success');
+});
+
+test('hosted CI requires matching workflow and entire native harness in source and both bases', async () => {
+ for (const ref of [sha, baseSha, runBaseSha]) {
+ for (const mutation of ['workflow', 'smoke', 'add', 'delete', 'mode']) {
+ const tree = trustedTree();
+ if (mutation === 'workflow') tree.tree[0].sha = 'f'.repeat(40);
+ if (mutation === 'smoke') tree.tree[2].sha = 'f'.repeat(40);
+ if (mutation === 'add') tree.tree.push({
+ path: '.github/native/extra.sh', mode: '100755', type: 'blob', sha: 'f'.repeat(40)
+ });
+ if (mutation === 'delete') tree.tree.splice(2, 1);
+ if (mutation === 'mode') tree.tree[3].mode = '100644';
+ const { status } = await evaluate([handoff(sha, 'IOS, ANDROID')],
+ hostedOptions({ trees: { [ref]: tree } }));
+ assert.equal(status.state, 'failure', `${ref}: ${mutation}`);
+ }
+ }
+});
+
+test('unrelated source changes do not invalidate immutable hosted CI definitions', async () => {
+ const tree = trustedTree();
+ tree.tree[4].sha = 'f'.repeat(40);
+ const { status } = await evaluate([handoff(sha, 'IOS, ANDROID')],
+ hostedOptions({ trees: { [sha]: tree } }));
+ assert.equal(status.state, 'success');
+});
+
+test('bootstrap without trusted native infrastructure and truncated trees fail closed', async () => {
+ for (const tree of [{ truncated: false, tree: [] },
+ { ...trustedTree(), truncated: true },
+ { truncated: false, tree: trustedTree().tree.filter(e => e.path !== nativeWorkflowPath) },
+ { truncated: false, tree: trustedTree().tree.filter(e => !e.path.startsWith('.github/native/')) }]) {
+ const { status } = await evaluate([handoff(sha, 'IOS, ANDROID')],
+ hostedOptions({ trees: { [baseSha]: tree } }));
+ assert.equal(status.state, 'failure');
+ }
+});
+
+test('hosted API failures never become a pass and preserve genuine local fallback', async () => {
+ for (const failure of [{ runsError: 'Actions unavailable' },
+ { jobsError: 'Jobs unavailable' }, { treeErrors: [runBaseSha] }]) {
+ const options = hostedOptions(failure);
+ const hostedOnly = await evaluate([handoff(sha, 'IOS, ANDROID')], options);
+ assert.equal(hostedOnly.status.state, 'failure');
+ assert.ok(hostedOnly.warnings.length);
+ const local = await evaluate([handoff(sha, 'IOS, ANDROID'), report()], options);
+ assert.equal(local.status.state, 'success');
+ }
+});
+
+test('cancelled, skipped, pending or incomplete hosted runs provide no platform evidence', async () => {
+ for (const change of [{ status: 'queued', conclusion: null },
+ { status: 'in_progress', conclusion: null }, { conclusion: 'cancelled' },
+ { conclusion: 'skipped' }, { conclusion: 'timed_out' }, { conclusion: 'action_required' },
+ { conclusion: 'neutral' }, { conclusion: null }]) {
+ const { status } = await evaluate([handoff(sha, 'IOS, ANDROID')],
+ hostedOptions({ runs: [hostedRun(change)] }));
+ assert.equal(status.state, 'failure', JSON.stringify(change));
+ }
+});
+
+test('a newer failed or pending run supersedes an older successful run regardless of API order', async () => {
+ for (const newest of [hostedRun({ id: 91, conclusion: 'cancelled' }),
+ hostedRun({ id: 91, status: 'in_progress', conclusion: null }),
+ hostedRun({ id: 91, conclusion: 'failure' })]) {
+ const { status, jobsCalls } = await evaluate([handoff(sha, 'IOS, ANDROID')], hostedOptions({
+ runs: [hostedRun(), newest], jobsByRun: { 91: [] }
+ }));
+ assert.equal(status.state, 'failure');
+ assert.ok(jobsCalls.every(call => call.args.run_id === 91));
+ }
+});
+
+test('reruns inspect only the newest attempt and do not reuse earlier success', async () => {
+ const result = await evaluate([handoff(sha, 'IOS, ANDROID')], hostedOptions({
+ runs: [hostedRun({ run_attempt: 3 })], jobs: [hostedJob('IOS'), hostedJob('ANDROID')]
+ }));
+ assert.equal(result.jobsCalls[0].args.attempt_number, 3);
+ assert.equal(result.status.state, 'failure');
+});
+
+test('a successful draft workflow with skipped native jobs supplies no platform or hardware pass', async () => {
+ for (const required of ['IOS', 'ANDROID', 'IOS, ANDROID', 'IOS, ANDROID, HARDWARE']) {
+ const result = await evaluate([handoff(sha, required)], hostedOptions({
+ draft: true,
+ jobs: ['IOS', 'ANDROID'].map(platform => hostedJob(platform, { conclusion: 'skipped', steps: [] })),
+ }));
+ assert.equal(result.status.state, 'failure', required);
+ }
+});
+
+test('a newer skipped draft run cannot reuse a ready PR run or an earlier attempt', async () => {
+ for (const run of [hostedRun({ id: 91 }), hostedRun({ id: 91, run_attempt: 3 })]) {
+ const result = await evaluate([handoff(sha, 'IOS, ANDROID')], hostedOptions({
+ draft: true, runs: [hostedRun(), run],
+ jobsByRun: { 91: ['IOS', 'ANDROID'].map(platform => hostedJob(platform,
+ { run_id: 91, run_attempt: run.run_attempt, conclusion: 'skipped', steps: [] })) },
+ }));
+ assert.equal(result.status.state, 'failure');
+ assert.ok(result.jobsCalls.every(call => call.args.run_id === 91 && call.args.attempt_number === run.run_attempt));
+ }
+});
+
+test('wrong run identity and stale source on jobs cannot satisfy current platform checks', async () => {
+ for (const change of [{ head_sha: 'd'.repeat(40) }, { run_id: 89 },
+ { run_attempt: 1 }, { status: 'in_progress' }, { conclusion: 'cancelled' },
+ { conclusion: 'skipped' }, { conclusion: 'failure' }]) {
+ const { status } = await evaluate([handoff(sha, 'IOS')], hostedOptions({
+ jobs: [hostedJob('IOS', change)]
+ }));
+ assert.equal(status.state, 'failure', JSON.stringify(change));
+ }
+});
+
+test('a build-only job or missing, skipped, cancelled or failed smoke is not native validation', async () => {
+ for (const steps of [[], [hostedJob('IOS').steps[0]], [hostedJob('IOS').steps[1]],
+ ...['skipped', 'cancelled', 'failure'].map(conclusion => [
+ hostedJob('IOS').steps[0], { ...hostedJob('IOS').steps[1], conclusion }
+ ]), [hostedJob('IOS').steps[0], { ...hostedJob('IOS').steps[1], status: 'in_progress' }]]) {
+ const { status } = await evaluate([handoff(sha, 'IOS')], hostedOptions({
+ jobs: [hostedJob('IOS', { steps })]
+ }));
+ assert.equal(status.state, 'failure', JSON.stringify(steps));
+ }
+});
+
+test('duplicate platform jobs or required steps do not ambiguously satisfy validation', async () => {
+ for (const jobs of [[hostedJob('IOS'), hostedJob('IOS')],
+ [hostedJob('IOS', { steps: [...hostedJob('IOS').steps, hostedJob('IOS').steps[1]] })]]) {
+ const { status } = await evaluate([handoff(sha, 'IOS')], hostedOptions({ jobs }));
+ assert.equal(status.state, 'failure');
+ }
+});
+
+test('workflow_run routing evaluates the associated PR and refreshes its current head', async () => {
+ const routedNumber = 7059;
+ const run = hostedRun({ pull_requests: [{ ...hostedRun().pull_requests[0], number: routedNumber }] });
+ const result = await evaluate([handoff(sha, 'IOS, ANDROID')], hostedOptions({
+ runs: [run], context: { issue: {}, eventName: 'workflow_run', payload: { workflow_run: run } }
+ }));
+ assert.equal(result.status.state, 'success');
+ assert.deepEqual(result.pullsRequested, [routedNumber, routedNumber]);
+ assert.match(result.status.target_url, /pull\/7059$/);
+});
+
+test('a PR head change during validation prevents posting obsolete success', async () => {
+ const result = await evaluate([handoff(sha, 'IOS, ANDROID')], hostedOptions({
+ afterHead: 'd'.repeat(40)
+ }));
+ assert.equal(result.statuses.length, 0);
+ assert.match(result.failures[0], /PR head changed/);
+});
+
+test('documentation and GitHub metadata exemption never consumes hosted CI assertions', async () => {
+ const result = await evaluate([], hostedOptions({ files: [
+ { filename: 'AGENTS.md' }, { filename: '.github/workflows/keeper-hosted-native.yml' }
+ ] }));
+ assert.equal(result.status.state, 'success');
+ assert.equal(result.runsCalls.length, 0);
+ assert.equal(result.jobsCalls.length, 0);
+});
+
+test('hosted workflow lifecycle events refresh the privileged gate under the exact workflow name', () => {
+ const nativeWorkflow = fs.readFileSync(path.join(path.dirname(workflowPath),
+ 'keeper-hosted-native.yml'), 'utf8');
+ const name = nativeWorkflow.match(/^name:\s*(.+)$/m)?.[1];
+ assert.ok(name, 'hosted workflow must have a name');
+ assert.ok(lines.some(line => line.trim() === `workflows: [${name}, Keeper release acceptance]`),
+ 'workflow_run must name the actual hosted workflow');
+ assert.ok(lines.some(line => line.trim() === 'types: [completed, requested, in_progress]'),
+ 'new attempts must invalidate old hosted evidence promptly');
+});
+
+const reusableRun = overrides => hostedRun({
+ path: '.github/workflows/keeper-release-acceptance.yml',
+ pull_requests: [{ ...hostedRun().pull_requests[0], number: 8000 }], ...overrides,
+});
+const reusableJob = (platform, overrides) => hostedJob(platform, {
+ name: `${platform.toLowerCase()} / Native ${platform} build and probes`,
+ steps: ['Build development app', ...(platform === 'IOS'
+ ? ['Run disposable startup smoke', 'Run disposable native persistence probe']
+ : ['Run Android startup and native persistence probes'])].map(name => ({ name, status: 'completed', conclusion: 'success' })),
+ ...overrides,
+});
+const reusableTree = () => ({ ...trustedTree(), tree: [...trustedTree().tree,
+ { path: '.github/workflows/keeper-release-acceptance.yml', mode: '100644', type: 'blob', sha: '6'.repeat(40) },
+ { path: '.github/workflows/keeper-native-platform.yml', mode: '100644', type: 'blob', sha: '7'.repeat(40) },
+] });
+const reusableOptions = overrides => ({
+ context: { issue: { number: 8000 } }, labels: [],
+ runs: [reusableRun()], jobs: [reusableJob('IOS'), reusableJob('ANDROID')],
+ trees: { [sha]: reusableTree(), [baseSha]: reusableTree(), [runBaseSha]: reusableTree() },
+ ...overrides,
+});
+test('reusable exact-head native scope can satisfy platform gate without claiming full matrix or hardware', async () => {
+ const { status } = await evaluate([handoff(sha, 'IOS, ANDROID')], reusableOptions());
+ assert.equal(status.state, 'success');
+ assert.match(status.description, /hosted IOS, ANDROID/);
+ const hardware = await evaluate([handoff()], reusableOptions());
+ assert.equal(hardware.status.state, 'failure');
+ assert.match(hardware.status.description, /HARDWARE/);
+});
+test('reusable evidence requires probe steps, latest attempt and matching protected worker in both bases', async () => {
+ for (const overrides of [
+ { jobs: [reusableJob('IOS', { steps: hostedJob('IOS').steps }), reusableJob('ANDROID')] },
+ { jobs: [reusableJob('IOS', { run_attempt: 1 }), reusableJob('ANDROID')] },
+ { runs: [reusableRun({ id: 91, conclusion: 'cancelled' }), reusableRun()] },
+ { runs: [reusableRun({ id: 91, conclusion: 'skipped' }), reusableRun()] },
+ { runs: [reusableRun({ path: '.github/workflows/keeper-native-diagnostic.yml' })] },
+ ]) {
+ const { status } = await evaluate([handoff(sha, 'IOS, ANDROID')], reusableOptions(overrides));
+ assert.equal(status.state, 'failure');
+ }
+ for (const ref of [baseSha, runBaseSha]) {
+ const changed = reusableTree();
+ changed.tree.find(e => e.path.endsWith('keeper-native-platform.yml')).sha = '8'.repeat(40);
+ const { status } = await evaluate([handoff(sha, 'IOS, ANDROID')], reusableOptions({
+ trees: { [sha]: reusableTree(), [baseSha]: reusableTree(), [runBaseSha]: reusableTree(), [ref]: changed },
+ }));
+ assert.equal(status.state, 'failure');
+ }
+});
+test('a newer unsuccessful reusable run supersedes older legacy successes across workflow routes', async () => {
+ const linked = { ...hostedRun().pull_requests[0], number: 8000 };
+ const { status } = await evaluate([handoff(sha, 'IOS, ANDROID')], reusableOptions({
+ runsByWorkflow: {
+ 'keeper-hosted-native.yml': [hostedRun({ pull_requests: [linked] })],
+ 'keeper-release-acceptance.yml': [reusableRun({ id: 91, conclusion: 'cancelled' })],
+ },
+ }));
+ assert.equal(status.state, 'failure');
+});
+test('a deliberately skipped alternate route cannot shadow actual selected-route evidence', async () => {
+ const linked = { ...hostedRun().pull_requests[0], number: 8000 };
+ for (const legacy of [false, true]) {
+ const { status } = await evaluate([handoff(sha, 'IOS, ANDROID')], reusableOptions({
+ labels: legacy ? [{ name: 'keeper/legacy-native' }] : [],
+ jobs: legacy ? [hostedJob('IOS'), hostedJob('ANDROID')] : [reusableJob('IOS'), reusableJob('ANDROID')],
+ runsByWorkflow: {
+ 'keeper-hosted-native.yml': [hostedRun({ id: legacy ? 90 : 92, pull_requests: [linked], conclusion: legacy ? 'success' : 'skipped' })],
+ 'keeper-release-acceptance.yml': [reusableRun({ id: legacy ? 92 : 90, conclusion: legacy ? 'skipped' : 'failure' })],
+ },
+ }));
+ assert.equal(status.state, 'success', `legacy=${legacy}`);
+ }
+});
+test('diagnostic label cannot consume prior trusted selected-route evidence', async () => {
+ const { status, runsCalls } = await evaluate([handoff(sha, 'IOS, ANDROID')], reusableOptions({
+ labels: [{ name: 'keeper/native-diagnostic' }],
+ }));
+ assert.equal(status.state, 'failure');
+ assert.equal(runsCalls.length, 0);
+});
+test('base, repository/ref or route movement at unchanged head cannot publish stale success', async () => {
+ for (const afterMutation of [
+ pr => { pr.base.sha = 'd'.repeat(40); }, pr => { pr.base.ref = 'other'; },
+ pr => { pr.base.repo.id += 1; }, pr => { pr.base.repo.full_name = 'other/repo'; },
+ pr => { pr.head.ref = 'other'; }, pr => { pr.head.repo.id += 1; },
+ pr => { pr.head.repo.full_name = 'other/repo'; }, pr => { pr.labels = [{ name: 'keeper/native-diagnostic' }]; },
+ ]) {
+ const { statuses, failures } = await evaluate([handoff(sha, 'IOS, ANDROID')], reusableOptions({ afterMutation }));
+ assert.equal(statuses.length, 1);
+ assert.equal(statuses[0].state, 'failure', 'same-head race explicitly supersedes prior success');
+ assert.match(failures[0], /changed during validation/);
+ }
+});
+
+test('route-label changes immediately reevaluate the trusted gate', () => {
+ assert.ok(lines.some(line => line.includes('ready_for_review, labeled, unlabeled]')));
+});
diff --git a/.github/tests/native-action-pins.test.cjs b/.github/tests/native-action-pins.test.cjs
new file mode 100644
index 0000000000..afb882b0bb
--- /dev/null
+++ b/.github/tests/native-action-pins.test.cjs
@@ -0,0 +1,185 @@
+'use strict';
+
+const assert = require('node:assert/strict');
+const fs = require('node:fs');
+const path = require('node:path');
+const { spawnSync } = require('node:child_process');
+const test = require('node:test');
+
+// Scope: workflows introduced by the bootstrap. Existing gate/action policy is
+// unchanged; this does not silently repin unrelated workflows.
+const workflows = ['keeper-hosted-native.yml', 'keeper-validation-tests.yml',
+ 'keeper-native-platform.yml', 'keeper-release-acceptance.yml', 'keeper-native-diagnostic.yml'];
+// Verified upstream refs/tags/v2.34.0^{} on 2026-10-18, also used by #7062.
+// The annotated tag object is 324029e2f414c084d8b15ba075288885e74aef9c.
+const emulatorCommit = '1dcd0090116d15e7c562f8db72807de5e036a4ed';
+const emulatorAction = 'reactivecircus/android-emulator-runner';
+// Other pins match the upstream tags noted in the workflows, read-only checked
+// on the same date. Updates require a new verified commit, not just SHA syntax.
+const verifiedPins = new Map([
+ ['actions/github-script', 'ed597411d8f924073f98dfc5c65a23a2325f34cd'],
+ ['actions/checkout', 'd23441a48e516b6c34aea4fa41551a30e30af803'],
+ ['actions/setup-node', '249970729cb0ef3589644e2896645e5dc5ba9c38'],
+ ['actions/setup-java', 'b6effb05e454b25005698d916606bdc6ffcbf961'],
+ ['ruby/setup-ruby', '675dd7ba1b06c8786a1480d89c384f5620a42647'],
+ ['actions/upload-artifact', 'b7c566a772e6b6bfb58ed0dc250532a479d7789f'],
+ ['android-actions/setup-android', 'be39fa834029ff78f1a44aa3bb0819b8fc2bd8fd'],
+ [emulatorAction, emulatorCommit],
+]);
+
+// Use the host's existing Python/PyYAML parser, never app dependencies or a
+// partial YAML regex. Missing tooling, ambiguous duplicate keys and unsupported
+// YAML values fail the contract; there is no permissive fallback or install.
+const yamlParser = `
+import json
+import sys
+import yaml
+
+class UniqueSafeLoader(yaml.SafeLoader):
+ pass
+
+def unique_mapping(loader, node, deep=False):
+ loader.flatten_mapping(node)
+ result = {}
+ for key_node, value_node in node.value:
+ key = loader.construct_object(key_node, deep=deep)
+ if key in result:
+ raise ValueError('Duplicate YAML mapping key')
+ result[key] = loader.construct_object(value_node, deep=deep)
+ return result
+
+UniqueSafeLoader.add_constructor(yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG, unique_mapping)
+print(json.dumps(yaml.load(sys.stdin.read(), Loader=UniqueSafeLoader)))
+`;
+
+function actionReferences(workflow, runParser = spawnSync) {
+ const result = runParser('python3', ['-B', '-c', yamlParser], {
+ input: workflow, encoding: 'utf8', timeout: 5000, maxBuffer: 1024 * 1024,
+ });
+ assert.equal(result.status, 0,
+ `YAML parsing is required (Python 3 + PyYAML): ${result.error?.message || result.stderr || ''}`);
+ const document = JSON.parse(result.stdout);
+ const mapping = value => value !== null && typeof value === 'object' && !Array.isArray(value);
+ assert.ok(mapping(document) && mapping(document.jobs), 'workflow must have a jobs mapping');
+ const references = [];
+ for (const job of Object.values(document.jobs)) {
+ assert.ok(mapping(job), 'each job must be a mapping');
+ if (Object.hasOwn(job, 'uses')) references.push(job.uses);
+ if (Object.hasOwn(job, 'steps')) {
+ assert.ok(Array.isArray(job.steps), 'job steps must be a sequence');
+ for (const step of job.steps) {
+ assert.ok(mapping(step), 'each step must be a mapping');
+ if (Object.hasOwn(step, 'uses')) references.push(step.uses);
+ }
+ }
+ }
+ assert.ok(references.every(reference => typeof reference === 'string'), 'uses values must be strings');
+ return references;
+}
+
+function validateActionPins(workflow) {
+ const references = actionReferences(workflow);
+ assert.ok(references.length > 0, 'expected external actions in bootstrap workflow');
+ for (const reference of references) {
+ if (reference === './.github/workflows/keeper-native-platform.yml') continue;
+ assert.match(reference, /^[\w-]+\/[\w./-]+@[0-9a-f]{40}$/,
+ `external actions require a full immutable commit: ${reference}`);
+ const [action, revision] = reference.split('@');
+ assert.ok(verifiedPins.has(action), `action needs a verified upstream commit: ${action}`);
+ assert.equal(revision, verifiedPins.get(action),
+ 'action must use its verified upstream commit, not an arbitrary SHA or tag object');
+ }
+}
+
+// Keep a valid companion action so a skipped mutable entry cannot pass merely
+// because the parser found some other pinned reference in the same workflow.
+function workflowWithStep(step) {
+ return `jobs:
+ contracts:
+ steps:
+ - uses: actions/setup-node@${verifiedPins.get('actions/setup-node')}
+ - ${step}
+`;
+}
+
+test('bootstrap external actions have full immutable pins and the verified emulator commit', () => {
+ for (const workflow of workflows) {
+ validateActionPins(fs.readFileSync(path.join(__dirname, '../workflows', workflow), 'utf8'));
+ }
+ const hosted = fs.readFileSync(path.join(__dirname, '../workflows', workflows[0]), 'utf8');
+ assert.equal(actionReferences(hosted).filter(ref => ref.startsWith(`${emulatorAction}@`)).length, 1);
+});
+
+test('action pin validation rejects mutable, short, malformed and tag-object revisions', () => {
+ for (const revision of ['v2', 'v2.34.0', 'main', emulatorCommit.slice(0, 12),
+ '324029e2f414c084d8b15ba075288885e74aef9c38',
+ '324029e2f414c084d8b15ba075288885e74aef9c', 'a'.repeat(40), 'g'.repeat(40),
+ '${{ inputs.revision }}']) {
+ assert.throws(() => validateActionPins(workflowWithStep(`uses: ${emulatorAction}@${revision}`)),
+ /full immutable commit|verified upstream commit/, revision);
+ }
+ assert.throws(() => validateActionPins(workflowWithStep('uses: actions/checkout@v6')), /full immutable commit/);
+ assert.throws(() => validateActionPins(workflowWithStep(`uses: actions/checkout@${'a'.repeat(40)}`)), /verified upstream commit/);
+ assert.throws(() => validateActionPins(workflowWithStep(`uses: unknown/action@${emulatorCommit}`)), /verified upstream commit/);
+ assert.throws(() => validateActionPins('jobs: {}\n'), assert.AssertionError);
+});
+
+test('quoted keys, flow mappings and folded values cannot hide a mutable action beside pinned actions', () => {
+ const forms = [
+ reference => `"uses": ${reference}`,
+ reference => `'uses': '${reference}'`,
+ reference => `"\\u0075ses": "${reference}"`,
+ reference => `!!str uses: ${reference}`,
+ reference => `{uses: ${reference}}`,
+ reference => `{"name": "checkout", "uses": "${reference}"}`,
+ reference => `uses: >-\n ${reference}`,
+ reference => `uses: |-\n ${reference}`,
+ ];
+ for (const form of forms) {
+ const pinned = `actions/checkout@${verifiedPins.get('actions/checkout')}`;
+ const valid = workflowWithStep(form(pinned));
+ assert.deepEqual(actionReferences(valid), [
+ `actions/setup-node@${verifiedPins.get('actions/setup-node')}`, pinned,
+ ]);
+ validateActionPins(valid);
+ for (const mutable of ['actions/checkout@v6', 'actions/checkout@main']) {
+ const invalid = workflowWithStep(form(mutable));
+ assert.ok(actionReferences(invalid).includes(mutable), 'mutable action must be inspected, not skipped');
+ assert.throws(() => validateActionPins(invalid), /full immutable commit/, form(mutable));
+ }
+ }
+});
+
+test('whole flow documents, aliases and job-level uses are inspected', () => {
+ const pinned = `actions/checkout@${verifiedPins.get('actions/checkout')}`;
+ const forms = [
+ reference => JSON.stringify({ jobs: { contracts: { steps: [
+ { uses: pinned }, { uses: reference },
+ ] } } }),
+ reference => `jobs:\n contracts:\n steps:\n - uses: ${pinned}\n - &checkout {uses: ${reference}}\n - *checkout\n`,
+ reference => `jobs: {build: {steps: [{uses: ${pinned}}]}, reuse: {"uses": "${reference}"}}\n`,
+ ];
+ for (const form of forms) {
+ validateActionPins(form(pinned));
+ assert.ok(actionReferences(form('actions/checkout@v6')).includes('actions/checkout@v6'));
+ assert.throws(() => validateActionPins(form('actions/checkout@v6')), /full immutable commit/);
+ }
+});
+
+test('YAML inspection fails closed for unavailable parsers, invalid input and duplicate keys', () => {
+ for (const result of [
+ { status: null, error: new Error('spawn python3 ENOENT') },
+ { status: 1, stderr: "ModuleNotFoundError: No module named 'yaml'" },
+ { status: null, error: new Error('parser timeout') },
+ ]) {
+ assert.throws(() => actionReferences('jobs: {}', () => result), /YAML parsing is required/);
+ }
+ assert.throws(() => validateActionPins('jobs: ['), /YAML parsing is required/);
+ const pinned = `actions/checkout@${verifiedPins.get('actions/checkout')}`;
+ for (const references of [[pinned, 'actions/checkout@v6'], ['actions/checkout@v6', pinned]]) {
+ assert.throws(() => validateActionPins(workflowWithStep(
+ `uses: ${references[0]}\n "uses": ${references[1]}`)), /Duplicate YAML mapping key/);
+ }
+ assert.throws(() => validateActionPins(workflowWithStep('uses: {action: actions/checkout@v6}')),
+ /uses values must be strings/);
+});
diff --git a/.github/tests/native-artifact-attempts.test.cjs b/.github/tests/native-artifact-attempts.test.cjs
new file mode 100644
index 0000000000..0fe37370f7
--- /dev/null
+++ b/.github/tests/native-artifact-attempts.test.cjs
@@ -0,0 +1,52 @@
+'use strict';
+// Workflow naming contracts only; no native execution or artifact upload.
+const assert = require('node:assert/strict');
+const { test } = require('node:test');
+const { spawnSync } = require('node:child_process');
+const path = require('node:path');
+const parsed = spawnSync('python3', ['-B', '-c', `
+import json,pathlib,sys,yaml
+print(json.dumps(yaml.load(pathlib.Path(sys.argv[1]).read_text(),Loader=yaml.BaseLoader)))
+`, path.resolve(__dirname, '../workflows/keeper-native-platform.yml')], { encoding: 'utf8', timeout: 5000 });
+assert.equal(parsed.status, 0, parsed.stderr);
+const workflow = JSON.parse(parsed.stdout);
+const upload = workflow.jobs.native.steps.find(step => step.name === 'Retain safe Phase A evidence');
+
+function artifactName({ diagnostic = true, platform = 'IOS', sha = 'a'.repeat(40), run = '90', attempt = '1' } = {}) {
+ const expressions = {
+ "inputs.diagnostic && 'diagnostic' || 'release'": diagnostic ? 'diagnostic' : 'release',
+ 'inputs.platform': platform, 'inputs.source_sha': sha,
+ 'github.run_id': run, 'github.run_attempt': attempt,
+ };
+ return upload.with.name.replace(/\$\{\{\s*(.*?)\s*\}\}/g, (_, expression) => {
+ assert.ok(Object.hasOwn(expressions, expression), 'unexpected artifact-name context');
+ return expressions[expression];
+ });
+}
+
+test('a retry retains a distinct immutable artifact for the same source and run', () => {
+ const retained = new Set();
+ for (const attempt of ['1', '2']) {
+ const name = artifactName({ attempt });
+ assert.equal(retained.has(name), false, 'same-SHA retry must not collide with earlier evidence');
+ retained.add(name);
+ assert.equal(name, `keeper-diagnostic-native-IOS-${'a'.repeat(40)}-90-${attempt}`);
+ }
+});
+
+test('artifact selectors distinguish route, platform, source, run and attempt', () => {
+ const names = [];
+ for (const diagnostic of [true, false]) for (const platform of ['IOS', 'ANDROID'])
+ for (const sha of ['a'.repeat(40), 'b'.repeat(40)]) for (const run of ['90', '91'])
+ for (const attempt of ['1', '2']) names.push(artifactName({ diagnostic, platform, sha, run, attempt }));
+ assert.equal(new Set(names).size, 32);
+});
+
+test('failed-run metadata retention cannot overwrite or delete previous attempts', () => {
+ assert.equal(upload.if, 'always()');
+ assert.equal(upload.with.path, 'artifacts/native/*/metadata.json');
+ assert.equal(upload.with['if-no-files-found'], 'error');
+ assert.equal(upload.with['retention-days'], '7');
+ assert.equal(upload.with.overwrite, undefined);
+ assert.equal(upload.with['include-hidden-files'], undefined);
+});
diff --git a/.github/tests/native-diagnostic-policy.test.cjs b/.github/tests/native-diagnostic-policy.test.cjs
new file mode 100644
index 0000000000..26dc6702e2
--- /dev/null
+++ b/.github/tests/native-diagnostic-policy.test.cjs
@@ -0,0 +1,150 @@
+'use strict';
+// Metadata-only policy checks; this file cannot supply native evidence.
+const assert = require('node:assert/strict');
+const { test } = require('node:test');
+const fs = require('node:fs');
+const { spawnSync } = require('node:child_process');
+const vm = require('node:vm');
+const path = require('node:path');
+const parsed = spawnSync('python3', ['-B', '-c', `
+import json,pathlib,sys,yaml
+print(json.dumps({p.name:yaml.load(p.read_text(),Loader=yaml.BaseLoader) for p in pathlib.Path(sys.argv[1]).glob('*.yml')}))
+`, path.resolve(__dirname, '../workflows')], { encoding: 'utf8', timeout: 5000 });
+assert.equal(parsed.status, 0, parsed.stderr);
+const workflows = JSON.parse(parsed.stdout);
+const diagnostic = workflows['keeper-native-diagnostic.yml'];
+const worker = workflows['keeper-native-platform.yml'];
+function enabled(condition, { draft = null, labeled = false, preflightLabeled = false, sameRepo = true, number = 8000, eventName = 'pull_request', diagnostic = false, sameSha = true } = {}) {
+ const expression = condition
+ .replaceAll('github.event_name', 'eventName')
+ .replaceAll('github.event.pull_request.number', 'number')
+ .replaceAll('github.event.pull_request.head.repo.full_name == github.repository', 'sameRepo')
+ .replaceAll('github.event.pull_request.draft', 'draft')
+ .replaceAll("contains(github.event.pull_request.labels.*.name, 'keeper/native-diagnostic')", 'labeled')
+ .replaceAll("contains(github.event.pull_request.labels.*.name, 'keeper/ios-driver-preflight')", 'preflightLabeled')
+ .replaceAll('inputs.source_sha == github.event.pull_request.head.sha', 'sameSha')
+ .replaceAll('inputs.diagnostic', 'diagnostic')
+ .replaceAll('always()', 'true');
+ return new Function('draft', 'labeled', 'preflightLabeled', 'sameRepo', 'number', 'eventName', 'diagnostic', 'sameSha', 'toJSON', `return (${expression});`)(draft, labeled, preflightLabeled, sameRepo, number, eventName, diagnostic, sameSha, JSON.stringify);
+}
+test('candidate diagnostics require explicit same-repository opt-in and serialize platforms', () => {
+ for (const name of ['ios', 'android']) {
+ const condition = diagnostic.jobs[name].if;
+ assert.equal(enabled(condition, { draft: true, labeled: true }), true);
+ for (const override of [{ labeled: false }, { sameRepo: false }, { number: 7045 }]) {
+ assert.equal(enabled(condition, { draft: true, labeled: true, ...override }), false);
+ }
+ }
+ assert.equal(diagnostic.jobs.android.needs, 'ios');
+ assert.equal(diagnostic.concurrency['cancel-in-progress'], 'false');
+ assert.equal(diagnostic.permissions.contents, 'read');
+ assert.equal(diagnostic.permissions['pull-requests'], 'read');
+});
+test('isolated driver label cannot schedule an app platform or overlap full diagnostics', () => {
+ const preflight = diagnostic.jobs['driver-preflight'];
+ for (const [labeled, preflightLabeled, expected] of [
+ [false, false, [false, false, false]],
+ [false, true, [true, false, false]],
+ [true, false, [false, true, true]],
+ [true, true, [false, true, true]],
+ ]) {
+ const actual = ['driver-preflight', 'ios', 'android'].map(name =>
+ enabled(diagnostic.jobs[name].if, { draft: true, labeled, preflightLabeled }));
+ assert.deepEqual(actual, expected, JSON.stringify({ labeled, preflightLabeled }));
+ }
+ for (const override of [{ sameRepo: false }, { number: 7045 }]) {
+ assert.equal(enabled(preflight.if, { preflightLabeled: true, ...override }), false);
+ }
+ assert.equal(preflight['runs-on'], 'macos-15');
+ assert.equal(preflight['timeout-minutes'], '15');
+ assert.equal(preflight.env.KEEPER_NATIVE_PLATFORM, 'IOS');
+ assert.equal(preflight.env.KEEPER_DIAGNOSTIC, 'true');
+ assert.equal(preflight.env.KEEPER_SOURCE_SHA, '${{ github.event.pull_request.head.sha }}');
+ assert.ok(!preflight.uses && !preflight.environment && !preflight.secrets);
+ const checkout = preflight.steps.find(step => step.name === 'Check out exact diagnostic source');
+ assert.equal(checkout.with.ref, '${{ github.event.pull_request.head.sha }}');
+ assert.equal(checkout.with['persist-credentials'], 'false');
+ const commands = preflight.steps.filter(step => step.run).map(step => step.run).join('\n');
+ assert.match(commands, /git rev-parse HEAD/);
+ assert.match(commands, /git diff --exit-code HEAD -- \.github\/native \.github\/workflows/);
+ assert.match(commands, /python3 \.github\/native\/driver_diagnosis\.py/);
+ assert.doesNotMatch(commands, /hosted_native\.py (?:prepare|build|smoke|probe|features)|product_measurements|gradlew|adb|xcodebuild/);
+ const evidence = preflight.steps.find(step => step.name === 'Retain bounded driver diagnosis');
+ assert.equal(evidence.with.path, 'artifacts/native/ios/metadata.json');
+});
+test('preflight live source guard rejects moved source, foreign repository and nonisolated labels', async () => {
+ const step = diagnostic.jobs['driver-preflight'].steps.find(step =>
+ step.name === 'Verify current preflight source and isolated opt-in');
+ const script = new vm.Script(`(async()=>{${step.with.script}})()`);
+ for (const mutation of [null, 'sha', 'labels', 'full-only', 'both-labels', 'repo', 'missing-source']) {
+ const pr = { head: { sha: 'a'.repeat(40), repo: { full_name: 'KeeperCommunity/bitcoin-keeper' } },
+ labels: [{ name: 'keeper/ios-driver-preflight' }] };
+ const env = { KEEPER_SOURCE_SHA: 'a'.repeat(40) };
+ if (mutation === 'sha') pr.head.sha = 'b'.repeat(40);
+ if (mutation === 'labels') pr.labels = [];
+ if (mutation === 'full-only') pr.labels = [{ name: 'keeper/native-diagnostic' }];
+ if (mutation === 'both-labels') pr.labels.push({ name: 'keeper/native-diagnostic' });
+ if (mutation === 'repo') pr.head.repo.full_name = 'fork/bitcoin-keeper';
+ if (mutation === 'missing-source') delete env.KEEPER_SOURCE_SHA;
+ const failures = [];
+ const requests = [];
+ await script.runInNewContext({
+ context: { repo: { owner: 'KeeperCommunity', repo: 'bitcoin-keeper' }, payload: { pull_request: { number: 8000 } } },
+ process: { env },
+ core: { setFailed: message => failures.push(message) },
+ github: { rest: { pulls: { get: async input => { requests.push(input); return { data: pr }; } } } },
+ });
+ assert.equal(failures.length, mutation === null ? 0 : 1, String(mutation));
+ assert.equal(JSON.stringify(requests), JSON.stringify([
+ { owner: 'KeeperCommunity', repo: 'bitcoin-keeper', pull_number: 8000 },
+ ]));
+ }
+});
+test('reusable worker cannot silently run a draft, non-PR or wrong SHA', () => {
+ const condition = worker.jobs.native.if;
+ assert.equal(enabled(condition, { draft: false }), true);
+ assert.equal(enabled(condition, { draft: true, labeled: true, diagnostic: true }), true);
+ for (const override of [{ labeled: false }, { diagnostic: false }, { sameSha: false },
+ { eventName: 'workflow_dispatch' }, { eventName: 'pull_request_target' }]) {
+ assert.equal(enabled(condition, { draft: true, labeled: true, diagnostic: true, ...override }), false);
+ }
+ for (const draft of [null, undefined, '', 'false', 'true', 0, 1, true]) {
+ assert.equal(enabled(condition, { draft }), false);
+ }
+});
+test('current-source recheck denies moved head, removed opt-in and foreign repository', async () => {
+ const step = worker.jobs.native.steps.find(step => step.name === 'Verify current diagnostic source');
+ const script = new vm.Script(`(async()=>{${step.with.script}})()`);
+ for (const mutation of [null, 'sha', 'labels', 'repo']) {
+ const pr = { head: { sha: 'a'.repeat(40), repo: { full_name: 'KeeperCommunity/bitcoin-keeper' } }, labels: [{ name: 'keeper/native-diagnostic' }] };
+ if (mutation === 'sha') pr.head.sha = 'b'.repeat(40);
+ if (mutation === 'labels') pr.labels = [];
+ if (mutation === 'repo') pr.head.repo.full_name = 'fork/bitcoin-keeper';
+ const failures = [];
+ await script.runInNewContext({
+ context: { repo: { owner: 'KeeperCommunity', repo: 'bitcoin-keeper' }, payload: { pull_request: { number: 8000 } } },
+ process: { env: { EXPECTED_SOURCE: 'a'.repeat(40) } },
+ core: { setFailed: message => failures.push(message) },
+ github: { rest: { pulls: { get: async () => ({ data: pr }) } } },
+ });
+ assert.equal(failures.length, mutation === null ? 0 : 1, String(mutation));
+ }
+});
+test('diagnostic workflow identity is rejected by the trusted release evidence verifier', async () => {
+ const { evidence } = require('../native/release_evidence.cjs');
+ const sha = 'a'.repeat(40);
+ const repository = 'KeeperCommunity/bitcoin-keeper';
+ const result = await evidence({
+ rest: { actions: { listWorkflowRuns: 'runs' } },
+ paginate: async () => [{ id: 12, run_attempt: 1, path: '.github/workflows/keeper-native-diagnostic.yml' }],
+ }, { repo: { owner: 'KeeperCommunity', repo: 'bitcoin-keeper' }, eventName: 'pull_request', runId: 12,
+ payload: { pull_request: { number: 8000, head: { sha, repo: { id: 1, full_name: repository } },
+ base: { ref: 'sprint', repo: { id: 1, full_name: repository } } } } },
+ { ios: 'success', android: 'success', attempt: 1 });
+ assert.equal(result, false);
+ assert.ok(!diagnostic.jobs.acceptance);
+ for (const source of [diagnostic, worker]) {
+ assert.ok(!source.environment && !source.secrets);
+ assert.ok(Object.values(source.permissions).every(value => value === 'read'));
+ }
+});
diff --git a/.github/tests/native-draft-policy.test.cjs b/.github/tests/native-draft-policy.test.cjs
new file mode 100644
index 0000000000..10f2212aec
--- /dev/null
+++ b/.github/tests/native-draft-policy.test.cjs
@@ -0,0 +1,240 @@
+'use strict';
+
+const assert = require('node:assert/strict');
+const fs = require('node:fs');
+const path = require('node:path');
+const { spawnSync } = require('node:child_process');
+const test = require('node:test');
+
+const directory = path.resolve(__dirname, '../workflows');
+// BaseLoader keeps YAML's `on` key and scalar text intact for these policy
+// checks. Parsing failure is fatal; this is not workflow semantic lint.
+const parsed = spawnSync('python3', ['-B', '-c', `
+import json, pathlib, sys, yaml
+print(json.dumps({p.name: yaml.load(p.read_text(), Loader=yaml.BaseLoader)
+ for p in pathlib.Path(sys.argv[1]).glob('*.yml')}))
+`, directory], { encoding: 'utf8', timeout: 5000 });
+assert.equal(parsed.status, 0, parsed.stderr || parsed.error?.message);
+const workflows = JSON.parse(parsed.stdout);
+const native = workflows['keeper-hosted-native.yml'];
+const ci = workflows['test.yml'];
+const guard = "github.event_name == 'pull_request' && toJSON(github.event.pull_request.draft) == 'false'";
+
+// Evaluate the actual checked-in expressions using only their two context
+// paths and toJSON. Missing context is null, as in Actions. These conditions
+// compare strings only, so JavaScript and Actions equality give the same result.
+function allowed(condition, eventName, draft = null, legacy = true) {
+ assert.equal(typeof condition, 'string', 'an explicit condition is required');
+ const expression = condition
+ .replaceAll("contains(github.event.pull_request.labels.*.name, 'keeper/legacy-native')", 'legacy')
+ .replaceAll("contains(github.event.pull_request.labels.*.name, 'keeper/native-diagnostic')", 'false')
+ .replaceAll('always()', 'true')
+ .replaceAll('github.event_name', 'eventName')
+ .replaceAll('github.event.pull_request.draft', 'draft');
+ return Boolean(new Function('eventName', 'draft', 'legacy', 'toJSON', `return (${expression});`)(
+ eventName, draft, legacy, JSON.stringify));
+}
+
+function triggered(workflow, event, action, branch) {
+ const config = workflow.on[event];
+ if (config === undefined) return false;
+ if (config.branches && !config.branches.includes(branch)) return false;
+ const types = config.types || (event === 'pull_request' ? ['opened', 'synchronize', 'reopened'] : null);
+ return !types || types.includes(action);
+}
+
+test('native opened, synchronize and reopened draft jobs are skipped before runner allocation', () => {
+ assert.deepEqual(Object.keys(native.jobs), ['ios', 'android']);
+ for (const action of ['opened', 'synchronize', 'reopened']) {
+ assert.ok(triggered(native, 'pull_request', action, 'sprint'));
+ for (const job of Object.values(native.jobs)) {
+ assert.ok(job.if.includes(guard));
+ assert.equal(allowed(job.if, 'pull_request', false, false), false, 'legacy lane needs explicit label');
+ assert.equal(allowed(job.if, 'pull_request', true), false, action);
+ assert.equal(allowed(job.if, 'pull_request', false), true, action);
+ }
+ }
+});
+
+test('ready-for-review schedules native work and normal Tests; conversion back to draft skips native work', () => {
+ assert.ok(triggered(native, 'pull_request', 'ready_for_review', 'sprint'));
+ assert.ok(triggered(ci, 'pull_request', 'ready_for_review', 'sprint'));
+ assert.ok(triggered(native, 'pull_request', 'converted_to_draft', 'sprint'));
+ for (const job of Object.values(native.jobs)) {
+ assert.equal(allowed(job.if, 'pull_request', false), true);
+ assert.equal(allowed(job.if, 'pull_request', true), false);
+ }
+ assert.equal(native.concurrency.group, 'keeper-hosted-native-${{ github.event.pull_request.number }}');
+ assert.equal(native.concurrency['cancel-in-progress'], 'true');
+});
+
+test('native non-PR and missing or malformed draft contexts fail closed', () => {
+ assert.deepEqual(Object.keys(native.on), ['pull_request']);
+ for (const job of Object.values(native.jobs)) {
+ for (const event of ['push', 'workflow_dispatch', 'workflow_call', 'workflow_run', 'schedule', 'pull_request_target']) {
+ assert.equal(allowed(job.if, event, false), false, event);
+ }
+ for (const draft of [null, '', 'false', 'true', 0, 1]) {
+ assert.equal(allowed(job.if, 'pull_request', draft), false, JSON.stringify(draft));
+ }
+ }
+});
+
+test('reusable paths keep explicit draft and diagnostic boundaries with no dispatch', () => {
+ const worker = workflows['keeper-native-platform.yml'];
+ const acceptance = workflows['keeper-release-acceptance.yml'];
+ const diagnostic = workflows['keeper-native-diagnostic.yml'];
+ assert.deepEqual(Object.keys(worker.on), ['workflow_call']);
+ assert.equal(worker.on.workflow_call.inputs.diagnostic.default, 'false');
+ assert.match(worker.jobs.native.if, /toJSON\(github.event.pull_request.draft\) == 'false'/);
+ assert.match(worker.jobs.native.if, /inputs.diagnostic && contains/);
+ for (const platform of ['ios', 'android']) {
+ assert.match(acceptance.jobs[platform].if, /toJSON\(github.event.pull_request.draft\) == 'false'/);
+ assert.equal(diagnostic.jobs[platform].with.diagnostic, 'true');
+ assert.match(diagnostic.jobs[platform].if, /keeper\/native-diagnostic/);
+ }
+ assert.deepEqual(acceptance.jobs.android.needs, ['provenance', 'ios']);
+ assert.equal(diagnostic.jobs.android.needs, 'ios');
+ assert.equal(diagnostic.concurrency['cancel-in-progress'], 'false');
+ for (const filename of ['keeper-hosted-native.yml', 'keeper-native-platform.yml',
+ 'keeper-release-acceptance.yml', 'keeper-native-diagnostic.yml']) {
+ assert.ok(!Object.hasOwn(workflows[filename].on, 'workflow_dispatch'), filename);
+ }
+ assert.equal(workflows['android-diagnostic-build.yml'].jobs.build.if, "github.event_name == 'workflow_dispatch'");
+ assert.equal(workflows['android-diagnostic-build.yml'].concurrency['cancel-in-progress'], 'false');
+});
+
+test('pushing an isolated branch permits only the read-only origin contract workflow', () => {
+ const triggeredFiles = Object.entries(workflows).filter(([, workflow]) =>
+ triggered(workflow, 'push', null, 'codex/cloud-bootstrap-privacy')).map(([filename]) => filename);
+ assert.deepEqual(triggeredFiles, ['keeper-release-origin-contracts.yml']);
+ const workflow = workflows['keeper-release-origin-contracts.yml'];
+ assert.deepEqual(workflow.permissions, { contents: 'read' });
+ assert.equal(workflow.on.pull_request_target, undefined);
+ assert.equal(workflow.concurrency['cancel-in-progress'], 'false');
+ const job = workflow.jobs.contracts;
+ assert.equal(job.environment, undefined);
+ assert.equal(job.secrets, undefined);
+ assert.equal(job.steps.some(step => /secrets\.|workflow_dispatch/.test(JSON.stringify(step))), false);
+ assert.deepEqual(job.steps.filter(step => step.run).map(step => step.run), [
+ 'node --test scripts/trusted-release-origin.test.cjs scripts/codeql-analysis-receipt.test.cjs scripts/protected-release-plan.test.cjs',
+ ]);
+});
+
+test('draft opening and updates retain the expected host checks without a release trigger', () => {
+ for (const action of ['opened', 'synchronize', 'reopened']) {
+ const triggeredFiles = Object.entries(workflows).filter(([, workflow]) =>
+ triggered(workflow, 'pull_request', action, 'sprint')).map(([filename]) => filename).sort();
+ const expected = [
+ 'android-diagnostic-build.yml', 'codeql.yml', 'keeper-canonical-native-contracts.yml', 'keeper-hosted-native.yml',
+ 'keeper-release-acceptance.yml', 'keeper-release-origin-contracts.yml',
+ 'keeper-release-preparation-contracts.yml', 'keeper-ruby-lock-contracts.yml',
+ 'keeper-validation-tests.yml', 'public-backend.yml', 'test.yml',
+ ];
+ if (action === 'synchronize' || action === 'reopened') expected.push('keeper-native-diagnostic.yml');
+ assert.deepEqual(triggeredFiles, expected.sort());
+ assert.ok(triggered(workflows['keeper-local-validation.yml'], 'pull_request_target', action, 'sprint'));
+ }
+});
+
+test('canonical provenance contracts stay read-only and separate from manual native execution', () => {
+ const contracts = workflows['keeper-canonical-native-contracts.yml'];
+ assert.deepEqual(Object.keys(contracts.on), ['pull_request']);
+ assert.deepEqual(contracts.permissions, { contents: 'read' });
+ assert.equal(contracts.concurrency, undefined);
+ const job = contracts.jobs.contracts;
+ assert.equal(job.environment, undefined);
+ assert.equal(job.secrets, undefined);
+ assert.equal(job['timeout-minutes'], '5');
+ assert.equal(job.steps.find(step => step.with?.['node-version']).with['node-version'], '22.23.3');
+ assert.deepEqual(job.steps.filter(step => step.run).map(step => step.name),
+ ['Test read-only canonical trust and archive controls']);
+ const native = workflows['keeper-canonical-native.yml'];
+ assert.deepEqual(Object.keys(native.on), ['workflow_dispatch']);
+ assert.equal(triggered(native, 'pull_request', 'opened', 'sprint'), false);
+ assert.equal(triggered(native, 'push', null, 'sprint'), false);
+});
+
+test('canonical pin credential stays in explicit provenance steps with read-only workflow permissions', () => {
+ const caller = workflows['keeper-canonical-native.yml'];
+ const worker = workflows['keeper-canonical-native-platform.yml'];
+ for (const workflow of [caller, worker]) {
+ assert.deepEqual(workflow.permissions, { contents: 'read', actions: 'read', checks: 'read' });
+ assert.equal(workflow.env?.KEEPER_CANONICAL_PIN_READ_TOKEN, undefined);
+ for (const job of Object.values(workflow.jobs)) {
+ assert.equal(job.environment, undefined);
+ assert.equal(job.env?.KEEPER_CANONICAL_PIN_READ_TOKEN, undefined);
+ for (const step of job.steps || []) {
+ if (step.env?.KEEPER_CANONICAL_PIN_READ_TOKEN) {
+ assert.match(step.uses, /^actions\/github-script@[a-f0-9]{40}$/);
+ assert.equal(step.with['github-token'], undefined, 'Actions/check APIs keep the normal workflow identity');
+ assert.match(step.with.script, /pinReaderFromEnvironment\(github, process.env\)/);
+ assert.match(step.with.script, /(?:admission: true, pinReader|\{ pinReader \})/);
+ } else {
+ assert.doesNotMatch(JSON.stringify(step), /secrets\./, 'build/tooling steps receive no pin credential');
+ }
+ }
+ }
+ }
+ assert.deepEqual(Object.keys(worker.on.workflow_call.secrets), ['canonical_pin_read_token']);
+ assert.equal(worker.on.workflow_call.secrets.canonical_pin_read_token.required, 'true');
+ for (const platform of ['ios', 'android']) {
+ assert.deepEqual(caller.jobs[platform].secrets, {
+ canonical_pin_read_token: '${{ secrets.KEEPER_CANONICAL_PIN_READ_TOKEN }}',
+ });
+ }
+ assert.deepEqual(caller.jobs.provenance.steps.find(step => step.id === 'check').env, {
+ KEEPER_CANONICAL_PIN_READ_TOKEN: '${{ secrets.KEEPER_CANONICAL_PIN_READ_TOKEN }}',
+ });
+ assert.equal(caller.jobs.attestation.steps.find(step => step.name === 'Verify canonical receipts and required matrix')
+ .env.KEEPER_CANONICAL_PIN_READ_TOKEN, '${{ secrets.KEEPER_CANONICAL_PIN_READ_TOKEN }}');
+ const checks = worker.jobs.native.steps.filter(step => step.env?.KEEPER_CANONICAL_PIN_READ_TOKEN);
+ assert.equal(checks.length, 1);
+ assert.equal(checks[0].env.KEEPER_CANONICAL_PIN_READ_TOKEN, '${{ secrets.canonical_pin_read_token }}');
+ assert.equal(checks[0].name, 'Verify canonical installed source');
+});
+
+test('release preparation PR checks stay offline and separate from the protected manual plan', () => {
+ const contracts = workflows['keeper-release-preparation-contracts.yml'];
+ assert.deepEqual(contracts.permissions, { contents: 'read' });
+ assert.equal(contracts.on.pull_request_target, undefined);
+ assert.equal(contracts.concurrency['cancel-in-progress'], 'false');
+ const job = contracts.jobs.contracts;
+ assert.equal(job.environment, undefined);
+ assert.equal(job.secrets, undefined);
+ assert.equal(job.steps.filter(step => step.run).length, 1);
+ assert.match(job.steps.find(step => step.run).run, /node --test scripts\/protected-release-plan\.test\.cjs/);
+ const plan = workflows['keeper-protected-release-plan.yml'];
+ assert.deepEqual(Object.keys(plan.on), ['workflow_dispatch']);
+ assert.equal(triggered(plan, 'pull_request', 'opened', 'sprint'), false);
+ assert.equal(triggered(plan, 'push', null, 'sprint'), false);
+});
+
+test('all Tests installs preserve current immutable script-disabled R4 setup and patches', () => {
+ const steps = ci.jobs.test.steps;
+ const install = steps.find(step => step.name === 'Install dependencies');
+ assert.match(install.run, /yarn install --frozen-lockfile --ignore-scripts --non-interactive/);
+ assert.equal(install.if, undefined);
+ assert.equal(steps.find(step => step.name === 'Apply repository dependency patches').run,
+ 'node_modules/.bin/patch-package --error-on-fail');
+ assert.match(steps.find(step => step.name === 'Verify dependency inputs remain unchanged').run,
+ /git diff --exit-code HEAD/);
+ assert.ok(!ci.jobs.test.if && !ci.jobs.test['continue-on-error']);
+ for (const step of steps) assert.ok(!step['continue-on-error']);
+ assert.equal(steps.find(step => step.name === 'Run tests').run, 'npm run test');
+});
+
+test('standalone native contracts install a locked isolated compiler without app lifecycle hooks', () => {
+ const job = workflows['keeper-validation-tests.yml'].jobs.contracts;
+ const install = job.steps.find(step => step.name === 'Install isolated locked contract tools without lifecycle scripts');
+ assert.match(install.run, /npm ci --prefix \.github\/native\/contract-tools --ignore-scripts --no-audit --no-fund/);
+ assert.match(install.run, /NODE_PATH=/);
+ assert.equal(job.environment, undefined);
+ assert.equal(job.secrets, undefined);
+ const compiler = require('../native/contract-tools/package.json');
+ const app = require('../../package.json');
+ assert.equal(compiler.dependencies.typescript, app.devDependencies.typescript);
+ const lock = require('../native/contract-tools/package-lock.json');
+ assert.equal(lock.packages['node_modules/typescript'].version, app.devDependencies.typescript);
+ assert.match(lock.packages['node_modules/typescript'].integrity, /^sha512-/);
+});
diff --git a/.github/tests/nodeify.test.cjs b/.github/tests/nodeify.test.cjs
new file mode 100644
index 0000000000..400c365346
--- /dev/null
+++ b/.github/tests/nodeify.test.cjs
@@ -0,0 +1,38 @@
+'use strict';
+
+const assert = require('node:assert/strict');
+const fs = require('node:fs');
+const os = require('node:os');
+const path = require('node:path');
+const { spawnSync } = require('node:child_process');
+const test = require('node:test');
+
+const wrapper = path.resolve(__dirname, '../native/nodeify.cjs');
+
+test('native shim preparation filters upstream defaults without requesting installation', t => {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'keeper-nodeify-'));
+ t.after(() => fs.rmSync(root, { recursive: true, force: true }));
+ const upstream = path.join(root, 'node_modules/rn-nodeify');
+ fs.mkdirSync(upstream, { recursive: true });
+ fs.writeFileSync(path.join(upstream, 'coreList.js'), "module.exports = ['constants', 'fs', 'net'];\n");
+ fs.writeFileSync(path.join(upstream, 'cmd.js'), `
+ process.stdout.write(JSON.stringify({
+ shims: require('./coreList'), arguments: process.argv.slice(2)
+ }));
+ `);
+ const result = spawnSync(process.execPath, ['-e',
+ 'require(process.argv[1]).runNodeify(process.cwd())', wrapper], { cwd: root, encoding: 'utf8' });
+ assert.equal(result.status, 0, result.stderr);
+ const output = JSON.parse(result.stdout);
+ assert.deepEqual(output.arguments, ['--hack']);
+ assert.deepEqual(output.shims, [
+ 'buffer', 'events', 'process', 'stream', 'inherits', 'path', 'assert', 'crypto',
+ ]);
+ assert.ok(!output.shims.includes('constants'));
+});
+
+test('native shim preparation rejects an unrelated working directory', () => {
+ const { runNodeify } = require(wrapper);
+ assert.throws(() => runNodeify(path.join(os.tmpdir(), 'unrelated-keeper-checkout')),
+ /repository root/);
+});
diff --git a/.github/tests/product-pin-metric.test.cjs b/.github/tests/product-pin-metric.test.cjs
new file mode 100644
index 0000000000..18cf109ac2
--- /dev/null
+++ b/.github/tests/product-pin-metric.test.cjs
@@ -0,0 +1,48 @@
+/* Host marker script controls only; these tests grant no native acceptance. */
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const fs = require('node:fs');
+const path = require('node:path');
+const vm = require('node:vm');
+const source = fs.readFileSync(path.join(__dirname, '../native/product_pin_metric.js'), 'utf8');
+const markers = [
+ 'confirm_passcode_visible', 'confirmation_digits_tapped', 'create_tapped',
+ 'continue_visible', 'continue_tapped', 'cancel_visible', 'cancel_tapped',
+ 'skip_visible', 'skip_tapped', 'start_new_visible',
+];
+
+function observe(marker, post = () => ({ status: 200 })) {
+ const calls = [];
+ const context = {
+ http: { post(url, options) { calls.push({ url, options }); return post(); } },
+ console: new Proxy({}, { get() { throw new Error('Logging is forbidden'); } }),
+ };
+ if (marker !== undefined) context.MARKER = marker;
+ vm.runInNewContext(source, context);
+ return calls;
+}
+
+test('every fixed marker sends exactly one field to the fixed loopback host', () => {
+ for (const marker of markers) {
+ const calls = observe(marker);
+ assert.equal(calls.length, 1);
+ assert.equal(calls[0].url, 'http://127.0.0.1:8765/pin-progress');
+ assert.deepEqual(JSON.parse(calls[0].options.body), { marker });
+ assert.equal(calls[0].options.headers['Content-Type'], 'application/json');
+ assert.deepEqual(Object.keys(calls[0].options).sort(), ['body', 'headers']);
+ }
+});
+
+test('unknown or non-string marker values never leave the script', () => {
+ for (const marker of [undefined, null, true, 1111, 'DO_NOT_RETAIN',
+ { toString() { throw new Error('DO_NOT_RETAIN'); } }, ['confirm_passcode_visible']]) {
+ assert.deepEqual(observe(marker), []);
+ }
+});
+
+test('transport errors and rejected progress do not become new UI acceptance conditions', () => {
+ assert.equal(observe(markers[0], () => { throw new Error('DO_NOT_RETAIN'); }).length, 1);
+ for (const reply of [{ status: 422, body: 'DO_NOT_RETAIN' }, undefined]) {
+ assert.equal(observe(markers[0], () => reply).length, 1);
+ }
+});
diff --git a/.github/tests/public-companion-receipts.test.cjs b/.github/tests/public-companion-receipts.test.cjs
new file mode 100644
index 0000000000..ea8766609f
--- /dev/null
+++ b/.github/tests/public-companion-receipts.test.cjs
@@ -0,0 +1,94 @@
+'use strict';
+const { test } = require('node:test');
+const assert = require('node:assert/strict');
+const { SCOPES, publicCompanionChecks, validatePublicCompanions } = require('../native/public_companion_receipts.cjs');
+const { attach } = require('./fixtures/public-companions.cjs');
+const slots = [
+ ['controlled-credential-json-ui', 'product_credential_ui', 'credential_errors_ui'],
+ ['controlled-version-history-ui', 'product_version_history_ui', 'version_history_ui'],
+ ['vault-reference-and-logical-archive-ui', 'product_vault_ui', 'vault_references_ui'],
+];
+for (const platform of ['IOS', 'ANDROID']) {
+ test(`${platform} actual producer schemas remain narrowly scoped`, () => {
+ const value = attach({}, platform);
+ assert.deepEqual(Object.keys(validatePublicCompanions(value, platform)), Object.keys(SCOPES));
+ assert.equal(value.product_credential_ui.os_keychain_denial_or_hardware_read_fault, 'NOT RUN');
+ assert.equal(value.product_version_history_ui.performance_sample, false);
+ assert.equal(value.product_vault_ui.native_private_material_exactness, 'NOT DIRECTLY INSPECTED BY UI');
+ assert.equal(value.product_vault_ui.protected_backup, 'DISABLED_FOR_DISPOSABLE_FIXTURE');
+ });
+ for (const [id, root, nested] of slots) {
+ for (const location of ['root', 'nested']) {
+ for (const [name, mutate] of [
+ ['missing result', (row, value) => location === 'root' ? delete value[root] : delete value.product_ui[nested]],
+ ['partial stage list', row => row.completed_stages.pop()],
+ ['duplicate stage', row => row.completed_stages[1] = row.completed_stages[0]],
+ ['out-of-order stage', row => row.completed_stages.reverse()],
+ ['running result', row => row.status = 'RUNNING'],
+ ['failed cleanup with stale PASS', row => row.cleanup = 'FAILED'],
+ ['unscoped arbitrary fields', row => row.raw = 'PRIVATE_SENTINEL'],
+ ['foreign nested SHA', row => row.source_sha = 'b'.repeat(40)],
+ ['foreign nested attempt', row => row.run_attempt = '99'],
+ ['missing installed proof', row => delete row.installed_artifact],
+ ['truthy proof', row => row.installed_artifact_verified = 'true'],
+ ['different byte inventory', row => row.installed_artifact[platform === 'IOS' ? 'inventory_sha256' : 'sha256'] = '1'.repeat(64)],
+ ['different executable', row => row.installed_artifact[platform === 'IOS' ? 'executable_sha256' : 'sha256'] = '2'.repeat(64)],
+ ]) test(`${platform} ${root} ${location} rejects ${name}`, () => {
+ const value = attach({}, platform), row = location === 'root' ? value[root] : value.product_ui[nested];
+ mutate(row, value);
+ const checks = publicCompanionChecks(value, platform);
+ assert.equal(checks[id].status, 'NOT VERIFIED');
+ for (const [other] of slots.filter(([other]) => other !== id)) assert.equal(checks[other].status, 'PASS');
+ assert.throws(() => validatePublicCompanions(value, platform), /PUBLIC_COMPANION_RECEIPT_INCOMPLETE/);
+ assert.equal(JSON.stringify(checks).includes('PRIVATE_SENTINEL'), false);
+ });
+ }
+ }
+ for (let index = 0; index < 12; index++) {
+ test(`${platform} every history phase ${index + 1} requires its own matching installed proof`, () => {
+ const value = attach({}, platform);
+ value.product_version_history_ui.stage_evidence[index].installed_artifact_verified = false;
+ assert.equal(publicCompanionChecks(value, platform)['controlled-version-history-ui'].status, 'NOT VERIFIED');
+ value.product_version_history_ui.stage_evidence[index].installed_artifact_verified = true;
+ value.product_ui.version_history_ui.stage_evidence[index].installed_artifact[platform === 'IOS' ? 'inventory_sha256' : 'sha256'] = '3'.repeat(64);
+ assert.throws(() => validatePublicCompanions(value, platform));
+ });
+ }
+ for (const [name, mutate] of [
+ ['missing byte root', value => delete value.installed_artifact],
+ ['different built binary', value => value.built_artifact[platform === 'IOS' ? 'executable_sha256' : 'sha256'] = '0'.repeat(64)],
+ ['missing final normal product restoration', value => value.product_ui.companion_metro_switches.pop()],
+ ['failed bundle transition', value => value.product_ui.companion_metro_switches[1].status = 'FAIL'],
+ ['unreviewed transition scope', value => value.product_ui.companion_metro_switches[0].scope = 'APP_ACCEPTANCE'],
+ ['failed overall product', value => value.product_ui.status = 'FAIL'],
+ ]) test(`${platform} root context rejects ${name}`, () => {
+ const value = attach({}, platform); mutate(value);
+ assert.ok(Object.values(publicCompanionChecks(value, platform)).every(row => row.status === 'NOT VERIFIED'));
+ assert.throws(() => validatePublicCompanions(value, platform));
+ });
+ for (const phase of ['build', 'smoke', 'native_probe', 'r5_features']) {
+ for (const state of ['FAIL', 'NOT RUN', 'RUNNING', undefined]) {
+ test(`${platform} ${phase} ${state ?? 'missing'} cannot support companion PASS`, () => {
+ const value = attach({}, platform);
+ if (state === undefined) delete value[phase]; else value[phase] = state;
+ assert.ok(Object.values(publicCompanionChecks(value, platform)).every(row => row.status === 'NOT VERIFIED'));
+ assert.throws(() => validatePublicCompanions(value, platform));
+ });
+ }
+ }
+ for (const [name, mutate] of [
+ ['OS denial promoted from JSON', value => value.product_credential_ui.os_keychain_denial_or_hardware_read_fault = 'PASS'],
+ ['credential service not removed', value => value.product_credential_ui.backup_service_removed_after_verified_restore = false],
+ ['empty credential treated as read failure', value => value.product_credential_ui.successfully_empty_store = 'PASS'],
+ ['history not restored', value => value.product_version_history_ui.original_history_restored = false],
+ ['history duplicate observation', value => value.product_version_history_ui.stale_current_observation_count = 2],
+ ['history parent account changed', value => value.product_version_history_ui.account_version_unchanged = false],
+ ['secret bytes falsely inspected', value => value.product_vault_ui.native_private_material_exactness = 'PASS'],
+ ['backup falsely enabled', value => value.product_vault_ui.protected_backup = 'PASS'],
+ ['physical acceptance fabricated', value => value.product_vault_ui.physical_biometrics = 'PASS'],
+ ['unrelated wallet lost', value => value.product_vault_ui.final_visible_wallet_count = 2],
+ ]) test(`${platform} does not enlarge scoped evidence: ${name}`, () => {
+ const value = attach({}, platform); mutate(value);
+ assert.throws(() => validatePublicCompanions(value, platform));
+ });
+}
diff --git a/.github/tests/r5_features.test.cjs b/.github/tests/r5_features.test.cjs
new file mode 100644
index 0000000000..169e5ebd6c
--- /dev/null
+++ b/.github/tests/r5_features.test.cjs
@@ -0,0 +1,140 @@
+// Host-only contract checks. They do not execute a native Realm or grant app acceptance.
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const fs = require('node:fs');
+const os = require('node:os');
+const path = require('node:path');
+const vm = require('node:vm');
+const ts = require('typescript');
+const { extract, prepare, SELECTION } = require('../native/r5_prepare.cjs');
+const {
+ recordBuilder,
+ runFeatures,
+ FeatureFailure,
+ SCENARIOS,
+ LIMITS,
+} = require('../native/r5_features_core');
+const root = path.resolve(__dirname, '../..');
+
+test('build-time probe extracts every selected production definition and records its source hash', () => {
+ const provenance = prepare();
+ assert.equal(provenance.length, Object.keys(SELECTION).length);
+ for (const item of provenance) {
+ assert.match(item.sha256, /^[a-f0-9]{64}$/);
+ assert.deepEqual(item.names, SELECTION[item.path]);
+ }
+ const generated = require('../native/.generated/r5_workers');
+ const workers = generated.createWorkers({});
+ for (const name of [
+ 'setupKeeperAppWorker',
+ 'deleteSigningDeviceWorker',
+ 'deleteAppImageEntityWorker',
+ 'getKeyUID',
+ 'observeBackupAccount',
+ 'currentBackupAccountSession',
+ ])
+ assert.equal(typeof workers[name], 'function');
+ assert.deepEqual(generated.provenance, provenance);
+});
+
+test('missing or duplicate production definitions fail closed rather than execute a substitute', () => {
+ const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'keeper-r5-extraction-'));
+ try {
+ const file = path.join(directory, 'source.ts');
+ fs.writeFileSync(file, 'export const retained = () => 1;');
+ assert.throws(() => extract(file, ['missing']), /selection changed/);
+ fs.writeFileSync(file, 'function retained(){}; function retained(){};');
+ assert.throws(() => extract(file, ['retained']), /Duplicate/);
+ } finally {
+ fs.rmSync(directory, { recursive: true });
+ }
+});
+
+test('actual production session observer invalidates an A to B to A worker scope', () => {
+ prepare();
+ const { createWorkers } = require('../native/.generated/r5_workers');
+ const workers = createWorkers({});
+ workers.observeBackupAccount('A');
+ const first = workers.currentBackupAccountSession();
+ workers.observeBackupAccount('A');
+ assert.equal(workers.currentBackupAccountSession(), first);
+ workers.observeBackupAccount('B');
+ workers.observeBackupAccount('A');
+ assert.ok(workers.currentBackupAccountSession() > first);
+});
+
+test('native fixture builder uses actual current schemas, required linked objects and sentinel-only inputs', () => {
+ const cache = new Map();
+ function load(relative) {
+ let file = path.resolve(root, relative);
+ if (fs.existsSync(file) && fs.statSync(file).isDirectory()) file = path.join(file, 'index.ts');
+ else if (!fs.existsSync(file)) file = `${file}.ts`;
+ if (cache.has(file)) return cache.get(file).exports;
+ const module = { exports: {} };
+ cache.set(file, module);
+ const source = fs.readFileSync(file, 'utf8');
+ const javascript = ts.transpileModule(source, {
+ compilerOptions: {
+ target: ts.ScriptTarget.ES2020,
+ module: ts.ModuleKind.CommonJS,
+ },
+ }).outputText;
+ vm.runInNewContext(
+ javascript,
+ {
+ exports: module.exports,
+ module,
+ Date,
+ require(name) {
+ if (name.startsWith('src/')) return load(name);
+ if (name.startsWith('.'))
+ return load(path.relative(root, path.resolve(path.dirname(file), name)));
+ throw new Error(`Unexpected schema import ${name}`);
+ },
+ },
+ { filename: file }
+ );
+ return module.exports;
+ }
+ const schema = load('src/storage/realm/schema').default;
+ const make = recordBuilder(schema);
+ const wallet = make('Wallet');
+ assert.equal(wallet.specs.xpub, '');
+ assert.equal(wallet.specs.balances.confirmed, 0);
+ assert.deepEqual(wallet.specs.transactions, []);
+ assert.equal(make('Vault').archived, false);
+ assert.equal(make('KeeperApp').subscription.level, 0);
+ assert.equal(make('Signer').lastHealthCheck.valueOf(), 0);
+ assert.throws(() => make('Missing'), /schema-missing/);
+});
+
+test('invalid persistent process state fails before opening any native database', async () => {
+ let opened = false;
+ const Realm = {
+ defaultPath: '/disposable/default.realm',
+ open() {
+ opened = true;
+ },
+ };
+ for (const serialized of [
+ 'broken',
+ '{"iteration":6,"measurements":[]}',
+ '{"iteration":1,"measurements":[]}',
+ ]) {
+ await assert.rejects(
+ runFeatures({ Realm, schema: [], storage: { getString: () => serialized } }),
+ (error) => error instanceof FeatureFailure && error.code === 'invalid-phase'
+ );
+ }
+ assert.equal(opened, false);
+});
+
+test('probe reports a bounded worker scope and cannot imply product startup, UI or backend coverage', () => {
+ assert.equal(SCENARIOS.length, 5);
+ assert.ok(SCENARIOS.every((id) => /^(production-|native-worker-)/.test(id)));
+ assert.ok(LIMITS.includes('no-product-ui-navigation-pin-or-biometric-acceptance'));
+ assert.ok(LIMITS.includes('probe-and-worker-timings-not-product-startup-ux'));
+ const entry = fs.readFileSync(path.join(root, '.github/native/r5_features.js'), 'utf8');
+ assert.ok(entry.includes('production-worker-native-storage'));
+ assert.ok(!/from ['"].*(?:App|store\/store|services\/backend)/.test(entry));
+});
diff --git a/.github/tests/release-evidence.test.cjs b/.github/tests/release-evidence.test.cjs
new file mode 100644
index 0000000000..fd818601f0
--- /dev/null
+++ b/.github/tests/release-evidence.test.cjs
@@ -0,0 +1,61 @@
+const assert = require('node:assert/strict');
+const { test } = require('node:test');
+const { evidence } = require('../native/release_evidence.cjs');
+function fixture() {
+ const repository = 'KeeperCommunity/bitcoin-keeper';
+ const pr = { number: 7058, head: { sha: 'a'.repeat(40), ref: 'future-release',
+ repo: { full_name: repository, id: 1 } }, base: { sha: 'b'.repeat(40), ref: 'sprint',
+ repo: { full_name: repository, id: 1 } } };
+ const context = { repo: { owner: 'KeeperCommunity', repo: 'bitcoin-keeper' },
+ eventName: 'pull_request', runId: 90, payload: { pull_request: pr } };
+ const run = { id: 90, run_attempt: 2, path: '.github/workflows/keeper-release-acceptance.yml',
+ event: 'pull_request', head_sha: pr.head.sha, head_branch: pr.head.ref,
+ head_repository: pr.head.repo, pull_requests: [structuredClone(pr)], status: 'in_progress' };
+ const jobs = ['IOS', 'ANDROID'].map(platform => ({
+ name: `${platform.toLowerCase()} / Native ${platform} build and probes`, head_sha: pr.head.sha,
+ run_id: 90, run_attempt: 2, status: 'completed', conclusion: 'success',
+ steps: ['Build development app', ...(platform === 'IOS'
+ ? ['Run disposable startup smoke', 'Run disposable native persistence probe']
+ : ['Run Android startup and native persistence probes'])].map(name =>
+ ({ name, status: 'completed', conclusion: 'success' })),
+ }));
+ const state = { runs: [run], jobs, context, input: { ios: 'success', android: 'success', attempt: 2 }, calls: [] };
+ const runsAPI = () => {}; const jobsAPI = () => {};
+ state.github = { rest: { actions: { listWorkflowRuns: runsAPI, listJobsForWorkflowRunAttempt: jobsAPI } },
+ paginate: async (api, args) => { state.calls.push(args); if (state.error) throw new Error('private');
+ return api === runsAPI ? [...state.runs] : state.jobs; } };
+ state.check = () => evidence(state.github, state.context, state.input);
+ return state;
+}
+test('current in-progress summary credits both completed exact-attempt native jobs only', async () => {
+ const state = fixture(); assert.equal(await state.check(), true);
+ assert.equal(state.calls[1].attempt_number, 2);
+ assert.equal(state.calls[0].head_sha, state.context.payload.pull_request.head.sha);
+});
+test('latest run and attempt prevent summary-only partial reruns and older-run reuse', async () => {
+ for (const mutate of [s => { s.jobs.pop(); }, s => { s.jobs[0].run_attempt = 1; },
+ s => { s.runs[0].run_attempt = 3; }, s => { s.runs.push({ ...s.runs[0], id: 91 }); }]) {
+ const state = fixture(); mutate(state); assert.equal(await state.check(), false);
+ }
+});
+test('wrong source, workflow, event, PR association and repository provide no evidence', async () => {
+ for (const mutate of [s => { s.runs[0].head_sha = 'c'.repeat(40); },
+ s => { s.runs[0].path = 'other.yml'; }, s => { s.runs[0].event = 'push'; },
+ s => { s.runs[0].head_branch = 'other'; }, s => { s.runs[0].head_repository = { id: 9 }; },
+ s => { s.runs[0].pull_requests[0].number += 1; },
+ s => { s.runs[0].pull_requests[0].base.sha = 'c'.repeat(40); }]) {
+ const state = fixture(); mutate(state); assert.equal(await state.check(), false);
+ }
+});
+test('failed/skipped/pending jobs, build-only results and ambiguous steps cannot pass', async () => {
+ for (const mutate of [s => { s.jobs[0].conclusion = 'failure'; },
+ s => { s.jobs[1].status = 'in_progress'; }, s => { s.jobs[0].steps.pop(); },
+ s => { s.jobs[1].steps[1].conclusion = 'skipped'; }, s => { s.jobs.push(s.jobs[0]); },
+ s => { s.jobs[0].steps.push(s.jobs[0].steps[0]); }, s => { s.input.android = 'skipped'; },
+ s => { s.context.payload.pull_request.number = 7045; },
+ s => { s.context.payload.pull_request.head.repo.full_name = 'fork/bitcoin-keeper'; },
+ s => { s.runs[0].status = 'queued'; },
+ s => { Object.assign(s.runs[0], { status: 'completed', conclusion: 'cancelled' }); }, s => { s.error = true; }]) {
+ const state = fixture(); mutate(state); assert.equal(await state.check(), false);
+ }
+});
diff --git a/.github/tests/release-pipeline.test.cjs b/.github/tests/release-pipeline.test.cjs
new file mode 100644
index 0000000000..459d06002b
--- /dev/null
+++ b/.github/tests/release-pipeline.test.cjs
@@ -0,0 +1,334 @@
+const assert = require('node:assert/strict');
+const fs = require('node:fs');
+const path = require('node:path');
+const vm = require('node:vm');
+const { test } = require('node:test');
+const { WORKFLOWS, fingerprint, preflight } = require('../native/release_preflight.cjs');
+const { REQUIRED, acceptance, markdown } = require('../native/release_acceptance.cjs');
+
+// GitHub metadata models only: these tests supply no native or release evidence.
+const repository = 'KeeperCommunity/bitcoin-keeper';
+const repositoryId = 470904030;
+const headSha = 'a'.repeat(40);
+const baseSha = 'b'.repeat(40);
+const runBaseSha = 'c'.repeat(40);
+const NATIVE_FILES = [
+ 'hosted_native.py', 'startup.yaml', 'nodeify.cjs', 'release_preflight.cjs',
+ 'release_acceptance.cjs', 'release_evidence.cjs', 'release_metro.cjs', 'release_probe.js',
+ 'release_probe_core.js', 'release_probe.yaml',
+].map(name => '.github/native/' + name);
+const clone = value => structuredClone(value);
+
+function trustedTree() {
+ const paths = [...WORKFLOWS, ...NATIVE_FILES, 'src/index.ts'];
+ return {
+ truncated: false,
+ tree: paths.map((path, index) => ({
+ path, mode: '100644', type: 'blob', sha: (index + 1).toString(16).padStart(40, '0'),
+ })),
+ };
+}
+
+function pullRequest() {
+ return {
+ number: 7058,
+ head: { sha: headSha, ref: 'codex/future-release',
+ repo: { full_name: repository, id: repositoryId } },
+ base: { sha: baseSha, ref: 'sprint',
+ repo: { full_name: repository, id: repositoryId } },
+ };
+}
+
+async function evaluate(options = {}) {
+ const original = pullRequest();
+ original.base.sha = runBaseSha;
+ const current = pullRequest();
+ options.original?.(original);
+ options.current?.(current);
+ const latest = clone(current);
+ options.latest?.(latest);
+ const calls = [];
+ let reads = 0;
+ const github = {
+ rest: {
+ pulls: {
+ get: async args => {
+ calls.push({ api: 'pulls.get', ...args });
+ reads += 1;
+ if (options.pullError) throw new Error('Private API detail must not be reported');
+ return { data: clone(reads === 1 ? current : latest) };
+ },
+ },
+ git: {
+ getTree: async args => {
+ calls.push({ api: 'git.getTree', ...args });
+ if (options.treeError === args.tree_sha) throw new Error('Private API detail');
+ return { data: clone(options.trees?.[args.tree_sha] ?? trustedTree()) };
+ },
+ },
+ },
+ };
+ const context = {
+ eventName: options.eventName ?? 'pull_request',
+ repo: { owner: 'KeeperCommunity', repo: 'bitcoin-keeper' },
+ payload: { pull_request: options.withoutPR ? undefined : original },
+ };
+ return { result: await preflight(github, context), calls };
+}
+
+test('unchanged reviewed CI on app/current-base/run-base yields exact-head preflight only', async () => {
+ const { result, calls } = await evaluate();
+ assert.equal(result.trusted, true);
+ assert.equal(calls.filter(call => call.api === 'pulls.get').length, 2);
+ assert.deepEqual(calls.filter(call => call.api === 'git.getTree').map(call => call.tree_sha),
+ [headSha, baseSha, runBaseSha]);
+ assert.ok(calls.filter(call => call.api === 'git.getTree').every(call => call.recursive === '1'));
+ assert.ok(calls.every(call => !/create|update|dispatch|status/.test(call.api)));
+});
+
+test('all later same-repository release PRs use the same preflight without release-number routing', async () => {
+ for (const number of [7058, 8001, 12000]) {
+ const { result } = await evaluate({
+ original: pr => { pr.number = number; },
+ current: pr => { pr.number = number; },
+ });
+ assert.equal(result.trusted, true, String(number));
+ }
+});
+
+test('R4 is excluded before any API read, even when its source otherwise matches', async () => {
+ const { result, calls } = await evaluate({ original: pr => { pr.number = 7045; } });
+ assert.equal(result.trusted, false);
+ assert.match(result.reason, /R4/);
+ assert.deepEqual(calls, []);
+});
+
+test('non-PR events and missing PR metadata never trigger native authorization', async () => {
+ for (const options of [{ eventName: 'workflow_dispatch' }, { eventName: 'pull_request_target' },
+ { eventName: 'push' }, { withoutPR: true }]) {
+ const { result, calls } = await evaluate(options);
+ assert.equal(result.trusted, false);
+ assert.deepEqual(calls, []);
+ }
+});
+
+test('forks, wrong target branches, stale payloads and repository-ID drift fail before tree reads', async () => {
+ const mutations = [
+ pr => { pr.head.repo = { full_name: 'fork/bitcoin-keeper', id: 123 }; },
+ pr => { pr.base.repo.full_name = 'fork/bitcoin-keeper'; },
+ pr => { pr.base.ref = 'other-base'; },
+ pr => { pr.head.ref = 'other-head'; },
+ pr => { pr.head.sha = 'd'.repeat(40); },
+ pr => { pr.head.sha = 'not-a-sha'; },
+ pr => { pr.head.repo.id += 1; },
+ pr => { pr.base.repo.id += 1; },
+ pr => { delete pr.head.repo; },
+ pr => { delete pr.base.repo.id; },
+ ];
+ for (const current of mutations) {
+ const { result, calls } = await evaluate({ current });
+ assert.equal(result.trusted, false);
+ assert.equal(calls.filter(call => call.api === 'git.getTree').length, 0);
+ }
+});
+
+test('source or base movement while checking provenance cannot receive current-head credit', async () => {
+ for (const latest of [pr => { pr.head.sha = 'd'.repeat(40); },
+ pr => { pr.base.sha = 'd'.repeat(40); }]) {
+ const { result } = await evaluate({ latest });
+ assert.equal(result.trusted, false);
+ assert.match(result.reason, /changed|provenance/);
+ }
+});
+
+test('retargeting or repository/ref identity drift at unchanged SHAs is still a race', async () => {
+ for (const latest of [pr => { pr.base.ref = 'another-branch-at-same-sha'; },
+ pr => { pr.head.ref = 'another-head-at-same-sha'; },
+ pr => { pr.base.repo.id += 1; }, pr => { pr.head.repo.id += 1; },
+ pr => { pr.base.repo.full_name = 'fork/bitcoin-keeper'; },
+ pr => { pr.head.repo.full_name = 'fork/bitcoin-keeper'; }]) {
+ const { result } = await evaluate({ latest });
+ assert.equal(result.trusted, false);
+ }
+});
+
+test('every workflow/harness addition, deletion, content, mode or type mutation denies trust in each snapshot', async () => {
+ for (const ref of [headSha, baseSha, runBaseSha]) {
+ for (const target of [...WORKFLOWS, ...NATIVE_FILES]) {
+ for (const mutation of ['content', 'delete', 'mode', 'type']) {
+ const tree = trustedTree();
+ const index = tree.tree.findIndex(entry => entry.path === target);
+ if (mutation === 'content') tree.tree[index].sha = 'f'.repeat(40);
+ if (mutation === 'delete') tree.tree.splice(index, 1);
+ if (mutation === 'mode') tree.tree[index].mode = '100755';
+ if (mutation === 'type') tree.tree[index].type = 'commit';
+ const { result } = await evaluate({ trees: { [ref]: tree } });
+ assert.equal(result.trusted, false, `${ref}:${target}:${mutation}`);
+ }
+ }
+ const tree = trustedTree();
+ tree.tree.push({ path: '.github/native/unreviewed-helper.cjs', mode: '100644',
+ type: 'blob', sha: 'f'.repeat(40) });
+ assert.equal((await evaluate({ trees: { [ref]: tree } })).result.trusted, false);
+ }
+});
+
+test('bootstrap is unavailable when any transitive workflow/native dependency is absent from every snapshot', async () => {
+ for (const missing of [...WORKFLOWS, ...NATIVE_FILES]) {
+ const tree = trustedTree();
+ tree.tree = tree.tree.filter(entry => entry.path !== missing);
+ const { result } = await evaluate({ trees: {
+ [headSha]: tree, [baseSha]: tree, [runBaseSha]: tree,
+ } });
+ assert.equal(result.trusted, false, missing);
+ }
+});
+
+test('required infrastructure symlinks cannot move executable dependencies outside the fingerprint', async () => {
+ for (const target of [...WORKFLOWS, ...NATIVE_FILES]) {
+ const tree = trustedTree();
+ tree.tree.find(entry => entry.path === target).mode = '120000';
+ const { result } = await evaluate({ trees: {
+ [headSha]: tree, [baseSha]: tree, [runBaseSha]: tree,
+ } });
+ assert.equal(result.trusted, false, target);
+ }
+});
+
+test('truncated or unavailable GitHub trees fail closed with bounded public reasons', async () => {
+ for (const ref of [headSha, baseSha, runBaseSha]) {
+ const tree = trustedTree();
+ tree.truncated = true;
+ for (const options of [{ trees: { [ref]: tree } }, { treeError: ref }]) {
+ const { result } = await evaluate(options);
+ assert.equal(result.trusted, false);
+ assert.doesNotMatch(result.reason, /Private API detail/);
+ }
+ }
+});
+
+test('fingerprinting is order independent and ordinary app changes are outside CI provenance', async () => {
+ const tree = trustedTree();
+ tree.tree.reverse();
+ assert.equal(fingerprint(tree), fingerprint(trustedTree()));
+ tree.tree.find(entry => entry.path === 'src/index.ts').sha = 'f'.repeat(40);
+ const { result } = await evaluate({ trees: { [headSha]: tree } });
+ assert.equal(result.trusted, true);
+});
+
+test('two successful native jobs record only their implemented scope and never imply release readiness', () => {
+ const result = acceptance({ trusted: true, ios: 'success', android: 'success' });
+ assert.equal(result.release_ready, false);
+ assert.equal(result.phase_a, 'BLOCKED');
+ assert.deepEqual(result.cases.map(scenario => scenario.id), REQUIRED);
+ assert.deepEqual(result.cases.slice(0, 2).map(scenario => scenario.status), ['PASS', 'PASS']);
+ assert.ok(result.cases.slice(2).every(scenario => scenario.status === 'NOT IMPLEMENTED'));
+ assert.match(result.cases[1].scope, /not application account isolation/);
+ assert.match(result.signing, /NOT IMPLEMENTED.*NOT VERIFIED/);
+ assert.match(result.physical, /NOT RUN/);
+});
+
+test('failed, skipped, cancelled, pending or missing platform jobs provide no matrix credit', () => {
+ for (const value of [undefined, null, '', 'failure', 'skipped', 'cancelled', 'pending',
+ 'in_progress', 'neutral', 'SUCCESS', true]) {
+ for (const platform of ['ios', 'android']) {
+ const result = acceptance({ trusted: true, ios: 'success', android: 'success', [platform]: value });
+ assert.ok(result.cases.slice(0, 2).every(scenario => scenario.status === 'NOT VERIFIED'),
+ `${platform}:${value}`);
+ assert.equal(result.release_ready, false);
+ assert.equal(result.phase_a, 'BLOCKED');
+ }
+ }
+});
+
+test('only a boolean trusted preflight permits implemented native scope to receive PASS', () => {
+ for (const trusted of [undefined, null, false, 'true', 1, {}]) {
+ const result = acceptance({ trusted, ios: 'success', android: 'success' });
+ assert.ok(result.cases.slice(0, 2).every(scenario => scenario.status === 'NOT VERIFIED'));
+ assert.equal(result.release_ready, false);
+ }
+});
+
+test('human-readable acceptance preserves all blocked scenarios and separate signing/physical requirements', () => {
+ const result = acceptance({ trusted: true, ios: 'success', android: 'success' });
+ const text = markdown(result);
+ assert.match(text, /Phase A release acceptance: BLOCKED/);
+ assert.match(text, /cannot approve a release/);
+ for (const id of REQUIRED) assert.ok(text.includes(id));
+ assert.match(text, /NOT IMPLEMENTED/);
+ assert.match(text, /exact distributed artifact required/);
+});
+
+test('Phase A caller and reusable worker expose no production-secret, protected-environment or privileged-event path', () => {
+ // The inherited #7060 workflow is independently reviewed; protect new Phase A execution here.
+ for (const filename of WORKFLOWS.filter(name => !name.endsWith('/keeper-hosted-native.yml'))) {
+ const source = fs.readFileSync(path.join(__dirname, '../..', filename), 'utf8')
+ .split('\n').filter(line => !line.trimStart().startsWith('#')).join('\n');
+ // Static security policy: these constructs change the runner trust boundary.
+ assert.doesNotMatch(source, /^\s*(?:secrets|environment)\s*:/m, filename);
+ assert.doesNotMatch(source, /\bsecrets\s*\./, filename);
+ assert.doesNotMatch(source, /^\s*(?:pull_request_target|workflow_dispatch|repository_dispatch)\s*:/m,
+ filename);
+ assert.doesNotMatch(source, /^\s*[\w-]+:\s*write\s*$/m, filename);
+ assert.doesNotMatch(source, /\bfastlane\b|\bgh\s+release\b/, filename);
+ for (const match of source.matchAll(/^\s*(?:-\s*)?uses:\s*(\S+)/gm)) {
+ assert.ok(match[1].startsWith('./.github/workflows/') || /@[a-f0-9]{40}$/.test(match[1]),
+ `${filename}: unpinned dependency ${match[1]}`);
+ }
+ }
+});
+
+function probeMiddleware(enhanced) {
+ const seen = [];
+ const original = (request, response, next) => {
+ seen.push({ url: request.url, response, next });
+ return 'served';
+ };
+ const base = { resolver: { preserved: true }, server: { preserveSetting: true } };
+ let enhancementCalls = 0;
+ if (enhanced) base.server.enhanceMiddleware = (inner, server) => {
+ enhancementCalls += 1;
+ assert.equal(inner, original);
+ assert.equal(server.marker, true);
+ return (request, response, next) => original(request, response, next);
+ };
+ const file = path.join(__dirname, '../native/release_metro.cjs');
+ const context = {
+ __dirname: path.dirname(file), module: { exports: {} },
+ require: name => {
+ if (name === '../../metro.config') return base;
+ if (name === 'node:path') return path;
+ throw new Error('Unexpected Metro dependency: ' + name);
+ },
+ };
+ vm.runInNewContext(fs.readFileSync(file, 'utf8'), context, { filename: file });
+ const config = context.module.exports;
+ assert.equal(config.resolver, base.resolver);
+ assert.equal(config.server.preserveSetting, true);
+ assert.equal(config.projectRoot, path.resolve(__dirname, '../..'));
+ assert.equal(base.projectRoot, undefined);
+ return { middleware: config.server.enhanceMiddleware(original, { marker: true }),
+ seen, getEnhancementCalls: () => enhancementCalls };
+}
+
+test('CI Metro remaps only the native entrypoint while preserving query, source maps and base middleware', () => {
+ for (const enhanced of [true, false]) {
+ const state = probeMiddleware(enhanced);
+ const cases = [
+ ['/index.bundle?platform=ios&dev=true', '/.github/native/release_probe.bundle?platform=ios&dev=true'],
+ ['/index.map?platform=android', '/.github/native/release_probe.map?platform=android'],
+ ['/index.bundle', '/.github/native/release_probe.bundle'],
+ ['/status', '/status'],
+ ['/nested/index.bundle?platform=ios', '/nested/index.bundle?platform=ios'],
+ ['/index.bundle.other?platform=ios', '/index.bundle.other?platform=ios'],
+ ['/another.bundle?platform=android', '/another.bundle?platform=android'],
+ ];
+ for (const [url, expected] of cases) {
+ const response = {};
+ const next = () => {};
+ assert.equal(state.middleware({ url }, response, next), 'served');
+ assert.deepEqual(state.seen.at(-1), { url: expected, response, next });
+ }
+ assert.equal(state.getEnhancementCalls(), enhanced ? 1 : 0);
+ }
+});
diff --git a/.github/tests/release-probe.test.cjs b/.github/tests/release-probe.test.cjs
new file mode 100644
index 0000000000..5f702b7e1d
--- /dev/null
+++ b/.github/tests/release-probe.test.cjs
@@ -0,0 +1,135 @@
+/* Host-only orchestration tests. This model supplies NO native platform evidence. */
+const assert = require('node:assert/strict');
+const { test } = require('node:test');
+const { runProbe, PHASE_KEY, MARKER_KEY, PRIMARY, OTHER, ROLLBACK } = require('../native/release_probe_core');
+
+function fixture(bugs = {}) {
+ const disk = new Map();
+ const values = new Map([['unrelated-storage-key', 'preserve']]);
+ const handles = new Set();
+ const storage = {
+ getString: (key) => values.get(key),
+ setItem: (key, value) => values.set(key, value),
+ deleteItem: (key) => values.delete(key),
+ };
+ const Realm = {
+ defaultPath: '/synthetic-device/default.realm',
+ async open(config) {
+ const key = config.encryptionKey[0];
+ if (!disk.has(config.path)) disk.set(config.path, { key, wallets: new Map() });
+ const file = disk.get(config.path);
+ if (key !== file.key && !bugs.acceptWrongKey) throw new Error('modeled wrong key');
+ const handle = {
+ objectForPrimaryKey: (_table, id) => file.wallets.get(id),
+ objects: () => [...file.wallets.values()],
+ write(callback) {
+ const before = structuredClone(file.wallets);
+ try {
+ callback();
+ } catch (error) {
+ if (!bugs.skipRollback) file.wallets = before;
+ throw error;
+ }
+ },
+ create(_table, value) { file.wallets.set(value.id, structuredClone(value)); },
+ delete(value) { if (!bugs.skipDelete) file.wallets.delete(value.id); },
+ close() { handles.delete(handle); },
+ };
+ handles.add(handle);
+ return handle;
+ },
+ deleteFile(config) {
+ if (bugs.cleanupFailure) throw new Error('modeled cleanup failure');
+ disk.delete(config.path);
+ },
+ };
+ return {
+ options: { Realm, schema: [], storage }, disk, values, handles,
+ a: () => disk.get('/synthetic-device/keeper-ci-release-probe-v1-a.realm'),
+ };
+}
+
+test('three process phases require persisted state and clean only disposable fixture', async () => {
+ const state = fixture();
+ assert.equal(await runProbe(state.options), 'seeded');
+ assert.equal(state.handles.size, 0);
+ assert.equal(state.values.get(PHASE_KEY), 'seeded');
+ assert.equal(await runProbe(state.options), 'mutated');
+ assert.equal(state.handles.size, 0);
+ assert.equal(state.a().wallets.has(PRIMARY), false);
+ assert.equal(state.a().wallets.has(OTHER), true);
+ assert.equal(state.a().wallets.has(ROLLBACK), false);
+ assert.equal(await runProbe(state.options), 'pass');
+ assert.equal(state.handles.size, 0);
+ assert.equal(state.disk.size, 0);
+ assert.deepEqual([...state.values], [['unrelated-storage-key', 'preserve']]);
+});
+
+test('missing persisted MMKV marker cannot progress after relaunch', async () => {
+ const state = fixture();
+ await runProbe(state.options);
+ state.values.delete(MARKER_KEY);
+ await assert.rejects(runProbe(state.options), { code: 'mmkv-marker-not-persisted' });
+ assert.equal(state.values.get(PHASE_KEY), 'seeded');
+ assert.equal(state.handles.size, 0);
+});
+
+test('wrong-key acceptance fails closed before wallet deletion', async () => {
+ const state = fixture({ acceptWrongKey: true });
+ await runProbe(state.options);
+ await assert.rejects(runProbe(state.options), { code: 'wrong-encryption-key-accepted' });
+ assert.equal(state.a().wallets.has(PRIMARY), true);
+ assert.equal(state.handles.size, 0);
+});
+
+test('corruption of embedded wallet balances cannot pass', async () => {
+ const state = fixture();
+ await runProbe(state.options);
+ state.a().wallets.get(OTHER).specs.balances.confirmed = 1;
+ await assert.rejects(runProbe(state.options), { code: 'embedded-wallet-state-not-persisted' });
+ assert.equal(state.values.get(PHASE_KEY), 'seeded');
+ assert.equal(state.handles.size, 0);
+});
+
+test('failed transaction rollback cannot progress', async () => {
+ const state = fixture({ skipRollback: true });
+ await runProbe(state.options);
+ await assert.rejects(runProbe(state.options), { code: 'transaction-rollback-failed' });
+ assert.equal(state.values.get(PHASE_KEY), 'seeded');
+ assert.equal(state.handles.size, 0);
+});
+
+test('failed deletion cannot advance persistence marker', async () => {
+ const state = fixture({ skipDelete: true });
+ await runProbe(state.options);
+ await assert.rejects(runProbe(state.options), { code: 'targeted-wallet-delete-failed' });
+ assert.equal(state.values.get(PHASE_KEY), 'seeded');
+ assert.equal(state.handles.size, 0);
+});
+
+test('lost deletion after second relaunch cannot pass', async () => {
+ const state = fixture();
+ await runProbe(state.options);
+ const original = structuredClone(state.a().wallets.get(PRIMARY));
+ await runProbe(state.options);
+ state.a().wallets.set(PRIMARY, original);
+ await assert.rejects(runProbe(state.options), { code: 'unexpected-primary-record-count' });
+ assert.equal(state.values.get(PHASE_KEY), 'mutated');
+ assert.equal(state.handles.size, 0);
+});
+
+test('fixture cleanup failure cannot produce pass', async () => {
+ const state = fixture({ cleanupFailure: true });
+ await runProbe(state.options);
+ await runProbe(state.options);
+ await assert.rejects(runProbe(state.options), /modeled cleanup failure/);
+ assert.equal(state.values.get(PHASE_KEY), 'mutated');
+ assert.equal(state.handles.size, 0);
+});
+
+test('unknown phase stops before accessing native databases', async () => {
+ const state = fixture();
+ state.values.set(PHASE_KEY, 'unexpected');
+ await assert.rejects(runProbe(state.options), { code: 'invalid-phase' });
+ assert.equal(state.disk.size, 0);
+});
diff --git a/.github/tests/startup-observer.test.cjs b/.github/tests/startup-observer.test.cjs
new file mode 100644
index 0000000000..9e2e2d891a
--- /dev/null
+++ b/.github/tests/startup-observer.test.cjs
@@ -0,0 +1,108 @@
+'use strict';
+const assert = require('node:assert/strict');
+const fs = require('node:fs');
+const path = require('node:path');
+const vm = require('node:vm');
+const { EventEmitter } = require('node:events');
+const test = require('node:test');
+const source = fs.readFileSync(path.join(__dirname, '../native/startup_observer.cjs'), 'utf8');
+const reporterSource = fs.readFileSync(path.join(__dirname, '../native/startup_reporter.cjs'), 'utf8');
+
+function load(config, enabled = true) {
+ const rows = [];
+ const reporterEvents = [];
+ const terminals = [];
+ class TerminalReporter {
+ constructor(terminal) { this.terminal = terminal; terminals.push(terminal); }
+ update(event) { assert.equal(this.terminal, terminals[0]); reporterEvents.push(event); return 31; }
+ }
+ let Reporter;
+ const context = { module: { exports: {} }, URL, Date,
+ process: { env: { RUNNER_TEMP: '/tmp/keeper-fixture', KEEPER_STARTUP_OBSERVER_PATH: enabled ? '/tmp/keeper-fixture/keeper-native-private/startup-observer.jsonl' : '/unsafe/PRIVATE_SENTINEL' } },
+ require(name) {
+ if (name === '../../metro.config.js') return config;
+ if (name === './startup_reporter.cjs') return Reporter;
+ if (name === 'metro') return { TerminalReporter };
+ if (name === 'node:module') return { createRequire(filename) {
+ assert(['/app/react-native/package.json', '/app/react-native/cli-plugin/package.json'].includes(filename));
+ const result = (name) => { assert.equal(name, 'metro'); return { TerminalReporter }; };
+ result.resolve = (name) => { assert.equal(name, '@react-native/community-cli-plugin/package.json'); return '/app/react-native/cli-plugin/package.json'; };
+ return result;
+ } };
+ if (name === 'node:fs') return { appendFileSync(file, text) { rows.push(JSON.parse(text)); } };
+ if (name === 'node:path') return path;
+ if (name === 'node:os') return { tmpdir: () => '/tmp' };
+ throw new Error('Unexpected fixture import');
+ },
+ };
+ context.require.resolve = (name) => { assert.equal(name, 'react-native/package.json'); return '/app/react-native/package.json'; };
+ const reporterContext = { ...context, module: { exports: {} } };
+ vm.runInNewContext(reporterSource, reporterContext);
+ Reporter = reporterContext.module.exports;
+ vm.runInNewContext(source, context);
+ return { config: context.module.exports, rows, Reporter, reporterEvents, terminals };
+}
+
+test('keeps normal resolver, transformer, entry settings and original reporter context', () => {
+ const observed = [];
+ const reporter = { update(event) { assert.equal(this, reporter); observed.push(event); return 17; } };
+ const original = { resolver: {}, transformer: {}, serializer: {}, projectRoot: '/original', reporter, server: { port: 8081 } };
+ const loaded = load(original);
+ for (const key of ['resolver', 'transformer', 'serializer', 'projectRoot']) assert.equal(loaded.config[key], original[key]);
+ assert.equal(loaded.config.server.port, 8081);
+ assert.equal(loaded.config.reporter, reporter);
+ const event = { type: 'bundle_build_started', bundleDetails: { platform: 'android', dev: true }, PRIVATE_SENTINEL: 'private' };
+ assert.equal(loaded.config.reporter.update(event), 17);
+ assert.equal(observed[0], event);
+ const terminal = {};
+ const cliReporter = new loaded.Reporter(terminal);
+ assert.equal(cliReporter.update(event), 31);
+ assert.equal(loaded.terminals[0], terminal);
+ assert.equal(loaded.reporterEvents[0], event);
+ assert(!JSON.stringify(loaded.rows).includes('PRIVATE_SENTINEL'));
+});
+
+test('forwards middleware enhancer, requests, streaming and backpressure unchanged', () => {
+ const calls = [];
+ const middleware = () => {};
+ const server = {};
+ const original = { reporter: { update() {} }, server: { enhanceMiddleware(inner, actualServer) {
+ assert.equal(this, original.server); assert.equal(inner, middleware); assert.equal(actualServer, server);
+ return function (...args) { calls.push([this, ...args]); return 23; };
+ } } };
+ const loaded = load(original);
+ const handler = loaded.config.server.enhanceMiddleware(middleware, server);
+ const req = { url: '/index.bundle?platform=android&dev=true&lazy=true&app=io.hexawallet.keeper.development&modulesOnly=false&runModule=true&excludeSource=true&sourcePaths=url-server&PRIVATE_SENTINEL=secret' };
+ const res = new EventEmitter(); res.statusCode = 500; res.write = () => false;
+ const write = res.write;
+ const next = () => {};
+ const receiver = {};
+ assert.equal(handler.call(receiver, req, res, next), 23);
+ assert.deepEqual(calls[0], [receiver, req, res, next]);
+ assert.equal(res.write, write); assert.equal(res.write(Buffer.from('unchanged')), false);
+ res.emit('finish');
+ assert.equal(loaded.rows[0].options.lazy, true);
+ assert.equal(loaded.rows[0].options.app, 'EXPECTED');
+ assert.equal(loaded.rows[1].outer_http_status, 500);
+ assert(!JSON.stringify(loaded.rows).includes('PRIVATE_SENTINEL'));
+});
+
+test('emits only fixed error/query categories and caps rows', () => {
+ const loaded = load({ reporter: { update() {} } });
+ const cliReporter = new loaded.Reporter({});
+ cliReporter.update({ type: 'bundling_error', error: { name: 'PRIVATE_SENTINEL', message: 'TypeError PRIVATE_SENTINEL secret URL/path' } });
+ const handler = loaded.config.server.enhanceMiddleware(() => true, {});
+ handler({ url: '/PRIVATE_SENTINEL.bundle?platform=PRIVATE_SENTINEL&app=PRIVATE_SENTINEL&dev=PRIVATE_SENTINEL' }, new EventEmitter(), () => {});
+ assert.equal(loaded.rows[0].error_type, 'OTHER');
+ assert.equal(loaded.rows[0].kind, 'ERROR');
+ assert.equal(loaded.rows[0].event, 'bundling_error');
+ assert.equal(loaded.rows[1].options.platform, 'OTHER');
+ assert(!JSON.stringify(loaded.rows).includes('PRIVATE_SENTINEL'));
+ for (let i = 0; i < 600; i++) cliReporter.update({ type: 'bundle_build_done' });
+ assert.equal(loaded.rows.length, 512);
+ const disabled = load({ reporter: { update() { return 9; } } }, false);
+ assert.equal(disabled.config.reporter.update({ type: 'bundle_build_done' }), 9);
+ assert.equal(disabled.rows.length, 0);
+ assert.equal(new disabled.Reporter({}).update({ type: 'bundle_build_done' }), 31);
+ assert.equal(disabled.rows.length, 0);
+});
diff --git a/.github/tests/test_044_android_artifact_readout.py b/.github/tests/test_044_android_artifact_readout.py
new file mode 100644
index 0000000000..2c04f87b2a
--- /dev/null
+++ b/.github/tests/test_044_android_artifact_readout.py
@@ -0,0 +1,422 @@
+"""Portable fabricated metadata controls; no download, app or native execution."""
+from contextlib import redirect_stdout
+import base64
+import copy
+import hashlib
+import importlib.util
+import io
+import json
+import os
+from pathlib import Path
+import stat
+import struct
+import tempfile
+import unittest
+from unittest import mock
+import zipfile
+
+SPEC = importlib.util.spec_from_file_location('fixed044_android_readout',
+ Path(__file__).resolve().parents[1] / 'scripts/read-044-android-artifact.py')
+reader = importlib.util.module_from_spec(SPEC)
+SPEC.loader.exec_module(reader)
+
+
+def fixture():
+ return {'schema': 1, 'source_sha': reader.SOURCE, 'workflow_sha': reader.WORKFLOW,
+ 'workflow_ref': reader.WORKFLOW_REF, 'run_id': reader.RUN, 'run_attempt': reader.ATTEMPT,
+ 'platform': 'ANDROID', 'diagnostic_only': True, 'build': 'PASS', 'smoke': 'PASS',
+ 'native_probe': 'PASS', 'r5_features': 'PASS', 'hardware': 'NOT RUN', 'signing': 'NOT RUN',
+ 'app_id': 'io.hexawallet.keeper.development', 'commands': [{
+ 'label': 'Record Node version', 'command': ['node', '--version'],
+ 'timeout_seconds': 120, 'exit_code': 0, 'duration_seconds': 0.1}],
+ 'startup_observation': {'hierarchy': {**dict.fromkeys(reader.STARTUP_FLAGS, False),
+ 'snapshot_count': 1}},
+ 'product_ui': {'status': 'FAIL', 'samples': [{'sample': 1, 'status': 'FAIL'}],
+ 'controlled_disconnect_retry': {'status': 'NOT RUN'}}}
+
+
+def failure_observation():
+ return {'scope': 'Failed-sample files and bound owned Metro only; observations do not prove current visibility, route, tap delivery or cause.',
+ 'junit': {'state': 'ERROR_RECORDED', 'failed_selector': 'start_new_tile',
+ 'failure_kind': 'ASSERT_VISIBLE'},
+ 'hierarchy': {'state': 'PARTIAL', 'snapshot_count': 1, 'node_count': 10,
+ 'rejected_snapshots': 1, 'snapshot_limit_exceeded': False,
+ 'scope': reader.PRODUCT_HIERARCHY_SCOPE,
+ 'flags': {**dict.fromkeys(reader.PRODUCT_FLAGS), 'onboarding_skip': True}},
+ 'product_metro': {'state': 'UNKNOWN', 'scope': 'Bound product-sample console window; markers are not cause or request proof.',
+ 'process_state': 'ALIVE', 'exit_code': None}}
+
+
+def boundary():
+ return {'schema': 1, 'scope': 'DEV_MARKERS_NOT_ROUTE_TAP_DELIVERY_OR_CAUSE_PROOF',
+ 'state': 'OBSERVED', 'cause': 'UNDETERMINED', 'freshness': 'GUEST_CLOCK_UNVERIFIED',
+ 'coverage': 'POSITIVE_ONLY_MISSING_STAGES_UNKNOWN', 'producer_per_stage_limit': 4,
+ 'producer_total_limit': 20, 'consumer_marker_limit': 64, 'input_byte_limit': 524288,
+ 'scan_record_limit': 10000, 'input_usable': True, 'full_input': True,
+ 'ownership_usable': True, 'input_limit_exceeded': False, 'record_limit_reached': False,
+ 'marker_limit_reached': False, 'stages': {key: None for key in reader.BOUNDARY_STAGES},
+ 'scanned_records': 10000, 'marker_records': 64, 'owned_marker_records': 64,
+ 'foreign_pid_records': 0, 'duplicate_records': 63, 'malformed_marker_records': 0,
+ 'unsupported_marker_records': 0, 'invalid_text_records': 0, 'partial_records': 0}
+
+
+def snapshot(bound=True):
+ return {'schema': 1, 'binding_state': 'BOUND' if bound else 'UNKNOWN',
+ 'reason': 'FAILED_ASSERTION_OUTCOME' if bound else 'UNBOUND_FAILED_ASSERTION',
+ 'scope': reader.SNAPSHOT_SCOPE,
+ 'failed_assertion': {'kind': 'ASSERT_VISIBLE', 'selector': 'start_new_tile',
+ 'sequence_number': 2047} if bound else None,
+ 'node_count': 10000 if bound else None,
+ 'skip': {'state': 'UNIQUE_VALID_BOUNDS' if bound else 'UNKNOWN',
+ 'exact_resource_id_count': 1 if bound else None,
+ 'bounds': {'left': -100000, 'top': 0, 'right': 100000, 'bottom': 20} if bound else None,
+ **dict.fromkeys(reader.SKIP_FLAGS),
+ 'conflicts': dict.fromkeys(reader.SKIP_FLAGS, False if bound else None)},
+ 'tap_coordinates': 'NOT_RECORDED', 'visible_to_user': 'NOT_RECORDED'}
+
+
+def observed_data():
+ data = fixture()
+ data['startup_diagnostics'] = {'android_runtime_diagnosis': {
+ 'onboarding_boundary_observation': boundary(),
+ 'runtime_errors': {'diagnostic_marker_records': 1200}}}
+ for item in (data['product_ui']['samples'][0], data['product_ui']['controlled_disconnect_retry']):
+ item['failed_assertion_snapshot'] = snapshot()
+ item['failure_observation'] = failure_observation()
+ item['android_runtime_diagnostic'] = {'facts': {
+ 'onboarding_boundary_observation': boundary(),
+ 'runtime_errors': {'diagnostic_marker_records': 1200}}}
+ return data
+
+
+def archive(data=None, raw=None, name='android/metadata.json', attributes=None, extra=False):
+ stream = io.BytesIO()
+ with zipfile.ZipFile(stream, 'w', zipfile.ZIP_DEFLATED) as output:
+ entry = zipfile.ZipInfo(name)
+ entry.compress_type = zipfile.ZIP_DEFLATED
+ entry.external_attr = attributes if attributes is not None else (stat.S_IFREG | 0o600) << 16
+ output.writestr(entry, raw if raw is not None else json.dumps(fixture() if data is None else data))
+ if extra:
+ output.writestr('raw.log', 'PRIVATE_SENTINEL')
+ return stream.getvalue()
+
+
+def bound(blob):
+ # Fabricated ZIP bytes only; production conclusion tuple remains unchanged.
+ return mock.patch.multiple(reader, JOB='999', ARTIFACT='1', RUN_CONCLUSION='failure', ZIP_SIZE=len(blob),
+ ZIP_SHA256=hashlib.sha256(blob).hexdigest(), NATIVE_CONCLUSION='failure',
+ BUILD_CONCLUSION='success', PROBES_CONCLUSION='failure')
+
+
+class AndroidByteReadoutTests(unittest.TestCase):
+ def reject(self, blob):
+ with self.assertRaises(Exception):
+ reader.validate_archive(blob)
+
+ def test_unavailable_selection_rejects_before_input_or_policy_access(self):
+ self.assertEqual((reader.JOB, reader.ARTIFACT, reader.ZIP_SIZE, reader.ZIP_SHA256,
+ reader.RUN_CONCLUSION, reader.NATIVE_CONCLUSION, reader.BUILD_CONCLUSION,
+ reader.PROBES_CONCLUSION), (None,) * 8)
+ self.assertEqual((reader.SOURCE, reader.RUN, reader.ATTEMPT, reader.WORKFLOW),
+ ('044ebb6ea2d465f6a70e9116e3feac5a604cd696', '39873063291', '1',
+ '5a7b0c5da0a38197f6dd675ff424f3ba3f441d02'))
+ with mock.patch.object(reader, 'checked_bytes') as checking, \
+ mock.patch.object(reader, 'Path') as paths, \
+ mock.patch.object(reader.os, 'open') as opening, \
+ mock.patch.object(reader, 'public_literals') as policy:
+ output = io.StringIO()
+ with redirect_stdout(output):
+ self.assertEqual(reader.main([]), 1)
+ self.assertEqual(output.getvalue(), 'FIXED_044_ANDROID_ARTIFACT_BYTE_READOUT_FAILED\n')
+ checking.assert_not_called(); paths.assert_not_called()
+ opening.assert_not_called(); policy.assert_not_called()
+
+ def test_partial_binding_never_reads_input_and_invalid_types_fail_closed(self):
+ blob = archive()
+ for name in ('JOB', 'ARTIFACT', 'ZIP_SHA256', 'ZIP_SIZE', 'RUN_CONCLUSION', 'NATIVE_CONCLUSION',
+ 'BUILD_CONCLUSION', 'PROBES_CONCLUSION'):
+ with bound(blob), mock.patch.object(reader, name, None), \
+ mock.patch.object(reader, 'checked_bytes') as checking, \
+ mock.patch.object(reader, 'Path') as paths, \
+ mock.patch.object(reader.os, 'open') as opening, \
+ mock.patch.object(reader, 'public_literals') as policy:
+ with redirect_stdout(io.StringIO()):
+ self.assertEqual(reader.main([]), 1)
+ checking.assert_not_called()
+ paths.assert_not_called(); opening.assert_not_called(); policy.assert_not_called()
+ for name, value in [('ARTIFACT', True), ('ZIP_SIZE', True), ('ZIP_SIZE', -1),
+ ('ZIP_SHA256', 'PRIVATE_SENTINEL'), ('NATIVE_CONCLUSION', 1),
+ ('NATIVE_CONCLUSION', 'cancelled'), ('RUN_CONCLUSION', 'skipped'),
+ ('PROBES_CONCLUSION', 'cancelled'), ('BUILD_CONCLUSION', 'PRIVATE_SENTINEL')]:
+ with bound(blob), mock.patch.object(reader, name, value):
+ with self.assertRaises(ValueError): reader.require_binding()
+
+ def test_exact_current_android_identity_and_root_types_are_required(self):
+ reader.validate_archive(archive())
+ for key, value in [('source_sha', '0' * 40), ('workflow_sha', '0' * 40),
+ ('run_id', '1'), ('run_attempt', '2'), ('schema', True),
+ ('platform', 'IOS'), ('diagnostic_only', False), ('smoke', 1),
+ ('native_probe', 'PRIVATE_SENTINEL'), ('commands', [None]),
+ ('commands', [{'label': 'Record Node version', 'command': [1]}])]:
+ data = fixture(); data[key] = value
+ with self.subTest(key=key): self.reject(archive(data))
+
+ def test_unknown_failed_false_null_and_missing_optional_receipts_are_transportable(self):
+ data = fixture(); data.update(build='FAIL', smoke='UNKNOWN', install_succeeded=False,
+ installed_artifact_verified=False, installed_artifact=None, startup_observation=None)
+ data.pop('commands'); data.pop('product_ui')
+ reader.validate_archive(archive(data))
+ data = fixture(); data['product_ui']['samples'][0]['failure_observation'] = None
+ reader.validate_archive(archive(data))
+
+ def test_new_receipts_accept_only_fixed_scoped_normal_and_unavailable_shapes(self):
+ data = observed_data()
+ data['product_ui']['samples'][0]['android_runtime_diagnostic']['facts'][
+ 'onboarding_boundary_observation']['stages']['SKIP_PRESS'] = True
+ reader.validate_archive(archive(data))
+ data['product_ui']['samples'][0]['failed_assertion_snapshot'] = snapshot(False)
+ reader.validate_archive(archive(data))
+ marker_fallback = {'state': 'UNKNOWN', 'scope': 'OPTIONAL_DEV_MARKER_PARSER_UNAVAILABLE',
+ 'cause': 'UNDETERMINED', 'freshness': 'GUEST_CLOCK_UNVERIFIED'}
+ snapshot_fallback = {'schema': 1, 'binding_state': 'UNKNOWN',
+ 'reason': 'COLLECTOR_UNAVAILABLE', 'scope': reader.SNAPSHOT_SCOPE}
+ data['startup_diagnostics']['android_runtime_diagnosis'][
+ 'onboarding_boundary_observation'] = marker_fallback
+ data['product_ui']['controlled_disconnect_retry']['failed_assertion_snapshot'] = snapshot_fallback
+ reader.validate_archive(archive(data))
+ # The old consumer's four-field receipt stays unchanged and adjacent.
+ self.assertEqual(set(data['product_ui']['samples'][0]['failure_observation']),
+ {'scope', 'junit', 'hierarchy', 'product_metro'})
+
+ def test_marker_caps_nullable_positive_stages_and_exact_fallback_are_enforced(self):
+ mutations = [('schema', True), ('producer_total_limit', 64), ('marker_records', 65),
+ ('partial_records', 2), ('scanned_records', 10001), ('input_usable', 1),
+ ('state', False), ('freshness', 'PASS'), ('cause', 'PASS'), ('stages', {}),
+ ('owned_marker_records', -1), ('coverage', 'PRIVATE_SENTINEL'), ('errors', [])]
+ for key, value in mutations:
+ data = observed_data()
+ data['startup_diagnostics']['android_runtime_diagnosis'][
+ 'onboarding_boundary_observation'][key] = value
+ with self.subTest(key=key): self.reject(archive(data))
+ for value in (False, 1, 'PASS'):
+ data = observed_data()
+ data['startup_diagnostics']['android_runtime_diagnosis'][
+ 'onboarding_boundary_observation']['stages']['SKIP_PRESS'] = value
+ self.reject(archive(data))
+ data = observed_data()
+ receipt = data['startup_diagnostics']['android_runtime_diagnosis']['onboarding_boundary_observation']
+ receipt.pop('partial_records'); self.reject(archive(data))
+ data = fixture()
+ data['startup_diagnostics'] = {'android_runtime_diagnosis': {'onboarding_boundary_observation': {
+ 'state': 'UNKNOWN', 'scope': 'OPTIONAL_DEV_MARKER_PARSER_UNAVAILABLE',
+ 'cause': 'UNDETERMINED', 'freshness': 'GUEST_CLOCK_UNVERIFIED', 'stages': {}}}}
+ self.reject(archive(data))
+
+ def test_snapshot_geometry_flags_counts_binding_and_privacy_are_enforced(self):
+ for key, value in [('schema', True), ('node_count', 0), ('node_count', 10001),
+ ('binding_state', 'PASS'), ('reason', 'UNBOUND_FAILED_ASSERTION'),
+ ('tap_coordinates', {'left': 1}), ('visible_to_user', True),
+ ('raw', 'PRIVATE_SENTINEL')]:
+ data = observed_data(); data['product_ui']['samples'][0]['failed_assertion_snapshot'][key] = value
+ self.reject(archive(data))
+ for key, value in [('sequence_number', True), ('sequence_number', 2048), ('selector', 'onboarding_skip')]:
+ data = observed_data()
+ data['product_ui']['samples'][0]['failed_assertion_snapshot']['failed_assertion'][key] = value
+ self.reject(archive(data))
+ for key, value in [('left', -100001), ('bottom', 0), ('right', 1.0), ('top', True)]:
+ data = observed_data()
+ data['product_ui']['samples'][0]['failed_assertion_snapshot']['skip']['bounds'][key] = value
+ self.reject(archive(data))
+ for key, value in [('exact_resource_id_count', 2), ('clickable', 1), ('conflicts', {}),
+ ('bounds', {'left': 0, 'right': 1, 'top': 0, 'bottom': 1, 'text': 'PASS'})]:
+ data = observed_data(); data['product_ui']['samples'][0]['failed_assertion_snapshot']['skip'][key] = value
+ self.reject(archive(data))
+ data = observed_data(); skip = data['product_ui']['samples'][0]['failed_assertion_snapshot']['skip']
+ skip['clickable'] = True; skip['conflicts']['clickable'] = True
+ self.reject(archive(data))
+ for count in (0, 2):
+ data = observed_data(); skip = data['product_ui']['samples'][0]['failed_assertion_snapshot']['skip']
+ skip.update(state='ABSENT' if count == 0 else 'UNKNOWN', bounds=None,
+ exact_resource_id_count=count, conflicts=dict.fromkeys(reader.SKIP_FLAGS))
+ reader.validate_archive(archive(data))
+
+ def test_new_fields_cannot_create_general_raw_or_wrong_path_exemptions(self):
+ for key, value in [('failed_assertion_snapshot', snapshot()),
+ ('onboarding_boundary_observation', boundary()), ('diagnostic_marker_records', 1)]:
+ data = fixture(); data['startup_diagnostics'] = {key: value}
+ self.reject(archive(data))
+ data = fixture(); data['product_ui']['samples'][0]['failure_observation'] = failure_observation()
+ data['product_ui']['samples'][0]['failure_observation']['failed_assertion_snapshot'] = snapshot()
+ self.reject(archive(data))
+ for value in (True, -1, 524289, 'PRIVATE_SENTINEL'):
+ data = observed_data()
+ data['startup_diagnostics']['android_runtime_diagnosis']['runtime_errors'][
+ 'diagnostic_marker_records'] = value
+ self.reject(archive(data))
+ for key, value in [('message', 'PRIVATE_SENTINEL'), ('attributes', {'text': 'PASS'}),
+ ('pid', 1), ('error', 'TypeError: PRIVATE_SENTINEL')]:
+ data = observed_data(); data['product_ui']['samples'][0]['failed_assertion_snapshot'][key] = value
+ self.reject(archive(data))
+
+ def test_legacy_startup_and_optional_sample_retry_hierarchy_flags_are_supported(self):
+ data = fixture()
+ data['product_ui']['samples'][0]['failure_observation'] = failure_observation()
+ data['product_ui']['controlled_disconnect_retry']['failure_observation'] = failure_observation()
+ data['startup_cleanup_errors'] = ['private_startup-observer']
+ data['toolchain'] = {'observed_android_sdk': {
+ 'platforms/android-36': {}, 'build-tools/35.0.0': {}, 'ndk/27.1.12297006': {}}}
+ data['product_ui']['samples'][0]['android_runtime_diagnostic'] = {'status': 'COLLECTED',
+ 'facts': {'host_memory': {'cgroup': {'memory.current': {'lookup_status': 'SUCCESS',
+ 'bytes': 1234}}}}}
+ reader.validate_archive(archive(data))
+ for target in ('legacy', 'sample', 'retry'):
+ malformed = copy.deepcopy(data)
+ hierarchy = (malformed['startup_observation']['hierarchy'] if target == 'legacy' else
+ malformed['product_ui']['samples'][0]['failure_observation']['hierarchy'] if target == 'sample' else
+ malformed['product_ui']['controlled_disconnect_retry']['failure_observation']['hierarchy'])
+ hierarchy['attributes'] = {'text': 'PASS'}
+ self.reject(archive(malformed))
+ data['product_ui']['samples'][0]['failure_observation']['hierarchy']['flags']['onboarding_skip'] = 1
+ self.reject(archive(data))
+ data = fixture(); data['startup_diagnostics'] = {'platforms/android-36': {}}
+ self.reject(archive(data))
+
+ def test_five_samples_retry_and_all_companion_command_paths_are_finite_public_data(self):
+ data = fixture(); data['commands'] = []
+ binary = next(value for value in reader.public_literals() if value.endswith('/bin/maestro'))
+ base = '/home/runner/work/_temp/keeper-native-private/keeper-product-ui-a1b2c3d4/'
+ def add(folder, filename, label, argument=None):
+ output = base + folder
+ args = [binary, '--device', 'emulator-5554', 'test', '--env',
+ 'APP_ID=io.hexawallet.keeper.development']
+ if argument: args += ['--env', argument]
+ args += ['--flatten-debug-output', '--debug-output', output, '--test-output-dir', output,
+ '--format', 'junit', '--output', output + '/junit.xml', '.github/native/' + filename]
+ data['commands'].append({'label': label, 'command': args,
+ 'timeout_seconds': 600, 'exit_code': 0, 'duration_seconds': 1})
+ for number in range(1, 7):
+ add('sample-' + str(number), 'product_retry.yaml' if number == 6 else 'product_first_wallet.yaml',
+ 'Full-product controlled disconnect and Retry fixture' if number == 6 else
+ 'Full-product first-wallet and relaunch UI sample')
+ add('key-ui', 'product_key_acceptance.yaml', 'Normal-app unused-key deletion and native PIN rejection')
+ for phase in ('armed', 'restored'):
+ add('credential-ui/credential_fixture-' + phase, 'credential_fixture.yaml',
+ 'Disposable credential acceptance phase', 'FIXTURE_STAGE=' + phase)
+ for phase in ('blocked', 'recovered'):
+ add('credential-ui/product_credential_' + phase, 'product_credential_' + phase + '.yaml',
+ 'Disposable credential acceptance phase')
+ policy = json.loads(Path(reader.__file__).with_name('044-android-metadata-policy.json').read_bytes())
+ for argument in policy['derived_public_literals']:
+ if argument.startswith('EXPECTED_FIXTURE_ID=history-fixture-'):
+ add('history-ui', 'history_fixture.yaml', 'Native controlled history fixture', argument)
+ add('history-ui', 'history_product.yaml', 'Normal cold-login current history observation')
+ add('vault-ui', 'product_vault_acceptance.yaml',
+ 'Normal-app genuine Vault visible hidden and archived key references')
+ reader.validate_archive(archive(data))
+ for path in (base + 'sample-7', base + 'private-wallet-name',
+ base.replace('a1b2c3d4', 'PRIVATE_SENTINEL') + 'sample-1',
+ '/home/other/private/sample-1'):
+ malformed = copy.deepcopy(data); malformed['commands'][0]['command'][10] = path
+ self.reject(archive(malformed))
+
+ def test_raw_ui_private_keys_values_controls_and_urls_are_rejected_everywhere(self):
+ for key, value in [('raw_logs', 'PRIVATE_SENTINEL'), ('PRIVATE_SENTINEL', 1),
+ ('errors', ['PRIVATE_SENTINEL']), ('scope', 'PRIVATE_SENTINEL\u2028'),
+ ('url', 'https://private.example/token?sig=PRIVATE_SENTINEL'),
+ ('scope', '\x00'), ('\n', 'PASS'), ('attributes', {'text': 'PASS'}),
+ ('children', []), ('hierarchy', {'text': 'PASS'})]:
+ data = fixture(); data['startup_diagnostics'] = {key: value}
+ with self.subTest(key=key): self.reject(archive(data))
+ data = fixture(); data['PRIVATE_SENTINEL'] = 'PASS'; self.reject(archive(data))
+
+ def test_duplicate_nonfinite_deep_oversized_json_and_unsafe_members_reject(self):
+ for raw in ('{"schema":1,"schema":1}', '{"x":NaN}', '{"x":1e999}', b'\xffPRIVATE_SENTINEL'):
+ self.reject(archive(raw=raw))
+ for kwargs in ({'extra': True}, {'name': '../android/metadata.json'}, {'name': 'metadata.json'},
+ {'name': 'android\\metadata.json'}, {'attributes': (stat.S_IFLNK | 0o777) << 16},
+ {'raw': b'x' * (reader.LIMIT + 1)}):
+ self.reject(archive(**kwargs))
+ data = fixture(); data['startup_diagnostics'] = {'errors': ['PASS'] * 1025}
+ self.reject(archive(data))
+ data = fixture(); branch = data['startup_diagnostics'] = {}
+ for _ in range(26): branch['errors'] = {}; branch = branch['errors']
+ self.reject(archive(data))
+ encrypted = bytearray(archive())
+ struct.pack_into('', 'exec'), scope)
+ return scope['maestro_failure_details']('Assertion is false: Create a passcode PRIVATE_SENTINEL')
+
+
+def fixture():
+ return {'schema': 1, 'source_sha': reader.SOURCE, 'workflow_sha': reader.WORKFLOW,
+ 'workflow_ref': reader.WORKFLOW_REF, 'run_id': reader.RUN, 'run_attempt': reader.ATTEMPT,
+ 'platform': 'ANDROID', 'diagnostic_only': True, 'build': 'PASS', 'smoke': 'FAIL',
+ 'native_probe': 'NOT RUN', 'r5_features': 'NOT RUN',
+ 'hardware': 'NOT RUN', 'signing': 'NOT RUN',
+ 'startup_diagnostics': {'metro_errors': ['METRO_ERROR'], 'maestro': {
+ 'failed_commands': [], 'testcase_failures': producer_failures(),
+ 'report': 'PRESENT', 'testcase_statuses': ['ERROR']}},
+ 'startup_observation': {'scope': 'Owned emulator launch window; fixed facts only.',
+ 'collection_errors': [], 'metro': {'rows': [
+ {'stage': 'APP_WINDOW', 'kind': 'ERROR', 'event': 'bundling_error',
+ 'error_type': 'TypeError', 'categories': ['TYPE']},
+ {'stage': 'APP_WINDOW', 'kind': 'RESPONSE', 'request': 'ENTRY_BUNDLE',
+ 'outer_http_status': 500}], 'invalid_rows': 0, 'input_truncated': False,
+ 'row_limit_reached': False, 'emitter_cap_observed': False,
+ 'scope': 'Outer HTTP status only; multipart terminal status is not observed.'},
+ 'hierarchy': {'raw': 'PRIVATE_SENTINEL'}, 'unselected': 'PRIVATE_SENTINEL'},
+ 'commands': [{'raw': 'PRIVATE_SENTINEL'}]}
+
+
+def archive(data=None, raw=None, extra=False):
+ stream = io.BytesIO()
+ with zipfile.ZipFile(stream, 'w', zipfile.ZIP_DEFLATED) as output:
+ output.writestr('android/metadata.json', raw if raw is not None else json.dumps(
+ fixture() if data is None else data))
+ if extra:
+ output.writestr('raw.log', 'PRIVATE_SENTINEL')
+ return stream.getvalue()
+
+
+def bound(blob):
+ return mock.patch.multiple(reader, ZIP_SIZE=len(blob), DIGEST=hashlib.sha256(blob).hexdigest())
+
+
+class Startup7158ReadoutTests(unittest.TestCase):
+ def project(self, data=None, blob=None):
+ blob = archive(data) if blob is None else blob
+ with bound(blob):
+ return reader.project(blob)
+
+ def test_typed_metro_rows_survive_without_commands_hierarchy_or_private_fields(self):
+ result = self.project()
+ self.assertEqual(result['scope'], 'OBSERVATIONS_ONLY_NOT_NATIVE_ACCEPTANCE_OR_CAUSE')
+ observations = result['observations']
+ self.assertEqual(observations['smoke'], 'FAIL')
+ self.assertEqual(observations['startup_observation']['metro']['rows'][0]['categories'], ['TYPE'])
+ self.assertEqual(observations['startup_observation']['metro']['rows'][1]['outer_http_status'], 500)
+ self.assertNotIn('commands', observations)
+ self.assertNotIn('hierarchy', observations['startup_observation'])
+ self.assertNotIn('PRIVATE_SENTINEL', json.dumps(result))
+
+ def test_every_missing_binding_fails_before_kernel_and_input(self):
+ blob = archive()
+ for name in ('WORKFLOW', 'WORKFLOW_REF', 'ZIP_SIZE', 'DIGEST'):
+ with bound(blob), mock.patch.object(reader, name, None), \
+ mock.patch.object(reader.Path, 'read_bytes') as reading, \
+ mock.patch.object(reader.zipfile, 'ZipFile') as archive_open:
+ with self.subTest(name=name), self.assertRaises(Exception):
+ reader.project(blob)
+ reading.assert_not_called()
+ archive_open.assert_not_called()
+
+ def test_pinned_producer_failure_is_fixed_and_preserved_at_exact_path_only(self):
+ self.assertEqual(producer_failures(), ['Maestro assertion failed: Create a passcode'])
+ result = self.project()
+ self.assertEqual(result['observations']['startup_diagnostics']['maestro']['testcase_failures'],
+ producer_failures())
+ self.assertNotIn('PRIVATE_SENTINEL', json.dumps(result))
+ for path in [('startup_diagnostics', 'metro_errors'),
+ ('startup_diagnostics', 'maestro', 'failed_commands'),
+ ('startup_observation', 'collection_errors')]:
+ data = fixture()
+ parent = data
+ for key in path[:-1]:
+ parent = parent[key]
+ parent[path[-1]] = producer_failures()
+ with self.subTest(path=path), self.assertRaises(Exception):
+ self.project(data)
+
+ def test_failure_receipt_requires_bounded_direct_string_list(self):
+ for failures in [None, False, 1, 'Maestro assertion failed: Create a passcode', {},
+ [None], [False], [1], [[]], [producer_failures()],
+ producer_failures() * 11, ['PRIVATE_SENTINEL'], ['PASS'], ['123'],
+ ['Maestro assertion failed: Create a passcode PRIVATE_SENTINEL'],
+ ['Maestro assertion failed: Create a passcode\n']]:
+ data = fixture()
+ data['startup_diagnostics']['maestro']['testcase_failures'] = failures
+ with self.subTest(failures=failures), self.assertRaises(Exception):
+ self.project(data)
+ for maestro in (None, [], 'Maestro assertion failed: Create a passcode'):
+ data = fixture()
+ data['startup_diagnostics']['maestro'] = maestro
+ with self.subTest(maestro=maestro), self.assertRaises(Exception):
+ self.project(data)
+
+ def test_absent_failure_receipt_stays_absent_without_becoming_a_pass(self):
+ for failures in ([], None):
+ data = fixture()
+ if failures is None:
+ del data['startup_diagnostics']['maestro']['testcase_failures']
+ else:
+ data['startup_diagnostics']['maestro']['testcase_failures'] = failures
+ result = self.project(data)
+ self.assertEqual(result['observations']['smoke'], 'FAIL')
+ maestro = result['observations']['startup_diagnostics']['maestro']
+ self.assertEqual('testcase_failures' in maestro, failures is not None)
+
+ def test_wrong_source_platform_attempt_workflow_or_unknown_root_reject(self):
+ for key, value in [('source_sha', '0' * 40), ('platform', 'IOS'), ('run_attempt', '2'),
+ ('workflow_sha', '0' * 40), ('raw_logs', 'PRIVATE_SENTINEL')]:
+ data = fixture()
+ data[key] = value
+ with self.subTest(key=key), self.assertRaises(Exception):
+ self.project(data)
+
+ def test_stage_mismatch_or_missing_observation_does_not_invent_a_result(self):
+ for key, value in [('build', 'FAIL'), ('smoke', 'PASS'), ('native_probe', 'PASS'),
+ ('r5_features', 'PASS'), ('startup_observation', None),
+ ('startup_diagnostics', []), ('product_ui', {'status': 'FAIL'})]:
+ data = fixture()
+ data[key] = value
+ with self.subTest(key=key), self.assertRaises(Exception):
+ self.project(data)
+
+ def test_selected_private_strings_raw_keys_and_unsafe_shapes_reject(self):
+ for change in [lambda d: d['startup_diagnostics'].update(raw='PRIVATE_SENTINEL'),
+ lambda d: d['startup_observation']['metro'].update(message='PRIVATE_SENTINEL'),
+ lambda d: d['startup_observation']['metro']['rows'][0].update(error_type='PRIVATE_SENTINEL'),
+ lambda d: d['startup_observation'].update(metro=['PRIVATE_SENTINEL'])]:
+ data = fixture()
+ change(data)
+ with self.subTest(change=change), self.assertRaises(Exception):
+ self.project(data)
+
+ def test_new_metro_coverage_flags_require_exact_path_and_boolean_type(self):
+ for flag in reader.METRO_BOOLEAN_FIELDS:
+ for value in (0, 1, None, 'false', [], {}):
+ data = fixture()
+ data['startup_observation']['metro'][flag] = value
+ with self.subTest(flag=flag, value=value), self.assertRaises(Exception):
+ self.project(data)
+ for parent in ('startup_diagnostics', 'startup_observation'):
+ data = fixture()
+ data[parent][flag] = True
+ # Unselected observation fields are deliberately omitted. A
+ # projected field cannot borrow the new public key elsewhere.
+ if parent == 'startup_observation':
+ data[parent]['metro']['rows'][0][flag] = True
+ with self.subTest(flag=flag, parent=parent), self.assertRaises(Exception):
+ self.project(data)
+
+ def test_original_zip_identity_layout_duplicates_and_nonfinite_values_reject(self):
+ with self.assertRaises(Exception):
+ reader.project(archive())
+ for blob in [archive(extra=True), archive() + b'PRIVATE_SENTINEL',
+ archive(raw='{"schema":1,"schema":1}'), archive(raw='{"schema":NaN}')]:
+ with self.subTest(size=len(blob)), self.assertRaises(Exception):
+ self.project(blob=blob)
+ blob = archive()
+ with bound(blob), mock.patch.object(reader, 'KERNEL_SHA256', '0' * 64), self.assertRaises(Exception):
+ reader.project(blob)
+
+ def test_symlink_file_alias_fails_without_releasing_observations(self):
+ blob = archive()
+ with tempfile.TemporaryDirectory() as directory, mock.patch.dict(os.environ, {'RUNNER_TEMP': directory}):
+ source = Path(directory) / 'original.zip'
+ source.write_bytes(blob)
+ source.chmod(0o600)
+ (Path(directory) / 'r5-7158-android-startup-fixed.zip').symlink_to(source)
+ with bound(blob), redirect_stdout(io.StringIO()) as output:
+ self.assertEqual(reader.main([]), 1)
+ self.assertEqual(output.getvalue(), 'STARTUP_7158_ANDROID_OBSERVATION_READOUT_FAILED:PRIVATE_FILE\n')
+
+ def test_output_never_forwards_a_private_decoder_failure(self):
+ with mock.patch.object(reader, 'require_binding', side_effect=ValueError('PRIVATE_SENTINEL')), \
+ redirect_stdout(io.StringIO()) as output:
+ self.assertEqual(reader.main([]), 1)
+ self.assertEqual(output.getvalue(), 'STARTUP_7158_ANDROID_OBSERVATION_READOUT_FAILED:SELECTION\n')
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/.github/tests/test_android_startup_diagnosis.py b/.github/tests/test_android_startup_diagnosis.py
new file mode 100644
index 0000000000..9e407aff3f
--- /dev/null
+++ b/.github/tests/test_android_startup_diagnosis.py
@@ -0,0 +1,231 @@
+"""Synthetic metadata/privacy controls; no Android execution or startup credit."""
+from contextlib import redirect_stdout
+import importlib.util
+import io
+import json
+from pathlib import Path
+import subprocess
+import tempfile
+import unittest
+from unittest import mock
+
+NATIVE = Path(__file__).resolve().parents[1] / 'native'
+
+
+def load(name, filename):
+ spec = importlib.util.spec_from_file_location(name, NATIVE / filename)
+ module = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(module)
+ return module
+
+
+diag = load('android_diagnosis_test', 'android_startup_diagnosis.py')
+native = load('hosted_android_diagnosis_test', 'hosted_native.py')
+APP = diag.APP
+
+
+class ParserTests(unittest.TestCase):
+ def test_fixed_types_and_fault_categories_never_export_unknown_names_or_messages(self):
+ for kind in diag.TYPES:
+ observed = diag.faults(kind + ': PRIVATE_SENTINEL /private/wallet seed=x')
+ self.assertIn(kind, observed['exception_types'])
+ self.assertNotIn('PRIVATE_SENTINEL', json.dumps(observed))
+ self.assertEqual(diag.faults('PrivateWalletError: PRIVATE_SENTINEL')['exception_types'], [])
+
+ def test_metro_context_recognizes_new_types_without_codeframes_or_bundle_inference(self):
+ result = diag.metro('ERROR PRIVATE_SENTINEL\n /private/file: TypeError: PRIVATE_SENTINEL\n'
+ ' 12 | ReferenceError: PRIVATE_SENTINEL\n'
+ ' at /private/RangeError:12\nRangeError: PRIVATE_SENTINEL\n'
+ 'TransformError: PRIVATE_SENTINEL\nBUNDLE PRIVATE_SENTINEL')
+ self.assertEqual(result['observed_error_headers'], 3)
+ self.assertEqual(result['exception_types'], ['TypeError', 'RangeError', 'TransformError'])
+ self.assertNotIn('PRIVATE_SENTINEL', json.dumps(result))
+ self.assertNotIn('PASS', json.dumps(result))
+ source = diag.metro('ERROR PRIVATE_SENTINEL\n> 14 | throw new TypeError("PRIVATE_SENTINEL")\n')
+ self.assertEqual(source['exception_types'], [])
+ self.assertEqual(source['fault_categories'], [])
+ oom = diag.metro('FATAL ERROR: Reached heap limit PRIVATE_SENTINEL')
+ self.assertEqual(oom['fault_categories'], ['WORKER_HEAP_EXHAUSTION'])
+
+ def test_inventory_distinguishes_actual_absence_from_failed_malformed_or_partial_lookup(self):
+ data, owned = diag.processes('PID NAME\n100 ' + APP + '\n101 ' + APP + ':worker\n102 private.other\n')
+ self.assertEqual((data['state'], data['matching_process_count']), ('PRESENT', 2))
+ self.assertEqual(owned, {100, 101})
+ data, _ = diag.processes('PID NAME\n102 ' + APP + '.other\n')
+ self.assertEqual(data['state'], 'ABSENT')
+ for payload, usable in [('', True), ('PID NAME', True), ('permission denied', True),
+ ('PID NAME\n100 ' + APP + '\nmalformed', True),
+ ('PID NAME\n100 ' + APP + '\n100 private.other', True),
+ ('PID NAME\n100 ' + APP, False)]:
+ with self.subTest(payload=payload):
+ data, owned = diag.processes(payload, usable)
+ self.assertEqual(data['state'], 'UNKNOWN')
+ self.assertIsNone(data['matching_process_count'])
+ self.assertEqual(owned, set())
+
+ def test_resumed_activity_is_unknown_on_missing_failed_ambiguous_or_malformed_output(self):
+ own = 'topResumedActivity=ActivityRecord{abc u0 ' + APP + '/.MainActivity t1}'
+ other = 'mResumedActivity: ActivityRecord{def u0 private.other/.Private t2}'
+ self.assertEqual(diag.foreground(own)['relation'], 'OWN_APP')
+ self.assertEqual(diag.foreground(other)['relation'], 'OTHER_APP')
+ self.assertEqual(diag.foreground('topResumedActivity=null')['relation'], 'NONE')
+ for payload, usable in [('', True), (own, False), (own + '\n' + other, True),
+ (own + '\nmResumedActivity: PRIVATE_SENTINEL', True)]:
+ self.assertEqual(diag.foreground(payload, usable)['relation'], 'UNKNOWN')
+ self.assertNotIn('private.other', json.dumps(diag.foreground(other)))
+
+ def test_android_log_requires_current_own_process_and_counts_unclassified_records(self):
+ payload = ('10-22 12:00:00.000 100 101 E ReactNativeJS: undefined is not a function PRIVATE_SENTINEL\n'
+ '10-22 12:00:00.001 100 101 F libc: Fatal signal 11 PRIVATE_SENTINEL\n'
+ '10-22 12:00:00.002 100 101 E NewPrivateTag: PRIVATE_SENTINEL\n'
+ '10-22 12:00:00.003 200 201 E ReactNativeJS: RangeError: PRIVATE_SENTINEL\n'
+ 'malformed PRIVATE_SENTINEL\n')
+ result = diag.android_log(payload, {100})
+ self.assertEqual(result['parsed_error_records'], 4)
+ self.assertEqual(result['own_error_records'], 3)
+ self.assertEqual(result['unclassified_own_error_records'], 1)
+ self.assertEqual(result['unparsed_nonempty_lines'], 1)
+ self.assertEqual(result['fault_categories'], ['JS_TYPE_ERROR', 'NATIVE_FATAL_SIGNAL'])
+ self.assertEqual(result['exception_types'], [])
+ unknown = diag.android_log(payload, set())
+ self.assertEqual(unknown['fault_categories'], [])
+ self.assertEqual(unknown['attribution'], 'UNKNOWN_NO_CURRENT_OWN_PROCESS')
+ self.assertNotIn('PRIVATE_SENTINEL', json.dumps(result))
+ self.assertNotIn('NewPrivateTag', json.dumps(result))
+
+ def test_exit_reasons_are_app_scoped_history_with_unknown_freshness_not_current_cause(self):
+ payload = ('process=' + APP + ' reason=5 (APP CRASH(NATIVE)) status=11 PRIVATE_SENTINEL\n'
+ 'process=' + APP + ':worker reason=777 (PRIVATE_SENTINEL)\n'
+ 'process=private.other reason=6 (ANR)\n')
+ result = diag.exit_history(payload)
+ self.assertEqual(result['matching_records'], 2)
+ self.assertEqual(result['reason_categories'], ['NATIVE_CRASH', 'UNRECOGNIZED_REASON'])
+ self.assertEqual(result['freshness'], 'UNKNOWN')
+ self.assertEqual(diag.exit_history(payload, False)['reason_categories'], [])
+ self.assertNotIn('PRIVATE_SENTINEL', json.dumps(result))
+
+
+class CollectionTests(unittest.TestCase):
+ def setUp(self):
+ self.directory = tempfile.TemporaryDirectory()
+ self.addCleanup(self.directory.cleanup)
+ self.root = Path(self.directory.name)
+ self.private = self.root / 'private'
+ self.private.mkdir()
+ (self.private / 'metro.log').write_text('ERROR RangeError: PRIVATE_SENTINEL\n')
+
+ def responder(self, args, stdout, **kwargs):
+ if 'ps' in args:
+ payload = 'PID NAME\n100 ' + APP + '\n200 private.other\n'
+ elif 'activities' in args:
+ payload = 'topResumedActivity=ActivityRecord{abc u0 ' + APP + '/.MainActivity t1}\n'
+ elif 'exit-info' in args:
+ payload = 'process=' + APP + ' reason=5 (APP CRASH(NATIVE)) PRIVATE_SENTINEL\n'
+ else:
+ payload = '10-22 12:00:00.000 100 101 E ReactNativeJS: TypeError: PRIVATE_SENTINEL\n'
+ stdout.write(payload.encode())
+ return subprocess.CompletedProcess(args, 0)
+
+ def test_collection_exports_fixed_facts_and_immediately_purges_private_output(self):
+ with mock.patch.object(subprocess, 'run', side_effect=self.responder):
+ result = diag.collect(self.private, 'emulator-5554')
+ self.assertEqual(result['processes']['state'], 'PRESENT')
+ self.assertEqual(result['foreground_activity']['relation'], 'OWN_APP')
+ self.assertEqual(result['runtime_errors']['fault_categories'], ['JS_TYPE_ERROR'])
+ self.assertEqual(result['metro']['fault_categories'], ['JS_RANGE_ERROR'])
+ self.assertEqual(result['cause'], 'UNDETERMINED')
+ self.assertEqual(result['cleanup_status'], 'DELETED')
+ self.assertFalse((self.private / 'android-startup-diagnosis').exists())
+ self.assertNotIn('PRIVATE_SENTINEL', json.dumps(result))
+ self.assertNotIn('private.other', json.dumps(result))
+ self.assertNotIn(APP, json.dumps(result))
+
+ def test_failed_and_timed_out_commands_never_claim_absence_or_foreground_state(self):
+ for timed_out in [False, True]:
+ def failure(args, stdout, **kwargs):
+ self.responder(args, stdout, **kwargs)
+ if timed_out:
+ raise subprocess.TimeoutExpired(args, 15, output='PRIVATE_SENTINEL')
+ return subprocess.CompletedProcess(args, 1)
+ with self.subTest(timed_out=timed_out), mock.patch.object(subprocess, 'run', side_effect=failure):
+ result = diag.collect(self.private, 'emulator-5554')
+ self.assertEqual(result['processes']['state'], 'UNKNOWN')
+ self.assertEqual(result['foreground_activity']['relation'], 'UNKNOWN')
+ self.assertTrue(all(command['lookup_status'] == 'UNKNOWN' for command in result['commands']))
+ self.assertEqual(result['runtime_errors']['fault_categories'], [])
+ self.assertEqual(result['exit_history']['reason_categories'], [])
+ self.assertFalse((self.private / 'android-startup-diagnosis').exists())
+ self.assertNotIn('PRIVATE_SENTINEL', json.dumps(result))
+
+ def test_truncated_inventory_never_establishes_absence_and_reports_read_coverage(self):
+ def oversize(args, stdout, **kwargs):
+ stdout.write(b'PID NAME\n200 private.other\n' + b'PRIVATE_SENTINEL\n' * 40)
+ return subprocess.CompletedProcess(args, 0)
+ with mock.patch.object(diag, 'LIMIT', 32), mock.patch.object(subprocess, 'run', side_effect=oversize):
+ result = diag.collect(self.private, 'emulator-5554')
+ self.assertEqual(result['processes']['state'], 'UNKNOWN')
+ self.assertTrue(all(command['input_truncated'] for command in result['commands']))
+ self.assertTrue(all(command['bytes_read'] <= 64 for command in result['commands']))
+ self.assertNotIn('PRIVATE_SENTINEL', json.dumps(result))
+
+ def test_bounded_reads_reject_symlink_and_preserve_contiguous_medium_files(self):
+ target = self.root / 'private-target'
+ target.write_text('PRIVATE_SENTINEL')
+ link = self.private / 'link'
+ link.symlink_to(target)
+ with self.assertRaises(ValueError):
+ diag.bounded(link, self.private)
+ path = self.private / 'medium'
+ path.write_text('x' * 60)
+ with mock.patch.object(diag, 'LIMIT', 32):
+ payload, coverage = diag.bounded(path, self.private)
+ self.assertEqual(payload, 'x' * 60)
+ self.assertEqual(coverage['read_scope'], 'FULL')
+ self.assertFalse(coverage['input_truncated'])
+
+ def test_host_memory_reports_only_fixed_numeric_fields_and_unknown_on_invalid_or_missing_files(self):
+ (self.root / 'proc').mkdir()
+ cgroup = self.root / 'sys/fs/cgroup'
+ cgroup.mkdir(parents=True)
+ (self.root / 'proc/meminfo').write_text('MemTotal: 100 kB\nMemAvailable: 50 kB\nSwapTotal: 0 kB\nSwapFree: 0 kB\n')
+ (cgroup / 'memory.current').write_text('1234')
+ (cgroup / 'memory.max').write_text('max')
+ (cgroup / 'memory.events').write_text('oom 2\noom_kill 1\nprivate PRIVATE_SENTINEL')
+ result = diag.host_memory(self.root)
+ self.assertEqual(result['meminfo']['bytes']['MemAvailable'], 50 * 1024)
+ self.assertEqual(result['cgroup']['memory.max']['limit'], 'UNLIMITED')
+ self.assertEqual(result['cgroup']['memory.events']['counts'], {'oom': 2, 'oom_kill': 1})
+ self.assertNotIn('PRIVATE_SENTINEL', json.dumps(result))
+ for extra in ['MemTotal: 200 kB\n', 'MemTotal: PRIVATE_SENTINEL\n']:
+ with (self.root / 'proc/meminfo').open('a') as output:
+ output.write(extra)
+ self.assertEqual(diag.host_memory(self.root)['meminfo']['lookup_status'], 'UNKNOWN')
+ for extra in ['oom 3\n', 'oom PRIVATE_SENTINEL\n']:
+ (cgroup / 'memory.events').write_text('oom 2\noom_kill 1\n' + extra)
+ self.assertEqual(diag.host_memory(self.root)['cgroup']['memory.events']['lookup_status'], 'UNKNOWN')
+ (self.root / 'proc/meminfo').write_text('PRIVATE_SENTINEL')
+ (cgroup / 'memory.current').unlink()
+ result = diag.host_memory(self.root)
+ self.assertEqual(result['meminfo']['lookup_status'], 'UNKNOWN')
+ self.assertEqual(result['cgroup']['memory.current']['lookup_status'], 'UNKNOWN')
+
+ def test_unsafe_device_selector_never_invokes_adb(self):
+ with mock.patch.object(subprocess, 'run') as run, self.assertRaises(ValueError):
+ diag.collect(self.private, 'physical-or-unowned-device')
+ run.assert_not_called()
+
+ def test_existing_failure_hook_preserves_smoke_failure_and_privacy(self):
+ metadata = self.root / 'metadata.json'
+ console = io.StringIO()
+ with mock.patch.multiple(native, PRIVATE=self.private, EVIDENCE=metadata, PLATFORM='ANDROID'), \
+ mock.patch.object(subprocess, 'run', side_effect=self.responder), redirect_stdout(console):
+ native.save({'commands': [], 'build': 'PASS', 'smoke': 'FAIL'})
+ native.record_startup_failure(self.private / 'missing.xml', 'emulator-5554')
+ result = native.read()
+ self.assertEqual(result['smoke'], 'FAIL')
+ self.assertEqual(result['startup_diagnostics']['android_runtime_diagnosis']['cause'], 'UNDETERMINED')
+ self.assertNotIn('PRIVATE_SENTINEL', metadata.read_text() + console.getvalue())
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/.github/tests/test_bea_android_artifact_readout.py b/.github/tests/test_bea_android_artifact_readout.py
new file mode 100644
index 0000000000..a01d6d945e
--- /dev/null
+++ b/.github/tests/test_bea_android_artifact_readout.py
@@ -0,0 +1,141 @@
+"""Original-byte binding and private-output controls, using synthetic receipts only."""
+from contextlib import redirect_stdout
+import copy
+import hashlib
+import importlib.util
+import io
+import json
+import os
+from pathlib import Path
+import tempfile
+import unittest
+from unittest import mock
+import zipfile
+
+SPEC = importlib.util.spec_from_file_location('bea_android_readout',
+ Path(__file__).resolve().parents[1] / 'scripts/read-bea-android-artifact.py')
+reader = importlib.util.module_from_spec(SPEC)
+SPEC.loader.exec_module(reader)
+FIXTURE_SPEC = importlib.util.spec_from_file_location('fixed_android_fixtures',
+ Path(__file__).with_name('test_044_android_artifact_readout.py'))
+fixtures = importlib.util.module_from_spec(FIXTURE_SPEC)
+FIXTURE_SPEC.loader.exec_module(fixtures)
+
+
+TEST_WORKFLOW = 'a' * 40
+TEST_REF = 'KeeperCommunity/bitcoin-keeper/.github/workflows/keeper-native-diagnostic.yml@refs/pull/9999/merge'
+
+
+def fixture():
+ value = fixtures.observed_data()
+ value.update(source_sha=reader.SOURCE, workflow_sha=TEST_WORKFLOW,
+ workflow_ref=TEST_REF, run_id=reader.RUN, run_attempt=reader.ATTEMPT)
+ value['commands'] = [{'PRIVATE_PATH_OR_OTHER_UNEXPORTED_CONTENT': 'PRIVATE_SENTINEL'}]
+ value['product_ui']['performance_scope'] = 'PRIVATE_SENTINEL'
+ value['product_ui']['samples'][0]['unselected_optional_field'] = 'PRIVATE_SENTINEL'
+ return value
+
+
+def archive(data=None, raw=None, extra=False):
+ stream = io.BytesIO()
+ with zipfile.ZipFile(stream, 'w', zipfile.ZIP_DEFLATED) as output:
+ output.writestr('android/metadata.json', raw if raw is not None else json.dumps(fixture() if data is None else data))
+ if extra: output.writestr('raw.log', 'PRIVATE_SENTINEL')
+ return stream.getvalue()
+
+
+def bound(blob):
+ return mock.patch.multiple(reader, ZIP_SIZE=len(blob), DIGEST=hashlib.sha256(blob).hexdigest(),
+ WORKFLOW=TEST_WORKFLOW, WORKFLOW_REF=TEST_REF, PRODUCT_STATUS='FAIL')
+
+
+class BeaAndroidReadoutTests(unittest.TestCase):
+ def project(self, data=None, blob=None):
+ blob = archive(data) if blob is None else blob
+ with bound(blob): return reader.project(blob)
+
+ def test_unavailable_binding_never_accesses_kernel_archive_or_filesystem(self):
+ with mock.patch.object(reader, 'WORKFLOW', None), \
+ mock.patch.object(reader.Path, 'read_bytes') as reading, \
+ mock.patch.object(reader.zipfile, 'ZipFile') as archive_open, \
+ mock.patch.object(reader.os, 'open') as opening:
+ with self.assertRaises(Exception): reader.project(b'PRIVATE_SENTINEL')
+ with redirect_stdout(io.StringIO()) as output:
+ self.assertEqual(reader.main([]), 1)
+ self.assertEqual(output.getvalue(), 'BEA_ANDROID_OBSERVATION_READOUT_FAILED:SELECTION\n')
+ reading.assert_not_called(); archive_open.assert_not_called(); opening.assert_not_called()
+
+ def test_each_missing_binding_stays_closed_before_kernel_or_input_access(self):
+ blob = archive()
+ for name in ('WORKFLOW', 'WORKFLOW_REF', 'ZIP_SIZE', 'DIGEST', 'PRODUCT_STATUS'):
+ with bound(blob), mock.patch.object(reader, name, None), \
+ mock.patch.object(reader.Path, 'read_bytes') as reading, \
+ mock.patch.object(reader.zipfile, 'ZipFile') as archive_open:
+ with self.subTest(name=name), self.assertRaises(Exception): reader.project(blob)
+ reading.assert_not_called(); archive_open.assert_not_called()
+
+ def test_new_fixed_marker_label_is_finite_and_other_values_remain_rejected(self):
+ data = fixture()
+ facts = data['product_ui']['samples'][0]['android_runtime_diagnostic']['facts']
+ facts['commands'] = [{'label': 'onboarding-markers', 'lookup_status': 'SUCCESS'}]
+ self.assertEqual(self.project(data)['observations']['product_ui']['samples'][0][
+ 'android_runtime_diagnostic']['facts']['commands'][0]['label'], 'onboarding-markers')
+ facts['commands'][0]['label'] = 'PRIVATE_SENTINEL'
+ with self.assertRaises(Exception): self.project(data)
+
+ def test_bounded_failure_facts_survive_and_unselected_content_never_exports(self):
+ data = fixture(); result = self.project(data)
+ self.assertEqual(result['scope'], 'OBSERVATIONS_ONLY_NOT_NATIVE_ACCEPTANCE_OR_CAUSE')
+ self.assertEqual(result['observations']['smoke'], 'PASS')
+ self.assertEqual(result['observations']['product_ui']['status'], 'FAIL')
+ self.assertEqual(result['observations']['product_ui']['samples'][0]['failure_observation'],
+ data['product_ui']['samples'][0]['failure_observation'])
+ self.assertEqual(result['observations']['product_ui']['samples'][0]['failed_assertion_snapshot'],
+ data['product_ui']['samples'][0]['failed_assertion_snapshot'])
+ self.assertEqual(len(result['metadata_sha256']), 64)
+ self.assertNotIn('commands', result['observations'])
+ self.assertNotIn('PRIVATE_SENTINEL', json.dumps(result))
+
+ def test_wrong_source_platform_attempt_workflow_and_unknown_root_reject(self):
+ for key, value in [('source_sha', '0' * 40), ('platform', 'IOS'), ('run_attempt', '2'),
+ ('workflow_sha', '0' * 40), ('raw_logs', 'PRIVATE_SENTINEL')]:
+ data = fixture(); data[key] = value
+ with self.subTest(key=key), self.assertRaises(Exception): self.project(data)
+
+ def test_projected_raw_values_unknown_nested_data_and_bad_snapshot_types_reject(self):
+ changes = [lambda s: s['failure_observation'].update(raw_logs='PRIVATE_SENTINEL'),
+ lambda s: s['failure_observation']['hierarchy']['flags'].update(onboarding_skip=1),
+ lambda s: s['failed_assertion_snapshot']['skip'].update(clickable='false'),
+ lambda s: s['failed_assertion_snapshot'].update(node_count=10001),
+ lambda s: s['failed_assertion_snapshot'].update(raw='PRIVATE_SENTINEL'),
+ lambda s: s['android_runtime_diagnostic']['facts'].update(message='PRIVATE_SENTINEL'),
+ lambda s: s['failed_assertion_snapshot']['failed_assertion'].update(selector='onboarding_skip')]
+ for change in changes:
+ data = fixture(); change(data['product_ui']['samples'][0])
+ with self.subTest(change=change), self.assertRaises(Exception): self.project(data)
+
+ def test_missing_failed_sample_wrong_product_types_and_unsafe_json_reject(self):
+ for product in [None, [], {'status': 'PASS', 'samples': [{}]},
+ {'status': 'FAIL', 'samples': []}, {'status': 'FAIL', 'samples': [None]},
+ {'status': 'FAIL', 'samples': [{}] * 7}]:
+ data = fixture(); data['product_ui'] = product
+ with self.subTest(product=product), self.assertRaises(Exception): self.project(data)
+ for blob in [archive(raw='{"schema":1,"schema":1}'), archive(raw='{"schema":NaN}'),
+ archive(extra=True), archive() + b'PRIVATE_SENTINEL']:
+ with self.subTest(size=len(blob)), self.assertRaises(Exception): self.project(blob=blob)
+
+ def test_original_digest_kernel_change_and_private_file_alias_fail_without_observations(self):
+ blob = archive()
+ with self.assertRaises(Exception): reader.project(blob)
+ with bound(blob), mock.patch.object(reader, 'KERNEL_SHA256', '0' * 64), self.assertRaises(Exception):
+ reader.project(blob)
+ with tempfile.TemporaryDirectory() as directory, mock.patch.dict(os.environ, {'RUNNER_TEMP': directory}):
+ source = Path(directory) / 'original.zip'; source.write_bytes(blob); source.chmod(0o600)
+ target = Path(directory) / 'r5-bea-android-fixed.zip'; target.symlink_to(source)
+ with bound(blob), redirect_stdout(io.StringIO()) as output:
+ self.assertEqual(reader.main([]), 1)
+ self.assertEqual(output.getvalue(), 'BEA_ANDROID_OBSERVATION_READOUT_FAILED:PRIVATE_FILE\n')
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/.github/tests/test_canonical_metadata.py b/.github/tests/test_canonical_metadata.py
new file mode 100644
index 0000000000..fc3733ac46
--- /dev/null
+++ b/.github/tests/test_canonical_metadata.py
@@ -0,0 +1,52 @@
+import importlib.util
+import io
+from pathlib import Path
+import stat
+import unittest
+import zipfile
+
+spec = importlib.util.spec_from_file_location('canonical_metadata',
+ Path(__file__).resolve().parents[1] / 'native/canonical_metadata.py')
+reader = importlib.util.module_from_spec(spec)
+spec.loader.exec_module(reader)
+
+
+def archive(entries):
+ output = io.BytesIO()
+ with zipfile.ZipFile(output, 'w', compression=zipfile.ZIP_DEFLATED) as file:
+ for name, body in entries:
+ file.writestr(name, body)
+ return output.getvalue()
+
+
+class ArchiveTests(unittest.TestCase):
+ def test_single_bounded_receipt(self):
+ self.assertEqual(reader.read_metadata(archive([('metadata.json', b'{"schema":1}')])), b'{"schema":1}')
+
+ def test_path_traversal_and_other_names_rejected(self):
+ for name in ('../metadata.json', '/metadata.json', 'ios/metadata.json', 'other.json'):
+ with self.assertRaises(ValueError):
+ reader.read_metadata(archive([(name, b'{}')]))
+
+ def test_multiple_members_rejected(self):
+ with self.assertRaises(ValueError):
+ reader.read_metadata(archive([('metadata.json', b'{}'), ('private.log', b'PRIVATE')]))
+
+ def test_symlink_rejected(self):
+ info = zipfile.ZipInfo('metadata.json')
+ info.external_attr = (stat.S_IFLNK | 0o777) << 16
+ with self.assertRaises(ValueError):
+ reader.read_metadata(archive([(info, b'/private/file')]))
+
+ def test_decompression_bomb_and_oversized_archive_rejected(self):
+ for raw in (archive([('metadata.json', b'x' * 524289)]), b'x' * 1048577):
+ with self.assertRaises(ValueError):
+ reader.read_metadata(raw)
+
+ def test_truncated_archive_rejected(self):
+ with self.assertRaises(zipfile.BadZipFile):
+ reader.read_metadata(archive([('metadata.json', b'{}')])[:20])
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/.github/tests/test_current_android_artifact_readout.py b/.github/tests/test_current_android_artifact_readout.py
new file mode 100644
index 0000000000..7adbf5d576
--- /dev/null
+++ b/.github/tests/test_current_android_artifact_readout.py
@@ -0,0 +1,287 @@
+"""Portable fabricated metadata controls; no download, app or native execution."""
+from contextlib import redirect_stdout
+import base64
+import copy
+import hashlib
+import importlib.util
+import io
+import json
+import os
+from pathlib import Path
+import stat
+import struct
+import tempfile
+import unittest
+from unittest import mock
+import zipfile
+
+SPEC = importlib.util.spec_from_file_location('current_android_readout',
+ Path(__file__).resolve().parents[1] / 'scripts/read-current-android-artifact.py')
+reader = importlib.util.module_from_spec(SPEC)
+SPEC.loader.exec_module(reader)
+
+
+def fixture():
+ return {'schema': 1, 'source_sha': reader.SOURCE, 'workflow_sha': reader.WORKFLOW,
+ 'workflow_ref': reader.WORKFLOW_REF, 'run_id': reader.RUN, 'run_attempt': reader.ATTEMPT,
+ 'platform': 'ANDROID', 'diagnostic_only': True, 'build': 'PASS', 'smoke': 'PASS',
+ 'native_probe': 'PASS', 'r5_features': 'PASS', 'hardware': 'NOT RUN', 'signing': 'NOT RUN',
+ 'app_id': 'io.hexawallet.keeper.development', 'commands': [{
+ 'label': 'Record Node version', 'command': ['node', '--version'],
+ 'timeout_seconds': 120, 'exit_code': 0, 'duration_seconds': 0.1}],
+ 'startup_observation': {'hierarchy': {**dict.fromkeys(reader.STARTUP_FLAGS, False),
+ 'snapshot_count': 1}},
+ 'product_ui': {'status': 'FAIL', 'samples': [{'sample': 1, 'status': 'FAIL'}],
+ 'controlled_disconnect_retry': {'status': 'NOT RUN'}}}
+
+
+def failure_observation():
+ return {'scope': 'Failed-sample files and bound owned Metro only; observations do not prove current visibility, route, tap delivery or cause.',
+ 'junit': {'state': 'ERROR_RECORDED', 'failed_selector': 'start_new_tile',
+ 'failure_kind': 'ASSERT_VISIBLE'},
+ 'hierarchy': {'state': 'PARTIAL', 'snapshot_count': 1, 'node_count': 10,
+ 'rejected_snapshots': 1, 'snapshot_limit_exceeded': False,
+ 'scope': reader.PRODUCT_HIERARCHY_SCOPE,
+ 'flags': {**dict.fromkeys(reader.PRODUCT_FLAGS), 'onboarding_skip': True}},
+ 'product_metro': {'state': 'UNKNOWN', 'scope': 'Bound product-sample console window; markers are not cause or request proof.',
+ 'process_state': 'ALIVE', 'exit_code': None}}
+
+
+def archive(data=None, raw=None, name='android/metadata.json', attributes=None, extra=False):
+ stream = io.BytesIO()
+ with zipfile.ZipFile(stream, 'w', zipfile.ZIP_DEFLATED) as output:
+ entry = zipfile.ZipInfo(name)
+ entry.compress_type = zipfile.ZIP_DEFLATED
+ entry.external_attr = attributes if attributes is not None else (stat.S_IFREG | 0o600) << 16
+ output.writestr(entry, raw if raw is not None else json.dumps(fixture() if data is None else data))
+ if extra:
+ output.writestr('raw.log', 'PRIVATE_SENTINEL')
+ return stream.getvalue()
+
+
+def bound(blob):
+ # Fabricated ZIP bytes only; production conclusion tuple remains unchanged.
+ return mock.patch.multiple(reader, ARTIFACT='1', ZIP_SIZE=len(blob),
+ ZIP_SHA256=hashlib.sha256(blob).hexdigest(), NATIVE_CONCLUSION='failure',
+ BUILD_CONCLUSION='success', PROBES_CONCLUSION='failure')
+
+
+class AndroidByteReadoutTests(unittest.TestCase):
+ def reject(self, blob):
+ with self.assertRaises(Exception):
+ reader.validate_archive(blob)
+
+ def test_production_bindings_match_observed_receipt_and_wrong_bytes_never_emit(self):
+ self.assertEqual((reader.ARTIFACT, reader.ZIP_SIZE, reader.ZIP_SHA256,
+ reader.NATIVE_CONCLUSION, reader.BUILD_CONCLUSION, reader.PROBES_CONCLUSION),
+ ('12466091444', 8950, '5c3210a6b0af7bf9ea0cddb61fd1494714e8cfac0db8385960fb6390f92aa545',
+ 'failure', 'success', 'failure'))
+ reader.require_binding()
+ with tempfile.TemporaryDirectory() as directory, mock.patch.dict(os.environ, {'RUNNER_TEMP': directory}), \
+ mock.patch.object(reader, 'public_literals') as policy, \
+ mock.patch.object(reader, 'validate_archive') as validating:
+ path = Path(directory) / 'r5-current-android-fixed.zip'
+ path.write_bytes(bytes(reader.ZIP_SIZE)); path.chmod(0o600)
+ output = io.StringIO()
+ with redirect_stdout(output):
+ self.assertEqual(reader.main([]), 1)
+ self.assertEqual(output.getvalue(), 'FIXED_ANDROID_ARTIFACT_BYTE_READOUT_FAILED\n')
+ policy.assert_not_called(); validating.assert_not_called()
+
+ def test_partial_binding_never_reads_input_and_invalid_types_fail_closed(self):
+ blob = archive()
+ for name in ('ARTIFACT', 'ZIP_SHA256', 'ZIP_SIZE', 'NATIVE_CONCLUSION',
+ 'BUILD_CONCLUSION', 'PROBES_CONCLUSION'):
+ with bound(blob), mock.patch.object(reader, name, None), \
+ mock.patch.object(reader, 'checked_bytes') as checking, \
+ mock.patch.object(reader, 'Path') as paths, \
+ mock.patch.object(reader.os, 'open') as opening, \
+ mock.patch.object(reader, 'public_literals') as policy:
+ with redirect_stdout(io.StringIO()):
+ self.assertEqual(reader.main([]), 1)
+ checking.assert_not_called()
+ paths.assert_not_called(); opening.assert_not_called(); policy.assert_not_called()
+ for name, value in [('ARTIFACT', True), ('ZIP_SIZE', True), ('ZIP_SIZE', -1),
+ ('ZIP_SHA256', 'PRIVATE_SENTINEL'), ('NATIVE_CONCLUSION', 1),
+ ('NATIVE_CONCLUSION', 'success'), ('BUILD_CONCLUSION', 'failure'),
+ ('PROBES_CONCLUSION', 'success'), ('BUILD_CONCLUSION', 'PRIVATE_SENTINEL')]:
+ with bound(blob), mock.patch.object(reader, name, value):
+ with self.assertRaises(ValueError): reader.require_binding()
+
+ def test_exact_current_android_identity_and_root_types_are_required(self):
+ reader.validate_archive(archive())
+ for key, value in [('source_sha', '0' * 40), ('workflow_sha', '0' * 40),
+ ('run_id', '1'), ('run_attempt', '2'), ('schema', True),
+ ('platform', 'IOS'), ('diagnostic_only', False), ('smoke', 1),
+ ('native_probe', 'PRIVATE_SENTINEL'), ('commands', [None]),
+ ('commands', [{'label': 'Record Node version', 'command': [1]}])]:
+ data = fixture(); data[key] = value
+ with self.subTest(key=key): self.reject(archive(data))
+
+ def test_unknown_failed_false_null_and_missing_optional_receipts_are_transportable(self):
+ data = fixture(); data.update(build='FAIL', smoke='UNKNOWN', install_succeeded=False,
+ installed_artifact_verified=False, installed_artifact=None, startup_observation=None)
+ data.pop('commands'); data.pop('product_ui')
+ reader.validate_archive(archive(data))
+ data = fixture(); data['product_ui']['samples'][0]['failure_observation'] = None
+ reader.validate_archive(archive(data))
+
+ def test_legacy_startup_and_optional_sample_retry_hierarchy_flags_are_supported(self):
+ data = fixture()
+ data['product_ui']['samples'][0]['failure_observation'] = failure_observation()
+ data['product_ui']['controlled_disconnect_retry']['failure_observation'] = failure_observation()
+ data['startup_cleanup_errors'] = ['private_startup-observer']
+ data['toolchain'] = {'observed_android_sdk': {
+ 'platforms/android-36': {}, 'build-tools/35.0.0': {}, 'ndk/27.1.12297006': {}}}
+ data['product_ui']['samples'][0]['android_runtime_diagnostic'] = {'status': 'COLLECTED',
+ 'facts': {'host_memory': {'cgroup': {'memory.current': {'lookup_status': 'SUCCESS',
+ 'bytes': 1234}}}}}
+ reader.validate_archive(archive(data))
+ for target in ('legacy', 'sample', 'retry'):
+ malformed = copy.deepcopy(data)
+ hierarchy = (malformed['startup_observation']['hierarchy'] if target == 'legacy' else
+ malformed['product_ui']['samples'][0]['failure_observation']['hierarchy'] if target == 'sample' else
+ malformed['product_ui']['controlled_disconnect_retry']['failure_observation']['hierarchy'])
+ hierarchy['attributes'] = {'text': 'PASS'}
+ self.reject(archive(malformed))
+ data['product_ui']['samples'][0]['failure_observation']['hierarchy']['flags']['onboarding_skip'] = 1
+ self.reject(archive(data))
+ data = fixture(); data['startup_diagnostics'] = {'platforms/android-36': {}}
+ self.reject(archive(data))
+
+ def test_five_samples_retry_and_all_companion_command_paths_are_finite_public_data(self):
+ data = fixture(); data['commands'] = []
+ binary = next(value for value in reader.public_literals() if value.endswith('/bin/maestro'))
+ base = '/home/runner/work/_temp/keeper-native-private/keeper-product-ui-a1b2c3d4/'
+ def add(folder, filename, label, argument=None):
+ output = base + folder
+ args = [binary, '--device', 'emulator-5554', 'test', '--env',
+ 'APP_ID=io.hexawallet.keeper.development']
+ if argument: args += ['--env', argument]
+ args += ['--flatten-debug-output', '--debug-output', output, '--test-output-dir', output,
+ '--format', 'junit', '--output', output + '/junit.xml', '.github/native/' + filename]
+ data['commands'].append({'label': label, 'command': args,
+ 'timeout_seconds': 600, 'exit_code': 0, 'duration_seconds': 1})
+ for number in range(1, 7):
+ add('sample-' + str(number), 'product_retry.yaml' if number == 6 else 'product_first_wallet.yaml',
+ 'Full-product controlled disconnect and Retry fixture' if number == 6 else
+ 'Full-product first-wallet and relaunch UI sample')
+ add('key-ui', 'product_key_acceptance.yaml', 'Normal-app unused-key deletion and native PIN rejection')
+ for phase in ('armed', 'restored'):
+ add('credential-ui/credential_fixture-' + phase, 'credential_fixture.yaml',
+ 'Disposable credential acceptance phase', 'FIXTURE_STAGE=' + phase)
+ for phase in ('blocked', 'recovered'):
+ add('credential-ui/product_credential_' + phase, 'product_credential_' + phase + '.yaml',
+ 'Disposable credential acceptance phase')
+ policy = json.loads(Path(reader.__file__).with_name('current-android-metadata-policy.json').read_bytes())
+ for argument in policy['derived_public_literals']:
+ if argument.startswith('EXPECTED_FIXTURE_ID=history-fixture-'):
+ add('history-ui', 'history_fixture.yaml', 'Native controlled history fixture', argument)
+ add('history-ui', 'history_product.yaml', 'Normal cold-login current history observation')
+ add('vault-ui', 'product_vault_acceptance.yaml',
+ 'Normal-app genuine Vault visible hidden and archived key references')
+ reader.validate_archive(archive(data))
+ for path in (base + 'sample-7', base + 'private-wallet-name',
+ base.replace('a1b2c3d4', 'PRIVATE_SENTINEL') + 'sample-1',
+ '/home/other/private/sample-1'):
+ malformed = copy.deepcopy(data); malformed['commands'][0]['command'][10] = path
+ self.reject(archive(malformed))
+
+ def test_raw_ui_private_keys_values_controls_and_urls_are_rejected_everywhere(self):
+ for key, value in [('raw_logs', 'PRIVATE_SENTINEL'), ('PRIVATE_SENTINEL', 1),
+ ('errors', ['PRIVATE_SENTINEL']), ('scope', 'PRIVATE_SENTINEL\u2028'),
+ ('url', 'https://private.example/token?sig=PRIVATE_SENTINEL'),
+ ('scope', '\x00'), ('\n', 'PASS'), ('attributes', {'text': 'PASS'}),
+ ('children', []), ('hierarchy', {'text': 'PASS'})]:
+ data = fixture(); data['startup_diagnostics'] = {key: value}
+ with self.subTest(key=key): self.reject(archive(data))
+ data = fixture(); data['PRIVATE_SENTINEL'] = 'PASS'; self.reject(archive(data))
+
+ def test_duplicate_nonfinite_deep_oversized_json_and_unsafe_members_reject(self):
+ for raw in ('{"schema":1,"schema":1}', '{"x":NaN}', '{"x":1e999}', b'\xffPRIVATE_SENTINEL'):
+ self.reject(archive(raw=raw))
+ for kwargs in ({'extra': True}, {'name': '../android/metadata.json'}, {'name': 'metadata.json'},
+ {'name': 'android\\metadata.json'}, {'attributes': (stat.S_IFLNK | 0o777) << 16},
+ {'raw': b'x' * (reader.LIMIT + 1)}):
+ self.reject(archive(**kwargs))
+ data = fixture(); data['startup_diagnostics'] = {'errors': ['PASS'] * 1025}
+ self.reject(archive(data))
+ data = fixture(); branch = data['startup_diagnostics'] = {}
+ for _ in range(26): branch['errors'] = {}; branch = branch['errors']
+ self.reject(archive(data))
+ encrypted = bytearray(archive())
+ struct.pack_into('synthetic',
+ 'PRIVATE_SENTINEL \u79d8\u5bc6 \u03bc\u03c5\u03c3\u03c4\u03b9\u03ba\u03cc \u202esecret \x00\x1b[31mprivate\x1b[0m',
+ 'PRIVATE_SENTINEL first line\nprivate continuation\rprivate last line',
+ 'PRIVATE_SENTINEL ' + 'long arbitrary private text ' * 100,
+ ]
+ routes = [
+ (native.failure_details, 'error: {}', ['TOOL_ERROR']),
+ (native.failure_details, 'e: {}', ['KOTLIN_COMPILER_ERROR']),
+ (native.failure_details, 'FAILURE: {}', ['BUILD_FAILURE']),
+ (native.failure_details, 'Caused by: {}', ['TOOL_ERROR']),
+ (native.maestro_failure_details, 'Unable to launch app {}', ['Maestro app launch failed']),
+ (native.maestro_failure_details, 'Failed to connect {}', ['Maestro connection failed']),
+ (native.maestro_failure_details, 'Failed to start {}', ['Maestro driver start failed']),
+ (native.maestro_failure_details, 'No devices found {}', ['Maestro device unavailable']),
+ (native.android_startup_errors, 'E/AndroidRuntime( 123): FATAL EXCEPTION: {}', ['ANDROID_RUNTIME_ERROR']),
+ (native.android_startup_errors, 'E/ReactNativeJS( 123): TypeError: {}', ['REACT_NATIVE_JS_ERROR']),
+ (native.android_startup_errors, 'F/ReactNative( 123): Could not {}', ['REACT_NATIVE_ERROR']),
+ (native.metro_startup_errors, 'ERROR {}', ['METRO_ERROR']),
+ (native.metro_startup_errors, 'SyntaxError: {}', ['METRO_SYNTAX_ERROR']),
+ (native.metro_startup_errors, 'TypeError: {}', ['METRO_TYPE_ERROR']),
+ (native.metro_startup_errors, 'ReferenceError: {}', ['METRO_REFERENCE_ERROR']),
+ (native.metro_startup_errors, 'Unable to resolve module {}', ['METRO_MODULE_RESOLUTION_ERROR']),
+ ]
+ for payload in payloads:
+ for classify, template, expected in routes:
+ with self.subTest(route=template, payload=payload[:70]):
+ self.assertEqual(classify(template.format(payload)), expected)
+ with self.subTest(route='ios', payload=payload[:70]):
+ diagnostics = native.ios_startup_diagnostics(
+ '2026-10-18 06:00:00.000 E hexa_keeper_dev[123:abc] ' + payload, 'hexa_keeper_dev')
+ self.assertEqual(diagnostics['errors'], ['IOS_STARTUP_ERROR'])
+
+ def test_general_failure_categories_cover_install_blockers_without_excerpts(self):
+ messages = [
+ ('error: lockfile needs to be updated', 'DEPENDENCY_LOCK_MISMATCH'),
+ ('[!] could not find compatible versions', 'DEPENDENCY_LOCK_MISMATCH'),
+ ('The sandbox is not in sync', 'DEPENDENCY_LOCK_MISMATCH'),
+ ('error: no space left on device', 'DISK_SPACE_EXHAUSTED'),
+ ('error: command not found', 'REQUIRED_TOOL_UNAVAILABLE'),
+ ('[!] requires a higher minimum deployment target', 'IOS_DEPLOYMENT_TARGET_UNSUPPORTED'),
+ ('[!] other pod failure', 'COCOAPODS_ERROR'),
+ ('A problem occurred', 'BUILD_FAILURE'),
+ ('Execution failed', 'BUILD_FAILURE'),
+ ('Could not find a dependency', 'DEPENDENCY_OR_TOOL_FAILURE'),
+ ('> compiler detail', 'TOOL_ERROR'),
+ ]
+ for message, category in messages:
+ with self.subTest(message=message):
+ self.assertEqual(native.failure_details(message + ' PRIVATE_SENTINEL'), [category])
+ self.assertEqual(native.failure_details('ordinary PRIVATE_SENTINEL\n> Task :compile\n'
+ ' 12 | error: PRIVATE_SENTINEL'), [])
+ self.assertEqual(native.failure_details('error: PRIVATE_SENTINEL\n' * 1000), ['TOOL_ERROR'])
+ self.assertEqual(native.metro_startup_errors('ERROR PRIVATE_SENTINEL\n' * 1000), ['METRO_ERROR'])
+ self.assertEqual(native.android_startup_errors('E/OtherApp( 1): Error: PRIVATE_SENTINEL'), [])
+
+ def test_failed_command_metadata_console_and_exception_do_not_export_private_text(self):
+ script = self.root / 'failed-command.py'
+ script.write_text('print("error: PRIVATE_SENTINEL arbitrary recovery text"); raise SystemExit(3)')
+ console = io.StringIO()
+ with redirect_stdout(console), self.assertRaises(RuntimeError) as failure:
+ native.command([sys.executable, str(script)], 'Build fixture')
+ record = native.read()['commands'][0]
+ self.assertEqual(record['exit_code'], 3)
+ self.assertEqual(record['redacted_tool_errors'], ['TOOL_ERROR'])
+ self.assertIn('TOOL_ERROR', console.getvalue())
+ self.assertNotIn('PRIVATE_SENTINEL', native.EVIDENCE.read_text() + console.getvalue() + str(failure.exception))
+ self.assertIn('PRIVATE_SENTINEL', (native.PRIVATE / 'command-001.log').read_text())
+
+ def test_startup_collector_exports_only_categories_and_preserves_failure(self):
+ native.PRIVATE.mkdir()
+ native.save({'commands': [{'label': 'Assert startup and disposable passcode transition'}],
+ 'build': 'PASS', 'smoke': 'FAIL'})
+ (native.PRIVATE / 'command-001.log').write_text('Unable to launch app PRIVATE_SENTINEL wallet text\n')
+ (native.PRIVATE / 'metro.log').write_text('ERROR PRIVATE_SENTINEL wallet text\n')
+ report = native.PRIVATE / 'smoke-junit.xml'
+ report.write_text(''
+ 'Failed to connect PRIVATE_SENTINEL wallet text\nUI hierarchy: PRIVATE_SENTINEL'
+ '')
+
+ def android_log(args, stdout, **kwargs):
+ stdout.write(b'E/AndroidRuntime( 123): FATAL EXCEPTION: PRIVATE_SENTINEL wallet text\n')
+ return subprocess.CompletedProcess(args, 0)
+
+ console = io.StringIO()
+ with redirect_stdout(console), mock.patch.object(subprocess, 'run', side_effect=android_log):
+ native.record_startup_failure(report, 'fixture-emulator')
+ data = native.read()
+ details = data['startup_diagnostics']
+ self.assertEqual((data['build'], data['smoke']), ('PASS', 'FAIL'))
+ self.assertEqual(details['maestro']['testcase_statuses'], ['ERROR'])
+ self.assertEqual(details['maestro']['failed_commands'], ['Maestro app launch failed'])
+ self.assertEqual(details['maestro']['testcase_failures'], ['Maestro connection failed'])
+ self.assertEqual(details['metro_errors'], ['METRO_ERROR'])
+ self.assertEqual(details['android_errors']['errors'], ['ANDROID_RUNTIME_ERROR'])
+ self.assertNotIn('PRIVATE_SENTINEL', json.dumps(data) + console.getvalue())
+
+ def test_cli_failure_never_prints_arbitrary_exception_text(self):
+ console = io.StringIO()
+ # The record phase fails before invoking a native tool. Exercise the real
+ # CLI exception boundary, including its nonzero exit, with a private error.
+ with mock.patch.dict(native.os.environ, {'KEEPER_NATIVE_PLATFORM': 'ANDROID'}), \
+ mock.patch.object(sys, 'argv', [str(Path(native.__file__)), 'record']), \
+ mock.patch.object(subprocess, 'check_output', side_effect=RuntimeError('PRIVATE_SENTINEL')), \
+ redirect_stderr(console), self.assertRaises(SystemExit) as failure:
+ runpy.run_path(native.__file__, run_name='__main__')
+ self.assertEqual(failure.exception.code, 1)
+ self.assertIn('Hosted native validation failed', console.getvalue())
+ self.assertNotIn('PRIVATE_SENTINEL', console.getvalue())
diff --git a/.github/tests/test_driver_diagnosis.py b/.github/tests/test_driver_diagnosis.py
new file mode 100644
index 0000000000..b441d0e0a4
--- /dev/null
+++ b/.github/tests/test_driver_diagnosis.py
@@ -0,0 +1,456 @@
+"""Offline driver-diagnostic controls; these supply no native acceptance."""
+
+import hashlib
+import importlib.util
+import io
+import json
+import os
+from pathlib import Path
+import plistlib
+import sys
+import tempfile
+import threading
+import unittest
+from unittest import mock
+import zipfile
+
+
+DIRECTORY = Path(__file__).resolve().parents[1] / 'native'
+SPEC_NATIVE = importlib.util.spec_from_file_location('driver_native_harness', DIRECTORY / 'hosted_native.py')
+native = importlib.util.module_from_spec(SPEC_NATIVE)
+SPEC_NATIVE.loader.exec_module(native)
+SPEC = importlib.util.spec_from_file_location('driver_diagnosis_controls', DIRECTORY / 'driver_diagnosis.py')
+diagnosis = importlib.util.module_from_spec(SPEC)
+with mock.patch.dict(sys.modules, {'hosted_native': native}):
+ SPEC.loader.exec_module(diagnosis)
+
+
+class DriverDiagnosisTest(unittest.TestCase):
+ def setUp(self):
+ temporary = tempfile.TemporaryDirectory()
+ self.addCleanup(temporary.cleanup)
+ self.root = Path(temporary.name)
+ self.private = self.root / 'private'
+ self.private.mkdir()
+ patch = mock.patch.multiple(native, PRIVATE=self.private, ROOT=self.root,
+ EVIDENCE=self.root / 'metadata.json', PLATFORM='IOS')
+ patch.start()
+ self.addCleanup(patch.stop)
+ native.save({'commands': [], 'toolchain': {'sdk': '18.5'},
+ 'build': 'NOT RUN', 'smoke': 'NOT RUN'})
+ self.device = '12345678-1234-1234-1234-123456789ABC'
+
+ def runner_jar(self, name='maestro-ios-driver.jar', sdk='iphonesimulator26.4', minimum='15.0'):
+ inner = io.BytesIO()
+ with zipfile.ZipFile(inner, 'w') as runner:
+ for path in [diagnosis.RUNNER_NAME + '.app/Info.plist',
+ diagnosis.RUNNER_NAME + '.app/PlugIns/maestro-driver-iosUITests.xctest/Info.plist']:
+ runner.writestr(path, plistlib.dumps({'DTSDKName': sdk, 'DTXcode': '2640',
+ 'MinimumOSVersion': minimum,
+ 'PRIVATE_SENTINEL': 'private runner metadata'}))
+ path = self.private / 'maestro' / name
+ path.parent.mkdir(exist_ok=True)
+ with zipfile.ZipFile(path, 'w') as jar:
+ jar.writestr('driver-iPhoneSimulator/Debug-iphonesimulator/maestro-driver-iosUITests-Runner.zip',
+ inner.getvalue())
+ return path
+
+ def test_fixed_categories_and_error_names_never_return_private_text(self):
+ samples = [
+ ('Library not loaded: PRIVATE_SENTINEL', 'DYLD_LIBRARY_MISSING'),
+ ('Symbol not found: PRIVATE_SENTINEL', 'DYLD_SYMBOL_MISSING'),
+ ('incompatible architecture PRIVATE_SENTINEL', 'DYLD_INCOMPATIBLE_LIBRARY'),
+ ('Failed to load the test bundle PRIVATE_SENTINEL', 'TEST_BUNDLE_LOAD_FAILED'),
+ ('failed to launch PRIVATE_SENTINEL', 'TEST_RUNNER_LAUNCH_FAILED'),
+ ('applicationverificationfailed PRIVATE_SENTINEL', 'TEST_RUNNER_INSTALL_FAILED'),
+ ('lost connection to the test manager PRIVATE_SENTINEL', 'TEST_MANAGER_CONNECTION_FAILED'),
+ ('built for a newer PRIVATE_SENTINEL', 'RUNTIME_OR_DEPLOYMENT_MISMATCH'),
+ ('unable to find runtime PRIVATE_SENTINEL', 'XCODE_COMPONENT_MISSING'),
+ ('ineligible destinations PRIVATE_SENTINEL', 'DESTINATION_UNAVAILABLE'),
+ ('invalid code signature PRIVATE_SENTINEL', 'CODE_SIGNING_FAILED'),
+ ('permission denied PRIVATE_SENTINEL', 'PERMISSION_DENIED'),
+ ('no space left on device PRIVATE_SENTINEL', 'DISK_SPACE_EXHAUSTED'),
+ ('"termination": {"private": "PRIVATE_SENTINEL"}', 'PROCESS_CRASHED'),
+ ('** TEST EXECUTE FAILED ** PRIVATE_SENTINEL', 'XCODE_TEST_EXECUTE_FAILED'),
+ ('** TEST FAILED ** PRIVATE_SENTINEL', 'XCODE_TEST_FAILED'),
+ ('Test Suite PRIVATE_SENTINEL started', 'XCODE_TEST_STARTED'),
+ ('** TEST EXECUTE SUCCEEDED ** PRIVATE_SENTINEL', 'XCODE_TEST_SUCCEEDED'),
+ ('server started PRIVATE_SENTINEL', 'DRIVER_SERVER_STARTED'),
+ ('PRIVATE_SENTINEL\nCommand line invocation:\nprivate continuation', 'XCODE_COMMAND_INVOCATION'),
+ ('PRIVATE_SENTINEL\nUser defaults from command line:\nprivate continuation', 'XCODE_USER_DEFAULTS'),
+ ('Domain=com.apple.CoreSimulator.SimError Code=405 PRIVATE_SENTINEL', 'ERROR_DOMAIN_CORE_SIMULATOR'),
+ ('Domain=IDETestOperationsObserverErrorDomain Code=4 PRIVATE_SENTINEL', 'ERROR_DOMAIN_IDE_TEST'),
+ ]
+ for payload, expected in samples:
+ with self.subTest(expected=expected):
+ result = diagnosis.classify(payload)
+ self.assertIn(expected, result)
+ self.assertTrue(set(result) <= set(diagnosis.CATEGORIES))
+ self.assertNotIn('PRIVATE_SENTINEL', json.dumps(result))
+ for payload in ['PRIVATE_SENTINEL', 'xpubPRIVATE_SENTINEL user@example.invalid',
+ 'https://example.invalid/private?token=PRIVATE_SENTINEL']:
+ self.assertEqual(diagnosis.classify(payload), [])
+ private_exception = type('PRIVATE_SENTINEL', (Exception,), {})('private contents')
+ self.assertEqual(diagnosis.safe_error(private_exception), 'OTHER_ERROR')
+ self.assertEqual(diagnosis.safe_error(ValueError('PRIVATE_SENTINEL')), 'ValueError')
+
+ def test_bounded_logs_export_only_prefix_facts_and_reject_escape(self):
+ log = self.private / 'private.log'
+ payload = b'Library not loaded: PRIVATE_SENTINEL\n' + b'x' * diagnosis.LIMIT
+ log.write_bytes(payload)
+ raw, facts = diagnosis.bounded(log)
+ self.assertEqual(len(raw), diagnosis.LIMIT)
+ self.assertTrue(facts['truncated'])
+ self.assertEqual(facts['bytes'], len(payload))
+ self.assertEqual(facts['prefix_sha256'], hashlib.sha256(payload[:diagnosis.LIMIT]).hexdigest())
+ self.assertEqual(facts['categories'], ['DYLD_LIBRARY_MISSING'])
+ self.assertNotIn('PRIVATE_SENTINEL', json.dumps(facts))
+ outside = self.root / 'outside.log'
+ outside.write_text('PRIVATE_SENTINEL')
+ link = self.private / 'escape.log'
+ link.symlink_to(outside)
+ for path in [outside, link]:
+ with self.subTest(path=path), self.assertRaises(ValueError):
+ diagnosis.bounded(path)
+
+ def test_bundled_plist_parser_reports_numeric_compatibility_without_extra_fields(self):
+ self.runner_jar()
+ facts = diagnosis.bundled_runner()
+ self.assertEqual(facts['selected_sdk_version'], '18.5')
+ self.assertEqual(len(facts['bundles']), 2)
+ for item in facts['bundles']:
+ self.assertEqual(item['sdk_version'], '26.4')
+ self.assertEqual(item['xcode_numeric'], '2640')
+ self.assertTrue(item['built_with_newer_sdk_than_selected'])
+ self.assertFalse(item['minimum_os_exceeds_selected_sdk'])
+ self.assertNotIn('PRIVATE_SENTINEL', json.dumps(facts))
+
+ def test_bundled_parser_rejects_missing_duplicate_invalid_or_malformed_inputs(self):
+ with self.assertRaises(ValueError):
+ diagnosis.bundled_runner()
+ jar = self.runner_jar(sdk='PRIVATE_SENTINEL', minimum='PRIVATE_SENTINEL')
+ facts = diagnosis.bundled_runner()
+ for item in facts['bundles']:
+ self.assertIsNone(item['sdk_version'])
+ self.assertIsNone(item['minimum_os_version'])
+ self.assertIsNone(item['built_with_newer_sdk_than_selected'])
+ extra = jar.parent / 'extra'
+ extra.mkdir()
+ duplicate = extra / jar.name
+ duplicate.write_bytes(jar.read_bytes())
+ with self.assertRaises(ValueError):
+ diagnosis.bundled_runner()
+ duplicate.unlink()
+ jar.write_bytes(b'PRIVATE_SENTINEL not a ZIP')
+ with self.assertRaises(zipfile.BadZipFile):
+ diagnosis.bundled_runner()
+
+ def test_collect_classifies_private_logs_and_reports_owned_runner_facts(self):
+ self.runner_jar()
+ state = self.private / 'maestro-preflight-state/maestro/tests/session'
+ state.mkdir(parents=True)
+ (state / 'maestro.log').write_text(
+ 'Running XcUITest with `xcodebuild test-without-building` with 22087 and config: PRIVATE_SENTINEL\n')
+ (state / 'xctest_runner_2026.log').write_text(
+ 'Library not loaded: PRIVATE_SENTINEL\n** TEST EXECUTE FAILED **\n')
+ home = self.root / 'home'
+ crash = home / 'Library/Logs/DiagnosticReports'
+ crash.mkdir(parents=True)
+ (crash / (diagnosis.RUNNER_NAME + '-private.ips')).write_text(
+ '"termination": {"private": "PRIVATE_SENTINEL"}')
+
+ def capture(args, label, timeout=20):
+ if label == 'xcodebuild-sample':
+ (self.private / 'driver-xcodebuild.sample').write_text(
+ 'xpc_connection_send_message_with_reply_sync\nSimDevice installApplication\nPRIVATE_SENTINEL')
+ payload = {
+ 'processes': ' 123 Z xcodebuild test-without-building -destination id=' + self.device + ' PRIVATE_SENTINEL\n'
+ ' 456 S xcodebuild test-without-building -destination id=OTHER PRIVATE_SENTINEL',
+ 'runner-installed': 'PRIVATE_SENTINEL app container',
+ 'runner-running': '123 0 UIKitApplication:' + diagnosis.RUNNER_ID + '[PRIVATE_SENTINEL]',
+ 'simulator-runner-events': 'PRIVATE_SENTINEL',
+ }.get(label, 'PRIVATE_SENTINEL')
+ return payload, {'label': label, 'exit_code': 0}
+
+ connection = mock.Mock()
+ connection.getresponse.return_value.status = 200
+ with mock.patch.object(diagnosis, 'capture', side_effect=capture), \
+ mock.patch.object(diagnosis.Path, 'home', return_value=home), \
+ mock.patch.object(diagnosis.socket, 'create_connection') as tcp, \
+ mock.patch.object(diagnosis.http.client, 'HTTPConnection', return_value=connection) as http:
+ facts = diagnosis.collect(self.device)
+ self.assertTrue(facts['runner_installed'])
+ self.assertTrue(facts['runner_running'])
+ self.assertEqual(facts['runner_last_exit_codes'], [0])
+ self.assertEqual(facts['owned_xcodebuild_process_count'], 1)
+ self.assertEqual(facts['owned_xcodebuild_zombie_count'], 1)
+ self.assertEqual(facts['xcodebuild_sample']['stack_categories'],
+ ['XPC_SYNC_WAIT', 'CORE_SIMULATOR', 'DEVICE_INSTALL'])
+ self.assertEqual(facts['driver_port'], 22087)
+ self.assertTrue(facts['driver_tcp_connects'])
+ self.assertEqual(facts['driver_status_http_code'], 200)
+ self.assertEqual(facts['recent_crash_reports'][0]['categories'], ['PROCESS_CRASHED'])
+ tcp.assert_called_once_with(('127.0.0.1', 22087), timeout=2)
+ http.assert_called_once_with('127.0.0.1', 22087, timeout=3)
+ connection.request.assert_called_once_with('GET', '/status')
+ connection.close.assert_called_once()
+ self.assertNotIn('PRIVATE_SENTINEL', json.dumps(facts))
+
+ def test_collect_without_driver_logs_never_probes_an_arbitrary_port(self):
+ with mock.patch.object(diagnosis, 'capture', return_value=('', {'exit_code': 1})), \
+ mock.patch.object(diagnosis.Path, 'home', return_value=self.root / 'absent'), \
+ mock.patch.object(diagnosis.socket, 'create_connection') as tcp, \
+ mock.patch.object(diagnosis.http.client, 'HTTPConnection') as http:
+ facts = diagnosis.collect(self.device)
+ self.assertIsNone(facts['runner_installed'])
+ self.assertIsNone(facts['runner_running'])
+ self.assertIsNone(facts['driver_port'])
+ self.assertEqual(facts['collection_errors'], [{'stage': 'bundled_runner', 'error_type': 'ValueError'}])
+ tcp.assert_not_called()
+ http.assert_not_called()
+
+ def test_baseline_controls_are_bounded_read_only_and_export_no_process_text(self):
+ selected = '/Applications/Xcode_16.4.app/Contents/Developer'
+ calls = []
+
+ def capture(args, label, timeout):
+ calls.append((args, label, timeout))
+ payload = '123 S ' + selected + '/Applications/Simulator.app/Contents/MacOS/Simulator PRIVATE_SENTINEL'
+ return payload, {'label': label, 'exit_code': 0 if label == 'baseline-processes' else 124}
+
+ with mock.patch.object(diagnosis, 'capture', side_effect=capture), \
+ mock.patch.dict(os.environ, {'DEVELOPER_DIR': selected}):
+ facts = diagnosis.baseline(self.device)
+ self.assertEqual(facts['simulator_frontend_process_count'], 1)
+ self.assertTrue(facts['selected_simulator_frontend_running'])
+ self.assertEqual(calls, [
+ (['ps', '-axo', 'pid=,stat=,args='], 'baseline-processes', 10),
+ (['xcrun', 'simctl', 'listapps', self.device], 'baseline-listapps', 10),
+ (['xcrun', 'simctl', 'get_app_container', self.device, 'com.apple.Preferences', 'app'],
+ 'baseline-preferences-container', 10),
+ ])
+ self.assertNotIn('PRIVATE_SENTINEL', json.dumps(facts))
+ self.assertNotIn(selected, json.dumps(facts))
+
+ def test_timed_out_runner_lookup_and_failed_process_control_remain_unknown(self):
+ with mock.patch.object(diagnosis, 'capture', return_value=('', {'exit_code': 124})), \
+ mock.patch.object(diagnosis.Path, 'home', return_value=self.root / 'absent'):
+ facts = diagnosis.collect(self.device)
+ before = diagnosis.baseline(self.device)
+ self.assertIsNone(facts['runner_installed'])
+ self.assertIsNone(facts['runner_running'])
+ self.assertIsNone(facts['owned_xcodebuild_alive'])
+ self.assertIsNone(before['simulator_frontend_process_count'])
+ self.assertIsNone(before['selected_simulator_frontend_running'])
+
+ def test_permission_errors_and_truncated_inventories_remain_unknown(self):
+ for truncated, payload in [(True, ''), (False, ''), (False, 'PRIVATE_SENTINEL malformed ps')]:
+ with self.subTest(truncated=truncated):
+ def capture(args, label, timeout=20):
+ if label == 'runner-installed':
+ return 'permission denied PRIVATE_SENTINEL', {'exit_code': 1, 'categories': ['PERMISSION_DENIED']}
+ return payload, {'exit_code': 0, 'truncated': truncated}
+ with mock.patch.object(diagnosis, 'capture', side_effect=capture), \
+ mock.patch.object(diagnosis.Path, 'home', return_value=self.root / 'absent'):
+ facts = diagnosis.collect(self.device)
+ before = diagnosis.baseline(self.device)
+ self.assertIsNone(facts['runner_installed'])
+ self.assertIsNone(facts['owned_xcodebuild_alive'])
+ self.assertIsNone(facts['owned_xcodebuild_process_count'])
+ self.assertIsNone(facts['owned_xcodebuild_zombie_count'])
+ self.assertNotIn('xcodebuild_sample', facts)
+ self.assertIsNone(facts['runner_running'])
+ self.assertIsNone(facts['runner_launchctl_entries'])
+ self.assertIsNone(before['simulator_frontend_process_count'])
+ self.assertNotIn('PRIVATE_SENTINEL', json.dumps(facts))
+
+ def test_receipt_read_and_save_failures_preserve_actual_driver_primary_and_cleanup(self):
+ for boundary in ['read', 'save']:
+ for primary in [True, False]:
+ with self.subTest(boundary=boundary, primary=primary):
+ native.save({'commands': [], 'toolchain': {}, 'maestro': {'binary': 'fixed-maestro'}})
+ original_error = RuntimeError('PRIVATE_SENTINEL hierarchy failure')
+ armed = [False]
+ events = []
+ real_read, real_save = native.read, native.save
+
+ def read():
+ if armed[0] and boundary == 'read':
+ raise OSError('PRIVATE_SENTINEL read failure')
+ return real_read()
+
+ def save(value):
+ if armed[0] and boundary == 'save':
+ raise OSError('PRIVATE_SENTINEL save failure')
+ real_save(value)
+
+ def command(args, label, **kwargs):
+ if label == 'Create owned driver-preflight simulator':
+ return self.device
+ if label == 'Check disposable iOS driver readiness':
+ armed[0] = True
+ events.append('hierarchy')
+ if primary:
+ raise original_error
+
+ def dispose(args, **kwargs):
+ events.append(args[2])
+ if args[2] == 'shutdown':
+ raise OSError('PRIVATE_SENTINEL shutdown failure')
+
+ with mock.patch.dict(os.environ, {'KEEPER_DIAGNOSTIC': 'true'}), \
+ mock.patch.object(native, 'record'), mock.patch.object(native, 'install_maestro'), \
+ mock.patch.object(native, 'wait_for_simulator_app_services'), \
+ mock.patch.object(native, 'command', side_effect=command), \
+ mock.patch.object(native, 'read', side_effect=read), \
+ mock.patch.object(native, 'save', side_effect=save), \
+ mock.patch.object(native.subprocess, 'run', side_effect=dispose), \
+ mock.patch.object(diagnosis, 'baseline', return_value={'commands': []}), \
+ mock.patch.object(diagnosis, 'collect', return_value={'scope': 'setup only'}), \
+ self.assertRaises(RuntimeError) as failure:
+ diagnosis.run()
+ if primary:
+ self.assertIs(failure.exception, original_error)
+ else:
+ self.assertNotIn('PRIVATE_SENTINEL', str(failure.exception))
+ self.assertEqual(events, ['hierarchy', 'shutdown', 'delete'])
+
+ def test_complete_valid_inventories_can_still_establish_absence(self):
+ def capture(args, label, timeout=20):
+ payload = 'PID Status Label\n' if label == 'runner-running' else '1 Ss /sbin/launchd\n'
+ return payload, {'exit_code': 0, 'truncated': False}
+ with mock.patch.object(diagnosis, 'capture', side_effect=capture), \
+ mock.patch.object(diagnosis.Path, 'home', return_value=self.root / 'absent'):
+ facts = diagnosis.collect(self.device)
+ before = diagnosis.baseline(self.device)
+ self.assertFalse(facts['owned_xcodebuild_alive'])
+ self.assertEqual(facts['owned_xcodebuild_process_count'], 0)
+ self.assertFalse(facts['runner_running'])
+ self.assertEqual(facts['runner_launchctl_entries'], 0)
+ self.assertEqual(before['simulator_frontend_process_count'], 0)
+
+ def test_run_rejects_other_platforms_and_missing_opt_in_before_operations(self):
+ for platform, opt_in in [('ANDROID', 'true'), ('IOS', ''), ('IOS', 'false')]:
+ with self.subTest(platform=platform, opt_in=opt_in), \
+ mock.patch.object(native, 'PLATFORM', platform), \
+ mock.patch.dict(os.environ, {'KEEPER_DIAGNOSTIC': opt_in}), \
+ mock.patch.object(native, 'record') as record, \
+ mock.patch.object(native, 'install_maestro') as install, \
+ self.assertRaises(ValueError):
+ diagnosis.run()
+ record.assert_not_called()
+ install.assert_not_called()
+
+ def test_run_collects_before_cleanup_and_preserves_original_driver_failure(self):
+ events = []
+ original_error = RuntimeError('PRIVATE_SENTINEL original driver failure')
+
+ def original(args, label, **kwargs):
+ events.append('hierarchy')
+ raise original_error
+
+ def driver(phase):
+ self.assertEqual(phase, 'driver')
+ try:
+ native.command(['maestro', '--device', self.device, 'hierarchy'],
+ 'Check disposable iOS driver readiness', timeout=300, error_details=False)
+ finally:
+ events.append('cleanup')
+
+ def collect(device, metadata):
+ self.assertEqual(device, self.device)
+ self.assertEqual(metadata['commands'][-1]['label'], 'Check disposable iOS driver readiness')
+ events.append('collect')
+ return {'collection_errors': [], 'scope': 'setup only'}
+
+ with mock.patch.dict(os.environ, {'KEEPER_DIAGNOSTIC': 'true'}), \
+ mock.patch.object(native, 'record'), mock.patch.object(native, 'install_maestro'), \
+ mock.patch.object(native, 'command', side_effect=original) as command, \
+ mock.patch.object(native, 'run_phase', side_effect=driver), \
+ mock.patch.object(diagnosis, 'baseline', return_value={'commands': []}), \
+ mock.patch.object(diagnosis, 'collect', side_effect=collect), \
+ self.assertRaises(RuntimeError) as failure:
+ diagnosis.run()
+ self.assertIs(failure.exception, original_error)
+ self.assertEqual(events, ['hierarchy', 'collect', 'cleanup'])
+ self.assertEqual(native.read()['driver_diagnosis']['scope'], 'setup only')
+ self.assertEqual(native.read()['driver_diagnosis']['snapshot_phase'], 'AFTER_DRIVER_COMMAND')
+ self.assertFalse(native.read()['driver_diagnosis']['hierarchy_running_before_collection'])
+ self.assertNotIn('PRIVATE_SENTINEL', native.EVIDENCE.read_text())
+ self.assertEqual(command.call_count, 1)
+
+ def test_live_sampling_precedes_cli_cleanup_and_persists_after_command_metadata(self):
+ events = []
+ sampled = threading.Event()
+ original_error = RuntimeError('PRIVATE_SENTINEL original driver failure')
+
+ def before(device):
+ self.assertEqual(device, self.device)
+ events.append('baseline')
+ return {'commands': []}
+
+ def original(args, label, **kwargs):
+ events.append('hierarchy-start')
+ self.assertTrue(sampled.wait(1), 'diagnosis must sample before command returns')
+ data = native.read()
+ data['command_final_write'] = True
+ native.save(data)
+ events.append('hierarchy-finish')
+ raise original_error
+
+ def collect(device, metadata):
+ self.assertEqual(device, self.device)
+ self.assertNotIn('command_final_write', metadata)
+ self.assertNotIn('hierarchy-finish', events)
+ events.append('collect')
+ sampled.set()
+ return {'collection_errors': [], 'scope': 'live setup only'}
+
+ def driver(phase):
+ try:
+ native.command(['maestro', '--device', self.device, 'hierarchy'],
+ 'Check disposable iOS driver readiness', timeout=300, error_details=False)
+ finally:
+ events.append('cleanup')
+
+ with mock.patch.dict(os.environ, {'KEEPER_DIAGNOSTIC': 'true'}), \
+ mock.patch.object(native, 'record'), mock.patch.object(native, 'install_maestro'), \
+ mock.patch.object(native, 'command', side_effect=original) as command, \
+ mock.patch.object(native, 'run_phase', side_effect=driver), \
+ mock.patch.object(diagnosis, 'POLL_SNAPSHOT_SECONDS', 0.01), \
+ mock.patch.object(diagnosis, 'baseline', side_effect=before), \
+ mock.patch.object(diagnosis, 'collect', side_effect=collect), \
+ self.assertRaises(RuntimeError) as failure:
+ diagnosis.run()
+ self.assertIs(failure.exception, original_error)
+ self.assertEqual(events, ['baseline', 'hierarchy-start', 'collect', 'hierarchy-finish', 'cleanup'])
+ data = native.read()
+ self.assertTrue(data['command_final_write'])
+ self.assertEqual(data['driver_diagnosis']['snapshot_phase'], 'DURING_DRIVER_POLLING')
+ self.assertTrue(data['driver_diagnosis']['hierarchy_running_before_collection'])
+ self.assertNotIn('PRIVATE_SENTINEL', native.EVIDENCE.read_text())
+ self.assertEqual(command.call_count, 1)
+
+ def test_collection_failure_does_not_replace_original_driver_failure(self):
+ original_error = RuntimeError('PRIVATE_SENTINEL original driver failure')
+
+ def driver(phase):
+ native.command(['maestro', '--device', self.device, 'hierarchy'],
+ 'Check disposable iOS driver readiness', timeout=300, error_details=False)
+
+ with mock.patch.dict(os.environ, {'KEEPER_DIAGNOSTIC': 'true'}), \
+ mock.patch.object(native, 'record'), mock.patch.object(native, 'install_maestro'), \
+ mock.patch.object(native, 'command', side_effect=original_error), \
+ mock.patch.object(native, 'run_phase', side_effect=driver), \
+ mock.patch.object(diagnosis, 'baseline', return_value={'commands': []}), \
+ mock.patch.object(diagnosis, 'collect', side_effect=ValueError('PRIVATE_SENTINEL collection')), \
+ self.assertRaises(RuntimeError) as failure:
+ diagnosis.run()
+ self.assertIs(failure.exception, original_error)
+ facts = native.read()['driver_diagnosis']
+ self.assertEqual(facts['collection_errors'], [{'stage': 'pre_cleanup', 'error_type': 'ValueError'}])
+ self.assertNotIn('PRIVATE_SENTINEL', native.EVIDENCE.read_text())
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/.github/tests/test_feature_runner.py b/.github/tests/test_feature_runner.py
new file mode 100644
index 0000000000..7bba343d48
--- /dev/null
+++ b/.github/tests/test_feature_runner.py
@@ -0,0 +1,117 @@
+"""Host contracts for native evidence validation; no native acceptance."""
+import copy
+import hashlib
+import importlib.util
+import json
+from pathlib import Path
+import tempfile
+import unittest
+from unittest import mock
+
+SPEC = importlib.util.spec_from_file_location('native_features', Path(__file__).resolve().parents[1] / 'native/hosted_native.py')
+native = importlib.util.module_from_spec(SPEC)
+SPEC.loader.exec_module(native)
+
+
+class FeatureEvidenceTest(unittest.TestCase):
+ def setUp(self):
+ self.directory = tempfile.TemporaryDirectory()
+ self.addCleanup(self.directory.cleanup)
+ self.root = Path(self.directory.name)
+ for path in native.R5_SOURCES:
+ file = self.root / path
+ file.parent.mkdir(parents=True, exist_ok=True)
+ file.write_text('public synthetic current source')
+ committed_sources = {path: (self.root / path).read_bytes() for path in native.R5_SOURCES}
+ committed_read = mock.patch.object(native.subprocess, 'check_output',
+ side_effect=lambda args, **kwargs: committed_sources[args[-1].removeprefix('HEAD:')])
+ committed_read.start()
+ self.addCleanup(committed_read.stop)
+ patch = mock.patch.multiple(native, ROOT=self.root, EVIDENCE=self.root / 'metadata.json')
+ patch.start()
+ self.addCleanup(patch.stop)
+ self.payload = {
+ 'schema': 1, 'scope': 'production-worker-native-storage', 'status': 'PASS', 'stage': 'pass',
+ 'scenarios': [{'id': item, 'status': 'PASS'} for item in native.R5_SCENARIOS],
+ 'measurements': [{'iteration': index, 'probe_ready_ms': 100.5, 'setup_first_wallet_ms': 25} for index in range(1, 6)],
+ 'limits': native.R5_LIMITS,
+ 'source_functions': [{'path': path, 'sha256': hashlib.sha256((self.root / path).read_bytes()).hexdigest(), 'names': names}
+ for path, names in native.R5_SOURCES.items()],
+ }
+
+ def test_only_bounded_metadata_survives_exact_source_validation(self):
+ self.payload['private_message'] = 'PRIVATE_SENTINEL'
+ evidence = native.validate_r5_feature_evidence(json.dumps(self.payload))
+ self.assertEqual(evidence['status'], 'PASS')
+ self.assertEqual(len(evidence['measurements']), 5)
+ self.assertNotIn('PRIVATE_SENTINEL', json.dumps(evidence))
+ self.assertIn('probe-and-worker-timings-not-product-startup-ux', evidence['limits'])
+
+ def test_incomplete_wrong_scope_or_failed_scenarios_cannot_supply_credit(self):
+ for field, value in [('schema', 2), ('scope', 'full-app-acceptance'), ('status', 'FAIL'),
+ ('stage', 'running'), ('scenarios', self.payload['scenarios'][:-1]),
+ ('measurements', self.payload['measurements'][:-1]), ('limits', [])]:
+ with self.subTest(field=field):
+ payload = {**self.payload, field: value}
+ with self.assertRaises(ValueError):
+ native.validate_r5_feature_evidence(json.dumps(payload))
+
+ def test_failed_skipped_or_duplicate_scenario_is_rejected(self):
+ for mutation in ['failure', 'skip', 'duplicate']:
+ payload = copy.deepcopy(self.payload)
+ if mutation == 'duplicate':
+ payload['scenarios'][1] = payload['scenarios'][0]
+ else:
+ payload['scenarios'][0]['status'] = mutation
+ with self.assertRaises(ValueError):
+ native.validate_r5_feature_evidence(json.dumps(payload))
+
+ def test_measurements_must_be_raw_ordered_finite_bounded_numbers(self):
+ for field, value in [('iteration', 2), ('iteration', True), ('probe_ready_ms', float('nan')), ('probe_ready_ms', True),
+ ('probe_ready_ms', -1), ('setup_first_wallet_ms', 600001),
+ ('setup_first_wallet_ms', '25')]:
+ with self.subTest(field=field, value=value):
+ payload = copy.deepcopy(self.payload)
+ payload['measurements'][0][field] = value
+ with self.assertRaises(ValueError):
+ native.validate_r5_feature_evidence(json.dumps(payload))
+
+ def test_stale_source_wrong_function_selection_and_oversized_data_fail_closed(self):
+ payload = copy.deepcopy(self.payload)
+ payload['source_functions'][0]['sha256'] = '0' * 64
+ with self.assertRaises(ValueError):
+ native.validate_r5_feature_evidence(json.dumps(payload))
+ payload = copy.deepcopy(self.payload)
+ payload['source_functions'][0]['names'] = ['otherFunction']
+ with self.assertRaises(ValueError):
+ native.validate_r5_feature_evidence(json.dumps(payload))
+ with self.assertRaises(ValueError):
+ native.validate_r5_feature_evidence(' ' * 65537)
+
+ def test_disk_reserve_is_recorded_and_exhaustion_stops_without_cleanup(self):
+ native.save({})
+ with mock.patch.object(native.shutil, 'disk_usage', return_value=mock.Mock(free=1024)), \
+ mock.patch.object(native.shutil, 'rmtree') as cleanup:
+ with self.assertRaisesRegex(RuntimeError, 'disk reserve'):
+ native.disk_preflight('before_native_build')
+ cleanup.assert_not_called()
+ evidence = native.read()['disk_preflight'][0]
+ self.assertEqual(evidence['result'], 'FAIL')
+ self.assertEqual(evidence['free_bytes'], 1024)
+ self.assertEqual(evidence['minimum_free_bytes'], 12 * 1024 ** 3)
+
+ def test_feature_runtime_requires_successful_product_startup_before_extraction(self):
+ native.save({'build': 'PASS', 'smoke': 'NOT RUN'})
+ with mock.patch.object(native.subprocess, 'Popen') as process:
+ with self.assertRaisesRegex(RuntimeError, 'app startup smoke'):
+ native.run_phase('features')
+ process.assert_not_called()
+ self.assertEqual(native.read()['r5_features'], 'FAIL')
+
+ def test_mutated_working_source_and_matching_probe_hash_cannot_impersonate_head(self):
+ path = self.payload['source_functions'][0]['path']
+ changed = b'altered public source after build'
+ (self.root / path).write_bytes(changed)
+ self.payload['source_functions'][0]['sha256'] = hashlib.sha256(changed).hexdigest()
+ with self.assertRaisesRegex(ValueError, 'committed candidate'):
+ native.validate_r5_feature_evidence(json.dumps(self.payload))
diff --git a/.github/tests/test_hosted_native.py b/.github/tests/test_hosted_native.py
new file mode 100644
index 0000000000..95339e12bc
--- /dev/null
+++ b/.github/tests/test_hosted_native.py
@@ -0,0 +1,538 @@
+"""Pure hosted-harness checks: these do not claim native simulator evidence."""
+
+import hashlib
+import importlib.util
+import json
+import os
+from pathlib import Path
+import subprocess
+import sys
+import tempfile
+import unittest
+from unittest import mock
+
+
+SPEC = importlib.util.spec_from_file_location(
+ 'hosted_native', Path(__file__).resolve().parents[1] / 'native' / 'hosted_native.py')
+native = importlib.util.module_from_spec(SPEC)
+SPEC.loader.exec_module(native)
+
+
+class HostedNativeHarnessTest(unittest.TestCase):
+ def setUp(self):
+ self.directory = tempfile.TemporaryDirectory()
+ self.addCleanup(self.directory.cleanup)
+ self.root = Path(self.directory.name)
+ self.patches = mock.patch.multiple(native, ROOT=self.root, PRIVATE=self.root / 'private',
+ EVIDENCE=self.root / 'evidence/metadata.json', PLATFORM='ANDROID')
+ self.patches.start()
+ self.addCleanup(self.patches.stop)
+ native.save({'commands': [], 'build': 'NOT RUN', 'smoke': 'NOT RUN'})
+
+ def test_metadata_records_the_current_run_attempt_without_native_credit(self):
+ source = 'a' * 40
+ for attempt in ['1', '2']:
+ with self.subTest(attempt=attempt), \
+ mock.patch.dict(os.environ, {'KEEPER_SOURCE_SHA': source,
+ 'KEEPER_DIAGNOSTIC': 'true',
+ 'GITHUB_RUN_ID': '90', 'GITHUB_RUN_ATTEMPT': attempt}), \
+ mock.patch.object(native.subprocess, 'check_output', return_value=source), \
+ mock.patch.object(native, 'command', return_value='synthetic-tool-version'), \
+ mock.patch.object(native, 'disk_preflight'):
+ native.record()
+ metadata = native.read()
+ self.assertEqual(metadata['source_sha'], source)
+ self.assertEqual(metadata['run_id'], '90')
+ self.assertEqual(metadata['run_attempt'], attempt)
+ self.assertTrue(metadata['diagnostic_only'])
+ for field in ['build', 'smoke', 'native_probe', 'r5_features', 'hardware', 'signing']:
+ self.assertEqual(metadata[field], 'NOT RUN')
+
+ def test_success_records_command_and_duration_without_output(self):
+ script = self.root / 'output.py'
+ script.write_text('print("private output")')
+ result = native.command([sys.executable, str(script)], 'Success', capture=True)
+ self.assertEqual(result, 'private output')
+ record = native.read()['commands'][0]
+ self.assertEqual(record['exit_code'], 0)
+ self.assertGreaterEqual(record['duration_seconds'], 0)
+ self.assertNotIn('private output', native.EVIDENCE.read_text())
+
+ def test_failure_exposes_only_allowlisted_diagnostic(self):
+ script = self.root / 'failure.py'
+ script.write_text('print("private payload: lockfile needs to be updated"); raise SystemExit(3)')
+ with self.assertRaisesRegex(RuntimeError, 'Manifest and yarn.lock are inconsistent'):
+ native.command([sys.executable, str(script)], 'Install')
+ record = native.read()['commands'][0]
+ self.assertEqual(record['exit_code'], 3)
+ self.assertNotIn('private payload', native.EVIDENCE.read_text())
+
+ def test_hierarchy_command_failure_never_exports_arbitrary_error_lines(self):
+ script = self.root / 'hierarchy_failure.py'
+ script.write_text('print("error: PRIVATE_SENTINEL hierarchy data"); raise SystemExit(1)')
+ with self.assertRaisesRegex(RuntimeError, 'exit 1'):
+ native.command([sys.executable, str(script)], 'Driver hierarchy', error_details=False)
+ self.assertEqual(native.read()['commands'][0]['redacted_tool_errors'], [])
+ self.assertNotIn('PRIVATE_SENTINEL', native.EVIDENCE.read_text())
+
+ def test_tool_errors_are_deduplicated_fixed_categories(self):
+ output = 'private payload\nerror: missing module https://example.test/private token=secret\n' \
+ + 'Caused by: password=private Bearer private\n' + 'error: detail\n' * 30
+ details = native.failure_details(output)
+ self.assertEqual(details, ['TOOL_ERROR'])
+ kotlin = '> Task :compile\n' * 40 + 'e: file:///runner/App.kt:1 unresolved reference'
+ self.assertEqual(native.failure_details(kotlin), ['KOTLIN_COMPILER_ERROR'])
+ excerpts = ''.join(' %s | +(NSDictionary*)statWithError:(NSError**)error:\n' % line
+ for line in range(30))
+ self.assertEqual(native.failure_details(excerpts + 'error: actual compiler failure'),
+ ['TOOL_ERROR'])
+
+ def test_timeout_records_failure_and_terminates_process(self):
+ with self.assertRaisesRegex(RuntimeError, 'exit 124'):
+ native.command([sys.executable, '-c', 'import time; time.sleep(30)'], 'Timeout', timeout=0.05)
+ self.assertEqual(native.read()['commands'][0]['exit_code'], 124)
+
+ def test_startup_diagnostics_keep_only_fixed_failed_steps_and_categories(self):
+ maestro = '\n'.join([
+ 'Assert that "Create a passcode" is visible... FAILED',
+ 'Tap on id: key_2... FAILED',
+ 'Tap on "private recovery phrase"... FAILED',
+ 'UI hierarchy: private state',
+ 'Assertion is false: "Create a passcode" is visible; UI hierarchy: PRIVATE_SENTINEL',
+ 'Element not found: key_1; private arbitrary suffix',
+ ])
+ messages = native.maestro_failure_details(maestro)
+ self.assertTrue(any('Create a passcode' in message for message in messages))
+ self.assertIn('Maestro tap key_2 FAILED', messages)
+ self.assertNotIn('private', '\n'.join(messages))
+ self.assertNotIn('PRIVATE_SENTINEL', '\n'.join(messages))
+ self.assertNotIn('hierarchy', '\n'.join(messages))
+ self.assertIn('Maestro assertion failed: Create a passcode', messages)
+ self.assertIn('Maestro element not found: key_1', messages)
+ metro = native.metro_startup_errors(' BUNDLE index.js\n ERROR Error: Unable to resolve module token=private https://example.test/private; View hierarchy: PRIVATE_SENTINEL')
+ self.assertEqual(metro, ['METRO_MODULE_RESOLUTION_ERROR'])
+ native_errors = native.android_startup_errors('\n'.join([
+ 'E/AndroidRuntime( 123): FATAL EXCEPTION: main; credentials: PRIVATE_SENTINEL',
+ 'E/ReactNativeJS( 123): TypeError: Cannot load module token=private',
+ 'E/OtherApp( 124): Error: private unrelated data',
+ 'E/ReactNativeJS( 123): at unneeded stack frame',
+ ]))
+ self.assertEqual(native_errors, ['ANDROID_RUNTIME_ERROR', 'REACT_NATIVE_JS_ERROR'])
+
+ def test_junit_failure_collection_omits_hierarchy_and_preserves_failed_result(self):
+ native.PRIVATE.mkdir()
+ native.save({'commands': [], 'build': 'PASS', 'smoke': 'FAIL'})
+ (native.PRIVATE / 'metro.log').write_text('No bundler error\n')
+ report = native.PRIVATE / 'smoke-junit.xml'
+ report.write_text(''
+ 'Assertion is false: Create a passcode is visible\nUI hierarchy: private data'
+ '')
+ hierarchy = native.PRIVATE / 'maestro-output/2026-10-17_092233/Disposable startup and passcode input/screen-hierarchy'
+ hierarchy.mkdir(parents=True)
+ (hierarchy / 'step-002-assertCondition-Create_a_passcode.json').write_text(json.dumps({
+ 'attributes': {'accessibilityText': 'PRIVATE_SENTINEL', 'resource-id': 'redbox-error'},
+ 'children': [{'attributes': {'accessibilityText': 'No script URL provided. PRIVATE_SENTINEL'}}]}))
+ native.record_startup_failure(report, None)
+ data = native.read()
+ self.assertEqual(data['smoke'], 'FAIL')
+ self.assertEqual(data['startup_diagnostics']['maestro']['testcase_statuses'], ['ERROR'])
+ self.assertNotIn('private data', native.EVIDENCE.read_text())
+ self.assertNotIn('PRIVATE_SENTINEL', native.EVIDENCE.read_text())
+ self.assertTrue(data['startup_diagnostics']['hierarchy_signals']['RNredbox'])
+ self.assertTrue(data['startup_diagnostics']['hierarchy_signals']['noScriptURL'])
+ self.assertTrue(data['startup_diagnostics']['maestro']['testcase_failures'])
+
+ def test_private_hierarchy_exports_only_fixed_signals_from_standalone_tree_nodes(self):
+ hierarchy = self.root / 'maestro-output/2026-10-17_092233/Disposable startup and passcode input/screen-hierarchy'
+ hierarchy.mkdir(parents=True)
+ (hierarchy / 'step-002-assertCondition-Create_a_passcode.json').write_text(json.dumps({
+ 'attributes': {'accessibilityText': 'Create a passcode', 'value': 'PRIVATE_SENTINEL'},
+ 'children': [
+ {'attributes': {'accessibilityText': 'Confirm your passcode'}},
+ {'attributes': {'resource-id': 'io.hexawallet.keeper.development:id/rn_redbox_stack',
+ 'text': 'Could not connect to development server. PRIVATE_SENTINEL'}},
+ {'attributes': {'title': 'Unable to load script. PRIVATE_SENTINEL'}},
+ {'attributes': {'text': 'SpringBoard PRIVATE_SENTINEL'}, 'children': None},
+ ]}))
+ # Other JSON files are not hierarchy snapshots and must not be parsed.
+ (hierarchy.parent / 'commands.json').write_text('{ malformed PRIVATE_SENTINEL')
+ signals = native.startup_hierarchy_signals(self.root / 'maestro-output')
+ self.assertEqual(signals, {'createPIN': True, 'confirmPIN': True, 'RNredbox': True,
+ 'noScriptURL': False, 'developmentServerError': True,
+ 'unableLoadScript': True, 'snapshot_count': 1, 'parse_error_types': []})
+ self.assertNotIn('PRIVATE_SENTINEL', json.dumps(signals))
+ self.assertNotIn('SpringBoard', json.dumps(signals))
+
+ def test_private_hierarchy_bounds_bytes_and_nodes_and_records_only_parse_error_classes(self):
+ hierarchy = self.root / 'maestro-output/screen-hierarchy'
+ hierarchy.mkdir(parents=True)
+ (hierarchy / 'step-001-malformed.json').write_text('{ PRIVATE_SENTINEL')
+ (hierarchy / 'step-002-oversize.json').write_bytes(b'PRIVATE_SENTINEL' * (1024 * 1024 // 8))
+ (hierarchy / 'step-003-too-many-nodes.json').write_text(json.dumps({
+ 'attributes': {'accessibilityText': 'Create a passcode'}, 'children': [{}] * 10000}))
+ signals = native.startup_hierarchy_signals(self.root / 'maestro-output')
+ self.assertEqual(signals['snapshot_count'], 3)
+ self.assertEqual(set(signals['parse_error_types']), {'JSONDecodeError', 'ValueError'})
+ self.assertFalse(signals['createPIN'])
+ self.assertNotIn('PRIVATE_SENTINEL', json.dumps(signals))
+
+ def test_maestro_preflight_retains_fixed_driver_markers_and_known_types_without_raw_messages(self):
+ output = native.PRIVATE / 'maestro-output'
+ output.mkdir(parents=True)
+ native.save({'commands': [{'label': 'Assert startup and disposable passcode transition'}],
+ 'smoke': 'FAIL'})
+ (native.PRIVATE / 'command-001.log').write_text(
+ 'xcuitest.installer.LocalXCTestInstaller$IOSDriverTimeoutException: '
+ 'iOS driver not ready in time, consider increasing timeout by configuring '
+ 'MAESTRO_DRIVER_STARTUP_TIMEOUT env variable PRIVATE_SENTINEL\n'
+ 'PRIVATE_SENTINELException: arbitrary exception names must not escape\n')
+ (output / 'maestro.log').write_text(
+ '[Start] Install XCUITest runner on PRIVATE_SENTINEL\n'
+ '[Done] Install XCUITest runner on PRIVATE_SENTINEL\n'
+ '[Start] Perform XCUITest driver status check on PRIVATE_SENTINEL\n'
+ '[Done] Perform XCUITest driver status check on PRIVATE_SENTINEL\n'
+ '[Failed] Perform XCUITest driver status check on PRIVATE_SENTINEL\n'
+ 'Installing pre built driver without xcodebuild PRIVATE_SENTINEL\n'
+ 'Requested driver host port PRIVATE_SENTINEL is not available\n')
+ (output / 'xctest_runner_fixture.log').write_text(
+ 'java.io.FileNotFoundException: xctestrun config does not exist PRIVATE_SENTINEL\n'
+ 'ui test runner does not exist PRIVATE_SENTINEL\n'
+ '** TEST EXECUTE FAILED ** PRIVATE_SENTINEL\nTesting failed: PRIVATE_SENTINEL\n')
+ result = native.maestro_preflight_diagnostics()
+ self.assertTrue(result['driver_startup_timeout'])
+ self.assertTrue(result['runner_install_started'])
+ self.assertTrue(result['runner_install_launch_returned'])
+ self.assertTrue(result['status_response_received'])
+ self.assertTrue(result['status_check_failed'])
+ self.assertTrue(result['host_port_unavailable'])
+ self.assertTrue(result['xctestrun_config_missing'])
+ self.assertTrue(result['ui_test_runner_missing'])
+ self.assertTrue(result['xcode_test_execute_failed'])
+ self.assertTrue(result['xcode_testing_failed'])
+ self.assertEqual(set(result['exception_types']), {'IOSDriverTimeoutException', 'FileNotFoundException'})
+ self.assertEqual(result['logs_read'], 3)
+ self.assertNotIn('PRIVATE_SENTINEL', json.dumps(result))
+ self.assertNotIn(str(output), json.dumps(result))
+ self.assertNotIn('driver_ready', result)
+ self.assertEqual(native.read()['smoke'], 'FAIL')
+
+ def test_ios_driver_preflight_is_setup_only_and_cleans_only_its_created_simulator(self):
+ native.save({'commands': [], 'maestro': {'binary': '/private/maestro'},
+ 'build': 'NOT RUN', 'smoke': 'NOT RUN'})
+ owned = '12345678-1234-1234-1234-123456789abc'
+ with mock.patch.object(native, 'PLATFORM', 'IOS'), mock.patch.dict(native.os.environ), \
+ mock.patch.object(native, 'wait_for_simulator_app_services') as ready, \
+ mock.patch.object(native, 'command', side_effect=[owned, None, None, None]) as command, \
+ mock.patch.object(subprocess, 'run', return_value=subprocess.CompletedProcess([], 0)) as cleanup:
+ native.driver()
+ self.assertEqual(native.os.environ['XDG_STATE_HOME'], str(native.PRIVATE / 'maestro-preflight-state'))
+ self.assertEqual(command.call_args.args[0],
+ ['/private/maestro', '--platform', 'ios', '--device', owned, 'hierarchy'])
+ self.assertFalse(command.call_args.kwargs['error_details'])
+ ready.assert_called_once_with(owned)
+ self.assertEqual([call.args[0] for call in cleanup.call_args_list],
+ [['xcrun', 'simctl', 'shutdown', owned], ['xcrun', 'simctl', 'delete', owned]])
+ self.assertEqual(native.read()['driver_preflight']['result'], 'PASS')
+ self.assertEqual(native.read()['build'], 'NOT RUN')
+ self.assertEqual(native.read()['smoke'], 'NOT RUN')
+
+ def test_ios_driver_failure_preserves_original_error_and_attempts_delete_after_cleanup_timeout(self):
+ native.save({'commands': [], 'maestro': {'binary': '/private/maestro'},
+ 'build': 'NOT RUN', 'smoke': 'NOT RUN'})
+ owned = '12345678-1234-1234-1234-123456789abc'
+ with mock.patch.object(native, 'PLATFORM', 'IOS'), mock.patch.dict(native.os.environ), \
+ mock.patch.object(native, 'wait_for_simulator_app_services'), \
+ mock.patch.object(native, 'command', side_effect=[owned, None, None, RuntimeError('driver failed PRIVATE_SENTINEL')]), \
+ mock.patch.object(subprocess, 'run', side_effect=[subprocess.TimeoutExpired('shutdown', 30),
+ subprocess.CompletedProcess([], 0)]) as cleanup, \
+ self.assertRaisesRegex(RuntimeError, 'driver failed PRIVATE_SENTINEL'):
+ native.run_phase('driver')
+ self.assertEqual(cleanup.call_count, 2)
+ self.assertEqual(cleanup.call_args.args[0], ['xcrun', 'simctl', 'delete', owned])
+ data = native.read()
+ self.assertEqual(data['driver_preflight']['result'], 'FAIL')
+ self.assertEqual(data['driver_preflight']['cleanup_errors'], [{'action': 'shutdown', 'error_type': 'TimeoutExpired'}])
+ self.assertEqual(data['failed_phase'], 'driver')
+ self.assertEqual(data['build'], 'NOT RUN')
+ self.assertEqual(data['smoke'], 'NOT RUN')
+ self.assertNotIn('PRIVATE_SENTINEL', native.EVIDENCE.read_text())
+
+ def test_unresponsive_simulator_blocks_maestro_and_cleans_owned_device(self):
+ native.save({'commands': [], 'maestro': {'binary': '/private/maestro'},
+ 'build': 'NOT RUN', 'smoke': 'NOT RUN'})
+ owned = '12345678-1234-1234-1234-123456789abc'
+ original_error = RuntimeError('PRIVATE_SENTINEL app services unavailable')
+ with mock.patch.object(native, 'PLATFORM', 'IOS'), mock.patch.dict(native.os.environ), \
+ mock.patch.object(native, 'wait_for_simulator_app_services', side_effect=original_error), \
+ mock.patch.object(native, 'command', side_effect=[owned, None, None]) as command, \
+ mock.patch.object(subprocess, 'run', return_value=subprocess.CompletedProcess([], 0)) as cleanup, \
+ self.assertRaises(RuntimeError) as failure:
+ native.run_phase('driver')
+ self.assertIs(failure.exception, original_error)
+ self.assertEqual(command.call_count, 3)
+ self.assertEqual(command.call_args.args[0], ['xcrun', 'simctl', 'bootstatus', owned, '-b'])
+ self.assertEqual([call.args[0] for call in cleanup.call_args_list],
+ [['xcrun', 'simctl', 'shutdown', owned], ['xcrun', 'simctl', 'delete', owned]])
+ self.assertEqual(native.read()['driver_preflight']['result'], 'FAIL')
+ self.assertNotIn('PRIVATE_SENTINEL', native.EVIDENCE.read_text())
+
+ def test_driver_preflight_diagnostics_cannot_contaminate_smoke_flags(self):
+ native.PRIVATE.mkdir()
+ driver_label = 'Check disposable iOS driver readiness'
+ native.save({'commands': [{'label': driver_label},
+ {'label': 'Assert startup and disposable passcode transition'}]})
+ (native.PRIVATE / 'command-001.log').write_text('IOSDriverTimeoutException PRIVATE_SENTINEL\n')
+ (native.PRIVATE / 'command-002.log').write_text('ordinary smoke output PRIVATE_SENTINEL\n')
+ state = native.PRIVATE / 'maestro-preflight-state/maestro/tests/timestamp'
+ state.mkdir(parents=True)
+ (state / 'maestro.log').write_text('** TEST EXECUTE FAILED ** PRIVATE_SENTINEL\n')
+ driver = native.maestro_preflight_diagnostics(state.parent, driver_label)
+ smoke = native.maestro_preflight_diagnostics()
+ self.assertTrue(driver['xcode_test_execute_failed'])
+ self.assertEqual(driver['exception_types'], ['IOSDriverTimeoutException'])
+ self.assertFalse(smoke['xcode_test_execute_failed'])
+ self.assertEqual(smoke['exception_types'], [])
+ self.assertNotIn('PRIVATE_SENTINEL', json.dumps(driver))
+
+ def test_maestro_preflight_bounds_files_bytes_and_collection_errors_without_changing_failure(self):
+ output = native.PRIVATE / 'maestro-output'
+ output.mkdir(parents=True)
+ native.save({'commands': [], 'smoke': 'FAIL'})
+ (output / 'maestro.log').write_bytes(
+ b'PRIVATE_SENTINEL' * (1024 * 1024 // 8) + b'\nInstalling driver with xcodebuild\n')
+ for index in range(7):
+ (output / ('xctest_runner_%s.log' % index)).write_text('PRIVATE_SENTINEL\n')
+ result = native.maestro_preflight_diagnostics()
+ self.assertEqual(result['logs_read'], 6)
+ self.assertTrue(result['log_limit_reached'])
+ self.assertEqual(result['truncated_logs'], 1)
+ self.assertFalse(result['xcodebuild_driver_selected'])
+ self.assertNotIn('PRIVATE_SENTINEL', json.dumps(result))
+ with mock.patch.object(native, 'private_log_prefix', side_effect=OSError('PRIVATE_SENTINEL')):
+ result = native.maestro_preflight_diagnostics()
+ self.assertEqual(result['collection_error_types'], ['OSError'])
+ self.assertEqual(native.read()['smoke'], 'FAIL')
+
+ def test_ios_startup_errors_restrict_process_and_export_only_a_fixed_category(self):
+ payload = '\n'.join([
+ 'Filtering the log data using the process predicate',
+ 'Timestamp Ty Process[PID:TID]',
+ '2026-10-17 09:22:33.123 E hexa_keeper_dev[123:abc] [com.facebook.react:javascript] NSException: module failed token=private; UI hierarchy: PRIVATE_SENTINEL',
+ 'private stack continuation',
+ '2026-10-17 09:22:34.123 E OtherApp[124:def] Error: hexa_keeper_dev private unrelated application',
+ '2026-10-17 09:22:35.123 Df hexa_keeper_dev[123:abc] normal startup message',
+ '2026-10-17 09:22:36.123 Df hexa_keeper_dev[123:abc] ReferenceError: missing startup module',
+ 'PRIVATE_SENTINEL multiline continuation',
+ '2026-10-17 09:22:37.123+0000 Df hexa_keeper_dev[123:abc] NSException: failed native startup',
+ 'PRIVATE_SENTINEL multiline continuation',
+ 'Error: hexa_keeper_dev[123:abc] missing timestamp must not be accepted',
+ ])
+ diagnostics = native.ios_startup_diagnostics(payload, 'hexa_keeper_dev')
+ errors = diagnostics['errors']
+ self.assertEqual(diagnostics['matching_process_records'], 4)
+ self.assertEqual(errors, ['IOS_STARTUP_ERROR'])
+ self.assertEqual(native.ios_startup_diagnostics('no compact records', 'hexa_keeper_dev')['matching_process_records'], 0)
+
+ def test_ios_collector_keeps_launch_prefix_when_log_is_truncated_and_preserves_failure(self):
+ native.PRIVATE.mkdir()
+ native.save({'commands': [], 'smoke': 'FAIL', 'built_artifact': {'executable': 'hexa_keeper_dev'}})
+ (native.PRIVATE / 'metro.log').write_text('\x1b[32m BUNDLE \x1b[0m private-path/index.js\n'
+ ' BUNDLE private-path/index.js\n PREBUNDLE private-path/index.js\n')
+
+ def compact_log(args, stdout, **kwargs):
+ self.assertEqual(args[args.index('--style') + 1], 'compact')
+ self.assertEqual(args[args.index('--last') + 1], '10m')
+ stdout.write(b'2026-10-17 09:22:33.123 Df hexa_keeper_dev[123:abc] ReferenceError: launch module failed token=private\n')
+ stdout.write(b'2026-10-17 09:22:34.123 E OtherApp[124:def] Error: private unrelated data\n')
+ # The first MiB ends within a continuation, not a complete record.
+ stdout.write(b'PRIVATE_SENTINEL' * (1024 * 1024 // 8))
+ stdout.write(b'\n2026-10-17 09:30:33.123 E hexa_keeper_dev[123:abc] Error: tail must not replace launch evidence\n')
+ return subprocess.CompletedProcess(args, 0)
+
+ with mock.patch.object(native, 'PLATFORM', 'IOS'), \
+ mock.patch.object(subprocess, 'run', side_effect=compact_log):
+ native.record_startup_failure(native.PRIVATE / 'missing-report.xml', 'owned-simulator')
+ data = native.read()
+ self.assertEqual(data['smoke'], 'FAIL')
+ diagnostics = data['startup_diagnostics']['ios_errors']
+ self.assertTrue(diagnostics['input_truncated'])
+ self.assertEqual(diagnostics['matching_process_records'], 1)
+ self.assertEqual(diagnostics['errors'], ['IOS_STARTUP_ERROR'])
+ self.assertEqual(data['startup_diagnostics']['metro_progress'],
+ {'bundle_marker_observed': True, 'bundle_marker_count': 2, 'prebundle_marker_count': 1})
+ self.assertNotIn('private unrelated', native.EVIDENCE.read_text())
+ self.assertNotIn('PRIVATE_SENTINEL', native.EVIDENCE.read_text())
+ self.assertNotIn('private-path', native.EVIDENCE.read_text())
+
+ def test_warmup_keeps_each_platform_body_private_and_does_not_supply_smoke_evidence(self):
+ native.PRIVATE.mkdir()
+ body = b'disposable development bundle PRIVATE_SENTINEL'
+
+ def warmup(args, *unused, **kwargs):
+ self.assertEqual(args[-1], 'http://127.0.0.1:8081/index.bundle?platform=%s&dev=true&minify=false'
+ % platform.lower())
+ Path(args[args.index('--output') + 1]).write_bytes(body)
+ return '200'
+
+ for platform in ['IOS', 'ANDROID']:
+ with self.subTest(platform=platform), mock.patch.object(native, 'PLATFORM', platform), \
+ mock.patch.object(native, 'command', side_effect=warmup):
+ native.warm_metro_bundle()
+ data = native.read()
+ self.assertEqual(data['smoke'], 'NOT RUN')
+ self.assertEqual(data['metro_warmup']['platform'], platform.lower())
+ self.assertEqual(data['metro_warmup']['result'], 'PASS')
+ self.assertEqual(data['metro_warmup']['http_status'], 200)
+ self.assertEqual(data['metro_warmup']['bytes'], len(body))
+ self.assertEqual(data['metro_warmup']['sha256'], hashlib.sha256(body).hexdigest())
+ self.assertNotIn('PRIVATE_SENTINEL', native.EVIDENCE.read_text())
+ with mock.patch.object(native, 'command', side_effect=RuntimeError('HTTP error')), \
+ self.assertRaisesRegex(RuntimeError, 'HTTP error'):
+ native.warm_metro_bundle()
+ self.assertEqual(native.read()['metro_warmup']['result'], 'FAIL')
+ self.assertEqual(native.read()['smoke'], 'NOT RUN')
+ with mock.patch.object(native, 'PLATFORM', 'unsupported&private=value'), \
+ mock.patch.object(native, 'command') as command, \
+ self.assertRaisesRegex(ValueError, 'Unsupported native bundle platform'):
+ native.warm_metro_bundle()
+ command.assert_not_called()
+
+ def test_ios_collector_rejects_unsafe_executable_without_running_command(self):
+ native.PRIVATE.mkdir()
+ native.save({'commands': [], 'smoke': 'FAIL', 'built_artifact': {'executable': '../unsafe"'}})
+ (native.PRIVATE / 'metro.log').write_text('')
+ with mock.patch.object(native, 'PLATFORM', 'IOS'), mock.patch.object(subprocess, 'run') as run:
+ native.record_startup_failure(native.PRIVATE / 'missing-report.xml', 'owned-simulator')
+ run.assert_not_called()
+ self.assertEqual(native.read()['smoke'], 'FAIL')
+ self.assertIn({'stage': 'ios_errors', 'error_type': 'ValueError'},
+ native.read()['startup_diagnostics']['collection_errors'])
+
+ def test_diagnostic_failure_never_replaces_original_smoke_failure(self):
+ native.PRIVATE.mkdir()
+ identity = {'sha256': 'test artifact'}
+ native.save({'commands': [], 'build': 'PASS', 'smoke': 'NOT RUN', 'built_artifact': identity})
+ metro = mock.Mock()
+ metro.poll.return_value = 1
+ with mock.patch.object(native, 'artifact_identity', return_value=identity), \
+ mock.patch.object(subprocess, 'Popen', return_value=metro), \
+ mock.patch.object(native, 'record_startup_failure', side_effect=RuntimeError('collector failed')), \
+ self.assertRaisesRegex(RuntimeError, 'Metro exited before the disposable smoke'):
+ native.run_phase('smoke')
+ self.assertEqual(native.read()['smoke'], 'FAIL')
+ self.assertEqual(native.read()['startup_diagnostics']['collection_errors'],
+ [{'stage': 'collector', 'error_type': 'RuntimeError'}])
+
+ def test_missing_executable_is_recorded(self):
+ with self.assertRaisesRegex(RuntimeError, 'exit 127'):
+ native.command([str(self.root / 'missing-command')], 'Missing')
+ self.assertEqual(native.read()['commands'][0]['exit_code'], 127)
+
+ def test_record_rejects_wrong_source_sha_before_collecting_evidence(self):
+ before = native.EVIDENCE.read_bytes()
+ with mock.patch.dict(native.os.environ, {'KEEPER_SOURCE_SHA': 'b' * 40}), \
+ mock.patch.object(subprocess, 'check_output', return_value='a' * 40 + '\n'), \
+ self.assertRaisesRegex(RuntimeError, 'exact requested PR head'):
+ native.record()
+ self.assertEqual(native.EVIDENCE.read_bytes(), before)
+
+ def test_android_fixtures_use_only_dummy_project_and_loopback_services(self):
+ (self.root / 'android/app').mkdir(parents=True)
+ native.fixtures()
+ environment = (self.root / '.env.ci').read_text()
+ self.assertIn('ENVIRONMENT=DEVELOPMENT', environment)
+ for line in environment.splitlines():
+ if 'https://' in line:
+ self.assertIn('127.0.0.1:9', line)
+ firebase = json.loads((self.root / 'android/app/google-services.json').read_text())
+ self.assertEqual(firebase['project_info']['project_id'], 'keeper-disposable-ci')
+ settings = json.loads((self.root / 'firebase.json').read_text())['react-native']
+ self.assertFalse(settings['messaging_auto_init_enabled'])
+ self.assertFalse(settings['app_data_collection_default_enabled'])
+ for overlay in native.read()['configuration_overlays']:
+ self.assertEqual(overlay['sha256'], hashlib.sha256((self.root / overlay['path']).read_bytes()).hexdigest())
+ self.assertEqual(len(native.read()['configuration_overlays']), 3)
+
+ def test_ios_fixtures_cover_both_tracked_firebase_files(self):
+ (self.root / 'ios/GoogleServices/dev').mkdir(parents=True)
+ with mock.patch.object(native, 'PLATFORM', 'IOS'):
+ native.fixtures()
+ paths = {overlay['path'] for overlay in native.read()['configuration_overlays']}
+ self.assertEqual(paths, {'.env.ci', 'firebase.json', 'ios/GoogleService-Info.plist',
+ 'ios/GoogleServices/dev/GoogleService-Info.plist'})
+
+ def test_emulator_revision_comes_from_sdk_metadata_without_executing_binary(self):
+ emulator = self.root / 'emulator'
+ emulator.mkdir()
+ (emulator / 'source.properties').write_text('Pkg.Revision = 36.6.11\nUnrelated = ignored\n')
+ with mock.patch.object(subprocess, 'Popen') as popen:
+ self.assertEqual(native.android_sdk_metadata(self.root, 'emulator'), {'Pkg.Revision': '36.6.11'})
+ popen.assert_not_called()
+
+ def test_emulator_metadata_must_exist_and_contain_revision(self):
+ with self.assertRaises(FileNotFoundError):
+ native.android_sdk_metadata(self.root, 'emulator')
+ emulator = self.root / 'emulator'
+ emulator.mkdir()
+ for text in ['Pkg.Desc = Android Emulator\n', 'Pkg.Revision = \n']:
+ with self.subTest(properties=text):
+ (emulator / 'source.properties').write_text(text)
+ with self.assertRaisesRegex(RuntimeError, 'no Pkg.Revision metadata'):
+ native.android_sdk_metadata(self.root, 'emulator')
+
+ def test_smoke_requires_successful_build(self):
+ with mock.patch.object(subprocess, 'Popen') as popen, \
+ self.assertRaisesRegex(RuntimeError, 'successful native build'):
+ native.smoke()
+ popen.assert_not_called()
+
+ def test_ios_build_rejects_unsupported_architecture_before_invoking_xcode(self):
+ with mock.patch.object(native, 'PLATFORM', 'IOS'), \
+ mock.patch.object(native, 'disk_preflight'), \
+ mock.patch.object(native.platform, 'machine', return_value='riscv64'), \
+ mock.patch.object(native, 'command') as command, \
+ self.assertRaisesRegex(RuntimeError, 'Unsupported hosted iOS simulator architecture'):
+ native.build()
+ command.assert_not_called()
+
+ def test_ios_build_uses_only_the_supported_host_simulator_architecture(self):
+ for architecture in ['arm64', 'x86_64']:
+ with self.subTest(architecture=architecture), \
+ mock.patch.object(native, 'disk_preflight'), \
+ mock.patch.object(native, 'PLATFORM', 'IOS'), \
+ mock.patch.object(native.platform, 'machine', return_value=architecture), \
+ mock.patch.object(native, 'artifact_identity', return_value={'sha256': 'test artifact'}), \
+ mock.patch.object(native, 'command') as command:
+ native.build()
+ arguments = command.call_args.args[0]
+ self.assertIn('ARCHS=' + architecture, arguments)
+ self.assertIn('ONLY_ACTIVE_ARCH=YES', arguments)
+ self.assertIn('CODE_SIGNING_ALLOWED=NO', arguments)
+ self.assertEqual(command.call_args.kwargs['timeout'], 2400)
+ self.assertEqual(native.read()['toolchain']['ios_simulator_architecture'], architecture)
+
+ def test_artifact_hash_detects_changed_apk_before_smoke(self):
+ apk = self.root / 'android/app/build/outputs/apk/development/debug/app-development-debug.apk'
+ apk.parent.mkdir(parents=True)
+ apk.write_bytes(b'first disposable artifact')
+ identity = native.artifact_identity()
+ self.assertEqual(identity['sha256'], hashlib.sha256(apk.read_bytes()).hexdigest())
+ native.save({'commands': [], 'build': 'PASS', 'smoke': 'NOT RUN', 'built_artifact': identity})
+ apk.write_bytes(b'replacement artifact')
+ with mock.patch.object(subprocess, 'Popen') as popen, \
+ self.assertRaisesRegex(RuntimeError, 'artifact changed'):
+ native.smoke()
+ popen.assert_not_called()
+
+ def test_failed_build_and_smoke_are_never_recorded_as_pass(self):
+ for phase in ['build', 'smoke']:
+ with self.subTest(phase=phase), \
+ mock.patch.object(native, phase, side_effect=RuntimeError('failure')), \
+ self.assertRaisesRegex(RuntimeError, 'failure'):
+ native.run_phase(phase)
+ self.assertEqual(native.read()[phase], 'FAIL')
+ self.assertEqual(native.read()['failed_phase'], phase)
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/.github/tests/test_install_diagnosis.py b/.github/tests/test_install_diagnosis.py
new file mode 100644
index 0000000000..c14b0bf58a
--- /dev/null
+++ b/.github/tests/test_install_diagnosis.py
@@ -0,0 +1,247 @@
+"""Offline observation controls; no app, simulator or native acceptance."""
+
+from contextlib import redirect_stdout
+import hashlib
+import importlib.util
+import io
+import json
+from pathlib import Path
+import tempfile
+import threading
+from types import SimpleNamespace
+import unittest
+from unittest import mock
+
+
+SPEC = importlib.util.spec_from_file_location(
+ 'install_diagnosis_controls', Path(__file__).resolve().parents[1] / 'native/install_diagnosis.py')
+diagnosis = importlib.util.module_from_spec(SPEC)
+SPEC.loader.exec_module(diagnosis)
+
+
+class InstallDiagnosisTest(unittest.TestCase):
+ def setUp(self):
+ directory = tempfile.TemporaryDirectory()
+ self.addCleanup(directory.cleanup)
+ self.root = Path(directory.name)
+ self.private = self.root / 'private'
+ self.private.mkdir()
+ self.evidence = self.root / 'metadata.json'
+ self.evidence.write_text(json.dumps({'commands': [], 'build': 'PASS', 'smoke': 'FAIL'}))
+ self.context = SimpleNamespace(PRIVATE=self.private, ROOT=self.root,
+ read=lambda: json.loads(self.evidence.read_text()),
+ save=lambda data: self.evidence.write_text(json.dumps(data)),
+ command=mock.Mock())
+ self.device = '12345678-1234-1234-1234-123456789ABC'
+ self.args = ['xcrun', 'simctl', 'install', self.device, '/private/PRIVATE_SENTINEL/App.app']
+
+ def test_log_export_is_fixed_categories_and_bounded_known_domain_codes(self):
+ payload = ('PRIVATE_SENTINEL failed to install; invalid code signature; permission denied\n'
+ 'Error Domain=com.apple.CoreSimulator.SimError Code=405 "PRIVATE_SENTINEL"\n'
+ 'Error Domain=NSPOSIXErrorDomain Code=60 "PRIVATE_SENTINEL"\n'
+ 'Error Domain=PRIVATE_SENTINEL Code=1\n'
+ 'Error Domain=NSCocoaErrorDomain Code=1234567890\n')
+ facts = diagnosis._classify(payload)
+ self.assertEqual(facts['categories'], ['INSTALL_FAILED', 'SIGNATURE_VERIFICATION_FAILED', 'PERMISSION_DENIED'])
+ self.assertEqual(facts['error_domain_codes'], {'CORE_SIMULATOR': [405], 'POSIX': [60]})
+ self.assertNotIn('PRIVATE_SENTINEL', json.dumps(facts))
+ self.assertEqual(diagnosis._classify('PRIVATE_SENTINEL token=arbitrary recovery words'),
+ {'categories': [], 'error_domain_codes': {}})
+ unknown = type('PRIVATE_SENTINEL', (Exception,), {})('arbitrary text')
+ self.assertEqual(diagnosis._error(unknown), 'OTHER_ERROR')
+
+ def test_private_log_reader_bounds_bytes_hashes_and_rejects_path_escape(self):
+ path = self.private / 'output.log'
+ payload = b'PRIVATE_SENTINEL failed to install\n' + b'x' * diagnosis.LIMIT
+ path.write_bytes(payload)
+ raw, facts = diagnosis._bounded(self.context, path)
+ self.assertEqual(len(raw), diagnosis.LIMIT)
+ self.assertTrue(facts['truncated'])
+ self.assertFalse(facts['grew_during_read'])
+ self.assertEqual(facts['bytes'], len(payload))
+ self.assertEqual(facts['prefix_sha256'], hashlib.sha256(payload[:diagnosis.LIMIT]).hexdigest())
+ self.assertNotIn('PRIVATE_SENTINEL', json.dumps(facts))
+ outside = self.root / 'outside.log'
+ outside.write_text('PRIVATE_SENTINEL')
+ link = self.private / 'link.log'
+ link.symlink_to(outside)
+ for item in [outside, link]:
+ with self.subTest(item=item), self.assertRaises(ValueError):
+ diagnosis._bounded(self.context, item)
+
+ def test_capture_does_not_follow_a_preexisting_output_symlink(self):
+ outside = self.root / 'outside.log'
+ outside.write_text('PRIVATE_SENTINEL remains intact')
+ (self.private / 'fixture-processes.log').symlink_to(outside)
+ with mock.patch.object(diagnosis.subprocess, 'Popen') as popen:
+ _, facts = diagnosis._capture(self.context, ['ps'], 'processes', 'fixture', 3)
+ popen.assert_not_called()
+ self.assertEqual(facts['error_type'], 'ValueError')
+ self.assertEqual(outside.read_text(), 'PRIVATE_SENTINEL remains intact')
+
+ def test_baseline_queries_app_services_without_app_or_service_changes(self):
+ with mock.patch.object(diagnosis, '_capture', return_value=('', {'exit_code': 124})) as capture, \
+ mock.patch.object(diagnosis.shutil, 'disk_usage', return_value=SimpleNamespace(free=123456)), \
+ mock.patch.object(diagnosis.os, 'getloadavg', return_value=(1.125, 2.25, 3.5)):
+ facts = diagnosis._baseline(self.context, self.device, 'fixture')
+ self.assertEqual([call.args for call in capture.call_args_list], [
+ (self.context, ['xcrun', 'simctl', 'listapps', self.device], 'baseline-listapps', 'fixture', 5),
+ (self.context, ['xcrun', 'simctl', 'get_app_container', self.device, 'com.apple.Preferences', 'app'],
+ 'baseline-preferences-container', 'fixture', 5),
+ ])
+ self.assertEqual(facts['disk_free_bytes'], 123456)
+ self.assertEqual(facts['host_load_1_5_15m'], [1.12, 2.25, 3.5])
+ self.assertEqual(facts['resource_errors'], [])
+ self.context.command.assert_not_called()
+
+ def test_collect_samples_only_one_exact_owned_install_and_keeps_service_output_private(self):
+ calls = []
+ (self.private / 'command-001.log').write_text('PRIVATE_SENTINEL resource busy')
+
+ def capture(context, args, label, prefix, timeout):
+ self.assertIs(context, self.context)
+ calls.append((args, label, timeout))
+ if label == 'install-sample':
+ Path(args[-1]).write_text('CoreSimulator SimDevice installApplication\n'
+ 'xpc_connection_send_message_with_reply_sync PRIVATE_SENTINEL')
+ payload = {
+ 'processes': '123 S /Developer/usr/bin/simctl install ' + self.device + ' PRIVATE_SENTINEL\n'
+ '456 S /Developer/usr/bin/simctl install OTHER PRIVATE_SENTINEL\n'
+ '789 S /Developer/usr/bin/simctl install OTHER/' + self.device + ' PRIVATE_SENTINEL',
+ 'simulator-services': '20 0 com.apple.mobile.installd\n- 0 com.apple.appinstalld\n'
+ '30 0 com.apple.lsd\nPRIVATE_SENTINEL',
+ 'owned-host-events': 'Error Domain=com.apple.CoreSimulator.SimError Code=405 PRIVATE_SENTINEL',
+ 'simulator-install-events': 'PRIVATE_SENTINEL',
+ }.get(label, '')
+ return payload, {'label': label, 'exit_code': 0, **diagnosis._classify(payload)}
+
+ with mock.patch.object(diagnosis, '_capture', side_effect=capture):
+ facts = diagnosis._collect(self.context, self.device, 'fixture', self.private / 'command-001.log')
+ self.assertEqual(facts['owned_install_process_count'], 1)
+ self.assertTrue(facts['owned_install_running'])
+ self.assertEqual(facts['install_sample']['stack_categories'],
+ ['CORE_SIMULATOR', 'MOBILE_INSTALLATION', 'XPC_SYNC_WAIT'])
+ self.assertIn((['sample', '123', '3', '1', '-file', str(self.private / 'fixture-install.sample')],
+ 'install-sample', 8), calls)
+ self.assertTrue(facts['services']['installd']['running'])
+ self.assertFalse(facts['services']['appinstalld']['running'])
+ self.assertTrue(facts['services']['lsd']['running'])
+ self.assertEqual(facts['install_command_output']['categories'], ['RESOURCE_BUSY'])
+ self.assertNotIn('PRIVATE_SENTINEL', json.dumps(facts))
+ self.assertNotIn(str(self.private), json.dumps(facts))
+ self.context.command.assert_not_called()
+
+ def test_failed_process_and_service_controls_stay_unknown_and_do_not_sample(self):
+ with mock.patch.object(diagnosis, '_capture', return_value=('', {'exit_code': 124})) as capture:
+ facts = diagnosis._collect(self.context, self.device, 'fixture', self.private / 'missing.log')
+ self.assertIsNone(facts['owned_install_process_count'])
+ self.assertIsNone(facts['owned_install_running'])
+ self.assertIsNone(facts['services']['installd']['running'])
+ self.assertFalse(any(call.args[2] == 'install-sample' for call in capture.call_args_list))
+
+ def test_observe_samples_during_one_unchanged_command_and_preserves_failure_metadata(self):
+ events = []
+ sampled = threading.Event()
+ original_error = RuntimeError('PRIVATE_SENTINEL original install failure')
+
+ def command(args, label, timeout):
+ self.assertIs(args, self.args)
+ self.assertEqual(label, 'Install unsigned development app')
+ self.assertEqual(timeout, 120)
+ events.append('install-start')
+ self.assertTrue(sampled.wait(2), 'sample must precede install return/cleanup')
+ data = self.context.read()
+ data['original_final_write'] = True
+ self.context.save(data)
+ events.append('install-end')
+ raise original_error
+
+ def baseline(*args):
+ events.append('baseline')
+ return {'commands': []}
+
+ def collect(*args):
+ events.append('sample')
+ self.assertNotIn('original_final_write', self.context.read())
+ sampled.set()
+ return {'commands': [], 'collection_errors': []}
+
+ self.context.command.side_effect = command
+ try:
+ with mock.patch.object(diagnosis, 'SNAPSHOT_SECONDS', 0.01), \
+ mock.patch.object(diagnosis, '_baseline', side_effect=baseline), \
+ mock.patch.object(diagnosis, '_collect', side_effect=collect), \
+ mock.patch.object(diagnosis, '_capture', return_value=('', {'exit_code': 124})), \
+ self.assertRaises(RuntimeError) as failure:
+ diagnosis.observe(self.context, self.device, self.args, 'Install unsigned development app', timeout=120)
+ self.assertIs(failure.exception, original_error)
+ finally:
+ events.append('caller-cleanup')
+ self.assertEqual(events, ['baseline', 'install-start', 'sample', 'install-end', 'caller-cleanup'])
+ self.context.command.assert_called_once_with(self.args, 'Install unsigned development app', timeout=120)
+ data = self.context.read()
+ self.assertTrue(data['original_final_write'])
+ facts = data['install_diagnoses'][0]
+ self.assertEqual(facts['snapshot_phase'], 'DURING_INSTALL')
+ self.assertTrue(facts['install_running_before_collection'])
+ self.assertEqual(facts['post_install_lookup']['state'], 'TIMEOUT')
+ self.assertEqual(facts['command_error_type'], 'RuntimeError')
+ self.assertEqual((data['build'], data['smoke']), ('PASS', 'FAIL'))
+ self.assertNotIn('installed_artifact_verified', data)
+ self.assertNotIn('PRIVATE_SENTINEL', self.evidence.read_text())
+
+ def test_fast_success_returns_original_result_without_retry_or_native_credit(self):
+ result = object()
+ self.context.command.return_value = result
+ with mock.patch.object(diagnosis, '_baseline', return_value={'commands': []}), \
+ mock.patch.object(diagnosis, '_collect', return_value={'commands': []}), \
+ mock.patch.object(diagnosis, '_capture', return_value=('', {'exit_code': 0})):
+ actual = diagnosis.observe(self.context, self.device, self.args, 'Install unsigned development app')
+ self.assertIs(actual, result)
+ self.context.command.assert_called_once_with(self.args, 'Install unsigned development app', timeout=120)
+ data = self.context.read()
+ self.assertEqual(data['install_diagnoses'][0]['snapshot_phase'], 'AFTER_INSTALL_COMMAND')
+ self.assertEqual(data['install_diagnoses'][0]['post_install_lookup']['state'], 'SUCCESS')
+ self.assertEqual(data['smoke'], 'FAIL')
+ self.assertNotIn('installed_artifact_verified', data)
+
+ def test_collection_and_persistence_errors_cannot_mask_original_install_failure(self):
+ original_error = RuntimeError('PRIVATE_SENTINEL original install failure')
+ self.context.command.side_effect = original_error
+ console = io.StringIO()
+ with mock.patch.object(diagnosis, '_baseline', side_effect=ValueError('PRIVATE_SENTINEL baseline')), \
+ mock.patch.object(diagnosis, '_collect', side_effect=ValueError('PRIVATE_SENTINEL snapshot')), \
+ mock.patch.object(diagnosis, '_capture', side_effect=ValueError('PRIVATE_SENTINEL lookup')), \
+ redirect_stdout(console), self.assertRaises(RuntimeError) as failure:
+ diagnosis.observe(self.context, self.device, self.args, 'Install unsigned development app')
+ self.assertIs(failure.exception, original_error)
+ self.context.command.assert_called_once()
+ self.assertNotIn('PRIVATE_SENTINEL', console.getvalue() + self.evidence.read_text())
+
+ def test_successful_install_with_unpersisted_diagnostics_blocks_with_fixed_error(self):
+ self.context.command.return_value = object()
+ self.context.save = mock.Mock(side_effect=ValueError('PRIVATE_SENTINEL persistence failure'))
+ with mock.patch.object(diagnosis, '_baseline', return_value={'commands': []}), \
+ mock.patch.object(diagnosis, '_collect', return_value={'commands': []}), \
+ mock.patch.object(diagnosis, '_capture', return_value=('', {'exit_code': 0})), \
+ self.assertRaises(RuntimeError) as failure:
+ diagnosis.observe(self.context, self.device, self.args, 'Install unsigned development app')
+ self.assertEqual(str(failure.exception), 'Bounded install diagnostics could not be saved.')
+ self.assertTrue(failure.exception.__suppress_context__)
+ self.context.command.assert_called_once_with(self.args, 'Install unsigned development app', timeout=120)
+ self.context.save.assert_called_once()
+ self.assertNotIn('install_diagnoses', self.context.read())
+ self.assertNotIn('PRIVATE_SENTINEL', str(failure.exception) + self.evidence.read_text())
+
+ def test_wrong_device_or_command_is_rejected_before_any_operation(self):
+ for device, args in [('OTHER', self.args), (self.device, ['adb', 'install', self.device]),
+ (self.device, ['xcrun', 'simctl', 'install', 'OTHER', 'PRIVATE_SENTINEL'])]:
+ with self.subTest(args=args), mock.patch.object(diagnosis, '_baseline') as baseline, \
+ self.assertRaises(ValueError):
+ diagnosis.observe(self.context, device, args, 'Install unsigned development app')
+ baseline.assert_not_called()
+ self.context.command.assert_not_called()
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/.github/tests/test_installed_artifact.py b/.github/tests/test_installed_artifact.py
new file mode 100644
index 0000000000..17299ab53c
--- /dev/null
+++ b/.github/tests/test_installed_artifact.py
@@ -0,0 +1,146 @@
+"""Host byte/transport controls; no native acceptance credit."""
+import importlib.util
+from pathlib import Path
+import plistlib
+import shutil
+import tempfile
+import unittest
+from unittest import mock
+
+SPEC = importlib.util.spec_from_file_location(
+ 'installed_native', Path(__file__).resolve().parents[1] / 'native/hosted_native.py')
+h = importlib.util.module_from_spec(SPEC)
+SPEC.loader.exec_module(h)
+
+
+class InstalledArtifactTest(unittest.TestCase):
+ def setUp(self):
+ temporary = tempfile.TemporaryDirectory()
+ self.addCleanup(temporary.cleanup)
+ self.root = Path(temporary.name)
+ self.private = self.root / 'private'
+ patch = mock.patch.multiple(h, ROOT=self.root, PRIVATE=self.private,
+ EVIDENCE=self.root / 'metadata.json', PLATFORM='ANDROID')
+ patch.start()
+ self.addCleanup(patch.stop)
+ apk = self.root / 'android/app/build/outputs/apk/development/debug/app-development-debug.apk'
+ apk.parent.mkdir(parents=True)
+ apk.write_bytes(b'PRIVATE_APK')
+ self.pm = '/data/app/~~ABC==/io.hexawallet.keeper.development-XYZ==/base.apk'
+ self.seed()
+
+ def seed(self):
+ h.save({'built_artifact': h.artifact_identity(), 'commands': [],
+ 'installed_artifact_verified': True, 'installed_artifact': {'stale': True}})
+
+ def reject(self, device):
+ with self.assertRaisesRegex(RuntimeError, 'not verified; no equivalence claimed'):
+ h.verify_installed_artifact(device)
+ self.assertFalse(h.read()['installed_artifact_verified'])
+ self.assertNotIn('installed_artifact', h.read())
+ self.assertNotIn('PRIVATE_', h.EVIDENCE.read_text())
+
+ def reply(self, value):
+ return mock.patch.object(h, 'command', return_value=value)
+
+ def pull(self, content=b'PRIVATE_APK', code=0):
+ def copy(args, **kwargs):
+ self.assertEqual(args[:5], ['adb', '-s', 'emulator-5554', 'pull', self.pm])
+ self.pulled = Path(args[5])
+ if content is not None:
+ self.pulled.write_bytes(content)
+ for field in ['stdout', 'stderr']:
+ self.assertEqual(kwargs[field], h.subprocess.DEVNULL)
+ return mock.Mock(returncode=code)
+ return mock.patch.object(h.subprocess, 'run', side_effect=copy)
+
+ def test_android_match_and_private_cleanup(self):
+ with self.reply('package:' + self.pm) as command, self.pull():
+ proof = h.verify_installed_artifact('emulator-5554')
+ self.assertEqual(command.call_args.args[0][-2:], ['path', h.APP_IDS['ANDROID']])
+ self.assertEqual(proof['sha256'], h.artifact_identity()['sha256'])
+ self.assertTrue(h.read()['installed_artifact_verified'])
+ self.assertFalse(self.pulled.parent.exists())
+ self.assertNotIn(self.pm, h.EVIDENCE.read_text())
+
+ def test_android_corrupt_missing_failed_pull(self):
+ for content, code in [(b'PRIVATE_APX', 0), (None, 0), (b'PRIVATE_APK', 1)]:
+ with self.subTest(content=content), self.reply('package:' + self.pm), self.pull(content, code):
+ self.reject('emulator-5554')
+ self.assertFalse(self.pulled.parent.exists())
+
+ def test_android_invalid_paths_or_splits(self):
+ for value in ['', self.pm + '\npackage:/data/app/split.apk',
+ self.pm.replace('development', 'production'),
+ self.pm.replace('/data/app/', '/sdcard/'), self.pm.replace('base.apk', 'base\\xapk')]:
+ with self.subTest(value=value), self.reply('package:' + value), mock.patch.object(h.subprocess, 'run') as pull:
+ self.reject('emulator-5554')
+ pull.assert_not_called()
+
+ def ios(self):
+ h.PLATFORM = 'IOS'
+ self.device = '12345678-1234-1234-1234-123456789ABC'
+ self.home = self.root / 'home'
+ self.bundle = self.private / 'DerivedData/Build/Products/Debug-iphonesimulator/hexa_keeper_dev.app'
+ self.bundle.mkdir(parents=True)
+ (self.bundle / 'Info.plist').write_bytes(plistlib.dumps(
+ {'CFBundleIdentifier': h.APP_IDS['IOS'], 'CFBundleExecutable': 'hexa_keeper_dev'}))
+ (self.bundle / 'hexa_keeper_dev').write_bytes(b'PRIVATE_EXE')
+ (self.bundle / 'asset').write_bytes(b'PRIVATE_ASSET')
+ self.app = (self.home / 'Library/Developer/CoreSimulator/Devices' / self.device /
+ 'data/Containers/Bundle/Application/ABCDEFAB-1234-1234-1234-123456789ABC' / self.bundle.name)
+ shutil.copytree(self.bundle, self.app)
+ self.seed()
+ patch = mock.patch.object(h.Path, 'home', return_value=self.home)
+ patch.start()
+ self.addCleanup(patch.stop)
+
+ def test_ios_match(self):
+ self.ios()
+ with self.reply(str(self.app)) as command:
+ proof = h.verify_installed_artifact(self.device)
+ self.assertEqual(command.call_args.args[0][-2:], [h.APP_IDS['IOS'], 'app'])
+ self.assertEqual(proof['executable_sha256'], h.artifact_identity()['executable_sha256'])
+ self.assertTrue(h.read()['installed_artifact_verified'])
+ self.assertNotIn(str(self.app), h.EVIDENCE.read_text())
+
+ def test_ios_corrupt_missing_added_bytes(self):
+ self.ios()
+ for name, value in [('hexa_keeper_dev', b'PRIVATE_EXX'), ('asset', b'PRIVATE_ASSXT'),
+ ('asset', None), ('unexpected', b'PRIVATE_EXTRA')]:
+ with self.subTest(name=name, value=value), self.reply(str(self.app)):
+ shutil.rmtree(self.app)
+ shutil.copytree(self.bundle, self.app)
+ target = self.app / name
+ target.unlink() if value is None else target.write_bytes(value)
+ self.reject(self.device)
+
+ def test_ios_foreign_paths_and_escaping_container(self):
+ self.ios()
+ for path in [str(self.bundle), str(self.app).replace(self.device, 'FOREIGN'), str(self.app) + '\n' + str(self.app)]:
+ with self.subTest(path=path), self.reply(path):
+ self.reject(self.device)
+ outside = self.root / 'outside'
+ shutil.move(str(self.app.parent), outside)
+ self.app.parent.symlink_to(outside, target_is_directory=True)
+ with self.reply(str(self.app)):
+ self.reject(self.device)
+
+ def test_ios_unsafe_tree(self):
+ self.ios()
+ (self.app / 'asset').unlink()
+ (self.app / 'asset').symlink_to(self.bundle / 'asset')
+ with self.reply(str(self.app)):
+ self.reject(self.device)
+ (self.bundle / 'Info.plist').write_bytes(plistlib.dumps(
+ {'CFBundleIdentifier': h.APP_IDS['IOS'], 'CFBundleExecutable': '../outside'}))
+ with mock.patch.object(h, 'command') as command:
+ self.reject(self.device)
+ command.assert_not_called()
+
+ def test_non_owned_device(self):
+ for platform, device in [('ANDROID', 'physical-serial'), ('IOS', 'booted')]:
+ h.PLATFORM = platform
+ with self.subTest(platform=platform), mock.patch.object(h, 'command') as command:
+ self.reject(device)
+ command.assert_not_called()
diff --git a/.github/tests/test_product_companion_cleanup.py b/.github/tests/test_product_companion_cleanup.py
new file mode 100644
index 0000000000..e02dc04565
--- /dev/null
+++ b/.github/tests/test_product_companion_cleanup.py
@@ -0,0 +1,179 @@
+"""Run each actual companion with fake UI/host boundaries and failing cleanup."""
+import contextlib
+import copy
+import importlib.util
+import json
+from pathlib import Path
+import tempfile
+import types
+import unittest
+from unittest import mock
+
+NATIVE = Path(__file__).resolve().parents[1] / 'native'
+COMPANIONS = ('key', 'credential', 'history', 'vault')
+
+
+def load(name):
+ spec = importlib.util.spec_from_file_location(name, NATIVE / (name + '.py'))
+ module = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(module)
+ return module
+
+
+class PrimaryFailure(RuntimeError):
+ pass
+
+
+class CompanionCleanupTests(unittest.TestCase):
+ def exercise(self, kind, *, primary=False, failures=(), initial_save_failure=False):
+ product = load('product_' + kind + '_acceptance')
+ temporary = tempfile.TemporaryDirectory()
+ self.addCleanup(temporary.cleanup)
+ root = Path(temporary.name)
+ private = root / 'private'
+ private.mkdir()
+ (root / 'release').mkdir()
+ (root / 'release/version.json').write_text(json.dumps(
+ {'version': '2.6.4', 'iosBuildNumber': 620, 'androidVersionCode': 627}))
+ sha, artifact = 'a' * 40, {'sha256': 'f' * 64}
+ proof = {'method': 'SINGLE_INSTALLED_BASE_APK_SHA256', 'sha256': 'f' * 64}
+ state = {'build': 'PASS', 'source_sha': sha, 'built_artifact': artifact,
+ 'maestro': {'binary': 'fake-maestro'}, 'product_key_ui': {
+ 'status': 'PASS', 'scenario': 'UNUSED_MOBILE_KEY_UI_DELETE_AND_NATIVE_PIN',
+ 'visible_eligible_keys_after_deletion': 0,
+ 'unrelated_visible_wallet_count_after_relaunch': 1,
+ 'new_account_requests_during_key_flow': 0,
+ 'installed_artifact_verified': True, 'installed_artifact': proof}}
+ slot = {'key': 'product_key_ui', 'credential': 'product_credential_ui',
+ 'history': 'product_version_history_ui', 'vault': 'product_vault_ui'}[kind]
+ output = private / (kind + '-ui')
+ events, attempted_receipts = [], []
+ runtime = {'started': False, 'save_calls': 0}
+ primary_error = PrimaryFailure('PRIVATE_SENTINEL primary error')
+
+ def save(value):
+ runtime['save_calls'] += 1
+ attempted_receipts.append(copy.deepcopy(value[slot]))
+ if initial_save_failure and runtime['save_calls'] == 1:
+ raise OSError('PRIVATE_SENTINEL initial metadata error')
+ if runtime['started']:
+ events.append('evidence-save')
+ if 'evidence-save' in failures:
+ raise OSError('PRIVATE_SENTINEL metadata error')
+ state.clear()
+ state.update(copy.deepcopy(value))
+
+ def cleanup_step(name):
+ events.append(name)
+ if name in failures:
+ raise OSError('PRIVATE_SENTINEL cleanup error')
+
+ def server(receipt):
+ runtime['receipt'] = receipt
+ return types.SimpleNamespace(serve_forever=lambda: None,
+ shutdown=lambda: cleanup_step('server-shutdown'),
+ server_close=lambda: cleanup_step('server-close'))
+
+ def installed(_device):
+ state.update(installed_artifact_verified=True, installed_artifact=copy.deepcopy(proof))
+ return copy.deepcopy(proof)
+
+ def command(args, _label, **_kwargs):
+ if args[0] == 'adb':
+ return
+ runtime['started'] = True
+ directory = Path(args[args.index('--debug-output') + 1])
+ (directory / 'private-ui.png').write_text('PRIVATE_SENTINEL')
+ if primary:
+ raise primary_error
+ if kind in ('key', 'vault'):
+ for stage in product.STAGES:
+ self.assertTrue(runtime['receipt'].mark(stage))
+ elif kind == 'credential' and not args[-1].endswith('credential_fixture.yaml'):
+ stages = product.STAGES[:3] if args[-1].endswith('blocked.yaml') else product.STAGES[3:]
+ for stage in stages:
+ self.assertTrue(runtime['receipt'].mark(stage))
+
+ real_rmtree = product.shutil.rmtree
+
+ def rmtree(path, *args, **kwargs):
+ if Path(path) == output:
+ cleanup_step('private-output')
+ return real_rmtree(path, *args, **kwargs)
+
+ h = types.SimpleNamespace(ROOT=root, PLATFORM='ANDROID', APP_IDS={'ANDROID': 'owned.app'},
+ read=lambda: copy.deepcopy(state), save=save, artifact_identity=lambda: artifact,
+ verify_installed_artifact=installed, command=command, successful_junit=lambda _: 1)
+ backend = types.SimpleNamespace(snapshot=lambda **_: {'status': 'PASS', 'sample': 6,
+ 'scenario': 'CONTROLLED_DISCONNECT_BEFORE_COMMIT_NOT_WAN_OFFLINE',
+ 'create_new_app_calls': 2, 'visible_wallet_count_after_relaunch': 1})
+ with contextlib.ExitStack() as stack:
+ stack.enter_context(mock.patch.dict(product.os.environ, {'GITHUB_ACTIONS': 'true',
+ 'RUNNER_ENVIRONMENT': 'github-hosted', 'KEEPER_SOURCE_SHA': sha}))
+ stack.enter_context(mock.patch.object(product.subprocess, 'check_output', return_value=sha))
+ stack.enter_context(mock.patch.object(product.subprocess, 'run',
+ return_value=types.SimpleNamespace(returncode=0)))
+ stack.enter_context(mock.patch.object(product.shutil, 'rmtree', side_effect=rmtree))
+ if kind != 'history':
+ stack.enter_context(mock.patch.object(product, 'make_server', side_effect=server))
+ arguments = [h, state, 'emulator-5554', private, backend]
+ if kind == 'vault':
+ arguments.append(lambda _h, device: installed(device))
+ elif kind in ('credential', 'history'):
+ arguments.append(lambda _phase: None)
+ try:
+ value = product.run_companion(*arguments)
+ except Exception as error:
+ value = error
+ return value, primary_error, state, slot, output, events, attempted_receipts
+
+ def test_primary_failure_survives_all_cleanup_and_save_failures_in_each_actual_companion(self):
+ for kind in COMPANIONS:
+ with self.subTest(kind=kind):
+ failures = ('server-shutdown', 'server-close', 'private-output', 'evidence-save')
+ value, primary, _state, _slot, output, events, receipts = self.exercise(
+ kind, primary=True, failures=failures)
+ self.assertIs(value, primary)
+ expected = ['private-output'] if kind == 'history' else list(failures[:3])
+ self.assertEqual(events[:len(expected)], expected)
+ self.assertEqual(events[len(expected):], ['evidence-save', 'evidence-save'])
+ self.assertTrue(output.exists(), 'injected purge failure must remain visible to the parent')
+ self.assertEqual(receipts[-1]['status'], 'FAIL')
+ self.assertEqual(receipts[-1]['failure_category'], 'PrimaryFailure')
+ self.assertEqual(receipts[-1]['cleanup'], 'FAILED')
+ self.assertNotIn('PRIVATE_SENTINEL', json.dumps(receipts))
+
+ def test_successful_ui_cannot_leave_pass_when_any_cleanup_or_final_save_fails(self):
+ for kind in COMPANIONS:
+ choices = ['private-output', 'evidence-save']
+ if kind != 'history':
+ choices += ['server-shutdown', 'server-close']
+ for failed_stage in choices:
+ with self.subTest(kind=kind, stage=failed_stage):
+ value, _primary, state, slot, output, events, receipts = self.exercise(
+ kind, failures=(failed_stage,))
+ self.assertIsInstance(value, Exception)
+ self.assertNotEqual(state[slot]['status'], 'PASS')
+ self.assertEqual(receipts[-1]['status'], 'FAIL')
+ if failed_stage != 'private-output':
+ self.assertFalse(output.exists())
+ if kind != 'history':
+ self.assertIn('server-shutdown', events)
+ self.assertIn('server-close', events)
+ self.assertIn('private-output', events)
+ self.assertNotIn('PRIVATE_SENTINEL', json.dumps(state))
+
+ def test_initial_save_failure_still_disposes_the_created_private_directory(self):
+ for kind in COMPANIONS:
+ with self.subTest(kind=kind):
+ value, _primary, state, slot, output, events, _receipts = self.exercise(
+ kind, initial_save_failure=True)
+ self.assertIsInstance(value, OSError)
+ self.assertEqual(state[slot]['status'], 'FAIL')
+ self.assertEqual(state[slot]['failure_category'], 'OSError')
+ self.assertFalse(output.exists())
+ self.assertIn('private-output', events)
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/.github/tests/test_product_credential_acceptance.py b/.github/tests/test_product_credential_acceptance.py
new file mode 100644
index 0000000000..44d8d4b927
--- /dev/null
+++ b/.github/tests/test_product_credential_acceptance.py
@@ -0,0 +1,189 @@
+"""Host safety contracts with fake driver/adapters, never native acceptance."""
+import contextlib
+import copy
+import importlib.util
+import json
+from pathlib import Path
+import re
+import tempfile
+import threading
+import types
+import unittest
+from unittest import mock
+import urllib.error
+import urllib.request
+
+SPEC = importlib.util.spec_from_file_location('product_credential_acceptance',
+ Path(__file__).resolve().parents[1] / 'native/product_credential_acceptance.py')
+product = importlib.util.module_from_spec(SPEC)
+SPEC.loader.exec_module(product)
+
+
+class ReceiptTests(unittest.TestCase):
+ def test_native_phase_confirmation_and_order_are_required(self):
+ receipt = product.Receipt()
+ self.assertFalse(receipt.mark(product.STAGES[0]))
+ with self.assertRaises(RuntimeError):
+ receipt.phase('restored')
+ receipt.phase('armed')
+ for stage in product.STAGES[:3]:
+ self.assertTrue(receipt.mark(stage))
+ self.assertFalse(receipt.mark(stage))
+ self.assertFalse(receipt.mark(product.STAGES[3]))
+ receipt.phase('restored')
+ for stage in product.STAGES[3:]:
+ self.assertTrue(receipt.mark(stage))
+ result = receipt.snapshot(passed=True)
+ self.assertEqual(result['status'], 'PASS')
+ self.assertEqual(result['os_keychain_denial_or_hardware_read_fault'], 'NOT RUN')
+ self.assertEqual(result['same_process_retry_after_external_repair'], 'NOT RUN')
+
+ def test_partial_blocking_ui_cannot_pass_or_advance_to_restore(self):
+ receipt = product.Receipt()
+ receipt.phase('armed')
+ receipt.mark(product.STAGES[0])
+ with self.assertRaises(RuntimeError):
+ receipt.phase('restored')
+ with self.assertRaises(RuntimeError):
+ receipt.snapshot(passed=True)
+
+ def test_fixed_endpoint_rejects_sensitive_extra_fields_or_unknown_stages(self):
+ receipt = product.Receipt()
+ receipt.phase('armed')
+ server = product.make_server(receipt, port=0)
+ threading.Thread(target=server.serve_forever, daemon=True).start()
+ try:
+ url = 'http://127.0.0.1:%d/metric' % server.server_port
+ for payload in [{'stage': 'PRIVATE_SENTINEL'},
+ {'stage': product.STAGES[0], 'secret': 'PRIVATE_SENTINEL'},
+ {'stage': 'PRIVATE_SENTINEL' * 100}]:
+ with self.assertRaises(urllib.error.HTTPError) as failure:
+ urllib.request.urlopen(urllib.request.Request(url,
+ data=json.dumps(payload).encode(), method='POST'))
+ self.assertEqual(failure.exception.code, 422)
+ with urllib.request.urlopen(urllib.request.Request(url,
+ data=json.dumps({'stage': product.STAGES[0]}).encode(), method='POST')) as response:
+ self.assertEqual(response.status, 200)
+ self.assertNotIn('PRIVATE_SENTINEL', json.dumps(receipt.snapshot()))
+ finally:
+ server.shutdown()
+ server.server_close()
+
+ def test_ui_flows_never_export_and_all_finish_with_a_stopped_app(self):
+ directory = Path(__file__).resolve().parents[1] / 'native'
+ flows = [(directory / name).read_text() for name in
+ ('credential_fixture.yaml', 'product_credential_blocked.yaml', 'product_credential_recovered.yaml')]
+ self.assertEqual(re.findall(r'STAGE: ([a-z_]+)', ''.join(flows)), list(product.STAGES))
+ for flow in flows:
+ self.assertTrue(flow.rstrip().endswith('- stopApp'))
+ for forbidden in ['takeScreenshot:', 'copyTextFrom:', 'inputText:', 'setClipboard:', 'clearKeychain:']:
+ self.assertNotIn(forbidden, flow)
+ self.assertIn('- tapOn: Retry', flows[1])
+ self.assertIn('- assertNotVisible: Create a passcode', flows[1])
+
+
+class RunnerTests(unittest.TestCase):
+ def exercise(self, *, missing_stage=False, phase_failure=False, switch_failure=False,
+ extra_create=False, installed_changed=False, source_dirty=False,
+ device='emulator-5554', prior_key_failure=False):
+ temporary = tempfile.TemporaryDirectory()
+ self.addCleanup(temporary.cleanup)
+ root = Path(temporary.name)
+ private = root / 'private'
+ private.mkdir()
+ sha, artifact = '1' * 40, {'sha256': 'f' * 64}
+ state = {'build': 'PASS', 'source_sha': sha, 'built_artifact': artifact,
+ 'maestro': {'binary': 'fake-maestro'},
+ 'product_key_ui': {'status': 'FAIL' if prior_key_failure else 'PASS'}}
+ runtime = {'switches': [], 'calls': 0, 'proofs': 0}
+
+ def backend_snapshot(passed=False):
+ runtime['calls'] += 1
+ return {'status': 'PASS', 'sample': 6, 'visible_wallet_count_after_relaunch': 1,
+ 'scenario': 'CONTROLLED_DISCONNECT_BEFORE_COMMIT_NOT_WAN_OFFLINE',
+ 'create_new_app_calls': 3 if extra_create and runtime['calls'] > 1 else 2}
+
+ def command(arguments, _label, **kwargs):
+ self.assertFalse(kwargs['error_details'])
+ if arguments[0] == 'adb':
+ return
+ output = Path(arguments[arguments.index('--debug-output') + 1])
+ (output / 'PRIVATE_SENTINEL.png').write_text('PRIVATE_SENTINEL')
+ if arguments[-1].endswith('credential_fixture.yaml'):
+ if phase_failure:
+ raise RuntimeError('PRIVATE_SENTINEL')
+ else:
+ stages = product.STAGES[:3] if arguments[-1].endswith('blocked.yaml') else product.STAGES[3:]
+ for stage in stages:
+ if missing_stage and stage == product.STAGES[-1]:
+ continue
+ self.assertTrue(runtime['receipt'].mark(stage))
+
+ def server(receipt):
+ runtime['receipt'] = receipt
+ return types.SimpleNamespace(serve_forever=lambda: None, shutdown=lambda: None, server_close=lambda: None)
+
+ def verify_installed(_device):
+ runtime['proofs'] += 1
+ proof = {'method': 'SINGLE_INSTALLED_BASE_APK_SHA256',
+ 'sha256': ('e' if installed_changed and runtime['proofs'] == 2 else 'f') * 64}
+ state.update(installed_artifact_verified=True, installed_artifact=copy.deepcopy(proof))
+ return proof
+
+ def save(value):
+ state.clear()
+ state.update(copy.deepcopy(value))
+
+ def switch(phase):
+ runtime['switches'].append(phase)
+ if switch_failure:
+ raise RuntimeError('PRIVATE_SENTINEL')
+
+ h = types.SimpleNamespace(ROOT=root, PLATFORM='ANDROID', APP_IDS={'ANDROID': 'owned.disposable'},
+ read=lambda: copy.deepcopy(state), save=save, artifact_identity=lambda: artifact,
+ verify_installed_artifact=verify_installed, command=command, successful_junit=lambda _report: 1)
+ with contextlib.ExitStack() as stack:
+ stack.enter_context(mock.patch.dict(product.os.environ, {'GITHUB_ACTIONS': 'true',
+ 'RUNNER_ENVIRONMENT': 'github-hosted', 'KEEPER_SOURCE_SHA': sha}))
+ stack.enter_context(mock.patch.object(product.subprocess, 'check_output', return_value=sha))
+ stack.enter_context(mock.patch.object(product.subprocess, 'run',
+ return_value=types.SimpleNamespace(returncode=1 if source_dirty else 0)))
+ stack.enter_context(mock.patch.object(product, 'make_server', side_effect=server))
+ try:
+ value = product.run_companion(h, state, device, private,
+ types.SimpleNamespace(snapshot=backend_snapshot), switch)
+ except Exception as error:
+ value = error
+ return value, state, runtime, private
+
+ def test_complete_flow_switches_to_ordinary_app_for_all_acceptance_and_destroys_private_output(self):
+ value, state, runtime, private = self.exercise()
+ self.assertEqual(value['status'], 'PASS')
+ self.assertEqual(runtime['switches'], ['arm', 'product', 'restore', 'product'])
+ self.assertEqual(runtime['proofs'], 2)
+ self.assertEqual(value['new_account_requests_during_credential_flow'], 0)
+ self.assertTrue(value['backup_service_removed_after_verified_restore'])
+ self.assertFalse((private / 'credential-ui').exists())
+ self.assertNotIn('PRIVATE_SENTINEL', json.dumps(state))
+
+ def test_missing_native_phase_ui_driver_receipt_or_source_proof_fails_without_leaking_diagnostics(self):
+ for option in ['missing_stage', 'phase_failure', 'switch_failure', 'extra_create', 'installed_changed']:
+ with self.subTest(option=option):
+ value, state, _runtime, private = self.exercise(**{option: True})
+ self.assertIsInstance(value, RuntimeError)
+ self.assertEqual(state['product_credential_ui']['status'], 'FAIL')
+ self.assertFalse((private / 'credential-ui').exists())
+ self.assertNotIn('PRIVATE_SENTINEL', json.dumps(state))
+
+ def test_prior_failure_real_device_and_dirty_sources_are_rejected_before_switching(self):
+ for options in [{'prior_key_failure': True}, {'source_dirty': True}, {'device': 'real-phone'}]:
+ with self.subTest(options=options):
+ value, state, runtime, private = self.exercise(**options)
+ self.assertIsInstance(value, RuntimeError)
+ self.assertEqual(runtime['switches'], [])
+ self.assertNotIn('product_credential_ui', state)
+ self.assertFalse((private / 'credential-ui').exists())
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/.github/tests/test_product_history_acceptance.py b/.github/tests/test_product_history_acceptance.py
new file mode 100644
index 0000000000..1127bb114e
--- /dev/null
+++ b/.github/tests/test_product_history_acceptance.py
@@ -0,0 +1,147 @@
+"""Offline runner boundary controls only; no native acceptance credit."""
+import contextlib
+import copy
+import importlib.util
+import json
+from pathlib import Path
+import tempfile
+import types
+import unittest
+from unittest import mock
+
+SPEC = importlib.util.spec_from_file_location('product_history_acceptance',
+ Path(__file__).resolve().parents[1] / 'native/product_history_acceptance.py')
+product = importlib.util.module_from_spec(SPEC)
+SPEC.loader.exec_module(product)
+
+
+class RunnerTests(unittest.TestCase):
+ def exercise(self, *, dirty=False, command_failure=False, invalid_installed=False,
+ changed_install=False, new_account=False, device='emulator-5554', switch_failure=False):
+ temporary = tempfile.TemporaryDirectory()
+ self.addCleanup(temporary.cleanup)
+ root = Path(temporary.name)
+ (root / 'release').mkdir()
+ (root / 'release/version.json').write_text(json.dumps(
+ {'version': '2.6.4', 'iosBuildNumber': 620, 'androidVersionCode': 627}))
+ private = root / 'private'
+ private.mkdir()
+ sha = 'a' * 40
+ artifact = {'sha256': 'b' * 64}
+ state = {'build': 'PASS', 'source_sha': sha, 'built_artifact': artifact,
+ 'maestro': {'binary': 'offline-fake-maestro'}}
+ commands, switches = [], []
+ installed_calls = 0
+ backend_calls = 0
+
+ def backend_snapshot(passed=False):
+ nonlocal backend_calls
+ backend_calls += 1
+ return {'status': 'PASS', 'sample': 6, 'create_new_app_calls':
+ 3 if new_account and backend_calls > 1 else 2,
+ 'scenario': 'CONTROLLED_DISCONNECT_BEFORE_COMMIT_NOT_WAN_OFFLINE',
+ 'visible_wallet_count_after_relaunch': 1}
+
+ def command(args, label, **kwargs):
+ self.assertFalse(kwargs['error_details'])
+ commands.append(args)
+ (private / 'history-ui/private-UI.png').write_text('PRIVATE_SENTINEL')
+ if command_failure:
+ raise RuntimeError('PRIVATE_SENTINEL')
+
+ def verify_installed(_):
+ nonlocal installed_calls
+ installed_calls += 1
+ proof = {'method': 'SINGLE_INSTALLED_BASE_APK_SHA256',
+ 'sha256': ('d' if changed_install and installed_calls > 1 else 'c') * 64}
+ state['installed_artifact_verified'] = not invalid_installed
+ state['installed_artifact'] = copy.deepcopy(proof)
+ return proof
+
+ def save(value):
+ state.clear()
+ state.update(copy.deepcopy(value))
+
+ def switch(phase):
+ switches.append(phase)
+ if switch_failure:
+ raise RuntimeError('PRIVATE_SENTINEL')
+
+ h = types.SimpleNamespace(ROOT=root, PLATFORM='ANDROID', APP_IDS={'ANDROID': 'disposable.app'},
+ read=lambda: copy.deepcopy(state), save=save, artifact_identity=lambda: artifact,
+ verify_installed_artifact=verify_installed, command=command, successful_junit=lambda _: 1)
+ backend = types.SimpleNamespace(snapshot=backend_snapshot)
+ with contextlib.ExitStack() as stack:
+ stack.enter_context(mock.patch.dict(product.os.environ, {'GITHUB_ACTIONS': 'true',
+ 'RUNNER_ENVIRONMENT': 'github-hosted', 'KEEPER_SOURCE_SHA': sha}))
+ stack.enter_context(mock.patch.object(product.subprocess, 'check_output', return_value=sha))
+ stack.enter_context(mock.patch.object(product.subprocess, 'run',
+ return_value=types.SimpleNamespace(returncode=1 if dirty else 0)))
+ try:
+ value = product.run_companion(h, state, device, private, backend, switch)
+ except Exception as error:
+ value = error
+ return value, state, commands, switches, installed_calls, private
+
+ def test_full_order_requires_all_fixed_native_and_normal_product_phases_and_byte_proofs(self):
+ value, state, commands, switches, installed_calls, private = self.exercise()
+ self.assertEqual(value['status'], 'PASS')
+ self.assertEqual(value['completed_stages'], list(product.PHASES))
+ self.assertEqual(switches, [p if p.startswith('history_') else 'product'
+ for p in product.PHASES] + ['product'])
+ self.assertEqual(len(commands), len(product.PHASES))
+ self.assertEqual(installed_calls, 2 * len(product.PHASES) + 2)
+ self.assertTrue(all(p['installed_artifact_verified'] for p in value['stage_evidence']))
+ self.assertEqual(value['original_history_restored'], True)
+ self.assertEqual(value['new_account_requests_during_history_flow'], 0)
+ self.assertFalse((private / 'history-ui').exists())
+ self.assertNotIn('PRIVATE_SENTINEL', json.dumps(state))
+
+ def test_interrupted_native_phase_never_claims_complete_and_purges_ui_output(self):
+ for option in ['command_failure', 'switch_failure']:
+ value, state, _, _, _, private = self.exercise(**{option: True})
+ self.assertIsInstance(value, RuntimeError)
+ self.assertEqual(state['product_version_history_ui']['status'], 'FAIL')
+ self.assertEqual(state['product_version_history_ui']['completed_stages'], [])
+ self.assertNotIn('original_history_restored', state['product_version_history_ui'])
+ self.assertNotIn('PRIVATE_SENTINEL', json.dumps(state))
+ self.assertFalse((private / 'history-ui').exists())
+
+ def test_changed_or_unverified_installed_bytes_cannot_pass(self):
+ for option in ['invalid_installed', 'changed_install']:
+ value, state, commands, _, _, private = self.exercise(**{option: True})
+ self.assertIsInstance(value, RuntimeError)
+ self.assertEqual(state['product_version_history_ui']['status'], 'FAIL')
+ self.assertEqual(commands, [])
+ self.assertFalse((private / 'history-ui').exists())
+
+ def test_new_account_request_after_scenario_is_a_failure(self):
+ value, state, *_ = self.exercise(new_account=True)
+ self.assertIsInstance(value, RuntimeError)
+ self.assertEqual(state['product_version_history_ui']['status'], 'FAIL')
+
+ def test_dirty_source_and_physical_device_are_rejected_before_commands(self):
+ for options in [{'dirty': True}, {'device': 'physical-device'}]:
+ value, state, commands, *_ = self.exercise(**options)
+ self.assertIsInstance(value, RuntimeError)
+ self.assertEqual(commands, [])
+ self.assertNotIn('product_version_history_ui', state)
+
+ def test_fixed_configs_select_only_their_committed_entrypoint_and_all_flows_stop_app(self):
+ native = Path(__file__).resolve().parents[1] / 'native'
+ for phase in product.PHASES:
+ if phase.startswith('history_'):
+ config = (native / (phase + '_metro.cjs')).read_text()
+ self.assertIn('/.github/native/' + phase + '.$1', config)
+ self.assertIn("registerFixture('" + phase[8:] + "')",
+ (native / (phase + '.js')).read_text())
+ self.assertNotIn('process.env', config)
+ for flow in ['history_product.yaml', 'history_fixture.yaml']:
+ source = (native / flow).read_text()
+ self.assertTrue(source.rstrip().endswith('- stopApp'))
+ for forbidden in ['takeScreenshot:', 'copyTextFrom:', 'setClipboard:', 'clearKeychain:']:
+ self.assertNotIn(forbidden, source)
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/.github/tests/test_product_key_acceptance.py b/.github/tests/test_product_key_acceptance.py
new file mode 100644
index 0000000000..67568db378
--- /dev/null
+++ b/.github/tests/test_product_key_acceptance.py
@@ -0,0 +1,181 @@
+"""Host-only normal-app companion contracts; no native acceptance credit."""
+import contextlib
+import copy
+import importlib.util
+import json
+from pathlib import Path
+import re
+import tempfile
+import threading
+import types
+import unittest
+from unittest import mock
+import urllib.error
+import urllib.request
+
+SPEC = importlib.util.spec_from_file_location(
+ 'product_key_acceptance', Path(__file__).resolve().parents[1] / 'native/product_key_acceptance.py')
+product = importlib.util.module_from_spec(SPEC)
+SPEC.loader.exec_module(product)
+
+
+class ReceiptTests(unittest.TestCase):
+ def test_exact_stage_order_is_required_without_substitute_or_repeated_marks(self):
+ receipt = product.Receipt()
+ self.assertFalse(receipt.mark('unused_mobile_key_deleted'))
+ for stage in product.STAGES:
+ self.assertTrue(receipt.mark(stage))
+ self.assertFalse(receipt.mark(stage))
+ evidence = receipt.snapshot(passed=True)
+ self.assertEqual(evidence['status'], 'PASS')
+ self.assertEqual(evidence['referenced_vault_ui'], 'NOT IMPLEMENTED')
+ self.assertEqual(evidence['credential_store_read_fault'], 'NOT RUN')
+
+ def test_missing_checks_never_pass(self):
+ receipt = product.Receipt()
+ receipt.mark(product.STAGES[0])
+ with self.assertRaisesRegex(RuntimeError, 'INCOMPLETE'):
+ receipt.snapshot(passed=True)
+ self.assertEqual(receipt.snapshot()['status'], 'FAIL')
+
+ def test_loopback_server_rejects_extra_fields_oversize_and_unknown_stage_without_retaining_data(self):
+ receipt = product.Receipt()
+ server = product.make_server(receipt, port=0)
+ thread = threading.Thread(target=server.serve_forever, daemon=True)
+ thread.start()
+ try:
+ url = 'http://127.0.0.1:%d/metric' % server.server_port
+ for payload in [{'stage': 'PRIVATE_SENTINEL'}, {'stage': product.STAGES[0], 'private': 'PRIVATE_SENTINEL'},
+ {'private': 'PRIVATE_SENTINEL' * 100}]:
+ request = urllib.request.Request(url, data=json.dumps(payload).encode(), method='POST')
+ with self.assertRaises(urllib.error.HTTPError) as failure:
+ urllib.request.urlopen(request)
+ self.assertEqual(failure.exception.code, 422)
+ request = urllib.request.Request(url, data=json.dumps({'stage': product.STAGES[0]}).encode(), method='POST')
+ with urllib.request.urlopen(request) as response:
+ self.assertEqual(response.status, 200)
+ self.assertNotIn('PRIVATE_SENTINEL', json.dumps(receipt.snapshot()))
+ finally:
+ server.shutdown()
+ server.server_close()
+
+ def test_reviewed_flow_has_every_receipt_mark_and_no_export_or_credential_injection_path(self):
+ flow = (Path(__file__).resolve().parents[1] / 'native/product_key_acceptance.yaml').read_text()
+ self.assertEqual(re.findall(r'STAGE: ([a-z_]+)', flow), list(product.STAGES))
+ self.assertIn('id: btn_MY_KEEPER', flow)
+ self.assertIn('id: keys_add_key', flow)
+ self.assertIn('id: btnDelete', flow)
+ for command in ['takeScreenshot:', 'copyTextFrom:', 'inputText:', 'setClipboard:', 'clearKeychain:']:
+ self.assertNotIn(command, flow)
+
+
+class RunnerTests(unittest.TestCase):
+ def exercise(self, *, omit_last=False, artifact_changed=False, command_failure=False,
+ source_dirty=False, device='emulator-5554', extra_create=False,
+ installed_failure=False, installed_mismatch=False, installed_unverified=False,
+ installed_private_extra=False):
+ directory = tempfile.TemporaryDirectory()
+ self.addCleanup(directory.cleanup)
+ root = Path(directory.name)
+ private = root / 'private'
+ private.mkdir()
+ sha = '1' * 40
+ artifact = {'sha256': 'f' * 64}
+ state = {'build': 'PASS', 'source_sha': sha, 'built_artifact': artifact,
+ 'maestro': {'binary': 'synthetic-maestro'}}
+ runtime = {}
+ backend_calls = 0
+
+ def backend_snapshot(passed=False):
+ nonlocal backend_calls
+ backend_calls += 1
+ return {'status': 'PASS', 'sample': 6, 'visible_wallet_count_after_relaunch': 1,
+ 'scenario': 'CONTROLLED_DISCONNECT_BEFORE_COMMIT_NOT_WAN_OFFLINE',
+ 'create_new_app_calls': 3 if extra_create and backend_calls > 1 else 2}
+
+ def command(_args, _label, **kwargs):
+ self.assertFalse(kwargs['error_details'])
+ output = private / 'key-ui'
+ (output / 'PRIVATE_SCREENSHOT_SENTINEL.png').write_text('PRIVATE_SENTINEL')
+ if command_failure:
+ raise RuntimeError('PRIVATE_SENTINEL')
+ for stage in product.STAGES[:-1] if omit_last else product.STAGES:
+ self.assertTrue(runtime['receipt'].mark(stage))
+
+ def server(receipt):
+ runtime['receipt'] = receipt
+ return types.SimpleNamespace(serve_forever=lambda: None, shutdown=lambda: None,
+ server_close=lambda: None)
+
+ identity = mock.Mock(side_effect=[artifact, {'sha256': 'changed'}] if artifact_changed else None,
+ return_value=artifact)
+ installed_calls = 0
+
+ def verify_installed(device):
+ nonlocal installed_calls
+ installed_calls += 1
+ state['installed_artifact_verified'] = False
+ state.pop('installed_artifact', None)
+ if installed_failure and installed_calls == 2:
+ raise RuntimeError('PRIVATE_SENTINEL')
+ proof = {'method': 'SINGLE_INSTALLED_BASE_APK_SHA256',
+ 'sha256': ('e' if installed_mismatch and installed_calls == 2 else 'f') * 64}
+ if installed_private_extra:
+ proof['unreviewed'] = 'PRIVATE_SENTINEL'
+ state['installed_artifact'] = copy.deepcopy(proof)
+ state['installed_artifact_verified'] = not installed_unverified
+ return proof
+
+ def save(value):
+ state.clear()
+ state.update(copy.deepcopy(value))
+
+ h = types.SimpleNamespace(ROOT=root, PLATFORM='ANDROID', APP_IDS={'ANDROID': 'disposable.app'},
+ read=lambda: copy.deepcopy(state), save=save, artifact_identity=identity,
+ verify_installed_artifact=verify_installed, command=command, successful_junit=lambda report: 1)
+ backend = types.SimpleNamespace(snapshot=backend_snapshot)
+ with contextlib.ExitStack() as stack:
+ stack.enter_context(mock.patch.dict(product.os.environ, {'GITHUB_ACTIONS': 'true',
+ 'RUNNER_ENVIRONMENT': 'github-hosted', 'KEEPER_SOURCE_SHA': sha}))
+ stack.enter_context(mock.patch.object(product.subprocess, 'check_output', return_value=sha))
+ stack.enter_context(mock.patch.object(product.subprocess, 'run', return_value=types.SimpleNamespace(
+ returncode=1 if source_dirty else 0)))
+ stack.enter_context(mock.patch.object(product, 'make_server', side_effect=server))
+ try:
+ value = product.run_companion(h, state, device, private, backend)
+ return value, state, private, installed_calls
+ except Exception as error:
+ return error, state, private, installed_calls
+
+ def test_complete_flow_keeps_scope_separate_and_removes_all_private_ui_output(self):
+ value, state, private, installed_calls = self.exercise()
+ self.assertEqual(value['status'], 'PASS')
+ self.assertEqual(value['new_account_requests_during_key_flow'], 0)
+ self.assertEqual(value['physical_biometrics'], 'NOT RUN')
+ self.assertEqual(installed_calls, 2)
+ self.assertTrue(value['installed_artifact_verified'])
+ self.assertEqual(value['installed_artifact']['sha256'], 'f' * 64)
+ self.assertFalse((private / 'key-ui').exists())
+ self.assertNotIn('PRIVATE_SENTINEL', json.dumps(state))
+
+ def test_missing_stage_artifact_drift_driver_failure_and_new_setup_each_fail_closed(self):
+ for option in ['omit_last', 'artifact_changed', 'command_failure', 'extra_create',
+ 'installed_failure', 'installed_mismatch', 'installed_unverified', 'installed_private_extra']:
+ with self.subTest(option=option):
+ value, state, private, _calls = self.exercise(**{option: True})
+ self.assertIsInstance(value, RuntimeError)
+ self.assertEqual(state['product_key_ui']['status'], 'FAIL')
+ self.assertFalse((private / 'key-ui').exists())
+ self.assertNotIn('PRIVATE_SENTINEL', json.dumps(state))
+
+ def test_real_device_or_dirty_source_is_rejected_before_ui_execution(self):
+ for options in [{'device': 'physical-device-id'}, {'source_dirty': True}]:
+ with self.subTest(options=options):
+ value, state, private, _calls = self.exercise(**options)
+ self.assertIsInstance(value, RuntimeError)
+ self.assertNotIn('product_key_ui', state)
+ self.assertFalse((private / 'key-ui').exists())
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/.github/tests/test_product_measurements.py b/.github/tests/test_product_measurements.py
new file mode 100644
index 0000000000..95e10b7e98
--- /dev/null
+++ b/.github/tests/test_product_measurements.py
@@ -0,0 +1,369 @@
+"""HTTP controls and fail-closed measurement receipts; these are not native tests."""
+import importlib.util
+import hashlib
+import http.client
+import json
+from pathlib import Path
+import threading
+import types
+import unittest
+from unittest import mock
+import urllib.error
+import urllib.request
+
+import yaml
+
+SPEC = importlib.util.spec_from_file_location('product_measurements',
+ Path(__file__).resolve().parents[1] / 'native/product_measurements.py')
+product = importlib.util.module_from_spec(SPEC)
+SPEC.loader.exec_module(product)
+
+
+class FixtureTests(unittest.TestCase):
+ def setUp(self):
+ self.receipt = product.Receipt()
+ self.server = product.make_server(self.receipt, port=0)
+ self.thread = threading.Thread(target=self.server.serve_forever, daemon=True)
+ self.thread.start()
+ self.base = 'http://127.0.0.1:%d' % self.server.server_port
+
+ def tearDown(self):
+ self.server.shutdown()
+ self.server.server_close()
+ self.thread.join(timeout=2)
+
+ def post(self, path, value):
+ raw = value if isinstance(value, bytes) else json.dumps(value).encode()
+ request = urllib.request.Request(self.base + path, data=raw, method='POST',
+ headers={'Content-Type': 'application/json'})
+ try:
+ with urllib.request.urlopen(request, timeout=2) as response:
+ return response.status, json.loads(response.read())
+ except urllib.error.HTTPError as error:
+ return error.code, json.loads(error.read())
+
+ def complete(self):
+ self.post('/createNewApp', {'publicId': 'DO_NOT_RETAIN', 'fcmToken': 'DO_NOT_RETAIN'})
+ for stage in product.STAGES:
+ self.assertEqual(self.post('/metric', {'stage': stage}), (200, {'accepted': True}))
+
+ def test_loopback_only(self):
+ self.assertEqual(self.server.server_address[0], '127.0.0.1')
+
+ def test_complete_numeric_receipt_does_not_retain_account_data(self):
+ self.complete()
+ evidence = self.receipt.snapshot(passed=True)
+ self.assertEqual(evidence['status'], 'PASS')
+ self.assertEqual(evidence['visible_wallet_count_after_relaunch'], 1)
+ self.assertEqual(len(evidence['raw_durations']), 5)
+ self.assertNotIn('DO_NOT_RETAIN', json.dumps(evidence))
+ self.assertTrue(all(value >= 0 for value in evidence['raw_durations'].values()))
+ self.assertFalse(evidence['pin_onboarding_progress']['complete'],
+ 'optional progress must not add a new product acceptance requirement')
+
+ def test_partial_pin_progress_is_ordered_and_independent_of_core_receipt(self):
+ self.assertEqual(self.post('/metric', {'stage': 'startup_start'})[0], 200)
+ before = self.receipt.snapshot()
+ for marker in product.PIN_MARKERS[:4]:
+ self.assertEqual(self.post('/pin-progress', {'marker': marker}), (200, {'accepted': True}))
+ after = self.receipt.snapshot()
+ progress = after.pop('pin_onboarding_progress')
+ before.pop('pin_onboarding_progress')
+ self.assertEqual(after, before, 'progress cannot change timing, stage or backend evidence')
+ self.assertEqual(progress['completed_markers'], list(product.PIN_MARKERS[:4]))
+ self.assertEqual(progress['next_marker'], product.PIN_MARKERS[4])
+ self.assertFalse(progress['complete'])
+ self.assertIn('acknowledgements only', progress['scope'])
+
+ def test_pin_marker_parser_rejects_private_unknown_duplicate_and_malformed_payloads(self):
+ bad = [
+ {'marker': 'DO_NOT_RETAIN'},
+ {'marker': product.PIN_MARKERS[1]}, # cannot skip the first marker
+ {'marker': product.PIN_MARKERS[0], 'secret': 'DO_NOT_RETAIN'},
+ {'marker': ['DO_NOT_RETAIN']}, {'marker': True}, {'marker': None},
+ ['DO_NOT_RETAIN'], 'DO_NOT_RETAIN',
+ b'{"marker":"confirm_passcode_visible","marker":"DO_NOT_RETAIN"}',
+ b'{"marker":"DO_NOT_RETAIN"', b'\xffDO_NOT_RETAIN',
+ ]
+ for payload in bad:
+ with self.subTest(payload=payload):
+ status, response = self.post('/pin-progress', payload)
+ self.assertEqual((status, response), (422, {'error': 'FIXED_PIN_PROGRESS_REJECTED'}))
+ state = self.receipt.snapshot()
+ self.assertEqual(state['pin_onboarding_progress']['completed_markers'], [])
+ self.assertEqual(state['other_backend_calls_rejected'], 0)
+ self.assertNotIn('DO_NOT_RETAIN', json.dumps((response, state)))
+
+ def test_pin_marker_duplicate_and_completion_do_not_accept_extra_events(self):
+ for index, marker in enumerate(product.PIN_MARKERS):
+ self.assertEqual(self.post('/pin-progress', {'marker': marker})[0], 200)
+ self.assertEqual(self.post('/pin-progress', {'marker': marker})[0], 422)
+ self.assertEqual(self.receipt.snapshot()['pin_onboarding_progress']['completed_markers'],
+ list(product.PIN_MARKERS[:index + 1]))
+ result = self.receipt.snapshot()['pin_onboarding_progress']
+ self.assertTrue(result['complete'])
+ self.assertIsNone(result['next_marker'])
+ self.assertEqual(self.receipt.snapshot()['status'], 'FAIL',
+ 'complete observer markers cannot grant application acceptance')
+
+ def test_pin_body_bound_is_independent_of_backend_payload_limit(self):
+ first = json.dumps({'marker': product.PIN_MARKERS[0]}).encode()
+ self.assertEqual(self.post('/pin-progress', first + b' ' * (128 - len(first)))[0], 200)
+ before = self.receipt.snapshot()
+ oversized = b'{"marker":"DO_NOT_RETAIN"}' + b' ' * 129
+ self.assertEqual(self.post('/pin-progress', oversized),
+ (413, {'error': 'FIXED_PIN_PROGRESS_REJECTED'}))
+ self.assertEqual(self.receipt.snapshot(), before)
+ self.assertNotIn('DO_NOT_RETAIN', json.dumps(before))
+
+ def test_pin_prefix_resets_for_both_normal_and_retry_fixtures(self):
+ for sample, retry in ((2, False), (6, True), (1, False)):
+ for marker in product.PIN_MARKERS:
+ self.assertEqual(self.post('/pin-progress', {'marker': marker})[0], 200)
+ self.receipt.reset(sample, retry=retry)
+ result = self.receipt.snapshot()
+ self.assertEqual(result['sample'], sample)
+ self.assertEqual(result['pin_onboarding_progress']['completed_markers'], [])
+ self.assertEqual(result['pin_onboarding_progress']['next_marker'], product.PIN_MARKERS[0])
+ self.assertFalse(result['pin_onboarding_progress']['complete'])
+ self.assertEqual(result['create_new_app_calls'], 0)
+
+ def test_out_of_order_and_duplicate_markers_are_rejected(self):
+ self.assertEqual(self.post('/metric', {'stage': 'wallet_ready'})[0], 422)
+ self.assertEqual(self.post('/metric', {'stage': 'startup_start'})[0], 200)
+ self.assertEqual(self.post('/metric', {'stage': 'startup_start'})[0], 422)
+ self.assertEqual(self.receipt.snapshot()['completed_stages'], ['startup_start'])
+
+ def test_unknown_marker_and_additional_fields_are_rejected_without_echo(self):
+ for payload in ({'stage': 'DO_NOT_RETAIN'}, {'stage': 'startup_start', 'secret': 'DO_NOT_RETAIN'}):
+ status, response = self.post('/metric', payload)
+ self.assertEqual(status, 422)
+ self.assertNotIn('DO_NOT_RETAIN', json.dumps(response))
+ self.assertEqual(self.receipt.snapshot()['completed_stages'], [])
+
+ def test_duplicate_setup_fails_even_after_every_ui_stage(self):
+ self.complete()
+ self.post('/createNewApp', b'{}')
+ with self.assertRaisesRegex(RuntimeError, 'DUPLICATE_SETUP'):
+ self.receipt.snapshot(passed=True)
+
+ def test_missing_setup_or_partial_flow_cannot_pass(self):
+ self.receipt.mark('startup_start')
+ with self.assertRaises(RuntimeError):
+ self.receipt.snapshot(passed=True)
+ self.assertEqual(self.receipt.snapshot()['status'], 'FAIL')
+
+ def test_unknown_backend_route_fails_closed(self):
+ status, response = self.post('/deleteBackup', b'{}')
+ self.assertEqual(status, 503)
+ self.assertNotIn('deleted', response)
+ self.assertEqual(self.receipt.snapshot()['other_backend_calls_rejected'], 1)
+
+ def test_rejected_get_is_counted_without_echoing_path_or_query(self):
+ with self.assertRaises(urllib.error.HTTPError) as failure:
+ urllib.request.urlopen(self.base + '/DO_NOT_RETAIN?secret=DO_NOT_RETAIN', timeout=2)
+ self.assertEqual(failure.exception.code, 503)
+ self.assertNotIn('DO_NOT_RETAIN', failure.exception.read().decode())
+ self.assertEqual(self.receipt.snapshot()['other_backend_calls_rejected'], 1)
+ self.assertNotIn('DO_NOT_RETAIN', json.dumps(self.receipt.snapshot()))
+
+ def test_oversized_payload_is_rejected_without_retention(self):
+ self.assertEqual(self.post('/createNewApp', b'x' * 8193)[0], 413)
+ self.assertEqual(self.receipt.snapshot()['create_new_app_calls'], 0)
+
+ def test_reset_discards_prior_sample_receipt(self):
+ self.complete()
+ self.receipt.reset(2)
+ state = self.receipt.snapshot()
+ self.assertEqual((state['sample'], state['create_new_app_calls']), (2, 0))
+ self.assertEqual(state['completed_stages'], [])
+
+ def start_retry_fixture(self):
+ self.receipt.reset(6, retry=True)
+ self.assertEqual(self.post('/metric', {'stage': 'retry_fixture_start'})[0], 200)
+ with self.assertRaises(http.client.RemoteDisconnected):
+ self.post('/createNewApp', {'publicId': 'DO_NOT_RETAIN'})
+
+ def finish_retry_fixture(self):
+ self.start_retry_fixture()
+ for stage in ('retry_error_visible', 'retry_submit'):
+ self.assertEqual(self.post('/metric', {'stage': stage})[0], 200)
+ self.assertEqual(self.post('/createNewApp', b'{}'), (200, {'created': True}))
+ for stage in product.RETRY_STAGES[3:]:
+ self.assertEqual(self.post('/metric', {'stage': stage})[0], 200)
+
+ def test_real_disconnect_then_explicit_retry_receipt_is_separate_from_timings(self):
+ self.finish_retry_fixture()
+ result = self.receipt.snapshot(passed=True)
+ self.assertEqual(result['create_new_app_calls'], 2)
+ self.assertEqual(result['transport_requests_dropped_without_commit'], 1)
+ self.assertEqual(result['acknowledged_create_responses'], 1)
+ self.assertEqual(result['visible_wallet_count_after_relaunch'], 1)
+ self.assertFalse(result['performance_sample'])
+ self.assertNotIn('raw_durations', result)
+ self.assertNotIn('DO_NOT_RETAIN', json.dumps(result))
+ self.assertFalse(result['pin_onboarding_progress']['complete'],
+ 'optional progress must not change controlled Retry acceptance')
+
+ def test_automatic_hidden_retry_prevents_error_marker_and_acceptance(self):
+ self.start_retry_fixture()
+ self.post('/createNewApp', b'{}') # without explicit UI Retry marker
+ self.assertEqual(self.post('/metric', {'stage': 'retry_error_visible'})[0], 422)
+ self.assertEqual(self.receipt.snapshot()['unexpected_create_attempts'], 1)
+ with self.assertRaises(RuntimeError):
+ self.receipt.snapshot(passed=True)
+
+ def test_extra_creation_after_relaunch_invalidates_retry_fixture(self):
+ self.finish_retry_fixture()
+ self.post('/createNewApp', b'{}')
+ with self.assertRaises(RuntimeError):
+ self.receipt.snapshot(passed=True)
+
+ def test_ui_error_cannot_be_claimed_without_real_first_disconnect(self):
+ self.receipt.reset(6, retry=True)
+ self.post('/metric', {'stage': 'retry_fixture_start'})
+ self.assertEqual(self.post('/metric', {'stage': 'retry_error_visible'})[0], 422)
+ self.assertEqual(self.receipt.snapshot()['transport_requests_dropped_without_commit'], 0)
+
+
+class PinFlowTests(unittest.TestCase):
+ def test_markers_follow_existing_actions_without_changing_the_pin_flow(self):
+ filename = Path(product.__file__).with_name('product_prepare_pin.yaml')
+ header, commands = list(yaml.safe_load_all(filename.read_text()))
+ self.assertEqual(header, {'appId': '${APP_ID}'})
+ expected = [
+ {'repeat': {'times': 4, 'commands': [{'tapOn': {'id': 'key_1'}}]}},
+ {'assertVisible': 'Confirm your passcode'},
+ {'repeat': {'times': 4, 'commands': [{'tapOn': {'id': 'key_1'}}]}},
+ {'tapOn': 'Create'},
+ {'extendedWaitUntil': {'visible': 'Continue', 'timeout': 30000}},
+ {'tapOn': 'Continue'},
+ {'extendedWaitUntil': {'visible': 'Cancel', 'timeout': 30000}},
+ {'tapOn': 'Cancel'},
+ {'extendedWaitUntil': {'visible': {'id': 'btn_skip'}, 'timeout': 30000}},
+ {'tapOn': {'id': 'btn_skip'}},
+ {'extendedWaitUntil': {'visible': {'id': 'view_startNewTile'}, 'timeout': 30000}},
+ ]
+ actions, markers, positions = [], [], []
+ for command in commands:
+ if 'runScript' not in command:
+ actions.append(command)
+ continue
+ self.assertEqual(set(command), {'runScript'})
+ script = command['runScript']
+ self.assertEqual(set(script), {'file', 'env'})
+ self.assertEqual(script['file'], 'product_pin_metric.js')
+ self.assertEqual(set(script['env']), {'MARKER'})
+ markers.append(script['env']['MARKER'])
+ positions.append(len(actions))
+ self.assertEqual(actions, expected)
+ self.assertEqual(markers, list(product.PIN_MARKERS))
+ self.assertEqual(positions, list(range(2, 12)), 'acknowledge each existing completed operation')
+
+
+class AndroidFailureObservationTests(unittest.TestCase):
+ def test_only_sample_private_directory_and_device_are_passed_to_fixed_collector(self):
+ facts = {'diagnostic_only': True, 'cause': 'UNDETERMINED', 'cleanup_status': 'DELETED'}
+ module = types.SimpleNamespace(collect=mock.Mock(return_value=facts))
+ spec = types.SimpleNamespace(loader=types.SimpleNamespace(exec_module=mock.Mock()))
+ with mock.patch.object(product.importlib.util, 'spec_from_file_location', return_value=spec) as source, \
+ mock.patch.object(product.importlib.util, 'module_from_spec', return_value=module):
+ value = product.android_failure_observation(Path('/owned/sample-1'), 'emulator-5554')
+ self.assertEqual(source.call_args.args[1], Path(product.__file__).with_name('android_startup_diagnosis.py'))
+ module.collect.assert_called_once_with(Path('/owned/sample-1'), 'emulator-5554')
+ self.assertEqual(value['facts'], facts)
+ self.assertEqual(value['status'], 'COLLECTED')
+ self.assertIn('no current product Metro log', value['scope'])
+
+ def test_import_and_collector_failures_have_only_fixed_unavailable_metadata(self):
+ for importing in (True, False):
+ with self.subTest(importing=importing):
+ loader = types.SimpleNamespace(exec_module=mock.Mock(
+ side_effect=RuntimeError('DO_NOT_RETAIN') if importing else None))
+ spec = types.SimpleNamespace(loader=loader)
+ module = types.SimpleNamespace(collect=mock.Mock(side_effect=RuntimeError('DO_NOT_RETAIN')))
+ with mock.patch.object(product.importlib.util, 'spec_from_file_location', return_value=spec), \
+ mock.patch.object(product.importlib.util, 'module_from_spec', return_value=module):
+ value = product.android_failure_observation(Path('/owned/sample-1'), 'emulator-5554')
+ self.assertEqual(value['status'], 'UNAVAILABLE')
+ self.assertEqual(set(value), {'status', 'scope'})
+ self.assertNotIn('DO_NOT_RETAIN', json.dumps(value))
+ self.assertEqual(module.collect.call_count, 0 if importing else 1)
+
+
+class PackageOverlayTests(unittest.TestCase):
+ def setUp(self):
+ self.original = {'name': 'fixture', 'dependencies': {'crypto-shim': '1.0.0'},
+ 'scripts': {'start': 'react-native start'}, 'browser': {'path': 'before'}}
+ self.installed = {**self.original, 'browser': {'path': 'react-native-path'},
+ 'react-native': {'crypto': 'crypto-shim'}, 'browserify': {'transform': []}}
+
+ def evidence(self, original=None, installed=None):
+ original_bytes = json.dumps(self.original if original is None else original).encode()
+ installed_bytes = json.dumps(self.installed if installed is None else installed).encode()
+ return original_bytes, installed_bytes, {
+ 'path': 'package.json', 'allowed_fields': ['browser', 'react-native', 'browserify'],
+ 'before_sha256': hashlib.sha256(original_bytes).hexdigest(),
+ 'after_sha256': hashlib.sha256(installed_bytes).hexdigest(),
+ }
+
+ def test_recorded_mapping_overlay_is_accepted(self):
+ product.verify_package_overlay(*self.evidence())
+
+ def test_recorded_unchanged_mapping_is_accepted(self):
+ product.verify_package_overlay(*self.evidence(installed=self.original))
+
+ def test_unrecorded_changes_are_rejected(self):
+ original, installed, overlay = self.evidence()
+ for missing in (None, {}, {**overlay, 'after_sha256': '0' * 64}):
+ with self.assertRaisesRegex(RuntimeError, 'UNRECORDED'):
+ product.verify_package_overlay(original, installed, missing)
+
+ def test_recording_must_match_committed_original_bytes(self):
+ original, installed, overlay = self.evidence()
+ with self.assertRaisesRegex(RuntimeError, 'UNRECORDED'):
+ product.verify_package_overlay(original + b' ', installed, overlay)
+
+ def test_hash_matching_protected_dependency_change_is_rejected(self):
+ installed = {**self.installed, 'dependencies': {'crypto-shim': '2.0.0'}}
+ with self.assertRaisesRegex(RuntimeError, 'PROTECTED_FIELDS_CHANGED'):
+ product.verify_package_overlay(*self.evidence(installed=installed))
+
+ def test_hash_matching_script_change_is_rejected(self):
+ installed = {**self.installed, 'scripts': {'start': 'different-entrypoint'}}
+ with self.assertRaisesRegex(RuntimeError, 'PROTECTED_FIELDS_CHANGED'):
+ product.verify_package_overlay(*self.evidence(installed=installed))
+
+ def test_expanded_field_allowlist_and_wrong_path_are_rejected(self):
+ original, installed, overlay = self.evidence()
+ for changed in ({**overlay, 'allowed_fields': overlay['allowed_fields'] + ['dependencies']},
+ {**overlay, 'path': 'another-package.json'}):
+ with self.assertRaisesRegex(RuntimeError, 'UNRECORDED'):
+ product.verify_package_overlay(original, installed, changed)
+
+
+class VersionExpectationTests(unittest.TestCase):
+ def test_installed_and_history_match_their_actual_native_format(self):
+ manifest = {'version': '2.6.4', 'androidVersionCode': 627, 'iosBuildNumber': 620}
+ for platform, build in [('ANDROID', 627), ('IOS', 620)]:
+ expected = product.version_expectation(manifest, platform)
+ self.assertRegex('2.6.4 (%d)' % build, expected['installed_regex'])
+ self.assertRegex('2.6.4(%d)' % build, expected['history_regex'])
+ self.assertNotRegex('2x6x4 (%d)' % build, expected['installed_regex'])
+
+ def test_new_source_versions_do_not_reuse_previous_expected_tuple(self):
+ expected = product.version_expectation({'version': '2.7.0', 'iosBuildNumber': 701}, 'IOS')
+ self.assertRegex('2.7.0 (701)', expected['installed_regex'])
+ self.assertNotRegex('2.6.4 (620)', expected['installed_regex'])
+
+ def test_work_package_labels_or_missing_invalid_builds_are_rejected(self):
+ for manifest in ({'version': '5.1', 'iosBuildNumber': 620},
+ {'version': '2.6.4'},
+ {'version': '2.6.4', 'iosBuildNumber': True},
+ {'version': '2.6.4', 'iosBuildNumber': -1}):
+ with self.assertRaises(RuntimeError):
+ product.version_expectation(manifest, 'IOS')
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/.github/tests/test_product_metro.py b/.github/tests/test_product_metro.py
new file mode 100644
index 0000000000..c8e9ad1e48
--- /dev/null
+++ b/.github/tests/test_product_metro.py
@@ -0,0 +1,393 @@
+"""Owned host process/flow boundaries; no native application acceptance."""
+import contextlib
+import importlib.util
+import copy
+import hashlib
+import json
+from pathlib import Path
+import signal
+import subprocess
+import tempfile
+import types
+import unittest
+from unittest import mock
+
+NATIVE = Path(__file__).resolve().parents[1] / 'native'
+
+
+def load(name):
+ spec = importlib.util.spec_from_file_location(name, NATIVE / (name + '.py'))
+ module = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(module)
+ return module
+
+
+metro = load('product_metro')
+product = load('product_measurements')
+
+
+class MetroTests(unittest.TestCase):
+ def setUp(self):
+ directory = tempfile.TemporaryDirectory()
+ self.addCleanup(directory.cleanup)
+ self.private = Path(directory.name)
+ self.h = types.SimpleNamespace(ROOT=NATIVE.parents[1], PLATFORM='ANDROID',
+ APP_IDS={'ANDROID': 'owned.app'}, warm_metro_bundle=mock.Mock(),
+ successful_junit=mock.Mock(return_value=1))
+ self.children, self.spawn_args = [], []
+
+ def spawn(args, **kwargs):
+ child = mock.Mock(pid=10000 + len(self.children))
+ child.poll.return_value = None
+ self.children.append(child)
+ self.spawn_args.append((args, kwargs))
+ return child
+ stack = contextlib.ExitStack()
+ self.addCleanup(stack.close)
+ self.spawn = stack.enter_context(mock.patch.object(metro.subprocess, 'Popen', side_effect=spawn))
+ self.kill = stack.enter_context(mock.patch.object(metro.os, 'killpg'))
+ stack.enter_context(mock.patch.object(metro.time, 'sleep'))
+ self.port = stack.enter_context(mock.patch.object(metro.OwnedMetro, 'port_occupied', return_value=False))
+ self.status = stack.enter_context(mock.patch.object(metro.urllib.request, 'urlopen'))
+ reply = self.status.return_value.__enter__.return_value
+ reply.status, reply.read.return_value = 200, b'packager-status:running'
+ self.manager = metro.OwnedMetro(self.h, self.private)
+
+ def test_fixed_bundle_switches_scrub_fixture_env_and_keep_phase_specific_warmups(self):
+ with mock.patch.dict(metro.os.environ, {'KEEPER_CREDENTIAL_FIXTURE_PHASE': 'restore'}):
+ self.manager.start('product', initial=True)
+ with self.assertRaisesRegex(RuntimeError, 'STOPPED_JUNIT'):
+ self.manager.switch('arm')
+ for phase in ('arm', 'product', 'history_seed_stale', 'product'):
+ self.manager.app_stopped = True # facade-owned grant tested below
+ self.manager.switch(phase)
+ for (args, kwargs), phase in zip(self.spawn_args,
+ ('product', 'arm', 'product', 'history_seed_stale', 'product')):
+ self.assertTrue(kwargs['start_new_session'])
+ self.assertEqual(kwargs['env'].get('KEEPER_CREDENTIAL_FIXTURE_PHASE'),
+ 'arm' if phase == 'arm' else None)
+ self.assertEqual('--config' in args, phase != 'product')
+ self.assertEqual(self.h.warm_metro_bundle.call_args_list,
+ [mock.call('startup'), mock.call('product_ui_arm'), mock.call('product_ui_product'),
+ mock.call('product_ui_history_seed_stale'), mock.call('product_ui_product')])
+ self.manager.close()
+ self.assertTrue(all(child.wait.called for child in self.children))
+
+ def test_foreign_listener_arbitrary_phase_and_unowned_process_are_never_adopted_or_killed(self):
+ self.port.return_value = True
+ with self.assertRaisesRegex(RuntimeError, 'PORT_OCCUPIED'):
+ self.manager.start('product', initial=True)
+ with self.assertRaisesRegex(RuntimeError, 'PHASE_REJECTED'):
+ self.manager.switch('../index.js')
+ with self.assertRaisesRegex(RuntimeError, 'UNOWNED_PROCESS'):
+ self.manager.stop(mock.Mock(pid=1))
+ self.spawn.assert_not_called()
+ self.kill.assert_not_called()
+
+ def test_latest_child_is_retained_for_cleanup_when_readiness_warmup_or_spawn_fails(self):
+ for failure in ('readiness', 'warmup', 'spawn'):
+ with self.subTest(failure=failure):
+ manager = metro.OwnedMetro(self.h, self.private)
+ self.h.warm_metro_bundle.side_effect = RuntimeError('private') if failure == 'warmup' else None
+ self.status.side_effect = OSError() if failure == 'readiness' else None
+ if failure == 'spawn':
+ self.spawn.side_effect = OSError('private')
+ with self.assertRaises((RuntimeError, OSError)):
+ manager.start('product', initial=True)
+ manager.close()
+ if failure != 'spawn':
+ self.assertIs(manager.process, manager.owned[-1])
+ self.assertTrue(manager.process.wait.called)
+ self.assertEqual(manager.events[-1]['status'], 'FAIL')
+
+ def test_timeout_escalates_and_waits_after_kill_and_cleanup_still_visits_every_owned_child(self):
+ self.manager.start('product', initial=True)
+ first = self.children[0]
+ first.wait.side_effect = [subprocess.TimeoutExpired('owned', 10), 0]
+ self.manager.app_stopped = True
+ self.manager.switch('arm')
+ first.wait.assert_has_calls([mock.call(timeout=10), mock.call(timeout=10)])
+ self.assertIn(mock.call(first.pid, signal.SIGKILL), self.kill.call_args_list)
+ second = self.children[-1]
+ second.wait.side_effect = RuntimeError('private')
+ with self.assertRaisesRegex(RuntimeError, 'CLEANUP_FAILED'):
+ self.manager.close()
+ self.assertTrue(second.wait.called)
+
+ def test_failed_replacement_start_keeps_both_owned_handles_for_final_cleanup(self):
+ self.manager.start('product', initial=True)
+ first = self.children[0]
+ self.manager.app_stopped = True
+ self.h.warm_metro_bundle.side_effect = RuntimeError('private')
+ with self.assertRaises(RuntimeError):
+ self.manager.switch('arm')
+ self.assertEqual(len(self.manager.owned), 2)
+ self.assertIs(self.manager.process, self.children[-1])
+ self.manager.close()
+ self.assertTrue(first.wait.called)
+ self.assertTrue(self.children[-1].wait.called)
+
+ def test_flow_facade_requires_matching_new_successful_junit_and_reviewed_final_stop(self):
+ self.manager.start('product', initial=True)
+ data = {'maestro': {'binary': 'owned-maestro'}}
+ report = self.private / 'flow.xml'
+ report.write_text('stale')
+
+ def command(_args, _label, **_kwargs):
+ self.assertFalse(report.exists(), 'stale report must be removed before invocation')
+ report.write_text('new')
+ self.h.command = mock.Mock(side_effect=command)
+ facade = metro.StoppedFlowHarness(self.h, data, 'emulator-5554', self.private, self.manager, set())
+ args = ['owned-maestro', '--device', 'emulator-5554', 'test', '--env', 'APP_ID=owned.app',
+ '--output', str(report), '--debug-output', str(self.private),
+ '--test-output-dir', str(self.private), '--format', 'junit',
+ '.github/native/product_key_acceptance.yaml']
+ facade.command(args, 'fixed', error_details=False)
+ self.assertFalse(self.manager.app_stopped)
+ with self.assertRaisesRegex(RuntimeError, 'MATCHING_JUNIT'):
+ facade.successful_junit(self.private / 'other.xml')
+ self.h.successful_junit.side_effect = RuntimeError('failed junit')
+ with self.assertRaises(RuntimeError):
+ facade.successful_junit(report)
+ self.assertFalse(self.manager.app_stopped)
+ with self.assertRaisesRegex(RuntimeError, 'MATCHING_JUNIT'):
+ facade.successful_junit(report)
+ self.h.successful_junit.side_effect = None
+ facade.command(args, 'fixed', error_details=False)
+ facade.successful_junit(report)
+ self.assertTrue(self.manager.app_stopped)
+ self.manager.switch('arm')
+ self.assertFalse(self.manager.app_stopped)
+ for changed in (args[:2] + ['another-device'] + args[3:],
+ args[:-1] + ['.github/native/unknown.yaml']):
+ with self.assertRaisesRegex(RuntimeError, 'REVIEWED_FLOW'):
+ facade.command(changed, 'fixed', error_details=False)
+ self.manager.phase = 'product'
+ outside = args.copy()
+ outside[outside.index('--debug-output') + 1] = '/tmp'
+ with self.assertRaisesRegex(RuntimeError, 'PRIVATE_OUTPUT'):
+ facade.command(outside, 'fixed', error_details=False)
+ self.h.command.side_effect = lambda *_a, **_k: report.symlink_to(self.private.parent / 'outside.xml')
+ with self.assertRaisesRegex(RuntimeError, 'PRIVATE_JUNIT'):
+ facade.command(args, 'fixed', error_details=False)
+ self.assertIsNone(facade.pending)
+ self.manager.close()
+
+
+class IntegrationTests(unittest.TestCase):
+ def test_ios_readiness_precedes_first_product_install_and_keeps_failure_cleanup(self):
+ for readiness_fails in (False, True):
+ with self.subTest(readiness_fails=readiness_fails), tempfile.TemporaryDirectory() as directory:
+ root = Path(directory)
+ private = root / 'private'
+ private.mkdir()
+ (root / 'release').mkdir()
+ manifest = b'{"name":"owned"}'
+ (root / 'package.json').write_bytes(manifest)
+ (root / 'release/version.json').write_text(json.dumps(
+ {'version': '2.6.4', 'androidVersionCode': 627, 'iosBuildNumber': 620}))
+ (root / '.env.ci').write_text('\n'.join([
+ 'ENVIRONMENT=DEVELOPMENT', 'RELAY=http://127.0.0.1:8765/',
+ 'SIGNING_SERVER_TESTNET=https://127.0.0.1:9/', 'SIGNING_SERVER_MAINNET=https://127.0.0.1:9/',
+ 'CHANNEL_URL=https://127.0.0.1:9/', 'SENTRY_DNS=https://public@127.0.0.1:9/1',
+ 'ENC_KEY_STORAGE_IDENTIFIER=KEEPER-HOSTED-DISPOSABLE']))
+ sha, artifact, order = 'a' * 40, {'sha256': 'b' * 64}, []
+ owned = '12345678-1234-1234-1234-123456789ABC'
+ digest = hashlib.sha256(manifest).hexdigest()
+ state = {'build': 'PASS', 'source_sha': sha, 'built_artifact': artifact,
+ 'commands': [], 'maestro': {'binary': 'fake-maestro'}, 'nodeify_overlay': {
+ 'path': 'package.json', 'allowed_fields': ['browser', 'react-native', 'browserify'],
+ 'before_sha256': digest, 'after_sha256': digest}}
+ original_error = RuntimeError('PRIVATE_SENTINEL original setup failure')
+
+ def save(value):
+ state.clear()
+ state.update(copy.deepcopy(value))
+
+ def command(args, label, **kwargs):
+ order.append(label)
+ if label == 'Create task-owned product UI simulator':
+ return owned
+ if label == 'Install exact product UI app':
+ self.assertEqual(kwargs, {'timeout': 120})
+ raise original_error
+
+ def ready(device):
+ self.assertEqual(device, owned)
+ order.append('app-services-ready')
+ if readiness_fails:
+ raise original_error
+
+ manager = types.SimpleNamespace(start=lambda *_a, **_k: order.append('metro-start'),
+ close=lambda: order.append('metro-close'), events=[])
+ server = types.SimpleNamespace(serve_forever=lambda: None,
+ shutdown=lambda: order.append('server-stop'), server_close=lambda: None)
+ h = types.SimpleNamespace(ROOT=root, PRIVATE=private, PLATFORM='IOS', APP_IDS={'IOS': 'owned.app'},
+ read=lambda: copy.deepcopy(state), save=save, artifact_identity=lambda: artifact,
+ command=command, wait_for_simulator_app_services=ready)
+
+ def shell(args, **_kwargs):
+ if args[:2] == ['xcrun', 'simctl']:
+ order.append('device-' + args[2])
+ return types.SimpleNamespace(returncode=0)
+
+ with contextlib.ExitStack() as stack:
+ stack.enter_context(mock.patch.dict(product.os.environ, {'GITHUB_ACTIONS': 'true',
+ 'RUNNER_ENVIRONMENT': 'github-hosted', 'KEEPER_SOURCE_SHA': sha}))
+ stack.enter_context(mock.patch.object(product.subprocess, 'check_output', side_effect=[sha, manifest]))
+ stack.enter_context(mock.patch.object(product.subprocess, 'run', side_effect=shell))
+ stack.enter_context(mock.patch.object(product, 'native_module',
+ return_value=types.SimpleNamespace(OwnedMetro=lambda *_: manager)))
+ stack.enter_context(mock.patch.object(product, 'make_server', return_value=server))
+ with self.assertRaises(RuntimeError) as failure:
+ product.run(h)
+ self.assertIs(failure.exception, original_error)
+ self.assertLess(order.index('Wait for product UI simulator'), order.index('app-services-ready'))
+ if readiness_fails:
+ self.assertNotIn('Install exact product UI app', order)
+ self.assertNotIn('Reset task-owned simulator credentials', order)
+ else:
+ self.assertLess(order.index('app-services-ready'), order.index('Install exact product UI app'))
+ self.assertLess(order.index('metro-close'), order.index('device-shutdown'))
+ self.assertLess(order.index('device-shutdown'), order.index('device-delete'))
+ self.assertEqual(state['product_ui']['samples'], [])
+ self.assertEqual(state['product_ui']['status'], 'FAIL')
+ self.assertNotIn('Full-product first-wallet and relaunch UI sample', order)
+ self.assertIn('server-stop', order)
+ self.assertEqual(list(private.iterdir()), [])
+
+ def test_primary_ui_failure_survives_save_and_metro_cleanup_errors_while_all_owned_data_is_disposed(self):
+ class PrimaryFailure(RuntimeError):
+ pass
+ with tempfile.TemporaryDirectory() as directory:
+ root = Path(directory)
+ private = root / 'private'
+ private.mkdir()
+ (root / 'release').mkdir()
+ manifest = b'{"name":"owned"}'
+ (root / 'package.json').write_bytes(manifest)
+ (root / 'release/version.json').write_text(json.dumps(
+ {'version': '2.6.4', 'androidVersionCode': 627, 'iosBuildNumber': 620}))
+ (root / '.env.ci').write_text('\n'.join([
+ 'ENVIRONMENT=DEVELOPMENT', 'RELAY=http://127.0.0.1:8765/',
+ 'SIGNING_SERVER_TESTNET=https://127.0.0.1:9/', 'SIGNING_SERVER_MAINNET=https://127.0.0.1:9/',
+ 'CHANNEL_URL=https://127.0.0.1:9/', 'SENTRY_DNS=https://public@127.0.0.1:9/1',
+ 'ENC_KEY_STORAGE_IDENTIFIER=KEEPER-HOSTED-DISPOSABLE']))
+ sha, artifact, order = 'a' * 40, {'sha256': 'b' * 64}, []
+ digest = hashlib.sha256(manifest).hexdigest()
+ state = {'build': 'PASS', 'source_sha': sha, 'built_artifact': artifact,
+ 'commands': [], 'maestro': {'binary': 'fake-maestro'}, 'nodeify_overlay': {
+ 'path': 'package.json', 'allowed_fields': ['browser', 'react-native', 'browserify'],
+ 'before_sha256': digest, 'after_sha256': digest}}
+ receipts, runtime = [], {}
+ original_error = PrimaryFailure('PRIVATE_SENTINEL')
+ def save(value):
+ receipts.append(copy.deepcopy(value['product_ui']))
+ if value['product_ui']['status'] == 'FAIL':
+ raise OSError('PRIVATE_SENTINEL')
+ state.clear()
+ state.update(copy.deepcopy(value))
+ def command(args, *_args, **_kwargs):
+ state['commands'].append({})
+ (private / ('command-%03d.log' % len(state['commands']))).write_text('PRIVATE_SENTINEL')
+ if args == ['adb', 'get-serialno']:
+ return 'emulator-5554'
+ if args[0] == 'fake-maestro':
+ for stage in product.STAGES[:2]:
+ runtime['receipt'].mark(stage)
+ for marker in product.PIN_MARKERS[:3]:
+ runtime['receipt'].mark_pin(marker)
+ output = Path(args[args.index('--debug-output') + 1])
+ (output / 'private-failure.png').write_text('PRIVATE_SENTINEL')
+ raise original_error
+ return 'fake image'
+ def installed(_device):
+ proof = {'method': 'SINGLE_INSTALLED_BASE_APK_SHA256', 'sha256': 'c' * 64}
+ state.update(installed_artifact_verified=True, installed_artifact=proof)
+ return proof
+ def close():
+ order.append('metro-close')
+ raise RuntimeError('PRIVATE_SENTINEL')
+ manager = types.SimpleNamespace(start=lambda *_a, **_k: None, close=close, events=[])
+ server = types.SimpleNamespace(serve_forever=lambda: None, shutdown=lambda: order.append('server-stop'),
+ server_close=lambda: None)
+ def make_server(receipt):
+ runtime['receipt'] = receipt
+ return server
+ def observe(output, device):
+ self.assertEqual(output.name, 'sample-1')
+ self.assertTrue((output / 'private-failure.png').exists())
+ self.assertEqual(device, 'emulator-5554')
+ order.append('failure-observation')
+ return {'status': 'UNAVAILABLE'}
+ h = types.SimpleNamespace(ROOT=root, PRIVATE=private, PLATFORM='ANDROID',
+ APP_IDS={'ANDROID': 'owned.app'}, read=lambda: copy.deepcopy(state), save=save,
+ artifact_identity=lambda: artifact, command=command, verify_installed_artifact=installed)
+ def shell(args, **_kwargs):
+ if args[0] == 'adb':
+ order.append('device-cleanup')
+ return types.SimpleNamespace(returncode=0)
+ with contextlib.ExitStack() as stack:
+ stack.enter_context(mock.patch.dict(product.os.environ, {'GITHUB_ACTIONS': 'true',
+ 'RUNNER_ENVIRONMENT': 'github-hosted', 'KEEPER_SOURCE_SHA': sha}))
+ stack.enter_context(mock.patch.object(product.subprocess, 'check_output', side_effect=[sha, manifest]))
+ stack.enter_context(mock.patch.object(product.subprocess, 'run', side_effect=shell))
+ stack.enter_context(mock.patch.object(product, 'native_module',
+ return_value=types.SimpleNamespace(OwnedMetro=lambda *_: manager)))
+ stack.enter_context(mock.patch.object(product, 'make_server', side_effect=make_server))
+ observation = stack.enter_context(mock.patch.object(product, 'android_failure_observation', side_effect=observe))
+ with self.assertRaises(PrimaryFailure) as failure:
+ product.run(h)
+ self.assertIs(failure.exception, original_error)
+ observation.assert_called_once()
+ self.assertLess(order.index('failure-observation'), order.index('metro-close'))
+ self.assertLess(order.index('metro-close'), order.index('device-cleanup'))
+ self.assertIn('server-stop', order)
+ self.assertEqual(list(private.iterdir()), [], 'task-owned UI/process output must be removed')
+ failed = receipts[-1]
+ self.assertEqual(failed['status'], 'FAIL')
+ self.assertEqual(len(failed['samples']), 1, 'the original command must not be retried')
+ self.assertEqual(failed['samples'][0]['completed_stages'], list(product.STAGES[:2]))
+ self.assertEqual(failed['samples'][0]['pin_onboarding_progress']['completed_markers'],
+ list(product.PIN_MARKERS[:3]))
+ self.assertEqual(failed['samples'][0]['android_runtime_diagnostic'], {'status': 'UNAVAILABLE'})
+ self.assertNotIn('PRIVATE_SENTINEL', json.dumps(receipts))
+
+ def test_order_preserves_completed_receipts_if_a_later_companion_fails(self):
+ for fail_history in (False, True):
+ calls, result = [], {}
+ control = types.SimpleNamespace(ensure_product=lambda: calls.append('product'), switch=lambda _: None)
+ proof = object()
+ def module(name):
+ def run(*args):
+ calls.append(name)
+ self.assertIs(args[-1], proof if name.endswith('vault_acceptance') else control.switch)
+ if fail_history and name == 'product_history_acceptance':
+ raise RuntimeError('private')
+ return {'status': 'PASS'}
+ return types.SimpleNamespace(run_companion=run)
+ with mock.patch.object(product, 'native_module', side_effect=module):
+ try:
+ product.run_post_key_companions(None, None, None, None, None, control, proof, result)
+ except RuntimeError:
+ self.assertTrue(fail_history)
+ self.assertEqual(calls[:5], ['product', 'product_credential_acceptance', 'product',
+ 'product', 'product_history_acceptance'])
+ self.assertIn('credential_errors_ui', result)
+ self.assertEqual('vault_references_ui' in result, not fail_history)
+ if not fail_history:
+ self.assertEqual(calls[-1], 'product')
+
+ def test_backend_and_receipt_ports_are_unique_and_match_fixed_metric_urls(self):
+ modules = [load(name) for name in ('product_measurements', 'product_key_acceptance',
+ 'product_credential_acceptance', 'product_vault_acceptance')]
+ ports = [module.PORT for module in modules]
+ self.assertEqual(ports, [8765, 8766, 8767, 8769])
+ self.assertEqual(len(set([*ports, 8768])), 5, '8768 belongs to private-protocol controls')
+ for port, filename in [(8766, 'product_key_metric.js'), (8767, 'product_credential_metric.js'),
+ (8769, 'product_vault_metric.js')]:
+ self.assertIn('http://127.0.0.1:%d/metric' % port, (NATIVE / filename).read_text())
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/.github/tests/test_product_vault_acceptance.py b/.github/tests/test_product_vault_acceptance.py
new file mode 100644
index 0000000000..34749933d8
--- /dev/null
+++ b/.github/tests/test_product_vault_acceptance.py
@@ -0,0 +1,225 @@
+"""Host controls only: no emulator, native acceptance or backend credit."""
+import contextlib
+import copy
+import importlib.util
+import json
+from pathlib import Path
+import re
+import tempfile
+import threading
+import types
+import unittest
+from unittest import mock
+import urllib.error
+import urllib.request
+
+SPEC = importlib.util.spec_from_file_location(
+ 'product_vault_acceptance', Path(__file__).resolve().parents[1] / 'native/product_vault_acceptance.py')
+product = importlib.util.module_from_spec(SPEC)
+SPEC.loader.exec_module(product)
+NATIVE = Path(__file__).resolve().parents[1] / 'native'
+
+
+class ReceiptTests(unittest.TestCase):
+ def test_all_stages_are_required_in_order_and_pass_remains_scoped(self):
+ receipt = product.Receipt()
+ self.assertFalse(receipt.mark(product.STAGES[-1]))
+ for stage in product.STAGES:
+ self.assertTrue(receipt.mark(stage))
+ self.assertFalse(receipt.mark(stage))
+ evidence = receipt.snapshot(passed=True)
+ self.assertEqual(evidence['status'], 'PASS')
+ self.assertEqual(evidence['archived_only_key_semantics'], 'LOGICAL_ARCHIVE_AND_REINSTATE_VERIFIED')
+ self.assertEqual(evidence['final_visible_wallet_count'], 3)
+ self.assertEqual(evidence['native_private_material_exactness'], 'NOT DIRECTLY INSPECTED BY UI')
+ self.assertEqual(evidence['physical_biometrics'], 'NOT RUN')
+ self.assertIn('NOT TESTED', evidence['backend_compatibility'])
+ self.assertEqual(evidence['release_readiness'], 'NOT ESTABLISHED')
+
+ def test_partial_work_does_not_become_native_acceptance(self):
+ receipt = product.Receipt()
+ for stage in product.STAGES[:-1]:
+ receipt.mark(stage)
+ with self.assertRaisesRegex(RuntimeError, 'INCOMPLETE'):
+ receipt.snapshot(passed=True)
+ self.assertEqual(receipt.snapshot()['visible_reference_ui'], 'NOT ESTABLISHED')
+ self.assertIsNone(receipt.snapshot()['unrelated_mobile_wallet_retained'])
+
+ def test_fixed_metric_protocol_discards_unexpected_private_values(self):
+ receipt = product.Receipt()
+ server = product.make_server(receipt, port=0)
+ thread = threading.Thread(target=server.serve_forever, daemon=True)
+ thread.start()
+ try:
+ url = 'http://127.0.0.1:%d/metric' % server.server_port
+ for payload in [{'stage': 'PRIVATE_SENTINEL'}, {'stage': []},
+ {'stage': product.STAGES[0], 'identifier': 'PRIVATE_SENTINEL'},
+ {'value': 'PRIVATE_SENTINEL' * 100}]:
+ request = urllib.request.Request(url, data=json.dumps(payload).encode(), method='POST')
+ with self.assertRaises(urllib.error.HTTPError) as failure:
+ urllib.request.urlopen(request)
+ self.assertEqual(failure.exception.code, 422)
+ request = urllib.request.Request(url, data=json.dumps({'stage': product.STAGES[0]}).encode(),
+ method='POST')
+ with urllib.request.urlopen(request) as response:
+ self.assertEqual(response.status, 200)
+ self.assertNotIn('PRIVATE_SENTINEL', json.dumps(receipt.snapshot()))
+ finally:
+ server.shutdown()
+ server.server_close()
+
+ def test_reviewed_ui_has_real_vault_and_restore_operations_without_private_exports(self):
+ flow = (NATIVE / 'product_vault_acceptance.yaml').read_text()
+ helper = (NATIVE / 'product_vault_public_seed.yaml').read_text()
+ self.assertEqual(re.findall(r'STAGE: ([a-z_]+)', flow), list(product.STAGES))
+ for action in ['id: btn_MY_KEEPER', 'id: btn_Seed Key', 'id: btn_decreaseValue',
+ 'tapOn: Replace Key', 'tapOn: Archived wallet versions', 'tapOn: Reinstate',
+ 'WALLET_COUNT: \'3\'', 'assertNotVisible: R5 Reference Vault']:
+ self.assertIn(action, flow)
+ for action in ['takeScreenshot:', 'copyTextFrom:', 'setClipboard:', 'clearKeychain:',
+ 'clearState:', 'openLink:', 'tapOn: Send', 'tapOn: Receive',
+ 'tapOn: Create\n', 'tapOn: Tip Now']:
+ self.assertNotIn(action, flow + helper)
+ self.assertEqual(re.findall(r'inputText: (.+)', flow), ['R5 Reference Vault'])
+ self.assertIn('inputText: ${output.publicWords[output.wordIndex]}', helper)
+ self.assertIn('tapOn: Import', helper)
+ self.assertIn('tapOn: Skip', helper)
+ # Imports are known public BIP39 vectors; no user input or generated
+ # material is copied out. The app supplies all derivations/origins.
+ self.assertEqual(re.findall(r'PUBLIC_WORDS: (.+)', flow), [
+ 'abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about',
+ 'legal winner thank year wave sausage worth useful legal winner thank yellow'])
+
+
+class RunnerTests(unittest.TestCase):
+ def exercise(self, *, missing_stage=False, driver_failure=False, bad_junit=False,
+ artifact_drift=False, installed_drift=False, predecessor_install_drift=False,
+ extra_account=False, dirty_source=False, predecessor_failure=False,
+ device='emulator-5554', platform='ANDROID', save_failure=False,
+ server_close_failure=False):
+ directory = tempfile.TemporaryDirectory()
+ self.addCleanup(directory.cleanup)
+ root = Path(directory.name)
+ private = root / 'private'
+ private.mkdir()
+ sha = '1' * 40
+ artifact = {'sha256': 'f' * 64}
+ proof = {'method': 'SINGLE_INSTALLED_BASE_APK_SHA256', 'sha256': 'f' * 64}
+ predecessor = {
+ 'status': 'FAIL' if predecessor_failure else 'PASS',
+ 'scenario': 'UNUSED_MOBILE_KEY_UI_DELETE_AND_NATIVE_PIN',
+ 'visible_eligible_keys_after_deletion': 0,
+ 'unrelated_visible_wallet_count_after_relaunch': 1,
+ 'new_account_requests_during_key_flow': 0,
+ 'installed_artifact_verified': True,
+ 'installed_artifact': dict(proof, sha256='e' * 64) if predecessor_install_drift else proof,
+ }
+ state = {'build': 'PASS', 'source_sha': sha, 'built_artifact': artifact,
+ 'maestro': {'binary': 'synthetic-maestro'}, 'product_key_ui': predecessor}
+ runtime = {}
+ backend_calls = 0
+ installed_calls = 0
+
+ def backend_snapshot(passed=False):
+ nonlocal backend_calls
+ backend_calls += 1
+ return {'status': 'PASS', 'sample': 6, 'visible_wallet_count_after_relaunch': 1,
+ 'scenario': 'CONTROLLED_DISCONNECT_BEFORE_COMMIT_NOT_WAN_OFFLINE',
+ 'create_new_app_calls': 3 if extra_account and backend_calls > 1 else 2}
+
+ def command(_args, _label, **kwargs):
+ self.assertFalse(kwargs['error_details'])
+ runtime['ui_started'] = True
+ output = private / 'vault-ui'
+ (output / 'PRIVATE_SCREENSHOT_SENTINEL.png').write_text('PRIVATE_SENTINEL')
+ if driver_failure:
+ raise RuntimeError('PRIVATE_SENTINEL')
+ for stage in product.STAGES[:-1] if missing_stage else product.STAGES:
+ self.assertTrue(runtime['receipt'].mark(stage))
+
+ def close_server():
+ if server_close_failure:
+ raise RuntimeError('PRIVATE_SENTINEL')
+
+ def server(receipt):
+ runtime['receipt'] = receipt
+ return types.SimpleNamespace(serve_forever=lambda: None, shutdown=lambda: None,
+ server_close=close_server)
+
+ def installed(_h, _device):
+ nonlocal installed_calls
+ installed_calls += 1
+ return dict(proof, sha256='e' * 64) if installed_drift and installed_calls > 1 else proof
+
+ def save(value):
+ # Fail the final evidence save; raw output must already be disposed.
+ if save_failure and runtime.get('ui_started'):
+ raise RuntimeError('PRIVATE_SENTINEL')
+ state.clear()
+ state.update(copy.deepcopy(value))
+
+ def junit(_report):
+ if bad_junit:
+ raise RuntimeError('PRIVATE_SENTINEL')
+
+ identity = mock.Mock(side_effect=[artifact, {'sha256': 'changed'}] if artifact_drift else None,
+ return_value=artifact)
+ h = types.SimpleNamespace(ROOT=root, PLATFORM=platform, APP_IDS={platform: 'disposable.app'},
+ read=lambda: copy.deepcopy(state), save=save, artifact_identity=identity,
+ command=command, successful_junit=junit)
+ backend = types.SimpleNamespace(snapshot=backend_snapshot)
+ with contextlib.ExitStack() as stack:
+ stack.enter_context(mock.patch.dict(product.os.environ, {'GITHUB_ACTIONS': 'true',
+ 'RUNNER_ENVIRONMENT': 'github-hosted', 'KEEPER_SOURCE_SHA': sha}))
+ stack.enter_context(mock.patch.object(product.subprocess, 'check_output', return_value=sha))
+ stack.enter_context(mock.patch.object(product.subprocess, 'run', return_value=types.SimpleNamespace(
+ returncode=1 if dirty_source else 0)))
+ stack.enter_context(mock.patch.object(product, 'make_server', side_effect=server))
+ try:
+ value = product.run_companion(h, state, device, private, backend, installed)
+ return value, state, private, installed_calls
+ except Exception as error:
+ return error, state, private, installed_calls
+
+ def test_complete_receipt_requires_junit_exact_install_and_no_extra_account(self):
+ value, state, private, installed_calls = self.exercise()
+ self.assertEqual(value['status'], 'PASS')
+ self.assertEqual(installed_calls, 2)
+ self.assertEqual(value['new_account_requests_during_vault_flow'], 0)
+ self.assertTrue(value['installed_artifact_verified'])
+ self.assertEqual(state['product_key_ui']['status'], 'PASS')
+ self.assertFalse((private / 'vault-ui').exists())
+ self.assertNotIn('PRIVATE_SENTINEL', json.dumps(state))
+
+ def test_incomplete_ui_junit_drift_and_extra_account_never_pass(self):
+ for option in ['missing_stage', 'driver_failure', 'bad_junit', 'artifact_drift',
+ 'installed_drift', 'predecessor_install_drift', 'extra_account']:
+ with self.subTest(option=option):
+ value, state, private, _ = self.exercise(**{option: True})
+ self.assertIsInstance(value, RuntimeError)
+ self.assertEqual(state['product_vault_ui']['status'], 'FAIL')
+ self.assertFalse((private / 'vault-ui').exists())
+ self.assertNotIn('PRIVATE_SENTINEL', json.dumps(state))
+
+ def test_unowned_device_dirty_source_or_incomplete_predecessor_never_runs(self):
+ for options in [{'device': 'physical-device-id'}, {'dirty_source': True},
+ {'predecessor_failure': True}, {'platform': 'UNRECOGNIZED'}]:
+ with self.subTest(options=options):
+ value, state, private, installed_calls = self.exercise(**options)
+ self.assertIsInstance(value, RuntimeError)
+ self.assertEqual(installed_calls, 0)
+ self.assertNotIn('product_vault_ui', state)
+ self.assertFalse((private / 'vault-ui').exists())
+
+ def test_private_output_is_purged_even_when_evidence_or_server_cleanup_fails(self):
+ for option in ['save_failure', 'server_close_failure']:
+ with self.subTest(option=option):
+ value, state, private, _ = self.exercise(**{option: True})
+ self.assertIsInstance(value, RuntimeError)
+ self.assertFalse((private / 'vault-ui').exists())
+ self.assertNotIn('PRIVATE_SENTINEL', json.dumps(state))
+ self.assertNotEqual(state['product_vault_ui']['status'], 'PASS')
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/.github/tests/test_release_native.py b/.github/tests/test_release_native.py
new file mode 100644
index 0000000000..efe847e5ca
--- /dev/null
+++ b/.github/tests/test_release_native.py
@@ -0,0 +1,151 @@
+"""Host-only Phase A harness contracts; no native runtime or platform credit."""
+import contextlib
+import importlib.util
+from pathlib import Path
+import tempfile
+import unittest
+from unittest import mock
+
+
+SPEC = importlib.util.spec_from_file_location(
+ 'release_native', Path(__file__).resolve().parents[1] / 'native' / 'hosted_native.py')
+native = importlib.util.module_from_spec(SPEC)
+SPEC.loader.exec_module(native)
+
+
+class ReleaseJunitTest(unittest.TestCase):
+ def setUp(self):
+ directory = tempfile.TemporaryDirectory()
+ self.addCleanup(directory.cleanup)
+ self.report = Path(directory.name) / 'probe.xml'
+
+ def test_actual_success_cases_are_required(self):
+ self.report.write_text(''
+ '')
+ self.assertEqual(native.successful_junit(self.report), 1)
+
+ def test_missing_empty_oversized_or_malformed_report_never_passes(self):
+ with self.assertRaises(RuntimeError):
+ native.successful_junit(self.report)
+ for content in ['', '', 'x' * (1024 * 1024 + 1), '<{tag}/>')
+ with self.assertRaises(RuntimeError):
+ native.successful_junit(self.report)
+ for status in ['ERROR', 'FAILED', 'SKIPPED', 'PENDING', '']:
+ with self.subTest(status=status):
+ self.report.write_text(f'')
+ with self.assertRaises(RuntimeError):
+ native.successful_junit(self.report)
+
+ def test_declared_suite_failures_without_child_details_never_pass(self):
+ for field in ['failures', 'errors', 'skipped']:
+ with self.subTest(field=field):
+ self.report.write_text(f'')
+ with self.assertRaises(RuntimeError):
+ native.successful_junit(self.report)
+
+
+class ReleaseNativeExecutionTest(unittest.TestCase):
+ def setUp(self):
+ directory = tempfile.TemporaryDirectory()
+ self.addCleanup(directory.cleanup)
+ self.root = Path(directory.name)
+ self.private = self.root / 'private'
+ self.private.mkdir()
+ patch = mock.patch.multiple(native, ROOT=self.root, PRIVATE=self.private,
+ EVIDENCE=self.root / 'metadata.json', PLATFORM='ANDROID')
+ patch.start()
+ self.addCleanup(patch.stop)
+ self.identity = {'sha256': 'synthetic-artifact-identity'}
+ native.save({'commands': [], 'build': 'PASS', 'smoke': 'PASS', 'native_probe': 'NOT RUN',
+ 'built_artifact': self.identity, 'maestro': {'binary': 'synthetic-maestro'},
+ 'toolchain': {}})
+
+ def exercise(self, after_identity=None, maestro_failure=False, report_failure=False, report_missing=False):
+ def command(args, label, **kwargs):
+ if '--format' in args:
+ if maestro_failure:
+ raise RuntimeError('PRIVATE_SENTINEL native failure')
+ if not report_missing:
+ (self.private / 'probe-junit.xml').write_text(
+ ''
+ + ('' if report_failure else '') + '')
+ return 'emulator-5554'
+
+ process = mock.Mock(pid=12345)
+ process.poll.return_value = None
+ response = mock.MagicMock()
+ response.__enter__.return_value.read.return_value = b'packager-status:running'
+ stack = contextlib.ExitStack()
+ self.addCleanup(stack.close)
+ stack.enter_context(mock.patch.object(native.subprocess, 'check_call'))
+ stack.enter_context(mock.patch.object(native.subprocess, 'Popen', return_value=process))
+ stack.enter_context(mock.patch.object(native.subprocess, 'run'))
+ stack.enter_context(mock.patch.object(native.os, 'killpg'))
+ stack.enter_context(mock.patch.object(native.urllib.request, 'urlopen', return_value=response))
+ stack.enter_context(mock.patch.object(native, 'command', side_effect=command))
+ stack.enter_context(mock.patch.object(native, 'warm_metro_bundle'))
+ stack.enter_context(mock.patch.object(native, 'android_sdk_metadata', return_value={}))
+ stack.enter_context(mock.patch.object(native, 'verify_installed_artifact'))
+ stack.enter_context(mock.patch.object(native, 'artifact_identity',
+ side_effect=[self.identity, after_identity or self.identity]))
+ native.run_phase('probe')
+
+ def test_probe_requires_actual_app_smoke_first(self):
+ data = native.read()
+ data['smoke'] = 'NOT RUN'
+ native.save(data)
+ with mock.patch.object(native.subprocess, 'check_call'), \
+ mock.patch.object(native.subprocess, 'Popen') as popen:
+ with self.assertRaisesRegex(RuntimeError, 'app startup smoke'):
+ native.run_phase('probe')
+ popen.assert_not_called()
+ self.assertEqual(native.read()['native_probe'], 'FAIL')
+
+ def test_changed_artifact_before_probe_stops_before_runtime(self):
+ with mock.patch.object(native.subprocess, 'check_call'), \
+ mock.patch.object(native, 'artifact_identity', return_value={'sha256': 'changed'}), \
+ mock.patch.object(native.subprocess, 'Popen') as popen:
+ with self.assertRaisesRegex(RuntimeError, 'artifact changed'):
+ native.run_phase('probe')
+ popen.assert_not_called()
+ self.assertEqual(native.read()['native_probe'], 'FAIL')
+
+ def test_probe_success_is_distinct_from_application_acceptance(self):
+ self.exercise()
+ data = native.read()
+ self.assertEqual(data['native_probe'], 'PASS')
+ self.assertEqual(data['native_probe_test_cases'], 1)
+ self.assertIn('NOT app key deletion', data['probe_scope'])
+ self.assertNotIn('release_ready', data)
+
+ def test_artifact_change_during_execution_cannot_pass(self):
+ with self.assertRaisesRegex(RuntimeError, 'artifact changed during'):
+ self.exercise(after_identity={'sha256': 'changed'})
+ self.assertEqual(native.read()['native_probe'], 'FAIL')
+
+ def test_missing_new_report_cannot_reuse_stale_success(self):
+ (self.private / 'probe-junit.xml').write_text('')
+ with self.assertRaisesRegex(RuntimeError, 'Missing or oversized'):
+ self.exercise(report_missing=True)
+ self.assertEqual(native.read()['native_probe'], 'FAIL')
+
+ def test_failed_native_command_or_report_never_exports_raw_data_or_passes(self):
+ for command_failure in [True, False]:
+ with self.subTest(command_failure=command_failure):
+ with self.assertRaises(RuntimeError):
+ self.exercise(maestro_failure=command_failure, report_failure=not command_failure)
+ self.assertEqual(native.read()['native_probe'], 'FAIL')
+ self.assertNotIn('PRIVATE_SENTINEL', native.EVIDENCE.read_text())
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/.github/tests/test_simulator_readiness.py b/.github/tests/test_simulator_readiness.py
new file mode 100644
index 0000000000..222f59ab8f
--- /dev/null
+++ b/.github/tests/test_simulator_readiness.py
@@ -0,0 +1,177 @@
+"""Offline readiness controls, not simulator or application acceptance."""
+
+import importlib.util
+import json
+from pathlib import Path
+import subprocess
+import tempfile
+from types import SimpleNamespace
+import unittest
+from unittest import mock
+
+
+SPEC = importlib.util.spec_from_file_location(
+ 'simulator_readiness_controls', Path(__file__).resolve().parents[1] / 'native/simulator_readiness.py')
+readiness = importlib.util.module_from_spec(SPEC)
+SPEC.loader.exec_module(readiness)
+
+
+class SimulatorReadinessTest(unittest.TestCase):
+ def setUp(self):
+ temporary = tempfile.TemporaryDirectory()
+ self.addCleanup(temporary.cleanup)
+ self.root = Path(temporary.name)
+ self.evidence = self.root / 'metadata.json'
+ self.evidence.write_text(json.dumps({'commands': [{'label': 'Wait for simulator boot'}],
+ 'build': 'PASS', 'smoke': 'NOT RUN', 'driver_preflight': {'result': 'FAIL'}}))
+ self.context = SimpleNamespace(PRIVATE=self.root,
+ read=lambda: json.loads(self.evidence.read_text()),
+ save=lambda data: self.evidence.write_text(json.dumps(data)))
+ self.device = '12345678-1234-1234-1234-123456789ABC'
+ self.now = 100.0
+
+ def clock(self):
+ return self.now
+
+ def sleep(self, seconds):
+ self.now += seconds
+
+ def test_success_requires_actual_query_exit_zero_and_grants_no_native_credit(self):
+ def run(args, **options):
+ self.assertEqual(args, ['xcrun', 'simctl', 'listapps', self.device])
+ self.assertEqual(options, {'stdout': subprocess.DEVNULL, 'stderr': subprocess.DEVNULL,
+ 'timeout': 5, 'check': False})
+ self.now += 0.2
+ return SimpleNamespace(returncode=0)
+
+ with mock.patch.object(readiness.time, 'monotonic', side_effect=self.clock), \
+ mock.patch.object(readiness.subprocess, 'run', side_effect=run) as command, \
+ mock.patch.object(readiness.time, 'sleep') as sleep:
+ record = readiness.wait_for_app_services(self.context, self.device)
+ command.assert_called_once()
+ sleep.assert_not_called()
+ self.assertEqual(record['result'], 'PASS')
+ self.assertEqual(record['criterion'], 'SIMCTL_LISTAPPS_EXIT_ZERO')
+ self.assertEqual(record['attempts'], [{'state': 'SUCCESS', 'exit_code': 0, 'duration_seconds': 0.2}])
+ self.assertEqual(record['after_command_index'], 1)
+ data = self.context.read()
+ self.assertEqual(data['simulator_app_service_readiness'], [record])
+ self.assertEqual(data['driver_preflight'], {'result': 'FAIL'})
+ self.assertEqual((data['build'], data['smoke']), ('PASS', 'NOT RUN'))
+ self.assertNotIn('install_succeeded', data)
+
+ def test_read_only_timeouts_and_failures_can_precede_one_successful_response(self):
+ calls = []
+
+ def run(args, **options):
+ calls.append(args)
+ if len(calls) == 1:
+ self.now += options['timeout']
+ raise subprocess.TimeoutExpired(args, options['timeout'], output='PRIVATE_SENTINEL')
+ self.now += 0.1
+ return SimpleNamespace(returncode=1 if len(calls) == 2 else 0)
+
+ with mock.patch.object(readiness.time, 'monotonic', side_effect=self.clock), \
+ mock.patch.object(readiness.time, 'sleep', side_effect=self.sleep), \
+ mock.patch.object(readiness.subprocess, 'run', side_effect=run):
+ record = readiness.wait_for_app_services(self.context, self.device)
+ self.assertEqual([item['state'] for item in record['attempts']], ['TIMEOUT', 'FAIL', 'SUCCESS'])
+ self.assertTrue(all(args == ['xcrun', 'simctl', 'listapps', self.device] for args in calls))
+ self.assertNotIn('PRIVATE_SENTINEL', self.evidence.read_text())
+ self.assertEqual(record['duration_seconds'], 7.2)
+
+ def test_overall_deadline_clamps_each_query_and_fails_closed_without_install_or_driver(self):
+ limits = []
+
+ def run(args, **options):
+ limits.append(options['timeout'])
+ self.now += options['timeout']
+ raise subprocess.TimeoutExpired(args, options['timeout'], stderr='PRIVATE_SENTINEL')
+
+ with mock.patch.object(readiness.time, 'monotonic', side_effect=self.clock), \
+ mock.patch.object(readiness.time, 'sleep', side_effect=self.sleep), \
+ mock.patch.object(readiness.subprocess, 'run', side_effect=run) as command, \
+ self.assertRaises(RuntimeError) as failure:
+ readiness.wait_for_app_services(self.context, self.device, timeout=12)
+ self.assertEqual(limits, [5, 5])
+ self.assertEqual(command.call_count, 2)
+ self.assertEqual(self.now, 112.0)
+ record = self.context.read()['simulator_app_service_readiness'][0]
+ self.assertEqual(record['result'], 'FAIL')
+ self.assertEqual(record['duration_seconds'], 12)
+ self.assertNotIn('PRIVATE_SENTINEL', str(failure.exception) + self.evidence.read_text())
+
+ def test_short_remaining_window_is_used_instead_of_a_fresh_five_seconds(self):
+ def run(args, **options):
+ self.now += options['timeout']
+ raise subprocess.TimeoutExpired(args, options['timeout'])
+
+ with mock.patch.object(readiness.time, 'monotonic', side_effect=self.clock), \
+ mock.patch.object(readiness.time, 'sleep', side_effect=self.sleep), \
+ mock.patch.object(readiness.subprocess, 'run', side_effect=run) as command, \
+ self.assertRaises(RuntimeError):
+ readiness.wait_for_app_services(self.context, self.device, timeout=8)
+ self.assertEqual([call.kwargs['timeout'] for call in command.call_args_list], [5, 2])
+ self.assertEqual(self.now, 108.0)
+
+ def test_success_observed_only_after_deadline_does_not_supply_a_timely_pass(self):
+ def run(args, **options):
+ self.now += 121
+ return SimpleNamespace(returncode=0)
+
+ with mock.patch.object(readiness.time, 'monotonic', side_effect=self.clock), \
+ mock.patch.object(readiness.subprocess, 'run', side_effect=run), \
+ self.assertRaises(RuntimeError):
+ readiness.wait_for_app_services(self.context, self.device)
+ record = self.context.read()['simulator_app_service_readiness'][0]
+ self.assertEqual(record['result'], 'FAIL')
+ self.assertTrue(record['attempts'][0]['observed_after_deadline'])
+
+ def test_unknown_query_errors_and_malformed_exit_status_never_supply_a_pass(self):
+ private_error = type('PRIVATE_SENTINEL', (Exception,), {})('arbitrary private message')
+ for outcome in [FileNotFoundError('PRIVATE_SENTINEL path'), private_error,
+ SimpleNamespace(returncode=None), SimpleNamespace(returncode=False)]:
+ with self.subTest(outcome=type(outcome).__name__), \
+ mock.patch.object(readiness.subprocess, 'run', side_effect=outcome if isinstance(outcome, Exception) else None,
+ return_value=outcome) as run, \
+ mock.patch.object(readiness.time, 'sleep') as sleep, \
+ self.assertRaises(RuntimeError):
+ readiness.wait_for_app_services(self.context, self.device)
+ run.assert_called_once()
+ sleep.assert_not_called()
+ records = self.context.read()['simulator_app_service_readiness']
+ self.assertTrue(all(record['result'] == 'FAIL' for record in records))
+ self.assertTrue(all(record['attempts'][0]['state'] == 'ERROR' for record in records))
+ self.assertNotIn('PRIVATE_SENTINEL', self.evidence.read_text())
+
+ def test_missing_persistence_cannot_allow_even_a_successful_response_to_continue(self):
+ self.context.save = mock.Mock(side_effect=ValueError('PRIVATE_SENTINEL path'))
+ with mock.patch.object(readiness.subprocess, 'run', return_value=SimpleNamespace(returncode=0)) as run, \
+ self.assertRaises(RuntimeError) as failure:
+ readiness.wait_for_app_services(self.context, self.device)
+ run.assert_called_once()
+ self.assertEqual(str(failure.exception), 'Simulator app-service readiness evidence could not be saved.')
+ self.assertTrue(failure.exception.__suppress_context__)
+ self.assertNotIn('PRIVATE_SENTINEL', str(failure.exception) + self.evidence.read_text())
+
+ def test_unreadable_source_metadata_fails_before_query_with_fixed_error(self):
+ self.context.read = mock.Mock(side_effect=ValueError('PRIVATE_SENTINEL private path'))
+ with mock.patch.object(readiness.subprocess, 'run') as run, self.assertRaises(RuntimeError) as failure:
+ readiness.wait_for_app_services(self.context, self.device)
+ run.assert_not_called()
+ self.assertEqual(str(failure.exception), 'Simulator app-service readiness evidence could not be read.')
+ self.assertTrue(failure.exception.__suppress_context__)
+ self.assertNotIn('PRIVATE_SENTINEL', str(failure.exception))
+
+ def test_invalid_device_or_window_cannot_start_a_query(self):
+ cases = [('PRIVATE_SENTINEL', 120), (None, 120), (self.device, 0), (self.device, -1),
+ (self.device, 121), (self.device, float('inf')), (self.device, float('nan')), (self.device, True)]
+ with mock.patch.object(readiness.subprocess, 'run') as run:
+ for device, timeout in cases:
+ with self.subTest(device=device, timeout=timeout), self.assertRaises(ValueError):
+ readiness.wait_for_app_services(self.context, device, timeout)
+ run.assert_not_called()
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/.github/tests/test_startup_diagnosis.py b/.github/tests/test_startup_diagnosis.py
new file mode 100644
index 0000000000..dc2958b8bb
--- /dev/null
+++ b/.github/tests/test_startup_diagnosis.py
@@ -0,0 +1,110 @@
+import importlib.util
+import json
+from pathlib import Path
+import tempfile
+from types import SimpleNamespace
+import unittest
+from unittest import mock
+
+spec = importlib.util.spec_from_file_location('startup_diagnosis_fixture', Path(__file__).resolve().parents[1] / 'native/startup_diagnosis.py')
+diagnosis = importlib.util.module_from_spec(spec)
+spec.loader.exec_module(diagnosis)
+
+
+class StartupDiagnosisTests(unittest.TestCase):
+ def setUp(self):
+ self.temporary = tempfile.TemporaryDirectory()
+ self.addCleanup(self.temporary.cleanup)
+ self.root = Path(self.temporary.name)
+ self.native = SimpleNamespace(PRIVATE=self.root, PLATFORM='ANDROID')
+
+ def test_rejects_physical_device_and_closes_failed_capture(self):
+ with self.assertRaises(ValueError):
+ diagnosis.start(self.native, 'physical-PRIVATE_SENTINEL')
+ with mock.patch.object(diagnosis.subprocess, 'Popen', side_effect=OSError('PRIVATE_SENTINEL')):
+ with self.assertRaises(OSError):
+ diagnosis.start(self.native, 'emulator-5554')
+ diagnosis.stop(None)
+
+ def test_owned_capture_stops_only_its_process(self):
+ process = mock.Mock()
+ process.poll.return_value = None
+ with mock.patch.object(diagnosis.subprocess, 'Popen', return_value=process) as popen:
+ handle = diagnosis.start(self.native, 'emulator-5554')
+ self.assertIn('ReactHost:V', popen.call_args.args[0])
+ self.assertIn('-T', popen.call_args.args[0])
+ diagnosis.stop(handle)
+ process.terminate.assert_called_once_with()
+ process.wait.assert_called_once_with(timeout=3)
+ self.assertTrue(handle.output.closed)
+
+ def test_regenerates_only_allowlisted_metadata(self):
+ (self.root / 'startup-logcat.log').write_text('E/ReactHost(123): TypeError PRIVATE_SENTINEL\nANR in ' + diagnosis.APP)
+ observations = [
+ {'time_ms': 100, 'kind': 'ERROR', 'event': 'bundling_error', 'error_type': 'PRIVATE_SENTINEL', 'categories': ['TYPE', 'PRIVATE_SENTINEL'] * 100, 'raw': 'PRIVATE_SENTINEL'},
+ {'time_ms': 200, 'kind': 'REQUEST', 'request': 'ENTRY_BUNDLE', 'options': {'lazy': True, 'app': 'PRIVATE_SENTINEL', 'platform': 'android', 'unknown': 'PRIVATE_SENTINEL'}},
+ {'time_ms': 200, 'kind': 'RESPONSE', 'request': 'ENTRY_BUNDLE', 'outer_http_status': 500, 'url': 'PRIVATE_SENTINEL'},
+ {'time_ms': 200, 'kind': 'PRIVATE_SENTINEL'},
+ ]
+ (self.root / 'startup-observer.jsonl').write_text('\n'.join(json.dumps(row) for row in observations))
+ directory = self.root / 'maestro-output' / 'screen-hierarchy'
+ directory.mkdir(parents=True)
+ values = ['Unable to check your passcode. Please try again.', 'Retry', 'Dismiss', 'Minimize', 'PRIVATE_SENTINEL']
+ (directory / 'step-1.json').write_text(json.dumps({'children': [{'attributes': {'text': value}} for value in values]}))
+ def subprocess_result(args, **kwargs):
+ if 'pidof' in args:
+ return SimpleNamespace(returncode=0, stdout=b'123\n')
+ kwargs['stdout'].write(('mResumedActivity: ActivityRecord{abc u0 ' + diagnosis.APP + '/.MainActivity t42} PRIVATE_SENTINEL').encode())
+ return SimpleNamespace(returncode=0)
+ with mock.patch.object(diagnosis.subprocess, 'run', side_effect=subprocess_result):
+ facts = diagnosis.collect(self.native, 'emulator-5554', SimpleNamespace(started_ms=150))
+ self.assertNotIn('PRIVATE_SENTINEL', json.dumps(facts))
+ self.assertEqual(facts['metro']['rows'][0]['categories'], ['TYPE'])
+ self.assertEqual(facts['metro']['rows'][0]['stage'], 'BEFORE_APP')
+ self.assertEqual(facts['metro']['rows'][1]['stage'], 'APP_WINDOW')
+ self.assertEqual(facts['metro']['invalid_rows'], 1)
+ self.assertTrue(facts['hierarchy']['credential_error'])
+ self.assertTrue(facts['hierarchy']['logbox_controls'])
+ self.assertTrue(facts['foreground']['own_app_resumed'])
+ self.assertTrue(facts['process']['alive'])
+
+ def test_failed_malformed_foreign_and_truncated_queries_do_not_claim_absence(self):
+ for code, pid, foreground, oversized in [
+ (1, b'', 'permission denied PRIVATE_SENTINEL', False),
+ (0, b'PRIVATE_SENTINEL', 'malformed PRIVATE_SENTINEL', False),
+ (0, b'', 'mResumedActivity: ActivityRecord{x u0 ' + diagnosis.APP + '.foreign/.MainActivity t1}', False),
+ (0, b'', 'mResumedActivity: ActivityRecord{x u0 foreign/.MainActivity t1} ' + diagnosis.APP + '/.MainActivity', False),
+ (0, b'123\n', 'mResumedActivity: ActivityRecord{x u0 ' + diagnosis.APP + '/.MainActivity t1}', True),
+ ]:
+ with self.subTest(code=code, oversized=oversized):
+ def run(args, **kwargs):
+ if 'pidof' in args:
+ return SimpleNamespace(returncode=code, stdout=pid)
+ kwargs['stdout'].write((foreground + ('x' * (1024 * 1024 + 1) if oversized else '')).encode())
+ return SimpleNamespace(returncode=code)
+ with mock.patch.object(diagnosis.subprocess, 'run', side_effect=run):
+ facts = diagnosis.collect(self.native, 'emulator-5554')
+ self.assertIsNone(facts['foreground']['own_app_resumed'])
+ if not oversized:
+ self.assertIsNone(facts['process']['alive'])
+ self.assertNotIn('PRIVATE_SENTINEL', json.dumps(facts))
+
+ def test_private_size_bounds_and_symlink_rejection(self):
+ path = self.root / 'large.log'
+ path.write_bytes(b'a' * (1024 * 1024 + 1))
+ payload, truncated = diagnosis._read(self.native, path)
+ self.assertTrue(truncated)
+ self.assertLessEqual(len(payload), 1024 * 1024 + 1)
+ link = self.root / 'link.log'
+ link.symlink_to(path)
+ with self.assertRaises(ValueError):
+ diagnosis._read(self.native, link)
+ small = self.root / 'small.json'
+ small.write_text(json.dumps({'padding': 'x' * (600 * 1024)}))
+ payload, truncated = diagnosis._read(self.native, small)
+ self.assertFalse(truncated)
+ self.assertEqual(len(json.loads(payload)['padding']), 600 * 1024)
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/.github/tests/test_startup_integration.py b/.github/tests/test_startup_integration.py
new file mode 100644
index 0000000000..a9fd30e965
--- /dev/null
+++ b/.github/tests/test_startup_integration.py
@@ -0,0 +1,465 @@
+"""Offline startup-observer lifecycle controls; no emulator or native credit."""
+
+from contextlib import ExitStack
+import importlib.util
+from pathlib import Path
+import tempfile
+from types import SimpleNamespace
+import unittest
+from unittest import mock
+
+
+SPEC = importlib.util.spec_from_file_location(
+ 'startup_integration_native', Path(__file__).resolve().parents[1] / 'native/hosted_native.py')
+native = importlib.util.module_from_spec(SPEC)
+SPEC.loader.exec_module(native)
+
+
+class StartupIntegrationTest(unittest.TestCase):
+ def setUp(self):
+ temporary = tempfile.TemporaryDirectory()
+ self.addCleanup(temporary.cleanup)
+ self.root = Path(temporary.name)
+ self.events = []
+ self.device = 'emulator-5554'
+ self.artifact = {'sha256': 'a' * 64}
+ self.metro = mock.Mock(pid=7000)
+ self.metro.poll.return_value = None
+ self.capture = object()
+ self.observer = SimpleNamespace(
+ start=mock.Mock(side_effect=self.start),
+ collect=mock.Mock(side_effect=self.collect),
+ stop=mock.Mock(side_effect=self.stop),
+ observe=mock.Mock(),
+ )
+ self.original_error = RuntimeError('PRIVATE_SENTINEL original smoke failure')
+ self.import_error = RuntimeError('PRIVATE_SENTINEL observer import failure')
+ self.spawn_error = OSError('PRIVATE_SENTINEL Metro spawn failure')
+
+ def start(self, context, device):
+ self.assertEqual(context.PLATFORM, 'ANDROID')
+ self.assertEqual(context.PRIVATE, self.root)
+ self.assertEqual(device, self.device)
+ self.events.append('capture-start')
+ return self.capture
+
+ def collect(self, context, device, capture):
+ self.assertEqual(device, self.device)
+ self.assertIn(capture, [self.capture, None])
+ self.events.append('capture-collect')
+ return {'scope': 'startup only', 'collection_errors': []}
+
+ def stop(self, capture):
+ self.assertIn(capture, [self.capture, None])
+ self.events.append('capture-stop')
+
+ def exercise(self, suite='startup', smoke_fails=False, start_fails=False,
+ collect_fails=False, stop_fails=False, platform='ANDROID',
+ import_fails=False, popen_fails=False, receipt_fails=None,
+ cleanup_fails=(), diagnostics_fail=False, install_timeout=False,
+ install_fails=False, readiness_fails=False):
+ captured = {}
+ original_read, original_save, original_unlink = native.read, native.save, Path.unlink
+ original_command = native.command
+
+ def late_read():
+ if receipt_fails == 'read' and 'capture-collect' in self.events:
+ raise OSError('PRIVATE_SENTINEL receipt read failure')
+ return original_read()
+
+ def late_save(value):
+ if receipt_fails == 'save' and 'capture-collect' in self.events:
+ raise OSError('PRIVATE_SENTINEL receipt write failure')
+ return original_save(value)
+
+ def unlink(path, *args, **kwargs):
+ if path.name in ['startup-logcat.log', 'startup-observer.jsonl', 'startup-foreground.log'] and 'capture-collect' in self.events:
+ self.events.append('purge-' + path.name)
+ if 'purge' in cleanup_fails:
+ raise OSError('PRIVATE_SENTINEL purge failure')
+ return original_unlink(path, *args, **kwargs)
+
+ def command(args, label, **kwargs):
+ if label == 'Install unsigned development app':
+ captured['install_command_count'] = captured.get('install_command_count', 0) + 1
+ captured['install_args'], captured['install_options'] = args, kwargs
+ if install_fails:
+ raise self.original_error
+ if install_timeout:
+ return original_command(args, label, **kwargs)
+ if label == 'Identify fresh emulator':
+ return self.device
+ if label == 'Record actual adb version':
+ return 'Android Debug Bridge version 1.0.41'
+ if label == 'Record Android emulator image':
+ return 'fixed-disposable-image'
+ if label == 'Create fresh iPhone 16 iOS 18.5 simulator':
+ return '12345678-1234-1234-1234-123456789ABC'
+ if label.startswith('Assert '):
+ self.events.append('maestro')
+ captured['flow'] = args[-1]
+ if smoke_fails:
+ raise self.original_error
+
+ def popen(args, **kwargs):
+ if args[:3] == ['xcrun', 'simctl', 'install']:
+ process = mock.Mock(pid=7001)
+ process.wait.side_effect = [native.subprocess.TimeoutExpired(args, 120), 0]
+ captured.setdefault('install_processes', []).append(process)
+ return process
+ captured['metro_args'] = args
+ captured['metro_options'] = kwargs
+ if popen_fails:
+ raise self.spawn_error
+ return self.metro
+
+ original_open = Path.open
+
+ def track_output(path, *args, **kwargs):
+ handle = original_open(path, *args, **kwargs)
+ if path == self.root / 'metro.log':
+ if 'metro-output' in cleanup_fails:
+ real_handle = handle
+ class FailingClose:
+ @property
+ def closed(self):
+ return real_handle.closed
+
+ def close(self):
+ real_handle.close()
+ raise OSError('PRIVATE_SENTINEL Metro output close failure')
+ handle = FailingClose()
+ captured['metro_output'] = handle
+ return handle
+
+ def load_observer(module):
+ if import_fails:
+ raise self.import_error
+
+ def observe_install(context, device, args, label, **kwargs):
+ self.events.append('install-observe')
+ self.assertEqual(device, '12345678-1234-1234-1234-123456789ABC')
+ self.assertEqual(context.PRIVATE, self.root)
+ return context.command(args, label, **kwargs)
+
+ self.observer.observe.side_effect = observe_install
+
+ def ready(device):
+ self.events.append('app-services-ready')
+ if readiness_fails:
+ raise self.original_error
+
+ def dispose(args, **kwargs):
+ event = 'device-' + args[2] if args[0] == 'xcrun' else 'device-uninstall'
+ self.events.append(event)
+ if event in cleanup_fails:
+ raise OSError('PRIVATE_SENTINEL disposal failure')
+ return SimpleNamespace(returncode=0)
+
+ def kill_metro(*args):
+ if args[0] == 7001:
+ self.events.append('install-kill')
+ return
+ self.events.append('metro-stop')
+ if 'metro-stop' in cleanup_fails:
+ raise OSError('PRIVATE_SENTINEL Metro cleanup failure')
+
+ def failure_diagnostics(*args):
+ self.events.append('failure-diagnostics')
+ if diagnostics_fail:
+ raise OSError('PRIVATE_SENTINEL diagnostics failure')
+
+ def fail_start(*args):
+ self.events.append('capture-start')
+ raise OSError('PRIVATE_SENTINEL start failure')
+
+ def fail_collect(*args):
+ self.events.append('capture-collect')
+ raise OSError('PRIVATE_SENTINEL collection failure')
+
+ def fail_stop(*args):
+ self.events.append('capture-stop')
+ raise OSError('PRIVATE_SENTINEL stop failure')
+
+ if start_fails:
+ self.observer.start.side_effect = fail_start
+ if collect_fails:
+ self.observer.collect.side_effect = fail_collect
+ if stop_fails:
+ self.observer.stop.side_effect = fail_stop
+ response = mock.MagicMock()
+ response.__enter__.return_value.read.return_value = b'packager-status:running'
+ loader = SimpleNamespace(exec_module=load_observer)
+ with ExitStack() as stack:
+ # A failed assertion must never render the worker's inherited env.
+ stack.enter_context(mock.patch.dict(native.os.environ, {'KEEPER_PUBLIC_TEST_ENV': 'fixture'}, clear=True))
+ stack.enter_context(mock.patch.multiple(native, PRIVATE=self.root, EVIDENCE=self.root / 'metadata.json',
+ ROOT=self.root, PLATFORM=platform))
+ native.save({'commands': [], 'build': 'PASS', 'smoke': 'PASS' if suite != 'startup' else 'NOT RUN',
+ 'built_artifact': self.artifact, 'toolchain': {}, 'maestro': {'binary': 'fixed-maestro'}})
+ patches = [
+ (native, 'command', command),
+ (native, 'artifact_identity', lambda: self.artifact),
+ (native, 'verify_installed_artifact', lambda device: self.events.append('installed-proof')),
+ (native, 'android_sdk_metadata', lambda *args: {'version': 'fixed'}),
+ (native, 'warm_metro_bundle', lambda suite: self.events.append('warm-' + suite)),
+ (native, 'wait_for_simulator_app_services', ready),
+ (native, 'successful_junit', lambda report: 1),
+ (native, 'record_startup_failure', failure_diagnostics),
+ (native, 'collect_r5_feature_evidence', lambda device: {'status': 'PASS'}),
+ (native.subprocess, 'Popen', popen),
+ (native.subprocess, 'run', dispose),
+ (native.urllib.request, 'urlopen', lambda *args, **kwargs: response),
+ (native.os, 'killpg', kill_metro),
+ (native.Path, 'open', track_output),
+ (native.Path, 'unlink', unlink),
+ (native, 'read', late_read),
+ (native, 'save', late_save),
+ (native.importlib.util, 'spec_from_file_location', lambda *args: SimpleNamespace(loader=loader)),
+ (native.importlib.util, 'module_from_spec', lambda *args: self.observer),
+ ]
+ for owner, name, replacement in patches:
+ stack.enter_context(mock.patch.object(owner, name, replacement))
+ try:
+ native.smoke(suite)
+ except Exception as error:
+ captured['error'] = error
+ captured['metadata'] = original_read()
+ return captured
+
+ def test_android_capture_stays_inside_owned_startup_and_all_resources_close(self):
+ value = self.exercise()
+ self.assertNotIn('error', value)
+ self.assertEqual(value['metadata']['smoke'], 'PASS')
+ self.assertEqual(value['metadata']['startup_observation']['scope'], 'startup only')
+ self.assertEqual(value['flow'], '.github/native/startup.yaml')
+ self.assertEqual(value['metro_args'][-4:], [
+ '--config', str(self.root / '.github/native/startup_observer.cjs'),
+ '--custom-log-reporter-path', str(self.root / '.github/native/startup_reporter.cjs'),
+ ])
+ self.assertEqual(value['metro_options']['env']['KEEPER_STARTUP_OBSERVER_PATH'],
+ str(self.root / 'startup-observer.jsonl'))
+ for before, after in [('capture-start', 'maestro'), ('maestro', 'capture-collect'),
+ ('capture-collect', 'capture-stop'), ('capture-stop', 'metro-stop'),
+ ('metro-stop', 'device-uninstall')]:
+ self.assertLess(self.events.index(before), self.events.index(after))
+ self.assertTrue(value['metro_options']['stdout'].closed)
+
+ def test_capture_failure_is_optional_but_collection_and_disposal_still_happen(self):
+ value = self.exercise(collect_fails=True)
+ self.assertNotIn('error', value)
+ self.assertEqual(value['metadata']['smoke'], 'PASS')
+ self.assertEqual(value['metadata']['startup_observation'], {'collection_errors': ['collector']})
+ self.assertNotIn('startup_observation_cleanup', value['metadata'])
+ self.assertIn('capture-stop', self.events)
+ self.assertIn('metro-stop', self.events)
+ self.assertIn('device-uninstall', self.events)
+ self.assertNotIn('PRIVATE_SENTINEL', str(value['metadata']))
+
+ def test_failed_capture_start_keeps_the_real_smoke_outcome_and_closes_other_resources(self):
+ value = self.exercise(start_fails=True)
+ self.assertNotIn('error', value)
+ self.assertEqual(value['metadata']['smoke'], 'PASS')
+ self.assertEqual(value['metadata']['startup_observation_capture'], 'UNAVAILABLE')
+ self.observer.collect.assert_called_once()
+ self.observer.stop.assert_called_once_with(None)
+ self.assertIn('metro-stop', self.events)
+ self.assertIn('device-uninstall', self.events)
+ self.assertTrue(value['metro_options']['stdout'].closed)
+ self.assertNotIn('PRIVATE_SENTINEL', str(value['metadata']))
+
+ def test_original_smoke_failure_survives_observer_and_cleanup_failures(self):
+ value = self.exercise(smoke_fails=True, collect_fails=True, stop_fails=True)
+ self.assertIs(value['error'], self.original_error)
+ self.assertEqual(value['metadata']['startup_observation_cleanup'], 'FAIL')
+ self.assertIn('metro-stop', self.events)
+ self.assertIn('device-uninstall', self.events)
+
+ def test_observer_import_or_metro_spawn_failure_closes_output_before_any_device_work(self):
+ for option in ['import_fails', 'popen_fails']:
+ with self.subTest(option=option):
+ self.events.clear()
+ value = self.exercise(**{option: True})
+ self.assertIsNotNone(value.get('error'))
+ self.assertTrue(value['metro_output'].closed)
+ self.assertEqual(self.events, [])
+ self.assertEqual(value['metadata']['smoke'], 'NOT RUN')
+ self.assertNotIn('startup_observation', value['metadata'])
+ self.assertNotIn('PRIVATE_SENTINEL', str(value['metadata']))
+ self.assertTrue(value['metro_options']['stdout'].closed)
+ self.assertNotIn('PRIVATE_SENTINEL', str(value['metadata']))
+
+ def test_unstopped_capture_cannot_allow_a_successful_phase_to_continue(self):
+ value = self.exercise(stop_fails=True)
+ self.assertIsNotNone(value.get('error'), 'an unconfirmed live capture must block subsequent feature/account probes')
+ self.assertEqual(value['metadata']['startup_observation_cleanup'], 'FAIL')
+ self.assertEqual(value['metadata']['smoke'], 'FAIL')
+ self.assertIn('metro-stop', self.events)
+ self.assertIn('device-uninstall', self.events)
+
+ def test_early_close_failure_preserves_exact_import_or_spawn_error(self):
+ for option, expected in [('import_fails', self.import_error), ('popen_fails', self.spawn_error)]:
+ with self.subTest(option=option):
+ self.events.clear()
+ value = self.exercise(**{option: True}, cleanup_fails=('metro-output',))
+ self.assertIs(value['error'], expected)
+ self.assertTrue(value['metro_output'].closed)
+ self.assertEqual(self.events, [])
+
+ def test_ios_install_timeout_still_fails_once_before_any_app_or_junit_credit(self):
+ value = self.exercise(platform='IOS', install_timeout=True)
+ self.assertIsInstance(value['error'], RuntimeError)
+ self.assertIn('exit 124', str(value['error']))
+ self.assertEqual(len(value['install_processes']), 1)
+ self.assertEqual(value['install_processes'][0].wait.call_args_list,
+ [mock.call(timeout=120), mock.call()])
+ entry = value['metadata']['commands'][0]
+ self.assertEqual((entry['label'], entry['timeout_seconds'], entry['exit_code']),
+ ('Install unsigned development app', 120, 124))
+ self.assertEqual(value['metadata']['smoke'], 'FAIL')
+ for field in ['install_succeeded', 'installed_artifact_verified', 'smoke_test_cases']:
+ self.assertNotIn(field, value['metadata'])
+ for event in ['maestro', 'installed-proof']:
+ self.assertNotIn(event, self.events)
+ self.assertNotIn('flow', value)
+ self.assertEqual(self.events.count('install-kill'), 1)
+ self.assertIn('device-shutdown', self.events)
+ self.assertIn('device-delete', self.events)
+ self.assertTrue(value['metro_output'].closed)
+
+ def test_ios_install_success_keeps_exact_bytes_and_default_passcode_flow(self):
+ value = self.exercise(platform='IOS')
+ self.assertNotIn('error', value)
+ self.assertEqual(value['install_options']['timeout'], 120)
+ self.assertEqual(value['install_args'][:3], ['xcrun', 'simctl', 'install'])
+ self.assertEqual(value['flow'], '.github/native/startup.yaml')
+ self.assertEqual(self.events.count('installed-proof'), 2)
+ self.assertEqual(value['metadata']['smoke'], 'PASS')
+
+ def test_ios_install_observation_delegates_once_after_readiness_before_proof_and_ui(self):
+ value = self.exercise(platform='IOS')
+ self.assertNotIn('error', value)
+ self.observer.observe.assert_called_once()
+ self.assertEqual(value['install_command_count'], 1)
+ self.assertEqual(value['install_args'], [
+ 'xcrun', 'simctl', 'install', '12345678-1234-1234-1234-123456789ABC',
+ str(self.root / 'DerivedData/Build/Products/Debug-iphonesimulator/hexa_keeper_dev.app'),
+ ])
+ self.assertEqual(value['install_options'], {'timeout': 120})
+ self.assertLess(self.events.index('app-services-ready'), self.events.index('install-observe'))
+ self.assertLess(self.events.index('install-observe'), self.events.index('installed-proof'))
+ self.assertLess(self.events.index('installed-proof'), self.events.index('maestro'))
+ self.assertNotIn('capture-start', self.events)
+ self.assertIn('device-shutdown', self.events)
+ self.assertIn('device-delete', self.events)
+
+ def test_ios_install_failure_preserves_original_error_and_cleanup_without_ui_credit(self):
+ value = self.exercise(platform='IOS', install_fails=True)
+ self.assertIs(value['error'], self.original_error)
+ self.assertEqual(value['install_command_count'], 1)
+ self.assertNotIn('installed-proof', self.events)
+ self.assertNotIn('maestro', self.events)
+ self.assertIn('failure-diagnostics', self.events)
+ self.assertIn('metro-stop', self.events)
+ self.assertIn('device-shutdown', self.events)
+ self.assertIn('device-delete', self.events)
+ self.assertTrue(value['metro_output'].closed)
+
+ def test_ios_unresponsive_app_services_block_install_and_ui_but_still_clean_up(self):
+ value = self.exercise(platform='IOS', readiness_fails=True)
+ self.assertIs(value['error'], self.original_error)
+ self.observer.observe.assert_not_called()
+ self.assertNotIn('install_command_count', value)
+ self.assertNotIn('installed-proof', self.events)
+ self.assertNotIn('maestro', self.events)
+ self.assertIn('device-shutdown', self.events)
+ self.assertIn('device-delete', self.events)
+ self.assertTrue(value['metro_output'].closed)
+
+ def test_ios_probe_and_features_keep_direct_single_install_after_readiness(self):
+ for suite in ['probe', 'features']:
+ with self.subTest(suite=suite):
+ self.events.clear()
+ self.observer.observe.reset_mock()
+ value = self.exercise(platform='IOS', suite=suite)
+ self.assertNotIn('error', value)
+ self.observer.observe.assert_not_called()
+ self.assertEqual(value['install_command_count'], 1)
+ self.assertEqual(value['install_options'], {'timeout': 120})
+ self.assertLess(self.events.index('app-services-ready'), self.events.index('installed-proof'))
+
+ def test_receipt_failures_preserve_primary_and_do_not_skip_any_disposal(self):
+ for boundary in ['read', 'save']:
+ for primary in [True, False]:
+ with self.subTest(boundary=boundary, primary=primary):
+ self.events.clear()
+ value = self.exercise(smoke_fails=primary, receipt_fails=boundary,
+ stop_fails=True, cleanup_fails=('metro-stop', 'metro-output', 'device-uninstall', 'purge'),
+ diagnostics_fail=True)
+ if primary:
+ self.assertIs(value['error'], self.original_error)
+ else:
+ self.assertIsInstance(value['error'], RuntimeError)
+ self.assertNotIn('PRIVATE_SENTINEL', str(value['error']))
+ for event in ['capture-stop', 'metro-stop', 'device-uninstall',
+ 'purge-startup-logcat.log', 'purge-startup-observer.jsonl',
+ 'purge-startup-foreground.log']:
+ self.assertEqual(self.events.count(event), 1)
+ self.assertTrue(value['metro_output'].closed)
+
+ def test_raw_purge_failure_blocks_a_successful_phase_after_other_cleanup(self):
+ value = self.exercise(cleanup_fails=('purge',))
+ self.assertIsInstance(value.get('error'), RuntimeError)
+ self.assertEqual(value['metadata']['smoke'], 'FAIL')
+ self.assertEqual(value['metadata']['startup_cleanup_errors'],
+ ['private_startup-logcat', 'private_startup-observer', 'private_startup-foreground'])
+ self.assertIn('capture-stop', self.events)
+ self.assertIn('device-uninstall', self.events)
+ self.assertTrue(value['metro_output'].closed)
+
+ def test_cleanup_failures_fail_closed_and_keep_attempting_ios_delete(self):
+ for primary in [True, False]:
+ with self.subTest(primary=primary):
+ self.events.clear()
+ value = self.exercise(platform='IOS', smoke_fails=primary,
+ cleanup_fails=('metro-stop', 'device-shutdown', 'device-delete'))
+ if primary:
+ self.assertIs(value['error'], self.original_error)
+ else:
+ self.assertIsInstance(value['error'], RuntimeError)
+ self.assertEqual(value['metadata']['smoke'], 'FAIL')
+ self.assertEqual(value['metadata']['startup_cleanup_errors'],
+ ['metro_process', 'device_shutdown', 'device_delete'])
+ self.assertTrue(value['metro_output'].closed)
+ self.assertLess(self.events.index('device-shutdown'), self.events.index('device-delete'))
+
+ def test_only_observer_raw_files_are_purged_after_collection(self):
+ observer_names = ['startup-logcat.log', 'startup-observer.jsonl', 'startup-foreground.log']
+ for name in [*observer_names, 'build-artifact', 'maestro.zip']:
+ (self.root / name).write_text('PRIVATE_SENTINEL')
+ value = self.exercise()
+ self.assertNotIn('error', value)
+ for name in observer_names:
+ self.assertFalse((self.root / name).exists())
+ self.assertGreater(self.events.index('purge-' + name), self.events.index('capture-stop'))
+ for name in ['build-artifact', 'maestro.zip']:
+ self.assertTrue((self.root / name).exists())
+
+ def test_probes_and_ios_preserve_their_existing_metro_configuration_without_observation(self):
+ for suite, platform, config in [('probe', 'ANDROID', 'release_metro.cjs'),
+ ('features', 'ANDROID', 'r5_metro.cjs'),
+ ('startup', 'IOS', None)]:
+ with self.subTest(suite=suite, platform=platform):
+ self.events.clear()
+ value = self.exercise(suite=suite, platform=platform)
+ self.assertNotIn('error', value)
+ self.assertNotIn('capture-start', self.events)
+ self.assertNotIn('startup_observation', value['metadata'])
+ if config:
+ self.assertEqual(value['metro_args'][-2:], ['--config', str(self.root / '.github/native' / config)])
+ else:
+ self.assertNotIn('--config', value['metro_args'])
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/.github/tests/version-history-fixture.test.cjs b/.github/tests/version-history-fixture.test.cjs
new file mode 100644
index 0000000000..d0eb29b881
--- /dev/null
+++ b/.github/tests/version-history-fixture.test.cjs
@@ -0,0 +1,102 @@
+/* Offline fake-native boundary controls; these are NOT native acceptance. */
+const assert = require('node:assert/strict');
+const test = require('node:test');
+const { BACKUP_KEY, STALE, runFixture } = require('../native/version_history_fixture_core');
+const original = [{version:'2.6.4(627)',title:'Initially installed',date:'2026-10-22T01:02:03.000Z',releaseNote:'fixture retained'}];
+function setup() {
+ const account = {isDefault:true,accountIdentifier:'',realmId:'keeper.realm',appId:'owned-fixture',hash:'known-pin-hash'};
+ const state = {appId:account.appId,appVersion:'2.6.4'};
+ const rows = structuredClone(original), backups = new Map();
+ const app = {id:account.appId,version:'2.6.4'};
+ let writes = 0, opens = 0, closes = 0, schemaVersion = 109;
+ const db = {
+ objects(name) { return {VersionHistory:rows,KeeperApp:[app],Wallet:[{id:'fixture-wallet'}],Vault:[]}[name]; },
+ write(fn) { writes++; fn(); }, delete(collection) { assert.equal(collection,rows); rows.length=0; },
+ create(name,row) { assert.equal(name,'VersionHistory'); rows.push(structuredClone(row)); },
+ close() { closes++; },
+ };
+ const args = {
+ phase:'seed_stale', development:true, now:()=>Date.parse('2026-10-22T02:03:04.500Z'),
+ config:{ENVIRONMENT:'DEVELOPMENT',RELAY:'http://127.0.0.1:8765/',ENC_KEY_STORAGE_IDENTIFIER:'KEEPER-HOSTED-DISPOSABLE'},
+ storage:{getString:()=>JSON.stringify({account:JSON.stringify({allAccounts:[account]}),storage:JSON.stringify(state)})},
+ fixtureStorage:{getString:(k)=>backups.get(k),set:(k,v)=>backups.set(k,v),remove:(k)=>backups.delete(k)},
+ Keychain:{getGenericPassword:async()=>({username:'KEEPER-HOSTED-DISPOSABLE',password:JSON.stringify({hash:account.hash,enc_key:'controlled-ciphertext'})})},
+ cryptoJS:{SHA512:()=>({toString:()=> 'known-pin-hash'}),enc:{Hex:{},Utf8:{}},AES:{decrypt:()=>({toString:()=> 'a'.repeat(64)})}},
+ DeviceInfo:{getVersion:()=> '2.6.4',getBuildNumber:()=> '627'},schema:['controlled-fake-native-schema'],
+ Realm:{schemaVersion:async(path,key)=>{assert.equal(path,'keeper.realm');assert.equal(key.length,64);return schemaVersion;},open:async()=>{opens++;return db;}},
+ };
+ const run=(phase)=>runFixture({...args,phase});
+ const observe=(date='2026-10-22T02:03:04.000Z')=>rows.push({version:'2.6.4(627)',title:'Current installation observed',date,releaseNote:null});
+ return {args,run,rows,backups,app,state,account,observe,get writes(){return writes;},get opens(){return opens;},get closes(){return closes;},set schemaVersion(v){schemaVersion=v;}};
+}
+async function staleFirst(f) {await f.run('seed_stale');f.observe();await f.run('verify_stale_first');}
+async function staleRepeat(f) {await staleFirst(f);await f.run('verify_stale_repeat');}
+test('full controlled stale/empty cycle preserves both provenance dates, repeated observation date, and exact original rows',async()=>{
+ const f=setup(); await staleRepeat(f);
+ assert.deepEqual(f.rows.filter(r=>r.version!=='2.6.4(627)').map(({releaseNote,...r})=>r),STALE);
+ await f.run('seed_empty'); assert.equal(f.rows.length,0);
+ f.observe();await f.run('verify_empty_first');await f.run('verify_empty_repeat');
+ await f.run('restore');await f.run('verify_restored');
+ assert.deepEqual(f.rows,original);assert.equal(f.backups.has(BACKUP_KEY),false);
+ assert.equal(f.app.version,'2.6.4');assert.equal(f.state.appVersion,'2.6.4');
+ assert.equal(f.opens,f.closes);assert.equal(f.writes,3);
+});
+test('missing native Realm is rejected before opening or creating data',async()=>{
+ const f=setup();f.schemaVersion=-1;await assert.rejects(f.run('seed_stale'),/existing-schema-required/);
+ assert.equal(f.opens,0);assert.equal(f.writes,0);assert.deepEqual(f.rows,original);
+});
+test('foreign or changed account version cannot seed history',async()=>{
+ for(const mutate of [f=>f.account.appId='other',f=>f.app.id='other',f=>f.app.version='2.6.3',f=>f.state.appVersion='2.6.3']) {
+ const f=setup();mutate(f);await assert.rejects(f.run('seed_stale'));assert.equal(f.writes,0);assert.deepEqual(f.rows,original);
+ }
+});
+test('successful empty credentials, foreign username, wrong PIN, and malformed native key fail before Realm open',async()=>{
+ for(const value of [false,{username:'other',password:'{}'},{username:'KEEPER-HOSTED-DISPOSABLE',password:JSON.stringify({hash:'wrong-pin',enc_key:'x'})}]) {
+ const f=setup();f.args.Keychain.getGenericPassword=async()=>value;
+ await assert.rejects(f.run('seed_stale'));assert.equal(f.opens,0);assert.equal(f.writes,0);
+ }
+ const f=setup();f.args.cryptoJS.AES.decrypt=()=>({toString:()=> 'invalid'});
+ await assert.rejects(f.run('seed_stale'),/valid-native-realm-key-required/);assert.equal(f.opens,0);
+});
+test('foreign backup owner and malformed original rows cannot restore over current history',async()=>{
+ for(const mutate of [b=>b.identity.appId='other',b=>b.original=[]]) {
+ const f=setup();await f.run('seed_stale');const b=JSON.parse(f.backups.get(BACKUP_KEY));mutate(b);f.backups.set(BACKUP_KEY,JSON.stringify(b));
+ await assert.rejects(f.run('restore'));assert.equal(f.writes,1);assert.equal(f.rows.length,2);
+ }
+});
+test('missing observation and fabricated migration cannot satisfy current observation',async()=>{
+ const f=setup();await f.run('seed_stale');await assert.rejects(f.run('verify_stale_first'),/observation-required/);
+ f.observe();f.rows[2].title='Upgraded from 2.6.3 to 2.6.4';await assert.rejects(f.run('verify_stale_first'),/observation-required/);
+});
+test('changed old date, missing recovery provenance, and extra upgrade rows are rejected',async()=>{
+ for(const mutate of [f=>f.rows[0].date='2026-03-04T00:00:00Z',f=>f.rows.shift(),f=>f.rows.push({version:'1.0.0(1)',title:'Upgraded from old',date:'2026-01-01'})]) {
+ const f=setup();await f.run('seed_stale');f.observe();mutate(f);
+ await assert.rejects(f.run('verify_stale_first'),/provenance-mutated-or-fabricated-upgrade/);
+ }
+});
+test('repeat login must preserve observed date and cannot skip first verification',async()=>{
+ const f=setup();await f.run('seed_stale');f.observe();await assert.rejects(f.run('verify_stale_repeat'),/history-phase-order-required/);
+ await f.run('verify_stale_first');f.rows[2].date='2026-10-22T03:04:05Z';
+ await assert.rejects(f.run('verify_stale_repeat'),/observation-date-changed-on-relaunch/);
+});
+test('empty fixture never erases unexpected history after previous verification',async()=>{
+ const f=setup();await staleRepeat(f);f.rows.push({version:'1.0.0(1)',title:'unexpected',date:'2026-01-01'});
+ await assert.rejects(f.run('seed_empty'),/verified-history-changed-before-empty-fixture/);assert.equal(f.writes,1);
+});
+test('empty history yields exactly one observation; extra rows cannot pass',async()=>{
+ const f=setup();await staleRepeat(f);await f.run('seed_empty');f.observe();f.rows.push({...STALE[0]});
+ await assert.rejects(f.run('verify_empty_first'),/provenance-mutated-or-fabricated-upgrade/);
+});
+test('fixture is development/loopback only and fixed phase names do not create arbitrary hooks',async()=>{
+ const f=setup();f.args.development=false;await assert.rejects(f.run('seed_stale'),/disposable-build-required/);
+ f.args.development=true;await assert.rejects(f.run('arbitrary'),/phase-rejected/);assert.equal(f.opens,0);
+});
+
+test('first observation must be inside the device-local seed and verification clock window',async()=>{
+ for(const date of ['2026-01-01T00:00:00.000Z','2030-01-01T00:00:00.000Z']) {
+ const f=setup();await f.run('seed_stale');f.observe(date);
+ await assert.rejects(f.run('verify_stale_first'),/observation-outside-device-clock-window/);
+ }
+ const f=setup();await staleRepeat(f);await f.run('seed_empty');f.observe('2026-10-21T02:03:04.000Z');
+ await assert.rejects(f.run('verify_empty_first'),/observation-outside-device-clock-window/);
+});
diff --git a/.github/workflows/android-diagnostic-build.yml b/.github/workflows/android-diagnostic-build.yml
new file mode 100644
index 0000000000..9ebe30f1f8
--- /dev/null
+++ b/.github/workflows/android-diagnostic-build.yml
@@ -0,0 +1,153 @@
+name: Android diagnostic build
+
+on:
+ pull_request:
+ branches:
+ - 'release/**'
+ - sprint
+ - dev
+ - main
+ workflow_dispatch:
+
+permissions:
+ contents: read
+
+concurrency:
+ group: android-diagnostic-${{ github.event.pull_request.number || github.ref }}
+ cancel-in-progress: false
+
+jobs:
+ build:
+ # Hosted feature acceptance owns PR native scheduling. Retain explicit package diagnostics only.
+ if: github.event_name == 'workflow_dispatch'
+ runs-on: ubuntu-24.04
+ timeout-minutes: 90
+
+ steps:
+ - name: Check out source
+ uses: actions/checkout@v4
+ with:
+ ref: ${{ github.event.pull_request.head.sha || github.sha }}
+ persist-credentials: false
+
+ - name: Set up Node
+ uses: actions/setup-node@v4
+ with:
+ node-version: 22.23.3
+
+ - name: Set up Java
+ uses: actions/setup-java@v4
+ with:
+ distribution: temurin
+ java-version: '17.0.19'
+
+ - name: Set up Android SDK tools
+ uses: android-actions/setup-android@v4
+ with:
+ packages: ''
+
+ - name: Install Android build packages
+ run: sdkmanager 'platforms;android-36' 'build-tools;35.0.0' 'ndk;27.0.12077973' 'ndk;27.1.12297006' 'cmake;3.22.1'
+
+ - name: Install JavaScript dependencies without the iOS setup hook
+ run: |
+ npm install --global yarn@1.22.22
+ yarn install --frozen-lockfile --ignore-scripts --non-interactive
+ ./node_modules/.bin/patch-package
+ ./node_modules/.bin/rn-nodeify --install buffer,events,process,stream,inherits,path,assert,crypto --hack --yarn
+
+ - name: Create diagnostic configuration
+ run: |
+ cat > "$RUNNER_TEMP/keeper-diagnostic.env" <<'EOF'
+ CHANNEL_URL=https://channel.bitcoinkeeper.app/
+ ENVIRONMENT=PRODUCTION
+ HEXA_ID_MAINNET=0000000000000000000000000000000000000000000000000000000000000000
+ HEXA_ID_TESTNET=0000000000000000000000000000000000000000000000000000000000000000
+ RELAY=https://example.invalid/
+ SIGNING_SERVER_MAINNET=https://example.invalid/
+ SIGNING_SERVER_TESTNET=https://example.invalid/
+ EOF
+ node scripts/verify-channel-config.cjs "$RUNNER_TEMP/keeper-diagnostic.env"
+ printf 'sdk.dir=%s\n' "$ANDROID_SDK_ROOT" > android/local.properties
+
+ - name: Verify pinned Android inputs
+ env:
+ SOURCE_COMMIT: ${{ github.event.pull_request.head.sha || github.sha }}
+ run: |
+ python3 -B reproducibility/verify-android-inputs.py \
+ --source-commit "$SOURCE_COMMIT" \
+ --env-file "$RUNNER_TEMP/keeper-diagnostic.env" \
+ --android-sdk-root "$ANDROID_SDK_ROOT"
+
+ - name: Confirm Gradle rejects a retired mobile credential
+ run: |
+ cp "$RUNNER_TEMP/keeper-diagnostic.env" "$RUNNER_TEMP/keeper-rejected.env"
+ printf 'GASFREE_API_KEY=diagnostic-only\n' >> "$RUNNER_TEMP/keeper-rejected.env"
+ if (cd android && ENVFILE="$RUNNER_TEMP/keeper-rejected.env" ./gradlew :app:help --no-daemon --console=plain > "$RUNNER_TEMP/rejected-build.log" 2>&1); then
+ echo 'Gradle accepted a retired mobile credential' >&2
+ exit 1
+ fi
+ if ! grep -q 'Retired API credentials must not be included in an Android build' "$RUNNER_TEMP/rejected-build.log"; then
+ tail -80 "$RUNNER_TEMP/rejected-build.log"
+ exit 1
+ fi
+
+ - name: Build APK and AAB with the public debug key
+ env:
+ STORE_PASSWORD: android
+ KEY_ALIAS: androiddebugkey
+ KEY_PASSWORD: android
+ run: |
+ export ENVFILE="$RUNNER_TEMP/keeper-diagnostic.env"
+ export KEEPER_ANDROID_KEYSTORE="$GITHUB_WORKSPACE/android/app/debug.keystore"
+ cd android
+ ./gradlew :app:assembleProductionRelease :app:bundleProductionRelease --no-daemon --console=plain
+
+ - name: Check diagnostic artifacts
+ run: |
+ apk=android/app/build/outputs/apk/production/release/app-production-release.apk
+ aab=android/app/build/outputs/bundle/productionRelease/app-production-release.aab
+ test -s "$apk"
+ test -s "$aab"
+ "$ANDROID_SDK_ROOT/build-tools/35.0.0/apksigner" verify "$apk"
+ badging=$("$ANDROID_SDK_ROOT/build-tools/35.0.0/aapt2" dump badging "$apk")
+ version=$(node -p 'require("./release/version.json").version')
+ version_code=$(node -p 'require("./release/version.json").androidVersionCode')
+ grep -Fq "package: name='io.hexawallet.bitcoinkeeper' versionCode='$version_code' versionName='$version'" <<< "$badging"
+ if ! jarsigner -verify -verbose -certs "$aab" > "$RUNNER_TEMP/aab-signature.log" 2>&1; then
+ tail -80 "$RUNNER_TEMP/aab-signature.log"
+ exit 1
+ fi
+ if ! grep -Fxq 'jar verified.' "$RUNNER_TEMP/aab-signature.log" || grep -Fq '? = unsigned entry' "$RUNNER_TEMP/aab-signature.log"; then
+ tail -80 "$RUNNER_TEMP/aab-signature.log"
+ echo 'AAB is unsigned or contains unsigned entries' >&2
+ exit 1
+ fi
+ unzip -tq "$apk" >/dev/null
+ unzip -tq "$aab" >/dev/null
+ sha256sum "$apk" "$aab"
+ echo 'Diagnostic APK/AAB built with placeholder config and debug signing; no reproducibility verdict.'
+
+ - name: Stage diagnostic APK and provenance
+ env:
+ SOURCE_COMMIT: ${{ github.event.pull_request.head.sha || github.sha }}
+ run: |
+ apk=android/app/build/outputs/apk/production/release/app-production-release.apk
+ artifact_dir="$RUNNER_TEMP/android-diagnostic-apk"
+ mkdir -p "$artifact_dir"
+ cp "$apk" "$artifact_dir/keeper-diagnostic-production-release.apk"
+ {
+ printf 'source_commit=%s\n' "$SOURCE_COMMIT"
+ printf 'workflow_run_id=%s\n' "$GITHUB_RUN_ID"
+ printf 'apk_sha256=%s\n' "$(sha256sum "$artifact_dir/keeper-diagnostic-production-release.apk" | cut -d ' ' -f1)"
+ printf 'configuration=placeholder\nsigning=public-debug-key\npurpose=package-inspection-only\n'
+ } > "$artifact_dir/provenance.txt"
+
+ - name: Upload diagnostic APK for inspection
+ uses: actions/upload-artifact@v4
+ with:
+ name: android-diagnostic-apk-${{ github.event.pull_request.head.sha || github.sha }}
+ path: ${{ runner.temp }}/android-diagnostic-apk/
+ if-no-files-found: error
+ retention-days: 7
+ compression-level: 0
diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml
index a9dbb36c04..a6bdff8e86 100644
--- a/.github/workflows/codeql.yml
+++ b/.github/workflows/codeql.yml
@@ -6,11 +6,14 @@ on:
- sprint
- dev
- main
+ - release/2.6.4
pull_request:
branches:
- sprint
+ - codex/r3-release-baseline-to-sprint
- dev
- main
+ - release/2.6.4
permissions:
actions: read
@@ -25,12 +28,34 @@ jobs:
steps:
- name: Checkout code
- uses: actions/checkout@v7
+ uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
+ with:
+ persist-credentials: false
- name: Initialize CodeQL
- uses: github/codeql-action/init@v4
+ uses: github/codeql-action/init@9b3254085494b55a0f7c4c2b3d2d52cc712ce370 # v4
with:
languages: javascript-typescript
- name: Analyze
- uses: github/codeql-action/analyze@v4
+ id: codeql
+ uses: github/codeql-action/analyze@9b3254085494b55a0f7c4c2b3d2d52cc712ce370 # v4
+ with:
+ category: keeper-javascript-typescript/
+ wait-for-processing: true
+
+ - name: Capture official CodeQL upload ID
+ if: github.event_name == 'push' && github.ref == 'refs/heads/sprint'
+ env:
+ KEEPER_CODEQL_SARIF_ID: ${{ steps.codeql.outputs.sarif-id }}
+ KEEPER_WORKFLOW_SHA: ${{ github.workflow_sha }}
+ run: node scripts/codeql-analysis-receipt.cjs
+
+ - name: Upload CodeQL analysis provenance
+ if: github.event_name == 'push' && github.ref == 'refs/heads/sprint'
+ uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
+ with:
+ name: keeper-codeql-analysis-${{ github.sha }}-${{ github.run_id }}-${{ github.run_attempt }}
+ path: ${{ runner.temp }}/keeper-codeql-analysis/analysis.json
+ if-no-files-found: error
+ retention-days: 7
diff --git a/.github/workflows/keeper-canonical-native-contracts.yml b/.github/workflows/keeper-canonical-native-contracts.yml
new file mode 100644
index 0000000000..5880cf66ef
--- /dev/null
+++ b/.github/workflows/keeper-canonical-native-contracts.yml
@@ -0,0 +1,26 @@
+name: Canonical native provenance contracts
+on:
+ pull_request:
+ branches: [sprint]
+ paths:
+ - '.github/native/canonical_*'
+ - '.github/tests/canonical-native.test.cjs'
+ - '.github/tests/test_canonical_metadata.py'
+ - '.github/workflows/keeper-canonical-native*'
+permissions:
+ contents: read
+jobs:
+ contracts:
+ runs-on: ubuntu-24.04
+ timeout-minutes: 5
+ steps:
+ - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6
+ with:
+ persist-credentials: false
+ - uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6
+ with:
+ node-version: '22.23.3'
+ - name: Test read-only canonical trust and archive controls
+ run: |
+ node --test .github/tests/canonical-native.test.cjs
+ python3 -m unittest discover -s .github/tests -p test_canonical_metadata.py
diff --git a/.github/workflows/keeper-canonical-native-platform.yml b/.github/workflows/keeper-canonical-native-platform.yml
new file mode 100644
index 0000000000..9c3b08862c
--- /dev/null
+++ b/.github/workflows/keeper-canonical-native-platform.yml
@@ -0,0 +1,161 @@
+name: Keeper canonical native platform
+
+on:
+ workflow_call:
+ inputs:
+ source_sha:
+ type: string
+ required: true
+ platform:
+ type: string
+ required: true
+ secrets:
+ canonical_pin_read_token:
+ description: Repository-selected Variables read identity for live pin verification only
+ required: true
+
+# This worker has no environment, release credentials or dispatch. Its only
+# secret input is scoped to the initial live-pin verification script.
+permissions:
+ contents: read
+ actions: read
+ checks: read
+
+jobs:
+ native:
+ name: Canonical ${{ inputs.platform }} build and features
+ if: github.event_name == 'workflow_dispatch' && github.ref == 'refs/heads/sprint' && inputs.source_sha == github.sha
+ runs-on: ${{ inputs.platform == 'IOS' && 'macos-15' || 'ubuntu-24.04' }}
+ # Same standard hosted workers and feature budget as candidate diagnostics.
+ timeout-minutes: 240
+ env:
+ CI: 'true'
+ HUSKY: '0'
+ KEEPER_SOURCE_SHA: ${{ inputs.source_sha }}
+ KEEPER_NATIVE_PLATFORM: ${{ inputs.platform }}
+ MAESTRO_CLI_NO_ANALYTICS: '1'
+ KEEPER_DIAGNOSTIC: 'false'
+ steps:
+ - name: Check out exact app source
+ uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6
+ with:
+ ref: ${{ inputs.source_sha }}
+ persist-credentials: false
+ - name: Verify canonical installed source
+ uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8
+ env:
+ KEEPER_CANONICAL_NATIVE_DRIVER_SHA: ${{ vars.KEEPER_CANONICAL_NATIVE_DRIVER_SHA }}
+ KEEPER_CANONICAL_PIN_READ_TOKEN: ${{ secrets.canonical_pin_read_token }}
+ with:
+ script: |
+ try {
+ const driver = require('./.github/native/canonical_native.cjs');
+ const pinReader = driver.pinReaderFromEnvironment(github, process.env);
+ const request = driver.requestFromEnvironment(context, process.env);
+ await driver.origin(github, context, request, { admission: true, pinReader });
+ } catch {
+ core.setFailed('Canonical installed source, exact attempt or native capacity is unverified. No native credit.');
+ }
+ - name: Set up Node
+ uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6
+ with:
+ node-version: '22.23.3'
+ cache: yarn
+ - name: Set up Java
+ uses: actions/setup-java@b6effb05e454b25005698d916606bdc6ffcbf961 # v5
+ with:
+ distribution: temurin
+ java-version: '17'
+ cache: gradle
+ - name: Set up Ruby
+ if: inputs.platform == 'IOS'
+ uses: ruby/setup-ruby@675dd7ba1b06c8786a1480d89c384f5620a42647 # v1.281.0
+ with:
+ ruby-version: '3.3.8'
+ - name: Select reviewed Xcode
+ if: inputs.platform == 'IOS'
+ run: echo 'DEVELOPER_DIR=/Applications/Xcode_16.4.app/Contents/Developer' >> "$GITHUB_ENV"
+ - name: Set up Android command-line tools
+ if: inputs.platform == 'ANDROID'
+ uses: android-actions/setup-android@be39fa834029ff78f1a44aa3bb0819b8fc2bd8fd # v4
+ with:
+ cmdline-tools-version: '13114758'
+ packages: platform-tools
+ log-accepted-android-sdk-licenses: false
+ - name: Record runner and toolchain
+ run: python3 .github/native/hosted_native.py record
+ - name: Install immutable native dependencies
+ run: python3 .github/native/hosted_native.py prepare
+ - name: Check disposable iOS driver readiness
+ if: inputs.platform == 'IOS'
+ run: |
+ test "$(git rev-parse HEAD)" = '${{ inputs.source_sha }}'
+ git diff --exit-code HEAD -- .github/native .github/workflows
+ python3 .github/native/hosted_native.py driver
+ - name: Build development app
+ run: |
+ test "$(git rev-parse HEAD)" = '${{ inputs.source_sha }}'
+ git diff --exit-code HEAD -- .github/native .github/workflows
+ python3 .github/native/hosted_native.py build
+ - name: Run disposable startup smoke
+ if: inputs.platform == 'IOS'
+ run: |
+ test "$(git rev-parse HEAD)" = '${{ inputs.source_sha }}'
+ git diff --exit-code HEAD -- .github/native .github/workflows
+ python3 .github/native/hosted_native.py smoke
+ - name: Run disposable native persistence probe
+ if: inputs.platform == 'IOS'
+ run: |
+ test "$(git rev-parse HEAD)" = '${{ inputs.source_sha }}'
+ git diff --exit-code HEAD -- .github/native .github/workflows
+ python3 .github/native/hosted_native.py probe
+ - name: Run R5 production worker native scenarios
+ if: inputs.platform == 'IOS'
+ run: |
+ test "$(git rev-parse HEAD)" = '${{ inputs.source_sha }}'
+ git diff --exit-code HEAD -- .github/native .github/workflows
+ python3 .github/native/hosted_native.py features
+ - name: Measure full-product startup wallet and Retry flows
+ if: inputs.platform == 'IOS'
+ run: |
+ test "$(git rev-parse HEAD)" = '${{ inputs.source_sha }}'
+ git diff --exit-code HEAD -- .github/native .github/workflows
+ python3 .github/native/product_measurements.py run
+ - name: Enable emulator acceleration
+ if: inputs.platform == 'ANDROID'
+ run: |
+ echo 'KERNEL=="kvm", GROUP="kvm", MODE="0666", OPTIONS+="static_node=kvm"' | sudo tee /etc/udev/rules.d/99-keeper-kvm.rules
+ sudo udevadm control --reload-rules
+ sudo udevadm trigger --name-match=kvm
+ - name: Run Android startup persistence worker and product flows
+ if: inputs.platform == 'ANDROID'
+ uses: reactivecircus/android-emulator-runner@1dcd0090116d15e7c562f8db72807de5e036a4ed # v2.34.0
+ with:
+ api-level: 35
+ target: google_apis
+ arch: x86_64
+ profile: pixel_6
+ cores: 2
+ ram-size: 3072M
+ force-avd-creation: true
+ disable-animations: true
+ emulator-boot-timeout: 240
+ emulator-options: -no-window -gpu swiftshader_indirect -noaudio -no-boot-anim -no-snapshot -camera-back none -camera-front none
+ script: |
+ test "$(git rev-parse HEAD)" = '${{ inputs.source_sha }}'
+ git diff --exit-code HEAD -- .github/native .github/workflows
+ python3 .github/native/hosted_native.py smoke
+ git diff --exit-code HEAD -- .github/native .github/workflows
+ python3 .github/native/hosted_native.py probe
+ git diff --exit-code HEAD -- .github/native .github/workflows
+ python3 .github/native/hosted_native.py features
+ git diff --exit-code HEAD -- .github/native .github/workflows
+ python3 .github/native/product_measurements.py run
+ - name: Retain exact canonical platform metadata
+ if: always()
+ uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6
+ with:
+ name: keeper-canonical-native-${{ inputs.platform }}-${{ inputs.source_sha }}-${{ github.run_id }}-${{ github.run_attempt }}
+ path: artifacts/native/${{ inputs.platform == 'IOS' && 'ios' || 'android' }}/metadata.json
+ if-no-files-found: error
+ retention-days: 7
diff --git a/.github/workflows/keeper-canonical-native.yml b/.github/workflows/keeper-canonical-native.yml
new file mode 100644
index 0000000000..5d9a02e6f2
--- /dev/null
+++ b/.github/workflows/keeper-canonical-native.yml
@@ -0,0 +1,116 @@
+name: Keeper canonical native acceptance
+
+on:
+ workflow_dispatch:
+ inputs:
+ source_sha:
+ description: Exact reviewed canonical sprint HEAD; must equal the installed driver pin
+ required: true
+ type: string
+
+# Read-only native testing. The separate Variables:read credential is available
+# only to provenance scripts; no environments, status writes or release operations.
+permissions:
+ contents: read
+ actions: read
+ checks: read
+
+env:
+ KEEPER_SOURCE_SHA: ${{ inputs.source_sha }}
+ KEEPER_CANONICAL_NATIVE_DRIVER_SHA: ${{ vars.KEEPER_CANONICAL_NATIVE_DRIVER_SHA }}
+
+jobs:
+ provenance:
+ name: Canonical installed driver and capacity admission
+ runs-on: ubuntu-24.04
+ timeout-minutes: 5
+ outputs:
+ trusted: ${{ steps.check.outputs.trusted }}
+ steps:
+ - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6
+ with:
+ ref: ${{ github.sha }}
+ persist-credentials: false
+ - id: check
+ uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8
+ env:
+ KEEPER_CANONICAL_PIN_READ_TOKEN: ${{ secrets.KEEPER_CANONICAL_PIN_READ_TOKEN }}
+ with:
+ script: |
+ try {
+ const driver = require('./.github/native/canonical_native.cjs');
+ const pinReader = driver.pinReaderFromEnvironment(github, process.env);
+ const request = driver.requestFromEnvironment(context, process.env);
+ await driver.origin(github, context, request, { admission: true, pinReader });
+ core.setOutput('trusted', 'true');
+ } catch {
+ core.setOutput('trusted', 'false');
+ core.setFailed('Canonical workflow, live pin read identity, source/attempt or native capacity is unverified. No native credit.');
+ }
+
+ ios:
+ needs: provenance
+ if: needs.provenance.outputs.trusted == 'true'
+ uses: ./.github/workflows/keeper-canonical-native-platform.yml
+ with:
+ source_sha: ${{ inputs.source_sha }}
+ platform: IOS
+ secrets:
+ canonical_pin_read_token: ${{ secrets.KEEPER_CANONICAL_PIN_READ_TOKEN }}
+
+ android:
+ needs: [provenance, ios]
+ if: needs.provenance.outputs.trusted == 'true' && needs.ios.result == 'success'
+ uses: ./.github/workflows/keeper-canonical-native-platform.yml
+ with:
+ source_sha: ${{ inputs.source_sha }}
+ platform: ANDROID
+ secrets:
+ canonical_pin_read_token: ${{ secrets.KEEPER_CANONICAL_PIN_READ_TOKEN }}
+
+ attestation:
+ name: Canonical native attestation
+ needs: [provenance, ios, android]
+ if: always()
+ runs-on: ubuntu-24.04
+ timeout-minutes: 10
+ steps:
+ - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6
+ with:
+ ref: ${{ github.sha }}
+ persist-credentials: false
+ - name: Verify canonical receipts and required matrix
+ uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8
+ env:
+ KEEPER_CANONICAL_PIN_READ_TOKEN: ${{ secrets.KEEPER_CANONICAL_PIN_READ_TOKEN }}
+ IOS_RESULT: ${{ needs.ios.result }}
+ ANDROID_RESULT: ${{ needs.android.result }}
+ with:
+ script: |
+ try {
+ if (process.env.IOS_RESULT !== 'success' || process.env.ANDROID_RESULT !== 'success') {
+ throw new Error('Required platform did not execute successfully');
+ }
+ const driver = require('./.github/native/canonical_native.cjs');
+ const pinReader = driver.pinReaderFromEnvironment(github, process.env);
+ const request = driver.requestFromEnvironment(context, process.env);
+ await driver.collect(github, context, request, 'artifacts/canonical-native', driver.readMetadataZip, { pinReader });
+ } catch {
+ core.setFailed('Canonical software matrix incomplete or exact Actions/receipt provenance invalid. No release authorization.');
+ }
+ - name: Retain bounded canonical readiness
+ if: always()
+ uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6
+ with:
+ name: keeper-canonical-native-readiness-${{ inputs.source_sha }}-${{ github.run_id }}-${{ github.run_attempt }}
+ path: artifacts/canonical-native/keeper-canonical-native-readiness.json
+ if-no-files-found: ignore
+ retention-days: 7
+ - name: Retain complete canonical attestation
+ if: success()
+ uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6
+ with:
+ name: keeper-canonical-native-attestation-${{ inputs.source_sha }}-${{ github.run_id }}-${{ github.run_attempt }}
+ path: artifacts/canonical-native/keeper-canonical-native-attestation.json
+ if-no-files-found: error
+ retention-days: 7
diff --git a/.github/workflows/keeper-hosted-native.yml b/.github/workflows/keeper-hosted-native.yml
new file mode 100644
index 0000000000..6fd390996e
--- /dev/null
+++ b/.github/workflows/keeper-hosted-native.yml
@@ -0,0 +1,151 @@
+name: Keeper hosted native validation
+
+on:
+ pull_request:
+ branches: [sprint]
+ types: [opened, synchronize, reopened, ready_for_review, converted_to_draft, labeled, unlabeled]
+
+# PR code runs only in disposable, unprivileged jobs. No signing or service secrets.
+permissions:
+ contents: read
+
+concurrency:
+ group: keeper-hosted-native-${{ github.event.pull_request.number }}
+ cancel-in-progress: true
+
+env:
+ CI: 'true'
+ HUSKY: '0'
+ KEEPER_SOURCE_SHA: ${{ github.event.pull_request.head.sha }}
+ MAESTRO_CLI_NO_ANALYTICS: '1'
+
+jobs:
+ ios:
+ name: Hosted iOS simulator
+ # Skip before allocating a runner; missing/non-boolean draft state fails closed.
+ if: github.event_name == 'pull_request' && toJSON(github.event.pull_request.draft) == 'false' && contains(github.event.pull_request.labels.*.name, 'keeper/legacy-native') && !contains(github.event.pull_request.labels.*.name, 'keeper/native-diagnostic')
+ runs-on: macos-15
+ timeout-minutes: 65
+ env:
+ KEEPER_NATIVE_PLATFORM: IOS
+ DEVELOPER_DIR: /Applications/Xcode_16.4.app/Contents/Developer
+ steps:
+ - name: Check out exact app source
+ uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6
+ with:
+ ref: ${{ github.event.pull_request.head.sha }}
+ persist-credentials: false
+ - name: Set up Node
+ uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6
+ with:
+ node-version: '22.22.0'
+ cache: yarn
+ - name: Set up Java for Maestro
+ uses: actions/setup-java@b6effb05e454b25005698d916606bdc6ffcbf961 # v5
+ with:
+ distribution: temurin
+ java-version: '17'
+ - name: Set up Ruby
+ uses: ruby/setup-ruby@675dd7ba1b06c8786a1480d89c384f5620a42647 # v1.281.0
+ with:
+ ruby-version: '3.3.8'
+ - name: Record runner and toolchain
+ run: python3 .github/native/hosted_native.py record
+ - name: Install immutable native dependencies
+ run: python3 .github/native/hosted_native.py prepare
+ - name: Check disposable iOS driver readiness
+ run: |
+ test "$(git rev-parse HEAD)" = '${{ github.event.pull_request.head.sha }}'
+ git diff --exit-code HEAD -- .github/native .github/workflows/keeper-hosted-native.yml
+ python3 .github/native/hosted_native.py driver
+ - name: Build development app
+ run: |
+ test "$(git rev-parse HEAD)" = '${{ github.event.pull_request.head.sha }}'
+ git diff --exit-code HEAD -- .github/native .github/workflows/keeper-hosted-native.yml
+ python3 .github/native/hosted_native.py build
+ - name: Run disposable startup smoke
+ run: |
+ test "$(git rev-parse HEAD)" = '${{ github.event.pull_request.head.sha }}'
+ git diff --exit-code HEAD -- .github/native .github/workflows/keeper-hosted-native.yml
+ python3 .github/native/hosted_native.py smoke
+ - name: Retain safe native evidence
+ if: always()
+ uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6
+ with:
+ name: keeper-native-ios-${{ github.event.pull_request.head.sha }}
+ path: |
+ artifacts/native/ios/metadata.json
+ artifacts/native/ios/Podfile.lock.candidate
+ if-no-files-found: warn
+ retention-days: 7
+
+ android:
+ needs: ios
+ name: Hosted Android emulator
+ if: always() && github.event_name == 'pull_request' && toJSON(github.event.pull_request.draft) == 'false' && contains(github.event.pull_request.labels.*.name, 'keeper/legacy-native') && !contains(github.event.pull_request.labels.*.name, 'keeper/native-diagnostic')
+ runs-on: ubuntu-24.04
+ timeout-minutes: 60
+ env:
+ KEEPER_NATIVE_PLATFORM: ANDROID
+ steps:
+ - name: Check out exact app source
+ uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6
+ with:
+ ref: ${{ github.event.pull_request.head.sha }}
+ persist-credentials: false
+ - name: Set up Node
+ uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6
+ with:
+ node-version: '22.22.0'
+ cache: yarn
+ - name: Set up Java
+ uses: actions/setup-java@b6effb05e454b25005698d916606bdc6ffcbf961 # v5
+ with:
+ distribution: temurin
+ java-version: '17'
+ cache: gradle
+ - name: Set up Android command-line tools
+ uses: android-actions/setup-android@be39fa834029ff78f1a44aa3bb0819b8fc2bd8fd # v4
+ with:
+ cmdline-tools-version: '13114758'
+ packages: platform-tools
+ log-accepted-android-sdk-licenses: false
+ - name: Record runner and toolchain
+ run: python3 .github/native/hosted_native.py record
+ - name: Install immutable native dependencies
+ run: python3 .github/native/hosted_native.py prepare
+ - name: Build development app
+ run: |
+ test "$(git rev-parse HEAD)" = '${{ github.event.pull_request.head.sha }}'
+ git diff --exit-code HEAD -- .github/native .github/workflows/keeper-hosted-native.yml
+ python3 .github/native/hosted_native.py build
+ - name: Enable emulator acceleration
+ run: |
+ echo 'KERNEL=="kvm", GROUP="kvm", MODE="0666", OPTIONS+="static_node=kvm"' | sudo tee /etc/udev/rules.d/99-keeper-kvm.rules
+ sudo udevadm control --reload-rules
+ sudo udevadm trigger --name-match=kvm
+ - name: Run disposable startup smoke
+ uses: reactivecircus/android-emulator-runner@1dcd0090116d15e7c562f8db72807de5e036a4ed # v2.34.0 (peeled commit)
+ with:
+ api-level: 35
+ target: google_apis
+ arch: x86_64
+ profile: pixel_6
+ cores: 2
+ ram-size: 3072M
+ force-avd-creation: true
+ disable-animations: true
+ emulator-boot-timeout: 240
+ emulator-options: -no-window -gpu swiftshader_indirect -noaudio -no-boot-anim -no-snapshot -camera-back none -camera-front none
+ script: |
+ test "$(git rev-parse HEAD)" = '${{ github.event.pull_request.head.sha }}'
+ git diff --exit-code HEAD -- .github/native .github/workflows/keeper-hosted-native.yml
+ python3 .github/native/hosted_native.py smoke
+ - name: Retain safe native evidence
+ if: always()
+ uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6
+ with:
+ name: keeper-native-android-${{ github.event.pull_request.head.sha }}
+ path: artifacts/native/android/metadata.json
+ if-no-files-found: warn
+ retention-days: 7
diff --git a/.github/workflows/keeper-local-validation.yml b/.github/workflows/keeper-local-validation.yml
index d66fc70f88..955aeeb775 100644
--- a/.github/workflows/keeper-local-validation.yml
+++ b/.github/workflows/keeper-local-validation.yml
@@ -4,24 +4,28 @@ name: Keeper local validation gate
on:
pull_request_target:
branches: [sprint]
- types: [opened, reopened, synchronize, edited, ready_for_review]
+ types: [opened, reopened, synchronize, edited, ready_for_review, labeled, unlabeled]
issue_comment:
types: [created, edited, deleted]
+ workflow_run:
+ workflows: [Keeper hosted native validation, Keeper release acceptance]
+ types: [completed, requested, in_progress]
permissions:
contents: read
issues: read
pull-requests: read
+ actions: read
statuses: write
concurrency:
- group: keeper-local-validation-${{ github.event.pull_request.number || github.event.issue.number }}
+ group: keeper-local-validation-${{ github.event.pull_request.number || github.event.issue.number || github.event.workflow_run.pull_requests[0].number || github.run_id }}
cancel-in-progress: false
jobs:
keeper-local-validation:
name: Keeper local validation gate
- if: github.event_name == 'pull_request_target' || github.event.issue.pull_request != null
+ if: github.event_name == 'pull_request_target' || github.event.issue.pull_request != null || github.event.workflow_run.event == 'pull_request'
runs-on: ubuntu-latest
steps:
- name: Verify local validation for exact PR commit
@@ -30,7 +34,9 @@ jobs:
script: |
const owner = context.repo.owner;
const repo = context.repo.repo;
- const pull_number = context.payload.pull_request?.number ?? context.issue.number;
+ const pull_number = context.payload.pull_request?.number ??
+ context.payload.workflow_run?.pull_requests?.[0]?.number ?? context.issue.number;
+ if (!pull_number) return;
const { data: pr } = await github.rest.pulls.get({ owner, repo, pull_number });
if (pr.base.ref !== 'sprint') {
core.info('Only PRs targeting sprint use this validation gate.');
@@ -87,8 +93,92 @@ jobs:
return allowed;
};
+ // PR workflows are editable by the PR author. A successful check name
+ // alone is NOT evidence. All executable CI files must match both the
+ // protected current base and the base used by that particular run.
+ // This intentionally rejects this infrastructure PR's bootstrap runs.
+ const nativeRoute = value => value.labels?.some(label => label.name === 'keeper/native-diagnostic')
+ ? 'diagnostic' : value.labels?.some(label => label.name === 'keeper/legacy-native')
+ ? 'keeper-hosted-native.yml' : 'keeper-release-acceptance.yml';
+ const hostedPasses = async () => {
+ const passed = new Set();
+ try {
+ const selectedWorkflow = nativeRoute(pr);
+ if (selectedWorkflow === 'diagnostic') return passed;
+ const repository = owner + '/' + repo;
+ if (pr.head.repo?.full_name !== repository) return passed;
+ const runs = await github.paginate(github.rest.actions.listWorkflowRuns, {
+ owner, repo, workflow_id: selectedWorkflow,
+ head_sha: sha, event: 'pull_request', per_page: 100
+ });
+ // Do not fall back to an older success after a failed/cancelled
+ // rerun or while newer evidence is pending.
+ const run = runs.sort((a, b) => b.id - a.id)[0];
+ const reusable = run?.path === '.github/workflows/keeper-release-acceptance.yml';
+ const workflowPath = '.github/workflows/' + selectedWorkflow;
+ if (reusable && pull_number === 7045) return passed;
+ if (!run || run.head_sha !== sha || run.event !== 'pull_request' ||
+ run.path !== workflowPath || run.head_branch !== pr.head.ref ||
+ run.head_repository?.full_name !== repository ||
+ run.status !== 'completed' || !['success', 'failure'].includes(run.conclusion)) {
+ return passed;
+ }
+ const linked = run.pull_requests?.find(p => p.number === pull_number);
+ if (!linked || linked.head?.sha !== sha || linked.head?.ref !== pr.head.ref ||
+ linked.base?.ref !== 'sprint' || !linked.base?.sha ||
+ linked.head?.repo?.id !== pr.head.repo.id ||
+ linked.base?.repo?.id !== pr.base.repo?.id ||
+ !pr.head.repo.id || !pr.base.repo?.id ||
+ !Number.isSafeInteger(run.run_attempt) || run.run_attempt < 1) return passed;
+ const fingerprint = async ref => {
+ const { data } = await github.rest.git.getTree({ owner, repo, tree_sha: ref, recursive: '1' });
+ if (data.truncated) throw new Error('Truncated trusted CI tree');
+ const requiredWorkflows = reusable
+ ? [workflowPath, '.github/workflows/keeper-native-platform.yml', '.github/workflows/keeper-hosted-native.yml']
+ : [workflowPath];
+ const entries = data.tree.filter(e => requiredWorkflows.includes(e.path) ||
+ e.path.startsWith('.github/native/'));
+ if (!requiredWorkflows.every(path => entries.some(e => e.path === path && e.type === 'blob' && ['100644', '100755'].includes(e.mode))) ||
+ !entries.some(e => e.path.startsWith('.github/native/') && e.type === 'blob')) {
+ throw new Error('Hosted native infrastructure not present in trusted base');
+ }
+ return JSON.stringify(entries.map(e => [e.path, e.mode, e.type, e.sha])
+ .sort((a, b) => a[0].localeCompare(b[0])));
+ };
+ const [headFiles, baseFiles, runBaseFiles] = await Promise.all([
+ fingerprint(sha), fingerprint(pr.base.sha), fingerprint(linked.base.sha)
+ ]);
+ if (headFiles !== baseFiles || headFiles !== runBaseFiles) return passed;
+ const jobs = await github.paginate(github.rest.actions.listJobsForWorkflowRunAttempt, {
+ owner, repo, run_id: run.id, attempt_number: run.run_attempt, per_page: 100
+ });
+ for (const [platform, legacyName] of [['IOS', 'Hosted iOS simulator'],
+ ['ANDROID', 'Hosted Android emulator']]) {
+ const name = reusable ? `${platform.toLowerCase()} / Native ${platform} build and probes` : legacyName;
+ const matches = jobs.filter(j => j.name === name);
+ if (matches.length !== 1) continue;
+ const job = matches[0];
+ if (job.head_sha !== sha || job.run_id !== run.id || job.run_attempt !== run.run_attempt ||
+ job.status !== 'completed' || job.conclusion !== 'success') continue;
+ const steps = reusable
+ ? ['Build development app', ...(platform === 'IOS'
+ ? ['Run disposable startup smoke', 'Run disposable native persistence probe']
+ : ['Run Android startup and native persistence probes'])]
+ : ['Build development app', 'Run disposable startup smoke'];
+ if (steps.every(name => job.steps?.filter(s => s.name === name &&
+ s.status === 'completed' && s.conclusion === 'success').length === 1)) {
+ passed.add(platform);
+ core.info(platform + ' hosted evidence: ' + run.html_url + ', attempt ' + run.run_attempt);
+ }
+ }
+ } catch (err) {
+ core.warning('Hosted evidence unavailable; local fallback retained: ' + err.message);
+ }
+ return passed;
+ };
+
let state = 'failure';
- let description = 'Awaiting local Mac validation';
+ let description = 'Awaiting exact-head hosted or local native validation';
if (docsOnly) {
state = 'success';
description = 'Documentation/GitHub metadata only; local testing exempt';
@@ -129,6 +219,7 @@ jobs:
if (malformed) {
description = 'Specify Required local checks: IOS, ANDROID, HARDWARE';
} else {
+ const hosted = await hostedPasses();
// Only the release owner can defer unrun physical checks. Keep
// every original handoff intact, and bind the newest owner
// decision to this PR and this exact head commit.
@@ -165,9 +256,7 @@ jobs:
break;
}
}
- if (!report) {
- description = 'Awaiting trusted Mac validation of current SHA';
- } else if (field(report, 'State') !== 'LOCAL_PASSED') {
+ if (report && field(report, 'State') !== 'LOCAL_PASSED') {
description = 'Latest local validation is not LOCAL_PASSED';
} else {
const reportFields = {
@@ -179,10 +268,12 @@ jobs:
const hardwareDeferred = required.has('HARDWARE') && hardwareDeferral &&
reportIndex > ownerDecisionIndex &&
/^(not run|deferred)\b/i.test(hardwareResult);
- const notPassed = [...required].filter(x =>
- !/^pass\b/i.test(field(report, reportFields[x])) &&
- !(x === 'HARDWARE' && hardwareDeferred)
- );
+ const notPassed = [...required].filter(x => {
+ const result = field(report, reportFields[x]);
+ if (/^fail(?:ed)?\b/i.test(result)) return true;
+ return !/^pass\b/i.test(result) && !hosted.has(x) &&
+ !(x === 'HARDWARE' && hardwareDeferred);
+ });
if (hardwareDeferred && !required.has('IOS') && !required.has('ANDROID')) {
description = 'IOS or ANDROID required before HARDWARE deferral';
} else if (notPassed.length) {
@@ -190,9 +281,10 @@ jobs:
} else {
state = 'success';
const passed = [...required].filter(x =>
- /^pass\b/i.test(field(report, reportFields[x]))
+ /^pass\b/i.test(field(report, reportFields[x])) || hosted.has(x)
);
description = 'Validated at current SHA: ' + passed.join(', ') +
+ (hosted.size ? '; hosted ' + [...hosted].join(', ') : '') +
(hardwareDeferred ? '; owner-deferred HARDWARE' : '');
}
}
@@ -200,6 +292,26 @@ jobs:
}
}
+ // API reads above can take time. Never post a success for a head that
+ // changed while evidence was being collected.
+ const { data: current } = await github.rest.pulls.get({ owner, repo, pull_number });
+ if (current.head.sha !== sha) {
+ core.setFailed('PR head changed during validation; awaiting new-head evaluation');
+ return;
+ }
+ if (current.base.sha !== pr.base.sha || current.base.ref !== pr.base.ref ||
+ current.base.repo?.id !== pr.base.repo?.id || current.base.repo?.full_name !== pr.base.repo?.full_name ||
+ current.head.ref !== pr.head.ref || current.head.repo?.id !== pr.head.repo?.id ||
+ current.head.repo?.full_name !== pr.head.repo?.full_name || nativeRoute(current) !== nativeRoute(pr)) {
+ // The head is unchanged, so explicitly revoke any prior success on this SHA.
+ await github.rest.repos.createCommitStatus({
+ owner, repo, sha, state: 'failure', context: contextName,
+ description: 'PR base, identity or native route changed; fresh evaluation required',
+ target_url: pr.html_url
+ });
+ core.setFailed('PR base, repository, ref or native route changed during validation; awaiting fresh evaluation');
+ return;
+ }
await github.rest.repos.createCommitStatus({
owner, repo, sha, state,
context: contextName,
diff --git a/.github/workflows/keeper-native-diagnostic.yml b/.github/workflows/keeper-native-diagnostic.yml
new file mode 100644
index 0000000000..64b6737f89
--- /dev/null
+++ b/.github/workflows/keeper-native-diagnostic.yml
@@ -0,0 +1,83 @@
+name: Keeper native candidate diagnostics
+
+on:
+ pull_request:
+ branches: [sprint]
+ types: [labeled, synchronize, reopened]
+
+# This explicit opt-in never writes status or supplies trusted native acceptance.
+permissions:
+ contents: read
+ pull-requests: read
+
+concurrency:
+ group: keeper-native-diagnostic-${{ github.event.pull_request.number }}
+ cancel-in-progress: false
+
+jobs:
+ driver-preflight:
+ # Diagnosis only. This label never opts into either app build or Android.
+ if: github.event.pull_request.number != 7045 && github.event.pull_request.head.repo.full_name == github.repository && contains(github.event.pull_request.labels.*.name, 'keeper/ios-driver-preflight') && !contains(github.event.pull_request.labels.*.name, 'keeper/native-diagnostic')
+ runs-on: macos-15
+ timeout-minutes: 15
+ env:
+ CI: 'true'
+ KEEPER_SOURCE_SHA: ${{ github.event.pull_request.head.sha }}
+ KEEPER_NATIVE_PLATFORM: IOS
+ KEEPER_DIAGNOSTIC: 'true'
+ MAESTRO_CLI_NO_ANALYTICS: '1'
+ DEVELOPER_DIR: /Applications/Xcode_16.4.app/Contents/Developer
+ steps:
+ - name: Check out exact diagnostic source
+ uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6
+ with:
+ ref: ${{ github.event.pull_request.head.sha }}
+ persist-credentials: false
+ - name: Verify current preflight source and isolated opt-in
+ uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8
+ with:
+ script: |
+ const { data: pr } = await github.rest.pulls.get({ ...context.repo, pull_number: context.payload.pull_request.number });
+ const labels = pr.labels.map(label => label.name);
+ if (pr.head.sha !== process.env.KEEPER_SOURCE_SHA || pr.head.repo.full_name !== `${context.repo.owner}/${context.repo.repo}` || !labels.includes('keeper/ios-driver-preflight') || labels.includes('keeper/native-diagnostic')) {
+ core.setFailed('Preflight source moved or isolated opt-in is absent; no native credit');
+ }
+ - name: Set up Node
+ uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6
+ with:
+ node-version: '22.23.3'
+ - name: Set up Java
+ uses: actions/setup-java@b6effb05e454b25005698d916606bdc6ffcbf961 # v5
+ with:
+ distribution: temurin
+ java-version: '17'
+ - name: Diagnose unchanged Maestro driver before app build
+ run: |
+ test "$(git rev-parse HEAD)" = "$KEEPER_SOURCE_SHA"
+ git diff --exit-code HEAD -- .github/native .github/workflows
+ python3 .github/native/driver_diagnosis.py
+ - name: Retain bounded driver diagnosis
+ if: always()
+ uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6
+ with:
+ name: keeper-ios-driver-diagnosis-${{ github.event.pull_request.head.sha }}
+ path: artifacts/native/ios/metadata.json
+ if-no-files-found: error
+ retention-days: 7
+
+ ios:
+ if: github.event.pull_request.number != 7045 && github.event.pull_request.head.repo.full_name == github.repository && contains(github.event.pull_request.labels.*.name, 'keeper/native-diagnostic')
+ uses: ./.github/workflows/keeper-native-platform.yml
+ with:
+ source_sha: ${{ github.event.pull_request.head.sha }}
+ platform: IOS
+ diagnostic: true
+
+ android:
+ needs: ios
+ if: always() && github.event.pull_request.number != 7045 && github.event.pull_request.head.repo.full_name == github.repository && contains(github.event.pull_request.labels.*.name, 'keeper/native-diagnostic')
+ uses: ./.github/workflows/keeper-native-platform.yml
+ with:
+ source_sha: ${{ github.event.pull_request.head.sha }}
+ platform: ANDROID
+ diagnostic: true
diff --git a/.github/workflows/keeper-native-platform.yml b/.github/workflows/keeper-native-platform.yml
new file mode 100644
index 0000000000..2444a7de09
--- /dev/null
+++ b/.github/workflows/keeper-native-platform.yml
@@ -0,0 +1,157 @@
+name: Keeper reusable native platform
+
+on:
+ workflow_call:
+ inputs:
+ source_sha:
+ type: string
+ required: true
+ platform:
+ type: string
+ required: true
+
+ diagnostic:
+ type: boolean
+ default: false
+ required: false
+
+# This worker has no environment, release credentials, secret inputs or dispatch.
+permissions:
+ contents: read
+ pull-requests: read
+
+jobs:
+ native:
+ name: Native ${{ inputs.platform }} build and probes
+ if: github.event_name == 'pull_request' && github.event.pull_request.number != 7045 && inputs.source_sha == github.event.pull_request.head.sha && (toJSON(github.event.pull_request.draft) == 'false' || (inputs.diagnostic && contains(github.event.pull_request.labels.*.name, 'keeper/native-diagnostic')))
+ runs-on: ${{ inputs.platform == 'IOS' && 'macos-15' || 'ubuntu-24.04' }}
+ # One build/device per platform includes all scoped companion UI phases.
+ # Standard hosted runners only; this is a global fail-closed runtime ceiling.
+ timeout-minutes: 240
+ env:
+ CI: 'true'
+ HUSKY: '0'
+ KEEPER_SOURCE_SHA: ${{ inputs.source_sha }}
+ KEEPER_NATIVE_PLATFORM: ${{ inputs.platform }}
+ MAESTRO_CLI_NO_ANALYTICS: '1'
+ KEEPER_DIAGNOSTIC: ${{ inputs.diagnostic }}
+ steps:
+ - name: Check out exact app source
+ uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6
+ with:
+ ref: ${{ inputs.source_sha }}
+ persist-credentials: false
+ - name: Verify current diagnostic source
+ if: inputs.diagnostic
+ uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8
+ env:
+ EXPECTED_SOURCE: ${{ inputs.source_sha }}
+ with:
+ script: |
+ const { data: pr } = await github.rest.pulls.get({ ...context.repo, pull_number: context.payload.pull_request.number });
+ if (pr.head.sha !== process.env.EXPECTED_SOURCE || pr.head.repo.full_name !== `${context.repo.owner}/${context.repo.repo}` || !pr.labels.some(label => label.name === 'keeper/native-diagnostic')) {
+ core.setFailed('Diagnostic source moved or opt-in removed; no native credit');
+ }
+ - name: Set up Node
+ uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6
+ with:
+ node-version: '22.23.3'
+ cache: yarn
+ - name: Set up Java
+ uses: actions/setup-java@b6effb05e454b25005698d916606bdc6ffcbf961 # v5
+ with:
+ distribution: temurin
+ java-version: '17'
+ cache: gradle
+ - name: Set up Ruby
+ if: inputs.platform == 'IOS'
+ uses: ruby/setup-ruby@675dd7ba1b06c8786a1480d89c384f5620a42647 # v1.281.0
+ with:
+ ruby-version: '3.3.8'
+ - name: Select reviewed Xcode
+ if: inputs.platform == 'IOS'
+ run: echo 'DEVELOPER_DIR=/Applications/Xcode_16.4.app/Contents/Developer' >> "$GITHUB_ENV"
+ - name: Set up Android command-line tools
+ if: inputs.platform == 'ANDROID'
+ uses: android-actions/setup-android@be39fa834029ff78f1a44aa3bb0819b8fc2bd8fd # v4
+ with:
+ cmdline-tools-version: '13114758'
+ packages: platform-tools
+ log-accepted-android-sdk-licenses: false
+ - name: Record runner and toolchain
+ run: python3 .github/native/hosted_native.py record
+ - name: Install immutable native dependencies
+ run: python3 .github/native/hosted_native.py prepare
+ - name: Check disposable iOS driver readiness
+ if: inputs.platform == 'IOS'
+ run: |
+ test "$(git rev-parse HEAD)" = '${{ inputs.source_sha }}'
+ git diff --exit-code HEAD -- .github/native .github/workflows
+ python3 .github/native/hosted_native.py driver
+ - name: Build development app
+ run: |
+ test "$(git rev-parse HEAD)" = '${{ inputs.source_sha }}'
+ git diff --exit-code HEAD -- .github/native .github/workflows
+ python3 .github/native/hosted_native.py build
+ - name: Run disposable startup smoke
+ if: inputs.platform == 'IOS'
+ run: |
+ test "$(git rev-parse HEAD)" = '${{ inputs.source_sha }}'
+ git diff --exit-code HEAD -- .github/native .github/workflows
+ python3 .github/native/hosted_native.py smoke
+ - name: Run disposable native persistence probe
+ if: inputs.platform == 'IOS'
+ run: |
+ test "$(git rev-parse HEAD)" = '${{ inputs.source_sha }}'
+ git diff --exit-code HEAD -- .github/native .github/workflows
+ python3 .github/native/hosted_native.py probe
+ - name: Run R5 production worker native scenarios
+ if: inputs.platform == 'IOS'
+ run: |
+ test "$(git rev-parse HEAD)" = '${{ inputs.source_sha }}'
+ git diff --exit-code HEAD -- .github/native .github/workflows
+ python3 .github/native/hosted_native.py features
+ - name: Measure five full-product startup and first-wallet runs
+ if: inputs.platform == 'IOS'
+ run: |
+ test "$(git rev-parse HEAD)" = '${{ inputs.source_sha }}'
+ git diff --exit-code HEAD -- .github/native .github/workflows
+ python3 .github/native/product_measurements.py run
+ - name: Enable emulator acceleration
+ if: inputs.platform == 'ANDROID'
+ run: |
+ echo 'KERNEL=="kvm", GROUP="kvm", MODE="0666", OPTIONS+="static_node=kvm"' | sudo tee /etc/udev/rules.d/99-keeper-kvm.rules
+ sudo udevadm control --reload-rules
+ sudo udevadm trigger --name-match=kvm
+ - name: Run Android startup and native persistence probes
+ if: inputs.platform == 'ANDROID'
+ uses: reactivecircus/android-emulator-runner@1dcd0090116d15e7c562f8db72807de5e036a4ed # v2.34.0
+ with:
+ api-level: 35
+ target: google_apis
+ arch: x86_64
+ profile: pixel_6
+ cores: 2
+ ram-size: 3072M
+ force-avd-creation: true
+ disable-animations: true
+ emulator-boot-timeout: 240
+ emulator-options: -no-window -gpu swiftshader_indirect -noaudio -no-boot-anim -no-snapshot -camera-back none -camera-front none
+ script: |
+ test "$(git rev-parse HEAD)" = '${{ inputs.source_sha }}'
+ git diff --exit-code HEAD -- .github/native .github/workflows
+ python3 .github/native/hosted_native.py smoke
+ git diff --exit-code HEAD -- .github/native .github/workflows
+ python3 .github/native/hosted_native.py probe
+ git diff --exit-code HEAD -- .github/native .github/workflows
+ python3 .github/native/hosted_native.py features
+ git diff --exit-code HEAD -- .github/native .github/workflows
+ python3 .github/native/product_measurements.py run
+ - name: Retain safe Phase A evidence
+ if: always()
+ uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6
+ with:
+ name: keeper-${{ inputs.diagnostic && 'diagnostic' || 'release' }}-native-${{ inputs.platform }}-${{ inputs.source_sha }}-${{ github.run_id }}-${{ github.run_attempt }}
+ path: artifacts/native/*/metadata.json
+ if-no-files-found: error
+ retention-days: 7
diff --git a/.github/workflows/keeper-protected-release-plan.yml b/.github/workflows/keeper-protected-release-plan.yml
new file mode 100644
index 0000000000..e14b026625
--- /dev/null
+++ b/.github/workflows/keeper-protected-release-plan.yml
@@ -0,0 +1,100 @@
+name: Protected release preparation (no signing or upload)
+
+on:
+ workflow_dispatch:
+ inputs:
+ source_sha:
+ description: Full reviewed immutable candidate commit
+ required: true
+ release_ref:
+ description: Protected release/version branch at that exact commit
+ required: true
+ operation:
+ description: Operation to prepare; this workflow cannot execute it
+ type: choice
+ options: [ios-signed-build, android-signed-build, testflight-upload, play-internal-upload]
+ required: true
+ version:
+ description: Exact marketing version
+ required: true
+ build:
+ description: Exact platform build counter
+ required: true
+ artifact_sha256:
+ description: Artifact digest for upload preparation; pending for signed-build preparation
+ required: true
+ default: pending
+ approval_comment_id:
+ description: Existing owner approval comment ID with exact scope and expiry
+ required: true
+
+permissions:
+ contents: read
+ actions: read
+ checks: read
+ statuses: read
+ issues: read
+
+concurrency:
+ group: keeper-protected-release-preparation
+ cancel-in-progress: false
+
+jobs:
+ authorize:
+ runs-on: ubuntu-latest
+ timeout-minutes: 10
+ outputs:
+ environment: ${{ steps.plan.outputs.environment }}
+ steps:
+ - name: Checkout installed trusted driver
+ uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
+ with:
+ ref: ${{ github.sha }}
+ path: driver
+ persist-credentials: false
+ - name: Use the reviewed Node runtime
+ uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7
+ with:
+ node-version: '22.23.3'
+ - name: Validate request before candidate checkout
+ env:
+ KEEPER_SOURCE_SHA: ${{ inputs.source_sha }}
+ KEEPER_RELEASE_REF: ${{ inputs.release_ref }}
+ KEEPER_OPERATION: ${{ inputs.operation }}
+ KEEPER_VERSION: ${{ inputs.version }}
+ KEEPER_BUILD: ${{ inputs.build }}
+ KEEPER_ARTIFACT_SHA256: ${{ inputs.artifact_sha256 }}
+ KEEPER_APPROVAL_COMMENT_ID: ${{ inputs.approval_comment_id }}
+ run: |
+ node -e "require('./driver/scripts/protected-release-plan.cjs').requestFromEnvironment(process.env)" 2>/dev/null || { echo 'Invalid preparation request'; exit 1; }
+ - name: Read candidate files without executing candidate scripts
+ uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
+ with:
+ ref: ${{ inputs.source_sha }}
+ path: candidate
+ persist-credentials: false
+ - name: Check exact source, owner receipt and protected setup
+ id: plan
+ env:
+ GH_TOKEN: ${{ github.token }}
+ KEEPER_CANDIDATE_PATH: candidate
+ KEEPER_SOURCE_SHA: ${{ inputs.source_sha }}
+ KEEPER_RELEASE_REF: ${{ inputs.release_ref }}
+ KEEPER_OPERATION: ${{ inputs.operation }}
+ KEEPER_VERSION: ${{ inputs.version }}
+ KEEPER_BUILD: ${{ inputs.build }}
+ KEEPER_ARTIFACT_SHA256: ${{ inputs.artifact_sha256 }}
+ KEEPER_APPROVAL_COMMENT_ID: ${{ inputs.approval_comment_id }}
+ run: node driver/scripts/protected-release-plan.cjs
+
+ protected-plan:
+ needs: authorize
+ runs-on: ubuntu-latest
+ timeout-minutes: 5
+ environment: ${{ needs.authorize.outputs.environment }}
+ permissions: {}
+ steps:
+ - name: Record preparation boundary
+ run: |
+ echo 'Protected authorization plan prepared. Signing and upload workers are NOT IMPLEMENTED.'
+ echo 'Artifact bytes/signatures remain unverified. No release action is permitted or executed here.'
diff --git a/.github/workflows/keeper-protected-release-workers.yml b/.github/workflows/keeper-protected-release-workers.yml
new file mode 100644
index 0000000000..18c99ece51
--- /dev/null
+++ b/.github/workflows/keeper-protected-release-workers.yml
@@ -0,0 +1,182 @@
+name: Protected release workers (explicit approval only)
+
+on:
+ workflow_dispatch:
+ inputs:
+ request_json:
+ description: Exact reviewed non-secret request JSON; see release/cloud/README.md
+ required: true
+ type: string
+
+permissions:
+ contents: read
+ actions: read
+ checks: read
+ statuses: read
+ issues: read
+
+concurrency:
+ group: keeper-protected-release-workers
+ cancel-in-progress: false
+
+jobs:
+ plan:
+ runs-on: ubuntu-latest
+ timeout-minutes: 10
+ outputs:
+ source_sha: ${{ steps.request.outputs.source_sha }}
+ operation: ${{ steps.request.outputs.operation }}
+ platform: ${{ steps.request.outputs.platform }}
+ environment: ${{ steps.plan.outputs.environment }}
+ steps:
+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
+ with:
+ ref: ${{ github.sha }}
+ path: driver
+ persist-credentials: false
+ - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7
+ with:
+ node-version: '22.23.3'
+ - name: Reject untrusted/malformed requests before candidate checkout
+ id: request
+ env:
+ KEEPER_RELEASE_REQUEST_JSON: ${{ inputs.request_json }}
+ run: node driver/scripts/protected-release-worker.cjs request
+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
+ with:
+ ref: ${{ steps.request.outputs.source_sha }}
+ path: candidate
+ persist-credentials: false
+ - name: Verify exact source, approval and protected environment exist
+ id: plan
+ env:
+ KEEPER_RELEASE_REQUEST_JSON: ${{ inputs.request_json }}
+ KEEPER_CANDIDATE_PATH: candidate
+ GH_TOKEN: ${{ github.token }}
+ run: node driver/scripts/protected-release-worker.cjs plan
+
+ approved-operation:
+ needs: plan
+ runs-on: ${{ needs.plan.outputs.platform == 'ios' && 'macos-15' || 'ubuntu-24.04' }}
+ timeout-minutes: 100
+ environment: ${{ needs.plan.outputs.environment }}
+ env:
+ KEEPER_RELEASE_REQUEST_JSON: ${{ inputs.request_json }}
+ KEEPER_CANDIDATE_PATH: ${{ github.workspace }}/candidate
+ KEEPER_EXPECTED_CERT_SHA256: ${{ vars.KEEPER_RELEASE_CERT_SHA256 }}
+ KEEPER_EXPECTED_CONFIG_SHA256: ${{ vars.KEEPER_PRODUCTION_CONFIG_SHA256 }}
+ KEEPER_IOS_TEAM_ID: ${{ vars.KEEPER_IOS_TEAM_ID }}
+ KEEPER_IOS_PROFILE_UUID: ${{ vars.KEEPER_IOS_PROFILE_UUID }}
+ FASTLANE_SKIP_UPDATE_CHECK: '1'
+ FASTLANE_OPT_OUT_USAGE: '1'
+ LANG: en_US.UTF-8
+ steps:
+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
+ with:
+ ref: ${{ github.sha }}
+ path: driver
+ persist-credentials: false
+ - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7
+ with:
+ node-version: '22.23.3'
+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
+ with:
+ ref: ${{ needs.plan.outputs.source_sha }}
+ path: candidate
+ persist-credentials: false
+ - name: Revalidate AFTER protected environment approval, before credentials
+ env:
+ GH_TOKEN: ${{ github.token }}
+ run: node driver/scripts/protected-release-worker.cjs revalidate
+ - uses: ruby/setup-ruby@675dd7ba1b06c8786a1480d89c384f5620a42647 # v1.281.0
+ with:
+ ruby-version: '3.3.8'
+ - uses: actions/setup-java@b6effb05e454b25005698d916606bdc6ffcbf961 # v5
+ with:
+ distribution: temurin
+ java-version: '17'
+ - name: Install frozen trusted uploader/Pod dependencies without credentials
+ working-directory: driver
+ env:
+ BUNDLE_DEPLOYMENT: 'true'
+ BUNDLE_FROZEN: 'true'
+ BUNDLE_PATH: ${{ runner.temp }}/keeper-gems
+ run: |
+ bundle install --jobs 4
+ echo "BUNDLE_GEMFILE=$GITHUB_WORKSPACE/driver/Gemfile" >> "$GITHUB_ENV"
+ echo "BUNDLE_PATH=$RUNNER_TEMP/keeper-gems" >> "$GITHUB_ENV"
+ echo "KEEPER_PACKAGE_OVERLAY_PATH=$RUNNER_TEMP/keeper-nodeify-overlay.json" >> "$GITHUB_ENV"
+ - name: Reject incompatible frozen iOS toolchain without credentials
+ if: needs.plan.outputs.operation == 'ios-signed-build'
+ run: python3 driver/scripts/cloud_release_worker.py ruby-lock-check candidate unused
+ - name: Install pinned bundletool without credentials
+ if: needs.plan.outputs.platform == 'android'
+ run: |
+ curl --fail --location --silent --show-error https://github.com/google/bundletool/releases/download/1.18.1/bundletool-all-1.18.1.jar --output "$RUNNER_TEMP/keeper-bundletool.jar"
+ echo "675786493983787ffa11550bdb7c0715679a44e1643f3ff980a529e9c822595c $RUNNER_TEMP/keeper-bundletool.jar" | sha256sum --check --status
+ echo "BUNDLETOOL_JAR=$RUNNER_TEMP/keeper-bundletool.jar" >> "$GITHUB_ENV"
+ - uses: android-actions/setup-android@be39fa834029ff78f1a44aa3bb0819b8fc2bd8fd # v4
+ if: needs.plan.outputs.operation == 'android-signed-build'
+ with:
+ cmdline-tools-version: '13114758'
+ packages: platform-tools
+ log-accepted-android-sdk-licenses: false
+ - name: Install reviewed Android build inputs without credentials
+ if: needs.plan.outputs.operation == 'android-signed-build'
+ run: sdkmanager 'platforms;android-36' 'build-tools;35.0.0' 'ndk;27.1.12297006' 'cmake;3.22.1'
+ - name: Prepare canonical native dependencies without credentials
+ if: endsWith(needs.plan.outputs.operation, '-signed-build')
+ working-directory: candidate
+ run: |
+ python3 -c "import shutil; assert shutil.disk_usage('.').free >= 16 * 1024**3, 'Insufficient native build disk reserve'"
+ npm install --global yarn@1.22.22 --ignore-scripts
+ yarn install --frozen-lockfile --ignore-scripts --non-interactive
+ node_modules/.bin/patch-package --error-on-fail
+ node .github/native/nodeify.cjs
+ git diff --exit-code HEAD -- yarn.lock ios/Podfile.lock
+ python3 ../driver/scripts/cloud_release_worker.py overlay . "$KEEPER_PACKAGE_OVERLAY_PATH"
+ - name: Prepare frozen iOS dependencies without credentials
+ if: needs.plan.outputs.operation == 'ios-signed-build'
+ working-directory: candidate/ios
+ env:
+ DEVELOPER_DIR: /Applications/Xcode_16.4.app/Contents/Developer
+ run: |
+ test -d "$DEVELOPER_DIR"
+ bundle exec pod install --deployment
+ git diff --exit-code HEAD -- Podfile.lock
+ echo "DEVELOPER_DIR=$DEVELOPER_DIR" >> "$GITHUB_ENV"
+ - name: Refresh authorization immediately before loading operation credentials
+ env:
+ GH_TOKEN: ${{ github.token }}
+ run: node driver/scripts/protected-release-worker.cjs revalidate
+ - name: Execute only the approved signed build, with no upload credentials
+ if: endsWith(needs.plan.outputs.operation, '-signed-build')
+ id: sign
+ env:
+ GH_TOKEN: ${{ github.token }}
+ KEEPER_PRODUCTION_CONFIG_BASE64: ${{ secrets.KEEPER_PRODUCTION_CONFIG_BASE64 }}
+ KEEPER_IOS_P12_BASE64: ${{ needs.plan.outputs.platform == 'ios' && secrets.KEEPER_IOS_P12_BASE64 || '' }}
+ KEEPER_IOS_P12_PASSWORD: ${{ needs.plan.outputs.platform == 'ios' && secrets.KEEPER_IOS_P12_PASSWORD || '' }}
+ KEEPER_IOS_PROFILE_BASE64: ${{ needs.plan.outputs.platform == 'ios' && secrets.KEEPER_IOS_PROFILE_BASE64 || '' }}
+ KEEPER_ANDROID_KEYSTORE_BASE64: ${{ needs.plan.outputs.platform == 'android' && secrets.KEEPER_ANDROID_KEYSTORE_BASE64 || '' }}
+ STORE_PASSWORD: ${{ needs.plan.outputs.platform == 'android' && secrets.STORE_PASSWORD || '' }}
+ KEY_PASSWORD: ${{ needs.plan.outputs.platform == 'android' && secrets.KEY_PASSWORD || '' }}
+ KEY_ALIAS: ${{ needs.plan.outputs.platform == 'android' && secrets.KEY_ALIAS || '' }}
+ run: node driver/scripts/protected-release-worker.cjs execute
+ - name: Execute only the approved immutable upload, with no signing credentials
+ if: endsWith(needs.plan.outputs.operation, '-upload')
+ id: upload
+ env:
+ GH_TOKEN: ${{ github.token }}
+ KEEPER_ASC_KEY_ID: ${{ needs.plan.outputs.platform == 'ios' && secrets.KEEPER_ASC_KEY_ID || '' }}
+ KEEPER_ASC_ISSUER_ID: ${{ needs.plan.outputs.platform == 'ios' && secrets.KEEPER_ASC_ISSUER_ID || '' }}
+ KEEPER_ASC_KEY_BASE64: ${{ needs.plan.outputs.platform == 'ios' && secrets.KEEPER_ASC_KEY_BASE64 || '' }}
+ KEEPER_PLAY_SERVICE_ACCOUNT: ${{ needs.plan.outputs.platform == 'android' && secrets.KEEPER_PLAY_SERVICE_ACCOUNT || '' }}
+ run: node driver/scripts/protected-release-worker.cjs execute
+ - name: Retain only the explicitly approved signed artifact or upload receipt
+ uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
+ with:
+ name: keeper-approved-release-${{ github.run_id }}-${{ github.run_attempt }}
+ path: ${{ steps.sign.outputs.artifact_dir || steps.upload.outputs.artifact_dir }}
+ if-no-files-found: error
+ retention-days: 14
diff --git a/.github/workflows/keeper-release-acceptance.yml b/.github/workflows/keeper-release-acceptance.yml
new file mode 100644
index 0000000000..313e68737e
--- /dev/null
+++ b/.github/workflows/keeper-release-acceptance.yml
@@ -0,0 +1,83 @@
+name: Keeper release acceptance
+
+on:
+ pull_request:
+ branches: [sprint]
+ types: [opened, synchronize, reopened, ready_for_review, converted_to_draft, labeled, unlabeled]
+
+permissions:
+ contents: read
+ pull-requests: read
+ actions: read
+
+concurrency:
+ group: keeper-release-acceptance-${{ github.event.pull_request.number }}
+ cancel-in-progress: true
+
+jobs:
+ provenance:
+ name: Reviewed CI bootstrap and exact-head provenance
+ # Freeze the existing R4 release and its gate, even after future CI installation.
+ if: github.event.pull_request.number != 7045
+ runs-on: ubuntu-24.04
+ timeout-minutes: 5
+ outputs:
+ trusted: ${{ steps.check.outputs.trusted }}
+ steps:
+ - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6
+ with:
+ ref: ${{ github.event.pull_request.head.sha }}
+ persist-credentials: false
+ - id: check
+ uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8
+ with:
+ script: |
+ const { preflight } = require('./.github/native/release_preflight.cjs');
+ const result = await preflight(github, context);
+ core.setOutput('trusted', String(result.trusted));
+ await core.summary.addHeading('Phase A provenance').addRaw(result.reason).write();
+
+ ios:
+ needs: provenance
+ if: toJSON(github.event.pull_request.draft) == 'false' && !contains(github.event.pull_request.labels.*.name, 'keeper/legacy-native') && !contains(github.event.pull_request.labels.*.name, 'keeper/native-diagnostic') && needs.provenance.outputs.trusted == 'true'
+ uses: ./.github/workflows/keeper-native-platform.yml
+ with:
+ source_sha: ${{ github.event.pull_request.head.sha }}
+ platform: IOS
+
+ android:
+ needs: [provenance, ios]
+ if: toJSON(github.event.pull_request.draft) == 'false' && !contains(github.event.pull_request.labels.*.name, 'keeper/legacy-native') && !contains(github.event.pull_request.labels.*.name, 'keeper/native-diagnostic') && needs.provenance.outputs.trusted == 'true'
+ uses: ./.github/workflows/keeper-native-platform.yml
+ with:
+ source_sha: ${{ github.event.pull_request.head.sha }}
+ platform: ANDROID
+
+ acceptance:
+ name: Phase A release acceptance (incomplete matrix blocks)
+ needs: [provenance, ios, android]
+ if: always() && github.event.pull_request.number != 7045
+ runs-on: ubuntu-24.04
+ timeout-minutes: 5
+ steps:
+ - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6
+ with:
+ ref: ${{ github.event.pull_request.head.sha }}
+ persist-credentials: false
+ - uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8
+ env:
+ IOS_RESULT: ${{ needs.ios.result }}
+ ANDROID_RESULT: ${{ needs.android.result }}
+ with:
+ script: |
+ const { preflight } = require('./.github/native/release_preflight.cjs');
+ const { acceptance, markdown } = require('./.github/native/release_acceptance.cjs');
+ const { evidence } = require('./.github/native/release_evidence.cjs');
+ const verified = await preflight(github, context);
+ const currentAttempt = verified.trusted && await evidence(github, context, {
+ ios: process.env.IOS_RESULT, android: process.env.ANDROID_RESULT,
+ attempt: Number(process.env.GITHUB_RUN_ATTEMPT) });
+ const result = acceptance({ trusted: currentAttempt,
+ ios: process.env.IOS_RESULT, android: process.env.ANDROID_RESULT });
+ await core.summary.addRaw(markdown(result)).write();
+ core.setFailed('BLOCKED: full app acceptance is NOT IMPLEMENTED / NOT VERIFIED; no release approval');
diff --git a/.github/workflows/keeper-release-origin-contracts.yml b/.github/workflows/keeper-release-origin-contracts.yml
new file mode 100644
index 0000000000..b8a2b56bfa
--- /dev/null
+++ b/.github/workflows/keeper-release-origin-contracts.yml
@@ -0,0 +1,41 @@
+name: Keeper release origin contracts
+
+on:
+ pull_request:
+ paths:
+ - '.github/workflows/keeper-release-origin-contracts.yml'
+ - 'scripts/trusted-release-origin*'
+ - 'scripts/codeql-analysis-receipt*'
+ - '.github/workflows/codeql.yml'
+ - 'docs/r5-trusted-release-origin.md'
+ push:
+ paths:
+ - '.github/workflows/keeper-release-origin-contracts.yml'
+ - 'scripts/trusted-release-origin*'
+ - 'scripts/codeql-analysis-receipt*'
+ - '.github/workflows/codeql.yml'
+ - 'docs/r5-trusted-release-origin.md'
+
+permissions:
+ contents: read
+
+concurrency:
+ group: release-origin-contracts-${{ github.ref }}
+ cancel-in-progress: false
+
+jobs:
+ contracts:
+ name: Mocked read-only provenance contracts
+ runs-on: ubuntu-24.04
+ timeout-minutes: 10
+ steps:
+ - name: Check out contract source
+ uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
+ with:
+ persist-credentials: false
+ - name: Set up Node
+ uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
+ with:
+ node-version: '22.23.3'
+ - name: Test fake API and bounded artifact evidence
+ run: node --test scripts/trusted-release-origin.test.cjs scripts/codeql-analysis-receipt.test.cjs scripts/protected-release-plan.test.cjs
diff --git a/.github/workflows/keeper-release-preparation-contracts.yml b/.github/workflows/keeper-release-preparation-contracts.yml
new file mode 100644
index 0000000000..f0d8425a0f
--- /dev/null
+++ b/.github/workflows/keeper-release-preparation-contracts.yml
@@ -0,0 +1,48 @@
+name: Protected release preparation contracts
+
+on:
+ pull_request:
+ paths:
+ - '.github/workflows/keeper-protected-release-plan.yml'
+ - '.github/workflows/keeper-release-preparation-contracts.yml'
+ - '.github/workflows/keeper-protected-release-workers.yml'
+ - 'scripts/protected-release-plan*'
+ - 'scripts/protected-release-worker*'
+ - 'scripts/cloud_release_inventory.py'
+ - 'scripts/test_cloud_release_inventory.py'
+ - 'scripts/cloud_release_worker.py'
+ - 'scripts/test_cloud_release_worker.py'
+ - 'scripts/release-version.cjs'
+ - 'scripts/test_cloud_upload_adapters.rb'
+ - 'release/cloud/**'
+ workflow_dispatch:
+
+permissions:
+ contents: read
+
+concurrency:
+ group: keeper-release-preparation-contracts-${{ github.event.pull_request.number || github.ref }}
+ cancel-in-progress: false
+
+jobs:
+ contracts:
+ runs-on: ubuntu-latest
+ timeout-minutes: 5
+ steps:
+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
+ with:
+ ref: ${{ github.event.pull_request.head.sha || github.sha }}
+ persist-credentials: false
+ - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7
+ with:
+ node-version: '22.23.3'
+ - uses: ruby/setup-ruby@675dd7ba1b06c8786a1480d89c384f5620a42647 # v1.281.0
+ with:
+ ruby-version: '3.3.8'
+ - name: Offline gate and inventory contracts
+ run: |
+ node --test scripts/protected-release-plan.test.cjs scripts/protected-release-worker.test.cjs scripts/release-version.test.cjs scripts/verify-channel-config.test.cjs
+ python3 -B -m unittest discover -s scripts -p 'test_cloud_release_inventory.py'
+ python3 -B -m unittest discover -s scripts -p 'test_release_artifact.py'
+ python3 -B -m unittest discover -s scripts -p 'test_cloud_release_worker.py'
+ ruby scripts/test_cloud_upload_adapters.rb
diff --git a/.github/workflows/keeper-ruby-lock-contracts.yml b/.github/workflows/keeper-ruby-lock-contracts.yml
new file mode 100644
index 0000000000..24f7346620
--- /dev/null
+++ b/.github/workflows/keeper-ruby-lock-contracts.yml
@@ -0,0 +1,52 @@
+name: Frozen cloud Ruby toolchain
+
+on:
+ pull_request:
+ paths:
+ - 'Gemfile'
+ - 'Gemfile.lock'
+ - 'ios/Podfile.lock'
+ - 'package.json'
+ - 'yarn.lock'
+ - 'scripts/check_cloud_release_inputs.py'
+ - 'scripts/cloud_release_worker.py'
+ - 'scripts/test_cloud_release_worker.py'
+ - '.github/workflows/keeper-ruby-lock-contracts.yml'
+ - 'release/cloud/Fastfile'
+ - 'scripts/test_cloud_upload_adapters.rb'
+ - 'scripts/test_cloud_upload_fastlane.rb'
+ workflow_dispatch:
+
+permissions:
+ contents: read
+
+concurrency:
+ group: keeper-ruby-lock-${{ github.event.pull_request.number || github.ref }}
+ cancel-in-progress: false
+
+jobs:
+ frozen-runtime:
+ runs-on: ubuntu-latest
+ timeout-minutes: 15
+ steps:
+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
+ with:
+ ref: ${{ github.event.pull_request.head.sha || github.sha }}
+ persist-credentials: false
+ - uses: ruby/setup-ruby@675dd7ba1b06c8786a1480d89c384f5620a42647 # v1.281.0
+ with:
+ ruby-version: '3.3.8'
+ - name: Install/load only the frozen toolchain; no native build or provider access
+ env:
+ BUNDLE_PATH: ${{ runner.temp }}/keeper-ruby-gems
+ BUNDLE_FROZEN: 'true'
+ run: |
+ python3 -B scripts/check_cloud_release_inputs.py --root .
+ python3 -B -m unittest discover -s scripts -p 'test_cloud_release_worker.py'
+ bundle install --jobs 4 --retry 1
+ bundle check
+ bundle exec ruby -e 'require "cocoapods"; require "xcodeproj"; require "rexml/document"; abort unless Pod::VERSION == "1.16.2" && Xcodeproj::VERSION == "1.27.0"; puts "Frozen CocoaPods/Xcodeproj load PASS"'
+ bundle exec ruby -rxcodeproj -e 'p = Xcodeproj::Project.open("ios/hexa_keeper.xcodeproj"); abort unless p.targets.any? { |t| t.name == "hexa_keeper" }; puts "Existing Xcode project parse PASS"'
+ ruby scripts/test_fastlane_build_only.rb
+ bundle exec ruby scripts/test_cloud_upload_fastlane.rb
+ git diff --exit-code HEAD -- Gemfile Gemfile.lock package.json yarn.lock ios/Podfile.lock
diff --git a/.github/workflows/keeper-validation-tests.yml b/.github/workflows/keeper-validation-tests.yml
new file mode 100644
index 0000000000..834cfae086
--- /dev/null
+++ b/.github/workflows/keeper-validation-tests.yml
@@ -0,0 +1,33 @@
+name: Native validation contracts
+
+on:
+ pull_request:
+ branches: [sprint]
+ push:
+ branches: [sprint]
+ paths: ['.github/**']
+
+permissions:
+ contents: read
+
+jobs:
+ contracts:
+ name: Native validation contracts
+ runs-on: ubuntu-24.04
+ timeout-minutes: 5
+ steps:
+ - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6
+ with:
+ persist-credentials: false
+ - uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6
+ with:
+ node-version: '22.23.3'
+ - name: Install isolated locked contract tools without lifecycle scripts
+ run: |
+ npm ci --prefix .github/native/contract-tools --ignore-scripts --no-audit --no-fund
+ echo "NODE_PATH=$GITHUB_WORKSPACE/.github/native/contract-tools/node_modules" >> "$GITHUB_ENV"
+ - name: Verify contract compiler matches the candidate
+ run: |
+ node -e "require('node:assert/strict').equal(require('typescript/package.json').version, require('./package.json').devDependencies.typescript)"
+ - run: node --test .github/tests/*.test.cjs
+ - run: python3 -B -m unittest discover -s .github/tests -p 'test_*.py'
diff --git a/.github/workflows/public-backend.yml b/.github/workflows/public-backend.yml
new file mode 100644
index 0000000000..9212bdce78
--- /dev/null
+++ b/.github/workflows/public-backend.yml
@@ -0,0 +1,59 @@
+name: Public backend setup
+
+on:
+ push:
+ branches: [sprint, main]
+ paths:
+ - 'dev/local-backend/**'
+ - '.github/workflows/public-backend.yml'
+ pull_request:
+ branches: [sprint, main]
+ paths:
+ - 'dev/local-backend/**'
+ - '.github/workflows/public-backend.yml'
+ workflow_dispatch:
+
+permissions:
+ contents: read
+
+concurrency:
+ group: public-backend-${{ github.event.pull_request.number || github.ref }}
+ cancel-in-progress: true
+
+jobs:
+ signing:
+ name: Public SigningServer adapter
+ runs-on: ubuntu-latest
+ timeout-minutes: 20
+ steps:
+ - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
+ with:
+ persist-credentials: false
+ - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
+ with:
+ node-version: '22'
+ - run: ./dev/local-backend/dev prepare-signing
+ - run: npm ci --ignore-scripts
+ working-directory: dev/local-backend/.sources/signing
+ - run: npm run compile
+ working-directory: dev/local-backend/.sources/signing
+ - run: npm test
+ working-directory: dev/local-backend/.sources/signing
+
+ backend:
+ name: Local backend and bootstrap
+ runs-on: ubuntu-latest
+ timeout-minutes: 25
+ steps:
+ - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
+ with:
+ persist-credentials: false
+ - uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5
+ with:
+ python-version: '3.9'
+ - run: python3 -B -m unittest discover -s dev/local-backend -p 'test_*.py'
+ - run: ./dev/local-backend/dev up
+ - run: ./dev/local-backend/verify-local.sh --persistence --boundaries
+ - name: Stop containers and retain volumes
+ if: always()
+ run: ./dev/local-backend/dev stop
diff --git a/.github/workflows/r5-044-ios-artifact-readout.yml b/.github/workflows/r5-044-ios-artifact-readout.yml
new file mode 100644
index 0000000000..2c732dd144
--- /dev/null
+++ b/.github/workflows/r5-044-ios-artifact-readout.yml
@@ -0,0 +1,38 @@
+name: Read exact 044 iOS metadata bytes
+
+on:
+ push:
+ branches: [codex/r5-044-artifact-readout-preparation-20261023]
+ paths:
+ - .github/workflows/r5-044-ios-artifact-readout.yml
+ - .github/scripts/read-044-ios-artifact.cjs
+ - .github/scripts/read-044-ios-artifact.py
+ - .github/scripts/044-ios-metadata-policy.json
+ - .github/scripts/verify-ci-source.cjs
+ - .github/tests/044-ios-artifact-readout.test.cjs
+ - .github/tests/test_044_ios_artifact_readout.py
+
+permissions:
+ contents: read
+ actions: read
+
+concurrency:
+ group: r5-fixed-completed-044-ios-artifact-readout
+ cancel-in-progress: false
+
+jobs:
+ readout:
+ if: ${{ github.repository == 'KeeperCommunity/bitcoin-keeper' && github.event_name == 'push' && github.ref == 'refs/heads/codex/r5-044-artifact-readout-preparation-20261023' }}
+ runs-on: macos-15
+ timeout-minutes: 5
+ steps:
+ - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6
+ with:
+ ref: ${{ github.sha }}
+ persist-credentials: false
+ - run: node .github/scripts/verify-ci-source.cjs
+ - uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8
+ with:
+ script: await require('./.github/scripts/read-044-ios-artifact.cjs').run({ github, context, core })
+ - if: always()
+ run: node .github/scripts/verify-ci-source.cjs
diff --git a/.github/workflows/r5-23f-artifact-readout.yml b/.github/workflows/r5-23f-artifact-readout.yml
new file mode 100644
index 0000000000..50e6e557d2
--- /dev/null
+++ b/.github/workflows/r5-23f-artifact-readout.yml
@@ -0,0 +1,36 @@
+name: Read fixed completed 23f Android receipt
+
+on:
+ push:
+ branches: [codex/r5-23f-artifact-readout]
+ paths:
+ - .github/workflows/r5-23f-artifact-readout.yml
+ - .github/scripts/read-23f-native-artifact.cjs
+ - .github/scripts/read-23f-android-artifact.py
+ - .github/tests/23f-artifact-readout.test.cjs
+ - .github/tests/test_23f_artifact_readout.py
+
+permissions:
+ contents: read
+ actions: read
+
+concurrency:
+ group: r5-fixed-completed-23f-artifact-readout
+ cancel-in-progress: false
+
+jobs:
+ readout:
+ if: github.repository == 'KeeperCommunity/bitcoin-keeper' && github.event_name == 'push' && github.ref == 'refs/heads/codex/r5-23f-artifact-readout'
+ runs-on: ubuntu-24.04
+ timeout-minutes: 5
+ steps:
+ - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6
+ with:
+ ref: ${{ github.sha }}
+ persist-credentials: false
+ - run: node .github/scripts/verify-ci-source.cjs
+ - uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8
+ with:
+ script: await require('./.github/scripts/read-23f-native-artifact.cjs').run({ github, context, core })
+ - if: always()
+ run: node .github/scripts/verify-ci-source.cjs
diff --git a/.github/workflows/r5-7158-android-startup-readout.yml b/.github/workflows/r5-7158-android-startup-readout.yml
new file mode 100644
index 0000000000..c554f9fde4
--- /dev/null
+++ b/.github/workflows/r5-7158-android-startup-readout.yml
@@ -0,0 +1,36 @@
+name: Read fixed 7158 Android startup observations
+
+on:
+ push:
+ branches: [codex/r5-7158-android-startup-readout-r2-20261024]
+ paths:
+ - .github/workflows/r5-7158-android-startup-readout.yml
+ - .github/scripts/read-7158-android-startup-artifact.cjs
+ - .github/scripts/read-7158-android-startup-artifact.py
+ - .github/tests/7158-android-startup-readout.test.cjs
+ - .github/tests/test_7158_android_startup_readout.py
+
+permissions:
+ contents: read
+ actions: read
+
+concurrency:
+ group: r5-fixed-7158-android-startup-readout
+ cancel-in-progress: false
+
+jobs:
+ readout:
+ if: github.repository == 'KeeperCommunity/bitcoin-keeper' && github.event_name == 'push' && github.ref == 'refs/heads/codex/r5-7158-android-startup-readout-r2-20261024'
+ runs-on: ubuntu-24.04
+ timeout-minutes: 5
+ steps:
+ - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6
+ with:
+ ref: ${{ github.sha }}
+ persist-credentials: false
+ - run: node .github/scripts/verify-ci-source.cjs
+ - uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8
+ with:
+ script: await require('./.github/scripts/read-7158-android-startup-artifact.cjs').run({ github, context, core })
+ - if: always()
+ run: node .github/scripts/verify-ci-source.cjs
diff --git a/.github/workflows/r5-bea-android-artifact-readout.yml b/.github/workflows/r5-bea-android-artifact-readout.yml
new file mode 100644
index 0000000000..5380ab3599
--- /dev/null
+++ b/.github/workflows/r5-bea-android-artifact-readout.yml
@@ -0,0 +1,36 @@
+name: Read fixed bea Android observations
+
+on:
+ push:
+ branches: [codex/r5-bea-android-artifact-readout-20261024]
+ paths:
+ - .github/workflows/r5-bea-android-artifact-readout.yml
+ - .github/scripts/read-bea-android-artifact.cjs
+ - .github/scripts/read-bea-android-artifact.py
+ - .github/tests/bea-android-artifact-readout.test.cjs
+ - .github/tests/test_bea_android_artifact_readout.py
+
+permissions:
+ contents: read
+ actions: read
+
+concurrency:
+ group: r5-fixed-bea-android-observation-readout
+ cancel-in-progress: false
+
+jobs:
+ readout:
+ if: github.repository == 'KeeperCommunity/bitcoin-keeper' && github.event_name == 'push' && github.ref == 'refs/heads/codex/r5-bea-android-artifact-readout-20261024'
+ runs-on: ubuntu-24.04
+ timeout-minutes: 5
+ steps:
+ - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6
+ with:
+ ref: ${{ github.sha }}
+ persist-credentials: false
+ - run: node .github/scripts/verify-ci-source.cjs
+ - uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8
+ with:
+ script: await require('./.github/scripts/read-bea-android-artifact.cjs').run({ github, context, core })
+ - if: always()
+ run: node .github/scripts/verify-ci-source.cjs
diff --git a/.github/workflows/r5-current-android-artifact-readout.yml b/.github/workflows/r5-current-android-artifact-readout.yml
new file mode 100644
index 0000000000..078379a555
--- /dev/null
+++ b/.github/workflows/r5-current-android-artifact-readout.yml
@@ -0,0 +1,37 @@
+name: Read exact completed current Android metadata bytes
+
+on:
+ push:
+ branches: [codex/r5-current-android-artifact-byte-readout-20261022]
+ paths:
+ - .github/workflows/r5-current-android-artifact-readout.yml
+ - .github/scripts/read-current-android-artifact.cjs
+ - .github/scripts/read-current-android-artifact.py
+ - .github/scripts/current-android-metadata-policy.json
+ - .github/tests/current-android-artifact-readout.test.cjs
+ - .github/tests/test_current_android_artifact_readout.py
+
+permissions:
+ contents: read
+ actions: read
+
+concurrency:
+ group: r5-fixed-completed-1bc-android-artifact-readout
+ cancel-in-progress: false
+
+jobs:
+ readout:
+ if: ${{ github.repository == 'KeeperCommunity/bitcoin-keeper' && github.event_name == 'push' && github.ref == 'refs/heads/codex/r5-current-android-artifact-byte-readout-20261022' }}
+ runs-on: macos-15
+ timeout-minutes: 5
+ steps:
+ - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6
+ with:
+ ref: ${{ github.sha }}
+ persist-credentials: false
+ - run: node .github/scripts/verify-ci-source.cjs
+ - uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8
+ with:
+ script: await require('./.github/scripts/read-current-android-artifact.cjs').run({ github, context, core })
+ - if: always()
+ run: node .github/scripts/verify-ci-source.cjs
diff --git a/.github/workflows/r5-current-ios-artifact-readout.yml b/.github/workflows/r5-current-ios-artifact-readout.yml
new file mode 100644
index 0000000000..e7efab2f6b
--- /dev/null
+++ b/.github/workflows/r5-current-ios-artifact-readout.yml
@@ -0,0 +1,37 @@
+name: Read fixed completed 1bc iOS metadata bytes
+
+on:
+ push:
+ branches: [codex/r5-current-ios-artifact-byte-readout-20261022]
+ paths:
+ - .github/workflows/r5-current-ios-artifact-readout.yml
+ - .github/scripts/read-current-ios-artifact.cjs
+ - .github/scripts/read-current-ios-artifact.py
+ - .github/scripts/current-ios-metadata-policy.json
+ - .github/tests/current-ios-artifact-readout.test.cjs
+ - .github/tests/test_current_ios_artifact_readout.py
+
+permissions:
+ contents: read
+ actions: read
+
+concurrency:
+ group: r5-fixed-completed-1bc-ios-artifact-readout
+ cancel-in-progress: false
+
+jobs:
+ readout:
+ if: github.repository == 'KeeperCommunity/bitcoin-keeper' && github.event_name == 'push' && github.ref == 'refs/heads/codex/r5-current-ios-artifact-byte-readout-20261022'
+ runs-on: macos-15
+ timeout-minutes: 5
+ steps:
+ - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6
+ with:
+ ref: ${{ github.sha }}
+ persist-credentials: false
+ - run: node .github/scripts/verify-ci-source.cjs
+ - uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8
+ with:
+ script: await require('./.github/scripts/read-current-ios-artifact.cjs').run({ github, context, core })
+ - if: always()
+ run: node .github/scripts/verify-ci-source.cjs
diff --git a/.github/workflows/r5-d270-android-artifact-readout.yml b/.github/workflows/r5-d270-android-artifact-readout.yml
new file mode 100644
index 0000000000..c5244686d4
--- /dev/null
+++ b/.github/workflows/r5-d270-android-artifact-readout.yml
@@ -0,0 +1,36 @@
+name: Read fixed d270 Android observations
+
+on:
+ push:
+ branches: [codex/r5-d270-android-artifact-readout-20261024]
+ paths:
+ - .github/workflows/r5-d270-android-artifact-readout.yml
+ - .github/scripts/read-d270-android-artifact.cjs
+ - .github/scripts/read-d270-android-artifact.py
+ - .github/tests/d270-android-artifact-readout.test.cjs
+ - .github/tests/test_d270_android_artifact_readout.py
+
+permissions:
+ contents: read
+ actions: read
+
+concurrency:
+ group: r5-fixed-d270-android-observation-readout
+ cancel-in-progress: false
+
+jobs:
+ readout:
+ if: github.repository == 'KeeperCommunity/bitcoin-keeper' && github.event_name == 'push' && github.ref == 'refs/heads/codex/r5-d270-android-artifact-readout-20261024'
+ runs-on: ubuntu-24.04
+ timeout-minutes: 5
+ steps:
+ - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6
+ with:
+ ref: ${{ github.sha }}
+ persist-credentials: false
+ - run: node .github/scripts/verify-ci-source.cjs
+ - uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8
+ with:
+ script: await require('./.github/scripts/read-d270-android-artifact.cjs').run({ github, context, core })
+ - if: always()
+ run: node .github/scripts/verify-ci-source.cjs
diff --git a/.github/workflows/r5-d270-ios-artifact-readout.yml b/.github/workflows/r5-d270-ios-artifact-readout.yml
new file mode 100644
index 0000000000..de596a720b
--- /dev/null
+++ b/.github/workflows/r5-d270-ios-artifact-readout.yml
@@ -0,0 +1,36 @@
+name: Read fixed d270 iOS observations
+
+on:
+ push:
+ branches: [codex/r5-d270-ios-artifact-readout-20261024]
+ paths:
+ - .github/workflows/r5-d270-ios-artifact-readout.yml
+ - .github/scripts/read-d270-ios-artifact.cjs
+ - .github/scripts/read-d270-ios-artifact.py
+ - .github/tests/d270-ios-artifact-readout.test.cjs
+ - .github/tests/test_d270_ios_artifact_readout.py
+
+permissions:
+ contents: read
+ actions: read
+
+concurrency:
+ group: r5-fixed-d270-ios-observation-readout
+ cancel-in-progress: false
+
+jobs:
+ readout:
+ if: github.repository == 'KeeperCommunity/bitcoin-keeper' && github.event_name == 'push' && github.ref == 'refs/heads/codex/r5-d270-ios-artifact-readout-20261024'
+ runs-on: macos-15
+ timeout-minutes: 5
+ steps:
+ - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6
+ with:
+ ref: ${{ github.sha }}
+ persist-credentials: false
+ - run: node .github/scripts/verify-ci-source.cjs
+ - uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8
+ with:
+ script: await require('./.github/scripts/read-d270-ios-artifact.cjs').run({ github, context, core })
+ - if: always()
+ run: node .github/scripts/verify-ci-source.cjs
diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml
index 5d6104f0ae..da11d62014 100644
--- a/.github/workflows/test.yml
+++ b/.github/workflows/test.yml
@@ -6,11 +6,17 @@ on:
- sprint
- dev
- main
+ - release/2.6.3
+ - release/2.6.4
pull_request:
branches:
- sprint
+ - codex/r3-release-baseline-to-sprint
- dev
- main
+ - release/2.6.3
+ - release/2.6.4
+ types: [opened, synchronize, reopened, ready_for_review]
permissions:
contents: read
@@ -22,35 +28,186 @@ jobs:
steps:
- name: Checkout code
- uses: actions/checkout@v7
+ uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
+ with:
+ ref: ${{ github.event.pull_request.head.sha || github.sha }}
+ persist-credentials: false
- name: Set up Node.js
- uses: actions/setup-node@v7
+ uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7
with:
- node-version: '22'
+ node-version: '22.23.3'
+
+ - name: Verify exact event source before setup
+ run: node .github/scripts/verify-ci-source.cjs
+ # Root prepare invokes CocoaPods and writes a Mac SDK path; setup.sh can
+ # mask the pod failure. Keep JavaScript CI installation explicit on Linux.
- name: Install dependencies
- run: yarn install --ignore-scripts
+ run: |
+ npm install --global yarn@1.22.22 --ignore-scripts
+ yarn install --frozen-lockfile --ignore-scripts --non-interactive
+
+ - name: Apply repository dependency patches
+ run: node_modules/.bin/patch-package --error-on-fail
+
+ - name: Verify dependency inputs remain unchanged
+ run: |
+ git diff --exit-code HEAD -- package.json yarn.lock ios/Podfile.lock
+ node .github/scripts/verify-ci-source.cjs
- name: Run lint
run: npm run lint
continue-on-error: true
+ - name: Verify exact source after checks
+ if: always()
+ run: node .github/scripts/verify-ci-source.cjs
+
test:
name: Tests
runs-on: ubuntu-latest
steps:
- name: Checkout code
- uses: actions/checkout@v7
+ uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
+ with:
+ ref: ${{ github.event.pull_request.head.sha || github.sha }}
+ persist-credentials: false
- name: Set up Node.js
- uses: actions/setup-node@v7
+ uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7
with:
- node-version: '22'
+ node-version: '22.23.3'
+ - name: Verify exact event source before setup
+ run: node .github/scripts/verify-ci-source.cjs
+
+ # Match the explicit JavaScript setup used by the lint job.
- name: Install dependencies
- run: yarn install
+ run: |
+ npm install --global yarn@1.22.22 --ignore-scripts
+ yarn install --frozen-lockfile --ignore-scripts --non-interactive
+
+ - name: Apply repository dependency patches
+ run: node_modules/.bin/patch-package --error-on-fail
+
+ - name: Verify dependency inputs remain unchanged
+ run: |
+ git diff --exit-code HEAD -- package.json yarn.lock ios/Podfile.lock
+ node .github/scripts/verify-ci-source.cjs
+
+ - name: Set up Ruby for build-only release lane regressions
+ uses: ruby/setup-ruby@v1
+ with:
+ ruby-version: '3.3.8'
+
+ - name: Check USDT pause and retired build inputs
+ run: |
+ node --test tests/services/usdtPause.test.cjs tests/recovery/usdtBackup.test.cjs \
+ scripts/verify-channel-config.test.cjs ios/scripts/verify-retired-env.test.cjs
- name: Run tests
run: npm run test
+
+ # Frozen installation intentionally skips lifecycle scripts. The released
+ # recovery suite includes genuine encrypted Realm transaction tests.
+ - name: Install the Realm N-API binding for recovery tests
+ working-directory: node_modules/realm
+ run: ../.bin/prebuild-install --runtime napi --target 6
+
+ - name: Run recovery regression tests
+ run: npm run test:recovery
+
+ - name: Verify checked-out release version consistency
+ run: npm run version:check
+
+ - name: Run release and packaged-artifact tests
+ run: npm run test:release
+
+ - name: Test Android 16 KB static inspection
+ run: python3 -B -m unittest scripts/test_check_android_16kb.py
+
+ - name: Test Android reproducibility tools
+ run: python3 -B -m unittest scripts/test_compare_android_apks.py reproducibility/test_verify_android_inputs.py
+
+ - name: Verify exact source after checks
+ if: always()
+ run: node .github/scripts/verify-ci-source.cjs
+
+ automatic-backup-genuine:
+ name: Automatic backup native Realm and Relay
+ runs-on: ubuntu-latest
+ timeout-minutes: 25
+ env:
+ KEEPER_RELAY_FIXTURE_MODULE: ${{ github.workspace }}/.ci-relay/tests/support/automaticBackupHttpFixture.cjs
+ BACKUP_TEST_MONGO_URL: mongodb://127.0.0.1:27058
+ REALM_DISABLE_ANALYTICS: '1'
+
+ steps:
+ - name: Checkout Keeper source
+ uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
+ with:
+ ref: ${{ github.event.pull_request.head.sha || github.sha }}
+ persist-credentials: false
+
+ - name: Checkout pinned paired Relay fixture
+ uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
+ with:
+ repository: KeeperCommunity/Relay
+ ref: 838049e537e07eb646a2a0393eb969fba43d0739
+ path: .ci-relay
+ persist-credentials: false
+
+ - name: Set up Node 22
+ uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
+ with:
+ node-version: '22'
+
+ - name: Verify exact event source before setup
+ run: node .github/scripts/verify-ci-source.cjs --paired-relay
+
+ - name: Install Keeper dependencies without native app setup
+ run: |
+ yarn install --frozen-lockfile --ignore-scripts
+ yarn patch-package
+
+ - name: Install the real Realm N-API binding
+ working-directory: node_modules/realm
+ run: ../.bin/prebuild-install --runtime napi --target 6
+
+ - name: Install paired Relay dependencies
+ working-directory: .ci-relay
+ run: yarn install --frozen-lockfile --non-interactive --ignore-scripts
+
+ - name: Verify exact Keeper source after setup
+ run: node .github/scripts/verify-ci-source.cjs --paired-relay
+
+ - name: Start disposable loopback Mongo replica set
+ shell: bash
+ run: |
+ set -euo pipefail
+ docker run --detach --name keeper-backup-mongo \
+ --publish 127.0.0.1:27058:27058 \
+ mongo:7.0@sha256:9854f7139445d766a9523571d6f047530c45547460ffcf8259eb2bf4264632ca \
+ mongod --replSet keeperQA --bind_ip_all --port 27058
+ for attempt in {1..30}; do
+ if docker exec keeper-backup-mongo mongosh --port 27058 --quiet --eval \
+ 'try { rs.status(); } catch (e) { if (e.code !== 94) throw e; rs.initiate({_id: "keeperQA", members: [{_id: 0, host: "127.0.0.1:27058"}]}); } quit(db.hello().isWritablePrimary ? 0 : 1)'; then
+ exit 0
+ fi
+ sleep 2
+ done
+ docker logs keeper-backup-mongo
+ exit 1
+
+ - name: Run genuine automatic backup source matrix
+ run: npm run test:automatic-backup-genuine
+
+ - name: Verify exact source after checks
+ if: always()
+ run: node .github/scripts/verify-ci-source.cjs --paired-relay
+
+ - name: Remove disposable Mongo container
+ if: always()
+ run: docker rm --force keeper-backup-mongo || true
diff --git a/AGENTS.md b/AGENTS.md
index db639d5817..6947232bab 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -1,9 +1,52 @@
# Bitcoin Keeper: Codex workflow
-This repository uses a **ChatGPT → Codex Cloud → Codex Local (Mac)** workflow for coding tasks. The GitHub pull request is the durable handoff between stages. Do **not** rely on one agent having access to another agent's conversation, unpushed changes, machine, or installed tools.
+## Current R5 owner direction (22 October 2026)
+
+R5 and subsequent ordinary development/native validation run in Cloud. Use hosted macOS/Xcode for iOS and hosted Android development/emulator runners; the owner's personal Mac is not a prerequisite. Preserve genuine phone/signer checks separately. The older Local handoff format below remains a compatibility record for the existing gate, not a request for the owner's Mac.
+
+Candidate diagnostics are explicit read-only runs on the exact PR head. Add `keeper/native-diagnostic` only when scheduling the isolated integration candidate; the new workflow serializes iOS then Android and does not cancel active native work. Pre-merge diagnostic success never grants protected-base native acceptance. After approved installation, `Keeper release acceptance` is the default reusable worker route; `keeper/legacy-native` selects the serialized legacy startup fallback instead. New commits invalidate previous source evidence. Missing app feature/UI/backend/physical checks stay explicit and blocking where required.
+
+Never merge, promote a shared branch, release-sign, upload, distribute, deploy or publish without the owner's explicit approval. Draft PR creation and isolated branch pushes are preparation, not release approval. See `docs/r5-cloud-native-reconciliation.md` for source identities and outstanding acceptance.
+
+
+The default workflow is **Cloud code complete → hosted native validation → authorized physical checks → release review**. Before protected-base installation, run exact-candidate diagnostics and keep trusted acceptance fail-closed. The Local format below remains a compatibility fallback for an available authorized tester; the owner's personal Mac is not a prerequisite. Signing remains a separate approved action. Follow the [bootstrap adoption order](docs/cloud-bootstrap-preparation.md), including the later restacking of Phase A #7062. The GitHub pull request is the durable handoff between stages. Do **not** rely on one agent having access to another agent's conversation, unpushed changes, machine, or installed tools.
Repository: `KeeperCommunity/bitcoin-keeper`. Use `sprint` as the PR base unless the task explicitly specifies another base.
+## R5 and future releases: permanent cloud-first default
+
+Follow [the cloud release pipeline](docs/cloud-release-pipeline.md) for R5 and every
+subsequent release. Complete code and representative native acceptance on hosted
+iOS simulators/Android emulators, then assign remaining real-device checks to a
+named authorized tester. The release owner's personal Mac is not the default
+handoff destination. Keep the existing Local path below as the safe fallback
+until each hosted capability is reviewed, installed and verified; its current
+`Codex local handoff` / `State: NEEDS_LOCAL` syntax remains the gate protocol, not
+a claim that a Mac session is always required. In that handoff, put hosted work
+and run URLs in `Cloud checks`, and set `Local checks requested: NONE` only when
+trusted hosted evidence satisfies all requested native checks and no physical
+checks remain. Otherwise name the actual remaining checks and who can run them.
+
+Bootstrap depends on reviewed [PR #7060](https://github.com/KeeperCommunity/bitcoin-keeper/pull/7060);
+check its current state. The initial Phase A candidate is stacked on that PR.
+Its reusable `keeper-native-platform.yml` workflow is called by
+`keeper-release-acceptance.yml` automatically for future PRs targeting `sprint`;
+there is no R5-only release selector or manual copying step. The active R4 PR
+#7045 is excluded. Do not change R4 source, refs, private fixtures, Mac work,
+required gate or approval process. Installing #7060 and this infrastructure on
+`sprint` requires independent review and owner approval. Diagnostic candidate
+runs are not trusted acceptance for R5 or another source SHA.
+
+Record the exact source SHA, workflow run/attempt, both platforms' actual
+build/UI outcomes, safe artifact hashes and unresolved feature acceptance.
+A startup smoke or representative probe does not prove R5's deletion, recovery,
+upgrade or security matrix. Released R4 is already reconciled. Product checks must run on the exact combined
+R5 candidate; unresolved high-risk cases remain blocking. Phase B protected
+signing and distribution are **NOT IMPLEMENTED / NOT VERIFIED** until their
+separate reviewed workflow and exact-artifact controls are proven. Do not merge,
+sign, upload a beta, submit to a store or publish without explicit owner approval
+for that action and artifact. Passing CI provides none of these approvals.
+
## Codex Cloud: implement and prepare handoff
1. Work in a task-specific branch; investigate, implement, add or update tests, and run suitable checks (for example, `npm run test` and `npm run lint`). Report actual pass/fail results; do not claim a native simulator was run unless it really was.
@@ -25,11 +68,11 @@ Repository: `KeeperCommunity/bitcoin-keeper`. Use `sprint` as the PR base unless
Risks / known gaps:
```
-4. For app/code changes, `Required local checks` must list one or more of `IOS`, `ANDROID`, `HARDWARE` (comma-separated). Use both iOS and Android for cross-platform changes; add hardware for signer/device interactions. If no Mac tests are necessary, explain why, but the GitHub gate exempts only documentation and `.github/` changes. The handoff must name the actual PR head commit SHA after the final cloud push.
-5. Return the PR URL/number and state `NEEDS_LOCAL` to the user so ChatGPT can generate the exact local handoff prompt. Continue unrelated cloud tasks while waiting for a Mac.
+4. For app/code changes, `Required local checks` must list one or more of `IOS`, `ANDROID`, `HARDWARE` (comma-separated). Use both iOS and Android for cross-platform changes; add hardware for signer/device interactions. If a reported native or physical check is unnecessary, explain why, but the GitHub gate exempts only documentation and `.github/` changes. The handoff must name the actual PR head commit SHA after the final cloud push.
+5. Return the PR URL/number and actual platform `PASS`/`FAIL`/`NOT RUN` results for the current head. Use `NEEDS_LOCAL` for remaining native or physical requirements; successful trusted hosted evidence may satisfy `IOS`/`ANDROID` without a Mac login. Continue unrelated cloud tasks while remaining native or physical checks are scheduled. Follow [hosted native validation](docs/hosted-native-validation.md) for trust, bootstrap, scope and artifact limitations.
6. If a task needs only code review, explicitly state why local testing is not required rather than silently skipping it.
-## Codex Local (Mac): validate the PR
+## Legacy Local validation format (available authorized testers)
When given **"Validate Keeper PR #"**, first read the newest **Codex local handoff** section and inspect the PR head SHA.
@@ -80,10 +123,10 @@ A known critical defect is not eligible for post-release deferral. In particular
- `LOCAL_PASSED` means only the reported checks passed on the reported commit. It is **not** approval to merge, sign, distribute, upload to TestFlight/Play Store, or publish a release.
- Release operations require **explicit user approval** for the intended build, environment, and distribution channel.
- ChatGPT is the coordinator: when the user shares a PR or asks for a handoff/status, inspect the latest PR details and comments; then provide the next exact copy-and-paste prompt for Cloud or Local Codex. ChatGPT should not claim to know Codex's private session state or that the Mac is currently available.
-- If the Mac is offline, the state remains `NEEDS_LOCAL`; cloud work does not have to stop.
+- `NEEDS_LOCAL` is the legacy status label for outstanding checks; it does not require the owner's personal Mac. Continue hosted native work and name genuine physical-device dependencies explicitly.
## GitHub merge gate
-The `.github/workflows/keeper-local-validation.yml` workflow posts commit status `keeper/local-validation` for the current PR head SHA. For code changes, it remains failing until a repository collaborator posts a `Codex local validation` comment with `State: LOCAL_PASSED`, the **exact current commit SHA**, and `pass` for every platform named by `Required local checks`, except `HARDWARE` when the exact-SHA owner decision above defers unrun physical checks. New commits invalidate previous local sign-off and deferral. Documentation and `.github/`-only PRs are exempt from Mac tests.
+The `.github/workflows/keeper-local-validation.yml` workflow posts commit status `keeper/local-validation` for the current PR head SHA. For code changes, it requires a trusted exact-head Cloud handoff. Each required `IOS`/`ANDROID` platform needs either a genuine successful hosted native build **and** disposable UI smoke from the selected reviewed reusable or legacy hosted route, or a repository collaborator's exact-head `LOCAL_PASSED` report. A hosted run is trusted only when its workflow and complete `.github/native/` harness match the protected current base and the run's original base; PR-authored check names, comments and artifacts alone are not CI evidence. New or changed CI infrastructure must first be reviewed and merged before it can provide authoritative native evidence. The latest run/attempt must contain successful build and smoke steps for that platform; stale, skipped, cancelled, pending, build-only or untrusted evidence supplies no hosted pass. A latest explicit local failure remains blocking. `HARDWARE` still requires the existing local physical result or exact-SHA owner decision and subsequent honest local report above. New commits invalidate previous native evidence, local sign-off and deferral. Documentation and `.github/`-only PRs are exempt from native tests.
This workflow **reports** a status; to **enforce** it, repository administrators must require the `keeper/local-validation` commit status for merges to `sprint` in GitHub Rulesets or branch protection. Require the existing `Tests` CI check as well. This is a review/test gate, not a guarantee that tests were actually executed; agents must report actual results truthfully. Release signing, TestFlight, Play Store, and production deployment remain separate and require explicit user approval.
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
new file mode 100644
index 0000000000..d7cec89098
--- /dev/null
+++ b/CONTRIBUTING.md
@@ -0,0 +1,128 @@
+# Contributing to Bitcoin Keeper
+
+Contributions are welcome through forks and pull requests. Keeper
+maintainers are responsible for code and security review, assessing privacy risks,
+deciding whether to accept changes, and controlling merges and public releases.
+Passing automated checks or submitting a working build does not constitute approval.
+
+## Set up a local workspace
+
+Fork this repository on GitHub and clone your fork for contributions. You do not
+need write access to the Keeper repository or production credentials. Follow the
+[local development guide](dev/local-backend/README.md) for tool versions, Docker
+backend setup, Android Studio/Xcode builds and troubleshooting. Docker runs the
+backend; native SDKs and the mobile app run on your host.
+
+The [SigningServer source](https://github.com/KeeperCommunity/SigningServer) is
+public and can be cloned, installed, built, tested and contributed to on its own.
+The full Docker app/backend setup uses the public
+[Relay](https://github.com/KeeperCommunity/Relay) and SigningServer sources;
+it requires no repository invitation. Optional private development resources
+follow a separate [access process](dev/local-backend/ACCESS.md). Access approval
+is separate from acceptance of contributed code.
+
+The guide's [capability table](dev/local-backend/README.md#what-works-locally) lists
+supported local flows and unavailable integrations. The
+[verification record](dev/local-backend/VERIFICATION.md) distinguishes tested
+behavior from failures and untested platforms. Start with disposable testnet
+wallets. Store accounts, release signing keys and production backend access are
+not prerequisites for contributing.
+
+## Develop a focused change
+
+1. Find an existing issue or describe the problem in a new issue. For a suspected
+ vulnerability, use the private process in [SECURITY.md](SECURITY.md) instead.
+2. Create a branch in your fork. Use the base branch associated with the issue;
+ if none is specified, use the repository's default development branch,
+ `sprint`. Do not assume a release tag includes every unreleased feature.
+3. Capture the change's scope and acceptance criteria using the repository's
+ OpenSpec workflow. The CLI is included in the locked development dependencies:
+
+ ```sh
+ yarn openspec new change your-change-name
+ yarn openspec status --change your-change-name
+ yarn openspec instructions proposal --change your-change-name
+ ```
+
+ Follow the artifact instructions for proposal, specs, design and tasks. Read
+ [OpenSpec configuration](openspec/config.yaml); for UI changes, also read
+ [DESIGN.md](DESIGN.md). The repository's
+ [change-engineer workflow](.github/agents/change-engineer.agent.md) describes
+ planning, implementation and archiving. Respect any explicit repository-owner
+ restrictions on committing, pushing or publishing when using coding agents.
+4. Implement the agreed scope, reuse existing components and keep unrelated
+ formatting, dependency upgrades, feature reconciliation and version bumps out
+ of the change. Maintainers coordinate version numbers and the
+ [Android](android/fastlane/README.md) and [iOS](ios/fastlane/README.md) release
+ workflows separately from local development.
+
+`sprint` is the shared integration branch. Maintainers may use a temporary
+release branch while a specific app version is stabilized. Carry fixes made on
+that branch back into `sprint` so the shared development line stays current;
+then follow the reviewed `dev` to `main` release promotion used by the project.
+
+For backend development, bootstrap creates ignored checkouts under
+`dev/local-backend/.sources/`. Save backend work in a branch/patch and submit it to
+the appropriate backend repository; an app PR does not include those ignored
+edits. Changes to packaged adapters must update the corresponding SHA-256 entries
+in `sources.lock.json` and be verified from freshly prepared sources. Do not
+package a generated checkout, database or signing volume in a PR.
+
+## Test and report the result
+
+Run checks relevant to the changed behavior. These commands run from the app root:
+
+| Change | Checks |
+| --- | --- |
+| App logic | `yarn test --runInBand` (or the relevant Jest test paths) and `yarn lint` |
+| User flow or native code | Build the affected development app and exercise the acceptance scenarios; use/update relevant Maestro flows under `flows/` |
+| Local backend/bootstrap | `python3 -B -m unittest discover -s dev/local-backend -p 'test_*.py'` and `./dev/local-backend/dev verify` |
+| Persistence or isolation | `./dev/local-backend/verify-local.sh --persistence --boundaries` on a disposable, otherwise idle Compose project |
+| OpenSpec | `yarn openspec validate your-change-name --strict` |
+
+Shared mobile changes should be checked on both Android and iOS. If a platform,
+hardware device or integration is unavailable, say so; maintainers decide what
+additional testing is required before acceptance. A local backend smoke test does
+not validate recovery, transaction signing or every mobile feature.
+
+Report the commands, commit, platform/device, actual results and relevant redacted
+evidence. Keep **passed**, **failed/blocked** and **not run** separate. Describe
+existing failures rather than hiding them or reporting an unexecuted check as a
+pass. Screenshots can support manual verification but do not turn a failed
+automated assertion into a passing automated test.
+
+## Submit and review
+
+Open a pull request from your fork and complete the supplied template. Link the
+issue and OpenSpec artifacts, explain the behavior change and provide the test
+results. Review the diff before submission: exclude local environment files,
+generated dependencies, databases, keys, wallet backups and signing credentials.
+Use [SECURITY.md](SECURITY.md) for private vulnerability details.
+
+Keeper maintainers review correctness, product fit, security/privacy, dependencies
+and test evidence. They may request revisions or additional tests, and decide
+whether a change is accepted. Only authorized maintainers merge and release
+official builds. Contributors do not need release permissions to participate.
+
+Copilot code review is requested automatically for pull requests targeting
+`sprint`. Read its actual comments and check each claim against the changed code
+and relevant tests. Fix valid findings or explain why a comment does not apply
+before requesting final human review. One developer approval remains the code
+review gate. GitHub requests Ben, Utkarsh, and Parsh when a PR is ready for review;
+any one can provide that approval. For changes to product behavior,
+UX, or copy, the product owner
+records separate product signoff in the PR discussion. A PR author's product
+signoff does not count as GitHub's required developer approval.
+
+Some existing CI checks use maintainer-managed services or secrets. If a check is
+unavailable on a fork PR, report it in the PR so maintainers can arrange review;
+do not request production secrets or treat an unavailable check as passing.
+This document defines review responsibilities; it does not claim that GitHub
+branch protection or approval rules have been configured or verified.
+
+GitHub runs app tests and separate public backend/bootstrap checks. The existing Electrum/wallet integration
+tests use public testnet nodes and fee services; an internet connection is needed.
+Coverage, where generated, measures the configured Electrum/wallet source
+directories, not every app screen. SonarCloud analysis on the development branch
+is deferred; passing tests are not a security analysis pass. See [CI notes](dev/local-backend/CI.md)
+for the branch-specific checks, deferred analysis work and evidence limits.
diff --git a/Gemfile b/Gemfile
index 18850d8fac..e9acfb67c1 100644
--- a/Gemfile
+++ b/Gemfile
@@ -2,10 +2,10 @@ source 'https://rubygems.org'
# You may use http://rbenv.org/ or https://rvm.io/ to install and use this version
ruby '>= 2.6.10'
# Exclude problematic versions of cocoapods and activesupport that causes build failures.
-gem 'cocoapods', '>= 1.13', '!= 1.15.0', '!= 1.15.1'
+gem 'cocoapods', '1.16.2'
gem 'activesupport', '>= 6.1.7.5', '!= 7.1.0'
gem "fastlane", "~> 2.225.0"
-gem 'xcodeproj', '< 1.26.0'
+gem 'xcodeproj', '1.27.0'
gem 'concurrent-ruby', '< 1.3.4'
diff --git a/Gemfile.lock b/Gemfile.lock
index 1dabd56760..4437d10ee3 100644
--- a/Gemfile.lock
+++ b/Gemfile.lock
@@ -42,10 +42,10 @@ GEM
base64 (0.2.0)
bigdecimal (3.1.6)
claide (1.1.0)
- cocoapods (1.15.2)
+ cocoapods (1.16.2)
addressable (~> 2.8)
claide (>= 1.0.2, < 2.0)
- cocoapods-core (= 1.15.2)
+ cocoapods-core (= 1.16.2)
cocoapods-deintegrate (>= 1.0.3, < 2.0)
cocoapods-downloader (>= 2.1, < 3.0)
cocoapods-plugins (>= 1.0.0, < 2.0)
@@ -59,8 +59,8 @@ GEM
molinillo (~> 0.8.0)
nap (~> 1.0)
ruby-macho (>= 2.3.0, < 3.0)
- xcodeproj (>= 1.23.0, < 2.0)
- cocoapods-core (1.15.2)
+ xcodeproj (>= 1.27.0, < 2.0)
+ cocoapods-core (1.16.2)
activesupport (>= 5.0, < 8)
addressable (~> 2.8)
algoliasearch (~> 1.0)
@@ -226,7 +226,7 @@ GEM
multi_json (1.15.0)
multipart-post (2.4.1)
mutex_m (0.2.0)
- nanaimo (0.3.0)
+ nanaimo (0.4.0)
nap (1.1.0)
naturally (2.2.1)
netrc (0.11.0)
@@ -241,7 +241,7 @@ GEM
trailblazer-option (>= 0.1.1, < 0.2.0)
uber (< 0.2.0)
retriable (3.1.2)
- rexml (3.2.6)
+ rexml (3.4.4)
rouge (2.0.7)
ruby-macho (2.5.1)
ruby2_keywords (0.0.5)
@@ -271,13 +271,13 @@ GEM
uber (0.1.0)
unicode-display_width (2.6.0)
word_wrap (1.0.0)
- xcodeproj (1.24.0)
+ xcodeproj (1.27.0)
CFPropertyList (>= 2.3.3, < 4.0)
atomos (~> 0.1.3)
claide (>= 1.0.2, < 2.0)
colored2 (~> 3.1)
- nanaimo (~> 0.3.0)
- rexml (~> 3.2.4)
+ nanaimo (~> 0.4.0)
+ rexml (>= 3.3.6, < 4.0)
xcpretty (0.3.0)
rouge (~> 2.0.7)
xcpretty-travis-formatter (1.0.1)
@@ -288,11 +288,14 @@ PLATFORMS
ruby
DEPENDENCIES
- cocoapods (>= 1.11.3)
+ activesupport (>= 6.1.7.5, != 7.1.0)
+ cocoapods (= 1.16.2)
+ concurrent-ruby (< 1.3.4)
fastlane (~> 2.225.0)
+ xcodeproj (= 1.27.0)
RUBY VERSION
ruby 3.3.0p0
BUNDLED WITH
- 2.5.6
+ 2.5.22
diff --git a/Readme.md b/Readme.md
index 3f1f9d298a..0db9aef789 100644
--- a/Readme.md
+++ b/Readme.md
@@ -55,11 +55,23 @@ Refer to platform-specific documentation for detailed setup requirements.
cd bitcoin-keeper
```
3. Install the project dependencies using Yarn:
- The prepare scripts will automatically install pods and nodify crypto-related packages for react-native
+ The prepare script configures the crypto-related React Native packages.
+ CocoaPods is an explicit iOS setup step; follow [CONTRIBUTING.md](CONTRIBUTING.md)
+ after dependency installation.
```shell
yarn install
```
+## Contributing and local backends
+
+See [CONTRIBUTING.md](CONTRIBUTING.md) for the contribution process and
+[the local development guide](dev/local-backend/README.md) for a reproducible
+backend setup using public [Relay](https://github.com/KeeperCommunity/Relay)
+and [SigningServer](https://github.com/KeeperCommunity/SigningServer) sources.
+The local stack uses disposable testnet fixtures and needs no production
+credentials. Keep native app builds on your host; the backend runs in Docker.
+Report suspected vulnerabilities through [private reporting](SECURITY.md).
+
## Build and Run
### Varients
diff --git a/android/app/build.gradle b/android/app/build.gradle
index e8ead00b0a..8c6fc44d1c 100644
--- a/android/app/build.gradle
+++ b/android/app/build.gradle
@@ -2,6 +2,13 @@ apply plugin: "com.android.application"
apply plugin: "com.facebook.react"
apply plugin: 'com.google.gms.google-services'
apply from: project(':react-native-config').projectDir.getPath() + "/dotenv.gradle"
+// react-native-config embeds every selected env key, even when JavaScript does not use it.
+// Check the resolved env map so direct Gradle builds cannot package retired credentials.
+def retiredCredentialKeys = ['GASFREE_API_KEY', 'GASFREE_API_SECRET',
+ 'LETS_EXCHANGE_API_KEY'].collectMany { [it, "RN_${it}"] }
+if (retiredCredentialKeys.any { project.ext.env.containsKey(it) }) {
+ throw new GradleException('Retired API credentials must not be included in an Android build')
+}
apply plugin: 'kotlin-android'
/**
@@ -98,8 +105,8 @@ android {
applicationId "io.hexawallet.keeper"
minSdkVersion rootProject.ext.minSdkVersion
targetSdkVersion rootProject.ext.targetSdkVersion
- versionCode 621
- versionName "2.3.15"
+ versionCode 627
+ versionName "2.6.4"
missingDimensionStrategy 'react-native-camera', 'general'
missingDimensionStrategy 'store', 'play'
multiDexEnabled true
@@ -115,12 +122,11 @@ android {
signingConfigs {
release {
- if (project.hasProperty('MYAPP_RELEASE_STORE_FILE')) {
- storeFile file(MYAPP_RELEASE_STORE_FILE)
- storePassword MYAPP_RELEASE_STORE_PASSWORD
- keyAlias MYAPP_RELEASE_KEY_ALIAS
- keyPassword MYAPP_RELEASE_KEY_PASSWORD
- }
+ // Release credentials belong in the build environment, never in Git.
+ storeFile file(System.getenv('KEEPER_ANDROID_KEYSTORE') ?: 'release.keystore')
+ storePassword System.getenv('STORE_PASSWORD')
+ keyAlias System.getenv('KEY_ALIAS')
+ keyPassword System.getenv('KEY_PASSWORD')
}
debug {
storeFile file('debug.keystore')
@@ -134,13 +140,16 @@ android {
signingConfig signingConfigs.debug
}
release {
- signingConfig signingConfigs.release
+ // Caution! In production, you need to generate your own keystore file.
+ // see https://reactnative.dev/docs/signed-apk-android.
+ // signingConfig signingConfigs.debug
minifyEnabled enableProguardInReleaseBuilds
proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
}
}
productFlavors {
production {
+ signingConfig signingConfigs.release
minSdkVersion rootProject.ext.minSdkVersion
applicationId "io.hexawallet.bitcoinkeeper"
targetSdkVersion rootProject.ext.targetSdkVersion
@@ -161,6 +170,15 @@ android {
}
dependencies {
+ // Portal's transitive JNA 5.14.0 has an 8 KB RELRO boundary even though
+ // its LOAD segments are 64 KB aligned. Keep classes and JNI on one AAR.
+ // 5.18.1 retains the 5.17 native fix and fixes the subsequent UniFFI
+ // Structure deadlock/concurrency regressions (JNA #1681 and #1686).
+ implementation('net.java.dev.jna:jna:5.18.1@aar') {
+ version { strictly '5.18.1' }
+ because 'Portal requires 16 KB JNA natives and the UniFFI Structure fixes'
+ }
+
// The version of react-native is set by the React Native Gradle Plugin
implementation project(':react-native-iap')
implementation 'com.google.mlkit:barcode-scanning:17.3.0'
diff --git a/android/app/src/debug/AndroidManifest.xml b/android/app/src/debug/AndroidManifest.xml
index 594604506c..fdb0c092e5 100644
--- a/android/app/src/debug/AndroidManifest.xml
+++ b/android/app/src/debug/AndroidManifest.xml
@@ -52,15 +52,6 @@
-
-
-
-
-
-
-
-
-
diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml
index de838aa93e..1b21a28af9 100644
--- a/android/app/src/main/AndroidManifest.xml
+++ b/android/app/src/main/AndroidManifest.xml
@@ -60,9 +60,19 @@
-
+
+
+
+
+
+
+
+
+
+
+
diff --git a/android/app/src/main/java/com/hexa_keeper/MainActivity.kt b/android/app/src/main/java/com/hexa_keeper/MainActivity.kt
index b9dd5e2ac9..c807d76e6e 100644
--- a/android/app/src/main/java/com/hexa_keeper/MainActivity.kt
+++ b/android/app/src/main/java/com/hexa_keeper/MainActivity.kt
@@ -8,6 +8,7 @@ import com.facebook.react.ReactActivity
import com.facebook.react.ReactActivityDelegate
import com.facebook.react.defaults.DefaultNewArchitectureEntryPoint.fabricEnabled
import com.facebook.react.defaults.DefaultReactActivityDelegate
+import com.swmansion.rnscreens.fragment.restoration.RNScreensFragmentFactory
class MainActivity : ReactActivity() {
@@ -17,6 +18,8 @@ class MainActivity : ReactActivity() {
DefaultReactActivityDelegate(this, mainComponentName, fabricEnabled)
override fun onCreate(savedInstanceState: Bundle?) {
+ // React Native owns screen state; discard stale native screen fragments on recreation.
+ supportFragmentManager.fragmentFactory = RNScreensFragmentFactory()
super.onCreate(savedInstanceState)
window.decorView.post {
diff --git a/android/fastlane/Fastfile b/android/fastlane/Fastfile
index 6765414875..6bfaee660d 100644
--- a/android/fastlane/Fastfile
+++ b/android/fastlane/Fastfile
@@ -15,6 +15,54 @@
default_platform(:android)
+def build_verified_production_android_artifacts!
+ sh("node", File.expand_path("../../scripts/release-version.cjs", __dir__), "release-check")
+ production_env = File.expand_path("../../.env.production", __dir__)
+ UI.user_error!("Missing reviewed .env.production") unless File.file?(production_env)
+ sh("node", File.expand_path("../../scripts/verify-channel-config.cjs", __dir__), production_env)
+ ENV['ENVFILE'] = production_env
+ store_password = ENV["STORE_PASSWORD"]
+ key_password = ENV["KEY_PASSWORD"]
+ key_alias = ENV["KEY_ALIAS"]
+ UI.user_error!("Missing Android release signing credentials") if [store_password, key_password, key_alias].any? { |value| value.to_s.empty? }
+ releaseFilePath = ENV["KEEPER_ANDROID_KEYSTORE"] || File.expand_path("../app/release.keystore", __dir__)
+ UI.user_error!("Missing Android release keystore") unless File.file?(releaseFilePath)
+ gradle(task: 'clean')
+ # Gradle must return the artifact path for this invocation.
+ Actions.lane_context.delete(SharedValues::GRADLE_AAB_OUTPUT_PATH)
+ gradle(
+ task: 'bundle',
+ build_type: 'productionRelease',
+ print_command: false,
+ properties: {
+ "android.injected.signing.store.file" => releaseFilePath,
+ "android.injected.signing.store.password" => store_password,
+ "android.injected.signing.key.alias" => key_alias,
+ "android.injected.signing.key.password" => key_password,
+ }
+ )
+ aab_path = Actions.lane_context[SharedValues::GRADLE_AAB_OUTPUT_PATH].to_s
+ UI.user_error!("Build did not return an AAB path") if aab_path.strip.empty?
+ Actions.lane_context.delete(SharedValues::GRADLE_APK_OUTPUT_PATH)
+ gradle(
+ task: 'assemble',
+ build_type: 'productionRelease',
+ print_command: false,
+ properties: {
+ "android.injected.signing.store.file" => releaseFilePath,
+ "android.injected.signing.store.password" => store_password,
+ "android.injected.signing.key.alias" => key_alias,
+ "android.injected.signing.key.password" => key_password,
+ }
+ )
+ apk_path = Actions.lane_context[SharedValues::GRADLE_APK_OUTPUT_PATH].to_s
+ UI.user_error!("Build did not return an APK path") if apk_path.strip.empty?
+ verifier = File.expand_path("../../scripts/verify-release-artifact.py", __dir__)
+ sh("python3", verifier, aab_path)
+ sh("python3", verifier, apk_path)
+ { aab: aab_path, apk: apk_path }
+end
+
platform :android do
desc "Push a new dev build to Slack"
lane :dev do
@@ -47,45 +95,17 @@ platform :android do
)
end
- desc "Push a new live build to Slack and internal track on Play Store"
+ desc "Build and verify production AAB and APK without uploading or notifying Slack"
+ lane :build_only do
+ build_verified_production_android_artifacts!
+ end
+
+ desc "Build explicitly versioned production artifacts and upload to Play internal testing"
lane :live do
- file_name = "../../.env"
- file_url = "https://raw.githubusercontent.com/bithyve/bitcoin-keeper-envs/live/app.live.env"
- auth_header = "Authorization: token #{ENV["GITHUB_ACCESS_TOKEN"]}"
- sh(
- "curl -H '#{auth_header}' -o '#{file_name}' -s '#{file_url}'",
- step_name: "curl -H '***' -o '#{file_name}' -s '#{file_url}'"
- )
- store_password = ENV["STORE_PASSWORD"]
- key_password = ENV["KEY_PASSWORD"]
- key_alias = ENV["KEY_ALIAS"]
- releaseFilePath = File.join(Dir.pwd, "../app", "release.keystore")
- bump_version_code()
- gradle(task: 'clean')
- gradle(
- task: 'bundle',
- build_type: 'productionRelease',
- print_command: false,
- properties: {
- "android.injected.signing.store.file" => releaseFilePath,
- "android.injected.signing.store.password" => store_password,
- "android.injected.signing.key.alias" => key_alias,
- "android.injected.signing.key.password" => key_password,
- }
- )
+ artifacts = build_verified_production_android_artifacts!
upload_to_play_store(
- track: 'internal'
- )
- gradle(
- task: 'assemble',
- build_type: 'productionRelease',
- print_command: false,
- properties: {
- "android.injected.signing.store.file" => releaseFilePath,
- "android.injected.signing.store.password" => store_password,
- "android.injected.signing.key.alias" => key_alias,
- "android.injected.signing.key.password" => key_password,
- }
+ track: 'internal',
+ aab: artifacts[:aab]
)
end
end
@@ -93,15 +113,21 @@ end
after_all do |lane|
versionCode = android_get_version_code()
- slack(message: "Build success :rocket:\nVersion Code: " + versionCode.to_s)
+ UI.message("Build success. Version Code: " + versionCode.to_s)
+ if lane.to_s.split.last != 'build_only' && ENV['KEEPER_NOTIFY_SLACK'] == '1'
+ slack(message: "Build success :rocket:\nVersion Code: " + versionCode.to_s)
end
+end
- error do |lane, exception|
+error do |lane, exception|
+ UI.error("Fastlane failed: " + exception.message.to_s)
+ if lane.to_s.split.last != 'build_only' && ENV['KEEPER_NOTIFY_SLACK'] == '1'
slack(
message: exception.message,
success:false
)
end
+end
lane :bump_version_code do
path = '../app/build.gradle'
diff --git a/android/fastlane/README.md b/android/fastlane/README.md
index a0074a4078..2e7a754656 100644
--- a/android/fastlane/README.md
+++ b/android/fastlane/README.md
@@ -40,7 +40,7 @@ Push a new dev build to Slack
[bundle exec] fastlane android live
```
-Push a new live build to Slack and internal track on Play Store
+Build explicitly versioned production artifacts and upload to Play internal testing
----
diff --git a/android/gradle.properties b/android/gradle.properties
index 4e6e2e1b48..2f15da72f1 100644
--- a/android/gradle.properties
+++ b/android/gradle.properties
@@ -36,10 +36,6 @@ reactNativeArchitectures=armeabi-v7a,arm64-v8a,x86,x86_64
# are providing them.
newArchEnabled=true
-MYAPP_RELEASE_STORE_FILE=release.keystore
-MYAPP_RELEASE_KEY_ALIAS=hexawallet
-MYAPP_RELEASE_STORE_PASSWORD=hexa@2021
-MYAPP_RELEASE_KEY_PASSWORD=hexa@2021
org.gradle.jvmargs=-Xmx4g -XX:MaxMetaspaceSize=2048m -XX:MaxMetaspaceSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8
# Use this property to enable or disable the Hermes JS engine.
diff --git a/android/gradle/wrapper/gradle-wrapper.properties b/android/gradle/wrapper/gradle-wrapper.properties
index d4081da476..a54add3199 100644
--- a/android/gradle/wrapper/gradle-wrapper.properties
+++ b/android/gradle/wrapper/gradle-wrapper.properties
@@ -1,6 +1,7 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.14.3-bin.zip
+distributionSha256Sum=bd71102213493060956ec229d946beee57158dbd89d0e62b91bca0fa2c5f3531
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
diff --git a/appcenter-pre-build.sh b/appcenter-pre-build.sh
index 6adc321a73..3705a26b9a 100644
--- a/appcenter-pre-build.sh
+++ b/appcenter-pre-build.sh
@@ -1,8 +1,19 @@
#!/usr/bin/env bash
# Creates an .env from ENV variables for use with react-native-config
+set -eu
+
+if [ -n "${RN_GASFREE_API_KEY+x}" ] || [ -n "${RN_GASFREE_API_SECRET+x}" ] || [ -n "${RN_LETS_EXCHANGE_API_KEY+x}" ]; then
+ printf "Retired API credentials must not be included in a mobile build\n" >&2
+ exit 1
+fi
+
ENV_WHITELIST=${ENV_WHITELIST:-"^RN_"}
printf "Creating an .env file with the following whitelist:\n"
printf "%s\n" $ENV_WHITELIST
set | egrep -e $ENV_WHITELIST | sed 's/^RN_//g' > .env
-printf "\n.env created with contents:\n\n"
-cat .env
\ No newline at end of file
+if grep -Eq '^(RN_)?(GASFREE_API_(KEY|SECRET)|LETS_EXCHANGE_API_KEY)=' .env; then
+ rm .env
+ printf "Retired API credentials must not be included in a mobile build\n" >&2
+ exit 1
+fi
+printf ".env created\n"
diff --git a/dev/local-backend/.env.example b/dev/local-backend/.env.example
new file mode 100644
index 0000000000..ed62df3b1f
--- /dev/null
+++ b/dev/local-backend/.env.example
@@ -0,0 +1,5 @@
+# Copy to .env only when changing the defaults. No secrets required.
+COMPOSE_PROJECT_NAME=keeper-contributor
+KEEPER_RELAY_PORT=3000
+KEEPER_CHANNEL_PORT=4002
+KEEPER_SIGNING_PORT=3003
diff --git a/dev/local-backend/.gitignore b/dev/local-backend/.gitignore
new file mode 100644
index 0000000000..53a25a248d
--- /dev/null
+++ b/dev/local-backend/.gitignore
@@ -0,0 +1,3 @@
+.sources/
+.env
+__pycache__/
diff --git a/dev/local-backend/ACCESS.md b/dev/local-backend/ACCESS.md
new file mode 100644
index 0000000000..d9012a6548
--- /dev/null
+++ b/dev/local-backend/ACCESS.md
@@ -0,0 +1,24 @@
+# Optional private development resources
+
+The public [app](https://github.com/KeeperCommunity/bitcoin-keeper),
+[Relay](https://github.com/KeeperCommunity/Relay), and
+[SigningServer](https://github.com/KeeperCommunity/SigningServer) can be cloned,
+built, tested and contributed to without a Keeper invitation. The local Docker
+setup in [README.md](README.md) uses only those public repositories and
+disposable development identities. Production credentials are never needed.
+
+Some assigned work may need separate private repositories, provider dashboards,
+or test infrastructure. Ask the Keeper maintainer coordinating that work in your
+existing private conversation. Include your GitHub username, task and the exact
+resource needed. Do not post credentials or private access requests in a public
+issue. If you do not have a maintainer contact, use the
+[community contact](../../Readme.md#community) to reach one privately.
+
+Maintainers review the work and grant only the needed permissions after checking
+that the resource is ready to share. Approval covers the development access, not
+every local command or proposed code change. Record invitation acceptance and
+setup success in the internal development backlog. A contributor must use their
+own GitHub identity; maintainers must not share personal tokens.
+
+Security reports follow [SECURITY.md](../../SECURITY.md). Code acceptance,
+merges, production access and releases remain separate maintainer decisions.
diff --git a/dev/local-backend/CI.md b/dev/local-backend/CI.md
new file mode 100644
index 0000000000..66064cccd7
--- /dev/null
+++ b/dev/local-backend/CI.md
@@ -0,0 +1,54 @@
+# Contributor checks and analysis
+
+## Public backend CI
+
+The app's local backend workflow pins the public
+[Relay](https://github.com/KeeperCommunity/Relay) and
+[SigningServer](https://github.com/KeeperCommunity/SigningServer). It requires no
+private repository token or production credential. The default branch runs
+`Public backend setup` for the packaged adapter, bootstrap and disposable API
+checks. Earlier Linux backend runs failed while fetching the private Relay;
+those historical runs do not establish the result for this public pin.
+Code acceptance and releases remain maintainer decisions.
+
+## Active checks
+
+The default branch's existing `Run Tests` workflow runs app tests. The new
+`Public backend setup` workflow runs a separate public SigningServer adapter
+fetch/install/compile/test job and full local backend bootstrap, API,
+persistence and network-boundary checks. Neither job uses hosted credentials.
+Pull requests are checked against their proposed merge with the target branch.
+The development branch's `Contributor checks` workflow additionally publishes
+app test coverage; its results are tracked with PR #7014.
+
+Where generated, Jest's LCOV measures only the
+Electrum/wallet directories listed in `jest.config.js`; this is not whole-app
+coverage. Test success is evidence about the exercised cases, not a security
+clearance. Maintainers retain security review and acceptance responsibility.
+
+## SonarCloud deferred on 26 September 2026
+
+The project owner chose to defer SonarCloud on the development branch. That job
+was removed from its active workflow; app tests and an LCOV artifact remain there. `sonar-project.properties` is
+retained for future restoration, including the report path and quality-gate wait
+setting. No analysis or quality-gate pass is claimed, and no threshold has been
+lowered. GitHub protection settings were not changed; if a required Sonar status
+blocks merging, a maintainer must reconcile that setting with this decision.
+
+Before deferral, PR #7014's original and updated scanners failed while retrieving
+the pull request, before analysis. Public project metadata lists the repository
+as `bithyve/bitcoin-keeper`, while this PR lives in
+`KeeperCommunity/bitcoin-keeper`. This suggests a stale binding; an administrator
+needs to verify the exact access/configuration problem when analysis is restored.
+
+Deferred follow-up: inspect the project's Repository binding and GitHub app
+access, confirm project/organization keys and the secret, restore a pinned scanner
+that consumes LCOV and waits for its quality gate, then review the actual result.
+Keep analyzer credentials away from fork code. See Sonar's
+[repository binding instructions](https://docs.sonarsource.com/sonarqube-cloud/managing-your-projects/administering-your-projects/changing-binding).
+
+The last existing `sprint` analysis (17 September, commit `1adf4f663`) reported a
+failed quality gate: 0% new-code coverage, reliability rating C, 5.1% duplication
+and 0% reviewed security hotspots, using a September 2024 previous-version
+baseline. These are historical findings, not this PR's analysis. Deferral does
+not resolve them or replace Keeper's review.
diff --git a/dev/local-backend/HANDOFF.md b/dev/local-backend/HANDOFF.md
new file mode 100644
index 0000000000..8d2fe447e2
--- /dev/null
+++ b/dev/local-backend/HANDOFF.md
@@ -0,0 +1,61 @@
+# Independent contributor setup check
+
+Use this full-stack checklist with the public Relay and SigningServer sources.
+SigningServer-only work can follow
+[its independent setup](README.md#signingserver-without-relay-access). A maintainer's working Mac does not establish that the guide works
+on another developer's machine. This check does not authorize code acceptance or
+an official release.
+
+## Start clean
+
+1. Use an anonymous fresh app clone at the exact commit
+ supplied by the maintainer. Record `git rev-parse HEAD`. Do not copy another
+ developer's `.env`, databases, signing volume, account credentials or key files.
+2. Follow [README.md](README.md) for the toolchain and a
+ running Docker engine. If other Keeper projects are running, choose a distinct
+ Compose project and three unused ports as documented there.
+3. Run `./dev/local-backend/dev up`. It must prepare the pinned sources, start the
+ services and pass the local API checks without production credentials.
+4. Run `./dev/local-backend/verify-local.sh --persistence --boundaries` while no
+ other test is using this project's services. It recreates this project's
+ containers while retaining its volumes. Both persistence and rejection of
+ mainnet/hosted database settings must pass.
+5. Run `python3 -B -m unittest discover -s dev/local-backend -p 'test_*.py'`.
+6. Follow the native development build instructions for the platforms available
+ on this machine. iOS requires a Mac and Xcode. Record unavailable platforms as
+ untested, not passed.
+7. In the development app, create only a disposable local test fixture, complete
+ passcode/onboarding, reach Mobile Wallet and More Options, then relaunch and
+ unlock. Confirm that the app uses the local environment. Do not import a real
+ wallet or move real funds for this check.
+8. Stop the selected stack with `./dev/local-backend/dev stop`. Retain the volumes
+ for follow-up unless you intentionally choose to discard this test fixture.
+
+## Send the result privately to the coordinating maintainer
+
+Copy this summary into the existing private conversation. Maintainers keep it in
+the internal development backlog, not a new public administrative issue.
+
+```text
+App commit:
+Backend revisions (from dev/local-backend/sources.lock.json):
+Host OS and architecture:
+Docker/Compose, Node/Yarn, Python, Java and Xcode versions as applicable:
+Fresh clone and new project/volumes: yes/no (explain reused state)
+
+PASS:
+FAIL or BLOCKED (exact step and sanitized error):
+NOT TESTED:
+Guide corrections or undocumented steps needed:
+Native platform(s), simulator/emulator and onboarding/relaunch result:
+```
+
+Do not attach recovery words, private keys, authentication tokens, receipts,
+databases, captured emails or unreviewed full logs. Report security findings via
+[SECURITY.md](../../SECURITY.md). Ordinary reproducible user-facing defects can
+have public product issues after removing private details.
+
+Passing this checklist proves only the listed local setup and smoke checks.
+Purchases, push delivery, scheduled inheritance, hardware wallets, transaction
+signing and recovery correctness require their own acceptance evidence; see the
+[capability table](README.md#what-works-locally) and [verification record](VERIFICATION.md).
diff --git a/dev/local-backend/README.md b/dev/local-backend/README.md
new file mode 100644
index 0000000000..07d2fb2f5e
--- /dev/null
+++ b/dev/local-backend/README.md
@@ -0,0 +1,177 @@
+# Contributor development environment
+
+Run MongoDB, Keeper relay/channel and the testnet signing backend in Docker. Run Metro, Android Studio and Xcode on your host. Hosted development services have been retired; this setup needs no production backend or release credentials.
+
+For choosing a change, OpenSpec, test reporting and submitting a pull request, see
+[Contributing](../../CONTRIBUTING.md). Keeper maintainers own security review,
+acceptance, merges and official releases.
+
+## Prerequisites
+
+Both [Relay](https://github.com/KeeperCommunity/Relay) and
+[SigningServer](https://github.com/KeeperCommunity/SigningServer) are public.
+The full local Docker stack uses pinned revisions of these clean public sources
+and needs no repository invitation or production credentials. Optional private
+development resources have a separate [access process](ACCESS.md).
+
+- Git, Python 3.9+, Docker Engine with Compose v2.20+ (or a newer Compose release). On macOS use Docker Desktop or Colima; Linux can use Docker Engine. Start the engine before setup. Reserve about 3–4 GB for Docker and run native builds sequentially on a 16 GB Mac.
+- Anonymous GitHub access to both public backends. First setup downloads sources, container images and dependencies. Subsequent starts can reuse them.
+- Mobile: Node 20.19.4+ (Node 22 is a suitable supported baseline), Yarn Classic 1.22.22. Use the committed `yarn.lock`.
+- Android: Android Studio, JDK 17, SDK platform 36, build tools 35.0.0, NDK 27.1.12297006, CMake 3.22.1 and platform tools. Set `JAVA_HOME` and `ANDROID_HOME`. These versions come from this app's Gradle files.
+- iOS: macOS, Xcode with an iOS simulator runtime, Ruby 3.3.0 (`.ruby-version`) and Bundler. Use the root `Gemfile.lock` and `ios/Podfile.lock`.
+
+Earlier native validation on this Mac used Apple Silicon, Xcode 26.4, Node 25.9.0, Yarn 1.22.22, JDK 17 and Ruby 3.3.0. App tests also passed in GitHub Linux CI on Node 22. Full contributor setup on Intel Macs, Linux and Windows/WSL still needs independent verification; iOS builds require macOS. See [verification](VERIFICATION.md) for actual results and limitations.
+
+Native tool installation: [React Native 0.83 environment guide](https://reactnative.dev/docs/0.83/set-up-your-environment). Follow the repo-specific Android versions above when they differ from that guide.
+
+## First start
+
+Clone the public default branch:
+
+```sh
+git clone https://github.com/KeeperCommunity/bitcoin-keeper.git
+cd bitcoin-keeper
+```
+
+`dev up` fetches only public backend sources.
+
+From this app checkout's root:
+
+```sh
+./dev/local-backend/dev doctor
+./dev/local-backend/dev up
+./dev/local-backend/dev env
+yarn install --frozen-lockfile --non-interactive
+```
+
+`up` fetches the exact backend Git revisions, applies the local development adapters, builds containers, waits for readiness and runs real disposable API checks. `env` creates `.env.local` with restrictive permissions; it refuses to overwrite an existing different configuration. Existing `.env` and production files are not used or modified.
+
+## SigningServer without Relay access
+
+For SigningServer changes that do not need the mobile app or Relay, use the
+[public repository's instructions](https://github.com/KeeperCommunity/SigningServer#install-and-verify):
+
+```sh
+git clone https://github.com/KeeperCommunity/SigningServer.git
+cd SigningServer
+npm ci --ignore-scripts
+npm run compile
+npm test
+```
+
+Use Node 22 and report the exact tested commit. The server's unit tests use
+disposable local fixtures; they do not establish full app/backend integration or
+live signing behavior. To check this app's local adapter against its pinned
+public source, run `./dev/local-backend/dev prepare-signing` from the app clone.
+That command checks the adapter digests and applies it under ignored
+`.sources/signing/` without fetching Relay or starting Docker. Submit upstream
+SigningServer changes to its own repository. Full `dev up`, API checks and native
+app setup use the public Relay source.
+
+The JavaScript install hook only installs the repo's Node compatibility shims. Native dependencies are separate explicit steps below. It no longer runs CocoaPods on Android-only machines or rewrites `android/local.properties` with a Mac-specific path.
+
+If default ports 3000/4002/3003 are occupied, copy `dev/local-backend/.env.example` to `dev/local-backend/.env`, set distinct ports and a unique project name, then run the commands above. Port 8081 is reserved for Metro and cannot be assigned to a backend service. Use the same settings for every invocation. Multiple copies using the same Compose project name share containers and volumes; give each independent environment a unique name. `.env.local` must match those ports. Commands work from any directory except the native/Yarn commands, which assume the app root.
+
+## Android
+
+Create and boot an emulator through Android Studio. Use an ARM64 image on Apple Silicon, x86_64 on Intel/Linux. Use `adb devices` to select its serial. In one terminal at the app root:
+
+```sh
+yarn start
+```
+
+In another terminal:
+
+```sh
+./dev/local-backend/dev android-forward --serial YOUR_SERIAL
+ENVFILE=.env.local ./android/gradlew -p android app:assembleDevelopmentDebug -PreactNativeArchitectures=arm64-v8a --max-workers=2
+adb -s YOUR_SERIAL install -r android/app/build/outputs/apk/development/debug/app-development-debug.apk
+adb -s YOUR_SERIAL shell am start -n io.hexawallet.keeper.development/io.hexawallet.keeper.MainActivityDefault
+```
+
+Use `-PreactNativeArchitectures=x86_64` for an x86_64 emulator. `ANDROID_HOME` lets Gradle locate the SDK without a machine-specific committed `local.properties`. Android debug signing uses the disposable debug keystore already in the repository. No release signing key is needed.
+
+Keep `localhost` in `.env.local`: the app's Android cleartext policy allows it. `android-forward` connects the selected device to Metro and the configured backend ports; rerun after restarting the device. A physical Android device can use the same USB forwarding, but physical-device validation is a separate step.
+
+## iOS
+
+Select Ruby 3.3.0 with your Ruby manager, then from the app root:
+
+```sh
+bundle install
+(cd ios && BUNDLE_GEMFILE="$PWD/../Gemfile" RCT_NEW_ARCH_ENABLED=1 bundle exec pod install)
+xcrun simctl list devices available
+```
+
+Use the root Gemfile explicitly; the `ios` directory has a different Gemfile. CocoaPods may refresh checkout-path-dependent Hermes podspec checksums on initial installation; review any lockfile diff and do not treat dependency version changes as routine setup.
+
+For exact-source validation, use `pod install --deployment` and report a checksum mismatch as blocked instead of changing the lock incidentally. Before building, check for the shared `/tmp/envfile` selector: react-native-config gives it precedence over `ENVFILE`. Preserve any existing selector, coordinate with other builds, and proceed only when the effective file is this checkout's `.env.local`. Do not print configuration contents or delete another build's selector.
+
+Start `yarn start` in a separate terminal. You can inspect the workspace in Xcode (`ios/hexa_keeper.xcworkspace`, scheme `hexa_keeper_dev`). Use the command below for local builds so `ENVFILE` reaches every native build phase; simply clicking Run with the default scheme settings does not select `.env.local`:
+
+```sh
+ENVFILE=.env.local xcodebuild -workspace ios/hexa_keeper.xcworkspace -scheme hexa_keeper_dev -configuration Debug -destination 'platform=iOS Simulator,id=YOUR_SIMULATOR_UDID' -derivedDataPath ios/build/local-dev build
+xcrun simctl boot YOUR_SIMULATOR_UDID
+xcrun simctl install YOUR_SIMULATOR_UDID ios/build/local-dev/Build/Products/Debug-iphonesimulator/hexa_keeper_dev.app
+xcrun simctl launch YOUR_SIMULATOR_UDID io.hexawallet.hexakeeper.dev
+```
+
+Skip `simctl boot` if already booted. Keep simulator signing enabled so the app retains required entitlements. Store publishing/signing is separate from contributor development; see the release documentation.
+
+## Daily use and verification
+
+```sh
+./dev/local-backend/dev status
+./dev/local-backend/dev verify
+./dev/local-backend/dev logs
+./dev/local-backend/dev stop
+```
+
+`stop` removes containers but retains both named volumes. A later `up` restores the environment. To check persistence and configuration boundaries explicitly:
+
+```sh
+./dev/local-backend/verify-local.sh --persistence --boundaries
+```
+
+This recreates only the selected Compose project's containers, retains its volumes, and compares the same app record, revisioned backup and testnet signing public key. It verifies backup snapshot reads, transactional repair and rejection of stale revisions, and checks startup rejection of mainnet and hosted databases. Run when no other test is using that project. Ordinary `verify` does not restart containers. Every verify run adds a disposable app/signer fixture and synthetic encrypted backup records to the local database; no testnet coins are needed and no transaction is sent. Tokens and private keys are not printed.
+
+For native smoke testing: launch the development app, complete onboarding with a disposable wallet, unlock, open Wallets and More Options, and select testnet before testing network functionality. An API smoke pass does not prove wallet backup/recovery or a real signing transaction.
+
+## What works locally
+
+| Capability | Scope |
+| --- | --- |
+| Mongo, relay app records | Local persistence and API create/read checks |
+| Channel | Socket.IO connection handshake |
+| Server Key | V3 testnet setup, public-key derivation, valid/invalid 2FA and persistence |
+| Email | Captured inside signing volume at `/local-data/outbox.jsonl`; never delivered |
+| Push, purchases, Ask Keeper AI, faucet, price feeds | Unavailable; relay reports unsupported routes explicitly |
+| Scheduled signing / inheritance jobs | Disabled; timer-dependent flows are not covered |
+| Blockchain / Electrum | Separate mobile internet connection; not provided by this stack |
+| Legacy V2 Server Key | Not supported by this acceptance check; a V2 setup probe terminated the pinned upstream process (see verification notes) |
+
+The relay health field `signing: false` describes the relay, not the separate signing service. Use each service's health endpoint. No production service deployment is performed.
+
+## Sources, data and network boundaries
+
+`sources.lock.json` pins both public backend revisions and all local adapter SHA-256 checksums. Relay's public source includes local mode; its local Dockerfile adapter pins the Node base image. The Node, Mongo and nginx base images are pinned by digest. Backend dependency installs use frozen Yarn / npm lockfiles; OS packages in the relay build still use Debian repositories, so this is a reproducible development workflow, not a bit-for-bit reproducible image build.
+
+`adapters/signing/` contains the local-mode modifications for the pinned public SigningServer source; `adapters/relay/` pins its local build image. `.sources/` is generated and ignored. Bootstrap never overwrites an existing checkout; reruns preserve local backend edits. After editing a backend, rerun `up` to rebuild. To change pins/adapters, save your backend edits and move the generated checkout aside first. Do not deploy the development adapters to production.
+
+Only the gateway publishes host ports, all on `127.0.0.1`. Mongo, relay and signing share an internal network with no external egress; the gateway also has a host-access network. Compose waits on service health, following [Docker's startup ordering](https://docs.docker.com/compose/how-tos/startup-order/). Build-time dependency downloads still use the internet. Mobile native integrations are outside Docker; this is not a fully offline mobile mode.
+
+Mongo starts as the single-member `keeper-local` replica set required by the backup API's transactions. Its idempotent health check initializes a new local volume and waits for a writable primary. Existing local data volumes are retained; a standalone Mongo server cannot exercise transactional backup repair.
+
+Signing identities are randomly generated per signing volume and stored with restricted permissions. Use disposable test wallets. Keep the Mongo and signing volumes together: deleting signing keys invalidates their stored Server Key records. There is deliberately no automatic reset/delete command. `docker compose down --volumes` is destructive and not part of normal setup. Do not distribute databases, keys, email captures, `.env` files or native signing credentials with the source.
+
+## Troubleshooting
+
+- Docker unavailable: start Docker Desktop or Colima, then rerun `doctor`.
+- Backend source fetch failure: check the public pinned revision and network connection; no application secret is needed.
+- Stale source/adapter marker: save edits and move the relevant `.sources/relay` or `.sources/signing` directory aside. Bootstrap refuses to overwrite it.
+- Health succeeds but a feature fails: consult the capability table; cloud integrations are not restored by local startup.
+- App cannot reach local services: check `.env.local`, rebuild with `ENVFILE=.env.local`, and rerun Android port forwarding. Changing an env file requires a native rebuild.
+- Xcode reports a missing Node executable: inspect the ignored `ios/.xcode.env.local`; CocoaPods may have cached a version-specific path removed by a Node upgrade. Update its `NODE_BINARY` to your current executable and rebuild.
+- If several Metro servers are running, select the one for this checkout on each device. Android emulator defaults can bypass USB forwarding via `10.0.2.2`; set its debug server host to `localhost:8081` when using `adb reverse`.
+- iOS pod install fails under system Ruby: select the repo's Ruby version and root Bundler environment. Do not run an unrelated globally installed CocoaPods.
+- Memory pressure: build iOS and Android sequentially, limit Gradle workers, and shut down unused simulators without erasing their data.
diff --git a/dev/local-backend/VERIFICATION.md b/dev/local-backend/VERIFICATION.md
new file mode 100644
index 0000000000..a22f83ad33
--- /dev/null
+++ b/dev/local-backend/VERIFICATION.md
@@ -0,0 +1,303 @@
+# Contributor setup verification
+
+## R4 public Relay repin — 9 October 2026
+
+The current source lock pins public Relay
+`fb93c887631a6f567155a88f8e93d566f9d32a53` and public SigningServer
+`3cc7728c27328e7b0358d1f91a32d8d13feba90a`. Compared with the previous
+Relay pin, the follow-up changes signer lookup cleanup and its regression tests;
+it does not change the mobile backup request or response shape or the app's local
+Dockerfile adapter. Relay's exact-head build, disposable backup tests and source
+scans passed in [PR #3](https://github.com/KeeperCommunity/Relay/pull/3).
+
+In the existing anonymous app checkout, with an isolated HOME, disabled
+system/global Git configuration and interactive credential prompts,
+`dev prepare` fetched the new Relay commit and applied the unchanged adapter.
+It preserved the prepared public
+SigningServer checkout. All 11 bootstrap fixtures and Compose configuration
+validation passed. No local Docker build or native app run was repeated for this
+new pin. The earlier full-stack acceptance in
+[app PR #7030](https://github.com/KeeperCommunity/bitcoin-keeper/pull/7030)
+used the previous Relay pin and is historical evidence for that revision.
+
+## Sprint contributor package — 7 October 2026
+
+That sprint contributor package pinned public Relay
+`4c54e28738815546718775dbbdb39f0342c1b646` and public SigningServer
+`3cc7728c27328e7b0358d1f91a32d8d13feba90a`, with local adapter checksums in
+`sources.lock.json`. These are newer revisions than the earlier sprint PR #7014
+and main PR #7026. The source locks include Relay snapshot/repair and revision
+guards, compatible SigningServer dependency fixes, and digest-pinned image adapters.
+
+At app commit `19e079ae4486dacf1f79bf5e527384e608872977`, the
+[public-backend CI](https://github.com/KeeperCommunity/bitcoin-keeper/actions/runs/37627727798)
+passed both the SigningServer adapter and full local backend/bootstrap jobs.
+Those checks used these backend pins and exercised local snapshot/repair,
+A → B → A revisions, stale-repair rejection and persistence. Subsequent contributor
+changes have their own PR check results. Native app builds must be assessed
+against the selected app branch and platform separately.
+
+All dated sections below are historical evidence for the exact revisions named
+in those sections. They do not verify the 9 October source lock or attribute
+earlier private-source failures to the current public backend.
+
+## Public Relay transition — 7 October 2026
+
+- Clean-history [Relay](https://github.com/KeeperCommunity/Relay) is public at
+ `3e1a01bd2fd5381d8546229922c431ce50bedad4`; the legacy credential-bearing
+ Relay repository remains private. GitHub private vulnerability reporting is
+ enabled on the public repository.
+- An anonymous Relay clone at that exact commit passed a frozen Node 22 install,
+ compilation, 104 tests across nine suites with disposable MongoDB, current
+ source and full-history secret scans, and the runtime dependency audit. A
+ separate local Compose run served ready/local health, persisted a synthetic
+ app record and returned 503 for an unavailable hosted integration. Its
+ disposable containers and volumes were removed.
+- Sprint PR #7014's public Relay pin and public SigningServer pin were fetched with
+ Git credential helpers disabled. Six bootstrap regression tests passed. The
+ isolated full stack passed health, Socket.IO, unsupported-route behavior,
+ synthetic app record create/read, and V3 testnet signer authorization and
+ valid/invalid 2FA. No production credentials or funded wallets were used.
+- The optional persistence/boundary rerun stopped during Docker network
+ recreation with an engine input/output error after the host filled its disk.
+ That rerun is **not passed**. Free space was recovered, but no further Docker
+ build is being run while concurrent mobile QA uses the machine. CI on the
+ updated app commit and an independent developer/machine remain pending.
+- No new native mobile build, physical-device check, hosted provider delivery,
+ real signing transaction, or production deployment is claimed by this
+ contributor source-pin change.
+
+## Public SigningServer follow-up — 6 October 2026
+
+- The pinned SigningServer source is now the public
+ `KeeperCommunity/SigningServer` revision
+ `b82dc4f4a8f75676b70b12545d59c7906556a92b`. Its local adapter checksum
+ check and patch application pass. With Node 22, the adapted source passes
+ `npm ci --ignore-scripts`, `npm run compile` and `npm test` (2 suites, 108 tests).
+ The new independent GitHub SigningServer adapter job passes those same steps.
+- SigningServer's previously cancelled current-source readiness job was rerun at
+ its public head: current-source and history scans both pass on the rerun.
+ Its own public test workflow also passes. Dependency review remains open;
+ successful source scans and tests are not security acceptance.
+- A separate anonymous app checkout at app commit
+ `41e482ec97ebffb0beff43ed807b1205fb26ed8e` used an empty home and package
+ cache, disabled Git credential helpers and prompts, and copied no backend
+ source or environment files. `dev prepare` stopped at private Relay as expected.
+ `dev prepare-signing` fetched the public pin and applied its adapter without
+ Relay. `dev env` created a local-only file with mode `0600`; six bootstrap
+ regression tests passed. No full Docker stack or native build was possible
+ without Relay access.
+- A separate anonymous SigningServer clone, with an initially empty package
+ cache and no Git credentials, passed `npm ci --ignore-scripts`,
+ `npm run compile` and `npm test` (2 suites, 108 tests). The local anonymous app
+ Yarn install was stopped before completion when this Mac had about 1.5 GB free;
+ no local anonymous app JavaScript install or Jest pass is claimed. On the same
+ app commit, GitHub Linux CI passed frozen Yarn install, 17 Jest suites / 183
+ tests, strict active OpenSpec validation and LCOV upload. Its full backend job
+ passed bootstrap tests but failed fetching private Relay; later API/persistence
+ checks were skipped. These CI results do not establish an independent
+ full-stack checkout or native app acceptance.
+- Relay remains private and its publication is deferred. Safe CI Relay access,
+ independent full-stack setup, remaining dependency/security review and
+ maintainer acceptance remain open. No production deployment or credential
+ change was part of this follow-up.
+
+## Earlier evidence — 26–28 September 2026
+
+## Contributor handoff follow-up — 28 September 2026
+
+- Removed the public contributor-access issue template. Access instructions now
+ use private intake/internal tracking, matching the owner's policy. Added
+ `HANDOFF.md` for independent-machine setup and separate pass/fail/untested reports.
+- Five bootstrap regression tests, ten local documentation links and diff
+ whitespace checks: PASS.
+- Restarted this Mac's existing Colima profile and ran the documented `dev up`
+ against the same pinned sources, existing disposable project/volumes and build
+ caches. Health, Socket.IO, explicit unsupported-route failure, app create/read
+ and V3 testnet authorization/2FA: PASS.
+- `verify-local.sh --persistence --boundaries`: PASS, including retained app and
+ signing identity after recreation and rejection of mainnet/hosted databases.
+ This rerun is not a fresh-machine, native UI or transaction-signing test.
+- Published baseline app head `434cd7c405d8723b3c21c7ce6e82745b9b254517`, GitHub
+ run `36240719417`: app tests/coverage PASS; backend bootstrap unit tests PASS;
+ backend startup FAIL and subsequent integration checks SKIPPED. CI access is
+ still unresolved; these CI results apply to that baseline, not a later head.
+- Independent-machine verification, supported mobile Server Key acceptance,
+ backend readiness acceptance and safe CI source access remain open. No new
+ native build, full UI automation, provider-purchase or security-clearance pass
+ is claimed by this follow-up.
+
+## Readiness before private access
+
+The owner requires the same repository hygiene before private contributor access
+as before public publication. Backend cleanup is published in private draft PRs.
+This app now pins those updated revisions and its refreshed adapters have passed
+a fresh Docker setup on this Mac. Broader backend access still awaits history
+hygiene, credential handling, remaining dependency/security review and acceptance.
+Detailed findings remain private.
+
+## Fresh backend readiness integration
+
+This earlier private-backend readiness run used private Relay and SigningServer
+revisions, separate from the current public source pins. New app worktree, newly
+fetched backend sources and new Docker volumes; host image/package caches and
+existing GitHub read access reused. Project `keeper-readiness-proof` used ports
+23000/24002/23003, preserving other development projects.
+
+- Source fetch, adapter checksums/application and container builds: PASS.
+- All four service health checks, Socket.IO handshake, explicit unsupported-route
+ response and persisted app record create/read: PASS.
+- V3 testnet Server Key setup, authorization and valid/invalid 2FA: PASS.
+- Container recreation preserves the same app record and derived signer public
+ key: PASS. Mainnet/hosted database startup rejection: PASS.
+- Five bootstrap regression tests: PASS. Both backend test jobs and
+ current-source scans pass in their own CI;
+ their history scans remain failing, tracked privately.
+- Updated native development builds: iOS PASS after replacing a stale local
+ Node path; Android PASS after selecting the installed JDK 17 (976 tasks, 58
+ executed, 918 cached). Both builds embed the isolated 23000/24002/23003 backend
+ configuration. Native app source is the previously verified sprint integration;
+ this follow-up changes only backend pins/adapters and documentation.
+- Relay container compilation initially failed from memory exhaustion. Importing
+ only the existing Android Publisher v3 client reduced measured local compiler
+ memory to about 422 MB; the final image builds successfully with a 1 GB Node
+ heap. This retains the same provider API/library version.
+- Final image startup/API/V3/2FA and persistence/configuration-boundary checks:
+ PASS. The earlier iOS onboarding record survives recreation. No actual store
+ purchase, signing transaction or backup/recovery correctness test is claimed.
+- Native local smoke: iOS passcode/onboarding, Mobile Wallet and More Options
+ PASS using Maestro steps plus screenshot inspection. Initial Start New selector
+ failed despite the visible control; a visually guided tap continued the flow.
+ Relaunch/unlock after final backend restart PASS after handling the notification
+ prompt and repeated introductory/recovery-backup reminders; More Options assertion
+ passed. The original uninterrupted automation flows remain recorded as failures.
+- Android: disposable emulator user 10 preserves the prior user's app data. Fresh
+ passcode/onboarding, Mobile Wallet and More Options PASS using ADB assertions
+ plus a visually guided Next tap. The first attempt used the wrong Metro; after
+ selecting the matching checkout and resetting only this new user's disposable
+ fixture, the relay created the native app record with HTTP 200. UIAutomator could
+ not reach idle during the animated Next screen; that original assertion timed
+ out, while visual navigation and subsequent assertions passed. An earlier
+ attempt also overlapped the deliberate backend restart and was retried.
+- Native app records are confirmed in local MongoDB. This is onboarding/connectivity
+ evidence, not real signing, recovery, purchase or cloud-integration acceptance.
+- Full Linux Docker CI still lacks private-source access. Independent-machine
+ setup and Keeper security acceptance remain pending. These commits are draft
+ review inputs and are not an approval to deploy production backends.
+
+## Access policy and analysis update
+
+The owner chose approved contributor access and deferred SonarCloud on 26
+September. [Access instructions](ACCESS.md) and a GitHub request template now
+cover profile/context review, approved resource grants and setup confirmation.
+Local edits need no individual approval. No invitations or CI credentials were
+provisioned by this documentation change. SonarCloud is removed from active CI;
+its earlier failures below remain historical evidence, not a passing analysis.
+App tests and coverage remain active; private-source access still blocks backend
+CI. Independent contributor setup remains pending.
+
+This documentation/workflow update passed YAML and issue-template parsing,
+21 local documentation link checks, all five bootstrap tests and strict validation
+of both active OpenSpec changes. Native builds were not repeated for this update;
+the existing build results below apply to the unchanged app/native code.
+
+## Integration onto sprint
+
+The current PR is being integrated onto `sprint` commit `1adf4f663`; the release
+baseline results below are historical and are not a substitute for these checks.
+Fresh worktree and node_modules, host SDKs/caches reused:
+
+- Frozen Yarn installation: PASS.
+- Jest: 17 suites / 183 tests PASS; process exits normally after adding test-only
+ Electrum/HTTP teardown. LCOV is generated (coverage scope is the existing
+ Electrum/wallet directories).
+- Five bootstrap regression tests (including denied source access) and both active
+ OpenSpec changes: PASS.
+- Broad validation of all legacy OpenSpec specs: 17 pre-existing specs failed;
+ CI validates active changes, not these legacy documents.
+- Ruby lockfile constraints synchronized with Gemfile without gem version changes.
+- Initial CocoaPods install failed because `sprint` locked openiap 1.2.22 while
+ its existing react-native-iap 16.5.0 requires 3.4.0. Targeted `pod update openiap`
+ aligned NitroIap/NitroModules/openiap with existing JavaScript dependencies;
+ 142 pods installed successfully. The updated lockfile is part of this PR.
+- Fresh backend API, V3 authorization/2FA, persistence and configuration boundary
+ checks: PASS using this Mac's existing backend source access.
+- Android development build: PASS (976 tasks, 5m20s). Install over the disposable
+ development app, local backend configuration and testnet passcode-screen launch:
+ PASS. Fresh signed iOS Debug simulator build: PASS (142 pods). Simulator install and
+ launch to the passcode screen: PASS by screenshot inspection. These launch
+ checks are not complete onboarding, recovery or transaction tests.
+- GitHub Linux app job: PASS, 17 suites / 183 tests, active OpenSpec validation and
+ LCOV artifact upload. Measured line coverage is 57.37% (1451/2529) within the
+ existing configured source scope; no 80% coverage claim is made.
+- GitHub Linux bootstrap unit tests: PASS. Docker startup: FAIL during source
+ fetch because both backend repositories were private at the time and CI lacked
+ access. Current full-stack CI still requires private Relay access. This is not
+ a passing full-stack setup check.
+- SonarCloud: both the original and updated scanner failed before analysis; repository binding
+ still points at the old organization. See [CI notes](CI.md). No analysis pass
+ or security clearance is claimed.
+
+This integration preserves `sprint`'s app version fields; the separate 2.5.15
+release-version work is not imported or reverted by this contributor PR.
+
+## Test environment
+
+Fresh HTTPS clone of the published app tag `v2.5.15` (`e79e16b572d6e3472ac94500bf812d937bd89135`), plus this contributor setup change. New app dependency directories and newly fetched backend checkouts; no copied backend env files, databases or signing keys. Existing host SDKs, package caches and container image caches were reused.
+
+Apple Silicon Mac, macOS 26.6.2, Xcode 26.4/iOS 26.4 simulator, Node 25.9.0, Yarn 1.22.22, Python 3.9, Ruby 3.3.0/CocoaPods 1.15.2, JDK 17.0.19. Docker Engine 29.5.2/Compose 5.5.1 on Colima. Independent Compose project `keeper-contributor-clean`, newly generated volumes, loopback ports 13000/14002/13003. Existing developer/release services and data were preserved.
+
+## Results
+
+| Check | Result |
+| --- | --- |
+| Fetch pinned sources and verify/apply packaged adapters | PASS, both backends fetched from GitHub |
+| Advertised `dev up`, including API checks | PASS after correcting the smoke fixture to use current V3 Server Key APIs |
+| Mongo, relay, signing, gateway readiness | PASS |
+| Socket.IO polling handshake | PASS |
+| Relay create/read persisted app record | PASS |
+| Unsupported relay integration | PASS, explicit HTTP 503 |
+| V3 testnet Server Key setup and public-key format | PASS |
+| Invalid authorization, valid 2FA, invalid 2FA | PASS |
+| Container removal/recreation with retained volumes | PASS, same app record and derived signing public key |
+| Mainnet and hosted Mongo configuration rejection | PASS for relay and signing |
+| Actual container network/port inspection | PASS, backend network internal, no database port published, gateway bound only to loopback |
+| Rerun setup, existing env preservation, adapter tampering, unknown checkout preservation, duplicate ports | PASS, four regression tests plus real repeated bootstrap |
+| Fresh mobile Yarn install on the historical v2.5.15 acceptance tag | PASS with frozen mode at that source state. The source PR's `sprint` lock had unmatched lint-plugin selectors; the R4 combined candidate includes a corrected lock and uses frozen install, which passed in hosted diagnostic CI. |
+| Fresh CocoaPods installation | PASS, 142 pods; see path-dependent checksum note below |
+| Fresh Android `assembleDevelopmentDebug` | PASS, 976 tasks executed, 5m17s |
+| Android installed local configuration | PASS, development environment and alternate local backend ports verified in generated BuildConfig |
+| Android fresh install, passcode creation, onboarding, Mobile Wallet and More Options | PASS via ADB UI assertions and observed emulator controls |
+| Android local app record creation | PASS, HTTP 200 and database record confirmation |
+| Android Maestro driver | UNAVAILABLE, gRPC connection failed twice before flow execution; no Maestro pass claimed |
+| Fresh iOS development simulator build | PASS, signed Debug simulator app from fresh Pods/derived data |
+| iOS simulator launch, passcode creation/unlock and local relay connection | PASS, dev app launched; local app record created (two native app records total) |
+| iOS onboarding through Wallets | PASS by simulator screenshot inspection; Maestro text assertion failed despite the visible Mobile Wallet tile |
+| iOS More Options | PASS, simulator navigation and screenshot inspected |
+| Node/Mongo/nginx pinned image manifests | PASS, each includes Linux amd64 and arm64 |
+| Existing release version consistency | PASS, unchanged 2.5.15 / Android 622 / iOS 615 |
+
+Native apps use a separate Metro process on port 8082 during this acceptance run, preserving the existing developer's Metro on 8081. Android's dev-server host is set to localhost with device port 8081 forwarded to host 8082. Ordinary single-checkout instructions use port 8081.
+
+## Findings and limits
+
+- The pinned relay and signing backends acknowledge creation before their save callbacks complete. The check polls for record visibility for up to five seconds before dependent reads; it does not hide a rejected verification token or an unexpected response.
+- An exploratory legacy V2 Server Key setup returned success and then terminated its signing process. Its source uses a structured verifier schema but writes a string. This is an observed limitation of the pinned backend, not a verified production incident. Current app acceptance uses V3. Legacy V2 workflows remain outside the supported acceptance scope; this packaging change does not repair wallet/signing business logic.
+- Initial CocoaPods `--deployment` failed because the Hermes podspec embeds an absolute `HERMES_CLI_PATH`. A normal locked `pod install` refreshed only that podspec checksum to the new checkout path. Comparing old/new podspec JSON confirmed the path is the only difference. No dependency version changed. This generated lockfile difference is not part of the contributor source change.
+- Initial iOS UI scripts hit modal timing/selector failures, and one automated unlock was rejected. Retrying the same fixture PIN with waits succeeded. The XCUITest driver also needed a simulator restart after a failed connection; app data was preserved. The Mobile Wallet tile and Start New card were visible in screenshots when text assertions could not find them. These are recorded as automation limitations, not passes of the original complete flows; visual checks are explicitly distinguished from automated assertions.
+- React Native/third-party dependencies emit existing peer-dependency, export-resolution and native deprecation warnings. Build success is not a claim that those upstream warnings are resolved.
+- This proves a fresh checkout on this Mac, not a second physical machine. Intel/Linux/Windows, physical devices, cloud integrations, hardware wallets, real Server Key transactions, recovery correctness and scheduled inheritance flows remain unverified here. Recovery T-060 and store/source reconciliation are separate tasks.
+- Backend image digests and source pins constrain inputs; package caches and Debian package repositories prevent claiming a bit-identical image build.
+
+## Reproduce checks
+
+The earlier contributor OpenSpec change is not included in this checkout. Its
+validation is not a reproducible acceptance check for this source package.
+
+```sh
+./dev/local-backend/dev up
+./dev/local-backend/verify-local.sh --persistence --boundaries
+python3 -B -m unittest discover -s dev/local-backend -p test_keeper.py
+```
+
+The acceptance logs and emulator fixtures remain on the maintainer's machine outside the source package. Do not include local databases, generated signing identities, recovery material or captured emails in a source review or handoff archive.
diff --git a/dev/local-backend/adapters/relay/files/Dockerfile.local b/dev/local-backend/adapters/relay/files/Dockerfile.local
new file mode 100644
index 0000000000..285e1e8e18
--- /dev/null
+++ b/dev/local-backend/adapters/relay/files/Dockerfile.local
@@ -0,0 +1,12 @@
+FROM node:22-bookworm-slim@sha256:43ac6c60b8f89723f746e8a92ce91abd5017e627ce1ddfe4238355d3a30b772c
+WORKDIR /app
+RUN apt-get update && apt-get install -y --no-install-recommends git ca-certificates python3 make g++ && rm -rf /var/lib/apt/lists/*
+COPY package.json yarn.lock ./
+RUN yarn install --frozen-lockfile --non-interactive --ignore-scripts
+COPY tsconfig.json ./
+COPY src ./src
+COPY public ./public
+RUN yarn compile
+ENV NODE_ENV=development
+USER node
+CMD ["node", "dist/index.js"]
diff --git a/dev/local-backend/adapters/signing/files/.dockerignore b/dev/local-backend/adapters/signing/files/.dockerignore
new file mode 100644
index 0000000000..e8b30bfc29
--- /dev/null
+++ b/dev/local-backend/adapters/signing/files/.dockerignore
@@ -0,0 +1,9 @@
+.git
+.env*
+node_modules
+dist
+**/*.pem
+**/*.p12
+**/*.key
+logfile.log
+coverage
diff --git a/dev/local-backend/adapters/signing/files/Dockerfile.local b/dev/local-backend/adapters/signing/files/Dockerfile.local
new file mode 100644
index 0000000000..f14a93fd88
--- /dev/null
+++ b/dev/local-backend/adapters/signing/files/Dockerfile.local
@@ -0,0 +1,11 @@
+FROM node:22-bookworm-slim@sha256:43ac6c60b8f89723f746e8a92ce91abd5017e627ce1ddfe4238355d3a30b772c
+WORKDIR /app
+COPY package.json package-lock.json ./
+RUN npm ci --ignore-scripts
+COPY tsconfig.json ./
+COPY src ./src
+COPY scripts/local-entry.cjs ./scripts/local-entry.cjs
+RUN npm run compile && mkdir /local-data && chown node:node /local-data /app
+ENV NODE_ENV=development
+USER node
+CMD ["node", "scripts/local-entry.cjs"]
diff --git a/dev/local-backend/adapters/signing/files/scripts/local-entry.cjs b/dev/local-backend/adapters/signing/files/scripts/local-entry.cjs
new file mode 100644
index 0000000000..2795934ca9
--- /dev/null
+++ b/dev/local-backend/adapters/signing/files/scripts/local-entry.cjs
@@ -0,0 +1,14 @@
+// Local test keys are created once per Docker volume. Never print their values.
+const fs = require('node:fs');
+const crypto = require('node:crypto');
+const bip39 = require('bip39');
+if (process.env.LOCAL_DEV !== 'true' || process.env.ENVIRONMENT !== 'TEST') throw new Error('Local entry requires LOCAL_DEV and TEST');
+const file = '/local-data/secrets.json';
+if (!fs.existsSync(file)) {
+ const rsa = crypto.generateKeyPairSync('rsa', { modulusLength: 2048,
+ privateKeyEncoding: { type: 'pkcs1', format: 'pem' }, publicKeyEncoding: { type: 'spki', format: 'pem' } });
+ const secrets = { 'local-rsa-private': rsa.privateKey, 'local-rsa-public': rsa.publicKey };
+ for (const id of ['local-signer-v2', 'local-signer-v3', 'local-inheritance-v2', 'local-inheritance-v3']) secrets[id] = bip39.generateMnemonic(256);
+ fs.writeFileSync(file, JSON.stringify(secrets), { mode: 0o600, flag: 'wx' });
+}
+require('../dist/index.js');
diff --git a/dev/local-backend/adapters/signing/files/src/config.ts b/dev/local-backend/adapters/signing/files/src/config.ts
new file mode 100644
index 0000000000..1df0526542
--- /dev/null
+++ b/dev/local-backend/adapters/signing/files/src/config.ts
@@ -0,0 +1,100 @@
+import * as bitcoinJS from "bitcoinjs-lib";
+import dotenv from "dotenv";
+import { fetchSecrets } from "./utilities/secretManager";
+import { logger } from "./utilities/logger"
+import { WalletCredsVersion } from "./interfaces/wallet";
+
+const result = dotenv.config();
+
+if (result.error && process.env.LOCAL_DEV !== "true") {
+ throw result.error;
+}
+
+export enum SERVER_TYPE {
+ MAIN = "MAIN",
+ TEST = "TEST"
+}
+
+export enum DATABASE_TYPE {
+ DEV = "DEV",
+ PROD = "PROD"
+}
+
+class Config {
+ public LOCAL_DEV = process.env.LOCAL_DEV === "true";
+ public ENVIRONMENT: string = process.env.ENVIRONMENT;
+ public PORT: string = process.env.PORT || "3003";
+ public NETWORK: bitcoinJS.Network;
+ public HEXA_ID = process.env.HEXA_ID
+ public RELAY = process.env.RELAY
+
+ public INHERITANCE_KEY_REQUEST_THRESHOLD: number; // 30days(prod) / 5 mins(dev)
+ public INHERITANCE_KEY_REQUEST_TTL: number; // 3x of request threshold duration
+ public ADMIN_KEY: string = process.env.BIT_ADMIN_KEY;
+ public VERSION: string = process.env.VERSION;
+
+ public MAILER_CONFIG = {
+ SES_REGION: process.env.SES_REGION,
+ SOURCE_EMAIL: process.env.SES_SOURCE_EMAIL,
+ ACCESS_KEY_ID: process.env.SES_ACCESS_KEY_ID,
+ SECRET_ACCESS_KEY: process.env.SES_SECRET_ACCESS_KEY,
+ }
+
+ public DB_MODE = process.env.DB_MODE;
+ public DATABASE_NAME_V2: string = process.env.DATABASE_NAME_V2;
+ public DATABASE_SECRET_IDENTIFIER_V2: string = process.env.DATABASE_SECRET_IDENTIFIER_V2;
+ public PROJECT_ID: string = process.env.PROJECT_ID;
+ public MIN_POLICY_UPDATE_DELAY: number;
+
+ public MNEMONIC_IDENTIFIERS = {
+ [WalletCredsVersion.V2]: process.env.MNEMONIC_IDENTIFIER_V2,
+ [WalletCredsVersion.V3]: process.env.MNEMONIC_IDENTIFIER_V3,
+ };
+
+ public INHERITANCE_MNEMONIC_IDENTIFIERS = {
+ [WalletCredsVersion.V2]: process.env.INHERITANCE_MNEMONIC_IDENTIFIER_V2,
+ [WalletCredsVersion.V3]: process.env.INHERITANCE_MNEMONIC_IDENTIFIER_V3,
+ };
+
+ public RSA_PRV_KEY_IDENTIFIER: string = process.env.RSA_PRV_KEY_IDENTIFIER;
+ public RSA_PUB_KEY_IDENTIFIER: string = process.env.RSA_PUB_KEY_IDENTIFIER;
+ public RSA_PRV_KEY: string;
+ public RSA_PUB_KEY: string;
+
+ constructor() {
+ if (this.LOCAL_DEV) {
+ const db = new URL(process.env.LOCAL_DATABASE_URL || "");
+ if (this.ENVIRONMENT !== "TEST" || this.DB_MODE !== "DEV" ||
+ db.protocol !== "mongodb:" || !["mongo", "localhost", "127.0.0.1"].includes(db.hostname) ||
+ db.username || db.password || db.pathname !== "/keeper_signing_local") {
+ throw new Error("Local signing requires TEST, DEV and the isolated local database");
+ }
+ if (this.HEXA_ID !== "keeper-local-only") throw new Error("Local signing requires its own application credential");
+ }
+ this.configureNetwork();
+ }
+
+ public configureNetwork = () => {
+ if (this.ENVIRONMENT === SERVER_TYPE.MAIN) {
+ this.NETWORK = bitcoinJS.networks.bitcoin;
+ this.INHERITANCE_KEY_REQUEST_THRESHOLD = 2592000000 // 30 days in milliseconds
+ this.MIN_POLICY_UPDATE_DELAY = 1 * 7 * 24 * 60 * 60 * 1000 // 1 week in milliseconds
+ } else if (this.ENVIRONMENT === SERVER_TYPE.TEST) {
+ this.NETWORK = bitcoinJS.networks.testnet;
+ this.INHERITANCE_KEY_REQUEST_THRESHOLD = 300000 // 5 mins in milliseconds
+ this.MIN_POLICY_UPDATE_DELAY = 1 * 60 * 60 * 1000 // 1 hour in milliseconds
+ } else {
+ throw new Error("Please specify an apt environment(MAIN||TEST)");
+ }
+ this.INHERITANCE_KEY_REQUEST_TTL = (this.INHERITANCE_KEY_REQUEST_THRESHOLD / 1000) * 3
+ };
+
+ public initRSAKeys = async () => {
+ const [privResponse, pubResponse] = await fetchSecrets([this.RSA_PRV_KEY_IDENTIFIER, this.RSA_PUB_KEY_IDENTIFIER]);
+ this.RSA_PRV_KEY = privResponse[this.RSA_PRV_KEY_IDENTIFIER]
+ this.RSA_PUB_KEY = pubResponse[this.RSA_PUB_KEY_IDENTIFIER]
+ logger.info('RSA keys have been initialized')
+ }
+}
+
+export default new Config();
diff --git a/dev/local-backend/adapters/signing/local.patch b/dev/local-backend/adapters/signing/local.patch
new file mode 100644
index 0000000000..d13580b53a
--- /dev/null
+++ b/dev/local-backend/adapters/signing/local.patch
@@ -0,0 +1,132 @@
+diff --git a/src/databases/dbV2.ts b/src/databases/dbV2.ts
+index dc661dc..31b47a9 100644
+--- a/src/databases/dbV2.ts
++++ b/src/databases/dbV2.ts
+@@ -269,6 +269,13 @@ class DatabaseV2 {
+ }
+
+ public initializeConnection = async () => {
++ if (config.LOCAL_DEV) {
++ this.connection = mongoose.createConnection(process.env.LOCAL_DATABASE_URL, {
++ dbName: "keeper_signing_local", autoIndex: true,
++ });
++ await this.connection.asPromise();
++ return;
++ }
+ const [response] = await fetchSecrets(
+ [config.DATABASE_SECRET_IDENTIFIER_V2],
+ true
+@@ -288,6 +295,8 @@ class DatabaseV2 {
+ });
+ };
+
++ public isReady = () => this.connection?.readyState === 1;
++
+ public getSignerV2Model = (): mongoose.Model => {
+ return this.connection.model("Signer", this.signerV2);
+ };
+diff --git a/src/index.ts b/src/index.ts
+index 7e3a325..bee0b07 100644
+--- a/src/index.ts
++++ b/src/index.ts
+@@ -3,6 +3,7 @@ import express, { Express } from "express";
+ import morgan from "morgan";
+
+ import config from "./config";
++import dbV2 from "./databases/dbV2";
+ import { logger, unhandledLogger} from "./utilities/logger"
+ import { initializeCrons } from "./utilities/crons";
+ import { initializeRoutes } from "./routes/router";
+@@ -14,7 +15,7 @@ class SigningServer {
+ this.app = express();
+ this.configure();
+ this.invoke();
+- initializeCrons();
++ if (!config.LOCAL_DEV) initializeCrons();
+ config.initRSAKeys();
+ }
+
+@@ -24,6 +25,13 @@ class SigningServer {
+ this.app.use(morgan("combined", { stream: { write: message => logger.info(message.trim()) } }));
+ this.app.use(bodyParser.json());
+ this.app.use(bodyParser.urlencoded({ extended: true }));
++ if (config.LOCAL_DEV) {
++ this.app.get("/health", (_req, res) => {
++ const ready = dbV2.isReady() && !!config.RSA_PUB_KEY;
++ res.status(ready ? 200 : 503).json({ ready, mode: "local", network: "TESTNET",
++ capabilities: { signing: ready, emailDelivery: false, pushDelivery: false, scheduledJobs: false } });
++ });
++ }
+ this.app.use(initializeRoutes(this.app));
+ }
+
+diff --git a/src/services/mailing/mailer.ts b/src/services/mailing/mailer.ts
+index 9ab6b1d..3995234 100644
+--- a/src/services/mailing/mailer.ts
++++ b/src/services/mailing/mailer.ts
+@@ -1,5 +1,6 @@
+ import config from "../../config";
+ import moment from "moment";
++import { appendFileSync } from "fs";
+ import AWS from "aws-sdk";
+ import { EMAIL_TEMPLATES } from "./templates";
+
+@@ -65,7 +66,7 @@ const fetchEmailContentByType = (
+ )
+ .replace(
+ "{{server_url}}",
+- config.ENVIRONMENT === "MAIN"
++ config.LOCAL_DEV ? "http://localhost:3003" : config.ENVIRONMENT === "MAIN"
+ ? "https://sign.bithyve.com"
+ : "https://dev-sign.bithyve.com"
+ )
+@@ -109,5 +110,9 @@ export const sendEmails = (
+ },
+ },
+ };
++ if (config.LOCAL_DEV) {
++ appendFileSync("/local-data/outbox.jsonl", JSON.stringify({ capturedAt: new Date().toISOString(), ...params }) + "\n", { mode: 0o600 });
++ return Promise.resolve({ MessageId: "local-captured-not-delivered" });
++ }
+ return AWS_SES.sendEmail(params).promise();
+ };
+diff --git a/src/services/notifications/pushNotification.ts b/src/services/notifications/pushNotification.ts
+index 87e9d5c..477681d 100644
+--- a/src/services/notifications/pushNotification.ts
++++ b/src/services/notifications/pushNotification.ts
+@@ -85,6 +85,7 @@ export const pushIKNotification = async (
+ requestAutoApprovesIn?: number;
+ }
+ ) => {
++ if (config.LOCAL_DEV) { logger.info("Local mode: push delivery disabled"); return; }
+ try {
+ const requestData = {
+ FCMs,
+@@ -118,6 +119,7 @@ export const pushServerKeyNotification = async (
+ signedTx?: string;
+ }
+ ) => {
++ if (config.LOCAL_DEV) { logger.info("Local mode: push delivery disabled"); return; }
+ try {
+ let title;
+ let body;
+diff --git a/src/utilities/secretManager.ts b/src/utilities/secretManager.ts
+index e6bfd49..3b3b732 100644
+--- a/src/utilities/secretManager.ts
++++ b/src/utilities/secretManager.ts
+@@ -1,7 +1,15 @@
+ import { SecretManagerServiceClient } from '@google-cloud/secret-manager';
+ import config from '../config';
++import { readFileSync } from 'fs';
+
+ export const fetchSecrets = async (secretIdentifiers: string[], shouldParse: Boolean = false) => {
++ if (config.LOCAL_DEV) {
++ const secrets = JSON.parse(readFileSync("/local-data/secrets.json", "utf8"));
++ return secretIdentifiers.map(identifier => {
++ if (!Object.prototype.hasOwnProperty.call(secrets, identifier)) throw new Error("Unknown local secret identifier");
++ return { [identifier]: shouldParse ? JSON.parse(secrets[identifier]) : secrets[identifier] };
++ });
++ }
+ const client = new SecretManagerServiceClient();
+ const projectId = config.PROJECT_ID;
+
diff --git a/dev/local-backend/app.env.local.example b/dev/local-backend/app.env.local.example
new file mode 100644
index 0000000000..0121ab915d
--- /dev/null
+++ b/dev/local-backend/app.env.local.example
@@ -0,0 +1,10 @@
+# Disposable local development only. Copy to app repo .env.local.
+ENVIRONMENT=DEVELOPMENT
+RELAY=http://localhost:3000/
+CHANNEL_URL=http://localhost:4002/
+SIGNING_SERVER_TESTNET=http://localhost:3003/
+SIGNING_SERVER_MAINNET=http://localhost:3003/mainnet-disabled/
+HEXA_ID_TESTNET=keeper-local-only
+HEXA_ID_MAINNET=keeper-local-mainnet-disabled
+ENC_KEY_STORAGE_IDENTIFIER=KEEPER-LOCAL-DEV
+SENTRY_DNS=http://local@localhost:3000/1
diff --git a/dev/local-backend/compose.yaml b/dev/local-backend/compose.yaml
new file mode 100644
index 0000000000..be79d65d3a
--- /dev/null
+++ b/dev/local-backend/compose.yaml
@@ -0,0 +1,99 @@
+name: ${COMPOSE_PROJECT_NAME:-keeper-contributor}
+services:
+ mongo:
+ image: mongo:7.0@sha256:9854f7139445d766a9523571d6f047530c45547460ffcf8259eb2bf4264632ca
+ command: [mongod, --replSet, keeper-local, --bind_ip_all]
+ volumes:
+ - mongo-data:/data/db
+ networks: [local-only]
+ healthcheck:
+ test: [CMD, mongosh, --quiet, --eval, "try { rs.status(); } catch (e) { if (e.code !== 94) throw e; rs.initiate({_id: 'keeper-local', members: [{_id: 0, host: 'mongo:27017'}]}); } quit(db.hello().isWritablePrimary ? 0 : 1)"]
+ interval: 5s
+ timeout: 5s
+ retries: 20
+ relay:
+ build:
+ context: ./.sources/relay
+ dockerfile: Dockerfile.local
+ environment:
+ LOCAL_DEV: "true"
+ ENVIRONMENT: DEVELOPMENT
+ BITCOIN_NETWORK: TESTNET
+ VERSION: local-development
+ DATABASE_URL: mongodb://mongo:27017/keeper_local?replicaSet=keeper-local
+ PORT: "3000"
+ WS_PORT: "4002"
+ HEXA_ID: keeper-local-only
+ ADMIN_KEY: keeper-local-admin-only
+ CHANNEL_URL: http://relay:4002/
+ FAUCET_MNEMONIC: "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about"
+ networks: [local-only]
+ depends_on:
+ mongo:
+ condition: service_healthy
+ healthcheck:
+ test: [CMD, node, -e, "fetch('http://localhost:3000/health').then(r=>process.exit(r.ok?0:1)).catch(()=>process.exit(1))"]
+ interval: 5s
+ timeout: 5s
+ retries: 20
+ signing:
+ build:
+ context: ./.sources/signing
+ dockerfile: Dockerfile.local
+ environment:
+ LOCAL_DEV: "true"
+ ENVIRONMENT: TEST
+ DB_MODE: DEV
+ PORT: "3003"
+ VERSION: local-development
+ HEXA_ID: keeper-local-only
+ BIT_ADMIN_KEY: keeper-local-admin-only
+ LOCAL_DATABASE_URL: mongodb://mongo:27017/keeper_signing_local?replicaSet=keeper-local
+ RELAY: http://relay:3000/
+ MNEMONIC_IDENTIFIER_V2: local-signer-v2
+ MNEMONIC_IDENTIFIER_V3: local-signer-v3
+ INHERITANCE_MNEMONIC_IDENTIFIER_V2: local-inheritance-v2
+ INHERITANCE_MNEMONIC_IDENTIFIER_V3: local-inheritance-v3
+ RSA_PRV_KEY_IDENTIFIER: local-rsa-private
+ RSA_PUB_KEY_IDENTIFIER: local-rsa-public
+ SES_REGION: us-east-1
+ SES_SOURCE_EMAIL: local@example.invalid
+ volumes:
+ - signing-data:/local-data
+ networks: [local-only]
+ depends_on:
+ mongo:
+ condition: service_healthy
+ healthcheck:
+ test: [CMD, node, -e, "fetch('http://localhost:3003/health').then(r=>process.exit(r.ok?0:1)).catch(()=>process.exit(1))"]
+ interval: 5s
+ timeout: 5s
+ retries: 20
+ gateway:
+ healthcheck:
+ test: [CMD-SHELL, "wget -q -O /dev/null http://127.0.0.1:3000/health && wget -q -O /dev/null http://127.0.0.1:3003/health"]
+ interval: 5s
+ timeout: 5s
+ retries: 20
+ image: nginx:1.28-alpine@sha256:a8b39bd9cf0f83869a2162827a0caf6137ddf759d50a171451b335cecc87d236
+ volumes:
+ - ./nginx.conf:/etc/nginx/conf.d/default.conf:ro
+ ports:
+ - "127.0.0.1:${KEEPER_RELAY_PORT:-3000}:3000"
+ - "127.0.0.1:${KEEPER_CHANNEL_PORT:-4002}:4002"
+ - "127.0.0.1:${KEEPER_SIGNING_PORT:-3003}:3003"
+ networks: [local-only, host-access]
+ depends_on:
+ relay:
+ condition: service_healthy
+ restart: true
+ signing:
+ condition: service_healthy
+ restart: true
+networks:
+ local-only:
+ internal: true
+ host-access:
+volumes:
+ mongo-data:
+ signing-data:
diff --git a/dev/local-backend/dev b/dev/local-backend/dev
new file mode 100755
index 0000000000..52a7cab783
--- /dev/null
+++ b/dev/local-backend/dev
@@ -0,0 +1,3 @@
+#!/bin/sh
+set -eu
+exec python3 "$(dirname "$0")/keeper.py" "$@"
diff --git a/dev/local-backend/keeper.py b/dev/local-backend/keeper.py
new file mode 100644
index 0000000000..fbb93a8dca
--- /dev/null
+++ b/dev/local-backend/keeper.py
@@ -0,0 +1,192 @@
+#!/usr/bin/env python3
+"""Contributor setup using only Python's standard library, Git and Compose."""
+import argparse
+import hashlib
+import json
+import os
+from pathlib import Path
+import re
+import shutil
+import subprocess
+import sys
+import tempfile
+
+HERE = Path(__file__).resolve().parent
+APP = HERE.parent.parent
+
+
+def run(args, **kwargs):
+ return subprocess.run([str(a) for a in args], check=True, **kwargs)
+
+
+def output(args, **kwargs):
+ return subprocess.check_output([str(a) for a in args], text=True, **kwargs).strip()
+
+
+def settings():
+ values = {}
+ envfile = HERE / '.env'
+ if envfile.exists():
+ for line in envfile.read_text().splitlines():
+ if line.strip() and not line.lstrip().startswith('#'):
+ key, sep, value = line.partition('=')
+ if not sep:
+ raise ValueError('Use KEY=value lines in dev/local-backend/.env')
+ values[key.strip()] = value.strip()
+ defaults = {'COMPOSE_PROJECT_NAME': 'keeper-contributor',
+ 'KEEPER_RELAY_PORT': '3000', 'KEEPER_CHANNEL_PORT': '4002',
+ 'KEEPER_SIGNING_PORT': '3003'}
+ for key, default in defaults.items():
+ values[key] = os.environ.get(key, values.get(key, default))
+ if not re.fullmatch(r'[a-z0-9][a-z0-9_-]*', values['COMPOSE_PROJECT_NAME']):
+ raise ValueError('COMPOSE_PROJECT_NAME must contain lowercase letters, digits, _ or -')
+ ports = [int(values[k]) for k in defaults if k.endswith('_PORT')]
+ if 8081 in ports:
+ raise ValueError('Port 8081 is reserved for Metro; choose another backend port')
+ if len(set(ports)) != 3 or any(p < 1024 or p > 65535 for p in ports):
+ raise ValueError('Choose three distinct ports between 1024 and 65535')
+ return {k: values[k] for k in defaults}
+
+
+def compose(*args, **kwargs):
+ env = dict(os.environ, **settings())
+ return run(['docker', 'compose', '--env-file', HERE / '.env.example',
+ '-f', HERE / 'compose.yaml', *args], env=env, **kwargs)
+
+
+def prepare(only=None):
+ lock = json.loads((HERE / 'sources.lock.json').read_text())
+ sources = HERE / '.sources'
+ sources.mkdir(exist_ok=True)
+ for name, spec in lock.items():
+ if only is not None and name != only:
+ continue
+ adapter = HERE / 'adapters' / name
+ adapter_files = [path for path in adapter.rglob('*') if path.is_file() or path.is_symlink()]
+ if any(path.is_symlink() for path in adapter_files):
+ raise ValueError(f'{name}: adapter symlinks are not allowed')
+ actual_assets = {path.relative_to(adapter).as_posix() for path in adapter_files}
+ if actual_assets != set(spec['assets']):
+ raise ValueError(f'{name}: adapter file set does not match source lock')
+ for asset, digest in spec['assets'].items():
+ if hashlib.sha256((adapter / asset).read_bytes()).hexdigest() != digest:
+ raise ValueError(f'{name}: adapter checksum mismatch: {asset}')
+ fingerprint = hashlib.sha256(json.dumps(spec, sort_keys=True).encode()).hexdigest()
+ target = sources / name
+ marker = target / '.keeper-source.json'
+ if target.exists():
+ if not marker.exists() or json.loads(marker.read_text()) != spec:
+ raise ValueError(f'{target}: existing checkout does not match this setup. '
+ 'Move it aside after saving your edits, then retry; it was not overwritten.')
+ if output(['git', '-C', target, 'rev-parse', 'HEAD']) != spec['revision']:
+ raise ValueError(f'{target}: HEAD changed; save your work and move this checkout aside.')
+ print(f'{name}: already prepared; preserving local backend edits ({fingerprint[:12]})')
+ continue
+ with tempfile.TemporaryDirectory(prefix=f'.{name}-', dir=sources) as temp:
+ checkout = Path(temp) / 'checkout'
+ run(['git', 'init', '--quiet', checkout])
+ run(['git', '-C', checkout, 'remote', 'add', 'origin', spec['url']])
+ print(f'{name}: fetching {spec["revision"]}', flush=True)
+ try:
+ run(['git', '-C', checkout, 'fetch', '--quiet', '--depth=1', 'origin', spec['revision']])
+ except subprocess.CalledProcessError as error:
+ raise ValueError(f'{name}: cannot fetch the pinned public backend revision. '
+ 'Check the revision and network connection. '
+ 'No existing checkout was replaced.') from error
+ run(['git', '-C', checkout, 'checkout', '--quiet', '--detach', spec['revision']])
+ if spec['assets']:
+ if (adapter / 'local.patch').exists():
+ run(['git', '-C', checkout, 'apply', '--check', adapter / 'local.patch'])
+ run(['git', '-C', checkout, 'apply', adapter / 'local.patch'])
+ for asset in (adapter / 'files').rglob('*'):
+ if asset.is_file():
+ dest = checkout / asset.relative_to(adapter / 'files')
+ dest.parent.mkdir(parents=True, exist_ok=True)
+ shutil.copyfile(asset, dest)
+ (checkout / '.keeper-source.json').write_text(json.dumps(spec, indent=2) + '\n')
+ checkout.rename(target)
+
+
+def app_env():
+ config = settings()
+ template = (HERE / 'app.env.local.example').read_text()
+ ports = {'3000': config['KEEPER_RELAY_PORT'],
+ '4002': config['KEEPER_CHANNEL_PORT'],
+ '3003': config['KEEPER_SIGNING_PORT']}
+ template = re.sub(r':(3000|4002|3003)/', lambda match: f':{ports[match.group(1)]}/', template)
+ dest = APP / '.env.local'
+ if dest.exists():
+ if dest.read_text() != template:
+ raise ValueError('.env.local already exists with different settings. Compare it with '
+ 'dev/local-backend/app.env.local.example; no file was overwritten.')
+ print('.env.local already matches this setup')
+ return
+ fd = os.open(dest, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600)
+ with os.fdopen(fd, 'w') as stream:
+ stream.write(template)
+ print('Created .env.local (local test settings only)')
+
+
+def doctor():
+ failed = False
+ for label, args in [('Git', ['git', '--version']), ('Docker Engine', ['docker', 'info', '--format', '{{.ServerVersion}}']),
+ ('Docker Compose', ['docker', 'compose', 'version']), ('Node', ['node', '--version']),
+ ('Yarn', ['yarn', '--version'])]:
+ try:
+ print(f'{label}: {output(args, stderr=subprocess.DEVNULL)}')
+ except (OSError, subprocess.CalledProcessError):
+ print(f'MISSING: {label}')
+ failed = True
+ print('Python:', sys.version.split()[0])
+ print('Android SDK:', os.environ.get('ANDROID_HOME', 'set ANDROID_HOME before Android builds'))
+ print('JAVA_HOME:', os.environ.get('JAVA_HOME', 'set JAVA_HOME to JDK 17 before Android builds'))
+ if sys.platform == 'darwin':
+ for label, args in [('Xcode', ['xcodebuild', '-version']), ('Ruby', ['ruby', '--version']),
+ ('Bundler', ['bundle', '--version'])]:
+ try:
+ print(f'{label}: {output(args, stderr=subprocess.DEVNULL)}')
+ except (OSError, subprocess.CalledProcessError):
+ print(f'MISSING for iOS: {label}')
+ print('See README.md for required native tool versions; this checks availability, not native builds.')
+ if failed:
+ raise ValueError('Install/start the missing prerequisites and rerun doctor.')
+
+
+def main():
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument('command', choices=['doctor', 'prepare', 'prepare-signing', 'up', 'stop', 'status', 'logs', 'verify', 'env', 'android-forward'])
+ parser.add_argument('--serial', help='Android emulator/device serial for android-forward')
+ args = parser.parse_args()
+ if args.command == 'doctor':
+ doctor()
+ elif args.command == 'prepare':
+ prepare()
+ elif args.command == 'prepare-signing':
+ prepare(only='signing')
+ elif args.command == 'up':
+ prepare()
+ compose('up', '-d', '--build', '--wait', '--wait-timeout', '180')
+ run([sys.executable, HERE / 'verify.py'])
+ elif args.command == 'stop':
+ compose('down') # Retain both databases and signing keys. No implicit data reset.
+ elif args.command == 'status':
+ compose('ps')
+ elif args.command == 'logs':
+ compose('logs', '--tail', '100')
+ elif args.command == 'verify':
+ run([sys.executable, HERE / 'verify.py'])
+ elif args.command == 'env':
+ app_env()
+ elif args.command == 'android-forward':
+ if not args.serial:
+ parser.error('android-forward requires --serial; use adb devices to choose one')
+ for port in ['8081'] + [v for k, v in settings().items() if k.endswith('_PORT')]:
+ run(['adb', '-s', args.serial, 'reverse', f'tcp:{port}', f'tcp:{port}'])
+
+
+if __name__ == '__main__':
+ try:
+ main()
+ except (OSError, ValueError, subprocess.CalledProcessError) as error:
+ print(f'Setup failed: {error}', file=sys.stderr)
+ sys.exit(1)
diff --git a/dev/local-backend/nginx.conf b/dev/local-backend/nginx.conf
new file mode 100644
index 0000000000..bcd9481514
--- /dev/null
+++ b/dev/local-backend/nginx.conf
@@ -0,0 +1,22 @@
+server {
+ listen 3000;
+ client_max_body_size 50m;
+ location / {
+ proxy_pass http://relay:3000;
+ }
+}
+server {
+ listen 4002;
+ location / {
+ proxy_pass http://relay:4002;
+ proxy_http_version 1.1;
+ proxy_set_header Upgrade $http_upgrade;
+ proxy_set_header Connection "upgrade";
+ }
+}
+server {
+ listen 3003;
+ location / {
+ proxy_pass http://signing:3003;
+ }
+}
diff --git a/dev/local-backend/sources.lock.json b/dev/local-backend/sources.lock.json
new file mode 100644
index 0000000000..4d5d02b531
--- /dev/null
+++ b/dev/local-backend/sources.lock.json
@@ -0,0 +1,20 @@
+{
+ "relay": {
+ "url": "https://github.com/KeeperCommunity/Relay.git",
+ "revision": "ee935359f22ff7932ea0a62e9084d4b49801f4aa",
+ "assets": {
+ "files/Dockerfile.local": "6dde6c692430b1a91a10cdd82e6f1562023cc5974ffd4d4f58fe57fa1994407a"
+ }
+ },
+ "signing": {
+ "url": "https://github.com/KeeperCommunity/SigningServer.git",
+ "revision": "3cc7728c27328e7b0358d1f91a32d8d13feba90a",
+ "assets": {
+ "files/.dockerignore": "78d9a1e03c57cfc1c7fb79ff2335aa2393bb075d0ac4a23feae81371728190be",
+ "files/Dockerfile.local": "04a0bfca3903eb1363f8804b7c181424747c949aed543a89fe7a02316ccafa3d",
+ "files/scripts/local-entry.cjs": "7e0d39965fd8d4a880ab68b5ff9e7b75595c33cbdb106bb5ec0b42d505b1827b",
+ "files/src/config.ts": "606fdeb4717e98ab95e5a6918a0c8a8b9b3427697d27bba263b9ec566a91438e",
+ "local.patch": "a592f37900215a5f013a0d349983f7a1d937206fbf1670c07fc9a37e457d743f"
+ }
+ }
+}
diff --git a/dev/local-backend/test_keeper.py b/dev/local-backend/test_keeper.py
new file mode 100644
index 0000000000..b5bc059b51
--- /dev/null
+++ b/dev/local-backend/test_keeper.py
@@ -0,0 +1,146 @@
+"""Regression checks for setup operations that must preserve developer work."""
+import hashlib
+import json
+import subprocess
+from pathlib import Path
+import tempfile
+import unittest
+from unittest.mock import patch
+
+import keeper
+import verify
+
+
+class PreserveDeveloperWork(unittest.TestCase):
+ def setUp(self):
+ self.temp = tempfile.TemporaryDirectory()
+ self.addCleanup(self.temp.cleanup)
+ self.app = Path(self.temp.name)
+ self.here = self.app / 'dev/local-backend'
+ self.here.mkdir(parents=True)
+ self.contexts = [patch.object(keeper, 'HERE', self.here), patch.object(keeper, 'APP', self.app),
+ patch.dict('os.environ', {}, clear=True)]
+ for context in self.contexts:
+ context.start()
+ self.addCleanup(context.stop)
+
+ def test_environment_is_exclusive_and_preserves_production(self):
+ (self.here / 'app.env.local.example').write_text('RELAY=http://localhost:3000/\n')
+ production = self.app / '.env.production'
+ production.write_text('existing-production-sentinel\n')
+ keeper.app_env()
+ self.assertEqual((self.app / '.env.local').stat().st_mode & 0o777, 0o600)
+ keeper.app_env() # Same configuration is repeatable.
+ (self.app / '.env.local').write_text('developer-settings\n')
+ with self.assertRaisesRegex(ValueError, 'already exists'):
+ keeper.app_env()
+ self.assertEqual((self.app / '.env.local').read_text(), 'developer-settings\n')
+ self.assertEqual(production.read_text(), 'existing-production-sentinel\n')
+
+ def test_swapped_ports_do_not_rewrite_each_other(self):
+ (self.here / 'app.env.local.example').write_text(
+ 'RELAY=http://localhost:3000/\nCHANNEL=http://localhost:4002/\n'
+ 'SIGNING=http://localhost:3003/\n')
+ (self.here / '.env').write_text('KEEPER_RELAY_PORT=4002\nKEEPER_CHANNEL_PORT=3000\n')
+ keeper.app_env()
+ self.assertEqual((self.app / '.env.local').read_text(),
+ 'RELAY=http://localhost:4002/\nCHANNEL=http://localhost:3000/\n'
+ 'SIGNING=http://localhost:3003/\n')
+
+ def test_adapter_tampering_is_rejected_before_fetch(self):
+ adapter = self.here / 'adapters/relay'
+ adapter.mkdir(parents=True)
+ (adapter / 'local.patch').write_text('changed')
+ (self.here / 'sources.lock.json').write_text(json.dumps({'relay': {
+ 'assets': {'local.patch': hashlib.sha256(b'original').hexdigest()}}}))
+ with patch.object(keeper, 'run') as command:
+ with self.assertRaisesRegex(ValueError, 'checksum mismatch'):
+ keeper.prepare()
+ command.assert_not_called()
+
+ def test_unlisted_adapter_file_is_rejected_before_fetch(self):
+ adapter = self.here / 'adapters/relay/files'
+ adapter.mkdir(parents=True)
+ (adapter / 'unlisted.js').write_text('unexpected')
+ (self.here / 'sources.lock.json').write_text(json.dumps({'relay': {'assets': {}}}))
+ with patch.object(keeper, 'run') as command:
+ with self.assertRaisesRegex(ValueError, 'file set does not match'):
+ keeper.prepare()
+ command.assert_not_called()
+
+ def test_adapter_symlinks_are_rejected_before_fetch_even_when_listed(self):
+ adapter = self.here / 'adapters/relay/files'
+ adapter.mkdir(parents=True)
+ target = self.app / 'outside-adapter.js'
+ target.write_text('fixture')
+ (adapter / 'link.js').symlink_to(target)
+ for assets in ({}, {'files/link.js': hashlib.sha256(b'fixture').hexdigest()}):
+ with self.subTest(listed=bool(assets)):
+ (self.here / 'sources.lock.json').write_text(json.dumps({
+ 'relay': {'assets': assets}}))
+ with patch.object(keeper, 'run') as command:
+ with self.assertRaisesRegex(ValueError, 'symlinks are not allowed'):
+ keeper.prepare()
+ command.assert_not_called()
+
+ def test_unknown_existing_checkout_is_not_overwritten(self):
+ source = self.here / '.sources/relay'
+ source.mkdir(parents=True)
+ edit = source / 'my-work.ts'
+ edit.write_text('keep this')
+ (self.here / 'sources.lock.json').write_text(json.dumps({'relay': {'assets': {}}}))
+ with patch.object(keeper, 'run') as command:
+ with self.assertRaisesRegex(ValueError, 'not overwritten'):
+ keeper.prepare()
+ command.assert_not_called()
+ self.assertEqual(edit.read_text(), 'keep this')
+
+ def test_port_collision_is_rejected(self):
+ (self.here / '.env').write_text('KEEPER_RELAY_PORT=3003\n')
+ with self.assertRaisesRegex(ValueError, 'distinct ports'):
+ keeper.settings()
+
+ def test_metro_port_is_reserved_for_each_backend_service(self):
+ for service in ('RELAY', 'CHANNEL', 'SIGNING'):
+ with self.subTest(service=service):
+ (self.here / '.env').write_text(f'KEEPER_{service}_PORT=8081\n')
+ with self.assertRaisesRegex(ValueError, 'reserved for Metro'):
+ keeper.settings()
+
+ def test_invalid_two_fa_requires_the_pinned_token_failure(self):
+ with patch.object(verify, 'request', return_value={
+ 'err': 'Validation failed: verification token is either invalid or has expired'}):
+ verify.verify_invalid_two_fa('3003', {'id': 'disposable-signer'})
+ for unrelated in ({'err': 'Unauthorized request'}, {'err': 'Invalid request schema'},
+ {'valid': False}, {'valid': True}):
+ with self.subTest(response=unrelated):
+ with patch.object(verify, 'request', return_value=unrelated):
+ with self.assertRaisesRegex(RuntimeError, 'unrelated error'):
+ verify.verify_invalid_two_fa('3003', {'id': 'disposable-signer'})
+
+ def test_fetch_failure_explains_public_revision_and_cleans_temporary_checkout(self):
+ (self.here / 'sources.lock.json').write_text(json.dumps({'relay': {
+ 'assets': {}, 'url': 'https://github.com/example/private-backend.git',
+ 'revision': 'a' * 40}}))
+ with patch.object(keeper, 'run', side_effect=[
+ None, None, subprocess.CalledProcessError(128, ['git', 'fetch'])]):
+ with self.assertRaisesRegex(ValueError, 'pinned public backend revision'):
+ keeper.prepare()
+ self.assertEqual(list((self.here / '.sources').iterdir()), [])
+
+ def test_signing_prepare_does_not_fetch_relay(self):
+ (self.here / 'sources.lock.json').write_text(json.dumps({
+ 'relay': {'assets': {}, 'url': 'https://github.com/example/private-relay.git', 'revision': 'a' * 40},
+ 'signing': {'assets': {}, 'url': 'https://github.com/example/public-signing.git', 'revision': 'b' * 40},
+ }))
+ with patch.object(keeper, 'run', side_effect=[
+ None, None, subprocess.CalledProcessError(128, ['git', 'fetch'])]) as command:
+ with self.assertRaisesRegex(ValueError, 'pinned public backend revision'):
+ keeper.prepare(only='signing')
+ self.assertEqual(command.call_count, 3)
+ self.assertIn('https://github.com/example/public-signing.git', command.call_args_list[1].args[0])
+ self.assertEqual(list((self.here / '.sources').iterdir()), [])
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/dev/local-backend/verify-local.sh b/dev/local-backend/verify-local.sh
new file mode 100755
index 0000000000..04dc216dfb
--- /dev/null
+++ b/dev/local-backend/verify-local.sh
@@ -0,0 +1,3 @@
+#!/bin/sh
+set -eu
+exec python3 "$(dirname "$0")/verify.py" "$@"
diff --git a/dev/local-backend/verify.py b/dev/local-backend/verify.py
new file mode 100644
index 0000000000..00922ffea3
--- /dev/null
+++ b/dev/local-backend/verify.py
@@ -0,0 +1,206 @@
+#!/usr/bin/env python3
+"""Exercise disposable local fixtures, never a hosted backend or real wallet."""
+import argparse
+import base64
+import hashlib
+import hmac
+import json
+import re
+import struct
+import subprocess
+import sys
+import time
+import urllib.error
+import urllib.request
+import uuid
+
+from keeper import compose, settings
+
+
+def require(condition, description):
+ if not condition:
+ raise RuntimeError(description)
+
+
+class NoRedirect(urllib.request.HTTPRedirectHandler):
+ def redirect_request(self, *args, **kwargs):
+ raise RuntimeError('Local check refused an HTTP redirect')
+
+
+def request(port, path, data=None, expected=200):
+ req = urllib.request.Request(f'http://127.0.0.1:{port}{path}',
+ data=None if data is None else json.dumps(data).encode(),
+ headers={'Content-Type': 'application/json', 'appversion': '2.5.15',
+ 'os': 'ANDROID', 'HEXA-ID': 'keeper-local-only'})
+ try:
+ response = urllib.request.build_opener(urllib.request.ProxyHandler({}), NoRedirect()).open(req, timeout=20)
+ except urllib.error.HTTPError as error:
+ response = error
+ with response:
+ statuses = expected if isinstance(expected, tuple) else (expected,)
+ require(response.code in statuses, f'{path}: expected HTTP {expected}, got {response.code}')
+ body = response.read().decode()
+ return body if path.startswith('/socket.io/') else json.loads(body)
+
+
+def token(secret):
+ key = base64.b32decode(secret + '=' * (-len(secret) % 8))
+ digest = hmac.new(key, struct.pack('>Q', int(time.time()) // 30), hashlib.sha1).digest()
+ offset = digest[-1] & 15
+ return str((struct.unpack('>I', digest[offset:offset + 4])[0] & 0x7fffffff) % 1000000).zfill(6)
+
+
+def health(relay, signing):
+ for port in (relay, signing):
+ result = request(port, '/health')
+ require(result.get('ready') is True and result.get('mode') == 'local' and
+ result.get('network') == 'TESTNET', 'Expected healthy local TESTNET service')
+ require(result['capabilities']['pushDelivery'] is False, 'Push must be disabled')
+ require(request(signing, '/health')['capabilities']['scheduledJobs'] is False, 'Scheduled jobs must be disabled')
+ print('PASS local/testnet health and disabled cloud capabilities')
+
+
+def boundaries():
+ cases = [('relay', 'BITCOIN_NETWORK=MAINNET', 'LOCAL_DEV requires'),
+ ('relay', 'DATABASE_URL=mongodb://example.invalid/keeper_local', 'LOCAL_DEV requires'),
+ ('signing', 'ENVIRONMENT=MAIN', 'Local signing requires'),
+ ('signing', 'LOCAL_DATABASE_URL=mongodb://example.invalid/keeper_signing_local', 'Local signing requires')]
+ for service, override, message in cases:
+ try:
+ compose('run', '--rm', '--no-deps', '-e', override, service, 'node', '-e',
+ "require('./dist/config')", capture_output=True, text=True)
+ except subprocess.CalledProcessError as error:
+ require(message in error.stdout + error.stderr, f'{service}: failed for an unexpected reason')
+ else:
+ raise RuntimeError(f'{service}: unsafe configuration was accepted')
+ print('PASS mainnet and hosted database configuration rejected')
+
+
+def backup_roundtrip(relay, fixture):
+ snapshot = request(relay, '/getBackupSnapshot', {'appId': fixture})
+ require(snapshot.get('exists') is True and
+ re.fullmatch(r'[a-f0-9]{64}', snapshot.get('revision', '')),
+ 'Created app backup snapshot unavailable')
+ replacement = {'appId': fixture, 'publicId': fixture, 'version': '2.6.3',
+ 'expectedRevision': snapshot['revision'],
+ 'walletObject': {'qa': 'synthetic-encrypted-wallet'},
+ 'signersObject': {}, 'vaultObject': {}, 'nodes': [], 'labels': []}
+ result = request(relay, '/repairAppBackup', replacement)
+ require(result.get('updated') is True, 'Revisioned backup repair failed')
+ repaired = request(relay, '/getBackupSnapshot', {'appId': fixture})
+ require(repaired.get('revision') != snapshot['revision'] and
+ repaired.get('appImage', {}).get('wallets', {}).get('qa') ==
+ replacement['walletObject']['qa'], 'Backup repair did not persist its image')
+ stale = dict(replacement, walletObject={'qa': 'stale-replacement-must-not-persist'})
+ result = request(relay, '/repairAppBackup', stale, expected=409)
+ require(result.get('updated') is False and result.get('error') == 'BACKUP_CHANGED',
+ 'Stale backup revision was accepted')
+ require(request(relay, '/getBackupSnapshot', {'appId': fixture}) == repaired,
+ 'Rejected stale repair changed the backup')
+ print('PASS revisioned backup create/read and stale-revision preservation')
+ changed = dict(replacement, expectedRevision=repaired['revision'],
+ walletObject={'qa': 'second-synthetic-encrypted-wallet'})
+ require(request(relay, '/repairAppBackup', changed).get('updated') is True,
+ 'Second disposable backup image was not saved')
+ second = request(relay, '/getBackupSnapshot', {'appId': fixture})
+ restored = dict(replacement, expectedRevision=second['revision'])
+ require(request(relay, '/repairAppBackup', restored).get('updated') is True,
+ 'Restoring disposable backup content failed')
+ final = request(relay, '/getBackupSnapshot', {'appId': fixture})
+ require(len({repaired['revision'], second['revision'], final['revision']}) == 3 and
+ final['appImage']['wallets'] == repaired['appImage']['wallets'],
+ 'A backup revision repeated after its content changed and returned')
+ obsolete = dict(changed, expectedRevision=repaired['revision'])
+ require(request(relay, '/repairAppBackup', obsolete, expected=409).get('error') ==
+ 'BACKUP_CHANGED', 'An obsolete revision was accepted after content returned')
+ require(request(relay, '/getBackupSnapshot', {'appId': fixture}) == final,
+ 'Rejected obsolete repair changed the restored backup')
+ print('PASS restored content retains a new revision and rejects obsolete repairs')
+ return final
+
+
+def verify_invalid_two_fa(signing, auth):
+ rejected = request(signing, '/v3/validateSingerSetup',
+ dict(auth, verificationToken='abcdef'), expected=400)
+ require(rejected.get('err') ==
+ 'Validation failed: verification token is either invalid or has expired',
+ 'Invalid 2FA check returned an unrelated error')
+
+
+def main():
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument('--persistence', action='store_true', help='Recreate this Compose stack, retaining volumes, and recheck fixtures')
+ parser.add_argument('--boundaries', action='store_true', help='Check startup rejection of mainnet and external databases')
+ args = parser.parse_args()
+ config = settings()
+ relay, channel, signing = (config[f'KEEPER_{key}_PORT'] for key in ('RELAY', 'CHANNEL', 'SIGNING'))
+ health(relay, signing) # Must pass before any mutations.
+ handshake = request(channel, '/socket.io/?EIO=4&transport=polling')
+ require(handshake.startswith('0') and json.loads(handshake[1:]).get('sid'), 'Socket.IO handshake failed')
+ print('PASS Socket.IO handshake')
+ unavailable = request(relay, '/local-unavailable-probe', {}, expected=503)
+ require(unavailable.get('error') == 'LOCAL_INTEGRATION_UNAVAILABLE', 'Unavailable route silently succeeded')
+ print('PASS unsupported integration fails explicitly')
+ fixture = 'contributor-smoke-' + uuid.uuid4().hex
+ created = request(relay, '/createNewApp', {'publicId': fixture, 'appID': fixture})
+ require(created.get('created') is True, 'App record creation failed')
+ # Existing relay acknowledges creation before its app save callback completes.
+ # Poll the non-throwing subscription endpoint before retrieving the app image.
+ for attempt in range(20):
+ subscription = request(relay, '/getSubscriptionDetails', {'id': fixture, 'appID': fixture})
+ if subscription.get('currentSubscription'):
+ break
+ time.sleep(0.25)
+ else:
+ raise RuntimeError('Created app did not become readable within 5 seconds')
+ app = request(relay, '/getAppImage', {'appId': fixture})
+ require(app.get('appImage', {}).get('appId') == fixture and
+ app['appImage'].get('publicId') == fixture and app['appImage'].get('_id'),
+ 'Persisted app record round trip failed')
+ print('PASS relay app record create/read')
+ backup = backup_roundtrip(relay, fixture)
+ app = request(relay, '/getAppImage', {'appId': fixture})
+ rejected = request(signing, '/v3/setupSigner', {'HEXA_ID': 'invalid'}, expected=400)
+ require(rejected.get('err') == 'Unauthorized request', 'Signing authorization failed')
+ result = request(signing, '/v3/setupSigner', {'HEXA_ID': 'keeper-local-only', 'policy': {'verification': {'method': 'TWO_FA'},
+ 'restrictions': {'none': True, 'maxTransactionAmount': None, 'timeWindow': None},
+ 'signingDelay': None}})
+ require(result.get('setupSuccessful') is True, 'Signer setup failed')
+ data = result['setupData']
+ require(data['bhXpub'].startswith('tpub'), 'Signer must use testnet public key')
+ secret = data['verification']['verifier'] # Disposable fixture; never print or write to source.
+ auth = {'HEXA_ID': 'keeper-local-only', 'id': data['id'], 'verificationToken': token(secret)}
+ # Pinned backend uses a save callback here too; wait only for record visibility.
+ for attempt in range(20):
+ result = request(signing, '/v3/validateSingerSetup', auth, expected=(200, 400))
+ if result.get('valid') is True:
+ break
+ require(result.get('err', '').startswith('Singer not found'), 'Valid 2FA token rejected')
+ time.sleep(0.25)
+ auth['verificationToken'] = token(secret)
+ else:
+ raise RuntimeError('Created signer did not become readable within 5 seconds')
+ verify_invalid_two_fa(signing, auth)
+ print('PASS testnet signer setup, authorization and valid/invalid 2FA')
+ if args.persistence:
+ compose('down')
+ compose('up', '-d', '--wait', '--wait-timeout', '180')
+ health(relay, signing)
+ require(request(relay, '/getAppImage', {'appId': fixture}) == app, 'App data changed after recreation')
+ require(request(relay, '/getBackupSnapshot', {'appId': fixture}) == backup,
+ 'Revisioned backup changed after recreation')
+ auth['verificationToken'] = token(secret)
+ restored = request(signing, '/v3/fetchSignerSetup', auth)
+ require(restored.get('valid') is True and restored.get('xpub') == data['bhXpub'], 'Signing identity changed after recreation')
+ print('PASS database and signing identity persist after container recreation')
+ if args.boundaries:
+ boundaries()
+ print('Local backend checks passed. Disposable records retained in this project\'s local volumes.')
+
+
+if __name__ == '__main__':
+ try:
+ main()
+ except Exception as error:
+ print(f'FAIL: {error}', file=sys.stderr)
+ sys.exit(1)
diff --git a/docs/7066-protected-backup-correction.md b/docs/7066-protected-backup-correction.md
new file mode 100644
index 0000000000..8de4b3b9e5
--- /dev/null
+++ b/docs/7066-protected-backup-correction.md
@@ -0,0 +1,246 @@
+# Protected-backup and Version History follow-up — #7066 / #7067
+
+## Source and scope
+
+This patch uses the owner-designated completed R5 implementation source
+`77b72da29ac5f2cdf3f51c9a0e9f3fd1c2af7238` from [PR #7058](https://github.com/KeeperCommunity/bitcoin-keeper/pull/7058).
+Live records checked on 22 October 2026 show an open draft with `NEEDS_LOCAL`,
+not a publicly released 2.6.5. There is no 2.6.5 GitHub tag/release. The source
+still declares 2.6.4 (Android 627, iOS 620); this patch assigns no version.
+Store publication/availability has not been independently checked. The owner
+reports the App Store showing 2.6.4 after updating, while Keeper's Version History
+still ends at 2.6.3. The actual running binary/build is not established by that
+historical row or by the store listing alone.
+Its ancestry includes released R4 source
+`1d8a86a7462d935cbd0e28b857934b5718c152fc` and `sprint`
+`def0d6a90c80287edb4f58ae272cbfc340f00d73`.
+
+Work runs in the selected **Bitcoin Keeper** managed environment, in a separate
+worktree and `codex/7066-protected-backup-correction` branch. Explicit fetch
+successfully obtained the R5 commit missing from the previous stale attempt.
+Live searches found no other #7066 PR/implementation. R5 and the original
+checkout remain unchanged. The PR targets `sprint` per AGENTS.md and links a
+patch-only comparison from the exact R5 SHA.
+
+The provisional code/test estimate was 5k–10k changed tokens; the first backup
+patch measured approximately 12.1k, including workflow/privacy regressions and
+the supplemental current-backend witness. The owner subsequently authorized the
+stale Version History correction in the same follow-up (called the "5.1 patch"
+in the conversation). The revised estimate is approximately 16k–17k code/test
+tokens. This is a scope label, not a new app release version. No legacy all-copy
+purge, protocol redesign, release change, or parked investigation is included.
+
+## Evidence and limits
+
+The [current Relay production receipt](https://github.com/KeeperCommunity/bitcoin-keeper-relay/pull/158#issuecomment-6321195858)
+reports selected source `29597b27eeeb299205bf7d0555db0a90c38cc4be` and 14 hosted
+protocol checks passing on 21 October after correcting a storage-readiness
+probe. The current app and Relay v3 signing, namespace, projection, revision,
+generation, epoch and tombstone contracts agree on inspection. The hosted
+checks used a fresh synthetic namespace; they do not establish this upgraded
+iPhone's backup state. No production operation is performed for this patch.
+
+An enabled never-enrolled installation has only a read-only Check Again action
+on the baseline status screen. Repeated reads leave that state unchanged and
+cannot finish enrollment. Existing accounts can retain automatic-backup consent
+while their legacy encrypted copy has never been enrolled into v3. The backend
+intentionally does not adopt a legacy copy as a protected backup. The patch
+exposes Back Up Now through the existing explicit repair path, preserving its
+account/session, consent, conflict, upload acknowledgement and complete readback
+guards. Check Again still never enrolls or uploads. Disabled/deleted/conflicting
+states do not silently repair or recreate a protected copy.
+
+The same action is available for the generic unverified state. This is a direct
+retry route; it is not evidence that every unverified state was permanently
+stuck. For example, after a committed enrollment with a lost reply, a later
+read can report different, where the baseline already offered backup. The
+failing-before UI controls specifically cover enabled never-enrolled and
+unverified states; the supplemental service witness separates those schedules.
+
+An authenticated, validated never-enrolled result is absence of a protected
+namespace, not evidence of deletion. Delete remains non-success in that case;
+the UI explains the absence instead of showing the generic uncertain-deletion
+message. It neither creates a namespace to delete nor deletes legacy copies.
+Authorization, network, invalid/incomplete readback and uncertain mutation
+results remain failures.
+
+The screenshot's generic unverified state does not establish which request
+failed. The original phone's cause and corrected behavior remain **unconfirmed**.
+The user can reveal the latest bounded diagnostic on the status screen: fixed
+operation/stage/category, HTTP error status when available, elapsed milliseconds,
+and app version/build. This result exists only in memory for the selected account
+session and is cleared on account changes/new operations. It never displays or
+persists caught errors, request/response bodies, headers, identifiers, ciphertext
+or recovery contents. Do not request raw logs to fill the remaining evidence gap.
+
+## Owner-added Version History correction
+
+The app's history list reads local Realm records; it is separate from both the
+App Store listing and the running binary's native version/build. Source diagnosis
+found a shared Redux version controlling account-specific upgrades, an unguarded
+last-row access, and a comparison of only the last build number. Those conditions
+can skip a selected account's upgrade, fail on missing history, or leave a stale
+marketing-version row when build numbers match. They are reproducible source
+defects, not confirmation of the original phone's precise cause.
+
+Use the selected account's valid persisted version for migration decisions,
+retaining the legacy fallback only when that account version is absent. That
+fallback cannot establish a current account or justify an observation by itself.
+Compare
+the complete native version/build tuple when reconciling history. A missing
+current row can be recorded as a current installation observation only after a
+successful upgrade or when that account is already current. Preserve existing
+recovery/installation rows and dates; do not fabricate a successful transition
+after a failed migration or grant backup verification. Account/session ownership
+and atomic migration rollback remain required.
+
+The Version History screen separately labels the running native version/build
+as **Installed app version**. Historical rows are retained as historical evidence,
+including when they disagree with the running version. The store listing must
+never supply a fabricated installed version.
+
+Native acceptance for this addition:
+
+- Upgrade a disposable 2.6.3 account and verify the installed native version/build,
+ account version and history entry after normal unlock. Repeat with another
+ account that has already advanced the shared version value.
+- Test empty/stale history, the same build across different marketing versions,
+ build-only changes, repeated cold launches, and an existing Recovered Wallet
+ record. No duplicates, invented upgrade dates, or overwritten recovery labels.
+- Inject a failed local migration and switch A → B → A during the operation.
+ Failure must not append a success/observation row for the attempted upgrade or
+ write another account/session. Backup consent/readback semantics stay intact.
+- Check the installed-version label and history on iOS/Android at small width and
+ larger text. On the owner's phone, only normal navigation/reopen/unlock and
+ reading version/build are permitted; no reset, reinstall or recovery operation.
+
+## Targeted native acceptance
+
+Run on the exact final PR head, with the actual compatible backend selected and
+recorded. Use disposable accounts and installations for every destructive step.
+Record IOS, ANDROID and HARDWARE results separately, including build/backend
+identity and any step not run. JavaScript, Linux Realm and fixture results do
+not constitute native or original-phone acceptance.
+
+1. Create an older-account fixture with synthetic recovery contents and legacy
+ encrypted server copies. Retain saved automatic-backup consent when upgrading
+ through 2.6.4 to the patch; use the native app's persisted storage. Include
+ wallets, keys, a vault, node and label/metadata as applicable. Check the fresh
+ account separately as a control.
+2. Interrupt an enrollment/upload or use the demonstrated failing path. Confirm
+ enabled and unverified are distinct facts. Check Again only reads. Back Up Now
+ explicitly retries through the guarded repair, then requires an acknowledged
+ upload plus authenticated complete matching readback. An uncertain reply must
+ not claim Verified. A remote recovery conflict must preserve both copies.
+3. Reopen/cold launch the same account and recheck. Make an ordinary backup-relevant
+ metadata change, confirm it reaches the protected copy, and recheck again.
+4. Recover the disposable protected backup into a separate disposable installation.
+ Verify complete expected recovery contents and restored consent remaining off
+ until the established explicit choice. Never restore over the owner's phone.
+5. Turn off automatic backup. Confirm no copy was deleted and status checking
+ remains read-only. Separately re-enable and verify backup, then delete the
+ disposable protected copy. Require fresh confirmed tombstone/readback, auto
+ off, and unchanged local recovery contents. Fresh-read the deleted state and
+ explicitly recreate; deleted protected records must not resurrect. Older
+ read-only encrypted copies may remain.
+6. Check missing enrollment, authorization failure, interrupted request and
+ malformed/incomplete readback. No error may become Verified/Deleted. Repeat
+ while switching A → B → A; stale work and diagnostics must not bind to the new
+ account/session. Revoke consent while backup runs and check the result.
+7. On iOS and Android, check More, backup status and the affected enable/delete
+ dialogs in light/dark themes, small width (320–360 logical pixels) and larger
+ system text. Both long actions must wrap, remain fully readable and tappable;
+ the explanatory copy must be complete. Scroll through persistent feedback
+ without obscuring bottom navigation. Check retained-copy notice spacing,
+ progress/disabled actions, diagnostic show/hide and accessibility labels.
+
+## Original working iPhone — non-destructive only
+
+Before an approved corrected build is available, capture only version/build from
+About and, if available, the user-initiated fixed diagnostic from a normal Check
+Again. Share only the bounded fields listed above, never screenshots containing
+account details or raw logs. After the approved build/backend pair is available,
+use normal Back Up Now and Check Again, then reopen/recheck. The owner must confirm
+that successful verification persists. Do not reset, uninstall, restore over,
+delete a backup, or export private recovery data on that phone as a diagnostic.
+
+Keep #7066 open until disposable native acceptance and original-phone confirmation
+are complete. No merge, signing, distribution, deployment or publication is
+authorized by this patch or by a passing Cloud check.
+
+## Reproduce the supplemental upgrade witness
+
+Use Node 22.23.3+, frozen app dependencies with repository patches, the genuine
+Realm 12.15.0 Linux/macOS N-API binding, a clean separately obtained Relay checkout
+at `29597b27eeeb299205bf7d0555db0a90c38cc4be` with frozen dependencies and
+`npm ci --ignore-scripts --prefix tests/proof-tools`, and a disposable loopback
+Mongo replica set on port 27038. The wrapper verifies exact source hashes and
+driver versions; it leaves the historical proof runner/pins unchanged.
+
+```sh
+KEEPER_PROTECTED_RELAY_CHECKOUT=/absolute/path/to/current-relay \
+BACKUP_TEST_MONGO_URL=mongodb://127.0.0.1:27038 \
+node scripts/run-protected-upgrade-regression.cjs
+```
+
+The witness uses actual persisted Redux consent, encrypted native Realm, signed
+HTTP, current Relay and disposable Mongo: old legacy account → cold rehydration
+and upgrade → never-enrolled read/delete non-success → interrupted enrollment
+reply → read-only recheck → explicit repair and complete comparison → disable
+retains copies → protected deletion/tombstone → explicit recreation. It checks
+that legacy and local recovery contents survive. It is a host integration proof,
+not native app or original-phone acceptance.
+
+In this Cloud environment execution is **BLOCKED**: the native Realm binding is
+absent and `prebuild-install --runtime napi --target 6` received proxy CONNECT
+403 from `static.realm.io`. No cached binding or official GitHub release asset
+was available. No network-policy bypass, mock substitute, or passing upgrade
+proof is claimed. Syntax and exact-current-source admission/wrong-head rejection
+were checked. Native acceptance must complete this witness and the matrix above.
+
+## Actual Cloud checks
+
+Node 22.23.3 / Yarn 1.22.22; frozen install and all six repository patches PASS.
+Package, lockfile, Pod inputs and version consistency remain unchanged.
+
+| Check | Actual result |
+| --- | --- |
+| `npm run test -- --runInBand --coverage=false` | PASS after history addition: 49 suites, 553 tests, zero skips/failures |
+| `node --test tests/recovery/backupDiagnostic.test.cjs tests/recovery/transport.test.cjs tests/recovery/repair.test.cjs` | PASS: 70 tests, zero skips/failures |
+| UI interaction suite | PASS: 12; exact-baseline controls FAIL 2 assertions, 10 deliberately deselected (enabled never-enrolled and unverified backup action absent) |
+| Diagnostic baseline controls | FAIL: all 9 before; PASS: all 9 after; these establish diagnostic coverage, not the phone's request cause |
+| `npm run test:recovery` | FAIL after history addition: 492 pass, one test-file load failure (493 total), zero skips; missing Realm binding prevents the 10 encrypted-Realm scenarios from loading |
+| History reconciliation and upgrade/login tests | PASS: 27 Node cases (13 new); Version History Jest PASS: 9; exact-before controls FAIL: 4 actual-login cases and one actual-migration preservation case |
+| Installed-version header | PASS: 2 UI regressions; both FAIL before; native version/history disagreement tested in both directions without rewriting rows |
+| Supplemental current-backend upgrade witness | BLOCKED by missing Realm native binding; no passing upgraded-account integration claim |
+| Current Relay protected/legacy protocol tests on disposable Mongo | PASS: 45; readiness tests PASS: 7; backend only, not upgraded-app acceptance |
+| Whole ESLint | FAIL: 4450 errors / 882 warnings; R5 baseline 4451 / 882, first patch 4450 / 882; normalized zero added by the history addition |
+| Whole TypeScript | FAIL: 943 diagnostics; exact baseline 943; normalized zero added/removed |
+| Focused backup service ESLint | PASS: zero errors/warnings |
+| CI USDT/retired-configuration guard command | FAIL: 30 pass / 11 fail, all 11 require unavailable Ruby |
+| `npm run test:release` | FAIL at Ruby stage (exit 127); preceding Node 28 and Python 7 tests PASS |
+| Local-validation/protected-runner contract tests | PASS: 14 |
+| Android static/reproducibility Python tools | PASS: 31 |
+| Version, JSON parsing, new proof/runner syntax, whitespace | PASS |
+| iOS / Android app build, simulator/emulator, physical phone | NOT RUN; required exact-head native handoff remains NEEDS_LOCAL |
+
+The current-backend command, run in its separate exact checkout, was:
+
+```sh
+KEEPER_APP_SOURCE=/absolute/path/to/keeper-patch \
+BACKUP_TEST_MONGO_URL=mongodb://127.0.0.1:27038 \
+node --test tests/protectedBackup.test.cjs tests/legacyBackupReadOnly.test.cjs
+```
+
+The task-owned disposable Mongo container is stopped; its data/evidence are
+retained. Passing backend checks do not replace the blocked upgraded-account
+witness. Existing formatting/lint/type failures are reported, not waived. No
+independent cryptographic certification or release clearance is claimed.
+
+The history before-controls use isolated source
+`3c5f8d8ace5c211ed78264b1a460c4e06e060ceb` (before the owner-added history
+correction). The current-backend 45+7 results and release/tooling results were
+executed for that first patch and retained as prior evidence; they were not
+rerun after the history-only addition. Current full Jest/recovery, lint/type,
+version/input and targeted history checks are reported separately above. IOS,
+ANDROID, HARDWARE and the original phone still require exact-head acceptance.
diff --git a/docs/cloud-bootstrap-preparation.md b/docs/cloud-bootstrap-preparation.md
new file mode 100644
index 0000000000..70a5b4559a
--- /dev/null
+++ b/docs/cloud-bootstrap-preparation.md
@@ -0,0 +1,175 @@
+# Cloud bootstrap preparation
+
+This is an unpublished infrastructure-only preparation from known committed
+sources. It carries no native pass, app acceptance, signing or release approval.
+No unpublished files from the original task or the owner's Mac were migrated or
+backed up. The original task's working-tree state remains unknown.
+
+## Source identities
+
+Fresh branch/PR refs matched these checkpoints on 18 October 2026:
+
+| Source | Commit |
+| --- | --- |
+| sprint / bootstrap base | `def0d6a90c80287edb4f58ae272cbfc340f00d73` |
+| #7060 `codex/7059-hosted-native-validation` | `d865ca9c4f91532a1524443cc6da42d8d7b07e1a` |
+| #7062 `codex/7061-cloud-release-phase-a` | `59c821ce195a5c063d99045fd97b5ac605433f62` |
+| R5 #7058 | `625435ac26af0304670c993a639626b1117699ba` |
+| R4 #7045, excluded | `be89c34473bb6aab253b98325f1fe746ca391c6f` |
+
+#7060 descends from the verified sprint commit; #7062 is stacked on #7060.
+The preparation reuses #7060's `.github/` infrastructure and relevant Markdown,
+with diagnostic privacy corrections, action-pin regressions and these adoption
+notes. Its gate implementation is unchanged from #7060. Original gate contract
+cases are retained, with additional skipped-draft/latest-attempt regressions.
+Provenance, latest-attempt, explicit-failure and hardware requirements
+remain intact. No live protection, permission or credential setting changes.
+
+`package.json`, `yarn.lock`, `ios/Podfile.lock` and
+`ios/hexa_keeper/AppDelegate.mm` remain at sprint. R4's assessment document,
+source, refs, private fixtures and Mac work are not imported or changed. Phase A
+app probes/scenario matrices and Phase B signing/distribution are excluded.
+
+## Diagnostic and action-pin correction
+
+General tool failures and Maestro, Android, Metro and iOS startup collectors
+export fixed categories or fixed public startup labels. They never return
+arbitrary log excerpts, including unknown errors. The legacy metadata field
+`redacted_tool_errors` now contains category identifiers only. Synthetic privacy
+regressions exercise unlabelled private text, wallet-like data, spaced secrets,
+URLs/paths, encoded text, Unicode/control characters, multiline input and repeated
+messages. Collector tests check metadata and console output while retaining
+failed command and smoke outcomes. Raw logs remain private to the disposable
+runner. Categories indicate observed markers, not a diagnosis or a platform pass.
+
+The emulator action uses upstream commit
+`1dcd0090116d15e7c562f8db72807de5e036a4ed`, matching #7062. Read-only verification
+of `ReactiveCircus/android-emulator-runner` on 18 October 2026 returned:
+
+```text
+refs/tags/v2.34.0 324029e2f414c084d8b15ba075288885e74aef9c
+refs/tags/v2.34.0^{} 1dcd0090116d15e7c562f8db72807de5e036a4ed
+```
+
+The old #7060 value appended `38` to the tag object's SHA and was malformed.
+Host contracts require full 40-character immutable action pins in the two newly
+introduced workflows, matching the upstream revisions verified on the same date,
+including this exact emulator commit. They reject mutable tags, short/malformed
+revisions, unverified actions/SHAs and the annotated tag object. Existing action policy
+in unrelated workflows and the inherited gate is unchanged.
+
+Pin inspection parses YAML with the host's existing Python 3 and PyYAML, then
+checks every job-level and step-level `uses` value. Quoted/escaped keys, flow
+mappings, folded scalars and aliases cannot hide mutable actions alongside valid
+pins. Missing parser tooling, invalid YAML, duplicate mapping keys and non-string
+action references fail the contract; there is no regex fallback or dependency
+installation. Future host-contract environments must provide Python 3 and PyYAML.
+
+## Draft publication behavior
+
+Both hosted native jobs require a `pull_request` event with a literal boolean
+`draft: false` before allocating a runner. Drafts and missing/malformed draft
+state cannot start either native job. `ready_for_review` starts a new eligible
+native run; marking a PR ready therefore requires separate native-run/budget
+authorization. `converted_to_draft` triggers a skipped run in the same PR
+concurrency group, configured to cancel an older native run. Cancellation is
+best effort and cannot undo work already started while the PR was ready.
+
+The existing CI `Tests` install would otherwise invoke `prepare` and CocoaPods.
+For draft PRs only, it now uses frozen Yarn with lifecycle scripts disabled.
+The normal `Tests` job still runs and any install/Jest failure still fails it.
+No app manifest, lock or test changes are included. Ready/non-PR installs retain
+their existing behavior, and `ready_for_review` reruns CI so a draft installation
+result cannot replace the normal ready-PR test run. Lint's existing install
+already disables lifecycle scripts. The frozen dependency blocker is not waived.
+
+Automatic checks for this branch targeting sprint, from the checked-in triggers:
+
+| Event | Automatic behavior |
+| --- | --- |
+| Push `codex/cloud-bootstrap-privacy` with no PR | No checked-in workflow matches this branch's push event |
+| Open/reopen a draft; push new commits to an open draft (`synchronize`) | Linux CodeQL; CI Lint and Tests; Node/Python Native validation contracts; existing trusted local-validation gate. Hosted iOS/Android jobs are skipped before runner allocation |
+| Edit the draft PR description | Existing trusted local-validation gate refreshes; no native workflow trigger |
+| Mark ready for review | Native jobs become eligible; CI reruns the normal install/tests; trusted gate refreshes. CodeQL and host contracts retain their existing default PR event types |
+| Convert back to draft | Hosted-native concurrency cancellation/skip only; no new native runner. Previously started ready-PR CI is not retroactively undone |
+
+The trusted gate's existing docs/`.github` exemption can report success for this
+infrastructure PR. That is not native acceptance or installation/merge approval.
+For app PRs, skipped jobs/steps, even inside an overall successful workflow, supply
+no native pass; a newer skipped run/attempt cannot reuse an older native success.
+All provenance, explicit-failure and HARDWARE checks remain unchanged.
+
+This bootstrap contains no `workflow_call`, `workflow_dispatch` or job-level
+reusable-workflow call. The entry-path contracts check that boundary. #7062's
+`keeper-release-acceptance.yml` callers and `keeper-native-platform.yml` worker
+remain outside this patch. Before their separate restack/adoption, add the same
+draft guard at both caller jobs and the worker, retaining source/provenance/R4
+checks. The reusable worker receives the [caller's GitHub event context](https://docs.github.com/en/actions/reference/workflows-and-actions/reusing-workflow-configurations#github-context); a direct
+non-PR caller must not bypass the guard. These future paths are not claimed fixed
+or installed by this bootstrap.
+
+The remaining Linux checks consume hosted runner time. Available included minutes
+and billing limits have not been verified, so this is not a zero-cost guarantee.
+Confirm allowance before publishing under a no-paid-resources restriction; do not
+disable required checks or change billing/security settings to bypass it. No
+workflow has been dispatched or run as part of this source-only preparation.
+
+## Adoption order and remaining gates
+
+1. Independently review this infrastructure diff and its host contracts. Any
+ publication, PR change or merge requires separate owner authorization. Only a
+ reviewed installation on protected sprint can establish the workflow/harness
+ baseline. Candidate runs cannot authorize their own changed infrastructure.
+2. Reconcile the app and dependency changes separately against the approved
+ source baseline. This bootstrap deliberately leaves frozen-install blockers
+ unresolved. Do not unlock dependency installation, weaken gates or treat host
+ contracts as native evidence. R4 work and the owner's Mac remain untouched.
+3. Restack #7062's Phase A delta onto the adopted bootstrap in separately
+ authorized work. Do not merge its existing #7060 ancestry wholesale: that
+ would also import the four excluded app/dependency files. Reconcile
+ `hosted_native.py` changes while preserving the fixed-category exports and
+ privacy regressions; retain the corrected emulator pin and extend pin/draft
+ entry-path contracts and guards to Phase A's callers and worker. Update #7062's bootstrap references to
+ the actual adopted source. Phase A requires its own review and protected-base
+ installation before it can supply authoritative evidence.
+4. After the source baseline and frozen dependencies are reconciled, obtain
+ authorization and budget for actual exact-source native runs using unchanged
+ reviewed infrastructure. Record source SHA, workflow/run/attempt, each real
+ build/UI outcome and safe artifact identities. New source commits invalidate
+ old passes. Missing, skipped, cancelled, untrusted or failed evidence does not
+ become a pass; explicit local failures and HARDWARE gates still apply. R5's
+ feature acceptance remains separate from this startup smoke.
+
+Signing, distribution, uploads, deployment and publication remain separately
+approved operations. Phase B is not implemented or verified by this preparation.
+The optional private signing follow-up note is not a Phase A prerequisite.
+
+## Validation scope
+
+Use `node --test .github/tests/*.test.cjs` and
+`python3 -B -m unittest discover -s .github/tests -p 'test_*.py'`, plus available
+workflow lint, syntax and diff checks. The host suite uses synthetic fixtures and
+mocked native commands; it requires no app dependency installation, emulator,
+native compilation or Actions dispatch. Report actual results in the private
+handoff. A missing lint tool is a validation-tool blocker, distinct from a failed
+host contract or the setup-reported frozen app dependency installation failure.
+
+Private preparation results on 18 October 2026:
+
+| Check | Result |
+| --- | --- |
+| Node host contracts | PASS: 53 tests, including gate, shim, action-pin and draft-entry contracts |
+| Python host contracts | PASS: 35 tests, including 5 adversarial privacy tests with subcases |
+| JavaScript and Python syntax | PASS |
+| Changed YAML syntax | PASS: installed PyYAML, 5 files; not workflow semantic lint |
+| Staged diff whitespace and scope | PASS: only `.github/` and relevant Markdown; excluded app files unchanged |
+| Workflow semantic lint (`actionlint`) | NOT RUN: executable unavailable; nothing installed |
+| App dependency installation / app tests | NOT RUN here; setup-reported frozen-install failure remains unresolved |
+| Native builds, simulators/emulators, hardware | NOT RUN |
+| Actions dispatch, signing/distribution, deployment | NOT RUN |
+
+The privacy regression suite was also applied to the original #7060 harness as a
+negative control: all 5 tests failed (168 assertion/subcase failures, no execution
+errors), confirming the tests detect the original exports. Those are intentional
+baseline failures, not failures of this prepared diff. No live native evidence or
+CI run from another SHA is credited to this preparation.
diff --git a/docs/cloud-release-pipeline.md b/docs/cloud-release-pipeline.md
new file mode 100644
index 0000000000..387bf3c353
--- /dev/null
+++ b/docs/cloud-release-pipeline.md
@@ -0,0 +1,191 @@
+# Permanent cloud release pipeline
+
+[Issue #7061](https://github.com/KeeperCommunity/bitcoin-keeper/issues/7061)
+establishes the default process for R5 and every later Keeper release: cloud code
+completion, hosted native acceptance, authorized physical testing, independent
+review, and separately approved signing/distribution/publication. R5 is the first
+rollout, not a special workflow. The target is zero ongoing dependency on the
+release owner's personal Mac; hosted iOS jobs still use macOS and physical
+checks still need suitable phones/signers and authorized people.
+
+This document describes the Phase A candidate and the separate Phase B plan.
+It does not grant merge, signing, upload, submission or publication approval.
+
+## Current capability and adoption
+
+Status snapshot: 2026-10-18. Recheck linked PRs and current trusted workflows at
+each handoff; these initial blockers are not evidence about a later head.
+
+| Capability | Current state and evidence boundary |
+| --- | --- |
+| Hosted development builds and account-free startup smoke | #7060 has actual iOS and Android build/UI passes at `d865ca9c4f91532a1524443cc6da42d8d7b07e1a`, run [39024530330](https://github.com/KeeperCommunity/bitcoin-keeper/actions/runs/39024530330). It remains an unmerged draft. That evidence belongs only to its tested source. |
+| Reusable Phase A release acceptance | Candidate infrastructure stacked on #7060. Its local contract checks are distinct from actual hosted builds/UI execution. R5 native and release acceptance remain **NOT VERIFIED** until R5's own exact head runs after trusted installation and baseline reconciliation. |
+| R5 feature/security matrix | **BLOCKED / NOT VERIFIED** until the relevant R4 baseline is reconciled and R5's own deletion/reference, setup/persistence, account-isolation and recovery/regression cases actually run. Representative probes do not waive missing or failed cases. |
+| Protected signed beta and store delivery | Phase B: **NOT IMPLEMENTED / NOT VERIFIED**. Existing Fastlane lanes are not a validated cloud release workflow. |
+| Physical phone/signer acceptance | **NOT VERIFIED** without named authorized tester reports for the exact approved distributed artifact. Hosted simulators/emulators supply no physical credit. |
+
+The Phase A action-pin contract also found a malformed inherited Android
+emulator-action reference in #7060. The new worker uses the verified v2.34.0
+commit; resolve/review the dependency reference in #7060 before installation.
+Its historical successful run is not proof that the malformed literal works.
+
+The active R4 PR [#7045](https://github.com/KeeperCommunity/bitcoin-keeper/pull/7045)
+and its existing process remain untouched. Do not update its source, refs,
+fixtures, Mac work, gate or approvals to adopt this pipeline. Do not transfer
+#7060's or this candidate's results to R4 or
+[R5 #7058](https://github.com/KeeperCommunity/bitcoin-keeper/pull/7058).
+
+Before adoption, independently review #7060's workflow, dependency and iOS-native
+changes against R4's eventual released baseline. Obtain owner approval before
+merging it. Then review the separate Phase A candidate and install its reviewed
+workflows on `sprint` only with approval. A stacked candidate can test its
+infrastructure, but cannot certify its own untrusted CI or bypass the currently
+required `keeper/local-validation` and `Tests` checks. Preserve the existing safe
+Local fallback until the applicable hosted capability is proven.
+
+## Phase A: reusable hosted acceptance
+
+The shared platform job is `.github/workflows/keeper-native-platform.yml`
+(`workflow_call`); `.github/workflows/keeper-release-acceptance.yml` invokes it for
+PRs targeting `sprint`. The trigger applies to future release/app PRs without a
+version-specific selector or manual workflow copy. The explicit active-R4 #7045
+exclusion prevents this rollout from starting new work on that release.
+
+Each run must use the full current PR head SHA and a disposable development
+configuration, with read-only repository access, no persisted checkout credential
+and no production signing/service secrets. Native builds execute PR-controlled
+source on disposable runners; independent source/CI review remains necessary.
+Reviewed workflow/harness provenance and actual step outcomes must be checked
+before treating a run as trusted evidence. Changing CI infrastructure requires
+review before it supplies authoritative acceptance.
+
+Preflight compares the caller, shared worker, existing #7060 workflow and the
+complete native harness against the exact app source, the current `sprint` base
+and the event's original base. The summary also verifies the newest Actions run,
+its exact attempt, PR association and actual native job/step results through the
+read-only Actions API. A partial rerun cannot reuse an earlier attempt's pass.
+Required executable files must exist as ordinary
+files in all three snapshots. Missing installation, changed CI, fork provenance
+or a concurrent source/base change supplies no native credit. Consequently this
+stacked candidate **skips its new native jobs** before reviewed installation.
+The full acceptance summary deliberately fails even if both primitive probe jobs
+pass: five required app scenarios are still **NOT IMPLEMENTED**. Extending those
+scenarios requires executable tests and review, not changing a status/waiver.
+
+The bounded representative matrix extends #7060's startup smoke with a separate
+development-only probe entrypoint using real native Realm/MMKV modules and the
+current app schema. Across three process launches it seeds synthetic wallet
+records, checks persistence and separate Realm-file isolation, rejects a wrong
+Realm encryption key, checks transaction rollback and targeted Realm deletion,
+then verifies persistence and deletes its disposable state. Its wallet records
+contain an invalid public sentinel, with no fundable keys. This verifies native
+storage primitives, not product key deletion/reference protections, app account
+isolation, setup/retry behavior, recovery, upgrade or release performance.
+
+Use only job-created throwaway state: no Mac accounts, keystores, private signer
+material, historical fixtures, funding or live signing. The summary must fail
+full acceptance when required R5 app/security cases are missing, blocked or
+failed. Keep the matrix small enough to fit the hosted job budget; expand
+coverage only for a concrete release risk.
+
+For every release, the Cloud handoff records:
+
+- Full PR head SHA and PR URL; required `IOS`, `ANDROID` and, when applicable,
+ `HARDWARE` checks.
+- Workflow run URL/attempt and actual build, startup, integration and timing
+ outcomes for each platform: `PASS`, `FAIL`, `NOT RUN` or `BLOCKED`.
+- Safe artifact identity/hashes and the exact scenarios exercised, with missing
+ feature/security cases and failures kept explicit.
+- Remaining physical checks, assigned tester and any required owner decision.
+
+Use the existing **Codex local handoff**, `State: NEEDS_LOCAL` and `Required local
+checks` fields in [AGENTS.md](../AGENTS.md). These are the current gate's protocol;
+the default execution destination for R5/future native work is hosted CI.
+`Local checks requested: NONE` is appropriate only when trusted hosted evidence
+satisfies all required native checks and no physical checks remain. Otherwise
+describe the actual fallback or physical work. Do not invent a passing Local
+report to represent a hosted run.
+
+A new head commit invalidates previous native evidence and owner scope decisions.
+Rerun both platforms on that head. Retain bounded safe metadata and diagnostic
+outcomes on failure; do not upload raw logs, credentials, generated account data,
+screenshots or development app bundles just to document a pass. A development
+artifact hash is not a signed beta identity. Follow the trust, bootstrap, runner
+budget and evidence rules in [hosted native validation](hosted-native-validation.md).
+
+### Staged runner budget
+
+The current R4 gate and #7060 startup workflow stay unchanged. During staged
+adoption, each eligible app PR push can therefore run the original startup pair
+as well as the new build/probe pair. The original caps are 65 iOS / 60 Android
+minutes; the new shared worker caps each platform at 75 minutes, builds once and
+runs startup plus native storage probes. Neither has automatic retries. The
+combined ceiling is 275 runner-minutes per push, approximately $9.49 if billable
+at the reference rates in [hosted validation](hosted-native-validation.md), before
+allowances/storage/other CI. This is a planning ceiling, not observed runtime or
+an account bill. The uninstalled candidate starts no new native jobs.
+
+Consolidating those platform builds and their trusted gate consumer needs a later
+reviewed change after the R4 noninterference constraint permits it. Do not alter
+R4's current gate or discard failed evidence to reduce this rollout's cost.
+
+## Phase B: separate protected delivery workflow
+
+**NOT IMPLEMENTED / NOT VERIFIED.** Deliver this in a separate PR with a short
+scope estimate before implementation. Keep Phase A focused; split or defer work
+if a phase approaches approximately 20,000 changed code/test tokens or contains
+two substantial independent features.
+
+Review the existing `ios/fastlane/Fastfile` and `android/fastlane/Fastfile` before
+choosing hosted macOS/Linux delivery, or Xcode Cloud for iOS. Inventory these
+prerequisites with the owner; record credential owners and availability without
+copying secret values into issues, PRs, logs or artifacts:
+
+| Area | Setup to resolve before signing/distribution |
+| --- | --- |
+| iOS | Apple team/app identifiers, distribution certificate/private-key custody, provisioning profiles, App Store Connect upload authorization, TestFlight groups and approved channel mappings. |
+| Android | Package identity, existing upload-key custody and alias, Play App Signing status, least-privileged Play service account, internal-test track and tester access. Never regenerate an upload key without authorization. |
+| Both | Reviewed production configuration, immutable commit/version/build identity, fresh store histories/counters, protected environments and approvers, retained artifact hashes/signatures/provenance and distribution receipts. |
+
+Audit tracked native signing configuration for embedded credential fields without
+printing their values. If values may be live, use the project's private security
+process and plan replacement/rotation with the owner. Do not assume tracked
+values are valid, usable or safe to reuse. Existing Fastlane build-number
+mutation and immediate upload behavior must be reviewed for exact-artifact and
+approval controls before being used remotely.
+
+The release-only workflow must accept trusted reviewed release source and bind
+its exact commit, version, build and channel. Production secrets belong only in
+least-privileged protected environments, never a PR job. Require explicit owner
+approval before signing and before any TestFlight/Play internal upload or other
+distribution. Preserve the signed artifact's hash, signature identity, provenance
+and upload receipt; testers and publication decisions must refer to that same
+artifact. Require separate explicit owner approval for external submission and
+public publication. Never treat a passing build, gate or beta test as approval.
+
+One-time account/provisioning/key-custody setup may require the owner. Describe
+that setup honestly; it is separate from an ongoing requirement to unlock the
+owner's Mac for each release.
+
+## Physical checks and final review
+
+Assign a named trusted tester/maintainer, or a securely operated device facility
+for supported cases, to install the approved TestFlight/Play internal artifact.
+Record the artifact hash/build/channel and head SHA, tester, phone OS/model,
+signer model/firmware, requested scenarios, actual outcomes and unresolved cases.
+Exercise real biometrics, cameras, NFC/USB/BLE, hardware signers and relevant
+policy/recovery behavior on the devices that support them. A simulator report
+cannot stand in for those results.
+
+Use owner-approved physical scope and retain [the existing exact-SHA HARDWARE
+deferral and critical-defect restrictions](../AGENTS.md#owner-directed-post-release-test-scope).
+A failed check or high-risk issue involving keys, recovery, funds, backups or
+incorrect signing stays blocking. Owner deferral must remain honest about
+unrun cases and cannot waive a required failed platform or physical result.
+
+Independent review, feature/security acceptance, artifact/version checks and
+explicit per-release approvals remain separate from CI. Report each unproven
+capability as **NOT IMPLEMENTED / NOT VERIFIED**, preserve current safe fallback,
+and state the next concrete action. Future releases reuse these reviewed shared
+workflows; only their source, versions, relevant acceptance cases, artifact and
+approvals change.
diff --git a/docs/hosted-native-validation.md b/docs/hosted-native-validation.md
new file mode 100644
index 0000000000..0191244736
--- /dev/null
+++ b/docs/hosted-native-validation.md
@@ -0,0 +1,198 @@
+# Hosted native validation
+
+This infrastructure-only bootstrap reuses issue #7059 / PR #7060's bounded hosted
+development builds and disposable first-use UI smoke. It excludes that PR's app
+and dependency changes. See [bootstrap preparation and adoption order](cloud-bootstrap-preparation.md)
+for exact committed sources, exclusions and the relationship to Phase A #7062.
+It does not change R4 #7045 or R5 #7058 app code, merge either branch, change branch
+protection, or approve a release. Adopt it for R5 after R4's released baseline is
+settled and R5 is reconciled against that baseline.
+
+## Handoff
+
+Draft publication skips both native jobs before runner allocation. The existing
+host checks still run; the draft `Tests` dependency install disables lifecycle
+scripts to avoid invoking native setup. See the [draft event table and budget
+limits](cloud-bootstrap-preparation.md#draft-publication-behavior). Skipped native
+jobs supply no platform pass. Marking ready for review enables native work and
+requires separate authorization and budget; a draft is not a trust installation.
+
+1. **Cloud code complete:** push the final code, run suitable regression checks,
+ and record the full PR head in the existing `Codex local handoff`. Keep
+ `Required local checks: IOS, ANDROID` and add `HARDWARE` when applicable.
+2. **Hosted native validation:** the PR workflow checks out that exact head with
+ read-only permissions and no persisted checkout credential. Both platform jobs
+ install locked dependencies, build the development app and run the disposable
+ startup smoke. Report each platform as `PASS`, `FAIL` or `NOT RUN` with the run
+ URL, attempt and tested SHA. A successful build without a successful UI smoke
+ is not a platform pass. Any new commit starts this step again.
+3. **Remaining native and physical checks:** assign an authorized tester to the
+ remaining feature-specific cases, fallback builds/UI when hosted setup fails,
+ and physical-device cases; do not assume the owner's Mac is available. Real
+ biometrics, phones/cameras, hardware signers, NFC/USB and signing prompts remain
+ explicit. Preserve the existing owner-scoped HARDWARE deferral procedure. A
+ later local `LOCAL_FAILED`/`BLOCKED` report cannot be hidden by a hosted pass.
+4. **Release review:** inspect the actual exact-head evidence and unresolved
+ issues, obtain independent review and explicit owner approval for any signing,
+ distribution or submission. CI success grants none of those approvals.
+
+Hosted coverage is deliberately narrow: cold startup to the passcode screen and
+entry of a throwaway first passcode through the confirmation screen. Stop before
+account/key generation, backup, wallet funding, live transactions or signer use.
+Do not mistake this smoke for the R5 deletion matrix, recovery/upgrade validation,
+startup performance acceptance or complete release readiness.
+
+## Trust and gate behavior
+
+The existing trusted base-branch gate never checks out or executes PR code and
+retains its `keeper/local-validation` status name. The new native workflow uses
+`pull_request`, never elevated `pull_request_target` execution. No signing,
+environment secrets, release credentials or production configuration are passed
+to its jobs.
+
+The gate reads Actions metadata itself. It selects the newest run at the current
+source SHA, verifies the workflow path, event, source repository/branch, associated
+PR and SHA, and compares every workflow/harness file (including additions and
+deletions) against both the current base and the run's base. The latest attempt
+must have exactly one successful platform job with successful `Build development
+app` and `Run disposable startup smoke` steps. A cancelled/pending run supplies no
+pass. A completed run whose other platform failed can still supply its genuinely
+successful platform. Partial reruns may lack the other platform in the latest
+attempt; use **Re-run all jobs** to establish both platforms together.
+
+Missing metadata, API failures, untrusted changed CI files and incomplete evidence
+produce zero hosted passes. Existing local reports remain a fallback. HARDWARE
+cannot be filled by simulator evidence. New commits also invalidate owner scope
+decisions. Owner deferral still needs a later honest local report recording
+physical checks as NOT RUN/DEFERRED; an actual failed physical test cannot be
+deferred. No PR-author assertion of a hosted result is parsed as evidence.
+
+This verifies reviewed CI provenance and actual GitHub step results. The native
+build still executes PR-controlled Gradle/Xcode/Metro code on its disposable
+runner. Integrity checks detect tracked harness changes between phases, but do
+not provide an adversarial sandbox against malicious same-user build scripts.
+Review native source and CI changes before merging; branch review requirements
+remain necessary. The gate does not make an unreviewed app trustworthy.
+
+Bootstrap is intentionally staged: this infrastructure PR can run diagnostics and
+test the verifier, but its new workflow is not yet in the protected base, so its
+hosted results cannot authorize app PRs. Review and merge the CI-only PR only when
+the owner approves. Then a new same-repository PR run using unchanged reviewed CI
+files can provide evidence. Fork runs and modified native CI need review/local
+fallback. The workflow-run listener is also effective only after the trusted gate
+is merged; pre-merge gate tests execute the candidate inline script with mocked
+API responses, not a privileged checkout of the candidate.
+
+## Dependency and native-install failures
+
+Use Yarn 1's frozen lock install with lifecycle scripts disabled, followed by the
+explicit CI preparation in `.github/native/`. The repository's normal `prepare`
+unconditionally invokes CocoaPods and writes a Mac-specific Android SDK path;
+running it on Linux is not supported. Do not silently regenerate `yarn.lock`, use
+an unlocked install, skip patch failures or replace a failed native build with
+Jest. CocoaPods deployment mode likewise exposes Podfile/lock drift.
+
+The pinned Node compatibility tool is restricted to setup.sh's existing shim
+whitelist without invoking its installer. Unrestricted `--hack` rewrites imports
+to optional packages that the manifest does not contain; the bounded wrapper
+keeps both platform Metro graphs resolvable using committed dependencies. Android
+command-line tools are provisioned explicitly before SDK/NDK installation.
+
+The #7060 source checkpoint documents dependency drift at sprint
+`def0d6a90c80287edb4f58ae272cbfc340f00d73`: missing Yarn lock selectors and older
+IAP/Nitro Pod-lock selections. Those app/dependency repairs are excluded here.
+The private environment's setup reported a failed frozen app dependency install;
+this preparation neither repeats nor repairs it. Host contracts do not validate
+app installation or either native platform.
+
+The inherited native lock-repair path is diagnostic only: if separately
+authorized, it fails without building/testing and retains a candidate lock for
+review. It is not enabled or run by this bootstrap. Dependency repair belongs in
+a separate reviewed source change; an authoritative native run must use frozen
+Yarn and `pod install --deployment`. New source commits require new native results.
+Do not import the ongoing R4 diagnostic/reproducibility branch or its private
+fixtures. Its existing Android build diagnostics do not constitute emulator UI
+evidence.
+
+## Evidence, runner budget and remaining work
+
+Each platform retains allowlisted source/toolchain/runner metadata, actual command
+exit outcomes and fixed diagnostic categories. Diagnostic Pod-lock repair
+may also retain its dependency-lock candidate; it cannot report a platform pass.
+Development configuration points service integrations at
+loopback and uses dummy Firebase identities. Only the bounded first-use scenario
+runs on fresh hosted devices. Raw build/device/Metro/Maestro logs, screenshots,
+app bundles, keystores and generated account data are not uploaded. Failed raw
+command output stays private to the ephemeral runner; metadata records which
+command failed. Keep artifacts for seven days.
+
+On startup failure, metadata may include fixed Maestro command/assertion labels,
+Metro failure categories and Android/iOS error categories from this job's fresh
+account-free device. No error message, path, arbitrary exception name or suffix is
+copied from those logs. The schema-1 `redacted_tool_errors` field retains its name
+for compatibility but now holds only fixed category identifiers. Unrecognized
+text supplies no category; an empty diagnostic list never means success. CLI
+failures also omit arbitrary exception text. Diagnostic collection cannot change
+a failed result. Cold development
+bundling has a three-minute initial-screen allowance and seven-minute Maestro
+command limit, with all UI assertions still required. This is not release
+performance acceptance. The iOS build command is limited to the hosted
+simulator's architecture and 40 minutes; Android's build command is capped at
+35 minutes.
+
+Before the iOS build, a separate disposable simulator checks Maestro's driver
+with a bounded `hierarchy` command. This is setup only: it installs no Keeper app
+and supplies no app build or UI credit. Its private XDG state and fixed diagnostic
+flags remain separate from the later smoke. The command is capped at five
+minutes, with Maestro's driver timeout unchanged; owned simulator cleanup runs
+on success or failure.
+
+For both platforms, a bounded loopback request compiles the development bundle
+before iOS simulator creation or Android app installation; only its HTTP status,
+byte count and hash are retained.
+This setup step supplies no native/UI pass. On failure, fixed startup-screen
+flags may be derived from bounded private Maestro hierarchy snapshots, without
+retaining their text or attributes. The iOS exception collector reads the first
+MiB of compact own-process output over the launch window, preserving early
+errors instead of parsing a truncated JSON array. Missing diagnostics remain
+explicit and do not imply a clean runtime.
+
+The iOS job is capped at 65 minutes and Android at 60 minutes, with command and
+emulator boot limits inside those budgets. The jobs have no automatic retries;
+new pushes cancel only
+this workflow's runs for that PR. Cold native compilation, SDK installation and
+CocoaPods can consume substantial hosted minutes. Use job timestamps and the
+Actions usage page to report observed runtime and cost; do not describe a failed
+dependency preflight's short duration as native-build timing. Current pricing,
+included minutes and spending limits depend on the repository's plan.
+As checked on 2026-10-17, GitHub's [standard runner rates](https://docs.github.com/en/billing/reference/actions-runner-pricing)
+are $0.062/minute for macOS and $0.006/minute for Linux x64. At those rates a
+30-minute iOS plus 30-minute Android attempt is about $2.04; reaching both job
+caps is about $4.39, before included minutes, artifact storage, rounding and the
+existing CI jobs. These are planning estimates, not measured native timings or
+an account bill. These rates were inherited from #7060 and were not rechecked in
+this source-only preparation. Observed bootstrap results belong in the validation report.
+Enable spending limits before routine use if needed.
+
+Any later validation report must record the actual source/run/attempt and each
+platform's build/UI outcome. This preparation runs no native workflow. Until both
+strict native builds and actual UI runs
+work reliably, use the existing local fallback without interrupting an active Mac
+session. A passing startup smoke does not transfer to another PR or prove its
+feature matrix. R4 and its existing Local evidence remain outside this bootstrap.
+Hardware and release approval remain separate.
+
+## Administrative configuration
+
+Require `keeper/local-validation` and existing `Tests` for merges to `sprint`,
+and require review for changes to the gate/native harness. `Native validation
+contracts` is a useful additional required check. Do not require both native jobs
+unconditionally when local fallback is intended: the combined gate resolves
+platform evidence. Administrators should verify the required status app/source,
+default-branch workflow availability, Actions runner permissions and private-repo
+minute budget. The inherited #7060 report states that on 2026-10-17 the active
+branch-rules endpoint reported required
+`keeper/local-validation` and `Tests` checks from GitHub Actions (integration
+15368). The legacy branch-protection endpoint returned HTTP 403; broader
+administrator and bypass settings remain unverified. These settings were not
+rechecked or changed by this source-only preparation.
diff --git a/docs/miniscript-witness-fee-sizing.md b/docs/miniscript-witness-fee-sizing.md
new file mode 100644
index 0000000000..2764391929
--- /dev/null
+++ b/docs/miniscript-witness-fee-sizing.md
@@ -0,0 +1,90 @@
+# Miniscript witness fee sizing: bounded CodeQL correction
+
+## Source and alert evidence
+
+The investigation starts at R5 PR #7082, commit
+`3eb92fc8a622a3e09926d49f47243c163e32d009`. Its operations module is blob
+`db29ee432496e84bc70be82b0d9a3017e154888d`. The fee-input helper is byte-identical
+in `sprint` at `def0d6a90c80287edb4f58ae272cbfc340f00d73` (module blob
+`7401a3ffcc234cb948f282f27fd36976176020a7`). This separate PR targets `sprint`
+with only the correction and regression evidence; it does not integrate R5.
+
+[Security check 119985857101](https://github.com/KeeperCommunity/bitcoin-keeper/runs/119985857101)
+reports one High finding at `operations/index.ts:110–111`: **Incomplete
+multi-character sanitization**, with the message that the string may still
+contain `