Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,21 @@ IP_HASH_SECRET=change_me_with_openssl_rand_hex_32
# Rate-Limit: Max. Link-Erstellungen pro IP / Stunde
RATE_LIMIT_CREATE_PER_HOUR=20

# ─── Spamschutz ───────────────────────────────────────────────────────
# Cloudflare Turnstile für das Formular. In Produktion PFLICHT: ohne beide
# Schlüssel kürzt das Formular dort nichts. Widget anlegen unter
# dash.cloudflare.com → Turnstile für s.msk-scripts.de. Für lokale Tests
# bestehen Cloudflares Testschlüssel immer:
# Site-Key 1x00000000000000000000AA, Secret 1x0000000000000000000000000000000AA
CAPTCHA_SITE_KEY=
CAPTCHA_SECRET_KEY=

# Links, die eine IP über das Formular in 24 Stunden kürzen darf
DAILY_LINKS_PER_IP=20

# Links, die ein API-Schlüssel pro Stunde kürzen darf (Schlüssel: scripts/api-key.sh)
API_KEY_CREATE_PER_HOUR=120

# ─── Short-Code Settings ──────────────────────────────────────────────
# Gültig sind 3 bis 16. Ungültige Werte fallen auf 7 zurück.
SHORTCODE_LENGTH=7
Expand Down
10 changes: 8 additions & 2 deletions .github/workflows/build.yml
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
# =============================================================================
# Build
# -----------------------------------------------------------------------------
# Compiles the app the same way the deploy workflow does, but on every pull
# request. Without it a change that breaks the build only shows up after the
# Type-checks, tests and compiles the app the same way the deploy workflow
# does, but on every pull request. Without it a change that breaks the build only shows up after the
# merge, when deploy.yml runs on main.
#
# No repository secrets are used on purpose. Pull requests from bots run in a
Expand Down Expand Up @@ -44,6 +44,12 @@ jobs:
- name: Install dependencies
run: npm ci

- name: Type-check
run: npm run type-check

- name: Test
run: npm test

- name: Build
env:
NEXT_PUBLIC_BASE_URL: http://localhost:3001
Expand Down
25 changes: 22 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ Part of the **MSK ecosystem** – open source, privacy-friendly, no tracking, no
| 🔌 **REST API** | Fully documented endpoints for automation |
| 🌍 **Bilingual UI** | German and English, switchable per user (cookie-based) |
| 🛡️ **Privacy-friendly** | IP hashing, no GeoIP, no third-party trackers, no analytics cookies |
| ⚡ **Rate limiting** | 20 links/hour per IP to prevent abuse |
| ⚡ **Spam protection** | Cloudflare Turnstile, daily limits per IP, phishing and shortener-chain checks, API keys for scripts |
| 🗑️ **Delete tokens** | Every short link comes with a one-time delete token |

---
Expand Down Expand Up @@ -111,14 +111,16 @@ This walks you through domain setup, MariaDB, Apache, Let's Encrypt SSL, systemd

## 📡 REST API

