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
16 changes: 16 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,22 @@ DB_NAME=msk_paste
# Generate with: openssl rand -hex 32
IP_HASH_SECRET=change_me_with_openssl_rand_hex_32

# ─── Spam protection ────────────────────────────────────────────────
# Cloudflare Turnstile for the create form. REQUIRED in production: without
# both keys the form cannot create pastes there. Create a widget at
# dash.cloudflare.com → Turnstile for paste.msk-scripts.de. For local tests
# Cloudflare's test keys always pass:
# site key 1x00000000000000000000AA, secret 1x0000000000000000000000000000000AA
CAPTCHA_SITE_KEY=
CAPTCHA_SECRET_KEY=

# Pastes and bytes one address may create through the form per 24 hours
DAILY_PASTES_PER_IP=20
DAILY_BYTES_PER_IP=5242880

# Pastes one API key may create per hour (keys: scripts/api-key.sh)
API_KEY_CREATE_PER_HOUR=120

# ─── Limits ──────────────────────────────────────────────────────────
# IMPORTANT: never put inline `# comments` next to a value — systemd's
# EnvironmentFile keeps them as part of the variable, which breaks parsing.
Expand Down
61 changes: 61 additions & 0 deletions .github/workflows/build.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
# =============================================================================
# Build
# -----------------------------------------------------------------------------
# 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
# context where secrets are empty, and a job that needs them fails there every
# time. The dummy values below are enough to compile: every route is rendered
# on demand, so nothing touches the database at build time.
# =============================================================================

name: Build

on:
push:
branches: [main]
pull_request:
branches: [main]

permissions:
contents: read

concurrency:
group: build-${{ github.ref }}
cancel-in-progress: true

jobs:
build:
name: Build
runs-on: ubuntu-latest

steps:
- name: Checkout repository
uses: actions/checkout@v6

- name: Setup Node.js
uses: actions/setup-node@v6
with:
node-version: '24'
cache: npm

- 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:3012
DB_HOST: build-dummy
DB_USER: build-dummy
DB_PASSWORD: build-dummy
DB_NAME: build-dummy
IP_HASH_SECRET: build-dummy-secret-do-not-use
run: npm run build
24 changes: 22 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,9 @@

## 🛡️ Privacy & Security

- **No tracking, no analytics, no third-party scripts** other than Google Fonts.
- **No tracking, no analytics.** The only third-party script is Cloudflare Turnstile on the create page.
- **Spam protection:** Turnstile, a honeypot, a signed form timestamp, daily limits per address and
content checks (encoded files, link spam, repeats). Scripts need an API key.
- **IPs are never stored.** Rate limiting uses HMAC-SHA-256(ip, secret).
- **Passwords** are stored as bcrypt hashes (cost 12) only.
- **Expired pastes are deleted**, not soft-deleted.
Expand Down Expand Up @@ -82,10 +84,14 @@ Details: [`deployment/README.md`](deployment/README.md).

## 📡 REST API

