diff --git a/KNOWLEDGE_BASE.md b/KNOWLEDGE_BASE.md index 6965f9e74..9c86b92f7 100644 --- a/KNOWLEDGE_BASE.md +++ b/KNOWLEDGE_BASE.md @@ -299,7 +299,7 @@ Sources: [image picker](resources/js/components/commit-image-picker.tsx), [image Each link in a commit or reply counts as at most **23 characters** toward the 4,000-character allowance; shorter links count at their actual length. This also applies to quotes, scheduled commits, previews, and terminal and app submissions. The full URL is stored and followed directly, not through a redirect service. Prose URLs longer than **2,048 characters** are rejected, including the inferred `https://` scheme for bare domains. Code still counts literally toward the 4,000-character allowance. Bodies are additionally capped at 40,000 raw characters to bound storage and processing. Private messages and issue drafts keep their existing literal character limits. -URLs and bare domains in commits and replies become clickable links. Long URLs are shortened visually; hover reveals the full destination. GitHub repository links show as `owner/repo`, and issue or pull request links as `owner/repo#123`, with the GitHub mark. Links to /dev/null commits show as the author's username and a short hash. Code keeps its literal text. The first link normally gets a preview card with available title, description, and image. In the commit, reply, and quote composers, choose another link from the body or choose no card; terminal commits and app commits always use the first link. Missing site metadata may leave a link without a rich preview. Different ways of writing the same link share one card: the host's case, a default port, a lone trailing `/`, the highlight a browser adds to a link (`#:~:text=`), and tracking parameters such as `utm_*`, `fbclid` or YouTube's `si` don't make a new one, and a few sites share one card across their addresses, so `youtube.com/watch?v=…` and `youtu.be/…` show the same card, as do `twitter.com` and `x.com`. Any other `#fragment` stays part of the link, so a link to a news entry, a line of code or a comment keeps a card of its own. The card links to that shared address, while the commit keeps the link exactly as written. +URLs and bare domains in commits and replies become clickable links. Long URLs are shortened visually; hover reveals the full destination. GitHub repository links show as `owner/repo`, and issue or pull request links as `owner/repo#123`, with the GitHub mark. Links to /dev/null commits show as the author's username and a short hash. Code keeps its literal text. The first link normally gets a preview card with available title, description, and image. In the commit, reply, and quote composers, and in apps, choose another link from the body or choose no card; terminal commits always use the first link. Missing site metadata may leave a link without a rich preview. Different ways of writing the same link share one card: the host's case, a default port, a lone trailing `/`, the highlight a browser adds to a link (`#:~:text=`), and tracking parameters such as `utm_*`, `fbclid` or YouTube's `si` don't make a new one, and a few sites share one card across their addresses, so `youtube.com/watch?v=…` and `youtu.be/…` show the same card, as do `twitter.com` and `x.com`. Any other `#fragment` stays part of the link, so a link to a news entry, a line of code or a comment keeps a card of its own. The card links to that shared address, while the commit keeps the link exactly as written. Supported links can also show click-to-play embedded players: YouTube, Vimeo, Loom, Twitch, Spotify, SoundCloud, Apple Music, Suno, CodePen, and asciinema. Only the link that gets the card can show a player, so choosing no card means no player. Embeds depend on server configuration and the linked URL being supported. Third-party player content loads only after you press play; those providers have their own privacy policies. This is embedding a link, not uploading a video or audio file to /dev/null. @@ -589,7 +589,7 @@ A signed request sees what the web shows you, such as your own pending commits a - read your account, logs, replies, notifications (including grouped activity), and starred commits; - read the organizations you are a member of, your role in each, and whether posting as an organization is switched on; - open the person or organization a mention in a commit or message captured, by the id each mention carries, as the web's mention links do, so it still leads to them after they rename and someone else takes the handle; -- commit, reply, and quote, with images, and delete your commits, with the same undo window as the web; +- commit, reply, and quote, with images and the link card of your choice, read a commit's link card again while it loads, and delete your commits, with the same undo window as the web; - preview commit drafts without publishing them; - request a feature or report a bug as `/feature` and `/bug` do, with the same limit of 10 opened issues a day; - follow or unfollow people and organizations, mute or unmute, and block or unblock, and list who you muted and blocked; @@ -625,7 +625,7 @@ A signed request sees what the web shows you, such as your own pending commits a Signed lists show each commit with its newest reply or quote. Add `?replies_per_page=` with 3, 5, 10, 15, 20, or 25 to show that many replies and quotes, like the replies choice in Settings → Appearance. -Signed request bodies are JSON, or multipart when they carry images or a voice note, so app commits can have images with descriptions or a poll but no link-card choice. Before your first app submission, accept the [commit rules](#moderation) through the web composer. Signed requests are limited to **120 requests per minute per user**. Each action's per-minute limit (pastéis, opening issues, and so on) counts on its own, shared between the web and the API. Settings → Devices lists your approved devices, with the app's name when it gave one and when each was last used, and revokes them. +Signed request bodies are JSON, or multipart when they carry images or a voice note, so app commits can have images with descriptions, a poll, or a chosen link card. Before your first app submission, accept the [commit rules](#moderation) through the web composer. Signed requests are limited to **120 requests per minute per user**. Each action's per-minute limit (pastéis, opening issues, and so on) counts on its own, shared between the web and the API. Settings → Devices lists your approved devices, with the app's name when it gave one and when each was last used, and revokes them. Sources: [signed requests](app/Services/SignedRequests.php), [sign-in page](app/Http/Controllers/MobileAuthorizationController.php), [devices settings](resources/js/pages/device/index.tsx), [API routes](routes/api.php). diff --git a/app/Http/Controllers/Api/CommitController.php b/app/Http/Controllers/Api/CommitController.php index e4b7b4dbb..fde49ee91 100644 --- a/app/Http/Controllers/Api/CommitController.php +++ b/app/Http/Controllers/Api/CommitController.php @@ -54,7 +54,7 @@ public function show(ShowApiCommitRequest $request, #[CurrentUser] ?User $curren public function store(CreateApiCommitRequest $request, #[CurrentUser] User $user, CreateCommit $action, CommitPageQuery $page): JsonResponse { try { - $commit = $action->handle($user, $request->string('body')->value(), $request->parent(), $request->quotedCommit(), $request->images(), $request->imageDescriptions(), poll: $request->poll(), replyRecipients: $request->replyRecipients(), organization: $request->organization(), guild: $request->guild()); + $commit = $action->handle($user, $request->string('body')->value(), $request->parent(), $request->quotedCommit(), $request->images(), $request->imageDescriptions(), linkPreview: $request->linkPreview(), poll: $request->poll(), replyRecipients: $request->replyRecipients(), organization: $request->organization(), guild: $request->guild()); } catch (GuildPaused) { return ApiException::guildPaused()->render(); } diff --git a/app/Http/Controllers/Api/CommitLinkPreviewController.php b/app/Http/Controllers/Api/CommitLinkPreviewController.php new file mode 100644 index 000000000..53f560326 --- /dev/null +++ b/app/Http/Controllers/Api/CommitLinkPreviewController.php @@ -0,0 +1,22 @@ +json([ + 'link_preview' => $commit->linkPreview, + ])->header('Cache-Control', 'private, no-store'); + } +} diff --git a/app/Http/Requests/CreateApiCommitRequest.php b/app/Http/Requests/CreateApiCommitRequest.php index e719f45fa..4f0ea8e60 100644 --- a/app/Http/Requests/CreateApiCommitRequest.php +++ b/app/Http/Requests/CreateApiCommitRequest.php @@ -13,6 +13,7 @@ use App\Queries\MentionedUsersQuery; use App\Rules\OrganizationToPostAs; use App\Rules\VisibleCommit; +use App\Services\Urls; use Illuminate\Contracts\Validation\ValidationRule; use Illuminate\Foundation\Http\FormRequest; use Illuminate\Http\UploadedFile; @@ -52,6 +53,7 @@ public function rules(): array { $user = $this->user(); assert($user instanceof User); + $body = $this->input('body'); $attachmentRules = CreateCommitRequest::attachmentRules(); return [ @@ -61,6 +63,7 @@ public function rules(): array 'reply_recipients' => ['sometimes', 'list', 'max:'.CreateCommitReplyRequest::MAX_REPLY_RECIPIENTS], 'reply_recipients.*' => ['required', 'string', 'distinct', Rule::in(array_values($this->parentMentions()))], 'quoted_commit_id' => ['bail', 'nullable', 'uuid', 'prohibits:parent_id', new VisibleCommit($user, __('That commit is no longer available to quote.'))], + 'link_preview_url' => ['nullable', 'string', Rule::in(is_string($body) ? resolve(Urls::class)->all($body) : [])], 'poll' => [...$attachmentRules['poll'], 'prohibits:quoted_commit_id'], 'poll.options' => $attachmentRules['poll.options'], 'poll.options.*' => $attachmentRules['poll.options.*'], @@ -104,6 +107,28 @@ public function attributes(): array ]; } + /** + * @return array + */ + public function messages(): array + { + return [ + 'link_preview_url.in' => 'The link card must be one of the links in the body.', + ]; + } + + /** + * The first link in the body gets the link card, unless the user chose another link or none at all. + */ + public function linkPreview(): bool|string + { + if (! $this->has('link_preview_url')) { + return true; + } + + return $this->filled('link_preview_url') ? $this->string('link_preview_url')->value() : false; + } + /** * A parent that went away since it was validated is a 404, so a reply never turns into a top-level commit. */ diff --git a/app/Http/Requests/ShowApiCommitLinkPreviewRequest.php b/app/Http/Requests/ShowApiCommitLinkPreviewRequest.php new file mode 100644 index 000000000..367fa4ce8 --- /dev/null +++ b/app/Http/Requests/ShowApiCommitLinkPreviewRequest.php @@ -0,0 +1,28 @@ +route('commit'); + assert($commit instanceof Commit); + + return $commit->isVisibleTo($this->user()) ? Response::allow() : Response::denyAsNotFound(); + } + + /** + * @return array{} + */ + public function rules(): array + { + return []; + } +} diff --git a/routes/api.php b/routes/api.php index ee64eceef..ccd2ef09e 100644 --- a/routes/api.php +++ b/routes/api.php @@ -6,6 +6,7 @@ use App\Http\Controllers\Api\BroadcastAuthorizationController; use App\Http\Controllers\Api\CallController; use App\Http\Controllers\Api\CommitController as ApiCommitController; +use App\Http\Controllers\Api\CommitLinkPreviewController; use App\Http\Controllers\Api\CommitPastelController; use App\Http\Controllers\Api\CommitPinController; use App\Http\Controllers\Api\CommitPollVoteController; @@ -132,6 +133,8 @@ ->name('api-user-commit.index'); Route::get('commits/{commit}', [ApiCommitController::class, 'show']) ->name('api-commit.show'); + Route::get('commits/{commit}/link-preview', [CommitLinkPreviewController::class, 'show']) + ->name('api-commit-link-preview.show'); Route::get('commits/{commit}/related', [RelatedCommitController::class, 'index']) ->name('api-related-commit.index'); Route::get('organizations/{handle}', [OrganizationController::class, 'show']) diff --git a/tests/Feature/Controllers/Api/CommitControllerTest.php b/tests/Feature/Controllers/Api/CommitControllerTest.php index 2d0348dda..eb6c4eb80 100644 --- a/tests/Feature/Controllers/Api/CommitControllerTest.php +++ b/tests/Feature/Controllers/Api/CommitControllerTest.php @@ -9,6 +9,7 @@ use App\Http\Requests\CreateApiCommitRequest; use App\Http\Requests\CreateCommitReplyRequest; use App\Jobs\ModerateCommit; +use App\Jobs\UnfurlLink; use App\Models\Commit; use App\Models\CommitImage; use App\Models\Guild; @@ -669,6 +670,7 @@ 'unknown parent' => [fn (): array => ['body' => 'It was DNS.', 'parent_id' => '0199e3a4-0000-7000-8000-000000000000'], 'parent_id', 'That commit is no longer available to reply to.'], 'hidden parent' => [fn (): array => ['body' => 'It was DNS.', 'parent_id' => Commit::factory()->pending()->create()->id], 'parent_id', 'That commit is no longer available to reply to.'], 'deleted parent' => [fn (): array => ['body' => 'It was DNS.', 'parent_id' => tap(Commit::factory()->create())->delete()->id], 'parent_id', 'That commit is no longer available to reply to.'], + 'a link card for a link not in the body' => [fn (): array => ['body' => 'Read https://example.com/first', 'link_preview_url' => 'https://example.com/other'], 'link_preview_url', 'The link card must be one of the links in the body.'], ]); it('may not reply to a commit across a block, as on the web', function (): void { @@ -1125,3 +1127,32 @@ expect(Commit::query()->where('body', 'Board post')->exists())->toBeFalse(); }); + +it('keeps the first link as the link card of a commit, reply or quote, unless the user chose another or none', function (Closure $target, array $choice, ?string $expected): void { + Queue::fake([UnfurlLink::class]); + $user = User::factory()->create(); + + signedApiRequest(apiKeyPairFor($user), 'POST', route('api-commit.store'), [ + 'body' => 'Shipped https://example.com/first and https://example.com/second', + ...$target(), + ...$choice, + ])->assertCreated(); + + $commit = $user->commits()->sole(); + + expect($commit->linkPreview?->url)->toBe($expected); + + if ($expected === null) { + Queue::assertNotPushed(UnfurlLink::class); + } else { + Queue::assertPushed(UnfurlLink::class, fn (UnfurlLink $job): bool => $job->linkPreview->is($commit->linkPreview)); + } +})->with([ + 'a commit' => fn (): array => [], + 'a reply' => fn (): array => ['parent_id' => Commit::factory()->create()->id], + 'a quote' => fn (): array => ['quoted_commit_id' => Commit::factory()->create()->id], +])->with([ + 'the first link' => [[], 'https://example.com/first'], + 'another link' => [['link_preview_url' => 'https://example.com/second'], 'https://example.com/second'], + 'no card' => [['link_preview_url' => null], null], +]); diff --git a/tests/Feature/Controllers/Api/CommitLinkPreviewControllerTest.php b/tests/Feature/Controllers/Api/CommitLinkPreviewControllerTest.php new file mode 100644 index 000000000..16356fd2a --- /dev/null +++ b/tests/Feature/Controllers/Api/CommitLinkPreviewControllerTest.php @@ -0,0 +1,61 @@ +user = User::factory()->create(); + $this->keyPair = apiKeyPairFor($this->user); +}); + +it('returns the link card of a commit while it is pending and once it is fetched', function (): void { + $linkPreview = LinkPreview::factory()->create(['url' => 'https://laravel.com']); + $commit = Commit::factory()->for($linkPreview)->create(); + $url = route('api-commit-link-preview.show', $commit); + + signedApiRequest($this->keyPair, 'GET', $url) + ->assertOk() + ->assertHeader('Cache-Control', 'no-store, private') + ->assertJsonPath('link_preview.url', 'https://laravel.com') + ->assertJsonPath('link_preview.title', null) + ->assertJsonPath('link_preview.is_pending', true); + + $linkPreview->update(['title' => 'Laravel', 'site_name' => 'Laravel', 'fetched_at' => now()]); + + signedApiRequest($this->keyPair, 'GET', $url) + ->assertOk() + ->assertJsonPath('link_preview.title', 'Laravel') + ->assertJsonPath('link_preview.is_pending', false); +}); + +it('returns no link card for a commit without one', function (): void { + signedApiRequest($this->keyPair, 'GET', route('api-commit-link-preview.show', Commit::factory()->create())) + ->assertOk() + ->assertExactJson(['link_preview' => null]); +}); + +it('returns the link card of the users own pending commit', function (): void { + $commit = Commit::factory()->for($this->user)->for(LinkPreview::factory())->pending()->create(); + + signedApiRequest($this->keyPair, 'GET', route('api-commit-link-preview.show', $commit)) + ->assertOk() + ->assertJsonPath('link_preview.is_pending', true); +}); + +it('returns not found for a commit the user may not see', function (bool $signed): void { + $commit = Commit::factory()->for(LinkPreview::factory()->fetched())->pending()->create(); + $url = route('api-commit-link-preview.show', $commit); + + ($signed ? signedApiRequest($this->keyPair, 'GET', $url) : $this->getJson($url))->assertNotFound(); +})->with(['signed' => true, 'guest' => false]); + +it('returns the link card of a public commit to guests, as the web does', function (): void { + $commit = Commit::factory()->for(LinkPreview::factory()->fetched()->create(['url' => 'https://laravel.com']))->create(); + + $this->getJson(route('api-commit-link-preview.show', $commit)) + ->assertOk() + ->assertJsonPath('link_preview.url', 'https://laravel.com'); +});