Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 45 additions & 3 deletions apps/mobile/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -1886,9 +1886,50 @@ function SecurityGate(props: AppProps) {
useNativeTranslation();
const state = useSyncExternalStore(securityPreferences.subscribe, securityPreferences.getSnapshot, securityPreferences.getSnapshot);
const viewLock = useSyncExternalStore(publicViewLock.subscribe, publicViewLock.getSnapshot, publicViewLock.getSnapshot);
useEffect(() => { if (state.status !== 'ready') { custodyIdle.allowNewInput(); watchIdle.allowNewInput(); } }, [state.status]);
useEffect(() => { void securityPreferences.load().catch(() => undefined); void publicViewLock.load().catch(() => undefined); return () => { custodyIdle.invalidate(); watchIdle.invalidate(); }; }, []);
return state.status === 'ready' && (viewLock.phase === 'unlocked' || viewLock.phase === 'locked') ? <IdleActivityBoundary><WalletModalHost><AppContent {...props} /></WalletModalHost></IdleActivityBoundary> : <Screen><Header title={nativeI18n.t('mobile.shellViews.app.securitySettings')} /><Notice title={state.status === 'opening' || viewLock.phase === 'opening' ? nativeI18n.t('mobile.shellViews.app.openingSecuritySettings') : nativeI18n.t('mobile.shellViews.app.securitySettingsUnavailable')} body={nativeI18n.t('mobile.shellViews.app.yourSavedDataHasNotBeenReplacedRetry')} />{(state.status === 'unavailable' || viewLock.phase === 'unavailable') && <Button title={nativeI18n.t('mobile.shellViews.app.retrySecuritySettings')} onPress={() => { void securityPreferences.load().catch(() => undefined); void publicViewLock.load().catch(() => undefined); }} />}</Screen>;
const [checking, setChecking] = useState(false);
const pending = useRef<Promise<unknown> | null>(null);
const ready = state.status === 'ready' && (viewLock.phase === 'unlocked' || viewLock.phase === 'locked');
const unavailable = !checking && (state.status === 'unavailable' || viewLock.phase === 'unavailable');
const loadSettings = useCallback(() => {
if (pending.current) return;
setChecking(true);
const attempt = Promise.allSettled([securityPreferences.load(), publicViewLock.load()]);
pending.current = attempt;
void attempt.then(() => {
if (pending.current !== attempt) return;
pending.current = null;
setChecking(false);
});
}, []);
useEffect(() => {
if (ready) return;
custodyIdle.allowNewInput();
watchIdle.allowNewInput();
}, [ready, state.status]);
useEffect(() => {
loadSettings();
return () => {
pending.current = null;
custodyIdle.invalidate();
watchIdle.invalidate();
};
}, [loadSettings]);
if (ready && !checking) {
return <IdleActivityBoundary><WalletModalHost><AppContent {...props} /></WalletModalHost></IdleActivityBoundary>;
}
return (
<SafeAreaView style={s.securityGate} edges={['top', 'bottom']}>
<Screen>
<Header title={nativeI18n.t('mobile.shellViews.app.securitySettings')} />
<Notice
title={nativeI18n.t(unavailable ? 'mobile.shellViews.app.securitySettingsUnavailable' : 'mobile.shellViews.app.openingSecuritySettings')}
body={unavailable ? nativeI18n.t('mobile.shellViews.app.yourSavedDataHasNotBeenReplacedRetry') : undefined}
announce
/>
{unavailable && <Button title={nativeI18n.t('mobile.shellViews.app.retrySecuritySettings')} onPress={loadSettings} />}
</Screen>
</SafeAreaView>
);
}
export default function App(props: AppProps = {}) {
return (
Expand All @@ -1898,6 +1939,7 @@ export default function App(props: AppProps = {}) {
);
}
const s = StyleSheet.create({
securityGate: { flex: 1, backgroundColor: colors.bg },
appOuter: { flex: 1, backgroundColor: '#040b16', alignItems: 'center' },
app: { width: '100%', maxWidth: 520, flex: 1, backgroundColor: colors.bg },
center: {
Expand Down
21 changes: 17 additions & 4 deletions apps/mobile/scripts/owned-build-child.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -9,15 +9,19 @@ function interruptedError(signal, preserveLock = false) {
});
}

function unconfirmedChildTree() {
return Object.assign(new Error('Native child-tree shutdown could not be confirmed.'), { preserveLock: true });
}

/** Only the new child's process group is signalled; never the caller's terminal group. */
async function runOwnedBuildChild(command, args, { cwd, env, signal }) {
if (signal.aborted) throw interruptedError(signal.reason);
const grouped = process.platform !== 'win32';
const child = spawn(command, args, { cwd, env, stdio: 'inherit', detached: grouped });
let spawnError, forceTimer, timeoutTimer, signallingError, closed = false, rejectClose;
let deadline, retiring = false;
let deadline, unverifiedUntil, retiring = false;
const send = value => {
if (!child.pid) return;
if (!child.pid || unverifiedUntil !== undefined) return;
try {
if (grouped) process.kill(-child.pid, value);
else child.kill(value);
Expand Down Expand Up @@ -59,17 +63,26 @@ async function runOwnedBuildChild(command, args, { cwd, env, signal }) {
let abandoned = false;
if (grouped && child.pid) {
for (;;) {
if (unverifiedUntil !== undefined && performance.now() >= unverifiedUntil)
throw unconfirmedChildTree();
try { process.kill(-child.pid, 0); }
catch (error) {
if (error.code === 'ESRCH') break;
throw Object.assign(new Error('Native child-tree shutdown could not be confirmed.'), { preserveLock: true });
if (process.platform !== 'darwin' || error.code !== 'EPERM' || !retiring)
throw unconfirmedChildTree();
if (unverifiedUntil === undefined) {
// Darwin can briefly report EPERM as a process group disappears.
// Recheck without targeting a group we can no longer verify.
unverifiedUntil = performance.now() + Math.min(250, deadline - Date.now());
clearTimeout(forceTimer);
}
}
// A direct child exit is not proof that its descendants stopped. Retire
// abandoned work even on exit zero; it must not overlap the next phase.
abandoned = true;
retire('SIGTERM');
if (signallingError || Date.now() >= deadline)
throw Object.assign(new Error('Native child-tree shutdown could not be confirmed.'), { preserveLock: true });
throw unconfirmedChildTree();
await new Promise(resolve => setTimeout(resolve, 50));
}
}
Expand Down
42 changes: 39 additions & 3 deletions apps/mobile/src/activity/nativeActivity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ import {
getEvmSettlementStatus,
type EvmSettlementStatus,
} from '../../../../source/utils/evmReplacement.ts';
import type { EvmObservationRequest, EvmTransactionObservation } from '../../../../source/shared/evmTransactionObservation.ts';
import { getObservedEvmTerminalPhase, type EvmObservationRequest, type EvmTransactionObservation } from '../../../../source/shared/evmTransactionObservation.ts';
import type { SmartAccountAuthorizationSummary } from '../../../../source/wallet/smartAccountAuthorization.ts';
import type { SmartAccountAuthorizationObservation } from '../../../../source/utils/smartAccount/authorizationStatus.ts';
import type { NativeTokenPortfolioScope } from '../portfolio/tokenRegistry.ts';
Expand Down Expand Up @@ -180,7 +180,11 @@ type RetainedObservationWork = {
queue: LocalActivityRecord[];
seen: Set<string>;
workers: number;
retry?: ReturnType<typeof setTimeout>;
};
const RECENT_SUBMISSION_MS = 5 * 60_000;
const PENDING_RECEIPT_INTERVAL_MS = 15_000;
const OLDER_RECEIPT_INTERVAL_MS = 60_000;
const initial = (): NativeActivitySnapshot =>
Object.freeze({
status: 'locked',
Expand All @@ -207,6 +211,7 @@ export class NativeActivity {
private viewSaveFailed = false;
private viewSaveAttempt = 0;
private listeners = new Set<() => void>();
private connection: object | null = null;
private scope: EvmActivityReadScope | null = null;
private scopeRevision: number | null = null;
private refreshingRows: ReadonlyMap<string, ActivityRow> | null = null;
Expand Down Expand Up @@ -276,8 +281,11 @@ export class NativeActivity {
for (const listener of this.listeners) listener();
}
connect(): () => void {
const connection = {};
this.connection = connection;
let revision = -1;
const update = () => {
if (this.connection !== connection) return;
const state = this.source.getSnapshot();
if (state.revision === revision) return;
revision = state.revision;
Expand All @@ -290,6 +298,8 @@ export class NativeActivity {
update();
return () => {
unsubscribe();
if (this.connection !== connection) return;
this.connection = null;
this.stop();
this.publish(initial());
};
Expand All @@ -308,7 +318,10 @@ export class NativeActivity {
this.pendingRows = [];
this.pendingCursor = undefined;
this.pagedLocals.clear();
this.retainedWork?.lifetime.abort();
if (this.retainedWork) {
clearTimeout(this.retainedWork.retry);
this.retainedWork.lifetime.abort();
}
this.retainedWork = undefined;
this.hydration = [];
this.checking.clear();
Expand Down Expand Up @@ -1064,9 +1077,32 @@ export class NativeActivity {
for (const local of candidates) if (!work.seen.has(local.hash)) {
work.seen.add(local.hash); work.queue.push(local);
}
const pending = () => [...this.locals.values()].filter(local => {
if (this.pagedLocals.has(local.hash) ||
local.phase !== 'attempted' && local.phase !== 'submitted' ||
this.observations.get(local.hash)?.block) return false;
const observation = this.retainedObservations.get(local.hash);
return !observation || !getObservedEvmTerminalPhase(observation, local.nonce);
});
const pump = () => {
const count = Math.min(2 - work.workers, work.queue.length);
if (count <= 0 || work.lifetime.signal.aborted) return;
if (work.lifetime.signal.aborted) return;
if (count <= 0) {
if (work.workers || work.retry !== undefined || !this.connection) return;
const unsettled = pending();
if (!unsettled.length) return;
const recent = unsettled.some(local => Date.now() - local.createdAt < RECENT_SUBMISSION_MS);
// Recheck only open submissions. Preserve the history and its pagination
// while the existing scoped receipt reader checks for settlement.
work.retry = setTimeout(() => {
work.retry = undefined;
try { guard(); } catch { return; }
if (work.workers || work.queue.length) return;
work.queue.push(...pending().filter(local => !this.checking.has(local.hash)));
pump();
}, recent ? PENDING_RECEIPT_INTERVAL_MS : OLDER_RECEIPT_INTERVAL_MS);
return;
}
const lifetime = work.lifetime.signal;
const wave = count > 1
? this.receipts.retainedWave?.(scope.network, this.receiptScope(scope, generation), lifetime, guard)
Expand Down
6 changes: 6 additions & 0 deletions apps/mobile/src/custody/keyringRuntime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1358,6 +1358,12 @@ export function createKeyringRuntimeFactory(
),
metadata, replacement, retainUnsignedNative: retention?.retainUnsignedNative,
onUnsentDappDiscarded: retention?.onUnsentDappDiscarded,
// Signed simulation can disclose the UserOperation, so only the
// separate, undispatched payer envelope can be retracted.
smartPayerCleanupSession: selected.type === 'SmartAccount' && assertSmartAdmission &&
metadata?.smartAccountExecution === true
? { keyring: transactionRecordKeyring(keyring, checkWalletOwner), assertCurrent: checkWalletOwner }
: undefined,
walletSendCleanupSession: (retention?.walletSend || retention?.onUnsentDappDiscarded) && selected.type !== 'SmartAccount'
? { keyring: transactionRecordKeyring(keyring, checkWalletOwner), assertCurrent: checkWalletOwner }
: undefined,
Expand Down
22 changes: 20 additions & 2 deletions apps/mobile/src/platform/security.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,33 @@ import * as SecureStore from 'expo-secure-store';
import { createSecurityRuntime } from '../core/securityRuntime';
import { SECURITY_PREFERENCES_KEY } from '../core/securityPreferences';
import { PublicViewLock, PUBLIC_VIEW_LOCK_KEY } from '../core/publicViewLock';
const SECURITY_READ_TIMEOUT_MS = 10_000;
const options: SecureStore.SecureStoreOptions = { keychainService: 'org.pali.mobile.security-preferences', keychainAccessible: SecureStore.WHEN_UNLOCKED_THIS_DEVICE_ONLY, requireAuthentication: false };
let memory: string | null = null;
let viewMemory: string | null = null;
const viewOptions: SecureStore.SecureStoreOptions = { ...options, keychainService: 'org.pali.mobile.public-view-lock' };

async function readSecureSetting(key: string, settings: SecureStore.SecureStoreOptions): Promise<string | null> {
if (!await SecureStore.isAvailableAsync()) throw new Error('Security settings unavailable');
let timer: ReturnType<typeof setTimeout> | undefined;
// A stalled read can be retried without releasing or duplicating a pending write.
try {
return await Promise.race([
SecureStore.getItemAsync(key, settings),
new Promise<never>((_, reject) => {
timer = setTimeout(() => reject(new Error('Security settings read timed out')), SECURITY_READ_TIMEOUT_MS);
}),
]);
} finally {
clearTimeout(timer);
}
}

export const publicViewLock = new PublicViewLock({
async get() { if (Platform.OS === 'web') return viewMemory; if (!await SecureStore.isAvailableAsync()) throw Error(); return SecureStore.getItemAsync(PUBLIC_VIEW_LOCK_KEY, viewOptions); },
async get() { return Platform.OS === 'web' ? viewMemory : readSecureSetting(PUBLIC_VIEW_LOCK_KEY, viewOptions); },
async set(raw) { if (Platform.OS === 'web') { viewMemory = raw; return; } if (!await SecureStore.isAvailableAsync()) throw Error(); await SecureStore.setItemAsync(PUBLIC_VIEW_LOCK_KEY, raw, viewOptions); },
});
export const { securityPreferences, custodyIdle, watchIdle, beginIdleInteraction, captureIdleInteraction, recordIdleActivity } = createSecurityRuntime({
async get() { if (Platform.OS === 'web') return memory; if (!await SecureStore.isAvailableAsync()) throw Error(); return SecureStore.getItemAsync(SECURITY_PREFERENCES_KEY, options); },
async get() { return Platform.OS === 'web' ? memory : readSecureSetting(SECURITY_PREFERENCES_KEY, options); },
async set(raw) { if (Platform.OS === 'web') { memory = raw; return; } if (!await SecureStore.isAvailableAsync()) throw Error(); await SecureStore.setItemAsync(SECURITY_PREFERENCES_KEY, raw, options); },
});
54 changes: 32 additions & 22 deletions apps/mobile/src/screens/NativeSmartAccountOperation.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -323,6 +323,13 @@ export function NativeSmartAccountOperationContent({
);
};
const payer = state.payerReview;
const payerBudget = phase === 'authorize' ? state.payerBudget : undefined;
const feeFact = (label: string, units: string) => (
<View style={s.feeFact}>
<Text style={s.label}>{t(label)}</Text>
{amount(units)}
</View>
);
const assetSummary = (display: AssetTransferDisplay, nativeUnits: string) => <>
<View style={s.transferHeading}>
<View style={s.transferIcon}><Coin id="token" asset={{ kind: 'evm', chainId: state.network.chainId, contractAddress: display.contract, decimals: display.decimals }} registrationHash={state.network.registrationHash} size={42} fallbackSymbol={display.items[0]?.symbol ?? undefined} /></View>
Expand Down Expand Up @@ -367,7 +374,7 @@ export function NativeSmartAccountOperationContent({
const primary = state.phase === 'authorize' ? (
<Button
title={
state.payerBudget
payerBudget
? t(batch ? 'mobile.recoveryStatusViews.operation.confirmCalls'
: transfer?.kind === 'dapp-call' ? 'mobile.recoveryStatusViews.operation.confirmTransaction'
: 'mobile.recoveryStatusViews.operation.confirmTransfer')
Expand Down Expand Up @@ -650,7 +657,7 @@ export function NativeSmartAccountOperationContent({
)}
{state.phase === 'authorize' && (
<>
<Notice
{!payerBudget && <Notice
title={
cancellation
? t('transactions.smartAuthorizations.cancelInstruction')
Expand All @@ -671,9 +678,7 @@ export function NativeSmartAccountOperationContent({
: t('mobile.recoveryStatusViews.operation.createThisAccountOnTheNetwork')
}
body={
state.payerBudget
? t('send.smartAccountFeeDetails')
: cancellation
cancellation
? t('transactions.smartAccountCancelDescription')
: modules
? t('mobile.smartAccountModules.authorizationHint')
Expand All @@ -695,25 +700,28 @@ export function NativeSmartAccountOperationContent({
: t('mobile.recoveryStatusViews.operation.authorizeThisSmartAccountTransferTheFollowingReviewConfirmsThe')
: t('mobile.recoveryStatusViews.operation.authorizeTheAccountsDeploymentThisOperationSendsNoAssetsThe')
}
/>
<Card style={s.card}>
<Text style={s.label}>{t(state.payerBudget ? 'send.smartAccountMaxFee' : 'mobile.recoveryStatusViews.operation.maximumAccountCharge')}</Text>
{amount(state.maximumPrefundUnits!)}
<Text style={s.label}>
{t('mobile.recoveryStatusViews.operation.unusedPrefundStaysWithYourAccount')}</Text>
{state.payerBudget && <>
<Text style={s.label}>{t('transactions.feePayer')}</Text>
<Text selectable style={s.address}>{state.payerBudget.address}</Text>
<Text style={s.label}>{t(state.payerBudget.gasTank
? 'mobile.recoveryStatusViews.operation.maximumNetworkFeeGasTank' : 'transactions.replay.maximumFee')}</Text>
{amount(state.payerBudget.maximumFeeWei)}
{state.payerBudget.maximumPrefundWei !== '0' && <>
<Text style={s.label}>{t('mobile.recoveryStatusViews.operation.fundTheAccountCharge')}</Text>
{amount(state.payerBudget.maximumPrefundWei)}
<Text style={s.label}>{t('transactions.replay.maximumFee')}</Text>
{amount(state.payerBudget.maximumPrefundFeeWei)}
/>}
<Card style={[s.card, payerBudget && s.feeCard]}>
{payerBudget ? <>
{feeFact('send.smartAccountMaxFee', state.maximumPrefundUnits!)}
{feeFact(payerBudget.gasTank
? 'mobile.recoveryStatusViews.operation.maximumNetworkFeeGasTank'
: 'transactions.replay.maximumFee', payerBudget.maximumFeeWei)}
<View style={s.feeFact}>
<Text style={s.label}>{t('transactions.feePayer')}</Text>
<Text selectable style={s.address}>{payerBudget.address}</Text>
</View>
{payerBudget.maximumPrefundWei !== '0' && <>
{feeFact('mobile.recoveryStatusViews.operation.fundTheAccountCharge', payerBudget.maximumPrefundWei)}
{feeFact('transactions.replay.maximumFee', payerBudget.maximumPrefundFeeWei)}
</>}
<Text style={s.label}>{t('send.smartAccountFeeDetails')}</Text>
</> : <>
<Text style={s.label}>{t('mobile.recoveryStatusViews.operation.maximumAccountCharge')}</Text>
{amount(state.maximumPrefundUnits!)}
</>}
<Text style={s.label}>
{t('mobile.recoveryStatusViews.operation.unusedPrefundStaysWithYourAccount')}</Text>
<Button
title={
details
Expand Down Expand Up @@ -992,6 +1000,8 @@ const s = StyleSheet.create({
contextHeading: { flexDirection: 'row', flexWrap: 'wrap', justifyContent: 'space-between', columnGap: 12, rowGap: 2 },
safe: { flex: 1, backgroundColor: colors.bg },
card: { padding: 16, gap: 10 },
feeCard: { paddingVertical: 12, gap: 8 },
feeFact: { gap: 3 },
transferHeading: { flexDirection: 'row', gap: 12, alignItems: 'center' },
transferTitle: { flex: 1, gap: 3 },
transferIcon: { width: 42, height: 42, borderRadius: 14, alignItems: 'center', justifyContent: 'center', backgroundColor: colors.raised },
Expand Down
Loading
Loading