dgf-prototype/backend/index.js

91 lines
2.1 KiB
JavaScript
Raw Normal View History

2024-03-19 22:22:36 -05:00
const express = require('express');
const { Level } = require('level');
2024-03-20 16:30:27 -05:00
const { recoverPersonalSignature } = require('@metamask/eth-sig-util');
const objectHash = require('object-hash');
2024-03-19 22:22:36 -05:00
require('dotenv').config();
const app = express();
const port = process.env.PORT || 3000;
const dataDir = process.env.DATA_DIR || 'data';
const db = new Level(`${dataDir}/forum`, { valueEncoding: 'json' });
const verifySignature = ({ author, content, signature }) => {
2024-03-20 16:30:27 -05:00
try {
const account = recoverPersonalSignature({ data: content, signature });
if (account !== author) {
console.log('error: author does not match signature');
return false;
2024-03-20 16:30:27 -05:00
}
} catch (e) {
console.log('error: failed to recover signature:', e.message);
return false;
}
return true;
};
app.use(express.json());
app.post('/write', async (req, res) => {
const { body: { author, content, signature } } = req;
// Check author signature
if (!verifySignature({ author, content, signature })) {
res.status(403).end();
2024-03-20 16:30:27 -05:00
return;
}
2024-03-19 22:22:36 -05:00
// Compute content hash
2024-03-20 16:30:27 -05:00
const data = { author, content, signature };
const hash = objectHash(data);
2024-03-19 22:22:36 -05:00
console.log('write', hash);
2024-03-19 22:22:36 -05:00
// Store content
db.put(hash, data);
2024-03-19 22:22:36 -05:00
// Return hash
res.send(hash);
});
app.get('/read/:hash', async (req, res) => {
const { hash } = req.params;
console.log('read', hash);
// Fetch content
2024-03-20 09:41:06 -05:00
let data;
try {
data = await db.get(req.params.hash);
} catch (e) {
console.log('read error:', e.message, hash);
res.status(e.status).end();
return;
}
// Verify hash
const derivedHash = objectHash(data);
if (derivedHash !== hash) {
console.log('error: hash mismatch');
res.status(500).end();
return;
}
// Verify signature
if (!verifySignature(data)) {
console.log('error: signature verificaition failed');
res.status(500).end();
return;
}
2024-03-19 22:22:36 -05:00
// Return content
res.json(data);
});
app.get('*', (req, res) => {
console.log(`req.path: ${req.path}`);
res.send('Hello World!');
});
app.listen(port, () => {
console.log(`Listening on port ${port}`);
});