Reading is open. Creating a paste from a script needs an API key, issued by the operator on the
server (see [API keys](#-api-keys)); without one, `POST /api/pastes` only accepts the site's own form.

### `POST /api/pastes`

```bash
curl -X POST https://paste.msk-scripts.de/api/pastes \
-H 'Authorization: Bearer mskp_…' \
-H 'Content-Type: application/json' \
-d '{
"content": "console.log(\"hello world\")",
Expand All @@ -112,7 +118,7 @@ Response:

| Method | Path | Purpose |
|----------|-------------------------------|--------------------------------------|
| `POST` | `/api/pastes` | Create a paste |
| `POST` | `/api/pastes` | Create a paste (API key required) |
| `GET` | `/api/pastes/:id` | Fetch paste metadata + content |
| `POST` | `/api/pastes/:id/verify` | Verify password, returns content |
| `DELETE` | `/api/pastes/:id?token=…` | Delete a paste with its delete token |
Expand All @@ -129,6 +135,20 @@ npm run lint # ESLint
npm run type-check # TypeScript --noEmit
npm run migrate # Apply DB migrations
npm run cleanup # Delete expired pastes (run via cron)
npm run api-key -- help # Manage API keys (see below)
```

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

## 📜 License
Expand Down
28 changes: 24 additions & 4 deletions app/api/pastes/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,24 +3,30 @@ import { jsonError, parseJsonBody, zodToApiError, buildPasteUrl, buildRawUrl } f
import { createPasteSchema } from '@/lib/validation'
import { createPaste, PasteError } from '@/lib/paste'
import { checkCreateRateLimit, getClientIp, hashIp, hashIpBuffer } from '@/lib/rateLimit'
import { bearerKey } from '@/lib/apiKeys'
import { guardCreate, recordAccepted } from '@/lib/spamGuard'
import { ZodError } from 'zod'
import type { CreatePasteResponse } from '@/types'
import type { ApiError, CreatePasteResponse } from '@/types'

const MAX_PASTE_SIZE_BYTES = Number(process.env.MAX_PASTE_SIZE_BYTES ?? 1_048_576)

/**
* POST /api/pastes
* Create a new paste.
* Create a new paste: from the site's form, or from a script with an API key
* (see src/lib/spamGuard.ts).
*/
export async function POST(req: NextRequest) {
// ─── Rate limit ─────────────────────────────────────────────────
// Per address for the form; an API key has a limit of its own.
const ip = getClientIp(req.headers)
const ipHashed = hashIp(ip)
const limit = checkCreateRateLimit(ipHashed)
const limit = bearerKey(req.headers) === null
? checkCreateRateLimit(ipHashed)
: { allowed: true, resetAt: 0 }

if (!limit.allowed) {
return NextResponse.json(
{ error: 'Rate limit exceeded' },
{ error: 'Rate limit exceeded', code: 'rate-limit' },
{
status: 429,
headers: {
Expand All @@ -47,6 +53,19 @@ export async function POST(req: NextRequest) {
return jsonError('Content exceeds maximum size', 413)
}

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

// ─── Create ─────────────────────────────────────────────────────
try {
const created = await createPaste({
Expand All @@ -59,6 +78,7 @@ export async function POST(req: NextRequest) {
customId: validated.customId,
ipHash: hashIpBuffer(ip),
})
recordAccepted(validated.content)

const response: CreatePasteResponse = {
pasteId: created.pasteId,
Expand Down
21 changes: 19 additions & 2 deletions app/page.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,19 @@
import Script from 'next/script'
import { headers } from 'next/headers'
import { getTranslations } from 'next-intl/server'
import { Header } from '@/components/Header'
import { Footer } from '@/components/Footer'
import { CreatePasteForm } from '@/components/CreatePasteForm'
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 t = await getTranslations('home')
const nonce = (await headers()).get('x-nonce') ?? undefined
const siteKey = turnstileSiteKey()

return (
<main className="min-h-screen flex flex-col">
Expand All @@ -19,11 +28,19 @@ export default async function HomePage() {
<p className="text-msk-muted text-sm sm:text-base mt-3">{t('subtitle')}</p>
</div>

<CreatePasteForm />
<CreatePasteForm siteKey={siteKey} formStamp={issueFormStamp()} />
</div>
</div>

<Footer />

{siteKey && (
<Script
src="https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit"
strategy="afterInteractive"
nonce={nonce}
/>
)}
</main>
)
}
2 changes: 1 addition & 1 deletion app/privacy/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ export default async function PrivacyPage() {
<header>
<h1 className="font-heading text-3xl text-msk-text">{t('title')}</h1>
<p className="text-xs text-msk-muted mt-2 font-mono">
{t('lastUpdated', { date: '2026-05-13' })}
{t('lastUpdated', { date: '2026-10-30' })}
</p>
</header>

Expand Down
24 changes: 18 additions & 6 deletions messages/de.json
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,19 @@
"submit": "Paste erstellen",
"submitting": "Wird erstellt…",
"networkError": "Netzwerkfehler – bitte erneut versuchen",
"sizeUsed": "{bytes} / {max} Bytes"
"sizeUsed": "{bytes} / {max} Bytes",
"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.",
"links": "Diese Paste besteht fast nur aus Links und sieht nach Spam aus.",
"blob": "Kodierte Dateien und Binärdaten wie lange Base64-Blöcke können nicht eingefügt werden.",
"duplicate": "Derselbe Inhalt wurde vor Kurzem schon eingefügt.",
"rateLimit": "Du hast in kurzer Zeit viele Pastes erstellt. Bitte warte eine Weile und versuche es dann noch einmal.",
"dailyLimit": "Du hast das Tageslimit für neue Pastes 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."
}
},
"result": {
"title": "Paste erstellt",
Expand Down Expand Up @@ -167,19 +179,19 @@
},
"legalBasis": {
"title": "6. Rechtsgrundlagen der Verarbeitung",
"text": "Wir verarbeiten deine Daten auf folgenden Rechtsgrundlagen:\n• Art. 6 Abs. 1 lit. b DSGVO (Vertragserfüllung) – für die Bereitstellung des Paste-Dienstes\n• Art. 6 Abs. 1 lit. f DSGVO (berechtigtes Interesse) – für Rate-Limiting, Missbrauchsbekämpfung und den sicheren Betrieb der Website\n• Art. 6 Abs. 1 lit. c DSGVO (rechtliche Verpflichtung) – sofern gesetzliche Aufbewahrungs- oder Auskunftspflichten bestehen"
"text": "Wir verarbeiten deine Daten auf folgenden Rechtsgrundlagen:\n• Art. 6 Abs. 1 lit. b DSGVO (Vertragserfüllung) – für die Bereitstellung des Paste-Dienstes\n• Art. 6 Abs. 1 lit. f DSGVO (berechtigtes Interesse) – für Rate-Limiting, die Spam-Prüfung (Cloudflare Turnstile, Abschnitt 14), Missbrauchsbekämpfung und den sicheren Betrieb der Website\n• Art. 6 Abs. 1 lit. c DSGVO (rechtliche Verpflichtung) – sofern gesetzliche Aufbewahrungs- oder Auskunftspflichten bestehen"
},
"cookies": {
"title": "7. Cookies",
"text": "Wir setzen ein einziges Cookie: NEXT_LOCALE speichert deine Sprachauswahl (DE/EN) für 12 Monate. Es ist technisch notwendig und nicht zur Werbung oder Analyse gedacht.\n\nRechtsgrundlage: Art. 6 Abs. 1 lit. f DSGVO (berechtigtes Interesse an einer komfortablen Sprachauswahl)."
},
"tracking": {
"title": "8. Kein Tracking",
"text": "Es werden keine Analyse-Tools (Google Analytics, Plausible, Matomo o. ä.) verwendet. Es findet keine GeoIP-Auflösung statt. Es werden keine Drittanbieter-Skripte geladen."
"text": "Es werden keine Analyse-Tools (Google Analytics, Plausible, Matomo o. ä.) verwendet. Es findet keine GeoIP-Auflösung statt. Abgesehen von der Spam-Prüfung auf der Seite zum Erstellen einer Paste (Abschnitt 14) werden keine Drittanbieter-Skripte geladen."
},
"retention": {
"title": "9. Speicherdauer",
"text": "Pastes werden nach Ablauf des gewählten Zeitraums automatisch und unwiderruflich gelöscht. „Burn after read“-Pastes werden direkt nach dem ersten Aufruf entfernt. Du kannst eine Paste jederzeit mit deinem Lösch-Token vorzeitig löschen.\n\nIP-Hashes für Rate-Limiting werden nur kurzzeitig im Arbeitsspeicher gehalten und automatisch nach 1 Stunde verworfen.\n\nServer-Logs werden gelöscht, sobald sie zur technischen Bereitstellung und Sicherheit nicht mehr erforderlich sind."
"text": "Pastes werden nach Ablauf des gewählten Zeitraums automatisch und unwiderruflich gelöscht. „Burn after read“-Pastes werden direkt nach dem ersten Aufruf entfernt. Du kannst eine Paste jederzeit mit deinem Lösch-Token vorzeitig löschen.\n\nDer mit einer Paste gespeicherte IP-Hash (Abschnitt 5) wird zusammen mit der Paste gelöscht. Er dient dazu, die Zahl der Pastes je Adresse und Tag zu begrenzen. Für das stündliche Rate-Limit werden IP-Hashes außerdem kurz im Arbeitsspeicher gehalten und nach 1 Stunde verworfen. Um wiederholten Spam zu erkennen, wird ein Hash des eingefügten Inhalts 24 Stunden im Arbeitsspeicher gehalten; er bezieht sich nicht auf deine Person.\n\nServer-Logs werden gelöscht, sobald sie zur technischen Bereitstellung und Sicherheit nicht mehr erforderlich sind."
},
"rights": {
"title": "10. Deine Rechte",
Expand All @@ -198,8 +210,8 @@
"text": "Passwörter werden ausschließlich als bcrypt-Hash (Cost-Faktor 12) gespeichert. Die Verbindung erfolgt verschlüsselt via HTTPS (TLS). Der Server ist mit aktuellen Sicherheits-Updates versehen, eine Firewall ist aktiv."
},
"thirdParty": {
"title": "14. Schriftarten & Drittanbieter",
"text": "Schriftarten (Inter, JetBrains Mono) werden über das in Next.js integrierte Font-System (next/font) bereits zur Build-Zeit lokal in den Build der Anwendung aufgenommen und anschließend ausschließlich vom eigenen Server ausgeliefert. Zur Laufzeit findet keine Verbindung zu Servern Dritter (insbesondere Google Fonts) statt.\n\nEs werden keine weiteren externen Skripte, Schriften oder Tracking-Dienste geladen."
"title": "14. Schriftarten, Spam-Prüfung & Drittanbieter",
"text": "Schriftarten (Syne, DM Sans, JetBrains Mono) werden über das in Next.js integrierte Font-System (next/font) bereits zur Build-Zeit in die Anwendung aufgenommen und ausschließlich vom eigenen Server ausgeliefert. Zur Laufzeit findet keine Verbindung zu Schriftanbietern statt.\n\nSpam-Prüfung: Die Seite zum Erstellen einer Paste 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 dieser Seite 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. Auf Seiten, die eine Paste anzeigen, wird Turnstile nicht geladen. Rechtsgrundlage: Art. 6 Abs. 1 lit. f DSGVO, unser berechtigtes Interesse am Schutz des Dienstes vor Spam 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/\n\nEs werden keine weiteren externen Skripte, Schriften oder Tracking-Dienste geladen."
},
"contact": {
"title": "15. Kontakt",
Expand Down
Loading
Loading