aboutsummaryrefslogtreecommitdiffstats
path: root/src/lib/nostr.ts
blob: 2e993f9d0ab1e6d93f04fdb1f52efec13541ed52 (plain) (blame)
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
import { Buffer } from "buffer";
import { browser } from "$app/environment";
import {
	decrypted,
	eventToSign,
	password as pw,
	passwordPrompt,
	signer as $signer,
} from "$lib/store";
import { post, wait } from "$lib/utils";
import { bytesToHex, hexToBytes } from "@noble/hashes/utils.js";
import {
	type EventTemplate,
	finalizeEvent,
	getEventHash,
	getPublicKey,
	nip04,
	nip19,
} from "nostr-tools";
import { decrypt as nip44decrypt, getConversationKey } from "nostr-tools/nip44";
import { Relay } from "nostr-tools/relay";
import { get } from "svelte/store";
import cookies from "js-cookie";

import {
	decrypt as nip49decrypt,
	encrypt as nip49encrypt,
} from "nostr-tools/nip49";

type User = {
	[key: string]: any;
};

type EncryptParams = {
	message: string;
	recipient: string;
	user: User;
};

export const encrypt = async ({ message, recipient, user }: EncryptParams) => {
	const sk = await getPrivateKey(user);
	return nip04.encrypt(sk, recipient, message);
};

export const decrypt = async ({ event, user }) => {
	const cache = get(decrypted);
	try {
		let { content, pubkey, id } = event;
		if (cache[id]) return cache[id];
		if (pubkey === user.pubkey) pubkey = event.tags[0][1];

		const message = await nip04.decrypt(
			await getPrivateKey(user),
			pubkey,
			content,
		);

		cache[id] = Buffer.from(message).toString("utf8");
		decrypted.set(cache);

		return cache[id];
	} catch (e) {
		// console.log(e);
	}
};

export const getPrivateKey = async (user: User): Promise<Uint8Array> => {
	let k;
	if (browser) {
		k = localStorage.getItem("nsec");
		if (k) {
			return nip19.decode(k).data as Uint8Array;
		}
	}

	// /me no longer returns the encrypted key; /login decrypts it into the
	// sk cookie instead. user.nsec is only present on a fresh login response.
	// Sessions without either (nostr or older logins) fetch it with the
	// password.
	const sk = browser && cookies.get("sk");
	let { nsec } = user;

	if (!sk && !nsec && user.hasnsec)
		({ nsec } = await post("/nsec", { password: await getPassword() }));

	if (sk) {
		k = hexToBytes(sk);
	} else if (nsec) {
		k = nip49decrypt(nsec, await getPassword());
	} else {
		throw new Error("Log in again with your password to unlock your nostr key");
	}

	localStorage.setItem("nsec", nip19.nsecEncode(k));
	return k;
};

const decodeNsec = (nsec: string): Uint8Array => {
	const { type, data } = nip19.decode(nsec);
	if (type === "nsec" && data instanceof Uint8Array) return data;
	throw new Error("invalid nsec");
};

export const getNsec = async (user: User) => {
	return nip19.nsecEncode(await getPrivateKey(user));
};

export const setNsec = async (user: User, nsec: string) => {
	user.pubkey = getPublicKey(decodeNsec(nsec));
	user.nsec = await encryptNsec(nsec);
};

export const encryptNsec = async (nsec: string) => {
	const d = decodeNsec(nsec);
	return nip49encrypt(d, await getPassword());
};

export const sign = async (event, user) => {
	if ((user?.hasnsec || user?.nsec) && !get($signer)?.ready) {
		const sk = await getPrivateKey(user);

		$signer.set({
			method: "nsec",
			ready: true,
			params: { sk: bytesToHex(sk), pk: getPublicKey(sk) },
		});
	}

	eventToSign.set(event);
	let unsubscribe;
	const { method, params } = await new Promise((r, j) => {
		unsubscribe = $signer.subscribe((v) => {
			if (v === "cancel") {
				j("cancelled");
				$signer.set(undefined);
			}
			v?.ready && r(v);
		});
	});
	await unsubscribe();
	const signedEvent = await signingMethods[method](event, params);
	eventToSign.set(signedEvent);
	setTimeout(() => eventToSign.set(null), 1000);
	return signedEvent;
};

export const send = (event: EventTemplate) => {
	return post("/events", { event });
};

const getPassword = async (): Promise<string> => {
	if (!get(pw)) passwordPrompt.set(true);
	await wait(() => !!get(pw));
	return get(pw) || "";
};

export const nostrConnectRelay = "wss://relay.nsec.app";

const signingMethods = {
	async connect(event, { sk, pk, pubkey }) {
		const id = crypto.randomUUID();
		const signEvent = {
			id,
			method: "sign_event",
			params: [JSON.stringify(event)],
		};

		const skBytes = hexToBytes(sk);
		const content = await nip04.encrypt(skBytes, pk, JSON.stringify(signEvent));

		const signedSignEvent = finalizeEvent(
			{
				created_at: Math.round(Date.now() / 1000),
				kind: 24133,
				pubkey,
				content,
				tags: [["p", pk]],
			},
			skBytes,
		);

		const relay = await Relay.connect(nostrConnectRelay);
		relay.publish(signedSignEvent);

		return new Promise((resolve) => {
			relay.subscribe([{ kinds: [24133], "#p": [pubkey] }], {
				async onevent(event) {
					pk = event.pubkey;
					try {
						let response;
						try {
							response = JSON.parse(await nip04.decrypt(hexToBytes(sk), pk, event.content));
						} catch (e) {
							const ck = await getConversationKey(hexToBytes(sk), pk);
							response = JSON.parse(await nip44decrypt(event.content, ck));
						}

						if (response.id === id) resolve(JSON.parse(response.result));
					} catch (e) {
						console.log("failed to parse nostr connect event", e);
					}
				},
			});
		});
	},

	async nsec(event, { sk }) {
		return finalizeEvent(event, hexToBytes(sk));
	},

	async extension(event) {
		return window.nostr.signEvent(event);
	},

	async signer(event, { pubkey, sig }) {
		event.pubkey = pubkey;
		const signedEvent = {
			...event,
			id: getEventHash(event),
			sig,
		};
		return signedEvent;
	},
};