diff --git a/__tests__/lib/space-feed-routing.test.ts b/__tests__/lib/space-feed-routing.test.ts index 586020d49..c0b042141 100644 --- a/__tests__/lib/space-feed-routing.test.ts +++ b/__tests__/lib/space-feed-routing.test.ts @@ -23,6 +23,8 @@ type FakeClient = { getFeed: jest.Mock agent: {fetchHandler: jest.Mock} call: jest.Mock + labelers: Set + xrpcDefaults: {appLabelers: null} } function client({did}: {did?: string}): FakeClient { @@ -58,6 +60,8 @@ function client({did}: {did?: string}): FakeClient { fetchHandler, getFeed, agent: {fetchHandler}, + labelers: new Set(), + xrpcDefaults: {appLabelers: null}, call: jest.fn((method: unknown, params: unknown) => method === com.atproto.repo.getRecord ? Promise.resolve({value: config}) diff --git a/src/lib/api/__tests__/community-notifications.test.ts b/src/lib/api/__tests__/community-notifications.test.ts index 49ed53d3d..4cf47f2c4 100644 --- a/src/lib/api/__tests__/community-notifications.test.ts +++ b/src/lib/api/__tests__/community-notifications.test.ts @@ -5,7 +5,9 @@ import {HOME_PROXY_HEADER} from '#/lib/constants' import {createLexClient} from '#/lib/lexClient' import {getErrorName, getErrorStatus} from '#/lib/xrpc-error' import { + GET_GROUPED_NOTIFICATIONS_METHOD, GET_UNREAD_COUNT_METHOD, + getGroupedNotifications, getUnreadCount, LIST_NOTIFICATIONS_METHOD, listNotifications, @@ -17,6 +19,46 @@ const PUBLIC_URI = 'at://did:plc:alice/app.bsky.feed.post/3kpublic' const CID = 'bafyreiacsg6vsw7ppwbnowzsdgstulhrwftirtcnvkcbnfgvhwjrnzfmsu' const STANDARD_LIST = 'app.bsky.notification.listNotifications' const STANDARD_COUNT = 'app.bsky.notification.getUnreadCount' +const STANDARD_GROUPED = 'app.bsky.notification.getGroupedNotifications' + +function groupedBody(method: string, post: string, postViewType: string) { + return { + cursor: 'next', + groups: [ + { + $type: `${method}#group`, + id: 'like-1', + isRead: false, + indexedAt: '2026-09-01T00:00:00.000Z', + count: 1, + kind: { + $type: `${method}#likeGroup`, + post, + items: [{actor: 'did:plc:alice'}], + }, + }, + ], + relatedViews: [ + { + $type: 'app.bsky.actor.defs#profileViewBasic', + did: 'did:plc:alice', + handle: 'alice.test', + }, + { + $type: postViewType, + uri: post, + cid: CID, + author: {did: 'did:plc:me', handle: 'me.test'}, + record: { + $type: 'app.bsky.feed.post', + text: 'hello', + createdAt: '2026-09-01T00:00:00.000Z', + }, + indexedAt: '2026-09-01T00:00:00.000Z', + }, + ], + } +} function notification(uri: string) { return { @@ -152,6 +194,50 @@ describe('community notification API', () => { expect(fetchHandler).toHaveBeenCalledTimes(1) }) + it('reads grouped notifications on space records in the standard shape', async () => { + const {client, fetchHandler, request} = mockClient() + fetchHandler.mockResolvedValue( + json( + groupedBody( + GET_GROUPED_NOTIFICATIONS_METHOD, + PRIVATE_URI, + 'community.blacksky.feed.defs#spacePostView', + ), + ), + ) + + await expect( + getGroupedNotifications(client, {feed: 'all', limit: 30}), + ).resolves.toEqual( + groupedBody(STANDARD_GROUPED, PRIVATE_URI, 'app.bsky.feed.defs#postView'), + ) + + expect(fetchHandler).toHaveBeenCalledTimes(1) + expect(request(0).method).toBe(GET_GROUPED_NOTIFICATIONS_METHOD) + expect(request(0).query.get('feed')).toBe('all') + expect(request(0).proxy).toBe(HOME_PROXY_HEADER) + }) + + it('falls back to the standard grouped notifications on the home appview', async () => { + const {client, fetchHandler, request} = mockClient() + const body = groupedBody( + STANDARD_GROUPED, + PUBLIC_URI, + 'app.bsky.feed.defs#postView', + ) + fetchHandler + .mockResolvedValueOnce(unsupported()) + .mockResolvedValueOnce(json(body)) + + await expect( + getGroupedNotifications(client, {feed: 'followers', limit: 1}), + ).resolves.toEqual(body) + + expect(request(1).method).toBe(STANDARD_GROUPED) + expect(request(1).query.get('feed')).toBe('followers') + expect(request(1).proxy).toBe(HOME_PROXY_HEADER) + }) + it('returns the community unread count', async () => { const {client, fetchHandler, request} = mockClient() fetchHandler.mockResolvedValue(json({count: 8})) diff --git a/src/lib/api/__tests__/community.test.ts b/src/lib/api/__tests__/community.test.ts index 1eb4e4bc7..605f8cd36 100644 --- a/src/lib/api/__tests__/community.test.ts +++ b/src/lib/api/__tests__/community.test.ts @@ -1,10 +1,14 @@ -import {type Client} from '@atproto/lex' +// The repo-wide stub of this module cannot encode a blob reference. +jest.unmock('multiformats/cid') + +import {Client, jsonToLex} from '@atproto/lex' import { BLUESKY_FALLBACK_PROXY_HEADER, BLUESKY_PROXY_HEADER, HOME_PROXY_HEADER, } from '#/lib/constants' +import {createLexClient} from '#/lib/lexClient' import { communityXrpc, getSpacePostLikes, @@ -21,12 +25,72 @@ describe('communityXrpc', () => { BLUESKY_PROXY_HEADER.set(originalHeader) }) - function mockClient() { + function mockClient(options?: Parameters[1]) { const fetchHandler = jest.fn, [string, RequestInit]>() fetchHandler.mockResolvedValue(new Response('{}')) - return {client: {agent: {fetchHandler}} as unknown as Client, fetchHandler} + return {client: createLexClient({fetchHandler}, options), fetchHandler} + } + + function headersOf( + fetchHandler: jest.Mock, [string, RequestInit]>, + ) { + return new Headers(fetchHandler.mock.calls[0][1].headers) } + it('sends the moderation authorities the client is configured with', async () => { + const {client, fetchHandler} = mockClient() + client.setLabelers(['did:plc:subscribed']) + + await communityXrpc(client, 'community.blacksky.feed.getCommunityTimeline') + + expect(headersOf(fetchHandler).get('atproto-accept-labelers')).toBe( + [ + ...Client.appLabelers.map(did => `${did};redact`), + 'did:plc:subscribed', + ].join(', '), + ) + }) + + it('sends no moderation authorities for a client that takes none', async () => { + const {client, fetchHandler} = mockClient({appLabelers: null}) + + await communityXrpc(client, 'community.blacksky.feed.getCommunityTimeline') + + expect(headersOf(fetchHandler).has('atproto-accept-labelers')).toBe(false) + }) + + it('encodes a blob reference in a body as a link', async () => { + const {client, fetchHandler} = mockClient() + const link = 'bafkreihdwdcefgh4dqkjv67uzcmw7ojee6xedzdetojuzjevtenxquvyku' + const image = jsonToLex({ + $type: 'blob', + ref: {$link: link}, + mimeType: 'image/png', + size: 10, + }) + + await communityXrpc(client, 'community.blacksky.feed.submitPost', { + body: {embed: {images: [{image, alt: ''}]}}, + }) + + const init = fetchHandler.mock.calls[0][1] + expect(JSON.parse(init.body as string)).toEqual({ + embed: { + images: [ + { + image: { + $type: 'blob', + ref: {$link: link}, + mimeType: 'image/png', + size: 10, + }, + alt: '', + }, + ], + }, + }) + }) + it('always targets the home appview, even when the global proxy header is flipped', async () => { BLUESKY_PROXY_HEADER.set(BLUESKY_FALLBACK_PROXY_HEADER) const {client, fetchHandler} = mockClient() diff --git a/src/lib/api/__tests__/space-write.test.ts b/src/lib/api/__tests__/space-write.test.ts index d25af835d..0fcbe3a98 100644 --- a/src/lib/api/__tests__/space-write.test.ts +++ b/src/lib/api/__tests__/space-write.test.ts @@ -1,5 +1,8 @@ -import {type Client} from '@atproto/lex' -import {describe, expect, it} from '@jest/globals' +// The repo-wide stub of this module cannot encode a blob reference. +jest.unmock('multiformats/cid') + +import {type Client, jsonToLex} from '@atproto/lex' +import {describe, expect, it, jest} from '@jest/globals' import { LIKE_COLLECTION, @@ -64,6 +67,25 @@ const bodyOf = (call: Call): Record => JSON.parse(call.body) as Record describe('space writes', () => { + it('encodes a blob reference in a record as a link', async () => { + const {client, calls} = clientWith() + const link = 'bafkreihdwdcefgh4dqkjv67uzcmw7ojee6xedzdetojuzjevtenxquvyku' + const image = jsonToLex({ + $type: 'blob', + ref: {$link: link}, + mimeType: 'image/png', + size: 10, + }) + + await spaceCreateRecord(client, SPACE, POST_COLLECTION, { + $type: POST_COLLECTION, + text: 'hello', + embed: {$type: 'app.bsky.embed.images', images: [{image, alt: ''}]}, + }) + + expect(calls[0].body).toContain(`"ref":{"$link":"${link}"}`) + }) + it('posts to the account’s own pds without a proxy header', async () => { const {client, calls} = clientWith() await spaceCreateRecord(client, SPACE, POST_COLLECTION, { diff --git a/src/lib/api/community-notifications.ts b/src/lib/api/community-notifications.ts index 1af8b5741..7ddff3b8d 100644 --- a/src/lib/api/community-notifications.ts +++ b/src/lib/api/community-notifications.ts @@ -2,11 +2,18 @@ import {type Client, XrpcResponseError} from '@atproto/lex' import {HOME_APPVIEW_PINNED_OPTS} from '#/lib/constants' import {app, community} from '#/lexicons' +import {toPostView} from './space-views' export const LIST_NOTIFICATIONS_METHOD = community.blacksky.notification.listNotifications.$lxm export const GET_UNREAD_COUNT_METHOD = community.blacksky.notification.getUnreadCount.$lxm +export const GET_GROUPED_NOTIFICATIONS_METHOD = + community.blacksky.notification.getGroupedNotifications.$lxm + +const STANDARD_GROUP_PREFIX = `${app.bsky.notification.getGroupedNotifications.$lxm}#` +const COMMUNITY_GROUP_PREFIX = `${GET_GROUPED_NOTIFICATIONS_METHOD}#` +const SPACE_POST_VIEW = 'community.blacksky.feed.defs#spacePostView' /* * An appview that predates these methods answers 501 MethodNotImplemented. The @@ -72,3 +79,50 @@ export async function getUnreadCount( ) } } + +function toStandardGroupType(type: string): string { + return type.replace(COMMUNITY_GROUP_PREFIX, STANDARD_GROUP_PREFIX) +} + +/* + * The community groups are the standard ones under this lexicon's id, and a + * post in a permissioned space arrives as a space post view. Both are renamed + * so the standard hydration reads them. + */ +function toStandardGroupedNotifications( + data: community.blacksky.notification.getGroupedNotifications.$OutputBody, +): app.bsky.notification.getGroupedNotifications.$OutputBody { + return { + ...data, + groups: data.groups.map(group => ({ + ...group, + ...(group.$type ? {$type: toStandardGroupType(group.$type)} : {}), + kind: {...group.kind, $type: toStandardGroupType(group.kind.$type)}, + })), + relatedViews: data.relatedViews?.map(view => + view.$type === SPACE_POST_VIEW ? (toPostView(view) ?? view) : view, + ), + } as unknown as app.bsky.notification.getGroupedNotifications.$OutputBody +} + +export async function getGroupedNotifications( + client: Client, + params: app.bsky.notification.getGroupedNotifications.$Params, +): Promise { + try { + return toStandardGroupedNotifications( + await client.call( + community.blacksky.notification.getGroupedNotifications, + params, + HOME_APPVIEW_PINNED_OPTS, + ), + ) + } catch (e) { + if (!isUnsupportedMethod(e)) throw e + return client.call( + app.bsky.notification.getGroupedNotifications, + params, + HOME_APPVIEW_PINNED_OPTS, + ) + } +} diff --git a/src/lib/api/community.ts b/src/lib/api/community.ts index 4e37cfab6..8c9218073 100644 --- a/src/lib/api/community.ts +++ b/src/lib/api/community.ts @@ -1,4 +1,4 @@ -import {type Client, jsonToLex} from '@atproto/lex' +import {Client, jsonToLex, lexStringify} from '@atproto/lex' import {type AtUriString} from '@atproto/syntax' import {HOME_PROXY_HEADER} from '#/lib/constants' @@ -7,6 +7,22 @@ import {toPostView} from './space-views' export type CommunityXrpcParam = string | number | boolean +/* + * A raw request skips the client's own header construction, so the moderation + * authorities it would have sent are added here in the same form. + */ +function acceptLabelers(client: Client): string | undefined { + const appLabelers = + client.xrpcDefaults.appLabelers === undefined + ? Client.appLabelers + : client.xrpcDefaults.appLabelers + const labelers = [ + ...Array.from(appLabelers ?? [], did => `${did};redact`), + ...client.labelers, + ] + return labelers.length > 0 ? labelers.join(', ') : undefined +} + export async function communityXrpc( client: Client, method: string, @@ -37,13 +53,18 @@ export async function communityXrpc( ? `${opts.serviceDid}#bsky_appview` : HOME_PROXY_HEADER, } + const labelers = acceptLabelers(client) + if (labelers) { + headers['atproto-accept-labelers'] = labelers + } const init: RequestInit = { method: opts?.body ? 'POST' : 'GET', headers, } if (opts?.body) { headers['Content-Type'] = 'application/json' - init.body = JSON.stringify(opts.body) + // Blob references are CID objects, which plain JSON does not encode as links. + init.body = lexStringify(opts.body) } return client.agent.fetchHandler(path, init) } diff --git a/src/lib/api/space-views.ts b/src/lib/api/space-views.ts index 57175a738..8797924f9 100644 --- a/src/lib/api/space-views.ts +++ b/src/lib/api/space-views.ts @@ -1,3 +1,5 @@ +import {isPlainObject} from '@atproto/lex' + import {type app} from '#/lexicons' /** @@ -32,10 +34,6 @@ const TYPE_MAP: Record = { 'app.bsky.unspecced.defs#threadItemBlocked', } -function isPlainObject(value: unknown): value is Record { - return !!value && typeof value === 'object' && !Array.isArray(value) -} - function rename(value: unknown): unknown { if (Array.isArray(value)) return value.map(rename) if (!isPlainObject(value)) return value diff --git a/src/lib/api/space-write.ts b/src/lib/api/space-write.ts index f992da008..a88eae64e 100644 --- a/src/lib/api/space-write.ts +++ b/src/lib/api/space-write.ts @@ -1,5 +1,5 @@ import {TID} from '@atproto/common-web' -import {type Client} from '@atproto/lex' +import {type Client, lexStringify, type LexValue} from '@atproto/lex' import {parseSpaceRecordUri, spaceUriOf} from '#/lib/api/space-uri' @@ -58,7 +58,8 @@ async function spaceXrpc( // Deliberately no `atproto-proxy`: this write belongs to the account's own // PDS, not the appview. headers: {'Content-Type': 'application/json'}, - body: JSON.stringify(body), + // Blob references are CID objects, which plain JSON does not encode as links. + body: lexStringify(body as LexValue), }) } diff --git a/src/state/queries/notifications/grouped/index.ts b/src/state/queries/notifications/grouped/index.ts index e2dd8332d..e16b2d46e 100644 --- a/src/state/queries/notifications/grouped/index.ts +++ b/src/state/queries/notifications/grouped/index.ts @@ -6,6 +6,7 @@ import { useInfiniteQuery, } from '@tanstack/react-query' +import {getGroupedNotifications} from '#/lib/api/community-notifications' import {useModerationOpts} from '#/state/preferences/moderation-opts' import {STALE} from '#/state/queries' import {getNextCursor} from '#/state/queries/notifications/grouped/cursor' @@ -128,10 +129,7 @@ export async function peekGroupedNotifications( feed: GroupedNotificationsFeed, ): Promise { const requestedAt = Date.now() - const res = await client.call(app.bsky.notification.getGroupedNotifications, { - feed, - limit: 1, - }) + const res = await getGroupedNotifications(client, {feed, limit: 1}) return {requestedAt, newestAt: getNewestAt(res.groups)} } @@ -173,14 +171,11 @@ export function useGroupedNotificationsQuery({ queryKey: createGroupedNotificationsQueryKey({feed}), async queryFn({pageParam}): Promise { const requestedAt = Date.now() - const res = await client.call( - app.bsky.notification.getGroupedNotifications, - { - feed, - limit: PAGE_SIZE, - cursor: pageParam, - }, - ) + const res = await getGroupedNotifications(client, { + feed, + limit: PAGE_SIZE, + cursor: pageParam, + }) return {...hydratePage(res, {viewerDid}), requestedAt} }, initialPageParam: undefined as string | undefined, diff --git a/src/state/session/__tests__/clients-test.ts b/src/state/session/__tests__/clients-test.ts index 758da293e..a8e756ac2 100644 --- a/src/state/session/__tests__/clients-test.ts +++ b/src/state/session/__tests__/clients-test.ts @@ -28,6 +28,7 @@ import { getUnauthenticatedThrowingClient, NotAuthenticatedError, routeSessionToPds, + sessionAuthWins, } from '../clients' import {sessionAccountToSessionData} from '../session-data' import { @@ -379,6 +380,47 @@ describe('routeSessionToPds', () => { }) }) +describe('sessionAuthWins', () => { + let fetchMock: MockFetch + + beforeEach(() => { + fetchMock = makeProfileFetch() + }) + + it('sends the session token in place of a caller-supplied one', async () => { + const session = makeSession(fetchMock) + + await sessionAuthWins(session).fetchHandler( + '/xrpc/com.atproto.server.getSession', + { + headers: { + Authorization: 'Bearer service-token', + 'atproto-proxy': 'did:web:feed.example#bsky_fg', + }, + }, + ) + + const headers = headersFor(fetchMock, 'com.atproto.server.getSession') + expect(headers.get('authorization')).toBe('Bearer access-jwt') + expect(headers.get('atproto-proxy')).toBe('did:web:feed.example#bsky_fg') + }) + + it('rejects the same request on the bare session', async () => { + const session = makeSession(fetchMock) + + await expect( + session.fetchHandler('/xrpc/com.atproto.server.getSession', { + headers: {Authorization: 'Bearer service-token'}, + }), + ).rejects.toThrow(TypeError) + expect(fetchMock).not.toHaveBeenCalled() + }) + + it('passes through the session did', () => { + expect(sessionAuthWins(makeSession(fetchMock)).did).toBe(DID) + }) +}) + describe('getUnauthenticatedThrowingClient', () => { it('is a stable singleton with no did', () => { const client = getUnauthenticatedThrowingClient() diff --git a/src/state/session/__tests__/provider-session-events-test.tsx b/src/state/session/__tests__/provider-session-events-test.tsx index e5308287a..cb1fa595f 100644 --- a/src/state/session/__tests__/provider-session-events-test.tsx +++ b/src/state/session/__tests__/provider-session-events-test.tsx @@ -552,4 +552,37 @@ describe('cross-tab sync', () => { expect(mockDisposeBundle).toHaveBeenCalledWith(resumedBundle) expect(mockRebuilds.length).toBe(0) }) + + it('keeps pending work when another tab updates the same OAuth account', async () => { + const account = makeAccount({ + accessJwt: undefined, + refreshJwt: undefined, + isOauthSession: true, + }) + const bundle = makeBundle(account) + const {api} = await renderLoggedIn(account, bundle) + + /* a switch to a second, password account is in flight */ + const other = makeAccount({did: 'did:plc:other'}) + const resumedBundle = makeBundle(other) + let finishResume!: (value: unknown) => void + mockResume.mockReturnValueOnce( + new Promise(resolve => { + finishResume = resolve + }), + ) + const pending = api.resumeSession(other) + + const updated = {...account, emailConfirmed: false} + act(() => { + emitSynced({accounts: [updated, other], currentAccount: updated}) + }) + + await act(async () => { + finishResume({bundle: resumedBundle, account: other}) + await pending + }) + + expect(mockDisposeBundle).not.toHaveBeenCalledWith(resumedBundle) + }) }) diff --git a/src/state/session/clients.ts b/src/state/session/clients.ts index 7764239b2..ec76dd0c6 100644 --- a/src/state/session/clients.ts +++ b/src/state/session/clients.ts @@ -128,6 +128,27 @@ export function routeSessionToPds( } } +/* + * `PasswordSession` throws on a request that already carries an Authorization + * header, where an OAuth session replaces it. Callers that attach their own + * token to a proxied request rely on the replacement. + */ +export function sessionAuthWins(agent: Agent): Agent { + return { + get did() { + return agent.did + }, + fetchHandler(path, init) { + const headers = new Headers(init.headers) + if (!headers.has('authorization')) { + return agent.fetchHandler(path, init) + } + headers.delete('authorization') + return agent.fetchHandler(path, {...init, headers}) + }, + } +} + /** Thrown when a write/auth-only client is used with no active session. */ export class NotAuthenticatedError extends Error { constructor(op = 'this operation') { diff --git a/src/state/session/index.tsx b/src/state/session/index.tsx index df61863d8..4d5a9c795 100644 --- a/src/state/session/index.tsx +++ b/src/state/session/index.tsx @@ -657,10 +657,12 @@ export function Provider({children}: React.PropsWithChildren<{}>) { /* * Cancel pending work when another tab logs out the account this tab * considers current. Do not cancel unrelated work between logged-out tabs. + * An OAuth account persists no tokens, so its flag marks it signed in. */ - const syncedDid = syncedAccount?.refreshJwt - ? syncedAccount.did - : undefined + const syncedDid = + syncedAccount?.refreshJwt || syncedAccount?.isOauthSession + ? syncedAccount.did + : undefined if ( syncedDid === undefined && state.currentBundleState.did !== undefined diff --git a/src/state/session/session-core.ts b/src/state/session/session-core.ts index fd67c2c3a..da83dc5a6 100644 --- a/src/state/session/session-core.ts +++ b/src/state/session/session-core.ts @@ -17,6 +17,7 @@ import { getPublicAppviewClient, getUnauthenticatedThrowingClient, routeSessionToPds, + sessionAuthWins, } from './clients' import {addSessionErrorLog} from './logging' import { @@ -140,10 +141,11 @@ export function buildBundle( * so an invalid value would throw from every client call; discard it here * and let the session route against its own service instead. */ - const agent = + const agent = sessionAuthWins( storedPdsUrl && canParseUrl(storedPdsUrl) ? routeSessionToPds(session, storedPdsUrl) - : session + : session, + ) return { session, appviewClient: buildAppviewClient(agent),