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
+3
View File
@@ -0,0 +1,3 @@
import { createAuthClient } from "better-auth/react"
export const authClient = createAuthClient()
+54
View File
@@ -0,0 +1,54 @@
import { betterAuth } from "better-auth"
import { drizzleAdapter } from "better-auth/adapters/drizzle"
import { genericOAuth } from "better-auth/plugins"
import { tanstackStartCookies } from "better-auth/tanstack-start"
import { getRequestHeaders } from "@tanstack/react-start/server"
import { db } from "@/db"
import * as schema from "@/db/schema"
const {
OIDC_DISCOVERY_URL: discoveryUrl,
OIDC_CLIENT_ID: clientId,
OIDC_CLIENT_SECRET: clientSecret,
} = process.env
const sso = discoveryUrl && clientId && clientSecret
export const SSO_PROVIDER_ID = "sso"
export const ssoName = sso ? process.env.OIDC_PROVIDER_NAME || "SSO" : null
export const signUpEnabled = process.env.DISABLE_SIGNUP !== "true"
export const auth = betterAuth({
baseURL: process.env.BETTER_AUTH_URL,
database: drizzleAdapter(db, { provider: "pg", schema }),
emailAndPassword: { enabled: true, disableSignUp: !signUpEnabled },
// without this the login rate limit cannot tell clients apart behind a proxy
advanced: {
ipAddress: {
trustedProxies: process.env.TRUSTED_PROXIES?.split(",").filter(Boolean),
},
},
plugins: [
...(sso
? [
genericOAuth({
config: [
{
providerId: SSO_PROVIDER_ID,
discoveryUrl,
clientId,
clientSecret,
scopes: ["openid", "email", "profile"],
},
],
}),
]
: []),
tanstackStartCookies(), // must stay last
],
})
export async function requireUser() {
const session = await auth.api.getSession({ headers: getRequestHeaders() })
if (!session) throw new Error("Unauthorized")
return session.user
}
+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
}
})
+38
View File
@@ -0,0 +1,38 @@
import assert from "node:assert/strict"
import { test } from "node:test"
import { drop, moveOver, order } from "./layout.ts"
const cards = () => [
{ id: "apps", links: [{ id: "a" }, { id: "b" }, { id: "c" }] },
{ id: "web", links: [{ id: "x" }] },
{ id: "empty", links: [] },
]
const ids = (layout: ReturnType<typeof cards>) =>
order(layout).map((c) => c.linkIds.join(""))
test("drop reorders inside a card", () => {
assert.deepEqual(ids(drop(cards(), "a", "c")), ["bca", "x", ""])
assert.deepEqual(ids(drop(cards(), "c", "a")), ["cab", "x", ""])
})
test("drop on itself or on its own card changes nothing", () => {
const before = cards()
assert.equal(drop(before, "a", "a"), before)
assert.equal(drop(before, "a", "apps"), before)
})
test("a link moves to another card, at the link it is over", () => {
assert.deepEqual(ids(moveOver(cards(), "a", "x")), ["bc", "ax", ""])
assert.deepEqual(ids(drop(cards(), "a", "x")), ["bc", "ax", ""])
})
test("a link dropped on a card goes to its end", () => {
assert.deepEqual(ids(drop(cards(), "a", "web")), ["bc", "xa", ""])
assert.deepEqual(ids(drop(cards(), "a", "empty")), ["bc", "x", "a"])
})
test("unknown ids change nothing", () => {
const before = cards()
assert.equal(drop(before, "nope", "x"), before)
assert.equal(drop(before, "a", "nope"), before)
})
+50
View File
@@ -0,0 +1,50 @@
// Where links sit in their cards. Pure, so drag and drop can be tested without a browser.
type Card = { id: string; links: { id: string }[] }
/** The card with this id, or the card that holds the link with this id. */
const cardOf = <TCard extends Card>(cards: TCard[], id: string) =>
cards.find((c) => c.id === id || c.links.some((l) => l.id === id))
/** While dragging: a link that hovers over another card moves into that card. */
export function moveOver<TCard extends Card>(
cards: TCard[],
linkId: string,
overId: string
): TCard[] {
const from = cardOf(cards, linkId)
const to = cardOf(cards, overId)
const link = from?.links.find((l) => l.id === linkId)
if (!from || !to || !link || from === to) return cards
// over a link: take its place. Over the card itself: go to the end.
const overIndex = to.links.findIndex((l) => l.id === overId)
const at = overIndex < 0 ? to.links.length : overIndex
return cards.map((c) =>
c === from
? { ...c, links: c.links.filter((l) => l !== link) }
: c === to
? { ...c, links: [...c.links.slice(0, at), link, ...c.links.slice(at)] }
: c
)
}
/** On drop: the link takes the place of the link it was dropped on. */
export function drop<TCard extends Card>(
cards: TCard[],
linkId: string,
overId: string
): TCard[] {
const moved = moveOver(cards, linkId, overId)
if (moved !== cards) return moved // it changed cards, that put it in place
const card = cardOf(cards, linkId)
const from = card?.links.findIndex((l) => l.id === linkId) ?? -1
const to = card?.links.findIndex((l) => l.id === overId) ?? -1
if (!card || from < 0 || to < 0 || from === to) return cards
const links = [...card.links]
links.splice(to, 0, ...links.splice(from, 1))
return cards.map((c) => (c === card ? { ...c, links } : c))
}
/** What the server stores: per card, its link ids in order. */
export const order = (cards: Card[]) =>
cards.map((c) => ({ id: c.id, linkIds: c.links.map((l) => l.id) }))
+35
View File
@@ -0,0 +1,35 @@
import assert from "node:assert/strict"
import { test } from "node:test"
import { parseSuggestions, searchUrl } from "./search.ts"
test("searchUrl", () => {
assert.equal(
searchUrl(" a b&c ", "duckduckgo", null),
"https://duckduckgo.com/?q=a%20b%26c"
)
assert.equal(
searchUrl("cats", "searxng", "https://sx.lan/"),
"https://sx.lan/search?q=cats"
)
// SearXNG selected but not configured
assert.equal(
searchUrl("cats", "searxng", null),
"https://duckduckgo.com/?q=cats"
)
assert.equal(
searchUrl("cats", "google", null),
"https://www.google.com/search?q=cats"
)
// bangs go to DuckDuckGo
assert.equal(
searchUrl("!w cats", "google", null),
"https://duckduckgo.com/?q=!w%20cats"
)
})
test("parseSuggestions", () => {
assert.deepEqual(parseSuggestions(["ca", ["cat", "car"]]), ["cat", "car"])
assert.deepEqual(parseSuggestions(["cat", "car"]), ["cat", "car"])
assert.deepEqual(parseSuggestions({ error: 1 }), [])
assert.deepEqual(parseSuggestions(["q", [{ phrase: "x" }, "ok"]]), ["ok"])
})
+38
View File
@@ -0,0 +1,38 @@
export const ENGINES = ["duckduckgo", "searxng", "google"] as const
export type Engine = (typeof ENGINES)[number]
export const ENGINE_NAMES: Record<Engine, string> = {
duckduckgo: "DuckDuckGo",
searxng: "SearXNG",
google: "Google",
}
/** SearXNG without a configured instance falls back to DuckDuckGo. */
export function effectiveEngine(engine: Engine, searxngUrl: string | null) {
return engine === "searxng" && !searxngUrl ? "duckduckgo" : engine
}
export function searchUrl(
query: string,
engine: Engine,
searxngUrl: string | null
) {
const q = encodeURIComponent(query.trim())
switch (effectiveEngine(engine, searxngUrl)) {
case "searxng":
return `${searxngUrl!.replace(/\/+$/, "")}/search?q=${q}`
case "google":
// !bangs are a DuckDuckGo feature, Google would search them literally
if (!query.trim().startsWith("!"))
return `https://www.google.com/search?q=${q}`
}
return `https://duckduckgo.com/?q=${q}`
}
/** Both DuckDuckGo and SearXNG answer in OpenSearch form: [query, [suggestions]] */
export function parseSuggestions(body: unknown): string[] {
const list = Array.isArray(body) && Array.isArray(body[1]) ? body[1] : body
return Array.isArray(list)
? list.filter((s) => typeof s === "string").slice(0, 8)
: []
}
-1
View File
@@ -1 +0,0 @@
export { cn } from "cn"