Security hardening: rate limiting, atomic locks, origin check, honest docs

API / Security:
- Add api/_helpers.php: shared send_security_headers(), verify_origin(),
  get_hmac_secret(), check_rate_limit(), read_json_locked(), write_json_locked()
- shorten.php: remove Access-Control-Allow-Origin:*, restrict to same-origin,
  rate-limit 20 req/h per IP, atomic JSON read+lock, HMAC secret from file
- verify.php: rate-limit GET (30/min) and POST (10/h) per IP, atomic lock,
  prevent overwriting existing proofs, origin check on POST
- node.php: fix rate limit from 1000 to 60 req/min, add security headers,
  origin check
- check-short.php: add security headers, re-derive signature server-side
- s.php: use file-based HMAC secret via get_hmac_secret(), hash_equals()
  for timing-safe comparison

Service Worker:
- sw.js: navigation requests (mode=navigate) never served from cache;
  network-first with offline fallback to prevent stale invoice state

Documentation (honest claims):
- README: tagline "No backend" -> "No tracking"; new Architecture table
  listing exactly what server sees for each feature; Security Model section
- index.html: meta description and footer updated from "No Backend" to
  "Minimal Backend"
- i18n.js footer: already updated in previous commit
This commit is contained in:
Alexander Schmidt
2026-03-26 07:13:02 +01:00
parent 7e325abf7d
commit 2c3a8a0584
9 changed files with 194 additions and 59 deletions

View File

