Address code review findings across API, web and deployment
release gate / check (push) Failing after 6m43s

High severity:
- wire TRUSTED_PROXY through Compose/deploy/docs and warn at web startup
- bucket public rate limits on effective client IP, add per-bookmark budget,
  and forward the signed browser identity from the share page
- disable first-run bootstrap in server deployments and document seeding
- serialize last-admin demotion in one advisory-locked transaction

Medium/low:
- cap and batch share recipient inserts
- add a shared outbound budget for preview/CardDAV/IMAP/signal work
- pin CardDAV dials to 443 and bound IMAP logout
- fix rightward kanban column drags and normalize cards on column delete
- classify backend outages in auth guards, add request timeouts and an
  error boundary, remove the dead login route, surface throttling
- enforce pinned/unpinned page reorder grouping server-side
- avoid preview work for stale bookmark versions; drop duplicate dialog fetch
- sequence-guard collection/tag/calendar/quick-find loads
- validate property config and fix MULTI_SELECT/DATE filter inputs
- document index maintenance; apply same-origin check to sign-out
- trim signup names, unique shared dates and kanban keys (migration 010),
  reset reference cache on identity changes, hide OIDC issuer, return 413
  for oversized direct bodies, escape Markdown link destinations
- remove dead template files and duplicate test helper

