From 1c6d21c76c0a595ded16494000488d5e10de55ba Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 10 Nov 2026 00:59:50 +0000 Subject: [PATCH 1/3] feat(push): open a tap on the saved connection that sent it Claude-Session: https://claude.ai/code/session_01QSeKYnW1Xf6HDSWz1eGAqv Co-authored-by: Claude --- app/_layout.tsx | 3 +- hooks/usePushRouting.ts | 80 ++++++++++++++++++++++++----- lib/connections/model.ts | 23 ++++++++- lib/push-notifications.ts | 105 +++++++++++++++++++++++++++++++++++--- 4 files changed, 188 insertions(+), 23 deletions(-) diff --git a/app/_layout.tsx b/app/_layout.tsx index 22f2904..24c50b6 100644 --- a/app/_layout.tsx +++ b/app/_layout.tsx @@ -40,7 +40,6 @@ hydrateAppLock(); */ export default function RootLayout() { const router = useRouter(); - const serverUrl = useServerStore((s) => s.serverUrl); const hydrate = useServerStore((s) => s.hydrate); useEffect(() => { @@ -65,7 +64,7 @@ export default function RootLayout() { (route: string) => router.navigate(consoleScreenHref(route, Date.now())), [router] ); - usePushRouting(serverUrl, openRoute); + usePushRouting(openRoute); useEffect(() => startAppLock(), []); const appLocked = useSecurityStore(isAppLocked); diff --git a/hooks/usePushRouting.ts b/hooks/usePushRouting.ts index 88add89..011d50d 100644 --- a/hooks/usePushRouting.ts +++ b/hooks/usePushRouting.ts @@ -1,23 +1,40 @@ /** - * usePushRouting — opens the Console route a tapped notification points at. + * usePushRouting — opens the Console route a tapped notification points at, + * on the saved connection that sent it. * * Covers taps while the app runs (listener) and the cold start from a tap * (`getLastNotificationResponseAsync`). Each notification is routed once, even * though the cold-start response stays readable for the life of the process. * + * Which connection a tap opens on is `pushTapTarget` (the push's `origin` + * against the saved connections, and the organization's server lock). A tap + * for another saved connection switches to it through the store's `select` — + * the switcher's path — and only then asks for the route, so the route reaches + * the new connection's Console (the WebView holds it until that Console is + * ready) and never the document being left. + * + * A tap waits, held, until the saved connections are loaded and the app lock + * is open: a switch is a change the switcher cannot make while the app is + * locked either, and the route follows it. Only the latest held tap is kept. + * * Token acquisition is NOT done here: the Console asks for the token over the * bridge (`getPushToken`) once the user is signed in, so the OS permission * prompt appears at a moment the Console chooses. `usePushTokenChanges` only * listens for tokens the OS reports (rotation) — it never asks for one. */ -import { useEffect, useRef } from "react"; +import { useEffect, useRef, useState } from "react"; import * as Notifications from "expo-notifications"; import { addPushTokenChangeListener, configureForegroundHandler, + pushSenderFromResponse, + pushTapTarget, routeFromResponse, } from "~/lib/push-notifications"; +import { addBreadcrumb } from "~/lib/sentry"; import type { PushTokenResult } from "~/lib/shell/bridge/protocol"; +import { useServerStore } from "~/stores/server-store"; +import { isAppLocked, useSecurityStore } from "~/stores/security-store"; const routed = new Set(); @@ -26,39 +43,78 @@ export function _resetRoutedNotifications(): void { routed.clear(); } -export function usePushRouting(serverUrl: string | null, onRoute: (route: string) => void): void { +/** + * Open one tap: pick its connection, switch to it when it is not the current + * one, then hand the route on. Reads the stores as they are now. + */ +async function openTap( + response: Notifications.NotificationResponse, + onRoute: (route: string) => void +): Promise { + const store = useServerStore.getState(); + const target = pushTapTarget(pushSenderFromResponse(response), { + connections: store.connections, + managed: store.managed, + }); + if (target.kind === "drop") { + addBreadcrumb({ category: "push", message: "push tap dropped", data: { reason: target.reason } }); + return; + } + const { connection } = target; + const route = routeFromResponse(response, connection.serverUrl); + if (route === null) return; + if (connection.host !== store.currentHost) { + await store.select(connection.host); + // Something else moved the current connection meanwhile: the route was not for it. + if (useServerStore.getState().currentHost !== connection.host) return; + } + onRoute(route); +} + +export function usePushRouting(onRoute: (route: string) => void): void { const onRouteRef = useRef(onRoute); useEffect(() => { onRouteRef.current = onRoute; }, [onRoute]); + const ready = useServerStore((s) => s.isReady); + const appLocked = useSecurityStore(isAppLocked); + const [held, setHeld] = useState(null); + useEffect(() => { configureForegroundHandler(); }, []); useEffect(() => { - if (!serverUrl) return; - - const handle = (response: Notifications.NotificationResponse) => { + let mounted = true; + const take = (response: Notifications.NotificationResponse) => { const id = response.notification?.request?.identifier; if (id) { if (routed.has(id)) return; routed.add(id); } - const route = routeFromResponse(response, serverUrl); - if (route) onRouteRef.current(route); + setHeld(response); }; - const sub = Notifications.addNotificationResponseReceivedListener(handle); + const sub = Notifications.addNotificationResponseReceivedListener(take); void Notifications.getLastNotificationResponseAsync() .then((response) => { - if (response) handle(response); + if (response && mounted) take(response); }) .catch(() => { // No cold-start response available — nothing to route. }); - return () => sub.remove(); - }, [serverUrl]); + return () => { + mounted = false; + sub.remove(); + }; + }, []); + + useEffect(() => { + if (held === null || !ready || appLocked) return; + setHeld(null); + void openTap(held, (route) => onRouteRef.current(route)); + }, [held, ready, appLocked]); } /** diff --git a/lib/connections/model.ts b/lib/connections/model.ts index e56499a..34dd872 100644 --- a/lib/connections/model.ts +++ b/lib/connections/model.ts @@ -10,7 +10,7 @@ * `stores/server-store.ts` publishes it, and removal's sign-out lives in * `./sign-out.ts`. */ -import { normalizeServerUrl, parseUrl, safeConsoleRoute } from "~/lib/shell/console-url"; +import { normalizeServerUrl, originOf, parseUrl, safeConsoleRoute } from "~/lib/shell/console-url"; import { DEFAULT_BRAND_COLOR, displayName, @@ -125,6 +125,27 @@ export function currentConnection(state: Connections): Connection | null { return state.list.find((c) => c.host === state.current) ?? null; } +/** + * The saved connection whose Console is loaded from `origin`, or `null`. + * + * A connection's origin is `scheme://host` of its server URL (`originOf`: the + * stored URL is normalized, so the host is lower-cased and the scheme's + * default port dropped), which is what its Console reads as + * `window.location.origin`. `origin` is compared with it byte for byte: no + * case folding, no port guessing, no host-only match. A value that is not a + * string matches nothing. One host is one connection, so at most one matches. + * + * A lookup key only: the shell never connects to, saves or builds a URL from + * an origin it was handed. + */ +export function connectionByOrigin( + list: readonly Connection[], + origin: unknown +): Connection | null { + if (typeof origin !== "string") return null; + return list.find((c) => originOf(c.serverUrl) === origin) ?? null; +} + /** * Save a connection and make it current. A host already in the list keeps its * place and `addedAt`; its label, branding and URL are refreshed, and its last diff --git a/lib/push-notifications.ts b/lib/push-notifications.ts index 8c0a6f2..af2380e 100644 --- a/lib/push-notifications.ts +++ b/lib/push-notifications.ts @@ -11,7 +11,8 @@ * - tell the Console when the OS reports a token (rotation), so it can * register the new one (`addPushTokenChangeListener`, delivered as the * `objectstack-native:pushTokenChanged` window event); - * - turn a tapped notification into a Console route. + * - turn a tapped notification into a Console route, on the saved connection + * that sent it (`pushTapTarget`). * * No React here; `hooks/usePushRouting` owns the listener lifecycle. */ @@ -21,17 +22,21 @@ import * as Device from "expo-device"; import * as Notifications from "expo-notifications"; import { routeFromConsoleUrl, safeConsoleRoute } from "~/lib/shell/console-url"; import type { PushTokenResult } from "~/lib/shell/bridge/protocol"; +import { connectionByOrigin, type Connection } from "~/lib/connections/model"; +import { isLocked, lockedHost, type ManagedConfig } from "~/lib/managed-config/model"; export type PermissionOutcome = "granted" | "denied" | "undetermined"; /** * The `data` payload a server-sent notification carries. `route` is the * Console route to open on tap; `url` is accepted when it points into this - * server's Console. + * server's Console. `origin` names the server that sent it (see + * {@link pushSenderFromResponse}). */ export interface PushDataPayload { route?: string; url?: string; + origin?: string; [key: string]: unknown; } @@ -195,19 +200,103 @@ export function routeFromResponse( response: Notifications.NotificationResponse | null | undefined, serverUrl: string | null ): string | null { + for (const data of payloadCandidates(response)) { + const route = routeFromPushData(data, serverUrl); + if (route) return route; + } + return null; +} + +/** The dictionaries a tap response may carry the server's keys in, in reading order. */ +function payloadCandidates( + response: Notifications.NotificationResponse | null | undefined +): (PushDataPayload | null)[] { const request = response?.notification?.request; - if (!request) return null; + if (!request) return []; const trigger = request.trigger as { payload?: unknown } | null | undefined; const userInfo = asPayload(trigger?.payload); - const candidates = [ + return [ asPayload(request.content?.data), userInfo, asPayload(userInfo?.body), asPayload(userInfo?.data), ]; - for (const data of candidates) { - const route = routeFromPushData(data, serverUrl); - if (route) return route; +} + +/** + * Which server a tapped push says it came from. APNs and FCM tell the app + * nothing about the sender, and every saved server registers the same device + * token, so the push data names it: `origin`, the origin the Console was + * loaded from when it registered the device (objectstack + * `PushDeliveryDataSchema.origin`). + * + * - `named: false`: no dictionary carries `origin` (a server from before the + * member; `null` reads as absent too). + * - `named: true`: the first dictionary that carries one, read in the same + * order as the route. The value is kept as sent, unvalidated: it is only + * ever compared with a saved connection's origin, so a value that is not a + * canonical origin (or not a string) names a sender no connection matches. + */ +export type PushSender = { named: false } | { named: true; origin: unknown }; + +export function pushSenderFromResponse( + response: Notifications.NotificationResponse | null | undefined +): PushSender { + for (const data of payloadCandidates(response)) { + if (data && data.origin !== undefined && data.origin !== null) { + return { named: true, origin: data.origin }; + } } - return null; + return { named: false }; +} + +/** Why a tap opens nothing (see {@link pushTapTarget}). */ +export type PushTapDropReason = + /** The push names a server that is not a saved connection (any more). */ + | "unsaved-origin" + /** The push names no server, and two or more are saved: the sender is unknown. */ + | "unnamed-sender" + /** Nothing is saved. */ + | "no-connection" + /** The organization locked the server, and this connection is not the managed one. */ + | "server-locked"; + +export type PushTapTarget = + | { kind: "open"; connection: Connection } + | { kind: "drop"; reason: PushTapDropReason }; + +/** + * The saved connection a tapped push opens on — or none, and the route is + * dropped. docs/PUSH-NOTIFICATIONS.md, "Which server a tap opens on": + * + * 1. `origin` is a saved connection's origin (byte for byte, + * `connectionByOrigin`): that connection. The current one routes as + * before; another one is switched to first (the caller's part). + * 2. `origin` is present and no saved connection has it: none. The route is + * never opened on another server. + * 3. No `origin` (an older server): the only saved connection, as before + * servers named themselves. With two or more saved the sender cannot be + * told, so none. + * + * Locked by the organization (MDM `lockServer`), only the managed connection + * is open to a tap: a push for any other is dropped, never switched to. + */ +export function pushTapTarget( + sender: PushSender, + state: { connections: readonly Connection[]; managed: ManagedConfig } +): PushTapTarget { + const { connections, managed } = state; + let connection: Connection | null; + if (sender.named) { + connection = connectionByOrigin(connections, sender.origin); + if (!connection) return { kind: "drop", reason: "unsaved-origin" }; + } else { + if (connections.length === 0) return { kind: "drop", reason: "no-connection" }; + if (connections.length > 1) return { kind: "drop", reason: "unnamed-sender" }; + connection = connections[0]; + } + if (isLocked(managed) && lockedHost(connections, managed) !== connection.host) { + return { kind: "drop", reason: "server-locked" }; + } + return { kind: "open", connection }; } From 909e2e899774ba37f563d52b9619761d2326dac0 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 10 Nov 2026 01:02:40 +0000 Subject: [PATCH 2/3] test(push): pin the four tap rules, the MDM and app-lock gates, cold start and the switch order Claude-Session: https://claude.ai/code/session_01QSeKYnW1Xf6HDSWz1eGAqv Co-authored-by: Claude --- __tests__/components/ConsoleScreen.test.tsx | 50 ++++- __tests__/hooks/usePushRouting.test.ts | 235 +++++++++++++++++--- __tests__/lib/connections/model.test.ts | 40 ++++ __tests__/lib/push-notifications.test.ts | 121 ++++++++++ 4 files changed, 419 insertions(+), 27 deletions(-) diff --git a/__tests__/components/ConsoleScreen.test.tsx b/__tests__/components/ConsoleScreen.test.tsx index b62f817..4712d1a 100644 --- a/__tests__/components/ConsoleScreen.test.tsx +++ b/__tests__/components/ConsoleScreen.test.tsx @@ -88,9 +88,11 @@ jest.mock("~/lib/shell/external", () => ({ openExternalUrl: jest.fn() })); const mockPush = jest.fn(); const mockReplace = jest.fn(); +// The Console screen's search params: what a notification tap or app link asks for. +let mockSearchParams: { route?: string; n?: string } = {}; jest.mock("expo-router", () => ({ useRouter: () => ({ push: mockPush, replace: mockReplace, navigate: jest.fn() }), - useLocalSearchParams: () => ({}), + useLocalSearchParams: () => mockSearchParams, Redirect: ({ href }: { href: string }) => { const { Text } = require("react-native"); return {href}; @@ -180,6 +182,7 @@ beforeAll(() => { beforeEach(() => { seed(); + mockSearchParams = {}; mockWebView.props = null; mockWebView.mounts = 0; mockWebView.injectJavaScript.mockReset(); @@ -312,6 +315,51 @@ describe("ConsoleScreen with saved connections", () => { }); }); +describe("ConsoleScreen and a push tap for another saved connection", () => { + const ROUTE = "/apps/hr/leave/4"; + const scripts = () => mockWebView.injectJavaScript.mock.calls.map(([script]) => script); + const gatedTo = (origin: string) => `window.location.origin !== ${JSON.stringify(origin)}`; + + /** The route reaches only ACME's document, after its Console says ready. */ + async function expectRouteOnAcmeOnly() { + expect(mockWebView.mounts).toBe(2); + expect(mockWebView.props.source).toEqual({ uri: `${ACME}/_console/apps/hr` }); + // Held: the new Console has not said ready, and the old document is gone. + expect(scripts().filter((s) => s.includes(ROUTE))).toEqual([]); + + await consoleReady(ACME); + const delivered = scripts().filter((s) => s.includes(ROUTE)); + expect(delivered).toHaveLength(1); + expect(delivered[0]).toContain(gatedTo(ACME)); + expect(delivered.some((s) => s.includes(gatedTo(ERP)))).toBe(false); + } + + it("switched first, then asked for (usePushRouting's order): the route opens on the new connection's Console", async () => { + const { rerender } = render(); + await consoleReady(); + mockWebView.injectJavaScript.mockReset(); + + await act(async () => useServerStore.getState().select("acme.objectos.ai")); + mockSearchParams = { route: ROUTE, n: "1" }; + rerender(); + await expectRouteOnAcmeOnly(); + }); + + it("switch and route in one render: the route still never reaches the document left", async () => { + const { rerender } = render(); + await consoleReady(); + mockWebView.injectJavaScript.mockReset(); + + act(() => { + void useServerStore.getState().select("acme.objectos.ai"); + mockSearchParams = { route: ROUTE, n: "1" }; + rerender(); + }); + await act(async () => undefined); + await expectRouteOnAcmeOnly(); + }); +}); + describe("ConsoleScreen under a managed deployment (MDM)", () => { const LOCKED = { serverUrl: ERP, lockServer: true }; diff --git a/__tests__/hooks/usePushRouting.test.ts b/__tests__/hooks/usePushRouting.test.ts index 30d32ee..ede8a82 100644 --- a/__tests__/hooks/usePushRouting.test.ts +++ b/__tests__/hooks/usePushRouting.test.ts @@ -1,10 +1,14 @@ -import { renderHook, waitFor } from "@testing-library/react-native"; +import { act, renderHook, waitFor } from "@testing-library/react-native"; import * as Notifications from "expo-notifications"; import { usePushRouting, usePushTokenChanges, _resetRoutedNotifications, } from "~/hooks/usePushRouting"; +import { EMPTY_CONNECTIONS, addConnection } from "~/lib/connections/model"; +import { NO_MANAGED_CONFIG, type ManagedConfig } from "~/lib/managed-config/model"; +import { useServerStore } from "~/stores/server-store"; +import { INITIAL_APP_LOCK_STATE, useSecurityStore } from "~/stores/security-store"; // The shared manual mock predates token events; add the one listener used here. jest.mock("expo-notifications", () => ({ @@ -12,63 +16,242 @@ jest.mock("expo-notifications", () => ({ addPushTokenListener: jest.fn(() => ({ remove: jest.fn() })), })); +// The store persists a switch; the write itself is server-url's own tests'. +jest.mock("~/lib/server-url", () => ({ + loadConnections: jest.fn(), + saveConnections: jest.fn(async () => undefined), +})); + const mockListen = Notifications.addNotificationResponseReceivedListener as jest.Mock; const mockLast = Notifications.getLastNotificationResponseAsync as jest.Mock; -const SERVER = "https://acme.example.com"; +const ERP = "https://erp.example.com"; +const ACME = "https://acme.objectos.ai"; +const ERP_HOST = "erp.example.com"; +const ACME_HOST = "acme.objectos.ai"; const response = (id: string, data: Record) => ({ notification: { request: { identifier: id, content: { data } } }, }); +/** Saved connections (the first one current), loaded unless `isReady: false`. */ +function seed( + serverUrls: string[], + opts: { isReady?: boolean; managed?: ManagedConfig } = {} +) { + let state = EMPTY_CONNECTIONS; + serverUrls.forEach((serverUrl, i) => { + state = addConnection( + state, + { kind: "server", label: serverUrl, serverUrl, brandColor: "#000000", initial: "X" }, + i + 1 + ); + }); + const current = state.list[0] ?? null; + useServerStore.setState({ + connections: state.list, + currentHost: current?.host ?? null, + pushLeftRegistered: [], + serverUrl: current?.serverUrl ?? null, + isReady: opts.isReady ?? true, + managed: opts.managed ?? NO_MANAGED_CONFIG, + managedDeclined: null, + }); +} + +/** The tap listener the hook installed. */ +function tap(id: string, data: Record) { + act(() => mockListen.mock.calls[0][0](response(id, data))); +} + +/** The app lock as a return past the timeout leaves it. */ +function lockApp() { + act(() => { + const { dispatch } = useSecurityStore.getState(); + dispatch({ type: "hydrated", settings: { enabled: true, timeoutSeconds: 300 } }); + }); +} + +function unlockApp() { + act(() => { + const { dispatch } = useSecurityStore.getState(); + dispatch({ type: "unlockStarted" }); + dispatch({ type: "unlockFinished", ok: true }); + }); +} + +/** + * Renders the hook with an `onRoute` that records, with each route, the + * connection that was current when it arrived. + */ +function renderRouting() { + const routes: { route: string; current: string | null; serverUrl: string | null }[] = []; + const onRoute = jest.fn((route: string) => { + const { currentHost, serverUrl } = useServerStore.getState(); + routes.push({ route, current: currentHost, serverUrl }); + }); + const rendered = renderHook(() => usePushRouting(onRoute)); + return { onRoute, routes, ...rendered }; +} + +/** Lets the hook's async switch (the store's queued write) settle. */ +async function settle() { + await act(async () => { + await new Promise((resolve) => setTimeout(resolve, 0)); + }); +} + beforeEach(() => { _resetRoutedNotifications(); mockListen.mockReset(); mockListen.mockReturnValue({ remove: jest.fn() }); mockLast.mockReset(); mockLast.mockResolvedValue(null); + useSecurityStore.setState(INITIAL_APP_LOCK_STATE); + seed([ERP, ACME]); }); describe("usePushRouting", () => { it("configures foreground presentation", () => { - renderHook(() => usePushRouting(null, jest.fn())); + renderRouting(); expect(Notifications.setNotificationHandler).toHaveBeenCalled(); }); - it("does not listen until a server is configured", () => { - renderHook(() => usePushRouting(null, jest.fn())); - expect(mockListen).not.toHaveBeenCalled(); + it("rule 1: a push from the current connection routes there, with no switch", async () => { + const { routes } = renderRouting(); + tap("n1", { route: "/apps/crm/lead/1", origin: ERP }); + await settle(); + expect(routes).toEqual([{ route: "/apps/crm/lead/1", current: ERP_HOST, serverUrl: ERP }]); }); - it("routes a tapped notification", () => { - const onRoute = jest.fn(); - renderHook(() => usePushRouting(SERVER, onRoute)); - mockListen.mock.calls[0][0](response("n1", { route: "/apps/crm/lead/1" })); - expect(onRoute).toHaveBeenCalledWith("/apps/crm/lead/1"); + it("rule 2: a push from another saved connection switches to it, then routes", async () => { + const { routes } = renderRouting(); + tap("n2", { route: "/apps/hr/leave/4", origin: ACME }); + await settle(); + // The route arrives only once the store's current connection is the sender. + expect(routes).toEqual([{ route: "/apps/hr/leave/4", current: ACME_HOST, serverUrl: ACME }]); + expect(useServerStore.getState().currentHost).toBe(ACME_HOST); }); - it("routes the cold-start notification once", async () => { - const onRoute = jest.fn(); - mockLast.mockResolvedValue(response("n2", { route: "/home" })); - const { rerender } = renderHook(({ s }) => usePushRouting(s, onRoute), { - initialProps: { s: SERVER }, - }); - await waitFor(() => expect(onRoute).toHaveBeenCalledTimes(1)); - rerender({ s: `${SERVER}/` }); - await waitFor(() => expect(mockLast).toHaveBeenCalledTimes(2)); - expect(onRoute).toHaveBeenCalledTimes(1); + it("rule 2: a url key is checked against the sender's Console, not the current one", async () => { + const { routes } = renderRouting(); + tap("n3", { url: `${ACME}/_console/apps/hr`, origin: ACME }); + await settle(); + expect(routes).toEqual([{ route: "/apps/hr", current: ACME_HOST, serverUrl: ACME }]); + }); + + it("rule 3: a push from a server that is not saved opens nothing and switches nothing", async () => { + const { onRoute } = renderRouting(); + tap("n4", { route: "/apps/crm/lead/1", origin: "https://removed.example.com" }); + tap("n5", { route: "/apps/crm/lead/1", origin: "https://ACME.objectos.ai" }); + await settle(); + expect(onRoute).not.toHaveBeenCalled(); + expect(useServerStore.getState().currentHost).toBe(ERP_HOST); + }); + + it("rule 4: without origin, one saved connection routes there; two or more drop the route", async () => { + const { onRoute, routes } = renderRouting(); + tap("n6", { route: "/apps/crm/lead/1" }); + await settle(); + expect(onRoute).not.toHaveBeenCalled(); + + act(() => seed([ACME])); + tap("n7", { route: "/apps/crm/lead/2" }); + await settle(); + expect(routes).toEqual([{ route: "/apps/crm/lead/2", current: ACME_HOST, serverUrl: ACME }]); + }); + + it("a push without a Console route switches nothing", async () => { + const { onRoute } = renderRouting(); + tap("n8", { url: "https://evil.example.com/x", origin: ACME }); + await settle(); + expect(onRoute).not.toHaveBeenCalled(); + expect(useServerStore.getState().currentHost).toBe(ERP_HOST); + }); + + it("MDM lock: a push for a connection the lock does not allow is dropped, never switched to", async () => { + seed([ERP, ACME], { managed: { serverUrl: ERP, lockServer: true } }); + const { routes } = renderRouting(); + tap("n9", { route: "/apps/hr", origin: ACME }); + await settle(); + expect(routes).toEqual([]); + expect(useServerStore.getState().currentHost).toBe(ERP_HOST); + + tap("n10", { route: "/apps/crm", origin: ERP }); + await settle(); + expect(routes).toEqual([{ route: "/apps/crm", current: ERP_HOST, serverUrl: ERP }]); + }); + + it("app lock: a tap is held while the app is locked, then switches and routes once unlocked", async () => { + lockApp(); + const { routes } = renderRouting(); + tap("n11", { route: "/apps/hr/leave/4", origin: ACME }); + await settle(); + expect(routes).toEqual([]); + expect(useServerStore.getState().currentHost).toBe(ERP_HOST); + + unlockApp(); + await settle(); + expect(routes).toEqual([{ route: "/apps/hr/leave/4", current: ACME_HOST, serverUrl: ACME }]); + }); + + it("app lock: only the latest tap held under the lock is opened", async () => { + lockApp(); + const { routes } = renderRouting(); + tap("n12", { route: "/apps/hr/leave/4", origin: ACME }); + tap("n13", { route: "/apps/crm/lead/9", origin: ERP }); + unlockApp(); + await settle(); + expect(routes).toEqual([{ route: "/apps/crm/lead/9", current: ERP_HOST, serverUrl: ERP }]); + }); + + it("waits for the saved connections to load before choosing one", async () => { + seed([], { isReady: false }); + const { routes } = renderRouting(); + tap("n14", { route: "/apps/hr", origin: ACME }); + await settle(); + expect(routes).toEqual([]); + + act(() => seed([ERP, ACME])); + await settle(); + expect(routes).toEqual([{ route: "/apps/hr", current: ACME_HOST, serverUrl: ACME }]); + }); + + it("cold start: the launching tap follows the same rules, and is routed once across the switch", async () => { + seed([], { isReady: false }); + lockApp(); + mockLast.mockResolvedValue(response("cold", { route: "/apps/hr/leave/4", origin: ACME })); + const { routes, rerender } = renderRouting(); + await settle(); + act(() => seed([ERP, ACME])); + await settle(); + expect(routes).toEqual([]); + + unlockApp(); + await waitFor(() => expect(routes).toHaveLength(1)); + expect(routes[0]).toEqual({ route: "/apps/hr/leave/4", current: ACME_HOST, serverUrl: ACME }); + + // The same response, delivered again by the listener or read again: not routed twice. + tap("cold", { route: "/apps/hr/leave/4", origin: ACME }); + rerender({}); + await settle(); + expect(routes).toHaveLength(1); }); - it("ignores payloads without a Console route", () => { - const onRoute = jest.fn(); - renderHook(() => usePushRouting(SERVER, onRoute)); - mockListen.mock.calls[0][0](response("n3", { url: "https://evil.example.com/x" })); + it("cold start: a launching tap from a server no longer saved opens nothing", async () => { + mockLast.mockResolvedValue( + response("cold-gone", { route: "/apps/hr", origin: "https://removed.example.com" }) + ); + const { onRoute } = renderRouting(); + await settle(); + expect(mockLast).toHaveBeenCalledTimes(1); expect(onRoute).not.toHaveBeenCalled(); + expect(useServerStore.getState().currentHost).toBe(ERP_HOST); }); it("stops listening on unmount", () => { const remove = jest.fn(); mockListen.mockReturnValue({ remove }); - const { unmount } = renderHook(() => usePushRouting(SERVER, jest.fn())); + const { unmount } = renderRouting(); unmount(); expect(remove).toHaveBeenCalled(); }); diff --git a/__tests__/lib/connections/model.test.ts b/__tests__/lib/connections/model.test.ts index e85b07d..f18cebb 100644 --- a/__tests__/lib/connections/model.test.ts +++ b/__tests__/lib/connections/model.test.ts @@ -2,6 +2,7 @@ import { CONNECTIONS_STORAGE_VERSION, EMPTY_CONNECTIONS, addConnection, + connectionByOrigin, connectionFromLegacyUrl, connectionFromProbe, currentConnection, @@ -47,6 +48,45 @@ function three(): Connections { const hosts = (state: Connections) => state.list.map((c) => c.host); +describe("connectionByOrigin", () => { + it("finds the connection whose Console is loaded from that origin", () => { + const state = three(); + expect(connectionByOrigin(state.list, "https://acme.objectos.ai")?.host).toBe( + "acme.objectos.ai" + ); + expect(connectionByOrigin(state.list, "https://nowhere.example.com")).toBeNull(); + }); + + it("derives the origin from the stored server URL: scheme kept, default port dropped, base path not part of it", () => { + const typed = connectionFromLegacyUrl("HTTP://Dev.Example.com:80/os/")!; + let state = addConnection(EMPTY_CONNECTIONS, typed, 1); + state = addConnection(state, { ...erp, serverUrl: "https://erp.example.com:8443" }, 2); + const stored = parseConnections(serializeConnections(state))!; + expect(connectionByOrigin(stored.list, "http://dev.example.com")?.serverUrl).toBe( + "http://dev.example.com/os" + ); + expect(connectionByOrigin(stored.list, "https://erp.example.com:8443")?.host).toBe( + "erp.example.com:8443" + ); + }); + + it("compares byte for byte, and matches nothing that is not a string", () => { + const { list } = three(); + for (const origin of [ + "https://ACME.objectos.ai", + "https://acme.objectos.ai:443", + "https://acme.objectos.ai/", + "http://acme.objectos.ai", + "acme.objectos.ai", + null, + undefined, + 7, + ]) { + expect(connectionByOrigin(list, origin)).toBeNull(); + } + }); +}); + describe("hostOf", () => { it("is the lower-cased host with the default port dropped", () => { expect(hostOf("https://ERP.example.com:443/os")).toBe("erp.example.com"); diff --git a/__tests__/lib/push-notifications.test.ts b/__tests__/lib/push-notifications.test.ts index ba4cc1d..01657f5 100644 --- a/__tests__/lib/push-notifications.test.ts +++ b/__tests__/lib/push-notifications.test.ts @@ -2,12 +2,16 @@ import { acquireDeviceToken, addPushTokenChangeListener, ensurePermission, + pushSenderFromResponse, + pushTapTarget, pushTokenFromDevice, routeFromPushData, routeFromResponse, ANDROID_DEFAULT_CHANNEL_ID, } from "~/lib/push-notifications"; import * as Notifications from "expo-notifications"; +import { EMPTY_CONNECTIONS, addConnection } from "~/lib/connections/model"; +import { NO_MANAGED_CONFIG } from "~/lib/managed-config/model"; // The shared manual mock predates token events; add the one listener used here. jest.mock("expo-notifications", () => ({ @@ -177,6 +181,123 @@ describe("routeFromResponse", () => { }); }); +describe("pushSenderFromResponse", () => { + const android = (data: Record) => + ({ + notification: { request: { content: { data }, trigger: { type: "push" } } }, + }) as unknown as Notifications.NotificationResponse; + const ios = (userInfo: Record) => + ({ + notification: { + request: { + content: { data: (userInfo.body as Record) ?? null }, + trigger: { type: "push", payload: userInfo }, + }, + }, + }) as unknown as Notifications.NotificationResponse; + + it("reads origin from the FCM data map and from beside aps (APNs)", () => { + expect(pushSenderFromResponse(android({ route: "/home", origin: SERVER }))).toEqual({ + named: true, + origin: SERVER, + }); + expect(pushSenderFromResponse(ios({ aps: {}, route: "/home", origin: SERVER }))).toEqual({ + named: true, + origin: SERVER, + }); + }); + + it("names no sender when no dictionary carries origin, or carries it as null", () => { + expect(pushSenderFromResponse(android({ route: "/home" }))).toEqual({ named: false }); + expect(pushSenderFromResponse(android({ route: "/home", origin: null }))).toEqual({ + named: false, + }); + expect(pushSenderFromResponse(null)).toEqual({ named: false }); + }); + + it("keeps a present value as sent, whatever its shape", () => { + expect(pushSenderFromResponse(android({ origin: 42 }))).toEqual({ named: true, origin: 42 }); + expect(pushSenderFromResponse(android({ origin: "" }))).toEqual({ named: true, origin: "" }); + }); +}); + +describe("pushTapTarget", () => { + const ERP = "https://erp.example.com"; + const ACME = "https://acme.objectos.ai:8443"; + const DEV = "http://localhost:3000"; + const input = (serverUrl: string) => ({ + kind: "server" as const, + label: serverUrl, + serverUrl, + brandColor: "#000000", + initial: "X", + }); + let state = addConnection(EMPTY_CONNECTIONS, input(ERP), 1); + state = addConnection(state, input(ACME), 2); + state = addConnection(state, input(`${DEV}/os`), 3); + const three = state.list; + const one = addConnection(EMPTY_CONNECTIONS, input(ERP), 1).list; + const named = (origin: unknown) => ({ named: true as const, origin }); + const target = (sender: Parameters[0], connections = three, managed = NO_MANAGED_CONFIG) => + pushTapTarget(sender, { connections, managed }); + const hostOf = (t: ReturnType) => + t.kind === "open" ? t.connection.host : t.reason; + + it("opens on the saved connection whose origin the push names, current or not", () => { + expect(hostOf(target(named(ERP)))).toBe("erp.example.com"); + expect(hostOf(target(named(ACME)))).toBe("acme.objectos.ai:8443"); + // A base path is not part of the origin. + expect(hostOf(target(named(DEV)))).toBe("localhost:3000"); + }); + + it("matches byte for byte: no case folding, port guessing, path or host-only match", () => { + for (const origin of [ + "HTTPS://erp.example.com", + "https://ERP.example.com", + "https://erp.example.com:443", + "https://erp.example.com/", + "erp.example.com", + "http://erp.example.com", + "https://acme.objectos.ai", + `${DEV}/os`, + "", + 42, + ]) { + expect(target(named(origin))).toEqual({ kind: "drop", reason: "unsaved-origin" }); + } + }); + + it("drops a push from a server that is not saved, even with one connection", () => { + expect(target(named("https://gone.example.com"), one)).toEqual({ + kind: "drop", + reason: "unsaved-origin", + }); + }); + + it("without origin, opens on the only saved connection and drops with two or more", () => { + expect(hostOf(target({ named: false }, one))).toBe("erp.example.com"); + expect(target({ named: false })).toEqual({ kind: "drop", reason: "unnamed-sender" }); + expect(target({ named: false }, [])).toEqual({ kind: "drop", reason: "no-connection" }); + }); + + it("locked by the organization, opens only on the managed connection", () => { + const locked = { serverUrl: ERP, lockServer: true }; + expect(hostOf(target(named(ERP), three, locked))).toBe("erp.example.com"); + expect(target(named(ACME), three, locked)).toEqual({ kind: "drop", reason: "server-locked" }); + // Locked to an address with no saved connection yet: nothing is open to a tap. + const pending = { serverUrl: "https://mdm.example.com", lockServer: true }; + expect(target(named(ERP), three, pending)).toEqual({ kind: "drop", reason: "server-locked" }); + expect(target({ named: false }, one, pending)).toEqual({ + kind: "drop", + reason: "server-locked", + }); + // A managed address without the lock restricts nothing. + expect(hostOf(target(named(ACME), three, { serverUrl: ERP, lockServer: false }))).toBe( + "acme.objectos.ai:8443" + ); + }); +}); + describe("pushTokenFromDevice", () => { it("maps a native token to the bridge shape", () => { expect(pushTokenFromDevice({ type: "ios", data: "apns-tok" })).toEqual({ From f5f9a368650d9fba41e16fb769eccc26d956185f Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 10 Nov 2026 01:03:59 +0000 Subject: [PATCH 3/3] docs(push): which server a tap opens on; retire the current-connection limit Claude-Session: https://claude.ai/code/session_01QSeKYnW1Xf6HDSWz1eGAqv Co-authored-by: Claude --- .changeset/174-push-per-connection.md | 28 ++++++++++++ docs/HYBRID-SHELL.md | 16 ++++--- docs/PUSH-NOTIFICATIONS.md | 61 ++++++++++++++++++++++++--- 3 files changed, 95 insertions(+), 10 deletions(-) create mode 100644 .changeset/174-push-per-connection.md diff --git a/.changeset/174-push-per-connection.md b/.changeset/174-push-per-connection.md new file mode 100644 index 0000000..891aec3 --- /dev/null +++ b/.changeset/174-push-per-connection.md @@ -0,0 +1,28 @@ +--- +"mobile": patch +--- + +Clause-②: no +Metadata-protocol: none + +A tapped push opens on the saved connection that sent it. The platform's push +data now names its server (`origin`, the origin the Console was loaded from +when it registered the device), and the shell compares it byte for byte with +each saved connection's origin: + +- From the current connection: the route opens there, as before. +- From another saved connection: the shell switches to it, the same way the + switcher does, and opens the route on that connection's Console once it has + loaded. The route never reaches the Console being left. +- From a server that is no longer saved: nothing opens; the app shows and the + route is dropped. +- From an older server that names no sender: with one saved connection the + route opens there; with two or more it is dropped, since the sender cannot + be told. + +A server locked by the organization's device management keeps a tap from +switching away from the managed connection: a push for any other saved +connection is dropped. With the app lock on, a tap waits until the user +unlocks, then switches and opens. A cold start from a tap follows the same +rules. The push's `origin` is only used to choose among saved connections: +the app never connects to a server because a push named it. diff --git a/docs/HYBRID-SHELL.md b/docs/HYBRID-SHELL.md index 59adae4..ec07a01 100644 --- a/docs/HYBRID-SHELL.md +++ b/docs/HYBRID-SHELL.md @@ -264,7 +264,9 @@ the system settings page for the app. through the load state machine's `switch` event (see "Load states"): a new WebView on the chosen host at that connection's last route. The bridge's origin check is the current connection's from that render on, so the page -left behind gets no answer. +left behind gets no answer. A push tap from another saved connection switches +the same way, then opens its route on that connection's Console +([PUSH-NOTIFICATIONS.md](./PUSH-NOTIFICATIONS.md#which-server-a-tap-opens-on)). **Removing** (swipe a row left; screen readers get a "Remove" action on the row) signs the connection out (`lib/connections/sign-out.ts`), in this order: @@ -338,7 +340,8 @@ In the shell: connections stay in the store, unlisted, and come back when the lock is lifted) and hides add and the managed row's Remove; removal of that host is refused before any sign-out step, `resetServer()` is answered - `failed`, and the picker opens nothing else. + `failed`, the picker opens nothing else, and a push tap from another saved + connection is dropped rather than switched to. - `trustedHosts` is not read from MDM: the navigation policy and the bridge's trusted origins come only from the build. @@ -1129,9 +1132,12 @@ See [PUSH-NOTIFICATIONS.md](./PUSH-NOTIFICATIONS.md). - **Android without `GET_COOKIE_INFO`.** On a WebView provider that lacks it, the cookie store reports no domains and refuses per-name clearing, so a removed connection's cookies stay. -- **Push taps carry no connection.** A notification is routed by its `route` - to the current connection's Console; a tap on one from another saved server - opens that route on the current one. +- **A push from an older server is dropped when two or more connections are + saved.** A server that predates the push data's `origin` names no sender, + and every saved server registers the same device token, so the shell cannot + tell which one sent it. With one saved connection the tap opens there; with + more it opens nothing (see PUSH-NOTIFICATIONS.md, "Which server a tap opens + on"). - **The app lock counts every trip out of the app.** With a short timeout, a return from anything that sends the app to the background locks it: on Android that includes the Custom Tab of the in-app browser, a file chooser diff --git a/docs/PUSH-NOTIFICATIONS.md b/docs/PUSH-NOTIFICATIONS.md index 0ae0736..178d5fd 100644 --- a/docs/PUSH-NOTIFICATIONS.md +++ b/docs/PUSH-NOTIFICATIONS.md @@ -27,20 +27,70 @@ server ──APNs / FCM──▶ device ──tap──▶ shell (hooks/usePushR - A notification names where a tap goes with one of two keys (see the payload contract below): - `route`: a Console route, e.g. `"/apps/crm/opportunity/123"` (preferred); - - `url`: accepted only when it points into the configured server's Console. + - `url`: accepted only when it points into the sending connection's Console. Anything else is ignored, so a notification cannot steer the shell to another site. A route must be a plain Console path: it starts with `/` (not `//`) and has no `.` / `..` segment (raw or percent-encoded), backslash or control character — the same check app links and the bridge's `navigate` use (`safeConsoleRoute` in `lib/shell/console-url.ts`). +- A notification names the server that sent it with `origin` (see "Which + server a tap opens on" below). With several saved connections, every one of + them registers the same device token, so this is the only way the shell can + tell them apart. + +## Which server a tap opens on + +The platform's push data (`PushDeliveryDataSchema` in objectstack +`packages/spec/src/api/push-delivery.zod.ts`) carries an optional `origin`: +the origin the Console was loaded from when it registered the device +(`window.location.origin`, for example `https://crm.example.com` or +`http://localhost:3000`). The shell compares it byte for byte with each saved +connection's origin, `scheme://host[:port]` of its server URL +(`connectionByOrigin` in `lib/connections/model.ts`). There is no case folding, +port guessing or host-only match: the server sends the canonical form, and a +value in any other form matches nothing. + +`pushTapTarget` (`lib/push-notifications.ts`) picks the connection, and +`hooks/usePushRouting.ts` acts on it: + +| The push | Saved connections | The tap | +|:---|:---|:---| +| `origin` is the current connection's | any | opens the route there | +| `origin` is another saved connection's | any | switches to it (the switcher's path), then opens the route on its Console once that has loaded | +| `origin` is present, no saved connection has it (removed, or never saved) | any | opens nothing; the app shows and the route is dropped | +| no `origin` (a server older than the member) | exactly one | opens the route on it | +| no `origin` | two or more | opens nothing: the sender cannot be told | + +- **The route goes to the new connection's Console, never the one being + left.** The switch is made first. The WebView then re-creates itself on the + new host and holds the route until that Console says it is ready (see "Load + states" in HYBRID-SHELL.md). The navigate script only runs on the current + connection's origin. +- **`origin` is a lookup key, nothing more.** The shell never connects to, + saves or builds a URL from a server a push names, and the `route` / `url` + checks above are unchanged. +- **A managed lock** (MDM `lockServer`, see "Managed deployment" in + HYBRID-SHELL.md) leaves only the managed connection open to a tap. A push + for any other saved connection is dropped and never switched to. While the + managed address waits for its confirm step, every push is dropped. +- **The app lock.** A tap waits while the app lock's overlay is up, and is + opened, switch included, once the user unlocks. The switcher cannot be + reached while the app is locked either. Only the latest tap that waited is + opened. +- **A cold start from a tap** follows the same rules, once the saved + connections have loaded (and the app is unlocked). Each notification is + opened at most once, across a switch too. +- A tap with no usable Console route switches nothing. + ## Payload contract -`route` / `url` are custom keys, delivered differently by each transport. +`route` / `url` / `origin` are custom keys, delivered differently by each +transport. `routeFromResponse` (`lib/push-notifications.ts`) reads, in order, the notification's `content.data`, then the iOS `trigger.payload` (the full APNs `userInfo`), its `body` dictionary, and last its `data` dictionary, and uses -the first valid one. `userInfo.data` is off-contract (never put the key under +the first valid one. `pushSenderFromResponse` reads `origin` in the same order. `userInfo.data` is off-contract (never put the key under `data` on iOS); it is read only as a fallback, after the other three. **APNs (iOS)** — put the key at the top level of the payload, beside `aps`: @@ -48,7 +98,8 @@ the first valid one. `userInfo.data` is off-contract (never put the key under ```json { "aps": { "alert": { "title": "New lead", "body": "Acme Corp" }, "sound": "default" }, - "route": "/apps/crm/lead/123" + "route": "/apps/crm/lead/123", + "origin": "https://crm.example.com" } ``` @@ -64,7 +115,7 @@ dictionary, the Expo push-service shape) is accepted too. "message": { "token": "…", "notification": { "title": "New lead", "body": "Acme Corp" }, - "data": { "route": "/apps/crm/lead/123" } + "data": { "route": "/apps/crm/lead/123", "origin": "https://crm.example.com" } } } ```