first pass at nip42 authentication #93

Merged
LiranCohen merged 6 commits from feature/Nip42-Support into nip42 2023-01-25 14:45:00 +00:00
5 changed files with 91 additions and 17 deletions

View File

@ -77,6 +77,16 @@ export default function useEventPublisher() {
}
v0l commented 2023-01-25 10:32:34 +00:00 (Migrated from github.com)
Review

You can simply just not return anything here instead, undefined is fine

You can simply just not return anything here instead, undefined is fine
return {
nip42Auth: async (challenge: string, relay:string) => {
if(pubKey) {
const ev = NEvent.ForPubKey(pubKey);
ev.Kind = EventKind.Auth;
ev.Content = "";
ev.Tags.push(new Tag(["relay", relay], 0));
ev.Tags.push(new Tag(["challenge", challenge], 1));
return await signEvent(ev);
}
},
broadcast: (ev: NEvent | undefined) => {
if (ev) {
console.debug("Sending event: ", ev);

View File

@ -7,6 +7,7 @@ import { DefaultConnectTimeout } from "Const";
import { ConnectionStats } from "Nostr/ConnectionStats";
import { RawEvent, TaggedRawEvent, u256 } from "Nostr";
import { RelayInfo } from "./RelayInfo";
import { System } from "./System";
export type CustomHook = (state: Readonly<StateSnapshot>) => void;
@ -47,7 +48,9 @@ export default class Connection {
LastState: Readonly<StateSnapshot>;
IsClosed: boolean;
ReconnectTimer: ReturnType<typeof setTimeout> | null;
EventsCallback: Map<u256, () => void>;
EventsCallback: Map<u256, (msg?:any) => void>;
AwaitingAuth: Map<string, boolean>;
Authed: boolean;
constructor(addr: string, options: RelaySettings) {
this.Address = addr;
@ -72,6 +75,8 @@ export default class Connection {
this.IsClosed = false;
this.ReconnectTimer = null;
this.EventsCallback = new Map();
this.AwaitingAuth = new Map();
this.Authed = false;
this.Connect();
}
@ -118,18 +123,8 @@ export default class Connection {
OnOpen(e: Event) {
this.ConnectTimeout = DefaultConnectTimeout;
this._InitSubscriptions();
console.log(`[${this.Address}] Open!`);
// send pending
for (let p of this.Pending) {
this._SendJson(p);
}
this.Pending = [];
for (let [_, s] of this.Subscriptions) {
this._SendSubscription(s);
}
this._UpdateState();
}
OnClose(e: CloseEvent) {
@ -152,6 +147,12 @@ export default class Connection {
let msg = JSON.parse(e.data);
let tag = msg[0];
switch (tag) {
case "AUTH": {
this._OnAuthAsync(msg[1])
this.Stats.EventsReceived++;
this._UpdateState();
break;
}
case "EVENT": {
this._OnEvent(msg[1], msg[2]);
this.Stats.EventsReceived++;
@ -169,7 +170,7 @@ export default class Connection {
if (this.EventsCallback.has(id)) {
let cb = this.EventsCallback.get(id)!;
this.EventsCallback.delete(id);
cb();
cb(msg);
}
break;
}
@ -297,7 +298,25 @@ export default class Connection {
}
}
_InitSubscriptions() {
// send pending
for (let p of this.Pending) {
this._SendJson(p);
}
this.Pending = [];
for (let [_, s] of this.Subscriptions) {
this._SendSubscription(s);
}
this._UpdateState();
}
_SendSubscription(sub: Subscriptions) {
if(!this.Authed && this.AwaitingAuth.size > 0) {
this.Pending.push(sub);
return;
}
let req = ["REQ", sub.Id, sub.ToObject()];
if (sub.OrSubs.length > 0) {
req = [
@ -332,6 +351,40 @@ export default class Connection {
}
}
async _OnAuthAsync(challenge: string): Promise<void> {
const authCleanup = () => {
this.AwaitingAuth.delete(challenge)
}
this.AwaitingAuth.set(challenge, true)
const authEvent = await System.nip42Auth(challenge, this.Address)
return new Promise((resolve,_) => {
if(!authEvent) {
authCleanup();
return Promise.reject('no event');
}
let t = setTimeout(() => {
authCleanup();
resolve();
}, 10_000);
this.EventsCallback.set(authEvent.Id, (msg:any[]) => {
clearTimeout(t);
authCleanup();
if(msg.length > 3 && msg[2] === true) {
this.Authed = true;
this._InitSubscriptions();
}
resolve();
});
let req = ["AUTH", authEvent.ToObject()];
this._SendJson(req);
this.Stats.EventsSent++;
this._UpdateState();
})
}
_OnEnd(subId: string) {
let sub = this.Subscriptions.get(subId);
if (sub) {
@ -375,4 +428,4 @@ export default class Connection {
}
return ev;
}
}
}

View File

@ -7,7 +7,8 @@ const enum EventKind {
DirectMessage = 4, // NIP-04
Deletion = 5, // NIP-09
Repost = 6, // NIP-18
Reaction = 7 // NIP-25
Reaction = 7, // NIP-25
Auth = 22242 // NIP-42
};
export default EventKind;

View File

@ -211,6 +211,10 @@ export class NostrSystem {
setTimeout(() => this._FetchMetadata(), 500);
}
async nip42Auth(challenge: string, relay:string): Promise<Event|undefined> {
return
}
}
export const System = new NostrSystem();

View File

@ -1,18 +1,19 @@
import "./Layout.css";
import { useEffect } from "react"
import { useEffect, useMemo } from "react"
import { useDispatch, useSelector } from "react-redux";
import { Outlet, useNavigate } from "react-router-dom";
import { faBell, faMessage } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { RootState } from "State/Store";
import { init, setPreferences, UserPreferences } from "State/Login";
import { init, UserPreferences } from "State/Login";
import { HexKey, RawEvent, TaggedRawEvent } from "Nostr";
import { RelaySettings } from "Nostr/Connection";
import { System } from "Nostr/System"
import ProfileImage from "Element/ProfileImage";
import useLoginFeed from "Feed/LoginFeed";
import { totalUnread } from "Pages/MessagesPage";
import useEventPublisher from "Feed/EventPublisher";
export default function Layout() {
const dispatch = useDispatch();
@ -24,8 +25,13 @@ export default function Layout() {
const readNotifications = useSelector<RootState, number>(s => s.login.readNotifications);
v0l commented 2023-01-25 10:37:44 +00:00 (Migrated from github.com)
Review

I think it would be simpler to just attach a function to System at startup which can handle these auth methods, instead of using the window event listener

I think it would be simpler to just attach a function to `System` at startup which can handle these auth methods, instead of using the window event listener
LiranCohen commented 2023-01-25 13:41:21 +00:00 (Migrated from github.com)
Review

Yeah, that does seem cleaner.

I just made some changes and pushed.

Yeah, that does seem cleaner. I just made some changes and pushed.
const dms = useSelector<RootState, RawEvent[]>(s => s.login.dms);
const prefs = useSelector<RootState, UserPreferences>(s => s.login.preferences);
const pub = useEventPublisher();
useLoginFeed();
useMemo(() => {
System.nip42Auth = pub.nip42Auth
},[pub])
useEffect(() => {
if (relays) {
for (let [k, v] of Object.entries(relays)) {