caelum0x 0ec2f66158 fix(ritgram): stop escaping post-content slashes, linkify URLs, fix profile Posts-tab 404
- postValidator: drop .escape() from createPost's content rule (was turning
  every literal "/" in a URL into /, so link detection and link previews
  silently never fired on any post containing a link). React already escapes
  rendered text; PostCard never uses dangerouslySetInnerHTML for post content.
- compose/edit live-preview panes DO use dangerouslySetInnerHTML for their
  markdown preview and relied on the backend .escape() as their only XSS
  guard -- added an explicit &/</> escape before any markdown transform so
  removing .escape() doesn't open that up.
- linkify.tsx: linkifyText only matched @mention/#hashtag; added a URL pass
  (same regex as extractUrls.ts) so bare https:// URLs render as a real
  <a target="_blank">, with mention/hashtag matching skipping any range a URL
  already claimed.
- Profile Posts tab called a route that doesn't exist
  (GET /users/:username/posts, 404 on every profile). Added real
  username/userId filtering to postController.getPosts (it previously ignored
  both query params entirely) and pointed both frontend callers
  (profileApi.ts's fetchUserPosts, ProfileTabs.tsx's dead-code twin) at
  GET /v1/posts?username=. Switched ProfileTabs' infinite-scroll fetcher from
  a cursor param the backend never returned to real page-based pagination.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 00:04:58 +03:00

184 lines
5.6 KiB
TypeScript

import { Fragment, type ReactNode } from 'react';
import Link from 'next/link';
import { UserHoverCard } from '@/components/UserHoverCard';
/**
* Matches @mentions and #hashtags in free text.
*
* - A token must be preceded by start-of-string or whitespace so that emails
* (`a@b.com`) and inline code fragments are not mistakenly linkified.
* - The captured word allows letters, numbers, and underscores — matching the
* product's username/hashtag rules (see settings/profile validateUsername and
* ContentComposer.extractHashtags).
*/
const TOKEN_PATTERN = /(^|[\s(])([@#])([A-Za-z0-9_]{1,40})/g;
/**
* Matches bare http(s) URLs in free text, same pattern as
* `utils/extractUrls.ts` (kept in sync intentionally — that util decides
* which URLs get a RichEmbeds preview card, this one decides which URL *text*
* becomes clickable inline).
*/
const URL_PATTERN = /\bhttps?:\/\/[^\s<>()]+/gi;
const TRAILING_PUNCTUATION = /[.,!?;:'")\]]+$/;
export interface LinkifyOptions {
/** Tailwind/utility classes applied to each generated link. */
linkClassName?: string;
}
const DEFAULT_LINK_CLASS = 'text-[var(--primary)] hover:underline';
interface FoundToken {
start: number;
end: number;
render: (key: string) => ReactNode;
}
/**
* Builds the destination route for a token.
* Mentions resolve to the user profile route (`/[username]`).
* Hashtags resolve to the hashtag feed route (`/hashtag/[tag]`).
*/
function hrefForToken(char: string, word: string): string {
return char === '#' ? `/hashtag/${encodeURIComponent(word)}` : `/${encodeURIComponent(word)}`;
}
/**
* Finds every bare http(s) URL in `text` and returns them as non-overlapping
* `FoundToken`s rendered as a real anchor (opens in a new tab). Runs before
* the @mention/#hashtag pass so a URL's own `#fragment` or `user@host`
* userinfo is never mistaken for a hashtag/mention inside it.
*/
function findUrlTokens(text: string, linkClassName: string): FoundToken[] {
const tokens: FoundToken[] = [];
URL_PATTERN.lastIndex = 0;
let match: RegExpExecArray | null;
while ((match = URL_PATTERN.exec(text)) !== null) {
const raw = match[0];
const trimmed = raw.replace(TRAILING_PUNCTUATION, '');
if (!trimmed) continue;
try {
// eslint-disable-next-line no-new
new URL(trimmed);
} catch {
continue;
}
const start = match.index;
const end = start + trimmed.length;
tokens.push({
start,
end,
render: (key) => (
<a
key={key}
href={trimmed}
target="_blank"
rel="noopener noreferrer nofollow ugc"
className={linkClassName}
onClick={(e) => e.stopPropagation()}
>
{trimmed}
</a>
),
});
}
return tokens;
}
/**
* Finds every @mention / #hashtag in `text`, skipping any range already
* claimed by a URL token (so `#fragment`/`user@host` inside a URL is never
* double-linkified).
*/
function findMentionHashtagTokens(
text: string,
linkClassName: string,
claimed: FoundToken[],
): FoundToken[] {
const tokens: FoundToken[] = [];
TOKEN_PATTERN.lastIndex = 0;
let match: RegExpExecArray | null;
let keyCounter = 0;
while ((match = TOKEN_PATTERN.exec(text)) !== null) {
const [, lead, char, word] = match;
const start = match.index + lead.length;
const end = start + char.length + word.length;
if (claimed.some((c) => start < c.end && end > c.start)) continue;
const link = (
<Link
key={`m-${keyCounter}`}
href={hrefForToken(char, word)}
className={linkClassName}
// Stop the click from bubbling to parent post/card click handlers.
onClick={(e) => e.stopPropagation()}
>
{char}
{word}
</Link>
);
tokens.push({
start,
end,
// Mentions get a profile-preview hover card; hashtags stay as plain links.
render: (key) =>
char === '@' ? (
<UserHoverCard key={key} username={word}>
{link}
</UserHoverCard>
) : (
<Fragment key={key}>{link}</Fragment>
),
});
keyCounter += 1;
}
return tokens;
}
/**
* Converts a plain text string into an array of React nodes where every bare
* http(s) URL, @mention and #hashtag becomes a clickable element (URLs as a
* real `<a target="_blank">`, mentions/hashtags as Next.js `<Link>`s). All
* other text is preserved verbatim (including whitespace), so it is safe to
* render inside a `whitespace-pre-wrap` container.
*
* This performs no HTML parsing — it only ever emits plain strings, `<a>`,
* and `<Link>` elements, so there is no XSS surface (unlike
* dangerouslySetInnerHTML-based approaches).
*/
export function linkifyText(text: string, options: LinkifyOptions = {}): ReactNode {
const linkClassName = options.linkClassName ?? DEFAULT_LINK_CLASS;
if (!text) return text;
const urlTokens = findUrlTokens(text, linkClassName);
const mentionTokens = findMentionHashtagTokens(text, linkClassName, urlTokens);
const allTokens = [...urlTokens, ...mentionTokens].sort((a, b) => a.start - b.start);
const nodes: ReactNode[] = [];
let lastIndex = 0;
let keyCounter = 0;
for (const token of allTokens) {
const precedingText = text.slice(lastIndex, token.start);
if (precedingText) {
nodes.push(<Fragment key={`t-${keyCounter++}`}>{precedingText}</Fragment>);
}
nodes.push(token.render(`l-${keyCounter++}`));
lastIndex = token.end;
}
// Trailing text after the final token.
const trailing = text.slice(lastIndex);
if (trailing) {
nodes.push(<Fragment key={`t-${keyCounter++}`}>{trailing}</Fragment>);
}
return nodes;
}