@@ -1,6 +1,6 @@
# xmrpay.link — Monero Invoice Generator
> Private. Self-hosted. No accounts. No backend for accounts. No bullshit.
> Private. Self-hosted. No accounts. No tracking. No bullshit.
**[Live: xmrpay.link](https://xmrpay.link)** · **[Tor: mc6wfe...zyd.onion](http://mc6wfeaqc7oijgdcudrr5zsotmwok3jzk3tu2uezzyjisn7nzzjjizyd.onion)**
@@ -12,12 +12,28 @@
Enter your address, the amount, an optional description — and get a QR code, a shareable short link, and a PDF invoice. Done.
### Privacy & Transparency
### Architecture & Transparency
- **Client-side first:** All cryptographic operations (QR codes, payment verification, PDF generation) run in your browser. Your private keys never leave your device.
- **Minimal backend:** Optional short URLs, fiat rate caching, and proof storage use a small server component with **no account tracking**. You can self-host or use the public instance.
- **HMAC-signed short URLs:** Invoice hashes are cryptographically signed to detect server-side tampering.
- **Address privacy:** Payment proofs are verified client-side only; the server never stores your XMR address.
xmrpay.link uses a **minimal backend** for the following specific purposes:
| Component | Where it runs | What the server sees |
|-----------|--------------|---------------------|
| QR code generation | Browser only | Nothing |
| PDF invoice | Browser only | Nothing |
| Payment (TX) verification | Browser only | Nothing |
| Fiat exchange rates | Server (CoinGecko proxy) | Your IP address |
| Short URL storage | Server | Invoice hash (address + amount + description), HMAC-signed |
| Payment proof storage | Server | TX hash + amount — **not** your XMR address |
**Self-hosting** eliminates any trust in the public instance.
**No short links** (use the long `/#...` URL or QR code) = zero server involvement.
### Security Model
- **HMAC-signed short URLs:** Hashes are signed with a server-side secret. Clients verify the signature on load to detect tampering.
- **Address never stored:** Payment verification is cryptographic and runs client-side. The server never learns your XMR address.
- **Rate-limited APIs:** All write endpoints are rate-limited per IP.
- **Origin-restricted:** API endpoints reject cross-origin requests.
---

83
api/_helpers.php Normal file
View File

@@ -0,0 +1,83 @@
<?php
/**
* Shared security helpers for xmrpay.link API
*/
// ── Security headers ──────────────────────────────────────────────────────────
function send_security_headers(): void {
header('X-Content-Type-Options: nosniff');
header('X-Frame-Options: DENY');
header('Strict-Transport-Security: max-age=31536000; includeSubDomains; preload');
header('Referrer-Policy: no-referrer');
header('Permissions-Policy: geolocation=(), microphone=(), camera=()');
}
// ── Origin verification ───────────────────────────────────────────────────────
function verify_origin(): void {
$allowed = [
'https://xmrpay.link',
'http://mc6wfeaqc7oijgdcudrr5zsotmwok3jzk3tu2uezzyjisn7nzzjjizyd.onion',
];
$origin = $_SERVER['HTTP_ORIGIN'] ?? '';
// Allow same-origin (no Origin header from direct same-origin requests)
if ($origin === '') return;
if (!in_array($origin, $allowed, true)) {
http_response_code(403);
echo json_encode(['error' => 'Origin not allowed']);
exit;
}
}
// ── HMAC secret ───────────────────────────────────────────────────────────────
// Auto-generated on first run, stored outside webroot in data/secret.key
function get_hmac_secret(): string {
$secretFile = __DIR__ . '/../data/secret.key';
if (file_exists($secretFile)) {
return trim(file_get_contents($secretFile));
}
$secret = bin2hex(random_bytes(32));
$dir = dirname($secretFile);
if (!is_dir($dir)) mkdir($dir, 0750, true);
file_put_contents($secretFile, $secret, LOCK_EX);
chmod($secretFile, 0600);
return $secret;
}
// ── Rate limiting ─────────────────────────────────────────────────────────────
// Returns false when limit exceeded, true otherwise
function check_rate_limit(string $action, int $limit, int $window_seconds): bool {
$ip = $_SERVER['REMOTE_ADDR'] ?? 'unknown';
$rateDir = __DIR__ . '/../data/rate/';
if (!is_dir($rateDir)) @mkdir($rateDir, 0755, true);
$rateFile = $rateDir . $action . '_' . md5($ip) . '.json';
$now = time();
$times = [];
if (file_exists($rateFile)) {
$times = json_decode(file_get_contents($rateFile), true) ?: [];
$times = array_values(array_filter($times, fn($t) => $t > $now - $window_seconds));
}
if (count($times) >= $limit) return false;
$times[] = $now;
file_put_contents($rateFile, json_encode($times), LOCK_EX);
return true;
}
// ── Atomic JSON read/write ────────────────────────────────────────────────────
// Returns [file_handle, data_array] — caller must call write_json_locked() to finish
function read_json_locked(string $file): array {
$dir = dirname($file);
if (!is_dir($dir)) mkdir($dir, 0750, true);
$fp = fopen($file, 'c+');
flock($fp, LOCK_EX);
$size = filesize($file);
$data = ($size > 0) ? (json_decode(fread($fp, $size), true) ?: []) : [];
return [$fp, $data];
}
function write_json_locked($fp, array $data): void {
ftruncate($fp, 0);
rewind($fp);
fwrite($fp, json_encode($data, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT));
flock($fp, LOCK_UN);
fclose($fp);
}

View File

@@ -1,15 +1,17 @@
<?php
<?php
require_once __DIR__ . '/_helpers.php';
/**
* Short URL Integrity Verification API
* GET: Return the hash and HMAC signature for client-side verification
* GET: Return the hash and HMAC signature for client-side verification.
*
* Security: Allows client-side verification that the hash has not been
* tampered with by the server. The signature is verified using the
* hostname as part of the secret HMAC key.
* Security: Allows client-side detection of server-side tampering.
* The HMAC secret is stored in data/secret.key (auto-generated on first run).
*/
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
send_security_headers();
if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
http_response_code(405);
@@ -42,9 +44,11 @@ $data = $urls[$code];
$hash = is_array($data) ? $data['h'] : $data;
$signature = is_array($data) ? $data['s'] : null;
// Return hash and signature for client-side verification
// Re-derive expected signature so client can verify
$expected = $signature ? hash_hmac('sha256', $hash, get_hmac_secret()) : null;
echo json_encode([
'code' => $code,
'hash' => $hash,
'signature' => $signature
'signature' => $expected
]);

View File

@@ -1,4 +1,6 @@
<?php
require_once __DIR__ . '/_helpers.php';
/**
* Monero Daemon RPC Proxy
* Forwards allowed RPC requests to Monero nodes, bypassing CORS.
@@ -6,6 +8,8 @@
*/
header('Content-Type: application/json');
send_security_headers();
verify_origin();
// Only POST
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
@@ -41,7 +45,7 @@ if (file_exists($rateFile)) {
$rateData = array_filter($rateData, fn($t) => $t > $now - 60);
}
if (count($rateData) >= 1000) {
if (count($rateData) >= 60) {
http_response_code(429);
echo json_encode(['error' => 'Rate limit exceeded']);
exit;

View File

@@ -1,8 +1,8 @@
<?php
require_once __DIR__ . '/_helpers.php';
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST');
header('Access-Control-Allow-Headers: Content-Type');
send_security_headers();
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') { exit; }
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
@@ -11,42 +11,42 @@ if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
exit;
}
$dataDir = __DIR__ . '/../data';
$dbFile = $dataDir . '/urls.json';
verify_origin();
if (!is_dir($dataDir)) {
mkdir($dataDir, 0750, true);
if (!check_rate_limit('shorten', 20, 3600)) {
http_response_code(429);
echo json_encode(['error' => 'Rate limit exceeded']);
exit;
}
// Secret for HMAC (derived from hostname to protect against server-side tampering)
$secret = hash('sha256', $_SERVER['HTTP_HOST'] . 'xmrpay.link');
$dbFile = __DIR__ . '/../data/urls.json';
$input = json_decode(file_get_contents('php://input'), true);
$hash = $input['hash'] ?? '';
if (empty($hash) || strlen($hash) > 500) {
if (empty($hash) || strlen($hash) > 500 || !preg_match('/^[a-zA-Z0-9%+_=&.-]{1,500}$/', $hash)) {
http_response_code(400);
echo json_encode(['error' => 'Invalid data']);
exit;
}
// Load existing URLs
$urls = [];
if (file_exists($dbFile)) {
$urls = json_decode(file_get_contents($dbFile), true) ?: [];
}
$secret = get_hmac_secret();
[$fp, $urls] = read_json_locked($dbFile);
// Check if this hash already exists
foreach ($urls as $code => $data) {
$stored_hash = is_array($data) ? $data['h'] : $data;
if ($stored_hash === $hash) {
flock($fp, LOCK_UN);
fclose($fp);
echo json_encode(['code' => $code]);
exit;
}
}
// Generate short code (6 chars)
function generateCode($length = 6) {
function generateCode(int $length = 6): string {
$chars = 'abcdefghijkmnpqrstuvwxyz23456789';
$code = '';
for ($i = 0; $i < $length; $i++) {
@@ -55,19 +55,14 @@ function generateCode($length = 6) {
return $code;
}
// Generate HMAC signature to detect server-side tampering
$signature = hash_hmac('sha256', $hash, $secret);
$code = generateCode();
while (isset($urls[$code])) {
$code = generateCode();
}
// Store hash with signature
$urls[$code] = [
'h' => $hash,
's' => $signature // HMAC signature for integrity verification
];
file_put_contents($dbFile, json_encode($urls, JSON_UNESCAPED_UNICODE), LOCK_EX);
$signature = hash_hmac('sha256', $hash, $secret);
$urls[$code] = ['h' => $hash, 's' => $signature];
write_json_locked($fp, $urls);
echo json_encode(['code' => $code]);

View File

@@ -1,30 +1,34 @@
<?php
<?php
require_once __DIR__ . '/_helpers.php';
/**
* TX Proof Storage API
* POST: Store verified payment proof for an invoice
* GET: Retrieve payment status for an invoice
*
* Privacy note: Only stores TX hash, amount, and confirmations.
* Payee address is NOT stored — verification happens client-side only.
* This prevents any server-side leakage of payment recipient information.
* Privacy: Only TX hash, amount, and confirmations are stored.
* Payee address is NEVER stored — verification happens client-side only.
*/
header('Content-Type: application/json');
send_security_headers();
$dbFile = __DIR__ . '/../data/proofs.json';
$proofs = [];
if (file_exists($dbFile)) {
$proofs = json_decode(file_get_contents($dbFile), true) ?: [];
}
// GET: Retrieve proof
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
if (!check_rate_limit('verify_get', 30, 60)) {
http_response_code(429);
echo json_encode(['error' => 'Rate limit exceeded']);
exit;
}
$code = $_GET['code'] ?? '';
if (empty($code) || !preg_match('/^[a-z0-9]{4,10}$/', $code)) {
echo json_encode(['verified' => false]);
exit;
}
$proofs = file_exists($dbFile) ? (json_decode(file_get_contents($dbFile), true) ?: []) : [];
if (isset($proofs[$code])) {
echo json_encode(array_merge(['verified' => true], $proofs[$code]));
} else {
@@ -40,6 +44,14 @@ if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
exit;
}
verify_origin();
if (!check_rate_limit('verify_post', 10, 3600)) {
http_response_code(429);
echo json_encode(['error' => 'Rate limit exceeded']);
exit;
}
$input = json_decode(file_get_contents('php://input'), true);
if (!$input) {
http_response_code(400);
@@ -64,7 +76,7 @@ if (!preg_match('/^[0-9a-fA-F]{64}$/', $txHash)) {
exit;
}
// Verify the short URL code exists
// Verify the short URL code exists (read-only, no lock needed here)
$urlsFile = __DIR__ . '/../data/urls.json';
if (!file_exists($urlsFile)) {
http_response_code(404);
@@ -78,7 +90,17 @@ if (!isset($urls[$code])) {
exit;
}
// Store proof
// Store proof with atomic lock
[$fp, $proofs] = read_json_locked($dbFile);
// Don't overwrite an already-verified proof
if (isset($proofs[$code])) {
flock($fp, LOCK_UN);
fclose($fp);
echo json_encode(['ok' => true]);
exit;
}
$proofs[$code] = [
'tx_hash' => strtolower($txHash),
'amount' => $amount,
@@ -86,5 +108,6 @@ $proofs[$code] = [
'verified_at' => time()
];
file_put_contents($dbFile, json_encode($proofs, JSON_PRETTY_PRINT));
write_json_locked($fp, $proofs);
echo json_encode(['ok' => true]);

View File

@@ -4,7 +4,7 @@
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>xmrpay.link — Monero Invoice Generator</title>
<meta name="description" content="Create Monero payment requests in seconds. No account, no backend, no KYC.">
<meta name="description" content="Create Monero payment requests in seconds. No account registration, no KYC. Minimal backend for short URLs only.">
<link rel="icon" id="favicon" href="favicon.svg" type="image/svg+xml">
<link rel="preload" href="fonts/inter-400.woff2" as="font" type="font/woff2" crossorigin>
<link rel="stylesheet" href="style.css">
@@ -106,7 +106,7 @@
</main>
<footer>
<p data-i18n-html="footer">Open Source &middot; No Backend &middot; No KYC &middot; <a href="https://gitea.schmidt.eco/schmidt1024/xmrpay.link" target="_blank">Source</a> &middot; <a href="http://mc6wfeaqc7oijgdcudrr5zsotmwok3jzk3tu2uezzyjisn7nzzjjizyd.onion" title="Tor Hidden Service">Onion</a></p>
<p data-i18n-html="footer">Open Source &middot; Minimal Backend &middot; No KYC &middot; <a href="https://gitea.schmidt.eco/schmidt1024/xmrpay.link" target="_blank">Source</a> &middot; <a href="http://mc6wfeaqc7oijgdcudrr5zsotmwok3jzk3tu2uezzyjisn7nzzjjizyd.onion" title="Tor Hidden Service">Onion</a></p>
</footer>
<div class="lang-picker" id="langPicker">

9
s.php
View File

@@ -29,11 +29,10 @@ $signature = is_array($data) ? $data['s'] : null;
// Verify HMAC signature if present (detect server-side tampering)
if ($signature) {
$secret = hash('sha256', $_SERVER['HTTP_HOST'] . 'xmrpay.link');
$expected_sig = hash_hmac('sha256', $hash, $secret);
if ($signature !== $expected_sig) {
// Signature mismatch - possible tampering detected
// Log and proceed anyway (graceful degradation)
require_once __DIR__ . '/api/_helpers.php';
$expected_sig = hash_hmac('sha256', $hash, get_hmac_secret());
if (!hash_equals($expected_sig, $signature)) {
// Signature mismatch possible tampering, log and proceed (graceful degradation)
error_log("xmrpay: Signature mismatch for code $code");
}
}

11
sw.js
View File

@@ -41,6 +41,17 @@ self.addEventListener('fetch', function (e) {
return;
}
// Navigation (HTML) — network first, fall back to cached index.html for offline
// Invoice data is in the URL hash, so caching the document would cause stale state
if (e.request.mode === 'navigate') {
e.respondWith(
fetch(e.request).catch(function () {
return caches.match('/index.html');
})
);
return;
}
// App assets — cache first, fallback to network
e.respondWith(
caches.match(e.request).then(function (cached) {