Multi-Agent Collaboration for Team and Friends
TypeScript agent-automationagent-orchestrationagent-workflowai-agentsai-collaborationai-memoryai-workforceautonomous-agentsclaude-codeclaude-code-skillscodexcoding-agentmulti-agentmultiple-agentone-person-businessone-person-companyone-person-teamopencodesolopreneur
community(web): preview-first invite landing page
Gus407c25fb9e89
diff --git a/src/web/src/app/(auth)/layout.tsx b/src/web/src/app/(auth)/layout.tsxindex c140de710..53aaf2413 100644--- a/src/web/src/app/(auth)/layout.tsx+++ b/src/web/src/app/(auth)/layout.tsx@@ -16,7 +16,9 @@ export default async function AuthLayout({children: React.ReactNode;}) {const session = await getSession();- if (session) redirect("/workspaces?auto");+ // Already signed in → community home. `/workspaces` was the retired legacy+ // (v0) surface.+ if (session) redirect("/c/me");return <>{children}</>;}diff --git a/src/web/src/app/(auth)/sign-in/sign-in-client.tsx b/src/web/src/app/(auth)/sign-in/sign-in-client.tsxindex ade8b4b4a..0602200f9 100644--- a/src/web/src/app/(auth)/sign-in/sign-in-client.tsx+++ b/src/web/src/app/(auth)/sign-in/sign-in-client.tsx@@ -25,7 +25,10 @@ import { GradientBackground } from "@/components/gradient-background"import { Logo } from "@/components/logo"import { DEV_PASSWORD } from "@alook/shared"-const DEFAULT_POST_LOGIN = "/workspaces?auto"+// Default post-login landing when no explicit `?redirect=` is present. Points+// at the community home (/c/me); the old `/workspaces` target was the legacy+// (v0) workspace surface being retired.+const DEFAULT_POST_LOGIN = "/c/me"function safeRedirectUrl(redirect: string | null): string {if (redirect && redirect.startsWith("/") && !redirect.startsWith("//")) {diff --git a/src/web/src/app/api/community/invites/[token]/info/route.test.ts b/src/web/src/app/api/community/invites/[token]/info/route.test.tsindex d95216987..140ad3b11 100644--- a/src/web/src/app/api/community/invites/[token]/info/route.test.ts+++ b/src/web/src/app/api/community/invites/[token]/info/route.test.ts@@ -9,6 +9,7 @@ const mockGetInviteByToken = vi.fn()const mockGetServer = vi.fn()const mockCountMembers = vi.fn()const mockListMembers = vi.fn()+const mockGetUsersByIds = vi.fn()vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))@@ -27,25 +28,27 @@ vi.mock("@alook/shared", async () => {countMembers: (...a: unknown[]) => mockCountMembers(...a),listMembers: (...a: unknown[]) => mockListMembers(...a),},+ user: {+ getUsersByIds: (...a: unknown[]) => mockGetUsersByIds(...a),+ },},}})-// Two `withAuth` shapes are covered in tests:-// * `authed` — the default: calls the handler as if the caller is signed in.-// * `anonymous` — returns 401 without calling the handler.+// The route is `withOptionalAuth` (preview-first): it NEVER 401s on a missing+// session — the handler runs either way, only `userId` differs. Two shapes:+// * `authed` — the default: handler runs with a userId, as if signed in.+// * `anonymous` — handler still runs, with userId undefined (no 401).// The mock is `let`-mutated between blocks so we can flip the behaviour per// test.let isAuthed = truevi.mock("@/lib/middleware/auth", () => ({- withAuth: (handler: any) => async (req: any, ctx?: any) => {- if (!isAuthed) {- const { NextResponse } = require("next/server")- return NextResponse.json({ error: "unauthorized" }, { status: 401 })- }+ withOptionalAuth: (handler: any) => async (req: any, ctx?: any) => {const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params- return handler(req, { env: { DB: {} }, userId: "u1", email: "[email protected]", params })+ return isAuthed+ ? handler(req, { env: { DB: {} }, userId: "u1", email: "[email protected]", params })+ : handler(req, { env: { DB: {} }, params })},}))@@ -74,6 +77,7 @@ describe("GET /api/community/invites/[token]/info", () => {mockGetInviteByToken.mockResolvedValue({id: "inv_1",serverId: "s1",+ createdBy: "u_inviter",expiresAt: null,maxUses: null,uses: 0,@@ -84,9 +88,12 @@ describe("GET /api/community/invites/[token]/info", () => {icon: null,description: "A place",})+ mockCountMembers.mockResolvedValue(3)+ mockListMembers.mockResolvedValue([])+ mockGetUsersByIds.mockResolvedValue([{ id: "u_inviter", name: "Gus", image: null }])})- it("returns memberCount resolved via countMembers, never listMembers", async () => {+ it("returns memberCount resolved via countMembers", async () => {mockCountMembers.mockResolvedValue(42)const res = await GET(req(), ctx())@@ -97,24 +104,75 @@ describe("GET /api/community/invites/[token]/info", () => {expect(mockCountMembers).toHaveBeenCalledTimes(1)expect(mockCountMembers).toHaveBeenCalledWith(expect.anything(), "s1")- expect(mockListMembers).not.toHaveBeenCalled()})- it("returns 401 for anonymous callers", async () => {+ it("serves anonymous callers the same payload (preview-first, no 401)", async () => {isAuthed = falseconst res = await GET(req(), ctx())- expect(res.status).toBe(401)- expect(mockGetInviteByToken).not.toHaveBeenCalled()+ expect(res.status).toBe(200)+ // Token is still the capability — the handler ran and resolved the invite.+ expect(mockGetInviteByToken).toHaveBeenCalledWith(expect.anything(), "tok_1")+ const body = await res.json() as { serverName: string }+ expect(body.serverName).toBe("Server One")})- it("returns 200 with no serverDescription key for authed callers", async () => {- mockCountMembers.mockResolvedValue(3)+ it("still rejects an invalid token for anonymous callers (token gate intact)", async () => {+ isAuthed = false+ mockGetInviteByToken.mockResolvedValue(null)+ const res = await GET(req(), ctx())+ expect(res.status).toBe(404)+ })++ it("exposes serverDescription for the landing page", async () => {const res = await GET(req(), ctx())expect(res.status).toBe(200)- const body = await res.json() as Record<string, unknown>- expect(body).not.toHaveProperty("serverDescription")+ const body = await res.json() as { serverDescription: string; serverName: string }+ expect(body.serverDescription).toBe("A place")expect(body.serverName).toBe("Server One")- expect(body.memberCount).toBe(3)+ })++ it("defaults serverDescription to empty string when the server has none", async () => {+ mockGetServer.mockResolvedValue({ id: "s1", name: "Server One", icon: null, description: null })+ const res = await GET(req(), ctx())+ const body = await res.json() as { serverDescription: string }+ expect(body.serverDescription).toBe("")+ })++ it("resolves the inviter from invite.createdBy", async () => {+ mockGetUsersByIds.mockResolvedValue([{ id: "u_inviter", name: "Gus", image: "user-avatar/u_inviter" }])+ const res = await GET(req(), ctx())+ const body = await res.json() as { inviter: { name: string; avatar: string } | null }+ expect(mockGetUsersByIds).toHaveBeenCalledWith(expect.anything(), ["u_inviter"])+ expect(body.inviter).toEqual({ id: "u_inviter", name: "Gus", avatar: "user-avatar/u_inviter" })+ })++ it("returns inviter=null when createdBy is null (pruned/legacy invite)", async () => {+ mockGetInviteByToken.mockResolvedValue({+ id: "inv_1", serverId: "s1", createdBy: null, expiresAt: null, maxUses: null, uses: 0,+ })+ const res = await GET(req(), ctx())+ const body = await res.json() as { inviter: unknown }+ expect(body.inviter).toBeNull()+ expect(mockGetUsersByIds).not.toHaveBeenCalled()+ })++ it("previews up to 5 member avatars (id + avatar only, no names) with image-or-initial fallback", async () => {+ mockListMembers.mockResolvedValue([+ { userId: "a", userName: "Ann", userImage: "user-avatar/a" },+ { userId: "b", userName: "Bob", userImage: null },+ { userId: "c", userName: "Cy", userImage: null },+ { userId: "d", userName: "Di", userImage: null },+ { userId: "e", userName: "Ed", userImage: null },+ { userId: "f", userName: "Fi", userImage: null },+ ])+ const res = await GET(req(), ctx())+ const body = await res.json() as { memberPreview: { id: string; avatar: string }[] }+ expect(body.memberPreview).toHaveLength(5)+ // Names are intentionally NOT exposed — only id + avatar.+ expect(body.memberPreview[0]).toEqual({ id: "a", avatar: "user-avatar/a" })+ // no image → single-letter initial fallback+ expect(body.memberPreview[1]).toEqual({ id: "b", avatar: "B" })+ expect(body.memberPreview[0]).not.toHaveProperty("name")})it("maps server.icon (R2 key) through serverIconUrl into a routable URL", async () => {@@ -124,7 +182,6 @@ describe("GET /api/community/invites/[token]/info", () => {icon: "server-icon/s1/abc",description: "",})- mockCountMembers.mockResolvedValue(1)const res = await GET(req(), ctx())const body = await res.json() as { serverIcon: string | null }diff --git a/src/web/src/app/api/community/invites/[token]/info/route.ts b/src/web/src/app/api/community/invites/[token]/info/route.tsindex 1da1ccbdc..fca5febd7 100644--- a/src/web/src/app/api/community/invites/[token]/info/route.ts+++ b/src/web/src/app/api/community/invites/[token]/info/route.ts@@ -1,13 +1,21 @@-import { withAuth } from "@/lib/middleware/auth"+import { withOptionalAuth } from "@/lib/middleware/auth"import { writeJSON, writeError } from "@/lib/middleware/helpers"import { getDb } from "@/lib/db"import { queries } from "@alook/shared"import { serverIconUrl } from "@/lib/community/storage"+import { avatarInitial } from "@/lib/community/avatar"-// Requires a logged-in caller: invite unfurls used to be public but that-// leaked server metadata to anyone with a token. `withAuth` gates it; the-// invite token remains the accept-side capability.-export const GET = withAuth(async (_req, ctx) => {+// How many member avatars the landing page previews. A small strip ("who's+// already here") + the total count reads warmer than a bare number; the client+// summarizes the rest as "+N" from `memberCount`.+const MEMBER_PREVIEW_LIMIT = 5++// Viewable logged-in OR anonymous — the invite landing page loads before any+// login (preview-first journey), so `withOptionalAuth` never 401s on a missing+// session. The invite token stays the sole capability: an invalid/expired token+// is still rejected below (404/410). Every field returned is the same for any+// caller (no per-viewer projection), so the handler ignores `ctx.userId`.+export const GET = withOptionalAuth(async (_req, ctx) => {const token = ctx.params?.tokenif (!token) return writeError("missing token", 400)@@ -29,10 +37,38 @@ export const GET = withAuth(async (_req, ctx) => {const memberCount = await queries.communityMember.countMembers(db, invite.serverId)+ // Inviter ("Invited by …") — resolved server-side in this same request. The+ // FK is `set null` on user delete, so `createdBy` may be null (legacy/pruned+ // invites); the field is then simply null and the client omits the line.+ const inviter = invite.createdBy+ ? (await queries.user.getUsersByIds(db, [invite.createdBy]))[0] ?? null+ : null++ // Member-avatar strip — a handful of faces reads warmer than a bare count.+ // `listMembers` is unpaginated; slice to the preview cap. Same+ // `image ?? initial` fallback the member-list projection uses.+ //+ // Names are deliberately NOT exposed here (product call): the preview is a+ // face strip for warmth, not a roster. Since a server has no public/private+ // flag and invite tokens are forwardable, dropping names keeps a token holder+ // from harvesting who's in the server by name. The avatar is a photo URL or a+ // single-letter initial (derived server-side); the initial never ships the+ // full name.+ const members = await queries.communityMember.listMembers(db, invite.serverId)+ const memberPreview = members.slice(0, MEMBER_PREVIEW_LIMIT).map((m) => ({+ id: m.userId,+ avatar: m.userImage ?? avatarInitial(m.userName),+ }))+return writeJSON({serverId: invite.serverId,serverName: server.name,serverIcon: serverIconUrl(server),+ serverDescription: server.description ?? "",memberCount,+ memberPreview,+ inviter: inviter+ ? { id: inviter.id, name: inviter.name, avatar: inviter.image ?? avatarInitial(inviter.name) }+ : null,})})diff --git a/src/web/src/app/c/invite/[token]/invite-accept-client.tsx b/src/web/src/app/c/invite/[token]/invite-accept-client.tsxindex aa477249b..50c0dff93 100644--- a/src/web/src/app/c/invite/[token]/invite-accept-client.tsx+++ b/src/web/src/app/c/invite/[token]/invite-accept-client.tsx@@ -1,19 +1,33 @@"use client"-import { useEffect, useState } from "react"-import { useRouter } from "next/navigation"+import { useCallback, useEffect, useRef, useState } from "react"+import { useRouter, useSearchParams } from "next/navigation"import { toast } from "sonner"+import { CircleAlert } from "lucide-react"import { Button } from "@/components/ui/button"import { avatarInitial } from "@/lib/community/avatar"import { Skeleton } from "@/components/ui/skeleton"-import { useQueryClient } from "@tanstack/react-query"import { apiFetch } from "@/lib/api/client"-import { communityKeys } from "@/lib/query-keys"+import { ApiError } from "@/lib/errors"+import { ServerIcon } from "@/components/community/server-icon"+import { Avatar } from "@/components/community/avatar"type InviteInfo = {+ serverId: stringserverName: stringserverIcon: string | null+ serverDescription: stringmemberCount: number+ memberPreview: { id: string; avatar: string }[]+ inviter: { id: string; name: string; avatar: string } | null+}++// The invite is dead (revoked / expired / used up) vs. merely unreachable. A+// 404/410 is a definitively-gone link — worth its own "this has expired" copy+// so the user asks for a fresh one instead of retrying; anything else is a+// generic failure.+function isDeadInvite(err: unknown): boolean {+ return err instanceof ApiError && (err.status === 404 || err.status === 410)}/**@@ -22,11 +36,11 @@ type InviteInfo = {*/export function InviteAcceptClient({ token }: { token: string }) {const router = useRouter()- const queryClient = useQueryClient()+ const searchParams = useSearchParams()const [info, setInfo] = useState<InviteInfo | null>(null)const [loading, setLoading] = useState(true)const [joining, setJoining] = useState(false)- const [error, setError] = useState<string | null>(null)+ const [error, setError] = useState<{ message: string; dead: boolean } | null>(null)useEffect(() => {async function fetchInfo() {@@ -35,7 +49,7 @@ export function InviteAcceptClient({ token }: { token: string }) {setInfo(data)} catch (err: unknown) {const message = err instanceof Error ? err.message : "This invite is no longer valid"- setError(message)+ setError({ message, dead: isDeadInvite(err) })} finally {setLoading(false)}@@ -43,89 +57,163 @@ export function InviteAcceptClient({ token }: { token: string }) {fetchInfo()}, [token])- const handleJoin = async () => {+ const handleJoin = useCallback(async () => {setJoining(true)+ // Raw fetch (not the shared `apiFetch`): apiFetch has a GLOBAL 401 handler+ // that hard-navigates to a bare `/sign-in` (no redirect param) before we+ // can react — which would drop the visitor at the default post-login page+ // (/workspaces → /studio/new) instead of back here. Preview-first needs the+ // 401 to route to sign-in WITH a return path, so we handle status ourselves.try {- const result = await apiFetch<{ serverId: string }>(`/api/community/invites/${token}/join`, {+ const res = await fetch(`/api/community/invites/${token}/join`, {method: "POST",+ credentials: "include",+ headers: { "Content-Type": "application/json" },})++ // Not signed in → bounce to sign-in carrying an `autojoin=1` return path+ // so the join resumes automatically once they're back. The visitor clicks+ // Join exactly once.+ if (res.status === 401) {+ const returnTo = `/c/invite/${token}?autojoin=1`+ router.push(`/sign-in?redirect=${encodeURIComponent(returnTo)}`)+ return+ }++ if (!res.ok) {+ const body = (await res.json().catch(() => null)) as { error?: string } | null+ toast(body?.error || "Couldn't join the server — try the invite again")+ setJoining(false)+ return+ }++ const result = (await res.json()) as { serverId: string }toast("Joined server")- // Refresh the server list before navigating so the rail shows the newly- // joined server on arrival instead of the user having to refresh.- await queryClient.invalidateQueries({ queryKey: communityKeys.servers() })+ // Navigate into the joined server. This page renders standalone (outside+ // CommunityShell / its QueryProvider), so there's no community query cache+ // to invalidate here — arriving at /c/channels mounts the shell fresh and+ // its server list fetches on mount.router.push(`/c/channels/${result.serverId}`)- } catch (err: unknown) {- const message = err instanceof Error ? err.message : "Couldn't join the server — try the invite again"- toast(message)+ } catch {+ toast("Couldn't join the server — try the invite again")setJoining(false)}- }+ }, [token, router])++ // Returning from the login wall (`?autojoin=1`) → resume the Join the visitor+ // already clicked. A ref latch fires it EXACTLY once per landing: a bare+ // `!joining` guard isn't enough because `info`'s reference can change (a+ // refetch / parent re-render) and re-run the effect before `joining` state+ // has settled, double-firing the join (a real member-row insert). The ref+ // flips synchronously on first fire and never resets, so re-renders are inert.+ const autojoin = searchParams.get("autojoin") === "1"+ const autojoinFired = useRef(false)+ useEffect(() => {+ if (autojoin && info && !autojoinFired.current) {+ autojoinFired.current = true+ handleJoin()+ }+ }, [autojoin, info, handleJoin])if (loading) {return (- <div className="flex min-h-screen items-center justify-center bg-background px-4">- <div className="w-full max-w-sm rounded-xl border border-border bg-card p-8 shadow-(--e2)">- <Skeleton className="mx-auto size-20 rounded-full" />- <Skeleton className="mx-auto mt-4 h-3 w-32 rounded" />- <Skeleton className="mx-auto mt-3 h-5 w-48 rounded" />- <Skeleton className="mx-auto mt-2 h-3 w-24 rounded" />- <Skeleton className="mt-6 h-9 w-full rounded-md" />- </div>- </div>+ <Shell>+ <Skeleton className="size-21 rounded-2xl" />+ <Skeleton className="mt-5 h-3 w-32 rounded" />+ <Skeleton className="mt-3 h-7 w-48 rounded" />+ <Skeleton className="mt-4 h-4 w-64 rounded" />+ <Skeleton className="mt-6 h-11 w-full rounded-xl" />+ </Shell>)}if (error) {return (- <div className="flex min-h-screen flex-col items-center justify-center gap-4 bg-background px-4">- <div className="max-w-sm rounded-xl border border-border bg-card p-8 text-center shadow-(--e2)">- <h1 className="text-xl font-semibold">This invite isn't working</h1>- <p className="mt-2 text-sm text-muted-foreground">{error}</p>- <p className="mt-1 text-xs text-muted-foreground">Ask whoever shared it for a fresh link.</p>- <Button- className="mt-6"- variant="secondary"- onClick={() => router.push("/c/me")}- >- Back to community- </Button>+ <Shell>+ <div className="grid size-16 place-items-center rounded-full bg-destructive/10 text-destructive">+ <CircleAlert className="size-7" /></div>- </div>+ <h1 className="mt-5 text-2xl font-semibold">+ {error.dead ? "This invite has expired" : "This invite isn't working"}+ </h1>+ <p className="mt-2 text-sm text-muted-foreground">+ {error.dead+ ? "Invite links can run out or be turned off. Ask whoever shared it for a fresh one."+ : error.message}+ </p>+ <Button className="mt-6" variant="secondary" onClick={() => router.push("/c/me")}>+ Back to Alook+ </Button>+ </Shell>)}return (- <div className="flex min-h-screen flex-col items-center justify-center gap-4 bg-background px-4">- <div className="max-w-sm rounded-xl border border-border bg-card p-8 text-center shadow-(--e2)">- {/* Server icon / initial */}- <div className="mx-auto mb-4 grid size-20 place-items-center rounded-full bg-muted">- {info?.serverIcon ? (- <img src={info.serverIcon} alt={info.serverName} className="size-20 rounded-full object-cover" />- ) : (- <span className="text-3xl font-semibold text-muted-foreground">- {info ? avatarInitial(info.serverName) : "?"}- </span>- )}+ <Shell>+ {info && (+ <ServerIcon+ id={info.serverId}+ name={info.serverName}+ initial={avatarInitial(info.serverName)}+ icon={info.serverIcon}+ size={84}+ className="rounded-2xl"+ />+ )}++ <p className="mt-5 text-xs font-medium text-muted-foreground">You're invited to join</p>+ <h1 className="mt-1 font-brand text-4xl leading-tight font-bold">{info?.serverName}</h1>++ {info?.serverDescription && (+ <p className="mt-3 max-w-xs text-sm leading-relaxed text-muted-foreground">{info.serverDescription}</p>+ )}++ {info?.inviter && (+ <div className="mt-4 flex items-center gap-1.5 text-sm text-muted-foreground">+ <span>Invited by</span>+ <Avatar label={info.inviter.avatar} seed={info.inviter.id} size={20} />+ <span className="font-medium text-foreground">{info.inviter.name}</span></div>+ )}- {/* Server info */}- <p className="text-xs font-medium text-muted-foreground">You're invited to join</p>- <h1 className="mt-1 text-2xl font-semibold">{info?.serverName}</h1>- {info?.memberCount != null && (- <p className="mt-2 text-xs text-muted-foreground">+ <Button className="mt-6 h-11 w-full rounded-xl text-base" onClick={handleJoin} disabled={joining}>+ {joining ? "Joining…" : "Join server"}+ </Button>++ {/* Members footer — avatar strip + count below the CTA as a quiet+ "who's already here" footer (no divider), then the reassurance line. */}+ {info && info.memberCount > 0 && (+ <div className="mt-4 flex items-center gap-2 text-xs text-muted-foreground">+ {info.memberPreview.length > 0 && (+ <div className="flex items-center -space-x-1.5">+ {info.memberPreview.map((m) => (+ <Avatar key={m.id} label={m.avatar} seed={m.id} size={20} ringColor="var(--background)" />+ ))}+ {info.memberCount > info.memberPreview.length && (+ <span className="z-10 grid h-5 min-w-5 place-items-center rounded-full bg-muted px-1 pb-1 text-[0.825rem] font-bold leading-none text-muted-foreground ring-2 ring-background">+ …+ </span>+ )}+ </div>+ )}+ <span>{info.memberCount} {info.memberCount === 1 ? "member" : "members"}- </p>- )}-- {/* Join button */}- <Button- className="mt-6 w-full"- onClick={handleJoin}- disabled={joining}- >- {joining ? "Joining…" : "Join server"}- </Button>- </div>+ </span>+ </div>+ )}++ <p className="mt-3 text-xs text-muted-foreground">Free to join · leave anytime</p>+ </Shell>+ )+}++// Frameless landing shell — full-screen centered content, no floating card+// (the old bordered `bg-card` box). Everything the flow renders (loading /+// error / ready) shares this frame so the layout doesn't shift between states.+function Shell({ children }: { children: React.ReactNode }) {+ return (+ <div className="flex min-h-screen flex-col items-center justify-center bg-background px-6 text-center">+ <div className="flex w-full max-w-sm flex-col items-center">{children}</div></div>)}diff --git a/src/web/src/app/c/layout.tsx b/src/web/src/app/c/layout.tsxindex d61cc781c..e03c3ffac 100644--- a/src/web/src/app/c/layout.tsx+++ b/src/web/src/app/c/layout.tsx@@ -1,24 +1,40 @@"use client"import { useEffect } from "react"-import { useRouter } from "next/navigation"+import { usePathname, useRouter } from "next/navigation"import { useSession } from "@/lib/auth-client"import { CommunityShell } from "./community-shell"import { avatarInitial } from "@/lib/community/avatar"+// The invite landing page is preview-first: a logged-out visitor must be able+// to see it (and only hit the login wall on Join). It's a standalone+// full-screen page that doesn't use CommunityShell (which requires a+// logged-in user), so it's exempt from this layout's session gate AND the+// shell — its own middleware exemption keeps the server side public. Mirrors+// the `PUBLIC_PREFIXES` guard in `middleware.ts`; both gates must agree.+function isPublicCommunityPath(pathname: string): boolean {+ return pathname.startsWith("/c/invite/")+}+export default function CommunityLayout({children,}: {children: React.ReactNode}) {const router = useRouter()+ const pathname = usePathname()+ const isPublic = isPublicCommunityPath(pathname)const { data: session, isPending } = useSession()useEffect(() => {- if (!isPending && !session) {+ if (!isPublic && !isPending && !session) {router.replace("/sign-in")}- }, [isPending, session, router])+ }, [isPublic, isPending, session, router])++ // Public community pages (invite landing) render standalone — no session+ // gate, no CommunityShell (a logged-out visitor has no currentUser).+ if (isPublic) return <>{children}</>if (isPending || !session) return nulldiff --git a/src/web/src/lib/middleware/auth.test.ts b/src/web/src/lib/middleware/auth.test.tsindex 8e3ad4daa..3bab2c49a 100644--- a/src/web/src/lib/middleware/auth.test.ts+++ b/src/web/src/lib/middleware/auth.test.ts@@ -25,7 +25,7 @@ vi.mock("@/lib/auth", () => ({})),}));-import { withAuth, warmMachineTokenCache } from "./auth";+import { withAuth, withOptionalAuth, warmMachineTokenCache } from "./auth";import { queries } from "@alook/shared";const mockGetMachineTokenByHash = queries.machineToken@@ -352,6 +352,111 @@ describe("withAuth middleware", () => {});});+describe("withOptionalAuth middleware", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ mockGetCloudflareContext.mockResolvedValue({ env: { DB: {} } });+ });++ const wrapped = withOptionalAuth(testHandler);++ it("runs the handler anonymously (userId undefined, NOT 401) when there is no session", async () => {+ mockGetSession.mockResolvedValue({ headers: new Headers(), response: null });++ const req = new NextRequest("http://localhost/api/test");+ const res = await wrapped(req);+ const body = await res.json();++ expect(res.status).toBe(200);+ expect(body.ok).toBe(true);+ expect(body.ctx.userId).toBeUndefined();+ expect(testHandler).toHaveBeenCalledOnce();+ });++ it("passes userId/email when a valid session is present", async () => {+ mockGetSession.mockResolvedValue({+ headers: new Headers(),+ response: { user: { id: "user-1", email: "[email protected]" } },+ });++ const req = new NextRequest("http://localhost/api/test");+ const res = await wrapped(req);+ const body = await res.json();++ expect(res.status).toBe(200);+ expect(body.ctx.userId).toBe("user-1");+ expect(body.ctx.email).toBe("[email protected]");+ });++ it("degrades a soft-deleted session to anonymous (NOT 401) and still runs the handler", async () => {+ mockGetSession.mockResolvedValue({+ headers: new Headers(),+ response: { user: { id: "user-x", email: "[email protected]", isBot: false, deletedAt: "2026-07-29T00:00:00.000Z" } },+ });++ const req = new NextRequest("http://localhost/api/test");+ const res = await wrapped(req);+ const body = await res.json();++ expect(res.status).toBe(200);+ expect(body.ctx.userId).toBeUndefined();+ expect(testHandler).toHaveBeenCalledOnce();+ });++ it("degrades a bot session to anonymous (NOT 401)", async () => {+ mockGetSession.mockResolvedValue({+ headers: new Headers(),+ response: { user: { id: "bot-1", email: "[email protected]", isBot: true, deletedAt: null } },+ });++ const req = new NextRequest("http://localhost/api/test");+ const res = await wrapped(req);+ const body = await res.json();++ expect(res.status).toBe(200);+ expect(body.ctx.userId).toBeUndefined();+ expect(testHandler).toHaveBeenCalledOnce();+ });++ it("degrades to anonymous (NOT 503) when getSession throws on both attempts — page is public-readable, fail open", async () => {+ mockGetSession.mockRejectedValue(new Error("better-auth down"));++ const req = new NextRequest("http://localhost/api/test");+ const res = await wrapped(req);+ const body = await res.json();++ expect(res.status).toBe(200);+ expect(body.ctx.userId).toBeUndefined();+ expect(testHandler).toHaveBeenCalledOnce();+ });++ it("does NOT consult the machine-token path — an al_ bearer is ignored, session resolves anonymous", async () => {+ mockGetSession.mockResolvedValue({ headers: new Headers(), response: null });++ const req = new NextRequest("http://localhost/api/test", {+ headers: { Authorization: "Bearer al_secret_token" },+ });+ const res = await wrapped(req);+ const body = await res.json();++ expect(res.status).toBe(200);+ expect(body.ctx.userId).toBeUndefined();+ // The optional wrapper never touches the machine-token D1 lookup.+ expect(mockGetMachineTokenByHash).not.toHaveBeenCalled();+ });++ it("resolves dynamic params from context", async () => {+ mockGetSession.mockResolvedValue({ headers: new Headers(), response: null });++ const req = new NextRequest("http://localhost/api/test");+ const res = await wrapped(req, { params: Promise.resolve({ token: "t1" }) });+ const body = await res.json();++ expect(res.status).toBe(200);+ expect(body.ctx.params).toEqual({ token: "t1" });+ });+});+describe("warmMachineTokenCache", () => {beforeEach(() => vi.clearAllMocks());diff --git a/src/web/src/lib/middleware/auth.ts b/src/web/src/lib/middleware/auth.tsindex cd0047754..bec55a5b4 100644--- a/src/web/src/lib/middleware/auth.ts+++ b/src/web/src/lib/middleware/auth.ts@@ -20,6 +20,24 @@ export interface AuthContext {user?: { isBot: boolean }}+/**+ * Context for a `withOptionalAuth` handler: identical to `AuthContext` but+ * `userId`/`email` are OPTIONAL — absent when the caller is anonymous (no+ * session, an errored session lookup, or a bot/deleted session degraded to+ * anonymous). A distinct interface so `AuthContext.userId` stays required and+ * no existing `withAuth` handler is disturbed.+ *+ * Not exported: handlers infer this shape from `OptionalAuthHandler`, so no+ * caller imports it by name yet. Export it once a handler needs the type+ * standalone (as `AuthContext` is, because withAuth handlers import it).+ */+interface OptionalAuthContext {+ env: Env+ userId?: string+ email?: string+ user?: { isBot: boolean }+}+/*** Merged machine-token cache entry. One KV read per authenticated request* yields BOTH the token-validation result (`row`) and the last-used bump@@ -74,6 +92,103 @@ export type AuthenticatedHandler = (ctx: AuthContext & { params?: Record<string, string> }) => Promise<NextResponse | Response>+export type OptionalAuthHandler = (+ req: NextRequest,+ ctx: OptionalAuthContext & { params?: Record<string, string> }+) => Promise<NextResponse | Response>++/**+ * Outcome of resolving a Better-Auth cookie session. Shared by `withAuth`+ * (which turns everything but `ok` into a 401/503) and `withOptionalAuth`+ * (which turns everything but `ok` into anonymous). Keeping the resolution in+ * ONE place means the two wrappers can never drift on session semantics — only+ * on what they DO with a non-`ok` outcome.+ *+ * - `ok` — a valid, non-bot, non-deleted session; `user` is populated.+ * - `error` — getSession threw on both attempts (transient infra failure).+ * - `none` — no session cookie / no session.+ * - `invalid` — a session for a bot or soft-deleted user; `signOut` was+ * attempted best-effort and the caller should clear cookies.+ */+type SessionResolution =+ | {+ kind: "ok"+ user: { id: string; email: string; isBot: boolean }+ setCookies: string[]+ }+ | { kind: "error" }+ | { kind: "none" }+ | { kind: "invalid" }++async function resolveSession(+ req: NextRequest,+ cloudflareEnv: Env,+): Promise<SessionResolution> {+ const auth = createAuth(cloudflareEnv)+ let sessionResult: { headers: Headers; response: Awaited<ReturnType<typeof auth.api.getSession>> } | null = null+ let lastErr: unknown++ for (let attempt = 0; attempt < 2; attempt++) {+ try {+ sessionResult = await auth.api.getSession({+ headers: req.headers,+ returnHeaders: true,+ }) as { headers: Headers; response: Awaited<ReturnType<typeof auth.api.getSession>> }+ lastErr = undefined+ break+ } catch (err) {+ lastErr = err+ }+ }++ if (lastErr) return { kind: "error" }+ if (!sessionResult?.response) return { kind: "none" }++ // Session guard — Better-Auth's Drizzle adapter reads user rows via+ // .select() directly, so a session cookie may carry stale state after a+ // user is soft-deleted or if some future flow ever mints a session for a+ // bot user row. Enforce at request-time:+ // - deletedAt != null → session invalid+ // - isBot === true → session invalid (bots must never sign in)+ // Belt-and-braces with the databaseHooks.session.create.before hook.+ // isBot/deletedAt ride the session user via better-auth `additionalFields`+ // (see auth.ts) — no dedicated per-request `getUserInternal` D1 read. Their+ // freshness = the session cookie-cache period (prod 5min); revocation+ // latency is therefore bounded by that window and is NOT loosened beyond+ // today's getSession cookie cache. (Bots never mint a session — the+ // session.create hook blocks them — so the isBot check is belt-and-braces;+ // deletedAt is the one with a real, ≤cookie-period latency.)+ const guardUser = sessionResult.response.user as { isBot?: boolean | null; deletedAt?: string | null }+ const sessionUserIsBot = guardUser.isBot === true+ if (sessionUserIsBot || (guardUser.deletedAt ?? null) !== null) {+ // Best-effort server-side invalidation. The caller clears cookies on its+ // response; Better-Auth will see the missing session next request.+ try {+ await auth.api.signOut({ headers: req.headers })+ } catch {+ // ignore — signOut best-effort+ }+ return { kind: "invalid" }+ }++ return {+ kind: "ok",+ user: {+ id: sessionResult.response.user.id,+ email: sessionResult.response.user.email,+ isBot: sessionUserIsBot,+ },+ setCookies: sessionResult.headers.getSetCookie(),+ }+}++// Clear known Better-Auth cookie names on a response to prevent replay of a+// session that the request-time guard rejected.+function clearAuthCookies(res: NextResponse): void {+ res.cookies.set("better-auth.session_token", "", { maxAge: 0, path: "/" })+ res.cookies.set("better-auth.session_data", "", { maxAge: 0, path: "/" })+}+export function withAuth(handler: AuthenticatedHandler) {return async (req: NextRequest,@@ -172,78 +287,104 @@ export function withAuth(handler: AuthenticatedHandler) {}// Fall back to Better Auth session (with returnHeaders to propagate cookie cache refresh)- const auth = createAuth(cloudflareEnv)- let sessionResult: { headers: Headers; response: Awaited<ReturnType<typeof auth.api.getSession>> } | null = null- let lastErr: unknown-- for (let attempt = 0; attempt < 2; attempt++) {- try {- sessionResult = await auth.api.getSession({- headers: req.headers,- returnHeaders: true,- }) as { headers: Headers; response: Awaited<ReturnType<typeof auth.api.getSession>> }- lastErr = undefined- break- } catch (err) {- lastErr = err- }- }+ const session = await resolveSession(req, cloudflareEnv)- if (lastErr) {+ if (session.kind === "error") {return NextResponse.json({ error: "session validation failed" }, { status: 503 })}- if (!sessionResult?.response) {+ if (session.kind === "none") {return NextResponse.json({ error: "unauthorized" }, { status: 401 })}-- // Session guard — Better-Auth's Drizzle adapter reads user rows via- // .select() directly, so a session cookie may carry stale state after a- // user is soft-deleted or if some future flow ever mints a session for a- // bot user row. Enforce at request-time:- // - deletedAt != null → session invalid- // - isBot === true → session invalid (bots must never sign in)- // Belt-and-braces with the databaseHooks.session.create.before hook.- // isBot/deletedAt ride the session user via better-auth `additionalFields`- // (see auth.ts) — no dedicated per-request `getUserInternal` D1 read. Their- // freshness = the session cookie-cache period (prod 5min); revocation- // latency is therefore bounded by that window and is NOT loosened beyond- // today's getSession cookie cache. (Bots never mint a session — the- // session.create hook blocks them — so the isBot check is belt-and-braces;- // deletedAt is the one with a real, ≤cookie-period latency.)- const guardUser = sessionResult.response.user as { isBot?: boolean | null; deletedAt?: string | null }- const sessionUserIsBot = guardUser.isBot === true- if (sessionUserIsBot || (guardUser.deletedAt ?? null) !== null) {- // Best-effort server-side invalidation. Cookie clear happens via the- // 401 response below; Better-Auth will see the missing session next- // request.- try {- await auth.api.signOut({ headers: req.headers })- } catch {- // ignore — signOut best-effort- }+ if (session.kind === "invalid") {const invalid = NextResponse.json({ error: "session no longer valid" },{ status: 401 },)- // Clear known Better-Auth cookie names to prevent replay.- invalid.cookies.set("better-auth.session_token", "", { maxAge: 0, path: "/" })- invalid.cookies.set("better-auth.session_data", "", { maxAge: 0, path: "/" })+ clearAuthCookies(invalid)return invalid}const authCtx: AuthContext = {env: cloudflareEnv,- userId: sessionResult.response.user.id,- email: sessionResult.response.user.email,- user: { isBot: sessionUserIsBot },+ userId: session.user.id,+ email: session.user.email,+ user: { isBot: session.user.isBot },+ }+ const res = await handler(req, { ...authCtx, params: resolvedParams })++ // Forward Set-Cookie headers from Better Auth to refresh session_data cookie cache+ if (session.setCookies.length > 0) {+ const mutableRes = new NextResponse(res.body, res)+ for (const cookie of session.setCookies) {+ mutableRes.headers.append("Set-Cookie", cookie)+ }+ return mutableRes+ }++ return res+ }+}++/**+ * Session-optional wrapper for pages that render the SAME content whether or+ * not the visitor is logged in (e.g. the invite landing page). Unlike+ * `withAuth`, it NEVER 401s on a missing session — the handler always runs.+ *+ * Red lines (Cecilia, /Gus/working #1131 #1 / #1147):+ * 1. Single-purpose: resolves the Better-Auth cookie session ONLY. It does NOT+ * read the machine-token / bot `al_...` bearer path — that is `withAuth`'s+ * private concern; a daemon/bot is not a use case for an optional-login page.+ * 2. Never 401 for auth reasons. Missing session → anonymous. A bot/deleted+ * session degrades to anonymous (cookies cleared best-effort) rather than+ * blocking. A transient getSession failure also degrades to anonymous — the+ * page is public-readable, so failing open is correct here.+ * 3. It only answers "who are you (or anonymous)". What data a route exposes is+ * the route's decision; this wrapper carries no disclosure logic, so it is+ * reusable by any future login-optional page.+ */+export function withOptionalAuth(handler: OptionalAuthHandler) {+ return async (+ req: NextRequest,+ context?: { params?: Promise<Record<string, string>> | Record<string, string> }+ ) => {+ const resolvedParams = context?.params+ ? context.params instanceof Promise+ ? await context.params+ : context.params+ : undefined++ const { env } = await getCloudflareContext({ async: true })+ const cloudflareEnv = env as Env+ bindCacheKV(cloudflareEnv.CACHE_KV ?? null)++ const session = await resolveSession(req, cloudflareEnv)++ // Anonymous context for every non-`ok` outcome — the defining difference+ // from withAuth. `invalid` (bot/deleted session) additionally clears the+ // stale cookies on the way out so the bad session doesn't linger.+ if (session.kind !== "ok") {+ const anonCtx: OptionalAuthContext = { env: cloudflareEnv }+ const res = await handler(req, { ...anonCtx, params: resolvedParams })+ if (session.kind === "invalid") {+ const mutableRes = new NextResponse(res.body, res)+ clearAuthCookies(mutableRes)+ return mutableRes+ }+ return res+ }++ const authCtx: OptionalAuthContext = {+ env: cloudflareEnv,+ userId: session.user.id,+ email: session.user.email,+ user: { isBot: session.user.isBot },}const res = await handler(req, { ...authCtx, params: resolvedParams })// Forward Set-Cookie headers from Better Auth to refresh session_data cookie cache- const setCookies = sessionResult.headers.getSetCookie()- if (setCookies.length > 0) {+ if (session.setCookies.length > 0) {const mutableRes = new NextResponse(res.body, res)- for (const cookie of setCookies) {+ for (const cookie of session.setCookies) {mutableRes.headers.append("Set-Cookie", cookie)}return mutableResdiff --git a/src/web/src/middleware.test.ts b/src/web/src/middleware.test.tsindex 67003e6fd..857b37985 100644--- a/src/web/src/middleware.test.ts+++ b/src/web/src/middleware.test.ts@@ -83,6 +83,24 @@ describe("middleware", () => {expect(res.headers.get("location")).toBeNull();expect(mockGetSession).not.toHaveBeenCalled();});++ it("serves /c/invite/<token> anonymously (preview-first, no login wall)", async () => {+ // The invite landing page is public even though it's under /c/ — a+ // logged-out visitor must SEE the invite and only hit login on Join.+ const req = makeReq("https://app.com/c/invite/tok_1", { "x-forwarded-proto": "https" });+ const res = await middleware(req);+ expect(res.headers.get("location")).toBeNull();+ expect(mockGetSession).not.toHaveBeenCalled();+ });++ it("still gates the rest of /c/ (the public exemption is scoped to /c/invite/)", async () => {+ mockGetSession.mockResolvedValue({ headers: new Headers(), response: null });+ const req = makeReq("https://app.com/c/channels/s1", { "x-forwarded-proto": "https" });+ const res = await middleware(req);+ const loc = new URL(res.headers.get("location")!);+ expect(loc.pathname).toBe("/sign-in");+ expect(loc.searchParams.get("redirect")).toBe("/c/channels/s1");+ });});describe("sign-in redirect when already authenticated (isSafeRedirect guard)", () => {@@ -102,25 +120,25 @@ describe("middleware", () => {expect(loc.pathname).toBe("/w/foo");});- it("rejects protocol-relative //evil.com → falls back to /workspaces", async () => {+ it("rejects protocol-relative //evil.com → falls back to /c/me", async () => {const loc = await signInWith("//evil.com");- expect(loc.pathname).toBe("/workspaces");+ expect(loc.pathname).toBe("/c/me");expect(loc.host).toBe("app.com");});- it("rejects absolute https://evil.com → falls back to /workspaces", async () => {+ it("rejects absolute https://evil.com → falls back to /c/me", async () => {const loc = await signInWith("https://evil.com");- expect(loc.pathname).toBe("/workspaces");+ expect(loc.pathname).toBe("/c/me");expect(loc.host).toBe("app.com");});// Regression guard for the open-redirect bug fixed 2026-05-30 (planner approved + applied):// a backslash-prefixed path "/\evil.com" used to pass isSafeRedirect() (starts with "/",// not "//"), and the WHATWG URL parser treats "\" as "/", so it resolved to https://evil.com.- // The guard now rejects any path whose 2nd char is "/" or "\", falling back to /workspaces.- it("rejects backslash /\\evil.com → falls back to /workspaces (open-redirect guard)", async () => {+ // The guard now rejects any path whose 2nd char is "/" or "\", falling back to the default.+ it("rejects backslash /\\evil.com → falls back to /c/me (open-redirect guard)", async () => {const loc = await signInWith("/\\evil.com");- expect(loc.pathname).toBe("/workspaces");+ expect(loc.pathname).toBe("/c/me");expect(loc.host).toBe("app.com");});diff --git a/src/web/src/middleware.ts b/src/web/src/middleware.tsindex 21b35f10f..6bd685fa4 100644--- a/src/web/src/middleware.ts+++ b/src/web/src/middleware.ts@@ -11,6 +11,15 @@ function isSafeRedirect(path: string): boolean {const AUTH_REQUIRED_PREFIXES = ["/invite/", "/w/", "/workspaces", "/dashboard", "/c/"]+// Paths that stay public even though they'd otherwise match an auth-required+// prefix. The invite landing page is preview-first: a logged-out user must be+// able to SEE the invite (server name/icon/description/members) and only hit+// the login wall when they click Join. Its `info` API is `withOptionalAuth`+// and the invite token is the capability, so serving the page anonymously+// leaks nothing gated. Scoped to exactly this path — the rest of `/c/` stays+// gated.+const PUBLIC_PREFIXES = ["/c/invite/"]+export async function middleware(request: NextRequest) {if (request.headers.get("x-forwarded-proto") === "http" &&@@ -23,7 +32,8 @@ export async function middleware(request: NextRequest) {}const { pathname } = request.nextUrl- const needsAuth = pathname === "/c" || AUTH_REQUIRED_PREFIXES.some((p) => pathname.startsWith(p))+ const isPublic = PUBLIC_PREFIXES.some((p) => pathname.startsWith(p))+ const needsAuth = !isPublic && (pathname === "/c" || AUTH_REQUIRED_PREFIXES.some((p) => pathname.startsWith(p)))if (needsAuth) {const { env } = await getCloudflareContext({ async: true })@@ -61,7 +71,9 @@ export async function middleware(request: NextRequest) {const redirect = request.nextUrl.searchParams.get("redirect")const target = redirect && isSafeRedirect(redirect)? new URL(redirect, request.url)- : new URL("/workspaces?auto", request.url)+ // Default landing for an already-signed-in visitor hitting /sign-in:+ // community home. `/workspaces` was the retired legacy (v0) surface.+ : new URL("/c/me", request.url)const res = NextResponse.redirect(target)for (const cookie of result.headers.getSetCookie()) {res.headers.append("Set-Cookie", cookie)