Merge pull request #6 from traberph/v2

v2: rewrite
This commit is contained in:
traberph
2026-10-14 14:35:22 +02:00
committed by GitHub
120 changed files with 8543 additions and 9862 deletions
Binary file not shown.

Before

Width:  |  Height:  |  Size: 153 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 178 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 88 KiB

BIN
View File
Binary file not shown.

Before

Width:  |  Height:  |  Size: 23 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 98 KiB

+4 -5
View File
@@ -1,8 +1,7 @@
Dockerfile
.dockerignore
node_modules
npm-debug.log
README.md
.next
dist
data
.env
.git
.assets
test
+23 -10
View File
@@ -1,14 +1,27 @@
# Authentication *required*
AUTH_AUTHENTIK_SECRET=
AUTH_SECRET=
AUTH_TRUST_HOST=https://traberph.de
NEXTAUTH_URL=https://traberph.de
# Public base URL of this instance *required*
BASE_URL=https://short.example.com
# Database *required*
DATABASE_URL="postgresql://postgres:postgres@localhost:5432/postgres"
# OIDC (Authentik) *required*
# Issuer is the provider's "OpenID Configuration Issuer", e.g. https://auth.example.com/application/o/short/
OIDC_ISSUER=
OIDC_CLIENT_ID=
OIDC_CLIENT_SECRET=
# Members of this Authentik group are admins
ADMIN_GROUP=short-admins
# Attribution *optional*
#DISABLE_ATTRIBUTION=true
# Random secret for signing cookies, e.g. `openssl rand -base64 32` *required*
SESSION_SECRET=
# Logo.dev *optional*
# Where the SQLite database and uploaded avatars are stored
DATA_DIR=./data
# Timezone used for "today" and the daily stats
TIMEZONE=Europe/Berlin
# Set when running behind a reverse proxy, so X-Forwarded-For is used for the visitor IP
TRUST_PROXY=true
# Optional
#LOGO_DEV_TOKEN=
#DISABLE_ATTRIBUTION=true
#PORT=3000
-3
View File
@@ -1,3 +0,0 @@
{
"extends": "next/core-web-vitals"
}
+19 -1
View File
@@ -6,6 +6,7 @@ on:
- main
tags:
- 'v*'
pull_request:
env:
REGISTRY: ghcr.io
@@ -14,7 +15,23 @@ env:
DOCKER_HUB_IMAGE_NAME: traberph/short
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: pnpm/action-setup@v4
- uses: actions/setup-node@v4
with:
node-version: 24
cache: pnpm
- run: pnpm install --frozen-lockfile
- run: pnpm typecheck
- run: pnpm test
- run: pnpm build
build-and-push:
needs: test
if: github.event_name == 'push'
runs-on: ubuntu-latest
permissions:
contents: read
@@ -49,7 +66,8 @@ jobs:
${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}
${{ env.DOCKER_HUB_REGISTRY }}/${{ env.DOCKER_HUB_IMAGE_NAME }}
tags: |
type=ref,event=tag
type=semver,pattern={{version}}
type=semver,pattern={{major}}
type=raw,value=latest,enable=${{ startsWith(github.ref, 'refs/heads/main') }}
- name: Build and push Docker images
+5 -38
View File
@@ -1,39 +1,6 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/node_modules
/.pnp
.pnp.js
.yarn/install-state.gz
# testing
/coverage
# next.js
/.next/
/out/
# production
/build
# misc
.DS_Store
*.pem
# debug
npm-debug.log*
yarn-debug.log*
yarn-error.log*
# local env files
.env*.local
# vercel
.vercel
# typescript
*.tsbuildinfo
next-env.d.ts
node_modules
dist
data
.env
.vol_db
*.tsbuildinfo
.DS_Store
+22 -63
View File
@@ -1,70 +1,29 @@
FROM node:18-alpine AS base
# Install dependencies only when needed
FROM base AS deps
# Check https://github.com/nodejs/docker-node/tree/b4117f9333da4138b03a546ec926ef50a31506c3#nodealpine to understand why libc6-compat might be needed.
RUN apk add --no-cache libc6-compat
FROM node:24-slim AS base
WORKDIR /app
RUN corepack enable
COPY package.json pnpm-lock.yaml pnpm-workspace.yaml ./
# Install dependencies based on the preferred package manager
COPY package.json yarn.lock* package-lock.json* pnpm-lock.yaml* ./
RUN \
if [ -f yarn.lock ]; then yarn --frozen-lockfile; \
elif [ -f package-lock.json ]; then npm ci; \
elif [ -f pnpm-lock.yaml ]; then corepack enable pnpm && pnpm i --frozen-lockfile; \
else echo "Lockfile not found." && exit 1; \
fi
# Rebuild the source code only when needed
FROM base AS builder
WORKDIR /app
COPY --from=deps /app/node_modules ./node_modules
FROM base AS build
RUN pnpm install --frozen-lockfile
COPY . .
RUN pnpm build
# Next.js collects completely anonymous telemetry data about general usage.
# Learn more here: https://nextjs.org/telemetry
# Uncomment the following line in case you want to disable telemetry during the build.
# ENV NEXT_TELEMETRY_DISABLED=1
FROM base AS prod-deps
RUN pnpm install --frozen-lockfile --prod
RUN npx prisma generate
RUN \
if [ -f yarn.lock ]; then yarn run build; \
elif [ -f package-lock.json ]; then npm run build; \
elif [ -f pnpm-lock.yaml ]; then corepack enable pnpm && pnpm run build; \
else echo "Lockfile not found." && exit 1; \
fi
# Production image, copy all the files and run next
FROM base AS runner
FROM node:24-slim AS runner
WORKDIR /app
ENV NODE_ENV=production
# Uncomment the following line in case you want to disable telemetry during runtime.
# ENV NEXT_TELEMETRY_DISABLED=1
RUN addgroup --system --gid 1001 nodejs
RUN adduser --system --uid 1001 nextjs
COPY --from=builder /app/public ./public
# Set the correct permission for prerender cache
RUN mkdir .next
RUN chown nextjs:nodejs .next
# Automatically leverage output traces to reduce image size
# https://nextjs.org/docs/advanced-features/output-file-tracing
COPY --from=builder --chown=nextjs:nodejs /app/.next/standalone ./
COPY --from=builder --chown=nextjs:nodejs /app/.next/static ./.next/static
USER nextjs
ENV NODE_ENV=production \
PORT=3000 \
DATA_DIR=/data
COPY --from=prod-deps /app/node_modules ./node_modules
COPY --from=build /app/dist ./dist
COPY drizzle ./drizzle
COPY package.json ./
RUN mkdir -p /data && chown node:node /data
USER node
VOLUME /data
EXPOSE 3000
ENV PORT=3000
# server.js is created by next build from the standalone output
# https://nextjs.org/docs/pages/api-reference/next-config-js/output
ENV HOSTNAME="0.0.0.0"
CMD ["node", "server.js"]
HEALTHCHECK --interval=30s --timeout=5s --start-period=10s \
CMD node -e "fetch('http://localhost:'+process.env.PORT+'/~/health').then(r=>process.exit(r.ok?0:1),()=>process.exit(1))"
CMD ["node", "dist/server/index.js"]
+73 -33
View File
@@ -1,55 +1,95 @@
# Short
# short
This tool is intended to provide simple URL shortening and link aggregation functionality.
Users should be able to create shortened links for example to generate smaller QR codes with the built-in QR code generator.
A small self-hosted URL shortener and link-page tool for a handful of people, with login through Authentik (OIDC).
The admin panel is a PWA for easy access and management of the links even on mobile devices.
- **Short links**: `/<code>` for admins, `/<username>/<code>` for everyone else. Codes can be custom or random, and destinations can be edited later.
- **Link pages**: a "link in bio" page with avatar, link buttons, Markdown text blocks and custom colours. Blocks are reordered by drag and drop.
- **QR codes**: choose the error correction level and colours, then download as PNG or SVG.
- **Privacy-friendly stats**: clicks per day, daily unique visitors, last visit. No raw IPs are stored, the visitor hash uses a salt that rotates daily, and individual clicks are deleted after 90 days.
- **API with personal access tokens**: for scripts and iOS Shortcuts.
- **Mobile-friendly admin UI**, installable as a PWA. Everything runs as a single container with SQLite.
It is powered by nextjs and postgres.
Authentication is handled via OAuth2.
See [REQUIREMENTS.md](REQUIREMENTS.md) for the full feature list.
# Configuration
## URLs
To configure short environment variables are used.
Modify the `.env.template` to your needs.
Postgres and Auth variables are mandatory for short to work.
| Path | What |
|---|---|
| `/` | Redirects to the pinned page, if an admin pinned one |
| `/<code>` | Root links and pages (admins) |
| `/<username>/<code>` | User links and pages |
| `/~/` | Admin UI |
| `/~/api/…` | JSON API |
| `/~/health` | Health check |
### logo.dev integration
Logo.dev can be used to automatically fetch logos for the urls on the aggregation pages.
To use Logo.dev an Token is required which can be requested via their webpage for free.
If Logo.dev is enabled the attribution is automatically added to the footer.
If `LOGO_DEV_TOKEN`is not set the first letter of the hostname is used as improvised logo.
## Roles
### traberph/short attribution
As default in the footer is an attribution link to this GitHub repo.
This can be disabled using the `DISABLE_ATTRIBUTION=true`.
- **Users** can create and manage links and link pages under `/<their username>/`. Link pages can only use their own links.
- **Admins** are members of the Authentik group `ADMIN_GROUP`. They can additionally create root links, pin a page to `/`, and view, edit and delete everything.
The username is Authentik's `preferred_username`, fixed at the first login. Usernames have to be URL-safe (`A-Z a-z 0-9 . _ -`). Root codes that match a username are blocked, and the dashboard warns admins about conflicts.
# Example Page
- optimized for mobile view
- simple and clean design
## Setup
![example page](.assets/screenshot_home.png)
### 1. Authentik
# Easy to use Admin Interface
Create an **OAuth2/OpenID provider** and an application for it:
## Overview Page
- Client type: *Confidential*
- Redirect URI: `https://<your domain>/~/auth/callback`
- Scopes: `openid`, `profile`, `email` (the default `profile` mapping includes the `groups` claim)
- Create a group (e.g. `short-admins`) for admins.
- Use the application's policy bindings to control who can log in at all.
- get an overview of all links and their views
### 2. Configuration
![admin landing page](.assets/admin01.png)
Copy `.env.template` to `.env` and fill it in:
## Redirect Pages
| Variable | Required | Description |
|---|---|---|
| `BASE_URL` | yes | Public URL, e.g. `https://short.example.com` |
| `OIDC_ISSUER` | yes | The provider's issuer URL, e.g. `https://auth.example.com/application/o/short/` |
| `OIDC_CLIENT_ID` / `OIDC_CLIENT_SECRET` | yes | From the Authentik provider |
| `SESSION_SECRET` | yes | At least 32 random characters: `openssl rand -base64 32` |
| `ADMIN_GROUP` | | Authentik group for admins, default `short-admins` |
| `TIMEZONE` | | Timezone for "today" and the daily stats, default `UTC` |
| `TRUST_PROXY` | | `true` behind a reverse proxy, so `X-Forwarded-For` is used for the visitor IP |
| `DATA_DIR` | | Database and uploads, default `./data` (`/data` in Docker) |
| `LOGO_DEV_TOKEN` | | Shows website logos on link page buttons via [logo.dev](https://logo.dev) (adds an attribution) |
| `DISABLE_ATTRIBUTION` | | `true` hides the "powered by" footer |
- a simple redirect to a target url
### 3. Run
![custom pages](.assets/admin03.png)
```sh
mkdir -p data && sudo chown 1000:1000 data # the container runs as uid 1000
docker compose up -d
```
# Custom Pages
Put it behind a reverse proxy with TLS. Back up `data/`: it holds the SQLite database (`short.db`) and the uploaded avatars. Database migrations run automatically on startup.
- an aggregation of multiple redirect pages
- (future work - text blocks; image blocks)
## API
![redirect pages](.assets/admin02.png)
The admin UI uses the same JSON API. Create a token under **API tokens**; it has the same permissions as your account.
```sh
curl -X POST https://short.example.com/~/api/pages \
-H "Authorization: Bearer short_…" \
-H "Content-Type: application/json" \
-d '{"kind":"redirect","dest":"https://example.com","code":"optional"}'
```
Main endpoints: `GET/POST /pages`, `GET/PATCH/DELETE /pages/:id`, `GET/DELETE /pages/:id/stats?days=7|30|90`, `POST /pages/:id/blocks`, `PUT /pages/:id/blocks/order`, `PATCH/DELETE /blocks/:id`, `PUT /pages/:id/avatar`, `GET/POST/DELETE /tokens`.
Admin only: `PUT/DELETE /pin`, `GET /users`, `GET /conflicts`.
## Development
```sh
pnpm install
cp .env.template .env # BASE_URL=http://localhost:5173 for dev
pnpm dev # API on :3000, admin UI with hot reload on http://localhost:5173/~/
pnpm test # vitest
pnpm typecheck
pnpm db:generate # after changing src/server/db/schema.ts
```
Stack: Node 24, [Hono](https://hono.dev), SQLite with [Drizzle](https://orm.drizzle.team), [openid-client](https://github.com/panva/openid-client), React + Vite + Tailwind for the admin UI.
+54
View File
@@ -0,0 +1,54 @@
# short v2 — Requirements
Scope: self-hosted URL shortener and link-page tool for a small audience (~10 users, a handful of clicks),
authenticated against an existing Authentik instance.
## Users & roles
- **R1** Login via OIDC (Authentik). Users are created automatically on first login.
- **R2** Admin = member of the Authentik group named in `ADMIN_GROUP`. Everyone else who can log in is a user.
The admin flag is refreshed on every login.
- **R3** Users create links and link pages only under `/<username>/<code>`. The bare `/<username>` stays unused.
The username is the Authentik `preferred_username`. Usernames cannot change and are moderated by admins.
Logins with usernames that are not URL-safe (`A-Z a-z 0-9 . _ -`) are rejected.
- **R4** Admins can also create links and pages at root level (`/<code>`) and can view, edit and delete
everything, including stats.
- **R5** Root codes can't match an existing username. If a new user's name already exists as a root code,
admins see a warning.
- **R6** Every route and endpoint is protected by default. Only redirects, public link pages and login are open.
## Links
- **R7** The shortcode is either typed in or, if left empty, randomly generated (5 characters).
- **R8** Destinations must be `http(s)://`. Reserved codes are blocked.
- **R9** Destinations can be edited. Links use 302 redirects.
- **R10** Deleting a link removes its stats and its buttons on link pages, in one transaction.
- **R11** An admin can pin the root `/` to any page.
## Link pages
- **R12** Title, avatar, ordered blocks (drag-and-drop reordering) and a theme (background and button colours).
- **R13** Block types: link button (points at a short link, so clicks are tracked) and text.
- **R14** Text blocks support basic Markdown (bold, italic, links, lists, headings). Raw HTML is stripped.
- **R15** Optional logo.dev favicons with letter placeholders as fallback. Optional attribution footer.
- Users' link pages can only use links from their own namespace. Admins can use any link.
## QR codes
- **R16** Choice of error correction level and colours. Download as PNG or SVG.
## Stats
- **R17** Total clicks, clicks today, unique visitors, last visit, and a clicks-per-day chart (7, 30 or 90 days).
- **R18** No raw IPs are stored. The visitor hash is a salted hash of IP and user agent, and the salt rotates daily,
so unique visitors are counted per day.
- **R19** Detailed clicks are deleted after 90 days and only daily totals are kept. Stats can be reset per link.
- **R20** Recording a click never slows down the redirect.
## API
- **R21** A JSON API that the admin UI itself uses.
- **R22** Personal access tokens per user (create and revoke in the UI), with the same permissions as that user.
## Operations
- **R23** SQLite in a volume, with migrations that run on startup. Starting fresh, no data migration from v1.
- **R24** A single Docker image, built by GitHub Actions and pushed to GHCR and Docker Hub.
Configured through env vars, with a health check endpoint.
- **R25** The admin UI works well on mobile and can be installed as a PWA.
## Non-goals (v1)
Image blocks, referrer/device/country stats, link expiry, custom domains, public sign-up.
+9 -14
View File
@@ -1,18 +1,13 @@
services:
db:
image: postgres:16
environment:
POSTGRES_USER: postgres
POSTGRES_PASSWORD: postgres
POSTGRES_DB: postgres
short:
image: ghcr.io/traberph/short:latest
# build: .
restart: unless-stopped
ports:
- "5432:5432"
volumes:
- ./.vol_db:/var/lib/postgresql/data
web:
build: .
ports:
- 3000:3000
- "3000:3000"
env_file:
- .env
environment:
DATA_DIR: /data
volumes:
- ./data:/data
+7
View File
@@ -0,0 +1,7 @@
import { defineConfig } from "drizzle-kit";
export default defineConfig({
dialect: "sqlite",
schema: "./src/server/db/schema.ts",
out: "./drizzle",
});
+84
View File
@@ -0,0 +1,84 @@
CREATE TABLE `api_tokens` (
`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
`user_id` integer NOT NULL,
`name` text NOT NULL,
`token_hash` text NOT NULL,
`created_at` integer DEFAULT (unixepoch()) NOT NULL,
`last_used_at` integer,
FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE cascade
);
--> statement-breakpoint
CREATE UNIQUE INDEX `api_tokens_token_hash_unique` ON `api_tokens` (`token_hash`);--> statement-breakpoint
CREATE TABLE `blocks` (
`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
`page_id` integer NOT NULL,
`position` integer NOT NULL,
`kind` text NOT NULL,
`label` text,
`markdown` text,
`target_id` integer,
FOREIGN KEY (`page_id`) REFERENCES `pages`(`id`) ON UPDATE no action ON DELETE cascade,
FOREIGN KEY (`target_id`) REFERENCES `pages`(`id`) ON UPDATE no action ON DELETE cascade
);
--> statement-breakpoint
CREATE INDEX `blocks_page` ON `blocks` (`page_id`,`position`);--> statement-breakpoint
CREATE INDEX `blocks_target` ON `blocks` (`target_id`);--> statement-breakpoint
CREATE TABLE `clicks` (
`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
`page_id` integer NOT NULL,
`at` integer NOT NULL,
`day` text NOT NULL,
`visitor` text NOT NULL,
FOREIGN KEY (`page_id`) REFERENCES `pages`(`id`) ON UPDATE no action ON DELETE cascade
);
--> statement-breakpoint
CREATE INDEX `clicks_page_day` ON `clicks` (`page_id`,`day`,`visitor`);--> statement-breakpoint
CREATE INDEX `clicks_at` ON `clicks` (`at`);--> statement-breakpoint
CREATE TABLE `daily_stats` (
`page_id` integer NOT NULL,
`day` text NOT NULL,
`clicks` integer DEFAULT 0 NOT NULL,
`uniques` integer DEFAULT 0 NOT NULL,
`last_at` integer NOT NULL,
PRIMARY KEY(`page_id`, `day`),
FOREIGN KEY (`page_id`) REFERENCES `pages`(`id`) ON UPDATE no action ON DELETE cascade
);
--> statement-breakpoint
CREATE TABLE `pages` (
`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
`namespace` text NOT NULL,
`code` text NOT NULL,
`kind` text NOT NULL,
`dest` text,
`title` text,
`avatar` text,
`theme` text,
`created_by` integer,
`created_at` integer DEFAULT (unixepoch()) NOT NULL,
`updated_at` integer DEFAULT (unixepoch()) NOT NULL,
FOREIGN KEY (`created_by`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE set null
);
--> statement-breakpoint
CREATE UNIQUE INDEX `pages_namespace_code` ON `pages` (`namespace`,`code`);--> statement-breakpoint
CREATE TABLE `sessions` (
`id` text PRIMARY KEY NOT NULL,
`user_id` integer NOT NULL,
`expires_at` integer NOT NULL,
FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE cascade
);
--> statement-breakpoint
CREATE TABLE `settings` (
`key` text PRIMARY KEY NOT NULL,
`value` text NOT NULL
);
--> statement-breakpoint
CREATE TABLE `users` (
`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
`sub` text NOT NULL,
`username` text NOT NULL,
`is_admin` integer DEFAULT false NOT NULL,
`created_at` integer DEFAULT (unixepoch()) NOT NULL
);
--> statement-breakpoint
CREATE UNIQUE INDEX `users_sub_unique` ON `users` (`sub`);--> statement-breakpoint
CREATE UNIQUE INDEX `users_username_unique` ON `users` (`username`);
+583
View File
@@ -0,0 +1,583 @@
{
"version": "6",
"dialect": "sqlite",
"id": "a6b76847-cea9-41ad-931d-e57ddc8613c4",
"prevId": "00000000-0000-0000-0000-000000000000",
"tables": {
"api_tokens": {
"name": "api_tokens",
"columns": {
"id": {
"name": "id",
"type": "integer",
"primaryKey": true,
"notNull": true,
"autoincrement": true
},
"user_id": {
"name": "user_id",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"name": {
"name": "name",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"token_hash": {
"name": "token_hash",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"created_at": {
"name": "created_at",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": "(unixepoch())"
},
"last_used_at": {
"name": "last_used_at",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
}
},
"indexes": {
"api_tokens_token_hash_unique": {
"name": "api_tokens_token_hash_unique",
"columns": [
"token_hash"
],
"isUnique": true
}
},
"foreignKeys": {
"api_tokens_user_id_users_id_fk": {
"name": "api_tokens_user_id_users_id_fk",
"tableFrom": "api_tokens",
"tableTo": "users",
"columnsFrom": [
"user_id"
],
"columnsTo": [
"id"
],
"onDelete": "cascade",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"checkConstraints": {}
},
"blocks": {
"name": "blocks",
"columns": {
"id": {
"name": "id",
"type": "integer",
"primaryKey": true,
"notNull": true,
"autoincrement": true
},
"page_id": {
"name": "page_id",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"position": {
"name": "position",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"kind": {
"name": "kind",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"label": {
"name": "label",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"markdown": {
"name": "markdown",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"target_id": {
"name": "target_id",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
}
},
"indexes": {
"blocks_page": {
"name": "blocks_page",
"columns": [
"page_id",
"position"
],
"isUnique": false
},
"blocks_target": {
"name": "blocks_target",
"columns": [
"target_id"
],
"isUnique": false
}
},
"foreignKeys": {
"blocks_page_id_pages_id_fk": {
"name": "blocks_page_id_pages_id_fk",
"tableFrom": "blocks",
"tableTo": "pages",
"columnsFrom": [
"page_id"
],
"columnsTo": [
"id"
],
"onDelete": "cascade",
"onUpdate": "no action"
},
"blocks_target_id_pages_id_fk": {
"name": "blocks_target_id_pages_id_fk",
"tableFrom": "blocks",
"tableTo": "pages",
"columnsFrom": [
"target_id"
],
"columnsTo": [
"id"
],
"onDelete": "cascade",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"checkConstraints": {}
},
"clicks": {
"name": "clicks",
"columns": {
"id": {
"name": "id",
"type": "integer",
"primaryKey": true,
"notNull": true,
"autoincrement": true
},
"page_id": {
"name": "page_id",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"at": {
"name": "at",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"day": {
"name": "day",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"visitor": {
"name": "visitor",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
}
},
"indexes": {
"clicks_page_day": {
"name": "clicks_page_day",
"columns": [
"page_id",
"day",
"visitor"
],
"isUnique": false
},
"clicks_at": {
"name": "clicks_at",
"columns": [
"at"
],
"isUnique": false
}
},
"foreignKeys": {
"clicks_page_id_pages_id_fk": {
"name": "clicks_page_id_pages_id_fk",
"tableFrom": "clicks",
"tableTo": "pages",
"columnsFrom": [
"page_id"
],
"columnsTo": [
"id"
],
"onDelete": "cascade",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"checkConstraints": {}
},
"daily_stats": {
"name": "daily_stats",
"columns": {
"page_id": {
"name": "page_id",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"day": {
"name": "day",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"clicks": {
"name": "clicks",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": 0
},
"uniques": {
"name": "uniques",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": 0
},
"last_at": {
"name": "last_at",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
}
},
"indexes": {},
"foreignKeys": {
"daily_stats_page_id_pages_id_fk": {
"name": "daily_stats_page_id_pages_id_fk",
"tableFrom": "daily_stats",
"tableTo": "pages",
"columnsFrom": [
"page_id"
],
"columnsTo": [
"id"
],
"onDelete": "cascade",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {
"daily_stats_page_id_day_pk": {
"columns": [
"page_id",
"day"
],
"name": "daily_stats_page_id_day_pk"
}
},
"uniqueConstraints": {},
"checkConstraints": {}
},
"pages": {
"name": "pages",
"columns": {
"id": {
"name": "id",
"type": "integer",
"primaryKey": true,
"notNull": true,
"autoincrement": true
},
"namespace": {
"name": "namespace",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"code": {
"name": "code",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"kind": {
"name": "kind",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"dest": {
"name": "dest",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"title": {
"name": "title",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"avatar": {
"name": "avatar",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"theme": {
"name": "theme",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"created_by": {
"name": "created_by",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"created_at": {
"name": "created_at",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": "(unixepoch())"
},
"updated_at": {
"name": "updated_at",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": "(unixepoch())"
}
},
"indexes": {
"pages_namespace_code": {
"name": "pages_namespace_code",
"columns": [
"namespace",
"code"
],
"isUnique": true
}
},
"foreignKeys": {
"pages_created_by_users_id_fk": {
"name": "pages_created_by_users_id_fk",
"tableFrom": "pages",
"tableTo": "users",
"columnsFrom": [
"created_by"
],
"columnsTo": [
"id"
],
"onDelete": "set null",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"checkConstraints": {}
},
"sessions": {
"name": "sessions",
"columns": {
"id": {
"name": "id",
"type": "text",
"primaryKey": true,
"notNull": true,
"autoincrement": false
},
"user_id": {
"name": "user_id",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"expires_at": {
"name": "expires_at",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
}
},
"indexes": {},
"foreignKeys": {
"sessions_user_id_users_id_fk": {
"name": "sessions_user_id_users_id_fk",
"tableFrom": "sessions",
"tableTo": "users",
"columnsFrom": [
"user_id"
],
"columnsTo": [
"id"
],
"onDelete": "cascade",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"checkConstraints": {}
},
"settings": {
"name": "settings",
"columns": {
"key": {
"name": "key",
"type": "text",
"primaryKey": true,
"notNull": true,
"autoincrement": false
},
"value": {
"name": "value",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
}
},
"indexes": {},
"foreignKeys": {},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"checkConstraints": {}
},
"users": {
"name": "users",
"columns": {
"id": {
"name": "id",
"type": "integer",
"primaryKey": true,
"notNull": true,
"autoincrement": true
},
"sub": {
"name": "sub",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"username": {
"name": "username",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"is_admin": {
"name": "is_admin",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": false
},
"created_at": {
"name": "created_at",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": "(unixepoch())"
}
},
"indexes": {
"users_sub_unique": {
"name": "users_sub_unique",
"columns": [
"sub"
],
"isUnique": true
},
"users_username_unique": {
"name": "users_username_unique",
"columns": [
"username"
],
"isUnique": true
}
},
"foreignKeys": {},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"checkConstraints": {}
}
},
"views": {},
"enums": {},
"_meta": {
"schemas": {},
"tables": {},
"columns": {}
},
"internal": {
"indexes": {}
}
}
+13
View File
@@ -0,0 +1,13 @@
{
"version": "7",
"dialect": "sqlite",
"entries": [
{
"idx": 0,
"version": "6",
"when": 1791978231861,
"tag": "0000_init",
"breakpoints": true
}
]
}
-20
View File
@@ -1,20 +0,0 @@
/** @type {import('next').NextConfig} */
const nextConfig = {
images: {
remotePatterns: [
{
protocol: 'https',
hostname: 'img.logo.dev',
}
]
},
output: "standalone",
experimental: {
serverActions: {
bodySizeLimit: "5mb"
}
}
};
export default nextConfig;
-7860
View File
File diff suppressed because it is too large Load Diff
+47 -27
View File
@@ -1,36 +1,56 @@
{
"name": "short",
"version": "0.1.0",
"version": "2.0.0",
"private": true,
"type": "module",
"engines": {
"node": ">=22"
},
"scripts": {
"dev": "next dev --turbopack",
"build": "next build",
"start": "next start",
"lint": "next lint"
"dev": "concurrently -n server,web \"pnpm dev:server\" \"pnpm dev:web\"",
"dev:server": "tsx watch --env-file-if-exists=.env src/server/index.tsx",
"dev:web": "vite",
"build": "pnpm build:web && pnpm build:server",
"build:web": "vite build",
"build:server": "tsc -p tsconfig.server.json",
"start": "node dist/server/index.js",
"typecheck": "tsc -p tsconfig.server.json --noEmit && tsc -p tsconfig.web.json --noEmit",
"test": "vitest run",
"db:generate": "drizzle-kit generate"
},
"dependencies": {
"@hello-pangea/dnd": "^18.0.1",
"@heroicons/react": "^2.2.0",
"@prisma/client": "^6.5.0",
"js-sha256": "^0.11.0",
"next": "^15.2.4",
"next-auth": "^5.0.0-beta.25",
"next-qrcode": "^2.5.1",
"react-hot-toast": "^2.5.2",
"recharts": "^2.15.1",
"ua-parser-js": "^2.0.3",
"zod": "^3.22.4"
"@hono/node-server": "^2.1.5",
"better-sqlite3": "^13.0.3",
"drizzle-orm": "^0.45.4",
"hono": "^4.13.13",
"markdown-it": "^15.0.2",
"openid-client": "^6.8.8",
"zod": "^4.6.7"
},
"devDependencies": {
"@tailwindcss/postcss": "^4.0.17",
"@types/node": "^20",
"@types/react": "^18",
"@types/react-dom": "^18",
"eslint": "^8",
"eslint-config-next": "14.1.0",
"postcss": "^8.5.3",
"prisma": "^6.5.0",
"tailwindcss": "^4.0.17",
"typescript": "^5"
}
"@dnd-kit/core": "^6.3.1",
"@dnd-kit/sortable": "^10.0.0",
"@dnd-kit/utilities": "^3.2.2",
"@tailwindcss/vite": "^4.3.3",
"@types/better-sqlite3": "^9.6.0",
"@types/markdown-it": "^14.2.0",
"@types/node": "^24.19.2",
"@types/qrcode": "^1.5.6",
"@types/react": "^19.3.0",
"@types/react-dom": "^19.3.0",
"@vitejs/plugin-react": "^6.1.2",
"concurrently": "^10.0.6",
"drizzle-kit": "^0.31.11",
"lucide-react": "^1.56.0",
"qrcode": "^1.5.4",
"react": "^19.3.0",
"react-dom": "^19.3.0",
"tailwindcss": "^4.3.3",
"tsx": "^4.23.15",
"typescript": "^7.0.2",
"uplot": "^1.6.32",
"vite": "^8.3.4",
"vitest": "^5.0.4"
},
"packageManager": "pnpm@11.28.5"
}
+2839
View File
File diff suppressed because it is too large Load Diff
+3
View File
@@ -0,0 +1,3 @@
allowBuilds:
better-sqlite3: true
esbuild: true
-6
View File
@@ -1,6 +0,0 @@
/** @type {import('tailwindcss').Config} */
export default {
plugins: {
'@tailwindcss/postcss': {},
},
}
-14
View File
@@ -1,14 +0,0 @@
import { PrismaClient } from '@prisma/client';
let prisma: PrismaClient;
if (process.env.NODE_ENV === 'production') {
prisma = new PrismaClient();
} else {
if (!(global as any).prisma) {
(global as any).prisma = new PrismaClient();
}
prisma = (global as any).prisma;
}
export default prisma;
-93
View File
@@ -1,93 +0,0 @@
generator client {
provider = "prisma-client-js"
}
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}
// The basis for the pages providing a shortcode to access them
model Page {
uuid String @id @default(uuid())
shortcode String @unique
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
redirectPage RedirectPage[]
customPage CustomPage[]
stat Stat[]
pinnedPage PinnedPage?
@@index([shortcode])
}
// The redirect page for the url shortener
model RedirectPage {
uuid String @id @default(uuid())
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
dest String
page Page @relation(fields: [pageUuid], references: [uuid])
pageUuid String
linkBlock LinkBlock[]
}
// The custom page to display mutliple blocks of text and links
model CustomPage {
uuid String @id @default(uuid())
title String
image String?
created_at DateTime @default(now())
updated_at DateTime @updatedAt
page Page @relation(fields: [pageUuid], references: [uuid])
pageUuid String
textBlock TextBlock[]
linkBlock LinkBlock[]
}
// Text block to be displayed on the custom page
// To provide additional information
model TextBlock {
uuid String @id @default(uuid())
order Int
text String
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
customPage CustomPage @relation(fields: [customPageUuid], references: [uuid])
customPageUuid String
}
// Link block to integrate a RedirectPage into the custom page
model LinkBlock {
uuid String @id @default(uuid())
order Int
title String
customPage CustomPage @relation(fields: [customPageUuid], references: [uuid])
redirectPage RedirectPage @relation(fields: [redirectPageUuid], references: [uuid])
customPageUuid String
redirectPageUuid String
}
// Statts to track the links being accessed
model Stat {
uuid String @id @default(uuid())
accessedAt DateTime @default(now())
hash String? @db.VarChar(64)
userAgent String? @db.Text
page Page @relation(fields: [pageUuid], references: [uuid])
pageUuid String
}
model PinnedPage {
id Int @id @default(1)
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
page Page @relation(fields: [pageUuid], references: [uuid])
pageUuid String @unique
}
-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);
}
+100
View File
@@ -0,0 +1,100 @@
import { ArrowLeft, LogIn } from "lucide-react";
import type { Me } from "../../shared/api-types.js";
import { useApi } from "../api.js";
import { buttonClass } from "../components/ui/button.js";
import { Link } from "../components/ui/misc.js";
import { EmptyState } from "../components/ui/surface.js";
import { parseRoute, usePath } from "../router.js";
import { AdminScreen } from "../screens/AdminScreen.js";
import { DetailScreen } from "../screens/detail/DetailScreen.js";
import { ListScreen } from "../screens/ListScreen.js";
import { OverviewScreen } from "../screens/OverviewScreen.js";
import { TokensScreen } from "../screens/TokensScreen.js";
import { Shell } from "./Shell.js";
function Login() {
return (
<div className="flex min-h-dvh items-center justify-center p-6">
<div className="w-full max-w-sm animate-pop-in rounded-2xl border border-border bg-surface p-8 text-center shadow-xl">
<img src="/~/short.svg" alt="" className="mx-auto mb-5 size-12 rounded-xl" />
<h1 className="text-xl font-semibold tracking-tight">Sign in to short</h1>
<p className="mt-1.5 text-sm text-muted">Manage your short links, link pages and stats.</p>
<a href="/~/auth/login" className={buttonClass("primary", "md", "mt-6 w-full")}>
<LogIn />
Continue with single sign-on
</a>
<a href="/" className="mt-4 inline-block text-sm text-muted hover:text-fg">
Back to homepage
</a>
</div>
</div>
);
}
function Splash() {
return (
<div className="flex min-h-dvh items-center justify-center">
<img src="/~/short.svg" alt="" className="size-10 animate-pulse rounded-lg" />
</div>
);
}
export function App() {
const me = useApi<Me>("/me");
const path = usePath();
if (me.error?.status === 401) return <Login />;
if (me.error) {
return (
<div className="flex min-h-dvh items-center justify-center p-6 text-center">
<div>
<h1 className="text-lg font-semibold">Can't reach the server</h1>
<p className="mt-1 text-sm text-muted">{me.error.message}</p>
</div>
</div>
);
}
if (!me.data) return <Splash />;
const logout = async () => {
await fetch("/~/auth/logout", { method: "POST", credentials: "same-origin" });
location.href = "/~/";
};
const route = parseRoute(path);
let screen;
switch (route.name) {
case "overview":
screen = <OverviewScreen me={me.data} />;
break;
case "list":
screen = <ListScreen key={route.kind} kind={route.kind} me={me.data} />;
break;
case "detail":
screen = <DetailScreen key={route.id} id={route.id} kind={route.kind} tab={route.tab} me={me.data} />;
break;
case "tokens":
screen = <TokensScreen />;
break;
case "admin":
screen = me.data.isAdmin ? <AdminScreen /> : null;
break;
}
return (
<Shell me={me.data} route={route} onLogout={logout}>
{screen ?? (
<EmptyState
icon={<ArrowLeft />}
title="Page not found"
description="This part of the dashboard doesn't exist."
action={
<Link to="/~/" className={buttonClass("secondary")}>
Go to overview
</Link>
}
/>
)}
</Shell>
);
}
+124
View File
@@ -0,0 +1,124 @@
import type { ReactNode } from "react";
import { KeyRound, LayoutDashboard, Link2, LogOut, PanelsTopLeft, ShieldCheck } from "lucide-react";
import type { Me } from "../../shared/api-types.js";
import { Button } from "../components/ui/button.js";
import { Link } from "../components/ui/misc.js";
import { cx } from "../lib/cx.js";
import type { Route } from "../router.js";
type Section = "overview" | "links" | "pages" | "tokens" | "admin";
function sectionOf(route: Route): Section | null {
switch (route.name) {
case "overview":
case "tokens":
case "admin":
return route.name;
case "list":
case "detail":
return route.kind === "redirect" ? "links" : "pages";
default:
return null;
}
}
const NAV: { id: Section; label: string; short: string; to: string; icon: ReactNode; adminOnly?: boolean }[] = [
{ id: "overview", label: "Overview", short: "Overview", to: "/~/", icon: <LayoutDashboard /> },
{ id: "links", label: "Short links", short: "Links", to: "/~/links", icon: <Link2 /> },
{ id: "pages", label: "Link pages", short: "Pages", to: "/~/pages", icon: <PanelsTopLeft /> },
{ id: "tokens", label: "API tokens", short: "Tokens", to: "/~/tokens", icon: <KeyRound /> },
{ id: "admin", label: "Administration", short: "Admin", to: "/~/admin", icon: <ShieldCheck />, adminOnly: true },
];
function Logo() {
return (
<Link to="/~/" className="flex items-center gap-2.5">
<img src="/~/short.svg" alt="" className="size-7 rounded-md" />
<span className="text-[15px] font-semibold tracking-tight text-fg">short</span>
</Link>
);
}
function UserAvatar({ username }: { username: string }) {
return (
<span className="flex size-8 shrink-0 items-center justify-center rounded-full bg-accent-soft text-sm font-semibold text-accent-soft-fg uppercase">
{username.charAt(0)}
</span>
);
}
export function Shell({ me, route, onLogout, children }: { me: Me; route: Route; onLogout: () => void; children: ReactNode }) {
const active = sectionOf(route);
const items = NAV.filter((n) => !n.adminOnly || me.isAdmin);
return (
<div className="min-h-dvh lg:pl-64">
{/* Desktop sidebar */}
<aside className="fixed inset-y-0 left-0 hidden w-64 flex-col border-r border-border bg-surface lg:flex">
<div className="flex h-16 items-center px-5">
<Logo />
</div>
<nav className="flex flex-1 flex-col gap-0.5 px-3 py-2" aria-label="Main">
{items.map((item) => (
<Link
key={item.id}
to={item.to}
aria-current={item.id === active ? "page" : undefined}
className={cx(
"flex items-center gap-3 rounded-lg px-3 py-2 text-sm font-medium transition-colors [&_svg]:size-4",
item.id === active ? "bg-accent-soft text-accent-soft-fg" : "text-muted hover:bg-surface-2 hover:text-fg",
)}
>
{item.icon}
{item.label}
</Link>
))}
</nav>
<div className="flex items-center gap-3 border-t border-border p-4">
<UserAvatar username={me.username} />
<div className="min-w-0 flex-1">
<div className="truncate text-sm font-medium text-fg">{me.username}</div>
<div className="text-xs text-muted">{me.isAdmin ? "Administrator" : "User"}</div>
</div>
<Button variant="ghost" size="icon-sm" onClick={onLogout} aria-label="Sign out" title="Sign out">
<LogOut />
</Button>
</div>
</aside>
{/* Mobile top bar */}
<header className="sticky top-0 z-30 flex h-14 items-center justify-between border-b border-border bg-surface/85 px-4 backdrop-blur lg:hidden">
<Logo />
<div className="flex items-center gap-1">
<UserAvatar username={me.username} />
<Button variant="ghost" size="icon-sm" onClick={onLogout} aria-label="Sign out">
<LogOut />
</Button>
</div>
</header>
<main className="mx-auto max-w-6xl px-4 pt-6 pb-28 sm:px-6 lg:px-10 lg:pt-10 lg:pb-12">{children}</main>
{/* Mobile tab bar */}
<nav
className="fixed inset-x-0 bottom-0 z-30 flex border-t border-border bg-surface/90 pb-[env(safe-area-inset-bottom)] backdrop-blur lg:hidden"
aria-label="Main"
>
{items.map((item) => (
<Link
key={item.id}
to={item.to}
aria-current={item.id === active ? "page" : undefined}
className={cx(
"flex flex-1 flex-col items-center gap-1 py-2 text-[11px] font-medium [&_svg]:size-5",
item.id === active ? "text-accent" : "text-muted",
)}
>
{item.icon}
{item.short}
</Link>
))}
</nav>
</div>
);
}
+136
View File
@@ -0,0 +1,136 @@
import { useState } from "react";
import type { Me, PageKind, PageSummary } from "../../shared/api-types.js";
import { api, ApiRequestError, errorMessage, useApi } from "../api.js";
import { Button } from "./ui/button.js";
import { Dialog } from "./ui/dialog.js";
import { Field, Input, PrefixInput, Select } from "./ui/form.js";
const COPY: Record<PageKind, { title: string; description: string; submit: string }> = {
redirect: {
title: "New short link",
description: "Redirects visitors to another URL. You can change the destination later.",
submit: "Create link",
},
linkpage: {
title: "New link page",
description: "A page with your avatar, link buttons and text — like a link in bio.",
submit: "Create page",
},
};
export function CreatePageDialog({
kind,
me,
open,
onClose,
onCreated,
}: {
kind: PageKind;
me: Me;
open: boolean;
onClose: () => void;
onCreated: (page: PageSummary) => void;
}) {
const users = useApi<string[]>(me.isAdmin && open ? "/users" : null);
const [namespace, setNamespace] = useState(me.username);
const [code, setCode] = useState("");
const [value, setValue] = useState("");
const [busy, setBusy] = useState(false);
const [errors, setErrors] = useState<Record<string, string>>({});
const close = () => {
setCode("");
setValue("");
setErrors({});
onClose();
};
const submit = async () => {
setBusy(true);
setErrors({});
try {
const page = await api<PageSummary>("POST", "/pages", {
kind,
namespace,
...(code.trim() && { code: code.trim() }),
...(kind === "redirect" ? { dest: value.trim() } : { title: value.trim() }),
});
close();
onCreated(page);
} catch (err) {
const issues = err instanceof ApiRequestError ? err.issues : undefined;
setErrors(
issues
? Object.fromEntries(Object.entries(issues).map(([k, v]) => [k, v.join(", ")]))
: { form: errorMessage(err) },
);
} finally {
setBusy(false);
}
};
const copy = COPY[kind];
const prefix = namespace ? `/${namespace}/` : "/";
return (
<Dialog
open={open}
onClose={close}
title={copy.title}
description={copy.description}
onSubmit={submit}
footer={
<>
<Button variant="secondary" onClick={close}>
Cancel
</Button>
<Button type="submit" loading={busy}>
{copy.submit}
</Button>
</>
}
>
{kind === "redirect" ? (
<Field label="Destination URL" error={errors.dest}>
{(id) => (
<Input id={id} type="url" required autoFocus placeholder="https://example.com/very/long/url" value={value} onChange={(e) => setValue(e.target.value)} />
)}
</Field>
) : (
<Field label="Title" error={errors.title}>
{(id) => <Input id={id} required autoFocus placeholder="Jane Doe" value={value} onChange={(e) => setValue(e.target.value)} />}
</Field>
)}
{me.isAdmin && (
<Field label="Namespace" hint="Root links are only available to admins." error={errors.namespace}>
{(id) => (
<Select id={id} value={namespace} onChange={(e) => setNamespace(e.target.value)}>
<option value="">Root (/)</option>
{(users.data ?? [me.username]).map((u) => (
<option key={u} value={u}>
{u === me.username ? `${u} (you)` : u}
</option>
))}
</Select>
)}
</Field>
)}
<Field label="Shortcode" hint="Optional. Leave empty for a random 5-character code." error={errors.code}>
{(id) => (
<PrefixInput
id={id}
prefix={prefix}
placeholder="random"
pattern="[A-Za-z0-9][A-Za-z0-9_\-]{0,63}"
value={code}
onChange={(e) => setCode(e.target.value)}
/>
)}
</Field>
{errors.form && <p className="text-sm text-danger">{errors.form}</p>}
</Dialog>
);
}
+47
View File
@@ -0,0 +1,47 @@
import type { ButtonHTMLAttributes, ReactNode } from "react";
import { LoaderCircle } from "lucide-react";
import { cx } from "../../lib/cx.js";
type Variant = "primary" | "secondary" | "ghost" | "danger";
type Size = "sm" | "md" | "icon" | "icon-sm";
const variants: Record<Variant, string> = {
primary: "bg-accent text-accent-fg shadow-sm hover:bg-accent-hover",
secondary: "border border-border bg-surface text-fg shadow-xs hover:bg-surface-2",
ghost: "text-muted hover:bg-surface-2 hover:text-fg",
danger: "bg-danger text-white shadow-sm hover:bg-danger/90",
};
const sizes: Record<Size, string> = {
sm: "h-8 px-3 text-sm",
md: "h-9 px-4 text-sm",
icon: "size-9",
"icon-sm": "size-8",
};
export function buttonClass(variant: Variant = "primary", size: Size = "md", className?: string) {
return cx(
"inline-flex shrink-0 cursor-pointer items-center justify-center gap-2 rounded-lg font-medium whitespace-nowrap transition-colors",
"focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-accent disabled:pointer-events-none disabled:opacity-50",
"[&_svg]:size-4 [&_svg]:shrink-0",
variants[variant],
sizes[size],
className,
);
}
interface ButtonProps extends ButtonHTMLAttributes<HTMLButtonElement> {
variant?: Variant;
size?: Size;
loading?: boolean;
icon?: ReactNode;
}
export function Button({ variant, size, loading, icon, className, children, disabled, type = "button", ...props }: ButtonProps) {
return (
<button type={type} className={buttonClass(variant, size, className)} disabled={disabled || loading} {...props}>
{loading ? <LoaderCircle className="animate-spin" /> : icon}
{children}
</button>
);
}
+118
View File
@@ -0,0 +1,118 @@
import { createContext, useCallback, useContext, useEffect, useRef, useState, type FormEvent, type ReactNode } from "react";
import { X } from "lucide-react";
import { cx } from "../../lib/cx.js";
import { Button } from "./button.js";
// Modal dialog built on the native <dialog> element (focus trapping, Escape and top layer for free).
export function Dialog({
open,
onClose,
title,
description,
children,
footer,
onSubmit,
size = "md",
}: {
open: boolean;
onClose: () => void;
title: ReactNode;
description?: ReactNode;
children?: ReactNode;
footer?: ReactNode;
/** When set, the dialog body is a form and the footer buttons can submit it. */
onSubmit?: (e: FormEvent) => void;
size?: "sm" | "md";
}) {
const ref = useRef<HTMLDialogElement>(null);
useEffect(() => {
const dialog = ref.current;
if (!dialog) return;
if (open && !dialog.open) dialog.showModal();
if (!open && dialog.open) dialog.close();
}, [open]);
const Body = onSubmit ? "form" : "div";
return (
<dialog
ref={ref}
onClose={onClose}
onClick={(e) => e.target === ref.current && onClose()}
className={cx(
"m-auto w-[calc(100%-2rem)] rounded-2xl border border-border bg-surface p-0 text-fg shadow-2xl backdrop:bg-black/50 backdrop:backdrop-blur-[2px] open:animate-pop-in",
size === "sm" ? "max-w-md" : "max-w-lg",
)}
>
{open && (
<Body
onSubmit={
onSubmit &&
((e: FormEvent) => {
e.preventDefault();
onSubmit(e);
})
}
>
<div className={cx("flex items-start justify-between gap-4 px-6 pt-5", !children && "pb-5")}>
<div>
<h2 className="text-lg font-semibold">{title}</h2>
{description && <p className="mt-1 text-sm text-muted">{description}</p>}
</div>
<Button variant="ghost" size="icon-sm" onClick={onClose} aria-label="Close" className="-mr-2">
<X />
</Button>
</div>
{children && <div className="flex flex-col gap-4 px-6 py-5">{children}</div>}
{footer && <div className="flex justify-end gap-2 rounded-b-2xl border-t border-border bg-surface-2/50 px-6 py-3">{footer}</div>}
</Body>
)}
</dialog>
);
}
interface ConfirmOptions {
title: string;
description?: ReactNode;
confirmLabel?: string;
danger?: boolean;
}
const ConfirmContext = createContext<(options: ConfirmOptions) => Promise<boolean>>(async () => false);
// Promise-based replacement for window.confirm: `if (await confirm({...})) …`
export function ConfirmProvider({ children }: { children: ReactNode }) {
const [state, setState] = useState<(ConfirmOptions & { resolve: (ok: boolean) => void }) | null>(null);
const confirm = useCallback((options: ConfirmOptions) => new Promise<boolean>((resolve) => setState({ ...options, resolve })), []);
const close = (ok: boolean) => {
state?.resolve(ok);
setState(null);
};
return (
<ConfirmContext.Provider value={confirm}>
{children}
<Dialog
open={!!state}
onClose={() => close(false)}
title={state?.title}
description={state?.description}
size="sm"
footer={
<>
<Button variant="secondary" onClick={() => close(false)}>
Cancel
</Button>
<Button variant={state?.danger ? "danger" : "primary"} onClick={() => close(true)} autoFocus>
{state?.confirmLabel ?? "Confirm"}
</Button>
</>
}
/>
</ConfirmContext.Provider>
);
}
export const useConfirm = () => useContext(ConfirmContext);
+104
View File
@@ -0,0 +1,104 @@
import { useId, type InputHTMLAttributes, type ReactNode, type SelectHTMLAttributes, type TextareaHTMLAttributes } from "react";
import { ChevronDown } from "lucide-react";
import { cx } from "../../lib/cx.js";
export function Field({
label,
hint,
error,
children,
className,
}: {
label: string;
hint?: ReactNode;
error?: string;
children: (id: string) => ReactNode;
className?: string;
}) {
const id = useId();
return (
<div className={cx("flex flex-col gap-1.5", className)}>
<label htmlFor={id} className="text-sm font-medium text-fg">
{label}
</label>
{children(id)}
{error ? <p className="text-xs text-danger">{error}</p> : hint && <p className="text-xs text-muted">{hint}</p>}
</div>
);
}
export function Input({ className, ...props }: InputHTMLAttributes<HTMLInputElement>) {
return <input className={cx("control h-9", className)} {...props} />;
}
// An input with a fixed, non-editable prefix such as "/alice/".
export function PrefixInput({ prefix, className, ...props }: InputHTMLAttributes<HTMLInputElement> & { prefix: string }) {
return (
<div className="flex rounded-lg shadow-xs focus-within:ring-3 focus-within:ring-accent/20">
<span className="flex max-w-[55%] items-center overflow-hidden rounded-l-lg border border-r-0 border-border bg-surface-2 px-3 font-mono text-xs text-muted">
{prefix}
</span>
<input className={cx("control h-9 rounded-l-none font-mono shadow-none focus:ring-0", className)} {...props} />
</div>
);
}
export function Textarea({ className, ...props }: TextareaHTMLAttributes<HTMLTextAreaElement>) {
return <textarea className={cx("control min-h-24 resize-y py-2", className)} {...props} />;
}
export function Select({ className, children, ...props }: SelectHTMLAttributes<HTMLSelectElement>) {
return (
<div className="relative">
<select className={cx("control h-9 cursor-pointer appearance-none pr-9", className)} {...props}>
{children}
</select>
<ChevronDown className="pointer-events-none absolute top-1/2 right-3 size-4 -translate-y-1/2 text-muted" />
</div>
);
}
// A row of mutually exclusive options, e.g. "7d / 30d / 90d".
export function Segmented<T extends string | number>({
value,
options,
onChange,
ariaLabel,
}: {
value: T;
options: { value: T; label: ReactNode }[];
onChange: (value: T) => void;
ariaLabel: string;
}) {
return (
<div role="radiogroup" aria-label={ariaLabel} className="inline-flex w-fit rounded-lg border border-border bg-surface-2 p-0.5">
{options.map((o) => (
<button
key={String(o.value)}
type="button"
role="radio"
aria-checked={o.value === value}
onClick={() => onChange(o.value)}
className={cx(
"h-7 cursor-pointer rounded-md px-3 text-sm font-medium transition",
o.value === value ? "bg-surface text-fg shadow-sm" : "text-muted hover:text-fg",
)}
>
{o.label}
</button>
))}
</div>
);
}
export function ColorInput({ value, onChange, label }: { value: string; onChange: (value: string) => void; label: string }) {
return (
<div className="flex items-center gap-2 rounded-lg border border-border bg-surface p-1 pr-3 shadow-xs">
<label className="relative size-7 shrink-0 cursor-pointer overflow-hidden rounded-md border border-border" style={{ background: value }}>
<span className="sr-only">{label}</span>
<input type="color" value={value} onChange={(e) => onChange(e.target.value)} className="absolute inset-0 cursor-pointer opacity-0" />
</label>
<span className="font-mono text-xs text-muted uppercase">{value}</span>
</div>
);
}
+105
View File
@@ -0,0 +1,105 @@
import { useState, type ReactNode } from "react";
import { Check, Copy } from "lucide-react";
import { cx } from "../../lib/cx.js";
import { linkHandler } from "../../router.js";
import { Button } from "./button.js";
import { useToast } from "./toast.js";
export function Link({ to, className, children, ...rest }: { to: string; className?: string; children: ReactNode; "aria-current"?: "page" }) {
return (
<a href={to} onClick={linkHandler(to)} className={className} {...rest}>
{children}
</a>
);
}
export function publicUrl(path: string): string {
return `${location.origin}${path}`;
}
export function CopyButton({ value, label, size = "icon-sm" }: { value: string; label?: string; size?: "icon-sm" | "sm" }) {
const [copied, setCopied] = useState(false);
const toast = useToast();
const copy = async () => {
try {
await navigator.clipboard.writeText(value);
setCopied(true);
setTimeout(() => setCopied(false), 1500);
} catch {
toast("Couldn't access the clipboard", true);
}
};
return (
<Button
variant={label ? "secondary" : "ghost"}
size={label ? "sm" : size}
onClick={(e) => {
e.stopPropagation();
e.preventDefault();
void copy();
}}
aria-label={label ?? "Copy"}
title="Copy URL"
icon={copied ? <Check className="text-success" /> : <Copy />}
>
{label && (copied ? "Copied" : label)}
</Button>
);
}
// Website favicon placeholder: the first letter of the destination's hostname.
export function DomainIcon({ url, className }: { url: string | null; className?: string }) {
let host = "";
try {
host = url ? new URL(url).hostname.replace(/^www\./, "") : "";
} catch {
// Keep the placeholder.
}
return (
<span
className={cx(
"flex size-8 shrink-0 items-center justify-center rounded-lg border border-border bg-surface-2 text-xs font-semibold text-muted uppercase",
className,
)}
aria-hidden
>
{host.charAt(0) || "?"}
</span>
);
}
export function Tabs({ tabs, active }: { tabs: { id: string; label: string; to: string; icon?: ReactNode }[]; active: string }) {
return (
<nav className="-mx-4 mb-6 overflow-x-auto border-b border-border px-4 sm:mx-0 sm:px-0" aria-label="Sections">
<div className="flex gap-1">
{tabs.map((t) => (
<Link
key={t.id}
to={t.to}
aria-current={t.id === active ? "page" : undefined}
className={cx(
"-mb-px flex items-center gap-2 border-b-2 px-3 py-2.5 text-sm font-medium whitespace-nowrap transition-colors [&_svg]:size-4",
t.id === active ? "border-accent text-fg" : "border-transparent text-muted hover:border-border-strong hover:text-fg",
)}
>
{t.icon}
{t.label}
</Link>
))}
</div>
</nav>
);
}
export function Stat({ label, value, icon, hint }: { label: string; value: ReactNode; icon?: ReactNode; hint?: ReactNode }) {
return (
<div className="min-w-0 rounded-xl border border-border bg-surface p-3 shadow-xs sm:p-4">
<div className="flex items-center justify-between gap-2 truncate text-xs text-muted sm:text-sm [&_svg]:hidden [&_svg]:size-4 sm:[&_svg]:block">
{label}
{icon}
</div>
<div className="mt-2 text-xl font-semibold tracking-tight text-fg tabular-nums sm:text-2xl">{value}</div>
{hint && <div className="mt-1 truncate text-xs text-muted">{hint}</div>}
</div>
);
}
+111
View File
@@ -0,0 +1,111 @@
import type { ReactNode } from "react";
import { AlertTriangle, Info } from "lucide-react";
import { cx } from "../../lib/cx.js";
export function Card({ children, className }: { children: ReactNode; className?: string }) {
return <section className={cx("rounded-xl border border-border bg-surface shadow-xs", className)}>{children}</section>;
}
export function CardHeader({ title, description, actions }: { title: ReactNode; description?: ReactNode; actions?: ReactNode }) {
return (
<div className="flex flex-wrap items-start justify-between gap-3 border-border px-5 py-4 not-last:border-b">
<div className="min-w-0">
<h2 className="text-base font-semibold text-fg">{title}</h2>
{description && <p className="mt-0.5 text-sm text-muted">{description}</p>}
</div>
{actions && <div className="flex items-center gap-2">{actions}</div>}
</div>
);
}
export function CardBody({ children, className }: { children: ReactNode; className?: string }) {
return <div className={cx("p-5", className)}>{children}</div>;
}
export function CardFooter({ children, className }: { children: ReactNode; className?: string }) {
return (
<div className={cx("flex items-center justify-end gap-2 rounded-b-xl border-t border-border bg-surface-2/50 px-5 py-3", className)}>
{children}
</div>
);
}
type Tone = "neutral" | "accent" | "warning" | "danger" | "success";
const badgeTones: Record<Tone, string> = {
neutral: "bg-surface-2 text-muted",
accent: "bg-accent-soft text-accent-soft-fg",
warning: "bg-warning-soft text-warning-soft-fg",
danger: "bg-danger-soft text-danger-soft-fg",
success: "bg-success/10 text-success",
};
export function Badge({ tone = "neutral", children, icon }: { tone?: Tone; children: ReactNode; icon?: ReactNode }) {
return (
<span
className={cx(
"inline-flex items-center gap-1 rounded-full px-2 py-0.5 text-xs font-medium whitespace-nowrap [&_svg]:size-3",
badgeTones[tone],
)}
>
{icon}
{children}
</span>
);
}
export function Alert({ tone = "warning", title, children }: { tone?: "warning" | "info"; title: string; children?: ReactNode }) {
const Icon = tone === "warning" ? AlertTriangle : Info;
return (
<div
className={cx(
"flex gap-3 rounded-xl border px-4 py-3 text-sm",
tone === "warning" ? "border-warning-soft-fg/20 bg-warning-soft text-warning-soft-fg" : "border-accent/20 bg-accent-soft text-accent-soft-fg",
)}
>
<Icon className="mt-0.5 size-4 shrink-0" />
<div>
<p className="font-medium">{title}</p>
{children && <div className="mt-1 opacity-90">{children}</div>}
</div>
</div>
);
}
export function EmptyState({ icon, title, description, action }: { icon: ReactNode; title: string; description?: string; action?: ReactNode }) {
return (
<div className="flex flex-col items-center px-6 py-14 text-center">
<div className="mb-4 flex size-12 items-center justify-center rounded-xl bg-accent-soft text-accent-soft-fg [&_svg]:size-6">{icon}</div>
<h3 className="font-semibold text-fg">{title}</h3>
{description && <p className="mt-1 max-w-sm text-sm text-muted">{description}</p>}
{action && <div className="mt-5">{action}</div>}
</div>
);
}
export function Skeleton({ className }: { className?: string }) {
return <div className={cx("animate-pulse rounded-md bg-surface-2", className)} />;
}
export function PageHeader({
title,
description,
actions,
breadcrumb,
}: {
title: ReactNode;
description?: ReactNode;
actions?: ReactNode;
breadcrumb?: ReactNode;
}) {
return (
<header className="mb-6 flex flex-wrap items-end justify-between gap-4 lg:mb-8">
<div className="min-w-0">
{breadcrumb && <div className="mb-2 text-sm text-muted">{breadcrumb}</div>}
<h1 className="text-2xl font-semibold tracking-tight text-fg">{title}</h1>
{description && <p className="mt-1 text-sm text-muted">{description}</p>}
</div>
{actions && <div className="flex flex-wrap items-center gap-2">{actions}</div>}
</header>
);
}
+60
View File
@@ -0,0 +1,60 @@
import { createContext, useCallback, useContext, useState, type ReactNode } from "react";
import { CircleAlert, CircleCheck } from "lucide-react";
import { errorMessage } from "../../api.js";
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)), error ? 5000 : 3000);
}, []);
return (
<ToastContext.Provider value={show}>
{children}
<div
aria-live="polite"
className="pointer-events-none fixed inset-x-0 bottom-20 z-50 flex flex-col items-center gap-2 px-4 lg:right-6 lg:bottom-6 lg:left-auto lg:items-end"
>
{toasts.map((t) => (
<div
key={t.id}
className="pointer-events-auto flex max-w-sm animate-pop-in items-center gap-2.5 rounded-xl border border-border bg-surface px-4 py-3 text-sm shadow-lg"
>
{t.error ? <CircleAlert className="size-4 shrink-0 text-danger" /> : <CircleCheck className="size-4 shrink-0 text-success" />}
{t.message}
</div>
))}
</div>
</ToastContext.Provider>
);
}
export const useToast = () => useContext(ToastContext);
// Runs an async action with a busy flag and reports the outcome 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 };
}
+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>
+4
View File
@@ -0,0 +1,4 @@
// Joins class names, skipping falsy values.
export function cx(...classes: (string | false | null | undefined)[]): string {
return classes.filter(Boolean).join(" ");
}
+8
View File
@@ -0,0 +1,8 @@
// Rough plain-text version of Markdown for compact previews in the editor.
export function stripMarkdown(markdown: string): string {
return markdown
.replace(/\[([^\]]*)\]\([^)]*\)/g, "$1")
.replace(/[*_`#>~]/g, "")
.replace(/\s+/g, " ")
.trim();
}
+16
View File
@@ -0,0 +1,16 @@
import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import { App } from "./app/App.js";
import { ConfirmProvider } from "./components/ui/dialog.js";
import { ToastProvider } from "./components/ui/toast.js";
import "./styles.css";
createRoot(document.getElementById("root")!).render(
<StrictMode>
<ToastProvider>
<ConfirmProvider>
<App />
</ConfirmProvider>
</ToastProvider>
</StrictMode>,
);

Before

Width:  |  Height:  |  Size: 7.3 KiB

After

Width:  |  Height:  |  Size: 7.3 KiB

Before

Width:  |  Height:  |  Size: 23 KiB

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" }
]
}

Before

Width:  |  Height:  |  Size: 773 B

After

Width:  |  Height:  |  Size: 773 B

+63
View File
@@ -0,0 +1,63 @@
import { useSyncExternalStore, type MouseEvent } from "react";
import type { PageKind } from "../shared/api-types.js";
// 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);
window.scrollTo({ top: 0 });
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);
};
}
export type Route =
| { name: "overview" }
| { name: "list"; kind: PageKind }
| { name: "detail"; kind: PageKind; id: number; tab: string | undefined }
| { name: "tokens" }
| { name: "admin" }
| { name: "notFound" };
const KIND_SEGMENT: Record<string, PageKind> = { links: "redirect", pages: "linkpage" };
export function listPath(kind: PageKind): string {
return kind === "redirect" ? "/~/links" : "/~/pages";
}
export function detailPath(page: { id: number; kind: PageKind }, tab?: string): string {
return `${listPath(page.kind)}/${page.id}${tab ? `/${tab}` : ""}`;
}
export function parseRoute(path: string): Route {
const p = path.replace(/\/+$/, "") || "/~";
if (p === "/~") return { name: "overview" };
if (p === "/~/tokens") return { name: "tokens" };
if (p === "/~/admin") return { name: "admin" };
const m = p.match(/^\/~\/(links|pages)(?:\/(\d+)(?:\/([a-z]+))?)?$/);
if (m) {
const kind = KIND_SEGMENT[m[1]!]!;
if (!m[2]) return { name: "list", kind };
return { name: "detail", kind, id: Number(m[2]), tab: m[3] };
}
return { name: "notFound" };
}
+124
View File
@@ -0,0 +1,124 @@
import { useEffect, useState } from "react";
import { PinOff, TriangleAlert, Users } from "lucide-react";
import type { Conflict, PageSummary } from "../../shared/api-types.js";
import { api, useApi } from "../api.js";
import { Button } from "../components/ui/button.js";
import { Select } from "../components/ui/form.js";
import { Link } from "../components/ui/misc.js";
import { Badge, Card, CardBody, CardHeader, EmptyState, PageHeader, Skeleton } from "../components/ui/surface.js";
import { useAction } from "../components/ui/toast.js";
import { detailPath } from "../router.js";
function HomepageCard({ pages, reload }: { pages: PageSummary[]; reload: () => Promise<void> }) {
const pinned = pages.find((p) => p.pinned);
const [selected, setSelected] = useState(pinned ? String(pinned.id) : "");
const { busy, run } = useAction();
useEffect(() => setSelected(pinned ? String(pinned.id) : ""), [pinned]);
const save = () =>
run(async () => {
if (selected) await api("PUT", "/pin", { pageId: Number(selected) });
else await api("DELETE", "/pin");
await reload();
}, selected ? "Homepage updated" : "Homepage cleared");
return (
<Card>
<CardHeader title="Homepage" description="Where visitors land when they open the bare domain." />
<CardBody className="flex flex-col gap-3 sm:flex-row">
<div className="flex-1">
<Select aria-label="Homepage" value={selected} onChange={(e) => setSelected(e.target.value)}>
<option value="">Default landing page</option>
{pages.map((p) => (
<option key={p.id} value={p.id}>
{p.path} — {p.kind === "redirect" ? p.dest : p.title}
</option>
))}
</Select>
</div>
<div className="flex gap-2">
{pinned && (
<Button variant="secondary" icon={<PinOff />} onClick={() => setSelected("")}>
Clear
</Button>
)}
<Button onClick={() => void save()} loading={busy} disabled={selected === (pinned ? String(pinned.id) : "")}>
Save
</Button>
</div>
</CardBody>
</Card>
);
}
export function AdminScreen() {
const pages = useApi<PageSummary[]>("/pages");
const users = useApi<string[]>("/users");
const conflicts = useApi<Conflict[]>("/conflicts");
const countByUser = new Map<string, number>();
for (const p of pages.data ?? []) countByUser.set(p.namespace, (countByUser.get(p.namespace) ?? 0) + 1);
return (
<>
<PageHeader title="Administration" description="Settings that affect the whole instance." />
<div className="flex flex-col gap-6">
{pages.data ? <HomepageCard pages={pages.data} reload={pages.reload} /> : <Skeleton className="h-36 rounded-xl" />}
<Card>
<CardHeader
title="Username conflicts"
description="Root links whose code matches a username. Users never get /username itself, but it's confusing."
/>
{!conflicts.data ? (
<Skeleton className="m-5 h-10" />
) : conflicts.data.length ? (
<ul className="divide-y divide-border">
{conflicts.data.map((c) => (
<li key={c.pageId} className="flex items-center gap-3 px-5 py-3">
<TriangleAlert className="size-4 text-warning-soft-fg" />
<span className="flex-1 font-mono text-sm">/{c.username}</span>
<Link to={detailPath({ id: c.pageId, kind: "redirect" }, "settings")} className="text-sm text-accent hover:underline">
Open root link
</Link>
</li>
))}
</ul>
) : (
<CardBody className="text-sm text-muted">No conflicts.</CardBody>
)}
</Card>
<Card className="overflow-hidden">
<CardHeader
title="Users"
description="Everyone who has signed in. Admin rights and usernames are managed in Authentik."
actions={users.data && <Badge>{users.data.length}</Badge>}
/>
{!users.data ? (
<Skeleton className="m-5 h-10" />
) : users.data.length ? (
<ul className="divide-y divide-border">
{users.data.map((u) => (
<li key={u} className="flex items-center gap-3 px-5 py-3">
<span className="flex size-8 items-center justify-center rounded-full bg-accent-soft text-sm font-semibold text-accent-soft-fg uppercase">
{u.charAt(0)}
</span>
<span className="flex-1 font-mono text-sm">/{u}/</span>
<span className="text-sm text-muted">
{countByUser.get(u) ?? 0} {(countByUser.get(u) ?? 0) === 1 ? "page" : "pages"}
</span>
</li>
))}
</ul>
) : (
<EmptyState icon={<Users />} title="No users yet" />
)}
</Card>
</div>
</>
);
}

Some files were not shown because too many files have changed in this diff Show More