diff --git a/Hcaptcha.js b/Hcaptcha.js
index 528a359..f50c4fa 100644
--- a/Hcaptcha.js
+++ b/Hcaptcha.js
@@ -6,6 +6,7 @@ import ReactNativeVersion from 'react-native/Libraries/Core/ReactNativeVersion';
import md5 from './md5';
import hcaptchaPackage from './package.json';
+import { parseSmsLink } from './hcaptchaSmsLink';
import {
clearJourneyEvents,
disableJourneyConsumer,
@@ -604,6 +605,59 @@ const Hcaptcha = forwardRef(({
},
}));
+ // The parser is the only place that decides what an SMS link is: a second scheme check here
+ // would be a narrower matcher that drifts out of sync with it - `smsto:` is accepted by
+ // `parseSmsLink` and would otherwise never reach this hand-off.
+ const openSmsLink = (smsUrl) => {
+ const link = parseSmsLink(smsUrl);
+ if (!link) {
+ return false;
+ }
+
+ // Rebuilt from the parsed parts rather than passed through: the recipient can arrive with
+ // formatting a messaging app rejects, and the challenge emits an empty leading query
+ // parameter (`?&body=`). The body itself is re-encoded unchanged, so the one-time code
+ // reaches the composer byte-exact.
+ const target = link.recipient
+ ? `sms:${link.recipient}${link.body ? `?body=${encodeURIComponent(link.body)}` : ''}`
+ : smsUrl;
+
+ Linking.openURL(target).catch(() => {
+ if (documentRef.current !== documentId) {
+ return;
+ }
+ // The rejection message embeds the URL, and the body carries a one-time code, so it is
+ // deliberately not forwarded: this event reaches host apps that log it.
+ onMessage({
+ nativeEvent: {
+ data: 'sms-open-failed',
+ description: 'Could not open the messaging app',
+ },
+ success: false,
+ });
+ });
+
+ return true;
+ };
+
+ // Shared by both navigation callbacks. The challenge opens its `sms:` link with
+ // `target="_blank"`, which never reaches `onShouldStartLoadWithRequest` - on Android
+ // `setSupportMultipleWindows` is always on, so it surfaces as `onOpenWindow` instead.
+ const handleExternalUrl = (candidate) => {
+ if (typeof candidate !== 'string') {
+ return false;
+ }
+
+ if (candidate.slice(0, 24) === 'https://www.hcaptcha.com') {
+ // Returning true keeps this off the `onOpenWindow` fallback below, which is where the
+ // rejection would otherwise have been caught.
+ Linking.openURL(candidate).catch(() => {});
+ return true;
+ }
+
+ return openSmsLink(candidate);
+ };
+
if (destroyed) {
return null;
}
@@ -614,30 +668,20 @@ const Hcaptcha = forwardRef(({
key={documentKey}
ref={webViewRef}
originWhitelist={['*']}
- onShouldStartLoadWithRequest={(event) => {
+ onShouldStartLoadWithRequest={(event) => documentRef.current === documentId && !handleExternalUrl(event.url)}
+ onOpenWindow={(event) => {
if (documentRef.current !== documentId) {
- return false;
+ return;
}
- 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) => {
- if (documentRef.current !== documentId) {
- return;
- }
- onMessage({
- nativeEvent: {
- data: 'sms-open-failed',
- description: err.message,
- },
- success: false,
- });
- });
- return false;
+ const { targetUrl } = event.nativeEvent;
+ if (handleExternalUrl(targetUrl)) {
+ return;
}
- return true;
+ // A `target="_blank"` link the challenge does not own. Android already sent these out
+ // to the system before this callback existed, so keep that behaviour rather than
+ // swallowing the navigation.
+ Linking.openURL(targetUrl).catch(() => {});
}}
mixedContentMode={'always'}
onContentProcessDidTerminate={reloadWebView}
diff --git a/__tests__/Hcaptcha.test.js b/__tests__/Hcaptcha.test.js
index 6d0abe8..6e40922 100644
--- a/__tests__/Hcaptcha.test.js
+++ b/__tests__/Hcaptcha.test.js
@@ -1077,7 +1077,7 @@ describe('Hcaptcha', () => {
expect(openURL).toHaveBeenCalledWith('https://www.hcaptcha.com/privacy');
});
- it('opens sms links externally and reports failures back through onMessage', async () => {
+ it('opens sms links externally, normalising the challenge link shape', async () => {
const openURL = jest.spyOn(Linking, 'openURL');
const onMessage = jest.fn();
const component = render(
@@ -1088,17 +1088,20 @@ describe('Hcaptcha', () => {
/>
);
+ // The shape the challenge emits, with the empty leading query parameter.
openURL.mockResolvedValueOnce(true);
const successfulSms = getWebView(component).props.onShouldStartLoadWithRequest({
- url: 'sms:+15551234567',
+ url: 'sms:+15550001111?&body=Do%20not%20share%20the%20code%3A%20aaaa-bbbb-cccc',
});
expect(successfulSms).toBe(false);
- expect(openURL).toHaveBeenCalledWith('sms:+15551234567');
+ expect(openURL).toHaveBeenCalledWith(
+ 'sms:+15550001111?body=Do%20not%20share%20the%20code%3A%20aaaa-bbbb-cccc'
+ );
openURL.mockRejectedValueOnce(new Error('sms unavailable'));
const failedSms = getWebView(component).props.onShouldStartLoadWithRequest({
- url: 'sms:+15557654321',
+ url: 'sms:+15550002222',
});
expect(failedSms).toBe(false);
@@ -1107,13 +1110,95 @@ describe('Hcaptcha', () => {
expect(onMessage).toHaveBeenCalledWith({
nativeEvent: {
data: 'sms-open-failed',
- description: 'sms unavailable',
+ // The rejection message embeds the URL, which carries the one-time code, so it is
+ // deliberately not forwarded.
+ description: 'Could not open the messaging app',
},
success: false,
});
});
});
+ it('handles target="_blank" links through onOpenWindow', () => {
+ // The challenge opens its sms link with target="_blank", which never reaches
+ // onShouldStartLoadWithRequest on Android.
+ const openURL = jest.spyOn(Linking, 'openURL').mockResolvedValue(true);
+ const component = render(
+
+ );
+
+ getWebView(component).props.onOpenWindow({
+ nativeEvent: { targetUrl: 'sms:+15550001111?&body=code%3A%20aaaa-bbbb-cccc' },
+ });
+ expect(openURL).toHaveBeenCalledWith('sms:+15550001111?body=code%3A%20aaaa-bbbb-cccc');
+
+ getWebView(component).props.onOpenWindow({
+ nativeEvent: { targetUrl: 'https://www.hcaptcha.com/privacy' },
+ });
+ expect(openURL).toHaveBeenCalledWith('https://www.hcaptcha.com/privacy');
+
+ getWebView(component).props.onOpenWindow({
+ nativeEvent: { targetUrl: 'https://example.com/other' },
+ });
+ expect(openURL).toHaveBeenCalledWith('https://example.com/other');
+ });
+
+ it('hands off an smsto link through the same normalisation as sms', () => {
+ // The parser accepts `smsto:`, so the dispatch must too: a separate scheme check here would
+ // be a narrower matcher and would send the link out unnormalised instead.
+ const openURL = jest.spyOn(Linking, 'openURL').mockResolvedValue(true);
+ const component = render(
+
+ );
+
+ const handled = getWebView(component).props.onShouldStartLoadWithRequest({
+ url: 'smsto:+1 (555) 000-1111?&body=code%3A%20aaaa-bbbb-cccc',
+ });
+
+ expect(handled).toBe(false);
+ expect(openURL).toHaveBeenCalledWith('sms:+15550001111?body=code%3A%20aaaa-bbbb-cccc');
+ });
+
+ it('does not reject when opening an hcaptcha.com link fails', async () => {
+ // This branch returns before the onOpenWindow fallback, so it has to catch for itself:
+ // an unhandled rejection here surfaces in the host app.
+ const openURL = jest
+ .spyOn(Linking, 'openURL')
+ .mockRejectedValueOnce(new Error('no browser'));
+ const onMessage = jest.fn();
+ const component = render(
+
+ );
+
+ const unhandled = jest.fn();
+ process.on('unhandledRejection', unhandled);
+
+ getWebView(component).props.onOpenWindow({
+ nativeEvent: { targetUrl: 'https://www.hcaptcha.com/privacy' },
+ });
+ expect(openURL).toHaveBeenCalledWith('https://www.hcaptcha.com/privacy');
+
+ // Let the rejection settle and the microtask queue drain.
+ await new Promise((resolve) => setImmediate(resolve));
+ process.off('unhandledRejection', unhandled);
+
+ expect(unhandled).not.toHaveBeenCalled();
+ // A browser that cannot open is not an SMS hand-off failure, so nothing is reported.
+ expect(onMessage).not.toHaveBeenCalled();
+ });
+
it('allows non-hcaptcha, non-sms navigations to continue inside the WebView', () => {
const openURL = jest.spyOn(Linking, 'openURL').mockResolvedValue(true);
const component = render(
diff --git a/__tests__/__snapshots__/ConfirmHcaptcha.test.js.snap b/__tests__/__snapshots__/ConfirmHcaptcha.test.js.snap
index ca1e5bc..aec99e0 100644
--- a/__tests__/__snapshots__/ConfirmHcaptcha.test.js.snap
+++ b/__tests__/__snapshots__/ConfirmHcaptcha.test.js.snap
@@ -91,6 +91,7 @@ exports[`ConfirmHcaptcha renders ConfirmHcaptcha with minimum props after show()
onContentProcessDidTerminate={[Function]}
onLoadStart={[Function]}
onMessage={[Function]}
+ onOpenWindow={[Function]}
onRenderProcessGone={[Function]}
onShouldStartLoadWithRequest={[Function]}
originWhitelist={
diff --git a/__tests__/__snapshots__/Hcaptcha.test.js.snap b/__tests__/__snapshots__/Hcaptcha.test.js.snap
index 026203e..f2a9fc4 100644
--- a/__tests__/__snapshots__/Hcaptcha.test.js.snap
+++ b/__tests__/__snapshots__/Hcaptcha.test.js.snap
@@ -25,6 +25,7 @@ exports[`Hcaptcha renders Hcaptcha with minimum props 1`] = `
onContentProcessDidTerminate={[Function]}
onLoadStart={[Function]}
onMessage={[Function]}
+ onOpenWindow={[Function]}
onRenderProcessGone={[Function]}
onShouldStartLoadWithRequest={[Function]}
originWhitelist={
diff --git a/__tests__/hcaptchaSmsLink.test.js b/__tests__/hcaptchaSmsLink.test.js
new file mode 100644
index 0000000..f1eb7bc
--- /dev/null
+++ b/__tests__/hcaptchaSmsLink.test.js
@@ -0,0 +1,134 @@
+import { parseSmsLink } from '../hcaptchaSmsLink';
+
+// The shape the MFA challenge emits: an hCaptcha number and a full sentence carrying a
+// hyphenated one-time code. The numbers and codes here are dummies.
+const POOL_NUMBER = '+15550001111';
+const POOL_BODY =
+ 'Return to the app and press Confirm after sending this message. ' +
+ 'Do not edit or share the code: aaaa-bbbb-cccc';
+const POOL_LINK =
+ 'sms:+15550001111?body=Return%20to%20the%20app%20and%20press%20Confirm%20after%20sending%20' +
+ 'this%20message.%20Do%20not%20edit%20or%20share%20the%20code%3A%20aaaa-bbbb-cccc';
+
+// The same shape with the empty first query parameter the challenge is reported to emit:
+// `?&body=`, not `?body=`.
+const EMPTY_LEADING_PAIR_LINK =
+ 'sms:+15550002222?&body=Return%20to%20the%20app%20and%20press%20Confirm%20after%20sending%20' +
+ 'this%20message.%20Do%20not%20edit%20or%20share%20the%20code%3A%20dddd-eeee-ffff';
+
+const NUMBER = '+15551234567';
+const CODE = 'code';
+const CODE_QUERY = '?body=code';
+
+/** @param suffix everything after the hCaptcha number in the link */
+const parseSuffix = (suffix) => parseSmsLink(`sms:${NUMBER}${suffix}`);
+
+describe('parseSmsLink', () => {
+ it('parses a full challenge-shaped link', () => {
+ expect(parseSmsLink(POOL_LINK)).toEqual({ recipient: POOL_NUMBER, body: POOL_BODY });
+ });
+
+ it('parses a link with an empty leading query parameter', () => {
+ expect(parseSmsLink(EMPTY_LEADING_PAIR_LINK)).toEqual({
+ recipient: '+15550002222',
+ body:
+ 'Return to the app and press Confirm after sending this message. ' +
+ 'Do not edit or share the code: dddd-eeee-ffff',
+ });
+ });
+
+ it('skips empty query parameters', () => {
+ expect(parseSuffix('?&body=code').body).toBe(CODE);
+ expect(parseSuffix('?&&body=code').body).toBe(CODE);
+ expect(parseSuffix('?x=1&body=code&').body).toBe(CODE);
+ });
+
+ it('keeps the body byte-exact', () => {
+ // The code is hyphenated in the SMS body and unhyphenated in the challenge UI; the backend
+ // normalises, so nothing here may trim, reformat or re-case the body.
+ expect(parseSuffix('?body=%20%20spaced%20%20').body).toBe(' spaced ');
+ expect(parseSuffix('?body=aaaa-bbbb-cccc').body).toBe('aaaa-bbbb-cccc');
+ });
+
+ it('splits the query before the subscriber params', () => {
+ // RFC 5724 allows `;` subscriber params before the query. Folding the two grammars together
+ // loses the body.
+ expect(parseSuffix(`;phone-context=+1${CODE_QUERY}`)).toEqual({
+ recipient: NUMBER,
+ body: CODE,
+ });
+ });
+
+ it('treats a semicolon inside the query as body text', () => {
+ expect(parseSuffix('?body=code;more').body).toBe('code;more');
+ });
+
+ it('reads the legacy body parameter from the head', () => {
+ expect(parseSuffix(';body=hello').body).toBe('hello');
+ });
+
+ it('keeps a plus in the body', () => {
+ // `+` is a literal plus in a URI query (RFC 3986); only form encoding reads it as a space.
+ expect(parseSuffix('?body=a+b').body).toBe('a+b');
+ });
+
+ it('decodes utf-8 escapes', () => {
+ expect(parseSuffix('?body=caf%C3%A9%20%E2%80%93%20ok').body).toBe('café – ok');
+ });
+
+ it('keeps malformed escapes as literal text', () => {
+ expect(parseSuffix('?body=100%25').body).toBe('100%');
+ expect(parseSuffix('?body=50%').body).toBe('50%');
+ expect(parseSuffix('?body=%zz').body).toBe('%zz');
+ });
+
+ it('normalises recipient formatting', () => {
+ expect(parseSmsLink('sms:+123-456-789?body=Hello%20World').recipient).toBe('+123456789');
+ expect(parseSmsLink('sms:%2B1%20(555)%20123.4567').recipient).toBe(NUMBER);
+ });
+
+ it('keeps only the first recipient', () => {
+ expect(parseSuffix(`,+15559999999${CODE_QUERY}`).recipient).toBe(NUMBER);
+ });
+
+ it('accepts the smsto and authority forms', () => {
+ expect(parseSmsLink(`smsto:${NUMBER}${CODE_QUERY}`).recipient).toBe(NUMBER);
+ expect(parseSmsLink(`sms://${NUMBER}${CODE_QUERY}`).body).toBe(CODE);
+ expect(parseSmsLink(`SMS:${NUMBER}?BODY=code`).body).toBe(CODE);
+ });
+
+ it('reports missing parts as null', () => {
+ expect(parseSuffix('').body).toBeNull();
+ expect(parseSuffix('?body=').body).toBeNull();
+ expect(parseSuffix('?subject=hi').body).toBeNull();
+ expect(parseSmsLink(`sms:${CODE_QUERY}`).recipient).toBeNull();
+ expect(parseSmsLink('sms:not-a-number?body=nope').recipient).toBeNull();
+ });
+
+ it('ignores literal fragments without removing encoded hashes', () => {
+ // A literal `#` ends the link, so a `?query` sitting after one is fragment text and the
+ // body goes with it. An encoded `%23` is payload and survives decoding.
+ const cases = [
+ [`sms:${NUMBER}#123?body=code`, NUMBER, null],
+ [`sms:${NUMBER}?body=code#123`, NUMBER, CODE],
+ [`sms:${NUMBER};body=code#123?body=other`, NUMBER, CODE],
+ [`sms:${NUMBER}?body=code%23suffix`, NUMBER, 'code#suffix'],
+ [`sms:${NUMBER}?body=code%23suffix#ignored`, NUMBER, 'code#suffix'],
+ [`sms:${NUMBER};body=code%23suffix#ignored`, NUMBER, 'code#suffix'],
+ [`sms:${NUMBER}?body=%2523#ignored`, NUMBER, '%23'],
+ ['sms:#123?body=code', null, null],
+ ];
+
+ cases.forEach(([url, recipient, body]) => {
+ expect(parseSmsLink(url)).toEqual({ recipient, body });
+ });
+ });
+
+ it('rejects non-sms urls', () => {
+ expect(parseSmsLink(null)).toBeNull();
+ expect(parseSmsLink(undefined)).toBeNull();
+ expect(parseSmsLink(`https://example.com${CODE_QUERY}`)).toBeNull();
+ expect(parseSmsLink(`tel:${NUMBER}`)).toBeNull();
+ expect(parseSmsLink(`smsx:${NUMBER}`)).toBeNull();
+ });
+});
diff --git a/hcaptchaSmsLink.js b/hcaptchaSmsLink.js
new file mode 100644
index 0000000..803dc0e
--- /dev/null
+++ b/hcaptchaSmsLink.js
@@ -0,0 +1,180 @@
+/**
+ * Parsing for the `sms:` URLs emitted by the MFA inbound-SMS challenge.
+ *
+ * Covers the RFC 5724 grammar - `sms:recipients[;subscriber-params][?query]` - as well as the
+ * legacy `;body=` form.
+ *
+ * The body carries a one-time code that the backend validates against the message it actually
+ * receives, so it is passed through byte-exact: percent-decoded and nothing else. It must never
+ * be trimmed, reformatted or logged.
+ */
+
+const SMS_SCHEME = 'sms:';
+const SMSTO_SCHEME = 'smsto:';
+const BODY_KEY = 'body';
+const QUERY_SEPARATORS = '&';
+const HEAD_SEPARATORS = ';&';
+
+const isHexDigit = (char) => /^[0-9a-fA-F]$/.test(char);
+
+/**
+ * Percent-decodes as UTF-8, leaving anything that is not a well-formed `%XX` escape as literal
+ * text.
+ *
+ * `+` is deliberately left alone: it means a literal plus in a URI query (RFC 3986), and only
+ * means a space in form encoding, which `sms:` links do not use. This rules out `URLSearchParams`
+ * and `querystring.parse`, both of which apply form decoding.
+ */
+const percentDecode = (value) => {
+ if (value.indexOf('%') < 0) {
+ return value;
+ }
+
+ let decoded = '';
+ let index = 0;
+ while (index < value.length) {
+ if (
+ value[index] !== '%' ||
+ index + 3 > value.length ||
+ !isHexDigit(value[index + 1]) ||
+ !isHexDigit(value[index + 2])
+ ) {
+ decoded += value[index];
+ index++;
+ continue;
+ }
+
+ // Consume the whole run of escapes at once so a multi-byte UTF-8 character split across
+ // several of them decodes as one character.
+ let end = index;
+ while (
+ end + 3 <= value.length &&
+ value[end] === '%' &&
+ isHexDigit(value[end + 1]) &&
+ isHexDigit(value[end + 2])
+ ) {
+ end += 3;
+ }
+
+ const run = value.slice(index, end);
+ try {
+ decoded += decodeURIComponent(run);
+ } catch (e) {
+ // Escapes that are individually well-formed but not valid UTF-8 together.
+ decoded += run;
+ }
+ index = end;
+ }
+
+ return decoded;
+};
+
+const indexOfAny = (value, characters, from) => {
+ for (let index = from; index < value.length; index++) {
+ if (characters.indexOf(value[index]) >= 0) {
+ return index;
+ }
+ }
+ return -1;
+};
+
+/**
+ * Reads a single parameter out of a `separators`-delimited list.
+ *
+ * Decoding happens after splitting so an encoded separator inside a value survives. Empty pairs
+ * are skipped rather than treated as the end of the list: the challenge is reported to emit
+ * `?&body=`, so the first pair is empty.
+ */
+const readValue = (key, parameters, separators) => {
+ let cursor = 0;
+ while (cursor < parameters.length) {
+ const next = indexOfAny(parameters, separators, cursor);
+ const end = next < 0 ? parameters.length : next;
+ const item = parameters.slice(cursor, end);
+ cursor = end + 1;
+
+ const equals = item.indexOf('=');
+ const name = equals < 0 ? item : item.slice(0, equals);
+ if (name.toLowerCase() === key) {
+ const decoded = percentDecode(equals < 0 ? '' : item.slice(equals + 1));
+ return decoded === '' ? null : decoded;
+ }
+ }
+
+ return null;
+};
+
+/**
+ * The challenge only ever targets a single hCaptcha number, so any extra recipients are dropped.
+ *
+ * The surviving characters are an allowlist rather than a denylist: formatting can arrive as
+ * spaces, dashes, parens or dots, and anything left in that the messaging app rejects makes it
+ * silently drop the recipient.
+ */
+const firstRecipient = (list) => {
+ const comma = list.indexOf(',');
+ const decoded = percentDecode(comma < 0 ? list : list.slice(0, comma));
+
+ let normalized = '';
+ for (let index = 0; index < decoded.length; index++) {
+ const current = decoded[index];
+ if (current === '+' || (current >= '0' && current <= '9')) {
+ normalized += current;
+ }
+ }
+
+ return normalized === '' ? null : normalized;
+};
+
+/**
+ * Parses an `sms:` or `smsto:` URL.
+ *
+ * @param {string} [url] the URL the WebView tried to navigate to
+ * @returns {{recipient: ?string, body: ?string}|null} the parsed link, or null for any URL that
+ * is not an SMS link
+ */
+export const parseSmsLink = (url) => {
+ if (typeof url !== 'string') {
+ return null;
+ }
+
+ const lowercased = url.toLowerCase();
+ let start;
+ if (lowercased.startsWith(SMS_SCHEME)) {
+ start = SMS_SCHEME.length;
+ } else if (lowercased.startsWith(SMSTO_SCHEME)) {
+ start = SMSTO_SCHEME.length;
+ } else {
+ return null;
+ }
+
+ // Tolerate the authority-style `sms://` spelling seen in the wild.
+ while (start < url.length && url[start] === '/') {
+ start++;
+ }
+
+ // A literal `#` starts a fragment (RFC 3986), so it and everything after it - including a
+ // `?query` that follows it - is not part of the link. An encoded `%23` stays payload data and
+ // is decoded only after splitting.
+ const fragment = url.indexOf('#', start);
+ const payload = fragment < 0 ? url.slice(start) : url.slice(start, fragment);
+
+ // The query and the `;` subscriber parameters are separate grammars, so `?` has to be split off
+ // first. Folding them together loses the body of a link such as
+ // `sms:+15551234567;phone-context=+1?body=code`.
+ const mark = payload.indexOf('?');
+ const head = mark < 0 ? payload : payload.slice(0, mark);
+ const query = mark < 0 ? '' : payload.slice(mark + 1);
+
+ const headParamsStart = indexOfAny(head, HEAD_SEPARATORS, 0);
+ const recipients = headParamsStart < 0 ? head : head.slice(0, headParamsStart);
+ const headParams = headParamsStart < 0 ? '' : head.slice(headParamsStart + 1);
+
+ // A `;` inside a query is body text, not a separator (RFC 3986 lists it as a sub-delim), so the
+ // query is split on `&` alone. The legacy `;body=` form is read from the head.
+ const body =
+ readValue(BODY_KEY, query, QUERY_SEPARATORS) ||
+ readValue(BODY_KEY, headParams, HEAD_SEPARATORS);
+
+ return { recipient: firstRecipient(recipients), body };
+};