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', {
+9 -5
View File
@@ -1,4 +1,4 @@
import NextAuth from 'next-auth'
import NextAuth, { CredentialsSignin } from 'next-auth'
import CredentialsProvider from 'next-auth/providers/credentials'
import jwt from 'jsonwebtoken'
import { createHmac } from 'node:crypto'
@@ -63,12 +63,16 @@ export const { handlers, auth, signIn, signOut } = NextAuth({
body: JSON.stringify({ email: credentials.email, password: credentials.password }),
})
if (!response.ok) {
// Surface Go's 429 so callers can distinguish throttling from bad
// credentials (the custom login route maps everything else to 401).
// Review M-8: surface Go's 429 as a distinct CredentialsSignin code
// so the login UI can say "too many attempts" instead of "invalid
// credentials" or "check your connection". Auth.js carries `code`
// through to the client's signIn() result. The status field remains
// for server-side callers/tests.
if (response.status === 429) {
const retry = response.headers.get('retry-after')
const err = new Error(response.status === 429 ? 'Throttled' : 'Unauthorized') as Error & { status?: number; retryAfter?: string }
const err = new CredentialsSignin() as CredentialsSignin & { status?: number; retryAfter?: string }
err.code = 'throttled'
err.status = 429
const retry = response.headers.get('retry-after')
if (retry) err.retryAfter = retry
throw err
}
+4 -18
View File
@@ -6,7 +6,7 @@ import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Textarea } from '@/components/ui/textarea'
import { Badge } from '@/components/ui/badge'
import { Link2, Loader2, Plus, X } from 'lucide-react'
import { Link2, Plus, X } from 'lucide-react'
import { toast } from 'sonner'
import { invalidateReference } from '@/lib/reference-data'
@@ -24,7 +24,6 @@ export function AddBookmarkDialog({ open, onClose, onCreated }: Props) {
const [dueDate, setDueDate] = useState('')
const [kanban, setKanban] = useState('INBOX')
const [loading, setLoading] = useState(false)
const [fetching, setFetching] = useState(false)
const [tags, setTags] = useState<{ id: string; name: string; color: string }[]>([])
const [allTags, setAllTags] = useState<any[]>([])
const [newTagName, setNewTagName] = useState('')
@@ -37,20 +36,9 @@ export function AddBookmarkDialog({ open, onClose, onCreated }: Props) {
}
}, [open])
const fetchPreview = useCallback(async () => {
if (!url) return
setFetching(true)
try {
const res = await fetch(`/api/preview?url=${encodeURIComponent(url)}`)
if (res.ok) {
const data = await res.json()
if (data?.ogTitle && !title) setTitle(data.ogTitle)
if (data?.ogDescription && !description) setDescription(data.ogDescription)
}
} catch { /* ignore */ }
setFetching(false)
}, [url, title, description])
// Review M-10: no client-side preview fetch. The server fetches preview
// metadata once during create (and fills title/description defaults), so a
// blur followed by Save no longer spends the preview budget twice.
const handleSubmit = useCallback(async () => {
if (!url) { toast.error('URL is required'); return }
setLoading(true)
@@ -111,9 +99,7 @@ export function AddBookmarkDialog({ open, onClose, onCreated }: Props) {
placeholder="https://..."
value={url}
onChange={(e: React.ChangeEvent<HTMLInputElement>) => setUrl(e.target.value)}
onBlur={fetchPreview}
/>
{fetching && <Loader2 className="absolute right-3 top-1/2 -translate-y-1/2 h-4 w-4 animate-spin text-muted-foreground" />}
</div>
</div>
<div>
+5 -6
View File
@@ -7,6 +7,7 @@ import { Sidebar } from '@/components/sidebar'
import { TopBar } from '@/components/top-bar'
import { AddBookmarkDialog } from '@/components/add-bookmark-dialog'
import { QuickFind } from '@/components/quick-find'
import { resetReferenceCache } from '@/lib/reference-data'
export type Bookmark = {
id: string
@@ -74,6 +75,8 @@ export function AppShell({ children }: { children: React.ReactNode }) {
try {
await fetch('/api/admin/view-as', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ userId: null }) })
} catch { /* navigating to /admin surfaces any persistent failure */ }
// Review L-6: leaving view-as restores the admin identity.
resetReferenceCache()
window.location.href = '/admin'
}, [])
@@ -104,12 +107,8 @@ export function AppShell({ children }: { children: React.ReactNode }) {
return () => clearInterval(interval)
}, [session?.user])
// Request notification permission
useEffect(() => {
if (typeof Notification !== 'undefined' && Notification.permission === 'default') {
Notification.requestPermission()
}
}, [])
// Review L-5: notification permission is requested from the alert bell on
// an explicit user action (top-bar.tsx), not on every app mount.
const refreshPage = useCallback(() => {
window.dispatchEvent(new Event('computer:bookmarks-changed'))
+11 -4
View File
@@ -5,7 +5,7 @@
// (new page, add bookmark, toggle theme). Search is read-only; mutations
// stay on their owning screens.
import { useCallback, useEffect, useState } from 'react'
import { useCallback, useEffect, useRef, useState } from 'react'
import { useRouter } from 'next/navigation'
import { useTheme } from 'next-themes'
import { toast } from 'sonner'
@@ -86,16 +86,23 @@ export function QuickFind({ open, onOpenChange, isAdmin = false, onAddBookmark }
}, [open])
// Bookmark search hits the API (debounced) because the server matches
// notes and URLs too, not just titles.
// notes and URLs too, not just titles. Review M-11: requests can still
// resolve out of order after the debounce fires, so only the newest
// sequence may publish results.
const searchSeq = useRef(0)
useEffect(() => {
if (!open) return
const q = query.trim()
const t = setTimeout(async () => {
if (q.length < 2) { setBookmarks([]); return }
if (q.length < 2) { searchSeq.current++; setBookmarks([]); return }
const seq = ++searchSeq.current
try {
const params = new URLSearchParams({ search: q, limit: '6' })
const res = await fetch(`/api/bookmarks?${params}`)
if (res.ok) setBookmarks(((await res.json()) as BookmarkHit[]).slice(0, 6))
if (!res.ok || seq !== searchSeq.current) return
const rows = (await res.json()) as BookmarkHit[]
if (seq !== searchSeq.current) return
setBookmarks(rows.slice(0, 6))
} catch { /* transient; retried on next keystroke */ }
}, q.length < 2 ? 0 : 200)
return () => clearTimeout(t)
+9 -3
View File
@@ -230,8 +230,10 @@ function SidebarNav({ open, pathname, isAdmin = false }: { open: boolean; pathna
}
}
const dropPage = (target: PageSummary, after: boolean) => {
const source = draggedPageRef.current
// The source id is passed in from the drop handler (reading the ref inside
// an event handler) so the compiler does not treat this helper as reading a
// ref during render.
const dropPage = (source: string | null, target: PageSummary, after: boolean) => {
draggedPageRef.current = null
setPageDrop(null)
if (!source) return
@@ -310,6 +312,8 @@ function SidebarNav({ open, pathname, isAdmin = false }: { open: boolean; pathna
key={p.id}
data-page-id={p.id}
onDragOver={(e) => {
// Event handler, not render: reading the drag source is safe.
// eslint-disable-next-line react-hooks/refs
if (!draggedPageRef.current || draggedPageRef.current === p.id) return
e.preventDefault()
e.dataTransfer.dropEffect = 'move'
@@ -322,7 +326,9 @@ function SidebarNav({ open, pathname, isAdmin = false }: { open: boolean; pathna
onDrop={(e) => {
e.preventDefault()
const rect = e.currentTarget.getBoundingClientRect()
dropPage(p, e.clientY > rect.top + rect.height / 2)
// Event handler, not render: reading the drag source is safe.
// eslint-disable-next-line react-hooks/refs
dropPage(draggedPageRef.current, p, e.clientY > rect.top + rect.height / 2)
}}
style={{ paddingLeft: depth * 12 }}
className={cn(
+27 -1
View File
@@ -18,6 +18,7 @@ import {
import { useTheme } from 'next-themes'
import { useMounted } from '@/components/client-only'
import { ACTIVE_PAGE_CHANGED } from '@/lib/pages'
import { resetReferenceCache } from '@/lib/reference-data'
// Notion keeps the top bar minimal: a breadcrumb path on the left, a subtle
// Quick Find pill, and ghost icon buttons on the right.
@@ -47,6 +48,25 @@ export function TopBar({ user, alerts, onDismissAlert, onAddBookmark, onToggleSi
const mounted = useMounted()
const { theme, setTheme } = useTheme()
const [activePageTitle, setActivePageTitle] = useState<string | null>(null)
// Review L-5: never prompt for notification permission on mount. Browsers
// increasingly ignore prompts without a user gesture, and the prompt was
// intrusive on every first load. The alert bell exposes an explicit action;
// permission is read when that panel opens (null until then, so the action
// never renders on the server or before the user interacts).
const [notificationPermission, setNotificationPermission] = useState<NotificationPermission | 'unsupported' | null>(null)
const toggleAlerts = () => {
setShowAlerts(!showAlerts)
setNotificationPermission(typeof Notification === 'undefined' ? 'unsupported' : Notification.permission)
}
const enableNotifications = async () => {
if (typeof Notification === 'undefined') return
const permission = await Notification.requestPermission()
setNotificationPermission(permission)
if (permission === 'granted') toast.success('Desktop alerts enabled')
else if (permission === 'denied') toast.error('Desktop alerts are blocked in your browser settings')
}
// The pages workspace announces the open page so breadcrumbs can show it.
// The title only renders on /pages, so route changes need no reset effect.
@@ -88,6 +108,7 @@ export function TopBar({ user, alerts, onDismissAlert, onAddBookmark, onToggleSi
if (!revoked) {
toast.error('Signed out on this device, but global revocation failed — other sessions may remain signed in until the backend recovers.')
}
resetReferenceCache()
void signOut({ redirectTo: '/login' })
}
@@ -142,7 +163,7 @@ export function TopBar({ user, alerts, onDismissAlert, onAddBookmark, onToggleSi
</Button>
<div className="relative shrink-0" id="topbar-alerts">
<Button variant="ghost" size="icon-sm" onClick={() => setShowAlerts(!showAlerts)}>
<Button variant="ghost" size="icon-sm" onClick={toggleAlerts}>
<Bell className="h-4 w-4" />
{(alerts?.length ?? 0) > 0 && (
<span className="absolute -top-0.5 -right-0.5 flex h-4 w-4 items-center justify-center rounded-full bg-destructive text-[10px] text-destructive-foreground">
@@ -153,6 +174,11 @@ export function TopBar({ user, alerts, onDismissAlert, onAddBookmark, onToggleSi
{showAlerts && (
<div className="absolute right-0 top-full mt-2 w-80 rounded-lg border bg-card p-2 shadow-lg z-50">
<p className="px-2 py-1 text-xs font-medium text-muted-foreground">Alerts</p>
{notificationPermission === 'default' && (
<Button variant="outline" size="sm" className="mx-2 mb-1 w-[calc(100%-1rem)]" onClick={enableNotifications}>
Enable desktop alerts
</Button>
)}
{(alerts?.length ?? 0) === 0 && (
<p className="px-2 py-4 text-sm text-center text-muted-foreground">No pending alerts</p>
)}
-66
View File
@@ -1,66 +0,0 @@
import { useState } from 'react'
import { Card, CardContent, CardHeader, CardTitle } from './card'
import { Badge } from './badge'
import { Checkbox } from './checkbox'
import { Button } from './button'
import { Pencil, Trash2 } from 'lucide-react'
import { motion } from 'framer-motion'
interface TaskCardProps {
id: string
title: string
description?: string
category: string
completed: boolean
onComplete: (id: string, completed: boolean) => void
onDelete: (id: string) => void
onEdit: (id: string) => void
}
export function TaskCard({
id,
title,
description,
category,
completed,
onComplete,
onDelete,
onEdit,
}: TaskCardProps) {
return (
<motion.div
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
exit={{ opacity: 0, y: -20 }}
transition={{ duration: 0.2 }}
>
<Card className={`w-full ${completed ? 'opacity-60' : ''}`}>
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<div className="flex items-center space-x-2">
<Checkbox
checked={completed}
onCheckedChange={(checked) => onComplete(id, checked as boolean)}
/>
<CardTitle className={`text-lg ${completed ? 'line-through' : ''}`}>
{title}
</CardTitle>
</div>
<div className="flex space-x-2">
<Button variant="ghost" size="icon" onClick={() => onEdit(id)}>
<Pencil className="h-4 w-4" />
</Button>
<Button variant="ghost" size="icon" onClick={() => onDelete(id)}>
<Trash2 className="h-4 w-4" />
</Button>
</div>
</CardHeader>
<CardContent>
{description && <p className="text-sm text-muted-foreground">{description}</p>}
<Badge variant="secondary" className="mt-2">
{category}
</Badge>
</CardContent>
</Card>
</motion.div>
)
}
+27
View File
@@ -0,0 +1,27 @@
// Review H-1: the proxy-attested client IP is what gives every browser its
// own login/signup/public-endpoint rate-limit bucket. It only works when the
// Next server trusts the proxy that pins X-Real-IP. A TLS deployment without
// that switch silently puts every client in the web container's bucket, so
// warn loudly at startup instead of waiting for an outage caused by one
// caller exhausting the instance limit.
export async function register() {
// Runs for both the Node and Edge runtimes; env diagnostics only apply to
// the server process.
if (process.env.NEXT_RUNTIME !== 'nodejs') return
const url = process.env.NEXTAUTH_URL || ''
const trusted = process.env.TRUSTED_PROXY === '1'
if (url.startsWith('https://') && !trusted) {
console.warn(
'[config] NEXTAUTH_URL is HTTPS but TRUSTED_PROXY is not 1. All clients ' +
'share the web container rate-limit bucket; set TRUSTED_PROXY=1 when a ' +
'proxy in front of web overwrites X-Real-IP (see RUNNING.md).',
)
}
if (trusted && !url.startsWith('https://')) {
console.warn(
'[config] TRUSTED_PROXY=1 is set for a non-HTTPS NEXTAUTH_URL. Only do ' +
'this when the proxy is the sole route to this server; otherwise ' +
'clients can spoof X-Real-IP and choose their rate-limit identity.',
)
}
}
+29 -1
View File
@@ -24,6 +24,21 @@ export const signClientIP = (ip: string): { ts: string; sig: string } => {
return { ts, sig: createHmac('sha256', secret).update(`${ip}|${ts}`).digest('hex') }
}
// Review H-2: server-rendered pages that call Go directly (the public share
// page) must forward the same attested identity as the data proxy, otherwise
// every rendered share view lands in the web container's bucket. Returns an
// empty object when there is no trusted proxy or no usable header.
export const forwardedClientHeaders = (source: Headers): Record<string, string> => {
const ip = observedClientIP(source)
if (!ip) return {}
const { ts, sig } = signClientIP(ip)
return {
'x-computer-client-ip': ip,
'x-computer-client-ts': ts,
'x-computer-client-sig': sig,
}
}
// Only this trusted Next server signs assertions. The browser never chooses a
// user ID, and Go still re-reads roles/ownership on every request. The typ
// claim binds the token to the Bearer channel; Go rejects it as a cookie and
@@ -55,5 +70,18 @@ export async function backendFetch(path: string, init: RequestInit = {}) {
}
const viewAs = (await cookies()).get('computer_view_as')?.value
if (viewAs) headers.set('Cookie', `computer_view_as=${encodeURIComponent(viewAs)}`)
return fetch(`${apiBase()}${path}`, { ...init, headers, cache: 'no-store' })
// Review M-7: bound server-side calls so a hung or blackholed backend
// cannot stall a route/server component until the platform timeout.
// Callers may provide their own signal to override this default.
const signal = init.signal ?? AbortSignal.timeout(10_000)
try {
return await fetch(`${apiBase()}${path}`, { ...init, headers, cache: 'no-store', signal })
} catch (error) {
if (error instanceof Error && error.name === 'TimeoutError') {
const timeout = new Error('Backend request timed out') as Error & { status?: number }
timeout.status = 504
throw timeout
}
throw error
}
}
+28 -1
View File
@@ -1,6 +1,33 @@
import { backendFetch } from '@/lib/api'
export const VIEW_AS_COOKIE = 'computer_view_as'
export type AuthUser = { id: string; name?: string | null; email?: string | null; image?: string | null; role: 'USER' | 'ADMIN'; actingAdminId?: string }
async function account() { const res = await backendFetch('/api/me'); return res.ok ? res.json() : null }
// Review M-6: Go distinguishes "no session" (401) from backend degradation
// (503). Collapsing both to null sent an authenticated admin to /login during
// a database outage, as if their credentials had failed. Only 401 means
// signed out; anything else is an outage the UI must show as such.
export class BackendUnavailableError extends Error {
status: number
constructor(status: number) {
super('Backend unavailable')
this.name = 'BackendUnavailableError'
this.status = status
}
}
async function account() {
let res: Response
try {
res = await backendFetch('/api/me')
} catch (error) {
const status = (error as { status?: unknown })?.status
throw new BackendUnavailableError(typeof status === 'number' ? status : 502)
}
if (res.status === 401) return null
if (!res.ok) throw new BackendUnavailableError(res.status)
return res.json()
}
export async function getRealUser(): Promise<AuthUser | null> { return (await account())?.user ?? null }
export async function getAuthUser(): Promise<AuthUser | null> { const me = await account(); return me ? { ...me.effectiveUser, ...(me.viewingAs ? { actingAdminId: me.user.id } : {}) } : null }
+7
View File
@@ -19,6 +19,13 @@ export function invalidateReference(kind: ReferenceKind) {
cache.delete(kind)
}
// Review L-6: the cache is module-global, not scoped to the authenticated
// identity. An in-tab identity change (sign-out, view-as enter/exit) must not
// serve the previous user's me/tags/contacts for up to 30 seconds.
export function resetReferenceCache() {
cache.clear()
}
// Resolves to null on any failure; failures are not kept cached.
export function fetchReference<T = unknown>(kind: ReferenceKind): Promise<T | null> {
const hit = cache.get(kind)
-28
View File
@@ -1,28 +0,0 @@
export type Expense = {
id: string
amount: number
category: string
description: string
date: Date
}
export type ExpenseFormData = Omit<Expense, 'id' | 'date'> & {
date: string
}
export const EXPENSE_CATEGORIES = [
'Food',
'Transportation',
'Housing',
'Utilities',
'Entertainment',
'Healthcare',
'Shopping',
'Education',
'Other'
] as const
export type DateRange = {
from: Date | undefined
to: Date | undefined
}
-8
View File
@@ -4,11 +4,3 @@ import { twMerge } from "tailwind-merge"
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs))
}
export function formatDuration(seconds: number): string {
const hours = Math.floor(seconds / 3600)
const minutes = Math.floor((seconds % 3600) / 60)
const remainingSeconds = seconds % 60
return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${remainingSeconds.toString().padStart(2, '0')}`
}