Climbing-Tracker/scripts/deploy.mjs

164 lines
6.9 KiB
JavaScript

#!/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}`)
}