diff --git a/package.json b/package.json index fb1e99fff..d0e7dba53 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "blacksky.community", - "version": "1.127.1", + "version": "1.127.2", "private": true, "packageManager": "pnpm@11.7.0", "engines": { diff --git a/src/lib/notifications/__tests__/notifications-test.ts b/src/lib/notifications/__tests__/notifications-test.ts new file mode 100644 index 000000000..ecb106f83 --- /dev/null +++ b/src/lib/notifications/__tests__/notifications-test.ts @@ -0,0 +1,49 @@ +import * as Notifications from 'expo-notifications' +import {type AtpAgent} from '@atproto/api' + +import {PUBLIC_APPVIEW_DID} from '#/lib/constants' +import {unregisterPushToken} from '#/lib/notifications/notifications' + +jest.mock('expo-notifications', () => ({ + getPermissionsAsync: jest.fn(), + getDevicePushTokenAsync: jest.fn(), + getBadgeCountAsync: jest.fn(), + setBadgeCountAsync: jest.fn(), +})) +jest.mock('#/state/session', () => ({ + useAgent: jest.fn(), + useSession: jest.fn(), +})) +jest.mock('#/analytics', () => ({useAnalytics: jest.fn()})) +jest.mock('#/../modules/expo-background-notification-handler', () => ({ + __esModule: true, + default: {setBadgeCountAsync: jest.fn()}, +})) + +describe('unregisterPushToken', () => { + it('uses the account service when an OAuth agent has no serviceUrl', async () => { + const unregisterPush = jest.fn().mockResolvedValue(undefined) + const agent = { + app: {bsky: {notification: {unregisterPush}}}, + session: {handle: 'alice.test'}, + } as unknown as AtpAgent + + jest.mocked(Notifications.getPermissionsAsync).mockResolvedValue({ + granted: true, + } as Notifications.NotificationPermissionsStatus) + jest.mocked(Notifications.getDevicePushTokenAsync).mockResolvedValue({ + type: 'ios', + data: 'device-token', + }) + + await unregisterPushToken([agent], 'https://blacksky.app') + + expect(unregisterPush).toHaveBeenCalledWith( + expect.objectContaining({ + serviceDid: PUBLIC_APPVIEW_DID, + token: 'device-token', + }), + expect.any(Object), + ) + }) +}) diff --git a/src/lib/notifications/notifications.ts b/src/lib/notifications/notifications.ts index c10554a87..8bed7e1aa 100644 --- a/src/lib/notifications/notifications.ts +++ b/src/lib/notifications/notifications.ts @@ -291,16 +291,22 @@ export async function resetBadgeCount() { await setBadgeCountAsync(0) } -export async function unregisterPushToken(agents: AtpAgent[]) { +export async function unregisterPushToken( + agents: AtpAgent[], + fallbackService?: string, +) { if (!IS_NATIVE) return try { const token = await getPushToken() if (token) { for (const agent of agents) { + const serviceHostname = + agent.serviceUrl?.hostname ?? + (fallbackService ? new URL(fallbackService).hostname : '') await agent.app.bsky.notification.unregisterPush( { - serviceDid: agent.serviceUrl.hostname.includes('staging') + serviceDid: serviceHostname.includes('staging') ? PUBLIC_STAGING_APPVIEW_DID : PUBLIC_APPVIEW_DID, platform: Platform.OS, diff --git a/src/state/queries/notifications/unread.tsx b/src/state/queries/notifications/unread.tsx index a3c4426f6..2a930f097 100644 --- a/src/state/queries/notifications/unread.tsx +++ b/src/state/queries/notifications/unread.tsx @@ -17,6 +17,7 @@ import {EventEmitter} from 'eventemitter3' import BroadcastChannel from '#/lib/broadcast' import {HOME_APPVIEW_PINNED_OPTS} from '#/lib/constants' import {resetBadgeCount} from '#/lib/notifications/notifications' +import {logger as notyLogger} from '#/lib/notifications/util' import {useModerationOpts} from '#/state/preferences/moderation-opts' import {truncateAndInvalidate} from '#/state/queries/util' import {useAgent, useSession} from '#/state/session' @@ -84,11 +85,10 @@ export function Provider({children}: React.PropsWithChildren<{}>) { if (!hasSession || !checkUnreadRef.current) { return } - checkUnreadRef.current() // fire on init - const interval = setInterval( - () => checkUnreadRef.current?.({isPoll: true}), - UPDATE_INTERVAL, - ) + void checkUnreadRef.current().catch(onUnreadCheckError) // fire on init + const interval = setInterval(() => { + void checkUnreadRef.current?.({isPoll: true}).catch(onUnreadCheckError) + }, UPDATE_INTERVAL) return () => clearInterval(interval) }, [hasSession]) @@ -220,6 +220,12 @@ export function Provider({children}: React.PropsWithChildren<{}>) { ) } +function onUnreadCheckError(error: unknown) { + notyLogger.warn('Unread notification check failed', { + message: error instanceof Error ? error.message : String(error), + }) +} + export function useUnreadNotifications() { return useContext(stateContext) } diff --git a/src/state/session/__tests__/oauth-lifecycle-test.ts b/src/state/session/__tests__/oauth-lifecycle-test.ts new file mode 100644 index 000000000..e691509d4 --- /dev/null +++ b/src/state/session/__tests__/oauth-lifecycle-test.ts @@ -0,0 +1,37 @@ +import {afterEach, describe, expect, it, jest} from '@jest/globals' + +import { + emitOauthLifecycleEvent, + setOauthLifecycleSink, +} from '../oauth-lifecycle' + +afterEach(() => setOauthLifecycleSink(null)) + +describe('OAuth lifecycle events', () => { + it('delivers events emitted before the sink subscribes', () => { + emitOauthLifecycleEvent({type: 'deleted', did: 'did:plc:alice'}) + const sink = jest.fn() + + setOauthLifecycleSink(sink) + + expect(sink).toHaveBeenCalledWith({ + type: 'deleted', + did: 'did:plc:alice', + }) + }) + + it('bounds events queued before the sink subscribes', () => { + for (let i = 0; i < 51; i++) { + emitOauthLifecycleEvent({type: 'deleted', did: `did:plc:${i}`}) + } + const sink = jest.fn() + + setOauthLifecycleSink(sink) + + expect(sink).toHaveBeenCalledTimes(50) + expect(sink).not.toHaveBeenCalledWith({ + type: 'deleted', + did: 'did:plc:0', + }) + }) +}) diff --git a/src/state/session/__tests__/oauth-restore-test.ts b/src/state/session/__tests__/oauth-restore-test.ts new file mode 100644 index 000000000..925a8868e --- /dev/null +++ b/src/state/session/__tests__/oauth-restore-test.ts @@ -0,0 +1,47 @@ +import {type OAuthSession} from '@atproto/oauth-client' +import {describe, expect, it, jest} from '@jest/globals' + +import {restoreOAuthSession} from '../oauth-restore' + +describe('OAuth restore coordination', () => { + it('shares one in-flight restore for the same DID', async () => { + let resolve!: (session: OAuthSession) => void + const pending = new Promise(res => { + resolve = res + }) + const client = {restore: jest.fn(() => pending)} + + const first = restoreOAuthSession(client, 'did:plc:alice', 1_000) + const second = restoreOAuthSession(client, 'did:plc:alice', 1_000) + const session = {} as OAuthSession + resolve(session) + + await expect(first).resolves.toBe(session) + await expect(second).resolves.toBe(session) + expect(client.restore).toHaveBeenCalledTimes(1) + }) + + it('keeps a timed-out restore shared until the underlying call settles', async () => { + jest.useFakeTimers() + let resolve!: (session: OAuthSession) => void + const pending = new Promise(res => { + resolve = res + }) + const client = {restore: jest.fn(() => pending)} + + const first = restoreOAuthSession(client, 'did:plc:bob', 10) + const timedOut = expect(first).rejects.toThrow( + 'OAuth session restore timed out', + ) + await jest.advanceTimersByTimeAsync(10) + await timedOut + + const second = restoreOAuthSession(client, 'did:plc:bob', 1_000) + const session = {} as OAuthSession + resolve(session) + + await expect(second).resolves.toBe(session) + expect(client.restore).toHaveBeenCalledTimes(1) + jest.useRealTimers() + }) +}) diff --git a/src/state/session/__tests__/session-test.ts b/src/state/session/__tests__/session-test.ts index 2a906938c..0dd22550e 100644 --- a/src/state/session/__tests__/session-test.ts +++ b/src/state/session/__tests__/session-test.ts @@ -979,6 +979,56 @@ describe('session', () => { `) }) + it('ends an active OAuth session while keeping the remembered account', () => { + const account = { + service: 'https://alice.com', + did: 'did:plc:alice', + handle: 'alice.test', + isOauthSession: true, + } + const agent = new AtpAgent({service: account.service}) + let state = run(getInitialState([]), [ + {type: 'switched-to-account', newAgent: agent, newAccount: account}, + ]) + + state = run(state, [ + {type: 'oauth-session-terminated', accountDid: account.did}, + ]) + + expect(state.currentAgentState.did).toBeUndefined() + expect(state.accounts).toEqual([account]) + expect(state.needsPersist).toBe(true) + }) + + it('ignores OAuth termination for an inactive account', () => { + const alice = { + service: 'https://alice.com', + did: 'did:plc:alice', + handle: 'alice.test', + isOauthSession: true, + } + const bob = { + service: 'https://bob.com', + did: 'did:plc:bob', + handle: 'bob.test', + isOauthSession: true, + } + const aliceAgent = new AtpAgent({service: alice.service}) + const bobAgent = new AtpAgent({service: bob.service}) + const state = run(getInitialState([]), [ + {type: 'switched-to-account', newAgent: aliceAgent, newAccount: alice}, + {type: 'switched-to-account', newAgent: bobAgent, newAccount: bob}, + ]) + + const next = reducer(state, { + type: 'oauth-session-terminated', + accountDid: alice.did, + }) + + expect(next).toBe(state) + expect(next.currentAgentState.did).toBe(bob.did) + }) + it('bails out of update on identical objects', () => { let state = getInitialState([]) diff --git a/src/state/session/index.tsx b/src/state/session/index.tsx index 1c67b892a..fc9865bc9 100644 --- a/src/state/session/index.tsx +++ b/src/state/session/index.tsx @@ -35,12 +35,14 @@ export {isSignupQueued} from './util' import {addSessionDebugLog} from './logging' export type {SessionAccount} from '#/state/session/types' +import {unregisterPushToken} from '#/lib/notifications/notifications' import {clearPersistedQueryStorage} from '#/lib/persisted-query-storage' import { type SessionApiContext, type SessionStateContext, } from '#/state/session/types' import {useOnboardingDispatch} from '#/state/shell/onboarding' +import {setOauthLifecycleSink} from './oauth-lifecycle' const StateContext = createContext({ accounts: [], @@ -109,6 +111,7 @@ export function Provider({children}: React.PropsWithChildren<{}>) { const cancelPendingTask = useOneTaskAtATime() // eslint-disable-next-line react/hook-use-state const [store] = useState(() => new SessionStore()) + const handledOauthDeletions = useRef(new Set()) const state = useSyncExternalStore(store.subscribe, store.getState) const onboardingDispatch = useOnboardingDispatch() @@ -180,6 +183,7 @@ export function Provider({children}: React.PropsWithChildren<{}>) { if (signal.aborted) { return } + handledOauthDeletions.current.delete(account.did) store.dispatch({ type: 'switched-to-account', newAgent: agent, @@ -202,6 +206,7 @@ export function Provider({children}: React.PropsWithChildren<{}>) { addSessionDebugLog({type: 'method:start', method: 'logout'}) cancelPendingTask() const prevState = store.getState() + unregisterActiveOauthPushToken(prevState) store.dispatch({ type: 'logged-out-current-account', }) @@ -233,6 +238,7 @@ export function Provider({children}: React.PropsWithChildren<{}>) { addSessionDebugLog({type: 'method:start', method: 'logout'}) cancelPendingTask() const prevState = store.getState() + unregisterActiveOauthPushToken(prevState) store.dispatch({ type: 'logged-out-every-account', }) @@ -292,6 +298,7 @@ export function Provider({children}: React.PropsWithChildren<{}>) { if (signal.aborted) { return } + handledOauthDeletions.current.delete(account.did) store.dispatch({ type: 'switched-to-account', newAgent: agent, @@ -333,6 +340,9 @@ export function Provider({children}: React.PropsWithChildren<{}>) { account, }) cancelPendingTask() + if (store.getState().currentAgentState.did === account.did) { + unregisterActiveOauthPushToken(store.getState()) + } store.dispatch({ type: 'removed-account', accountDid: account.did, @@ -341,6 +351,22 @@ export function Provider({children}: React.PropsWithChildren<{}>) { }, [store, cancelPendingTask], ) + useEffect(() => { + setOauthLifecycleSink(event => { + if (handledOauthDeletions.current.has(event.did)) return + if (store.getState().currentAgentState.did !== event.did) return + + handledOauthDeletions.current.add(event.did) + store.dispatch({ + type: 'oauth-session-terminated', + accountDid: event.did, + }) + emitSessionDropped() + void clearPersistedQueryStorage(event.did) + }) + return () => setOauthLifecycleSink(null) + }, [store]) + useEffect(() => { setOauthTelemetrySink(event => { ax.metric(event.type, event.payload) @@ -453,6 +479,16 @@ export function Provider({children}: React.PropsWithChildren<{}>) { ) } +function unregisterActiveOauthPushToken(state: State) { + const did = state.currentAgentState.did + const account = state.accounts.find(candidate => candidate.did === did) + if (!account?.isOauthSession) return + void unregisterPushToken( + [state.currentAgentState.agent as AtpAgent], + account.service, + ) +} + function useOneTaskAtATime() { const abortController = useRef(null) const cancelPendingTask = useCallback(() => { diff --git a/src/state/session/oauth-agent.ts b/src/state/session/oauth-agent.ts index 3b0ddeb6c..f161fd9df 100644 --- a/src/state/session/oauth-agent.ts +++ b/src/state/session/oauth-agent.ts @@ -1,4 +1,4 @@ -/* eslint-disable @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-call, @typescript-eslint/no-unsafe-member-access -- Expo OAuth types do not resolve in Linux CI */ +/* eslint-disable @typescript-eslint/no-explicit-any -- Expo OAuth types do not resolve in Linux CI */ import { Agent, type AtpSessionData, @@ -15,6 +15,7 @@ import { } from './agent' import {configureModerationForAccount} from './moderation' import {getOAuthClient} from './oauth-client' +import {restoreOAuthSession} from './oauth-restore' import {type SessionAccount} from './types' export async function oauthCreateAgent(session: OAuthSession) { @@ -34,15 +35,11 @@ export async function oauthResumeSession(account: SessionAccount) { const client = getOAuthClient() let session: OAuthSession try { - session = await Promise.race([ - client.restore(account.did), - new Promise((_, reject) => - setTimeout( - () => reject(new Error('OAuth session restore timed out')), - OAUTH_RESTORE_TIMEOUT_MS, - ), - ), - ]) + session = await restoreOAuthSession( + client, + account.did, + OAUTH_RESTORE_TIMEOUT_MS, + ) } catch (e) { logger.error('oauthResumeSession: restore failed', { did: account.did, diff --git a/src/state/session/oauth-client.ts b/src/state/session/oauth-client.ts index 2317be2c1..661150617 100644 --- a/src/state/session/oauth-client.ts +++ b/src/state/session/oauth-client.ts @@ -8,6 +8,7 @@ import { emitOauthTelemetry, } from '#/state/session/oauth-telemetry' import {OAUTH_BASE_URL, OAUTH_CLIENT_NAME, OAUTH_SCOPE} from './oauth-config' +import {emitOauthLifecycleEvent} from './oauth-lifecycle' const LOCAL_OAUTH_HANDLE_RESOLVER = process.env.EXPO_PUBLIC_OAUTH_HANDLE_RESOLVER @@ -71,6 +72,7 @@ const sessionHooks = { ? cause : undefined logger.warn('oauth: session deleted', {sub, cause: category, message}) + emitOauthLifecycleEvent({type: 'deleted', did: sub}) emitOauthTelemetry({ type: 'oauth:sessionDeleted', payload: {cause: category, message: message?.slice(0, 200)}, diff --git a/src/state/session/oauth-lifecycle.ts b/src/state/session/oauth-lifecycle.ts new file mode 100644 index 000000000..40856ea38 --- /dev/null +++ b/src/state/session/oauth-lifecycle.ts @@ -0,0 +1,26 @@ +export type OauthLifecycleEvent = { + type: 'deleted' + did: string +} + +export type OauthLifecycleSink = (event: OauthLifecycleEvent) => void + +let sink: OauthLifecycleSink | null = null +const pending: OauthLifecycleEvent[] = [] + +export function setOauthLifecycleSink(next: OauthLifecycleSink | null) { + sink = next + if (sink && pending.length) { + const drained = pending.splice(0, pending.length) + for (const event of drained) sink(event) + } +} + +export function emitOauthLifecycleEvent(event: OauthLifecycleEvent) { + if (sink) { + sink(event) + } else { + pending.push(event) + if (pending.length > 50) pending.shift() + } +} diff --git a/src/state/session/oauth-restore.ts b/src/state/session/oauth-restore.ts new file mode 100644 index 000000000..d4672f6ff --- /dev/null +++ b/src/state/session/oauth-restore.ts @@ -0,0 +1,48 @@ +import {type OAuthSession} from '@atproto/oauth-client' + +type OAuthRestoreClient = { + restore(did: string): Promise +} + +const pendingRestores = new Map>() + +export function restoreOAuthSession( + client: OAuthRestoreClient, + did: string, + timeoutMs: number, +): Promise { + let pending = pendingRestores.get(did) + if (!pending) { + pending = client.restore(did) + pendingRestores.set(did, pending) + pending.then( + () => { + if (pendingRestores.get(did) === pending) pendingRestores.delete(did) + }, + () => { + if (pendingRestores.get(did) === pending) pendingRestores.delete(did) + }, + ) + } + + return withTimeout(pending, timeoutMs) +} + +function withTimeout(promise: Promise, timeoutMs: number): Promise { + return new Promise((resolve, reject) => { + const timeout = setTimeout( + () => reject(new Error('OAuth session restore timed out')), + timeoutMs, + ) + promise.then( + value => { + clearTimeout(timeout) + resolve(value) + }, + err => { + clearTimeout(timeout) + reject(err instanceof Error ? err : new Error(String(err))) + }, + ) + }) +} diff --git a/src/state/session/reducer.ts b/src/state/session/reducer.ts index f02e3e486..600b0a85b 100644 --- a/src/state/session/reducer.ts +++ b/src/state/session/reducer.ts @@ -50,6 +50,10 @@ export type Action = | { type: 'logged-out-every-account' } + | { + type: 'oauth-session-terminated' + accountDid: string + } | { type: 'synced-accounts' syncedAccounts: SessionAccount[] @@ -146,7 +150,7 @@ let reducer = (state: State, action: Action): State => { // side effect const account = state.accounts.find(a => a.did === accountDid) - if (account) { + if (account && !account.isOauthSession) { createTemporaryAgentsAndResume([account]) .then(agents => unregisterPushToken(agents)) .then(() => @@ -174,7 +178,7 @@ let reducer = (state: State, action: Action): State => { const accountDid = currentAgentState.did // side effect const account = state.accounts.find(a => a.did === accountDid) - if (account && accountDid) { + if (account && accountDid && !account.isOauthSession) { createTemporaryAgentsAndResume([account]) .then(agents => unregisterPushToken(agents)) .then(() => @@ -203,7 +207,9 @@ let reducer = (state: State, action: Action): State => { } } case 'logged-out-every-account': { - createTemporaryAgentsAndResume(state.accounts) + createTemporaryAgentsAndResume( + state.accounts.filter(account => !account.isOauthSession), + ) .then(agents => unregisterPushToken(agents)) .then(() => logger.debug('Push token unregistered')) .catch(err => { @@ -223,6 +229,14 @@ let reducer = (state: State, action: Action): State => { needsPersist: true, } } + case 'oauth-session-terminated': { + if (state.currentAgentState.did !== action.accountDid) return state + return { + accounts: state.accounts, + currentAgentState: createPublicAgentState(), + needsPersist: true, + } + } case 'synced-accounts': { const {syncedAccounts, syncedCurrentDid} = action return {