From db76865ccee3cc09706c225752d45fa1d475a14b Mon Sep 17 00:00:00 2001 From: maelstrom Date: Fri, 1 May 2026 22:41:31 +0200 Subject: [PATCH] validation code --- src/lib/post.ts | 52 ++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 51 insertions(+), 1 deletion(-) diff --git a/src/lib/post.ts b/src/lib/post.ts index 1754a38..d2869c9 100644 --- a/src/lib/post.ts +++ b/src/lib/post.ts @@ -22,4 +22,54 @@ export type ThreadPost = Post & { // The CID as it was, referenced by the current thread // Can be compared with the current cid to check if a post has been edited contextCid: CidString; -}; \ No newline at end of file +}; + +function refsEqual(ref1?: strongRef.Main, ref2?: strongRef.Main) { + return ref1?.uri === ref2?.uri && ref1?.cid === ref2?.cid +} + +export function validatePost(post: Post) { + // Require threadless posts to be not have a thread chain + if (post.thread.length === 0 && post.reblog !== undefined) + return false + + // First item in thread must match root, last item must match parent + if (post.thread.length > 0 && (post.reblog === undefined || !refsEqual(post.reblog.root, post.thread.at(0)) || !refsEqual(post.reblog.parent, post.thread.at(-1)))) + return false + + return true +} + +// TODO: Actually use this somewhere +export function validatePostThread(threadRefs: Post['thread'], threadItems: ThreadPost[]) { + // Each thread item must either be undefined (not found by us), or: + // 1. Must be valid + // 2. Thread field must match threadRefs[0:i] + + function validateThreadRefs(bottomThreadRefs: Post['thread'], itemThreadRefs: Post['thread'], itemIndex: number) { + // The number of thread refs each post has must reflect its position in the chain + if (itemThreadRefs.length !== itemIndex) return false + + for (const [i] of itemThreadRefs.entries()) { + if (bottomThreadRefs[i] !== itemThreadRefs[i]) { + return false + } + } + return true + } + + for (const [i] of threadRefs.entries()) { + const threadItem = threadItems[i] + + // If the item is not found by us, don't check it + if (threadItem === undefined) continue; + + // Otherwise, validate it + if (!validatePost(threadItem)) return false; + + // Validate the thread refs + if (!validateThreadRefs(threadRefs, threadItem.thread, i)) return false + } + + return true +} \ No newline at end of file -- 2.51.2