diff options
| author | Adam Soltys <[email protected]> | 2026-01-28 22:51:34 -0800 |
|---|---|---|
| committer | Adam Soltys <[email protected]> | 2026-01-28 22:51:34 -0800 |
| commit | 568a936e08586b7ac07b4c7adaf5bf9b8ef6ba2f (patch) | |
| tree | 56a45c92cd37c8ba1d1d794d300af0462c86dbf3 /src/lib | |
| parent | 685d085596a1a20d2b5680cf8000313173bbe6fd (diff) | |
| parent | 838f74effb5b45e545bf68a4659e1e36c14da81f (diff) | |
| download | coinos-ui-nip17dm-fixes.tar.gz coinos-ui-nip17dm-fixes.zip | |
Merge remote-tracking branch 'origin/nip17dm'nip17dm-fixes
# Conflicts:
# .env.sample
Diffstat (limited to 'src/lib')
| -rw-r--r-- | src/lib/nip01.ts | 19 | ||||
| -rw-r--r-- | src/lib/nip07.ts | 42 | ||||
| -rw-r--r-- | src/lib/nip11.ts | 15 | ||||
| -rw-r--r-- | src/lib/nip17.ts | 223 | ||||
| -rw-r--r-- | src/lib/nip40.ts | 16 | ||||
| -rw-r--r-- | src/lib/nip44.ts | 135 | ||||
| -rw-r--r-- | src/lib/nip51.ts | 71 | ||||
| -rw-r--r-- | src/lib/nostr.ts | 11 |
8 files changed, 532 insertions, 0 deletions
diff --git a/src/lib/nip01.ts b/src/lib/nip01.ts new file mode 100644 index 00000000..a5d3f4b5 --- /dev/null +++ b/src/lib/nip01.ts @@ -0,0 +1,19 @@ +import { PUBLIC_DM_RELAYS, PUBLIC_COINOS_RELAY } from '$env/static/public'; +const DM_RELAYS_LIST = PUBLIC_DM_RELAYS.split(','); +const USERINFO_RELAYS = [ ...DM_RELAYS_LIST, PUBLIC_COINOS_RELAY ]; + +import { SimplePool } from 'nostr-tools/pool'; +const pool = new SimplePool(); + +// Returns the content of the kind-0 event of the provided pubkey. +export const getNostrUserInfo = async (pubkey: string) => { + const events = await pool.querySync( + USERINFO_RELAYS, { kinds: [0], limit: 1, authors: [pubkey] } + ); + + if (events.length == 0) { + return null; + } + + return JSON.parse(events[0].content); +} diff --git a/src/lib/nip07.ts b/src/lib/nip07.ts new file mode 100644 index 00000000..9f675950 --- /dev/null +++ b/src/lib/nip07.ts @@ -0,0 +1,42 @@ +import { bytesToHex } from '@noble/hashes/utils'; +import { finalizeEvent } from 'nostr-tools/pure'; +import { unwrapEvent } from 'nostr-tools/nip17'; +import { getPrivateKey } from '$lib/nostr'; +import * as libnip44 from '$lib/nip44'; +import { u } from '$lib/nip44'; + +// Signs an event using NIP-07 if available, otherwise getPrivateKey() +export const signEvent = async (event: object, user: object): object => { + if (await window.nostr.getPublicKey() === user.pubkey) { + return window.nostr.signEvent(event); + } else { + const sk = await getPrivateKey(); + return finalizeEvent(event, sk); + } +} + +// Encrypts an event in NIP-44 using NIP-07 if available, otherwise getPrivateKey() +export const encrypt = async (json: object, user: object, receiverPK: string): string => { + if (await window.nostr.getPublicKey() === user.pubkey) { + return window.nostr.nip44.encrypt( + receiverPK, JSON.stringify(json)); + } else { + const senderSK = await getPrivateKey(); + const senderSKString = bytesToHex(senderSK); + const ckey = u.getConversationKey(senderSKString, receiverPK); + return libnip44.encrypt(JSON.stringify(json), ckey); + } +} + +// Decrypts an event in NIP-44 using NIP-07 if available, otherwise getPrivateKey() +export const decrypt = async (encrypted: string, user: object, receiverPK: string): object => { + if (await window.nostr.getPublicKey() === user.pubkey) { + return JSON.parse(await window.nostr.nip44.decrypt( + receiverPK, encrypted)); + } else { + const senderSK = await getPrivateKey(); + const senderSKString = bytesToHex(senderSK); + const ckey = u.getConversationKey(senderSKString, receiverPK); + return JSON.parse(libnip44.decrypt(encrypted, ckey)); + } +} diff --git a/src/lib/nip11.ts b/src/lib/nip11.ts new file mode 100644 index 00000000..af254b7e --- /dev/null +++ b/src/lib/nip11.ts @@ -0,0 +1,15 @@ +import { fetchRelayInformation } from 'nostr-tools/nip11'; + +// Accepts a list of relays, and returns a list of the relays that support all the provided NIPs. +export const relaysSupporting = async (relays: string[], nips: number[]) => { + let supportingRelays = []; + + for (const relay of relays) { + const relayInfo = await fetchRelayInformation(relay); + if (nips.every(relay => relayInfo.supported_nips.includes(relay))) { + supportingRelays.push(relay); + } + } + + return supportingRelays; +} diff --git a/src/lib/nip17.ts b/src/lib/nip17.ts new file mode 100644 index 00000000..b128dab9 --- /dev/null +++ b/src/lib/nip17.ts @@ -0,0 +1,223 @@ +import { bytesToHex } from '@noble/hashes/utils'; + +import { finalizeEvent, getEventHash, generateSecretKey, getPublicKey } from 'nostr-tools/pure'; +import { SimplePool } from 'nostr-tools/pool'; +import { unwrapEvent } from 'nostr-tools/nip17'; + +import { getPrivateKey } from '$lib/nostr'; +import { relaysSupporting } from '$lib/nip11'; +import { expired, expiration } from '$lib/nip40'; +import { encrypt, u } from '$lib/nip44'; + +const TWO_DAYS = 2 * 24 * 60 * 60; +const randomTimestamp = () => Math.floor( + Date.now() / 1000 - Math.random() * TWO_DAYS); +const pool = new SimplePool(); +let relayListCache = new Map(); + +import { PUBLIC_DM_RELAYS } from '$env/static/public'; +const DM_RELAYS_LIST = PUBLIC_DM_RELAYS.split(','); +const DM_FETCH_LIMIT = 256; + +// Create a NIP-17 message using a provided sender secret key. +// If wrapPK is specified and different than receiverPK, +// the message will be gift-wrapped to wrapPK +// but the rumour will be sent to receiverPK. +// If expiryDays is specified, the message will expire in that many days, +// plus a random amount from 0 to 2 for security. +// (expiration time = random creation time + expiryDays + 2 days) +export const createNIP17MessageSK = (text: string, senderSK: Uint8Array, receiverPK: string, wrapPK: string = null, expiryDays: number = null) => { + const rumour = createRumour(text, getPublicKey(senderSK), receiverPK); + const sealed = sealRumourSK(rumour, senderSK, wrapPK || receiverPK, expiryDays); + return giftWrap(sealed, wrapPK || receiverPK, expiryDays); +} + +// Create a NIP-17 message using NIP-07, requiring no sender secret key. +// If wrapPK is specified and different than receiverPK, +// the message will be gift-wrapped to wrapPK +// but the rumour will be sent to receiverPK. +// If expiryDays is specified, the message will expire in that many days, +// plus a random amount from 0 to 2 for security. +// (expiration time = random creation time + expiryDays + 2 days) +export const createNIP17MessageNIP07 = async (text: string, senderPK: string, receiverPK: string, wrapPK: string = null, expiryDays: number = null) => { + const rumour = createRumour(text, senderPK, receiverPK); + const sealed = await sealRumourNip07(rumour, wrapPK || receiverPK, expiryDays); + return giftWrap(sealed, wrapPK || receiverPK, expiryDays); +} + +const createRumour = (text: string, senderPK: string, receiverPK: string) => { + const rumour = { + kind: 14, // rumour + created_at: Math.floor(Date.now() / 1000), + tags: [["p", receiverPK]], + pubkey: senderPK, + content: text + }; + rumour.id = getEventHash(rumour); // do NOT sign rumours! + return rumour; +} + +const sealRumourSK = (rumour: object, senderSK: Uint8Array, receiverPK: string, expiryDays: number = null) => { + const senderSKString = bytesToHex(senderSK); + const conversationKey = u.getConversationKey(senderSKString, receiverPK); + const encryptedRumour = encrypt(JSON.stringify(rumour), conversationKey); + + const created = randomTimestamp(); + const sealEvent = { + kind: 13, // seal + created_at: created, + tags: [], + pubkey: getPublicKey(senderSK), + content: encryptedRumour + } + if (expiryDays != null) { + const expiration = created + (expiryDays + 2) * 86400; + sealEvent.tags.push(["expiration", expiration.toString()]); + } + + return finalizeEvent(sealEvent, senderSK); +} + +const sealRumourNip07 = async (rumour: object, receiverPK: string, expiryDays: number = null) => { + const encryptedRumour = await window.nostr.nip44.encrypt( + receiverPK, JSON.stringify(rumour)); + + const created = randomTimestamp(); + const sealEvent = { + kind: 13, // seal + created_at: created, + tags: [], + content: encryptedRumour + } + if (expiryDays != null) { + const expiration = created + (expiryDays + 2) * 86400; + sealEvent.tags.push(["expiration", expiration.toString()]); + } + + return window.nostr.signEvent(sealEvent); +} + +const giftWrap = (event: object, receiverPK: string, expiryDays: number = null) => { + const secretKey = generateSecretKey(); + const SKString = bytesToHex(secretKey); + const conversationKey = u.getConversationKey(secretKey, receiverPK); + const encryptedEvent = encrypt(JSON.stringify(event), conversationKey); + const created = randomTimestamp(); + + const giftWrapEvent = { + kind: 1059, // gift wrap + created_at: created, + tags: [["p", receiverPK]], + pubkey: getPublicKey(secretKey), + content: encryptedEvent + } + if (expiryDays != null) { + const expiration = created + (expiryDays + 2) * 86400; + giftWrapEvent.tags.push(["expiration", expiration.toString()]); + } + + return finalizeEvent(giftWrapEvent, secretKey); +} + +const decryptNIP17MessageNIP07 = async (wrapped: object): object => { + const sealedText = await window.nostr.nip44.decrypt( + wrapped.pubkey, wrapped.content); + const sealed = JSON.parse(sealedText); + const rumourText = await window.nostr.nip44.decrypt( + sealed.pubkey, sealed.content); + return JSON.parse(rumourText); +} + +// Decrypts the provided message, addressed to the user. +// If NIP-07 is available, it uses that, otherwise it uses getPrivateKey(). +export const decrypt = async (wrapped: object, user: object): object => { + if (await window.nostr.getPublicKey() === user.pubkey) { + return decryptNIP17MessageNIP07(wrapped); + } else { + const sk = await getPrivateKey(user); + return unwrapEvent(wrapped, sk); + } + } + +// Returns the rumours of the messages the provided user has sent or received. +// If the events have an expiration timestamp, +// that timestamp is added to its rumour object as the property `expiration`. +export const getMessageRumours = async (user: object): object[] => { + const relays = await getPreferredRelays(user.pubkey); + const wrapped = await pool.querySync( + relays, { kinds: [1059], "#p": [user.pubkey], limit: DM_FETCH_LIMIT } + ); + + let rumours = []; + // intentionally decrypting sequentially to avoid having a bunch of popups + for (event of wrapped) { + if (expired(event)) { + console.log("relay(s) contain expired event", event.id); + continue; + } + + const rumour = await decrypt(event, user); + + const expires = expiration(event); + if (expires) { + rumour.expiration = expires; + } + + rumours.push(rumour); + } + + return rumours; +} + +// Returns the preferred relays of the user with the provided pubkey, +// according to their kind-10050 event. +export const getPreferredRelays = async (pubkey: string): string[] => { + if (relayListCache.has(pubkey)) + return relayListCache.get(pubkey); + + const events = await pool.querySync( + DM_RELAYS_LIST, { kinds: [10050], limit: 1, authors: [pubkey] } + ); + + let relays = []; + for (const event of events) { + for (const tag of event.tags) { + if (tag.length >= 2 && tag[0] == "relay") { + relays.push(tag[1]); + } + } + } + + relayListCache.set(pubkey, relays); + return relays; +} + +const publishToPreferred = async (event: object, pubkey: string, expiryEnabled: boolean): Promise<string> => { + let preferredRelays = await getPreferredRelays(pubkey); + if (expiryEnabled) { + preferredRelays = await relaysSupporting(preferredRelays, [40]); + } + return Promise.any(pool.publish(preferredRelays, event)); +} + +// Sends a NIP-17 message from `user` to `recipient`. +// If expiryDays is set, messages will expire after that many days. +export const send = async (message: string, user: object, recipient: object, expiryDays?: number) => { + let event1, event2; + if (await window.nostr.getPublicKey() === user.pubkey) { + event1 = await createNIP17MessageNIP07( + message, user.pubkey, recipient.pubkey, recipient.pubkey, expiryDays); + event2 = await createNIP17MessageNIP07( + message, user.pubkey, recipient.pubkey, user.pubkey, expiryDays); + } else { + const sk = await getPrivateKey(user); + event1 = createNIP17MessageSK( + message, sk, recipient.pubkey, recipient.pubkey, expiryDays); + event2 = createNIP17MessageSK( + message, sk, recipient.pubkey, user.pubkey, expiryDays); + } + + const p1 = publishToPreferred(event1, recipient.pubkey, expiryDays != null); + const p2 = publishToPreferred(event2, user.pubkey, expiryDays != null); + return Promise.all([p1, p2]); +} diff --git a/src/lib/nip40.ts b/src/lib/nip40.ts new file mode 100644 index 00000000..030fe0df --- /dev/null +++ b/src/lib/nip40.ts @@ -0,0 +1,16 @@ +// Returns true if the message has an expiration in the past, false otherwise. +export const expired = (event: object): boolean => { + const expiryTime = expiration(event); + return expiryTime !== null && Date.now() / 1000 >= expiryTime; +} + +// Returns the provided event's expiration time, as a Unix ms integer. +// If it has none, returns null. +export const expiration = (event: object): number | null => { + for (const tag of event.tags) { + if (tag[0] == "expiration") { + return parseInt(tag[1]); + } + } + return null; +} diff --git a/src/lib/nip44.ts b/src/lib/nip44.ts new file mode 100644 index 00000000..313d6f6b --- /dev/null +++ b/src/lib/nip44.ts @@ -0,0 +1,135 @@ +// Copied from this public-domain code:
+// https://github.com/paulmillr/nip44/blob/main/javascript/index.ts
+// Modified slightly to deal with a dependency issue
+
+import { chacha20 } from '@noble/ciphers/chacha';
+import { equalBytes } from '@noble/ciphers/utils';
+import { secp256k1 } from '@noble/curves/secp256k1';
+import { extract as hkdf_extract, expand as hkdf_expand } from '@noble/hashes/hkdf';
+import { hmac } from '@noble/hashes/hmac';
+import { sha256 } from '@noble/hashes/sha256';
+import { concatBytes, randomBytes, utf8ToBytes } from '@noble/hashes/utils';
+import { base64 } from '@scure/base';
+
+declare const TextDecoder: any;
+
+const decoder = new TextDecoder();
+export const u = {
+ minPlaintextSize: 0x0001, // 1b msg => padded to 32b
+ maxPlaintextSize: 0xffff, // 65535 (64kb-1) => padded to 64kb
+
+ utf8Encode: utf8ToBytes,
+ utf8Decode(bytes: Uint8Array) {
+ return decoder.decode(bytes);
+ },
+
+ getConversationKey(privkeyA: string, pubkeyB: string): Uint8Array {
+ const sharedX = secp256k1.getSharedSecret(privkeyA, '02' + pubkeyB).subarray(1, 33);
+ return hkdf_extract(sha256, sharedX, 'nip44-v2');
+ },
+
+ getMessageKeys(conversationKey: Uint8Array, nonce: Uint8Array) {
+ // ensureBytes(conversationKey, 32);
+ // ensureBytes(nonce, 32);
+ const keys = hkdf_expand(sha256, conversationKey, nonce, 76);
+ return {
+ chacha_key: keys.subarray(0, 32),
+ chacha_nonce: keys.subarray(32, 44),
+ hmac_key: keys.subarray(44, 76),
+ };
+ },
+
+ calcPaddedLen(len: number): number {
+ if (!Number.isSafeInteger(len) || len < 1) throw new Error('expected positive integer');
+ if (len <= 32) return 32;
+ const nextPower = 1 << (Math.floor(Math.log2(len - 1)) + 1);
+ const chunk = nextPower <= 256 ? 32 : nextPower / 8;
+ return chunk * (Math.floor((len - 1) / chunk) + 1);
+ },
+
+ writeU16BE(num: number) {
+ if (!Number.isSafeInteger(num) || num < u.minPlaintextSize || num > u.maxPlaintextSize)
+ throw new Error('invalid plaintext size: must be between 1 and 65535 bytes');
+ const arr = new Uint8Array(2);
+ new DataView(arr.buffer).setUint16(0, num, false);
+ return arr;
+ },
+
+ pad(plaintext: string): Uint8Array {
+ const unpadded = u.utf8Encode(plaintext);
+ const unpaddedLen = unpadded.length;
+ const prefix = u.writeU16BE(unpaddedLen);
+ const suffix = new Uint8Array(u.calcPaddedLen(unpaddedLen) - unpaddedLen);
+ return concatBytes(prefix, unpadded, suffix);
+ },
+
+ unpad(padded: Uint8Array): string {
+ const unpaddedLen = new DataView(padded.buffer).getUint16(0);
+ const unpadded = padded.subarray(2, 2 + unpaddedLen);
+ if (
+ unpaddedLen < u.minPlaintextSize ||
+ unpaddedLen > u.maxPlaintextSize ||
+ unpadded.length !== unpaddedLen ||
+ padded.length !== 2 + u.calcPaddedLen(unpaddedLen)
+ )
+ throw new Error('invalid padding');
+ return u.utf8Decode(unpadded);
+ },
+
+ hmacAad(key: Uint8Array, message: Uint8Array, aad: Uint8Array) {
+ if (aad.length !== 32) throw new Error('AAD associated data must be 32 bytes');
+ const combined = concatBytes(aad, message);
+ return hmac(sha256, key, combined);
+ },
+
+ // metadata: always 65b (version: 1b, nonce: 32b, max: 32b)
+ // plaintext: 1b to 0xffff
+ // padded plaintext: 32b to 0xffff
+ // ciphertext: 32b+2 to 0xffff+2
+ // raw payload: 99 (65+32+2) to 65603 (65+0xffff+2)
+ // compressed payload (base64): 132b to 87472b
+ decodePayload(payload: string) {
+ if (typeof payload !== 'string') throw new Error('payload must be a valid string');
+ const plen = payload.length;
+ if (plen < 132 || plen > 87472) throw new Error('invalid payload length: ' + plen);
+ if (payload[0] === '#') throw new Error('unknown encryption version');
+ let data: Uint8Array;
+ try {
+ data = base64.decode(payload);
+ } catch (error) {
+ throw new Error('invalid base64: ' + (error as any).message);
+ }
+ const dlen = data.length;
+ if (dlen < 99 || dlen > 65603) throw new Error('invalid data length: ' + dlen);
+ const vers = data[0];
+ if (vers !== 2) throw new Error('unknown encryption version ' + vers);
+ return {
+ nonce: data.subarray(1, 33),
+ ciphertext: data.subarray(33, -32),
+ mac: data.subarray(-32),
+ };
+ },
+};
+
+export function encrypt(plaintext: string, conversationKey: Uint8Array, nonce = randomBytes(32)): string {
+ const { chacha_key, chacha_nonce, hmac_key } = u.getMessageKeys(conversationKey, nonce);
+ const padded = u.pad(plaintext);
+ const ciphertext = chacha20(chacha_key, chacha_nonce, padded);
+ const mac = u.hmacAad(hmac_key, ciphertext, nonce);
+ return base64.encode(concatBytes(new Uint8Array([2]), nonce, ciphertext, mac));
+}
+
+export function decrypt(payload: string, conversationKey: Uint8Array): string {
+ const { nonce, ciphertext, mac } = u.decodePayload(payload);
+ const { chacha_key, chacha_nonce, hmac_key } = u.getMessageKeys(conversationKey, nonce);
+ const calculatedMac = u.hmacAad(hmac_key, ciphertext, nonce);
+ if (!equalBytes(calculatedMac, mac)) throw new Error('invalid MAC');
+ const padded = chacha20(chacha_key, chacha_nonce, ciphertext);
+ return u.unpad(padded);
+}
+
+export const v2 = {
+ utils: u,
+ encrypt,
+ decrypt,
+};
diff --git a/src/lib/nip51.ts b/src/lib/nip51.ts new file mode 100644 index 00000000..b1b0b613 --- /dev/null +++ b/src/lib/nip51.ts @@ -0,0 +1,71 @@ +import { SimplePool } from 'nostr-tools/pool'; +import { verifyEvent } from 'nostr-tools/pure'; +import { signEvent, encrypt, decrypt } from '$lib/nip07'; +const pool = new SimplePool(); + +import { PUBLIC_DM_RELAYS } from '$env/static/public'; +const DM_RELAYS_LIST = PUBLIC_DM_RELAYS.split(','); + +// Mute the provided pubkey, as the provided user. +export const mute = async (user: object, pubkey: string, hide: bool) => { + let { shown, hidden } = await getMuteLists(user); + if (hide) { + hidden.push(["p", pubkey]); + } else { + shown.push(["p", pubkey]); + } + await publishMuteList(user, shown, hidden); +} + +const tagMatches = (tag: string[], pubkey: string): bool => + tag.length >= 2 && tag[0] === "p" && tag[1] === pubkey; + +// Unmute the provided pubkey, as the provided user. +export const unmute = async (user: object, pubkey: string) => { + let { shown, hidden } = await getMuteLists(user); + shown = shown.filter(tag => !tagMatches(tag, pubkey)); + hidden = hidden.filter(tag => !tagMatches(tag, pubkey)); + await publishMuteList(user, shown, hidden); +} + +// Returns a set of the provided user's muted accounts. +export const mutedAccounts = async (user: object): Set<string> => { + const { shown, hidden } = await getMuteLists(user); + let muted = new Set<string>(); + for (const tag of shown) { + if (tag.length >= 2 && tag[0] === "p") { + muted.add(tag[1]); + } + } + for (const tag of hidden) { + if (tag.length >= 2 && tag[0] === "p") { + muted.add(tag[1]); + } + } + return muted; +} + +const getMuteLists = async (user: object): object => { + const listEvents = await pool.querySync( + DM_RELAYS_LIST, { kinds: [10000], "authors": [user.pubkey], limit: 1 } + ); + if (listEvents.length == 0) { + return { shown: [], hidden: [] }; + } + + return { + shown: listEvents[0].tags, + hidden: listEvents[0].content == "" ? [] : + await decrypt(listEvents[0].content, user, user.pubkey) + }; +} + +const publishMuteList = async (user: object, shown: string[], hidden: string[]) => { + const event = await signEvent({ + kind: 10000, + created_at: Math.floor(Date.now() / 1000), + tags: shown, + content: await encrypt(hidden, user, user.pubkey) + }, user); + return Promise.any(pool.publish(DM_RELAYS_LIST, event)); +} diff --git a/src/lib/nostr.ts b/src/lib/nostr.ts index a22882bc..beebba02 100644 --- a/src/lib/nostr.ts +++ b/src/lib/nostr.ts @@ -210,3 +210,14 @@ const signingMethods = { return signedEvent; }, }; + +// Returns all the keys mentioned in the provided event's 'p' tags. +export const pTagKeys = (event: object): string[] => { + let keys = []; + for (const tag of event.tags) { + if (tag[0] === "p") { + keys.push(tag[1]); + } + } + return keys; +} |
