Implement social-feed: local follows + /feed + profile visibility

Implements the social-feed change end-to-end. Local-only follows
between users on the same instance, an aggregated /feed of public
activities from people you follow, and an explicit profile_visibility
setting so the question "can someone follow me?" has a deterministic
answer.

Schema (additive, drizzle-kit push --force in cd-apps handles it):
- journal.follows table keyed by `followed_actor_iri TEXT` for
  federation forward-compat. Local IRIs look like
  `${ORIGIN}/users/${username}`. `accepted_at` is nullable so the
  Pending state from social-federation slots in without migration.
- journal.users.profile_visibility ('public' | 'private', default
  'public'). Existing users land 'public' via the default; current
  effective behavior is unchanged.

Server (apps/journal/app/lib):
- actor-iri.ts: localActorIri(username) helper — single source of
  truth for IRI construction.
- follow.server.ts: followUser / unfollowUser / getFollowState /
  countFollowers / countFollowing / listFollowers / listFollowing.
  Refuses self-follow + private targets. Idempotent.
- activities.server.ts: listSocialFeed(followerId, limit) joining
  follows → activities WHERE visibility='public', reverse-chrono.

Routes:
- POST /api/users/:username/follow + /unfollow (session-bound)
- /feed (signed-in only; redirects anon to /auth/login)
- /users/:username/followers + /users/:username/following (paginated)
- /users/:username gates on profile_visibility AND has-public-content
  for visitors; owners on private get an amber explainer banner.
- /settings adds a Public/Private radio with explainer text.

UI:
- FollowButton component on profile page (hidden for owner + anon).
- Follower/following counts on profile linking to collection pages.
- "Feed" link in nav (signed-in) + on personal dashboard alongside
  "New Activity".

Privacy manifest updated to document the new follows relation and
profile_visibility setting.

Tests: follow.integration.test.ts (FOLLOW_INTEGRATION=1) for the
follow lifecycle; e2e/social.test.ts for /feed redirect, follow
button + count transitions, and the profile_visibility 404 toggle.

Local development: run `pnpm db:push` after pulling to apply the
schema additions. Production migrates automatically via cd-apps.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
Ullrich Schäfer 2026-04-25 22:51:18 +02:00
parent 6440631be4
commit 811d5f62f5
23 changed files with 1115 additions and 40 deletions

View file

