trails/apps/journal/app/routes/users.$username.tsx
Ullrich Schäfer 5905cdadea
Apply public-content-visibility: visibility flag + public profile
Implements the public-content-visibility OpenSpec change. Adds the
smallest social surface that lets us demo the product to logged-out
visitors without user signup.

Schema:
- `visibility text NOT NULL DEFAULT 'private'` on routes + activities.
- Shared Visibility type exported from the schema module.

Access:
- New canView(content, viewer, { asDirectLink }) helper in auth.server.ts
  centralises the rule: public → anyone; unlisted → anyone on direct
  link; private → owner only.
- routes.$id and activities.$id loaders return 404 (not 403) when
  canView rejects, so existence of private content isn't leaked.
- Detail pages emit Open Graph + Twitter Card meta on public/unlisted
  content only.

Editing:
- Visibility <select> on routes/:id/edit with owner-only access.
- Activity detail page gets a small visibility form + set-visibility
  action intent (no separate activity-edit page needed).
- EN + DE i18n under routes.visibility.* and activities.visibility.*.

Listings:
- Listing helpers listPublicRoutesForOwner / listPublicActivitiesForOwner
  for cross-user queries. Existing owner-scoped listRoutes/listActivities
  stay — owners see their own content regardless of visibility.

Public profile:
- /users/:username is now truly public. Renders the user's public
  routes + activities, 404s when no public content exists AND viewer
  isn't the owner (prevents account enumeration).
- Owner sees a short "this is your profile" note linking to settings.
- Open Graph meta (og:type=profile) for shareable preview.

Privacy manifest:
- Added a bullet noting public content is world-visible on profile
  and indexable by search engines.
- Bumped PRIVACY_LAST_UPDATED to 2026-04-20 + rendered legal-archive
  snapshot.

Tests:
- 13 unit tests for canView covering the full matrix.
- 6 E2E tests in e2e/public-content.test.ts covering:
  - Private route → 404 for logged-out visitor
  - Public route → reachable + OG tags present (og:title, og:type,
    og:site_name)
  - Owner still sees own private content
  - Profile 404 when no public content
  - Profile renders when at least one public route exists
  - Unlisted route reachable via direct URL but hidden from profile
- Test file runs serially (describe.configure mode=serial) to avoid
  WebAuthn virtual-authenticator races under Playwright's default
  parallel workers.
- New public-content Playwright project added to config.

Rollout safety: every existing row in prod keeps visibility='private'
by default — nothing becomes visible to outsiders until an owner
explicitly opts in.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-19 09:11:39 +02:00

179 lines
6.7 KiB
TypeScript

