-
Notifications
You must be signed in to change notification settings - Fork 0
/
worker.js
263 lines (252 loc) · 8.4 KB
/
worker.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
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
import { schnorr } from "@noble/curves/secp256k1";
// Relay info (NIP-11)
const relayInfo = {
name: "UNOstr",
description: "A reverse Nostr relay that ONLY requests events from all online relays",
pubkey: "d49a9023a21dba1b3c8306ca369bf3243d8b44b8f0b6d1196607f7b0990fa8df",
contact: "[email protected]",
supported_nips: [],
software: "https://github.com/Spl0itable/unostr",
version: "0.0.1",
};
// Relay favicon
const relayIcon = "https://raw.githubusercontent.com/Spl0itable/unostr/main/unostr-favicon-min.png";
// Nostr address NIP-05 verified users
const nip05Users = {
"lucas": "d49a9023a21dba1b3c8306ca369bf3243d8b44b8f0b6d1196607f7b0990fa8df",
// ... more NIP-05 verified users
};
// Handles upgrading to websocket and serving relay info
addEventListener("fetch", (event) => {
const { request } = event;
const url = new URL(request.url);
if (url.pathname === "/") {
if (request.headers.get("Upgrade") === "websocket") {
event.respondWith(handleWebSocket(event, request));
} else if (request.headers.get("Accept") === "application/nostr+json") {
event.respondWith(handleRelayInfoRequest());
} else {
event.respondWith(
new Response("Connect using a Nostr client", { status: 200 })
);
}
} else if (url.pathname === "/.well-known/nostr.json") {
event.respondWith(handleNIP05Request(url));
} else if (url.pathname === "/favicon.ico") {
event.respondWith(serveFavicon(event));
} else {
event.respondWith(new Response("Invalid request", { status: 400 }));
}
});
async function handleRelayInfoRequest() {
const headers = new Headers({
"Content-Type": "application/nostr+json",
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Headers": "Content-Type, Accept",
"Access-Control-Allow-Methods": "GET",
});
return new Response(JSON.stringify(relayInfo), { status: 200, headers: headers });
}
async function serveFavicon() {
const response = await fetch(relayIcon);
if (response.ok) {
const headers = new Headers(response.headers);
headers.set("Cache-Control", "max-age=3600");
return new Response(response.body, {
status: response.status,
headers: headers,
});
}
return new Response(null, { status: 404 });
}
async function handleNIP05Request(url) {
const name = url.searchParams.get("name");
if (!name) {
return new Response(JSON.stringify({ error: "Missing 'name' parameter" }), {
status: 400,
headers: { "Content-Type": "application/json" },
});
}
const pubkey = nip05Users[name.toLowerCase()];
if (!pubkey) {
return new Response(JSON.stringify({ error: "User not found" }), {
status: 404,
headers: { "Content-Type": "application/json" },
});
}
const response = {
names: {
[name]: pubkey,
},
relays: {
[pubkey]: [
// ... add relays for NIP-05 users
],
},
};
return new Response(JSON.stringify(response), {
status: 200,
headers: {
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "*",
},
});
}
// Handles websocket messages
async function handleWebSocket(event, request) {
const { 0: client, 1: server } = new WebSocketPair();
server.accept();
server.addEventListener("message", async (messageEvent) => {
event.waitUntil(
(async () => {
try {
const message = JSON.parse(messageEvent.data);
const messageType = message[0];
switch (messageType) {
case "EVENT":
await processEvent(message[1], server);
break;
case "REQ":
await processReq(message, server);
break;
case "CLOSE":
await closeSubscription(message[1], server);
break;
// Add more cases
}
} catch (e) {
sendError(server, "Failed to process the message");
console.error("Failed to process message:", e);
}
})()
);
});
server.addEventListener("close", (event) => {
console.log("WebSocket closed", event.code, event.reason);
});
server.addEventListener("error", (error) => {
console.error("WebSocket error:", error);
});
return new Response(null, {
status: 101,
webSocket: client,
});
}
// Handles EVENT message
async function processEvent(event, server) {
try {
const isValidSignature = await verifyEventSignature(event);
if (isValidSignature) {
sendOK(server, event.id, false, "Denied! This relay does not accept events.");
} else {
sendOK(server, event.id, false, "Invalid: signature verification failed.");
}
} catch (error) {
console.error("Error in EVENT processing:", error);
sendOK(server, event.id, false, `Error: EVENT processing failed - ${error.message}`);
}
}
// Handles REQ message
async function processReq(message, server) {
const subscriptionId = message[1];
const filters = message[2] || {};
const onlineRelays = await getOnlineRelays();
onlineRelays.forEach((relayUrl) => {
const socket = new WebSocket(relayUrl);
socket.addEventListener("open", () => {
const reqMessage = JSON.stringify(["REQ", subscriptionId, filters]);
socket.send(reqMessage);
});
socket.addEventListener("message", (event) => {
const [type, subId, eventData] = JSON.parse(event.data);
if (type === "EVENT" && subId === subscriptionId) {
server.send(JSON.stringify(["EVENT", subscriptionId, eventData]));
}
});
socket.addEventListener("error", (error) => {
console.error(`Error fetching events from relay ${relayUrl}:`, error);
});
socket.addEventListener("close", (event) => {
console.log(`WebSocket closed for ${relayUrl}`, event.code, event.reason);
});
});
}
// Handles CLOSE message
async function closeSubscription(subscriptionId, server) {
try {
server.send(JSON.stringify(["CLOSED", subscriptionId, "Subscription closed"]));
} catch (error) {
console.error("Error closing subscription:", error);
sendError(server, `error: failed to close subscription ${subscriptionId}`);
}
}
// Uses nostr.watch API for online relays
async function getOnlineRelays() {
try {
const response = await fetch("https://api.nostr.watch/v1/online");
if (response.ok) {
const data = await response.json();
return data;
} else {
console.error(`Failed to fetch online relays from primary endpoint. Status: ${response.status}`);
console.log("Trying backup endpoint...");
const backupResponse = await fetch("https://raw.githubusercontent.com/Spl0itable/unostr/main/relays");
if (backupResponse.ok) {
const backupData = await backupResponse.text();
const relays = backupData.split("\n").filter((relay) => relay.trim() !== "");
console.log("Fetched relays from backup endpoint.");
return relays;
} else {
console.error(`Failed to fetch online relays from backup endpoint. Status: ${backupResponse.status}`);
return [];
}
}
} catch (error) {
console.error("Error fetching online relays:", error);
return [];
}
}
// Verify event sig
async function verifyEventSignature(event) {
try {
const signatureBytes = hexToBytes(event.sig);
const serializedEventData = serializeEventForSigning(event);
const messageHashBuffer = await crypto.subtle.digest(
"SHA-256",
new TextEncoder().encode(serializedEventData)
);
const messageHash = new Uint8Array(messageHashBuffer);
const publicKeyBytes = hexToBytes(event.pubkey);
const signatureIsValid = schnorr.verify(signatureBytes, messageHash, publicKeyBytes);
return signatureIsValid;
} catch (error) {
console.error("Error verifying event signature:", error);
return false;
}
}
function serializeEventForSigning(event) {
const serializedEvent = JSON.stringify([
0,
event.pubkey,
event.created_at,
event.kind,
event.tags,
event.content,
]);
return serializedEvent;
}
function hexToBytes(hexString) {
if (hexString.length % 2 !== 0) throw new Error("Invalid hex string");
const bytes = new Uint8Array(hexString.length / 2);
for (let i = 0; i < bytes.length; i++) {
bytes[i] = parseInt(hexString.substr(i * 2, 2), 16);
}
return bytes;
}
// Sends event response to client
function sendOK(server, eventId, status, message) {
server.send(JSON.stringify(["OK", eventId, status, message]));
}
function sendError(server, message) {
server.send(JSON.stringify(["NOTICE", message]));
}