Verified with go build/vet, full PostgreSQL race suite, db convergence,
tsc, both ESLint configs and a Next production build.
This commit is contained in:
Andrew S Erwin
2026-10-20 00:13:30 -05:00
parent 5eab58f99c
commit 4e421f6ea2
58 changed files with 1419 additions and 333 deletions
+3
View File
@@ -4,6 +4,7 @@ import { useEffect, useState } from 'react'
import { toast } from 'sonner'
import { Eye, Shield } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { resetReferenceCache } from '@/lib/reference-data'
type U = { id: string; name: string | null; email: string; role: string; _count?: { bookmarks: number; pages: number; tags: number } }
@@ -21,6 +22,8 @@ export function AdminClient({ currentUserId }: { currentUserId: string }) {
const viewAs = async (userId: string) => {
const res = await fetch('/api/admin/view-as', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ userId }) })
if (!res.ok) return toast.error('Could not switch account')
// Review L-6: entering view-as changes the effective identity.
resetReferenceCache()
window.location.href = '/pages'
}
+4 -5
View File
@@ -18,17 +18,16 @@ export function BookmarksClient({ initialSearch = null, initialOpen = null }: {
const [selected, setSelected] = useState<Bookmark | null>(null)
// Review CR-04: the sheet must receive the CURRENT row after mutations —
// its conflict banner ("Load latest version") and successful saves need
// the fresh version, or the next save would send a stale base.
const selectedRef = useRef<Bookmark | null>(null)
selectedRef.current = selected
// the fresh version, or the next save would send a stale base. Depend on
// `selected` instead of writing a ref during render.
const refreshSelected = useCallback(async () => {
const id = selectedRef.current?.id
const id = selected?.id
if (!id) return
try {
const res = await fetch(`/api/bookmarks/${encodeURIComponent(id)}`, { cache: 'no-store' })
if (res.ok) setSelected(await res.json())
} catch { /* the list load surfaces errors */ }
}, [])
}, [selected])
const [tab, setTab] = useState<'mine' | 'shared'>('mine')
const [sortField, setSortField] = useState<'title' | 'updatedAt' | 'kanbanStatus'>('updatedAt')
const [sortDir, setSortDir] = useState<'asc' | 'desc'>('desc')
+32 -6
View File
@@ -1,6 +1,6 @@
'use client'
import { useState, useEffect, useCallback, useMemo } from 'react'
import { useState, useEffect, useCallback, useMemo, useRef } from 'react'
import { Button } from '@/components/ui/button'
import { BookmarkCard } from '@/components/bookmark-card'
import { BookmarkDetailSheet } from '@/components/bookmark-detail-sheet'
@@ -11,11 +11,16 @@ import { Input } from '@/components/ui/input'
import { toast } from 'sonner'
import { fetchBookmarks } from '@/lib/bookmarks'
const INITIAL_DATE = new Date(2026, 9, 1)
// Review L-4: a fixed, obviously-not-current placeholder. The real month and
// today are set after mount (to avoid an SSR/client hydration mismatch), and
// the calendar renders a skeleton until then instead of briefly presenting
// this epoch as the current month.
const INITIAL_DATE = new Date(2000, 0, 1)
export function CalendarClient() {
const [currentMonth, setCurrentMonth] = useState<Date>(INITIAL_DATE)
const [today, setToday] = useState<Date>(INITIAL_DATE)
const [ready, setReady] = useState(false)
const [bookmarks, setBookmarks] = useState<Bookmark[]>([])
const [selectedDay, setSelectedDay] = useState<Date | null>(null)
const [selectedBookmark, setSelectedBookmark] = useState<Bookmark | null>(null)
@@ -38,18 +43,25 @@ export function CalendarClient() {
}, [shareQuery])
useEffect(() => {
const timer = setTimeout(() => { const now = new Date(); setCurrentMonth(now); setToday(now) }, 0)
const timer = setTimeout(() => { const now = new Date(); setCurrentMonth(now); setToday(now); setReady(true) }, 0)
return () => clearTimeout(timer)
}, [])
// Review M-11: bookmark-change events and slow initial loads can overlap;
// only the newest pass may publish its data.
const loadSeq = useRef(0)
const load = useCallback(async () => {
const seq = ++loadSeq.current
setLoading(true)
try {
const [mine, shared, dates] = await Promise.all([fetchBookmarks(), fetchBookmarks(new URLSearchParams({ shared: 'true' })), fetch('/api/shared-dates')])
if (seq !== loadSeq.current) return
const sharedDatesJson = dates.ok ? await dates.json() : null
if (seq !== loadSeq.current) return
setBookmarks([...mine, ...shared])
if (dates.ok) setSharedDates(await dates.json())
} catch { toast.error('Could not load calendar') }
finally { setLoading(false) }
if (sharedDatesJson) setSharedDates(sharedDatesJson)
} catch { if (seq === loadSeq.current) toast.error('Could not load calendar') }
finally { if (seq === loadSeq.current) setLoading(false) }
}, [])
useEffect(() => { const timer = setTimeout(load, 0); window.addEventListener('computer:bookmarks-changed', load); return () => { clearTimeout(timer); window.removeEventListener('computer:bookmarks-changed', load) } }, [load])
@@ -80,6 +92,18 @@ export function CalendarClient() {
return bookmarksByDay[key] ?? []
}, [selectedDay, bookmarksByDay])
if (!ready) {
return (
<div className="space-y-6">
<div>
<h1 className="font-display text-2xl font-bold tracking-tight">Calendar</h1>
<p className="text-sm text-muted-foreground mt-1">Bookmarks organized by due date</p>
</div>
<div className="h-[60vh] animate-pulse rounded-lg border border-border/60 bg-muted/30" aria-label="Loading calendar" />
</div>
)
}
return (
<div className="space-y-6">
<div className="flex items-center justify-between">
@@ -151,6 +175,8 @@ export function CalendarClient() {
<h2 className="font-medium">{format(selectedDay, 'EEEE, MMMM d, yyyy')}</h2>
<div className="flex gap-2"><Input placeholder="Share date with user…" value={shareQuery} onChange={e => setShareQuery(e.target.value)} /></div>
</div>
{/* Review L-9: sharing a date is broader than the old label said. */}
<p className="text-xs text-muted-foreground">Recipients will see your bookmarks due that day, including their notes.</p>
{shareUsers.map(u => <Button key={u.id} size="sm" variant="outline" onClick={async () => { const res = await fetch('/api/shared-dates', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ date: format(selectedDay, 'yyyy-MM-dd'), recipientIds: [u.id] }) }); if (!res.ok) { toast.error('Could not share date'); return } toast.success('Date shared'); setShareQuery(''); setShareUsers([]); load() }}>Share with {u.name || u.email}</Button>)}
{sharedDates.filter(s => s.date.slice(0, 10) === format(selectedDay, 'yyyy-MM-dd')).map(s => <div key={s.id} className="flex items-center gap-2 text-xs text-muted-foreground"><span>{s.creator.name || s.creator.email} shared with {s.recipient.name || s.recipient.email}</span><Button size="xs" variant="ghost" onClick={async () => { const res = await fetch(`/api/shared-dates/${s.id}`, { method: 'DELETE' }); if (!res.ok) { toast.error('Only the owner can stop sharing'); return } load() }}>Stop sharing</Button></div>)}
{selectedBookmarks.length === 0 ? (
+37 -9
View File
@@ -1,6 +1,6 @@
'use client'
import { useCallback, useEffect, useState } from 'react'
import { useCallback, useEffect, useRef, useState } from 'react'
import Link from 'next/link'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
@@ -109,7 +109,7 @@ function plainValue(prop: CollectionProperty, value: unknown): string {
if (prop.type === 'DATE' && typeof value === 'string' && value) {
if (prop.config.mode === 'date') return value.slice(0, 10)
const date = new Date(value)
return Number.isNaN(date.getTime()) ? value : date.toLocaleString()
return Number.isNaN(date.getTime()) ? value : date.toLocaleString('en-US', { timeZone: 'UTC' })
}
if (value === null || value === undefined || value === '') return '—'
return String(value)
@@ -246,6 +246,12 @@ export function CollectionsClient() {
const [shareQuery, setShareQuery] = useState('')
const [shareResults, setShareResults] = useState<{ id: string; name: string | null; email: string }[]>([])
// Review M-11: switching collections/views quickly used to let an older
// response overwrite the newer selection. Each loader has a request
// sequence and only the latest may apply its result.
const detailSeq = useRef(0)
const itemsSeq = useRef(0)
const loadCollections = useCallback(async () => {
try {
const res = await fetch('/api/collections')
@@ -254,27 +260,33 @@ export function CollectionsClient() {
}, [])
const loadDetail = useCallback(async (id: string) => {
const seq = ++detailSeq.current
try {
const res = await fetch(`/api/collections/${id}`)
if (seq !== detailSeq.current) return
if (!res.ok) { setDetail(null); return }
const data: CollectionDetail = await res.json()
if (seq !== detailSeq.current) return
setDetail(data)
setNameDraft(data.name)
setViewId((current) => (current && data.views.some((v) => v.id === current) ? current : data.views[0]?.id ?? null))
} catch { toast.error('Could not load collection') }
} catch { if (seq === detailSeq.current) toast.error('Could not load collection') }
}, [])
const loadItems = useCallback(async (id: string, view: string | null, append?: string | null) => {
const seq = ++itemsSeq.current
try {
const params = new URLSearchParams({ limit: '200' })
if (view) params.set('viewId', view)
if (append) params.set('cursor', append)
const res = await fetch(`/api/collections/${id}/items?${params}`)
if (seq !== itemsSeq.current) return
if (!res.ok) return
const rows: CollectionItem[] = await res.json()
if (seq !== itemsSeq.current) return
setItems((current) => (append ? [...current, ...rows] : rows))
setCursor(res.headers.get('X-Next-Cursor'))
} catch { toast.error('Could not load items') }
} catch { if (seq === itemsSeq.current) toast.error('Could not load items') }
}, [])
useEffect(() => { const t = setTimeout(loadCollections, 0); return () => clearTimeout(t) }, [loadCollections])
@@ -286,14 +298,14 @@ export function CollectionsClient() {
}, [collections, activeId])
useEffect(() => {
const t = setTimeout(() => {
if (!activeId) { setDetail(null); return }
if (!activeId) { detailSeq.current++; setDetail(null); return }
loadDetail(activeId)
}, 0)
return () => clearTimeout(t)
}, [activeId, loadDetail])
useEffect(() => {
const t = setTimeout(() => {
if (!activeId) { setItems([]); return }
if (!activeId) { itemsSeq.current++; setItems([]); return }
loadItems(activeId, viewId)
}, 0)
return () => clearTimeout(t)
@@ -529,7 +541,12 @@ export function CollectionsClient() {
if (!['empty', 'notEmpty'].includes(fOp)) {
if (prop.type === 'NUMBER') value = Number(fValue)
else if (prop.type === 'CHECKBOX') value = fValue === 'true'
else value = fValue
else if (prop.type === 'DATE' && prop.config?.mode === 'datetime') {
// Review M-14: datetime-local emits a local string; the server stores
// fixed-width UTC.
const parsed = new Date(fValue)
value = Number.isNaN(parsed.getTime()) ? '' : parsed.toISOString()
} else value = fValue
if (fValue === '' || (prop.type === 'NUMBER' && Number.isNaN(value))) { toast.error('Filter value required'); return }
}
setClause([...filterClauses, value === undefined ? { propertyId: fProp, op: fOp } : { propertyId: fProp, op: fOp, value }])
@@ -539,7 +556,9 @@ export function CollectionsClient() {
const prop = detail?.properties.find((p) => p.id === c.propertyId)
if (!prop) return 'unknown'
let shown = c.value
if (prop.type === 'SELECT' && typeof c.value === 'string') shown = prop.config.options?.find((o) => o.id === c.value)?.label ?? c.value
// Review M-14: MULTI_SELECT filters also carry an option id; show its
// label like SELECT instead of the raw id.
if ((prop.type === 'SELECT' || prop.type === 'MULTI_SELECT') && typeof c.value === 'string') shown = prop.config.options?.find((o) => o.id === c.value)?.label ?? c.value
if (prop.type === 'CHECKBOX') shown = c.value === true ? 'checked' : 'unchecked'
return `${prop.name} ${OP_LABELS[c.op] ?? c.op}${shown !== undefined ? ` ${shown}` : ''}`
}
@@ -637,6 +656,9 @@ export function CollectionsClient() {
onDrop={(e) => {
e.preventDefault()
const item = items.find((i) => i.id === draggedItemId)
// This is a drop handler, not render; the compiler rule cannot
// see through the async helper's captured state.
// eslint-disable-next-line react-hooks/refs
if (item) void moveItemToGroup(item, col.key === NONE ? null : col.key)
setDraggedItemId(null)
setBoardDropKey(null)
@@ -824,12 +846,18 @@ export function CollectionsClient() {
</Select>
{!['empty', 'notEmpty'].includes(fOp) && (() => {
const p = detail.properties.find((x) => x.id === fProp)
if (p?.type === 'SELECT') return (
if (p?.type === 'SELECT' || p?.type === 'MULTI_SELECT') return (
<Select value={fValue || undefined} onValueChange={setFValue}>
<SelectTrigger aria-label="Filter value"><SelectValue placeholder="Value" /></SelectTrigger>
<SelectContent>{(p.config.options ?? []).map((o) => <SelectItem key={o.id} value={o.id}>{o.label}</SelectItem>)}</SelectContent>
</Select>
)
// Review M-14: DATE filters used to render a plain
// text box, so a normal date always failed server
// validation. Match the property editor's inputs.
if (p?.type === 'DATE') return p.config?.mode === 'datetime'
? <Input type="datetime-local" value={fValue} onChange={(e) => setFValue(e.target.value)} aria-label="Filter value" className="h-8 text-sm" />
: <Input type="date" value={fValue} onChange={(e) => setFValue(e.target.value)} aria-label="Filter value" className="h-8 text-sm" />
if (p?.type === 'CHECKBOX') return (
<Select value={fValue || undefined} onValueChange={setFValue}>
<SelectTrigger aria-label="Filter value"><SelectValue placeholder="Value" /></SelectTrigger>
+28
View File
@@ -0,0 +1,28 @@
'use client'
// Review M-6: a backend outage is not a logout. Server components throw
// BackendUnavailableError (auth guards) or fail their data fetch; show a
// retry surface instead of redirecting to /login or rendering empty data.
import { useEffect } from 'react'
export default function AppError({ error, reset }: { error: Error & { digest?: string }; reset: () => void }) {
useEffect(() => {
console.error('App route failed', error)
}, [error])
return (
<main className="mx-auto flex min-h-[60vh] max-w-md flex-col items-center justify-center gap-4 p-6 text-center">
<h1 className="text-xl font-semibold">Service temporarily unavailable</h1>
<p className="text-sm text-muted-foreground">
The application backend could not be reached. You are still signed in; try again in a moment.
</p>
<button
type="button"
onClick={() => reset()}
className="rounded-md bg-primary px-4 py-2 text-sm font-medium text-primary-foreground hover:opacity-90"
>
Try again
</button>
</main>
)
}
+16 -7
View File
@@ -49,6 +49,10 @@ export function KanbanClient() {
const [draggedColumnId, setDraggedColumnId] = useState<string | null>(null)
const [cardDrop, setCardDrop] = useState<CardDrop | null>(null)
const [columnDropId, setColumnDropId] = useState<string | null>(null)
// Review M-4: a column drop needs a direction. "Before the target" made a
// rightward drag onto the adjacent column a no-op (the source was already
// before it), so the pointer's half of the target decides before/after.
const [columnDropAfter, setColumnDropAfter] = useState(false)
const [editingId, setEditingId] = useState<string | null>(null)
const [editLabel, setEditLabel] = useState('')
const [adding, setAdding] = useState(false)
@@ -85,6 +89,7 @@ export function KanbanClient() {
setDraggedColumnId(null)
setCardDrop(null)
setColumnDropId(null)
setColumnDropAfter(false)
}, [])
const finishDrag = useCallback(() => {
@@ -101,16 +106,18 @@ export function KanbanClient() {
else { toast.error('Could not reorder columns'); load() }
}, [load])
const reorderColumn = useCallback((sourceId: string, targetId: string) => {
const reorderColumn = useCallback((sourceId: string, targetId: string, afterTarget: boolean) => {
if (sourceId === targetId) return
const from = columns.findIndex(c => c.id === sourceId)
const to = columns.findIndex(c => c.id === targetId)
if (from < 0 || to < 0) return
if (from < 0 || !columns.some(c => c.id === targetId)) return
const next = [...columns]
const [moved] = next.splice(from, 1)
// Drop before the target column; this is the least surprising direction
// for both leftward and rightward moves.
next.splice(from < to ? to - 1 : to, 0, moved)
// The target's index after removal, then before or after it according to
// the pointer half the drop reported.
let insertAt = next.findIndex(c => c.id === targetId)
if (insertAt < 0) return
if (afterTarget) insertAt += 1
next.splice(insertAt, 0, moved)
saveColumnOrder(next)
}, [columns, saveColumnOrder])
@@ -223,6 +230,8 @@ export function KanbanClient() {
if (draggedColumnId === col.id) return
e.preventDefault()
e.dataTransfer.dropEffect = 'move'
const rect = e.currentTarget.getBoundingClientRect()
setColumnDropAfter(e.clientX > rect.left + rect.width / 2)
setColumnDropId(col.id)
setCardDrop(null)
return
@@ -237,7 +246,7 @@ export function KanbanClient() {
const handleColumnDrop = (e: React.DragEvent<HTMLElement>, col: Column) => {
e.preventDefault()
if (draggedColumnId) {
reorderColumn(draggedColumnId, col.id)
reorderColumn(draggedColumnId, col.id, columnDropAfter)
finishDrag()
return
}
+2 -2
View File
@@ -110,7 +110,7 @@ function PageEmbedCard({ embed }: { embed: PageEmbed }) {
if (prop.type === 'DATE' && typeof value === 'string' && value) {
if (prop.config.mode === 'date') return value.slice(0, 10)
const date = new Date(value)
return Number.isNaN(date.getTime()) ? value : date.toLocaleDateString()
return Number.isNaN(date.getTime()) ? value : date.toLocaleDateString('en-US', { timeZone: 'UTC' })
}
if (value === null || value === undefined || value === '') return '—'
return String(value)
@@ -1010,7 +1010,7 @@ export function PagesClient({ initialId }: { initialId: string | null }) {
<button type="button" className="flex w-full items-center justify-between gap-2 text-left" onClick={() => void viewRevision(rev.id)}>
<span className="min-w-0">
<span className="block truncate text-sm font-medium">Version {rev.version}</span>
<span className="block text-xs text-muted-foreground">{new Date(rev.createdAt).toLocaleString()}</span>
<span className="block text-xs text-muted-foreground">{new Date(rev.createdAt).toLocaleString('en-US', { timeZone: 'UTC' })}</span>
</span>
{revisions[0]?.id === rev.id && <span className="shrink-0 text-[10px] uppercase tracking-wide text-muted-foreground">Current</span>}
</button>
+17 -5
View File
@@ -1,6 +1,6 @@
'use client'
import { useState, useEffect, useCallback } from 'react'
import { useState, useEffect, useCallback, useRef } from 'react'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Badge } from '@/components/ui/badge'
@@ -51,11 +51,17 @@ export function TagsClient({ initialTag = null }: { initialTag?: string | null }
} catch { toast.error('Could not load tags') }
}, [])
// Review M-11: a slower response for the previously selected tag must not
// replace the list after the user has moved on.
const bookmarksSeq = useRef(0)
const loadBookmarks = useCallback(async (tagId: string) => {
const seq = ++bookmarksSeq.current
setLoading(true)
try { setBookmarks(await fetchBookmarks(new URLSearchParams({ tagId }))) }
catch { toast.error('Could not load bookmarks') }
finally { setLoading(false) }
try {
const rows = await fetchBookmarks(new URLSearchParams({ tagId }))
if (seq === bookmarksSeq.current) setBookmarks(rows)
} catch { if (seq === bookmarksSeq.current) toast.error('Could not load bookmarks') }
finally { if (seq === bookmarksSeq.current) setLoading(false) }
}, [])
useEffect(() => { const timer = setTimeout(loadTags, 0); return () => clearTimeout(timer) }, [loadTags])
@@ -65,7 +71,13 @@ export function TagsClient({ initialTag = null }: { initialTag?: string | null }
const timer = setTimeout(() => setSelectedTag(initialTag), 0)
return () => clearTimeout(timer)
}, [initialTag])
useEffect(() => { const timer = setTimeout(() => { if (selectedTag) loadBookmarks(selectedTag) }, 0); return () => clearTimeout(timer) }, [selectedTag, loadBookmarks])
useEffect(() => {
const timer = setTimeout(() => {
if (!selectedTag) { bookmarksSeq.current++; setBookmarks([]); return }
loadBookmarks(selectedTag)
}, 0)
return () => clearTimeout(timer)
}, [selectedTag, loadBookmarks])
useEffect(() => { const reload = () => { loadTags(); if (selectedTag) loadBookmarks(selectedTag) }; window.addEventListener('computer:bookmarks-changed', reload); return () => window.removeEventListener('computer:bookmarks-changed', reload) }, [loadTags, loadBookmarks, selectedTag])
const createTag = async () => {
+1 -1
View File
@@ -100,7 +100,7 @@ export function TrashClient() {
<div className="min-w-0 flex-1">
<p className="truncate text-sm font-medium">{entry.title}</p>
<p className="text-xs text-muted-foreground">
{new Date(entry.deletedAt).toLocaleString()}
{new Date(entry.deletedAt).toLocaleString('en-US', { timeZone: 'UTC' })}
</p>
</div>
<Badge variant="secondary" className="capitalize">{entry.type}</Badge>
+12 -1
View File
@@ -96,6 +96,11 @@ async function proxy(request: NextRequest) {
}
const response = await backendFetch(request.nextUrl.pathname + request.nextUrl.search, {
method: request.method, headers, body,
// Go's slowest handlers (IMAP/signal checks) legitimately run ~45s;
// keep the proxy budget inside Go's 60s WriteTimeout while still
// bounding a blackholed connection. fast server-component calls keep
// backendFetch's 10s default.
signal: AbortSignal.timeout(55_000),
})
const outgoing = new Headers()
for (const name of ['content-type', 'content-disposition', 'set-cookie', 'x-next-cursor']) {
@@ -105,8 +110,14 @@ async function proxy(request: NextRequest) {
outgoing.set('Cache-Control', 'no-store')
return new Response(response.body, { status: response.status, headers: outgoing })
} catch (error) {
// Review M-7: a timed-out backend is a 504 so callers can distinguish it
// from an unreachable one (502).
const timedOut = (error as { status?: unknown })?.status === 504
console.error('Go API unavailable', error)
return Response.json({ error: 'API unavailable' }, { status: 502 })
return Response.json(
{ error: timedOut ? 'API timed out' : 'API unavailable' },
{ status: timedOut ? 504 : 502 },
)
}
}
export { proxy as GET, proxy as HEAD, proxy as POST, proxy as PUT, proxy as PATCH, proxy as DELETE }
-24
View File
@@ -1,24 +0,0 @@
export const dynamic = 'force-dynamic'
import { NextResponse } from 'next/server'
import { signIn } from '@/auth'
export async function POST(req: Request) {
const expectedOrigin = new URL(process.env.NEXTAUTH_URL || req.url).origin
if (req.headers.get('origin') !== expectedOrigin) {
return NextResponse.json({ error: 'Invalid request origin' }, { status: 403 })
}
if (req.headers.get('content-type')?.split(';')[0].trim().toLowerCase() !== 'application/json') {
return NextResponse.json({ error: 'Content-Type must be application/json' }, { status: 415 })
}
try {
const body = await req.json()
const result = await signIn('credentials', {
email: body.email,
password: body.password,
redirect: false,
})
return NextResponse.json({ ok: true, url: result })
} catch {
return NextResponse.json({ error: 'Invalid credentials' }, { status: 401 })
}
}
+4
View File
@@ -26,6 +26,10 @@ export function LoginClient({ oidcEnabled }: { oidcEnabled: boolean }) {
const result = await signIn('credentials', { email, password, redirect: false })
if (result?.ok) {
router.push('/pages')
} else if (result?.code === 'throttled') {
// Review M-8: Go's 429 is propagated as a CredentialsSignin code;
// do not present throttling as a wrong password.
toast.error('Too many attempts. Wait a few minutes and try again.')
} else {
toast.error('Invalid credentials')
}
+10 -2
View File
@@ -1,11 +1,19 @@
import { apiBase } from '@/lib/api'
import { apiBase, forwardedClientHeaders } from '@/lib/api'
import { headers } from 'next/headers'
import { notFound } from 'next/navigation'
import { PublicBookmarkView } from './client'
export default async function PublicSharePage({ params }: { params: Promise<{ id: string }> }) {
const { id } = await params
const response = await fetch(`${apiBase()}/api/public/bookmarks/${encodeURIComponent(id)}`, { cache: 'no-store' })
// Review H-2: pass the attested browser identity through to Go. Without it
// every server-rendered share view shares the web container's public
// rate-limit bucket, so one hot link (or one client) could exhaust it.
const response = await fetch(`${apiBase()}/api/public/bookmarks/${encodeURIComponent(id)}`, {
cache: 'no-store',
headers: forwardedClientHeaders(await headers()),
signal: AbortSignal.timeout(10_000),
})
if (!response.ok) notFound()
const bookmark = await response.json()
+3 -1
View File
@@ -18,7 +18,9 @@ export function SignupClient() {
const handleSignup = async (e: React.FormEvent) => {
e.preventDefault()
if (password.length < 6) { toast.error('Password must be at least 6 characters'); return }
// Review M-8: match the server's 8-character minimum (and the input's
// minLength). The old 6-character check let a doomed request through.
if (password.length < 8) { toast.error('Password must be at least 8 characters'); return }
setLoading(true)
try {
const res = await fetch('/api/signup', {