diff --git a/src/ageAssurance/useBeginAgeAssurance.ts b/src/ageAssurance/useBeginAgeAssurance.ts index 8ce68476e..0b54cb527 100644 --- a/src/ageAssurance/useBeginAgeAssurance.ts +++ b/src/ageAssurance/useBeginAgeAssurance.ts @@ -51,10 +51,13 @@ export function useBeginAgeAssurance() { * allowed to preset that header where a session-backed one is not, which * also makes the old `refreshJwt = ''` clone unnecessary. */ - const scopedClient = createLexClient({ - service: APPVIEW, - headers: {authorization: `Bearer ${token}`}, - }) + const scopedClient = createLexClient( + { + service: APPVIEW, + headers: {authorization: `Bearer ${token}`}, + }, + {includeDeviceSessionHeaders: true}, + ) ax.metric('ageAssurance:api:begin', { platform: Platform.OS, diff --git a/src/analytics/identifiers/device.test.ts b/src/analytics/identifiers/device.test.ts new file mode 100644 index 000000000..edce1da14 --- /dev/null +++ b/src/analytics/identifiers/device.test.ts @@ -0,0 +1,28 @@ +import AsyncStorage from '@react-native-async-storage/async-storage' + +import {device} from '#/storage' +import {getAndMigrateDeviceId, getDeviceId} from './device' + +jest.mock('#/storage', () => ({ + device: { + get: jest.fn(), + set: jest.fn(), + }, +})) + +beforeEach(() => { + jest.clearAllMocks() +}) + +describe('device identifier', () => { + it('reads the migrated ID from memory after initialization', async () => { + jest.mocked(AsyncStorage.getItem).mockResolvedValue('legacy-device-id') + + await expect(getAndMigrateDeviceId()).resolves.toBe('legacy-device-id') + jest.mocked(device.get).mockClear() + + expect(getDeviceId()).toBe('legacy-device-id') + expect(getDeviceId()).toBe('legacy-device-id') + expect(device.get).not.toHaveBeenCalled() + }) +}) diff --git a/src/analytics/identifiers/device.ts b/src/analytics/identifiers/device.ts index ac5014354..c0600ddf5 100644 --- a/src/analytics/identifiers/device.ts +++ b/src/analytics/identifiers/device.ts @@ -4,23 +4,22 @@ import AsyncStorage from '@react-native-async-storage/async-storage' import {device} from '#/storage' const LEGACY_STABLE_ID = 'STATSIG_LOCAL_STORAGE_STABLE_ID' +let deviceId = device.get(['deviceId']) export async function getAndMigrateDeviceId() { - const migrated = getDeviceId() - if (migrated) return migrated - const id = (await AsyncStorage.getItem(LEGACY_STABLE_ID)) || uuid.v4() - device.set(['deviceId'], id) - return id + if (deviceId) return deviceId + deviceId = (await AsyncStorage.getItem(LEGACY_STABLE_ID)) || uuid.v4() + device.set(['deviceId'], deviceId) + return deviceId } export function getDeviceId() { - return device.get(['deviceId']) + return deviceId } export function getDeviceIdOrThrow() { - const id = device.get(['deviceId']) - if (!id) { + if (!deviceId) { throw new Error(`deviceId is not set, call getAndMigrateDeviceId first`) } - return id + return deviceId } diff --git a/src/analytics/identifiers/session.ts b/src/analytics/identifiers/session.ts index 1699d474a..a681d41e1 100644 --- a/src/analytics/identifiers/session.ts +++ b/src/analytics/identifiers/session.ts @@ -25,7 +25,7 @@ export function getInitialSessionId() { * generally be trusted to be up to date. */ export function getSessionId() { - return device.get(['nativeSessionId']) + return sessionId } export function useSessionId() { diff --git a/src/analytics/identifiers/session.web.ts b/src/analytics/identifiers/session.web.ts index c126a54cc..f9e769e29 100644 --- a/src/analytics/identifiers/session.web.ts +++ b/src/analytics/identifiers/session.web.ts @@ -28,7 +28,7 @@ export function getInitialSessionId() { * generally be trusted to be up to date. */ export function getSessionId() { - return window.sessionStorage.getItem(SESSION_ID_KEY) + return sessionId } export function useSessionId() { diff --git a/src/lib/api/feed/custom.ts b/src/lib/api/feed/custom.ts index c3329af76..ca616fa83 100644 --- a/src/lib/api/feed/custom.ts +++ b/src/lib/api/feed/custom.ts @@ -123,9 +123,10 @@ let loggedOutAppviewClient: Client | undefined * own failure handling and should not move the app-wide network signal. */ function getLoggedOutAppviewClient(): Client { - return (loggedOutAppviewClient ??= createLexClient({ - service: PUBLIC_APPVIEW, - })) + return (loggedOutAppviewClient ??= createLexClient( + {service: PUBLIC_APPVIEW}, + {includeDeviceSessionHeaders: true}, + )) } /* diff --git a/src/lib/lexClient.test.ts b/src/lib/lexClient.test.ts new file mode 100644 index 000000000..718ddb811 --- /dev/null +++ b/src/lib/lexClient.test.ts @@ -0,0 +1,73 @@ +import {beforeEach, describe, expect, it, jest} from '@jest/globals' + +jest.mock('#/analytics/identifiers', () => ({ + getDeviceId: jest.fn(), + getSessionId: jest.fn(), +})) + +import {getDeviceId, getSessionId} from '#/analytics/identifiers' +import {app} from '#/lexicons' +import {createLexClient} from './lexClient' + +const fetchHandler = jest.fn( + (_path: `/${string}`, _init: RequestInit): Promise => + Promise.resolve( + new Response( + JSON.stringify({did: 'did:plc:alice', handle: 'alice.test'}), + {headers: {'content-type': 'application/json'}}, + ), + ), +) + +function requestHeaders(call: number): Headers { + return new Headers(fetchHandler.mock.calls[call][1].headers) +} + +describe('createLexClient', () => { + beforeEach(() => { + fetchHandler.mockClear() + }) + + it('sends the current device and session identifiers on every request', async () => { + jest.mocked(getDeviceId).mockReturnValue('device-123') + jest.mocked(getSessionId).mockReturnValue('session-123') + const client = createLexClient( + {fetchHandler}, + {includeDeviceSessionHeaders: true}, + ) + + await client.call(app.bsky.actor.getProfile, {actor: 'alice.test'}) + jest.mocked(getSessionId).mockReturnValue('session-456') + await client.call(app.bsky.actor.getProfile, {actor: 'alice.test'}) + + expect(requestHeaders(0).get('x-atproto-device-id')).toBe('device-123') + expect(requestHeaders(0).get('x-atproto-session-id')).toBe('session-123') + expect(requestHeaders(1).get('x-atproto-device-id')).toBe('device-123') + expect(requestHeaders(1).get('x-atproto-session-id')).toBe('session-456') + }) + + it('omits identifiers unless the destination explicitly opts in', async () => { + jest.mocked(getDeviceId).mockReturnValue('device-123') + jest.mocked(getSessionId).mockReturnValue('session-123') + const client = createLexClient({fetchHandler}) + + await client.call(app.bsky.actor.getProfile, {actor: 'alice.test'}) + + expect(requestHeaders(0).get('x-atproto-device-id')).toBeNull() + expect(requestHeaders(0).get('x-atproto-session-id')).toBeNull() + }) + + it('omits the device identifier before initialization', async () => { + jest.mocked(getDeviceId).mockReturnValue(undefined) + jest.mocked(getSessionId).mockReturnValue('session-123') + const client = createLexClient( + {fetchHandler}, + {includeDeviceSessionHeaders: true}, + ) + + await client.call(app.bsky.actor.getProfile, {actor: 'alice.test'}) + + expect(requestHeaders(0).get('x-atproto-device-id')).toBeNull() + expect(requestHeaders(0).get('x-atproto-session-id')).toBe('session-123') + }) +}) diff --git a/src/lib/lexClient.ts b/src/lib/lexClient.ts index 568f9c142..6635108a4 100644 --- a/src/lib/lexClient.ts +++ b/src/lib/lexClient.ts @@ -1,10 +1,47 @@ import { type Agent, type AgentOptions, + buildAgent, Client, type ClientOptions, } from '@atproto/lex' +import {getDeviceId, getSessionId} from '#/analytics/identifiers' + +type CreateLexClientOptions = ClientOptions & { + /** + * Include the stable device ID and current session ID on every request. + * Enable only when the request is bound for a trusted service. + */ + includeDeviceSessionHeaders?: boolean +} + +/** + * Adds the current analytics identifiers to every AT Protocol request. Values + * are read at dispatch time so session rotation does not require rebuilding + * long-lived clients. + */ +function withDeviceSessionHeaders(agentOptions: Agent | AgentOptions): Agent { + const agent = buildAgent(agentOptions) + return { + get did() { + return agent.did + }, + fetchHandler(path, init) { + const headers = new Headers(init.headers) + const deviceId = getDeviceId() + const sessionId = getSessionId() + if (deviceId) { + headers.set('x-atproto-device-id', deviceId) + } + if (sessionId) { + headers.set('x-atproto-session-id', sessionId) + } + return agent.fetchHandler(path, {...init, headers}) + }, + } +} + /** * App-standard factory for lex {@link Client}s. Use this instead of `new * Client(...)` so every client shares the same lenient response processing. @@ -20,9 +57,16 @@ import { */ export function createLexClient( agent: Agent | AgentOptions, - options?: ClientOptions, + options: CreateLexClientOptions = {}, ): Client { - return new Client(agent, {strictResponseProcessing: false, ...options}) + const {includeDeviceSessionHeaders, ...clientOptions} = options + return new Client( + includeDeviceSessionHeaders ? withDeviceSessionHeaders(agent) : agent, + { + strictResponseProcessing: false, + ...clientOptions, + }, + ) } /** @@ -41,10 +85,12 @@ export function createLexClient( * input, and a typo'd or dead service must not be reported as the app losing * network reachability. * - * `appLabelers: null` suppresses the global `Client.appLabelers` static: these - * are `com.atproto.server` calls to a host the user typed, which have no use - * for moderation labels, and the header would disclose the app's configured - * moderation authorities to an arbitrary third-party server. + * The default `includeDeviceSessionHeaders: false` keeps stable analytics IDs + * off these requests. `appLabelers: null` also suppresses the global + * `Client.appLabelers` static: these are `com.atproto.server` calls to a host the + * user typed, which have no use for moderation labels, and the header would + * disclose the app's configured moderation authorities to an arbitrary + * third-party server. */ export function createServiceClient(service: string): Client { return createLexClient({service}, {appLabelers: null}) diff --git a/src/state/session/__tests__/clients-test.ts b/src/state/session/__tests__/clients-test.ts index ec0e8d99c..758da293e 100644 --- a/src/state/session/__tests__/clients-test.ts +++ b/src/state/session/__tests__/clients-test.ts @@ -7,6 +7,11 @@ jest.mock('#/state/events', () => ({ emitNetworkLost: jest.fn(), })) +jest.mock('#/analytics/identifiers', () => ({ + getDeviceId: () => 'device-123', + getSessionId: () => 'session-456', +})) + jest.mock('jwt-decode', () => ({ jwtDecode() { return {scope: 'com.atproto.access'} @@ -111,6 +116,16 @@ describe('buildAppviewClient', () => { ).toBe(BLUESKY_PROXY_HEADER.get()) }) + it('emits the device and session headers', async () => { + const client = buildAppviewClient(makeSession(fetchMock)) + + await client.call(app.bsky.actor.getProfile, {actor: HANDLE}) + + const headers = headersFor(fetchMock, 'app.bsky.actor.getProfile') + expect(headers.get('x-atproto-device-id')).toBe('device-123') + expect(headers.get('x-atproto-session-id')).toBe('session-456') + }) + it('emits an account subscription exactly once', async () => { const client = buildAppviewClient(makeSession(fetchMock)) client.setLabelers(['did:plc:labeler']) @@ -205,6 +220,8 @@ describe('buildPdsClient', () => { const headers = headersFor(fetchMock, 'com.atproto.server.getSession') expect(headers.get('atproto-proxy')).toBeNull() expect(headers.get('atproto-accept-labelers')).toBeNull() + expect(headers.get('x-atproto-device-id')).toBeNull() + expect(headers.get('x-atproto-session-id')).toBeNull() }) it('resolves the relative xrpc path against the account host', async () => { @@ -249,6 +266,8 @@ describe('buildChatClient', () => { */ expect(headers.get('atproto-proxy')).toBe(CHAT_PROXY_SERVICE) expect(headers.get('authorization')).toBe('Bearer access-jwt') + expect(headers.get('x-atproto-device-id')).toBe('device-123') + expect(headers.get('x-atproto-session-id')).toBe('session-456') }) it('emits a global app labeler once, redacted', async () => { diff --git a/src/state/session/clients.ts b/src/state/session/clients.ts index b1ba60be9..dbcd9540b 100644 --- a/src/state/session/clients.ts +++ b/src/state/session/clients.ts @@ -28,7 +28,10 @@ import {networkAwareFetch} from './network' * fetch, which is `networkAwareFetch` wrapped in the disposal kill switch. */ export function buildAppviewClient(agent: Agent): Client { - return createLexClient(agent, {service: BLUESKY_PROXY_HEADER.get()}) + return createLexClient(agent, { + service: BLUESKY_PROXY_HEADER.get(), + includeDeviceSessionHeaders: true, + }) } /** @@ -62,6 +65,7 @@ export function buildPdsClient(agent: Agent): Client { export function buildChatClient(agent: Agent): Client { return createLexClient(agent, { service: CHAT_PROXY_SERVICE, + includeDeviceSessionHeaders: true, }) } @@ -148,8 +152,11 @@ let publicLexClient: Client | undefined * building the bundle. */ export function getPublicAppviewClient(): Client { - return (publicLexClient ??= createLexClient({ - service: PUBLIC_BSKY_SERVICE, - fetch: networkAwareFetch, - })) + return (publicLexClient ??= createLexClient( + { + service: PUBLIC_BSKY_SERVICE, + fetch: networkAwareFetch, + }, + {includeDeviceSessionHeaders: true}, + )) }