@ -12,11 +12,18 @@ export async function action({ request }: Route.ActionArgs) {
const formData = await request.formData();
const displayName = (formData.get("displayName") as string)?.trim() || null;
const bio = (formData.get("bio") as string)?.trim().slice(0, 160) || null;
const rawVisibility = formData.get("profileVisibility") as string | null;
const profileVisibility: "public" | "private" | undefined =
rawVisibility === "public" || rawVisibility === "private" ? rawVisibility : undefined;
const db = getDb();
await db
.update(users)
.set({ displayName, bio })
.set({
displayName,
bio,
...(profileVisibility ? { profileVisibility } : {}),
})
.where(eq(users.id, user.id));
return data({ ok: true });

View file

@ -0,0 +1,26 @@
import { data } from "react-router";
import type { Route } from "./+types/api.users.$username.follow";
import { getSessionUser } from "~/lib/auth.server";
import { followUser, FollowError } from "~/lib/follow.server";
export async function action({ request, params }: Route.ActionArgs) {
if (request.method !== "POST") {
return data({ error: "Method not allowed" }, { status: 405 });
}
const user = await getSessionUser(request);
if (!user) return data({ error: "Unauthorized" }, { status: 401 });
const username = params.username;
if (!username) return data({ error: "username required" }, { status: 400 });
try {
const state = await followUser(user.id, username);
return data({ ok: true, ...state });
} catch (e) {
if (e instanceof FollowError) {
const status = e.code === "user_not_found" ? 404 : 400;
return data({ error: e.message, code: e.code }, { status });
}
throw e;
}
}

View file

@ -0,0 +1,26 @@
import { data } from "react-router";
import type { Route } from "./+types/api.users.$username.unfollow";
import { getSessionUser } from "~/lib/auth.server";
import { unfollowUser, FollowError } from "~/lib/follow.server";
export async function action({ request, params }: Route.ActionArgs) {
if (request.method !== "POST") {
return data({ error: "Method not allowed" }, { status: 405 });
}
const user = await getSessionUser(request);
if (!user) return data({ error: "Unauthorized" }, { status: 401 });
const username = params.username;
if (!username) return data({ error: "username required" }, { status: 400 });
try {
const state = await unfollowUser(user.id, username);
return data({ ok: true, ...state });
} catch (e) {
if (e instanceof FollowError) {
const status = e.code === "user_not_found" ? 404 : 400;
return data({ error: e.message, code: e.code }, { status });
}
throw e;
}
}

View file

@ -0,0 +1,102 @@
import { data, redirect } from "react-router";
import { useTranslation } from "react-i18next";
import type { Route } from "./+types/feed";
import { getSessionUser } from "~/lib/auth.server";
import { listSocialFeed } from "~/lib/activities.server";
import { ClientDate } from "~/components/ClientDate";
import { ClientMap } from "~/components/ClientMap";
export async function loader({ request }: Route.LoaderArgs) {
const user = await getSessionUser(request);
if (!user) throw redirect("/auth/login");
const rows = await listSocialFeed(user.id, 50);
return data({
activities: rows.map((a) => ({
id: a.id,
name: a.name,
distance: a.distance,
elevationGain: a.elevationGain,
duration: a.duration,
startedAt: a.startedAt?.toISOString() ?? null,
createdAt: a.createdAt.toISOString(),
geojson: a.geojson ?? null,
ownerUsername: a.ownerUsername,
ownerDisplayName: a.ownerDisplayName,
})),
});
}
export function meta(_args: Route.MetaArgs) {
return [{ title: "Feed — trails.cool" }];
}
export default function Feed({ loaderData }: Route.ComponentProps) {
const { activities } = loaderData;
const { t } = useTranslation("journal");
return (
<div className="mx-auto max-w-4xl px-4 py-8">
<h1 className="text-2xl font-bold text-gray-900">{t("social.feed.heading")}</h1>
{activities.length === 0 ? (
<div className="mt-12 text-center">
<p className="text-gray-500">{t("social.feed.empty")}</p>
<a
href="/"
className="mt-3 inline-block text-sm text-blue-600 hover:underline"
>
{t("social.feed.publicFeedLink")}
</a>
</div>
) : (
<ul className="mt-6 space-y-4">
{activities.map((a) => (
<li key={a.id}>
<a
href={`/activities/${a.id}`}
className="block rounded-lg border border-gray-200 p-4 hover:bg-gray-50"
>
<div className="flex gap-4">
<div className="w-40 shrink-0">
{a.geojson ? (
<ClientMap geojson={a.geojson} />
) : (
<div className="flex h-28 w-full items-center justify-center rounded bg-gray-100 text-xs text-gray-400">
{t("routes.noMapPreview")}
</div>
)}
</div>
<div className="flex flex-1 flex-col justify-between">
<div>
<h3 className="text-base font-medium text-gray-900">{a.name}</h3>
<div className="mt-1 text-sm text-gray-500">
<a
href={`/users/${a.ownerUsername}`}
className="hover:text-gray-700 hover:underline"
onClick={(e) => e.stopPropagation()}
>
{a.ownerDisplayName ?? a.ownerUsername}
</a>
{" · "}
<ClientDate iso={a.startedAt ?? a.createdAt} />
</div>
<div className="mt-1 flex gap-4 text-sm text-gray-500">
{a.distance != null && (
<span>{(a.distance / 1000).toFixed(1)} km</span>
)}
{a.elevationGain != null && (
<span> {Math.round(a.elevationGain)} m</span>
)}
</div>
</div>
</div>
</div>
</a>
</li>
))}
</ul>
)}
</div>
);
}

View file

@ -167,12 +167,20 @@ export default function Home({ loaderData }: Route.ComponentProps) {
{user.displayName ?? user.username}
</a>
</h1>
<a
href="/activities/new"
className="rounded-md bg-blue-600 px-4 py-2 text-sm font-medium text-white hover:bg-blue-700"
>
{t("activities.new")}
</a>
<div className="flex items-center gap-3">
<a
href="/feed"
className="rounded-md border border-gray-300 px-4 py-2 text-sm font-medium text-gray-700 hover:bg-gray-50"
>
{t("social.feed.title")}
</a>
<a
href="/activities/new"
className="rounded-md bg-blue-600 px-4 py-2 text-sm font-medium text-white hover:bg-blue-700"
>
{t("activities.new")}
</a>
</div>
</div>
{showAddPasskey && !passkeyDone && supportsPasskey === true && (

View file

@ -394,6 +394,20 @@ export default function PrivacyPage() {
including on your public profile at <code>/users/&lt;you&gt;</code>
and on search engines that index those pages.
</li>
<li>
Profile visibility (<code>public</code> / <code>private</code>,
default <code>public</code>): a separate switch from content
visibility. <code>private</code> 404s your profile page and makes
you unfollowable; you can still post <code>public</code> content
reachable by direct URL. Change anytime in account settings.
</li>
<li>
Follows: which users on this instance follow which. Visible to
anyone via your <code>/users/&lt;you&gt;/followers</code> and
<code>/users/&lt;you&gt;/following</code> pages, mirroring
Mastodon-style conventions. Set your profile to{" "}
<code>private</code> to be unfollowable.
</li>
</ul>
</section>

View file

@ -48,6 +48,7 @@ export async function loader({ request }: Route.LoaderArgs) {
email: user.email,
displayName: user.displayName,
bio: user.bio,
profileVisibility: user.profileVisibility,
},
passkeys: passkeys.map((p) => ({
id: p.id,
@ -77,6 +78,9 @@ export default function Settings({ loaderData }: Route.ComponentProps) {
const [displayName, setDisplayName] = useState(user.displayName ?? "");
const [bio, setBio] = useState(user.bio ?? "");
const [profileVisibility, setProfileVisibility] = useState<"public" | "private">(
user.profileVisibility,
);
const [profileSaved, setProfileSaved] = useState(false);
const [newEmail, setNewEmail] = useState("");
@ -202,6 +206,49 @@ export default function Settings({ loaderData }: Route.ComponentProps) {
/>
<p className="mt-1 text-xs text-gray-500">{bio.length}/160</p>
</div>
<fieldset>
<legend className="block text-sm font-medium text-gray-700">
{t("settings.profile.visibility.label")}
</legend>
<div className="mt-2 space-y-2">
<label className="flex items-start gap-2 text-sm">
<input
type="radio"
name="profileVisibility"
value="public"
checked={profileVisibility === "public"}
onChange={() => setProfileVisibility("public")}
className="mt-0.5"
/>
<span>
<span className="font-medium text-gray-900">
{t("settings.profile.visibility.public")}
</span>
<span className="ml-2 text-gray-500">
{t("settings.profile.visibility.publicHelp")}
</span>
</span>
</label>
<label className="flex items-start gap-2 text-sm">
<input
type="radio"
name="profileVisibility"
value="private"
checked={profileVisibility === "private"}
onChange={() => setProfileVisibility("private")}
className="mt-0.5"
/>
<span>
<span className="font-medium text-gray-900">
{t("settings.profile.visibility.private")}
</span>
<span className="ml-2 text-gray-500">
{t("settings.profile.visibility.privateHelp")}
</span>
</span>
</label>
</div>
</fieldset>
<div className="flex items-center gap-3">
<button
type="submit"

View file

@ -0,0 +1,37 @@
import { data } from "react-router";
import { eq } from "drizzle-orm";
import type { Route } from "./+types/users.$username.followers";
import { getDb } from "~/lib/db";
import { users } from "@trails-cool/db/schema/journal";
import { listFollowers, countFollowers } from "~/lib/follow.server";
import { CollectionPage } from "~/components/CollectionPage";
export async function loader({ params, request }: Route.LoaderArgs) {
const db = getDb();
const [user] = await db.select().from(users).where(eq(users.username, params.username));
if (!user || user.profileVisibility !== "public") {
throw data({ error: "User not found" }, { status: 404 });
}
const url = new URL(request.url);
const page = Math.max(1, parseInt(url.searchParams.get("page") ?? "1", 10) || 1);
const [entries, total] = await Promise.all([
listFollowers(user.id, page),
countFollowers(user.id),
]);
return data({
user: { username: user.username, displayName: user.displayName },
page,
total,
entries,
});
}
export function meta({ data: d }: Route.MetaArgs) {
return [{ title: `Followers of @${d?.user.username ?? ""} — trails.cool` }];
}
export default function Followers({ loaderData }: Route.ComponentProps) {
return <CollectionPage kind="followers" {...loaderData} />;
}

View file

@ -0,0 +1,37 @@
import { data } from "react-router";
import { eq } from "drizzle-orm";
import type { Route } from "./+types/users.$username.following";
import { getDb } from "~/lib/db";
import { users } from "@trails-cool/db/schema/journal";
import { listFollowing, countFollowing } from "~/lib/follow.server";
import { CollectionPage } from "~/components/CollectionPage";
export async function loader({ params, request }: Route.LoaderArgs) {
const db = getDb();
const [user] = await db.select().from(users).where(eq(users.username, params.username));
if (!user || user.profileVisibility !== "public") {
throw data({ error: "User not found" }, { status: 404 });
}
const url = new URL(request.url);
const page = Math.max(1, parseInt(url.searchParams.get("page") ?? "1", 10) || 1);
const [entries, total] = await Promise.all([
listFollowing(user.id, page),
countFollowing(user.id),
]);
return data({
user: { username: user.username, displayName: user.displayName },
page,
total,
entries,
});
}
export function meta({ data: d }: Route.MetaArgs) {
return [{ title: `Following of @${d?.user.username ?? ""} — trails.cool` }];
}
export default function Following({ loaderData }: Route.ComponentProps) {
return <CollectionPage kind="following" {...loaderData} />;
}

View file

@ -8,7 +8,9 @@ import { getSessionUser } from "~/lib/auth.server";
import { listPublicRoutesForOwner } from "~/lib/routes.server";
import { listPublicActivitiesForOwner } from "~/lib/activities.server";
import { loadPersona } from "~/lib/demo-bot.server";
import { countFollowers, countFollowing, getFollowState } from "~/lib/follow.server";
import { ClientDate } from "~/components/ClientDate";
import { FollowButton } from "~/components/FollowButton";
export async function loader({ params, request }: Route.LoaderArgs) {
const db = getDb();
@ -18,20 +20,33 @@ export async function loader({ params, request }: Route.LoaderArgs) {
throw data({ error: "User not found" }, { status: 404 });
}
const [publicRoutes, publicActivities, currentUser] = await Promise.all([
const [publicRoutes, publicActivities, currentUser, followers, following] = await Promise.all([
listPublicRoutesForOwner(user.id),
listPublicActivitiesForOwner(user.id),
getSessionUser(request),
countFollowers(user.id),
countFollowing(user.id),
]);
const isOwn = currentUser?.id === user.id;
// 404 for users with no public content at all, to prevent account
// enumeration. Owners still see their own profile even when empty.
// Profile-visibility gate: a `private` profile 404s for everyone but
// the owner, regardless of how much public content they have.
if (!isOwn && user.profileVisibility !== "public") {
throw data({ error: "User not found" }, { status: 404 });
}
// 404 for public-but-empty profiles to prevent account enumeration.
// Owners still see their own profile even when empty.
if (!isOwn && publicRoutes.length === 0 && publicActivities.length === 0) {
throw data({ error: "User not found" }, { status: 404 });
}
// Follow state for non-owner viewers (null when anonymous).
const followState = !isOwn && currentUser
? await getFollowState(currentUser.id, user.username)
: null;
// Demo-account badge: true when this profile matches the instance's
// configured demo persona username. Computed server-side so we don't
// ship the persona config through client HTML.
@ -64,6 +79,11 @@ export async function loader({ params, request }: Route.LoaderArgs) {
})),
isOwn,
isDemoUser,
followers,
following,
followState,
isLoggedIn: currentUser !== null,
profileVisibility: user.profileVisibility,
});
}
@ -89,7 +109,7 @@ export function meta({ data: loaderData }: Route.MetaArgs) {
}
export default function UserProfilePage({ loaderData }: Route.ComponentProps) {
const { user, routes, activities, isOwn, isDemoUser } = loaderData;
const { user, routes, activities, isOwn, isDemoUser, followers, following, followState, isLoggedIn } = loaderData;
const { t } = useTranslation("journal");
return (
@ -98,7 +118,7 @@ export default function UserProfilePage({ loaderData }: Route.ComponentProps) {
<div className="flex h-16 w-16 items-center justify-center rounded-full bg-blue-100 text-2xl font-bold text-blue-600">
{user.username[0]?.toUpperCase()}
</div>
<div>
<div className="flex-1">
<div className="flex items-center gap-2">
<h1 className="text-2xl font-bold text-gray-900">
{user.displayName ?? user.username}
@ -113,10 +133,40 @@ export default function UserProfilePage({ loaderData }: Route.ComponentProps) {
@{user.username}@{user.domain}
</p>
{user.bio && <p className="mt-2 text-gray-700">{user.bio}</p>}
<div className="mt-2 flex gap-4 text-sm text-gray-600">
<a
href={`/users/${user.username}/followers`}
className="hover:text-gray-900 hover:underline"
>
<span className="font-semibold text-gray-900">{followers}</span>{" "}
{t("social.followers.label")}
</a>
<a
href={`/users/${user.username}/following`}
className="hover:text-gray-900 hover:underline"
>
<span className="font-semibold text-gray-900">{following}</span>{" "}
{t("social.following.label")}
</a>
</div>
</div>
{!isOwn && isLoggedIn && (
<FollowButton
username={user.username}
initialState={followState}
/>
)}
</div>
{isOwn && (
{isOwn && loaderData.profileVisibility === "private" && (
<div className="mt-6 rounded-md border border-amber-200 bg-amber-50 p-3 text-sm text-amber-800">
{t("profile.privateNote")}{" "}
<a href="/settings" className="underline hover:text-amber-900">
{t("profile.goToSettings")}
</a>
</div>
)}
{isOwn && loaderData.profileVisibility === "public" && (
<div className="mt-6 rounded-md border border-blue-100 bg-blue-50 p-3 text-sm text-blue-800">
{t("profile.ownNote")}{" "}
<a href="/settings" className="underline hover:text-blue-900">