mirror of
https://github.com/mileswolfallen2/miles-web.git
synced 2026-12-03 15:43:25 +00:00
update
This commit is contained in:
1 parent
c250653961
commit
f26fdd9d07
18 files changed
+493
-83
No files matched your search
+13
-10
@@ -15,13 +15,16 @@ NODE_ENV=production
|
|||||||
HOST=127.0.0.1
|
HOST=127.0.0.1
|
||||||
PORT=8787
|
PORT=8787
|
||||||
|
|
||||||
# The canonical browser origin. Also used as the default CORS origin.
|
# The public API origin (the Cloudflare Tunnel hostname for this Node app).
|
||||||
PUBLIC_ORIGIN=https://milesallen.site
|
# The static site can stay on https://milesallen.site and call this origin.
|
||||||
|
PUBLIC_ORIGIN=https://api.milesallen.site
|
||||||
|
|
||||||
# Extra cross-origin origins, comma-separated. https://milesallen.site and
|
# Browser origins allowed to call the API. https://milesallen.site,
|
||||||
# https://www.milesallen.site are always allowed. Same-origin requests from the
|
# https://www.milesallen.site, and https://api.milesallen.site are always
|
||||||
# browser's current host are also accepted.
|
# allowed; same-origin requests from the current host are accepted too.
|
||||||
# ALLOWED_ORIGINS=https://milesallen.site,https://www.milesallen.site
|
# api.milesallen.site and milesallen.site are same-site, so the vault cookie
|
||||||
|
# keeps SameSite=Strict and still works across the two hostnames.
|
||||||
|
ALLOWED_ORIGINS=https://milesallen.site,https://www.milesallen.site
|
||||||
|
|
||||||
# Set true only when a trusted reverse proxy (Caddy, Cloudflare Tunnel) sets
|
# Set true only when a trusted reverse proxy (Caddy, Cloudflare Tunnel) sets
|
||||||
# CF-Connecting-IP or X-Forwarded-For. Never enable this on a direct public
|
# CF-Connecting-IP or X-Forwarded-For. Never enable this on a direct public
|
||||||
@@ -29,7 +32,7 @@ PUBLIC_ORIGIN=https://milesallen.site
|
|||||||
TRUST_PROXY=true
|
TRUST_PROXY=true
|
||||||
|
|
||||||
# Where the static site lives. Defaults to the process working directory.
|
# Where the static site lives. Defaults to the process working directory.
|
||||||
# SITE_ROOT=/opt/miles-web
|
# SITE_ROOT=/opt/websites/miles-web
|
||||||
|
|
||||||
# SQLite file. Keep it outside the web root if you serve files with another
|
# SQLite file. Keep it outside the web root if you serve files with another
|
||||||
# web server. The Node app already blocks /data and /server.
|
# web server. The Node app already blocks /data and /server.
|
||||||
@@ -129,6 +132,6 @@ LOG_LEVEL=info
|
|||||||
# ---------------------------------------------------------------------------
|
# ---------------------------------------------------------------------------
|
||||||
# Optional registry path overrides
|
# Optional registry path overrides
|
||||||
# ---------------------------------------------------------------------------
|
# ---------------------------------------------------------------------------
|
||||||
# PROJECTS_CONFIG_PATH=/opt/miles-web/server/config/projects.json
|
# PROJECTS_CONFIG_PATH=/opt/websites/miles-web/server/config/projects.json
|
||||||
# SERVICES_CONFIG_PATH=/opt/miles-web/server/config/services.json
|
# SERVICES_CONFIG_PATH=/opt/websites/miles-web/server/config/services.json
|
||||||
# SERVERS_CONFIG_PATH=/opt/miles-web/server/config/servers.json
|
# SERVERS_CONFIG_PATH=/opt/websites/miles-web/server/config/servers.json
|
||||||
@@ -10,6 +10,20 @@ The backend is plain JavaScript on Node.js with two native dependencies
|
|||||||
(`better-sqlite3` and `argon2`); there is no Docker, Go, Rust, Python, or
|
(`better-sqlite3` and `argon2`); there is no Docker, Go, Rust, Python, or
|
||||||
frontend framework involved.
|
frontend framework involved.
|
||||||
|
|
||||||
|
### Split-origin deployment
|
||||||
|
|
||||||
|
The static site can stay on `https://milesallen.site` while the Node backend is
|
||||||
|
exposed on `https://api.milesallen.site` through a Cloudflare Tunnel. Both
|
||||||
|
hostnames are under `milesallen.site`, so the vault cookie keeps
|
||||||
|
`SameSite=Strict` and still works across them. `site-config.js` holds the
|
||||||
|
API hostname; the dashboard, vault lock page, and analytics beacon use it
|
||||||
|
and fall back to same-origin when it is empty (local development).
|
||||||
|
|
||||||
|
The server's CORS allowlist includes `https://milesallen.site`,
|
||||||
|
`https://www.milesallen.site`, and `https://api.milesallen.site`. The JSON API
|
||||||
|
and the vault/game pages are served by the Node process; the main static site
|
||||||
|
can remain on its current host.
|
||||||
|
|
||||||
## What is included
|
## What is included
|
||||||
|
|
||||||
| Area | What it does |
|
| Area | What it does |
|
||||||
@@ -86,6 +100,7 @@ Do not reuse a development passphrase in production, and never commit `.env`.
|
|||||||
| `npm start` | Start the server without watch mode |
|
| `npm start` | Start the server without watch mode |
|
||||||
| `npm test` | Run the full automated test suite with `node:test` |
|
| `npm test` | Run the full automated test suite with `node:test` |
|
||||||
| `npm run db:migrate` | Apply migrations and seed the project/service/server registries |
|
| `npm run db:migrate` | Apply migrations and seed the project/service/server registries |
|
||||||
|
| `npm run preflight` | Validate `.env`, paths, permissions, native modules, and `ping` before deployment |
|
||||||
| `npm run hash-password -- "passphrase"` | Print an Argon2id hash to put in `.env` |
|
| `npm run hash-password -- "passphrase"` | Print an Argon2id hash to put in `.env` |
|
||||||
| `npm run smoke` | Check a running local server's APIs and vault gates |
|
| `npm run smoke` | Check a running local server's APIs and vault gates |
|
||||||
|
|
||||||
@@ -107,6 +122,16 @@ URLs/enabled flags and server name/IP/enabled flags without editing code. The
|
|||||||
registries are seeded into SQLite on startup and can be re-seeded by running
|
registries are seeded into SQLite on startup and can be re-seeded by running
|
||||||
`npm run db:migrate`.
|
`npm run db:migrate`.
|
||||||
|
|
||||||
|
### API hostname
|
||||||
|
|
||||||
|
`site-config.js` contains the browser-facing API base. In production it maps
|
||||||
|
`https://milesallen.site` and `https://www.milesallen.site` to
|
||||||
|
`https://api.milesallen.site`. Override it per deployment by setting
|
||||||
|
`window.MILES_API_BASE` before the script runs, or by adding a
|
||||||
|
`<meta name="miles-api-base" content="https://api.example.com">` tag. When the
|
||||||
|
value is empty, all API calls stay same-origin, which is what local development
|
||||||
|
uses.
|
||||||
|
|
||||||
### Adding a project
|
### Adding a project
|
||||||
|
|
||||||
Add an object to `server/config/projects.json`:
|
Add an object to `server/config/projects.json`:
|
||||||
@@ -172,8 +197,9 @@ and refuses logins; it does not fall back to a default password.
|
|||||||
- GitHub and FEDL calls happen on the server. The GitHub token is never included
|
- GitHub and FEDL calls happen on the server. The GitHub token is never included
|
||||||
in API responses or frontend code.
|
in API responses or frontend code.
|
||||||
- CORS is an explicit allowlist: `https://milesallen.site`,
|
- CORS is an explicit allowlist: `https://milesallen.site`,
|
||||||
`https://www.milesallen.site`, local development origins, and same-origin
|
`https://www.milesallen.site`, `https://api.milesallen.site`, local
|
||||||
requests. Unknown cross-origin API requests are rejected.
|
development origins, and same-origin requests. Unknown cross-origin API
|
||||||
|
requests are rejected.
|
||||||
- Request bodies have a hard size limit, API and login routes are rate limited,
|
- Request bodies have a hard size limit, API and login routes are rate limited,
|
||||||
request timeouts are enforced, and errors returned to clients do not expose
|
request timeouts are enforced, and errors returned to clients do not expose
|
||||||
stack traces or secrets.
|
stack traces or secrets.
|
||||||
@@ -209,6 +235,7 @@ vault/game redirects, and that an analytics hit is accepted.
|
|||||||
|
|
||||||
```text
|
```text
|
||||||
analytics.js Privacy-friendly pageview beacon
|
analytics.js Privacy-friendly pageview beacon
|
||||||
|
site-config.js Browser-facing API hostname for split-origin
|
||||||
dashboard.html/.css/.js API-driven developer dashboard
|
dashboard.html/.css/.js API-driven developer dashboard
|
||||||
moon-vault.html Public vault lock screen
|
moon-vault.html Public vault lock screen
|
||||||
server/
|
server/
|
||||||
@@ -220,7 +247,7 @@ server/
|
|||||||
lib/ Env, cookies, crypto, errors, HTTP, logging, limits
|
lib/ Env, cookies, crypto, errors, HTTP, logging, limits
|
||||||
services/ Ping, HTTP checks, status, monitor, GitHub, FEDL,
|
services/ Ping, HTTP checks, status, monitor, GitHub, FEDL,
|
||||||
analytics, vault
|
analytics, vault
|
||||||
scripts/ migrate, hash-password, smoke
|
scripts/ migrate, preflight, hash-password, smoke
|
||||||
views/vault.html Authenticated vault content
|
views/vault.html Authenticated vault content
|
||||||
migrations/001_init.sql Schema and indexes
|
migrations/001_init.sql Schema and indexes
|
||||||
tests/ node:test suite and isolated fixtures
|
tests/ node:test suite and isolated fixtures
|
||||||
|
|||||||
+14
-1
@@ -23,8 +23,21 @@
|
|||||||
];
|
];
|
||||||
if (skip.some(function (pattern) { return pattern.test(path); })) return;
|
if (skip.some(function (pattern) { return pattern.test(path); })) return;
|
||||||
|
|
||||||
|
function defaultEndpoint() {
|
||||||
|
if (window.MILES_API_URL) return window.MILES_API_URL + '/analytics/hit';
|
||||||
|
var metaBase = document.querySelector('meta[name="miles-api-base"]');
|
||||||
|
if (metaBase && metaBase.getAttribute('content')) {
|
||||||
|
return metaBase.getAttribute('content').replace(/\/+$/, '') + '/api/analytics/hit';
|
||||||
|
}
|
||||||
|
var host = window.location.hostname;
|
||||||
|
if (host === 'milesallen.site' || host === 'www.milesallen.site') {
|
||||||
|
return 'https://api.milesallen.site/api/analytics/hit';
|
||||||
|
}
|
||||||
|
return '/api/analytics/hit';
|
||||||
|
}
|
||||||
|
|
||||||
var meta = document.querySelector('meta[name="miles-analytics-endpoint"]');
|
var meta = document.querySelector('meta[name="miles-analytics-endpoint"]');
|
||||||
var endpoint = (meta && meta.getAttribute('content')) || '/api/analytics/hit';
|
var endpoint = (meta && meta.getAttribute('content')) || defaultEndpoint();
|
||||||
|
|
||||||
var payload = {
|
var payload = {
|
||||||
path: path,
|
path: path,
|
||||||
|
|||||||
+1
-1
@@ -11,7 +11,7 @@
|
|||||||
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
|
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
|
||||||
<link href="https://fonts.googleapis.com/css2?family=Press+Start+2P&family=Space+Mono:wght@400;700&family=Inter:wght@400;500;600;700;800&display=swap" rel="stylesheet">
|
<link href="https://fonts.googleapis.com/css2?family=Press+Start+2P&family=Space+Mono:wght@400;700&family=Inter:wght@400;500;600;700;800&display=swap" rel="stylesheet">
|
||||||
<link rel="stylesheet" href="dashboard.css">
|
<link rel="stylesheet" href="dashboard.css">
|
||||||
<script>document.documentElement.dataset.api = '/api';</script>
|
<script src="site-config.js"></script>
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
<div class="scanlines" aria-hidden="true"></div>
|
<div class="scanlines" aria-hidden="true"></div>
|
||||||
|
|||||||
+7
-1
@@ -1,7 +1,13 @@
|
|||||||
(function () {
|
(function () {
|
||||||
'use strict';
|
'use strict';
|
||||||
|
|
||||||
var API = document.documentElement.dataset.api || '/api';
|
var host = window.location.hostname;
|
||||||
|
var fallbackBase = (host === 'milesallen.site' || host === 'www.milesallen.site')
|
||||||
|
? 'https://api.milesallen.site'
|
||||||
|
: '';
|
||||||
|
var API = document.documentElement.dataset.api ||
|
||||||
|
window.MILES_API_URL ||
|
||||||
|
(fallbackBase ? fallbackBase + '/api' : '/api');
|
||||||
var REFRESH_SECONDS = 60;
|
var REFRESH_SECONDS = 60;
|
||||||
var countdown = REFRESH_SECONDS;
|
var countdown = REFRESH_SECONDS;
|
||||||
var refreshing = false;
|
var refreshing = false;
|
||||||
|
|||||||
+10
-4
@@ -53,12 +53,18 @@ include stack traces or secret values.
|
|||||||
### CORS
|
### CORS
|
||||||
|
|
||||||
Cross-origin API requests are accepted only from the configured allowlist:
|
Cross-origin API requests are accepted only from the configured allowlist:
|
||||||
`https://milesallen.site`, `https://www.milesallen.site`, local development
|
`https://milesallen.site`, `https://www.milesallen.site`,
|
||||||
origins, and the request's own origin. Unknown origins receive `403`.
|
`https://api.milesallen.site`, local development origins, and the request's own
|
||||||
|
origin. Unknown origins receive `403`.
|
||||||
|
|
||||||
`OPTIONS` preflight requests receive `204` with `Access-Control-Allow-Origin`,
|
`OPTIONS` preflight requests receive `204` with `Access-Control-Allow-Origin`,
|
||||||
`Access-Control-Allow-Methods: GET, POST, OPTIONS`, and
|
`Access-Control-Allow-Credentials: true`,
|
||||||
`Access-Control-Allow-Headers: Content-Type`.
|
`Access-Control-Allow-Methods: GET, POST, OPTIONS`,
|
||||||
|
`Access-Control-Allow-Headers: Content-Type`, and
|
||||||
|
`Access-Control-Expose-Headers: Retry-After`. The vault login, session, and
|
||||||
|
logout endpoints require credentialed requests; the browser page at
|
||||||
|
`milesallen.site` uses `site-config.js` to call `api.milesallen.site`. Both
|
||||||
|
hostnames are same-site, so the vault cookie keeps `SameSite=Strict`.
|
||||||
|
|
||||||
### Rate limits
|
### Rate limits
|
||||||
|
|
||||||
|
|||||||
+118
-42
@@ -4,15 +4,29 @@ This guide describes how to run the backend on a Debian 13 host behind Caddy or
|
|||||||
Cloudflare Tunnel. It is written to be followed and verified step by step. The
|
Cloudflare Tunnel. It is written to be followed and verified step by step. The
|
||||||
repository does not perform the deployment for you.
|
repository does not perform the deployment for you.
|
||||||
|
|
||||||
The app is a single Node.js process that serves the static site and the API from
|
The app is a single Node.js process. SQLite is the only database. There is no
|
||||||
the same origin. SQLite is the only database. There is no Docker, external
|
Docker, external database, or frontend build step.
|
||||||
database, or frontend build step.
|
|
||||||
|
Two layouts are supported:
|
||||||
|
|
||||||
|
- **Split origin (recommended):** keep the static site on
|
||||||
|
`https://milesallen.site` and expose this Node process on
|
||||||
|
`https://api.milesallen.site`. The dashboard, vault lock page, and analytics
|
||||||
|
beacon read the API hostname from `site-config.js`; the server accepts
|
||||||
|
cross-origin requests from the main site. Because both hostnames are under
|
||||||
|
`milesallen.site`, the vault cookie stays `SameSite=Strict`.
|
||||||
|
- **Single origin:** point the tunnel or Caddy at the whole site so
|
||||||
|
`milesallen.site` is served by this process. Leave `site-config.js` empty.
|
||||||
|
|
||||||
|
The vault page (`/vault`) and games (`/games/*`) are always served by this Node
|
||||||
|
process, so they live on the API hostname in the split-origin layout.
|
||||||
|
|
||||||
## 1. Target layout
|
## 1. Target layout
|
||||||
|
|
||||||
| Path | Purpose |
|
| Path | Purpose |
|
||||||
| --- | --- |
|
| --- | --- |
|
||||||
| `/opt/miles-web` | Repository, static site, backend, `.env` |
|
| `/opt/websites/miles-web` | Repository, static site, backend, `.env` |
|
||||||
|
| `/opt/websites/miles-web/site-config.js` | Browser-facing API hostname |
|
||||||
| `/var/lib/miles-dashboard/dashboard.db` | SQLite database |
|
| `/var/lib/miles-dashboard/dashboard.db` | SQLite database |
|
||||||
| `/var/backups/miles-dashboard/` | SQLite backups |
|
| `/var/backups/miles-dashboard/` | SQLite backups |
|
||||||
| `/etc/systemd/system/miles-dashboard.service` | systemd unit |
|
| `/etc/systemd/system/miles-dashboard.service` | systemd unit |
|
||||||
@@ -62,15 +76,15 @@ Do not use `sudo npm`. Install dependencies as the service user.
|
|||||||
sudo useradd --system --create-home \
|
sudo useradd --system --create-home \
|
||||||
--home-dir /var/lib/miles-dashboard \
|
--home-dir /var/lib/miles-dashboard \
|
||||||
--shell /usr/sbin/nologin miles
|
--shell /usr/sbin/nologin miles
|
||||||
sudo mkdir -p /opt/miles-web /var/lib/miles-dashboard /var/backups/miles-dashboard
|
sudo mkdir -p /opt/websites/miles-web /var/lib/miles-dashboard /var/backups/miles-dashboard
|
||||||
sudo chown -R miles:miles /opt/miles-web /var/lib/miles-dashboard /var/backups/miles-dashboard
|
sudo chown -R miles:miles /opt/websites/miles-web /var/lib/miles-dashboard /var/backups/miles-dashboard
|
||||||
```
|
```
|
||||||
|
|
||||||
Clone the repository into `/opt/miles-web` (the directory must be empty):
|
Clone the repository into `/opt/websites/miles-web` (the directory must be empty):
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
sudo -u miles git clone <YOUR_REPOSITORY_URL> /opt/miles-web
|
sudo -u miles git clone <YOUR_REPOSITORY_URL> /opt/websites/miles-web
|
||||||
cd /opt/miles-web
|
cd /opt/websites/miles-web
|
||||||
sudo -u miles npm ci --omit=dev
|
sudo -u miles npm ci --omit=dev
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -83,14 +97,14 @@ then run `npm ci --omit=dev` as `miles`.
|
|||||||
|
|
||||||
```bash
|
```bash
|
||||||
sudo apt install -y build-essential python3
|
sudo apt install -y build-essential python3
|
||||||
cd /opt/miles-web
|
cd /opt/websites/miles-web
|
||||||
sudo -u miles npm rebuild better-sqlite3 argon2
|
sudo -u miles npm rebuild better-sqlite3 argon2
|
||||||
```
|
```
|
||||||
|
|
||||||
## 4. Environment file
|
## 4. Environment file
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
cd /opt/miles-web
|
cd /opt/websites/miles-web
|
||||||
sudo -u miles cp .env.example .env
|
sudo -u miles cp .env.example .env
|
||||||
sudo -u miles chmod 600 .env
|
sudo -u miles chmod 600 .env
|
||||||
sudo -u miles editor .env
|
sudo -u miles editor .env
|
||||||
@@ -102,10 +116,11 @@ Production values to set:
|
|||||||
NODE_ENV=production
|
NODE_ENV=production
|
||||||
HOST=127.0.0.1
|
HOST=127.0.0.1
|
||||||
PORT=8787
|
PORT=8787
|
||||||
PUBLIC_ORIGIN=https://milesallen.site
|
PUBLIC_ORIGIN=https://api.milesallen.site
|
||||||
|
ALLOWED_ORIGINS=https://milesallen.site,https://www.milesallen.site
|
||||||
TRUST_PROXY=true
|
TRUST_PROXY=true
|
||||||
DB_PATH=/var/lib/miles-dashboard/dashboard.db
|
DB_PATH=/var/lib/miles-dashboard/dashboard.db
|
||||||
SITE_ROOT=/opt/miles-web
|
SITE_ROOT=/opt/websites/miles-web
|
||||||
COOKIE_SECURE=true
|
COOKIE_SECURE=true
|
||||||
GITHUB_USERNAME=mileswolfallen2
|
GITHUB_USERNAME=mileswolfallen2
|
||||||
GITHUB_TOKEN=<server-only token>
|
GITHUB_TOKEN=<server-only token>
|
||||||
@@ -143,11 +158,32 @@ Notes:
|
|||||||
classic token with no scopes is sufficient. Never put it in frontend files.
|
classic token with no scopes is sufficient. Never put it in frontend files.
|
||||||
- `VAULT_PASSWORD_HASH` must start with `$argon2`. If it is missing, the vault
|
- `VAULT_PASSWORD_HASH` must start with `$argon2`. If it is missing, the vault
|
||||||
is disabled and refuses logins.
|
is disabled and refuses logins.
|
||||||
|
- `PUBLIC_ORIGIN` is the API hostname in the split-origin layout. Keep
|
||||||
|
`ALLOWED_ORIGINS` set to the main site hostnames so browser requests from
|
||||||
|
`milesallen.site` pass CORS.
|
||||||
|
- `site-config.js` should contain the same API hostname. The default already
|
||||||
|
maps `milesallen.site` and `www.milesallen.site` to
|
||||||
|
`https://api.milesallen.site`; edit it if you use a different tunnel
|
||||||
|
hostname.
|
||||||
|
|
||||||
## 5. Initialize the database
|
## 5. Preflight and initialize the database
|
||||||
|
|
||||||
|
Run the preflight check before starting anything. It validates `.env`, paths,
|
||||||
|
permissions, the Argon2id hash, CORS origins, native modules, and the `ping`
|
||||||
|
command without opening the database or server:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
cd /opt/miles-web
|
cd /opt/websites/miles-web
|
||||||
|
sudo -u miles npm run preflight
|
||||||
|
```
|
||||||
|
|
||||||
|
Fix every `FAIL` before continuing. `WARN` entries are optional
|
||||||
|
recommendations (for example, no GitHub token).
|
||||||
|
|
||||||
|
Then apply migrations and seed the registries:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd /opt/websites/miles-web
|
||||||
sudo -u miles npm run db:migrate
|
sudo -u miles npm run db:migrate
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -173,8 +209,8 @@ Wants=network-online.target
|
|||||||
Type=simple
|
Type=simple
|
||||||
User=miles
|
User=miles
|
||||||
Group=miles
|
Group=miles
|
||||||
WorkingDirectory=/opt/miles-web
|
WorkingDirectory=/opt/websites/miles-web
|
||||||
EnvironmentFile=/opt/miles-web/.env
|
EnvironmentFile=/opt/websites/miles-web/.env
|
||||||
ExecStart=/usr/bin/node server/index.js
|
ExecStart=/usr/bin/node server/index.js
|
||||||
Restart=on-failure
|
Restart=on-failure
|
||||||
RestartSec=5
|
RestartSec=5
|
||||||
@@ -183,7 +219,7 @@ KillSignal=SIGTERM
|
|||||||
StandardOutput=journal
|
StandardOutput=journal
|
||||||
StandardError=journal
|
StandardError=journal
|
||||||
|
|
||||||
# Hardening. /opt/miles-web is read-only to the service; the DB directory is
|
# Hardening. /opt/websites/miles-web is read-only to the service; the DB directory is
|
||||||
# the only writable path.
|
# the only writable path.
|
||||||
NoNewPrivileges=yes
|
NoNewPrivileges=yes
|
||||||
PrivateTmp=yes
|
PrivateTmp=yes
|
||||||
@@ -229,7 +265,7 @@ The smoke script is intended for local verification. On a production database
|
|||||||
it records one synthetic `/smoke-test` analytics pageview:
|
it records one synthetic `/smoke-test` analytics pageview:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
cd /opt/miles-web
|
cd /opt/websites/miles-web
|
||||||
sudo -u miles npm run smoke
|
sudo -u miles npm run smoke
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -250,12 +286,18 @@ sudo apt install -y caddy
|
|||||||
Replace `/etc/caddy/Caddyfile`:
|
Replace `/etc/caddy/Caddyfile`:
|
||||||
|
|
||||||
```caddyfile
|
```caddyfile
|
||||||
|
# Single-origin layout
|
||||||
milesallen.site, www.milesallen.site {
|
milesallen.site, www.milesallen.site {
|
||||||
encode zstd gzip
|
encode zstd gzip
|
||||||
reverse_proxy 127.0.0.1:8787
|
reverse_proxy 127.0.0.1:8787
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
If you use Caddy for the split-origin layout instead, replace the site
|
||||||
|
addresses with `api.milesallen.site` and set
|
||||||
|
`PUBLIC_ORIGIN=https://api.milesallen.site` while the static site stays on its
|
||||||
|
own host.
|
||||||
|
|
||||||
Caddy obtains and renews TLS certificates automatically. Validate and reload:
|
Caddy obtains and renews TLS certificates automatically. Validate and reload:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
@@ -280,12 +322,13 @@ With Caddy in front:
|
|||||||
|
|
||||||
- `TRUST_PROXY=true`
|
- `TRUST_PROXY=true`
|
||||||
- `COOKIE_SECURE=true`
|
- `COOKIE_SECURE=true`
|
||||||
- `PUBLIC_ORIGIN=https://milesallen.site`
|
- `PUBLIC_ORIGIN=https://milesallen.site` for the single-origin layout, or
|
||||||
|
`https://api.milesallen.site` for the split-origin layout
|
||||||
- Keep `HOST=127.0.0.1`
|
- Keep `HOST=127.0.0.1`
|
||||||
|
|
||||||
Caddy sets `X-Forwarded-For`; the app reads it only when `TRUST_PROXY=true`.
|
Caddy sets `X-Forwarded-For`; the app reads it only when `TRUST_PROXY=true`.
|
||||||
|
|
||||||
## 8. Cloudflare Tunnel alternative
|
## 8. Cloudflare Tunnel (API hostname)
|
||||||
|
|
||||||
Use this instead of public ports and Caddy. The origin can stay on loopback and
|
Use this instead of public ports and Caddy. The origin can stay on loopback and
|
||||||
no inbound 80/443 is required.
|
no inbound 80/443 is required.
|
||||||
@@ -295,8 +338,7 @@ Install `cloudflared` using Cloudflare's current Debian instructions, then:
|
|||||||
```bash
|
```bash
|
||||||
cloudflared tunnel login
|
cloudflared tunnel login
|
||||||
cloudflared tunnel create miles-dashboard
|
cloudflared tunnel create miles-dashboard
|
||||||
cloudflared tunnel route dns miles-dashboard milesallen.site
|
cloudflared tunnel route dns miles-dashboard api.milesallen.site
|
||||||
cloudflared tunnel route dns miles-dashboard www.milesallen.site
|
|
||||||
```
|
```
|
||||||
|
|
||||||
Create `/etc/cloudflared/config.yml`:
|
Create `/etc/cloudflared/config.yml`:
|
||||||
@@ -305,9 +347,7 @@ Create `/etc/cloudflared/config.yml`:
|
|||||||
tunnel: <TUNNEL_ID>
|
tunnel: <TUNNEL_ID>
|
||||||
credentials-file: /etc/cloudflared/<TUNNEL_ID>.json
|
credentials-file: /etc/cloudflared/<TUNNEL_ID>.json
|
||||||
ingress:
|
ingress:
|
||||||
- hostname: milesallen.site
|
- hostname: api.milesallen.site
|
||||||
service: http://127.0.0.1:8787
|
|
||||||
- hostname: www.milesallen.site
|
|
||||||
service: http://127.0.0.1:8787
|
service: http://127.0.0.1:8787
|
||||||
- service: http_status:404
|
- service: http_status:404
|
||||||
```
|
```
|
||||||
@@ -325,6 +365,25 @@ Keep `HOST=127.0.0.1`, set `TRUST_PROXY=true` (Cloudflare sets
|
|||||||
`CF-Connecting-IP`), and keep `COOKIE_SECURE=true`. No `ufw` rule for 8787,
|
`CF-Connecting-IP`), and keep `COOKIE_SECURE=true`. No `ufw` rule for 8787,
|
||||||
80, or 443 is needed for the tunnel path.
|
80, or 443 is needed for the tunnel path.
|
||||||
|
|
||||||
|
This exposes the API, dashboard assets, vault lock page, `/vault`, and
|
||||||
|
`/games/*` at `https://api.milesallen.site`. The static site on
|
||||||
|
`https://milesallen.site` calls it cross-origin using `site-config.js`; the
|
||||||
|
server already allows the main-site origins through CORS.
|
||||||
|
|
||||||
|
If you also want this Node process to serve the main static site, add these
|
||||||
|
lines before the catch-all and route DNS for them:
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
- hostname: milesallen.site
|
||||||
|
service: http://127.0.0.1:8787
|
||||||
|
- hostname: www.milesallen.site
|
||||||
|
service: http://127.0.0.1:8787
|
||||||
|
```
|
||||||
|
|
||||||
|
Do not expose port 8787 in the firewall. In the split-origin layout, the main
|
||||||
|
static host must publish the updated `site-config.js`, `dashboard.js`,
|
||||||
|
`dashboard.html`, `analytics.js`, and `moon-vault.html` from this repository.
|
||||||
|
|
||||||
## 9. Persistence, backups, and restore
|
## 9. Persistence, backups, and restore
|
||||||
|
|
||||||
### What persists
|
### What persists
|
||||||
@@ -382,7 +441,7 @@ curl -fsS http://127.0.0.1:8787/api/health
|
|||||||
## 10. Upgrades
|
## 10. Upgrades
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
cd /opt/miles-web
|
cd /opt/websites/miles-web
|
||||||
sudo -u miles git pull --ff-only
|
sudo -u miles git pull --ff-only
|
||||||
sudo -u miles npm ci --omit=dev
|
sudo -u miles npm ci --omit=dev
|
||||||
sudo -u miles npm run db:migrate
|
sudo -u miles npm run db:migrate
|
||||||
@@ -396,7 +455,7 @@ idempotent and tracked in `schema_migrations`.
|
|||||||
After a Node major-version upgrade, rebuild native modules if needed:
|
After a Node major-version upgrade, rebuild native modules if needed:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
cd /opt/miles-web
|
cd /opt/websites/miles-web
|
||||||
sudo -u miles npm rebuild better-sqlite3 argon2
|
sudo -u miles npm rebuild better-sqlite3 argon2
|
||||||
sudo systemctl restart miles-dashboard
|
sudo systemctl restart miles-dashboard
|
||||||
```
|
```
|
||||||
@@ -406,6 +465,10 @@ sudo systemctl restart miles-dashboard
|
|||||||
Run these after deployment:
|
Run these after deployment:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
|
# Configuration and runtime prerequisites
|
||||||
|
cd /opt/websites/miles-web
|
||||||
|
sudo -u miles npm run preflight
|
||||||
|
|
||||||
# Process and logs
|
# Process and logs
|
||||||
sudo systemctl status miles-dashboard --no-pager
|
sudo systemctl status miles-dashboard --no-pager
|
||||||
sudo journalctl -u miles-dashboard -n 50 --no-pager
|
sudo journalctl -u miles-dashboard -n 50 --no-pager
|
||||||
@@ -414,23 +477,30 @@ sudo journalctl -u miles-dashboard -n 50 --no-pager
|
|||||||
curl -fsS http://127.0.0.1:8787/api/health
|
curl -fsS http://127.0.0.1:8787/api/health
|
||||||
curl -fsS http://127.0.0.1:8787/api/status
|
curl -fsS http://127.0.0.1:8787/api/status
|
||||||
|
|
||||||
# Public site through the proxy
|
# Public API through the tunnel
|
||||||
curl -fsS https://milesallen.site/api/health
|
curl -fsS https://api.milesallen.site/api/health
|
||||||
curl -fsS -o /dev/null -w '%{http_code}\n' https://milesallen.site/
|
curl -fsS https://api.milesallen.site/api/status
|
||||||
curl -fsS -o /dev/null -w '%{http_code}\n' https://milesallen.site/dashboard.html
|
|
||||||
|
# CORS from the main site
|
||||||
|
curl -s -D - -o /dev/null -X OPTIONS \
|
||||||
|
-H 'Origin: https://milesallen.site' \
|
||||||
|
-H 'Access-Control-Request-Method: GET' \
|
||||||
|
https://api.milesallen.site/api/status | grep -i 'access-control-allow'
|
||||||
|
|
||||||
# Vault is locked without a session
|
# Vault is locked without a session
|
||||||
curl -s -o /dev/null -w '%{http_code} %{redirect_url}\n' https://milesallen.site/vault
|
curl -s -o /dev/null -w '%{http_code} %{redirect_url}\n' https://api.milesallen.site/vault
|
||||||
curl -s -o /dev/null -w '%{http_code} %{redirect_url}\n' https://milesallen.site/games/dino.html
|
curl -s -o /dev/null -w '%{http_code} %{redirect_url}\n' https://api.milesallen.site/games/dino.html
|
||||||
|
|
||||||
# Private files are not served
|
# Private files are not served
|
||||||
curl -s -o /dev/null -w '%{http_code}\n' https://milesallen.site/.env
|
curl -s -o /dev/null -w '%{http_code}\n' https://api.milesallen.site/.env
|
||||||
curl -s -o /dev/null -w '%{http_code}\n' https://milesallen.site/server/config.js
|
curl -s -o /dev/null -w '%{http_code}\n' https://api.milesallen.site/server/config.js
|
||||||
curl -s -o /dev/null -w '%{http_code}\n' https://milesallen.site/data/dashboard.db
|
curl -s -o /dev/null -w '%{http_code}\n' https://api.milesallen.site/data/dashboard.db
|
||||||
```
|
```
|
||||||
|
|
||||||
Expected result for the private-file checks is `403`. The vault and game checks
|
Expected result for the private-file checks is `403`. The vault and game checks
|
||||||
should return `302` to `/moon-vault.html` before login.
|
should return `302` to `/moon-vault.html` before login. The CORS preflight should
|
||||||
|
show `Access-Control-Allow-Origin: https://milesallen.site` and
|
||||||
|
`Access-Control-Allow-Credentials: true`.
|
||||||
|
|
||||||
Then verify in a browser:
|
Then verify in a browser:
|
||||||
|
|
||||||
@@ -448,7 +518,7 @@ Then verify in a browser:
|
|||||||
|
|
||||||
```bash
|
```bash
|
||||||
sudo apt install -y build-essential python3
|
sudo apt install -y build-essential python3
|
||||||
cd /opt/miles-web
|
cd /opt/websites/miles-web
|
||||||
sudo -u miles npm rebuild better-sqlite3 argon2
|
sudo -u miles npm rebuild better-sqlite3 argon2
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -502,14 +572,20 @@ to `.env`, and restart. The hash must start with `$argon2`.
|
|||||||
|
|
||||||
- If serving over plain HTTP with `COOKIE_SECURE=true`, the browser discards
|
- If serving over plain HTTP with `COOKIE_SECURE=true`, the browser discards
|
||||||
the cookie. Use HTTPS or set `COOKIE_SECURE=false` for local-only testing.
|
the cookie. Use HTTPS or set `COOKIE_SECURE=false` for local-only testing.
|
||||||
- Confirm the browser is using the same origin as `PUBLIC_ORIGIN`.
|
- In the split-origin layout, the cookie belongs to `api.milesallen.site`.
|
||||||
|
Confirm `site-config.js` points at that hostname and the login request uses
|
||||||
|
`credentials: 'include'`.
|
||||||
|
- `milesallen.site` and `api.milesallen.site` are same-site, so
|
||||||
|
`SameSite=Strict` is correct. If you move the API to a different registrable
|
||||||
|
domain, the cookie would need `SameSite=None; Secure` instead.
|
||||||
- Confirm `SESSION_SECRET` did not change and the database was not wiped.
|
- Confirm `SESSION_SECRET` did not change and the database was not wiped.
|
||||||
- Check that `TRUST_PROXY` matches the actual proxy setup.
|
- Check that `TRUST_PROXY` matches the actual proxy setup.
|
||||||
|
|
||||||
### API returns `403 forbidden` cross-origin
|
### API returns `403 forbidden` cross-origin
|
||||||
|
|
||||||
The request origin is not in the allowlist. Set `PUBLIC_ORIGIN` and
|
The request origin is not in the allowlist. Set `PUBLIC_ORIGIN` to the API
|
||||||
`ALLOWED_ORIGINS` to the real HTTPS origins. Same-origin requests are always
|
hostname and `ALLOWED_ORIGINS` to the main-site hostnames, then restart. Confirm
|
||||||
|
`site-config.js` uses the same API hostname. Same-origin requests are always
|
||||||
accepted.
|
accepted.
|
||||||
|
|
||||||
### `SQLITE_BUSY` or database locked
|
### `SQLITE_BUSY` or database locked
|
||||||
|
|||||||
+13
-4
@@ -11,6 +11,7 @@
|
|||||||
<link rel="preconnect" href="https://fonts.googleapis.com">
|
<link rel="preconnect" href="https://fonts.googleapis.com">
|
||||||
<link href="https://fonts.googleapis.com/css2?family=Press+Start+2P&family=Space+Mono:wght@400;700&family=Inter:wght@400;500;600;800&display=swap" rel="stylesheet">
|
<link href="https://fonts.googleapis.com/css2?family=Press+Start+2P&family=Space+Mono:wght@400;700&family=Inter:wght@400;500;600;800&display=swap" rel="stylesheet">
|
||||||
<link rel="stylesheet" href="projects/style.css">
|
<link rel="stylesheet" href="projects/style.css">
|
||||||
|
<script src="site-config.js"></script>
|
||||||
<style>
|
<style>
|
||||||
:root{--vault-bg:#07070c;}
|
:root{--vault-bg:#07070c;}
|
||||||
body{background:radial-gradient(circle at 50% 35%,#101020 0%,#05050a 70%);min-height:100vh;}
|
body{background:radial-gradient(circle at 50% 35%,#101020 0%,#05050a 70%);min-height:100vh;}
|
||||||
@@ -84,11 +85,19 @@ nav{position:fixed;top:0;left:0;right:0;z-index:100;background:rgba(7,7,12,0.9);
|
|||||||
card.classList.add('shake');
|
card.classList.add('shake');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
var host = window.location.hostname;
|
||||||
|
var fallbackBase = (host === 'milesallen.site' || host === 'www.milesallen.site')
|
||||||
|
? 'https://api.milesallen.site'
|
||||||
|
: '';
|
||||||
|
var base = window.MILES_API_BASE || fallbackBase;
|
||||||
|
var API = window.MILES_API_URL || (base ? base + '/api' : '/api');
|
||||||
|
var VAULT_URL = window.MILES_VAULT_URL || (base ? base + '/vault' : '/vault');
|
||||||
|
|
||||||
function go() {
|
function go() {
|
||||||
window.location.replace('/vault');
|
window.location.replace(VAULT_URL);
|
||||||
}
|
}
|
||||||
|
|
||||||
fetch('/api/vault/session', { credentials: 'same-origin', cache: 'no-store' })
|
fetch(API + '/vault/session', { credentials: 'include', cache: 'no-store' })
|
||||||
.then(function (response) {
|
.then(function (response) {
|
||||||
if (!response.ok) throw new Error('Vault status unavailable');
|
if (!response.ok) throw new Error('Vault status unavailable');
|
||||||
return response.json();
|
return response.json();
|
||||||
@@ -115,9 +124,9 @@ nav{position:fixed;top:0;left:0;right:0;z-index:100;background:rgba(7,7,12,0.9);
|
|||||||
button.disabled = true;
|
button.disabled = true;
|
||||||
setMessage('checking…', true);
|
setMessage('checking…', true);
|
||||||
|
|
||||||
fetch('/api/vault/login', {
|
fetch(API + '/vault/login', {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
credentials: 'same-origin',
|
credentials: 'include',
|
||||||
cache: 'no-store',
|
cache: 'no-store',
|
||||||
headers: { 'Content-Type': 'application/json', 'Accept': 'application/json' },
|
headers: { 'Content-Type': 'application/json', 'Accept': 'application/json' },
|
||||||
body: JSON.stringify({ password: password })
|
body: JSON.stringify({ password: password })
|
||||||
|
|||||||
@@ -12,6 +12,7 @@
|
|||||||
"start": "node server/index.js",
|
"start": "node server/index.js",
|
||||||
"test": "node --test tests/",
|
"test": "node --test tests/",
|
||||||
"db:migrate": "node server/scripts/migrate.js",
|
"db:migrate": "node server/scripts/migrate.js",
|
||||||
|
"preflight": "node server/scripts/preflight.js",
|
||||||
"hash-password": "node server/scripts/hash-password.js",
|
"hash-password": "node server/scripts/hash-password.js",
|
||||||
"smoke": "node server/scripts/smoke.js"
|
"smoke": "node server/scripts/smoke.js"
|
||||||
},
|
},
|
||||||
|
|||||||
+34
-8
@@ -19,6 +19,23 @@ const PUBLIC_API_PREFIX = '/api';
|
|||||||
const VAULT_PAGE = '/vault';
|
const VAULT_PAGE = '/vault';
|
||||||
const VAULT_VIEW = 'server/views/vault.html';
|
const VAULT_VIEW = 'server/views/vault.html';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Decode and normalize a request path once for routing and access gates.
|
||||||
|
* Repeated decoding prevents bypasses such as /games%2Fdino.html or
|
||||||
|
* /%67ames/dino.html from reaching protected static files.
|
||||||
|
*/
|
||||||
|
function canonicalPathname(rawPathname) {
|
||||||
|
let value = rawPathname || '/';
|
||||||
|
for (let round = 0; round < 4; round += 1) {
|
||||||
|
const decoded = decodeURIComponent(value);
|
||||||
|
if (decoded === value) break;
|
||||||
|
value = decoded;
|
||||||
|
}
|
||||||
|
value = path.posix.normalize(value);
|
||||||
|
if (!value.startsWith('/')) value = `/${value}`;
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
|
||||||
function methodNotAllowed(res, allowed) {
|
function methodNotAllowed(res, allowed) {
|
||||||
sendJson(
|
sendJson(
|
||||||
res,
|
res,
|
||||||
@@ -87,8 +104,7 @@ export function createApp({ config, db, logger, services, now = () => new Date()
|
|||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
async function route(req, res, url, context) {
|
async function route(req, res, url, context, pathname) {
|
||||||
const { pathname } = url;
|
|
||||||
const method = req.method || 'GET';
|
const method = req.method || 'GET';
|
||||||
|
|
||||||
if (pathname === '/api' || pathname === '/api/') {
|
if (pathname === '/api' || pathname === '/api/') {
|
||||||
@@ -333,12 +349,18 @@ export function createApp({ config, db, logger, services, now = () => new Date()
|
|||||||
const id = requestId();
|
const id = requestId();
|
||||||
const started = Date.now();
|
const started = Date.now();
|
||||||
const url = new URL(req.url || '/', `http://${req.headers.host || 'localhost'}`);
|
const url = new URL(req.url || '/', `http://${req.headers.host || 'localhost'}`);
|
||||||
const pathname = url.pathname;
|
|
||||||
const method = req.method || 'GET';
|
const method = req.method || 'GET';
|
||||||
|
|
||||||
res.setHeader('X-Request-Id', id);
|
res.setHeader('X-Request-Id', id);
|
||||||
applySecurityHeaders(res, { production: config.production });
|
applySecurityHeaders(res, { production: config.production });
|
||||||
|
|
||||||
|
let pathname;
|
||||||
|
try {
|
||||||
|
pathname = canonicalPathname(url.pathname);
|
||||||
|
} catch {
|
||||||
|
return sendText(res, 400, 'Bad request');
|
||||||
|
}
|
||||||
|
|
||||||
const isApi = pathname === PUBLIC_API_PREFIX || pathname.startsWith(`${PUBLIC_API_PREFIX}/`);
|
const isApi = pathname === PUBLIC_API_PREFIX || pathname.startsWith(`${PUBLIC_API_PREFIX}/`);
|
||||||
const cors = applyCors(req, res);
|
const cors = applyCors(req, res);
|
||||||
if (isApi) {
|
if (isApi) {
|
||||||
@@ -384,7 +406,7 @@ export function createApp({ config, db, logger, services, now = () => new Date()
|
|||||||
ip: getClientIp(req, { trustProxy: config.trustProxy })
|
ip: getClientIp(req, { trustProxy: config.trustProxy })
|
||||||
};
|
};
|
||||||
|
|
||||||
const apiResult = await route(req, res, url, context);
|
const apiResult = await route(req, res, url, context, pathname);
|
||||||
if (apiResult !== null) return;
|
if (apiResult !== null) return;
|
||||||
|
|
||||||
if (pathname === VAULT_PAGE || pathname === `${VAULT_PAGE}/`) {
|
if (pathname === VAULT_PAGE || pathname === `${VAULT_PAGE}/`) {
|
||||||
@@ -399,14 +421,16 @@ export function createApp({ config, db, logger, services, now = () => new Date()
|
|||||||
return sendFile(req, res, vaultViewPath, stat, { cache: 'no-store' });
|
return sendFile(req, res, vaultViewPath, stat, { cache: 'no-store' });
|
||||||
}
|
}
|
||||||
|
|
||||||
if (pathname === '/games' || pathname.startsWith('/games/')) {
|
const protectedPath = pathname.toLowerCase();
|
||||||
|
if (protectedPath === '/games' || protectedPath.startsWith('/games/')) {
|
||||||
if (!requireVault(req, res)) return;
|
if (!requireVault(req, res)) return;
|
||||||
return serveStatic(req, res, {
|
return serveStatic(req, res, {
|
||||||
root: config.siteRoot,
|
root: config.siteRoot,
|
||||||
pathname,
|
pathname,
|
||||||
// Never let a browser cache vault-protected content: a cached game
|
// Never let a browser cache vault-protected content: a cached game
|
||||||
// must not remain viewable after logout or session expiry.
|
// must not remain viewable after logout or session expiry.
|
||||||
cache: 'no-store'
|
cache: 'no-store',
|
||||||
|
decodedPath: true
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -414,7 +438,8 @@ export function createApp({ config, db, logger, services, now = () => new Date()
|
|||||||
return serveStatic(req, res, {
|
return serveStatic(req, res, {
|
||||||
root: config.siteRoot,
|
root: config.siteRoot,
|
||||||
pathname: '/dashboard.html',
|
pathname: '/dashboard.html',
|
||||||
notFoundFile: path.join(config.siteRoot, '404.html')
|
notFoundFile: path.join(config.siteRoot, '404.html'),
|
||||||
|
decodedPath: true
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -425,7 +450,8 @@ export function createApp({ config, db, logger, services, now = () => new Date()
|
|||||||
return serveStatic(req, res, {
|
return serveStatic(req, res, {
|
||||||
root: config.siteRoot,
|
root: config.siteRoot,
|
||||||
pathname,
|
pathname,
|
||||||
notFoundFile: path.join(config.siteRoot, '404.html')
|
notFoundFile: path.join(config.siteRoot, '404.html'),
|
||||||
|
decodedPath: true
|
||||||
});
|
});
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
if (err instanceof AppError) {
|
if (err instanceof AppError) {
|
||||||
|
|||||||
+5
-1
@@ -148,7 +148,11 @@ export function loadConfig(env = process.env) {
|
|||||||
}
|
}
|
||||||
})();
|
})();
|
||||||
|
|
||||||
const productionOrigins = ['https://milesallen.site', 'https://www.milesallen.site'];
|
const productionOrigins = [
|
||||||
|
'https://milesallen.site',
|
||||||
|
'https://www.milesallen.site',
|
||||||
|
'https://api.milesallen.site'
|
||||||
|
];
|
||||||
const defaultOrigins = production
|
const defaultOrigins = production
|
||||||
? [publicOrigin, ...productionOrigins]
|
? [publicOrigin, ...productionOrigins]
|
||||||
: [
|
: [
|
||||||
|
|||||||
@@ -67,6 +67,7 @@ export function corsFor(origin, allowedOrigins) {
|
|||||||
'Access-Control-Allow-Credentials': 'true',
|
'Access-Control-Allow-Credentials': 'true',
|
||||||
'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
|
'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
|
||||||
'Access-Control-Allow-Headers': 'Content-Type',
|
'Access-Control-Allow-Headers': 'Content-Type',
|
||||||
|
'Access-Control-Expose-Headers': 'Retry-After',
|
||||||
'Access-Control-Max-Age': '600',
|
'Access-Control-Max-Age': '600',
|
||||||
Vary: 'Origin'
|
Vary: 'Origin'
|
||||||
};
|
};
|
||||||
|
|||||||
+11
-7
@@ -68,12 +68,16 @@ function cacheControl(file) {
|
|||||||
: 'public, max-age=3600';
|
: 'public, max-age=3600';
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function resolveStaticPath(root, rawPathname) {
|
export async function resolveStaticPath(root, rawPathname, { decodedPath = false } = {}) {
|
||||||
let pathname;
|
let pathname;
|
||||||
try {
|
if (decodedPath) {
|
||||||
pathname = decodeURIComponent(rawPathname);
|
pathname = rawPathname;
|
||||||
} catch {
|
} else {
|
||||||
return { error: 400 };
|
try {
|
||||||
|
pathname = decodeURIComponent(rawPathname);
|
||||||
|
} catch {
|
||||||
|
return { error: 400 };
|
||||||
|
}
|
||||||
}
|
}
|
||||||
if (!pathname.startsWith('/') || pathname.includes('\\') || pathname.includes('\0')) {
|
if (!pathname.startsWith('/') || pathname.includes('\\') || pathname.includes('\0')) {
|
||||||
return { error: 400 };
|
return { error: 400 };
|
||||||
@@ -165,8 +169,8 @@ export async function sendFile(req, res, file, stat, { status = 200, cache = nul
|
|||||||
fs.createReadStream(file).pipe(res);
|
fs.createReadStream(file).pipe(res);
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function serveStatic(req, res, { root, pathname, notFoundFile = null, cache = null }) {
|
export async function serveStatic(req, res, { root, pathname, notFoundFile = null, cache = null, decodedPath = false }) {
|
||||||
const result = await resolveStaticPath(root, pathname);
|
const result = await resolveStaticPath(root, pathname, { decodedPath });
|
||||||
if (result.error === 404) {
|
if (result.error === 404) {
|
||||||
if (notFoundFile) {
|
if (notFoundFile) {
|
||||||
try {
|
try {
|
||||||
|
|||||||
@@ -0,0 +1,139 @@
|
|||||||
|
import fs from 'node:fs';
|
||||||
|
import path from 'node:path';
|
||||||
|
import { execFileSync } from 'node:child_process';
|
||||||
|
import { loadEnv } from '../lib/env.js';
|
||||||
|
import { loadConfig } from '../config.js';
|
||||||
|
|
||||||
|
const checks = [];
|
||||||
|
function pass(label, detail = '') { checks.push({ level: 'pass', label, detail }); }
|
||||||
|
function warn(label, detail = '') { checks.push({ level: 'warn', label, detail }); }
|
||||||
|
function fail(label, detail = '') { checks.push({ level: 'fail', label, detail }); }
|
||||||
|
|
||||||
|
function check(condition, label, detail, { fatal = true } = {}) {
|
||||||
|
if (condition) pass(label, detail);
|
||||||
|
else if (fatal) fail(label, detail);
|
||||||
|
else warn(label, detail);
|
||||||
|
}
|
||||||
|
|
||||||
|
function canWriteDir(dir) {
|
||||||
|
try {
|
||||||
|
fs.mkdirSync(dir, { recursive: true });
|
||||||
|
fs.accessSync(dir, fs.constants.W_OK);
|
||||||
|
return true;
|
||||||
|
} catch {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function fileExists(file) {
|
||||||
|
try {
|
||||||
|
return fs.statSync(file).isFile();
|
||||||
|
} catch {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function dirExists(dir) {
|
||||||
|
try {
|
||||||
|
return fs.statSync(dir).isDirectory();
|
||||||
|
} catch {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function main() {
|
||||||
|
const envPath = path.resolve(process.cwd(), '.env');
|
||||||
|
const envExists = fileExists(envPath);
|
||||||
|
check(envExists, '.env exists', envPath);
|
||||||
|
if (envExists) {
|
||||||
|
const mode = fs.statSync(envPath).mode & 0o777;
|
||||||
|
check((mode & 0o077) === 0, '.env permissions are private', `mode ${mode.toString(8)}`, { fatal: false });
|
||||||
|
}
|
||||||
|
|
||||||
|
loadEnv(envPath);
|
||||||
|
const config = loadConfig();
|
||||||
|
|
||||||
|
const major = Number.parseInt(process.versions.node.split('.')[0], 10);
|
||||||
|
check(major >= 20, 'Node.js version >= 20', process.versions.node);
|
||||||
|
|
||||||
|
check(config.production, 'NODE_ENV is production', config.env, { fatal: false });
|
||||||
|
check(
|
||||||
|
config.production ? config.sessionSecret.length >= 32 : true,
|
||||||
|
'SESSION_SECRET is long enough',
|
||||||
|
`${config.sessionSecret.length} chars`
|
||||||
|
);
|
||||||
|
check(
|
||||||
|
config.production ? config.cookie.secure : true,
|
||||||
|
'COOKIE_SECURE is enabled in production',
|
||||||
|
String(config.cookie.secure)
|
||||||
|
);
|
||||||
|
check(config.publicOrigin.startsWith('https://'), 'PUBLIC_ORIGIN uses HTTPS', config.publicOrigin, {
|
||||||
|
fatal: config.production
|
||||||
|
});
|
||||||
|
for (const origin of ['https://milesallen.site', 'https://www.milesallen.site']) {
|
||||||
|
check(config.allowedOrigins.has(origin), `CORS origin allowed: ${origin}`, 'allowed');
|
||||||
|
}
|
||||||
|
check(path.isAbsolute(config.siteRoot), 'SITE_ROOT is absolute', config.siteRoot);
|
||||||
|
check(path.isAbsolute(config.dbPath), 'DB_PATH is absolute', config.dbPath);
|
||||||
|
|
||||||
|
check(dirExists(config.siteRoot), 'SITE_ROOT directory exists', config.siteRoot);
|
||||||
|
for (const relative of ['index.html', 'dashboard.html', 'moon-vault.html', 'site-config.js', 'projects/style.css']) {
|
||||||
|
check(fileExists(path.join(config.siteRoot, relative)), `site file present: ${relative}`);
|
||||||
|
}
|
||||||
|
check(dirExists(path.join(config.siteRoot, 'games')), 'games directory present', path.join(config.siteRoot, 'games'));
|
||||||
|
|
||||||
|
const dbDir = path.dirname(config.dbPath);
|
||||||
|
check(canWriteDir(dbDir), 'database directory is writable', dbDir);
|
||||||
|
|
||||||
|
const vaultHash = config.vault.passwordHash || '';
|
||||||
|
check(
|
||||||
|
vaultHash.startsWith('$argon2id$'),
|
||||||
|
'VAULT_PASSWORD_HASH is an Argon2id hash',
|
||||||
|
vaultHash ? 'hash present' : 'not set'
|
||||||
|
);
|
||||||
|
check(!config.vault.password, 'plaintext VAULT_PASSWORD is not used', config.vault.password ? 'remove it' : 'ok', {
|
||||||
|
fatal: false
|
||||||
|
});
|
||||||
|
|
||||||
|
check(Boolean(config.github.token), 'GITHUB_TOKEN is set', config.github.token ? 'present' : 'anonymous API limits', {
|
||||||
|
fatal: false
|
||||||
|
});
|
||||||
|
|
||||||
|
try {
|
||||||
|
execFileSync('ping', ['-c', '1', '-W', '2', '127.0.0.1'], { stdio: 'ignore' });
|
||||||
|
pass('ping command works', 'localhost probe');
|
||||||
|
} catch (err) {
|
||||||
|
warn('ping command check failed', err?.code === 'ENOENT' ? 'ping not installed' : 'probe failed');
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
await import('better-sqlite3');
|
||||||
|
pass('better-sqlite3 loads');
|
||||||
|
} catch (err) {
|
||||||
|
fail('better-sqlite3 loads', err.message);
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
await import('argon2');
|
||||||
|
pass('argon2 loads');
|
||||||
|
} catch (err) {
|
||||||
|
fail('argon2 loads', err.message);
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const warning of config.warnings) warn('config warning', warning);
|
||||||
|
|
||||||
|
const width = Math.max(...checks.map((c) => c.label.length));
|
||||||
|
for (const entry of checks) {
|
||||||
|
const tag = entry.level === 'pass' ? 'PASS' : entry.level === 'warn' ? 'WARN' : 'FAIL';
|
||||||
|
console.log(`${tag} ${entry.label.padEnd(width)} ${entry.detail}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const failures = checks.filter((c) => c.level === 'fail').length;
|
||||||
|
const warnings = checks.filter((c) => c.level === 'warn').length;
|
||||||
|
console.log(`\n${checks.length - failures - warnings} passed, ${warnings} warnings, ${failures} failed`);
|
||||||
|
if (failures > 0) process.exitCode = 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
main().catch((err) => {
|
||||||
|
console.error(`preflight failed: ${err.message}`);
|
||||||
|
process.exitCode = 1;
|
||||||
|
});
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
/*
|
||||||
|
* Deployment configuration for the public site.
|
||||||
|
*
|
||||||
|
* The static site can live on milesallen.site while the Node backend is
|
||||||
|
* exposed on api.milesallen.site. Everything else (API calls, the vault,
|
||||||
|
* analytics) is derived from this one value.
|
||||||
|
*
|
||||||
|
* Override before this file loads if you use a different hostname:
|
||||||
|
* <script>window.MILES_API_BASE = 'https://api.example.com';</script>
|
||||||
|
* <script src="site-config.js"></script>
|
||||||
|
*
|
||||||
|
* Locally the value stays empty, so requests remain same-origin.
|
||||||
|
*/
|
||||||
|
(function () {
|
||||||
|
'use strict';
|
||||||
|
if (window.__milesSiteConfig) return;
|
||||||
|
window.__milesSiteConfig = true;
|
||||||
|
|
||||||
|
var meta = document.querySelector('meta[name="miles-api-base"]');
|
||||||
|
var configured = window.MILES_API_BASE;
|
||||||
|
if (typeof configured !== 'string') {
|
||||||
|
configured = meta ? meta.getAttribute('content') || '' : '';
|
||||||
|
}
|
||||||
|
|
||||||
|
var host = window.location.hostname;
|
||||||
|
var local = host === 'localhost' || host === '127.0.0.1' || host === '::1' || host === '[::1]';
|
||||||
|
if (!configured && !local) {
|
||||||
|
// Production split-origin default. API and static site are same-site
|
||||||
|
// (both under milesallen.site), so vault cookies remain SameSite=Strict.
|
||||||
|
if (host === 'milesallen.site' || host === 'www.milesallen.site') {
|
||||||
|
configured = 'https://api.milesallen.site';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
configured = configured.replace(/\/+$/, '');
|
||||||
|
window.MILES_API_BASE = configured;
|
||||||
|
window.MILES_API_URL = configured ? configured + '/api' : '/api';
|
||||||
|
window.MILES_VAULT_URL = configured ? configured + '/vault' : '/vault';
|
||||||
|
})();
|
||||||
@@ -76,12 +76,29 @@ test('HTTP app exposes documented APIs, security headers, and CORS allowlist', a
|
|||||||
});
|
});
|
||||||
assert.equal(preflight.status, 204);
|
assert.equal(preflight.status, 204);
|
||||||
assert.equal(preflight.headers.get('access-control-allow-origin'), 'https://milesallen.site');
|
assert.equal(preflight.headers.get('access-control-allow-origin'), 'https://milesallen.site');
|
||||||
|
assert.equal(preflight.headers.get('access-control-allow-credentials'), 'true');
|
||||||
|
|
||||||
|
const apiPreflight = await fetch(base + '/api/status', {
|
||||||
|
method: 'OPTIONS',
|
||||||
|
headers: {
|
||||||
|
Origin: 'https://api.milesallen.site',
|
||||||
|
'Access-Control-Request-Method': 'GET'
|
||||||
|
}
|
||||||
|
});
|
||||||
|
assert.equal(apiPreflight.status, 204);
|
||||||
|
assert.equal(apiPreflight.headers.get('access-control-allow-origin'), 'https://api.milesallen.site');
|
||||||
|
assert.equal(apiPreflight.headers.get('access-control-allow-credentials'), 'true');
|
||||||
|
assert.equal(apiPreflight.headers.get('access-control-expose-headers'), 'Retry-After');
|
||||||
|
|
||||||
const blocked = await fetch(base + '/api/status', {
|
const blocked = await fetch(base + '/api/status', {
|
||||||
headers: { Origin: 'https://evil.example' }
|
headers: { Origin: 'https://evil.example' }
|
||||||
});
|
});
|
||||||
assert.equal(blocked.status, 403);
|
assert.equal(blocked.status, 403);
|
||||||
|
|
||||||
|
const siteConfig = await fetch(base + '/site-config.js');
|
||||||
|
assert.equal(siteConfig.status, 200);
|
||||||
|
assert.match(await siteConfig.text(), /api\.milesallen\.site/);
|
||||||
|
|
||||||
const missing = await fetch(base + '/api/nope');
|
const missing = await fetch(base + '/api/nope');
|
||||||
assert.equal(missing.status, 404);
|
assert.equal(missing.status, 404);
|
||||||
const missingBody = await missing.json();
|
const missingBody = await missing.json();
|
||||||
@@ -108,6 +125,17 @@ test('Moon Vault content is server-gated and the old passphrase is gone from pub
|
|||||||
const deniedGame = await fetch(base + '/games/dino.html', { redirect: 'manual' });
|
const deniedGame = await fetch(base + '/games/dino.html', { redirect: 'manual' });
|
||||||
assert.equal(deniedGame.status, 302);
|
assert.equal(deniedGame.status, 302);
|
||||||
|
|
||||||
|
for (const encoded of [
|
||||||
|
'/games%2Fdino.html',
|
||||||
|
'/%67ames/dino.html',
|
||||||
|
'/games/%2564ino.html',
|
||||||
|
'/GAMES/dino.html',
|
||||||
|
'/Games/dino.html'
|
||||||
|
]) {
|
||||||
|
const bypass = await fetch(base + encoded, { redirect: 'manual' });
|
||||||
|
assert.equal(bypass.status, 302, `protected path must stay gated: ${encoded}`);
|
||||||
|
}
|
||||||
|
|
||||||
const badLogin = await fetch(base + '/api/vault/login', {
|
const badLogin = await fetch(base + '/api/vault/login', {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: { 'Content-Type': 'application/json' },
|
headers: { 'Content-Type': 'application/json' },
|
||||||
@@ -143,6 +171,12 @@ test('Moon Vault content is server-gated and the old passphrase is gone from pub
|
|||||||
assert.equal(game.status, 200);
|
assert.equal(game.status, 200);
|
||||||
assert.equal(game.headers.get('cache-control'), 'no-store', 'protected games must not be cached');
|
assert.equal(game.headers.get('cache-control'), 'no-store', 'protected games must not be cached');
|
||||||
|
|
||||||
|
const encodedGame = await fetch(base + '/games%2Fdino.html', {
|
||||||
|
headers: { Cookie: cookie },
|
||||||
|
redirect: 'manual'
|
||||||
|
});
|
||||||
|
assert.equal(encodedGame.status, 200, 'encoded protected paths work for authenticated sessions');
|
||||||
|
|
||||||
const logout = await fetch(base + '/api/vault/logout', {
|
const logout = await fetch(base + '/api/vault/logout', {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: { Cookie: cookie }
|
headers: { Cookie: cookie }
|
||||||
|
|||||||
@@ -45,6 +45,23 @@ test('config honors environment overrides without changing code', () => {
|
|||||||
assert.equal(config.monitor.expectedSubnet, '192.168.1.0/24');
|
assert.equal(config.monitor.expectedSubnet, '192.168.1.0/24');
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('production split-origin config allows the API and main site origins', () => {
|
||||||
|
const config = loadConfig({
|
||||||
|
NODE_ENV: 'production',
|
||||||
|
SESSION_SECRET: secret,
|
||||||
|
VAULT_PASSWORD: 'a local passphrase',
|
||||||
|
PUBLIC_ORIGIN: 'https://api.milesallen.site',
|
||||||
|
ALLOWED_ORIGINS: 'https://milesallen.site,https://www.milesallen.site'
|
||||||
|
});
|
||||||
|
|
||||||
|
assert.equal(config.publicOrigin, 'https://api.milesallen.site');
|
||||||
|
assert.ok(config.allowedOrigins.has('https://milesallen.site'));
|
||||||
|
assert.ok(config.allowedOrigins.has('https://www.milesallen.site'));
|
||||||
|
assert.ok(config.allowedOrigins.has('https://api.milesallen.site'));
|
||||||
|
assert.equal(config.cookie.sameSite, 'Strict');
|
||||||
|
assert.equal(config.cookie.secure, true);
|
||||||
|
});
|
||||||
|
|
||||||
test('production refuses missing or short session secrets', () => {
|
test('production refuses missing or short session secrets', () => {
|
||||||
assert.throws(
|
assert.throws(
|
||||||
() => loadConfig({ NODE_ENV: 'production', VAULT_PASSWORD: 'a local passphrase' }),
|
() => loadConfig({ NODE_ENV: 'production', VAULT_PASSWORD: 'a local passphrase' }),
|
||||||
|
|||||||
+6
-1
@@ -50,7 +50,12 @@ export function makeConfig(overrides = {}) {
|
|||||||
dbPath: path.join(tempDir, 'dashboard.db'),
|
dbPath: path.join(tempDir, 'dashboard.db'),
|
||||||
tempDir,
|
tempDir,
|
||||||
publicOrigin: 'http://localhost:8787',
|
publicOrigin: 'http://localhost:8787',
|
||||||
allowedOrigins: new Set(['http://localhost:8787', 'https://milesallen.site']),
|
allowedOrigins: new Set([
|
||||||
|
'http://localhost:8787',
|
||||||
|
'https://milesallen.site',
|
||||||
|
'https://www.milesallen.site',
|
||||||
|
'https://api.milesallen.site'
|
||||||
|
]),
|
||||||
sessionSecret: 'test-session-secret-that-is-long-enough-0123456789',
|
sessionSecret: 'test-session-secret-that-is-long-enough-0123456789',
|
||||||
trustProxy: false,
|
trustProxy: false,
|
||||||
cookie: {
|
cookie: {
|
||||||
|
|||||||
Reference in new issue
Block a user