mirror of
https://github.com/traberph/short.git
synced 2026-11-22 22:55:12 +00:00
v2: rewrite on Hono + SQLite with user namespaces
Replaces the Next.js/Prisma/next-auth app with a single-container Hono server, SQLite via Drizzle, OIDC login against Authentik and a React/Vite admin UI that talks to a JSON API. - users get /<username>/<code>, admins (Authentik group) get root codes, pinning and full access - link pages with link and Markdown text blocks, themes, avatars - editable 302 redirects, random or custom codes - personal API tokens, CSRF-protected cookie sessions - privacy-friendly stats: daily-rotating visitor salt, 90-day click retention with daily totals kept - QR codes as PNG/SVG - tests for permissions, auth, redirects and stats; CI runs them before publishing images See REQUIREMENTS.md for the full requirement list. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -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));
|
||||
})
|
||||
);
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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();
|
||||
});
|
||||
}
|
||||
@@ -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";
|
||||
@@ -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);
|
||||
});
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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),
|
||||
};
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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(),
|
||||
});
|
||||
@@ -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);
|
||||
});
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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");
|
||||
@@ -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.
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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")));
|
||||
}
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user