diff --git a/KNOWLEDGE_BASE.md b/KNOWLEDGE_BASE.md index d29acd2c7b..3b1f721063 100644 --- a/KNOWLEDGE_BASE.md +++ b/KNOWLEDGE_BASE.md @@ -294,6 +294,8 @@ Sources: [image picker](resources/js/components/commit-image-picker.tsx), [image ### Links, link cards, and embedded players +Links to commits on this site show the linked commit in a card with its author, text, images, and poll. The card only shows content the viewer may see; unavailable commits show an unavailable placeholder. This is a link preview and does not create a quote or notify the linked author. Linked cards do not expand into further linked cards. + 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. diff --git a/app/Http/Controllers/CommitPreviewController.php b/app/Http/Controllers/CommitPreviewController.php index 816e0b2fd2..1d2d4e39f6 100644 --- a/app/Http/Controllers/CommitPreviewController.php +++ b/app/Http/Controllers/CommitPreviewController.php @@ -5,14 +5,27 @@ namespace App\Http\Controllers; use App\Http\Requests\CreateCommitPreviewRequest; +use App\Http\Requests\ShowCommitPreviewRequest; +use App\Models\Commit; +use App\Models\Profile; +use App\Models\User; +use App\Queries\CommitPreviewQuery; use App\Queries\MentionedOrganizationsQuery; use App\Queries\MentionedUsersQuery; use App\Services\CodeSpans; use App\Services\EmojiShortcodes; +use Illuminate\Container\Attributes\CurrentUser; use Illuminate\Http\JsonResponse; final readonly class CommitPreviewController { + public function show(ShowCommitPreviewRequest $request, #[CurrentUser] ?User $currentUser, Profile $profile, Commit $commit, CommitPreviewQuery $preview): JsonResponse + { + return response()->json([ + 'commit' => $preview->get($commit, $profile, $currentUser), + ])->header('Cache-Control', 'private, no-store'); + } + /** * Highlighting and finding who a mention points to run on the server only, so the composer asks here to preview a * draft with code blocks or mentions. diff --git a/app/Http/Requests/ShowCommitPreviewRequest.php b/app/Http/Requests/ShowCommitPreviewRequest.php new file mode 100644 index 0000000000..4a8428e96b --- /dev/null +++ b/app/Http/Requests/ShowCommitPreviewRequest.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/app/Jobs/UnfurlLink.php b/app/Jobs/UnfurlLink.php index 5ef508274b..26182a6051 100644 --- a/app/Jobs/UnfurlLink.php +++ b/app/Jobs/UnfurlLink.php @@ -6,6 +6,7 @@ use App\Actions\UpdateLinkPreview; use App\Models\LinkPreview; +use App\Services\CommitLinks; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Queue\Queueable; use Illuminate\Queue\Attributes\Backoff; @@ -27,12 +28,18 @@ public function __construct(public readonly LinkPreview $linkPreview) /** * Commits that share a link may each queue this job before the first one runs, so only the first one fetches. */ - public function handle(UpdateLinkPreview $action): void + public function handle(UpdateLinkPreview $action, CommitLinks $commitLinks): void { if ($this->linkPreview->fetched_at !== null) { return; } + if ($commitLinks->previewUrl($this->linkPreview->url) !== null) { + $this->linkPreview->update(['fetched_at' => now()]); + + return; + } + $action->handle($this->linkPreview); } diff --git a/app/Models/LinkPreview.php b/app/Models/LinkPreview.php index cda016627b..a699a237ff 100644 --- a/app/Models/LinkPreview.php +++ b/app/Models/LinkPreview.php @@ -4,6 +4,7 @@ namespace App\Models; +use App\Services\CommitLinks; use App\Services\Embeds; use Carbon\CarbonInterface; use Database\Factories\LinkPreviewFactory; @@ -62,6 +63,10 @@ public function casts(): array */ public function toArray(): array { - return [...parent::toArray(), 'is_pending' => $this->fetched_at === null, 'embed' => resolve(Embeds::class)->for($this->url)?->toArray()]; + $commitPreviewUrl = resolve(CommitLinks::class)->previewUrl($this->url); + + return $commitPreviewUrl === null + ? [...parent::toArray(), 'is_pending' => $this->fetched_at === null, 'embed' => resolve(Embeds::class)->for($this->url)?->toArray()] + : ['url' => $this->url, 'title' => null, 'description' => null, 'image_url' => null, 'site_name' => null, 'is_pending' => false, 'embed' => null, 'commit_preview_url' => $commitPreviewUrl]; } } diff --git a/app/Queries/CommitPreviewQuery.php b/app/Queries/CommitPreviewQuery.php new file mode 100644 index 0000000000..eec0b1b42c --- /dev/null +++ b/app/Queries/CommitPreviewQuery.php @@ -0,0 +1,21 @@ +with(['images', 'linkPreview']) + ->withPollFor($viewer) + ->findOrFail($commit->id) + ->setRelation('author', $author); + } +} diff --git a/app/Services/CommitLinks.php b/app/Services/CommitLinks.php new file mode 100644 index 0000000000..dff613d1ef --- /dev/null +++ b/app/Services/CommitLinks.php @@ -0,0 +1,45 @@ +string('app.url')); + assert($site instanceof Url); + + if (! $parsed instanceof Url + || ! in_array($parsed->getScheme(), ['http', 'https'], true) + || $parsed->getAsciiHost() !== $site->getAsciiHost() + || $parsed->getPort() !== $site->getPort()) { + return null; + } + + $route = $this->router->getRoutes()->getByName('commit.show'); + assert($route instanceof Route); + + if (preg_match($route->toSymfonyRoute()->compile()->getRegex(), mb_rtrim($parsed->getPath(), '/'), $matches) !== 1 + || ! Str::isUuid($matches['commit'])) { + return null; + } + + return route('commit-preview.show', ['profile' => $matches['profile'], 'commit' => $matches['commit']], absolute: false); + } +} diff --git a/resources/js/components/commit-link-preview.tsx b/resources/js/components/commit-link-preview.tsx new file mode 100644 index 0000000000..933039d896 --- /dev/null +++ b/resources/js/components/commit-link-preview.tsx @@ -0,0 +1,67 @@ +import { useEffect, useState } from 'react'; +import { QuotedCommit } from '@/components/quoted-commit'; +import { Skeleton } from '@/components/ui/skeleton'; +import type { QuotedCommit as QuotedCommitData } from '@/types'; + +export function CommitLinkPreview({ + url, + isStatic = false, +}: { + url: string; + isStatic?: boolean; +}) { + const [commit, setCommit] = useState(); + + useEffect(() => { + const controller = new AbortController(); + + void fetch(url, { + headers: { Accept: 'application/json' }, + cache: 'no-store', + signal: controller.signal, + }) + .then(async (response) => { + const data = response.ok + ? ((await response.json()) as { commit: QuotedCommitData }) + : null; + + if (!controller.signal.aborted) { + setCommit(data?.commit ?? null); + } + }) + .catch(() => { + if (!controller.signal.aborted) { + setCommit(null); + } + }); + + return () => controller.abort(); + }, [url]); + + if (commit === undefined) { + return ( +
+
+ + +
+ + +
+ ); + } + + return ( + + ); +} diff --git a/resources/js/components/link-preview.tsx b/resources/js/components/link-preview.tsx index 9729fb50bd..7a28573447 100644 --- a/resources/js/components/link-preview.tsx +++ b/resources/js/components/link-preview.tsx @@ -1,5 +1,6 @@ import { usePage } from '@inertiajs/react'; import { useEffect, useState } from 'react'; +import { CommitLinkPreview } from '@/components/commit-link-preview'; import { LinkEmbed } from '@/components/link-embed'; import { Skeleton } from '@/components/ui/skeleton'; import type { RealtimeChannel } from '@/lib/realtime'; @@ -183,17 +184,32 @@ function LinkPreviewSkeleton() { ); } -export function LinkPreview({ - refreshUrl, - preview: initialPreview, - isStatic = false, - source, -}: { +type LinkPreviewProps = { refreshUrl: string; preview: LinkPreviewData; isStatic?: boolean; source?: LinkPreviewSource; -}) { + suppressLinkedPreview?: boolean; +}; + +export function LinkPreview(props: LinkPreviewProps) { + const url = props.preview.commit_preview_url; + + if (url) { + return props.suppressLinkedPreview ? null : ( + + ); + } + + return ; +} + +function ExternalLinkPreview({ + refreshUrl, + preview: initialPreview, + isStatic = false, + source, +}: LinkPreviewProps) { const { preview, isWaiting } = useFetchedLinkPreview( refreshUrl, initialPreview, diff --git a/resources/js/components/quoted-commit.tsx b/resources/js/components/quoted-commit.tsx index c605e4caa5..63d1699ad8 100644 --- a/resources/js/components/quoted-commit.tsx +++ b/resources/js/components/quoted-commit.tsx @@ -20,10 +20,12 @@ export function QuotedCommit({ commit, isPreview = false, label = 'Quoting', + suppressLinkedPreview = false, }: { commit: QuotedCommitData | DeletedCommit | null; isPreview?: boolean; label?: string; + suppressLinkedPreview?: boolean; }) { const now = useNow(); if (commit === null || isDeleted(commit)) { @@ -81,6 +83,7 @@ export function QuotedCommit({ refreshUrl={CommitLinkPreviewController.show.url(commit.id)} preview={commit.link_preview} isStatic + suppressLinkedPreview={suppressLinkedPreview} source={{ commitId: commit.id }} /> )} diff --git a/resources/js/types/commit.ts b/resources/js/types/commit.ts index 73c8df690e..b588aa3b7d 100644 --- a/resources/js/types/commit.ts +++ b/resources/js/types/commit.ts @@ -15,6 +15,7 @@ export type Embed = { }; export type LinkPreview = { + commit_preview_url?: string | null; url: string; title: string | null; description: string | null; diff --git a/routes/web.php b/routes/web.php index adb6d2c4db..b7231a5d3f 100644 --- a/routes/web.php +++ b/routes/web.php @@ -273,6 +273,11 @@ Route::get('@{profile:handle}/commits/{commit}', [CommitController::class, 'show']) ->scopeBindings() ->name('commit.show'); + Route::get('@{profile:handle}/commits/{commit}/preview', [CommitPreviewController::class, 'show']) + ->withoutMiddleware(RememberIntendedUrl::class) + ->scopeBindings() + ->whereUuid('commit') + ->name('commit-preview.show'); Route::get('@{profile:handle}/commits/{commit}/photos/{photo}', [CommitPhotoController::class, 'show']) ->scopeBindings() ->whereNumber('photo') diff --git a/tests/Feature/Controllers/CommitPreviewControllerTest.php b/tests/Feature/Controllers/CommitPreviewControllerTest.php index a3c28421dd..d6ba483727 100644 --- a/tests/Feature/Controllers/CommitPreviewControllerTest.php +++ b/tests/Feature/Controllers/CommitPreviewControllerTest.php @@ -2,8 +2,94 @@ declare(strict_types=1); +use App\Enums\CommitStatus; +use App\Models\Commit; +use App\Models\CommitImage; +use App\Models\Poll; +use App\Models\PollVote; use App\Models\User; +it('returns a visible commit with the content needed by its quote card', function (): void { + $commit = Commit::factory()->create(['body' => "Hello\n```php\nreturn true;\n```"]); + $image = CommitImage::factory()->for($commit)->create(); + + $this->getJson(route('commit-preview.show', [$commit->author, $commit])) + ->assertOk() + ->assertHeader('Cache-Control', 'no-store, private') + ->assertJsonPath('commit.id', $commit->id) + ->assertJsonPath('commit.author.handle', $commit->author->handle) + ->assertJsonPath('commit.body', $commit->body) + ->assertJsonPath('commit.body_segments.1.type', 'block') + ->assertJsonPath('commit.images.0.id', $image->id) + ->assertJsonMissingPath('commit.embedding') + ->assertJsonMissingPath('commit.quoted_commit'); +}); + +it('does not replace the page a guest returns to after signing in', function (): void { + $commit = Commit::factory()->create(); + $intended = route('user.show', $commit->user); + + $this->withSession(['url.intended' => $intended]) + ->getJson(route('commit-preview.show', [$commit->author, $commit])) + ->assertOk() + ->assertSessionHas('url.intended', $intended); +}); + +it('does not set a sign-in destination when a guest loads preview JSON', function (): void { + $commit = Commit::factory()->create(); + + $this->getJson(route('commit-preview.show', [$commit->author, $commit])) + ->assertOk() + ->assertSessionMissing('url.intended'); +}); + +it('does not expose pending or rejected linked commits to other viewers', function (CommitStatus $status, bool $signedIn): void { + $commit = Commit::factory()->create(['status' => $status]); + + if ($signedIn) { + $this->actingAs(User::factory()->create()); + } + + $this->getJson(route('commit-preview.show', [$commit->author, $commit]))->assertNotFound(); +})->with([CommitStatus::Pending, CommitStatus::Rejected])->with([false, true]); + +it('lets the author preview their own unpublished commit', function (CommitStatus $status): void { + $commit = Commit::factory()->create(['status' => $status]); + + $this->actingAs($commit->user)->getJson(route('commit-preview.show', [$commit->author, $commit])) + ->assertOk()->assertJsonPath('commit.id', $commit->id); +})->with([CommitStatus::Pending, CommitStatus::Rejected]); + +it('hides linked commits across a block in either direction', function (bool $viewerBlocks): void { + $viewer = User::factory()->create(); + $commit = Commit::factory()->create(); + $viewerBlocks ? $viewer->blocking()->attach($commit->user) : $commit->user->blocking()->attach($viewer); + + $this->actingAs($viewer)->getJson(route('commit-preview.show', [$commit->author, $commit]))->assertNotFound(); +})->with([false, true]); + +it('does not resolve deleted commits or a commit under the wrong author', function (): void { + $commit = Commit::factory()->create(); + + $this->getJson(route('commit-preview.show', [User::factory()->create()->profile, $commit]))->assertNotFound(); + $commit->delete(); + $this->getJson(route('commit-preview.show', [$commit->author, $commit]))->assertNotFound(); +}); + +it('shows linked poll results only when the viewer may see them', function (): void { + $viewer = User::factory()->create(); + $poll = Poll::factory()->withOptions('Tabs', 'Spaces')->create(); + $url = route('commit-preview.show', [$poll->commit->author, $poll->commit]); + + $this->getJson($url)->assertOk()->assertJsonPath('commit.poll.total_votes', null); + + PollVote::factory()->for($poll->options->first(), 'option')->for($viewer)->create(); + + $this->actingAs($viewer)->getJson($url)->assertOk() + ->assertJsonPath('commit.poll.total_votes', 1) + ->assertJsonPath('commit.poll.has_voted', true); +}); + it('renders a draft the way the commit it becomes is rendered', function (): void { $user = User::factory()->create(); User::factory()->create(['handle' => 'nunomaduro']); diff --git a/tests/Unit/CommitLinkPreview.test.tsx b/tests/Unit/CommitLinkPreview.test.tsx new file mode 100644 index 0000000000..3ccc13d25f --- /dev/null +++ b/tests/Unit/CommitLinkPreview.test.tsx @@ -0,0 +1,126 @@ +/// +import assert from 'node:assert/strict'; +import * as React from 'react'; +import type { ReactElement } from 'react'; +import { afterEach, test, vi } from 'vite-plus/test'; +import type { QuotedCommit as QuotedCommitData } from '../../resources/js/types'; + +let value: QuotedCommitData | null | undefined; +let effect: (() => () => void) | undefined; +let cleanup: (() => void) | undefined; + +vi.doMock('react', () => ({ + ...React, + useEffect: (callback: () => () => void) => { + effect = callback; + }, + useState: () => [value, (next: typeof value) => (value = next)], +})); + +const { CommitLinkPreview } = + await import('../../resources/js/components/commit-link-preview'); +const { LinkPreview } = + await import('../../resources/js/components/link-preview'); +const url = '/@author/commits/123e4567-e89b-12d3-a456-426614174000/preview'; + +afterEach(() => { + cleanup?.(); + cleanup = undefined; + effect = undefined; + value = undefined; + vi.unstubAllGlobals(); +}); + +function mount(): void { + CommitLinkPreview({ url }); + cleanup = effect?.(); +} + +test('fetches current commit data once instead of polling cached link metadata', async () => { + const commit = { id: 'linked' } as QuotedCommitData; + const fetch = vi + .fn() + .mockResolvedValue(new Response(JSON.stringify({ commit }))); + vi.stubGlobal('fetch', fetch); + mount(); + + await vi.waitFor(() => assert.deepEqual(value, commit)); + + const rendered = CommitLinkPreview({ url }) as ReactElement<{ + commit: QuotedCommitData; + label: string; + isPreview: boolean; + suppressLinkedPreview: boolean; + }>; + assert.deepEqual(rendered.props.commit, commit); + assert.equal(rendered.props.label, 'Linked commit'); + assert.equal(rendered.props.isPreview, false); + assert.equal(rendered.props.suppressLinkedPreview, true); + const staticCard = CommitLinkPreview({ url, isStatic: true }) as ReactElement<{ + isPreview: boolean; + }>; + assert.equal(staticCard.props.isPreview, true); + assert.equal(fetch.mock.calls.length, 1); + assert.equal(fetch.mock.calls[0][0], url); + assert.equal(fetch.mock.calls[0][1]?.cache, 'no-store'); +}); + +test('shows unavailable when the viewer cannot read the linked commit', async () => { + vi.stubGlobal( + 'fetch', + vi.fn().mockResolvedValue(new Response(null, { status: 404 })), + ); + mount(); + + await vi.waitFor(() => assert.equal(value, null)); +}); + +test('handles a failed request without showing old preview content', async () => { + vi.stubGlobal('fetch', vi.fn().mockRejectedValue(new Error('Offline'))); + mount(); + + await vi.waitFor(() => assert.equal(value, null)); +}); + +test('cancels the request when navigation removes the preview', async () => { + let finish: ((response: Response) => void) | undefined; + const fetch = vi + .fn() + .mockImplementation(() => new Promise((resolve) => (finish = resolve))); + vi.stubGlobal('fetch', fetch); + mount(); + cleanup?.(); + finish?.(new Response(JSON.stringify({ commit: { id: 'old-page' } }))); + await new Promise((resolve) => setTimeout(resolve, 0)); + + assert.equal(fetch.mock.calls[0][1]?.signal?.aborted, true); + assert.equal(value, undefined); +}); + +test('uses the actual commit preview and stops at one nesting level', () => { + const props = { + refreshUrl: '/unused-link-metadata', + preview: { + url: 'https://dev-null.sh/@author/commits/123e4567-e89b-12d3-a456-426614174000', + title: 'Old cached content', + description: null, + image_url: null, + site_name: null, + is_pending: true, + commit_preview_url: url, + }, + }; + + const rendered = LinkPreview(props) as ReactElement<{ url: string }>; + + assert.equal(rendered.type, CommitLinkPreview); + assert.equal(rendered.props.url, url); + + // Static quotes keep the first linked card, but must not nest an interactive link. + const staticCard = LinkPreview({ ...props, isStatic: true }) as ReactElement<{ + isStatic: boolean; + }>; + assert.equal(staticCard.type, CommitLinkPreview); + assert.equal(staticCard.props.isStatic, true); + assert.equal(LinkPreview({ ...props, suppressLinkedPreview: true }), null); +}); diff --git a/tests/Unit/Jobs/UnfurlLinkTest.php b/tests/Unit/Jobs/UnfurlLinkTest.php index 194755436e..7f2611b309 100644 --- a/tests/Unit/Jobs/UnfurlLinkTest.php +++ b/tests/Unit/Jobs/UnfurlLinkTest.php @@ -38,6 +38,19 @@ function runNextQueuedJob(): void expect($linkPreview->refresh()->title)->toBe('Fetched before'); }); +it('does not fetch metadata for links to this sites commits', function (): void { + config(['app.url' => 'https://dev-null.sh']); + Http::fake(); + $preview = LinkPreview::factory()->create([ + 'url' => 'https://dev-null.sh/@author/commits/123e4567-e89b-12d3-a456-426614174000', + ]); + + dispatch_sync(new UnfurlLink($preview)); + + Http::assertNothingSent(); + expect($preview->refresh()->fetched_at)->not->toBeNull(); +}); + it('retries a page that may be reachable later', function (): void { Exceptions::fake(); diff --git a/tests/Unit/Models/LinkPreviewTest.php b/tests/Unit/Models/LinkPreviewTest.php index 83447671b6..92a18353e7 100644 --- a/tests/Unit/Models/LinkPreviewTest.php +++ b/tests/Unit/Models/LinkPreviewTest.php @@ -21,6 +21,26 @@ ]); }); +it('replaces cached metadata of an internal commit with its private preview endpoint', function (): void { + config(['app.url' => 'https://dev-null.sh']); + $preview = LinkPreview::factory()->fetched()->create([ + 'url' => 'https://dev-null.sh/@author/commits/123e4567-e89b-12d3-a456-426614174000', + 'title' => 'Previously public words', + 'description' => 'Cached content must not bypass visibility checks.', + 'image_url' => 'https://dev-null.sh/old-image.png', + ]); + + expect($preview->toArray())->toMatchArray([ + 'title' => null, + 'description' => null, + 'image_url' => null, + 'site_name' => null, + 'is_pending' => false, + 'embed' => null, + 'commit_preview_url' => '/@author/commits/123e4567-e89b-12d3-a456-426614174000/preview', + ]); +}); + it('is pending until it is fetched', function (): void { expect(LinkPreview::factory()->create()->toArray()['is_pending'])->toBeTrue() ->and(LinkPreview::factory()->fetched()->create()->toArray()['is_pending'])->toBeFalse() diff --git a/tests/Unit/QuotedCommit.test.tsx b/tests/Unit/QuotedCommit.test.tsx index a790caf257..2547712a70 100644 --- a/tests/Unit/QuotedCommit.test.tsx +++ b/tests/Unit/QuotedCommit.test.tsx @@ -3,7 +3,7 @@ import assert from 'node:assert/strict'; import { createInertiaApp } from '@inertiajs/react'; import { renderToString } from 'react-dom/server'; -import { test } from 'vite-plus/test'; +import { test, vi } from 'vite-plus/test'; import { QuotedCommit } from '../../resources/js/components/quoted-commit'; import type { LinkPreview, @@ -29,6 +29,23 @@ const commit = { author: { id: 'author', name: 'Matthieu Napoli', handle: 'mnapoli' }, } as QuotedCommitData; +// The fetch lifecycle is covered in CommitLinkPreview.test.tsx. Here the linked +// commit is already loaded, so we can test its actual markup inside a quote. +let resolvedLinkedCommit: QuotedCommitData | null = null; + +vi.mock('../../resources/js/components/commit-link-preview', () => ({ + CommitLinkPreview: ({ isStatic }: { isStatic?: boolean }) => + resolvedLinkedCommit ? ( + + ) : ( +
+ ), +})); + const poll = { id: 'poll', closes_at: '2099-01-01T00:00:00.000000Z', @@ -132,6 +149,38 @@ test('shows the images, link card and embed of a quoted commit inside the single } }); + +test('shows the resolved linked card inside an ordinary quote without nested links', async () => { + const preview: LinkPreview = { + url: 'https://dev-null.sh/@author/commits/123e4567-e89b-12d3-a456-426614174000', + title: null, + description: null, + image_url: null, + site_name: null, + is_pending: false, + commit_preview_url: '/@author/commits/123e4567-e89b-12d3-a456-426614174000/preview', + }; + + resolvedLinkedCommit = { + ...commit, + id: 'linked', + body_segments: [{ type: 'text', text: 'Resolved linked commit' }], + preview_segments: null, + link_preview: preview, + }; + + try { + const body = await render(false, { ...commit, link_preview: preview }); + + assert.match(body, /Resolved linked commit/); + assert.equal(body.match(/data-test="quoted-commit"/g)?.length, 2); + assert.equal(body.match(/ { const body = await render(false, { ...commit, diff --git a/tests/Unit/Services/CommitLinksTest.php b/tests/Unit/Services/CommitLinksTest.php new file mode 100644 index 0000000000..9bb592c7b1 --- /dev/null +++ b/tests/Unit/Services/CommitLinksTest.php @@ -0,0 +1,28 @@ + 'https://dev-null.sh']); + $id = '123e4567-e89b-12d3-a456-426614174000'; + + expect(resolve(CommitLinks::class)->previewUrl("https://dev-null.sh/@author/commits/{$id}{$suffix}")) + ->toBe(route('commit-preview.show', ['profile' => 'author', 'commit' => $id], absolute: false)); +})->with(['', '?from=log#reply', '/']); + +it('does not resolve other sites or routes as commit previews', function (string $url): void { + config(['app.url' => 'https://dev-null.sh']); + + expect(resolve(CommitLinks::class)->previewUrl($url))->toBeNull(); +})->with([ + 'invalid url' => 'not a url', + 'other scheme' => 'ftp://dev-null.sh/@author/commits/123e4567-e89b-12d3-a456-426614174000', + 'other host' => 'https://example.com/@author/commits/123e4567-e89b-12d3-a456-426614174000', + 'lookalike host' => 'https://dev-null.sh.example.com/@author/commits/123e4567-e89b-12d3-a456-426614174000', + 'other port' => 'https://dev-null.sh:8443/@author/commits/123e4567-e89b-12d3-a456-426614174000', + 'profile' => 'https://dev-null.sh/@author', + 'invalid id' => 'https://dev-null.sh/@author/commits/not-a-uuid', + 'photo' => 'https://dev-null.sh/@author/commits/123e4567-e89b-12d3-a456-426614174000/photos/1', +]);