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: 46 additions & 2 deletions hooks/__tests__/usePushNotifications.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ jest.mock('@react-native-firebase/messaging', () => () => ({ onTokenRefresh: jes
jest.mock('@/lib/api', () => ({ registerPushToken: jest.fn() }));
jest.mock('@/lib/registerForPushNotifications', () => ({
registerForPushNotificationsAsync: jest.fn(),
pushDeviceInfo: jest.fn(() => ({})),
}));
jest.mock('@/lib/analytics', () => ({ track: jest.fn() }));
// Both zustand stores the hook imports persist through MMKV, whose native
Expand Down Expand Up @@ -144,8 +145,26 @@ describe('routeForLink', () => {
);
});

it('returns nothing for a link it cannot place, rather than guessing', () => {
expect(routeForLink(link('/some/unknown/screen'))).toBeUndefined();
it('opens any other in-app path the way a Universal Link would', () => {
// An admin can point an automated nudge at a screen this map does not
// list; it opens without an app release, keeping its own params but not
// the campaign's.
expect(routeForLink(link('/coins'))).toEqual('/coins');
expect(routeForLink(link('/deposit?method=bank&utm_source=deposit_sepa'))).toEqual({
pathname: '/deposit',
params: { method: 'bank' },
});
});

it('refuses the screens a push must never open by path', () => {
expect(routeForLink(link('/settings/delete-account'))).toBeUndefined();
expect(routeForLink(link('/signup'))).toBeUndefined();
expect(routeForLink(link('/recovery'))).toBeUndefined();
expect(routeForLink(link('/card/3ds/abc'))).toBeUndefined();
});

it('returns nothing for a link it cannot read, rather than guessing', () => {
expect(routeForLink(link('/a b'))).toBeUndefined();
expect(routeForLink('not a url')).toBeUndefined();
expect(routeForLink(undefined)).toBeUndefined();
});
Expand Down Expand Up @@ -410,6 +429,31 @@ describe('handleNotificationResponse', () => {
expect(navigate).toHaveBeenCalledWith(path.CARD_INFO);
});

it('records the automated nudge and version the push came from', () => {
handleNotificationResponse(
iosResponseFor('n-nudge', {
type: 'no-deposit-reminder',
stage: '1',
nudge_key: 'no-deposit-reminder-1',
nudge_version: '3',
utm_source: 'reminder_1',
utm_medium: 'push',
utm_campaign: 'solid_engagement',
link: link('/?utm_source=reminder_1'),
}),
jest.fn(),
);

expect(track).toHaveBeenCalledWith(
TRACKING_EVENTS.PUSH_NOTIFICATION_OPENED,
expect.objectContaining({
notification_type: 'no-deposit-reminder',
nudge_key: 'no-deposit-reminder-1',
nudge_version: '3',
}),
);
});

it('records the open with its type and campaign', () => {
handleNotificationResponse(
iosResponseFor('n1', {
Expand Down
71 changes: 67 additions & 4 deletions hooks/usePushNotifications.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,10 @@ import { TRACKING_EVENTS } from '@/constants/tracking-events';
import { track } from '@/lib/analytics';
import { registerPushToken } from '@/lib/api';
import { pushNotificationData } from '@/lib/pushNotificationData';
import { registerForPushNotificationsAsync } from '@/lib/registerForPushNotifications';
import {
pushDeviceInfo,
registerForPushNotificationsAsync,
} from '@/lib/registerForPushNotifications';
import { SUPPORT_PUSH_TYPE } from '@/lib/support/focus';
import { VaultType } from '@/lib/types';
import { useAttributionStore } from '@/store/useAttributionStore';
Expand Down Expand Up @@ -78,6 +81,13 @@ type NotificationData = {
* pushes, whose destination is one transaction and cannot be a static URL.
*/
link?: string;
/**
* The automated nudge the push belongs to (Growth → Automated nudges) and
* the version of it that was sent, so an open can be credited to the exact
* copy an admin saved.
*/
nudge_key?: string;
nudge_version?: string;
};

/**
Expand Down Expand Up @@ -117,6 +127,52 @@ const ROUTE_BY_LINK_PATH: Record<string, Href> = {
/** Vaults `/savings?vault=` may open: the savings screen's own selector values. */
const LINKABLE_VAULTS: readonly string[] = Object.values(VaultType);

/**
* Screens a push link never opens by path, even though the router knows them:
* signup, recovery and onboarding (a signed-in user has no business there),
* the permission and scanner screens, and settings, where a mistyped link must
* not land someone on account deletion. A path here falls back to `type`.
*/
const PUSH_LINK_DENIED_PREFIXES: readonly string[] = [
'/signup',
'/onboarding',
'/welcome',
'/recovery',
'/passkey-not-supported',
'/notifications',
'/rescue-token',
'/qr-scanner',
'/extensions',
'/settings',
'/agent',
'/card/3ds',
];

/** A plain in-app path: segments of letters, digits and `-._~`, no `//`. */
const PUSH_LINK_PATH = /^\/(?:[A-Za-z0-9\-._~]+\/?)*$/;

/** A query param an in-app route may read; campaign params stay with attribution. */
const PUSH_LINK_PARAM = /^[A-Za-z][A-Za-z0-9_]{0,39}$/;

/**
* Any other in-app path, the way a Universal Link would open it
* (`redirectSystemPath`), so a nudge an admin points at a new screen opens it
* without an app release. Only plain paths outside the denied ones, and only
* short non-campaign params ride along.
*/
function anyInAppRoute(url: URL, pathname: string): Href | undefined {
if (!PUSH_LINK_PATH.test(pathname)) return undefined;
if (PUSH_LINK_DENIED_PREFIXES.some(p => pathname === p || pathname.startsWith(`${p}/`))) {
return undefined;
}
const params: Record<string, string> = {};
url.searchParams.forEach((value, key) => {
if (key.startsWith('utm_') || !PUSH_LINK_PARAM.test(key) || value.length > 200) return;
params[key] = value;
});
return (Object.keys(params).length > 0 ? { pathname, params } : pathname) as Href;
}

/** `/rewards/ai-api?key=`: a key id, which is a 24-hex Mongo id. */
const LINKABLE_AI_API_KEY = /^[a-f0-9]{24}$/i;

Expand Down Expand Up @@ -193,7 +249,7 @@ function routeForLink(link?: string): Href | undefined {
if (action) return { pathname: '/', params: homeLinkParamsFor(action) } as Href;
}

return ROUTE_BY_LINK_PATH[pathname];
return ROUTE_BY_LINK_PATH[pathname] ?? anyInAppRoute(url, pathname);
} catch {
return undefined;
}
Expand Down Expand Up @@ -309,12 +365,16 @@ function recordOpen(data?: NotificationData) {
const { utm_source, utm_medium, utm_campaign, type } = data ?? {};

if (utm_source || utm_campaign) {
useAttributionStore.getState().updateAttribution({
const attribution = useAttributionStore.getState();
attribution.updateAttribution({
utm_source,
utm_medium,
utm_campaign,
attribution_captured_at: Date.now(),
});
// The push is the newest touch: `last_touch_utm_*` on later events
// should name it, not whatever link the user came through before.
attribution.saveLastTouchAttribution({ utm_source, utm_medium, utm_campaign });
}

track(TRACKING_EVENTS.PUSH_NOTIFICATION_OPENED, {
Expand All @@ -326,6 +386,9 @@ function recordOpen(data?: NotificationData) {
// means either a spend push (which never has one) or a notification sent
// before links existed, and both route on `type` instead.
push_link: data?.link,
// The automated nudge and the saved version of it that was sent.
...(data?.nudge_key && { nudge_key: data.nudge_key }),
...(data?.nudge_version && { nudge_version: data.nudge_version }),
// Card spend only: which outcome, and for a decline why and the fix the push
// led with — what turns "opened a decline push" into "opened, then fixed it".
...(data?.status && { status: data.status }),
Expand Down Expand Up @@ -469,7 +532,7 @@ export function usePushNotifications() {
// Re-register token whenever FCM refreshes it (e.g., app reinstall, token expiry)
const unsubscribeTokenRefresh = messaging().onTokenRefresh(async (newToken: string) => {
try {
await registerPushToken(newToken, Platform.OS as 'ios' | 'android');
await registerPushToken(newToken, Platform.OS as 'ios' | 'android', pushDeviceInfo());
} catch (error) {
console.warn('Failed to register refreshed push token:', error);
}
Expand Down
13 changes: 11 additions & 2 deletions lib/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5933,7 +5933,16 @@ export const ensureWebhookSubscription = async (): Promise<EnsureWebhookResponse

// Push Notification Token Management

export const registerPushToken = async (token: string, platform: string) => {
/**
* Register this device's push token. `timezone` (the device's IANA zone) lets
* marketing nudges wait out the user's quiet hours; `appVersion` lets the
* backend tell which builds a token belongs to. Older backends ignore both.
*/
export const registerPushToken = async (
token: string,
platform: string,
device: { timezone?: string; appVersion?: string } = {},
) => {
const jwt = getJWTToken();
const response = await fetch(`${EXPO_PUBLIC_FLASH_API_BASE_URL}/accounts/v1/users/push-token`, {
method: 'POST',
Expand All @@ -5943,7 +5952,7 @@ export const registerPushToken = async (token: string, platform: string) => {
...(jwt ? { Authorization: `Bearer ${jwt}` } : {}),
},
credentials: 'include',
body: JSON.stringify({ token, platform }),
body: JSON.stringify({ token, platform, ...device }),
});
if (!response.ok) throw response;
return response.json();
Expand Down
3 changes: 3 additions & 0 deletions lib/attribution.ts
Original file line number Diff line number Diff line change
Expand Up @@ -283,6 +283,7 @@ export type AttributionChannel =
| 'paid_social'
| 'social'
| 'email'
| 'push'
| 'referral'
| 'direct'
| 'other';
Expand Down Expand Up @@ -318,6 +319,8 @@ export const getAttributionChannel = (data: Partial<AttributionData>): Attributi

if (medium.includes('social') || medium.includes('organic_social')) return 'social';
if (medium.includes('email')) return 'email';
// Our own pushes stamp utm_medium=push (backend push-attribution.constants).
if (medium === 'push') return 'push';
if (medium.includes('organic')) return 'organic';
}

Expand Down
24 changes: 23 additions & 1 deletion lib/registerForPushNotifications.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,32 @@
import { Platform } from 'react-native';
import * as Application from 'expo-application';
import * as Device from 'expo-device';
import * as Notifications from 'expo-notifications';
import messaging from '@react-native-firebase/messaging';

import { registerPushToken } from '@/lib/api';

/** The device's IANA time zone, e.g. "Europe/Lisbon", when the runtime knows it. */
function deviceTimezone(): string | undefined {
try {
const zone = Intl.DateTimeFormat().resolvedOptions().timeZone;
return zone && /^[A-Za-z_]+(?:\/[A-Za-z0-9_+-]+)*$/.test(zone) ? zone : undefined;
} catch {
return undefined;
}
}

/**
* What the backend stores with a push token: the device's time zone (marketing
* nudges wait out quiet hours in it) and the app build.
*/
export function pushDeviceInfo(): { timezone?: string; appVersion?: string } {
return {
timezone: deviceTimezone(),
appVersion: Application.nativeApplicationVersion ?? undefined,
};
}

interface RegisterForPushNotificationsOptions {
/** Whether an undetermined/denied permission should trigger the system prompt. */
requestPermission?: boolean;
Expand Down Expand Up @@ -45,7 +67,7 @@ export async function registerForPushNotificationsAsync({

// Persist token to backend (best-effort — don't block on failure)
const platform = Platform.OS as 'ios' | 'android';
await registerPushToken(fcmToken, platform);
await registerPushToken(fcmToken, platform, pushDeviceInfo());

return fcmToken;
} catch (e: unknown) {
Expand Down
Loading