-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
87 lines (69 loc) · 2.6 KB
/
server.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
const express = require("express");
const bodyParser = require("body-parser");
const ws = require("ws");
const crypto = require("crypto");
const { LTO, Binary } = require("@ltonetwork/lto");
const app = express();
const wsSockets = new Map();
const lto = new LTO(process.env.LTO_NETWORK_ID || 'T');
const port = process.env.PORT || 3000;
const wsServer = new ws.Server({ noServer: true, path: "/connect" });
wsServer.on('connection', async socket => {
const bytes = await crypto.randomBytes(32);
const code = new Binary(bytes).base58;
wsSockets.set(code, socket);
socket.on('close', () => {
wsSockets.delete(code);
});
socket.send(JSON.stringify({ code }));
// Expecting a response within 10m
setTimeout(() => socket.close(), 600000);
});
function clientError(res, status, message) {
res.status(status).write(message);
res.end();
}
app.use(bodyParser.json());
app.get('/', (req, res) => {
res.status(200).json({
name: "LTO Wallet Auth",
network: lto.networkId || lto.networkByte
});
res.end();
});
app.post('/:code', (req, res) => {
const {code} = req.params;
if (!wsSockets.has(code)) return clientError(res, 404, "Code is no longer active");
if (!req.body.publicKey) return clientError(res, 400, "Missing required body param 'publicKey'");
if (!req.body.signature) return clientError(res, 400, "Missing required body param 'signature'");
const account = lto.account({
keyType: req.body.keyType || 'ed25519',
publicKey: req.body.publicKey,
});
// Accept both with and without port
const messages = [...new Set([
`lto:sign:${req.protocol}://${req.hostname}${req.originalUrl}`,
`lto:sign:${req.protocol}://${req.hostname}:${port}${req.originalUrl}`,
`lto:sign:https://${req.hostname}${req.originalUrl}`,
`lto:sign:https://${req.hostname}:${port}${req.originalUrl}`,
])];
const verified = messages.filter(
msg => account.verify(msg, Binary.fromBase58(req.body.signature))
).length > 0;
if (!verified) {
return clientError(res, 400, "Invalid signature for " + `lto:sign:${req.protocol}://${req.hostname}${req.originalUrl}`);
}
wsSockets.get(code).send(JSON.stringify({
address: account.address,
keyType: account.keyType,
publicKey: account.publicKey,
}));
res.status(200).write('connected');
res.end();
})
const server = app.listen(port);
server.on('upgrade', (request, socket, head) => {
wsServer.handleUpgrade(request, socket, head, socket => {
wsServer.emit('connection', socket, request);
});
});