@nodatachat/mcp 1.3.0 → 1.3.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,31 +1,31 @@
1
1
  #!/usr/bin/env node
2
- /*! @nodatachat/mcp 1.3.0 | Copyright 2026 Capsule Ltd. | FSL-1.1-ALv2 | see LICENSE.md */
2
+ /*! @nodatachat/mcp 1.3.2 | Copyright 2026 Capsule Ltd. | FSL-1.1-ALv2 | see LICENSE.md */
3
3
  import{createRequire as __ndReq}from"node:module";const require=__ndReq(import.meta.url);
4
- var za=Object.create;var Er=Object.defineProperty;var Ya=Object.getOwnPropertyDescriptor;var Xa=Object.getOwnPropertyNames;var Za=Object.getPrototypeOf,Qa=Object.prototype.hasOwnProperty;var A=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,n)=>(typeof require<"u"?require:t)[n]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var O=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var ei=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Xa(t))!Qa.call(e,o)&&o!==n&&Er(e,o,{get:()=>t[o],enumerable:!(r=Ya(t,o))||r.enumerable});return e};var kr=(e,t,n)=>(n=e!=null?za(Za(e)):{},ei(t||!e||!e.__esModule?Er(n,"default",{value:e,enumerable:!0}):n,e));var kn=O(Y=>{"use strict";Object.defineProperty(Y,"__esModule",{value:!0});Y.MAX_SEALED_BYTES=void 0;Y.kidForPublicKey=Gr;Y.deriveKeyPairFromSeed=Ui;Y.generateSeed=Hi;Y.buildEnvInfo=Vi;Y.sealDek=Gi;Y.openSealedDek=qi;Y.decodeSealHeader=qr;var Ur=A("crypto"),Lr=A("@hpke/core"),Ki=A("@hpke/dhkem-x25519"),ji=A("@hpke/chacha20poly1305"),Mi=A("@noble/curves/ed25519.js"),Fi=A("@noble/hashes/hkdf.js"),Li=A("@noble/hashes/sha2.js"),Dt=new Lr.CipherSuite({kem:new Ki.DhkemX25519HkdfSha256,kdf:new Lr.HkdfSha256,aead:new ji.Chacha20Poly1305}),Hr=1,Vr=1;Y.MAX_SEALED_BYTES=4096;function Gr(e){return(0,Ur.createHash)("sha256").update(e).digest("hex").slice(0,16)}function Ui(e){if(e.length<16)throw new Error("seed too short (need at least 16 bytes)");let t=new TextEncoder().encode("protect.env.x25519.v1"),n=Buffer.from((0,Fi.hkdf)(Li.sha256,e,new Uint8Array(0),t,32)),r=Buffer.from(Mi.x25519.scalarMultBase(n));return{secretKey:n,publicKey:r,kid:Gr(r)}}function Hi(){return(0,Ur.randomBytes)(32)}function Vi(e){return Buffer.from(`protect.env.v3|${e}`,"utf8")}async function Gi(e,t,n){if(e.length!==32)throw new Error("sealDek: DEK must be 32 bytes");if(t.length!==32)throw new Error("sealDek: public key must be 32 bytes");let r=await Dt.kem.deserializePublicKey(Te(t)),o=await Dt.createSenderContext({recipientPublicKey:r,info:Te(n)}),a=Buffer.from(await o.seal(Te(e),new ArrayBuffer(0))),i=Buffer.from(o.enc),s=Buffer.alloc(6+i.length+a.length);return s[0]=Hr,s[1]=Vr,s.writeUInt16BE(i.length,2),s.writeUInt16BE(a.length,4),i.copy(s,6),a.copy(s,6+i.length),s}async function qi(e,t,n){let r=qr(e),o=e.subarray(6,6+r.encLen),a=e.subarray(6+r.encLen),i=await Dt.kem.deserializePrivateKey(Te(t)),s=await Dt.createRecipientContext({recipientKey:i,enc:Te(o),info:Te(n)});return Buffer.from(await s.open(Te(a)))}function qr(e){if(e.length<6)throw new Error("sealed bytes too short");if(e.length>Y.MAX_SEALED_BYTES)throw new Error("sealed bytes too long");let t=e[0],n=e[1];if(t!==Hr)throw new Error(`unsupported seal version 0x${t.toString(16)}`);if(n!==Vr)throw new Error(`unsupported HPKE suite 0x${n.toString(16)}`);let r=e.readUInt16BE(2),o=e.readUInt16BE(4);if(e.length!==6+r+o)throw new Error("sealed length mismatch");if(r!==32)throw new Error("unexpected KEM enc length (X25519 is 32 bytes)");if(o<16)throw new Error("ciphertext shorter than the AEAD tag");return{ver:t,suite:n,encLen:r,ctLen:o}}function Te(e){return e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength)}});var Jr=O(pe=>{"use strict";Object.defineProperty(pe,"__esModule",{value:!0});pe.V3_PREFIX=void 0;pe.sealValue=Wi;pe.formatToken=Ji;pe.parseToken=Wr;pe.openValue=zi;var Ot=A("crypto"),Nt=kn();pe.V3_PREFIX="aes256gcm:v3:";async function Wi(e,t){let n=(0,Ot.randomBytes)(32),r=(0,Ot.randomBytes)(12),o=(0,Ot.createCipheriv)("aes-256-gcm",n,r),a=Buffer.concat([o.update(e,"utf8"),o.final()]),i=Buffer.concat([a,o.getAuthTag()]),s=await(0,Nt.sealDek)(n,t.publicKey,(0,Nt.buildEnvInfo)(t.kid));return n.fill(0),{sealedDekB64:s.toString("base64"),iv:r,cipher:i}}function Ji(e,t){return`${pe.V3_PREFIX}${e.iv.toString("base64")}:${e.cipher.toString("base64")}:${t}`}function Wr(e){let t=e.split(":");if(t.length!==5||t[0]!=="aes256gcm"||t[1]!=="v3")throw new Error("not a v3 token");let[,,n,r,o]=t;if(!o)throw new Error("v3 token has no seal id");let a=Buffer.from(n,"base64"),i=Buffer.from(r,"base64");if(a.length!==12)throw new Error("v3 token has a malformed iv");if(i.length<17)throw new Error("v3 token ciphertext is too short");return{iv:a,cipher:i,sealId:o}}async function zi(e,t,n){let{iv:r,cipher:o}=Wr(e),a=await(0,Nt.openSealedDek)(Buffer.from(t,"base64"),n.secretKey,(0,Nt.buildEnvInfo)(n.kid)),i=o.subarray(o.length-16),s=o.subarray(0,o.length-16),l=(0,Ot.createDecipheriv)("aes-256-gcm",a,r);l.setAuthTag(i);try{return Buffer.concat([l.update(s),l.final()]).toString("utf8")}finally{a.fill(0)}}});var Zr=O(V=>{"use strict";var Yi=V&&V.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n);var o=Object.getOwnPropertyDescriptor(t,n);(!o||("get"in o?!t.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,o)}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),Xi=V&&V.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),An=V&&V.__importStar||(function(){var e=function(t){return e=Object.getOwnPropertyNames||function(n){var r=[];for(var o in n)Object.prototype.hasOwnProperty.call(n,o)&&(r[r.length]=o);return r},e(t)};return function(t){if(t&&t.__esModule)return t;var n={};if(t!=null)for(var r=e(t),o=0;o<r.length;o++)r[o]!=="default"&&Yi(n,t,r[o]);return Xi(n,t),n}})();Object.defineProperty(V,"__esModule",{value:!0});V.deviceKeyPath=Qi;V.hasDeviceKey=es;V.loadDeviceKey=ts;V.createDeviceKey=ns;V.importDeviceKey=rs;V.exportSeedHex=os;V.deviceKeyIsExposed=as;var W=An(A("fs")),Zi=An(A("os")),zr=An(A("path")),it=kn(),xn=zr.join(Zi.homedir(),".nodata"),M=zr.join(xn,"device-key.json");function Qi(){return M}function Yr(){let e=process.env.NODATA_DEVICE_SEED;if(!e)return null;let t=e.trim();if(!/^[0-9a-fA-F]{64}$/.test(t))throw new Error("NODATA_DEVICE_SEED must be 64 hex characters (32 bytes)");return Buffer.from(t,"hex")}function es(){return Yr()!==null||W.existsSync(M)}function ts(){let e=Yr();if(e)return(0,it.deriveKeyPairFromSeed)(e);if(!W.existsSync(M))return null;let t;try{t=JSON.parse(W.readFileSync(M,"utf-8"))}catch{throw new Error(`Device key file is unreadable: ${M}`)}if(!t.seed_hex||!/^[0-9a-f]{64}$/i.test(t.seed_hex))throw new Error(`Device key file is malformed (bad seed): ${M}`);let n=(0,it.deriveKeyPairFromSeed)(Buffer.from(t.seed_hex,"hex"));if(t.kid&&t.kid!==n.kid)throw new Error(`Device key file is inconsistent: stored kid ${t.kid} does not match the seed (${n.kid}).`);return n}function ns(e={}){if(W.existsSync(M)&&!e.force)throw new Error(`A device key already exists at ${M}. Replacing it makes every existing v3 seal unopenable. Back up the seed first (nodata key export), then pass --force.`);let t=(0,it.generateSeed)(),n=(0,it.deriveKeyPairFromSeed)(t);return Xr(t,n),n}function rs(e,t={}){let n=e.trim().replace(/\s+/g,"");if(!/^[0-9a-fA-F]{64}$/.test(n))throw new Error("Seed must be 64 hex characters (32 bytes).");if(W.existsSync(M)&&!t.force)throw new Error(`A device key already exists at ${M}. Pass --force to replace it.`);let r=Buffer.from(n,"hex"),o=(0,it.deriveKeyPairFromSeed)(r);return Xr(r,o),o}function os(){if(!W.existsSync(M))throw new Error("No device key file to export.");return JSON.parse(W.readFileSync(M,"utf-8")).seed_hex}function Xr(e,t){W.existsSync(xn)||W.mkdirSync(xn,{recursive:!0});let n={version:1,kid:t.kid,pubkey_hex:t.publicKey.toString("hex"),seed_hex:e.toString("hex"),created_at:new Date().toISOString()};W.writeFileSync(M,JSON.stringify(n,null,2)+`
5
- `,{mode:384});try{W.chmodSync(M,384)}catch{}}function as(){if(process.platform==="win32"||!W.existsSync(M))return!1;try{return(W.statSync(M).mode&63)!==0}catch{return!1}}});var to=O(J=>{"use strict";var is=J&&J.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n);var o=Object.getOwnPropertyDescriptor(t,n);(!o||("get"in o?!t.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,o)}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),ss=J&&J.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),Qr=J&&J.__importStar||(function(){var e=function(t){return e=Object.getOwnPropertyNames||function(n){var r=[];for(var o in n)Object.prototype.hasOwnProperty.call(n,o)&&(r[r.length]=o);return r},e(t)};return function(t){if(t&&t.__esModule)return t;var n={};if(t!=null)for(var r=e(t),o=0;o<r.length;o++)r[o]!=="default"&&is(n,t,r[o]);return ss(n,t),n}})();Object.defineProperty(J,"__esModule",{value:!0});J.ensureDeviceKey=cs;J.sealFile=ls;J.readManifest=eo;J.openFile=ds;J.writeLocalReceipt=us;var Tn=A("crypto"),ye=A("fs"),st=A("path"),Pn=Qr(Jr()),Dn=Qr(Zr());function cs(){let e=Dn.loadDeviceKey();return e?{key:e,created:!1}:{key:Dn.createDeviceKey(),created:!0}}async function ls(e,t,n){let r=(0,ye.readFileSync)(e),o=(0,Tn.createHash)("sha256").update(r).digest("hex"),a=n??"local-"+(0,Tn.randomUUID)(),i=await Pn.sealValue(r.toString("base64"),t),s={v:3,alg:"aes256gcm:v3",kid:t.kid,orig:(0,st.basename)(e),enc:"base64",token:Pn.formatToken(i,a),sealed_dek:i.sealedDekB64,sha256:o,sealed_at:new Date().toISOString()},l=e+".ndc";return(0,ye.writeFileSync)(l,JSON.stringify(s,null,2)+`
6
- `,{mode:384}),{path:e,ndc:l,sha256:o,sealId:a}}function eo(e){try{let t=JSON.parse((0,ye.readFileSync)(e,"utf8"));return t.alg==="aes256gcm:v3"&&t.token&&t.sealed_dek?t:null}catch{return null}}async function ds(e,t){if(!(0,ye.existsSync)(e))return{ok:!1,error:"not_found"};let n=eo(e);if(!n)return{ok:!1,error:"not_a_seal"};let r=t===void 0?Dn.loadDeviceKey():t;if(!r)return{ok:!1,error:"no_device_key"};let o;try{o=await Pn.openValue(n.token,n.sealed_dek,r)}catch{return{ok:!1,error:"wrong_key"}}let a=Buffer.from(o,"base64"),i=e.endsWith(".ndc")?e.slice(0,-4):e+".opened";(0,ye.existsSync)(i)&&(i=i+".opened"),(0,ye.writeFileSync)(i,a);let s=(0,Tn.createHash)("sha256").update(a).digest("hex")===n.sha256;return{ok:!0,outPath:i,sha256:n.sha256,intact:s}}function us(e,t){let n=(0,st.join)(e,".nodata","receipts");(0,ye.mkdirSync)(n,{recursive:!0});let r={action:t.action,at:new Date().toISOString(),governed:"local",device_kid:t.kid,removed_plaintext:t.removed_plaintext,files:t.files.map(a=>({path:(0,st.relative)(e,a.path),sha256:a.sha256,seal_id:a.sealId,sealed:(0,st.basename)(a.ndc)})),...t.extra??{}},o=(0,st.join)(n,`${t.action}-${Date.now()}.json`);return(0,ye.writeFileSync)(o,JSON.stringify(r,null,2)+`
7
- `),o}});var Pe=O(Kn=>{"use strict";Object.defineProperty(Kn,"__esModule",{value:!0});var lt=class{static async generateKeyPair(){let t=await crypto.subtle.generateKey({name:"RSA-OAEP",modulusLength:4096,publicExponent:new Uint8Array([1,0,1]),hash:"SHA-256"},!0,["encrypt","decrypt"]),n=await crypto.subtle.exportKey("jwk",t.publicKey),r=await crypto.subtle.exportKey("jwk",t.privateKey);return{publicKeyJwk:n,privateKeyJwk:r}}static async encryptMessage(t,n){let r=await crypto.subtle.importKey("jwk",n,{name:"RSA-OAEP",hash:"SHA-256"},!1,["encrypt"]),o=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!0,["encrypt","decrypt"]),a=crypto.getRandomValues(new Uint8Array(12)),i=new TextEncoder().encode(t),s=await crypto.subtle.encrypt({name:"AES-GCM",iv:a,tagLength:128},o,i),l=await crypto.subtle.exportKey("raw",o),d=await crypto.subtle.encrypt({name:"RSA-OAEP"},r,l);return{encrypted_blob:this.arrayBufferToBase64(s),encrypted_aes_key:this.arrayBufferToBase64(d),iv:this.arrayBufferToBase64(a)}}static async decryptMessage(t,n){let r=await crypto.subtle.importKey("jwk",n,{name:"RSA-OAEP",hash:"SHA-256"},!1,["decrypt"]),o=this.base64ToArrayBuffer(t.encrypted_aes_key),a=await crypto.subtle.decrypt({name:"RSA-OAEP"},r,o),i=await crypto.subtle.importKey("raw",a,{name:"AES-GCM",length:256},!1,["decrypt"]),s=this.base64ToArrayBuffer(t.iv),l=this.base64ToArrayBuffer(t.encrypted_blob),d=await crypto.subtle.decrypt({name:"AES-GCM",iv:s,tagLength:128},i,l);return new TextDecoder().decode(d)}static async encryptFile(t,n){let r=await t.arrayBuffer(),o=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!0,["encrypt","decrypt"]),a=crypto.getRandomValues(new Uint8Array(12)),i=await crypto.subtle.encrypt({name:"AES-GCM",iv:a,tagLength:128},o,r),s=JSON.stringify({name:t.name,type:t.type,size:t.size,lastModified:t.lastModified}),l=crypto.getRandomValues(new Uint8Array(12)),d=await crypto.subtle.encrypt({name:"AES-GCM",iv:l,tagLength:128},o,new TextEncoder().encode(s)),u=await crypto.subtle.importKey("jwk",n,{name:"RSA-OAEP",hash:"SHA-256"},!1,["encrypt"]),p=await crypto.subtle.exportKey("raw",o),h=await crypto.subtle.encrypt({name:"RSA-OAEP"},u,p);return{encrypted_file:this.arrayBufferToBase64(i),encrypted_file_key:this.arrayBufferToBase64(h),iv:this.arrayBufferToBase64(a),encrypted_metadata:this.arrayBufferToBase64(d),metadata_iv:this.arrayBufferToBase64(l),encrypted_size:i.byteLength}}static async importKeyFromFragment(t){let n=t.replace(/-/g,"+").replace(/_/g,"/"),r=this.base64ToArrayBuffer(n.padEnd(Math.ceil(n.length/4)*4,"="));if(r.byteLength!==32)throw new Error("channel key must be 32 bytes");return crypto.subtle.importKey("raw",r,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}static async deriveKeyFromOTP(t,n,r="SHA-512"){let o=await crypto.subtle.importKey("raw",new TextEncoder().encode(t),"PBKDF2",!1,["deriveBits","deriveKey"]);return await crypto.subtle.deriveKey({name:"PBKDF2",salt:new TextEncoder().encode(n),iterations:31e4,hash:r},o,{name:"AES-GCM",length:256},!0,["encrypt","decrypt"])}static async encryptWithDerivedKey(t,n){let r=crypto.getRandomValues(new Uint8Array(12)),o=new TextEncoder().encode(t),a=await crypto.subtle.encrypt({name:"AES-GCM",iv:r,tagLength:128},n,o);return{encrypted:this.arrayBufferToBase64(a),iv:this.arrayBufferToBase64(r)}}static async decryptWithDerivedKey(t,n,r){let o=this.base64ToArrayBuffer(t),a=this.base64ToArrayBuffer(n),i=await crypto.subtle.decrypt({name:"AES-GCM",iv:a,tagLength:128},r,o);return new TextDecoder().decode(i)}static async sha256Hex(t){let n=t instanceof Uint8Array?t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength):t,r=await crypto.subtle.digest("SHA-256",n);return Array.from(new Uint8Array(r)).map(o=>o.toString(16).padStart(2,"0")).join("")}static async encryptFileWithDerivedKey(t,n){let r=await t.arrayBuffer(),o=await this.sha256Hex(r),a=crypto.getRandomValues(new Uint8Array(12)),i=await crypto.subtle.encrypt({name:"AES-GCM",iv:a,tagLength:128},n,r),s=JSON.stringify({name:t.name,type:t.type,size:t.size,lastModified:t.lastModified}),l=crypto.getRandomValues(new Uint8Array(12)),d=await crypto.subtle.encrypt({name:"AES-GCM",iv:l,tagLength:128},n,new TextEncoder().encode(s));return{encrypted_file:this.arrayBufferToBase64(i),iv:this.arrayBufferToBase64(a),encrypted_metadata:this.arrayBufferToBase64(d),metadata_iv:this.arrayBufferToBase64(l),encrypted_size:i.byteLength,plaintext_sha256:o,ciphertext_sha256:await this.sha256Hex(i)}}static async decryptFileBytesWithDerivedKey(t,n,r){let o=this.base64ToArrayBuffer(n);return crypto.subtle.decrypt({name:"AES-GCM",iv:o,tagLength:128},r,t)}static async decryptFileWithDerivedKey(t,n,r){let o=this.base64ToArrayBuffer(t),a=this.base64ToArrayBuffer(n);return crypto.subtle.decrypt({name:"AES-GCM",iv:a,tagLength:128},r,o)}static async deriveSeedKey(t,n="SHA-512"){let r=t.trim().toLowerCase(),o=await crypto.subtle.importKey("raw",new TextEncoder().encode(r),"PBKDF2",!1,["deriveBits","deriveKey"]);return await crypto.subtle.deriveKey({name:"PBKDF2",salt:new TextEncoder().encode(this.SEED_SALT),iterations:this.PBKDF2_ITERATIONS,hash:n},o,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}static async exportKeyWithSeed(t,n){let r=await crypto.subtle.exportKey("jwk",t),o=new TextEncoder().encode(JSON.stringify(r)),a=crypto.getRandomValues(new Uint8Array(12)),i=await crypto.subtle.encrypt({name:"AES-GCM",iv:a,tagLength:128},n,o),s=new Uint8Array(a.byteLength+i.byteLength);return s.set(a,0),s.set(new Uint8Array(i),a.byteLength),s.buffer}static async importKeyWithSeed(t,n){let r=new Uint8Array(t),o=r.slice(0,12),a=r.slice(12),i=await crypto.subtle.decrypt({name:"AES-GCM",iv:o,tagLength:128},n,a),s=new TextDecoder().decode(i),l=JSON.parse(s),d=await crypto.subtle.importKey("jwk",l,{name:"RSA-OAEP",hash:"SHA-256"},!0,["decrypt"]);return new Uint8Array(i).fill(0),d}static async hashPhone(t){let n=new TextEncoder().encode(t.replace(/\D/g,"")),r=await crypto.subtle.digest("SHA-256",n);return Array.from(new Uint8Array(r)).map(o=>o.toString(16).padStart(2,"0")).join("")}static arrayBufferToBase64(t){let n=new Uint8Array(t),r=32768,o=[];for(let a=0;a<n.length;a+=r)o.push(String.fromCharCode(...n.subarray(a,a+r)));return btoa(o.join(""))}static async encryptFileToBytesWithDerivedKey(t,n){let r=await t.arrayBuffer(),o=await this.sha256Hex(r),a=crypto.getRandomValues(new Uint8Array(12)),i=await crypto.subtle.encrypt({name:"AES-GCM",iv:a,tagLength:128},n,r),s=JSON.stringify({name:t.name,type:t.type,size:t.size,lastModified:t.lastModified}),l=crypto.getRandomValues(new Uint8Array(12)),d=await crypto.subtle.encrypt({name:"AES-GCM",iv:l,tagLength:128},n,new TextEncoder().encode(s));return{ciphertext:i,iv:this.arrayBufferToBase64(a),encrypted_metadata:this.arrayBufferToBase64(d),metadata_iv:this.arrayBufferToBase64(l),encrypted_size:i.byteLength,plaintext_sha256:o,ciphertext_sha256:await this.sha256Hex(i)}}static base64ToArrayBuffer(t){let n=atob(t),r=new Uint8Array(n.length);for(let o=0;o<n.length;o++)r[o]=n.charCodeAt(o);return r.buffer}static wipeFromMemory(t){new Uint8Array(t).fill(0)}};lt.PBKDF2_ITERATIONS=31e4;lt.SEED_SALT="NoDataChat-Seed-v1";Kn.default=lt});var so=O(Rt=>{"use strict";Object.defineProperty(Rt,"__esModule",{value:!0});Rt.solveProofOfWork=vs;Rt.verifyProofOfWork=ws;function Ss(e){let t=new Uint8Array(e),n="";for(let r=0;r<t.length;r++)n+=t[r].toString(16).padStart(2,"0");return n}async function io(e){let t=new TextEncoder().encode(e),n=await crypto.subtle.digest("SHA-256",t);return Ss(n)}async function vs(e,t=4){if(t<1||t>16)throw new Error("Difficulty must be between 1 and 16");let n="0".repeat(t),r=0;for(;;){let o=e+r.toString(),a=await io(o);if(a.startsWith(n))return{nonce:r,hash:a};if(r++,r>2e9)throw new Error("Proof of work exceeded maximum attempts")}}async function ws(e,t,n=4){if(n<1||n>16)return!1;let r="0".repeat(n),o=e+t.toString();return(await io(o)).startsWith(r)}});var Mn=O(je=>{"use strict";var Es=je&&je.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(je,"__esModule",{value:!0});je.NoDataEmail=void 0;var ie=Es(Pe()),jn=class{static async seal(t,n,r,o,a,i={}){let{encrypt_subject:s=!0,ttl_hours:l=72,attachments:d=[]}=i,u=await ie.default.encryptMessage(o,a),p=r,h=!1;if(s){let v=await ie.default.encryptMessage(r,a);p=JSON.stringify(v),h=!0}let m=[];for(let v of d){let k=await ie.default.encryptFile(v,a);m.push({encrypted_file:k})}return{from_alias:t,to:n,subject:p,subject_encrypted:h,body:u,attachments:m,sealed_at:new Date().toISOString(),ttl_hours:l,envelope_id:crypto.randomUUID(),crypto_version:"0.2.0"}}static async open(t,n){let r=await ie.default.decryptMessage(t.body,n),o=t.subject;if(t.subject_encrypted){let i=JSON.parse(t.subject);o=await ie.default.decryptMessage(i,n)}let a=[];for(let i of t.attachments){let{encrypted_file:s}=i,l=ie.default.base64ToArrayBuffer(s.metadata_iv),d=ie.default.base64ToArrayBuffer(s.encrypted_metadata),u=ie.default.base64ToArrayBuffer(s.encrypted_file_key),p=await crypto.subtle.importKey("jwk",n,{name:"RSA-OAEP",hash:"SHA-256"},!1,["decrypt"]),h=await crypto.subtle.decrypt({name:"RSA-OAEP"},p,u),m=await crypto.subtle.importKey("raw",h,{name:"AES-GCM",length:256},!1,["decrypt"]),v=await crypto.subtle.decrypt({name:"AES-GCM",iv:l,tagLength:128},m,d),k=JSON.parse(new TextDecoder().decode(v)),S=ie.default.base64ToArrayBuffer(s.iv),_=ie.default.base64ToArrayBuffer(s.encrypted_file),w=await crypto.subtle.decrypt({name:"AES-GCM",iv:S,tagLength:128},m,_);a.push({filename:k.name,mime_type:k.type,data:w,size:k.size})}return{subject:o,body:r,attachments:a,sealed_at:t.sealed_at,ttl_hours:t.ttl_hours,envelope_id:t.envelope_id}}static isExpired(t){let r=new Date(t.sealed_at).getTime()+t.ttl_hours*60*60*1e3;return Date.now()>r}static toMimeBody(t,n){let r=JSON.stringify(t),o=btoa(unescape(encodeURIComponent(r)));return['Content-Type: multipart/mixed; boundary="nodata-boundary"',"","--nodata-boundary","Content-Type: text/html; charset=utf-8","",'<div style="font-family:system-ui;padding:24px;text-align:center">',"<h2>This email is encrypted with Capsule</h2>","<p>The sender used end-to-end encryption. To read this message:</p>",`<a href="${n}?env=${t.envelope_id}" `,'style="display:inline-block;padding:12px 24px;background:#000;color:#fff;','border-radius:8px;text-decoration:none;font-weight:600">',"Open Encrypted Email</a>",'<p style="color:#888;font-size:12px;margin-top:16px">',"Powered by Capsule &mdash; Nothing is ever stored. Ever.</p>","</div>","--nodata-boundary",'Content-Type: application/x-nodata-envelope; name="envelope.nodata"',"Content-Transfer-Encoding: base64",'Content-Disposition: attachment; filename="envelope.nodata"',"",o,"--nodata-boundary--"].join(`\r
8
- `)}};je.NoDataEmail=jn});var Un=O(Me=>{"use strict";var ks=Me&&Me.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(Me,"__esModule",{value:!0});Me.NoDataWebhook=void 0;var Fn=ks(Pe()),Ln=class{static async encrypt(t,n,r,o){let{event_type:a,source:i,ttl_seconds:s=3600}=o,l=JSON.stringify(t),d=await Fn.default.encryptMessage(l,n),u=new Date().toISOString(),p=crypto.randomUUID(),h=`${p}.${u}.${d.encrypted_blob}`,m=await this.hmacSign(h,r);return{encrypted_event:d,event_type:a,source:i,signature:m,timestamp:u,delivery_id:p,ttl_seconds:s,crypto_version:"0.2.0"}}static async verify(t,n){let r=`${t.delivery_id}.${t.timestamp}.${t.encrypted_event.encrypted_blob}`,o=await this.hmacSign(r,n),a=new TextEncoder().encode(t.signature),i=new TextEncoder().encode(o),s=a.length^i.length,l=Math.min(a.length,i.length);for(let m=0;m<l;m++)s|=a[m]^i[m];let d=s===0,p=new Date(t.timestamp).getTime()+t.ttl_seconds*1e3,h=Date.now()>p;return{valid:d,expired:h,event_type:t.event_type,source:t.source,delivery_id:t.delivery_id}}static async decrypt(t,n){let r=await Fn.default.decryptMessage(t.encrypted_event,n);return JSON.parse(r)}static async verifyAndDecrypt(t,n,r){let o=await this.verify(t,r);if(!o.valid)throw new Error(`[NoDataWebhook] Invalid signature for delivery ${o.delivery_id}`);if(o.expired)throw new Error(`[NoDataWebhook] Payload expired for delivery ${o.delivery_id}`);return{data:await this.decrypt(t,n),delivery_id:o.delivery_id,event_type:o.event_type}}static async hmacSign(t,n){let r=await crypto.subtle.importKey("raw",new TextEncoder().encode(n),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),o=await crypto.subtle.sign("HMAC",r,new TextEncoder().encode(t));return Fn.default.arrayBufferToBase64(o)}};Me.NoDataWebhook=Ln});var Vn=O(Fe=>{"use strict";var xs=Fe&&Fe.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(Fe,"__esModule",{value:!0});Fe.NoDataSystems=void 0;var $t=xs(Pe()),Hn=class{static async encryptRecord(t,n,r,o,a,i){let s=[],l={};for(let[d,u]of Object.entries(r))if(o.sensitive.includes(d)){let p=typeof u=="string"?u:JSON.stringify(u),h=await $t.default.encryptMessage(p,a),m=await this.hashValue(p);s.push({value:h,search_hash:m,field_name:d,encrypted_at:new Date().toISOString()})}else l[d]=u;return{record_id:t,record_type:n,encrypted_fields:s,clear_fields:l,encrypted_by:i,created_at:new Date().toISOString(),crypto_version:"0.2.0"}}static async decryptRecord(t,n){let r={...t.clear_fields};for(let o of t.encrypted_fields){let a=await $t.default.decryptMessage(o.value,n);try{r[o.field_name]=JSON.parse(a)}catch{r[o.field_name]=a}}return{record_id:t.record_id,record_type:t.record_type,fields:r,created_at:t.created_at}}static async searchByHash(t,n,r){let o=await this.hashValue(r);return t.filter(a=>a.encrypted_fields.some(i=>i.field_name===n&&i.search_hash===o))}static async encryptField(t,n,r){let o=typeof n=="string"?n:JSON.stringify(n),a=await $t.default.encryptMessage(o,r),i=await this.hashValue(o);return{value:a,search_hash:i,field_name:t,encrypted_at:new Date().toISOString()}}static async decryptField(t,n){let r=await $t.default.decryptMessage(t.value,n);try{return JSON.parse(r)}catch{return r}}static createSchema(t,n){return{sensitive:n,clear:t.filter(r=>!n.includes(r))}}static async hashValue(t){let n=`nodatachat:field:${t}`,r=new TextEncoder().encode(n),o=await crypto.subtle.digest("SHA-256",r);return Array.from(new Uint8Array(o)).map(a=>a.toString(16).padStart(2,"0")).join("")}};Fe.NoDataSystems=Hn});var qn=O(Le=>{"use strict";var As=Le&&Le.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(Le,"__esModule",{value:!0});Le.NoDataForms=void 0;var se=As(Pe()),Gn=class{static async encryptSubmission(t,n,r,o,a={}){let{ttl_hours:i=0,view_once:s=!1,attachments:l=[]}=a,d={},u={};for(let S of n)S.sensitive!==!1?d[S.name]=S.value:u[S.name]=S.value;let p=JSON.stringify(n.map(S=>({name:S.name,value:S.value}))),h=await this.sha256(p),m=await se.default.encryptMessage(JSON.stringify(d),r),v=[];for(let S of l){let _=await se.default.encryptFile(S,r);v.push(_)}let k=n.map(S=>S.name);return{submission_id:crypto.randomUUID(),form_id:t,encrypted_fields:m,clear_fields:u,attachments:v,integrity_hash:h,field_order:k,submitter_id:o,submitted_at:new Date().toISOString(),ttl_hours:i,view_once:s,crypto_version:"0.2.0"}}static async decryptSubmission(t,n){let r=await se.default.decryptMessage(t.encrypted_fields,n),o=JSON.parse(r),a={...t.clear_fields,...o},s=(t.field_order||Object.keys(a).sort()).map(p=>({name:p,value:a[p]})),d=await this.sha256(JSON.stringify(s))===t.integrity_hash,u=[];for(let p of t.attachments){let h=await crypto.subtle.importKey("jwk",n,{name:"RSA-OAEP",hash:"SHA-256"},!1,["decrypt"]),m=await crypto.subtle.decrypt({name:"RSA-OAEP"},h,se.default.base64ToArrayBuffer(p.encrypted_file_key)),v=await crypto.subtle.importKey("raw",m,{name:"AES-GCM",length:256},!1,["decrypt"]),k=await crypto.subtle.decrypt({name:"AES-GCM",iv:se.default.base64ToArrayBuffer(p.metadata_iv),tagLength:128},v,se.default.base64ToArrayBuffer(p.encrypted_metadata)),S=JSON.parse(new TextDecoder().decode(k)),_=await crypto.subtle.decrypt({name:"AES-GCM",iv:se.default.base64ToArrayBuffer(p.iv),tagLength:128},v,se.default.base64ToArrayBuffer(p.encrypted_file));u.push({filename:S.name,mime_type:S.type,data:_,size:S.size})}return{submission_id:t.submission_id,form_id:t.form_id,fields:a,attachments:u,integrity_valid:d,submitted_at:t.submitted_at}}static isExpired(t){if(t.ttl_hours===0)return!1;let r=new Date(t.submitted_at).getTime()+t.ttl_hours*60*60*1e3;return Date.now()>r}static async encryptGrade(t,n,r,o,a=0){let i=await se.default.encryptMessage(JSON.stringify(t),n),s=await this.sha256(`nodatachat:student:${t.student_id}`);return{encrypted_grade:i,student_hash:s,course_id:r,term:o,delivery_id:crypto.randomUUID(),delivered_at:new Date().toISOString(),ttl_hours:a,crypto_version:"0.2.0"}}static async decryptGrade(t,n){let r=await se.default.decryptMessage(t.encrypted_grade,n);return JSON.parse(r)}static async sha256(t){let n=new TextEncoder().encode(t),r=await crypto.subtle.digest("SHA-256",n);return Array.from(new Uint8Array(r)).map(o=>o.toString(16).padStart(2,"0")).join("")}};Le.NoDataForms=Gn});var co=O(Ue=>{"use strict";var Ts=Ue&&Ue.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(Ue,"__esModule",{value:!0});Ue.NoDataSDK=void 0;var Bt=Ts(Pe()),ge=Mn(),_e=Un(),X=Vn(),ce=qn(),Wn=class{static async init(t={}){let n;return t.keyPair?n=t.keyPair:(n=await Bt.default.generateKeyPair(),t.onKeysGenerated&&await t.onKeysGenerated(n)),{publicKey:n.publicKeyJwk,email:{seal:ge.NoDataEmail.seal.bind(ge.NoDataEmail),open:ge.NoDataEmail.open.bind(ge.NoDataEmail),isExpired:ge.NoDataEmail.isExpired.bind(ge.NoDataEmail),toMimeBody:ge.NoDataEmail.toMimeBody.bind(ge.NoDataEmail)},webhook:{encrypt:_e.NoDataWebhook.encrypt.bind(_e.NoDataWebhook),verify:_e.NoDataWebhook.verify.bind(_e.NoDataWebhook),decrypt:_e.NoDataWebhook.decrypt.bind(_e.NoDataWebhook),verifyAndDecrypt:_e.NoDataWebhook.verifyAndDecrypt.bind(_e.NoDataWebhook)},systems:{encryptRecord:X.NoDataSystems.encryptRecord.bind(X.NoDataSystems),decryptRecord:X.NoDataSystems.decryptRecord.bind(X.NoDataSystems),searchByHash:X.NoDataSystems.searchByHash.bind(X.NoDataSystems),encryptField:X.NoDataSystems.encryptField.bind(X.NoDataSystems),decryptField:X.NoDataSystems.decryptField.bind(X.NoDataSystems),createSchema:X.NoDataSystems.createSchema.bind(X.NoDataSystems)},forms:{encryptSubmission:ce.NoDataForms.encryptSubmission.bind(ce.NoDataForms),decryptSubmission:ce.NoDataForms.decryptSubmission.bind(ce.NoDataForms),isExpired:ce.NoDataForms.isExpired.bind(ce.NoDataForms),encryptGrade:ce.NoDataForms.encryptGrade.bind(ce.NoDataForms),decryptGrade:ce.NoDataForms.decryptGrade.bind(ce.NoDataForms)},crypto:Bt.default}}static async quickEncrypt(t,n){let r=typeof t=="string"?t:JSON.stringify(t),o=await Bt.default.encryptMessage(r,n);return JSON.stringify(o)}static async quickDecrypt(t,n){let r=JSON.parse(t),o=await Bt.default.decryptMessage(r,n);try{return JSON.parse(o)}catch{return o}}};Ue.NoDataSDK=Wn});var lo=O(Z=>{"use strict";Object.defineProperty(Z,"__esModule",{value:!0});Z.NoDataSDK=Z.NoDataForms=Z.NoDataSystems=Z.NoDataWebhook=Z.NoDataEmail=void 0;var Ps=Mn();Object.defineProperty(Z,"NoDataEmail",{enumerable:!0,get:function(){return Ps.NoDataEmail}});var Ds=Un();Object.defineProperty(Z,"NoDataWebhook",{enumerable:!0,get:function(){return Ds.NoDataWebhook}});var Os=Vn();Object.defineProperty(Z,"NoDataSystems",{enumerable:!0,get:function(){return Os.NoDataSystems}});var Ns=qn();Object.defineProperty(Z,"NoDataForms",{enumerable:!0,get:function(){return Ns.NoDataForms}});var Is=co();Object.defineProperty(Z,"NoDataSDK",{enumerable:!0,get:function(){return Is.NoDataSDK}})});var Ve=O(T=>{"use strict";Object.defineProperty(T,"__esModule",{value:!0});T.PQ_SIZES=T.NDC_WIRE_V03=T.NDC_WIRE_V1=T.NDC_V03_RATCHET_DOMAIN=T.NDC_V03_CONTENT_KEY_DOMAIN=T.NDC_V03_KEM_DOMAIN=T.PQ_SUITE=void 0;T.generateHybridKemKeypair=Cs;T.deriveHybridKemKeypairFromSeed=Rs;T.hybridKemEncapsulate=$s;T.hybridKemDecapsulate=Bs;T.deriveContentKey=Ks;T.ratchetAdvance=js;T.generateHybridSigKeypair=Ms;T.hybridSign=Fs;T.hybridVerify=Ls;T.generateMlDsa65Keypair=Us;T.mlDsa65SignDetached=Hs;T.mlDsa65VerifyDetached=Vs;var be=A("@noble/curves/ed25519.js"),dt=A("@noble/hashes/sha2.js"),ut=A("@noble/hashes/hkdf.js"),Kt=A("@noble/post-quantum/ml-kem.js"),He=A("@noble/post-quantum/ml-dsa.js");T.PQ_SUITE={KEM:"X25519+ML-KEM-768",SIG:"Ed25519+ML-DSA-65",AEAD:"AES-256-GCM",KDF:"HKDF-SHA-256"};T.NDC_V03_KEM_DOMAIN="NDC-v0.3-hybrid-kem";T.NDC_V03_CONTENT_KEY_DOMAIN="NDC-v0.3-content-key";T.NDC_V03_RATCHET_DOMAIN="NDC-ratchet";T.NDC_WIRE_V1=1;T.NDC_WIRE_V03=2;function uo(...e){let t=0;for(let o of e)t+=o.length;let n=new Uint8Array(t),r=0;for(let o of e)n.set(o,r),r+=o.length;return n}function pt(e){return new TextEncoder().encode(e)}function po(e,t,n,r){let o=uo(e,t),a=uo(pt(T.NDC_V03_KEM_DOMAIN),n,r);return(0,ut.hkdf)(dt.sha256,o,new Uint8Array(0),a,32)}function Cs(){let{secretKey:e,publicKey:t}=be.x25519.keygen(),{publicKey:n,secretKey:r}=Kt.ml_kem768.keygen();return{publicKey:{x25519:t,mlKem:n},secretKey:{x25519:e,mlKem:r}}}function Rs(e){if(e.length<32)throw new Error("seed too short (need >=32 bytes)");let t=(0,ut.hkdf)(dt.sha256,e,new Uint8Array(0),pt("ndc-hybrid-kem-x25519-v1"),32),n=(0,ut.hkdf)(dt.sha256,e,new Uint8Array(0),pt("ndc-hybrid-kem-mlkem768-v1"),64),r=be.x25519.getPublicKey(t),{publicKey:o,secretKey:a}=Kt.ml_kem768.keygen(n);return{publicKey:{x25519:r,mlKem:o},secretKey:{x25519:t,mlKem:a}}}function $s(e){let{secretKey:t,publicKey:n}=be.x25519.keygen(),r=be.x25519.getSharedSecret(t,e.x25519),{cipherText:o,sharedSecret:a}=Kt.ml_kem768.encapsulate(e.mlKem),i=po(a,r,n,e.x25519);return{ciphertext:{ctClassical:n,ctPq:o},sharedSecret:i,ephemeralX25519Pk:n}}function Bs(e,t,n){let r=be.x25519.getSharedSecret(e.x25519,n.ctClassical),o=Kt.ml_kem768.decapsulate(n.ctPq,e.mlKem);return po(o,r,n.ctClassical,t)}function Ks(e){return(0,ut.hkdf)(dt.sha256,e,new Uint8Array(0),pt(T.NDC_V03_CONTENT_KEY_DOMAIN),32)}function js(e,t){return(0,ut.hkdf)(dt.sha256,e,t,pt(T.NDC_V03_RATCHET_DOMAIN),32)}function Ms(){let{secretKey:e,publicKey:t}=be.ed25519.keygen(),{publicKey:n,secretKey:r}=He.ml_dsa65.keygen();return{publicKey:{ed25519:t,mlDsa:n},secretKey:{ed25519:e,mlDsa:r}}}function Fs(e,t){return{ed25519:be.ed25519.sign(t,e.ed25519),mlDsa:He.ml_dsa65.sign(t,e.mlDsa)}}function Ls(e,t,n){return be.ed25519.verify(n.ed25519,t,e.ed25519)?He.ml_dsa65.verify(n.mlDsa,t,e.mlDsa):!1}function Us(){let{publicKey:e,secretKey:t}=He.ml_dsa65.keygen();return{publicKey:e,secretKey:t}}function Hs(e,t){return He.ml_dsa65.sign(t,e)}function Vs(e,t,n){return He.ml_dsa65.verify(n,t,e)}T.PQ_SIZES={X25519_PK:32,X25519_SK:32,ML_KEM_768_PK:1184,ML_KEM_768_SK:2400,ML_KEM_768_CT:1088,ED25519_PK:32,ED25519_SK:32,ED25519_SIG:64,ML_DSA_65_PK:1952,ML_DSA_65_SK:4032,ML_DSA_65_SIG:3309,HYBRID_SHARED_SECRET:32}});var Mt=O(P=>{"use strict";Object.defineProperty(P,"__esModule",{value:!0});P.deriveContentKey=P.ContainerV3Error=P.CONTAINER_HEADER_MAX_BYTES=P.CONTAINER_FIXED_PREFIX_BYTES=P.CONTAINER_MAGIC=void 0;P.canonicalJson=jt;P.headerSigningBytes=Jn;P.signContainerHeader=mo;P.verifyContainerHeader=go;P.encodeContainerV3=_o;P.decodeContainerV3=bo;P.sealHybrid=Ys;P.openHybrid=Xs;var Gs=A("@noble/hashes/hkdf.js"),qs=A("@noble/hashes/sha2.js"),K=Ve();Object.defineProperty(P,"deriveContentKey",{enumerable:!0,get:function(){return K.deriveContentKey}});P.CONTAINER_MAGIC=new Uint8Array([78,68,76,66]);P.CONTAINER_FIXED_PREFIX_BYTES=8;P.CONTAINER_HEADER_MAX_BYTES=16777215;var Ws="NDC-v0.3-wrap-key",F=class extends Error{constructor(t,n){super(n),this.name="ContainerV3Error",this.code=t}};P.ContainerV3Error=F;var fe=e=>{if(typeof Buffer<"u")return Buffer.from(e).toString("base64");let t="";for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return btoa(t)},De=e=>{if(typeof Buffer<"u")return new Uint8Array(Buffer.from(e,"base64"));let t=atob(e),n=new Uint8Array(t.length);for(let r=0;r<t.length;r++)n[r]=t.charCodeAt(r);return n},yo=e=>{let t="";for(let n=0;n<e.length;n++)t+=e[n].toString(16).padStart(2,"0");return t};function jt(e){if(e===null||typeof e!="object")return JSON.stringify(e);if(Array.isArray(e))return"["+e.map(jt).join(",")+"]";let t=e;return"{"+Object.keys(t).sort().map(r=>JSON.stringify(r)+":"+jt(t[r])).join(",")+"}"}function Jn(e){let t={...e};return delete t.sig,new TextEncoder().encode(jt(t))}function mo(e,t,n){let r=(0,K.hybridSign)(n.secretKey,Jn(e));return{...e,sig:{signer_kid:t,ed25519:fe(r.ed25519),ml_dsa_65:fe(r.mlDsa)}}}function go(e,t){let n={ed25519:De(e.sig.ed25519),mlDsa:De(e.sig.ml_dsa_65)};return(0,K.hybridVerify)(t,Jn(e),n)}var Js=["lockbox_id","format_version","profile","suite","server","kem","wrapped_content_key","iv","tag","bearer","dpop_required","ciphertext_sha256","issued_at","cache_ttl_seconds","original_filename","original_content_type","sig"];function zs(e){if(!e||typeof e!="object")throw new F("header_schema_mismatch","header is not an object");let t=e;for(let r of Js)if(t[r]===void 0)throw new F("header_schema_mismatch",`header missing required field: ${String(r)}`);if(t.format_version!==3)throw new F("unsupported_version",`format_version ${t.format_version} unknown`);if(t.profile!=="pq-hybrid")throw new F("suite_unknown",`profile must be 'pq-hybrid', got '${String(t.profile)}'`);let n=t.suite;if(n.kem!==K.PQ_SUITE.KEM||n.sig!==K.PQ_SUITE.SIG||n.aead!==K.PQ_SUITE.AEAD||n.kdf!==K.PQ_SUITE.KDF)throw new F("suite_unknown",`suite mismatch: viewer supports ${JSON.stringify(K.PQ_SUITE)}, header has ${JSON.stringify(n)}`)}function _o(e,t){let n=new TextEncoder().encode(JSON.stringify(e));if(n.length>P.CONTAINER_HEADER_MAX_BYTES)throw new F("header_schema_mismatch",`header too large (${n.length} bytes; max 16 MB)`);let r=new Uint8Array(P.CONTAINER_FIXED_PREFIX_BYTES+n.length+t.length);return r.set(P.CONTAINER_MAGIC,0),r[4]=K.NDC_WIRE_V03,r[5]=n.length>>16&255,r[6]=n.length>>8&255,r[7]=n.length&255,r.set(n,P.CONTAINER_FIXED_PREFIX_BYTES),r.set(t,P.CONTAINER_FIXED_PREFIX_BYTES+n.length),r}function bo(e){if(e.length<P.CONTAINER_FIXED_PREFIX_BYTES)throw new F("header_truncated",`container truncated: ${e.length} bytes (need \u2265 ${P.CONTAINER_FIXED_PREFIX_BYTES})`);for(let o=0;o<4;o++)if(e[o]!==P.CONTAINER_MAGIC[o])throw new F("bad_magic",`bad magic: expected NDLB, got ${yo(e.slice(0,4))}`);if(e[4]!==K.NDC_WIRE_V03)throw new F("unsupported_version",`expected wire version 0x${K.NDC_WIRE_V03.toString(16)}, got 0x${e[4].toString(16)}`);let t=e[5]<<16|e[6]<<8|e[7],n=P.CONTAINER_FIXED_PREFIX_BYTES+t;if(e.length<n)throw new F("header_truncated",`header truncated: declared ${t}, only ${e.length-P.CONTAINER_FIXED_PREFIX_BYTES} bytes left`);let r;try{r=JSON.parse(new TextDecoder("utf-8").decode(e.slice(P.CONTAINER_FIXED_PREFIX_BYTES,n)))}catch(o){throw new F("header_invalid_json",`header JSON parse failed: ${o.message}`)}return zs(r),{header:r,ciphertextWithTag:e.slice(n)}}var Oe=e=>e;async function fo(e,t,n){let r=await crypto.subtle.importKey("raw",Oe(e),{name:"AES-GCM"},!1,["encrypt"]),o=await crypto.subtle.encrypt({name:"AES-GCM",iv:Oe(t)},r,Oe(n));return new Uint8Array(o)}async function ho(e,t,n){let r=await crypto.subtle.importKey("raw",Oe(e),{name:"AES-GCM"},!1,["decrypt"]),o=await crypto.subtle.decrypt({name:"AES-GCM",iv:Oe(t)},r,Oe(n));return new Uint8Array(o)}function So(e){return(0,Gs.hkdf)(qs.sha256,e,new Uint8Array(0),new TextEncoder().encode(Ws),32)}async function vo(e){let t=await crypto.subtle.digest("SHA-256",Oe(e));return yo(new Uint8Array(t))}async function Ys(e){let t=crypto.getRandomValues(new Uint8Array(32)),n=crypto.getRandomValues(new Uint8Array(12)),r=await fo(t,n,e.plaintext),o=r.slice(r.length-16),a=r.slice(0,r.length-16),i=(0,K.hybridKemEncapsulate)(e.recipientPublicKey),s=So(i.sharedSecret),l=crypto.getRandomValues(new Uint8Array(12)),d=await fo(s,l,t),u=await vo(a),p={lockbox_id:e.meta.lockbox_id,format_version:3,profile:"pq-hybrid",suite:{kem:K.PQ_SUITE.KEM,sig:K.PQ_SUITE.SIG,aead:K.PQ_SUITE.AEAD,kdf:K.PQ_SUITE.KDF},server:e.meta.server,kem:{recipient_kid:e.recipientKid,ct_classical:fe(i.ciphertext.ctClassical),ct_pq:fe(i.ciphertext.ctPq),ephemeral_x25519_pk:fe(i.ephemeralX25519Pk)},wrapped_content_key:{wrapped:fe(d),wrap_iv:fe(l)},iv:fe(n),tag:fe(o),bearer:e.meta.bearer,dpop_required:e.meta.dpop_required,ratchet_state:e.meta.ratchet_state,tee_attestation_url:e.meta.tee_attestation_url,original_filename:e.meta.original_filename,original_content_type:e.meta.original_content_type,ciphertext_sha256:u,issued_at:new Date().toISOString(),cache_ttl_seconds:e.meta.cache_ttl_seconds},h=mo(p,e.signerKid,e.signerKeypair),m=_o(h,r);return t.fill(0),{container:m,header:h,serverState:{lockbox_id:e.meta.lockbox_id,kem_ct_classical_b64:h.kem.ct_classical,kem_ct_pq_b64:h.kem.ct_pq,wrapped_content_key_b64:h.wrapped_content_key.wrapped,wrap_iv_b64:h.wrapped_content_key.wrap_iv}}}async function Xs(e){let{header:t,ciphertextWithTag:n}=bo(e.container);if(!go(t,e.signerPublicKey))throw new F("signature_invalid","hybrid signature verification failed");let r=n.slice(0,n.length-16),o=await vo(r);if(o!==t.ciphertext_sha256)throw new F("integrity_mismatch",`ciphertext sha256 mismatch: expected ${t.ciphertext_sha256.slice(0,16)}\u2026, got ${o.slice(0,16)}\u2026`);let a={ctClassical:De(t.kem.ct_classical),ctPq:De(t.kem.ct_pq)},i=(0,K.hybridKemDecapsulate)(e.recipientSecretKey,e.recipientPublicX25519,a),s=So(i),l=De(t.wrapped_content_key.wrapped),d=De(t.wrapped_content_key.wrap_iv),u=await ho(s,d,l),p=De(t.iv),h=await ho(u,p,n);return u.fill(0),{plaintext:h,header:t}}});var Yn=O(qe=>{"use strict";Object.defineProperty(qe,"__esModule",{value:!0});qe.publicJwkFromBytes=Eo;qe.jwkThumbprint=ko;qe.createDpop=Qs;qe.verifyDpop=tc;var wo=A("@noble/curves/ed25519.js"),Zs=A("@noble/hashes/sha2.js"),Ge=e=>{if(typeof Buffer<"u")return Buffer.from(e).toString("base64").replace(/=+$/,"").replace(/\+/g,"-").replace(/\//g,"_");let t="";for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return btoa(t).replace(/=+$/,"").replace(/\+/g,"-").replace(/\//g,"_")},Ft=e=>{let t=e.replace(/-/g,"+").replace(/_/g,"/"),n=t.length%4?4-t.length%4:0,r=t+"=".repeat(n);if(typeof Buffer<"u")return new Uint8Array(Buffer.from(r,"base64"));let o=atob(r),a=new Uint8Array(o.length);for(let i=0;i<o.length;i++)a[i]=o.charCodeAt(i);return a},ft=e=>new TextEncoder().encode(e);function Eo(e){if(e.length!==32)throw new Error(`expected 32-byte Ed25519 public key, got ${e.length}`);return{kty:"OKP",crv:"Ed25519",x:Ge(e)}}function ko(e){let t=`{"crv":"${e.crv}","kty":"${e.kty}","x":"${e.x}"}`,n=(0,Zs.sha256)(ft(t));return Ge(n)}function Qs(e){let n={typ:"dpop+jwt",alg:"EdDSA",jwk:Eo(e.publicKey)},r={htm:e.htm.toUpperCase(),htu:zn(e.htu),jti:e.jti??ec(),iat:e.iat??Math.floor(Date.now()/1e3)};e.nonce&&(r.nonce=e.nonce);let o=Ge(ft(JSON.stringify(n))),a=Ge(ft(JSON.stringify(r))),i=`${o}.${a}`,s=wo.ed25519.sign(ft(i),e.secretKey);return`${i}.${Ge(s)}`}function ec(){return Ge(crypto.getRandomValues(new Uint8Array(16)))}function zn(e){try{let t=new URL(e);return`${t.protocol}//${t.host}${t.pathname}`}catch{return e}}async function tc(e,t){let n=e.split(".");if(n.length!==3)return L("malformed","expected three JWT parts");let[r,o,a]=n,i;try{i=JSON.parse(new TextDecoder().decode(Ft(r)))}catch{return L("bad_header","header is not valid base64url JSON")}if(i.typ!=="dpop+jwt")return L("bad_typ",`typ must be 'dpop+jwt', got '${String(i.typ)}'`);if(i.alg!=="EdDSA")return L("bad_alg",`alg must be 'EdDSA', got '${String(i.alg)}'`);if(!i.jwk||i.jwk.kty!=="OKP"||i.jwk.crv!=="Ed25519")return L("bad_header","jwk must be an Ed25519 OKP key");let s=ko(i.jwk);if(s!==t.expectedJkt)return L("jkt_mismatch",`jkt does not match registered key: expected ${t.expectedJkt.slice(0,12)}\u2026, got ${s.slice(0,12)}\u2026`);let l;try{l=JSON.parse(new TextDecoder().decode(Ft(o)))}catch{return L("bad_payload","payload is not valid base64url JSON")}if(l.htm!==t.expectedHtm.toUpperCase())return L("htm_mismatch",`htm '${l.htm}' \u2260 expected '${t.expectedHtm.toUpperCase()}'`);if(l.htu!==zn(t.expectedHtu))return L("htu_mismatch",`htu '${l.htu}' \u2260 expected '${zn(t.expectedHtu)}'`);if(t.expectedNonce!==void 0&&l.nonce!==t.expectedNonce)return L("nonce_mismatch","DPoP nonce does not match server-issued nonce");let d=Math.floor(Date.now()/1e3),u=t.maxAgeSeconds??30;if(typeof l.iat!="number")return L("bad_payload","iat missing or not a number");if(l.iat>d+5)return L("iat_in_future",`iat ${l.iat} > now+skew`);if(d-l.iat>u)return L("iat_too_old",`iat ${l.iat} older than ${u}s`);let p;try{p=Ft(i.jwk.x)}catch{return L("bad_header","jwk.x is not base64url")}let h=Ft(a),m=ft(`${r}.${o}`);return wo.ed25519.verify(h,m,p)?await t.isJtiFresh(l.jti)?{ok:!0,jti:l.jti,iat:l.iat}:L("replay",`jti ${l.jti} was already seen`):L("signature_invalid","Ed25519 signature does not verify")}function L(e,t){return{ok:!1,code:e,reason:t}}});var No=O(b=>{"use strict";Object.defineProperty(b,"__esModule",{value:!0});b.ABSORB_STATUS=b.DELTA_KIND=b.RCPT_TOTAL_LEN=b.RCPT_SIGNED_LEN=b.PVE_TOTAL_LEN=b.PVE_SIGNED_LEN=b.RCPT_VERSION=b.PVE_VERSION=b.RCPT_MAGIC=b.PVE_MAGIC=void 0;b.deltaIdFromUuid=ac;b.uuidFromDeltaId=ic;b.originJktForPublicKey=yt;b.encodePveSignedBytes=To;b.signPve=sc;b.parsePve=Po;b.pveHash=cc;b.verifyPve=lc;b.encodeReceiptSignedBytes=Do;b.signReceipt=dc;b.parseReceipt=Oo;b.verifyReceipt=uc;var Lt=A("@noble/curves/ed25519.js"),nc=A("@noble/hashes/sha2.js"),xo=Yn();b.PVE_MAGIC=new Uint8Array([80,86,69,49]);b.RCPT_MAGIC=new Uint8Array([82,67,86,49]);b.PVE_VERSION=1;b.RCPT_VERSION=1;b.PVE_SIGNED_LEN=160;b.PVE_TOTAL_LEN=b.PVE_SIGNED_LEN+64;b.RCPT_SIGNED_LEN=78;b.RCPT_TOTAL_LEN=b.RCPT_SIGNED_LEN+64;var Ao=new Uint8Array(32);b.DELTA_KIND={relay:1,ndc:2,v4section:3,chatmsg:4};b.ABSORB_STATUS={decrypted_ok:1,verified_only:2,denied:3};function rc(e){if(typeof Buffer<"u")return Buffer.from(e).toString("base64").replace(/=+$/,"").replace(/\+/g,"-").replace(/\//g,"_");let t="";for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return btoa(t).replace(/=+$/,"").replace(/\+/g,"-").replace(/\//g,"_")}function oc(e){let t=e.replace(/-/g,"+").replace(/_/g,"/"),n=t.length%4?4-t.length%4:0,r=t+"=".repeat(n);if(typeof Buffer<"u")return new Uint8Array(Buffer.from(r,"base64"));let o=atob(r),a=new Uint8Array(o.length);for(let i=0;i<o.length;i++)a[i]=o.charCodeAt(i);return a}function Qn(e,t){if(e.length!==t.length)return!1;let n=0;for(let r=0;r<e.length;r++)n|=e[r]^t[r];return n===0}function ht(e){for(let t=0;t<e.length;t++)if(e[t]!==0)return!1;return!0}function Xn(e){if(e==null)return Ao;if(e instanceof Uint8Array){if(e.length!==32)throw new Error(`jkt bytes must be 32, got ${e.length}`);return e}let t=oc(e);if(t.length!==32)throw new Error(`jkt must decode to 32 bytes, got ${t.length}`);return t}function Zn(e){return ht(e)?null:rc(e)}function ac(e){let t=e.replace(/-/g,"");if(t.length!==32)throw new Error(`expected a 16-byte UUID, got '${e}'`);let n=new Uint8Array(16);for(let r=0;r<16;r++)n[r]=parseInt(t.slice(r*2,r*2+2),16);return n}function ic(e){if(e.length!==16)throw new Error(`expected 16 bytes, got ${e.length}`);let t=Array.from(e,n=>n.toString(16).padStart(2,"0")).join("");return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}function yt(e){return(0,xo.jwkThumbprint)((0,xo.publicJwkFromBytes)(e))}function To(e){if(e.deltaId.length!==16)throw new Error("delta_id must be 16 bytes");if(e.ciphertextSha256.length!==32)throw new Error("ciphertext_sha256 must be 32 bytes");if(e.classification<0||e.classification>65535)throw new Error("classification must fit in uint16");let t=new Uint8Array(b.PVE_SIGNED_LEN),n=new DataView(t.buffer),r=0;return t.set(b.PVE_MAGIC,r),r+=4,t[r]=b.PVE_VERSION,r+=1,t[r]=e.deltaKind,r+=1,t.set(e.deltaId,r),r+=16,t.set(e.ciphertextSha256,r),r+=32,t.set(Xn(e.originJkt),r),r+=32,t.set(Xn(e.destJkt??null),r),r+=32,t.set(e.prevDeltaHash??Ao,r),r+=32,n.setUint16(r,e.classification,!1),r+=2,n.setBigUint64(r,BigInt(e.issuedAt),!1),r+=8,t}function sc(e,t){let n=yt(e.originPublicKey),r=To({deltaKind:e.deltaKind,deltaId:e.deltaId,ciphertextSha256:e.ciphertextSha256,originJkt:n,destJkt:e.destJkt??null,prevDeltaHash:e.prevDeltaHash??null,classification:e.classification,issuedAt:e.issuedAt??Date.now()}),o=Lt.ed25519.sign(r,t),a=new Uint8Array(b.PVE_TOTAL_LEN);return a.set(r,0),a.set(o,b.PVE_SIGNED_LEN),a}function Po(e){if(e.length!==b.PVE_TOTAL_LEN)throw new Error(`PVE must be ${b.PVE_TOTAL_LEN} bytes, got ${e.length}`);if(!Qn(e.subarray(0,4),b.PVE_MAGIC))throw new Error("bad PVE magic");let t=new DataView(e.buffer,e.byteOffset,e.byteLength),n=4,r=e[n];n+=1;let o=e[n];n+=1;let a=e.slice(n,n+16);n+=16;let i=e.slice(n,n+32);n+=32;let s=e.slice(n,n+32);n+=32;let l=e.slice(n,n+32);n+=32;let d=e.slice(n,n+32);n+=32;let u=t.getUint16(n,!1);n+=2;let p=Number(t.getBigUint64(n,!1));n+=8;let h=e.slice(0,b.PVE_SIGNED_LEN),m=e.slice(b.PVE_SIGNED_LEN,b.PVE_TOTAL_LEN),v=Zn(s);if(v===null)throw new Error("origin_jkt must not be zero");return{fields:{version:r,deltaKind:o,deltaId:a,ciphertextSha256:i,originJkt:v,destJkt:Zn(l),prevDeltaHash:ht(d)?null:d,classification:u,issuedAt:p},signedBytes:h,originSig:m,broadcast:ht(l),genesis:ht(d)}}function cc(e){return(0,nc.sha256)(e)}function lc(e,t){let n;try{n=Po(e)}catch(o){let a=o instanceof Error?o.message:String(o);return a.includes("magic")?{ok:!1,code:"bad_magic",reason:a}:{ok:!1,code:"malformed",reason:a}}if(n.fields.version!==b.PVE_VERSION)return{ok:!1,code:"bad_version",reason:`unsupported PVE version ${n.fields.version}`};let r;try{r=yt(t)}catch(o){return{ok:!1,code:"malformed",reason:o instanceof Error?o.message:String(o)}}return r!==n.fields.originJkt?{ok:!1,code:"jkt_mismatch",reason:`presented key thumbprint ${r.slice(0,12)}\u2026 \u2260 committed origin_jkt ${n.fields.originJkt.slice(0,12)}\u2026`}:Lt.ed25519.verify(n.originSig,n.signedBytes,t)?{ok:!0,parsed:n}:{ok:!1,code:"signature_invalid",reason:"Ed25519 origin signature does not verify"}}function Do(e){if(e.pveHash.length!==32)throw new Error("pve_hash must be 32 bytes");let t=Xn(e.destJkt);if(ht(t))throw new Error("receipt dest_jkt must not be zero");let n=new Uint8Array(b.RCPT_SIGNED_LEN),r=new DataView(n.buffer),o=0;return n.set(b.RCPT_MAGIC,o),o+=4,n[o]=b.RCPT_VERSION,o+=1,n.set(e.pveHash,o),o+=32,n.set(t,o),o+=32,n[o]=e.absorbStatus,o+=1,r.setBigUint64(o,BigInt(e.absorbedAt),!1),o+=8,n}function dc(e,t){let n=yt(e.destPublicKey),r=Do({pveHash:e.pveHash,destJkt:n,absorbStatus:e.absorbStatus,absorbedAt:e.absorbedAt??Date.now()}),o=Lt.ed25519.sign(r,t),a=new Uint8Array(b.RCPT_TOTAL_LEN);return a.set(r,0),a.set(o,b.RCPT_SIGNED_LEN),a}function Oo(e){if(e.length!==b.RCPT_TOTAL_LEN)throw new Error(`receipt must be ${b.RCPT_TOTAL_LEN} bytes, got ${e.length}`);if(!Qn(e.subarray(0,4),b.RCPT_MAGIC))throw new Error("bad receipt magic");let t=new DataView(e.buffer,e.byteOffset,e.byteLength),n=4,r=e[n];n+=1;let o=e.slice(n,n+32);n+=32;let a=e.slice(n,n+32);n+=32;let i=e[n];n+=1;let s=Number(t.getBigUint64(n,!1));n+=8;let l=Zn(a);if(l===null)throw new Error("receipt dest_jkt must not be zero");return{fields:{version:r,pveHash:o,destJkt:l,absorbStatus:i,absorbedAt:s},signedBytes:e.slice(0,b.RCPT_SIGNED_LEN),destSig:e.slice(b.RCPT_SIGNED_LEN,b.RCPT_TOTAL_LEN)}}function uc(e,t,n){let r;try{r=Oo(e)}catch(a){let i=a instanceof Error?a.message:String(a);return i.includes("magic")?{ok:!1,code:"bad_magic",reason:i}:{ok:!1,code:"malformed",reason:i}}if(r.fields.version!==b.RCPT_VERSION)return{ok:!1,code:"bad_version",reason:`unsupported receipt version ${r.fields.version}`};let o;try{o=yt(t)}catch(a){return{ok:!1,code:"malformed",reason:a instanceof Error?a.message:String(a)}}return o!==r.fields.destJkt?{ok:!1,code:"jkt_mismatch",reason:`presented key thumbprint ${o.slice(0,12)}\u2026 \u2260 committed dest_jkt ${r.fields.destJkt.slice(0,12)}\u2026`}:n!==void 0&&!Qn(n,r.fields.pveHash)?{ok:!1,code:"pve_hash_mismatch",reason:"receipt does not acknowledge the expected PVE"}:Lt.ed25519.verify(r.destSig,r.signedBytes,t)?{ok:!0,parsed:r}:{ok:!1,code:"signature_invalid",reason:"Ed25519 destination signature does not verify"}}});var Co=O(mt=>{"use strict";Object.defineProperty(mt,"__esModule",{value:!0});mt.stepRatchet=pc;mt.replayRatchet=fc;mt.destroyKey=hc;var Io=Ve();function pc(e,t){if(t.length!==32)throw new Error(`ratchet token must be 32 bytes, got ${t.length}`);return{nextContentKey:(0,Io.ratchetAdvance)(e.contentKey,t),openCount:e.openCount+1}}function fc(e,t){let n=[e],r=e;for(let o of t)r=(0,Io.ratchetAdvance)(r,o),n.push(r);return n}function hc(e){e.fill(0)}});var nr=O(We=>{"use strict";Object.defineProperty(We,"__esModule",{value:!0});We.__coseInternals=void 0;We.verifyCoseSign1Es384=gc;We.decodeAttestationPayload=_c;var yc=A("@noble/curves/nist.js"),mc=A("@noble/hashes/sha2.js"),er=class{constructor(t){this.b=t,this.p=0}u8(){if(this.p>=this.b.length)throw new Error("cbor: truncated");return this.b[this.p++]}uN(t){let n=0;for(let r=0;r<t;r++)n=n*256+this.u8();return n}len(t){if(t<24)return t;if(t===24)return this.u8();if(t===25)return this.uN(2);if(t===26)return this.uN(4);if(t===27){let n=this.uN(4),r=this.uN(4);return n*4294967296+r}throw new Error(`cbor: unsupported additional info ${t}`)}read(){let t=this.u8(),n=t>>5,r=t&31;switch(n){case 0:return this.len(r);case 1:return-1-this.len(r);case 2:{let o=this.len(r),a=this.b.subarray(this.p,this.p+o);if(a.length!==o)throw new Error("cbor: bstr truncated");return this.p+=o,a.slice()}case 3:{let o=this.len(r),a=this.b.subarray(this.p,this.p+o);if(a.length!==o)throw new Error("cbor: tstr truncated");return this.p+=o,new TextDecoder("utf-8").decode(a)}case 4:{let o=this.len(r),a=[];for(let i=0;i<o;i++)a.push(this.read());return a}case 5:{let o=this.len(r),a=new Map;for(let i=0;i<o;i++){let s=this.read(),l=this.read();a.set(s,l)}return a}case 6:return this.len(r),this.read();case 7:if(r===20)return!1;if(r===21)return!0;if(r===22||r===23)return null;throw new Error(`cbor: unsupported simple/float ${r}`);default:throw new Error(`cbor: unknown major ${n}`)}}};function tr(e){return new er(e).read()}function Ht(e,t){let n=e<<5;return t<24?Uint8Array.of(n|t):t<=255?Uint8Array.of(n|24,t):t<=65535?Uint8Array.of(n|25,t>>8&255,t&255):Uint8Array.of(n|26,t>>>24&255,t>>16&255,t>>8&255,t&255)}function Vt(...e){let t=e.reduce((o,a)=>o+a.length,0),n=new Uint8Array(t),r=0;for(let o of e)n.set(o,r),r+=o.length;return n}function Ut(e){return Vt(Ht(2,e.length),e)}function Ro(e){let t=new TextEncoder().encode(e);return Vt(Ht(3,t.length),t)}function $o(e,t){return Vt(Ht(4,4),Ro("Signature1"),Ut(e),Ut(new Uint8Array(0)),Ut(t))}function gc(e,t){let n;try{n=tr(e)}catch(d){return{ok:!1,code:"malformed",reason:`cbor decode failed: ${d.message}`}}if(!Array.isArray(n)||n.length!==4)return{ok:!1,code:"bad_structure",reason:"COSE_Sign1 must be a 4-element array"};let[r,,o,a]=n;if(!(r instanceof Uint8Array))return{ok:!1,code:"bad_structure",reason:"protected header must be a byte string"};if(!(o instanceof Uint8Array)||o.length===0)return{ok:!1,code:"no_payload",reason:"detached/empty payload is not supported"};if(!(a instanceof Uint8Array))return{ok:!1,code:"bad_structure",reason:"signature must be a byte string"};if(a.length!==96)return{ok:!1,code:"bad_signature_len",reason:`expected 96-byte ES384 sig, got ${a.length}`};let i=$o(r,o),s=(0,mc.sha384)(i),l=!1;try{l=yc.p384.verify(a,s,t,{prehash:!1})}catch(d){return{ok:!1,code:"signature_invalid",reason:`verify threw: ${d.message}`}}return l?{ok:!0,payload:o}:{ok:!1,code:"signature_invalid",reason:"ECDSA P-384 verification failed"}}function _c(e){try{let t=tr(e);return t instanceof Map?t:null}catch{return null}}We.__coseInternals={sig1Structure:$o,encBstr:Ut,encText:Ro,encHead:Ht,concat:Vt,decodeCbor:tr}});var Bo=O(gt=>{"use strict";Object.defineProperty(gt,"__esModule",{value:!0});gt.parseAttestation=Sc;gt.verifyAttestation=vc;gt.fetchAttestation=wc;var bc=nr();function Sc(e){try{let t=new TextDecoder("utf-8").decode(e),n=JSON.parse(t);return n.vendor?n.module_id?!n.pcrs||typeof n.pcrs!="object"?{error:"missing pcrs"}:typeof n.timestamp!="number"?{error:"missing timestamp"}:typeof n.user_data_sha256!="string"?{error:"missing user_data_sha256"}:{vendor:n.vendor,module_id:n.module_id,pcrs:n.pcrs,timestamp:n.timestamp,user_data_sha256:n.user_data_sha256,raw:e}:{error:"missing module_id"}:{error:"missing vendor"}}catch(t){return{error:`parse failed: ${t.message}`}}}function vc(e,t){if(e.vendor!==t.vendor)return{ok:!1,code:"vendor_mismatch",reason:`vendor '${e.vendor}' \u2260 expected '${t.vendor}'`};if(e.module_id!==t.module_id)return{ok:!1,code:"module_id_mismatch",reason:`module_id mismatch (got '${e.module_id.slice(0,16)}\u2026')`};for(let[a,i]of Object.entries(t.pcrs))if(e.pcrs[a]!==i)return{ok:!1,code:"pcr_mismatch",reason:`PCR ${a}: got '${(e.pcrs[a]??"").slice(0,16)}\u2026', expected '${i.slice(0,16)}\u2026'`};if(e.user_data_sha256!==t.expected_user_data_sha256)return{ok:!1,code:"user_data_mismatch",reason:"attested user_data does not match presented key"};let n=Math.floor(Date.now()/1e3),r=t.maxAgeSeconds??600;if(e.timestamp>n+30)return{ok:!1,code:"in_future",reason:`attestation timestamp ${e.timestamp} > now+30s`};if(n-e.timestamp>r)return{ok:!1,code:"expired",reason:`attestation ${n-e.timestamp}s old (max ${r}s)`};let o=!1;if(t.cose){if(!t.trustedLeafPubKey)return{ok:!1,code:"signature_invalid",reason:"cose supplied without trustedLeafPubKey \u2014 cannot verify, refusing"};let a=(0,bc.verifyCoseSign1Es384)(t.cose,t.trustedLeafPubKey);if(!a.ok)return{ok:!1,code:"signature_invalid",reason:`cose: ${a.code}: ${a.reason}`};o=!0}return{ok:!0,vendor:e.vendor,module_id:e.module_id,signature_verified:o}}async function wc(e){let n=await(e.fetchImpl??fetch)(e.attestationUrl,{method:"GET"});if(!n.ok)throw new Error(`attestation fetch failed: ${n.status} ${n.statusText}`);return new Uint8Array(await n.arrayBuffer())}});var Mo=O(Je=>{"use strict";Object.defineProperty(Je,"__esModule",{value:!0});Je.splitSecret=Ac;Je.combineShares=Tc;Je.serializeShare=Oc;Je.deserializeShare=Nc;var Ne=null,Ie=null;function Ko(){if(Ne&&Ie)return;Ne=new Uint8Array(512),Ie=new Uint8Array(256);let e=1;for(let t=0;t<255;t++){Ne[t]=e,Ie[e]=t;let n=e<<1;n&256&&(n^=283),n^=e,e=n&255}for(let t=255;t<512;t++)Ne[t]=Ne[t-255]}function Gt(e,t){return e===0||t===0?0:(Ko(),Ne[Ie[e]+Ie[t]])}function Ec(e,t){if(e===0)return 0;if(t===0)throw new Error("division by zero in GF(2^8)");Ko();let n=Ie[e]-Ie[t];return Ne[n<0?n+255:n]}function jo(e,t){return e^t}function kc(e,t){let n=0;for(let r=e.length-1;r>=0;r--)n=jo(Gt(n,t),e[r]);return n}var xc=e=>crypto.getRandomValues(new Uint8Array(e));function Ac(e,t){if(t.k<2)throw new Error("threshold k must be \u2265 2");if(t.n<t.k)throw new Error(`total shares n (${t.n}) must be \u2265 threshold k (${t.k})`);if(t.n>255)throw new Error("total shares n must be \u2264 255 (limit of GF(2^8))");if(e.length===0)throw new Error("secret must be non-empty");let n=t.randomBytes??xc,r=[];for(let o=1;o<=t.n;o++)r.push({x:o,y:new Uint8Array(e.length)});for(let o=0;o<e.length;o++){let a=new Uint8Array(t.k);a[0]=e[o];let i=n(t.k-1);for(let s=1;s<t.k;s++)a[s]=i[s-1];for(let s=0;s<t.n;s++)r[s].y[o]=kc(a,r[s].x)}return r}function Tc(e){if(e.length<2)throw new Error("need at least 2 shares to reconstruct");let t=e[0].y.length;for(let o of e){if(o.y.length!==t)throw new Error("shares have inconsistent length");if(o.x===0)throw new Error("share x must not be 0")}let n=new Set;for(let o of e){if(n.has(o.x))throw new Error(`duplicate share x=${o.x}`);n.add(o.x)}let r=new Uint8Array(t);for(let o=0;o<t;o++){let a=0;for(let i=0;i<e.length;i++){let s=1,l=1;for(let u=0;u<e.length;u++)i!==u&&(s=Gt(s,e[u].x),l=Gt(l,e[i].x^e[u].x));let d=Ec(s,l);a=jo(a,Gt(e[i].y[o],d))}r[o]=a}return r}var Pc=e=>{if(typeof Buffer<"u")return Buffer.from(e).toString("base64");let t="";for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return btoa(t)},Dc=e=>{if(typeof Buffer<"u")return new Uint8Array(Buffer.from(e,"base64"));let t=atob(e),n=new Uint8Array(t.length);for(let r=0;r<t.length;r++)n[r]=t.charCodeAt(r);return n};function Oc(e){return{x:e.x,y_b64:Pc(e.y)}}function Nc(e){return{x:e.x,y:Dc(e.y_b64)}}});var Ho=O(Se=>{"use strict";Object.defineProperty(Se,"__esModule",{value:!0});Se.SegmentError=void 0;Se.sealSegments=Bc;Se.openSegments=Kc;Se.manifestDigest=jc;Se.buildCapability=Mc;var rr=A("@noble/hashes/sha2.js"),Ic="pq-hybrid-segments",Cc="AES-256-GCM",ze=e=>e,Fo=e=>{if(typeof Buffer<"u")return Buffer.from(e).toString("base64");let t="";for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return btoa(t)},Lo=e=>{if(typeof Buffer<"u")return new Uint8Array(Buffer.from(e,"base64"));let t=atob(e),n=new Uint8Array(t.length);for(let r=0;r<t.length;r++)n[r]=t.charCodeAt(r);return n},Uo=e=>{let t="";for(let n=0;n<e.length;n++)t+=e[n].toString(16).padStart(2,"0");return t};async function Rc(e,t,n){let r=await crypto.subtle.importKey("raw",ze(e),{name:"AES-GCM"},!1,["encrypt"]),o=await crypto.subtle.encrypt({name:"AES-GCM",iv:ze(t)},r,ze(n));return new Uint8Array(o)}async function $c(e,t,n){let r=await crypto.subtle.importKey("raw",ze(e),{name:"AES-GCM"},!1,["decrypt"]),o=await crypto.subtle.decrypt({name:"AES-GCM",iv:ze(t)},r,ze(n));return new Uint8Array(o)}var Ce=class extends Error{constructor(t,n){super(n),this.name="SegmentError",this.code=t}};Se.SegmentError=Ce;async function Bc(e){let t=new Set;for(let o of e){if(t.has(o.segment_id))throw new Ce("duplicate_segment_id",`segment_id '${o.segment_id}' appears twice`);t.add(o.segment_id)}let n=[],r=[];for(let o of e){let a=crypto.getRandomValues(new Uint8Array(32)),i=crypto.getRandomValues(new Uint8Array(12)),s=await Rc(a,i,o.plaintext),l=s.slice(0,s.length-16),d=Uo((0,rr.sha256)(l));n.push({segment_id:o.segment_id,key:a}),r.push({segment_id:o.segment_id,label:o.label,content_type:o.content_type,iv_b64:Fo(i),ciphertext_b64:Fo(s),ciphertext_sha256:d})}return{manifest:{profile:Ic,aead:Cc,segments:r},keys:n}}async function Kc(e,t){let n=new Map;for(let o of t.keys)n.set(o.segment_id,o.key);let r=[];for(let o of e.segments){if(!t.allowed_segment_ids.includes(o.segment_id))continue;let a=n.get(o.segment_id);if(!a)throw new Ce("key_missing",`capability lists ${o.segment_id} as allowed but holds no key for it`);let i=Lo(o.ciphertext_b64),s=i.slice(0,i.length-16);if(Uo((0,rr.sha256)(s))!==o.ciphertext_sha256)throw new Ce("integrity_mismatch",`segment ${o.segment_id}: ciphertext sha256 mismatch`);let d=Lo(o.iv_b64),u=await $c(a,d,i);r.push({segment_id:o.segment_id,label:o.label,content_type:o.content_type,plaintext:u})}return r}function jc(e){let t=e.segments.map(r=>({id:r.segment_id,h:r.ciphertext_sha256})),n=JSON.stringify({profile:e.profile,aead:e.aead,segments:t});return(0,rr.sha256)(new TextEncoder().encode(n))}function Mc(e,t,n){let r=new Set(t),o=n.filter(a=>r.has(a.segment_id));if(o.length!==t.length){let a=t.filter(i=>!o.find(s=>s.segment_id===i));throw new Ce("segment_not_found",`cannot build capability \u2014 no key for: ${a.join(", ")}`)}return{recipient_kid:e,allowed_segment_ids:t,keys:o}}});var qo=O(_t=>{"use strict";Object.defineProperty(_t,"__esModule",{value:!0});_t.computeWatermark=Go;_t.findLeakSource=Uc;_t.watermarkSvgOverlay=Hc;var Fc=A("@noble/hashes/hmac.js"),Lc=A("@noble/hashes/sha2.js");function Go(e){let t=[e.recipientId,e.lockboxId,String(e.openCount),String(e.iat)].join("|"),n=(0,Fc.hmac)(Lc.sha256,e.tenantSecret,new TextEncoder().encode(t)),r=Vo(n.slice(0,16)),o=Vo(n.slice(0,4)),a=new Date(e.iat*1e3).toISOString().slice(0,10),i=`${e.recipientId} \xB7 ${a} \xB7 ${o}`;return{short_hex:o,full_hex:r,display_label:i}}function Uc(e,t,n){let r=e.toLowerCase();for(let o of n){let a=Go({tenantSecret:t,...o});if(r===a.full_hex)return{matched:!0,candidate:o,matched_on:"full_hex"};if(r===a.short_hex)return{matched:!0,candidate:o,matched_on:"short_hex"}}return{matched:!1,reason:"no_candidate_matched"}}function Hc(e,t){let n=t?.width??800,r=t?.height??1e3,o=t?.opacity??.1,i=(s=>s.replace(/[<>&"]/g,l=>({"<":"&lt;",">":"&gt;","&":"&amp;",'"':"&quot;"})[l]))(e.display_label);return`<svg xmlns="http://www.w3.org/2000/svg" width="${n}" height="${r}" pointer-events="none">
4
+ var Yi=Object.create;var Wr=Object.defineProperty;var Xi=Object.getOwnPropertyDescriptor;var Zi=Object.getOwnPropertyNames;var Qi=Object.getPrototypeOf,es=Object.prototype.hasOwnProperty;var T=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,n)=>(typeof require<"u"?require:t)[n]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var C=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var ts=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Zi(t))!es.call(e,o)&&o!==n&&Wr(e,o,{get:()=>t[o],enumerable:!(r=Xi(t,o))||r.enumerable});return e};var Jr=(e,t,n)=>(n=e!=null?Yi(Qi(e)):{},ts(t||!e||!e.__esModule?Wr(n,"default",{value:e,enumerable:!0}):n,e));var Fn=C(Z=>{"use strict";Object.defineProperty(Z,"__esModule",{value:!0});Z.MAX_SEALED_BYTES=void 0;Z.kidForPublicKey=So;Z.deriveKeyPairFromSeed=Ys;Z.generateSeed=Xs;Z.buildEnvInfo=Zs;Z.sealDek=Qs;Z.openSealedDek=ec;Z.decodeSealHeader=wo;var go=T("crypto"),mo=T("@hpke/core"),Gs=T("@hpke/dhkem-x25519"),qs=T("@hpke/chacha20poly1305"),Ws=T("@noble/curves/ed25519.js"),Js=T("@noble/hashes/hkdf.js"),zs=T("@noble/hashes/sha2.js"),Ft=new mo.CipherSuite({kem:new Gs.DhkemX25519HkdfSha256,kdf:new mo.HkdfSha256,aead:new qs.Chacha20Poly1305}),_o=1,bo=1;Z.MAX_SEALED_BYTES=4096;function So(e){return(0,go.createHash)("sha256").update(e).digest("hex").slice(0,16)}function Ys(e){if(e.length<16)throw new Error("seed too short (need at least 16 bytes)");let t=new TextEncoder().encode("protect.env.x25519.v1"),n=Buffer.from((0,Js.hkdf)(zs.sha256,e,new Uint8Array(0),t,32)),r=Buffer.from(Ws.x25519.scalarMultBase(n));return{secretKey:n,publicKey:r,kid:So(r)}}function Xs(){return(0,go.randomBytes)(32)}function Zs(e){return Buffer.from(`protect.env.v3|${e}`,"utf8")}async function Qs(e,t,n){if(e.length!==32)throw new Error("sealDek: DEK must be 32 bytes");if(t.length!==32)throw new Error("sealDek: public key must be 32 bytes");let r=await Ft.kem.deserializePublicKey(Ie(t)),o=await Ft.createSenderContext({recipientPublicKey:r,info:Ie(n)}),a=Buffer.from(await o.seal(Ie(e),new ArrayBuffer(0))),i=Buffer.from(o.enc),s=Buffer.alloc(6+i.length+a.length);return s[0]=_o,s[1]=bo,s.writeUInt16BE(i.length,2),s.writeUInt16BE(a.length,4),i.copy(s,6),a.copy(s,6+i.length),s}async function ec(e,t,n){let r=wo(e),o=e.subarray(6,6+r.encLen),a=e.subarray(6+r.encLen),i=await Ft.kem.deserializePrivateKey(Ie(t)),s=await Ft.createRecipientContext({recipientKey:i,enc:Ie(o),info:Ie(n)});return Buffer.from(await s.open(Ie(a)))}function wo(e){if(e.length<6)throw new Error("sealed bytes too short");if(e.length>Z.MAX_SEALED_BYTES)throw new Error("sealed bytes too long");let t=e[0],n=e[1];if(t!==_o)throw new Error(`unsupported seal version 0x${t.toString(16)}`);if(n!==bo)throw new Error(`unsupported HPKE suite 0x${n.toString(16)}`);let r=e.readUInt16BE(2),o=e.readUInt16BE(4);if(e.length!==6+r+o)throw new Error("sealed length mismatch");if(r!==32)throw new Error("unexpected KEM enc length (X25519 is 32 bytes)");if(o<16)throw new Error("ciphertext shorter than the AEAD tag");return{ver:t,suite:n,encLen:r,ctLen:o}}function Ie(e){return e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength)}});var ko=C(he=>{"use strict";Object.defineProperty(he,"__esModule",{value:!0});he.V3_PREFIX=void 0;he.sealValue=tc;he.formatToken=nc;he.parseToken=vo;he.openValue=rc;var Ut=T("crypto"),Ht=Fn();he.V3_PREFIX="aes256gcm:v3:";async function tc(e,t){let n=(0,Ut.randomBytes)(32),r=(0,Ut.randomBytes)(12),o=(0,Ut.createCipheriv)("aes-256-gcm",n,r),a=Buffer.concat([o.update(e,"utf8"),o.final()]),i=Buffer.concat([a,o.getAuthTag()]),s=await(0,Ht.sealDek)(n,t.publicKey,(0,Ht.buildEnvInfo)(t.kid));return n.fill(0),{sealedDekB64:s.toString("base64"),iv:r,cipher:i}}function nc(e,t){return`${he.V3_PREFIX}${e.iv.toString("base64")}:${e.cipher.toString("base64")}:${t}`}function vo(e){let t=e.split(":");if(t.length!==5||t[0]!=="aes256gcm"||t[1]!=="v3")throw new Error("not a v3 token");let[,,n,r,o]=t;if(!o)throw new Error("v3 token has no seal id");let a=Buffer.from(n,"base64"),i=Buffer.from(r,"base64");if(a.length!==12)throw new Error("v3 token has a malformed iv");if(i.length<17)throw new Error("v3 token ciphertext is too short");return{iv:a,cipher:i,sealId:o}}async function rc(e,t,n){let{iv:r,cipher:o}=vo(e),a=await(0,Ht.openSealedDek)(Buffer.from(t,"base64"),n.secretKey,(0,Ht.buildEnvInfo)(n.kid)),i=o.subarray(o.length-16),s=o.subarray(0,o.length-16),c=(0,Ut.createDecipheriv)("aes-256-gcm",a,r);c.setAuthTag(i);try{return Buffer.concat([c.update(s),c.final()]).toString("utf8")}finally{a.fill(0)}}});var To=C(V=>{"use strict";var oc=V&&V.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n);var o=Object.getOwnPropertyDescriptor(t,n);(!o||("get"in o?!t.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,o)}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),ac=V&&V.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),Hn=V&&V.__importStar||(function(){var e=function(t){return e=Object.getOwnPropertyNames||function(n){var r=[];for(var o in n)Object.prototype.hasOwnProperty.call(n,o)&&(r[r.length]=o);return r},e(t)};return function(t){if(t&&t.__esModule)return t;var n={};if(t!=null)for(var r=e(t),o=0;o<r.length;o++)r[o]!=="default"&&oc(n,t,r[o]);return ac(n,t),n}})();Object.defineProperty(V,"__esModule",{value:!0});V.deviceKeyPath=sc;V.hasDeviceKey=cc;V.loadDeviceKey=lc;V.createDeviceKey=dc;V.importDeviceKey=uc;V.exportSeedHex=pc;V.deviceKeyIsExposed=fc;var z=Hn(T("fs")),ic=Hn(T("os")),Eo=Hn(T("path")),ht=Fn(),Un=Eo.join(ic.homedir(),".nodata"),L=Eo.join(Un,"device-key.json");function sc(){return L}function xo(){let e=process.env.NODATA_DEVICE_SEED;if(!e)return null;let t=e.trim();if(!/^[0-9a-fA-F]{64}$/.test(t))throw new Error("NODATA_DEVICE_SEED must be 64 hex characters (32 bytes)");return Buffer.from(t,"hex")}function cc(){return xo()!==null||z.existsSync(L)}function lc(){let e=xo();if(e)return(0,ht.deriveKeyPairFromSeed)(e);if(!z.existsSync(L))return null;let t;try{t=JSON.parse(z.readFileSync(L,"utf-8"))}catch{throw new Error(`Device key file is unreadable: ${L}`)}if(!t.seed_hex||!/^[0-9a-f]{64}$/i.test(t.seed_hex))throw new Error(`Device key file is malformed (bad seed): ${L}`);let n=(0,ht.deriveKeyPairFromSeed)(Buffer.from(t.seed_hex,"hex"));if(t.kid&&t.kid!==n.kid)throw new Error(`Device key file is inconsistent: stored kid ${t.kid} does not match the seed (${n.kid}).`);return n}function dc(e={}){if(z.existsSync(L)&&!e.force)throw new Error(`A device key already exists at ${L}. Replacing it makes every existing v3 seal unopenable. Back up the seed first (nodata key export), then pass --force.`);let t=(0,ht.generateSeed)(),n=(0,ht.deriveKeyPairFromSeed)(t);return Ao(t,n),n}function uc(e,t={}){let n=e.trim().replace(/\s+/g,"");if(!/^[0-9a-fA-F]{64}$/.test(n))throw new Error("Seed must be 64 hex characters (32 bytes).");if(z.existsSync(L)&&!t.force)throw new Error(`A device key already exists at ${L}. Pass --force to replace it.`);let r=Buffer.from(n,"hex"),o=(0,ht.deriveKeyPairFromSeed)(r);return Ao(r,o),o}function pc(){if(!z.existsSync(L))throw new Error("No device key file to export.");return JSON.parse(z.readFileSync(L,"utf-8")).seed_hex}function Ao(e,t){z.existsSync(Un)||z.mkdirSync(Un,{recursive:!0});let n={version:1,kid:t.kid,pubkey_hex:t.publicKey.toString("hex"),seed_hex:e.toString("hex"),created_at:new Date().toISOString()};z.writeFileSync(L,JSON.stringify(n,null,2)+`
5
+ `,{mode:384});try{z.chmodSync(L,384)}catch{}}function fc(){if(process.platform==="win32"||!z.existsSync(L))return!1;try{return(z.statSync(L).mode&63)!==0}catch{return!1}}});var No=C(Y=>{"use strict";var hc=Y&&Y.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n);var o=Object.getOwnPropertyDescriptor(t,n);(!o||("get"in o?!t.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,o)}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),yc=Y&&Y.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),Po=Y&&Y.__importStar||(function(){var e=function(t){return e=Object.getOwnPropertyNames||function(n){var r=[];for(var o in n)Object.prototype.hasOwnProperty.call(n,o)&&(r[r.length]=o);return r},e(t)};return function(t){if(t&&t.__esModule)return t;var n={};if(t!=null)for(var r=e(t),o=0;o<r.length;o++)r[o]!=="default"&&hc(n,t,r[o]);return yc(n,t),n}})();Object.defineProperty(Y,"__esModule",{value:!0});Y.ensureDeviceKey=mc;Y.sealFile=gc;Y.readManifest=Do;Y.openFile=_c;Y.writeLocalReceipt=bc;var Vn=T("crypto"),ge=T("fs"),yt=T("path"),Gn=Po(ko()),qn=Po(To());function mc(){let e=qn.loadDeviceKey();return e?{key:e,created:!1}:{key:qn.createDeviceKey(),created:!0}}async function gc(e,t,n){let r=(0,ge.readFileSync)(e),o=(0,Vn.createHash)("sha256").update(r).digest("hex"),a=n??"local-"+(0,Vn.randomUUID)(),i=await Gn.sealValue(r.toString("base64"),t),s={v:3,alg:"aes256gcm:v3",kid:t.kid,orig:(0,yt.basename)(e),enc:"base64",token:Gn.formatToken(i,a),sealed_dek:i.sealedDekB64,sha256:o,sealed_at:new Date().toISOString()},c=e+".ndc";return(0,ge.writeFileSync)(c,JSON.stringify(s,null,2)+`
6
+ `,{mode:384}),{path:e,ndc:c,sha256:o,sealId:a}}function Do(e){try{let t=JSON.parse((0,ge.readFileSync)(e,"utf8"));return t.alg==="aes256gcm:v3"&&t.token&&t.sealed_dek?t:null}catch{return null}}async function _c(e,t){if(!(0,ge.existsSync)(e))return{ok:!1,error:"not_found"};let n=Do(e);if(!n)return{ok:!1,error:"not_a_seal"};let r=t===void 0?qn.loadDeviceKey():t;if(!r)return{ok:!1,error:"no_device_key"};let o;try{o=await Gn.openValue(n.token,n.sealed_dek,r)}catch{return{ok:!1,error:"wrong_key"}}let a=Buffer.from(o,"base64"),i=e.endsWith(".ndc")?e.slice(0,-4):e+".opened";(0,ge.existsSync)(i)&&(i=i+".opened"),(0,ge.writeFileSync)(i,a);let s=(0,Vn.createHash)("sha256").update(a).digest("hex")===n.sha256;return{ok:!0,outPath:i,sha256:n.sha256,intact:s}}function bc(e,t){let n=(0,yt.join)(e,".nodata","receipts");(0,ge.mkdirSync)(n,{recursive:!0});let r={action:t.action,at:new Date().toISOString(),governed:"local",device_kid:t.kid,removed_plaintext:t.removed_plaintext,files:t.files.map(a=>({path:(0,yt.relative)(e,a.path),sha256:a.sha256,seal_id:a.sealId,sealed:(0,yt.basename)(a.ndc)})),...t.extra??{}},o=(0,yt.join)(n,`${t.action}-${Date.now()}.json`);return(0,ge.writeFileSync)(o,JSON.stringify(r,null,2)+`
7
+ `),o}});var $e=C(Zn=>{"use strict";Object.defineProperty(Zn,"__esModule",{value:!0});var _t=class{static async generateKeyPair(){let t=await crypto.subtle.generateKey({name:"RSA-OAEP",modulusLength:4096,publicExponent:new Uint8Array([1,0,1]),hash:"SHA-256"},!0,["encrypt","decrypt"]),n=await crypto.subtle.exportKey("jwk",t.publicKey),r=await crypto.subtle.exportKey("jwk",t.privateKey);return{publicKeyJwk:n,privateKeyJwk:r}}static async encryptMessage(t,n){let r=await crypto.subtle.importKey("jwk",n,{name:"RSA-OAEP",hash:"SHA-256"},!1,["encrypt"]),o=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!0,["encrypt","decrypt"]),a=crypto.getRandomValues(new Uint8Array(12)),i=new TextEncoder().encode(t),s=await crypto.subtle.encrypt({name:"AES-GCM",iv:a,tagLength:128},o,i),c=await crypto.subtle.exportKey("raw",o),d=await crypto.subtle.encrypt({name:"RSA-OAEP"},r,c);return{encrypted_blob:this.arrayBufferToBase64(s),encrypted_aes_key:this.arrayBufferToBase64(d),iv:this.arrayBufferToBase64(a)}}static async decryptMessage(t,n){let r=await crypto.subtle.importKey("jwk",n,{name:"RSA-OAEP",hash:"SHA-256"},!1,["decrypt"]),o=this.base64ToArrayBuffer(t.encrypted_aes_key),a=await crypto.subtle.decrypt({name:"RSA-OAEP"},r,o),i=await crypto.subtle.importKey("raw",a,{name:"AES-GCM",length:256},!1,["decrypt"]),s=this.base64ToArrayBuffer(t.iv),c=this.base64ToArrayBuffer(t.encrypted_blob),d=await crypto.subtle.decrypt({name:"AES-GCM",iv:s,tagLength:128},i,c);return new TextDecoder().decode(d)}static async encryptFile(t,n){let r=await t.arrayBuffer(),o=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!0,["encrypt","decrypt"]),a=crypto.getRandomValues(new Uint8Array(12)),i=await crypto.subtle.encrypt({name:"AES-GCM",iv:a,tagLength:128},o,r),s=JSON.stringify({name:t.name,type:t.type,size:t.size,lastModified:t.lastModified}),c=crypto.getRandomValues(new Uint8Array(12)),d=await crypto.subtle.encrypt({name:"AES-GCM",iv:c,tagLength:128},o,new TextEncoder().encode(s)),u=await crypto.subtle.importKey("jwk",n,{name:"RSA-OAEP",hash:"SHA-256"},!1,["encrypt"]),p=await crypto.subtle.exportKey("raw",o),f=await crypto.subtle.encrypt({name:"RSA-OAEP"},u,p);return{encrypted_file:this.arrayBufferToBase64(i),encrypted_file_key:this.arrayBufferToBase64(f),iv:this.arrayBufferToBase64(a),encrypted_metadata:this.arrayBufferToBase64(d),metadata_iv:this.arrayBufferToBase64(c),encrypted_size:i.byteLength}}static async importKeyFromFragment(t){let n=t.replace(/-/g,"+").replace(/_/g,"/"),r=this.base64ToArrayBuffer(n.padEnd(Math.ceil(n.length/4)*4,"="));if(r.byteLength!==32)throw new Error("channel key must be 32 bytes");return crypto.subtle.importKey("raw",r,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}static async deriveKeyFromOTP(t,n,r="SHA-512"){let o=await crypto.subtle.importKey("raw",new TextEncoder().encode(t),"PBKDF2",!1,["deriveBits","deriveKey"]);return await crypto.subtle.deriveKey({name:"PBKDF2",salt:new TextEncoder().encode(n),iterations:31e4,hash:r},o,{name:"AES-GCM",length:256},!0,["encrypt","decrypt"])}static async encryptWithDerivedKey(t,n){let r=crypto.getRandomValues(new Uint8Array(12)),o=new TextEncoder().encode(t),a=await crypto.subtle.encrypt({name:"AES-GCM",iv:r,tagLength:128},n,o);return{encrypted:this.arrayBufferToBase64(a),iv:this.arrayBufferToBase64(r)}}static async decryptWithDerivedKey(t,n,r){let o=this.base64ToArrayBuffer(t),a=this.base64ToArrayBuffer(n),i=await crypto.subtle.decrypt({name:"AES-GCM",iv:a,tagLength:128},r,o);return new TextDecoder().decode(i)}static async sha256Hex(t){let n=t instanceof Uint8Array?t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength):t,r=await crypto.subtle.digest("SHA-256",n);return Array.from(new Uint8Array(r)).map(o=>o.toString(16).padStart(2,"0")).join("")}static async encryptFileWithDerivedKey(t,n){let r=await t.arrayBuffer(),o=await this.sha256Hex(r),a=crypto.getRandomValues(new Uint8Array(12)),i=await crypto.subtle.encrypt({name:"AES-GCM",iv:a,tagLength:128},n,r),s=JSON.stringify({name:t.name,type:t.type,size:t.size,lastModified:t.lastModified}),c=crypto.getRandomValues(new Uint8Array(12)),d=await crypto.subtle.encrypt({name:"AES-GCM",iv:c,tagLength:128},n,new TextEncoder().encode(s));return{encrypted_file:this.arrayBufferToBase64(i),iv:this.arrayBufferToBase64(a),encrypted_metadata:this.arrayBufferToBase64(d),metadata_iv:this.arrayBufferToBase64(c),encrypted_size:i.byteLength,plaintext_sha256:o,ciphertext_sha256:await this.sha256Hex(i)}}static async decryptFileBytesWithDerivedKey(t,n,r){let o=this.base64ToArrayBuffer(n);return crypto.subtle.decrypt({name:"AES-GCM",iv:o,tagLength:128},r,t)}static async decryptFileWithDerivedKey(t,n,r){let o=this.base64ToArrayBuffer(t),a=this.base64ToArrayBuffer(n);return crypto.subtle.decrypt({name:"AES-GCM",iv:a,tagLength:128},r,o)}static async deriveSeedKey(t,n="SHA-512"){let r=t.trim().toLowerCase(),o=await crypto.subtle.importKey("raw",new TextEncoder().encode(r),"PBKDF2",!1,["deriveBits","deriveKey"]);return await crypto.subtle.deriveKey({name:"PBKDF2",salt:new TextEncoder().encode(this.SEED_SALT),iterations:this.PBKDF2_ITERATIONS,hash:n},o,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}static async exportKeyWithSeed(t,n){let r=await crypto.subtle.exportKey("jwk",t),o=new TextEncoder().encode(JSON.stringify(r)),a=crypto.getRandomValues(new Uint8Array(12)),i=await crypto.subtle.encrypt({name:"AES-GCM",iv:a,tagLength:128},n,o),s=new Uint8Array(a.byteLength+i.byteLength);return s.set(a,0),s.set(new Uint8Array(i),a.byteLength),s.buffer}static async importKeyWithSeed(t,n){let r=new Uint8Array(t),o=r.slice(0,12),a=r.slice(12),i=await crypto.subtle.decrypt({name:"AES-GCM",iv:o,tagLength:128},n,a),s=new TextDecoder().decode(i),c=JSON.parse(s),d=await crypto.subtle.importKey("jwk",c,{name:"RSA-OAEP",hash:"SHA-256"},!0,["decrypt"]);return new Uint8Array(i).fill(0),d}static async hashPhone(t){let n=new TextEncoder().encode(t.replace(/\D/g,"")),r=await crypto.subtle.digest("SHA-256",n);return Array.from(new Uint8Array(r)).map(o=>o.toString(16).padStart(2,"0")).join("")}static arrayBufferToBase64(t){let n=new Uint8Array(t),r=32768,o=[];for(let a=0;a<n.length;a+=r)o.push(String.fromCharCode(...n.subarray(a,a+r)));return btoa(o.join(""))}static async encryptFileToBytesWithDerivedKey(t,n){let r=await t.arrayBuffer(),o=await this.sha256Hex(r),a=crypto.getRandomValues(new Uint8Array(12)),i=await crypto.subtle.encrypt({name:"AES-GCM",iv:a,tagLength:128},n,r),s=JSON.stringify({name:t.name,type:t.type,size:t.size,lastModified:t.lastModified}),c=crypto.getRandomValues(new Uint8Array(12)),d=await crypto.subtle.encrypt({name:"AES-GCM",iv:c,tagLength:128},n,new TextEncoder().encode(s));return{ciphertext:i,iv:this.arrayBufferToBase64(a),encrypted_metadata:this.arrayBufferToBase64(d),metadata_iv:this.arrayBufferToBase64(c),encrypted_size:i.byteLength,plaintext_sha256:o,ciphertext_sha256:await this.sha256Hex(i)}}static base64ToArrayBuffer(t){let n=atob(t),r=new Uint8Array(n.length);for(let o=0;o<n.length;o++)r[o]=n.charCodeAt(o);return r.buffer}static wipeFromMemory(t){new Uint8Array(t).fill(0)}};_t.PBKDF2_ITERATIONS=31e4;_t.SEED_SALT="NoDataChat-Seed-v1";Zn.default=_t});var Ro=C(Wt=>{"use strict";Object.defineProperty(Wt,"__esModule",{value:!0});Wt.solveProofOfWork=Dc;Wt.verifyProofOfWork=Nc;function Pc(e){let t=new Uint8Array(e),n="";for(let r=0;r<t.length;r++)n+=t[r].toString(16).padStart(2,"0");return n}async function $o(e){let t=new TextEncoder().encode(e),n=await crypto.subtle.digest("SHA-256",t);return Pc(n)}async function Dc(e,t=4){if(t<1||t>16)throw new Error("Difficulty must be between 1 and 16");let n="0".repeat(t),r=0;for(;;){let o=e+r.toString(),a=await $o(o);if(a.startsWith(n))return{nonce:r,hash:a};if(r++,r>2e9)throw new Error("Proof of work exceeded maximum attempts")}}async function Nc(e,t,n=4){if(n<1||n>16)return!1;let r="0".repeat(n),o=e+t.toString();return(await $o(o)).startsWith(r)}});var er=C(qe=>{"use strict";var Oc=qe&&qe.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(qe,"__esModule",{value:!0});qe.NoDataEmail=void 0;var se=Oc($e()),Qn=class{static async seal(t,n,r,o,a,i={}){let{encrypt_subject:s=!0,ttl_hours:c=72,attachments:d=[]}=i,u=await se.default.encryptMessage(o,a),p=r,f=!1;if(s){let _=await se.default.encryptMessage(r,a);p=JSON.stringify(_),f=!0}let y=[];for(let _ of d){let k=await se.default.encryptFile(_,a);y.push({encrypted_file:k})}return{from_alias:t,to:n,subject:p,subject_encrypted:f,body:u,attachments:y,sealed_at:new Date().toISOString(),ttl_hours:c,envelope_id:crypto.randomUUID(),crypto_version:"0.2.0"}}static async open(t,n){let r=await se.default.decryptMessage(t.body,n),o=t.subject;if(t.subject_encrypted){let i=JSON.parse(t.subject);o=await se.default.decryptMessage(i,n)}let a=[];for(let i of t.attachments){let{encrypted_file:s}=i,c=se.default.base64ToArrayBuffer(s.metadata_iv),d=se.default.base64ToArrayBuffer(s.encrypted_metadata),u=se.default.base64ToArrayBuffer(s.encrypted_file_key),p=await crypto.subtle.importKey("jwk",n,{name:"RSA-OAEP",hash:"SHA-256"},!1,["decrypt"]),f=await crypto.subtle.decrypt({name:"RSA-OAEP"},p,u),y=await crypto.subtle.importKey("raw",f,{name:"AES-GCM",length:256},!1,["decrypt"]),_=await crypto.subtle.decrypt({name:"AES-GCM",iv:c,tagLength:128},y,d),k=JSON.parse(new TextDecoder().decode(_)),b=se.default.base64ToArrayBuffer(s.iv),S=se.default.base64ToArrayBuffer(s.encrypted_file),v=await crypto.subtle.decrypt({name:"AES-GCM",iv:b,tagLength:128},y,S);a.push({filename:k.name,mime_type:k.type,data:v,size:k.size})}return{subject:o,body:r,attachments:a,sealed_at:t.sealed_at,ttl_hours:t.ttl_hours,envelope_id:t.envelope_id}}static isExpired(t){let r=new Date(t.sealed_at).getTime()+t.ttl_hours*60*60*1e3;return Date.now()>r}static toMimeBody(t,n){let r=JSON.stringify(t),o=btoa(unescape(encodeURIComponent(r)));return['Content-Type: multipart/mixed; boundary="nodata-boundary"',"","--nodata-boundary","Content-Type: text/html; charset=utf-8","",'<div style="font-family:system-ui;padding:24px;text-align:center">',"<h2>This email is encrypted with Capsule</h2>","<p>The sender used end-to-end encryption. To read this message:</p>",`<a href="${n}?env=${t.envelope_id}" `,'style="display:inline-block;padding:12px 24px;background:#000;color:#fff;','border-radius:8px;text-decoration:none;font-weight:600">',"Open Encrypted Email</a>",'<p style="color:#888;font-size:12px;margin-top:16px">',"Powered by Capsule &mdash; Nothing is ever stored. Ever.</p>","</div>","--nodata-boundary",'Content-Type: application/x-nodata-envelope; name="envelope.nodata"',"Content-Transfer-Encoding: base64",'Content-Disposition: attachment; filename="envelope.nodata"',"",o,"--nodata-boundary--"].join(`\r
8
+ `)}};qe.NoDataEmail=Qn});var rr=C(We=>{"use strict";var Cc=We&&We.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(We,"__esModule",{value:!0});We.NoDataWebhook=void 0;var tr=Cc($e()),nr=class{static async encrypt(t,n,r,o){let{event_type:a,source:i,ttl_seconds:s=3600}=o,c=JSON.stringify(t),d=await tr.default.encryptMessage(c,n),u=new Date().toISOString(),p=crypto.randomUUID(),f=`${p}.${u}.${d.encrypted_blob}`,y=await this.hmacSign(f,r);return{encrypted_event:d,event_type:a,source:i,signature:y,timestamp:u,delivery_id:p,ttl_seconds:s,crypto_version:"0.2.0"}}static async verify(t,n){let r=`${t.delivery_id}.${t.timestamp}.${t.encrypted_event.encrypted_blob}`,o=await this.hmacSign(r,n),a=new TextEncoder().encode(t.signature),i=new TextEncoder().encode(o),s=a.length^i.length,c=Math.min(a.length,i.length);for(let y=0;y<c;y++)s|=a[y]^i[y];let d=s===0,p=new Date(t.timestamp).getTime()+t.ttl_seconds*1e3,f=Date.now()>p;return{valid:d,expired:f,event_type:t.event_type,source:t.source,delivery_id:t.delivery_id}}static async decrypt(t,n){let r=await tr.default.decryptMessage(t.encrypted_event,n);return JSON.parse(r)}static async verifyAndDecrypt(t,n,r){let o=await this.verify(t,r);if(!o.valid)throw new Error(`[NoDataWebhook] Invalid signature for delivery ${o.delivery_id}`);if(o.expired)throw new Error(`[NoDataWebhook] Payload expired for delivery ${o.delivery_id}`);return{data:await this.decrypt(t,n),delivery_id:o.delivery_id,event_type:o.event_type}}static async hmacSign(t,n){let r=await crypto.subtle.importKey("raw",new TextEncoder().encode(n),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),o=await crypto.subtle.sign("HMAC",r,new TextEncoder().encode(t));return tr.default.arrayBufferToBase64(o)}};We.NoDataWebhook=nr});var ar=C(Je=>{"use strict";var Ic=Je&&Je.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(Je,"__esModule",{value:!0});Je.NoDataSystems=void 0;var Jt=Ic($e()),or=class{static async encryptRecord(t,n,r,o,a,i){let s=[],c={};for(let[d,u]of Object.entries(r))if(o.sensitive.includes(d)){let p=typeof u=="string"?u:JSON.stringify(u),f=await Jt.default.encryptMessage(p,a),y=await this.hashValue(p);s.push({value:f,search_hash:y,field_name:d,encrypted_at:new Date().toISOString()})}else c[d]=u;return{record_id:t,record_type:n,encrypted_fields:s,clear_fields:c,encrypted_by:i,created_at:new Date().toISOString(),crypto_version:"0.2.0"}}static async decryptRecord(t,n){let r={...t.clear_fields};for(let o of t.encrypted_fields){let a=await Jt.default.decryptMessage(o.value,n);try{r[o.field_name]=JSON.parse(a)}catch{r[o.field_name]=a}}return{record_id:t.record_id,record_type:t.record_type,fields:r,created_at:t.created_at}}static async searchByHash(t,n,r){let o=await this.hashValue(r);return t.filter(a=>a.encrypted_fields.some(i=>i.field_name===n&&i.search_hash===o))}static async encryptField(t,n,r){let o=typeof n=="string"?n:JSON.stringify(n),a=await Jt.default.encryptMessage(o,r),i=await this.hashValue(o);return{value:a,search_hash:i,field_name:t,encrypted_at:new Date().toISOString()}}static async decryptField(t,n){let r=await Jt.default.decryptMessage(t.value,n);try{return JSON.parse(r)}catch{return r}}static createSchema(t,n){return{sensitive:n,clear:t.filter(r=>!n.includes(r))}}static async hashValue(t){let n=`nodatachat:field:${t}`,r=new TextEncoder().encode(n),o=await crypto.subtle.digest("SHA-256",r);return Array.from(new Uint8Array(o)).map(a=>a.toString(16).padStart(2,"0")).join("")}};Je.NoDataSystems=or});var sr=C(ze=>{"use strict";var $c=ze&&ze.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(ze,"__esModule",{value:!0});ze.NoDataForms=void 0;var ce=$c($e()),ir=class{static async encryptSubmission(t,n,r,o,a={}){let{ttl_hours:i=0,view_once:s=!1,attachments:c=[]}=a,d={},u={};for(let b of n)b.sensitive!==!1?d[b.name]=b.value:u[b.name]=b.value;let p=JSON.stringify(n.map(b=>({name:b.name,value:b.value}))),f=await this.sha256(p),y=await ce.default.encryptMessage(JSON.stringify(d),r),_=[];for(let b of c){let S=await ce.default.encryptFile(b,r);_.push(S)}let k=n.map(b=>b.name);return{submission_id:crypto.randomUUID(),form_id:t,encrypted_fields:y,clear_fields:u,attachments:_,integrity_hash:f,field_order:k,submitter_id:o,submitted_at:new Date().toISOString(),ttl_hours:i,view_once:s,crypto_version:"0.2.0"}}static async decryptSubmission(t,n){let r=await ce.default.decryptMessage(t.encrypted_fields,n),o=JSON.parse(r),a={...t.clear_fields,...o},s=(t.field_order||Object.keys(a).sort()).map(p=>({name:p,value:a[p]})),d=await this.sha256(JSON.stringify(s))===t.integrity_hash,u=[];for(let p of t.attachments){let f=await crypto.subtle.importKey("jwk",n,{name:"RSA-OAEP",hash:"SHA-256"},!1,["decrypt"]),y=await crypto.subtle.decrypt({name:"RSA-OAEP"},f,ce.default.base64ToArrayBuffer(p.encrypted_file_key)),_=await crypto.subtle.importKey("raw",y,{name:"AES-GCM",length:256},!1,["decrypt"]),k=await crypto.subtle.decrypt({name:"AES-GCM",iv:ce.default.base64ToArrayBuffer(p.metadata_iv),tagLength:128},_,ce.default.base64ToArrayBuffer(p.encrypted_metadata)),b=JSON.parse(new TextDecoder().decode(k)),S=await crypto.subtle.decrypt({name:"AES-GCM",iv:ce.default.base64ToArrayBuffer(p.iv),tagLength:128},_,ce.default.base64ToArrayBuffer(p.encrypted_file));u.push({filename:b.name,mime_type:b.type,data:S,size:b.size})}return{submission_id:t.submission_id,form_id:t.form_id,fields:a,attachments:u,integrity_valid:d,submitted_at:t.submitted_at}}static isExpired(t){if(t.ttl_hours===0)return!1;let r=new Date(t.submitted_at).getTime()+t.ttl_hours*60*60*1e3;return Date.now()>r}static async encryptGrade(t,n,r,o,a=0){let i=await ce.default.encryptMessage(JSON.stringify(t),n),s=await this.sha256(`nodatachat:student:${t.student_id}`);return{encrypted_grade:i,student_hash:s,course_id:r,term:o,delivery_id:crypto.randomUUID(),delivered_at:new Date().toISOString(),ttl_hours:a,crypto_version:"0.2.0"}}static async decryptGrade(t,n){let r=await ce.default.decryptMessage(t.encrypted_grade,n);return JSON.parse(r)}static async sha256(t){let n=new TextEncoder().encode(t),r=await crypto.subtle.digest("SHA-256",n);return Array.from(new Uint8Array(r)).map(o=>o.toString(16).padStart(2,"0")).join("")}};ze.NoDataForms=ir});var Bo=C(Ye=>{"use strict";var Rc=Ye&&Ye.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(Ye,"__esModule",{value:!0});Ye.NoDataSDK=void 0;var zt=Rc($e()),be=er(),Se=rr(),Q=ar(),le=sr(),cr=class{static async init(t={}){let n;return t.keyPair?n=t.keyPair:(n=await zt.default.generateKeyPair(),t.onKeysGenerated&&await t.onKeysGenerated(n)),{publicKey:n.publicKeyJwk,email:{seal:be.NoDataEmail.seal.bind(be.NoDataEmail),open:be.NoDataEmail.open.bind(be.NoDataEmail),isExpired:be.NoDataEmail.isExpired.bind(be.NoDataEmail),toMimeBody:be.NoDataEmail.toMimeBody.bind(be.NoDataEmail)},webhook:{encrypt:Se.NoDataWebhook.encrypt.bind(Se.NoDataWebhook),verify:Se.NoDataWebhook.verify.bind(Se.NoDataWebhook),decrypt:Se.NoDataWebhook.decrypt.bind(Se.NoDataWebhook),verifyAndDecrypt:Se.NoDataWebhook.verifyAndDecrypt.bind(Se.NoDataWebhook)},systems:{encryptRecord:Q.NoDataSystems.encryptRecord.bind(Q.NoDataSystems),decryptRecord:Q.NoDataSystems.decryptRecord.bind(Q.NoDataSystems),searchByHash:Q.NoDataSystems.searchByHash.bind(Q.NoDataSystems),encryptField:Q.NoDataSystems.encryptField.bind(Q.NoDataSystems),decryptField:Q.NoDataSystems.decryptField.bind(Q.NoDataSystems),createSchema:Q.NoDataSystems.createSchema.bind(Q.NoDataSystems)},forms:{encryptSubmission:le.NoDataForms.encryptSubmission.bind(le.NoDataForms),decryptSubmission:le.NoDataForms.decryptSubmission.bind(le.NoDataForms),isExpired:le.NoDataForms.isExpired.bind(le.NoDataForms),encryptGrade:le.NoDataForms.encryptGrade.bind(le.NoDataForms),decryptGrade:le.NoDataForms.decryptGrade.bind(le.NoDataForms)},crypto:zt.default}}static async quickEncrypt(t,n){let r=typeof t=="string"?t:JSON.stringify(t),o=await zt.default.encryptMessage(r,n);return JSON.stringify(o)}static async quickDecrypt(t,n){let r=JSON.parse(t),o=await zt.default.decryptMessage(r,n);try{return JSON.parse(o)}catch{return o}}};Ye.NoDataSDK=cr});var jo=C(ee=>{"use strict";Object.defineProperty(ee,"__esModule",{value:!0});ee.NoDataSDK=ee.NoDataForms=ee.NoDataSystems=ee.NoDataWebhook=ee.NoDataEmail=void 0;var Bc=er();Object.defineProperty(ee,"NoDataEmail",{enumerable:!0,get:function(){return Bc.NoDataEmail}});var jc=rr();Object.defineProperty(ee,"NoDataWebhook",{enumerable:!0,get:function(){return jc.NoDataWebhook}});var Kc=ar();Object.defineProperty(ee,"NoDataSystems",{enumerable:!0,get:function(){return Kc.NoDataSystems}});var Lc=sr();Object.defineProperty(ee,"NoDataForms",{enumerable:!0,get:function(){return Lc.NoDataForms}});var Mc=Bo();Object.defineProperty(ee,"NoDataSDK",{enumerable:!0,get:function(){return Mc.NoDataSDK}})});var Ze=C(D=>{"use strict";Object.defineProperty(D,"__esModule",{value:!0});D.PQ_SIZES=D.NDC_WIRE_V03=D.NDC_WIRE_V1=D.NDC_V03_RATCHET_DOMAIN=D.NDC_V03_CONTENT_KEY_DOMAIN=D.NDC_V03_KEM_DOMAIN=D.PQ_SUITE=void 0;D.generateHybridKemKeypair=Fc;D.deriveHybridKemKeypairFromSeed=Uc;D.hybridKemEncapsulate=Hc;D.hybridKemDecapsulate=Vc;D.deriveContentKey=Gc;D.ratchetAdvance=qc;D.generateHybridSigKeypair=Wc;D.hybridSign=Jc;D.hybridVerify=zc;D.generateMlDsa65Keypair=Yc;D.mlDsa65SignDetached=Xc;D.mlDsa65VerifyDetached=Zc;var we=T("@noble/curves/ed25519.js"),bt=T("@noble/hashes/sha2.js"),St=T("@noble/hashes/hkdf.js"),Yt=T("@noble/post-quantum/ml-kem.js"),Xe=T("@noble/post-quantum/ml-dsa.js");D.PQ_SUITE={KEM:"X25519+ML-KEM-768",SIG:"Ed25519+ML-DSA-65",AEAD:"AES-256-GCM",KDF:"HKDF-SHA-256"};D.NDC_V03_KEM_DOMAIN="NDC-v0.3-hybrid-kem";D.NDC_V03_CONTENT_KEY_DOMAIN="NDC-v0.3-content-key";D.NDC_V03_RATCHET_DOMAIN="NDC-ratchet";D.NDC_WIRE_V1=1;D.NDC_WIRE_V03=2;function Ko(...e){let t=0;for(let o of e)t+=o.length;let n=new Uint8Array(t),r=0;for(let o of e)n.set(o,r),r+=o.length;return n}function wt(e){return new TextEncoder().encode(e)}function Lo(e,t,n,r){let o=Ko(e,t),a=Ko(wt(D.NDC_V03_KEM_DOMAIN),n,r);return(0,St.hkdf)(bt.sha256,o,new Uint8Array(0),a,32)}function Fc(){let{secretKey:e,publicKey:t}=we.x25519.keygen(),{publicKey:n,secretKey:r}=Yt.ml_kem768.keygen();return{publicKey:{x25519:t,mlKem:n},secretKey:{x25519:e,mlKem:r}}}function Uc(e){if(e.length<32)throw new Error("seed too short (need >=32 bytes)");let t=(0,St.hkdf)(bt.sha256,e,new Uint8Array(0),wt("ndc-hybrid-kem-x25519-v1"),32),n=(0,St.hkdf)(bt.sha256,e,new Uint8Array(0),wt("ndc-hybrid-kem-mlkem768-v1"),64),r=we.x25519.getPublicKey(t),{publicKey:o,secretKey:a}=Yt.ml_kem768.keygen(n);return{publicKey:{x25519:r,mlKem:o},secretKey:{x25519:t,mlKem:a}}}function Hc(e){let{secretKey:t,publicKey:n}=we.x25519.keygen(),r=we.x25519.getSharedSecret(t,e.x25519),{cipherText:o,sharedSecret:a}=Yt.ml_kem768.encapsulate(e.mlKem),i=Lo(a,r,n,e.x25519);return{ciphertext:{ctClassical:n,ctPq:o},sharedSecret:i,ephemeralX25519Pk:n}}function Vc(e,t,n){let r=we.x25519.getSharedSecret(e.x25519,n.ctClassical),o=Yt.ml_kem768.decapsulate(n.ctPq,e.mlKem);return Lo(o,r,n.ctClassical,t)}function Gc(e){return(0,St.hkdf)(bt.sha256,e,new Uint8Array(0),wt(D.NDC_V03_CONTENT_KEY_DOMAIN),32)}function qc(e,t){return(0,St.hkdf)(bt.sha256,e,t,wt(D.NDC_V03_RATCHET_DOMAIN),32)}function Wc(){let{secretKey:e,publicKey:t}=we.ed25519.keygen(),{publicKey:n,secretKey:r}=Xe.ml_dsa65.keygen();return{publicKey:{ed25519:t,mlDsa:n},secretKey:{ed25519:e,mlDsa:r}}}function Jc(e,t){return{ed25519:we.ed25519.sign(t,e.ed25519),mlDsa:Xe.ml_dsa65.sign(t,e.mlDsa)}}function zc(e,t,n){return we.ed25519.verify(n.ed25519,t,e.ed25519)?Xe.ml_dsa65.verify(n.mlDsa,t,e.mlDsa):!1}function Yc(){let{publicKey:e,secretKey:t}=Xe.ml_dsa65.keygen();return{publicKey:e,secretKey:t}}function Xc(e,t){return Xe.ml_dsa65.sign(t,e)}function Zc(e,t,n){return Xe.ml_dsa65.verify(n,t,e)}D.PQ_SIZES={X25519_PK:32,X25519_SK:32,ML_KEM_768_PK:1184,ML_KEM_768_SK:2400,ML_KEM_768_CT:1088,ED25519_PK:32,ED25519_SK:32,ED25519_SIG:64,ML_DSA_65_PK:1952,ML_DSA_65_SK:4032,ML_DSA_65_SIG:3309,HYBRID_SHARED_SECRET:32}});var Zt=C(N=>{"use strict";Object.defineProperty(N,"__esModule",{value:!0});N.deriveContentKey=N.ContainerV3Error=N.CONTAINER_HEADER_MAX_BYTES=N.CONTAINER_FIXED_PREFIX_BYTES=N.CONTAINER_MAGIC=void 0;N.canonicalJson=Xt;N.headerSigningBytes=lr;N.signContainerHeader=Ho;N.verifyContainerHeader=Vo;N.encodeContainerV3=Go;N.decodeContainerV3=qo;N.sealHybrid=ol;N.openHybrid=al;var Qc=T("@noble/hashes/hkdf.js"),el=T("@noble/hashes/sha2.js"),K=Ze();Object.defineProperty(N,"deriveContentKey",{enumerable:!0,get:function(){return K.deriveContentKey}});N.CONTAINER_MAGIC=new Uint8Array([78,68,76,66]);N.CONTAINER_FIXED_PREFIX_BYTES=8;N.CONTAINER_HEADER_MAX_BYTES=16777215;var tl="NDC-v0.3-wrap-key",M=class extends Error{constructor(t,n){super(n),this.name="ContainerV3Error",this.code=t}};N.ContainerV3Error=M;var ye=e=>{if(typeof Buffer<"u")return Buffer.from(e).toString("base64");let t="";for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return btoa(t)},Re=e=>{if(typeof Buffer<"u")return new Uint8Array(Buffer.from(e,"base64"));let t=atob(e),n=new Uint8Array(t.length);for(let r=0;r<t.length;r++)n[r]=t.charCodeAt(r);return n},Uo=e=>{let t="";for(let n=0;n<e.length;n++)t+=e[n].toString(16).padStart(2,"0");return t};function Xt(e){if(e===null||typeof e!="object")return JSON.stringify(e);if(Array.isArray(e))return"["+e.map(Xt).join(",")+"]";let t=e;return"{"+Object.keys(t).sort().map(r=>JSON.stringify(r)+":"+Xt(t[r])).join(",")+"}"}function lr(e){let t={...e};return delete t.sig,new TextEncoder().encode(Xt(t))}function Ho(e,t,n){let r=(0,K.hybridSign)(n.secretKey,lr(e));return{...e,sig:{signer_kid:t,ed25519:ye(r.ed25519),ml_dsa_65:ye(r.mlDsa)}}}function Vo(e,t){let n={ed25519:Re(e.sig.ed25519),mlDsa:Re(e.sig.ml_dsa_65)};return(0,K.hybridVerify)(t,lr(e),n)}var nl=["lockbox_id","format_version","profile","suite","server","kem","wrapped_content_key","iv","tag","bearer","dpop_required","ciphertext_sha256","issued_at","cache_ttl_seconds","original_filename","original_content_type","sig"];function rl(e){if(!e||typeof e!="object")throw new M("header_schema_mismatch","header is not an object");let t=e;for(let r of nl)if(t[r]===void 0)throw new M("header_schema_mismatch",`header missing required field: ${String(r)}`);if(t.format_version!==3)throw new M("unsupported_version",`format_version ${t.format_version} unknown`);if(t.profile!=="pq-hybrid")throw new M("suite_unknown",`profile must be 'pq-hybrid', got '${String(t.profile)}'`);let n=t.suite;if(n.kem!==K.PQ_SUITE.KEM||n.sig!==K.PQ_SUITE.SIG||n.aead!==K.PQ_SUITE.AEAD||n.kdf!==K.PQ_SUITE.KDF)throw new M("suite_unknown",`suite mismatch: viewer supports ${JSON.stringify(K.PQ_SUITE)}, header has ${JSON.stringify(n)}`)}function Go(e,t){let n=new TextEncoder().encode(JSON.stringify(e));if(n.length>N.CONTAINER_HEADER_MAX_BYTES)throw new M("header_schema_mismatch",`header too large (${n.length} bytes; max 16 MB)`);let r=new Uint8Array(N.CONTAINER_FIXED_PREFIX_BYTES+n.length+t.length);return r.set(N.CONTAINER_MAGIC,0),r[4]=K.NDC_WIRE_V03,r[5]=n.length>>16&255,r[6]=n.length>>8&255,r[7]=n.length&255,r.set(n,N.CONTAINER_FIXED_PREFIX_BYTES),r.set(t,N.CONTAINER_FIXED_PREFIX_BYTES+n.length),r}function qo(e){if(e.length<N.CONTAINER_FIXED_PREFIX_BYTES)throw new M("header_truncated",`container truncated: ${e.length} bytes (need \u2265 ${N.CONTAINER_FIXED_PREFIX_BYTES})`);for(let o=0;o<4;o++)if(e[o]!==N.CONTAINER_MAGIC[o])throw new M("bad_magic",`bad magic: expected NDLB, got ${Uo(e.slice(0,4))}`);if(e[4]!==K.NDC_WIRE_V03)throw new M("unsupported_version",`expected wire version 0x${K.NDC_WIRE_V03.toString(16)}, got 0x${e[4].toString(16)}`);let t=e[5]<<16|e[6]<<8|e[7],n=N.CONTAINER_FIXED_PREFIX_BYTES+t;if(e.length<n)throw new M("header_truncated",`header truncated: declared ${t}, only ${e.length-N.CONTAINER_FIXED_PREFIX_BYTES} bytes left`);let r;try{r=JSON.parse(new TextDecoder("utf-8").decode(e.slice(N.CONTAINER_FIXED_PREFIX_BYTES,n)))}catch(o){throw new M("header_invalid_json",`header JSON parse failed: ${o.message}`)}return rl(r),{header:r,ciphertextWithTag:e.slice(n)}}var Be=e=>e;async function Mo(e,t,n){let r=await crypto.subtle.importKey("raw",Be(e),{name:"AES-GCM"},!1,["encrypt"]),o=await crypto.subtle.encrypt({name:"AES-GCM",iv:Be(t)},r,Be(n));return new Uint8Array(o)}async function Fo(e,t,n){let r=await crypto.subtle.importKey("raw",Be(e),{name:"AES-GCM"},!1,["decrypt"]),o=await crypto.subtle.decrypt({name:"AES-GCM",iv:Be(t)},r,Be(n));return new Uint8Array(o)}function Wo(e){return(0,Qc.hkdf)(el.sha256,e,new Uint8Array(0),new TextEncoder().encode(tl),32)}async function Jo(e){let t=await crypto.subtle.digest("SHA-256",Be(e));return Uo(new Uint8Array(t))}async function ol(e){let t=crypto.getRandomValues(new Uint8Array(32)),n=crypto.getRandomValues(new Uint8Array(12)),r=await Mo(t,n,e.plaintext),o=r.slice(r.length-16),a=r.slice(0,r.length-16),i=(0,K.hybridKemEncapsulate)(e.recipientPublicKey),s=Wo(i.sharedSecret),c=crypto.getRandomValues(new Uint8Array(12)),d=await Mo(s,c,t),u=await Jo(a),p={lockbox_id:e.meta.lockbox_id,format_version:3,profile:"pq-hybrid",suite:{kem:K.PQ_SUITE.KEM,sig:K.PQ_SUITE.SIG,aead:K.PQ_SUITE.AEAD,kdf:K.PQ_SUITE.KDF},server:e.meta.server,kem:{recipient_kid:e.recipientKid,ct_classical:ye(i.ciphertext.ctClassical),ct_pq:ye(i.ciphertext.ctPq),ephemeral_x25519_pk:ye(i.ephemeralX25519Pk)},wrapped_content_key:{wrapped:ye(d),wrap_iv:ye(c)},iv:ye(n),tag:ye(o),bearer:e.meta.bearer,dpop_required:e.meta.dpop_required,ratchet_state:e.meta.ratchet_state,tee_attestation_url:e.meta.tee_attestation_url,original_filename:e.meta.original_filename,original_content_type:e.meta.original_content_type,ciphertext_sha256:u,issued_at:new Date().toISOString(),cache_ttl_seconds:e.meta.cache_ttl_seconds},f=Ho(p,e.signerKid,e.signerKeypair),y=Go(f,r);return t.fill(0),{container:y,header:f,serverState:{lockbox_id:e.meta.lockbox_id,kem_ct_classical_b64:f.kem.ct_classical,kem_ct_pq_b64:f.kem.ct_pq,wrapped_content_key_b64:f.wrapped_content_key.wrapped,wrap_iv_b64:f.wrapped_content_key.wrap_iv}}}async function al(e){let{header:t,ciphertextWithTag:n}=qo(e.container);if(!Vo(t,e.signerPublicKey))throw new M("signature_invalid","hybrid signature verification failed");let r=n.slice(0,n.length-16),o=await Jo(r);if(o!==t.ciphertext_sha256)throw new M("integrity_mismatch",`ciphertext sha256 mismatch: expected ${t.ciphertext_sha256.slice(0,16)}\u2026, got ${o.slice(0,16)}\u2026`);let a={ctClassical:Re(t.kem.ct_classical),ctPq:Re(t.kem.ct_pq)},i=(0,K.hybridKemDecapsulate)(e.recipientSecretKey,e.recipientPublicX25519,a),s=Wo(i),c=Re(t.wrapped_content_key.wrapped),d=Re(t.wrapped_content_key.wrap_iv),u=await Fo(s,d,c),p=Re(t.iv),f=await Fo(u,p,n);return u.fill(0),{plaintext:f,header:t}}});var ur=C(et=>{"use strict";Object.defineProperty(et,"__esModule",{value:!0});et.publicJwkFromBytes=Yo;et.jwkThumbprint=Xo;et.createDpop=sl;et.verifyDpop=ll;var zo=T("@noble/curves/ed25519.js"),il=T("@noble/hashes/sha2.js"),Qe=e=>{if(typeof Buffer<"u")return Buffer.from(e).toString("base64").replace(/=+$/,"").replace(/\+/g,"-").replace(/\//g,"_");let t="";for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return btoa(t).replace(/=+$/,"").replace(/\+/g,"-").replace(/\//g,"_")},Qt=e=>{let t=e.replace(/-/g,"+").replace(/_/g,"/"),n=t.length%4?4-t.length%4:0,r=t+"=".repeat(n);if(typeof Buffer<"u")return new Uint8Array(Buffer.from(r,"base64"));let o=atob(r),a=new Uint8Array(o.length);for(let i=0;i<o.length;i++)a[i]=o.charCodeAt(i);return a},vt=e=>new TextEncoder().encode(e);function Yo(e){if(e.length!==32)throw new Error(`expected 32-byte Ed25519 public key, got ${e.length}`);return{kty:"OKP",crv:"Ed25519",x:Qe(e)}}function Xo(e){let t=`{"crv":"${e.crv}","kty":"${e.kty}","x":"${e.x}"}`,n=(0,il.sha256)(vt(t));return Qe(n)}function sl(e){let n={typ:"dpop+jwt",alg:"EdDSA",jwk:Yo(e.publicKey)},r={htm:e.htm.toUpperCase(),htu:dr(e.htu),jti:e.jti??cl(),iat:e.iat??Math.floor(Date.now()/1e3)};e.nonce&&(r.nonce=e.nonce);let o=Qe(vt(JSON.stringify(n))),a=Qe(vt(JSON.stringify(r))),i=`${o}.${a}`,s=zo.ed25519.sign(vt(i),e.secretKey);return`${i}.${Qe(s)}`}function cl(){return Qe(crypto.getRandomValues(new Uint8Array(16)))}function dr(e){try{let t=new URL(e);return`${t.protocol}//${t.host}${t.pathname}`}catch{return e}}async function ll(e,t){let n=e.split(".");if(n.length!==3)return F("malformed","expected three JWT parts");let[r,o,a]=n,i;try{i=JSON.parse(new TextDecoder().decode(Qt(r)))}catch{return F("bad_header","header is not valid base64url JSON")}if(i.typ!=="dpop+jwt")return F("bad_typ",`typ must be 'dpop+jwt', got '${String(i.typ)}'`);if(i.alg!=="EdDSA")return F("bad_alg",`alg must be 'EdDSA', got '${String(i.alg)}'`);if(!i.jwk||i.jwk.kty!=="OKP"||i.jwk.crv!=="Ed25519")return F("bad_header","jwk must be an Ed25519 OKP key");let s=Xo(i.jwk);if(s!==t.expectedJkt)return F("jkt_mismatch",`jkt does not match registered key: expected ${t.expectedJkt.slice(0,12)}\u2026, got ${s.slice(0,12)}\u2026`);let c;try{c=JSON.parse(new TextDecoder().decode(Qt(o)))}catch{return F("bad_payload","payload is not valid base64url JSON")}if(c.htm!==t.expectedHtm.toUpperCase())return F("htm_mismatch",`htm '${c.htm}' \u2260 expected '${t.expectedHtm.toUpperCase()}'`);if(c.htu!==dr(t.expectedHtu))return F("htu_mismatch",`htu '${c.htu}' \u2260 expected '${dr(t.expectedHtu)}'`);if(t.expectedNonce!==void 0&&c.nonce!==t.expectedNonce)return F("nonce_mismatch","DPoP nonce does not match server-issued nonce");let d=Math.floor(Date.now()/1e3),u=t.maxAgeSeconds??30;if(typeof c.iat!="number")return F("bad_payload","iat missing or not a number");if(c.iat>d+5)return F("iat_in_future",`iat ${c.iat} > now+skew`);if(d-c.iat>u)return F("iat_too_old",`iat ${c.iat} older than ${u}s`);let p;try{p=Qt(i.jwk.x)}catch{return F("bad_header","jwk.x is not base64url")}let f=Qt(a),y=vt(`${r}.${o}`);return zo.ed25519.verify(f,y,p)?await t.isJtiFresh(c.jti)?{ok:!0,jti:c.jti,iat:c.iat}:F("replay",`jti ${c.jti} was already seen`):F("signature_invalid","Ed25519 signature does not verify")}function F(e,t){return{ok:!1,code:e,reason:t}}});var oa=C(w=>{"use strict";Object.defineProperty(w,"__esModule",{value:!0});w.ABSORB_STATUS=w.DELTA_KIND=w.RCPT_TOTAL_LEN=w.RCPT_SIGNED_LEN=w.PVE_TOTAL_LEN=w.PVE_SIGNED_LEN=w.RCPT_VERSION=w.PVE_VERSION=w.RCPT_MAGIC=w.PVE_MAGIC=void 0;w.deltaIdFromUuid=fl;w.uuidFromDeltaId=hl;w.originJktForPublicKey=Et;w.encodePveSignedBytes=ea;w.signPve=yl;w.parsePve=ta;w.pveHash=ml;w.verifyPve=gl;w.encodeReceiptSignedBytes=na;w.signReceipt=_l;w.parseReceipt=ra;w.verifyReceipt=bl;var en=T("@noble/curves/ed25519.js"),dl=T("@noble/hashes/sha2.js"),Zo=ur();w.PVE_MAGIC=new Uint8Array([80,86,69,49]);w.RCPT_MAGIC=new Uint8Array([82,67,86,49]);w.PVE_VERSION=1;w.RCPT_VERSION=1;w.PVE_SIGNED_LEN=160;w.PVE_TOTAL_LEN=w.PVE_SIGNED_LEN+64;w.RCPT_SIGNED_LEN=78;w.RCPT_TOTAL_LEN=w.RCPT_SIGNED_LEN+64;var Qo=new Uint8Array(32);w.DELTA_KIND={relay:1,ndc:2,v4section:3,chatmsg:4};w.ABSORB_STATUS={decrypted_ok:1,verified_only:2,denied:3};function ul(e){if(typeof Buffer<"u")return Buffer.from(e).toString("base64").replace(/=+$/,"").replace(/\+/g,"-").replace(/\//g,"_");let t="";for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return btoa(t).replace(/=+$/,"").replace(/\+/g,"-").replace(/\//g,"_")}function pl(e){let t=e.replace(/-/g,"+").replace(/_/g,"/"),n=t.length%4?4-t.length%4:0,r=t+"=".repeat(n);if(typeof Buffer<"u")return new Uint8Array(Buffer.from(r,"base64"));let o=atob(r),a=new Uint8Array(o.length);for(let i=0;i<o.length;i++)a[i]=o.charCodeAt(i);return a}function hr(e,t){if(e.length!==t.length)return!1;let n=0;for(let r=0;r<e.length;r++)n|=e[r]^t[r];return n===0}function kt(e){for(let t=0;t<e.length;t++)if(e[t]!==0)return!1;return!0}function pr(e){if(e==null)return Qo;if(e instanceof Uint8Array){if(e.length!==32)throw new Error(`jkt bytes must be 32, got ${e.length}`);return e}let t=pl(e);if(t.length!==32)throw new Error(`jkt must decode to 32 bytes, got ${t.length}`);return t}function fr(e){return kt(e)?null:ul(e)}function fl(e){let t=e.replace(/-/g,"");if(t.length!==32)throw new Error(`expected a 16-byte UUID, got '${e}'`);let n=new Uint8Array(16);for(let r=0;r<16;r++)n[r]=parseInt(t.slice(r*2,r*2+2),16);return n}function hl(e){if(e.length!==16)throw new Error(`expected 16 bytes, got ${e.length}`);let t=Array.from(e,n=>n.toString(16).padStart(2,"0")).join("");return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}function Et(e){return(0,Zo.jwkThumbprint)((0,Zo.publicJwkFromBytes)(e))}function ea(e){if(e.deltaId.length!==16)throw new Error("delta_id must be 16 bytes");if(e.ciphertextSha256.length!==32)throw new Error("ciphertext_sha256 must be 32 bytes");if(e.classification<0||e.classification>65535)throw new Error("classification must fit in uint16");let t=new Uint8Array(w.PVE_SIGNED_LEN),n=new DataView(t.buffer),r=0;return t.set(w.PVE_MAGIC,r),r+=4,t[r]=w.PVE_VERSION,r+=1,t[r]=e.deltaKind,r+=1,t.set(e.deltaId,r),r+=16,t.set(e.ciphertextSha256,r),r+=32,t.set(pr(e.originJkt),r),r+=32,t.set(pr(e.destJkt??null),r),r+=32,t.set(e.prevDeltaHash??Qo,r),r+=32,n.setUint16(r,e.classification,!1),r+=2,n.setBigUint64(r,BigInt(e.issuedAt),!1),r+=8,t}function yl(e,t){let n=Et(e.originPublicKey),r=ea({deltaKind:e.deltaKind,deltaId:e.deltaId,ciphertextSha256:e.ciphertextSha256,originJkt:n,destJkt:e.destJkt??null,prevDeltaHash:e.prevDeltaHash??null,classification:e.classification,issuedAt:e.issuedAt??Date.now()}),o=en.ed25519.sign(r,t),a=new Uint8Array(w.PVE_TOTAL_LEN);return a.set(r,0),a.set(o,w.PVE_SIGNED_LEN),a}function ta(e){if(e.length!==w.PVE_TOTAL_LEN)throw new Error(`PVE must be ${w.PVE_TOTAL_LEN} bytes, got ${e.length}`);if(!hr(e.subarray(0,4),w.PVE_MAGIC))throw new Error("bad PVE magic");let t=new DataView(e.buffer,e.byteOffset,e.byteLength),n=4,r=e[n];n+=1;let o=e[n];n+=1;let a=e.slice(n,n+16);n+=16;let i=e.slice(n,n+32);n+=32;let s=e.slice(n,n+32);n+=32;let c=e.slice(n,n+32);n+=32;let d=e.slice(n,n+32);n+=32;let u=t.getUint16(n,!1);n+=2;let p=Number(t.getBigUint64(n,!1));n+=8;let f=e.slice(0,w.PVE_SIGNED_LEN),y=e.slice(w.PVE_SIGNED_LEN,w.PVE_TOTAL_LEN),_=fr(s);if(_===null)throw new Error("origin_jkt must not be zero");return{fields:{version:r,deltaKind:o,deltaId:a,ciphertextSha256:i,originJkt:_,destJkt:fr(c),prevDeltaHash:kt(d)?null:d,classification:u,issuedAt:p},signedBytes:f,originSig:y,broadcast:kt(c),genesis:kt(d)}}function ml(e){return(0,dl.sha256)(e)}function gl(e,t){let n;try{n=ta(e)}catch(o){let a=o instanceof Error?o.message:String(o);return a.includes("magic")?{ok:!1,code:"bad_magic",reason:a}:{ok:!1,code:"malformed",reason:a}}if(n.fields.version!==w.PVE_VERSION)return{ok:!1,code:"bad_version",reason:`unsupported PVE version ${n.fields.version}`};let r;try{r=Et(t)}catch(o){return{ok:!1,code:"malformed",reason:o instanceof Error?o.message:String(o)}}return r!==n.fields.originJkt?{ok:!1,code:"jkt_mismatch",reason:`presented key thumbprint ${r.slice(0,12)}\u2026 \u2260 committed origin_jkt ${n.fields.originJkt.slice(0,12)}\u2026`}:en.ed25519.verify(n.originSig,n.signedBytes,t)?{ok:!0,parsed:n}:{ok:!1,code:"signature_invalid",reason:"Ed25519 origin signature does not verify"}}function na(e){if(e.pveHash.length!==32)throw new Error("pve_hash must be 32 bytes");let t=pr(e.destJkt);if(kt(t))throw new Error("receipt dest_jkt must not be zero");let n=new Uint8Array(w.RCPT_SIGNED_LEN),r=new DataView(n.buffer),o=0;return n.set(w.RCPT_MAGIC,o),o+=4,n[o]=w.RCPT_VERSION,o+=1,n.set(e.pveHash,o),o+=32,n.set(t,o),o+=32,n[o]=e.absorbStatus,o+=1,r.setBigUint64(o,BigInt(e.absorbedAt),!1),o+=8,n}function _l(e,t){let n=Et(e.destPublicKey),r=na({pveHash:e.pveHash,destJkt:n,absorbStatus:e.absorbStatus,absorbedAt:e.absorbedAt??Date.now()}),o=en.ed25519.sign(r,t),a=new Uint8Array(w.RCPT_TOTAL_LEN);return a.set(r,0),a.set(o,w.RCPT_SIGNED_LEN),a}function ra(e){if(e.length!==w.RCPT_TOTAL_LEN)throw new Error(`receipt must be ${w.RCPT_TOTAL_LEN} bytes, got ${e.length}`);if(!hr(e.subarray(0,4),w.RCPT_MAGIC))throw new Error("bad receipt magic");let t=new DataView(e.buffer,e.byteOffset,e.byteLength),n=4,r=e[n];n+=1;let o=e.slice(n,n+32);n+=32;let a=e.slice(n,n+32);n+=32;let i=e[n];n+=1;let s=Number(t.getBigUint64(n,!1));n+=8;let c=fr(a);if(c===null)throw new Error("receipt dest_jkt must not be zero");return{fields:{version:r,pveHash:o,destJkt:c,absorbStatus:i,absorbedAt:s},signedBytes:e.slice(0,w.RCPT_SIGNED_LEN),destSig:e.slice(w.RCPT_SIGNED_LEN,w.RCPT_TOTAL_LEN)}}function bl(e,t,n){let r;try{r=ra(e)}catch(a){let i=a instanceof Error?a.message:String(a);return i.includes("magic")?{ok:!1,code:"bad_magic",reason:i}:{ok:!1,code:"malformed",reason:i}}if(r.fields.version!==w.RCPT_VERSION)return{ok:!1,code:"bad_version",reason:`unsupported receipt version ${r.fields.version}`};let o;try{o=Et(t)}catch(a){return{ok:!1,code:"malformed",reason:a instanceof Error?a.message:String(a)}}return o!==r.fields.destJkt?{ok:!1,code:"jkt_mismatch",reason:`presented key thumbprint ${o.slice(0,12)}\u2026 \u2260 committed dest_jkt ${r.fields.destJkt.slice(0,12)}\u2026`}:n!==void 0&&!hr(n,r.fields.pveHash)?{ok:!1,code:"pve_hash_mismatch",reason:"receipt does not acknowledge the expected PVE"}:en.ed25519.verify(r.destSig,r.signedBytes,t)?{ok:!0,parsed:r}:{ok:!1,code:"signature_invalid",reason:"Ed25519 destination signature does not verify"}}});var ia=C(xt=>{"use strict";Object.defineProperty(xt,"__esModule",{value:!0});xt.stepRatchet=Sl;xt.replayRatchet=wl;xt.destroyKey=vl;var aa=Ze();function Sl(e,t){if(t.length!==32)throw new Error(`ratchet token must be 32 bytes, got ${t.length}`);return{nextContentKey:(0,aa.ratchetAdvance)(e.contentKey,t),openCount:e.openCount+1}}function wl(e,t){let n=[e],r=e;for(let o of t)r=(0,aa.ratchetAdvance)(r,o),n.push(r);return n}function vl(e){e.fill(0)}});var gr=C(tt=>{"use strict";Object.defineProperty(tt,"__esModule",{value:!0});tt.__coseInternals=void 0;tt.verifyCoseSign1Es384=xl;tt.decodeAttestationPayload=Al;var kl=T("@noble/curves/nist.js"),El=T("@noble/hashes/sha2.js"),yr=class{constructor(t){this.b=t,this.p=0}u8(){if(this.p>=this.b.length)throw new Error("cbor: truncated");return this.b[this.p++]}uN(t){let n=0;for(let r=0;r<t;r++)n=n*256+this.u8();return n}len(t){if(t<24)return t;if(t===24)return this.u8();if(t===25)return this.uN(2);if(t===26)return this.uN(4);if(t===27){let n=this.uN(4),r=this.uN(4);return n*4294967296+r}throw new Error(`cbor: unsupported additional info ${t}`)}read(){let t=this.u8(),n=t>>5,r=t&31;switch(n){case 0:return this.len(r);case 1:return-1-this.len(r);case 2:{let o=this.len(r),a=this.b.subarray(this.p,this.p+o);if(a.length!==o)throw new Error("cbor: bstr truncated");return this.p+=o,a.slice()}case 3:{let o=this.len(r),a=this.b.subarray(this.p,this.p+o);if(a.length!==o)throw new Error("cbor: tstr truncated");return this.p+=o,new TextDecoder("utf-8").decode(a)}case 4:{let o=this.len(r),a=[];for(let i=0;i<o;i++)a.push(this.read());return a}case 5:{let o=this.len(r),a=new Map;for(let i=0;i<o;i++){let s=this.read(),c=this.read();a.set(s,c)}return a}case 6:return this.len(r),this.read();case 7:if(r===20)return!1;if(r===21)return!0;if(r===22||r===23)return null;throw new Error(`cbor: unsupported simple/float ${r}`);default:throw new Error(`cbor: unknown major ${n}`)}}};function mr(e){return new yr(e).read()}function nn(e,t){let n=e<<5;return t<24?Uint8Array.of(n|t):t<=255?Uint8Array.of(n|24,t):t<=65535?Uint8Array.of(n|25,t>>8&255,t&255):Uint8Array.of(n|26,t>>>24&255,t>>16&255,t>>8&255,t&255)}function rn(...e){let t=e.reduce((o,a)=>o+a.length,0),n=new Uint8Array(t),r=0;for(let o of e)n.set(o,r),r+=o.length;return n}function tn(e){return rn(nn(2,e.length),e)}function sa(e){let t=new TextEncoder().encode(e);return rn(nn(3,t.length),t)}function ca(e,t){return rn(nn(4,4),sa("Signature1"),tn(e),tn(new Uint8Array(0)),tn(t))}function xl(e,t){let n;try{n=mr(e)}catch(d){return{ok:!1,code:"malformed",reason:`cbor decode failed: ${d.message}`}}if(!Array.isArray(n)||n.length!==4)return{ok:!1,code:"bad_structure",reason:"COSE_Sign1 must be a 4-element array"};let[r,,o,a]=n;if(!(r instanceof Uint8Array))return{ok:!1,code:"bad_structure",reason:"protected header must be a byte string"};if(!(o instanceof Uint8Array)||o.length===0)return{ok:!1,code:"no_payload",reason:"detached/empty payload is not supported"};if(!(a instanceof Uint8Array))return{ok:!1,code:"bad_structure",reason:"signature must be a byte string"};if(a.length!==96)return{ok:!1,code:"bad_signature_len",reason:`expected 96-byte ES384 sig, got ${a.length}`};let i=ca(r,o),s=(0,El.sha384)(i),c=!1;try{c=kl.p384.verify(a,s,t,{prehash:!1})}catch(d){return{ok:!1,code:"signature_invalid",reason:`verify threw: ${d.message}`}}return c?{ok:!0,payload:o}:{ok:!1,code:"signature_invalid",reason:"ECDSA P-384 verification failed"}}function Al(e){try{let t=mr(e);return t instanceof Map?t:null}catch{return null}}tt.__coseInternals={sig1Structure:ca,encBstr:tn,encText:sa,encHead:nn,concat:rn,decodeCbor:mr}});var la=C(At=>{"use strict";Object.defineProperty(At,"__esModule",{value:!0});At.parseAttestation=Pl;At.verifyAttestation=Dl;At.fetchAttestation=Nl;var Tl=gr();function Pl(e){try{let t=new TextDecoder("utf-8").decode(e),n=JSON.parse(t);return n.vendor?n.module_id?!n.pcrs||typeof n.pcrs!="object"?{error:"missing pcrs"}:typeof n.timestamp!="number"?{error:"missing timestamp"}:typeof n.user_data_sha256!="string"?{error:"missing user_data_sha256"}:{vendor:n.vendor,module_id:n.module_id,pcrs:n.pcrs,timestamp:n.timestamp,user_data_sha256:n.user_data_sha256,raw:e}:{error:"missing module_id"}:{error:"missing vendor"}}catch(t){return{error:`parse failed: ${t.message}`}}}function Dl(e,t){if(e.vendor!==t.vendor)return{ok:!1,code:"vendor_mismatch",reason:`vendor '${e.vendor}' \u2260 expected '${t.vendor}'`};if(e.module_id!==t.module_id)return{ok:!1,code:"module_id_mismatch",reason:`module_id mismatch (got '${e.module_id.slice(0,16)}\u2026')`};for(let[a,i]of Object.entries(t.pcrs))if(e.pcrs[a]!==i)return{ok:!1,code:"pcr_mismatch",reason:`PCR ${a}: got '${(e.pcrs[a]??"").slice(0,16)}\u2026', expected '${i.slice(0,16)}\u2026'`};if(e.user_data_sha256!==t.expected_user_data_sha256)return{ok:!1,code:"user_data_mismatch",reason:"attested user_data does not match presented key"};let n=Math.floor(Date.now()/1e3),r=t.maxAgeSeconds??600;if(e.timestamp>n+30)return{ok:!1,code:"in_future",reason:`attestation timestamp ${e.timestamp} > now+30s`};if(n-e.timestamp>r)return{ok:!1,code:"expired",reason:`attestation ${n-e.timestamp}s old (max ${r}s)`};let o=!1;if(t.cose){if(!t.trustedLeafPubKey)return{ok:!1,code:"signature_invalid",reason:"cose supplied without trustedLeafPubKey \u2014 cannot verify, refusing"};let a=(0,Tl.verifyCoseSign1Es384)(t.cose,t.trustedLeafPubKey);if(!a.ok)return{ok:!1,code:"signature_invalid",reason:`cose: ${a.code}: ${a.reason}`};o=!0}return{ok:!0,vendor:e.vendor,module_id:e.module_id,signature_verified:o}}async function Nl(e){let n=await(e.fetchImpl??fetch)(e.attestationUrl,{method:"GET"});if(!n.ok)throw new Error(`attestation fetch failed: ${n.status} ${n.statusText}`);return new Uint8Array(await n.arrayBuffer())}});var pa=C(nt=>{"use strict";Object.defineProperty(nt,"__esModule",{value:!0});nt.splitSecret=$l;nt.combineShares=Rl;nt.serializeShare=Kl;nt.deserializeShare=Ll;var je=null,Ke=null;function da(){if(je&&Ke)return;je=new Uint8Array(512),Ke=new Uint8Array(256);let e=1;for(let t=0;t<255;t++){je[t]=e,Ke[e]=t;let n=e<<1;n&256&&(n^=283),n^=e,e=n&255}for(let t=255;t<512;t++)je[t]=je[t-255]}function on(e,t){return e===0||t===0?0:(da(),je[Ke[e]+Ke[t]])}function Ol(e,t){if(e===0)return 0;if(t===0)throw new Error("division by zero in GF(2^8)");da();let n=Ke[e]-Ke[t];return je[n<0?n+255:n]}function ua(e,t){return e^t}function Cl(e,t){let n=0;for(let r=e.length-1;r>=0;r--)n=ua(on(n,t),e[r]);return n}var Il=e=>crypto.getRandomValues(new Uint8Array(e));function $l(e,t){if(t.k<2)throw new Error("threshold k must be \u2265 2");if(t.n<t.k)throw new Error(`total shares n (${t.n}) must be \u2265 threshold k (${t.k})`);if(t.n>255)throw new Error("total shares n must be \u2264 255 (limit of GF(2^8))");if(e.length===0)throw new Error("secret must be non-empty");let n=t.randomBytes??Il,r=[];for(let o=1;o<=t.n;o++)r.push({x:o,y:new Uint8Array(e.length)});for(let o=0;o<e.length;o++){let a=new Uint8Array(t.k);a[0]=e[o];let i=n(t.k-1);for(let s=1;s<t.k;s++)a[s]=i[s-1];for(let s=0;s<t.n;s++)r[s].y[o]=Cl(a,r[s].x)}return r}function Rl(e){if(e.length<2)throw new Error("need at least 2 shares to reconstruct");let t=e[0].y.length;for(let o of e){if(o.y.length!==t)throw new Error("shares have inconsistent length");if(o.x===0)throw new Error("share x must not be 0")}let n=new Set;for(let o of e){if(n.has(o.x))throw new Error(`duplicate share x=${o.x}`);n.add(o.x)}let r=new Uint8Array(t);for(let o=0;o<t;o++){let a=0;for(let i=0;i<e.length;i++){let s=1,c=1;for(let u=0;u<e.length;u++)i!==u&&(s=on(s,e[u].x),c=on(c,e[i].x^e[u].x));let d=Ol(s,c);a=ua(a,on(e[i].y[o],d))}r[o]=a}return r}var Bl=e=>{if(typeof Buffer<"u")return Buffer.from(e).toString("base64");let t="";for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return btoa(t)},jl=e=>{if(typeof Buffer<"u")return new Uint8Array(Buffer.from(e,"base64"));let t=atob(e),n=new Uint8Array(t.length);for(let r=0;r<t.length;r++)n[r]=t.charCodeAt(r);return n};function Kl(e){return{x:e.x,y_b64:Bl(e.y)}}function Ll(e){return{x:e.x,y:jl(e.y_b64)}}});var ma=C(ve=>{"use strict";Object.defineProperty(ve,"__esModule",{value:!0});ve.SegmentError=void 0;ve.sealSegments=Vl;ve.openSegments=Gl;ve.manifestDigest=ql;ve.buildCapability=Wl;var _r=T("@noble/hashes/sha2.js"),Ml="pq-hybrid-segments",Fl="AES-256-GCM",rt=e=>e,fa=e=>{if(typeof Buffer<"u")return Buffer.from(e).toString("base64");let t="";for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return btoa(t)},ha=e=>{if(typeof Buffer<"u")return new Uint8Array(Buffer.from(e,"base64"));let t=atob(e),n=new Uint8Array(t.length);for(let r=0;r<t.length;r++)n[r]=t.charCodeAt(r);return n},ya=e=>{let t="";for(let n=0;n<e.length;n++)t+=e[n].toString(16).padStart(2,"0");return t};async function Ul(e,t,n){let r=await crypto.subtle.importKey("raw",rt(e),{name:"AES-GCM"},!1,["encrypt"]),o=await crypto.subtle.encrypt({name:"AES-GCM",iv:rt(t)},r,rt(n));return new Uint8Array(o)}async function Hl(e,t,n){let r=await crypto.subtle.importKey("raw",rt(e),{name:"AES-GCM"},!1,["decrypt"]),o=await crypto.subtle.decrypt({name:"AES-GCM",iv:rt(t)},r,rt(n));return new Uint8Array(o)}var Le=class extends Error{constructor(t,n){super(n),this.name="SegmentError",this.code=t}};ve.SegmentError=Le;async function Vl(e){let t=new Set;for(let o of e){if(t.has(o.segment_id))throw new Le("duplicate_segment_id",`segment_id '${o.segment_id}' appears twice`);t.add(o.segment_id)}let n=[],r=[];for(let o of e){let a=crypto.getRandomValues(new Uint8Array(32)),i=crypto.getRandomValues(new Uint8Array(12)),s=await Ul(a,i,o.plaintext),c=s.slice(0,s.length-16),d=ya((0,_r.sha256)(c));n.push({segment_id:o.segment_id,key:a}),r.push({segment_id:o.segment_id,label:o.label,content_type:o.content_type,iv_b64:fa(i),ciphertext_b64:fa(s),ciphertext_sha256:d})}return{manifest:{profile:Ml,aead:Fl,segments:r},keys:n}}async function Gl(e,t){let n=new Map;for(let o of t.keys)n.set(o.segment_id,o.key);let r=[];for(let o of e.segments){if(!t.allowed_segment_ids.includes(o.segment_id))continue;let a=n.get(o.segment_id);if(!a)throw new Le("key_missing",`capability lists ${o.segment_id} as allowed but holds no key for it`);let i=ha(o.ciphertext_b64),s=i.slice(0,i.length-16);if(ya((0,_r.sha256)(s))!==o.ciphertext_sha256)throw new Le("integrity_mismatch",`segment ${o.segment_id}: ciphertext sha256 mismatch`);let d=ha(o.iv_b64),u=await Hl(a,d,i);r.push({segment_id:o.segment_id,label:o.label,content_type:o.content_type,plaintext:u})}return r}function ql(e){let t=e.segments.map(r=>({id:r.segment_id,h:r.ciphertext_sha256})),n=JSON.stringify({profile:e.profile,aead:e.aead,segments:t});return(0,_r.sha256)(new TextEncoder().encode(n))}function Wl(e,t,n){let r=new Set(t),o=n.filter(a=>r.has(a.segment_id));if(o.length!==t.length){let a=t.filter(i=>!o.find(s=>s.segment_id===i));throw new Le("segment_not_found",`cannot build capability \u2014 no key for: ${a.join(", ")}`)}return{recipient_kid:e,allowed_segment_ids:t,keys:o}}});var ba=C(Tt=>{"use strict";Object.defineProperty(Tt,"__esModule",{value:!0});Tt.computeWatermark=_a;Tt.findLeakSource=Yl;Tt.watermarkSvgOverlay=Xl;var Jl=T("@noble/hashes/hmac.js"),zl=T("@noble/hashes/sha2.js");function _a(e){let t=[e.recipientId,e.lockboxId,String(e.openCount),String(e.iat)].join("|"),n=(0,Jl.hmac)(zl.sha256,e.tenantSecret,new TextEncoder().encode(t)),r=ga(n.slice(0,16)),o=ga(n.slice(0,4)),a=new Date(e.iat*1e3).toISOString().slice(0,10),i=`${e.recipientId} \xB7 ${a} \xB7 ${o}`;return{short_hex:o,full_hex:r,display_label:i}}function Yl(e,t,n){let r=e.toLowerCase();for(let o of n){let a=_a({tenantSecret:t,...o});if(r===a.full_hex)return{matched:!0,candidate:o,matched_on:"full_hex"};if(r===a.short_hex)return{matched:!0,candidate:o,matched_on:"short_hex"}}return{matched:!1,reason:"no_candidate_matched"}}function Xl(e,t){let n=t?.width??800,r=t?.height??1e3,o=t?.opacity??.1,i=(s=>s.replace(/[<>&"]/g,c=>({"<":"&lt;",">":"&gt;","&":"&amp;",'"':"&quot;"})[c]))(e.display_label);return`<svg xmlns="http://www.w3.org/2000/svg" width="${n}" height="${r}" pointer-events="none">
9
9
  <g fill="#000" opacity="${o}" font-family="Helvetica, Arial, sans-serif" font-size="20" text-anchor="middle">
10
10
  <text x="${n/2}" y="${r*.2}" transform="rotate(-30 ${n/2} ${r*.2})">${i}</text>
11
11
  <text x="${n/2}" y="${r*.5}" transform="rotate(-30 ${n/2} ${r*.5})">${i}</text>
12
12
  <text x="${n/2}" y="${r*.8}" transform="rotate(-30 ${n/2} ${r*.8})">${i}</text>
13
13
  </g>
14
14
  <text x="${n-12}" y="${r-8}" font-family="monospace" font-size="10" fill="#000" opacity="${o*2}" text-anchor="end">${e.short_hex}</text>
15
- </svg>`}function Vo(e){let t="";for(let n=0;n<e.length;n++)t+=e[n].toString(16).padStart(2,"0");return t}});var Qo=O(G=>{"use strict";Object.defineProperty(G,"__esModule",{value:!0});G.DRAND_LOE_MAINNET=G.TimeGateError=void 0;G.timeGateEncrypt=Vc;G.timeGateDecrypt=Gc;G.roundForTime=qc;G.timeForRound=Wc;G.drandTimeLockEncrypt=zc;G.drandTimeLockDecrypt=Xo;G.makeFakeDrandChain=Yc;G.fetchDrandRound=Zo;G.drandTimeLockOpen=Zc;var le=A("@noble/curves/bls12-381.js"),Jt=A("@noble/hashes/sha2.js"),ve=e=>e,Jo="NDC-v0.3-server-time-gate";async function Vc(e){let t=crypto.getRandomValues(new Uint8Array(12)),n=new TextEncoder().encode(`${Jo}|${e.notBeforeUnixSec}`),r=await crypto.subtle.importKey("raw",ve(e.serverWrapKey),{name:"AES-GCM"},!1,["encrypt"]),o=await crypto.subtle.encrypt({name:"AES-GCM",iv:ve(t),additionalData:ve(n)},r,ve(e.plaintext));return{variant:"server-attested",notBeforeUnixSec:e.notBeforeUnixSec,iv_b64:qt(t),ciphertext_b64:qt(new Uint8Array(o))}}var bt=class extends Error{constructor(t,n){super(n),this.name="TimeGateError",this.code=t}};G.TimeGateError=bt;async function Gc(e){if(e.currentUnixSec<e.ciphertext.notBeforeUnixSec)throw new bt("not_yet",`time-gate not yet open: now ${e.currentUnixSec} < notBefore ${e.ciphertext.notBeforeUnixSec}`);let t=new TextEncoder().encode(`${Jo}|${e.ciphertext.notBeforeUnixSec}`),n=await crypto.subtle.importKey("raw",ve(e.serverWrapKey),{name:"AES-GCM"},!1,["decrypt"]);try{let r=await crypto.subtle.decrypt({name:"AES-GCM",iv:ve(Wt(e.ciphertext.iv_b64)),additionalData:ve(t)},n,ve(Wt(e.ciphertext.ciphertext_b64)));return new Uint8Array(r)}catch{throw new bt("tamper_detected","AES-GCM authentication tag failed \u2014 ciphertext or AAD tampered")}}G.DRAND_LOE_MAINNET={publicKeyHex:"868f005eb8e6e4ca0a47c8a77ceaa5309a47978a7c71bc5cce96366b5d7a569937c529eeda66c7293784a9402801af31",chainHashHex:"8990e7a9aaed2ffed73dbd7092123d6f289930540d7651336225dc172e51b2ce",genesisUnixSec:1595431050,periodSec:30,hashDst:"BLS_SIG_BLS12381G2_XMD:SHA-256_SSWU_RO_NUL_"};function qc(e,t){return e<=t.genesisUnixSec?1:Math.ceil((e-t.genesisUnixSec)/t.periodSec)}function Wc(e,t){return t.genesisUnixSec+e*t.periodSec}function zo(e){let t=new Uint8Array(8),n=e;for(let r=7;r>=0;r--)t[r]=n&255,n=Math.floor(n/256);return(0,Jt.sha256)(t)}function Yo(e){let t=new Uint8Array(576),n=0;for(let r of[e.c0,e.c1])for(let o of[r.c0,r.c1,r.c2])for(let a of[o.c0,o.c1])Jc(a,t,n,48),n+=48;return t}function Jc(e,t,n,r){let o=e,a=BigInt(255),i=BigInt(8);for(let s=r-1;s>=0;s--)t[n+s]=Number(o&a),o>>=i}function zc(e,t,n,r){if(e.length!==32)throw new Error(`drand-IBE expects a 32-byte content key, got ${e.length}`);let o=le.bls12_381.G1.Point,a=le.bls12_381.fields.Fr,i=o.fromBytes(n),s;do s=Qc(crypto.getRandomValues(new Uint8Array(32)))%a.ORDER;while(s===BigInt(0));let l=o.BASE.multiply(s),d=le.bls12_381.longSignatures.hash(zo(t),r.hashDst),u=i.multiply(s),p=le.bls12_381.pairing(u,d,!0),h=(0,Jt.sha256)(Yo(p)),m=new Uint8Array(32);for(let v=0;v<32;v++)m[v]=e[v]^h[v];return{variant:"drand-ibe",chainHashHex:r.chainHashHex,round:t,u_b64:qt(l.toBytes()),v_b64:qt(m)}}function Xo(e){if(e.ciphertext.variant!=="drand-ibe")throw new Error("not a drand-IBE ciphertext");if(e.ciphertext.chainHashHex!==e.chain.chainHashHex)throw new Error("chain hash mismatch \u2014 ciphertext sealed to a different drand chain");let n=le.bls12_381.G1.Point.fromBytes(Wt(e.ciphertext.u_b64)),r=le.bls12_381.longSignatures.Signature.fromBytes(e.roundSignature),o=le.bls12_381.pairing(n,r,!0),a=(0,Jt.sha256)(Yo(o)),i=Wt(e.ciphertext.v_b64);if(i.length!==32)throw new Error("drand-IBE V must be 32 bytes");let s=new Uint8Array(32);for(let l=0;l<32;l++)s[l]=i[l]^a[l];return s}function Yc(e){let t;if(e&&e.length===48)t=e;else{t=new Uint8Array(48);let a=e??crypto.getRandomValues(new Uint8Array(48));t.set(a.slice(0,48),0)}let{secretKey:n,publicKey:r}=le.bls12_381.longSignatures.keygen(t),o={publicKeyHex:Wo(r.toBytes()),chainHashHex:Wo((0,Jt.sha256)(r.toBytes())),genesisUnixSec:17e8,periodSec:30,hashDst:"BLS_SIG_BLS12381G2_XMD:SHA-256_SSWU_RO_NUL_"};return{config:o,publicKey:r.toBytes(),signRound(a){let i=le.bls12_381.longSignatures.hash(zo(a),o.hashDst);return le.bls12_381.longSignatures.sign(i,n).toBytes()}}}function Wo(e){let t="";for(let n=0;n<e.length;n++)t+=e[n].toString(16).padStart(2,"0");return t}function Xc(e){if(e.length%2!==0)throw new Error("hex must have even length");let t=new Uint8Array(e.length/2);for(let n=0;n<t.length;n++)t[n]=parseInt(e.substr(n*2,2),16);return t}async function Zo(e,t,n={}){let r=n.fetchImpl??fetch,o=n.timeoutMs??8e3,a=`${t.replace(/\/$/,"")}/public/${e}`,i,s;typeof AbortController<"u"&&(i=new AbortController,s=setTimeout(()=>i.abort(),o));let l;try{l=await r(a,{signal:i?.signal})}finally{s&&clearTimeout(s)}if(!l.ok)throw new Error(`drand fetch failed: ${a} \u2192 HTTP ${l.status}`);let d=await l.json();if(typeof d.round!="number"||typeof d.signature!="string"||typeof d.randomness!="string")throw new Error(`drand response malformed at ${a}`);let u=Xc(d.signature);if(u.length!==96)throw new Error(`drand signature wrong length: expected 96 bytes (compressed G2), got ${u.length}`);return{round:d.round,randomness_hex:d.randomness,signature_bytes:u,previous_signature_hex:d.previous_signature}}async function Zc(e,t,n,r={}){let o=await Zo(e.round,t,r);return Xo({ciphertext:e,roundSignature:o.signature_bytes,chain:n})}function qt(e){if(typeof Buffer<"u")return Buffer.from(e).toString("base64");let t="";for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return btoa(t)}function Wt(e){if(typeof Buffer<"u")return new Uint8Array(Buffer.from(e,"base64"));let t=atob(e),n=new Uint8Array(t.length);for(let r=0;r<t.length;r++)n[r]=t.charCodeAt(r);return n}function Qc(e){let t=BigInt(0),n=BigInt(8);for(let r=0;r<e.length;r++)t=t<<n|BigInt(e[r]);return t}});var oa=O(Q=>{"use strict";Object.defineProperty(Q,"__esModule",{value:!0});Q.GENESIS_PREV_HASH=void 0;Q.receiptHash=ar;Q.issueReceipt=ir;Q.verifyReceipt=ra;Q.auditChain=nl;Q.issueGenesisReceipt=rl;Q.appendReceipt=ol;var el=A("@noble/hashes/sha2.js"),or=Mt(),na=Ve();Q.GENESIS_PREV_HASH="0".repeat(64);var ea=e=>{if(typeof Buffer<"u")return Buffer.from(e).toString("base64");let t="";for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return btoa(t)},ta=e=>{if(typeof Buffer<"u")return new Uint8Array(Buffer.from(e,"base64"));let t=atob(e),n=new Uint8Array(t.length);for(let r=0;r<t.length;r++)n[r]=t.charCodeAt(r);return n},tl=e=>{let t="";for(let n=0;n<e.length;n++)t+=e[n].toString(16).padStart(2,"0");return t};function ar(e){return tl((0,el.sha256)(new TextEncoder().encode((0,or.canonicalJson)(e))))}function ir(e){let t={event_type:e.event_type,sequence:e.sequence,iat:e.iat??new Date().toISOString(),lockbox_id:e.lockbox_id,prev_hash:e.prev_hash,payload:e.payload},n=new TextEncoder().encode((0,or.canonicalJson)(t)),r=(0,na.hybridSign)(e.signing_key.secretKey,n);return{body:t,sig:{signer_kid:e.signer_kid,ed25519_b64:ea(r.ed25519),ml_dsa_65_b64:ea(r.mlDsa)}}}function ra(e,t){let n=new TextEncoder().encode((0,or.canonicalJson)(e.body)),r={ed25519:ta(e.sig.ed25519_b64),mlDsa:ta(e.sig.ml_dsa_65_b64)};return(0,na.hybridVerify)(t,n,r)}function nl(e,t,n=1){if(e.length===0)return{ok:!0,receipts_checked:0};let r=n,o=n===1?Q.GENESIS_PREV_HASH:null;for(let a of e){if(a.body.sequence!==r)return{ok:!1,code:a.body.sequence<r?"duplicate_sequence":"out_of_order",at_sequence:a.body.sequence,reason:`expected sequence ${r}, got ${a.body.sequence}`};if(o!==null&&a.body.prev_hash!==o)return{ok:!1,code:r===1?"missing_genesis":"broken_prev_hash",at_sequence:a.body.sequence,reason:`prev_hash mismatch: expected ${o.slice(0,16)}\u2026, got ${a.body.prev_hash.slice(0,16)}\u2026`};if(!ra(a,t))return{ok:!1,code:"bad_signature",at_sequence:a.body.sequence,reason:"hybrid signature does not verify"};o=ar(a.body),r+=1}return{ok:!0,receipts_checked:e.length}}function rl(e){return ir({event_type:e.initial_event,lockbox_id:e.lockbox_id,prev_hash:Q.GENESIS_PREV_HASH,sequence:1,payload:e.initial_payload,signer_kid:e.signer_kid,signing_key:e.signing_key,iat:e.iat})}function ol(e,t){return ir({...t,prev_hash:ar(e.body),sequence:e.body.sequence+1})}});var ia=O(zt=>{"use strict";Object.defineProperty(zt,"__esModule",{value:!0});zt.recommend=dl;zt.summarise=ul;var al={healthcare:{mode:"mode-4h",ttlSeconds:3600,forensicWatermark:!0,teeAttestation:!0,rationale:"HIPAA \xB7 BAA \xB7 per-recipient attribution required"},insurance:{mode:"mode-4",ttlSeconds:28800,forensicWatermark:!0,teeAttestation:!1,rationale:"Adjusters need offline access during field visits"},bank:{mode:"mode-4h",ttlSeconds:3600,forensicWatermark:!0,teeAttestation:!1,rationale:"SOX \xB7 per-open audit \xB7 forward secrecy on signed mandates"},legal:{mode:"mode-4p",ttlSeconds:86400,forensicWatermark:!0,teeAttestation:!1,rationale:"Client privilege \xB7 approval-quorum patterns common"},government:{mode:"mode-4h",ttlSeconds:3600,forensicWatermark:!0,teeAttestation:!0,rationale:"Classified \xB7 per-open attestation \xB7 k-of-N release"},media:{mode:"mode-4p",ttlSeconds:604800,forensicWatermark:!0,teeAttestation:!1,rationale:"Source protection \xB7 leak attribution \xB7 light verification UX"},hr:{mode:"mode-4",ttlSeconds:86400,forensicWatermark:!0,teeAttestation:!1,rationale:"Performance reviews \xB7 separation packages \xB7 low compliance"},smb:{mode:"mode-4",ttlSeconds:604800,forensicWatermark:!1,teeAttestation:!1,rationale:"Cost-sensitive \xB7 low compliance overhead"}},il={"medical-phi":{minMode:"mode-4h",maxTtlSeconds:3600,watermarkRequired:!0,selectiveDisclosure:!0,thresholdSuggested:!1,teeRequired:!0},"financial-statements":{minMode:"mode-4",maxTtlSeconds:28800,watermarkRequired:!0,selectiveDisclosure:!0,thresholdSuggested:!0,teeRequired:!1},"identity-documents":{minMode:"mode-4h",maxTtlSeconds:3600,watermarkRequired:!0,selectiveDisclosure:!0,thresholdSuggested:!1,teeRequired:!0},"legal-contracts":{minMode:"mode-4p",maxTtlSeconds:86400,watermarkRequired:!0,selectiveDisclosure:!0,thresholdSuggested:!0,teeRequired:!1},"board-materials":{minMode:"mode-4p",maxTtlSeconds:86400,watermarkRequired:!0,selectiveDisclosure:!0,thresholdSuggested:!0,teeRequired:!1},"source-code":{minMode:"mode-4h",maxTtlSeconds:3600,watermarkRequired:!0,selectiveDisclosure:!0,thresholdSuggested:!1,teeRequired:!0},marketing:{minMode:"mode-4",maxTtlSeconds:604800,watermarkRequired:!1,selectiveDisclosure:!1,thresholdSuggested:!1,teeRequired:!1},"internal-memo":{minMode:"mode-4",maxTtlSeconds:86400,watermarkRequired:!1,selectiveDisclosure:!1,thresholdSuggested:!1,teeRequired:!1},"live-ops-data":{minMode:"mode-4",maxTtlSeconds:86400,watermarkRequired:!1,selectiveDisclosure:!1,thresholdSuggested:!1,teeRequired:!1}},sl={email:{deliveryMode:"attachment",adapters:["gmail","outlook","smtp"],notes:[]},chat:{deliveryMode:"link",adapters:["whatsapp","telegram","slack","teams"],notes:["Send the ndc:// link only; file bytes never traverse the chat provider"]},"cloud-share":{deliveryMode:"link",adapters:["drive","sharepoint","dropbox","box"],notes:[]},sftp:{deliveryMode:"attachment",adapters:["sftp","ftps"],notes:["Legacy partners often require this"]},sms:{deliveryMode:"link",adapters:["sms-short-link"],notes:["Link only; SMS cannot carry binary"]},voice:{deliveryMode:"link",adapters:["voice-readback"],notes:["Voice carries the unlock factor, not the content"]},"web-portal":{deliveryMode:"link",adapters:["web-portal-pickup","embed-iframe"],notes:[]},"qr-physical":{deliveryMode:"in-person",adapters:["qr-code","usb-handoff","airdrop"],notes:["Recipient must scan / plug in physically"]},webhook:{deliveryMode:"attachment",adapters:["webhook-push"],notes:["B2B server-to-server only"]}},cl=[{channel:"chat",fileClass:"medical-phi",note:"PHI over chat \u2192 link only; never attach the bytes"},{channel:"chat",fileClass:"identity-documents",note:"ID documents over chat \u2192 link only"},{channel:"chat",fileClass:"legal-contracts",note:"Legal contracts over chat are discouraged; use email/portal"},{channel:"chat",fileClass:"board-materials",note:"Board materials over chat are discouraged; use email/portal"},{channel:"chat",fileClass:"source-code",note:"Source code over chat is discouraged; use cloud-share/portal"},{channel:"cloud-share",fileClass:"identity-documents",note:"ID documents on cloud share discouraged; prefer email or portal"},{channel:"sms",fileClass:"medical-phi",note:"PHI over SMS is not compliant; reroute to web-portal"},{channel:"voice",fileClass:"medical-phi",note:"Voice only carries the unlock; the bytes must travel another channel"}],aa={"mode-4":1,"mode-4p":2,"mode-4h":3,"mode-6":4};function ll(e,t){return aa[e]>=aa[t]?e:t}function dl(e){let t=al[e.orgType],n=il[e.fileClass],r=sl[e.channel],o=ll(t.mode,n.minMode);e.recipientLacksPasskey&&o==="mode-4h"&&(o="mode-4p");let a=Math.min(t.ttlSeconds,n.maxTtlSeconds),i={forensicWatermark:t.forensicWatermark||n.watermarkRequired,selectiveDisclosureSegments:n.selectiveDisclosure||!!e.perRecipientPolicy,thresholdKofN:e.multipleApproversRequired??null,teeAttestation:t.teeAttestation||n.teeRequired,perOpenRatchet:o==="mode-4h"||o==="mode-4p"||o==="mode-6",dpopRequired:o!=="mode-4",timelockDrand:!!e.timeLockUnixSec&&!!e.timeLockDecentralized,timelockServerGate:!!e.timeLockUnixSec&&!e.timeLockDecentralized},s={...r,adapterCandidates:[...r.adapters]},l=[...s.notes],d=cl.find(u=>u.channel===e.channel&&u.fileClass===e.fileClass);return d&&(l.unshift(`\u26A0 ${d.note}`),s.deliveryMode==="attachment"&&(s.deliveryMode="link")),e.fileClass==="live-ops-data"&&e.channel==="email"&&l.push("Live ops data over email is non-standard; consider webhook-push or web-portal."),{sensitivityMode:o,cacheTtlSeconds:a,features:i,delivery:{deliveryMode:s.deliveryMode,adapterCandidates:s.adapterCandidates},notes:l}}function ul(e){let t=[e.sensitivityMode,`TTL ${e.cacheTtlSeconds}s`];return e.features.forensicWatermark&&t.push("watermark"),e.features.selectiveDisclosureSegments&&t.push("segments"),e.features.thresholdKofN&&t.push(`threshold ${e.features.thresholdKofN.k}-of-${e.features.thresholdKofN.n}`),e.features.teeAttestation&&t.push("TEE"),e.features.perOpenRatchet&&t.push("ratchet"),e.features.dpopRequired&&t.push("DPoP"),e.features.timelockDrand?t.push("drand-tlock"):e.features.timelockServerGate&&t.push("server-timegate"),t.push(`via ${e.delivery.deliveryMode} (${e.delivery.adapterCandidates.join("/")})`),t.join(" \xB7 ")}});var ca=O(Ye=>{"use strict";Object.defineProperty(Ye,"__esModule",{value:!0});Ye.recommendationToMandate=ml;Ye.v3SealReceiptPayload=gl;Ye.v3OpenReceiptPayload=_l;Ye.showcaseChips=bl;function pl(e){switch(e){case"mode-4":return"name_email";case"mode-4p":return"name_email";case"mode-4h":return"hardware_attest";case"mode-6":return"name_email_phone"}}function fl(e){return e.features.dpopRequired?"device_mfa":e.sensitivityMode==="mode-4h"?"first_device":e.sensitivityMode==="mode-4"?"any":"first_device"}function hl(e){return e.delivery.deliveryMode==="attachment"?"file":e.delivery.deliveryMode==="link"?"link":"view_only"}function sa(e){let t=e.delivery.adapterCandidates;return t.some(n=>n==="outlook"||n==="sharepoint"||n==="teams")?"m365":t.some(n=>n==="webhook-push"||n==="web-portal-pickup"||n==="embed-iframe")?"in_app":"capsule"}function yl(e){let t=sa(e);return t==="m365"?"m365_only":t==="in_app"?"in_app":"any"}function ml(e){let{recommendation:t,source:n}=e,r=t.sensitivityMode==="mode-6",o=n.timeLockUnixSec?new Date(n.timeLockUnixSec*1e3).toISOString():null;return{time:{ttl_seconds:t.cacheTtlSeconds,burn_after_first_read:r,unlock_at:o,max_opens:r?1:null},identity:{capture:pl(t.sensitivityMode),claim_required:t.sensitivityMode!=="mode-4",allow_magic_link:t.sensitivityMode==="mode-4",allowed_emails:null},device:{binding:fl(t),listed_fingerprints:null},channel:{delivery:hl(t),route:sa(t),channel_constraint:yl(t)},burn:{crypto_shred_on_burn:!0,mdm_wipe_webhook:!1,undo_window_s:0,dual_control:!!t.features.thresholdKofN},encrypt:{mode:"hpke",vault_mirror:t.features.teeAttestation,scoped_key_release:!0},proof:{signing:"ed25519",anchor:t.features.teeAttestation?"rekor":"none",c2pa_in_file:!1,ndc_seal:!0},watermark:{visible:t.features.forensicWatermark,forensic:t.features.forensicWatermark,content:t.features.forensicWatermark?"recipient_id":null,custom_text:null,forensics_lookup:t.features.forensicWatermark},ndc_v3_extensions:{profile:"pq-hybrid",suite:{kem:"X25519+ML-KEM-768",sig:"Ed25519+ML-DSA-65",aead:"AES-256-GCM",kdf:"HKDF-SHA-256"},dpop_required:t.features.dpopRequired,ratchet_enabled:t.features.perOpenRatchet,tee_attestation_required:t.features.teeAttestation,threshold_k_of_n:t.features.thresholdKofN,segments_enabled:t.features.selectiveDisclosureSegments,timelock_drand:t.features.timelockDrand,timelock_server_gate:t.features.timelockServerGate,timelock_unix_sec:n.timeLockUnixSec??null}}}function gl(e){return{event_kind:"ndc_v3_sealed",lockbox_id:e.lockbox_id,ciphertext_sha256:e.ciphertext_sha256,recipient_kid:e.recipient_kid,signer_kid:e.signer_kid,mandate:e.mandate,bytes_sealed:e.bytes_sealed,issued_at:e.issued_at??new Date().toISOString()}}function _l(e){return{event_kind:"ndc_v3_opened",lockbox_id:e.lockbox_id,ratchet_sequence:e.ratchet_sequence,dpop_jkt:e.dpop_jkt,ip_hash:e.ip_hash,opened_at:e.opened_at??new Date().toISOString()}}function bl(e){let t=[],n=e.ndc_v3_extensions;return t.push("PQ-hybrid"),n.dpop_required&&t.push("DPoP"),n.ratchet_enabled&&t.push("per-open ratchet"),e.watermark.forensic&&t.push("forensic watermark"),n.segments_enabled&&t.push("selective disclosure"),n.threshold_k_of_n&&t.push(`${n.threshold_k_of_n.k}-of-${n.threshold_k_of_n.n} quorum`),n.tee_attestation_required&&t.push("TEE attest"),n.timelock_drand?t.push("drand time-lock"):n.timelock_server_gate&&t.push("server time-gate"),e.time.burn_after_first_read&&t.push("burn-after-read"),t}});var fa=O(de=>{"use strict";Object.defineProperty(de,"__esModule",{value:!0});de.encodeFragment=pa;de.decodeFragment=Sl;de.extractProofToken=vl;de.encodeProofToken=wl;de.decodeShareCredential=El;de.sealBytesForPublicShare=Al;de.openPublicShare=Tl;de.wrapFragmentForShortLink=Pl;var la=Ve(),da=Mt();function we(e){let t="";for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return btoa(t)}function St(e){let t=atob(e),n=new Uint8Array(t.length);for(let r=0;r<t.length;r++)n[r]=t.charCodeAt(r);return n}function ua(e){return we(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function pa(e){return encodeURIComponent(JSON.stringify(e))}function Sl(e){let t=JSON.parse(decodeURIComponent(e));if(t.v!==3)throw new Error(`fragment version unsupported: ${t.v}`);return t}function vl(e){return{v:3,kind:"proof",n:e.n,t:e.t,spe:e.spe,spm:e.spm}}function wl(e){return encodeURIComponent(JSON.stringify(e))}function El(e){let t=e.trim(),n=t.indexOf("#"),r=n>=0?t.slice(n+1):t,o;try{o=JSON.parse(decodeURIComponent(r))}catch(a){throw new Error(`credential parse failed: ${a.message??"invalid_json"}`)}if(o.v!==3)throw new Error(`credential version unsupported: ${String(o.v)}`);return o.kind==="proof"?{kind:"proof",value:o}:{kind:"fragment",value:o}}function kl(){let e=new Uint8Array(16);crypto.getRandomValues(e);let t="";for(let n=0;n<e.length;n++)t+=e[n].toString(16).padStart(2,"0");return t}function xl(){let e=new Uint8Array(32);return crypto.getRandomValues(e),ua(e)}async function Al(e){let t=e.bytes,n={name:e.filename,type:e.contentType},r=(0,la.generateHybridKemKeypair)(),o=(0,la.generateHybridSigKeypair)(),a=kl(),i=xl(),s=await(0,da.sealHybrid)({plaintext:t,recipientPublicKey:r.publicKey,recipientKid:`ephemeral-${a}`,signerKeypair:o,signerKid:`lock-${a}`,meta:{lockbox_id:a,server:e.server,bearer:i,original_filename:n.name,original_content_type:n.type||"application/octet-stream",cache_ttl_seconds:e.ttlSeconds,dpop_required:!1,tee_attestation_url:null,ratchet_state:null}}),l=pa({v:3,n:n.name,t:n.type||"application/octet-stream",rsx:we(r.secretKey.x25519),rsm:we(r.secretKey.mlKem),rpx:we(r.publicKey.x25519),spe:we(o.publicKey.ed25519),spm:we(o.publicKey.mlDsa)});return{container:s.container,fragment:l,lockboxId:a}}async function Tl(e){let t={x25519:St(e.fragment.rsx),mlKem:St(e.fragment.rsm)},n=St(e.fragment.rpx),r={ed25519:St(e.fragment.spe),mlDsa:St(e.fragment.spm)},{plaintext:o,header:a}=await(0,da.openHybrid)({container:e.container,recipientSecretKey:t,recipientPublicX25519:n,signerPublicKey:r});return{plaintext:o,filename:a.original_filename||e.fragment.n,contentType:a.original_content_type||e.fragment.t,signerKid:a.sig.signer_kid,issuedAt:a.issued_at,ciphertextSha256:a.ciphertext_sha256}}async function Pl(e){let t=crypto.getRandomValues(new Uint8Array(32)),n=crypto.getRandomValues(new Uint8Array(12)),r=new TextEncoder().encode(e),o=new ArrayBuffer(32);new Uint8Array(o).set(t);let a=new ArrayBuffer(12);new Uint8Array(a).set(n);let i=new ArrayBuffer(r.byteLength);new Uint8Array(i).set(r);let s=await crypto.subtle.importKey("raw",o,{name:"AES-GCM"},!1,["encrypt"]),l=new Uint8Array(await crypto.subtle.encrypt({name:"AES-GCM",iv:a},s,i));return{wrapKeyB64Url:ua(t),wrappedFragmentB64:we(l),wrapIvB64:we(n)}}});var ga=O(c=>{"use strict";var Dl=c&&c.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(c,"__esModule",{value:!0});c.PVE_SIGNED_LEN=c.RCPT_VERSION=c.PVE_VERSION=c.RCPT_MAGIC=c.PVE_MAGIC=c.verifyDpop=c.publicJwkFromBytes=c.jwkThumbprint=c.createDpop=c.verifyContainerHeader=c.signContainerHeader=c.sealHybrid=c.openHybrid=c.headerSigningBytes=c.encodeContainerV3=c.decodeContainerV3=c.ContainerV3Error=c.CONTAINER_HEADER_MAX_BYTES=c.CONTAINER_FIXED_PREFIX_BYTES=c.CONTAINER_MAGIC=c.canonicalJson=c.NDC_V03_RATCHET_DOMAIN=c.NDC_V03_CONTENT_KEY_DOMAIN=c.NDC_V03_KEM_DOMAIN=c.NDC_WIRE_V03=c.NDC_WIRE_V1=c.PQ_SIZES=c.PQ_SUITE=c.ratchetAdvance=c.deriveContentKey=c.mlDsa65VerifyDetached=c.mlDsa65SignDetached=c.generateMlDsa65Keypair=c.hybridVerify=c.hybridSign=c.hybridKemDecapsulate=c.hybridKemEncapsulate=c.generateHybridSigKeypair=c.deriveHybridKemKeypairFromSeed=c.generateHybridKemKeypair=c.ALGORITHMS=c.CRYPTO_VERSION=c.NoDataSDK=c.NoDataForms=c.NoDataSystems=c.NoDataWebhook=c.NoDataEmail=c.verifyProofOfWork=c.solveProofOfWork=c.NoDataCrypto=void 0;c.auditChain=c.appendReceipt=c.timeGateEncrypt=c.timeGateDecrypt=c.timeForRound=c.TimeGateError=c.roundForTime=c.makeFakeDrandChain=c.fetchDrandRound=c.drandTimeLockOpen=c.drandTimeLockEncrypt=c.drandTimeLockDecrypt=c.DRAND_LOE_MAINNET=c.watermarkSvgOverlay=c.findLeakSource=c.computeWatermark=c.SegmentError=c.sealSegments=c.openSegments=c.manifestDigest=c.buildCapability=c.splitSecret=c.serializeShare=c.deserializeShare=c.combineShares=c.decodeAttestationPayload=c.verifyCoseSign1Es384=c.verifyAttestation=c.parseAttestation=c.fetchAttestation=c.stepRatchet=c.replayRatchet=c.destroyKey=c.verifyReceiptDelta=c.parseReceiptDelta=c.signReceiptDelta=c.encodeReceiptDeltaSignedBytes=c.verifyPve=c.pveHash=c.parsePve=c.signPve=c.encodePveSignedBytes=c.originJktForPublicKey=c.uuidFromDeltaId=c.deltaIdFromUuid=c.ABSORB_STATUS=c.DELTA_KIND=c.RCPT_TOTAL_LEN=c.RCPT_SIGNED_LEN=c.PVE_TOTAL_LEN=void 0;c.wrapFragmentForShortLink=c.openPublicShare=c.sealBytesForPublicShare=c.decodeShareCredential=c.encodeProofToken=c.extractProofToken=c.decodeFragment=c.encodeFragment=c.v3SealReceiptPayload=c.v3OpenReceiptPayload=c.showcaseChips=c.recommendationToMandate=c.summarise=c.recommend=c.verifyReceipt=c.receiptHash=c.issueReceipt=c.issueGenesisReceipt=c.GENESIS_PREV_HASH=void 0;var Ol=Pe();Object.defineProperty(c,"NoDataCrypto",{enumerable:!0,get:function(){return Dl(Ol).default}});var ha=so();Object.defineProperty(c,"solveProofOfWork",{enumerable:!0,get:function(){return ha.solveProofOfWork}});Object.defineProperty(c,"verifyProofOfWork",{enumerable:!0,get:function(){return ha.verifyProofOfWork}});var vt=lo();Object.defineProperty(c,"NoDataEmail",{enumerable:!0,get:function(){return vt.NoDataEmail}});Object.defineProperty(c,"NoDataWebhook",{enumerable:!0,get:function(){return vt.NoDataWebhook}});Object.defineProperty(c,"NoDataSystems",{enumerable:!0,get:function(){return vt.NoDataSystems}});Object.defineProperty(c,"NoDataForms",{enumerable:!0,get:function(){return vt.NoDataForms}});Object.defineProperty(c,"NoDataSDK",{enumerable:!0,get:function(){return vt.NoDataSDK}});c.CRYPTO_VERSION="0.2.0";c.ALGORITHMS={ENCRYPTION:"AES-256-GCM",KEY_EXCHANGE:"RSA-OAEP-4096",KEY_DERIVATION:"PBKDF2-SHA256-310K",SIGNING:"Ed25519",HASHING:"SHA-256",PROOF_OF_WORK:"SHA-256-NONCE"};var B=Ve();Object.defineProperty(c,"generateHybridKemKeypair",{enumerable:!0,get:function(){return B.generateHybridKemKeypair}});Object.defineProperty(c,"deriveHybridKemKeypairFromSeed",{enumerable:!0,get:function(){return B.deriveHybridKemKeypairFromSeed}});Object.defineProperty(c,"generateHybridSigKeypair",{enumerable:!0,get:function(){return B.generateHybridSigKeypair}});Object.defineProperty(c,"hybridKemEncapsulate",{enumerable:!0,get:function(){return B.hybridKemEncapsulate}});Object.defineProperty(c,"hybridKemDecapsulate",{enumerable:!0,get:function(){return B.hybridKemDecapsulate}});Object.defineProperty(c,"hybridSign",{enumerable:!0,get:function(){return B.hybridSign}});Object.defineProperty(c,"hybridVerify",{enumerable:!0,get:function(){return B.hybridVerify}});Object.defineProperty(c,"generateMlDsa65Keypair",{enumerable:!0,get:function(){return B.generateMlDsa65Keypair}});Object.defineProperty(c,"mlDsa65SignDetached",{enumerable:!0,get:function(){return B.mlDsa65SignDetached}});Object.defineProperty(c,"mlDsa65VerifyDetached",{enumerable:!0,get:function(){return B.mlDsa65VerifyDetached}});Object.defineProperty(c,"deriveContentKey",{enumerable:!0,get:function(){return B.deriveContentKey}});Object.defineProperty(c,"ratchetAdvance",{enumerable:!0,get:function(){return B.ratchetAdvance}});Object.defineProperty(c,"PQ_SUITE",{enumerable:!0,get:function(){return B.PQ_SUITE}});Object.defineProperty(c,"PQ_SIZES",{enumerable:!0,get:function(){return B.PQ_SIZES}});Object.defineProperty(c,"NDC_WIRE_V1",{enumerable:!0,get:function(){return B.NDC_WIRE_V1}});Object.defineProperty(c,"NDC_WIRE_V03",{enumerable:!0,get:function(){return B.NDC_WIRE_V03}});Object.defineProperty(c,"NDC_V03_KEM_DOMAIN",{enumerable:!0,get:function(){return B.NDC_V03_KEM_DOMAIN}});Object.defineProperty(c,"NDC_V03_CONTENT_KEY_DOMAIN",{enumerable:!0,get:function(){return B.NDC_V03_CONTENT_KEY_DOMAIN}});Object.defineProperty(c,"NDC_V03_RATCHET_DOMAIN",{enumerable:!0,get:function(){return B.NDC_V03_RATCHET_DOMAIN}});var ee=Mt();Object.defineProperty(c,"canonicalJson",{enumerable:!0,get:function(){return ee.canonicalJson}});Object.defineProperty(c,"CONTAINER_MAGIC",{enumerable:!0,get:function(){return ee.CONTAINER_MAGIC}});Object.defineProperty(c,"CONTAINER_FIXED_PREFIX_BYTES",{enumerable:!0,get:function(){return ee.CONTAINER_FIXED_PREFIX_BYTES}});Object.defineProperty(c,"CONTAINER_HEADER_MAX_BYTES",{enumerable:!0,get:function(){return ee.CONTAINER_HEADER_MAX_BYTES}});Object.defineProperty(c,"ContainerV3Error",{enumerable:!0,get:function(){return ee.ContainerV3Error}});Object.defineProperty(c,"decodeContainerV3",{enumerable:!0,get:function(){return ee.decodeContainerV3}});Object.defineProperty(c,"encodeContainerV3",{enumerable:!0,get:function(){return ee.encodeContainerV3}});Object.defineProperty(c,"headerSigningBytes",{enumerable:!0,get:function(){return ee.headerSigningBytes}});Object.defineProperty(c,"openHybrid",{enumerable:!0,get:function(){return ee.openHybrid}});Object.defineProperty(c,"sealHybrid",{enumerable:!0,get:function(){return ee.sealHybrid}});Object.defineProperty(c,"signContainerHeader",{enumerable:!0,get:function(){return ee.signContainerHeader}});Object.defineProperty(c,"verifyContainerHeader",{enumerable:!0,get:function(){return ee.verifyContainerHeader}});var Yt=Yn();Object.defineProperty(c,"createDpop",{enumerable:!0,get:function(){return Yt.createDpop}});Object.defineProperty(c,"jwkThumbprint",{enumerable:!0,get:function(){return Yt.jwkThumbprint}});Object.defineProperty(c,"publicJwkFromBytes",{enumerable:!0,get:function(){return Yt.publicJwkFromBytes}});Object.defineProperty(c,"verifyDpop",{enumerable:!0,get:function(){return Yt.verifyDpop}});var R=No();Object.defineProperty(c,"PVE_MAGIC",{enumerable:!0,get:function(){return R.PVE_MAGIC}});Object.defineProperty(c,"RCPT_MAGIC",{enumerable:!0,get:function(){return R.RCPT_MAGIC}});Object.defineProperty(c,"PVE_VERSION",{enumerable:!0,get:function(){return R.PVE_VERSION}});Object.defineProperty(c,"RCPT_VERSION",{enumerable:!0,get:function(){return R.RCPT_VERSION}});Object.defineProperty(c,"PVE_SIGNED_LEN",{enumerable:!0,get:function(){return R.PVE_SIGNED_LEN}});Object.defineProperty(c,"PVE_TOTAL_LEN",{enumerable:!0,get:function(){return R.PVE_TOTAL_LEN}});Object.defineProperty(c,"RCPT_SIGNED_LEN",{enumerable:!0,get:function(){return R.RCPT_SIGNED_LEN}});Object.defineProperty(c,"RCPT_TOTAL_LEN",{enumerable:!0,get:function(){return R.RCPT_TOTAL_LEN}});Object.defineProperty(c,"DELTA_KIND",{enumerable:!0,get:function(){return R.DELTA_KIND}});Object.defineProperty(c,"ABSORB_STATUS",{enumerable:!0,get:function(){return R.ABSORB_STATUS}});Object.defineProperty(c,"deltaIdFromUuid",{enumerable:!0,get:function(){return R.deltaIdFromUuid}});Object.defineProperty(c,"uuidFromDeltaId",{enumerable:!0,get:function(){return R.uuidFromDeltaId}});Object.defineProperty(c,"originJktForPublicKey",{enumerable:!0,get:function(){return R.originJktForPublicKey}});Object.defineProperty(c,"encodePveSignedBytes",{enumerable:!0,get:function(){return R.encodePveSignedBytes}});Object.defineProperty(c,"signPve",{enumerable:!0,get:function(){return R.signPve}});Object.defineProperty(c,"parsePve",{enumerable:!0,get:function(){return R.parsePve}});Object.defineProperty(c,"pveHash",{enumerable:!0,get:function(){return R.pveHash}});Object.defineProperty(c,"verifyPve",{enumerable:!0,get:function(){return R.verifyPve}});Object.defineProperty(c,"encodeReceiptDeltaSignedBytes",{enumerable:!0,get:function(){return R.encodeReceiptSignedBytes}});Object.defineProperty(c,"signReceiptDelta",{enumerable:!0,get:function(){return R.signReceipt}});Object.defineProperty(c,"parseReceiptDelta",{enumerable:!0,get:function(){return R.parseReceipt}});Object.defineProperty(c,"verifyReceiptDelta",{enumerable:!0,get:function(){return R.verifyReceipt}});var sr=Co();Object.defineProperty(c,"destroyKey",{enumerable:!0,get:function(){return sr.destroyKey}});Object.defineProperty(c,"replayRatchet",{enumerable:!0,get:function(){return sr.replayRatchet}});Object.defineProperty(c,"stepRatchet",{enumerable:!0,get:function(){return sr.stepRatchet}});var cr=Bo();Object.defineProperty(c,"fetchAttestation",{enumerable:!0,get:function(){return cr.fetchAttestation}});Object.defineProperty(c,"parseAttestation",{enumerable:!0,get:function(){return cr.parseAttestation}});Object.defineProperty(c,"verifyAttestation",{enumerable:!0,get:function(){return cr.verifyAttestation}});var ya=nr();Object.defineProperty(c,"verifyCoseSign1Es384",{enumerable:!0,get:function(){return ya.verifyCoseSign1Es384}});Object.defineProperty(c,"decodeAttestationPayload",{enumerable:!0,get:function(){return ya.decodeAttestationPayload}});var Xt=Mo();Object.defineProperty(c,"combineShares",{enumerable:!0,get:function(){return Xt.combineShares}});Object.defineProperty(c,"deserializeShare",{enumerable:!0,get:function(){return Xt.deserializeShare}});Object.defineProperty(c,"serializeShare",{enumerable:!0,get:function(){return Xt.serializeShare}});Object.defineProperty(c,"splitSecret",{enumerable:!0,get:function(){return Xt.splitSecret}});var wt=Ho();Object.defineProperty(c,"buildCapability",{enumerable:!0,get:function(){return wt.buildCapability}});Object.defineProperty(c,"manifestDigest",{enumerable:!0,get:function(){return wt.manifestDigest}});Object.defineProperty(c,"openSegments",{enumerable:!0,get:function(){return wt.openSegments}});Object.defineProperty(c,"sealSegments",{enumerable:!0,get:function(){return wt.sealSegments}});Object.defineProperty(c,"SegmentError",{enumerable:!0,get:function(){return wt.SegmentError}});var lr=qo();Object.defineProperty(c,"computeWatermark",{enumerable:!0,get:function(){return lr.computeWatermark}});Object.defineProperty(c,"findLeakSource",{enumerable:!0,get:function(){return lr.findLeakSource}});Object.defineProperty(c,"watermarkSvgOverlay",{enumerable:!0,get:function(){return lr.watermarkSvgOverlay}});var ne=Qo();Object.defineProperty(c,"DRAND_LOE_MAINNET",{enumerable:!0,get:function(){return ne.DRAND_LOE_MAINNET}});Object.defineProperty(c,"drandTimeLockDecrypt",{enumerable:!0,get:function(){return ne.drandTimeLockDecrypt}});Object.defineProperty(c,"drandTimeLockEncrypt",{enumerable:!0,get:function(){return ne.drandTimeLockEncrypt}});Object.defineProperty(c,"drandTimeLockOpen",{enumerable:!0,get:function(){return ne.drandTimeLockOpen}});Object.defineProperty(c,"fetchDrandRound",{enumerable:!0,get:function(){return ne.fetchDrandRound}});Object.defineProperty(c,"makeFakeDrandChain",{enumerable:!0,get:function(){return ne.makeFakeDrandChain}});Object.defineProperty(c,"roundForTime",{enumerable:!0,get:function(){return ne.roundForTime}});Object.defineProperty(c,"TimeGateError",{enumerable:!0,get:function(){return ne.TimeGateError}});Object.defineProperty(c,"timeForRound",{enumerable:!0,get:function(){return ne.timeForRound}});Object.defineProperty(c,"timeGateDecrypt",{enumerable:!0,get:function(){return ne.timeGateDecrypt}});Object.defineProperty(c,"timeGateEncrypt",{enumerable:!0,get:function(){return ne.timeGateEncrypt}});var Re=oa();Object.defineProperty(c,"appendReceipt",{enumerable:!0,get:function(){return Re.appendReceipt}});Object.defineProperty(c,"auditChain",{enumerable:!0,get:function(){return Re.auditChain}});Object.defineProperty(c,"GENESIS_PREV_HASH",{enumerable:!0,get:function(){return Re.GENESIS_PREV_HASH}});Object.defineProperty(c,"issueGenesisReceipt",{enumerable:!0,get:function(){return Re.issueGenesisReceipt}});Object.defineProperty(c,"issueReceipt",{enumerable:!0,get:function(){return Re.issueReceipt}});Object.defineProperty(c,"receiptHash",{enumerable:!0,get:function(){return Re.receiptHash}});Object.defineProperty(c,"verifyReceipt",{enumerable:!0,get:function(){return Re.verifyReceipt}});var ma=ia();Object.defineProperty(c,"recommend",{enumerable:!0,get:function(){return ma.recommend}});Object.defineProperty(c,"summarise",{enumerable:!0,get:function(){return ma.summarise}});var Zt=ca();Object.defineProperty(c,"recommendationToMandate",{enumerable:!0,get:function(){return Zt.recommendationToMandate}});Object.defineProperty(c,"showcaseChips",{enumerable:!0,get:function(){return Zt.showcaseChips}});Object.defineProperty(c,"v3OpenReceiptPayload",{enumerable:!0,get:function(){return Zt.v3OpenReceiptPayload}});Object.defineProperty(c,"v3SealReceiptPayload",{enumerable:!0,get:function(){return Zt.v3SealReceiptPayload}});var Ee=fa();Object.defineProperty(c,"encodeFragment",{enumerable:!0,get:function(){return Ee.encodeFragment}});Object.defineProperty(c,"decodeFragment",{enumerable:!0,get:function(){return Ee.decodeFragment}});Object.defineProperty(c,"extractProofToken",{enumerable:!0,get:function(){return Ee.extractProofToken}});Object.defineProperty(c,"encodeProofToken",{enumerable:!0,get:function(){return Ee.encodeProofToken}});Object.defineProperty(c,"decodeShareCredential",{enumerable:!0,get:function(){return Ee.decodeShareCredential}});Object.defineProperty(c,"sealBytesForPublicShare",{enumerable:!0,get:function(){return Ee.sealBytesForPublicShare}});Object.defineProperty(c,"openPublicShare",{enumerable:!0,get:function(){return Ee.openPublicShare}});Object.defineProperty(c,"wrapFragmentForShortLink",{enumerable:!0,get:function(){return Ee.wrapFragmentForShortLink}})});import{McpServer as od}from"@modelcontextprotocol/sdk/server/mcp.js";import{StdioServerTransport as ad}from"@modelcontextprotocol/sdk/server/stdio.js";import{z as f}from"zod";import{z as me}from"zod";import{readdirSync as Kr,readFileSync as jr,statSync as hn}from"node:fs";import{join as Pi}from"node:path";var xr=[{id:"aws-access-key",name:"AWS Access Key",pattern:/(?:^|[^A-Z0-9])AKIA[A-Z2-7]{16}(?:[^A-Z2-7]|$)/,severity:"critical"},{id:"aws-secret-key",name:"AWS Secret Key",pattern:/(?:aws_secret_access_key|aws_secret_key|secret_access_key)\s*[=:]\s*['"]?[A-Za-z0-9/+=]{40}['"]?/,severity:"critical"},{id:"gcp-api-key",name:"GCP API Key",pattern:/AIza[0-9A-Za-z_-]{35}/,severity:"critical"},{id:"gcp-service-account",name:"GCP Service Account",pattern:/"type"\s*:\s*"service_account"/,severity:"critical"},{id:"github-token",name:"GitHub Token",pattern:/gh[pousr]_[0-9a-zA-Z]{36,}/,severity:"critical"},{id:"github-fine-grained",name:"GitHub Fine-Grained Token",pattern:/github_pat_[0-9a-zA-Z_]{22,}/,severity:"critical"},{id:"gitlab-token",name:"GitLab Token",pattern:/glpat-[0-9a-zA-Z_-]{20,}/,severity:"critical"},{id:"stripe-secret",name:"Stripe Secret Key",pattern:/sk_live_[0-9a-zA-Z]{24,}/,severity:"critical"},{id:"stripe-restricted",name:"Stripe Restricted Key",pattern:/rk_live_[0-9a-zA-Z]{24,}/,severity:"critical"},{id:"slack-token",name:"Slack Token",pattern:/xox[baprs]-[0-9a-zA-Z-]{10,}/,severity:"high"},{id:"slack-webhook",name:"Slack Webhook",pattern:/hooks\.slack\.com\/services\/T[0-9A-Z]{8,}\/B[0-9A-Z]{8,}\/[0-9a-zA-Z]{24}/,severity:"high"},{id:"twilio-api-key",name:"Twilio API Key",pattern:/SK[0-9a-fA-F]{32}/,severity:"high"},{id:"sendgrid-api-key",name:"SendGrid API Key",pattern:/SG\.[0-9a-zA-Z_-]{22}\.[0-9a-zA-Z_-]{43}/,severity:"critical"},{id:"postgres-uri",name:"PostgreSQL Connection String",pattern:/postgres(?:ql)?:\/\/[^\s'"]{10,}/,severity:"critical"},{id:"mongodb-uri",name:"MongoDB Connection String",pattern:/mongodb(?:\+srv)?:\/\/[^\s'"]{10,}/,severity:"critical"},{id:"redis-uri",name:"Redis Connection String",pattern:/redis(?:s)?:\/\/[^\s'"]{10,}/,severity:"high"},{id:"openai-key",name:"OpenAI API Key",pattern:/sk-[0-9a-zA-Z]{20,}T3BlbkFJ[0-9a-zA-Z]{20,}/,severity:"critical"},{id:"anthropic-key",name:"Anthropic API Key",pattern:/sk-ant-[0-9a-zA-Z_-]{40,}/,severity:"critical"},{id:"firebase-key",name:"Firebase API Key",pattern:/AIza[0-9A-Za-z_-]{35}/,severity:"high"},{id:"supabase-key",name:"Supabase Service Key",pattern:/eyJ[0-9a-zA-Z_-]{100,}/,severity:"critical"},{id:"private-key",name:"Private Key",pattern:/-----BEGIN (?:RSA |EC |DSA |OPENSSH )?PRIVATE KEY-----/,severity:"critical"},{id:"jwt-secret",name:"JWT/Generic Secret",pattern:/(?:jwt_secret|JWT_SECRET|secret_key|SECRET_KEY|api_secret|API_SECRET)\s*[=:]\s*['"][^'"]{8,}['"]/,severity:"high"},{id:"password-in-code",name:"Password in Code",pattern:/(?:password|passwd|pwd)\s*[=:]\s*['"][^'"]{8,}['"]/,severity:"high"},{id:"bearer-token",name:"Bearer Token in Code",pattern:/['"]Bearer\s+[0-9a-zA-Z._-]{20,}['"]/,severity:"high"}],Ar=/node_modules\/|\.next\/|\.test\.|\.spec\.|__tests__\/|\.env\.example$|\.nodata-proof\.json$|\.git\//,ti=[{name:"lodash",below:"4.17.21",severity:"critical",cve:"CVE-2021-23337",desc:"Command injection via template"},{name:"minimist",below:"1.2.6",severity:"critical",cve:"CVE-2021-44906",desc:"Prototype pollution"},{name:"json5",below:"2.2.2",severity:"high",cve:"CVE-2022-46175",desc:"Prototype pollution"},{name:"express",below:"4.19.2",severity:"high",cve:"CVE-2024-29041",desc:"Open redirect"},{name:"path-to-regexp",below:"6.3.0",severity:"high",cve:"CVE-2024-45296",desc:"ReDoS"},{name:"sanitize-html",below:"2.12.1",severity:"high",cve:"CVE-2024-21501",desc:"XSS bypass"},{name:"dompurify",below:"3.0.9",severity:"high",cve:"CVE-2024-45801",desc:"mXSS"},{name:"jsonwebtoken",below:"9.0.0",severity:"critical",cve:"CVE-2022-23529",desc:"Key confusion attack"},{name:"jose",below:"4.15.5",severity:"high",cve:"CVE-2024-28176",desc:"DoS via JWE"},{name:"axios",below:"1.6.0",severity:"high",cve:"CVE-2023-45857",desc:"CSRF cookie leak"},{name:"node-fetch",below:"2.6.7",severity:"high",cve:"CVE-2022-0235",desc:"Header leak on redirect"},{name:"serialize-javascript",below:"6.0.2",severity:"critical",cve:"CVE-2024-11831",desc:"XSS via serialization"},{name:"xml2js",below:"0.6.0",severity:"high",cve:"CVE-2023-0842",desc:"Prototype pollution"},{name:"next",below:"14.1.1",severity:"high",cve:"CVE-2024-34350",desc:"SSRF via headers"},{name:"sharp",below:"0.32.6",severity:"high",cve:"CVE-2023-4863",desc:"libwebp heap overflow"},{name:"multer",below:"1.4.5",severity:"high",cve:"CVE-2022-24434",desc:"Prototype pollution"},{name:"tough-cookie",below:"4.1.3",severity:"medium",cve:"CVE-2023-26136",desc:"Prototype pollution"},{name:"semver",below:"7.5.4",severity:"medium",cve:"CVE-2022-25883",desc:"ReDoS"},{name:"ip",below:"2.0.1",severity:"critical",cve:"CVE-2024-29415",desc:"SSRF bypass via octal IP"},{name:"tar",below:"6.2.1",severity:"high",cve:"CVE-2024-28863",desc:"DoS via path traversal"}];function ni(e,t){let n=a=>a.replace(/^[^0-9]*/,"").split(".").map(i=>parseInt(i,10)||0),r=n(e),o=n(t);for(let a=0;a<3;a++){if((r[a]||0)<(o[a]||0))return!0;if((r[a]||0)>(o[a]||0))return!1}return!1}function Tr(e){let t=[],n;try{n=JSON.parse(e)}catch{return t}let r={...n.dependencies??{},...n.devDependencies??{}};for(let[o,a]of Object.entries(r)){let i=(a||"").replace(/^[\^~>=<\s]+/,""),s=ti.find(l=>l.name===o&&ni(i,l.below));s&&t.push({name:o,version:i,vuln:s})}return t}var ri=[{pattern:/^(full_?name|first_?name|last_?name|spouse_?name|beneficiary_?name)$/i,type:"name",label:"Person name"},{pattern:/^(email|e_?mail|email_?address)$/i,type:"email",label:"Email address"},{pattern:/^(phone|mobile|telephone|phone_?number|cell_?phone)$/i,type:"phone",label:"Phone number"},{pattern:/^(id_?number|identity|ssn|social_?security|national_?id|teudat_?zehut)$/i,type:"id",label:"ID number"},{pattern:/^(address|street_?address|home_?address)$/i,type:"address",label:"Address"},{pattern:/^(date_?of_?birth|dob|birth_?date|birthday)$/i,type:"dob",label:"Date of birth"},{pattern:/^(bank_?account|iban|account_?number|bank_?details|routing_?number)$/i,type:"financial",label:"Bank account"},{pattern:/^(credit_?card|card_?number|cvv|cc_?number)$/i,type:"financial",label:"Credit card"},{pattern:/^(salary|income|commission|premium|compensation)$/i,type:"financial",label:"Salary / income"},{pattern:/^(medical_?info|health_?conditions|diagnosis|medication|prescription)$/i,type:"medical",label:"Medical"},{pattern:/^(passport|passport_?number|passport_?id)$/i,type:"id",label:"Passport"},{pattern:/^(driver_?license|drivers_?license|dl_?number)$/i,type:"id",label:"Driver license"},{pattern:/^(tax_?id|tin|vat_?number|ein)$/i,type:"financial",label:"Tax ID"},{pattern:/^(insurance_?number|policy_?number|member_?id)$/i,type:"id",label:"Insurance/Policy"},{pattern:/^(biometric|fingerprint|face_?id|retina)$/i,type:"biometric",label:"Biometric"},{pattern:/^(latitude|longitude|lat|lng|geo_?location|coordinates)$/i,type:"location",label:"Geolocation"}],oi=[{pattern:/^(?:שם|שם_מלא|שם פרטי|שם_פרטי|שם משפחה|שם_משפחה|שם הלקוח|שם בן זוג|שם המבוטח|שם המוטב|שם הילד|שם הקטין)$/i,type:"name",label:"\u05E9\u05DD \u05D0\u05D3\u05DD"},{pattern:/^(?:ת"ז|ת\.ז|ת ז|תז|תעודת זהות|תעודת_זהות|מספר זהות|מס' זהות|teudat_zehut|tz|israeli_id|il_id)$/i,type:"id",label:"\u05EA\u05E2\u05D5\u05D3\u05EA \u05D6\u05D4\u05D5\u05EA"},{pattern:/^(?:דרכון|מספר דרכון|רישיון נהיגה|רישיון_נהיגה|רשיון נהיגה)$/i,type:"id",label:"\u05D3\u05E8\u05DB\u05D5\u05DF/\u05E8\u05D9\u05E9\u05D9\u05D5\u05DF"},{pattern:/^(?:מייל|דוא"ל|דוא_ל|דואר אלקטרוני|אימייל|כתובת מייל)$/i,type:"email",label:"\u05D3\u05D5\u05D0\u05E8 \u05D0\u05DC\u05E7\u05D8\u05E8\u05D5\u05E0\u05D9"},{pattern:/^(?:טלפון|טל'|נייד|פלאפון|סלולרי|מספר טלפון|טלפון נייד)$/i,type:"phone",label:"\u05DE\u05E1\u05E4\u05E8 \u05D8\u05DC\u05E4\u05D5\u05DF"},{pattern:/^(?:כתובת|כתובת מגורים|רחוב|מס בית|עיר|ישוב|יישוב|מיקוד|כתובת מלאה|מען)$/i,type:"address",label:"\u05DB\u05EA\u05D5\u05D1\u05EA"},{pattern:/^(?:תאריך לידה|ת לידה|תאריך הולדת|יום הולדת|גיל)$/i,type:"dob",label:"\u05EA\u05D0\u05E8\u05D9\u05DA \u05DC\u05D9\u05D3\u05D4"},{pattern:/^(?:חשבון בנק|מספר חשבון|מס חשבון|בנק|סניף|iban|iban_il)$/i,type:"financial",label:"\u05D7\u05E9\u05D1\u05D5\u05DF \u05D1\u05E0\u05E7"},{pattern:/^(?:כרטיס אשראי|מספר אשראי|cvv|אשראי)$/i,type:"financial",label:"\u05DB\u05E8\u05D8\u05D9\u05E1 \u05D0\u05E9\u05E8\u05D0\u05D9"},{pattern:/^(?:שכר|משכורת|הכנסה|פרמיה|שכר ברוטו|שכר נטו|תגמול|בונוס|פיצוי)$/i,type:"financial",label:"\u05E9\u05DB\u05E8/\u05D4\u05DB\u05E0\u05E1\u05D4"},{pattern:/^(?:אבחון|אבחנה|מחלה|תרופה|מרשם|בדיקה רפואית|מצב רפואי|חיסון|רגישות|אלרגיה|סוג דם)$/i,type:"medical",label:"\u05DE\u05D9\u05D3\u05E2 \u05E8\u05E4\u05D5\u05D0\u05D9"},{pattern:/^(?:מספר פוליסה|מס פוליסה|פוליסה|מספר חבר|מספר ביטוח)$/i,type:"id",label:"\u05E4\u05D5\u05DC\u05D9\u05E1\u05D4/\u05D7\u05D1\u05E8\u05D5\u05EA"},{pattern:/^(?:שם הילד|תעודת זהות של ילד|ילדים|קטין|מספר ילדים|תעודת לידה)$/i,type:"minor_data",label:"\u05DE\u05D9\u05D3\u05E2 \u05E2\u05DC \u05E7\u05D8\u05D9\u05DF"},{pattern:/^(?:דת|לאום|מין|נטייה מינית|השקפה פוליטית|מצב משפחתי|עדה|מוצא)$/i,type:"sensitive_personal",label:"\u05DE\u05D9\u05D3\u05E2 \u05D0\u05D9\u05E9\u05D9 \u05E8\u05D2\u05D9\u05E9"},{pattern:/^(?:מספר רכב|מס רכב|לוחית רישוי|מספר רישוי)$/i,type:"tracking",label:"\u05DE\u05E1\u05E4\u05E8 \u05E8\u05DB\u05D1"}],ai=/^(id|uuid|created_?at|updated_?at|deleted_?at|status|type|category|description|title|slug|url|path|key|value|enabled|active|public|version|metadata|config|settings|data|content|note|comment|label|color|icon)$/i;function Qe(e){if(!e)return null;let t=e.trim();if(ai.test(t)||/^name$/i.test(t))return null;for(let n of[...oi,...ri])if(n.pattern.test(t))return{type:n.type,label:n.label};return null}var dn={id:"critical",financial:"critical",medical:"critical",biometric:"critical",minor_data:"critical",sensitive_personal:"critical",email:"high",phone:"high",name:"high",address:"high",dob:"high",tracking:"medium",location:"medium"};function At(e){let t=String(e??"").replace(/\D/g,"");if(t.length===0||t.length>9)return!1;let n=t.padStart(9,"0"),r=0;for(let o=0;o<9;o++){let a=parseInt(n[o]??"0",10)*(o%2+1);a>9&&(a-=9),r+=a}return r%10===0&&parseInt(n,10)>0}var et=/(?:\+972[\s-]?|0)(?:5[0-9]|[2-4]|[89])(?:[\s-]?\d){7}/g;var tt=/\bIL\d{2}\s?(?:\d{4}\s?){4}\d{3}\b/g;function ii(e){let t=String(e??"").replace(/\D/g,"");if(t.length<12||t.length>19)return!1;let n=0,r=!1;for(let o=t.length-1;o>=0;o-=1){let a=parseInt(t[o]??"0",10);r&&(a*=2,a>9&&(a-=9)),n+=a,r=!r}return n%10===0}function si(e){let t=String(e??"").replace(/\s/g,"").toUpperCase();if(!/^[A-Z]{2}\d{2}[A-Z0-9]{10,30}$/.test(t))return!1;let n=t.slice(4)+t.slice(0,4),r=0;for(let o of n){let a=o>="A"&&o<="Z"?String(o.charCodeAt(0)-55):o;for(let i of a)r=(r*10+Number(i))%97}return r===1}var cn="(?<!\\d)(?<!\\d[.,])",ln="(?!\\d)(?![.,]\\d)",un=[{subkind:"israeli_id",severity:"high",pattern:new RegExp(`${cn}\\d{9}${ln}`,"g"),validate:At,hint:"Israeli national ID (check digit verified) in plaintext. Encrypt the column or mask it at rest."},{subkind:"credit_card",severity:"critical",pattern:new RegExp(`${cn}(?:\\d[ -]?){12,18}\\d${ln}`,"g"),validate:ii,hint:"Payment card number (Luhn verified) in plaintext. This is PCI scope."},{subkind:"iban",severity:"high",pattern:/\b[A-Z]{2}\d{2}[A-Z0-9]{10,30}\b/g,validate:si,hint:"Bank account in IBAN form (mod-97 verified) in plaintext."},{subkind:"israeli_phone",severity:"medium",pattern:new RegExp(`${cn}(?:\\+972[- ]?|0)(?:5\\d|[2-489])[- ]?\\d{3}[- ]?\\d{4}${ln}`,"g"),validate:e=>{let t=e.replace(/\D/g,"").replace(/^972/,"0");return t.length===10&&t.startsWith("0")},hint:"Israeli phone number in plaintext."}];function Pr(e){let t=[];for(let n of un){n.pattern.lastIndex=0;let r=new Set,o,a=0;for(;(o=n.pattern.exec(e))!==null&&(a+=1,!(a>2e5));){let i=o[0];if(n.validate(i)&&r.add(i.replace(/[\s-]/g,"")),r.size>=1e5)break}r.size>0&&t.push({subkind:n.subkind,severity:n.severity,hint:n.hint,count:r.size})}return t}function Be(e,t){let n=[],r="",o=!1;for(let a=0;a<e.length;a++){let i=e[a];o?i==='"'&&e[a+1]==='"'?(r+='"',a++):i==='"'?o=!1:r+=i:i==='"'?o=!0:i===t?(n.push(r),r=""):r+=i}return n.push(r),n}import{inflateRawSync as gi}from"node:zlib";import{inflateSync as ci}from"node:zlib";var pn=new Set([".pdf"]),Dr=8*1024*1024;function li(e){let t=e.toString("latin1"),n=new Map,r=/(\d+)\s+(\d+)\s+obj\b/g,o;for(;(o=r.exec(t))!==null;){let a=Number(o[1]),i=r.lastIndex,s=t.indexOf("endobj",i);if(s<0)continue;let l=t.indexOf("stream",i),d,u=null;if(l>=0&&l<s){d=t.slice(i,l);let p=l+6;t[p]==="\r"&&(p+=1),t[p]===`
16
- `&&(p+=1);let h=t.indexOf("endstream",p);h>p&&(u=e.subarray(p,h))}else d=t.slice(i,s);n.set(a,{num:a,dict:d,stream:u})}return n}function di(e){let t=e.toString("latin1").replace(/\s/g,"");t.startsWith("<~")&&(t=t.slice(2));let n=t.indexOf("~>");n>=0&&(t=t.slice(0,n));let r=[],o=0,a=0;for(let i of t){if(i==="z"&&a===0){r.push(0,0,0,0);continue}let s=i.charCodeAt(0)-33;if(s<0||s>84)return null;o=o*85+s,a+=1,a===5&&(r.push(o>>>24&255,o>>>16&255,o>>>8&255,o&255),o=0,a=0)}if(a>0){for(let s=a;s<5;s+=1)o=o*85+84;let i=[o>>>24&255,o>>>16&255,o>>>8&255,o&255];for(let s=0;s<a-1;s+=1)r.push(i[s]??0)}return Buffer.from(r)}function ui(e){let t=e.toString("latin1").replace(/\s/g,"").split(">")[0]??"",n=t.length%2?t+"0":t;return/^[0-9A-Fa-f]*$/.test(n)?Buffer.from(n,"hex"):null}function pi(e){let t=/\/Filter\s*(\[[^\]]*\]|\/\w+)/.exec(e);return!t||!t[1]?[]:[...t[1].matchAll(/\/(\w+)/g)].map(n=>n[1]??"")}function Nr(e){if(!e.stream)return null;let t=e.stream;for(let n of pi(e.dict)){let r=null;if(n==="FlateDecode")try{r=ci(t)}catch{return null}else if(n==="ASCII85Decode")r=di(t);else if(n==="ASCIIHexDecode")r=ui(t);else return null;if(r===null)return null;t=r}return t.toString("latin1")}function fi(e){let t=new Map,n=1,r=/begincodespacerange([\s\S]*?)endcodespacerange/.exec(e);if(r&&r[1]){let l=/<([0-9A-Fa-f]+)>/.exec(r[1]);l&&l[1]&&l[1].length>=4&&(n=2)}let o=l=>{let d="";for(let u=0;u+3<l.length+1;u+=4){let p=parseInt(l.slice(u,u+4),16);Number.isFinite(p)&&p>0&&(d+=String.fromCharCode(p))}return d},a=/beginbfchar([\s\S]*?)endbfchar/g,i;for(;(i=a.exec(e))!==null;){let l=/<([0-9A-Fa-f]+)>\s*<([0-9A-Fa-f]*)>/g,d;for(;(d=l.exec(i[1]??""))!==null;)t.set(parseInt(d[1]??"0",16),o(d[2]??""))}let s=/beginbfrange([\s\S]*?)endbfrange/g;for(;(i=s.exec(e))!==null;){let l=i[1]??"",d=/<([0-9A-Fa-f]+)>\s*<([0-9A-Fa-f]+)>\s*<([0-9A-Fa-f]*)>/g,u;for(;(u=d.exec(l))!==null;){let p=parseInt(u[1]??"0",16),h=parseInt(u[2]??"0",16),m=parseInt((u[3]??"0").slice(0,4)||"0",16);if(!(h-p>65535))for(let v=p;v<=h;v+=1)t.set(v,String.fromCharCode(m+(v-p)))}}return{map:t,bytes:n}}function hi(e){let t=new Map,n=new Map,r=[];for(let o of e.values()){let a=/\/Font\s*<<([\s\S]*?)>>/.exec(o.dict);a?.[1]&&r.push(a[1]);let i=/\/Font\s+(\d+)\s+\d+\s+R/.exec(o.dict);if(i){let s=e.get(Number(i[1]));s&&r.push(s.dict)}}for(let o of r){let a=/\/([^\s/<>[\]()]+)\s+(\d+)\s+\d+\s+R/g,i;for(;(i=a.exec(o))!==null;)n.set(i[1]??"",Number(i[2]))}for(let[o,a]of n){let i=e.get(a);if(!i)continue;let s=/\/ToUnicode\s+(\d+)\s+\d+\s+R/.exec(i.dict);if(!s)continue;let l=e.get(Number(s[1]));if(!l)continue;let d=Nr(l);d&&t.set(o,fi(d))}return t}function Ir(e){let t=[];for(let n=0;n<e.length;n+=1){let r=e[n];if(r!=="\\"){t.push(r.charCodeAt(0)&255);continue}let o=e[n+1];if(o===void 0)break;if(o>="0"&&o<="7"){let i="",s=n+1;for(;s<e.length&&i.length<3&&e[s]>="0"&&e[s]<="7";)i+=e[s],s+=1;t.push(parseInt(i,8)&255),n=s-1;continue}let a={n:10,r:13,t:9,b:8,f:12};t.push(a[o]??o.charCodeAt(0)&255),n+=1}return t}function Cr(e){if(e.length<2||e[0]!==254||e[1]!==255)return null;let t="";for(let n=2;n+1<e.length;n+=2)t+=String.fromCharCode((e[n]??0)<<8|(e[n+1]??0));return t}function Or(e,t){let n=Cr(e);if(n!==null)return n;if(!t)return e.map(o=>String.fromCharCode(o)).join("");let r="";if(t.bytes===2)for(let o=0;o+1<e.length;o+=2){let a=(e[o]??0)<<8|(e[o+1]??0);r+=t.map.get(a)??""}else for(let o of e)r+=t.map.get(o)??String.fromCharCode(o);return r}function yi(e,t){let n="",r,o=/\/([^\s/<>[\]()]+)\s+[\d.]+\s+Tf|\((?:\\.|[^\\)])*\)|<[0-9A-Fa-f\s]*>|TJ|Tj|'|"/g,a,i="";for(;(a=o.exec(e))!==null;){let s=a[0];if(s.endsWith("Tf")){r=t.get(a[1]??"");continue}if(s==="TJ"||s==="Tj"||s==="'"||s==='"'){i&&(n+=i+`
17
- `,i="");continue}if(s.startsWith("("))i+=Or(Ir(s.slice(1,-1)),r);else if(s.startsWith("<")){let l=s.slice(1,-1).replace(/\s+/g,""),d=[];for(let u=0;u+1<l.length;u+=2)d.push(parseInt(l.slice(u,u+2),16));i+=Or(d,r)}}return i&&(n+=i+`
18
- `),n}function mi(e,t){let n=e.toString("latin1"),r=/\/Info\s+(\d+)\s+\d+\s+R/.exec(n),o=r?t.get(Number(r[1]))?.dict:void 0;if(!o)return"";let a=[],i=/\/(Author|Title|Subject|Keywords|Creator|Producer)\s*(\((?:\\.|[^\\)])*\)|<[0-9A-Fa-f\s]*>)/g,s;for(;(s=i.exec(o))!==null;){let l=s[2]??"";if(l.startsWith("(")){let d=Ir(l.slice(1,-1));a.push(Cr(d)??d.map(u=>String.fromCharCode(u)).join(""))}else{let d=l.slice(1,-1).replace(/\s+/g,""),u="";if(d.toUpperCase().startsWith("FEFF"))for(let p=4;p+3<d.length+1;p+=4)u+=String.fromCharCode(parseInt(d.slice(p,p+4),16));else for(let p=0;p+1<d.length;p+=2)u+=String.fromCharCode(parseInt(d.slice(p,p+2),16));a.push(u)}}return a.join(`
19
- `)}function Rr(e){if(!e.subarray(0,8).toString("latin1").startsWith("%PDF-")||e.toString("latin1",0,Math.min(e.length,4096)).includes("/Encrypt"))return null;let n=li(e);if(n.size===0)return null;let r=hi(n),o=[];o.push(mi(e,n));let a=0,i=0,s=!1;for(let l of n.values()){if(!l.stream||/\/Subtype|\/Type\s*\/(XObject|Font|Metadata)|\/FontFile/.test(l.dict))continue;let d=Nr(l);if(d===null||!/(TJ|Tj)\b/.test(d))continue;let u=yi(d,r);if(u.trim().length!==0){if(i+=1,a+u.length>Dr){o.push(u.slice(0,Math.max(0,Dr-a))),s=!0;break}o.push(u),a+=u.length}}return i===0?null:{text:o.join(`
20
- `),truncated:s,streams:i}}var $r=new Set([".xlsx",".xlsm",".docx",".pptx"]),fn=8*1024*1024,_i=101010256,bi=33639248,Si=67324752;function vi(e){let t=Math.min(e.length,67584),n=-1;for(let i=e.length-22;i>=e.length-t&&i>=0;i-=1)if(e.readUInt32LE(i)===_i){n=i;break}if(n<0)return null;let r=e.readUInt16LE(n+10),o=e.readUInt32LE(n+16);if(o>=e.length)return null;let a=[];for(let i=0;i<r&&!(o+46>e.length||e.readUInt32LE(o)!==bi);i+=1){let s=e.readUInt16LE(o+10),l=e.readUInt32LE(o+20),d=e.readUInt32LE(o+24),u=e.readUInt16LE(o+28),p=e.readUInt16LE(o+30),h=e.readUInt16LE(o+32),m=e.readUInt32LE(o+42),v=e.subarray(o+46,o+46+u).toString("utf8");a.push({name:v,method:s,compSize:l,uncompSize:d,localHeaderOffset:m}),o+=46+u+p+h}return a}function wi(e,t){let n=t.localHeaderOffset;if(n+30>e.length||e.readUInt32LE(n)!==Si)return null;let r=e.readUInt16LE(n+26),o=e.readUInt16LE(n+28),a=n+30+r+o,i=a+t.compSize;if(i>e.length)return null;let s=e.subarray(a,i);try{if(t.method===0)return s.toString("utf8");if(t.method===8)return gi(s).toString("utf8")}catch{return null}return null}var Ei={"&amp;":"&","&lt;":"<","&gt;":">","&quot;":'"',"&apos;":"'"};function Br(e){return e.replace(/&(amp|lt|gt|quot|apos);/g,t=>Ei[t]??t).replace(/&#(\d+);/g,(t,n)=>{let r=Number(n);return r>0&&r<1114112?String.fromCodePoint(r):""}).replace(/&#x([0-9a-fA-F]+);/g,(t,n)=>{let r=parseInt(n,16);return r>0&&r<1114112?String.fromCodePoint(r):""})}function ki(e){return Br(e.replace(/<[^>]*>/g,`
15
+ </svg>`}function ga(e){let t="";for(let n=0;n<e.length;n++)t+=e[n].toString(16).padStart(2,"0");return t}});var Aa=C(q=>{"use strict";Object.defineProperty(q,"__esModule",{value:!0});q.DRAND_LOE_MAINNET=q.TimeGateError=void 0;q.timeGateEncrypt=Zl;q.timeGateDecrypt=Ql;q.roundForTime=ed;q.timeForRound=td;q.drandTimeLockEncrypt=rd;q.drandTimeLockDecrypt=Ea;q.makeFakeDrandChain=od;q.fetchDrandRound=xa;q.drandTimeLockOpen=id;var de=T("@noble/curves/bls12-381.js"),cn=T("@noble/hashes/sha2.js"),ke=e=>e,wa="NDC-v0.3-server-time-gate";async function Zl(e){let t=crypto.getRandomValues(new Uint8Array(12)),n=new TextEncoder().encode(`${wa}|${e.notBeforeUnixSec}`),r=await crypto.subtle.importKey("raw",ke(e.serverWrapKey),{name:"AES-GCM"},!1,["encrypt"]),o=await crypto.subtle.encrypt({name:"AES-GCM",iv:ke(t),additionalData:ke(n)},r,ke(e.plaintext));return{variant:"server-attested",notBeforeUnixSec:e.notBeforeUnixSec,iv_b64:an(t),ciphertext_b64:an(new Uint8Array(o))}}var Pt=class extends Error{constructor(t,n){super(n),this.name="TimeGateError",this.code=t}};q.TimeGateError=Pt;async function Ql(e){if(e.currentUnixSec<e.ciphertext.notBeforeUnixSec)throw new Pt("not_yet",`time-gate not yet open: now ${e.currentUnixSec} < notBefore ${e.ciphertext.notBeforeUnixSec}`);let t=new TextEncoder().encode(`${wa}|${e.ciphertext.notBeforeUnixSec}`),n=await crypto.subtle.importKey("raw",ke(e.serverWrapKey),{name:"AES-GCM"},!1,["decrypt"]);try{let r=await crypto.subtle.decrypt({name:"AES-GCM",iv:ke(sn(e.ciphertext.iv_b64)),additionalData:ke(t)},n,ke(sn(e.ciphertext.ciphertext_b64)));return new Uint8Array(r)}catch{throw new Pt("tamper_detected","AES-GCM authentication tag failed \u2014 ciphertext or AAD tampered")}}q.DRAND_LOE_MAINNET={publicKeyHex:"868f005eb8e6e4ca0a47c8a77ceaa5309a47978a7c71bc5cce96366b5d7a569937c529eeda66c7293784a9402801af31",chainHashHex:"8990e7a9aaed2ffed73dbd7092123d6f289930540d7651336225dc172e51b2ce",genesisUnixSec:1595431050,periodSec:30,hashDst:"BLS_SIG_BLS12381G2_XMD:SHA-256_SSWU_RO_NUL_"};function ed(e,t){return e<=t.genesisUnixSec?1:Math.ceil((e-t.genesisUnixSec)/t.periodSec)}function td(e,t){return t.genesisUnixSec+e*t.periodSec}function va(e){let t=new Uint8Array(8),n=e;for(let r=7;r>=0;r--)t[r]=n&255,n=Math.floor(n/256);return(0,cn.sha256)(t)}function ka(e){let t=new Uint8Array(576),n=0;for(let r of[e.c0,e.c1])for(let o of[r.c0,r.c1,r.c2])for(let a of[o.c0,o.c1])nd(a,t,n,48),n+=48;return t}function nd(e,t,n,r){let o=e,a=BigInt(255),i=BigInt(8);for(let s=r-1;s>=0;s--)t[n+s]=Number(o&a),o>>=i}function rd(e,t,n,r){if(e.length!==32)throw new Error(`drand-IBE expects a 32-byte content key, got ${e.length}`);let o=de.bls12_381.G1.Point,a=de.bls12_381.fields.Fr,i=o.fromBytes(n),s;do s=sd(crypto.getRandomValues(new Uint8Array(32)))%a.ORDER;while(s===BigInt(0));let c=o.BASE.multiply(s),d=de.bls12_381.longSignatures.hash(va(t),r.hashDst),u=i.multiply(s),p=de.bls12_381.pairing(u,d,!0),f=(0,cn.sha256)(ka(p)),y=new Uint8Array(32);for(let _=0;_<32;_++)y[_]=e[_]^f[_];return{variant:"drand-ibe",chainHashHex:r.chainHashHex,round:t,u_b64:an(c.toBytes()),v_b64:an(y)}}function Ea(e){if(e.ciphertext.variant!=="drand-ibe")throw new Error("not a drand-IBE ciphertext");if(e.ciphertext.chainHashHex!==e.chain.chainHashHex)throw new Error("chain hash mismatch \u2014 ciphertext sealed to a different drand chain");let n=de.bls12_381.G1.Point.fromBytes(sn(e.ciphertext.u_b64)),r=de.bls12_381.longSignatures.Signature.fromBytes(e.roundSignature),o=de.bls12_381.pairing(n,r,!0),a=(0,cn.sha256)(ka(o)),i=sn(e.ciphertext.v_b64);if(i.length!==32)throw new Error("drand-IBE V must be 32 bytes");let s=new Uint8Array(32);for(let c=0;c<32;c++)s[c]=i[c]^a[c];return s}function od(e){let t;if(e&&e.length===48)t=e;else{t=new Uint8Array(48);let a=e??crypto.getRandomValues(new Uint8Array(48));t.set(a.slice(0,48),0)}let{secretKey:n,publicKey:r}=de.bls12_381.longSignatures.keygen(t),o={publicKeyHex:Sa(r.toBytes()),chainHashHex:Sa((0,cn.sha256)(r.toBytes())),genesisUnixSec:17e8,periodSec:30,hashDst:"BLS_SIG_BLS12381G2_XMD:SHA-256_SSWU_RO_NUL_"};return{config:o,publicKey:r.toBytes(),signRound(a){let i=de.bls12_381.longSignatures.hash(va(a),o.hashDst);return de.bls12_381.longSignatures.sign(i,n).toBytes()}}}function Sa(e){let t="";for(let n=0;n<e.length;n++)t+=e[n].toString(16).padStart(2,"0");return t}function ad(e){if(e.length%2!==0)throw new Error("hex must have even length");let t=new Uint8Array(e.length/2);for(let n=0;n<t.length;n++)t[n]=parseInt(e.substr(n*2,2),16);return t}async function xa(e,t,n={}){let r=n.fetchImpl??fetch,o=n.timeoutMs??8e3,a=`${t.replace(/\/$/,"")}/public/${e}`,i,s;typeof AbortController<"u"&&(i=new AbortController,s=setTimeout(()=>i.abort(),o));let c;try{c=await r(a,{signal:i?.signal})}finally{s&&clearTimeout(s)}if(!c.ok)throw new Error(`drand fetch failed: ${a} \u2192 HTTP ${c.status}`);let d=await c.json();if(typeof d.round!="number"||typeof d.signature!="string"||typeof d.randomness!="string")throw new Error(`drand response malformed at ${a}`);let u=ad(d.signature);if(u.length!==96)throw new Error(`drand signature wrong length: expected 96 bytes (compressed G2), got ${u.length}`);return{round:d.round,randomness_hex:d.randomness,signature_bytes:u,previous_signature_hex:d.previous_signature}}async function id(e,t,n,r={}){let o=await xa(e.round,t,r);return Ea({ciphertext:e,roundSignature:o.signature_bytes,chain:n})}function an(e){if(typeof Buffer<"u")return Buffer.from(e).toString("base64");let t="";for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return btoa(t)}function sn(e){if(typeof Buffer<"u")return new Uint8Array(Buffer.from(e,"base64"));let t=atob(e),n=new Uint8Array(t.length);for(let r=0;r<t.length;r++)n[r]=t.charCodeAt(r);return n}function sd(e){let t=BigInt(0),n=BigInt(8);for(let r=0;r<e.length;r++)t=t<<n|BigInt(e[r]);return t}});var Oa=C(te=>{"use strict";Object.defineProperty(te,"__esModule",{value:!0});te.GENESIS_PREV_HASH=void 0;te.receiptHash=Sr;te.issueReceipt=wr;te.verifyReceipt=Na;te.auditChain=dd;te.issueGenesisReceipt=ud;te.appendReceipt=pd;var cd=T("@noble/hashes/sha2.js"),br=Zt(),Da=Ze();te.GENESIS_PREV_HASH="0".repeat(64);var Ta=e=>{if(typeof Buffer<"u")return Buffer.from(e).toString("base64");let t="";for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return btoa(t)},Pa=e=>{if(typeof Buffer<"u")return new Uint8Array(Buffer.from(e,"base64"));let t=atob(e),n=new Uint8Array(t.length);for(let r=0;r<t.length;r++)n[r]=t.charCodeAt(r);return n},ld=e=>{let t="";for(let n=0;n<e.length;n++)t+=e[n].toString(16).padStart(2,"0");return t};function Sr(e){return ld((0,cd.sha256)(new TextEncoder().encode((0,br.canonicalJson)(e))))}function wr(e){let t={event_type:e.event_type,sequence:e.sequence,iat:e.iat??new Date().toISOString(),lockbox_id:e.lockbox_id,prev_hash:e.prev_hash,payload:e.payload},n=new TextEncoder().encode((0,br.canonicalJson)(t)),r=(0,Da.hybridSign)(e.signing_key.secretKey,n);return{body:t,sig:{signer_kid:e.signer_kid,ed25519_b64:Ta(r.ed25519),ml_dsa_65_b64:Ta(r.mlDsa)}}}function Na(e,t){let n=new TextEncoder().encode((0,br.canonicalJson)(e.body)),r={ed25519:Pa(e.sig.ed25519_b64),mlDsa:Pa(e.sig.ml_dsa_65_b64)};return(0,Da.hybridVerify)(t,n,r)}function dd(e,t,n=1){if(e.length===0)return{ok:!0,receipts_checked:0};let r=n,o=n===1?te.GENESIS_PREV_HASH:null;for(let a of e){if(a.body.sequence!==r)return{ok:!1,code:a.body.sequence<r?"duplicate_sequence":"out_of_order",at_sequence:a.body.sequence,reason:`expected sequence ${r}, got ${a.body.sequence}`};if(o!==null&&a.body.prev_hash!==o)return{ok:!1,code:r===1?"missing_genesis":"broken_prev_hash",at_sequence:a.body.sequence,reason:`prev_hash mismatch: expected ${o.slice(0,16)}\u2026, got ${a.body.prev_hash.slice(0,16)}\u2026`};if(!Na(a,t))return{ok:!1,code:"bad_signature",at_sequence:a.body.sequence,reason:"hybrid signature does not verify"};o=Sr(a.body),r+=1}return{ok:!0,receipts_checked:e.length}}function ud(e){return wr({event_type:e.initial_event,lockbox_id:e.lockbox_id,prev_hash:te.GENESIS_PREV_HASH,sequence:1,payload:e.initial_payload,signer_kid:e.signer_kid,signing_key:e.signing_key,iat:e.iat})}function pd(e,t){return wr({...t,prev_hash:Sr(e.body),sequence:e.body.sequence+1})}});var Ia=C(ln=>{"use strict";Object.defineProperty(ln,"__esModule",{value:!0});ln.recommend=_d;ln.summarise=bd;var fd={healthcare:{mode:"mode-4h",ttlSeconds:3600,forensicWatermark:!0,teeAttestation:!0,rationale:"HIPAA \xB7 BAA \xB7 per-recipient attribution required"},insurance:{mode:"mode-4",ttlSeconds:28800,forensicWatermark:!0,teeAttestation:!1,rationale:"Adjusters need offline access during field visits"},bank:{mode:"mode-4h",ttlSeconds:3600,forensicWatermark:!0,teeAttestation:!1,rationale:"SOX \xB7 per-open audit \xB7 forward secrecy on signed mandates"},legal:{mode:"mode-4p",ttlSeconds:86400,forensicWatermark:!0,teeAttestation:!1,rationale:"Client privilege \xB7 approval-quorum patterns common"},government:{mode:"mode-4h",ttlSeconds:3600,forensicWatermark:!0,teeAttestation:!0,rationale:"Classified \xB7 per-open attestation \xB7 k-of-N release"},media:{mode:"mode-4p",ttlSeconds:604800,forensicWatermark:!0,teeAttestation:!1,rationale:"Source protection \xB7 leak attribution \xB7 light verification UX"},hr:{mode:"mode-4",ttlSeconds:86400,forensicWatermark:!0,teeAttestation:!1,rationale:"Performance reviews \xB7 separation packages \xB7 low compliance"},smb:{mode:"mode-4",ttlSeconds:604800,forensicWatermark:!1,teeAttestation:!1,rationale:"Cost-sensitive \xB7 low compliance overhead"}},hd={"medical-phi":{minMode:"mode-4h",maxTtlSeconds:3600,watermarkRequired:!0,selectiveDisclosure:!0,thresholdSuggested:!1,teeRequired:!0},"financial-statements":{minMode:"mode-4",maxTtlSeconds:28800,watermarkRequired:!0,selectiveDisclosure:!0,thresholdSuggested:!0,teeRequired:!1},"identity-documents":{minMode:"mode-4h",maxTtlSeconds:3600,watermarkRequired:!0,selectiveDisclosure:!0,thresholdSuggested:!1,teeRequired:!0},"legal-contracts":{minMode:"mode-4p",maxTtlSeconds:86400,watermarkRequired:!0,selectiveDisclosure:!0,thresholdSuggested:!0,teeRequired:!1},"board-materials":{minMode:"mode-4p",maxTtlSeconds:86400,watermarkRequired:!0,selectiveDisclosure:!0,thresholdSuggested:!0,teeRequired:!1},"source-code":{minMode:"mode-4h",maxTtlSeconds:3600,watermarkRequired:!0,selectiveDisclosure:!0,thresholdSuggested:!1,teeRequired:!0},marketing:{minMode:"mode-4",maxTtlSeconds:604800,watermarkRequired:!1,selectiveDisclosure:!1,thresholdSuggested:!1,teeRequired:!1},"internal-memo":{minMode:"mode-4",maxTtlSeconds:86400,watermarkRequired:!1,selectiveDisclosure:!1,thresholdSuggested:!1,teeRequired:!1},"live-ops-data":{minMode:"mode-4",maxTtlSeconds:86400,watermarkRequired:!1,selectiveDisclosure:!1,thresholdSuggested:!1,teeRequired:!1}},yd={email:{deliveryMode:"attachment",adapters:["gmail","outlook","smtp"],notes:[]},chat:{deliveryMode:"link",adapters:["whatsapp","telegram","slack","teams"],notes:["Send the ndc:// link only; file bytes never traverse the chat provider"]},"cloud-share":{deliveryMode:"link",adapters:["drive","sharepoint","dropbox","box"],notes:[]},sftp:{deliveryMode:"attachment",adapters:["sftp","ftps"],notes:["Legacy partners often require this"]},sms:{deliveryMode:"link",adapters:["sms-short-link"],notes:["Link only; SMS cannot carry binary"]},voice:{deliveryMode:"link",adapters:["voice-readback"],notes:["Voice carries the unlock factor, not the content"]},"web-portal":{deliveryMode:"link",adapters:["web-portal-pickup","embed-iframe"],notes:[]},"qr-physical":{deliveryMode:"in-person",adapters:["qr-code","usb-handoff","airdrop"],notes:["Recipient must scan / plug in physically"]},webhook:{deliveryMode:"attachment",adapters:["webhook-push"],notes:["B2B server-to-server only"]}},md=[{channel:"chat",fileClass:"medical-phi",note:"PHI over chat \u2192 link only; never attach the bytes"},{channel:"chat",fileClass:"identity-documents",note:"ID documents over chat \u2192 link only"},{channel:"chat",fileClass:"legal-contracts",note:"Legal contracts over chat are discouraged; use email/portal"},{channel:"chat",fileClass:"board-materials",note:"Board materials over chat are discouraged; use email/portal"},{channel:"chat",fileClass:"source-code",note:"Source code over chat is discouraged; use cloud-share/portal"},{channel:"cloud-share",fileClass:"identity-documents",note:"ID documents on cloud share discouraged; prefer email or portal"},{channel:"sms",fileClass:"medical-phi",note:"PHI over SMS is not compliant; reroute to web-portal"},{channel:"voice",fileClass:"medical-phi",note:"Voice only carries the unlock; the bytes must travel another channel"}],Ca={"mode-4":1,"mode-4p":2,"mode-4h":3,"mode-6":4};function gd(e,t){return Ca[e]>=Ca[t]?e:t}function _d(e){let t=fd[e.orgType],n=hd[e.fileClass],r=yd[e.channel],o=gd(t.mode,n.minMode);e.recipientLacksPasskey&&o==="mode-4h"&&(o="mode-4p");let a=Math.min(t.ttlSeconds,n.maxTtlSeconds),i={forensicWatermark:t.forensicWatermark||n.watermarkRequired,selectiveDisclosureSegments:n.selectiveDisclosure||!!e.perRecipientPolicy,thresholdKofN:e.multipleApproversRequired??null,teeAttestation:t.teeAttestation||n.teeRequired,perOpenRatchet:o==="mode-4h"||o==="mode-4p"||o==="mode-6",dpopRequired:o!=="mode-4",timelockDrand:!!e.timeLockUnixSec&&!!e.timeLockDecentralized,timelockServerGate:!!e.timeLockUnixSec&&!e.timeLockDecentralized},s={...r,adapterCandidates:[...r.adapters]},c=[...s.notes],d=md.find(u=>u.channel===e.channel&&u.fileClass===e.fileClass);return d&&(c.unshift(`\u26A0 ${d.note}`),s.deliveryMode==="attachment"&&(s.deliveryMode="link")),e.fileClass==="live-ops-data"&&e.channel==="email"&&c.push("Live ops data over email is non-standard; consider webhook-push or web-portal."),{sensitivityMode:o,cacheTtlSeconds:a,features:i,delivery:{deliveryMode:s.deliveryMode,adapterCandidates:s.adapterCandidates},notes:c}}function bd(e){let t=[e.sensitivityMode,`TTL ${e.cacheTtlSeconds}s`];return e.features.forensicWatermark&&t.push("watermark"),e.features.selectiveDisclosureSegments&&t.push("segments"),e.features.thresholdKofN&&t.push(`threshold ${e.features.thresholdKofN.k}-of-${e.features.thresholdKofN.n}`),e.features.teeAttestation&&t.push("TEE"),e.features.perOpenRatchet&&t.push("ratchet"),e.features.dpopRequired&&t.push("DPoP"),e.features.timelockDrand?t.push("drand-tlock"):e.features.timelockServerGate&&t.push("server-timegate"),t.push(`via ${e.delivery.deliveryMode} (${e.delivery.adapterCandidates.join("/")})`),t.join(" \xB7 ")}});var Ra=C(ot=>{"use strict";Object.defineProperty(ot,"__esModule",{value:!0});ot.recommendationToMandate=Ed;ot.v3SealReceiptPayload=xd;ot.v3OpenReceiptPayload=Ad;ot.showcaseChips=Td;function Sd(e){switch(e){case"mode-4":return"name_email";case"mode-4p":return"name_email";case"mode-4h":return"hardware_attest";case"mode-6":return"name_email_phone"}}function wd(e){return e.features.dpopRequired?"device_mfa":e.sensitivityMode==="mode-4h"?"first_device":e.sensitivityMode==="mode-4"?"any":"first_device"}function vd(e){return e.delivery.deliveryMode==="attachment"?"file":e.delivery.deliveryMode==="link"?"link":"view_only"}function $a(e){let t=e.delivery.adapterCandidates;return t.some(n=>n==="outlook"||n==="sharepoint"||n==="teams")?"m365":t.some(n=>n==="webhook-push"||n==="web-portal-pickup"||n==="embed-iframe")?"in_app":"capsule"}function kd(e){let t=$a(e);return t==="m365"?"m365_only":t==="in_app"?"in_app":"any"}function Ed(e){let{recommendation:t,source:n}=e,r=t.sensitivityMode==="mode-6",o=n.timeLockUnixSec?new Date(n.timeLockUnixSec*1e3).toISOString():null;return{time:{ttl_seconds:t.cacheTtlSeconds,burn_after_first_read:r,unlock_at:o,max_opens:r?1:null},identity:{capture:Sd(t.sensitivityMode),claim_required:t.sensitivityMode!=="mode-4",allow_magic_link:t.sensitivityMode==="mode-4",allowed_emails:null},device:{binding:wd(t),listed_fingerprints:null},channel:{delivery:vd(t),route:$a(t),channel_constraint:kd(t)},burn:{crypto_shred_on_burn:!0,mdm_wipe_webhook:!1,undo_window_s:0,dual_control:!!t.features.thresholdKofN},encrypt:{mode:"hpke",vault_mirror:t.features.teeAttestation,scoped_key_release:!0},proof:{signing:"ed25519",anchor:t.features.teeAttestation?"rekor":"none",c2pa_in_file:!1,ndc_seal:!0},watermark:{visible:t.features.forensicWatermark,forensic:t.features.forensicWatermark,content:t.features.forensicWatermark?"recipient_id":null,custom_text:null,forensics_lookup:t.features.forensicWatermark},ndc_v3_extensions:{profile:"pq-hybrid",suite:{kem:"X25519+ML-KEM-768",sig:"Ed25519+ML-DSA-65",aead:"AES-256-GCM",kdf:"HKDF-SHA-256"},dpop_required:t.features.dpopRequired,ratchet_enabled:t.features.perOpenRatchet,tee_attestation_required:t.features.teeAttestation,threshold_k_of_n:t.features.thresholdKofN,segments_enabled:t.features.selectiveDisclosureSegments,timelock_drand:t.features.timelockDrand,timelock_server_gate:t.features.timelockServerGate,timelock_unix_sec:n.timeLockUnixSec??null}}}function xd(e){return{event_kind:"ndc_v3_sealed",lockbox_id:e.lockbox_id,ciphertext_sha256:e.ciphertext_sha256,recipient_kid:e.recipient_kid,signer_kid:e.signer_kid,mandate:e.mandate,bytes_sealed:e.bytes_sealed,issued_at:e.issued_at??new Date().toISOString()}}function Ad(e){return{event_kind:"ndc_v3_opened",lockbox_id:e.lockbox_id,ratchet_sequence:e.ratchet_sequence,dpop_jkt:e.dpop_jkt,ip_hash:e.ip_hash,opened_at:e.opened_at??new Date().toISOString()}}function Td(e){let t=[],n=e.ndc_v3_extensions;return t.push("PQ-hybrid"),n.dpop_required&&t.push("DPoP"),n.ratchet_enabled&&t.push("per-open ratchet"),e.watermark.forensic&&t.push("forensic watermark"),n.segments_enabled&&t.push("selective disclosure"),n.threshold_k_of_n&&t.push(`${n.threshold_k_of_n.k}-of-${n.threshold_k_of_n.n} quorum`),n.tee_attestation_required&&t.push("TEE attest"),n.timelock_drand?t.push("drand time-lock"):n.timelock_server_gate&&t.push("server time-gate"),e.time.burn_after_first_read&&t.push("burn-after-read"),t}});var Ma=C(ue=>{"use strict";Object.defineProperty(ue,"__esModule",{value:!0});ue.encodeFragment=La;ue.decodeFragment=Pd;ue.extractProofToken=Dd;ue.encodeProofToken=Nd;ue.decodeShareCredential=Od;ue.sealBytesForPublicShare=$d;ue.openPublicShare=Rd;ue.wrapFragmentForShortLink=Bd;var Ba=Ze(),ja=Zt();function Ee(e){let t="";for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return btoa(t)}function Dt(e){let t=atob(e),n=new Uint8Array(t.length);for(let r=0;r<t.length;r++)n[r]=t.charCodeAt(r);return n}function Ka(e){return Ee(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function La(e){return encodeURIComponent(JSON.stringify(e))}function Pd(e){let t=JSON.parse(decodeURIComponent(e));if(t.v!==3)throw new Error(`fragment version unsupported: ${t.v}`);return t}function Dd(e){return{v:3,kind:"proof",n:e.n,t:e.t,spe:e.spe,spm:e.spm}}function Nd(e){return encodeURIComponent(JSON.stringify(e))}function Od(e){let t=e.trim(),n=t.indexOf("#"),r=n>=0?t.slice(n+1):t,o;try{o=JSON.parse(decodeURIComponent(r))}catch(a){throw new Error(`credential parse failed: ${a.message??"invalid_json"}`)}if(o.v!==3)throw new Error(`credential version unsupported: ${String(o.v)}`);return o.kind==="proof"?{kind:"proof",value:o}:{kind:"fragment",value:o}}function Cd(){let e=new Uint8Array(16);crypto.getRandomValues(e);let t="";for(let n=0;n<e.length;n++)t+=e[n].toString(16).padStart(2,"0");return t}function Id(){let e=new Uint8Array(32);return crypto.getRandomValues(e),Ka(e)}async function $d(e){let t=e.bytes,n={name:e.filename,type:e.contentType},r=(0,Ba.generateHybridKemKeypair)(),o=(0,Ba.generateHybridSigKeypair)(),a=Cd(),i=Id(),s=await(0,ja.sealHybrid)({plaintext:t,recipientPublicKey:r.publicKey,recipientKid:`ephemeral-${a}`,signerKeypair:o,signerKid:`lock-${a}`,meta:{lockbox_id:a,server:e.server,bearer:i,original_filename:n.name,original_content_type:n.type||"application/octet-stream",cache_ttl_seconds:e.ttlSeconds,dpop_required:!1,tee_attestation_url:null,ratchet_state:null}}),c=La({v:3,n:n.name,t:n.type||"application/octet-stream",rsx:Ee(r.secretKey.x25519),rsm:Ee(r.secretKey.mlKem),rpx:Ee(r.publicKey.x25519),spe:Ee(o.publicKey.ed25519),spm:Ee(o.publicKey.mlDsa)});return{container:s.container,fragment:c,lockboxId:a}}async function Rd(e){let t={x25519:Dt(e.fragment.rsx),mlKem:Dt(e.fragment.rsm)},n=Dt(e.fragment.rpx),r={ed25519:Dt(e.fragment.spe),mlDsa:Dt(e.fragment.spm)},{plaintext:o,header:a}=await(0,ja.openHybrid)({container:e.container,recipientSecretKey:t,recipientPublicX25519:n,signerPublicKey:r});return{plaintext:o,filename:a.original_filename||e.fragment.n,contentType:a.original_content_type||e.fragment.t,signerKid:a.sig.signer_kid,issuedAt:a.issued_at,ciphertextSha256:a.ciphertext_sha256}}async function Bd(e){let t=crypto.getRandomValues(new Uint8Array(32)),n=crypto.getRandomValues(new Uint8Array(12)),r=new TextEncoder().encode(e),o=new ArrayBuffer(32);new Uint8Array(o).set(t);let a=new ArrayBuffer(12);new Uint8Array(a).set(n);let i=new ArrayBuffer(r.byteLength);new Uint8Array(i).set(r);let s=await crypto.subtle.importKey("raw",o,{name:"AES-GCM"},!1,["encrypt"]),c=new Uint8Array(await crypto.subtle.encrypt({name:"AES-GCM",iv:a},s,i));return{wrapKeyB64Url:Ka(t),wrappedFragmentB64:Ee(c),wrapIvB64:Ee(n)}}});var Va=C(l=>{"use strict";var jd=l&&l.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(l,"__esModule",{value:!0});l.PVE_SIGNED_LEN=l.RCPT_VERSION=l.PVE_VERSION=l.RCPT_MAGIC=l.PVE_MAGIC=l.verifyDpop=l.publicJwkFromBytes=l.jwkThumbprint=l.createDpop=l.verifyContainerHeader=l.signContainerHeader=l.sealHybrid=l.openHybrid=l.headerSigningBytes=l.encodeContainerV3=l.decodeContainerV3=l.ContainerV3Error=l.CONTAINER_HEADER_MAX_BYTES=l.CONTAINER_FIXED_PREFIX_BYTES=l.CONTAINER_MAGIC=l.canonicalJson=l.NDC_V03_RATCHET_DOMAIN=l.NDC_V03_CONTENT_KEY_DOMAIN=l.NDC_V03_KEM_DOMAIN=l.NDC_WIRE_V03=l.NDC_WIRE_V1=l.PQ_SIZES=l.PQ_SUITE=l.ratchetAdvance=l.deriveContentKey=l.mlDsa65VerifyDetached=l.mlDsa65SignDetached=l.generateMlDsa65Keypair=l.hybridVerify=l.hybridSign=l.hybridKemDecapsulate=l.hybridKemEncapsulate=l.generateHybridSigKeypair=l.deriveHybridKemKeypairFromSeed=l.generateHybridKemKeypair=l.ALGORITHMS=l.CRYPTO_VERSION=l.NoDataSDK=l.NoDataForms=l.NoDataSystems=l.NoDataWebhook=l.NoDataEmail=l.verifyProofOfWork=l.solveProofOfWork=l.NoDataCrypto=void 0;l.auditChain=l.appendReceipt=l.timeGateEncrypt=l.timeGateDecrypt=l.timeForRound=l.TimeGateError=l.roundForTime=l.makeFakeDrandChain=l.fetchDrandRound=l.drandTimeLockOpen=l.drandTimeLockEncrypt=l.drandTimeLockDecrypt=l.DRAND_LOE_MAINNET=l.watermarkSvgOverlay=l.findLeakSource=l.computeWatermark=l.SegmentError=l.sealSegments=l.openSegments=l.manifestDigest=l.buildCapability=l.splitSecret=l.serializeShare=l.deserializeShare=l.combineShares=l.decodeAttestationPayload=l.verifyCoseSign1Es384=l.verifyAttestation=l.parseAttestation=l.fetchAttestation=l.stepRatchet=l.replayRatchet=l.destroyKey=l.verifyReceiptDelta=l.parseReceiptDelta=l.signReceiptDelta=l.encodeReceiptDeltaSignedBytes=l.verifyPve=l.pveHash=l.parsePve=l.signPve=l.encodePveSignedBytes=l.originJktForPublicKey=l.uuidFromDeltaId=l.deltaIdFromUuid=l.ABSORB_STATUS=l.DELTA_KIND=l.RCPT_TOTAL_LEN=l.RCPT_SIGNED_LEN=l.PVE_TOTAL_LEN=void 0;l.wrapFragmentForShortLink=l.openPublicShare=l.sealBytesForPublicShare=l.decodeShareCredential=l.encodeProofToken=l.extractProofToken=l.decodeFragment=l.encodeFragment=l.v3SealReceiptPayload=l.v3OpenReceiptPayload=l.showcaseChips=l.recommendationToMandate=l.summarise=l.recommend=l.verifyReceipt=l.receiptHash=l.issueReceipt=l.issueGenesisReceipt=l.GENESIS_PREV_HASH=void 0;var Kd=$e();Object.defineProperty(l,"NoDataCrypto",{enumerable:!0,get:function(){return jd(Kd).default}});var Fa=Ro();Object.defineProperty(l,"solveProofOfWork",{enumerable:!0,get:function(){return Fa.solveProofOfWork}});Object.defineProperty(l,"verifyProofOfWork",{enumerable:!0,get:function(){return Fa.verifyProofOfWork}});var Nt=jo();Object.defineProperty(l,"NoDataEmail",{enumerable:!0,get:function(){return Nt.NoDataEmail}});Object.defineProperty(l,"NoDataWebhook",{enumerable:!0,get:function(){return Nt.NoDataWebhook}});Object.defineProperty(l,"NoDataSystems",{enumerable:!0,get:function(){return Nt.NoDataSystems}});Object.defineProperty(l,"NoDataForms",{enumerable:!0,get:function(){return Nt.NoDataForms}});Object.defineProperty(l,"NoDataSDK",{enumerable:!0,get:function(){return Nt.NoDataSDK}});l.CRYPTO_VERSION="0.2.0";l.ALGORITHMS={ENCRYPTION:"AES-256-GCM",KEY_EXCHANGE:"RSA-OAEP-4096",KEY_DERIVATION:"PBKDF2-SHA256-310K",SIGNING:"Ed25519",HASHING:"SHA-256",PROOF_OF_WORK:"SHA-256-NONCE"};var j=Ze();Object.defineProperty(l,"generateHybridKemKeypair",{enumerable:!0,get:function(){return j.generateHybridKemKeypair}});Object.defineProperty(l,"deriveHybridKemKeypairFromSeed",{enumerable:!0,get:function(){return j.deriveHybridKemKeypairFromSeed}});Object.defineProperty(l,"generateHybridSigKeypair",{enumerable:!0,get:function(){return j.generateHybridSigKeypair}});Object.defineProperty(l,"hybridKemEncapsulate",{enumerable:!0,get:function(){return j.hybridKemEncapsulate}});Object.defineProperty(l,"hybridKemDecapsulate",{enumerable:!0,get:function(){return j.hybridKemDecapsulate}});Object.defineProperty(l,"hybridSign",{enumerable:!0,get:function(){return j.hybridSign}});Object.defineProperty(l,"hybridVerify",{enumerable:!0,get:function(){return j.hybridVerify}});Object.defineProperty(l,"generateMlDsa65Keypair",{enumerable:!0,get:function(){return j.generateMlDsa65Keypair}});Object.defineProperty(l,"mlDsa65SignDetached",{enumerable:!0,get:function(){return j.mlDsa65SignDetached}});Object.defineProperty(l,"mlDsa65VerifyDetached",{enumerable:!0,get:function(){return j.mlDsa65VerifyDetached}});Object.defineProperty(l,"deriveContentKey",{enumerable:!0,get:function(){return j.deriveContentKey}});Object.defineProperty(l,"ratchetAdvance",{enumerable:!0,get:function(){return j.ratchetAdvance}});Object.defineProperty(l,"PQ_SUITE",{enumerable:!0,get:function(){return j.PQ_SUITE}});Object.defineProperty(l,"PQ_SIZES",{enumerable:!0,get:function(){return j.PQ_SIZES}});Object.defineProperty(l,"NDC_WIRE_V1",{enumerable:!0,get:function(){return j.NDC_WIRE_V1}});Object.defineProperty(l,"NDC_WIRE_V03",{enumerable:!0,get:function(){return j.NDC_WIRE_V03}});Object.defineProperty(l,"NDC_V03_KEM_DOMAIN",{enumerable:!0,get:function(){return j.NDC_V03_KEM_DOMAIN}});Object.defineProperty(l,"NDC_V03_CONTENT_KEY_DOMAIN",{enumerable:!0,get:function(){return j.NDC_V03_CONTENT_KEY_DOMAIN}});Object.defineProperty(l,"NDC_V03_RATCHET_DOMAIN",{enumerable:!0,get:function(){return j.NDC_V03_RATCHET_DOMAIN}});var ne=Zt();Object.defineProperty(l,"canonicalJson",{enumerable:!0,get:function(){return ne.canonicalJson}});Object.defineProperty(l,"CONTAINER_MAGIC",{enumerable:!0,get:function(){return ne.CONTAINER_MAGIC}});Object.defineProperty(l,"CONTAINER_FIXED_PREFIX_BYTES",{enumerable:!0,get:function(){return ne.CONTAINER_FIXED_PREFIX_BYTES}});Object.defineProperty(l,"CONTAINER_HEADER_MAX_BYTES",{enumerable:!0,get:function(){return ne.CONTAINER_HEADER_MAX_BYTES}});Object.defineProperty(l,"ContainerV3Error",{enumerable:!0,get:function(){return ne.ContainerV3Error}});Object.defineProperty(l,"decodeContainerV3",{enumerable:!0,get:function(){return ne.decodeContainerV3}});Object.defineProperty(l,"encodeContainerV3",{enumerable:!0,get:function(){return ne.encodeContainerV3}});Object.defineProperty(l,"headerSigningBytes",{enumerable:!0,get:function(){return ne.headerSigningBytes}});Object.defineProperty(l,"openHybrid",{enumerable:!0,get:function(){return ne.openHybrid}});Object.defineProperty(l,"sealHybrid",{enumerable:!0,get:function(){return ne.sealHybrid}});Object.defineProperty(l,"signContainerHeader",{enumerable:!0,get:function(){return ne.signContainerHeader}});Object.defineProperty(l,"verifyContainerHeader",{enumerable:!0,get:function(){return ne.verifyContainerHeader}});var dn=ur();Object.defineProperty(l,"createDpop",{enumerable:!0,get:function(){return dn.createDpop}});Object.defineProperty(l,"jwkThumbprint",{enumerable:!0,get:function(){return dn.jwkThumbprint}});Object.defineProperty(l,"publicJwkFromBytes",{enumerable:!0,get:function(){return dn.publicJwkFromBytes}});Object.defineProperty(l,"verifyDpop",{enumerable:!0,get:function(){return dn.verifyDpop}});var R=oa();Object.defineProperty(l,"PVE_MAGIC",{enumerable:!0,get:function(){return R.PVE_MAGIC}});Object.defineProperty(l,"RCPT_MAGIC",{enumerable:!0,get:function(){return R.RCPT_MAGIC}});Object.defineProperty(l,"PVE_VERSION",{enumerable:!0,get:function(){return R.PVE_VERSION}});Object.defineProperty(l,"RCPT_VERSION",{enumerable:!0,get:function(){return R.RCPT_VERSION}});Object.defineProperty(l,"PVE_SIGNED_LEN",{enumerable:!0,get:function(){return R.PVE_SIGNED_LEN}});Object.defineProperty(l,"PVE_TOTAL_LEN",{enumerable:!0,get:function(){return R.PVE_TOTAL_LEN}});Object.defineProperty(l,"RCPT_SIGNED_LEN",{enumerable:!0,get:function(){return R.RCPT_SIGNED_LEN}});Object.defineProperty(l,"RCPT_TOTAL_LEN",{enumerable:!0,get:function(){return R.RCPT_TOTAL_LEN}});Object.defineProperty(l,"DELTA_KIND",{enumerable:!0,get:function(){return R.DELTA_KIND}});Object.defineProperty(l,"ABSORB_STATUS",{enumerable:!0,get:function(){return R.ABSORB_STATUS}});Object.defineProperty(l,"deltaIdFromUuid",{enumerable:!0,get:function(){return R.deltaIdFromUuid}});Object.defineProperty(l,"uuidFromDeltaId",{enumerable:!0,get:function(){return R.uuidFromDeltaId}});Object.defineProperty(l,"originJktForPublicKey",{enumerable:!0,get:function(){return R.originJktForPublicKey}});Object.defineProperty(l,"encodePveSignedBytes",{enumerable:!0,get:function(){return R.encodePveSignedBytes}});Object.defineProperty(l,"signPve",{enumerable:!0,get:function(){return R.signPve}});Object.defineProperty(l,"parsePve",{enumerable:!0,get:function(){return R.parsePve}});Object.defineProperty(l,"pveHash",{enumerable:!0,get:function(){return R.pveHash}});Object.defineProperty(l,"verifyPve",{enumerable:!0,get:function(){return R.verifyPve}});Object.defineProperty(l,"encodeReceiptDeltaSignedBytes",{enumerable:!0,get:function(){return R.encodeReceiptSignedBytes}});Object.defineProperty(l,"signReceiptDelta",{enumerable:!0,get:function(){return R.signReceipt}});Object.defineProperty(l,"parseReceiptDelta",{enumerable:!0,get:function(){return R.parseReceipt}});Object.defineProperty(l,"verifyReceiptDelta",{enumerable:!0,get:function(){return R.verifyReceipt}});var vr=ia();Object.defineProperty(l,"destroyKey",{enumerable:!0,get:function(){return vr.destroyKey}});Object.defineProperty(l,"replayRatchet",{enumerable:!0,get:function(){return vr.replayRatchet}});Object.defineProperty(l,"stepRatchet",{enumerable:!0,get:function(){return vr.stepRatchet}});var kr=la();Object.defineProperty(l,"fetchAttestation",{enumerable:!0,get:function(){return kr.fetchAttestation}});Object.defineProperty(l,"parseAttestation",{enumerable:!0,get:function(){return kr.parseAttestation}});Object.defineProperty(l,"verifyAttestation",{enumerable:!0,get:function(){return kr.verifyAttestation}});var Ua=gr();Object.defineProperty(l,"verifyCoseSign1Es384",{enumerable:!0,get:function(){return Ua.verifyCoseSign1Es384}});Object.defineProperty(l,"decodeAttestationPayload",{enumerable:!0,get:function(){return Ua.decodeAttestationPayload}});var un=pa();Object.defineProperty(l,"combineShares",{enumerable:!0,get:function(){return un.combineShares}});Object.defineProperty(l,"deserializeShare",{enumerable:!0,get:function(){return un.deserializeShare}});Object.defineProperty(l,"serializeShare",{enumerable:!0,get:function(){return un.serializeShare}});Object.defineProperty(l,"splitSecret",{enumerable:!0,get:function(){return un.splitSecret}});var Ot=ma();Object.defineProperty(l,"buildCapability",{enumerable:!0,get:function(){return Ot.buildCapability}});Object.defineProperty(l,"manifestDigest",{enumerable:!0,get:function(){return Ot.manifestDigest}});Object.defineProperty(l,"openSegments",{enumerable:!0,get:function(){return Ot.openSegments}});Object.defineProperty(l,"sealSegments",{enumerable:!0,get:function(){return Ot.sealSegments}});Object.defineProperty(l,"SegmentError",{enumerable:!0,get:function(){return Ot.SegmentError}});var Er=ba();Object.defineProperty(l,"computeWatermark",{enumerable:!0,get:function(){return Er.computeWatermark}});Object.defineProperty(l,"findLeakSource",{enumerable:!0,get:function(){return Er.findLeakSource}});Object.defineProperty(l,"watermarkSvgOverlay",{enumerable:!0,get:function(){return Er.watermarkSvgOverlay}});var ae=Aa();Object.defineProperty(l,"DRAND_LOE_MAINNET",{enumerable:!0,get:function(){return ae.DRAND_LOE_MAINNET}});Object.defineProperty(l,"drandTimeLockDecrypt",{enumerable:!0,get:function(){return ae.drandTimeLockDecrypt}});Object.defineProperty(l,"drandTimeLockEncrypt",{enumerable:!0,get:function(){return ae.drandTimeLockEncrypt}});Object.defineProperty(l,"drandTimeLockOpen",{enumerable:!0,get:function(){return ae.drandTimeLockOpen}});Object.defineProperty(l,"fetchDrandRound",{enumerable:!0,get:function(){return ae.fetchDrandRound}});Object.defineProperty(l,"makeFakeDrandChain",{enumerable:!0,get:function(){return ae.makeFakeDrandChain}});Object.defineProperty(l,"roundForTime",{enumerable:!0,get:function(){return ae.roundForTime}});Object.defineProperty(l,"TimeGateError",{enumerable:!0,get:function(){return ae.TimeGateError}});Object.defineProperty(l,"timeForRound",{enumerable:!0,get:function(){return ae.timeForRound}});Object.defineProperty(l,"timeGateDecrypt",{enumerable:!0,get:function(){return ae.timeGateDecrypt}});Object.defineProperty(l,"timeGateEncrypt",{enumerable:!0,get:function(){return ae.timeGateEncrypt}});var Me=Oa();Object.defineProperty(l,"appendReceipt",{enumerable:!0,get:function(){return Me.appendReceipt}});Object.defineProperty(l,"auditChain",{enumerable:!0,get:function(){return Me.auditChain}});Object.defineProperty(l,"GENESIS_PREV_HASH",{enumerable:!0,get:function(){return Me.GENESIS_PREV_HASH}});Object.defineProperty(l,"issueGenesisReceipt",{enumerable:!0,get:function(){return Me.issueGenesisReceipt}});Object.defineProperty(l,"issueReceipt",{enumerable:!0,get:function(){return Me.issueReceipt}});Object.defineProperty(l,"receiptHash",{enumerable:!0,get:function(){return Me.receiptHash}});Object.defineProperty(l,"verifyReceipt",{enumerable:!0,get:function(){return Me.verifyReceipt}});var Ha=Ia();Object.defineProperty(l,"recommend",{enumerable:!0,get:function(){return Ha.recommend}});Object.defineProperty(l,"summarise",{enumerable:!0,get:function(){return Ha.summarise}});var pn=Ra();Object.defineProperty(l,"recommendationToMandate",{enumerable:!0,get:function(){return pn.recommendationToMandate}});Object.defineProperty(l,"showcaseChips",{enumerable:!0,get:function(){return pn.showcaseChips}});Object.defineProperty(l,"v3OpenReceiptPayload",{enumerable:!0,get:function(){return pn.v3OpenReceiptPayload}});Object.defineProperty(l,"v3SealReceiptPayload",{enumerable:!0,get:function(){return pn.v3SealReceiptPayload}});var xe=Ma();Object.defineProperty(l,"encodeFragment",{enumerable:!0,get:function(){return xe.encodeFragment}});Object.defineProperty(l,"decodeFragment",{enumerable:!0,get:function(){return xe.decodeFragment}});Object.defineProperty(l,"extractProofToken",{enumerable:!0,get:function(){return xe.extractProofToken}});Object.defineProperty(l,"encodeProofToken",{enumerable:!0,get:function(){return xe.encodeProofToken}});Object.defineProperty(l,"decodeShareCredential",{enumerable:!0,get:function(){return xe.decodeShareCredential}});Object.defineProperty(l,"sealBytesForPublicShare",{enumerable:!0,get:function(){return xe.sealBytesForPublicShare}});Object.defineProperty(l,"openPublicShare",{enumerable:!0,get:function(){return xe.openPublicShare}});Object.defineProperty(l,"wrapFragmentForShortLink",{enumerable:!0,get:function(){return xe.wrapFragmentForShortLink}})});import{McpServer as $u}from"@modelcontextprotocol/sdk/server/mcp.js";import{StdioServerTransport as Ru}from"@modelcontextprotocol/sdk/server/stdio.js";import{z as h}from"zod";import{z as _e}from"zod";import{readdirSync as ao,readFileSync as io,statSync as Cn}from"node:fs";import{join as Ps}from"node:path";var jt=[{id:"aws-access-key",name:"AWS Access Key",pattern:/(?:^|[^A-Z0-9])AKIA[A-Z2-7]{16}(?:[^A-Z2-7]|$)/,severity:"critical"},{id:"aws-secret-key",name:"AWS Secret Key",pattern:/(?:aws_secret_access_key|aws_secret_key|secret_access_key)\s*[=:]\s*['"]?[A-Za-z0-9/+=]{40}['"]?/,severity:"critical"},{id:"gcp-api-key",name:"GCP API Key",pattern:/AIza[0-9A-Za-z_-]{35}/,severity:"critical"},{id:"gcp-service-account",name:"GCP Service Account",pattern:/"type"\s*:\s*"service_account"/,severity:"critical"},{id:"github-token",name:"GitHub Token",pattern:/gh[pousr]_[0-9a-zA-Z]{36,}/,severity:"critical"},{id:"github-fine-grained",name:"GitHub Fine-Grained Token",pattern:/github_pat_[0-9a-zA-Z_]{22,}/,severity:"critical"},{id:"gitlab-token",name:"GitLab Token",pattern:/glpat-[0-9a-zA-Z_-]{20,}/,severity:"critical"},{id:"stripe-secret",name:"Stripe Secret Key",pattern:/sk_live_[0-9a-zA-Z]{24,}/,severity:"critical"},{id:"stripe-restricted",name:"Stripe Restricted Key",pattern:/rk_live_[0-9a-zA-Z]{24,}/,severity:"critical"},{id:"slack-token",name:"Slack Token",pattern:/xox[baprs]-[0-9a-zA-Z-]{10,}/,severity:"high"},{id:"slack-webhook",name:"Slack Webhook",pattern:/hooks\.slack\.com\/services\/T[0-9A-Z]{8,}\/B[0-9A-Z]{8,}\/[0-9a-zA-Z]{24}/,severity:"high"},{id:"twilio-api-key",name:"Twilio API Key",pattern:/SK[0-9a-fA-F]{32}/,severity:"high"},{id:"sendgrid-api-key",name:"SendGrid API Key",pattern:/SG\.[0-9a-zA-Z_-]{22}\.[0-9a-zA-Z_-]{43}/,severity:"critical"},{id:"postgres-uri",name:"PostgreSQL Connection String",pattern:/postgres(?:ql)?:\/\/[^\s'"]{10,}/,severity:"critical"},{id:"mongodb-uri",name:"MongoDB Connection String",pattern:/mongodb(?:\+srv)?:\/\/[^\s'"]{10,}/,severity:"critical"},{id:"redis-uri",name:"Redis Connection String",pattern:/redis(?:s)?:\/\/[^\s'"]{10,}/,severity:"high"},{id:"openai-key",name:"OpenAI API Key",pattern:/sk-[0-9a-zA-Z]{20,}T3BlbkFJ[0-9a-zA-Z]{20,}/,severity:"critical"},{id:"anthropic-key",name:"Anthropic API Key",pattern:/sk-ant-[0-9a-zA-Z_-]{40,}/,severity:"critical"},{id:"firebase-key",name:"Firebase API Key",pattern:/AIza[0-9A-Za-z_-]{35}/,severity:"high"},{id:"supabase-key",name:"Supabase Service Key",pattern:/eyJ[0-9a-zA-Z_-]{100,}/,severity:"critical"},{id:"private-key",name:"Private Key",pattern:/-----BEGIN (?:RSA |EC |DSA |OPENSSH )?PRIVATE KEY-----/,severity:"critical"},{id:"jwt-secret",name:"JWT/Generic Secret",pattern:/(?:jwt_secret|JWT_SECRET|secret_key|SECRET_KEY|api_secret|API_SECRET)\s*[=:]\s*['"][^'"]{8,}['"]/,severity:"high"},{id:"password-in-code",name:"Password in Code",pattern:/(?:password|passwd|pwd)\s*[=:]\s*['"][^'"]{8,}['"]/,severity:"high"},{id:"bearer-token",name:"Bearer Token in Code",pattern:/['"]Bearer\s+[0-9a-zA-Z._-]{20,}['"]/,severity:"high"}],zr=/node_modules\/|\.next\/|\.test\.|\.spec\.|__tests__\/|\.env\.example$|\.nodata-proof\.json$|\.git\//,ns=[{name:"lodash",below:"4.17.21",severity:"critical",cve:"CVE-2021-23337",desc:"Command injection via template"},{name:"minimist",below:"1.2.6",severity:"critical",cve:"CVE-2021-44906",desc:"Prototype pollution"},{name:"json5",below:"2.2.2",severity:"high",cve:"CVE-2022-46175",desc:"Prototype pollution"},{name:"express",below:"4.19.2",severity:"high",cve:"CVE-2024-29041",desc:"Open redirect"},{name:"path-to-regexp",below:"6.3.0",severity:"high",cve:"CVE-2024-45296",desc:"ReDoS"},{name:"sanitize-html",below:"2.12.1",severity:"high",cve:"CVE-2024-21501",desc:"XSS bypass"},{name:"dompurify",below:"3.0.9",severity:"high",cve:"CVE-2024-45801",desc:"mXSS"},{name:"jsonwebtoken",below:"9.0.0",severity:"critical",cve:"CVE-2022-23529",desc:"Key confusion attack"},{name:"jose",below:"4.15.5",severity:"high",cve:"CVE-2024-28176",desc:"DoS via JWE"},{name:"axios",below:"1.6.0",severity:"high",cve:"CVE-2023-45857",desc:"CSRF cookie leak"},{name:"node-fetch",below:"2.6.7",severity:"high",cve:"CVE-2022-0235",desc:"Header leak on redirect"},{name:"serialize-javascript",below:"6.0.2",severity:"critical",cve:"CVE-2024-11831",desc:"XSS via serialization"},{name:"xml2js",below:"0.6.0",severity:"high",cve:"CVE-2023-0842",desc:"Prototype pollution"},{name:"next",below:"14.1.1",severity:"high",cve:"CVE-2024-34350",desc:"SSRF via headers"},{name:"sharp",below:"0.32.6",severity:"high",cve:"CVE-2023-4863",desc:"libwebp heap overflow"},{name:"multer",below:"1.4.5",severity:"high",cve:"CVE-2022-24434",desc:"Prototype pollution"},{name:"tough-cookie",below:"4.1.3",severity:"medium",cve:"CVE-2023-26136",desc:"Prototype pollution"},{name:"semver",below:"7.5.4",severity:"medium",cve:"CVE-2022-25883",desc:"ReDoS"},{name:"ip",below:"2.0.1",severity:"critical",cve:"CVE-2024-29415",desc:"SSRF bypass via octal IP"},{name:"tar",below:"6.2.1",severity:"high",cve:"CVE-2024-28863",desc:"DoS via path traversal"}];function rs(e,t){let n=a=>a.replace(/^[^0-9]*/,"").split(".").map(i=>parseInt(i,10)||0),r=n(e),o=n(t);for(let a=0;a<3;a++){if((r[a]||0)<(o[a]||0))return!0;if((r[a]||0)>(o[a]||0))return!1}return!1}function Yr(e){let t=[],n;try{n=JSON.parse(e)}catch{return t}let r={...n.dependencies??{},...n.devDependencies??{}};for(let[o,a]of Object.entries(r)){let i=(a||"").replace(/^[\^~>=<\s]+/,""),s=ns.find(c=>c.name===o&&rs(i,c.below));s&&t.push({name:o,version:i,vuln:s})}return t}var os=[{pattern:/^(full_?name|first_?name|last_?name|spouse_?name|beneficiary_?name)$/i,type:"name",label:"Person name"},{pattern:/^(email|e_?mail|email_?address)$/i,type:"email",label:"Email address"},{pattern:/^(phone|mobile|telephone|phone_?number|cell_?phone)$/i,type:"phone",label:"Phone number"},{pattern:/^(id_?number|identity|ssn|social_?security|national_?id|teudat_?zehut)$/i,type:"id",label:"ID number"},{pattern:/^(address|street_?address|home_?address)$/i,type:"address",label:"Address"},{pattern:/^(date_?of_?birth|dob|birth_?date|birthday)$/i,type:"dob",label:"Date of birth"},{pattern:/^(bank_?account|iban|account_?number|bank_?details|routing_?number)$/i,type:"financial",label:"Bank account"},{pattern:/^(credit_?card|card_?number|cvv|cc_?number)$/i,type:"financial",label:"Credit card"},{pattern:/^(salary|income|commission|premium|compensation)$/i,type:"financial",label:"Salary / income"},{pattern:/^(medical_?info|health_?conditions|diagnosis|medication|prescription)$/i,type:"medical",label:"Medical"},{pattern:/^(passport|passport_?number|passport_?id)$/i,type:"id",label:"Passport"},{pattern:/^(driver_?license|drivers_?license|dl_?number)$/i,type:"id",label:"Driver license"},{pattern:/^(tax_?id|tin|vat_?number|ein)$/i,type:"financial",label:"Tax ID"},{pattern:/^(insurance_?number|policy_?number|member_?id)$/i,type:"id",label:"Insurance/Policy"},{pattern:/^(biometric|fingerprint|face_?id|retina)$/i,type:"biometric",label:"Biometric"},{pattern:/^(latitude|longitude|lat|lng|geo_?location|coordinates)$/i,type:"location",label:"Geolocation"}],as=[{pattern:/^(?:שם|שם_מלא|שם פרטי|שם_פרטי|שם משפחה|שם_משפחה|שם הלקוח|שם בן זוג|שם המבוטח|שם המוטב|שם הילד|שם הקטין)$/i,type:"name",label:"\u05E9\u05DD \u05D0\u05D3\u05DD"},{pattern:/^(?:ת"ז|ת\.ז|ת ז|תז|תעודת זהות|תעודת_זהות|מספר זהות|מס' זהות|teudat_zehut|tz|israeli_id|il_id)$/i,type:"id",label:"\u05EA\u05E2\u05D5\u05D3\u05EA \u05D6\u05D4\u05D5\u05EA"},{pattern:/^(?:דרכון|מספר דרכון|רישיון נהיגה|רישיון_נהיגה|רשיון נהיגה)$/i,type:"id",label:"\u05D3\u05E8\u05DB\u05D5\u05DF/\u05E8\u05D9\u05E9\u05D9\u05D5\u05DF"},{pattern:/^(?:מייל|דוא"ל|דוא_ל|דואר אלקטרוני|אימייל|כתובת מייל)$/i,type:"email",label:"\u05D3\u05D5\u05D0\u05E8 \u05D0\u05DC\u05E7\u05D8\u05E8\u05D5\u05E0\u05D9"},{pattern:/^(?:טלפון|טל'|נייד|פלאפון|סלולרי|מספר טלפון|טלפון נייד)$/i,type:"phone",label:"\u05DE\u05E1\u05E4\u05E8 \u05D8\u05DC\u05E4\u05D5\u05DF"},{pattern:/^(?:כתובת|כתובת מגורים|רחוב|מס בית|עיר|ישוב|יישוב|מיקוד|כתובת מלאה|מען)$/i,type:"address",label:"\u05DB\u05EA\u05D5\u05D1\u05EA"},{pattern:/^(?:תאריך לידה|ת לידה|תאריך הולדת|יום הולדת|גיל)$/i,type:"dob",label:"\u05EA\u05D0\u05E8\u05D9\u05DA \u05DC\u05D9\u05D3\u05D4"},{pattern:/^(?:חשבון בנק|מספר חשבון|מס חשבון|סניף|iban|iban_il)$/i,type:"financial",label:"\u05D7\u05E9\u05D1\u05D5\u05DF \u05D1\u05E0\u05E7"},{pattern:/^(?:כרטיס אשראי|מספר אשראי|cvv|אשראי)$/i,type:"financial",label:"\u05DB\u05E8\u05D8\u05D9\u05E1 \u05D0\u05E9\u05E8\u05D0\u05D9"},{pattern:/^(?:שכר|משכורת|הכנסה|פרמיה|שכר ברוטו|שכר נטו|תגמול|בונוס|פיצוי)$/i,type:"financial",label:"\u05E9\u05DB\u05E8/\u05D4\u05DB\u05E0\u05E1\u05D4"},{pattern:/^(?:אבחון|אבחנה|מחלה|תרופה|מרשם|בדיקה רפואית|מצב רפואי|חיסון|רגישות|אלרגיה|סוג דם)$/i,type:"medical",label:"\u05DE\u05D9\u05D3\u05E2 \u05E8\u05E4\u05D5\u05D0\u05D9"},{pattern:/^(?:מספר פוליסה|מס פוליסה|פוליסה|מספר חבר|מספר ביטוח)$/i,type:"id",label:"\u05E4\u05D5\u05DC\u05D9\u05E1\u05D4/\u05D7\u05D1\u05E8\u05D5\u05EA"},{pattern:/^(?:שם הילד|תעודת זהות של ילד|ילדים|קטין|מספר ילדים|תעודת לידה)$/i,type:"minor_data",label:"\u05DE\u05D9\u05D3\u05E2 \u05E2\u05DC \u05E7\u05D8\u05D9\u05DF"},{pattern:/^(?:דת|לאום|מין|נטייה מינית|השקפה פוליטית|מצב משפחתי|עדה|מוצא)$/i,type:"sensitive_personal",label:"\u05DE\u05D9\u05D3\u05E2 \u05D0\u05D9\u05E9\u05D9 \u05E8\u05D2\u05D9\u05E9"},{pattern:/^(?:מספר רכב|מס רכב|לוחית רישוי|מספר רישוי)$/i,type:"tracking",label:"\u05DE\u05E1\u05E4\u05E8 \u05E8\u05DB\u05D1"}],is=/^(id|uuid|created_?at|updated_?at|deleted_?at|status|type|category|description|title|slug|url|path|key|value|enabled|active|public|version|metadata|config|settings|data|content|note|comment|label|color|icon)$/i;function Ne(e){if(!e)return null;let t=e.trim();if(is.test(t)||/^name$/i.test(t))return null;let n=t.replace(/[\s-]+/g,"_");for(let r of[...as,...os])if(r.pattern.test(t)||r.pattern.test(n))return{type:r.type,label:r.label};return null}var An={id:"critical",financial:"critical",medical:"critical",biometric:"critical",minor_data:"critical",sensitive_personal:"critical",email:"high",phone:"high",name:"high",address:"high",dob:"high",tracking:"medium",location:"medium"};function Kt(e){let t=String(e??"").replace(/\D/g,"");if(t.length===0||t.length>9)return!1;let n=t.padStart(9,"0"),r=0;for(let o=0;o<9;o++){let a=parseInt(n[o]??"0",10)*(o%2+1);a>9&&(a-=9),r+=a}return r%10===0&&parseInt(n,10)>0}var st=/(?:\+972[\s-]?|0)(?:5[0-9]|[2-4]|[89])(?:[\s-]?\d){7}/g;var ct=/\bIL\d{2}\s?(?:\d{4}\s?){4}\d{3}\b/g;function ss(e){let t=String(e??"").replace(/\D/g,"");if(t.length<12||t.length>19)return!1;let n=0,r=!1;for(let o=t.length-1;o>=0;o-=1){let a=parseInt(t[o]??"0",10);r&&(a*=2,a>9&&(a-=9)),n+=a,r=!r}return n%10===0}function cs(e){let t=String(e??"").replace(/\s/g,"").toUpperCase();if(!/^[A-Z]{2}\d{2}[A-Z0-9]{10,30}$/.test(t))return!1;let n=t.slice(4)+t.slice(0,4),r=0;for(let o of n){let a=o>="A"&&o<="Z"?String(o.charCodeAt(0)-55):o;for(let i of a)r=(r*10+Number(i))%97}return r===1}var En="(?<!\\d)(?<!\\d[.,])",xn="(?!\\d)(?![.,]\\d)",Tn=[{subkind:"israeli_id",severity:"high",pattern:new RegExp(`${En}\\d{9}${xn}`,"g"),validate:Kt,hint:"Israeli national ID (check digit verified) in plaintext. Encrypt the column or mask it at rest."},{subkind:"credit_card",severity:"critical",pattern:new RegExp(`${En}[2-6][ -]?(?:\\d[ -]?){11,17}\\d${xn}`,"g"),validate:ss,hint:"Payment card number (Luhn verified) in plaintext. This is PCI scope."},{subkind:"iban",severity:"high",pattern:/\b[A-Z]{2}\d{2}(?: ?[A-Z0-9]{4}){2,7}(?: ?[A-Z0-9]{1,4})?\b/g,validate:cs,hint:"Bank account in IBAN form (mod-97 verified) in plaintext."},{subkind:"israeli_phone",severity:"medium",pattern:new RegExp(`${En}(?:\\+972[- ]?|0)(?:[57]\\d|[2-489])[- ]?\\d{3}[- ]?\\d{4}${xn}`,"g"),validate:e=>{let t=e.replace(/\D/g,"").replace(/^972/,"0");return/^0[57]\d{8}$/.test(t)?!0:/^0[2-489]\d{7}$/.test(t)&&(/[- ]/.test(e)||e.startsWith("+972"))},hint:"Israeli phone number in plaintext."}];function Xr(e){let t=[];for(let n of Tn){n.pattern.lastIndex=0;let r=new Set,o,a=0;for(;(o=n.pattern.exec(e))!==null&&(a+=1,!(a>2e5));){let i=o[0];if(n.validate(i)&&r.add(i.replace(/[\s-]/g,"")),r.size>=1e5)break}r.size>0&&t.push({subkind:n.subkind,severity:n.severity,hint:n.hint,count:r.size})}return t}function Ue(e,t){let n=[],r="",o=!1;for(let a=0;a<e.length;a++){let i=e[a];o?i==='"'&&e[a+1]==='"'?(r+='"',a++):i==='"'?o=!1:r+=i:i==='"'?o=!0:i===t?(n.push(r),r=""):r+=i}return n.push(r),n}import{inflateRawSync as _s}from"node:zlib";import{inflateSync as ls}from"node:zlib";var Pn=new Set([".pdf"]),Zr=8*1024*1024;function ds(e){let t=e.toString("latin1"),n=new Map,r=/(\d+)\s+(\d+)\s+obj\b/g,o;for(;(o=r.exec(t))!==null;){let a=Number(o[1]),i=r.lastIndex,s=t.indexOf("endobj",i);if(s<0)continue;let c=t.indexOf("stream",i),d,u=null;if(c>=0&&c<s){d=t.slice(i,c);let p=c+6;t[p]==="\r"&&(p+=1),t[p]===`
16
+ `&&(p+=1);let f=t.indexOf("endstream",p);f>p&&(u=e.subarray(p,f))}else d=t.slice(i,s);n.set(a,{num:a,dict:d,stream:u})}return n}function us(e){let t=e.toString("latin1").replace(/\s/g,"");t.startsWith("<~")&&(t=t.slice(2));let n=t.indexOf("~>");n>=0&&(t=t.slice(0,n));let r=[],o=0,a=0;for(let i of t){if(i==="z"&&a===0){r.push(0,0,0,0);continue}let s=i.charCodeAt(0)-33;if(s<0||s>84)return null;o=o*85+s,a+=1,a===5&&(r.push(o>>>24&255,o>>>16&255,o>>>8&255,o&255),o=0,a=0)}if(a>0){for(let s=a;s<5;s+=1)o=o*85+84;let i=[o>>>24&255,o>>>16&255,o>>>8&255,o&255];for(let s=0;s<a-1;s+=1)r.push(i[s]??0)}return Buffer.from(r)}function ps(e){let t=e.toString("latin1").replace(/\s/g,"").split(">")[0]??"",n=t.length%2?t+"0":t;return/^[0-9A-Fa-f]*$/.test(n)?Buffer.from(n,"hex"):null}function fs(e){let t=/\/Filter\s*(\[[^\]]*\]|\/\w+)/.exec(e);return!t||!t[1]?[]:[...t[1].matchAll(/\/(\w+)/g)].map(n=>n[1]??"")}function eo(e){if(!e.stream)return null;let t=e.stream;for(let n of fs(e.dict)){let r=null;if(n==="FlateDecode")try{r=ls(t)}catch{return null}else if(n==="ASCII85Decode")r=us(t);else if(n==="ASCIIHexDecode")r=ps(t);else return null;if(r===null)return null;t=r}return t.toString("latin1")}function hs(e){let t=new Map,n=1,r=/begincodespacerange([\s\S]*?)endcodespacerange/.exec(e);if(r&&r[1]){let c=/<([0-9A-Fa-f]+)>/.exec(r[1]);c&&c[1]&&c[1].length>=4&&(n=2)}let o=c=>{let d="";for(let u=0;u+3<c.length+1;u+=4){let p=parseInt(c.slice(u,u+4),16);Number.isFinite(p)&&p>0&&(d+=String.fromCharCode(p))}return d},a=/beginbfchar([\s\S]*?)endbfchar/g,i;for(;(i=a.exec(e))!==null;){let c=/<([0-9A-Fa-f]+)>\s*<([0-9A-Fa-f]*)>/g,d;for(;(d=c.exec(i[1]??""))!==null;)t.set(parseInt(d[1]??"0",16),o(d[2]??""))}let s=/beginbfrange([\s\S]*?)endbfrange/g;for(;(i=s.exec(e))!==null;){let c=i[1]??"",d=/<([0-9A-Fa-f]+)>\s*<([0-9A-Fa-f]+)>\s*<([0-9A-Fa-f]*)>/g,u;for(;(u=d.exec(c))!==null;){let p=parseInt(u[1]??"0",16),f=parseInt(u[2]??"0",16),y=parseInt((u[3]??"0").slice(0,4)||"0",16);if(!(f-p>65535))for(let _=p;_<=f;_+=1)t.set(_,String.fromCharCode(y+(_-p)))}}return{map:t,bytes:n}}function ys(e){let t=new Map,n=new Map,r=[];for(let o of e.values()){let a=/\/Font\s*<<([\s\S]*?)>>/.exec(o.dict);a?.[1]&&r.push(a[1]);let i=/\/Font\s+(\d+)\s+\d+\s+R/.exec(o.dict);if(i){let s=e.get(Number(i[1]));s&&r.push(s.dict)}}for(let o of r){let a=/\/([^\s/<>[\]()]+)\s+(\d+)\s+\d+\s+R/g,i;for(;(i=a.exec(o))!==null;)n.set(i[1]??"",Number(i[2]))}for(let[o,a]of n){let i=e.get(a);if(!i)continue;let s=/\/ToUnicode\s+(\d+)\s+\d+\s+R/.exec(i.dict);if(!s)continue;let c=e.get(Number(s[1]));if(!c)continue;let d=eo(c);d&&t.set(o,hs(d))}return t}function to(e){let t=[];for(let n=0;n<e.length;n+=1){let r=e[n];if(r!=="\\"){t.push(r.charCodeAt(0)&255);continue}let o=e[n+1];if(o===void 0)break;if(o>="0"&&o<="7"){let i="",s=n+1;for(;s<e.length&&i.length<3&&e[s]>="0"&&e[s]<="7";)i+=e[s],s+=1;t.push(parseInt(i,8)&255),n=s-1;continue}let a={n:10,r:13,t:9,b:8,f:12};t.push(a[o]??o.charCodeAt(0)&255),n+=1}return t}function no(e){if(e.length<2||e[0]!==254||e[1]!==255)return null;let t="";for(let n=2;n+1<e.length;n+=2)t+=String.fromCharCode((e[n]??0)<<8|(e[n+1]??0));return t}function Qr(e,t){let n=no(e);if(n!==null)return n;if(!t)return e.map(o=>String.fromCharCode(o)).join("");let r="";if(t.bytes===2)for(let o=0;o+1<e.length;o+=2){let a=(e[o]??0)<<8|(e[o+1]??0);r+=t.map.get(a)??""}else for(let o of e)r+=t.map.get(o)??String.fromCharCode(o);return r}function ms(e,t){let n="",r,o=/\/([^\s/<>[\]()]+)\s+[\d.]+\s+Tf|\((?:\\.|[^\\)])*\)|<[0-9A-Fa-f\s]*>|TJ|Tj|'|"/g,a,i="";for(;(a=o.exec(e))!==null;){let s=a[0];if(s.endsWith("Tf")){r=t.get(a[1]??"");continue}if(s==="TJ"||s==="Tj"||s==="'"||s==='"'){i&&(n+=i+`
17
+ `,i="");continue}if(s.startsWith("("))i+=Qr(to(s.slice(1,-1)),r);else if(s.startsWith("<")){let c=s.slice(1,-1).replace(/\s+/g,""),d=[];for(let u=0;u+1<c.length;u+=2)d.push(parseInt(c.slice(u,u+2),16));i+=Qr(d,r)}}return i&&(n+=i+`
18
+ `),n}function gs(e,t){let n=e.toString("latin1"),r=/\/Info\s+(\d+)\s+\d+\s+R/.exec(n),o=r?t.get(Number(r[1]))?.dict:void 0;if(!o)return"";let a=[],i=/\/(Author|Title|Subject|Keywords|Creator|Producer)\s*(\((?:\\.|[^\\)])*\)|<[0-9A-Fa-f\s]*>)/g,s;for(;(s=i.exec(o))!==null;){let c=s[2]??"";if(c.startsWith("(")){let d=to(c.slice(1,-1));a.push(no(d)??d.map(u=>String.fromCharCode(u)).join(""))}else{let d=c.slice(1,-1).replace(/\s+/g,""),u="";if(d.toUpperCase().startsWith("FEFF"))for(let p=4;p+3<d.length+1;p+=4)u+=String.fromCharCode(parseInt(d.slice(p,p+4),16));else for(let p=0;p+1<d.length;p+=2)u+=String.fromCharCode(parseInt(d.slice(p,p+2),16));a.push(u)}}return a.join(`
19
+ `)}function ro(e){if(!e.subarray(0,8).toString("latin1").startsWith("%PDF-")||e.toString("latin1",0,Math.min(e.length,4096)).includes("/Encrypt"))return null;let n=ds(e);if(n.size===0)return null;let r=ys(n),o=[];o.push(gs(e,n));let a=0,i=0,s=!1;for(let c of n.values()){if(!c.stream||/\/Subtype|\/Type\s*\/(XObject|Font|Metadata)|\/FontFile/.test(c.dict))continue;let d=eo(c);if(d===null||!/(TJ|Tj)\b/.test(d))continue;let u=ms(d,r);if(u.trim().length!==0){if(i+=1,a+u.length>Zr){o.push(u.slice(0,Math.max(0,Zr-a))),s=!0;break}o.push(u),a+=u.length}}return i===0?null:{text:o.join(`
20
+ `),truncated:s,streams:i}}var oo=new Set([".xlsx",".xlsm",".docx",".pptx"]),Dn=8*1024*1024,bs=101010256,Ss=33639248,ws=67324752;function Nn(e){let t=Math.min(e.length,67584),n=-1;for(let i=e.length-22;i>=e.length-t&&i>=0;i-=1)if(e.readUInt32LE(i)===bs){n=i;break}if(n<0)return null;let r=e.readUInt16LE(n+10),o=e.readUInt32LE(n+16);if(o>=e.length)return null;let a=[];for(let i=0;i<r&&!(o+46>e.length||e.readUInt32LE(o)!==Ss);i+=1){let s=e.readUInt16LE(o+10),c=e.readUInt32LE(o+20),d=e.readUInt32LE(o+24),u=e.readUInt16LE(o+28),p=e.readUInt16LE(o+30),f=e.readUInt16LE(o+32),y=e.readUInt32LE(o+42),_=e.subarray(o+46,o+46+u).toString("utf8");a.push({name:_,method:s,compSize:c,uncompSize:d,localHeaderOffset:y}),o+=46+u+p+f}return a}function On(e,t){let n=t.localHeaderOffset;if(n+30>e.length||e.readUInt32LE(n)!==ws)return null;let r=e.readUInt16LE(n+26),o=e.readUInt16LE(n+28),a=n+30+r+o,i=a+t.compSize;if(i>e.length)return null;let s=e.subarray(a,i);try{if(t.method===0)return Buffer.from(s);if(t.method===8)return _s(s)}catch{return null}return null}function vs(e,t){return On(e,t)?.toString("utf8")??null}var ks={"&amp;":"&","&lt;":"<","&gt;":">","&quot;":'"',"&apos;":"'"};function He(e){return e.replace(/&(amp|lt|gt|quot|apos);/g,t=>ks[t]??t).replace(/&#(\d+);/g,(t,n)=>{let r=Number(n);return r>0&&r<1114112?String.fromCodePoint(r):""}).replace(/&#x([0-9a-fA-F]+);/g,(t,n)=>{let r=parseInt(n,16);return r>0&&r<1114112?String.fromCodePoint(r):""})}function Es(e){return He(e.replace(/<[^>]*>/g,`
21
21
  `)).replace(/\n{2,}/g,`
22
- `)}function xi(e,t,n){let r=new RegExp(`<${t}\\b[^>]*\\b${n}="([^"]*)"`,"g"),o=[],a;for(;(a=r.exec(e))!==null;)a[1]&&o.push(Br(a[1]));return o}function Ai(e,t){let n=[];for(let r of t)(r==="docProps/core.xml"||r==="docProps/app.xml")&&n.push(r);if(e===".xlsx"||e===".xlsm")for(let r of t)(r==="xl/sharedStrings.xml"||r==="xl/workbook.xml"||/^xl\/worksheets\/sheet\d+\.xml$/.test(r)||/^xl\/comments\d*\.xml$/.test(r))&&n.push(r);else if(e===".docx")for(let r of t)(r==="word/document.xml"||/^word\/(header|footer|footnotes|endnotes|comments)\d*\.xml$/.test(r))&&n.push(r);else if(e===".pptx")for(let r of t)/^ppt\/(slides|notesSlides)\/(slide|notesSlide)\d+\.xml$/.test(r)&&n.push(r);return n}function Ti(e,t){let n=vi(e);if(!n||n.length===0)return null;let r=new Map(n.map(d=>[d.name,d])),o=Ai(t,n.map(d=>d.name));if(o.length===0)return null;let a=[],i=[],s=0,l=!1;for(let d of o){if(s>=fn){l=!0;break}let u=r.get(d);if(!u)continue;let p=wi(e,u);if(p===null)continue;let h=ki(p);if(d==="xl/workbook.xml"){let m=xi(p,"sheet","name");m.length&&(h+=`
23
- `+m.join(`
24
- `))}s+h.length>fn&&(h=h.slice(0,Math.max(0,fn-s)),l=!0),h.trim().length!==0&&(a.push(h),i.push(d),s+=h.length)}return a.length===0?null:{text:a.join(`
25
- `),truncated:l,parts:i}}function Tt(e,t){if($r.has(t))return Ti(e,t);if(pn.has(t)){let n=Rr(e);return n?{text:n.text,truncated:n.truncated,parts:[`pdf:${n.streams}-streams`]}:null}return null}var Pt=new Set([...$r,...pn]);var yn=10,nt=5e3,Di=64*1024*1024,mn=32*1024,Oi=new Set([".exe",".dll",".so",".dylib",".msi",".bin",".iso",".zip",".tar",".gz",".7z",".rar",".png",".jpg",".jpeg",".gif",".bmp",".tif",".tiff",".webp",".ico",".mp3",".mp4",".mov",".avi",".mkv",".wav",".flac",".ogg",".psd",".ai",".fla",".dwg",".dxf",".sqlite",".sqlite3",".db",".pyc",".class"]),Ni=new Set(["node_modules",".git",".hg",".svn"]),Ii=[{re:/\b\d{3}-\d{2}-\d{4}\b/,kind:"pii_unencrypted",subkind:"ssn",severity:"high",hint:"US Social Security Number pattern in plaintext."},{re:/\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}\b/i,kind:"pii_unencrypted",subkind:"email",severity:"low",hint:"Email addresses in plaintext."},{re:/(passport|teudat.?zehut|(?<![א-ת])תעודת.?זהות(?![א-ת])|(?<![א-ת])ת["'׳״]?\.?ז(?![א-ת]))/i,kind:"pii_unencrypted",subkind:"passport_keyword",severity:"medium",hint:"Filename / content references passport / national-ID keyword."}],Ci=[{re:/(salary|payroll|משכורת|ssn|social.?security|passport|דרכון|תעודת.?זהות)/i,kind:"pii_unencrypted",subkind:"sensitive_filename",severity:"medium",hint:"Filename suggests sensitive PII content."},{re:/\.(env|env\.local|pem|key|p12|pfx)$/i,kind:"pii_unencrypted",subkind:"secret_file",severity:"high",hint:"File extension implies secret / credential bundle in plaintext."}];function Ri(e){let t=e.lastIndexOf(".");return t<0?"":e.slice(t).toLowerCase()}async function rt(e){let t=Date.now(),n=[],r=[],o=0,a=0,i={hit_file_cap:!1,hit_depth_cap:!1,max_files:nt,max_depth:yn,skipped_by_extension:0,documents_extracted:0,documents_truncated:0,documents_unreadable:0,files_too_large:0,files_sampled_only:0,sample_bytes:mn};function s(S){return(S.startsWith(e.target_path)?S.slice(e.target_path.length).replace(/^[\\/]+/,""):S).replace(/\\/g,"/")}function l(S,_,w,x,y){let g=s(S);g!==""&&r.push({target_id:e.target_id,path:g,kind:_,size_bytes:w,modified_at:x?x.toISOString():null,child_count:y})}function d(S,_){n.push({target_id:e.target_id,relative_path:S,finding_kind:_.kind,finding_subkind:_.subkind,severity:_.severity,remediation_hint:_.hint})}function u(S,_,w,x,y){n.push({target_id:e.target_id,relative_path:S,finding_kind:_,finding_subkind:x,severity:w,remediation_hint:y})}function p(S,_){if(o+=1,o>nt){i.hit_file_cap=!0;return}let w=s(S);for(let E of Ci)E.re.test(_)&&d(w,E);let x=Ri(_);if(Oi.has(x)){i.skipped_by_extension+=1;return}let y=Pt.has(x),g=0;try{g=hn(S).size}catch{return}if(y&&g>Di){i.files_too_large+=1;return}let N;try{let E=jr(S,{flag:"r"});N=y?E:E.subarray(0,mn)}catch{return}a+=1;let $;if(y){let E=Tt(N,x);if(!E){i.documents_unreadable+=1;return}$=E.text,i.documents_extracted+=1,E.truncated&&(i.documents_truncated+=1)}else{let E=0;for(let I=0;I<N.length;I+=1)N[I]===0&&(E+=1);if(N.length>0&&E/N.length>.05)return;$=N.toString("utf8"),g>mn&&(i.files_sampled_only+=1)}let D=new Set;for(let E of Ii)if(E.re.test($)){let I=`${E.subkind}::${w}`;D.has(I)||(D.add(I),d(w,E))}for(let E of Pr($)){let I=`validated::${E.subkind}::${w}`;D.has(I)||(D.add(I),u(w,"pii_unencrypted",E.severity,E.subkind,`${E.hint} ${E.count} distinct value${E.count===1?"":"s"} in this file.`))}if(!Ar.test(w)){let E=$.split(`
26
- `),I=Math.min(E.length,2e3);for(let C=0;C<I;C++){let j=E[C];if(!j)continue;let re=j.trimStart();if(!(re.startsWith("//")||re.startsWith("/*")||re.startsWith("*")||re.startsWith("#"))&&!/process\.env/.test(j)&&!/\$\{[A-Z_]+/.test(j)){for(let oe of xr)if(oe.pattern.test(j)){let he=`secret::${oe.id}::${w}::${C+1}`;if(D.has(he))break;D.add(he),u(w,"hardcoded_secret",oe.severity,oe.id,`Looks like a ${oe.name} hardcoded near line ${C+1}. Move to an env var or secret manager.`);break}}}}if(_==="package.json"&&!w.includes("node_modules"))try{let E=jr(S,"utf8"),I=Tr(E);for(let C of I){let j=`vuln::${C.name}::${w}`;D.has(j)||(D.add(j),u(w,"vulnerable_dependency",C.vuln.severity,C.name,`${C.name}@${C.version} is below ${C.vuln.below} (${C.vuln.cve} \xB7 ${C.vuln.desc}). Bump to ${C.vuln.below} or higher.`))}}catch{}if(x===".csv"||x===".tsv"){let E=x===".tsv"?" ":",",I=$.split(/\r?\n/);if(I.length>0){let C=Be(I[0]??"",E),j=I.slice(1,51).map(re=>Be(re??"",E));C.forEach((re,oe)=>{let he=(re??"").trim();if(!he)return;let xe=Qe(he)?.type??null;if(!xe){let Xe=[];for(let Ja of j){let sn=Ja[oe];if(sn&&sn.trim().length>0&&Xe.push(sn),Xe.length>=50)break}let Ze=m(Xe);Ze&&(xe=Ze)}if(xe){let Xe=dn[xe]??"medium",Ze=`header::${w}::${he}::${xe}`;if(D.has(Ze))return;D.add(Ze),u(w,"pii_header_match",Xe,`${xe}:${he}`,`Column "${he}" looks like ${xe} data. Wrap with envelope or move to a vault-backed reference.`)}})}}if(x===".json"&&!_.endsWith(".nodata-proof.json"))try{let E=JSON.parse($),I=Array.isArray(E)?E[0]:E;if(I&&typeof I=="object")for(let C of Object.keys(I)){let j=Qe(C);if(j){let re=dn[j.type]??"medium",oe=`jsonkey::${w}::${C}::${j.type}`;if(D.has(oe))continue;D.add(oe),u(w,"pii_header_match",re,`${j.type}:${C}`,`JSON key "${C}" looks like ${j.type} data.`)}}}catch{}/\.(txt|log|md|csv|tsv|json|jsonl|xml|html?|yaml|yml|sql)$/i.test(_)&&h($,w,D)}function h(S,_,w){let x=S.split(`
27
- `),y=Math.min(x.length,1e3),g=-1,N=-1,$=-1;for(let D=0;D<y;D++){let E=x[D]??"";if($<0){let I=E.match(/\b\d{9}\b/);I&&At(I[0])&&($=D+1)}if(g<0&&(et.lastIndex=0,et.test(E)&&(g=D+1)),N<0&&(tt.lastIndex=0,tt.test(E)&&(N=D+1)),$>0&&g>0&&N>0)break}$>0&&!w.has(`ilid::${_}`)&&(w.add(`ilid::${_}`),u(_,"israeli_id_value","critical",`near_line:${$}`,`Israeli ID with valid Luhn checksum detected near line ${$}. Strong signal that real customer IDs are in plaintext.`)),g>0&&!w.has(`ilphone::${_}`)&&(w.add(`ilphone::${_}`),u(_,"israeli_phone_value","high",`near_line:${g}`,`Israeli phone number detected near line ${g}.`)),N>0&&!w.has(`iliban::${_}`)&&(w.add(`iliban::${_}`),u(_,"israeli_iban_value","critical",`near_line:${N}`,`Israeli IBAN (IL prefix) detected near line ${N}.`))}function m(S){if(S.length===0)return null;let _=0,w=0,x=0;for(let g of S)typeof g=="string"&&(At(g)&&_++,et.lastIndex=0,et.test(g)&&w++,tt.lastIndex=0,tt.test(g)&&x++);let y=S.length;return _/y>=.3?"id":w/y>=.3?"phone":x/y>=.3?"financial":null}function v(S,_){if(_>yn){i.hit_depth_cap=!0;return}if(o>nt){i.hit_file_cap=!0;return}let w;try{w=Kr(S)}catch{return}for(let x of w){if(o>nt)return;let y=Pi(S,x),g;try{g=hn(y)}catch{continue}if(!g.isSymbolicLink())if(g.isDirectory()){if(Ni.has(x))continue;let N=null;try{N=Kr(y).length}catch{N=null}l(y,"folder",null,g.mtime??null,N),v(y,_+1)}else g.isFile()&&(l(y,"file",g.size,g.mtime??null,null),p(y,x))}}let k;try{k=hn(e.target_path).isDirectory()}catch{k=!1}return k?(e.log.info("folder-scanner: starting",{target_label:e.target_label,target_path:e.target_path,max_files:nt,max_depth:yn}),v(e.target_path,0),{target_id:e.target_id,target_label:e.target_label,target_path:e.target_path,files_walked:o,files_inspected:a,duration_ms:Date.now()-t,findings:n,inventory:r,coverage:i}):{target_id:e.target_id,target_label:e.target_label,target_path:e.target_path,files_walked:0,files_inspected:0,duration_ms:Date.now()-t,findings:[],inventory:[],coverage:i,error:"target_path_not_found_or_not_directory"}}var ot={info(){}};var Ke={critical:4,high:3,medium:2,low:1,info:0},Sn=["critical","high","medium","low","info"];function gn(e,t,n){let r=e.get(t)??{key:t,total:0,worst:"info",bySeverity:{}};r.total+=1,r.bySeverity[n.severity]=(r.bySeverity[n.severity]??0)+1,(Ke[n.severity]??0)>(Ke[r.worst]??0)&&(r.worst=n.severity),e.set(t,r)}function _n(e){return[...e.values()].sort((t,n)=>(Ke[n.worst]??0)-(Ke[t.worst]??0)||n.total-t.total||t.key.localeCompare(n.key))}function Ae(e){let t=e.findings??[],n={},r=new Map,o=new Map,a=new Map;for(let s of t){n[s.severity]=(n[s.severity]??0)+1;let l=s.finding_subkind&&!/^near_line/.test(s.finding_subkind)?s.finding_subkind:"";gn(r,l||s.finding_kind,s);let d=s.relative_path.replace(/\\/g,"/"),u=d.includes("/")?d.slice(0,d.indexOf("/")):".";gn(o,u,s),gn(a,d,s)}let i=_n(a);return{total:t.length,bySeverity:n,byType:_n(r),byFolder:_n(o),byFile:i,filesWithFindings:i.map(s=>s.key)}}function ae(e){return e.replace(/[&<>"']/g,t=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[t])}function bn(e,t,n){let r=`<tr><th>${ae(n)}</th><th>total</th>${Sn.map(a=>`<th class="${a}">${a}</th>`).join("")}</tr>`,o=t.map(a=>`<tr><td class="k">${ae(a.key)}</td><td>${a.total}</td>${Sn.map(i=>`<td>${a.bySeverity[i]??""}</td>`).join("")}</tr>`).join("");return`<h2>${ae(e)} <span class="n">${t.length}</span></h2><table>${r}${o}</table>`}function vn(e,t=Ae(e)){let n=Sn.filter(s=>t.bySeverity[s]).map(s=>`<span class="pill ${s}">${t.bySeverity[s]} ${s}</span>`).join(" "),r=e.coverage,o=[];r?.hit_file_cap&&o.push(`stopped at the ${r.max_files}-file cap`),r?.hit_depth_cap&&o.push(`folders deeper than ${r.max_depth} levels were not descended`),r?.files_too_large&&o.push(`${r.files_too_large} file(s) too large to read`),r?.documents_unreadable&&o.push(`${r.documents_unreadable} document(s) unreadable`);let a=[...e.findings??[]].sort((s,l)=>(Ke[l.severity]??0)-(Ke[s.severity]??0)),i=a.map(s=>`<tr><td><span class="pill ${s.severity}">${s.severity}</span></td><td>${ae(s.finding_subkind||s.finding_kind)}</td><td class="k">${ae(s.relative_path)}</td><td class="h">${ae(s.remediation_hint??"")}</td></tr>`).join("");return`<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
28
- <title>NoData scan \xB7 ${ae(e.target_label||e.target_path)}</title>
22
+ `)}function xs(e,t,n){let r=new RegExp(`<${t}\\b[^>]*\\b${n}="([^"]*)"`,"g"),o=[],a;for(;(a=r.exec(e))!==null;)a[1]&&o.push(He(a[1]));return o}function As(e,t){let n=[];for(let r of t)(r==="docProps/core.xml"||r==="docProps/app.xml")&&n.push(r);if(e===".xlsx"||e===".xlsm")for(let r of t)(r==="xl/sharedStrings.xml"||r==="xl/workbook.xml"||/^xl\/worksheets\/sheet\d+\.xml$/.test(r)||/^xl\/comments\d*\.xml$/.test(r))&&n.push(r);else if(e===".docx")for(let r of t)(r==="word/document.xml"||/^word\/(header|footer|footnotes|endnotes|comments)\d*\.xml$/.test(r))&&n.push(r);else if(e===".pptx")for(let r of t)/^ppt\/(slides|notesSlides)\/(slide|notesSlide)\d+\.xml$/.test(r)&&n.push(r);return n}function Ts(e,t){let n=Nn(e);if(!n||n.length===0)return null;let r=new Map(n.map(d=>[d.name,d])),o=As(t,n.map(d=>d.name));if(o.length===0)return null;let a=[],i=[],s=0,c=!1;for(let d of o){if(s>=Dn){c=!0;break}let u=r.get(d);if(!u)continue;let p=vs(e,u);if(p===null)continue;let f=Es(p);if(d==="xl/workbook.xml"){let y=xs(p,"sheet","name");y.length&&(f+=`
23
+ `+y.join(`
24
+ `))}s+f.length>Dn&&(f=f.slice(0,Math.max(0,Dn-s)),c=!0),f.trim().length!==0&&(a.push(f),i.push(d),s+=f.length)}return a.length===0?null:{text:a.join(`
25
+ `),truncated:c,parts:i}}function Oe(e,t){if(oo.has(t))return Ts(e,t);if(Pn.has(t)){let n=ro(e);return n?{text:n.text,truncated:n.truncated,parts:[`pdf:${n.streams}-streams`]}:null}return null}var Lt=new Set([...oo,...Pn]);var In=10,lt=5e3,Ds=64*1024*1024,$n=32*1024,Ns=new Set([".exe",".dll",".so",".dylib",".msi",".bin",".iso",".zip",".tar",".gz",".7z",".rar",".png",".jpg",".jpeg",".gif",".bmp",".tif",".tiff",".webp",".ico",".mp3",".mp4",".mov",".avi",".mkv",".wav",".flac",".ogg",".psd",".ai",".fla",".dwg",".dxf",".sqlite",".sqlite3",".db",".pyc",".class"]),Os=new Set(["node_modules",".git",".hg",".svn"]),Cs=[{re:/\b\d{3}-\d{2}-\d{4}\b/,kind:"pii_unencrypted",subkind:"ssn",severity:"high",hint:"US Social Security Number pattern in plaintext."},{re:/\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}\b/i,kind:"pii_unencrypted",subkind:"email",severity:"low",hint:"Email addresses in plaintext."},{re:/(passport|teudat.?zehut|(?<![א-ת])תעודת.?זהות(?![א-ת])|(?<![א-ת])ת["'׳״]?\.?ז(?![א-ת]))/i,kind:"pii_unencrypted",subkind:"passport_keyword",severity:"medium",hint:"Filename / content references passport / national-ID keyword."}],Is=[{re:/(salary|payroll|משכורת|ssn|social.?security|passport|דרכון|תעודת.?זהות)/i,kind:"pii_unencrypted",subkind:"sensitive_filename",severity:"medium",hint:"Filename suggests sensitive PII content."},{re:/\.(env|env\.local|pem|key|p12|pfx)$/i,kind:"pii_unencrypted",subkind:"secret_file",severity:"high",hint:"File extension implies secret / credential bundle in plaintext."}];function $s(e){let t=e.lastIndexOf(".");return t<0?"":e.slice(t).toLowerCase()}async function dt(e){let t=Date.now(),n=[],r=[],o=0,a=0,i={hit_file_cap:!1,hit_depth_cap:!1,max_files:lt,max_depth:In,skipped_by_extension:0,documents_extracted:0,documents_truncated:0,documents_unreadable:0,files_too_large:0,files_sampled_only:0,sample_bytes:$n};function s(b){return(b.startsWith(e.target_path)?b.slice(e.target_path.length).replace(/^[\\/]+/,""):b).replace(/\\/g,"/")}function c(b,S,v,E,m){let g=s(b);g!==""&&r.push({target_id:e.target_id,path:g,kind:S,size_bytes:v,modified_at:E?E.toISOString():null,child_count:m})}function d(b,S){n.push({target_id:e.target_id,relative_path:b,finding_kind:S.kind,finding_subkind:S.subkind,severity:S.severity,remediation_hint:S.hint})}function u(b,S,v,E,m){n.push({target_id:e.target_id,relative_path:b,finding_kind:S,finding_subkind:E,severity:v,remediation_hint:m})}function p(b,S){if(o+=1,o>lt){i.hit_file_cap=!0;return}let v=s(b);for(let x of Is)x.re.test(S)&&d(v,x);let E=$s(S);if(Ns.has(E)){i.skipped_by_extension+=1;return}let m=Lt.has(E),g=0;try{g=Cn(b).size}catch{return}if(m&&g>Ds){i.files_too_large+=1;return}let A;try{let x=io(b,{flag:"r"});A=m?x:x.subarray(0,$n)}catch{return}a+=1;let I;if(m){let x=Oe(A,E);if(!x){i.documents_unreadable+=1;return}I=x.text,i.documents_extracted+=1,x.truncated&&(i.documents_truncated+=1)}else{let x=0;for(let O=0;O<A.length;O+=1)A[O]===0&&(x+=1);if(A.length>0&&x/A.length>.05)return;I=A.toString("utf8"),g>$n&&(i.files_sampled_only+=1)}let P=new Set;for(let x of Cs)if(x.re.test(I)){let O=`${x.subkind}::${v}`;P.has(O)||(P.add(O),d(v,x))}for(let x of Xr(I)){let O=`validated::${x.subkind}::${v}`;P.has(O)||(P.add(O),u(v,"pii_unencrypted",x.severity,x.subkind,`${x.hint} ${x.count} distinct value${x.count===1?"":"s"} in this file.`))}if(!zr.test(v)){let x=I.split(`
26
+ `),O=Math.min(x.length,2e3);for(let $=0;$<O;$++){let B=x[$];if(!B)continue;let W=B.trimStart();if(!(W.startsWith("//")||W.startsWith("/*")||W.startsWith("*")||W.startsWith("#"))&&!/process\.env/.test(B)&&!/\$\{[A-Z_]+/.test(B)){for(let J of jt)if(J.pattern.test(B)){let me=`secret::${J.id}::${v}::${$+1}`;if(P.has(me))break;P.add(me),u(v,"hardcoded_secret",J.severity,J.id,`Looks like a ${J.name} hardcoded near line ${$+1}. Move to an env var or secret manager.`);break}}}}if(S==="package.json"&&!v.includes("node_modules"))try{let x=io(b,"utf8"),O=Yr(x);for(let $ of O){let B=`vuln::${$.name}::${v}`;P.has(B)||(P.add(B),u(v,"vulnerable_dependency",$.vuln.severity,$.name,`${$.name}@${$.version} is below ${$.vuln.below} (${$.vuln.cve} \xB7 ${$.vuln.desc}). Bump to ${$.vuln.below} or higher.`))}}catch{}if(E===".csv"||E===".tsv"){let x=E===".tsv"?" ":",",O=I.split(/\r?\n/);if(O.length>0){let $=Ue(O[0]??"",x),B=O.slice(1,51).map(W=>Ue(W??"",x));$.forEach((W,J)=>{let me=(W??"").trim();if(!me)return;let De=Ne(me)?.type??null;if(!De){let at=[];for(let zi of B){let kn=zi[J];if(kn&&kn.trim().length>0&&at.push(kn),at.length>=50)break}let it=y(at);it&&(De=it)}if(De){let at=An[De]??"medium",it=`header::${v}::${me}::${De}`;if(P.has(it))return;P.add(it),u(v,"pii_header_match",at,`${De}:${me}`,`Column "${me}" looks like ${De} data. Wrap with envelope or move to a vault-backed reference.`)}})}}if(E===".json"&&!S.endsWith(".nodata-proof.json"))try{let x=JSON.parse(I),O=Array.isArray(x)?x[0]:x;if(O&&typeof O=="object")for(let $ of Object.keys(O)){let B=Ne($);if(B){let W=An[B.type]??"medium",J=`jsonkey::${v}::${$}::${B.type}`;if(P.has(J))continue;P.add(J),u(v,"pii_header_match",W,`${B.type}:${$}`,`JSON key "${$}" looks like ${B.type} data.`)}}}catch{}/\.(txt|log|md|csv|tsv|json|jsonl|xml|html?|yaml|yml|sql)$/i.test(S)&&f(I,v,P)}function f(b,S,v){let E=b.split(`
27
+ `),m=Math.min(E.length,1e3),g=-1,A=-1,I=-1;for(let P=0;P<m;P++){let x=E[P]??"";if(I<0){let O=x.match(/\b\d{9}\b/);O&&Kt(O[0])&&(I=P+1)}if(g<0&&(st.lastIndex=0,st.test(x)&&(g=P+1)),A<0&&(ct.lastIndex=0,ct.test(x)&&(A=P+1)),I>0&&g>0&&A>0)break}I>0&&!v.has(`ilid::${S}`)&&(v.add(`ilid::${S}`),u(S,"israeli_id_value","critical",`near_line:${I}`,`Israeli ID with valid Luhn checksum detected near line ${I}. Strong signal that real customer IDs are in plaintext.`)),g>0&&!v.has(`ilphone::${S}`)&&(v.add(`ilphone::${S}`),u(S,"israeli_phone_value","high",`near_line:${g}`,`Israeli phone number detected near line ${g}.`)),A>0&&!v.has(`iliban::${S}`)&&(v.add(`iliban::${S}`),u(S,"israeli_iban_value","critical",`near_line:${A}`,`Israeli IBAN (IL prefix) detected near line ${A}.`))}function y(b){if(b.length===0)return null;let S=0,v=0,E=0;for(let g of b)typeof g=="string"&&(Kt(g)&&S++,st.lastIndex=0,st.test(g)&&v++,ct.lastIndex=0,ct.test(g)&&E++);let m=b.length;return S/m>=.3?"id":v/m>=.3?"phone":E/m>=.3?"financial":null}function _(b,S){if(S>In){i.hit_depth_cap=!0;return}if(o>lt){i.hit_file_cap=!0;return}let v;try{v=ao(b)}catch{return}for(let E of v){if(o>lt)return;let m=Ps(b,E),g;try{g=Cn(m)}catch{continue}if(!g.isSymbolicLink())if(g.isDirectory()){if(Os.has(E))continue;let A=null;try{A=ao(m).length}catch{A=null}c(m,"folder",null,g.mtime??null,A),_(m,S+1)}else g.isFile()&&(c(m,"file",g.size,g.mtime??null,null),p(m,E))}}let k;try{k=Cn(e.target_path).isDirectory()}catch{k=!1}return k?(e.log.info("folder-scanner: starting",{target_label:e.target_label,target_path:e.target_path,max_files:lt,max_depth:In}),_(e.target_path,0),{target_id:e.target_id,target_label:e.target_label,target_path:e.target_path,files_walked:o,files_inspected:a,duration_ms:Date.now()-t,findings:n,inventory:r,coverage:i}):{target_id:e.target_id,target_label:e.target_label,target_path:e.target_path,files_walked:0,files_inspected:0,duration_ms:Date.now()-t,findings:[],inventory:[],coverage:i,error:"target_path_not_found_or_not_directory"}}var ut={info(){}};var Ve={critical:4,high:3,medium:2,low:1,info:0},Kn=["critical","high","medium","low","info"];function Rn(e,t,n){let r=e.get(t)??{key:t,total:0,worst:"info",bySeverity:{}};r.total+=1,r.bySeverity[n.severity]=(r.bySeverity[n.severity]??0)+1,(Ve[n.severity]??0)>(Ve[r.worst]??0)&&(r.worst=n.severity),e.set(t,r)}function Bn(e){return[...e.values()].sort((t,n)=>(Ve[n.worst]??0)-(Ve[t.worst]??0)||n.total-t.total||t.key.localeCompare(n.key))}function Ce(e){let t=e.findings??[],n={},r=new Map,o=new Map,a=new Map;for(let s of t){n[s.severity]=(n[s.severity]??0)+1;let c=s.finding_subkind&&!/^near_line/.test(s.finding_subkind)?s.finding_subkind:"";Rn(r,c||s.finding_kind,s);let d=s.relative_path.replace(/\\/g,"/"),u=d.includes("/")?d.slice(0,d.indexOf("/")):".";Rn(o,u,s),Rn(a,d,s)}let i=Bn(a);return{total:t.length,bySeverity:n,byType:Bn(r),byFolder:Bn(o),byFile:i,filesWithFindings:i.map(s=>s.key)}}function ie(e){return e.replace(/[&<>"']/g,t=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[t])}function jn(e,t,n){let r=`<tr><th>${ie(n)}</th><th>total</th>${Kn.map(a=>`<th class="${a}">${a}</th>`).join("")}</tr>`,o=t.map(a=>`<tr><td class="k">${ie(a.key)}</td><td>${a.total}</td>${Kn.map(i=>`<td>${a.bySeverity[i]??""}</td>`).join("")}</tr>`).join("");return`<h2>${ie(e)} <span class="n">${t.length}</span></h2><table>${r}${o}</table>`}function Ln(e,t=Ce(e)){let n=Kn.filter(s=>t.bySeverity[s]).map(s=>`<span class="pill ${s}">${t.bySeverity[s]} ${s}</span>`).join(" "),r=e.coverage,o=[];r?.hit_file_cap&&o.push(`stopped at the ${r.max_files}-file cap`),r?.hit_depth_cap&&o.push(`folders deeper than ${r.max_depth} levels were not descended`),r?.files_too_large&&o.push(`${r.files_too_large} file(s) too large to read`),r?.documents_unreadable&&o.push(`${r.documents_unreadable} document(s) unreadable`);let a=[...e.findings??[]].sort((s,c)=>(Ve[c.severity]??0)-(Ve[s.severity]??0)),i=a.map(s=>`<tr><td><span class="pill ${s.severity}">${s.severity}</span></td><td>${ie(s.finding_subkind||s.finding_kind)}</td><td class="k">${ie(s.relative_path)}</td><td class="h">${ie(s.remediation_hint??"")}</td></tr>`).join("");return`<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
28
+ <title>NoData scan \xB7 ${ie(e.target_label||e.target_path)}</title>
29
29
  <style>
30
30
  body{margin:0;background:#FAF7F0;color:#1a1a1a;font:14px/1.5 Inter,Heebo,system-ui,sans-serif}
31
31
  main{max-width:1100px;margin:0 auto;padding:28px 18px 60px}
@@ -38,57 +38,85 @@ td.k{font-family:ui-monospace,Menlo,monospace;font-size:12.5px;word-break:break-
38
38
  .medium{color:#7a6400}.pill.medium{background:#fbf3cf}.low{color:#445}.pill.low{background:#eef0f4}
39
39
  .note{margin-top:18px;color:#666;font-size:12.5px}
40
40
  </style></head><body><main>
41
- <h1>Scan \xB7 ${ae(e.target_label||e.target_path)}</h1>
42
- <p class="sub">${ae(e.target_path)} \xB7 ${e.files_walked} files walked, ${e.files_inspected} inspected in ${e.duration_ms} ms \xB7 ran on this machine, nothing uploaded</p>
41
+ <h1>Scan \xB7 ${ie(e.target_label||e.target_path)}</h1>
42
+ <p class="sub">${ie(e.target_path)} \xB7 ${e.files_walked} files walked, ${e.files_inspected} inspected in ${e.duration_ms} ms \xB7 ran on this machine, nothing uploaded</p>
43
43
  <p><strong>${t.total}</strong> findings ${n}</p>
44
- ${o.length?`<p class="note">Coverage: ${ae(o.join("; "))}.</p>`:""}
45
- ${bn("By type",t.byType,"type")}
46
- ${bn("By folder",t.byFolder,"folder")}
47
- ${bn("By file",t.byFile,"file")}
44
+ ${o.length?`<p class="note">Coverage: ${ie(o.join("; "))}.</p>`:""}
45
+ ${jn("By type",t.byType,"type")}
46
+ ${jn("By folder",t.byFolder,"folder")}
47
+ ${jn("By file",t.byFile,"file")}
48
48
  <h2>Every finding <span class="n">${a.length}</span></h2>
49
49
  <table><tr><th>severity</th><th>type</th><th>file</th><th>what to do</th></tr>${i}</table>
50
50
  <p class="note">Content-free: this report lists where and what kind \u2014 never a matched value.</p>
51
- </main></body></html>`}var Mr={israeli_id:"[ID]",credit_card:"[CARD]",iban:"[IBAN]",israeli_phone:"[PHONE]",email:"[EMAIL]"},$i=/[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}/g;function wn(e,t,n=1){e[t]=(e[t]??0)+n}function at(e,t={}){let n=e;for(let r of un)r.pattern.lastIndex=0,n=n.replace(r.pattern,o=>r.validate(o)?(wn(t,r.subkind),Mr[r.subkind]??`[${r.subkind.toUpperCase()}]`):o);return n=n.replace($i,()=>(wn(t,"email"),Mr.email)),{text:n,counts:t,columnsHidden:[]}}function Fr(e,t){return e.includes(t)||e.includes('"')||e.includes(`
52
- `)?`"${e.replace(/"/g,'""')}"`:e}function Bi(e){let t=(e.match(/\t/g)??[]).length,n=(e.match(/;/g)??[]).length,r=(e.match(/,/g)??[]).length;return t>r&&t>=n?" ":n>r?";":","}function En(e,t){let n=e.split(/\r?\n/),r=t??Bi(n[0]??""),o=Be(n[0]??"",r),a=o.map(l=>Qe(l)),i={},s=[o.map(l=>Fr(l,r)).join(r)];for(let l of n.slice(1)){if(l===""){s.push(l);continue}let d=Be(l,r).map((u,p)=>{let h=a[p];return h&&u.trim()!==""?(wn(i,`column:${h.type}`),`[${h.type.toUpperCase()}]`):at(u,i).text});s.push(d.map(u=>Fr(u,r)).join(r))}return{text:s.join(`
53
- `),counts:i,columnsHidden:o.filter((l,d)=>a[d])}}var te=kr(to(),1);import{homedir as ps}from"node:os";import{basename as Rn,dirname as On,extname as fs,join as Ct,resolve as It}from"node:path";import{existsSync as ct,mkdirSync as hs,readFileSync as ys,rmSync as ms,statSync as Nn,writeFileSync as no}from"node:fs";import{pathToFileURL as $n}from"node:url";var q=(e,t=!1)=>({content:[{type:"text",text:e}],...t?{isError:t}:{}}),ro=Ct(ps(),".nodata","reports"),In=25;function Bn(e){return/\.ndc$/i.test(e)||/\.clean\.[A-Za-z0-9]+$/.test(e)}function gs(){return new Date().toISOString().replace(/[:.]/g,"-").slice(0,19)}function _s(e){return e.replace(/[^A-Za-z0-9_-]+/g,"_").slice(0,60)||"folder"}async function oo(e){return rt({target_id:"mcp",target_label:Rn(e),target_path:e,log:ot})}function Cn(e,t){let n=e.slice(0,t).map(r=>` ${String(r.total).padStart(6)} ${r.worst.padEnd(8)} ${r.key}`);return e.length>t&&n.push(` \u2026 ${e.length-t} more in the full report`),n.join(`
54
- `)}function bs(e,t,n,r){if(e.error)return`Could not scan ${e.target_path}: ${e.error}`;let o=["critical","high","medium","low","info"].filter(i=>t.bySeverity[i]).map(i=>`${t.bySeverity[i]} ${i}`).join(" \xB7 "),a=[`SCAN ${e.target_path}`,` ${r} \xB7 ran on this machine, nothing uploaded`,` ${e.files_walked} files walked, ${e.files_inspected} inspected, ${e.duration_ms} ms`,"",`FOUND ${t.total} findings${o?" \u2014 "+o:""} in ${t.filesWithFindings.length} files`];return t.total>0&&(a.push("","BY TYPE (all)",Cn(t.byType,100)),a.push("","BY FOLDER",Cn(t.byFolder,10)),a.push("","WORST FILES",Cn(t.byFile,12))),n&&a.push("","FULL REPORT (every finding, content-free) \u2014 open in a browser:",` ${$n(n).href}`),t.total>0&&a.push("","NEXT \u2014 same workspace:",` \xB7 LOCK the ${t.filesWithFindings.length} files with findings: nodata_protect path: "${e.target_path}" (asks before it changes anything)`,' \xB7 WORK on a clean copy (values replaced by [CARD], [ID] \u2026): nodata_redact path: "<file>"'," \xB7 A database table instead of files: nodata_register_table \u2192 nodata_grant"),a.join(`
55
- `)}function ao(e,t){e.registerTool("nodata_scan_folder",{description:"SEE what's sensitive. Scans a LOCAL folder for hardcoded secrets and unencrypted PII (checksum-validated Israeli ID, Luhn credit card, IBAN, phones), reading PDF and Office files too, entirely on this machine. Returns the WHOLE result \u2014 counts by type, by folder and by file \u2014 and writes a full content-free HTML report (every finding) to ~/.nodata/reports, with a link to open it. Then offers the next step in the same workspace: nodata_protect (lock the files with findings) or nodata_redact (a clean copy to work on). Call this when the user asks to scan/audit/check a folder.",inputSchema:{path:me.string().optional().describe("Folder to scan. Default: the directory the server runs in.")}},async({path:n})=>{let r=It((n??".").trim()||".");if(!ct(r))return q(`No folder found at: ${r}`);try{let o=await oo(r),a=Ae(o),i=null;return o.error||(hs(ro,{recursive:!0}),i=Ct(ro,`scan-${_s(Rn(r))}-${gs()}.html`),no(i,vn(o,a),{mode:384})),q(bs(o,a,i,t()))}catch(o){return q(`Scan failed: ${o instanceof Error?o.message:String(o)}`,!0)}}),e.registerTool("nodata_protect",{description:"LOCK files: seal each one to this device's key as <file>.ndc (AES-256-GCM, the key never leaves this machine; the same format as `nodata protect`, so `nodata open` opens it too). Given a folder, seals only the files the scan finds exposure in; given a file, seals that file. ASKS FIRST: without confirm:true it only lists what would be sealed and changes nothing \u2014 show that list to the user and call again with confirm:true only after they approve. Writes a local receipt (hashes, seal ids) under <folder>/.nodata/receipts. remove:true also deletes the plaintext originals.",inputSchema:{path:me.string().describe("File or folder to protect."),confirm:me.boolean().optional().describe("true = do it. Omit to preview."),remove:me.boolean().optional().describe("Delete the plaintext originals after sealing. Default false.")}},async({path:n,confirm:r,remove:o})=>{let a=It(n);if(!ct(a))return q(`Not found: ${a}`,!0);let i=Nn(a).isDirectory(),s;if(i?s=Ae(await oo(a)).filesWithFindings.map(v=>Ct(a,v)).filter(v=>ct(v)&&Nn(v).isFile()&&!Bn(v)):s=a.endsWith(".ndc")?[]:[a],s.length===0)return q(`Nothing to seal in ${a} \u2014 no file with findings.`);if(!r){let m=s.slice(0,In).map(v=>` \xB7 ${v}`);return s.length>In&&m.push(` \u2026 and ${s.length-In} more`),q([`PREVIEW \u2014 nothing changed yet. ${t()}`,`Would seal ${s.length} file(s) to this device's key${o?" and DELETE the plaintext originals":" (originals kept)"}:`,...m,"","Ask the user to approve, then call nodata_protect again with confirm: true."].join(`
56
- `))}let{key:l,created:d}=te.ensureDeviceKey(),u=[];for(let m of s)u.push(await te.sealFile(m,l)),o&&ms(m);let p=i?a:On(a),h=te.writeLocalReceipt(p,{action:"protect",kid:l.kid,removed_plaintext:!!o,files:u,extra:{approved_by:t(),surface:"mcp"}});return q([`SEALED ${u.length} file(s) \u2014 ${t()}${d?" \xB7 a new device key was created at ~/.nodata/device-key.json (back it up: without it these files cannot be opened)":""}`,`device key id: ${l.kid}`,o?"Plaintext originals deleted.":"Originals are still in place \u2014 run again with remove: true to leave only the sealed copies.",`Receipt (hashes + seal ids, content-free): ${$n(h).href}`,'Open one again: nodata_open path: "<file>.ndc"'].join(`
57
- `))}),e.registerTool("nodata_open",{description:"RELEASE a sealed file: open <file>.ndc back to its original next to it (never overwrites), with this device's key, and check its hash matches what was sealed. ASKS FIRST: without confirm:true it only says what would be opened. Writes a local receipt.",inputSchema:{path:me.string().describe("The .ndc file to open."),confirm:me.boolean().optional().describe("true = open it. Omit to preview.")}},async({path:n,confirm:r})=>{let o=It(n),a=ct(o)?te.readManifest(o):null;if(!a)return q(`Not a NoData sealed file: ${o}`,!0);if(!r)return q(`PREVIEW \u2014 nothing changed yet. ${t()}
58
- Would open "${a.orig}" (sealed ${a.sealed_at}, device key ${a.kid}) as plaintext next to ${o}.
59
- Ask the user to approve, then call nodata_open again with confirm: true.`);let i=await te.openFile(o);if(!i.ok){let l=i.error==="wrong_key"?"this device's key is not the one it was sealed to":i.error==="no_device_key"?"this machine has no device key (~/.nodata/device-key.json)":i.error;return q(`Could not open ${o}: ${l}.`,!0)}let s=te.writeLocalReceipt(On(o),{action:"open",kid:a.kid,removed_plaintext:!1,files:[{path:i.outPath,ndc:o,sha256:i.sha256,sealId:a.token.split(":").pop()??""}],extra:{approved_by:t(),surface:"mcp",hash_matches:i.intact}});return q([`OPENED ${i.outPath} \u2014 ${t()}`,i.intact?"Hash matches what was sealed \u2014 the file is unaltered.":"WARNING: hash differs from the sealed record.",`Receipt: ${$n(s).href}`].join(`
60
- `))}),e.registerTool("nodata_redact",{description:"WORK on the rest: make a clean copy of a file with every sensitive value replaced by a typed token ([CARD], [ID], [IBAN], [PHONE], [EMAIL]); in CSV/TSV a column whose header names personal data is hidden whole, so rows and columns still line up. Same detectors as the scan. The original is untouched; the copy is written next to it as <name>.clean.<ext> (Office/PDF \u2192 .clean.txt). return_text:true also returns the clean text (up to 60 KB) so it can be analysed right here \u2014 it contains no detected value.",inputSchema:{path:me.string().describe("The file to redact (csv, tsv, txt, md, json, log, docx, xlsx, pptx, pdf)."),return_text:me.boolean().optional().describe("Also return the clean text for analysis.")}},async({path:n,return_text:r})=>{let o=It(n);if(!ct(o)||!Nn(o).isFile())return q(`Not a file: ${o}`,!0);let a=fs(o).toLowerCase(),i=ys(o),s,l=a||".txt";if(a===".csv"||a===".tsv")s=En(i.toString("utf8"),a===".tsv"?" ":void 0);else if(Pt.has(a)){let h=Tt(i,a);if(!h)return q(`Could not read the text of ${o}.`,!0);s=at(h.text),l=".txt"}else s=at(i.toString("utf8"));let d=Ct(On(o),`${Rn(o,a)}.clean${l}`);no(d,s.text,{mode:384});let u=Object.entries(s.counts).sort((h,m)=>m[1]-h[1]).map(([h,m])=>` ${String(m).padStart(6)} ${h}`),p=[`CLEAN COPY ${d} \u2014 ${t()} \xB7 original untouched`,u.length?`Replaced:
61
- ${u.join(`
62
- `)}`:"Nothing sensitive detected \u2014 the copy equals the original text.",s.columnsHidden.length?`Columns hidden whole: ${s.columnsHidden.join(", ")}`:""].filter(Boolean);return r&&p.push("",`--- clean text${s.text.length>6e4?" (first 60000 chars)":""} ---`,s.text.slice(0,6e4)),q(p.join(`
63
- `))})}var en=kr(ga(),1);import{z as $e}from"zod";import{createHash as Nl}from"node:crypto";import{existsSync as ur,mkdirSync as Il,readFileSync as wa,readdirSync as Cl,statSync as _a,writeFileSync as Rl}from"node:fs";import{homedir as $l}from"node:os";import{basename as dr,extname as Bl,join as Ea,resolve as Kl}from"node:path";var z=(e,t=!1)=>({content:[{type:"text",text:e}],...t?{isError:t}:{}}),Qt=Ea($l(),".nodata","shares"),jl=12*1024*1024,Ml={".pdf":"application/pdf",".txt":"text/plain",".csv":"text/csv",".md":"text/markdown",".json":"application/json",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".docx":"application/vnd.openxmlformats-officedocument.wordprocessingml.document",".xlsx":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",".pptx":"application/vnd.openxmlformats-officedocument.presentationml.presentation"};function ka(e){return Ea(Qt,`${e.replace(/[^a-f0-9]/gi,"")}.json`)}function ba(e){let t=ka(e);if(!ur(t))return null;try{return JSON.parse(wa(t,"utf8"))}catch{return null}}function Sa(e){let t=e.match(/\/lock\/open\/([a-f0-9]{8,64})/i);return(t?t[1]:e.trim()).toLowerCase()}async function va(e,t,n){let r=await fetch(e,{method:"POST",headers:{"content-type":"application/json",...n?{authorization:`Bearer ${n}`}:{}},body:JSON.stringify(t)});return{status:r.status,body:await r.json().catch(()=>({}))}}function xa(e,t,n,r){e.registerTool("nodata_send",{description:"SEND a file as a governed link: encrypted on this machine (post-quantum hybrid), stored by NoData only as ciphertext \u2014 the key rides in the link's #fragment, which NoData never receives. Expires after ttl and after max_opens opens; can be burned (nodata_burn) at any time, after which nobody can open it again. Filed under your organization with a signed receipt and a proof_url. ASKS FIRST: without confirm:true it only shows what would be sent. Returns the link to hand to the recipient.",inputSchema:{path:$e.string().describe("The file to send (up to 12 MB)."),ttl_hours:$e.number().optional().describe("Hours until the link expires. Default 72, max 168 (7 days)."),max_opens:$e.number().optional().describe("Opens allowed before it burns itself. Default 3, max 1000."),confirm:$e.boolean().optional().describe("true = send it. Omit to preview.")}},async({path:o,ttl_hours:a,max_opens:i,confirm:s})=>{let l=Kl(o);if(!ur(l)||!_a(l).isFile())return z(`Not a file: ${l}`,!0);let d=_a(l).size;if(d>jl)return z(`${dr(l)} is ${(d/1048576).toFixed(1)} MB; a governed link carries up to 12 MB.`,!0);let u=Math.round(Math.min(Math.max(a??72,1/60),168)*3600),p=Math.round(Math.min(Math.max(i??3,1),1e3));if(!s)return z([`PREVIEW \u2014 nothing sent yet. ${r()}`,`Would send "${dr(l)}" (${(d/1024).toFixed(1)} KB) as a governed link:`," \xB7 encrypted here; NoData stores only ciphertext and never gets the key",` \xB7 expires in ${(u/3600).toFixed(u<3600?2:0)} h, or after ${p} open(s)`," \xB7 revocable any time with nodata_burn; every open is counted","","Ask the user to approve, then call nodata_send again with the same arguments and confirm: true."].join(`
64
- `));let h=wa(l),m=dr(l),v=Ml[Bl(l).toLowerCase()]??"application/octet-stream",k=await(0,en.sealBytesForPublicShare)({bytes:h,filename:m,contentType:v,ttlSeconds:u,server:t}),S=await(0,en.wrapFragmentForShortLink)(k.fragment),_;try{_=await va(`${t}/api/lock/public/issue`,{formatVersion:3,lockboxId:k.lockboxId,containerB64:Buffer.from(k.container).toString("base64"),filename:m,contentType:v,ttlSeconds:u,maxOpens:p,wrappedFragmentB64:S.wrappedFragmentB64,wrapIvB64:S.wrapIvB64},await n())}catch(y){return z(`Could not reach NoData: ${y instanceof Error?y.message:String(y)}`,!0)}if(_.status>=400||_.body.ok!==!0)return z(`Send refused (HTTP ${_.status}): ${JSON.stringify(_.body)}`,!0);let w=String(_.body.id),x={id:w,file:l,filename:m,sha256:Nl("sha256").update(h).digest("hex"),link:`${t}/lock/open/${w}#${S.wrapKeyB64Url}`,wrap_key_b64url:S.wrapKeyB64Url,expires_at:String(_.body.expiresAt??""),max_opens:p,sent_by:r(),sent_at:new Date().toISOString(),receipt_id:_.body.receipt_id??null,proof_url:_.body.proof_url??null};return Il(Qt,{recursive:!0}),Rl(ka(w),JSON.stringify(x,null,2)+`
65
- `,{mode:384}),z([`SENT "${m}" \u2014 ${r()}`,"Link (give this to the recipient; anyone holding it can open it until it expires or is burned):",` ${x.link}`,`Expires ${x.expires_at} \xB7 max ${p} open(s) \xB7 id ${w}`,x.proof_url?`Proof (signed receipt, public): ${x.proof_url}`:"No receipt: the link was not attributed to an organization.",`Check it: nodata_link_status id: "${w}" \xB7 Revoke it: nodata_burn id: "${w}"`].join(`
66
- `))}),e.registerTool("nodata_link_status",{description:"STATUS of links sent with nodata_send: opens so far, expiry, whether burned. Pass an id or link for one; omit to list every link sent from this machine.",inputSchema:{id:$e.string().optional().describe("Share id or /lock/open link. Omit to list all.")}},async({id:o})=>{let a=o?[Sa(o)]:ur(Qt)?Cl(Qt).filter(s=>s.endsWith(".json")).map(s=>s.slice(0,-5)):[];if(a.length===0)return z("No links sent from this machine yet. Send one with nodata_send.");let i=[`LINKS \u2014 ${r()}`];for(let s of a.slice(0,50)){let l=ba(s),d={};try{let p=await fetch(`${t}/api/lock/public/status/${s}`);d=await p.json().catch(()=>({})),p.status===404&&(d={missing:!0})}catch{d={unreachable:!0}}let u=d.missing?"not found":d.unreachable?"status unavailable":d.burned?"BURNED":d.expired?"expired":"live";i.push(` ${s} ${u.padEnd(10)} opens ${d.openCount??"?"}/${d.maxOpens??l?.max_opens??"?"} expires ${d.expiresAt??l?.expires_at??"?"} ${l?l.filename:""}`)}return z(i.join(`
67
- `))}),e.registerTool("nodata_burn",{description:"BURN a link sent with nodata_send: the stored ciphertext is zeroed, so nobody \u2014 the recipient, a forwarded copy, NoData \u2014 can open it again. Irreversible. ASKS FIRST: without confirm:true it only says what would be burned. Returns the signed burn receipt and its proof_url.",inputSchema:{id:$e.string().describe("Share id or the /lock/open link."),confirm:$e.boolean().optional().describe("true = burn it. Omit to preview.")}},async({id:o,confirm:a})=>{let i=Sa(o),s=o.match(/#([A-Za-z0-9_-]{43})/)?.[1],l=ba(i),d=l?.wrap_key_b64url??s;if(!d)return z(`No burn key for ${i} on this machine. Pass the full link (it carries the key after #), or burn it from the machine that sent it.`,!0);if(!a)return z(`PREVIEW \u2014 nothing burned yet. ${r()}
68
- Would burn ${l?`"${l.filename}" `:""}(${i}). After this NOBODY can open it again \u2014 irreversible.
69
- Ask the user to approve, then call nodata_burn again with confirm: true.`);let u;try{u=await va(`${t}/api/lock/public/burn/${i}`,{wrapKeyB64Url:d})}catch(p){return z(`Could not reach NoData: ${p instanceof Error?p.message:String(p)}`,!0)}return u.status>=400||u.body.ok!==!0?z(`Burn refused (HTTP ${u.status}): ${JSON.stringify(u.body)}`,!0):z([`BURNED ${i} \u2014 ${r()}. The ciphertext is zeroed; the link is dead for everyone.`,u.body.proof_url?`Proof (signed receipt, public): ${u.body.proof_url}`:""].filter(Boolean).join(`
70
- `))})}import{z as tn}from"zod";import ke from"node:crypto";var pr=Buffer.from([78,68,67,49]),Fl=2,fr=36,Et=32,Ll=64,Ul=12,Hl=16,Vl=4096,Gl=256,Aa=32,hr=8,ql=1;async function Wl(){let[{CipherSuite:e,HkdfSha256:t},{DhkemX25519HkdfSha256:n},{Chacha20Poly1305:r}]=await Promise.all([import("@hpke/core"),import("@hpke/dhkem-x25519"),import("@hpke/chacha20poly1305")]);return new e({kem:new n,kdf:new t,aead:new r})}function yr(e){let t=new Uint8Array(e.length);return t.set(e),t.buffer}async function Jl(e,t){let n=t.trim();if(n.includes("-----BEGIN PUBLIC KEY-----")){let o=n.replace(/-----BEGIN PUBLIC KEY-----/,"").replace(/-----END PUBLIC KEY-----/,"").replace(/\s+/g,"");return e.kem.deserializePublicKey(yr(Buffer.from(o,"base64")))}let r=Buffer.from(n.replace(/-/g,"+").replace(/_/g,"/"),"base64");if(r.length!==32)throw new Error(`master pubkey must be a 32-byte X25519 key, got ${r.length} bytes`);return e.kem.deserializePublicKey(yr(r))}function zl(e){let t=ke.createPublicKey({key:e,format:"pem"}).export({format:"der",type:"spki"});if(t.length<Et)throw new Error("unexpected Ed25519 SPKI DER length");return t.subarray(t.length-Et)}function Yl(e){return ke.createHash("sha256").update(e,"utf8").digest().subarray(0,hr)}async function Ta(e){let t=Buffer.from(e.filename,"utf8");if(t.length>Vl)throw new Error("filename too long");let n=Buffer.from(e.contentType,"utf8");if(n.length>Gl)throw new Error("content-type too long");let r=e.receiptId??ke.randomUUID(),o=Buffer.from(r,"utf8");if(o.length!==fr)throw new Error("receiptId must be a 36-char canonical UUID");let a=zl(e.issuerPubkeyPem);if(a.length!==Et)throw new Error("issuer pubkey must be 32 bytes");let i=ke.randomBytes(32),s=ke.randomBytes(Ul),l=ke.createCipheriv("aes-256-gcm",i,s),d=Buffer.concat([l.update(e.fileBytes),l.final()]),u=l.getAuthTag();if(u.length!==Hl)throw new Error("unexpected GCM tag length");let p=ke.createHash("sha256").update(e.fileBytes).digest(),h=await Wl(),m=await Jl(h,e.recipientPubkeyB64),v=await h.createSenderContext({recipientPublicKey:m}),k=Buffer.from(v.enc),S=Buffer.from(await v.seal(yr(i))),_=Yl(e.recipientPubkeyB64),w=1+hr+2+k.length+2+S.length,x=pr.length+1+fr+Et+2+t.length+2+n.length+8+Aa+w,y=Buffer.alloc(x),g=0;pr.copy(y,g),g+=pr.length,y[g++]=Fl,o.copy(y,g),g+=fr,a.copy(y,g),g+=Et,y.writeUInt16LE(t.length,g),g+=2,t.copy(y,g),g+=t.length,y.writeUInt16LE(n.length,g),g+=2,n.copy(y,g),g+=n.length,y.writeBigUInt64LE(BigInt(e.issuedAt??Date.now()),g),g+=8,p.copy(y,g),g+=Aa,y[g++]=ql,_.copy(y,g),g+=hr,y.writeUInt16LE(k.length,g),g+=2,k.copy(y,g),g+=k.length,y.writeUInt16LE(S.length,g),g+=2,S.copy(y,g),g+=S.length;let N=ke.sign(null,y,e.issuerPrivateKey);if(N.length!==Ll)throw new Error("header signature must be 64 bytes");let $=Buffer.concat([y,N,s,u,d]),D={relative_path:"",plaintext_sha256:p.toString("hex"),size_bytes:e.fileBytes.length,lockbox_id:e.lockboxId??null,ndc_version:2,recovery_alg:1,recovery_master_fp:_.toString("hex"),header_sig_b64:N.toString("base64"),content_key_b64:i.toString("base64")};return{ndcBytes:$,report:D}}import{createPrivateKey as Pa,createPublicKey as Da,generateKeyPairSync as Xl}from"node:crypto";import{existsSync as gr,mkdirSync as Zl,readFileSync as Ia,rmSync as Ql,statSync as nn,writeFileSync as Ca}from"node:fs";import{homedir as Oa}from"node:os";import{basename as kt,extname as ed,join as _r,resolve as td}from"node:path";var ue=(e,t=!1)=>({content:[{type:"text",text:e}],...t?{isError:t}:{}}),xt="mcp-archive",mr=25,Na=25*1024*1024,nd={".pdf":"application/pdf",".txt":"text/plain",".csv":"text/csv",".md":"text/markdown",".json":"application/json",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".docx":"application/vnd.openxmlformats-officedocument.wordprocessingml.document",".xlsx":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",".pptx":"application/vnd.openxmlformats-officedocument.presentationml.presentation"},rd={critical:"restricted",high:"confidential",medium:"internal",low:"internal",info:"internal"};function Ra(e,t){if(e){let o=Pa({key:Buffer.from(e,"base64"),format:"der",type:"pkcs8"});return{privateKey:o,publicPem:Da(o).export({format:"pem",type:"spki"}),label:`device ${t??""}`.trim()}}let n=_r(Oa(),".nodata","issuer-ed25519.json");if(gr(n)){let o=JSON.parse(Ia(n,"utf8")).private_pem,a=Pa(o);return{privateKey:a,publicPem:Da(a).export({format:"pem",type:"spki"}),label:"this machine"}}let r=Xl("ed25519");return Zl(_r(Oa(),".nodata"),{recursive:!0}),Ca(n,JSON.stringify({private_pem:r.privateKey.export({format:"pem",type:"pkcs8"})},null,2)+`
71
- `,{mode:384}),{privateKey:r.privateKey,publicPem:r.publicKey.export({format:"pem",type:"spki"}),label:"this machine"}}function $a(e,t,n,r){e.registerTool("nodata_wrap",{description:"WRAP files into your organization's sovereign archive (a zero-knowledge capsule): each file is encrypted ON THIS MACHINE to the public half of your org master key \u2014 the 12 words from signup \u2014 and only ciphertext is uploaded. NoData can never open it; your 12 words (or recovery file) always can, even if this computer is lost or NoData is offline. Each document gets a signed receipt and proof_url. Given a folder, wraps the files the scan finds exposure in (classified by severity); given a file, wraps that file. ASKS FIRST: without confirm:true it only lists what would be wrapped. keep_local:true (default) also writes <file>.capsule.ndc next to the original; remove:true deletes the plaintext originals after a successful upload.",inputSchema:{path:tn.string().describe("File or folder to wrap."),confirm:tn.boolean().optional().describe("true = wrap it. Omit to preview."),keep_local:tn.boolean().optional().describe("Also keep <file>.capsule.ndc next to the original. Default true."),remove:tn.boolean().optional().describe("Delete plaintext originals after upload. Default false.")}},async({path:o,confirm:a,keep_local:i,remove:s})=>{let l=td(o);if(!gr(l))return ue(`Not found: ${l}`,!0);let d;if(nn(l).isDirectory()?d=Ae(await rt({target_id:"mcp",target_label:kt(l),target_path:l,log:ot})).byFile.map(g=>({path:_r(l,g.key),classification:rd[g.worst]??"internal"})):d=[{path:l,classification:"confidential"}],d=d.filter(y=>gr(y.path)&&nn(y.path).isFile()&&!Bn(y.path)),d.length===0)return ue(`Nothing to wrap in ${l} \u2014 no file with findings.`);let u=d.filter(y=>nn(y.path).size>Na);d=d.filter(y=>nn(y.path).size<=Na);let p=await t.get("/api/v1/recovery/pubkey");if(p.status===401||p.status===403)return ue(`Not authorized to read the org key (HTTP ${p.status}). Connect with nodata_connect.`,!0);let h=typeof p.body.pubkeyB64=="string"?p.body.pubkeyB64:null;if(!h)return ue(`Your organization has no master key yet \u2014 the 12-word recovery setup was not completed, so there is nothing to wrap to.
72
- Finish it once in the console (Recovery setup), then wrap again. NoData never sees the words.`,!0);if(!a){let y=d.slice(0,mr).map(g=>` \xB7 [${g.classification}] ${g.path}`);return d.length>mr&&y.push(` \u2026 and ${d.length-mr} more`),ue([`PREVIEW \u2014 nothing wrapped yet. ${r()}`,`Would wrap ${d.length} file(s) into the "${xt}" capsule, sealed to your org master key (fingerprint ${p.body.fingerprint??"?"}):`,...y,u.length?`Skipped (over 25 MB): ${u.map(g=>kt(g.path)).join(", ")}`:"",`Encrypted here; only ciphertext is uploaded. Opens with your 12 words \u2014 never with NoData.${s?" Plaintext originals WILL BE DELETED after upload.":""}`,"","Ask the user to approve, then call nodata_wrap again with the same arguments and confirm: true."].filter(Boolean).join(`
73
- `))}let m=await t.get("/api/v1/capsules");if(m.status>=400)return ue(`Could not list capsules (HTTP ${m.status}): ${JSON.stringify(m.body)}`,!0);let k=(m.body.capsules??[]).find(y=>y.slug===xt);if(k&&k.key_mode!=="zk")return ue(`A "${xt}" capsule exists but is not zero-knowledge (key_mode ${String(k.key_mode)}) \u2014 refusing to wrap into it.`,!0);if(!k){let y=await t.post("/api/v1/capsules",{handle:xt,display_name:"MCP archive",key_mode:"zk",capsule_pubkey:h});if(y.status>=400)return ue(`Could not create the archive capsule (HTTP ${y.status}): ${JSON.stringify(y.body)}`,!0);k=y.body}let S=String(k.slug??k.capsule_id??"");if(!S)return ue(`Capsule id missing in ${JSON.stringify(k)}`,!0);let _=n(),w=[],x=[];for(let y of d){let g=Ia(y.path),{ndcBytes:N,report:$}=await Ta({fileBytes:g,filename:kt(y.path),contentType:nd[ed(y.path).toLowerCase()]??"application/octet-stream",recipientPubkeyB64:h,issuerPrivateKey:_.privateKey,issuerPubkeyPem:_.publicPem}),D=await t.post(`/api/v1/capsules/${encodeURIComponent(S)}/documents`,{title:kt(y.path),ndc_b64:N.toString("base64"),classification:y.classification,plaintext_sha256:$.plaintext_sha256,size_bytes:$.size_bytes});if(D.status>=400||D.body.ok!==!0){x.push(` \u2717 ${y.path} \u2014 HTTP ${D.status}: ${JSON.stringify(D.body).slice(0,200)}`);continue}i!==!1&&Ca(`${y.path}.capsule.ndc`,N,{mode:384}),s&&Ql(y.path),w.push(` \u2713 [${y.classification}] ${kt(y.path)}${D.body.proof_url?` proof: ${D.body.proof_url}`:""}`)}return ue([`WRAPPED ${w.length}/${d.length} into "${xt}" \u2014 ${r()} \xB7 signed by ${_.label}`,...w,...x,"Sealed to your org master key: NoData stores ciphertext only and cannot open it. Your 12 words (or recovery file) open every document.",i!==!1?"Local copies: <file>.capsule.ndc next to each original.":"",s?"Plaintext originals deleted (only for files that uploaded).":""].filter(Boolean).join(`
74
- `),x.length>0&&w.length===0)})}import{homedir as La,hostname as Ua}from"node:os";import{join as rn,resolve as br}from"node:path";import{existsSync as vr,readFileSync as Ha,writeFileSync as Va,mkdirSync as Ga,chmodSync as id}from"node:fs";import{spawn as sd}from"node:child_process";import{generateKeyPairSync as cd,createPrivateKey as ld,sign as dd,randomBytes as ud}from"node:crypto";var wr="1.3.0",qa=rn(La(),".nodata"),on=rn(qa,"credentials.json");function pd(){try{if(!vr(on))return null;let e=JSON.parse(Ha(on,"utf8"));if(!e)return null;let t=e.device&&typeof e.device.private_key_pkcs8_b64=="string",n=typeof e.api_key=="string"&&e.api_key;return t||n?e:null}catch{return null}}function Ba(e){Ga(qa,{recursive:!0});let t=JSON.stringify({...e,saved_at:new Date().toISOString()},null,2);Va(on,t,{mode:384});try{id(on,384)}catch{}}var fd=`nodata-mcp v${wr} \u2014 NoData MCP server
51
+ </main></body></html>`}var so={israeli_id:"[ID]",credit_card:"[CARD]",iban:"[IBAN]",israeli_phone:"[PHONE]",email:"[EMAIL]"},Rs=/[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}/g,Bs=[...Tn].sort((e,t)=>+(t.subkind==="iban")-+(e.subkind==="iban"));function Mn(e,t,n=1){e[t]=(e[t]??0)+n}function re(e,t={}){let n=e;for(let r of Bs)r.pattern.lastIndex=0,n=n.replace(r.pattern,o=>r.validate(o)?(Mn(t,r.subkind),so[r.subkind]??`[${r.subkind.toUpperCase()}]`):o);return n=n.replace(Rs,()=>(Mn(t,"email"),so.email)),{text:n,counts:t,columnsHidden:[]}}function co(e,t){return e.includes(t)||e.includes('"')||e.includes(`
52
+ `)?`"${e.replace(/"/g,'""')}"`:e}function js(e){let t=(e.match(/\t/g)??[]).length,n=(e.match(/;/g)??[]).length,r=(e.match(/,/g)??[]).length;return t>r&&t>=n?" ":n>r?";":","}function pt(e,t){let n=e.split(/\r?\n/),r=t??js(n[0]??""),o=Ue(n[0]??"",r),a=o.map(c=>Ne(c)),i={},s=[o.map(c=>co(c,r)).join(r)];for(let c of n.slice(1)){if(c===""){s.push(c);continue}let d=Ue(c,r).map((u,p)=>{let f=a[p];return f&&u.trim()!==""?(Mn(i,`column:${f.type}`),`[${f.type.toUpperCase()}]`):re(u,i).text});s.push(d.map(u=>co(u,r)).join(r))}return{text:s.join(`
53
+ `),counts:i,columnsHidden:o.filter((c,d)=>a[d])}}import{deflateRawSync as Ks}from"node:zlib";var Ls=/^xl\/(pivotCache|charts|externalLinks)\//,Ms=10;function Fs(e,t,n=1){e[t]=(e[t]??0)+n}function fo(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function ho(e){let t=e.replace(/<rPh\b[\s\S]*?<\/rPh>/g,""),n="";for(let r of t.matchAll(/<t(?:\s[^>]*)?>([\s\S]*?)<\/t>/g))n+=r[1];return He(n)}function Us(e){return e?[...e.matchAll(/<si\b[^>]*>([\s\S]*?)<\/si>|<si\b[^>]*\/>/g)].map(t=>ho(t[1]??"")):[]}var lo=/<c\b([^>]*?)(?:\/>|>([\s\S]*?)<\/c>)/g;function Mt(e,t){let n=new RegExp(`\\b${t}="([^"]*)"`).exec(e);return n?n[1]:null}function uo(e,t){if(e.type==="s"){let r=/<v>([^<]*)<\/v>/.exec(e.inner);return r?t[Number(r[1])]??null:null}if(e.type==="inlineStr"){let r=/<is>([\s\S]*?)<\/is>/.exec(e.inner);return r?ho(r[1]):null}if(e.type==="b"||e.type==="e")return null;let n=/<v>([^<]*)<\/v>/.exec(e.inner);return n?He(n[1]):null}function po(e,t){return`<c${e.replace(/\s*\bt="[^"]*"/,"")} t="inlineStr"><is><t xml:space="preserve">${fo(t)}</t></is></c>`}var Hs=(()=>{let e=new Uint32Array(256);for(let t=0;t<256;t+=1){let n=t;for(let r=0;r<8;r+=1)n=n&1?3988292384^n>>>1:n>>>1;e[t]=n>>>0}return e})();function Vs(e){let t=4294967295;for(let n=0;n<e.length;n+=1)t=Hs[(t^e[n])&255]^t>>>8;return(t^4294967295)>>>0}function yo(e){let t=[],n=[],r=0;for(let i of e){let s=Buffer.from(i.name,"utf8"),c=i.name.endsWith("/"),d=c?Buffer.alloc(0):Ks(i.data),u=c?0:8,p=c?0:Vs(i.data),f=Buffer.alloc(30);f.writeUInt32LE(67324752,0),f.writeUInt16LE(20,4),f.writeUInt16LE(2048,6),f.writeUInt16LE(u,8),f.writeUInt32LE(p,14),f.writeUInt32LE(d.length,18),f.writeUInt32LE(i.data.length,22),f.writeUInt16LE(s.length,26),t.push(f,s,d);let y=Buffer.alloc(46);y.writeUInt32LE(33639248,0),y.writeUInt16LE(20,4),y.writeUInt16LE(20,6),y.writeUInt16LE(2048,8),y.writeUInt16LE(u,10),y.writeUInt32LE(p,16),y.writeUInt32LE(d.length,20),y.writeUInt32LE(i.data.length,24),y.writeUInt16LE(s.length,28),y.writeUInt32LE(r,42),n.push(y,s),r+=f.length+s.length+d.length}let o=Buffer.concat(n),a=Buffer.alloc(22);return a.writeUInt32LE(101010256,0),a.writeUInt16LE(e.length,8),a.writeUInt16LE(e.length,10),a.writeUInt32LE(o.length,12),a.writeUInt32LE(r,16),Buffer.concat([...t,o,a])}function ft(e){let t=Nn(e);if(!t||t.length===0||t.some(f=>Ls.test(f.name)))return null;let n=new Map;for(let f of t){if(f.name.endsWith("/")){n.set(f.name,Buffer.alloc(0));continue}let y=On(e,f);if(!y)return null;n.set(f.name,y)}let r=[...n.keys()].filter(f=>/^xl\/worksheets\/sheet\d+\.xml$/.test(f));if(r.length===0)return null;let o=n.get("xl/sharedStrings.xml")?.toString("utf8")??null,a=Us(o),i=new Set,s={},c=new Set;for(let f of r){let y=n.get(f).toString("utf8"),_=[];for(let E of y.matchAll(lo)){let m=Mt(E[1],"r"),g=m?/^([A-Z]+)(\d+)$/.exec(m):null;if(!g)return null;_.push({full:E[0],attrs:E[1],inner:E[2]??"",col:g[1],row:Number(g[2]),type:Mt(E[1],"t")??"n"})}let k=[...new Set(_.map(E=>E.row))].sort((E,m)=>E-m).slice(0,Ms),b=-1,S=new Map;for(let E of k){let m=new Map;for(let g of _.filter(A=>A.row===E)){let A=uo(g,a),I=A?Ne(A):null;I&&(m.set(g.col,I.type),c.add(A.trim()))}if(m.size>0){b=E;for(let[g,A]of m)S.set(g,A);break}}let v=y.replace(lo,(E,m,g)=>{let A=Mt(m,"r"),[,I,P]=/^([A-Z]+)(\d+)$/.exec(A),x={full:E,attrs:m,inner:g??"",col:I,row:Number(P),type:Mt(m,"t")??"n"},O=uo(x,a),$=()=>{if(x.type==="s"){let J=/<v>([^<]*)<\/v>/.exec(x.inner);J&&i.add(Number(J[1]))}return E};if(O===null||O.trim()==="")return $();let B=S.get(I);if(B&&x.row>b)return Fs(s,`column:${B}`),po(m,`[${B.toUpperCase()}]`);let W=re(O,s);return W.text===O?$():po(m,W.text)});n.set(f,Buffer.from(v,"utf8"))}if(o){let f=-1,y=o.replace(/<si\b[^>]*>[\s\S]*?<\/si>|<si\b[^>]*\/>/g,_=>(f+=1,i.has(f)?_:"<si><t></t></si>"));n.set("xl/sharedStrings.xml",Buffer.from(y,"utf8"))}for(let f of[...n.keys()].filter(y=>/^xl\/comments\d*\.xml$/.test(y))){let _=n.get(f).toString("utf8").replace(/(<t(?:\s[^>]*)?>)([\s\S]*?)(<\/t>)/g,(k,b,S,v)=>{let E=re(He(S),s);return`${b}${fo(E.text)}${v}`});n.set(f,Buffer.from(_,"utf8"))}let d=n.get("docProps/core.xml");if(d){let f=d.toString("utf8").replace(/(<dc:creator>)[\s\S]*?(<\/dc:creator>)/,"$1$2").replace(/(<cp:lastModifiedBy>)[\s\S]*?(<\/cp:lastModifiedBy>)/,"$1$2");n.set("docProps/core.xml",Buffer.from(f,"utf8"))}let u=n.has("xl/calcChain.xml"),p=t.map(f=>f.name).filter(f=>!(u&&f==="xl/calcChain.xml"));if(u)for(let f of["[Content_Types].xml","xl/_rels/workbook.xml.rels"]){let y=n.get(f);y&&n.set(f,Buffer.from(y.toString("utf8").replace(/<(Override|Relationship)\b[^>]*calcChain[^>]*\/>/g,""),"utf8"))}return{bytes:yo(p.map(f=>({name:f,data:n.get(f)}))),counts:s,columnsHidden:[...c]}}var oe=Jr(No(),1);import{homedir as Sc}from"node:os";import{basename as qt,dirname as Vt,extname as wc,join as gt,resolve as Gt}from"node:path";import{existsSync as mt,mkdirSync as vc,readFileSync as kc,rmSync as Ec,statSync as Wn,writeFileSync as Jn}from"node:fs";import{pathToFileURL as Xn}from"node:url";function Ge(e){return/\.ndc$/i.test(e)||/\.clean\.[A-Za-z0-9]+$/.test(e)}var G=(e,t=!1)=>({content:[{type:"text",text:e}],...t?{isError:t}:{}}),Oo=gt(Sc(),".nodata","reports"),zn=25;function xc(){return new Date().toISOString().replace(/[:.]/g,"-").slice(0,19)}function Ac(e){return e.replace(/[^A-Za-z0-9_-]+/g,"_").slice(0,60)||"folder"}async function Co(e){return dt({target_id:"mcp",target_label:qt(e),target_path:e,log:ut})}function Yn(e,t){let n=e.slice(0,t).map(r=>` ${String(r.total).padStart(6)} ${r.worst.padEnd(8)} ${r.key}`);return e.length>t&&n.push(` \u2026 ${e.length-t} more in the full report`),n.join(`
54
+ `)}function Tc(e,t,n,r){if(e.error)return`Could not scan ${e.target_path}: ${e.error}`;let o=["critical","high","medium","low","info"].filter(i=>t.bySeverity[i]).map(i=>`${t.bySeverity[i]} ${i}`).join(" \xB7 "),a=[`SCAN ${e.target_path}`,` ${r} \xB7 ran on this machine, nothing uploaded`,` ${e.files_walked} files walked, ${e.files_inspected} inspected, ${e.duration_ms} ms`,"",`FOUND ${t.total} findings${o?" \u2014 "+o:""} in ${t.filesWithFindings.length} files`];return t.total>0&&(a.push("","BY TYPE (all)",Yn(t.byType,100)),a.push("","BY FOLDER",Yn(t.byFolder,10)),a.push("","WORST FILES",Yn(t.byFile,12))),n&&a.push("","FULL REPORT (every finding, content-free) \u2014 open in a browser:",` ${Xn(n).href}`),t.total>0&&a.push("","NEXT \u2014 same workspace:",` \xB7 LOCK the ${t.filesWithFindings.length} files with findings: nodata_protect path: "${e.target_path}" (asks before it changes anything)`,' \xB7 WORK on a clean copy (values replaced by [CARD], [ID] \u2026): nodata_redact path: "<file>"'," \xB7 A database table instead of files: nodata_register_table \u2192 nodata_grant"),a.join(`
55
+ `)}function Io(e,t){e.registerTool("nodata_scan_folder",{description:"SEE what's sensitive. Scans a LOCAL folder for hardcoded secrets and unencrypted PII (checksum-validated Israeli ID, Luhn credit card, IBAN, phones), reading PDF and Office files too, entirely on this machine. Returns the WHOLE result \u2014 counts by type, by folder and by file \u2014 and writes a full content-free HTML report (every finding) to ~/.nodata/reports, with a link to open it. Then offers the next step in the same workspace: nodata_protect (lock the files with findings) or nodata_redact (a clean copy to work on). Call this when the user asks to scan/audit/check a folder.",inputSchema:{path:_e.string().optional().describe("Folder to scan. Default: the directory the server runs in.")}},async({path:r})=>{let o=Gt((r??".").trim()||".");if(!mt(o))return G(`No folder found at: ${o}`);try{let a=await Co(o),i=Ce(a),s=null;return a.error||(vc(Oo,{recursive:!0}),s=gt(Oo,`scan-${Ac(qt(o))}-${xc()}.html`),Jn(s,Ln(a,i),{mode:384})),G(Tc(a,i,s,t()))}catch(a){return G(`Scan failed: ${a instanceof Error?a.message:String(a)}`,!0)}}),e.registerTool("nodata_protect",{description:"LOCK files: seal each one to this device's key as <file>.ndc (AES-256-GCM, the key never leaves this machine; the same format as `nodata protect`, so `nodata open` opens it too). Given a folder, seals only the files the scan finds exposure in; given a file, seals that file. ASKS FIRST: without confirm:true it only lists what would be sealed and changes nothing \u2014 show that list to the user and call again with confirm:true only after they approve. Writes a local receipt (hashes, seal ids) under <folder>/.nodata/receipts. remove:true also deletes the plaintext originals.",inputSchema:{path:_e.string().describe("File or folder to protect."),confirm:_e.boolean().optional().describe("true = do it. Omit to preview."),remove:_e.boolean().optional().describe("Delete the plaintext originals after sealing. Default false.")}},async({path:r,confirm:o,remove:a})=>{let i=Gt(r);if(!mt(i))return G(`Not found: ${i}`,!0);let s=Wn(i).isDirectory(),c;if(s?c=Ce(await Co(i)).filesWithFindings.map(k=>gt(i,k)).filter(k=>mt(k)&&Wn(k).isFile()&&!Ge(k)):c=i.endsWith(".ndc")?[]:[i],c.length===0)return G(`Nothing to seal in ${i} \u2014 no file with findings.`);if(!o){let _=c.slice(0,zn).map(k=>` \xB7 ${k}`);return c.length>zn&&_.push(` \u2026 and ${c.length-zn} more`),G([`PREVIEW \u2014 nothing changed yet. ${t()}`,`Would seal ${c.length} file(s) to this device's key${a?" and DELETE the plaintext originals":" (originals kept)"}:`,..._,"","Ask the user to approve, then call nodata_protect again with confirm: true."].join(`
56
+ `))}let{key:d,created:u}=oe.ensureDeviceKey(),p=[];for(let _ of c)p.push(await oe.sealFile(_,d)),a&&Ec(_);let f=s?i:Vt(i),y=oe.writeLocalReceipt(f,{action:"protect",kid:d.kid,removed_plaintext:!!a,files:p,extra:{approved_by:t(),surface:"mcp"}});return G([`SEALED ${p.length} file(s) \u2014 ${t()}${u?" \xB7 a new device key was created at ~/.nodata/device-key.json (back it up: without it these files cannot be opened)":""}`,`device key id: ${d.kid}`,a?"Plaintext originals deleted.":"Originals are still in place \u2014 run again with remove: true to leave only the sealed copies.",`Receipt (hashes + seal ids, content-free): ${Xn(y).href}`,'Open one again: nodata_open path: "<file>.ndc"'].join(`
57
+ `))}),e.registerTool("nodata_open",{description:"RELEASE a sealed file: open <file>.ndc back to its original next to it (never overwrites), with this device's key, and check its hash matches what was sealed. ASKS FIRST: without confirm:true it only says what would be opened. Writes a local receipt.",inputSchema:{path:_e.string().describe("The .ndc file to open."),confirm:_e.boolean().optional().describe("true = open it. Omit to preview.")}},async({path:r,confirm:o})=>{let a=Gt(r),i=mt(a)?oe.readManifest(a):null;if(!i)return G(`Not a NoData sealed file: ${a}`,!0);if(!o)return G(`PREVIEW \u2014 nothing changed yet. ${t()}
58
+ Would open "${i.orig}" (sealed ${i.sealed_at}, device key ${i.kid}) as plaintext next to ${a}.
59
+ Ask the user to approve, then call nodata_open again with confirm: true.`);let s=await oe.openFile(a);if(!s.ok){let d=s.error==="wrong_key"?"this device's key is not the one it was sealed to":s.error==="no_device_key"?"this machine has no device key (~/.nodata/device-key.json)":s.error;return G(`Could not open ${a}: ${d}.`,!0)}let c=oe.writeLocalReceipt(Vt(a),{action:"open",kid:i.kid,removed_plaintext:!1,files:[{path:s.outPath,ndc:a,sha256:s.sha256,sealId:i.token.split(":").pop()??""}],extra:{approved_by:t(),surface:"mcp",hash_matches:s.intact}});return G([`OPENED ${s.outPath} \u2014 ${t()}`,s.intact?"Hash matches what was sealed \u2014 the file is unaltered.":"WARNING: hash differs from the sealed record.",`Receipt: ${Xn(c).href}`].join(`
60
+ `))}),e.registerTool("nodata_redact",{description:"WORK on the rest: make a clean copy of a file with every sensitive value replaced by a typed token ([CARD], [ID], [IBAN], [PHONE], [EMAIL]); in CSV/TSV and Excel a column whose header names personal data (name, address, account number\u2026) is hidden whole, so rows and columns still line up. Same detectors as the scan. In Excel (.xlsx) the same column rule applies per sheet and the copy stays a workbook with its formatting. The original is untouched; the copy is written next to it as <name>.clean.<ext> (Word/PowerPoint/PDF \u2192 .clean.txt). return_text:true also returns the clean text (up to 60 KB) so it can be analysed right here \u2014 it contains no detected value.",inputSchema:{path:_e.string().describe("The file to redact (csv, tsv, txt, md, json, log, docx, xlsx, pptx, pdf)."),return_text:_e.boolean().optional().describe("Also return the clean text for analysis.")}},async({path:r,return_text:o})=>{let a=Gt(r);if(!mt(a)||!Wn(a).isFile())return G(`Not a file: ${a}`,!0);let i=wc(a).toLowerCase(),s=kc(a),c,d=i||".txt",u="",p=i===".xlsx"||i===".xlsm"?ft(s):null;if(p){let y=gt(Vt(a),`${qt(a,i)}.clean${i}`);return Jn(y,p.bytes,{mode:384}),c={text:Oe(p.bytes,i)?.text??"",counts:p.counts,columnsHidden:p.columnsHidden},G(n(y,c,o))}if((i===".xlsx"||i===".xlsm")&&(u="This workbook has pivot tables, charts or external links, which keep their own copies of the values \u2014 the clean copy is plain text, not a workbook."),i===".csv"||i===".tsv")c=pt(s.toString("utf8"),i===".tsv"?" ":void 0);else if(Lt.has(i)){let y=Oe(s,i);if(!y)return G(`Could not read the text of ${a}.`,!0);c=re(y.text),d=".txt"}else c=re(s.toString("utf8"));let f=gt(Vt(a),`${qt(a,i)}.clean${d}`);return Jn(f,c.text,{mode:384}),G(n(f,c,o,u))});function n(r,o,a,i=""){let s=Object.entries(o.counts).sort((d,u)=>u[1]-d[1]).map(([d,u])=>` ${String(u).padStart(6)} ${d}`),c=[`CLEAN COPY ${r} \u2014 ${t()} \xB7 original untouched`,i,s.length?`Replaced:
61
+ ${s.join(`
62
+ `)}`:"Nothing sensitive detected \u2014 the copy equals the original text.",o.columnsHidden.length?`Columns hidden whole: ${o.columnsHidden.join(", ")}`:""].filter(Boolean);return a&&c.push("",`--- clean text${o.text.length>6e4?" (first 60000 chars)":""} ---`,o.text.slice(0,6e4)),c.join(`
63
+ `)}}var hn=Jr(Va(),1);import{z as Fe}from"zod";import{createHash as Ld}from"node:crypto";import{existsSync as Ar,mkdirSync as Md,readFileSync as za,readdirSync as Fd,statSync as Ga,writeFileSync as Ud}from"node:fs";import{homedir as Hd}from"node:os";import{basename as xr,extname as Vd,join as Ya,resolve as Gd}from"node:path";var X=(e,t=!1)=>({content:[{type:"text",text:e}],...t?{isError:t}:{}}),fn=Ya(Hd(),".nodata","shares"),qd=12*1024*1024,Wd={".pdf":"application/pdf",".txt":"text/plain",".csv":"text/csv",".md":"text/markdown",".json":"application/json",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".docx":"application/vnd.openxmlformats-officedocument.wordprocessingml.document",".xlsx":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",".pptx":"application/vnd.openxmlformats-officedocument.presentationml.presentation"};function Xa(e){return Ya(fn,`${e.replace(/[^a-f0-9]/gi,"")}.json`)}function qa(e){let t=Xa(e);if(!Ar(t))return null;try{return JSON.parse(za(t,"utf8"))}catch{return null}}function Wa(e){let t=e.match(/\/lock\/open\/([a-f0-9]{8,64})/i);return(t?t[1]:e.trim()).toLowerCase()}async function Ja(e,t,n){let r=await fetch(e,{method:"POST",headers:{"content-type":"application/json",...n?{authorization:`Bearer ${n}`}:{}},body:JSON.stringify(t)});return{status:r.status,body:await r.json().catch(()=>({}))}}function Za(e,t,n,r){e.registerTool("nodata_send",{description:"SEND a file as a governed link: encrypted on this machine (post-quantum hybrid), stored by NoData only as ciphertext \u2014 the key rides in the link's #fragment, which NoData never receives. Expires after ttl and after max_opens opens; can be burned (nodata_burn) at any time, after which nobody can open it again. Filed under your organization with a signed receipt and a proof_url. ASKS FIRST: without confirm:true it only shows what would be sent. Returns the link to hand to the recipient.",inputSchema:{path:Fe.string().describe("The file to send (up to 12 MB)."),ttl_hours:Fe.number().optional().describe("Hours until the link expires. Default 72, max 168 (7 days)."),max_opens:Fe.number().optional().describe("Opens allowed before it burns itself. Default 3, max 1000."),confirm:Fe.boolean().optional().describe("true = send it. Omit to preview.")}},async({path:o,ttl_hours:a,max_opens:i,confirm:s})=>{let c=Gd(o);if(!Ar(c)||!Ga(c).isFile())return X(`Not a file: ${c}`,!0);let d=Ga(c).size;if(d>qd)return X(`${xr(c)} is ${(d/1048576).toFixed(1)} MB; a governed link carries up to 12 MB.`,!0);let u=Math.round(Math.min(Math.max(a??72,1/60),168)*3600),p=Math.round(Math.min(Math.max(i??3,1),1e3));if(!s)return X([`PREVIEW \u2014 nothing sent yet. ${r()}`,`Would send "${xr(c)}" (${(d/1024).toFixed(1)} KB) as a governed link:`," \xB7 encrypted here; NoData stores only ciphertext and never gets the key",` \xB7 expires in ${(u/3600).toFixed(u<3600?2:0)} h, or after ${p} open(s)`," \xB7 revocable any time with nodata_burn; every open is counted","","Ask the user to approve, then call nodata_send again with the same arguments and confirm: true."].join(`
64
+ `));let f=za(c),y=xr(c),_=Wd[Vd(c).toLowerCase()]??"application/octet-stream",k=await(0,hn.sealBytesForPublicShare)({bytes:f,filename:y,contentType:_,ttlSeconds:u,server:t}),b=await(0,hn.wrapFragmentForShortLink)(k.fragment),S;try{S=await Ja(`${t}/api/lock/public/issue`,{formatVersion:3,lockboxId:k.lockboxId,containerB64:Buffer.from(k.container).toString("base64"),filename:y,contentType:_,ttlSeconds:u,maxOpens:p,wrappedFragmentB64:b.wrappedFragmentB64,wrapIvB64:b.wrapIvB64},await n())}catch(m){return X(`Could not reach NoData: ${m instanceof Error?m.message:String(m)}`,!0)}if(S.status>=400||S.body.ok!==!0)return X(`Send refused (HTTP ${S.status}): ${JSON.stringify(S.body)}`,!0);let v=String(S.body.id),E={id:v,file:c,filename:y,sha256:Ld("sha256").update(f).digest("hex"),link:`${t}/lock/open/${v}#${b.wrapKeyB64Url}`,wrap_key_b64url:b.wrapKeyB64Url,expires_at:String(S.body.expiresAt??""),max_opens:p,sent_by:r(),sent_at:new Date().toISOString(),receipt_id:S.body.receipt_id??null,proof_url:S.body.proof_url??null};return Md(fn,{recursive:!0}),Ud(Xa(v),JSON.stringify(E,null,2)+`
65
+ `,{mode:384}),X([`SENT "${y}" \u2014 ${r()}`,"Link (give this to the recipient; anyone holding it can open it until it expires or is burned):",` ${E.link}`,`Expires ${E.expires_at} \xB7 max ${p} open(s) \xB7 id ${v}`,E.proof_url?`Proof (signed receipt, public): ${E.proof_url}`:"No receipt: the link was not attributed to an organization.",`Check it: nodata_link_status id: "${v}" \xB7 Revoke it: nodata_burn id: "${v}"`].join(`
66
+ `))}),e.registerTool("nodata_link_status",{description:"STATUS of links sent with nodata_send: opens so far, expiry, whether burned. Pass an id or link for one; omit to list every link sent from this machine.",inputSchema:{id:Fe.string().optional().describe("Share id or /lock/open link. Omit to list all.")}},async({id:o})=>{let a=o?[Wa(o)]:Ar(fn)?Fd(fn).filter(s=>s.endsWith(".json")).map(s=>s.slice(0,-5)):[];if(a.length===0)return X("No links sent from this machine yet. Send one with nodata_send.");let i=[`LINKS \u2014 ${r()}`];for(let s of a.slice(0,50)){let c=qa(s),d={};try{let p=await fetch(`${t}/api/lock/public/status/${s}`);d=await p.json().catch(()=>({})),p.status===404&&(d={missing:!0})}catch{d={unreachable:!0}}let u=d.missing?"not found":d.unreachable?"status unavailable":d.burned?"BURNED":d.expired?"expired":"live";i.push(` ${s} ${u.padEnd(10)} opens ${d.openCount??"?"}/${d.maxOpens??c?.max_opens??"?"} expires ${d.expiresAt??c?.expires_at??"?"} ${c?c.filename:""}`)}return X(i.join(`
67
+ `))}),e.registerTool("nodata_burn",{description:"BURN a link sent with nodata_send: the stored ciphertext is zeroed, so nobody \u2014 the recipient, a forwarded copy, NoData \u2014 can open it again. Irreversible. ASKS FIRST: without confirm:true it only says what would be burned. Returns the signed burn receipt and its proof_url.",inputSchema:{id:Fe.string().describe("Share id or the /lock/open link."),confirm:Fe.boolean().optional().describe("true = burn it. Omit to preview.")}},async({id:o,confirm:a})=>{let i=Wa(o),s=o.match(/#([A-Za-z0-9_-]{43})/)?.[1],c=qa(i),d=c?.wrap_key_b64url??s;if(!d)return X(`No burn key for ${i} on this machine. Pass the full link (it carries the key after #), or burn it from the machine that sent it.`,!0);if(!a)return X(`PREVIEW \u2014 nothing burned yet. ${r()}
68
+ Would burn ${c?`"${c.filename}" `:""}(${i}). After this NOBODY can open it again \u2014 irreversible.
69
+ Ask the user to approve, then call nodata_burn again with confirm: true.`);let u;try{u=await Ja(`${t}/api/lock/public/burn/${i}`,{wrapKeyB64Url:d})}catch(p){return X(`Could not reach NoData: ${p instanceof Error?p.message:String(p)}`,!0)}return u.status>=400||u.body.ok!==!0?X(`Burn refused (HTTP ${u.status}): ${JSON.stringify(u.body)}`,!0):X([`BURNED ${i} \u2014 ${r()}. The ciphertext is zeroed; the link is dead for everyone.`,u.body.proof_url?`Proof (signed receipt, public): ${u.body.proof_url}`:""].filter(Boolean).join(`
70
+ `))})}import{appendFileSync as Jd,copyFileSync as Qa,existsSync as Nr,mkdirSync as Or,readFileSync as Cr,statSync as ni,writeFileSync as ri}from"node:fs";import{homedir as Te}from"node:os";import{basename as zd,extname as oi,isAbsolute as Yd,join as Ae,resolve as Xd}from"node:path";var Zd=new Set([".csv",".tsv",".txt",".md",".json",".log",".xml",".sql",".yaml",".yml",".xlsx",".xlsm",".docx",".pptx",".pdf"]),Qd=50*1024*1024,eu=8,tu={israeli_id:"Israeli ID",credit_card:"card",iban:"IBAN",israeli_phone:"phone",email:"email",secret:"secret"};function ai(e){let t=zd(e).toLowerCase();return Zd.has(oi(t))||t===".env"||t.startsWith(".env.")}function nu(e){let t=oi(e).toLowerCase(),n=Cr(e),r,o;if(t===".csv"||t===".tsv")o=n.toString("utf8"),r=pt(o,t===".tsv"?" ":void 0).counts;else if(t===".xlsx"||t===".xlsm"||t===".docx"||t===".pptx"||t===".pdf"){let i=t===".xlsx"||t===".xlsm"?ft(n):null;o=Oe(n,t)?.text??"",r=i?i.counts:re(o).counts}else o=n.toString("utf8"),r=re(o).counts;let a=jt.filter(i=>i.pattern.test(o)).length;return a&&(r.secret=(r.secret??0)+a),r}function ru(e){return Object.entries(e).sort((t,n)=>n[1]-t[1]).map(([t,n])=>`${n} ${t.startsWith("column:")?`${t.slice(7)} (column)`:tu[t]??t}`).join(", ")}function ou(e,t,n){let r=a=>Yd(a)?a:Xd(n,a),o=a=>{try{return ni(a).isFile()}catch{return!1}};if(e==="Read"&&typeof t.file_path=="string")return[r(t.file_path)];if(e==="Grep"&&typeof t.path=="string"&&o(r(t.path)))return[r(t.path)];if(e==="Bash"&&typeof t.command=="string"){let a=t.command.match(/"[^"]*"|'[^']*'|[^\s|;&<>()]+/g)??[],i=[];for(let s of a){let c=r(s.replace(/^['"]|['"]$/g,"").replace(/^~(?=\/)/,Te()));if(ai(c)&&o(c)&&!i.includes(c)&&i.push(c),i.length>=eu)break}return i}return[]}function au(e,t,n,r){let o=[];for(let i of ou(e,t,n)){if(!ai(i)||Ge(i)||!Nr(i))continue;let s;try{if(ni(i).size>Qd)s=`${i}: too large to check here (over 50 MB)`;else{let c=nu(i);if(Object.keys(c).length===0)continue;s=`${i}: ${ru(c)}`}}catch{s=`${i}: could not be checked`}o.push(s)}if(o.length===0)return{decision:"allow"};let a=`NoData scanned this on your machine before the assistant reads it:
71
+ ${o.join(`
72
+ `)}
73
+ Reading it puts these values in front of the AI. Safer: nodata_redact (a clean copy to work on) or nodata_protect (lock it).`+(r?"":" Allow this read anyway?");return{decision:r?"deny":"ask",reason:a}}function iu(e){try{let t=Ae(Te(),".nodata");Or(t,{recursive:!0}),Jd(Ae(t,"gate.log"),JSON.stringify({at:new Date().toISOString(),...e})+`
74
+ `,{mode:384})}catch{}}async function ii(e){let t=e.includes("--block"),n="";for await(let i of process.stdin)n+=i;let r;try{r=JSON.parse(n)}catch{return}let o=r.tool_name??"",a=au(o,r.tool_input??{},r.cwd??process.cwd(),t);a.decision!=="allow"&&(iu({tool:o,decision:a.decision}),process.stdout.write(JSON.stringify({hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:a.decision,permissionDecisionReason:a.reason}})))}var Tr=()=>Ae(Te(),".nodata","gate.mjs"),Ir=()=>Ae(Te(),".claude","settings.json"),ei="Read|Grep|Bash",ti=()=>Ae(Te(),".nodata","status.mjs"),Pr=()=>Ae(Te(),".nodata","statusline-prev.json"),si=e=>!!e&&(e.command.includes(".nodata/status.mjs")||e.command.includes(".nodata\\status.mjs")),Dr=e=>(e.hooks??[]).some(t=>t.command.includes(".nodata/gate.mjs")||t.command.includes(".nodata\\gate.mjs"));function ci(){let e=Ir();return Nr(e)?JSON.parse(Cr(e,"utf8")):{}}function li(e){Or(Ae(Te(),".claude"),{recursive:!0}),ri(Ir(),JSON.stringify(e,null,2)+`
75
+ `)}function di(e,t){Or(Ae(Te(),".nodata"),{recursive:!0}),Qa(e,Tr());let n=ci(),r=n.hooks??={},o=(r.PreToolUse??=[]).filter(a=>!Dr(a));return o.push({matcher:ei,hooks:[{type:"command",command:`node "${Tr().replace(/\\/g,"/")}"${t?" --block":""}`,timeout:30}]}),r.PreToolUse=o,Qa(new URL("./status.js",e),ti()),n.statusLine&&!si(n.statusLine)&&ri(Pr(),JSON.stringify(n.statusLine,null,2)+`
76
+ `),n.statusLine={type:"command",command:`node "${ti().replace(/\\/g,"/")}"`},li(n),`NoData read gate installed (${t?"block":"ask"} mode).
77
+ hook: ${Ir()} \u2192 PreToolUse ${ei}
78
+ scanner: ${Tr()}
79
+ Before Claude Code reads a data file (csv, xlsx, docx, pdf, .env \u2026), NoData scans it here.
80
+ Findings \u2192 ${t?"the read is refused":"you are asked first"}, with the counts and the safer step.
81
+ Status line: "\u25CF NoData" at the bottom of Claude Code \u2014 green = guarded, yellow = gate off, red = terms not accepted; no segment = not guarded.
82
+ Restart Claude Code to load it. Remove with: npx @nodatachat/mcp uninstall-gate`}function ui(){let e=ci(),t=e.hooks?.PreToolUse;if(!t||!t.some(Dr))return"The NoData read gate is not installed.";if(e.hooks.PreToolUse=t.filter(n=>!Dr(n)),e.hooks.PreToolUse.length===0&&delete e.hooks.PreToolUse,si(e.statusLine)){let n=Nr(Pr())?JSON.parse(Cr(Pr(),"utf8")):null;n?e.statusLine=n:delete e.statusLine}return li(e),"NoData read gate removed. Restart Claude Code to unload it."}var pi=["\u{1F7E3}","\u{1F535}","\u{1F7E0}","\u{1F7E4}","\u{1F7E1}"];function su(e){let t=0;for(let n of e)t=t*31+n.codePointAt(0)>>>0;return pi[t%pi.length]}function $r(e,t){let n=(e||"agent").toLowerCase().replace(/[^a-z0-9._-]+/g,"-").slice(0,40);return t?`${n}@${t}`:n}function fi(e){return`${su(e)} ${e}`}import{z as cu}from"zod";import{createHash as yi}from"node:crypto";import{appendFileSync as lu,existsSync as mi,mkdirSync as gi,readFileSync as _i,writeFileSync as du}from"node:fs";import{homedir as uu}from"node:os";import{join as mn}from"node:path";var pe="2026-09-24-v3";var pu=new Set(["nodata_terms","nodata_get_started","nodata_connect"]),Ct=()=>mn(uu(),".nodata"),yn=()=>mn(Ct(),"consent.json");function gn(){try{return mi(yn())?JSON.parse(_i(yn(),"utf8")):null}catch{return null}}function _n(){return gn()?.terms_version===pe}function bi(e){gi(Ct(),{recursive:!0}),du(yn(),JSON.stringify(e,null,2)+`
83
+ `,{mode:384})}async function Rr(e,t){try{let n=await e.token();if(!n)return!1;let r=await fetch(`${e.baseUrl}/api/audit-log`,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${n}`},body:JSON.stringify(t)}),o=await r.json().catch(()=>({}));return r.ok&&o.logged===!0}catch{return!1}}async function Si(e,t,n,r){let o=new Date().toISOString(),a=yi("sha256").update(`${t}|${n}|${r}|${o}`).digest("hex");try{gi(Ct(),{recursive:!0}),lu(mn(Ct(),"acks.jsonl"),JSON.stringify({at:o,context:t,agent:n,detail:r,proof_hash:a})+`
84
+ `,{mode:384})}catch{}return e?Rr(e,{action:"action_ack",actionDetail:`${t}:${r}`,agent:n,proofHash:a,tosVersion:pe}):!1}async function fu(e,t){let n=new Date().toISOString(),r=yi("sha256").update(`${pe}|mcp|${t}|${e?.org??""}|${n}`).digest("hex"),o={terms_version:pe,accepted_at:n,agent:t,org:e?.org??null,consent_hash:r,server_recorded:!1};return e&&(o.server_recorded=await Rr(e,{action:"tos_accept",tosVersion:pe,context:"mcp",agent:t,proofHash:r})),bi(o),o}async function wi(e){let t=gn();if(!t||t.terms_version!==pe||t.server_recorded)return;await Rr(e,{action:"tos_accept",tosVersion:pe,context:"mcp-sync",agent:t.agent,proofHash:t.consent_hash})&&bi({...t,org:e.org,server_recorded:!0})}function hi(e){try{return _i(mn(Ct(),e),"utf8").split(`
85
+ `).filter(Boolean).length}catch{return 0}}function hu(){return["What is recorded about this machine (all in ~/.nodata, operational only):",` \xB7 consent.json \u2014 ${mi(yn())?"your terms acceptance":"none yet"}`,` \xB7 acks.jsonl \u2014 ${hi("acks.jsonl")} acknowledgement(s), e.g. installing the read gate`,` \xB7 gate.log \u2014 ${hi("gate.log")} read-gate decision(s): tool and ask/deny, no path, no value`,"NoData's copy of the acceptance and acknowledgements is also written to your organisation's proof vault, encrypted to your 12 words."].join(`
86
+ `)}var yu=e=>[`NoData terms ${pe} \u2014 ${e}`,"","Section 7, AI agents, MCP and local tools, in short:"," \xB7 NoData is responsible for what passes through its tools: scan, lock/encrypt, clean copies, grants and revocation, governed sharing, proofs."," \xB7 NoData is NOT responsible for code or programs an AI agent writes or runs by itself, for an agent reaching files without NoData's tools, or for reads the user approved."," \xB7 The read gate is an aid, not a guarantee; locking a file (nodata_protect / nodata_wrap) is full protection."," \xB7 NoData is designed not to know your data (no data seen, no keys held, every action proven), but coding with agents opens many doors \u2014 check, ask NoData to act, and verify from the proof that it did. Consider a code-review policy before agent-written code touches real data."," \xB7 Like everything built on language models, agents and tools can make mistakes: check results, don't rely on them blindly."," \xB7 A proposed policy is not an accepted one: accepting, changing or rejecting it is your decision, and its results are your responsibility."," \xB7 You choose the agents you connect, the permissions you grant and the approvals you give.","","Recorded on acceptance \u2014 here (~/.nodata/consent.json) and at NoData: organisation, agent, terms version, time and a hash. No file content, no values."].join(`
87
+ `);function vi(e,t,n,r){e.registerTool("nodata_terms",{description:"Show NoData's terms of use (current version) and, on the user's explicit approval, accept them. Data tools stay off until the current version is accepted. ASKS FIRST: without confirm:true it only shows the terms summary and link \u2014 show it to the user and call again with confirm:true only if they say they accept. Records operational identity only (organisation, agent, version, time, hash), never content.",inputSchema:{confirm:cu.boolean().optional().describe("true = the user accepts these terms. Omit to show them.")}},async({confirm:o})=>{let a=gn();if(!o){let s=_n()?`Already accepted by ${a.agent} on ${a.accepted_at}${a.server_recorded?" (recorded at NoData)":" (recorded locally; NoData copy pending)"}.`:a?`Accepted version ${a.terms_version} earlier \u2014 the terms have changed and need accepting again.`:"Not accepted yet.";return{content:[{type:"text",text:`${yu(r)}
88
+
89
+ ${s}
90
+
91
+ ${hu()}
92
+
93
+ Ask the user whether they accept, then call nodata_terms again with confirm: true.`}]}}let i=await fu(t,n());return{content:[{type:"text",text:`ACCEPTED terms ${i.terms_version} \u2014 ${i.agent}${i.org?` \xB7 org ${i.org}`:""} \xB7 ${i.accepted_at}
94
+ local copy: ~/.nodata/consent.json \xB7 hash ${i.consent_hash.slice(0,16)}\u2026
95
+ `+(i.server_recorded?" recorded at NoData (tied to your organisation).":t?" NoData could not be reached \u2014 kept locally; it is sent on the next connected run.":" not connected yet \u2014 kept locally; it is recorded at NoData the first time you connect.")+`
96
+ The data tools are on.`}]}})}function ki(e){let t=e,n=t.registerTool.bind(e);t.registerTool=(r,o,a)=>n(r,o,async(...i)=>{if(pu.has(r)||_n())return a(...i);let s=gn();return{content:[{type:"text",text:(s?`NoData's terms changed (you accepted ${s.terms_version}; current is ${pe}).`:"NoData's terms of use have not been accepted on this machine yet.")+` ${r} is held until they are. Call nodata_terms to show them to the user, and nodata_terms confirm:true once they accept.`}],isError:!0}})}import{z as bn}from"zod";import Pe from"node:crypto";var Br=Buffer.from([78,68,67,49]),mu=2,jr=36,It=32,gu=64,_u=12,bu=16,Su=4096,wu=256,Ei=32,Kr=8,vu=1;async function ku(){let[{CipherSuite:e,HkdfSha256:t},{DhkemX25519HkdfSha256:n},{Chacha20Poly1305:r}]=await Promise.all([import("@hpke/core"),import("@hpke/dhkem-x25519"),import("@hpke/chacha20poly1305")]);return new e({kem:new n,kdf:new t,aead:new r})}function Lr(e){let t=new Uint8Array(e.length);return t.set(e),t.buffer}async function Eu(e,t){let n=t.trim();if(n.includes("-----BEGIN PUBLIC KEY-----")){let o=n.replace(/-----BEGIN PUBLIC KEY-----/,"").replace(/-----END PUBLIC KEY-----/,"").replace(/\s+/g,"");return e.kem.deserializePublicKey(Lr(Buffer.from(o,"base64")))}let r=Buffer.from(n.replace(/-/g,"+").replace(/_/g,"/"),"base64");if(r.length!==32)throw new Error(`master pubkey must be a 32-byte X25519 key, got ${r.length} bytes`);return e.kem.deserializePublicKey(Lr(r))}function xu(e){let t=Pe.createPublicKey({key:e,format:"pem"}).export({format:"der",type:"spki"});if(t.length<It)throw new Error("unexpected Ed25519 SPKI DER length");return t.subarray(t.length-It)}function Au(e){return Pe.createHash("sha256").update(e,"utf8").digest().subarray(0,Kr)}async function xi(e){let t=Buffer.from(e.filename,"utf8");if(t.length>Su)throw new Error("filename too long");let n=Buffer.from(e.contentType,"utf8");if(n.length>wu)throw new Error("content-type too long");let r=e.receiptId??Pe.randomUUID(),o=Buffer.from(r,"utf8");if(o.length!==jr)throw new Error("receiptId must be a 36-char canonical UUID");let a=xu(e.issuerPubkeyPem);if(a.length!==It)throw new Error("issuer pubkey must be 32 bytes");let i=Pe.randomBytes(32),s=Pe.randomBytes(_u),c=Pe.createCipheriv("aes-256-gcm",i,s),d=Buffer.concat([c.update(e.fileBytes),c.final()]),u=c.getAuthTag();if(u.length!==bu)throw new Error("unexpected GCM tag length");let p=Pe.createHash("sha256").update(e.fileBytes).digest(),f=await ku(),y=await Eu(f,e.recipientPubkeyB64),_=await f.createSenderContext({recipientPublicKey:y}),k=Buffer.from(_.enc),b=Buffer.from(await _.seal(Lr(i))),S=Au(e.recipientPubkeyB64),v=1+Kr+2+k.length+2+b.length,E=Br.length+1+jr+It+2+t.length+2+n.length+8+Ei+v,m=Buffer.alloc(E),g=0;Br.copy(m,g),g+=Br.length,m[g++]=mu,o.copy(m,g),g+=jr,a.copy(m,g),g+=It,m.writeUInt16LE(t.length,g),g+=2,t.copy(m,g),g+=t.length,m.writeUInt16LE(n.length,g),g+=2,n.copy(m,g),g+=n.length,m.writeBigUInt64LE(BigInt(e.issuedAt??Date.now()),g),g+=8,p.copy(m,g),g+=Ei,m[g++]=vu,S.copy(m,g),g+=Kr,m.writeUInt16LE(k.length,g),g+=2,k.copy(m,g),g+=k.length,m.writeUInt16LE(b.length,g),g+=2,b.copy(m,g),g+=b.length;let A=Pe.sign(null,m,e.issuerPrivateKey);if(A.length!==gu)throw new Error("header signature must be 64 bytes");let I=Buffer.concat([m,A,s,u,d]),P={relative_path:"",plaintext_sha256:p.toString("hex"),size_bytes:e.fileBytes.length,lockbox_id:e.lockboxId??null,ndc_version:2,recovery_alg:1,recovery_master_fp:S.toString("hex"),header_sig_b64:A.toString("base64"),content_key_b64:i.toString("base64")};return{ndcBytes:I,report:P}}import{createPrivateKey as Ai,createPublicKey as Ti,generateKeyPairSync as Tu}from"node:crypto";import{existsSync as Fr,mkdirSync as Pu,readFileSync as Ni,rmSync as Du,statSync as Sn,writeFileSync as Oi}from"node:fs";import{homedir as Pi}from"node:os";import{basename as $t,extname as Nu,join as Ur,resolve as Ou}from"node:path";var fe=(e,t=!1)=>({content:[{type:"text",text:e}],...t?{isError:t}:{}}),Rt="mcp-archive",Mr=25,Di=25*1024*1024,Cu={".pdf":"application/pdf",".txt":"text/plain",".csv":"text/csv",".md":"text/markdown",".json":"application/json",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".docx":"application/vnd.openxmlformats-officedocument.wordprocessingml.document",".xlsx":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",".pptx":"application/vnd.openxmlformats-officedocument.presentationml.presentation"},Iu={critical:"restricted",high:"confidential",medium:"internal",low:"internal",info:"internal"};function Ci(e,t){if(e){let o=Ai({key:Buffer.from(e,"base64"),format:"der",type:"pkcs8"});return{privateKey:o,publicPem:Ti(o).export({format:"pem",type:"spki"}),label:`device ${t??""}`.trim()}}let n=Ur(Pi(),".nodata","issuer-ed25519.json");if(Fr(n)){let o=JSON.parse(Ni(n,"utf8")).private_pem,a=Ai(o);return{privateKey:a,publicPem:Ti(a).export({format:"pem",type:"spki"}),label:"this machine"}}let r=Tu("ed25519");return Pu(Ur(Pi(),".nodata"),{recursive:!0}),Oi(n,JSON.stringify({private_pem:r.privateKey.export({format:"pem",type:"pkcs8"})},null,2)+`
97
+ `,{mode:384}),{privateKey:r.privateKey,publicPem:r.publicKey.export({format:"pem",type:"spki"}),label:"this machine"}}function Ii(e,t,n,r){e.registerTool("nodata_wrap",{description:"WRAP files into your organization's sovereign archive (a zero-knowledge capsule): each file is encrypted ON THIS MACHINE to the public half of your org master key \u2014 the 12 words from signup \u2014 and only ciphertext is uploaded. NoData can never open it; your 12 words (or recovery file) always can, even if this computer is lost or NoData is offline. Each document gets a signed receipt and proof_url. Given a folder, wraps the files the scan finds exposure in (classified by severity); given a file, wraps that file. ASKS FIRST: without confirm:true it only lists what would be wrapped. keep_local:true (default) also writes <file>.capsule.ndc next to the original; remove:true deletes the plaintext originals after a successful upload.",inputSchema:{path:bn.string().describe("File or folder to wrap."),confirm:bn.boolean().optional().describe("true = wrap it. Omit to preview."),keep_local:bn.boolean().optional().describe("Also keep <file>.capsule.ndc next to the original. Default true."),remove:bn.boolean().optional().describe("Delete plaintext originals after upload. Default false.")}},async({path:o,confirm:a,keep_local:i,remove:s})=>{let c=Ou(o);if(!Fr(c))return fe(`Not found: ${c}`,!0);let d;if(Sn(c).isDirectory()?d=Ce(await dt({target_id:"mcp",target_label:$t(c),target_path:c,log:ut})).byFile.map(g=>({path:Ur(c,g.key),classification:Iu[g.worst]??"internal"})):d=[{path:c,classification:"confidential"}],d=d.filter(m=>Fr(m.path)&&Sn(m.path).isFile()&&!Ge(m.path)),d.length===0)return fe(`Nothing to wrap in ${c} \u2014 no file with findings.`);let u=d.filter(m=>Sn(m.path).size>Di);d=d.filter(m=>Sn(m.path).size<=Di);let p=await t.get("/api/v1/recovery/pubkey");if(p.status===401||p.status===403)return fe(`Not authorized to read the org key (HTTP ${p.status}). Connect with nodata_connect.`,!0);let f=typeof p.body.pubkeyB64=="string"?p.body.pubkeyB64:null;if(!f)return fe(`Your organization has no master key yet \u2014 the 12-word recovery setup was not completed, so there is nothing to wrap to.
98
+ Finish it once in the console (Recovery setup), then wrap again. NoData never sees the words.`,!0);if(!a){let m=d.slice(0,Mr).map(g=>` \xB7 [${g.classification}] ${g.path}`);return d.length>Mr&&m.push(` \u2026 and ${d.length-Mr} more`),fe([`PREVIEW \u2014 nothing wrapped yet. ${r()}`,`Would wrap ${d.length} file(s) into the "${Rt}" capsule, sealed to your org master key (fingerprint ${p.body.fingerprint??"?"}):`,...m,u.length?`Skipped (over 25 MB): ${u.map(g=>$t(g.path)).join(", ")}`:"",`Encrypted here; only ciphertext is uploaded. Opens with your 12 words \u2014 never with NoData.${s?" Plaintext originals WILL BE DELETED after upload.":""}`,"","Ask the user to approve, then call nodata_wrap again with the same arguments and confirm: true."].filter(Boolean).join(`
99
+ `))}let y=await t.get("/api/v1/capsules");if(y.status>=400)return fe(`Could not list capsules (HTTP ${y.status}): ${JSON.stringify(y.body)}`,!0);let k=(y.body.capsules??[]).find(m=>m.slug===Rt);if(k&&k.key_mode!=="zk")return fe(`A "${Rt}" capsule exists but is not zero-knowledge (key_mode ${String(k.key_mode)}) \u2014 refusing to wrap into it.`,!0);if(!k){let m=await t.post("/api/v1/capsules",{handle:Rt,display_name:"MCP archive",key_mode:"zk",capsule_pubkey:f});if(m.status>=400)return fe(`Could not create the archive capsule (HTTP ${m.status}): ${JSON.stringify(m.body)}`,!0);k=m.body}let b=String(k.slug??k.capsule_id??"");if(!b)return fe(`Capsule id missing in ${JSON.stringify(k)}`,!0);let S=n(),v=[],E=[];for(let m of d){let g=Ni(m.path),{ndcBytes:A,report:I}=await xi({fileBytes:g,filename:$t(m.path),contentType:Cu[Nu(m.path).toLowerCase()]??"application/octet-stream",recipientPubkeyB64:f,issuerPrivateKey:S.privateKey,issuerPubkeyPem:S.publicPem}),P=await t.post(`/api/v1/capsules/${encodeURIComponent(b)}/documents`,{title:$t(m.path),ndc_b64:A.toString("base64"),classification:m.classification,plaintext_sha256:I.plaintext_sha256,size_bytes:I.size_bytes});if(P.status>=400||P.body.ok!==!0){E.push(` \u2717 ${m.path} \u2014 HTTP ${P.status}: ${JSON.stringify(P.body).slice(0,200)}`);continue}i!==!1&&Oi(`${m.path}.capsule.ndc`,A,{mode:384}),s&&Du(m.path),v.push(` \u2713 [${m.classification}] ${$t(m.path)}${P.body.proof_url?` proof: ${P.body.proof_url}`:""}`)}return fe([`WRAPPED ${v.length}/${d.length} into "${Rt}" \u2014 ${r()} \xB7 signed by ${S.label}`,...v,...E,"Sealed to your org master key: NoData stores ciphertext only and cannot open it. Your 12 words (or recovery file) open every document.",i!==!1?"Local copies: <file>.capsule.ndc next to each original.":"",s?"Plaintext originals deleted (only for files that uploaded).":""].filter(Boolean).join(`
100
+ `),E.length>0&&v.length===0)})}import{homedir as Ui,hostname as Hi}from"node:os";import{join as wn,resolve as Hr}from"node:path";import{existsSync as Gr,readFileSync as Vi,writeFileSync as Gi,mkdirSync as qi,chmodSync as Bu}from"node:fs";import{spawn as ju}from"node:child_process";import{generateKeyPairSync as Ku,createPrivateKey as Lu,sign as Mu,randomBytes as Fu}from"node:crypto";var qr="1.3.2",Wi=wn(Ui(),".nodata"),vn=wn(Wi,"credentials.json");function Uu(){try{if(!Gr(vn))return null;let e=JSON.parse(Vi(vn,"utf8"));if(!e)return null;let t=e.device&&typeof e.device.private_key_pkcs8_b64=="string",n=typeof e.api_key=="string"&&e.api_key;return t||n?e:null}catch{return null}}function $i(e){qi(Wi,{recursive:!0});let t=JSON.stringify({...e,saved_at:new Date().toISOString()},null,2);Gi(vn,t,{mode:384});try{Bu(vn,384)}catch{}}var Hu=`nodata-mcp v${qr} \u2014 NoData MCP server
75
101
 
76
102
  ADMIN mode: nodata-mcp --api-key sk_live_...
77
103
  AGENT mode: nodata-mcp --grant-token ndca-...
78
104
  Options: --base-url <url> (default https://www.nodatacapsule.com)
79
105
  --help \xB7 --version
106
+ nodata-mcp install-gate [--block] ask (or refuse) before Claude Code reads a data file with findings
107
+ nodata-mcp uninstall-gate
80
108
 
81
109
  Env vars: NODATA_API_KEY \xB7 NODATA_GRANT_TOKEN \xB7 NODATA_BASE_URL
82
110
  Get a free API key: https://www.nodatacapsule.com/developers/get-started
83
- Mint a grant token: POST /api/v1/governance/grant (or the nodata_grant tool).`;function hd(e){let t="",n="",r="https://www.nodatacapsule.com";for(let i=0;i<e.length;i++)e[i]==="--api-key"&&e[i+1]?t=e[++i]:e[i]==="--grant-token"&&e[i+1]?n=e[++i]:e[i]==="--base-url"&&e[i+1]?r=e[++i]:e[i]==="--help"||e[i]==="-h"?(console.log(fd),process.exit(0)):e[i]==="--version"||e[i]==="-v"?(console.log(wr),process.exit(0)):e[i].startsWith("--")&&console.error(`nodata-mcp: unknown option '${e[i]}' (see --help)`);let o=t||n?"flag":"none";!t&&process.env.NODATA_API_KEY&&(t=process.env.NODATA_API_KEY,o="env"),!n&&process.env.NODATA_GRANT_TOKEN&&(n=process.env.NODATA_GRANT_TOKEN,o==="none"&&(o="env")),process.env.NODATA_BASE_URL&&(r=process.env.NODATA_BASE_URL);let a;if(!t&&!n){let i=pd();i&&(!process.env.NODATA_BASE_URL&&r==="https://www.nodatacapsule.com"&&i.base_url&&(r=i.base_url),i.device?(a=i.device,o="stored"):i.api_key&&(t=i.api_key,o="stored"))}return r=r.replace(/\/+$/,""),{apiKey:t,grantToken:n,baseUrl:r,credentialSource:o,device:a}}var Ka=3e4;async function Wa(e,t){let n;try{n=await fetch(e,{...t,signal:AbortSignal.timeout(Ka)})}catch(o){return{ok:!1,status:0,body:{error:o instanceof Error&&o.name==="TimeoutError"?`Request timed out after ${Ka/1e3}s: ${e}`:`Network error reaching ${e}: ${o instanceof Error?o.message:String(o)}`}}}let r;try{r=await n.json()}catch{r={error:`Non-JSON response (HTTP ${n.status})`}}return{ok:n.ok,status:n.status,body:r}}async function an(e){if(typeof e=="string")return{token:e};try{return{token:await e()}}catch(t){return{error:{ok:!1,status:0,body:{error:`Could not obtain an access token: ${t instanceof Error?t.message:String(t)}`}}}}}async function H(e,t,n,r){let o=await an(t);return"error"in o?o.error:Wa(`${e}${n}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${o.token}`},body:JSON.stringify(r)})}async function Sr(e,t,n,r){let o=await an(t);if("error"in o)return o.error;let a=new URL(`${e}${n}`);for(let[i,s]of Object.entries(r))s!==void 0&&s!==""&&a.searchParams.set(i,s);return Wa(a.toString(),{method:"GET",headers:{Authorization:`Bearer ${o.token}`}})}function U(e){let t=JSON.stringify(e.body,null,2);return e.ok?{content:[{type:"text",text:t}]}:{content:[{type:"text",text:`Error (HTTP ${e.status}):
84
- ${t}`}],isError:!0}}function yd(e){let t=e?[br(e)]:[br(".env.local"),br(".env")];if(e&&!vr(t[0]))return{error:`env file not found: ${t[0]}`};let n={},r=[];for(let a of t)if(vr(a)){r.push(a);for(let i of Ha(a,"utf8").split(/\r?\n/)){let s=i.match(/^\s*(?:export\s+)?([A-Z0-9_]+)\s*=\s*(.*)\s*$/);!s||s[1]in n||(n[s[1]]=s[2].replace(/^(['"])(.*)\1$/,"$2").trim())}}let o=a=>{for(let i of a){let s=n[i]??process.env[i];if(s)return{name:i,value:s}}};return{url:o(["SUPABASE_URL","NEXT_PUBLIC_SUPABASE_URL","VITE_SUPABASE_URL","EXPO_PUBLIC_SUPABASE_URL"]),anon:o(["SUPABASE_ANON_KEY","NEXT_PUBLIC_SUPABASE_ANON_KEY","VITE_SUPABASE_ANON_KEY","EXPO_PUBLIC_SUPABASE_ANON_KEY","SUPABASE_PUBLISHABLE_KEY","NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY"]),jwt:o(["SUPABASE_JWT_SECRET","JWT_SECRET"]),files:r}}function md(e){try{let n=(e.startsWith("ndca-")?e.slice(5):e).split(".")[1];return n?JSON.parse(Buffer.from(n.replace(/-/g,"+").replace(/_/g,"/"),"base64").toString("utf8")).handle??null:null}catch{return null}}var gd=5*6e4;function _d(){let{publicKey:e,privateKey:t}=cd("ed25519"),n=e.export({format:"der",type:"spki"}),r=t.export({format:"der",type:"pkcs8"});return{publicKeyHex:n.subarray(-32).toString("hex"),privateKeyPkcs8B64:r.toString("base64")}}function bd(e,t){let n=ld({key:Buffer.from(e,"base64"),format:"der",type:"pkcs8"});return dd(null,Buffer.from(t,"utf8"),n).toString("base64")}function Sd(){let e=Ua().toLowerCase().replace(/[^a-z0-9-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,20)||"device";return`${/^[a-z]/.test(e)?e:`d-${e}`}-${ud(3).toString("hex")}`.slice(0,32)}async function vd(e,t,n,r,o){let a=await H(e,t,"/api/v1/attest/devices",{handle:n,label:r,ed25519_pubkey_hex:o});if(a.ok){let i=a.body.org_id??"";return i?{ok:!0,orgId:i}:{ok:!1,status:a.status,error:"enroll response missing org_id"}}return{ok:!1,status:a.status,error:a.body?.error??`HTTP ${a.status}`}}async function wd(e,t){let n=await H(e,"","/api/v1/attest/challenge",{org_id:t.org_id,handle:t.handle});if(!n.ok)throw new Error(`challenge: ${n.body?.error??`HTTP ${n.status}`}`);let{challenge:r,nonce:o}=n.body;if(!r||!o)throw new Error("challenge response malformed");let a=bd(t.private_key_pkcs8_b64,r),i=await H(e,"","/api/v1/attest",{org_id:t.org_id,handle:t.handle,nonce:o,signature:a});if(!i.ok)throw new Error(`attest: ${i.body?.error??`HTTP ${i.status}`}`);let s=i.body;if(!s.allowed||!s.access_token)throw new Error(`attestation rejected: ${s.reason??"denied"}`);return{token:s.access_token,expiresAtMs:s.expires_at?Date.parse(s.expires_at):Date.now()+15*6e4}}function Ed(e,t){let n=null;return async()=>((!n||Date.now()>=n.expiresAtMs-gd)&&(n=await wd(e,t)),n.token)}function kd(e,t){let n=rn(La(),".nodata","approvals");Ga(n,{recursive:!0});let r=rn(n,`${new Date().toISOString().replace(/[:.]/g,"-").slice(0,19)}-${e}.json`);return Va(r,JSON.stringify({kind:e,approved_at:new Date().toISOString(),...t},null,2)+`
85
- `,{mode:384}),r}function xd(e,t,n,r){e.registerTool("nodata_register_table",{description:"Register one of your own tables as AI-agent-readable. This writes POLICY only: it declares which columns are sensitive (released per-column only if their ciphertext exists) and which are plaintext metadata. It does NOT encrypt or change anything in the user's database \u2014 never tell the user their data is now encrypted. Relay the response's `message` and `next_steps` verbatim. After this, grants can target the table.",inputSchema:{table_name:f.string().describe("Your SQL table name"),encrypted_columns:f.array(f.string()).describe("Columns stored as <col>_ct/_iv/_tag triplets"),plaintext_columns:f.array(f.string()).optional().describe("Plaintext metadata/filter columns"),classification_column:f.string().optional().describe("Plaintext column carrying the classification value")}},async({table_name:o,encrypted_columns:a,plaintext_columns:i,classification_column:s})=>{let l=await H(t,n,"/api/v1/governance/tables",{table_name:o,encrypted_columns:a,plaintext_columns:i??[],classification_column:s});return U(l)}),e.registerTool("nodata_connect_source",{description:"Connect the user's own Supabase project as the data source for their registered tables, so granted agents can read metadata through NoData. Reads the project URL, anon key and JWT secret from the user's LOCAL env file (e.g. .env.local) and sends them directly to NoData \u2014 never ask the user to paste a key or secret into the chat, and never print them. Only allowed_tables are readable (deny-by-default).",inputSchema:{allowed_tables:f.array(f.string()).describe("Tables agents may read through this source"),env_file:f.string().optional().describe("Path to the env file holding the Supabase keys (default: .env.local, then .env in the working directory)"),source_url:f.string().optional().describe("Override the project URL (https://<ref>.supabase.co) if the env file lacks it")}},async({allowed_tables:o,env_file:a,source_url:i})=>{let s=yd(a);if("error"in s)return{content:[{type:"text",text:`Error: ${s.error}`}],isError:!0};let l=i??s.url?.value,d=[l?null:"project URL (SUPABASE_URL / NEXT_PUBLIC_SUPABASE_URL)",s.anon?null:"anon key (SUPABASE_ANON_KEY / NEXT_PUBLIC_SUPABASE_ANON_KEY)",s.jwt?null:"JWT secret (SUPABASE_JWT_SECRET \xB7 Supabase \u2192 Settings \u2192 API \u2192 JWT secret)"].filter(Boolean);if(d.length>0)return{content:[{type:"text",text:`Not sent. Missing in ${s.files.join(", ")||"the environment"}: ${d.join("; ")}.
86
- Ask the user to add them to that file themselves (not in this chat), then call this tool again.`}],isError:!0};let u=await H(t,n,"/api/connector/secrets",{source_url:l,allowed_tables:o,anon_key:s.anon.value,jwt_secret:s.jwt.value}),p={read_from:s.files,variables_used:[s.url?.name,s.anon.name,s.jwt.name].filter(Boolean)};return U({...u,body:{...u.body,...p}})}),e.registerTool("nodata_grant",{description:"Issue ONE AI agent a claim-scoped grant over your data \u2014 claims, not blanket access. Returns a grant_token (shown once) the agent presents to read. Denied columns never decrypt. For one agent over several tables pass `tables` in a single call \u2014 do NOT call this once per table, that creates a separate agent each time. ASKS FIRST: without confirm:true it returns the exact policy change and grants nothing \u2014 show it to the user and call again with confirm:true only after they approve. On confirm, a copy of the approval (who, what, when, the receipt and its proof_url \u2014 never the token) is kept in ~/.nodata/approvals.",inputSchema:{agent:f.string().describe("Agent label (becomes its handle)"),tables:f.array(f.object({table:f.string(),columns:f.array(f.string()).describe("Columns the agent may read in this table"),where:f.record(f.string(),f.union([f.string(),f.number(),f.boolean()])).optional()})).optional().describe("Several tables for the same agent. When set, table/columns/where are ignored."),table:f.string().optional().describe("Single target table (default agent_demo_records)"),columns:f.array(f.string()).optional().describe("Columns the agent may read (single-table form)"),where:f.record(f.string(),f.union([f.string(),f.number(),f.boolean()])).optional().describe("Equality filter (plaintext cols only)"),classifications:f.array(f.string()).optional().describe("Allowed classification values; empty = no gating"),ttl_seconds:f.number().optional().describe("Token lifetime (default 30d, max 1y)"),confirm:f.boolean().optional().describe("true = grant it. Omit to preview the policy change.")}},async({agent:o,tables:a,table:i,columns:s,where:l,classifications:d,ttl_seconds:u,confirm:p})=>{let h={agent:o,...a?{tables:a}:{table:i??"agent_demo_records",columns:s,where:l},classifications:d,ttl_seconds:u};if(!p){let k=(a??[{table:i??"agent_demo_records",columns:s??[],where:l}]).map(_=>` \xB7 ${_.table}: ${(_.columns??[]).join(", ")||"(no columns)"}${_.where?` where ${JSON.stringify(_.where)}`:""}`),S=u?`${Math.round(u/86400*10)/10} days`:"30 days (default)";return{content:[{type:"text",text:[`POLICY CHANGE \u2014 PREVIEW, nothing granted yet. Requested by ${r()}`,`Agent "${o}" would be able to read ONLY:`,...k,`Classifications: ${d?.length?d.join(", "):"not gated"}`,`Valid for: ${S}. Every other column stays sealed and every read is receipted.`,"","Ask the user to approve this change, then call nodata_grant again with the same arguments and confirm: true."].join(`
87
- `)}]}}let m=await H(t,n,"/api/v1/governance/grant",h);if(m.ok){let v=m.body,k=kd("grant",{approved_by:r(),request:h,result:{handle:v.handle,agent_id:v.agent_id,expires_at:v.expires_at,grant_receipt_id:v.grant_receipt_id,proof_url:v.proof_url}});m.body.approval_copy=k}return U(m)}),e.registerTool("nodata_policy",{description:"The POLICY BOARD: every AI agent in the organization and exactly what it can reach \u2014 tables, columns, classifications \u2014 plus status. Deny-by-default: an agent with no grant reaches nothing. Change it with nodata_grant (asks for approval first) and nodata_revoke (immediate). Content-free: names only, never a value.",inputSchema:{}},async()=>{let o=await Sr(t,n,"/api/v1/agents",{});if(!o.ok)return U(o);let i=o.body.agents??[],s=[`POLICY BOARD \u2014 ${r()}`,`${i.length} agent(s). Deny-by-default: no grant \u21D2 no access.`,""];for(let l of i){let d=l.scope,u=d?d.grants===0?"reaches nothing":`${d.tables_allowed.join(", ")||"(tables)"} \u2192 ${d.columns_allowed.join(", ")||"(no columns)"} \xB7 classifications: ${d.unrestricted_classifications?"not gated":d.classifications_allowed.join(", ")||"none"}`:"scope unavailable";s.push(` ${String(l.handle??l.name).padEnd(24)} ${String(l.status??"").padEnd(8)} ${u}`)}return s.push("",'Change: nodata_grant (preview \u2192 approve) \xB7 nodata_revoke handle: "<agent>" (immediate) \xB7 proofs: nodata_proofs'),{content:[{type:"text",text:s.join(`
88
- `)}]}}),e.registerTool("nodata_revoke",{description:"Revoke an agent's grant by handle (kills all its active credentials) or by a specific jti. Revocation is mathematics \u2014 the next read 401s and any cached data is governance-dead.",inputSchema:{handle:f.string().optional().describe("Agent handle to revoke"),jti:f.string().optional().describe("Specific credential jti to revoke"),reason:f.string().optional()}},async({handle:o,jti:a,reason:i})=>{let s=await H(t,n,"/api/v1/governance/revoke",{handle:o,jti:a,reason:i});return U(s)}),e.registerTool("nodata_encrypt",{description:"Encrypt a sensitive field value using Capsule Blind Relay. Returns ciphertext. NoData stores nothing \u2014 the key is embedded in the ciphertext for YOU to store.",inputSchema:{field:f.string(),value:f.string(),context:f.string().optional()}},async({field:o,value:a,context:i})=>{let s={field:o,value:a};return i&&(s.context=i),U(await H(t,n,"/api/v1/encrypt",s))}),e.registerTool("nodata_decrypt",{description:"Decrypt a Capsule ciphertext back to plaintext (aes256gcm:v1:iv:cipher:key format).",inputSchema:{ciphertext:f.string(),field:f.string().optional(),requester:f.string().optional()}},async({ciphertext:o,field:a,requester:i})=>{let s={ciphertext:o};return a&&(s.field=a),i&&(s.requester=i),U(await H(t,n,"/api/v1/decrypt",s))}),e.registerTool("nodata_deliver",{description:"Create a burn-after-read secure link for delivering sensitive content. Returns a view URL and OTP.",inputSchema:{content:f.string(),to:f.string().optional(),maxViews:f.number().optional(),ttl:f.string().optional(),burn:f.boolean().optional()}},async({content:o,to:a,maxViews:i,ttl:s,burn:l})=>{let d={content:o};return a&&(d.to=a),i!==void 0&&(d.maxViews=i),s&&(d.ttl=s),l!==void 0&&(d.burn=l),U(await H(t,n,"/api/v1/deliver",d))}),e.registerTool("nodata_evidence",{description:"Field-level encrypt/decrypt/deliver events (field_access_log). Requires the Engine scope on the key. For the signed decision-receipt chain \u2014 grants, agent reads, denials \u2014 use nodata_proofs instead, which every org key can call. Metadata only.",inputSchema:{from:f.string().optional(),to:f.string().optional(),action:f.string().optional(),limit:f.number().optional()}},async({from:o,to:a,action:i,limit:s})=>{let l={from:o,to:a,action:i,limit:s!==void 0?String(s):void 0};return U(await Sr(t,n,"/api/v1/evidence",l))}),e.registerTool("nodata_proofs",{description:"List your organization's signed proofs: every grant, agent read and denial, newest first. Content-free (labels, hashes, timestamps). Each proof can be verified by anyone, without an account, by POSTing {proof_id: <its receipt_id>} to /api/access/verify. The response's `plan` says which proof types the user's plan includes and which need an upgrade (with the plan name) \u2014 relay it as is.",inputSchema:{receipt_id:f.string().optional().describe("Fetch one proof by id"),surface:f.string().optional().describe("Filter, e.g. 'governance.grant', 'agent.read'"),decision:f.string().optional().describe("Filter: 'grant' | 'allow' | 'deny' | 'revoke'"),from:f.string().optional().describe("ISO timestamp"),to:f.string().optional().describe("ISO timestamp"),limit:f.number().optional().describe("1..1000, default 50")}},async({receipt_id:o,surface:a,decision:i,from:s,to:l,limit:d})=>U(await Sr(t,n,"/api/v1/proofs",{receipt_id:o,surface:a,decision:i,from:s,to:l,limit:d!==void 0?String(d):void 0})))}function Ad(e,t,n){let r=md(n);r||console.error("nodata-mcp: warning \u2014 could not derive an agent handle from the grant token (expected ndca-<jwt> with a 'handle' claim). nodata_decide/nodata_retrieve will work; nodata_read/nodata_use will fail until a valid grant token is provided."),e.registerTool("nodata_decide",{description:"Ask whether this agent MAY reach a resource, WITHOUT reading it. Returns a decision (allow / degrade / deny), the reachable column subset, an access-distance cost, and a signed proof \u2014 never any data. Use it to plan: check reachability before you retrieve. Hard-scoped to this server's grant token.",inputSchema:{table:f.string().describe("Table to check (must be in your grant)"),columns:f.array(f.string()).describe("Columns you want to reach"),where:f.record(f.string(),f.union([f.string(),f.number(),f.boolean()])).optional().describe("Equality filter (readable columns only)")}},async({table:o,columns:a,where:i})=>{let s=await H(t,n,"/api/access/decide",{resource:{table:o,columns:a,where:i},intent:"read"});return U(s)}),e.registerTool("nodata_retrieve",{description:"Retrieve prompt-ready context for a resource, filtered to exactly what this agent may see. Denied columns are never decrypted; the response includes an accounting of what was withheld (columns + estimated tokens saved) and a signed proof. Prefer this over a raw read when assembling an LLM prompt. Hard-scoped to this server's grant token.",inputSchema:{table:f.string().describe("Table to retrieve from (must be in your grant)"),columns:f.array(f.string()).describe("Columns to include in context"),where:f.record(f.string(),f.union([f.string(),f.number(),f.boolean()])).optional(),top_k:f.number().optional().describe("Max rows (default 50, max 200)")}},async({table:o,columns:a,where:i,top_k:s})=>{let l=await H(t,n,"/api/access/retrieve",{resource:{table:o,columns:a,where:i},top_k:s});return U(l)}),e.registerTool("nodata_read",{description:"Read governed data within this agent's grant. You may only request columns your grant allows \u2014 denied columns never decrypt server-side, and every read emits a cryptographic receipt. This tool is hard-scoped to the grant token this server was started with.",inputSchema:{table:f.string().describe("Table to read (must be in your grant)"),columns:f.array(f.string()).describe("Columns to read (must be in your grant)"),where:f.record(f.string(),f.union([f.string(),f.number(),f.boolean()])).optional(),limit:f.number().optional().describe("Max rows (default 50, max 200)")}},async({table:o,columns:a,where:i,limit:s})=>{if(!r)return{content:[{type:"text",text:"Error: could not derive agent handle from grant token."}],isError:!0};let l=await H(t,n,`/api/agents/${encodeURIComponent(r)}/read`,{table:o,columns:a,where:i,limit:s});return U(l)}),e.registerTool("nodata_use",{description:"Invoke a pre-registered capability (deploy, send, charge, query, \u2026) WITHOUT receiving the secret. The Capsule injects the sealed credential server-side and returns only the result. You may invoke only capabilities your grant allows; the secret never reaches you. Hard-scoped to the grant token this server was started with.",inputSchema:{capability:f.string().describe("Capability name to invoke (must be in your grant, e.g. 'deploy-prod')"),params:f.record(f.string(),f.unknown()).optional().describe("Allowlisted params; unknown keys are dropped server-side"),resource_key:f.string().optional().describe("Optional folder/resource the action targets (enforced against corpus scope)")}},async({capability:o,params:a,resource_key:i})=>{if(!r)return{content:[{type:"text",text:"Error: could not derive agent handle from grant token."}],isError:!0};let s=await H(t,n,`/api/agents/${encodeURIComponent(r)}/use`,{capability:o,params:a,resource_key:i});return U(s)}),e.registerTool("nodata_code_advise",{description:"Ask the blind code advisor to diagnose/fix a bug in a code capsule WITHOUT seeing its source. You receive guidance + a targeted diff + an exposure proof (source never left the boundary); the source is never returned to you. Requires the capsule owner to have granted this agent (scope.fabric_developers). Hard-scoped to this server's grant token.",inputSchema:{capsule_id:f.string().describe("The code capsule to advise on (you must be granted on it)"),question:f.string().optional().describe("What to fix / improve, in natural language"),note:f.string().optional().describe("Extra context for the advisor"),error:f.object({message:f.string().optional(),stack:f.string().optional(),kind:f.string().optional()}).optional().describe("An error the code produced, to guide the fix"),steer:f.string().optional().describe("A steer on a refine turn (e.g. 'no, round half-up')"),prior_diff:f.string().optional().describe("The previously proposed diff, to refine")}},async({capsule_id:o,question:a,note:i,error:s,steer:l,prior_diff:d})=>{if(!r)return{content:[{type:"text",text:"Error: could not derive agent handle from grant token."}],isError:!0};let u=await H(t,n,`/api/agents/${encodeURIComponent(r)}/code-capsule/${encodeURIComponent(o)}/advise`,{question:a,note:i,error:s,steer:l,prior_diff:d});return U(u)}),e.registerTool("nodata_code_patch",{description:"Submit a fix to a code capsule as a SIGNED, queued patch WITHOUT seeing its source. Provide a raw unified `diff`, or a whole-file `replace` ({path, content}) that is diffed server-side against the sealed source. The source is never persisted or returned; you get back a patch id, the diff hash, and a receipt. Requires a capsule grant (scope.fabric_developers). Hard-scoped to this server's grant token.",inputSchema:{capsule_id:f.string().describe("The code capsule to patch (you must be granted on it)"),summary:f.string().optional().describe("Short human-readable summary of the fix"),diff:f.string().optional().describe("A raw unified diff (advanced)"),replace:f.object({path:f.string(),content:f.string()}).optional().describe("Whole-file replacement; the diff is synthesized server-side against sealed source")}},async({capsule_id:o,summary:a,diff:i,replace:s})=>{if(!r)return{content:[{type:"text",text:"Error: could not derive agent handle from grant token."}],isError:!0};let l=await H(t,n,`/api/agents/${encodeURIComponent(r)}/code-capsule/${encodeURIComponent(o)}/patch`,{summary:a,diff:i,replace:s});return U(l)})}var ja=`WHAT NODATA DOES \u2014 in one line:
111
+ Mint a grant token: POST /api/v1/governance/grant (or the nodata_grant tool).`;function Ri(e){let t="",n="",r="https://www.nodatacapsule.com";for(let i=0;i<e.length;i++)e[i]==="--api-key"&&e[i+1]?t=e[++i]:e[i]==="--grant-token"&&e[i+1]?n=e[++i]:e[i]==="--base-url"&&e[i+1]?r=e[++i]:e[i]==="--help"||e[i]==="-h"?(console.log(Hu),process.exit(0)):e[i]==="--version"||e[i]==="-v"?(console.log(qr),process.exit(0)):e[i].startsWith("--")&&console.error(`nodata-mcp: unknown option '${e[i]}' (see --help)`);let o=t||n?"flag":"none";!t&&process.env.NODATA_API_KEY&&(t=process.env.NODATA_API_KEY,o="env"),!n&&process.env.NODATA_GRANT_TOKEN&&(n=process.env.NODATA_GRANT_TOKEN,o==="none"&&(o="env")),process.env.NODATA_BASE_URL&&(r=process.env.NODATA_BASE_URL);let a;if(!t&&!n){let i=Uu();i&&(!process.env.NODATA_BASE_URL&&r==="https://www.nodatacapsule.com"&&i.base_url&&(r=i.base_url),i.device?(a=i.device,o="stored"):i.api_key&&(t=i.api_key,o="stored"))}return r=r.replace(/\/+$/,""),{apiKey:t,grantToken:n,baseUrl:r,credentialSource:o,device:a}}var Bi=3e4;async function Ji(e,t){let n;try{n=await fetch(e,{...t,signal:AbortSignal.timeout(Bi)})}catch(o){return{ok:!1,status:0,body:{error:o instanceof Error&&o.name==="TimeoutError"?`Request timed out after ${Bi/1e3}s: ${e}`:`Network error reaching ${e}: ${o instanceof Error?o.message:String(o)}`}}}let r;try{r=await n.json()}catch{r={error:`Non-JSON response (HTTP ${n.status})`}}return{ok:n.ok,status:n.status,body:r}}async function Bt(e){if(typeof e=="string")return{token:e};try{return{token:await e()}}catch(t){return{error:{ok:!1,status:0,body:{error:`Could not obtain an access token: ${t instanceof Error?t.message:String(t)}`}}}}}function ji(e){return async()=>{let t=await Bt(e);return"error"in t?null:t.token}}async function H(e,t,n,r){let o=await Bt(t);return"error"in o?o.error:Ji(`${e}${n}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${o.token}`},body:JSON.stringify(r)})}async function Vr(e,t,n,r){let o=await Bt(t);if("error"in o)return o.error;let a=new URL(`${e}${n}`);for(let[i,s]of Object.entries(r))s!==void 0&&s!==""&&a.searchParams.set(i,s);return Ji(a.toString(),{method:"GET",headers:{Authorization:`Bearer ${o.token}`}})}function U(e){let t=JSON.stringify(e.body,null,2);return e.ok?{content:[{type:"text",text:t}]}:{content:[{type:"text",text:`Error (HTTP ${e.status}):
112
+ ${t}`}],isError:!0}}function Vu(e){let t=e?[Hr(e)]:[Hr(".env.local"),Hr(".env")];if(e&&!Gr(t[0]))return{error:`env file not found: ${t[0]}`};let n={},r=[];for(let a of t)if(Gr(a)){r.push(a);for(let i of Vi(a,"utf8").split(/\r?\n/)){let s=i.match(/^\s*(?:export\s+)?([A-Z0-9_]+)\s*=\s*(.*)\s*$/);!s||s[1]in n||(n[s[1]]=s[2].replace(/^(['"])(.*)\1$/,"$2").trim())}}let o=a=>{for(let i of a){let s=n[i]??process.env[i];if(s)return{name:i,value:s}}};return{url:o(["SUPABASE_URL","NEXT_PUBLIC_SUPABASE_URL","VITE_SUPABASE_URL","EXPO_PUBLIC_SUPABASE_URL"]),anon:o(["SUPABASE_ANON_KEY","NEXT_PUBLIC_SUPABASE_ANON_KEY","VITE_SUPABASE_ANON_KEY","EXPO_PUBLIC_SUPABASE_ANON_KEY","SUPABASE_PUBLISHABLE_KEY","NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY"]),jwt:o(["SUPABASE_JWT_SECRET","JWT_SECRET"]),files:r}}function Gu(e){try{let n=(e.startsWith("ndca-")?e.slice(5):e).split(".")[1];return n?JSON.parse(Buffer.from(n.replace(/-/g,"+").replace(/_/g,"/"),"base64").toString("utf8")).handle??null:null}catch{return null}}var qu=5*6e4;function Wu(){let{publicKey:e,privateKey:t}=Ku("ed25519"),n=e.export({format:"der",type:"spki"}),r=t.export({format:"der",type:"pkcs8"});return{publicKeyHex:n.subarray(-32).toString("hex"),privateKeyPkcs8B64:r.toString("base64")}}function Ju(e,t){let n=Lu({key:Buffer.from(e,"base64"),format:"der",type:"pkcs8"});return Mu(null,Buffer.from(t,"utf8"),n).toString("base64")}function zu(){let e=Hi().toLowerCase().replace(/[^a-z0-9-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,20)||"device";return`${/^[a-z]/.test(e)?e:`d-${e}`}-${Fu(3).toString("hex")}`.slice(0,32)}async function Yu(e,t,n,r,o){let a=await H(e,t,"/api/v1/attest/devices",{handle:n,label:r,ed25519_pubkey_hex:o});if(a.ok){let i=a.body.org_id??"";return i?{ok:!0,orgId:i}:{ok:!1,status:a.status,error:"enroll response missing org_id"}}return{ok:!1,status:a.status,error:a.body?.error??`HTTP ${a.status}`}}async function Xu(e,t){let n=await H(e,"","/api/v1/attest/challenge",{org_id:t.org_id,handle:t.handle});if(!n.ok)throw new Error(`challenge: ${n.body?.error??`HTTP ${n.status}`}`);let{challenge:r,nonce:o}=n.body;if(!r||!o)throw new Error("challenge response malformed");let a=Ju(t.private_key_pkcs8_b64,r),i=await H(e,"","/api/v1/attest",{org_id:t.org_id,handle:t.handle,nonce:o,signature:a});if(!i.ok)throw new Error(`attest: ${i.body?.error??`HTTP ${i.status}`}`);let s=i.body;if(!s.allowed||!s.access_token)throw new Error(`attestation rejected: ${s.reason??"denied"}`);return{token:s.access_token,expiresAtMs:s.expires_at?Date.parse(s.expires_at):Date.now()+15*6e4}}function Ki(e,t){let n=null;return async()=>((!n||Date.now()>=n.expiresAtMs-qu)&&(n=await Xu(e,t)),n.token)}function Zu(e,t){let n=wn(Ui(),".nodata","approvals");qi(n,{recursive:!0});let r=wn(n,`${new Date().toISOString().replace(/[:.]/g,"-").slice(0,19)}-${e}.json`);return Gi(r,JSON.stringify({kind:e,approved_at:new Date().toISOString(),...t},null,2)+`
113
+ `,{mode:384}),r}function Qu(e,t,n,r){e.registerTool("nodata_register_table",{description:"Register one of your own tables as AI-agent-readable. This writes POLICY only: it declares which columns are sensitive (released per-column only if their ciphertext exists) and which are plaintext metadata. It does NOT encrypt or change anything in the user's database \u2014 never tell the user their data is now encrypted. Relay the response's `message` and `next_steps` verbatim. After this, grants can target the table.",inputSchema:{table_name:h.string().describe("Your SQL table name"),encrypted_columns:h.array(h.string()).describe("Columns stored as <col>_ct/_iv/_tag triplets"),plaintext_columns:h.array(h.string()).optional().describe("Plaintext metadata/filter columns"),classification_column:h.string().optional().describe("Plaintext column carrying the classification value")}},async({table_name:o,encrypted_columns:a,plaintext_columns:i,classification_column:s})=>{let c=await H(t,n,"/api/v1/governance/tables",{table_name:o,encrypted_columns:a,plaintext_columns:i??[],classification_column:s});return U(c)}),e.registerTool("nodata_connect_source",{description:"Connect the user's own Supabase project as the data source for their registered tables, so granted agents can read metadata through NoData. Reads the project URL, anon key and JWT secret from the user's LOCAL env file (e.g. .env.local) and sends them directly to NoData \u2014 never ask the user to paste a key or secret into the chat, and never print them. Only allowed_tables are readable (deny-by-default).",inputSchema:{allowed_tables:h.array(h.string()).describe("Tables agents may read through this source"),env_file:h.string().optional().describe("Path to the env file holding the Supabase keys (default: .env.local, then .env in the working directory)"),source_url:h.string().optional().describe("Override the project URL (https://<ref>.supabase.co) if the env file lacks it")}},async({allowed_tables:o,env_file:a,source_url:i})=>{let s=Vu(a);if("error"in s)return{content:[{type:"text",text:`Error: ${s.error}`}],isError:!0};let c=i??s.url?.value,d=[c?null:"project URL (SUPABASE_URL / NEXT_PUBLIC_SUPABASE_URL)",s.anon?null:"anon key (SUPABASE_ANON_KEY / NEXT_PUBLIC_SUPABASE_ANON_KEY)",s.jwt?null:"JWT secret (SUPABASE_JWT_SECRET \xB7 Supabase \u2192 Settings \u2192 API \u2192 JWT secret)"].filter(Boolean);if(d.length>0)return{content:[{type:"text",text:`Not sent. Missing in ${s.files.join(", ")||"the environment"}: ${d.join("; ")}.
114
+ Ask the user to add them to that file themselves (not in this chat), then call this tool again.`}],isError:!0};let u=await H(t,n,"/api/connector/secrets",{source_url:c,allowed_tables:o,anon_key:s.anon.value,jwt_secret:s.jwt.value}),p={read_from:s.files,variables_used:[s.url?.name,s.anon.name,s.jwt.name].filter(Boolean)};return U({...u,body:{...u.body,...p}})}),e.registerTool("nodata_grant",{description:"Issue ONE AI agent a claim-scoped grant over your data \u2014 claims, not blanket access. Returns a grant_token (shown once) the agent presents to read. Denied columns never decrypt. For one agent over several tables pass `tables` in a single call \u2014 do NOT call this once per table, that creates a separate agent each time. ASKS FIRST: without confirm:true it returns the exact policy change and grants nothing \u2014 show it to the user and call again with confirm:true only after they approve. On confirm, a copy of the approval (who, what, when, the receipt and its proof_url \u2014 never the token) is kept in ~/.nodata/approvals.",inputSchema:{agent:h.string().describe("Agent label (becomes its handle)"),tables:h.array(h.object({table:h.string(),columns:h.array(h.string()).describe("Columns the agent may read in this table"),where:h.record(h.string(),h.union([h.string(),h.number(),h.boolean()])).optional()})).optional().describe("Several tables for the same agent. When set, table/columns/where are ignored."),table:h.string().optional().describe("Single target table (default agent_demo_records)"),columns:h.array(h.string()).optional().describe("Columns the agent may read (single-table form)"),where:h.record(h.string(),h.union([h.string(),h.number(),h.boolean()])).optional().describe("Equality filter (plaintext cols only)"),classifications:h.array(h.string()).optional().describe("Allowed classification values; empty = no gating"),ttl_seconds:h.number().optional().describe("Token lifetime (default 30d, max 1y)"),confirm:h.boolean().optional().describe("true = grant it. Omit to preview the policy change.")}},async({agent:o,tables:a,table:i,columns:s,where:c,classifications:d,ttl_seconds:u,confirm:p})=>{let f={agent:o,...a?{tables:a}:{table:i??"agent_demo_records",columns:s,where:c},classifications:d,ttl_seconds:u};if(!p){let k=(a??[{table:i??"agent_demo_records",columns:s??[],where:c}]).map(S=>` \xB7 ${S.table}: ${(S.columns??[]).join(", ")||"(no columns)"}${S.where?` where ${JSON.stringify(S.where)}`:""}`),b=u?`${Math.round(u/86400*10)/10} days`:"30 days (default)";return{content:[{type:"text",text:[`POLICY CHANGE \u2014 PREVIEW, nothing granted yet. Requested by ${r()}`,`Agent "${o}" would be able to read ONLY:`,...k,`Classifications: ${d?.length?d.join(", "):"not gated"}`,`Valid for: ${b}. Every other column stays sealed and every read is receipted.`,"","Ask the user to approve this change, then call nodata_grant again with the same arguments and confirm: true."].join(`
115
+ `)}]}}let y=await H(t,n,"/api/v1/governance/grant",f);if(y.ok){let _=y.body,k=Zu("grant",{approved_by:r(),request:f,result:{handle:_.handle,agent_id:_.agent_id,expires_at:_.expires_at,grant_receipt_id:_.grant_receipt_id,proof_url:_.proof_url}});y.body.approval_copy=k}return U(y)}),e.registerTool("nodata_policy",{description:"The POLICY BOARD: every AI agent in the organization and exactly what it can reach \u2014 tables, columns, classifications \u2014 plus status. Deny-by-default: an agent with no grant reaches nothing. Change it with nodata_grant (asks for approval first) and nodata_revoke (immediate). Content-free: names only, never a value.",inputSchema:{}},async()=>{let o=await Vr(t,n,"/api/v1/agents",{});if(!o.ok)return U(o);let i=o.body.agents??[],s=[`POLICY BOARD \u2014 ${r()}`,`${i.length} agent(s). Deny-by-default: no grant \u21D2 no access.`,""];for(let c of i){let d=c.scope,u=d?d.grants===0?"reaches nothing":`${d.tables_allowed.join(", ")||"(tables)"} \u2192 ${d.columns_allowed.join(", ")||"(no columns)"} \xB7 classifications: ${d.unrestricted_classifications?"not gated":d.classifications_allowed.join(", ")||"none"}`:"scope unavailable";s.push(` ${String(c.handle??c.name).padEnd(24)} ${String(c.status??"").padEnd(8)} ${u}`)}return s.push("",'Change: nodata_grant (preview \u2192 approve) \xB7 nodata_revoke handle: "<agent>" (immediate) \xB7 proofs: nodata_proofs'),{content:[{type:"text",text:s.join(`
116
+ `)}]}}),e.registerTool("nodata_revoke",{description:"Revoke an agent's grant by handle (kills all its active credentials) or by a specific jti. Revocation is mathematics \u2014 the next read 401s and any cached data is governance-dead.",inputSchema:{handle:h.string().optional().describe("Agent handle to revoke"),jti:h.string().optional().describe("Specific credential jti to revoke"),reason:h.string().optional()}},async({handle:o,jti:a,reason:i})=>{let s=await H(t,n,"/api/v1/governance/revoke",{handle:o,jti:a,reason:i});return U(s)}),e.registerTool("nodata_encrypt",{description:"Encrypt a sensitive field value using Capsule Blind Relay. Returns ciphertext. NoData stores nothing \u2014 the key is embedded in the ciphertext for YOU to store.",inputSchema:{field:h.string(),value:h.string(),context:h.string().optional()}},async({field:o,value:a,context:i})=>{let s={field:o,value:a};return i&&(s.context=i),U(await H(t,n,"/api/v1/encrypt",s))}),e.registerTool("nodata_decrypt",{description:"Decrypt a Capsule ciphertext back to plaintext (aes256gcm:v1:iv:cipher:key format).",inputSchema:{ciphertext:h.string(),field:h.string().optional(),requester:h.string().optional()}},async({ciphertext:o,field:a,requester:i})=>{let s={ciphertext:o};return a&&(s.field=a),i&&(s.requester=i),U(await H(t,n,"/api/v1/decrypt",s))}),e.registerTool("nodata_deliver",{description:"Create a burn-after-read secure link for delivering sensitive content. Returns a view URL and OTP.",inputSchema:{content:h.string(),to:h.string().optional(),maxViews:h.number().optional(),ttl:h.string().optional(),burn:h.boolean().optional()}},async({content:o,to:a,maxViews:i,ttl:s,burn:c})=>{let d={content:o};return a&&(d.to=a),i!==void 0&&(d.maxViews=i),s&&(d.ttl=s),c!==void 0&&(d.burn=c),U(await H(t,n,"/api/v1/deliver",d))}),e.registerTool("nodata_evidence",{description:"Field-level encrypt/decrypt/deliver events (field_access_log). Requires the Engine scope on the key. For the signed decision-receipt chain \u2014 grants, agent reads, denials \u2014 use nodata_proofs instead, which every org key can call. Metadata only.",inputSchema:{from:h.string().optional(),to:h.string().optional(),action:h.string().optional(),limit:h.number().optional()}},async({from:o,to:a,action:i,limit:s})=>{let c={from:o,to:a,action:i,limit:s!==void 0?String(s):void 0};return U(await Vr(t,n,"/api/v1/evidence",c))}),e.registerTool("nodata_proofs",{description:"List your organization's signed proofs: every grant, agent read and denial, newest first. Content-free (labels, hashes, timestamps). Each proof can be verified by anyone, without an account, by POSTing {proof_id: <its receipt_id>} to /api/access/verify. The response's `plan` says which proof types the user's plan includes and which need an upgrade (with the plan name) \u2014 relay it as is.",inputSchema:{receipt_id:h.string().optional().describe("Fetch one proof by id"),surface:h.string().optional().describe("Filter, e.g. 'governance.grant', 'agent.read'"),decision:h.string().optional().describe("Filter: 'grant' | 'allow' | 'deny' | 'revoke'"),from:h.string().optional().describe("ISO timestamp"),to:h.string().optional().describe("ISO timestamp"),limit:h.number().optional().describe("1..1000, default 50")}},async({receipt_id:o,surface:a,decision:i,from:s,to:c,limit:d})=>U(await Vr(t,n,"/api/v1/proofs",{receipt_id:o,surface:a,decision:i,from:s,to:c,limit:d!==void 0?String(d):void 0})))}function ep(e,t,n){let r=Gu(n);r||console.error("nodata-mcp: warning \u2014 could not derive an agent handle from the grant token (expected ndca-<jwt> with a 'handle' claim). nodata_decide/nodata_retrieve will work; nodata_read/nodata_use will fail until a valid grant token is provided."),e.registerTool("nodata_decide",{description:"Ask whether this agent MAY reach a resource, WITHOUT reading it. Returns a decision (allow / degrade / deny), the reachable column subset, an access-distance cost, and a signed proof \u2014 never any data. Use it to plan: check reachability before you retrieve. Hard-scoped to this server's grant token.",inputSchema:{table:h.string().describe("Table to check (must be in your grant)"),columns:h.array(h.string()).describe("Columns you want to reach"),where:h.record(h.string(),h.union([h.string(),h.number(),h.boolean()])).optional().describe("Equality filter (readable columns only)")}},async({table:o,columns:a,where:i})=>{let s=await H(t,n,"/api/access/decide",{resource:{table:o,columns:a,where:i},intent:"read"});return U(s)}),e.registerTool("nodata_retrieve",{description:"Retrieve prompt-ready context for a resource, filtered to exactly what this agent may see. Denied columns are never decrypted; the response includes an accounting of what was withheld (columns + estimated tokens saved) and a signed proof. Prefer this over a raw read when assembling an LLM prompt. Hard-scoped to this server's grant token.",inputSchema:{table:h.string().describe("Table to retrieve from (must be in your grant)"),columns:h.array(h.string()).describe("Columns to include in context"),where:h.record(h.string(),h.union([h.string(),h.number(),h.boolean()])).optional(),top_k:h.number().optional().describe("Max rows (default 50, max 200)")}},async({table:o,columns:a,where:i,top_k:s})=>{let c=await H(t,n,"/api/access/retrieve",{resource:{table:o,columns:a,where:i},top_k:s});return U(c)}),e.registerTool("nodata_read",{description:"Read governed data within this agent's grant. You may only request columns your grant allows \u2014 denied columns never decrypt server-side, and every read emits a cryptographic receipt. This tool is hard-scoped to the grant token this server was started with.",inputSchema:{table:h.string().describe("Table to read (must be in your grant)"),columns:h.array(h.string()).describe("Columns to read (must be in your grant)"),where:h.record(h.string(),h.union([h.string(),h.number(),h.boolean()])).optional(),limit:h.number().optional().describe("Max rows (default 50, max 200)")}},async({table:o,columns:a,where:i,limit:s})=>{if(!r)return{content:[{type:"text",text:"Error: could not derive agent handle from grant token."}],isError:!0};let c=await H(t,n,`/api/agents/${encodeURIComponent(r)}/read`,{table:o,columns:a,where:i,limit:s});return U(c)}),e.registerTool("nodata_use",{description:"Invoke a pre-registered capability (deploy, send, charge, query, \u2026) WITHOUT receiving the secret. The Capsule injects the sealed credential server-side and returns only the result. You may invoke only capabilities your grant allows; the secret never reaches you. Hard-scoped to the grant token this server was started with.",inputSchema:{capability:h.string().describe("Capability name to invoke (must be in your grant, e.g. 'deploy-prod')"),params:h.record(h.string(),h.unknown()).optional().describe("Allowlisted params; unknown keys are dropped server-side"),resource_key:h.string().optional().describe("Optional folder/resource the action targets (enforced against corpus scope)")}},async({capability:o,params:a,resource_key:i})=>{if(!r)return{content:[{type:"text",text:"Error: could not derive agent handle from grant token."}],isError:!0};let s=await H(t,n,`/api/agents/${encodeURIComponent(r)}/use`,{capability:o,params:a,resource_key:i});return U(s)}),e.registerTool("nodata_code_advise",{description:"Ask the blind code advisor to diagnose/fix a bug in a code capsule WITHOUT seeing its source. You receive guidance + a targeted diff + an exposure proof (source never left the boundary); the source is never returned to you. Requires the capsule owner to have granted this agent (scope.fabric_developers). Hard-scoped to this server's grant token.",inputSchema:{capsule_id:h.string().describe("The code capsule to advise on (you must be granted on it)"),question:h.string().optional().describe("What to fix / improve, in natural language"),note:h.string().optional().describe("Extra context for the advisor"),error:h.object({message:h.string().optional(),stack:h.string().optional(),kind:h.string().optional()}).optional().describe("An error the code produced, to guide the fix"),steer:h.string().optional().describe("A steer on a refine turn (e.g. 'no, round half-up')"),prior_diff:h.string().optional().describe("The previously proposed diff, to refine")}},async({capsule_id:o,question:a,note:i,error:s,steer:c,prior_diff:d})=>{if(!r)return{content:[{type:"text",text:"Error: could not derive agent handle from grant token."}],isError:!0};let u=await H(t,n,`/api/agents/${encodeURIComponent(r)}/code-capsule/${encodeURIComponent(o)}/advise`,{question:a,note:i,error:s,steer:c,prior_diff:d});return U(u)}),e.registerTool("nodata_code_patch",{description:"Submit a fix to a code capsule as a SIGNED, queued patch WITHOUT seeing its source. Provide a raw unified `diff`, or a whole-file `replace` ({path, content}) that is diffed server-side against the sealed source. The source is never persisted or returned; you get back a patch id, the diff hash, and a receipt. Requires a capsule grant (scope.fabric_developers). Hard-scoped to this server's grant token.",inputSchema:{capsule_id:h.string().describe("The code capsule to patch (you must be granted on it)"),summary:h.string().optional().describe("Short human-readable summary of the fix"),diff:h.string().optional().describe("A raw unified diff (advanced)"),replace:h.object({path:h.string(),content:h.string()}).optional().describe("Whole-file replacement; the diff is synthesized server-side against sealed source")}},async({capsule_id:o,summary:a,diff:i,replace:s})=>{if(!r)return{content:[{type:"text",text:"Error: could not derive agent handle from grant token."}],isError:!0};let c=await H(t,n,`/api/agents/${encodeURIComponent(r)}/code-capsule/${encodeURIComponent(o)}/patch`,{summary:a,diff:i,replace:s});return U(c)})}var Li=`WHAT NODATA DOES \u2014 in one line:
89
117
  Give any agent real power over your data, without the power to leak it.
90
118
  (Possession is not permission: it can hold the key and still not read what you didn't allow.)
91
- `,Td=`TURN THE DATA TOOLS ON \u2014 3 steps, about a minute, once:
119
+ `,tp=`TURN THE DATA TOOLS ON \u2014 3 steps, about a minute, once:
92
120
 
93
121
  1. GET A KEY call nodata_connect (no arguments)
94
122
  -> opens the signup in your browser: email + company (~30s), a 12-word
@@ -101,7 +129,7 @@ Ask the user to add them to that file themselves (not in this chat), then call t
101
129
  3. ACTIVATE type /mcp (or restart Claude Code) so the tools load.
102
130
 
103
131
  COMING BACK LATER? Nothing to redo \u2014 it starts ready. If the tools look missing, just /mcp.
104
- `,Pd=`YOUR WORKSPACE \u2014 say it in plain words; anything that changes files or policy asks you first:
132
+ `,np=`YOUR WORKSPACE \u2014 say it in plain words; anything that changes files or policy asks you first:
105
133
 
106
134
  1. SEE "scan <folder>" -> nodata_scan_folder: the whole result + a full HTML report,
107
135
  on this machine, nothing uploads.
@@ -117,28 +145,30 @@ COMING BACK LATER? Nothing to redo \u2014 it starts ready. If the tools look mis
117
145
 
118
146
  Database tables: nodata_register_table + nodata_connect_source, then nodata_grant.
119
147
  One secret value: nodata_encrypt, hand it over once: nodata_deliver.
120
- `,Dd=`WHAT YOU CAN DO \u2014 scoped to your grant; you reach only what it allows, the rest never decrypts:
148
+ `,rp=`WHAT YOU CAN DO \u2014 scoped to your grant; you reach only what it allows, the rest never decrypts:
121
149
 
122
150
  1. PLAN nodata_decide "may I reach X?" -> allow / partial / deny + a signed proof. No data moves.
123
151
  2. PULL nodata_retrieve prompt-ready context, allowed fields only, with a receipt.
124
152
  (nodata_read for raw governed rows.)
125
153
  3. ACT nodata_use run a capability with a secret injected server-side \u2014 you never see it.
126
- `,Ma=`STUCK? There's always a next step:
154
+ `,Mi=`STUCK? There's always a next step:
127
155
  - Don't see the nodata_* tools? They load when the client starts \u2014 type /mcp or restart.
128
156
  (Expected, not an error.)
129
157
  - No MCP at all? The same governance runs from one curl, or the guided page:
130
158
  https://www.nodatacapsule.com/developers/get-started
131
- `;function Fa(e){return e==="setup"?`You're connected to NoData \u2014 but there's NO key yet, so the data tools are still off.
159
+ `;function Fi(e){return e==="setup"?`You're connected to NoData \u2014 but there's NO key yet, so the data tools are still off.
132
160
 
133
161
  `:e==="agent"?`You're connected to NoData, scoped to one grant token.
134
162
 
135
163
  `:`You're connected to NoData (admin mode). You don't memorize commands \u2014 just ask in plain words.
136
164
 
137
- `}function Od(e){if(e==="setup")return Fa(e)+ja+`
138
- `+Td+`
139
- `+Ma;let t=e==="agent"?Dd:Pd;return Fa(e)+ja+`
165
+ `}function op(e){return(e!=="agent"&&!_n()?`FIRST \u2014 NoData's terms of use (updated for AI agents) are not accepted on this machine yet. Call nodata_terms to show them; the data tools start once the user accepts.
166
+
167
+ `:"")+ap(e)}function ap(e){if(e==="setup")return Fi(e)+Li+`
168
+ `+tp+`
169
+ `+Mi;let t=e==="agent"?rp:np;return Fi(e)+Li+`
140
170
  `+t+`
141
- `+Ma}function Nd(e,t){e.registerTool("nodata_get_started",{description:"Call this FIRST (no arguments). NoData in one line: what you can achieve \u2014 an agent that cannot leak, a look at what is already exposed, a secret we cannot read \u2014 with the single next step for each, and how to recover if the tools or MCP seem stuck. If the user asks what NoData can do, how to start, or why the tools are missing, call this and relay it.",inputSchema:{}},async()=>({content:[{type:"text",text:Od(t)}]}))}var Id="/capsule-api/register";function Cd(e){let t=process.platform==="win32",n=process.platform==="darwin"?"open":t?"cmd":"xdg-open",r=t?["/c","start","",e]:[e];try{let o=sd(n,r,{stdio:"ignore",detached:!0});return o.on("error",()=>{}),o.unref(),!0}catch{return!1}}function Rd(e,t){e.registerTool("nodata_connect",{description:"Switch NoData's data tools on. Step 1: call with NO arguments to open the free signup in a browser (email + company, ~30s \u2014 also where your 12-word recovery phrase + email verification happen); it shows an ORG KEY once. Step 2: call this tool again with that key as `api_key` and it is saved on this machine, so every later start comes up ready with nothing to retype. Step 3: type /mcp (or restart) so the client loads the tools.",inputSchema:{api_key:f.string().optional().describe("The org key shown once at signup (ndp_\u2026 or sk_\u2026). Omit on the first call to open signup.")}},async({api_key:n})=>{let r=(n??"").trim();if(!r){let u=t+Id;return{content:[{type:"text",text:(Cd(u)?`STEP 1 of 3 \u2014 opened the NoData signup in your browser:
171
+ `+Mi}function ip(e,t){e.registerTool("nodata_get_started",{description:"Call this FIRST (no arguments). NoData in one line: what you can achieve \u2014 an agent that cannot leak, a look at what is already exposed, a secret we cannot read \u2014 with the single next step for each, and how to recover if the tools or MCP seem stuck. If the user asks what NoData can do, how to start, or why the tools are missing, call this and relay it.",inputSchema:{}},async()=>({content:[{type:"text",text:op(t)}]}))}var sp="/capsule-api/register";function cp(e){let t=process.platform==="win32",n=process.platform==="darwin"?"open":t?"cmd":"xdg-open",r=t?["/c","start","",e]:[e];try{let o=ju(n,r,{stdio:"ignore",detached:!0});return o.on("error",()=>{}),o.unref(),!0}catch{return!1}}function lp(e,t){e.registerTool("nodata_connect",{description:"Switch NoData's data tools on. Step 1: call with NO arguments to open the free signup in a browser (email + company, ~30s \u2014 also where your 12-word recovery phrase + email verification happen); it shows an ORG KEY once. Step 2: call this tool again with that key as `api_key` and it is saved on this machine, so every later start comes up ready with nothing to retype. Step 3: type /mcp (or restart) so the client loads the tools.",inputSchema:{api_key:h.string().optional().describe("The org key shown once at signup (ndp_\u2026 or sk_\u2026). Omit on the first call to open signup.")}},async({api_key:n})=>{let r=(n??"").trim();if(!r){let u=t+sp;return{content:[{type:"text",text:(cp(u)?`STEP 1 of 3 \u2014 opened the NoData signup in your browser:
142
172
  `:`STEP 1 of 3 \u2014 open the NoData signup in your browser:
143
173
  `)+u+`
144
174
 
@@ -150,13 +180,15 @@ There, about a minute:
150
180
  STEP 2 \u2014 come back and call this tool again with the key:
151
181
  nodata_connect api_key: "<the key you copied>"
152
182
  and I'll save it so you never paste it again. (Then STEP 3: type /mcp to activate.)`}]}}if(!/^(ndp_|sk_)/.test(r))return{content:[{type:"text",text:`That doesn't look like a NoData org key (it should start with ndp_ or sk_).
153
- Copy the key shown once on the signup page and try again: nodata_connect api_key: "ndp_\u2026".`}]};let{publicKeyHex:o,privateKeyPkcs8B64:a}=_d(),i=Sd(),s=Ua()||"this device",l=await vd(t,r,i,s,o);if(l.ok){try{Ba({device:{org_id:l.orgId,handle:i,label:s,private_key_pkcs8_b64:a,public_key_hex:o},base_url:t})}catch(u){return{content:[{type:"text",text:"Enrolled the device, but couldn't save it locally: "+(u instanceof Error?u.message:String(u))}]}}return{content:[{type:"text",text:`STEP 2 done \u2014 this device is enrolled as "${s}" (${i}), and only its PRIVATE key is
183
+ Copy the key shown once on the signup page and try again: nodata_connect api_key: "ndp_\u2026".`}]};let{publicKeyHex:o,privateKeyPkcs8B64:a}=Wu(),i=zu(),s=Hi()||"this device",c=await Yu(t,r,i,s,o);if(c.ok){try{$i({device:{org_id:c.orgId,handle:i,label:s,private_key_pkcs8_b64:a,public_key_hex:o},base_url:t})}catch(u){return{content:[{type:"text",text:"Enrolled the device, but couldn't save it locally: "+(u instanceof Error?u.message:String(u))}]}}return{content:[{type:"text",text:`STEP 2 done \u2014 this device is enrolled as "${s}" (${i}), and only its PRIVATE key is
154
184
  saved at ~/.nodata/credentials.json (readable only by you). The org key you pasted was NOT
155
185
  stored: every start now proves possession by signing a fresh challenge and gets a 15-minute token.
156
186
 
157
- STEP 3 \u2014 type /mcp (or restart Claude Code) and the admin tools appear. Next time: nothing to do.`}]}}let d=l.status===404||l.status===0;try{Ba({api_key:r,key_prefix:r.slice(0,12),base_url:t})}catch(u){return{content:[{type:"text",text:"Couldn't save locally: "+(u instanceof Error?u.message:String(u))+`
187
+ STEP 3 \u2014 type /mcp (or restart Claude Code) and the admin tools appear. Next time: nothing to do.`}]}}let d=c.status===404||c.status===0;try{$i({api_key:r,key_prefix:r.slice(0,12),base_url:t})}catch(u){return{content:[{type:"text",text:"Couldn't save locally: "+(u instanceof Error?u.message:String(u))+`
158
188
  As a fallback, pass it on launch: claude mcp add nodata --env NODATA_API_KEY=<your key> -- npx @nodatachat/mcp`}]}}return{content:[{type:"text",text:(d?`STEP 2 done \u2014 saved your key on this machine (device attestation isn't available on this
159
- server yet, so this is the key-at-rest path). `:`STEP 2 done \u2014 saved your key on this machine (device enrollment didn't succeed: ${l.error}). `)+`Every future start loads it automatically \u2014 no re-register, no re-paste.
189
+ server yet, so this is the key-at-rest path). `:`STEP 2 done \u2014 saved your key on this machine (device enrollment didn't succeed: ${c.error}). `)+`Every future start loads it automatically \u2014 no re-register, no re-paste.
160
190
 
161
- STEP 3 \u2014 type /mcp (or restart Claude Code) and the admin tools appear. Next time: nothing to do.`}]}})}async function $d(){let{apiKey:e,grantToken:t,baseUrl:n,credentialSource:r,device:o}=hd(process.argv.slice(2)),a=t?"agent":e||o?"admin":"setup",i=new od({name:a==="agent"?"NoData (agent-scoped)":a==="setup"?"NoData (setup)":"NoData",version:wr}),s=()=>o?`device "${o.label}" (${o.handle}) \xB7 org ${o.org_id}`:e?`org key ${e.slice(0,12)}\u2026`:"not connected \u2014 local only",l=o?Ed(n,o):e||null;if(l){xd(i,n,l,s),xa(i,n,async()=>{let p=await an(l);if("error"in p)throw new Error("no usable org credential \u2014 run nodata_connect");return p.token},s);let u=async(p,h,m)=>{let v=await an(l);if("error"in v)return{status:401,body:{error:"no usable org credential \u2014 run nodata_connect"}};let k=await fetch(`${n}${h}`,{method:p,headers:{authorization:`Bearer ${v.token}`,...m?{"content-type":"application/json"}:{}},...m?{body:JSON.stringify(m)}:{}});return{status:k.status,body:await k.json().catch(()=>({}))}};$a(i,{get:p=>u("GET",p),post:(p,h)=>u("POST",p,h)},()=>Ra(o?.private_key_pkcs8_b64,o?.label),s)}t&&Ad(i,n,t),Nd(i,a),a!=="agent"&&ao(i,s),a==="setup"?(Rd(i,n),console.error(`nodata-mcp: no credential given \u2014 running in setup mode (data tools disabled).
162
- Call nodata_connect (opens signup, enrolls this device), or pass --api-key / --grant-token. See --help.`)):o?console.error(`nodata-mcp: loaded device identity "${o.label}" (${o.handle}) \u2014 attest mode; tokens are minted per session.`):r==="stored"&&console.error("nodata-mcp: loaded saved credential from ~/.nodata/credentials.json (admin mode).");let d=new ad;await i.connect(d)}$d().catch(e=>{console.error("Fatal error:",e),process.exit(1)});
191
+ STEP 3 \u2014 type /mcp (or restart Claude Code) and the admin tools appear. Next time: nothing to do.`}]}})}async function dp(){let e=process.argv[2];if(e==="gate")return ii(process.argv.slice(3));if(e==="install-gate"||e==="uninstall-gate"){let y=Ri([]),_=y.device?Ki(y.baseUrl,y.device):y.apiKey||null,k=_?{baseUrl:y.baseUrl,org:y.device?.org_id??null,token:ji(_)}:null,b=process.argv.includes("--block"),S=e==="install-gate"?di(new URL("./gate.js",import.meta.url),b):ui(),v=await Si(k,e==="install-gate"?"read-gate-install":"read-gate-uninstall",$r("cli",y.device?.label),b?"block":"ask");process.stdout.write(S+(v?`
192
+ Recorded at NoData for your organisation (operational only).`:"")+`
193
+ `);return}let{apiKey:t,grantToken:n,baseUrl:r,credentialSource:o,device:a}=Ri(process.argv.slice(2)),i=n?"agent":t||a?"admin":"setup",s=new $u({name:i==="agent"?"NoData (agent-scoped)":i==="setup"?"NoData (setup)":"NoData",version:qr}),c=()=>$r(s.server.getClientVersion()?.name,a?.label),d=()=>`${fi(c())} \xB7 `+(a?`device "${a.label}" (${a.handle}) \xB7 org ${a.org_id}`:t?`org key ${t.slice(0,12)}\u2026`:"not connected \u2014 local only"),u=a?Ki(r,a):t||null,p=u?{baseUrl:r,org:a?.org_id??null,token:ji(u)}:null;if(i!=="agent"&&(vi(s,p,c,`${r}/terms`),ki(s),p&&wi(p)),u){Qu(s,r,u,d),Za(s,r,async()=>{let _=await Bt(u);if("error"in _)throw new Error("no usable org credential \u2014 run nodata_connect");return _.token},d);let y=async(_,k,b)=>{let S=await Bt(u);if("error"in S)return{status:401,body:{error:"no usable org credential \u2014 run nodata_connect"}};let v=await fetch(`${r}${k}`,{method:_,headers:{authorization:`Bearer ${S.token}`,...b?{"content-type":"application/json"}:{}},...b?{body:JSON.stringify(b)}:{}});return{status:v.status,body:await v.json().catch(()=>({}))}};Ii(s,{get:_=>y("GET",_),post:(_,k)=>y("POST",_,k)},()=>Ci(a?.private_key_pkcs8_b64,a?.label),d)}n&&ep(s,r,n),ip(s,i),i!=="agent"&&Io(s,d),i==="setup"?(lp(s,r),console.error(`nodata-mcp: no credential given \u2014 running in setup mode (data tools disabled).
194
+ Call nodata_connect (opens signup, enrolls this device), or pass --api-key / --grant-token. See --help.`)):a?console.error(`nodata-mcp: loaded device identity "${a.label}" (${a.handle}) \u2014 attest mode; tokens are minted per session.`):o==="stored"&&console.error("nodata-mcp: loaded saved credential from ~/.nodata/credentials.json (admin mode).");let f=new Ru;await s.connect(f)}dp().catch(e=>{console.error("Fatal error:",e),process.exit(1)});