71 lines
1.8 KiB
JavaScript
71 lines
1.8 KiB
JavaScript
const express = require('express');
|
|
const { Level } = require('level');
|
|
const { recoverPersonalSignature } = require('@metamask/eth-sig-util');
|
|
// const { ecrecover, fromRpcSig, pubToAddress } = require('@ethereumjs/util');
|
|
// const { Keccak } = require('sha3');
|
|
const {
|
|
createHash,
|
|
} = require('node:crypto');
|
|
|
|
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 keccak = Keccak(256);
|
|
|
|
app.use(express.json());
|
|
|
|
app.post('/write', async (req, res) => {
|
|
const { body: { author, content, signature } } = req;
|
|
// Check author signature
|
|
try {
|
|
const account = recoverPersonalSignature({ data: content, signature });
|
|
if (account !== author) {
|
|
console.log('error: author does not match signature');
|
|
res.status(403).end();
|
|
return;
|
|
}
|
|
} catch (e) {
|
|
console.log('error: failed to recover signature:', e.message);
|
|
res.status(400).end();
|
|
return;
|
|
}
|
|
// Compute content hash
|
|
const data = { author, content, signature };
|
|
const hash = createHash('sha256').update(JSON.stringify(data)).digest('base64url');
|
|
console.log('write', hash);
|
|
// Store content
|
|
db.put(hash, data);
|
|
// Return hash
|
|
res.send(hash);
|
|
});
|
|
|
|
app.get('/read/:hash', async (req, res) => {
|
|
// Fetch content
|
|
const { hash } = req.params;
|
|
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;
|
|
}
|
|
console.log('read', hash);
|
|
// 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}`);
|
|
});
|