@nodatachat/mcp 1.3.10 → 1.3.15
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/README.md +31 -7
- package/dist/gate.js +22 -16
- package/dist/index.js +138 -114
- package/dist/status.js +2 -2
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,33 +1,33 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
/*! @nodatachat/mcp 1.3.
|
|
2
|
+
/*! @nodatachat/mcp 1.3.15 | 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
|
|
5
|
-
`,{mode:384});try{
|
|
6
|
-
`,{mode:384}),{path:e,ndc:c,sha256:i,sealId:o}}function
|
|
7
|
-
`),i}});var Me=N(Fr=>{"use strict";Object.defineProperty(Fr,"__esModule",{value:!0});var Tt=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"]),i=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!0,["encrypt","decrypt"]),o=crypto.getRandomValues(new Uint8Array(12)),a=new TextEncoder().encode(t),s=await crypto.subtle.encrypt({name:"AES-GCM",iv:o,tagLength:128},i,a),c=await crypto.subtle.exportKey("raw",i),l=await crypto.subtle.encrypt({name:"RSA-OAEP"},r,c);return{encrypted_blob:this.arrayBufferToBase64(s),encrypted_aes_key:this.arrayBufferToBase64(l),iv:this.arrayBufferToBase64(o)}}static async decryptMessage(t,n){let r=await crypto.subtle.importKey("jwk",n,{name:"RSA-OAEP",hash:"SHA-256"},!1,["decrypt"]),i=this.base64ToArrayBuffer(t.encrypted_aes_key),o=await crypto.subtle.decrypt({name:"RSA-OAEP"},r,i),a=await crypto.subtle.importKey("raw",o,{name:"AES-GCM",length:256},!1,["decrypt"]),s=this.base64ToArrayBuffer(t.iv),c=this.base64ToArrayBuffer(t.encrypted_blob),l=await crypto.subtle.decrypt({name:"AES-GCM",iv:s,tagLength:128},a,c);return new TextDecoder().decode(l)}static async encryptFile(t,n){let r=await t.arrayBuffer(),i=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!0,["encrypt","decrypt"]),o=crypto.getRandomValues(new Uint8Array(12)),a=await crypto.subtle.encrypt({name:"AES-GCM",iv:o,tagLength:128},i,r),s=JSON.stringify({name:t.name,type:t.type,size:t.size,lastModified:t.lastModified}),c=crypto.getRandomValues(new Uint8Array(12)),l=await crypto.subtle.encrypt({name:"AES-GCM",iv:c,tagLength:128},i,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",i),h=await crypto.subtle.encrypt({name:"RSA-OAEP"},u,p);return{encrypted_file:this.arrayBufferToBase64(a),encrypted_file_key:this.arrayBufferToBase64(h),iv:this.arrayBufferToBase64(o),encrypted_metadata:this.arrayBufferToBase64(l),metadata_iv:this.arrayBufferToBase64(c),encrypted_size:a.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 i=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},i,{name:"AES-GCM",length:256},!0,["encrypt","decrypt"])}static async encryptWithDerivedKey(t,n){let r=crypto.getRandomValues(new Uint8Array(12)),i=new TextEncoder().encode(t),o=await crypto.subtle.encrypt({name:"AES-GCM",iv:r,tagLength:128},n,i);return{encrypted:this.arrayBufferToBase64(o),iv:this.arrayBufferToBase64(r)}}static async decryptWithDerivedKey(t,n,r){let i=this.base64ToArrayBuffer(t),o=this.base64ToArrayBuffer(n),a=await crypto.subtle.decrypt({name:"AES-GCM",iv:o,tagLength:128},r,i);return new TextDecoder().decode(a)}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(i=>i.toString(16).padStart(2,"0")).join("")}static async encryptFileWithDerivedKey(t,n){let r=await t.arrayBuffer(),i=await this.sha256Hex(r),o=crypto.getRandomValues(new Uint8Array(12)),a=await crypto.subtle.encrypt({name:"AES-GCM",iv:o,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)),l=await crypto.subtle.encrypt({name:"AES-GCM",iv:c,tagLength:128},n,new TextEncoder().encode(s));return{encrypted_file:this.arrayBufferToBase64(a),iv:this.arrayBufferToBase64(o),encrypted_metadata:this.arrayBufferToBase64(l),metadata_iv:this.arrayBufferToBase64(c),encrypted_size:a.byteLength,plaintext_sha256:i,ciphertext_sha256:await this.sha256Hex(a)}}static async decryptFileBytesWithDerivedKey(t,n,r){let i=this.base64ToArrayBuffer(n);return crypto.subtle.decrypt({name:"AES-GCM",iv:i,tagLength:128},r,t)}static async decryptFileWithDerivedKey(t,n,r){let i=this.base64ToArrayBuffer(t),o=this.base64ToArrayBuffer(n);return crypto.subtle.decrypt({name:"AES-GCM",iv:o,tagLength:128},r,i)}static async deriveSeedKey(t,n="SHA-512"){let r=t.trim().toLowerCase(),i=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},i,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}static async exportKeyWithSeed(t,n){let r=await crypto.subtle.exportKey("jwk",t),i=new TextEncoder().encode(JSON.stringify(r)),o=crypto.getRandomValues(new Uint8Array(12)),a=await crypto.subtle.encrypt({name:"AES-GCM",iv:o,tagLength:128},n,i),s=new Uint8Array(o.byteLength+a.byteLength);return s.set(o,0),s.set(new Uint8Array(a),o.byteLength),s.buffer}static async importKeyWithSeed(t,n){let r=new Uint8Array(t),i=r.slice(0,12),o=r.slice(12),a=await crypto.subtle.decrypt({name:"AES-GCM",iv:i,tagLength:128},n,o),s=new TextDecoder().decode(a),c=JSON.parse(s),l=await crypto.subtle.importKey("jwk",c,{name:"RSA-OAEP",hash:"SHA-256"},!0,["decrypt"]);return new Uint8Array(a).fill(0),l}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(i=>i.toString(16).padStart(2,"0")).join("")}static arrayBufferToBase64(t){let n=new Uint8Array(t),r=32768,i=[];for(let o=0;o<n.length;o+=r)i.push(String.fromCharCode(...n.subarray(o,o+r)));return btoa(i.join(""))}static async encryptFileToBytesWithDerivedKey(t,n){let r=await t.arrayBuffer(),i=await this.sha256Hex(r),o=crypto.getRandomValues(new Uint8Array(12)),a=await crypto.subtle.encrypt({name:"AES-GCM",iv:o,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)),l=await crypto.subtle.encrypt({name:"AES-GCM",iv:c,tagLength:128},n,new TextEncoder().encode(s));return{ciphertext:a,iv:this.arrayBufferToBase64(o),encrypted_metadata:this.arrayBufferToBase64(l),metadata_iv:this.arrayBufferToBase64(c),encrypted_size:a.byteLength,plaintext_sha256:i,ciphertext_sha256:await this.sha256Hex(a)}}static base64ToArrayBuffer(t){let n=atob(t),r=new Uint8Array(n.length);for(let i=0;i<n.length;i++)r[i]=n.charCodeAt(i);return r.buffer}static wipeFromMemory(t){new Uint8Array(t).fill(0)}};Tt.PBKDF2_ITERATIONS=31e4;Tt.SEED_SALT="NoDataChat-Seed-v1";Fr.default=Tt});var Wo=N(vn=>{"use strict";Object.defineProperty(vn,"__esModule",{value:!0});vn.solveProofOfWork=_d;vn.verifyProofOfWork=bd;function yd(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 Go(e){let t=new TextEncoder().encode(e),n=await crypto.subtle.digest("SHA-256",t);return yd(n)}async function _d(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 i=e+r.toString(),o=await Go(i);if(o.startsWith(n))return{nonce:r,hash:o};if(r++,r>2e9)throw new Error("Proof of work exceeded maximum attempts")}}async function bd(e,t,n=4){if(n<1||n>16)return!1;let r="0".repeat(n),i=e+t.toString();return(await Go(i)).startsWith(r)}});var Mr=N(et=>{"use strict";var vd=et&&et.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(et,"__esModule",{value:!0});et.NoDataEmail=void 0;var pe=vd(Me()),Lr=class{static async seal(t,n,r,i,o,a={}){let{encrypt_subject:s=!0,ttl_hours:c=72,attachments:l=[]}=a,u=await pe.default.encryptMessage(i,o),p=r,h=!1;if(s){let g=await pe.default.encryptMessage(r,o);p=JSON.stringify(g),h=!0}let f=[];for(let g of l){let b=await pe.default.encryptFile(g,o);f.push({encrypted_file:b})}return{from_alias:t,to:n,subject:p,subject_encrypted:h,body:u,attachments:f,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 pe.default.decryptMessage(t.body,n),i=t.subject;if(t.subject_encrypted){let a=JSON.parse(t.subject);i=await pe.default.decryptMessage(a,n)}let o=[];for(let a of t.attachments){let{encrypted_file:s}=a,c=pe.default.base64ToArrayBuffer(s.metadata_iv),l=pe.default.base64ToArrayBuffer(s.encrypted_metadata),u=pe.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),f=await crypto.subtle.importKey("raw",h,{name:"AES-GCM",length:256},!1,["decrypt"]),g=await crypto.subtle.decrypt({name:"AES-GCM",iv:c,tagLength:128},f,l),b=JSON.parse(new TextDecoder().decode(g)),S=pe.default.base64ToArrayBuffer(s.iv),v=pe.default.base64ToArrayBuffer(s.encrypted_file),w=await crypto.subtle.decrypt({name:"AES-GCM",iv:S,tagLength:128},f,v);o.push({filename:b.name,mime_type:b.type,data:w,size:b.size})}return{subject:i,body:r,attachments:o,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),i=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 — 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"',"",i,"--nodata-boundary--"].join(`\r
|
|
8
|
-
`)}};et.NoDataEmail=Lr});var Ur=N(tt=>{"use strict";var kd=tt&&tt.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(tt,"__esModule",{value:!0});tt.NoDataWebhook=void 0;var Kr=kd(Me()),Hr=class{static async encrypt(t,n,r,i){let{event_type:o,source:a,ttl_seconds:s=3600}=i,c=JSON.stringify(t),l=await Kr.default.encryptMessage(c,n),u=new Date().toISOString(),p=crypto.randomUUID(),h=`${p}.${u}.${l.encrypted_blob}`,f=await this.hmacSign(h,r);return{encrypted_event:l,event_type:o,source:a,signature:f,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}`,i=await this.hmacSign(r,n),o=new TextEncoder().encode(t.signature),a=new TextEncoder().encode(i),s=o.length^a.length,c=Math.min(o.length,a.length);for(let f=0;f<c;f++)s|=o[f]^a[f];let l=s===0,p=new Date(t.timestamp).getTime()+t.ttl_seconds*1e3,h=Date.now()>p;return{valid:l,expired:h,event_type:t.event_type,source:t.source,delivery_id:t.delivery_id}}static async decrypt(t,n){let r=await Kr.default.decryptMessage(t.encrypted_event,n);return JSON.parse(r)}static async verifyAndDecrypt(t,n,r){let i=await this.verify(t,r);if(!i.valid)throw new Error(`[NoDataWebhook] Invalid signature for delivery ${i.delivery_id}`);if(i.expired)throw new Error(`[NoDataWebhook] Payload expired for delivery ${i.delivery_id}`);return{data:await this.decrypt(t,n),delivery_id:i.delivery_id,event_type:i.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"]),i=await crypto.subtle.sign("HMAC",r,new TextEncoder().encode(t));return Kr.default.arrayBufferToBase64(i)}};tt.NoDataWebhook=Hr});var Gr=N(nt=>{"use strict";var Sd=nt&&nt.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(nt,"__esModule",{value:!0});nt.NoDataSystems=void 0;var kn=Sd(Me()),Vr=class{static async encryptRecord(t,n,r,i,o,a){let s=[],c={};for(let[l,u]of Object.entries(r))if(i.sensitive.includes(l)){let p=typeof u=="string"?u:JSON.stringify(u),h=await kn.default.encryptMessage(p,o),f=await this.hashValue(p);s.push({value:h,search_hash:f,field_name:l,encrypted_at:new Date().toISOString()})}else c[l]=u;return{record_id:t,record_type:n,encrypted_fields:s,clear_fields:c,encrypted_by:a,created_at:new Date().toISOString(),crypto_version:"0.2.0"}}static async decryptRecord(t,n){let r={...t.clear_fields};for(let i of t.encrypted_fields){let o=await kn.default.decryptMessage(i.value,n);try{r[i.field_name]=JSON.parse(o)}catch{r[i.field_name]=o}}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 i=await this.hashValue(r);return t.filter(o=>o.encrypted_fields.some(a=>a.field_name===n&&a.search_hash===i))}static async encryptField(t,n,r){let i=typeof n=="string"?n:JSON.stringify(n),o=await kn.default.encryptMessage(i,r),a=await this.hashValue(i);return{value:o,search_hash:a,field_name:t,encrypted_at:new Date().toISOString()}}static async decryptField(t,n){let r=await kn.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),i=await crypto.subtle.digest("SHA-256",r);return Array.from(new Uint8Array(i)).map(o=>o.toString(16).padStart(2,"0")).join("")}};nt.NoDataSystems=Vr});var zr=N(rt=>{"use strict";var wd=rt&&rt.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(rt,"__esModule",{value:!0});rt.NoDataForms=void 0;var fe=wd(Me()),Wr=class{static async encryptSubmission(t,n,r,i,o={}){let{ttl_hours:a=0,view_once:s=!1,attachments:c=[]}=o,l={},u={};for(let S of n)S.sensitive!==!1?l[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),f=await fe.default.encryptMessage(JSON.stringify(l),r),g=[];for(let S of c){let v=await fe.default.encryptFile(S,r);g.push(v)}let b=n.map(S=>S.name);return{submission_id:crypto.randomUUID(),form_id:t,encrypted_fields:f,clear_fields:u,attachments:g,integrity_hash:h,field_order:b,submitter_id:i,submitted_at:new Date().toISOString(),ttl_hours:a,view_once:s,crypto_version:"0.2.0"}}static async decryptSubmission(t,n){let r=await fe.default.decryptMessage(t.encrypted_fields,n),i=JSON.parse(r),o={...t.clear_fields,...i},s=(t.field_order||Object.keys(o).sort()).map(p=>({name:p,value:o[p]})),l=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"]),f=await crypto.subtle.decrypt({name:"RSA-OAEP"},h,fe.default.base64ToArrayBuffer(p.encrypted_file_key)),g=await crypto.subtle.importKey("raw",f,{name:"AES-GCM",length:256},!1,["decrypt"]),b=await crypto.subtle.decrypt({name:"AES-GCM",iv:fe.default.base64ToArrayBuffer(p.metadata_iv),tagLength:128},g,fe.default.base64ToArrayBuffer(p.encrypted_metadata)),S=JSON.parse(new TextDecoder().decode(b)),v=await crypto.subtle.decrypt({name:"AES-GCM",iv:fe.default.base64ToArrayBuffer(p.iv),tagLength:128},g,fe.default.base64ToArrayBuffer(p.encrypted_file));u.push({filename:S.name,mime_type:S.type,data:v,size:S.size})}return{submission_id:t.submission_id,form_id:t.form_id,fields:o,attachments:u,integrity_valid:l,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,i,o=0){let a=await fe.default.encryptMessage(JSON.stringify(t),n),s=await this.sha256(`nodatachat:student:${t.student_id}`);return{encrypted_grade:a,student_hash:s,course_id:r,term:i,delivery_id:crypto.randomUUID(),delivered_at:new Date().toISOString(),ttl_hours:o,crypto_version:"0.2.0"}}static async decryptGrade(t,n){let r=await fe.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(i=>i.toString(16).padStart(2,"0")).join("")}};rt.NoDataForms=Wr});var zo=N(it=>{"use strict";var Ed=it&&it.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(it,"__esModule",{value:!0});it.NoDataSDK=void 0;var Sn=Ed(Me()),we=Mr(),Ee=Ur(),re=Gr(),he=zr(),qr=class{static async init(t={}){let n;return t.keyPair?n=t.keyPair:(n=await Sn.default.generateKeyPair(),t.onKeysGenerated&&await t.onKeysGenerated(n)),{publicKey:n.publicKeyJwk,email:{seal:we.NoDataEmail.seal.bind(we.NoDataEmail),open:we.NoDataEmail.open.bind(we.NoDataEmail),isExpired:we.NoDataEmail.isExpired.bind(we.NoDataEmail),toMimeBody:we.NoDataEmail.toMimeBody.bind(we.NoDataEmail)},webhook:{encrypt:Ee.NoDataWebhook.encrypt.bind(Ee.NoDataWebhook),verify:Ee.NoDataWebhook.verify.bind(Ee.NoDataWebhook),decrypt:Ee.NoDataWebhook.decrypt.bind(Ee.NoDataWebhook),verifyAndDecrypt:Ee.NoDataWebhook.verifyAndDecrypt.bind(Ee.NoDataWebhook)},systems:{encryptRecord:re.NoDataSystems.encryptRecord.bind(re.NoDataSystems),decryptRecord:re.NoDataSystems.decryptRecord.bind(re.NoDataSystems),searchByHash:re.NoDataSystems.searchByHash.bind(re.NoDataSystems),encryptField:re.NoDataSystems.encryptField.bind(re.NoDataSystems),decryptField:re.NoDataSystems.decryptField.bind(re.NoDataSystems),createSchema:re.NoDataSystems.createSchema.bind(re.NoDataSystems)},forms:{encryptSubmission:he.NoDataForms.encryptSubmission.bind(he.NoDataForms),decryptSubmission:he.NoDataForms.decryptSubmission.bind(he.NoDataForms),isExpired:he.NoDataForms.isExpired.bind(he.NoDataForms),encryptGrade:he.NoDataForms.encryptGrade.bind(he.NoDataForms),decryptGrade:he.NoDataForms.decryptGrade.bind(he.NoDataForms)},crypto:Sn.default}}static async quickEncrypt(t,n){let r=typeof t=="string"?t:JSON.stringify(t),i=await Sn.default.encryptMessage(r,n);return JSON.stringify(i)}static async quickDecrypt(t,n){let r=JSON.parse(t),i=await Sn.default.decryptMessage(r,n);try{return JSON.parse(i)}catch{return i}}};it.NoDataSDK=qr});var qo=N(ie=>{"use strict";Object.defineProperty(ie,"__esModule",{value:!0});ie.NoDataSDK=ie.NoDataForms=ie.NoDataSystems=ie.NoDataWebhook=ie.NoDataEmail=void 0;var xd=Mr();Object.defineProperty(ie,"NoDataEmail",{enumerable:!0,get:function(){return xd.NoDataEmail}});var Ad=Ur();Object.defineProperty(ie,"NoDataWebhook",{enumerable:!0,get:function(){return Ad.NoDataWebhook}});var Td=Gr();Object.defineProperty(ie,"NoDataSystems",{enumerable:!0,get:function(){return Td.NoDataSystems}});var Pd=zr();Object.defineProperty(ie,"NoDataForms",{enumerable:!0,get:function(){return Pd.NoDataForms}});var Id=zo();Object.defineProperty(ie,"NoDataSDK",{enumerable:!0,get:function(){return Id.NoDataSDK}})});var at=N($=>{"use strict";Object.defineProperty($,"__esModule",{value:!0});$.PQ_SIZES=$.NDC_WIRE_V03=$.NDC_WIRE_V1=$.NDC_V03_RATCHET_DOMAIN=$.NDC_V03_CONTENT_KEY_DOMAIN=$.NDC_V03_KEM_DOMAIN=$.PQ_SUITE=void 0;$.generateHybridKemKeypair=$d;$.deriveHybridKemKeypairFromSeed=Rd;$.hybridKemEncapsulate=Dd;$.hybridKemDecapsulate=Cd;$.deriveContentKey=Nd;$.ratchetAdvance=Od;$.generateHybridSigKeypair=jd;$.hybridSign=Bd;$.hybridVerify=Fd;$.generateMlDsa65Keypair=Ld;$.mlDsa65SignDetached=Md;$.mlDsa65VerifyDetached=Kd;var xe=P("@noble/curves/ed25519.js"),Pt=P("@noble/hashes/sha2.js"),It=P("@noble/hashes/hkdf.js"),wn=P("@noble/post-quantum/ml-kem.js"),ot=P("@noble/post-quantum/ml-dsa.js");$.PQ_SUITE={KEM:"X25519+ML-KEM-768",SIG:"Ed25519+ML-DSA-65",AEAD:"AES-256-GCM",KDF:"HKDF-SHA-256"};$.NDC_V03_KEM_DOMAIN="NDC-v0.3-hybrid-kem";$.NDC_V03_CONTENT_KEY_DOMAIN="NDC-v0.3-content-key";$.NDC_V03_RATCHET_DOMAIN="NDC-ratchet";$.NDC_WIRE_V1=1;$.NDC_WIRE_V03=2;function Jo(...e){let t=0;for(let i of e)t+=i.length;let n=new Uint8Array(t),r=0;for(let i of e)n.set(i,r),r+=i.length;return n}function $t(e){return new TextEncoder().encode(e)}function Xo(e,t,n,r){let i=Jo(e,t),o=Jo($t($.NDC_V03_KEM_DOMAIN),n,r);return(0,It.hkdf)(Pt.sha256,i,new Uint8Array(0),o,32)}function $d(){let{secretKey:e,publicKey:t}=xe.x25519.keygen(),{publicKey:n,secretKey:r}=wn.ml_kem768.keygen();return{publicKey:{x25519:t,mlKem:n},secretKey:{x25519:e,mlKem:r}}}function Rd(e){if(e.length<32)throw new Error("seed too short (need >=32 bytes)");let t=(0,It.hkdf)(Pt.sha256,e,new Uint8Array(0),$t("ndc-hybrid-kem-x25519-v1"),32),n=(0,It.hkdf)(Pt.sha256,e,new Uint8Array(0),$t("ndc-hybrid-kem-mlkem768-v1"),64),r=xe.x25519.getPublicKey(t),{publicKey:i,secretKey:o}=wn.ml_kem768.keygen(n);return{publicKey:{x25519:r,mlKem:i},secretKey:{x25519:t,mlKem:o}}}function Dd(e){let{secretKey:t,publicKey:n}=xe.x25519.keygen(),r=xe.x25519.getSharedSecret(t,e.x25519),{cipherText:i,sharedSecret:o}=wn.ml_kem768.encapsulate(e.mlKem),a=Xo(o,r,n,e.x25519);return{ciphertext:{ctClassical:n,ctPq:i},sharedSecret:a,ephemeralX25519Pk:n}}function Cd(e,t,n){let r=xe.x25519.getSharedSecret(e.x25519,n.ctClassical),i=wn.ml_kem768.decapsulate(n.ctPq,e.mlKem);return Xo(i,r,n.ctClassical,t)}function Nd(e){return(0,It.hkdf)(Pt.sha256,e,new Uint8Array(0),$t($.NDC_V03_CONTENT_KEY_DOMAIN),32)}function Od(e,t){return(0,It.hkdf)(Pt.sha256,e,t,$t($.NDC_V03_RATCHET_DOMAIN),32)}function jd(){let{secretKey:e,publicKey:t}=xe.ed25519.keygen(),{publicKey:n,secretKey:r}=ot.ml_dsa65.keygen();return{publicKey:{ed25519:t,mlDsa:n},secretKey:{ed25519:e,mlDsa:r}}}function Bd(e,t){return{ed25519:xe.ed25519.sign(t,e.ed25519),mlDsa:ot.ml_dsa65.sign(t,e.mlDsa)}}function Fd(e,t,n){return xe.ed25519.verify(n.ed25519,t,e.ed25519)?ot.ml_dsa65.verify(n.mlDsa,t,e.mlDsa):!1}function Ld(){let{publicKey:e,secretKey:t}=ot.ml_dsa65.keygen();return{publicKey:e,secretKey:t}}function Md(e,t){return ot.ml_dsa65.sign(t,e)}function Kd(e,t,n){return ot.ml_dsa65.verify(n,t,e)}$.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 xn=N(R=>{"use strict";Object.defineProperty(R,"__esModule",{value:!0});R.deriveContentKey=R.ContainerV3Error=R.CONTAINER_HEADER_MAX_BYTES=R.CONTAINER_FIXED_PREFIX_BYTES=R.CONTAINER_MAGIC=void 0;R.canonicalJson=En;R.headerSigningBytes=Jr;R.signContainerHeader=ea;R.verifyContainerHeader=ta;R.encodeContainerV3=na;R.decodeContainerV3=ra;R.sealHybrid=zd;R.openHybrid=qd;var Hd=P("@noble/hashes/hkdf.js"),Ud=P("@noble/hashes/sha2.js"),K=at();Object.defineProperty(R,"deriveContentKey",{enumerable:!0,get:function(){return K.deriveContentKey}});R.CONTAINER_MAGIC=new Uint8Array([78,68,76,66]);R.CONTAINER_FIXED_PREFIX_BYTES=8;R.CONTAINER_HEADER_MAX_BYTES=16777215;var Vd="NDC-v0.3-wrap-key",U=class extends Error{constructor(t,n){super(n),this.name="ContainerV3Error",this.code=t}};R.ContainerV3Error=U;var be=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)},Ke=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},Qo=e=>{let t="";for(let n=0;n<e.length;n++)t+=e[n].toString(16).padStart(2,"0");return t};function En(e){if(e===null||typeof e!="object")return JSON.stringify(e);if(Array.isArray(e))return"["+e.map(En).join(",")+"]";let t=e;return"{"+Object.keys(t).sort().map(r=>JSON.stringify(r)+":"+En(t[r])).join(",")+"}"}function Jr(e){let t={...e};return delete t.sig,new TextEncoder().encode(En(t))}function ea(e,t,n){let r=(0,K.hybridSign)(n.secretKey,Jr(e));return{...e,sig:{signer_kid:t,ed25519:be(r.ed25519),ml_dsa_65:be(r.mlDsa)}}}function ta(e,t){let n={ed25519:Ke(e.sig.ed25519),mlDsa:Ke(e.sig.ml_dsa_65)};return(0,K.hybridVerify)(t,Jr(e),n)}var Gd=["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 Wd(e){if(!e||typeof e!="object")throw new U("header_schema_mismatch","header is not an object");let t=e;for(let r of Gd)if(t[r]===void 0)throw new U("header_schema_mismatch",`header missing required field: ${String(r)}`);if(t.format_version!==3)throw new U("unsupported_version",`format_version ${t.format_version} unknown`);if(t.profile!=="pq-hybrid")throw new U("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 U("suite_unknown",`suite mismatch: viewer supports ${JSON.stringify(K.PQ_SUITE)}, header has ${JSON.stringify(n)}`)}function na(e,t){let n=new TextEncoder().encode(JSON.stringify(e));if(n.length>R.CONTAINER_HEADER_MAX_BYTES)throw new U("header_schema_mismatch",`header too large (${n.length} bytes; max 16 MB)`);let r=new Uint8Array(R.CONTAINER_FIXED_PREFIX_BYTES+n.length+t.length);return r.set(R.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,R.CONTAINER_FIXED_PREFIX_BYTES),r.set(t,R.CONTAINER_FIXED_PREFIX_BYTES+n.length),r}function ra(e){if(e.length<R.CONTAINER_FIXED_PREFIX_BYTES)throw new U("header_truncated",`container truncated: ${e.length} bytes (need \u2265 ${R.CONTAINER_FIXED_PREFIX_BYTES})`);for(let i=0;i<4;i++)if(e[i]!==R.CONTAINER_MAGIC[i])throw new U("bad_magic",`bad magic: expected NDLB, got ${Qo(e.slice(0,4))}`);if(e[4]!==K.NDC_WIRE_V03)throw new U("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=R.CONTAINER_FIXED_PREFIX_BYTES+t;if(e.length<n)throw new U("header_truncated",`header truncated: declared ${t}, only ${e.length-R.CONTAINER_FIXED_PREFIX_BYTES} bytes left`);let r;try{r=JSON.parse(new TextDecoder("utf-8").decode(e.slice(R.CONTAINER_FIXED_PREFIX_BYTES,n)))}catch(i){throw new U("header_invalid_json",`header JSON parse failed: ${i.message}`)}return Wd(r),{header:r,ciphertextWithTag:e.slice(n)}}var He=e=>e;async function Yo(e,t,n){let r=await crypto.subtle.importKey("raw",He(e),{name:"AES-GCM"},!1,["encrypt"]),i=await crypto.subtle.encrypt({name:"AES-GCM",iv:He(t)},r,He(n));return new Uint8Array(i)}async function Zo(e,t,n){let r=await crypto.subtle.importKey("raw",He(e),{name:"AES-GCM"},!1,["decrypt"]),i=await crypto.subtle.decrypt({name:"AES-GCM",iv:He(t)},r,He(n));return new Uint8Array(i)}function ia(e){return(0,Hd.hkdf)(Ud.sha256,e,new Uint8Array(0),new TextEncoder().encode(Vd),32)}async function oa(e){let t=await crypto.subtle.digest("SHA-256",He(e));return Qo(new Uint8Array(t))}async function zd(e){let t=crypto.getRandomValues(new Uint8Array(32)),n=crypto.getRandomValues(new Uint8Array(12)),r=await Yo(t,n,e.plaintext),i=r.slice(r.length-16),o=r.slice(0,r.length-16),a=(0,K.hybridKemEncapsulate)(e.recipientPublicKey),s=ia(a.sharedSecret),c=crypto.getRandomValues(new Uint8Array(12)),l=await Yo(s,c,t),u=await oa(o),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:be(a.ciphertext.ctClassical),ct_pq:be(a.ciphertext.ctPq),ephemeral_x25519_pk:be(a.ephemeralX25519Pk)},wrapped_content_key:{wrapped:be(l),wrap_iv:be(c)},iv:be(n),tag:be(i),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=ea(p,e.signerKid,e.signerKeypair),f=na(h,r);return t.fill(0),{container:f,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 qd(e){let{header:t,ciphertextWithTag:n}=ra(e.container);if(!ta(t,e.signerPublicKey))throw new U("signature_invalid","hybrid signature verification failed");let r=n.slice(0,n.length-16),i=await oa(r);if(i!==t.ciphertext_sha256)throw new U("integrity_mismatch",`ciphertext sha256 mismatch: expected ${t.ciphertext_sha256.slice(0,16)}\u2026, got ${i.slice(0,16)}\u2026`);let o={ctClassical:Ke(t.kem.ct_classical),ctPq:Ke(t.kem.ct_pq)},a=(0,K.hybridKemDecapsulate)(e.recipientSecretKey,e.recipientPublicX25519,o),s=ia(a),c=Ke(t.wrapped_content_key.wrapped),l=Ke(t.wrapped_content_key.wrap_iv),u=await Zo(s,l,c),p=Ke(t.iv),h=await Zo(u,p,n);return u.fill(0),{plaintext:h,header:t}}});var Yr=N(ct=>{"use strict";Object.defineProperty(ct,"__esModule",{value:!0});ct.publicJwkFromBytes=sa;ct.jwkThumbprint=ca;ct.createDpop=Xd;ct.verifyDpop=Zd;var aa=P("@noble/curves/ed25519.js"),Jd=P("@noble/hashes/sha2.js"),st=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,"_")},An=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 i=atob(r),o=new Uint8Array(i.length);for(let a=0;a<i.length;a++)o[a]=i.charCodeAt(a);return o},Rt=e=>new TextEncoder().encode(e);function sa(e){if(e.length!==32)throw new Error(`expected 32-byte Ed25519 public key, got ${e.length}`);return{kty:"OKP",crv:"Ed25519",x:st(e)}}function ca(e){let t=`{"crv":"${e.crv}","kty":"${e.kty}","x":"${e.x}"}`,n=(0,Jd.sha256)(Rt(t));return st(n)}function Xd(e){let n={typ:"dpop+jwt",alg:"EdDSA",jwk:sa(e.publicKey)},r={htm:e.htm.toUpperCase(),htu:Xr(e.htu),jti:e.jti??Yd(),iat:e.iat??Math.floor(Date.now()/1e3)};e.nonce&&(r.nonce=e.nonce);let i=st(Rt(JSON.stringify(n))),o=st(Rt(JSON.stringify(r))),a=`${i}.${o}`,s=aa.ed25519.sign(Rt(a),e.secretKey);return`${a}.${st(s)}`}function Yd(){return st(crypto.getRandomValues(new Uint8Array(16)))}function Xr(e){try{let t=new URL(e);return`${t.protocol}//${t.host}${t.pathname}`}catch{return e}}async function Zd(e,t){let n=e.split(".");if(n.length!==3)return V("malformed","expected three JWT parts");let[r,i,o]=n,a;try{a=JSON.parse(new TextDecoder().decode(An(r)))}catch{return V("bad_header","header is not valid base64url JSON")}if(a.typ!=="dpop+jwt")return V("bad_typ",`typ must be 'dpop+jwt', got '${String(a.typ)}'`);if(a.alg!=="EdDSA")return V("bad_alg",`alg must be 'EdDSA', got '${String(a.alg)}'`);if(!a.jwk||a.jwk.kty!=="OKP"||a.jwk.crv!=="Ed25519")return V("bad_header","jwk must be an Ed25519 OKP key");let s=ca(a.jwk);if(s!==t.expectedJkt)return V("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(An(i)))}catch{return V("bad_payload","payload is not valid base64url JSON")}if(c.htm!==t.expectedHtm.toUpperCase())return V("htm_mismatch",`htm '${c.htm}' \u2260 expected '${t.expectedHtm.toUpperCase()}'`);if(c.htu!==Xr(t.expectedHtu))return V("htu_mismatch",`htu '${c.htu}' \u2260 expected '${Xr(t.expectedHtu)}'`);if(t.expectedNonce!==void 0&&c.nonce!==t.expectedNonce)return V("nonce_mismatch","DPoP nonce does not match server-issued nonce");let l=Math.floor(Date.now()/1e3),u=t.maxAgeSeconds??30;if(typeof c.iat!="number")return V("bad_payload","iat missing or not a number");if(c.iat>l+5)return V("iat_in_future",`iat ${c.iat} > now+skew`);if(l-c.iat>u)return V("iat_too_old",`iat ${c.iat} older than ${u}s`);let p;try{p=An(a.jwk.x)}catch{return V("bad_header","jwk.x is not base64url")}let h=An(o),f=Rt(`${r}.${i}`);return aa.ed25519.verify(h,f,p)?await t.isJtiFresh(c.jti)?{ok:!0,jti:c.jti,iat:c.iat}:V("replay",`jti ${c.jti} was already seen`):V("signature_invalid","Ed25519 signature does not verify")}function V(e,t){return{ok:!1,code:e,reason:t}}});var ma=N(E=>{"use strict";Object.defineProperty(E,"__esModule",{value:!0});E.ABSORB_STATUS=E.DELTA_KIND=E.RCPT_TOTAL_LEN=E.RCPT_SIGNED_LEN=E.PVE_TOTAL_LEN=E.PVE_SIGNED_LEN=E.RCPT_VERSION=E.PVE_VERSION=E.RCPT_MAGIC=E.PVE_MAGIC=void 0;E.deltaIdFromUuid=nu;E.uuidFromDeltaId=ru;E.originJktForPublicKey=Ct;E.encodePveSignedBytes=ua;E.signPve=iu;E.parsePve=pa;E.pveHash=ou;E.verifyPve=au;E.encodeReceiptSignedBytes=fa;E.signReceipt=su;E.parseReceipt=ha;E.verifyReceipt=cu;var Tn=P("@noble/curves/ed25519.js"),Qd=P("@noble/hashes/sha2.js"),la=Yr();E.PVE_MAGIC=new Uint8Array([80,86,69,49]);E.RCPT_MAGIC=new Uint8Array([82,67,86,49]);E.PVE_VERSION=1;E.RCPT_VERSION=1;E.PVE_SIGNED_LEN=160;E.PVE_TOTAL_LEN=E.PVE_SIGNED_LEN+64;E.RCPT_SIGNED_LEN=78;E.RCPT_TOTAL_LEN=E.RCPT_SIGNED_LEN+64;var da=new Uint8Array(32);E.DELTA_KIND={relay:1,ndc:2,v4section:3,chatmsg:4};E.ABSORB_STATUS={decrypted_ok:1,verified_only:2,denied:3};function eu(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 tu(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 i=atob(r),o=new Uint8Array(i.length);for(let a=0;a<i.length;a++)o[a]=i.charCodeAt(a);return o}function ei(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 Dt(e){for(let t=0;t<e.length;t++)if(e[t]!==0)return!1;return!0}function Zr(e){if(e==null)return da;if(e instanceof Uint8Array){if(e.length!==32)throw new Error(`jkt bytes must be 32, got ${e.length}`);return e}let t=tu(e);if(t.length!==32)throw new Error(`jkt must decode to 32 bytes, got ${t.length}`);return t}function Qr(e){return Dt(e)?null:eu(e)}function nu(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 ru(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 Ct(e){return(0,la.jwkThumbprint)((0,la.publicJwkFromBytes)(e))}function ua(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(E.PVE_SIGNED_LEN),n=new DataView(t.buffer),r=0;return t.set(E.PVE_MAGIC,r),r+=4,t[r]=E.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(Zr(e.originJkt),r),r+=32,t.set(Zr(e.destJkt??null),r),r+=32,t.set(e.prevDeltaHash??da,r),r+=32,n.setUint16(r,e.classification,!1),r+=2,n.setBigUint64(r,BigInt(e.issuedAt),!1),r+=8,t}function iu(e,t){let n=Ct(e.originPublicKey),r=ua({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()}),i=Tn.ed25519.sign(r,t),o=new Uint8Array(E.PVE_TOTAL_LEN);return o.set(r,0),o.set(i,E.PVE_SIGNED_LEN),o}function pa(e){if(e.length!==E.PVE_TOTAL_LEN)throw new Error(`PVE must be ${E.PVE_TOTAL_LEN} bytes, got ${e.length}`);if(!ei(e.subarray(0,4),E.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 i=e[n];n+=1;let o=e.slice(n,n+16);n+=16;let a=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 l=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,E.PVE_SIGNED_LEN),f=e.slice(E.PVE_SIGNED_LEN,E.PVE_TOTAL_LEN),g=Qr(s);if(g===null)throw new Error("origin_jkt must not be zero");return{fields:{version:r,deltaKind:i,deltaId:o,ciphertextSha256:a,originJkt:g,destJkt:Qr(c),prevDeltaHash:Dt(l)?null:l,classification:u,issuedAt:p},signedBytes:h,originSig:f,broadcast:Dt(c),genesis:Dt(l)}}function ou(e){return(0,Qd.sha256)(e)}function au(e,t){let n;try{n=pa(e)}catch(i){let o=i instanceof Error?i.message:String(i);return o.includes("magic")?{ok:!1,code:"bad_magic",reason:o}:{ok:!1,code:"malformed",reason:o}}if(n.fields.version!==E.PVE_VERSION)return{ok:!1,code:"bad_version",reason:`unsupported PVE version ${n.fields.version}`};let r;try{r=Ct(t)}catch(i){return{ok:!1,code:"malformed",reason:i instanceof Error?i.message:String(i)}}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`}:Tn.ed25519.verify(n.originSig,n.signedBytes,t)?{ok:!0,parsed:n}:{ok:!1,code:"signature_invalid",reason:"Ed25519 origin signature does not verify"}}function fa(e){if(e.pveHash.length!==32)throw new Error("pve_hash must be 32 bytes");let t=Zr(e.destJkt);if(Dt(t))throw new Error("receipt dest_jkt must not be zero");let n=new Uint8Array(E.RCPT_SIGNED_LEN),r=new DataView(n.buffer),i=0;return n.set(E.RCPT_MAGIC,i),i+=4,n[i]=E.RCPT_VERSION,i+=1,n.set(e.pveHash,i),i+=32,n.set(t,i),i+=32,n[i]=e.absorbStatus,i+=1,r.setBigUint64(i,BigInt(e.absorbedAt),!1),i+=8,n}function su(e,t){let n=Ct(e.destPublicKey),r=fa({pveHash:e.pveHash,destJkt:n,absorbStatus:e.absorbStatus,absorbedAt:e.absorbedAt??Date.now()}),i=Tn.ed25519.sign(r,t),o=new Uint8Array(E.RCPT_TOTAL_LEN);return o.set(r,0),o.set(i,E.RCPT_SIGNED_LEN),o}function ha(e){if(e.length!==E.RCPT_TOTAL_LEN)throw new Error(`receipt must be ${E.RCPT_TOTAL_LEN} bytes, got ${e.length}`);if(!ei(e.subarray(0,4),E.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 i=e.slice(n,n+32);n+=32;let o=e.slice(n,n+32);n+=32;let a=e[n];n+=1;let s=Number(t.getBigUint64(n,!1));n+=8;let c=Qr(o);if(c===null)throw new Error("receipt dest_jkt must not be zero");return{fields:{version:r,pveHash:i,destJkt:c,absorbStatus:a,absorbedAt:s},signedBytes:e.slice(0,E.RCPT_SIGNED_LEN),destSig:e.slice(E.RCPT_SIGNED_LEN,E.RCPT_TOTAL_LEN)}}function cu(e,t,n){let r;try{r=ha(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(r.fields.version!==E.RCPT_VERSION)return{ok:!1,code:"bad_version",reason:`unsupported receipt version ${r.fields.version}`};let i;try{i=Ct(t)}catch(o){return{ok:!1,code:"malformed",reason:o instanceof Error?o.message:String(o)}}return i!==r.fields.destJkt?{ok:!1,code:"jkt_mismatch",reason:`presented key thumbprint ${i.slice(0,12)}\u2026 \u2260 committed dest_jkt ${r.fields.destJkt.slice(0,12)}\u2026`}:n!==void 0&&!ei(n,r.fields.pveHash)?{ok:!1,code:"pve_hash_mismatch",reason:"receipt does not acknowledge the expected PVE"}:Tn.ed25519.verify(r.destSig,r.signedBytes,t)?{ok:!0,parsed:r}:{ok:!1,code:"signature_invalid",reason:"Ed25519 destination signature does not verify"}}});var ya=N(Nt=>{"use strict";Object.defineProperty(Nt,"__esModule",{value:!0});Nt.stepRatchet=lu;Nt.replayRatchet=du;Nt.destroyKey=uu;var ga=at();function lu(e,t){if(t.length!==32)throw new Error(`ratchet token must be 32 bytes, got ${t.length}`);return{nextContentKey:(0,ga.ratchetAdvance)(e.contentKey,t),openCount:e.openCount+1}}function du(e,t){let n=[e],r=e;for(let i of t)r=(0,ga.ratchetAdvance)(r,i),n.push(r);return n}function uu(e){e.fill(0)}});var ri=N(lt=>{"use strict";Object.defineProperty(lt,"__esModule",{value:!0});lt.__coseInternals=void 0;lt.verifyCoseSign1Es384=hu;lt.decodeAttestationPayload=mu;var pu=P("@noble/curves/nist.js"),fu=P("@noble/hashes/sha2.js"),ti=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 i=this.len(r),o=this.b.subarray(this.p,this.p+i);if(o.length!==i)throw new Error("cbor: bstr truncated");return this.p+=i,o.slice()}case 3:{let i=this.len(r),o=this.b.subarray(this.p,this.p+i);if(o.length!==i)throw new Error("cbor: tstr truncated");return this.p+=i,new TextDecoder("utf-8").decode(o)}case 4:{let i=this.len(r),o=[];for(let a=0;a<i;a++)o.push(this.read());return o}case 5:{let i=this.len(r),o=new Map;for(let a=0;a<i;a++){let s=this.read(),c=this.read();o.set(s,c)}return o}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 ni(e){return new ti(e).read()}function In(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 $n(...e){let t=e.reduce((i,o)=>i+o.length,0),n=new Uint8Array(t),r=0;for(let i of e)n.set(i,r),r+=i.length;return n}function Pn(e){return $n(In(2,e.length),e)}function _a(e){let t=new TextEncoder().encode(e);return $n(In(3,t.length),t)}function ba(e,t){return $n(In(4,4),_a("Signature1"),Pn(e),Pn(new Uint8Array(0)),Pn(t))}function hu(e,t){let n;try{n=ni(e)}catch(l){return{ok:!1,code:"malformed",reason:`cbor decode failed: ${l.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,,i,o]=n;if(!(r instanceof Uint8Array))return{ok:!1,code:"bad_structure",reason:"protected header must be a byte string"};if(!(i instanceof Uint8Array)||i.length===0)return{ok:!1,code:"no_payload",reason:"detached/empty payload is not supported"};if(!(o instanceof Uint8Array))return{ok:!1,code:"bad_structure",reason:"signature must be a byte string"};if(o.length!==96)return{ok:!1,code:"bad_signature_len",reason:`expected 96-byte ES384 sig, got ${o.length}`};let a=ba(r,i),s=(0,fu.sha384)(a),c=!1;try{c=pu.p384.verify(o,s,t,{prehash:!1})}catch(l){return{ok:!1,code:"signature_invalid",reason:`verify threw: ${l.message}`}}return c?{ok:!0,payload:i}:{ok:!1,code:"signature_invalid",reason:"ECDSA P-384 verification failed"}}function mu(e){try{let t=ni(e);return t instanceof Map?t:null}catch{return null}}lt.__coseInternals={sig1Structure:ba,encBstr:Pn,encText:_a,encHead:In,concat:$n,decodeCbor:ni}});var va=N(Ot=>{"use strict";Object.defineProperty(Ot,"__esModule",{value:!0});Ot.parseAttestation=yu;Ot.verifyAttestation=_u;Ot.fetchAttestation=bu;var gu=ri();function yu(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 _u(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[o,a]of Object.entries(t.pcrs))if(e.pcrs[o]!==a)return{ok:!1,code:"pcr_mismatch",reason:`PCR ${o}: got '${(e.pcrs[o]??"").slice(0,16)}\u2026', expected '${a.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 i=!1;if(t.cose){if(!t.trustedLeafPubKey)return{ok:!1,code:"signature_invalid",reason:"cose supplied without trustedLeafPubKey \u2014 cannot verify, refusing"};let o=(0,gu.verifyCoseSign1Es384)(t.cose,t.trustedLeafPubKey);if(!o.ok)return{ok:!1,code:"signature_invalid",reason:`cose: ${o.code}: ${o.reason}`};i=!0}return{ok:!0,vendor:e.vendor,module_id:e.module_id,signature_verified:i}}async function bu(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 wa=N(dt=>{"use strict";Object.defineProperty(dt,"__esModule",{value:!0});dt.splitSecret=wu;dt.combineShares=Eu;dt.serializeShare=Tu;dt.deserializeShare=Pu;var Ue=null,Ve=null;function ka(){if(Ue&&Ve)return;Ue=new Uint8Array(512),Ve=new Uint8Array(256);let e=1;for(let t=0;t<255;t++){Ue[t]=e,Ve[e]=t;let n=e<<1;n&256&&(n^=283),n^=e,e=n&255}for(let t=255;t<512;t++)Ue[t]=Ue[t-255]}function Rn(e,t){return e===0||t===0?0:(ka(),Ue[Ve[e]+Ve[t]])}function vu(e,t){if(e===0)return 0;if(t===0)throw new Error("division by zero in GF(2^8)");ka();let n=Ve[e]-Ve[t];return Ue[n<0?n+255:n]}function Sa(e,t){return e^t}function ku(e,t){let n=0;for(let r=e.length-1;r>=0;r--)n=Sa(Rn(n,t),e[r]);return n}var Su=e=>crypto.getRandomValues(new Uint8Array(e));function wu(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??Su,r=[];for(let i=1;i<=t.n;i++)r.push({x:i,y:new Uint8Array(e.length)});for(let i=0;i<e.length;i++){let o=new Uint8Array(t.k);o[0]=e[i];let a=n(t.k-1);for(let s=1;s<t.k;s++)o[s]=a[s-1];for(let s=0;s<t.n;s++)r[s].y[i]=ku(o,r[s].x)}return r}function Eu(e){if(e.length<2)throw new Error("need at least 2 shares to reconstruct");let t=e[0].y.length;for(let i of e){if(i.y.length!==t)throw new Error("shares have inconsistent length");if(i.x===0)throw new Error("share x must not be 0")}let n=new Set;for(let i of e){if(n.has(i.x))throw new Error(`duplicate share x=${i.x}`);n.add(i.x)}let r=new Uint8Array(t);for(let i=0;i<t;i++){let o=0;for(let a=0;a<e.length;a++){let s=1,c=1;for(let u=0;u<e.length;u++)a!==u&&(s=Rn(s,e[u].x),c=Rn(c,e[a].x^e[u].x));let l=vu(s,c);o=Sa(o,Rn(e[a].y[i],l))}r[i]=o}return r}var xu=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)},Au=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 Tu(e){return{x:e.x,y_b64:xu(e.y)}}function Pu(e){return{x:e.x,y:Au(e.y_b64)}}});var Ta=N(Ae=>{"use strict";Object.defineProperty(Ae,"__esModule",{value:!0});Ae.SegmentError=void 0;Ae.sealSegments=Cu;Ae.openSegments=Nu;Ae.manifestDigest=Ou;Ae.buildCapability=ju;var ii=P("@noble/hashes/sha2.js"),Iu="pq-hybrid-segments",$u="AES-256-GCM",ut=e=>e,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)},xa=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},Aa=e=>{let t="";for(let n=0;n<e.length;n++)t+=e[n].toString(16).padStart(2,"0");return t};async function Ru(e,t,n){let r=await crypto.subtle.importKey("raw",ut(e),{name:"AES-GCM"},!1,["encrypt"]),i=await crypto.subtle.encrypt({name:"AES-GCM",iv:ut(t)},r,ut(n));return new Uint8Array(i)}async function Du(e,t,n){let r=await crypto.subtle.importKey("raw",ut(e),{name:"AES-GCM"},!1,["decrypt"]),i=await crypto.subtle.decrypt({name:"AES-GCM",iv:ut(t)},r,ut(n));return new Uint8Array(i)}var Ge=class extends Error{constructor(t,n){super(n),this.name="SegmentError",this.code=t}};Ae.SegmentError=Ge;async function Cu(e){let t=new Set;for(let i of e){if(t.has(i.segment_id))throw new Ge("duplicate_segment_id",`segment_id '${i.segment_id}' appears twice`);t.add(i.segment_id)}let n=[],r=[];for(let i of e){let o=crypto.getRandomValues(new Uint8Array(32)),a=crypto.getRandomValues(new Uint8Array(12)),s=await Ru(o,a,i.plaintext),c=s.slice(0,s.length-16),l=Aa((0,ii.sha256)(c));n.push({segment_id:i.segment_id,key:o}),r.push({segment_id:i.segment_id,label:i.label,content_type:i.content_type,iv_b64:Ea(a),ciphertext_b64:Ea(s),ciphertext_sha256:l})}return{manifest:{profile:Iu,aead:$u,segments:r},keys:n}}async function Nu(e,t){let n=new Map;for(let i of t.keys)n.set(i.segment_id,i.key);let r=[];for(let i of e.segments){if(!t.allowed_segment_ids.includes(i.segment_id))continue;let o=n.get(i.segment_id);if(!o)throw new Ge("key_missing",`capability lists ${i.segment_id} as allowed but holds no key for it`);let a=xa(i.ciphertext_b64),s=a.slice(0,a.length-16);if(Aa((0,ii.sha256)(s))!==i.ciphertext_sha256)throw new Ge("integrity_mismatch",`segment ${i.segment_id}: ciphertext sha256 mismatch`);let l=xa(i.iv_b64),u=await Du(o,l,a);r.push({segment_id:i.segment_id,label:i.label,content_type:i.content_type,plaintext:u})}return r}function Ou(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,ii.sha256)(new TextEncoder().encode(n))}function ju(e,t,n){let r=new Set(t),i=n.filter(o=>r.has(o.segment_id));if(i.length!==t.length){let o=t.filter(a=>!i.find(s=>s.segment_id===a));throw new Ge("segment_not_found",`cannot build capability \u2014 no key for: ${o.join(", ")}`)}return{recipient_kid:e,allowed_segment_ids:t,keys:i}}});var $a=N(jt=>{"use strict";Object.defineProperty(jt,"__esModule",{value:!0});jt.computeWatermark=Ia;jt.findLeakSource=Lu;jt.watermarkSvgOverlay=Mu;var Bu=P("@noble/hashes/hmac.js"),Fu=P("@noble/hashes/sha2.js");function Ia(e){let t=[e.recipientId,e.lockboxId,String(e.openCount),String(e.iat)].join("|"),n=(0,Bu.hmac)(Fu.sha256,e.tenantSecret,new TextEncoder().encode(t)),r=Pa(n.slice(0,16)),i=Pa(n.slice(0,4)),o=new Date(e.iat*1e3).toISOString().slice(0,10),a=`${e.recipientId} \xB7 ${o} \xB7 ${i}`;return{short_hex:i,full_hex:r,display_label:a}}function Lu(e,t,n){let r=e.toLowerCase();for(let i of n){let o=Ia({tenantSecret:t,...i});if(r===o.full_hex)return{matched:!0,candidate:i,matched_on:"full_hex"};if(r===o.short_hex)return{matched:!0,candidate:i,matched_on:"short_hex"}}return{matched:!1,reason:"no_candidate_matched"}}function Mu(e,t){let n=t?.width??800,r=t?.height??1e3,i=t?.opacity??.1,a=(s=>s.replace(/[<>&"]/g,c=>({"<":"<",">":">","&":"&",'"':"""})[c]))(e.display_label);return`<svg xmlns="http://www.w3.org/2000/svg" width="${n}" height="${r}" pointer-events="none">
|
|
4
|
+
var _l=Object.create;var yo=Object.defineProperty;var bl=Object.getOwnPropertyDescriptor;var vl=Object.getOwnPropertyNames;var kl=Object.getPrototypeOf,wl=Object.prototype.hasOwnProperty;var D=(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 Sl=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of vl(t))!wl.call(e,i)&&i!==n&&yo(e,i,{get:()=>t[i],enumerable:!(r=bl(t,i))||r.enumerable});return e};var xr=(e,t,n)=>(n=e!=null?_l(kl(e)):{},Sl(t||!e||!e.__esModule?yo(n,"default",{value:e,enumerable:!0}):n,e));var Wr=O(re=>{"use strict";Object.defineProperty(re,"__esModule",{value:!0});re.MAX_SEALED_BYTES=void 0;re.kidForPublicKey=oa;re.deriveKeyPairFromSeed=Nd;re.generateSeed=Od;re.buildEnvInfo=jd;re.sealDek=Ld;re.openSealedDek=Bd;re.decodeSealHeader=aa;var na=D("crypto"),ta=D("@hpke/core"),Pd=D("@hpke/dhkem-x25519"),$d=D("@hpke/chacha20poly1305"),Rd=D("@noble/curves/ed25519.js"),Dd=D("@noble/hashes/hkdf.js"),Cd=D("@noble/hashes/sha2.js"),Cn=new ta.CipherSuite({kem:new Pd.DhkemX25519HkdfSha256,kdf:new ta.HkdfSha256,aead:new $d.Chacha20Poly1305}),ra=1,ia=1;re.MAX_SEALED_BYTES=4096;function oa(e){return(0,na.createHash)("sha256").update(e).digest("hex").slice(0,16)}function Nd(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,Dd.hkdf)(Cd.sha256,e,new Uint8Array(0),t,32)),r=Buffer.from(Rd.x25519.scalarMultBase(n));return{secretKey:n,publicKey:r,kid:oa(r)}}function Od(){return(0,na.randomBytes)(32)}function jd(e){return Buffer.from(`protect.env.v3|${e}`,"utf8")}async function Ld(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 Cn.kem.deserializePublicKey(Ve(t)),i=await Cn.createSenderContext({recipientPublicKey:r,info:Ve(n)}),o=Buffer.from(await i.seal(Ve(e),new ArrayBuffer(0))),a=Buffer.from(i.enc),s=Buffer.alloc(6+a.length+o.length);return s[0]=ra,s[1]=ia,s.writeUInt16BE(a.length,2),s.writeUInt16BE(o.length,4),a.copy(s,6),o.copy(s,6+a.length),s}async function Bd(e,t,n){let r=aa(e),i=e.subarray(6,6+r.encLen),o=e.subarray(6+r.encLen),a=await Cn.kem.deserializePrivateKey(Ve(t)),s=await Cn.createRecipientContext({recipientKey:a,enc:Ve(i),info:Ve(n)});return Buffer.from(await s.open(Ve(o)))}function aa(e){if(e.length<6)throw new Error("sealed bytes too short");if(e.length>re.MAX_SEALED_BYTES)throw new Error("sealed bytes too long");let t=e[0],n=e[1];if(t!==ra)throw new Error(`unsupported seal version 0x${t.toString(16)}`);if(n!==ia)throw new Error(`unsupported HPKE suite 0x${n.toString(16)}`);let r=e.readUInt16BE(2),i=e.readUInt16BE(4);if(e.length!==6+r+i)throw new Error("sealed length mismatch");if(r!==32)throw new Error("unexpected KEM enc length (X25519 is 32 bytes)");if(i<16)throw new Error("ciphertext shorter than the AEAD tag");return{ver:t,suite:n,encLen:r,ctLen:i}}function Ve(e){return e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength)}});var ca=O(we=>{"use strict";Object.defineProperty(we,"__esModule",{value:!0});we.V3_PREFIX=void 0;we.sealValue=Fd;we.formatToken=Md;we.parseToken=sa;we.openValue=Kd;var Nn=D("crypto"),On=Wr();we.V3_PREFIX="aes256gcm:v3:";async function Fd(e,t){let n=(0,Nn.randomBytes)(32),r=(0,Nn.randomBytes)(12),i=(0,Nn.createCipheriv)("aes-256-gcm",n,r),o=Buffer.concat([i.update(e,"utf8"),i.final()]),a=Buffer.concat([o,i.getAuthTag()]),s=await(0,On.sealDek)(n,t.publicKey,(0,On.buildEnvInfo)(t.kid));return n.fill(0),{sealedDekB64:s.toString("base64"),iv:r,cipher:a}}function Md(e,t){return`${we.V3_PREFIX}${e.iv.toString("base64")}:${e.cipher.toString("base64")}:${t}`}function sa(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,i]=t;if(!i)throw new Error("v3 token has no seal id");let o=Buffer.from(n,"base64"),a=Buffer.from(r,"base64");if(o.length!==12)throw new Error("v3 token has a malformed iv");if(a.length<17)throw new Error("v3 token ciphertext is too short");return{iv:o,cipher:a,sealId:i}}async function Kd(e,t,n){let{iv:r,cipher:i}=sa(e),o=await(0,On.openSealedDek)(Buffer.from(t,"base64"),n.secretKey,(0,On.buildEnvInfo)(n.kid)),a=i.subarray(i.length-16),s=i.subarray(0,i.length-16),c=(0,Nn.createDecipheriv)("aes-256-gcm",o,r);c.setAuthTag(a);try{return Buffer.concat([c.update(s),c.final()]).toString("utf8")}finally{o.fill(0)}}});var pa=O(X=>{"use strict";var Hd=X&&X.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);(!i||("get"in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),Ud=X&&X.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),qr=X&&X.__importStar||(function(){var e=function(t){return e=Object.getOwnPropertyNames||function(n){var r=[];for(var i in n)Object.prototype.hasOwnProperty.call(n,i)&&(r[r.length]=i);return r},e(t)};return function(t){if(t&&t.__esModule)return t;var n={};if(t!=null)for(var r=e(t),i=0;i<r.length;i++)r[i]!=="default"&&Hd(n,t,r[i]);return Ud(n,t),n}})();Object.defineProperty(X,"__esModule",{value:!0});X.deviceKeyPath=Gd;X.hasDeviceKey=Wd;X.loadDeviceKey=zd;X.createDeviceKey=qd;X.importDeviceKey=Jd;X.exportSeedHex=Xd;X.deviceKeyIsExposed=Yd;var ee=qr(D("fs")),Vd=qr(D("os")),la=qr(D("path")),Ct=Wr(),zr=la.join(Vd.homedir(),".nodata"),G=la.join(zr,"device-key.json");function Gd(){return G}function da(){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 Wd(){return da()!==null||ee.existsSync(G)}function zd(){let e=da();if(e)return(0,Ct.deriveKeyPairFromSeed)(e);if(!ee.existsSync(G))return null;let t;try{t=JSON.parse(ee.readFileSync(G,"utf-8"))}catch{throw new Error(`Device key file is unreadable: ${G}`)}if(!t.seed_hex||!/^[0-9a-f]{64}$/i.test(t.seed_hex))throw new Error(`Device key file is malformed (bad seed): ${G}`);let n=(0,Ct.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 qd(e={}){if(ee.existsSync(G)&&!e.force)throw new Error(`A device key already exists at ${G}. Replacing it makes every existing v3 seal unopenable. Back up the seed first (nodata key export), then pass --force.`);let t=(0,Ct.generateSeed)(),n=(0,Ct.deriveKeyPairFromSeed)(t);return ua(t,n),n}function Jd(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(ee.existsSync(G)&&!t.force)throw new Error(`A device key already exists at ${G}. Pass --force to replace it.`);let r=Buffer.from(n,"hex"),i=(0,Ct.deriveKeyPairFromSeed)(r);return ua(r,i),i}function Xd(){if(!ee.existsSync(G))throw new Error("No device key file to export.");return JSON.parse(ee.readFileSync(G,"utf-8")).seed_hex}function ua(e,t){ee.existsSync(zr)||ee.mkdirSync(zr,{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()};ee.writeFileSync(G,JSON.stringify(n,null,2)+`
|
|
5
|
+
`,{mode:384});try{ee.chmodSync(G,384)}catch{}}function Yd(){if(process.platform==="win32"||!ee.existsSync(G))return!1;try{return(ee.statSync(G).mode&63)!==0}catch{return!1}}});var Zr=O(te=>{"use strict";var Zd=te&&te.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);(!i||("get"in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),Qd=te&&te.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),fa=te&&te.__importStar||(function(){var e=function(t){return e=Object.getOwnPropertyNames||function(n){var r=[];for(var i in n)Object.prototype.hasOwnProperty.call(n,i)&&(r[r.length]=i);return r},e(t)};return function(t){if(t&&t.__esModule)return t;var n={};if(t!=null)for(var r=e(t),i=0;i<r.length;i++)r[i]!=="default"&&Zd(n,t,r[i]);return Qd(n,t),n}})();Object.defineProperty(te,"__esModule",{value:!0});te.ensureDeviceKey=eu;te.sealFile=tu;te.readManifest=ha;te.openFile=nu;te.writeLocalReceipt=ru;var Jr=D("crypto"),xe=D("fs"),Nt=D("path"),Xr=fa(ca()),Yr=fa(pa());function eu(){let e=Yr.loadDeviceKey();return e?{key:e,created:!1}:{key:Yr.createDeviceKey(),created:!0}}async function tu(e,t,n){let r=(0,xe.readFileSync)(e),i=(0,Jr.createHash)("sha256").update(r).digest("hex"),o=n??"local-"+(0,Jr.randomUUID)(),a=await Xr.sealValue(r.toString("base64"),t),s={v:3,alg:"aes256gcm:v3",kid:t.kid,orig:(0,Nt.basename)(e),enc:"base64",token:Xr.formatToken(a,o),sealed_dek:a.sealedDekB64,sha256:i,sealed_at:new Date().toISOString()},c=e+".ndc";return(0,xe.writeFileSync)(c,JSON.stringify(s,null,2)+`
|
|
6
|
+
`,{mode:384}),{path:e,ndc:c,sha256:i,sealId:o}}function ha(e){try{let t=JSON.parse((0,xe.readFileSync)(e,"utf8"));return t.alg==="aes256gcm:v3"&&t.token&&t.sealed_dek?t:null}catch{return null}}async function nu(e,t){if(!(0,xe.existsSync)(e))return{ok:!1,error:"not_found"};let n=ha(e);if(!n)return{ok:!1,error:"not_a_seal"};let r=t===void 0?Yr.loadDeviceKey():t;if(!r)return{ok:!1,error:"no_device_key"};let i;try{i=await Xr.openValue(n.token,n.sealed_dek,r)}catch{return{ok:!1,error:"wrong_key"}}let o=Buffer.from(i,"base64"),a=e.endsWith(".ndc")?e.slice(0,-4):e+".opened";(0,xe.existsSync)(a)&&(a=a+".opened"),(0,xe.writeFileSync)(a,o);let s=(0,Jr.createHash)("sha256").update(o).digest("hex")===n.sha256;return{ok:!0,outPath:a,sha256:n.sha256,intact:s}}function ru(e,t){let n=(0,Nt.join)(e,".nodata","receipts");(0,xe.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(o=>({path:(0,Nt.relative)(e,o.path),sha256:o.sha256,seal_id:o.sealId,sealed:(0,Nt.basename)(o.ndc)})),...t.extra??{}},i=(0,Nt.join)(n,`${t.action}-${Date.now()}.json`);return(0,xe.writeFileSync)(i,JSON.stringify(r,null,2)+`
|
|
7
|
+
`),i}});var We=O(di=>{"use strict";Object.defineProperty(di,"__esModule",{value:!0});var Ht=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"]),i=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!0,["encrypt","decrypt"]),o=crypto.getRandomValues(new Uint8Array(12)),a=new TextEncoder().encode(t),s=await crypto.subtle.encrypt({name:"AES-GCM",iv:o,tagLength:128},i,a),c=await crypto.subtle.exportKey("raw",i),l=await crypto.subtle.encrypt({name:"RSA-OAEP"},r,c);return{encrypted_blob:this.arrayBufferToBase64(s),encrypted_aes_key:this.arrayBufferToBase64(l),iv:this.arrayBufferToBase64(o)}}static async decryptMessage(t,n){let r=await crypto.subtle.importKey("jwk",n,{name:"RSA-OAEP",hash:"SHA-256"},!1,["decrypt"]),i=this.base64ToArrayBuffer(t.encrypted_aes_key),o=await crypto.subtle.decrypt({name:"RSA-OAEP"},r,i),a=await crypto.subtle.importKey("raw",o,{name:"AES-GCM",length:256},!1,["decrypt"]),s=this.base64ToArrayBuffer(t.iv),c=this.base64ToArrayBuffer(t.encrypted_blob),l=await crypto.subtle.decrypt({name:"AES-GCM",iv:s,tagLength:128},a,c);return new TextDecoder().decode(l)}static async encryptFile(t,n){let r=await t.arrayBuffer(),i=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!0,["encrypt","decrypt"]),o=crypto.getRandomValues(new Uint8Array(12)),a=await crypto.subtle.encrypt({name:"AES-GCM",iv:o,tagLength:128},i,r),s=JSON.stringify({name:t.name,type:t.type,size:t.size,lastModified:t.lastModified}),c=crypto.getRandomValues(new Uint8Array(12)),l=await crypto.subtle.encrypt({name:"AES-GCM",iv:c,tagLength:128},i,new TextEncoder().encode(s)),p=await crypto.subtle.importKey("jwk",n,{name:"RSA-OAEP",hash:"SHA-256"},!1,["encrypt"]),u=await crypto.subtle.exportKey("raw",i),f=await crypto.subtle.encrypt({name:"RSA-OAEP"},p,u);return{encrypted_file:this.arrayBufferToBase64(a),encrypted_file_key:this.arrayBufferToBase64(f),iv:this.arrayBufferToBase64(o),encrypted_metadata:this.arrayBufferToBase64(l),metadata_iv:this.arrayBufferToBase64(c),encrypted_size:a.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 i=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},i,{name:"AES-GCM",length:256},!0,["encrypt","decrypt"])}static async encryptWithDerivedKey(t,n){let r=crypto.getRandomValues(new Uint8Array(12)),i=new TextEncoder().encode(t),o=await crypto.subtle.encrypt({name:"AES-GCM",iv:r,tagLength:128},n,i);return{encrypted:this.arrayBufferToBase64(o),iv:this.arrayBufferToBase64(r)}}static async decryptWithDerivedKey(t,n,r){let i=this.base64ToArrayBuffer(t),o=this.base64ToArrayBuffer(n),a=await crypto.subtle.decrypt({name:"AES-GCM",iv:o,tagLength:128},r,i);return new TextDecoder().decode(a)}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(i=>i.toString(16).padStart(2,"0")).join("")}static async encryptFileWithDerivedKey(t,n){let r=await t.arrayBuffer(),i=await this.sha256Hex(r),o=crypto.getRandomValues(new Uint8Array(12)),a=await crypto.subtle.encrypt({name:"AES-GCM",iv:o,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)),l=await crypto.subtle.encrypt({name:"AES-GCM",iv:c,tagLength:128},n,new TextEncoder().encode(s));return{encrypted_file:this.arrayBufferToBase64(a),iv:this.arrayBufferToBase64(o),encrypted_metadata:this.arrayBufferToBase64(l),metadata_iv:this.arrayBufferToBase64(c),encrypted_size:a.byteLength,plaintext_sha256:i,ciphertext_sha256:await this.sha256Hex(a)}}static async decryptFileBytesWithDerivedKey(t,n,r){let i=this.base64ToArrayBuffer(n);return crypto.subtle.decrypt({name:"AES-GCM",iv:i,tagLength:128},r,t)}static async decryptFileWithDerivedKey(t,n,r){let i=this.base64ToArrayBuffer(t),o=this.base64ToArrayBuffer(n);return crypto.subtle.decrypt({name:"AES-GCM",iv:o,tagLength:128},r,i)}static async deriveSeedKey(t,n="SHA-512"){let r=t.trim().toLowerCase(),i=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},i,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}static async exportKeyWithSeed(t,n){let r=await crypto.subtle.exportKey("jwk",t),i=new TextEncoder().encode(JSON.stringify(r)),o=crypto.getRandomValues(new Uint8Array(12)),a=await crypto.subtle.encrypt({name:"AES-GCM",iv:o,tagLength:128},n,i),s=new Uint8Array(o.byteLength+a.byteLength);return s.set(o,0),s.set(new Uint8Array(a),o.byteLength),s.buffer}static async importKeyWithSeed(t,n){let r=new Uint8Array(t),i=r.slice(0,12),o=r.slice(12),a=await crypto.subtle.decrypt({name:"AES-GCM",iv:i,tagLength:128},n,o),s=new TextDecoder().decode(a),c=JSON.parse(s),l=await crypto.subtle.importKey("jwk",c,{name:"RSA-OAEP",hash:"SHA-256"},!0,["decrypt"]);return new Uint8Array(a).fill(0),l}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(i=>i.toString(16).padStart(2,"0")).join("")}static arrayBufferToBase64(t){let n=new Uint8Array(t),r=32768,i=[];for(let o=0;o<n.length;o+=r)i.push(String.fromCharCode(...n.subarray(o,o+r)));return btoa(i.join(""))}static async encryptFileToBytesWithDerivedKey(t,n){let r=await t.arrayBuffer(),i=await this.sha256Hex(r),o=crypto.getRandomValues(new Uint8Array(12)),a=await crypto.subtle.encrypt({name:"AES-GCM",iv:o,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)),l=await crypto.subtle.encrypt({name:"AES-GCM",iv:c,tagLength:128},n,new TextEncoder().encode(s));return{ciphertext:a,iv:this.arrayBufferToBase64(o),encrypted_metadata:this.arrayBufferToBase64(l),metadata_iv:this.arrayBufferToBase64(c),encrypted_size:a.byteLength,plaintext_sha256:i,ciphertext_sha256:await this.sha256Hex(a)}}static base64ToArrayBuffer(t){let n=atob(t),r=new Uint8Array(n.length);for(let i=0;i<n.length;i++)r[i]=n.charCodeAt(i);return r.buffer}static wipeFromMemory(t){new Uint8Array(t).fill(0)}};Ht.PBKDF2_ITERATIONS=31e4;Ht.SEED_SALT="NoDataChat-Seed-v1";di.default=Ht});var za=O(Kn=>{"use strict";Object.defineProperty(Kn,"__esModule",{value:!0});Kn.solveProofOfWork=Nu;Kn.verifyProofOfWork=Ou;function Cu(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 Wa(e){let t=new TextEncoder().encode(e),n=await crypto.subtle.digest("SHA-256",t);return Cu(n)}async function Nu(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 i=e+r.toString(),o=await Wa(i);if(o.startsWith(n))return{nonce:r,hash:o};if(r++,r>2e9)throw new Error("Proof of work exceeded maximum attempts")}}async function Ou(e,t,n=4){if(n<1||n>16)return!1;let r="0".repeat(n),i=e+t.toString();return(await Wa(i)).startsWith(r)}});var pi=O(ut=>{"use strict";var ju=ut&&ut.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(ut,"__esModule",{value:!0});ut.NoDataEmail=void 0;var me=ju(We()),ui=class{static async seal(t,n,r,i,o,a={}){let{encrypt_subject:s=!0,ttl_hours:c=72,attachments:l=[]}=a,p=await me.default.encryptMessage(i,o),u=r,f=!1;if(s){let _=await me.default.encryptMessage(r,o);u=JSON.stringify(_),f=!0}let h=[];for(let _ of l){let y=await me.default.encryptFile(_,o);h.push({encrypted_file:y})}return{from_alias:t,to:n,subject:u,subject_encrypted:f,body:p,attachments:h,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 me.default.decryptMessage(t.body,n),i=t.subject;if(t.subject_encrypted){let a=JSON.parse(t.subject);i=await me.default.decryptMessage(a,n)}let o=[];for(let a of t.attachments){let{encrypted_file:s}=a,c=me.default.base64ToArrayBuffer(s.metadata_iv),l=me.default.base64ToArrayBuffer(s.encrypted_metadata),p=me.default.base64ToArrayBuffer(s.encrypted_file_key),u=await crypto.subtle.importKey("jwk",n,{name:"RSA-OAEP",hash:"SHA-256"},!1,["decrypt"]),f=await crypto.subtle.decrypt({name:"RSA-OAEP"},u,p),h=await crypto.subtle.importKey("raw",f,{name:"AES-GCM",length:256},!1,["decrypt"]),_=await crypto.subtle.decrypt({name:"AES-GCM",iv:c,tagLength:128},h,l),y=JSON.parse(new TextDecoder().decode(_)),v=me.default.base64ToArrayBuffer(s.iv),S=me.default.base64ToArrayBuffer(s.encrypted_file),w=await crypto.subtle.decrypt({name:"AES-GCM",iv:v,tagLength:128},h,S);o.push({filename:y.name,mime_type:y.type,data:w,size:y.size})}return{subject:i,body:r,attachments:o,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),i=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 — 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"',"",i,"--nodata-boundary--"].join(`\r
|
|
8
|
+
`)}};ut.NoDataEmail=ui});var mi=O(pt=>{"use strict";var Lu=pt&&pt.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(pt,"__esModule",{value:!0});pt.NoDataWebhook=void 0;var fi=Lu(We()),hi=class{static async encrypt(t,n,r,i){let{event_type:o,source:a,ttl_seconds:s=3600}=i,c=JSON.stringify(t),l=await fi.default.encryptMessage(c,n),p=new Date().toISOString(),u=crypto.randomUUID(),f=`${u}.${p}.${l.encrypted_blob}`,h=await this.hmacSign(f,r);return{encrypted_event:l,event_type:o,source:a,signature:h,timestamp:p,delivery_id:u,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}`,i=await this.hmacSign(r,n),o=new TextEncoder().encode(t.signature),a=new TextEncoder().encode(i),s=o.length^a.length,c=Math.min(o.length,a.length);for(let h=0;h<c;h++)s|=o[h]^a[h];let l=s===0,u=new Date(t.timestamp).getTime()+t.ttl_seconds*1e3,f=Date.now()>u;return{valid:l,expired:f,event_type:t.event_type,source:t.source,delivery_id:t.delivery_id}}static async decrypt(t,n){let r=await fi.default.decryptMessage(t.encrypted_event,n);return JSON.parse(r)}static async verifyAndDecrypt(t,n,r){let i=await this.verify(t,r);if(!i.valid)throw new Error(`[NoDataWebhook] Invalid signature for delivery ${i.delivery_id}`);if(i.expired)throw new Error(`[NoDataWebhook] Payload expired for delivery ${i.delivery_id}`);return{data:await this.decrypt(t,n),delivery_id:i.delivery_id,event_type:i.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"]),i=await crypto.subtle.sign("HMAC",r,new TextEncoder().encode(t));return fi.default.arrayBufferToBase64(i)}};pt.NoDataWebhook=hi});var yi=O(ft=>{"use strict";var Bu=ft&&ft.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(ft,"__esModule",{value:!0});ft.NoDataSystems=void 0;var Hn=Bu(We()),gi=class{static async encryptRecord(t,n,r,i,o,a){let s=[],c={};for(let[l,p]of Object.entries(r))if(i.sensitive.includes(l)){let u=typeof p=="string"?p:JSON.stringify(p),f=await Hn.default.encryptMessage(u,o),h=await this.hashValue(u);s.push({value:f,search_hash:h,field_name:l,encrypted_at:new Date().toISOString()})}else c[l]=p;return{record_id:t,record_type:n,encrypted_fields:s,clear_fields:c,encrypted_by:a,created_at:new Date().toISOString(),crypto_version:"0.2.0"}}static async decryptRecord(t,n){let r={...t.clear_fields};for(let i of t.encrypted_fields){let o=await Hn.default.decryptMessage(i.value,n);try{r[i.field_name]=JSON.parse(o)}catch{r[i.field_name]=o}}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 i=await this.hashValue(r);return t.filter(o=>o.encrypted_fields.some(a=>a.field_name===n&&a.search_hash===i))}static async encryptField(t,n,r){let i=typeof n=="string"?n:JSON.stringify(n),o=await Hn.default.encryptMessage(i,r),a=await this.hashValue(i);return{value:o,search_hash:a,field_name:t,encrypted_at:new Date().toISOString()}}static async decryptField(t,n){let r=await Hn.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),i=await crypto.subtle.digest("SHA-256",r);return Array.from(new Uint8Array(i)).map(o=>o.toString(16).padStart(2,"0")).join("")}};ft.NoDataSystems=gi});var bi=O(ht=>{"use strict";var Fu=ht&&ht.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(ht,"__esModule",{value:!0});ht.NoDataForms=void 0;var ge=Fu(We()),_i=class{static async encryptSubmission(t,n,r,i,o={}){let{ttl_hours:a=0,view_once:s=!1,attachments:c=[]}=o,l={},p={};for(let v of n)v.sensitive!==!1?l[v.name]=v.value:p[v.name]=v.value;let u=JSON.stringify(n.map(v=>({name:v.name,value:v.value}))),f=await this.sha256(u),h=await ge.default.encryptMessage(JSON.stringify(l),r),_=[];for(let v of c){let S=await ge.default.encryptFile(v,r);_.push(S)}let y=n.map(v=>v.name);return{submission_id:crypto.randomUUID(),form_id:t,encrypted_fields:h,clear_fields:p,attachments:_,integrity_hash:f,field_order:y,submitter_id:i,submitted_at:new Date().toISOString(),ttl_hours:a,view_once:s,crypto_version:"0.2.0"}}static async decryptSubmission(t,n){let r=await ge.default.decryptMessage(t.encrypted_fields,n),i=JSON.parse(r),o={...t.clear_fields,...i},s=(t.field_order||Object.keys(o).sort()).map(u=>({name:u,value:o[u]})),l=await this.sha256(JSON.stringify(s))===t.integrity_hash,p=[];for(let u of t.attachments){let f=await crypto.subtle.importKey("jwk",n,{name:"RSA-OAEP",hash:"SHA-256"},!1,["decrypt"]),h=await crypto.subtle.decrypt({name:"RSA-OAEP"},f,ge.default.base64ToArrayBuffer(u.encrypted_file_key)),_=await crypto.subtle.importKey("raw",h,{name:"AES-GCM",length:256},!1,["decrypt"]),y=await crypto.subtle.decrypt({name:"AES-GCM",iv:ge.default.base64ToArrayBuffer(u.metadata_iv),tagLength:128},_,ge.default.base64ToArrayBuffer(u.encrypted_metadata)),v=JSON.parse(new TextDecoder().decode(y)),S=await crypto.subtle.decrypt({name:"AES-GCM",iv:ge.default.base64ToArrayBuffer(u.iv),tagLength:128},_,ge.default.base64ToArrayBuffer(u.encrypted_file));p.push({filename:v.name,mime_type:v.type,data:S,size:v.size})}return{submission_id:t.submission_id,form_id:t.form_id,fields:o,attachments:p,integrity_valid:l,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,i,o=0){let a=await ge.default.encryptMessage(JSON.stringify(t),n),s=await this.sha256(`nodatachat:student:${t.student_id}`);return{encrypted_grade:a,student_hash:s,course_id:r,term:i,delivery_id:crypto.randomUUID(),delivered_at:new Date().toISOString(),ttl_hours:o,crypto_version:"0.2.0"}}static async decryptGrade(t,n){let r=await ge.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(i=>i.toString(16).padStart(2,"0")).join("")}};ht.NoDataForms=_i});var qa=O(mt=>{"use strict";var Mu=mt&&mt.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(mt,"__esModule",{value:!0});mt.NoDataSDK=void 0;var Un=Mu(We()),Pe=pi(),$e=mi(),oe=yi(),ye=bi(),vi=class{static async init(t={}){let n;return t.keyPair?n=t.keyPair:(n=await Un.default.generateKeyPair(),t.onKeysGenerated&&await t.onKeysGenerated(n)),{publicKey:n.publicKeyJwk,email:{seal:Pe.NoDataEmail.seal.bind(Pe.NoDataEmail),open:Pe.NoDataEmail.open.bind(Pe.NoDataEmail),isExpired:Pe.NoDataEmail.isExpired.bind(Pe.NoDataEmail),toMimeBody:Pe.NoDataEmail.toMimeBody.bind(Pe.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:oe.NoDataSystems.encryptRecord.bind(oe.NoDataSystems),decryptRecord:oe.NoDataSystems.decryptRecord.bind(oe.NoDataSystems),searchByHash:oe.NoDataSystems.searchByHash.bind(oe.NoDataSystems),encryptField:oe.NoDataSystems.encryptField.bind(oe.NoDataSystems),decryptField:oe.NoDataSystems.decryptField.bind(oe.NoDataSystems),createSchema:oe.NoDataSystems.createSchema.bind(oe.NoDataSystems)},forms:{encryptSubmission:ye.NoDataForms.encryptSubmission.bind(ye.NoDataForms),decryptSubmission:ye.NoDataForms.decryptSubmission.bind(ye.NoDataForms),isExpired:ye.NoDataForms.isExpired.bind(ye.NoDataForms),encryptGrade:ye.NoDataForms.encryptGrade.bind(ye.NoDataForms),decryptGrade:ye.NoDataForms.decryptGrade.bind(ye.NoDataForms)},crypto:Un.default}}static async quickEncrypt(t,n){let r=typeof t=="string"?t:JSON.stringify(t),i=await Un.default.encryptMessage(r,n);return JSON.stringify(i)}static async quickDecrypt(t,n){let r=JSON.parse(t),i=await Un.default.decryptMessage(r,n);try{return JSON.parse(i)}catch{return i}}};mt.NoDataSDK=vi});var Ja=O(ae=>{"use strict";Object.defineProperty(ae,"__esModule",{value:!0});ae.NoDataSDK=ae.NoDataForms=ae.NoDataSystems=ae.NoDataWebhook=ae.NoDataEmail=void 0;var Ku=pi();Object.defineProperty(ae,"NoDataEmail",{enumerable:!0,get:function(){return Ku.NoDataEmail}});var Hu=mi();Object.defineProperty(ae,"NoDataWebhook",{enumerable:!0,get:function(){return Hu.NoDataWebhook}});var Uu=yi();Object.defineProperty(ae,"NoDataSystems",{enumerable:!0,get:function(){return Uu.NoDataSystems}});var Vu=bi();Object.defineProperty(ae,"NoDataForms",{enumerable:!0,get:function(){return Vu.NoDataForms}});var Gu=qa();Object.defineProperty(ae,"NoDataSDK",{enumerable:!0,get:function(){return Gu.NoDataSDK}})});var yt=O(C=>{"use strict";Object.defineProperty(C,"__esModule",{value:!0});C.PQ_SIZES=C.NDC_WIRE_V03=C.NDC_WIRE_V1=C.NDC_V03_RATCHET_DOMAIN=C.NDC_V03_CONTENT_KEY_DOMAIN=C.NDC_V03_KEM_DOMAIN=C.PQ_SUITE=void 0;C.generateHybridKemKeypair=Wu;C.deriveHybridKemKeypairFromSeed=zu;C.hybridKemEncapsulate=qu;C.hybridKemDecapsulate=Ju;C.deriveContentKey=Xu;C.ratchetAdvance=Yu;C.generateHybridSigKeypair=Zu;C.hybridSign=Qu;C.hybridVerify=ep;C.generateMlDsa65Keypair=tp;C.mlDsa65SignDetached=np;C.mlDsa65VerifyDetached=rp;var Re=D("@noble/curves/ed25519.js"),Ut=D("@noble/hashes/sha2.js"),Vt=D("@noble/hashes/hkdf.js"),Vn=D("@noble/post-quantum/ml-kem.js"),gt=D("@noble/post-quantum/ml-dsa.js");C.PQ_SUITE={KEM:"X25519+ML-KEM-768",SIG:"Ed25519+ML-DSA-65",AEAD:"AES-256-GCM",KDF:"HKDF-SHA-256"};C.NDC_V03_KEM_DOMAIN="NDC-v0.3-hybrid-kem";C.NDC_V03_CONTENT_KEY_DOMAIN="NDC-v0.3-content-key";C.NDC_V03_RATCHET_DOMAIN="NDC-ratchet";C.NDC_WIRE_V1=1;C.NDC_WIRE_V03=2;function Xa(...e){let t=0;for(let i of e)t+=i.length;let n=new Uint8Array(t),r=0;for(let i of e)n.set(i,r),r+=i.length;return n}function Gt(e){return new TextEncoder().encode(e)}function Ya(e,t,n,r){let i=Xa(e,t),o=Xa(Gt(C.NDC_V03_KEM_DOMAIN),n,r);return(0,Vt.hkdf)(Ut.sha256,i,new Uint8Array(0),o,32)}function Wu(){let{secretKey:e,publicKey:t}=Re.x25519.keygen(),{publicKey:n,secretKey:r}=Vn.ml_kem768.keygen();return{publicKey:{x25519:t,mlKem:n},secretKey:{x25519:e,mlKem:r}}}function zu(e){if(e.length<32)throw new Error("seed too short (need >=32 bytes)");let t=(0,Vt.hkdf)(Ut.sha256,e,new Uint8Array(0),Gt("ndc-hybrid-kem-x25519-v1"),32),n=(0,Vt.hkdf)(Ut.sha256,e,new Uint8Array(0),Gt("ndc-hybrid-kem-mlkem768-v1"),64),r=Re.x25519.getPublicKey(t),{publicKey:i,secretKey:o}=Vn.ml_kem768.keygen(n);return{publicKey:{x25519:r,mlKem:i},secretKey:{x25519:t,mlKem:o}}}function qu(e){let{secretKey:t,publicKey:n}=Re.x25519.keygen(),r=Re.x25519.getSharedSecret(t,e.x25519),{cipherText:i,sharedSecret:o}=Vn.ml_kem768.encapsulate(e.mlKem),a=Ya(o,r,n,e.x25519);return{ciphertext:{ctClassical:n,ctPq:i},sharedSecret:a,ephemeralX25519Pk:n}}function Ju(e,t,n){let r=Re.x25519.getSharedSecret(e.x25519,n.ctClassical),i=Vn.ml_kem768.decapsulate(n.ctPq,e.mlKem);return Ya(i,r,n.ctClassical,t)}function Xu(e){return(0,Vt.hkdf)(Ut.sha256,e,new Uint8Array(0),Gt(C.NDC_V03_CONTENT_KEY_DOMAIN),32)}function Yu(e,t){return(0,Vt.hkdf)(Ut.sha256,e,t,Gt(C.NDC_V03_RATCHET_DOMAIN),32)}function Zu(){let{secretKey:e,publicKey:t}=Re.ed25519.keygen(),{publicKey:n,secretKey:r}=gt.ml_dsa65.keygen();return{publicKey:{ed25519:t,mlDsa:n},secretKey:{ed25519:e,mlDsa:r}}}function Qu(e,t){return{ed25519:Re.ed25519.sign(t,e.ed25519),mlDsa:gt.ml_dsa65.sign(t,e.mlDsa)}}function ep(e,t,n){return Re.ed25519.verify(n.ed25519,t,e.ed25519)?gt.ml_dsa65.verify(n.mlDsa,t,e.mlDsa):!1}function tp(){let{publicKey:e,secretKey:t}=gt.ml_dsa65.keygen();return{publicKey:e,secretKey:t}}function np(e,t){return gt.ml_dsa65.sign(t,e)}function rp(e,t,n){return gt.ml_dsa65.verify(n,t,e)}C.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 Wn=O(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=Gn;N.headerSigningBytes=ki;N.signContainerHeader=ts;N.verifyContainerHeader=ns;N.encodeContainerV3=rs;N.decodeContainerV3=is;N.sealHybrid=lp;N.openHybrid=dp;var ip=D("@noble/hashes/hkdf.js"),op=D("@noble/hashes/sha2.js"),V=yt();Object.defineProperty(N,"deriveContentKey",{enumerable:!0,get:function(){return V.deriveContentKey}});N.CONTAINER_MAGIC=new Uint8Array([78,68,76,66]);N.CONTAINER_FIXED_PREFIX_BYTES=8;N.CONTAINER_HEADER_MAX_BYTES=16777215;var ap="NDC-v0.3-wrap-key",W=class extends Error{constructor(t,n){super(n),this.name="ContainerV3Error",this.code=t}};N.ContainerV3Error=W;var Se=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)},ze=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},es=e=>{let t="";for(let n=0;n<e.length;n++)t+=e[n].toString(16).padStart(2,"0");return t};function Gn(e){if(e===null||typeof e!="object")return JSON.stringify(e);if(Array.isArray(e))return"["+e.map(Gn).join(",")+"]";let t=e;return"{"+Object.keys(t).sort().map(r=>JSON.stringify(r)+":"+Gn(t[r])).join(",")+"}"}function ki(e){let t={...e};return delete t.sig,new TextEncoder().encode(Gn(t))}function ts(e,t,n){let r=(0,V.hybridSign)(n.secretKey,ki(e));return{...e,sig:{signer_kid:t,ed25519:Se(r.ed25519),ml_dsa_65:Se(r.mlDsa)}}}function ns(e,t){let n={ed25519:ze(e.sig.ed25519),mlDsa:ze(e.sig.ml_dsa_65)};return(0,V.hybridVerify)(t,ki(e),n)}var sp=["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 cp(e){if(!e||typeof e!="object")throw new W("header_schema_mismatch","header is not an object");let t=e;for(let r of sp)if(t[r]===void 0)throw new W("header_schema_mismatch",`header missing required field: ${String(r)}`);if(t.format_version!==3)throw new W("unsupported_version",`format_version ${t.format_version} unknown`);if(t.profile!=="pq-hybrid")throw new W("suite_unknown",`profile must be 'pq-hybrid', got '${String(t.profile)}'`);let n=t.suite;if(n.kem!==V.PQ_SUITE.KEM||n.sig!==V.PQ_SUITE.SIG||n.aead!==V.PQ_SUITE.AEAD||n.kdf!==V.PQ_SUITE.KDF)throw new W("suite_unknown",`suite mismatch: viewer supports ${JSON.stringify(V.PQ_SUITE)}, header has ${JSON.stringify(n)}`)}function rs(e,t){let n=new TextEncoder().encode(JSON.stringify(e));if(n.length>N.CONTAINER_HEADER_MAX_BYTES)throw new W("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]=V.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 is(e){if(e.length<N.CONTAINER_FIXED_PREFIX_BYTES)throw new W("header_truncated",`container truncated: ${e.length} bytes (need \u2265 ${N.CONTAINER_FIXED_PREFIX_BYTES})`);for(let i=0;i<4;i++)if(e[i]!==N.CONTAINER_MAGIC[i])throw new W("bad_magic",`bad magic: expected NDLB, got ${es(e.slice(0,4))}`);if(e[4]!==V.NDC_WIRE_V03)throw new W("unsupported_version",`expected wire version 0x${V.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 W("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(i){throw new W("header_invalid_json",`header JSON parse failed: ${i.message}`)}return cp(r),{header:r,ciphertextWithTag:e.slice(n)}}var qe=e=>e;async function Za(e,t,n){let r=await crypto.subtle.importKey("raw",qe(e),{name:"AES-GCM"},!1,["encrypt"]),i=await crypto.subtle.encrypt({name:"AES-GCM",iv:qe(t)},r,qe(n));return new Uint8Array(i)}async function Qa(e,t,n){let r=await crypto.subtle.importKey("raw",qe(e),{name:"AES-GCM"},!1,["decrypt"]),i=await crypto.subtle.decrypt({name:"AES-GCM",iv:qe(t)},r,qe(n));return new Uint8Array(i)}function os(e){return(0,ip.hkdf)(op.sha256,e,new Uint8Array(0),new TextEncoder().encode(ap),32)}async function as(e){let t=await crypto.subtle.digest("SHA-256",qe(e));return es(new Uint8Array(t))}async function lp(e){let t=crypto.getRandomValues(new Uint8Array(32)),n=crypto.getRandomValues(new Uint8Array(12)),r=await Za(t,n,e.plaintext),i=r.slice(r.length-16),o=r.slice(0,r.length-16),a=(0,V.hybridKemEncapsulate)(e.recipientPublicKey),s=os(a.sharedSecret),c=crypto.getRandomValues(new Uint8Array(12)),l=await Za(s,c,t),p=await as(o),u={lockbox_id:e.meta.lockbox_id,format_version:3,profile:"pq-hybrid",suite:{kem:V.PQ_SUITE.KEM,sig:V.PQ_SUITE.SIG,aead:V.PQ_SUITE.AEAD,kdf:V.PQ_SUITE.KDF},server:e.meta.server,kem:{recipient_kid:e.recipientKid,ct_classical:Se(a.ciphertext.ctClassical),ct_pq:Se(a.ciphertext.ctPq),ephemeral_x25519_pk:Se(a.ephemeralX25519Pk)},wrapped_content_key:{wrapped:Se(l),wrap_iv:Se(c)},iv:Se(n),tag:Se(i),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:p,issued_at:new Date().toISOString(),cache_ttl_seconds:e.meta.cache_ttl_seconds},f=ts(u,e.signerKid,e.signerKeypair),h=rs(f,r);return t.fill(0),{container:h,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 dp(e){let{header:t,ciphertextWithTag:n}=is(e.container);if(!ns(t,e.signerPublicKey))throw new W("signature_invalid","hybrid signature verification failed");let r=n.slice(0,n.length-16),i=await as(r);if(i!==t.ciphertext_sha256)throw new W("integrity_mismatch",`ciphertext sha256 mismatch: expected ${t.ciphertext_sha256.slice(0,16)}\u2026, got ${i.slice(0,16)}\u2026`);let o={ctClassical:ze(t.kem.ct_classical),ctPq:ze(t.kem.ct_pq)},a=(0,V.hybridKemDecapsulate)(e.recipientSecretKey,e.recipientPublicX25519,o),s=os(a),c=ze(t.wrapped_content_key.wrapped),l=ze(t.wrapped_content_key.wrap_iv),p=await Qa(s,l,c),u=ze(t.iv),f=await Qa(p,u,n);return p.fill(0),{plaintext:f,header:t}}});var Si=O(bt=>{"use strict";Object.defineProperty(bt,"__esModule",{value:!0});bt.publicJwkFromBytes=cs;bt.jwkThumbprint=ls;bt.createDpop=pp;bt.verifyDpop=hp;var ss=D("@noble/curves/ed25519.js"),up=D("@noble/hashes/sha2.js"),_t=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,"_")},zn=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 i=atob(r),o=new Uint8Array(i.length);for(let a=0;a<i.length;a++)o[a]=i.charCodeAt(a);return o},Wt=e=>new TextEncoder().encode(e);function cs(e){if(e.length!==32)throw new Error(`expected 32-byte Ed25519 public key, got ${e.length}`);return{kty:"OKP",crv:"Ed25519",x:_t(e)}}function ls(e){let t=`{"crv":"${e.crv}","kty":"${e.kty}","x":"${e.x}"}`,n=(0,up.sha256)(Wt(t));return _t(n)}function pp(e){let n={typ:"dpop+jwt",alg:"EdDSA",jwk:cs(e.publicKey)},r={htm:e.htm.toUpperCase(),htu:wi(e.htu),jti:e.jti??fp(),iat:e.iat??Math.floor(Date.now()/1e3)};e.nonce&&(r.nonce=e.nonce);let i=_t(Wt(JSON.stringify(n))),o=_t(Wt(JSON.stringify(r))),a=`${i}.${o}`,s=ss.ed25519.sign(Wt(a),e.secretKey);return`${a}.${_t(s)}`}function fp(){return _t(crypto.getRandomValues(new Uint8Array(16)))}function wi(e){try{let t=new URL(e);return`${t.protocol}//${t.host}${t.pathname}`}catch{return e}}async function hp(e,t){let n=e.split(".");if(n.length!==3)return z("malformed","expected three JWT parts");let[r,i,o]=n,a;try{a=JSON.parse(new TextDecoder().decode(zn(r)))}catch{return z("bad_header","header is not valid base64url JSON")}if(a.typ!=="dpop+jwt")return z("bad_typ",`typ must be 'dpop+jwt', got '${String(a.typ)}'`);if(a.alg!=="EdDSA")return z("bad_alg",`alg must be 'EdDSA', got '${String(a.alg)}'`);if(!a.jwk||a.jwk.kty!=="OKP"||a.jwk.crv!=="Ed25519")return z("bad_header","jwk must be an Ed25519 OKP key");let s=ls(a.jwk);if(s!==t.expectedJkt)return z("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(zn(i)))}catch{return z("bad_payload","payload is not valid base64url JSON")}if(c.htm!==t.expectedHtm.toUpperCase())return z("htm_mismatch",`htm '${c.htm}' \u2260 expected '${t.expectedHtm.toUpperCase()}'`);if(c.htu!==wi(t.expectedHtu))return z("htu_mismatch",`htu '${c.htu}' \u2260 expected '${wi(t.expectedHtu)}'`);if(t.expectedNonce!==void 0&&c.nonce!==t.expectedNonce)return z("nonce_mismatch","DPoP nonce does not match server-issued nonce");let l=Math.floor(Date.now()/1e3),p=t.maxAgeSeconds??30;if(typeof c.iat!="number")return z("bad_payload","iat missing or not a number");if(c.iat>l+5)return z("iat_in_future",`iat ${c.iat} > now+skew`);if(l-c.iat>p)return z("iat_too_old",`iat ${c.iat} older than ${p}s`);let u;try{u=zn(a.jwk.x)}catch{return z("bad_header","jwk.x is not base64url")}let f=zn(o),h=Wt(`${r}.${i}`);return ss.ed25519.verify(f,h,u)?await t.isJtiFresh(c.jti)?{ok:!0,jti:c.jti,iat:c.iat}:z("replay",`jti ${c.jti} was already seen`):z("signature_invalid","Ed25519 signature does not verify")}function z(e,t){return{ok:!1,code:e,reason:t}}});var gs=O(A=>{"use strict";Object.defineProperty(A,"__esModule",{value:!0});A.ABSORB_STATUS=A.DELTA_KIND=A.RCPT_TOTAL_LEN=A.RCPT_SIGNED_LEN=A.PVE_TOTAL_LEN=A.PVE_SIGNED_LEN=A.RCPT_VERSION=A.PVE_VERSION=A.RCPT_MAGIC=A.PVE_MAGIC=void 0;A.deltaIdFromUuid=_p;A.uuidFromDeltaId=bp;A.originJktForPublicKey=qt;A.encodePveSignedBytes=ps;A.signPve=vp;A.parsePve=fs;A.pveHash=kp;A.verifyPve=wp;A.encodeReceiptSignedBytes=hs;A.signReceipt=Sp;A.parseReceipt=ms;A.verifyReceipt=Ep;var qn=D("@noble/curves/ed25519.js"),mp=D("@noble/hashes/sha2.js"),ds=Si();A.PVE_MAGIC=new Uint8Array([80,86,69,49]);A.RCPT_MAGIC=new Uint8Array([82,67,86,49]);A.PVE_VERSION=1;A.RCPT_VERSION=1;A.PVE_SIGNED_LEN=160;A.PVE_TOTAL_LEN=A.PVE_SIGNED_LEN+64;A.RCPT_SIGNED_LEN=78;A.RCPT_TOTAL_LEN=A.RCPT_SIGNED_LEN+64;var us=new Uint8Array(32);A.DELTA_KIND={relay:1,ndc:2,v4section:3,chatmsg:4};A.ABSORB_STATUS={decrypted_ok:1,verified_only:2,denied:3};function gp(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 yp(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 i=atob(r),o=new Uint8Array(i.length);for(let a=0;a<i.length;a++)o[a]=i.charCodeAt(a);return o}function Ai(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 zt(e){for(let t=0;t<e.length;t++)if(e[t]!==0)return!1;return!0}function Ei(e){if(e==null)return us;if(e instanceof Uint8Array){if(e.length!==32)throw new Error(`jkt bytes must be 32, got ${e.length}`);return e}let t=yp(e);if(t.length!==32)throw new Error(`jkt must decode to 32 bytes, got ${t.length}`);return t}function xi(e){return zt(e)?null:gp(e)}function _p(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 bp(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 qt(e){return(0,ds.jwkThumbprint)((0,ds.publicJwkFromBytes)(e))}function ps(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(A.PVE_SIGNED_LEN),n=new DataView(t.buffer),r=0;return t.set(A.PVE_MAGIC,r),r+=4,t[r]=A.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(Ei(e.originJkt),r),r+=32,t.set(Ei(e.destJkt??null),r),r+=32,t.set(e.prevDeltaHash??us,r),r+=32,n.setUint16(r,e.classification,!1),r+=2,n.setBigUint64(r,BigInt(e.issuedAt),!1),r+=8,t}function vp(e,t){let n=qt(e.originPublicKey),r=ps({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()}),i=qn.ed25519.sign(r,t),o=new Uint8Array(A.PVE_TOTAL_LEN);return o.set(r,0),o.set(i,A.PVE_SIGNED_LEN),o}function fs(e){if(e.length!==A.PVE_TOTAL_LEN)throw new Error(`PVE must be ${A.PVE_TOTAL_LEN} bytes, got ${e.length}`);if(!Ai(e.subarray(0,4),A.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 i=e[n];n+=1;let o=e.slice(n,n+16);n+=16;let a=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 l=e.slice(n,n+32);n+=32;let p=t.getUint16(n,!1);n+=2;let u=Number(t.getBigUint64(n,!1));n+=8;let f=e.slice(0,A.PVE_SIGNED_LEN),h=e.slice(A.PVE_SIGNED_LEN,A.PVE_TOTAL_LEN),_=xi(s);if(_===null)throw new Error("origin_jkt must not be zero");return{fields:{version:r,deltaKind:i,deltaId:o,ciphertextSha256:a,originJkt:_,destJkt:xi(c),prevDeltaHash:zt(l)?null:l,classification:p,issuedAt:u},signedBytes:f,originSig:h,broadcast:zt(c),genesis:zt(l)}}function kp(e){return(0,mp.sha256)(e)}function wp(e,t){let n;try{n=fs(e)}catch(i){let o=i instanceof Error?i.message:String(i);return o.includes("magic")?{ok:!1,code:"bad_magic",reason:o}:{ok:!1,code:"malformed",reason:o}}if(n.fields.version!==A.PVE_VERSION)return{ok:!1,code:"bad_version",reason:`unsupported PVE version ${n.fields.version}`};let r;try{r=qt(t)}catch(i){return{ok:!1,code:"malformed",reason:i instanceof Error?i.message:String(i)}}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`}:qn.ed25519.verify(n.originSig,n.signedBytes,t)?{ok:!0,parsed:n}:{ok:!1,code:"signature_invalid",reason:"Ed25519 origin signature does not verify"}}function hs(e){if(e.pveHash.length!==32)throw new Error("pve_hash must be 32 bytes");let t=Ei(e.destJkt);if(zt(t))throw new Error("receipt dest_jkt must not be zero");let n=new Uint8Array(A.RCPT_SIGNED_LEN),r=new DataView(n.buffer),i=0;return n.set(A.RCPT_MAGIC,i),i+=4,n[i]=A.RCPT_VERSION,i+=1,n.set(e.pveHash,i),i+=32,n.set(t,i),i+=32,n[i]=e.absorbStatus,i+=1,r.setBigUint64(i,BigInt(e.absorbedAt),!1),i+=8,n}function Sp(e,t){let n=qt(e.destPublicKey),r=hs({pveHash:e.pveHash,destJkt:n,absorbStatus:e.absorbStatus,absorbedAt:e.absorbedAt??Date.now()}),i=qn.ed25519.sign(r,t),o=new Uint8Array(A.RCPT_TOTAL_LEN);return o.set(r,0),o.set(i,A.RCPT_SIGNED_LEN),o}function ms(e){if(e.length!==A.RCPT_TOTAL_LEN)throw new Error(`receipt must be ${A.RCPT_TOTAL_LEN} bytes, got ${e.length}`);if(!Ai(e.subarray(0,4),A.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 i=e.slice(n,n+32);n+=32;let o=e.slice(n,n+32);n+=32;let a=e[n];n+=1;let s=Number(t.getBigUint64(n,!1));n+=8;let c=xi(o);if(c===null)throw new Error("receipt dest_jkt must not be zero");return{fields:{version:r,pveHash:i,destJkt:c,absorbStatus:a,absorbedAt:s},signedBytes:e.slice(0,A.RCPT_SIGNED_LEN),destSig:e.slice(A.RCPT_SIGNED_LEN,A.RCPT_TOTAL_LEN)}}function Ep(e,t,n){let r;try{r=ms(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(r.fields.version!==A.RCPT_VERSION)return{ok:!1,code:"bad_version",reason:`unsupported receipt version ${r.fields.version}`};let i;try{i=qt(t)}catch(o){return{ok:!1,code:"malformed",reason:o instanceof Error?o.message:String(o)}}return i!==r.fields.destJkt?{ok:!1,code:"jkt_mismatch",reason:`presented key thumbprint ${i.slice(0,12)}\u2026 \u2260 committed dest_jkt ${r.fields.destJkt.slice(0,12)}\u2026`}:n!==void 0&&!Ai(n,r.fields.pveHash)?{ok:!1,code:"pve_hash_mismatch",reason:"receipt does not acknowledge the expected PVE"}:qn.ed25519.verify(r.destSig,r.signedBytes,t)?{ok:!0,parsed:r}:{ok:!1,code:"signature_invalid",reason:"Ed25519 destination signature does not verify"}}});var _s=O(Jt=>{"use strict";Object.defineProperty(Jt,"__esModule",{value:!0});Jt.stepRatchet=xp;Jt.replayRatchet=Ap;Jt.destroyKey=Tp;var ys=yt();function xp(e,t){if(t.length!==32)throw new Error(`ratchet token must be 32 bytes, got ${t.length}`);return{nextContentKey:(0,ys.ratchetAdvance)(e.contentKey,t),openCount:e.openCount+1}}function Ap(e,t){let n=[e],r=e;for(let i of t)r=(0,ys.ratchetAdvance)(r,i),n.push(r);return n}function Tp(e){e.fill(0)}});var Pi=O(vt=>{"use strict";Object.defineProperty(vt,"__esModule",{value:!0});vt.__coseInternals=void 0;vt.verifyCoseSign1Es384=$p;vt.decodeAttestationPayload=Rp;var Ip=D("@noble/curves/nist.js"),Pp=D("@noble/hashes/sha2.js"),Ti=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 i=this.len(r),o=this.b.subarray(this.p,this.p+i);if(o.length!==i)throw new Error("cbor: bstr truncated");return this.p+=i,o.slice()}case 3:{let i=this.len(r),o=this.b.subarray(this.p,this.p+i);if(o.length!==i)throw new Error("cbor: tstr truncated");return this.p+=i,new TextDecoder("utf-8").decode(o)}case 4:{let i=this.len(r),o=[];for(let a=0;a<i;a++)o.push(this.read());return o}case 5:{let i=this.len(r),o=new Map;for(let a=0;a<i;a++){let s=this.read(),c=this.read();o.set(s,c)}return o}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 Ii(e){return new Ti(e).read()}function Xn(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 Yn(...e){let t=e.reduce((i,o)=>i+o.length,0),n=new Uint8Array(t),r=0;for(let i of e)n.set(i,r),r+=i.length;return n}function Jn(e){return Yn(Xn(2,e.length),e)}function bs(e){let t=new TextEncoder().encode(e);return Yn(Xn(3,t.length),t)}function vs(e,t){return Yn(Xn(4,4),bs("Signature1"),Jn(e),Jn(new Uint8Array(0)),Jn(t))}function $p(e,t){let n;try{n=Ii(e)}catch(l){return{ok:!1,code:"malformed",reason:`cbor decode failed: ${l.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,,i,o]=n;if(!(r instanceof Uint8Array))return{ok:!1,code:"bad_structure",reason:"protected header must be a byte string"};if(!(i instanceof Uint8Array)||i.length===0)return{ok:!1,code:"no_payload",reason:"detached/empty payload is not supported"};if(!(o instanceof Uint8Array))return{ok:!1,code:"bad_structure",reason:"signature must be a byte string"};if(o.length!==96)return{ok:!1,code:"bad_signature_len",reason:`expected 96-byte ES384 sig, got ${o.length}`};let a=vs(r,i),s=(0,Pp.sha384)(a),c=!1;try{c=Ip.p384.verify(o,s,t,{prehash:!1})}catch(l){return{ok:!1,code:"signature_invalid",reason:`verify threw: ${l.message}`}}return c?{ok:!0,payload:i}:{ok:!1,code:"signature_invalid",reason:"ECDSA P-384 verification failed"}}function Rp(e){try{let t=Ii(e);return t instanceof Map?t:null}catch{return null}}vt.__coseInternals={sig1Structure:vs,encBstr:Jn,encText:bs,encHead:Xn,concat:Yn,decodeCbor:Ii}});var ks=O(Xt=>{"use strict";Object.defineProperty(Xt,"__esModule",{value:!0});Xt.parseAttestation=Cp;Xt.verifyAttestation=Np;Xt.fetchAttestation=Op;var Dp=Pi();function Cp(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 Np(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[o,a]of Object.entries(t.pcrs))if(e.pcrs[o]!==a)return{ok:!1,code:"pcr_mismatch",reason:`PCR ${o}: got '${(e.pcrs[o]??"").slice(0,16)}\u2026', expected '${a.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 i=!1;if(t.cose){if(!t.trustedLeafPubKey)return{ok:!1,code:"signature_invalid",reason:"cose supplied without trustedLeafPubKey \u2014 cannot verify, refusing"};let o=(0,Dp.verifyCoseSign1Es384)(t.cose,t.trustedLeafPubKey);if(!o.ok)return{ok:!1,code:"signature_invalid",reason:`cose: ${o.code}: ${o.reason}`};i=!0}return{ok:!0,vendor:e.vendor,module_id:e.module_id,signature_verified:i}}async function Op(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 Es=O(kt=>{"use strict";Object.defineProperty(kt,"__esModule",{value:!0});kt.splitSecret=Fp;kt.combineShares=Mp;kt.serializeShare=Up;kt.deserializeShare=Vp;var Je=null,Xe=null;function ws(){if(Je&&Xe)return;Je=new Uint8Array(512),Xe=new Uint8Array(256);let e=1;for(let t=0;t<255;t++){Je[t]=e,Xe[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 Zn(e,t){return e===0||t===0?0:(ws(),Je[Xe[e]+Xe[t]])}function jp(e,t){if(e===0)return 0;if(t===0)throw new Error("division by zero in GF(2^8)");ws();let n=Xe[e]-Xe[t];return Je[n<0?n+255:n]}function Ss(e,t){return e^t}function Lp(e,t){let n=0;for(let r=e.length-1;r>=0;r--)n=Ss(Zn(n,t),e[r]);return n}var Bp=e=>crypto.getRandomValues(new Uint8Array(e));function Fp(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??Bp,r=[];for(let i=1;i<=t.n;i++)r.push({x:i,y:new Uint8Array(e.length)});for(let i=0;i<e.length;i++){let o=new Uint8Array(t.k);o[0]=e[i];let a=n(t.k-1);for(let s=1;s<t.k;s++)o[s]=a[s-1];for(let s=0;s<t.n;s++)r[s].y[i]=Lp(o,r[s].x)}return r}function Mp(e){if(e.length<2)throw new Error("need at least 2 shares to reconstruct");let t=e[0].y.length;for(let i of e){if(i.y.length!==t)throw new Error("shares have inconsistent length");if(i.x===0)throw new Error("share x must not be 0")}let n=new Set;for(let i of e){if(n.has(i.x))throw new Error(`duplicate share x=${i.x}`);n.add(i.x)}let r=new Uint8Array(t);for(let i=0;i<t;i++){let o=0;for(let a=0;a<e.length;a++){let s=1,c=1;for(let p=0;p<e.length;p++)a!==p&&(s=Zn(s,e[p].x),c=Zn(c,e[a].x^e[p].x));let l=jp(s,c);o=Ss(o,Zn(e[a].y[i],l))}r[i]=o}return r}var Kp=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)},Hp=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 Up(e){return{x:e.x,y_b64:Kp(e.y)}}function Vp(e){return{x:e.x,y:Hp(e.y_b64)}}});var Is=O(De=>{"use strict";Object.defineProperty(De,"__esModule",{value:!0});De.SegmentError=void 0;De.sealSegments=Jp;De.openSegments=Xp;De.manifestDigest=Yp;De.buildCapability=Zp;var $i=D("@noble/hashes/sha2.js"),Gp="pq-hybrid-segments",Wp="AES-256-GCM",wt=e=>e,xs=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)},As=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},Ts=e=>{let t="";for(let n=0;n<e.length;n++)t+=e[n].toString(16).padStart(2,"0");return t};async function zp(e,t,n){let r=await crypto.subtle.importKey("raw",wt(e),{name:"AES-GCM"},!1,["encrypt"]),i=await crypto.subtle.encrypt({name:"AES-GCM",iv:wt(t)},r,wt(n));return new Uint8Array(i)}async function qp(e,t,n){let r=await crypto.subtle.importKey("raw",wt(e),{name:"AES-GCM"},!1,["decrypt"]),i=await crypto.subtle.decrypt({name:"AES-GCM",iv:wt(t)},r,wt(n));return new Uint8Array(i)}var Ye=class extends Error{constructor(t,n){super(n),this.name="SegmentError",this.code=t}};De.SegmentError=Ye;async function Jp(e){let t=new Set;for(let i of e){if(t.has(i.segment_id))throw new Ye("duplicate_segment_id",`segment_id '${i.segment_id}' appears twice`);t.add(i.segment_id)}let n=[],r=[];for(let i of e){let o=crypto.getRandomValues(new Uint8Array(32)),a=crypto.getRandomValues(new Uint8Array(12)),s=await zp(o,a,i.plaintext),c=s.slice(0,s.length-16),l=Ts((0,$i.sha256)(c));n.push({segment_id:i.segment_id,key:o}),r.push({segment_id:i.segment_id,label:i.label,content_type:i.content_type,iv_b64:xs(a),ciphertext_b64:xs(s),ciphertext_sha256:l})}return{manifest:{profile:Gp,aead:Wp,segments:r},keys:n}}async function Xp(e,t){let n=new Map;for(let i of t.keys)n.set(i.segment_id,i.key);let r=[];for(let i of e.segments){if(!t.allowed_segment_ids.includes(i.segment_id))continue;let o=n.get(i.segment_id);if(!o)throw new Ye("key_missing",`capability lists ${i.segment_id} as allowed but holds no key for it`);let a=As(i.ciphertext_b64),s=a.slice(0,a.length-16);if(Ts((0,$i.sha256)(s))!==i.ciphertext_sha256)throw new Ye("integrity_mismatch",`segment ${i.segment_id}: ciphertext sha256 mismatch`);let l=As(i.iv_b64),p=await qp(o,l,a);r.push({segment_id:i.segment_id,label:i.label,content_type:i.content_type,plaintext:p})}return r}function Yp(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,$i.sha256)(new TextEncoder().encode(n))}function Zp(e,t,n){let r=new Set(t),i=n.filter(o=>r.has(o.segment_id));if(i.length!==t.length){let o=t.filter(a=>!i.find(s=>s.segment_id===a));throw new Ye("segment_not_found",`cannot build capability \u2014 no key for: ${o.join(", ")}`)}return{recipient_kid:e,allowed_segment_ids:t,keys:i}}});var Rs=O(Yt=>{"use strict";Object.defineProperty(Yt,"__esModule",{value:!0});Yt.computeWatermark=$s;Yt.findLeakSource=tf;Yt.watermarkSvgOverlay=nf;var Qp=D("@noble/hashes/hmac.js"),ef=D("@noble/hashes/sha2.js");function $s(e){let t=[e.recipientId,e.lockboxId,String(e.openCount),String(e.iat)].join("|"),n=(0,Qp.hmac)(ef.sha256,e.tenantSecret,new TextEncoder().encode(t)),r=Ps(n.slice(0,16)),i=Ps(n.slice(0,4)),o=new Date(e.iat*1e3).toISOString().slice(0,10),a=`${e.recipientId} \xB7 ${o} \xB7 ${i}`;return{short_hex:i,full_hex:r,display_label:a}}function tf(e,t,n){let r=e.toLowerCase();for(let i of n){let o=$s({tenantSecret:t,...i});if(r===o.full_hex)return{matched:!0,candidate:i,matched_on:"full_hex"};if(r===o.short_hex)return{matched:!0,candidate:i,matched_on:"short_hex"}}return{matched:!1,reason:"no_candidate_matched"}}function nf(e,t){let n=t?.width??800,r=t?.height??1e3,i=t?.opacity??.1,a=(s=>s.replace(/[<>&"]/g,c=>({"<":"<",">":">","&":"&",'"':"""})[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="${i}" 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})">${a}</text>
|
|
11
11
|
<text x="${n/2}" y="${r*.5}" transform="rotate(-30 ${n/2} ${r*.5})">${a}</text>
|
|
12
12
|
<text x="${n/2}" y="${r*.8}" transform="rotate(-30 ${n/2} ${r*.8})">${a}</text>
|
|
13
13
|
</g>
|
|
14
14
|
<text x="${n-12}" y="${r-8}" font-family="monospace" font-size="10" fill="#000" opacity="${i*2}" text-anchor="end">${e.short_hex}</text>
|
|
15
|
-
</svg>`}function Pa(e){let t="";for(let n=0;n<e.length;n++)t+=e[n].toString(16).padStart(2,"0");return t}});var Ba=N(J=>{"use strict";Object.defineProperty(J,"__esModule",{value:!0});J.DRAND_LOE_MAINNET=J.TimeGateError=void 0;J.timeGateEncrypt=Ku;J.timeGateDecrypt=Hu;J.roundForTime=Uu;J.timeForRound=Vu;J.drandTimeLockEncrypt=Wu;J.drandTimeLockDecrypt=Oa;J.makeFakeDrandChain=zu;J.fetchDrandRound=ja;J.drandTimeLockOpen=Ju;var me=P("@noble/curves/bls12-381.js"),Nn=P("@noble/hashes/sha2.js"),Te=e=>e,Da="NDC-v0.3-server-time-gate";async function Ku(e){let t=crypto.getRandomValues(new Uint8Array(12)),n=new TextEncoder().encode(`${Da}|${e.notBeforeUnixSec}`),r=await crypto.subtle.importKey("raw",Te(e.serverWrapKey),{name:"AES-GCM"},!1,["encrypt"]),i=await crypto.subtle.encrypt({name:"AES-GCM",iv:Te(t),additionalData:Te(n)},r,Te(e.plaintext));return{variant:"server-attested",notBeforeUnixSec:e.notBeforeUnixSec,iv_b64:Dn(t),ciphertext_b64:Dn(new Uint8Array(i))}}var Bt=class extends Error{constructor(t,n){super(n),this.name="TimeGateError",this.code=t}};J.TimeGateError=Bt;async function Hu(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(`${Da}|${e.ciphertext.notBeforeUnixSec}`),n=await crypto.subtle.importKey("raw",Te(e.serverWrapKey),{name:"AES-GCM"},!1,["decrypt"]);try{let r=await crypto.subtle.decrypt({name:"AES-GCM",iv:Te(Cn(e.ciphertext.iv_b64)),additionalData:Te(t)},n,Te(Cn(e.ciphertext.ciphertext_b64)));return new Uint8Array(r)}catch{throw new Bt("tamper_detected","AES-GCM authentication tag failed \u2014 ciphertext or AAD tampered")}}J.DRAND_LOE_MAINNET={publicKeyHex:"868f005eb8e6e4ca0a47c8a77ceaa5309a47978a7c71bc5cce96366b5d7a569937c529eeda66c7293784a9402801af31",chainHashHex:"8990e7a9aaed2ffed73dbd7092123d6f289930540d7651336225dc172e51b2ce",genesisUnixSec:1595431050,periodSec:30,hashDst:"BLS_SIG_BLS12381G2_XMD:SHA-256_SSWU_RO_NUL_"};function Uu(e,t){return e<=t.genesisUnixSec?1:Math.ceil((e-t.genesisUnixSec)/t.periodSec)}function Vu(e,t){return t.genesisUnixSec+e*t.periodSec}function Ca(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,Nn.sha256)(t)}function Na(e){let t=new Uint8Array(576),n=0;for(let r of[e.c0,e.c1])for(let i of[r.c0,r.c1,r.c2])for(let o of[i.c0,i.c1])Gu(o,t,n,48),n+=48;return t}function Gu(e,t,n,r){let i=e,o=BigInt(255),a=BigInt(8);for(let s=r-1;s>=0;s--)t[n+s]=Number(i&o),i>>=a}function Wu(e,t,n,r){if(e.length!==32)throw new Error(`drand-IBE expects a 32-byte content key, got ${e.length}`);let i=me.bls12_381.G1.Point,o=me.bls12_381.fields.Fr,a=i.fromBytes(n),s;do s=Xu(crypto.getRandomValues(new Uint8Array(32)))%o.ORDER;while(s===BigInt(0));let c=i.BASE.multiply(s),l=me.bls12_381.longSignatures.hash(Ca(t),r.hashDst),u=a.multiply(s),p=me.bls12_381.pairing(u,l,!0),h=(0,Nn.sha256)(Na(p)),f=new Uint8Array(32);for(let g=0;g<32;g++)f[g]=e[g]^h[g];return{variant:"drand-ibe",chainHashHex:r.chainHashHex,round:t,u_b64:Dn(c.toBytes()),v_b64:Dn(f)}}function Oa(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=me.bls12_381.G1.Point.fromBytes(Cn(e.ciphertext.u_b64)),r=me.bls12_381.longSignatures.Signature.fromBytes(e.roundSignature),i=me.bls12_381.pairing(n,r,!0),o=(0,Nn.sha256)(Na(i)),a=Cn(e.ciphertext.v_b64);if(a.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]=a[c]^o[c];return s}function zu(e){let t;if(e&&e.length===48)t=e;else{t=new Uint8Array(48);let o=e??crypto.getRandomValues(new Uint8Array(48));t.set(o.slice(0,48),0)}let{secretKey:n,publicKey:r}=me.bls12_381.longSignatures.keygen(t),i={publicKeyHex:Ra(r.toBytes()),chainHashHex:Ra((0,Nn.sha256)(r.toBytes())),genesisUnixSec:17e8,periodSec:30,hashDst:"BLS_SIG_BLS12381G2_XMD:SHA-256_SSWU_RO_NUL_"};return{config:i,publicKey:r.toBytes(),signRound(o){let a=me.bls12_381.longSignatures.hash(Ca(o),i.hashDst);return me.bls12_381.longSignatures.sign(a,n).toBytes()}}}function Ra(e){let t="";for(let n=0;n<e.length;n++)t+=e[n].toString(16).padStart(2,"0");return t}function qu(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 ja(e,t,n={}){let r=n.fetchImpl??fetch,i=n.timeoutMs??8e3,o=`${t.replace(/\/$/,"")}/public/${e}`,a,s;typeof AbortController<"u"&&(a=new AbortController,s=setTimeout(()=>a.abort(),i));let c;try{c=await r(o,{signal:a?.signal})}finally{s&&clearTimeout(s)}if(!c.ok)throw new Error(`drand fetch failed: ${o} \u2192 HTTP ${c.status}`);let l=await c.json();if(typeof l.round!="number"||typeof l.signature!="string"||typeof l.randomness!="string")throw new Error(`drand response malformed at ${o}`);let u=qu(l.signature);if(u.length!==96)throw new Error(`drand signature wrong length: expected 96 bytes (compressed G2), got ${u.length}`);return{round:l.round,randomness_hex:l.randomness,signature_bytes:u,previous_signature_hex:l.previous_signature}}async function Ju(e,t,n,r={}){let i=await ja(e.round,t,r);return Oa({ciphertext:e,roundSignature:i.signature_bytes,chain:n})}function Dn(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 Cn(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 Xu(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 Ha=N(oe=>{"use strict";Object.defineProperty(oe,"__esModule",{value:!0});oe.GENESIS_PREV_HASH=void 0;oe.receiptHash=ai;oe.issueReceipt=si;oe.verifyReceipt=Ka;oe.auditChain=Qu;oe.issueGenesisReceipt=ep;oe.appendReceipt=tp;var Yu=P("@noble/hashes/sha2.js"),oi=xn(),Ma=at();oe.GENESIS_PREV_HASH="0".repeat(64);var 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)},La=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},Zu=e=>{let t="";for(let n=0;n<e.length;n++)t+=e[n].toString(16).padStart(2,"0");return t};function ai(e){return Zu((0,Yu.sha256)(new TextEncoder().encode((0,oi.canonicalJson)(e))))}function si(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,oi.canonicalJson)(t)),r=(0,Ma.hybridSign)(e.signing_key.secretKey,n);return{body:t,sig:{signer_kid:e.signer_kid,ed25519_b64:Fa(r.ed25519),ml_dsa_65_b64:Fa(r.mlDsa)}}}function Ka(e,t){let n=new TextEncoder().encode((0,oi.canonicalJson)(e.body)),r={ed25519:La(e.sig.ed25519_b64),mlDsa:La(e.sig.ml_dsa_65_b64)};return(0,Ma.hybridVerify)(t,n,r)}function Qu(e,t,n=1){if(e.length===0)return{ok:!0,receipts_checked:0};let r=n,i=n===1?oe.GENESIS_PREV_HASH:null;for(let o of e){if(o.body.sequence!==r)return{ok:!1,code:o.body.sequence<r?"duplicate_sequence":"out_of_order",at_sequence:o.body.sequence,reason:`expected sequence ${r}, got ${o.body.sequence}`};if(i!==null&&o.body.prev_hash!==i)return{ok:!1,code:r===1?"missing_genesis":"broken_prev_hash",at_sequence:o.body.sequence,reason:`prev_hash mismatch: expected ${i.slice(0,16)}\u2026, got ${o.body.prev_hash.slice(0,16)}\u2026`};if(!Ka(o,t))return{ok:!1,code:"bad_signature",at_sequence:o.body.sequence,reason:"hybrid signature does not verify"};i=ai(o.body),r+=1}return{ok:!0,receipts_checked:e.length}}function ep(e){return si({event_type:e.initial_event,lockbox_id:e.lockbox_id,prev_hash:oe.GENESIS_PREV_HASH,sequence:1,payload:e.initial_payload,signer_kid:e.signer_kid,signing_key:e.signing_key,iat:e.iat})}function tp(e,t){return si({...t,prev_hash:ai(e.body),sequence:e.body.sequence+1})}});var Va=N(On=>{"use strict";Object.defineProperty(On,"__esModule",{value:!0});On.recommend=sp;On.summarise=cp;var np={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"}},rp={"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}},ip={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"]}},op=[{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"}],Ua={"mode-4":1,"mode-4p":2,"mode-4h":3,"mode-6":4};function ap(e,t){return Ua[e]>=Ua[t]?e:t}function sp(e){let t=np[e.orgType],n=rp[e.fileClass],r=ip[e.channel],i=ap(t.mode,n.minMode);e.recipientLacksPasskey&&i==="mode-4h"&&(i="mode-4p");let o=Math.min(t.ttlSeconds,n.maxTtlSeconds),a={forensicWatermark:t.forensicWatermark||n.watermarkRequired,selectiveDisclosureSegments:n.selectiveDisclosure||!!e.perRecipientPolicy,thresholdKofN:e.multipleApproversRequired??null,teeAttestation:t.teeAttestation||n.teeRequired,perOpenRatchet:i==="mode-4h"||i==="mode-4p"||i==="mode-6",dpopRequired:i!=="mode-4",timelockDrand:!!e.timeLockUnixSec&&!!e.timeLockDecentralized,timelockServerGate:!!e.timeLockUnixSec&&!e.timeLockDecentralized},s={...r,adapterCandidates:[...r.adapters]},c=[...s.notes],l=op.find(u=>u.channel===e.channel&&u.fileClass===e.fileClass);return l&&(c.unshift(`\u26A0 ${l.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:i,cacheTtlSeconds:o,features:a,delivery:{deliveryMode:s.deliveryMode,adapterCandidates:s.adapterCandidates},notes:c}}function cp(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 Wa=N(pt=>{"use strict";Object.defineProperty(pt,"__esModule",{value:!0});pt.recommendationToMandate=fp;pt.v3SealReceiptPayload=hp;pt.v3OpenReceiptPayload=mp;pt.showcaseChips=gp;function lp(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 dp(e){return e.features.dpopRequired?"device_mfa":e.sensitivityMode==="mode-4h"?"first_device":e.sensitivityMode==="mode-4"?"any":"first_device"}function up(e){return e.delivery.deliveryMode==="attachment"?"file":e.delivery.deliveryMode==="link"?"link":"view_only"}function Ga(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 pp(e){let t=Ga(e);return t==="m365"?"m365_only":t==="in_app"?"in_app":"any"}function fp(e){let{recommendation:t,source:n}=e,r=t.sensitivityMode==="mode-6",i=n.timeLockUnixSec?new Date(n.timeLockUnixSec*1e3).toISOString():null;return{time:{ttl_seconds:t.cacheTtlSeconds,burn_after_first_read:r,unlock_at:i,max_opens:r?1:null},identity:{capture:lp(t.sensitivityMode),claim_required:t.sensitivityMode!=="mode-4",allow_magic_link:t.sensitivityMode==="mode-4",allowed_emails:null},device:{binding:dp(t),listed_fingerprints:null},channel:{delivery:up(t),route:Ga(t),channel_constraint:pp(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 hp(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 mp(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 gp(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 Ya=N(ge=>{"use strict";Object.defineProperty(ge,"__esModule",{value:!0});ge.encodeFragment=Xa;ge.decodeFragment=yp;ge.extractProofToken=_p;ge.encodeProofToken=bp;ge.decodeShareCredential=vp;ge.sealBytesForPublicShare=wp;ge.openPublicShare=Ep;ge.wrapFragmentForShortLink=xp;var za=at(),qa=xn();function Pe(e){let t="";for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return btoa(t)}function Ft(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 Ja(e){return Pe(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function Xa(e){return encodeURIComponent(JSON.stringify(e))}function yp(e){let t=JSON.parse(decodeURIComponent(e));if(t.v!==3)throw new Error(`fragment version unsupported: ${t.v}`);return t}function _p(e){return{v:3,kind:"proof",n:e.n,t:e.t,spe:e.spe,spm:e.spm}}function bp(e){return encodeURIComponent(JSON.stringify(e))}function vp(e){let t=e.trim(),n=t.indexOf("#"),r=n>=0?t.slice(n+1):t,i;try{i=JSON.parse(decodeURIComponent(r))}catch(o){throw new Error(`credential parse failed: ${o.message??"invalid_json"}`)}if(i.v!==3)throw new Error(`credential version unsupported: ${String(i.v)}`);return i.kind==="proof"?{kind:"proof",value:i}:{kind:"fragment",value:i}}function kp(){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 Sp(){let e=new Uint8Array(32);return crypto.getRandomValues(e),Ja(e)}async function wp(e){let t=e.bytes,n={name:e.filename,type:e.contentType},r=(0,za.generateHybridKemKeypair)(),i=(0,za.generateHybridSigKeypair)(),o=kp(),a=Sp(),s=await(0,qa.sealHybrid)({plaintext:t,recipientPublicKey:r.publicKey,recipientKid:`ephemeral-${o}`,signerKeypair:i,signerKid:`lock-${o}`,meta:{lockbox_id:o,server:e.server,bearer:a,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=Xa({v:3,n:n.name,t:n.type||"application/octet-stream",rsx:Pe(r.secretKey.x25519),rsm:Pe(r.secretKey.mlKem),rpx:Pe(r.publicKey.x25519),spe:Pe(i.publicKey.ed25519),spm:Pe(i.publicKey.mlDsa)});return{container:s.container,fragment:c,lockboxId:o}}async function Ep(e){let t={x25519:Ft(e.fragment.rsx),mlKem:Ft(e.fragment.rsm)},n=Ft(e.fragment.rpx),r={ed25519:Ft(e.fragment.spe),mlDsa:Ft(e.fragment.spm)},{plaintext:i,header:o}=await(0,qa.openHybrid)({container:e.container,recipientSecretKey:t,recipientPublicX25519:n,signerPublicKey:r});return{plaintext:i,filename:o.original_filename||e.fragment.n,contentType:o.original_content_type||e.fragment.t,signerKid:o.sig.signer_kid,issuedAt:o.issued_at,ciphertextSha256:o.ciphertext_sha256}}async function xp(e){let t=crypto.getRandomValues(new Uint8Array(32)),n=crypto.getRandomValues(new Uint8Array(12)),r=new TextEncoder().encode(e),i=new ArrayBuffer(32);new Uint8Array(i).set(t);let o=new ArrayBuffer(12);new Uint8Array(o).set(n);let a=new ArrayBuffer(r.byteLength);new Uint8Array(a).set(r);let s=await crypto.subtle.importKey("raw",i,{name:"AES-GCM"},!1,["encrypt"]),c=new Uint8Array(await crypto.subtle.encrypt({name:"AES-GCM",iv:o},s,a));return{wrapKeyB64Url:Ja(t),wrappedFragmentB64:Pe(c),wrapIvB64:Pe(n)}}});var ts=N(d=>{"use strict";var Ap=d&&d.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(d,"__esModule",{value:!0});d.PVE_SIGNED_LEN=d.RCPT_VERSION=d.PVE_VERSION=d.RCPT_MAGIC=d.PVE_MAGIC=d.verifyDpop=d.publicJwkFromBytes=d.jwkThumbprint=d.createDpop=d.verifyContainerHeader=d.signContainerHeader=d.sealHybrid=d.openHybrid=d.headerSigningBytes=d.encodeContainerV3=d.decodeContainerV3=d.ContainerV3Error=d.CONTAINER_HEADER_MAX_BYTES=d.CONTAINER_FIXED_PREFIX_BYTES=d.CONTAINER_MAGIC=d.canonicalJson=d.NDC_V03_RATCHET_DOMAIN=d.NDC_V03_CONTENT_KEY_DOMAIN=d.NDC_V03_KEM_DOMAIN=d.NDC_WIRE_V03=d.NDC_WIRE_V1=d.PQ_SIZES=d.PQ_SUITE=d.ratchetAdvance=d.deriveContentKey=d.mlDsa65VerifyDetached=d.mlDsa65SignDetached=d.generateMlDsa65Keypair=d.hybridVerify=d.hybridSign=d.hybridKemDecapsulate=d.hybridKemEncapsulate=d.generateHybridSigKeypair=d.deriveHybridKemKeypairFromSeed=d.generateHybridKemKeypair=d.ALGORITHMS=d.CRYPTO_VERSION=d.NoDataSDK=d.NoDataForms=d.NoDataSystems=d.NoDataWebhook=d.NoDataEmail=d.verifyProofOfWork=d.solveProofOfWork=d.NoDataCrypto=void 0;d.auditChain=d.appendReceipt=d.timeGateEncrypt=d.timeGateDecrypt=d.timeForRound=d.TimeGateError=d.roundForTime=d.makeFakeDrandChain=d.fetchDrandRound=d.drandTimeLockOpen=d.drandTimeLockEncrypt=d.drandTimeLockDecrypt=d.DRAND_LOE_MAINNET=d.watermarkSvgOverlay=d.findLeakSource=d.computeWatermark=d.SegmentError=d.sealSegments=d.openSegments=d.manifestDigest=d.buildCapability=d.splitSecret=d.serializeShare=d.deserializeShare=d.combineShares=d.decodeAttestationPayload=d.verifyCoseSign1Es384=d.verifyAttestation=d.parseAttestation=d.fetchAttestation=d.stepRatchet=d.replayRatchet=d.destroyKey=d.verifyReceiptDelta=d.parseReceiptDelta=d.signReceiptDelta=d.encodeReceiptDeltaSignedBytes=d.verifyPve=d.pveHash=d.parsePve=d.signPve=d.encodePveSignedBytes=d.originJktForPublicKey=d.uuidFromDeltaId=d.deltaIdFromUuid=d.ABSORB_STATUS=d.DELTA_KIND=d.RCPT_TOTAL_LEN=d.RCPT_SIGNED_LEN=d.PVE_TOTAL_LEN=void 0;d.wrapFragmentForShortLink=d.openPublicShare=d.sealBytesForPublicShare=d.decodeShareCredential=d.encodeProofToken=d.extractProofToken=d.decodeFragment=d.encodeFragment=d.v3SealReceiptPayload=d.v3OpenReceiptPayload=d.showcaseChips=d.recommendationToMandate=d.summarise=d.recommend=d.verifyReceipt=d.receiptHash=d.issueReceipt=d.issueGenesisReceipt=d.GENESIS_PREV_HASH=void 0;var Tp=Me();Object.defineProperty(d,"NoDataCrypto",{enumerable:!0,get:function(){return Ap(Tp).default}});var Za=Wo();Object.defineProperty(d,"solveProofOfWork",{enumerable:!0,get:function(){return Za.solveProofOfWork}});Object.defineProperty(d,"verifyProofOfWork",{enumerable:!0,get:function(){return Za.verifyProofOfWork}});var Lt=qo();Object.defineProperty(d,"NoDataEmail",{enumerable:!0,get:function(){return Lt.NoDataEmail}});Object.defineProperty(d,"NoDataWebhook",{enumerable:!0,get:function(){return Lt.NoDataWebhook}});Object.defineProperty(d,"NoDataSystems",{enumerable:!0,get:function(){return Lt.NoDataSystems}});Object.defineProperty(d,"NoDataForms",{enumerable:!0,get:function(){return Lt.NoDataForms}});Object.defineProperty(d,"NoDataSDK",{enumerable:!0,get:function(){return Lt.NoDataSDK}});d.CRYPTO_VERSION="0.2.0";d.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 L=at();Object.defineProperty(d,"generateHybridKemKeypair",{enumerable:!0,get:function(){return L.generateHybridKemKeypair}});Object.defineProperty(d,"deriveHybridKemKeypairFromSeed",{enumerable:!0,get:function(){return L.deriveHybridKemKeypairFromSeed}});Object.defineProperty(d,"generateHybridSigKeypair",{enumerable:!0,get:function(){return L.generateHybridSigKeypair}});Object.defineProperty(d,"hybridKemEncapsulate",{enumerable:!0,get:function(){return L.hybridKemEncapsulate}});Object.defineProperty(d,"hybridKemDecapsulate",{enumerable:!0,get:function(){return L.hybridKemDecapsulate}});Object.defineProperty(d,"hybridSign",{enumerable:!0,get:function(){return L.hybridSign}});Object.defineProperty(d,"hybridVerify",{enumerable:!0,get:function(){return L.hybridVerify}});Object.defineProperty(d,"generateMlDsa65Keypair",{enumerable:!0,get:function(){return L.generateMlDsa65Keypair}});Object.defineProperty(d,"mlDsa65SignDetached",{enumerable:!0,get:function(){return L.mlDsa65SignDetached}});Object.defineProperty(d,"mlDsa65VerifyDetached",{enumerable:!0,get:function(){return L.mlDsa65VerifyDetached}});Object.defineProperty(d,"deriveContentKey",{enumerable:!0,get:function(){return L.deriveContentKey}});Object.defineProperty(d,"ratchetAdvance",{enumerable:!0,get:function(){return L.ratchetAdvance}});Object.defineProperty(d,"PQ_SUITE",{enumerable:!0,get:function(){return L.PQ_SUITE}});Object.defineProperty(d,"PQ_SIZES",{enumerable:!0,get:function(){return L.PQ_SIZES}});Object.defineProperty(d,"NDC_WIRE_V1",{enumerable:!0,get:function(){return L.NDC_WIRE_V1}});Object.defineProperty(d,"NDC_WIRE_V03",{enumerable:!0,get:function(){return L.NDC_WIRE_V03}});Object.defineProperty(d,"NDC_V03_KEM_DOMAIN",{enumerable:!0,get:function(){return L.NDC_V03_KEM_DOMAIN}});Object.defineProperty(d,"NDC_V03_CONTENT_KEY_DOMAIN",{enumerable:!0,get:function(){return L.NDC_V03_CONTENT_KEY_DOMAIN}});Object.defineProperty(d,"NDC_V03_RATCHET_DOMAIN",{enumerable:!0,get:function(){return L.NDC_V03_RATCHET_DOMAIN}});var ae=xn();Object.defineProperty(d,"canonicalJson",{enumerable:!0,get:function(){return ae.canonicalJson}});Object.defineProperty(d,"CONTAINER_MAGIC",{enumerable:!0,get:function(){return ae.CONTAINER_MAGIC}});Object.defineProperty(d,"CONTAINER_FIXED_PREFIX_BYTES",{enumerable:!0,get:function(){return ae.CONTAINER_FIXED_PREFIX_BYTES}});Object.defineProperty(d,"CONTAINER_HEADER_MAX_BYTES",{enumerable:!0,get:function(){return ae.CONTAINER_HEADER_MAX_BYTES}});Object.defineProperty(d,"ContainerV3Error",{enumerable:!0,get:function(){return ae.ContainerV3Error}});Object.defineProperty(d,"decodeContainerV3",{enumerable:!0,get:function(){return ae.decodeContainerV3}});Object.defineProperty(d,"encodeContainerV3",{enumerable:!0,get:function(){return ae.encodeContainerV3}});Object.defineProperty(d,"headerSigningBytes",{enumerable:!0,get:function(){return ae.headerSigningBytes}});Object.defineProperty(d,"openHybrid",{enumerable:!0,get:function(){return ae.openHybrid}});Object.defineProperty(d,"sealHybrid",{enumerable:!0,get:function(){return ae.sealHybrid}});Object.defineProperty(d,"signContainerHeader",{enumerable:!0,get:function(){return ae.signContainerHeader}});Object.defineProperty(d,"verifyContainerHeader",{enumerable:!0,get:function(){return ae.verifyContainerHeader}});var jn=Yr();Object.defineProperty(d,"createDpop",{enumerable:!0,get:function(){return jn.createDpop}});Object.defineProperty(d,"jwkThumbprint",{enumerable:!0,get:function(){return jn.jwkThumbprint}});Object.defineProperty(d,"publicJwkFromBytes",{enumerable:!0,get:function(){return jn.publicJwkFromBytes}});Object.defineProperty(d,"verifyDpop",{enumerable:!0,get:function(){return jn.verifyDpop}});var F=ma();Object.defineProperty(d,"PVE_MAGIC",{enumerable:!0,get:function(){return F.PVE_MAGIC}});Object.defineProperty(d,"RCPT_MAGIC",{enumerable:!0,get:function(){return F.RCPT_MAGIC}});Object.defineProperty(d,"PVE_VERSION",{enumerable:!0,get:function(){return F.PVE_VERSION}});Object.defineProperty(d,"RCPT_VERSION",{enumerable:!0,get:function(){return F.RCPT_VERSION}});Object.defineProperty(d,"PVE_SIGNED_LEN",{enumerable:!0,get:function(){return F.PVE_SIGNED_LEN}});Object.defineProperty(d,"PVE_TOTAL_LEN",{enumerable:!0,get:function(){return F.PVE_TOTAL_LEN}});Object.defineProperty(d,"RCPT_SIGNED_LEN",{enumerable:!0,get:function(){return F.RCPT_SIGNED_LEN}});Object.defineProperty(d,"RCPT_TOTAL_LEN",{enumerable:!0,get:function(){return F.RCPT_TOTAL_LEN}});Object.defineProperty(d,"DELTA_KIND",{enumerable:!0,get:function(){return F.DELTA_KIND}});Object.defineProperty(d,"ABSORB_STATUS",{enumerable:!0,get:function(){return F.ABSORB_STATUS}});Object.defineProperty(d,"deltaIdFromUuid",{enumerable:!0,get:function(){return F.deltaIdFromUuid}});Object.defineProperty(d,"uuidFromDeltaId",{enumerable:!0,get:function(){return F.uuidFromDeltaId}});Object.defineProperty(d,"originJktForPublicKey",{enumerable:!0,get:function(){return F.originJktForPublicKey}});Object.defineProperty(d,"encodePveSignedBytes",{enumerable:!0,get:function(){return F.encodePveSignedBytes}});Object.defineProperty(d,"signPve",{enumerable:!0,get:function(){return F.signPve}});Object.defineProperty(d,"parsePve",{enumerable:!0,get:function(){return F.parsePve}});Object.defineProperty(d,"pveHash",{enumerable:!0,get:function(){return F.pveHash}});Object.defineProperty(d,"verifyPve",{enumerable:!0,get:function(){return F.verifyPve}});Object.defineProperty(d,"encodeReceiptDeltaSignedBytes",{enumerable:!0,get:function(){return F.encodeReceiptSignedBytes}});Object.defineProperty(d,"signReceiptDelta",{enumerable:!0,get:function(){return F.signReceipt}});Object.defineProperty(d,"parseReceiptDelta",{enumerable:!0,get:function(){return F.parseReceipt}});Object.defineProperty(d,"verifyReceiptDelta",{enumerable:!0,get:function(){return F.verifyReceipt}});var ci=ya();Object.defineProperty(d,"destroyKey",{enumerable:!0,get:function(){return ci.destroyKey}});Object.defineProperty(d,"replayRatchet",{enumerable:!0,get:function(){return ci.replayRatchet}});Object.defineProperty(d,"stepRatchet",{enumerable:!0,get:function(){return ci.stepRatchet}});var li=va();Object.defineProperty(d,"fetchAttestation",{enumerable:!0,get:function(){return li.fetchAttestation}});Object.defineProperty(d,"parseAttestation",{enumerable:!0,get:function(){return li.parseAttestation}});Object.defineProperty(d,"verifyAttestation",{enumerable:!0,get:function(){return li.verifyAttestation}});var Qa=ri();Object.defineProperty(d,"verifyCoseSign1Es384",{enumerable:!0,get:function(){return Qa.verifyCoseSign1Es384}});Object.defineProperty(d,"decodeAttestationPayload",{enumerable:!0,get:function(){return Qa.decodeAttestationPayload}});var Bn=wa();Object.defineProperty(d,"combineShares",{enumerable:!0,get:function(){return Bn.combineShares}});Object.defineProperty(d,"deserializeShare",{enumerable:!0,get:function(){return Bn.deserializeShare}});Object.defineProperty(d,"serializeShare",{enumerable:!0,get:function(){return Bn.serializeShare}});Object.defineProperty(d,"splitSecret",{enumerable:!0,get:function(){return Bn.splitSecret}});var Mt=Ta();Object.defineProperty(d,"buildCapability",{enumerable:!0,get:function(){return Mt.buildCapability}});Object.defineProperty(d,"manifestDigest",{enumerable:!0,get:function(){return Mt.manifestDigest}});Object.defineProperty(d,"openSegments",{enumerable:!0,get:function(){return Mt.openSegments}});Object.defineProperty(d,"sealSegments",{enumerable:!0,get:function(){return Mt.sealSegments}});Object.defineProperty(d,"SegmentError",{enumerable:!0,get:function(){return Mt.SegmentError}});var di=$a();Object.defineProperty(d,"computeWatermark",{enumerable:!0,get:function(){return di.computeWatermark}});Object.defineProperty(d,"findLeakSource",{enumerable:!0,get:function(){return di.findLeakSource}});Object.defineProperty(d,"watermarkSvgOverlay",{enumerable:!0,get:function(){return di.watermarkSvgOverlay}});var de=Ba();Object.defineProperty(d,"DRAND_LOE_MAINNET",{enumerable:!0,get:function(){return de.DRAND_LOE_MAINNET}});Object.defineProperty(d,"drandTimeLockDecrypt",{enumerable:!0,get:function(){return de.drandTimeLockDecrypt}});Object.defineProperty(d,"drandTimeLockEncrypt",{enumerable:!0,get:function(){return de.drandTimeLockEncrypt}});Object.defineProperty(d,"drandTimeLockOpen",{enumerable:!0,get:function(){return de.drandTimeLockOpen}});Object.defineProperty(d,"fetchDrandRound",{enumerable:!0,get:function(){return de.fetchDrandRound}});Object.defineProperty(d,"makeFakeDrandChain",{enumerable:!0,get:function(){return de.makeFakeDrandChain}});Object.defineProperty(d,"roundForTime",{enumerable:!0,get:function(){return de.roundForTime}});Object.defineProperty(d,"TimeGateError",{enumerable:!0,get:function(){return de.TimeGateError}});Object.defineProperty(d,"timeForRound",{enumerable:!0,get:function(){return de.timeForRound}});Object.defineProperty(d,"timeGateDecrypt",{enumerable:!0,get:function(){return de.timeGateDecrypt}});Object.defineProperty(d,"timeGateEncrypt",{enumerable:!0,get:function(){return de.timeGateEncrypt}});var We=Ha();Object.defineProperty(d,"appendReceipt",{enumerable:!0,get:function(){return We.appendReceipt}});Object.defineProperty(d,"auditChain",{enumerable:!0,get:function(){return We.auditChain}});Object.defineProperty(d,"GENESIS_PREV_HASH",{enumerable:!0,get:function(){return We.GENESIS_PREV_HASH}});Object.defineProperty(d,"issueGenesisReceipt",{enumerable:!0,get:function(){return We.issueGenesisReceipt}});Object.defineProperty(d,"issueReceipt",{enumerable:!0,get:function(){return We.issueReceipt}});Object.defineProperty(d,"receiptHash",{enumerable:!0,get:function(){return We.receiptHash}});Object.defineProperty(d,"verifyReceipt",{enumerable:!0,get:function(){return We.verifyReceipt}});var es=Va();Object.defineProperty(d,"recommend",{enumerable:!0,get:function(){return es.recommend}});Object.defineProperty(d,"summarise",{enumerable:!0,get:function(){return es.summarise}});var Fn=Wa();Object.defineProperty(d,"recommendationToMandate",{enumerable:!0,get:function(){return Fn.recommendationToMandate}});Object.defineProperty(d,"showcaseChips",{enumerable:!0,get:function(){return Fn.showcaseChips}});Object.defineProperty(d,"v3OpenReceiptPayload",{enumerable:!0,get:function(){return Fn.v3OpenReceiptPayload}});Object.defineProperty(d,"v3SealReceiptPayload",{enumerable:!0,get:function(){return Fn.v3SealReceiptPayload}});var Ie=Ya();Object.defineProperty(d,"encodeFragment",{enumerable:!0,get:function(){return Ie.encodeFragment}});Object.defineProperty(d,"decodeFragment",{enumerable:!0,get:function(){return Ie.decodeFragment}});Object.defineProperty(d,"extractProofToken",{enumerable:!0,get:function(){return Ie.extractProofToken}});Object.defineProperty(d,"encodeProofToken",{enumerable:!0,get:function(){return Ie.encodeProofToken}});Object.defineProperty(d,"decodeShareCredential",{enumerable:!0,get:function(){return Ie.decodeShareCredential}});Object.defineProperty(d,"sealBytesForPublicShare",{enumerable:!0,get:function(){return Ie.sealBytesForPublicShare}});Object.defineProperty(d,"openPublicShare",{enumerable:!0,get:function(){return Ie.openPublicShare}});Object.defineProperty(d,"wrapFragmentForShortLink",{enumerable:!0,get:function(){return Ie.wrapFragmentForShortLink}})});import{McpServer as bh}from"@modelcontextprotocol/sdk/server/mcp.js";import{StdioServerTransport as vh}from"@modelcontextprotocol/sdk/server/stdio.js";import{z as m}from"zod";import{z as Se}from"zod";import{readdirSync as vo,readFileSync as ko,statSync as gr}from"node:fs";import{basename as So,join as _l}from"node:path";var ce={text:[],header:[],secrets:[],table:null};function sr(e){e.table&&(ce.table=e.table);for(let t of e.text??[])ce.text.some(n=>n.kind===t.kind)||ce.text.push(t);e.header&&!ce.header.includes(e.header)&&ce.header.push(e.header);for(let t of e.secrets??[])ce.secrets.some(n=>n.id===t.id)||ce.secrets.push(t)}function rn(){return ce.text}function qi(){return ce.header}function Je(){return ce.table}function Ji(){return ce.secrets}var on=[{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"}];function an(){let e=Ji().filter(t=>!on.some(n=>n.id===t.id));return[...on,...e]}var Xi=/node_modules\/|\.next\/|\.test\.|\.spec\.|__tests__\/|\.env\.example$|\.nodata-proof\.json$|\.git\//,Cc=[{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 Nc(e,t){let n=o=>o.replace(/^[^0-9]*/,"").split(".").map(a=>parseInt(a,10)||0),r=n(e),i=n(t);for(let o=0;o<3;o++){if((r[o]||0)<(i[o]||0))return!0;if((r[o]||0)>(i[o]||0))return!1}return!1}function Yi(e){let t=[],n;try{n=JSON.parse(e)}catch{return t}let r={...n.dependencies??{},...n.devDependencies??{}};for(let[i,o]of Object.entries(r)){let a=(o||"").replace(/^[\^~>=<\s]+/,""),s=Cc.find(c=>c.name===i&&Nc(a,c.below));s&&t.push({name:i,version:a,vuln:s})}return t}var Oc=[{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"}],jc=[{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"}],Bc=/^(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,Fc=/^שם[ _](?:ה)?(?:קובץ|מוצר|פריט|חברה|ארגון|עסק|פרויקט|גיליון|טבלה|שדה|קטגוריה|סניף|בנק|עיר|רחוב|ישוב|יישוב|מסמך|תוכנית|חבילה|קורס|מחלקה|אתר|דומיין|מותג|ספק|שירות|תפקיד)$|^(file|product|item|company|org|organization|project|sheet|table|field|category|branch|bank|city|street|document|plan|course|department|site|domain|brand|vendor|service|role)[ _-]?name$/i;function Ne(e){if(!e)return null;let t=e.trim();if(Bc.test(t)||/^name$/i.test(t))return null;let n=t.replace(/[\s-]+/g,"_");for(let r of[...jc,...Oc])if(r.pattern.test(t)||r.pattern.test(n))return{type:r.type,label:r.label};if(Fc.test(t))return null;if(/^שם[ _][\u0590-\u05FF"'׳ ]{2,20}$/.test(t))return{type:"name",label:"\u05E9\u05DD \u05D0\u05D3\u05DD"};if(/^(customer|client|employee|inspector|supervisor|contact|person|patient|user|owner|manager|agent|member|driver|tenant|student|parent|beneficiary|insured)_?(full_?)?name$/i.test(n))return{type:"name",label:"Person name"};for(let r of qi()){let i=r(t);if(i)return{type:i.type,label:i.label}}return null}var sn={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 cn(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 i=0;i<9;i++){let o=parseInt(n[i]??"0",10)*(i%2+1);o>9&&(o-=9),r+=o}return r%10===0&&parseInt(n,10)>0}var gt=/(?:\+972[\s-]?|0)(?:5[0-9]|[2-4]|[89])(?:[\s-]?\d){7}/g;var yt=/\bIL\d{2}\s?(?:\d{4}\s?){4}\d{3}\b/g;function Lc(e){let t=String(e??"").replace(/\D/g,"");if(t.length<12||t.length>19)return!1;let n=0,r=!1;for(let i=t.length-1;i>=0;i-=1){let o=parseInt(t[i]??"0",10);r&&(o*=2,o>9&&(o-=9)),n+=o,r=!r}return n%10===0}function Mc(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 i of n){let o=i>="A"&&i<="Z"?String(i.charCodeAt(0)-55):i;for(let a of o)r=(r*10+Number(a))%97}return r===1}var cr="(?<!\\d)(?<!\\d[.,])",lr="(?!\\d)(?![.,]\\d)",dr=[{subkind:"israeli_id",severity:"high",pattern:new RegExp(`${cr}\\d{9}${lr}`,"g"),validate:cn,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(`${cr}[2-6][ -]?(?:\\d[ -]?){11,17}\\d${lr}`,"g"),validate:Lc,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:Mc,hint:"Bank account in IBAN form (mod-97 verified) in plaintext."},{subkind:"israeli_phone",severity:"medium",pattern:new RegExp(`${cr}(?:\\+972[- ]?|0)(?:[57]\\d|[2-489])[- ]?\\d{3}[- ]?\\d{4}${lr}`,"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 Zi(e){let t=[];for(let n of dr){n.pattern.lastIndex=0;let r=new Set,i,o=0;for(;(i=n.pattern.exec(e))!==null&&(o+=1,!(o>2e5));){let a=i[0];if(n.validate(a)&&r.add(a.replace(/[\s-]/g,"")),r.size>=1e5)break}r.size>0&&t.push({subkind:n.subkind,severity:n.severity,hint:n.hint,count:r.size})}for(let n of rn()){let r=new Set;for(let i of n.find(e))r.add(e.slice(i.start,i.end).trim());r.size>0&&t.push({subkind:n.kind,severity:n.severity,hint:n.hint,count:r.size})}return t}function Oe(e,t){let n=[],r="",i=!1;for(let o=0;o<e.length;o++){let a=e[o];i?a==='"'&&e[o+1]==='"'?(r+='"',o++):a==='"'?i=!1:r+=a:a==='"'?i=!0:a===t?(n.push(r),r=""):r+=a}return n.push(r),n}import{inflateRawSync as Xc}from"node:zlib";import{inflateSync as Kc}from"node:zlib";var ur=new Set([".pdf"]),Qi=8*1024*1024;function Hc(e){let t=e.toString("latin1"),n=new Map,r=/(\d+)\s+(\d+)\s+obj\b/g,i;for(;(i=r.exec(t))!==null;){let o=Number(i[1]),a=r.lastIndex,s=t.indexOf("endobj",a);if(s<0)continue;let c=t.indexOf("stream",a),l,u=null;if(c>=0&&c<s){l=t.slice(a,c);let p=c+6;t[p]==="\r"&&(p+=1),t[p]===`
|
|
16
|
-
`&&(
|
|
17
|
-
`,a="");continue}if(s.startsWith("("))a+=
|
|
18
|
-
`),n}function
|
|
19
|
-
`)}function
|
|
20
|
-
`),truncated:s,streams:a}}var
|
|
15
|
+
</svg>`}function Ps(e){let t="";for(let n=0;n<e.length;n++)t+=e[n].toString(16).padStart(2,"0");return t}});var Bs=O(Y=>{"use strict";Object.defineProperty(Y,"__esModule",{value:!0});Y.DRAND_LOE_MAINNET=Y.TimeGateError=void 0;Y.timeGateEncrypt=rf;Y.timeGateDecrypt=of;Y.roundForTime=af;Y.timeForRound=sf;Y.drandTimeLockEncrypt=lf;Y.drandTimeLockDecrypt=js;Y.makeFakeDrandChain=df;Y.fetchDrandRound=Ls;Y.drandTimeLockOpen=pf;var _e=D("@noble/curves/bls12-381.js"),tr=D("@noble/hashes/sha2.js"),Ce=e=>e,Cs="NDC-v0.3-server-time-gate";async function rf(e){let t=crypto.getRandomValues(new Uint8Array(12)),n=new TextEncoder().encode(`${Cs}|${e.notBeforeUnixSec}`),r=await crypto.subtle.importKey("raw",Ce(e.serverWrapKey),{name:"AES-GCM"},!1,["encrypt"]),i=await crypto.subtle.encrypt({name:"AES-GCM",iv:Ce(t),additionalData:Ce(n)},r,Ce(e.plaintext));return{variant:"server-attested",notBeforeUnixSec:e.notBeforeUnixSec,iv_b64:Qn(t),ciphertext_b64:Qn(new Uint8Array(i))}}var Zt=class extends Error{constructor(t,n){super(n),this.name="TimeGateError",this.code=t}};Y.TimeGateError=Zt;async function of(e){if(e.currentUnixSec<e.ciphertext.notBeforeUnixSec)throw new Zt("not_yet",`time-gate not yet open: now ${e.currentUnixSec} < notBefore ${e.ciphertext.notBeforeUnixSec}`);let t=new TextEncoder().encode(`${Cs}|${e.ciphertext.notBeforeUnixSec}`),n=await crypto.subtle.importKey("raw",Ce(e.serverWrapKey),{name:"AES-GCM"},!1,["decrypt"]);try{let r=await crypto.subtle.decrypt({name:"AES-GCM",iv:Ce(er(e.ciphertext.iv_b64)),additionalData:Ce(t)},n,Ce(er(e.ciphertext.ciphertext_b64)));return new Uint8Array(r)}catch{throw new Zt("tamper_detected","AES-GCM authentication tag failed \u2014 ciphertext or AAD tampered")}}Y.DRAND_LOE_MAINNET={publicKeyHex:"868f005eb8e6e4ca0a47c8a77ceaa5309a47978a7c71bc5cce96366b5d7a569937c529eeda66c7293784a9402801af31",chainHashHex:"8990e7a9aaed2ffed73dbd7092123d6f289930540d7651336225dc172e51b2ce",genesisUnixSec:1595431050,periodSec:30,hashDst:"BLS_SIG_BLS12381G2_XMD:SHA-256_SSWU_RO_NUL_"};function af(e,t){return e<=t.genesisUnixSec?1:Math.ceil((e-t.genesisUnixSec)/t.periodSec)}function sf(e,t){return t.genesisUnixSec+e*t.periodSec}function Ns(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,tr.sha256)(t)}function Os(e){let t=new Uint8Array(576),n=0;for(let r of[e.c0,e.c1])for(let i of[r.c0,r.c1,r.c2])for(let o of[i.c0,i.c1])cf(o,t,n,48),n+=48;return t}function cf(e,t,n,r){let i=e,o=BigInt(255),a=BigInt(8);for(let s=r-1;s>=0;s--)t[n+s]=Number(i&o),i>>=a}function lf(e,t,n,r){if(e.length!==32)throw new Error(`drand-IBE expects a 32-byte content key, got ${e.length}`);let i=_e.bls12_381.G1.Point,o=_e.bls12_381.fields.Fr,a=i.fromBytes(n),s;do s=ff(crypto.getRandomValues(new Uint8Array(32)))%o.ORDER;while(s===BigInt(0));let c=i.BASE.multiply(s),l=_e.bls12_381.longSignatures.hash(Ns(t),r.hashDst),p=a.multiply(s),u=_e.bls12_381.pairing(p,l,!0),f=(0,tr.sha256)(Os(u)),h=new Uint8Array(32);for(let _=0;_<32;_++)h[_]=e[_]^f[_];return{variant:"drand-ibe",chainHashHex:r.chainHashHex,round:t,u_b64:Qn(c.toBytes()),v_b64:Qn(h)}}function js(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=_e.bls12_381.G1.Point.fromBytes(er(e.ciphertext.u_b64)),r=_e.bls12_381.longSignatures.Signature.fromBytes(e.roundSignature),i=_e.bls12_381.pairing(n,r,!0),o=(0,tr.sha256)(Os(i)),a=er(e.ciphertext.v_b64);if(a.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]=a[c]^o[c];return s}function df(e){let t;if(e&&e.length===48)t=e;else{t=new Uint8Array(48);let o=e??crypto.getRandomValues(new Uint8Array(48));t.set(o.slice(0,48),0)}let{secretKey:n,publicKey:r}=_e.bls12_381.longSignatures.keygen(t),i={publicKeyHex:Ds(r.toBytes()),chainHashHex:Ds((0,tr.sha256)(r.toBytes())),genesisUnixSec:17e8,periodSec:30,hashDst:"BLS_SIG_BLS12381G2_XMD:SHA-256_SSWU_RO_NUL_"};return{config:i,publicKey:r.toBytes(),signRound(o){let a=_e.bls12_381.longSignatures.hash(Ns(o),i.hashDst);return _e.bls12_381.longSignatures.sign(a,n).toBytes()}}}function Ds(e){let t="";for(let n=0;n<e.length;n++)t+=e[n].toString(16).padStart(2,"0");return t}function uf(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 Ls(e,t,n={}){let r=n.fetchImpl??fetch,i=n.timeoutMs??8e3,o=`${t.replace(/\/$/,"")}/public/${e}`,a,s;typeof AbortController<"u"&&(a=new AbortController,s=setTimeout(()=>a.abort(),i));let c;try{c=await r(o,{signal:a?.signal})}finally{s&&clearTimeout(s)}if(!c.ok)throw new Error(`drand fetch failed: ${o} \u2192 HTTP ${c.status}`);let l=await c.json();if(typeof l.round!="number"||typeof l.signature!="string"||typeof l.randomness!="string")throw new Error(`drand response malformed at ${o}`);let p=uf(l.signature);if(p.length!==96)throw new Error(`drand signature wrong length: expected 96 bytes (compressed G2), got ${p.length}`);return{round:l.round,randomness_hex:l.randomness,signature_bytes:p,previous_signature_hex:l.previous_signature}}async function pf(e,t,n,r={}){let i=await Ls(e.round,t,r);return js({ciphertext:e,roundSignature:i.signature_bytes,chain:n})}function Qn(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 er(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 ff(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 Us=O(se=>{"use strict";Object.defineProperty(se,"__esModule",{value:!0});se.GENESIS_PREV_HASH=void 0;se.receiptHash=Di;se.issueReceipt=Ci;se.verifyReceipt=Hs;se.auditChain=gf;se.issueGenesisReceipt=yf;se.appendReceipt=_f;var hf=D("@noble/hashes/sha2.js"),Ri=Wn(),Ks=yt();se.GENESIS_PREV_HASH="0".repeat(64);var Fs=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)},Ms=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},mf=e=>{let t="";for(let n=0;n<e.length;n++)t+=e[n].toString(16).padStart(2,"0");return t};function Di(e){return mf((0,hf.sha256)(new TextEncoder().encode((0,Ri.canonicalJson)(e))))}function Ci(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,Ri.canonicalJson)(t)),r=(0,Ks.hybridSign)(e.signing_key.secretKey,n);return{body:t,sig:{signer_kid:e.signer_kid,ed25519_b64:Fs(r.ed25519),ml_dsa_65_b64:Fs(r.mlDsa)}}}function Hs(e,t){let n=new TextEncoder().encode((0,Ri.canonicalJson)(e.body)),r={ed25519:Ms(e.sig.ed25519_b64),mlDsa:Ms(e.sig.ml_dsa_65_b64)};return(0,Ks.hybridVerify)(t,n,r)}function gf(e,t,n=1){if(e.length===0)return{ok:!0,receipts_checked:0};let r=n,i=n===1?se.GENESIS_PREV_HASH:null;for(let o of e){if(o.body.sequence!==r)return{ok:!1,code:o.body.sequence<r?"duplicate_sequence":"out_of_order",at_sequence:o.body.sequence,reason:`expected sequence ${r}, got ${o.body.sequence}`};if(i!==null&&o.body.prev_hash!==i)return{ok:!1,code:r===1?"missing_genesis":"broken_prev_hash",at_sequence:o.body.sequence,reason:`prev_hash mismatch: expected ${i.slice(0,16)}\u2026, got ${o.body.prev_hash.slice(0,16)}\u2026`};if(!Hs(o,t))return{ok:!1,code:"bad_signature",at_sequence:o.body.sequence,reason:"hybrid signature does not verify"};i=Di(o.body),r+=1}return{ok:!0,receipts_checked:e.length}}function yf(e){return Ci({event_type:e.initial_event,lockbox_id:e.lockbox_id,prev_hash:se.GENESIS_PREV_HASH,sequence:1,payload:e.initial_payload,signer_kid:e.signer_kid,signing_key:e.signing_key,iat:e.iat})}function _f(e,t){return Ci({...t,prev_hash:Di(e.body),sequence:e.body.sequence+1})}});var Gs=O(nr=>{"use strict";Object.defineProperty(nr,"__esModule",{value:!0});nr.recommend=Ef;nr.summarise=xf;var bf={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"}},vf={"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}},kf={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"]}},wf=[{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"}],Vs={"mode-4":1,"mode-4p":2,"mode-4h":3,"mode-6":4};function Sf(e,t){return Vs[e]>=Vs[t]?e:t}function Ef(e){let t=bf[e.orgType],n=vf[e.fileClass],r=kf[e.channel],i=Sf(t.mode,n.minMode);e.recipientLacksPasskey&&i==="mode-4h"&&(i="mode-4p");let o=Math.min(t.ttlSeconds,n.maxTtlSeconds),a={forensicWatermark:t.forensicWatermark||n.watermarkRequired,selectiveDisclosureSegments:n.selectiveDisclosure||!!e.perRecipientPolicy,thresholdKofN:e.multipleApproversRequired??null,teeAttestation:t.teeAttestation||n.teeRequired,perOpenRatchet:i==="mode-4h"||i==="mode-4p"||i==="mode-6",dpopRequired:i!=="mode-4",timelockDrand:!!e.timeLockUnixSec&&!!e.timeLockDecentralized,timelockServerGate:!!e.timeLockUnixSec&&!e.timeLockDecentralized},s={...r,adapterCandidates:[...r.adapters]},c=[...s.notes],l=wf.find(p=>p.channel===e.channel&&p.fileClass===e.fileClass);return l&&(c.unshift(`\u26A0 ${l.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:i,cacheTtlSeconds:o,features:a,delivery:{deliveryMode:s.deliveryMode,adapterCandidates:s.adapterCandidates},notes:c}}function xf(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 zs=O(St=>{"use strict";Object.defineProperty(St,"__esModule",{value:!0});St.recommendationToMandate=$f;St.v3SealReceiptPayload=Rf;St.v3OpenReceiptPayload=Df;St.showcaseChips=Cf;function Af(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 Tf(e){return e.features.dpopRequired?"device_mfa":e.sensitivityMode==="mode-4h"?"first_device":e.sensitivityMode==="mode-4"?"any":"first_device"}function If(e){return e.delivery.deliveryMode==="attachment"?"file":e.delivery.deliveryMode==="link"?"link":"view_only"}function Ws(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 Pf(e){let t=Ws(e);return t==="m365"?"m365_only":t==="in_app"?"in_app":"any"}function $f(e){let{recommendation:t,source:n}=e,r=t.sensitivityMode==="mode-6",i=n.timeLockUnixSec?new Date(n.timeLockUnixSec*1e3).toISOString():null;return{time:{ttl_seconds:t.cacheTtlSeconds,burn_after_first_read:r,unlock_at:i,max_opens:r?1:null},identity:{capture:Af(t.sensitivityMode),claim_required:t.sensitivityMode!=="mode-4",allow_magic_link:t.sensitivityMode==="mode-4",allowed_emails:null},device:{binding:Tf(t),listed_fingerprints:null},channel:{delivery:If(t),route:Ws(t),channel_constraint:Pf(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 Rf(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 Df(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 Cf(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 Zs=O(be=>{"use strict";Object.defineProperty(be,"__esModule",{value:!0});be.encodeFragment=Ys;be.decodeFragment=Nf;be.extractProofToken=Of;be.encodeProofToken=jf;be.decodeShareCredential=Lf;be.sealBytesForPublicShare=Mf;be.openPublicShare=Kf;be.wrapFragmentForShortLink=Hf;var qs=yt(),Js=Wn();function Ne(e){let t="";for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return btoa(t)}function Qt(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 Xs(e){return Ne(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function Ys(e){return encodeURIComponent(JSON.stringify(e))}function Nf(e){let t=JSON.parse(decodeURIComponent(e));if(t.v!==3)throw new Error(`fragment version unsupported: ${t.v}`);return t}function Of(e){return{v:3,kind:"proof",n:e.n,t:e.t,spe:e.spe,spm:e.spm}}function jf(e){return encodeURIComponent(JSON.stringify(e))}function Lf(e){let t=e.trim(),n=t.indexOf("#"),r=n>=0?t.slice(n+1):t,i;try{i=JSON.parse(decodeURIComponent(r))}catch(o){throw new Error(`credential parse failed: ${o.message??"invalid_json"}`)}if(i.v!==3)throw new Error(`credential version unsupported: ${String(i.v)}`);return i.kind==="proof"?{kind:"proof",value:i}:{kind:"fragment",value:i}}function Bf(){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 Ff(){let e=new Uint8Array(32);return crypto.getRandomValues(e),Xs(e)}async function Mf(e){let t=e.bytes,n={name:e.filename,type:e.contentType},r=(0,qs.generateHybridKemKeypair)(),i=(0,qs.generateHybridSigKeypair)(),o=Bf(),a=Ff(),s=await(0,Js.sealHybrid)({plaintext:t,recipientPublicKey:r.publicKey,recipientKid:`ephemeral-${o}`,signerKeypair:i,signerKid:`lock-${o}`,meta:{lockbox_id:o,server:e.server,bearer:a,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=Ys({v:3,n:n.name,t:n.type||"application/octet-stream",rsx:Ne(r.secretKey.x25519),rsm:Ne(r.secretKey.mlKem),rpx:Ne(r.publicKey.x25519),spe:Ne(i.publicKey.ed25519),spm:Ne(i.publicKey.mlDsa)});return{container:s.container,fragment:c,lockboxId:o}}async function Kf(e){let t={x25519:Qt(e.fragment.rsx),mlKem:Qt(e.fragment.rsm)},n=Qt(e.fragment.rpx),r={ed25519:Qt(e.fragment.spe),mlDsa:Qt(e.fragment.spm)},{plaintext:i,header:o}=await(0,Js.openHybrid)({container:e.container,recipientSecretKey:t,recipientPublicX25519:n,signerPublicKey:r});return{plaintext:i,filename:o.original_filename||e.fragment.n,contentType:o.original_content_type||e.fragment.t,signerKid:o.sig.signer_kid,issuedAt:o.issued_at,ciphertextSha256:o.ciphertext_sha256}}async function Hf(e){let t=crypto.getRandomValues(new Uint8Array(32)),n=crypto.getRandomValues(new Uint8Array(12)),r=new TextEncoder().encode(e),i=new ArrayBuffer(32);new Uint8Array(i).set(t);let o=new ArrayBuffer(12);new Uint8Array(o).set(n);let a=new ArrayBuffer(r.byteLength);new Uint8Array(a).set(r);let s=await crypto.subtle.importKey("raw",i,{name:"AES-GCM"},!1,["encrypt"]),c=new Uint8Array(await crypto.subtle.encrypt({name:"AES-GCM",iv:o},s,a));return{wrapKeyB64Url:Xs(t),wrappedFragmentB64:Ne(c),wrapIvB64:Ne(n)}}});var nc=O(d=>{"use strict";var Uf=d&&d.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(d,"__esModule",{value:!0});d.PVE_SIGNED_LEN=d.RCPT_VERSION=d.PVE_VERSION=d.RCPT_MAGIC=d.PVE_MAGIC=d.verifyDpop=d.publicJwkFromBytes=d.jwkThumbprint=d.createDpop=d.verifyContainerHeader=d.signContainerHeader=d.sealHybrid=d.openHybrid=d.headerSigningBytes=d.encodeContainerV3=d.decodeContainerV3=d.ContainerV3Error=d.CONTAINER_HEADER_MAX_BYTES=d.CONTAINER_FIXED_PREFIX_BYTES=d.CONTAINER_MAGIC=d.canonicalJson=d.NDC_V03_RATCHET_DOMAIN=d.NDC_V03_CONTENT_KEY_DOMAIN=d.NDC_V03_KEM_DOMAIN=d.NDC_WIRE_V03=d.NDC_WIRE_V1=d.PQ_SIZES=d.PQ_SUITE=d.ratchetAdvance=d.deriveContentKey=d.mlDsa65VerifyDetached=d.mlDsa65SignDetached=d.generateMlDsa65Keypair=d.hybridVerify=d.hybridSign=d.hybridKemDecapsulate=d.hybridKemEncapsulate=d.generateHybridSigKeypair=d.deriveHybridKemKeypairFromSeed=d.generateHybridKemKeypair=d.ALGORITHMS=d.CRYPTO_VERSION=d.NoDataSDK=d.NoDataForms=d.NoDataSystems=d.NoDataWebhook=d.NoDataEmail=d.verifyProofOfWork=d.solveProofOfWork=d.NoDataCrypto=void 0;d.auditChain=d.appendReceipt=d.timeGateEncrypt=d.timeGateDecrypt=d.timeForRound=d.TimeGateError=d.roundForTime=d.makeFakeDrandChain=d.fetchDrandRound=d.drandTimeLockOpen=d.drandTimeLockEncrypt=d.drandTimeLockDecrypt=d.DRAND_LOE_MAINNET=d.watermarkSvgOverlay=d.findLeakSource=d.computeWatermark=d.SegmentError=d.sealSegments=d.openSegments=d.manifestDigest=d.buildCapability=d.splitSecret=d.serializeShare=d.deserializeShare=d.combineShares=d.decodeAttestationPayload=d.verifyCoseSign1Es384=d.verifyAttestation=d.parseAttestation=d.fetchAttestation=d.stepRatchet=d.replayRatchet=d.destroyKey=d.verifyReceiptDelta=d.parseReceiptDelta=d.signReceiptDelta=d.encodeReceiptDeltaSignedBytes=d.verifyPve=d.pveHash=d.parsePve=d.signPve=d.encodePveSignedBytes=d.originJktForPublicKey=d.uuidFromDeltaId=d.deltaIdFromUuid=d.ABSORB_STATUS=d.DELTA_KIND=d.RCPT_TOTAL_LEN=d.RCPT_SIGNED_LEN=d.PVE_TOTAL_LEN=void 0;d.wrapFragmentForShortLink=d.openPublicShare=d.sealBytesForPublicShare=d.decodeShareCredential=d.encodeProofToken=d.extractProofToken=d.decodeFragment=d.encodeFragment=d.v3SealReceiptPayload=d.v3OpenReceiptPayload=d.showcaseChips=d.recommendationToMandate=d.summarise=d.recommend=d.verifyReceipt=d.receiptHash=d.issueReceipt=d.issueGenesisReceipt=d.GENESIS_PREV_HASH=void 0;var Vf=We();Object.defineProperty(d,"NoDataCrypto",{enumerable:!0,get:function(){return Uf(Vf).default}});var Qs=za();Object.defineProperty(d,"solveProofOfWork",{enumerable:!0,get:function(){return Qs.solveProofOfWork}});Object.defineProperty(d,"verifyProofOfWork",{enumerable:!0,get:function(){return Qs.verifyProofOfWork}});var en=Ja();Object.defineProperty(d,"NoDataEmail",{enumerable:!0,get:function(){return en.NoDataEmail}});Object.defineProperty(d,"NoDataWebhook",{enumerable:!0,get:function(){return en.NoDataWebhook}});Object.defineProperty(d,"NoDataSystems",{enumerable:!0,get:function(){return en.NoDataSystems}});Object.defineProperty(d,"NoDataForms",{enumerable:!0,get:function(){return en.NoDataForms}});Object.defineProperty(d,"NoDataSDK",{enumerable:!0,get:function(){return en.NoDataSDK}});d.CRYPTO_VERSION="0.2.0";d.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 K=yt();Object.defineProperty(d,"generateHybridKemKeypair",{enumerable:!0,get:function(){return K.generateHybridKemKeypair}});Object.defineProperty(d,"deriveHybridKemKeypairFromSeed",{enumerable:!0,get:function(){return K.deriveHybridKemKeypairFromSeed}});Object.defineProperty(d,"generateHybridSigKeypair",{enumerable:!0,get:function(){return K.generateHybridSigKeypair}});Object.defineProperty(d,"hybridKemEncapsulate",{enumerable:!0,get:function(){return K.hybridKemEncapsulate}});Object.defineProperty(d,"hybridKemDecapsulate",{enumerable:!0,get:function(){return K.hybridKemDecapsulate}});Object.defineProperty(d,"hybridSign",{enumerable:!0,get:function(){return K.hybridSign}});Object.defineProperty(d,"hybridVerify",{enumerable:!0,get:function(){return K.hybridVerify}});Object.defineProperty(d,"generateMlDsa65Keypair",{enumerable:!0,get:function(){return K.generateMlDsa65Keypair}});Object.defineProperty(d,"mlDsa65SignDetached",{enumerable:!0,get:function(){return K.mlDsa65SignDetached}});Object.defineProperty(d,"mlDsa65VerifyDetached",{enumerable:!0,get:function(){return K.mlDsa65VerifyDetached}});Object.defineProperty(d,"deriveContentKey",{enumerable:!0,get:function(){return K.deriveContentKey}});Object.defineProperty(d,"ratchetAdvance",{enumerable:!0,get:function(){return K.ratchetAdvance}});Object.defineProperty(d,"PQ_SUITE",{enumerable:!0,get:function(){return K.PQ_SUITE}});Object.defineProperty(d,"PQ_SIZES",{enumerable:!0,get:function(){return K.PQ_SIZES}});Object.defineProperty(d,"NDC_WIRE_V1",{enumerable:!0,get:function(){return K.NDC_WIRE_V1}});Object.defineProperty(d,"NDC_WIRE_V03",{enumerable:!0,get:function(){return K.NDC_WIRE_V03}});Object.defineProperty(d,"NDC_V03_KEM_DOMAIN",{enumerable:!0,get:function(){return K.NDC_V03_KEM_DOMAIN}});Object.defineProperty(d,"NDC_V03_CONTENT_KEY_DOMAIN",{enumerable:!0,get:function(){return K.NDC_V03_CONTENT_KEY_DOMAIN}});Object.defineProperty(d,"NDC_V03_RATCHET_DOMAIN",{enumerable:!0,get:function(){return K.NDC_V03_RATCHET_DOMAIN}});var ce=Wn();Object.defineProperty(d,"canonicalJson",{enumerable:!0,get:function(){return ce.canonicalJson}});Object.defineProperty(d,"CONTAINER_MAGIC",{enumerable:!0,get:function(){return ce.CONTAINER_MAGIC}});Object.defineProperty(d,"CONTAINER_FIXED_PREFIX_BYTES",{enumerable:!0,get:function(){return ce.CONTAINER_FIXED_PREFIX_BYTES}});Object.defineProperty(d,"CONTAINER_HEADER_MAX_BYTES",{enumerable:!0,get:function(){return ce.CONTAINER_HEADER_MAX_BYTES}});Object.defineProperty(d,"ContainerV3Error",{enumerable:!0,get:function(){return ce.ContainerV3Error}});Object.defineProperty(d,"decodeContainerV3",{enumerable:!0,get:function(){return ce.decodeContainerV3}});Object.defineProperty(d,"encodeContainerV3",{enumerable:!0,get:function(){return ce.encodeContainerV3}});Object.defineProperty(d,"headerSigningBytes",{enumerable:!0,get:function(){return ce.headerSigningBytes}});Object.defineProperty(d,"openHybrid",{enumerable:!0,get:function(){return ce.openHybrid}});Object.defineProperty(d,"sealHybrid",{enumerable:!0,get:function(){return ce.sealHybrid}});Object.defineProperty(d,"signContainerHeader",{enumerable:!0,get:function(){return ce.signContainerHeader}});Object.defineProperty(d,"verifyContainerHeader",{enumerable:!0,get:function(){return ce.verifyContainerHeader}});var rr=Si();Object.defineProperty(d,"createDpop",{enumerable:!0,get:function(){return rr.createDpop}});Object.defineProperty(d,"jwkThumbprint",{enumerable:!0,get:function(){return rr.jwkThumbprint}});Object.defineProperty(d,"publicJwkFromBytes",{enumerable:!0,get:function(){return rr.publicJwkFromBytes}});Object.defineProperty(d,"verifyDpop",{enumerable:!0,get:function(){return rr.verifyDpop}});var F=gs();Object.defineProperty(d,"PVE_MAGIC",{enumerable:!0,get:function(){return F.PVE_MAGIC}});Object.defineProperty(d,"RCPT_MAGIC",{enumerable:!0,get:function(){return F.RCPT_MAGIC}});Object.defineProperty(d,"PVE_VERSION",{enumerable:!0,get:function(){return F.PVE_VERSION}});Object.defineProperty(d,"RCPT_VERSION",{enumerable:!0,get:function(){return F.RCPT_VERSION}});Object.defineProperty(d,"PVE_SIGNED_LEN",{enumerable:!0,get:function(){return F.PVE_SIGNED_LEN}});Object.defineProperty(d,"PVE_TOTAL_LEN",{enumerable:!0,get:function(){return F.PVE_TOTAL_LEN}});Object.defineProperty(d,"RCPT_SIGNED_LEN",{enumerable:!0,get:function(){return F.RCPT_SIGNED_LEN}});Object.defineProperty(d,"RCPT_TOTAL_LEN",{enumerable:!0,get:function(){return F.RCPT_TOTAL_LEN}});Object.defineProperty(d,"DELTA_KIND",{enumerable:!0,get:function(){return F.DELTA_KIND}});Object.defineProperty(d,"ABSORB_STATUS",{enumerable:!0,get:function(){return F.ABSORB_STATUS}});Object.defineProperty(d,"deltaIdFromUuid",{enumerable:!0,get:function(){return F.deltaIdFromUuid}});Object.defineProperty(d,"uuidFromDeltaId",{enumerable:!0,get:function(){return F.uuidFromDeltaId}});Object.defineProperty(d,"originJktForPublicKey",{enumerable:!0,get:function(){return F.originJktForPublicKey}});Object.defineProperty(d,"encodePveSignedBytes",{enumerable:!0,get:function(){return F.encodePveSignedBytes}});Object.defineProperty(d,"signPve",{enumerable:!0,get:function(){return F.signPve}});Object.defineProperty(d,"parsePve",{enumerable:!0,get:function(){return F.parsePve}});Object.defineProperty(d,"pveHash",{enumerable:!0,get:function(){return F.pveHash}});Object.defineProperty(d,"verifyPve",{enumerable:!0,get:function(){return F.verifyPve}});Object.defineProperty(d,"encodeReceiptDeltaSignedBytes",{enumerable:!0,get:function(){return F.encodeReceiptSignedBytes}});Object.defineProperty(d,"signReceiptDelta",{enumerable:!0,get:function(){return F.signReceipt}});Object.defineProperty(d,"parseReceiptDelta",{enumerable:!0,get:function(){return F.parseReceipt}});Object.defineProperty(d,"verifyReceiptDelta",{enumerable:!0,get:function(){return F.verifyReceipt}});var Ni=_s();Object.defineProperty(d,"destroyKey",{enumerable:!0,get:function(){return Ni.destroyKey}});Object.defineProperty(d,"replayRatchet",{enumerable:!0,get:function(){return Ni.replayRatchet}});Object.defineProperty(d,"stepRatchet",{enumerable:!0,get:function(){return Ni.stepRatchet}});var Oi=ks();Object.defineProperty(d,"fetchAttestation",{enumerable:!0,get:function(){return Oi.fetchAttestation}});Object.defineProperty(d,"parseAttestation",{enumerable:!0,get:function(){return Oi.parseAttestation}});Object.defineProperty(d,"verifyAttestation",{enumerable:!0,get:function(){return Oi.verifyAttestation}});var ec=Pi();Object.defineProperty(d,"verifyCoseSign1Es384",{enumerable:!0,get:function(){return ec.verifyCoseSign1Es384}});Object.defineProperty(d,"decodeAttestationPayload",{enumerable:!0,get:function(){return ec.decodeAttestationPayload}});var ir=Es();Object.defineProperty(d,"combineShares",{enumerable:!0,get:function(){return ir.combineShares}});Object.defineProperty(d,"deserializeShare",{enumerable:!0,get:function(){return ir.deserializeShare}});Object.defineProperty(d,"serializeShare",{enumerable:!0,get:function(){return ir.serializeShare}});Object.defineProperty(d,"splitSecret",{enumerable:!0,get:function(){return ir.splitSecret}});var tn=Is();Object.defineProperty(d,"buildCapability",{enumerable:!0,get:function(){return tn.buildCapability}});Object.defineProperty(d,"manifestDigest",{enumerable:!0,get:function(){return tn.manifestDigest}});Object.defineProperty(d,"openSegments",{enumerable:!0,get:function(){return tn.openSegments}});Object.defineProperty(d,"sealSegments",{enumerable:!0,get:function(){return tn.sealSegments}});Object.defineProperty(d,"SegmentError",{enumerable:!0,get:function(){return tn.SegmentError}});var ji=Rs();Object.defineProperty(d,"computeWatermark",{enumerable:!0,get:function(){return ji.computeWatermark}});Object.defineProperty(d,"findLeakSource",{enumerable:!0,get:function(){return ji.findLeakSource}});Object.defineProperty(d,"watermarkSvgOverlay",{enumerable:!0,get:function(){return ji.watermarkSvgOverlay}});var pe=Bs();Object.defineProperty(d,"DRAND_LOE_MAINNET",{enumerable:!0,get:function(){return pe.DRAND_LOE_MAINNET}});Object.defineProperty(d,"drandTimeLockDecrypt",{enumerable:!0,get:function(){return pe.drandTimeLockDecrypt}});Object.defineProperty(d,"drandTimeLockEncrypt",{enumerable:!0,get:function(){return pe.drandTimeLockEncrypt}});Object.defineProperty(d,"drandTimeLockOpen",{enumerable:!0,get:function(){return pe.drandTimeLockOpen}});Object.defineProperty(d,"fetchDrandRound",{enumerable:!0,get:function(){return pe.fetchDrandRound}});Object.defineProperty(d,"makeFakeDrandChain",{enumerable:!0,get:function(){return pe.makeFakeDrandChain}});Object.defineProperty(d,"roundForTime",{enumerable:!0,get:function(){return pe.roundForTime}});Object.defineProperty(d,"TimeGateError",{enumerable:!0,get:function(){return pe.TimeGateError}});Object.defineProperty(d,"timeForRound",{enumerable:!0,get:function(){return pe.timeForRound}});Object.defineProperty(d,"timeGateDecrypt",{enumerable:!0,get:function(){return pe.timeGateDecrypt}});Object.defineProperty(d,"timeGateEncrypt",{enumerable:!0,get:function(){return pe.timeGateEncrypt}});var Ze=Us();Object.defineProperty(d,"appendReceipt",{enumerable:!0,get:function(){return Ze.appendReceipt}});Object.defineProperty(d,"auditChain",{enumerable:!0,get:function(){return Ze.auditChain}});Object.defineProperty(d,"GENESIS_PREV_HASH",{enumerable:!0,get:function(){return Ze.GENESIS_PREV_HASH}});Object.defineProperty(d,"issueGenesisReceipt",{enumerable:!0,get:function(){return Ze.issueGenesisReceipt}});Object.defineProperty(d,"issueReceipt",{enumerable:!0,get:function(){return Ze.issueReceipt}});Object.defineProperty(d,"receiptHash",{enumerable:!0,get:function(){return Ze.receiptHash}});Object.defineProperty(d,"verifyReceipt",{enumerable:!0,get:function(){return Ze.verifyReceipt}});var tc=Gs();Object.defineProperty(d,"recommend",{enumerable:!0,get:function(){return tc.recommend}});Object.defineProperty(d,"summarise",{enumerable:!0,get:function(){return tc.summarise}});var or=zs();Object.defineProperty(d,"recommendationToMandate",{enumerable:!0,get:function(){return or.recommendationToMandate}});Object.defineProperty(d,"showcaseChips",{enumerable:!0,get:function(){return or.showcaseChips}});Object.defineProperty(d,"v3OpenReceiptPayload",{enumerable:!0,get:function(){return or.v3OpenReceiptPayload}});Object.defineProperty(d,"v3SealReceiptPayload",{enumerable:!0,get:function(){return or.v3SealReceiptPayload}});var Oe=Zs();Object.defineProperty(d,"encodeFragment",{enumerable:!0,get:function(){return Oe.encodeFragment}});Object.defineProperty(d,"decodeFragment",{enumerable:!0,get:function(){return Oe.decodeFragment}});Object.defineProperty(d,"extractProofToken",{enumerable:!0,get:function(){return Oe.extractProofToken}});Object.defineProperty(d,"encodeProofToken",{enumerable:!0,get:function(){return Oe.encodeProofToken}});Object.defineProperty(d,"decodeShareCredential",{enumerable:!0,get:function(){return Oe.decodeShareCredential}});Object.defineProperty(d,"sealBytesForPublicShare",{enumerable:!0,get:function(){return Oe.sealBytesForPublicShare}});Object.defineProperty(d,"openPublicShare",{enumerable:!0,get:function(){return Oe.openPublicShare}});Object.defineProperty(d,"wrapFragmentForShortLink",{enumerable:!0,get:function(){return Oe.wrapFragmentForShortLink}})});import{McpServer as $m}from"@modelcontextprotocol/sdk/server/mcp.js";import{StdioServerTransport as Rm}from"@modelcontextprotocol/sdk/server/stdio.js";import{z as g}from"zod";import{z as he}from"zod";import{readdirSync as qo,readFileSync as Jo,statSync as Dn}from"node:fs";import{basename as Xo,join as Or}from"node:path";var le={text:[],header:[],secrets:[],table:null};function Ar(e){e.table&&(le.table=e.table);for(let t of e.text??[])le.text.some(n=>n.kind===t.kind)||le.text.push(t);e.header&&!le.header.includes(e.header)&&le.header.push(e.header);for(let t of e.secrets??[])le.secrets.some(n=>n.id===t.id)||le.secrets.push(t)}function bn(){return le.text}function _o(){return le.header}function nt(){return le.table}function bo(){return le.secrets}var vn=[{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"}];function kn(){let e=bo().filter(t=>!vn.some(n=>n.id===t.id));return[...vn,...e]}var vo=/node_modules\/|\.next\/|\.test\.|\.spec\.|__tests__\/|\.nodata-proof\.json$|\.git\//,ko=/(^|\/)\.env(\.[\w-]+)*\.(example|sample|template|dist)$|\.(example|sample|template)$|(^|\/)[^/]*\.(example|sample)\.[a-z0-9]+$/i,wo=/(^|\/)(__tests__|__mocks__|tests?|spec|fixtures?|mocks?|samples?|examples?|demo|testdata)(\/|$)|\.(test|spec)\.[a-z0-9]+$|\.min\.(m?js|css)$|(^|\/)[^/]*\.worker\.min\.m?js$/i,El=[{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 xl(e,t){let n=o=>o.replace(/^[^0-9]*/,"").split(".").map(a=>parseInt(a,10)||0),r=n(e),i=n(t);for(let o=0;o<3;o++){if((r[o]||0)<(i[o]||0))return!0;if((r[o]||0)>(i[o]||0))return!1}return!1}function So(e){let t=[],n;try{n=JSON.parse(e)}catch{return t}let r={...n.dependencies??{},...n.devDependencies??{}};for(let[i,o]of Object.entries(r)){let a=(o||"").replace(/^[\^~>=<\s]+/,""),s=El.find(c=>c.name===i&&xl(a,c.below));s&&t.push({name:i,version:a,vuln:s})}return t}var Al=[{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"}],Tl=[{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"}],Il=/^(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,Pl=/^שם[ _](?:ה)?(?:קובץ|מוצר|פריט|חברה|ארגון|עסק|פרויקט|גיליון|טבלה|שדה|קטגוריה|סניף|בנק|עיר|רחוב|ישוב|יישוב|מסמך|תוכנית|חבילה|קורס|מחלקה|אתר|דומיין|מותג|ספק|שירות|תפקיד)$|^(file|product|item|company|org|organization|project|sheet|table|field|category|branch|bank|city|street|document|plan|course|department|site|domain|brand|vendor|service|role)[ _-]?name$/i;function Me(e){if(!e)return null;let t=e.trim();if(Il.test(t)||/^name$/i.test(t))return null;let n=t.replace(/[\s-]+/g,"_");for(let r of[...Tl,...Al])if(r.pattern.test(t)||r.pattern.test(n))return{type:r.type,label:r.label};if(Pl.test(t))return null;if(/^שם[ _][\u0590-\u05FF"'׳ ]{2,20}$/.test(t))return{type:"name",label:"\u05E9\u05DD \u05D0\u05D3\u05DD"};if(/^(customer|client|employee|inspector|supervisor|contact|person|patient|user|owner|manager|agent|member|driver|tenant|student|parent|beneficiary|insured)_?(full_?)?name$/i.test(n))return{type:"name",label:"Person name"};for(let r of _o()){let i=r(t);if(i)return{type:i.type,label:i.label}}return null}var wn={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 Sn(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 i=0;i<9;i++){let o=parseInt(n[i]??"0",10)*(i%2+1);o>9&&(o-=9),r+=o}return r%10===0&&parseInt(n,10)>0}var Tt=/(?:\+972[\s-]?|0)(?:5[0-9]|[2-4]|[89])(?:[\s-]?\d){7}/g;var It=/\bIL\d{2}\s?(?:\d{4}\s?){4}\d{3}\b/g;function $l(e){let t=String(e??"").replace(/\D/g,"");if(t.length<12||t.length>19)return!1;let n=0,r=!1;for(let i=t.length-1;i>=0;i-=1){let o=parseInt(t[i]??"0",10);r&&(o*=2,o>9&&(o-=9)),n+=o,r=!r}return n%10===0}function Rl(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 i of n){let o=i>="A"&&i<="Z"?String(i.charCodeAt(0)-55):i;for(let a of o)r=(r*10+Number(a))%97}return r===1}var Tr="(?<!\\d)(?<!\\d[.,])",Ir="(?!\\d)(?![.,]\\d)",Pr=[{subkind:"israeli_id",severity:"high",pattern:new RegExp(`${Tr}\\d{9}${Ir}`,"g"),validate:Sn,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(`${Tr}[2-6][ -]?(?:\\d[ -]?){11,17}\\d${Ir}`,"g"),validate:$l,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:Rl,hint:"Bank account in IBAN form (mod-97 verified) in plaintext."},{subkind:"israeli_phone",severity:"medium",pattern:new RegExp(`${Tr}(?:\\+972[- ]?|0)(?:[57]\\d|[2-489])[- ]?\\d{3}[- ]?\\d{4}${Ir}`,"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 En(e){let t=[];for(let n of Pr){n.pattern.lastIndex=0;let r=new Set,i,o=0;for(;(i=n.pattern.exec(e))!==null&&(o+=1,!(o>2e5));){let a=i[0];if(n.validate(a)&&r.add(a.replace(/[\s-]/g,"")),r.size>=1e5)break}r.size>0&&t.push({subkind:n.subkind,severity:n.severity,hint:n.hint,count:r.size})}for(let n of bn()){let r=new Set;for(let i of n.find(e))r.add(e.slice(i.start,i.end).trim());r.size>0&&t.push({subkind:n.kind,severity:n.severity,hint:n.hint,count:r.size})}return t}function Ke(e,t){let n=[],r="",i=!1;for(let o=0;o<e.length;o++){let a=e[o];i?a==='"'&&e[o+1]==='"'?(r+='"',o++):a==='"'?i=!1:r+=a:a==='"'?i=!0:a===t?(n.push(r),r=""):r+=a}return n.push(r),n}import{inflateRawSync as Kl}from"node:zlib";import{inflateSync as Dl}from"node:zlib";var $r=new Set([".pdf"]),Eo=8*1024*1024;function Cl(e){let t=e.toString("latin1"),n=new Map,r=/(\d+)\s+(\d+)\s+obj\b/g,i;for(;(i=r.exec(t))!==null;){let o=Number(i[1]),a=r.lastIndex,s=t.indexOf("endobj",a);if(s<0)continue;let c=t.indexOf("stream",a),l,p=null;if(c>=0&&c<s){l=t.slice(a,c);let u=c+6;t[u]==="\r"&&(u+=1),t[u]===`
|
|
16
|
+
`&&(u+=1);let f=t.indexOf("endstream",u);f>u&&(p=e.subarray(u,f))}else l=t.slice(a,s);n.set(o,{num:o,dict:l,stream:p})}return n}function Nl(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=[],i=0,o=0;for(let a of t){if(a==="z"&&o===0){r.push(0,0,0,0);continue}let s=a.charCodeAt(0)-33;if(s<0||s>84)return null;i=i*85+s,o+=1,o===5&&(r.push(i>>>24&255,i>>>16&255,i>>>8&255,i&255),i=0,o=0)}if(o>0){for(let s=o;s<5;s+=1)i=i*85+84;let a=[i>>>24&255,i>>>16&255,i>>>8&255,i&255];for(let s=0;s<o-1;s+=1)r.push(a[s]??0)}return Buffer.from(r)}function Ol(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 jl(e){let t=/\/Filter\s*(\[[^\]]*\]|\/\w+)/.exec(e);return!t||!t[1]?[]:[...t[1].matchAll(/\/(\w+)/g)].map(n=>n[1]??"")}function Ao(e){if(!e.stream)return null;let t=e.stream;for(let n of jl(e.dict)){let r=null;if(n==="FlateDecode")try{r=Dl(t)}catch{return null}else if(n==="ASCII85Decode")r=Nl(t);else if(n==="ASCIIHexDecode")r=Ol(t);else return null;if(r===null)return null;t=r}return t.toString("latin1")}function Ll(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 i=c=>{let l="";for(let p=0;p+3<c.length+1;p+=4){let u=parseInt(c.slice(p,p+4),16);Number.isFinite(u)&&u>0&&(l+=String.fromCharCode(u))}return l},o=/beginbfchar([\s\S]*?)endbfchar/g,a;for(;(a=o.exec(e))!==null;){let c=/<([0-9A-Fa-f]+)>\s*<([0-9A-Fa-f]*)>/g,l;for(;(l=c.exec(a[1]??""))!==null;)t.set(parseInt(l[1]??"0",16),i(l[2]??""))}let s=/beginbfrange([\s\S]*?)endbfrange/g;for(;(a=s.exec(e))!==null;){let c=a[1]??"",l=/<([0-9A-Fa-f]+)>\s*<([0-9A-Fa-f]+)>\s*<([0-9A-Fa-f]*)>/g,p;for(;(p=l.exec(c))!==null;){let u=parseInt(p[1]??"0",16),f=parseInt(p[2]??"0",16),h=parseInt((p[3]??"0").slice(0,4)||"0",16);if(!(f-u>65535))for(let _=u;_<=f;_+=1)t.set(_,String.fromCharCode(h+(_-u)))}}return{map:t,bytes:n}}function Bl(e){let t=new Map,n=new Map,r=[];for(let i of e.values()){let o=/\/Font\s*<<([\s\S]*?)>>/.exec(i.dict);o?.[1]&&r.push(o[1]);let a=/\/Font\s+(\d+)\s+\d+\s+R/.exec(i.dict);if(a){let s=e.get(Number(a[1]));s&&r.push(s.dict)}}for(let i of r){let o=/\/([^\s/<>[\]()]+)\s+(\d+)\s+\d+\s+R/g,a;for(;(a=o.exec(i))!==null;)n.set(a[1]??"",Number(a[2]))}for(let[i,o]of n){let a=e.get(o);if(!a)continue;let s=/\/ToUnicode\s+(\d+)\s+\d+\s+R/.exec(a.dict);if(!s)continue;let c=e.get(Number(s[1]));if(!c)continue;let l=Ao(c);l&&t.set(i,Ll(l))}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 i=e[n+1];if(i===void 0)break;if(i>="0"&&i<="7"){let a="",s=n+1;for(;s<e.length&&a.length<3&&e[s]>="0"&&e[s]<="7";)a+=e[s],s+=1;t.push(parseInt(a,8)&255),n=s-1;continue}let o={n:10,r:13,t:9,b:8,f:12};t.push(o[i]??i.charCodeAt(0)&255),n+=1}return t}function Io(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 xo(e,t){let n=Io(e);if(n!==null)return n;if(!t)return e.map(i=>String.fromCharCode(i)).join("");let r="";if(t.bytes===2)for(let i=0;i+1<e.length;i+=2){let o=(e[i]??0)<<8|(e[i+1]??0);r+=t.map.get(o)??""}else for(let i of e)r+=t.map.get(i)??String.fromCharCode(i);return r}function Fl(e,t){let n="",r,i=/\/([^\s/<>[\]()]+)\s+[\d.]+\s+Tf|\((?:\\.|[^\\)])*\)|<[0-9A-Fa-f\s]*>|TJ|Tj|'|"/g,o,a="";for(;(o=i.exec(e))!==null;){let s=o[0];if(s.endsWith("Tf")){r=t.get(o[1]??"");continue}if(s==="TJ"||s==="Tj"||s==="'"||s==='"'){a&&(n+=a+`
|
|
17
|
+
`,a="");continue}if(s.startsWith("("))a+=xo(To(s.slice(1,-1)),r);else if(s.startsWith("<")){let c=s.slice(1,-1).replace(/\s+/g,""),l=[];for(let p=0;p+1<c.length;p+=2)l.push(parseInt(c.slice(p,p+2),16));a+=xo(l,r)}}return a&&(n+=a+`
|
|
18
|
+
`),n}function Ml(e,t){let n=e.toString("latin1"),r=/\/Info\s+(\d+)\s+\d+\s+R/.exec(n),i=r?t.get(Number(r[1]))?.dict:void 0;if(!i)return"";let o=[],a=/\/(Author|Title|Subject|Keywords|Creator|Producer)\s*(\((?:\\.|[^\\)])*\)|<[0-9A-Fa-f\s]*>)/g,s;for(;(s=a.exec(i))!==null;){let c=s[2]??"";if(c.startsWith("(")){let l=To(c.slice(1,-1));o.push(Io(l)??l.map(p=>String.fromCharCode(p)).join(""))}else{let l=c.slice(1,-1).replace(/\s+/g,""),p="";if(l.toUpperCase().startsWith("FEFF"))for(let u=4;u+3<l.length+1;u+=4)p+=String.fromCharCode(parseInt(l.slice(u,u+4),16));else for(let u=0;u+1<l.length;u+=2)p+=String.fromCharCode(parseInt(l.slice(u,u+2),16));o.push(p)}}return o.join(`
|
|
19
|
+
`)}function Po(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=Cl(e);if(n.size===0)return null;let r=Bl(n),i=[];i.push(Ml(e,n));let o=0,a=0,s=!1;for(let c of n.values()){if(!c.stream||/\/Subtype|\/Type\s*\/(XObject|Font|Metadata)|\/FontFile/.test(c.dict))continue;let l=Ao(c);if(l===null||!/(TJ|Tj)\b/.test(l))continue;let p=Fl(l,r);if(p.trim().length!==0){if(a+=1,o+p.length>Eo){i.push(p.slice(0,Math.max(0,Eo-o))),s=!0;break}i.push(p),o+=p.length}}return a===0?null:{text:i.join(`
|
|
20
|
+
`),truncated:s,streams:a}}var $o=new Set([".xlsx",".xlsm",".docx",".pptx"]),Rr=8*1024*1024,Hl=101010256,Ul=33639248,Vl=67324752;function rt(e){let t=Math.min(e.length,67584),n=-1;for(let a=e.length-22;a>=e.length-t&&a>=0;a-=1)if(e.readUInt32LE(a)===Hl){n=a;break}if(n<0)return null;let r=e.readUInt16LE(n+10),i=e.readUInt32LE(n+16);if(i>=e.length)return null;let o=[];for(let a=0;a<r&&!(i+46>e.length||e.readUInt32LE(i)!==Ul);a+=1){let s=e.readUInt16LE(i+10),c=e.readUInt32LE(i+20),l=e.readUInt32LE(i+24),p=e.readUInt16LE(i+28),u=e.readUInt16LE(i+30),f=e.readUInt16LE(i+32),h=e.readUInt32LE(i+42),_=e.subarray(i+46,i+46+p).toString("utf8");o.push({name:_,method:s,compSize:c,uncompSize:l,localHeaderOffset:h}),i+=46+p+u+f}return o}function it(e,t){let n=t.localHeaderOffset;if(n+30>e.length||e.readUInt32LE(n)!==Vl)return null;let r=e.readUInt16LE(n+26),i=e.readUInt16LE(n+28),o=n+30+r+i,a=o+t.compSize;if(a>e.length)return null;let s=e.subarray(o,a);try{if(t.method===0)return Buffer.from(s);if(t.method===8)return Kl(s)}catch{return null}return null}function Gl(e,t){return it(e,t)?.toString("utf8")??null}var Wl={"&":"&","<":"<",">":">",""":'"',"'":"'"};function Ee(e){return e.replace(/&(amp|lt|gt|quot|apos);/g,t=>Wl[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 zl(e){return Ee(e.replace(/<[^>]*>/g,`
|
|
21
21
|
`)).replace(/\n{2,}/g,`
|
|
22
|
-
`)}function
|
|
23
|
-
`+
|
|
24
|
-
`))}s+
|
|
25
|
-
`),truncated:c,parts:a}}function
|
|
26
|
-
`)?`"${e.replace(/"/g,'""')}"`:e}function
|
|
27
|
-
`),counts:a,columnsHidden:i.filter((f,g)=>o[g])}}var dl=/^xl\/(pivotCache|charts|externalLinks)\//,uo=10;function ul(e,t,n=1){e[t]=(e[t]??0)+n}function po(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}function fo(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 Xe(n)}function ho(e){return e?[...e.matchAll(/<si\b[^>]*>([\s\S]*?)<\/si>|<si\b[^>]*\/>/g)].map(t=>fo(t[1]??"")):[]}var mo=/<c\b([^>]*?)(?:\/>|>([\s\S]*?)<\/c>)/g;function fn(e,t){let n=new RegExp(`\\b${t}="([^"]*)"`).exec(e);return n?n[1]:null}function Be(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?fo(r[1]):null}if(e.type==="b"||e.type==="e")return null;let n=/<v>([^<]*)<\/v>/.exec(e.inner);return n?Xe(n[1]):null}function go(e){let t=[];for(let n of e.matchAll(mo)){let r=fn(n[1],"r"),i=r?/^([A-Z]+)(\d+)$/.exec(r):null;if(!i)return null;t.push({full:n[0],attrs:n[1],inner:n[2]??"",col:i[1],row:Number(i[2]),type:fn(n[1],"t")??"n"})}return t}function pl(e,t){let n=[...new Set(e.map(r=>r.row))].sort((r,i)=>r-i).slice(0,uo);for(let r of n){let i=new Map;for(let o of e.filter(a=>a.row===r)){let a=Be(o,t),s=a?Ne(a):null;s&&i.set(o.col,{type:s.type,header:a.trim()})}if(i.size>0)return{row:r,cols:i}}return{row:-1,cols:new Map}}var yo=/^xl\/worksheets\/sheet\d+\.xml$/,fl=200;function hl(e){let t=e.trim();return/^[\d.,\-+/:%$₪€\s]+$/.test(t)||t.length>60}function ml(e,t){let n=[...new Set(e.map(o=>o.row))].sort((o,a)=>o-a).slice(0,uo),r=-1,i=-1/0;for(let o of n){let a=e.filter(l=>l.row===o).map(l=>(Be(l,t)??"").trim()).filter(Boolean);if(a.length<2)continue;let s=a.filter(l=>!hl(l)).length,c=s*2-(a.length-s);c>i&&(i=c,r=o)}return r}function _o(e,t,n){let r=pl(t,n),i=Je();if(!i)return r;let o=r.row>=0?r.row:ml(t,n);if(o<0)return r;let a=t.filter(p=>p.row===o).map(p=>({col:p.col,text:(Be(p,n)??"").trim()})).filter(p=>p.text),s=new Map(a.map((p,h)=>[p.col,h])),c=new Map;for(let p of t){if(p.row<=o)continue;let h=s.get(p.col);if(h!==void 0){if(!c.has(p.row)){if(c.size>=fl)continue;c.set(p.row,a.map(()=>""))}c.get(p.row)[h]=Be(p,n)??""}}let l=new Map(o===r.row?r.cols:[]),u=a.map(p=>p.text);for(let p of i({name:e,headers:u,rows:[...c.values()]})){let h=u.indexOf(p.column);h<0||l.set(a[h].col,{type:p.type,header:p.column,category:p.category,severity:p.severity,how:p.how})}return{row:o,cols:l}}function mr(e){let t=ln(e);if(!t||t.length===0)return null;let n=o=>{let a=t.find(c=>c.name===o),s=a?dn(e,a):null;return s?s.toString("utf8"):null},r=ho(n("xl/sharedStrings.xml")),i=[];for(let o of t.filter(a=>yo.test(a.name))){let a=n(o.name),s=a?go(a):null;if(!s)continue;let c=o.name.replace(/^xl\/worksheets\//,"").replace(/\.xml$/,""),l=_o(c,s,r);for(let[u,p]of l.cols){let h=s.filter(f=>f.col===u&&f.row>l.row&&(Be(f,r)??"").trim()!=="").length;h>0&&i.push({...p,sheet:c,count:h})}}return i}function lo(e,t){return`<c${e.replace(/\s*\bt="[^"]*"/,"")} t="inlineStr"><is><t xml:space="preserve">${po(t)}</t></is></c>`}var gl=(()=>{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 yl(e){let t=4294967295;for(let n=0;n<e.length;n+=1)t=gl[(t^e[n])&255]^t>>>8;return(t^4294967295)>>>0}function bo(e){let t=[],n=[],r=0;for(let a of e){let s=Buffer.from(a.name,"utf8"),c=a.name.endsWith("/"),l=c?Buffer.alloc(0):ll(a.data),u=c?0:8,p=c?0:yl(a.data),h=Buffer.alloc(30);h.writeUInt32LE(67324752,0),h.writeUInt16LE(20,4),h.writeUInt16LE(2048,6),h.writeUInt16LE(u,8),h.writeUInt32LE(p,14),h.writeUInt32LE(l.length,18),h.writeUInt32LE(a.data.length,22),h.writeUInt16LE(s.length,26),t.push(h,s,l);let f=Buffer.alloc(46);f.writeUInt32LE(33639248,0),f.writeUInt16LE(20,4),f.writeUInt16LE(20,6),f.writeUInt16LE(2048,8),f.writeUInt16LE(u,10),f.writeUInt32LE(p,16),f.writeUInt32LE(l.length,20),f.writeUInt32LE(a.data.length,24),f.writeUInt16LE(s.length,28),f.writeUInt32LE(r,42),n.push(f,s),r+=h.length+s.length+l.length}let i=Buffer.concat(n),o=Buffer.alloc(22);return o.writeUInt32LE(101010256,0),o.writeUInt16LE(e.length,8),o.writeUInt16LE(e.length,10),o.writeUInt32LE(i.length,12),o.writeUInt32LE(r,16),Buffer.concat([...t,i,o])}function bt(e){let t=ln(e);if(!t||t.length===0||t.some(f=>dl.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 g=dn(e,f);if(!g)return null;n.set(f.name,g)}let r=[...n.keys()].filter(f=>yo.test(f));if(r.length===0)return null;let i=n.get("xl/sharedStrings.xml")?.toString("utf8")??null,o=ho(i),a=new Set,s={},c=new Set,l=fr();for(let f of r){let g=n.get(f).toString("utf8"),b=go(g);if(!b)return null;let S=_o(f.replace(/^xl\/worksheets\//,"").replace(/\.xml$/,""),b,o),v=S.row,w=new Map;for(let A of b){if(A.type!=="n"||A.row<=v)continue;let T=Be(A,o);T!==null&&w.set(A.col,[...w.get(A.col)??[],T])}let y=hr(w),_=new Map;for(let[A,{type:T,header:D,how:C}]of S.cols)C==="header"&&y.has(A)||(_.set(A,T),c.add(D));let k=g.replace(mo,(A,T,D)=>{let C=fn(T,"r"),[,x,I]=/^([A-Z]+)(\d+)$/.exec(C),O={full:A,attrs:T,inner:D??"",col:x,row:Number(I),type:fn(T,"t")??"n"},B=Be(O,o),z=()=>{if(O.type==="s"){let X=/<v>([^<]*)<\/v>/.exec(O.inner);X&&a.add(Number(X[1]))}return A};if(B===null||B.trim()==="")return z();let M=_.get(x);if(M&&O.row>v)return ul(s,`column:${M}`),lo(T,l(M,B));if(O.type==="n"&&y.has(x))return z();let j=te(B,s);return j.text===B?z():lo(T,j.text)});n.set(f,Buffer.from(k,"utf8"))}if(i){let f=-1,g=i.replace(/<si\b[^>]*>[\s\S]*?<\/si>|<si\b[^>]*\/>/g,b=>(f+=1,a.has(f)?b:"<si><t></t></si>"));n.set("xl/sharedStrings.xml",Buffer.from(g,"utf8"))}for(let f of[...n.keys()].filter(g=>/^xl\/comments\d*\.xml$/.test(g))){let b=n.get(f).toString("utf8").replace(/(<t(?:\s[^>]*)?>)([\s\S]*?)(<\/t>)/g,(S,v,w,y)=>{let _=te(Xe(w),s);return`${v}${po(_.text)}${y}`});n.set(f,Buffer.from(b,"utf8"))}let u=n.get("docProps/core.xml");if(u){let f=u.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 p=n.has("xl/calcChain.xml"),h=t.map(f=>f.name).filter(f=>!(p&&f==="xl/calcChain.xml"));if(p)for(let f of["[Content_Types].xml","xl/_rels/workbook.xml.rels"]){let g=n.get(f);g&&n.set(f,Buffer.from(g.toString("utf8").replace(/<(Override|Relationship)\b[^>]*calcChain[^>]*\/>/g,""),"utf8"))}return{bytes:bo(h.map(f=>({name:f,data:n.get(f)}))),counts:s,columnsHidden:[...c]}}var yr=10,vt=5e3,bl=64*1024*1024,_r=32*1024,vl=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"]),kl=new Set(["node_modules",".git",".hg",".svn"]),Sl=[{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."}],wl=[{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 El(e){let t=e.lastIndexOf(".");return t<0?"":e.slice(t).toLowerCase()}async function kt(e){let t=Date.now(),n=[],r=[],i=0,o=0,a={hit_file_cap:!1,hit_depth_cap:!1,max_files:vt,max_depth:yr,skipped_by_extension:0,documents_extracted:0,documents_truncated:0,documents_unreadable:0,files_too_large:0,files_sampled_only:0,sample_bytes:_r};function s(v){return(v.startsWith(e.target_path)?v.slice(e.target_path.length).replace(/^[\\/]+/,"")||So(v):v).replace(/\\/g,"/")}function c(v,w,y,_,k){let A=s(v);A!==""&&r.push({target_id:e.target_id,path:A,kind:w,size_bytes:y,modified_at:_?_.toISOString():null,child_count:k})}function l(v,w){n.push({target_id:e.target_id,relative_path:v,finding_kind:w.kind,finding_subkind:w.subkind,severity:w.severity,remediation_hint:w.hint})}function u(v,w,y,_,k){n.push({target_id:e.target_id,relative_path:v,finding_kind:w,finding_subkind:_,severity:y,remediation_hint:k})}function p(v,w){if(i+=1,i>vt){a.hit_file_cap=!0;return}let y=s(v);for(let x of wl)x.re.test(w)&&l(y,x);let _=El(w);if(vl.has(_)){a.skipped_by_extension+=1;return}let k=un.has(_),A=0;try{A=gr(v).size}catch{return}if(k&&A>bl){a.files_too_large+=1;return}let T;try{let x=ko(v,{flag:"r"});T=k?x:x.subarray(0,_r)}catch{return}o+=1;let D;if(k){let x=je(T,_);if(!x){a.documents_unreadable+=1;return}D=x.text,a.documents_extracted+=1,x.truncated&&(a.documents_truncated+=1)}else{let x=0;for(let I=0;I<T.length;I+=1)T[I]===0&&(x+=1);if(T.length>0&&x/T.length>.05)return;D=T.toString("utf8"),A>_r&&(a.files_sampled_only+=1)}let C=new Set;for(let x of Sl)if(x.re.test(D)){let I=`${x.subkind}::${y}`;C.has(I)||(C.add(I),l(y,x))}for(let x of Zi(D)){let I=`validated::${x.subkind}::${y}`;C.has(I)||(C.add(I),u(y,"pii_unencrypted",x.severity,x.subkind,`${x.hint} ${x.count} distinct value${x.count===1?"":"s"} in this file.`))}if(!Xi.test(y)){let x=an(),I=D.split(`
|
|
28
|
-
`),
|
|
29
|
-
`)
|
|
30
|
-
<title>NoData scan \xB7 ${
|
|
22
|
+
`)}function ql(e,t,n){let r=new RegExp(`<${t}\\b[^>]*\\b${n}="([^"]*)"`,"g"),i=[],o;for(;(o=r.exec(e))!==null;)o[1]&&i.push(Ee(o[1]));return i}function Jl(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 Xl(e,t){let n=rt(e);if(!n||n.length===0)return null;let r=new Map(n.map(l=>[l.name,l])),i=Jl(t,n.map(l=>l.name));if(i.length===0)return null;let o=[],a=[],s=0,c=!1;for(let l of i){if(s>=Rr){c=!0;break}let p=r.get(l);if(!p)continue;let u=Gl(e,p);if(u===null)continue;let f=zl(u);if(l==="xl/workbook.xml"){let h=ql(u,"sheet","name");h.length&&(f+=`
|
|
23
|
+
`+h.join(`
|
|
24
|
+
`))}s+f.length>Rr&&(f=f.slice(0,Math.max(0,Rr-s)),c=!0),f.trim().length!==0&&(o.push(f),a.push(l),s+=f.length)}return o.length===0?null:{text:o.join(`
|
|
25
|
+
`),truncated:c,parts:a}}function ke(e,t){if($o.has(t))return Xl(e,t);if($r.has(t)){let n=Po(e);return n?{text:n.text,truncated:n.truncated,parts:[`pdf:${n.streams}-streams`]}:null}return null}var xn=new Set([...$o,...$r]);import{deflateRawSync as ed}from"node:zlib";var Ro={israeli_id:"[ID]",credit_card:"[CARD]",iban:"[IBAN]",israeli_phone:"[PHONE]",email:"[EMAIL]"},Yl=/[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}/g,Zl=[...Pr].sort((e,t)=>+(t.subkind==="iban")-+(e.subkind==="iban"));function An(e,t,n=1){e[t]=(e[t]??0)+n}var ot=null,Tn=e=>{let t=e.trim();ot&&t&&ot.add(t)};function In(e){let t=ot;ot=new Set;try{return{result:e(),replaced:ot}}finally{ot=t}}function de(e,t={}){let n=e;for(let r of Zl)r.pattern.lastIndex=0,n=n.replace(r.pattern,i=>r.validate(i)?(An(t,r.subkind),Tn(i),Ro[r.subkind]??`[${r.subkind.toUpperCase()}]`):i);n=n.replace(Yl,r=>(An(t,"email"),Tn(r),Ro.email));for(let r of bn()){let i=r.find(n).sort((o,a)=>a.start-o.start);for(let o of i)Tn(n.slice(o.start,o.end)),n=n.slice(0,o.start)+`[${r.kind.toUpperCase()}]`+n.slice(o.end),An(t,r.kind)}return{text:n,counts:t,columnsHidden:[]}}function Dr(){let e=new Map,t={};return(n,r)=>{Tn(r);let i=`${n}\0${r.trim()}`,o=e.get(i);return o===void 0&&(o=t[n]=(t[n]??0)+1,e.set(i,o)),`[${n.toUpperCase()}-${o}]`}}function Pn(e){let t=e.trim();return/^\[[A-Z_]+(?:-\d+)?\]$/.test(t)||/^[\d]{0,4}[*•xX]{3,}[\d]{0,4}$/.test(t)}var Co=/^\s*-?\d+(?:\.\d+)?\s*$/;function Cr(e){let t=new Set;for(let[n,r]of e){let i=r.filter(a=>Co.test(a));if(i.length<3)continue;i.filter(a=>de(a).text!==a).length/i.length<.5&&t.add(n)}return t}function Do(e,t){return e.includes(t)||e.includes('"')||e.includes(`
|
|
26
|
+
`)?`"${e.replace(/"/g,'""')}"`:e}function Ql(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??Ql(n[0]??""),i=Ke(n[0]??"",r),o=i.map(h=>Me(h)),a={},s=Dr(),c=n.slice(1).map(h=>h===""?null:Ke(h,r)),l=new Map;for(let h of c)h?.forEach((_,y)=>l.set(y,[...l.get(y)??[],_]));let p=Cr(l),u=nt();if(u){let h=c.filter(_=>_!==null).slice(0,200);for(let _ of u({name:"table",headers:i,rows:h})){let y=i.indexOf(_.column);y>=0&&!(_.how==="header"&&p.has(y))&&(o[y]={type:_.type,label:_.category})}}let f=[i.map(h=>Do(h,r)).join(r)];for(let h of c){if(h===null){f.push("");continue}let _=h.map((y,v)=>{let S=o[v];return S&&y.trim()!==""&&!Pn(y)?(An(a,`column:${S.type}`),s(S.type,y)):p.has(v)&&Co.test(y)?y:de(y,a).text});f.push(_.map(y=>Do(y,r)).join(r))}return{text:f.join(`
|
|
27
|
+
`),counts:a,columnsHidden:i.filter((h,_)=>o[_])}}var td=/^xl\/(pivotCache|charts|externalLinks)\//,jo=10;function nd(e,t,n=1){e[t]=(e[t]??0)+n}function Lo(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}function Bo(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 Ee(n)}function Fo(e){return e?[...e.matchAll(/<si\b[^>]*>([\s\S]*?)<\/si>|<si\b[^>]*\/>/g)].map(t=>Bo(t[1]??"")):[]}var Mo=/<c\b([^>]*?)(?:\/>|>([\s\S]*?)<\/c>)/g;function $n(e,t){let n=new RegExp(`\\b${t}="([^"]*)"`).exec(e);return n?n[1]:null}function He(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?Bo(r[1]):null}if(e.type==="b"||e.type==="e")return null;let n=/<v>([^<]*)<\/v>/.exec(e.inner);return n?Ee(n[1]):null}function Ko(e){let t=[];for(let n of e.matchAll(Mo)){let r=$n(n[1],"r"),i=r?/^([A-Z]+)(\d+)$/.exec(r):null;if(!i)return null;t.push({full:n[0],attrs:n[1],inner:n[2]??"",col:i[1],row:Number(i[2]),type:$n(n[1],"t")??"n"})}return t}function rd(e,t){let n=[...new Set(e.map(r=>r.row))].sort((r,i)=>r-i).slice(0,jo);for(let r of n){let i=new Map;for(let o of e.filter(a=>a.row===r)){let a=He(o,t),s=a?Me(a):null;s&&i.set(o.col,{type:s.type,header:a.trim()})}if(i.size>0)return{row:r,cols:i}}return{row:-1,cols:new Map}}var Ho=/^xl\/worksheets\/sheet\d+\.xml$/,id=200;function od(e){let t=e.trim();return/^[\d.,\-+/:%$₪€\s]+$/.test(t)||t.length>60}function ad(e,t){let n=[...new Set(e.map(o=>o.row))].sort((o,a)=>o-a).slice(0,jo),r=-1,i=-1/0;for(let o of n){let a=e.filter(l=>l.row===o).map(l=>(He(l,t)??"").trim()).filter(Boolean);if(a.length<2)continue;let s=a.filter(l=>!od(l)).length,c=s*2-(a.length-s);c>i&&(i=c,r=o)}return r}function Uo(e,t,n){let r=rd(t,n),i=nt();if(!i)return r;let o=r.row>=0?r.row:ad(t,n);if(o<0)return r;let a=t.filter(u=>u.row===o).map(u=>({col:u.col,text:(He(u,n)??"").trim()})).filter(u=>u.text),s=new Map(a.map((u,f)=>[u.col,f])),c=new Map;for(let u of t){if(u.row<=o)continue;let f=s.get(u.col);if(f!==void 0){if(!c.has(u.row)){if(c.size>=id)continue;c.set(u.row,a.map(()=>""))}c.get(u.row)[f]=He(u,n)??""}}let l=new Map(o===r.row?r.cols:[]),p=a.map(u=>u.text);for(let u of i({name:e,headers:p,rows:[...c.values()]})){let f=p.indexOf(u.column);f<0||l.set(a[f].col,{type:u.type,header:u.column,category:u.category,severity:u.severity,how:u.how})}return{row:o,cols:l}}function Nr(e){let t=rt(e);if(!t||t.length===0)return null;let n=o=>{let a=t.find(c=>c.name===o),s=a?it(e,a):null;return s?s.toString("utf8"):null},r=Fo(n("xl/sharedStrings.xml")),i=[];for(let o of t.filter(a=>Ho.test(a.name))){let a=n(o.name),s=a?Ko(a):null;if(!s)continue;let c=o.name.replace(/^xl\/worksheets\//,"").replace(/\.xml$/,""),l=Uo(c,s,r);for(let[p,u]of l.cols){let f=s.filter(h=>{let _=h.col===p&&h.row>l.row?(He(h,r)??"").trim():"";return _!==""&&!Pn(_)}).length;f>0&&i.push({...u,sheet:c,count:f})}}return i}function No(e,t){return`<c${e.replace(/\s*\bt="[^"]*"/,"")} t="inlineStr"><is><t xml:space="preserve">${Lo(t)}</t></is></c>`}var sd=(()=>{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 cd(e){let t=4294967295;for(let n=0;n<e.length;n+=1)t=sd[(t^e[n])&255]^t>>>8;return(t^4294967295)>>>0}var Oo=33;function Vo(e){let t=[],n=[],r=0;for(let a of e){let s=Buffer.from(a.name,"utf8"),c=a.name.endsWith("/"),l=c?Buffer.alloc(0):ed(a.data),p=c?0:8,u=c?0:cd(a.data),f=Buffer.alloc(30);f.writeUInt32LE(67324752,0),f.writeUInt16LE(20,4),f.writeUInt16LE(2048,6),f.writeUInt16LE(p,8),f.writeUInt16LE(Oo,12),f.writeUInt32LE(u,14),f.writeUInt32LE(l.length,18),f.writeUInt32LE(a.data.length,22),f.writeUInt16LE(s.length,26),t.push(f,s,l);let h=Buffer.alloc(46);h.writeUInt32LE(33639248,0),h.writeUInt16LE(20,4),h.writeUInt16LE(20,6),h.writeUInt16LE(2048,8),h.writeUInt16LE(p,10),h.writeUInt16LE(Oo,14),h.writeUInt32LE(u,16),h.writeUInt32LE(l.length,20),h.writeUInt32LE(a.data.length,24),h.writeUInt16LE(s.length,28),h.writeUInt32LE(r,42),n.push(h,s),r+=f.length+s.length+l.length}let i=Buffer.concat(n),o=Buffer.alloc(22);return o.writeUInt32LE(101010256,0),o.writeUInt16LE(e.length,8),o.writeUInt16LE(e.length,10),o.writeUInt32LE(i.length,12),o.writeUInt32LE(r,16),Buffer.concat([...t,i,o])}function $t(e){let t=rt(e);if(!t||t.length===0||t.some(y=>td.test(y.name)))return null;let n=new Map;for(let y of t){if(y.name.endsWith("/")){n.set(y.name,Buffer.alloc(0));continue}let v=it(e,y);if(!v)return null;n.set(y.name,v)}let r=[...n.keys()].filter(y=>Ho.test(y));if(r.length===0)return null;let i=n.get("xl/sharedStrings.xml")?.toString("utf8")??null,o=Fo(i),a=new Set,s={},c=new Set,l=Dr();for(let y of r){let v=n.get(y).toString("utf8"),S=Ko(v);if(!S)return null;let w=Uo(y.replace(/^xl\/worksheets\//,"").replace(/\.xml$/,""),S,o),x=w.row,m=new Map;for(let E of S){if(E.type!=="n"||E.row<=x)continue;let P=He(E,o);P!==null&&m.set(E.col,[...m.get(E.col)??[],P])}let k=Cr(m),$=new Map;for(let[E,{type:P,header:I,how:T}]of w.cols)T==="header"&&k.has(E)||($.set(E,P),c.add(I));let b=v.replace(Mo,(E,P,I)=>{let T=$n(P,"r"),[,R,M]=/^([A-Z]+)(\d+)$/.exec(T),B={full:E,attrs:P,inner:I??"",col:R,row:Number(M),type:$n(P,"t")??"n"},H=He(B,o),U=()=>{if(B.type==="s"){let tt=/<v>([^<]*)<\/v>/.exec(B.inner);tt&&a.add(Number(tt[1]))}return E};if(H===null||H.trim()==="")return U();let j=$.get(R);if(j&&B.row>x&&!Pn(H))return nd(s,`column:${j}`),No(P,l(j,H));if(B.type==="n"&&k.has(R))return U();let Z=de(H,s);return Z.text===H?U():No(P,Z.text)});n.set(y,Buffer.from(b,"utf8"))}if(i){let y=-1,v=i.replace(/<si\b[^>]*>[\s\S]*?<\/si>|<si\b[^>]*\/>/g,S=>(y+=1,a.has(y)?S:"<si><t></t></si>"));n.set("xl/sharedStrings.xml",Buffer.from(v,"utf8"))}for(let y of[...n.keys()].filter(v=>/^xl\/comments\d*\.xml$/.test(v))){let S=n.get(y).toString("utf8").replace(/(<t(?:\s[^>]*)?>)([\s\S]*?)(<\/t>)/g,(w,x,m,k)=>{let $=de(Ee(m),s);return`${x}${Lo($.text)}${k}`});n.set(y,Buffer.from(S,"utf8"))}let p=n.get("docProps/core.xml");if(p){let y=p.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(y,"utf8"))}let u=n.get("xl/workbook.xml");if(u){let y=u.toString("utf8").replace(/<(\w+:)?absPath\b[^>]*\/>|<(\w+:)?absPath\b[^>]*>[\s\S]*?<\/(\w+:)?absPath>/g,"");n.set("xl/workbook.xml",Buffer.from(y,"utf8"))}let f=n.get("docProps/app.xml");if(f){let y=f.toString("utf8").replace(/(<Company>)[\s\S]*?(<\/Company>)/,"$1$2").replace(/(<Manager>)[\s\S]*?(<\/Manager>)/,"$1$2");n.set("docProps/app.xml",Buffer.from(y,"utf8"))}let h=n.has("xl/calcChain.xml"),_=t.map(y=>y.name).filter(y=>!(h&&y==="xl/calcChain.xml"));if(h)for(let y of["[Content_Types].xml","xl/_rels/workbook.xml.rels"]){let v=n.get(y);v&&n.set(y,Buffer.from(v.toString("utf8").replace(/<(Override|Relationship)\b[^>]*calcChain[^>]*\/>/g,""),"utf8"))}return{bytes:Vo(_.map(y=>({name:y,data:n.get(y)}))),counts:s,columnsHidden:[...c]}}import{createHash as ld}from"node:crypto";var Wo=/(^|\/)(\.env(\.[\w.-]+)?|[\w.-]+\.env(\.[\w.-]+)?)$/i,dd=/(SECRET|PASSWORD|PASSWD|PASS|PWD|TOKEN|PRIVATE|CREDENTIAL|API_?KEY|_KEY|KEY_ID|DSN|DATABASE_URL|_URI|POOLER_URL|SALT|PEPPER)$/i,ud=/(^NEXT_PUBLIC_|^VITE_|^EXPO_PUBLIC_|ANON_KEY$|PUBLISHABLE_KEY$|PUBLIC_KEY$)/i,Go=/(ENCRYPT|CIPHER|PII|DATA_?KEY|KMS|MASTER_?KEY|BLIND_?INDEX|VAULT_?KEY)/i,pd=12,Rn=class{byHash=new Map;add(t,n){for(let r of n.split(/\r?\n/)){let i=/^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/.exec(r);if(!i)continue;let o=i[1];if(!dd.test(o)||ud.test(o))continue;let a=i[2].trim();if(a.startsWith('"')&&a.endsWith('"')||a.startsWith("'")&&a.endsWith("'")?a=a.slice(1,-1):a=a.replace(/\s+#.*$/,""),a.length<pd||/^\$\{?[A-Z_]+\}?$/.test(a))continue;let s=/^[a-z][a-z0-9+.-]*:\/\/[^:/@\s]+:([^@\s]+)@/i.exec(a);if(/^[a-z][a-z0-9+.-]*:\/\//i.test(a)&&!s)continue;let c=s?fd(s[1]):a;if(c.length<8)continue;let l=ld("sha256").update(c).digest("hex"),p=this.byHash.get(l)??[];p.some(u=>u.file===t&&u.name===o)||p.push({file:t,name:o}),this.byHash.set(l,p)}}groups(){let t=[];for(let n of this.byHash.values()){let r=[...new Set(n.map(a=>a.name))].sort(),i=[...new Set(n.map(a=>a.file))].sort();if(r.length<2&&i.length<2)continue;let o=r.some(a=>Go.test(a));t.push({names:r,files:i,encryption:o&&r.some(a=>!Go.test(a))})}return t}};function fd(e){try{return decodeURIComponent(e)}catch{return e}}function zo(e){let t=[];e.names.length>1&&t.push(`one secret is used as ${e.names.length} variables (${e.names.join(", ")})`),e.files.length>1&&t.push(`${e.names.length===1?e.names[0]:"the same secret"} is copied in ${e.files.length} files (${e.files.join(", ")})`);let n=`Shared secret: ${t.join("; and ")}.`;return e.encryption?n+=" \u26A0 It is ALSO a data-encryption key: do NOT rotate it like a normal key \u2014 everything already encrypted with it would stop decrypting. First give the other uses their own new secret, then change the encryption key only in a planned re-encryption.":e.names.length>1?n+=" Replacing it breaks every use at once \u2014 give each use its own secret first, then retire the shared one.":n+=" Every copy has to be removed or updated when the key is replaced; keep one source (the vault) instead.",n}var jr=10,hd=5e3,md=5e4,gd=64*1024*1024,Lr=32*1024,yd=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"]),Yo=new Set(["node_modules",".git",".hg",".svn"]),Zo=new Set([".cache",".cargo",".rustup",".npm",".pnpm-store",".yarn",".gradle",".m2",".nuget",".conda",".pyenv",".rbenv",".nvm",".volta",".bun",".deno",".docker",".android",".vscode-server",".agents",".agent",".codeium",".continue","antigravity",".antigravity","__pycache__",".venv","venv","site-packages",".next",".turbo",".expo",".nx",".parcel-cache",".svelte-kit","appdata",".trash","$recycle.bin"].map(e=>e.toLowerCase())),_d=/(^|\/)\.(vscode|cursor|windsurf|antigravity|vscode-server)\/extensions$/i,Br=40,bd={critical:"high",high:"medium",medium:"low",low:"info",info:"info"},vd=[{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."}],kd=[{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 wd(e){let t=e.lastIndexOf(".");return t<0?"":e.slice(t).toLowerCase()}async function Rt(e){let t=Date.now(),n=[],r=new Rn,i=[],o=0,a=0,s={hit_file_cap:!1,hit_depth_cap:!1,max_files:Math.min(Math.max(1,e.max_files??hd),md),max_depth:jr,tool_dirs_skipped:0,tool_dir_names:[],not_reached:[],skipped_by_extension:0,documents_extracted:0,documents_truncated:0,documents_unreadable:0,files_too_large:0,files_sampled_only:0,sample_bytes:Lr};function c(w){return(w.startsWith(e.target_path)?w.slice(e.target_path.length).replace(/^[\\/]+/,"")||Xo(w):w).replace(/\\/g,"/")}function l(w,x,m,k,$){let b=c(w);b!==""&&i.push({target_id:e.target_id,path:b,kind:x,size_bytes:m,modified_at:k?k.toISOString():null,child_count:$})}function p(w,x){n.push({target_id:e.target_id,relative_path:w,finding_kind:x.kind,finding_subkind:x.subkind,severity:x.severity,remediation_hint:x.hint})}function u(w,x,m,k,$){x!=="hardcoded_secret"&&wo.test(w)&&(m=bd[m],$=`${$??""} (Test / sample / minified file \u2014 probably sample data; check before acting.)`.trim()),n.push({target_id:e.target_id,relative_path:w,finding_kind:x,finding_subkind:k,severity:m,remediation_hint:$})}function f(w,x){if(o+=1,o>s.max_files){s.hit_file_cap=!0;return}let m=c(w);for(let T of kd)T.re.test(x)&&p(m,T);let k=wd(x);if(yd.has(k)){s.skipped_by_extension+=1;return}let $=xn.has(k),b=0;try{b=Dn(w).size}catch{return}if($&&b>gd){s.files_too_large+=1;return}let E;try{let T=Jo(w,{flag:"r"});E=$?T:T.subarray(0,Lr)}catch{return}a+=1;let P;if($){let T=ke(E,k);if(!T){s.documents_unreadable+=1;return}P=T.text,s.documents_extracted+=1,T.truncated&&(s.documents_truncated+=1)}else{let T=0;for(let R=0;R<E.length;R+=1)E[R]===0&&(T+=1);if(E.length>0&&T/E.length>.05)return;P=E.toString("utf8"),b>Lr&&(s.files_sampled_only+=1)}let I=new Set;Wo.test(m)&&r.add(m,P);for(let T of vd)if(T.re.test(P)){let R=`${T.subkind}::${m}`;I.has(R)||(I.add(R),p(m,T))}for(let T of En(P)){let R=`validated::${T.subkind}::${m}`;I.has(R)||(I.add(R),u(m,"pii_unencrypted",T.severity,T.subkind,`${T.hint} ${T.count} distinct value${T.count===1?"":"s"} in this file.`))}if(!vo.test(m)){let T=kn(),R=P.split(`
|
|
28
|
+
`),M=Math.min(R.length,2e3);for(let B=0;B<M;B++){let H=R[B];if(!H)continue;let U=H.trimStart();if(!(U.startsWith("//")||U.startsWith("/*")||U.startsWith("*")||U.startsWith("#"))&&!/process\.env/.test(H)&&!/\$\{[A-Z_]+/.test(H)){for(let j of T)if(j.pattern.test(H)){let Z=`secret::${j.id}::${m}::${B+1}`;if(I.has(Z))break;I.add(Z);let tt=ko.test(m);u(m,"hardcoded_secret",tt?"critical":j.severity,j.id,tt?`A real-looking ${j.name} in an EXAMPLE file near line ${B+1}. Example files are committed to Git and shared on purpose \u2014 rotate this key at its source and put a placeholder in the example.`:`Looks like a ${j.name} hardcoded near line ${B+1}. Move to an env var or secret manager.`);break}}}}if(x==="package.json"&&!m.includes("node_modules"))try{let T=Jo(w,"utf8"),R=So(T);for(let M of R){let B=`vuln::${M.name}::${m}`;I.has(B)||(I.add(B),u(m,"vulnerable_dependency",M.vuln.severity,M.name,`${M.name}@${M.version} is below ${M.vuln.below} (${M.vuln.cve} \xB7 ${M.vuln.desc}). Bump to ${M.vuln.below} or higher.`))}}catch{}if(k===".csv"||k===".tsv"){let T=k===".tsv"?" ":",",R=P.split(/\r?\n/);if(R.length>0){let M=Ke(R[0]??"",T),B=R.slice(1,51).map(U=>Ke(U??"",T)),H=nt();if(H){let U=R.slice(1,201).filter(j=>j!=="").map(j=>Ke(j,T));for(let j of H({name:"table",headers:M,rows:U})){let Z=`header::${m}::${j.column}::${j.type}`;I.has(Z)||(I.add(Z),u(m,"pii_header_match",j.severity,`${j.type}:${j.column}`,`Column "${j.column}" holds ${j.category} (${j.how==="value"?`${j.hits} sampled values matched`:"by its header"}). Wrap with envelope or keep a clean copy for work.`))}}H||M.forEach((U,j)=>{let Z=(U??"").trim();if(!Z)return;let Fe=Me(Z)?.type??null;if(!Fe){let xt=[];for(let yl of B){let Er=yl[j];if(Er&&Er.trim().length>0&&xt.push(Er),xt.length>=50)break}let At=_(xt);At&&(Fe=At)}if(Fe){let xt=wn[Fe]??"medium",At=`header::${m}::${Z}::${Fe}`;if(I.has(At))return;I.add(At),u(m,"pii_header_match",xt,`${Fe}:${Z}`,`Column "${Z}" looks like ${Fe} data. Wrap with envelope or move to a vault-backed reference.`)}})}}if(k===".xlsx"||k===".xlsm")for(let T of Nr(E)??[]){let R=`xlsxheader::${m}::${T.sheet}::${T.header}::${T.type}`;I.has(R)||(I.add(R),u(m,"pii_header_match",T.severity??wn[T.type]??"medium",`${T.type}:${T.header}`,`Column "${T.header}" (${T.sheet}) holds ${T.category??`${T.type} data`}${T.how==="value"?" (found by its values)":""} \u2014 ${T.count} filled cell${T.count===1?"":"s"}. Wrap with envelope or keep a clean copy for work.`))}if(k===".json"&&!x.endsWith(".nodata-proof.json"))try{let T=JSON.parse(P),R=Array.isArray(T)?T[0]:T;if(R&&typeof R=="object")for(let M of Object.keys(R)){let B=Me(M);if(B){let H=wn[B.type]??"medium",U=`jsonkey::${m}::${M}::${B.type}`;if(I.has(U))continue;I.add(U),u(m,"pii_header_match",H,`${B.type}:${M}`,`JSON key "${M}" looks like ${B.type} data.`)}}}catch{}/\.(txt|log|md|csv|tsv|json|jsonl|xml|html?|yaml|yml|sql)$/i.test(x)&&h(P,m,I)}function h(w,x,m){let k=w.split(`
|
|
29
|
+
`),$=Math.min(k.length,1e3),b=-1,E=-1,P=-1;for(let I=0;I<$;I++){let T=k[I]??"";if(P<0){let R=T.match(/\b\d{9}\b/);R&&Sn(R[0])&&(P=I+1)}if(b<0&&(Tt.lastIndex=0,Tt.test(T)&&(b=I+1)),E<0&&(It.lastIndex=0,It.test(T)&&(E=I+1)),P>0&&b>0&&E>0)break}P>0&&!m.has(`ilid::${x}`)&&(m.add(`ilid::${x}`),u(x,"israeli_id_value","critical",`near_line:${P}`,`Israeli ID with valid Luhn checksum detected near line ${P}. Strong signal that real customer IDs are in plaintext.`)),b>0&&!m.has(`ilphone::${x}`)&&(m.add(`ilphone::${x}`),u(x,"israeli_phone_value","high",`near_line:${b}`,`Israeli phone number detected near line ${b}.`)),E>0&&!m.has(`iliban::${x}`)&&(m.add(`iliban::${x}`),u(x,"israeli_iban_value","critical",`near_line:${E}`,`Israeli IBAN (IL prefix) detected near line ${E}.`))}function _(w){if(w.length===0)return null;let x=0,m=0,k=0;for(let b of w)typeof b=="string"&&(Sn(b)&&x++,Tt.lastIndex=0,Tt.test(b)&&m++,It.lastIndex=0,It.test(b)&&k++);let $=w.length;return x/$>=.3?"id":m/$>=.3?"phone":k/$>=.3?"financial":null}function y(w,x){if(x>jr){s.hit_depth_cap=!0;return}if(o>s.max_files){s.hit_file_cap=!0;return}let m;try{m=qo(w)}catch{return}for(let k=0;k<m.length;k++){let $=m[k];if(o>s.max_files){s.hit_file_cap=!0;let P=c(w);P&&!s.not_reached.includes(`${P} (partly)`)&&s.not_reached.length<Br&&s.not_reached.push(`${P} (partly)`);for(let I of m.slice(k)){if(s.not_reached.length>=Br)break;try{Dn(Or(w,I)).isDirectory()&&!Yo.has(I)&&!Zo.has(I.toLowerCase())&&s.not_reached.push(c(Or(w,I)))}catch{}}return}let b=Or(w,$),E;try{E=Dn(b)}catch{continue}if(!E.isSymbolicLink())if(E.isDirectory()){if(Yo.has($))continue;if(!e.include_tool_dirs&&(Zo.has($.toLowerCase())||_d.test(c(b)))){s.tool_dirs_skipped+=1,!s.tool_dir_names.includes($)&&s.tool_dir_names.length<Br&&s.tool_dir_names.push($);continue}let P=null;try{P=qo(b).length}catch{P=null}l(b,"folder",null,E.mtime??null,P),y(b,x+1)}else E.isFile()&&(l(b,"file",E.size,E.mtime??null,null),f(b,$))}}let v,S=null;try{let w=Dn(e.target_path);v=w.isDirectory()||w.isFile(),w.isFile()&&(S={size:w.size,mtime:w.mtime??null})}catch{v=!1}if(!v)return{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:s,error:"target_path_not_found_or_not_directory"};e.log.info("folder-scanner: starting",{target_label:e.target_label,target_path:e.target_path,max_files:s.max_files,max_depth:jr}),S?(l(e.target_path,"file",S.size,S.mtime,null),f(e.target_path,Xo(e.target_path))):y(e.target_path,0);for(let w of r.groups()){let x=zo(w);for(let m of w.files)u(m,"secret_reuse",w.encryption?"critical":"high",w.encryption?"shared_encryption_key":w.names.length>1?"shared_secret":"copied_secret",x)}return{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:i,coverage:s}}var Dt={info(){}};var at={critical:4,high:3,medium:2,low:1,info:0},Hr=["critical","high","medium","low","info"];function Fr(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,(at[n.severity]??0)>(at[r.worst]??0)&&(r.worst=n.severity),e.set(t,r)}function Mr(e){return[...e.values()].sort((t,n)=>(at[n.worst]??0)-(at[t.worst]??0)||n.total-t.total||t.key.localeCompare(n.key))}function Ue(e){let t=e.findings??[],n={},r=new Map,i=new Map,o=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:"";Fr(r,c||s.finding_kind,s);let l=s.relative_path.replace(/\\/g,"/"),p=l.includes("/")?l.slice(0,l.indexOf("/")):".";Fr(i,p,s),Fr(o,l,s)}let a=Mr(o);return{total:t.length,bySeverity:n,byType:Mr(r),byFolder:Mr(i),byFile:a,filesWithFindings:a.map(s=>s.key)}}function fe(e){return e.replace(/[&<>"']/g,t=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[t])}function Kr(e,t,n){let r=`<tr><th>${fe(n)}</th><th>total</th>${Hr.map(o=>`<th class="${o}">${o}</th>`).join("")}</tr>`,i=t.map(o=>`<tr><td class="k">${fe(o.key)}</td><td>${o.total}</td>${Hr.map(a=>`<td>${o.bySeverity[a]??""}</td>`).join("")}</tr>`).join("");return`<h2>${fe(e)} <span class="n">${t.length}</span></h2><table>${r}${i}</table>`}function Ur(e,t=Ue(e)){let n=Hr.filter(s=>t.bySeverity[s]).map(s=>`<span class="pill ${s}">${t.bySeverity[s]} ${s}</span>`).join(" "),r=e.coverage,i=[];r?.hit_file_cap&&i.push(`stopped at the ${r.max_files}-file cap${r.not_reached?.length?` \u2014 not reached: ${r.not_reached.join(", ")}`:""}`),r?.tool_dirs_skipped&&i.push(`${r.tool_dirs_skipped} tool / cache folder(s) skipped (${r.tool_dir_names.join(", ")})`),r?.hit_depth_cap&&i.push(`folders deeper than ${r.max_depth} levels were not descended`),r?.files_too_large&&i.push(`${r.files_too_large} file(s) too large to read`),r?.documents_unreadable&&i.push(`${r.documents_unreadable} document(s) unreadable`);let o=[...e.findings??[]].sort((s,c)=>(at[c.severity]??0)-(at[s.severity]??0)),a=o.map(s=>`<tr><td><span class="pill ${s.severity}">${s.severity}</span></td><td>${fe(s.finding_subkind||s.finding_kind)}</td><td class="k">${fe(s.relative_path)}</td><td class="h">${fe(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">
|
|
30
|
+
<title>NoData scan \xB7 ${fe(e.target_label||e.target_path)}</title>
|
|
31
31
|
<style>
|
|
32
32
|
body{margin:0;background:#FAF7F0;color:#1a1a1a;font:14px/1.5 Inter,Heebo,system-ui,sans-serif}
|
|
33
33
|
main{max-width:1100px;margin:0 auto;padding:28px 18px 60px}
|
|
@@ -40,88 +40,106 @@ td.k{font-family:ui-monospace,Menlo,monospace;font-size:12.5px;word-break:break-
|
|
|
40
40
|
.medium{color:#7a6400}.pill.medium{background:#fbf3cf}.low{color:#445}.pill.low{background:#eef0f4}
|
|
41
41
|
.note{margin-top:18px;color:#666;font-size:12.5px}
|
|
42
42
|
</style></head><body><main>
|
|
43
|
-
<h1>Scan \xB7 ${
|
|
44
|
-
<p class="sub">${
|
|
43
|
+
<h1>Scan \xB7 ${fe(e.target_label||e.target_path)}</h1>
|
|
44
|
+
<p class="sub">${fe(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>
|
|
45
45
|
<p><strong>${t.total}</strong> findings ${n}</p>
|
|
46
|
-
${i.length?`<p class="note">Coverage: ${
|
|
47
|
-
${
|
|
48
|
-
${
|
|
49
|
-
${
|
|
46
|
+
${i.length?`<p class="note">Coverage: ${fe(i.join("; "))}.</p>`:""}
|
|
47
|
+
${Kr("By type",t.byType,"type")}
|
|
48
|
+
${Kr("By folder",t.byFolder,"folder")}
|
|
49
|
+
${Kr("By file",t.byFile,"file")}
|
|
50
50
|
<h2>Every finding <span class="n">${o.length}</span></h2>
|
|
51
51
|
<table><tr><th>severity</th><th>type</th><th>file</th><th>what to do</th></tr>${a}</table>
|
|
52
52
|
<p class="note">Content-free: this report lists where and what kind \u2014 never a matched value.</p>
|
|
53
|
-
</main></body></html>`}
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
`)
|
|
61
|
-
`)
|
|
62
|
-
`))
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
${
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
`)
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
53
|
+
</main></body></html>`}import{createHash as Sd}from"node:crypto";var Ed=4,Qo=e=>Sd("sha256").update(e).digest("hex");function xd(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function Vr(e,t,n,r){let i=t.length>4&&t.readUInt32LE(0)===67324752?rt(t):null,o=i?i.filter(u=>!u.name.endsWith("/")).map(u=>{let f=it(t,u)?.toString("utf8")??"";return f+`
|
|
54
|
+
`+Ee(f)}):[t.toString("utf8")],a=[...r],s=a.filter(u=>u.length>=Ed),c=0;for(let u of s){let f=new Set([u,xd(u)]);o.some(h=>[...f].some(_=>h.includes(_)))&&c++}let l=i?ke(t,n)?.text??o.join(`
|
|
55
|
+
`):o[0],p=En(l).reduce((u,f)=>u+f.count,0);return{method:"every replaced value searched, as written and XML-escaped, in every part of the clean file; clean text re-scanned with the validated detectors; both files fingerprinted",original_sha256:Qo(e),clean_sha256:Qo(t),values_checked:s.length,values_too_short_to_check:a.length-s.length,parts_searched:o.length,values_found:c,rescan_hits:p,ok:c===0}}var Ad=["Put the new key where the app reads it (for a developer machine: the NoData vault + nodata_run, not a .env file).","Check that the app still works with the new key.","Only then delete / revoke the OLD key \u2014 until you do, whoever copied it can still use it."],L=(e,t,n)=>({provider:e,url:t,steps:[...n,...Ad]}),Td={"aws-access-key":L("AWS","https://console.aws.amazon.com/iam/home#/security_credentials",["Open IAM \u2192 your user \u2192 Security credentials.","Create a NEW access key (you see its secret once \u2014 keep it only in the vault)."]),"aws-secret-key":L("AWS","https://console.aws.amazon.com/iam/home#/security_credentials",["Open IAM \u2192 your user \u2192 Security credentials.","Create a NEW access key (you see its secret once \u2014 keep it only in the vault).","Mark the old key Inactive before deleting it."]),"gcp-api-key":L("Google Cloud","https://console.cloud.google.com/apis/credentials",["Open APIs & Services \u2192 Credentials.","Pick the key \u2192 Regenerate key (or create a new one and restrict it to the APIs you use)."]),"gcp-service-account":L("Google Cloud (service account)","https://console.cloud.google.com/iam-admin/serviceaccounts",["Open IAM & Admin \u2192 Service accounts \u2192 the account \u2192 Keys.","Add key \u2192 Create new key (JSON). Keep the file out of Git and out of shared folders."]),"firebase-key":L("Firebase / Google Cloud","https://console.cloud.google.com/apis/credentials",["A Firebase web key is meant to be public \u2014 restrict it instead: Credentials \u2192 the key \u2192 Application restrictions (your domains only).","If it is not a web key, regenerate it."]),"github-token":L("GitHub","https://github.com/settings/tokens",["Open Settings \u2192 Developer settings \u2192 Personal access tokens.","Generate a new token with only the scopes you need."]),"github-fine-grained":L("GitHub","https://github.com/settings/tokens?type=beta",["Open Fine-grained tokens.","Regenerate the token (or create a new one for only the repositories you need)."]),"gitlab-token":L("GitLab","https://gitlab.com/-/user_settings/personal_access_tokens",["Open Access tokens.","Create a new token with only the scopes you need."]),"stripe-secret":L("Stripe","https://dashboard.stripe.com/apikeys",["Open Developers \u2192 API keys.","Roll the secret key (Stripe can keep the old one alive for a short overlap)."]),"stripe-restricted":L("Stripe","https://dashboard.stripe.com/apikeys",["Open Developers \u2192 API keys \u2192 Restricted keys.","Roll the key, or create a new restricted key."]),"slack-token":L("Slack","https://api.slack.com/apps",["Open your app \u2192 OAuth & Permissions.","Rotate / reinstall to get a new token."]),"slack-webhook":L("Slack","https://api.slack.com/apps",["Open your app \u2192 Incoming Webhooks.","Add a new webhook URL for the channel."]),"twilio-api-key":L("Twilio","https://console.twilio.com/us1/account/keys-credentials/api-keys",["Open Account \u2192 API keys & tokens.","Create a new API key."]),"sendgrid-api-key":L("SendGrid","https://app.sendgrid.com/settings/api_keys",["Open Settings \u2192 API Keys.","Create a new key with only the permissions you need."]),"openai-key":L("OpenAI","https://platform.openai.com/api-keys",["Open API keys.","Create a new secret key."]),"anthropic-key":L("Anthropic","https://console.anthropic.com/settings/keys",["Open Settings \u2192 API keys.","Create a new key."]),"supabase-key":L("Supabase","https://supabase.com/dashboard/project/_/settings/api-keys",["Open the project \u2192 Project Settings \u2192 API Keys.","Create a new SECRET key (a service_role / secret key bypasses every database rule \u2014 treat it like a root password).","Older projects with JWT keys: rotating the JWT secret replaces every key and signs everyone out \u2014 plan it."]),"postgres-uri":L("PostgreSQL (the password in the connection string)","https://supabase.com/dashboard/project/_/settings/database",["Change the database user's password: in Supabase \u2192 Project Settings \u2192 Database \u2192 Reset password; elsewhere, your host's console or ALTER USER \u2026 WITH PASSWORD.","Update the connection string with the new password."]),"mongodb-uri":L("MongoDB","https://cloud.mongodb.com/",["Open Atlas \u2192 Database Access \u2192 the user \u2192 Edit \u2192 Edit password.","Update the connection string."]),"redis-uri":L("Redis","",["Reset the password in your Redis host's console (or CONFIG SET requirepass on your own server).","Update the connection string."]),"private-key":L("Private key (SSH / TLS / signing)","",["Generate a new key pair.","Register the new PUBLIC key where the old one was trusted (server authorized_keys, certificate, service settings)."]),"jwt-secret":L("Your app's JWT secret","",["Set a new long random secret in the app's configuration.","Every signed-in user will be signed out \u2014 plan the moment."]),"password-in-code":L("A password in code","",["Change the password in the system it belongs to."]),"bearer-token":L("An access token","",["Revoke the token in the service that issued it and issue a new one."])},Id=L("A credential","",["Find the service it belongs to and issue a new credential there."]);function ea(e){return Td[e]??Id}function Gr(e){let t=new Map;for(let n of e){if(n.finding_kind!=="hardcoded_secret"||!n.finding_subkind)continue;let r=ea(n.finding_subkind),i=t.get(r.provider)??{...r,ruleIds:[],files:[],count:0};i.count+=1,i.ruleIds.includes(n.finding_subkind)||i.ruleIds.push(n.finding_subkind),i.files.includes(n.relative_path)||i.files.push(n.relative_path),t.set(r.provider,i)}return[...t.values()].sort((n,r)=>r.count-n.count)}var ue=xr(Zr(),1);import{homedir as Iu}from"node:os";import{basename as dt,dirname as Kt,extname as Pu,join as Ge,resolve as Fn}from"node:path";import{existsSync as Ft,mkdirSync as Ua,readFileSync as li,rmSync as Va,statSync as oi,writeFileSync as Mn}from"node:fs";import{pathToFileURL as Mt}from"node:url";function Ae(e){return/\.ndc$/i.test(e)||/\.clean\.[A-Za-z0-9]+$/.test(e)}import{z as ct}from"zod";var lt=xr(Zr(),1);import{mkdirSync as mu,writeFileSync as gu}from"node:fs";import{homedir as yu}from"node:os";import{existsSync as Ca,rmSync as _u,statSync as bu}from"node:fs";import{basename as vu,dirname as ku,join as ii,relative as ti,resolve as wu}from"node:path";import{pathToFileURL as Na}from"node:url";import{z as Sa}from"zod";import{createHash as xa}from"node:crypto";import{appendFileSync as su,existsSync as Aa,mkdirSync as Ta,readFileSync as Ia,writeFileSync as cu}from"node:fs";import{homedir as lu}from"node:os";import{join as Ln}from"node:path";import{existsSync as ma,mkdirSync as iu,readFileSync as ga,writeFileSync as ou}from"node:fs";import{homedir as ya}from"node:os";import{join as _a}from"node:path";var Ot=()=>_a(ya(),".nodata","prefs.json");function ba(){try{let e=ma(Ot())?JSON.parse(ga(Ot(),"utf8")).lang:null;return e==="he"||e==="en"?e:null}catch{return null}}function au(){let t=process.env.LC_ALL||process.env.LC_MESSAGES||process.env.LANG||"";try{t||=Intl.DateTimeFormat().resolvedOptions().locale}catch{}return/^(he|iw)(?:[-_.@]|$)/i.test(t)?"he":"en"}function Te(){return ba()??au()}function st(){return ba()!==null}function Qr(e){iu(_a(ya(),".nodata"),{recursive:!0});let t={};try{ma(Ot())&&(t=JSON.parse(ga(Ot(),"utf8")))}catch{}ou(Ot(),JSON.stringify({...t,lang:e},null,2)+`
|
|
56
|
+
`)}function va(e,t,n=Te()){return n==="he"?e:t}function ka(e=Te()){return e==="he"?"The user chose Hebrew. Always write to the user in clear, correct Hebrew \u2014 every answer, question, summary and relayed tool result \u2014 for the whole session. Keep tool, file and command names as they are.":"The user chose English. Always write to the user in English for the whole session."}function wa(e){return e!=="he"&&e!=="en"?`Language: ${Te()==="he"?"\u05E2\u05D1\u05E8\u05D9\u05EA (he)":"English (en)"}${st()?"":" \u2014 from this machine's settings"}.
|
|
57
|
+
Change with: nodata-mcp lang he | nodata-mcp lang en`:(Qr(e),e==="he"?"\u2713 \u05D4\u05E9\u05E4\u05D4 \u05E0\u05E7\u05D1\u05E2\u05D4: \u05E2\u05D1\u05E8\u05D9\u05EA. NoData \u05D9\u05D3\u05D1\u05E8 \u05E2\u05D1\u05E8\u05D9\u05EA, \u05D5\u05DB\u05DC \u05E1\u05D5\u05DB\u05DF \u05D1\u05DE\u05D7\u05E9\u05D1 \u05D4\u05D6\u05D4 \u05D9\u05E7\u05D1\u05DC \u05D4\u05D5\u05E8\u05D0\u05D4 \u05DC\u05E2\u05E0\u05D5\u05EA \u05D1\u05E2\u05D1\u05E8\u05D9\u05EA. \u05D4\u05E4\u05E2\u05DC \u05DE\u05D7\u05D3\u05E9 \u05D0\u05EA Claude Code.":"\u2713 Language set: English. Restart Claude Code to apply.")}var ie="2026-09-24-v3";var du=new Set(["nodata_terms","nodata_get_started","nodata_connect"]),jt=()=>Ln(lu(),".nodata"),jn=()=>Ln(jt(),"consent.json");function Bn(){try{return Aa(jn())?JSON.parse(Ia(jn(),"utf8")):null}catch{return null}}function Lt(){return Bn()?.terms_version===ie}function Pa(e){Ta(jt(),{recursive:!0}),cu(jn(),JSON.stringify(e,null,2)+`
|
|
58
|
+
`,{mode:384})}async function ei(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)}),i=await r.json().catch(()=>({}));return r.ok&&i.logged===!0}catch{return!1}}function uu(e,t){return e.org?`${e.baseUrl}/tenant-v2/${encodeURIComponent(e.org)}/proofs?q=proof:${t.slice(0,16)}`:null}function Ie(e){return e?` and recorded at NoData for your organisation${typeof e=="string"?` \u2014 proof: ${e}`:""}`:""}async function Bt(e,t,n,r){let i=new Date().toISOString(),o=xa("sha256").update(`${t}|${n}|${r}|${i}`).digest("hex");try{Ta(jt(),{recursive:!0}),su(Ln(jt(),"acks.jsonl"),JSON.stringify({at:i,context:t,agent:n,detail:r,proof_hash:o})+`
|
|
59
|
+
`,{mode:384})}catch{}return e&&await ei(e,{action:"action_ack",actionDetail:`${t}:${r}`,agent:n,proofHash:o,tosVersion:ie})?uu(e,o)??!0:!1}async function pu(e,t){let n=new Date().toISOString(),r=xa("sha256").update(`${ie}|mcp|${t}|${e?.org??""}|${n}`).digest("hex"),i={terms_version:ie,accepted_at:n,agent:t,org:e?.org??null,consent_hash:r,server_recorded:!1};return e&&(i.server_recorded=await ei(e,{action:"tos_accept",tosVersion:ie,context:"mcp",agent:t,proofHash:r})),Pa(i),i}async function $a(e){let t=Bn();if(!t||t.terms_version!==ie||t.server_recorded)return;await ei(e,{action:"tos_accept",tosVersion:ie,context:"mcp-sync",agent:t.agent,proofHash:t.consent_hash})&&Pa({...t,org:e.org,server_recorded:!0})}function Ea(e){try{return Ia(Ln(jt(),e),"utf8").split(`
|
|
60
|
+
`).filter(Boolean).length}catch{return 0}}function fu(){return["What is recorded about this machine (all in ~/.nodata, operational only):",` \xB7 consent.json \u2014 ${Aa(jn())?"your terms acceptance":"none yet"}`,` \xB7 acks.jsonl \u2014 ${Ea("acks.jsonl")} acknowledgement(s), e.g. installing the read gate`,` \xB7 gate.log \u2014 ${Ea("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(`
|
|
61
|
+
`)}var hu=e=>[`NoData terms ${ie} \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(`
|
|
62
|
+
`);function Ra(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. LANGUAGE: if the user has not chosen one, ask them \u2014 \u05E2\u05D1\u05E8\u05D9\u05EA or English \u2014 and pass it as `language`; it is kept for every later session and every agent on this machine.",inputSchema:{confirm:Sa.boolean().optional().describe("true = the user accepts these terms. Omit to show them."),language:Sa.enum(["he","en"]).optional().describe("The language the user chose for NoData and their agents: he (\u05E2\u05D1\u05E8\u05D9\u05EA) or en (English).")}},async({confirm:i,language:o})=>{o&&Qr(o);let a=Bn();if(!i){let c=Lt()?`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:`${hu(r)}
|
|
63
|
+
|
|
64
|
+
${c}
|
|
65
|
+
|
|
66
|
+
${fu()}
|
|
67
|
+
|
|
68
|
+
`+(st()?"":`Also ask which language they want NoData and their agents to use with them \u2014 \u05E2\u05D1\u05E8\u05D9\u05EA or English \u2014 and pass it as language: "he" | "en".
|
|
69
|
+
`)+"Ask the user whether they accept, then call nodata_terms again with confirm: true."}]}}let s=await pu(t,n());return{content:[{type:"text",text:`ACCEPTED terms ${s.terms_version} \u2014 ${s.agent}${s.org?` \xB7 org ${s.org}`:""} \xB7 ${s.accepted_at}
|
|
70
|
+
local copy: ~/.nodata/consent.json \xB7 hash ${s.consent_hash.slice(0,16)}\u2026
|
|
71
|
+
`+(s.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.")+`
|
|
72
|
+
The data tools are on.`}]}})}function Da(e){let t=e,n=t.registerTool.bind(e);t.registerTool=(r,i,o)=>n(r,i,async(...a)=>{if(du.has(r)||Lt())return o(...a);let s=Bn();return{content:[{type:"text",text:(s?`NoData's terms changed (you accepted ${s.terms_version}; current is ${ie}).`:"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}})}var Su={critical:"Restricted",high:"Confidential",medium:"Internal",low:"Internal",info:"Internal"},Oa={critical:4,high:3,medium:2,low:1,info:0},ni={both:"clean copy to work on + lock the original",protect:"lock",redact:"clean copy to work on",keep:"leave as is"},Eu={credit_card:"card",israeli_id:"ID",israeli_id_value:"ID",iban:"IBAN",israeli_iban_value:"IBAN",israeli_phone:"phone",israeli_phone_value:"phone",email:"email"};function ja(e){if(e.finding_kind==="hardcoded_secret")return"secret";if(e.finding_kind==="secret_reuse")return e.finding_subkind==="shared_encryption_key"?"shared encryption key":"shared secret";if(e.finding_kind==="pii_header_match")return`${(e.finding_subkind??"personal").split(":")[0]} column`;let t=e.finding_subkind&&!e.finding_subkind.startsWith("near_line")?e.finding_subkind:e.finding_kind;return Eu[t]??t.replace(/_/g," ")}function xu(e){let t=new Map;for(let i of e)t.set(i.relative_path,[...t.get(i.relative_path)??[],i]);let n=[];for(let[i,o]of t){let a=o.reduce((h,_)=>(Oa[_.severity]??0)>(Oa[h]??0)?_.severity:h,"info"),s=Su[a]??"Internal",c=o.some(h=>h.finding_kind==="hardcoded_secret"||h.finding_kind==="secret_reuse"),l=new Map;for(let h of o){let _=ja(h);l.set(_,Math.max(l.get(_)??0,o.filter(y=>ja(y)===_&&y.finding_kind===h.finding_kind).length))}let p=[...l].map(([h,_])=>`${_} ${h}`).join(", "),u,f;c?(u="protect",f="a credential in plaintext \u2014 lock the file, and ROTATE the credential at its source: a leaked key stays valid until it is replaced"):s==="Restricted"?(u="both",f="restricted data \u2014 keep a clean copy for work and lock the original away from people and AI"):s==="Confidential"?(u="protect",f="confidential personal data (IDs, accounts) \u2014 lock it; make a clean copy when you need to work on it"):(u="redact",f="internal contact data \u2014 a clean copy is enough to work safely"),n.push({file:i,tier:s,found:p,secret:c,action:u,why:f})}let r={Restricted:0,Confidential:1,Internal:2};return n.sort((i,o)=>r[i.tier]-r[o.tier]||i.file.localeCompare(o.file))}function Ba(e){let n=e.replace(/\\/g,"/").replace(/\/$/,"/**").replace(/[.+^${}()|[\]]/g,"\\$&").replace(/\*\*/g,"\0").replace(/\*/g,"[^/]*").replace(/\?/g,"[^/]").replace(/\u0000/g,".*");return new RegExp(`^${n}$`)}function Au(e,t){if(!t)return;if(t[e])return t[e];let n=null;for(let[r,i]of Object.entries(t)){if(!/[*?/]/.test(r)||!Ba(r).test(e))continue;let o=r.replace(/[*?]/g,"").length;(!n||o>n.score)&&(n={score:o,act:i})}return n?.act}function La(e){let t=Gr(e),n=[...new Set(e.filter(i=>i.finding_kind==="secret_reuse").map(i=>i.remediation_hint??""))].filter(Boolean),r=[];if(n.length){r.push("","SHARED SECRETS \u2014 read this BEFORE replacing keys:");for(let i of n.sort((o,a)=>Number(a.includes("\u26A0"))-Number(o.includes("\u26A0"))))r.push(` ${i.includes("\u26A0")?"\u{1F534}":"\u25A0"} ${i}`)}if(!t.length)return r;r.push("",`ROTATE AT THE SOURCE \u2014 ${t.reduce((i,o)=>i+o.count,0)} leaked key(s); locking a file does not un-leak a key:`);for(let i of t)r.push(` \u25A0 ${i.provider} \u2014 ${i.count} in ${i.files.length} file(s)${i.url?` \xB7 ${i.url}`:""}`),i.steps.forEach((o,a)=>r.push(` ${a+1}. ${o}`)),r.push(` files: ${i.files.slice(0,6).join(", ")}${i.files.length>6?` \u2026 +${i.files.length-6}`:""}`);return r}function Tu(e,t){let n=ii(yu(),".nodata","reports");mu(n,{recursive:!0});let r=ii(n,`plan-${e.replace(/[^A-Za-z0-9_-]+/g,"_").slice(0,40)||"folder"}-${new Date().toISOString().replace(/[:.]/g,"-")}.csv`),i=o=>`"${o.replace(/"/g,'""')}"`;return gu(r,["file,tier,found,secret,recommended,chosen",...t.map(o=>[i(o.file),o.tier,i(o.found),o.secret,o.action,o.chosen].join(","))].join(`
|
|
73
|
+
`)+`
|
|
74
|
+
`,{mode:384}),r}var ri=40;function Fa(e,t){e.registerTool("nodata_plan",{description:'RECOMMEND a policy after a scan, per file, and apply it only once the user approves. For every file with findings it proposes a tier (Restricted / Confidential / Internal) and an action: "both" (clean copy to work on + lock the original), "protect" (lock), "redact" (clean copy) or "keep"; credentials also get a rotate-at-source step. ASKS FIRST: without confirm:true it only shows the plan. The user may change any action \u2014 pass them as `actions` {"relative/path": "protect"|"redact"|"both"|"keep"} \u2014 then call again with the same path, the same actions and confirm:true. Proposing is not accepting: never confirm on the user\'s behalf. Content-free: paths and counts only.',inputSchema:{path:ct.string().describe("Folder or file to plan for."),actions:ct.record(ct.string(),ct.enum(["both","protect","redact","keep"])).optional().describe(`The user's changes: by relative path, or by folder / pattern for many files at once ("scripts/**": "keep", ".next/**": "keep", "*.env": "protect"). An exact path beats a pattern; a more specific pattern beats a broader one.`),remove_originals:ct.boolean().optional().describe("When locking, delete the plaintext original. Default false (originals kept)."),confirm:ct.boolean().optional().describe("true = the user approved this plan. Omit to show it.")}},async({path:n,actions:r,remove_originals:i,confirm:o})=>{let a=wu(n);if(!Ca(a))return{content:[{type:"text",text:`Nothing found at: ${a}`}],isError:!0};let s=bu(a).isDirectory()?a:ku(a),c=await t.scan(a),l=xu(c.findings.filter(b=>!Ae(b.relative_path)));if(l.length===0)return{content:[{type:"text",text:`No findings in ${a} \u2014 nothing to decide. ${t.who()}`}]};let p=Object.keys(r??{}).filter(b=>!l.some(E=>E.file===b||/[*?/]/.test(b)&&Ba(b).test(E.file))),u=l.map(b=>{let E=Au(b.file,r);return{...b,chosen:E??b.action,changed:!!E&&E!==b.action}}),f=u.length>ri,h=f?Tu(vu(a),u):null,_=new Map;for(let b of u){let E=b.file.split("/"),P=E.length>1?E.slice(0,Math.min(2,E.length-1)).join("/"):"(top level)",I=_.get(P)??{};I[b.chosen]=(I[b.chosen]??0)+1,_.set(P,I)}let y=[..._].sort((b,E)=>Object.values(E[1]).reduce((P,I)=>P+I,0)-Object.values(b[1]).reduce((P,I)=>P+I,0)).slice(0,25).map(([b,E])=>` ${b} \u2014 ${Object.entries(E).map(([P,I])=>`${I} ${ni[P]}`).join(" \xB7 ")}`),v=(f?u.filter(b=>b.tier!=="Internal"||b.changed).slice(0,ri):u).map(b=>` [${b.tier}] ${b.file} \u2014 ${b.found}
|
|
75
|
+
\u2192 ${ni[b.chosen]}${b.changed?` (changed by you; recommended: ${ni[b.action]})`:` \u2014 ${b.why}`}`+(b.secret?`
|
|
76
|
+
\u26A0 also rotate the credential at its source (NoData cannot do that step)`:""));if(!o)return{content:[{type:"text",text:[`RECOMMENDED POLICY \u2014 nothing changed yet. ${t.who()}`,`${l.length} file(s) with findings under ${a}:`,...f?["BY FOLDER",...y,"",`MOST SENSITIVE (first ${ri}; every file is in the list below):`]:[],...v,h?`
|
|
77
|
+
The whole plan, one line per file, content-free: ${Na(h).href}`:"",f?'Decide by folder rather than by file \u2014 e.g. actions: {"scripts/**": "keep", ".next/**": "keep", "*.env": "protect"}.':"",...La(c.findings),p.length?`
|
|
78
|
+
Not in the scan (ignored): ${p.join(", ")}`:"","","Locking keeps the plaintext originals unless remove_originals: true.",'This is a proposal. Show it to the user; they can change any line (e.g. "keep" a file, or "redact" instead of "protect").',"Then call nodata_plan again with the same path, their changes in `actions`, and confirm: true \u2014 only after they approve."].filter(b=>b!=="").join(`
|
|
79
|
+
`)}]};let S=[],w=[],x=[];for(let b of u){let E=ii(s,b.file);if(!Ca(E)){w.push(` \u2717 ${b.file} \u2014 no longer there`);continue}if(b.chosen==="redact"||b.chosen==="both"){let P=t.cleanCopy(E);"error"in P?w.push(` \u2717 ${b.file} \u2014 ${P.error}`):S.push(` \u2713 ${b.file} \u2192 clean copy ${ti(s,P.outPath)} (checked: ${P.verification.values_found} of ${P.verification.values_checked} hidden values left in it)`)}(b.chosen==="protect"||b.chosen==="both")&&x.push(E),b.chosen==="keep"&&S.push(` \xB7 ${b.file} \u2014 left as is (your choice)`)}let m="";if(x.length){let{key:b}=lt.ensureDeviceKey(),E=[];for(let I of x)E.push(await lt.sealFile(I,b)),i&&_u(I),S.push(` \u{1F512} ${ti(s,I)} \u2192 ${ti(s,I)}.ndc${i?" (original deleted)":""}`);let P=u.map(I=>({file:I.file,tier:I.tier,recommended:I.action,chosen:I.chosen}));m=lt.writeLocalReceipt(s,{action:"policy-apply",kid:b.kid,removed_plaintext:!!i,files:E,extra:{approved_by:t.who(),surface:"mcp",plan:P}})}let k=u.filter(b=>b.changed).length,$=await t.ack(`${u.length} files \xB7 ${k} changed by the user \xB7 ${x.length} locked`);return{content:[{type:"text",text:[`APPLIED the approved policy \u2014 ${t.who()}`,...S,...w,...La(c.findings),m?`Receipt (the plan, hashes, seal ids \u2014 no content): ${Na(m).href}`:"",`Approval kept in ~/.nodata/acks.jsonl${Ie($)}.`].filter(Boolean).join(`
|
|
80
|
+
`)}]}})}var Q=(e,t=!1)=>({content:[{type:"text",text:e}],...t?{isError:t}:{}}),Ma=Ge(Iu(),".nodata","reports"),ai=25;function $u(){return new Date().toISOString().replace(/[:.]/g,"-").slice(0,19)}function Ru(e){return e.replace(/[^A-Za-z0-9_-]+/g,"_").slice(0,60)||"folder"}function Ka(e,t,n,r){let i=Vr(li(e),li(t),n,r),o=Ge(Kt(e),".nodata","receipts");Ua(o,{recursive:!0});let a=Ge(o,`redact-verify-${Date.now()}.json`);return Mn(a,JSON.stringify({action:"redact-verify",at:new Date().toISOString(),governed:"local",original:{path:dt(e)},clean:{path:dt(t)},...i},null,2)+`
|
|
81
|
+
`),i.ok?{verification:i,receiptPath:a}:(Va(t,{force:!0}),{error:`The clean copy still held ${i.values_found} of the ${i.values_checked} hidden values, so it was removed \u2014 nothing was handed on. Receipt: ${Mt(a).href}`})}function Ha(e){let t=Pu(e).toLowerCase(),n=li(e),r=t===".xlsx"||t===".xlsm"?In(()=>$t(n)):null,i=r?.result??null;if(i&&r){let f=Ge(Kt(e),`${dt(e,t)}.clean${t}`);Mn(f,i.bytes,{mode:384});let h=Ka(e,f,t,r.replaced);return"error"in h?h:{outPath:f,result:{text:ke(i.bytes,t)?.text??"",counts:i.counts,columnsHidden:i.columnsHidden},note:"",...h}}let o=t===".xlsx"||t===".xlsm"?"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.":"",a=t||".txt",s;if(xn.has(t)){let f=ke(n,t);if(!f)return{error:`Could not read the text of ${e}.`};s=f.text,a=".txt"}else s=n.toString("utf8");let{result:c,replaced:l}=In(()=>t===".csv"||t===".tsv"?Pt(s,t===".tsv"?" ":void 0):de(s)),p=Ge(Kt(e),`${dt(e,t)}.clean${a}`);Mn(p,c.text,{mode:384});let u=Ka(e,p,a,l);return"error"in u?u:{outPath:p,result:c,note:o,...u}}async function si(e,t={}){return Rt({target_id:"mcp",target_label:dt(e),target_path:e,log:Dt,...t})}function ci(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(`
|
|
82
|
+
`)}function Du(e,t,n,r){if(e.error)return`Could not scan ${e.target_path}: ${e.error}`;let i=["critical","high","medium","low","info"].filter(c=>t.bySeverity[c]).map(c=>`${t.bySeverity[c]} ${c}`).join(" \xB7 "),o=[`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${i?" \u2014 "+i:""} in ${t.filesWithFindings.length} files`];t.total>0&&(o.push("","BY TYPE (all)",ci(t.byType,100)),o.push("","BY FOLDER",ci(t.byFolder,10)),o.push("","WORST FILES",ci(t.byFile,12)));let a=e.coverage,s=[];return a?.hit_file_cap&&(s.push(` \u26A0 stopped after ${a.max_files} files \u2014 NOT everything was scanned.`),a.not_reached?.length&&s.push(` not reached: ${a.not_reached.join(", ")}`," \u2192 scan those folders on their own, or raise max_files (up to 50000).")),a?.hit_depth_cap&&s.push(` \u26A0 folders deeper than ${a.max_depth} levels were not descended.`),a?.tool_dirs_skipped&&s.push(` \xB7 skipped ${a.tool_dirs_skipped} tool / cache folder(s) \u2014 not your files: ${a.tool_dir_names.join(", ")} (include_tool_dirs: true to scan them).`),s.length&&o.push("","COVERAGE",...s),n&&o.push("","FULL REPORT (every finding, content-free) \u2014 open in a browser:",` ${Mt(n).href}`),t.total>0&&o.push("","NEXT \u2014 same workspace:",` \xB7 RECOMMEND a policy per file (you approve or change it): nodata_plan path: "${e.target_path}"`,...e.findings.some(c=>c.finding_kind==="hardcoded_secret")?[" \xB7 LEAKED KEYS: nodata_plan also lists, per provider, where and how to replace each one \u2014 the step that actually stops their use."]:[],` \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"),o.join(`
|
|
83
|
+
`)}function Ga(e,t,n=async()=>!1){Fa(e,{who:t,scan:si,cleanCopy:Ha,ack:n}),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:he.string().optional().describe("Folder or single file to scan. Default: the directory the server runs in."),max_files:he.number().int().min(1).max(5e4).optional().describe("Files to walk before stopping. Default 5000; raise it for a home folder or a large drive."),include_tool_dirs:he.boolean().optional().describe("Also scan tool / cache folders (.cache, .cargo, editor extensions, AppData \u2026). Default false \u2014 they hold samples, not the user's files.")}},async({path:o,max_files:a,include_tool_dirs:s})=>{let c=Fn((o??".").trim()||".");if(!Ft(c))return Q(`Nothing found at: ${c}`);try{let l=await si(c,{max_files:a,include_tool_dirs:s}),p=Ue(l),u=null;return l.error||(Ua(Ma,{recursive:!0}),u=Ge(Ma,`scan-${Ru(dt(c))}-${$u()}.html`),Mn(u,Ur(l,p),{mode:384})),Q(Du(l,p,u,t()))}catch(l){return Q(`Scan failed: ${l instanceof Error?l.message:String(l)}`,!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:he.string().describe("File or folder to protect."),confirm:he.boolean().optional().describe("true = do it. Omit to preview."),remove:he.boolean().optional().describe("Delete the plaintext originals after sealing. Default false.")}},async({path:o,confirm:a,remove:s})=>{let c=Fn(o);if(!Ft(c))return Q(`Not found: ${c}`,!0);let l=oi(c).isDirectory(),p;if(l?p=Ue(await si(c)).filesWithFindings.map(S=>Ge(c,S)).filter(S=>Ft(S)&&oi(S).isFile()&&!Ae(S)):p=c.endsWith(".ndc")?[]:[c],p.length===0)return Q(`Nothing to seal in ${c} \u2014 no file with findings.`);if(!a){let v=p.slice(0,ai).map(S=>` \xB7 ${S}`);return p.length>ai&&v.push(` \u2026 and ${p.length-ai} more`),Q([`PREVIEW \u2014 nothing changed yet. ${t()}`,`Would seal ${p.length} file(s) to this device's key${s?" and DELETE the plaintext originals":" (originals kept)"}:`,...v,"","Ask the user to approve, then call nodata_protect again with confirm: true."].join(`
|
|
84
|
+
`))}let{key:u,created:f}=ue.ensureDeviceKey(),h=[];for(let v of p)h.push(await ue.sealFile(v,u)),s&&Va(v);let _=l?c:Kt(c),y=ue.writeLocalReceipt(_,{action:"protect",kid:u.kid,removed_plaintext:!!s,files:h,extra:{approved_by:t(),surface:"mcp"}});return Q([`SEALED ${h.length} file(s) \u2014 ${t()}${f?" \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: ${u.kid}`,s?"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): ${Mt(y).href}`,'Open one again: nodata_open path: "<file>.ndc"'].join(`
|
|
85
|
+
`))}),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:he.string().describe("The .ndc file to open."),confirm:he.boolean().optional().describe("true = open it. Omit to preview.")}},async({path:o,confirm:a})=>{let s=Fn(o),c=Ft(s)?ue.readManifest(s):null;if(!c)return Q(`Not a NoData sealed file: ${s}`,!0);if(!a)return Q(`PREVIEW \u2014 nothing changed yet. ${t()}
|
|
86
|
+
Would open "${c.orig}" (sealed ${c.sealed_at}, device key ${c.kid}) as plaintext next to ${s}.
|
|
87
|
+
Ask the user to approve, then call nodata_open again with confirm: true.`);let l=await ue.openFile(s);if(!l.ok){let u=l.error==="wrong_key"?"this device's key is not the one it was sealed to":l.error==="no_device_key"?"this machine has no device key (~/.nodata/device-key.json)":l.error;return Q(`Could not open ${s}: ${u}.`,!0)}let p=ue.writeLocalReceipt(Kt(s),{action:"open",kid:c.kid,removed_plaintext:!1,files:[{path:l.outPath,ndc:s,sha256:l.sha256,sealId:c.token.split(":").pop()??""}],extra:{approved_by:t(),surface:"mcp",hash_matches:l.intact}});return Q([`OPENED ${l.outPath} \u2014 ${t()}`,l.intact?"Hash matches what was sealed \u2014 the file is unaltered.":"WARNING: hash differs from the sealed record.",`Receipt: ${Mt(p).href}`].join(`
|
|
88
|
+
`))}),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 replaced whole with one stable token per value ([NAME-1], [NAME-2] \u2026 \u2014 the same person keeps the same token), so rows and columns still line up and still group by person. Columns of amounts stay whole. 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. ON SCREEN: someone may be sitting next to the user. Answer with totals, counts and summaries by default; ask before printing rows or individual values, even from the clean copy (a value the detectors did not recognise is still in it).",inputSchema:{path:he.string().describe("The file to redact (csv, tsv, txt, md, json, log, docx, xlsx, pptx, pdf)."),return_text:he.boolean().optional().describe("Also return the clean text for analysis.")}},async({path:o,return_text:a})=>{let s=Fn(o);if(!Ft(s)||!oi(s).isFile())return Q(`Not a file: ${s}`,!0);let c=Ha(s);if("error"in c)return Q(c.error,!0);let l=c.verification,p=await n(`redact-verify \xB7 ${l.values_checked} values checked \xB7 ${l.values_found} found \xB7 clean ${l.clean_sha256.slice(0,16)}`);return Q(i(c.outPath,c.result,a,c.note)+`
|
|
89
|
+
|
|
90
|
+
`+r(c,p))});function r(o,a){let s=o.verification;return["PROOF \u2014 the copy was checked before it was kept:",` ${s.values_checked} hidden values searched in all ${s.parts_searched} part(s) of the clean file \u2192 ${s.values_found} found.`+(s.values_too_short_to_check?` (${s.values_too_short_to_check} too short to search reliably.)`:""),` Re-scan of the clean text: ${s.rescan_hits===0?"no validated value":`${s.rescan_hits} validated-looking value(s) \u2014 amounts the amount rule keeps can pass a check digit; review if unexpected`}.`,` Fingerprints (SHA-256): original ${s.original_sha256.slice(0,16)}\u2026 \xB7 clean ${s.clean_sha256.slice(0,16)}\u2026`,` Receipt: ${Mt(o.receiptPath).href}${Ie(a)}`," Limit: proves the copy holds none of the values the detectors found; a value they did not recognise was never hidden."].join(`
|
|
91
|
+
`)}function i(o,a,s,c=""){let l=Object.entries(a.counts).sort((u,f)=>f[1]-u[1]).map(([u,f])=>` ${String(f).padStart(6)} ${u}`),p=[`CLEAN COPY ${o} \u2014 ${t()} \xB7 original untouched`,c,l.length?`Replaced:
|
|
92
|
+
${l.join(`
|
|
93
|
+
`)}`:"Nothing sensitive detected \u2014 the copy equals the original text.",a.columnsHidden.length?`Columns hidden whole: ${a.columnsHidden.join(", ")}`:""].filter(Boolean);return s&&p.push("",`--- clean text${a.text.length>6e4?" (first 60000 chars)":""} ---`,a.text.slice(0,6e4)),p.join(`
|
|
94
|
+
`)}}var sr=xr(nc(),1);import{z as Qe}from"zod";import{createHash as Gf}from"node:crypto";import{existsSync as Bi,mkdirSync as Wf,readFileSync as sc,readdirSync as zf,statSync as rc,writeFileSync as qf}from"node:fs";import{homedir as Jf}from"node:os";import{basename as Li,extname as Xf,join as cc,resolve as Yf}from"node:path";var ne=(e,t=!1)=>({content:[{type:"text",text:e}],...t?{isError:t}:{}}),ar=cc(Jf(),".nodata","shares"),Zf=12*1024*1024,Qf={".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 lc(e){return cc(ar,`${e.replace(/[^a-f0-9]/gi,"")}.json`)}function ic(e){let t=lc(e);if(!Bi(t))return null;try{return JSON.parse(sc(t,"utf8"))}catch{return null}}function oc(e){let t=e.match(/\/lock\/open\/([a-f0-9]{8,64})/i);return(t?t[1]:e.trim()).toLowerCase()}async function ac(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 dc(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:Qe.string().describe("The file to send (up to 12 MB)."),ttl_hours:Qe.number().optional().describe("Hours until the link expires. Default 72, max 168 (7 days)."),max_opens:Qe.number().optional().describe("Opens allowed before it burns itself. Default 3, max 1000."),confirm:Qe.boolean().optional().describe("true = send it. Omit to preview.")}},async({path:i,ttl_hours:o,max_opens:a,confirm:s})=>{let c=Yf(i);if(!Bi(c)||!rc(c).isFile())return ne(`Not a file: ${c}`,!0);let l=rc(c).size;if(l>Zf)return ne(`${Li(c)} is ${(l/1048576).toFixed(1)} MB; a governed link carries up to 12 MB.`,!0);let p=Math.round(Math.min(Math.max(o??72,1/60),168)*3600),u=Math.round(Math.min(Math.max(a??3,1),1e3));if(!s)return ne([`PREVIEW \u2014 nothing sent yet. ${r()}`,`Would send "${Li(c)}" (${(l/1024).toFixed(1)} KB) as a governed link:`," \xB7 encrypted here; NoData stores only ciphertext and never gets the key",` \xB7 expires in ${(p/3600).toFixed(p<3600?2:0)} h, or after ${u} 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(`
|
|
95
|
+
`));let f=sc(c),h=Li(c),_=Qf[Xf(c).toLowerCase()]??"application/octet-stream",y=await(0,sr.sealBytesForPublicShare)({bytes:f,filename:h,contentType:_,ttlSeconds:p,server:t}),v=await(0,sr.wrapFragmentForShortLink)(y.fragment),S;try{S=await ac(`${t}/api/lock/public/issue`,{formatVersion:3,lockboxId:y.lockboxId,containerB64:Buffer.from(y.container).toString("base64"),filename:h,contentType:_,ttlSeconds:p,maxOpens:u,wrappedFragmentB64:v.wrappedFragmentB64,wrapIvB64:v.wrapIvB64},await n())}catch(m){return ne(`Could not reach NoData: ${m instanceof Error?m.message:String(m)}`,!0)}if(S.status>=400||S.body.ok!==!0)return ne(`Send refused (HTTP ${S.status}): ${JSON.stringify(S.body)}`,!0);let w=String(S.body.id),x={id:w,file:c,filename:h,sha256:Gf("sha256").update(f).digest("hex"),link:`${t}/lock/open/${w}#${v.wrapKeyB64Url}`,wrap_key_b64url:v.wrapKeyB64Url,expires_at:String(S.body.expiresAt??""),max_opens:u,sent_by:r(),sent_at:new Date().toISOString(),receipt_id:S.body.receipt_id??null,proof_url:S.body.proof_url??null};return Wf(ar,{recursive:!0}),qf(lc(w),JSON.stringify(x,null,2)+`
|
|
96
|
+
`,{mode:384}),ne([`SENT "${h}" \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 ${u} 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(`
|
|
97
|
+
`))}),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:Qe.string().optional().describe("Share id or /lock/open link. Omit to list all.")}},async({id:i})=>{let o=i?[oc(i)]:Bi(ar)?zf(ar).filter(s=>s.endsWith(".json")).map(s=>s.slice(0,-5)):[];if(o.length===0)return ne("No links sent from this machine yet. Send one with nodata_send.");let a=[`LINKS \u2014 ${r()}`];for(let s of o.slice(0,50)){let c=ic(s),l={};try{let u=await fetch(`${t}/api/lock/public/status/${s}`);l=await u.json().catch(()=>({})),u.status===404&&(l={missing:!0})}catch{l={unreachable:!0}}let p=l.missing?"not found":l.unreachable?"status unavailable":l.burned?"BURNED":l.expired?"expired":"live";a.push(` ${s} ${p.padEnd(10)} opens ${l.openCount??"?"}/${l.maxOpens??c?.max_opens??"?"} expires ${l.expiresAt??c?.expires_at??"?"} ${c?c.filename:""}`)}return ne(a.join(`
|
|
98
|
+
`))}),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:Qe.string().describe("Share id or the /lock/open link."),confirm:Qe.boolean().optional().describe("true = burn it. Omit to preview.")}},async({id:i,confirm:o})=>{let a=oc(i),s=i.match(/#([A-Za-z0-9_-]{43})/)?.[1],c=ic(a),l=c?.wrap_key_b64url??s;if(!l)return ne(`No burn key for ${a} on this machine. Pass the full link (it carries the key after #), or burn it from the machine that sent it.`,!0);if(!o)return ne(`PREVIEW \u2014 nothing burned yet. ${r()}
|
|
73
99
|
Would burn ${c?`"${c.filename}" `:""}(${a}). After this NOBODY can open it again \u2014 irreversible.
|
|
74
|
-
Ask the user to approve, then call nodata_burn again with confirm: true.`);let
|
|
75
|
-
`))})}import{appendFileSync as
|
|
100
|
+
Ask the user to approve, then call nodata_burn again with confirm: true.`);let p;try{p=await ac(`${t}/api/lock/public/burn/${a}`,{wrapKeyB64Url:l})}catch(u){return ne(`Could not reach NoData: ${u instanceof Error?u.message:String(u)}`,!0)}return p.status>=400||p.body.ok!==!0?ne(`Burn refused (HTTP ${p.status}): ${JSON.stringify(p.body)}`,!0):ne([`BURNED ${a} \u2014 ${r()}. The ciphertext is zeroed; the link is dead for everyone.`,p.body.proof_url?`Proof (signed receipt, public): ${p.body.proof_url}`:""].filter(Boolean).join(`
|
|
101
|
+
`))})}import{appendFileSync as eh,copyFileSync as uc,existsSync as Hi,mkdirSync as Ui,readFileSync as Vi,statSync as fc,writeFileSync as hc}from"node:fs";import{homedir as Le}from"node:os";import{basename as th,extname as mc,isAbsolute as nh,join as je,resolve as rh}from"node:path";var ih=new Set([".csv",".tsv",".txt",".md",".json",".log",".xml",".sql",".yaml",".yml",".xlsx",".xlsm",".docx",".pptx",".pdf"]),oh=50*1024*1024,ah=8,sh={israeli_id:"Israeli ID",credit_card:"card",iban:"IBAN",israeli_phone:"phone",email:"email",secret:"secret"};function gc(e){let t=th(e).toLowerCase();return ih.has(mc(t))||t===".env"||t.startsWith(".env.")}function ch(e){let t=mc(e).toLowerCase(),n=Vi(e),r,i;if(t===".csv"||t===".tsv")i=n.toString("utf8"),r=Pt(i,t===".tsv"?" ":void 0).counts;else if(t===".xlsx"||t===".xlsm"||t===".docx"||t===".pptx"||t===".pdf"){let a=t===".xlsx"||t===".xlsm"?$t(n):null;i=ke(n,t)?.text??"",r=a?a.counts:de(i).counts}else i=n.toString("utf8"),r=de(i).counts;let o=vn.filter(a=>a.pattern.test(i)).length;return o&&(r.secret=(r.secret??0)+o),r}var lh={israeli_id:"\u05EA\u05E2\u05D5\u05D3\u05EA \u05D6\u05D4\u05D5\u05EA",id:"\u05EA\u05E2\u05D5\u05D3\u05EA \u05D6\u05D4\u05D5\u05EA",credit_card:"\u05DB\u05E8\u05D8\u05D9\u05E1 \u05D0\u05E9\u05E8\u05D0\u05D9",iban:"IBAN",israeli_phone:"\u05D8\u05DC\u05E4\u05D5\u05DF",phone:"\u05D8\u05DC\u05E4\u05D5\u05DF",email:'\u05D3\u05D5\u05D0"\u05DC',secret:"\u05E1\u05D5\u05D3",name:"\u05E9\u05DD",address:"\u05DB\u05EA\u05D5\u05D1\u05EA",policy:"\u05DE\u05E1\u05E4\u05E8 \u05E4\u05D5\u05DC\u05D9\u05E1\u05D4",agent_id:"\u05DE\u05E1\u05E4\u05E8 \u05E1\u05D5\u05DB\u05DF",financial:"\u05DE\u05D9\u05D3\u05E2 \u05E4\u05D9\u05E0\u05E0\u05E1\u05D9",medical:"\u05DE\u05D9\u05D3\u05E2 \u05E8\u05E4\u05D5\u05D0\u05D9",dob:"\u05EA\u05D0\u05E8\u05D9\u05DA \u05DC\u05D9\u05D3\u05D4",bank_account:"\u05D7\u05E9\u05D1\u05D5\u05DF \u05D1\u05E0\u05E7",plate:"\u05DE\u05E1\u05E4\u05E8 \u05E8\u05DB\u05D1"};function dh(e){let t=Te()==="he",n=r=>(t?lh[r]:sh[r])??r;return Object.entries(e).sort((r,i)=>i[1]-r[1]).map(([r,i])=>`${i} ${r.startsWith("column:")?`${n(r.slice(7))} (${t?"\u05E2\u05DE\u05D5\u05D3\u05D4":"column"})`:n(r)}`).join(", ")}function uh(e,t,n){let r=o=>nh(o)?o:rh(n,o),i=o=>{try{return fc(o).isFile()}catch{return!1}};if(e==="Read"&&typeof t.file_path=="string")return[r(t.file_path)];if(e==="Grep"&&typeof t.path=="string"&&i(r(t.path)))return[r(t.path)];if((e==="Bash"||e==="PowerShell")&&typeof t.command=="string"){let o=t.command,a=[...[...o.matchAll(/"([^"]*)"/g)].map(c=>c[1]),...[...o.matchAll(/'([^']*)'/g)].map(c=>c[1]),...o.split(/[\s|;&<>(),=`]+/)],s=[];for(let c of a){let l=c.trim().replace(/^['"]|['"]$/g,"").replace(/\\\\/g,"\\").replace(/^~(?=[\\/])/,Le()).replace(/^\/([a-zA-Z])\//,(u,f)=>process.platform==="win32"?`${f}:/`:u);if(!l||!gc(l))continue;let p=r(l);if(i(p)&&!s.includes(p)&&s.push(p),s.length>=ah)break}return s}return[]}function Fi(e){return e.replace(/\\+/g,"/")}function ph(e){let t=e.trim();return/[;|&\n]|`|\$\(/.test(t.replace(/^cmd(?:\.exe)?\s+\/c\s+/i,""))?!1:/^(?:cmd(?:\.exe)?\s+\/c\s+)?(?:explorer(?:\.exe)?|start|invoke-item|ii|start-process|open|xdg-open)\b/i.test(t)}function yc(e,t,n){let r=[];if((e==="Bash"||e==="PowerShell")&&typeof t.command=="string"&&ph(t.command))return r;for(let i of uh(e,t,n)){if(!gc(i)||Ae(i)||!Hi(i))continue;let o;try{if(fc(i).size>oh)o=`${Fi(i)}: too large to check here (over 50 MB)`;else{let a=ch(i);if(Object.keys(a).length===0)continue;o=`${Fi(i)}: ${dh(a)}`}}catch{o=`${Fi(i)}: could not be checked`}r.push(o)}return r}function fh(e,t,n,r){let i=yc(e,t,n);if(i.length===0)return{decision:"allow"};let o=va(`NoData \u05E1\u05E8\u05E7 \u05D0\u05EA \u05D4\u05E7\u05D5\u05D1\u05E5 \u05D1\u05DE\u05D7\u05E9\u05D1 \u05E9\u05DC\u05DA \u2014 \u05E9\u05D5\u05DD \u05D3\u05D1\u05E8 \u05DC\u05D0 \u05D9\u05E6\u05D0:
|
|
76
102
|
${i.join(`
|
|
77
103
|
`)}
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
`)}
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
104
|
+
`+(r?"\u05D4\u05E7\u05E8\u05D9\u05D0\u05D4 \u05E0\u05D7\u05E1\u05DE\u05D4: Claude \u05DC\u05D0 \u05D9\u05E7\u05E8\u05D0 \u05D0\u05EA \u05D4\u05DE\u05E7\u05D5\u05E8. \u05D1\u05DE\u05E7\u05D5\u05DD \u05D6\u05D4: nodata_redact (\u05E2\u05D5\u05EA\u05E7 \u05E0\u05E7\u05D9 \u05DC\u05E2\u05D1\u05D5\u05D3\u05D4) \u05D0\u05D5 nodata_protect (\u05E0\u05E2\u05D9\u05DC\u05D4).":"\u05D0\u05DD \u05EA\u05D0\u05E9\u05E8, Claude \u05D9\u05E7\u05E8\u05D0 \u05D0\u05EA \u05D4\u05E7\u05D5\u05D1\u05E5 \u05E2\u05E6\u05DE\u05D5 \u05D5\u05D4\u05EA\u05D5\u05DB\u05DF \u05D9\u05D9\u05E9\u05DC\u05D7 \u05DC\u05DE\u05D5\u05D3\u05DC \u05D4\u05D1\u05D9\u05E0\u05D4 \u05D4\u05DE\u05DC\u05D0\u05DB\u05D5\u05EA\u05D9\u05EA. \u05D1\u05DE\u05E7\u05D5\u05DD \u05D6\u05D4: nodata_redact (\u05E2\u05D5\u05EA\u05E7 \u05E0\u05E7\u05D9 \u05DC\u05E2\u05D1\u05D5\u05D3\u05D4) \u05D0\u05D5 nodata_protect (\u05E0\u05E2\u05D9\u05DC\u05D4). \u05DC\u05D0\u05E9\u05E8 \u05D1\u05DB\u05DC \u05D6\u05D0\u05EA?"),`NoData scanned this file on your machine \u2014 nothing left it:
|
|
105
|
+
${i.join(`
|
|
106
|
+
`)}
|
|
107
|
+
`+(r?"Read refused: Claude will not read the original. Instead: nodata_redact (a clean copy to work on) or nodata_protect (lock it).":"If you allow it, Claude reads the file itself and its content goes to the AI model. Instead: nodata_redact (a clean copy to work on) or nodata_protect (lock it). Allow anyway?"));return{decision:r?"deny":"ask",reason:o}}function hh(e,t,n){let r=yc(e,t,n);return r.length===0?null:`NoData \xB7 ON SCREEN rule. What you just read holds personal data:
|
|
108
|
+
${r.join(`
|
|
109
|
+
`)}
|
|
110
|
+
The user's screen is not private \u2014 someone may be beside them. Answer with totals, counts, groupings and trends. Do not print names, ID / policy / account numbers, addresses, phones, or amounts tied to a person \u2014 not in a table, not as an "example" \u2014 unless the user explicitly asks to see those values. For a clean, anonymised or shareable version use nodata_redact \u2014 never your own script: it verifies the copy and records a proof.`+(Te()==="he"?" Answer the user in Hebrew.":"")}function mh(e){try{let t=je(Le(),".nodata");Ui(t,{recursive:!0}),eh(je(t,"gate.log"),JSON.stringify({at:new Date().toISOString(),...e})+`
|
|
111
|
+
`,{mode:384})}catch{}}async function _c(e){let t=e.includes("--block"),n=e.includes("--post"),r="";for await(let s of process.stdin)r+=s;let i;try{i=JSON.parse(r)}catch{return}let o=i.tool_name??"";if(n){let s=hh(o,i.tool_input??{},i.cwd??process.cwd());s&&process.stdout.write(JSON.stringify({hookSpecificOutput:{hookEventName:"PostToolUse",additionalContext:s}}));return}let a=fh(o,i.tool_input??{},i.cwd??process.cwd(),t);a.decision!=="allow"&&(mh({tool:o,decision:a.decision}),process.stdout.write(JSON.stringify({hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:a.decision,permissionDecisionReason:a.reason}})))}var cr=()=>je(Le(),".nodata","gate.mjs"),Gi=()=>je(Le(),".claude","settings.json"),Mi="Read|Grep|Bash|PowerShell",pc=()=>je(Le(),".nodata","status.mjs"),Ki=()=>je(Le(),".nodata","statusline-prev.json"),bc=e=>!!e&&(e.command.includes(".nodata/status.mjs")||e.command.includes(".nodata\\status.mjs")),nn=e=>(e.hooks??[]).some(t=>t.command.includes(".nodata/gate.mjs")||t.command.includes(".nodata\\gate.mjs"));function vc(){let e=Gi();return Hi(e)?JSON.parse(Vi(e,"utf8")):{}}function kc(e){Ui(je(Le(),".claude"),{recursive:!0}),hc(Gi(),JSON.stringify(e,null,2)+`
|
|
112
|
+
`)}function wc(e,t){Ui(je(Le(),".nodata"),{recursive:!0}),uc(e,cr());let n=vc(),r=n.hooks??={},i=(r.PreToolUse??=[]).filter(a=>!nn(a));i.push({matcher:Mi,hooks:[{type:"command",command:`node "${cr().replace(/\\/g,"/")}"${t?" --block":""}`,timeout:30}]}),r.PreToolUse=i;let o=(r.PostToolUse??=[]).filter(a=>!nn(a));return o.push({matcher:Mi,hooks:[{type:"command",command:`node "${cr().replace(/\\/g,"/")}" --post`,timeout:30}]}),r.PostToolUse=o,uc(new URL("./status.js",e),pc()),n.statusLine&&!bc(n.statusLine)&&hc(Ki(),JSON.stringify(n.statusLine,null,2)+`
|
|
113
|
+
`),n.statusLine={type:"command",command:`node "${pc().replace(/\\/g,"/")}"`},kc(n),`NoData read gate installed (${t?"block":"ask"} mode).
|
|
114
|
+
hook: ${Gi()} \u2192 PreToolUse ${Mi} (+ PostToolUse: on-screen reminder after an approved read)
|
|
115
|
+
scanner: ${cr()}
|
|
84
116
|
Before Claude Code reads a data file (csv, xlsx, docx, pdf, .env \u2026), NoData scans it here.
|
|
85
117
|
Findings \u2192 ${t?"the read is refused":"you are asked first"}, with the counts and the safer step.
|
|
86
118
|
Status line: "\u25CF NoData" at the bottom of Claude Code \u2014 green = guarded, yellow = gate off, red = terms not accepted; no segment = not guarded.
|
|
87
|
-
Restart Claude Code to load it. Remove with: npx @nodatachat/mcp uninstall-gate`}function Ss(){let e=bs(),t=e.hooks?.PreToolUse;if(!t||!t.some(gi))return"The NoData read gate is not installed.";if(e.hooks.PreToolUse=t.filter(n=>!gi(n)),e.hooks.PreToolUse.length===0&&delete e.hooks.PreToolUse,_s(e.statusLine)){let n=yi(mi())?JSON.parse(bi(mi(),"utf8")):null;n?e.statusLine=n:delete e.statusLine}return vs(e),"NoData read gate removed. Restart Claude Code to unload it."}var Xp=[{type:"id_number",patterns:[/\b\d{9}\b/g,/ת\.?ז\.?\s*:?\s*(\d{9})/g,/זהות\s*:?\s*(\d{9})/g],confidence:.9,replacement:()=>"[\u05EA.\u05D6. \u05DE\u05D5\u05E1\u05EA\u05E8]"},{type:"phone",patterns:[/\b0[2-9]\d[\s\-]?\d{7}\b/g,/\b05[0-9][\s\-]?\d{7}\b/g,/\+972[\s\-]?[2-9]\d[\s\-]?\d{7}\b/g],confidence:.95,replacement:()=>"[\u05D8\u05DC\u05E4\u05D5\u05DF \u05DE\u05D5\u05E1\u05EA\u05E8]"},{type:"email",patterns:[/[a-zA-Z0-9._%+\-]+@[a-zA-Z0-9.\-]+\.[a-zA-Z]{2,}/g],confidence:.99,replacement:e=>{let[,t]=e.split("@");return`[\u05D0\u05D9\u05DE\u05D9\u05D9\u05DC: ***@${t}]`}},{type:"full_name",patterns:[/(?:לקוח|מטופל|מועמד|שם|נהג|מבוטח|תובע|נתבע|שוכר|מחזיק)[:\s]+([א-ת][א-ת"'\-\s]{2,30}?)(?=[,\n\d]|ת\.ז)/g,/(?:עו"ד|ד"ר|פרופ'|מר|גברת)\s+([א-ת][א-ת"'\-\s]{2,25}?)(?=[,\n])/g],confidence:.75,replacement:()=>"[\u05E9\u05DD \u05DE\u05D5\u05E1\u05EA\u05E8]"},{type:"bank_account",patterns:[/\b\d{2}[\-]\d{5,9}[\-]\d{2,3}\b/g,/(?:חשבון|ח-ן)\s*:?\s*(\d[\d\-]{8,15})/g],confidence:.88,replacement:()=>"[\u05D7\u05E9\u05D1\u05D5\u05DF \u05D1\u05E0\u05E7 \u05DE\u05D5\u05E1\u05EA\u05E8]"},{type:"medical",patterns:[/(?<![א-ת])[בהוכלמש]{0,2}(?:סוכרת|יתר לחץ דם|אסתמה|דיכאון|חרדה|סרטן|אי ספיקת לב|אפילפסיה)(?![א-ת])/g,/\b(?:Metformin|Lisinopril|Atorvastatin|Amlodipine|Sertraline|Fluoxetine|Omeprazole|Warfarin|Aspirin|Insulin)\b/gi,/\bHbA1c\s*:?\s*[\d.]+%?/g,/\bBMI\s*:?\s*[\d.]+/g,/(?<![א-ת])[בהוכלמש]{0,2}אבחנ[הות]\s*:?\s*[^,\n.]{2,40}/g],confidence:.85,replacement:()=>"[\u05DE\u05D9\u05D3\u05E2 \u05E8\u05E4\u05D5\u05D0\u05D9 \u05DE\u05D5\u05E1\u05EA\u05E8]"},{type:"financial_amount",patterns:[/[\d,]+(?:\.\d{2})?\s*(?:₪|ש"ח|NIS|שקל(?:ים)?)/g,/(?:₪|NIS)\s*[\d,]+(?:\.\d{2})?/g],confidence:.92,replacement:()=>"[\u05E1\u05DB\u05D5\u05DD \u05DB\u05E1\u05E4\u05D9 \u05DE\u05D5\u05E1\u05EA\u05E8]"},{type:"birth_date",patterns:[/(?:תאריך לידה|נולד|נולדה|ד\.ל\.)\s*:?\s*\d{1,2}[\/\.\-]\d{1,2}[\/\.\-]\d{2,4}/g,/(?<![א-ת])[בהוכלמש]{0,2}גיל\s*:?\s*\d{1,3}\b/g],confidence:.88,replacement:()=>"[\u05EA\u05D0\u05E8\u05D9\u05DA \u05DC\u05D9\u05D3\u05D4 \u05DE\u05D5\u05E1\u05EA\u05E8]"},{type:"address",patterns:[/רחוב\s+[א-ת][א-ת\s"'\-]{2,30}\s+\d{1,5}/g,/(?:רח'|רח\.)\s+[א-ת][א-ת\s"'\-]{2,30}\d{1,5}/g],confidence:.72,replacement:()=>"[\u05DB\u05EA\u05D5\u05D1\u05EA \u05DE\u05D5\u05E1\u05EA\u05E8\u05EA]"},{type:"license_plate",patterns:[/\b\d{2,3}[\-]\d{2,3}[\-]\d{2,3}\b/g],confidence:.8,replacement:()=>"[\u05DC\u05D5\u05D7\u05D9\u05EA \u05E8\u05D9\u05E9\u05D5\u05D9 \u05DE\u05D5\u05E1\u05EA\u05E8\u05EA]"}];function Yp(e){if(e.length!==9)return!1;let t=e.split("").map(Number),n=0;for(let r=0;r<9;r++){let i=t[r]*(r%2===0?1:2);i>9&&(i-=9),n+=i}return n%10===0}var Kn=class{constructor(t){this.enabledTypes=new Set(t)}detect(t){let n=[],r=new Set;for(let o of Xp)if(this.enabledTypes.has(o.type))for(let a of o.patterns){let s=new RegExp(a.source,a.flags),c;for(;(c=s.exec(t))!==null;){let l=c[0],u=`${o.type}:${c.index}`;if(!r.has(u)){if(r.add(u),o.type==="id_number"){let p=l.replace(/\D/g,"");if(/^\d{9}$/.test(l)&&p.length===9&&!Yp(p))continue}n.push({type:o.type,value:l,startIndex:c.index,endIndex:c.index+l.length,confidence:o.confidence,replacement:o.replacement(l,o.type)})}}}n.sort((o,a)=>o.startIndex-a.startIndex||a.confidence-o.confidence);let i=[];for(let o of n)i.some(s=>o.startIndex<s.endIndex&&o.endIndex>s.startIndex)||i.push(o);return i}};var Zp=[{pattern:/^(?:שם|שם_מלא|שם פרטי|שם_פרטי|שם משפחה|שם_משפחה|שם_אדם|שם הלקוח|שם_הלקוח|שם בן זוג|שם בן_זוג|שם המבוטח|שם_המבוטח|שם המוטב|שם_המוטב|שם מבוטח|שם_מבוטח|שם מוטב|שם_מוטב|שם הילד|שם_הילד|שם הקטין|שם_הקטין|firstname_he|lastname_he|shem|shem_mishpacha|shem_prati)$/i,type:"name",label:"Person name (Hebrew)",labelHe:"\u05E9\u05DD \u05D0\u05D3\u05DD"},{pattern:/^(?:ת"ז|ת\.ז|ת ז|תז|תעודת זהות|תעודת_זהות|מספר זהות|מספר_זהות|מס' זהות|מס_זהות|מס' ת"ז|teudat_zehut|tz|t_z|israeli_id|il_id)$/i,type:"id",label:"Israeli ID",labelHe:"\u05EA\u05E2\u05D5\u05D3\u05EA \u05D6\u05D4\u05D5\u05EA"},{pattern:/^(?:דרכון|מספר דרכון|מס דרכון|רישיון נהיגה|רישיון_נהיגה|רשיון נהיגה|מס רישיון|דרכון_מספר)$/i,type:"id",label:"Passport / DL (Hebrew)",labelHe:"\u05D3\u05E8\u05DB\u05D5\u05DF/\u05E8\u05D9\u05E9\u05D9\u05D5\u05DF"},{pattern:/^(?:מייל|דוא"ל|דוא_ל|דואר אלקטרוני|דואר_אלקטרוני|אימייל|כתובת מייל|כתובת_מייל|כתובת דואר|כתובת_דואר)$/i,type:"email",label:"Email (Hebrew)",labelHe:"\u05D3\u05D5\u05D0\u05E8 \u05D0\u05DC\u05E7\u05D8\u05E8\u05D5\u05E0\u05D9"},{pattern:/^(?:טלפון|טל'|נייד|פלאפון|סלולרי|מספר טלפון|מספר_טלפון|טלפון נייד|טלפון_נייד|מס נייד|מס_נייד|מס' טל)$/i,type:"phone",label:"Phone (Hebrew)",labelHe:"\u05DE\u05E1\u05E4\u05E8 \u05D8\u05DC\u05E4\u05D5\u05DF"},{pattern:/^(?:כתובת|כתובת מגורים|כתובת_מגורים|רחוב|מס בית|מספר בית|עיר|ישוב|יישוב|מיקוד|כתובת מלאה|כתובת_מלאה|מען)$/i,type:"address",label:"Address (Hebrew)",labelHe:"\u05DB\u05EA\u05D5\u05D1\u05EA"},{pattern:/^(?:תאריך לידה|תאריך_לידה|ת לידה|תאריך הולדת|תאריך_הולדת|יום הולדת|יום_הולדת|גיל)$/i,type:"dob",label:"Date of birth (Hebrew)",labelHe:"\u05EA\u05D0\u05E8\u05D9\u05DA \u05DC\u05D9\u05D3\u05D4"},{pattern:/^(?:חשבון בנק|חשבון_בנק|מספר חשבון|מספר_חשבון|מס חשבון|מס' חשבון|בנק|סניף|מס סניף|iban|iban_il)$/i,type:"financial",label:"Bank account (Hebrew)",labelHe:"\u05D7\u05E9\u05D1\u05D5\u05DF \u05D1\u05E0\u05E7"},{pattern:/^(?:כרטיס אשראי|כרטיס_אשראי|מספר אשראי|מס אשראי|מס' אשראי|cvv|אשראי|מס כרטיס|מס_כרטיס)$/i,type:"financial",label:"Credit card (Hebrew)",labelHe:"\u05DB\u05E8\u05D8\u05D9\u05E1 \u05D0\u05E9\u05E8\u05D0\u05D9"},{pattern:/^(?:שכר|משכורת|הכנסה|פרמיה|שכר ברוטו|שכר_ברוטו|שכר נטו|שכר_נטו|תגמול|בונוס|פיצוי)$/i,type:"financial",label:"Salary / income (Hebrew)",labelHe:"\u05E9\u05DB\u05E8/\u05D4\u05DB\u05E0\u05E1\u05D4"},{pattern:/^(?:אבחון|אבחנה|מחלה|תרופה|מרשם|בדיקה רפואית|בדיקה_רפואית|מצב רפואי|מצב_רפואי|חיסון|תוצאת בדיקה|תוצאת_בדיקה|רופא|רגישות|אלרגיה|סוג דם|סוג_דם)$/i,type:"medical",label:"Medical (Hebrew)",labelHe:"\u05DE\u05D9\u05D3\u05E2 \u05E8\u05E4\u05D5\u05D0\u05D9"},{pattern:/^(?:מספר פוליסה|מספר_פוליסה|מס פוליסה|מס' פוליסה|פוליסה|מספר חבר|מספר_חבר|מס חבר|מספר ביטוח|מספר_ביטוח|policy_?number|policy_?no|policy_?id)$/i,type:"policy",label:"Insurance policy number (Hebrew)",labelHe:"\u05DE\u05E1\u05E4\u05E8 \u05E4\u05D5\u05DC\u05D9\u05E1\u05D4"},{pattern:/^(?:מספר סוכן|מספר_סוכן|מס סוכן|מס' סוכן|מס_סוכן|קוד סוכן|קוד_סוכן|מספר משווק|מספר_משווק|מספר יצרן|סוכן ביטוח|agent_?number|agent_?no|agent_?id|agent_?code|broker_?id|broker_?number)$/i,type:"agent_id",label:"Insurance agent / broker number (Hebrew)",labelHe:"\u05DE\u05E1\u05E4\u05E8 \u05E1\u05D5\u05DB\u05DF"},{pattern:/^(?:שם הילד|שם_הילד|תעודת זהות של ילד|ילדים|קטין|מספר ילדים|מספר_ילדים|תעודת לידה|ת לידה ילד)$/i,type:"minor_data",label:"Minor data (Hebrew)",labelHe:"\u05DE\u05D9\u05D3\u05E2 \u05E2\u05DC \u05E7\u05D8\u05D9\u05DF"},{pattern:/^(?:דת|לאום|מין|נטייה מינית|נטייה_מינית|השקפה פוליטית|השקפה_פוליטית|מצב משפחתי|מצב_משפחתי|עדה|מוצא)$/i,type:"sensitive_personal",label:"Sensitive personal (Hebrew)",labelHe:"\u05DE\u05D9\u05D3\u05E2 \u05D0\u05D9\u05E9\u05D9 \u05E8\u05D2\u05D9\u05E9"},{pattern:/^(?:מספר רכב|מספר_רכב|מס רכב|מס' רכב|לוחית רישוי|לוחית_רישוי|מספר רישוי|מספר_רישוי)$/i,type:"tracking",label:"Vehicle ID (Hebrew)",labelHe:"\u05DE\u05E1\u05E4\u05E8 \u05E8\u05DB\u05D1"}];function ki(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 i=0;i<9;i++){let o=parseInt(n[i]??"0",10)*(i%2+1);o>9&&(o-=9),r+=o}return r%10===0&&parseInt(n,10)>0}var Hn=/(?:\+972[\s-]?|0)(?:5[0-9]|[2-4]|[89])(?:[\s-]?\d){7}/g,Un=/[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}/gi,Vn=/\bIL\d{2}\s?(?:\d{4}\s?){4}\d{3}\b/g;function ws(e){let t=String(e??"").replace(/\D/g,"");if(t.length<13||t.length>19)return!1;let n=0,r=!1;for(let i=t.length-1;i>=0;i--){let o=t.charCodeAt(i)-48;if(o<0||o>9)return!1;r&&(o*=2,o>9&&(o-=9)),n+=o,r=!r}return n%10===0}function Es(e){if(!e)return null;let t=e.trim();for(let n of Zp)if(n.pattern.test(t))return{type:n.type,label:n.label,labelHe:n.labelHe};return null}var Qp=[{type:"biometric",tokens:["biometric","fingerprint","\u05D1\u05D9\u05D5\u05DE\u05D8\u05E8\u05D9"],phrases:["face id","\u05D8\u05D1\u05D9\u05E2\u05EA \u05D0\u05E6\u05D1\u05E2"]},{type:"medical",tokens:["diagnosis","medical","disease","medication","prescription","allergy","vaccine","\u05D0\u05D1\u05D7\u05D5\u05DF","\u05D0\u05D1\u05D7\u05E0\u05D4","\u05DE\u05D7\u05DC\u05D4","\u05EA\u05E8\u05D5\u05E4\u05D4","\u05DE\u05E8\u05E9\u05DD","\u05D7\u05D9\u05E1\u05D5\u05DF","\u05D0\u05DC\u05E8\u05D2\u05D9\u05D4"],phrases:["medical record","blood type","\u05DE\u05E6\u05D1 \u05E8\u05E4\u05D5\u05D0\u05D9","\u05E1\u05D5\u05D2 \u05D3\u05DD"]},{type:"sensitive_personal",tokens:["religion","ethnicity","nationality","\u05D3\u05EA","\u05DC\u05D0\u05D5\u05DD","\u05E2\u05D3\u05D4","\u05DE\u05D5\u05E6\u05D0"],phrases:["sexual orientation","marital status","\u05DE\u05E6\u05D1 \u05DE\u05E9\u05E4\u05D7\u05EA\u05D9","\u05E0\u05D8\u05D9\u05D9\u05D4 \u05DE\u05D9\u05E0\u05D9\u05EA"]},{type:"minor_data",tokens:["minor","\u05E7\u05D8\u05D9\u05DF"],phrases:["child name","\u05E9\u05DD \u05D4\u05D9\u05DC\u05D3","\u05E9\u05DD \u05D4\u05E7\u05D8\u05D9\u05DF"]},{type:"id",tokens:["ssn","passport","\u05D6\u05D4\u05D5\u05EA","\u05D3\u05E8\u05DB\u05D5\u05DF"],phrases:["national id","id number","identity number","social security","driver license","driving license","drivers license","passport number","tax id","\u05EA\u05E2\u05D5\u05D3\u05EA \u05D6\u05D4\u05D5\u05EA","\u05DE\u05E1\u05E4\u05E8 \u05D6\u05D4\u05D5\u05EA","\u05E8\u05D9\u05E9\u05D9\u05D5\u05DF \u05E0\u05D4\u05D9\u05D2\u05D4"]},{type:"financial",tokens:["iban","swift","bic","salary","income","wage","\u05D0\u05E9\u05E8\u05D0\u05D9","\u05E9\u05DB\u05E8","\u05DE\u05E9\u05DB\u05D5\u05E8\u05EA","\u05D4\u05DB\u05E0\u05E1\u05D4"],phrases:["bank account","account number","credit card","card number","routing number","sort code","\u05D7\u05E9\u05D1\u05D5\u05DF \u05D1\u05E0\u05E7","\u05DE\u05E1\u05E4\u05E8 \u05D7\u05E9\u05D1\u05D5\u05DF","\u05DB\u05E8\u05D8\u05D9\u05E1 \u05D0\u05E9\u05E8\u05D0\u05D9"]},{type:"policy",tokens:["policy","\u05E4\u05D5\u05DC\u05D9\u05E1\u05D4"],phrases:["policy number","member number","\u05DE\u05E1\u05E4\u05E8 \u05E4\u05D5\u05DC\u05D9\u05E1\u05D4"]},{type:"agent_id",tokens:["\u05DE\u05E9\u05D5\u05D5\u05E7"],phrases:["agent number","agent code","broker id","\u05DE\u05E1\u05E4\u05E8 \u05E1\u05D5\u05DB\u05DF"]},{type:"dob",tokens:["dob","birthdate","birthday","\u05DC\u05D9\u05D3\u05D4","\u05D4\u05D5\u05DC\u05D3\u05EA","\u05D2\u05D9\u05DC"],phrases:["date of birth","birth date","\u05EA\u05D0\u05E8\u05D9\u05DA \u05DC\u05D9\u05D3\u05D4"]},{type:"phone",tokens:["phone","tel","mobile","cell","fax","\u05D8\u05DC\u05E4\u05D5\u05DF","\u05E0\u05D9\u05D9\u05D3","\u05E4\u05DC\u05D0\u05E4\u05D5\u05DF","\u05E1\u05DC\u05D5\u05DC\u05E8\u05D9"],phrases:["phone number","mobile number","cell phone","\u05D8\u05DC\u05E4\u05D5\u05DF \u05E0\u05D9\u05D9\u05D3"]},{type:"email",tokens:["email","mail","\u05D0\u05D9\u05DE\u05D9\u05D9\u05DC","\u05DE\u05D9\u05D9\u05DC","\u05D3\u05D5\u05D0\u05DC"],phrases:["email address","e mail","\u05D3\u05D5\u05D0\u05E8 \u05D0\u05DC\u05E7\u05D8\u05E8\u05D5\u05E0\u05D9","\u05DB\u05EA\u05D5\u05D1\u05EA \u05DE\u05D9\u05D9\u05DC"]},{type:"address",tokens:["address","street","city","zipcode","zip","postcode","\u05DB\u05EA\u05D5\u05D1\u05EA","\u05E8\u05D7\u05D5\u05D1","\u05E2\u05D9\u05E8","\u05D9\u05E9\u05D5\u05D1","\u05D9\u05D9\u05E9\u05D5\u05D1","\u05DE\u05D9\u05E7\u05D5\u05D3","\u05DE\u05E2\u05DF"],phrases:["home address","postal code","street address","zip code","\u05DB\u05EA\u05D5\u05D1\u05EA \u05DE\u05D2\u05D5\u05E8\u05D9\u05DD"]},{type:"location",tokens:["gps","latitude","longitude","geolocation","\u05DE\u05D9\u05E7\u05D5\u05DD"],phrases:["gps coordinates"]},{type:"tracking",tokens:["plate","vehicle","\u05E8\u05DB\u05D1","\u05E8\u05D9\u05E9\u05D5\u05D9"],phrases:["license plate","vehicle number","plate number","\u05DE\u05E1\u05E4\u05E8 \u05E8\u05DB\u05D1"]},{type:"name",tokens:["name","\u05E9\u05DD"],phrases:["first name","last name","full name","family name","given name","surname","\u05E9\u05DD \u05E4\u05E8\u05D8\u05D9","\u05E9\u05DD \u05DE\u05E9\u05E4\u05D7\u05D4","\u05E9\u05DD \u05DE\u05DC\u05D0"]}];function Gn(e){if(!e)return null;let t=e.trim().toLowerCase().replace(/["'`׳״]/g,"").replace(/[_\-.]+/g," ").replace(/\s+/g," ").trim();if(!t)return null;let n=new Set(t.match(/[\p{L}\p{N}]+/gu)??[]);for(let r of Qp)if(r.phrases?.some(o=>t.includes(o))||r.tokens?.some(o=>n.has(o)))return{type:r.type,label:r.type,labelHe:Wn(r.type)};return null}function Wn(e){return{id:"\u05EA\u05E2\u05D5\u05D3\u05EA \u05D6\u05D4\u05D5\u05EA",agent_id:"\u05DE\u05E1\u05E4\u05E8 \u05E1\u05D5\u05DB\u05DF",policy:"\u05DE\u05E1\u05E4\u05E8 \u05E4\u05D5\u05DC\u05D9\u05E1\u05D4",name:"\u05E9\u05DD \u05D0\u05D3\u05DD",email:"\u05D3\u05D5\u05D0\u05E8 \u05D0\u05DC\u05E7\u05D8\u05E8\u05D5\u05E0\u05D9",phone:"\u05DE\u05E1\u05E4\u05E8 \u05D8\u05DC\u05E4\u05D5\u05DF",address:"\u05DB\u05EA\u05D5\u05D1\u05EA",dob:"\u05EA\u05D0\u05E8\u05D9\u05DA \u05DC\u05D9\u05D3\u05D4",financial:"\u05E4\u05E8\u05D8\u05D9\u05DD \u05E4\u05D9\u05E0\u05E0\u05E1\u05D9\u05D9\u05DD",medical:"\u05DE\u05D9\u05D3\u05E2 \u05E8\u05E4\u05D5\u05D0\u05D9",minor_data:"\u05DE\u05D9\u05D3\u05E2 \u05E2\u05DC \u05E7\u05D8\u05D9\u05DF",sensitive_personal:"\u05DE\u05D9\u05D3\u05E2 \u05D0\u05D9\u05E9\u05D9 \u05E8\u05D2\u05D9\u05E9",biometric:"\u05DE\u05D9\u05D3\u05E2 \u05D1\u05D9\u05D5\u05DE\u05D8\u05E8\u05D9",auth:"\u05E1\u05D9\u05E1\u05DE\u05D0\u05D5\u05EA/\u05E1\u05D5\u05D3\u05D5\u05EA",tracking:"\u05DE\u05D6\u05D4\u05D9 \u05DE\u05E2\u05E7\u05D1",location:"\u05DE\u05D9\u05E7\u05D5\u05DD"}[e]??"\u05DE\u05D9\u05D3\u05E2 \u05D0\u05D9\u05E9\u05D9"}function xs(e){let t=0,n=0,r=0,i=0,o=0;for(let s of e)typeof s=="string"&&(ki(s)&&t++,Hn.lastIndex=0,Hn.test(s)&&n++,Un.lastIndex=0,Un.test(s)&&r++,Vn.lastIndex=0,Vn.test(s)&&i++,ws(s)&&o++);let a=e.length||1;return t/a>=.3?{type:"id",label:"Israeli ID (sniffed)",matchedSample:t}:i/a>=.3?{type:"financial",label:"IBAN-IL (sniffed)",matchedSample:i}:n/a>=.3?{type:"phone",label:"IL phone (sniffed)",matchedSample:n}:r/a>=.3?{type:"email",label:"Email (sniffed)",matchedSample:r}:o/a>=.3?{type:"financial",label:"Credit card (sniffed)",matchedSample:o}:null}var As={_comment:"CANONICAL secret ruleset \u2014 the SINGLE SOURCE OF TRUTH for hardcoded-secret detection, loaded by BOTH the web scanner (lib/soc/exposure-map.ts) and the installed Capsule agent (apps/desktop/src-tauri/src/scanner.rs, via include_str!). Patterns are written in the regex subset both JavaScript and the Rust `regex` crate accept (no lookaround, no backreferences). A connection string counts only WITH credentials (user:pass@). Edit here once and both engines stay aligned.",rules:[{id:"aws-access-key",subkind:"aws_access_key",name:"AWS Access Key",severity:"critical",pattern:"(?:^|[^A-Z0-9])AKIA[A-Z2-7]{16}(?:[^A-Z2-7]|$)",hint:"AWS access key id detected. Rotate via IAM and move to an environment variable."},{id:"aws-secret-key",subkind:"aws_secret_key",name:"AWS Secret Key",severity:"critical",pattern:`(?:aws_secret_access_key|aws_secret_key|secret_access_key)\\s*[=:]\\s*['"]?[A-Za-z0-9/+=]{40}['"]?`,hint:"AWS secret access key detected. Rotate immediately."},{id:"gcp-api-key",subkind:"gcp_api_key",name:"GCP API Key",severity:"critical",pattern:"AIza[0-9A-Za-z_-]{35}",hint:"Google API key detected. Restrict or rotate it in the Google Cloud console."},{id:"gcp-service-account",subkind:"gcp_service_account",name:"GCP Service Account",severity:"critical",pattern:'"type"\\s*:\\s*"service_account"',hint:"GCP service-account JSON detected. Move it out of the repo and rotate the key."},{id:"github-token",subkind:"github_token",name:"GitHub Token",severity:"critical",pattern:"gh[pousr]_[0-9a-zA-Z]{36,}",hint:"GitHub token detected. Revoke at https://github.com/settings/tokens."},{id:"github-fine-grained",subkind:"github_fine_grained_token",name:"GitHub Fine-Grained Token",severity:"critical",pattern:"github_pat_[0-9a-zA-Z_]{22,}",hint:"GitHub fine-grained token detected. Revoke it in GitHub settings."},{id:"gitlab-token",subkind:"gitlab_token",name:"GitLab Token",severity:"critical",pattern:"glpat-[0-9a-zA-Z_-]{20,}",hint:"GitLab token detected. Revoke it in GitLab access tokens."},{id:"stripe-secret",subkind:"stripe_key",name:"Stripe Secret Key",severity:"critical",pattern:"sk_live_[0-9a-zA-Z]{24,}",hint:"Stripe live secret key detected. Roll it in the Stripe dashboard."},{id:"stripe-restricted",subkind:"stripe_restricted_key",name:"Stripe Restricted Key",severity:"critical",pattern:"rk_live_[0-9a-zA-Z]{24,}",hint:"Stripe restricted key detected. Roll it in the Stripe dashboard."},{id:"slack-token",subkind:"slack_token",name:"Slack Token",severity:"high",pattern:"xox[baprs]-[0-9a-zA-Z-]{10,}",hint:"Slack token detected. Revoke it in the Slack app settings."},{id:"slack-webhook",subkind:"slack_webhook",name:"Slack Webhook",severity:"high",pattern:"hooks\\.slack\\.com/services/T[0-9A-Z]{8,}/B[0-9A-Z]{8,}/[0-9a-zA-Z]{24}",hint:"Slack incoming-webhook URL detected. Regenerate it."},{id:"twilio-api-key",subkind:"twilio_api_key",name:"Twilio API Key",severity:"high",pattern:"SK[0-9a-fA-F]{32}",hint:"Twilio API key detected. Rotate it in the Twilio console."},{id:"sendgrid-api-key",subkind:"sendgrid_api_key",name:"SendGrid API Key",severity:"critical",pattern:"SG\\.[0-9a-zA-Z_-]{22}\\.[0-9a-zA-Z_-]{43}",hint:"SendGrid API key detected. Rotate it in the SendGrid console."},{id:"postgres-uri",subkind:"postgres_uri",name:"PostgreSQL Connection String",severity:"critical",pattern:`postgres(?:ql)?://[^\\s'":/@]*:[^\\s'"@]+@[^\\s'"]+`,hint:"PostgreSQL connection string WITH credentials detected. Move it to a secret manager and rotate the password."},{id:"mongodb-uri",subkind:"mongodb_uri",name:"MongoDB Connection String",severity:"critical",pattern:`mongodb(?:\\+srv)?://[^\\s'":/@]*:[^\\s'"@]+@[^\\s'"]+`,hint:"MongoDB connection string WITH credentials detected. Move it to a secret manager and rotate the password."},{id:"redis-uri",subkind:"redis_uri",name:"Redis Connection String",severity:"high",pattern:`redis(?:s)?://[^\\s'":/@]*:[^\\s'"@]+@[^\\s'"]+`,hint:"Redis connection string WITH credentials detected. Move it to a secret manager and rotate the password."},{id:"openai-key",subkind:"openai_key",name:"OpenAI API Key",severity:"critical",pattern:"sk-[0-9a-zA-Z]{20,}T3BlbkFJ[0-9a-zA-Z]{20,}",hint:"OpenAI API key detected. Rotate at https://platform.openai.com/api-keys."},{id:"anthropic-key",subkind:"anthropic_key",name:"Anthropic API Key",severity:"critical",pattern:"sk-ant-[0-9a-zA-Z_-]{40,}",hint:"Anthropic API key detected. Rotate at https://console.anthropic.com/."},{id:"firebase-key",subkind:"firebase_key",name:"Firebase API Key",severity:"high",pattern:"AIza[0-9A-Za-z_-]{35}",hint:"Firebase API key detected. Restrict it in the Firebase console."},{id:"supabase-key",subkind:"supabase_key",name:"Supabase Service Key",severity:"critical",pattern:"eyJ[0-9a-zA-Z_-]{100,}",hint:"Long JWT (possible Supabase service key) detected. Rotate it and keep it server-side only."},{id:"private-key",subkind:"private_key",name:"Private Key",severity:"critical",pattern:"-----BEGIN (?:RSA |EC |DSA |OPENSSH )?PRIVATE KEY-----",hint:"Private key material in plaintext. Rotate immediately and move to a key manager (KMS/Vault).",skipPlaceholder:!0},{id:"jwt-secret",subkind:"jwt_secret",name:"JWT/Generic Secret",severity:"high",pattern:`(?:jwt_secret|JWT_SECRET|secret_key|SECRET_KEY|api_secret|API_SECRET)\\s*[=:]\\s*['"][^'"]{8,}['"]`,hint:"Hardcoded signing/API secret detected. Move it to an environment variable and rotate it."},{id:"password-in-code",subkind:"password_in_code",name:"Password in Code",severity:"high",pattern:`(?:password|passwd|pwd)\\s*[=:]\\s*['"][^'"]{8,}['"]`,hint:"Hardcoded password detected. Move it to a secret manager and rotate it."},{id:"bearer-token",subkind:"bearer_token",name:"Bearer Token in Code",severity:"high",pattern:`['"]Bearer\\s+[0-9a-zA-Z._-]{20,}['"]`,hint:"Hardcoded bearer token detected. Move it to a secret manager and rotate it."},{id:"hex-secret-32",subkind:"hex_secret",name:"Hardcoded 32+ Hex Secret",severity:"medium",pattern:`['"][0-9a-f]{32,}['"]`,hint:"Long hex string that looks like a secret/hash. Confirm it is not a live credential."},{id:"base64-secret",subkind:"base64_secret",name:"Hardcoded Base64 Secret (long)",severity:"medium",pattern:`['"][A-Za-z0-9+/]{64,}={0,2}['"]`,hint:"Long base64 blob that looks like an embedded secret. Confirm it is not a live credential."}]};var nf=[{pattern:/^(full_?name|first_?name|last_?name|spouse_?name|beneficiary_?name)$/i,type:"name",label:"Person name",labelHe:"\u05E9\u05DD \u05D0\u05D3\u05DD"},{pattern:/^(email|e_?mail|email_?address)$/i,type:"email",label:"Email address",labelHe:"\u05DB\u05EA\u05D5\u05D1\u05EA \u05D0\u05D9\u05DE\u05D9\u05D9\u05DC"},{pattern:/^(phone|mobile|telephone|phone_?number|cell_?phone)$/i,type:"phone",label:"Phone number",labelHe:"\u05DE\u05E1\u05E4\u05E8 \u05D8\u05DC\u05E4\u05D5\u05DF"},{pattern:/^(id_?number|identity|ssn|social_?security|national_?id|teudat_?zehut)$/i,type:"id",label:"ID number",labelHe:"\u05DE\u05E1\u05E4\u05E8 \u05DE\u05D6\u05D4\u05D4"},{pattern:/^(address|street_?address|home_?address)$/i,type:"address",label:"Address",labelHe:"\u05DB\u05EA\u05D5\u05D1\u05EA"},{pattern:/^(date_?of_?birth|dob|birth_?date|birthday)$/i,type:"dob",label:"Date of birth",labelHe:"\u05EA\u05D0\u05E8\u05D9\u05DA \u05DC\u05D9\u05D3\u05D4"},{pattern:/^(bank_?account|iban|account_?number|bank_?details|routing_?number)$/i,type:"financial",label:"Bank account",labelHe:"\u05D7\u05E9\u05D1\u05D5\u05DF \u05D1\u05E0\u05E7"},{pattern:/^(credit_?card|card_?number|cvv|cc_?number)$/i,type:"financial",label:"Credit card",labelHe:"\u05DB\u05E8\u05D8\u05D9\u05E1 \u05D0\u05E9\u05E8\u05D0\u05D9"},{pattern:/^(salary|income|commission|premium|compensation)$/i,type:"financial",label:"Financial data",labelHe:"\u05E0\u05EA\u05D5\u05DF \u05E4\u05D9\u05E0\u05E0\u05E1\u05D9"},{pattern:/^(medical_?info|health_?conditions|diagnosis|medication)$/i,type:"medical",label:"Medical data",labelHe:"\u05DE\u05D9\u05D3\u05E2 \u05E8\u05E4\u05D5\u05D0\u05D9"},{pattern:/^(ip_?address)$/i,type:"tracking",label:"IP address",labelHe:"\u05DB\u05EA\u05D5\u05D1\u05EA IP"},{pattern:/^(passport|passport_?number|passport_?id)$/i,type:"id",label:"Passport number",labelHe:"\u05DE\u05E1\u05E4\u05E8 \u05D3\u05E8\u05DB\u05D5\u05DF"},{pattern:/^(driver_?license|drivers_?license|dl_?number)$/i,type:"id",label:"Driver license",labelHe:"\u05E8\u05D9\u05E9\u05D9\u05D5\u05DF \u05E0\u05D4\u05D9\u05D2\u05D4"},{pattern:/^(iban|swift_?code|bic)$/i,type:"financial",label:"Banking code",labelHe:"\u05E7\u05D5\u05D3 \u05D1\u05E0\u05E7\u05D0\u05D9"},{pattern:/^(tax_?id|tin|vat_?number|ein)$/i,type:"financial",label:"Tax ID",labelHe:"\u05DE\u05E1\u05E4\u05E8 \u05DE\u05E1"},{pattern:/^(insurance_?number|policy_?number|member_?id)$/i,type:"id",label:"Insurance/Member ID",labelHe:"\u05DE\u05E1\u05E4\u05E8 \u05D1\u05D9\u05D8\u05D5\u05D7/\u05D7\u05D1\u05E8"},{pattern:/^(blood_?type|allergy|allergies|prescription)$/i,type:"medical",label:"Medical data",labelHe:"\u05DE\u05D9\u05D3\u05E2 \u05E8\u05E4\u05D5\u05D0\u05D9"},{pattern:/^(biometric|fingerprint|face_?id|retina)$/i,type:"biometric",label:"Biometric data",labelHe:"\u05DE\u05D9\u05D3\u05E2 \u05D1\u05D9\u05D5\u05DE\u05D8\u05E8\u05D9"},{pattern:/^(latitude|longitude|lat|lng|geo_?location|coordinates)$/i,type:"location",label:"Geolocation",labelHe:"\u05DE\u05D9\u05E7\u05D5\u05DD \u05D2\u05D9\u05D0\u05D5\u05D2\u05E8\u05E4\u05D9"},{pattern:/^(mac_?address|device_?fingerprint|imei|serial_?number)$/i,type:"tracking",label:"Device identifier",labelHe:"\u05DE\u05D6\u05D4\u05D4 \u05DE\u05DB\u05E9\u05D9\u05E8"},{pattern:/^(ethnicity|race|religion|political_?affiliation|sexual_?orientation)$/i,type:"sensitive_personal",label:"Sensitive personal",labelHe:"\u05DE\u05D9\u05D3\u05E2 \u05D0\u05D9\u05E9\u05D9 \u05E8\u05D2\u05D9\u05E9"},{pattern:/^(minor|child_?name|child_?age|dependent)$/i,type:"minor_data",label:"Minor data",labelHe:"\u05DE\u05D9\u05D3\u05E2 \u05E2\u05DC \u05E7\u05D8\u05D9\u05E0\u05D9\u05DD"},{pattern:/^(signature|digital_?signature)$/i,type:"id",label:"Signature",labelHe:"\u05D7\u05EA\u05D9\u05DE\u05D4"},{pattern:/^(vehicle_?number|license_?plate|plate_?number)$/i,type:"tracking",label:"Vehicle ID",labelHe:"\u05DE\u05D6\u05D4\u05D4 \u05E8\u05DB\u05D1"}],rf=/^(id|uuid|created_?at|updated_?at|deleted_?at|status|type|category|description|title|slug|url|path|key|value|sort_?order|position|enabled|active|public|version|metadata|config|settings|options|data|content|body|raw|json|text|note|comment|label|color|icon|image|avatar|logo|thumbnail|preview|template|schema|format|mode|level|priority|severity|source|target|parent|child|owner|creator|modifier|assignee|project|workspace|organization|team|group|channel|thread|room|session|device|platform|browser|locale|timezone|currency|country|region|city|zip|postal|state|province|name|display_?name|user_?agent|password_?hash|secret|token|private_?key|auth_?token|constraint|index|sequence|trigger|function|procedure|database|namespace|migration|revision)$/i,of=/^(beacon_?registr|device_?config|hardware|sensor|firmware|telemetry|metric|analytic|log_?event|audit_?log|system_?config|cache|queue|job|migration|schema_?version|spatial_?ref)/i,af=/^(minor|major|uuid|rssi|tx_?power|beacon_?id|device_?type|firmware_?version|batch_?id|zone_?id)$/i;function Ts(e,t){if(rf.test(e)||/^name$/i.test(e)||t&&of.test(t)||af.test(e))return null;for(let r of nf)if(r.pattern.test(e))return r.type;let n=Es(e);return n?n.type:null}var Ug=As.rules.map(e=>({id:e.id,name:e.name,pattern:new RegExp(e.pattern),severity:e.severity}));var Vg=512*1024,Gg=50*1024*1024;var sf={id:"high",agent_id:"high",policy:"high",financial:"high",medical:"critical",sensitive_personal:"critical",minor_data:"critical",biometric:"critical",auth:"critical",name:"medium",email:"high",phone:"high",address:"high",dob:"high",location:"high",tracking:"low"};function cf(e){return sf[e]??"low"}function Is(e,t){let n=[];for(let r of t){let i=r.rows.length;for(let o=0;o<r.headers.length;o++){let a=r.headers[o]??"",s=a?Ts(a.trim().replace(/["'`׳״:]/g,"").replace(/\s+/g,"_"),r.name)??Gn(a)?.type??null:null,c=[];for(let u of r.rows){let p=u[o];typeof p=="string"&&p.length>0&&c.push(p)}let l=c.length>0?xs(c):null;l?n.push(Ps(e,r.name,a,l.type,l.label,"value",l.matchedSample,i)):s&&n.push(Ps(e,r.name,a,s,Wn(s),"header",0,i))}}return n}function Ps(e,t,n,r,i,o,a,s){return{file:e,location:t,column:n,type:r,label:i,category:Wn(r),severity:cf(r),matchKind:o,hits:a,sampleSize:s}}var $s={_comment:"CANONICAL secret ruleset \u2014 the SINGLE SOURCE OF TRUTH for hardcoded-secret detection, loaded by BOTH the web scanner (lib/soc/exposure-map.ts) and the installed Capsule agent (apps/desktop/src-tauri/src/scanner.rs, via include_str!). Patterns are written in the regex subset both JavaScript and the Rust `regex` crate accept (no lookaround, no backreferences). A connection string counts only WITH credentials (user:pass@). Edit here once and both engines stay aligned.",rules:[{id:"aws-access-key",subkind:"aws_access_key",name:"AWS Access Key",severity:"critical",pattern:"(?:^|[^A-Z0-9])AKIA[A-Z2-7]{16}(?:[^A-Z2-7]|$)",hint:"AWS access key id detected. Rotate via IAM and move to an environment variable."},{id:"aws-secret-key",subkind:"aws_secret_key",name:"AWS Secret Key",severity:"critical",pattern:`(?:aws_secret_access_key|aws_secret_key|secret_access_key)\\s*[=:]\\s*['"]?[A-Za-z0-9/+=]{40}['"]?`,hint:"AWS secret access key detected. Rotate immediately."},{id:"gcp-api-key",subkind:"gcp_api_key",name:"GCP API Key",severity:"critical",pattern:"AIza[0-9A-Za-z_-]{35}",hint:"Google API key detected. Restrict or rotate it in the Google Cloud console."},{id:"gcp-service-account",subkind:"gcp_service_account",name:"GCP Service Account",severity:"critical",pattern:'"type"\\s*:\\s*"service_account"',hint:"GCP service-account JSON detected. Move it out of the repo and rotate the key."},{id:"github-token",subkind:"github_token",name:"GitHub Token",severity:"critical",pattern:"gh[pousr]_[0-9a-zA-Z]{36,}",hint:"GitHub token detected. Revoke at https://github.com/settings/tokens."},{id:"github-fine-grained",subkind:"github_fine_grained_token",name:"GitHub Fine-Grained Token",severity:"critical",pattern:"github_pat_[0-9a-zA-Z_]{22,}",hint:"GitHub fine-grained token detected. Revoke it in GitHub settings."},{id:"gitlab-token",subkind:"gitlab_token",name:"GitLab Token",severity:"critical",pattern:"glpat-[0-9a-zA-Z_-]{20,}",hint:"GitLab token detected. Revoke it in GitLab access tokens."},{id:"stripe-secret",subkind:"stripe_key",name:"Stripe Secret Key",severity:"critical",pattern:"sk_live_[0-9a-zA-Z]{24,}",hint:"Stripe live secret key detected. Roll it in the Stripe dashboard."},{id:"stripe-restricted",subkind:"stripe_restricted_key",name:"Stripe Restricted Key",severity:"critical",pattern:"rk_live_[0-9a-zA-Z]{24,}",hint:"Stripe restricted key detected. Roll it in the Stripe dashboard."},{id:"slack-token",subkind:"slack_token",name:"Slack Token",severity:"high",pattern:"xox[baprs]-[0-9a-zA-Z-]{10,}",hint:"Slack token detected. Revoke it in the Slack app settings."},{id:"slack-webhook",subkind:"slack_webhook",name:"Slack Webhook",severity:"high",pattern:"hooks\\.slack\\.com/services/T[0-9A-Z]{8,}/B[0-9A-Z]{8,}/[0-9a-zA-Z]{24}",hint:"Slack incoming-webhook URL detected. Regenerate it."},{id:"twilio-api-key",subkind:"twilio_api_key",name:"Twilio API Key",severity:"high",pattern:"SK[0-9a-fA-F]{32}",hint:"Twilio API key detected. Rotate it in the Twilio console."},{id:"sendgrid-api-key",subkind:"sendgrid_api_key",name:"SendGrid API Key",severity:"critical",pattern:"SG\\.[0-9a-zA-Z_-]{22}\\.[0-9a-zA-Z_-]{43}",hint:"SendGrid API key detected. Rotate it in the SendGrid console."},{id:"postgres-uri",subkind:"postgres_uri",name:"PostgreSQL Connection String",severity:"critical",pattern:`postgres(?:ql)?://[^\\s'":/@]*:[^\\s'"@]+@[^\\s'"]+`,hint:"PostgreSQL connection string WITH credentials detected. Move it to a secret manager and rotate the password."},{id:"mongodb-uri",subkind:"mongodb_uri",name:"MongoDB Connection String",severity:"critical",pattern:`mongodb(?:\\+srv)?://[^\\s'":/@]*:[^\\s'"@]+@[^\\s'"]+`,hint:"MongoDB connection string WITH credentials detected. Move it to a secret manager and rotate the password."},{id:"redis-uri",subkind:"redis_uri",name:"Redis Connection String",severity:"high",pattern:`redis(?:s)?://[^\\s'":/@]*:[^\\s'"@]+@[^\\s'"]+`,hint:"Redis connection string WITH credentials detected. Move it to a secret manager and rotate the password."},{id:"openai-key",subkind:"openai_key",name:"OpenAI API Key",severity:"critical",pattern:"sk-[0-9a-zA-Z]{20,}T3BlbkFJ[0-9a-zA-Z]{20,}",hint:"OpenAI API key detected. Rotate at https://platform.openai.com/api-keys."},{id:"anthropic-key",subkind:"anthropic_key",name:"Anthropic API Key",severity:"critical",pattern:"sk-ant-[0-9a-zA-Z_-]{40,}",hint:"Anthropic API key detected. Rotate at https://console.anthropic.com/."},{id:"firebase-key",subkind:"firebase_key",name:"Firebase API Key",severity:"high",pattern:"AIza[0-9A-Za-z_-]{35}",hint:"Firebase API key detected. Restrict it in the Firebase console."},{id:"supabase-key",subkind:"supabase_key",name:"Supabase Service Key",severity:"critical",pattern:"eyJ[0-9a-zA-Z_-]{100,}",hint:"Long JWT (possible Supabase service key) detected. Rotate it and keep it server-side only."},{id:"private-key",subkind:"private_key",name:"Private Key",severity:"critical",pattern:"-----BEGIN (?:RSA |EC |DSA |OPENSSH )?PRIVATE KEY-----",hint:"Private key material in plaintext. Rotate immediately and move to a key manager (KMS/Vault).",skipPlaceholder:!0},{id:"jwt-secret",subkind:"jwt_secret",name:"JWT/Generic Secret",severity:"high",pattern:`(?:jwt_secret|JWT_SECRET|secret_key|SECRET_KEY|api_secret|API_SECRET)\\s*[=:]\\s*['"][^'"]{8,}['"]`,hint:"Hardcoded signing/API secret detected. Move it to an environment variable and rotate it."},{id:"password-in-code",subkind:"password_in_code",name:"Password in Code",severity:"high",pattern:`(?:password|passwd|pwd)\\s*[=:]\\s*['"][^'"]{8,}['"]`,hint:"Hardcoded password detected. Move it to a secret manager and rotate it."},{id:"bearer-token",subkind:"bearer_token",name:"Bearer Token in Code",severity:"high",pattern:`['"]Bearer\\s+[0-9a-zA-Z._-]{20,}['"]`,hint:"Hardcoded bearer token detected. Move it to a secret manager and rotate it."},{id:"hex-secret-32",subkind:"hex_secret",name:"Hardcoded 32+ Hex Secret",severity:"medium",pattern:`['"][0-9a-f]{32,}['"]`,hint:"Long hex string that looks like a secret/hash. Confirm it is not a live credential."},{id:"base64-secret",subkind:"base64_secret",name:"Hardcoded Base64 Secret (long)",severity:"medium",pattern:`['"][A-Za-z0-9+/]{64,}={0,2}['"]`,hint:"Long base64 blob that looks like an embedded secret. Confirm it is not a live credential."}]};var df=[{type:"full_name",kind:"name",severity:"medium",hint:`A person's name in free text (after a role word such as \u05DC\u05E7\u05D5\u05D7 / \u05DE\u05E8 / \u05E2\u05D5"\u05D3).`},{type:"bank_account",kind:"bank_account",severity:"high",hint:"An Israeli bank account number (branch-account-check form) in plaintext."},{type:"medical",kind:"medical",severity:"high",hint:"Medical information (diagnosis, medication, lab value) in plaintext."},{type:"birth_date",kind:"dob",severity:"medium",hint:"A date of birth in plaintext."},{type:"address",kind:"address",severity:"medium",hint:"A street address in plaintext."},{type:"license_plate",kind:"plate",severity:"low",hint:"A vehicle licence plate in plaintext."}],uf=/^(?:לקוח|מטופל|מועמד|שם|נהג|מבוטח|תובע|נתבע|שוכר|מחזיק|עו"ד|ד"ר|פרופ'|מר|גברת|חשבון|ח-ן|[בהוכלמש]{0,2}אבחנ[הות]|תאריך לידה|נולד|נולדה|ד\.ל\.|[בהוכלמש]{0,2}גיל)\s*:?\s*/;function pf(e,t,n,r){if(r==="address")return{start:t,end:n};let i=uf.exec(e.slice(t,n));return i&&t+i[0].length<n?{start:t+i[0].length,end:n}:{start:t,end:n}}var ff=new Set(["hex-secret-32","base64-secret"]),Rs=!1;function Ds(){if(Rs)return;Rs=!0;let e=df.map(({type:n,kind:r,severity:i,hint:o})=>{let a=new Kn([n]);return{kind:r,severity:i,hint:o,find:s=>a.detect(s).map(c=>pf(s,c.startIndex,c.endIndex,r))}}),t=$s.rules.filter(n=>!ff.has(n.id)).map(n=>({id:n.id,name:n.name,severity:n.severity,pattern:new RegExp(n.pattern)}));sr({text:e,header:n=>{let r=Gn(n);return r?{type:r.type,label:r.labelHe||r.label}:null},secrets:t,table:n=>Is("",[n]).filter(r=>r.column).map(r=>({column:r.column,type:r.type,category:r.category,severity:r.severity,hits:r.hits,how:r.matchKind==="value"?"value":"header"}))})}import{z as bf}from"zod";import{existsSync as vf,mkdirSync as kf,readFileSync as Sf,writeFileSync as wf}from"node:fs";import{homedir as Os,hostname as zn}from"node:os";import{join as ft}from"node:path";function qe(e){if(e===null||typeof e!="object")return JSON.stringify(e);if(Array.isArray(e))return"["+e.map(qe).join(",")+"]";let t=e;return"{"+Object.keys(t).sort().map(r=>JSON.stringify(r)+":"+qe(t[r])).join(",")+"}"}import{mkdirSync as hf,readFileSync as Si,writeFileSync as wi,existsSync as Ei,chmodSync as mf,statSync as gf}from"node:fs";import{join as Ai}from"node:path";import Ti from"node:crypto";function Kt(e){return Ai(e,"agent-private-key.pem")}function Pi(e){return Ai(e,"agent-public-key.pem")}function xi(e){return Ai(e,"agent-key-meta.json")}function Ii(e){hf(e,{recursive:!0});let t=Kt(e),n=Pi(e);if(Ei(t)&&Ei(n))try{return yf(e)}catch(r){throw new Error(`agent keystore corrupted at ${e}: ${r.message}`)}return _f(e)}function yf(e){let t=Si(Kt(e),"utf8"),n=Si(Pi(e),"utf8"),r=Ei(xi(e))?JSON.parse(Si(xi(e),"utf8")):{},i=Ti.createPrivateKey({key:t,format:"pem"});if(i.asymmetricKeyType!=="ed25519")throw new Error(`expected ed25519 key, got ${i.asymmetricKeyType}`);return{privateKey:i,publicKeyPem:n,generatedAt:r.generatedAt??new Date(gf(Kt(e)).mtime).toISOString()}}function _f(e){let{publicKey:t,privateKey:n}=Ti.generateKeyPairSync("ed25519"),r=n.export({type:"pkcs8",format:"pem"}),i=t.export({type:"spki",format:"pem"}),o=new Date().toISOString();if(wi(Kt(e),r,{encoding:"utf8"}),wi(Pi(e),i,{encoding:"utf8"}),wi(xi(e),JSON.stringify({generatedAt:o},null,2),"utf8"),process.platform!=="win32")try{mf(Kt(e),384)}catch{}return{privateKey:n,publicKeyPem:i,generatedAt:o}}function Ht(e,t){return Ti.sign(null,Buffer.from(t,"utf8"),e.privateKey).toString("hex")}var Cs=3e4,Ut=class{constructor(t){this.apiBase=t}url(t){return this.apiBase.replace(/\/+$/,"")+t}async request(t,n){let r=this.url(t);try{return await fetch(r,{...n,signal:AbortSignal.timeout(Cs)})}catch(i){let o=i;if(o?.name==="TimeoutError"||o?.name==="AbortError")throw new Error(`${t} timed out after ${Cs}ms (${r})`);let a=o?.cause?.code;throw new Error(`${t} could not reach ${r}${a?` (${a})`:""}: ${o?.message??String(i)}`)}}async enroll(t){let n=await this.request("/api/capsule/enroll",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(t)}),r=await n.text();if(!n.ok)throw new Error(`enroll failed: HTTP ${n.status} \u2014 ${r}`);return JSON.parse(r)}async heartbeat(t,n){let r=qe({deployment_id:t.deployment_id,agent_version:t.agent_version,applied_config:t.applied_config??null,discovered_release_version:t.discovered_release_version??null}),i=Ht(n,r),o={...t,signature_hex:i},a=await this.request("/api/capsule/heartbeat",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(o)}),s=await a.text();if(!a.ok)throw new Error(`heartbeat failed: HTTP ${a.status} \u2014 ${s}`);try{return JSON.parse(s)}catch{return{ok:!0,desired_config:null,apply_update:!1}}}async submitSealBackup(t,n){let{deployment_id:r,...i}=t,o=qe(i),a=Ht(n,o),s={deployment_id:r,...i,signature_hex:a},c=await this.request("/api/capsule/seal/backup",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(s)}),l=await c.text();if(!c.ok)throw new Error(`seal backup failed: HTTP ${c.status} \u2014 ${l}`);return JSON.parse(l)}async submitScan(t,n){let r=qe(t),i=Ht(n,r),o={...t,signature_hex:i},a=await this.request("/api/capsule/scan/submit",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(o)}),s=await a.text();if(!a.ok)throw new Error(`scan submit failed: HTTP ${a.status} \u2014 ${s}`);return JSON.parse(s)}async submitSeal(t,n){let{deployment_id:r,...i}=t,o=qe(i),a=Ht(n,o),s={deployment_id:r,...i,signature_hex:a},c=await this.request("/api/capsule/seal/submit",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(s)}),l=await c.text();if(!c.ok)throw new Error(`seal submit failed: HTTP ${c.status} \u2014 ${l}`);return JSON.parse(l)}};var se="2026-09-24-v3";var Ef=300*1e3,xf=1440*60*1e3,Gt=()=>ft(Os(),".nodata"),qn=()=>ft(Gt(),"capsule.json"),Ns=()=>ft(Gt(),"capsule-agents.json"),js=()=>ft(Gt(),"capsule-key");function Xn(e){try{return vf(e)?JSON.parse(Sf(e,"utf8")):null}catch{return null}}function Jn(e,t){kf(Gt(),{recursive:!0}),wf(e,JSON.stringify(t,null,2)+`
|
|
88
|
-
`,{mode:384})}function
|
|
89
|
-
`)}]}}if(!t.org)return{content:[{type:"text",text:"This machine has no enrolled device identity, so it cannot register as a node. Connect first with nodata_connect (it enrolls the device), restart, then run nodata_node again."}],isError:!0};if(!n)return{content:[{type:"text",text:[`PREVIEW \u2014 nothing registered yet. ${t.who()}`,`Register this machine (${
|
|
90
|
-
`)}]};let i=await t.org.token();if(!i)return{content:[{type:"text",text:"No usable org credential \u2014 run nodata_connect."}],isError:!0};let o=await fetch(`${t.org.baseUrl}/api/v1/tenants/${encodeURIComponent(t.org.id)}/capsule/install-token`,{method:"POST",headers:{authorization:`Bearer ${i}`}}),a=await o.json().catch(()=>({}));if(!o.ok||!a.install_token)return{content:[{type:"text",text:`Could not start registration (HTTP ${o.status}): ${a.error??"no install token"}`}],isError:!0};let s=
|
|
91
|
-
`)}]}})}import{z as
|
|
119
|
+
Restart Claude Code to load it. Remove with: npx @nodatachat/mcp uninstall-gate`}function Sc(){let e=vc(),t=e.hooks?.PreToolUse;if(!t||!t.some(nn))return"The NoData read gate is not installed.";if(e.hooks.PreToolUse=t.filter(n=>!nn(n)),e.hooks.PreToolUse.length===0&&delete e.hooks.PreToolUse,e.hooks.PostToolUse&&(e.hooks.PostToolUse=e.hooks.PostToolUse.filter(n=>!nn(n)),e.hooks.PostToolUse.length===0&&delete e.hooks.PostToolUse),bc(e.statusLine)){let n=Hi(Ki())?JSON.parse(Vi(Ki(),"utf8")):null;n?e.statusLine=n:delete e.statusLine}return kc(e),"NoData read gate removed. Restart Claude Code to unload it."}var gh=[{type:"id_number",patterns:[/\b\d{9}\b/g,/ת\.?ז\.?\s*:?\s*(\d{9})/g,/זהות\s*:?\s*(\d{9})/g],confidence:.9,replacement:()=>"[\u05EA.\u05D6. \u05DE\u05D5\u05E1\u05EA\u05E8]"},{type:"phone",patterns:[/\b0[2-9]\d[\s\-]?\d{7}\b/g,/\b05[0-9][\s\-]?\d{7}\b/g,/\+972[\s\-]?[2-9]\d[\s\-]?\d{7}\b/g],confidence:.95,replacement:()=>"[\u05D8\u05DC\u05E4\u05D5\u05DF \u05DE\u05D5\u05E1\u05EA\u05E8]"},{type:"email",patterns:[/[a-zA-Z0-9._%+\-]+@[a-zA-Z0-9.\-]+\.[a-zA-Z]{2,}/g],confidence:.99,replacement:e=>{let[,t]=e.split("@");return`[\u05D0\u05D9\u05DE\u05D9\u05D9\u05DC: ***@${t}]`}},{type:"full_name",patterns:[/(?:לקוח|מטופל|מועמד|שם|נהג|מבוטח|תובע|נתבע|שוכר|מחזיק)[:\s]+([א-ת][א-ת"'\-\s]{2,30}?)(?=[,\n\d]|ת\.ז)/g,/(?:עו"ד|ד"ר|פרופ'|מר|גברת)\s+([א-ת][א-ת"'\-\s]{2,25}?)(?=[,\n])/g],confidence:.75,replacement:()=>"[\u05E9\u05DD \u05DE\u05D5\u05E1\u05EA\u05E8]"},{type:"bank_account",patterns:[/\b\d{2}[\-]\d{5,9}[\-]\d{2,3}\b/g,/(?:חשבון|ח-ן)\s*:?\s*(\d[\d\-]{8,15})/g],confidence:.88,replacement:()=>"[\u05D7\u05E9\u05D1\u05D5\u05DF \u05D1\u05E0\u05E7 \u05DE\u05D5\u05E1\u05EA\u05E8]"},{type:"medical",patterns:[/(?<![א-ת])[בהוכלמש]{0,2}(?:סוכרת|יתר לחץ דם|אסתמה|דיכאון|חרדה|סרטן|אי ספיקת לב|אפילפסיה)(?![א-ת])/g,/\b(?:Metformin|Lisinopril|Atorvastatin|Amlodipine|Sertraline|Fluoxetine|Omeprazole|Warfarin|Aspirin|Insulin)\b/gi,/\bHbA1c\s*:?\s*[\d.]+%?/g,/\bBMI\s*:?\s*[\d.]+/g,/(?<![א-ת])[בהוכלמש]{0,2}אבחנ[הות]\s*:?\s*[^,\n.]{2,40}/g],confidence:.85,replacement:()=>"[\u05DE\u05D9\u05D3\u05E2 \u05E8\u05E4\u05D5\u05D0\u05D9 \u05DE\u05D5\u05E1\u05EA\u05E8]"},{type:"financial_amount",patterns:[/[\d,]+(?:\.\d{2})?\s*(?:₪|ש"ח|NIS|שקל(?:ים)?)/g,/(?:₪|NIS)\s*[\d,]+(?:\.\d{2})?/g],confidence:.92,replacement:()=>"[\u05E1\u05DB\u05D5\u05DD \u05DB\u05E1\u05E4\u05D9 \u05DE\u05D5\u05E1\u05EA\u05E8]"},{type:"birth_date",patterns:[/(?:תאריך לידה|נולד|נולדה|ד\.ל\.)\s*:?\s*\d{1,2}[\/\.\-]\d{1,2}[\/\.\-]\d{2,4}/g,/(?<![א-ת])[בהוכלמש]{0,2}גיל\s*:?\s*\d{1,3}\b/g],confidence:.88,replacement:()=>"[\u05EA\u05D0\u05E8\u05D9\u05DA \u05DC\u05D9\u05D3\u05D4 \u05DE\u05D5\u05E1\u05EA\u05E8]"},{type:"address",patterns:[/רחוב\s+[א-ת][א-ת\s"'\-]{2,30}\s+\d{1,5}/g,/(?:רח'|רח\.)\s+[א-ת][א-ת\s"'\-]{2,30}\d{1,5}/g],confidence:.72,replacement:()=>"[\u05DB\u05EA\u05D5\u05D1\u05EA \u05DE\u05D5\u05E1\u05EA\u05E8\u05EA]"},{type:"license_plate",patterns:[/\b\d{2,3}[\-]\d{2,3}[\-]\d{2,3}\b/g],confidence:.8,replacement:()=>"[\u05DC\u05D5\u05D7\u05D9\u05EA \u05E8\u05D9\u05E9\u05D5\u05D9 \u05DE\u05D5\u05E1\u05EA\u05E8\u05EA]"}];function yh(e){if(e.length!==9)return!1;let t=e.split("").map(Number),n=0;for(let r=0;r<9;r++){let i=t[r]*(r%2===0?1:2);i>9&&(i-=9),n+=i}return n%10===0}var lr=class{constructor(t){this.enabledTypes=new Set(t)}detect(t){let n=[],r=new Set;for(let o of gh)if(this.enabledTypes.has(o.type))for(let a of o.patterns){let s=new RegExp(a.source,a.flags),c;for(;(c=s.exec(t))!==null;){let l=c[0],p=`${o.type}:${c.index}`;if(!r.has(p)){if(r.add(p),o.type==="id_number"){let u=l.replace(/\D/g,"");if(/^\d{9}$/.test(l)&&u.length===9&&!yh(u))continue}n.push({type:o.type,value:l,startIndex:c.index,endIndex:c.index+l.length,confidence:o.confidence,replacement:o.replacement(l,o.type)})}}}n.sort((o,a)=>o.startIndex-a.startIndex||a.confidence-o.confidence);let i=[];for(let o of n)i.some(s=>o.startIndex<s.endIndex&&o.endIndex>s.startIndex)||i.push(o);return i}};var _h=[{pattern:/^(?:שם|שם_מלא|שם פרטי|שם_פרטי|שם משפחה|שם_משפחה|שם_אדם|שם הלקוח|שם_הלקוח|שם בן זוג|שם בן_זוג|שם המבוטח|שם_המבוטח|שם המוטב|שם_המוטב|שם מבוטח|שם_מבוטח|שם מוטב|שם_מוטב|שם הילד|שם_הילד|שם הקטין|שם_הקטין|firstname_he|lastname_he|shem|shem_mishpacha|shem_prati)$/i,type:"name",label:"Person name (Hebrew)",labelHe:"\u05E9\u05DD \u05D0\u05D3\u05DD"},{pattern:/^(?:ת"ז|ת\.ז|ת ז|תז|תעודת זהות|תעודת_זהות|מספר זהות|מספר_זהות|מס' זהות|מס_זהות|מס' ת"ז|teudat_zehut|tz|t_z|israeli_id|il_id)$/i,type:"id",label:"Israeli ID",labelHe:"\u05EA\u05E2\u05D5\u05D3\u05EA \u05D6\u05D4\u05D5\u05EA"},{pattern:/^(?:דרכון|מספר דרכון|מס דרכון|רישיון נהיגה|רישיון_נהיגה|רשיון נהיגה|מס רישיון|דרכון_מספר)$/i,type:"id",label:"Passport / DL (Hebrew)",labelHe:"\u05D3\u05E8\u05DB\u05D5\u05DF/\u05E8\u05D9\u05E9\u05D9\u05D5\u05DF"},{pattern:/^(?:מייל|דוא"ל|דוא_ל|דואר אלקטרוני|דואר_אלקטרוני|אימייל|כתובת מייל|כתובת_מייל|כתובת דואר|כתובת_דואר)$/i,type:"email",label:"Email (Hebrew)",labelHe:"\u05D3\u05D5\u05D0\u05E8 \u05D0\u05DC\u05E7\u05D8\u05E8\u05D5\u05E0\u05D9"},{pattern:/^(?:טלפון|טל'|נייד|פלאפון|סלולרי|מספר טלפון|מספר_טלפון|טלפון נייד|טלפון_נייד|מס נייד|מס_נייד|מס' טל)$/i,type:"phone",label:"Phone (Hebrew)",labelHe:"\u05DE\u05E1\u05E4\u05E8 \u05D8\u05DC\u05E4\u05D5\u05DF"},{pattern:/^(?:כתובת|כתובת מגורים|כתובת_מגורים|רחוב|מס בית|מספר בית|עיר|ישוב|יישוב|מיקוד|כתובת מלאה|כתובת_מלאה|מען)$/i,type:"address",label:"Address (Hebrew)",labelHe:"\u05DB\u05EA\u05D5\u05D1\u05EA"},{pattern:/^(?:תאריך לידה|תאריך_לידה|ת לידה|תאריך הולדת|תאריך_הולדת|יום הולדת|יום_הולדת|גיל)$/i,type:"dob",label:"Date of birth (Hebrew)",labelHe:"\u05EA\u05D0\u05E8\u05D9\u05DA \u05DC\u05D9\u05D3\u05D4"},{pattern:/^(?:חשבון בנק|חשבון_בנק|מספר חשבון|מספר_חשבון|מס חשבון|מס' חשבון|בנק|סניף|מס סניף|iban|iban_il)$/i,type:"financial",label:"Bank account (Hebrew)",labelHe:"\u05D7\u05E9\u05D1\u05D5\u05DF \u05D1\u05E0\u05E7"},{pattern:/^(?:כרטיס אשראי|כרטיס_אשראי|מספר אשראי|מס אשראי|מס' אשראי|cvv|אשראי|מס כרטיס|מס_כרטיס)$/i,type:"financial",label:"Credit card (Hebrew)",labelHe:"\u05DB\u05E8\u05D8\u05D9\u05E1 \u05D0\u05E9\u05E8\u05D0\u05D9"},{pattern:/^(?:שכר|משכורת|הכנסה|פרמיה|שכר ברוטו|שכר_ברוטו|שכר נטו|שכר_נטו|תגמול|בונוס|פיצוי)$/i,type:"financial",label:"Salary / income (Hebrew)",labelHe:"\u05E9\u05DB\u05E8/\u05D4\u05DB\u05E0\u05E1\u05D4"},{pattern:/^(?:אבחון|אבחנה|מחלה|תרופה|מרשם|בדיקה רפואית|בדיקה_רפואית|מצב רפואי|מצב_רפואי|חיסון|תוצאת בדיקה|תוצאת_בדיקה|רופא|רגישות|אלרגיה|סוג דם|סוג_דם)$/i,type:"medical",label:"Medical (Hebrew)",labelHe:"\u05DE\u05D9\u05D3\u05E2 \u05E8\u05E4\u05D5\u05D0\u05D9"},{pattern:/^(?:מספר פוליסה|מספר_פוליסה|מס פוליסה|מס' פוליסה|פוליסה|מספר חבר|מספר_חבר|מס חבר|מספר ביטוח|מספר_ביטוח|policy_?number|policy_?no|policy_?id)$/i,type:"policy",label:"Insurance policy number (Hebrew)",labelHe:"\u05DE\u05E1\u05E4\u05E8 \u05E4\u05D5\u05DC\u05D9\u05E1\u05D4"},{pattern:/^(?:מספר סוכן|מספר_סוכן|מס סוכן|מס' סוכן|מס_סוכן|קוד סוכן|קוד_סוכן|מספר משווק|מספר_משווק|מספר יצרן|סוכן ביטוח|agent_?number|agent_?no|agent_?id|agent_?code|broker_?id|broker_?number)$/i,type:"agent_id",label:"Insurance agent / broker number (Hebrew)",labelHe:"\u05DE\u05E1\u05E4\u05E8 \u05E1\u05D5\u05DB\u05DF"},{pattern:/^(?:שם הילד|שם_הילד|תעודת זהות של ילד|ילדים|קטין|מספר ילדים|מספר_ילדים|תעודת לידה|ת לידה ילד)$/i,type:"minor_data",label:"Minor data (Hebrew)",labelHe:"\u05DE\u05D9\u05D3\u05E2 \u05E2\u05DC \u05E7\u05D8\u05D9\u05DF"},{pattern:/^(?:דת|לאום|מין|נטייה מינית|נטייה_מינית|השקפה פוליטית|השקפה_פוליטית|מצב משפחתי|מצב_משפחתי|עדה|מוצא)$/i,type:"sensitive_personal",label:"Sensitive personal (Hebrew)",labelHe:"\u05DE\u05D9\u05D3\u05E2 \u05D0\u05D9\u05E9\u05D9 \u05E8\u05D2\u05D9\u05E9"},{pattern:/^(?:מספר רכב|מספר_רכב|מס רכב|מס' רכב|לוחית רישוי|לוחית_רישוי|מספר רישוי|מספר_רישוי)$/i,type:"tracking",label:"Vehicle ID (Hebrew)",labelHe:"\u05DE\u05E1\u05E4\u05E8 \u05E8\u05DB\u05D1"}];function Wi(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 i=0;i<9;i++){let o=parseInt(n[i]??"0",10)*(i%2+1);o>9&&(o-=9),r+=o}return r%10===0&&parseInt(n,10)>0}var dr=/(?:\+972[\s-]?|0)(?:5[0-9]|[2-4]|[89])(?:[\s-]?\d){7}/g,ur=/[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}/gi,pr=/\bIL\d{2}\s?(?:\d{4}\s?){4}\d{3}\b/g;function Ec(e){let t=String(e??"").replace(/\D/g,"");if(t.length<13||t.length>19)return!1;let n=0,r=!1;for(let i=t.length-1;i>=0;i--){let o=t.charCodeAt(i)-48;if(o<0||o>9)return!1;r&&(o*=2,o>9&&(o-=9)),n+=o,r=!r}return n%10===0}function xc(e){if(!e)return null;let t=e.trim();for(let n of _h)if(n.pattern.test(t))return{type:n.type,label:n.label,labelHe:n.labelHe};return null}var bh=[{type:"biometric",tokens:["biometric","fingerprint","\u05D1\u05D9\u05D5\u05DE\u05D8\u05E8\u05D9"],phrases:["face id","\u05D8\u05D1\u05D9\u05E2\u05EA \u05D0\u05E6\u05D1\u05E2"]},{type:"medical",tokens:["diagnosis","medical","disease","medication","prescription","allergy","vaccine","\u05D0\u05D1\u05D7\u05D5\u05DF","\u05D0\u05D1\u05D7\u05E0\u05D4","\u05DE\u05D7\u05DC\u05D4","\u05EA\u05E8\u05D5\u05E4\u05D4","\u05DE\u05E8\u05E9\u05DD","\u05D7\u05D9\u05E1\u05D5\u05DF","\u05D0\u05DC\u05E8\u05D2\u05D9\u05D4"],phrases:["medical record","blood type","\u05DE\u05E6\u05D1 \u05E8\u05E4\u05D5\u05D0\u05D9","\u05E1\u05D5\u05D2 \u05D3\u05DD"]},{type:"sensitive_personal",tokens:["religion","ethnicity","nationality","\u05D3\u05EA","\u05DC\u05D0\u05D5\u05DD","\u05E2\u05D3\u05D4","\u05DE\u05D5\u05E6\u05D0"],phrases:["sexual orientation","marital status","\u05DE\u05E6\u05D1 \u05DE\u05E9\u05E4\u05D7\u05EA\u05D9","\u05E0\u05D8\u05D9\u05D9\u05D4 \u05DE\u05D9\u05E0\u05D9\u05EA"]},{type:"minor_data",tokens:["minor","\u05E7\u05D8\u05D9\u05DF"],phrases:["child name","\u05E9\u05DD \u05D4\u05D9\u05DC\u05D3","\u05E9\u05DD \u05D4\u05E7\u05D8\u05D9\u05DF"]},{type:"id",tokens:["ssn","passport","\u05D6\u05D4\u05D5\u05EA","\u05D3\u05E8\u05DB\u05D5\u05DF"],phrases:["national id","id number","identity number","social security","driver license","driving license","drivers license","passport number","tax id","\u05EA\u05E2\u05D5\u05D3\u05EA \u05D6\u05D4\u05D5\u05EA","\u05DE\u05E1\u05E4\u05E8 \u05D6\u05D4\u05D5\u05EA","\u05E8\u05D9\u05E9\u05D9\u05D5\u05DF \u05E0\u05D4\u05D9\u05D2\u05D4"]},{type:"financial",tokens:["iban","swift","bic","salary","income","wage","\u05D0\u05E9\u05E8\u05D0\u05D9","\u05E9\u05DB\u05E8","\u05DE\u05E9\u05DB\u05D5\u05E8\u05EA","\u05D4\u05DB\u05E0\u05E1\u05D4"],phrases:["bank account","account number","credit card","card number","routing number","sort code","\u05D7\u05E9\u05D1\u05D5\u05DF \u05D1\u05E0\u05E7","\u05DE\u05E1\u05E4\u05E8 \u05D7\u05E9\u05D1\u05D5\u05DF","\u05DB\u05E8\u05D8\u05D9\u05E1 \u05D0\u05E9\u05E8\u05D0\u05D9"]},{type:"policy",tokens:["policy","\u05E4\u05D5\u05DC\u05D9\u05E1\u05D4"],phrases:["policy number","member number","\u05DE\u05E1\u05E4\u05E8 \u05E4\u05D5\u05DC\u05D9\u05E1\u05D4"]},{type:"agent_id",tokens:["\u05DE\u05E9\u05D5\u05D5\u05E7"],phrases:["agent number","agent code","broker id","\u05DE\u05E1\u05E4\u05E8 \u05E1\u05D5\u05DB\u05DF"]},{type:"dob",tokens:["dob","birthdate","birthday","\u05DC\u05D9\u05D3\u05D4","\u05D4\u05D5\u05DC\u05D3\u05EA","\u05D2\u05D9\u05DC"],phrases:["date of birth","birth date","\u05EA\u05D0\u05E8\u05D9\u05DA \u05DC\u05D9\u05D3\u05D4"]},{type:"phone",tokens:["phone","tel","mobile","cell","fax","\u05D8\u05DC\u05E4\u05D5\u05DF","\u05E0\u05D9\u05D9\u05D3","\u05E4\u05DC\u05D0\u05E4\u05D5\u05DF","\u05E1\u05DC\u05D5\u05DC\u05E8\u05D9"],phrases:["phone number","mobile number","cell phone","\u05D8\u05DC\u05E4\u05D5\u05DF \u05E0\u05D9\u05D9\u05D3"]},{type:"email",tokens:["email","mail","\u05D0\u05D9\u05DE\u05D9\u05D9\u05DC","\u05DE\u05D9\u05D9\u05DC","\u05D3\u05D5\u05D0\u05DC"],phrases:["email address","e mail","\u05D3\u05D5\u05D0\u05E8 \u05D0\u05DC\u05E7\u05D8\u05E8\u05D5\u05E0\u05D9","\u05DB\u05EA\u05D5\u05D1\u05EA \u05DE\u05D9\u05D9\u05DC"]},{type:"address",tokens:["address","street","city","zipcode","zip","postcode","\u05DB\u05EA\u05D5\u05D1\u05EA","\u05E8\u05D7\u05D5\u05D1","\u05E2\u05D9\u05E8","\u05D9\u05E9\u05D5\u05D1","\u05D9\u05D9\u05E9\u05D5\u05D1","\u05DE\u05D9\u05E7\u05D5\u05D3","\u05DE\u05E2\u05DF"],phrases:["home address","postal code","street address","zip code","\u05DB\u05EA\u05D5\u05D1\u05EA \u05DE\u05D2\u05D5\u05E8\u05D9\u05DD"]},{type:"location",tokens:["gps","latitude","longitude","geolocation","\u05DE\u05D9\u05E7\u05D5\u05DD"],phrases:["gps coordinates"]},{type:"tracking",tokens:["plate","vehicle","\u05E8\u05DB\u05D1","\u05E8\u05D9\u05E9\u05D5\u05D9"],phrases:["license plate","vehicle number","plate number","\u05DE\u05E1\u05E4\u05E8 \u05E8\u05DB\u05D1"]},{type:"name",tokens:["name","\u05E9\u05DD"],phrases:["first name","last name","full name","family name","given name","surname","\u05E9\u05DD \u05E4\u05E8\u05D8\u05D9","\u05E9\u05DD \u05DE\u05E9\u05E4\u05D7\u05D4","\u05E9\u05DD \u05DE\u05DC\u05D0"]}];function fr(e){if(!e)return null;let t=e.trim().toLowerCase().replace(/["'`׳״]/g,"").replace(/[_\-.]+/g," ").replace(/\s+/g," ").trim();if(!t)return null;let n=new Set(t.match(/[\p{L}\p{N}]+/gu)??[]);for(let r of bh)if(r.phrases?.some(o=>t.includes(o))||r.tokens?.some(o=>n.has(o)))return{type:r.type,label:r.type,labelHe:hr(r.type)};return null}function hr(e){return{id:"\u05EA\u05E2\u05D5\u05D3\u05EA \u05D6\u05D4\u05D5\u05EA",agent_id:"\u05DE\u05E1\u05E4\u05E8 \u05E1\u05D5\u05DB\u05DF",policy:"\u05DE\u05E1\u05E4\u05E8 \u05E4\u05D5\u05DC\u05D9\u05E1\u05D4",name:"\u05E9\u05DD \u05D0\u05D3\u05DD",email:"\u05D3\u05D5\u05D0\u05E8 \u05D0\u05DC\u05E7\u05D8\u05E8\u05D5\u05E0\u05D9",phone:"\u05DE\u05E1\u05E4\u05E8 \u05D8\u05DC\u05E4\u05D5\u05DF",address:"\u05DB\u05EA\u05D5\u05D1\u05EA",dob:"\u05EA\u05D0\u05E8\u05D9\u05DA \u05DC\u05D9\u05D3\u05D4",financial:"\u05E4\u05E8\u05D8\u05D9\u05DD \u05E4\u05D9\u05E0\u05E0\u05E1\u05D9\u05D9\u05DD",medical:"\u05DE\u05D9\u05D3\u05E2 \u05E8\u05E4\u05D5\u05D0\u05D9",minor_data:"\u05DE\u05D9\u05D3\u05E2 \u05E2\u05DC \u05E7\u05D8\u05D9\u05DF",sensitive_personal:"\u05DE\u05D9\u05D3\u05E2 \u05D0\u05D9\u05E9\u05D9 \u05E8\u05D2\u05D9\u05E9",biometric:"\u05DE\u05D9\u05D3\u05E2 \u05D1\u05D9\u05D5\u05DE\u05D8\u05E8\u05D9",auth:"\u05E1\u05D9\u05E1\u05DE\u05D0\u05D5\u05EA/\u05E1\u05D5\u05D3\u05D5\u05EA",tracking:"\u05DE\u05D6\u05D4\u05D9 \u05DE\u05E2\u05E7\u05D1",location:"\u05DE\u05D9\u05E7\u05D5\u05DD"}[e]??"\u05DE\u05D9\u05D3\u05E2 \u05D0\u05D9\u05E9\u05D9"}function Ac(e){let t=0,n=0,r=0,i=0,o=0;for(let s of e)typeof s=="string"&&(Wi(s)&&t++,dr.lastIndex=0,dr.test(s)&&n++,ur.lastIndex=0,ur.test(s)&&r++,pr.lastIndex=0,pr.test(s)&&i++,Ec(s)&&o++);let a=e.length||1;return t/a>=.3?{type:"id",label:"Israeli ID (sniffed)",matchedSample:t}:i/a>=.3?{type:"financial",label:"IBAN-IL (sniffed)",matchedSample:i}:n/a>=.3?{type:"phone",label:"IL phone (sniffed)",matchedSample:n}:r/a>=.3?{type:"email",label:"Email (sniffed)",matchedSample:r}:o/a>=.3?{type:"financial",label:"Credit card (sniffed)",matchedSample:o}:null}var Tc={_comment:"CANONICAL secret ruleset \u2014 the SINGLE SOURCE OF TRUTH for hardcoded-secret detection, loaded by BOTH the web scanner (lib/soc/exposure-map.ts) and the installed Capsule agent (apps/desktop/src-tauri/src/scanner.rs, via include_str!). Patterns are written in the regex subset both JavaScript and the Rust `regex` crate accept (no lookaround, no backreferences). A connection string counts only WITH credentials (user:pass@). Edit here once and both engines stay aligned.",rules:[{id:"aws-access-key",subkind:"aws_access_key",name:"AWS Access Key",severity:"critical",pattern:"(?:^|[^A-Z0-9])AKIA[A-Z2-7]{16}(?:[^A-Z2-7]|$)",hint:"AWS access key id detected. Rotate via IAM and move to an environment variable."},{id:"aws-secret-key",subkind:"aws_secret_key",name:"AWS Secret Key",severity:"critical",pattern:`(?:aws_secret_access_key|aws_secret_key|secret_access_key)\\s*[=:]\\s*['"]?[A-Za-z0-9/+=]{40}['"]?`,hint:"AWS secret access key detected. Rotate immediately."},{id:"gcp-api-key",subkind:"gcp_api_key",name:"GCP API Key",severity:"critical",pattern:"AIza[0-9A-Za-z_-]{35}",hint:"Google API key detected. Restrict or rotate it in the Google Cloud console."},{id:"gcp-service-account",subkind:"gcp_service_account",name:"GCP Service Account",severity:"critical",pattern:'"type"\\s*:\\s*"service_account"',hint:"GCP service-account JSON detected. Move it out of the repo and rotate the key."},{id:"github-token",subkind:"github_token",name:"GitHub Token",severity:"critical",pattern:"gh[pousr]_[0-9a-zA-Z]{36,}",hint:"GitHub token detected. Revoke at https://github.com/settings/tokens."},{id:"github-fine-grained",subkind:"github_fine_grained_token",name:"GitHub Fine-Grained Token",severity:"critical",pattern:"github_pat_[0-9a-zA-Z_]{22,}",hint:"GitHub fine-grained token detected. Revoke it in GitHub settings."},{id:"gitlab-token",subkind:"gitlab_token",name:"GitLab Token",severity:"critical",pattern:"glpat-[0-9a-zA-Z_-]{20,}",hint:"GitLab token detected. Revoke it in GitLab access tokens."},{id:"stripe-secret",subkind:"stripe_key",name:"Stripe Secret Key",severity:"critical",pattern:"sk_live_[0-9a-zA-Z]{24,}",hint:"Stripe live secret key detected. Roll it in the Stripe dashboard."},{id:"stripe-restricted",subkind:"stripe_restricted_key",name:"Stripe Restricted Key",severity:"critical",pattern:"rk_live_[0-9a-zA-Z]{24,}",hint:"Stripe restricted key detected. Roll it in the Stripe dashboard."},{id:"slack-token",subkind:"slack_token",name:"Slack Token",severity:"high",pattern:"xox[baprs]-[0-9a-zA-Z-]{10,}",hint:"Slack token detected. Revoke it in the Slack app settings."},{id:"slack-webhook",subkind:"slack_webhook",name:"Slack Webhook",severity:"high",pattern:"hooks\\.slack\\.com/services/T[0-9A-Z]{8,}/B[0-9A-Z]{8,}/[0-9a-zA-Z]{24}",hint:"Slack incoming-webhook URL detected. Regenerate it."},{id:"twilio-api-key",subkind:"twilio_api_key",name:"Twilio API Key",severity:"high",pattern:"SK[0-9a-fA-F]{32}",hint:"Twilio API key detected. Rotate it in the Twilio console."},{id:"sendgrid-api-key",subkind:"sendgrid_api_key",name:"SendGrid API Key",severity:"critical",pattern:"SG\\.[0-9a-zA-Z_-]{22}\\.[0-9a-zA-Z_-]{43}",hint:"SendGrid API key detected. Rotate it in the SendGrid console."},{id:"postgres-uri",subkind:"postgres_uri",name:"PostgreSQL Connection String",severity:"critical",pattern:`postgres(?:ql)?://[^\\s'":/@]*:[^\\s'"@]+@[^\\s'"]+`,hint:"PostgreSQL connection string WITH credentials detected. Move it to a secret manager and rotate the password."},{id:"mongodb-uri",subkind:"mongodb_uri",name:"MongoDB Connection String",severity:"critical",pattern:`mongodb(?:\\+srv)?://[^\\s'":/@]*:[^\\s'"@]+@[^\\s'"]+`,hint:"MongoDB connection string WITH credentials detected. Move it to a secret manager and rotate the password."},{id:"redis-uri",subkind:"redis_uri",name:"Redis Connection String",severity:"high",pattern:`redis(?:s)?://[^\\s'":/@]*:[^\\s'"@]+@[^\\s'"]+`,hint:"Redis connection string WITH credentials detected. Move it to a secret manager and rotate the password."},{id:"openai-key",subkind:"openai_key",name:"OpenAI API Key",severity:"critical",pattern:"sk-[0-9a-zA-Z]{20,}T3BlbkFJ[0-9a-zA-Z]{20,}",hint:"OpenAI API key detected. Rotate at https://platform.openai.com/api-keys."},{id:"anthropic-key",subkind:"anthropic_key",name:"Anthropic API Key",severity:"critical",pattern:"sk-ant-[0-9a-zA-Z_-]{40,}",hint:"Anthropic API key detected. Rotate at https://console.anthropic.com/."},{id:"firebase-key",subkind:"firebase_key",name:"Firebase API Key",severity:"high",pattern:"AIza[0-9A-Za-z_-]{35}",hint:"Firebase API key detected. Restrict it in the Firebase console."},{id:"supabase-key",subkind:"supabase_key",name:"Supabase Service Key",severity:"critical",pattern:"eyJ[0-9a-zA-Z_-]{100,}",hint:"Long JWT (possible Supabase service key) detected. Rotate it and keep it server-side only."},{id:"private-key",subkind:"private_key",name:"Private Key",severity:"critical",pattern:"-----BEGIN (?:RSA |EC |DSA |OPENSSH )?PRIVATE KEY-----",hint:"Private key material in plaintext. Rotate immediately and move to a key manager (KMS/Vault).",skipPlaceholder:!0},{id:"jwt-secret",subkind:"jwt_secret",name:"JWT/Generic Secret",severity:"high",pattern:`(?:jwt_secret|JWT_SECRET|secret_key|SECRET_KEY|api_secret|API_SECRET)\\s*[=:]\\s*['"][^'"]{8,}['"]`,hint:"Hardcoded signing/API secret detected. Move it to an environment variable and rotate it."},{id:"password-in-code",subkind:"password_in_code",name:"Password in Code",severity:"high",pattern:`(?:password|passwd|pwd)\\s*[=:]\\s*['"][^'"]{8,}['"]`,hint:"Hardcoded password detected. Move it to a secret manager and rotate it."},{id:"bearer-token",subkind:"bearer_token",name:"Bearer Token in Code",severity:"high",pattern:`['"]Bearer\\s+[0-9a-zA-Z._-]{20,}['"]`,hint:"Hardcoded bearer token detected. Move it to a secret manager and rotate it."},{id:"hex-secret-32",subkind:"hex_secret",name:"Hardcoded 32+ Hex Secret",severity:"medium",pattern:`['"][0-9a-f]{32,}['"]`,hint:"Long hex string that looks like a secret/hash. Confirm it is not a live credential."},{id:"base64-secret",subkind:"base64_secret",name:"Hardcoded Base64 Secret (long)",severity:"medium",pattern:`['"][A-Za-z0-9+/]{64,}={0,2}['"]`,hint:"Long base64 blob that looks like an embedded secret. Confirm it is not a live credential."}]};var wh=[{pattern:/^(full_?name|first_?name|last_?name|spouse_?name|beneficiary_?name)$/i,type:"name",label:"Person name",labelHe:"\u05E9\u05DD \u05D0\u05D3\u05DD"},{pattern:/^(email|e_?mail|email_?address)$/i,type:"email",label:"Email address",labelHe:"\u05DB\u05EA\u05D5\u05D1\u05EA \u05D0\u05D9\u05DE\u05D9\u05D9\u05DC"},{pattern:/^(phone|mobile|telephone|phone_?number|cell_?phone)$/i,type:"phone",label:"Phone number",labelHe:"\u05DE\u05E1\u05E4\u05E8 \u05D8\u05DC\u05E4\u05D5\u05DF"},{pattern:/^(id_?number|identity|ssn|social_?security|national_?id|teudat_?zehut)$/i,type:"id",label:"ID number",labelHe:"\u05DE\u05E1\u05E4\u05E8 \u05DE\u05D6\u05D4\u05D4"},{pattern:/^(address|street_?address|home_?address)$/i,type:"address",label:"Address",labelHe:"\u05DB\u05EA\u05D5\u05D1\u05EA"},{pattern:/^(date_?of_?birth|dob|birth_?date|birthday)$/i,type:"dob",label:"Date of birth",labelHe:"\u05EA\u05D0\u05E8\u05D9\u05DA \u05DC\u05D9\u05D3\u05D4"},{pattern:/^(bank_?account|iban|account_?number|bank_?details|routing_?number)$/i,type:"financial",label:"Bank account",labelHe:"\u05D7\u05E9\u05D1\u05D5\u05DF \u05D1\u05E0\u05E7"},{pattern:/^(credit_?card|card_?number|cvv|cc_?number)$/i,type:"financial",label:"Credit card",labelHe:"\u05DB\u05E8\u05D8\u05D9\u05E1 \u05D0\u05E9\u05E8\u05D0\u05D9"},{pattern:/^(salary|income|commission|premium|compensation)$/i,type:"financial",label:"Financial data",labelHe:"\u05E0\u05EA\u05D5\u05DF \u05E4\u05D9\u05E0\u05E0\u05E1\u05D9"},{pattern:/^(medical_?info|health_?conditions|diagnosis|medication)$/i,type:"medical",label:"Medical data",labelHe:"\u05DE\u05D9\u05D3\u05E2 \u05E8\u05E4\u05D5\u05D0\u05D9"},{pattern:/^(ip_?address)$/i,type:"tracking",label:"IP address",labelHe:"\u05DB\u05EA\u05D5\u05D1\u05EA IP"},{pattern:/^(passport|passport_?number|passport_?id)$/i,type:"id",label:"Passport number",labelHe:"\u05DE\u05E1\u05E4\u05E8 \u05D3\u05E8\u05DB\u05D5\u05DF"},{pattern:/^(driver_?license|drivers_?license|dl_?number)$/i,type:"id",label:"Driver license",labelHe:"\u05E8\u05D9\u05E9\u05D9\u05D5\u05DF \u05E0\u05D4\u05D9\u05D2\u05D4"},{pattern:/^(iban|swift_?code|bic)$/i,type:"financial",label:"Banking code",labelHe:"\u05E7\u05D5\u05D3 \u05D1\u05E0\u05E7\u05D0\u05D9"},{pattern:/^(tax_?id|tin|vat_?number|ein)$/i,type:"financial",label:"Tax ID",labelHe:"\u05DE\u05E1\u05E4\u05E8 \u05DE\u05E1"},{pattern:/^(insurance_?number|policy_?number|member_?id)$/i,type:"id",label:"Insurance/Member ID",labelHe:"\u05DE\u05E1\u05E4\u05E8 \u05D1\u05D9\u05D8\u05D5\u05D7/\u05D7\u05D1\u05E8"},{pattern:/^(blood_?type|allergy|allergies|prescription)$/i,type:"medical",label:"Medical data",labelHe:"\u05DE\u05D9\u05D3\u05E2 \u05E8\u05E4\u05D5\u05D0\u05D9"},{pattern:/^(biometric|fingerprint|face_?id|retina)$/i,type:"biometric",label:"Biometric data",labelHe:"\u05DE\u05D9\u05D3\u05E2 \u05D1\u05D9\u05D5\u05DE\u05D8\u05E8\u05D9"},{pattern:/^(latitude|longitude|lat|lng|geo_?location|coordinates)$/i,type:"location",label:"Geolocation",labelHe:"\u05DE\u05D9\u05E7\u05D5\u05DD \u05D2\u05D9\u05D0\u05D5\u05D2\u05E8\u05E4\u05D9"},{pattern:/^(mac_?address|device_?fingerprint|imei|serial_?number)$/i,type:"tracking",label:"Device identifier",labelHe:"\u05DE\u05D6\u05D4\u05D4 \u05DE\u05DB\u05E9\u05D9\u05E8"},{pattern:/^(ethnicity|race|religion|political_?affiliation|sexual_?orientation)$/i,type:"sensitive_personal",label:"Sensitive personal",labelHe:"\u05DE\u05D9\u05D3\u05E2 \u05D0\u05D9\u05E9\u05D9 \u05E8\u05D2\u05D9\u05E9"},{pattern:/^(minor|child_?name|child_?age|dependent)$/i,type:"minor_data",label:"Minor data",labelHe:"\u05DE\u05D9\u05D3\u05E2 \u05E2\u05DC \u05E7\u05D8\u05D9\u05E0\u05D9\u05DD"},{pattern:/^(signature|digital_?signature)$/i,type:"id",label:"Signature",labelHe:"\u05D7\u05EA\u05D9\u05DE\u05D4"},{pattern:/^(vehicle_?number|license_?plate|plate_?number)$/i,type:"tracking",label:"Vehicle ID",labelHe:"\u05DE\u05D6\u05D4\u05D4 \u05E8\u05DB\u05D1"}],Sh=/^(id|uuid|created_?at|updated_?at|deleted_?at|status|type|category|description|title|slug|url|path|key|value|sort_?order|position|enabled|active|public|version|metadata|config|settings|options|data|content|body|raw|json|text|note|comment|label|color|icon|image|avatar|logo|thumbnail|preview|template|schema|format|mode|level|priority|severity|source|target|parent|child|owner|creator|modifier|assignee|project|workspace|organization|team|group|channel|thread|room|session|device|platform|browser|locale|timezone|currency|country|region|city|zip|postal|state|province|name|display_?name|user_?agent|password_?hash|secret|token|private_?key|auth_?token|constraint|index|sequence|trigger|function|procedure|database|namespace|migration|revision)$/i,Eh=/^(beacon_?registr|device_?config|hardware|sensor|firmware|telemetry|metric|analytic|log_?event|audit_?log|system_?config|cache|queue|job|migration|schema_?version|spatial_?ref)/i,xh=/^(minor|major|uuid|rssi|tx_?power|beacon_?id|device_?type|firmware_?version|batch_?id|zone_?id)$/i;function Ic(e,t){if(Sh.test(e)||/^name$/i.test(e)||t&&Eh.test(t)||xh.test(e))return null;for(let r of wh)if(r.pattern.test(e))return r.type;let n=xc(e);return n?n.type:null}var $_=Tc.rules.map(e=>({id:e.id,name:e.name,pattern:new RegExp(e.pattern),severity:e.severity}));var R_=512*1024,D_=50*1024*1024;var Ah={id:"high",agent_id:"high",policy:"high",financial:"high",medical:"critical",sensitive_personal:"critical",minor_data:"critical",biometric:"critical",auth:"critical",name:"medium",email:"high",phone:"high",address:"high",dob:"high",location:"high",tracking:"low"};function Th(e){return Ah[e]??"low"}function $c(e,t){let n=[];for(let r of t){let i=r.rows.length;for(let o=0;o<r.headers.length;o++){let a=r.headers[o]??"",s=a?Ic(a.trim().replace(/["'`׳״:]/g,"").replace(/\s+/g,"_"),r.name)??fr(a)?.type??null:null,c=[];for(let p of r.rows){let u=p[o];typeof u=="string"&&u.length>0&&c.push(u)}let l=c.length>0?Ac(c):null;l?n.push(Pc(e,r.name,a,l.type,l.label,"value",l.matchedSample,i)):s&&n.push(Pc(e,r.name,a,s,hr(s),"header",0,i))}}return n}function Pc(e,t,n,r,i,o,a,s){return{file:e,location:t,column:n,type:r,label:i,category:hr(r),severity:Th(r),matchKind:o,hits:a,sampleSize:s}}var Rc={_comment:"CANONICAL secret ruleset \u2014 the SINGLE SOURCE OF TRUTH for hardcoded-secret detection, loaded by BOTH the web scanner (lib/soc/exposure-map.ts) and the installed Capsule agent (apps/desktop/src-tauri/src/scanner.rs, via include_str!). Patterns are written in the regex subset both JavaScript and the Rust `regex` crate accept (no lookaround, no backreferences). A connection string counts only WITH credentials (user:pass@). Edit here once and both engines stay aligned.",rules:[{id:"aws-access-key",subkind:"aws_access_key",name:"AWS Access Key",severity:"critical",pattern:"(?:^|[^A-Z0-9])AKIA[A-Z2-7]{16}(?:[^A-Z2-7]|$)",hint:"AWS access key id detected. Rotate via IAM and move to an environment variable."},{id:"aws-secret-key",subkind:"aws_secret_key",name:"AWS Secret Key",severity:"critical",pattern:`(?:aws_secret_access_key|aws_secret_key|secret_access_key)\\s*[=:]\\s*['"]?[A-Za-z0-9/+=]{40}['"]?`,hint:"AWS secret access key detected. Rotate immediately."},{id:"gcp-api-key",subkind:"gcp_api_key",name:"GCP API Key",severity:"critical",pattern:"AIza[0-9A-Za-z_-]{35}",hint:"Google API key detected. Restrict or rotate it in the Google Cloud console."},{id:"gcp-service-account",subkind:"gcp_service_account",name:"GCP Service Account",severity:"critical",pattern:'"type"\\s*:\\s*"service_account"',hint:"GCP service-account JSON detected. Move it out of the repo and rotate the key."},{id:"github-token",subkind:"github_token",name:"GitHub Token",severity:"critical",pattern:"gh[pousr]_[0-9a-zA-Z]{36,}",hint:"GitHub token detected. Revoke at https://github.com/settings/tokens."},{id:"github-fine-grained",subkind:"github_fine_grained_token",name:"GitHub Fine-Grained Token",severity:"critical",pattern:"github_pat_[0-9a-zA-Z_]{22,}",hint:"GitHub fine-grained token detected. Revoke it in GitHub settings."},{id:"gitlab-token",subkind:"gitlab_token",name:"GitLab Token",severity:"critical",pattern:"glpat-[0-9a-zA-Z_-]{20,}",hint:"GitLab token detected. Revoke it in GitLab access tokens."},{id:"stripe-secret",subkind:"stripe_key",name:"Stripe Secret Key",severity:"critical",pattern:"sk_live_[0-9a-zA-Z]{24,}",hint:"Stripe live secret key detected. Roll it in the Stripe dashboard."},{id:"stripe-restricted",subkind:"stripe_restricted_key",name:"Stripe Restricted Key",severity:"critical",pattern:"rk_live_[0-9a-zA-Z]{24,}",hint:"Stripe restricted key detected. Roll it in the Stripe dashboard."},{id:"slack-token",subkind:"slack_token",name:"Slack Token",severity:"high",pattern:"xox[baprs]-[0-9a-zA-Z-]{10,}",hint:"Slack token detected. Revoke it in the Slack app settings."},{id:"slack-webhook",subkind:"slack_webhook",name:"Slack Webhook",severity:"high",pattern:"hooks\\.slack\\.com/services/T[0-9A-Z]{8,}/B[0-9A-Z]{8,}/[0-9a-zA-Z]{24}",hint:"Slack incoming-webhook URL detected. Regenerate it."},{id:"twilio-api-key",subkind:"twilio_api_key",name:"Twilio API Key",severity:"high",pattern:"SK[0-9a-fA-F]{32}",hint:"Twilio API key detected. Rotate it in the Twilio console."},{id:"sendgrid-api-key",subkind:"sendgrid_api_key",name:"SendGrid API Key",severity:"critical",pattern:"SG\\.[0-9a-zA-Z_-]{22}\\.[0-9a-zA-Z_-]{43}",hint:"SendGrid API key detected. Rotate it in the SendGrid console."},{id:"postgres-uri",subkind:"postgres_uri",name:"PostgreSQL Connection String",severity:"critical",pattern:`postgres(?:ql)?://[^\\s'":/@]*:[^\\s'"@]+@[^\\s'"]+`,hint:"PostgreSQL connection string WITH credentials detected. Move it to a secret manager and rotate the password."},{id:"mongodb-uri",subkind:"mongodb_uri",name:"MongoDB Connection String",severity:"critical",pattern:`mongodb(?:\\+srv)?://[^\\s'":/@]*:[^\\s'"@]+@[^\\s'"]+`,hint:"MongoDB connection string WITH credentials detected. Move it to a secret manager and rotate the password."},{id:"redis-uri",subkind:"redis_uri",name:"Redis Connection String",severity:"high",pattern:`redis(?:s)?://[^\\s'":/@]*:[^\\s'"@]+@[^\\s'"]+`,hint:"Redis connection string WITH credentials detected. Move it to a secret manager and rotate the password."},{id:"openai-key",subkind:"openai_key",name:"OpenAI API Key",severity:"critical",pattern:"sk-[0-9a-zA-Z]{20,}T3BlbkFJ[0-9a-zA-Z]{20,}",hint:"OpenAI API key detected. Rotate at https://platform.openai.com/api-keys."},{id:"anthropic-key",subkind:"anthropic_key",name:"Anthropic API Key",severity:"critical",pattern:"sk-ant-[0-9a-zA-Z_-]{40,}",hint:"Anthropic API key detected. Rotate at https://console.anthropic.com/."},{id:"firebase-key",subkind:"firebase_key",name:"Firebase API Key",severity:"high",pattern:"AIza[0-9A-Za-z_-]{35}",hint:"Firebase API key detected. Restrict it in the Firebase console."},{id:"supabase-key",subkind:"supabase_key",name:"Supabase Service Key",severity:"critical",pattern:"eyJ[0-9a-zA-Z_-]{100,}",hint:"Long JWT (possible Supabase service key) detected. Rotate it and keep it server-side only."},{id:"private-key",subkind:"private_key",name:"Private Key",severity:"critical",pattern:"-----BEGIN (?:RSA |EC |DSA |OPENSSH )?PRIVATE KEY-----",hint:"Private key material in plaintext. Rotate immediately and move to a key manager (KMS/Vault).",skipPlaceholder:!0},{id:"jwt-secret",subkind:"jwt_secret",name:"JWT/Generic Secret",severity:"high",pattern:`(?:jwt_secret|JWT_SECRET|secret_key|SECRET_KEY|api_secret|API_SECRET)\\s*[=:]\\s*['"][^'"]{8,}['"]`,hint:"Hardcoded signing/API secret detected. Move it to an environment variable and rotate it."},{id:"password-in-code",subkind:"password_in_code",name:"Password in Code",severity:"high",pattern:`(?:password|passwd|pwd)\\s*[=:]\\s*['"][^'"]{8,}['"]`,hint:"Hardcoded password detected. Move it to a secret manager and rotate it."},{id:"bearer-token",subkind:"bearer_token",name:"Bearer Token in Code",severity:"high",pattern:`['"]Bearer\\s+[0-9a-zA-Z._-]{20,}['"]`,hint:"Hardcoded bearer token detected. Move it to a secret manager and rotate it."},{id:"hex-secret-32",subkind:"hex_secret",name:"Hardcoded 32+ Hex Secret",severity:"medium",pattern:`['"][0-9a-f]{32,}['"]`,hint:"Long hex string that looks like a secret/hash. Confirm it is not a live credential."},{id:"base64-secret",subkind:"base64_secret",name:"Hardcoded Base64 Secret (long)",severity:"medium",pattern:`['"][A-Za-z0-9+/]{64,}={0,2}['"]`,hint:"Long base64 blob that looks like an embedded secret. Confirm it is not a live credential."}]};var Ph=[{type:"full_name",kind:"name",severity:"medium",hint:`A person's name in free text (after a role word such as \u05DC\u05E7\u05D5\u05D7 / \u05DE\u05E8 / \u05E2\u05D5"\u05D3).`},{type:"bank_account",kind:"bank_account",severity:"high",hint:"An Israeli bank account number (branch-account-check form) in plaintext."},{type:"medical",kind:"medical",severity:"high",hint:"Medical information (diagnosis, medication, lab value) in plaintext."},{type:"birth_date",kind:"dob",severity:"medium",hint:"A date of birth in plaintext."},{type:"address",kind:"address",severity:"medium",hint:"A street address in plaintext."},{type:"license_plate",kind:"plate",severity:"low",hint:"A vehicle licence plate in plaintext."}],$h=/^(?:לקוח|מטופל|מועמד|שם|נהג|מבוטח|תובע|נתבע|שוכר|מחזיק|עו"ד|ד"ר|פרופ'|מר|גברת|חשבון|ח-ן|[בהוכלמש]{0,2}אבחנ[הות]|תאריך לידה|נולד|נולדה|ד\.ל\.|[בהוכלמש]{0,2}גיל)\s*:?\s*/;function Rh(e,t,n,r){if(r==="address")return{start:t,end:n};let i=$h.exec(e.slice(t,n));return i&&t+i[0].length<n?{start:t+i[0].length,end:n}:{start:t,end:n}}var Dh=new Set(["hex-secret-32","base64-secret"]),Dc=!1;function Cc(){if(Dc)return;Dc=!0;let e=Ph.map(({type:n,kind:r,severity:i,hint:o})=>{let a=new lr([n]);return{kind:r,severity:i,hint:o,find:s=>a.detect(s).map(c=>Rh(s,c.startIndex,c.endIndex,r))}}),t=Rc.rules.filter(n=>!Dh.has(n.id)).map(n=>({id:n.id,name:n.name,severity:n.severity,pattern:new RegExp(n.pattern)}));Ar({text:e,header:n=>{let r=fr(n);return r?{type:r.type,label:r.labelHe||r.label}:null},secrets:t,table:n=>$c("",[n]).filter(r=>r.column).map(r=>({column:r.column,type:r.type,category:r.category,severity:r.severity,hits:r.hits,how:r.matchKind==="value"?"value":"header"}))})}import{z as Bh}from"zod";import{existsSync as Fh,mkdirSync as Mh,readFileSync as Kh,writeFileSync as Hh}from"node:fs";import{homedir as jc,hostname as mr}from"node:os";import{join as Et}from"node:path";function et(e){if(e===null||typeof e!="object")return JSON.stringify(e);if(Array.isArray(e))return"["+e.map(et).join(",")+"]";let t=e;return"{"+Object.keys(t).sort().map(r=>JSON.stringify(r)+":"+et(t[r])).join(",")+"}"}import{mkdirSync as Ch,readFileSync as zi,writeFileSync as qi,existsSync as Ji,chmodSync as Nh,statSync as Oh}from"node:fs";import{join as Yi}from"node:path";import Zi from"node:crypto";function rn(e){return Yi(e,"agent-private-key.pem")}function Qi(e){return Yi(e,"agent-public-key.pem")}function Xi(e){return Yi(e,"agent-key-meta.json")}function eo(e){Ch(e,{recursive:!0});let t=rn(e),n=Qi(e);if(Ji(t)&&Ji(n))try{return jh(e)}catch(r){throw new Error(`agent keystore corrupted at ${e}: ${r.message}`)}return Lh(e)}function jh(e){let t=zi(rn(e),"utf8"),n=zi(Qi(e),"utf8"),r=Ji(Xi(e))?JSON.parse(zi(Xi(e),"utf8")):{},i=Zi.createPrivateKey({key:t,format:"pem"});if(i.asymmetricKeyType!=="ed25519")throw new Error(`expected ed25519 key, got ${i.asymmetricKeyType}`);return{privateKey:i,publicKeyPem:n,generatedAt:r.generatedAt??new Date(Oh(rn(e)).mtime).toISOString()}}function Lh(e){let{publicKey:t,privateKey:n}=Zi.generateKeyPairSync("ed25519"),r=n.export({type:"pkcs8",format:"pem"}),i=t.export({type:"spki",format:"pem"}),o=new Date().toISOString();if(qi(rn(e),r,{encoding:"utf8"}),qi(Qi(e),i,{encoding:"utf8"}),qi(Xi(e),JSON.stringify({generatedAt:o},null,2),"utf8"),process.platform!=="win32")try{Nh(rn(e),384)}catch{}return{privateKey:n,publicKeyPem:i,generatedAt:o}}function on(e,t){return Zi.sign(null,Buffer.from(t,"utf8"),e.privateKey).toString("hex")}var Nc=3e4,an=class{constructor(t){this.apiBase=t}url(t){return this.apiBase.replace(/\/+$/,"")+t}async request(t,n){let r=this.url(t);try{return await fetch(r,{...n,signal:AbortSignal.timeout(Nc)})}catch(i){let o=i;if(o?.name==="TimeoutError"||o?.name==="AbortError")throw new Error(`${t} timed out after ${Nc}ms (${r})`);let a=o?.cause?.code;throw new Error(`${t} could not reach ${r}${a?` (${a})`:""}: ${o?.message??String(i)}`)}}async enroll(t){let n=await this.request("/api/capsule/enroll",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(t)}),r=await n.text();if(!n.ok)throw new Error(`enroll failed: HTTP ${n.status} \u2014 ${r}`);return JSON.parse(r)}async heartbeat(t,n){let r=et({deployment_id:t.deployment_id,agent_version:t.agent_version,applied_config:t.applied_config??null,discovered_release_version:t.discovered_release_version??null}),i=on(n,r),o={...t,signature_hex:i},a=await this.request("/api/capsule/heartbeat",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(o)}),s=await a.text();if(!a.ok)throw new Error(`heartbeat failed: HTTP ${a.status} \u2014 ${s}`);try{return JSON.parse(s)}catch{return{ok:!0,desired_config:null,apply_update:!1}}}async submitSealBackup(t,n){let{deployment_id:r,...i}=t,o=et(i),a=on(n,o),s={deployment_id:r,...i,signature_hex:a},c=await this.request("/api/capsule/seal/backup",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(s)}),l=await c.text();if(!c.ok)throw new Error(`seal backup failed: HTTP ${c.status} \u2014 ${l}`);return JSON.parse(l)}async submitScan(t,n){let r=et(t),i=on(n,r),o={...t,signature_hex:i},a=await this.request("/api/capsule/scan/submit",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(o)}),s=await a.text();if(!a.ok)throw new Error(`scan submit failed: HTTP ${a.status} \u2014 ${s}`);return JSON.parse(s)}async submitSeal(t,n){let{deployment_id:r,...i}=t,o=et(i),a=on(n,o),s={deployment_id:r,...i,signature_hex:a},c=await this.request("/api/capsule/seal/submit",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(s)}),l=await c.text();if(!c.ok)throw new Error(`seal submit failed: HTTP ${c.status} \u2014 ${l}`);return JSON.parse(l)}};var Uh=300*1e3,Vh=1440*60*1e3,cn=()=>Et(jc(),".nodata"),gr=()=>Et(cn(),"capsule.json"),Oc=()=>Et(cn(),"capsule-agents.json"),Lc=()=>Et(cn(),"capsule-key");function _r(e){try{return Fh(e)?JSON.parse(Kh(e,"utf8")):null}catch{return null}}function yr(e,t){Mh(cn(),{recursive:!0}),Hh(e,JSON.stringify(t,null,2)+`
|
|
120
|
+
`,{mode:384})}function ln(){return _r(gr())}function Gh(e){let t=Date.now(),n=_r(Oc())??{};n[e]=t;let r=Object.fromEntries(Object.entries(n).filter(([,i])=>t-i<Vh));return yr(Oc(),r),Object.keys(r).sort()}function br(){let t=(_r(Et(jc(),".claude","settings.json"))?.hooks?.PreToolUse??[]).flatMap(n=>n.hooks??[]).find(n=>n.command.includes("gate.mjs"))?.command;return t?t.includes("--block")?"block":"ask":null}function Bc(){return _r(Et(cn(),"consent.json"))?.terms_version??null}var sn=null;async function to(e){let t=ln();if(!t)return null;let n=Gh(e.agent()),r=new an(t.api_base);try{let i=await r.heartbeat({deployment_id:t.deployment_id,agent_version:`mcp-${e.version}`,applied_config:{scan_interval_minutes:sn?.scan_interval_minutes??1440,release_channel:sn?.release_channel??"stable",enabled_apps:sn?.enabled_apps??null,scan_scope:{surface:"mcp",host:mr(),agents:n,gate:br(),terms_version:Bc(),current_terms:ie}}},eo(Lc()));sn=i.desired_config??sn;let o={...t,last_heartbeat_ok_at:new Date().toISOString(),last_error:null,revoked:!!i.revoked};return yr(gr(),o),o}catch(i){let o={...t,last_error:i instanceof Error?i.message.slice(0,200):String(i)};return yr(gr(),o),o}}function no(e){if(!ln())return;let t=()=>{to(e)};setTimeout(t,3e3).unref(),setInterval(t,Uh).unref()}function Wh(e){if(!e)return"never";let t=Math.round((Date.now()-Date.parse(e))/6e4);return t<1?"just now":t<60?`${t} min ago`:`${Math.round(t/60)} h ago`}function Fc(e,t){e.registerTool("nodata_node",{description:`Register THIS MACHINE as a Capsule node of the organisation \u2014 so "this machine is guarded" is something the organisation can verify, not only the user. One node per machine; every agent here (Claude Code, Cursor \u2026) is a workload on it; billing stays per decision, a node is not a billing unit. Uses the Capsule agent's own enrolment and signed heartbeat. The heartbeat reports only: the host name, the agents' names, whether the read gate is on, and the accepted terms version \u2014 never content. ASKS FIRST: without confirm:true it shows the status, or what registering would send. Call with confirm:true only after the user approves.`,inputSchema:{confirm:Bh.boolean().optional().describe("true = register this machine. Omit to see status / preview.")}},async({confirm:n})=>{let r=ln();if(r){let f=await to(t);return{content:[{type:"text",text:[`CAPSULE NODE ${r.deployment_id} \u2014 org ${r.org_id} \xB7 ${t.who()}`,` last verified heartbeat: ${Wh(f?.last_heartbeat_ok_at)}${f?.last_error?` (last error: ${f.last_error})`:""}`,f?.revoked?" \u26A0 The organisation has paused this node.":"",` reported: host ${mr()}, agents, read gate ${br()??"off"}, terms ${Bc()??"not accepted"} \u2014 no content.`].filter(Boolean).join(`
|
|
121
|
+
`)}]}}if(!t.org)return{content:[{type:"text",text:"This machine has no enrolled device identity, so it cannot register as a node. Connect first with nodata_connect (it enrolls the device), restart, then run nodata_node again."}],isError:!0};if(!n)return{content:[{type:"text",text:[`PREVIEW \u2014 nothing registered yet. ${t.who()}`,`Register this machine (${mr()}) as a Capsule node of org ${t.org.id}:`," \xB7 a signing key is created in ~/.nodata/capsule-key (it never leaves this machine);"," \xB7 while an agent runs here, a signed heartbeat every 5 minutes reports: host name, the agents' names, read gate on/off, accepted terms version;"," \xB7 never file names, paths, findings or content;"," \xB7 the organisation sees the machine in its fleet, and can pause it.","A node is not a billing unit \u2014 billing stays per decision.","","Ask the user to approve, then call nodata_node again with confirm: true."].join(`
|
|
122
|
+
`)}]};let i=await t.org.token();if(!i)return{content:[{type:"text",text:"No usable org credential \u2014 run nodata_connect."}],isError:!0};let o=await fetch(`${t.org.baseUrl}/api/v1/tenants/${encodeURIComponent(t.org.id)}/capsule/install-token`,{method:"POST",headers:{authorization:`Bearer ${i}`}}),a=await o.json().catch(()=>({}));if(!o.ok||!a.install_token)return{content:[{type:"text",text:`Could not start registration (HTTP ${o.status}): ${a.error??"no install token"}`}],isError:!0};let s=eo(Lc()),l=await new an(t.org.baseUrl).enroll({install_token:a.install_token,pubkey_pem:s.publicKeyPem,agent_version:`mcp-${t.version}`,agent_kind:"npm_cli"});yr(gr(),{deployment_id:l.deployment_id,org_id:t.org.id,api_base:t.org.baseUrl,enrolled_at:new Date().toISOString()});let p=await to(t);no(t);let u=await t.ack(`node ${l.deployment_id} on ${mr()}`);return{content:[{type:"text",text:[`REGISTERED \u2014 this machine is Capsule node ${l.deployment_id} of org ${t.org.id}. ${t.who()}`,` first heartbeat: ${p?.last_heartbeat_ok_at?"verified":`failed (${p?.last_error??"unknown"})`}`," the status line now shows when NoData last verified this node.",`Approval kept in ~/.nodata/acks.jsonl${Ie(u)}.`].join(`
|
|
123
|
+
`)}]}})}import{z as dn}from"zod";import{spawn as zh}from"node:child_process";import{createHash as qh,randomBytes as Jh}from"node:crypto";import{existsSync as ro,mkdirSync as Xh,readFileSync as Yh,rmSync as Zh,statSync as Qh,writeFileSync as em}from"node:fs";import{homedir as Mc}from"node:os";import{join as Kc,resolve as tm}from"node:path";var fn=()=>Kc(Mc(),".nodata","secrets.json"),pn=64*1024,nm=600*1e3,rm=6;function im(){try{return ro(fn())?JSON.parse(Yh(fn(),"utf8")):null}catch{return null}}function om(e){return new Promise(t=>{let n=process.stdin;if(process.stderr.write(e),!n.isTTY){let o="";n.setEncoding("utf8"),n.on("data",a=>o+=a),n.on("end",()=>t(o.trim()));return}let r="";n.setRawMode(!0),n.resume(),n.setEncoding("utf8");let i=o=>{for(let a of o){if(a==="\r"||a===`
|
|
92
124
|
`)return n.setRawMode(!1),n.pause(),n.off("data",i),process.stderr.write(`
|
|
93
125
|
`),t(r.trim());a===""&&(n.setRawMode(!1),process.stderr.write(`
|
|
94
|
-
`),process.exit(130)),a==="\x7F"||a==="\b"?r=r.slice(0,-1):r+=a}};n.on("data",i)})}async function
|
|
95
|
-
`,{mode:384}),`\u2713 Saved to ~/.nodata/secrets.json (readable by you only)${r?` \xB7 project ${r}`:""}. The agent can now ask to run commands with these secrets \u2014 each one needs your approval.`):"\u2717 That is not a NoData CLI token (it starts with ndcs_). Nothing saved."}function
|
|
96
|
-
`+e.slice(-
|
|
97
|
-
`)+1)}};a.stdout.on("data",l),a.stderr.on("data",l);let
|
|
98
|
-
${
|
|
126
|
+
`),process.exit(130)),a==="\x7F"||a==="\b"?r=r.slice(0,-1):r+=a}};n.on("data",i)})}async function Hc(e,t){let n=e.indexOf("--project"),r=n>=0?e[n+1]??null:null,i=await om("Paste your NoData CLI token (ndcs_\u2026; Courier \u2192 \u{1F511} \u05E1\u05D5\u05D3\u05D5\u05EA \u2192 CLI token). It is not shown: ");return i.startsWith("ndcs_")?(Xh(Kc(Mc(),".nodata"),{recursive:!0}),em(fn(),JSON.stringify({token:i,base_url:t,project:r,saved_at:new Date().toISOString()},null,2)+`
|
|
127
|
+
`,{mode:384}),`\u2713 Saved to ~/.nodata/secrets.json (readable by you only)${r?` \xB7 project ${r}`:""}. The agent can now ask to run commands with these secrets \u2014 each one needs your approval.`):"\u2717 That is not a NoData CLI token (it starts with ndcs_). Nothing saved."}function Uc(){return ro(fn())?(Zh(fn()),"\u2713 Removed ~/.nodata/secrets.json. Revoke the token itself in Courier \u2192 \u{1F511} \u05E1\u05D5\u05D3\u05D5\u05EA if it may have leaked."):"No saved CLI token."}function am(e,t){let n=e,r=0,i=[];for(let[o,a]of Object.entries(t)){if(!a||a.length<rm)continue;let s=Buffer.from(a,"utf8");for(let c of new Set([a,s.toString("base64"),s.toString("base64url"),s.toString("hex"),encodeURIComponent(a),JSON.stringify(a).slice(1,-1)]))i.push([c,`[secret:${o}]`])}i.sort((o,a)=>a[0].length-o[0].length);for(let[o,a]of i){let s=n.split(o);s.length>1&&(r+=s.length-1,n=s.join(a))}for(let o of kn()){let a=new RegExp(o.pattern.source,o.pattern.flags.includes("g")?o.pattern.flags:o.pattern.flags+"g");n=n.replace(a,s=>s.startsWith("[secret")?s:(r++,`[secret:${o.id}]`))}return{text:n,blanked:r}}function sm(e){return e.length>pn?`\u2026 (${e.length-pn} earlier characters not shown)
|
|
128
|
+
`+e.slice(-pn):e}function cm(e,t,n,r){return new Promise(i=>{let o=Date.now(),a=zh(e,{cwd:t,env:n,shell:!0,stdio:["ignore","pipe","pipe"]}),s="",c=!1,l=u=>{if(s+=u.toString("utf8"),s.length>pn*32){let f=s.slice(-pn*16);s=f.slice(f.indexOf(`
|
|
129
|
+
`)+1)}};a.stdout.on("data",l),a.stderr.on("data",l);let p=setTimeout(()=>{c=!0,a.kill("SIGTERM")},r);a.on("error",u=>{clearTimeout(p),i({code:null,output:s+`
|
|
130
|
+
${u.message}`,timedOut:c,ms:Date.now()-o})}),a.on("close",u=>{clearTimeout(p),i({code:u,output:s,timedOut:c,ms:Date.now()-o})})})}async function lm(e,t){let n=await fetch(`${e.base_url}/api/secrets/pull`,{method:"POST",headers:{authorization:`Bearer ${e.token}`,"content-type":"application/json"},body:JSON.stringify(t?{projectLabel:t}:{})}),r=await n.json().catch(()=>({}));return n.ok?{secrets:r.secrets??{},project:r.project??t}:{error:`HTTP ${n.status}${r.error?` \u2014 ${r.error}`:""}`}}var un=new Map,dm=(e,t,n)=>qh("sha256").update(`${e}\0${t}\0${n??""}`).digest("hex");function Vc(e,t){let n=t.pull??lm;e.registerTool("nodata_run",{description:"Run a command on this machine (tests, a migration, a deploy script) WITH the project's secrets from the NoData vault as environment variables \u2014 without you seeing them. The secrets are pulled into memory only (no .env is written); you get back the exit code and the output with every secret value blanked. EVERY command needs the user's approval, as written: the user is asked directly when the client supports it; otherwise call without `approval` to get a preview and a code, show the user the exact command, and call again with the code only after they approve. Never embed a secret value in the command, never try to print or encode one, and never confirm on the user's behalf. Needs a CLI token saved once in the terminal: `npx -y @nodatachat/mcp secrets-login` \u2014 never ask for the token in the chat.",inputSchema:{command:dn.string().min(1).describe("The exact command line to run, e.g. `npm test`."),cwd:dn.string().optional().describe("Folder to run in. Default: the current folder."),project:dn.string().optional().describe("Secrets project label. Default: the token's project."),timeout_seconds:dn.number().int().min(5).max(1800).optional().describe("Default 300."),approval:dn.string().optional().describe("The code from the preview \u2014 only after the user approved this exact command.")}},async({command:r,cwd:i,project:o,timeout_seconds:a,approval:s})=>{let c=im();if(!c)return{content:[{type:"text",text:`No NoData CLI token on this machine. Ask the user to run, in their own terminal (not here):
|
|
99
131
|
npx -y @nodatachat/mcp secrets-login [--project <label>]
|
|
100
|
-
The token is minted in Courier \u2192 \u{1F511} \u05E1\u05D5\u05D3\u05D5\u05EA \u2192 CLI token. Never ask the user to paste it into the chat.`}],isError:!0};let l=
|
|
101
|
-
`),
|
|
102
|
-
${
|
|
103
|
-
|
|
104
|
-
A command that holds a secret can also send it out. Approve only a command you recognise.`,requestedSchema:{type:"object",properties:{}}})).action}catch(
|
|
105
|
-
`)}]}}
|
|
106
|
-
`)}],isError:
|
|
107
|
-
`,{mode:384})}
|
|
108
|
-
|
|
109
|
-
`).
|
|
110
|
-
`)}
|
|
111
|
-
`);function ec(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:zf.boolean().optional().describe("true = the user accepts these terms. Omit to show them.")}},async({confirm:i})=>{let o=Qn();if(!i){let s=er()?`Already accepted by ${o.agent} on ${o.accepted_at}${o.server_recorded?" (recorded at NoData)":" (recorded locally; NoData copy pending)"}.`:o?`Accepted version ${o.terms_version} earlier \u2014 the terms have changed and need accepting again.`:"Not accepted yet.";return{content:[{type:"text",text:`${eh(r)}
|
|
112
|
-
|
|
113
|
-
${s}
|
|
114
|
-
|
|
115
|
-
${Qf()}
|
|
116
|
-
|
|
117
|
-
Ask the user whether they accept, then call nodata_terms again with confirm: true.`}]}}let a=await Zf(t,n());return{content:[{type:"text",text:`ACCEPTED terms ${a.terms_version} \u2014 ${a.agent}${a.org?` \xB7 org ${a.org}`:""} \xB7 ${a.accepted_at}
|
|
118
|
-
local copy: ~/.nodata/consent.json \xB7 hash ${a.consent_hash.slice(0,16)}\u2026
|
|
119
|
-
`+(a.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.")+`
|
|
120
|
-
The data tools are on.`}]}})}function tc(e){let t=e,n=t.registerTool.bind(e);t.registerTool=(r,i,o)=>n(r,i,async(...a)=>{if(Yf.has(r)||er())return o(...a);let s=Qn();return{content:[{type:"text",text:(s?`NoData's terms changed (you accepted ${s.terms_version}; current is ${se}).`:"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 tr}from"zod";import De from"node:crypto";var ji=Buffer.from([78,68,67,49]),th=2,Bi=36,Zt=32,nh=64,rh=12,ih=16,oh=4096,ah=256,nc=32,Fi=8,sh=1;async function ch(){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 Li(e){let t=new Uint8Array(e.length);return t.set(e),t.buffer}async function lh(e,t){let n=t.trim();if(n.includes("-----BEGIN PUBLIC KEY-----")){let i=n.replace(/-----BEGIN PUBLIC KEY-----/,"").replace(/-----END PUBLIC KEY-----/,"").replace(/\s+/g,"");return e.kem.deserializePublicKey(Li(Buffer.from(i,"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(Li(r))}function dh(e){let t=De.createPublicKey({key:e,format:"pem"}).export({format:"der",type:"spki"});if(t.length<Zt)throw new Error("unexpected Ed25519 SPKI DER length");return t.subarray(t.length-Zt)}function uh(e){return De.createHash("sha256").update(e,"utf8").digest().subarray(0,Fi)}async function rc(e){let t=Buffer.from(e.filename,"utf8");if(t.length>oh)throw new Error("filename too long");let n=Buffer.from(e.contentType,"utf8");if(n.length>ah)throw new Error("content-type too long");let r=e.receiptId??De.randomUUID(),i=Buffer.from(r,"utf8");if(i.length!==Bi)throw new Error("receiptId must be a 36-char canonical UUID");let o=dh(e.issuerPubkeyPem);if(o.length!==Zt)throw new Error("issuer pubkey must be 32 bytes");let a=De.randomBytes(32),s=De.randomBytes(rh),c=De.createCipheriv("aes-256-gcm",a,s),l=Buffer.concat([c.update(e.fileBytes),c.final()]),u=c.getAuthTag();if(u.length!==ih)throw new Error("unexpected GCM tag length");let p=De.createHash("sha256").update(e.fileBytes).digest(),h=await ch(),f=await lh(h,e.recipientPubkeyB64),g=await h.createSenderContext({recipientPublicKey:f}),b=Buffer.from(g.enc),S=Buffer.from(await g.seal(Li(a))),v=uh(e.recipientPubkeyB64),w=1+Fi+2+b.length+2+S.length,y=ji.length+1+Bi+Zt+2+t.length+2+n.length+8+nc+w,_=Buffer.alloc(y),k=0;ji.copy(_,k),k+=ji.length,_[k++]=th,i.copy(_,k),k+=Bi,o.copy(_,k),k+=Zt,_.writeUInt16LE(t.length,k),k+=2,t.copy(_,k),k+=t.length,_.writeUInt16LE(n.length,k),k+=2,n.copy(_,k),k+=n.length,_.writeBigUInt64LE(BigInt(e.issuedAt??Date.now()),k),k+=8,p.copy(_,k),k+=nc,_[k++]=sh,v.copy(_,k),k+=Fi,_.writeUInt16LE(b.length,k),k+=2,b.copy(_,k),k+=b.length,_.writeUInt16LE(S.length,k),k+=2,S.copy(_,k),k+=S.length;let A=De.sign(null,_,e.issuerPrivateKey);if(A.length!==nh)throw new Error("header signature must be 64 bytes");let T=Buffer.concat([_,A,s,u,l]),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:v.toString("hex"),header_sig_b64:A.toString("base64"),content_key_b64:a.toString("base64")};return{ndcBytes:T,report:D}}import{createPrivateKey as ic,createPublicKey as oc,generateKeyPairSync as ph}from"node:crypto";import{existsSync as Ki,mkdirSync as fh,readFileSync as cc,rmSync as hh,statSync as nr,writeFileSync as lc}from"node:fs";import{homedir as ac}from"node:os";import{basename as Qt,extname as mh,join as Hi,resolve as gh}from"node:path";var ye=(e,t=!1)=>({content:[{type:"text",text:e}],...t?{isError:t}:{}}),en="mcp-archive",Mi=25,sc=25*1024*1024,yh={".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"},_h={critical:"restricted",high:"confidential",medium:"internal",low:"internal",info:"internal"};function dc(e,t){if(e){let i=ic({key:Buffer.from(e,"base64"),format:"der",type:"pkcs8"});return{privateKey:i,publicPem:oc(i).export({format:"pem",type:"spki"}),label:`device ${t??""}`.trim()}}let n=Hi(ac(),".nodata","issuer-ed25519.json");if(Ki(n)){let i=JSON.parse(cc(n,"utf8")).private_pem,o=ic(i);return{privateKey:o,publicPem:oc(o).export({format:"pem",type:"spki"}),label:"this machine"}}let r=ph("ed25519");return fh(Hi(ac(),".nodata"),{recursive:!0}),lc(n,JSON.stringify({private_pem:r.privateKey.export({format:"pem",type:"pkcs8"})},null,2)+`
|
|
121
|
-
`,{mode:384}),{privateKey:r.privateKey,publicPem:r.publicKey.export({format:"pem",type:"spki"}),label:"this machine"}}function uc(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:tr.string().describe("File or folder to wrap."),confirm:tr.boolean().optional().describe("true = wrap it. Omit to preview."),keep_local:tr.boolean().optional().describe("Also keep <file>.capsule.ndc next to the original. Default true."),remove:tr.boolean().optional().describe("Delete plaintext originals after upload. Default false.")}},async({path:i,confirm:o,keep_local:a,remove:s})=>{let c=gh(i);if(!Ki(c))return ye(`Not found: ${c}`,!0);let l;if(nr(c).isDirectory()?l=Fe(await kt({target_id:"mcp",target_label:Qt(c),target_path:c,log:St})).byFile.map(k=>({path:Hi(c,k.key),classification:_h[k.worst]??"internal"})):l=[{path:c,classification:"confidential"}],l=l.filter(_=>Ki(_.path)&&nr(_.path).isFile()&&!ke(_.path)),l.length===0)return ye(`Nothing to wrap in ${c} \u2014 no file with findings.`);let u=l.filter(_=>nr(_.path).size>sc);l=l.filter(_=>nr(_.path).size<=sc);let p=await t.get("/api/v1/recovery/pubkey");if(p.status===401||p.status===403)return ye(`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 ye(`Your organization has no master key yet \u2014 the 12-word recovery setup was not completed, so there is nothing to wrap to.
|
|
122
|
-
Finish it once in the console (Recovery setup), then wrap again. NoData never sees the words.`,!0);if(!o){let _=l.slice(0,Mi).map(k=>` \xB7 [${k.classification}] ${k.path}`);return l.length>Mi&&_.push(` \u2026 and ${l.length-Mi} more`),ye([`PREVIEW \u2014 nothing wrapped yet. ${r()}`,`Would wrap ${l.length} file(s) into the "${en}" capsule, sealed to your org master key (fingerprint ${p.body.fingerprint??"?"}):`,..._,u.length?`Skipped (over 25 MB): ${u.map(k=>Qt(k.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(`
|
|
123
|
-
`))}let f=await t.get("/api/v1/capsules");if(f.status>=400)return ye(`Could not list capsules (HTTP ${f.status}): ${JSON.stringify(f.body)}`,!0);let b=(f.body.capsules??[]).find(_=>_.slug===en);if(b&&b.key_mode!=="zk")return ye(`A "${en}" capsule exists but is not zero-knowledge (key_mode ${String(b.key_mode)}) \u2014 refusing to wrap into it.`,!0);if(!b){let _=await t.post("/api/v1/capsules",{handle:en,display_name:"MCP archive",key_mode:"zk",capsule_pubkey:h});if(_.status>=400)return ye(`Could not create the archive capsule (HTTP ${_.status}): ${JSON.stringify(_.body)}`,!0);b=_.body}let S=String(b.slug??b.capsule_id??"");if(!S)return ye(`Capsule id missing in ${JSON.stringify(b)}`,!0);let v=n(),w=[],y=[];for(let _ of l){let k=cc(_.path),{ndcBytes:A,report:T}=await rc({fileBytes:k,filename:Qt(_.path),contentType:yh[mh(_.path).toLowerCase()]??"application/octet-stream",recipientPubkeyB64:h,issuerPrivateKey:v.privateKey,issuerPubkeyPem:v.publicPem}),D=await t.post(`/api/v1/capsules/${encodeURIComponent(S)}/documents`,{title:Qt(_.path),ndc_b64:A.toString("base64"),classification:_.classification,plaintext_sha256:T.plaintext_sha256,size_bytes:T.size_bytes});if(D.status>=400||D.body.ok!==!0){y.push(` \u2717 ${_.path} \u2014 HTTP ${D.status}: ${JSON.stringify(D.body).slice(0,200)}`);continue}a!==!1&&lc(`${_.path}.capsule.ndc`,A,{mode:384}),s&&hh(_.path),w.push(` \u2713 [${_.classification}] ${Qt(_.path)}${D.body.proof_url?` proof: ${D.body.proof_url}`:""}`)}return ye([`WRAPPED ${w.length}/${l.length} into "${en}" \u2014 ${r()} \xB7 signed by ${v.label}`,...w,...y,"Sealed to your org master key: NoData stores ciphertext only and cannot open it. Your 12 words (or recovery file) open every document.",a!==!1?"Local copies: <file>.capsule.ndc next to each original.":"",s?"Plaintext originals deleted (only for files that uploaded).":""].filter(Boolean).join(`
|
|
124
|
-
`),y.length>0&&w.length===0)})}import{homedir as bc,hostname as vc}from"node:os";import{join as rr,resolve as Ui}from"node:path";import{existsSync as Wi,readFileSync as kc,writeFileSync as Sc,mkdirSync as wc,chmodSync as kh}from"node:fs";import{spawn as Sh}from"node:child_process";import{generateKeyPairSync as wh,createPrivateKey as Eh,sign as xh,randomBytes as Ah}from"node:crypto";var tn="1.3.10",Ec=rr(bc(),".nodata"),ir=rr(Ec,"credentials.json");function Th(){try{if(!Wi(ir))return null;let e=JSON.parse(kc(ir,"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 pc(e){wc(Ec,{recursive:!0});let t=JSON.stringify({...e,saved_at:new Date().toISOString()},null,2);Sc(ir,t,{mode:384});try{kh(ir,384)}catch{}}var Ph=`nodata-mcp v${tn} \u2014 NoData MCP server
|
|
132
|
+
The token is minted in Courier \u2192 \u{1F511} \u05E1\u05D5\u05D3\u05D5\u05EA \u2192 CLI token. Never ask the user to paste it into the chat.`}],isError:!0};let l=tm(i??process.cwd());if(!ro(l)||!Qh(l).isDirectory())return{content:[{type:"text",text:`No such folder: ${l}`}],isError:!0};let p=o??c.project??null,u=dm(r,l,p),f=[` command: ${r}`,` folder: ${l}`,` secrets: ${p?`project "${p}"`:"the token's secrets"} (values stay hidden from the agent)`].join(`
|
|
133
|
+
`),h;if(e.server.getClientCapabilities()?.elicitation){let x;try{x=(await e.server.elicitInput({message:`NoData \u2014 run this command with your secrets?
|
|
134
|
+
${f}
|
|
135
|
+
|
|
136
|
+
A command that holds a secret can also send it out. Approve only a command you recognise.`,requestedSchema:{type:"object",properties:{}}})).action}catch(m){return{content:[{type:"text",text:`NOT RUN \u2014 no approval was received from the user${m instanceof Error?` (${m.message.slice(0,80)})`:""}. ${t.who()}`}],isError:!0}}if(x!=="accept")return await t.ack(`declined \xB7 ${p??"token project"}`),{content:[{type:"text",text:`NOT RUN \u2014 the user did not approve. ${t.who()}`}]};h="user-dialog"}else{let x=Date.now();for(let[k,$]of un)x-$.at>nm&&un.delete(k);let m=s?un.get(s):void 0;if(!m||m.bind!==u){let k=Jh(4).toString("hex");return un.set(k,{bind:u,at:x}),{content:[{type:"text",text:[`PREVIEW \u2014 nothing run yet. ${t.who()}`,f,s?"(The code given does not match this exact command, or expired \u2014 a new one is below.)":"","",`Show the user this exact command. Only if they approve it, call nodata_run again with the same command, folder and project and approval: "${k}" (valid 10 minutes, once).`,"A command that holds a secret can also send it out \u2014 the user should approve only a command they recognise."].filter(Boolean).join(`
|
|
137
|
+
`)}]}}un.delete(s),h="code"}let _=await n(c,p);if("error"in _)return{content:[{type:"text",text:`Could not get the secrets (${_.error}). Nothing was run.`}],isError:!0};let y=Object.keys(_.secrets).sort(),v=await cm(r,l,{...process.env,..._.secrets},(a??300)*1e3),S=am(v.output,_.secrets),w=await t.ack(`${_.project??"token project"} \xB7 ${y.length} secrets \xB7 exit ${v.code??"none"}${v.timedOut?" (timed out)":""} \xB7 approved by ${h}`);return{content:[{type:"text",text:[`RAN with ${y.length} secret(s) from ${_.project?`project "${_.project}"`:"the token's secrets"} \u2014 ${t.who()}`,` exit ${v.code??"none"}${v.timedOut?" (stopped: timeout)":""} \xB7 ${(v.ms/1e3).toFixed(1)}s \xB7 ${S.blanked} secret value(s) blanked in the output`,y.length?` injected (names only): ${y.join(", ")}`:" no secrets were granted to this token \u2014 the command ran without any",`Approval kept in ~/.nodata/acks.jsonl${Ie(w)}; each released value has its own proof at NoData.`,"","\u2500\u2500 output (secret values blanked) \u2500\u2500",sm(S.text)||"(no output)"].join(`
|
|
138
|
+
`)}],isError:v.code!==0}})}var Gc=["\u{1F7E3}","\u{1F535}","\u{1F7E0}","\u{1F7E4}","\u{1F7E1}"];function um(e){let t=0;for(let n of e)t=t*31+n.codePointAt(0)>>>0;return Gc[t%Gc.length]}function io(e,t){let n=(e||"agent").toLowerCase().replace(/[^a-z0-9._-]+/g,"-").slice(0,40);return t?`${n}@${t}`:n}function Wc(e){return`${um(e)} ${e}`}import{z as vr}from"zod";import Be from"node:crypto";var oo=Buffer.from([78,68,67,49]),pm=2,ao=36,hn=32,fm=64,hm=12,mm=16,gm=4096,ym=256,zc=32,so=8,_m=1;async function bm(){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 co(e){let t=new Uint8Array(e.length);return t.set(e),t.buffer}async function vm(e,t){let n=t.trim();if(n.includes("-----BEGIN PUBLIC KEY-----")){let i=n.replace(/-----BEGIN PUBLIC KEY-----/,"").replace(/-----END PUBLIC KEY-----/,"").replace(/\s+/g,"");return e.kem.deserializePublicKey(co(Buffer.from(i,"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(co(r))}function km(e){let t=Be.createPublicKey({key:e,format:"pem"}).export({format:"der",type:"spki"});if(t.length<hn)throw new Error("unexpected Ed25519 SPKI DER length");return t.subarray(t.length-hn)}function wm(e){return Be.createHash("sha256").update(e,"utf8").digest().subarray(0,so)}async function qc(e){let t=Buffer.from(e.filename,"utf8");if(t.length>gm)throw new Error("filename too long");let n=Buffer.from(e.contentType,"utf8");if(n.length>ym)throw new Error("content-type too long");let r=e.receiptId??Be.randomUUID(),i=Buffer.from(r,"utf8");if(i.length!==ao)throw new Error("receiptId must be a 36-char canonical UUID");let o=km(e.issuerPubkeyPem);if(o.length!==hn)throw new Error("issuer pubkey must be 32 bytes");let a=Be.randomBytes(32),s=Be.randomBytes(hm),c=Be.createCipheriv("aes-256-gcm",a,s),l=Buffer.concat([c.update(e.fileBytes),c.final()]),p=c.getAuthTag();if(p.length!==mm)throw new Error("unexpected GCM tag length");let u=Be.createHash("sha256").update(e.fileBytes).digest(),f=await bm(),h=await vm(f,e.recipientPubkeyB64),_=await f.createSenderContext({recipientPublicKey:h}),y=Buffer.from(_.enc),v=Buffer.from(await _.seal(co(a))),S=wm(e.recipientPubkeyB64),w=1+so+2+y.length+2+v.length,x=oo.length+1+ao+hn+2+t.length+2+n.length+8+zc+w,m=Buffer.alloc(x),k=0;oo.copy(m,k),k+=oo.length,m[k++]=pm,i.copy(m,k),k+=ao,o.copy(m,k),k+=hn,m.writeUInt16LE(t.length,k),k+=2,t.copy(m,k),k+=t.length,m.writeUInt16LE(n.length,k),k+=2,n.copy(m,k),k+=n.length,m.writeBigUInt64LE(BigInt(e.issuedAt??Date.now()),k),k+=8,u.copy(m,k),k+=zc,m[k++]=_m,S.copy(m,k),k+=so,m.writeUInt16LE(y.length,k),k+=2,y.copy(m,k),k+=y.length,m.writeUInt16LE(v.length,k),k+=2,v.copy(m,k),k+=v.length;let $=Be.sign(null,m,e.issuerPrivateKey);if($.length!==fm)throw new Error("header signature must be 64 bytes");let b=Buffer.concat([m,$,s,p,l]),E={relative_path:"",plaintext_sha256:u.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:$.toString("base64"),content_key_b64:a.toString("base64")};return{ndcBytes:b,report:E}}import{createPrivateKey as Jc,createPublicKey as Xc,generateKeyPairSync as Sm}from"node:crypto";import{existsSync as uo,mkdirSync as Em,readFileSync as Qc,rmSync as xm,statSync as kr,writeFileSync as el}from"node:fs";import{homedir as Yc}from"node:os";import{basename as mn,extname as Am,join as po,resolve as Tm}from"node:path";var ve=(e,t=!1)=>({content:[{type:"text",text:e}],...t?{isError:t}:{}}),gn="mcp-archive",lo=25,Zc=25*1024*1024,Im={".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"},Pm={critical:"restricted",high:"confidential",medium:"internal",low:"internal",info:"internal"};function tl(e,t){if(e){let i=Jc({key:Buffer.from(e,"base64"),format:"der",type:"pkcs8"});return{privateKey:i,publicPem:Xc(i).export({format:"pem",type:"spki"}),label:`device ${t??""}`.trim()}}let n=po(Yc(),".nodata","issuer-ed25519.json");if(uo(n)){let i=JSON.parse(Qc(n,"utf8")).private_pem,o=Jc(i);return{privateKey:o,publicPem:Xc(o).export({format:"pem",type:"spki"}),label:"this machine"}}let r=Sm("ed25519");return Em(po(Yc(),".nodata"),{recursive:!0}),el(n,JSON.stringify({private_pem:r.privateKey.export({format:"pem",type:"pkcs8"})},null,2)+`
|
|
139
|
+
`,{mode:384}),{privateKey:r.privateKey,publicPem:r.publicKey.export({format:"pem",type:"spki"}),label:"this machine"}}function nl(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:vr.string().describe("File or folder to wrap."),confirm:vr.boolean().optional().describe("true = wrap it. Omit to preview."),keep_local:vr.boolean().optional().describe("Also keep <file>.capsule.ndc next to the original. Default true."),remove:vr.boolean().optional().describe("Delete plaintext originals after upload. Default false.")}},async({path:i,confirm:o,keep_local:a,remove:s})=>{let c=Tm(i);if(!uo(c))return ve(`Not found: ${c}`,!0);let l;if(kr(c).isDirectory()?l=Ue(await Rt({target_id:"mcp",target_label:mn(c),target_path:c,log:Dt})).byFile.map(k=>({path:po(c,k.key),classification:Pm[k.worst]??"internal"})):l=[{path:c,classification:"confidential"}],l=l.filter(m=>uo(m.path)&&kr(m.path).isFile()&&!Ae(m.path)),l.length===0)return ve(`Nothing to wrap in ${c} \u2014 no file with findings.`);let p=l.filter(m=>kr(m.path).size>Zc);l=l.filter(m=>kr(m.path).size<=Zc);let u=await t.get("/api/v1/recovery/pubkey");if(u.status===401||u.status===403)return ve(`Not authorized to read the org key (HTTP ${u.status}). Connect with nodata_connect.`,!0);let f=typeof u.body.pubkeyB64=="string"?u.body.pubkeyB64:null;if(!f)return ve(`Your organization has no master key yet \u2014 the 12-word recovery setup was not completed, so there is nothing to wrap to.
|
|
140
|
+
Finish it once in the console (Recovery setup), then wrap again. NoData never sees the words.`,!0);if(!o){let m=l.slice(0,lo).map(k=>` \xB7 [${k.classification}] ${k.path}`);return l.length>lo&&m.push(` \u2026 and ${l.length-lo} more`),ve([`PREVIEW \u2014 nothing wrapped yet. ${r()}`,`Would wrap ${l.length} file(s) into the "${gn}" capsule, sealed to your org master key (fingerprint ${u.body.fingerprint??"?"}):`,...m,p.length?`Skipped (over 25 MB): ${p.map(k=>mn(k.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(`
|
|
141
|
+
`))}let h=await t.get("/api/v1/capsules");if(h.status>=400)return ve(`Could not list capsules (HTTP ${h.status}): ${JSON.stringify(h.body)}`,!0);let y=(h.body.capsules??[]).find(m=>m.slug===gn);if(y&&y.key_mode!=="zk")return ve(`A "${gn}" capsule exists but is not zero-knowledge (key_mode ${String(y.key_mode)}) \u2014 refusing to wrap into it.`,!0);if(!y){let m=await t.post("/api/v1/capsules",{handle:gn,display_name:"MCP archive",key_mode:"zk",capsule_pubkey:f});if(m.status>=400)return ve(`Could not create the archive capsule (HTTP ${m.status}): ${JSON.stringify(m.body)}`,!0);y=m.body}let v=String(y.slug??y.capsule_id??"");if(!v)return ve(`Capsule id missing in ${JSON.stringify(y)}`,!0);let S=n(),w=[],x=[];for(let m of l){let k=Qc(m.path),{ndcBytes:$,report:b}=await qc({fileBytes:k,filename:mn(m.path),contentType:Im[Am(m.path).toLowerCase()]??"application/octet-stream",recipientPubkeyB64:f,issuerPrivateKey:S.privateKey,issuerPubkeyPem:S.publicPem}),E=await t.post(`/api/v1/capsules/${encodeURIComponent(v)}/documents`,{title:mn(m.path),ndc_b64:$.toString("base64"),classification:m.classification,plaintext_sha256:b.plaintext_sha256,size_bytes:b.size_bytes});if(E.status>=400||E.body.ok!==!0){x.push(` \u2717 ${m.path} \u2014 HTTP ${E.status}: ${JSON.stringify(E.body).slice(0,200)}`);continue}a!==!1&&el(`${m.path}.capsule.ndc`,$,{mode:384}),s&&xm(m.path),w.push(` \u2713 [${m.classification}] ${mn(m.path)}${E.body.proof_url?` proof: ${E.body.proof_url}`:""}`)}return ve([`WRAPPED ${w.length}/${l.length} into "${gn}" \u2014 ${r()} \xB7 signed by ${S.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.",a!==!1?"Local copies: <file>.capsule.ndc next to each original.":"",s?"Plaintext originals deleted (only for files that uploaded).":""].filter(Boolean).join(`
|
|
142
|
+
`),x.length>0&&w.length===0)})}import{homedir as dl,hostname as ul}from"node:os";import{join as wr,resolve as fo}from"node:path";import{existsSync as go,readFileSync as pl,writeFileSync as fl,mkdirSync as hl,chmodSync as Dm}from"node:fs";import{spawn as Cm}from"node:child_process";import{generateKeyPairSync as Nm,createPrivateKey as Om,sign as jm,randomBytes as Lm}from"node:crypto";var yn="1.3.15",ml=wr(dl(),".nodata"),Sr=wr(ml,"credentials.json");function Bm(){try{if(!go(Sr))return null;let e=JSON.parse(pl(Sr,"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 rl(e){hl(ml,{recursive:!0});let t=JSON.stringify({...e,saved_at:new Date().toISOString()},null,2);fl(Sr,t,{mode:384});try{Dm(Sr,384)}catch{}}var Fm=`nodata-mcp v${yn} \u2014 NoData MCP server
|
|
125
143
|
|
|
126
144
|
ADMIN mode: nodata-mcp --api-key sk_live_...
|
|
127
145
|
AGENT mode: nodata-mcp --grant-token ndca-...
|
|
@@ -131,18 +149,19 @@ Finish it once in the console (Recovery setup), then wrap again. NoData never se
|
|
|
131
149
|
nodata-mcp uninstall-gate
|
|
132
150
|
nodata-mcp secrets-login [--project <label>] save a secrets CLI token (typed here, never in the chat) for nodata_run
|
|
133
151
|
nodata-mcp secrets-logout
|
|
152
|
+
nodata-mcp lang he|en the language NoData and your agents use with you
|
|
134
153
|
|
|
135
154
|
Env vars: NODATA_API_KEY \xB7 NODATA_GRANT_TOKEN \xB7 NODATA_BASE_URL
|
|
136
155
|
Get a free API key: https://www.nodatacapsule.com/developers/get-started
|
|
137
|
-
Mint a grant token: POST /api/v1/governance/grant (or the nodata_grant tool).`;function
|
|
138
|
-
${t}`}],isError:!0}}function
|
|
139
|
-
`,{mode:384}),r}function
|
|
140
|
-
Ask the user to add them to that file themselves (not in this chat), then call this tool again.`}],isError:!0};let
|
|
141
|
-
`)}]}}let
|
|
142
|
-
`)}]}}),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:
|
|
156
|
+
Mint a grant token: POST /api/v1/governance/grant (or the nodata_grant tool).`;function ho(e){let t="",n="",r="https://www.nodatacapsule.com";for(let a=0;a<e.length;a++)e[a]==="--api-key"&&e[a+1]?t=e[++a]:e[a]==="--grant-token"&&e[a+1]?n=e[++a]:e[a]==="--base-url"&&e[a+1]?r=e[++a]:e[a]==="--help"||e[a]==="-h"?(console.log(Fm),process.exit(0)):e[a]==="--version"||e[a]==="-v"?(console.log(yn),process.exit(0)):e[a].startsWith("--")&&console.error(`nodata-mcp: unknown option '${e[a]}' (see --help)`);let i=t||n?"flag":"none";!t&&process.env.NODATA_API_KEY&&(t=process.env.NODATA_API_KEY,i="env"),!n&&process.env.NODATA_GRANT_TOKEN&&(n=process.env.NODATA_GRANT_TOKEN,i==="none"&&(i="env")),process.env.NODATA_BASE_URL&&(r=process.env.NODATA_BASE_URL);let o;if(!t&&!n){let a=Bm();a&&(!process.env.NODATA_BASE_URL&&r==="https://www.nodatacapsule.com"&&a.base_url&&(r=a.base_url),a.device?(o=a.device,i="stored"):a.api_key&&(t=a.api_key,i="stored"))}return r=r.replace(/\/+$/,""),{apiKey:t,grantToken:n,baseUrl:r,credentialSource:i,device:o}}var il=3e4;async function gl(e,t){let n;try{n=await fetch(e,{...t,signal:AbortSignal.timeout(il)})}catch(i){return{ok:!1,status:0,body:{error:i instanceof Error&&i.name==="TimeoutError"?`Request timed out after ${il/1e3}s: ${e}`:`Network error reaching ${e}: ${i instanceof Error?i.message:String(i)}`}}}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 _n(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 ol(e){return async()=>{let t=await _n(e);return"error"in t?null:t.token}}async function J(e,t,n,r){let i=await _n(t);return"error"in i?i.error:gl(`${e}${n}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${i.token}`},body:JSON.stringify(r)})}async function mo(e,t,n,r){let i=await _n(t);if("error"in i)return i.error;let o=new URL(`${e}${n}`);for(let[a,s]of Object.entries(r))s!==void 0&&s!==""&&o.searchParams.set(a,s);return gl(o.toString(),{method:"GET",headers:{Authorization:`Bearer ${i.token}`}})}function q(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}):
|
|
157
|
+
${t}`}],isError:!0}}function Mm(e){let t=e?[fo(e)]:[fo(".env.local"),fo(".env")];if(e&&!go(t[0]))return{error:`env file not found: ${t[0]}`};let n={},r=[];for(let o of t)if(go(o)){r.push(o);for(let a of pl(o,"utf8").split(/\r?\n/)){let s=a.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 i=o=>{for(let a of o){let s=n[a]??process.env[a];if(s)return{name:a,value:s}}};return{url:i(["SUPABASE_URL","NEXT_PUBLIC_SUPABASE_URL","VITE_SUPABASE_URL","EXPO_PUBLIC_SUPABASE_URL"]),anon:i(["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:i(["SUPABASE_JWT_SECRET","JWT_SECRET"]),files:r}}function Km(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 Hm=5*6e4;function Um(){let{publicKey:e,privateKey:t}=Nm("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 Vm(e,t){let n=Om({key:Buffer.from(e,"base64"),format:"der",type:"pkcs8"});return jm(null,Buffer.from(t,"utf8"),n).toString("base64")}function Gm(){let e=ul().toLowerCase().replace(/[^a-z0-9-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,20)||"device";return`${/^[a-z]/.test(e)?e:`d-${e}`}-${Lm(3).toString("hex")}`.slice(0,32)}async function Wm(e,t,n,r,i){let o=await J(e,t,"/api/v1/attest/devices",{handle:n,label:r,ed25519_pubkey_hex:i});if(o.ok){let a=o.body.org_id??"";return a?{ok:!0,orgId:a}:{ok:!1,status:o.status,error:"enroll response missing org_id"}}return{ok:!1,status:o.status,error:o.body?.error??`HTTP ${o.status}`}}async function zm(e,t){let n=await J(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:i}=n.body;if(!r||!i)throw new Error("challenge response malformed");let o=Vm(t.private_key_pkcs8_b64,r),a=await J(e,"","/api/v1/attest",{org_id:t.org_id,handle:t.handle,nonce:i,signature:o});if(!a.ok)throw new Error(`attest: ${a.body?.error??`HTTP ${a.status}`}`);let s=a.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 al(e,t){let n=null;return async()=>((!n||Date.now()>=n.expiresAtMs-Hm)&&(n=await zm(e,t)),n.token)}function qm(e,t){let n=wr(dl(),".nodata","approvals");hl(n,{recursive:!0});let r=wr(n,`${new Date().toISOString().replace(/[:.]/g,"-").slice(0,19)}-${e}.json`);return fl(r,JSON.stringify({kind:e,approved_at:new Date().toISOString(),...t},null,2)+`
|
|
158
|
+
`,{mode:384}),r}function Jm(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:g.string().describe("Your SQL table name"),encrypted_columns:g.array(g.string()).describe("Columns stored as <col>_ct/_iv/_tag triplets"),plaintext_columns:g.array(g.string()).optional().describe("Plaintext metadata/filter columns"),classification_column:g.string().optional().describe("Plaintext column carrying the classification value")}},async({table_name:i,encrypted_columns:o,plaintext_columns:a,classification_column:s})=>{let c=await J(t,n,"/api/v1/governance/tables",{table_name:i,encrypted_columns:o,plaintext_columns:a??[],classification_column:s});return q(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:g.array(g.string()).describe("Tables agents may read through this source"),env_file:g.string().optional().describe("Path to the env file holding the Supabase keys (default: .env.local, then .env in the working directory)"),source_url:g.string().optional().describe("Override the project URL (https://<ref>.supabase.co) if the env file lacks it")}},async({allowed_tables:i,env_file:o,source_url:a})=>{let s=Mm(o);if("error"in s)return{content:[{type:"text",text:`Error: ${s.error}`}],isError:!0};let c=a??s.url?.value,l=[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(l.length>0)return{content:[{type:"text",text:`Not sent. Missing in ${s.files.join(", ")||"the environment"}: ${l.join("; ")}.
|
|
159
|
+
Ask the user to add them to that file themselves (not in this chat), then call this tool again.`}],isError:!0};let p=await J(t,n,"/api/connector/secrets",{source_url:c,allowed_tables:i,anon_key:s.anon.value,jwt_secret:s.jwt.value}),u={read_from:s.files,variables_used:[s.url?.name,s.anon.name,s.jwt.name].filter(Boolean)};return q({...p,body:{...p.body,...u}})}),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:g.string().describe("Agent label (becomes its handle)"),tables:g.array(g.object({table:g.string(),columns:g.array(g.string()).describe("Columns the agent may read in this table"),where:g.record(g.string(),g.union([g.string(),g.number(),g.boolean()])).optional()})).optional().describe("Several tables for the same agent. When set, table/columns/where are ignored."),table:g.string().optional().describe("Single target table (default agent_demo_records)"),columns:g.array(g.string()).optional().describe("Columns the agent may read (single-table form)"),where:g.record(g.string(),g.union([g.string(),g.number(),g.boolean()])).optional().describe("Equality filter (plaintext cols only)"),classifications:g.array(g.string()).optional().describe("Allowed classification values; empty = no gating"),ttl_seconds:g.number().optional().describe("Token lifetime (default 30d, max 1y)"),confirm:g.boolean().optional().describe("true = grant it. Omit to preview the policy change.")}},async({agent:i,tables:o,table:a,columns:s,where:c,classifications:l,ttl_seconds:p,confirm:u})=>{let f={agent:i,...o?{tables:o}:{table:a??"agent_demo_records",columns:s,where:c},classifications:l,ttl_seconds:p};if(!u){let y=(o??[{table:a??"agent_demo_records",columns:s??[],where:c}]).map(S=>` \xB7 ${S.table}: ${(S.columns??[]).join(", ")||"(no columns)"}${S.where?` where ${JSON.stringify(S.where)}`:""}`),v=p?`${Math.round(p/86400*10)/10} days`:"30 days (default)";return{content:[{type:"text",text:[`POLICY CHANGE \u2014 PREVIEW, nothing granted yet. Requested by ${r()}`,`Agent "${i}" would be able to read ONLY:`,...y,`Classifications: ${l?.length?l.join(", "):"not gated"}`,`Valid for: ${v}. 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(`
|
|
160
|
+
`)}]}}let h=await J(t,n,"/api/v1/governance/grant",f);if(h.ok){let _=h.body,y=qm("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}});h.body.approval_copy=y}return q(h)}),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 i=await mo(t,n,"/api/v1/agents",{});if(!i.ok)return q(i);let a=i.body.agents??[],s=[`POLICY BOARD \u2014 ${r()}`,`${a.length} agent(s). Deny-by-default: no grant \u21D2 no access.`,""];for(let c of a){let l=c.scope,p=l?l.grants===0?"reaches nothing":`${l.tables_allowed.join(", ")||"(tables)"} \u2192 ${l.columns_allowed.join(", ")||"(no columns)"} \xB7 classifications: ${l.unrestricted_classifications?"not gated":l.classifications_allowed.join(", ")||"none"}`:"scope unavailable";s.push(` ${String(c.handle??c.name).padEnd(24)} ${String(c.status??"").padEnd(8)} ${p}`)}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(`
|
|
161
|
+
`)}]}}),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:g.string().optional().describe("Agent handle to revoke"),jti:g.string().optional().describe("Specific credential jti to revoke"),reason:g.string().optional()}},async({handle:i,jti:o,reason:a})=>{let s=await J(t,n,"/api/v1/governance/revoke",{handle:i,jti:o,reason:a});return q(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:g.string(),value:g.string(),context:g.string().optional()}},async({field:i,value:o,context:a})=>{let s={field:i,value:o};return a&&(s.context=a),q(await J(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:g.string(),field:g.string().optional(),requester:g.string().optional()}},async({ciphertext:i,field:o,requester:a})=>{let s={ciphertext:i};return o&&(s.field=o),a&&(s.requester=a),q(await J(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:g.string(),to:g.string().optional(),maxViews:g.number().optional(),ttl:g.string().optional(),burn:g.boolean().optional()}},async({content:i,to:o,maxViews:a,ttl:s,burn:c})=>{let l={content:i};return o&&(l.to=o),a!==void 0&&(l.maxViews=a),s&&(l.ttl=s),c!==void 0&&(l.burn=c),q(await J(t,n,"/api/v1/deliver",l))}),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:g.string().optional(),to:g.string().optional(),action:g.string().optional(),limit:g.number().optional()}},async({from:i,to:o,action:a,limit:s})=>{let c={from:i,to:o,action:a,limit:s!==void 0?String(s):void 0};return q(await mo(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:g.string().optional().describe("Fetch one proof by id"),surface:g.string().optional().describe("Filter, e.g. 'governance.grant', 'agent.read'"),decision:g.string().optional().describe("Filter: 'grant' | 'allow' | 'deny' | 'revoke'"),from:g.string().optional().describe("ISO timestamp"),to:g.string().optional().describe("ISO timestamp"),limit:g.number().optional().describe("1..1000, default 50")}},async({receipt_id:i,surface:o,decision:a,from:s,to:c,limit:l})=>q(await mo(t,n,"/api/v1/proofs",{receipt_id:i,surface:o,decision:a,from:s,to:c,limit:l!==void 0?String(l):void 0})))}function Xm(e,t,n){let r=Km(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:g.string().describe("Table to check (must be in your grant)"),columns:g.array(g.string()).describe("Columns you want to reach"),where:g.record(g.string(),g.union([g.string(),g.number(),g.boolean()])).optional().describe("Equality filter (readable columns only)")}},async({table:i,columns:o,where:a})=>{let s=await J(t,n,"/api/access/decide",{resource:{table:i,columns:o,where:a},intent:"read"});return q(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:g.string().describe("Table to retrieve from (must be in your grant)"),columns:g.array(g.string()).describe("Columns to include in context"),where:g.record(g.string(),g.union([g.string(),g.number(),g.boolean()])).optional(),top_k:g.number().optional().describe("Max rows (default 50, max 200)")}},async({table:i,columns:o,where:a,top_k:s})=>{let c=await J(t,n,"/api/access/retrieve",{resource:{table:i,columns:o,where:a},top_k:s});return q(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:g.string().describe("Table to read (must be in your grant)"),columns:g.array(g.string()).describe("Columns to read (must be in your grant)"),where:g.record(g.string(),g.union([g.string(),g.number(),g.boolean()])).optional(),limit:g.number().optional().describe("Max rows (default 50, max 200)")}},async({table:i,columns:o,where:a,limit:s})=>{if(!r)return{content:[{type:"text",text:"Error: could not derive agent handle from grant token."}],isError:!0};let c=await J(t,n,`/api/agents/${encodeURIComponent(r)}/read`,{table:i,columns:o,where:a,limit:s});return q(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:g.string().describe("Capability name to invoke (must be in your grant, e.g. 'deploy-prod')"),params:g.record(g.string(),g.unknown()).optional().describe("Allowlisted params; unknown keys are dropped server-side"),resource_key:g.string().optional().describe("Optional folder/resource the action targets (enforced against corpus scope)")}},async({capability:i,params:o,resource_key:a})=>{if(!r)return{content:[{type:"text",text:"Error: could not derive agent handle from grant token."}],isError:!0};let s=await J(t,n,`/api/agents/${encodeURIComponent(r)}/use`,{capability:i,params:o,resource_key:a});return q(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:g.string().describe("The code capsule to advise on (you must be granted on it)"),question:g.string().optional().describe("What to fix / improve, in natural language"),note:g.string().optional().describe("Extra context for the advisor"),error:g.object({message:g.string().optional(),stack:g.string().optional(),kind:g.string().optional()}).optional().describe("An error the code produced, to guide the fix"),steer:g.string().optional().describe("A steer on a refine turn (e.g. 'no, round half-up')"),prior_diff:g.string().optional().describe("The previously proposed diff, to refine")}},async({capsule_id:i,question:o,note:a,error:s,steer:c,prior_diff:l})=>{if(!r)return{content:[{type:"text",text:"Error: could not derive agent handle from grant token."}],isError:!0};let p=await J(t,n,`/api/agents/${encodeURIComponent(r)}/code-capsule/${encodeURIComponent(i)}/advise`,{question:o,note:a,error:s,steer:c,prior_diff:l});return q(p)}),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:g.string().describe("The code capsule to patch (you must be granted on it)"),summary:g.string().optional().describe("Short human-readable summary of the fix"),diff:g.string().optional().describe("A raw unified diff (advanced)"),replace:g.object({path:g.string(),content:g.string()}).optional().describe("Whole-file replacement; the diff is synthesized server-side against sealed source")}},async({capsule_id:i,summary:o,diff:a,replace:s})=>{if(!r)return{content:[{type:"text",text:"Error: could not derive agent handle from grant token."}],isError:!0};let c=await J(t,n,`/api/agents/${encodeURIComponent(r)}/code-capsule/${encodeURIComponent(i)}/patch`,{summary:o,diff:a,replace:s});return q(c)})}var sl=`WHAT NODATA DOES \u2014 in one line:
|
|
143
162
|
Give any agent real power over your data, without the power to leak it.
|
|
144
163
|
(Possession is not permission: it can hold the key and still not read what you didn't allow.)
|
|
145
|
-
`,
|
|
164
|
+
`,Ym=`TURN THE DATA TOOLS ON \u2014 3 steps, about a minute, once:
|
|
146
165
|
|
|
147
166
|
1. GET A KEY call nodata_connect (no arguments)
|
|
148
167
|
-> opens the signup in your browser: email + company (~30s), a 12-word
|
|
@@ -155,7 +174,7 @@ Ask the user to add them to that file themselves (not in this chat), then call t
|
|
|
155
174
|
3. ACTIVATE type /mcp (or restart Claude Code) so the tools load.
|
|
156
175
|
|
|
157
176
|
COMING BACK LATER? Nothing to redo \u2014 it starts ready. If the tools look missing, just /mcp.
|
|
158
|
-
`,
|
|
177
|
+
`,Zm=`YOUR WORKSPACE \u2014 say it in plain words; anything that changes files or policy asks you first:
|
|
159
178
|
|
|
160
179
|
1. SEE "scan <folder>" -> nodata_scan_folder: the whole result + a full HTML report,
|
|
161
180
|
on this machine, nothing uploads.
|
|
@@ -171,32 +190,32 @@ COMING BACK LATER? Nothing to redo \u2014 it starts ready. If the tools look mis
|
|
|
171
190
|
|
|
172
191
|
Database tables: nodata_register_table + nodata_connect_source, then nodata_grant.
|
|
173
192
|
One secret value: nodata_encrypt, hand it over once: nodata_deliver.
|
|
174
|
-
`,
|
|
193
|
+
`,Qm=`WHAT YOU CAN DO \u2014 scoped to your grant; you reach only what it allows, the rest never decrypts:
|
|
175
194
|
|
|
176
195
|
1. PLAN nodata_decide "may I reach X?" -> allow / partial / deny + a signed proof. No data moves.
|
|
177
196
|
2. PULL nodata_retrieve prompt-ready context, allowed fields only, with a receipt.
|
|
178
197
|
(nodata_read for raw governed rows.)
|
|
179
198
|
3. ACT nodata_use run a capability with a secret injected server-side \u2014 you never see it.
|
|
180
|
-
`,
|
|
199
|
+
`,cl=`STUCK? There's always a next step:
|
|
181
200
|
- Don't see the nodata_* tools? They load when the client starts \u2014 type /mcp or restart.
|
|
182
201
|
(Expected, not an error.)
|
|
183
202
|
- No MCP at all? The same governance runs from one curl, or the guided page:
|
|
184
203
|
https://www.nodatacapsule.com/developers/get-started
|
|
185
|
-
`;function
|
|
204
|
+
`;function ll(e){return e==="setup"?`You're connected to NoData \u2014 but there's NO key yet, so the data tools are still off.
|
|
186
205
|
|
|
187
206
|
`:e==="agent"?`You're connected to NoData, scoped to one grant token.
|
|
188
207
|
|
|
189
208
|
`:`You're connected to NoData (admin mode). You don't memorize commands \u2014 just ask in plain words.
|
|
190
209
|
|
|
191
|
-
`}function
|
|
210
|
+
`}function eg(e){return(e!=="agent"&&!Lt()?`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.
|
|
192
211
|
|
|
193
|
-
`:"")+
|
|
194
|
-
`+
|
|
195
|
-
`+
|
|
212
|
+
`:"")+tg(e)}function tg(e){if(e==="setup")return ll(e)+sl+`
|
|
213
|
+
`+Ym+`
|
|
214
|
+
`+cl;let t=e==="agent"?Qm:Zm;return ll(e)+sl+`
|
|
196
215
|
`+t+`
|
|
197
|
-
`+
|
|
216
|
+
`+cl}function ng(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:eg(t)}]}))}var rg="/capsule-api/register";function ig(e){let t=process.platform==="win32",n=process.platform==="darwin"?"open":t?"cmd":"xdg-open",r=t?["/c","start","",e]:[e];try{let i=Cm(n,r,{stdio:"ignore",detached:!0});return i.on("error",()=>{}),i.unref(),!0}catch{return!1}}function og(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:g.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 p=t+rg;return{content:[{type:"text",text:(ig(p)?`STEP 1 of 3 \u2014 opened the NoData signup in your browser:
|
|
198
217
|
`:`STEP 1 of 3 \u2014 open the NoData signup in your browser:
|
|
199
|
-
`)+
|
|
218
|
+
`)+p+`
|
|
200
219
|
|
|
201
220
|
There, about a minute:
|
|
202
221
|
- email + company (a personal email is fine for the sandbox)
|
|
@@ -206,16 +225,21 @@ There, about a minute:
|
|
|
206
225
|
STEP 2 \u2014 come back and call this tool again with the key:
|
|
207
226
|
nodata_connect api_key: "<the key you copied>"
|
|
208
227
|
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_).
|
|
209
|
-
Copy the key shown once on the signup page and try again: nodata_connect api_key: "ndp_\u2026".`}]};let{publicKeyHex:i,privateKeyPkcs8B64:o}=
|
|
228
|
+
Copy the key shown once on the signup page and try again: nodata_connect api_key: "ndp_\u2026".`}]};let{publicKeyHex:i,privateKeyPkcs8B64:o}=Um(),a=Gm(),s=ul()||"this device",c=await Wm(t,r,a,s,i);if(c.ok){try{rl({device:{org_id:c.orgId,handle:a,label:s,private_key_pkcs8_b64:o,public_key_hex:i},base_url:t})}catch(p){return{content:[{type:"text",text:"Enrolled the device, but couldn't save it locally: "+(p instanceof Error?p.message:String(p))}]}}return{content:[{type:"text",text:`STEP 2 done \u2014 this device is enrolled as "${s}" (${a}), and only its PRIVATE key is
|
|
210
229
|
saved at ~/.nodata/credentials.json (readable only by you). The org key you pasted was NOT
|
|
211
230
|
stored: every start now proves possession by signing a fresh challenge and gets a 15-minute token.
|
|
212
231
|
|
|
213
|
-
STEP 3 \u2014 type /mcp (or restart Claude Code) and the admin tools appear. Next time: nothing to do.`}]}}let l=c.status===404||c.status===0;try{
|
|
232
|
+
STEP 3 \u2014 type /mcp (or restart Claude Code) and the admin tools appear. Next time: nothing to do.`}]}}let l=c.status===404||c.status===0;try{rl({api_key:r,key_prefix:r.slice(0,12),base_url:t})}catch(p){return{content:[{type:"text",text:"Couldn't save locally: "+(p instanceof Error?p.message:String(p))+`
|
|
214
233
|
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:(l?`STEP 2 done \u2014 saved your key on this machine (device attestation isn't available on this
|
|
215
234
|
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.
|
|
216
235
|
|
|
217
|
-
STEP 3 \u2014 type /mcp (or restart Claude Code) and the admin tools appear. Next time: nothing to do.`}]}})}
|
|
218
|
-
|
|
219
|
-
`);return
|
|
220
|
-
|
|
221
|
-
|
|
236
|
+
STEP 3 \u2014 type /mcp (or restart Claude Code) and the admin tools appear. Next time: nothing to do.`}]}})}var ag=["NoData guards this machine's data files. For ANY work on a user's data file (xlsx, xls, csv, tsv, docx, pptx, pdf, json, txt \u2026), by default and without being asked:","1. Scan first \u2014 nodata_scan_folder (a file or a folder). Report counts, not values.","2. To clean, anonymise, redact, mask or share a file \u2014 use nodata_redact. Never write your own script for this: nodata_redact checks every hidden value against the copy, removes a copy that is not clean, and records a proof with a link.","3. Work, analyse and answer from the clean copy. Do not open the original directly; if the read gate asks, suggest the clean copy first.","4. After a scan, offer nodata_plan (a recommended policy the user approves) \u2014 locking what should be locked with nodata_protect.","5. On screen: totals, counts, groupings \u2014 never names, ID / policy / account numbers or other individual values unless the user explicitly asks."].join(`
|
|
237
|
+
`);function sg(){let e=br(),t=Lt(),n=ln(),r=[];return t||r.push("the terms are not accepted yet \u2014 data tools are held (offer nodata_terms)"),e||r.push("the read gate is off \u2014 offer that the user run `npx -y @nodatachat/mcp@latest install-gate` in their terminal, then restart"),st()||r.push("no language chosen \u2014 ask: \u05E2\u05D1\u05E8\u05D9\u05EA or English (nodata_terms takes `language`)"),[`NoData status on this machine: read gate ${e??"OFF"} \xB7 terms ${t?"accepted":"NOT accepted"} \xB7 language ${Te()}${st()?"":" (not chosen)"} \xB7 node ${n?"registered":"not registered"}.`,"At the START of your first reply in this session, tell the user in ONE short line that NoData guards their data files on this machine (scan, clean copy with proof, lock), and its status."+(r.length?` Then offer to turn on what is off: ${r.join("; ")}.`:" Everything is on \u2014 say so.")].join(`
|
|
238
|
+
`)}async function cg(){Cc();let e=process.argv[2];if(e==="gate")return _c(process.argv.slice(3));if(e==="install-gate"||e==="uninstall-gate"){let h=ho([]),_=h.device?al(h.baseUrl,h.device):h.apiKey||null,y=_?{baseUrl:h.baseUrl,org:h.device?.org_id??null,token:ol(_)}:null,v=process.argv.includes("--block"),S=e==="install-gate"?wc(new URL("./gate.js",import.meta.url),v):Sc(),w=await Bt(y,e==="install-gate"?"read-gate-install":"read-gate-uninstall",io("cli",h.device?.label),v?"block":"ask");process.stdout.write(S+(w?`
|
|
239
|
+
Recorded at NoData for your organisation (operational only)${typeof w=="string"?` \u2014 proof: ${w}`:""}.`:"")+`
|
|
240
|
+
`);return}if(e==="lang"){process.stdout.write(wa(process.argv[3])+`
|
|
241
|
+
`);return}if(e==="secrets-login"||e==="secrets-logout"){let h=e==="secrets-login"?await Hc(process.argv.slice(3),ho([]).baseUrl):Uc();process.stdout.write(h+`
|
|
242
|
+
`);return}let{apiKey:t,grantToken:n,baseUrl:r,credentialSource:i,device:o}=ho(process.argv.slice(2)),a=n?"agent":t||o?"admin":"setup",s=new $m({name:a==="agent"?"NoData (agent-scoped)":a==="setup"?"NoData (setup)":"NoData",version:yn},{instructions:[ka(),a==="agent"?"":sg(),a==="agent"?"":ag].filter(Boolean).join(`
|
|
243
|
+
|
|
244
|
+
`)}),c=()=>io(s.server.getClientVersion()?.name,o?.label),l=()=>`${Wc(c())} \xB7 `+(o?`device "${o.label}" (${o.handle}) \xB7 org ${o.org_id}`:t?`org key ${t.slice(0,12)}\u2026`:"not connected \u2014 local only"),p=o?al(r,o):t||null,u=p?{baseUrl:r,org:o?.org_id??null,token:ol(p)}:null;if(a!=="agent"&&(Ra(s,u,c,`${r}/terms`),Da(s),u&&$a(u)),a!=="agent"&&Fc(s,{version:yn,agent:c,who:l,org:o&&u?{id:o.org_id,baseUrl:r,token:u.token}:null,ack:h=>Bt(u,"capsule-node-register",c(),h)}),no({version:yn,agent:c}),p){Jm(s,r,p,l),dc(s,r,async()=>{let _=await _n(p);if("error"in _)throw new Error("no usable org credential \u2014 run nodata_connect");return _.token},l);let h=async(_,y,v)=>{let S=await _n(p);if("error"in S)return{status:401,body:{error:"no usable org credential \u2014 run nodata_connect"}};let w=await fetch(`${r}${y}`,{method:_,headers:{authorization:`Bearer ${S.token}`,...v?{"content-type":"application/json"}:{}},...v?{body:JSON.stringify(v)}:{}});return{status:w.status,body:await w.json().catch(()=>({}))}};nl(s,{get:_=>h("GET",_),post:(_,y)=>h("POST",_,y)},()=>tl(o?.private_key_pkcs8_b64,o?.label),l)}n&&Xm(s,r,n),ng(s,a),a!=="agent"&&Ga(s,l,h=>Bt(u,"policy-apply",c(),h)),a!=="agent"&&Vc(s,{who:l,ack:h=>Bt(u,"secrets-run",c(),h)}),a==="setup"?(og(s,r),console.error(`nodata-mcp: no credential given \u2014 running in setup mode (data tools disabled).
|
|
245
|
+
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.`):i==="stored"&&console.error("nodata-mcp: loaded saved credential from ~/.nodata/credentials.json (admin mode).");let f=new Rm;await s.connect(f)}cg().catch(e=>{console.error("Fatal error:",e),process.exit(1)});
|