diff --git a/__tests__/lib/feed-manip-community.test.ts b/__tests__/lib/feed-manip-community.test.ts index 8350acef5..a78ca36a3 100644 --- a/__tests__/lib/feed-manip-community.test.ts +++ b/__tests__/lib/feed-manip-community.test.ts @@ -4,7 +4,7 @@ import { type AppBskyFeedPost, } from '@atproto/api' -import {FeedTuner} from '#/lib/api/feed-manip' +import {FeedTuner, FeedViewPostsSlice} from '#/lib/api/feed-manip' // The repo-wide manual mock stubs CID.parse away, which makes every // cid-format validation fail; these tests exercise real record validation. @@ -20,6 +20,8 @@ const VIEWER_DID = 'did:plc:viewer' const MEMBER_DID = 'did:plc:member' const COLLECTION = 'community.blacksky.feed.post' const CID = 'bafyreihhl5mpvjkrhnnagen2fomozzhnhhdq2jr6cego2nzbvmwewv5rd4' +const SPACE_URI = + 'at://did:plc:community/space/community.blacksky.feed/aabbcc/did:plc:member/app.bsky.feed.post/root' function author( did: string, @@ -77,6 +79,37 @@ function followingTuner() { } describe('FeedTuner with merged community posts', () => { + it('keeps a space quote whose embedded record uses a space URI', () => { + const post = communityPost({rkey: 'quote'}) + post.uri = + 'at://did:plc:community/space/community.blacksky.feed/aabbcc/did:plc:member/app.bsky.feed.post/quote' + post.record = { + $type: 'app.bsky.feed.post', + text: 'quoted', + createdAt: '2026-07-17T12:00:00.000Z', + embed: { + $type: 'app.bsky.embed.record', + record: {uri: SPACE_URI, cid: CID}, + }, + } + post.embed = { + $type: 'app.bsky.embed.record#view', + record: { + $type: 'app.bsky.embed.record#viewRecord', + uri: SPACE_URI, + cid: CID, + author: author(MEMBER_DID), + value: {text: 'root', createdAt: '2026-07-17T12:00:00.000Z'}, + indexedAt: '2026-07-17T12:00:00.000Z', + }, + } + + const slice = new FeedViewPostsSlice({post}) + + expect(slice.items).toHaveLength(1) + expect(slice.isQuotePost).toBe(true) + }) + it('keeps a top-level community post', () => { const feed: AppBskyFeedDefs.FeedViewPost[] = [ {post: communityPost({rkey: 'aaa'})}, diff --git a/__tests__/lib/space-feed-routing.test.ts b/__tests__/lib/space-feed-routing.test.ts new file mode 100644 index 000000000..945977790 --- /dev/null +++ b/__tests__/lib/space-feed-routing.test.ts @@ -0,0 +1,155 @@ +// `jsonToLex` walks the body looking for CID links, and the multiformats CID +// helper it uses does not load under jest's module resolution. Nothing here is +// about CID inflation, so it is stubbed to a passthrough. +jest.mock('@atproto/api', () => ({ + ...jest.requireActual('@atproto/api'), + jsonToLex: (value: unknown) => value, +})) + +import {type AtpAgent} from '@atproto/api' + +import {CustomFeedAPI} from '#/lib/api/feed/custom' +import {toPostView, toSpaceFeedPage} from '#/lib/api/space-views' + +const FEED = 'at://did:plc:community/app.bsky.feed.generator/private' +const SPACE = 'at://did:plc:community/space/community.blacksky.feed/private' +const POST = `${SPACE}/did:plc:alice/app.bsky.feed.post/3kaaa` + +const config = { + $type: 'community.blacksky.feed.config', + contentType: 'communityRecord', + visibility: 'gated', + group: 'at://did:plc:community/app.bsky.graph.list/members', + createdAt: '2026-08-18T00:00:00.000Z', + space: SPACE, +} + +type FakeAgent = { + did?: string + fetchHandler: jest.Mock + app: {bsky: {feed: {getFeed: jest.Mock}}} + com: {atproto: {repo: {getRecord: jest.Mock}}} +} + +function agent({did}: {did?: string}): FakeAgent { + const getFeed = jest.fn() + const fetchHandler = jest.fn((path: string) => { + if (path.includes('community.blacksky.feed.getSpaceFeed')) { + return Promise.resolve( + new Response( + JSON.stringify({ + cursor: '2026-08-18T00:00:00.000Z::bafyone', + feed: [ + { + post: { + $type: 'community.blacksky.feed.defs#spacePostView', + uri: POST, + cid: 'bafyone', + author: {did: 'did:plc:alice', handle: 'alice.test'}, + record: {$type: 'app.bsky.feed.post', text: 'hi'}, + indexedAt: '2026-08-18T00:00:00.000Z', + communitySpace: SPACE, + }, + }, + ], + }), + {status: 200, headers: {'content-type': 'application/json'}}, + ), + ) + } + throw new Error(`unexpected request: ${path}`) + }) + return { + did, + fetchHandler, + app: {bsky: {feed: {getFeed}}}, + com: { + atproto: { + repo: { + getRecord: jest.fn(() => Promise.resolve({data: {value: config}})), + }, + }, + }, + } +} + +// The feed APIs take a real `AtpAgent`; only the four members above are +// reachable on this path, so the fake is narrowed rather than filled in. +const asAgent = (a: FakeAgent) => a as unknown as AtpAgent + +describe('space-backed feed routing', () => { + it('reads a space feed through the private endpoint and never the standard one', async () => { + const a = agent({did: 'did:plc:alice'}) + const api = new CustomFeedAPI({agent: asAgent(a), feedParams: {feed: FEED}}) + + const page = await api.fetch({cursor: undefined, limit: 30}) + + expect(a.app.bsky.feed.getFeed).not.toHaveBeenCalled() + expect(page.feed).toHaveLength(1) + // The real space record URI survives: every later interaction (like, + // delete, permalink, thread) targets it. + expect(page.feed[0].post.uri).toBe(POST) + expect(page.feed[0].post.$type).toBe('app.bsky.feed.defs#postView') + }) + + it('peekLatest uses the same endpoint, so polling agrees with pagination', async () => { + const a = agent({did: 'did:plc:alice'}) + const api = new CustomFeedAPI({agent: asAgent(a), feedParams: {feed: FEED}}) + + await api.peekLatest() + + expect(a.app.bsky.feed.getFeed).not.toHaveBeenCalled() + expect(a.fetchHandler).toHaveBeenCalled() + }) + + it('refuses logged out rather than falling back to the public appview', async () => { + const a = agent({}) + const api = new CustomFeedAPI({agent: asAgent(a), feedParams: {feed: FEED}}) + + await expect(api.fetch({cursor: undefined, limit: 30})).rejects.toThrow( + 'FeedSignedInOnly', + ) + await expect(api.peekLatest()).rejects.toThrow('FeedSignedInOnly') + expect(a.fetchHandler).not.toHaveBeenCalled() + }) +}) + +describe('private view type mapping', () => { + it('renames the whole tree, quote embeds included', () => { + const page = toSpaceFeedPage({ + feed: [ + { + post: { + $type: 'community.blacksky.feed.defs#spacePostView', + uri: POST, + cid: 'bafyone', + author: {did: 'did:plc:alice'}, + record: {}, + indexedAt: '2026-08-18T00:00:00.000Z', + embed: { + $type: 'community.blacksky.feed.defs#spaceRecordView', + record: { + $type: 'community.blacksky.feed.defs#spaceViewRecord', + uri: POST, + }, + }, + }, + }, + ], + }) + const embed = page.feed[0].post.embed as unknown as Record< + string, + Record + > + expect(embed.$type).toBe('app.bsky.embed.record#view') + expect(embed.record.$type).toBe('app.bsky.embed.record#viewRecord') + // A space URI is carried through untouched; nothing parses it. + expect(embed.record.uri).toBe(POST) + }) + + it('drops a structurally invalid row instead of the whole page', () => { + const page = toSpaceFeedPage({feed: [{post: {}}, {nope: true}]}) + expect(page.feed).toEqual([]) + expect(toPostView({uri: 42})).toBeUndefined() + }) +}) diff --git a/app.config.js b/app.config.js index fd86d4e7f..9613f922a 100644 --- a/app.config.js +++ b/app.config.js @@ -223,6 +223,7 @@ module.exports = function (_config) { ], }, web: { + bundler: 'metro', favicon: './assets/favicon.png', }, updates: { diff --git a/src/lib/api/__tests__/community-feed.test.ts b/src/lib/api/__tests__/community-feed.test.ts index 0b70806d9..55380c4bb 100644 --- a/src/lib/api/__tests__/community-feed.test.ts +++ b/src/lib/api/__tests__/community-feed.test.ts @@ -1,10 +1,11 @@ -import {type AtpAgent} from '@atproto/api' +import {type AtpAgent, XRPCError} from '@atproto/api' import { ADMIT_FEED_POST, admitFeedPost, CHECK_FEED_PERMISSIONS, fetchCommunityFeedConfig, + fetchCommunityFeedConfigStrict, fetchCommunityFeedTarget, fetchFeedPermissions, fetchFeedServiceDid, @@ -70,6 +71,20 @@ describe('community feed API', () => { }) }) + it('distinguishes an absent config from a failed config read', async () => { + const {agent, getRecord} = mockAgent() + getRecord.mockRejectedValueOnce(new XRPCError(400, 'RecordNotFound')) + + await expect( + fetchCommunityFeedConfigStrict(agent, feed), + ).resolves.toBeNull() + + getRecord.mockRejectedValueOnce(new XRPCError(503, 'UpstreamFailure')) + await expect(fetchCommunityFeedConfigStrict(agent, feed)).rejects.toThrow( + 'UpstreamFailure', + ) + }) + it('checks self-scoped permissions with exact service auth and filters unknown values', async () => { const {agent, fetchHandler} = mockAgent() fetchHandler.mockResolvedValue( diff --git a/src/lib/api/__tests__/post-routing.test.ts b/src/lib/api/__tests__/post-routing.test.ts index 3dcde8429..a807874e3 100644 --- a/src/lib/api/__tests__/post-routing.test.ts +++ b/src/lib/api/__tests__/post-routing.test.ts @@ -113,30 +113,39 @@ describe('quoting a space post from outside the space', () => { it.each([ ['a pasted permalink', permalink], ['an at:// space record uri', SPACE_POST], - ])('refuses %s rather than writing it to the public repo', async (_n, uri) => { - const {agent, applyWrites, fetchHandler} = mockAgent() - - await expect( - post(agent, queryClient, {thread: threadQuoting(uri)}), - ).rejects.toThrow(/private post/) - - expect(applyWrites).not.toHaveBeenCalled() - expect(fetchHandler).not.toHaveBeenCalled() - expect(postToSpace).not.toHaveBeenCalled() - }) + ])( + 'refuses %s rather than writing it to the public repo', + async (_n, uri) => { + const {agent, applyWrites, fetchHandler} = mockAgent() + + await expect( + post(agent, queryClient, {thread: threadQuoting(uri)}), + ).rejects.toThrow(/private post/) + + expect(applyWrites).not.toHaveBeenCalled() + expect(fetchHandler).not.toHaveBeenCalled() + expect(postToSpace).not.toHaveBeenCalled() + }, + ) it.each([ ['opened from the space post', {communitySpaceUri: SPACE}], ['composing into the space-backed feed', {}], - ])('allows the quote when the post goes into that space (%s)', async (_n, extra) => { - const {agent} = mockAgent() - - await post(agent, queryClient, { - thread: {...(threadQuoting(permalink, SPACE) as object), ...extra} as never, - }) - - expect(postToSpace).toHaveBeenCalled() - }) + ])( + 'allows the quote when the post goes into that space (%s)', + async (_n, extra) => { + const {agent} = mockAgent() + + await post(agent, queryClient, { + thread: { + ...(threadQuoting(permalink, SPACE) as object), + ...extra, + } as never, + }) + + expect(postToSpace).toHaveBeenCalled() + }, + ) }) describe('quotedSpace', () => { diff --git a/src/lib/api/__tests__/space-permalink.test.ts b/src/lib/api/__tests__/space-permalink.test.ts index 4db8a7d88..dfa47cb1d 100644 --- a/src/lib/api/__tests__/space-permalink.test.ts +++ b/src/lib/api/__tests__/space-permalink.test.ts @@ -59,13 +59,19 @@ describe('recognising a space link before it is expanded', () => { const encoded = encodeURIComponent(SPACE) it.each([ - ['a full url', `https://blacksky.community/profile/did:plc:alice/post/3kabc?space=${encoded}`], + [ + 'a full url', + `https://blacksky.community/profile/did:plc:alice/post/3kabc?space=${encoded}`, + ], ['a relative path', `/profile/did:plc:alice/post/3kabc?space=${encoded}`], [ 'a suffix route', `https://bsky.app/profile/did:plc:alice/post/3kabc/liked-by?space=${encoded}`, ], - ['an unencoded space param', `/profile/did:plc:alice/post/3kabc?space=${SPACE}`], + [ + 'an unencoded space param', + `/profile/did:plc:alice/post/3kabc?space=${SPACE}`, + ], ])('spots %s', (_name, url) => { expect(isSpacePostUrl(url)).toBe(true) }) @@ -76,7 +82,10 @@ describe('recognising a space link before it is expanded', () => { 'a community stub url', '/profile/did:plc:alice/post/3kabc?collection=community.blacksky.feed.post', ], - ['a space param that is not a space uri', '/profile/did:plc:alice/post/3kabc?space=nonsense'], + [ + 'a space param that is not a space uri', + '/profile/did:plc:alice/post/3kabc?space=nonsense', + ], ['nothing', undefined], ])('ignores %s', (_name, url) => { expect(isSpacePostUrl(url)).toBe(false) diff --git a/src/lib/api/__tests__/space-post.test.ts b/src/lib/api/__tests__/space-post.test.ts index d8fa6d045..2e1e79399 100644 --- a/src/lib/api/__tests__/space-post.test.ts +++ b/src/lib/api/__tests__/space-post.test.ts @@ -11,15 +11,17 @@ jest.mock('../index', () => ({ ), resolveEmbed: jest.fn(), resolveReply: jest.fn(), - resolveRT: jest.fn(async (_agent, richtext) => richtext), + resolveRT: jest.fn((_agent, richtext) => Promise.resolve(richtext)), })) jest.mock('../space-write', () => ({ POST_COLLECTION: 'app.bsky.feed.post', - spaceCreateRecord: jest.fn(async () => ({ - uri: 'at://space/post', - cid: 'bafyspace', - })), + spaceCreateRecord: jest.fn(() => + Promise.resolve({ + uri: 'at://space/post', + cid: 'bafyspace', + }), + ), })) const SPACE = 'at://did:plc:space/space/community.blacksky.feed/private' diff --git a/src/lib/api/community-feed.ts b/src/lib/api/community-feed.ts index c58032730..374a9c55b 100644 --- a/src/lib/api/community-feed.ts +++ b/src/lib/api/community-feed.ts @@ -1,4 +1,4 @@ -import {type AtpAgent, AtUri} from '@atproto/api' +import {type AtpAgent, AtUri, XRPCError} from '@atproto/api' import {getServiceAuthToken} from '#/lib/api/service-auth' import {isSpaceUri} from '#/lib/api/space-uri' @@ -91,16 +91,40 @@ export async function fetchCommunityFeedConfig( feed: string, ): Promise { try { - const uri = new AtUri(feed) - if (!uri.rkey) return null + return await fetchCommunityFeedConfigStrict(agent, feed) + } catch { + return null + } +} + +/** + * Distinguishes "no config record exists" (null) from a failed read (throws). + * The feed dispatch must not treat a transient config-read failure as "not + * space-backed" and route a private feed down the standard path. + */ +export async function fetchCommunityFeedConfigStrict( + agent: AtpAgent, + feed: string, +): Promise { + let uri: AtUri + try { + uri = new AtUri(feed) + } catch { + return null + } + if (!uri.rkey) return null + try { const {data} = await agent.com.atproto.repo.getRecord({ repo: uri.hostname, collection: COMMUNITY_FEED_CONFIG_COLLECTION, rkey: uri.rkey, }) return parseCommunityFeedConfig(data.value) - } catch { - return null + } catch (e) { + if (e instanceof XRPCError && e.error === 'RecordNotFound') { + return null + } + throw e } } diff --git a/src/lib/api/community-post.ts b/src/lib/api/community-post.ts index 1963a466d..4eb41154a 100644 --- a/src/lib/api/community-post.ts +++ b/src/lib/api/community-post.ts @@ -1,7 +1,14 @@ -import {type AppBskyFeedDefs, type BskyAgent, jsonToLex} from '@atproto/api' +import { + type AppBskyFeedDefs, + AppBskyFeedPost, + type BskyAgent, + jsonToLex, +} from '@atproto/api' import {communityXrpc} from '#/lib/api/community' import {isSpaceRecordUri, parseSpaceUri} from '#/lib/api/space-uri' +import {toPostView} from '#/lib/api/space-views' +import * as bsky from '#/types/bsky' export const GET_COMMUNITY_POST = 'community.blacksky.feed.getCommunityPost' @@ -18,6 +25,27 @@ export function isCommunityPostUri(uri: string | undefined): boolean { ) } +/** + * Space records use the same post record shape as public posts, but their + * reply and quote refs are permissioned-space URIs rather than AT-URIs. The + * public lexicon validator therefore cannot validate those otherwise valid + * records. Space responses are already validated by the AppView endpoint; + * retain the fields the renderer requires here while keeping strict lexicon + * validation for public posts. + */ +export function isRenderablePostRecord( + post: AppBskyFeedDefs.PostView, +): post is AppBskyFeedDefs.PostView & {record: AppBskyFeedPost.Record} { + if (!AppBskyFeedPost.isRecord(post.record)) return false + if (!isSpaceRecordUri(post.uri)) { + return bsky.validate(post.record, AppBskyFeedPost.validateRecord) + } + return ( + typeof post.record.text === 'string' && + typeof post.record.createdAt === 'string' + ) +} + export type CommunityPostView = AppBskyFeedDefs.PostView & { communitySpace?: string } @@ -57,7 +85,8 @@ export async function fetchCommunityPostView( } throw new Error(body.message || body.error || `HTTP ${res.status}`) } - const data = jsonToLex(await res.json()) as {post?: AppBskyFeedDefs.PostView} - if (!data.post) throw new Error('Community post not found') - return data.post + const data = jsonToLex(await res.json()) as {post?: unknown} + const post = toPostView(data.post) + if (!post) throw new Error('Community post not found') + return post } diff --git a/src/lib/api/community-thread.ts b/src/lib/api/community-thread.ts index 09ad2766f..f3c6743a5 100644 --- a/src/lib/api/community-thread.ts +++ b/src/lib/api/community-thread.ts @@ -1,6 +1,7 @@ import {type BskyAgent} from '@atproto/api' import {communityXrpc} from '#/lib/api/community' +import {toSpaceThreadBody} from '#/lib/api/space-views' export const GET_COMMUNITY_THREAD = 'community.blacksky.feed.getCommunityThread' @@ -42,7 +43,11 @@ export async function fetchCommunityThread( } throw new Error(body.message || body.error || `HTTP ${res.status}`) } - const data = (await res.json()) as Partial + // The wire types are community.blacksky.feed.defs; the thread renderer + // consumes the standard threadItem shapes, which are structurally identical. + const data = toSpaceThreadBody( + await res.json(), + ) as Partial return { thread: data.thread ?? [], hasOtherReplies: !!data.hasOtherReplies, diff --git a/src/lib/api/feed-manip.ts b/src/lib/api/feed-manip.ts index 335bf28c8..501e12573 100644 --- a/src/lib/api/feed-manip.ts +++ b/src/lib/api/feed-manip.ts @@ -6,7 +6,7 @@ import { AppBskyFeedPost, } from '@atproto/api' -import * as bsky from '#/types/bsky' +import {isRenderablePostRecord} from '#/lib/api/community-post' import {isPostInLanguage} from '../../locale/helpers' import {FALLBACK_MARKER_POST} from './feed/home' import {type ReasonFeedSource} from './feed/types' @@ -68,10 +68,7 @@ export class FeedViewPostsSlice { this.isFallbackMarker = true return } - if ( - !AppBskyFeedPost.isRecord(post.record) || - !bsky.validate(post.record, AppBskyFeedPost.validateRecord) - ) { + if (!isRenderablePostRecord(post)) { return } const parent = reply?.parent @@ -101,8 +98,7 @@ export class FeedViewPostsSlice { } if ( !AppBskyFeedDefs.isPostView(parent) || - !AppBskyFeedPost.isRecord(parent.record) || - !bsky.validate(parent.record, AppBskyFeedPost.validateRecord) + !isRenderablePostRecord(parent) ) { this.isOrphan = true return @@ -141,11 +137,7 @@ export class FeedViewPostsSlice { // Keep going, it might still have a root, and we need this for thread // de-deduping } - if ( - !AppBskyFeedDefs.isPostView(root) || - !AppBskyFeedPost.isRecord(root.record) || - !bsky.validate(root.record, AppBskyFeedPost.validateRecord) - ) { + if (!AppBskyFeedDefs.isPostView(root) || !isRenderablePostRecord(root)) { this.isOrphan = true return } diff --git a/src/lib/api/feed/custom.ts b/src/lib/api/feed/custom.ts index 0284f7503..00065bc6f 100644 --- a/src/lib/api/feed/custom.ts +++ b/src/lib/api/feed/custom.ts @@ -7,10 +7,12 @@ import { import { type CommunityFeedConfig, - fetchCommunityFeedConfig, + fetchCommunityFeedConfigStrict, fetchFeedServiceDid, + isSpaceBackedFeed, } from '#/lib/api/community-feed' import {getServiceAuthToken} from '#/lib/api/service-auth' +import {fetchSpaceFeed, signInRequiredError} from '#/lib/api/space-feed' import { getAppLanguageAsContentLanguage, getContentLanguages, @@ -41,10 +43,15 @@ export class CustomFeedAPI implements FeedAPI { this.agent = agent this.params = feedParams this.userInterests = userInterests - this.communityConfig = fetchCommunityFeedConfig(agent, feedParams.feed) - this.feedServiceDid = this.communityConfig.then(config => - config ? fetchFeedServiceDid(agent, feedParams.feed) : null, + this.communityConfig = fetchCommunityFeedConfigStrict( + agent, + feedParams.feed, ) + this.feedServiceDid = this.communityConfig + .then(config => + config ? fetchFeedServiceDid(agent, feedParams.feed) : null, + ) + .catch(() => null) } async communityAuthHeaders(): Promise> { @@ -62,7 +69,24 @@ export class CustomFeedAPI implements FeedAPI { return {Authorization: `Bearer ${token}`} } + /** + * A space-backed feed never reaches the standard route, in either method. + * `app.bsky.feed.getFeed` now refuses it outright, so a poller that skipped + * this branch would error on every tick, and the logged-out fallback below + * would ask the public appview for private content. + */ + private async spaceFeed(): Promise { + const config = await this.communityConfig + return isSpaceBackedFeed(config) ? this.params.feed : null + } + async peekLatest(): Promise { + const spaceFeed = await this.spaceFeed() + if (spaceFeed) { + if (!this.agent.did) throw signInRequiredError() + const page = await fetchSpaceFeed(this.agent, spaceFeed, {limit: 1}) + return page.feed[0] + } const contentLangs = getContentLanguages().join(',') const communityAuthHeaders = this.agent.did ? await this.communityAuthHeaders() @@ -90,6 +114,16 @@ export class CustomFeedAPI implements FeedAPI { cursor: string | undefined limit: number }): Promise { + const spaceFeed = await this.spaceFeed() + if (spaceFeed) { + if (!this.agent.did) throw signInRequiredError() + const page = await fetchSpaceFeed(this.agent, spaceFeed, {cursor, limit}) + return { + cursor: page.feed.length ? page.cursor : undefined, + feed: page.feed, + } + } + const contentLangs = getContentLanguages().join(',') const agent = this.agent const isBlueskyOwned = isBlueskyOwnedFeed(this.params.feed) diff --git a/src/lib/api/space-feed.ts b/src/lib/api/space-feed.ts new file mode 100644 index 000000000..99d27338d --- /dev/null +++ b/src/lib/api/space-feed.ts @@ -0,0 +1,45 @@ +import {type BskyAgent, jsonToLex} from '@atproto/api' + +import {communityXrpc} from '#/lib/api/community' +import {type SpaceFeedPage, toSpaceFeedPage} from '#/lib/api/space-views' + +export const GET_SPACE_FEED = 'community.blacksky.feed.getSpaceFeed' + +/** + * Thrown when a space-backed feed is opened without a session. The message is + * the `KnownError.FeedSignedInOnly` token so `detectKnownError` renders the + * sign-in-required state; the alternative — falling through to the public + * `api.bsky.app` fetch the standard custom-feed path uses when logged out — + * would ask a public appview for private content and leave the feed spinning. + */ +export const signInRequiredError = () => new Error('FeedSignedInOnly') + +/** + * The private read for a space-backed feed. + * + * `feed` is still the ordinary public `app.bsky.feed.generator` at-uri: the + * generator record remains the feed's identity, so no saved-feed preference + * needs migrating. Only the query chosen for that URI changes. The record URIs + * inside the response are space URIs and are never parsed here. + */ +export async function fetchSpaceFeed( + agent: BskyAgent, + feed: string, + {cursor, limit}: {cursor?: string; limit?: number} = {}, +): Promise { + const params: Record = {feed} + if (cursor) params.cursor = cursor + if (limit) params.limit = String(limit) + + const res = await communityXrpc(agent, GET_SPACE_FEED, {params}) + if (!res.ok) { + const body = (await res.json().catch(() => ({}))) as { + error?: string + message?: string + } + // Surfaced verbatim so an access refusal stays an access refusal: an empty + // page here would report "no posts" for "no access". + throw new Error(body.message || body.error || `HTTP ${res.status}`) + } + return toSpaceFeedPage(jsonToLex(await res.json())) +} diff --git a/src/lib/api/space-views.ts b/src/lib/api/space-views.ts new file mode 100644 index 000000000..0a27dc4ca --- /dev/null +++ b/src/lib/api/space-views.ts @@ -0,0 +1,93 @@ +import {type AppBskyFeedDefs} from '@atproto/api' + +/** + * The private read contract's wire types, mapped back onto the shapes the feed + * UI already renders. + * + * A permissioned-space record URI is not an at-uri, so the appview cannot + * return one inside `app.bsky.feed.defs#postView`, whose `uri` is declared + * `format: at-uri`. Its private endpoints therefore answer in + * `community.blacksky.feed.defs`, which is structurally the same but declares + * every URI-bearing field a plain string. + * + * These are the same objects under different `$type`s, so the mapping is a + * rename: the alternative is a parallel renderer for private posts, which + * would drift from the public one. Nothing here parses a URI — the whole point + * of the custom types is that these URIs must never reach `AtUri`. + */ + +const DEFS = 'community.blacksky.feed.defs' + +const TYPE_MAP: Record = { + [`${DEFS}#spacePostView`]: 'app.bsky.feed.defs#postView', + [`${DEFS}#spaceRecordView`]: 'app.bsky.embed.record#view', + [`${DEFS}#spaceViewRecord`]: 'app.bsky.embed.record#viewRecord', + [`${DEFS}#spaceViewNotFound`]: 'app.bsky.embed.record#viewNotFound', + [`${DEFS}#spaceViewBlocked`]: 'app.bsky.embed.record#viewBlocked', + [`${DEFS}#spaceRecordWithMediaView`]: 'app.bsky.embed.recordWithMedia#view', + [`${DEFS}#spaceThreadItemPost`]: 'app.bsky.unspecced.defs#threadItemPost', + [`${DEFS}#spaceThreadItemNotFound`]: + 'app.bsky.unspecced.defs#threadItemNotFound', + [`${DEFS}#spaceThreadItemBlocked`]: + '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 + const out: Record = {} + for (const [key, entry] of Object.entries(value)) { + out[key] = + key === '$type' && typeof entry === 'string' + ? (TYPE_MAP[entry] ?? entry) + : rename(entry) + } + return out +} + +/** + * A single item of a private feed page. Returns undefined when the item is not + * structurally a feed item, so one malformed row cannot take a page down. + */ +export function toFeedViewPost( + item: unknown, +): AppBskyFeedDefs.FeedViewPost | undefined { + if (!isPlainObject(item)) return undefined + const post = item.post + if (!isPlainObject(post) || typeof post.uri !== 'string') return undefined + return rename(item) as AppBskyFeedDefs.FeedViewPost +} + +/** A private post view, from `getCommunityPost` or a private feed row. */ +export function toPostView( + post: unknown, +): AppBskyFeedDefs.PostView | undefined { + if (!isPlainObject(post) || typeof post.uri !== 'string') return undefined + return rename(post) as AppBskyFeedDefs.PostView +} + +export type SpaceFeedPage = { + cursor?: string + feed: AppBskyFeedDefs.FeedViewPost[] +} + +/** The whole `getSpaceFeed` / community-feed body. */ +export function toSpaceFeedPage(body: unknown): SpaceFeedPage { + const source = isPlainObject(body) ? body : {} + const feed = Array.isArray(source.feed) ? source.feed : [] + return { + cursor: typeof source.cursor === 'string' ? source.cursor : undefined, + feed: feed + .map(toFeedViewPost) + .filter((item): item is AppBskyFeedDefs.FeedViewPost => !!item), + } +} + +/** The `thread`/`hasOtherReplies` body of a private thread read. */ +export function toSpaceThreadBody(body: unknown): unknown { + return rename(body) +} diff --git a/src/lib/api/space-write.ts b/src/lib/api/space-write.ts index 5d870d7ed..6e0113ece 100644 --- a/src/lib/api/space-write.ts +++ b/src/lib/api/space-write.ts @@ -5,12 +5,12 @@ import {parseSpaceRecordUri, spaceUriOf} from '#/lib/api/space-uri' /** * Writes into a permissioned space. * - * A space record goes to the account's **own PDS**, which routes - * `com.atproto.space.*` to the space host. That means **no `atproto-proxy` - * header**: proxying would send the write to the appview, which is not where - * this content lives. It also means the request is DPoP-signed by the agent - * exactly like any other PDS write — the space host verifies that token - * itself. + * A space record goes to the account's **own PDS**. The local stack does not + * implement the 0016 PDS methods yet, so development may point these requests + * at its same-origin edge instead. That means **no `atproto-proxy` header**: + * proxying would send the write to the appview, which is not where this + * content lives. The request remains DPoP-signed by the agent, and the space + * host verifies that token itself. * * Records are sent as raw JSON rather than through typed builders. A like or a * reply inside a space refers to other space records, whose URIs are not valid @@ -24,6 +24,11 @@ export const SPACE_DELETE_RECORD = 'com.atproto.space.deleteRecord' export const POST_COLLECTION = 'app.bsky.feed.post' export const LIKE_COLLECTION = 'app.bsky.feed.like' +const LOCAL_SPACE_XRPC_ORIGIN = + __DEV__ && + process.env.NODE_ENV !== 'test' && + process.env.EXPO_PUBLIC_SPACE_XRPC_ORIGIN + export type SpaceWriteResult = { uri: string cid: string @@ -42,7 +47,11 @@ async function spaceXrpc( method: string, body: unknown, ): Promise { - return agent.fetchHandler(`/xrpc/${method}`, { + const path = `/xrpc/${method}` + const url = LOCAL_SPACE_XRPC_ORIGIN + ? `${LOCAL_SPACE_XRPC_ORIGIN}${path}` + : path + return agent.fetchHandler(url, { method: 'POST', // Deliberately no `atproto-proxy`: this write belongs to the account's own // PDS, not the appview. diff --git a/src/lib/constants.ts b/src/lib/constants.ts index ea07aad80..be4390a2f 100644 --- a/src/lib/constants.ts +++ b/src/lib/constants.ts @@ -9,7 +9,9 @@ export const LOCAL_DEV_SERVICE = export const STAGING_SERVICE = 'https://staging.bsky.dev' export const BSKY_SERVICE = 'https://blacksky.app' export const BSKY_SERVICE_DID = 'did:web:bsky.social' -export const PUBLIC_BSKY_SERVICE = 'https://api.blacksky.community' +export const PUBLIC_BSKY_SERVICE = + (__DEV__ && process.env.EXPO_PUBLIC_APPVIEW_URL) || + 'https://api.blacksky.community' export const DEFAULT_SERVICE = BSKY_SERVICE // Handle suffixes that identify a Latinsky-community account living on the shared diff --git a/src/state/queries/community-feed.ts b/src/state/queries/community-feed.ts index 1753c6180..e518019e0 100644 --- a/src/state/queries/community-feed.ts +++ b/src/state/queries/community-feed.ts @@ -18,13 +18,15 @@ import { import {communityXrpc} from '#/lib/api/community' import {FeedTuner} from '#/lib/api/feed-manip' +import {spaceRecordAuthor} from '#/lib/api/space-uri' +import {toPostView, toSpaceFeedPage} from '#/lib/api/space-views' import {useModerationOpts} from '#/state/preferences/moderation-opts' import {STALE} from '#/state/queries' import {usePreferencesQuery} from '#/state/queries/preferences' import { - didOrHandleUriMatches, embedViewRecordToPostView, getEmbeddedPost, + makeUriMatcher, } from '#/state/queries/util' import {useAgent} from '#/state/session' @@ -79,7 +81,7 @@ export function useCommunityFeedQuery(actor: string | undefined) { if (!res.ok) { throw new Error(`getCommunityFeed failed: ${res.status}`) } - return jsonToLex(await res.json()) as CommunityFeedPage + return toSpaceFeedPage(jsonToLex(await res.json())) }, initialPageParam: undefined, getNextPageParam: lastPage => lastPage.cursor, @@ -116,7 +118,7 @@ export function useCommunityTimelineQuery(enabled: boolean) { if (!res.ok) { throw new Error(`getCommunityTimeline failed: ${res.status}`) } - return jsonToLex(await res.json()) as CommunityFeedPage + return toSpaceFeedPage(jsonToLex(await res.json())) }, initialPageParam: undefined, getNextPageParam: lastPage => lastPage.cursor, @@ -144,8 +146,8 @@ export async function fetchCommunityTimelineHead( if (!res.ok) { throw new Error(`getCommunityTimeline failed: ${res.status}`) } - const page = jsonToLex(await res.json()) as CommunityFeedPage - return page.feed?.find(surfacesInCommunityFeed) + const page = toSpaceFeedPage(jsonToLex(await res.json())) + return page.feed.find(surfacesInCommunityFeed) } // A reply only resurfaces its thread when the root author is @@ -171,7 +173,11 @@ export function surfacesInCommunityFeed( if (!item.reason && !AppBskyFeedDefs.isPostView(item.reply?.parent)) { return false } - return new AtUri(reply.root.uri).host === item.post.author.did + // A space record URI names its author in its own segment; `AtUri` would + // report the space authority as the host and never match. + const rootAuthor = + spaceRecordAuthor(reply.root.uri) ?? new AtUri(reply.root.uri).host + return rootAuthor === item.post.author.did } const COMMUNITY_POST_RQKEY_ROOT = 'community-post' @@ -193,10 +199,10 @@ export function useCommunityPostQuery(uri: string | undefined) { if (!res.ok) { throw new Error(`getCommunityPost failed: ${res.status}`) } - const data = jsonToLex(await res.json()) as { - post: AppBskyFeedDefs.PostView - } - return data.post + const data = jsonToLex(await res.json()) as {post?: unknown} + const post = toPostView(data.post) + if (!post) throw new Error('Community post not found') + return post }, enabled: !!uri, }) @@ -321,7 +327,7 @@ export function* findAllPostsInQueryData( queryClient: QueryClient, uri: string, ): Generator { - const atUri = new AtUri(uri) + const matches = makeUriMatcher(uri) // Search both actor feeds and timeline const queryDatas = [ @@ -345,25 +351,25 @@ export function* findAllPostsInQueryData( if (!item?.post) { continue } - if (didOrHandleUriMatches(atUri, item.post)) { + if (matches(item.post)) { yield item.post } // Check for quoted posts in embeds const quotedPost = getEmbeddedPost(item.post.embed) - if (quotedPost && didOrHandleUriMatches(atUri, quotedPost)) { + if (quotedPost && matches(quotedPost)) { yield embedViewRecordToPostView(quotedPost) } // Reply-context rows render in slices too; without these, likes on // a parent/root row never reach the shadow cache. if (AppBskyFeedDefs.isPostView(item.reply?.parent)) { - if (didOrHandleUriMatches(atUri, item.reply.parent)) { + if (matches(item.reply.parent)) { yield item.reply.parent } } if (AppBskyFeedDefs.isPostView(item.reply?.root)) { - if (didOrHandleUriMatches(atUri, item.reply.root)) { + if (matches(item.reply.root)) { yield item.reply.root } } diff --git a/src/state/queries/notifications/util.ts b/src/state/queries/notifications/util.ts index e9264d9ff..8215d6756 100644 --- a/src/state/queries/notifications/util.ts +++ b/src/state/queries/notifications/util.ts @@ -16,6 +16,7 @@ import {type QueryClient} from '@tanstack/react-query' import chunk from 'lodash.chunk' import {communityXrpc} from '#/lib/api/community' +import {toPostView} from '#/lib/api/space-views' import {HOME_APPVIEW_PINNED_OPTS} from '#/lib/constants' import {labelIsHideableOffense} from '#/lib/moderation' import * as bsky from '#/types/bsky' @@ -253,10 +254,8 @@ async function fetchSubjects( }) .then(async res => { if (!res.ok) return undefined - const data = jsonToLex(await res.json()) as { - post?: AppBskyFeedDefs.PostView - } - return data.post + const data = jsonToLex(await res.json()) as {post?: unknown} + return toPostView(data.post) }) .catch(() => undefined), ), diff --git a/src/state/queries/post-feed.ts b/src/state/queries/post-feed.ts index b0c226b23..f7163ea76 100644 --- a/src/state/queries/post-feed.ts +++ b/src/state/queries/post-feed.ts @@ -5,7 +5,6 @@ import { AppBskyFeedDefs, type AppBskyFeedPost, type AtpAgent, - AtUri, moderatePost, type ModerationDecision, type ModerationPrefs, @@ -40,9 +39,9 @@ import {useFeedTuners} from '../preferences/feed-tuners' import {useModerationOpts} from '../preferences/moderation-opts' import {usePreferencesQuery} from './preferences' import { - didOrHandleUriMatches, embedViewRecordToPostView, getEmbeddedPost, + makeUriMatcher, } from './util' type ActorDid = string @@ -500,7 +499,7 @@ export function* findAllPostsInQueryData( queryClient: QueryClient, uri: string, ): Generator { - const atUri = new AtUri(uri) + const matches = makeUriMatcher(uri) const queryDatas = queryClient.getQueriesData< InfiniteData @@ -513,36 +512,33 @@ export function* findAllPostsInQueryData( } for (const page of queryData?.pages) { for (const item of page.feed) { - if (didOrHandleUriMatches(atUri, item.post)) { + if (matches(item.post)) { yield item.post } const quotedPost = getEmbeddedPost(item.post.embed) - if (quotedPost && didOrHandleUriMatches(atUri, quotedPost)) { + if (quotedPost && matches(quotedPost)) { yield embedViewRecordToPostView(quotedPost) } if (AppBskyFeedDefs.isPostView(item.reply?.parent)) { - if (didOrHandleUriMatches(atUri, item.reply.parent)) { + if (matches(item.reply.parent)) { yield item.reply.parent } const parentQuotedPost = getEmbeddedPost(item.reply.parent.embed) - if ( - parentQuotedPost && - didOrHandleUriMatches(atUri, parentQuotedPost) - ) { + if (parentQuotedPost && matches(parentQuotedPost)) { yield embedViewRecordToPostView(parentQuotedPost) } } if (AppBskyFeedDefs.isPostView(item.reply?.root)) { - if (didOrHandleUriMatches(atUri, item.reply.root)) { + if (matches(item.reply.root)) { yield item.reply.root } const rootQuotedPost = getEmbeddedPost(item.reply.root.embed) - if (rootQuotedPost && didOrHandleUriMatches(atUri, rootQuotedPost)) { + if (rootQuotedPost && matches(rootQuotedPost)) { yield embedViewRecordToPostView(rootQuotedPost) } } diff --git a/src/state/queries/util.ts b/src/state/queries/util.ts index 7ea54745c..90c0520d1 100644 --- a/src/state/queries/util.ts +++ b/src/state/queries/util.ts @@ -4,7 +4,7 @@ import { AppBskyEmbedRecordWithMedia, type AppBskyFeedDefs, AppBskyFeedPost, - type AtUri, + AtUri, } from '@atproto/api' import { type InfiniteData, @@ -12,6 +12,7 @@ import { type QueryKey, } from '@tanstack/react-query' +import {isSpaceRecordUri} from '#/lib/api/space-uri' import * as bsky from '#/types/bsky' export type StructuredQueryKey> = readonly [ @@ -102,6 +103,27 @@ export function didOrHandleUriMatches( return atUri.host === record.author.handle && record.uri.endsWith(atUri.rkey) } +/** + * A predicate matching cached posts against a target URI, for shadow-cache + * updates (like, delete, ...). + * + * A permissioned-space record URI is not an at-uri: `AtUri` misparses it, so + * its `host` becomes the space authority and its `rkey` the space type. The + * handle branch of `didOrHandleUriMatches` would then compare the wrong + * segments and could match a different post entirely, which is why the space + * form is matched by exact equality — it is always fully qualified — and never + * constructed as an `AtUri` at all. + */ +export function makeUriMatcher(uri: string) { + if (isSpaceRecordUri(uri)) { + return (record: {uri: string; author: AppBskyActorDefs.ProfileViewBasic}) => + record.uri === uri + } + const atUri = new AtUri(uri) + return (record: {uri: string; author: AppBskyActorDefs.ProfileViewBasic}) => + didOrHandleUriMatches(atUri, record) +} + export function getEmbeddedPost( v: unknown, ): AppBskyEmbedRecord.ViewRecord | undefined { diff --git a/src/state/session/oauth-client.ts b/src/state/session/oauth-client.ts index e4ee5ed9d..2317be2c1 100644 --- a/src/state/session/oauth-client.ts +++ b/src/state/session/oauth-client.ts @@ -9,6 +9,22 @@ import { } from '#/state/session/oauth-telemetry' import {OAUTH_BASE_URL, OAUTH_CLIENT_NAME, OAUTH_SCOPE} from './oauth-config' +const LOCAL_OAUTH_HANDLE_RESOLVER = + process.env.EXPO_PUBLIC_OAUTH_HANDLE_RESOLVER +const LOCAL_OAUTH_PLC_DIRECTORY_URL = + process.env.EXPO_PUBLIC_OAUTH_PLC_DIRECTORY_URL +const USE_LOCAL_OAUTH_RESOLUTION = + __DEV__ && !!LOCAL_OAUTH_HANDLE_RESOLVER && !!LOCAL_OAUTH_PLC_DIRECTORY_URL + +const oauthResolutionOptions = { + handleResolver: USE_LOCAL_OAUTH_RESOLUTION + ? LOCAL_OAUTH_HANDLE_RESOLVER + : 'https://blacksky.app', + ...(USE_LOCAL_OAUTH_RESOLUTION + ? {plcDirectoryUrl: LOCAL_OAUTH_PLC_DIRECTORY_URL, allowHttp: true} + : {}), +} + export const NATIVE_REDIRECT_URI = 'community.blacksky:/oauth/callback' // The redirect deep-link can arrive with either a single (`:/oauth`) or double @@ -79,7 +95,7 @@ const BSKY_OAUTH_CLIENT = new ExpoOAuthClient({ application_type: 'native', dpop_bound_access_tokens: true, }, - handleResolver: 'https://blacksky.app', + ...oauthResolutionOptions, fetch: debugFetch, ...sessionHooks, }) diff --git a/src/state/session/oauth-client.web.ts b/src/state/session/oauth-client.web.ts index a38b0ebb3..b512bcf2f 100644 --- a/src/state/session/oauth-client.web.ts +++ b/src/state/session/oauth-client.web.ts @@ -9,6 +9,22 @@ import { import {type Metrics} from '#/analytics/metrics' import {OAUTH_SCOPE} from './oauth-config' +const LOCAL_OAUTH_HANDLE_RESOLVER = + process.env.EXPO_PUBLIC_OAUTH_HANDLE_RESOLVER +const LOCAL_OAUTH_PLC_DIRECTORY_URL = + process.env.EXPO_PUBLIC_OAUTH_PLC_DIRECTORY_URL +const USE_LOCAL_OAUTH_RESOLUTION = + __DEV__ && !!LOCAL_OAUTH_HANDLE_RESOLVER && !!LOCAL_OAUTH_PLC_DIRECTORY_URL + +const oauthResolutionOptions = { + handleResolver: USE_LOCAL_OAUTH_RESOLUTION + ? LOCAL_OAUTH_HANDLE_RESOLVER + : 'https://blacksky.app', + ...(USE_LOCAL_OAUTH_RESOLUTION + ? {plcDirectoryUrl: LOCAL_OAUTH_PLC_DIRECTORY_URL, allowHttp: true} + : {}), +} + function getOAuthBaseUrl(): string { if (typeof window !== 'undefined') { return window.location.origin @@ -162,7 +178,7 @@ function createWebOAuthClient() { application_type: 'web', dpop_bound_access_tokens: true, }, - handleResolver: 'https://blacksky.app', + ...oauthResolutionOptions, fetch: oauthInstrumentedFetch, ...sessionHooks, }) @@ -184,7 +200,7 @@ function createWebOAuthClient() { application_type: 'web', dpop_bound_access_tokens: true, }, - handleResolver: 'https://blacksky.app', + ...oauthResolutionOptions, fetch: oauthInstrumentedFetch, ...sessionHooks, }) diff --git a/src/view/com/composer/PostTargetSelect.tsx b/src/view/com/composer/PostTargetSelect.tsx index 3542ab872..7c5188a20 100644 --- a/src/view/com/composer/PostTargetSelect.tsx +++ b/src/view/com/composer/PostTargetSelect.tsx @@ -49,7 +49,7 @@ export function PostTargetSelect({ const selected = options.find(option => option.value === value) return ( - + { diff --git a/src/view/com/post/Post.tsx b/src/view/com/post/Post.tsx index 8f5e43518..3ced56d22 100644 --- a/src/view/com/post/Post.tsx +++ b/src/view/com/post/Post.tsx @@ -10,7 +10,10 @@ import { } from '@atproto/api' import {useQueryClient} from '@tanstack/react-query' -import {getCommunitySpaceUri} from '#/lib/api/community-post' +import { + getCommunitySpaceUri, + isRenderablePostRecord, +} from '#/lib/api/community-post' import {MAX_POST_LINES} from '#/lib/constants' import {useOpenComposer} from '#/lib/hooks/useOpenComposer' import {postPermalink} from '#/lib/routes/links' @@ -40,7 +43,6 @@ import {TranslatedPost} from '#/components/Post/Translated' import {PostControls} from '#/components/PostControls' import {RichText} from '#/components/RichText' import {SubtleHover} from '#/components/SubtleHover' -import * as bsky from '#/types/bsky' export function Post({ post, @@ -57,10 +59,7 @@ export function Post({ }) { const moderationOpts = useModerationOpts() const record = useMemo( - () => - bsky.validate(post.record, AppBskyFeedPost.validateRecord) - ? post.record - : undefined, + () => (isRenderablePostRecord(post) ? post.record : undefined), [post], ) const postShadowed = usePostShadow(post) diff --git a/src/view/com/posts/PostFeedItem.tsx b/src/view/com/posts/PostFeedItem.tsx index d93c4a8ea..7a1a2c90e 100644 --- a/src/view/com/posts/PostFeedItem.tsx +++ b/src/view/com/posts/PostFeedItem.tsx @@ -11,7 +11,10 @@ import { } from '@atproto/api' import {useQueryClient} from '@tanstack/react-query' -import {getCommunitySpaceUri} from '#/lib/api/community-post' +import { + getCommunitySpaceUri, + isRenderablePostRecord, +} from '#/lib/api/community-post' import {type ReasonFeedSource} from '#/lib/api/feed/types' import {MAX_POST_LINES} from '#/lib/constants' import {useOpenComposer} from '#/lib/hooks/useOpenComposer' @@ -480,10 +483,7 @@ let PostContent = ({ ) const record = useMemo( - () => - bsky.validate(post.record, AppBskyFeedPost.validateRecord) - ? post.record - : undefined, + () => (isRenderablePostRecord(post) ? post.record : undefined), [post], )