Every feature in the web UI is available through the REST API.
Reading is open. Shortening a link from a script needs an API key, issued by the operator on the
server (see [API keys](#-api-keys)); without one, `POST /api/links` only accepts the site's own form.

Full documentation: **[docu.msk-scripts.de/shortener](https://docu.msk-scripts.de/shortener)**

### Create a link

```bash
curl -X POST https://s.msk-scripts.de/api/links \
-H "Authorization: Bearer msks_…" \
-H "Content-Type: application/json" \
-d '{
"url": "https://msk-scripts.de",
Expand All @@ -143,7 +145,7 @@ curl -X POST https://s.msk-scripts.de/api/links \

| Method | Path | Description |
|---|---|---|
| `POST` | `/api/links` | Create a new short link |
| `POST` | `/api/links` | Create a new short link (API key required) |
| `GET` | `/api/links/:code` | Look up a link |
| `DELETE` | `/api/links/:code` | Delete a link (requires `deleteToken`) |
| `GET` | `/api/links/:code/stats` | Get click statistics for one link |
Expand All @@ -153,6 +155,21 @@ curl -X POST https://s.msk-scripts.de/api/links \

---

## 🔑 API keys

Only someone with a shell on the server and read access to the app's `.env` can manage keys. A key is
shown once when it is created; the database keeps only a scrypt hash of it.

```bash
/opt/msk-shortener/scripts/api-key.sh help # all commands
/opt/msk-shortener/scripts/api-key.sh list # id, prefix, label, last use, state
/opt/msk-shortener/scripts/api-key.sh create "<label>" # issue a key
/opt/msk-shortener/scripts/api-key.sh revoke <key|prefix|id> # block it, keep the row
/opt/msk-shortener/scripts/api-key.sh delete <key|prefix|id> # remove it
```

---

## ⚙️ Configuration

All configuration happens through environment variables. See [`.env.example`](.env.example) for the full list.
Expand Down Expand Up @@ -180,6 +197,8 @@ MSK Shortener is built with GDPR compliance and personal privacy in mind.
- **Password hashing** — bcrypt with cost factor 12
- **SSRF protection** — private IP ranges (RFC 1918, loopback, link-local) are rejected as targets
- **Rate limiting** — abuse protection per IP
- **Spam and phishing protection** — Cloudflare Turnstile on the form, a honeypot, a signed form timestamp,
daily limits per IP, and targets checked for phishing hostnames, IP hosts and other shorteners
- **Strict CSP headers** — defense in depth against XSS

A full **privacy policy** in German and English is available at [`/privacy`](https://s.msk-scripts.de/privacy) on every instance.
Expand Down
22 changes: 21 additions & 1 deletion app/api/links/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ import { z } from 'zod'
import { createLinkSchema } from '@/lib/validation'
import { createLink, LinkServiceError } from '@/lib/links'
import { getClientIp, hashIp, checkCreateRateLimit } from '@/lib/rateLimit'
import { bearerKey } from '@/lib/apiKeys'
import { guardCreate } from '@/lib/spamGuard'
import type { CreateLinkResponse, ApiError } from '@/types'

// ─── POST /api/links – Link erstellen ────────────────────────────────
Expand All @@ -12,12 +14,17 @@ export async function POST(request: NextRequest) {
const ipHash = hashIp(clientIp)

// ─── Rate-Limit prüfen ──────────────────────────────────────────
const rateLimit = checkCreateRateLimit(ipHash)
// Per address for the form; an API key has a limit of its own.
const viaKey = bearerKey(request.headers) !== null
const rateLimit = viaKey
? { allowed: true, remaining: 0, resetAt: Date.now() }
: checkCreateRateLimit(ipHash)
if (!rateLimit.allowed) {
const retryAfter = Math.ceil((rateLimit.resetAt - Date.now()) / 1000)
return NextResponse.json<ApiError>(
{
error: 'Zu viele Anfragen. Bitte später erneut versuchen.',
code: 'rate-limit',
},
{
status: 429,
Expand Down Expand Up @@ -56,6 +63,19 @@ export async function POST(request: NextRequest) {

const { url, customCode, password, expiresAt } = parsed.data

// ─── Spam guard ──────────────────────────────────────────────────
const raw = (typeof body === 'object' && body !== null ? body : {}) as Record<string, unknown>
const guard = await guardCreate({
headers: request.headers,
url,
proof: { website: raw.website, formStamp: raw.formStamp, turnstileToken: raw.turnstileToken },
ip: clientIp,
ipHash,
})
if (!guard.ok) {
return NextResponse.json<ApiError>({ error: guard.message, code: guard.code }, { status: guard.status })
}

// ─── Link erstellen ──────────────────────────────────────────────
const { link, deleteToken } = await createLink({
url,
Expand Down
23 changes: 20 additions & 3 deletions app/page.tsx
Original file line number Diff line number Diff line change
@@ -1,12 +1,21 @@
import Link from 'next/link'
import Script from 'next/script'
import { headers } from 'next/headers'
import { getTranslations } from 'next-intl/server'
import { CreateLinkForm } from '@/components/CreateLinkForm'
import { DeleteLinkButton } from '@/components/DeleteLinkButton'
import { Header } from '@/components/Header'
import { issueFormStamp } from '@/lib/formStamp'
import { turnstileSiteKey } from '@/lib/turnstile'

// Every render carries a fresh form stamp.
export const dynamic = 'force-dynamic'

export default async function HomePage() {
const t = await getTranslations('home')
const f = await getTranslations('footer')
const t = await getTranslations('home')
const f = await getTranslations('footer')
const nonce = (await headers()).get('x-nonce') ?? undefined
const siteKey = turnstileSiteKey()

return (
<div className="min-h-screen flex flex-col">
Expand All @@ -29,7 +38,7 @@ export default async function HomePage() {

{/* Form Card */}
<div className="bg-msk-surface/50 border border-msk-border rounded-2xl p-6 md:p-8 shadow-2xl backdrop-blur-sm">
<CreateLinkForm />
<CreateLinkForm siteKey={siteKey} formStamp={issueFormStamp()} />
</div>

{/* Sekundäre Aktionen */}
Expand Down Expand Up @@ -77,6 +86,14 @@ export default async function HomePage() {
</div>
</div>
</footer>

{siteKey && (
<Script
src="https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit"
strategy="afterInteractive"
nonce={nonce}
/>
)}
</div>
)
}
Expand Down
4 changes: 4 additions & 0 deletions app/privacy/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,10 @@ export default async function PrivacyPage() {
<p className="font-medium text-msk-text mb-1">{t('section6HostingTitle')}</p>
<p className="text-sm text-msk-muted">{t('section6HostingText')}</p>
</div>
<div className="bg-msk-surface/50 border border-msk-border rounded-lg p-4 mt-3">
<p className="font-medium text-msk-text mb-1">{t('section6TurnstileTitle')}</p>
<p className="text-sm text-msk-muted">{t('section6TurnstileText')}</p>
</div>
</Section>

{/* Section 7: Deine Rechte */}
Expand Down
24 changes: 20 additions & 4 deletions messages/de.json
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,21 @@
"expiresAtRemove": "Ablaufdatum entfernen",
"submit": "Link verkürzen",
"submitting": "Verkürze…",
"networkError": "Netzwerkfehler – bitte erneut versuchen"
"networkError": "Netzwerkfehler – bitte erneut versuchen",
"spam": {
"rejected": "Die Anfrage wurde abgelehnt. Bitte lade die Seite neu und versuche es noch einmal.",
"reload": "Die Seite ist abgelaufen. Bitte lade sie neu und versuche es noch einmal.",
"tooFast": "Das ging sehr schnell. Bitte warte einen Moment und sende noch einmal.",
"ownLink": "Kurz-Links dieses Dienstes können nicht noch einmal gekürzt werden.",
"shortener": "Links anderer URL-Shortener werden nicht angenommen. Bitte nutze die ursprüngliche Adresse.",
"blockedHost": "Diese Domain ist nicht erlaubt.",
"ipHost": "Links auf reine IP-Adressen werden nicht angenommen.",
"phishing": "Diese Adresse sieht nach einer Phishing-Seite aus und kann nicht gekürzt werden.",
"rateLimit": "Du hast in kurzer Zeit viele Links gekürzt. Bitte warte eine Weile und versuche es dann noch einmal.",
"dailyLimit": "Du hast das Tageslimit für neue Links erreicht. Bitte versuche es morgen wieder.",
"captcha": "Bitte schließe die Spam-Prüfung über dem Button ab.",
"captchaUnavailable": "Die Spam-Prüfung ist gerade nicht erreichbar. Bitte versuche es gleich noch einmal."
}
},
"linkResult": {
"success": "Link erstellt!",
Expand Down Expand Up @@ -160,7 +174,7 @@
"metaTitle": "Datenschutzerklärung",
"metaDescription": "Datenschutzerklärung für MSK Shortener.",
"title": "Datenschutzerklärung",
"lastUpdated": "Stand: Mai 2026",
"lastUpdated": "Stand: Oktober 2026",
"intro": "Wir nehmen den Schutz deiner persönlichen Daten sehr ernst. Diese Datenschutzerklärung informiert dich über Art, Umfang und Zweck der Verarbeitung personenbezogener Daten bei der Nutzung von MSK Shortener.",

"section1Title": "1. Verantwortlicher",
Expand Down Expand Up @@ -189,17 +203,19 @@
"section3NoTracking": "Es werden keine Tracking-Cookies, Analytics-Cookies oder Werbe-Cookies verwendet.",

"section4Title": "4. Rechtsgrundlagen der Verarbeitung",
"section4Text": "Die Verarbeitung deiner Daten erfolgt auf Grundlage von Art. 6 Abs. 1 lit. b DSGVO (Vertragserfüllung) sowie Art. 6 Abs. 1 lit. f DSGVO (berechtigte Interessen – Missbrauchsbekämpfung und Bereitstellung anonymer Statistiken).",
"section4Text": "Die Verarbeitung deiner Daten erfolgt auf Grundlage von Art. 6 Abs. 1 lit. b DSGVO (Vertragserfüllung) sowie Art. 6 Abs. 1 lit. f DSGVO (berechtigte Interessen – Missbrauchsbekämpfung einschließlich der Spam-Prüfung mit Cloudflare Turnstile und Bereitstellung anonymer Statistiken).",

"section5Title": "5. Speicherdauer",
"section5Links": "Kurz-Links werden gespeichert, bis sie entweder vom Ersteller über den Delete-Token gelöscht werden oder das optionale Ablaufdatum erreicht wird.",
"section5Clicks": "Klick-Daten enthalten kein IP-Merkmal und keine sonstige Kennung, mit der sich eine Person wiedererkennen ließe. Sie werden deshalb zeitlich unbefristet gespeichert.",
"section5Logs": "Server-Logs (Apache Access-Logs) werden ausschließlich zu Zwecken der technischen Bereitstellung und Sicherheit verarbeitet und gelöscht, sobald sie hierfür nicht mehr erforderlich sind.",

"section6Title": "6. Empfänger der Daten",
"section6Intro": "Deine Daten werden nicht an Dritte weitergegeben, mit folgender Ausnahme:",
"section6Intro": "Deine Daten werden nicht an Dritte weitergegeben, mit folgenden Ausnahmen:",
"section6HostingTitle": "Hosting-Provider",
"section6HostingText": "Diese Website wird auf Servern von Netcup GmbH (Daimlerstraße 25, 76185 Karlsruhe, Deutschland) betrieben. Mit Netcup besteht ein Auftragsverarbeitungsvertrag gemäß Art. 28 DSGVO.",
"section6TurnstileTitle": "Spam-Prüfung (Cloudflare Turnstile)",
"section6TurnstileText": "Das Formular zum Kürzen eines Links nutzt Cloudflare Turnstile, einen Dienst der Cloudflare, Inc. (101 Townsend St, San Francisco, CA 94107, USA), um Menschen von automatisierten Anfragen zu unterscheiden. Beim Aufruf der Startseite lädt dein Browser ein Skript von challenges.cloudflare.com, und Turnstile wertet technische Daten wie deine IP-Adresse und Eigenschaften deines Browsers aus. Wir erhalten nur das Ergebnis der Prüfung. Beim Aufruf eines Kurz-Links wird Turnstile nicht geladen. Rechtsgrundlage: Art. 6 Abs. 1 lit. f DSGVO, unser berechtigtes Interesse am Schutz des Dienstes vor Spam, Phishing und Missbrauch. Cloudflare ist unter dem EU-US Data Privacy Framework zertifiziert; zusätzlich gelten Standardvertragsklauseln. Datenschutzerklärung von Cloudflare: https://www.cloudflare.com/privacypolicy/",

"section7Title": "7. Deine Rechte",
"section7Intro": "Du hast jederzeit folgende Rechte:",
Expand Down
24 changes: 20 additions & 4 deletions messages/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,21 @@
"expiresAtRemove": "Remove expiry date",
"submit": "Shorten link",
"submitting": "Shortening…",
"networkError": "Network error – please try again"
"networkError": "Network error – please try again",
"spam": {
"rejected": "Your request was rejected. Please reload the page and try again.",
"reload": "This page has expired. Please reload it and try again.",
"tooFast": "That was quick. Please wait a moment and send again.",
"ownLink": "Short links of this service cannot be shortened again.",
"shortener": "Links of other URL shorteners are not accepted. Please use the original address.",
"blockedHost": "This domain is not allowed.",
"ipHost": "Links to bare IP addresses are not accepted.",
"phishing": "This address looks like a phishing page and cannot be shortened.",
"rateLimit": "You have shortened many links in a short time. Please wait a while and try again.",
"dailyLimit": "You have reached the daily limit for new links. Please try again tomorrow.",
"captcha": "Please complete the spam check above the button.",
"captchaUnavailable": "The spam check is unavailable right now. Please try again in a moment."
}
},
"linkResult": {
"success": "Link created!",
Expand Down Expand Up @@ -160,7 +174,7 @@
"metaTitle": "Privacy Policy",
"metaDescription": "Privacy policy for MSK Shortener.",
"title": "Privacy Policy",
"lastUpdated": "As of May 2026",
"lastUpdated": "As of October 2026",
"intro": "We take the protection of your personal data very seriously. This privacy policy informs you about the nature, scope and purpose of processing personal data when using MSK Shortener.",

"section1Title": "1. Data Controller",
Expand Down Expand Up @@ -189,17 +203,19 @@
"section3NoTracking": "No tracking cookies, analytics cookies or advertising cookies are used.",

"section4Title": "4. Legal basis for processing",
"section4Text": "Processing of your data is based on Art. 6 (1) (b) GDPR (contract performance) and Art. 6 (1) (f) GDPR (legitimate interests – abuse prevention and provision of anonymous statistics).",
"section4Text": "Processing of your data is based on Art. 6 (1) (b) GDPR (contract performance) and Art. 6 (1) (f) GDPR (legitimate interests – abuse prevention including the spam check with Cloudflare Turnstile, and provision of anonymous statistics).",

"section5Title": "5. Storage duration",
"section5Links": "Short links are stored until they are either deleted by the creator using the delete token or until the optional expiry date is reached.",
"section5Clicks": "Click data contains no IP identifier and no other marker that could recognize a person again. It is therefore stored indefinitely.",
"section5Logs": "Server logs (Apache access logs) are processed exclusively for the purposes of technical operation and security, and are deleted as soon as they are no longer required for these purposes.",

"section6Title": "6. Recipients of the data",
"section6Intro": "Your data is not shared with third parties, with the following exception:",
"section6Intro": "Your data is not shared with third parties, with the following exceptions:",
"section6HostingTitle": "Hosting provider",
"section6HostingText": "This website is operated on servers of Netcup GmbH (Daimlerstraße 25, 76185 Karlsruhe, Germany). A data processing agreement pursuant to Art. 28 GDPR exists with Netcup.",
"section6TurnstileTitle": "Spam check (Cloudflare Turnstile)",
"section6TurnstileText": "The form for shortening a link uses Cloudflare Turnstile, a service of Cloudflare, Inc. (101 Townsend St, San Francisco, CA 94107, USA), to tell people from automated requests. When the home page is opened, your browser loads a script from challenges.cloudflare.com, and Turnstile evaluates technical data such as your IP address and properties of your browser. We only receive the result of the check. Turnstile is not loaded when a short link is opened. Legal basis: Art. 6 (1) (f) GDPR, our legitimate interest in protecting the service against spam, phishing and abuse. Cloudflare is certified under the EU-US Data Privacy Framework; in addition, Standard Contractual Clauses apply. Cloudflare's privacy policy: https://www.cloudflare.com/privacypolicy/",

"section7Title": "7. Your rights",
"section7Intro": "You have the following rights at any time:",
Expand Down
Loading
Loading