Skip to content

Commit

Permalink
feat(*): add server logic for detect webview
Browse files Browse the repository at this point in the history
  • Loading branch information
Andrei Takarski committed Oct 31, 2024
1 parent 00a10e9 commit f24b65d
Show file tree
Hide file tree
Showing 26 changed files with 930 additions and 20 deletions.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
4 changes: 2 additions & 2 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
export { BridgeToNative } from './bridge-to-native';
export { NativeParams, Theme, Environment, NativeFeatureKey, PdfType } from './types';
export { BridgeToNative } from './client/bridge-to-native';
export { NativeParams, Theme, Environment, NativeFeatureKey, PdfType } from './client/types';
36 changes: 36 additions & 0 deletions src/server/check-is-webview.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import {
extractAppVersion,
extractUserAgent,
isAkeyWebview,
extractNativeParamsFromCookies
} from './utils';
import { RequestHeaderType } from './types';
import { versionPattern, webviewUaIOSPattern } from './reg-exp-patterns';

export const isWebviewByUserAgent = (
userAgent: string,
appVersion: string | undefined,
) => {
if (userAgent && isAkeyWebview(userAgent)) {
return false;
}

return (
(appVersion && versionPattern.test(appVersion)) || !!userAgent?.match(webviewUaIOSPattern)
);
};

export const isWebviewByCookies = (nativeParamsFromCookies: Record<string, any> | null) => {
return !!(nativeParamsFromCookies && nativeParamsFromCookies.isWebview)
}
export const checkIsWebview = (
request: RequestHeaderType,
): boolean => {
const userAgent = extractUserAgent(request);

// `app-version` в заголовках – индикатор вебвью. В iOS есть только в первом запросе от webview
const appVersion = extractAppVersion(request);
const nativeParamsFromCookies = extractNativeParamsFromCookies(request);

return isWebviewByCookies(nativeParamsFromCookies) || isWebviewByUserAgent(userAgent, appVersion);
};
13 changes: 13 additions & 0 deletions src/server/constants.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
export const THEME_QUERY = 'theme';
export const TITLE = 'title';

export const WEBVIEW_IOS_APP_ID_QUERY = 'applicationId';
export const WEBVIEW_IOS_APP_VERSION_QUERY = 'device_app_version';
export const WEBVIEW_WITHOUT_LAYOUT_QUERY = 'without_layout';
export const WEBVIEW_NEXT_PAGE_ID_QUERY = 'nextPageId';

export const CAPSULE_UA_SUBSTR = 'Capsule';
export const AKEY_UA_SUBSTR = 'AKEY';
export const VOSKHOD_UA_SUBSTR = 'VOSKHOD';

export const NATIVE_PARAMS_COOKIE_NAME = 'app_native_params';
92 changes: 92 additions & 0 deletions src/server/detect-and-extract-native-params.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
import {
THEME_QUERY,
TITLE,
WEBVIEW_IOS_APP_ID_QUERY,
WEBVIEW_IOS_APP_VERSION_QUERY,
WEBVIEW_NEXT_PAGE_ID_QUERY,
WEBVIEW_WITHOUT_LAYOUT_QUERY,
NATIVE_PARAMS_COOKIE_NAME
} from './constants';

import { extractAppVersion } from './utils';

import { extractAndJoinOriginalWebviewParams } from './extract-and-join-original-webview-params';
import { checkIsWebview } from './check-is-webview';
import { iosAppIdPattern, versionPattern } from './reg-exp-patterns';
import { EmptyNativeParams, NativeParams, RequestHeaderType } from "./types";

/**
* Вытаскивает из query и headers все детали для вебвью.
*
* @returns Примечание по `appVersion`: В вебвью окружении версия всегда имеет формат `x.x.x`.
*/

