v2: rewrite on Hono + SQLite with user namespaces

Replaces the Next.js/Prisma/next-auth app with a single-container
Hono server, SQLite via Drizzle, OIDC login against Authentik and a
React/Vite admin UI that talks to a JSON API.

- users get /<username>/<code>, admins (Authentik group) get root
  codes, pinning and full access
- link pages with link and Markdown text blocks, themes, avatars
- editable 302 redirects, random or custom codes
- personal API tokens, CSRF-protected cookie sessions
- privacy-friendly stats: daily-rotating visitor salt, 90-day click
  retention with daily totals kept
- QR codes as PNG/SVG
- tests for permissions, auth, redirects and stats; CI runs them
  before publishing images

See REQUIREMENTS.md for the full requirement list.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-14 13:57:47 +02:00
co-authored by Claude Opus 5.5
parent 9758f4bf45
commit b217214512
108 changed files with 6942 additions and 9862 deletions
-189
View File
@@ -1,189 +0,0 @@
"use server"
import { z } from "zod";
import prisma from "../../prisma/prisma";
import { revalidatePath } from "next/cache";
export async function createLinkBlock(prevState: any, formData: FormData) {
const schema = z.object({
customPageUuid: z.string().uuid(),
redirectPageShortcode: z.string(),
title: z.string().max(100),
order: z.coerce.number()
});
const data = schema.safeParse({
customPageUuid: formData.get("customPageUuid"),
redirectPageShortcode: formData.get("redirectPageShortcode"),
title: formData.get("title"),
order: formData.get("order")
});
if (!data.success) {
return {
message: "Invalid data",
error: data.error.flatten().fieldErrors,
};
}
const customPage = await prisma.customPage.findUnique({
where: { uuid: data.data.customPageUuid },
include: {
page: true,
linkBlock: true
}
});
if (!customPage) {
return {
message: "Custom page not found",
error: {}
};
}
const page = await prisma.page.findUnique({
where: { shortcode: data.data.redirectPageShortcode },
include: { redirectPage: true }
});
const redirectPage = page?.redirectPage[0]
if (!redirectPage) {
return {
message: "Redirect page not found",
error: {}
};
}
try {
const currentLinkCount = customPage.linkBlock.length;
const newOrder = currentLinkCount + 1;
await prisma.linkBlock.create({
data: {
customPageUuid: data.data.customPageUuid,
redirectPageUuid: redirectPage?.uuid,
title: data.data.title,
order: newOrder
}
});
} catch (e: any) {
return {
message: "Error adding link to page",
error: e.message
};
}
revalidatePath("/~/dash");
revalidatePath(`/~/dash/${data.data.customPageUuid}/page`);
revalidatePath(`/${customPage.page.shortcode}`);
return {
message: "Adding link to page"
};
}
export async function deleteLinkBlock(prevState: any, formData: FormData) {
const schema = z.object({
uuid: z.string().uuid()
});
const data = schema.safeParse({
uuid: formData.get("uuid")
});
if (!data.success) {
return {
message: "Invalid data",
error: data.error.flatten().fieldErrors,
};
}
try {
await prisma.linkBlock.delete({
where: {
uuid: data.data.uuid
}
});
} catch (e: any) {
return {
message: "Cant delete link from page",
};
}
revalidatePath("/~/dash");
return {
message: "Removed link from page"
};
}
export async function updateLinkBlockOrder(prevState: any, formData: FormData) {
const schema = z.object({
linkBlockUuid: z.string().uuid(),
newOrder: z.coerce.number()
});
const data = schema.safeParse({
linkBlockUuid: formData.get("linkBlockUuid"),
newOrder: formData.get("newOrder")
});
if (!data.success) {
return {
message: "Invalid data",
error: data.error.flatten().fieldErrors,
};
}
try {
// Get the link block being moved
const movedLinkBlock = await prisma.linkBlock.findUnique({
where: { uuid: data.data.linkBlockUuid },
include: { customPage: true }
});
if (!movedLinkBlock) {
return {
message: "Link block not found",
error: {}
};
}
// Get all link blocks for this custom page ordered by their current order
const allLinkBlocks = await prisma.linkBlock.findMany({
where: { customPageUuid: movedLinkBlock.customPageUuid },
orderBy: { order: "asc" }
});
// Find the current index of the moved block
const currentIndex = allLinkBlocks.findIndex(block => block.uuid === data.data.linkBlockUuid);
// Create a new array with the block moved to its new position
const reorderedBlocks = [...allLinkBlocks];
const [movedBlock] = reorderedBlocks.splice(currentIndex, 1);
reorderedBlocks.splice(data.data.newOrder - 1, 0, movedBlock);
// Update orders based on the new positions
const updates = reorderedBlocks.map((block, index) => {
return prisma.linkBlock.update({
where: { uuid: block.uuid },
data: { order: index + 1 }
});
});
// Execute all updates in a transaction
await prisma.$transaction(updates);
} catch (e: any) {
return {
message: "Error updating link order",
error: e.message
};
}
revalidatePath("/~/dash");
revalidatePath(`/~/dash/${data.data.linkBlockUuid}/page`);
return {
message: "Link order updated"
};
}
-239
View File
@@ -1,239 +0,0 @@
"use server"
import { z } from "zod";
import prisma from "../../prisma/prisma";
import { revalidatePath } from "next/cache";
export async function createCustomPage(prevState: any, fromData: FormData) {
const schema = z.object({
shortcode: z.string().min(1).max(100),
title: z.string().min(1).max(100),
image: z.instanceof(File)
.refine((file) => ["image/png", "image/jpeg"].includes(file.type)
, { message: "Only PNG and JPEG images are allowed" })
.refine((file) => file.size < 1024 * 1024 * 10, { message: "Image must be less than 10MB" })
});
const data = schema.safeParse({
shortcode: fromData.get("shortcode"),
title: fromData.get("title"),
image: fromData.get("image")
});
if (!data.success) {
return {
message: "Invalid data",
error: data.error.flatten().fieldErrors,
};
}
const imageBase64 = await data.data.image.arrayBuffer().then((buffer) => {
return Buffer.from(buffer).toString("base64");
});
try {
const page = await prisma.page.create({
data: {
shortcode: data.data.shortcode
}
});
const customPage = await prisma.customPage.create({
data: {
pageUuid: page.uuid,
title: data.data.title,
image: imageBase64
}
});
} catch (e) {
return {
message: "Shortcode already exists",
error: {
shortcode: ["Shortcode already exists"]
}
};
}
revalidatePath("/~/dash");
return {
message: "Page created",
};
}
export async function createRedirectPage(prevState: any, fromData: FormData) {
const schema = z.object({
dest: z.string().url().max(1000),
shortcode: z.string().min(1).max(100)
});
const data = schema.safeParse({
dest: fromData.get("dest"),
shortcode: fromData.get("shortcode")
});
if (!data.success) {
return {
message: "Invalid data",
error: data.error.flatten().fieldErrors,
};
}
const page = await prisma.page.create({
data: {
shortcode: data.data.shortcode
}
});
const redirectPage = await prisma.redirectPage.create({
data: {
pageUuid: page.uuid,
dest: data.data.dest
}
});
revalidatePath("/~/dash");
return {
message: "URL created",
};
}
export async function deletePage(prevState: any, fromData: FormData) {
const schema = z.object({
uuid: z.string().uuid()
});
const data = schema.safeParse({
uuid: fromData.get("uuid")
});
if (!data.success) {
return {
message: "Invalid data",
error: data.error.flatten().fieldErrors,
};
}
await prisma.redirectPage.deleteMany({
where: {
pageUuid: data.data.uuid
}
});
await prisma.customPage.deleteMany({
where: {
pageUuid: data.data.uuid
}
});
await prisma.stat.deleteMany({
where: {
pageUuid: data.data.uuid
}
});
await prisma.page.delete({
where: {
uuid: data.data.uuid
}
});
revalidatePath("/~/dash");
return {
message: "Page deleted",
};
}
export async function pinPageToRoot(prevState: any, fromData: FormData) {
const schema = z.object({
uuid: z.string().uuid(),
unpin: z.enum(['true', 'false']).transform((value) => value === 'true').optional()
});
const data = schema.safeParse({
uuid: fromData.get("uuid"),
unpin: fromData.get("unpin")
});
if (!data.success) {
return {
message: "Invalid data",
error: data.error.flatten().fieldErrors,
};
}
console.log(data.data.unpin);
if (data.data.unpin) {
console.log
await prisma.pinnedPage.delete({
where: {
id: 1
}
});
revalidatePath("/~/dash");
revalidatePath("/");
return {
message: "Page unpinned",
};
} else {
await prisma.pinnedPage.upsert({
where: {
id: 1
},
update: {
pageUuid: data.data.uuid
},
create: {
id: 1,
pageUuid: data.data.uuid
}
});
revalidatePath("/~/dash");
revalidatePath("/");
return {
message: "Page pinned",
};
}
}
export async function deletePageStats(prevState: any, formData: FormData) {
const schema = z.object({
uuid: z.string().uuid()
});
const data = schema.safeParse({
uuid: formData.get("uuid")
});
if (!data.success) {
return {
message: "Invalid data",
error: data.error.flatten().fieldErrors,
};
}
await prisma.stat.deleteMany({
where: {
pageUuid: data.data.uuid
}
});
revalidatePath(`/~/dash/${data.data.uuid}`);
return {
message: "Stats deleted",
};
}
-128
View File
@@ -1,128 +0,0 @@
'use server'
import prisma from "../../prisma/prisma";
export async function getDailyStats(pageUuid: string) {
const sevenDaysAgo = new Date();
sevenDaysAgo.setDate(sevenDaysAgo.getDate() - 7);
const dailyStats = await prisma.stat.groupBy({
by: ['accessedAt'],
where: {
pageUuid: pageUuid,
accessedAt: {
gte: sevenDaysAgo
}
},
_count: {
uuid: true
},
orderBy: {
accessedAt: 'asc'
}
});
// Group by date only (ignoring time)
const groupedByDate = dailyStats.reduce((acc, stat) => {
const date = stat.accessedAt.toISOString().split('T')[0];
if (!acc[date]) {
acc[date] = {
date: stat.accessedAt.toISOString(),
clicks: 0
};
}
acc[date].clicks += stat._count.uuid;
return acc;
}, {} as Record<string, { date: string; clicks: number }>);
return Object.values(groupedByDate);
}
export async function getPageData(uuid: string) {
return await prisma.page.findUnique({
where: { uuid: uuid },
include: {
pinnedPage: true,
redirectPage: true,
customPage: true,
stat: { orderBy: { accessedAt: "desc" } },
_count: {
select: { stat: true }
}
}
});
}
export async function getPageStats(uuid: string) {
const today = new Date();
today.setHours(0, 0, 0, 0);
const [stats, clicksToday, lastVisit] = await Promise.all([
prisma.stat.groupBy({
by: ['hash', 'userAgent'],
where: {
pageUuid: uuid
},
_count: {
uuid: true
},
_max: {
accessedAt: true
},
orderBy: {
_max: {
accessedAt: "desc"
}
}
}),
prisma.stat.count({
where: {
pageUuid: uuid,
accessedAt: {
gte: today
}
}
}),
prisma.stat.findFirst({
where: {
pageUuid: uuid
},
orderBy: {
accessedAt: 'desc'
}
})
]);
return {
stats,
clicksToday,
lastVisit: lastVisit?.accessedAt
};
}
export async function getCustomPageData(customPageUuid: string) {
const [linkPages, linkBlocks] = await Promise.all([
prisma.redirectPage.findMany({
include: { page: true }
}),
prisma.linkBlock.findMany({
where: {
customPageUuid: customPageUuid
},
orderBy: {
order: "asc"
},
include: {
redirectPage: { include: { page: true } }
}
})
]);
const shortcodes = linkPages.map((p) => p.page.shortcode);
return {
linkPages,
linkBlocks,
shortcodes
};
}
-55
View File
@@ -1,55 +0,0 @@
import prisma from "../../../prisma/prisma";
import { headers } from "next/headers";
import { notFound, redirect, RedirectType } from "next/navigation";
import { sha256 } from "js-sha256";
import CustomPageComponent from "@/components/CustomPageComponent";
import { PageProps } from "../../../.next/types/app/layout";
export default async function RedirectToUrl({ params }: PageProps) {
const { shortcode } = await params;
const page = await prisma.page.findUnique({
where: {shortcode: shortcode},
include: {
redirectPage: true,
customPage: true
}
});
if (!page) {
return notFound()
}
// Log the visit
const requestHeaders = await headers();
const userAgent = requestHeaders.get('user-agent') || 'unknown';
const ip = requestHeaders.get('x-forwarded-for') || 'unknown';
const anonymIp = ip.replace(/(\d+)\.(\d+)\.(\d+)\.(\d+)/, '$1.$2.$3.0');
const hash = sha256(`${anonymIp}-${userAgent}`);
await prisma.stat.create({
data: {
pageUuid: page.uuid,
userAgent: userAgent,
hash: hash
}
});
if (page.redirectPage.length>0) {
// Redirect to the destination
const redirectPage = page.redirectPage[0];
redirect(redirectPage.dest);
}else if (page.customPage.length>0) {
// Show the custom page
const customPage = page.customPage[0];
return <CustomPageComponent customPage={customPage}/>
} else {
return notFound()
}
}
-2
View File
@@ -1,2 +0,0 @@
import { handlers } from "@/auth" // Referring to the auth.ts we just created
export const { GET, POST } = handlers
Binary file not shown.

Before

Width:  |  Height:  |  Size: 28 KiB

