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