feat: Dahoam start page with accounts, cards and search
images / check (push) Successful in 27s
images / image (push) Successful in 32s

Replica of the reference start page: wallpaper, serif clock, search bar
and link cards, as a TanStack Start app.

- Better Auth: email/password and OIDC single sign-on
- Postgres with Drizzle for the auth tables, cards, links, settings and
  uploaded wallpapers; the server applies the migrations on start
- cards group links; links are dragged inside and between cards
- search with DuckDuckGo, SearXNG or Google, suggestions and / commands
- settings page: name, search engine, wallpaper, account
- UI from collabry-components, copied into src/vendor/collabry
- Dockerfile and a Gitea workflow that checks the code, builds the image
  for amd64 and arm64 and pushes it to the registry on main
This commit is contained in:
Niklas Haiden
2026-11-18 00:09:19 +01:00
parent 54914e8e03
commit 8df74a849c
80 changed files with 9642 additions and 1572 deletions
+221
View File
@@ -0,0 +1,221 @@
import { createServerFn } from "@tanstack/react-start"
import { getRequestHeaders } from "@tanstack/react-start/server"
import { and, asc, eq, inArray, sql } from "drizzle-orm"
import { z } from "zod"
import { db } from "@/db"
import { card, link, settings, wallpaper } from "@/db/schema"
import { auth, requireUser, signUpEnabled, ssoName } from "@/lib/auth"
import { ENGINES, parseSuggestions } from "@/lib/search"
const httpUrl = z.url({ protocol: /^https?$/ }).max(2000)
async function requireCard(userId: string, cardId: string) {
const found = await db
.select({ id: card.id })
.from(card)
.where(and(eq(card.id, cardId), eq(card.userId, userId)))
if (!found.length) throw new Error("Unknown card")
}
/** The position after the last link of a card. */
const endOf = (cardId: string) =>
sql<number>`(select coalesce(max(${link.position}) + 1, 0) from ${link} where ${link.cardId} = ${cardId})`
export const getAuthInfo = createServerFn({ method: "GET" }).handler(
async () => ({
signedIn: !!(await auth.api.getSession({ headers: getRequestHeaders() })),
ssoName,
signUpEnabled,
})
)
/** Everything the dashboard renders, or null when signed out. */
export const getDashboard = createServerFn({ method: "GET" }).handler(
async () => {
const session = await auth.api.getSession({ headers: getRequestHeaders() })
if (!session) return null
const userId = session.user.id
const [cards, links, rows] = await Promise.all([
db
.select({ id: card.id, name: card.name })
.from(card)
.where(eq(card.userId, userId))
.orderBy(asc(card.createdAt)),
db
.select({
id: link.id,
cardId: link.cardId,
name: link.name,
url: link.url,
icon: link.icon,
})
.from(link)
.where(eq(link.userId, userId))
.orderBy(asc(link.position), asc(link.createdAt)),
db.select().from(settings).where(eq(settings.userId, userId)),
])
// Links need a card to live in, so nobody is left without one.
// shortcut: two first loads at the same moment make two cards, add a unique
// constraint if that ever shows up
if (!cards.length)
cards.push(
...(await db
.insert(card)
.values({ userId, name: "Apps" })
.returning({ id: card.id, name: card.name }))
)
const s = rows.at(0) // no row until the first save
return {
user: { name: session.user.name, email: session.user.email },
cards: cards.map((c) => ({
...c,
links: links.filter((l) => l.cardId === c.id),
})),
title: s?.title ?? "Dahoam",
searchEngine: s?.searchEngine ?? "duckduckgo",
wallpaperUrl: s?.wallpaperUrl ?? null,
searxngUrl: process.env.SEARXNG_URL || null,
}
}
)
export const saveLink = createServerFn({ method: "POST" })
.validator(
z.object({
id: z.uuid().optional(),
name: z.string().trim().min(1).max(60),
url: httpUrl,
icon: z.string().trim().max(2000).nullable(),
cardId: z.uuid(),
})
)
.handler(async ({ data: { id, ...values } }) => {
const user = await requireUser()
await requireCard(user.id, values.cardId)
const end = endOf(values.cardId)
if (id) {
await db
.update(link)
.set({
...values,
// a link that changes cards goes to the end of the new one
position: sql`case when ${link.cardId} = ${values.cardId} then ${link.position} else ${end} end`,
})
.where(and(eq(link.id, id), eq(link.userId, user.id)))
} else {
await db
.insert(link)
.values({ ...values, userId: user.id, position: end })
}
})
export const saveCard = createServerFn({ method: "POST" })
.validator(
z.object({
id: z.uuid().optional(),
name: z.string().trim().min(1).max(40),
})
)
.handler(async ({ data: { id, name } }) => {
const user = await requireUser()
if (id) {
await db
.update(card)
.set({ name })
.where(and(eq(card.id, id), eq(card.userId, user.id)))
} else {
await db.insert(card).values({ name, userId: user.id })
}
})
/** Deletes the card and, through the foreign key, its links. */
export const deleteCard = createServerFn({ method: "POST" })
.validator(z.object({ id: z.uuid() }))
.handler(async ({ data }) => {
const user = await requireUser()
await db
.delete(card)
.where(and(eq(card.id, data.id), eq(card.userId, user.id)))
})
/** Stores the result of a drag: for each card, its links in order. */
export const moveLinks = createServerFn({ method: "POST" })
.validator(
z.object({
cards: z
.array(z.object({ id: z.uuid(), linkIds: z.array(z.uuid()).max(500) }))
.max(100),
})
)
.handler(async ({ data }) => {
const user = await requireUser()
const cardIds = [...new Set(data.cards.map((c) => c.id))]
const owned = await db
.select({ id: card.id })
.from(card)
.where(and(eq(card.userId, user.id), inArray(card.id, cardIds)))
if (owned.length !== cardIds.length) throw new Error("Unknown card")
// shortcut: one UPDATE per link, fine for a few hundred links; switch to a
// single UPDATE ... FROM (VALUES ...) if a save gets slow
await db.transaction(async (tx) => {
for (const c of data.cards)
for (const [position, id] of c.linkIds.entries())
await tx
.update(link)
.set({ cardId: c.id, position })
.where(and(eq(link.id, id), eq(link.userId, user.id)))
})
})
export const deleteLink = createServerFn({ method: "POST" })
.validator(z.object({ id: z.uuid() }))
.handler(async ({ data }) => {
const user = await requireUser()
await db
.delete(link)
.where(and(eq(link.id, data.id), eq(link.userId, user.id)))
})
export const saveSettings = createServerFn({ method: "POST" })
.validator(
// a patch: the settings page saves each setting on its own
z
.object({
title: z.string().trim().min(1).max(40),
searchEngine: z.enum(ENGINES),
// external image, the user's own upload, or null for the default
wallpaperUrl: z
.union([httpUrl, z.string().regex(/^\/api\/wallpaper\?v=\d+$/)])
.nullable(),
})
.partial()
.refine((patch) => Object.keys(patch).length > 0)
)
.handler(async ({ data }) => {
const user = await requireUser()
await db
.insert(settings)
.values({ ...data, userId: user.id })
.onConflictDoUpdate({ target: settings.userId, set: data })
// the stored upload is no longer shown
if (data.wallpaperUrl !== undefined && !data.wallpaperUrl?.startsWith("/"))
await db.delete(wallpaper).where(eq(wallpaper.userId, user.id))
})
export const suggest = createServerFn({ method: "GET" })
.validator(z.object({ q: z.string().max(200), searxng: z.boolean() }))
.handler(async ({ data }) => {
await requireUser() // not an open proxy
const base = data.searxng && process.env.SEARXNG_URL
const url = base
? `${base.replace(/\/+$/, "")}/autocompleter?q=`
: "https://duckduckgo.com/ac/?type=list&q="
try {
const res = await fetch(url + encodeURIComponent(data.q), {
signal: AbortSignal.timeout(2000),
})
return res.ok ? parseSuggestions(await res.json()) : []
} catch {
return [] // suggestions are optional, search still works
}
})