Merge pull request #93 from Schrall/fix/bluesky-mention-facet-resolve-did

Fix: resolve Bluesky @mention handles to DIDs (mentions caused "Invalid post data")
This commit is contained in:
Paulo Castellano 2026-06-13 19:57:17 -03:00 committed by GitHub
commit 7baf1b7df5
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 180 additions and 4 deletions

View file

@ -13,6 +13,7 @@
use Illuminate\Http\Client\Response;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use Throwable;
class BlueskyPublisher
{
@ -180,7 +181,7 @@ private function parseFacets(string $text): array
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[] = [
@ -205,10 +206,22 @@ private function parseFacets(string $text): array
PREG_OFFSET_CAPTURE
);
$didCache = [];
foreach ($mentionMatches[0] as $match) {
$mention = $match[0];
$handle = substr($mention, 1); // Remove @
$start = $this->getUtf8ByteOffset($text, $match[1]);
// 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);
}
$did = $didCache[$handle];
if ($did === null) {
continue;
}
$start = $this->getUtf8ByteOffset($text, (int) $match[1]);
$end = $start + strlen($mention);
$facets[] = [
@ -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,
],
],
];
@ -236,7 +249,7 @@ private function parseFacets(string $text): array
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[] = [
@ -256,6 +269,31 @@ private function parseFacets(string $text): array
return $facets;
}
/**
* Resolve a Bluesky handle to its DID via com.atproto.identity.resolveHandle.
*
* 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
{
$appView = (string) config('trypost.platforms.bluesky.public_appview');
try {
$response = $this->socialHttp()->get(
"{$appView}/xrpc/com.atproto.identity.resolveHandle",
['handle' => $handle],
);
$did = $response->successful() ? data_get($response->json(), 'did') : null;
return is_string($did) && str_starts_with($did, 'did:') ? $did : null;
} catch (Throwable) {
return null;
}
}
private function getUtf8ByteOffset(string $text, int $charOffset): int
{
return strlen(substr($text, 0, $charOffset));

View file

@ -101,6 +101,144 @@
});
});
test('bluesky publisher resolves mentions to DIDs as facets', function () {
$this->post->update(['content' => 'Shout out to @friend.bsky.social']);
Http::fake([
// 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),
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);
Http::assertSent(function ($request) {
$record = $request->data()['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),
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),
]);
// 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->data()['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 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 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([