updates
This commit is contained in:
15
README.md
15
README.md
@ -30,12 +30,12 @@ RewriteCond %{REQUEST_FILENAME} !-f
|
||||
RewriteRule ^ index.php [L]
|
||||
```
|
||||
|
||||
**nginx**:
|
||||
**nginx**: use the included [`nginx.conf`](nginx.conf), which goes inside your `http` block (e.g. in `sites-enabled`). It:
|
||||
|
||||
```nginx
|
||||
location ~ ^/(urls|last)\.txt$ { deny all; }
|
||||
location / { try_files $uri /index.php?$query_string; }
|
||||
```
|
||||
- sends every request to `index.php`, so nothing else in the directory (`urls.txt`, `.git`, …) is served directly
|
||||
- rate-limits each IP to 10 requests/second (burst 20) overall, and to 10/minute (burst 5) for creating links or trying passwords. Over-limit requests get `429`.
|
||||
|
||||
It expects an `upstream php { ... }` pointing at PHP-FPM. If nginx is behind another proxy, uncomment the `real_ip` lines. Otherwise every visitor shares the proxy's rate limit.
|
||||
|
||||
**Local development** (PHP's built-in server, using `index.php` as the router):
|
||||
|
||||
@ -54,8 +54,13 @@ php -S localhost:4000 index.php
|
||||
| `$max_url_length` | `100` | Longer URLs are rejected. |
|
||||
| `$charset` | (shuffled) | Characters used in keys. Don't change it once links exist. |
|
||||
| `$enable_test` | `false` | Turns on the key-generation test form. |
|
||||
| `$auth_cookie`, `$auth_cookie_days` | `shortener_auth`, `365` | Cookie that remembers a correct password, and how long it lasts. |
|
||||
| `$urls_file`, `$last_file` | `urls.txt`, `last.txt` | Where the data is stored. |
|
||||
|
||||
### Remembered password
|
||||
|
||||
If you tick **Remember me for a year** when entering the correct password, the app sets a cookie that lasts one year. While it's valid, the form doesn't ask for the password and a **Log out** link appears at the bottom of the page. Logging out clears the cookie. The cookie holds an HMAC token derived from the password, not the password itself, so changing `$password` signs everyone out. The cookie is only accepted on POST requests, so a link to `/?url=...` on another site can't create links using your cookie.
|
||||
|
||||
## API
|
||||
|
||||
Shorten a URL from the command line. The response is plain text:
|
||||
|
||||
95
index.php
95
index.php
@ -10,6 +10,8 @@ $max_url_length = 100; // urls longer than this are considered nefarious
|
||||
$allowed_domains = []; // list of allowed domains for URL shortening
|
||||
$password = 'change me!'; // password to shorten a URL, leave empty to disable password protection
|
||||
$enable_test = false; // enable the test function to output a series of incremented keys
|
||||
$auth_cookie = 'shortener_auth'; // name of the cookie that remembers a correct password
|
||||
$auth_cookie_days = 365; // how long the remembered password lasts
|
||||
|
||||
// Returns the contents of $last_file, or empty string if the file does not exist
|
||||
function get_last() {
|
||||
@ -146,6 +148,63 @@ $key = get_input('key');
|
||||
$test_start = get_input('test_start');
|
||||
$test_count = get_input('test_count');
|
||||
|
||||
// The auth cookie holds an HMAC of the password, never the password itself.
|
||||
// Changing $password invalidates every cookie already issued.
|
||||
function auth_token() {
|
||||
global $password;
|
||||
return hash_hmac('sha256', 'shortener-auth', $password);
|
||||
}
|
||||
|
||||
// True if the request carries a valid auth cookie
|
||||
function has_auth_cookie() {
|
||||
global $password, $auth_cookie;
|
||||
return $password !== ''
|
||||
&& isset($_COOKIE[$auth_cookie])
|
||||
&& is_string($_COOKIE[$auth_cookie])
|
||||
&& hash_equals(auth_token(), $_COOKIE[$auth_cookie]);
|
||||
}
|
||||
|
||||
// Sets the auth cookie, or clears it when $value is ''
|
||||
function set_auth_cookie($value) {
|
||||
global $auth_cookie, $auth_cookie_days;
|
||||
setcookie($auth_cookie, $value, [
|
||||
'expires' => $value === '' ? time() - 3600 : time() + $auth_cookie_days * 86400,
|
||||
'path' => '/',
|
||||
'secure' => !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off',
|
||||
'httponly' => true,
|
||||
'samesite' => 'Lax',
|
||||
]);
|
||||
}
|
||||
|
||||
// Checks the password or auth cookie. On a correct password with the
|
||||
// "remember" box ticked, sets the cookie. The cookie only counts for POST,
|
||||
// so a link like /?url=... on another site can't create short links with
|
||||
// a visitor's cookie.
|
||||
function is_authorized() {
|
||||
global $password, $input_password, $has_cookie;
|
||||
if ($password === '') {
|
||||
return true;
|
||||
}
|
||||
if (is_string($input_password) && hash_equals($password, $input_password)) {
|
||||
if (get_input('remember') === '1') {
|
||||
set_auth_cookie(auth_token());
|
||||
$has_cookie = true;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
return $has_cookie && $_SERVER['REQUEST_METHOD'] === 'POST';
|
||||
}
|
||||
|
||||
$has_cookie = has_auth_cookie();
|
||||
|
||||
// Log out: clear the cookie, then redirect so a refresh doesn't resubmit.
|
||||
// POST only, so another site can't log a visitor out with a plain link.
|
||||
if ($_SERVER['REQUEST_METHOD'] === 'POST' && get_input('logout') !== null) {
|
||||
set_auth_cookie('');
|
||||
header('Location: /', true, 303);
|
||||
exit;
|
||||
}
|
||||
|
||||
// Requests from the HTML form send format=html and get the result rendered
|
||||
// in the page; everything else (curl, scripts) gets the plain-text response.
|
||||
$from_form = get_input('format') === 'html';
|
||||
@ -156,8 +215,8 @@ $error = null;
|
||||
if ($url) {
|
||||
$status = 200;
|
||||
$parsed_url = parse_url($url);
|
||||
if ($password !== '' && $input_password !== $password) {
|
||||
// if a password is set, check it
|
||||
if (!is_authorized()) {
|
||||
// if a password is set, check it (or the auth cookie)
|
||||
$status = 401; // Unauthorized
|
||||
$error = "Unauthorized: Incorrect password.";
|
||||
} elseif (strlen($url) > $max_url_length) {
|
||||
@ -185,9 +244,9 @@ if ($url) {
|
||||
}
|
||||
|
||||
// If test parameters are provided, output a series of incremented keys
|
||||
if ($enable_test &&$test_start !== null && $test_count !== null) {
|
||||
// validate password
|
||||
if ($password !== '' && $input_password !== $password) {
|
||||
if ($enable_test && $test_start !== null && $test_count !== null) {
|
||||
// validate password (or the auth cookie)
|
||||
if (!is_authorized()) {
|
||||
http_response_code(401); // Unauthorized
|
||||
echo "Unauthorized: Incorrect password.\n";
|
||||
exit;
|
||||
@ -284,6 +343,19 @@ if ($key !== '' && !$from_form) {
|
||||
cursor: pointer;
|
||||
}
|
||||
.result a { display: inline-block; margin-top: 0.5rem; color: #15803d; word-break: break-all; }
|
||||
.remember { display: flex; align-items: center; gap: 0.5rem; font-weight: normal; margin: -0.25rem 0 1rem; }
|
||||
.remember input { width: 1.15rem; height: 1.15rem; margin: 0; accent-color: #2563eb; }
|
||||
.logout { margin: 1.5rem 0 0; text-align: center; }
|
||||
.logout button {
|
||||
padding: 0.5rem;
|
||||
font: inherit;
|
||||
font-size: 0.9rem;
|
||||
color: #6b7280;
|
||||
background: none;
|
||||
border: 0;
|
||||
text-decoration: underline;
|
||||
cursor: pointer;
|
||||
}
|
||||
.error { background: #fef2f2; border: 1px solid #f5b5b5; color: #b42318; font-weight: 600; }
|
||||
@media (max-width: 480px) {
|
||||
body { padding: 0.75rem; }
|
||||
@ -297,6 +369,7 @@ if ($key !== '' && !$from_form) {
|
||||
}
|
||||
.result { background: #0f2a1b; border-color: #1f5a37; }
|
||||
.result a { color: #6ee7a0; }
|
||||
.logout button { color: #9ca3af; }
|
||||
.error { background: #2d1515; border-color: #6b2a2a; color: #fca5a5; }
|
||||
}
|
||||
</style>
|
||||
@ -341,9 +414,10 @@ if ($key !== '' && !$from_form) {
|
||||
<input type="url" id="url" name="url" required placeholder="https://example.com/..."
|
||||
value="<?= $error !== null ? htmlspecialchars($url) : '' ?>"
|
||||
autocapitalize="off" autocorrect="off" spellcheck="false">
|
||||
<?php if ($password !== ''): ?>
|
||||
<?php if ($password !== '' && !$has_cookie): ?>
|
||||
<label for="password">Enter the password:</label>
|
||||
<input type="password" id="password" name="password" autocomplete="current-password" required>
|
||||
<label class="remember"><input type="checkbox" name="remember" value="1"<?= get_input('remember') === '1' ? ' checked' : '' ?>> Remember me for a year</label>
|
||||
<?php endif; ?>
|
||||
<input type="submit" value="Shorten">
|
||||
</form>
|
||||
@ -356,13 +430,20 @@ if ($key !== '' && !$from_form) {
|
||||
autocapitalize="off" autocorrect="off" spellcheck="false">
|
||||
<label for="test_count">How many keys to generate:</label>
|
||||
<input type="number" id="test_count" name="test_count" min="1" inputmode="numeric" required>
|
||||
<?php if ($password !== ''): ?>
|
||||
<?php if ($password !== '' && !$has_cookie): ?>
|
||||
<label for="test_password">Enter the password:</label>
|
||||
<input type="password" id="test_password" name="password" autocomplete="current-password" required>
|
||||
<label class="remember"><input type="checkbox" name="remember" value="1"<?= get_input('remember') === '1' ? ' checked' : '' ?>> Remember me for a year</label>
|
||||
<?php endif; ?>
|
||||
<input type="submit" value="Generate">
|
||||
</form>
|
||||
<?php endif; ?>
|
||||
|
||||
<?php if ($has_cookie): ?>
|
||||
<form method="post" action="/" class="logout">
|
||||
<button type="submit" name="logout" value="1">Log out</button>
|
||||
</form>
|
||||
<?php endif; ?>
|
||||
</main>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
70
nginx.conf
Normal file
70
nginx.conf
Normal file
@ -0,0 +1,70 @@
|
||||
## This file is included inside nginx's http block (e.g. from sites-enabled),
|
||||
## so the limit_req_zone and map directives below are valid here.
|
||||
|
||||
## Rate limiting (ngx_http_limit_req_module: built into nginx by default).
|
||||
## The zones key on the client IP. If nginx sits behind another proxy or
|
||||
## load balancer, every request appears to come from that proxy's IP and
|
||||
## all clients share one limit. In that case, uncomment the real_ip lines
|
||||
## in the server block below.
|
||||
|
||||
## General limit for every request, including short-link redirects.
|
||||
limit_req_zone $binary_remote_addr zone=shortener_all:10m rate=10r/s;
|
||||
|
||||
## Stricter limit for requests that can create a link or try a password:
|
||||
## any POST, or a GET carrying ?url= or ?password=. Plain GET/HEAD requests
|
||||
## get an empty key, which nginx doesn't count against this zone.
|
||||
map "$request_method:$arg_url$arg_password" $shortener_write_key {
|
||||
"~^(GET|HEAD):$" "";
|
||||
default $binary_remote_addr;
|
||||
}
|
||||
limit_req_zone $shortener_write_key zone=shortener_write:10m rate=10r/m;
|
||||
|
||||
server {
|
||||
listen 3337;
|
||||
## Your website name goes here.
|
||||
server_name r.bagaag.com;
|
||||
## Your only path reference.
|
||||
root /var/www/shortener;
|
||||
|
||||
## Behind a proxy: trust its X-Forwarded-For header so rate limits apply
|
||||
## per real client (needs ngx_http_realip_module, which distro packages
|
||||
## include). Set the proxy's address.
|
||||
# set_real_ip_from 127.0.0.1;
|
||||
# real_ip_header X-Forwarded-For;
|
||||
|
||||
limit_req_status 429;
|
||||
port_in_redirect off;
|
||||
|
||||
## Browsers ask for this automatically; answer quietly without logging.
|
||||
location = /favicon.ico {
|
||||
log_not_found off;
|
||||
access_log off;
|
||||
return 404;
|
||||
}
|
||||
|
||||
## The one static file served: tells crawlers to stay out.
|
||||
location = /robots.txt {
|
||||
access_log off;
|
||||
try_files /robots.txt =404;
|
||||
}
|
||||
|
||||
## Every other path is handled by index.php, so nothing else in the
|
||||
## directory (urls.txt, last.txt, .git, README.md, nginx.conf, ...) is
|
||||
## ever served directly. The original URI is preserved in REQUEST_URI,
|
||||
## which index.php uses to look up short-link keys.
|
||||
location / {
|
||||
rewrite ^ /index.php last;
|
||||
}
|
||||
|
||||
location = /index.php {
|
||||
limit_req zone=shortener_all burst=20 nodelay;
|
||||
limit_req zone=shortener_write burst=5 nodelay;
|
||||
|
||||
#NOTE: You should have "cgi.fix_pathinfo = 0;" in php.ini
|
||||
proxy_set_header Host r.bagaag.com;
|
||||
include fastcgi.conf;
|
||||
fastcgi_intercept_errors on;
|
||||
fastcgi_pass php;
|
||||
client_max_body_size 1M;
|
||||
}
|
||||
}
|
||||
2
robots.txt
Normal file
2
robots.txt
Normal file
@ -0,0 +1,2 @@
|
||||
User-agent: *
|
||||
Disallow: /
|
||||
Reference in New Issue
Block a user