keep comments concise

This commit is contained in:
Michael Black
2026-05-26 16:10:36 -05:00
parent 20bbceeee9
commit e9384aa8fe
7 changed files with 94 additions and 167 deletions
+7 -12
View File
@@ -4,15 +4,12 @@ import (
appbsky "github.com/bluesky-social/indigo/api/bsky"
)
// Helpers for extracting Open Graph / Twitter Card metadata from post
// embeds. These produce data for og:* and twitter:* meta tags only they
// are not used by the schema.org JSON-LD output (which lives in jsonld.go).
//
// The og:video tags exist as a separate code path because JSON-LD does not
// currently emit a VideoObject (deferred — requires `duration` from the
// appview that is not exposed today).
// Helpers for extracting Open Graph metadata from post embeds. These feed
// og:* / twitter:* meta tags only; the schema.org JSON-LD output lives in
// jsonld.go. og:video has its own path because JSON-LD does not yet emit
// VideoObject (deferred — needs `duration` from the appview).
// videoMeta is the metadata needed for og:video meta tags.
// videoMeta holds og:video meta tag data.
type videoMeta struct {
URL string
Type string
@@ -21,10 +18,8 @@ type videoMeta struct {
HasSize bool
}
// extractVideoMeta returns og:video metadata for the post if it has a video
// embed, otherwise the zero value. Respects the same embedHidden gate as
// extractPostMedia (in jsonld.go) so og:video and og:image suppression stay
// in sync.
// extractVideoMeta returns og:video metadata, or the zero value if there's
// no video embed. Respects embedHidden so og:video and og:image stay in sync.
func extractVideoMeta(pv *appbsky.FeedDefs_PostView, embedHidden bool) videoMeta {
if pv == nil || pv.Embed == nil || embedHidden {
return videoMeta{}
+40 -65
View File
@@ -56,7 +56,7 @@ type discussionForumPosting struct {
SharedContent *sharedContent `json:"sharedContent,omitempty"`
}
// comment is the schema.org Comment shape used inside
// comment is the schema.org Comment shape used in
// DiscussionForumPosting.comment[]. The comment property does not accept
// DiscussionForumPosting, so replies map to Comment.
type comment struct {
@@ -85,24 +85,18 @@ type profilePage struct {
HasPart []discussionForumPosting `json:"hasPart,omitempty"`
}
// maxComments is the maximum number of top-level replies emitted in
// DiscussionForumPosting.comment[]. Bounded to keep SSR HTML payload small.
// maxComments caps DiscussionForumPosting.comment[] to keep SSR HTML small.
const maxComments = 10
// maxRecentPosts is the maximum number of recent posts emitted on a profile
// page in ProfilePage.hasPart[].
// maxRecentPosts caps ProfilePage.hasPart[].
const maxRecentPosts = 10
// authorFeedFetchLimit is how many entries to request from getAuthorFeed
// when populating ProfilePage.hasPart. We oversample because the
// posts_no_replies filter still returns reposts (which we drop client-side
// — only the author's own posts go in hasPart). A 3x oversample is a safe
// margin even for profiles that repost frequently.
// authorFeedFetchLimit oversamples getAuthorFeed because posts_no_replies
// still returns reposts; we drop those client-side. 3x is a safe margin.
const authorFeedFetchLimit = 3 * maxRecentPosts
// bskyPostURL returns the canonical handle-form URL for a post, given the
// post's author handle and record key. Returns "" if the handle is unusable
// (empty or handle.invalid) or rkey is empty.
// bskyPostURL returns the canonical handle-form post URL, or "" if handle
// or rkey is unusable.
func bskyPostURL(handle, rkey string) string {
if handle == "" || handle == "handle.invalid" || rkey == "" {
return ""
@@ -110,9 +104,7 @@ func bskyPostURL(handle, rkey string) string {
return fmt.Sprintf("https://bsky.app/profile/%s/post/%s", handle, rkey)
}
// bskyPostURLFromATURI is a convenience wrapper for callers that hold an
// at-uri rather than a record key directly. Returns "" if the URI cannot be
// parsed.
// bskyPostURLFromATURI is bskyPostURL for callers holding an at-uri.
func bskyPostURLFromATURI(handle, atURI string) string {
parsed, err := syntax.ParseATURI(atURI)
if err != nil {
@@ -121,8 +113,8 @@ func bskyPostURLFromATURI(handle, atURI string) string {
return bskyPostURL(handle, parsed.RecordKey().String())
}
// bskyProfileURL returns the canonical handle-form URL for a profile.
// Returns "" if the handle is unusable.
// bskyProfileURL returns the canonical handle-form profile URL, or "" if
// the handle is unusable.
func bskyProfileURL(handle string) string {
if handle == "" || handle == "handle.invalid" {
return ""
@@ -130,10 +122,9 @@ func bskyProfileURL(handle string) string {
return fmt.Sprintf("https://bsky.app/profile/%s", handle)
}
// extractPostMedia returns the image thumbnail URLs for the post (if any).
// All URLs are reused verbatim from the appview response — the same strings
// that go into og:image meta tags — so Google sees byte-identical media
// references. Callers derive thumbnailUrl from urls[0].
// extractPostMedia returns thumbnail URLs for the post's image or video
// embed, byte-identical to what we put in og:image. Callers derive
// thumbnailUrl from urls[0].
func extractPostMedia(pv *appbsky.FeedDefs_PostView, embedHidden bool) []string {
if pv == nil || pv.Embed == nil || embedHidden {
return nil
@@ -157,8 +148,7 @@ func extractPostMedia(pv *appbsky.FeedDefs_PostView, embedHidden bool) []string
return nil
}
// imageThumbs returns the thumb URLs for a slice of image embed views, or
// nil if the slice is empty.
// imageThumbs returns the thumb URLs, or nil if empty.
func imageThumbs(images []*appbsky.EmbedImages_ViewImage) []string {
if len(images) == 0 {
return nil
@@ -170,9 +160,8 @@ func imageThumbs(images []*appbsky.EmbedImages_ViewImage) []string {
return urls
}
// extractQuotedPostURL returns the canonical handle-form URL of a quoted
// post, if the embed is a viewable record (not blocked / detached / not
// found / non-post record like a feed generator or list).
// extractQuotedPostURL returns the canonical URL of a quoted post, or ""
// if the embed is blocked / not-found / detached / a non-post record.
func extractQuotedPostURL(pv *appbsky.FeedDefs_PostView) string {
if pv == nil || pv.Embed == nil {
return ""
@@ -188,14 +177,13 @@ func extractQuotedPostURL(pv *appbsky.FeedDefs_PostView) string {
}
vr := rec.Record.EmbedRecord_ViewRecord
if vr == nil || vr.Author == nil {
// Skip _ViewBlocked, _ViewNotFound, _ViewDetached, and non-post records.
return ""
}
return bskyPostURLFromATURI(vr.Author.Handle, vr.Uri)
}
// extractSharedContentURL returns the URL of an external link embedded in
// the post (or in the media slot of a record-with-media embed).
// extractSharedContentURL returns the URL of an external link embed (also
// from the media slot of a record-with-media embed).
func extractSharedContentURL(pv *appbsky.FeedDefs_PostView) string {
if pv == nil || pv.Embed == nil {
return ""
@@ -212,9 +200,8 @@ func extractSharedContentURL(pv *appbsky.FeedDefs_PostView) string {
return ""
}
// buildAuthor constructs a Person object. Organization classification for
// custom-domain or organization-style accounts is a future enhancement; for
// now, every author is emitted as Person.
// buildAuthor constructs a Person. Organization classification for
// custom-domain accounts is a future enhancement.
func buildAuthor(author *appbsky.ActorDefs_ProfileViewBasic) *personOrOrg {
if author == nil {
return nil
@@ -236,9 +223,9 @@ func buildAuthor(author *appbsky.ActorDefs_ProfileViewBasic) *personOrOrg {
return p
}
// postEmbedHidden checks self-labels and post-view labels for any label that
// causes embeds to be omitted. Mirrors logic in WebPost handler so the
// JSON-LD shape stays consistent with og:image emission.
// postEmbedHidden reports whether any post-view label or self-label asks
// embeds to be omitted. WebPost uses this so og:image and JSON-LD media
// suppression stay in sync.
func postEmbedHidden(pv *appbsky.FeedDefs_PostView, hideLabels map[string]bool) bool {
if pv == nil {
return false
@@ -263,8 +250,8 @@ func postEmbedHidden(pv *appbsky.FeedDefs_PostView, hideLabels map[string]bool)
return false
}
// postRecordText returns the expanded post text (with shortened links
// expanded back to full URLs) or "" if the record is missing or malformed.
// postRecordText returns the post's expanded text, or "" if the record is
// missing or malformed.
func postRecordText(pv *appbsky.FeedDefs_PostView) string {
if pv == nil || pv.Record == nil {
return ""
@@ -276,10 +263,8 @@ func postRecordText(pv *appbsky.FeedDefs_PostView) string {
return ExpandPostText(rec)
}
// buildPostStats returns the standard like/comment/share interaction stat
// triple. CommentAction count uses ReplyCount to match what Google expects
// in InteractionCounter; commentCount is emitted separately on
// DiscussionForumPosting.
// buildPostStats returns the like / comment / share interaction triple.
// commentCount is emitted separately on DiscussionForumPosting.
func buildPostStats(pv *appbsky.FeedDefs_PostView) []interactionStat {
if pv == nil {
return nil
@@ -297,10 +282,10 @@ func buildPostStats(pv *appbsky.FeedDefs_PostView) []interactionStat {
}
}
// buildPostNode constructs a DiscussionForumPosting (in nested form, no
// @context, no envelope). Used both for top-level posts and for entries in
// hasPart / comment arrays. Returns the zero value if pv or pv.Author is nil
// callers should treat that as "skip this entry".
// buildPostNode constructs a DiscussionForumPosting in nested form (no
// envelope, no @context). Used for top-level posts and for entries in
// hasPart / comment arrays. Returns the zero value if pv or pv.Author is
// nil; callers should treat that as "skip".
func buildPostNode(pv *appbsky.FeedDefs_PostView, replies []*appbsky.FeedDefs_ThreadViewPost_Replies_Elem, hideLabels map[string]bool) discussionForumPosting {
if pv == nil || pv.Author == nil {
return discussionForumPosting{}
@@ -349,7 +334,6 @@ func buildPostNode(pv *appbsky.FeedDefs_PostView, replies []*appbsky.FeedDefs_Th
}
reply := buildReplyNode(r.FeedDefs_ThreadViewPost.Post, hideLabels)
if reply.Type == "" {
// nil-Author guard tripped; skip.
continue
}
node.Comment = append(node.Comment, reply)
@@ -358,8 +342,8 @@ func buildPostNode(pv *appbsky.FeedDefs_PostView, replies []*appbsky.FeedDefs_Th
return node
}
// buildReplyNode builds a schema.org Comment for a reply. Returns the zero
// value if pv or pv.Author is nil; callers should treat that as "skip".
// buildReplyNode builds a schema.org Comment for a reply. Returns the
// zero value if pv or pv.Author is nil.
func buildReplyNode(pv *appbsky.FeedDefs_PostView, hideLabels map[string]bool) comment {
if pv == nil || pv.Author == nil {
return comment{}
@@ -382,28 +366,21 @@ func buildReplyNode(pv *appbsky.FeedDefs_PostView, hideLabels map[string]bool) c
}
}
// buildPostJSONLD marshals the top-level WebPage envelope for a post page.
// This is what gets injected into <script type="application/ld+json">.
//
// canonicalURL is the public URL for the page. Callers (WebPost) prefer the
// handle-form URL when the author has a usable handle, otherwise fall back
// to the request URI (DID form). The same string is used for both
// envelope.url and mainEntity.url so search engines see a single
// authoritative URL for the post.
// buildPostJSONLD marshals the WebPage envelope wrapping a
// DiscussionForumPosting. canonicalURL is used for both envelope.url and
// (as a fallback) mainEntity.url so they always agree.
func buildPostJSONLD(pv *appbsky.FeedDefs_PostView, replies []*appbsky.FeedDefs_ThreadViewPost_Replies_Elem, canonicalURL string, hideLabels map[string]bool) (string, error) {
if pv == nil || pv.Author == nil {
return "", fmt.Errorf("nil post view or author")
}
node := buildPostNode(pv, replies, hideLabels)
// buildPostNode derives mainEntity.url from the author handle alone, so
// it ends up empty when the handle is unusable (handle.invalid). Fall
// back to canonicalURL so envelope.url and mainEntity.url always agree.
// mainEntity.url is empty when the author handle is unusable; fall back
// to canonicalURL so it agrees with envelope.url.
if node.URL == "" {
node.URL = canonicalURL
}
// Top-level entity: wrap in WebPage envelope per Google's recommendation.
envelope := webPage{
Context: schemaOrgContext,
Type: "WebPage",
@@ -417,8 +394,7 @@ func buildPostJSONLD(pv *appbsky.FeedDefs_PostView, replies []*appbsky.FeedDefs_
return string(b), nil
}
// buildProfileJSONLD marshals the ProfilePage object (including hasPart
// recent posts) for a profile page.
// buildProfileJSONLD marshals a ProfilePage (with hasPart recent posts).
func buildProfileJSONLD(pv *appbsky.ActorDefs_ProfileViewDetailed, recentPosts []*appbsky.FeedDefs_PostView, hideLabels map[string]bool) (string, error) {
if pv == nil {
return "", fmt.Errorf("nil profile view")
@@ -471,10 +447,9 @@ func buildProfileJSONLD(pv *appbsky.ActorDefs_ProfileViewDetailed, recentPosts [
if len(page.HasPart) >= maxRecentPosts {
break
}
// Recent posts go in nested form (no replies, no envelope).
// Recent posts go in nested form.
node := buildPostNode(rp, nil, hideLabels)
if node.Type == "" {
// nil-Author guard tripped; skip.
continue
}
page.HasPart = append(page.HasPart, node)
+14 -28
View File
@@ -11,11 +11,11 @@ import (
lexutil "github.com/bluesky-social/indigo/lex/util"
)
// strPtr / intPtr / boolPtr - small helpers for the optional appbsky fields.
// Pointer helpers for optional appbsky fields.
func strPtr(s string) *string { return &s }
func intPtr(i int64) *int64 { return &i }
// newProfileViewDetailed returns a populated ProfileViewDetailed for tests.
// newProfileViewDetailed returns a populated profile for tests.
func newProfileViewDetailed() *appbsky.ActorDefs_ProfileViewDetailed {
return &appbsky.ActorDefs_ProfileViewDetailed{
Did: "did:plc:alice",
@@ -298,21 +298,18 @@ func TestBuildPostJSONLD_HiddenEmbed(t *testing.T) {
}
func TestBuildPostJSONLD_TextEscaping(t *testing.T) {
// Crafted to break naive string concatenation: includes ", \, newline,
// </script>, and a unicode character.
// Includes ", \, newline, </script>, and a unicode char.
tricky := "hello \"world\" \\ <\\>\n</script> 🎉"
pv := makePostView("alice.bsky.social", "did:plc:alice", "abc123", tricky)
out, err := buildPostJSONLD(pv, nil, "u", hideEmbedLabels)
if err != nil {
t.Fatal(err)
}
// Must round-trip through the JSON parser.
main := unmarshalLD(t, out)["mainEntity"].(map[string]any)
if main["text"] != tricky {
t.Errorf("text round-trip failed: got %q want %q", main["text"], tricky)
}
// Defensive: literal "</script>" must not appear in the output, since
// that would break out of <script type="application/ld+json">.
// Literal </script> would break out of the script tag.
if strings.Contains(out, "</script>") {
t.Errorf("output contains literal </script>, would break HTML embedding")
}
@@ -322,9 +319,7 @@ func TestBuildPostJSONLD_Comments(t *testing.T) {
pv := makePostView("alice.bsky.social", "did:plc:alice", "abc123", "main")
*pv.ReplyCount = 14
// 14 replies: 12 valid, 1 not-found, 1 blocked. The cap is maxComments=10
// so we expect exactly 10 valid entries in comment[], with the
// non-thread variants filtered out.
// 12 valid replies + 1 not-found + 1 blocked. Cap is maxComments=10.
const validReplies = 12
var replies []*appbsky.FeedDefs_ThreadViewPost_Replies_Elem
for i := 0; i < validReplies; i++ {
@@ -355,15 +350,12 @@ func TestBuildPostJSONLD_Comments(t *testing.T) {
if len(comments) != maxComments {
t.Errorf("expected %d comments (capped from %d valid), got %d", maxComments, validReplies, len(comments))
}
// First comment must be the first reply (FIFO order, not the not-found
// one which sits at the end).
// FIFO order: first valid reply, not the not-found at the end.
first := comments[0].(map[string]any)
if first["identifier"] != "at://did:plc:rep00/app.bsky.feed.post/reply00" {
t.Errorf("first comment should be reply00, got %v", first["identifier"])
}
// Each comment must be schema.org Comment (not DiscussionForumPosting —
// that type is invalid for the comment property) and must NOT have
// nested comment[] / isBasedOn / sharedContent.
// Comment type, no nested comment[] / isBasedOn / sharedContent.
for i, c := range comments {
cm := c.(map[string]any)
if cm["@type"] != "Comment" {
@@ -390,9 +382,8 @@ func TestBuildPostJSONLD_HandleInvalidAuthor(t *testing.T) {
out, _ := buildPostJSONLD(pv, nil, fallback, hideEmbedLabels)
envelope := unmarshalLD(t, out)
main := envelope["mainEntity"].(map[string]any)
// With no usable handle, mainEntity.url falls back to the canonical URL
// the caller provided (DID-form request URI), so the envelope URL and
// the post URL agree on a single string.
// mainEntity.url falls back to the caller's canonical URL so envelope
// and post URLs always agree.
if main["url"] != fallback {
t.Errorf("mainEntity.url should fall back to canonical URL, got %v", main["url"])
}
@@ -403,21 +394,18 @@ func TestBuildPostJSONLD_HandleInvalidAuthor(t *testing.T) {
t.Errorf("envelope.url and mainEntity.url disagree: %v vs %v",
envelope["url"], main["url"])
}
// identifier (AT-URI) is still present and stable across handle changes.
// identifier (AT-URI) stays stable across handle changes.
if main["identifier"] != pv.Uri {
t.Errorf("identifier should still be the AT-URI, got %v", main["identifier"])
}
// Author URL is omitted (no usable handle to construct a profile URL).
// Author URL omitted (no usable handle).
author := main["author"].(map[string]any)
if _, present := author["url"]; present {
t.Errorf("handle.invalid author should not produce author.url")
}
}
// TestBuildPostJSONLD_EnvelopeURLMatchesMainEntity asserts the P0.3
// invariant that the WebPage envelope and the inner DiscussionForumPosting
// always carry the same URL — both for happy-path (handle-form canonical)
// and the handle.invalid fallback case.
// envelope.url and mainEntity.url must always agree.
func TestBuildPostJSONLD_EnvelopeURLMatchesMainEntity(t *testing.T) {
cases := []struct {
name, handle, did, rkey, canonical string
@@ -454,8 +442,7 @@ func TestBuildPostJSONLD_EnvelopeURLMatchesMainEntity(t *testing.T) {
}
func TestBuildPostJSONLD_NilAuthor(t *testing.T) {
// Defensive: appview is contractually required to send an Author, but we
// shouldn't panic if a malformed payload sneaks through.
// Defensive: don't panic if Author is nil.
pv := makePostView("alice.bsky.social", "did:plc:alice", "abc123", "hi")
pv.Author = nil
if _, err := buildPostJSONLD(pv, nil, "u", hideEmbedLabels); err == nil {
@@ -464,8 +451,7 @@ func TestBuildPostJSONLD_NilAuthor(t *testing.T) {
}
func TestBuildPostJSONLD_NilAuthorReply(t *testing.T) {
// A reply with a nil author should be silently dropped from comment[]
// rather than producing an entry with no @type.
// Reply with nil Author should be dropped, not emitted with empty @type.
pv := makePostView("alice.bsky.social", "did:plc:alice", "abc123", "main")
*pv.ReplyCount = 2
+2 -3
View File
@@ -7,9 +7,8 @@ import (
// Helpers for inspecting profile / post labels.
// profileRequiresAuth reports whether the profile has self-applied the
// `!no-unauthenticated` label, indicating the user only wants their content
// shown to signed-in viewers. SSR responses for these profiles must omit
// post text, descriptions, and other content beyond minimal identity.
// !no-unauthenticated label. SSR responses for these profiles omit post
// content beyond minimal identity.
func profileRequiresAuth(pv *appbsky.ActorDefs_ProfileViewDetailed) bool {
if pv == nil {
return false
+2 -4
View File
@@ -56,10 +56,8 @@ func TestProfileRequiresAuth(t *testing.T) {
want: false,
},
{
// Helper does not currently honor a Neg flag — matches existing
// inline behavior in WebPost / WebProfile / WebProfileRSS. If
// negation semantics are needed for self-labels, all four call
// sites need to change together.
// Negation isn't honored — matches prior inline behavior in
// WebPost / WebProfile / WebProfileRSS.
name: "negated label still triggers (matches prior behavior)",
pv: &appbsky.ActorDefs_ProfileViewDetailed{
Did: "did:plc:alice",
+13 -27
View File
@@ -11,19 +11,13 @@ import (
"github.com/flosch/pongo2/v6"
)
// renderTemplate executes a template by name with the given context and
// returns the rendered output. Uses the same renderer plumbing as the live
// server so we exercise the real template loader.
//
// post.html and profile.html both extend base.html, which {% include %}s
// templates/scripts.html — a file generated by the React/Vite web build.
// When that file is absent (e.g. running `go test` in a fresh checkout
// without a prior `yarn build-web`), template loading fails. Skip rather
// than fail in that case.
// renderTemplate executes a template using the live renderer and returns
// the output. base.html includes templates/scripts.html, which is generated
// by `yarn build-web`; skip the test if it's missing.
func renderTemplate(t *testing.T, name string, ctx pongo2.Context) string {
t.Helper()
if _, err := bskyweb.TemplateFS.ReadFile("templates/scripts.html"); err != nil {
t.Skip("templates/scripts.html not present (run yarn build-web first); skipping render tests")
t.Skip("templates/scripts.html not present (run yarn build-web first)")
}
r := NewRenderer("templates/", &bskyweb.TemplateFS, false)
tmpl, err := r.TemplateSet.FromCache(name)
@@ -39,8 +33,7 @@ func renderTemplate(t *testing.T, name string, ctx pongo2.Context) string {
var jsonLDRe = regexp.MustCompile(`(?s)<script type="application/ld\+json">(.*?)</script>`)
// extractJSONLD pulls out the body of the <script type="application/ld+json">
// block from rendered HTML. Asserts the block exists.
// extractJSONLD pulls out the body of the application/ld+json script tag.
func extractJSONLD(t *testing.T, html string) string {
t.Helper()
m := jsonLDRe.FindStringSubmatch(html)
@@ -71,8 +64,7 @@ func TestRenderPost_EmitsJSONLD(t *testing.T) {
if parsed["@type"] != "WebPage" {
t.Errorf("expected WebPage envelope, got %v", parsed["@type"])
}
// Verify canonical link is the handle-form URL (not the request URI
// canonicalized).
// Canonical link should be the handle-form URL.
if !strings.Contains(html, `<link rel="canonical" href="https://bsky.app/profile/alice.bsky.social/post/abc123" />`) {
t.Errorf("canonical link missing or wrong:\n%s", html)
}
@@ -88,11 +80,10 @@ func TestRenderPost_OGImageMatchesJSONLD(t *testing.T) {
"requestURI": "https://bsky.app/profile/alice.bsky.social/post/abc123",
"canonicalURL": "https://bsky.app/profile/alice.bsky.social/post/abc123",
"postJSONLD": ld,
// Mirrors what server.go puts in: og:image meta tags use imgThumbUrls.
"imgThumbUrls": []string{thumb1, thumb2},
})
// og:image must use the same URLs as JSON-LD's image[] (Google byte-equality requirement).
// og:image and JSON-LD image[] must be byte-identical.
if !strings.Contains(html, `<meta property="og:image" content="`+thumb1+`">`) {
t.Errorf("og:image[0] not found in rendered HTML")
}
@@ -108,8 +99,7 @@ func TestRenderPost_OGImageMatchesJSONLD(t *testing.T) {
}
func TestRenderPost_FallsBackToCanonicalizeFilter(t *testing.T) {
// When canonicalURL is not set, template should fall back to
// requestURI|canonicalize_url.
// Without canonicalURL, the template falls back to requestURI|canonicalize_url.
pv := makePostView("alice.bsky.social", "did:plc:alice", "abc123", "hi")
ld, _ := buildPostJSONLD(pv, nil, "u", hideEmbedLabels)
html := renderTemplate(t, "post.html", pongo2.Context{
@@ -145,11 +135,9 @@ func TestRenderProfile_EmitsJSONLD(t *testing.T) {
}
}
// TestRenderProfile_AuthRequiredEmitsJSONLD confirms that auth-required
// profiles still emit ProfilePage / Person structured data (without
// hasPart). Previously this regressed when WebProfile was refactored to
// short-circuit before buildProfileJSONLD; the regression test guards
// against re-introducing that.
// Regression: auth-required profiles must still emit ProfilePage JSON-LD
// (without hasPart). Previously regressed when WebProfile short-circuited
// before buildProfileJSONLD.
func TestRenderProfile_AuthRequiredEmitsJSONLD(t *testing.T) {
pv := newProfileViewDetailed()
ld, err := buildProfileJSONLD(pv, nil, hideEmbedLabels)
@@ -176,9 +164,7 @@ func TestRenderProfile_AuthRequiredEmitsJSONLD(t *testing.T) {
}
}
// TestRenderPost_OGUrlMatchesCanonical confirms that og:url and
// <link rel="canonical"> emit the same URL when canonicalURL is set, so
// social cards and search engines see a consistent reference.
// og:url and <link rel="canonical"> must emit the same URL.
func TestRenderPost_OGUrlMatchesCanonical(t *testing.T) {
pv := makePostView("alice.bsky.social", "did:plc:alice", "abc123", "hi")
ld, _ := buildPostJSONLD(pv, nil, "u", hideEmbedLabels)
@@ -195,7 +181,7 @@ func TestRenderPost_OGUrlMatchesCanonical(t *testing.T) {
if !strings.Contains(html, `<link rel="canonical" href="`+canonical+`" />`) {
t.Errorf("canonical link missing or wrong:\n%s", html)
}
// Inverse: the request URI (DID form) should NOT appear as og:url.
// DID-form request URI must not leak into og:url.
if strings.Contains(html, `<meta property="og:url" content="https://bsky.app/profile/did:plc:alice/post/abc123">`) {
t.Errorf("og:url should not echo DID-form request URI when canonical is set")
}
+16 -28
View File
@@ -529,10 +529,9 @@ func (srv *Server) WebPost(c echo.Context) error {
req := c.Request()
requestURI := fmt.Sprintf("https://%s%s", req.Host, req.URL.Path)
// always prefer the handle-form URL when we have a usable handle, regardless of how the request was looked up.
// This both handles DID-form requests and normalizes handle-form requests against stale handles in the URL,
// guaranteeing JSON-LD `url` and <link rel="canonical"> match exactly.
// If the handle is unusable (handle.invalid or empty), fall back to the request URI with query/fragment stripped.
// Always prefer the handle-form URL so JSON-LD `url` and
// <link rel="canonical"> match. Falls back to requestURI when the
// handle is unusable (template strips query/fragment).
canonicalURL := bskyPostURL(pv.Handle, rkey.String())
if !unauthedViewingOkay {
@@ -568,10 +567,8 @@ func (srv *Server) WebPost(c echo.Context) error {
data["canonicalURL"] = canonicalURL
}
// Embed-hidden gate, post text, image thumbs, and video metadata are all
// derived from helpers in jsonld.go so the og:* / twitter:* meta tags
// and the JSON-LD payload stay in lockstep — Google's Rich Results
// validator requires og:image and JSON-LD image[] to be byte-identical.
// Share extraction helpers with jsonld.go so og:image and JSON-LD
// image[] are byte-identical (per Google's requirement).
isEmbedHidden := postEmbedHidden(postView, hideEmbedLabels)
data["postText"] = postRecordText(postView)
@@ -587,9 +584,8 @@ func (srv *Server) WebPost(c echo.Context) error {
}
}
// Build schema.org JSON-LD for SEO. canonicalURL is what we want as the
// public URL; if it's empty (handle.invalid edge case), fall back to the
// request URI so the field still gets emitted with something sensible.
// Build JSON-LD. Fall back to requestURI when handle is unusable so the
// envelope url is never empty.
jsonldURL := canonicalURL
if jsonldURL == "" {
jsonldURL = requestURI
@@ -666,27 +662,19 @@ func (srv *Server) WebProfile(c echo.Context) error {
data["requestURI"] = fmt.Sprintf("https://%s%s", req.Host, req.URL.Path)
data["requestHost"] = req.Host
// Canonical URL: always prefer the handle-form URL when we have a usable
// handle, regardless of how the request was looked up. This handles
// DID-form requests and normalizes handle-form requests against stale
// handles, guaranteeing JSON-LD `url` and <link rel="canonical"> match.
// Falls back to requestURI (with query/fragment stripped by the
// canonicalize_url filter) when the handle is unusable.
// Prefer the handle-form URL so JSON-LD `url` and
// <link rel="canonical"> match. Template falls back to requestURI
// when the handle is unusable.
if url := bskyProfileURL(pv.Handle); url != "" {
data["canonicalURL"] = url
}
// Fetch recent posts to embed as ProfilePage.hasPart so search engines
// can connect a profile to its recent content. Failures here degrade
// gracefully — we still render the profile without hasPart.
// Fetch recent posts for ProfilePage.hasPart. Skipped for auth-required
// profiles (posts aren't publicly indexable anyway). Failures degrade
// gracefully — the profile still renders without hasPart.
//
// Skipped for auth-required profiles (their posts aren't publicly
// indexable anyway), but the rest of the ProfilePage / Person markup
// is still emitted so search engines see basic identity.
//
// NOTE: this adds an extra XRPC call on every public profile page
// render. If upstream load becomes a concern, consider caching
// per-profile (recent posts change slowly relative to profile views).
// NOTE: extra XRPC call on every public profile render; consider
// caching per-profile if upstream load becomes a concern.
var recentPosts []*appbsky.FeedDefs_PostView
if unauthedViewingOkay {
af, err := appbsky.FeedGetAuthorFeed(ctx, srv.xrpcc, pv.Did, "", "posts_no_replies", false, authorFeedFetchLimit)
@@ -697,7 +685,7 @@ func (srv *Server) WebProfile(c echo.Context) error {
if p == nil || p.Post == nil {
continue
}
// Only the author's own posts (matches RSS handler behavior).
// Only the author's own posts (matches RSS handler).
if p.Post.Author == nil || p.Post.Author.Did != pv.Did {
continue
}