Skip to content

Commit f52567f

Browse files
committed
feat(console): register the mobile shell's push token and unregister it on removal
Co-Authored-By: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01L6bhgWPe8iKWPE5j7CLjdF
1 parent f6faf75 commit f52567f

7 files changed

Lines changed: 410 additions & 0 deletions

File tree

‎ui/apps/console/src/App.tsx‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,7 @@ import { studioRoutes } from './components/StudioRoute';
4949
import { SetupRoute } from './components/SetupRoute';
5050
import { UnmatchedRoute } from './components/UnmatchedRoute';
5151
import { nativeShellRouteTarget } from './nativeShellRoute';
52+
import { useNativePushRegistration } from './nativePushRegistration';
5253
import { FormPage } from './components/FormPage';
5354
import { InternalFormRoute } from './components/InternalFormRoute';
5455
import { MetadataHmrReloader } from './components/MetadataHmrReloader';
@@ -160,6 +161,10 @@ const BASENAME = resolveBasename();
160161
* active, else the first active app. The shell's published `currentAppName` is
161162
* left to that guard because it is an app NAME, and only the app list turns a
162163
* name into the address its route uses.
164+
*
165+
* Push registration (`useNativePushRegistration`) is called first, so its
166+
* listener for a rotated token is installed in the commit that posts `ready()`,
167+
* and its unregister answers the shell's removal of this connection.
163168
*/
164169
function NativeShellRouting() {
165170
const location = useLocation();
@@ -174,9 +179,11 @@ function NativeShellRouting() {
174179
},
175180
[apps, hostHint, navigate],
176181
);
182+
const unregisterPushDevice = useNativePushRegistration(location.pathname);
177183
const host = useNativeHostRouting({
178184
route: `${location.pathname}${location.search}${location.hash}`,
179185
navigate: navigateShellRoute,
186+
onConnectionRemoved: unregisterPushDevice,
180187
});
181188
const platform = host?.platform;
182189
useEffect(() => {
Lines changed: 295 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,295 @@
1+
/**
2+
* ObjectUI
3+
* Copyright (c) 2024-present ObjectStack Inc.
4+
*
5+
* This source code is licensed under the MIT license found in the
6+
* LICENSE file in the root directory of this source tree.
7+
*/
8+
9+
/**
10+
* Native shell push registration: the Console registers the mobile shell's
11+
* push token with the server's device registry (`POST
12+
* /api/v1/notifications/devices`) under its own session, and unregisters it
13+
* when the shell removes this Console's connection.
14+
*
15+
* The shell holds no API credential, so the Console is the only party that
16+
* can register. What it does, in the shell only (a browser installs nothing):
17+
*
18+
* - Asks the shell for the token (`getPushToken()`, announced as the
19+
* `getPushToken` capability) once per page load, and only once a signed-in
20+
* person has reached a meaningful screen (`/home` or an app) and stayed on it
21+
* for `NATIVE_PUSH_PROMPT_DELAY_MS`. The first call shows the OS permission
22+
* prompt, so it never runs on a sign-in surface. A `null` answer (simulator,
23+
* permission denied, no token) sends nothing.
24+
* - Registers the token, and re-registers when the shell announces a rotated
25+
* one (`objectstack-native:pushTokenChanged`, announced as the
26+
* `pushTokenChanged` capability) or another person signs in on this page.
27+
* The last registration is kept for the session (`sessionStorage`); an equal
28+
* token for the same person is not sent again. The registry moves a token
29+
* from whoever held it, so a new person's registration takes the device over
30+
* from the previous one.
31+
* - Never registers while the session is an impersonation: that would move
32+
* the impersonated person's pushes onto the administrator's device.
33+
* - Sends `deviceId` as the shell's `installId` when the shell exposes one as
34+
* a string, else the id the server answered last time, else none.
35+
* - Sends `origin` only when the page was loaded over `http:` or `https:`: an
36+
* opaque origin reads `"null"`, which the request grammar refuses.
37+
*
38+
* `installId` and the rotation event are optional members of the bridge and
39+
* are feature-detected, so an older shell keeps working.
40+
*/
41+
42+
import { useEffect, useRef, useState } from 'react';
43+
import { ObjectStackClient } from '@objectstack/client';
44+
import { createAuthenticatedFetch, registerBeforeSignOut, useAuth } from '@object-ui/auth';
45+
import {
46+
NATIVE_PUSH_TOKEN_CHANGED_EVENT,
47+
nativeGetPushToken,
48+
nativeHostCan,
49+
useNativeHost,
50+
type NativePushToken,
51+
type NativePushTokenChangedEvent,
52+
type ObjectStackNative,
53+
} from '@object-ui/mobile';
54+
55+
/** The capability a shell announces when it dispatches `NATIVE_PUSH_TOKEN_CHANGED_EVENT`. */
56+
const PUSH_TOKEN_CHANGED_CAPABILITY = 'pushTokenChanged';
57+
58+
/**
59+
* How long a signed-in person stays on a meaningful screen before the Console
60+
* asks the shell for the token (and the OS shows its permission prompt).
61+
*/
62+
export const NATIVE_PUSH_PROMPT_DELAY_MS = 1500;
63+
64+
/** Where the session's last registration is kept. */
65+
export const NATIVE_PUSH_REGISTRATION_KEY = 'objectui:native-push:registration';
66+
67+
/** The session's last registration: who, which token, and the device id the server answered. */
68+
interface PushRegistrationRecord {
69+
userId: string;
70+
token: string;
71+
vendor: NativePushToken['vendor'];
72+
deviceId: string;
73+
}
74+
75+
const SERVER_URL = import.meta.env.VITE_SERVER_URL || '';
76+
77+
let client: ObjectStackClient | null = null;
78+
/** Whether this page load has asked the shell for the token yet. */
79+
let tokenAsked = false;
80+
/** The latest token this page load has seen, from `getPushToken()` or the rotation event. */
81+
let knownToken: NativePushToken | null = null;
82+
/** Registrations run one after another, so two triggers never race to the registry. */
83+
let queue: Promise<void> = Promise.resolve();
84+
85+
function pushClient(): ObjectStackClient {
86+
client ??= new ObjectStackClient({ baseUrl: SERVER_URL, fetch: createAuthenticatedFetch() });
87+
return client;
88+
}
89+
90+
function readRecord(): PushRegistrationRecord | null {
91+
try {
92+
const raw = sessionStorage.getItem(NATIVE_PUSH_REGISTRATION_KEY);
93+
if (!raw) return null;
94+
const value: unknown = JSON.parse(raw);
95+
if (!value || typeof value !== 'object') return null;
96+
const { userId, token, vendor, deviceId } = value as Record<string, unknown>;
97+
if (typeof userId !== 'string' || typeof token !== 'string' || typeof deviceId !== 'string') return null;
98+
if (vendor !== 'apns' && vendor !== 'fcm') return null;
99+
return { userId, token, vendor, deviceId };
100+
} catch {
101+
return null;
102+
}
103+
}
104+
105+
function writeRecord(record: PushRegistrationRecord): void {
106+
try {
107+
sessionStorage.setItem(NATIVE_PUSH_REGISTRATION_KEY, JSON.stringify(record));
108+
} catch {
109+
/* storage unavailable: the next trigger registers again, which the registry treats as a refresh */
110+
}
111+
}
112+
113+
function clearRecord(): void {
114+
try {
115+
sessionStorage.removeItem(NATIVE_PUSH_REGISTRATION_KEY);
116+
} catch {
117+
/* storage unavailable */
118+
}
119+
}
120+
121+
/** The shell's `installId` when it exposes one as a string (a shell that predates it carries none). */
122+
function installIdOf(host: ObjectStackNative): string | null {
123+
const { installId } = host;
124+
return typeof installId === 'string' && installId !== '' ? installId : null;
125+
}
126+
127+
/** The registry's platform for this shell, or `null` for a shell that is neither iOS nor Android. */
128+
function platformOf(host: ObjectStackNative): 'ios' | 'android' | null {
129+
return host.platform === 'ios' || host.platform === 'android' ? host.platform : null;
130+
}
131+
132+
/** `window.location.origin`, only for a page loaded over http or https. */
133+
function pageOrigin(): string | undefined {
134+
if (typeof window === 'undefined') return undefined;
135+
const { protocol, origin } = window.location;
136+
return protocol === 'http:' || protocol === 'https:' ? origin : undefined;
137+
}
138+
139+
function isPushToken(value: unknown): value is NativePushToken {
140+
if (!value || typeof value !== 'object') return false;
141+
const { token, vendor } = value as Record<string, unknown>;
142+
return typeof token === 'string' && token !== '' && (vendor === 'apns' || vendor === 'fcm');
143+
}
144+
145+
function shellAnnounces(host: ObjectStackNative, capability: string): boolean {
146+
try {
147+
return typeof host.has === 'function' && host.has(capability) === true;
148+
} catch {
149+
return false;
150+
}
151+
}
152+
153+
/** Register `token` for `userId` unless the session already registered exactly that. */
154+
function syncRegistration(host: ObjectStackNative, userId: string, token: NativePushToken): Promise<void> {
155+
queue = queue.then(async () => {
156+
const platform = platformOf(host);
157+
if (!platform) return;
158+
const record = readRecord();
159+
if (record && record.userId === userId && record.token === token.token && record.vendor === token.vendor) return;
160+
const deviceId = installIdOf(host) ?? (record?.userId === userId ? record.deviceId : undefined);
161+
const origin = pageOrigin();
162+
try {
163+
const answer = await pushClient().notifications.registerDevice({
164+
token: token.token,
165+
vendor: token.vendor,
166+
platform,
167+
...(deviceId ? { deviceId } : {}),
168+
...(origin ? { origin } : {}),
169+
});
170+
writeRecord({ userId, token: token.token, vendor: token.vendor, deviceId: answer.deviceId });
171+
} catch (error) {
172+
console.warn('[native-push] the device registration failed; pushes will not reach this device until it succeeds', error);
173+
}
174+
});
175+
return queue;
176+
}
177+
178+
/** Whether `pathname` is a screen the person came for: Home or an app. */
179+
function isMeaningfulScreen(pathname: string): boolean {
180+
return pathname === '/home' || pathname.startsWith('/home/') || pathname.startsWith('/apps/');
181+
}
182+
183+
interface LatestState {
184+
host: ObjectStackNative | null;
185+
userId: string | null;
186+
signedIn: boolean;
187+
}
188+
189+
/**
190+
* Unregister the device this Console registered, under the current session.
191+
* Resolves when nothing is left registered; rejects when the device may still
192+
* be registered (no session to unregister with, or the request failed).
193+
*/
194+
async function unregisterThisDevice(latest: { current: LatestState }): Promise<void> {
195+
await queue;
196+
const current = latest.current;
197+
const record = readRecord();
198+
const deviceId = record?.deviceId ?? (current.host ? installIdOf(current.host) : null);
199+
if (!deviceId) return;
200+
if (!current.signedIn) {
201+
throw new Error('[native-push] no session to unregister this device with; it may still be registered');
202+
}
203+
try {
204+
await pushClient().notifications.unregisterDevice(deviceId);
205+
} catch (error) {
206+
// The registry no longer holds it (or never did): nothing is left registered.
207+
if ((error as { httpStatus?: unknown } | null)?.httpStatus !== 404) throw error;
208+
}
209+
clearRecord();
210+
}
211+
212+
/**
213+
* Wires push registration to the native shell. Call it from the component that
214+
* calls `useNativeHostRouting`, before that call, and pass what it returns as
215+
* that call's `onConnectionRemoved`: the rotation listener is then installed in
216+
* the same commit that posts `ready()`, which is when the shell releases a
217+
* token it held. `pathname` is the router's path without the basename.
218+
*
219+
* The returned function unregisters the device this Console registered, under
220+
* its own session, and `signOut()` runs it before the session ends. It
221+
* resolves when there is nothing to unregister or the registry no longer holds
222+
* the device, and rejects when the device may still be registered, so the
223+
* shell records the truth. Its identity is stable for the component's life.
224+
*/
225+
export function useNativePushRegistration(pathname: string): () => Promise<void> {
226+
const host = useNativeHost();
227+
const { user, session, isAuthenticated } = useAuth();
228+
const signedIn = isAuthenticated && typeof user?.id === 'string' && user.id !== '';
229+
// An impersonation never registers: it would move the impersonated person's
230+
// pushes onto the administrator's device.
231+
const userId = signedIn && !session?.impersonatedBy ? (user?.id ?? null) : null;
232+
const meaningful = isMeaningfulScreen(pathname);
233+
234+
const latest = useRef<LatestState>({ host, userId, signedIn });
235+
useEffect(() => {
236+
latest.current = { host, userId, signedIn };
237+
});
238+
// `useState`'s initializer runs once, so the identity never changes (a memo may be discarded).
239+
const [unregister] = useState(() => () => unregisterThisDevice(latest));
240+
241+
// A token the shell rotated: register it for whoever is signed in now, or
242+
// keep it for the next person who signs in on this page.
243+
useEffect(() => {
244+
if (!host || !shellAnnounces(host, PUSH_TOKEN_CHANGED_CAPABILITY)) return undefined;
245+
const onTokenChanged = (event: Event) => {
246+
const { detail } = event as Partial<NativePushTokenChangedEvent>;
247+
if (!isPushToken(detail)) return;
248+
knownToken = { token: detail.token, vendor: detail.vendor };
249+
const current = latest.current;
250+
if (current.host && current.userId) void syncRegistration(current.host, current.userId, knownToken);
251+
};
252+
window.addEventListener(NATIVE_PUSH_TOKEN_CHANGED_EVENT, onTokenChanged);
253+
return () => window.removeEventListener(NATIVE_PUSH_TOKEN_CHANGED_EVENT, onTokenChanged);
254+
}, [host]);
255+
256+
// A signed-in person with a token already known: register it for them.
257+
useEffect(() => {
258+
if (!host || !userId || !knownToken) return;
259+
void syncRegistration(host, userId, knownToken);
260+
}, [host, userId]);
261+
262+
// No token yet: ask the shell once per page load, after the person has
263+
// reached a meaningful screen, so the OS prompt never interrupts sign-in.
264+
useEffect(() => {
265+
if (!host || !userId || !meaningful || tokenAsked || knownToken) return undefined;
266+
if (!nativeHostCan(host, 'getPushToken')) return undefined;
267+
const timer = window.setTimeout(() => {
268+
if (tokenAsked) return;
269+
tokenAsked = true;
270+
void nativeGetPushToken().then((result) => {
271+
if (result.status !== 'ok' || !isPushToken(result.value)) return;
272+
knownToken = { token: result.value.token, vendor: result.value.vendor };
273+
const current = latest.current;
274+
if (current.host && current.userId) void syncRegistration(current.host, current.userId, knownToken);
275+
});
276+
}, NATIVE_PUSH_PROMPT_DELAY_MS);
277+
return () => window.clearTimeout(timer);
278+
}, [host, userId, meaningful]);
279+
280+
// Signing out ends the session the unregister needs, so it runs first.
281+
useEffect(() => {
282+
if (!host) return undefined;
283+
return registerBeforeSignOut(unregister);
284+
}, [host, unregister]);
285+
286+
return unregister;
287+
}
288+
289+
/** Test seam: forget this page load's token, ask and client. */
290+
export function resetNativePushRegistrationForTests(): void {
291+
client = null;
292+
tokenAsked = false;
293+
knownToken = null;
294+
queue = Promise.resolve();
295+
}

0 commit comments

Comments
 (0)