From a3d81dd911b39877dc07d993912c14a2271646aa Mon Sep 17 00:00:00 2001 From: Daniel Holmgren Date: Fri, 3 Nov 2023 16:55:50 -0500 Subject: [PATCH] Prevent thread loops (#1813) * prevent thread loops * include original uri * tidy * tweak * last tweak * last tweak i swear * wording --- .../src/api/app/bsky/feed/getPostThread.ts | 20 +++++++++++++++---- 1 file changed, 16 insertions(+), 4 deletions(-) diff --git a/packages/bsky/src/api/app/bsky/feed/getPostThread.ts b/packages/bsky/src/api/app/bsky/feed/getPostThread.ts index 1480e54ac1a..0e31107d052 100644 --- a/packages/bsky/src/api/app/bsky/feed/getPostThread.ts +++ b/packages/bsky/src/api/app/bsky/feed/getPostThread.ts @@ -255,11 +255,15 @@ const getThreadData = async ( .orderBy('sortAt', 'desc') .execute(), ]) - const parentsByUri = parents.reduce((acc, parent) => { - return Object.assign(acc, { [parent.postUri]: parent }) + // prevent self-referential loops + const includedPosts = new Set([uri]) + const parentsByUri = parents.reduce((acc, post) => { + return Object.assign(acc, { [post.uri]: post }) }, {} as Record) const childrenByParentUri = children.reduce((acc, child) => { if (!child.replyParent) return acc + if (includedPosts.has(child.uri)) return acc + includedPosts.add(child.uri) acc[child.replyParent] ??= [] acc[child.replyParent].push(child) return acc @@ -269,7 +273,12 @@ const getThreadData = async ( return { post, parent: post.replyParent - ? getParentData(parentsByUri, post.replyParent, parentHeight) + ? getParentData( + parentsByUri, + includedPosts, + post.replyParent, + parentHeight, + ) : undefined, replies: getChildrenData(childrenByParentUri, uri, depth), } @@ -277,16 +286,19 @@ const getThreadData = async ( const getParentData = ( postsByUri: Record, + includedPosts: Set, uri: string, depth: number, ): PostThread | ParentNotFoundError | undefined => { if (depth < 1) return undefined + if (includedPosts.has(uri)) return undefined + includedPosts.add(uri) const post = postsByUri[uri] if (!post) return new ParentNotFoundError(uri) return { post, parent: post.replyParent - ? getParentData(postsByUri, post.replyParent, depth - 1) + ? getParentData(postsByUri, includedPosts, post.replyParent, depth - 1) : undefined, replies: [], }