@koralabs/handle-chat-sdk 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.
package/index.d.ts ADDED
@@ -0,0 +1,7 @@
1
+ export * from './interfaces/Chat.js';
2
+ export * from './interfaces/Directory.js';
3
+ export * from './interfaces/Store.js';
4
+ export * from './lib/helper.js';
5
+ export * from './lib/message-helper.js';
6
+ export * from './lib/SignalDirectory.js';
7
+ export * from './lib/SignalProtocolStore.js';
package/index.js ADDED
@@ -0,0 +1,7 @@
1
+ export * from './interfaces/Chat.js';
2
+ export * from './interfaces/Directory.js';
3
+ export * from './interfaces/Store.js';
4
+ export * from './lib/helper.js';
5
+ export * from './lib/message-helper.js';
6
+ export * from './lib/SignalDirectory.js';
7
+ export * from './lib/SignalProtocolStore.js';
@@ -0,0 +1,31 @@
1
+ import { MessageType } from "@privacyresearch/libsignal-protocol-typescript";
2
+ import { SerializableFullDirectoryEntry } from "./Directory.js";
3
+ import { SerializedStoreEntry } from "./Store.js";
4
+ export interface ChatUser {
5
+ address: string;
6
+ name: string;
7
+ accepted: boolean;
8
+ chats: ProcessedChatMessage[];
9
+ waitingForSession?: boolean;
10
+ hasPendingChats?: boolean;
11
+ deviceId?: number;
12
+ image?: string;
13
+ bundle?: SerializableFullDirectoryEntry;
14
+ store?: SerializedStoreEntry;
15
+ }
16
+ export interface ProcessedChatMessage {
17
+ id: number;
18
+ to: string;
19
+ from: string;
20
+ messageText: string;
21
+ timestamp: number;
22
+ }
23
+ export interface ChatMessage {
24
+ id: number;
25
+ to: string;
26
+ from: string;
27
+ message: MessageType;
28
+ delivered: boolean;
29
+ timestamp: number;
30
+ session_init?: boolean;
31
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,27 @@
1
+ import { PreKeyType, SignedPublicPreKeyType } from "@privacyresearch/libsignal-protocol-typescript";
2
+ export interface PublicDirectoryEntry {
3
+ identityPubKey: ArrayBuffer;
4
+ signedPreKey: SignedPublicPreKeyType;
5
+ oneTimePreKey?: ArrayBuffer;
6
+ }
7
+ export interface FullDirectoryEntry {
8
+ registrationId: number;
9
+ identityPubKey: ArrayBuffer;
10
+ signedPreKey: SignedPublicPreKeyType;
11
+ oneTimePreKeys: PreKeyType[];
12
+ }
13
+ export interface SerializablePreKey {
14
+ keyId: number;
15
+ publicKey: string;
16
+ }
17
+ export interface SerializableSignedPublicPreKey {
18
+ keyId: number;
19
+ publicKey: string;
20
+ signature: string;
21
+ }
22
+ export interface SerializableFullDirectoryEntry {
23
+ registrationId: number;
24
+ identityPubKey: string;
25
+ signedPreKey: SerializableSignedPublicPreKey;
26
+ oneTimePreKeys: SerializablePreKey[];
27
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,29 @@
1
+ import { KeyPairType, PreKeyPairType, SignedPreKeyPairType } from "@privacyresearch/libsignal-protocol-typescript";
2
+ export interface StoreEntry {
3
+ registrationId: number;
4
+ identityKey: KeyPairType;
5
+ preKey: PreKeyPairType;
6
+ signedPreKey: SignedPreKeyPairType;
7
+ }
8
+ export interface SerializedStoreEntry {
9
+ registrationId: number;
10
+ identityKey: {
11
+ pubKey: string;
12
+ privKey: string;
13
+ };
14
+ preKey: {
15
+ keyId: number;
16
+ keyPair: {
17
+ pubKey: string;
18
+ privKey: string;
19
+ };
20
+ };
21
+ signedPreKey: {
22
+ keyId: number;
23
+ keyPair: {
24
+ pubKey: string;
25
+ privKey: string;
26
+ };
27
+ signature: string;
28
+ };
29
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,23 @@
1
+ import { DeviceType, PreKeyType } from "@privacyresearch/libsignal-protocol-typescript";
2
+ import { FullDirectoryEntry, SerializableFullDirectoryEntry } from "../interfaces/Directory.js";
3
+ import { SerializedStoreEntry, StoreEntry } from "../interfaces/Store.js";
4
+ import { SignalProtocolStore } from "./SignalProtocolStore.js";
5
+ export declare class SignalDirectory {
6
+ private _data;
7
+ storeKeyBundle(address: string, bundle: FullDirectoryEntry): void;
8
+ addOneTimePreKeys(address: string, keys: PreKeyType[]): void;
9
+ getPreKeyBundle(address: string): DeviceType | undefined;
10
+ }
11
+ export declare const serializeBundle: (bundle: FullDirectoryEntry) => SerializableFullDirectoryEntry;
12
+ export declare const deserializeBundle: (serializable: SerializableFullDirectoryEntry) => DeviceType;
13
+ export declare const serializeStore: (entry: StoreEntry) => SerializedStoreEntry;
14
+ export declare const deserializeStore: (serializedEntry: SerializedStoreEntry) => StoreEntry;
15
+ export declare const populateStore: (store: SignalProtocolStore, storeEntry: StoreEntry) => void;
16
+ export declare const createStoreBundle: () => Promise<{
17
+ bundle: FullDirectoryEntry;
18
+ storeEntry: StoreEntry;
19
+ }>;
20
+ export declare const createID: (directory: SignalDirectory, name: string, store: SignalProtocolStore) => Promise<{
21
+ bundle: FullDirectoryEntry;
22
+ storeEntry: StoreEntry;
23
+ }>;
@@ -0,0 +1,157 @@
1
+ import { KeyHelper } from "@privacyresearch/libsignal-protocol-typescript";
2
+ import { arrayBufferToBase64, base64ToArrayBuffer } from "./helper.js";
3
+ export class SignalDirectory {
4
+ _data = {};
5
+ storeKeyBundle(address, bundle) {
6
+ this._data[address] = bundle;
7
+ }
8
+ addOneTimePreKeys(address, keys) {
9
+ this._data[address].oneTimePreKeys.unshift(...keys);
10
+ }
11
+ getPreKeyBundle(address) {
12
+ const bundle = this._data[address];
13
+ if (!bundle) {
14
+ return undefined;
15
+ }
16
+ const oneTimePreKey = bundle.oneTimePreKeys.pop();
17
+ const { identityPubKey, signedPreKey, registrationId } = bundle;
18
+ return {
19
+ identityKey: identityPubKey,
20
+ signedPreKey,
21
+ preKey: oneTimePreKey,
22
+ registrationId,
23
+ };
24
+ }
25
+ }
26
+ // Serialize ArrayBuffer to base64 for storage
27
+ export const serializeBundle = (bundle) => {
28
+ return {
29
+ registrationId: bundle.registrationId,
30
+ identityPubKey: arrayBufferToBase64(bundle.identityPubKey),
31
+ signedPreKey: {
32
+ keyId: bundle.signedPreKey.keyId,
33
+ publicKey: arrayBufferToBase64(bundle.signedPreKey.publicKey),
34
+ signature: arrayBufferToBase64(bundle.signedPreKey.signature),
35
+ },
36
+ oneTimePreKeys: bundle.oneTimePreKeys.map((key) => ({
37
+ keyId: key.keyId,
38
+ publicKey: arrayBufferToBase64(key.publicKey),
39
+ })),
40
+ };
41
+ };
42
+ // Deserialize base64 back to ArrayBuffer
43
+ export const deserializeBundle = (serializable) => {
44
+ const deserializedBundle = {
45
+ registrationId: serializable.registrationId,
46
+ identityPubKey: base64ToArrayBuffer(serializable.identityPubKey),
47
+ signedPreKey: {
48
+ keyId: serializable.signedPreKey.keyId,
49
+ publicKey: base64ToArrayBuffer(serializable.signedPreKey.publicKey),
50
+ signature: base64ToArrayBuffer(serializable.signedPreKey.signature),
51
+ },
52
+ oneTimePreKeys: serializable.oneTimePreKeys.map((key) => ({
53
+ keyId: key.keyId,
54
+ publicKey: base64ToArrayBuffer(key.publicKey),
55
+ })),
56
+ };
57
+ const oneTimePreKey = deserializedBundle.oneTimePreKeys.pop();
58
+ const { identityPubKey, signedPreKey, registrationId } = deserializedBundle;
59
+ return {
60
+ identityKey: identityPubKey,
61
+ signedPreKey,
62
+ preKey: oneTimePreKey,
63
+ registrationId,
64
+ };
65
+ };
66
+ export const serializeStore = (entry) => {
67
+ return {
68
+ registrationId: entry.registrationId,
69
+ identityKey: {
70
+ pubKey: arrayBufferToBase64(entry.identityKey.pubKey),
71
+ privKey: arrayBufferToBase64(entry.identityKey.privKey)
72
+ },
73
+ preKey: {
74
+ keyId: entry.preKey.keyId,
75
+ keyPair: {
76
+ pubKey: arrayBufferToBase64(entry.preKey.keyPair.pubKey),
77
+ privKey: arrayBufferToBase64(entry.preKey.keyPair.privKey),
78
+ }
79
+ },
80
+ signedPreKey: {
81
+ keyId: entry.signedPreKey.keyId,
82
+ keyPair: {
83
+ pubKey: arrayBufferToBase64(entry.signedPreKey.keyPair.pubKey),
84
+ privKey: arrayBufferToBase64(entry.signedPreKey.keyPair.privKey),
85
+ },
86
+ signature: arrayBufferToBase64(entry.signedPreKey.signature)
87
+ }
88
+ };
89
+ };
90
+ export const deserializeStore = (serializedEntry) => {
91
+ return {
92
+ registrationId: serializedEntry.registrationId,
93
+ identityKey: {
94
+ pubKey: base64ToArrayBuffer(serializedEntry.identityKey.pubKey),
95
+ privKey: base64ToArrayBuffer(serializedEntry.identityKey.privKey)
96
+ },
97
+ preKey: {
98
+ keyId: serializedEntry.preKey.keyId,
99
+ keyPair: {
100
+ pubKey: base64ToArrayBuffer(serializedEntry.preKey.keyPair.pubKey),
101
+ privKey: base64ToArrayBuffer(serializedEntry.preKey.keyPair.privKey),
102
+ }
103
+ },
104
+ signedPreKey: {
105
+ keyId: serializedEntry.signedPreKey.keyId,
106
+ keyPair: {
107
+ pubKey: base64ToArrayBuffer(serializedEntry.signedPreKey.keyPair.pubKey),
108
+ privKey: base64ToArrayBuffer(serializedEntry.signedPreKey.keyPair.privKey),
109
+ },
110
+ signature: base64ToArrayBuffer(serializedEntry.signedPreKey.signature)
111
+ }
112
+ };
113
+ };
114
+ export const populateStore = (store, storeEntry) => {
115
+ const { registrationId, identityKey: identityKeyPair, preKey, signedPreKey } = storeEntry;
116
+ store.storeRegistrationId(registrationId);
117
+ store.storeIdentityKey(identityKeyPair);
118
+ store.storePreKey(`${preKey.keyId}`, preKey.keyPair);
119
+ store.storeSignedPreKey(signedPreKey.keyId, signedPreKey.keyPair);
120
+ };
121
+ export const createStoreBundle = async () => {
122
+ const registrationId = KeyHelper.generateRegistrationId();
123
+ const identityKeyPair = await KeyHelper.generateIdentityKeyPair();
124
+ const baseKeyId = Math.floor(10000 * Math.random());
125
+ const preKey = await KeyHelper.generatePreKey(baseKeyId);
126
+ const signedPreKeyId = Math.floor(10000 * Math.random());
127
+ const signedPreKey = await KeyHelper.generateSignedPreKey(identityKeyPair, signedPreKeyId);
128
+ const storeEntry = {
129
+ registrationId,
130
+ identityKey: identityKeyPair,
131
+ preKey,
132
+ signedPreKey,
133
+ };
134
+ const publicSignedPreKey = {
135
+ keyId: signedPreKeyId,
136
+ publicKey: signedPreKey.keyPair.pubKey,
137
+ signature: signedPreKey.signature,
138
+ };
139
+ // Now we register this with the server so all users can see them
140
+ const publicPreKey = {
141
+ keyId: preKey.keyId,
142
+ publicKey: preKey.keyPair.pubKey,
143
+ };
144
+ const bundle = {
145
+ registrationId,
146
+ identityPubKey: identityKeyPair.pubKey,
147
+ signedPreKey: publicSignedPreKey,
148
+ oneTimePreKeys: [publicPreKey],
149
+ };
150
+ return { bundle, storeEntry };
151
+ };
152
+ export const createID = async (directory, name, store) => {
153
+ const { bundle, storeEntry } = await createStoreBundle();
154
+ populateStore(store, storeEntry);
155
+ directory.storeKeyBundle(name, bundle);
156
+ return { bundle, storeEntry };
157
+ };
@@ -0,0 +1,46 @@
1
+ import { Direction, PreKeyPairType, SessionRecordType, SignedPreKeyPairType, StorageType } from '@privacyresearch/libsignal-protocol-typescript';
2
+ export declare function isKeyPairType(kp: any): kp is KeyPairType;
3
+ export declare function isPreKeyType(pk: any): pk is PreKeyPairType;
4
+ export declare function isSignedPreKeyType(spk: any): spk is SignedPreKeyPairType;
5
+ interface KeyPairType {
6
+ pubKey: ArrayBuffer;
7
+ privKey: ArrayBuffer;
8
+ }
9
+ interface PreKeyType {
10
+ keyId: number;
11
+ keyPair: KeyPairType;
12
+ }
13
+ interface SignedPreKeyType extends PreKeyType {
14
+ signature: ArrayBuffer;
15
+ }
16
+ export type StoreValue = KeyPairType | string | number | KeyPairType | PreKeyType | SignedPreKeyType | ArrayBuffer | undefined;
17
+ export declare class SignalProtocolStore implements StorageType {
18
+ private _store;
19
+ constructor();
20
+ get(key: string, defaultValue: StoreValue): StoreValue;
21
+ remove(key: string): void;
22
+ put(key: string, value: StoreValue): void;
23
+ getIdentityKeyPair(): Promise<KeyPairType | undefined>;
24
+ getLocalRegistrationId(): Promise<number | undefined>;
25
+ isTrustedIdentity(identifier: string, identityKey: ArrayBuffer, _direction: Direction): Promise<boolean>;
26
+ loadPreKey(keyId: string | number): Promise<KeyPairType | undefined>;
27
+ loadSession(identifier: string): Promise<SessionRecordType | undefined>;
28
+ loadSignedPreKey(keyId: number | string): Promise<KeyPairType | undefined>;
29
+ removePreKey(keyId: number | string): Promise<void>;
30
+ saveIdentity(identifier: string, identityKey: ArrayBuffer): Promise<boolean>;
31
+ storeSession(identifier: string, record: SessionRecordType): Promise<void>;
32
+ loadIdentityKey(identifier: string): Promise<ArrayBuffer | undefined>;
33
+ storePreKey(keyId: number | string, keyPair: KeyPairType): Promise<void>;
34
+ storeRegistrationId(registrationId: number): Promise<void>;
35
+ deleteRegistrationId(registrationId: number): Promise<void>;
36
+ storeIdentityKey(keyPair: KeyPairType): Promise<void>;
37
+ storeSignedPreKey(keyId: number | string, keyPair: KeyPairType): Promise<void>;
38
+ removeSignedPreKey(keyId: number | string): Promise<void>;
39
+ removeSession(identifier: string): Promise<void>;
40
+ removeSessionIdentity(address: string): Promise<void>;
41
+ removeAllSessions(identifier: string): Promise<void>;
42
+ removeKeysWithIdentifier(identifier: string): Promise<void>;
43
+ }
44
+ export declare function arrayBufferToString(b: ArrayBuffer): string;
45
+ export declare function uint8ArrayToString(arr: Uint8Array): string;
46
+ export {};
@@ -0,0 +1,195 @@
1
+ /* eslint-disable @typescript-eslint/no-explicit-any */
2
+ import { SignalProtocolAddress } from '@privacyresearch/libsignal-protocol-typescript';
3
+ // Type guards
4
+ export function isKeyPairType(kp) {
5
+ return !!(kp?.privKey && kp?.pubKey);
6
+ }
7
+ export function isPreKeyType(pk) {
8
+ return typeof pk?.keyId === 'number' && isKeyPairType(pk?.keyPair);
9
+ }
10
+ export function isSignedPreKeyType(spk) {
11
+ return spk?.signature && isPreKeyType(spk);
12
+ }
13
+ function isArrayBuffer(thing) {
14
+ const t = typeof thing;
15
+ return !!thing && t !== 'string' && t !== 'number' && 'byteLength' in thing;
16
+ }
17
+ export class SignalProtocolStore {
18
+ _store;
19
+ constructor() {
20
+ this._store = {};
21
+ }
22
+ //
23
+ get(key, defaultValue) {
24
+ if (key === null || key === undefined)
25
+ throw new Error('Tried to get value for undefined/null key');
26
+ if (key in this._store) {
27
+ return this._store[key];
28
+ }
29
+ else {
30
+ return defaultValue;
31
+ }
32
+ }
33
+ remove(key) {
34
+ if (key === null || key === undefined)
35
+ throw new Error('Tried to remove value for undefined/null key');
36
+ this._store = Object.fromEntries(Object.entries(this._store).filter(([k, _v]) => k !== key));
37
+ //delete this._store[key]
38
+ }
39
+ put(key, value) {
40
+ if (key === undefined || value === undefined || key === null || value === null)
41
+ throw new Error('Tried to store undefined/null');
42
+ this._store[key] = value;
43
+ }
44
+ async getIdentityKeyPair() {
45
+ const kp = this.get('identityKey', undefined);
46
+ if (isKeyPairType(kp) || typeof kp === 'undefined') {
47
+ return kp;
48
+ }
49
+ throw new Error('Item stored as identity key of unknown type.');
50
+ }
51
+ async getLocalRegistrationId() {
52
+ const rid = this.get('registrationId', undefined);
53
+ if (typeof rid === 'number' || typeof rid === 'undefined') {
54
+ return rid;
55
+ }
56
+ throw new Error('Stored Registration ID is not a number');
57
+ }
58
+ isTrustedIdentity(identifier, identityKey, _direction) {
59
+ if (identifier === null || identifier === undefined) {
60
+ throw new Error('tried to check identity key for undefined/null key');
61
+ }
62
+ const trusted = this.get('identityKey' + identifier, undefined);
63
+ // TODO: Is this right? If the ID is NOT in our store we trust it?
64
+ if (trusted === undefined) {
65
+ return Promise.resolve(true);
66
+ }
67
+ return Promise.resolve(arrayBufferToString(identityKey) === arrayBufferToString(trusted));
68
+ }
69
+ async loadPreKey(keyId) {
70
+ let res = this.get('25519KeypreKey' + keyId, undefined);
71
+ if (isKeyPairType(res)) {
72
+ res = { pubKey: res.pubKey, privKey: res.privKey };
73
+ return res;
74
+ }
75
+ else if (typeof res === 'undefined') {
76
+ return res;
77
+ }
78
+ throw new Error(`stored key has wrong type`);
79
+ }
80
+ async loadSession(identifier) {
81
+ const rec = this.get('session' + identifier, undefined);
82
+ if (typeof rec === 'string') {
83
+ return rec;
84
+ }
85
+ else if (typeof rec === 'undefined') {
86
+ return rec;
87
+ }
88
+ throw new Error(`session record is not an ArrayBuffer`);
89
+ }
90
+ async loadSignedPreKey(keyId) {
91
+ const res = this.get('25519KeysignedKey' + keyId, undefined);
92
+ if (isKeyPairType(res)) {
93
+ return { pubKey: res.pubKey, privKey: res.privKey };
94
+ }
95
+ else if (typeof res === 'undefined') {
96
+ return res;
97
+ }
98
+ throw new Error(`stored key has wrong type`);
99
+ }
100
+ async removePreKey(keyId) {
101
+ this.remove('25519KeypreKey' + keyId);
102
+ }
103
+ async saveIdentity(identifier, identityKey) {
104
+ if (identifier === null || identifier === undefined)
105
+ throw new Error('Tried to put identity key for undefined/null key');
106
+ const address = SignalProtocolAddress.fromString(identifier);
107
+ const existing = this.get('identityKey' + address.getName(), undefined);
108
+ this.put('identityKey' + address.getName(), identityKey);
109
+ if (existing && !isArrayBuffer(existing)) {
110
+ throw new Error('Identity Key is incorrect type');
111
+ }
112
+ if (existing && arrayBufferToString(identityKey) !== arrayBufferToString(existing)) {
113
+ return true;
114
+ }
115
+ else {
116
+ return false;
117
+ }
118
+ }
119
+ async storeSession(identifier, record) {
120
+ return this.put('session' + identifier, record);
121
+ }
122
+ async loadIdentityKey(identifier) {
123
+ if (identifier === null || identifier === undefined) {
124
+ throw new Error('Tried to get identity key for undefined/null key');
125
+ }
126
+ const key = this.get('identityKey' + identifier, undefined);
127
+ if (isArrayBuffer(key)) {
128
+ return key;
129
+ }
130
+ else if (typeof key === 'undefined') {
131
+ return key;
132
+ }
133
+ throw new Error(`Identity key has wrong type`);
134
+ }
135
+ async storePreKey(keyId, keyPair) {
136
+ return this.put('25519KeypreKey' + keyId, keyPair);
137
+ }
138
+ async storeRegistrationId(registrationId) {
139
+ return this.put('registrationID', registrationId);
140
+ }
141
+ async deleteRegistrationId(registrationId) {
142
+ return this.remove('registrationID' + registrationId);
143
+ }
144
+ async storeIdentityKey(keyPair) {
145
+ return this.put('identityKey', keyPair);
146
+ }
147
+ // TODO: Why is this keyId a number where others are strings?
148
+ async storeSignedPreKey(keyId, keyPair) {
149
+ return this.put('25519KeysignedKey' + keyId, keyPair);
150
+ }
151
+ async removeSignedPreKey(keyId) {
152
+ return this.remove('25519KeysignedKey' + keyId);
153
+ }
154
+ async removeSession(identifier) {
155
+ return this.remove('session' + identifier);
156
+ }
157
+ async removeSessionIdentity(address) {
158
+ return this.remove('identityKey' + address);
159
+ }
160
+ async removeAllSessions(identifier) {
161
+ for (const id in this._store) {
162
+ if (id.startsWith('session' + identifier)) {
163
+ delete this._store[id];
164
+ }
165
+ }
166
+ }
167
+ async removeKeysWithIdentifier(identifier) {
168
+ for (const id in this._store) {
169
+ // Only remove session-related keys, not identity keys or prekeys
170
+ if (id.startsWith('session' + identifier) || id.startsWith('identityKey' + identifier)) {
171
+ console.log('Removing key with id', id);
172
+ this.remove(id);
173
+ }
174
+ }
175
+ }
176
+ }
177
+ export function arrayBufferToString(b) {
178
+ return uint8ArrayToString(new Uint8Array(b));
179
+ }
180
+ export function uint8ArrayToString(arr) {
181
+ const end = arr.length;
182
+ let begin = 0;
183
+ if (begin === end)
184
+ return '';
185
+ let chars = [];
186
+ const parts = [];
187
+ while (begin < end) {
188
+ chars.push(arr[begin++]);
189
+ if (chars.length >= 1024) {
190
+ parts.push(String.fromCharCode(...chars));
191
+ chars = [];
192
+ }
193
+ }
194
+ return parts.join('') + String.fromCharCode(...chars);
195
+ }
@@ -0,0 +1,2 @@
1
+ export declare const arrayBufferToBase64: (buffer: ArrayBuffer) => string;
2
+ export declare const base64ToArrayBuffer: (base64: string) => ArrayBuffer;
package/lib/helper.js ADDED
@@ -0,0 +1,17 @@
1
+ // Helper functions for ArrayBuffer serialization
2
+ export const arrayBufferToBase64 = (buffer) => {
3
+ const uint8Array = new Uint8Array(buffer);
4
+ let binary = "";
5
+ for (let i = 0; i < uint8Array.byteLength; i++) {
6
+ binary += String.fromCharCode(uint8Array[i]);
7
+ }
8
+ return btoa(binary);
9
+ };
10
+ export const base64ToArrayBuffer = (base64) => {
11
+ const binary = atob(base64);
12
+ const bytes = new Uint8Array(binary.length);
13
+ for (let i = 0; i < binary.length; i++) {
14
+ bytes[i] = binary.charCodeAt(i);
15
+ }
16
+ return bytes.buffer;
17
+ };
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,10 @@
1
+ import assert from 'node:assert';
2
+ import { afterEach, describe, it, mock } from 'node:test';
3
+ describe('helper tests', () => {
4
+ afterEach(() => {
5
+ mock.restoreAll();
6
+ });
7
+ it('should pass', async () => {
8
+ assert.strictEqual('', '');
9
+ });
10
+ });
@@ -0,0 +1,14 @@
1
+ import { SessionCipher, SignalProtocolAddress } from "@privacyresearch/libsignal-protocol-typescript";
2
+ import { ChatMessage, ChatUser, ProcessedChatMessage } from "../interfaces/Chat.js";
3
+ import { SignalProtocolStore } from "./SignalProtocolStore.js";
4
+ export declare const readMessage: (msg: ChatMessage, cipher: SessionCipher) => Promise<{
5
+ id: number;
6
+ to: string;
7
+ from: string;
8
+ timestamp: number;
9
+ messageText: string;
10
+ }>;
11
+ export declare const encryptAndBuildMessage: (message: string | ArrayBuffer, senderUser: ChatUser, senderStore: SignalProtocolStore, recipientProtocolAddress: SignalProtocolAddress) => Promise<{
12
+ msg: ChatMessage;
13
+ processedMsg: ProcessedChatMessage;
14
+ }>;
@@ -0,0 +1,50 @@
1
+ import { SessionCipher } from "@privacyresearch/libsignal-protocol-typescript";
2
+ export const readMessage = async (msg, cipher) => {
3
+ try {
4
+ let plaintext = new Uint8Array().buffer;
5
+ if (msg.message.type === 3) {
6
+ console.log('Decrypting PreKey message');
7
+ plaintext = await cipher.decryptPreKeyWhisperMessage(msg.message.body, "binary");
8
+ }
9
+ else if (msg.message.type === 1) {
10
+ console.log('Decrypting Whisper message');
11
+ plaintext = await cipher.decryptWhisperMessage(msg.message.body, "binary");
12
+ }
13
+ else {
14
+ throw new Error(`Unsupported message type: ${msg.message.type}`);
15
+ }
16
+ const stringPlaintext = new TextDecoder().decode(new Uint8Array(plaintext));
17
+ const { id, to, from, timestamp } = msg;
18
+ return { id, to, from, timestamp, messageText: stringPlaintext };
19
+ }
20
+ catch (error) {
21
+ console.error('Failed to decrypt message:', {
22
+ messageId: msg.id,
23
+ messageType: msg.message.type,
24
+ error: error instanceof Error ? error.message : String(error)
25
+ });
26
+ // Return a placeholder for failed decryption rather than throwing
27
+ return {
28
+ id: msg.id,
29
+ to: msg.to,
30
+ from: msg.from,
31
+ timestamp: msg.timestamp,
32
+ messageText: '[Failed to decrypt message] Error: ' + (error instanceof Error ? error.message : String(error))
33
+ };
34
+ }
35
+ };
36
+ const buildMessage = async ({ encryptedMessage, decryptedMessage, recipientAddress, senderAddress }) => {
37
+ const timestamp = Date.now();
38
+ const id = Math.floor(Math.random() * 1e9);
39
+ const to = recipientAddress;
40
+ const from = senderAddress;
41
+ const msg = { to, from, message: encryptedMessage, timestamp, delivered: false, id };
42
+ const processedMsg = { id, to, from, timestamp, messageText: decryptedMessage };
43
+ return { msg, processedMsg };
44
+ };
45
+ export const encryptAndBuildMessage = async (message, senderUser, senderStore, recipientProtocolAddress) => {
46
+ const cipher = new SessionCipher(senderStore, recipientProtocolAddress);
47
+ const ciphertext = await cipher.encrypt(typeof message === "string" ? new TextEncoder().encode(message).buffer : message);
48
+ const processedMessage = await buildMessage({ encryptedMessage: ciphertext, decryptedMessage: typeof message === "string" ? message : new TextDecoder().decode(new Uint8Array(message)), recipientAddress: recipientProtocolAddress.name, senderAddress: senderUser.address });
49
+ return processedMessage;
50
+ };
package/package.json ADDED
@@ -0,0 +1,37 @@
1
+ {
2
+ "name": "@koralabs/handle-chat-sdk",
3
+ "version": "0.0.1",
4
+ "description": "SDK for handling chat functionalities",
5
+ "main": "index.js",
6
+ "type": "module",
7
+ "scripts": {
8
+ "build": "rm -rf lib/ && tsc",
9
+ "lint": "npx eslint './src/**/*.{ts,mjs}' --max-warnings=0",
10
+ "test": "node --import tsx --test src/**/*.test.ts"
11
+ },
12
+ "dependencies": {
13
+ "@privacyresearch/libsignal-protocol-typescript": "^0.0.16",
14
+ "@signalapp/libsignal-client": "^0.55.0",
15
+ "tsx": "^4.20.6",
16
+ "uuid": "^9.0.0"
17
+ },
18
+ "devDependencies": {
19
+ "@eslint/js": "^9.39.1",
20
+ "@types/node": "^24.7.2",
21
+ "@types/uuid": "^10.0.0",
22
+ "eslint": "^9.39.1",
23
+ "eslint-plugin-simple-import-sort": "^12.1.1",
24
+ "globals": "^16.5.0",
25
+ "typescript-eslint": "^8.46.3"
26
+ },
27
+ "keywords": [
28
+ "messaging",
29
+ "encryption",
30
+ "handles",
31
+ "chat",
32
+ "sdk",
33
+ "crypto"
34
+ ],
35
+ "author": "",
36
+ "license": "MIT"
37
+ }