Skip to content
Merged
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
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,7 @@
"miniapps:dev:biobridge": "pnpm --filter @biochain/miniapp-biobridge dev"
},
"dependencies": {
"@biochain/android-focus-blur-guard": "workspace:*",
"@base-ui/react": "^1.0.0",
"@bfchain/util": "^5.0.0",
"@bfmeta/sign-util": "^1.3.10",
Expand Down
41 changes: 41 additions & 0 deletions packages/android-focus-blur-guard/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
{
"name": "@biochain/android-focus-blur-guard",
"version": "0.1.0",
"description": "Android focus/blur loop guard for WebView and iframe contexts",
"type": "module",
"main": "./src/index.ts",
"module": "./src/index.ts",
"types": "./src/index.ts",
"exports": {
".": {
"import": "./src/index.ts",
"types": "./src/index.ts"
}
},
"files": [
"src"
],
"scripts": {
"build": "echo 'No build step required'",
"typecheck": "tsc --noEmit",
"typecheck:run": "tsc --noEmit",
"test": "vitest",
"test:run": "vitest run --passWithNoTests",
"test:storybook": "echo 'No storybook'",
"i18n:run": "echo 'No i18n'",
"theme:run": "echo 'No theme'"
},
"devDependencies": {
"jsdom": "^27.2.0",
"typescript": "^5.9.3",
"vitest": "^4.0.0"
},
"keywords": [
"android",
"focus",
"blur",
"guard",
"webview"
],
"license": "MIT"
}
68 changes: 68 additions & 0 deletions packages/android-focus-blur-guard/src/index.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
import {
installAndroidFocusBlurLoopGuard,
isAndroidUserAgent,
uninstallAndroidFocusBlurLoopGuard,
} from './index';

describe('android-focus-blur-guard', () => {
beforeEach(() => {
uninstallAndroidFocusBlurLoopGuard();
});

it('detects android user agent', () => {
expect(isAndroidUserAgent('Mozilla/5.0 (Linux; Android 14; Pixel 8)')).toBe(true);
expect(isAndroidUserAgent('Mozilla/5.0 (iPhone; CPU iPhone OS 18_0 like Mac OS X)')).toBe(false);
});

it('suppresses blur for body/html/iframe elements', () => {
const nativeSpy = vi.fn();
const originalBlur = HTMLElement.prototype.blur;
HTMLElement.prototype.blur = function mockNativeBlur(this: HTMLElement): void {
nativeSpy(this.tagName);
};

const restore = installAndroidFocusBlurLoopGuard({
isAndroid: () => true,
});

document.body.blur();
document.documentElement.blur();
const iframe = document.createElement('iframe');
document.body.appendChild(iframe);
iframe.blur();

const input = document.createElement('input');
document.body.appendChild(input);
input.blur();

expect(nativeSpy).toHaveBeenCalledTimes(1);
expect(nativeSpy).toHaveBeenCalledWith('INPUT');

restore();
HTMLElement.prototype.blur = originalBlur;
});

it('blocks blur event propagation when active element is body-like', () => {
installAndroidFocusBlurLoopGuard({
isAndroid: () => true,
});

const listener = vi.fn();
window.addEventListener('blur', listener);

window.dispatchEvent(new Event('blur'));

expect(listener).not.toHaveBeenCalled();
});

it('does not install on non-android runtime', () => {
const nativeBlur = HTMLElement.prototype.blur;
const restore = installAndroidFocusBlurLoopGuard({
isAndroid: () => false,
});

expect(HTMLElement.prototype.blur).toBe(nativeBlur);
restore();
});
});
137 changes: 137 additions & 0 deletions packages/android-focus-blur-guard/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,137 @@
export interface AndroidFocusBlurLoopGuardOptions {
/**
* Android 运行时检测(默认通过 UA 判断)
*/
isAndroid?: () => boolean;
/**
* 是否将 iframe 元素视为需拦截目标(默认 true)
*/
blockIframeElement?: boolean;
}

type GuardState = {
restore: () => void;
};

type GuardWindow = Window &
typeof globalThis & {
__biochainAndroidFocusBlurLoopGuardState__?: GuardState;
};

const GUARD_KEY = '__biochainAndroidFocusBlurLoopGuardState__' as const;

function isBlockedElement(element: Element | null, blockIframeElement: boolean): element is HTMLElement {
if (!(element instanceof HTMLElement)) {
return false;
}

if (element === document.body || element === document.documentElement) {
return true;
}

if (blockIframeElement && element instanceof HTMLIFrameElement) {
return true;
}

return false;
}

export function isAndroidUserAgent(userAgent: string): boolean {
return /android/i.test(userAgent);
}

function isAndroidRuntime(): boolean {
if (typeof navigator === 'undefined') {
return false;
}

const nav = navigator as Navigator & {
userAgentData?: {
platform?: string;
};
};

const platform = nav.userAgentData?.platform;
if (platform && /android/i.test(platform)) {
return true;
}

return isAndroidUserAgent(nav.userAgent);
}

/**
* 在 Android WebView 环境为全局 focus/blur 死循环做止血补丁。
* - 拦截 window blur/focus 事件在 body/html/iframe 激活时的传播
* - 禁止对 body/html/iframe 执行 blur()
* - 对 blur() 做最小重入保护
*/
export function installAndroidFocusBlurLoopGuard(
options: AndroidFocusBlurLoopGuardOptions = {},
): () => void {
if (typeof window === 'undefined' || typeof document === 'undefined') {
return () => {};
}

const guardWindow = window as GuardWindow;
const existing = guardWindow[GUARD_KEY];
if (existing) {
return existing.restore;
}

const checkAndroid = options.isAndroid ?? isAndroidRuntime;
if (!checkAndroid()) {
return () => {};
}

const blockIframeElement = options.blockIframeElement ?? true;
const nativeBlur = HTMLElement.prototype.blur;
let blurring = false;

const eventFirewall = (event: Event) => {
if (!isBlockedElement(document.activeElement, blockIframeElement)) {
return;
}
event.stopImmediatePropagation();
event.stopPropagation();
};

window.addEventListener('blur', eventFirewall, true);
window.addEventListener('focus', eventFirewall, true);

HTMLElement.prototype.blur = function patchedBlur(this: HTMLElement): void {
if (isBlockedElement(this, blockIframeElement)) {
return;
}

if (blurring) {
return;
}

blurring = true;
try {
nativeBlur.call(this);
} finally {
queueMicrotask(() => {
blurring = false;
});
}
};

const restore = () => {
window.removeEventListener('blur', eventFirewall, true);
window.removeEventListener('focus', eventFirewall, true);
HTMLElement.prototype.blur = nativeBlur;
delete guardWindow[GUARD_KEY];
};

guardWindow[GUARD_KEY] = { restore };
return restore;
}

export function uninstallAndroidFocusBlurLoopGuard(): void {
if (typeof window === 'undefined') {
return;
}
const guardWindow = window as GuardWindow;
guardWindow[GUARD_KEY]?.restore();
}
16 changes: 16 additions & 0 deletions packages/android-focus-blur-guard/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
{
"compilerOptions": {
"target": "ES2022",
"lib": ["ES2022", "DOM", "DOM.Iterable"],
"module": "ESNext",
"moduleResolution": "bundler",
"strict": true,
"noEmit": true,
"esModuleInterop": true,
"skipLibCheck": true,
"declaration": true,
"declarationMap": true,
"isolatedModules": true
},
"include": ["src"]
}
8 changes: 8 additions & 0 deletions packages/android-focus-blur-guard/vite.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import { defineConfig } from 'vitest/config';

export default defineConfig({
test: {
environment: 'jsdom',
globals: true,
},
});
1 change: 1 addition & 0 deletions packages/bio-sdk/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
"vitest": "^4.0.0"
},
"dependencies": {
"@biochain/android-focus-blur-guard": "workspace:*",
"zod": "^4.1.13"
},
"keywords": [
Expand Down
3 changes: 3 additions & 0 deletions packages/bio-sdk/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import { BioProviderImpl } from './provider'
import { EthereumProvider, initEthereumProvider } from './ethereum-provider'
import { TronLinkProvider, TronWebProvider, initTronProvider } from './tron-provider'
import type { BioProvider } from './types'
import { installAndroidFocusBlurLoopGuard } from '@biochain/android-focus-blur-guard'

// Re-export types
export * from './types'
Expand Down Expand Up @@ -80,6 +81,8 @@ export function initAllProviders(targetOrigin = '*'): {

// Auto-initialize if running in browser
if (typeof window !== 'undefined') {
installAndroidFocusBlurLoopGuard()

const init = () => {
initBioProvider()
initEthereumProvider()
Expand Down
20 changes: 19 additions & 1 deletion pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 3 additions & 0 deletions src/main.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,13 @@
import './lib/error-capture'
import './lib/superjson'
import './polyfills'
import { installAndroidFocusBlurLoopGuard } from '@biochain/android-focus-blur-guard'
import { startServiceMain } from './service-main'
import { startFrontendMain } from './frontend-main'
import { shouldBlockContextMenu } from './lib/context-menu-guard'

installAndroidFocusBlurLoopGuard()

// 禁用右键菜单(移动端 App 体验)
document.addEventListener('contextmenu', (event) => {
if (!shouldBlockContextMenu(event.target)) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -402,6 +402,12 @@ describe('miniapp confirm jobs regressions', () => {
expect(confirmButton).not.toBeDisabled();
});

expect(screen.getByTestId('miniapp-transfer-remark')).toBeInTheDocument();
expect(screen.getByText('ex_type')).toBeInTheDocument();
expect(screen.getByText('exchange.purchase')).toBeInTheDocument();
expect(screen.getByText('ex_id')).toBeInTheDocument();
expect(screen.getByText('exchange-001')).toBeInTheDocument();

fireEvent.click(confirmButton);
fireEvent.click(screen.getByTestId('pattern-lock'));

Expand Down
Loading