From 13a5bbafd6868b8793de6b67ac64f687b0f3453d Mon Sep 17 00:00:00 2001 From: Ben Ashton Date: Thu, 3 Dec 2026 15:33:08 -0700 Subject: [PATCH] Make deploy portable without my ssh key, add CLAUDE.md --- .env.example | 5 ++ .gitattributes | 3 + CLAUDE.md | 69 +++++++++++++++++++ package-lock.json | 88 ++++++++++++++++++++++++ package.json | 7 +- scripts/deploy.mjs | 163 +++++++++++++++++++++++++++++++++++++++++++++ vite.config.js | 17 ++++- 7 files changed, 349 insertions(+), 3 deletions(-) create mode 100644 .env.example create mode 100644 .gitattributes create mode 100644 CLAUDE.md create mode 100644 scripts/deploy.mjs diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..11a21dc --- /dev/null +++ b/.env.example @@ -0,0 +1,5 @@ +# Copy this file to .env and fill in the password. .env is never committed. +# This is the "Modify Password" chosen when the files container was created on +# n0m.org. It gives full access to the container, including everyone's saved +# climbs and photos, so keep it private. +N0M_MODIFY_PASSWORD= diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..9662904 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,3 @@ +# Shell scripts must keep Unix line endings on every OS, or bash on the server +# cannot run them +*.sh text eol=lf diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 0000000..4cea09c --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,69 @@ +# Climbing Tracker + +A climbing tracker for Alysia and her friends: log climbs (with photos), see progress, set goals, schedule group sessions. Alysia directs the work and has no coding experience, so explain things in plain language and choose sensible technical defaults rather than asking her technical questions. + +The app is live at https://n0m.org/act/ and real people's data is stored there. n0m.org is Ben's personal server and also hosts other things, so treat it gently (see "Things that can hurt n0m"). + +## Layout + +- `src/` — the React app (one page, built with Vite). All data handling goes through `api.sh` relative to the page. +- `cgi/api.sh` — the server-side data API, a bash CGI script built on `cgi/exprash.sh` (Ben's Express-like router for bash; treat it as a vendored library). +- `vite.config.js` — also contains a dev-server stand-in for `api.sh` that answers at the same addresses and stores data in `data/` locally. **Any change to `cgi/api.sh` needs the matching change here**, and vice versa. +- `scripts/deploy.mjs` — uploads `dist/` to n0m over SFTP. +- `data/` — local dev data only (gitignored). The real data is on the server. + +## Running and deploying + +- `npm run dev` — local version at http://localhost:5173 with its own separate test data. +- `npm run upload` — builds, uploads to the `act` container, then checks the live site serves the new page and that saved data still loads. + +Alysia has asked for changes to go online as soon as they are tested: test locally first, deploy, then tell her plainly that it is online (or that it failed). + +The deploy needs a `.env` file containing `N0M_MODIFY_PASSWORD` (see `.env.example`). It is the container's "Modify Password" and gives full read/write/delete access to everything in the container, including everyone's data. Never commit it, print it, or put it anywhere but `.env`. + +## What lives on the server + +Inside the `act` container, next to the uploaded app files: + +``` +data/users/.json one file per profile (climbs, goals, sessions, RSVPs…) +data/photos/-.jpg +data/backups/ one copy per profile per day, taken before that day's first save +data/.auth/ password hash for a profile +data/.auth/_pepper random secret mixed into the password hashes +``` + +**Never upload to, overwrite or delete anything under `data/`.** `deploy.mjs` refuses to run if `dist/` contains a `data/` folder; keep that check. + +A forgotten profile password is reset by deleting `data/.auth/` (over SFTP with the modify password, or Ben can do it). The next sign-in then asks for a new password. Deleting `_pepper` would invalidate every password. + +## How n0m serves a files container + +These quirks shaped the design. Check them before changing how the app talks to the server. + +- **Any non-executable file is downloadable** by URL, including files in dot folders, and folders are listable. Nothing in the container is private unless it is executable. +- **Executable files are run as CGI scripts** instead of being sent. That is why `api.sh` must keep its execute bit, and why the secret files in `data/.auth/` start with `#!/bin/true` and are mode 700: requesting them runs `true` and returns nothing. +- **Scripts run in a sandbox** (bubblewrap) with the container mounted read-write and **no network access**. So the server cannot send push notifications, emails or call other services. Standard tools from `/usr/bin` are available; do not assume `jq`. +- **Request bodies reach a script only if they are JSON or URL-encoded, and at most 100 KB.** Anything else arrives empty. This is why each profile is saved as one JSON document (it must stay under 100 KB), and why photos are compressed in the browser to 64 KB and sent as base64 inside JSON. +- **A URL that continues past a script's file name hangs forever** (e.g. `api.sh/users/x`). Use query strings (`api.sh?user=x`). +- **File types are guessed from content**, not extension, except `.js`, and `.css`/`.html` when the guess is plain text. The app's CSS is therefore inlined into the JS bundle rather than served as a stylesheet. +- **The first file whose name starts with `index` is served as the folder's page.** Do not put other `index*` files in the container root. `deploy.mjs` names its temporary files `deploy-tmp-…` for this reason. +- A script's response must start with a `Content-Type` header line (Exprash's `send` does this). + +## n0m's SFTP server + +`sftp://n0m.org:2222`, username = container keyword (`act`), password = the modify password. It is a small custom server, not OpenSSH: + +- SFTP only: no shell, no exec, so no rsync or scp. Password login only. +- Implemented: STAT, OPEN, READ, WRITE, CLOSE, OPENDIR/READDIR, MKDIR, RMDIR, REMOVE, RENAME, SETSTAT. +- Not implemented: LSTAT, FSETSTAT, symlinks. +- MKDIR fails if the folder exists. SETSTAT can only change the owner's execute bit. +- The host key fingerprint is pinned in `scripts/deploy.mjs`. + +## Things that can hurt n0m + +Ben knows the n0m code has rough edges and has asked that we avoid tripping them: + +- **Never chmod (SETSTAT) a path that does not exist** on the SFTP server. It has no error handling there and may take the whole n0m process down. `deploy.mjs` only chmods a file it has just uploaded. +- Prefer the operations `deploy.mjs` already uses over general-purpose SFTP clients, which lean on the unimplemented ones. +- If n0m itself misbehaves (every script on the site failing, uploads refused), that is Ben's to fix on the server. Tell Alysia to ask him rather than working around it. diff --git a/package-lock.json b/package-lock.json index 70fb119..745b4b1 100644 --- a/package-lock.json +++ b/package-lock.json @@ -12,6 +12,9 @@ "react": "^19.3.1", "react-dom": "^19.3.1", "vite": "^8.4.0" + }, + "devDependencies": { + "ssh2": "^1.17.0" } }, "node_modules/@oxc-project/types": { @@ -332,6 +335,51 @@ } } }, + "node_modules/asn1": { + "version": "0.2.6", + "resolved": "https://registry.npmjs.org/asn1/-/asn1-0.2.6.tgz", + "integrity": "sha512-ix/FxPn0MDjeyJ7i/yoHGFt/EX6LyNbxSEhPPXODPL+KB0VPk86UYfL0lMdy+KCnv+fmvIzySwaK5COwqVbWTQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "safer-buffer": "~2.1.0" + } + }, + "node_modules/bcrypt-pbkdf": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/bcrypt-pbkdf/-/bcrypt-pbkdf-1.0.2.tgz", + "integrity": "sha512-qeFIXtP4MSoi6NLqO12WfqARWWuCKi2Rn/9hJLEmtB5yTNr9DqFWkJRCf2qShWzPeAMRnOgCrq0sg/KLv5ES9w==", + "dev": true, + "license": "BSD-3-Clause", + "dependencies": { + "tweetnacl": "^0.14.3" + } + }, + "node_modules/buildcheck": { + "version": "0.0.7", + "resolved": "https://registry.npmjs.org/buildcheck/-/buildcheck-0.0.7.tgz", + "integrity": "sha512-lHblz4ahamxpTmnsk+MNTRWsjYKv965MwOrSJyeD588rR3Jcu7swE+0wN5F+PbL5cjgu/9ObkhfzEPuofEMwLA==", + "dev": true, + "optional": true, + "engines": { + "node": ">=10.0.0" + } + }, + "node_modules/cpu-features": { + "version": "0.0.10", + "resolved": "https://registry.npmjs.org/cpu-features/-/cpu-features-0.0.10.tgz", + "integrity": "sha512-9IkYqtX3YHPCzoVg1Py+o9057a3i0fp7S530UWokCSaFVTc7CwXPRiOjRjBQQ18ZCNafx78YfnG+HALxtVmOGA==", + "dev": true, + "hasInstallScript": true, + "optional": true, + "dependencies": { + "buildcheck": "~0.0.6", + "nan": "^2.19.0" + }, + "engines": { + "node": ">=10.0.0" + } + }, "node_modules/detect-libc": { "version": "2.1.2", "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz", @@ -633,6 +681,14 @@ "url": "https://opencollective.com/parcel" } }, + "node_modules/nan": { + "version": "2.30.0", + "resolved": "https://registry.npmjs.org/nan/-/nan-2.30.0.tgz", + "integrity": "sha512-P5mokDkSvCGBz6mZDD/2l+w9QoICRXdCyZ9ONGmTePr40oihJg3Kpn0YU3twKd6PJnwSlLBWNQeOT6yWEV2c4A==", + "dev": true, + "license": "MIT", + "optional": true + }, "node_modules/nanoid": { "version": "3.3.20", "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.20.tgz", @@ -769,6 +825,13 @@ "@rolldown/binding-win32-x64-msvc": "1.3.4" } }, + "node_modules/safer-buffer": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", + "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", + "dev": true, + "license": "MIT" + }, "node_modules/scheduler": { "version": "0.28.0", "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.28.0.tgz", @@ -784,6 +847,24 @@ "node": ">=6.0.0" } }, + "node_modules/ssh2": { + "version": "1.17.0", + "resolved": "https://registry.npmjs.org/ssh2/-/ssh2-1.17.0.tgz", + "integrity": "sha512-wPldCk3asibAjQ/kziWQQt1Wh3PgDFpC0XpwclzKcdT1vql6KeYxf5LIt4nlFkUeR8WuphYMKqUA56X4rjbfgQ==", + "dev": true, + "hasInstallScript": true, + "dependencies": { + "asn1": "^0.2.6", + "bcrypt-pbkdf": "^1.0.2" + }, + "engines": { + "node": ">=10.16.0" + }, + "optionalDependencies": { + "cpu-features": "~0.0.10", + "nan": "^2.23.0" + } + }, "node_modules/tinyglobby": { "version": "0.2.17", "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz", @@ -800,6 +881,13 @@ "url": "https://github.com/sponsors/SuperchupuDev" } }, + "node_modules/tweetnacl": { + "version": "0.14.5", + "resolved": "https://registry.npmjs.org/tweetnacl/-/tweetnacl-0.14.5.tgz", + "integrity": "sha512-KXXFFdAbFXY4geFIwoyNK+f5Z1b7swfXABfL7HXCmoIWMKU3dmS26672A4EeQtDzLKy7SXmfBu51JolvEKwtGA==", + "dev": true, + "license": "Unlicense" + }, "node_modules/vite": { "version": "8.4.0", "resolved": "https://registry.npmjs.org/vite/-/vite-8.4.0.tgz", diff --git a/package.json b/package.json index 2390b3b..314ae8c 100644 --- a/package.json +++ b/package.json @@ -8,13 +8,16 @@ }, "scripts": { "dev": "vite", - "build": "vite build && cp cgi/api.sh cgi/exprash.sh dist/ && chmod 755 dist/api.sh", - "upload": "npm run build && rsync -avH --exclude 'data/' -e 'ssh -p 24' ./dist/ \"ben@n0m.org:/home/ben/n0m/current/files/$npm_package_config_slug/\"" + "build": "vite build", + "upload": "npm run build && node scripts/deploy.mjs" }, "dependencies": { "@vitejs/plugin-react": "^6.3.0", "react": "^19.3.1", "react-dom": "^19.3.1", "vite": "^8.4.0" + }, + "devDependencies": { + "ssh2": "^1.17.0" } } diff --git a/scripts/deploy.mjs b/scripts/deploy.mjs new file mode 100644 index 0000000..ca255d8 --- /dev/null +++ b/scripts/deploy.mjs @@ -0,0 +1,163 @@ +#!/usr/bin/env node +// Uploads the built app (dist/) to its files container on n0m.org over SFTP. +// Run it with `npm run upload`, which builds first. +// +// n0m's SFTP server is not a full one, so this script sticks to the operations +// it implements: STAT, MKDIR, OPEN, WRITE, CLOSE, SETSTAT (owner execute bit +// only) and RENAME. See CLAUDE.md for the details. +import { Client } from 'ssh2' +import crypto from 'node:crypto' +import fs from 'node:fs' +import path from 'node:path' + +const HOST = 'n0m.org' +const PORT = 2222 +// Fingerprint of n0m's SFTP host key. The password is only sent to a server +// that proves it holds this key. Check it with: +// ssh-keyscan -p 2222 n0m.org | ssh-keygen -lf - +const HOST_KEY_FINGERPRINT = 'SHA256:LxJeC+keUAMPnSz7s1a7LagR/p/ZTDrB4jBsiN2AdSU' + +// Files that n0m must run as scripts rather than send as plain files +const EXECUTABLE = new Set(['api.sh']) +// Uploaded last and in this order, so the page never points at missing files +const UPLOAD_LAST = ['exprash.sh', 'api.sh', 'index.html'] +// Each file is uploaded under a temporary name and then renamed into place. +// The name must not start with "index", or n0m could serve it as the page. +const TMP_PREFIX = 'deploy-tmp-' +const CHUNK = 32 * 1024 + +const root = path.resolve(import.meta.dirname, '..') +const dist = path.join(root, 'dist') + +function fail(message) { + console.error(`\nUpload failed: ${message}`) + process.exit(1) +} + +// ---------- Settings ---------- +try { process.loadEnvFile(path.join(root, '.env')) } catch { /* no .env file */ } +const pkg = JSON.parse(fs.readFileSync(path.join(root, 'package.json'), 'utf8')) +const slug = process.env.N0M_SLUG || pkg.config?.slug +const password = process.env.N0M_MODIFY_PASSWORD +if (!slug) fail('No container keyword. Set "config.slug" in package.json.') +if (!password) fail('No password. Copy .env.example to .env and fill in N0M_MODIFY_PASSWORD.') + +// ---------- What to upload ---------- +function listFiles(dir, prefix = '') { + return fs.readdirSync(dir, { withFileTypes: true }).flatMap((entry) => { + const rel = prefix + entry.name + return entry.isDirectory() ? listFiles(path.join(dir, entry.name), `${rel}/`) : [rel] + }) +} +if (!fs.existsSync(path.join(dist, 'index.html'))) fail('dist/ has not been built. Run `npm run build` first.') +const order = (f) => UPLOAD_LAST.indexOf(f) // -1 for everything else +const files = listFiles(dist).sort((a, b) => order(a) - order(b) || a.localeCompare(b)) +// Everyone's saved climbs, passwords and photos live in data/ on the server. +// Nothing in a build should ever go there. +if (files.some((f) => f === 'data' || f.startsWith('data/'))) fail('dist/ contains a data/ folder. Refusing to upload over the saved data.') + +// ---------- SFTP helpers ---------- +const call = (sftp, method, ...args) => new Promise((resolve, reject) => { + sftp[method](...args, (err, result) => (err ? reject(err) : resolve(result))) +}) +const stat = (sftp, p) => call(sftp, 'stat', p).catch(() => null) + +async function ensureDir(sftp, dir) { + let current = '' + for (const part of dir.split('/').filter(Boolean)) { + current += (current ? '/' : '') + part + // n0m's MKDIR fails on a folder that already exists, so check first + if (!(await stat(sftp, current))) await call(sftp, 'mkdir', current) + } +} + +async function upload(sftp, rel) { + let bytes = fs.readFileSync(path.join(dist, rel)) + // Scripts must have Unix line endings or bash on the server can't run them + if (rel.endsWith('.sh')) bytes = Buffer.from(bytes.toString('utf8').replace(/\r\n/g, '\n')) + + // Files in assets/ are named after their contents, so same name and size means unchanged + if (rel.startsWith('assets/') && (await stat(sftp, rel))?.size === bytes.length) return 'unchanged' + + const dir = path.posix.dirname(rel) + if (dir !== '.') await ensureDir(sftp, dir) + const tmp = path.posix.join(dir, TMP_PREFIX + path.posix.basename(rel)) + + const handle = await call(sftp, 'open', tmp, 'w') + try { + for (let pos = 0; pos < bytes.length; pos += CHUNK) { + const length = Math.min(CHUNK, bytes.length - pos) + await call(sftp, 'write', handle, bytes, pos, length, pos) + } + } finally { + await call(sftp, 'close', handle) + } + + if ((await stat(sftp, tmp))?.size !== bytes.length) throw new Error(`${rel} did not arrive complete`) + // Only ever chmod a file that was just uploaded: n0m's SETSTAT does not cope + // with a path that doesn't exist + if (EXECUTABLE.has(rel)) await call(sftp, 'chmod', tmp, 0o755) + // The rename replaces the old file in one step, so visitors never see half a file + await call(sftp, 'rename', tmp, rel) + if (EXECUTABLE.has(rel) && !((await stat(sftp, rel))?.mode & 0o100)) throw new Error(`${rel} is not executable on the server`) + return `${bytes.length} bytes` +} + +// ---------- Connect and upload ---------- +function connect() { + return new Promise((resolve, reject) => { + const client = new Client() + let keyOk = false + client + .on('ready', () => client.sftp((err, sftp) => (err ? reject(err) : resolve({ client, sftp })))) + .on('error', (err) => { + if (!keyOk) return reject(new Error(`${HOST} did not present the expected host key, so the password was not sent. If Ben has changed n0m's SFTP key, update HOST_KEY_FINGERPRINT in scripts/deploy.mjs.`)) + if (err.level === 'client-authentication') return reject(new Error(`n0m refused the password for "${slug}". Check N0M_MODIFY_PASSWORD in .env.`)) + reject(err) + }) + .connect({ + host: HOST, + port: PORT, + username: slug, + password, + readyTimeout: 20000, + hostVerifier: (key) => { + const fingerprint = 'SHA256:' + crypto.createHash('sha256').update(key).digest('base64').replace(/=+$/, '') + keyOk = fingerprint === HOST_KEY_FINGERPRINT + return keyOk + }, + }) + }) +} + +// ---------- Check the live site afterwards ---------- +async function checkLive() { + const base = `https://${HOST}/${slug}/` + const page = await (await fetch(base, { cache: 'no-store' })).text() + const script = fs.readFileSync(path.join(dist, 'index.html'), 'utf8').match(/assets\/[^"]+\.js/)?.[0] + if (script && !page.includes(script)) throw new Error(`${base} is not serving the new page`) + const data = await (await fetch(`${base}api.sh`, { cache: 'no-store' })).json().catch(() => null) + if (!data || data.ok === false) throw new Error(`${base}api.sh is not returning saved data`) + return { base, profiles: Object.keys(data).length } +} + +console.log(`Uploading ${files.length} files to ${HOST}/${slug} …`) +let connection +try { + connection = await connect() + for (const rel of files) { + const result = await upload(connection.sftp, rel) + console.log(` ${rel} (${result})`) + } +} catch (err) { + connection?.client.end() + fail(err.message) +} +connection.client.end() + +try { + const { base, profiles } = await checkLive() + console.log(`\nDone. ${base} is serving the new version and its saved data loads (${profiles} profiles).`) +} catch (err) { + fail(`the files were uploaded, but the check afterwards failed: ${err.message}`) +} diff --git a/vite.config.js b/vite.config.js index ea30e41..0da70b6 100644 --- a/vite.config.js +++ b/vite.config.js @@ -103,8 +103,23 @@ function dataApi() { } } +// After a build, copies the server-side scripts into dist/ next to the page +function copyCgi() { + return { + name: 'copy-cgi', + apply: 'build', + closeBundle() { + const dist = path.resolve(import.meta.dirname, 'dist') + for (const file of ['api.sh', 'exprash.sh']) { + fs.copyFileSync(path.resolve(import.meta.dirname, 'cgi', file), path.join(dist, file)) + } + fs.chmodSync(path.join(dist, 'api.sh'), 0o755) + }, + } +} + export default defineConfig({ base: './', - plugins: [react(), dataApi()], + plugins: [react(), dataApi(), copyCgi()], server: { port: 5173, strictPort: true, host: 'localhost' }, })