minimal nip-96 file server behind tor

upload
curl --socks5-hostname 127.0.0.1:9050 -X POST -H "Content-Type: multipart/form-data" -F "file=@test.txt" http://s6mn26rvxxoiezkh43e42on4nsnj2etpkvy7pjkj4rgpv7n5n4gjgqyd.onion/upload

app.js

const express = require('express')
const multer  = require('multer')
const crypto = require('crypto')
const fs = require('fs/promises')
const fs_ = require('fs')
const path = require('path')
const upload = multer({ dest: 'uploads/' })
const app = express();
const port = 8000
const baseurl = "http://s6mn26rvxxoiezkh43e42on4nsnj2etpkvy7pjkj4rgpv7n5n4gjgqyd.onion"

app.post('/upload', upload.single('file'), async (req, res, next) => {
  const file = req.file;
  if (!file) {
    const error = new Error('Please upload a file');
    error.httpStatusCode = 400;
    return next(error);
  }

  console.log("file", file)

  const fileBuffer = await fs.readFile(file.path);
  const hashSum = crypto.createHash('sha256')
  hashSum.update(fileBuffer)
  const hash = hashSum.digest('hex')

  await fs.rename(file.path, "uploads/" + hash)

  await fs.writeFile("uploads/" + hash + ".json", JSON.stringify({
    mimetype: file.mimetype
  }))

  res.send(JSON.stringify({
    status: "success",
    message: "Upload successful",
    nip94_event: {
      tags: [
        ["url", baseurl + "/uploads/" + hash],
        ["ox", hash],
      ],
      content: ""
    }
  }))
})

app.get('/uploads/:hash', async (req, res) => {
  const filename = "uploads/" + req.params.hash + ".json"
  console.log(req.params.hash)

  if(!await fs_.existsSync(filename)){
    res.send("404")
    res.status(404)
    return
  }

  try{
    const info = JSON.parse(await fs.readFile(filename))
    res.set("Content-Type", info.mimetype)
  }catch(e){
    console.log("info file does not exist for hash " + req.params.hash)
  }

  res.sendFile(path.join(__dirname, 'uploads/' + req.params.hash))
})

app.listen(port, () => {
  console.log('Server is listening on port ' + port);
})
Edit

Pub: 01 Feb 2024 14:34 UTC

Edit: 01 Feb 2024 14:59 UTC

Views: 68