-
Notifications
You must be signed in to change notification settings - Fork 26
Expand file tree
/
Copy pathHcaptcha.js
More file actions
459 lines (415 loc) · 15.5 KB
/
Hcaptcha.js
File metadata and controls
459 lines (415 loc) · 15.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
import React, { useEffect, useMemo, useRef, useState } from 'react';
import WebView from 'react-native-webview';
import { ActivityIndicator, Linking, Platform, StyleSheet, TouchableWithoutFeedback, View } from 'react-native';
import ReactNativeVersion from 'react-native/Libraries/Core/ReactNativeVersion';
import md5 from './md5';
import hcaptchaPackage from './package.json';
import {
clearJourneyEvents,
disableJourneyConsumer,
enableJourneyConsumer,
peekJourneyEvents,
} from './journey';
const patchPostMessageJsCode = `(${String(function () {
var originalPostMessage = window.ReactNativeWebView.postMessage;
var patchedPostMessage = function (message, targetOrigin, transfer) {
originalPostMessage(message, targetOrigin, transfer);
};
patchedPostMessage.toString = function () {
return String(Object.hasOwnProperty).replace(
'hasOwnProperty',
'postMessage'
);
};
window.ReactNativeWebView.postMessage = patchedPostMessage;
})})();`;
const HCAPTCHA_READY_EVENT = '__hcaptcha_ready__';
const serializeForInlineScript = (value) =>
JSON.stringify(value)
.replace(/</g, '\\u003c')
.replace(/>/g, '\\u003e')
.replace(/&/g, '\\u0026')
.replace(/\u2028/g, '\\u2028')
.replace(/\u2029/g, '\\u2029');
const normalizeTheme = (value) => {
if (value == null) {
return null;
}
if (typeof value === 'object') {
return value;
}
if (typeof value === 'string') {
try {
return JSON.parse(value);
} catch (_) {
return value;
}
}
return value;
};
const normalizeSize = (value) => {
if (value == null) {
return 'invisible';
}
return value === 'checkbox' ? 'normal' : value;
};
const getVersionPart = (value) => (
typeof value === 'number' && Number.isFinite(value) && value >= 0 && value < 100
? value
: null
);
const parseReactNativeVersion = (value) => {
const candidate = value && typeof value === 'object' && value.version ? value.version : value;
const major = getVersionPart(candidate?.major);
const minor = getVersionPart(candidate?.minor);
const patch = getVersionPart(candidate?.patch);
if (major == null || minor == null || patch == null) {
return null;
}
return { major, minor, patch };
};
const getReactNativeVersion = (value = Platform?.constants?.reactNativeVersion) =>
parseReactNativeVersion(value) || parseReactNativeVersion(ReactNativeVersion?.version);
const buildDebugInfo = (debug, reactNativeVersion = Platform?.constants?.reactNativeVersion) => {
const result = { ...(debug || {}) };
try {
const version = getReactNativeVersion(reactNativeVersion);
if (version) {
result[`rnver_${version.major}_${version.minor}_${version.patch}`] = true;
}
result['dep_' + md5(Object.keys(global).join(''))] = true;
result['sdk_' + hcaptchaPackage.version.toString().replace(/\./g, '_')] = true;
} catch (e) {
console.log(e);
}
return result;
};
const buildVerifyData = ({
phoneNumber,
phonePrefix,
rqdata,
userJourney,
verifyParams,
}) => {
const normalizedVerifyParams = verifyParams || {};
const data = {};
const finalRqdata = normalizedVerifyParams.rqdata ?? rqdata ?? undefined;
const finalPhonePrefix = normalizedVerifyParams.phonePrefix ?? phonePrefix ?? undefined;
const finalPhoneNumber = normalizedVerifyParams.phoneNumber ?? phoneNumber ?? undefined;
if (finalRqdata) {
data.rqdata = finalRqdata;
}
if (finalPhonePrefix) {
data.mfa_phoneprefix = finalPhonePrefix;
}
if (finalPhoneNumber) {
data.mfa_phone = finalPhoneNumber;
}
if (Array.isArray(userJourney) && userJourney.length > 0) {
data.userjourney = userJourney;
}
return data;
};
const buildVerifyInjectionScript = (payload, resetFirst = false) =>
`try { ${resetFirst ? 'reset(); ' : ''}setData(${serializeForInlineScript(payload)}); execute(); } catch (e) { window.ReactNativeWebView.postMessage((e && e.name) || 'error'); } true;`;
const buildHcaptchaApiUrl = (jsSrc, siteKey, hl, theme, host, sentry, endpoint, assethost, imghost, reportapi, orientation) => {
var url = `${jsSrc || 'https://hcaptcha.com/1/api.js'}?render=explicit&onload=onloadCallback`;
let effectiveHost;
if (host) {
effectiveHost = encodeURIComponent(host);
} else {
effectiveHost = (siteKey || 'missing-sitekey') + '.react-native.hcaptcha.com';
}
for (let [key, value] of Object.entries({ host: effectiveHost, hl, custom: typeof theme === 'object', sentry, endpoint, assethost, imghost, reportapi, orientation })) {
if (value) {
url += `&${key}=${encodeURIComponent(value)}`;
}
}
return url;
};
/**
*
* @param {*} onMessage: callback after receiving response, error, or when user cancels
* @param {*} siteKey: your hCaptcha sitekey
* @param {string} size: The size of the widget, can be 'invisible', 'compact' or 'normal'. 'checkbox' is kept as a legacy alias for 'normal'. Default: 'invisible'
* @param {*} style: custom style
* @param {*} url: base url
* @param {*} languageCode: can be found at https://docs.hcaptcha.com/languages
* @param {*} showLoading: loading indicator for webview till hCaptcha web content loads
* @param {*} closableLoading: allow user to cancel hcaptcha during loading by touch loader overlay
* @param {*} loadingIndicatorColor: color for the ActivityIndicator
* @param {*} backgroundColor: backgroundColor which can be injected into HTML to alter css backdrop colour
* @param {string|object} theme: can be 'light', 'dark', 'contrast' or custom theme object
* @param {string} rqdata: see Enterprise docs
* @param {boolean} sentry: sentry error reporting
* @param {string} jsSrc: The url of api.js. Default: https://js.hcaptcha.com/1/api.js (Override only if using first-party hosting feature.)
* @param {string} endpoint: Point hCaptcha JS Ajax Requests to alternative API Endpoint. Default: https://api.hcaptcha.com (Override only if using first-party hosting feature.)
* @param {string} reportapi: Point hCaptcha Bug Reporting Request to alternative API Endpoint. Default: https://accounts.hcaptcha.com (Override only if using first-party hosting feature.)
* @param {string} assethost: Points loaded hCaptcha assets to a user defined asset location, used for proxies. Default: https://newassets.hcaptcha.com (Override only if using first-party hosting feature.)
* @param {string} imghost: Points loaded hCaptcha challenge images to a user defined image location, used for proxies. Default: https://imgs.hcaptcha.com (Override only if using first-party hosting feature.)
* @param {string} host: hCaptcha SDK host identifier. null value means that it will be generated by SDK
* @param {object} debug: debug information
* @param {string} orientation: hCaptcha challenge orientation
* @param {string} phonePrefix: Optional phone country calling code (without '+'), e.g., "44". Used in MFA flows.
* @param {string} phoneNumber: Optional full phone number in E.164 format ("+44123..."), for use in MFA.
* @param {boolean} userJourney: Enable automatic user journey injection
* @param {object} verifyParams: Verification payload overrides
*/
const Hcaptcha = ({
onMessage,
size,
siteKey,
style,
url,
languageCode,
showLoading,
closableLoading,
loadingIndicatorColor,
backgroundColor,
theme,
rqdata,
sentry,
jsSrc,
endpoint,
reportapi,
assethost,
imghost,
host,
debug,
orientation,
phonePrefix,
phoneNumber,
userJourney,
verifyParams,
_journeyManagedExternally,
}) => {
const tokenTimeout = 120000;
const loadingTimeout = 15000;
const [isLoading, setIsLoading] = useState(true);
const journeyEnabled = Boolean(userJourney);
const hasJourneyConsumerRef = useRef(false);
const normalizedTheme = useMemo(() => normalizeTheme(theme), [theme]);
const normalizedSize = useMemo(() => normalizeSize(size), [size]);
const apiUrl = useMemo(
() => buildHcaptchaApiUrl(jsSrc, siteKey, languageCode, normalizedTheme, host, sentry, endpoint, assethost, imghost, reportapi, orientation),
[jsSrc, siteKey, languageCode, normalizedTheme, host, sentry, endpoint, assethost, imghost, reportapi, orientation]
);
const debugInfo = useMemo(
() => buildDebugInfo(debug),
[debug]
);
const serializedWebViewConfig = useMemo(
() => serializeForInlineScript({
apiUrl,
backgroundColor: backgroundColor ?? '',
debugInfo,
phoneNumber: phoneNumber ?? null,
phonePrefix: phonePrefix ?? null,
rqdata: rqdata ?? null,
siteKey: siteKey || '',
size: normalizedSize,
theme: normalizedTheme,
}),
[apiUrl, backgroundColor, debugInfo, normalizedSize, normalizedTheme, phoneNumber, phonePrefix, rqdata, siteKey]
);
const generateTheWebViewContent = useMemo(
() =>
`<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<script type="text/javascript">
var hcaptchaConfig = ${serializedWebViewConfig};
Object.entries(hcaptchaConfig.debugInfo || {}).forEach(function (entry) { window[entry[0]] = entry[1] });
</script>
<script type="text/javascript">
var loadApiScript = function() {
var script = document.createElement('script');
script.async = true;
script.defer = true;
script.src = hcaptchaConfig.apiUrl;
document.head.appendChild(script);
};
var hcaptchaWidgetId = null;
var setData = function(data) {
hcaptcha.setData(hcaptchaWidgetId, data || {});
};
var execute = function() {
hcaptcha.execute(hcaptchaWidgetId);
};
var reset = function() {
hcaptcha.reset(hcaptchaWidgetId);
};
var onloadCallback = function() {
try {
console.log("challenge onload starting");
hcaptchaWidgetId = hcaptcha.render("hcaptcha-container", getRenderConfig(hcaptchaConfig.siteKey, hcaptchaConfig.theme, hcaptchaConfig.size));
window.ReactNativeWebView.postMessage("${HCAPTCHA_READY_EVENT}");
// have loaded by this point; render is sync.
console.log("challenge render complete");
} catch (e) {
console.log("challenge failed to render:", e);
window.ReactNativeWebView.postMessage(e.name);
}
};
var onDataCallback = function(response) {
window.ReactNativeWebView.postMessage(response);
};
var onCancel = function() {
window.ReactNativeWebView.postMessage("challenge-closed");
};
var onOpen = function() {
document.body.style.backgroundColor = hcaptchaConfig.backgroundColor;
window.ReactNativeWebView.postMessage("open");
console.log("challenge opened");
};
var onDataExpiredCallback = function(error) { window.ReactNativeWebView.postMessage(error); };
var onChalExpiredCallback = function(error) { window.ReactNativeWebView.postMessage(error); };
var onDataErrorCallback = function(error) {
console.warn("challenge error callback fired");
window.ReactNativeWebView.postMessage(error);
};
const getRenderConfig = function(siteKey, theme, size) {
var config = {
sitekey: siteKey,
size: size,
callback: onDataCallback,
"close-callback": onCancel,
"open-callback": onOpen,
"expired-callback": onDataExpiredCallback,
"chalexpired-callback": onChalExpiredCallback,
"error-callback": onDataErrorCallback
};
if (theme) {
config.theme = theme;
}
return config;
};
loadApiScript();
</script>
</head>
<body>
<div id="hcaptcha-container"></div>
</body>
</html>`,
[serializedWebViewConfig]
);
useEffect(() => {
if (_journeyManagedExternally || !journeyEnabled || hasJourneyConsumerRef.current) {
return undefined;
}
enableJourneyConsumer();
hasJourneyConsumerRef.current = true;
return () => {
if (hasJourneyConsumerRef.current) {
disableJourneyConsumer();
hasJourneyConsumerRef.current = false;
}
};
}, [_journeyManagedExternally, journeyEnabled]);
useEffect(() => {
const timeoutId = setTimeout(() => {
if (isLoading) {
onMessage({ nativeEvent: { data: 'error', description: 'loading timeout' } });
}
}, loadingTimeout);
return () => clearTimeout(timeoutId);
}, [isLoading, onMessage]);
const webViewRef = useRef(null);
const injectVerifyData = (resetFirst = false) => {
if (!webViewRef.current) {
return;
}
webViewRef.current.injectJavaScript(buildVerifyInjectionScript(buildVerifyData({
phoneNumber,
phonePrefix,
rqdata,
userJourney: journeyEnabled ? peekJourneyEvents() : undefined,
verifyParams,
}), resetFirst));
};
// This shows ActivityIndicator till webview loads hCaptcha images
const renderLoading = () => (
<TouchableWithoutFeedback onPress={() => closableLoading && onMessage({ nativeEvent: { data: 'cancel' } })}>
<View style={styles.loadingOverlay}>
<ActivityIndicator size="large" color={loadingIndicatorColor} />
</View>
</TouchableWithoutFeedback>
);
const reset = () => {
injectVerifyData(true);
};
return (
<View style={styles.container}>
<WebView
ref={webViewRef}
originWhitelist={['*']}
onShouldStartLoadWithRequest={(event) => {
if (event.url.slice(0, 24) === 'https://www.hcaptcha.com') {
Linking.openURL(event.url);
return false;
} else if (event.url.toLowerCase().startsWith('sms:')) {
Linking.openURL(event.url).catch((err) => {
onMessage({
nativeEvent: {
data: 'sms-open-failed',
description: err.message,
},
success: false,
});
});
return false;
}
return true;
}}
mixedContentMode={'always'}
onMessage={(e) => {
if (e.nativeEvent.data === HCAPTCHA_READY_EVENT) {
injectVerifyData();
return;
}
e.reset = reset;
e.success = true;
if (e.nativeEvent.data === 'open') {
setIsLoading(false);
} else if (e.nativeEvent.data.length > 35) {
const expiredTokenTimerId = setTimeout(() => onMessage({ nativeEvent: { data: 'expired' }, success: false, reset }), tokenTimeout);
e.markUsed = () => clearTimeout(expiredTokenTimerId);
if (journeyEnabled) {
clearJourneyEvents();
}
} else /* error */ {
e.success = false;
}
onMessage(e);
}}
javaScriptEnabled
injectedJavaScript={patchPostMessageJsCode}
automaticallyAdjustContentInsets
style={[styles.webview, style]}
source={{
html: generateTheWebViewContent,
baseUrl: `${url}`,
}}
/>
{showLoading && isLoading && renderLoading()}
</View>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
},
loadingOverlay: {
...StyleSheet.absoluteFillObject,
justifyContent: 'center',
},
webview: {
backgroundColor: 'transparent',
width: '100%',
},
});
export default Hcaptcha;
export { buildDebugInfo, buildVerifyData, HCAPTCHA_READY_EVENT };