From bec6159b4a19905efa79acce105e63a80f0d1100 Mon Sep 17 00:00:00 2001
From: tamaina <tamaina@hotmail.co.jp>
Date: Fri, 1 Mar 2024 06:58:43 +0000
Subject: [PATCH] exactKey

---
 .../core/activitypub/ApDbResolverService.ts   | 48 ++++++++++++-------
 1 file changed, 30 insertions(+), 18 deletions(-)

diff --git a/packages/backend/src/core/activitypub/ApDbResolverService.ts b/packages/backend/src/core/activitypub/ApDbResolverService.ts
index d95bd3bbda..25a37ca096 100644
--- a/packages/backend/src/core/activitypub/ApDbResolverService.ts
+++ b/packages/backend/src/core/activitypub/ApDbResolverService.ts
@@ -131,31 +131,43 @@ export class ApDbResolverService implements OnApplicationShutdown {
 			v => v != null,
 		);
 
-		if (keys == null || keys.length === 8) return null;
+		if (keys == null || !Array.isArray(keys)) return null;
+
+		if (keys.length === 0) {
+			return {
+				user,
+				key: keys[0],
+			};
+		}
+
+		const exactKey = keys.find(x => x.keyId === keyId);
+		if (exactKey) {
+			return {
+				user,
+				key: exactKey,
+			};
+		}
 
 		// 公開鍵は複数あるが、mainっぽいのを選ぶ
-		const key = keys.length === 1 ?
-			keys[0] :
-			keys.find(x => {
-				try {
-					if (x.keyId === keyId) return true;
-					const url = new URL(x.keyId);
-					const path = url.pathname.split('/').pop()?.toLowerCase();
-					if (url.hash) {
-						if (url.hash.toLowerCase().includes('main')) {
-							return true;
-						}
-					} else if (path?.includes('main') || path === 'publickey') {
+		const mainKey = keys.find(x => {
+			try {
+				if (x.keyId === keyId) return true;
+				const url = new URL(x.keyId);
+				const path = url.pathname.split('/').pop()?.toLowerCase();
+				if (url.hash) {
+					if (url.hash.toLowerCase().includes('main')) {
 						return true;
 					}
-				} catch { /* noop */ }
-
-				return false;
-			}) ?? keys[0];
+				} else if (path?.includes('main') || path === 'publickey') {
+					return true;
+				}
+			} catch { /* noop */ }
 
+			return false;
+		});
 		return {
 			user,
-			key,
+			key: mainKey ?? keys[0],
 		};
 	}