nostr-double-ratchet 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,192 @@
1
+ import { generateSecretKey, getPublicKey, nip44, finalizeEvent, VerifiedEvent, nip19 } from "nostr-tools";
2
+ import { base58 } from '@scure/base';
3
+ import { NostrSubscribe, Unsubscribe } from "./types";
4
+ import { getConversationKey } from "nostr-tools/nip44";
5
+ import { Channel } from "./Channel";
6
+ import { EVENT_KIND } from "./types";
7
+ import { EncryptFunction, DecryptFunction } from "./types";
8
+
9
+ /**
10
+ * Invite link is a safe way to exchange session keys and initiate secret channels.
11
+ *
12
+ * Even if inviter's or invitee's long-term private key (identity key) and the shared secret (link) is compromised,
13
+ * forward secrecy is preserved as long as the session keys are not compromised.
14
+ *
15
+ * Shared secret Nostr channel: inviter listens to it and invitees can write to it. Outside observers don't know who are communicating over it.
16
+ * It is vulnerable to spam, so the link should only be given to trusted invitees or used with a reasonable maxUses limit.
17
+ *
18
+ * Also make sure to keep the session key safe.
19
+ */
20
+ export class InviteLink {
21
+ constructor(
22
+ public inviterSessionPublicKey: string,
23
+ public linkSecret: string,
24
+ public inviter: string,
25
+ public inviterSessionPrivateKey?: Uint8Array,
26
+ public label?: string,
27
+ public maxUses?: number,
28
+ public usedBy: string[] = [],
29
+ ) {}
30
+
31
+ static createNew(inviter: string, label?: string, maxUses?: number): InviteLink {
32
+ const inviterSessionPrivateKey = generateSecretKey();
33
+ const inviterSessionPublicKey = getPublicKey(inviterSessionPrivateKey);
34
+ const linkSecret = base58.encode(generateSecretKey()).slice(8, 40);
35
+ return new InviteLink(
36
+ inviterSessionPublicKey,
37
+ linkSecret,
38
+ inviter,
39
+ inviterSessionPrivateKey,
40
+ label,
41
+ maxUses
42
+ );
43
+ }
44
+
45
+ static fromUrl(url: string): InviteLink {
46
+ const parsedUrl = new URL(url);
47
+ const inviter = parsedUrl.pathname.slice(1);
48
+ const inviterSessionPublicKey = parsedUrl.searchParams.get('s');
49
+ const linkSecret = parsedUrl.hash.slice(1);
50
+
51
+ if (!inviter) {
52
+ throw new Error("Inviter not found in the URL");
53
+ }
54
+ if (!inviterSessionPublicKey) {
55
+ throw new Error("Session key not found in the URL");
56
+ }
57
+
58
+ const decodedInviter = nip19.decode(inviter);
59
+ const decodedSessionKey = nip19.decode(inviterSessionPublicKey);
60
+
61
+ if (typeof decodedInviter.data !== 'string') {
62
+ throw new Error("Decoded inviter is not a string");
63
+ }
64
+ if (typeof decodedSessionKey.data !== 'string') {
65
+ throw new Error("Decoded session key is not a string");
66
+ }
67
+
68
+ const inviterHexPub = decodedInviter.data;
69
+ const inviterSessionPublicKeyHex = decodedSessionKey.data;
70
+
71
+ return new InviteLink(inviterSessionPublicKeyHex, linkSecret, inviterHexPub);
72
+ }
73
+
74
+ static deserialize(json: string): InviteLink {
75
+ const data = JSON.parse(json);
76
+ return new InviteLink(
77
+ data.inviterSessionPublicKey,
78
+ data.linkSecret,
79
+ data.inviter,
80
+ data.inviterSessionPrivateKey ? new Uint8Array(data.inviterSessionPrivateKey) : undefined,
81
+ data.label,
82
+ data.maxUses,
83
+ data.usedBy
84
+ );
85
+ }
86
+
87
+ serialize(): string {
88
+ return JSON.stringify({
89
+ inviterSessionPublicKey: this.inviterSessionPublicKey,
90
+ linkSecret: this.linkSecret,
91
+ inviter: this.inviter,
92
+ inviterSessionPrivateKey: this.inviterSessionPrivateKey ? Array.from(this.inviterSessionPrivateKey) : undefined,
93
+ label: this.label,
94
+ maxUses: this.maxUses,
95
+ usedBy: this.usedBy,
96
+ });
97
+ }
98
+
99
+ getUrl(root = "https://iris.to") {
100
+ const url = new URL(`${root}/${nip19.npubEncode(this.inviter)}`)
101
+ url.searchParams.set('s', nip19.npubEncode(this.inviterSessionPublicKey))
102
+ url.hash = this.linkSecret
103
+ return url.toString()
104
+ }
105
+
106
+ /**
107
+ * Accepts the invite and creates a new channel with the inviter.
108
+ *
109
+ * @param inviteeSecretKey - The invitee's secret key or a signing function
110
+ * @param nostrSubscribe - A function to subscribe to Nostr events
111
+ * @returns An object containing the new channel and an event to be published
112
+ *
113
+ * 1. Inner event: No signature, content encrypted with DH(inviter, invitee).
114
+ * Purpose: Authenticate invitee. Contains invitee session key.
115
+ * 2. Envelope: No signature, content encrypted with DH(inviter, random key).
116
+ * Purpose: Contains inner event. Hides invitee from others who might have the shared Nostr key.
117
+
118
+ * Note: You need to publish the returned event on Nostr using NDK or another Nostr system of your choice,
119
+ * so the inviter can create the channel on their side.
120
+ */
121
+ async acceptInvite(
122
+ nostrSubscribe: NostrSubscribe,
123
+ inviteePublicKey: string,
124
+ inviteeSecretKey: Uint8Array | EncryptFunction,
125
+ ): Promise<{ channel: Channel, event: VerifiedEvent }> {
126
+ const inviteeSessionKey = generateSecretKey();
127
+ const inviteeSessionPublicKey = getPublicKey(inviteeSessionKey);
128
+ const inviterPublicKey = this.inviter || this.inviterSessionPublicKey;
129
+
130
+ const channel = Channel.init(nostrSubscribe, this.inviterSessionPublicKey, inviteeSessionKey);
131
+
132
+ // Create a random keypair for the envelope sender
133
+ const randomSenderKey = generateSecretKey();
134
+ const randomSenderPublicKey = getPublicKey(randomSenderKey);
135
+
136
+ const encrypt = typeof inviteeSecretKey === 'function' ?
137
+ inviteeSecretKey :
138
+ (plaintext: string, pubkey: string) => Promise.resolve(nip44.encrypt(plaintext, getConversationKey(inviteeSecretKey, pubkey)));
139
+
140
+ const innerEvent = {
141
+ pubkey: inviteePublicKey,
142
+ tags: [['secret', this.linkSecret]],
143
+ content: await encrypt(inviteeSessionPublicKey, inviterPublicKey),
144
+ created_at: Math.floor(Date.now() / 1000),
145
+ };
146
+
147
+ const envelope = {
148
+ kind: EVENT_KIND,
149
+ pubkey: randomSenderPublicKey,
150
+ content: nip44.encrypt(JSON.stringify(innerEvent), getConversationKey(randomSenderKey, this.inviterSessionPublicKey)),
151
+ created_at: Math.floor(Date.now() / 1000),
152
+ tags: [['p', this.inviterSessionPublicKey]],
153
+ };
154
+
155
+ return { channel, event: finalizeEvent(envelope, randomSenderKey) };
156
+ }
157
+
158
+ listen(inviterSecretKey: Uint8Array | DecryptFunction, nostrSubscribe: NostrSubscribe, onChannel: (channel: Channel, identity?: string) => void): Unsubscribe {
159
+ if (!this.inviterSessionPrivateKey) {
160
+ throw new Error("Inviter session key is not available");
161
+ }
162
+
163
+ const filter = {
164
+ kinds: [EVENT_KIND],
165
+ '#p': [this.inviterSessionPublicKey],
166
+ };
167
+
168
+ return nostrSubscribe(filter, async (event) => {
169
+ try {
170
+ const decrypted = await nip44.decrypt(event.content, getConversationKey(this.inviterSessionPrivateKey!, event.pubkey));
171
+ const innerEvent = JSON.parse(decrypted);
172
+
173
+ if (!innerEvent.tags || !innerEvent.tags.some(([key, value]: [string, string]) => key === 'secret' && value === this.linkSecret)) {
174
+ console.error("Invalid secret from event", event);
175
+ return;
176
+ }
177
+
178
+ const innerDecrypt = typeof inviterSecretKey === 'function' ?
179
+ inviterSecretKey :
180
+ (ciphertext: string, pubkey: string) => Promise.resolve(nip44.decrypt(ciphertext, getConversationKey(inviterSecretKey, pubkey)));
181
+
182
+ const inviteeSessionPublicKey = await innerDecrypt(innerEvent.content, innerEvent.pubkey);
183
+
184
+ const channel = Channel.init(nostrSubscribe, inviteeSessionPublicKey, this.inviterSessionPrivateKey!);
185
+
186
+ onChannel(channel, innerEvent.pubkey);
187
+ } catch (error) {
188
+ console.error("Error processing invite message:", error);
189
+ }
190
+ });
191
+ }
192
+ }
package/src/index.ts ADDED
@@ -0,0 +1,4 @@
1
+ export * from "./Channel"
2
+ export * from "./InviteLink"
3
+ export * from "./types"
4
+ export * from "./utils"
package/src/types.ts ADDED
@@ -0,0 +1,68 @@
1
+ import { VerifiedEvent } from "nostr-tools";
2
+
3
+ export type Message = {
4
+ id: string;
5
+ data: string;
6
+ pubkey: string;
7
+ time: number; // unlike Nostr, we use milliseconds instead of seconds
8
+ }
9
+
10
+ export type RatchetMessage = {
11
+ number: number;
12
+ data: string;
13
+ nextPublicKey: string;
14
+ time: number;
15
+ }
16
+
17
+ export type NostrFilter = {
18
+ authors?: string[];
19
+ kinds?: number[];
20
+ }
21
+
22
+ export type KeyPair = {
23
+ publicKey: string;
24
+ privateKey: Uint8Array;
25
+ }
26
+
27
+ export interface ChannelState {
28
+ theirCurrentNostrPublicKey: string;
29
+ ourCurrentNostrKey: KeyPair;
30
+ ourNextNostrKey: KeyPair;
31
+ receivingChainKey: Uint8Array;
32
+ nextReceivingChainKey: Uint8Array;
33
+ sendingChainKey: Uint8Array;
34
+ sendingChainMessageNumber: number;
35
+ receivingChainMessageNumber: number;
36
+ previousSendingChainMessageCount: number;
37
+ skippedMessageKeys: Record<number, Uint8Array>;
38
+ }
39
+
40
+ export type Unsubscribe = () => void;
41
+ export type NostrSubscribe = (filter: NostrFilter, onEvent: (e: VerifiedEvent) => void) => Unsubscribe;
42
+ export type MessageCallback = (message: Message) => void;
43
+
44
+ export const EVENT_KIND = 4;
45
+ export const MAX_SKIP = 100;
46
+
47
+ export type NostrEvent = {
48
+ id: string;
49
+ pubkey: string;
50
+ created_at: number;
51
+ kind: number;
52
+ tags: string[][];
53
+ content: string;
54
+ sig: string;
55
+ }
56
+
57
+ export enum Sender {
58
+ Us,
59
+ Them
60
+ }
61
+
62
+ export enum KeyType {
63
+ Current,
64
+ Next
65
+ }
66
+
67
+ export type EncryptFunction = (plaintext: string, pubkey: string) => Promise<string>;
68
+ export type DecryptFunction = (ciphertext: string, pubkey: string) => Promise<string>;
package/src/utils.ts ADDED
@@ -0,0 +1,91 @@
1
+ import { hexToBytes, bytesToHex } from "@noble/hashes/utils";
2
+ import { ChannelState, Message } from "./types";
3
+ import { Channel } from "./Channel";
4
+ import { extract as hkdf_extract, expand as hkdf_expand } from '@noble/hashes/hkdf';
5
+ import { sha256 } from '@noble/hashes/sha256';
6
+
7
+ export function serializeChannelState(state: ChannelState): string {
8
+ return JSON.stringify({
9
+ theirCurrentNostrPublicKey: state.theirCurrentNostrPublicKey,
10
+ ourCurrentNostrKey: {
11
+ publicKey: state.ourCurrentNostrKey.publicKey,
12
+ privateKey: bytesToHex(state.ourCurrentNostrKey.privateKey),
13
+ },
14
+ ourNextNostrKey: {
15
+ publicKey: state.ourNextNostrKey.publicKey,
16
+ privateKey: bytesToHex(state.ourNextNostrKey.privateKey),
17
+ },
18
+ receivingChainKey: bytesToHex(state.receivingChainKey),
19
+ nextReceivingChainKey: bytesToHex(state.nextReceivingChainKey),
20
+ sendingChainKey: bytesToHex(state.sendingChainKey),
21
+ sendingChainMessageNumber: state.sendingChainMessageNumber,
22
+ receivingChainMessageNumber: state.receivingChainMessageNumber,
23
+ previousSendingChainMessageCount: state.previousSendingChainMessageCount,
24
+ skippedMessageKeys: Object.fromEntries(
25
+ Object.entries(state.skippedMessageKeys).map(([key, value]) => [
26
+ key,
27
+ bytesToHex(value),
28
+ ])
29
+ ),
30
+ });
31
+ }
32
+
33
+ export function deserializeChannelState(data: string): ChannelState {
34
+ const state = JSON.parse(data);
35
+ return {
36
+ theirCurrentNostrPublicKey: state.theirCurrentNostrPublicKey,
37
+ ourCurrentNostrKey: {
38
+ publicKey: state.ourCurrentNostrKey.publicKey,
39
+ privateKey: hexToBytes(state.ourCurrentNostrKey.privateKey),
40
+ },
41
+ ourNextNostrKey: {
42
+ publicKey: state.ourNextNostrKey.publicKey,
43
+ privateKey: hexToBytes(state.ourNextNostrKey.privateKey),
44
+ },
45
+ receivingChainKey: hexToBytes(state.receivingChainKey),
46
+ nextReceivingChainKey: hexToBytes(state.nextReceivingChainKey),
47
+ sendingChainKey: hexToBytes(state.sendingChainKey),
48
+ sendingChainMessageNumber: state.sendingChainMessageNumber,
49
+ receivingChainMessageNumber: state.receivingChainMessageNumber,
50
+ previousSendingChainMessageCount: state.previousSendingChainMessageCount,
51
+ skippedMessageKeys: Object.fromEntries(
52
+ Object.entries(state.skippedMessageKeys).map(([key, value]) => [
53
+ key,
54
+ hexToBytes(value as string),
55
+ ])
56
+ ),
57
+ };
58
+ }
59
+
60
+ export async function* createMessageStream(channel: Channel): AsyncGenerator<Message, void, unknown> {
61
+ const messageQueue: Message[] = [];
62
+ let resolveNext: ((value: Message) => void) | null = null;
63
+
64
+ const unsubscribe = channel.onMessage((message) => {
65
+ if (resolveNext) {
66
+ resolveNext(message);
67
+ resolveNext = null;
68
+ } else {
69
+ messageQueue.push(message);
70
+ }
71
+ });
72
+
73
+ try {
74
+ while (true) {
75
+ if (messageQueue.length > 0) {
76
+ yield messageQueue.shift()!;
77
+ } else {
78
+ yield new Promise<Message>(resolve => {
79
+ resolveNext = resolve;
80
+ });
81
+ }
82
+ }
83
+ } finally {
84
+ unsubscribe();
85
+ }
86
+ }
87
+
88
+ export function kdf(input1: Uint8Array, input2: Uint8Array = new Uint8Array(32)) {
89
+ const prk = hkdf_extract(sha256, input1, input2)
90
+ return hkdf_expand(sha256, prk, new Uint8Array([1]), 32)
91
+ }