export const detectAndExtractNativeParams = (
request: RequestHeaderType,
addCookie?: (cookieKey: string, cookieValue: string) => void
): EmptyNativeParams | NativeParams => {
const isWebview = checkIsWebview(request);

if (!isWebview) {
return { isWebview } as EmptyNativeParams;
}

const {
[THEME_QUERY]: themeQuery,
// При желании через диплинк на вебвью можно передать желаемый заголовок,
// который АО установит в верхней АМ панели при загрузке АО.
// По умолчанию нужна именно пустая строка.
[TITLE]: title = '',
// Говорят, этого может и не быть в урле. Формат `com.xxxxxxxxx.app`.
[WEBVIEW_IOS_APP_ID_QUERY]: iosAppIdQuery,
[WEBVIEW_IOS_APP_VERSION_QUERY]: iosAppVersionQuery,
[WEBVIEW_WITHOUT_LAYOUT_QUERY]: withoutLayoutQuery,
[WEBVIEW_NEXT_PAGE_ID_QUERY]: nextPageId,
} = request.query as Record<string, string>;

const originalWebviewParams = extractAndJoinOriginalWebviewParams(
request.query as Record<string, string>,
);

// Пробуем вытащить схему iOS приложения из query, если есть.
let iosAppId;

if (iosAppIdPattern.test(iosAppIdQuery)) {
const [, appIdSubsting] = iosAppIdQuery.match(iosAppIdPattern) as string[];

iosAppId = appIdSubsting;
}

// Определяем версию АМ из query или заголовка.
let appVersion = '0.0.0';

const appVersionFromHeaders = extractAppVersion(request);

if (typeof iosAppVersionQuery === 'string' && versionPattern.test(iosAppVersionQuery)) {
appVersion = iosAppVersionQuery;
} else if (
typeof appVersionFromHeaders === 'string' &&
versionPattern.test(appVersionFromHeaders)
) {
const [, versionSubstring] = appVersionFromHeaders.match(versionPattern) || [];

appVersion = versionSubstring;
}

const nativeParams = {
appVersion,
iosAppId,
isWebview,
theme: themeQuery === 'dark' ? 'dark' : 'light',
title,
withoutLayout: withoutLayoutQuery === 'true',
originalWebviewParams,
nextPageId: nextPageId ? Number(nextPageId) : null,
} as NativeParams;

if(addCookie) {
addCookie(NATIVE_PARAMS_COOKIE_NAME, encodeURIComponent(JSON.stringify(nativeParams)));
}

return nativeParams;
};
42 changes: 42 additions & 0 deletions src/server/extract-and-join-original-webview-params.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
// Словарь всех известных на данный момент сервисных query параметров в webview
const webviewInitParamsDictionary = [
'device_app_version',
'device_os_version',
'device_boot_time',
'device_timezone',
'applicationId',
'device_app_id',
'device_locale',
'paySupported',
'device_model',
'device_uuid',
'device_name',
'device_id',
'client_id',
'theme',
'scope',
];

/**
* Данная утилита извлекает из Fastify.Query все известные
* сервисные query параметры которые добавляются к url внутри
* webview при первой инициализации и собирает их в query строку.
*
* @param query - Fastify.Query в формате объекта
* @return строка query параметров в формате: "title=Title&theme=dark..."
* */
export const extractAndJoinOriginalWebviewParams = (
query: Record<string, string>,
): string => {
const params = new URLSearchParams();

webviewInitParamsDictionary.forEach((key) => {
const value = query[key];

if (value) {
params.set(key, value);
}
});

return params.toString();
};
5 changes: 5 additions & 0 deletions src/server/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
export * from './detect-and-extract-native-params';
export * from './check-is-webview';
export * from './types';
export * from './reg-exp-patterns';
export * from './extract-and-join-original-webview-params';
9 changes: 9 additions & 0 deletions src/server/reg-exp-patterns.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
export const iosAppIdPattern = /^com\.([a-z]+)\.app$/;

// Android приписывает после версии тип билда, например `feature`. Нам эта инфа не нужна.
export const versionPattern = /^(\d+\.\d+\.\d+)(\s.+)?$/;

export const webviewUaIOSPattern = new RegExp(
['WebView', '(iPhone|iPod|iPad)(?!.*Safari)'].join('|'),
'ig',
);
16 changes: 16 additions & 0 deletions src/server/types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
export type RequestHeaderType = Record<string, any>;

export type EmptyNativeParams = {
isWebview: false;
};

export type NativeParams = {
appVersion: string;
iosAppId?: string;
isWebview: true;
theme: 'dark' | 'light';
title: string;
withoutLayout: boolean;
originalWebviewParams: string;
nextPageId: number | null;
};
59 changes: 59 additions & 0 deletions src/server/utils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import {
CAPSULE_UA_SUBSTR,
AKEY_UA_SUBSTR,
VOSKHOD_UA_SUBSTR,
NATIVE_PARAMS_COOKIE_NAME
} from './constants';
import { RequestHeaderType } from './types';

/**
* Заголовок с версией приложения, который посылает вебвью из AM Android
*/
const AppVersion = 'app-version';

/**
* Возвращает `app-version` из заголовков запроса
*/
export function extractAppVersion(request: RequestHeaderType): string | undefined {
return request.headers[AppVersion];
}

/**
* Возвращает `User-agent` из заголовков запроса
*/
export function extractUserAgent(request: RequestHeaderType): string {
return request.headers['user-agent'];
}

/**
* Возвращает объект с `webview-параметрами` из cookies
*/
export function extractNativeParamsFromCookies(request: RequestHeaderType): Record<string, string> | null {
const cookieHeader = request.headers['cookie'];

if (!cookieHeader) {
return {};
}

const cookiesArray = cookieHeader.split('; ');
const cookieString = cookiesArray.find((cookie: string) => cookie.startsWith(`${NATIVE_PARAMS_COOKIE_NAME}=`));

if (!cookieString) return null;

const [, value] = cookieString.split('=');

try {
return JSON.parse(decodeURIComponent(value));
} catch {
return null;
}
}


/**
* Проверка по юзерагенту на сервере
*/
export const isAkeyWebview = (userAgent: string) =>
userAgent.includes(CAPSULE_UA_SUBSTR) ||
userAgent.includes(AKEY_UA_SUBSTR) ||
userAgent.includes(VOSKHOD_UA_SUBSTR);
2 changes: 1 addition & 1 deletion test/constants.test.ts → test/client/constants.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { nativeFeaturesFromVersion, versionToIosAppId } from '../src/constants';
import { nativeFeaturesFromVersion, versionToIosAppId } from '../../src/client/constants';

const versionPattern = /^\d+.\d+.\d+$/;

Expand Down
10 changes: 5 additions & 5 deletions test/index.test.ts → test/client/index.test.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
/* eslint-disable @typescript-eslint/dot-notation -- отключено, чтобы можно было обращаться к приватным полям для их тестирования */

import { BridgeToNative } from '../src';
import { BridgeToNative } from '../../src';
import {
CLOSE_WEBVIEW_SEARCH_KEY,
CLOSE_WEBVIEW_SEARCH_VALUE,
PREVIOUS_B2N_STATE_STORAGE_KEY,
START_VERSION_ANDROID_ALLOW_OPEN_NEW_WEBVIEW,
} from '../src/constants';
} from '../../src/client/constants';
import { mockSessionStorage } from './mock/mock-session-storage';
import { WebViewWindow } from '../src/types';
import { WebViewWindow } from '../../src/client/types';

const mockedNativeFallbacksInstance = {};
const mockedNativeNavigationAndTitleInstance = {
Expand All @@ -18,14 +18,14 @@ const MockedNativeNavigationAndTitleConstructor = jest.fn(
() => mockedNativeNavigationAndTitleInstance,
);

jest.mock('../src/native-fallbacks', () => ({
jest.mock('../../src/client/native-fallbacks', () => ({
__esModule: true,
NativeFallbacks: function MockedNativeFallbacksConstructor() {
return mockedNativeFallbacksInstance;
},
}));

jest.mock('../src/native-navigation-and-title', () => ({
jest.mock('../../src/client/native-navigation-and-title', () => ({
__esModule: true,
get NativeNavigationAndTitle() {
return MockedNativeNavigationAndTitleConstructor;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
/* eslint-disable @typescript-eslint/dot-notation -- отключено, чтобы можно было обращаться к приватным полям для их тестирования */

import { BridgeToNative } from '../src/bridge-to-native';
import { BridgeToNative } from '../../src/client/bridge-to-native';

describe('BridgeToNative integration testing', () => {
const defaultAmParams = {
Expand Down
File renamed without changes.
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import type { BridgeToNative } from '../src/bridge-to-native';
import { nativeFeaturesFromVersion } from '../src/constants';
import { NativeFallbacks } from '../src/native-fallbacks';
import { PdfType } from '../src/types';
import type { BridgeToNative } from '../../src/client/bridge-to-native';
import { nativeFeaturesFromVersion } from '../../src/client/constants';
import { NativeFallbacks } from '../../src/client/native-fallbacks';
import { PdfType } from '../../src/client/types';

let androidEnvFlag = false;
let iosAppId: string | undefined;
Expand Down Expand Up @@ -32,7 +32,7 @@ const mockedBridgeToAmInstance = {
},
} as unknown as BridgeToNative;

jest.mock('../src/bridge-to-native', () => ({
jest.mock('../../src/client/bridge-to-native', () => ({
__esModule: true,
BridgeToNative: function MockedBridgeToAmConstructor() {
return mockedBridgeToAmInstance;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
/* eslint-disable @typescript-eslint/dot-notation -- отключено, чтобы можно было обращаться к приватным полям для их тестирования */

import type { BridgeToNative } from '../src';
import type { BridgeToNative } from '../../src';

import { PREVIOUS_NATIVE_NAVIGATION_AND_TITLE_STATE_STORAGE_KEY } from '../src/constants';
import { PREVIOUS_NATIVE_NAVIGATION_AND_TITLE_STATE_STORAGE_KEY } from '../../src/client/constants';
import { mockSessionStorage } from './mock/mock-session-storage';
import { NativeNavigationAndTitle } from '../src/native-navigation-and-title';
import { NativeNavigationAndTitle } from '../../src/client/native-navigation-and-title';

let androidEnvFlag = false;
let mockedSetPageSettings: unknown;
Expand Down Expand Up @@ -37,7 +37,7 @@ Object.defineProperty(global, 'handleRedirect', {
configurable: true,
});

jest.mock('../src/bridge-to-native', () => ({
jest.mock('../../src/client/bridge-to-native', () => ({
__esModule: true,
BridgeToNative: function MockedBridgeToAmConstructor() {
return mockedBridgeToNativeInstance;
Expand Down
4 changes: 2 additions & 2 deletions test/utils.test.ts → test/client/utils.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@ import {
getAppId,
getUrlInstance,
isValidVersionFormat,
} from '../src/utils';
import { ANDROID_APP_ID } from '../src/constants';
} from '../../src/client/utils';
import { ANDROID_APP_ID } from '../../src/client/constants';

describe('extractAppNameRouteAndQuery', () => {
it('should extract app-name without path and query', () => {
Expand Down
Loading

0 comments on commit f24b65d

Please sign in to comment.