Climbing-Tracker/vite.config.js
2026-12-03 15:10:17 -07:00

111 lines
4.8 KiB
JavaScript

import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import fs from 'node:fs'
import path from 'node:path'
import crypto from 'node:crypto'
// When running on this laptop, this saves the app's data to files inside the
// project (data/users/<id>.json). It answers at the same addresses as the
// hosted version, where cgi/api.sh does this job.
const dataDir = path.resolve(import.meta.dirname, 'data')
const usersDir = path.join(dataDir, 'users')
const legacyFile = path.join(dataDir, 'climbing-data.json')
const authDir = path.join(dataDir, '.auth')
const photosDir = path.join(dataDir, 'photos')
// Passwords work the same way as in cgi/api.sh: the browser sends a token in
// the X-Auth header and a SHA-256 of that token is kept in data/.auth/<id>
const validToken = (t) => /^[a-f0-9]{64}$/.test(t || '')
const tokenHash = (t) => crypto.createHash('sha256').update(t).digest('hex')
const authFile = (id) => path.join(authDir, id)
const hasPassword = (id) => fs.existsSync(authFile(id))
const passwordCorrect = (id, t) => validToken(t) && hasPassword(id) &&
fs.readFileSync(authFile(id), 'utf8').trim() === tokenHash(t)
function readAll() {
fs.mkdirSync(usersDir, { recursive: true })
// One-off move of the original single-person data into a profile
const first = path.join(usersDir, 'alysia.json')
if (fs.existsSync(legacyFile) && !fs.existsSync(first)) {
const old = JSON.parse(fs.readFileSync(legacyFile, 'utf8'))
fs.writeFileSync(first, JSON.stringify({ name: 'Alysia', ...old }))
fs.renameSync(legacyFile, legacyFile + '.old')
}
const all = {}
for (const file of fs.readdirSync(usersDir)) {
const id = file.replace(/\.json$/, '')
if (file.endsWith('.json') && /^[a-z0-9]+$/.test(id)) {
all[id] = JSON.parse(fs.readFileSync(path.join(usersDir, file), 'utf8'))
}
}
return all
}
function dataApi() {
return {
name: 'climbing-data-api',
configureServer(server) {
server.middlewares.use('/api.sh', (req, res) => {
const send = (code, obj) => {
res.statusCode = code
res.setHeader('Content-Type', 'application/json')
res.end(JSON.stringify(obj))
}
const { pathname, searchParams } = new URL(req.url, 'http://localhost')
const user = pathname === '/' && (searchParams.get('user') || '').match(/^([a-z0-9]{4,24})$/)
const token = req.headers['x-auth']
const check = searchParams.get('check')
if (req.method === 'GET' && pathname === '/' && check !== null) {
const valid = /^[a-z0-9]{4,24}$/.test(check)
send(200, { ok: valid && passwordCorrect(check, token), hasPassword: valid && hasPassword(check) })
} else if (req.method === 'GET' && pathname === '/') {
send(200, readAll())
} else if (req.method === 'PUT' && user) {
let body = ''
req.on('data', (c) => (body += c))
req.on('end', () => {
try {
JSON.parse(body)
const id = user[1]
const photoId = searchParams.get('photo')
if (photoId !== null) {
// Photo for a climb: { photo: "<base64 JPEG>" }, or "" to delete it
if (!/^[a-z0-9]{4,24}$/.test(photoId)) return send(400, { ok: false })
if (!passwordCorrect(id, token)) return send(403, { ok: false, auth: false })
const file = path.join(photosDir, `${id}-${photoId}.jpg`)
const bytes = Buffer.from(JSON.parse(body).photo || '', 'base64')
fs.mkdirSync(photosDir, { recursive: true })
if (bytes.length === 0) fs.rmSync(file, { force: true })
else if (bytes[0] === 0xff && bytes[1] === 0xd8 && bytes.length <= 72000) fs.writeFileSync(file, bytes)
else return send(400, { ok: false })
return send(200, { ok: true })
}
if (!validToken(token) || (hasPassword(id) && !passwordCorrect(id, token))) {
return send(403, { ok: false, auth: false })
}
// A profile without a password yet is claimed by the first save
fs.mkdirSync(authDir, { recursive: true })
if (!hasPassword(id)) fs.writeFileSync(authFile(id), tokenHash(token))
fs.mkdirSync(usersDir, { recursive: true })
const file = path.join(usersDir, user[1] + '.json')
fs.writeFileSync(file + '.tmp', body)
fs.renameSync(file + '.tmp', file)
send(200, { ok: true })
} catch (e) {
send(400, { ok: false })
}
})
} else {
send(404, { ok: false })
}
})
},
}
}
export default defineConfig({
base: './',
plugins: [react(), dataApi()],
server: { port: 5173, strictPort: true, host: 'localhost' },
})