diff options
| author | Adrien Hopkins <[email protected]> | 2025-08-26 20:14:08 -0500 |
|---|---|---|
| committer | Adrien Hopkins <[email protected]> | 2025-08-26 20:14:08 -0500 |
| commit | e7dc3dc7c42803f6c5f020055a00af5f9d89d8a9 (patch) | |
| tree | 3102f6b70c6c5a8e50cc7efa2b8aeffadf3a6026 /src/lib/nip17.ts | |
| parent | 0df147447bdc08069e1e7b1cbfe116dbabf00233 (diff) | |
| download | coinos-ui-e7dc3dc7c42803f6c5f020055a00af5f9d89d8a9.tar.gz coinos-ui-e7dc3dc7c42803f6c5f020055a00af5f9d89d8a9.zip | |
Add improved NIP-17 code
This is based on an audited NIP-44 implementation.
Diffstat (limited to 'src/lib/nip17.ts')
| -rw-r--r-- | src/lib/nip17.ts | 59 |
1 files changed, 59 insertions, 0 deletions
diff --git a/src/lib/nip17.ts b/src/lib/nip17.ts new file mode 100644 index 00000000..66f49639 --- /dev/null +++ b/src/lib/nip17.ts @@ -0,0 +1,59 @@ +import { bytesToHex } from '@noble/hashes/utils'; +import { finalizeEvent, getEventHash, generateSecretKey, getPublicKey } from 'nostr-tools/pure'; +import { encrypt, u } from '$lib/nip44'; + +const TWO_DAYS = 2 * 24 * 60 * 60; +const randomTimestamp = () => Math.floor( + Date.now() / 1000 - Math.random() * TWO_DAYS); + +export const createNIP17Message = (text: string, senderSK: Uint8Array, receiverPK: string) => { + const rumour = createRumour(text, senderSK, receiverPK); + const sealed = sealRumour(rumour, senderSK, receiverPK); + const wrapped = giftWrap(sealed, receiverPK); + return wrapped; +} + +const createRumour = (text: string, senderSK: Uint8Array, receiverPK: string) => { + const rumour = { + kind: 14, // rumour + created_at: Math.floor(Date.now() / 1000), + tags: [["p", receiverPK]], + pubkey: getPublicKey(senderSK), + content: text + }; + rumour.id = getEventHash(rumour); + return rumour; +} + +const sealRumour = (rumour: object, senderSK: Uint8Array, receiverPK: string) => { + const senderSKString = bytesToHex(senderSK); + const conversationKey = u.getConversationKey(senderSKString, receiverPK); + const encryptedRumour = encrypt(JSON.stringify(rumour), conversationKey); + + const sealEvent = { + kind: 13, // seal + created_at: randomTimestamp(), + tags: [], + pubkey: getPublicKey(senderSK), + content: encryptedRumour + } + + return finalizeEvent(sealEvent, senderSK); +} + +const giftWrap = (event: object, receiverPK: string) => { + const secretKey = generateSecretKey(); + const SKString = bytesToHex(secretKey); + const conversationKey = u.getConversationKey(secretKey, receiverPK); + const encryptedEvent = encrypt(JSON.stringify(event), conversationKey); + + const giftWrapEvent = { + kind: 1059, // gift wrap + created_at: randomTimestamp(), + tags: [["p", receiverPK]], + pubkey: getPublicKey(secretKey), + content: encryptedEvent + } + + return finalizeEvent(giftWrapEvent, secretKey); +} |
