@notabene/javascript-sdk 2.8.0-next.4 → 2.8.0-next.5

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,284 @@
1
+ import fc from 'fast-check';
2
+ import { beforeEach, describe, expect, it, vi } from 'vitest';
3
+ import type { DID } from '../../types';
4
+ import { ConnectionManager, TransactionType } from '../connections';
5
+ import { seal } from '../encryption';
6
+
7
+ // Mock fetch globally
8
+ const fetchMock = vi.fn();
9
+ global.fetch = fetchMock;
10
+
11
+ // Helper to generate valid DID strings
12
+ const arbDID = fc
13
+ .tuple(fc.string(), fc.string())
14
+ .map(([method, id]) => `did:${method}:${id}` as DID);
15
+
16
+ // Test helper to create arbitrary ComponentRequests
17
+ const arbComponentRequest = fc.record({
18
+ tx: fc.record({
19
+ requestId: fc.option(fc.uuid(), { nil: undefined }),
20
+ customer: fc.option(
21
+ fc.record({
22
+ name: fc.string(),
23
+ email: fc.option(fc.string(), { nil: undefined }),
24
+ phone: fc.option(fc.string(), { nil: undefined }),
25
+ type: fc.constant(undefined), // Optional PersonType
26
+ accountNumber: fc.option(fc.string(), { nil: undefined }),
27
+ did: fc.option(arbDID, { nil: undefined }),
28
+ verified: fc.option(fc.boolean(), { nil: undefined }),
29
+ website: fc.option(fc.webUrl(), { nil: undefined }),
30
+ geographicAddress: fc.option(fc.constant(undefined), {
31
+ nil: undefined,
32
+ }),
33
+ nationalIdentification: fc.option(fc.constant(undefined), {
34
+ nil: undefined,
35
+ }),
36
+ }),
37
+ { nil: undefined },
38
+ ),
39
+ }),
40
+ authToken: fc.option(fc.string(), { nil: undefined }),
41
+ txOptions: fc.option(fc.record({}), { nil: undefined }),
42
+ });
43
+
44
+ // New arbitrary for ConnectionMetadata
45
+ const arbConnectionMetadata = fc.record({
46
+ participants: fc.array(fc.string(), { minLength: 1 }), // At least one participant
47
+ nodeUrl: fc.webUrl(),
48
+ transactionType: fc.constantFrom<TransactionType>('withdraw', 'deposit'),
49
+ });
50
+
51
+ describe('ConnectionManager', () => {
52
+ let manager: ConnectionManager;
53
+ const testEndpoint = 'https://test-endpoint.com';
54
+
55
+ beforeEach(() => {
56
+ manager = new ConnectionManager(testEndpoint);
57
+ fetchMock.mockReset();
58
+ });
59
+
60
+ describe('create', () => {
61
+ it('should successfully create a new connection', async () => {
62
+ await fc.assert(
63
+ fc.asyncProperty(
64
+ arbComponentRequest,
65
+ arbConnectionMetadata,
66
+ async (request, metadata) => {
67
+ // Mock successful response
68
+ const mockResponse = {
69
+ id: 'test-id',
70
+ version: 1,
71
+ metadata,
72
+ sealed: ['encrypted-data'],
73
+ };
74
+
75
+ fetchMock.mockResolvedValueOnce({
76
+ ok: true,
77
+ json: async () => mockResponse,
78
+ });
79
+
80
+ const result = await manager.create(request, metadata);
81
+
82
+ // Verify fetch was called correctly
83
+ expect(fetchMock).toHaveBeenCalledWith(testEndpoint, {
84
+ method: 'POST',
85
+ headers: {
86
+ 'Content-Type': 'application/json',
87
+ },
88
+ body: expect.any(String),
89
+ });
90
+
91
+ // Verify response structure
92
+ expect(result).toEqual({
93
+ id: mockResponse.id,
94
+ metadata: mockResponse.metadata,
95
+ version: mockResponse.version,
96
+ data: request,
97
+ key: expect.any(String),
98
+ });
99
+ },
100
+ ),
101
+ );
102
+ });
103
+
104
+ it('should throw error on failed creation', async () => {
105
+ await fc.assert(
106
+ fc.asyncProperty(
107
+ arbComponentRequest,
108
+ arbConnectionMetadata,
109
+ async (request, metadata) => {
110
+ // Mock failed response
111
+ fetchMock.mockResolvedValueOnce({
112
+ ok: false,
113
+ text: async () => 'Creation failed',
114
+ });
115
+
116
+ await expect(manager.create(request, metadata)).rejects.toThrow(
117
+ 'Failed to create connection',
118
+ );
119
+ },
120
+ ),
121
+ );
122
+ });
123
+ });
124
+
125
+ describe('update', () => {
126
+ it('should successfully update an existing connection', async () => {
127
+ await fc.assert(
128
+ fc.asyncProperty(
129
+ fc.uuid(),
130
+ arbComponentRequest,
131
+ fc.integer(),
132
+ async (id, request, version) => {
133
+ // Mock successful response
134
+ const mockResponse = {
135
+ id,
136
+ metadata: arbConnectionMetadata,
137
+ version: version + 1,
138
+ sealed: ['new-encrypted-data'],
139
+ };
140
+
141
+ fetchMock.mockResolvedValueOnce({
142
+ ok: true,
143
+ json: async () => mockResponse,
144
+ });
145
+
146
+ const result = await manager.update(id, request, version);
147
+
148
+ // Verify fetch was called correctly
149
+ expect(fetchMock).toHaveBeenCalledWith(`${testEndpoint}/${id}`, {
150
+ method: 'PATCH',
151
+ headers: {
152
+ 'Content-Type': 'application/json',
153
+ },
154
+ body: expect.any(String),
155
+ });
156
+
157
+ // Verify response structure
158
+ expect(result).toEqual({
159
+ id: mockResponse.id,
160
+ version: mockResponse.version,
161
+ metadata: mockResponse.metadata,
162
+ data: request,
163
+ key: expect.any(String),
164
+ });
165
+ },
166
+ ),
167
+ );
168
+ });
169
+
170
+ it('should throw error on failed update', async () => {
171
+ await fc.assert(
172
+ fc.asyncProperty(
173
+ fc.uuid(),
174
+ arbComponentRequest,
175
+ fc.integer(),
176
+ async (id, request, version) => {
177
+ // Mock failed response
178
+ fetchMock.mockResolvedValueOnce({
179
+ ok: false,
180
+ text: async () => 'Update failed',
181
+ });
182
+
183
+ await expect(manager.update(id, request, version)).rejects.toThrow(
184
+ 'Failed to update connection',
185
+ );
186
+ },
187
+ ),
188
+ );
189
+ });
190
+ });
191
+
192
+ describe('get', () => {
193
+ it('should successfully retrieve and decrypt connection data', async () => {
194
+ // Create a real sealed object to use in our test
195
+ const testData = { requestId: 'test-123' };
196
+ const sealed = await seal(testData);
197
+
198
+ await fc.assert(
199
+ fc.asyncProperty(fc.uuid(), async (id) => {
200
+ // Mock successful response with real encrypted data
201
+ const mockResponse = {
202
+ id,
203
+ version: 1,
204
+ metadata: arbConnectionMetadata,
205
+ sealed: [sealed.ciphertext], // Use the real ciphertext
206
+ };
207
+
208
+ fetchMock.mockResolvedValueOnce({
209
+ ok: true,
210
+ json: async () => mockResponse,
211
+ });
212
+
213
+ const result = await manager.get(id, sealed.key); // Use the matching key
214
+
215
+ // Verify fetch was called correctly
216
+ expect(fetchMock).toHaveBeenCalledWith(`${testEndpoint}/${id}`, {
217
+ method: 'GET',
218
+ });
219
+
220
+ // Verify response structure
221
+ expect(result).toEqual({
222
+ id: mockResponse.id,
223
+ version: mockResponse.version,
224
+ metadata: mockResponse.metadata,
225
+ data: testData, // Should match our original test data
226
+ key: sealed.key,
227
+ });
228
+ }),
229
+ );
230
+ });
231
+
232
+ it('should throw error on failed retrieval', async () => {
233
+ await fc.assert(
234
+ fc.asyncProperty(fc.uuid(), fc.string(), async (id, key) => {
235
+ // Mock failed response
236
+ fetchMock.mockResolvedValueOnce({
237
+ ok: false,
238
+ text: async () => 'Retrieval failed',
239
+ });
240
+
241
+ await expect(manager.get(id, key)).rejects.toThrow(
242
+ 'Failed to get connection',
243
+ );
244
+ }),
245
+ );
246
+ });
247
+ });
248
+
249
+ describe('close', () => {
250
+ it('should successfully close a connection', async () => {
251
+ await fc.assert(
252
+ fc.asyncProperty(fc.uuid(), async (id) => {
253
+ // Mock successful response
254
+ fetchMock.mockResolvedValueOnce({
255
+ ok: true,
256
+ });
257
+
258
+ await manager.close(id);
259
+
260
+ // Verify fetch was called correctly
261
+ expect(fetchMock).toHaveBeenCalledWith(`${testEndpoint}/${id}`, {
262
+ method: 'DELETE',
263
+ });
264
+ }),
265
+ );
266
+ });
267
+
268
+ it('should throw error on failed closure', async () => {
269
+ await fc.assert(
270
+ fc.asyncProperty(fc.uuid(), async (id) => {
271
+ // Mock failed response
272
+ fetchMock.mockResolvedValueOnce({
273
+ ok: false,
274
+ text: async () => 'Closure failed',
275
+ });
276
+
277
+ await expect(manager.close(id)).rejects.toThrow(
278
+ 'Failed to close connection',
279
+ );
280
+ }),
281
+ );
282
+ });
283
+ });
284
+ });
@@ -0,0 +1,79 @@
1
+ import * as fc from 'fast-check';
2
+ import { describe, expect, it } from 'vitest';
3
+ import { Agent, AgentType } from '../../types';
4
+ import { seal, unseal } from '../encryption';
5
+
6
+ // Helper to validate that two objects are deeply equal
7
+ function deepEqual(
8
+ obj1: Record<string, unknown>,
9
+ obj2: Record<string, unknown>,
10
+ ): boolean {
11
+ return JSON.stringify(obj1) === JSON.stringify(obj2);
12
+ }
13
+
14
+ describe('normal tests', () => {
15
+ it('should correctly seal and unseal a Javascript object', async () => {
16
+ const agent: Agent = { type: AgentType.VASP, did: 'did:web:hello.com' };
17
+ const sealed = await seal<Agent>(agent);
18
+ const unsealed = await unseal<Agent>(sealed);
19
+ expect(unsealed).toEqual(agent);
20
+ });
21
+ });
22
+ describe('seal and unseal functions with combined IV and ciphertext', () => {
23
+ it('should correctly seal and unseal a JavaScript object', async () => {
24
+ await fc.assert(
25
+ fc.asyncProperty(
26
+ fc.object(), // Generate random objects
27
+ async (originalObject) => {
28
+ const { ciphertext, key } =
29
+ await seal<Record<string, unknown>>(originalObject); // Seal the object
30
+ const unsealedObject = await unseal<Record<string, unknown>>({
31
+ ciphertext,
32
+ key,
33
+ }); // Unseal the ciphertext
34
+
35
+ // Validate that the unsealed object matches the original
36
+ expect(deepEqual(originalObject, unsealedObject)).toBe(true);
37
+ },
38
+ ),
39
+ );
40
+ });
41
+
42
+ it('should throw an error if the key is invalid', async () => {
43
+ await fc.assert(
44
+ fc.asyncProperty(
45
+ fc.object(),
46
+ fc.string(), // Generate a random invalid key
47
+ async (originalObject, invalidKey) => {
48
+ const { ciphertext } =
49
+ await seal<Record<string, unknown>>(originalObject);
50
+
51
+ await expect(
52
+ unseal<Record<string, unknown>>({ ciphertext, key: invalidKey }),
53
+ ).rejects.toThrowError();
54
+ },
55
+ ),
56
+ );
57
+ });
58
+
59
+ it('should throw an error if the ciphertext is tampered with', async () => {
60
+ await fc.assert(
61
+ fc.asyncProperty(fc.object(), async (originalObject) => {
62
+ const { ciphertext, key } =
63
+ await seal<Record<string, unknown>>(originalObject);
64
+
65
+ // Tamper with the ciphertext
66
+ const tamperedCiphertext =
67
+ ciphertext.slice(0, -1) + (ciphertext.at(-1) === 'A' ? 'B' : 'A');
68
+
69
+ // Expect decryption to fail
70
+ await expect(
71
+ unseal<Record<string, unknown>>({
72
+ ciphertext: tamperedCiphertext,
73
+ key,
74
+ }),
75
+ ).rejects.toThrowError();
76
+ }),
77
+ );
78
+ });
79
+ });
@@ -0,0 +1,174 @@
1
+ import type { ComponentRequest, TransactionOptions, UUID } from '../types';
2
+ import { seal, unseal } from './encryption';
3
+
4
+ export type TransactionType = 'withdraw' | 'deposit';
5
+ export interface ConnectionData<T extends ComponentRequest> {
6
+ tx: T;
7
+ authToken?: string;
8
+ txOptions?: TransactionOptions;
9
+ }
10
+
11
+ export interface ConnectionMetadata {
12
+ nodeUrl?: string;
13
+ participants: string[];
14
+ transactionType: TransactionType;
15
+ }
16
+ export interface ConnectionResponse<T extends ComponentRequest> {
17
+ id: UUID;
18
+ version: number;
19
+ metadata: ConnectionMetadata;
20
+ data: ConnectionData<T>;
21
+ key: string;
22
+ }
23
+
24
+ /**
25
+ * Manages encrypted connections using Cloudflare Durable Objects
26
+ */
27
+ export class ConnectionManager {
28
+ private endpoint: string;
29
+
30
+ constructor(endpoint: string) {
31
+ this.endpoint = endpoint;
32
+ }
33
+
34
+ /**
35
+ * Creates a new encrypted connection
36
+ * @param data The component request data to encrypt and store
37
+ * @param participants Array of participant identifiers
38
+ * @returns Promise resolving to connection details including ID, version, and encryption key
39
+ */
40
+ async create<T extends ComponentRequest>(
41
+ data: ConnectionData<T>,
42
+ metadata: ConnectionMetadata,
43
+ ): Promise<ConnectionResponse<T>> {
44
+ // Encrypt the data
45
+ const sealed = await seal(data);
46
+
47
+ // Prepare the request body
48
+ const body = {
49
+ metadata,
50
+ sealed: sealed.ciphertext,
51
+ };
52
+
53
+ // Create the connection
54
+ const response = await fetch(this.endpoint, {
55
+ method: 'POST',
56
+ headers: {
57
+ 'Content-Type': 'application/json',
58
+ },
59
+ body: JSON.stringify(body),
60
+ });
61
+
62
+ if (!response.ok) {
63
+ throw new Error(`Failed to create connection: ${await response.text()}`);
64
+ }
65
+
66
+ const result = await response.json();
67
+
68
+ return {
69
+ id: result.id,
70
+ version: result.version,
71
+ metadata: metadata,
72
+ data: data,
73
+ key: sealed.key,
74
+ };
75
+ }
76
+
77
+ /**
78
+ * Updates an existing connection with new encrypted data
79
+ * @param id Connection ID
80
+ * @param data New data to encrypt and store
81
+ * @param version Current version number
82
+ * @returns Promise resolving to updated connection details including new encryption key
83
+ */
84
+ async update<T extends ComponentRequest>(
85
+ id: UUID,
86
+ data: ConnectionData<T>,
87
+ version: number,
88
+ ): Promise<ConnectionResponse<T>> {
89
+ // Encrypt the new data
90
+ const sealed = await seal(data);
91
+
92
+ // Prepare the request body
93
+ const body = {
94
+ sealed: sealed.ciphertext,
95
+ version,
96
+ };
97
+
98
+ // Update the connection
99
+ const response = await fetch(`${this.endpoint}/${id}`, {
100
+ method: 'PATCH',
101
+ headers: {
102
+ 'Content-Type': 'application/json',
103
+ },
104
+ body: JSON.stringify(body),
105
+ });
106
+
107
+ if (!response.ok) {
108
+ throw new Error(`Failed to update connection: ${await response.text()}`);
109
+ }
110
+
111
+ const result = await response.json();
112
+
113
+ return {
114
+ id: result.id,
115
+ metadata: result.metadata,
116
+ version: result.version,
117
+ data: data,
118
+ key: sealed.key,
119
+ };
120
+ }
121
+
122
+ /**
123
+ * Retrieves and decrypts connection data
124
+ * @param id Connection ID
125
+ * @param key Encryption key from previous create/update operation
126
+ * @returns Promise resolving to connection details including decrypted data
127
+ */
128
+ async get<T extends ComponentRequest>(
129
+ id: UUID,
130
+ key: string,
131
+ ): Promise<ConnectionResponse<T>> {
132
+ // Get the connection data
133
+ const response = await fetch(`${this.endpoint}/${id}`, {
134
+ method: 'GET',
135
+ });
136
+
137
+ if (!response.ok) {
138
+ throw new Error(`Failed to get connection: ${await response.text()}`);
139
+ }
140
+
141
+ const result = await response.json();
142
+
143
+ // Get the latest sealed data
144
+ const latestSealed = result.sealed[result.sealed.length - 1];
145
+
146
+ // Decrypt the data
147
+ const data = await unseal<ConnectionData<T>>({
148
+ ciphertext: latestSealed,
149
+ key,
150
+ });
151
+
152
+ return {
153
+ id: result.id,
154
+ version: result.version,
155
+ metadata: result.metadata,
156
+ data,
157
+ key,
158
+ };
159
+ }
160
+
161
+ /**
162
+ * Closes a connection
163
+ * @param id Connection ID
164
+ */
165
+ async close(id: UUID): Promise<void> {
166
+ const response = await fetch(`${this.endpoint}/${id}`, {
167
+ method: 'DELETE',
168
+ });
169
+
170
+ if (!response.ok) {
171
+ throw new Error(`Failed to close connection: ${await response.text()}`);
172
+ }
173
+ }
174
+ }
@@ -0,0 +1,111 @@
1
+ /**
2
+ * Result of a sealing operation, containing ciphertext and encryption key.
3
+ */
4
+ export interface Sealed {
5
+ /** Base64-encoded ciphertext combined with initialization vector (IV) */
6
+ ciphertext: string;
7
+ /** Base64-encoded encryption key */
8
+ key: string;
9
+ }
10
+
11
+ /**
12
+ * Encrypts an object using AES-GCM encryption.
13
+ * @template T Type of data to encrypt
14
+ * @param data Data to encrypt
15
+ * @returns Promise resolving to a Sealed object containing ciphertext and key
16
+ */
17
+ export async function seal<T>(data: T): Promise<Sealed> {
18
+ // Convert the object to a JSON string
19
+ const plaintext = JSON.stringify(data);
20
+ const encoder = new TextEncoder();
21
+
22
+ // Generate a random encryption key and IV
23
+ const rawKey = crypto.getRandomValues(new Uint8Array(32)); // 256-bit key
24
+ const key = await crypto.subtle.importKey(
25
+ 'raw',
26
+ rawKey,
27
+ { name: 'AES-GCM' },
28
+ false,
29
+ ['encrypt'],
30
+ );
31
+
32
+ const iv = crypto.getRandomValues(new Uint8Array(12)); // 96-bit IV
33
+
34
+ // Encrypt the plaintext
35
+ const ciphertextBuffer = await crypto.subtle.encrypt(
36
+ { name: 'AES-GCM', iv: iv },
37
+ key,
38
+ encoder.encode(plaintext),
39
+ );
40
+
41
+ // Combine the IV and ciphertext, separated by `-`
42
+ const ciphertext = `${arrayBufferToBase64(iv)}-${arrayBufferToBase64(ciphertextBuffer)}`;
43
+
44
+ // Return the base64 encoded ciphertext and key
45
+ return {
46
+ ciphertext,
47
+ key: arrayBufferToBase64(rawKey),
48
+ };
49
+ }
50
+
51
+ /**
52
+ * Decrypts previously sealed object.
53
+ * @template T Type of data that was encrypted
54
+ * @param sealed Sealed object containing ciphertext and key
55
+ * @returns Promise resolving to the original decrypted data
56
+ */
57
+
58
+ export async function unseal<T>({ ciphertext, key }: Sealed): Promise<T> {
59
+ // Split the IV and the ciphertext
60
+ const [ivBase64, ciphertextBase64] = ciphertext.split('-');
61
+
62
+ // Decode the key, IV, and ciphertext
63
+ const rawKey = new Uint8Array(
64
+ atob(key)
65
+ .split('')
66
+ .map((c) => c.charCodeAt(0)),
67
+ );
68
+ const iv = base64ToUint8Array(ivBase64);
69
+ const ciphertextBuffer = base64ToUint8Array(ciphertextBase64);
70
+
71
+ // Import the key
72
+ const keyObj = await crypto.subtle.importKey(
73
+ 'raw',
74
+ rawKey,
75
+ { name: 'AES-GCM' },
76
+ false,
77
+ ['decrypt'],
78
+ );
79
+
80
+ // Decrypt the ciphertext
81
+ const decoder = new TextDecoder();
82
+ const plaintextBuffer = await crypto.subtle.decrypt(
83
+ { name: 'AES-GCM', iv: new Uint8Array(iv) },
84
+ keyObj,
85
+ ciphertextBuffer,
86
+ );
87
+
88
+ // Parse and return the original object
89
+ return JSON.parse(decoder.decode(plaintextBuffer));
90
+ }
91
+
92
+ // Utility function to convert ArrayBuffer to Base64
93
+ function arrayBufferToBase64(buffer: ArrayBuffer): string {
94
+ const uint8Array = new Uint8Array(buffer);
95
+ let binary = '';
96
+ for (let i = 0; i < uint8Array.length; i++) {
97
+ binary += String.fromCharCode(uint8Array[i]);
98
+ }
99
+ return btoa(binary);
100
+ }
101
+
102
+ // Utility function to convert Base64 to ArrayBuffer
103
+
104
+ function base64ToUint8Array(base64: string): Uint8Array {
105
+ const binary = atob(base64);
106
+ const buffer = new Uint8Array(binary.length);
107
+ for (let i = 0; i < binary.length; i++) {
108
+ buffer[i] = binary.charCodeAt(i);
109
+ }
110
+ return buffer;
111
+ }