diff --git a/README.md b/README.md index 4ae41c6..88eade8 100644 --- a/README.md +++ b/README.md @@ -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**: `/` for admins, `//` for everyone else. Codes can be custom or random, and destinations can be edited later. +- **Short links**: `/` for admins, `//` 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. diff --git a/REQUIREMENTS.md b/REQUIREMENTS.md index 08b9760..4018159 100644 --- a/REQUIREMENTS.md +++ b/REQUIREMENTS.md @@ -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. diff --git a/src/server/lib/pages.ts b/src/server/lib/pages.ts index 4e4990b..7803065 100644 --- a/src/server/lib/pages.ts +++ b/src/server/lib/pages.ts @@ -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)) diff --git a/src/shared/validation.ts b/src/shared/validation.ts index 52a534c..e4f6ff5 100644 --- a/src/shared/validation.ts +++ b/src/shared/validation.ts @@ -62,6 +62,8 @@ export const createPageSchema = z.discriminatedUnion("kind", [ export type CreatePageInput = z.infer; 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(), diff --git a/src/web/screens/detail/SettingsTab.tsx b/src/web/screens/detail/SettingsTab.tsx index 5d336bd..adefdbc 100644 --- a/src/web/screens/detail/SettingsTab.tsx +++ b/src/web/screens/detail/SettingsTab.tsx @@ -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(); + 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: ( + + + {page.path} stops working immediately. Shared links, bookmarks and printed QR codes + that use it will show a "not found" page. + + + New address: {newPath} + + + ), + confirmLabel: "Change address", + danger: true, + }); + if (!ok) return; + setBusy(true); + setError(undefined); + try { + onChange(await api("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 ( + +
{ + e.preventDefault(); + void rename(); + }} + > + } /> + + + {(id) => ( + { + setCode(e.target.value); + setError(undefined); + }} + /> + )} + + {changed && ( + + {page.path} will stop working, including QR codes you've already shared or printed. + + )} + + + {changed && ( + + )} + + + +
+ ); +} + export function SettingsTab({ page, me, @@ -74,13 +161,7 @@ export function SettingsTab({
{page.kind === "redirect" && } - - - - {publicUrl(page.path)} - - - + {me.isAdmin && ( diff --git a/test/api.test.ts b/test/api.test.ts index 9e8eab0..ab1f15f 100644 --- a/test/api.test.ts +++ b/test/api.test.ts @@ -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");