-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.ts
622 lines (528 loc) · 16.4 KB
/
app.ts
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
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
import { Bot, handleBotMessage } from "./bot.ts";
import {
DefaultEventRetension,
DefaultNIPs,
DefaultTimeRange,
SpamDetectPercent,
} from "./constant.ts";
import { decoder, hex, http, nostr } from "./deps.ts";
import { getHandler } from "./handler.ts";
import { handlePayment, LnurlPayment } from "./lnurl.ts";
import { PgRepo } from "./pg.ts";
import { SpamFilter } from "./spam.ts";
import { EventRetention, Limits, Nip11, Repository } from "./types.ts";
import { FeeType, parseEventRetention, parseFeeConfigure } from "./util.ts";
export class Application {
subs = new Map<WebSocket, Record<string, nostr.Filter[]>>();
challenges = new Map<WebSocket, string>();
authed = new Map<WebSocket, string>();
features: Record<string, string | number | boolean> = {};
repo: Repository;
payment: LnurlPayment | null = null;
bot: Bot | null = null;
channel: BroadcastChannel | null = null;
spam: SpamFilter | null = null;
port: number;
nip11: Nip11;
limits: Limits;
createdAtRange: number[];
botKey: string;
botPubkey = "";
relays: string[] = [];
pool: nostr.SimplePool;
retentions: EventRetention[] = DefaultEventRetension;
env: Record<string, string> = {};
// Whitelist pubkeys
pubkeys: string[] = [];
// Payment settings
fees = {
admission: [] as FeeType[],
subscription: [] as FeeType[],
publication: [] as FeeType[],
};
defaultPlan: FeeType | null = null;
constructor() {
const env = Deno.env.toObject();
this.env = env;
this.features = parseFeatures(this.env);
this.repo = new PgRepo(
env.DB_URL || "postgres://localhost:5432/nostring",
this,
);
if (env.PAYMENT_LNURL) {
if (!env.BOT_KEY) {
throw new Error("You should setup a BOT_KEY for handle payment.");
}
this.payment = new LnurlPayment(this);
}
this.createdAtRange = (env.EVENT_TIEMSTAMP_RANGE || DefaultTimeRange)
.split("~").map(parseInt);
if (this.createdAtRange.length !== 2) {
throw new Error("Invalid createdAt range");
}
this.port = parseInt(env.PORT || "9000");
this.limits = {
maxMessageLength: parseInt(env.MAX_MESSAGE_LENGTH) || 393216,
maxSubscriptions: parseInt(env.MAX_SUBSCRIPTIONS) || 32,
maxFilters: parseInt(env.MAX_FILTERS) || 10,
maxLimit: parseInt(env.MAX_LIMIT) || 500,
maxSubidLength: parseInt(env.MAX_SUBID_LENGTH) || 64,
minPrefix: parseInt(env.MIN_PREFIX) || 32,
maxEventTags: parseInt(env.MAX_EVENT_TAGS) || 2048,
maxContentLength: parseInt(env.MAX_CONTENT_LENGTH) || 102400,
minPowDifficulty: parseInt(env.MIN_POW_DIFFICULTY) || 0,
authRequired: env.AUTH_REQUIRED === "true",
paymentRequired: env.PAYMENT_REQUIRED === "true",
};
const arr = (env.BROADCAST_RELAYS || "").split(",");
this.pool = new nostr.SimplePool();
arr.forEach((i) => {
if (/^wss?\:\/\//.test(i)) {
this.relays.push(i);
this.pool.ensureRelay(i).then((relay) => {
console.log(`Broadcast relay ready: ${relay.url}`);
});
}
});
if (env.EVENT_RETENTION) {
this.retentions = parseEventRetention(env.EVENT_RETENTION);
}
if (env.WHITELIST_PUBKEYS) {
const keys = env.WHITELIST_PUBKEYS.split(",");
for (const i of keys) {
if (/^[a-f0-9]{64}$/.test(i)) this.pubkeys.push(i);
}
}
if (env.FEES_ADMISSION) {
this.fees.admission = parseFeeConfigure(env.FEES_ADMISSION);
}
if (env.FEES_SUBSCRIPTION) {
this.fees.subscription = parseFeeConfigure(env.FEES_SUBSCRIPTION);
}
if (env.FEES_PUBLICATION) {
this.fees.publication = parseFeeConfigure(env.FEES_PUBLICATION);
}
if (this.fees.admission.length) {
this.defaultPlan = this.fees.admission[0];
} else if (this.fees.subscription.length) {
this.defaultPlan = this.fees.subscription[0];
}
this.nip11 = {
name: env.RELAY_NAME || "nostring",
contact: env.ADMIN_CONTACT || "",
description: env.RELAY_DESC || "",
pubkey: env.ADMIN_PUBKEY || "",
software: "https://github.com/xbol0/nostring",
supported_nips: (env.NIPS || DefaultNIPs).split(",")
.map((i) => parseInt(i)),
version: "3.0.0-rc.2",
relay_countries: env.RELAY_COUNTRIES
? env.RELAY_COUNTRIES.split(",")
: void 0,
language_tags: env.LANGUAGE_TAGS ? env.LANGUAGE_TAGS.split(",") : void 0,
tags: env.TAGS ? env.TAGS.split(",") : void 0,
posting_policy: env.POSTING_POLICY,
limitation: this.limits,
fees: this.fees,
event_retention: this.retentions,
};
this.botKey = env.BOT_KEY;
if (this.botKey && /^[a-f0-9]{64}$/.test(this.botKey)) {
this.botPubkey = nostr.getPublicKey(this.botKey);
this.bot = new Bot(this.botKey, this);
}
if (
this.features.broadcastchannel && typeof BroadcastChannel !== "undefined"
) {
this.channel = new BroadcastChannel("nostr");
this.channel.addEventListener("message", (e) => {
try {
this.notify(JSON.parse(e.data));
} catch {
// Skip
console.log(e.data);
}
});
this.channel.addEventListener("messageerror", (e) => {
console.error(e.data);
});
}
if (this.features.spamfilter) {
this.spam = new SpamFilter(this.features.spamfilter as number);
}
}
addSocket(socket: WebSocket) {
socket.addEventListener("open", () => {
if (this.limits.authRequired) {
this.sendAuth(socket);
}
}, { once: true });
socket.addEventListener("error", () => {
this.subs.delete(socket);
this.challenges.delete(socket);
this.authed.delete(socket);
});
socket.addEventListener("close", () => {
this.subs.delete(socket);
this.challenges.delete(socket);
this.authed.delete(socket);
});
socket.addEventListener("message", (ev) => {
let data: [string, ...unknown[]];
const str = typeof ev.data === "string"
? ev.data
: decoder.decode(ev.data);
if (
this.limits.maxMessageLength &&
str.length > this.limits.maxMessageLength
) {
return this.send(socket, [
"NOTIFY",
"Message body size out of limits: " + this.limits.maxMessageLength,
]);
}
try {
data = JSON.parse(str);
if (!Array.isArray(data)) {
throw new Error("Not an Array");
}
if (data.length < 2) {
throw new Error("Array length should greater than 2");
}
if (typeof data[0] !== "string") {
throw new Error("Invalid message type");
}
if (
data[0] === "EVENT" &&
!nostr.validateEvent(data[1] as nostr.UnsignedEvent)
) {
throw new Error("Invalid event message");
}
if (
data[0] === "AUTH" &&
!nostr.validateEvent(data[1] as nostr.UnsignedEvent)
) {
throw new Error("Invalid auth message");
}
if (data[0] === "CLOSE" && typeof data[1] !== "string") {
throw new Error("Invalid close message");
}
if (data[0] === "REQ") {
if (typeof data[1] !== "string") {
throw new Error("Invalid req message");
}
if (data[1].length > this.limits.maxSubidLength) {
throw new Error("Subscription ID out of limit");
}
if (data.length < 3) {
throw new Error("Invalid req message");
}
if (!data.slice(2).every((i) => typeof i === "object" && i)) {
throw new Error("Invalid req message");
}
}
if (data[0] === "COUNT" && data.length === 3) {
if (typeof data[1] !== "string") {
throw new Error("Invalid count message");
}
if (typeof data[2] !== "object" || !data[2]) {
throw new Error("Invalid filter");
}
}
} catch (e) {
return this.send(socket, ["NOTIFY", "Invalid body: " + e.message]);
}
switch (data[0]) {
case "REQ":
return this.onREQ(
data[1] as string,
data.slice(2) as nostr.Filter[],
socket,
);
case "CLOSE":
return this.onCLOSE(data[1] as string, socket);
case "AUTH":
return this.onAUTH(data[1] as nostr.Event, socket);
case "EVENT":
return this.onEVENT(data[1] as nostr.Event, socket);
case "COUNT":
return this.onCOUNT(
data[1] as string,
data[2] as nostr.Filter,
socket,
);
default:
return this.send(socket, ["NOTIFY", `Unknown type: '${data[0]}'`]);
}
});
}
async onREQ(id: string, filters: nostr.Filter[], socket: WebSocket) {
let sub = this.subs.get(socket);
if (!sub) {
sub = {};
this.subs.set(socket, sub);
}
if (
this.limits.maxSubscriptions &&
Object.keys(sub).length > this.limits.maxSubscriptions
) {
return this.send(socket, [
"NOTIFY",
`${id}: Connection subscriptions out of limit`,
]);
}
if (this.limits.maxFilters && filters.length > this.limits.maxFilters) {
return this.send(socket, [
"NOTIFY",
`${id}: Subscription filters out of limit`,
]);
}
for (const i of filters) {
if (this.limits.authRequired && i.kinds?.includes(4)) {
if (!this.authed.has(socket)) {
this.send(socket, [
"NOTIFY",
`${id}: Kind 4 subscription needs authentication`,
]);
return this.sendAuth(socket);
}
}
if (Object.keys(i).filter((j) => j != "limit").length === 0) {
return this.send(socket, ["NOTIFY", "DO not pass empty filter"]);
}
}
sub[id] = filters;
for (const f of filters) {
try {
(await this.repo.query(f))
.forEach((i) => this.send(socket, ["EVENT", id, i]));
} catch (e) {
this.send(socket, ["NOTIFY", `${id}: ${e.message}`]);
return;
}
}
this.send(socket, ["EOSE", id]);
}
async onCOUNT(id: string, filter: nostr.Filter, socket: WebSocket) {
if (this.limits.authRequired && filter.kinds?.includes(4)) {
if (!this.authed.has(socket)) {
return this.send(socket, ["COUNT", id, { count: 0 }]);
}
}
if (Object.keys(filter).filter((j) => j != "limit").length === 0) {
return this.send(socket, ["COUNT", id, { count: 0 }]);
}
try {
this.send(socket, ["COUNT", id, {
count: await this.repo.count(filter),
}]);
} catch (e) {
console.error(e);
return this.send(socket, ["COUNT", id, { count: 0 }]);
}
}
async onEVENT(ev: nostr.Event, socket: WebSocket) {
if (ev.content.length > this.limits.maxContentLength) {
return this.send(socket, ["NOTIFY", "Content length out of limit"]);
}
if (
this.features.allow_unknown_kind && (ev.kind < 0 || ev.kind >= 40000)
) {
return this.send(socket, ["OK", ev.id, false, "invalid: Unknown kind"]);
}
if (ev.content.length > this.limits.maxContentLength) {
return this.send(socket, [
"OK",
ev.id,
false,
"invalid: Content length out of limit",
]);
}
if (ev.tags.length > this.limits.maxEventTags) {
return this.send(socket, [
"OK",
ev.id,
false,
"invalid: Event count out of limit",
]);
}
// NIP-22
const now = ~~(Date.now() / 1000);
if (
ev.created_at > now + this.createdAtRange[1] ||
ev.created_at < now + this.createdAtRange[0]
) {
return this.send(socket, [
"OK",
ev.id,
false,
"invalid: created_at field is out of the acceptable range",
]);
}
if (!nostr.verifySignature(ev)) {
return this.send(socket, [
"OK",
ev.id,
false,
"invalid: Unverified signature",
]);
}
// NIP-13: PoW
if (this.limits.minPowDifficulty) {
const pow = ev.tags.find((i) => i[0] === "nonce");
if (!pow) {
return this.send(socket, [
"NOTIFY",
"PoW less then " + this.limits.minPowDifficulty,
]);
}
const diff = parseInt(pow[2]);
if (diff < this.limits.minPowDifficulty) {
return this.send(socket, [
"NOTIFY",
"PoW less then " + this.limits.minPowDifficulty,
]);
}
const buf = hex.decode(ev.id.slice(0, Math.ceil(diff / 8) * 2));
const str = [...buf].map((i) => i.toString(2).padStart(8, "0")).slice(
diff,
);
if (!str.every((i) => i === "0")) {
return this.send(socket, ["NOTIFY", "Invalid POW"]);
}
}
// NIP-26
if (ev.tags.find((i) => i[0] === "delegation")) {
if (!nostr.nip26.getDelegator(ev)) {
return this.send(socket, ["NOTIFY", "Invalid delegation"]);
}
}
if (this.features.spamfilter && !this.spam!.filter(ev)) {
return this.send(socket, ["OK", ev.id, false, "invalid: Spam"]);
}
try {
await this.repo.save(ev);
} catch (err) {
return this.send(socket, ["OK", ev.id, false, `invalid: ${err.message}`]);
}
this.send(socket, ["OK", ev.id, true, ""]);
this.notify(ev);
if (
ev.kind === 4 && this.botKey &&
ev.tags.find((i) => i[0] === "p")?.[1] === this.botPubkey
) {
handleBotMessage(ev, this);
return;
}
if (
ev.kind === 9735 && this.payment && ev.pubkey === this.payment.pubkey &&
ev.tags.find((i) => i[0] === "p")?.[1] === this.botPubkey
) {
handlePayment(this, ev);
}
this.broadcast(ev);
if (this.channel) this.channel.postMessage(JSON.stringify(ev));
}
onCLOSE(id: string, socket: WebSocket) {
delete this.subs.get(socket)?.[id];
}
onAUTH(ev: nostr.Event, socket: WebSocket) {
if (ev.kind !== 22242) return;
const stored = ev.tags.find((i) => i[0] === "challenge");
if (!stored) return;
const challenge = this.challenges.get(socket);
if (stored[1] !== challenge) return;
if (!nostr.verifySignature(ev)) {
return this.send(socket, [
"OK",
ev.id,
false,
"invalid: Unverified signature",
]);
}
this.authed.set(socket, ev.pubkey);
this.challenges.delete(socket);
this.send(socket, ["OK", ev.id, true, ""]);
}
getHandler() {
return getHandler(this);
}
notify(ev: nostr.Event) {
for (const [ws, info] of this.subs.entries()) {
for (const [id, filters] of Object.entries(info)) {
if (nostr.matchFilters(filters, ev)) {
this.send(ws, ["EVENT", id, ev]);
}
}
}
}
send(socket: WebSocket, data: unknown[]) {
if (socket.readyState !== socket.OPEN) return;
try {
socket.send(JSON.stringify(data));
} catch {
// Skip error handle
}
}
sendAuth(socket: WebSocket) {
const c = crypto.randomUUID();
this.challenges.set(socket, c);
this.send(socket, ["AUTH", c]);
}
async report(s: string) {
if (!this.botKey || !this.nip11.pubkey) return;
try {
const ev = nostr.finishEvent({
kind: 4,
created_at: ~~(Date.now() / 1000),
tags: [["p", this.nip11.pubkey]],
content: await nostr.nip04.encrypt(this.botKey, this.nip11.pubkey, s),
}, this.botKey);
await this.repo.save(ev);
this.notify(ev);
this.broadcast(ev);
} catch (e) {
console.error("REPORT Error:", e);
}
}
broadcast(e: nostr.Event) {
if (!this.relays.length) return;
this.pool.publish(this.relays, e);
}
async serve() {
await this.repo.init();
await this.payment?.init();
await this.bot?.init();
await this.spam?.start();
http.serve(this.getHandler(), { port: this.port });
}
}
function parseFeatures(
env: Record<string, string>,
): Record<string, string | number | boolean> {
const obj: Record<string, string | number | boolean> = {};
if (
typeof env.ENABLE_BROADCASTCHANNEL !== "undefined" &&
env.ENABLE_BROADCASTCHANNEL !== "false"
) {
obj["broadcastchannel"] = true;
}
if (
typeof env.ENABLE_ALLOW_UNKNOWN_KIND !== "undefined" &&
env.ENABLE_ALLOW_UNKNOWN_KIND !== "false"
) {
obj["allow_unknown_kind"] = true;
}
if (
typeof env.DISABLE_NIP11 !== "undefined" &&
env.DISABLE_NIP11 !== "false"
) {
obj["disable_nip11"] = true;
}
if (env.SPAM_DETECT_PERCENT !== "0") {
obj["spamfilter"] = parseFloat(
env.SPAM_DETECT_PERCENT || SpamDetectPercent,
);
}
return obj;
}