@nodatachat/sdk 1.0.0 → 2.1.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,11 @@
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 Dt=Object.defineProperty;var jr=Object.getOwnPropertyDescriptor;var qr=Object.getOwnPropertyNames;var $r=Object.prototype.hasOwnProperty;var Vr=(n,e)=>{for(var t in e)Dt(n,t,{get:e[t],enumerable:!0})},Gr=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of qr(e))!$r.call(n,s)&&s!==t&&Dt(n,s,{get:()=>e[s],enumerable:!(r=jr(e,s))||r.enumerable});return n};var zr=n=>Gr(Dt({},"__esModule",{value:!0}),n);var qs={};Vr(qs,{nodataFastify:()=>js});module.exports=zr(qs);var M=class extends Error{constructor(t,r,s,o){super(t);this.status=r;this.code=s;this.retryAfter=o;this.name="NoDataError"}};var Kr="https://www.nodatacapsule.com",Zr=3e4,Xr=2,Je=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||Kr).replace(/\/+$/,""),this.timeout=e.timeout||Zr,this.retries=e.retries??Xr,this.customHeaders=e.headers||{},this.onRequest=e.onRequest,this.onResponse=e.onResponse,this.onError=e.onError}async request(e,t,r,s){let o=`${this.baseUrl}${t}`;if(s){let d=new URLSearchParams(Object.fromEntries(Object.entries(s).filter(([,l])=>l!=null))).toString();d&&(o+=`?${d}`)}let i={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)};r&&e!=="GET"&&(i.body=JSON.stringify(r)),this.onRequest?.(o,i);let a=null,u=1+this.retries;for(let c=1;c<=u;c++){let d=Date.now();try{let l=await fetch(o,i),h=Date.now()-d;if(this.onResponse?.(o,l.status,h),l.status===429&&c<u){let w=parseInt(l.headers.get("Retry-After")||"5",10);await Ht(w*1e3);continue}if(l.status>=500&&c<u){await Ht(1e3*c);continue}let p=await l.json().catch(()=>({}));if(!l.ok)throw new M(p.error||`HTTP ${l.status}`,l.status,p.code,l.status===429?parseInt(l.headers.get("Retry-After")||"60",10):void 0);return p}catch(l){if(a=l instanceof Error?l:new Error(String(l)),this.onError?.(o,a),l instanceof M)throw l;if(c<u){await Ht(1e3*c);continue}}}throw a||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)}async raw(e,t,r){let s=`${this.baseUrl}${t}`,o={method:e,headers:{Authorization:`Bearer ${this.apiKey}`,"User-Agent":"@nodatachat/sdk/1.0.0","X-SDK-Version":"1.0.0",...r!==void 0?{"Content-Type":"application/json"}:{},...this.customHeaders},signal:AbortSignal.timeout(this.timeout),...r!==void 0?{body:JSON.stringify(r)}:{}};this.onRequest?.(s,o);let i=Date.now(),a=await fetch(s,o);this.onResponse?.(s,a.status,Date.now()-i);let u=await a.json().catch(()=>({})),c=u&&typeof u.data=="object"&&u.data!==null&&!Array.isArray(u.data)?u.data:u;return{ok:a.ok,status:a.status,data:{...c,...u.error?{error:u.error}:{}}}}};function Ht(n){return new Promise(e=>setTimeout(e,n))}var Re=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(o=>this.encrypt({...o,context:o.context||t})))).map((o,i)=>o.status==="fulfilled"?o.value:{success:!1,ciphertext:"",field:e[i].field,audit_id:"",algorithm:"",error:o.reason?.message||"Encryption failed"});return{success:s.every(o=>o.success),results:s,ok:s.filter(o=>o.success).length,failed:s.filter(o=>!o.success).length}}async batchDecrypt(e,t){let s=(await Promise.allSettled(e.map(o=>this.decrypt({...o,requester:o.requester||t})))).map((o,i)=>o.status==="fulfilled"?o.value:{success:!1,value:"",field:e[i].field,audit_id:"",error:o.reason?.message||"Decryption failed"});return{success:s.every(o=>o.success),results:s,ok:s.filter(o=>o.success).length,failed:s.filter(o=>!o.success).length}}async batchNative(e,t){return this.http.post("/api/v1/batch",{items:e,context:t})}async encryptObject(e,t,r){return this.processObject(e,t,async(s,o)=>(await this.encrypt({field:o,value:s,context:r})).ciphertext)}async decryptObject(e,t,r){return this.processObject(e,t,async(s,o)=>(await this.decrypt({ciphertext:s,field:o,requester:r})).value)}async processObject(e,t,r){if(e==null)return e;if(Array.isArray(e))return Promise.all(e.map(s=>this.processObject(s,t,r)));if(typeof e=="object"){let s={};for(let[o,i]of Object.entries(e))t.includes(o)&&typeof i=="string"&&i.length>0?s[o]=await r(i,o):typeof i=="object"?s[o]=await this.processObject(i,t,r):s[o]=i;return s}return e}};var Ce=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})}},Be=class{constructor(e,t){this.baseURL=e;this.grantToken=t}async read(e){let t=e.handle??Yr(this.grantToken);if(!t)throw new M("AgentReader.read: could not derive agent handle from token; pass { handle }",400);let r=`${this.baseURL}/api/agents/${encodeURIComponent(t)}/read`,s=await fetch(r,{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})}),o=await s.json().catch(()=>({}));if(!s.ok)throw new M(o.error||`HTTP ${s.status}`,s.status,o.reason);return o}};function Yr(n){try{let t=(n.startsWith("ndca-")?n.slice(5):n).split(".")[1];if(!t)return null;let r=t.replace(/-/g,"+").replace(/_/g,"/");return JSON.parse(atob(r)).handle??null}catch{return null}}var Qe=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`)}},et=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`)}},tt=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)}},nt=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)}},Te=class{constructor(e,t){this.http=e;this.summary=t;this.documents=new Qe(e,t.slug),this.members=new et(e,t.slug),this.audit=new tt(e,t.slug),this.ai=new nt(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})}},Oe=class{constructor(e){this.http=e}async create(e){let t=await this.http.post("/api/v1/capsules",e);return new Te(this.http,t)}async get(e){let t=await this.http.get(`/api/v1/capsules/${encodeURIComponent(e)}`);return new Te(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 Ie=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 De=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(),r=await this.http.post(`/api/v1/tenants/${encodeURIComponent(t)}/capsule/install-token`,{}),s=r.install_token??"",o=(e.api_base??this.http.baseURL).replace(/\/+$/,""),i=e.source==="folder"?`--source folder --path ${e.path??"./"}`:e.source==="drive"?`--source drive --folder ${e.folder_id??"<folder-id>"}`:`--source ${e.source}`,a=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 ${o} ${i}${a}`,expires_at:r.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 rt=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 st=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 ot=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 it=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 at=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 He=class{governance;blindRelay;channel;deliver;evidence;vault;webhook;constructor(e){this.governance=new Ce(e),this.blindRelay=new Re(e),this.channel=new rt(e),this.deliver=new ot(e),this.evidence=new it(e),this.vault=new at(e),this.webhook=new st(e)}};var Le=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}:{}}),r=(t.sections??[]).map(s=>({title:s.title??"",classification:s.classification??"internal",sent:!!s.sent}));return{decision:t.decision??(r.some(s=>s.sent)?"allow":"deny"),answer:t.answer??null,model:t.model??null,sections:r,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}}};function Lt(n){return n instanceof Uint8Array||ArrayBuffer.isView(n)&&n.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in n&&n.BYTES_PER_ELEMENT===1}function ie(n,e=""){if(typeof n!="number"){let t=e&&`"${e}" `;throw new TypeError(`${t}expected number, got ${typeof n}`)}if(!Number.isSafeInteger(n)||n<0){let t=e&&`"${e}" `;throw new RangeError(`${t}expected integer >= 0, got ${n}`)}}function $(n,e,t=""){let r=Lt(n),s=n?.length,o=e!==void 0;if(!r||o&&s!==e){let i=t&&`"${t}" `,a=o?` of length ${e}`:"",u=r?`length=${s}`:`type=${typeof n}`,c=i+"expected Uint8Array"+a+", got "+u;throw r?new RangeError(c):new TypeError(c)}return n}function Ue(n){if(typeof n!="function"||typeof n.create!="function")throw new TypeError("Hash must wrapped by utils.createHasher");if(ie(n.outputLen),ie(n.blockLen),n.outputLen<1)throw new Error('"outputLen" must be >= 1');if(n.blockLen<1)throw new Error('"blockLen" must be >= 1')}function ve(n,e=!0){if(n.destroyed)throw new Error("Hash instance has been destroyed");if(e&&n.finished)throw new Error("Hash#digest() has already been called")}function ct(n,e){$(n,void 0,"digestInto() output");let t=e.outputLen;if(n.length<t)throw new RangeError('"digestInto() output" expected to be of length >='+t)}function X(...n){for(let e=0;e<n.length;e++)n[e].fill(0)}function ut(n){return new DataView(n.buffer,n.byteOffset,n.byteLength)}function Y(n,e){return n<<32-e|n>>>e}var Bn=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",Wr=Array.from({length:256},(n,e)=>e.toString(16).padStart(2,"0"));function dt(n){if($(n),Bn)return n.toHex();let e="";for(let t=0;t<n.length;t++)e+=Wr[n[t]];return e}var ee={_0:48,_9:57,A:65,F:70,a:97,f:102};function Cn(n){if(n>=ee._0&&n<=ee._9)return n-ee._0;if(n>=ee.A&&n<=ee.F)return n-(ee.A-10);if(n>=ee.a&&n<=ee.f)return n-(ee.a-10)}function Pe(n){if(typeof n!="string")throw new TypeError("hex string expected, got "+typeof n);if(Bn)try{return Uint8Array.fromHex(n)}catch(s){throw s instanceof SyntaxError?new RangeError(s.message):s}let e=n.length,t=e/2;if(e%2)throw new RangeError("hex string expected, got unpadded hex of length "+e);let r=new Uint8Array(t);for(let s=0,o=0;s<t;s++,o+=2){let i=Cn(n.charCodeAt(o)),a=Cn(n.charCodeAt(o+1));if(i===void 0||a===void 0){let u=n[o]+n[o+1];throw new RangeError('hex string expected, got non-hex character "'+u+'" at index '+o)}r[s]=i*16+a}return r}function Ut(...n){let e=0;for(let r=0;r<n.length;r++){let s=n[r];$(s),e+=s.length}let t=new Uint8Array(e);for(let r=0,s=0;r<n.length;r++){let o=n[r];t.set(o,s),s+=o.length}return t}function Pt(n,e={}){let t=(s,o)=>n(o).update(s).digest(),r=n(void 0);return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.canXOF=r.canXOF,t.create=s=>n(s),Object.assign(t,e),Object.freeze(t)}function Tn(n=32){ie(n,"bytesLength");let e=typeof globalThis=="object"?globalThis.crypto:null;if(typeof e?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined");if(n>65536)throw new RangeError(`"bytesLength" expected <= 65536, got ${n}`);return e.getRandomValues(new Uint8Array(n))}var Ft=n=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,n])});function On(n,e,t){return n&e^~n&t}function In(n,e,t){return n&e^n&t^e&t}var Fe=class{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,t,r,s){this.blockLen=e,this.outputLen=t,this.padOffset=r,this.isLE=s,this.buffer=new Uint8Array(e),this.view=ut(this.buffer)}update(e){ve(this),$(e);let{view:t,buffer:r,blockLen:s}=this,o=e.length;for(let i=0;i<o;){let a=Math.min(s-this.pos,o-i);if(a===s){let u=ut(e);for(;s<=o-i;i+=s)this.process(u,i);continue}r.set(e.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===s&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){ve(this),ct(e,this),this.finished=!0;let{buffer:t,view:r,blockLen:s,isLE:o}=this,{pos:i}=this;t[i++]=128,X(this.buffer.subarray(i)),this.padOffset>s-i&&(this.process(r,0),i=0);for(let l=i;l<s;l++)t[l]=0;r.setBigUint64(s-8,BigInt(this.length*8),o),this.process(r,0);let a=ut(e),u=this.outputLen;if(u%4)throw new Error("_sha2: outputLen must be aligned to 32bit");let c=u/4,d=this.get();if(c>d.length)throw new Error("_sha2: outputLen bigger than state");for(let l=0;l<c;l++)a.setUint32(4*l,d[l],o)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let r=e.slice(0,t);return this.destroy(),r}_cloneInto(e){e||=new this.constructor,e.set(...this.get());let{blockLen:t,buffer:r,length:s,finished:o,destroyed:i,pos:a}=this;return e.destroyed=i,e.finished=o,e.length=s,e.pos=a,s%t&&e.buffer.set(r),e}clone(){return this._cloneInto()}},te=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var N=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var lt=BigInt(4294967295),Dn=BigInt(32);function Jr(n,e=!1){return e?{h:Number(n&lt),l:Number(n>>Dn&lt)}:{h:Number(n>>Dn&lt)|0,l:Number(n&lt)|0}}function Hn(n,e=!1){let t=n.length,r=new Uint32Array(t),s=new Uint32Array(t);for(let o=0;o<t;o++){let{h:i,l:a}=Jr(n[o],e);[r[o],s[o]]=[i,a]}return[r,s]}var Mt=(n,e,t)=>n>>>t,Nt=(n,e,t)=>n<<32-t|e>>>t,ge=(n,e,t)=>n>>>t|e<<32-t,be=(n,e,t)=>n<<32-t|e>>>t,Me=(n,e,t)=>n<<64-t|e>>>t-32,Ne=(n,e,t)=>n>>>t-32|e<<64-t;function W(n,e,t,r){let s=(e>>>0)+(r>>>0);return{h:n+t+(s/2**32|0)|0,l:s|0}}var Ln=(n,e,t)=>(n>>>0)+(e>>>0)+(t>>>0),Un=(n,e,t,r)=>e+t+r+(n/2**32|0)|0,Pn=(n,e,t,r)=>(n>>>0)+(e>>>0)+(t>>>0)+(r>>>0),Fn=(n,e,t,r,s)=>e+t+r+s+(n/2**32|0)|0,Mn=(n,e,t,r,s)=>(n>>>0)+(e>>>0)+(t>>>0)+(r>>>0)+(s>>>0),Nn=(n,e,t,r,s,o)=>e+t+r+s+o+(n/2**32|0)|0;var es=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),ae=new Uint32Array(64),jt=class extends Fe{constructor(e){super(64,e,8,!1)}get(){let{A:e,B:t,C:r,D:s,E:o,F:i,G:a,H:u}=this;return[e,t,r,s,o,i,a,u]}set(e,t,r,s,o,i,a,u){this.A=e|0,this.B=t|0,this.C=r|0,this.D=s|0,this.E=o|0,this.F=i|0,this.G=a|0,this.H=u|0}process(e,t){for(let l=0;l<16;l++,t+=4)ae[l]=e.getUint32(t,!1);for(let l=16;l<64;l++){let h=ae[l-15],p=ae[l-2],w=Y(h,7)^Y(h,18)^h>>>3,R=Y(p,17)^Y(p,19)^p>>>10;ae[l]=R+ae[l-7]+w+ae[l-16]|0}let{A:r,B:s,C:o,D:i,E:a,F:u,G:c,H:d}=this;for(let l=0;l<64;l++){let h=Y(a,6)^Y(a,11)^Y(a,25),p=d+h+On(a,u,c)+es[l]+ae[l]|0,R=(Y(r,2)^Y(r,13)^Y(r,22))+In(r,s,o)|0;d=c,c=u,u=a,a=i+p|0,i=o,o=s,s=r,r=p+R|0}r=r+this.A|0,s=s+this.B|0,o=o+this.C|0,i=i+this.D|0,a=a+this.E|0,u=u+this.F|0,c=c+this.G|0,d=d+this.H|0,this.set(r,s,o,i,a,u,c,d)}roundClean(){X(ae)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),X(this.buffer)}},qt=class extends jt{A=te[0]|0;B=te[1]|0;C=te[2]|0;D=te[3]|0;E=te[4]|0;F=te[5]|0;G=te[6]|0;H=te[7]|0;constructor(){super(32)}};var jn=Hn(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(n=>BigInt(n))),ts=jn[0],ns=jn[1],ce=new Uint32Array(80),ue=new Uint32Array(80),$t=class extends Fe{constructor(e){super(128,e,16,!1)}get(){let{Ah:e,Al:t,Bh:r,Bl:s,Ch:o,Cl:i,Dh:a,Dl:u,Eh:c,El:d,Fh:l,Fl:h,Gh:p,Gl:w,Hh:R,Hl:f}=this;return[e,t,r,s,o,i,a,u,c,d,l,h,p,w,R,f]}set(e,t,r,s,o,i,a,u,c,d,l,h,p,w,R,f){this.Ah=e|0,this.Al=t|0,this.Bh=r|0,this.Bl=s|0,this.Ch=o|0,this.Cl=i|0,this.Dh=a|0,this.Dl=u|0,this.Eh=c|0,this.El=d|0,this.Fh=l|0,this.Fl=h|0,this.Gh=p|0,this.Gl=w|0,this.Hh=R|0,this.Hl=f|0}process(e,t){for(let x=0;x<16;x++,t+=4)ce[x]=e.getUint32(t),ue[x]=e.getUint32(t+=4);for(let x=16;x<80;x++){let k=ce[x-15]|0,A=ue[x-15]|0,B=ge(k,A,1)^ge(k,A,8)^Mt(k,A,7),E=be(k,A,1)^be(k,A,8)^Nt(k,A,7),C=ce[x-2]|0,S=ue[x-2]|0,D=ge(C,S,19)^Me(C,S,61)^Mt(C,S,6),H=be(C,S,19)^Ne(C,S,61)^Nt(C,S,6),b=Pn(E,H,ue[x-7],ue[x-16]),_=Fn(b,B,D,ce[x-7],ce[x-16]);ce[x]=_|0,ue[x]=b|0}let{Ah:r,Al:s,Bh:o,Bl:i,Ch:a,Cl:u,Dh:c,Dl:d,Eh:l,El:h,Fh:p,Fl:w,Gh:R,Gl:f,Hh:g,Hl:y}=this;for(let x=0;x<80;x++){let k=ge(l,h,14)^ge(l,h,18)^Me(l,h,41),A=be(l,h,14)^be(l,h,18)^Ne(l,h,41),B=l&p^~l&R,E=h&w^~h&f,C=Mn(y,A,E,ns[x],ue[x]),S=Nn(C,g,k,B,ts[x],ce[x]),D=C|0,H=ge(r,s,28)^Me(r,s,34)^Me(r,s,39),b=be(r,s,28)^Ne(r,s,34)^Ne(r,s,39),_=r&o^r&a^o&a,m=s&i^s&u^i&u;g=R|0,y=f|0,R=p|0,f=w|0,p=l|0,w=h|0,{h:l,l:h}=W(c|0,d|0,S|0,D|0),c=a|0,d=u|0,a=o|0,u=i|0,o=r|0,i=s|0;let v=Ln(D,b,m);r=Un(v,S,H,_),s=v|0}({h:r,l:s}=W(this.Ah|0,this.Al|0,r|0,s|0)),{h:o,l:i}=W(this.Bh|0,this.Bl|0,o|0,i|0),{h:a,l:u}=W(this.Ch|0,this.Cl|0,a|0,u|0),{h:c,l:d}=W(this.Dh|0,this.Dl|0,c|0,d|0),{h:l,l:h}=W(this.Eh|0,this.El|0,l|0,h|0),{h:p,l:w}=W(this.Fh|0,this.Fl|0,p|0,w|0),{h:R,l:f}=W(this.Gh|0,this.Gl|0,R|0,f|0),{h:g,l:y}=W(this.Hh|0,this.Hl|0,g|0,y|0),this.set(r,s,o,i,a,u,c,d,l,h,p,w,R,f,g,y)}roundClean(){X(ce,ue)}destroy(){this.destroyed=!0,X(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},Vt=class extends $t{Ah=N[0]|0;Al=N[1]|0;Bh=N[2]|0;Bl=N[3]|0;Ch=N[4]|0;Cl=N[5]|0;Dh=N[6]|0;Dl=N[7]|0;Eh=N[8]|0;El=N[9]|0;Fh=N[10]|0;Fl=N[11]|0;Gh=N[12]|0;Gl=N[13]|0;Hh=N[14]|0;Hl=N[15]|0;constructor(){super(64)}};var je=Pt(()=>new qt,Ft(1));var ft=Pt(()=>new Vt,Ft(3));var O=(n,e,t)=>$(n,e,t),zt=ie,Kt=dt,J=(...n)=>Ut(...n),qn=n=>Pe(n),gt=Lt,bt=n=>Tn(n),ht=BigInt(0),Gt=BigInt(1);function Ee(n,e=""){if(typeof n!="boolean"){let t=e&&`"${e}" `;throw new TypeError(t+"expected boolean, got type="+typeof n)}return n}function rs(n){if(typeof n=="bigint"){if(!pt(n))throw new RangeError("positive bigint expected, got "+n)}else zt(n);return n}function ne(n,e=""){if(typeof n!="number"){let t=e&&`"${e}" `;throw new TypeError(t+"expected number, got type="+typeof n)}if(!Number.isSafeInteger(n)){let t=e&&`"${e}" `;throw new RangeError(t+"expected safe integer, got "+n)}}function $n(n){if(typeof n!="string")throw new TypeError("hex string expected, got "+typeof n);return n===""?ht:BigInt("0x"+n)}function Zt(n){return $n(dt(n))}function K(n){return $n(dt(de($(n)).reverse()))}function Xt(n,e){if(ie(e),e===0)throw new RangeError("zero length");n=rs(n);let t=n.toString(16);if(t.length>e*2)throw new RangeError("number too large");return Pe(t.padStart(e*2,"0"))}function mt(n,e){return Xt(n,e).reverse()}function Vn(n,e){if(n=O(n),e=O(e),n.length!==e.length)return!1;let t=0;for(let r=0;r<n.length;r++)t|=n[r]^e[r];return t===0}function de(n){return Uint8Array.from(O(n))}function yt(n){if(typeof n!="string")throw new TypeError("ascii string expected, got "+typeof n);return Uint8Array.from(n,(e,t)=>{let r=e.charCodeAt(0);if(e.length!==1||r>127)throw new RangeError(`string contains non-ASCII character "${n[t]}" with code ${r} at position ${t}`);return r})}var pt=n=>typeof n=="bigint"&&ht<=n;function ss(n,e,t){return pt(n)&&pt(e)&&pt(t)&&e<=n&&n<t}function ke(n,e,t,r){if(!ss(e,t,r))throw new RangeError("expected valid "+n+": "+t+" <= n < "+r+", got "+e)}function Yt(n){if(n<ht)throw new Error("expected non-negative bigint, got "+n);let e;for(e=0;n>ht;n>>=Gt,e+=1);return e}var Gn=n=>(Gt<<BigInt(n))-Gt;function re(n,e={},t={}){if(Object.prototype.toString.call(n)!=="[object Object]")throw new TypeError("expected valid options object");function r(o,i,a){if(!a&&i!=="function"&&!Object.hasOwn(n,o))throw new TypeError(`param "${o}" is invalid: expected own property`);let u=n[o];if(a&&u===void 0)return;let c=typeof u;if(c!==i||u===null)throw new TypeError(`param "${o}" is invalid: expected ${i}, got ${c}`)}let s=(o,i)=>Object.entries(o).forEach(([a,u])=>r(a,u,i));s(e,!1),s(t,!0)}var Wt=()=>{throw new Error("not implemented")};var j=BigInt(0),P=BigInt(1),me=BigInt(2),Xn=BigInt(3),Yn=BigInt(4),Wn=BigInt(5),os=BigInt(7),Jn=BigInt(8),is=BigInt(9),Qn=BigInt(16);function I(n,e){if(e<=j)throw new Error("mod: expected positive modulus, got "+e);let t=n%e;return t>=j?t:e+t}function Z(n,e,t){if(e<j)throw new Error("pow2: expected non-negative exponent, got "+e);let r=n;for(;e-- >j;)r*=r,r%=t;return r}function zn(n,e){if(n===j)throw new Error("invert: expected non-zero number");if(e<=j)throw new Error("invert: expected positive modulus, got "+e);let t=I(n,e),r=e,s=j,o=P,i=P,a=j;for(;t!==j;){let c=r/t,d=r-t*c,l=s-i*c,h=o-a*c;r=t,t=d,s=i,o=a,i=l,a=h}if(r!==P)throw new Error("invert: does not exist");return I(s,e)}function Jt(n,e,t){let r=n;if(!r.eql(r.sqr(e),t))throw new Error("Cannot find square root")}function er(n,e){let t=n,r=(t.ORDER+P)/Yn,s=t.pow(e,r);return Jt(t,s,e),s}function as(n,e){let t=n,r=(t.ORDER-Wn)/Jn,s=t.mul(e,me),o=t.pow(s,r),i=t.mul(e,o),a=t.mul(t.mul(i,me),o),u=t.mul(i,t.sub(a,t.ONE));return Jt(t,u,e),u}function cs(n){let e=wt(n),t=tr(n),r=t(e,e.neg(e.ONE)),s=t(e,r),o=t(e,e.neg(r)),i=(n+os)/Qn;return((a,u)=>{let c=a,d=c.pow(u,i),l=c.mul(d,r),h=c.mul(d,s),p=c.mul(d,o),w=c.eql(c.sqr(l),u),R=c.eql(c.sqr(h),u);d=c.cmov(d,l,w),l=c.cmov(p,h,R);let f=c.eql(c.sqr(l),u),g=c.cmov(d,l,f);return Jt(c,g,u),g})}function tr(n){if(n<Xn)throw new Error("sqrt is not defined for small field");let e=n-P,t=0;for(;e%me===j;)e/=me,t++;let r=me,s=wt(n);for(;Kn(s,r)===1;)if(r++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(t===1)return er;let o=s.pow(r,e),i=(e+P)/me;return function(u,c){let d=u;if(d.is0(c))return c;if(Kn(d,c)!==1)throw new Error("Cannot find square root");let l=t,h=d.mul(d.ONE,o),p=d.pow(c,e),w=d.pow(c,i);for(;!d.eql(p,d.ONE);){if(d.is0(p))return d.ZERO;let R=1,f=d.sqr(p);for(;!d.eql(f,d.ONE);)if(R++,f=d.sqr(f),R===l)throw new Error("Cannot find square root");let g=P<<BigInt(l-R-1),y=d.pow(h,g);l=R,h=d.sqr(y),p=d.mul(p,h),w=d.mul(w,y)}return w}}function us(n){return n%Yn===Xn?er:n%Jn===Wn?as:n%Qn===is?cs(n):tr(n)}var se=(n,e)=>(I(n,e)&P)===P,ds=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function nr(n){let e={ORDER:"bigint",BYTES:"number",BITS:"number"},t=ds.reduce((r,s)=>(r[s]="function",r),e);if(re(n,t),ne(n.BYTES,"BYTES"),ne(n.BITS,"BITS"),n.BYTES<1||n.BITS<1)throw new Error("invalid field: expected BYTES/BITS > 0");if(n.ORDER<=P)throw new Error("invalid field: expected ORDER > 1, got "+n.ORDER);return n}function ls(n,e,t){let r=n;if(t<j)throw new Error("invalid exponent, negatives unsupported");if(t===j)return r.ONE;if(t===P)return e;let s=r.ONE,o=e;for(;t>j;)t&P&&(s=r.mul(s,o)),o=r.sqr(o),t>>=P;return s}function _t(n,e,t=!1){let r=n,s=new Array(e.length).fill(t?r.ZERO:void 0),o=e.reduce((a,u,c)=>r.is0(u)?a:(s[c]=a,r.mul(a,u)),r.ONE),i=r.inv(o);return e.reduceRight((a,u,c)=>r.is0(u)?a:(s[c]=r.mul(a,s[c]),r.mul(a,u)),i),s}function Kn(n,e){let t=n,r=(t.ORDER-P)/me,s=t.pow(e,r),o=t.eql(s,t.ONE),i=t.eql(s,t.ZERO),a=t.eql(s,t.neg(t.ONE));if(!o&&!i&&!a)throw new Error("invalid Legendre symbol result");return o?1:i?0:-1}function fs(n,e){if(e!==void 0&&zt(e),n<=j)throw new Error("invalid n length: expected positive n, got "+n);if(e!==void 0&&e<1)throw new Error("invalid n length: expected positive bit length, got "+e);let t=Yt(n);if(e!==void 0&&e<t)throw new Error(`invalid n length: expected bit length (${t}) >= n.length (${e})`);let r=e!==void 0?e:t,s=Math.ceil(r/8);return{nBitLength:r,nByteLength:s}}var Zn=new WeakMap,xt=class{ORDER;BITS;BYTES;isLE;ZERO=j;ONE=P;_lengths;_mod;constructor(e,t={}){if(e<=P)throw new Error("invalid field: expected ORDER > 1, got "+e);let r;this.isLE=!1,t!=null&&typeof t=="object"&&(typeof t.BITS=="number"&&(r=t.BITS),typeof t.sqrt=="function"&&Object.defineProperty(this,"sqrt",{value:t.sqrt,enumerable:!0}),typeof t.isLE=="boolean"&&(this.isLE=t.isLE),t.allowedLengths&&(this._lengths=Object.freeze(t.allowedLengths.slice())),typeof t.modFromBytes=="boolean"&&(this._mod=t.modFromBytes));let{nBitLength:s,nByteLength:o}=fs(e,r);if(o>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=e,this.BITS=s,this.BYTES=o,Object.freeze(this)}create(e){return I(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new TypeError("invalid field element: expected bigint, got "+typeof e);return j<=e&&e<this.ORDER}is0(e){return e===j}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&P)===P}neg(e){return I(-e,this.ORDER)}eql(e,t){return e===t}sqr(e){return I(e*e,this.ORDER)}add(e,t){return I(e+t,this.ORDER)}sub(e,t){return I(e-t,this.ORDER)}mul(e,t){return I(e*t,this.ORDER)}pow(e,t){return ls(this,e,t)}div(e,t){return I(e*zn(t,this.ORDER),this.ORDER)}sqrN(e){return e*e}addN(e,t){return e+t}subN(e,t){return e-t}mulN(e,t){return e*t}inv(e){return zn(e,this.ORDER)}sqrt(e){let t=Zn.get(this);return t||Zn.set(this,t=us(this.ORDER)),t(this,e)}toBytes(e){return this.isLE?mt(e,this.BYTES):Xt(e,this.BYTES)}fromBytes(e,t=!1){O(e);let{_lengths:r,BYTES:s,isLE:o,ORDER:i,_mod:a}=this;if(r){if(e.length<1||!r.includes(e.length)||e.length>s)throw new Error("Field.fromBytes: expected "+r+" bytes, got "+e.length);let c=new Uint8Array(s);c.set(e,o?0:c.length-e.length),e=c}if(e.length!==s)throw new Error("Field.fromBytes: expected "+s+" bytes, got "+e.length);let u=o?K(e):Zt(e);if(a&&(u=I(u,i)),!t&&!this.isValid(u))throw new Error("invalid field element: outside of range 0..ORDER");return u}invertBatch(e){return _t(this,e)}cmov(e,t,r){return Ee(r,"condition"),r?t:e}};Object.freeze(xt.prototype);function wt(n,e={}){return new xt(n,e)}var Rt=BigInt(0),nn=BigInt(1);function rr(n,e){let t=e.negate();return n?t:e}function Et(n,e){let t=_t(n.Fp,e.map(r=>r.Z));return e.map((r,s)=>n.fromAffine(r.toAffine(t[s])))}function ar(n,e){if(!Number.isSafeInteger(n)||n<=0||n>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+n)}function Qt(n,e){ar(n,e);let t=Math.ceil(e/n)+1,r=2**(n-1),s=2**n,o=Gn(n),i=BigInt(n);return{windows:t,windowSize:r,mask:o,maxNumber:s,shiftBy:i}}function sr(n,e,t){let{windowSize:r,mask:s,maxNumber:o,shiftBy:i}=t,a=Number(n&s),u=n>>i;a>r&&(a-=o,u+=nn);let c=e*r,d=c+Math.abs(a)-1,l=a===0,h=a<0,p=e%2!==0;return{nextN:u,offset:d,isZero:l,isNeg:h,isNegF:p,offsetF:c}}var en=new WeakMap,cr=new WeakMap;function tn(n){return cr.get(n)||1}function or(n){if(n!==Rt)throw new Error("invalid wNAF")}var vt=class{BASE;ZERO;Fn;bits;constructor(e,t){this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=t}_unsafeLadder(e,t,r=this.ZERO){let s=e;for(;t>Rt;)t&nn&&(r=r.add(s)),s=s.double(),t>>=nn;return r}precomputeWindow(e,t){let{windows:r,windowSize:s}=Qt(t,this.bits),o=[],i=e,a=i;for(let u=0;u<r;u++){a=i,o.push(a);for(let c=1;c<s;c++)a=a.add(i),o.push(a);i=a.double()}return o}wNAF(e,t,r){if(!this.Fn.isValid(r))throw new Error("invalid scalar");let s=this.ZERO,o=this.BASE,i=Qt(e,this.bits);for(let a=0;a<i.windows;a++){let{nextN:u,offset:c,isZero:d,isNeg:l,isNegF:h,offsetF:p}=sr(r,a,i);r=u,d?o=o.add(rr(h,t[p])):s=s.add(rr(l,t[c]))}return or(r),{p:s,f:o}}wNAFUnsafe(e,t,r,s=this.ZERO){let o=Qt(e,this.bits);for(let i=0;i<o.windows&&r!==Rt;i++){let{nextN:a,offset:u,isZero:c,isNeg:d}=sr(r,i,o);if(r=a,!c){let l=t[u];s=s.add(d?l.negate():l)}}return or(r),s}getPrecomputes(e,t,r){let s=en.get(t);return s||(s=this.precomputeWindow(t,e),e!==1&&(typeof r=="function"&&(s=r(s)),en.set(t,s))),s}cached(e,t,r){let s=tn(e);return this.wNAF(s,this.getPrecomputes(s,e,r),t)}unsafe(e,t,r,s){let o=tn(e);return o===1?this._unsafeLadder(e,t,s):this.wNAFUnsafe(o,this.getPrecomputes(o,e,r),t,s)}createCache(e,t){ar(t,this.bits),cr.set(e,t),en.delete(e)}hasCache(e){return tn(e)!==1}};function ir(n,e,t){if(e){if(e.ORDER!==n)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return nr(e),e}else return wt(n,{isLE:t})}function ur(n,e,t={},r){if(r===void 0&&(r=n==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${n} CURVE object`);for(let u of["p","n","h"]){let c=e[u];if(!(typeof c=="bigint"&&c>Rt))throw new Error(`CURVE.${u} must be positive bigint`)}let s=ir(e.p,t.Fp,r),o=ir(e.n,t.Fn,r),a=["Gx","Gy","a",n==="weierstrass"?"b":"d"];for(let u of a)if(!s.isValid(e[u]))throw new Error(`CURVE.${u} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:s,Fn:o}}function kt(n,e){return function(r){let s=n(r);return{secretKey:s,publicKey:e(s)}}}var le=BigInt(0),F=BigInt(1),rn=BigInt(2),ps=BigInt(8);function hs(n,e,t,r){let s=n.sqr(t),o=n.sqr(r),i=n.add(n.mul(e.a,s),o),a=n.add(n.ONE,n.mul(e.d,n.mul(s,o)));return n.eql(i,a)}function dr(n,e={}){let t=e,r=ur("edwards",n,t,t.FpFnLE),{Fp:s,Fn:o}=r,i=r.CURVE,{h:a}=i;re(t,{},{uvRatio:"function"});let u=rn<<BigInt(o.BYTES*8)-F,c=R=>s.create(R),d=t.uvRatio===void 0?(R,f)=>{try{return{isValid:!0,value:s.sqrt(s.div(R,f))}}catch{return{isValid:!1,value:le}}}:t.uvRatio;if(!hs(s,i,i.Gx,i.Gy))throw new Error("bad curve params: generator point");function l(R,f,g=!1){let y=g?F:le;return ke("coordinate "+R,f,y,u),f}function h(R){if(!(R instanceof p))throw new Error("EdwardsPoint expected")}class p{static BASE=new p(i.Gx,i.Gy,F,c(i.Gx*i.Gy));static ZERO=new p(le,F,F,le);static Fp=s;static Fn=o;X;Y;Z;T;constructor(f,g,y,x){this.X=l("x",f),this.Y=l("y",g),this.Z=l("z",y,!0),this.T=l("t",x),Object.freeze(this)}static CURVE(){return i}static fromAffine(f){if(f instanceof p)throw new Error("extended point not allowed");let{x:g,y}=f||{};return l("x",g),l("y",y),new p(g,y,F,c(g*y))}static fromBytes(f,g=!1){let y=s.BYTES,{a:x,d:k}=i;f=de(O(f,y,"point")),Ee(g,"zip215");let A=de(f),B=f[y-1];A[y-1]=B&-129;let E=K(A),C=g?u:s.ORDER;ke("point.y",E,le,C);let S=c(E*E),D=c(S-F),H=c(k*S-x),{isValid:b,value:_}=d(D,H);if(!b)throw new Error("bad point: invalid y coordinate");let m=(_&F)===F,v=(B&128)!==0;if(!g&&_===le&&v)throw new Error("bad point: x=0 and x_0=1");return v!==m&&(_=c(-_)),p.fromAffine({x:_,y:E})}static fromHex(f,g=!1){return p.fromBytes(qn(f),g)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(f=8,g=!0){return w.createCache(this,f),g||this.multiply(rn),this}assertValidity(){let f=this,{a:g,d:y}=i;if(f.is0())throw new Error("bad point: ZERO");let{X:x,Y:k,Z:A,T:B}=f,E=c(x*x),C=c(k*k),S=c(A*A),D=c(S*S),H=c(E*g),b=c(S*c(H+C)),_=c(D+c(y*c(E*C)));if(b!==_)throw new Error("bad point: equation left != right (1)");let m=c(x*k),v=c(A*B);if(m!==v)throw new Error("bad point: equation left != right (2)")}equals(f){h(f);let{X:g,Y:y,Z:x}=this,{X:k,Y:A,Z:B}=f,E=c(g*B),C=c(k*x),S=c(y*B),D=c(A*x);return E===C&&S===D}is0(){return this.equals(p.ZERO)}negate(){return new p(c(-this.X),this.Y,this.Z,c(-this.T))}double(){let{a:f}=i,{X:g,Y:y,Z:x}=this,k=c(g*g),A=c(y*y),B=c(rn*c(x*x)),E=c(f*k),C=g+y,S=c(c(C*C)-k-A),D=E+A,H=D-B,b=E-A,_=c(S*H),m=c(D*b),v=c(S*b),T=c(H*D);return new p(_,m,T,v)}add(f){h(f);let{a:g,d:y}=i,{X:x,Y:k,Z:A,T:B}=this,{X:E,Y:C,Z:S,T:D}=f,H=c(x*E),b=c(k*C),_=c(B*y*D),m=c(A*S),v=c((x+k)*(E+C)-H-b),T=m-_,L=m+_,U=c(b-g*H),q=c(v*T),V=c(L*U),G=c(v*U),z=c(T*L);return new p(q,V,z,G)}subtract(f){return h(f),this.add(f.negate())}multiply(f){if(!o.isValidNot0(f))throw new RangeError("invalid scalar: expected 1 <= sc < curve.n");let{p:g,f:y}=w.cached(this,f,x=>Et(p,x));return Et(p,[g,y])[0]}multiplyUnsafe(f){if(!o.isValid(f))throw new RangeError("invalid scalar: expected 0 <= sc < curve.n");return f===le?p.ZERO:this.is0()||f===F?this:w.unsafe(this,f,g=>Et(p,g))}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){return w.unsafe(this,i.n).is0()}toAffine(f){let g=this,y=f,{X:x,Y:k,Z:A}=g,B=g.is0();y==null&&(y=B?ps:s.inv(A));let E=c(x*y),C=c(k*y),S=s.mul(A,y);if(B)return{x:le,y:F};if(S!==F)throw new Error("invZ was invalid");return{x:E,y:C}}clearCofactor(){return a===F?this:this.multiplyUnsafe(a)}toBytes(){let{x:f,y:g}=this.toAffine(),y=s.toBytes(g);return y[y.length-1]|=f&F?128:0,y}toHex(){return Kt(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let w=new vt(p,o.BITS);return o.BITS>=8&&p.BASE.precompute(8),Object.freeze(p.prototype),Object.freeze(p),p}var At=class{static BASE;static ZERO;static Fp;static Fn;ep;constructor(e){this.ep=e}static fromBytes(e){Wt()}static fromHex(e){Wt()}get x(){return this.toAffine().x}get y(){return this.toAffine().y}clearCofactor(){return this}assertValidity(){this.ep.assertValidity()}toAffine(e){return this.ep.toAffine(e)}toHex(){return Kt(this.toBytes())}toString(){return this.toHex()}isTorsionFree(){return!0}isSmallOrder(){return!1}add(e){return this.assertSame(e),this.init(this.ep.add(e.ep))}subtract(e){return this.assertSame(e),this.init(this.ep.subtract(e.ep))}multiply(e){return this.init(this.ep.multiply(e))}multiplyUnsafe(e){return this.init(this.ep.multiplyUnsafe(e))}double(){return this.init(this.ep.double())}negate(){return this.init(this.ep.negate())}precompute(e,t){return this.ep.precompute(e,t),this}};function lr(n,e,t={}){if(typeof e!="function")throw new Error('"hash" function param is required');let r=e,s=t;re(s,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",zip215:"boolean",mapToCurve:"function"});let{prehash:o}=s,{BASE:i,Fp:a,Fn:u}=n,c=r.outputLen,d=2*a.BYTES;if(c!==void 0&&(ne(c,"hash.outputLen"),c!==d))throw new Error(`hash.outputLen must be ${d}, got ${c}`);let l=s.randomBytes===void 0?bt:s.randomBytes,h=s.adjustScalarBytes===void 0?b=>b:s.adjustScalarBytes,p=s.domain===void 0?(b,_,m)=>{if(Ee(m,"phflag"),_.length||m)throw new Error("Contexts/pre-hash are not supported");return b}:s.domain;function w(b){return u.create(K(b))}function R(b){let _=E.secretKey;O(b,E.secretKey,"secretKey");let m=O(r(b),2*_,"hashedSecretKey"),v=h(m.slice(0,_)),T=m.slice(_,2*_),L=w(v);return{head:v,prefix:T,scalar:L}}function f(b){let{head:_,prefix:m,scalar:v}=R(b),T=i.multiply(v),L=T.toBytes();return{head:_,prefix:m,scalar:v,point:T,pointBytes:L}}function g(b){return f(b).pointBytes}function y(b=Uint8Array.of(),..._){let m=J(..._);return w(r(p(m,O(b,void 0,"context"),!!o)))}function x(b,_,m={}){b=O(b,void 0,"message"),o&&(b=o(b));let{prefix:v,scalar:T,pointBytes:L}=f(_),U=y(m.context,v,b),q=i.multiply(U).toBytes(),V=y(m.context,q,L,b),G=u.create(U+V*T);if(!u.isValid(G))throw new Error("sign failed: invalid s");let z=J(q,u.toBytes(G));return O(z,E.signature,"result")}let k={zip215:s.zip215};function A(b,_,m,v=k){let{context:T}=v,L=v.zip215===void 0?!!k.zip215:v.zip215,U=E.signature;b=O(b,U,"signature"),_=O(_,void 0,"message"),m=O(m,E.publicKey,"publicKey"),L!==void 0&&Ee(L,"zip215"),o&&(_=o(_));let q=U/2,V=b.subarray(0,q),G=K(b.subarray(q,U)),z,Ze,we;try{z=n.fromBytes(m,L),Ze=n.fromBytes(V,L),we=i.multiplyUnsafe(G)}catch{return!1}if(!L&&z.isSmallOrder())return!1;let Xe=y(T,V,m,_);return Ze.add(z.multiplyUnsafe(Xe)).subtract(we).clearCofactor().is0()}let B=a.BYTES,E={secretKey:B,publicKey:B,signature:2*B,seed:B};function C(b){return b=b===void 0?l(E.seed):b,O(b,E.seed,"seed")}function S(b){return gt(b)&&b.length===E.secretKey}function D(b,_){try{return!!n.fromBytes(b,_===void 0?k.zip215:_)}catch{return!1}}let H={getExtendedPublicKey:f,randomSecretKey:C,isValidSecretKey:S,isValidPublicKey:D,toMontgomery(b){let{y:_}=n.fromBytes(b),m=E.publicKey,v=m===32;if(!v&&m!==57)throw new Error("only defined for 25519 and 448");let T=v?a.div(F+_,F-_):a.div(_-F,_+F);return a.toBytes(T)},toMontgomerySecret(b){let _=E.secretKey;O(b,_);let m=r(b.subarray(0,_));return h(m).subarray(0,_)}};return Object.freeze(E),Object.freeze(H),Object.freeze({keygen:kt(C,g),getPublicKey:g,sign:x,verify:A,utils:H,Point:n,lengths:E})}function qe(n,e){if(ne(n),ne(e),e<0||e>4)throw new Error("invalid I2OSP length: "+e);if(n<0||n>2**(8*e)-1)throw new Error("invalid I2OSP input: "+n);let t=Array.from({length:e}).fill(0);for(let r=e-1;r>=0;r--)t[r]=n&255,n>>>=8;return new Uint8Array(t)}function gs(n,e){let t=new Uint8Array(n.length);for(let r=0;r<n.length;r++)t[r]=n[r]^e[r];return t}function bs(n){if(!gt(n)&&typeof n!="string")throw new Error("DST must be Uint8Array or ascii string");let e=typeof n=="string"?yt(n):n;if(e.length===0)throw new Error("DST must be non-empty");return e}function sn(n,e,t,r){O(n),ne(t),e=bs(e),e.length>255&&(e=r(J(yt("H2C-OVERSIZE-DST-"),e)));let{outputLen:s,blockLen:o}=r,i=Math.ceil(t/s);if(t>65535||i>255)throw new Error("expand_message_xmd: invalid lenInBytes");let a=J(e,qe(e.length,1)),u=new Uint8Array(o),c=qe(t,2),d=new Array(i),l=r(J(u,n,c,qe(0,1),a));d[0]=r(J(l,qe(1,1),a));for(let p=1;p<i;p++){let w=[gs(l,d[p-1]),qe(p+1,1),a];d[p]=r(J(...w))}return J(...d).slice(0,t)}var fr="HashToScalar-";var $e=BigInt(0),Ae=BigInt(1),St=BigInt(2);function ms(n){return re(n,{P:"bigint",type:"string",adjustScalarBytes:"function",powPminus2:"function"},{randomBytes:"function"}),Object.freeze({...n})}function pr(n){let e=ms(n),{P:t,type:r,adjustScalarBytes:s,powPminus2:o,randomBytes:i}=e,a=r==="x25519";if(!a&&r!=="x448")throw new Error("invalid type");let u=i===void 0?bt:i,c=a?255:448,d=a?32:56,l=BigInt(a?9:5),h=BigInt(a?121665:39081),p=a?St**BigInt(254):St**BigInt(447),w=a?BigInt(8)*St**BigInt(251)-Ae:BigInt(4)*St**BigInt(445)-Ae,R=p+w+Ae,f=m=>I(m,t),g=y(l);function y(m){return mt(f(m),d)}function x(m){let v=de(O(m,d,"uCoordinate"));return a&&(v[31]&=127),f(K(v))}function k(m){return K(s(de(O(m,d,"scalar"))))}function A(m,v){let T=D(x(v),k(m));if(T===$e)throw new Error("invalid private or public key received");return y(T)}function B(m){return A(m,g)}let E=B,C=A;function S(m,v,T){let L=f(m*(v-T));return v=f(v-L),T=f(T+L),{x_2:v,x_3:T}}function D(m,v){ke("u",m,$e,t),ke("scalar",v,p,R);let T=v,L=m,U=Ae,q=$e,V=m,G=Ae,z=$e;for(let we=BigInt(c-1);we>=$e;we--){let Xe=T>>we&Ae;z^=Xe,{x_2:U,x_3:V}=S(z,U,V),{x_2:q,x_3:G}=S(z,q,G),z=Xe;let Ye=U+q,We=f(Ye*Ye),It=U-q,Rn=f(It*It),vn=We-Rn,Mr=V+G,Nr=V-G,En=f(Nr*Ye),kn=f(Mr*It),An=En+kn,Sn=En-kn;V=f(An*An),G=f(L*f(Sn*Sn)),U=f(We*Rn),q=f(vn*(We+f(h*vn)))}({x_2:U,x_3:V}=S(z,U,V)),{x_2:q,x_3:G}=S(z,q,G);let Ze=o(q);return f(U*Ze)}let H={secretKey:d,publicKey:d,seed:d},b=m=>(m=m===void 0?u(d):m,O(m,H.seed,"seed"),m),_={randomSecretKey:b};return Object.freeze(H),Object.freeze(_),Object.freeze({keygen:kt(b,E),getSharedSecret:C,getPublicKey:E,scalarMult:A,scalarMultBase:B,utils:_,GuBytes:g.slice(),lengths:H})}var ys=BigInt(0),oe=BigInt(1),hr=BigInt(2),xs=BigInt(3),_s=BigInt(5),ws=BigInt(8),ye=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),un={p:ye,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:ws,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function mr(n){let e=BigInt(10),t=BigInt(20),r=BigInt(40),s=BigInt(80),o=ye,a=n*n%o*n%o,u=Z(a,hr,o)*a%o,c=Z(u,oe,o)*n%o,d=Z(c,_s,o)*c%o,l=Z(d,e,o)*d%o,h=Z(l,t,o)*l%o,p=Z(h,r,o)*h%o,w=Z(p,s,o)*p%o,R=Z(w,s,o)*p%o,f=Z(R,e,o)*d%o;return{pow_p_5_8:Z(f,hr,o)*n%o,b2:a}}function yr(n){return n[0]&=248,n[31]&=127,n[31]|=64,n}var on=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function dn(n,e){let t=ye,r=I(e*e*e,t),s=I(r*r*e,t),o=mr(n*s).pow_p_5_8,i=I(n*r*o,t),a=I(e*i*i,t),u=i,c=I(i*on,t),d=a===n,l=a===I(-n,t),h=a===I(-n*on,t);return d&&(i=u),(l||h)&&(i=c),se(i,t)&&(i=I(-i,t)),{isValid:d||l,value:i}}var pe=dr(un,{uvRatio:dn}),fe=pe.Fp,xr=pe.Fn;function Rs(n){return lr(pe,ft,Object.assign({adjustScalarBytes:yr,zip215:!0},n))}var _r=Rs({});var xe=(()=>{let n=ye;return pr({P:n,type:"x25519",powPminus2:e=>{let{pow_p_5_8:t,b2:r}=mr(e);return I(Z(t,xs,n)*r,n)},adjustScalarBytes:yr})})();var an=on,vs=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),Es=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),ks=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),As=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952"),gr=n=>dn(oe,n),Ss=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),cn=n=>fe.create(K(n)&Ss);function br(n){let{d:e}=un,t=ye,r=g=>fe.create(g),s=r(an*n*n),o=r((s+oe)*ks),i=BigInt(-1),a=r((i-e*s)*r(s+e)),{isValid:u,value:c}=dn(o,a),d=r(c*n);se(d,t)||(d=r(-d)),u||(c=d),u||(i=s);let l=r(i*(s-oe)*As-a),h=c*c,p=r((c+c)*a),w=r(l*vs),R=r(oe-h),f=r(oe+h);return new pe(r(p*f),r(R*w),r(w*f),r(p*R))}var he=class n extends At{static BASE=new n(pe.BASE);static ZERO=new n(pe.ZERO);static Fp=fe;static Fn=xr;constructor(e){super(e)}static fromAffine(e){return new n(pe.fromAffine(e))}assertSame(e){if(!(e instanceof n))throw new Error("RistrettoPoint expected")}init(e){return new n(e)}static fromBytes(e){$(e,32);let{a:t,d:r}=un,s=ye,o=k=>fe.create(k),i=cn(e);if(!Vn(fe.toBytes(i),e)||se(i,s))throw new Error("invalid ristretto255 encoding 1");let a=o(i*i),u=o(oe+t*a),c=o(oe-t*a),d=o(u*u),l=o(c*c),h=o(t*r*d-l),{isValid:p,value:w}=gr(o(h*l)),R=o(w*c),f=o(w*R*h),g=o((i+i)*R);se(g,s)&&(g=o(-g));let y=o(u*f),x=o(g*y);if(!p||se(x,s)||y===ys)throw new Error("invalid ristretto255 encoding 2");return new n(new pe(g,y,oe,x))}static fromHex(e){return n.fromBytes(Pe(e))}toBytes(){let{X:e,Y:t,Z:r,T:s}=this.ep,o=ye,i=f=>fe.create(f),a=i(i(r+t)*i(r-t)),u=i(e*t),c=i(u*u),{value:d}=gr(i(a*c)),l=i(d*a),h=i(d*u),p=i(l*h*s),w;if(se(s*p,o)){let f=i(t*an),g=i(e*an);e=f,t=g,w=i(l*Es)}else w=h;se(e*p,o)&&(t=i(-t));let R=i((r-t)*w);return se(R,o)&&(R=i(-R)),fe.toBytes(R)}equals(e){this.assertSame(e);let{X:t,Y:r}=this.ep,{X:s,Y:o}=e.ep,i=c=>fe.create(c),a=i(t*o)===i(r*s),u=i(r*o)===i(t*s);return a||u}is0(){return this.equals(n.ZERO)}};Object.freeze(he.BASE);Object.freeze(he.ZERO);Object.freeze(he.prototype);Object.freeze(he);var Cs=Object.freeze({Point:he,hashToCurve(n,e){let t=e?.DST===void 0?"ristretto255_XMD:SHA-512_R255MAP_RO_":e.DST,r=sn(n,t,64,ft);return Cs.deriveToCurve(r)},hashToScalar(n,e={DST:fr}){let t=sn(n,e.DST,64,ft);return xr.create(K(t))},deriveToCurve(n){$(n,64);let e=cn(n.subarray(0,32)),t=br(e),r=cn(n.subarray(32,64)),s=br(r);return new he(t.add(s))}});var Ct=class{oHash;iHash;blockLen;outputLen;canXOF=!1;finished=!1;destroyed=!1;constructor(e,t){if(Ue(e),$(t,void 0,"key"),this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let r=this.blockLen,s=new Uint8Array(r);s.set(t.length>r?e.create().update(t).digest():t);for(let o=0;o<s.length;o++)s[o]^=54;this.iHash.update(s),this.oHash=e.create();for(let o=0;o<s.length;o++)s[o]^=106;this.oHash.update(s),X(s)}update(e){return ve(this),this.iHash.update(e),this}digestInto(e){ve(this),ct(e,this),this.finished=!0;let t=e.subarray(0,this.outputLen);this.iHash.digestInto(t),this.oHash.update(t),this.oHash.digestInto(t),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||=Object.create(Object.getPrototypeOf(this),{});let{oHash:t,iHash:r,finished:s,destroyed:o,blockLen:i,outputLen:a}=this;return e=e,e.finished=s,e.destroyed=o,e.blockLen=i,e.outputLen=a,e.oHash=t._cloneInto(e.oHash),e.iHash=r._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},ln=(()=>{let n=((e,t,r)=>new Ct(e,t).update(r).digest());return n.create=(e,t)=>new Ct(e,t),n})();function Bs(n,e,t){return Ue(n),t===void 0&&(t=new Uint8Array(n.outputLen)),ln(n,t,e)}var fn=Uint8Array.of(0),wr=Uint8Array.of();function Ts(n,e,t,r=32){Ue(n),ie(r,"length"),$(e,void 0,"prk");let s=n.outputLen;if(e.length<s)throw new Error('"prk" must be at least HashLen octets');if(r>255*s)throw new Error("Length must be <= 255*HashLen");let o=Math.ceil(r/s);t===void 0?t=wr:$(t,void 0,"info");let i=new Uint8Array(o*s),a=ln.create(n,e),u=a._cloneInto(),c=new Uint8Array(a.outputLen);for(let d=0;d<o;d++)fn[0]=d+1,u.update(d===0?wr:c).update(t).update(fn).digestInto(c),i.set(c,s*d),a._cloneInto(u);return a.destroy(),u.destroy(),X(c,fn),i.slice(0,r)}var Rr=(n,e,t,r,s)=>Ts(n,Bs(n,e,t),r,s);var Os=new TextEncoder().encode("mygate-e2e-sealed-box-v1"),Ve=32,Se=12;function pn(n){let e="";for(let t=0;t<n.length;t++)e+=String.fromCharCode(n[t]);return typeof btoa<"u"?btoa(e):Buffer.from(e,"binary").toString("base64")}function hn(n){if(typeof atob<"u"){let e=atob(n),t=new Uint8Array(e.length);for(let r=0;r<e.length;r++)t[r]=e.charCodeAt(r);return t}return new Uint8Array(Buffer.from(n,"base64"))}function Ge(n){return Array.from(n,e=>e.toString(16).padStart(2,"0")).join("")}function _e(n){if(n.length%2!==0)throw new Error("hex length must be even");let e=new Uint8Array(n.length/2);for(let t=0;t<e.length;t++)e[t]=parseInt(n.slice(t*2,t*2+2),16);return e}function vr(...n){let e=0;for(let s of n)e+=s.length;let t=new Uint8Array(e),r=0;for(let s of n)t.set(s,r),r+=s.length;return t}function Er(n){let e=new Uint8Array(n);return globalThis.crypto.getRandomValues(e),e}function kr(){return xe.utils.randomSecretKey()}function gn(n){return xe.getPublicKey(n)}async function Ar(n){if(n.length!==32)throw new Error(`AES-256-GCM key must be 32 bytes, got ${n.length}`);return globalThis.crypto.subtle.importKey("raw",n,{name:"AES-GCM"},!1,["encrypt","decrypt"])}async function Sr(n,e){let t=await Ar(n),r=Er(Se),s=await globalThis.crypto.subtle.encrypt({name:"AES-GCM",iv:r},t,e);return{ciphertext:new Uint8Array(s),nonce:r}}async function Cr(n,e,t){if(t.length!==Se)throw new Error(`AES-GCM nonce must be ${Se} bytes`);let r=await Ar(n),s=await globalThis.crypto.subtle.decrypt({name:"AES-GCM",iv:t},r,e);return new Uint8Array(s)}function Br(n,e,t){return Rr(je,n,vr(e,t),Os,32)}async function Is(n,e){if(n.length!==32)throw new Error("X25519 recipient public key must be 32 bytes");let t=xe.utils.randomSecretKey(),r=xe.getPublicKey(t),s=xe.getSharedSecret(t,n),o=Br(s,r,n),{ciphertext:i,nonce:a}=await Sr(o,e);return vr(r,a,i)}async function Ds(n,e,t){if(t.length<Ve+Se+16)throw new Error("sealed box payload too short");let r=t.slice(0,Ve),s=t.slice(Ve,Ve+Se),o=t.slice(Ve+Se),i=xe.getSharedSecret(n,r),a=Br(i,r,e);return Cr(a,o,s)}async function Tr(n,e){let t=Er(32),{ciphertext:r,nonce:s}=await Sr(t,e),o=await Is(_e(n),t);return{ciphertext_b64:pn(r),wrapped_key_b64:pn(o),payload_iv_b64:pn(s)}}async function Or(n,e){let t=_e(n),r=gn(t),s=await Ds(t,r,hn(e.wrapped_key_b64));return Cr(s,hn(e.ciphertext_b64),hn(e.payload_iv_b64))}var Ir="application/vnd.nodata.command+json",Dr="nodata.command/1";var Hs=/^[a-z][a-z0-9_]*(\.[a-z][a-z0-9_]*){1,3}$/,Ls=/^[a-z][a-z0-9_]{0,63}$/;function bn(n){if(!n||typeof n!="object"||Array.isArray(n))return{ok:!1,reason:"not_an_object"};let e=n,t=new Set(["nodata","id","cmd","fields","reply_to","issued_at"]),r=Object.keys(e).filter(i=>!t.has(i));if(r.length)return{ok:!1,reason:`unexpected_keys:${r.join(",")}`};if(e.nodata!==Dr)return{ok:!1,reason:"not_a_command"};if(typeof e.id!="string"||!/^[0-9a-f-]{36}$/i.test(e.id))return{ok:!1,reason:"bad_id"};if(typeof e.cmd!="string"||!Hs.test(e.cmd))return{ok:!1,reason:"bad_cmd"};if(e.reply_to!==null&&(typeof e.reply_to!="string"||!/^[0-9a-f-]{36}$/i.test(e.reply_to)))return{ok:!1,reason:"bad_reply_to"};if(typeof e.issued_at!="string"||Number.isNaN(Date.parse(e.issued_at)))return{ok:!1,reason:"bad_issued_at"};if(!e.fields||typeof e.fields!="object"||Array.isArray(e.fields))return{ok:!1,reason:"bad_fields"};let s=e.fields,o=Object.keys(s);if(o.length>64)return{ok:!1,reason:"too_many_fields"};for(let i of o){if(!Ls.test(i))return{ok:!1,reason:`bad_field_name:${i}`};let a=s[i];if(!(a===null||typeof a=="boolean"||typeof a=="number"||typeof a=="string"))return{ok:!1,reason:`field_not_flat:${i}`};if(typeof a=="string"&&a.length>2e3)return{ok:!1,reason:`field_too_long:${i}`}}return{ok:!0,envelope:e}}function Hr(n,e,t=null,r=new Date){let s=typeof crypto<"u"&&"randomUUID"in crypto?crypto.randomUUID():Us();return{nodata:Dr,id:s,cmd:n,fields:e,reply_to:t,issued_at:r.toISOString()}}function Us(){let n=new Uint8Array(16);globalThis.crypto.getRandomValues(n),n[6]=n[6]&15|64,n[8]=n[8]&63|128;let e=Array.from(n,t=>t.toString(16).padStart(2,"0")).join("");return`${e.slice(0,8)}-${e.slice(8,12)}-${e.slice(12,16)}-${e.slice(16,20)}-${e.slice(20)}`}function mn(n){let e=t=>t===null||typeof t!="object"?t:Array.isArray(t)?t.map(e):Object.fromEntries(Object.keys(t).sort().map(r=>[r,e(t[r])]));return JSON.stringify(e(n))}var ri={"read-request":{name:"request.json",maxBytes:16384},"read-refused":{name:"refused.json",maxBytes:16384},"folder-projection":{name:"projection.json",maxBytes:48*1024}};var yn={version:1,note:"NoData's public signing keys, pinned. chain_keys sign receipts and epoch seal roots; pack_envelope_signers sign evidence-pack envelopes. Source: https://nodatachat.com/api/chain/pubkey at publish time. A key counts only once a published version of this package lists it. receipt_context_since: when the key began signing receipts in their signing context (server mig 612, read from production 2026-10-19); a context-free receipt it signed after that (+15 min) fails verification.",pinned_from:"https://nodatachat.com/api/chain/pubkey (chain key, read 2026-09-30) \xB7 claude_identities where admin_user_id = the pack-signing identity (envelope signer, read 2026-09-30)",chain_keys:[{kid:"nd-chain-2026-05-03-bc58",ed25519_pubkey_hex:"b525adfa0035d5c7351b514a0316142586de9468ec5ee3b708cff0c4585b5036",ml_dsa65_pubkey_hex:"cc46f06f86d1b4a608a4c1167f1494a4cd1a837d215ff88e7b1aca49e82be3f32e190e1836d477670bae2c8a6f7648d3ce0d93b2f51ab0d3150d7dd45b0cf8217f119388e5a4b3770459654c4b0caab4d8a0ccdafdbc5231cd6c26410c38cd0ec62b21bf73b8e1e82daca3b1e4d520d9d25041917f4fd2b92bb19ffbe50f569ca29fa0185923732949daf5f832805303ef5a020cf3ea9de395d66e54d9bf52a56875087096cd8470918b7f25d623335c8662e7c8e6cefce7b88cc4cc6f7d32ed0f1a00332606af78332e9febb72b7e77b396b9da5ff96167055305595327ead40d2084a50f0d3fcd2423d8ed46edc5459ed1b0ff5a14f142bb38511b99a6da841895ccd65c19ab856bbdee270b48bc01ee8b0243fbc6e806851831409e5ae90d9c3300a9125042fd9b6d381c3eb09d5ee6f33e36bd5b41572bcce0350af8e217963154b550a163c5203f9a38a65312f23088c568d5af720c2ff4e979491109ca9ffdb9edc46f31410939e0264cbc02ea0106f9d6c8616222655e6593f8be5b9fa4423afec46aea9d53e42eb5d3f976cdd86d978a4599b87198d4fb8054bc40828f4d0100131537030053645616ecf48d013f8bbafb3a404735b7ffd6c88273765af340e84207f48be92e909ece357fa6ea2050e085570f413e48179a5aaac2bf216e54714d3ee1102e91fd23305b50b14b133299be4517d074732976b003a6669ecbceb2e40a8a1b2f4ca2b2a25d017b404b21672a0de61a45fd153684d730dc126f30a406d6b06447180258a9659cb3de926abd997b3f740c2783e334dd914ac663abc7f96217844ef0611619c35e30ed55f1563d8183b9f586d6c34715ce68708806105426e897df1473d53da835bed6288951238ed694c154655455ff61e13caeb592cc2857537fe9d2eb723bcad3898396af9673ba5b2f722092f0d2a9388e960ccde7272df5e2fe0ea9e499a909b655a59c85cfa1c622c651c8af20b4fb8bab9ab78d951c621d4b75c812246b2e925bcde42cc6a0a13467b4bcfb9aea5e4949effc71769dccc619eafc6d229cba478e3ad7289dc14b0c4842b4cf0cadd30deb9375fc1659d084779819705a6da7bccbf8d21ecd82391de5b61126d5b872f7d95514717b6fdc218dc0a048364c46142b114ee10d582740668f5b105edc034eb794c7e3906c77a44677e67709dbb1d3078783b488473e83e457e6ab98d2d659cf50066bc7f01190e065a9ef955e0257535bd5fab8ad007673637b2d005349e7f19fea2eeea82597867d5e366e41993775e4f4f70869fb1f9989d6d9902787f8233e9c7e586fe6bcf799ecf2da02ce08232ef1315b4e8857bcdb58bda53991f529d2ff023d0279552396dd0bb0fceaaf5dfb9eda0160bb09dd92b8085bc92c6006c20409cf9a5079072a09df221a76efc5ec13c97d154d22e382018ed8eb767f77aae578121c2231fe964338e637e7c060d555a2574b49c08956c729e79090b917e162488b1c9e962a3a921ac6f98a8c020c48aa2812f2f7a205a2d23aa2be1a953d9e33fbdea94688cf3d44200ed2cb009be8b684e99a96f0bc59eff5490eee0636b8b5665d7ddbb6ad44b90caa62b524f8a1caf6d0dbbc5e2ef0c2e65976d94e80e8dbd5ab8a420fdb638562bd2181c0ca243496582bab2847394e1e2dd4a24d4b24794b770b2475916746fb2bdc50f7994b4b346bfcfc5b4a99266cdf551340903d6994206ae1edb968c15d89f2a4cc6f3cb27b88989489b598f76fb6d1afa52e3a4c73175a216fa30d76acfccade7adb5628a88931b37bcff93c615a78a0b47827e385395e0b53c683f2ff07dd6cc636a086c295f06766570fc7652568676ecc5869378bdc0a63753807f1c7de7e5525d48328fa4103ed2ce9abafe0dc861055be6943cf2a87371ec1f9205c1955ddcf2f2ca982d877040dc92bf64278273c5ebbe3de0ef9d5eae255359e7ac97123b92488ffd0f1ea7deca36110135e02988be06bba4a3bf1b0da067976a6bc0c166ac349b2a853eb204fec6c142cad3decb05da15448f0d82d5faed3bc4beb400c51e05de06d950c128e2d3323a2d47dbf88684970084ed6608b95d7d585c3762c714c063c0a4ce1cacd5b31f261376bd972982957150dbbeb158999c1f60a76c6233a8749c10c016e0ad69bdac19e8c4d28126b7cc79c79aa82c25cef5521afdd759ca198b77c1a4a5f2c0497a4136e9818113c612d109de2cfaba691e05b791474599bf5cb918097f07b95dde658d2c5c01bf2bb6715dcb40c4c5686ec1642f9fd84377a90ea2456561ff91ba798d98211975c3da57be1b1e57a4660f979407e5f8616c4f62730161d2dcd86cf5383665c64cb77abbcf2e1406bc189e9575e3c1407aa6a467e6bd7a8edf7affde32b88dfa178902163a37c6b6c6bacb777a0bfbf46a0324c0ae5de7c2bdb6aad6ce51c0f5b4a5ab7c139d6bcdacc8ea46e37e040b785dbfc3145e408593c6f143dc1b4fde763e32e6d60c32d1a5c6d0bdf2d7d97f2bdeeba4a439abe7c75daced72a7678af1412f6c2917e39d6419c103f3a32e964369136a1183feb8d484712bcde8b14e2e8a7374dfb0dd7ee07dd15727b340005ed98bf5850b9de92b1912639e15f91d16968cd8bc336afc132ec6c93deba843e636de52f32be6e3c1e0ea50fdf03206c8dfa74f4c600e7d4d133c2ccc61ac50ae2f54e4f1ad02dc7ec86d8732cf12f0ac2c2ee10de6829695e539a6f76f9d9a4cda9d2ed1377c7a203baff1b",created_at:"2026-05-03T08:06:17.512936+00:00",retired_at:null,receipt_context_since:"2026-10-19T09:50:04.571Z"}],pack_envelope_signers:[{kid:"pack-signer-2026-04-29",ed25519_pubkey_hex:"853a62cb452a35fd6499d8fedb97448e0e24ef0d071343b2c9652aa2831bbdf6",status:"active",created_at:"2026-04-29T18:20:16.11538+00:00"}]};var wn=[...yn.chain_keys.filter(n=>!n.retired_at).map(n=>n.ed25519_pubkey_hex.toLowerCase()),...yn.pack_envelope_signers.map(n=>n.ed25519_pubkey_hex.toLowerCase())];function Fr(n){return Ge(je(_e(n))).slice(0,16)}var Lr="connect-command",ze=/^[0-9a-f]{16}$/,Fs=/^[a-z][a-z0-9_]*(\.[a-z][a-z0-9_]*){1,3}$/,Bt=class extends M{constructor(t,r,s,o){super(o,428,"approval_required");this.approveUrl=t;this.approvalId=r;this.orgApprovalId=s;this.name="FabricApprovalRequired"}};function xn(){return Ge(kr())}var Ke=class{constructor(e){this.http=e}newSecret(){return xn()}async open(e={}){let t=(e.secret??xn()).trim().toLowerCase();if(!/^[0-9a-f]{64}$/.test(t))throw new Error("nd.fabric: secret must be 64 hex characters (nd.fabric.newSecret())");let r=Ge(gn(_e(t))),s=await this.http.raw("POST",`/api/v1/relay/enroll${e.replace?"?replace=true":""}`,{ecdh_pubkey_hex:r});if(!s.ok)throw Q("enroll",s);let o=String(s.data.ecdh_kid??"");if(!ze.test(o))throw new M("enroll answered without an address",s.status);if(o!==Fr(r))throw new M("enroll answered an address that is not this key's",s.status,"address_mismatch");return new Tt(this.http,t,o,(e.trustedReceiptKeys??wn).map(i=>i.toLowerCase()))}},Tt=class{constructor(e,t,r,s=wn){this.http=e;this.secret=t;this.address=r;this.trustedReceiptKeys=s}async invite(e={}){let t=await this.http.raw("POST","/api/v1/fabric-grants",{action:"invite",my_kid:this.address,template:"ping",...e.note?{note:e.note}:{},...e.days?{grant_days:e.days}:{},...Pr(e)});if(!t.ok)throw Q("invite",t);return{url:String(t.data.invite_url??""),expiresAt:typeof t.data.expires_at=="string"?t.data.expires_at:null,grantDays:typeof t.data.grant_days=="number"?t.data.grant_days:null}}async accept(e,t={}){let r=e.match(/invite=([^&\s]+)/),s=decodeURIComponent(r?r[1]:e.trim());if(!s.includes("."))throw new Error("nd.fabric.accept: give the invitation link or its token");let o=await this.http.raw("POST","/api/v1/fabric-grants",{action:"accept",token:s,subject_kid:this.address,mutual:t.oneWay!==!0,...t.termsAccepted?{terms_accepted:!0}:{},...Pr(t)});if(!o.ok)throw Q("accept",o);let i=o.data.partner??{};if(!i.sender_kid||!ze.test(i.sender_kid))throw new M("connected, but the invitation named no address of theirs to send to (they invited without one)",o.status,"no_partner_address");return{kid:i.sender_kid,name:i.name??null}}async partners(){let e=await this.http.raw("GET","/api/v1/fabric-grants");if(!e.ok)throw Q("partners",e);return Ms(e.data)}async send(e,t,r={},s={}){if(!Fs.test(t))throw new Error(`nd.fabric.send: '${t}' is not a command name (e.g. order.create)`);let o=await this.addressOf(e),i=Hr(t,r,s.replyTo??null),a=bn(i);if(!a.ok)throw new Error(`nd.fabric.send: not a command (${a.reason})`);let u=mn(i),c=await this.http.raw("GET",`/api/v1/relay/resolve?handle=${encodeURIComponent(o)}`);if(!c.ok)throw Q("resolve",c);let d=String(c.data.recipient_pubkey??"");if(!/^[0-9a-f]{64}$/.test(d))throw new M(`${o} has no public key to seal to`,c.status,"no_public_key");if(Fr(d)!==o)throw new M(`the key the directory gave for ${o} is not that address's key; nothing was sent`,c.status,"key_mismatch");let l=await Tr(d,new TextEncoder().encode(u)),h=await this.http.raw("POST","/api/v1/relay/send",{recipient_kid:o,...l,route_taken:"capsule",content_type_hint:Ir,purpose:Lr,ttl_hours:Math.min(Math.max(s.ttlHours??24,1),720),max_fetches:Math.min(Math.max(s.opens??1,1),20),released_sha256:Ur(u)});if(!h.ok)throw Q("send",h);return{id:String(h.data.id??""),commandId:i.id,to:o}}reply(e,t,r={}){if(!e.commandId)throw new Error("nd.fabric.reply: this message was not an opened command");return this.send(e.from,t,r,{replyTo:e.commandId})}async inbox(e={}){let t=await this.http.raw("GET","/api/v1/relay/inbox");if(!t.ok)throw Q("inbox",t);let r=(t.data.items??[]).filter(i=>i.purpose===Lr),s=e.accept?new Set(e.accept):null,o=[];for(let i of r){let a={relayId:i.id,from:i.sender_kid,fromOrg:i.sender?.org??null},u=await this.http.raw("GET",`/api/v1/relay/fetch/${encodeURIComponent(i.id)}`);if(!u.ok){o.push({...a,status:"unopened",reason:String(u.data.refused??u.data.error??u.status),verified:{committed:null,receiptSignature:null}});continue}let c=Ns(u.data.receipt,this.trustedReceiptKeys),d=null;try{let p=await Or(this.secret,u.data),w=bn(JSON.parse(new TextDecoder().decode(p)));d=w.ok?w.envelope:null}catch{d=null}if(!d){o.push({...a,status:"refused",reason:"not_a_command",verified:{committed:null,receiptSignature:c}});continue}let h={committed:typeof u.data.released_sha256=="string"?Ur(mn(d))===u.data.released_sha256:null,receiptSignature:c};if(s&&!s.has(d.cmd)){o.push({...a,status:"refused",reason:`not_accepted:${d.cmd}`,cmd:d.cmd,commandId:d.id,verified:h});continue}o.push({...a,status:"accepted",cmd:d.cmd,fields:d.fields,replyTo:d.reply_to,commandId:d.id,issuedAt:d.issued_at,verified:h})}return o}async disconnect(e){let t=await this.addressOf(e),r=await this.http.raw("GET","/api/v1/fabric-grants");if(!r.ok)throw Q("partners",r);let s=(r.data.grants??[]).filter(a=>!a.revoked_at&&a.subject_kid===t),o=(r.data.inbound??[]).filter(a=>a.subject_kid===this.address&&(a.allowed_sender_kids??[]).includes(t)),i=0;for(let a of s){let u=await this.http.raw("PATCH","/api/v1/fabric-grants",{grant_id:a.id,reason:"disconnected from the SDK"});if(!u.ok)throw Q("disconnect",u);i++}for(let a of o){let u=await this.http.raw("POST","/api/v1/fabric-grants",{action:"leave",grant_id:a.id});if(!u.ok)throw Q("disconnect",u);i++}return{ended:i}}async addressOf(e){if(typeof e!="string")return e.kid;let t=e.trim().toLowerCase();if(ze.test(t))return t;let r=(await this.partners()).filter(s=>(s.name??"").toLowerCase()===t);if(r.length===1)return r[0].kid;throw new Error(r.length?`nd.fabric: '${e}' names ${r.length} connections; use the address`:`nd.fabric: no connection named '${e}'`)}};function Ms(n){let e=new Map;for(let t of n.grants??[])!t.revoked_at&&ze.test(t.subject_kid)&&e.set(t.subject_kid,{kid:t.subject_kid,name:t.partner_name??null});for(let t of n.inbound??[])for(let r of t.allowed_sender_kids??[]){if(!ze.test(r))continue;let s=e.get(r);e.set(r,{kid:r,name:s?.name??t.partner_name??null})}return[...e.values()]}function Ur(n){return Ge(je(new TextEncoder().encode(n)))}function _n(n){if(n===null||typeof n!="object")return JSON.stringify(n);if(Array.isArray(n))return"["+n.map(_n).join(",")+"]";let e=n;return"{"+Object.keys(e).sort().map(t=>JSON.stringify(t)+":"+_n(e[t])).join(",")+"}"}function Ns(n,e=wn){let t=n;if(!t?.payload||!t.signature_hex||!t.signing_pubkey_hex)return null;if(!e.includes(t.signing_pubkey_hex.toLowerCase()))return!1;try{return _r.verify(_e(t.signature_hex),new TextEncoder().encode(_n(t.payload)),_e(t.signing_pubkey_hex))}catch{return!1}}function Pr(n){return n.orgApprovalId?{org_approval_id:n.orgApprovalId}:n.approvalId?{approval_id:n.approvalId}:{}}function Q(n,e){let t=e.data;if(e.status===428){let s=typeof t.approval=="object"&&t.approval!==null?t.approval:{},o=typeof t.lock=="object"&&t.lock!==null?t.lock:{};return new Bt((s.approve_url??(typeof t.approve_url=="string"?t.approve_url:null))||null,s.approval_id??null,o.lock_id??null,`${n}: waiting for a person's approval${t.why?` (${String(t.why)})`:""}. Approve it in the browser, then call again with the approval id.`)}let r=String(t.refused??t.error??`HTTP ${e.status}`);return new M(`${n} refused: ${r}${t.reason?` (${String(t.reason)})`:t.why?` (${String(t.why)})`:""}`,e.status,String(t.refused??t.error??""))}var Ot=class{http;_encrypt;capsules;tenants;scan;fabric;engines;_compute;constructor(e){this.http=new Je(e),this._compute=new Le(this.http),this._encrypt=new Re(this.http),this.capsules=new Oe(this.http),this.tenants=new Ie(this.http),this.scan=new De(this.http),this.fabric=new Ke(this.http),this.engines=new He(this.http)}compute(e){return this._compute.run(e)}verify(e){return this._compute.verify(e)}authorize(e){return this.http.post("/api/v1/authorize",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 Be(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,r){return this._encrypt.encryptObject(e,t,r)}decryptObject(e,t,r){return this._encrypt.decryptObject(e,t,r)}async ping(){let e=Date.now();return await this.http.get("/api/health"),{success:!0,latencyMs:Date.now()-e}}};function js(n,e,t){let r=new Ot({apiKey:e.apiKey,baseUrl:e.baseUrl}),s=e.encryptFields||[],o=e.decryptFields||[],i=e.skipPaths||[];o.length>0&&n.addHook("preHandler",async a=>{if(i.some(c=>a.url.startsWith(c))||!a.body||typeof a.body!="object"||a.method==="GET")return;if(!e.decryptHeader||a.headers[e.decryptHeader.toLowerCase()])try{a.body=await r.decryptObject(a.body,o,a.headers["x-requester"]||"fastify-plugin")}catch{}}),s.length>0&&n.addHook("onSend",async(a,u,c)=>{if(typeof c!="string")return c;try{let d=JSON.parse(c);if(typeof d=="object"&&d!==null){let l=await r.encryptObject(d,s,e.context);return JSON.stringify(l)}}catch{}return c}),t()}0&&(module.exports={nodataFastify});
2
+ /*! Bundled license information:
3
+
4
+ @noble/curves/utils.js:
5
+ @noble/curves/abstract/modular.js:
6
+ @noble/curves/abstract/curve.js:
7
+ @noble/curves/abstract/edwards.js:
8
+ @noble/curves/abstract/montgomery.js:
9
+ @noble/curves/ed25519.js:
10
+ (*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
11
+ */