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