@nodatachat/sdk 1.0.0

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,601 @@
1
+ // src/types.ts
2
+ var NoDataError = class extends Error {
3
+ constructor(message, status, code, retryAfter) {
4
+ super(message);
5
+ this.status = status;
6
+ this.code = code;
7
+ this.retryAfter = retryAfter;
8
+ this.name = "NoDataError";
9
+ }
10
+ };
11
+
12
+ // src/client.ts
13
+ var DEFAULT_BASE_URL = "https://www.nodatachat.com";
14
+ var DEFAULT_TIMEOUT = 3e4;
15
+ var DEFAULT_RETRIES = 2;
16
+ var HttpClient = class {
17
+ apiKey;
18
+ baseUrl;
19
+ timeout;
20
+ retries;
21
+ customHeaders;
22
+ onRequest;
23
+ onResponse;
24
+ onError;
25
+ constructor(config) {
26
+ if (!config.apiKey) {
27
+ throw new Error(
28
+ "NoData SDK: apiKey is required. Get one at https://www.nodatachat.com/developers"
29
+ );
30
+ }
31
+ this.apiKey = config.apiKey;
32
+ this.baseUrl = (config.baseUrl || DEFAULT_BASE_URL).replace(/\/+$/, "");
33
+ this.timeout = config.timeout || DEFAULT_TIMEOUT;
34
+ this.retries = config.retries ?? DEFAULT_RETRIES;
35
+ this.customHeaders = config.headers || {};
36
+ this.onRequest = config.onRequest;
37
+ this.onResponse = config.onResponse;
38
+ this.onError = config.onError;
39
+ }
40
+ async request(method, path, body, query) {
41
+ let url = `${this.baseUrl}${path}`;
42
+ if (query) {
43
+ const params = new URLSearchParams(
44
+ Object.fromEntries(Object.entries(query).filter(([, v]) => v != null))
45
+ );
46
+ const qs = params.toString();
47
+ if (qs) url += `?${qs}`;
48
+ }
49
+ const init = {
50
+ method,
51
+ headers: {
52
+ "Authorization": `Bearer ${this.apiKey}`,
53
+ "Content-Type": "application/json",
54
+ "User-Agent": "@nodatachat/sdk/1.0.0",
55
+ "X-SDK-Version": "1.0.0",
56
+ ...this.customHeaders
57
+ },
58
+ signal: AbortSignal.timeout(this.timeout)
59
+ };
60
+ if (body && method !== "GET") {
61
+ init.body = JSON.stringify(body);
62
+ }
63
+ this.onRequest?.(url, init);
64
+ let lastError = null;
65
+ const maxAttempts = 1 + this.retries;
66
+ for (let attempt = 1; attempt <= maxAttempts; attempt++) {
67
+ const start = Date.now();
68
+ try {
69
+ const res = await fetch(url, init);
70
+ const duration = Date.now() - start;
71
+ this.onResponse?.(url, res.status, duration);
72
+ if (res.status === 429 && attempt < maxAttempts) {
73
+ const retryAfter = parseInt(res.headers.get("Retry-After") || "5", 10);
74
+ await sleep(retryAfter * 1e3);
75
+ continue;
76
+ }
77
+ if (res.status >= 500 && attempt < maxAttempts) {
78
+ await sleep(1e3 * attempt);
79
+ continue;
80
+ }
81
+ const data = await res.json().catch(() => ({}));
82
+ if (!res.ok) {
83
+ throw new NoDataError(
84
+ data.error || `HTTP ${res.status}`,
85
+ res.status,
86
+ data.code,
87
+ res.status === 429 ? parseInt(res.headers.get("Retry-After") || "60", 10) : void 0
88
+ );
89
+ }
90
+ return data;
91
+ } catch (err) {
92
+ lastError = err instanceof Error ? err : new Error(String(err));
93
+ this.onError?.(url, lastError);
94
+ if (err instanceof NoDataError) throw err;
95
+ if (attempt < maxAttempts) {
96
+ await sleep(1e3 * attempt);
97
+ continue;
98
+ }
99
+ }
100
+ }
101
+ throw lastError || new Error("Request failed");
102
+ }
103
+ get(path, query) {
104
+ return this.request("GET", path, void 0, query);
105
+ }
106
+ post(path, body) {
107
+ return this.request("POST", path, body);
108
+ }
109
+ del(path, body) {
110
+ return this.request("DELETE", path, body);
111
+ }
112
+ };
113
+ function sleep(ms) {
114
+ return new Promise((resolve) => setTimeout(resolve, ms));
115
+ }
116
+
117
+ // src/encrypt.ts
118
+ var EncryptModule = class {
119
+ constructor(http) {
120
+ this.http = http;
121
+ }
122
+ /**
123
+ * Encrypt a single field value.
124
+ * Server encrypts with AES-256-GCM and returns ciphertext + key material.
125
+ * Store the result in YOUR database — NoData stores nothing.
126
+ */
127
+ async encrypt(req) {
128
+ return this.http.post("/api/v1/encrypt", {
129
+ field: req.field,
130
+ value: req.value,
131
+ context: req.context
132
+ });
133
+ }
134
+ /**
135
+ * Decrypt a single field value.
136
+ * Requires the ciphertext that was returned from encrypt().
137
+ */
138
+ async decrypt(req) {
139
+ return this.http.post("/api/v1/decrypt", {
140
+ ciphertext: req.ciphertext,
141
+ field: req.field,
142
+ requester: req.requester,
143
+ purpose: req.purpose
144
+ });
145
+ }
146
+ /**
147
+ * Encrypt multiple fields in parallel.
148
+ * Failed fields don't block successful ones.
149
+ */
150
+ async batchEncrypt(fields, context) {
151
+ const results = await Promise.allSettled(
152
+ fields.map(
153
+ (f) => this.encrypt({ ...f, context: f.context || context })
154
+ )
155
+ );
156
+ const mapped = results.map((r, i) => {
157
+ if (r.status === "fulfilled") return r.value;
158
+ return {
159
+ success: false,
160
+ ciphertext: "",
161
+ field: fields[i].field,
162
+ audit_id: "",
163
+ algorithm: "",
164
+ error: r.reason?.message || "Encryption failed"
165
+ };
166
+ });
167
+ return {
168
+ success: mapped.every((r) => r.success),
169
+ results: mapped,
170
+ ok: mapped.filter((r) => r.success).length,
171
+ failed: mapped.filter((r) => !r.success).length
172
+ };
173
+ }
174
+ /**
175
+ * Decrypt multiple fields in parallel.
176
+ */
177
+ async batchDecrypt(fields, requester) {
178
+ const results = await Promise.allSettled(
179
+ fields.map(
180
+ (f) => this.decrypt({ ...f, requester: f.requester || requester })
181
+ )
182
+ );
183
+ const mapped = results.map((r, i) => {
184
+ if (r.status === "fulfilled") return r.value;
185
+ return {
186
+ success: false,
187
+ value: "",
188
+ field: fields[i].field,
189
+ audit_id: "",
190
+ error: r.reason?.message || "Decryption failed"
191
+ };
192
+ });
193
+ return {
194
+ success: mapped.every((r) => r.success),
195
+ results: mapped,
196
+ ok: mapped.filter((r) => r.success).length,
197
+ failed: mapped.filter((r) => !r.success).length
198
+ };
199
+ }
200
+ /**
201
+ * Native batch — single HTTP call for up to 100 encrypt/decrypt operations.
202
+ * More efficient than batchEncrypt/batchDecrypt for large batches.
203
+ */
204
+ async batchNative(items, context) {
205
+ return this.http.post("/api/v1/batch", { items, context });
206
+ }
207
+ /**
208
+ * Encrypt all matching fields in a plain object.
209
+ * Walks nested objects and arrays.
210
+ *
211
+ * @example
212
+ * ```ts
213
+ * const encrypted = await nd.encryptObject(
214
+ * { name: "David", phone: "0501234567", email: "d@x.com", age: 30 },
215
+ * ["phone", "email"]
216
+ * );
217
+ * // → { name: "David", phone: "aes256gcm:v1:...", email: "aes256gcm:v1:...", age: 30 }
218
+ * ```
219
+ */
220
+ async encryptObject(obj, fields, context) {
221
+ return this.processObject(obj, fields, async (value, field) => {
222
+ const result = await this.encrypt({ field, value, context });
223
+ return result.ciphertext;
224
+ });
225
+ }
226
+ /**
227
+ * Decrypt all matching fields in an encrypted object.
228
+ */
229
+ async decryptObject(obj, fields, requester) {
230
+ return this.processObject(obj, fields, async (value, field) => {
231
+ const result = await this.decrypt({ ciphertext: value, field, requester });
232
+ return result.value;
233
+ });
234
+ }
235
+ async processObject(obj, fields, processor) {
236
+ if (obj === null || obj === void 0) return obj;
237
+ if (Array.isArray(obj)) {
238
+ return Promise.all(obj.map((item) => this.processObject(item, fields, processor)));
239
+ }
240
+ if (typeof obj === "object") {
241
+ const result = {};
242
+ for (const [key, value] of Object.entries(obj)) {
243
+ if (fields.includes(key) && typeof value === "string" && value.length > 0) {
244
+ result[key] = await processor(value, key);
245
+ } else if (typeof value === "object") {
246
+ result[key] = await this.processObject(value, fields, processor);
247
+ } else {
248
+ result[key] = value;
249
+ }
250
+ }
251
+ return result;
252
+ }
253
+ return obj;
254
+ }
255
+ };
256
+
257
+ // src/channels.ts
258
+ var ChannelModule = class {
259
+ constructor(http) {
260
+ this.http = http;
261
+ }
262
+ /**
263
+ * Create a secure channel for data transfer.
264
+ *
265
+ * Returns a channel_token that the sender uses, and optionally
266
+ * a verification_code for the receiver.
267
+ *
268
+ * @example
269
+ * ```ts
270
+ * // System A creates a channel
271
+ * const ch = await nd.channel.create({ ttl: "1h", requireVerification: true });
272
+ * // Send ch.channel_token to System B (the sender)
273
+ * // Send ch.verification_code to the receiver (out-of-band)
274
+ * ```
275
+ */
276
+ async create(req = {}) {
277
+ return this.http.post("/api/secure-channel/init", {
278
+ label: req.label,
279
+ ttl: req.ttl || "24h",
280
+ max_transfers: req.maxTransfers || 10,
281
+ require_verification: req.requireVerification ?? false
282
+ });
283
+ }
284
+ /**
285
+ * Send data through a secure channel.
286
+ * Data is encrypted in transit — the server never sees plaintext.
287
+ *
288
+ * @example
289
+ * ```ts
290
+ * // System B sends credit card data to System A
291
+ * await nd.channel.send({
292
+ * token: ch.channel_token,
293
+ * data: { card: "4111111111111111", cvv: "123" },
294
+ * burnAfterRead: true,
295
+ * });
296
+ * ```
297
+ */
298
+ async send(req) {
299
+ const payload = typeof req.data === "string" ? req.data : JSON.stringify(req.data);
300
+ return this.http.post("/api/secure-channel/upload", {
301
+ channel_token: req.token,
302
+ content: payload,
303
+ content_type: req.contentType || "application/json",
304
+ burn_after_read: req.burnAfterRead ?? true
305
+ });
306
+ }
307
+ /**
308
+ * Receive data from a secure channel.
309
+ *
310
+ * @example
311
+ * ```ts
312
+ * // System A retrieves the data
313
+ * const result = await nd.channel.receive({
314
+ * token: ch.channel_token,
315
+ * verificationCode: "123456",
316
+ * });
317
+ * const card = JSON.parse(result.data);
318
+ * ```
319
+ */
320
+ async receive(req) {
321
+ return this.http.post("/api/secure-channel/download", {
322
+ channel_token: req.token,
323
+ verification_code: req.verificationCode
324
+ });
325
+ }
326
+ /**
327
+ * Verify a channel recipient with a code (out-of-band verification).
328
+ */
329
+ async verify(token, code) {
330
+ return this.http.post("/api/secure-channel/verify-code", {
331
+ channel_token: token,
332
+ code
333
+ });
334
+ }
335
+ /**
336
+ * Get delivery proof (Merkle-based).
337
+ */
338
+ async proof(channelToken) {
339
+ return this.http.post("/api/secure-channel/delivery-proof", {
340
+ channel_token: channelToken
341
+ });
342
+ }
343
+ };
344
+
345
+ // src/webhooks.ts
346
+ var WebhookModule = class {
347
+ constructor(http) {
348
+ this.http = http;
349
+ }
350
+ /**
351
+ * Create a webhook channel.
352
+ *
353
+ * Returns an ingest_url — point your external system's webhook at it.
354
+ * All payloads are encrypted with PBKDF2 → AES-256-GCM.
355
+ * Only YOU can decrypt (using the returned secret).
356
+ *
357
+ * @example
358
+ * ```ts
359
+ * // Create a webhook channel for Stripe events
360
+ * const wh = await nd.webhook.create({ label: "stripe-payments", ttl: "30d" });
361
+ *
362
+ * // Configure Stripe to POST to: wh.ingest_url
363
+ * // Store wh.secret securely — you need it to decrypt events
364
+ *
365
+ * // Later, poll for events:
366
+ * const events = await nd.webhook.events(wh.channel_token, wh.secret);
367
+ * ```
368
+ */
369
+ async create(req = {}) {
370
+ return this.http.post("/api/webhook/channel/create", {
371
+ label: req.label,
372
+ ttl: req.ttl || "30d",
373
+ max_events: req.maxEvents || 1e4,
374
+ burn_after_read: req.burnAfterRead ?? false
375
+ });
376
+ }
377
+ /**
378
+ * Retrieve encrypted webhook events.
379
+ * Events are returned encrypted — use the secret from create() to decrypt client-side.
380
+ */
381
+ async events(channelToken, options) {
382
+ return this.http.post("/api/webhook/channel/events", {
383
+ channel_token: channelToken,
384
+ limit: options?.limit || 50,
385
+ since: options?.since
386
+ });
387
+ }
388
+ /**
389
+ * List all webhook channels for this API key.
390
+ */
391
+ async list() {
392
+ return this.http.get("/api/webhook/dashboard");
393
+ }
394
+ };
395
+
396
+ // src/deliver.ts
397
+ var DeliverModule = class {
398
+ constructor(http) {
399
+ this.http = http;
400
+ }
401
+ /**
402
+ * Create a secure, self-destructing delivery.
403
+ *
404
+ * Use for: credit card numbers, passwords, API keys, PII.
405
+ * The recipient opens the link, sees the content ONCE, and it burns.
406
+ *
407
+ * @example
408
+ * ```ts
409
+ * // Send a credit card number securely
410
+ * const d = await nd.deliver.send({
411
+ * content: "4111-1111-1111-1111",
412
+ * ttl: "1h",
413
+ * burn: true,
414
+ * maxViews: 1,
415
+ * });
416
+ * // Send d.delivery_url to the recipient
417
+ * // After they open it — gone forever
418
+ * ```
419
+ */
420
+ async send(req) {
421
+ return this.http.post("/api/v1/deliver", {
422
+ content: req.content,
423
+ to: req.to,
424
+ ttl: req.ttl || "24h",
425
+ burn: req.burn ?? true,
426
+ maxViews: req.maxViews || 1
427
+ });
428
+ }
429
+ /**
430
+ * Create an anonymous burn drop (no auth required on read side).
431
+ */
432
+ async burn(content, options) {
433
+ return this.http.post("/api/burn/create", {
434
+ content,
435
+ ttl_hours: options?.ttlHours || 24,
436
+ burn_after_read: options?.burnAfterRead ?? true,
437
+ available_at: options?.availableAt
438
+ });
439
+ }
440
+ /**
441
+ * Read a burn drop (self-destructs on read if configured).
442
+ */
443
+ async read(dropId) {
444
+ return this.http.post("/api/burn/read", { drop_id: dropId });
445
+ }
446
+ };
447
+
448
+ // src/evidence.ts
449
+ var EvidenceModule = class {
450
+ constructor(http) {
451
+ this.http = http;
452
+ }
453
+ /**
454
+ * Query the audit trail.
455
+ * Returns metadata only — never content.
456
+ *
457
+ * @example
458
+ * ```ts
459
+ * const trail = await nd.evidence.query({
460
+ * field: "credit_card",
461
+ * action: "decrypt",
462
+ * from: "2026-03-01",
463
+ * to: "2026-03-27",
464
+ * });
465
+ * // Shows WHO decrypted WHAT field WHEN — for SOC compliance
466
+ * ```
467
+ */
468
+ async query(q = {}) {
469
+ return this.http.get("/api/v1/evidence", {
470
+ from: q.from || "",
471
+ to: q.to || "",
472
+ action: q.action || "",
473
+ field: q.field || "",
474
+ limit: String(q.limit || 100)
475
+ });
476
+ }
477
+ /**
478
+ * Generate a proof certificate for a specific operation.
479
+ */
480
+ async certificate(auditId) {
481
+ return this.http.post("/api/proof-certificate", { audit_id: auditId });
482
+ }
483
+ /**
484
+ * Verify a receipt/proof hash.
485
+ */
486
+ async verify(proofHash) {
487
+ return this.http.post("/api/receipt/verify", { proof_hash: proofHash });
488
+ }
489
+ };
490
+
491
+ // src/vault.ts
492
+ var VaultModule = class {
493
+ constructor(http) {
494
+ this.http = http;
495
+ }
496
+ /**
497
+ * Store an encrypted blob in the vault.
498
+ * YOU encrypt client-side. Server stores blindly.
499
+ *
500
+ * @example
501
+ * ```ts
502
+ * // Encrypt client-side, then store
503
+ * const blob = myEncrypt(sensitiveData, myKey);
504
+ * const vault = await nd.vault.create({
505
+ * label: "customer-contracts",
506
+ * encrypted_blob: blob.ciphertext,
507
+ * iv: blob.iv,
508
+ * metadata: { customer_id: "cust_123" },
509
+ * });
510
+ * ```
511
+ */
512
+ async create(req) {
513
+ return this.http.post("/api/vault/create", req);
514
+ }
515
+ /**
516
+ * Retrieve an encrypted blob from the vault.
517
+ * YOU decrypt client-side.
518
+ */
519
+ async read(vaultId) {
520
+ return this.http.post("/api/vault/read", {
521
+ vault_id: vaultId
522
+ });
523
+ }
524
+ /**
525
+ * Delete a vault entry (irreversible).
526
+ */
527
+ async delete(vaultId) {
528
+ return this.http.post("/api/vault/delete", { vault_id: vaultId });
529
+ }
530
+ /**
531
+ * Check vault service status.
532
+ */
533
+ async status() {
534
+ return this.http.get("/api/vault/status");
535
+ }
536
+ };
537
+
538
+ // src/index.ts
539
+ var NoData = class {
540
+ http;
541
+ _encrypt;
542
+ /** Secure channels — system-to-system encrypted transfer */
543
+ channel;
544
+ /** Webhooks — receive external webhooks through encrypted channels */
545
+ webhook;
546
+ /** Delivery — burn-after-read secure delivery */
547
+ deliver;
548
+ /** Evidence — audit trail + cryptographic proofs */
549
+ evidence;
550
+ /** Vault — zero-knowledge encrypted storage */
551
+ vault;
552
+ constructor(config) {
553
+ this.http = new HttpClient(config);
554
+ this._encrypt = new EncryptModule(this.http);
555
+ this.channel = new ChannelModule(this.http);
556
+ this.webhook = new WebhookModule(this.http);
557
+ this.deliver = new DeliverModule(this.http);
558
+ this.evidence = new EvidenceModule(this.http);
559
+ this.vault = new VaultModule(this.http);
560
+ }
561
+ // ─── Top-level shortcuts ───────────────────────────────
562
+ /** Encrypt a single field (blind relay — server stores nothing) */
563
+ encrypt(req) {
564
+ return this._encrypt.encrypt(req);
565
+ }
566
+ /** Decrypt a single field */
567
+ decrypt(req) {
568
+ return this._encrypt.decrypt(req);
569
+ }
570
+ /** Encrypt multiple fields in parallel */
571
+ batchEncrypt(fields, context) {
572
+ return this._encrypt.batchEncrypt(fields, context);
573
+ }
574
+ /** Decrypt multiple fields in parallel */
575
+ batchDecrypt(fields, requester) {
576
+ return this._encrypt.batchDecrypt(fields, requester);
577
+ }
578
+ /** Single-call batch — up to 100 encrypt/decrypt ops in one HTTP request */
579
+ batchNative(items, context) {
580
+ return this._encrypt.batchNative(items, context);
581
+ }
582
+ /** Encrypt all matching fields in a plain object (deep walk) */
583
+ encryptObject(obj, fields, context) {
584
+ return this._encrypt.encryptObject(obj, fields, context);
585
+ }
586
+ /** Decrypt all matching fields in an encrypted object (deep walk) */
587
+ decryptObject(obj, fields, requester) {
588
+ return this._encrypt.decryptObject(obj, fields, requester);
589
+ }
590
+ /** Health check */
591
+ async ping() {
592
+ const start = Date.now();
593
+ await this.http.get("/api/health");
594
+ return { success: true, latencyMs: Date.now() - start };
595
+ }
596
+ };
597
+
598
+ export {
599
+ NoDataError,
600
+ NoData
601
+ };