-109
View File
@@ -1,109 +0,0 @@
@import "tailwindcss";
@utility common-red {
@apply text-red-800;
}
body {
@apply text-gray-300 bg-gray-900;
}
h1 {
@apply text-5xl font-bold;
}
h2 {
@apply text-2xl font-bold;
}
.form-group {
@apply mb-2;
}
.form-field-error {
@apply common-red;
}
.form-label-error {
@apply common-red;
}
form {
@apply w-full;
}
input {
@apply w-full appearance-none bg-gray-800 border border-gray-800 text-gray-300 py-3 px-4 mb-1 leading-tight focus:outline-none focus:bg-gray-700 rounded;
}
select {
@apply w-full appearance-none bg-gray-800 border border-gray-800 text-gray-300 py-3 px-4 mb-1 leading-tight focus:outline-none focus:bg-gray-700 rounded;
}
label {
@apply block uppercase tracking-wide text-xs font-bold mb-2;
}
button {
@apply rounded bg-green-600 hover:bg-green-700 text-white py-2 px-4 disabled:opacity-50;
}
.button-icon {
@apply h-5 w-5 inline-block align-middle;
}
.zebra {
@apply even:bg-slate-800 p-2 py-5 rounded;
}
@keyframes slide-in {
0% {
transform: translateY(-30px);
opacity: 0;
}
100% {
transform: translateY(0);
opacity: 1;
}
}
.slide-animated {
animation: slide-in 0.7s ease forwards;
opacity: 0;
}
@keyframes zoom-in {
0% {
transform: scale(0.7);
opacity: 0;
}
100% {
transform: scale(1);
opacity: 1;
}
}
.zoom-animated {
animation: zoom-in 1.5s ease forwards;
transform: scale(0.7);
}
@keyframes fade-in {
0% {
opacity: 0;
}
100% {
opacity: 1;
}
}
.fade-animated {
animation: fade-in 0.7s ease forwards;
opacity: 0;
}
.vcenter {
@apply flex items-center flex-col justify-center mt-5;
min-height: 80vh;
}
-22
View File
@@ -1,22 +0,0 @@
import type { Metadata } from "next";
import { Inter } from "next/font/google";
import "./globals.css";
const inter = Inter({ subsets: ["latin"] });
export const metadata: Metadata = {
title: "traberph short",
description: "A simple URL shortener",
};
export default function RootLayout({
children,
}: Readonly<{
children: React.ReactNode;
}>) {
return (
<html lang="en">
<body className={inter.className}>{children}</body>
</html>
);
}
-27
View File
@@ -1,27 +0,0 @@
import type { MetadataRoute } from "next";
export default function manifest(): MetadataRoute.Manifest {
return {
name: "traberph/short",
short_name: "short",
description: "A URL shortener",
start_url: "/~/dash",
display: "standalone",
theme_color: "#111827",
background_color: "#111827",
icons: [
{
src:'/icon-192x192.png',
sizes: '192x192',
type: 'image/png',
},
{
src:'/icon-512x512.png',
sizes: '512x512',
type: 'image/png',
},
],
};
}
-24
View File
@@ -1,24 +0,0 @@
import Image from "next/image";
import Link from "next/link";
import prisma from "../../prisma/prisma";
import { redirect } from "next/navigation";
export default async function Home() {
const pinnedPage = await prisma.pinnedPage.findFirst({ where: { id: 1 }, include: { page: true } });
if (pinnedPage) {
redirect(pinnedPage.page.shortcode);
}
return (
(<div className="vcenter">
<h1>Welcome</h1>
<p>This is a url shortner</p>
<p>Currently there is no default root page defined</p>
<Link href="/~/dash" className="mt-5 hover:underline">Set pin a page in the dashboard</Link>
<Link href="https:github.com/traberph/short" className="hover:underline">Or check out the project page</Link>
</div>
)
);
}
-112
View File
@@ -1,112 +0,0 @@
import prisma from "../../../../../prisma/prisma";
import { redirect } from "next/navigation";
import Link from "next/link";
import Image from "next/image";
import DeletePageForm from "@/components/forms/deletePageForm";
import CustomPageDashboard from "@/components/CustomPageDashboard";
import LinkFavicon from "@/components/LinkFavicon";
import { hashToColor } from "@/utils";
import PinPageToRootForm from "@/components/forms/pinPageToRootForm";
import { ArrowTopRightOnSquareIcon, BookmarkIcon } from "@heroicons/react/24/solid";
import QRCode from "@/components/QRCode";
import ResetStatsForm from "@/components/forms/resetStatsForm";
import LineChart from "@/components/LineChart";
import { getDailyStats, getPageData, getPageStats, getCustomPageData } from "@/actions/stats";
interface PageProps {
params: Promise<{
uuid: string
}>
}
export default async function DetailedStats({ params }: PageProps) {
const { uuid } = await params;
const [page, pageStats] = await Promise.all([
getPageData(uuid),
getPageStats(uuid)
]);
if (!page) {
redirect("/~/dash");
}
const redirectPage = page.redirectPage[0];
const customPage = page.customPage[0];
// get custom page data if needed
const customPageData = customPage ? await getCustomPageData(customPage.uuid) : undefined;
// Get chart data using server action
const chartData = await getDailyStats(uuid);
return (
<div>
<div className="flex justify-between max-sm:flex-col mb-10">
<div className="flex">
{redirectPage || customPage.image ?
<div className=" h-10 w-10 mr-4 ">
{redirectPage ? <LinkFavicon url={redirectPage.dest} /> :
<Image
src={`data:image/png;base64,${customPage.image}`}
width={100}
height={100}
alt=" "
className="rounded-full"
/>}
</div>
: ""}
<div>
<p>Shortcode: {page.shortcode}</p>
{page.redirectPage.length > 0 ?
<p><a className="underline" href={page.redirectPage[0].dest}>{page.redirectPage[0].dest}</a></p> : ""}
</div>
<div className="ml-5">
{page.pinnedPage ? <BookmarkIcon className="button-icon common-red"/> : ""}
</div>
</div>
<div className="flex max-sm:mt-5">
<div className="">
<Link href={`/${page.shortcode}`} target="blank"><button><ArrowTopRightOnSquareIcon className="button-icon" /></button></Link>
</div>
<div className="ml-5">
<PinPageToRootForm pageUuid={page.uuid} pinned={!!page.pinnedPage} />
</div>
<div className="ml-5">
<DeletePageForm uuid={page.uuid} />
</div>
</div>
</div>
<div className="mb-10">
<QRCode url={page.shortcode} />
</div>
{customPage ? <CustomPageDashboard customPage={customPage} linkBlocks={customPageData?.linkBlocks || []} shortcodes={customPageData?.shortcodes || []} /> : ""}
<div className="flex justify-between items-center mt-10">
<h2 className="m-0">Stats</h2>
<div className="ml-auto">
<ResetStatsForm uuid={page.uuid} />
</div>
</div>
<p className="my-2">Clicks today: {pageStats.clicksToday}</p>
<p className="my-2">Last visit: {pageStats.lastVisit?.toLocaleString()}</p>
<p className="my-2">Unique visitors: {pageStats.stats.length}</p>
<p className="my-2">All clicks: {page._count.stat}</p>
<h3 className="mt-10">Last 7 Days</h3>
<LineChart data={chartData} />
<h3 className="mt-10">All Visits</h3>
{pageStats.stats.map((stat) => (<div className="zebra" key={stat.hash}>
<p style={{ color: hashToColor(stat.hash) }}>{stat.userAgent}</p>
<p>Visits: {"" + stat._count.uuid}</p>
<p>Last Visit: {stat._max.accessedAt?.toLocaleString()}</p>
</div>))}
</div>
);
}
-39
View File
@@ -1,39 +0,0 @@
// layout for dashboard
import Link from 'next/link';
import React, { ReactNode } from 'react';
import { Toaster } from "react-hot-toast";
import { auth } from "@/auth";
import { redirect } from 'next/navigation';
import SignOutButton from '@/components/forms/signOutButton';
export default async function Dashboard({ children }: { children: ReactNode }) {
const session = await auth();
const awSession = await session;
const user = awSession?.user;
if (!user) {
redirect("/~/");
}
return (
<div className='p-10 max-w-7xl mx-auto max-sm:px-6'>
<div className='flex justify-between max-sm:flex-col mb-10'>
<Link href="/~/dash/">
<h1>Dashboard</h1>
</Link>
<div className="flex flex-col max-sm:mt-5 justify-start">
{user?.name ? <>
<div>{user?.name || user.email}</div>
<SignOutButton /></> : ""}
</div>
</div>
<Toaster position='top-right' />
{children}
</div>
);
}
-38
View File
@@ -1,38 +0,0 @@
import React from 'react';
import prisma from '@/../prisma/prisma'
import CreateRedirectPageForm from '@/components/forms/createRedirectPageForm';
import CreateCustomPageForm from '@/components/forms/createCustomPageForm';
import PageListComponent from '@/components/PageListComponent';
export default async function Dashboard() {
const pages = await prisma.page.findMany({
include: {
pinnedPage: true,
redirectPage: true,
customPage: true,
_count: {
select: { stat: true }
}
}
});
const redirectPages = pages.filter((page) => page.redirectPage.length > 0);
const customPages = pages.filter((page) => page.customPage.length > 0);
const pinnedPage = await prisma.pinnedPage.findFirst({ where: { id: 1 } });
return (<>
<h2>Redirect Pages</h2>
{redirectPages.map((page) => (
<PageListComponent key={page.uuid} page={page} />))}
<h2 className='mt-11'>Create Redirect Page</h2>
<CreateRedirectPageForm />
<h2 className='mt-11'>Custom Pages</h2>
{customPages.map((page) => (<PageListComponent key={page.uuid} page={page} />))}
<h2 className='mt-11'>Create Custom Page</h2>
<CreateCustomPageForm />
</>
);
}
-24
View File
@@ -1,24 +0,0 @@
import { auth } from "@/auth";
import SignInButton from "@/components/forms/signInButton";
import Link from "next/link";
import { redirect } from "next/navigation";
export default async function AdminRoot() {
const session = await auth();
const awSession = await session;
const user = awSession?.user;
if (user) {
redirect("/~/dash/");
}
return (<div className="vcenter">
<Link href="https://github.com/traberph/short"><h1 className="my-5">traberph/short</h1></Link>
<SignInButton />
<Link href="/" className="mt-3 hover:underline">or back to root</Link>
</div>
)
}
-6
View File
@@ -1,6 +0,0 @@
import NextAuth from "next-auth"
import Authentik from "next-auth/providers/authentik"
export const { handlers, signIn, signOut, auth } = NextAuth({
providers: [Authentik],
})
-62
View File
@@ -1,62 +0,0 @@
import { CustomPage } from "@prisma/client";
import Image from "next/image";
import prisma from "../../prisma/prisma";
import LinkFavicon from "./LinkFavicon";
export default async function CustomPageComponent(params: { customPage: CustomPage }) {
const customPage = params.customPage;
const token = process.env.LOGO_DEV_TOKEN;
const disableAttribution = process.env.DISABLE_ATTRIBUTION;
const linkBlocks = await prisma.linkBlock.findMany({
where: {
customPageUuid: customPage.uuid
},
orderBy: {
order: "asc"
},
include: {
redirectPage: { include: { page: true } }
}
});
return (
<div className="vcenter">
<Image
src={`data:image/png;base64,${customPage.image}`}
alt=" "
width={100}
height={100}
className="rounded-full zoom-animated"
/>
<h1 className="my-10 text-center zoom-animated">{customPage.title}</h1>
<div className="w-full max-w-96 p-2">
{linkBlocks.map((block, index) => (
<button
key={block.uuid}
className="bg-slate-600 hover:bg-slate-500 w-full my-2 slide-animated"
style={{ animationDelay: `${1.5 + index * 0.1}s` }}
>
<a href={`/${block.redirectPage.page.shortcode}`}>
<div className="relative flex items-center">
<div className="flex-shrink-0 w-8 h-8"><LinkFavicon url={block.redirectPage.dest} /></div>
<div className="absolute left-1/2 transform -translate-x-1/2 text-center font-bold">{block.title}</div>
</div>
</a>
</button>
))}
</div>
<div
className="text-slate-700 mt-10 fade-animated"
style={{ animationDelay: `${1.5 + linkBlocks.length * 0.1}s`, opacity: 0 }}
>
{disableAttribution ? null : <p className="text-center">powered by <a className="underline" target="blank" href="https://github.com/traberph/short">traberph/short</a></p>}
{token ? <p className="text-center">Logos provided by <a className="underline" href="https://logo.dev" alt="Logo API">Logo.dev</a></p> : ""}
</div>
</div>
);
}
-79
View File
@@ -1,79 +0,0 @@
"use client"
import { CustomPage } from "@prisma/client"
import prisma from "../../prisma/prisma"
import CreateLinkBlockForm from "./forms/createLinkBlockForm"
import DeleteLinkBlockForm from "./forms/deleteLinkBlockForm"
import { ArrowTopRightOnSquareIcon, ArrowTrendingUpIcon } from "@heroicons/react/24/solid"
import { DragDropContext, Droppable, Draggable } from "@hello-pangea/dnd"
import { updateLinkBlockOrder } from "@/actions/block_actions"
import { useRouter } from "next/navigation"
import { useState } from "react"
export default function CustomPageDashboard({ customPage, linkBlocks, shortcodes }: {
customPage: CustomPage,
linkBlocks: any[],
shortcodes: string[]
}) {
const router = useRouter();
const [localLinkBlocks, setLocalLinkBlocks] = useState(linkBlocks);
const handleDragEnd = async (result: any) => {
if (!result.destination) return;
const items = Array.from(localLinkBlocks);
const [reorderedItem] = items.splice(result.source.index, 1);
items.splice(result.destination.index, 0, reorderedItem);
// Update local state immediately
setLocalLinkBlocks(items);
// Update the database in the background
const formData = new FormData();
formData.append("linkBlockUuid", reorderedItem.uuid);
formData.append("newOrder", result.destination.index + 1);
await updateLinkBlockOrder(null, formData);
};
return (<>
<h2 className="mb-5">Links on Page</h2>
<DragDropContext onDragEnd={handleDragEnd}>
<Droppable droppableId="links">
{(provided) => (
<div {...provided.droppableProps} ref={provided.innerRef}>
{localLinkBlocks.map((block, index) => (
<Draggable key={block.uuid} draggableId={block.uuid} index={index}>
{(provided) => (
<div
ref={provided.innerRef}
{...provided.draggableProps}
{...provided.dragHandleProps}
className="flex items-center justify-between zebra max-sm:flex-col max-sm:items-start"
>
<div className="flex">
<div className="mr-5">title: <span className="font-bold">{block.title}</span></div>
<div>link page: <span className="font-bold">{block.redirectPage.page.shortcode}</span></div>
</div>
<div className="flex max-sm:mt-3 max-sm:w-full max-sm:justify-between">
<button>
<a href={`/${block.redirectPage.page.shortcode}`} className="btn btn-primary"><ArrowTopRightOnSquareIcon className="button-icon" /></a>
</button>
<button className="ml-3">
<a href={`/~/dash/${block.redirectPage.page.uuid}`} className="btn btn-primary"><ArrowTrendingUpIcon className="button-icon" /></a>
</button>
<DeleteLinkBlockForm linkBlockUuid={block.uuid} />
</div>
</div>
)}
</Draggable>
))}
{provided.placeholder}
</div>
)}
</Droppable>
</DragDropContext>
<h2 className="mt-10">Add new link page connection</h2>
<CreateLinkBlockForm customPage={customPage.uuid} shortcodes={shortcodes || []} />
</>)
}
-47
View File
@@ -1,47 +0,0 @@
"use client"
import { LineChart as RechartsLineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer } from 'recharts';
interface LineChartProps {
data: {
date: string;
clicks: number;
}[];
}
export default function LineChart({ data }: LineChartProps) {
return (
<div className="w-full h-[300px] mt-5">
<ResponsiveContainer width="100%" height="100%">
<RechartsLineChart data={data}>
<CartesianGrid strokeDasharray="3 3" stroke="#374151" />
<XAxis
dataKey="date"
stroke="#9CA3AF"
tickFormatter={(value: string) => new Date(value).toLocaleDateString()}
/>
<YAxis
stroke="#9CA3AF"
allowDecimals={false}
/>
<Tooltip
contentStyle={{
backgroundColor: '#1F2937',
border: 'none',
borderRadius: '0.5rem',
color: '#9CA3AF'
}}
labelFormatter={(value: string) => new Date(value).toLocaleDateString()}
/>
<Line
type="monotone"
dataKey="clicks"
stroke="#10B981"
strokeWidth={2}
dot={{ fill: '#10B981', strokeWidth: 2 }}
/>
</RechartsLineChart>
</ResponsiveContainer>
</div>
);
}
-25
View File
@@ -1,25 +0,0 @@
import Image from "next/image";
export default function LinkFavicon({ url }: { url: string }) {
const hostname = new URL(url).hostname;
const token = process.env.LOGO_DEV_TOKEN;
if (!token) {
const text = hostname.split(".")[0].charAt(0).toUpperCase();
return (
<span className="rounded-full w-8 h-8 flex items-center justify-center bg-gray-100 text-gray-600">
{text}
</span>
)
}
return (
<Image
src={`https://img.logo.dev/${hostname}?token=${token}`}
width={100}
height={100}
alt=" "
className="rounded-full"
/>
);
}
-58
View File
@@ -1,58 +0,0 @@
import React from 'react';
import type { Prisma } from '@prisma/client';
import Image from 'next/image';
import Link from 'next/link';
import LinkFavicon from './LinkFavicon';
import PinPageToRootForm from './forms/pinPageToRootForm';
import { BookmarkIcon } from '@heroicons/react/24/solid';
type PageWithRelations = Prisma.PageGetPayload<{
include: {
pinnedPage: true;
redirectPage: true;
customPage: true;
_count: {
select: { stat: true }
}
}
}>
export default async function PageListComponent({ page }: { page: PageWithRelations }) {
const redirectPage = page.redirectPage[0];
const customPage = page.customPage[0];
return (
<Link href={`/~/dash/${page.uuid}`}>
<div className='flex justify-between items-center hover:bg-slate-700 my-2 p-1 rounded'>
<div className='flex items-center'>
<div className='w-8 h-8'>
{redirectPage ?
<LinkFavicon url={redirectPage.dest} /> :
<Image
loading='lazy'
width={100}
height={100}
src={`data:image/png;base64,${customPage.image}`}
alt="icon"
className="rounded-full"
/>}
</div>
<div className='ml-3'>
<p className="font-bold text-lg text-white">{page.shortcode}</p>
<p className="text-sm text-gray-400">{redirectPage ? redirectPage.dest : customPage.title}</p>
</div>
<div className="ml-5">
{page.pinnedPage ? <BookmarkIcon className='button-icon common-red'/> : ""}
</div>
</div>
<div>
{page._count.stat ? <p className="text-gray-400 font-bold text-right">{page._count.stat} visits</p> : ""}
</div>
</div>
</Link>
);
}
-59
View File
@@ -1,59 +0,0 @@
"use client"
import { useQRCode } from "next-qrcode"
import { useState } from "react";
export default function QRCode({ url }: { url: string }) {
const { Canvas } = useQRCode();
const values = ['L', 'M', 'Q', 'H'];
const [errorCorrectionLevel, setErrorCorrectionLevel] = useState(2);
const [dark, setDark] = useState('#000000');
const [light, setLight] = useState('#FFFFFF');
return (<>
<div className="flex justify-between max-sm:flex-col">
<div className="flex justify-between flex-col">
<h2>QR Code</h2>
<span className="flex items-center justify-between"> Error Correction Level:
<div className="flex justify-between">
{values.map((value, index) => (
<span
key={index}
className={`cursor-pointer mx-2 ${errorCorrectionLevel === index ? 'text-white' : 'text-gray-400'}`}
onClick={() => setErrorCorrectionLevel(index)}>
{value}
</span>
))}
</div>
</span>
<span className="flex items-center justify-between">
Dark:
<input type="color" className="ml-3 w-5 h-5 p-0" value={dark} onChange={(e) => setDark(e.target.value)} />
</span>
<span className="flex items-center justify-between">
Light:
<input type="color" className="ml-3 w-5 h-5 p-0" value={light} onChange={(e) => setLight(e.target.value)} />
</span>
</div>
<div className="max-sm:mt-5">
<Canvas
text={"https://"+ window.location.host + "/" + url}
options={{
errorCorrectionLevel: values[errorCorrectionLevel],
width: 150,
color: {
dark: dark,
light: light
}
}}
/>
</div>
</div>
</>
)
}
-12
View File
@@ -1,12 +0,0 @@
"use client"
import { useFormStatus } from "react-dom";
export default function SubmitButton({children}: {children?: React.ReactNode}) {
const { pending } = useFormStatus();
return (
<button disabled={pending} type="submit">
{children?children:"Submit"}
</button>
);
}
@@ -1,41 +0,0 @@
"use client"
import { createCustomPage } from "@/actions/page_actions";
import { useActionState, useEffect } from "react";
import SubmitButton from "../SubmitButton";
import { handleToast } from "@/utils";
export default function CreateCustomPageForm() {
const initialState = {
message: "",
error: {}
};
const [state, formAction] = useActionState(createCustomPage, initialState);
useEffect(() => { handleToast(state); }, [state]);
return (
<form action={formAction}>
<div className="form-group">
<label htmlFor="shortcode">Shortcode</label>
<input type="text" name="shortcode" id="shortcode" className={state.error?.shortcode ? "border-red-400" : ""} />
<p className="form-label-error">{state.error?.shortcode}</p>
</div>
<div className="form-group">
<label htmlFor="title">Title</label>
<input type="text" name="title" id="title" className={state.error?.title ? "border-red-400" : ""} />
<p className="form-label-error">{state.error?.title}</p>
</div>
<div className="form-group">
<label htmlFor="image">Image</label>
<input type="file" name="image" id="image" className={state.error?.image ? "border-red-400" : ""} />
<p className="form-label-error">{state.error?.image}</p>
</div>
<p>{state.message}</p>
<SubmitButton />
</form>
);
}
@@ -1,40 +0,0 @@
"use client"
import { createLinkBlock } from "@/actions/block_actions"
import { useActionState, useEffect } from "react";
import SubmitButton from "../SubmitButton";
import toast from "react-hot-toast";
import { handleToast } from "@/utils";
import { LinkIcon } from "@heroicons/react/24/solid";
export default function CreateLinkBlockForm({ customPage, shortcodes }: { customPage: string, shortcodes: string[] }) {
const initialState = {
message: "",
error: {}
};
const [state, formAction] = useActionState(createLinkBlock, initialState);
useEffect(() => { handleToast(state); }, [state]);
return (<form action={formAction} className="mt-5">
<div className="form-group">
<label htmlFor="redirectPageShortcode">Redirect Page</label>
<select name="redirectPageShortcode" id="redirectPageShortcode" className={state.error?.redirectPageShortcode ? "border-red-400" : ""}>
{shortcodes.map((s) => <option key={s} value={s}>{s}</option>)}
</select>
<p className="form-label-error">{state.error?.redirectPageShortcode}</p>
</div>
<div className="form-group">
<label htmlFor="title">Title</label>
<input type="text" name="title" id="title" className={state.error?.title ? "border-red-400" : ""} />
<p className="form-label-error">{state.error?.title}</p>
</div>
<input type="hidden" name="order" value="1" />
<input type="hidden" name="customPageUuid" value={customPage} />
<SubmitButton>add to page <LinkIcon className="ml-2 button-icon" /></SubmitButton>
</form>
);
}
@@ -1,33 +0,0 @@
"use client"
import { createRedirectPage } from "@/actions/page_actions";
import { useActionState, useEffect } from "react";
import SubmitButton from "../SubmitButton";
import toast from "react-hot-toast";
import { handleToast } from "@/utils";
export default function CreateRedirectPageForm() {
const initialState = {
message: "",
error: {}
};
const [state, formAction] = useActionState(createRedirectPage, initialState);
useEffect(() => { handleToast(state); }, [state]);
return (
<form action={formAction}>
<div className="form-group">
<label htmlFor='shortcode'>Shortcode</label>
<input type='text' name='shortcode' id='shortcode' className={state.error?.shortcode ? "border-red-400" : ""} />
<p className="form-label-error">{state.error?.shortcode}</p>
</div>
<div className="form-group">
<label htmlFor='dest'>Destination URL</label>
<input type='text' name='dest' id='dest' className={state.error?.dest ? "border-red-400" : ""} />
<p className="form-label-error">{state.error?.dest}</p>
</div>
<SubmitButton />
</form>
);
}
@@ -1,28 +0,0 @@
"use client"
import { deleteLinkBlock } from "@/actions/block_actions";
import { useActionState, useEffect } from "react";
import SubmitButton from "../SubmitButton";
import { handleToast } from "@/utils";
import { LinkSlashIcon } from "@heroicons/react/24/solid";
export default function DeleteLinkBlockForm({ linkBlockUuid }: { linkBlockUuid: string }) {
const initialState = {
message: "",
error: {}
};
const [state, formAction] = useActionState(deleteLinkBlock, initialState);
useEffect(() => { handleToast(state); }, [state]);
return (<form action={formAction} className="ml-3 w-min">
<input type="hidden" name="uuid" id="uuid" value={linkBlockUuid} />
<SubmitButton>
<LinkSlashIcon className="button-icon" />
</SubmitButton>
</form>
)
}
-27
View File
@@ -1,27 +0,0 @@
"use client"
import { deletePage } from "@/actions/page_actions";
import { useActionState, useEffect } from "react";
import SubmitButton from "../SubmitButton";
import toast from "react-hot-toast";
import { handleToast } from "@/utils";
import { TrashIcon } from "@heroicons/react/24/solid";
export default function DeletePageForm({ uuid }: { uuid: string }) {
const initialState = {
message: "",
error: {},
};
const [state, formAction] = useActionState(deletePage, initialState);
useEffect(() => { handleToast(state); }, [state]);
return (
<form action={formAction}>
<input type="hidden" name="uuid" value={uuid} />
<SubmitButton><TrashIcon className="button-icon" /></SubmitButton>
</form>
);
}
@@ -1,30 +0,0 @@
"use client"
import { pinPageToRoot } from "@/actions/page_actions";
import { handleToast } from "@/utils";
import { BookmarkIcon, BookmarkSlashIcon } from "@heroicons/react/24/solid";
import { use, useActionState, useEffect, useState } from "react";
import { toast } from 'react-hot-toast';
export default function PinPageToRootForm({ pageUuid, pinned }: { pageUuid: string, pinned: boolean }) {
const initialState = {
message: "",
error: {}
};
const [state, formAction] = useActionState(pinPageToRoot, initialState);
useEffect(() => { handleToast(state); }, [state]);
return (<form action={formAction}>
<input type="hidden" name="uuid" value={pageUuid} />
<input type="hidden" name="unpin" value={"" + pinned} />
<button type="submit" className="btn btn-primary">
{pinned ?
<BookmarkSlashIcon className="h-5 w-5 inline-block align-middle" />
:
<BookmarkIcon className="h-5 w-5 inline-block align-middle" />
}
</button>
</form>)
}
-25
View File
@@ -1,25 +0,0 @@
"use client"
import { deletePageStats } from "@/actions/page_actions";
import { useActionState, useEffect } from "react";
import SubmitButton from "../SubmitButton";
import { handleToast } from "@/utils";
import { ArrowPathIcon } from "@heroicons/react/24/solid";
export default function ResetStatsForm({ uuid }: { uuid: string }) {
const initialState = {
message: "",
error: {}
};
const [state, formAction] = useActionState(deletePageStats, initialState);
useEffect(() => { handleToast(state); }, [state]);
return (
<form action={formAction}>
<input type="hidden" name="uuid" value={uuid} />
<SubmitButton><ArrowPathIcon className="button-icon" /></SubmitButton>
</form>
);
}
-15
View File
@@ -1,15 +0,0 @@
import { signIn } from "@/auth"
export default function SignInButton() {
return (<div>
<form
action={async () => {
"use server"
await signIn("authentik")
}}
>
<button type="submit">Sign In</button>
</form>
</div>
)
}
-15
View File
@@ -1,15 +0,0 @@
import { signOut } from "@/auth"
export default function SignOutButton() {
return (
<form
className="flex m-0 p-0"
action={async () => {
"use server"
await signOut()
}}
>
<button className='max-sm:ml-0 ml-auto bg-transparent p-0 hover:underline hover:bg-transparent' type="submit">logout</button>
</form>
)
}
-1
View File
@@ -1 +0,0 @@
export { auth as middleware } from "@/auth"
+180
View File
@@ -0,0 +1,180 @@
import { Hono } from "hono";
import { bodyLimit } from "hono/body-limit";
import { desc, eq, and } from "drizzle-orm";
import type { z } from "zod";
import type { ApiToken, CreatedToken } from "../shared/api-types.js";
import {
createBlockSchema,
createPageSchema,
createTokenSchema,
pinSchema,
reorderBlocksSchema,
statsRangeSchema,
updateBlockSchema,
updatePageSchema,
} from "../shared/validation.js";
import type { AppEnv, Deps } from "./app.js";
import { requireActor } from "./auth/middleware.js";
import { createApiToken } from "./auth/sessions.js";
import { apiTokens } from "./db/schema.js";
import { forbidden, HttpError, notFound } from "./lib/errors.js";
import { removeMedia, saveAvatar } from "./lib/media.js";
import * as pages from "./lib/pages.js";
import { getStats, resetStats } from "./lib/stats.js";
function parse<T extends z.ZodType>(schema: T, data: unknown): z.infer<T> {
const result = schema.safeParse(data);
if (result.success) return result.data;
const issues: Record<string, string[]> = {};
for (const issue of result.error.issues) {
const key = issue.path.join(".") || "_";
(issues[key] ??= []).push(issue.message);
}
throw new HttpError(400, "Invalid input", issues);
}
async function jsonBody(c: { req: { json(): Promise<unknown> } }): Promise<unknown> {
try {
return await c.req.json();
} catch {
throw new HttpError(400, "Expected a JSON body");
}
}
function idParam(value: string | undefined): number {
const id = Number(value);
if (!Number.isInteger(id) || id <= 0) throw notFound();
return id;
}
function toApiToken(row: typeof apiTokens.$inferSelect): ApiToken {
return {
id: row.id,
name: row.name,
createdAt: row.createdAt.toISOString(),
lastUsedAt: row.lastUsedAt?.toISOString() ?? null,
};
}
export function apiRoutes(deps: Deps) {
const { db, config } = deps;
return (
new Hono<AppEnv>()
.use(requireActor(deps))
.get("/me", (c) => {
const { username, isAdmin } = c.var.actor;
return c.json({ username, isAdmin });
})
// Pages (redirects and link pages)
.get("/pages", (c) => c.json(pages.listPages(db, c.var.actor)))
.post("/pages", async (c) => {
const input = parse(createPageSchema, await jsonBody(c));
return c.json(pages.createPage(db, c.var.actor, input), 201);
})
.get("/pages/:id", (c) => c.json(pages.getPageDetail(db, c.var.actor, idParam(c.req.param("id")))))
.patch("/pages/:id", async (c) => {
const input = parse(updatePageSchema, await jsonBody(c));
return c.json(pages.updatePage(db, c.var.actor, idParam(c.req.param("id")), input));
})
.delete("/pages/:id", (c) => {
const avatar = pages.deletePage(db, c.var.actor, idParam(c.req.param("id")));
if (avatar) removeMedia(config.dataDir, avatar);
return c.body(null, 204);
})
.put("/pages/:id/avatar", bodyLimit({ maxSize: 3 * 1024 * 1024 }), async (c) => {
const id = idParam(c.req.param("id"));
if (pages.getPageDetail(db, c.var.actor, id).kind !== "linkpage") {
throw new HttpError(400, "Only link pages have an avatar");
}
const body = await c.req.parseBody();
const file = body.file;
if (!(file instanceof File)) throw new HttpError(400, "Expected an image in the 'file' field");
const name = await saveAvatar(config.dataDir, file);
const previous = pages.setAvatar(db, c.var.actor, id, name);
if (previous) removeMedia(config.dataDir, previous);
return c.json({ avatarUrl: pages.avatarUrl(name) });
})
.delete("/pages/:id/avatar", (c) => {
const previous = pages.setAvatar(db, c.var.actor, idParam(c.req.param("id")), null);
if (previous) removeMedia(config.dataDir, previous);
return c.body(null, 204);
})
// Blocks on link pages
.post("/pages/:id/blocks", async (c) => {
const input = parse(createBlockSchema, await jsonBody(c));
return c.json(pages.addBlock(db, c.var.actor, idParam(c.req.param("id")), input), 201);
})
.put("/pages/:id/blocks/order", async (c) => {
const { ids } = parse(reorderBlocksSchema, await jsonBody(c));
return c.json(pages.reorderBlocks(db, c.var.actor, idParam(c.req.param("id")), ids));
})
.patch("/blocks/:id", async (c) => {
const input = parse(updateBlockSchema, await jsonBody(c));
return c.json(pages.updateBlock(db, c.var.actor, idParam(c.req.param("id")), input));
})
.delete("/blocks/:id", (c) => c.json(pages.deleteBlock(db, c.var.actor, idParam(c.req.param("id")))))
// Stats
.get("/pages/:id/stats", (c) => {
const id = idParam(c.req.param("id"));
pages.assertCanManage(db, c.var.actor, id);
const { days } = parse(statsRangeSchema, c.req.query());
return c.json(getStats(db, config.timezone, id, days));
})
.delete("/pages/:id/stats", (c) => {
const id = idParam(c.req.param("id"));
pages.assertCanManage(db, c.var.actor, id);
resetStats(db, id);
return c.body(null, 204);
})
// Personal access tokens (always the caller's own)
.get("/tokens", (c) => {
const rows = db
.select()
.from(apiTokens)
.where(eq(apiTokens.userId, c.var.actor.id))
.orderBy(desc(apiTokens.createdAt))
.all();
return c.json(rows.map(toApiToken));
})
.post("/tokens", async (c) => {
const { name } = parse(createTokenSchema, await jsonBody(c));
const { row, token } = createApiToken(db, c.var.actor.id, name);
return c.json({ ...toApiToken(row), token } satisfies CreatedToken, 201);
})
.delete("/tokens/:id", (c) => {
const id = idParam(c.req.param("id"));
const { changes } = db
.delete(apiTokens)
.where(and(eq(apiTokens.id, id), eq(apiTokens.userId, c.var.actor.id)))
.run();
if (!changes) throw notFound();
return c.body(null, 204);
})
// Admin only
.put("/pin", async (c) => {
const { pageId } = parse(pinSchema, await jsonBody(c));
pages.pinPage(db, c.var.actor, pageId);
return c.body(null, 204);
})
.delete("/pin", (c) => {
pages.pinPage(db, c.var.actor, null);
return c.body(null, 204);
})
.get("/users", (c) => {
if (!c.var.actor.isAdmin) throw forbidden();
return c.json(pages.listUsernames(db));
})
.get("/conflicts", (c) => {
if (!c.var.actor.isAdmin) throw forbidden();
return c.json(pages.listConflicts(db));
})
);
}
+101
View File
@@ -0,0 +1,101 @@
import { existsSync, readFileSync } from "node:fs";
import path from "node:path";
import { Hono } from "hono";
import { serveStatic } from "@hono/node-server/serve-static";
import { secureHeaders } from "hono/secure-headers";
import { sql } from "drizzle-orm";
import { apiRoutes } from "./api.js";
import { authRoutes } from "./auth/routes.js";
import type { OidcProvider } from "./auth/oidc.js";
import type { Config } from "./config.js";
import type { Db } from "./db/index.js";
import { HttpError } from "./lib/errors.js";
import { readMedia } from "./lib/media.js";
import type { Actor } from "./lib/permissions.js";
import { publicRoutes } from "./public/routes.js";
import { MessagePage } from "./public/views.js";
export interface Deps {
db: Db;
config: Config;
oidc: OidcProvider;
/** Directory with the built admin UI; the UI isn't served when missing (e.g. in dev, Vite serves it). */
webDir?: string;
}
export type AppEnv = { Variables: { actor: Actor } };
export function createApp(deps: Deps) {
const { db, config } = deps;
const app = new Hono<AppEnv>();
app.use(
secureHeaders({
contentSecurityPolicy: {
defaultSrc: ["'self'"],
scriptSrc: ["'self'"],
styleSrc: ["'self'", "'unsafe-inline'"],
imgSrc: ["'self'", "data:", "blob:", "https://img.logo.dev"],
objectSrc: ["'none'"],
baseUri: ["'none'"],
// The admin UI previews link pages in an iframe.
frameAncestors: ["'self'"],
formAction: ["'self'"],
},
referrerPolicy: "strict-origin-when-cross-origin",
}),
);
app.onError((err, c) => {
const isApi = c.req.path.startsWith("/~/api/");
if (err instanceof HttpError) {
if (isApi) return c.json({ error: err.message, issues: err.issues }, err.status);
return c.html(<MessagePage title="Something went wrong" message={err.message} link={{ href: "/~/", label: "Back" }} />, err.status);
}
console.error(err);
if (isApi) return c.json({ error: "Internal server error" }, 500);
return c.html(<MessagePage title="Something went wrong" message="Please try again later." />, 500);
});
app.get("/~/health", (c) => {
db.run(sql`select 1`);
return c.json({ ok: true });
});
app.route("/~/auth", authRoutes(deps));
app.route("/~/api", apiRoutes(deps));
app.all("/~/api/*", (c) => c.json({ error: "Not found" }, 404));
app.get("/~/media/:file", (c) => {
const media = readMedia(config.dataDir, c.req.param("file"));
if (!media) return c.notFound();
return c.body(new Uint8Array(media.bytes), 200, {
"Content-Type": media.type,
"Cache-Control": "public, max-age=31536000, immutable",
});
});
// Admin UI (single-page app). Hashed assets are cached forever, index.html never.
const webDir = deps.webDir;
if (webDir && existsSync(path.join(webDir, "index.html"))) {
const indexHtml = readFileSync(path.join(webDir, "index.html"), "utf8");
const files = serveStatic({ root: path.relative(process.cwd(), webDir), rewriteRequestPath: (p) => p.replace(/^\/~/, "") });
app.use("/~/*", async (c, next) => {
// index.html always goes through the SPA fallback below.
if (c.req.path.endsWith("/") || c.req.path.endsWith("/index.html")) return next();
const res = await files(c, next);
if (res && c.req.path.startsWith("/~/assets/")) res.headers.set("Cache-Control", "public, max-age=31536000, immutable");
return res;
});
app.get("/~/*", (c) => {
c.header("Cache-Control", "no-cache");
return c.html(indexHtml);
});
}
app.get("/~", (c) => c.redirect("/~/"));
app.route("/", publicRoutes(deps));
app.notFound((c) => c.html(<MessagePage title="Not found" message="This link doesn't exist." />, 404));
return app;
}
+38
View File
@@ -0,0 +1,38 @@
import { getCookie } from "hono/cookie";
import { createMiddleware } from "hono/factory";
import type { AppEnv, Deps } from "../app.js";
import { HttpError } from "../lib/errors.js";
import { SESSION_COOKIE } from "./routes.js";
import { actorFromApiToken, actorFromSession } from "./sessions.js";
const SAFE_METHODS = new Set(["GET", "HEAD", "OPTIONS"]);
// Guards the whole API: every request needs a bearer token or a session cookie.
// Cookie-authenticated writes must come from our own origin (CSRF protection).
export function requireActor({ db, config }: Deps) {
const ownOrigin = new URL(config.baseUrl).origin;
return createMiddleware<AppEnv>(async (c, next) => {
const authorization = c.req.header("authorization");
if (authorization) {
const [scheme, token] = authorization.split(" ");
const actor = scheme?.toLowerCase() === "bearer" && token ? actorFromApiToken(db, token) : null;
if (!actor) throw new HttpError(401, "Invalid API token");
c.set("actor", actor);
return next();
}
const session = getCookie(c, SESSION_COOKIE);
const actor = session ? actorFromSession(db, session) : null;
if (!actor) throw new HttpError(401, "Not logged in");
if (!SAFE_METHODS.has(c.req.method)) {
const origin = c.req.header("origin");
const site = c.req.header("sec-fetch-site");
if (origin !== ownOrigin && site !== "same-origin") throw new HttpError(403, "Cross-site request blocked");
}
c.set("actor", actor);
return next();
});
}
+53
View File
@@ -0,0 +1,53 @@
import * as client from "openid-client";
import type { Config } from "../config.js";
export interface OidcClaims {
sub: string;
username: string | undefined;
groups: string[];
}
// Thin wrapper so the app can be tested without a real identity provider.
export interface OidcProvider {
authorizationUrl(params: { state: string; codeChallenge: string; redirectUri: string }): Promise<URL>;
exchange(params: { currentUrl: URL; state: string; codeVerifier: string }): Promise<OidcClaims>;
}
export function createOidcProvider(config: Config): OidcProvider {
// Discovery happens lazily so the server can start while Authentik is unavailable.
let discovered: Promise<client.Configuration> | undefined;
const getConfiguration = () => {
discovered ??= client
.discovery(new URL(config.oidc.issuer), config.oidc.clientId, config.oidc.clientSecret)
.catch((err: unknown) => {
discovered = undefined;
throw err;
});
return discovered;
};
return {
async authorizationUrl({ state, codeChallenge, redirectUri }) {
return client.buildAuthorizationUrl(await getConfiguration(), {
redirect_uri: redirectUri,
scope: "openid profile email",
code_challenge: codeChallenge,
code_challenge_method: "S256",
state,
});
},
async exchange({ currentUrl, state, codeVerifier }) {
const tokens = await client.authorizationCodeGrant(await getConfiguration(), currentUrl, {
pkceCodeVerifier: codeVerifier,
expectedState: state,
});
const claims = tokens.claims();
if (!claims) throw new Error("No ID token returned");
const groups = Array.isArray(claims.groups) ? claims.groups.filter((g): g is string => typeof g === "string") : [];
const username = typeof claims.preferred_username === "string" ? claims.preferred_username : undefined;
return { sub: claims.sub, username, groups };
},
};
}
export { calculatePKCECodeChallenge, randomPKCECodeVerifier, randomState } from "openid-client";
+59
View File
@@ -0,0 +1,59 @@
import { Hono } from "hono";
import { deleteCookie, getCookie, getSignedCookie, setCookie, setSignedCookie } from "hono/cookie";
import type { AppEnv, Deps } from "../app.js";
import { calculatePKCECodeChallenge, randomPKCECodeVerifier, randomState } from "./oidc.js";
import { createSession, deleteSession, SESSION_TTL_MS, upsertUser } from "./sessions.js";
export const SESSION_COOKIE = "short_session";
const LOGIN_COOKIE = "short_login";
export function authRoutes({ db, config, oidc }: Deps) {
const secure = config.baseUrl.startsWith("https://");
const redirectUri = `${config.baseUrl}/~/auth/callback`;
return new Hono<AppEnv>()
.get("/login", async (c) => {
const state = randomState();
const codeVerifier = randomPKCECodeVerifier();
const url = await oidc.authorizationUrl({
state,
codeChallenge: await calculatePKCECodeChallenge(codeVerifier),
redirectUri,
});
await setSignedCookie(c, LOGIN_COOKIE, JSON.stringify({ state, codeVerifier }), config.sessionSecret, {
path: "/~/auth",
httpOnly: true,
secure,
sameSite: "Lax",
maxAge: 600,
});
return c.redirect(url.href);
})
.get("/callback", async (c) => {
const raw = await getSignedCookie(c, config.sessionSecret, LOGIN_COOKIE);
deleteCookie(c, LOGIN_COOKIE, { path: "/~/auth" });
if (!raw) return c.redirect("/~/auth/login");
const { state, codeVerifier } = JSON.parse(raw) as { state: string; codeVerifier: string };
// Behind a reverse proxy the request URL may be internal, so rebuild it from BASE_URL.
const requestUrl = new URL(c.req.url);
const currentUrl = new URL(`${redirectUri}${requestUrl.search}`);
const claims = await oidc.exchange({ currentUrl, state, codeVerifier });
const actor = upsertUser(db, claims, config.adminGroup);
setCookie(c, SESSION_COOKIE, createSession(db, actor.id), {
path: "/",
httpOnly: true,
secure,
sameSite: "Lax",
maxAge: SESSION_TTL_MS / 1000,
});
return c.redirect("/~/");
})
.post("/logout", (c) => {
const token = getCookie(c, SESSION_COOKIE);
if (token) deleteSession(db, token);
deleteCookie(c, SESSION_COOKIE, { path: "/" });
return c.body(null, 204);
});
}
+77
View File
@@ -0,0 +1,77 @@
import { and, eq, gt, lt } from "drizzle-orm";
import type { Db } from "../db/index.js";
import { apiTokens, sessions, users } from "../db/schema.js";
import { HttpError } from "../lib/errors.js";
import { randomToken, sha256 } from "../lib/crypto.js";
import { isValidUsername } from "../../shared/validation.js";
import type { Actor } from "../lib/permissions.js";
import type { OidcClaims } from "./oidc.js";
export const SESSION_TTL_MS = 30 * 24 * 60 * 60 * 1000;
const TOKEN_PREFIX = "short_";
// Creates or updates the user for an OIDC login. The username is fixed at first login;
// only the admin flag follows the Authentik groups.
export function upsertUser(db: Db, claims: OidcClaims, adminGroup: string): Actor {
const isAdmin = claims.groups.includes(adminGroup);
const existing = db.select().from(users).where(eq(users.sub, claims.sub)).get();
if (existing) {
db.update(users).set({ isAdmin }).where(eq(users.id, existing.id)).run();
return { id: existing.id, username: existing.username, isAdmin };
}
const username = claims.username;
if (!username || !isValidUsername(username)) {
throw new HttpError(403, "Your username can't be used in URLs. Ask an admin to change it in Authentik.");
}
if (db.select().from(users).where(eq(users.username, username)).get()) {
throw new HttpError(409, "This username already belongs to another account.");
}
const row = db.insert(users).values({ sub: claims.sub, username, isAdmin }).returning().get();
return { id: row.id, username: row.username, isAdmin: row.isAdmin };
}
export function createSession(db: Db, userId: number, now = new Date()): string {
const token = randomToken();
db.insert(sessions)
.values({ id: sha256(token), userId, expiresAt: new Date(now.getTime() + SESSION_TTL_MS) })
.run();
return token;
}
export function deleteSession(db: Db, token: string): void {
db.delete(sessions).where(eq(sessions.id, sha256(token))).run();
}
export function actorFromSession(db: Db, token: string, now = new Date()): Actor | null {
const row = db
.select({ id: users.id, username: users.username, isAdmin: users.isAdmin })
.from(sessions)
.innerJoin(users, eq(users.id, sessions.userId))
.where(and(eq(sessions.id, sha256(token)), gt(sessions.expiresAt, now)))
.get();
return row ?? null;
}
export function actorFromApiToken(db: Db, token: string, now = new Date()): Actor | null {
if (!token.startsWith(TOKEN_PREFIX)) return null;
const row = db
.select({ tokenId: apiTokens.id, id: users.id, username: users.username, isAdmin: users.isAdmin })
.from(apiTokens)
.innerJoin(users, eq(users.id, apiTokens.userId))
.where(eq(apiTokens.tokenHash, sha256(token)))
.get();
if (!row) return null;
db.update(apiTokens).set({ lastUsedAt: now }).where(eq(apiTokens.id, row.tokenId)).run();
return { id: row.id, username: row.username, isAdmin: row.isAdmin };
}
export function createApiToken(db: Db, userId: number, name: string) {
const token = TOKEN_PREFIX + randomToken();
const row = db.insert(apiTokens).values({ userId, name, tokenHash: sha256(token) }).returning().get();
return { row, token };
}
export function pruneSessions(db: Db, now = new Date()): number {
return db.delete(sessions).where(lt(sessions.expiresAt, now)).run().changes;
}
+48
View File
@@ -0,0 +1,48 @@
import path from "node:path";
export interface Config {
baseUrl: string;
oidc: { issuer: string; clientId: string; clientSecret: string };
adminGroup: string;
sessionSecret: string;
dataDir: string;
timezone: string;
trustProxy: boolean;
logoDevToken: string | undefined;
disableAttribution: boolean;
retentionDays: number;
port: number;
}
function required(env: NodeJS.ProcessEnv, name: string): string {
const value = env[name];
if (!value) throw new Error(`Missing required environment variable ${name}`);
return value;
}
export function loadConfig(env: NodeJS.ProcessEnv = process.env): Config {
const timezone = env.TIMEZONE || "UTC";
// Throws a RangeError early for unknown timezones.
new Intl.DateTimeFormat("en-CA", { timeZone: timezone });
const sessionSecret = required(env, "SESSION_SECRET");
if (sessionSecret.length < 32) throw new Error("SESSION_SECRET must be at least 32 characters");
return {
baseUrl: required(env, "BASE_URL").replace(/\/+$/, ""),
oidc: {
issuer: required(env, "OIDC_ISSUER"),
clientId: required(env, "OIDC_CLIENT_ID"),
clientSecret: required(env, "OIDC_CLIENT_SECRET"),
},
adminGroup: env.ADMIN_GROUP || "short-admins",
sessionSecret,
dataDir: path.resolve(env.DATA_DIR || "./data"),
timezone,
trustProxy: env.TRUST_PROXY === "true",
logoDevToken: env.LOGO_DEV_TOKEN || undefined,
disableAttribution: env.DISABLE_ATTRIBUTION === "true",
retentionDays: 90,
port: Number(env.PORT || 3000),
};
}
+22
View File
@@ -0,0 +1,22 @@
import path from "node:path";
import { fileURLToPath } from "node:url";
import Database from "better-sqlite3";
import { drizzle, type BetterSQLite3Database } from "drizzle-orm/better-sqlite3";
import { migrate } from "drizzle-orm/better-sqlite3/migrator";
import * as schema from "./schema.js";
export type Db = BetterSQLite3Database<typeof schema>;
export type Tx = Parameters<Parameters<Db["transaction"]>[0]>[0];
const migrationsFolder = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../../../drizzle");
// Opens the database (":memory:" for tests) and applies pending migrations.
export function openDb(file: string): Db {
const sqlite = new Database(file);
sqlite.pragma("journal_mode = WAL");
sqlite.pragma("foreign_keys = ON");
sqlite.pragma("busy_timeout = 5000");
const db = drizzle(sqlite, { schema });
migrate(db, { migrationsFolder });
return db;
}
+107
View File
@@ -0,0 +1,107 @@
import { sql } from "drizzle-orm";
import { index, integer, primaryKey, sqliteTable, text, uniqueIndex } from "drizzle-orm/sqlite-core";
const createdAt = () =>
integer("created_at", { mode: "timestamp" })
.notNull()
.default(sql`(unixepoch())`);
export const users = sqliteTable("users", {
id: integer("id").primaryKey({ autoIncrement: true }),
sub: text("sub").notNull().unique(),
username: text("username").notNull().unique(),
isAdmin: integer("is_admin", { mode: "boolean" }).notNull().default(false),
createdAt: createdAt(),
});
// Redirects and link pages share one table: both are addressed by (namespace, code).
// namespace "" is the root, otherwise it is the owner's username.
export const pages = sqliteTable(
"pages",
{
id: integer("id").primaryKey({ autoIncrement: true }),
namespace: text("namespace").notNull(),
code: text("code").notNull(),
kind: text("kind", { enum: ["redirect", "linkpage"] }).notNull(),
dest: text("dest"),
title: text("title"),
avatar: text("avatar"),
theme: text("theme", { mode: "json" }),
createdBy: integer("created_by").references(() => users.id, { onDelete: "set null" }),
createdAt: createdAt(),
updatedAt: integer("updated_at", { mode: "timestamp" })
.notNull()
.default(sql`(unixepoch())`),
},
(t) => [uniqueIndex("pages_namespace_code").on(t.namespace, t.code)],
);
export const blocks = sqliteTable(
"blocks",
{
id: integer("id").primaryKey({ autoIncrement: true }),
pageId: integer("page_id")
.notNull()
.references(() => pages.id, { onDelete: "cascade" }),
position: integer("position").notNull(),
kind: text("kind", { enum: ["link", "text"] }).notNull(),
label: text("label"),
markdown: text("markdown"),
targetId: integer("target_id").references(() => pages.id, { onDelete: "cascade" }),
},
(t) => [index("blocks_page").on(t.pageId, t.position), index("blocks_target").on(t.targetId)],
);
// Individual clicks, kept for the retention period only.
export const clicks = sqliteTable(
"clicks",
{
id: integer("id").primaryKey({ autoIncrement: true }),
pageId: integer("page_id")
.notNull()
.references(() => pages.id, { onDelete: "cascade" }),
at: integer("at", { mode: "timestamp" }).notNull(),
day: text("day").notNull(),
visitor: text("visitor").notNull(),
},
(t) => [index("clicks_page_day").on(t.pageId, t.day, t.visitor), index("clicks_at").on(t.at)],
);
// Daily totals, kept forever.
export const dailyStats = sqliteTable(
"daily_stats",
{
pageId: integer("page_id")
.notNull()
.references(() => pages.id, { onDelete: "cascade" }),
day: text("day").notNull(),
clicks: integer("clicks").notNull().default(0),
uniques: integer("uniques").notNull().default(0),
lastAt: integer("last_at", { mode: "timestamp" }).notNull(),
},
(t) => [primaryKey({ columns: [t.pageId, t.day] })],
);
export const sessions = sqliteTable("sessions", {
id: text("id").primaryKey(), // sha256 of the cookie value
userId: integer("user_id")
.notNull()
.references(() => users.id, { onDelete: "cascade" }),
expiresAt: integer("expires_at", { mode: "timestamp" }).notNull(),
});
export const apiTokens = sqliteTable("api_tokens", {
id: integer("id").primaryKey({ autoIncrement: true }),
userId: integer("user_id")
.notNull()
.references(() => users.id, { onDelete: "cascade" }),
name: text("name").notNull(),
tokenHash: text("token_hash").notNull().unique(),
createdAt: createdAt(),
lastUsedAt: integer("last_used_at", { mode: "timestamp" }),
});
export const settings = sqliteTable("settings", {
key: text("key").primaryKey(),
value: text("value").notNull(),
});
+44
View File
@@ -0,0 +1,44 @@
import { mkdirSync } from "node:fs";
import path from "node:path";
import { serve } from "@hono/node-server";
import { createApp } from "./app.js";
import { createOidcProvider } from "./auth/oidc.js";
import { pruneSessions } from "./auth/sessions.js";
import { loadConfig } from "./config.js";
import { openDb } from "./db/index.js";
import { pruneClicks } from "./lib/stats.js";
const config = loadConfig();
mkdirSync(config.dataDir, { recursive: true });
const db = openDb(path.join(config.dataDir, "short.db"));
const app = createApp({
db,
config,
oidc: createOidcProvider(config),
webDir: path.resolve("dist/web"),
});
// Retention: drop individual clicks after the retention period and expired sessions, daily.
const housekeeping = () => {
try {
const clicks = pruneClicks(db, config.retentionDays);
const sessions = pruneSessions(db);
if (clicks || sessions) console.log(`Housekeeping: removed ${clicks} old clicks, ${sessions} expired sessions`);
} catch (err) {
console.error("Housekeeping failed", err);
}
};
housekeeping();
setInterval(housekeeping, 24 * 60 * 60 * 1000).unref();
const server = serve({ fetch: app.fetch, port: config.port }, (info) => {
console.log(`short listening on http://localhost:${info.port} (public URL ${config.baseUrl})`);
});
for (const signal of ["SIGINT", "SIGTERM"] as const) {
process.on(signal, () => {
server.close();
process.exit(0);
});
}
+18
View File
@@ -0,0 +1,18 @@
import { createHash, randomBytes, randomInt } from "node:crypto";
export function sha256(value: string): string {
return createHash("sha256").update(value).digest("hex");
}
export function randomToken(bytes = 32): string {
return randomBytes(bytes).toString("base64url");
}
// No 0/O/1/l/I to keep generated codes readable.
const CODE_ALPHABET = "abcdefghijkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789";
export function randomCode(length = 5): string {
let code = "";
for (let i = 0; i < length; i++) code += CODE_ALPHABET[randomInt(CODE_ALPHABET.length)];
return code;
}
+12
View File
@@ -0,0 +1,12 @@
export class HttpError extends Error {
constructor(
readonly status: 400 | 401 | 403 | 404 | 409 | 413 | 415,
message: string,
readonly issues?: Record<string, string[]>,
) {
super(message);
}
}
export const notFound = () => new HttpError(404, "Not found");
export const forbidden = () => new HttpError(403, "Forbidden");
+51
View File
@@ -0,0 +1,51 @@
import { mkdirSync, readFileSync, unlinkSync, writeFileSync } from "node:fs";
import path from "node:path";
import { randomToken } from "./crypto.js";
import { HttpError } from "./errors.js";
const MAX_AVATAR_BYTES = 2 * 1024 * 1024;
const NAME_PATTERN = /^[A-Za-z0-9_-]+\.(png|jpg|webp)$/;
export const CONTENT_TYPES = { png: "image/png", jpg: "image/jpeg", webp: "image/webp" } as const;
type Ext = keyof typeof CONTENT_TYPES;
// Detects the image type from its first bytes instead of trusting the upload's content type.
function sniff(bytes: Uint8Array): Ext | null {
const ascii = (start: number, end: number) => String.fromCharCode(...bytes.subarray(start, end));
if (bytes[0] === 0x89 && ascii(1, 4) === "PNG") return "png";
if (bytes[0] === 0xff && bytes[1] === 0xd8 && bytes[2] === 0xff) return "jpg";
if (ascii(0, 4) === "RIFF" && ascii(8, 12) === "WEBP") return "webp";
return null;
}
const mediaDir = (dataDir: string) => path.join(dataDir, "media");
export async function saveAvatar(dataDir: string, file: File): Promise<string> {
if (file.size > MAX_AVATAR_BYTES) throw new HttpError(413, "Image must be smaller than 2 MB");
const bytes = new Uint8Array(await file.arrayBuffer());
const ext = sniff(bytes);
if (!ext) throw new HttpError(415, "Only PNG, JPEG and WebP images are allowed");
const name = `${randomToken(16)}.${ext}`;
mkdirSync(mediaDir(dataDir), { recursive: true });
writeFileSync(path.join(mediaDir(dataDir), name), bytes);
return name;
}
export function readMedia(dataDir: string, name: string): { bytes: Buffer; type: string } | null {
const match = name.match(NAME_PATTERN);
if (!match) return null;
try {
return { bytes: readFileSync(path.join(mediaDir(dataDir), name)), type: CONTENT_TYPES[match[1] as Ext] };
} catch {
return null;
}
}
export function removeMedia(dataDir: string, name: string): void {
if (!NAME_PATTERN.test(name)) return;
try {
unlinkSync(path.join(mediaDir(dataDir), name));
} catch {
// Already gone.
}
}
+318
View File
@@ -0,0 +1,318 @@
import { and, asc, eq, inArray, sql } from "drizzle-orm";
import type { Block, Conflict, PageDetail, PageSummary } from "../../shared/api-types.js";
import {
DEFAULT_THEME,
RESERVED_CODES,
type CreateBlockInput,
type CreatePageInput,
type Theme,
type UpdatePageInput,
} from "../../shared/validation.js";
import type { Db } from "../db/index.js";
import { blocks, dailyStats, pages, settings, users } from "../db/schema.js";
import { randomCode } from "./crypto.js";
import { forbidden, HttpError, notFound } from "./errors.js";
import { canLinkTo, canManagePage, canWriteNamespace, type Actor } from "./permissions.js";
type PageRow = typeof pages.$inferSelect;
const PINNED_KEY = "pinned_page_id";
export function pagePath(page: { namespace: string; code: string }): string {
return page.namespace ? `/${page.namespace}/${page.code}` : `/${page.code}`;
}
export function avatarUrl(avatar: string | null): string | null {
return avatar ? `/~/media/${avatar}` : null;
}
export function getPinnedPageId(db: Db): number | null {
const row = db.select().from(settings).where(eq(settings.key, PINNED_KEY)).get();
return row ? Number(row.value) : null;
}
export function findByPath(db: Db, namespace: string, code: string): PageRow | undefined {
return db
.select()
.from(pages)
.where(and(eq(pages.namespace, namespace), eq(pages.code, code)))
.get();
}
function isUsername(db: Db, name: string): boolean {
return !!db
.select({ id: users.id })
.from(users)
.where(sql`lower(${users.username}) = lower(${name})`)
.get();
}
function codeTaken(db: Db, namespace: string, code: string): boolean {
if (findByPath(db, namespace, code)) return true;
return namespace === "" && (RESERVED_CODES.has(code.toLowerCase()) || isUsername(db, code));
}
function resolveNamespace(db: Db, actor: Actor, requested: string | undefined): string {
const namespace = requested ?? actor.username;
if (!canWriteNamespace(actor, namespace)) throw forbidden();
if (namespace !== "" && !db.select().from(users).where(eq(users.username, namespace)).get()) {
throw new HttpError(400, "Unknown namespace", { namespace: ["No user with this name"] });
}
return namespace;
}
function loadManagedPage(db: Db, actor: Actor, id: number): PageRow {
const page = db.select().from(pages).where(eq(pages.id, id)).get();
// Pages outside the actor's reach are reported as missing, so ids can't be probed.
if (!page || !canManagePage(actor, page)) throw notFound();
return page;
}
export function createPage(db: Db, actor: Actor, input: CreatePageInput): PageSummary {
const namespace = resolveNamespace(db, actor, input.namespace);
let code = input.code;
if (code) {
if (codeTaken(db, namespace, code)) {
throw new HttpError(409, "Shortcode is not available", { code: ["Already in use or reserved"] });
}
} else {
for (let attempt = 0; attempt < 20 && !code; attempt++) {
const candidate = randomCode();
if (!codeTaken(db, namespace, candidate)) code = candidate;
}
if (!code) throw new HttpError(409, "Could not generate a free shortcode");
}
const row = db
.insert(pages)
.values({
namespace,
code,
kind: input.kind,
dest: input.kind === "redirect" ? input.dest : null,
title: input.kind === "linkpage" ? input.title : null,
theme: input.kind === "linkpage" ? DEFAULT_THEME : null,
createdBy: actor.id,
})
.returning()
.get();
return toSummary(row, 0, false);
}
export function updatePage(db: Db, actor: Actor, id: number, input: UpdatePageInput): PageDetail {
const page = loadManagedPage(db, actor, id);
if (input.dest !== undefined && page.kind !== "redirect") throw new HttpError(400, "Only redirects have a destination");
if ((input.title !== undefined || input.theme !== undefined) && page.kind !== "linkpage") {
throw new HttpError(400, "Only link pages have a title and theme");
}
db.update(pages)
.set({ ...input, updatedAt: new Date() })
.where(eq(pages.id, id))
.run();
return getPageDetail(db, actor, id);
}
export function setAvatar(db: Db, actor: Actor, id: number, avatar: string | null): string | null {
const page = loadManagedPage(db, actor, id);
if (page.kind !== "linkpage") throw new HttpError(400, "Only link pages have an avatar");
db.update(pages).set({ avatar, updatedAt: new Date() }).where(eq(pages.id, id)).run();
return page.avatar;
}
// Returns the removed page's avatar file, if any, so the caller can delete it from disk.
export function deletePage(db: Db, actor: Actor, id: number): string | null {
const page = loadManagedPage(db, actor, id);
db.transaction((tx) => {
// Blocks, clicks and stats go with the page via ON DELETE CASCADE.
tx.delete(pages).where(eq(pages.id, id)).run();
tx.delete(settings)
.where(and(eq(settings.key, PINNED_KEY), eq(settings.value, String(id))))
.run();
});
return page.avatar;
}
function totalClicks(db: Db, pageIds: number[]): Map<number, number> {
if (pageIds.length === 0) return new Map();
const rows = db
.select({ pageId: dailyStats.pageId, total: sql<number>`sum(${dailyStats.clicks})` })
.from(dailyStats)
.where(inArray(dailyStats.pageId, pageIds))
.groupBy(dailyStats.pageId)
.all();
return new Map(rows.map((r) => [r.pageId, r.total]));
}
function toSummary(row: PageRow, clicks: number, pinned: boolean): PageSummary {
return {
id: row.id,
namespace: row.namespace,
code: row.code,
path: pagePath(row),
kind: row.kind,
dest: row.dest,
title: row.title,
totalClicks: clicks,
pinned,
};
}
export function listPages(db: Db, actor: Actor): PageSummary[] {
const query = db.select().from(pages);
const rows = (actor.isAdmin ? query : query.where(eq(pages.namespace, actor.username)))
.orderBy(asc(pages.namespace), asc(pages.code))
.all();
const counts = totalClicks(
db,
rows.map((r) => r.id),
);
const pinned = getPinnedPageId(db);
return rows.map((r) => toSummary(r, counts.get(r.id) ?? 0, r.id === pinned));
}
export function getBlocks(db: Db, pageId: number): Block[] {
const rows = db.select().from(blocks).where(eq(blocks.pageId, pageId)).orderBy(asc(blocks.position)).all();
const targetIds = rows.flatMap((b) => (b.targetId ? [b.targetId] : []));
const targets = targetIds.length
? new Map(
db
.select()
.from(pages)
.where(inArray(pages.id, targetIds))
.all()
.map((t) => [t.id, t]),
)
: new Map<number, PageRow>();
return rows.map((b) => {
const target = b.targetId ? targets.get(b.targetId) : undefined;
return {
id: b.id,
position: b.position,
kind: b.kind,
label: b.label,
markdown: b.markdown,
target: target ? { id: target.id, path: pagePath(target), dest: target.dest } : null,
};
});
}
export function getPageDetail(db: Db, actor: Actor, id: number): PageDetail {
const page = loadManagedPage(db, actor, id);
const clicks = totalClicks(db, [id]).get(id) ?? 0;
return {
...toSummary(page, clicks, getPinnedPageId(db) === id),
theme: (page.theme as Theme | null) ?? DEFAULT_THEME,
avatarUrl: avatarUrl(page.avatar),
blocks: page.kind === "linkpage" ? getBlocks(db, id) : [],
};
}
export function assertCanManage(db: Db, actor: Actor, id: number): void {
loadManagedPage(db, actor, id);
}
function loadLinkPage(db: Db, actor: Actor, id: number): PageRow {
const page = loadManagedPage(db, actor, id);
if (page.kind !== "linkpage") throw new HttpError(400, "Blocks can only be added to link pages");
return page;
}
export function addBlock(db: Db, actor: Actor, pageId: number, input: CreateBlockInput): Block[] {
const page = loadLinkPage(db, actor, pageId);
let targetId: number | null = null;
if (input.kind === "link") {
const target = db.select().from(pages).where(eq(pages.id, input.targetId)).get();
if (!target || !canLinkTo(actor, page, target)) {
throw new HttpError(400, "Invalid link target", { targetId: ["Pick one of your redirect links"] });
}
targetId = target.id;
}
const max = db
.select({ max: sql<number | null>`max(${blocks.position})` })
.from(blocks)
.where(eq(blocks.pageId, pageId))
.get();
db.insert(blocks)
.values({
pageId,
position: (max?.max ?? -1) + 1,
kind: input.kind,
label: input.kind === "link" ? input.label : null,
markdown: input.kind === "text" ? input.markdown : null,
targetId,
})
.run();
return getBlocks(db, pageId);
}
function loadManagedBlock(db: Db, actor: Actor, blockId: number) {
const block = db.select().from(blocks).where(eq(blocks.id, blockId)).get();
if (!block) throw notFound();
loadManagedPage(db, actor, block.pageId);
return block;
}
export function updateBlock(
db: Db,
actor: Actor,
blockId: number,
input: { label?: string; markdown?: string },
): Block[] {
const block = loadManagedBlock(db, actor, blockId);
if (block.kind === "link" && input.markdown !== undefined) throw new HttpError(400, "Link blocks have no text");
if (block.kind === "text" && input.label !== undefined) throw new HttpError(400, "Text blocks have no label");
db.update(blocks).set(input).where(eq(blocks.id, blockId)).run();
return getBlocks(db, block.pageId);
}
export function deleteBlock(db: Db, actor: Actor, blockId: number): Block[] {
const block = loadManagedBlock(db, actor, blockId);
db.delete(blocks).where(eq(blocks.id, blockId)).run();
return getBlocks(db, block.pageId);
}
export function reorderBlocks(db: Db, actor: Actor, pageId: number, ids: number[]): Block[] {
loadLinkPage(db, actor, pageId);
const current = db.select({ id: blocks.id }).from(blocks).where(eq(blocks.pageId, pageId)).all();
const currentIds = new Set(current.map((b) => b.id));
if (ids.length !== currentIds.size || new Set(ids).size !== ids.length || !ids.every((id) => currentIds.has(id))) {
throw new HttpError(400, "ids must list every block of the page exactly once");
}
db.transaction((tx) => {
ids.forEach((id, position) => tx.update(blocks).set({ position }).where(eq(blocks.id, id)).run());
});
return getBlocks(db, pageId);
}
export function pinPage(db: Db, actor: Actor, pageId: number | null): void {
if (!actor.isAdmin) throw forbidden();
if (pageId === null) {
db.delete(settings).where(eq(settings.key, PINNED_KEY)).run();
return;
}
if (!db.select().from(pages).where(eq(pages.id, pageId)).get()) throw notFound();
db.insert(settings)
.values({ key: PINNED_KEY, value: String(pageId) })
.onConflictDoUpdate({ target: settings.key, set: { value: String(pageId) } })
.run();
}
// Users whose name is also used as a root code (possible when the user logs in after the code was created).
export function listConflicts(db: Db): Conflict[] {
return db
.select({ username: users.username, pageId: pages.id })
.from(users)
.innerJoin(pages, and(eq(pages.namespace, ""), sql`lower(${pages.code}) = lower(${users.username})`))
.all();
}
export function listUsernames(db: Db): string[] {
return db
.select({ username: users.username })
.from(users)
.orderBy(asc(users.username))
.all()
.map((u) => u.username);
}
+26
View File
@@ -0,0 +1,26 @@
// All authorization rules in one place. Ownership follows the namespace:
// a user owns everything under /<username>/, root ("") belongs to admins.
export interface Actor {
id: number;
username: string;
isAdmin: boolean;
}
interface Namespaced {
namespace: string;
}
export function canWriteNamespace(actor: Actor, namespace: string): boolean {
return actor.isAdmin || namespace === actor.username;
}
export function canManagePage(actor: Actor, page: Namespaced): boolean {
return canWriteNamespace(actor, page.namespace);
}
// A link page may only contain buttons for links in its own namespace, unless an admin builds it.
export function canLinkTo(actor: Actor, page: Namespaced, target: Namespaced & { kind: string }): boolean {
if (target.kind !== "redirect") return false;
return actor.isAdmin || target.namespace === page.namespace;
}
+132
View File
@@ -0,0 +1,132 @@
import { and, desc, eq, gte, lt, sql } from "drizzle-orm";
import type { PageStats } from "../../shared/api-types.js";
import type { Db, Tx } from "../db/index.js";
import { clicks, dailyStats, settings } from "../db/schema.js";
import { randomToken, sha256 } from "./crypto.js";
// Calendar day (YYYY-MM-DD) in the configured timezone.
export function dayOf(date: Date, timezone: string): string {
return new Intl.DateTimeFormat("en-CA", {
timeZone: timezone,
year: "numeric",
month: "2-digit",
day: "2-digit",
}).format(date);
}
function addDays(day: string, delta: number): string {
const d = new Date(`${day}T12:00:00Z`);
d.setUTCDate(d.getUTCDate() + delta);
return d.toISOString().slice(0, 10);
}
// The visitor salt is random, stored only for the current day and replaced on the next one,
// so visitor hashes can't be linked across days or reversed after the fact.
function dailySalt(db: Db | Tx, day: string): string {
const row = db.select().from(settings).where(eq(settings.key, "visitor_salt")).get();
if (row) {
const stored = JSON.parse(row.value) as { day: string; salt: string };
if (stored.day === day) return stored.salt;
}
const salt = randomToken();
const value = JSON.stringify({ day, salt });
db.insert(settings)
.values({ key: "visitor_salt", value })
.onConflictDoUpdate({ target: settings.key, set: { value } })
.run();
return salt;
}
// Normalizes an IP so that the last part is dropped (IPv4 /24, IPv6 /48) before hashing.
export function anonymizeIp(ip: string): string {
const v4 = ip.match(/^(?:::ffff:)?(\d+)\.(\d+)\.(\d+)\.\d+$/);
if (v4) return `${v4[1]}.${v4[2]}.${v4[3]}.0`;
if (ip.includes(":")) return ip.split(":").slice(0, 3).join(":") + "::";
return "unknown";
}
export function recordClick(
db: Db,
timezone: string,
pageId: number,
ip: string,
userAgent: string,
now = new Date(),
): void {
const day = dayOf(now, timezone);
db.transaction((tx) => {
const visitor = sha256(`${dailySalt(tx, day)}|${anonymizeIp(ip)}|${userAgent}`);
const seen = tx
.select({ id: clicks.id })
.from(clicks)
.where(and(eq(clicks.pageId, pageId), eq(clicks.day, day), eq(clicks.visitor, visitor)))
.limit(1)
.get();
tx.insert(clicks).values({ pageId, at: now, day, visitor }).run();
tx.insert(dailyStats)
.values({ pageId, day, clicks: 1, uniques: seen ? 0 : 1, lastAt: now })
.onConflictDoUpdate({
target: [dailyStats.pageId, dailyStats.day],
set: {
clicks: sql`${dailyStats.clicks} + 1`,
uniques: sql`${dailyStats.uniques} + ${seen ? 0 : 1}`,
lastAt: now,
},
})
.run();
});
}
export function getStats(db: Db, timezone: string, pageId: number, days: number, now = new Date()): PageStats {
const today = dayOf(now, timezone);
const from = addDays(today, -(days - 1));
const rows = db
.select()
.from(dailyStats)
.where(and(eq(dailyStats.pageId, pageId), gte(dailyStats.day, from)))
.all();
const byDay = new Map(rows.map((r) => [r.day, r]));
const series = [];
for (let i = 0; i < days; i++) {
const day = addDays(from, i);
const row = byDay.get(day);
series.push({ day, clicks: row?.clicks ?? 0, uniques: row?.uniques ?? 0 });
}
const totals = db
.select({ total: sql<number>`coalesce(sum(${dailyStats.clicks}), 0)` })
.from(dailyStats)
.where(eq(dailyStats.pageId, pageId))
.get();
const last = db
.select({ lastAt: dailyStats.lastAt })
.from(dailyStats)
.where(eq(dailyStats.pageId, pageId))
.orderBy(desc(dailyStats.day))
.limit(1)
.get();
const todayRow = byDay.get(today);
return {
total: totals?.total ?? 0,
today: todayRow?.clicks ?? 0,
uniquesToday: todayRow?.uniques ?? 0,
lastVisit: last?.lastAt.toISOString() ?? null,
series,
};
}
export function resetStats(db: Db, pageId: number): void {
db.transaction((tx) => {
tx.delete(clicks).where(eq(clicks.pageId, pageId)).run();
tx.delete(dailyStats).where(eq(dailyStats.pageId, pageId)).run();
});
}
// Deletes individual clicks older than the retention period. Daily totals are kept.
export function pruneClicks(db: Db, retentionDays: number, now = new Date()): number {
const cutoff = new Date(now.getTime() - retentionDays * 24 * 60 * 60 * 1000);
return db.delete(clicks).where(lt(clicks.at, cutoff)).run().changes;
}
+16
View File
@@ -0,0 +1,16 @@
import MarkdownIt from "markdown-it";
// Raw HTML and images are disabled; markdown-it also rejects javascript: and similar link targets.
const md = new MarkdownIt({ html: false, linkify: true, breaks: true }).disable(["image", "table"]);
const defaultLinkOpen =
md.renderer.rules.link_open ?? ((tokens, idx, options, _env, self) => self.renderToken(tokens, idx, options));
md.renderer.rules.link_open = (tokens, idx, options, env, self) => {
tokens[idx]?.attrSet("rel", "noopener nofollow");
return defaultLinkOpen(tokens, idx, options, env, self);
};
export function renderMarkdown(source: string): string {
return md.render(source);
}
+76
View File
@@ -0,0 +1,76 @@
import { Hono, type Context } from "hono";
import { getConnInfo } from "@hono/node-server/conninfo";
import { eq } from "drizzle-orm";
import type { AppEnv, Deps } from "../app.js";
import { pages as pagesTable } from "../db/schema.js";
import { avatarUrl, findByPath, getBlocks, getPinnedPageId, pagePath } from "../lib/pages.js";
import { recordClick } from "../lib/stats.js";
import { DEFAULT_THEME, type Theme } from "../../shared/validation.js";
import { LinkPage, MessagePage } from "./views.js";
export function publicRoutes({ db, config }: Deps) {
const clientIp = (c: Context<AppEnv>): string => {
if (config.trustProxy) {
const forwarded = c.req.header("x-forwarded-for")?.split(",")[0]?.trim();
if (forwarded) return forwarded;
}
try {
return getConnInfo(c).remote.address ?? "unknown";
} catch {
return "unknown";
}
};
// Stats are written after the response has been handed off, so they never delay the visitor.
const track = (c: Context<AppEnv>, pageId: number) => {
const ip = clientIp(c);
const userAgent = c.req.header("user-agent") ?? "unknown";
setImmediate(() => {
try {
recordClick(db, config.timezone, pageId, ip, userAgent);
} catch (err) {
console.error("Failed to record click", err);
}
});
};
const notFoundPage = (c: Context<AppEnv>) =>
c.html(<MessagePage title="Not found" message="This link doesn't exist." />, 404);
const serve = (c: Context<AppEnv>, namespace: string, code: string) => {
const page = findByPath(db, namespace, code);
if (!page) return notFoundPage(c);
// The dashboard preview shouldn't inflate the stats.
if (c.req.query("preview") === undefined) track(c, page.id);
c.header("Cache-Control", "private, no-store");
if (page.kind === "redirect" && page.dest) return c.redirect(page.dest, 302);
return c.html(
<LinkPage
title={page.title ?? page.code}
avatarUrl={avatarUrl(page.avatar)}
theme={(page.theme as Theme | null) ?? DEFAULT_THEME}
blocks={getBlocks(db, page.id)}
logoDevToken={config.logoDevToken}
showAttribution={!config.disableAttribution}
/>,
);
};
return new Hono<AppEnv>()
.get("/", (c) => {
const pinnedId = getPinnedPageId(db);
const pinned = pinnedId ? db.select().from(pagesTable).where(eq(pagesTable.id, pinnedId)).get() : undefined;
if (pinned) return c.redirect(pagePath(pinned), 302);
return c.html(
<MessagePage
title="short"
message="Nothing is pinned to this page yet."
link={{ href: "/~/", label: "Open the dashboard" }}
/>,
);
})
.get("/:code", (c) => serve(c, "", c.req.param("code")))
.get("/:namespace/:code", (c) => serve(c, c.req.param("namespace"), c.req.param("code")));
}
+129
View File
@@ -0,0 +1,129 @@
import type { Child } from "hono/jsx";
import { raw } from "hono/html";
import type { Block } from "../../shared/api-types.js";
import type { Theme } from "../../shared/validation.js";
import { renderMarkdown } from "./markdown.js";
const STYLES = `
*{box-sizing:border-box}
body{margin:0;min-height:100vh;font-family:system-ui,-apple-system,"Segoe UI",sans-serif;background:var(--bg);color:var(--fg)}
main{display:flex;flex-direction:column;align-items:center;padding:3rem 1rem;max-width:28rem;margin:0 auto}
.avatar{width:96px;height:96px;border-radius:9999px;object-fit:cover;animation:zoom .6s ease both}
h1{font-size:2rem;margin:1.5rem 0 2rem;text-align:center;animation:zoom .6s ease both}
.blocks{width:100%;display:flex;flex-direction:column;gap:.75rem}
.blocks>*{animation:slide .5s ease both}
.button{display:flex;align-items:center;gap:.75rem;padding:.6rem .75rem;border-radius:.5rem;background:var(--btn);color:var(--btn-fg);text-decoration:none;font-weight:600;transition:filter .15s}
.button:hover{filter:brightness(1.15)}
.button .label{flex:1;text-align:center;margin-right:2rem}
.icon{width:2rem;height:2rem;border-radius:9999px;flex-shrink:0;display:flex;align-items:center;justify-content:center;background:rgba(255,255,255,.85);color:#374151;font-weight:700}
.text{line-height:1.5;text-align:center}
.text a{color:inherit}
footer{margin-top:3rem;font-size:.85rem;opacity:.5;text-align:center}
footer a{color:inherit}
.center{min-height:100vh;display:flex;flex-direction:column;align-items:center;justify-content:center;text-align:center;padding:1rem}
@keyframes zoom{from{transform:scale(.7);opacity:0}to{transform:none;opacity:1}}
@keyframes slide{from{transform:translateY(-20px);opacity:0}to{transform:none;opacity:1}}
@media (prefers-reduced-motion:reduce){*{animation:none!important}}
`;
const DARK: Theme = { background: "#111827", text: "#e5e7eb", button: "#475569", buttonText: "#ffffff" };
function Layout({ title, theme = DARK, children }: { title: string; theme?: Theme; children: Child }) {
// Theme values are validated hex colors, so they are safe to put into CSS.
const vars = `:root{--bg:${theme.background};--fg:${theme.text};--btn:${theme.button};--btn-fg:${theme.buttonText}}`;
return (
<>
{raw("<!doctype html>")}
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>{title}</title>
<link rel="icon" href="/~/short.svg" type="image/svg+xml" />
<style>{raw(vars + STYLES)}</style>
</head>
<body>{children}</body>
</html>
</>
);
}
function LinkIcon({ dest, logoDevToken }: { dest: string | null; logoDevToken: string | undefined }) {
let hostname = "";
try {
hostname = dest ? new URL(dest).hostname : "";
} catch {
// Fall through to the letter placeholder.
}
if (hostname && logoDevToken) {
const src = `https://img.logo.dev/${encodeURIComponent(hostname)}?token=${encodeURIComponent(logoDevToken)}`;
return <img class="icon" src={src} alt="" loading="lazy" />;
}
const letter = hostname.replace(/^www\./, "").charAt(0).toUpperCase() || "•";
return <span class="icon">{letter}</span>;
}
export interface LinkPageProps {
title: string;
avatarUrl: string | null;
theme: Theme;
blocks: Block[];
logoDevToken: string | undefined;
showAttribution: boolean;
}
export function LinkPage(props: LinkPageProps) {
return (
<Layout title={props.title} theme={props.theme}>
<main>
{props.avatarUrl && <img class="avatar" src={props.avatarUrl} alt="" />}
<h1>{props.title}</h1>
<div class="blocks">
{props.blocks.map((block, index) => {
const style = `animation-delay:${0.3 + index * 0.08}s`;
if (block.kind === "text") {
return <div class="text" style={style}>{raw(renderMarkdown(block.markdown ?? ""))}</div>;
}
if (!block.target) return null;
return (
<a class="button" href={block.target.path} style={style}>
<LinkIcon dest={block.target.dest} logoDevToken={props.logoDevToken} />
<span class="label">{block.label}</span>
</a>
);
})}
</div>
<footer>
{props.showAttribution && (
<p>
powered by <a href="https://github.com/traberph/short">traberph/short</a>
</p>
)}
{props.logoDevToken && (
<p>
Logos provided by <a href="https://logo.dev">Logo.dev</a>
</p>
)}
</footer>
</main>
</Layout>
);
}
export function MessagePage({ title, message, link }: { title: string; message: string; link?: { href: string; label: string } }) {
return (
<Layout title={title}>
<div class="center">
<h1>{title}</h1>
<p>{message}</p>
{link && (
<p>
<a href={link.href} style="color:inherit">
{link.label}
</a>
</p>
)}
</div>
</Layout>
);
}
+71
View File
@@ -0,0 +1,71 @@
// Response shapes of the JSON API, shared by server and admin UI.
import type { Theme } from "./validation.js";
export type PageKind = "redirect" | "linkpage";
export interface Me {
username: string;
isAdmin: boolean;
}
export interface PageSummary {
id: number;
namespace: string;
code: string;
path: string;
kind: PageKind;
dest: string | null;
title: string | null;
totalClicks: number;
pinned: boolean;
}
export interface Block {
id: number;
position: number;
kind: "link" | "text";
label: string | null;
markdown: string | null;
target: { id: number; path: string; dest: string | null } | null;
}
export interface PageDetail extends PageSummary {
theme: Theme;
avatarUrl: string | null;
blocks: Block[];
}
export interface StatsDay {
day: string;
clicks: number;
uniques: number;
}
export interface PageStats {
total: number;
today: number;
uniquesToday: number;
lastVisit: string | null;
series: StatsDay[];
}
export interface ApiToken {
id: number;
name: string;
createdAt: string;
lastUsedAt: string | null;
}
export interface CreatedToken extends ApiToken {
token: string;
}
export interface Conflict {
username: string;
pageId: number;
}
export interface ApiError {
error: string;
issues?: Record<string, string[]>;
}
+92
View File
@@ -0,0 +1,92 @@
import { z } from "zod";
// Shortcodes: letters, digits, "-" and "_". Everything else in the URL space is reserved by construction
// (the admin UI and API live under "/~").
export const CODE_PATTERN = /^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/;
// Root codes that would be confusing or are kept free for future use.
export const RESERVED_CODES = new Set(["api", "auth", "assets", "static", "admin", "login", "logout", "health", "media"]);
// Authentik usernames used as namespaces must be URL-safe.
export const USERNAME_PATTERN = /^[A-Za-z0-9._-]{1,64}$/;
export function isValidUsername(username: string): boolean {
return USERNAME_PATTERN.test(username) && username !== "." && username !== "..";
}
export function isHttpUrl(value: string): boolean {
try {
const url = new URL(value);
return url.protocol === "http:" || url.protocol === "https:";
} catch {
return false;
}
}
const hexColor = z.string().regex(/^#[0-9a-fA-F]{6}$/, "Must be a hex color like #112233");
export const themeSchema = z.object({
background: hexColor,
text: hexColor,
button: hexColor,
buttonText: hexColor,
});
export type Theme = z.infer<typeof themeSchema>;
export const DEFAULT_THEME: Theme = {
background: "#111827",
text: "#e5e7eb",
button: "#475569",
buttonText: "#ffffff",
};
const destSchema = z.string().trim().max(2048).refine(isHttpUrl, "Must be an http(s) URL");
const codeSchema = z.string().trim().regex(CODE_PATTERN, "Use 1–64 letters, digits, - or _");
const titleSchema = z.string().trim().min(1).max(100);
export const createPageSchema = z.discriminatedUnion("kind", [
z.object({
kind: z.literal("redirect"),
// "" = root (admins only); omitted = the caller's own namespace
namespace: z.string().optional(),
code: codeSchema.optional(),
dest: destSchema,
}),
z.object({
kind: z.literal("linkpage"),
namespace: z.string().optional(),
code: codeSchema.optional(),
title: titleSchema,
}),
]);
export type CreatePageInput = z.infer<typeof createPageSchema>;
export const updatePageSchema = z.object({
dest: destSchema.optional(),
title: titleSchema.optional(),
theme: themeSchema.optional(),
});
export type UpdatePageInput = z.infer<typeof updatePageSchema>;
export const createBlockSchema = z.discriminatedUnion("kind", [
z.object({ kind: z.literal("link"), targetId: z.number().int().positive(), label: titleSchema }),
z.object({ kind: z.literal("text"), markdown: z.string().max(5000) }),
]);
export type CreateBlockInput = z.infer<typeof createBlockSchema>;
export const updateBlockSchema = z.object({
label: titleSchema.optional(),
markdown: z.string().max(5000).optional(),
});
export const reorderBlocksSchema = z.object({
ids: z.array(z.number().int().positive()).max(500),
});
export const statsRangeSchema = z.object({
days: z.coerce.number().pipe(z.union([z.literal(7), z.literal(30), z.literal(90)])).default(7),
});
export const pinSchema = z.object({ pageId: z.number().int().positive() });
export const createTokenSchema = z.object({ name: z.string().trim().min(1).max(100) });
-23
View File
@@ -1,23 +0,0 @@
import toast from "react-hot-toast";
export function hashToColor(hash: string | null): string {
if (!hash) {
return "black";
}
const r = parseInt(hash.slice(0, 2), 16);
const g = parseInt(hash.slice(2, 4), 16);
const b = parseInt(hash.slice(4, 6), 16);
const color = `rgb(${r}, ${g}, ${b})`;
return color;
}
export function handleToast(state: { message: string, error?: any }) {
if (state.message) {
console.log(state);
if (state.error) {
toast.error(state.message);
} else {
toast.success(state.message);
}
}
}
+58
View File
@@ -0,0 +1,58 @@
import { useCallback, useEffect, useState } from "react";
import type { ApiError } from "../shared/api-types.js";
export class ApiRequestError extends Error {
constructor(
readonly status: number,
message: string,
readonly issues?: Record<string, string[]>,
) {
super(message);
}
}
export async function api<T = void>(method: string, path: string, body?: unknown): Promise<T> {
const isForm = body instanceof FormData;
const res = await fetch(`/~/api${path}`, {
method,
credentials: "same-origin",
headers: body !== undefined && !isForm ? { "content-type": "application/json" } : undefined,
body: body === undefined ? undefined : isForm ? body : JSON.stringify(body),
});
if (res.status === 204) return undefined as T;
const data: unknown = await res.json().catch(() => ({ error: res.statusText }));
if (!res.ok) {
const err = data as ApiError;
throw new ApiRequestError(res.status, err.error ?? "Request failed", err.issues);
}
return data as T;
}
// Loads data on mount and whenever `path` changes; `reload` refetches, `set` updates locally.
export function useApi<T>(path: string | null) {
const [data, setData] = useState<T | undefined>();
const [error, setError] = useState<ApiRequestError | undefined>();
const reload = useCallback(async () => {
if (!path) return;
try {
setData(await api<T>("GET", path));
setError(undefined);
} catch (err) {
setError(err instanceof ApiRequestError ? err : new ApiRequestError(0, String(err)));
}
}, [path]);
useEffect(() => {
void reload();
}, [reload]);
return { data, error, reload, set: setData };
}
export function errorMessage(err: unknown): string {
if (err instanceof ApiRequestError && err.issues) {
return Object.values(err.issues).flat().join(", ") || err.message;
}
return err instanceof Error ? err.message : String(err);
}
+156
View File
@@ -0,0 +1,156 @@
import { useState } from "react";
import { DndContext, KeyboardSensor, PointerSensor, closestCenter, useSensor, useSensors, type DragEndEvent } from "@dnd-kit/core";
import { SortableContext, arrayMove, sortableKeyboardCoordinates, useSortable, verticalListSortingStrategy } from "@dnd-kit/sortable";
import { CSS } from "@dnd-kit/utilities";
import type { Block, PageSummary } from "../../shared/api-types.js";
import { api, useApi } from "../api.js";
import { useAction } from "./ui.js";
function SortableBlock({ block, onChange }: { block: Block; onChange: (blocks: Block[]) => void }) {
const { attributes, listeners, setNodeRef, transform, transition, isDragging } = useSortable({ id: block.id });
const [editing, setEditing] = useState(false);
const [text, setText] = useState(block.kind === "text" ? (block.markdown ?? "") : (block.label ?? ""));
const { busy, run } = useAction();
const save = () =>
run(async () => {
onChange(await api<Block[]>("PATCH", `/blocks/${block.id}`, block.kind === "text" ? { markdown: text } : { label: text }));
setEditing(false);
});
const remove = () => run(async () => onChange(await api<Block[]>("DELETE", `/blocks/${block.id}`)));
return (
<div
ref={setNodeRef}
style={{ transform: CSS.Transform.toString(transform), transition }}
className={`flex items-start gap-3 rounded bg-gray-800 p-3 ${isDragging ? "relative z-10 opacity-80 shadow-lg" : ""}`}
>
<button className="cursor-grab touch-none px-1 text-gray-500" aria-label="Drag to reorder" {...attributes} {...listeners}>
⠿
</button>
<div className="min-w-0 flex-1">
<div className="text-xs text-gray-500 uppercase">{block.kind === "text" ? "Text" : `Link → ${block.target?.path}`}</div>
{editing ? (
block.kind === "text" ? (
<textarea rows={4} value={text} onChange={(e) => setText(e.target.value)} />
) : (
<input value={text} onChange={(e) => setText(e.target.value)} />
)
) : (
<div className="truncate whitespace-pre-wrap text-white">{block.kind === "text" ? block.markdown : block.label}</div>
)}
</div>
<div className="flex gap-2">
{editing ? (
<button className="btn px-2 py-1 text-sm" onClick={save} disabled={busy}>
Save
</button>
) : (
<button className="btn btn-secondary px-2 py-1 text-sm" onClick={() => setEditing(true)}>
Edit
</button>
)}
<button className="btn btn-danger px-2 py-1 text-sm" onClick={remove} disabled={busy}>
✕
</button>
</div>
</div>
);
}
export function BlockEditor({
pageId,
namespace,
isAdmin,
blocks,
onChange,
}: {
pageId: number;
namespace: string;
isAdmin: boolean;
blocks: Block[];
onChange: (blocks: Block[]) => void;
}) {
const pages = useApi<PageSummary[]>("/pages");
const { busy, run } = useAction();
const [targetId, setTargetId] = useState("");
const [label, setLabel] = useState("");
const [markdown, setMarkdown] = useState("");
const sensors = useSensors(
useSensor(PointerSensor, { activationConstraint: { distance: 5 } }),
useSensor(KeyboardSensor, { coordinateGetter: sortableKeyboardCoordinates }),
);
// Same rule as the server: own namespace only, unless admin.
const targets = (pages.data ?? []).filter((p) => p.kind === "redirect" && (isAdmin || p.namespace === namespace));
const onDragEnd = ({ active, over }: DragEndEvent) => {
if (!over || active.id === over.id) return;
const reordered = arrayMove(
blocks,
blocks.findIndex((b) => b.id === active.id),
blocks.findIndex((b) => b.id === over.id),
);
onChange(reordered);
void run(async () => onChange(await api<Block[]>("PUT", `/pages/${pageId}/blocks/order`, { ids: reordered.map((b) => b.id) })));
};
const addLink = () =>
run(async () => {
onChange(await api<Block[]>("POST", `/pages/${pageId}/blocks`, { kind: "link", targetId: Number(targetId), label }));
setTargetId("");
setLabel("");
});
const addText = () =>
run(async () => {
onChange(await api<Block[]>("POST", `/pages/${pageId}/blocks`, { kind: "text", markdown }));
setMarkdown("");
});
return (
<section className="card">
<h2 className="mb-4">Blocks</h2>
<DndContext sensors={sensors} collisionDetection={closestCenter} onDragEnd={onDragEnd}>
<SortableContext items={blocks.map((b) => b.id)} strategy={verticalListSortingStrategy}>
<div className="flex flex-col gap-2">
{blocks.map((b) => (
<SortableBlock key={b.id} block={b} onChange={onChange} />
))}
{!blocks.length && <p className="text-gray-500">No blocks yet.</p>}
</div>
</SortableContext>
</DndContext>
<div className="mt-6 grid gap-6 md:grid-cols-2">
<div>
<h3 className="mb-2 font-semibold text-white">Add link button</h3>
<select value={targetId} onChange={(e) => setTargetId(e.target.value)} className="mb-2">
<option value="">Choose a short link…</option>
{targets.map((p) => (
<option key={p.id} value={p.id}>
{p.path} → {p.dest}
</option>
))}
</select>
<input className="mb-2" placeholder="Button label" value={label} onChange={(e) => setLabel(e.target.value)} />
<button className="btn" onClick={addLink} disabled={busy || !targetId || !label.trim()}>
Add link
</button>
</div>
<div>
<h3 className="mb-2 font-semibold text-white">Add text</h3>
<textarea
className="mb-2"
rows={3}
placeholder="**Markdown** is supported: bold, italic, links, lists, headings"
value={markdown}
onChange={(e) => setMarkdown(e.target.value)}
/>
<button className="btn" onClick={addText} disabled={busy || !markdown.trim()}>
Add text
</button>
</div>
</div>
</section>
);
}
+72
View File
@@ -0,0 +1,72 @@
import { useEffect, useState } from "react";
import QRCode, { type QRCodeErrorCorrectionLevel } from "qrcode";
const LEVELS: QRCodeErrorCorrectionLevel[] = ["L", "M", "Q", "H"];
function download(href: string, filename: string) {
const a = document.createElement("a");
a.href = href;
a.download = filename;
a.click();
}
export function QrPanel({ url, name }: { url: string; name: string }) {
const [level, setLevel] = useState<QRCodeErrorCorrectionLevel>("Q");
const [dark, setDark] = useState("#000000");
const [light, setLight] = useState("#ffffff");
const [svg, setSvg] = useState("");
const options = { errorCorrectionLevel: level, margin: 2, color: { dark, light } };
useEffect(() => {
QRCode.toString(url, { errorCorrectionLevel: level, margin: 2, color: { dark, light }, type: "svg" }).then(setSvg, () => setSvg(""));
}, [url, level, dark, light]);
const downloadSvg = () => {
const blobUrl = URL.createObjectURL(new Blob([svg], { type: "image/svg+xml" }));
download(blobUrl, `${name}.svg`);
setTimeout(() => URL.revokeObjectURL(blobUrl), 1000);
};
const downloadPng = async () => download(await QRCode.toDataURL(url, { ...options, width: 1024 }), `${name}.png`);
return (
<section className="card">
<h2 className="mb-4">QR code</h2>
<div className="flex flex-wrap gap-6">
<div
className="h-40 w-40 overflow-hidden rounded [&>svg]:h-full [&>svg]:w-full"
// The SVG markup is generated locally by the qrcode library.
dangerouslySetInnerHTML={{ __html: svg }}
/>
<div className="flex flex-col gap-3 text-sm">
<div className="flex items-center gap-2">
Error correction:
{LEVELS.map((l) => (
<button
key={l}
className={`cursor-pointer rounded px-2 ${l === level ? "bg-gray-600 text-white" : "text-gray-400"}`}
onClick={() => setLevel(l)}
>
{l}
</button>
))}
</div>
<label className="flex items-center gap-3 normal-case">
Foreground <input type="color" value={dark} onChange={(e) => setDark(e.target.value)} />
</label>
<label className="flex items-center gap-3 normal-case">
Background <input type="color" value={light} onChange={(e) => setLight(e.target.value)} />
</label>
<div className="flex gap-2">
<button className="btn btn-secondary py-1" onClick={downloadSvg} disabled={!svg}>
SVG
</button>
<button className="btn btn-secondary py-1" onClick={downloadPng}>
PNG
</button>
</div>
</div>
</div>
</section>
);
}
+110
View File
@@ -0,0 +1,110 @@
import { useEffect, useRef, useState } from "react";
import uPlot from "uplot";
import "uplot/dist/uPlot.min.css";
import type { PageStats, StatsDay } from "../../shared/api-types.js";
import { api, useApi } from "../api.js";
import { useAction } from "./ui.js";
const RANGES = [7, 30, 90] as const;
function Chart({ series }: { series: StatsDay[] }) {
const container = useRef<HTMLDivElement>(null);
useEffect(() => {
const el = container.current;
if (!el) return;
const x = series.map((d) => new Date(`${d.day}T00:00:00`).getTime() / 1000);
const axis = { stroke: "#9ca3af", grid: { stroke: "#1f2937" }, ticks: { stroke: "#1f2937" } };
const plot = new uPlot(
{
width: el.clientWidth,
height: 220,
cursor: { drag: { x: false, y: false } },
scales: { y: { range: (_u, _min, max) => [0, Math.max(4, Math.ceil(max * 1.1))] } },
axes: [
{
...axis,
// One tick per day (or week), labelled with the date only.
incrs: [86400, 7 * 86400],
values: (_u, ticks) =>
ticks.map((t) => new Date(t * 1000).toLocaleDateString(undefined, { month: "short", day: "numeric" })),
},
{ ...axis, values: (_u, ticks) => ticks.map((t) => (Number.isInteger(t) ? String(t) : "")) },
],
series: [
{},
{ label: "Clicks", stroke: "#22c55e", width: 2, fill: "rgba(34,197,94,0.12)", points: { show: series.length <= 30 } },
{ label: "Unique visitors", stroke: "#60a5fa", width: 2, points: { show: series.length <= 30 } },
],
},
[x, series.map((d) => d.clicks), series.map((d) => d.uniques)],
el,
);
const resize = new ResizeObserver(() => plot.setSize({ width: el.clientWidth, height: 220 }));
resize.observe(el);
return () => {
resize.disconnect();
plot.destroy();
};
}, [series]);
return <div ref={container} className="w-full" />;
}
export function StatsPanel({ pageId }: { pageId: number }) {
const [days, setDays] = useState<(typeof RANGES)[number]>(7);
const stats = useApi<PageStats>(`/pages/${pageId}/stats?days=${days}`);
const { busy, run } = useAction();
const reset = () => {
if (!confirm("Delete all stats for this page?")) return;
void run(async () => {
await api("DELETE", `/pages/${pageId}/stats`);
await stats.reload();
}, "Stats reset");
};
const s = stats.data;
const tiles = s
? [
["Total clicks", s.total],
["Clicks today", s.today],
["Unique visitors today", s.uniquesToday],
["Last visit", s.lastVisit ? new Date(s.lastVisit).toLocaleString() : "—"],
]
: [];
return (
<section className="card">
<div className="mb-4 flex flex-wrap items-center justify-between gap-3">
<h2>Stats</h2>
<div className="flex items-center gap-2">
{RANGES.map((r) => (
<button key={r} className={`btn py-1 ${r === days ? "" : "btn-secondary"}`} onClick={() => setDays(r)}>
{r}d
</button>
))}
<button className="btn btn-danger py-1" onClick={reset} disabled={busy}>
Reset
</button>
</div>
</div>
{s && (
<>
<div className="mb-4 grid grid-cols-2 gap-3 sm:grid-cols-4">
{tiles.map(([label, value]) => (
<div key={label} className="rounded bg-gray-900/60 p-3">
<div className="text-xs text-gray-400 uppercase">{label}</div>
<div className="text-lg font-semibold text-white">{value}</div>
</div>
))}
</div>
<Chart series={s.series} />
<p className="mt-2 text-xs text-gray-500">
Unique visitors are counted per day. Individual clicks are kept for 90 days, daily totals forever.
</p>
</>
)}
</section>
);
}
+74
View File
@@ -0,0 +1,74 @@
import { createContext, useCallback, useContext, useState, type ReactNode } from "react";
import { errorMessage } from "../api.js";
import { linkHandler } from "../router.js";
export function Link({ to, className, children }: { to: string; className?: string; children: ReactNode }) {
return (
<a href={to} onClick={linkHandler(to)} className={className}>
{children}
</a>
);
}
export function Field({ label, children, hint }: { label: string; children: ReactNode; hint?: string }) {
return (
<div className="mb-3">
<label>{label}</label>
{children}
{hint && <p className="mt-1 text-xs text-gray-500">{hint}</p>}
</div>
);
}
type Toast = { id: number; message: string; error: boolean };
const ToastContext = createContext<(message: string, error?: boolean) => void>(() => {});
export function ToastProvider({ children }: { children: ReactNode }) {
const [toasts, setToasts] = useState<Toast[]>([]);
const show = useCallback((message: string, error = false) => {
const id = Date.now() + Math.random();
setToasts((t) => [...t, { id, message, error }]);
setTimeout(() => setToasts((t) => t.filter((x) => x.id !== id)), 3500);
}, []);
return (
<ToastContext.Provider value={show}>
{children}
<div className="fixed top-4 right-4 z-50 flex flex-col gap-2">
{toasts.map((t) => (
<div key={t.id} className={`rounded px-4 py-2 text-white shadow-lg ${t.error ? "bg-red-800" : "bg-green-700"}`}>
{t.message}
</div>
))}
</div>
</ToastContext.Provider>
);
}
export const useToast = () => useContext(ToastContext);
// Runs an async action with a busy flag and reports failures as a toast.
export function useAction() {
const toast = useToast();
const [busy, setBusy] = useState(false);
const run = useCallback(
async (action: () => Promise<unknown>, success?: string): Promise<boolean> => {
setBusy(true);
try {
await action();
if (success) toast(success);
return true;
} catch (err) {
toast(errorMessage(err), true);
return false;
} finally {
setBusy(false);
}
},
[toast],
);
return { busy, run };
}
export function publicUrl(path: string): string {
return `${location.origin}${path}`;
}
+16
View File
@@ -0,0 +1,16 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#111827" />
<link rel="icon" href="/~/short.svg" type="image/svg+xml" />
<link rel="manifest" href="/~/manifest.webmanifest" />
<link rel="apple-touch-icon" href="/~/icon-192x192.png" />
<title>short</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="./main.tsx"></script>
</body>
</html>
+80
View File
@@ -0,0 +1,80 @@
import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import type { Me } from "../shared/api-types.js";
import { useApi } from "./api.js";
import { Link, ToastProvider } from "./components/ui.js";
import { usePath } from "./router.js";
import { Dashboard } from "./screens/Dashboard.js";
import { PageScreen } from "./screens/PageScreen.js";
import { TokensScreen } from "./screens/TokensScreen.js";
import "./styles.css";
function Login() {
return (
<div className="flex min-h-screen flex-col items-center justify-center gap-6 p-6 text-center">
<img src="/~/short.svg" alt="" className="h-16 w-16" />
<h1>short</h1>
<a className="btn" href="/~/auth/login">
Sign in
</a>
<a href="/" className="text-sm hover:underline">
back to root
</a>
</div>
);
}
function App() {
const me = useApi<Me>("/me");
const path = usePath();
if (me.error?.status === 401) return <Login />;
if (me.error) return <p className="p-10">Could not reach the server: {me.error.message}</p>;
if (!me.data) return null;
const logout = async () => {
await fetch("/~/auth/logout", { method: "POST", credentials: "same-origin" });
location.href = "/~/";
};
const pageMatch = path.match(/^\/~\/pages\/(\d+)$/);
const screen = pageMatch ? (
<PageScreen id={Number(pageMatch[1])} me={me.data} />
) : path === "/~/tokens" ? (
<TokensScreen />
) : (
<Dashboard me={me.data} />
);
return (
<div className="mx-auto max-w-5xl px-4 py-8 sm:px-8">
<header className="mb-8 flex flex-wrap items-center justify-between gap-4">
<Link to="/~/" className="flex items-center gap-3">
<img src="/~/short.svg" alt="" className="h-8 w-8" />
<h1>short</h1>
</Link>
<nav className="flex items-center gap-4 text-sm">
<Link to="/~/tokens" className="hover:underline">
API tokens
</Link>
<span className="text-gray-500">
{me.data.username}
{me.data.isAdmin && " (admin)"}
</span>
<button className="btn btn-secondary py-1" onClick={logout}>
Sign out
</button>
</nav>
</header>
{screen}
</div>
);
}
createRoot(document.getElementById("root")!).render(
<StrictMode>
<ToastProvider>
<App />
</ToastProvider>
</StrictMode>,
);
Binary file not shown.

After

Width:  |  Height:  |  Size: 7.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

+14
View File
@@ -0,0 +1,14 @@
{
"name": "traberph/short",
"short_name": "short",
"description": "A URL shortener",
"start_url": "/~/",
"scope": "/~/",
"display": "standalone",
"theme_color": "#111827",
"background_color": "#111827",
"icons": [
{ "src": "/~/icon-192x192.png", "sizes": "192x192", "type": "image/png" },
{ "src": "/~/icon-512x512.png", "sizes": "512x512", "type": "image/png" }
]
}
+11
View File
@@ -0,0 +1,11 @@
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" >
<defs>
<linearGradient id="grad1" x1="0%" y1="0%" x2="100%" y2="0%">
<stop offset="0%" style="stop-color:rgb(200,0,55);stop-opacity:1" />
<stop offset="100%" style="stop-color:rgb(55,0,200);stop-opacity:1" />
</linearGradient>
</defs>
<rect x="0" y="0" width="24" height="24" fill="url(#grad1)" stroke-width="0" />
<path transform="scale(0.8) translate(2.4, 2.4) rotate(45, 12,12 ) " stroke-linecap="round" stroke-linejoin="round" stroke="#FFFFFF" d="M13.19 8.688a4.5 4.5 0 0 1 1.242 7.244l-4.5 4.5a4.5 4.5 0 0 1-6.364-6.364l1.757-1.757m13.35-.622 1.757-1.757a4.5 4.5 0 0 0-6.364-6.364l-4.5 4.5a4.5 4.5 0 0 0 1.242 7.244" />
</svg>

After

Width:  |  Height:  |  Size: 773 B

+29
View File
@@ -0,0 +1,29 @@
import { useSyncExternalStore, type MouseEvent } from "react";
// A tiny history-based router; the app only has a handful of screens under /~/.
const listeners = new Set<() => void>();
export function navigate(to: string) {
history.pushState(null, "", to);
listeners.forEach((l) => l());
}
window.addEventListener("popstate", () => listeners.forEach((l) => l()));
export function usePath(): string {
return useSyncExternalStore(
(listener) => {
listeners.add(listener);
return () => listeners.delete(listener);
},
() => location.pathname,
);
}
export function linkHandler(to: string) {
return (e: MouseEvent) => {
if (e.metaKey || e.ctrlKey || e.shiftKey || e.button !== 0) return;
e.preventDefault();
navigate(to);
};
}
+151
View File
@@ -0,0 +1,151 @@
import { useState, type FormEvent } from "react";
import type { Conflict, Me, PageKind, PageSummary } from "../../shared/api-types.js";
import { api, useApi } from "../api.js";
import { Field, Link, publicUrl, useAction, useToast } from "../components/ui.js";
import { navigate } from "../router.js";
function CreateForm({ me, onCreated }: { me: Me; onCreated: () => void }) {
const users = useApi<string[]>(me.isAdmin ? "/users" : null);
const { busy, run } = useAction();
const [kind, setKind] = useState<PageKind>("redirect");
const [namespace, setNamespace] = useState(me.username);
const [code, setCode] = useState("");
const [value, setValue] = useState("");
const submit = (e: FormEvent) => {
e.preventDefault();
void run(async () => {
const body = {
kind,
namespace,
...(code.trim() && { code: code.trim() }),
...(kind === "redirect" ? { dest: value.trim() } : { title: value.trim() }),
};
const page = await api<PageSummary>("POST", "/pages", body);
setCode("");
setValue("");
if (page.kind === "linkpage") navigate(`/~/pages/${page.id}`);
else {
await navigator.clipboard?.writeText(publicUrl(page.path)).catch(() => {});
onCreated();
}
}, kind === "redirect" ? "Link created and copied" : "Link page created");
};
const prefix = namespace ? `/${namespace}/` : "/";
return (
<form onSubmit={submit} className="card mb-10">
<div className="mb-4 flex gap-2">
{(["redirect", "linkpage"] as const).map((k) => (
<button
key={k}
type="button"
className={`btn py-1 ${kind === k ? "" : "btn-secondary"}`}
onClick={() => setKind(k)}
>
{k === "redirect" ? "Short link" : "Link page"}
</button>
))}
</div>
<div className="grid gap-x-4 sm:grid-cols-[auto_1fr]">
{me.isAdmin && (
<Field label="Namespace">
<select value={namespace} onChange={(e) => setNamespace(e.target.value)}>
<option value="">/ (root)</option>
{(users.data ?? [me.username]).map((u) => (
<option key={u} value={u}>
/{u}/
</option>
))}
</select>
</Field>
)}
<Field label="Shortcode" hint={`${prefix}${code || "…"} — leave empty for a random code`}>
<input value={code} onChange={(e) => setCode(e.target.value)} placeholder="random" pattern="[A-Za-z0-9][A-Za-z0-9_\-]{0,63}" />
</Field>
</div>
<Field label={kind === "redirect" ? "Destination URL" : "Title"}>
<input
required
type={kind === "redirect" ? "url" : "text"}
value={value}
onChange={(e) => setValue(e.target.value)}
placeholder={kind === "redirect" ? "https://…" : "My links"}
/>
</Field>
<button className="btn mt-2" disabled={busy}>
Create
</button>
</form>
);
}
function PageRow({ page }: { page: PageSummary }) {
const toast = useToast();
const copy = async () => {
await navigator.clipboard.writeText(publicUrl(page.path));
toast("Copied");
};
return (
<div className="flex items-center gap-3 rounded px-3 py-3 odd:bg-gray-800/60">
<Link to={`/~/pages/${page.id}`} className="min-w-0 flex-1">
<div className="truncate font-semibold text-white">
{page.path}
{page.pinned && <span className="ml-2 rounded bg-yellow-700 px-1.5 text-xs">pinned to /</span>}
</div>
<div className="truncate text-sm text-gray-400">{page.kind === "redirect" ? page.dest : page.title}</div>
</Link>
<span className="text-sm whitespace-nowrap text-gray-400">{page.totalClicks} clicks</span>
<button className="btn btn-secondary px-2 py-1 text-sm" onClick={copy} title="Copy URL">
Copy
</button>
</div>
);
}
export function Dashboard({ me }: { me: Me }) {
const pages = useApi<PageSummary[]>("/pages");
const conflicts = useApi<Conflict[]>(me.isAdmin ? "/conflicts" : null);
const [filter, setFilter] = useState("");
const visible = (pages.data ?? []).filter(
(p) => !filter || p.path.toLowerCase().includes(filter.toLowerCase()) || (p.dest ?? p.title ?? "").toLowerCase().includes(filter.toLowerCase()),
);
const links = visible.filter((p) => p.kind === "redirect");
const linkPages = visible.filter((p) => p.kind === "linkpage");
return (
<>
{!!conflicts.data?.length && (
<div className="mb-6 rounded border border-yellow-700 bg-yellow-900/30 p-4 text-sm">
<strong>Username conflicts:</strong>{" "}
{conflicts.data.map((c, i) => (
<span key={c.pageId}>
{i > 0 && ", "}
<Link to={`/~/pages/${c.pageId}`} className="underline">
/{c.username}
</Link>
</span>
))}{" "}
{conflicts.data.length === 1 ? "is" : "are"} both a root link and a username. Consider renaming the root link.
</div>
)}
<h2 className="mb-3">Create</h2>
<CreateForm me={me} onCreated={() => void pages.reload()} />
<div className="mb-3 flex items-center justify-between gap-4">
<h2>Pages</h2>
<input className="max-w-xs" placeholder="Filter…" value={filter} onChange={(e) => setFilter(e.target.value)} />
</div>
{pages.error && <p className="text-red-400">{pages.error.message}</p>}
<h3 className="mt-6 mb-2 text-sm font-bold text-gray-400 uppercase">Link pages</h3>
{linkPages.length ? linkPages.map((p) => <PageRow key={p.id} page={p} />) : <p className="text-gray-500">None yet.</p>}
<h3 className="mt-6 mb-2 text-sm font-bold text-gray-400 uppercase">Short links</h3>
{links.length ? links.map((p) => <PageRow key={p.id} page={p} />) : <p className="text-gray-500">None yet.</p>}
</>
);
}
+188
View File
@@ -0,0 +1,188 @@
import { useEffect, useState, type FormEvent } from "react";
import type { Me, PageDetail } from "../../shared/api-types.js";
import type { Theme } from "../../shared/validation.js";
import { api, useApi } from "../api.js";
import { BlockEditor } from "../components/BlockEditor.js";
import { QrPanel } from "../components/QrPanel.js";
import { StatsPanel } from "../components/StatsPanel.js";
import { Field, Link, publicUrl, useAction, useToast } from "../components/ui.js";
import { navigate } from "../router.js";
const THEME_FIELDS: [keyof Theme, string][] = [
["background", "Background"],
["text", "Text"],
["button", "Button"],
["buttonText", "Button text"],
];
function RedirectSettings({ page, onSaved }: { page: PageDetail; onSaved: (p: PageDetail) => void }) {
const [dest, setDest] = useState(page.dest ?? "");
const { busy, run } = useAction();
const submit = (e: FormEvent) => {
e.preventDefault();
void run(async () => onSaved(await api<PageDetail>("PATCH", `/pages/${page.id}`, { dest })), "Saved");
};
return (
<form className="card" onSubmit={submit}>
<Field label="Destination URL">
<input type="url" required value={dest} onChange={(e) => setDest(e.target.value)} />
</Field>
<button className="btn" disabled={busy || dest === page.dest}>
Save
</button>
</form>
);
}
function LinkPageSettings({ page, onSaved }: { page: PageDetail; onSaved: (p: PageDetail) => void }) {
const [title, setTitle] = useState(page.title ?? "");
const [theme, setTheme] = useState(page.theme);
const { busy, run } = useAction();
const submit = (e: FormEvent) => {
e.preventDefault();
void run(async () => onSaved(await api<PageDetail>("PATCH", `/pages/${page.id}`, { title, theme })), "Saved");
};
const upload = (file: File | undefined) => {
if (!file) return;
const form = new FormData();
form.append("file", file);
void run(async () => {
const { avatarUrl } = await api<{ avatarUrl: string }>("PUT", `/pages/${page.id}/avatar`, form);
onSaved({ ...page, avatarUrl });
}, "Avatar updated");
};
const removeAvatar = () =>
run(async () => {
await api("DELETE", `/pages/${page.id}/avatar`);
onSaved({ ...page, avatarUrl: null });
});
return (
<form className="card" onSubmit={submit}>
<div className="mb-4 flex items-center gap-4">
{page.avatarUrl ? (
<img src={page.avatarUrl} alt="" className="h-16 w-16 rounded-full object-cover" />
) : (
<div className="h-16 w-16 rounded-full bg-gray-700" />
)}
<label className="btn btn-secondary mb-0 cursor-pointer py-1 text-base font-medium tracking-normal normal-case">
Upload avatar
<input type="file" accept="image/png,image/jpeg,image/webp" className="hidden" onChange={(e) => upload(e.target.files?.[0])} />
</label>
{page.avatarUrl && (
<button type="button" className="btn btn-secondary py-1" onClick={removeAvatar}>
Remove
</button>
)}
</div>
<Field label="Title">
<input required value={title} onChange={(e) => setTitle(e.target.value)} />
</Field>
<div className="mb-4 flex flex-wrap gap-6">
{THEME_FIELDS.map(([key, label]) => (
<label key={key} className="flex items-center gap-2 normal-case">
<input type="color" value={theme[key]} onChange={(e) => setTheme({ ...theme, [key]: e.target.value })} />
{label}
</label>
))}
</div>
<button className="btn" disabled={busy}>
Save
</button>
</form>
);
}
export function PageScreen({ id, me }: { id: number; me: Me }) {
const page = useApi<PageDetail>(`/pages/${id}`);
const toast = useToast();
const { busy, run } = useAction();
const [previewKey, setPreviewKey] = useState(0);
// Reload the preview whenever the page changes.
useEffect(() => setPreviewKey((k) => k + 1), [page.data]);
if (page.error) {
return (
<p>
{page.error.status === 404 ? "Page not found." : page.error.message}{" "}
<Link to="/~/" className="underline">
Back
</Link>
</p>
);
}
const p = page.data;
if (!p) return null;
const url = publicUrl(p.path);
const remove = () => {
if (!confirm(`Delete ${p.path}? Its stats and any buttons pointing to it are removed too.`)) return;
void run(async () => {
await api("DELETE", `/pages/${p.id}`);
navigate("/~/");
}, "Deleted");
};
const togglePin = () =>
run(async () => {
if (p.pinned) await api("DELETE", "/pin");
else await api("PUT", "/pin", { pageId: p.id });
await page.reload();
}, p.pinned ? "Unpinned" : "Pinned to /");
return (
<div className="flex flex-col gap-6">
<div className="flex flex-wrap items-center justify-between gap-4">
<div className="min-w-0">
<Link to="/~/" className="text-sm text-gray-400 hover:underline">
← All pages
</Link>
<h1 className="truncate">{p.path}</h1>
<p className="text-sm text-gray-400">{p.kind === "redirect" ? "Short link" : "Link page"}</p>
</div>
<div className="flex flex-wrap gap-2">
<a className="btn btn-secondary" href={p.path} target="_blank" rel="noreferrer">
Open
</a>
<button className="btn btn-secondary" onClick={() => navigator.clipboard.writeText(url).then(() => toast("Copied"))}>
Copy URL
</button>
{me.isAdmin && (
<button className="btn btn-secondary" onClick={togglePin} disabled={busy}>
{p.pinned ? "Unpin from /" : "Pin to /"}
</button>
)}
<button className="btn btn-danger" onClick={remove} disabled={busy}>
Delete
</button>
</div>
</div>
{p.kind === "redirect" ? (
<RedirectSettings page={p} onSaved={page.set} />
) : (
<div className="grid gap-6 lg:grid-cols-[1fr_320px]">
<div className="flex flex-col gap-6">
<LinkPageSettings key={p.id} page={p} onSaved={page.set} />
<BlockEditor
pageId={p.id}
namespace={p.namespace}
isAdmin={me.isAdmin}
blocks={p.blocks}
onChange={(blocks) => page.set({ ...p, blocks })}
/>
</div>
<div className="hidden lg:block">
<h2 className="mb-2">Preview</h2>
<iframe key={previewKey} src={`${p.path}?preview`} title="Preview" className="h-[640px] w-full rounded-lg border border-gray-700" />
</div>
</div>
)}
<QrPanel url={url} name={p.code} />
<StatsPanel pageId={p.id} />
</div>
);
}
+91
View File
@@ -0,0 +1,91 @@
import { useState, type FormEvent } from "react";
import type { ApiToken, CreatedToken } from "../../shared/api-types.js";
import { api, useApi } from "../api.js";
import { Field, useAction, useToast } from "../components/ui.js";
export function TokensScreen() {
const tokens = useApi<ApiToken[]>("/tokens");
const { busy, run } = useAction();
const toast = useToast();
const [name, setName] = useState("");
const [created, setCreated] = useState<CreatedToken | null>(null);
const create = (e: FormEvent) => {
e.preventDefault();
void run(async () => {
setCreated(await api<CreatedToken>("POST", "/tokens", { name }));
setName("");
await tokens.reload();
});
};
const revoke = (t: ApiToken) => {
if (!confirm(`Revoke "${t.name}"? Scripts using it stop working.`)) return;
void run(async () => {
await api("DELETE", `/tokens/${t.id}`);
await tokens.reload();
}, "Token revoked");
};
const example = `curl -X POST ${location.origin}/~/api/pages \\
-H "Authorization: Bearer <token>" \\
-H "Content-Type: application/json" \\
-d '{"kind":"redirect","dest":"https://example.com"}'`;
return (
<div className="flex flex-col gap-6">
<h1>API tokens</h1>
<p className="text-sm text-gray-400">Tokens act with your permissions. Use them for scripts or iOS Shortcuts.</p>
<form className="card" onSubmit={create}>
<Field label="Name">
<input required value={name} onChange={(e) => setName(e.target.value)} placeholder="e.g. iPhone Shortcut" />
</Field>
<button className="btn" disabled={busy}>
Create token
</button>
{created && (
<div className="mt-4 rounded border border-green-700 bg-green-900/30 p-3">
<p className="mb-2 text-sm">Copy this token now. It won't be shown again.</p>
<div className="flex gap-2">
<code className="flex-1 overflow-x-auto rounded bg-gray-900 px-2 py-1">{created.token}</code>
<button
type="button"
className="btn btn-secondary py-1"
onClick={() => navigator.clipboard.writeText(created.token).then(() => toast("Copied"))}
>
Copy
</button>
</div>
</div>
)}
</form>
<section className="card">
<h2 className="mb-3">Your tokens</h2>
{tokens.data?.length ? (
tokens.data.map((t) => (
<div key={t.id} className="flex items-center justify-between gap-3 border-b border-gray-700 py-2 last:border-0">
<div>
<div className="font-semibold text-white">{t.name}</div>
<div className="text-xs text-gray-400">
created {new Date(t.createdAt).toLocaleDateString()} · last used{" "}
{t.lastUsedAt ? new Date(t.lastUsedAt).toLocaleString() : "never"}
</div>
</div>
<button className="btn btn-danger py-1" onClick={() => revoke(t)} disabled={busy}>
Revoke
</button>
</div>
))
) : (
<p className="text-gray-500">No tokens yet.</p>
)}
</section>
<section className="card">
<h2 className="mb-3">Example</h2>
<pre className="overflow-x-auto rounded bg-gray-900 p-3 text-sm">{example}</pre>
</section>
</div>
);
}
+34
View File
@@ -0,0 +1,34 @@
@import "tailwindcss";
@layer base {
body {
@apply bg-gray-900 text-gray-300 antialiased;
}
h1 {
@apply text-3xl font-bold text-white;
}
h2 {
@apply text-xl font-bold text-white;
}
label {
@apply mb-1 block text-xs font-bold tracking-wide uppercase;
}
input:not([type="color"]):not([type="file"]),
select,
textarea {
@apply w-full rounded border border-gray-800 bg-gray-800 px-3 py-2 text-gray-200 focus:bg-gray-700 focus:outline-none;
}
}
@utility btn {
@apply inline-flex cursor-pointer items-center justify-center gap-2 rounded bg-green-600 px-4 py-2 font-medium text-white hover:bg-green-700 disabled:cursor-default disabled:opacity-50;
}
@utility btn-secondary {
@apply bg-gray-700 hover:bg-gray-600;
}
@utility btn-danger {
@apply bg-red-800 hover:bg-red-700;
}
@utility card {
@apply rounded-lg bg-gray-800/60 p-4;
}