aboutsummaryrefslogtreecommitdiffstats
path: root/src/lib/nip17.ts
blob: 707417860b80289f3868b7f9103d58adff6223ac (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
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
import { bytesToHex, hexToBytes } from '@noble/hashes/utils';

import { finalizeEvent, getEventHash, generateSecretKey, getPublicKey } from 'nostr-tools/pure';
import { SimplePool } from 'nostr-tools/pool';
import { Relay } from 'nostr-tools/relay';
import { unwrapEvent } from 'nostr-tools/nip17';

import { ensureSigner } from '$lib/nip07';
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 = 65536;

// 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 triggers the signer modal.
export const decrypt = async (wrapped: object, user: object): object => {
    const sk = await ensureSigner(user.pubkey);

    if (sk === null) {
        return decryptNIP17MessageNIP07(wrapped);
    } else {
        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 preferredRelays = await getPreferredRelays(user.pubkey);
    // Always include default relays to catch messages that might be there
    const relays = [...new Set([...preferredRelays, ...DM_RELAYS_LIST])];
    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 (const event of wrapped) {
        if (expired(event)) {
            console.log("relay(s) contain expired event", event.id);
            continue;
        }

        try {
            const rumour = await decrypt(event, user);

            const expires = expiration(event);
            if (expires) {
                rumour.expiration = expires;
            }

            rumours.push(rumour);
        } catch (e) {
            console.error('Failed to decrypt event:', event.id, e);
        }
    }

    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]);
            }
        }
    }

    // Fall back to default DM relays if user hasn't published their preferred relays
    if (relays.length === 0) {
        relays = DM_RELAYS_LIST;
    }

    relayListCache.set(pubkey, relays);
    return relays;
}

// Publish to a single relay with NIP-42 auth support
const publishWithAuth = async (relayUrl: string, event: object, sk: Uint8Array | null): Promise<string> => {
    const relay = await Relay.connect(relayUrl);

    const signAuthEvent = async (authEvent: object) => {
        if (sk) {
            return finalizeEvent(authEvent, sk);
        } else if (window.nostr) {
            return await window.nostr.signEvent(authEvent);
        }
        throw new Error('No signing method for auth');
    };

    try {
        return await relay.publish(event);
    } catch (e) {
        // Check if it's an auth error
        if (e?.message?.includes('auth-required')) {
            // Authenticate and retry
            await relay.auth(signAuthEvent);
            return await relay.publish(event);
        }
        throw e;
    }
};

// Store the current sk for use in publish
let currentSk: Uint8Array | null = null;

const publishToPreferred = async (event: object, pubkey: string, expiryEnabled: boolean): Promise<string> => {
    let preferredRelays = await getPreferredRelays(pubkey);
    if (expiryEnabled) {
        preferredRelays = await relaysSupporting(preferredRelays, [40]);
    }
    if (preferredRelays.length === 0) {
        throw new Error('No relays available to publish to');
    }

    const promises = preferredRelays.map(url => publishWithAuth(url, event, currentSk));
    try {
        return await Promise.any(promises);
    } catch (e) {
        const results = await Promise.allSettled(promises);
        console.error('All relay publishes failed:', results);
        throw e;
    }
}

const createAndPublishMessageEvent = async (sk: Uint8Array, message: string, userPK: string, recipientPK: string, eventFor: string, expiryDays?: number) => {
    let event;
    if (sk === null) { // Use NIP-07 extension
        event = await createNIP17MessageNIP07(
            message, userPK, recipientPK, eventFor, expiryDays);
    } else {
        event = createNIP17MessageSK(
            message, sk, recipientPK, eventFor, expiryDays);
    }

    return publishToPreferred(event, eventFor, expiryDays != null);
}

// 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) => {
    const sk = await ensureSigner(user.pubkey);

    // Store sk for auth handler
    currentSk = sk;

    if (user.pubkey === recipient.pubkey) {
        return createAndPublishMessageEvent(
            sk, message, user.pubkey, recipient.pubkey, user.pubkey, expiryDays);
    } else {
        const p1 = createAndPublishMessageEvent(
            sk, message, user.pubkey, recipient.pubkey, recipient.pubkey, expiryDays);
        const p2 = createAndPublishMessageEvent(
            sk, message, user.pubkey, recipient.pubkey, user.pubkey, expiryDays);
        return Promise.all([p1, p2]);
    }
}