allow publishing events from allowed pubkeys without auth, if env variable is set
This commit is contained in:
parent
3367cb929b
commit
22a4fe069f
2 changed files with 13 additions and 5 deletions
3
index.ts
3
index.ts
|
@ -1,7 +1,8 @@
|
|||
import { main } from "./src/main.ts";
|
||||
|
||||
let allowUnauthedPublish = Boolean(process.env.ALLOW_UNAUTHED_PUBLISH) || false;
|
||||
let relay = process.env.RELAY_URL ?? Bun.argv[Bun.argv.length - 1];
|
||||
if (!relay?.startsWith("wss://") && !relay?.startsWith("ws://"))
|
||||
relay = "wss://relay.arx-ccn.com";
|
||||
|
||||
main(relay)
|
||||
main(relay, allowUnauthedPublish)
|
||||
|
|
15
src/main.ts
15
src/main.ts
|
@ -16,23 +16,26 @@ type Nip42ProxySocketData = {
|
|||
remoteWs: WebSocket;
|
||||
};
|
||||
|
||||
async function validateAuthEvent(event: Event, challenge: string): boolean {
|
||||
async function validateAuthEvent(event: Event, challenge: string): Promise<boolean> {
|
||||
if (event.kind !== 22242) return false;
|
||||
const last30Seconds = Math.floor(Date.now() / 1000) - 30;
|
||||
if (event.created_at < last30Seconds) return false;
|
||||
const challengeTag = event.tags.find(tag => tag[0] === 'challenge')?.[1];
|
||||
if (challengeTag !== challenge) return false;
|
||||
return await isPubkeyAllowed(event);
|
||||
}
|
||||
|
||||
async function isPubkeyAllowed(event: Event): Promise<boolean> {
|
||||
const file = Bun.file("./allowed-pubkeys.json");
|
||||
if (!await file.exists()) return true;
|
||||
const allowedPubkeys = JSON.parse(await file.text());
|
||||
if (!allowedPubkeys.includes(event.pubkey)) return false;
|
||||
return true;
|
||||
return allowedPubkeys.includes(event.pubkey);
|
||||
}
|
||||
|
||||
const sendMessage = (ws: ServerWebSocket<Nip42ProxySocketData>, message: any[]) => ws.send(JSON.stringify(message), true);
|
||||
const sendAuth = (ws: ServerWebSocket<Nip42ProxySocketData>) => sendMessage(ws, ["AUTH", ws.data.authToken, "This is an authenticated relay."]);
|
||||
|
||||
export function main(mainRelayUrl: string) {
|
||||
export function main(mainRelayUrl: string, allowUnauthedPublish: boolean) {
|
||||
const server = Bun.serve<Nip42ProxySocketData, {}>({
|
||||
fetch(req, server) {
|
||||
const upgrade = server.upgrade(req, {
|
||||
|
@ -54,6 +57,10 @@ export function main(mainRelayUrl: string) {
|
|||
}
|
||||
if (command === "EVENT") {
|
||||
const [event] = data;
|
||||
if (allowUnauthedPublish && await isPubkeyAllowed(event)) {
|
||||
ws.data.remoteWs.send(msg);
|
||||
return;
|
||||
}
|
||||
sendMessage(ws, ["OK", event.id, false, 'auth-required: you must authenticate first']);
|
||||
}
|
||||
if (command === "AUTH") {
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue