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,252 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { BASE_URL, flush, setup } from "./helpers.js";
|
||||
|
||||
describe("authentication", () => {
|
||||
it("rejects API requests without credentials", async () => {
|
||||
const { app } = setup();
|
||||
expect((await app.request("/~/api/me")).status).toBe(401);
|
||||
expect((await app.request("/~/api/pages", { method: "POST" })).status).toBe(401);
|
||||
});
|
||||
|
||||
it("rejects unknown bearer tokens", async () => {
|
||||
const { app } = setup();
|
||||
const res = await app.request("/~/api/me", { headers: { authorization: "Bearer short_nope" } });
|
||||
expect(res.status).toBe(401);
|
||||
});
|
||||
|
||||
it("accepts session cookies but blocks cross-site writes", async () => {
|
||||
const { app, user } = setup();
|
||||
const { session } = user("alice");
|
||||
const cookie = `short_session=${session}`;
|
||||
|
||||
expect((await app.request("/~/api/me", { headers: { cookie } })).status).toBe(200);
|
||||
|
||||
const body = JSON.stringify({ kind: "redirect", dest: "https://example.com" });
|
||||
const headers = { cookie, "content-type": "application/json" };
|
||||
const crossSite = await app.request("/~/api/pages", {
|
||||
method: "POST",
|
||||
body,
|
||||
headers: { ...headers, origin: "https://evil.test" },
|
||||
});
|
||||
expect(crossSite.status).toBe(403);
|
||||
|
||||
const sameSite = await app.request("/~/api/pages", { method: "POST", body, headers: { ...headers, origin: BASE_URL } });
|
||||
expect(sameSite.status).toBe(201);
|
||||
});
|
||||
|
||||
it("logs in via OIDC, keeps the username and follows the admin group", async () => {
|
||||
const { app, setNextLogin } = setup();
|
||||
|
||||
const login = await app.request("/~/auth/login");
|
||||
expect(login.status).toBe(302);
|
||||
const loginCookie = login.headers.get("set-cookie")!.split(";")[0]!;
|
||||
|
||||
setNextLogin({ sub: "s1", username: "alice", groups: ["short-admins"] });
|
||||
const callback = await app.request("/~/auth/callback?code=c&state=s", { headers: { cookie: loginCookie } });
|
||||
expect(callback.status).toBe(302);
|
||||
const session = callback.headers.getSetCookie().find((c) => c.startsWith("short_session="))!.split(";")[0]!;
|
||||
const me = await (await app.request("/~/api/me", { headers: { cookie: session } })).json();
|
||||
expect(me).toEqual({ username: "alice", isAdmin: true });
|
||||
|
||||
// A renamed account keeps its original namespace; losing the group removes admin.
|
||||
const login2 = await app.request("/~/auth/login");
|
||||
setNextLogin({ sub: "s1", username: "alice2", groups: [] });
|
||||
const callback2 = await app.request("/~/auth/callback?code=c&state=s", {
|
||||
headers: { cookie: login2.headers.get("set-cookie")!.split(";")[0]! },
|
||||
});
|
||||
const session2 = callback2.headers.getSetCookie().find((c) => c.startsWith("short_session="))!.split(";")[0]!;
|
||||
expect(await (await app.request("/~/api/me", { headers: { cookie: session2 } })).json()).toEqual({
|
||||
username: "alice",
|
||||
isAdmin: false,
|
||||
});
|
||||
});
|
||||
|
||||
it("rejects usernames that aren't URL-safe", async () => {
|
||||
const { app, setNextLogin } = setup();
|
||||
const login = await app.request("/~/auth/login");
|
||||
setNextLogin({ sub: "s2", username: "bob smith", groups: [] });
|
||||
const res = await app.request("/~/auth/callback?code=c&state=s", {
|
||||
headers: { cookie: login.headers.get("set-cookie")!.split(";")[0]! },
|
||||
});
|
||||
expect(res.status).toBe(403);
|
||||
});
|
||||
});
|
||||
|
||||
describe("namespaces and permissions", () => {
|
||||
it("puts user links into their namespace and forbids root", async () => {
|
||||
const { user } = setup();
|
||||
const alice = user("alice");
|
||||
|
||||
const own = await alice.api("POST", "/pages", { kind: "redirect", code: "cv", dest: "https://example.com/cv" });
|
||||
expect(own.status).toBe(201);
|
||||
expect((await own.json()).path).toBe("/alice/cv");
|
||||
|
||||
const root = await alice.api("POST", "/pages", { kind: "redirect", namespace: "", dest: "https://example.com" });
|
||||
expect(root.status).toBe(403);
|
||||
|
||||
const other = await alice.api("POST", "/pages", { kind: "redirect", namespace: "bob", dest: "https://example.com" });
|
||||
expect(other.status).toBe(403);
|
||||
});
|
||||
|
||||
it("generates a code when none is given", async () => {
|
||||
const { user } = setup();
|
||||
const res = await user("alice").api("POST", "/pages", { kind: "redirect", dest: "https://example.com" });
|
||||
expect((await res.json()).code).toMatch(/^[A-Za-z0-9]{5}$/);
|
||||
});
|
||||
|
||||
it("only accepts http(s) destinations", async () => {
|
||||
const { user } = setup();
|
||||
const res = await user("alice").api("POST", "/pages", { kind: "redirect", dest: "javascript:alert(1)" });
|
||||
expect(res.status).toBe(400);
|
||||
});
|
||||
|
||||
it("hides other users' pages and lets admins manage everything", async () => {
|
||||
const { user } = setup();
|
||||
const alice = user("alice");
|
||||
const bob = user("bob");
|
||||
const admin = user("root", true);
|
||||
|
||||
const page = await (await alice.api("POST", "/pages", { kind: "redirect", code: "a", dest: "https://a.test" })).json();
|
||||
|
||||
expect((await bob.api("GET", `/pages/${page.id}`)).status).toBe(404);
|
||||
expect((await bob.api("PATCH", `/pages/${page.id}`, { dest: "https://evil.test" })).status).toBe(404);
|
||||
expect((await bob.api("DELETE", `/pages/${page.id}`)).status).toBe(404);
|
||||
expect(await (await bob.api("GET", "/pages")).json()).toEqual([]);
|
||||
|
||||
expect((await admin.api("PATCH", `/pages/${page.id}`, { dest: "https://b.test" })).status).toBe(200);
|
||||
expect((await admin.api("GET", "/pages")).status).toBe(200);
|
||||
expect((await admin.api("POST", "/pages", { kind: "redirect", namespace: "", code: "x", dest: "https://x.test" })).status).toBe(201);
|
||||
});
|
||||
|
||||
it("keeps root codes and usernames apart", async () => {
|
||||
const { user } = setup();
|
||||
user("alice");
|
||||
const admin = user("root", true);
|
||||
|
||||
const clash = await admin.api("POST", "/pages", { kind: "redirect", namespace: "", code: "Alice", dest: "https://a.test" });
|
||||
expect(clash.status).toBe(409);
|
||||
const reserved = await admin.api("POST", "/pages", { kind: "redirect", namespace: "", code: "api", dest: "https://a.test" });
|
||||
expect(reserved.status).toBe(409);
|
||||
|
||||
// A user who logs in after a root code with their name exists shows up as a conflict.
|
||||
await admin.api("POST", "/pages", { kind: "redirect", namespace: "", code: "carol", dest: "https://c.test" });
|
||||
user("carol");
|
||||
expect(await (await admin.api("GET", "/conflicts")).json()).toEqual([{ username: "carol", pageId: expect.any(Number) }]);
|
||||
});
|
||||
|
||||
it("restricts admin-only endpoints", async () => {
|
||||
const { user } = setup();
|
||||
const alice = user("alice");
|
||||
expect((await alice.api("GET", "/users")).status).toBe(403);
|
||||
expect((await alice.api("GET", "/conflicts")).status).toBe(403);
|
||||
expect((await alice.api("DELETE", "/pin")).status).toBe(403);
|
||||
});
|
||||
});
|
||||
|
||||
describe("link pages", () => {
|
||||
it("only links to the user's own redirects", async () => {
|
||||
const { user } = setup();
|
||||
const alice = user("alice");
|
||||
const bob = user("bob");
|
||||
|
||||
const page = await (await alice.api("POST", "/pages", { kind: "linkpage", code: "me", title: "Alice" })).json();
|
||||
const own = await (await alice.api("POST", "/pages", { kind: "redirect", code: "gh", dest: "https://github.com" })).json();
|
||||
const foreign = await (await bob.api("POST", "/pages", { kind: "redirect", code: "gh", dest: "https://github.com" })).json();
|
||||
|
||||
expect((await alice.api("POST", `/pages/${page.id}/blocks`, { kind: "link", targetId: foreign.id, label: "x" })).status).toBe(400);
|
||||
expect((await alice.api("POST", `/pages/${page.id}/blocks`, { kind: "link", targetId: own.id, label: "GitHub" })).status).toBe(201);
|
||||
const blocks = await (await alice.api("POST", `/pages/${page.id}/blocks`, { kind: "text", markdown: "**hi**" })).json();
|
||||
expect(blocks.map((b: { kind: string }) => b.kind)).toEqual(["link", "text"]);
|
||||
|
||||
const reordered = await alice.api("PUT", `/pages/${page.id}/blocks/order`, { ids: [blocks[1].id, blocks[0].id] });
|
||||
expect((await reordered.json()).map((b: { kind: string }) => b.kind)).toEqual(["text", "link"]);
|
||||
expect((await alice.api("PUT", `/pages/${page.id}/blocks/order`, { ids: [blocks[0].id] })).status).toBe(400);
|
||||
});
|
||||
|
||||
it("renders markdown without raw HTML or script links", async () => {
|
||||
const { app, user } = setup();
|
||||
const alice = user("alice");
|
||||
const page = await (await alice.api("POST", "/pages", { kind: "linkpage", code: "me", title: "Alice" })).json();
|
||||
await alice.api("POST", `/pages/${page.id}/blocks`, {
|
||||
kind: "text",
|
||||
markdown: "**bold** <script>alert(1)</script> [x](javascript:alert(1))",
|
||||
});
|
||||
|
||||
const html = await (await app.request("/alice/me")).text();
|
||||
expect(html).toContain("<strong>bold</strong>");
|
||||
expect(html).not.toContain("<script>");
|
||||
expect(html).not.toContain('href="javascript:');
|
||||
});
|
||||
|
||||
it("removes blocks, stats and pin when a linked page is deleted", async () => {
|
||||
const { app, user } = setup();
|
||||
const admin = user("root", true);
|
||||
const page = await (await admin.api("POST", "/pages", { kind: "linkpage", namespace: "", code: "home", title: "Home" })).json();
|
||||
const link = await (await admin.api("POST", "/pages", { kind: "redirect", namespace: "", code: "gh", dest: "https://github.com" })).json();
|
||||
await admin.api("POST", `/pages/${page.id}/blocks`, { kind: "link", targetId: link.id, label: "GitHub" });
|
||||
await admin.api("PUT", "/pin", { pageId: link.id });
|
||||
await app.request("/gh");
|
||||
await flush();
|
||||
|
||||
expect((await admin.api("DELETE", `/pages/${link.id}`)).status).toBe(204);
|
||||
expect((await (await admin.api("GET", `/pages/${page.id}`)).json()).blocks).toEqual([]);
|
||||
expect((await app.request("/")).status).toBe(200);
|
||||
});
|
||||
});
|
||||
|
||||
describe("redirects and stats", () => {
|
||||
it("redirects with 302 and counts clicks and daily uniques", async () => {
|
||||
const { app, user } = setup();
|
||||
const alice = user("alice");
|
||||
const page = await (await alice.api("POST", "/pages", { kind: "redirect", code: "cv", dest: "https://example.com/cv" })).json();
|
||||
|
||||
const visit = (ip: string) =>
|
||||
app.request("/alice/cv", { headers: { "x-forwarded-for": ip, "user-agent": "test" } });
|
||||
const res = await visit("1.2.3.4");
|
||||
expect(res.status).toBe(302);
|
||||
expect(res.headers.get("location")).toBe("https://example.com/cv");
|
||||
await visit("1.2.3.99"); // same /24 and user agent → same visitor
|
||||
await visit("5.6.7.8");
|
||||
await flush();
|
||||
|
||||
const stats = await (await alice.api("GET", `/pages/${page.id}/stats?days=7`)).json();
|
||||
expect(stats.total).toBe(3);
|
||||
expect(stats.today).toBe(3);
|
||||
expect(stats.uniquesToday).toBe(2);
|
||||
expect(stats.series).toHaveLength(7);
|
||||
|
||||
expect((await alice.api("DELETE", `/pages/${page.id}/stats`)).status).toBe(204);
|
||||
expect((await (await alice.api("GET", `/pages/${page.id}/stats`)).json()).total).toBe(0);
|
||||
});
|
||||
|
||||
it("returns 404 for unknown links and the pinned page at the root", async () => {
|
||||
const { app, user } = setup();
|
||||
expect((await app.request("/nope")).status).toBe(404);
|
||||
expect((await app.request("/alice/nope")).status).toBe(404);
|
||||
|
||||
const admin = user("root", true);
|
||||
const page = await (await admin.api("POST", "/pages", { kind: "linkpage", namespace: "", code: "home", title: "Home" })).json();
|
||||
await admin.api("PUT", "/pin", { pageId: page.id });
|
||||
const root = await app.request("/");
|
||||
expect(root.status).toBe(302);
|
||||
expect(root.headers.get("location")).toBe("/home");
|
||||
});
|
||||
});
|
||||
|
||||
describe("api tokens", () => {
|
||||
it("creates, lists and revokes the caller's tokens only", async () => {
|
||||
const { app, user } = setup();
|
||||
const alice = user("alice");
|
||||
const bob = user("bob");
|
||||
|
||||
const created = await (await alice.api("POST", "/tokens", { name: "shortcuts" })).json();
|
||||
expect(created.token).toMatch(/^short_/);
|
||||
const viaToken = await app.request("/~/api/me", { headers: { authorization: `Bearer ${created.token}` } });
|
||||
expect((await viaToken.json()).username).toBe("alice");
|
||||
|
||||
expect((await bob.api("DELETE", `/tokens/${created.id}`)).status).toBe(404);
|
||||
expect((await alice.api("DELETE", `/tokens/${created.id}`)).status).toBe(204);
|
||||
const revoked = await app.request("/~/api/me", { headers: { authorization: `Bearer ${created.token}` } });
|
||||
expect(revoked.status).toBe(401);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,62 @@
|
||||
import { mkdtempSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
import { createApp } from "../src/server/app.js";
|
||||
import type { OidcClaims, OidcProvider } from "../src/server/auth/oidc.js";
|
||||
import { createApiToken, createSession, upsertUser } from "../src/server/auth/sessions.js";
|
||||
import type { Config } from "../src/server/config.js";
|
||||
import { openDb } from "../src/server/db/index.js";
|
||||
|
||||
export const BASE_URL = "https://short.test";
|
||||
|
||||
export function setup() {
|
||||
const config: Config = {
|
||||
baseUrl: BASE_URL,
|
||||
oidc: { issuer: "https://auth.test/", clientId: "id", clientSecret: "secret" },
|
||||
adminGroup: "short-admins",
|
||||
sessionSecret: "x".repeat(32),
|
||||
dataDir: mkdtempSync(path.join(tmpdir(), "short-test-")),
|
||||
timezone: "Europe/Berlin",
|
||||
trustProxy: true,
|
||||
logoDevToken: undefined,
|
||||
disableAttribution: false,
|
||||
retentionDays: 90,
|
||||
port: 0,
|
||||
};
|
||||
const db = openDb(":memory:");
|
||||
|
||||
// The fake provider returns whatever claims the test queued for the next login.
|
||||
let nextClaims: OidcClaims = { sub: "sub-x", username: "x", groups: [] };
|
||||
const oidc: OidcProvider = {
|
||||
authorizationUrl: async ({ state }) => new URL(`https://auth.test/authorize?state=${state}`),
|
||||
exchange: async () => nextClaims,
|
||||
};
|
||||
|
||||
const app = createApp({ db, config, oidc });
|
||||
|
||||
const user = (username: string, isAdmin = false) => {
|
||||
const actor = upsertUser(db, { sub: `sub-${username}`, username, groups: isAdmin ? ["short-admins"] : [] }, "short-admins");
|
||||
const token = createApiToken(db, actor.id, "test").token;
|
||||
const session = createSession(db, actor.id);
|
||||
const api = (method: string, url: string, body?: unknown) =>
|
||||
app.request(`/~/api${url}`, {
|
||||
method,
|
||||
headers: { authorization: `Bearer ${token}`, ...(body !== undefined && { "content-type": "application/json" }) },
|
||||
body: body === undefined ? undefined : JSON.stringify(body),
|
||||
});
|
||||
return { actor, token, session, api };
|
||||
};
|
||||
|
||||
return {
|
||||
app,
|
||||
db,
|
||||
config,
|
||||
user,
|
||||
setNextLogin: (claims: OidcClaims) => {
|
||||
nextClaims = claims;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
// Lets setImmediate callbacks (click tracking) run.
|
||||
export const flush = () => new Promise((resolve) => setImmediate(resolve));
|
||||
@@ -0,0 +1,40 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { openDb } from "../src/server/db/index.js";
|
||||
import { pages } from "../src/server/db/schema.js";
|
||||
import { anonymizeIp, dayOf, getStats, pruneClicks, recordClick } from "../src/server/lib/stats.js";
|
||||
|
||||
describe("stats", () => {
|
||||
it("anonymizes IPv4 and IPv6 addresses", () => {
|
||||
expect(anonymizeIp("1.2.3.4")).toBe("1.2.3.0");
|
||||
expect(anonymizeIp("::ffff:1.2.3.4")).toBe("1.2.3.0");
|
||||
expect(anonymizeIp("2001:db8:abcd:12::1")).toBe("2001:db8:abcd::");
|
||||
});
|
||||
|
||||
it("uses the configured timezone for days", () => {
|
||||
const lateEvening = new Date("2026-03-01T23:30:00Z");
|
||||
expect(dayOf(lateEvening, "UTC")).toBe("2026-03-01");
|
||||
expect(dayOf(lateEvening, "Europe/Berlin")).toBe("2026-03-02");
|
||||
});
|
||||
|
||||
it("counts the same visitor again on a new day and keeps totals after pruning", () => {
|
||||
const db = openDb(":memory:");
|
||||
const page = db.insert(pages).values({ namespace: "", code: "x", kind: "redirect", dest: "https://x.test" }).returning().get();
|
||||
|
||||
const day1 = new Date("2026-01-01T10:00:00Z");
|
||||
const day2 = new Date("2026-01-02T10:00:00Z");
|
||||
recordClick(db, "UTC", page.id, "1.2.3.4", "ua", day1);
|
||||
recordClick(db, "UTC", page.id, "1.2.3.4", "ua", day1);
|
||||
recordClick(db, "UTC", page.id, "1.2.3.4", "ua", day2);
|
||||
|
||||
const stats = getStats(db, "UTC", page.id, 7, day2);
|
||||
expect(stats.total).toBe(3);
|
||||
expect(stats.series.slice(-2)).toEqual([
|
||||
{ day: "2026-01-01", clicks: 2, uniques: 1 },
|
||||
{ day: "2026-01-02", clicks: 1, uniques: 1 },
|
||||
]);
|
||||
|
||||
const later = new Date("2026-06-01T00:00:00Z");
|
||||
expect(pruneClicks(db, 90, later)).toBe(3);
|
||||
expect(getStats(db, "UTC", page.id, 7, later).total).toBe(3);
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user