Merge pull request #7 from traberph/v2

Allow renaming shortcodes
This commit is contained in:
traberph
2026-10-14 16:04:42 +02:00
committed by GitHub
6 changed files with 131 additions and 13 deletions
+1 -1
View File
@@ -2,7 +2,7 @@
A small self-hosted URL shortener and link-page tool for a handful of people, with login through Authentik (OIDC).
- **Short links**: `/<code>` for admins, `/<username>/<code>` for everyone else. Codes can be custom or random, and destinations can be edited later.
- **Short links**: `/<code>` for admins, `/<username>/<code>` for everyone else. Codes can be custom or random, and both codes 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.
+2 -1
View File
@@ -19,7 +19,8 @@ authenticated against an existing Authentik instance.
## 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.
- **R9** Destinations and shortcodes can be edited. Renaming a shortcode breaks the old URL, so the UI asks for
confirmation. 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.
+3
View File
@@ -106,6 +106,9 @@ export function updatePage(db: Db, actor: Actor, id: number, input: UpdatePageIn
if ((input.title !== undefined || input.theme !== undefined) && page.kind !== "linkpage") {
throw new HttpError(400, "Only link pages have a title and theme");
}
if (input.code !== undefined && input.code !== page.code && codeTaken(db, page.namespace, input.code)) {
throw new HttpError(409, "Shortcode is not available", { code: ["Already in use or reserved"] });
}
db.update(pages)
.set({ ...input, updatedAt: new Date() })
.where(eq(pages.id, id))
+2
View File
@@ -62,6 +62,8 @@ export const createPageSchema = z.discriminatedUnion("kind", [
export type CreatePageInput = z.infer<typeof createPageSchema>;
export const updatePageSchema = z.object({
// Renaming breaks the old URL; the admin UI asks for confirmation first.
code: codeSchema.optional(),
dest: destSchema.optional(),
title: titleSchema.optional(),
theme: themeSchema.optional(),
+92 -11
View File
@@ -1,13 +1,13 @@
import { useState } from "react";
import { Pin, PinOff, Trash2 } from "lucide-react";
import type { Me, PageDetail } from "../../../shared/api-types.js";
import { api } from "../../api.js";
import { api, ApiRequestError, errorMessage } from "../../api.js";
import { Button } from "../../components/ui/button.js";
import { useConfirm } from "../../components/ui/dialog.js";
import { Field, Input } from "../../components/ui/form.js";
import { Field, Input, PrefixInput } from "../../components/ui/form.js";
import { CopyButton, publicUrl } from "../../components/ui/misc.js";
import { Card, CardBody, CardFooter, CardHeader } from "../../components/ui/surface.js";
import { useAction } from "../../components/ui/toast.js";
import { Alert, Card, CardBody, CardFooter, CardHeader } from "../../components/ui/surface.js";
import { useAction, useToast } from "../../components/ui/toast.js";
import { listPath, navigate } from "../../router.js";
function DestinationCard({ page, onChange }: { page: PageDetail; onChange: (page: PageDetail) => void }) {
@@ -35,6 +35,93 @@ function DestinationCard({ page, onChange }: { page: PageDetail; onChange: (page
);
}
function AddressCard({ page, onChange }: { page: PageDetail; onChange: (page: PageDetail) => void }) {
const [code, setCode] = useState(page.code);
const [error, setError] = useState<string | undefined>();
const [busy, setBusy] = useState(false);
const confirm = useConfirm();
const toast = useToast();
const prefix = page.namespace ? `/${page.namespace}/` : "/";
const newPath = `${prefix}${code.trim()}`;
const changed = code.trim() !== page.code;
const rename = async () => {
const ok = await confirm({
title: "Change the address?",
description: (
<span className="flex flex-col gap-3">
<span>
<span className="font-mono">{page.path}</span> stops working immediately. Shared links, bookmarks and printed QR codes
that use it will show a "not found" page.
</span>
<span>
New address: <span className="font-mono text-fg">{newPath}</span>
</span>
</span>
),
confirmLabel: "Change address",
danger: true,
});
if (!ok) return;
setBusy(true);
setError(undefined);
try {
onChange(await api<PageDetail>("PATCH", `/pages/${page.id}`, { code: code.trim() }));
toast(`Address changed to ${newPath}`);
} catch (err) {
setError(err instanceof ApiRequestError && err.issues?.code ? err.issues.code.join(", ") : errorMessage(err));
} finally {
setBusy(false);
}
};
return (
<Card>
<form
onSubmit={(e) => {
e.preventDefault();
void rename();
}}
>
<CardHeader title="Address" description="The public URL of this page." actions={<CopyButton value={publicUrl(page.path)} label="Copy" />} />
<CardBody className="flex flex-col gap-4">
<Field label="Shortcode" error={error}>
{(id) => (
<PrefixInput
id={id}
prefix={prefix}
required
pattern="[A-Za-z0-9][A-Za-z0-9_\-]{0,63}"
value={code}
onChange={(e) => {
setCode(e.target.value);
setError(undefined);
}}
/>
)}
</Field>
{changed && (
<Alert title="Changing the shortcode breaks the current URL">
<span className="font-mono">{page.path}</span> will stop working, including QR codes you've already shared or printed.
</Alert>
)}
</CardBody>
<CardFooter>
{changed && (
<Button variant="secondary" onClick={() => setCode(page.code)}>
Cancel
</Button>
)}
<Button type="submit" variant={changed ? "danger" : "primary"} loading={busy} disabled={!changed || !code.trim()}>
Change address
</Button>
</CardFooter>
</form>
</Card>
);
}
export function SettingsTab({
page,
me,
@@ -74,13 +161,7 @@ export function SettingsTab({
<div className="flex max-w-3xl flex-col gap-6">
{page.kind === "redirect" && <DestinationCard page={page} onChange={onChange} />}
<Card>
<CardHeader title="Address" description="Shortcodes can't be changed. Create a new one if you need a different address." />
<CardBody className="flex items-center gap-2">
<code className="flex-1 truncate rounded-lg bg-surface-2 px-3 py-2 font-mono text-sm">{publicUrl(page.path)}</code>
<CopyButton value={publicUrl(page.path)} label="Copy" />
</CardBody>
</Card>
<AddressCard key={page.code} page={page} onChange={onChange} />
{me.isAdmin && (
<Card>
+31
View File
@@ -134,6 +134,37 @@ describe("namespaces and permissions", () => {
expect(await (await admin.api("GET", "/conflicts")).json()).toEqual([{ username: "carol", pageId: expect.any(Number) }]);
});
it("renames shortcodes and keeps stats and link buttons", async () => {
const { app, user } = setup();
user("bob");
const alice = user("alice");
const admin = user("root", true);
const link = await (await alice.api("POST", "/pages", { kind: "redirect", code: "old", dest: "https://a.test" })).json();
await alice.api("POST", "/pages", { kind: "redirect", code: "taken", dest: "https://b.test" });
const page = await (await alice.api("POST", "/pages", { kind: "linkpage", code: "me", title: "Alice" })).json();
await alice.api("POST", `/pages/${page.id}/blocks`, { kind: "link", targetId: link.id, label: "A" });
await app.request("/alice/old");
await flush();
expect((await alice.api("PATCH", `/pages/${link.id}`, { code: "taken" })).status).toBe(409);
expect((await alice.api("PATCH", `/pages/${link.id}`, { code: "bad code" })).status).toBe(400);
expect((await user("eve").api("PATCH", `/pages/${link.id}`, { code: "x" })).status).toBe(404);
const renamed = await alice.api("PATCH", `/pages/${link.id}`, { code: "new" });
expect((await renamed.json()).path).toBe("/alice/new");
expect((await app.request("/alice/old")).status).toBe(404);
expect((await app.request("/alice/new")).headers.get("location")).toBe("https://a.test");
expect((await (await alice.api("GET", `/pages/${link.id}/stats`)).json()).total).toBe(1);
expect((await (await alice.api("GET", `/pages/${page.id}`)).json()).blocks[0].target.path).toBe("/alice/new");
// Root renames follow the same reserved-code and username rules as creating.
const root = await (await admin.api("POST", "/pages", { kind: "redirect", namespace: "", code: "r", dest: "https://r.test" })).json();
expect((await admin.api("PATCH", `/pages/${root.id}`, { code: "api" })).status).toBe(409);
expect((await admin.api("PATCH", `/pages/${root.id}`, { code: "bob" })).status).toBe(409);
expect((await admin.api("PATCH", `/pages/${root.id}`, { code: "r" })).status).toBe(200);
});
it("restricts admin-only endpoints", async () => {
const { user } = setup();
const alice = user("alice");