From eaef12b331c3741ac322eaf6182e130c2483fc62 Mon Sep 17 00:00:00 2001 From: Patrick Schrall Date: Thu, 11 Jun 2026 15:17:06 +0200 Subject: [PATCH 1/8] Fix(bluesky): resolve @mention handles to DIDs before building facets MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A mention facet (app.bsky.richtext.facet#mention) requires the target's DID in its `did` field. The publisher put the raw handle there with the comment "Will be resolved by Bluesky", but Bluesky does not resolve handles at that point — it rejects the whole record with InvalidRequest, surfaced to users as "Invalid post data". As a result, every scheduled post that contained an @mention failed to publish, while posts without a mention published fine. Resolve each handle to a DID via com.atproto.identity.resolveHandle (account PDS first, then the public AppView / bsky.social as fallback), cache resolutions per post, and use the resolved DID in the facet. If a handle cannot be resolved, the facet is skipped so the post still publishes with the @handle as plain text instead of failing entirely. Co-Authored-By: Claude Opus 4.8 (1M context) --- app/Services/Social/BlueskyPublisher.php | 62 +++++++++++++++++- .../Services/Social/BlueskyPublisherTest.php | 65 +++++++++++++++++++ 2 files changed, 124 insertions(+), 3 deletions(-) diff --git a/app/Services/Social/BlueskyPublisher.php b/app/Services/Social/BlueskyPublisher.php index 38094fc6..abc4a04e 100644 --- a/app/Services/Social/BlueskyPublisher.php +++ b/app/Services/Social/BlueskyPublisher.php @@ -60,7 +60,7 @@ public function publish(PostPlatform $postPlatform): array // Parse facets (links, mentions, hashtags) from text $text = $content ?? ''; - $facets = $this->parseFacets($text); + $facets = $this->parseFacets($text, $service, $account); // Create post record $record = [ @@ -166,7 +166,7 @@ private function uploadBlob(SocialAccount $account, string $service, string $url } } - private function parseFacets(string $text): array + private function parseFacets(string $text, ?string $service = null, ?SocialAccount $account = null): array { $facets = []; @@ -205,9 +205,22 @@ private function parseFacets(string $text): array PREG_OFFSET_CAPTURE ); + $didCache = []; foreach ($mentionMatches[0] as $match) { $mention = $match[0]; $handle = substr($mention, 1); // Remove @ + + // A mention facet requires the target's DID, not the handle. Bluesky + // does NOT resolve a handle placed in the `did` field — sending one + // makes the whole record invalid (InvalidRequest / "Invalid post + // data"), so every post containing a mention fails to publish. + // Resolve the handle to a DID here; if it can't be resolved, skip the + // facet so the post still publishes with the @handle as plain text. + $did = $didCache[$handle] ?? ($didCache[$handle] = $this->resolveHandleToDid($handle, $service, $account)); + if ($did === null) { + continue; + } + $start = $this->getUtf8ByteOffset($text, $match[1]); $end = $start + strlen($mention); @@ -219,7 +232,7 @@ private function parseFacets(string $text): array 'features' => [ [ '$type' => 'app.bsky.richtext.facet#mention', - 'did' => $handle, // Will be resolved by Bluesky + 'did' => $did, ], ], ]; @@ -256,6 +269,49 @@ private function parseFacets(string $text): array return $facets; } + /** + * Resolve a Bluesky handle to its DID via com.atproto.identity.resolveHandle. + * + * Tries the account's own PDS first (authenticated), then falls back to the + * public AppView and the bsky.social entryway. Returns null on failure so the + * caller can skip the mention facet instead of sending an invalid record. + */ + private function resolveHandleToDid(string $handle, ?string $service = null, ?SocialAccount $account = null): ?string + { + $endpoints = array_values(array_unique(array_filter([ + $service, + 'https://public.api.bsky.app', + 'https://bsky.social', + ]))); + + foreach ($endpoints as $endpoint) { + try { + $request = $this->socialHttp(); + if ($account && $endpoint === $service) { + $request = $request->withToken($account->access_token); + } + + $response = $request->get( + "{$endpoint}/xrpc/com.atproto.identity.resolveHandle", + ['handle' => $handle], + ); + + $did = $response->successful() ? data_get($response->json(), 'did') : null; + if (is_string($did) && str_starts_with($did, 'did:')) { + return $did; + } + } catch (\Throwable $e) { + Log::warning('Bluesky handle resolution failed', [ + 'handle' => $handle, + 'endpoint' => $endpoint, + 'error' => $e->getMessage(), + ]); + } + } + + return null; + } + private function getUtf8ByteOffset(string $text, int $charOffset): int { return strlen(substr($text, 0, $charOffset)); diff --git a/tests/Feature/Services/Social/BlueskyPublisherTest.php b/tests/Feature/Services/Social/BlueskyPublisherTest.php index 0d017b88..71610c69 100644 --- a/tests/Feature/Services/Social/BlueskyPublisherTest.php +++ b/tests/Feature/Services/Social/BlueskyPublisherTest.php @@ -101,6 +101,71 @@ }); }); +test('bluesky publisher resolves mentions to DIDs as facets', function () { + $this->post->update(['content' => 'Shout out to @friend.bsky.social']); + + Http::fake([ + 'https://bsky.social/xrpc/com.atproto.identity.resolveHandle*' => Http::response([ + 'did' => 'did:plc:friend456', + ], 200), + 'https://bsky.social/xrpc/com.atproto.repo.createRecord' => Http::response([ + 'uri' => 'at://did:plc:testuser123/app.bsky.feed.post/3abc123xyz', + 'cid' => 'bafyreiabc123', + ], 200), + ]); + + $this->publisher->publish($this->postPlatform); + + Http::assertSent(function ($request) { + $record = $request['record'] ?? null; + + if (! $record || ! isset($record['facets'])) { + return false; + } + + foreach ($record['facets'] as $facet) { + $feature = $facet['features'][0]; + if ($feature['$type'] === 'app.bsky.richtext.facet#mention') { + // The facet must carry the resolved DID, not the raw handle. + return $feature['did'] === 'did:plc:friend456'; + } + } + + return false; + }); +}); + +test('bluesky publisher skips mention facet when handle cannot be resolved', function () { + $this->post->update(['content' => 'Shout out to @ghost.bsky.social']); + + Http::fake([ + '*/xrpc/com.atproto.identity.resolveHandle*' => Http::response(['error' => 'InvalidRequest'], 400), + 'https://bsky.social/xrpc/com.atproto.repo.createRecord' => Http::response([ + 'uri' => 'at://did:plc:testuser123/app.bsky.feed.post/3abc123xyz', + 'cid' => 'bafyreiabc123', + ], 200), + ]); + + // Post still publishes; the unresolved @handle stays as plain text. + $result = $this->publisher->publish($this->postPlatform); + + expect($result['id'])->toBe('3abc123xyz'); + + Http::assertSent(function ($request) { + $record = $request['record'] ?? null; + + if (! $record) { + return false; + } + + $hasMentionFacet = collect($record['facets'] ?? [])->contains( + fn ($facet) => $facet['features'][0]['$type'] === 'app.bsky.richtext.facet#mention' + ); + + return str_contains($record['text'], '@ghost.bsky.social') && ! $hasMentionFacet; + }); +}); + test('bluesky publisher uploads images', function () { // Create a media item through the PostPlatform's media() relation $this->post->update([ From b317b8dbb2243014784ae20ce1cbbc9ebbd9da36 Mon Sep 17 00:00:00 2001 From: Patrick Schrall Date: Thu, 11 Jun 2026 17:37:16 +0200 Subject: [PATCH 2/8] Address Copilot review: normalize endpoints, quieter logs, robust tests - resolveHandleToDid: rtrim trailing slash on the service URL before building the request URL and before the `=== $service` auth check (avoids double-slash URLs and mis-detected auth). - Log per-endpoint resolution attempts at debug; emit a single warning only after all endpoints are exhausted (less noise during transient outages). - Tests: fake resolveHandle with a wildcard so the case is isolated from the configured service URL; read request payload via $request->data(). Co-Authored-By: Claude Opus 4.8 (1M context) --- app/Services/Social/BlueskyPublisher.php | 19 ++++++++++++++++++- .../Services/Social/BlueskyPublisherTest.php | 9 ++++++--- 2 files changed, 24 insertions(+), 4 deletions(-) diff --git a/app/Services/Social/BlueskyPublisher.php b/app/Services/Social/BlueskyPublisher.php index abc4a04e..b3a7943e 100644 --- a/app/Services/Social/BlueskyPublisher.php +++ b/app/Services/Social/BlueskyPublisher.php @@ -278,12 +278,18 @@ private function parseFacets(string $text, ?string $service = null, ?SocialAccou */ private function resolveHandleToDid(string $handle, ?string $service = null, ?SocialAccount $account = null): ?string { + // Normalize so a trailing slash neither produces a double-slash URL nor + // breaks the `=== $service` check below (which decides authentication). + $service = $service !== null ? rtrim($service, '/') : null; + $endpoints = array_values(array_unique(array_filter([ $service, 'https://public.api.bsky.app', 'https://bsky.social', ]))); + $lastError = null; + $lastEndpoint = null; foreach ($endpoints as $endpoint) { try { $request = $this->socialHttp(); @@ -301,7 +307,12 @@ private function resolveHandleToDid(string $handle, ?string $service = null, ?So return $did; } } catch (\Throwable $e) { - Log::warning('Bluesky handle resolution failed', [ + // Per-endpoint failures are expected during transient outages; + // keep them at debug to avoid noisy logs and surface a single + // warning below only when every endpoint has been exhausted. + $lastError = $e->getMessage(); + $lastEndpoint = $endpoint; + Log::debug('Bluesky handle resolution attempt failed', [ 'handle' => $handle, 'endpoint' => $endpoint, 'error' => $e->getMessage(), @@ -309,6 +320,12 @@ private function resolveHandleToDid(string $handle, ?string $service = null, ?So } } + Log::warning('Bluesky handle resolution failed; mention will be sent as plain text', [ + 'handle' => $handle, + 'endpoint' => $lastEndpoint, + 'error' => $lastError, + ]); + return null; } diff --git a/tests/Feature/Services/Social/BlueskyPublisherTest.php b/tests/Feature/Services/Social/BlueskyPublisherTest.php index 71610c69..6ce6df4a 100644 --- a/tests/Feature/Services/Social/BlueskyPublisherTest.php +++ b/tests/Feature/Services/Social/BlueskyPublisherTest.php @@ -105,7 +105,10 @@ $this->post->update(['content' => 'Shout out to @friend.bsky.social']); Http::fake([ - 'https://bsky.social/xrpc/com.atproto.identity.resolveHandle*' => Http::response([ + // Wildcard so the fake matches whichever endpoint resolveHandleToDid() + // tries first (the account PDS, public AppView, or bsky.social) and the + // test stays isolated from the configured service URL. + '*/xrpc/com.atproto.identity.resolveHandle*' => Http::response([ 'did' => 'did:plc:friend456', ], 200), 'https://bsky.social/xrpc/com.atproto.repo.createRecord' => Http::response([ @@ -117,7 +120,7 @@ $this->publisher->publish($this->postPlatform); Http::assertSent(function ($request) { - $record = $request['record'] ?? null; + $record = $request->data()['record'] ?? null; if (! $record || ! isset($record['facets'])) { return false; @@ -152,7 +155,7 @@ expect($result['id'])->toBe('3abc123xyz'); Http::assertSent(function ($request) { - $record = $request['record'] ?? null; + $record = $request->data()['record'] ?? null; if (! $record) { return false; From 5cafac34c18d0ded89b7363f95e13991751dba60 Mon Sep 17 00:00:00 2001 From: Paulo Castellano Date: Sat, 13 Jun 2026 18:15:31 -0300 Subject: [PATCH 3/8] Resolve Bluesky endpoints from config and import Throwable Use the existing config('trypost.platforms.bluesky.public_appview') and default_service keys for the handle-resolution fallbacks instead of hardcoding the hosts, so a self-hosted override (BLUESKY_PUBLIC_APPVIEW) is honored here like it already is in BlueskyAnalytics. Import Throwable instead of referencing it inline. --- app/Services/Social/BlueskyPublisher.php | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/app/Services/Social/BlueskyPublisher.php b/app/Services/Social/BlueskyPublisher.php index b3a7943e..2fb38557 100644 --- a/app/Services/Social/BlueskyPublisher.php +++ b/app/Services/Social/BlueskyPublisher.php @@ -13,6 +13,7 @@ use Illuminate\Http\Client\Response; use Illuminate\Support\Facades\Http; use Illuminate\Support\Facades\Log; +use Throwable; class BlueskyPublisher { @@ -284,8 +285,8 @@ private function resolveHandleToDid(string $handle, ?string $service = null, ?So $endpoints = array_values(array_unique(array_filter([ $service, - 'https://public.api.bsky.app', - 'https://bsky.social', + config('trypost.platforms.bluesky.public_appview'), + config('trypost.platforms.bluesky.default_service'), ]))); $lastError = null; @@ -306,7 +307,7 @@ private function resolveHandleToDid(string $handle, ?string $service = null, ?So if (is_string($did) && str_starts_with($did, 'did:')) { return $did; } - } catch (\Throwable $e) { + } catch (Throwable $e) { // Per-endpoint failures are expected during transient outages; // keep them at debug to avoid noisy logs and surface a single // warning below only when every endpoint has been exhausted. From 5d80caffefea4921bd5608dd4328da9b03953786 Mon Sep 17 00:00:00 2001 From: Paulo Castellano Date: Sat, 13 Jun 2026 18:16:24 -0300 Subject: [PATCH 4/8] Shorten the mention-facet comment to one line --- app/Services/Social/BlueskyPublisher.php | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) diff --git a/app/Services/Social/BlueskyPublisher.php b/app/Services/Social/BlueskyPublisher.php index 2fb38557..31eaff47 100644 --- a/app/Services/Social/BlueskyPublisher.php +++ b/app/Services/Social/BlueskyPublisher.php @@ -211,12 +211,7 @@ private function parseFacets(string $text, ?string $service = null, ?SocialAccou $mention = $match[0]; $handle = substr($mention, 1); // Remove @ - // A mention facet requires the target's DID, not the handle. Bluesky - // does NOT resolve a handle placed in the `did` field — sending one - // makes the whole record invalid (InvalidRequest / "Invalid post - // data"), so every post containing a mention fails to publish. - // Resolve the handle to a DID here; if it can't be resolved, skip the - // facet so the post still publishes with the @handle as plain text. + // A mention facet needs the target's DID, not the handle; skip it if unresolvable. $did = $didCache[$handle] ?? ($didCache[$handle] = $this->resolveHandleToDid($handle, $service, $account)); if ($did === null) { continue; From 409c6f013902ad21cabbd2afc18abb1ad8b52077 Mon Sep 17 00:00:00 2001 From: Paulo Castellano Date: Sat, 13 Jun 2026 18:19:04 -0300 Subject: [PATCH 5/8] Drop the resolution warning log and fake createRecord via config MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Remove the final Log::warning (and the lastError/lastEndpoint tracking that only fed it) — the per-endpoint debug log already covers diagnosis. Fake the createRecord endpoint from config('trypost.platforms.bluesky.default_service') in the new tests instead of hardcoding the host. --- app/Services/Social/BlueskyPublisher.php | 13 ------------- .../Services/Social/BlueskyPublisherTest.php | 4 ++-- 2 files changed, 2 insertions(+), 15 deletions(-) diff --git a/app/Services/Social/BlueskyPublisher.php b/app/Services/Social/BlueskyPublisher.php index 31eaff47..dda56f9a 100644 --- a/app/Services/Social/BlueskyPublisher.php +++ b/app/Services/Social/BlueskyPublisher.php @@ -284,8 +284,6 @@ private function resolveHandleToDid(string $handle, ?string $service = null, ?So config('trypost.platforms.bluesky.default_service'), ]))); - $lastError = null; - $lastEndpoint = null; foreach ($endpoints as $endpoint) { try { $request = $this->socialHttp(); @@ -303,11 +301,6 @@ private function resolveHandleToDid(string $handle, ?string $service = null, ?So return $did; } } catch (Throwable $e) { - // Per-endpoint failures are expected during transient outages; - // keep them at debug to avoid noisy logs and surface a single - // warning below only when every endpoint has been exhausted. - $lastError = $e->getMessage(); - $lastEndpoint = $endpoint; Log::debug('Bluesky handle resolution attempt failed', [ 'handle' => $handle, 'endpoint' => $endpoint, @@ -316,12 +309,6 @@ private function resolveHandleToDid(string $handle, ?string $service = null, ?So } } - Log::warning('Bluesky handle resolution failed; mention will be sent as plain text', [ - 'handle' => $handle, - 'endpoint' => $lastEndpoint, - 'error' => $lastError, - ]); - return null; } diff --git a/tests/Feature/Services/Social/BlueskyPublisherTest.php b/tests/Feature/Services/Social/BlueskyPublisherTest.php index 6ce6df4a..0c38df33 100644 --- a/tests/Feature/Services/Social/BlueskyPublisherTest.php +++ b/tests/Feature/Services/Social/BlueskyPublisherTest.php @@ -111,7 +111,7 @@ '*/xrpc/com.atproto.identity.resolveHandle*' => Http::response([ 'did' => 'did:plc:friend456', ], 200), - 'https://bsky.social/xrpc/com.atproto.repo.createRecord' => Http::response([ + config('trypost.platforms.bluesky.default_service').'/xrpc/com.atproto.repo.createRecord' => Http::response([ 'uri' => 'at://did:plc:testuser123/app.bsky.feed.post/3abc123xyz', 'cid' => 'bafyreiabc123', ], 200), @@ -143,7 +143,7 @@ Http::fake([ '*/xrpc/com.atproto.identity.resolveHandle*' => Http::response(['error' => 'InvalidRequest'], 400), - 'https://bsky.social/xrpc/com.atproto.repo.createRecord' => Http::response([ + config('trypost.platforms.bluesky.default_service').'/xrpc/com.atproto.repo.createRecord' => Http::response([ 'uri' => 'at://did:plc:testuser123/app.bsky.feed.post/3abc123xyz', 'cid' => 'bafyreiabc123', ], 200), From 9f0c264c39a42fb86658c5c7fc9c223684bd2b08 Mon Sep 17 00:00:00 2001 From: Paulo Castellano Date: Sat, 13 Jun 2026 18:21:16 -0300 Subject: [PATCH 6/8] Cover mention endpoint fallback and partial resolution Add tests for the two untested branches of the DID resolution: falling back to the public AppView when the account's PDS can't resolve a handle, and a post mixing a resolvable mention (kept as a facet) with an unresolvable one (a 200 without a DID, left as plain text). The prior tests only hit the happy path and the all-endpoints-fail path via a wildcard that masked the fallback. --- .../Services/Social/BlueskyPublisherTest.php | 74 +++++++++++++++++++ 1 file changed, 74 insertions(+) diff --git a/tests/Feature/Services/Social/BlueskyPublisherTest.php b/tests/Feature/Services/Social/BlueskyPublisherTest.php index 0c38df33..d7a296e5 100644 --- a/tests/Feature/Services/Social/BlueskyPublisherTest.php +++ b/tests/Feature/Services/Social/BlueskyPublisherTest.php @@ -169,6 +169,80 @@ }); }); +test('bluesky publisher falls back to the public AppView when the PDS cannot resolve', function () { + $this->post->update(['content' => 'Shout out to @friend.bsky.social']); + + $service = config('trypost.platforms.bluesky.default_service'); + $appView = config('trypost.platforms.bluesky.public_appview'); + + Http::fake([ + // The account's PDS fails to resolve; resolution must fall back to the + // public AppView rather than giving up after the first endpoint. + $service.'/xrpc/com.atproto.identity.resolveHandle*' => Http::response(['error' => 'InvalidRequest'], 400), + $appView.'/xrpc/com.atproto.identity.resolveHandle*' => Http::response(['did' => 'did:plc:friend456'], 200), + $service.'/xrpc/com.atproto.repo.createRecord' => Http::response([ + 'uri' => 'at://did:plc:testuser123/app.bsky.feed.post/3abc123xyz', + 'cid' => 'bafyreiabc123', + ], 200), + ]); + + $this->publisher->publish($this->postPlatform); + + Http::assertSent(function ($request) { + $record = $request->data()['record'] ?? null; + + if (! $record) { + return false; + } + + foreach ($record['facets'] ?? [] as $facet) { + $feature = $facet['features'][0]; + if ($feature['$type'] === 'app.bsky.richtext.facet#mention') { + return $feature['did'] === 'did:plc:friend456'; + } + } + + return false; + }); +}); + +test('bluesky publisher resolves some mentions and skips the unresolvable ones', function () { + $this->post->update(['content' => 'cc @good.bsky.social and @bad.bsky.social']); + + Http::fake(function ($request) { + if (str_contains($request->url(), 'resolveHandle')) { + // `good` resolves; `bad` answers 200 without a DID — treated as + // unresolvable, exercising the str_starts_with('did:') guard. + return str_contains($request->url(), 'good.bsky.social') + ? Http::response(['did' => 'did:plc:good999'], 200) + : Http::response([], 200); + } + + return Http::response([ + 'uri' => 'at://did:plc:testuser123/app.bsky.feed.post/3abc123xyz', + 'cid' => 'bafyreiabc123', + ], 200); + }); + + $this->publisher->publish($this->postPlatform); + + Http::assertSent(function ($request) { + $record = $request->data()['record'] ?? null; + + if (! $record) { + return false; + } + + $mentions = collect($record['facets'] ?? []) + ->filter(fn ($facet) => $facet['features'][0]['$type'] === 'app.bsky.richtext.facet#mention'); + + // Only the resolvable handle becomes a facet; the other stays plain text. + return $mentions->count() === 1 + && $mentions->first()['features'][0]['did'] === 'did:plc:good999' + && str_contains($record['text'], '@bad.bsky.social'); + }); +}); + test('bluesky publisher uploads images', function () { // Create a media item through the PostPlatform's media() relation $this->post->update([ From 5227cde5c729e695a22658540332826bfeaf3a08 Mon Sep 17 00:00:00 2001 From: Paulo Castellano Date: Sat, 13 Jun 2026 18:35:30 -0300 Subject: [PATCH 7/8] Cache unresolvable handles and tighten offset types Memoize by key (array_key_exists) so a handle that fails to resolve is tried once per post instead of on every repeat occurrence, and add a test that a repeated handle resolves once. Cast the PREG_OFFSET_CAPTURE offsets to int to match getUtf8ByteOffset's signature, and reword the resolver docblock to say "configured default service" instead of naming bsky.social. --- app/Services/Social/BlueskyPublisher.php | 16 +++++---- .../Services/Social/BlueskyPublisherTest.php | 33 +++++++++++++++++++ 2 files changed, 43 insertions(+), 6 deletions(-) diff --git a/app/Services/Social/BlueskyPublisher.php b/app/Services/Social/BlueskyPublisher.php index dda56f9a..b44060ab 100644 --- a/app/Services/Social/BlueskyPublisher.php +++ b/app/Services/Social/BlueskyPublisher.php @@ -181,7 +181,7 @@ private function parseFacets(string $text, ?string $service = null, ?SocialAccou foreach ($urlMatches[0] as $match) { $url = $match[0]; - $start = $this->getUtf8ByteOffset($text, $match[1]); + $start = $this->getUtf8ByteOffset($text, (int) $match[1]); $end = $start + strlen($url); $facets[] = [ @@ -212,12 +212,16 @@ private function parseFacets(string $text, ?string $service = null, ?SocialAccou $handle = substr($mention, 1); // Remove @ // A mention facet needs the target's DID, not the handle; skip it if unresolvable. - $did = $didCache[$handle] ?? ($didCache[$handle] = $this->resolveHandleToDid($handle, $service, $account)); + // Cache by key (not ??) so an unresolvable handle is resolved once, not per occurrence. + if (! array_key_exists($handle, $didCache)) { + $didCache[$handle] = $this->resolveHandleToDid($handle, $service, $account); + } + $did = $didCache[$handle]; if ($did === null) { continue; } - $start = $this->getUtf8ByteOffset($text, $match[1]); + $start = $this->getUtf8ByteOffset($text, (int) $match[1]); $end = $start + strlen($mention); $facets[] = [ @@ -245,7 +249,7 @@ private function parseFacets(string $text, ?string $service = null, ?SocialAccou foreach ($hashtagMatches[0] as $match) { $hashtag = $match[0]; $tag = substr($hashtag, 1); // Remove # - $start = $this->getUtf8ByteOffset($text, $match[1]); + $start = $this->getUtf8ByteOffset($text, (int) $match[1]); $end = $start + strlen($hashtag); $facets[] = [ @@ -269,8 +273,8 @@ private function parseFacets(string $text, ?string $service = null, ?SocialAccou * Resolve a Bluesky handle to its DID via com.atproto.identity.resolveHandle. * * Tries the account's own PDS first (authenticated), then falls back to the - * public AppView and the bsky.social entryway. Returns null on failure so the - * caller can skip the mention facet instead of sending an invalid record. + * public AppView and the configured default service. Returns null on failure + * so the caller can skip the mention facet instead of sending an invalid record. */ private function resolveHandleToDid(string $handle, ?string $service = null, ?SocialAccount $account = null): ?string { diff --git a/tests/Feature/Services/Social/BlueskyPublisherTest.php b/tests/Feature/Services/Social/BlueskyPublisherTest.php index d7a296e5..db740e74 100644 --- a/tests/Feature/Services/Social/BlueskyPublisherTest.php +++ b/tests/Feature/Services/Social/BlueskyPublisherTest.php @@ -243,6 +243,39 @@ }); }); +test('bluesky publisher resolves a repeated handle only once', function () { + $this->post->update(['content' => 'thanks @dup.bsky.social, really @dup.bsky.social']); + + Http::fake([ + '*/xrpc/com.atproto.identity.resolveHandle*' => Http::response(['did' => 'did:plc:dup789'], 200), + config('trypost.platforms.bluesky.default_service').'/xrpc/com.atproto.repo.createRecord' => Http::response([ + 'uri' => 'at://did:plc:testuser123/app.bsky.feed.post/3abc123xyz', + 'cid' => 'bafyreiabc123', + ], 200), + ]); + + $this->publisher->publish($this->postPlatform); + + // The same handle appears twice but the per-post cache resolves it once. + $resolveCalls = Http::recorded(fn ($request) => str_contains($request->url(), 'resolveHandle'))->count(); + expect($resolveCalls)->toBe(1); + + // Both occurrences still become mention facets carrying the DID. + Http::assertSent(function ($request) { + $record = $request->data()['record'] ?? null; + + if (! $record) { + return false; + } + + $mentions = collect($record['facets'] ?? []) + ->filter(fn ($facet) => $facet['features'][0]['$type'] === 'app.bsky.richtext.facet#mention'); + + return $mentions->count() === 2 + && $mentions->every(fn ($facet) => $facet['features'][0]['did'] === 'did:plc:dup789'); + }); +}); + test('bluesky publisher uploads images', function () { // Create a media item through the PostPlatform's media() relation $this->post->update([ From 60094c93162131ff4e0056ba9921ca0164f376bb Mon Sep 17 00:00:00 2001 From: Paulo Castellano Date: Sat, 13 Jun 2026 18:41:43 -0300 Subject: [PATCH 8/8] Simplify handle resolution to a single AppView call MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit resolveHandle is a public read served by the AppView, so drop the PDS-first auth, the multi-endpoint fallback loop and the threaded service/account args in favor of one unauthenticated GET against config public_appview — matching how BlueskyAnalytics already reads from the AppView. The try/catch stays so a network error degrades the mention to plain text instead of failing the post. Remove the now-obsolete fallback test. --- app/Services/Social/BlueskyPublisher.php | 56 ++++++------------- .../Services/Social/BlueskyPublisherTest.php | 37 ------------ 2 files changed, 17 insertions(+), 76 deletions(-) diff --git a/app/Services/Social/BlueskyPublisher.php b/app/Services/Social/BlueskyPublisher.php index b44060ab..a47115e1 100644 --- a/app/Services/Social/BlueskyPublisher.php +++ b/app/Services/Social/BlueskyPublisher.php @@ -61,7 +61,7 @@ public function publish(PostPlatform $postPlatform): array // Parse facets (links, mentions, hashtags) from text $text = $content ?? ''; - $facets = $this->parseFacets($text, $service, $account); + $facets = $this->parseFacets($text); // Create post record $record = [ @@ -167,7 +167,7 @@ private function uploadBlob(SocialAccount $account, string $service, string $url } } - private function parseFacets(string $text, ?string $service = null, ?SocialAccount $account = null): array + private function parseFacets(string $text): array { $facets = []; @@ -214,7 +214,7 @@ private function parseFacets(string $text, ?string $service = null, ?SocialAccou // A mention facet needs the target's DID, not the handle; skip it if unresolvable. // Cache by key (not ??) so an unresolvable handle is resolved once, not per occurrence. if (! array_key_exists($handle, $didCache)) { - $didCache[$handle] = $this->resolveHandleToDid($handle, $service, $account); + $didCache[$handle] = $this->resolveHandleToDid($handle); } $did = $didCache[$handle]; if ($did === null) { @@ -272,48 +272,26 @@ private function parseFacets(string $text, ?string $service = null, ?SocialAccou /** * Resolve a Bluesky handle to its DID via com.atproto.identity.resolveHandle. * - * Tries the account's own PDS first (authenticated), then falls back to the - * public AppView and the configured default service. Returns null on failure - * so the caller can skip the mention facet instead of sending an invalid record. + * resolveHandle is a public read served by the AppView (no auth). Returns + * null on any failure so the caller can skip the mention facet and publish + * the @handle as plain text instead of an invalid record. */ - private function resolveHandleToDid(string $handle, ?string $service = null, ?SocialAccount $account = null): ?string + private function resolveHandleToDid(string $handle): ?string { - // Normalize so a trailing slash neither produces a double-slash URL nor - // breaks the `=== $service` check below (which decides authentication). - $service = $service !== null ? rtrim($service, '/') : null; + $appView = (string) config('trypost.platforms.bluesky.public_appview'); - $endpoints = array_values(array_unique(array_filter([ - $service, - config('trypost.platforms.bluesky.public_appview'), - config('trypost.platforms.bluesky.default_service'), - ]))); + try { + $response = $this->socialHttp()->get( + "{$appView}/xrpc/com.atproto.identity.resolveHandle", + ['handle' => $handle], + ); - foreach ($endpoints as $endpoint) { - try { - $request = $this->socialHttp(); - if ($account && $endpoint === $service) { - $request = $request->withToken($account->access_token); - } + $did = $response->successful() ? data_get($response->json(), 'did') : null; - $response = $request->get( - "{$endpoint}/xrpc/com.atproto.identity.resolveHandle", - ['handle' => $handle], - ); - - $did = $response->successful() ? data_get($response->json(), 'did') : null; - if (is_string($did) && str_starts_with($did, 'did:')) { - return $did; - } - } catch (Throwable $e) { - Log::debug('Bluesky handle resolution attempt failed', [ - 'handle' => $handle, - 'endpoint' => $endpoint, - 'error' => $e->getMessage(), - ]); - } + return is_string($did) && str_starts_with($did, 'did:') ? $did : null; + } catch (Throwable) { + return null; } - - return null; } private function getUtf8ByteOffset(string $text, int $charOffset): int diff --git a/tests/Feature/Services/Social/BlueskyPublisherTest.php b/tests/Feature/Services/Social/BlueskyPublisherTest.php index db740e74..8df42b21 100644 --- a/tests/Feature/Services/Social/BlueskyPublisherTest.php +++ b/tests/Feature/Services/Social/BlueskyPublisherTest.php @@ -169,43 +169,6 @@ }); }); -test('bluesky publisher falls back to the public AppView when the PDS cannot resolve', function () { - $this->post->update(['content' => 'Shout out to @friend.bsky.social']); - - $service = config('trypost.platforms.bluesky.default_service'); - $appView = config('trypost.platforms.bluesky.public_appview'); - - Http::fake([ - // The account's PDS fails to resolve; resolution must fall back to the - // public AppView rather than giving up after the first endpoint. - $service.'/xrpc/com.atproto.identity.resolveHandle*' => Http::response(['error' => 'InvalidRequest'], 400), - $appView.'/xrpc/com.atproto.identity.resolveHandle*' => Http::response(['did' => 'did:plc:friend456'], 200), - $service.'/xrpc/com.atproto.repo.createRecord' => Http::response([ - 'uri' => 'at://did:plc:testuser123/app.bsky.feed.post/3abc123xyz', - 'cid' => 'bafyreiabc123', - ], 200), - ]); - - $this->publisher->publish($this->postPlatform); - - Http::assertSent(function ($request) { - $record = $request->data()['record'] ?? null; - - if (! $record) { - return false; - } - - foreach ($record['facets'] ?? [] as $facet) { - $feature = $facet['features'][0]; - if ($feature['$type'] === 'app.bsky.richtext.facet#mention') { - return $feature['did'] === 'did:plc:friend456'; - } - } - - return false; - }); -}); - test('bluesky publisher resolves some mentions and skips the unresolvable ones', function () { $this->post->update(['content' => 'cc @good.bsky.social and @bad.bsky.social']);