-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
151 lines (132 loc) · 4.49 KB
/
index.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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
const HOME = require('os').homedir();
const fs = require('fs');
const base32 = require('bs32');
const blake3 = require('blake3');
const { Zone, wire, dnssec } = require('bns');
const { SOARecord, Record, codes, types } = wire;
const Replicator = require('@hyperswarm/replicator');
const Hyperzone = require('hyperzone');
const Cache = require('bns/lib/cache');
const empty = new Zone();
// todo: Class-ify
function middleware (dir) {
const zones = new Map();
const storageDir = dir || `${HOME}/.hyperzones/auth`;
const hyperzoneOpts = { sparse: true, alwaysUpdate: true };
const replicatorOpts = { client: true, server: true, live: true };
const replicator = new Replicator();
replicator.on('connection', (socket, info) => {
console.log('[hyperzone] connection @', base32.encode(info.publicKey));
});
replicator.on('error', err => console.error('[hyperzone] replication error :', err.message));
replicator.on('delete', (info) => {
console.log('[hyperzone] closed @', base32.encode(info.publicKey));
});
replicator.on('close', () => {
console.log('[hyperzone] closed.');
});
let loadedZones = false;
const put = (key, opts) => {
if (!key) {
return;
}
let buf;
if (typeof key === 'string') {
if (key.length === 52) {
buf = base32.decode(key);
} else if (key.length === 64) {
buf = Buffer.from(key, 'hex');
key = base32.encode(buf);
} else {
return;
}
} else if (Buffer.isBuffer(key)) {
buf = key;
key = base32.encode(buf);
} else {
return;
}
let zone = zones.get(key);
if (zone) {
return zone;
}
console.log(`[hyperzone] put : ${key}`);
const promise = new Promise(async (resolve) => {
const storage = `${storageDir}/${key}`;
zone = new Hyperzone(storage, buf, opts);
zones.set(key, zone);
resolve(zone);
replicator.add(zone.db, replicatorOpts)
.catch(err => console.error('[hyperzone] replication error :', (err.message || '').toLowerCase()));
await zone.ready();
const origin = await zone.origin();
zones.set(origin, zone);
});
zones.set(key, promise);
return promise;
};
try {
Promise.all(fs.readdirSync(storageDir).map(put))
.then(() => loadedZones = true)
.catch(console.error);
} catch (e) {}
return {
hostname: ':data.:protocol(_hyperzone|hyperzone).:gateway?.',
handler: async function ({ protocol, data }, name, type, response, rc, ns) {
if (name.indexOf(protocol) > 0) {
return null;
}
for (const [origin, zone] of zones.entries()) {
if (origin === ns.name) {
const res = await zone.resolve(name, type, origin);
try {
await handleCache(zone, res, name, type, origin, rc, this.cache);
} catch (err) {}
return res;
}
}
data = data.split('.');
const key = data[data.length - 1];
if (key.length === 52) {
const zone = await put(key);
if (zone.origin) {
const origin = await zone.origin();
if (origin) {
// cache (name, type, ns.name) -> cache_entry
// on new hyperzone data, lookup (name, type, ns.name) to fetch new data
// clear cache_entry if new data
const res = await zone.resolve(name, type, ns.name);
try {
await handleCache(zone, res, name, type, origin, rc, this.cache);
} catch (err) {}
return res;
}
}
const res = empty.resolve(name, types[type]);
res.code = codes.SERVFAIL; // ensure response not cached
return res;
} else {
return response;
}
}
};
}
module.exports = middleware;
async function handleCache (zone, res, name, type, origin, rc, cache) {
if (!rc.cacheHandlers) return;
rc.cacheHandlers.push(id => {
const oldData = blake3.hash([...res.answer, ...res.authority, ...res.additional].join('.')).toString('hex');
const handler = async () => {
const update = await zone.resolve(name, type, origin);
const newData = blake3.hash([...update.answer, ...update.authority, ...update.additional].join('.')).toString('hex');
if (oldData !== newData) {
console.log('[hyperzone] received update : stale cache cleared.');
cache.remove(id);
} else {
console.log('[hyperzone] received update : cache still fresh.');
zone.db.feed.update(handler);
}
};
zone.db.feed.update(handler);
});
}