import { data } from "react-router";
import type { Route } from "./+types/users.$username";
import { useTranslation } from "react-i18next";
import { getDb } from "~/lib/db";
import { users } from "@trails-cool/db/schema/journal";
import { eq } from "drizzle-orm";
import { getSessionUser } from "~/lib/auth.server";
import { listPublicRoutesForOwner } from "~/lib/routes.server";
import { listPublicActivitiesForOwner } from "~/lib/activities.server";
import { ClientDate } from "~/components/ClientDate";
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) {
throw data({ error: "User not found" }, { status: 404 });
}
const [publicRoutes, publicActivities, currentUser] = await Promise.all([
listPublicRoutesForOwner(user.id),
listPublicActivitiesForOwner(user.id),
getSessionUser(request),
]);
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.
if (!isOwn && publicRoutes.length === 0 && publicActivities.length === 0) {
throw data({ error: "User not found" }, { status: 404 });
}
return data({
user: {
username: user.username,
displayName: user.displayName,
bio: user.bio,
domain: user.domain,
createdAt: user.createdAt.toISOString(),
},
routes: publicRoutes.map((r) => ({
id: r.id,
name: r.name,
description: r.description,
distance: r.distance,
elevationGain: r.elevationGain,
updatedAt: r.updatedAt.toISOString(),
})),
activities: publicActivities.map((a) => ({
id: a.id,
name: a.name,
description: a.description,
distance: a.distance,
duration: a.duration,
startedAt: a.startedAt?.toISOString() ?? null,
createdAt: a.createdAt.toISOString(),
})),
isOwn,
});
}
export function meta({ data: loaderData }: Route.MetaArgs) {
const user = (loaderData as { user?: { username: string; displayName: string | null; domain: string; bio: string | null } })?.user;
const displayName = user?.displayName ?? user?.username ?? "Profile";
const title = `${displayName} (@${user?.username}) — trails.cool`;
const description = user?.bio && user.bio.length > 0
? user.bio.slice(0, 280)
: `${displayName} on trails.cool`;
if (!user) return [{ title }];
return [
{ title },
{ property: "og:title", content: title },
{ property: "og:description", content: description },
{ property: "og:type", content: "profile" },
{ property: "og:site_name", content: "trails.cool" },
{ name: "twitter:card", content: "summary" },
{ name: "twitter:title", content: title },
{ name: "twitter:description", content: description },
];
}
export default function UserProfilePage({ loaderData }: Route.ComponentProps) {
const { user, routes, activities, isOwn } = loaderData;
const { t } = useTranslation("journal");
return (
<div className="mx-auto max-w-3xl px-4 py-8">
<div className="flex items-start gap-4">
<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>
<h1 className="text-2xl font-bold text-gray-900">
{user.displayName ?? user.username}
</h1>
<p className="text-sm text-gray-500">
@{user.username}@{user.domain}
</p>
{user.bio && <p className="mt-2 text-gray-700">{user.bio}</p>}
</div>
</div>
{isOwn && (
<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">
{t("profile.goToSettings")}
</a>
</div>
)}
<section className="mt-8">
<h2 className="text-lg font-semibold text-gray-900">
{t("routes.title")} ({routes.length})
</h2>
{routes.length === 0 ? (
<p className="mt-2 text-sm text-gray-500">{t("profile.noPublicRoutes")}</p>
) : (
<ul className="mt-3 divide-y divide-gray-200 rounded-md border border-gray-200">
{routes.map((r) => (
<li key={r.id} className="px-4 py-3">
<a href={`/routes/${r.id}`} className="block hover:bg-gray-50">
<div className="flex items-baseline justify-between gap-4">
<span className="font-medium text-gray-900">{r.name}</span>
{r.distance != null && (
<span className="shrink-0 text-sm tabular-nums text-gray-600">
{(r.distance / 1000).toFixed(1)} km
</span>
)}
</div>
{r.description && (
<p className="mt-1 line-clamp-1 text-sm text-gray-500">{r.description}</p>
)}
<p className="mt-1 text-xs text-gray-400">
<ClientDate iso={r.updatedAt} />
</p>
</a>
</li>
))}
</ul>
)}
</section>
<section className="mt-8">
<h2 className="text-lg font-semibold text-gray-900">
{t("activities.title")} ({activities.length})
</h2>
{activities.length === 0 ? (
<p className="mt-2 text-sm text-gray-500">{t("profile.noPublicActivities")}</p>
) : (
<ul className="mt-3 divide-y divide-gray-200 rounded-md border border-gray-200">
{activities.map((a) => (
<li key={a.id} className="px-4 py-3">
<a href={`/activities/${a.id}`} className="block hover:bg-gray-50">
<div className="flex items-baseline justify-between gap-4">
<span className="font-medium text-gray-900">{a.name}</span>
{a.distance != null && (
<span className="shrink-0 text-sm tabular-nums text-gray-600">
{(a.distance / 1000).toFixed(1)} km
</span>
)}
</div>
{a.description && (
<p className="mt-1 line-clamp-1 text-sm text-gray-500">{a.description}</p>
)}
<p className="mt-1 text-xs text-gray-400">
<ClientDate iso={a.startedAt ?? a.createdAt} />
</p>
</a>
</li>
))}
</ul>
)}
</section>
</div>
);
}