@nodatachat/mcp 1.3.1 → 1.3.8
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 +61 -1
- package/dist/gate.js +18 -0
- package/dist/index.js +133 -74
- package/dist/status.js +2 -0
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,31 +1,31 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
/*! @nodatachat/mcp 1.3.
|
|
2
|
+
/*! @nodatachat/mcp 1.3.8 | 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:o,sealId:
|
|
7
|
-
`),o}});var Oe=N(Hn=>{"use strict";Object.defineProperty(Hn,"__esModule",{value:!0});var pt=class{static async generateKeyPair(){let t=await crypto.subtle.generateKey({name:"RSA-OAEP",modulusLength:4096,publicExponent:new Uint8Array([1,0,1]),hash:"SHA-256"},!0,["encrypt","decrypt"]),n=await crypto.subtle.exportKey("jwk",t.publicKey),r=await crypto.subtle.exportKey("jwk",t.privateKey);return{publicKeyJwk:n,privateKeyJwk:r}}static async encryptMessage(t,n){let r=await crypto.subtle.importKey("jwk",n,{name:"RSA-OAEP",hash:"SHA-256"},!1,["encrypt"]),o=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!0,["encrypt","decrypt"]),a=crypto.getRandomValues(new Uint8Array(12)),i=new TextEncoder().encode(t),s=await crypto.subtle.encrypt({name:"AES-GCM",iv:a,tagLength:128},o,i),c=await crypto.subtle.exportKey("raw",o),d=await crypto.subtle.encrypt({name:"RSA-OAEP"},r,c);return{encrypted_blob:this.arrayBufferToBase64(s),encrypted_aes_key:this.arrayBufferToBase64(d),iv:this.arrayBufferToBase64(a)}}static async decryptMessage(t,n){let r=await crypto.subtle.importKey("jwk",n,{name:"RSA-OAEP",hash:"SHA-256"},!1,["decrypt"]),o=this.base64ToArrayBuffer(t.encrypted_aes_key),a=await crypto.subtle.decrypt({name:"RSA-OAEP"},r,o),i=await crypto.subtle.importKey("raw",a,{name:"AES-GCM",length:256},!1,["decrypt"]),s=this.base64ToArrayBuffer(t.iv),c=this.base64ToArrayBuffer(t.encrypted_blob),d=await crypto.subtle.decrypt({name:"AES-GCM",iv:s,tagLength:128},i,c);return new TextDecoder().decode(d)}static async encryptFile(t,n){let r=await t.arrayBuffer(),o=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!0,["encrypt","decrypt"]),a=crypto.getRandomValues(new Uint8Array(12)),i=await crypto.subtle.encrypt({name:"AES-GCM",iv:a,tagLength:128},o,r),s=JSON.stringify({name:t.name,type:t.type,size:t.size,lastModified:t.lastModified}),c=crypto.getRandomValues(new Uint8Array(12)),d=await crypto.subtle.encrypt({name:"AES-GCM",iv:c,tagLength:128},o,new TextEncoder().encode(s)),u=await crypto.subtle.importKey("jwk",n,{name:"RSA-OAEP",hash:"SHA-256"},!1,["encrypt"]),p=await crypto.subtle.exportKey("raw",o),f=await crypto.subtle.encrypt({name:"RSA-OAEP"},u,p);return{encrypted_file:this.arrayBufferToBase64(i),encrypted_file_key:this.arrayBufferToBase64(f),iv:this.arrayBufferToBase64(a),encrypted_metadata:this.arrayBufferToBase64(d),metadata_iv:this.arrayBufferToBase64(c),encrypted_size:i.byteLength}}static async importKeyFromFragment(t){let n=t.replace(/-/g,"+").replace(/_/g,"/"),r=this.base64ToArrayBuffer(n.padEnd(Math.ceil(n.length/4)*4,"="));if(r.byteLength!==32)throw new Error("channel key must be 32 bytes");return crypto.subtle.importKey("raw",r,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}static async deriveKeyFromOTP(t,n,r="SHA-512"){let o=await crypto.subtle.importKey("raw",new TextEncoder().encode(t),"PBKDF2",!1,["deriveBits","deriveKey"]);return await crypto.subtle.deriveKey({name:"PBKDF2",salt:new TextEncoder().encode(n),iterations:31e4,hash:r},o,{name:"AES-GCM",length:256},!0,["encrypt","decrypt"])}static async encryptWithDerivedKey(t,n){let r=crypto.getRandomValues(new Uint8Array(12)),o=new TextEncoder().encode(t),a=await crypto.subtle.encrypt({name:"AES-GCM",iv:r,tagLength:128},n,o);return{encrypted:this.arrayBufferToBase64(a),iv:this.arrayBufferToBase64(r)}}static async decryptWithDerivedKey(t,n,r){let o=this.base64ToArrayBuffer(t),a=this.base64ToArrayBuffer(n),i=await crypto.subtle.decrypt({name:"AES-GCM",iv:a,tagLength:128},r,o);return new TextDecoder().decode(i)}static async sha256Hex(t){let n=t instanceof Uint8Array?t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength):t,r=await crypto.subtle.digest("SHA-256",n);return Array.from(new Uint8Array(r)).map(o=>o.toString(16).padStart(2,"0")).join("")}static async encryptFileWithDerivedKey(t,n){let r=await t.arrayBuffer(),o=await this.sha256Hex(r),a=crypto.getRandomValues(new Uint8Array(12)),i=await crypto.subtle.encrypt({name:"AES-GCM",iv:a,tagLength:128},n,r),s=JSON.stringify({name:t.name,type:t.type,size:t.size,lastModified:t.lastModified}),c=crypto.getRandomValues(new Uint8Array(12)),d=await crypto.subtle.encrypt({name:"AES-GCM",iv:c,tagLength:128},n,new TextEncoder().encode(s));return{encrypted_file:this.arrayBufferToBase64(i),iv:this.arrayBufferToBase64(a),encrypted_metadata:this.arrayBufferToBase64(d),metadata_iv:this.arrayBufferToBase64(c),encrypted_size:i.byteLength,plaintext_sha256:o,ciphertext_sha256:await this.sha256Hex(i)}}static async decryptFileBytesWithDerivedKey(t,n,r){let o=this.base64ToArrayBuffer(n);return crypto.subtle.decrypt({name:"AES-GCM",iv:o,tagLength:128},r,t)}static async decryptFileWithDerivedKey(t,n,r){let o=this.base64ToArrayBuffer(t),a=this.base64ToArrayBuffer(n);return crypto.subtle.decrypt({name:"AES-GCM",iv:a,tagLength:128},r,o)}static async deriveSeedKey(t,n="SHA-512"){let r=t.trim().toLowerCase(),o=await crypto.subtle.importKey("raw",new TextEncoder().encode(r),"PBKDF2",!1,["deriveBits","deriveKey"]);return await crypto.subtle.deriveKey({name:"PBKDF2",salt:new TextEncoder().encode(this.SEED_SALT),iterations:this.PBKDF2_ITERATIONS,hash:n},o,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}static async exportKeyWithSeed(t,n){let r=await crypto.subtle.exportKey("jwk",t),o=new TextEncoder().encode(JSON.stringify(r)),a=crypto.getRandomValues(new Uint8Array(12)),i=await crypto.subtle.encrypt({name:"AES-GCM",iv:a,tagLength:128},n,o),s=new Uint8Array(a.byteLength+i.byteLength);return s.set(a,0),s.set(new Uint8Array(i),a.byteLength),s.buffer}static async importKeyWithSeed(t,n){let r=new Uint8Array(t),o=r.slice(0,12),a=r.slice(12),i=await crypto.subtle.decrypt({name:"AES-GCM",iv:o,tagLength:128},n,a),s=new TextDecoder().decode(i),c=JSON.parse(s),d=await crypto.subtle.importKey("jwk",c,{name:"RSA-OAEP",hash:"SHA-256"},!0,["decrypt"]);return new Uint8Array(i).fill(0),d}static async hashPhone(t){let n=new TextEncoder().encode(t.replace(/\D/g,"")),r=await crypto.subtle.digest("SHA-256",n);return Array.from(new Uint8Array(r)).map(o=>o.toString(16).padStart(2,"0")).join("")}static arrayBufferToBase64(t){let n=new Uint8Array(t),r=32768,o=[];for(let a=0;a<n.length;a+=r)o.push(String.fromCharCode(...n.subarray(a,a+r)));return btoa(o.join(""))}static async encryptFileToBytesWithDerivedKey(t,n){let r=await t.arrayBuffer(),o=await this.sha256Hex(r),a=crypto.getRandomValues(new Uint8Array(12)),i=await crypto.subtle.encrypt({name:"AES-GCM",iv:a,tagLength:128},n,r),s=JSON.stringify({name:t.name,type:t.type,size:t.size,lastModified:t.lastModified}),c=crypto.getRandomValues(new Uint8Array(12)),d=await crypto.subtle.encrypt({name:"AES-GCM",iv:c,tagLength:128},n,new TextEncoder().encode(s));return{ciphertext:i,iv:this.arrayBufferToBase64(a),encrypted_metadata:this.arrayBufferToBase64(d),metadata_iv:this.arrayBufferToBase64(c),encrypted_size:i.byteLength,plaintext_sha256:o,ciphertext_sha256:await this.sha256Hex(i)}}static base64ToArrayBuffer(t){let n=atob(t),r=new Uint8Array(n.length);for(let o=0;o<n.length;o++)r[o]=n.charCodeAt(o);return r.buffer}static wipeFromMemory(t){new Uint8Array(t).fill(0)}};pt.PBKDF2_ITERATIONS=31e4;pt.SEED_SALT="NoDataChat-Seed-v1";Hn.default=pt});var _o=N(jt=>{"use strict";Object.defineProperty(jt,"__esModule",{value:!0});jt.solveProofOfWork=js;jt.verifyProofOfWork=Ms;function Ks(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 Ks(n)}async function js(e,t=4){if(t<1||t>16)throw new Error("Difficulty must be between 1 and 16");let n="0".repeat(t),r=0;for(;;){let o=e+r.toString(),a=await go(o);if(a.startsWith(n))return{nonce:r,hash:a};if(r++,r>2e9)throw new Error("Proof of work exceeded maximum attempts")}}async function Ms(e,t,n=4){if(n<1||n>16)return!1;let r="0".repeat(n),o=e+t.toString();return(await go(o)).startsWith(r)}});var Gn=N(Fe=>{"use strict";var Ls=Fe&&Fe.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(Fe,"__esModule",{value:!0});Fe.NoDataEmail=void 0;var ie=Ls(Oe()),Vn=class{static async seal(t,n,r,o,a,i={}){let{encrypt_subject:s=!0,ttl_hours:c=72,attachments:d=[]}=i,u=await ie.default.encryptMessage(o,a),p=r,f=!1;if(s){let b=await ie.default.encryptMessage(r,a);p=JSON.stringify(b),f=!0}let y=[];for(let b of d){let k=await ie.default.encryptFile(b,a);y.push({encrypted_file:k})}return{from_alias:t,to:n,subject:p,subject_encrypted:f,body:u,attachments:y,sealed_at:new Date().toISOString(),ttl_hours:c,envelope_id:crypto.randomUUID(),crypto_version:"0.2.0"}}static async open(t,n){let r=await ie.default.decryptMessage(t.body,n),o=t.subject;if(t.subject_encrypted){let i=JSON.parse(t.subject);o=await ie.default.decryptMessage(i,n)}let a=[];for(let i of t.attachments){let{encrypted_file:s}=i,c=ie.default.base64ToArrayBuffer(s.metadata_iv),d=ie.default.base64ToArrayBuffer(s.encrypted_metadata),u=ie.default.base64ToArrayBuffer(s.encrypted_file_key),p=await crypto.subtle.importKey("jwk",n,{name:"RSA-OAEP",hash:"SHA-256"},!1,["decrypt"]),f=await crypto.subtle.decrypt({name:"RSA-OAEP"},p,u),y=await crypto.subtle.importKey("raw",f,{name:"AES-GCM",length:256},!1,["decrypt"]),b=await crypto.subtle.decrypt({name:"AES-GCM",iv:c,tagLength:128},y,d),k=JSON.parse(new TextDecoder().decode(b)),S=ie.default.base64ToArrayBuffer(s.iv),_=ie.default.base64ToArrayBuffer(s.encrypted_file),v=await crypto.subtle.decrypt({name:"AES-GCM",iv:S,tagLength:128},y,_);a.push({filename:k.name,mime_type:k.type,data:v,size:k.size})}return{subject:o,body:r,attachments:a,sealed_at:t.sealed_at,ttl_hours:t.ttl_hours,envelope_id:t.envelope_id}}static isExpired(t){let r=new Date(t.sealed_at).getTime()+t.ttl_hours*60*60*1e3;return Date.now()>r}static toMimeBody(t,n){let r=JSON.stringify(t),o=btoa(unescape(encodeURIComponent(r)));return['Content-Type: multipart/mixed; boundary="nodata-boundary"',"","--nodata-boundary","Content-Type: text/html; charset=utf-8","",'<div style="font-family:system-ui;padding:24px;text-align:center">',"<h2>This email is encrypted with Capsule</h2>","<p>The sender used end-to-end encryption. To read this message:</p>",`<a href="${n}?env=${t.envelope_id}" `,'style="display:inline-block;padding:12px 24px;background:#000;color:#fff;','border-radius:8px;text-decoration:none;font-weight:600">',"Open Encrypted Email</a>",'<p style="color:#888;font-size:12px;margin-top:16px">',"Powered by Capsule — Nothing is ever stored. Ever.</p>","</div>","--nodata-boundary",'Content-Type: application/x-nodata-envelope; name="envelope.nodata"',"Content-Transfer-Encoding: base64",'Content-Disposition: attachment; filename="envelope.nodata"',"",o,"--nodata-boundary--"].join(`\r
|
|
8
|
-
`)}};Fe.NoDataEmail=Vn});var Jn=N(Ue=>{"use strict";var Fs=Ue&&Ue.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(Ue,"__esModule",{value:!0});Ue.NoDataWebhook=void 0;var qn=Fs(Oe()),Wn=class{static async encrypt(t,n,r,o){let{event_type:a,source:i,ttl_seconds:s=3600}=o,c=JSON.stringify(t),d=await qn.default.encryptMessage(c,n),u=new Date().toISOString(),p=crypto.randomUUID(),f=`${p}.${u}.${d.encrypted_blob}`,y=await this.hmacSign(f,r);return{encrypted_event:d,event_type:a,source:i,signature:y,timestamp:u,delivery_id:p,ttl_seconds:s,crypto_version:"0.2.0"}}static async verify(t,n){let r=`${t.delivery_id}.${t.timestamp}.${t.encrypted_event.encrypted_blob}`,o=await this.hmacSign(r,n),a=new TextEncoder().encode(t.signature),i=new TextEncoder().encode(o),s=a.length^i.length,c=Math.min(a.length,i.length);for(let y=0;y<c;y++)s|=a[y]^i[y];let d=s===0,p=new Date(t.timestamp).getTime()+t.ttl_seconds*1e3,f=Date.now()>p;return{valid:d,expired:f,event_type:t.event_type,source:t.source,delivery_id:t.delivery_id}}static async decrypt(t,n){let r=await qn.default.decryptMessage(t.encrypted_event,n);return JSON.parse(r)}static async verifyAndDecrypt(t,n,r){let o=await this.verify(t,r);if(!o.valid)throw new Error(`[NoDataWebhook] Invalid signature for delivery ${o.delivery_id}`);if(o.expired)throw new Error(`[NoDataWebhook] Payload expired for delivery ${o.delivery_id}`);return{data:await this.decrypt(t,n),delivery_id:o.delivery_id,event_type:o.event_type}}static async hmacSign(t,n){let r=await crypto.subtle.importKey("raw",new TextEncoder().encode(n),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),o=await crypto.subtle.sign("HMAC",r,new TextEncoder().encode(t));return qn.default.arrayBufferToBase64(o)}};Ue.NoDataWebhook=Wn});var Yn=N(He=>{"use strict";var Us=He&&He.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(He,"__esModule",{value:!0});He.NoDataSystems=void 0;var Mt=Us(Oe()),zn=class{static async encryptRecord(t,n,r,o,a,i){let s=[],c={};for(let[d,u]of Object.entries(r))if(o.sensitive.includes(d)){let p=typeof u=="string"?u:JSON.stringify(u),f=await Mt.default.encryptMessage(p,a),y=await this.hashValue(p);s.push({value:f,search_hash:y,field_name:d,encrypted_at:new Date().toISOString()})}else c[d]=u;return{record_id:t,record_type:n,encrypted_fields:s,clear_fields:c,encrypted_by:i,created_at:new Date().toISOString(),crypto_version:"0.2.0"}}static async decryptRecord(t,n){let r={...t.clear_fields};for(let o of t.encrypted_fields){let a=await Mt.default.decryptMessage(o.value,n);try{r[o.field_name]=JSON.parse(a)}catch{r[o.field_name]=a}}return{record_id:t.record_id,record_type:t.record_type,fields:r,created_at:t.created_at}}static async searchByHash(t,n,r){let o=await this.hashValue(r);return t.filter(a=>a.encrypted_fields.some(i=>i.field_name===n&&i.search_hash===o))}static async encryptField(t,n,r){let o=typeof n=="string"?n:JSON.stringify(n),a=await Mt.default.encryptMessage(o,r),i=await this.hashValue(o);return{value:a,search_hash:i,field_name:t,encrypted_at:new Date().toISOString()}}static async decryptField(t,n){let r=await Mt.default.decryptMessage(t.value,n);try{return JSON.parse(r)}catch{return r}}static createSchema(t,n){return{sensitive:n,clear:t.filter(r=>!n.includes(r))}}static async hashValue(t){let n=`nodatachat:field:${t}`,r=new TextEncoder().encode(n),o=await crypto.subtle.digest("SHA-256",r);return Array.from(new Uint8Array(o)).map(a=>a.toString(16).padStart(2,"0")).join("")}};He.NoDataSystems=zn});var Zn=N(Ve=>{"use strict";var Hs=Ve&&Ve.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(Ve,"__esModule",{value:!0});Ve.NoDataForms=void 0;var se=Hs(Oe()),Xn=class{static async encryptSubmission(t,n,r,o,a={}){let{ttl_hours:i=0,view_once:s=!1,attachments:c=[]}=a,d={},u={};for(let S of n)S.sensitive!==!1?d[S.name]=S.value:u[S.name]=S.value;let p=JSON.stringify(n.map(S=>({name:S.name,value:S.value}))),f=await this.sha256(p),y=await se.default.encryptMessage(JSON.stringify(d),r),b=[];for(let S of c){let _=await se.default.encryptFile(S,r);b.push(_)}let k=n.map(S=>S.name);return{submission_id:crypto.randomUUID(),form_id:t,encrypted_fields:y,clear_fields:u,attachments:b,integrity_hash:f,field_order:k,submitter_id:o,submitted_at:new Date().toISOString(),ttl_hours:i,view_once:s,crypto_version:"0.2.0"}}static async decryptSubmission(t,n){let r=await se.default.decryptMessage(t.encrypted_fields,n),o=JSON.parse(r),a={...t.clear_fields,...o},s=(t.field_order||Object.keys(a).sort()).map(p=>({name:p,value:a[p]})),d=await this.sha256(JSON.stringify(s))===t.integrity_hash,u=[];for(let p of t.attachments){let f=await crypto.subtle.importKey("jwk",n,{name:"RSA-OAEP",hash:"SHA-256"},!1,["decrypt"]),y=await crypto.subtle.decrypt({name:"RSA-OAEP"},f,se.default.base64ToArrayBuffer(p.encrypted_file_key)),b=await crypto.subtle.importKey("raw",y,{name:"AES-GCM",length:256},!1,["decrypt"]),k=await crypto.subtle.decrypt({name:"AES-GCM",iv:se.default.base64ToArrayBuffer(p.metadata_iv),tagLength:128},b,se.default.base64ToArrayBuffer(p.encrypted_metadata)),S=JSON.parse(new TextDecoder().decode(k)),_=await crypto.subtle.decrypt({name:"AES-GCM",iv:se.default.base64ToArrayBuffer(p.iv),tagLength:128},b,se.default.base64ToArrayBuffer(p.encrypted_file));u.push({filename:S.name,mime_type:S.type,data:_,size:S.size})}return{submission_id:t.submission_id,form_id:t.form_id,fields:a,attachments:u,integrity_valid:d,submitted_at:t.submitted_at}}static isExpired(t){if(t.ttl_hours===0)return!1;let r=new Date(t.submitted_at).getTime()+t.ttl_hours*60*60*1e3;return Date.now()>r}static async encryptGrade(t,n,r,o,a=0){let i=await se.default.encryptMessage(JSON.stringify(t),n),s=await this.sha256(`nodatachat:student:${t.student_id}`);return{encrypted_grade:i,student_hash:s,course_id:r,term:o,delivery_id:crypto.randomUUID(),delivered_at:new Date().toISOString(),ttl_hours:a,crypto_version:"0.2.0"}}static async decryptGrade(t,n){let r=await se.default.decryptMessage(t.encrypted_grade,n);return JSON.parse(r)}static async sha256(t){let n=new TextEncoder().encode(t),r=await crypto.subtle.digest("SHA-256",n);return Array.from(new Uint8Array(r)).map(o=>o.toString(16).padStart(2,"0")).join("")}};Ve.NoDataForms=Xn});var bo=N(Ge=>{"use strict";var Vs=Ge&&Ge.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(Ge,"__esModule",{value:!0});Ge.NoDataSDK=void 0;var Lt=Vs(Oe()),_e=Gn(),be=Jn(),Q=Yn(),ce=Zn(),Qn=class{static async init(t={}){let n;return t.keyPair?n=t.keyPair:(n=await Lt.default.generateKeyPair(),t.onKeysGenerated&&await t.onKeysGenerated(n)),{publicKey:n.publicKeyJwk,email:{seal:_e.NoDataEmail.seal.bind(_e.NoDataEmail),open:_e.NoDataEmail.open.bind(_e.NoDataEmail),isExpired:_e.NoDataEmail.isExpired.bind(_e.NoDataEmail),toMimeBody:_e.NoDataEmail.toMimeBody.bind(_e.NoDataEmail)},webhook:{encrypt:be.NoDataWebhook.encrypt.bind(be.NoDataWebhook),verify:be.NoDataWebhook.verify.bind(be.NoDataWebhook),decrypt:be.NoDataWebhook.decrypt.bind(be.NoDataWebhook),verifyAndDecrypt:be.NoDataWebhook.verifyAndDecrypt.bind(be.NoDataWebhook)},systems:{encryptRecord:Q.NoDataSystems.encryptRecord.bind(Q.NoDataSystems),decryptRecord:Q.NoDataSystems.decryptRecord.bind(Q.NoDataSystems),searchByHash:Q.NoDataSystems.searchByHash.bind(Q.NoDataSystems),encryptField:Q.NoDataSystems.encryptField.bind(Q.NoDataSystems),decryptField:Q.NoDataSystems.decryptField.bind(Q.NoDataSystems),createSchema:Q.NoDataSystems.createSchema.bind(Q.NoDataSystems)},forms:{encryptSubmission:ce.NoDataForms.encryptSubmission.bind(ce.NoDataForms),decryptSubmission:ce.NoDataForms.decryptSubmission.bind(ce.NoDataForms),isExpired:ce.NoDataForms.isExpired.bind(ce.NoDataForms),encryptGrade:ce.NoDataForms.encryptGrade.bind(ce.NoDataForms),decryptGrade:ce.NoDataForms.decryptGrade.bind(ce.NoDataForms)},crypto:Lt.default}}static async quickEncrypt(t,n){let r=typeof t=="string"?t:JSON.stringify(t),o=await Lt.default.encryptMessage(r,n);return JSON.stringify(o)}static async quickDecrypt(t,n){let r=JSON.parse(t),o=await Lt.default.decryptMessage(r,n);try{return JSON.parse(o)}catch{return o}}};Ge.NoDataSDK=Qn});var So=N(ee=>{"use strict";Object.defineProperty(ee,"__esModule",{value:!0});ee.NoDataSDK=ee.NoDataForms=ee.NoDataSystems=ee.NoDataWebhook=ee.NoDataEmail=void 0;var Gs=Gn();Object.defineProperty(ee,"NoDataEmail",{enumerable:!0,get:function(){return Gs.NoDataEmail}});var qs=Jn();Object.defineProperty(ee,"NoDataWebhook",{enumerable:!0,get:function(){return qs.NoDataWebhook}});var Ws=Yn();Object.defineProperty(ee,"NoDataSystems",{enumerable:!0,get:function(){return Ws.NoDataSystems}});var Js=Zn();Object.defineProperty(ee,"NoDataForms",{enumerable:!0,get:function(){return Js.NoDataForms}});var zs=bo();Object.defineProperty(ee,"NoDataSDK",{enumerable:!0,get:function(){return zs.NoDataSDK}})});var We=N(D=>{"use strict";Object.defineProperty(D,"__esModule",{value:!0});D.PQ_SIZES=D.NDC_WIRE_V03=D.NDC_WIRE_V1=D.NDC_V03_RATCHET_DOMAIN=D.NDC_V03_CONTENT_KEY_DOMAIN=D.NDC_V03_KEM_DOMAIN=D.PQ_SUITE=void 0;D.generateHybridKemKeypair=Ys;D.deriveHybridKemKeypairFromSeed=Xs;D.hybridKemEncapsulate=Zs;D.hybridKemDecapsulate=Qs;D.deriveContentKey=ec;D.ratchetAdvance=tc;D.generateHybridSigKeypair=nc;D.hybridSign=rc;D.hybridVerify=oc;D.generateMlDsa65Keypair=ac;D.mlDsa65SignDetached=ic;D.mlDsa65VerifyDetached=sc;var Se=T("@noble/curves/ed25519.js"),ft=T("@noble/hashes/sha2.js"),ht=T("@noble/hashes/hkdf.js"),Ft=T("@noble/post-quantum/ml-kem.js"),qe=T("@noble/post-quantum/ml-dsa.js");D.PQ_SUITE={KEM:"X25519+ML-KEM-768",SIG:"Ed25519+ML-DSA-65",AEAD:"AES-256-GCM",KDF:"HKDF-SHA-256"};D.NDC_V03_KEM_DOMAIN="NDC-v0.3-hybrid-kem";D.NDC_V03_CONTENT_KEY_DOMAIN="NDC-v0.3-content-key";D.NDC_V03_RATCHET_DOMAIN="NDC-ratchet";D.NDC_WIRE_V1=1;D.NDC_WIRE_V03=2;function wo(...e){let t=0;for(let o of e)t+=o.length;let n=new Uint8Array(t),r=0;for(let o of e)n.set(o,r),r+=o.length;return n}function yt(e){return new TextEncoder().encode(e)}function vo(e,t,n,r){let o=wo(e,t),a=wo(yt(D.NDC_V03_KEM_DOMAIN),n,r);return(0,ht.hkdf)(ft.sha256,o,new Uint8Array(0),a,32)}function Ys(){let{secretKey:e,publicKey:t}=Se.x25519.keygen(),{publicKey:n,secretKey:r}=Ft.ml_kem768.keygen();return{publicKey:{x25519:t,mlKem:n},secretKey:{x25519:e,mlKem:r}}}function Xs(e){if(e.length<32)throw new Error("seed too short (need >=32 bytes)");let t=(0,ht.hkdf)(ft.sha256,e,new Uint8Array(0),yt("ndc-hybrid-kem-x25519-v1"),32),n=(0,ht.hkdf)(ft.sha256,e,new Uint8Array(0),yt("ndc-hybrid-kem-mlkem768-v1"),64),r=Se.x25519.getPublicKey(t),{publicKey:o,secretKey:a}=Ft.ml_kem768.keygen(n);return{publicKey:{x25519:r,mlKem:o},secretKey:{x25519:t,mlKem:a}}}function Zs(e){let{secretKey:t,publicKey:n}=Se.x25519.keygen(),r=Se.x25519.getSharedSecret(t,e.x25519),{cipherText:o,sharedSecret:a}=Ft.ml_kem768.encapsulate(e.mlKem),i=vo(a,r,n,e.x25519);return{ciphertext:{ctClassical:n,ctPq:o},sharedSecret:i,ephemeralX25519Pk:n}}function Qs(e,t,n){let r=Se.x25519.getSharedSecret(e.x25519,n.ctClassical),o=Ft.ml_kem768.decapsulate(n.ctPq,e.mlKem);return vo(o,r,n.ctClassical,t)}function ec(e){return(0,ht.hkdf)(ft.sha256,e,new Uint8Array(0),yt(D.NDC_V03_CONTENT_KEY_DOMAIN),32)}function tc(e,t){return(0,ht.hkdf)(ft.sha256,e,t,yt(D.NDC_V03_RATCHET_DOMAIN),32)}function nc(){let{secretKey:e,publicKey:t}=Se.ed25519.keygen(),{publicKey:n,secretKey:r}=qe.ml_dsa65.keygen();return{publicKey:{ed25519:t,mlDsa:n},secretKey:{ed25519:e,mlDsa:r}}}function rc(e,t){return{ed25519:Se.ed25519.sign(t,e.ed25519),mlDsa:qe.ml_dsa65.sign(t,e.mlDsa)}}function oc(e,t,n){return Se.ed25519.verify(n.ed25519,t,e.ed25519)?qe.ml_dsa65.verify(n.mlDsa,t,e.mlDsa):!1}function ac(){let{publicKey:e,secretKey:t}=qe.ml_dsa65.keygen();return{publicKey:e,secretKey:t}}function ic(e,t){return qe.ml_dsa65.sign(t,e)}function sc(e,t,n){return qe.ml_dsa65.verify(n,t,e)}D.PQ_SIZES={X25519_PK:32,X25519_SK:32,ML_KEM_768_PK:1184,ML_KEM_768_SK:2400,ML_KEM_768_CT:1088,ED25519_PK:32,ED25519_SK:32,ED25519_SIG:64,ML_DSA_65_PK:1952,ML_DSA_65_SK:4032,ML_DSA_65_SIG:3309,HYBRID_SHARED_SECRET:32}});var Ht=N(O=>{"use strict";Object.defineProperty(O,"__esModule",{value:!0});O.deriveContentKey=O.ContainerV3Error=O.CONTAINER_HEADER_MAX_BYTES=O.CONTAINER_FIXED_PREFIX_BYTES=O.CONTAINER_MAGIC=void 0;O.canonicalJson=Ut;O.headerSigningBytes=er;O.signContainerHeader=Ao;O.verifyContainerHeader=To;O.encodeContainerV3=Po;O.decodeContainerV3=Do;O.sealHybrid=fc;O.openHybrid=hc;var cc=T("@noble/hashes/hkdf.js"),lc=T("@noble/hashes/sha2.js"),j=We();Object.defineProperty(O,"deriveContentKey",{enumerable:!0,get:function(){return j.deriveContentKey}});O.CONTAINER_MAGIC=new Uint8Array([78,68,76,66]);O.CONTAINER_FIXED_PREFIX_BYTES=8;O.CONTAINER_HEADER_MAX_BYTES=16777215;var dc="NDC-v0.3-wrap-key",L=class extends Error{constructor(t,n){super(n),this.name="ContainerV3Error",this.code=t}};O.ContainerV3Error=L;var fe=e=>{if(typeof Buffer<"u")return Buffer.from(e).toString("base64");let t="";for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return btoa(t)},Ie=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},xo=e=>{let t="";for(let n=0;n<e.length;n++)t+=e[n].toString(16).padStart(2,"0");return t};function Ut(e){if(e===null||typeof e!="object")return JSON.stringify(e);if(Array.isArray(e))return"["+e.map(Ut).join(",")+"]";let t=e;return"{"+Object.keys(t).sort().map(r=>JSON.stringify(r)+":"+Ut(t[r])).join(",")+"}"}function er(e){let t={...e};return delete t.sig,new TextEncoder().encode(Ut(t))}function Ao(e,t,n){let r=(0,j.hybridSign)(n.secretKey,er(e));return{...e,sig:{signer_kid:t,ed25519:fe(r.ed25519),ml_dsa_65:fe(r.mlDsa)}}}function To(e,t){let n={ed25519:Ie(e.sig.ed25519),mlDsa:Ie(e.sig.ml_dsa_65)};return(0,j.hybridVerify)(t,er(e),n)}var uc=["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 pc(e){if(!e||typeof e!="object")throw new L("header_schema_mismatch","header is not an object");let t=e;for(let r of uc)if(t[r]===void 0)throw new L("header_schema_mismatch",`header missing required field: ${String(r)}`);if(t.format_version!==3)throw new L("unsupported_version",`format_version ${t.format_version} unknown`);if(t.profile!=="pq-hybrid")throw new L("suite_unknown",`profile must be 'pq-hybrid', got '${String(t.profile)}'`);let n=t.suite;if(n.kem!==j.PQ_SUITE.KEM||n.sig!==j.PQ_SUITE.SIG||n.aead!==j.PQ_SUITE.AEAD||n.kdf!==j.PQ_SUITE.KDF)throw new L("suite_unknown",`suite mismatch: viewer supports ${JSON.stringify(j.PQ_SUITE)}, header has ${JSON.stringify(n)}`)}function Po(e,t){let n=new TextEncoder().encode(JSON.stringify(e));if(n.length>O.CONTAINER_HEADER_MAX_BYTES)throw new L("header_schema_mismatch",`header too large (${n.length} bytes; max 16 MB)`);let r=new Uint8Array(O.CONTAINER_FIXED_PREFIX_BYTES+n.length+t.length);return r.set(O.CONTAINER_MAGIC,0),r[4]=j.NDC_WIRE_V03,r[5]=n.length>>16&255,r[6]=n.length>>8&255,r[7]=n.length&255,r.set(n,O.CONTAINER_FIXED_PREFIX_BYTES),r.set(t,O.CONTAINER_FIXED_PREFIX_BYTES+n.length),r}function Do(e){if(e.length<O.CONTAINER_FIXED_PREFIX_BYTES)throw new L("header_truncated",`container truncated: ${e.length} bytes (need \u2265 ${O.CONTAINER_FIXED_PREFIX_BYTES})`);for(let o=0;o<4;o++)if(e[o]!==O.CONTAINER_MAGIC[o])throw new L("bad_magic",`bad magic: expected NDLB, got ${xo(e.slice(0,4))}`);if(e[4]!==j.NDC_WIRE_V03)throw new L("unsupported_version",`expected wire version 0x${j.NDC_WIRE_V03.toString(16)}, got 0x${e[4].toString(16)}`);let t=e[5]<<16|e[6]<<8|e[7],n=O.CONTAINER_FIXED_PREFIX_BYTES+t;if(e.length<n)throw new L("header_truncated",`header truncated: declared ${t}, only ${e.length-O.CONTAINER_FIXED_PREFIX_BYTES} bytes left`);let r;try{r=JSON.parse(new TextDecoder("utf-8").decode(e.slice(O.CONTAINER_FIXED_PREFIX_BYTES,n)))}catch(o){throw new L("header_invalid_json",`header JSON parse failed: ${o.message}`)}return pc(r),{header:r,ciphertextWithTag:e.slice(n)}}var Ne=e=>e;async function Eo(e,t,n){let r=await crypto.subtle.importKey("raw",Ne(e),{name:"AES-GCM"},!1,["encrypt"]),o=await crypto.subtle.encrypt({name:"AES-GCM",iv:Ne(t)},r,Ne(n));return new Uint8Array(o)}async function ko(e,t,n){let r=await crypto.subtle.importKey("raw",Ne(e),{name:"AES-GCM"},!1,["decrypt"]),o=await crypto.subtle.decrypt({name:"AES-GCM",iv:Ne(t)},r,Ne(n));return new Uint8Array(o)}function Oo(e){return(0,cc.hkdf)(lc.sha256,e,new Uint8Array(0),new TextEncoder().encode(dc),32)}async function Io(e){let t=await crypto.subtle.digest("SHA-256",Ne(e));return xo(new Uint8Array(t))}async function fc(e){let t=crypto.getRandomValues(new Uint8Array(32)),n=crypto.getRandomValues(new Uint8Array(12)),r=await Eo(t,n,e.plaintext),o=r.slice(r.length-16),a=r.slice(0,r.length-16),i=(0,j.hybridKemEncapsulate)(e.recipientPublicKey),s=Oo(i.sharedSecret),c=crypto.getRandomValues(new Uint8Array(12)),d=await Eo(s,c,t),u=await Io(a),p={lockbox_id:e.meta.lockbox_id,format_version:3,profile:"pq-hybrid",suite:{kem:j.PQ_SUITE.KEM,sig:j.PQ_SUITE.SIG,aead:j.PQ_SUITE.AEAD,kdf:j.PQ_SUITE.KDF},server:e.meta.server,kem:{recipient_kid:e.recipientKid,ct_classical:fe(i.ciphertext.ctClassical),ct_pq:fe(i.ciphertext.ctPq),ephemeral_x25519_pk:fe(i.ephemeralX25519Pk)},wrapped_content_key:{wrapped:fe(d),wrap_iv:fe(c)},iv:fe(n),tag:fe(o),bearer:e.meta.bearer,dpop_required:e.meta.dpop_required,ratchet_state:e.meta.ratchet_state,tee_attestation_url:e.meta.tee_attestation_url,original_filename:e.meta.original_filename,original_content_type:e.meta.original_content_type,ciphertext_sha256:u,issued_at:new Date().toISOString(),cache_ttl_seconds:e.meta.cache_ttl_seconds},f=Ao(p,e.signerKid,e.signerKeypair),y=Po(f,r);return t.fill(0),{container:y,header:f,serverState:{lockbox_id:e.meta.lockbox_id,kem_ct_classical_b64:f.kem.ct_classical,kem_ct_pq_b64:f.kem.ct_pq,wrapped_content_key_b64:f.wrapped_content_key.wrapped,wrap_iv_b64:f.wrapped_content_key.wrap_iv}}}async function hc(e){let{header:t,ciphertextWithTag:n}=Do(e.container);if(!To(t,e.signerPublicKey))throw new L("signature_invalid","hybrid signature verification failed");let r=n.slice(0,n.length-16),o=await Io(r);if(o!==t.ciphertext_sha256)throw new L("integrity_mismatch",`ciphertext sha256 mismatch: expected ${t.ciphertext_sha256.slice(0,16)}\u2026, got ${o.slice(0,16)}\u2026`);let a={ctClassical:Ie(t.kem.ct_classical),ctPq:Ie(t.kem.ct_pq)},i=(0,j.hybridKemDecapsulate)(e.recipientSecretKey,e.recipientPublicX25519,a),s=Oo(i),c=Ie(t.wrapped_content_key.wrapped),d=Ie(t.wrapped_content_key.wrap_iv),u=await ko(s,d,c),p=Ie(t.iv),f=await ko(u,p,n);return u.fill(0),{plaintext:f,header:t}}});var nr=N(ze=>{"use strict";Object.defineProperty(ze,"__esModule",{value:!0});ze.publicJwkFromBytes=Co;ze.jwkThumbprint=Ro;ze.createDpop=mc;ze.verifyDpop=_c;var No=T("@noble/curves/ed25519.js"),yc=T("@noble/hashes/sha2.js"),Je=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,"_")},Vt=e=>{let t=e.replace(/-/g,"+").replace(/_/g,"/"),n=t.length%4?4-t.length%4:0,r=t+"=".repeat(n);if(typeof Buffer<"u")return new Uint8Array(Buffer.from(r,"base64"));let o=atob(r),a=new Uint8Array(o.length);for(let i=0;i<o.length;i++)a[i]=o.charCodeAt(i);return a},mt=e=>new TextEncoder().encode(e);function Co(e){if(e.length!==32)throw new Error(`expected 32-byte Ed25519 public key, got ${e.length}`);return{kty:"OKP",crv:"Ed25519",x:Je(e)}}function Ro(e){let t=`{"crv":"${e.crv}","kty":"${e.kty}","x":"${e.x}"}`,n=(0,yc.sha256)(mt(t));return Je(n)}function mc(e){let n={typ:"dpop+jwt",alg:"EdDSA",jwk:Co(e.publicKey)},r={htm:e.htm.toUpperCase(),htu:tr(e.htu),jti:e.jti??gc(),iat:e.iat??Math.floor(Date.now()/1e3)};e.nonce&&(r.nonce=e.nonce);let o=Je(mt(JSON.stringify(n))),a=Je(mt(JSON.stringify(r))),i=`${o}.${a}`,s=No.ed25519.sign(mt(i),e.secretKey);return`${i}.${Je(s)}`}function gc(){return Je(crypto.getRandomValues(new Uint8Array(16)))}function tr(e){try{let t=new URL(e);return`${t.protocol}//${t.host}${t.pathname}`}catch{return e}}async function _c(e,t){let n=e.split(".");if(n.length!==3)return F("malformed","expected three JWT parts");let[r,o,a]=n,i;try{i=JSON.parse(new TextDecoder().decode(Vt(r)))}catch{return F("bad_header","header is not valid base64url JSON")}if(i.typ!=="dpop+jwt")return F("bad_typ",`typ must be 'dpop+jwt', got '${String(i.typ)}'`);if(i.alg!=="EdDSA")return F("bad_alg",`alg must be 'EdDSA', got '${String(i.alg)}'`);if(!i.jwk||i.jwk.kty!=="OKP"||i.jwk.crv!=="Ed25519")return F("bad_header","jwk must be an Ed25519 OKP key");let s=Ro(i.jwk);if(s!==t.expectedJkt)return F("jkt_mismatch",`jkt does not match registered key: expected ${t.expectedJkt.slice(0,12)}\u2026, got ${s.slice(0,12)}\u2026`);let c;try{c=JSON.parse(new TextDecoder().decode(Vt(o)))}catch{return F("bad_payload","payload is not valid base64url JSON")}if(c.htm!==t.expectedHtm.toUpperCase())return F("htm_mismatch",`htm '${c.htm}' \u2260 expected '${t.expectedHtm.toUpperCase()}'`);if(c.htu!==tr(t.expectedHtu))return F("htu_mismatch",`htu '${c.htu}' \u2260 expected '${tr(t.expectedHtu)}'`);if(t.expectedNonce!==void 0&&c.nonce!==t.expectedNonce)return F("nonce_mismatch","DPoP nonce does not match server-issued nonce");let d=Math.floor(Date.now()/1e3),u=t.maxAgeSeconds??30;if(typeof c.iat!="number")return F("bad_payload","iat missing or not a number");if(c.iat>d+5)return F("iat_in_future",`iat ${c.iat} > now+skew`);if(d-c.iat>u)return F("iat_too_old",`iat ${c.iat} older than ${u}s`);let p;try{p=Vt(i.jwk.x)}catch{return F("bad_header","jwk.x is not base64url")}let f=Vt(a),y=mt(`${r}.${o}`);return No.ed25519.verify(f,y,p)?await t.isJtiFresh(c.jti)?{ok:!0,jti:c.jti,iat:c.iat}:F("replay",`jti ${c.jti} was already seen`):F("signature_invalid","Ed25519 signature does not verify")}function F(e,t){return{ok:!1,code:e,reason:t}}});var Fo=N(w=>{"use strict";Object.defineProperty(w,"__esModule",{value:!0});w.ABSORB_STATUS=w.DELTA_KIND=w.RCPT_TOTAL_LEN=w.RCPT_SIGNED_LEN=w.PVE_TOTAL_LEN=w.PVE_SIGNED_LEN=w.RCPT_VERSION=w.PVE_VERSION=w.RCPT_MAGIC=w.PVE_MAGIC=void 0;w.deltaIdFromUuid=vc;w.uuidFromDeltaId=Ec;w.originJktForPublicKey=_t;w.encodePveSignedBytes=Ko;w.signPve=kc;w.parsePve=jo;w.pveHash=xc;w.verifyPve=Ac;w.encodeReceiptSignedBytes=Mo;w.signReceipt=Tc;w.parseReceipt=Lo;w.verifyReceipt=Pc;var Gt=T("@noble/curves/ed25519.js"),bc=T("@noble/hashes/sha2.js"),$o=nr();w.PVE_MAGIC=new Uint8Array([80,86,69,49]);w.RCPT_MAGIC=new Uint8Array([82,67,86,49]);w.PVE_VERSION=1;w.RCPT_VERSION=1;w.PVE_SIGNED_LEN=160;w.PVE_TOTAL_LEN=w.PVE_SIGNED_LEN+64;w.RCPT_SIGNED_LEN=78;w.RCPT_TOTAL_LEN=w.RCPT_SIGNED_LEN+64;var Bo=new Uint8Array(32);w.DELTA_KIND={relay:1,ndc:2,v4section:3,chatmsg:4};w.ABSORB_STATUS={decrypted_ok:1,verified_only:2,denied:3};function Sc(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 wc(e){let t=e.replace(/-/g,"+").replace(/_/g,"/"),n=t.length%4?4-t.length%4:0,r=t+"=".repeat(n);if(typeof Buffer<"u")return new Uint8Array(Buffer.from(r,"base64"));let o=atob(r),a=new Uint8Array(o.length);for(let i=0;i<o.length;i++)a[i]=o.charCodeAt(i);return a}function ar(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 gt(e){for(let t=0;t<e.length;t++)if(e[t]!==0)return!1;return!0}function rr(e){if(e==null)return Bo;if(e instanceof Uint8Array){if(e.length!==32)throw new Error(`jkt bytes must be 32, got ${e.length}`);return e}let t=wc(e);if(t.length!==32)throw new Error(`jkt must decode to 32 bytes, got ${t.length}`);return t}function or(e){return gt(e)?null:Sc(e)}function vc(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 Ec(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 _t(e){return(0,$o.jwkThumbprint)((0,$o.publicJwkFromBytes)(e))}function Ko(e){if(e.deltaId.length!==16)throw new Error("delta_id must be 16 bytes");if(e.ciphertextSha256.length!==32)throw new Error("ciphertext_sha256 must be 32 bytes");if(e.classification<0||e.classification>65535)throw new Error("classification must fit in uint16");let t=new Uint8Array(w.PVE_SIGNED_LEN),n=new DataView(t.buffer),r=0;return t.set(w.PVE_MAGIC,r),r+=4,t[r]=w.PVE_VERSION,r+=1,t[r]=e.deltaKind,r+=1,t.set(e.deltaId,r),r+=16,t.set(e.ciphertextSha256,r),r+=32,t.set(rr(e.originJkt),r),r+=32,t.set(rr(e.destJkt??null),r),r+=32,t.set(e.prevDeltaHash??Bo,r),r+=32,n.setUint16(r,e.classification,!1),r+=2,n.setBigUint64(r,BigInt(e.issuedAt),!1),r+=8,t}function kc(e,t){let n=_t(e.originPublicKey),r=Ko({deltaKind:e.deltaKind,deltaId:e.deltaId,ciphertextSha256:e.ciphertextSha256,originJkt:n,destJkt:e.destJkt??null,prevDeltaHash:e.prevDeltaHash??null,classification:e.classification,issuedAt:e.issuedAt??Date.now()}),o=Gt.ed25519.sign(r,t),a=new Uint8Array(w.PVE_TOTAL_LEN);return a.set(r,0),a.set(o,w.PVE_SIGNED_LEN),a}function jo(e){if(e.length!==w.PVE_TOTAL_LEN)throw new Error(`PVE must be ${w.PVE_TOTAL_LEN} bytes, got ${e.length}`);if(!ar(e.subarray(0,4),w.PVE_MAGIC))throw new Error("bad PVE magic");let t=new DataView(e.buffer,e.byteOffset,e.byteLength),n=4,r=e[n];n+=1;let o=e[n];n+=1;let a=e.slice(n,n+16);n+=16;let i=e.slice(n,n+32);n+=32;let s=e.slice(n,n+32);n+=32;let c=e.slice(n,n+32);n+=32;let d=e.slice(n,n+32);n+=32;let u=t.getUint16(n,!1);n+=2;let p=Number(t.getBigUint64(n,!1));n+=8;let f=e.slice(0,w.PVE_SIGNED_LEN),y=e.slice(w.PVE_SIGNED_LEN,w.PVE_TOTAL_LEN),b=or(s);if(b===null)throw new Error("origin_jkt must not be zero");return{fields:{version:r,deltaKind:o,deltaId:a,ciphertextSha256:i,originJkt:b,destJkt:or(c),prevDeltaHash:gt(d)?null:d,classification:u,issuedAt:p},signedBytes:f,originSig:y,broadcast:gt(c),genesis:gt(d)}}function xc(e){return(0,bc.sha256)(e)}function Ac(e,t){let n;try{n=jo(e)}catch(o){let a=o instanceof Error?o.message:String(o);return a.includes("magic")?{ok:!1,code:"bad_magic",reason:a}:{ok:!1,code:"malformed",reason:a}}if(n.fields.version!==w.PVE_VERSION)return{ok:!1,code:"bad_version",reason:`unsupported PVE version ${n.fields.version}`};let r;try{r=_t(t)}catch(o){return{ok:!1,code:"malformed",reason:o instanceof Error?o.message:String(o)}}return r!==n.fields.originJkt?{ok:!1,code:"jkt_mismatch",reason:`presented key thumbprint ${r.slice(0,12)}\u2026 \u2260 committed origin_jkt ${n.fields.originJkt.slice(0,12)}\u2026`}:Gt.ed25519.verify(n.originSig,n.signedBytes,t)?{ok:!0,parsed:n}:{ok:!1,code:"signature_invalid",reason:"Ed25519 origin signature does not verify"}}function Mo(e){if(e.pveHash.length!==32)throw new Error("pve_hash must be 32 bytes");let t=rr(e.destJkt);if(gt(t))throw new Error("receipt dest_jkt must not be zero");let n=new Uint8Array(w.RCPT_SIGNED_LEN),r=new DataView(n.buffer),o=0;return n.set(w.RCPT_MAGIC,o),o+=4,n[o]=w.RCPT_VERSION,o+=1,n.set(e.pveHash,o),o+=32,n.set(t,o),o+=32,n[o]=e.absorbStatus,o+=1,r.setBigUint64(o,BigInt(e.absorbedAt),!1),o+=8,n}function Tc(e,t){let n=_t(e.destPublicKey),r=Mo({pveHash:e.pveHash,destJkt:n,absorbStatus:e.absorbStatus,absorbedAt:e.absorbedAt??Date.now()}),o=Gt.ed25519.sign(r,t),a=new Uint8Array(w.RCPT_TOTAL_LEN);return a.set(r,0),a.set(o,w.RCPT_SIGNED_LEN),a}function Lo(e){if(e.length!==w.RCPT_TOTAL_LEN)throw new Error(`receipt must be ${w.RCPT_TOTAL_LEN} bytes, got ${e.length}`);if(!ar(e.subarray(0,4),w.RCPT_MAGIC))throw new Error("bad receipt magic");let t=new DataView(e.buffer,e.byteOffset,e.byteLength),n=4,r=e[n];n+=1;let o=e.slice(n,n+32);n+=32;let a=e.slice(n,n+32);n+=32;let i=e[n];n+=1;let s=Number(t.getBigUint64(n,!1));n+=8;let c=or(a);if(c===null)throw new Error("receipt dest_jkt must not be zero");return{fields:{version:r,pveHash:o,destJkt:c,absorbStatus:i,absorbedAt:s},signedBytes:e.slice(0,w.RCPT_SIGNED_LEN),destSig:e.slice(w.RCPT_SIGNED_LEN,w.RCPT_TOTAL_LEN)}}function Pc(e,t,n){let r;try{r=Lo(e)}catch(a){let i=a instanceof Error?a.message:String(a);return i.includes("magic")?{ok:!1,code:"bad_magic",reason:i}:{ok:!1,code:"malformed",reason:i}}if(r.fields.version!==w.RCPT_VERSION)return{ok:!1,code:"bad_version",reason:`unsupported receipt version ${r.fields.version}`};let o;try{o=_t(t)}catch(a){return{ok:!1,code:"malformed",reason:a instanceof Error?a.message:String(a)}}return o!==r.fields.destJkt?{ok:!1,code:"jkt_mismatch",reason:`presented key thumbprint ${o.slice(0,12)}\u2026 \u2260 committed dest_jkt ${r.fields.destJkt.slice(0,12)}\u2026`}:n!==void 0&&!ar(n,r.fields.pveHash)?{ok:!1,code:"pve_hash_mismatch",reason:"receipt does not acknowledge the expected PVE"}:Gt.ed25519.verify(r.destSig,r.signedBytes,t)?{ok:!0,parsed:r}:{ok:!1,code:"signature_invalid",reason:"Ed25519 destination signature does not verify"}}});var Ho=N(bt=>{"use strict";Object.defineProperty(bt,"__esModule",{value:!0});bt.stepRatchet=Dc;bt.replayRatchet=Oc;bt.destroyKey=Ic;var Uo=We();function Dc(e,t){if(t.length!==32)throw new Error(`ratchet token must be 32 bytes, got ${t.length}`);return{nextContentKey:(0,Uo.ratchetAdvance)(e.contentKey,t),openCount:e.openCount+1}}function Oc(e,t){let n=[e],r=e;for(let o of t)r=(0,Uo.ratchetAdvance)(r,o),n.push(r);return n}function Ic(e){e.fill(0)}});var cr=N(Ye=>{"use strict";Object.defineProperty(Ye,"__esModule",{value:!0});Ye.__coseInternals=void 0;Ye.verifyCoseSign1Es384=Rc;Ye.decodeAttestationPayload=$c;var Nc=T("@noble/curves/nist.js"),Cc=T("@noble/hashes/sha2.js"),ir=class{constructor(t){this.b=t,this.p=0}u8(){if(this.p>=this.b.length)throw new Error("cbor: truncated");return this.b[this.p++]}uN(t){let n=0;for(let r=0;r<t;r++)n=n*256+this.u8();return n}len(t){if(t<24)return t;if(t===24)return this.u8();if(t===25)return this.uN(2);if(t===26)return this.uN(4);if(t===27){let n=this.uN(4),r=this.uN(4);return n*4294967296+r}throw new Error(`cbor: unsupported additional info ${t}`)}read(){let t=this.u8(),n=t>>5,r=t&31;switch(n){case 0:return this.len(r);case 1:return-1-this.len(r);case 2:{let o=this.len(r),a=this.b.subarray(this.p,this.p+o);if(a.length!==o)throw new Error("cbor: bstr truncated");return this.p+=o,a.slice()}case 3:{let o=this.len(r),a=this.b.subarray(this.p,this.p+o);if(a.length!==o)throw new Error("cbor: tstr truncated");return this.p+=o,new TextDecoder("utf-8").decode(a)}case 4:{let o=this.len(r),a=[];for(let i=0;i<o;i++)a.push(this.read());return a}case 5:{let o=this.len(r),a=new Map;for(let i=0;i<o;i++){let s=this.read(),c=this.read();a.set(s,c)}return a}case 6:return this.len(r),this.read();case 7:if(r===20)return!1;if(r===21)return!0;if(r===22||r===23)return null;throw new Error(`cbor: unsupported simple/float ${r}`);default:throw new Error(`cbor: unknown major ${n}`)}}};function sr(e){return new ir(e).read()}function Wt(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 Jt(...e){let t=e.reduce((o,a)=>o+a.length,0),n=new Uint8Array(t),r=0;for(let o of e)n.set(o,r),r+=o.length;return n}function qt(e){return Jt(Wt(2,e.length),e)}function Vo(e){let t=new TextEncoder().encode(e);return Jt(Wt(3,t.length),t)}function Go(e,t){return Jt(Wt(4,4),Vo("Signature1"),qt(e),qt(new Uint8Array(0)),qt(t))}function Rc(e,t){let n;try{n=sr(e)}catch(d){return{ok:!1,code:"malformed",reason:`cbor decode failed: ${d.message}`}}if(!Array.isArray(n)||n.length!==4)return{ok:!1,code:"bad_structure",reason:"COSE_Sign1 must be a 4-element array"};let[r,,o,a]=n;if(!(r instanceof Uint8Array))return{ok:!1,code:"bad_structure",reason:"protected header must be a byte string"};if(!(o instanceof Uint8Array)||o.length===0)return{ok:!1,code:"no_payload",reason:"detached/empty payload is not supported"};if(!(a instanceof Uint8Array))return{ok:!1,code:"bad_structure",reason:"signature must be a byte string"};if(a.length!==96)return{ok:!1,code:"bad_signature_len",reason:`expected 96-byte ES384 sig, got ${a.length}`};let i=Go(r,o),s=(0,Cc.sha384)(i),c=!1;try{c=Nc.p384.verify(a,s,t,{prehash:!1})}catch(d){return{ok:!1,code:"signature_invalid",reason:`verify threw: ${d.message}`}}return c?{ok:!0,payload:o}:{ok:!1,code:"signature_invalid",reason:"ECDSA P-384 verification failed"}}function $c(e){try{let t=sr(e);return t instanceof Map?t:null}catch{return null}}Ye.__coseInternals={sig1Structure:Go,encBstr:qt,encText:Vo,encHead:Wt,concat:Jt,decodeCbor:sr}});var qo=N(St=>{"use strict";Object.defineProperty(St,"__esModule",{value:!0});St.parseAttestation=Kc;St.verifyAttestation=jc;St.fetchAttestation=Mc;var Bc=cr();function Kc(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 jc(e,t){if(e.vendor!==t.vendor)return{ok:!1,code:"vendor_mismatch",reason:`vendor '${e.vendor}' \u2260 expected '${t.vendor}'`};if(e.module_id!==t.module_id)return{ok:!1,code:"module_id_mismatch",reason:`module_id mismatch (got '${e.module_id.slice(0,16)}\u2026')`};for(let[a,i]of Object.entries(t.pcrs))if(e.pcrs[a]!==i)return{ok:!1,code:"pcr_mismatch",reason:`PCR ${a}: got '${(e.pcrs[a]??"").slice(0,16)}\u2026', expected '${i.slice(0,16)}\u2026'`};if(e.user_data_sha256!==t.expected_user_data_sha256)return{ok:!1,code:"user_data_mismatch",reason:"attested user_data does not match presented key"};let n=Math.floor(Date.now()/1e3),r=t.maxAgeSeconds??600;if(e.timestamp>n+30)return{ok:!1,code:"in_future",reason:`attestation timestamp ${e.timestamp} > now+30s`};if(n-e.timestamp>r)return{ok:!1,code:"expired",reason:`attestation ${n-e.timestamp}s old (max ${r}s)`};let o=!1;if(t.cose){if(!t.trustedLeafPubKey)return{ok:!1,code:"signature_invalid",reason:"cose supplied without trustedLeafPubKey \u2014 cannot verify, refusing"};let a=(0,Bc.verifyCoseSign1Es384)(t.cose,t.trustedLeafPubKey);if(!a.ok)return{ok:!1,code:"signature_invalid",reason:`cose: ${a.code}: ${a.reason}`};o=!0}return{ok:!0,vendor:e.vendor,module_id:e.module_id,signature_verified:o}}async function Mc(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 zo=N(Xe=>{"use strict";Object.defineProperty(Xe,"__esModule",{value:!0});Xe.splitSecret=Hc;Xe.combineShares=Vc;Xe.serializeShare=Wc;Xe.deserializeShare=Jc;var Ce=null,Re=null;function Wo(){if(Ce&&Re)return;Ce=new Uint8Array(512),Re=new Uint8Array(256);let e=1;for(let t=0;t<255;t++){Ce[t]=e,Re[e]=t;let n=e<<1;n&256&&(n^=283),n^=e,e=n&255}for(let t=255;t<512;t++)Ce[t]=Ce[t-255]}function zt(e,t){return e===0||t===0?0:(Wo(),Ce[Re[e]+Re[t]])}function Lc(e,t){if(e===0)return 0;if(t===0)throw new Error("division by zero in GF(2^8)");Wo();let n=Re[e]-Re[t];return Ce[n<0?n+255:n]}function Jo(e,t){return e^t}function Fc(e,t){let n=0;for(let r=e.length-1;r>=0;r--)n=Jo(zt(n,t),e[r]);return n}var Uc=e=>crypto.getRandomValues(new Uint8Array(e));function Hc(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??Uc,r=[];for(let o=1;o<=t.n;o++)r.push({x:o,y:new Uint8Array(e.length)});for(let o=0;o<e.length;o++){let a=new Uint8Array(t.k);a[0]=e[o];let i=n(t.k-1);for(let s=1;s<t.k;s++)a[s]=i[s-1];for(let s=0;s<t.n;s++)r[s].y[o]=Fc(a,r[s].x)}return r}function Vc(e){if(e.length<2)throw new Error("need at least 2 shares to reconstruct");let t=e[0].y.length;for(let o of e){if(o.y.length!==t)throw new Error("shares have inconsistent length");if(o.x===0)throw new Error("share x must not be 0")}let n=new Set;for(let o of e){if(n.has(o.x))throw new Error(`duplicate share x=${o.x}`);n.add(o.x)}let r=new Uint8Array(t);for(let o=0;o<t;o++){let a=0;for(let i=0;i<e.length;i++){let s=1,c=1;for(let u=0;u<e.length;u++)i!==u&&(s=zt(s,e[u].x),c=zt(c,e[i].x^e[u].x));let d=Lc(s,c);a=Jo(a,zt(e[i].y[o],d))}r[o]=a}return r}var Gc=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)},qc=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 Wc(e){return{x:e.x,y_b64:Gc(e.y)}}function Jc(e){return{x:e.x,y:qc(e.y_b64)}}});var Qo=N(we=>{"use strict";Object.defineProperty(we,"__esModule",{value:!0});we.SegmentError=void 0;we.sealSegments=Qc;we.openSegments=el;we.manifestDigest=tl;we.buildCapability=nl;var lr=T("@noble/hashes/sha2.js"),zc="pq-hybrid-segments",Yc="AES-256-GCM",Ze=e=>e,Yo=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)},Xo=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},Zo=e=>{let t="";for(let n=0;n<e.length;n++)t+=e[n].toString(16).padStart(2,"0");return t};async function Xc(e,t,n){let r=await crypto.subtle.importKey("raw",Ze(e),{name:"AES-GCM"},!1,["encrypt"]),o=await crypto.subtle.encrypt({name:"AES-GCM",iv:Ze(t)},r,Ze(n));return new Uint8Array(o)}async function Zc(e,t,n){let r=await crypto.subtle.importKey("raw",Ze(e),{name:"AES-GCM"},!1,["decrypt"]),o=await crypto.subtle.decrypt({name:"AES-GCM",iv:Ze(t)},r,Ze(n));return new Uint8Array(o)}var $e=class extends Error{constructor(t,n){super(n),this.name="SegmentError",this.code=t}};we.SegmentError=$e;async function Qc(e){let t=new Set;for(let o of e){if(t.has(o.segment_id))throw new $e("duplicate_segment_id",`segment_id '${o.segment_id}' appears twice`);t.add(o.segment_id)}let n=[],r=[];for(let o of e){let a=crypto.getRandomValues(new Uint8Array(32)),i=crypto.getRandomValues(new Uint8Array(12)),s=await Xc(a,i,o.plaintext),c=s.slice(0,s.length-16),d=Zo((0,lr.sha256)(c));n.push({segment_id:o.segment_id,key:a}),r.push({segment_id:o.segment_id,label:o.label,content_type:o.content_type,iv_b64:Yo(i),ciphertext_b64:Yo(s),ciphertext_sha256:d})}return{manifest:{profile:zc,aead:Yc,segments:r},keys:n}}async function el(e,t){let n=new Map;for(let o of t.keys)n.set(o.segment_id,o.key);let r=[];for(let o of e.segments){if(!t.allowed_segment_ids.includes(o.segment_id))continue;let a=n.get(o.segment_id);if(!a)throw new $e("key_missing",`capability lists ${o.segment_id} as allowed but holds no key for it`);let i=Xo(o.ciphertext_b64),s=i.slice(0,i.length-16);if(Zo((0,lr.sha256)(s))!==o.ciphertext_sha256)throw new $e("integrity_mismatch",`segment ${o.segment_id}: ciphertext sha256 mismatch`);let d=Xo(o.iv_b64),u=await Zc(a,d,i);r.push({segment_id:o.segment_id,label:o.label,content_type:o.content_type,plaintext:u})}return r}function tl(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,lr.sha256)(new TextEncoder().encode(n))}function nl(e,t,n){let r=new Set(t),o=n.filter(a=>r.has(a.segment_id));if(o.length!==t.length){let a=t.filter(i=>!o.find(s=>s.segment_id===i));throw new $e("segment_not_found",`cannot build capability \u2014 no key for: ${a.join(", ")}`)}return{recipient_kid:e,allowed_segment_ids:t,keys:o}}});var na=N(wt=>{"use strict";Object.defineProperty(wt,"__esModule",{value:!0});wt.computeWatermark=ta;wt.findLeakSource=al;wt.watermarkSvgOverlay=il;var rl=T("@noble/hashes/hmac.js"),ol=T("@noble/hashes/sha2.js");function ta(e){let t=[e.recipientId,e.lockboxId,String(e.openCount),String(e.iat)].join("|"),n=(0,rl.hmac)(ol.sha256,e.tenantSecret,new TextEncoder().encode(t)),r=ea(n.slice(0,16)),o=ea(n.slice(0,4)),a=new Date(e.iat*1e3).toISOString().slice(0,10),i=`${e.recipientId} \xB7 ${a} \xB7 ${o}`;return{short_hex:o,full_hex:r,display_label:i}}function al(e,t,n){let r=e.toLowerCase();for(let o of n){let a=ta({tenantSecret:t,...o});if(r===a.full_hex)return{matched:!0,candidate:o,matched_on:"full_hex"};if(r===a.short_hex)return{matched:!0,candidate:o,matched_on:"short_hex"}}return{matched:!1,reason:"no_candidate_matched"}}function il(e,t){let n=t?.width??800,r=t?.height??1e3,o=t?.opacity??.1,i=(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 cc=Object.create;var Mo=Object.defineProperty;var lc=Object.getOwnPropertyDescriptor;var dc=Object.getOwnPropertyNames;var uc=Object.getPrototypeOf,pc=Object.prototype.hasOwnProperty;var I=(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 R=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var fc=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of dc(t))!pc.call(e,o)&&o!==n&&Mo(e,o,{get:()=>t[o],enumerable:!(r=lc(t,o))||r.enumerable});return e};var Yn=(e,t,n)=>(n=e!=null?cc(uc(e)):{},fc(t||!e||!e.__esModule?Mo(n,"default",{value:e,enumerable:!0}):n,e));var gr=R(te=>{"use strict";Object.defineProperty(te,"__esModule",{value:!0});te.MAX_SEALED_BYTES=void 0;te.kidForPublicKey=hi;te.deriveKeyPairFromSeed=ll;te.generateSeed=dl;te.buildEnvInfo=ul;te.sealDek=pl;te.openSealedDek=fl;te.decodeSealHeader=mi;var ui=I("crypto"),di=I("@hpke/core"),ol=I("@hpke/dhkem-x25519"),il=I("@hpke/chacha20poly1305"),al=I("@noble/curves/ed25519.js"),sl=I("@noble/hashes/hkdf.js"),cl=I("@noble/hashes/sha2.js"),ln=new di.CipherSuite({kem:new ol.DhkemX25519HkdfSha256,kdf:new di.HkdfSha256,aead:new il.Chacha20Poly1305}),pi=1,fi=1;te.MAX_SEALED_BYTES=4096;function hi(e){return(0,ui.createHash)("sha256").update(e).digest("hex").slice(0,16)}function ll(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,sl.hkdf)(cl.sha256,e,new Uint8Array(0),t,32)),r=Buffer.from(al.x25519.scalarMultBase(n));return{secretKey:n,publicKey:r,kid:hi(r)}}function dl(){return(0,ui.randomBytes)(32)}function ul(e){return Buffer.from(`protect.env.v3|${e}`,"utf8")}async function pl(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 ln.kem.deserializePublicKey(Be(t)),o=await ln.createSenderContext({recipientPublicKey:r,info:Be(n)}),i=Buffer.from(await o.seal(Be(e),new ArrayBuffer(0))),a=Buffer.from(o.enc),s=Buffer.alloc(6+a.length+i.length);return s[0]=pi,s[1]=fi,s.writeUInt16BE(a.length,2),s.writeUInt16BE(i.length,4),a.copy(s,6),i.copy(s,6+a.length),s}async function fl(e,t,n){let r=mi(e),o=e.subarray(6,6+r.encLen),i=e.subarray(6+r.encLen),a=await ln.kem.deserializePrivateKey(Be(t)),s=await ln.createRecipientContext({recipientKey:a,enc:Be(o),info:Be(n)});return Buffer.from(await s.open(Be(i)))}function mi(e){if(e.length<6)throw new Error("sealed bytes too short");if(e.length>te.MAX_SEALED_BYTES)throw new Error("sealed bytes too long");let t=e[0],n=e[1];if(t!==pi)throw new Error(`unsupported seal version 0x${t.toString(16)}`);if(n!==fi)throw new Error(`unsupported HPKE suite 0x${n.toString(16)}`);let r=e.readUInt16BE(2),o=e.readUInt16BE(4);if(e.length!==6+r+o)throw new Error("sealed length mismatch");if(r!==32)throw new Error("unexpected KEM enc length (X25519 is 32 bytes)");if(o<16)throw new Error("ciphertext shorter than the AEAD tag");return{ver:t,suite:n,encLen:r,ctLen:o}}function Be(e){return e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength)}});var gi=R(ge=>{"use strict";Object.defineProperty(ge,"__esModule",{value:!0});ge.V3_PREFIX=void 0;ge.sealValue=hl;ge.formatToken=ml;ge.parseToken=yi;ge.openValue=yl;var dn=I("crypto"),un=gr();ge.V3_PREFIX="aes256gcm:v3:";async function hl(e,t){let n=(0,dn.randomBytes)(32),r=(0,dn.randomBytes)(12),o=(0,dn.createCipheriv)("aes-256-gcm",n,r),i=Buffer.concat([o.update(e,"utf8"),o.final()]),a=Buffer.concat([i,o.getAuthTag()]),s=await(0,un.sealDek)(n,t.publicKey,(0,un.buildEnvInfo)(t.kid));return n.fill(0),{sealedDekB64:s.toString("base64"),iv:r,cipher:a}}function ml(e,t){return`${ge.V3_PREFIX}${e.iv.toString("base64")}:${e.cipher.toString("base64")}:${t}`}function yi(e){let t=e.split(":");if(t.length!==5||t[0]!=="aes256gcm"||t[1]!=="v3")throw new Error("not a v3 token");let[,,n,r,o]=t;if(!o)throw new Error("v3 token has no seal id");let i=Buffer.from(n,"base64"),a=Buffer.from(r,"base64");if(i.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:i,cipher:a,sealId:o}}async function yl(e,t,n){let{iv:r,cipher:o}=yi(e),i=await(0,un.openSealedDek)(Buffer.from(t,"base64"),n.secretKey,(0,un.buildEnvInfo)(n.kid)),a=o.subarray(o.length-16),s=o.subarray(0,o.length-16),c=(0,dn.createDecipheriv)("aes-256-gcm",i,r);c.setAuthTag(a);try{return Buffer.concat([c.update(s),c.final()]).toString("utf8")}finally{i.fill(0)}}});var Si=R(W=>{"use strict";var gl=W&&W.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n);var o=Object.getOwnPropertyDescriptor(t,n);(!o||("get"in o?!t.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,o)}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),_l=W&&W.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),br=W&&W.__importStar||(function(){var e=function(t){return e=Object.getOwnPropertyNames||function(n){var r=[];for(var o in n)Object.prototype.hasOwnProperty.call(n,o)&&(r[r.length]=o);return r},e(t)};return function(t){if(t&&t.__esModule)return t;var n={};if(t!=null)for(var r=e(t),o=0;o<r.length;o++)r[o]!=="default"&&gl(n,t,r[o]);return _l(n,t),n}})();Object.defineProperty(W,"__esModule",{value:!0});W.deviceKeyPath=vl;W.hasDeviceKey=Sl;W.loadDeviceKey=wl;W.createDeviceKey=kl;W.importDeviceKey=xl;W.exportSeedHex=El;W.deviceKeyIsExposed=Al;var X=br(I("fs")),bl=br(I("os")),_i=br(I("path")),St=gr(),_r=_i.join(bl.homedir(),".nodata"),M=_i.join(_r,"device-key.json");function vl(){return M}function bi(){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 Sl(){return bi()!==null||X.existsSync(M)}function wl(){let e=bi();if(e)return(0,St.deriveKeyPairFromSeed)(e);if(!X.existsSync(M))return null;let t;try{t=JSON.parse(X.readFileSync(M,"utf-8"))}catch{throw new Error(`Device key file is unreadable: ${M}`)}if(!t.seed_hex||!/^[0-9a-f]{64}$/i.test(t.seed_hex))throw new Error(`Device key file is malformed (bad seed): ${M}`);let n=(0,St.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 kl(e={}){if(X.existsSync(M)&&!e.force)throw new Error(`A device key already exists at ${M}. Replacing it makes every existing v3 seal unopenable. Back up the seed first (nodata key export), then pass --force.`);let t=(0,St.generateSeed)(),n=(0,St.deriveKeyPairFromSeed)(t);return vi(t,n),n}function xl(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(X.existsSync(M)&&!t.force)throw new Error(`A device key already exists at ${M}. Pass --force to replace it.`);let r=Buffer.from(n,"hex"),o=(0,St.deriveKeyPairFromSeed)(r);return vi(r,o),o}function El(){if(!X.existsSync(M))throw new Error("No device key file to export.");return JSON.parse(X.readFileSync(M,"utf-8")).seed_hex}function vi(e,t){X.existsSync(_r)||X.mkdirSync(_r,{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()};X.writeFileSync(M,JSON.stringify(n,null,2)+`
|
|
5
|
+
`,{mode:384});try{X.chmodSync(M,384)}catch{}}function Al(){if(process.platform==="win32"||!X.existsSync(M))return!1;try{return(X.statSync(M).mode&63)!==0}catch{return!1}}});var kr=R(Z=>{"use strict";var Tl=Z&&Z.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n);var o=Object.getOwnPropertyDescriptor(t,n);(!o||("get"in o?!t.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,o)}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),Pl=Z&&Z.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),wi=Z&&Z.__importStar||(function(){var e=function(t){return e=Object.getOwnPropertyNames||function(n){var r=[];for(var o in n)Object.prototype.hasOwnProperty.call(n,o)&&(r[r.length]=o);return r},e(t)};return function(t){if(t&&t.__esModule)return t;var n={};if(t!=null)for(var r=e(t),o=0;o<r.length;o++)r[o]!=="default"&&Tl(n,t,r[o]);return Pl(n,t),n}})();Object.defineProperty(Z,"__esModule",{value:!0});Z.ensureDeviceKey=Il;Z.sealFile=Dl;Z.readManifest=ki;Z.openFile=$l;Z.writeLocalReceipt=Nl;var vr=I("crypto"),be=I("fs"),wt=I("path"),Sr=wi(gi()),wr=wi(Si());function Il(){let e=wr.loadDeviceKey();return e?{key:e,created:!1}:{key:wr.createDeviceKey(),created:!0}}async function Dl(e,t,n){let r=(0,be.readFileSync)(e),o=(0,vr.createHash)("sha256").update(r).digest("hex"),i=n??"local-"+(0,vr.randomUUID)(),a=await Sr.sealValue(r.toString("base64"),t),s={v:3,alg:"aes256gcm:v3",kid:t.kid,orig:(0,wt.basename)(e),enc:"base64",token:Sr.formatToken(a,i),sealed_dek:a.sealedDekB64,sha256:o,sealed_at:new Date().toISOString()},c=e+".ndc";return(0,be.writeFileSync)(c,JSON.stringify(s,null,2)+`
|
|
6
|
+
`,{mode:384}),{path:e,ndc:c,sha256:o,sealId:i}}function ki(e){try{let t=JSON.parse((0,be.readFileSync)(e,"utf8"));return t.alg==="aes256gcm:v3"&&t.token&&t.sealed_dek?t:null}catch{return null}}async function $l(e,t){if(!(0,be.existsSync)(e))return{ok:!1,error:"not_found"};let n=ki(e);if(!n)return{ok:!1,error:"not_a_seal"};let r=t===void 0?wr.loadDeviceKey():t;if(!r)return{ok:!1,error:"no_device_key"};let o;try{o=await Sr.openValue(n.token,n.sealed_dek,r)}catch{return{ok:!1,error:"wrong_key"}}let i=Buffer.from(o,"base64"),a=e.endsWith(".ndc")?e.slice(0,-4):e+".opened";(0,be.existsSync)(a)&&(a=a+".opened"),(0,be.writeFileSync)(a,i);let s=(0,vr.createHash)("sha256").update(i).digest("hex")===n.sha256;return{ok:!0,outPath:a,sha256:n.sha256,intact:s}}function Nl(e,t){let n=(0,wt.join)(e,".nodata","receipts");(0,be.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(i=>({path:(0,wt.relative)(e,i.path),sha256:i.sha256,seal_id:i.sealId,sealed:(0,wt.basename)(i.ndc)})),...t.extra??{}},o=(0,wt.join)(n,`${t.action}-${Date.now()}.json`);return(0,be.writeFileSync)(o,JSON.stringify(r,null,2)+`
|
|
7
|
+
`),o}});var je=R($r=>{"use strict";Object.defineProperty($r,"__esModule",{value:!0});var Et=class{static async generateKeyPair(){let t=await crypto.subtle.generateKey({name:"RSA-OAEP",modulusLength:4096,publicExponent:new Uint8Array([1,0,1]),hash:"SHA-256"},!0,["encrypt","decrypt"]),n=await crypto.subtle.exportKey("jwk",t.publicKey),r=await crypto.subtle.exportKey("jwk",t.privateKey);return{publicKeyJwk:n,privateKeyJwk:r}}static async encryptMessage(t,n){let r=await crypto.subtle.importKey("jwk",n,{name:"RSA-OAEP",hash:"SHA-256"},!1,["encrypt"]),o=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!0,["encrypt","decrypt"]),i=crypto.getRandomValues(new Uint8Array(12)),a=new TextEncoder().encode(t),s=await crypto.subtle.encrypt({name:"AES-GCM",iv:i,tagLength:128},o,a),c=await crypto.subtle.exportKey("raw",o),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(i)}}static async decryptMessage(t,n){let r=await crypto.subtle.importKey("jwk",n,{name:"RSA-OAEP",hash:"SHA-256"},!1,["decrypt"]),o=this.base64ToArrayBuffer(t.encrypted_aes_key),i=await crypto.subtle.decrypt({name:"RSA-OAEP"},r,o),a=await crypto.subtle.importKey("raw",i,{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(),o=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!0,["encrypt","decrypt"]),i=crypto.getRandomValues(new Uint8Array(12)),a=await crypto.subtle.encrypt({name:"AES-GCM",iv:i,tagLength:128},o,r),s=JSON.stringify({name:t.name,type:t.type,size:t.size,lastModified:t.lastModified}),c=crypto.getRandomValues(new Uint8Array(12)),l=await crypto.subtle.encrypt({name:"AES-GCM",iv:c,tagLength:128},o,new TextEncoder().encode(s)),u=await crypto.subtle.importKey("jwk",n,{name:"RSA-OAEP",hash:"SHA-256"},!1,["encrypt"]),p=await crypto.subtle.exportKey("raw",o),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(i),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 o=await crypto.subtle.importKey("raw",new TextEncoder().encode(t),"PBKDF2",!1,["deriveBits","deriveKey"]);return await crypto.subtle.deriveKey({name:"PBKDF2",salt:new TextEncoder().encode(n),iterations:31e4,hash:r},o,{name:"AES-GCM",length:256},!0,["encrypt","decrypt"])}static async encryptWithDerivedKey(t,n){let r=crypto.getRandomValues(new Uint8Array(12)),o=new TextEncoder().encode(t),i=await crypto.subtle.encrypt({name:"AES-GCM",iv:r,tagLength:128},n,o);return{encrypted:this.arrayBufferToBase64(i),iv:this.arrayBufferToBase64(r)}}static async decryptWithDerivedKey(t,n,r){let o=this.base64ToArrayBuffer(t),i=this.base64ToArrayBuffer(n),a=await crypto.subtle.decrypt({name:"AES-GCM",iv:i,tagLength:128},r,o);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(o=>o.toString(16).padStart(2,"0")).join("")}static async encryptFileWithDerivedKey(t,n){let r=await t.arrayBuffer(),o=await this.sha256Hex(r),i=crypto.getRandomValues(new Uint8Array(12)),a=await crypto.subtle.encrypt({name:"AES-GCM",iv:i,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(i),encrypted_metadata:this.arrayBufferToBase64(l),metadata_iv:this.arrayBufferToBase64(c),encrypted_size:a.byteLength,plaintext_sha256:o,ciphertext_sha256:await this.sha256Hex(a)}}static async decryptFileBytesWithDerivedKey(t,n,r){let o=this.base64ToArrayBuffer(n);return crypto.subtle.decrypt({name:"AES-GCM",iv:o,tagLength:128},r,t)}static async decryptFileWithDerivedKey(t,n,r){let o=this.base64ToArrayBuffer(t),i=this.base64ToArrayBuffer(n);return crypto.subtle.decrypt({name:"AES-GCM",iv:i,tagLength:128},r,o)}static async deriveSeedKey(t,n="SHA-512"){let r=t.trim().toLowerCase(),o=await crypto.subtle.importKey("raw",new TextEncoder().encode(r),"PBKDF2",!1,["deriveBits","deriveKey"]);return await crypto.subtle.deriveKey({name:"PBKDF2",salt:new TextEncoder().encode(this.SEED_SALT),iterations:this.PBKDF2_ITERATIONS,hash:n},o,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}static async exportKeyWithSeed(t,n){let r=await crypto.subtle.exportKey("jwk",t),o=new TextEncoder().encode(JSON.stringify(r)),i=crypto.getRandomValues(new Uint8Array(12)),a=await crypto.subtle.encrypt({name:"AES-GCM",iv:i,tagLength:128},n,o),s=new Uint8Array(i.byteLength+a.byteLength);return s.set(i,0),s.set(new Uint8Array(a),i.byteLength),s.buffer}static async importKeyWithSeed(t,n){let r=new Uint8Array(t),o=r.slice(0,12),i=r.slice(12),a=await crypto.subtle.decrypt({name:"AES-GCM",iv:o,tagLength:128},n,i),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(o=>o.toString(16).padStart(2,"0")).join("")}static arrayBufferToBase64(t){let n=new Uint8Array(t),r=32768,o=[];for(let i=0;i<n.length;i+=r)o.push(String.fromCharCode(...n.subarray(i,i+r)));return btoa(o.join(""))}static async encryptFileToBytesWithDerivedKey(t,n){let r=await t.arrayBuffer(),o=await this.sha256Hex(r),i=crypto.getRandomValues(new Uint8Array(12)),a=await crypto.subtle.encrypt({name:"AES-GCM",iv:i,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(i),encrypted_metadata:this.arrayBufferToBase64(l),metadata_iv:this.arrayBufferToBase64(c),encrypted_size:a.byteLength,plaintext_sha256:o,ciphertext_sha256:await this.sha256Hex(a)}}static base64ToArrayBuffer(t){let n=atob(t),r=new Uint8Array(n.length);for(let o=0;o<n.length;o++)r[o]=n.charCodeAt(o);return r.buffer}static wipeFromMemory(t){new Uint8Array(t).fill(0)}};Et.PBKDF2_ITERATIONS=31e4;Et.SEED_SALT="NoDataChat-Seed-v1";$r.default=Et});var Ri=R(mn=>{"use strict";Object.defineProperty(mn,"__esModule",{value:!0});mn.solveProofOfWork=Xl;mn.verifyProofOfWork=Zl;function Yl(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 Ni(e){let t=new TextEncoder().encode(e),n=await crypto.subtle.digest("SHA-256",t);return Yl(n)}async function Xl(e,t=4){if(t<1||t>16)throw new Error("Difficulty must be between 1 and 16");let n="0".repeat(t),r=0;for(;;){let o=e+r.toString(),i=await Ni(o);if(i.startsWith(n))return{nonce:r,hash:i};if(r++,r>2e9)throw new Error("Proof of work exceeded maximum attempts")}}async function Zl(e,t,n=4){if(n<1||n>16)return!1;let r="0".repeat(n),o=e+t.toString();return(await Ni(o)).startsWith(r)}});var Rr=R(Ze=>{"use strict";var Ql=Ze&&Ze.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(Ze,"__esModule",{value:!0});Ze.NoDataEmail=void 0;var de=Ql(je()),Nr=class{static async seal(t,n,r,o,i,a={}){let{encrypt_subject:s=!0,ttl_hours:c=72,attachments:l=[]}=a,u=await de.default.encryptMessage(o,i),p=r,h=!1;if(s){let y=await de.default.encryptMessage(r,i);p=JSON.stringify(y),h=!0}let f=[];for(let y of l){let S=await de.default.encryptFile(y,i);f.push({encrypted_file:S})}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 de.default.decryptMessage(t.body,n),o=t.subject;if(t.subject_encrypted){let a=JSON.parse(t.subject);o=await de.default.decryptMessage(a,n)}let i=[];for(let a of t.attachments){let{encrypted_file:s}=a,c=de.default.base64ToArrayBuffer(s.metadata_iv),l=de.default.base64ToArrayBuffer(s.encrypted_metadata),u=de.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"]),y=await crypto.subtle.decrypt({name:"AES-GCM",iv:c,tagLength:128},f,l),S=JSON.parse(new TextDecoder().decode(y)),w=de.default.base64ToArrayBuffer(s.iv),b=de.default.base64ToArrayBuffer(s.encrypted_file),x=await crypto.subtle.decrypt({name:"AES-GCM",iv:w,tagLength:128},f,b);i.push({filename:S.name,mime_type:S.type,data:x,size:S.size})}return{subject:o,body:r,attachments:i,sealed_at:t.sealed_at,ttl_hours:t.ttl_hours,envelope_id:t.envelope_id}}static isExpired(t){let r=new Date(t.sealed_at).getTime()+t.ttl_hours*60*60*1e3;return Date.now()>r}static toMimeBody(t,n){let r=JSON.stringify(t),o=btoa(unescape(encodeURIComponent(r)));return['Content-Type: multipart/mixed; boundary="nodata-boundary"',"","--nodata-boundary","Content-Type: text/html; charset=utf-8","",'<div style="font-family:system-ui;padding:24px;text-align:center">',"<h2>This email is encrypted with Capsule</h2>","<p>The sender used end-to-end encryption. To read this message:</p>",`<a href="${n}?env=${t.envelope_id}" `,'style="display:inline-block;padding:12px 24px;background:#000;color:#fff;','border-radius:8px;text-decoration:none;font-weight:600">',"Open Encrypted Email</a>",'<p style="color:#888;font-size:12px;margin-top:16px">',"Powered by Capsule — Nothing is ever stored. Ever.</p>","</div>","--nodata-boundary",'Content-Type: application/x-nodata-envelope; name="envelope.nodata"',"Content-Transfer-Encoding: base64",'Content-Disposition: attachment; filename="envelope.nodata"',"",o,"--nodata-boundary--"].join(`\r
|
|
8
|
+
`)}};Ze.NoDataEmail=Nr});var Br=R(Qe=>{"use strict";var ed=Qe&&Qe.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(Qe,"__esModule",{value:!0});Qe.NoDataWebhook=void 0;var Or=ed(je()),Cr=class{static async encrypt(t,n,r,o){let{event_type:i,source:a,ttl_seconds:s=3600}=o,c=JSON.stringify(t),l=await Or.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:i,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}`,o=await this.hmacSign(r,n),i=new TextEncoder().encode(t.signature),a=new TextEncoder().encode(o),s=i.length^a.length,c=Math.min(i.length,a.length);for(let f=0;f<c;f++)s|=i[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 Or.default.decryptMessage(t.encrypted_event,n);return JSON.parse(r)}static async verifyAndDecrypt(t,n,r){let o=await this.verify(t,r);if(!o.valid)throw new Error(`[NoDataWebhook] Invalid signature for delivery ${o.delivery_id}`);if(o.expired)throw new Error(`[NoDataWebhook] Payload expired for delivery ${o.delivery_id}`);return{data:await this.decrypt(t,n),delivery_id:o.delivery_id,event_type:o.event_type}}static async hmacSign(t,n){let r=await crypto.subtle.importKey("raw",new TextEncoder().encode(n),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),o=await crypto.subtle.sign("HMAC",r,new TextEncoder().encode(t));return Or.default.arrayBufferToBase64(o)}};Qe.NoDataWebhook=Cr});var Kr=R(et=>{"use strict";var td=et&&et.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(et,"__esModule",{value:!0});et.NoDataSystems=void 0;var yn=td(je()),jr=class{static async encryptRecord(t,n,r,o,i,a){let s=[],c={};for(let[l,u]of Object.entries(r))if(o.sensitive.includes(l)){let p=typeof u=="string"?u:JSON.stringify(u),h=await yn.default.encryptMessage(p,i),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 o of t.encrypted_fields){let i=await yn.default.decryptMessage(o.value,n);try{r[o.field_name]=JSON.parse(i)}catch{r[o.field_name]=i}}return{record_id:t.record_id,record_type:t.record_type,fields:r,created_at:t.created_at}}static async searchByHash(t,n,r){let o=await this.hashValue(r);return t.filter(i=>i.encrypted_fields.some(a=>a.field_name===n&&a.search_hash===o))}static async encryptField(t,n,r){let o=typeof n=="string"?n:JSON.stringify(n),i=await yn.default.encryptMessage(o,r),a=await this.hashValue(o);return{value:i,search_hash:a,field_name:t,encrypted_at:new Date().toISOString()}}static async decryptField(t,n){let r=await yn.default.decryptMessage(t.value,n);try{return JSON.parse(r)}catch{return r}}static createSchema(t,n){return{sensitive:n,clear:t.filter(r=>!n.includes(r))}}static async hashValue(t){let n=`nodatachat:field:${t}`,r=new TextEncoder().encode(n),o=await crypto.subtle.digest("SHA-256",r);return Array.from(new Uint8Array(o)).map(i=>i.toString(16).padStart(2,"0")).join("")}};et.NoDataSystems=jr});var Mr=R(tt=>{"use strict";var nd=tt&&tt.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(tt,"__esModule",{value:!0});tt.NoDataForms=void 0;var ue=nd(je()),Lr=class{static async encryptSubmission(t,n,r,o,i={}){let{ttl_hours:a=0,view_once:s=!1,attachments:c=[]}=i,l={},u={};for(let w of n)w.sensitive!==!1?l[w.name]=w.value:u[w.name]=w.value;let p=JSON.stringify(n.map(w=>({name:w.name,value:w.value}))),h=await this.sha256(p),f=await ue.default.encryptMessage(JSON.stringify(l),r),y=[];for(let w of c){let b=await ue.default.encryptFile(w,r);y.push(b)}let S=n.map(w=>w.name);return{submission_id:crypto.randomUUID(),form_id:t,encrypted_fields:f,clear_fields:u,attachments:y,integrity_hash:h,field_order:S,submitter_id:o,submitted_at:new Date().toISOString(),ttl_hours:a,view_once:s,crypto_version:"0.2.0"}}static async decryptSubmission(t,n){let r=await ue.default.decryptMessage(t.encrypted_fields,n),o=JSON.parse(r),i={...t.clear_fields,...o},s=(t.field_order||Object.keys(i).sort()).map(p=>({name:p,value:i[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,ue.default.base64ToArrayBuffer(p.encrypted_file_key)),y=await crypto.subtle.importKey("raw",f,{name:"AES-GCM",length:256},!1,["decrypt"]),S=await crypto.subtle.decrypt({name:"AES-GCM",iv:ue.default.base64ToArrayBuffer(p.metadata_iv),tagLength:128},y,ue.default.base64ToArrayBuffer(p.encrypted_metadata)),w=JSON.parse(new TextDecoder().decode(S)),b=await crypto.subtle.decrypt({name:"AES-GCM",iv:ue.default.base64ToArrayBuffer(p.iv),tagLength:128},y,ue.default.base64ToArrayBuffer(p.encrypted_file));u.push({filename:w.name,mime_type:w.type,data:b,size:w.size})}return{submission_id:t.submission_id,form_id:t.form_id,fields:i,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,o,i=0){let a=await ue.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:o,delivery_id:crypto.randomUUID(),delivered_at:new Date().toISOString(),ttl_hours:i,crypto_version:"0.2.0"}}static async decryptGrade(t,n){let r=await ue.default.decryptMessage(t.encrypted_grade,n);return JSON.parse(r)}static async sha256(t){let n=new TextEncoder().encode(t),r=await crypto.subtle.digest("SHA-256",n);return Array.from(new Uint8Array(r)).map(o=>o.toString(16).padStart(2,"0")).join("")}};tt.NoDataForms=Lr});var Oi=R(nt=>{"use strict";var rd=nt&&nt.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(nt,"__esModule",{value:!0});nt.NoDataSDK=void 0;var gn=rd(je()),we=Rr(),ke=Br(),ne=Kr(),pe=Mr(),Fr=class{static async init(t={}){let n;return t.keyPair?n=t.keyPair:(n=await gn.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:ke.NoDataWebhook.encrypt.bind(ke.NoDataWebhook),verify:ke.NoDataWebhook.verify.bind(ke.NoDataWebhook),decrypt:ke.NoDataWebhook.decrypt.bind(ke.NoDataWebhook),verifyAndDecrypt:ke.NoDataWebhook.verifyAndDecrypt.bind(ke.NoDataWebhook)},systems:{encryptRecord:ne.NoDataSystems.encryptRecord.bind(ne.NoDataSystems),decryptRecord:ne.NoDataSystems.decryptRecord.bind(ne.NoDataSystems),searchByHash:ne.NoDataSystems.searchByHash.bind(ne.NoDataSystems),encryptField:ne.NoDataSystems.encryptField.bind(ne.NoDataSystems),decryptField:ne.NoDataSystems.decryptField.bind(ne.NoDataSystems),createSchema:ne.NoDataSystems.createSchema.bind(ne.NoDataSystems)},forms:{encryptSubmission:pe.NoDataForms.encryptSubmission.bind(pe.NoDataForms),decryptSubmission:pe.NoDataForms.decryptSubmission.bind(pe.NoDataForms),isExpired:pe.NoDataForms.isExpired.bind(pe.NoDataForms),encryptGrade:pe.NoDataForms.encryptGrade.bind(pe.NoDataForms),decryptGrade:pe.NoDataForms.decryptGrade.bind(pe.NoDataForms)},crypto:gn.default}}static async quickEncrypt(t,n){let r=typeof t=="string"?t:JSON.stringify(t),o=await gn.default.encryptMessage(r,n);return JSON.stringify(o)}static async quickDecrypt(t,n){let r=JSON.parse(t),o=await gn.default.decryptMessage(r,n);try{return JSON.parse(o)}catch{return o}}};nt.NoDataSDK=Fr});var Ci=R(re=>{"use strict";Object.defineProperty(re,"__esModule",{value:!0});re.NoDataSDK=re.NoDataForms=re.NoDataSystems=re.NoDataWebhook=re.NoDataEmail=void 0;var od=Rr();Object.defineProperty(re,"NoDataEmail",{enumerable:!0,get:function(){return od.NoDataEmail}});var id=Br();Object.defineProperty(re,"NoDataWebhook",{enumerable:!0,get:function(){return id.NoDataWebhook}});var ad=Kr();Object.defineProperty(re,"NoDataSystems",{enumerable:!0,get:function(){return ad.NoDataSystems}});var sd=Mr();Object.defineProperty(re,"NoDataForms",{enumerable:!0,get:function(){return sd.NoDataForms}});var cd=Oi();Object.defineProperty(re,"NoDataSDK",{enumerable:!0,get:function(){return cd.NoDataSDK}})});var ot=R(D=>{"use strict";Object.defineProperty(D,"__esModule",{value:!0});D.PQ_SIZES=D.NDC_WIRE_V03=D.NDC_WIRE_V1=D.NDC_V03_RATCHET_DOMAIN=D.NDC_V03_CONTENT_KEY_DOMAIN=D.NDC_V03_KEM_DOMAIN=D.PQ_SUITE=void 0;D.generateHybridKemKeypair=ld;D.deriveHybridKemKeypairFromSeed=dd;D.hybridKemEncapsulate=ud;D.hybridKemDecapsulate=pd;D.deriveContentKey=fd;D.ratchetAdvance=hd;D.generateHybridSigKeypair=md;D.hybridSign=yd;D.hybridVerify=gd;D.generateMlDsa65Keypair=_d;D.mlDsa65SignDetached=bd;D.mlDsa65VerifyDetached=vd;var xe=I("@noble/curves/ed25519.js"),At=I("@noble/hashes/sha2.js"),Tt=I("@noble/hashes/hkdf.js"),_n=I("@noble/post-quantum/ml-kem.js"),rt=I("@noble/post-quantum/ml-dsa.js");D.PQ_SUITE={KEM:"X25519+ML-KEM-768",SIG:"Ed25519+ML-DSA-65",AEAD:"AES-256-GCM",KDF:"HKDF-SHA-256"};D.NDC_V03_KEM_DOMAIN="NDC-v0.3-hybrid-kem";D.NDC_V03_CONTENT_KEY_DOMAIN="NDC-v0.3-content-key";D.NDC_V03_RATCHET_DOMAIN="NDC-ratchet";D.NDC_WIRE_V1=1;D.NDC_WIRE_V03=2;function Bi(...e){let t=0;for(let o of e)t+=o.length;let n=new Uint8Array(t),r=0;for(let o of e)n.set(o,r),r+=o.length;return n}function Pt(e){return new TextEncoder().encode(e)}function ji(e,t,n,r){let o=Bi(e,t),i=Bi(Pt(D.NDC_V03_KEM_DOMAIN),n,r);return(0,Tt.hkdf)(At.sha256,o,new Uint8Array(0),i,32)}function ld(){let{secretKey:e,publicKey:t}=xe.x25519.keygen(),{publicKey:n,secretKey:r}=_n.ml_kem768.keygen();return{publicKey:{x25519:t,mlKem:n},secretKey:{x25519:e,mlKem:r}}}function dd(e){if(e.length<32)throw new Error("seed too short (need >=32 bytes)");let t=(0,Tt.hkdf)(At.sha256,e,new Uint8Array(0),Pt("ndc-hybrid-kem-x25519-v1"),32),n=(0,Tt.hkdf)(At.sha256,e,new Uint8Array(0),Pt("ndc-hybrid-kem-mlkem768-v1"),64),r=xe.x25519.getPublicKey(t),{publicKey:o,secretKey:i}=_n.ml_kem768.keygen(n);return{publicKey:{x25519:r,mlKem:o},secretKey:{x25519:t,mlKem:i}}}function ud(e){let{secretKey:t,publicKey:n}=xe.x25519.keygen(),r=xe.x25519.getSharedSecret(t,e.x25519),{cipherText:o,sharedSecret:i}=_n.ml_kem768.encapsulate(e.mlKem),a=ji(i,r,n,e.x25519);return{ciphertext:{ctClassical:n,ctPq:o},sharedSecret:a,ephemeralX25519Pk:n}}function pd(e,t,n){let r=xe.x25519.getSharedSecret(e.x25519,n.ctClassical),o=_n.ml_kem768.decapsulate(n.ctPq,e.mlKem);return ji(o,r,n.ctClassical,t)}function fd(e){return(0,Tt.hkdf)(At.sha256,e,new Uint8Array(0),Pt(D.NDC_V03_CONTENT_KEY_DOMAIN),32)}function hd(e,t){return(0,Tt.hkdf)(At.sha256,e,t,Pt(D.NDC_V03_RATCHET_DOMAIN),32)}function md(){let{secretKey:e,publicKey:t}=xe.ed25519.keygen(),{publicKey:n,secretKey:r}=rt.ml_dsa65.keygen();return{publicKey:{ed25519:t,mlDsa:n},secretKey:{ed25519:e,mlDsa:r}}}function yd(e,t){return{ed25519:xe.ed25519.sign(t,e.ed25519),mlDsa:rt.ml_dsa65.sign(t,e.mlDsa)}}function gd(e,t,n){return xe.ed25519.verify(n.ed25519,t,e.ed25519)?rt.ml_dsa65.verify(n.mlDsa,t,e.mlDsa):!1}function _d(){let{publicKey:e,secretKey:t}=rt.ml_dsa65.keygen();return{publicKey:e,secretKey:t}}function bd(e,t){return rt.ml_dsa65.sign(t,e)}function vd(e,t,n){return rt.ml_dsa65.verify(n,t,e)}D.PQ_SIZES={X25519_PK:32,X25519_SK:32,ML_KEM_768_PK:1184,ML_KEM_768_SK:2400,ML_KEM_768_CT:1088,ED25519_PK:32,ED25519_SK:32,ED25519_SIG:64,ML_DSA_65_PK:1952,ML_DSA_65_SK:4032,ML_DSA_65_SIG:3309,HYBRID_SHARED_SECRET:32}});var vn=R($=>{"use strict";Object.defineProperty($,"__esModule",{value:!0});$.deriveContentKey=$.ContainerV3Error=$.CONTAINER_HEADER_MAX_BYTES=$.CONTAINER_FIXED_PREFIX_BYTES=$.CONTAINER_MAGIC=void 0;$.canonicalJson=bn;$.headerSigningBytes=Hr;$.signContainerHeader=Fi;$.verifyContainerHeader=Hi;$.encodeContainerV3=Ui;$.decodeContainerV3=Vi;$.sealHybrid=Ad;$.openHybrid=Td;var Sd=I("@noble/hashes/hkdf.js"),wd=I("@noble/hashes/sha2.js"),L=ot();Object.defineProperty($,"deriveContentKey",{enumerable:!0,get:function(){return L.deriveContentKey}});$.CONTAINER_MAGIC=new Uint8Array([78,68,76,66]);$.CONTAINER_FIXED_PREFIX_BYTES=8;$.CONTAINER_HEADER_MAX_BYTES=16777215;var kd="NDC-v0.3-wrap-key",F=class extends Error{constructor(t,n){super(n),this.name="ContainerV3Error",this.code=t}};$.ContainerV3Error=F;var _e=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},Mi=e=>{let t="";for(let n=0;n<e.length;n++)t+=e[n].toString(16).padStart(2,"0");return t};function bn(e){if(e===null||typeof e!="object")return JSON.stringify(e);if(Array.isArray(e))return"["+e.map(bn).join(",")+"]";let t=e;return"{"+Object.keys(t).sort().map(r=>JSON.stringify(r)+":"+bn(t[r])).join(",")+"}"}function Hr(e){let t={...e};return delete t.sig,new TextEncoder().encode(bn(t))}function Fi(e,t,n){let r=(0,L.hybridSign)(n.secretKey,Hr(e));return{...e,sig:{signer_kid:t,ed25519:_e(r.ed25519),ml_dsa_65:_e(r.mlDsa)}}}function Hi(e,t){let n={ed25519:Ke(e.sig.ed25519),mlDsa:Ke(e.sig.ml_dsa_65)};return(0,L.hybridVerify)(t,Hr(e),n)}var xd=["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 Ed(e){if(!e||typeof e!="object")throw new F("header_schema_mismatch","header is not an object");let t=e;for(let r of xd)if(t[r]===void 0)throw new F("header_schema_mismatch",`header missing required field: ${String(r)}`);if(t.format_version!==3)throw new F("unsupported_version",`format_version ${t.format_version} unknown`);if(t.profile!=="pq-hybrid")throw new F("suite_unknown",`profile must be 'pq-hybrid', got '${String(t.profile)}'`);let n=t.suite;if(n.kem!==L.PQ_SUITE.KEM||n.sig!==L.PQ_SUITE.SIG||n.aead!==L.PQ_SUITE.AEAD||n.kdf!==L.PQ_SUITE.KDF)throw new F("suite_unknown",`suite mismatch: viewer supports ${JSON.stringify(L.PQ_SUITE)}, header has ${JSON.stringify(n)}`)}function Ui(e,t){let n=new TextEncoder().encode(JSON.stringify(e));if(n.length>$.CONTAINER_HEADER_MAX_BYTES)throw new F("header_schema_mismatch",`header too large (${n.length} bytes; max 16 MB)`);let r=new Uint8Array($.CONTAINER_FIXED_PREFIX_BYTES+n.length+t.length);return r.set($.CONTAINER_MAGIC,0),r[4]=L.NDC_WIRE_V03,r[5]=n.length>>16&255,r[6]=n.length>>8&255,r[7]=n.length&255,r.set(n,$.CONTAINER_FIXED_PREFIX_BYTES),r.set(t,$.CONTAINER_FIXED_PREFIX_BYTES+n.length),r}function Vi(e){if(e.length<$.CONTAINER_FIXED_PREFIX_BYTES)throw new F("header_truncated",`container truncated: ${e.length} bytes (need \u2265 ${$.CONTAINER_FIXED_PREFIX_BYTES})`);for(let o=0;o<4;o++)if(e[o]!==$.CONTAINER_MAGIC[o])throw new F("bad_magic",`bad magic: expected NDLB, got ${Mi(e.slice(0,4))}`);if(e[4]!==L.NDC_WIRE_V03)throw new F("unsupported_version",`expected wire version 0x${L.NDC_WIRE_V03.toString(16)}, got 0x${e[4].toString(16)}`);let t=e[5]<<16|e[6]<<8|e[7],n=$.CONTAINER_FIXED_PREFIX_BYTES+t;if(e.length<n)throw new F("header_truncated",`header truncated: declared ${t}, only ${e.length-$.CONTAINER_FIXED_PREFIX_BYTES} bytes left`);let r;try{r=JSON.parse(new TextDecoder("utf-8").decode(e.slice($.CONTAINER_FIXED_PREFIX_BYTES,n)))}catch(o){throw new F("header_invalid_json",`header JSON parse failed: ${o.message}`)}return Ed(r),{header:r,ciphertextWithTag:e.slice(n)}}var Le=e=>e;async function Ki(e,t,n){let r=await crypto.subtle.importKey("raw",Le(e),{name:"AES-GCM"},!1,["encrypt"]),o=await crypto.subtle.encrypt({name:"AES-GCM",iv:Le(t)},r,Le(n));return new Uint8Array(o)}async function Li(e,t,n){let r=await crypto.subtle.importKey("raw",Le(e),{name:"AES-GCM"},!1,["decrypt"]),o=await crypto.subtle.decrypt({name:"AES-GCM",iv:Le(t)},r,Le(n));return new Uint8Array(o)}function Gi(e){return(0,Sd.hkdf)(wd.sha256,e,new Uint8Array(0),new TextEncoder().encode(kd),32)}async function Wi(e){let t=await crypto.subtle.digest("SHA-256",Le(e));return Mi(new Uint8Array(t))}async function Ad(e){let t=crypto.getRandomValues(new Uint8Array(32)),n=crypto.getRandomValues(new Uint8Array(12)),r=await Ki(t,n,e.plaintext),o=r.slice(r.length-16),i=r.slice(0,r.length-16),a=(0,L.hybridKemEncapsulate)(e.recipientPublicKey),s=Gi(a.sharedSecret),c=crypto.getRandomValues(new Uint8Array(12)),l=await Ki(s,c,t),u=await Wi(i),p={lockbox_id:e.meta.lockbox_id,format_version:3,profile:"pq-hybrid",suite:{kem:L.PQ_SUITE.KEM,sig:L.PQ_SUITE.SIG,aead:L.PQ_SUITE.AEAD,kdf:L.PQ_SUITE.KDF},server:e.meta.server,kem:{recipient_kid:e.recipientKid,ct_classical:_e(a.ciphertext.ctClassical),ct_pq:_e(a.ciphertext.ctPq),ephemeral_x25519_pk:_e(a.ephemeralX25519Pk)},wrapped_content_key:{wrapped:_e(l),wrap_iv:_e(c)},iv:_e(n),tag:_e(o),bearer:e.meta.bearer,dpop_required:e.meta.dpop_required,ratchet_state:e.meta.ratchet_state,tee_attestation_url:e.meta.tee_attestation_url,original_filename:e.meta.original_filename,original_content_type:e.meta.original_content_type,ciphertext_sha256:u,issued_at:new Date().toISOString(),cache_ttl_seconds:e.meta.cache_ttl_seconds},h=Fi(p,e.signerKid,e.signerKeypair),f=Ui(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 Td(e){let{header:t,ciphertextWithTag:n}=Vi(e.container);if(!Hi(t,e.signerPublicKey))throw new F("signature_invalid","hybrid signature verification failed");let r=n.slice(0,n.length-16),o=await Wi(r);if(o!==t.ciphertext_sha256)throw new F("integrity_mismatch",`ciphertext sha256 mismatch: expected ${t.ciphertext_sha256.slice(0,16)}\u2026, got ${o.slice(0,16)}\u2026`);let i={ctClassical:Ke(t.kem.ct_classical),ctPq:Ke(t.kem.ct_pq)},a=(0,L.hybridKemDecapsulate)(e.recipientSecretKey,e.recipientPublicX25519,i),s=Gi(a),c=Ke(t.wrapped_content_key.wrapped),l=Ke(t.wrapped_content_key.wrap_iv),u=await Li(s,l,c),p=Ke(t.iv),h=await Li(u,p,n);return u.fill(0),{plaintext:h,header:t}}});var Vr=R(at=>{"use strict";Object.defineProperty(at,"__esModule",{value:!0});at.publicJwkFromBytes=zi;at.jwkThumbprint=Ji;at.createDpop=Id;at.verifyDpop=$d;var qi=I("@noble/curves/ed25519.js"),Pd=I("@noble/hashes/sha2.js"),it=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,"_")},Sn=e=>{let t=e.replace(/-/g,"+").replace(/_/g,"/"),n=t.length%4?4-t.length%4:0,r=t+"=".repeat(n);if(typeof Buffer<"u")return new Uint8Array(Buffer.from(r,"base64"));let o=atob(r),i=new Uint8Array(o.length);for(let a=0;a<o.length;a++)i[a]=o.charCodeAt(a);return i},It=e=>new TextEncoder().encode(e);function zi(e){if(e.length!==32)throw new Error(`expected 32-byte Ed25519 public key, got ${e.length}`);return{kty:"OKP",crv:"Ed25519",x:it(e)}}function Ji(e){let t=`{"crv":"${e.crv}","kty":"${e.kty}","x":"${e.x}"}`,n=(0,Pd.sha256)(It(t));return it(n)}function Id(e){let n={typ:"dpop+jwt",alg:"EdDSA",jwk:zi(e.publicKey)},r={htm:e.htm.toUpperCase(),htu:Ur(e.htu),jti:e.jti??Dd(),iat:e.iat??Math.floor(Date.now()/1e3)};e.nonce&&(r.nonce=e.nonce);let o=it(It(JSON.stringify(n))),i=it(It(JSON.stringify(r))),a=`${o}.${i}`,s=qi.ed25519.sign(It(a),e.secretKey);return`${a}.${it(s)}`}function Dd(){return it(crypto.getRandomValues(new Uint8Array(16)))}function Ur(e){try{let t=new URL(e);return`${t.protocol}//${t.host}${t.pathname}`}catch{return e}}async function $d(e,t){let n=e.split(".");if(n.length!==3)return H("malformed","expected three JWT parts");let[r,o,i]=n,a;try{a=JSON.parse(new TextDecoder().decode(Sn(r)))}catch{return H("bad_header","header is not valid base64url JSON")}if(a.typ!=="dpop+jwt")return H("bad_typ",`typ must be 'dpop+jwt', got '${String(a.typ)}'`);if(a.alg!=="EdDSA")return H("bad_alg",`alg must be 'EdDSA', got '${String(a.alg)}'`);if(!a.jwk||a.jwk.kty!=="OKP"||a.jwk.crv!=="Ed25519")return H("bad_header","jwk must be an Ed25519 OKP key");let s=Ji(a.jwk);if(s!==t.expectedJkt)return H("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(Sn(o)))}catch{return H("bad_payload","payload is not valid base64url JSON")}if(c.htm!==t.expectedHtm.toUpperCase())return H("htm_mismatch",`htm '${c.htm}' \u2260 expected '${t.expectedHtm.toUpperCase()}'`);if(c.htu!==Ur(t.expectedHtu))return H("htu_mismatch",`htu '${c.htu}' \u2260 expected '${Ur(t.expectedHtu)}'`);if(t.expectedNonce!==void 0&&c.nonce!==t.expectedNonce)return H("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 H("bad_payload","iat missing or not a number");if(c.iat>l+5)return H("iat_in_future",`iat ${c.iat} > now+skew`);if(l-c.iat>u)return H("iat_too_old",`iat ${c.iat} older than ${u}s`);let p;try{p=Sn(a.jwk.x)}catch{return H("bad_header","jwk.x is not base64url")}let h=Sn(i),f=It(`${r}.${o}`);return qi.ed25519.verify(h,f,p)?await t.isJtiFresh(c.jti)?{ok:!0,jti:c.jti,iat:c.iat}:H("replay",`jti ${c.jti} was already seen`):H("signature_invalid","Ed25519 signature does not verify")}function H(e,t){return{ok:!1,code:e,reason:t}}});var na=R(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=Cd;E.uuidFromDeltaId=Bd;E.originJktForPublicKey=$t;E.encodePveSignedBytes=Zi;E.signPve=jd;E.parsePve=Qi;E.pveHash=Kd;E.verifyPve=Ld;E.encodeReceiptSignedBytes=ea;E.signReceipt=Md;E.parseReceipt=ta;E.verifyReceipt=Fd;var wn=I("@noble/curves/ed25519.js"),Nd=I("@noble/hashes/sha2.js"),Yi=Vr();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 Xi=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 Rd(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 Od(e){let t=e.replace(/-/g,"+").replace(/_/g,"/"),n=t.length%4?4-t.length%4:0,r=t+"=".repeat(n);if(typeof Buffer<"u")return new Uint8Array(Buffer.from(r,"base64"));let o=atob(r),i=new Uint8Array(o.length);for(let a=0;a<o.length;a++)i[a]=o.charCodeAt(a);return i}function qr(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 Gr(e){if(e==null)return Xi;if(e instanceof Uint8Array){if(e.length!==32)throw new Error(`jkt bytes must be 32, got ${e.length}`);return e}let t=Od(e);if(t.length!==32)throw new Error(`jkt must decode to 32 bytes, got ${t.length}`);return t}function Wr(e){return Dt(e)?null:Rd(e)}function Cd(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 Bd(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 $t(e){return(0,Yi.jwkThumbprint)((0,Yi.publicJwkFromBytes)(e))}function Zi(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(Gr(e.originJkt),r),r+=32,t.set(Gr(e.destJkt??null),r),r+=32,t.set(e.prevDeltaHash??Xi,r),r+=32,n.setUint16(r,e.classification,!1),r+=2,n.setBigUint64(r,BigInt(e.issuedAt),!1),r+=8,t}function jd(e,t){let n=$t(e.originPublicKey),r=Zi({deltaKind:e.deltaKind,deltaId:e.deltaId,ciphertextSha256:e.ciphertextSha256,originJkt:n,destJkt:e.destJkt??null,prevDeltaHash:e.prevDeltaHash??null,classification:e.classification,issuedAt:e.issuedAt??Date.now()}),o=wn.ed25519.sign(r,t),i=new Uint8Array(E.PVE_TOTAL_LEN);return i.set(r,0),i.set(o,E.PVE_SIGNED_LEN),i}function Qi(e){if(e.length!==E.PVE_TOTAL_LEN)throw new Error(`PVE must be ${E.PVE_TOTAL_LEN} bytes, got ${e.length}`);if(!qr(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 o=e[n];n+=1;let i=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),y=Wr(s);if(y===null)throw new Error("origin_jkt must not be zero");return{fields:{version:r,deltaKind:o,deltaId:i,ciphertextSha256:a,originJkt:y,destJkt:Wr(c),prevDeltaHash:Dt(l)?null:l,classification:u,issuedAt:p},signedBytes:h,originSig:f,broadcast:Dt(c),genesis:Dt(l)}}function Kd(e){return(0,Nd.sha256)(e)}function Ld(e,t){let n;try{n=Qi(e)}catch(o){let i=o instanceof Error?o.message:String(o);return i.includes("magic")?{ok:!1,code:"bad_magic",reason:i}:{ok:!1,code:"malformed",reason:i}}if(n.fields.version!==E.PVE_VERSION)return{ok:!1,code:"bad_version",reason:`unsupported PVE version ${n.fields.version}`};let r;try{r=$t(t)}catch(o){return{ok:!1,code:"malformed",reason:o instanceof Error?o.message:String(o)}}return r!==n.fields.originJkt?{ok:!1,code:"jkt_mismatch",reason:`presented key thumbprint ${r.slice(0,12)}\u2026 \u2260 committed origin_jkt ${n.fields.originJkt.slice(0,12)}\u2026`}:wn.ed25519.verify(n.originSig,n.signedBytes,t)?{ok:!0,parsed:n}:{ok:!1,code:"signature_invalid",reason:"Ed25519 origin signature does not verify"}}function ea(e){if(e.pveHash.length!==32)throw new Error("pve_hash must be 32 bytes");let t=Gr(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),o=0;return n.set(E.RCPT_MAGIC,o),o+=4,n[o]=E.RCPT_VERSION,o+=1,n.set(e.pveHash,o),o+=32,n.set(t,o),o+=32,n[o]=e.absorbStatus,o+=1,r.setBigUint64(o,BigInt(e.absorbedAt),!1),o+=8,n}function Md(e,t){let n=$t(e.destPublicKey),r=ea({pveHash:e.pveHash,destJkt:n,absorbStatus:e.absorbStatus,absorbedAt:e.absorbedAt??Date.now()}),o=wn.ed25519.sign(r,t),i=new Uint8Array(E.RCPT_TOTAL_LEN);return i.set(r,0),i.set(o,E.RCPT_SIGNED_LEN),i}function ta(e){if(e.length!==E.RCPT_TOTAL_LEN)throw new Error(`receipt must be ${E.RCPT_TOTAL_LEN} bytes, got ${e.length}`);if(!qr(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 o=e.slice(n,n+32);n+=32;let i=e.slice(n,n+32);n+=32;let a=e[n];n+=1;let s=Number(t.getBigUint64(n,!1));n+=8;let c=Wr(i);if(c===null)throw new Error("receipt dest_jkt must not be zero");return{fields:{version:r,pveHash:o,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 Fd(e,t,n){let r;try{r=ta(e)}catch(i){let a=i instanceof Error?i.message:String(i);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 o;try{o=$t(t)}catch(i){return{ok:!1,code:"malformed",reason:i instanceof Error?i.message:String(i)}}return o!==r.fields.destJkt?{ok:!1,code:"jkt_mismatch",reason:`presented key thumbprint ${o.slice(0,12)}\u2026 \u2260 committed dest_jkt ${r.fields.destJkt.slice(0,12)}\u2026`}:n!==void 0&&!qr(n,r.fields.pveHash)?{ok:!1,code:"pve_hash_mismatch",reason:"receipt does not acknowledge the expected PVE"}:wn.ed25519.verify(r.destSig,r.signedBytes,t)?{ok:!0,parsed:r}:{ok:!1,code:"signature_invalid",reason:"Ed25519 destination signature does not verify"}}});var oa=R(Nt=>{"use strict";Object.defineProperty(Nt,"__esModule",{value:!0});Nt.stepRatchet=Hd;Nt.replayRatchet=Ud;Nt.destroyKey=Vd;var ra=ot();function Hd(e,t){if(t.length!==32)throw new Error(`ratchet token must be 32 bytes, got ${t.length}`);return{nextContentKey:(0,ra.ratchetAdvance)(e.contentKey,t),openCount:e.openCount+1}}function Ud(e,t){let n=[e],r=e;for(let o of t)r=(0,ra.ratchetAdvance)(r,o),n.push(r);return n}function Vd(e){e.fill(0)}});var Yr=R(st=>{"use strict";Object.defineProperty(st,"__esModule",{value:!0});st.__coseInternals=void 0;st.verifyCoseSign1Es384=qd;st.decodeAttestationPayload=zd;var Gd=I("@noble/curves/nist.js"),Wd=I("@noble/hashes/sha2.js"),zr=class{constructor(t){this.b=t,this.p=0}u8(){if(this.p>=this.b.length)throw new Error("cbor: truncated");return this.b[this.p++]}uN(t){let n=0;for(let r=0;r<t;r++)n=n*256+this.u8();return n}len(t){if(t<24)return t;if(t===24)return this.u8();if(t===25)return this.uN(2);if(t===26)return this.uN(4);if(t===27){let n=this.uN(4),r=this.uN(4);return n*4294967296+r}throw new Error(`cbor: unsupported additional info ${t}`)}read(){let t=this.u8(),n=t>>5,r=t&31;switch(n){case 0:return this.len(r);case 1:return-1-this.len(r);case 2:{let o=this.len(r),i=this.b.subarray(this.p,this.p+o);if(i.length!==o)throw new Error("cbor: bstr truncated");return this.p+=o,i.slice()}case 3:{let o=this.len(r),i=this.b.subarray(this.p,this.p+o);if(i.length!==o)throw new Error("cbor: tstr truncated");return this.p+=o,new TextDecoder("utf-8").decode(i)}case 4:{let o=this.len(r),i=[];for(let a=0;a<o;a++)i.push(this.read());return i}case 5:{let o=this.len(r),i=new Map;for(let a=0;a<o;a++){let s=this.read(),c=this.read();i.set(s,c)}return i}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 Jr(e){return new zr(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 En(...e){let t=e.reduce((o,i)=>o+i.length,0),n=new Uint8Array(t),r=0;for(let o of e)n.set(o,r),r+=o.length;return n}function kn(e){return En(xn(2,e.length),e)}function ia(e){let t=new TextEncoder().encode(e);return En(xn(3,t.length),t)}function aa(e,t){return En(xn(4,4),ia("Signature1"),kn(e),kn(new Uint8Array(0)),kn(t))}function qd(e,t){let n;try{n=Jr(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,,o,i]=n;if(!(r instanceof Uint8Array))return{ok:!1,code:"bad_structure",reason:"protected header must be a byte string"};if(!(o instanceof Uint8Array)||o.length===0)return{ok:!1,code:"no_payload",reason:"detached/empty payload is not supported"};if(!(i instanceof Uint8Array))return{ok:!1,code:"bad_structure",reason:"signature must be a byte string"};if(i.length!==96)return{ok:!1,code:"bad_signature_len",reason:`expected 96-byte ES384 sig, got ${i.length}`};let a=aa(r,o),s=(0,Wd.sha384)(a),c=!1;try{c=Gd.p384.verify(i,s,t,{prehash:!1})}catch(l){return{ok:!1,code:"signature_invalid",reason:`verify threw: ${l.message}`}}return c?{ok:!0,payload:o}:{ok:!1,code:"signature_invalid",reason:"ECDSA P-384 verification failed"}}function zd(e){try{let t=Jr(e);return t instanceof Map?t:null}catch{return null}}st.__coseInternals={sig1Structure:aa,encBstr:kn,encText:ia,encHead:xn,concat:En,decodeCbor:Jr}});var sa=R(Rt=>{"use strict";Object.defineProperty(Rt,"__esModule",{value:!0});Rt.parseAttestation=Yd;Rt.verifyAttestation=Xd;Rt.fetchAttestation=Zd;var Jd=Yr();function Yd(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 Xd(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[i,a]of Object.entries(t.pcrs))if(e.pcrs[i]!==a)return{ok:!1,code:"pcr_mismatch",reason:`PCR ${i}: got '${(e.pcrs[i]??"").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 o=!1;if(t.cose){if(!t.trustedLeafPubKey)return{ok:!1,code:"signature_invalid",reason:"cose supplied without trustedLeafPubKey \u2014 cannot verify, refusing"};let i=(0,Jd.verifyCoseSign1Es384)(t.cose,t.trustedLeafPubKey);if(!i.ok)return{ok:!1,code:"signature_invalid",reason:`cose: ${i.code}: ${i.reason}`};o=!0}return{ok:!0,vendor:e.vendor,module_id:e.module_id,signature_verified:o}}async function Zd(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 da=R(ct=>{"use strict";Object.defineProperty(ct,"__esModule",{value:!0});ct.splitSecret=nu;ct.combineShares=ru;ct.serializeShare=au;ct.deserializeShare=su;var Me=null,Fe=null;function ca(){if(Me&&Fe)return;Me=new Uint8Array(512),Fe=new Uint8Array(256);let e=1;for(let t=0;t<255;t++){Me[t]=e,Fe[e]=t;let n=e<<1;n&256&&(n^=283),n^=e,e=n&255}for(let t=255;t<512;t++)Me[t]=Me[t-255]}function An(e,t){return e===0||t===0?0:(ca(),Me[Fe[e]+Fe[t]])}function Qd(e,t){if(e===0)return 0;if(t===0)throw new Error("division by zero in GF(2^8)");ca();let n=Fe[e]-Fe[t];return Me[n<0?n+255:n]}function la(e,t){return e^t}function eu(e,t){let n=0;for(let r=e.length-1;r>=0;r--)n=la(An(n,t),e[r]);return n}var tu=e=>crypto.getRandomValues(new Uint8Array(e));function nu(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??tu,r=[];for(let o=1;o<=t.n;o++)r.push({x:o,y:new Uint8Array(e.length)});for(let o=0;o<e.length;o++){let i=new Uint8Array(t.k);i[0]=e[o];let a=n(t.k-1);for(let s=1;s<t.k;s++)i[s]=a[s-1];for(let s=0;s<t.n;s++)r[s].y[o]=eu(i,r[s].x)}return r}function ru(e){if(e.length<2)throw new Error("need at least 2 shares to reconstruct");let t=e[0].y.length;for(let o of e){if(o.y.length!==t)throw new Error("shares have inconsistent length");if(o.x===0)throw new Error("share x must not be 0")}let n=new Set;for(let o of e){if(n.has(o.x))throw new Error(`duplicate share x=${o.x}`);n.add(o.x)}let r=new Uint8Array(t);for(let o=0;o<t;o++){let i=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=An(s,e[u].x),c=An(c,e[a].x^e[u].x));let l=Qd(s,c);i=la(i,An(e[a].y[o],l))}r[o]=i}return r}var ou=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)},iu=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 au(e){return{x:e.x,y_b64:ou(e.y)}}function su(e){return{x:e.x,y:iu(e.y_b64)}}});var ha=R(Ee=>{"use strict";Object.defineProperty(Ee,"__esModule",{value:!0});Ee.SegmentError=void 0;Ee.sealSegments=pu;Ee.openSegments=fu;Ee.manifestDigest=hu;Ee.buildCapability=mu;var Xr=I("@noble/hashes/sha2.js"),cu="pq-hybrid-segments",lu="AES-256-GCM",lt=e=>e,ua=e=>{if(typeof Buffer<"u")return Buffer.from(e).toString("base64");let t="";for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return btoa(t)},pa=e=>{if(typeof Buffer<"u")return new Uint8Array(Buffer.from(e,"base64"));let t=atob(e),n=new Uint8Array(t.length);for(let r=0;r<t.length;r++)n[r]=t.charCodeAt(r);return n},fa=e=>{let t="";for(let n=0;n<e.length;n++)t+=e[n].toString(16).padStart(2,"0");return t};async function du(e,t,n){let r=await crypto.subtle.importKey("raw",lt(e),{name:"AES-GCM"},!1,["encrypt"]),o=await crypto.subtle.encrypt({name:"AES-GCM",iv:lt(t)},r,lt(n));return new Uint8Array(o)}async function uu(e,t,n){let r=await crypto.subtle.importKey("raw",lt(e),{name:"AES-GCM"},!1,["decrypt"]),o=await crypto.subtle.decrypt({name:"AES-GCM",iv:lt(t)},r,lt(n));return new Uint8Array(o)}var He=class extends Error{constructor(t,n){super(n),this.name="SegmentError",this.code=t}};Ee.SegmentError=He;async function pu(e){let t=new Set;for(let o of e){if(t.has(o.segment_id))throw new He("duplicate_segment_id",`segment_id '${o.segment_id}' appears twice`);t.add(o.segment_id)}let n=[],r=[];for(let o of e){let i=crypto.getRandomValues(new Uint8Array(32)),a=crypto.getRandomValues(new Uint8Array(12)),s=await du(i,a,o.plaintext),c=s.slice(0,s.length-16),l=fa((0,Xr.sha256)(c));n.push({segment_id:o.segment_id,key:i}),r.push({segment_id:o.segment_id,label:o.label,content_type:o.content_type,iv_b64:ua(a),ciphertext_b64:ua(s),ciphertext_sha256:l})}return{manifest:{profile:cu,aead:lu,segments:r},keys:n}}async function fu(e,t){let n=new Map;for(let o of t.keys)n.set(o.segment_id,o.key);let r=[];for(let o of e.segments){if(!t.allowed_segment_ids.includes(o.segment_id))continue;let i=n.get(o.segment_id);if(!i)throw new He("key_missing",`capability lists ${o.segment_id} as allowed but holds no key for it`);let a=pa(o.ciphertext_b64),s=a.slice(0,a.length-16);if(fa((0,Xr.sha256)(s))!==o.ciphertext_sha256)throw new He("integrity_mismatch",`segment ${o.segment_id}: ciphertext sha256 mismatch`);let l=pa(o.iv_b64),u=await uu(i,l,a);r.push({segment_id:o.segment_id,label:o.label,content_type:o.content_type,plaintext:u})}return r}function hu(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,Xr.sha256)(new TextEncoder().encode(n))}function mu(e,t,n){let r=new Set(t),o=n.filter(i=>r.has(i.segment_id));if(o.length!==t.length){let i=t.filter(a=>!o.find(s=>s.segment_id===a));throw new He("segment_not_found",`cannot build capability \u2014 no key for: ${i.join(", ")}`)}return{recipient_kid:e,allowed_segment_ids:t,keys:o}}});var ga=R(Ot=>{"use strict";Object.defineProperty(Ot,"__esModule",{value:!0});Ot.computeWatermark=ya;Ot.findLeakSource=_u;Ot.watermarkSvgOverlay=bu;var yu=I("@noble/hashes/hmac.js"),gu=I("@noble/hashes/sha2.js");function ya(e){let t=[e.recipientId,e.lockboxId,String(e.openCount),String(e.iat)].join("|"),n=(0,yu.hmac)(gu.sha256,e.tenantSecret,new TextEncoder().encode(t)),r=ma(n.slice(0,16)),o=ma(n.slice(0,4)),i=new Date(e.iat*1e3).toISOString().slice(0,10),a=`${e.recipientId} \xB7 ${i} \xB7 ${o}`;return{short_hex:o,full_hex:r,display_label:a}}function _u(e,t,n){let r=e.toLowerCase();for(let o of n){let i=ya({tenantSecret:t,...o});if(r===i.full_hex)return{matched:!0,candidate:o,matched_on:"full_hex"};if(r===i.short_hex)return{matched:!0,candidate:o,matched_on:"short_hex"}}return{matched:!1,reason:"no_candidate_matched"}}function bu(e,t){let n=t?.width??800,r=t?.height??1e3,o=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="${o}" font-family="Helvetica, Arial, sans-serif" font-size="20" text-anchor="middle">
|
|
10
|
-
<text x="${n/2}" y="${r*.2}" transform="rotate(-30 ${n/2} ${r*.2})">${
|
|
11
|
-
<text x="${n/2}" y="${r*.5}" transform="rotate(-30 ${n/2} ${r*.5})">${
|
|
12
|
-
<text x="${n/2}" y="${r*.8}" transform="rotate(-30 ${n/2} ${r*.8})">${
|
|
10
|
+
<text x="${n/2}" y="${r*.2}" transform="rotate(-30 ${n/2} ${r*.2})">${a}</text>
|
|
11
|
+
<text x="${n/2}" y="${r*.5}" transform="rotate(-30 ${n/2} ${r*.5})">${a}</text>
|
|
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="${o*2}" text-anchor="end">${e.short_hex}</text>
|
|
15
|
-
</svg>`}function ea(e){let t="";for(let n=0;n<e.length;n++)t+=e[n].toString(16).padStart(2,"0");return t}});var la=N(q=>{"use strict";Object.defineProperty(q,"__esModule",{value:!0});q.DRAND_LOE_MAINNET=q.TimeGateError=void 0;q.timeGateEncrypt=sl;q.timeGateDecrypt=cl;q.roundForTime=ll;q.timeForRound=dl;q.drandTimeLockEncrypt=pl;q.drandTimeLockDecrypt=sa;q.makeFakeDrandChain=fl;q.fetchDrandRound=ca;q.drandTimeLockOpen=yl;var le=T("@noble/curves/bls12-381.js"),Zt=T("@noble/hashes/sha2.js"),ve=e=>e,oa="NDC-v0.3-server-time-gate";async function sl(e){let t=crypto.getRandomValues(new Uint8Array(12)),n=new TextEncoder().encode(`${oa}|${e.notBeforeUnixSec}`),r=await crypto.subtle.importKey("raw",ve(e.serverWrapKey),{name:"AES-GCM"},!1,["encrypt"]),o=await crypto.subtle.encrypt({name:"AES-GCM",iv:ve(t),additionalData:ve(n)},r,ve(e.plaintext));return{variant:"server-attested",notBeforeUnixSec:e.notBeforeUnixSec,iv_b64:Yt(t),ciphertext_b64:Yt(new Uint8Array(o))}}var vt=class extends Error{constructor(t,n){super(n),this.name="TimeGateError",this.code=t}};q.TimeGateError=vt;async function cl(e){if(e.currentUnixSec<e.ciphertext.notBeforeUnixSec)throw new vt("not_yet",`time-gate not yet open: now ${e.currentUnixSec} < notBefore ${e.ciphertext.notBeforeUnixSec}`);let t=new TextEncoder().encode(`${oa}|${e.ciphertext.notBeforeUnixSec}`),n=await crypto.subtle.importKey("raw",ve(e.serverWrapKey),{name:"AES-GCM"},!1,["decrypt"]);try{let r=await crypto.subtle.decrypt({name:"AES-GCM",iv:ve(Xt(e.ciphertext.iv_b64)),additionalData:ve(t)},n,ve(Xt(e.ciphertext.ciphertext_b64)));return new Uint8Array(r)}catch{throw new vt("tamper_detected","AES-GCM authentication tag failed \u2014 ciphertext or AAD tampered")}}q.DRAND_LOE_MAINNET={publicKeyHex:"868f005eb8e6e4ca0a47c8a77ceaa5309a47978a7c71bc5cce96366b5d7a569937c529eeda66c7293784a9402801af31",chainHashHex:"8990e7a9aaed2ffed73dbd7092123d6f289930540d7651336225dc172e51b2ce",genesisUnixSec:1595431050,periodSec:30,hashDst:"BLS_SIG_BLS12381G2_XMD:SHA-256_SSWU_RO_NUL_"};function ll(e,t){return e<=t.genesisUnixSec?1:Math.ceil((e-t.genesisUnixSec)/t.periodSec)}function dl(e,t){return t.genesisUnixSec+e*t.periodSec}function aa(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,Zt.sha256)(t)}function ia(e){let t=new Uint8Array(576),n=0;for(let r of[e.c0,e.c1])for(let o of[r.c0,r.c1,r.c2])for(let a of[o.c0,o.c1])ul(a,t,n,48),n+=48;return t}function ul(e,t,n,r){let o=e,a=BigInt(255),i=BigInt(8);for(let s=r-1;s>=0;s--)t[n+s]=Number(o&a),o>>=i}function pl(e,t,n,r){if(e.length!==32)throw new Error(`drand-IBE expects a 32-byte content key, got ${e.length}`);let o=le.bls12_381.G1.Point,a=le.bls12_381.fields.Fr,i=o.fromBytes(n),s;do s=ml(crypto.getRandomValues(new Uint8Array(32)))%a.ORDER;while(s===BigInt(0));let c=o.BASE.multiply(s),d=le.bls12_381.longSignatures.hash(aa(t),r.hashDst),u=i.multiply(s),p=le.bls12_381.pairing(u,d,!0),f=(0,Zt.sha256)(ia(p)),y=new Uint8Array(32);for(let b=0;b<32;b++)y[b]=e[b]^f[b];return{variant:"drand-ibe",chainHashHex:r.chainHashHex,round:t,u_b64:Yt(c.toBytes()),v_b64:Yt(y)}}function sa(e){if(e.ciphertext.variant!=="drand-ibe")throw new Error("not a drand-IBE ciphertext");if(e.ciphertext.chainHashHex!==e.chain.chainHashHex)throw new Error("chain hash mismatch \u2014 ciphertext sealed to a different drand chain");let n=le.bls12_381.G1.Point.fromBytes(Xt(e.ciphertext.u_b64)),r=le.bls12_381.longSignatures.Signature.fromBytes(e.roundSignature),o=le.bls12_381.pairing(n,r,!0),a=(0,Zt.sha256)(ia(o)),i=Xt(e.ciphertext.v_b64);if(i.length!==32)throw new Error("drand-IBE V must be 32 bytes");let s=new Uint8Array(32);for(let c=0;c<32;c++)s[c]=i[c]^a[c];return s}function fl(e){let t;if(e&&e.length===48)t=e;else{t=new Uint8Array(48);let a=e??crypto.getRandomValues(new Uint8Array(48));t.set(a.slice(0,48),0)}let{secretKey:n,publicKey:r}=le.bls12_381.longSignatures.keygen(t),o={publicKeyHex:ra(r.toBytes()),chainHashHex:ra((0,Zt.sha256)(r.toBytes())),genesisUnixSec:17e8,periodSec:30,hashDst:"BLS_SIG_BLS12381G2_XMD:SHA-256_SSWU_RO_NUL_"};return{config:o,publicKey:r.toBytes(),signRound(a){let i=le.bls12_381.longSignatures.hash(aa(a),o.hashDst);return le.bls12_381.longSignatures.sign(i,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 hl(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 ca(e,t,n={}){let r=n.fetchImpl??fetch,o=n.timeoutMs??8e3,a=`${t.replace(/\/$/,"")}/public/${e}`,i,s;typeof AbortController<"u"&&(i=new AbortController,s=setTimeout(()=>i.abort(),o));let c;try{c=await r(a,{signal:i?.signal})}finally{s&&clearTimeout(s)}if(!c.ok)throw new Error(`drand fetch failed: ${a} \u2192 HTTP ${c.status}`);let d=await c.json();if(typeof d.round!="number"||typeof d.signature!="string"||typeof d.randomness!="string")throw new Error(`drand response malformed at ${a}`);let u=hl(d.signature);if(u.length!==96)throw new Error(`drand signature wrong length: expected 96 bytes (compressed G2), got ${u.length}`);return{round:d.round,randomness_hex:d.randomness,signature_bytes:u,previous_signature_hex:d.previous_signature}}async function yl(e,t,n,r={}){let o=await ca(e.round,t,r);return sa({ciphertext:e,roundSignature:o.signature_bytes,chain:n})}function Yt(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 Xt(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 ml(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(te=>{"use strict";Object.defineProperty(te,"__esModule",{value:!0});te.GENESIS_PREV_HASH=void 0;te.receiptHash=ur;te.issueReceipt=pr;te.verifyReceipt=fa;te.auditChain=bl;te.issueGenesisReceipt=Sl;te.appendReceipt=wl;var gl=T("@noble/hashes/sha2.js"),dr=Ht(),pa=We();te.GENESIS_PREV_HASH="0".repeat(64);var da=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)},ua=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},_l=e=>{let t="";for(let n=0;n<e.length;n++)t+=e[n].toString(16).padStart(2,"0");return t};function ur(e){return _l((0,gl.sha256)(new TextEncoder().encode((0,dr.canonicalJson)(e))))}function pr(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,dr.canonicalJson)(t)),r=(0,pa.hybridSign)(e.signing_key.secretKey,n);return{body:t,sig:{signer_kid:e.signer_kid,ed25519_b64:da(r.ed25519),ml_dsa_65_b64:da(r.mlDsa)}}}function fa(e,t){let n=new TextEncoder().encode((0,dr.canonicalJson)(e.body)),r={ed25519:ua(e.sig.ed25519_b64),mlDsa:ua(e.sig.ml_dsa_65_b64)};return(0,pa.hybridVerify)(t,n,r)}function bl(e,t,n=1){if(e.length===0)return{ok:!0,receipts_checked:0};let r=n,o=n===1?te.GENESIS_PREV_HASH:null;for(let a of e){if(a.body.sequence!==r)return{ok:!1,code:a.body.sequence<r?"duplicate_sequence":"out_of_order",at_sequence:a.body.sequence,reason:`expected sequence ${r}, got ${a.body.sequence}`};if(o!==null&&a.body.prev_hash!==o)return{ok:!1,code:r===1?"missing_genesis":"broken_prev_hash",at_sequence:a.body.sequence,reason:`prev_hash mismatch: expected ${o.slice(0,16)}\u2026, got ${a.body.prev_hash.slice(0,16)}\u2026`};if(!fa(a,t))return{ok:!1,code:"bad_signature",at_sequence:a.body.sequence,reason:"hybrid signature does not verify"};o=ur(a.body),r+=1}return{ok:!0,receipts_checked:e.length}}function Sl(e){return pr({event_type:e.initial_event,lockbox_id:e.lockbox_id,prev_hash:te.GENESIS_PREV_HASH,sequence:1,payload:e.initial_payload,signer_kid:e.signer_kid,signing_key:e.signing_key,iat:e.iat})}function wl(e,t){return pr({...t,prev_hash:ur(e.body),sequence:e.body.sequence+1})}});var ma=N(Qt=>{"use strict";Object.defineProperty(Qt,"__esModule",{value:!0});Qt.recommend=Tl;Qt.summarise=Pl;var vl={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"}},El={"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}},kl={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"]}},xl=[{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"}],ya={"mode-4":1,"mode-4p":2,"mode-4h":3,"mode-6":4};function Al(e,t){return ya[e]>=ya[t]?e:t}function Tl(e){let t=vl[e.orgType],n=El[e.fileClass],r=kl[e.channel],o=Al(t.mode,n.minMode);e.recipientLacksPasskey&&o==="mode-4h"&&(o="mode-4p");let a=Math.min(t.ttlSeconds,n.maxTtlSeconds),i={forensicWatermark:t.forensicWatermark||n.watermarkRequired,selectiveDisclosureSegments:n.selectiveDisclosure||!!e.perRecipientPolicy,thresholdKofN:e.multipleApproversRequired??null,teeAttestation:t.teeAttestation||n.teeRequired,perOpenRatchet:o==="mode-4h"||o==="mode-4p"||o==="mode-6",dpopRequired:o!=="mode-4",timelockDrand:!!e.timeLockUnixSec&&!!e.timeLockDecentralized,timelockServerGate:!!e.timeLockUnixSec&&!e.timeLockDecentralized},s={...r,adapterCandidates:[...r.adapters]},c=[...s.notes],d=xl.find(u=>u.channel===e.channel&&u.fileClass===e.fileClass);return d&&(c.unshift(`\u26A0 ${d.note}`),s.deliveryMode==="attachment"&&(s.deliveryMode="link")),e.fileClass==="live-ops-data"&&e.channel==="email"&&c.push("Live ops data over email is non-standard; consider webhook-push or web-portal."),{sensitivityMode:o,cacheTtlSeconds:a,features:i,delivery:{deliveryMode:s.deliveryMode,adapterCandidates:s.adapterCandidates},notes:c}}function Pl(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 _a=N(Qe=>{"use strict";Object.defineProperty(Qe,"__esModule",{value:!0});Qe.recommendationToMandate=Cl;Qe.v3SealReceiptPayload=Rl;Qe.v3OpenReceiptPayload=$l;Qe.showcaseChips=Bl;function Dl(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 Ol(e){return e.features.dpopRequired?"device_mfa":e.sensitivityMode==="mode-4h"?"first_device":e.sensitivityMode==="mode-4"?"any":"first_device"}function Il(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 Nl(e){let t=ga(e);return t==="m365"?"m365_only":t==="in_app"?"in_app":"any"}function Cl(e){let{recommendation:t,source:n}=e,r=t.sensitivityMode==="mode-6",o=n.timeLockUnixSec?new Date(n.timeLockUnixSec*1e3).toISOString():null;return{time:{ttl_seconds:t.cacheTtlSeconds,burn_after_first_read:r,unlock_at:o,max_opens:r?1:null},identity:{capture:Dl(t.sensitivityMode),claim_required:t.sensitivityMode!=="mode-4",allow_magic_link:t.sensitivityMode==="mode-4",allowed_emails:null},device:{binding:Ol(t),listed_fingerprints:null},channel:{delivery:Il(t),route:ga(t),channel_constraint:Nl(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 Rl(e){return{event_kind:"ndc_v3_sealed",lockbox_id:e.lockbox_id,ciphertext_sha256:e.ciphertext_sha256,recipient_kid:e.recipient_kid,signer_kid:e.signer_kid,mandate:e.mandate,bytes_sealed:e.bytes_sealed,issued_at:e.issued_at??new Date().toISOString()}}function $l(e){return{event_kind:"ndc_v3_opened",lockbox_id:e.lockbox_id,ratchet_sequence:e.ratchet_sequence,dpop_jkt:e.dpop_jkt,ip_hash:e.ip_hash,opened_at:e.opened_at??new Date().toISOString()}}function Bl(e){let t=[],n=e.ndc_v3_extensions;return t.push("PQ-hybrid"),n.dpop_required&&t.push("DPoP"),n.ratchet_enabled&&t.push("per-open ratchet"),e.watermark.forensic&&t.push("forensic watermark"),n.segments_enabled&&t.push("selective disclosure"),n.threshold_k_of_n&&t.push(`${n.threshold_k_of_n.k}-of-${n.threshold_k_of_n.n} quorum`),n.tee_attestation_required&&t.push("TEE attest"),n.timelock_drand?t.push("drand time-lock"):n.timelock_server_gate&&t.push("server time-gate"),e.time.burn_after_first_read&&t.push("burn-after-read"),t}});var Ea=N(de=>{"use strict";Object.defineProperty(de,"__esModule",{value:!0});de.encodeFragment=va;de.decodeFragment=Kl;de.extractProofToken=jl;de.encodeProofToken=Ml;de.decodeShareCredential=Ll;de.sealBytesForPublicShare=Hl;de.openPublicShare=Vl;de.wrapFragmentForShortLink=Gl;var ba=We(),Sa=Ht();function Ee(e){let t="";for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return btoa(t)}function Et(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 wa(e){return Ee(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function va(e){return encodeURIComponent(JSON.stringify(e))}function Kl(e){let t=JSON.parse(decodeURIComponent(e));if(t.v!==3)throw new Error(`fragment version unsupported: ${t.v}`);return t}function jl(e){return{v:3,kind:"proof",n:e.n,t:e.t,spe:e.spe,spm:e.spm}}function Ml(e){return encodeURIComponent(JSON.stringify(e))}function Ll(e){let t=e.trim(),n=t.indexOf("#"),r=n>=0?t.slice(n+1):t,o;try{o=JSON.parse(decodeURIComponent(r))}catch(a){throw new Error(`credential parse failed: ${a.message??"invalid_json"}`)}if(o.v!==3)throw new Error(`credential version unsupported: ${String(o.v)}`);return o.kind==="proof"?{kind:"proof",value:o}:{kind:"fragment",value:o}}function Fl(){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 Ul(){let e=new Uint8Array(32);return crypto.getRandomValues(e),wa(e)}async function Hl(e){let t=e.bytes,n={name:e.filename,type:e.contentType},r=(0,ba.generateHybridKemKeypair)(),o=(0,ba.generateHybridSigKeypair)(),a=Fl(),i=Ul(),s=await(0,Sa.sealHybrid)({plaintext:t,recipientPublicKey:r.publicKey,recipientKid:`ephemeral-${a}`,signerKeypair:o,signerKid:`lock-${a}`,meta:{lockbox_id:a,server:e.server,bearer:i,original_filename:n.name,original_content_type:n.type||"application/octet-stream",cache_ttl_seconds:e.ttlSeconds,dpop_required:!1,tee_attestation_url:null,ratchet_state:null}}),c=va({v:3,n:n.name,t:n.type||"application/octet-stream",rsx:Ee(r.secretKey.x25519),rsm:Ee(r.secretKey.mlKem),rpx:Ee(r.publicKey.x25519),spe:Ee(o.publicKey.ed25519),spm:Ee(o.publicKey.mlDsa)});return{container:s.container,fragment:c,lockboxId:a}}async function Vl(e){let t={x25519:Et(e.fragment.rsx),mlKem:Et(e.fragment.rsm)},n=Et(e.fragment.rpx),r={ed25519:Et(e.fragment.spe),mlDsa:Et(e.fragment.spm)},{plaintext:o,header:a}=await(0,Sa.openHybrid)({container:e.container,recipientSecretKey:t,recipientPublicX25519:n,signerPublicKey:r});return{plaintext:o,filename:a.original_filename||e.fragment.n,contentType:a.original_content_type||e.fragment.t,signerKid:a.sig.signer_kid,issuedAt:a.issued_at,ciphertextSha256:a.ciphertext_sha256}}async function Gl(e){let t=crypto.getRandomValues(new Uint8Array(32)),n=crypto.getRandomValues(new Uint8Array(12)),r=new TextEncoder().encode(e),o=new ArrayBuffer(32);new Uint8Array(o).set(t);let a=new ArrayBuffer(12);new Uint8Array(a).set(n);let i=new ArrayBuffer(r.byteLength);new Uint8Array(i).set(r);let s=await crypto.subtle.importKey("raw",o,{name:"AES-GCM"},!1,["encrypt"]),c=new Uint8Array(await crypto.subtle.encrypt({name:"AES-GCM",iv:a},s,i));return{wrapKeyB64Url:wa(t),wrappedFragmentB64:Ee(c),wrapIvB64:Ee(n)}}});var Ta=N(l=>{"use strict";var ql=l&&l.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(l,"__esModule",{value:!0});l.PVE_SIGNED_LEN=l.RCPT_VERSION=l.PVE_VERSION=l.RCPT_MAGIC=l.PVE_MAGIC=l.verifyDpop=l.publicJwkFromBytes=l.jwkThumbprint=l.createDpop=l.verifyContainerHeader=l.signContainerHeader=l.sealHybrid=l.openHybrid=l.headerSigningBytes=l.encodeContainerV3=l.decodeContainerV3=l.ContainerV3Error=l.CONTAINER_HEADER_MAX_BYTES=l.CONTAINER_FIXED_PREFIX_BYTES=l.CONTAINER_MAGIC=l.canonicalJson=l.NDC_V03_RATCHET_DOMAIN=l.NDC_V03_CONTENT_KEY_DOMAIN=l.NDC_V03_KEM_DOMAIN=l.NDC_WIRE_V03=l.NDC_WIRE_V1=l.PQ_SIZES=l.PQ_SUITE=l.ratchetAdvance=l.deriveContentKey=l.mlDsa65VerifyDetached=l.mlDsa65SignDetached=l.generateMlDsa65Keypair=l.hybridVerify=l.hybridSign=l.hybridKemDecapsulate=l.hybridKemEncapsulate=l.generateHybridSigKeypair=l.deriveHybridKemKeypairFromSeed=l.generateHybridKemKeypair=l.ALGORITHMS=l.CRYPTO_VERSION=l.NoDataSDK=l.NoDataForms=l.NoDataSystems=l.NoDataWebhook=l.NoDataEmail=l.verifyProofOfWork=l.solveProofOfWork=l.NoDataCrypto=void 0;l.auditChain=l.appendReceipt=l.timeGateEncrypt=l.timeGateDecrypt=l.timeForRound=l.TimeGateError=l.roundForTime=l.makeFakeDrandChain=l.fetchDrandRound=l.drandTimeLockOpen=l.drandTimeLockEncrypt=l.drandTimeLockDecrypt=l.DRAND_LOE_MAINNET=l.watermarkSvgOverlay=l.findLeakSource=l.computeWatermark=l.SegmentError=l.sealSegments=l.openSegments=l.manifestDigest=l.buildCapability=l.splitSecret=l.serializeShare=l.deserializeShare=l.combineShares=l.decodeAttestationPayload=l.verifyCoseSign1Es384=l.verifyAttestation=l.parseAttestation=l.fetchAttestation=l.stepRatchet=l.replayRatchet=l.destroyKey=l.verifyReceiptDelta=l.parseReceiptDelta=l.signReceiptDelta=l.encodeReceiptDeltaSignedBytes=l.verifyPve=l.pveHash=l.parsePve=l.signPve=l.encodePveSignedBytes=l.originJktForPublicKey=l.uuidFromDeltaId=l.deltaIdFromUuid=l.ABSORB_STATUS=l.DELTA_KIND=l.RCPT_TOTAL_LEN=l.RCPT_SIGNED_LEN=l.PVE_TOTAL_LEN=void 0;l.wrapFragmentForShortLink=l.openPublicShare=l.sealBytesForPublicShare=l.decodeShareCredential=l.encodeProofToken=l.extractProofToken=l.decodeFragment=l.encodeFragment=l.v3SealReceiptPayload=l.v3OpenReceiptPayload=l.showcaseChips=l.recommendationToMandate=l.summarise=l.recommend=l.verifyReceipt=l.receiptHash=l.issueReceipt=l.issueGenesisReceipt=l.GENESIS_PREV_HASH=void 0;var Wl=Oe();Object.defineProperty(l,"NoDataCrypto",{enumerable:!0,get:function(){return ql(Wl).default}});var ka=_o();Object.defineProperty(l,"solveProofOfWork",{enumerable:!0,get:function(){return ka.solveProofOfWork}});Object.defineProperty(l,"verifyProofOfWork",{enumerable:!0,get:function(){return ka.verifyProofOfWork}});var kt=So();Object.defineProperty(l,"NoDataEmail",{enumerable:!0,get:function(){return kt.NoDataEmail}});Object.defineProperty(l,"NoDataWebhook",{enumerable:!0,get:function(){return kt.NoDataWebhook}});Object.defineProperty(l,"NoDataSystems",{enumerable:!0,get:function(){return kt.NoDataSystems}});Object.defineProperty(l,"NoDataForms",{enumerable:!0,get:function(){return kt.NoDataForms}});Object.defineProperty(l,"NoDataSDK",{enumerable:!0,get:function(){return kt.NoDataSDK}});l.CRYPTO_VERSION="0.2.0";l.ALGORITHMS={ENCRYPTION:"AES-256-GCM",KEY_EXCHANGE:"RSA-OAEP-4096",KEY_DERIVATION:"PBKDF2-SHA256-310K",SIGNING:"Ed25519",HASHING:"SHA-256",PROOF_OF_WORK:"SHA-256-NONCE"};var K=We();Object.defineProperty(l,"generateHybridKemKeypair",{enumerable:!0,get:function(){return K.generateHybridKemKeypair}});Object.defineProperty(l,"deriveHybridKemKeypairFromSeed",{enumerable:!0,get:function(){return K.deriveHybridKemKeypairFromSeed}});Object.defineProperty(l,"generateHybridSigKeypair",{enumerable:!0,get:function(){return K.generateHybridSigKeypair}});Object.defineProperty(l,"hybridKemEncapsulate",{enumerable:!0,get:function(){return K.hybridKemEncapsulate}});Object.defineProperty(l,"hybridKemDecapsulate",{enumerable:!0,get:function(){return K.hybridKemDecapsulate}});Object.defineProperty(l,"hybridSign",{enumerable:!0,get:function(){return K.hybridSign}});Object.defineProperty(l,"hybridVerify",{enumerable:!0,get:function(){return K.hybridVerify}});Object.defineProperty(l,"generateMlDsa65Keypair",{enumerable:!0,get:function(){return K.generateMlDsa65Keypair}});Object.defineProperty(l,"mlDsa65SignDetached",{enumerable:!0,get:function(){return K.mlDsa65SignDetached}});Object.defineProperty(l,"mlDsa65VerifyDetached",{enumerable:!0,get:function(){return K.mlDsa65VerifyDetached}});Object.defineProperty(l,"deriveContentKey",{enumerable:!0,get:function(){return K.deriveContentKey}});Object.defineProperty(l,"ratchetAdvance",{enumerable:!0,get:function(){return K.ratchetAdvance}});Object.defineProperty(l,"PQ_SUITE",{enumerable:!0,get:function(){return K.PQ_SUITE}});Object.defineProperty(l,"PQ_SIZES",{enumerable:!0,get:function(){return K.PQ_SIZES}});Object.defineProperty(l,"NDC_WIRE_V1",{enumerable:!0,get:function(){return K.NDC_WIRE_V1}});Object.defineProperty(l,"NDC_WIRE_V03",{enumerable:!0,get:function(){return K.NDC_WIRE_V03}});Object.defineProperty(l,"NDC_V03_KEM_DOMAIN",{enumerable:!0,get:function(){return K.NDC_V03_KEM_DOMAIN}});Object.defineProperty(l,"NDC_V03_CONTENT_KEY_DOMAIN",{enumerable:!0,get:function(){return K.NDC_V03_CONTENT_KEY_DOMAIN}});Object.defineProperty(l,"NDC_V03_RATCHET_DOMAIN",{enumerable:!0,get:function(){return K.NDC_V03_RATCHET_DOMAIN}});var ne=Ht();Object.defineProperty(l,"canonicalJson",{enumerable:!0,get:function(){return ne.canonicalJson}});Object.defineProperty(l,"CONTAINER_MAGIC",{enumerable:!0,get:function(){return ne.CONTAINER_MAGIC}});Object.defineProperty(l,"CONTAINER_FIXED_PREFIX_BYTES",{enumerable:!0,get:function(){return ne.CONTAINER_FIXED_PREFIX_BYTES}});Object.defineProperty(l,"CONTAINER_HEADER_MAX_BYTES",{enumerable:!0,get:function(){return ne.CONTAINER_HEADER_MAX_BYTES}});Object.defineProperty(l,"ContainerV3Error",{enumerable:!0,get:function(){return ne.ContainerV3Error}});Object.defineProperty(l,"decodeContainerV3",{enumerable:!0,get:function(){return ne.decodeContainerV3}});Object.defineProperty(l,"encodeContainerV3",{enumerable:!0,get:function(){return ne.encodeContainerV3}});Object.defineProperty(l,"headerSigningBytes",{enumerable:!0,get:function(){return ne.headerSigningBytes}});Object.defineProperty(l,"openHybrid",{enumerable:!0,get:function(){return ne.openHybrid}});Object.defineProperty(l,"sealHybrid",{enumerable:!0,get:function(){return ne.sealHybrid}});Object.defineProperty(l,"signContainerHeader",{enumerable:!0,get:function(){return ne.signContainerHeader}});Object.defineProperty(l,"verifyContainerHeader",{enumerable:!0,get:function(){return ne.verifyContainerHeader}});var en=nr();Object.defineProperty(l,"createDpop",{enumerable:!0,get:function(){return en.createDpop}});Object.defineProperty(l,"jwkThumbprint",{enumerable:!0,get:function(){return en.jwkThumbprint}});Object.defineProperty(l,"publicJwkFromBytes",{enumerable:!0,get:function(){return en.publicJwkFromBytes}});Object.defineProperty(l,"verifyDpop",{enumerable:!0,get:function(){return en.verifyDpop}});var $=Fo();Object.defineProperty(l,"PVE_MAGIC",{enumerable:!0,get:function(){return $.PVE_MAGIC}});Object.defineProperty(l,"RCPT_MAGIC",{enumerable:!0,get:function(){return $.RCPT_MAGIC}});Object.defineProperty(l,"PVE_VERSION",{enumerable:!0,get:function(){return $.PVE_VERSION}});Object.defineProperty(l,"RCPT_VERSION",{enumerable:!0,get:function(){return $.RCPT_VERSION}});Object.defineProperty(l,"PVE_SIGNED_LEN",{enumerable:!0,get:function(){return $.PVE_SIGNED_LEN}});Object.defineProperty(l,"PVE_TOTAL_LEN",{enumerable:!0,get:function(){return $.PVE_TOTAL_LEN}});Object.defineProperty(l,"RCPT_SIGNED_LEN",{enumerable:!0,get:function(){return $.RCPT_SIGNED_LEN}});Object.defineProperty(l,"RCPT_TOTAL_LEN",{enumerable:!0,get:function(){return $.RCPT_TOTAL_LEN}});Object.defineProperty(l,"DELTA_KIND",{enumerable:!0,get:function(){return $.DELTA_KIND}});Object.defineProperty(l,"ABSORB_STATUS",{enumerable:!0,get:function(){return $.ABSORB_STATUS}});Object.defineProperty(l,"deltaIdFromUuid",{enumerable:!0,get:function(){return $.deltaIdFromUuid}});Object.defineProperty(l,"uuidFromDeltaId",{enumerable:!0,get:function(){return $.uuidFromDeltaId}});Object.defineProperty(l,"originJktForPublicKey",{enumerable:!0,get:function(){return $.originJktForPublicKey}});Object.defineProperty(l,"encodePveSignedBytes",{enumerable:!0,get:function(){return $.encodePveSignedBytes}});Object.defineProperty(l,"signPve",{enumerable:!0,get:function(){return $.signPve}});Object.defineProperty(l,"parsePve",{enumerable:!0,get:function(){return $.parsePve}});Object.defineProperty(l,"pveHash",{enumerable:!0,get:function(){return $.pveHash}});Object.defineProperty(l,"verifyPve",{enumerable:!0,get:function(){return $.verifyPve}});Object.defineProperty(l,"encodeReceiptDeltaSignedBytes",{enumerable:!0,get:function(){return $.encodeReceiptSignedBytes}});Object.defineProperty(l,"signReceiptDelta",{enumerable:!0,get:function(){return $.signReceipt}});Object.defineProperty(l,"parseReceiptDelta",{enumerable:!0,get:function(){return $.parseReceipt}});Object.defineProperty(l,"verifyReceiptDelta",{enumerable:!0,get:function(){return $.verifyReceipt}});var fr=Ho();Object.defineProperty(l,"destroyKey",{enumerable:!0,get:function(){return fr.destroyKey}});Object.defineProperty(l,"replayRatchet",{enumerable:!0,get:function(){return fr.replayRatchet}});Object.defineProperty(l,"stepRatchet",{enumerable:!0,get:function(){return fr.stepRatchet}});var hr=qo();Object.defineProperty(l,"fetchAttestation",{enumerable:!0,get:function(){return hr.fetchAttestation}});Object.defineProperty(l,"parseAttestation",{enumerable:!0,get:function(){return hr.parseAttestation}});Object.defineProperty(l,"verifyAttestation",{enumerable:!0,get:function(){return hr.verifyAttestation}});var xa=cr();Object.defineProperty(l,"verifyCoseSign1Es384",{enumerable:!0,get:function(){return xa.verifyCoseSign1Es384}});Object.defineProperty(l,"decodeAttestationPayload",{enumerable:!0,get:function(){return xa.decodeAttestationPayload}});var tn=zo();Object.defineProperty(l,"combineShares",{enumerable:!0,get:function(){return tn.combineShares}});Object.defineProperty(l,"deserializeShare",{enumerable:!0,get:function(){return tn.deserializeShare}});Object.defineProperty(l,"serializeShare",{enumerable:!0,get:function(){return tn.serializeShare}});Object.defineProperty(l,"splitSecret",{enumerable:!0,get:function(){return tn.splitSecret}});var xt=Qo();Object.defineProperty(l,"buildCapability",{enumerable:!0,get:function(){return xt.buildCapability}});Object.defineProperty(l,"manifestDigest",{enumerable:!0,get:function(){return xt.manifestDigest}});Object.defineProperty(l,"openSegments",{enumerable:!0,get:function(){return xt.openSegments}});Object.defineProperty(l,"sealSegments",{enumerable:!0,get:function(){return xt.sealSegments}});Object.defineProperty(l,"SegmentError",{enumerable:!0,get:function(){return xt.SegmentError}});var yr=na();Object.defineProperty(l,"computeWatermark",{enumerable:!0,get:function(){return yr.computeWatermark}});Object.defineProperty(l,"findLeakSource",{enumerable:!0,get:function(){return yr.findLeakSource}});Object.defineProperty(l,"watermarkSvgOverlay",{enumerable:!0,get:function(){return yr.watermarkSvgOverlay}});var oe=la();Object.defineProperty(l,"DRAND_LOE_MAINNET",{enumerable:!0,get:function(){return oe.DRAND_LOE_MAINNET}});Object.defineProperty(l,"drandTimeLockDecrypt",{enumerable:!0,get:function(){return oe.drandTimeLockDecrypt}});Object.defineProperty(l,"drandTimeLockEncrypt",{enumerable:!0,get:function(){return oe.drandTimeLockEncrypt}});Object.defineProperty(l,"drandTimeLockOpen",{enumerable:!0,get:function(){return oe.drandTimeLockOpen}});Object.defineProperty(l,"fetchDrandRound",{enumerable:!0,get:function(){return oe.fetchDrandRound}});Object.defineProperty(l,"makeFakeDrandChain",{enumerable:!0,get:function(){return oe.makeFakeDrandChain}});Object.defineProperty(l,"roundForTime",{enumerable:!0,get:function(){return oe.roundForTime}});Object.defineProperty(l,"TimeGateError",{enumerable:!0,get:function(){return oe.TimeGateError}});Object.defineProperty(l,"timeForRound",{enumerable:!0,get:function(){return oe.timeForRound}});Object.defineProperty(l,"timeGateDecrypt",{enumerable:!0,get:function(){return oe.timeGateDecrypt}});Object.defineProperty(l,"timeGateEncrypt",{enumerable:!0,get:function(){return oe.timeGateEncrypt}});var Be=ha();Object.defineProperty(l,"appendReceipt",{enumerable:!0,get:function(){return Be.appendReceipt}});Object.defineProperty(l,"auditChain",{enumerable:!0,get:function(){return Be.auditChain}});Object.defineProperty(l,"GENESIS_PREV_HASH",{enumerable:!0,get:function(){return Be.GENESIS_PREV_HASH}});Object.defineProperty(l,"issueGenesisReceipt",{enumerable:!0,get:function(){return Be.issueGenesisReceipt}});Object.defineProperty(l,"issueReceipt",{enumerable:!0,get:function(){return Be.issueReceipt}});Object.defineProperty(l,"receiptHash",{enumerable:!0,get:function(){return Be.receiptHash}});Object.defineProperty(l,"verifyReceipt",{enumerable:!0,get:function(){return Be.verifyReceipt}});var Aa=ma();Object.defineProperty(l,"recommend",{enumerable:!0,get:function(){return Aa.recommend}});Object.defineProperty(l,"summarise",{enumerable:!0,get:function(){return Aa.summarise}});var nn=_a();Object.defineProperty(l,"recommendationToMandate",{enumerable:!0,get:function(){return nn.recommendationToMandate}});Object.defineProperty(l,"showcaseChips",{enumerable:!0,get:function(){return nn.showcaseChips}});Object.defineProperty(l,"v3OpenReceiptPayload",{enumerable:!0,get:function(){return nn.v3OpenReceiptPayload}});Object.defineProperty(l,"v3SealReceiptPayload",{enumerable:!0,get:function(){return nn.v3SealReceiptPayload}});var ke=Ea();Object.defineProperty(l,"encodeFragment",{enumerable:!0,get:function(){return ke.encodeFragment}});Object.defineProperty(l,"decodeFragment",{enumerable:!0,get:function(){return ke.decodeFragment}});Object.defineProperty(l,"extractProofToken",{enumerable:!0,get:function(){return ke.extractProofToken}});Object.defineProperty(l,"encodeProofToken",{enumerable:!0,get:function(){return ke.encodeProofToken}});Object.defineProperty(l,"decodeShareCredential",{enumerable:!0,get:function(){return ke.decodeShareCredential}});Object.defineProperty(l,"sealBytesForPublicShare",{enumerable:!0,get:function(){return ke.sealBytesForPublicShare}});Object.defineProperty(l,"openPublicShare",{enumerable:!0,get:function(){return ke.openPublicShare}});Object.defineProperty(l,"wrapFragmentForShortLink",{enumerable:!0,get:function(){return ke.wrapFragmentForShortLink}})});import{McpServer as wd}from"@modelcontextprotocol/sdk/server/mcp.js";import{StdioServerTransport as vd}from"@modelcontextprotocol/sdk/server/stdio.js";import{z as h}from"zod";import{z as ge}from"zod";import{readdirSync as Ur,readFileSync as Hr,statSync as Sn}from"node:fs";import{join as Ki}from"node:path";var Ir=[{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"}],Nr=/node_modules\/|\.next\/|\.test\.|\.spec\.|__tests__\/|\.env\.example$|\.nodata-proof\.json$|\.git\//,ui=[{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 pi(e,t){let n=a=>a.replace(/^[^0-9]*/,"").split(".").map(i=>parseInt(i,10)||0),r=n(e),o=n(t);for(let a=0;a<3;a++){if((r[a]||0)<(o[a]||0))return!0;if((r[a]||0)>(o[a]||0))return!1}return!1}function Cr(e){let t=[],n;try{n=JSON.parse(e)}catch{return t}let r={...n.dependencies??{},...n.devDependencies??{}};for(let[o,a]of Object.entries(r)){let i=(a||"").replace(/^[\^~>=<\s]+/,""),s=ui.find(c=>c.name===o&&pi(i,c.below));s&&t.push({name:o,version:i,vuln:s})}return t}var fi=[{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"}],hi=[{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"}],yi=/^(id|uuid|created_?at|updated_?at|deleted_?at|status|type|category|description|title|slug|url|path|key|value|enabled|active|public|version|metadata|config|settings|data|content|note|comment|label|color|icon)$/i;function Te(e){if(!e)return null;let t=e.trim();if(yi.test(t)||/^name$/i.test(t))return null;let n=t.replace(/[\s-]+/g,"_");for(let r of[...hi,...fi])if(r.pattern.test(t)||r.pattern.test(n))return{type:r.type,label:r.label};return null}var hn={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 Dt(e){let t=String(e??"").replace(/\D/g,"");if(t.length===0||t.length>9)return!1;let n=t.padStart(9,"0"),r=0;for(let o=0;o<9;o++){let a=parseInt(n[o]??"0",10)*(o%2+1);a>9&&(a-=9),r+=a}return r%10===0&&parseInt(n,10)>0}var nt=/(?:\+972[\s-]?|0)(?:5[0-9]|[2-4]|[89])(?:[\s-]?\d){7}/g;var rt=/\bIL\d{2}\s?(?:\d{4}\s?){4}\d{3}\b/g;function mi(e){let t=String(e??"").replace(/\D/g,"");if(t.length<12||t.length>19)return!1;let n=0,r=!1;for(let o=t.length-1;o>=0;o-=1){let a=parseInt(t[o]??"0",10);r&&(a*=2,a>9&&(a-=9)),n+=a,r=!r}return n%10===0}function gi(e){let t=String(e??"").replace(/\s/g,"").toUpperCase();if(!/^[A-Z]{2}\d{2}[A-Z0-9]{10,30}$/.test(t))return!1;let n=t.slice(4)+t.slice(0,4),r=0;for(let o of n){let a=o>="A"&&o<="Z"?String(o.charCodeAt(0)-55):o;for(let i of a)r=(r*10+Number(i))%97}return r===1}var pn="(?<!\\d)(?<!\\d[.,])",fn="(?!\\d)(?![.,]\\d)",yn=[{subkind:"israeli_id",severity:"high",pattern:new RegExp(`${pn}\\d{9}${fn}`,"g"),validate:Dt,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(`${pn}[2-6][ -]?(?:\\d[ -]?){11,17}\\d${fn}`,"g"),validate:mi,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:gi,hint:"Bank account in IBAN form (mod-97 verified) in plaintext."},{subkind:"israeli_phone",severity:"medium",pattern:new RegExp(`${pn}(?:\\+972[- ]?|0)(?:[57]\\d|[2-489])[- ]?\\d{3}[- ]?\\d{4}${fn}`,"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 Rr(e){let t=[];for(let n of yn){n.pattern.lastIndex=0;let r=new Set,o,a=0;for(;(o=n.pattern.exec(e))!==null&&(a+=1,!(a>2e5));){let i=o[0];if(n.validate(i)&&r.add(i.replace(/[\s-]/g,"")),r.size>=1e5)break}r.size>0&&t.push({subkind:n.subkind,severity:n.severity,hint:n.hint,count:r.size})}return t}function je(e,t){let n=[],r="",o=!1;for(let a=0;a<e.length;a++){let i=e[a];o?i==='"'&&e[a+1]==='"'?(r+='"',a++):i==='"'?o=!1:r+=i:i==='"'?o=!0:i===t?(n.push(r),r=""):r+=i}return n.push(r),n}import{inflateRawSync as Ti}from"node:zlib";import{inflateSync as _i}from"node:zlib";var mn=new Set([".pdf"]),$r=8*1024*1024;function bi(e){let t=e.toString("latin1"),n=new Map,r=/(\d+)\s+(\d+)\s+obj\b/g,o;for(;(o=r.exec(t))!==null;){let a=Number(o[1]),i=r.lastIndex,s=t.indexOf("endobj",i);if(s<0)continue;let c=t.indexOf("stream",i),d,u=null;if(c>=0&&c<s){d=t.slice(i,c);let p=c+6;t[p]==="\r"&&(p+=1),t[p]===`
|
|
16
|
-
`&&(p+=1);let
|
|
17
|
-
`,
|
|
18
|
-
`),n}function
|
|
19
|
-
`)}function
|
|
20
|
-
`),truncated:s,streams:
|
|
15
|
+
</svg>`}function ma(e){let t="";for(let n=0;n<e.length;n++)t+=e[n].toString(16).padStart(2,"0");return t}});var xa=R(q=>{"use strict";Object.defineProperty(q,"__esModule",{value:!0});q.DRAND_LOE_MAINNET=q.TimeGateError=void 0;q.timeGateEncrypt=vu;q.timeGateDecrypt=Su;q.roundForTime=wu;q.timeForRound=ku;q.drandTimeLockEncrypt=Eu;q.drandTimeLockDecrypt=wa;q.makeFakeDrandChain=Au;q.fetchDrandRound=ka;q.drandTimeLockOpen=Pu;var fe=I("@noble/curves/bls12-381.js"),In=I("@noble/hashes/sha2.js"),Ae=e=>e,ba="NDC-v0.3-server-time-gate";async function vu(e){let t=crypto.getRandomValues(new Uint8Array(12)),n=new TextEncoder().encode(`${ba}|${e.notBeforeUnixSec}`),r=await crypto.subtle.importKey("raw",Ae(e.serverWrapKey),{name:"AES-GCM"},!1,["encrypt"]),o=await crypto.subtle.encrypt({name:"AES-GCM",iv:Ae(t),additionalData:Ae(n)},r,Ae(e.plaintext));return{variant:"server-attested",notBeforeUnixSec:e.notBeforeUnixSec,iv_b64:Tn(t),ciphertext_b64:Tn(new Uint8Array(o))}}var Ct=class extends Error{constructor(t,n){super(n),this.name="TimeGateError",this.code=t}};q.TimeGateError=Ct;async function Su(e){if(e.currentUnixSec<e.ciphertext.notBeforeUnixSec)throw new Ct("not_yet",`time-gate not yet open: now ${e.currentUnixSec} < notBefore ${e.ciphertext.notBeforeUnixSec}`);let t=new TextEncoder().encode(`${ba}|${e.ciphertext.notBeforeUnixSec}`),n=await crypto.subtle.importKey("raw",Ae(e.serverWrapKey),{name:"AES-GCM"},!1,["decrypt"]);try{let r=await crypto.subtle.decrypt({name:"AES-GCM",iv:Ae(Pn(e.ciphertext.iv_b64)),additionalData:Ae(t)},n,Ae(Pn(e.ciphertext.ciphertext_b64)));return new Uint8Array(r)}catch{throw new Ct("tamper_detected","AES-GCM authentication tag failed \u2014 ciphertext or AAD tampered")}}q.DRAND_LOE_MAINNET={publicKeyHex:"868f005eb8e6e4ca0a47c8a77ceaa5309a47978a7c71bc5cce96366b5d7a569937c529eeda66c7293784a9402801af31",chainHashHex:"8990e7a9aaed2ffed73dbd7092123d6f289930540d7651336225dc172e51b2ce",genesisUnixSec:1595431050,periodSec:30,hashDst:"BLS_SIG_BLS12381G2_XMD:SHA-256_SSWU_RO_NUL_"};function wu(e,t){return e<=t.genesisUnixSec?1:Math.ceil((e-t.genesisUnixSec)/t.periodSec)}function ku(e,t){return t.genesisUnixSec+e*t.periodSec}function va(e){let t=new Uint8Array(8),n=e;for(let r=7;r>=0;r--)t[r]=n&255,n=Math.floor(n/256);return(0,In.sha256)(t)}function Sa(e){let t=new Uint8Array(576),n=0;for(let r of[e.c0,e.c1])for(let o of[r.c0,r.c1,r.c2])for(let i of[o.c0,o.c1])xu(i,t,n,48),n+=48;return t}function xu(e,t,n,r){let o=e,i=BigInt(255),a=BigInt(8);for(let s=r-1;s>=0;s--)t[n+s]=Number(o&i),o>>=a}function Eu(e,t,n,r){if(e.length!==32)throw new Error(`drand-IBE expects a 32-byte content key, got ${e.length}`);let o=fe.bls12_381.G1.Point,i=fe.bls12_381.fields.Fr,a=o.fromBytes(n),s;do s=Iu(crypto.getRandomValues(new Uint8Array(32)))%i.ORDER;while(s===BigInt(0));let c=o.BASE.multiply(s),l=fe.bls12_381.longSignatures.hash(va(t),r.hashDst),u=a.multiply(s),p=fe.bls12_381.pairing(u,l,!0),h=(0,In.sha256)(Sa(p)),f=new Uint8Array(32);for(let y=0;y<32;y++)f[y]=e[y]^h[y];return{variant:"drand-ibe",chainHashHex:r.chainHashHex,round:t,u_b64:Tn(c.toBytes()),v_b64:Tn(f)}}function wa(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=fe.bls12_381.G1.Point.fromBytes(Pn(e.ciphertext.u_b64)),r=fe.bls12_381.longSignatures.Signature.fromBytes(e.roundSignature),o=fe.bls12_381.pairing(n,r,!0),i=(0,In.sha256)(Sa(o)),a=Pn(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]^i[c];return s}function Au(e){let t;if(e&&e.length===48)t=e;else{t=new Uint8Array(48);let i=e??crypto.getRandomValues(new Uint8Array(48));t.set(i.slice(0,48),0)}let{secretKey:n,publicKey:r}=fe.bls12_381.longSignatures.keygen(t),o={publicKeyHex:_a(r.toBytes()),chainHashHex:_a((0,In.sha256)(r.toBytes())),genesisUnixSec:17e8,periodSec:30,hashDst:"BLS_SIG_BLS12381G2_XMD:SHA-256_SSWU_RO_NUL_"};return{config:o,publicKey:r.toBytes(),signRound(i){let a=fe.bls12_381.longSignatures.hash(va(i),o.hashDst);return fe.bls12_381.longSignatures.sign(a,n).toBytes()}}}function _a(e){let t="";for(let n=0;n<e.length;n++)t+=e[n].toString(16).padStart(2,"0");return t}function Tu(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 ka(e,t,n={}){let r=n.fetchImpl??fetch,o=n.timeoutMs??8e3,i=`${t.replace(/\/$/,"")}/public/${e}`,a,s;typeof AbortController<"u"&&(a=new AbortController,s=setTimeout(()=>a.abort(),o));let c;try{c=await r(i,{signal:a?.signal})}finally{s&&clearTimeout(s)}if(!c.ok)throw new Error(`drand fetch failed: ${i} \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 ${i}`);let u=Tu(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 Pu(e,t,n,r={}){let o=await ka(e.round,t,r);return wa({ciphertext:e,roundSignature:o.signature_bytes,chain:n})}function Tn(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 Pn(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 Iu(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 Ia=R(oe=>{"use strict";Object.defineProperty(oe,"__esModule",{value:!0});oe.GENESIS_PREV_HASH=void 0;oe.receiptHash=Qr;oe.issueReceipt=eo;oe.verifyReceipt=Pa;oe.auditChain=Nu;oe.issueGenesisReceipt=Ru;oe.appendReceipt=Ou;var Du=I("@noble/hashes/sha2.js"),Zr=vn(),Ta=ot();oe.GENESIS_PREV_HASH="0".repeat(64);var Ea=e=>{if(typeof Buffer<"u")return Buffer.from(e).toString("base64");let t="";for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return btoa(t)},Aa=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},$u=e=>{let t="";for(let n=0;n<e.length;n++)t+=e[n].toString(16).padStart(2,"0");return t};function Qr(e){return $u((0,Du.sha256)(new TextEncoder().encode((0,Zr.canonicalJson)(e))))}function eo(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,Zr.canonicalJson)(t)),r=(0,Ta.hybridSign)(e.signing_key.secretKey,n);return{body:t,sig:{signer_kid:e.signer_kid,ed25519_b64:Ea(r.ed25519),ml_dsa_65_b64:Ea(r.mlDsa)}}}function Pa(e,t){let n=new TextEncoder().encode((0,Zr.canonicalJson)(e.body)),r={ed25519:Aa(e.sig.ed25519_b64),mlDsa:Aa(e.sig.ml_dsa_65_b64)};return(0,Ta.hybridVerify)(t,n,r)}function Nu(e,t,n=1){if(e.length===0)return{ok:!0,receipts_checked:0};let r=n,o=n===1?oe.GENESIS_PREV_HASH:null;for(let i of e){if(i.body.sequence!==r)return{ok:!1,code:i.body.sequence<r?"duplicate_sequence":"out_of_order",at_sequence:i.body.sequence,reason:`expected sequence ${r}, got ${i.body.sequence}`};if(o!==null&&i.body.prev_hash!==o)return{ok:!1,code:r===1?"missing_genesis":"broken_prev_hash",at_sequence:i.body.sequence,reason:`prev_hash mismatch: expected ${o.slice(0,16)}\u2026, got ${i.body.prev_hash.slice(0,16)}\u2026`};if(!Pa(i,t))return{ok:!1,code:"bad_signature",at_sequence:i.body.sequence,reason:"hybrid signature does not verify"};o=Qr(i.body),r+=1}return{ok:!0,receipts_checked:e.length}}function Ru(e){return eo({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 Ou(e,t){return eo({...t,prev_hash:Qr(e.body),sequence:e.body.sequence+1})}});var $a=R(Dn=>{"use strict";Object.defineProperty(Dn,"__esModule",{value:!0});Dn.recommend=Mu;Dn.summarise=Fu;var Cu={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"}},Bu={"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}},ju={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"]}},Ku=[{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"}],Da={"mode-4":1,"mode-4p":2,"mode-4h":3,"mode-6":4};function Lu(e,t){return Da[e]>=Da[t]?e:t}function Mu(e){let t=Cu[e.orgType],n=Bu[e.fileClass],r=ju[e.channel],o=Lu(t.mode,n.minMode);e.recipientLacksPasskey&&o==="mode-4h"&&(o="mode-4p");let i=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:o==="mode-4h"||o==="mode-4p"||o==="mode-6",dpopRequired:o!=="mode-4",timelockDrand:!!e.timeLockUnixSec&&!!e.timeLockDecentralized,timelockServerGate:!!e.timeLockUnixSec&&!e.timeLockDecentralized},s={...r,adapterCandidates:[...r.adapters]},c=[...s.notes],l=Ku.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:o,cacheTtlSeconds:i,features:a,delivery:{deliveryMode:s.deliveryMode,adapterCandidates:s.adapterCandidates},notes:c}}function Fu(e){let t=[e.sensitivityMode,`TTL ${e.cacheTtlSeconds}s`];return e.features.forensicWatermark&&t.push("watermark"),e.features.selectiveDisclosureSegments&&t.push("segments"),e.features.thresholdKofN&&t.push(`threshold ${e.features.thresholdKofN.k}-of-${e.features.thresholdKofN.n}`),e.features.teeAttestation&&t.push("TEE"),e.features.perOpenRatchet&&t.push("ratchet"),e.features.dpopRequired&&t.push("DPoP"),e.features.timelockDrand?t.push("drand-tlock"):e.features.timelockServerGate&&t.push("server-timegate"),t.push(`via ${e.delivery.deliveryMode} (${e.delivery.adapterCandidates.join("/")})`),t.join(" \xB7 ")}});var Ra=R(dt=>{"use strict";Object.defineProperty(dt,"__esModule",{value:!0});dt.recommendationToMandate=Wu;dt.v3SealReceiptPayload=qu;dt.v3OpenReceiptPayload=zu;dt.showcaseChips=Ju;function Hu(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 Uu(e){return e.features.dpopRequired?"device_mfa":e.sensitivityMode==="mode-4h"?"first_device":e.sensitivityMode==="mode-4"?"any":"first_device"}function Vu(e){return e.delivery.deliveryMode==="attachment"?"file":e.delivery.deliveryMode==="link"?"link":"view_only"}function Na(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 Gu(e){let t=Na(e);return t==="m365"?"m365_only":t==="in_app"?"in_app":"any"}function Wu(e){let{recommendation:t,source:n}=e,r=t.sensitivityMode==="mode-6",o=n.timeLockUnixSec?new Date(n.timeLockUnixSec*1e3).toISOString():null;return{time:{ttl_seconds:t.cacheTtlSeconds,burn_after_first_read:r,unlock_at:o,max_opens:r?1:null},identity:{capture:Hu(t.sensitivityMode),claim_required:t.sensitivityMode!=="mode-4",allow_magic_link:t.sensitivityMode==="mode-4",allowed_emails:null},device:{binding:Uu(t),listed_fingerprints:null},channel:{delivery:Vu(t),route:Na(t),channel_constraint:Gu(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 qu(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 zu(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 Ju(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 Ka=R(he=>{"use strict";Object.defineProperty(he,"__esModule",{value:!0});he.encodeFragment=ja;he.decodeFragment=Yu;he.extractProofToken=Xu;he.encodeProofToken=Zu;he.decodeShareCredential=Qu;he.sealBytesForPublicShare=np;he.openPublicShare=rp;he.wrapFragmentForShortLink=op;var Oa=ot(),Ca=vn();function Te(e){let t="";for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return btoa(t)}function Bt(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 Ba(e){return Te(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function ja(e){return encodeURIComponent(JSON.stringify(e))}function Yu(e){let t=JSON.parse(decodeURIComponent(e));if(t.v!==3)throw new Error(`fragment version unsupported: ${t.v}`);return t}function Xu(e){return{v:3,kind:"proof",n:e.n,t:e.t,spe:e.spe,spm:e.spm}}function Zu(e){return encodeURIComponent(JSON.stringify(e))}function Qu(e){let t=e.trim(),n=t.indexOf("#"),r=n>=0?t.slice(n+1):t,o;try{o=JSON.parse(decodeURIComponent(r))}catch(i){throw new Error(`credential parse failed: ${i.message??"invalid_json"}`)}if(o.v!==3)throw new Error(`credential version unsupported: ${String(o.v)}`);return o.kind==="proof"?{kind:"proof",value:o}:{kind:"fragment",value:o}}function ep(){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 tp(){let e=new Uint8Array(32);return crypto.getRandomValues(e),Ba(e)}async function np(e){let t=e.bytes,n={name:e.filename,type:e.contentType},r=(0,Oa.generateHybridKemKeypair)(),o=(0,Oa.generateHybridSigKeypair)(),i=ep(),a=tp(),s=await(0,Ca.sealHybrid)({plaintext:t,recipientPublicKey:r.publicKey,recipientKid:`ephemeral-${i}`,signerKeypair:o,signerKid:`lock-${i}`,meta:{lockbox_id:i,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=ja({v:3,n:n.name,t:n.type||"application/octet-stream",rsx:Te(r.secretKey.x25519),rsm:Te(r.secretKey.mlKem),rpx:Te(r.publicKey.x25519),spe:Te(o.publicKey.ed25519),spm:Te(o.publicKey.mlDsa)});return{container:s.container,fragment:c,lockboxId:i}}async function rp(e){let t={x25519:Bt(e.fragment.rsx),mlKem:Bt(e.fragment.rsm)},n=Bt(e.fragment.rpx),r={ed25519:Bt(e.fragment.spe),mlDsa:Bt(e.fragment.spm)},{plaintext:o,header:i}=await(0,Ca.openHybrid)({container:e.container,recipientSecretKey:t,recipientPublicX25519:n,signerPublicKey:r});return{plaintext:o,filename:i.original_filename||e.fragment.n,contentType:i.original_content_type||e.fragment.t,signerKid:i.sig.signer_kid,issuedAt:i.issued_at,ciphertextSha256:i.ciphertext_sha256}}async function op(e){let t=crypto.getRandomValues(new Uint8Array(32)),n=crypto.getRandomValues(new Uint8Array(12)),r=new TextEncoder().encode(e),o=new ArrayBuffer(32);new Uint8Array(o).set(t);let i=new ArrayBuffer(12);new Uint8Array(i).set(n);let a=new ArrayBuffer(r.byteLength);new Uint8Array(a).set(r);let s=await crypto.subtle.importKey("raw",o,{name:"AES-GCM"},!1,["encrypt"]),c=new Uint8Array(await crypto.subtle.encrypt({name:"AES-GCM",iv:i},s,a));return{wrapKeyB64Url:Ba(t),wrappedFragmentB64:Te(c),wrapIvB64:Te(n)}}});var Ha=R(d=>{"use strict";var ip=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 ap=je();Object.defineProperty(d,"NoDataCrypto",{enumerable:!0,get:function(){return ip(ap).default}});var La=Ri();Object.defineProperty(d,"solveProofOfWork",{enumerable:!0,get:function(){return La.solveProofOfWork}});Object.defineProperty(d,"verifyProofOfWork",{enumerable:!0,get:function(){return La.verifyProofOfWork}});var jt=Ci();Object.defineProperty(d,"NoDataEmail",{enumerable:!0,get:function(){return jt.NoDataEmail}});Object.defineProperty(d,"NoDataWebhook",{enumerable:!0,get:function(){return jt.NoDataWebhook}});Object.defineProperty(d,"NoDataSystems",{enumerable:!0,get:function(){return jt.NoDataSystems}});Object.defineProperty(d,"NoDataForms",{enumerable:!0,get:function(){return jt.NoDataForms}});Object.defineProperty(d,"NoDataSDK",{enumerable:!0,get:function(){return jt.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=ot();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 ie=vn();Object.defineProperty(d,"canonicalJson",{enumerable:!0,get:function(){return ie.canonicalJson}});Object.defineProperty(d,"CONTAINER_MAGIC",{enumerable:!0,get:function(){return ie.CONTAINER_MAGIC}});Object.defineProperty(d,"CONTAINER_FIXED_PREFIX_BYTES",{enumerable:!0,get:function(){return ie.CONTAINER_FIXED_PREFIX_BYTES}});Object.defineProperty(d,"CONTAINER_HEADER_MAX_BYTES",{enumerable:!0,get:function(){return ie.CONTAINER_HEADER_MAX_BYTES}});Object.defineProperty(d,"ContainerV3Error",{enumerable:!0,get:function(){return ie.ContainerV3Error}});Object.defineProperty(d,"decodeContainerV3",{enumerable:!0,get:function(){return ie.decodeContainerV3}});Object.defineProperty(d,"encodeContainerV3",{enumerable:!0,get:function(){return ie.encodeContainerV3}});Object.defineProperty(d,"headerSigningBytes",{enumerable:!0,get:function(){return ie.headerSigningBytes}});Object.defineProperty(d,"openHybrid",{enumerable:!0,get:function(){return ie.openHybrid}});Object.defineProperty(d,"sealHybrid",{enumerable:!0,get:function(){return ie.sealHybrid}});Object.defineProperty(d,"signContainerHeader",{enumerable:!0,get:function(){return ie.signContainerHeader}});Object.defineProperty(d,"verifyContainerHeader",{enumerable:!0,get:function(){return ie.verifyContainerHeader}});var $n=Vr();Object.defineProperty(d,"createDpop",{enumerable:!0,get:function(){return $n.createDpop}});Object.defineProperty(d,"jwkThumbprint",{enumerable:!0,get:function(){return $n.jwkThumbprint}});Object.defineProperty(d,"publicJwkFromBytes",{enumerable:!0,get:function(){return $n.publicJwkFromBytes}});Object.defineProperty(d,"verifyDpop",{enumerable:!0,get:function(){return $n.verifyDpop}});var j=na();Object.defineProperty(d,"PVE_MAGIC",{enumerable:!0,get:function(){return j.PVE_MAGIC}});Object.defineProperty(d,"RCPT_MAGIC",{enumerable:!0,get:function(){return j.RCPT_MAGIC}});Object.defineProperty(d,"PVE_VERSION",{enumerable:!0,get:function(){return j.PVE_VERSION}});Object.defineProperty(d,"RCPT_VERSION",{enumerable:!0,get:function(){return j.RCPT_VERSION}});Object.defineProperty(d,"PVE_SIGNED_LEN",{enumerable:!0,get:function(){return j.PVE_SIGNED_LEN}});Object.defineProperty(d,"PVE_TOTAL_LEN",{enumerable:!0,get:function(){return j.PVE_TOTAL_LEN}});Object.defineProperty(d,"RCPT_SIGNED_LEN",{enumerable:!0,get:function(){return j.RCPT_SIGNED_LEN}});Object.defineProperty(d,"RCPT_TOTAL_LEN",{enumerable:!0,get:function(){return j.RCPT_TOTAL_LEN}});Object.defineProperty(d,"DELTA_KIND",{enumerable:!0,get:function(){return j.DELTA_KIND}});Object.defineProperty(d,"ABSORB_STATUS",{enumerable:!0,get:function(){return j.ABSORB_STATUS}});Object.defineProperty(d,"deltaIdFromUuid",{enumerable:!0,get:function(){return j.deltaIdFromUuid}});Object.defineProperty(d,"uuidFromDeltaId",{enumerable:!0,get:function(){return j.uuidFromDeltaId}});Object.defineProperty(d,"originJktForPublicKey",{enumerable:!0,get:function(){return j.originJktForPublicKey}});Object.defineProperty(d,"encodePveSignedBytes",{enumerable:!0,get:function(){return j.encodePveSignedBytes}});Object.defineProperty(d,"signPve",{enumerable:!0,get:function(){return j.signPve}});Object.defineProperty(d,"parsePve",{enumerable:!0,get:function(){return j.parsePve}});Object.defineProperty(d,"pveHash",{enumerable:!0,get:function(){return j.pveHash}});Object.defineProperty(d,"verifyPve",{enumerable:!0,get:function(){return j.verifyPve}});Object.defineProperty(d,"encodeReceiptDeltaSignedBytes",{enumerable:!0,get:function(){return j.encodeReceiptSignedBytes}});Object.defineProperty(d,"signReceiptDelta",{enumerable:!0,get:function(){return j.signReceipt}});Object.defineProperty(d,"parseReceiptDelta",{enumerable:!0,get:function(){return j.parseReceipt}});Object.defineProperty(d,"verifyReceiptDelta",{enumerable:!0,get:function(){return j.verifyReceipt}});var to=oa();Object.defineProperty(d,"destroyKey",{enumerable:!0,get:function(){return to.destroyKey}});Object.defineProperty(d,"replayRatchet",{enumerable:!0,get:function(){return to.replayRatchet}});Object.defineProperty(d,"stepRatchet",{enumerable:!0,get:function(){return to.stepRatchet}});var no=sa();Object.defineProperty(d,"fetchAttestation",{enumerable:!0,get:function(){return no.fetchAttestation}});Object.defineProperty(d,"parseAttestation",{enumerable:!0,get:function(){return no.parseAttestation}});Object.defineProperty(d,"verifyAttestation",{enumerable:!0,get:function(){return no.verifyAttestation}});var Ma=Yr();Object.defineProperty(d,"verifyCoseSign1Es384",{enumerable:!0,get:function(){return Ma.verifyCoseSign1Es384}});Object.defineProperty(d,"decodeAttestationPayload",{enumerable:!0,get:function(){return Ma.decodeAttestationPayload}});var Nn=da();Object.defineProperty(d,"combineShares",{enumerable:!0,get:function(){return Nn.combineShares}});Object.defineProperty(d,"deserializeShare",{enumerable:!0,get:function(){return Nn.deserializeShare}});Object.defineProperty(d,"serializeShare",{enumerable:!0,get:function(){return Nn.serializeShare}});Object.defineProperty(d,"splitSecret",{enumerable:!0,get:function(){return Nn.splitSecret}});var Kt=ha();Object.defineProperty(d,"buildCapability",{enumerable:!0,get:function(){return Kt.buildCapability}});Object.defineProperty(d,"manifestDigest",{enumerable:!0,get:function(){return Kt.manifestDigest}});Object.defineProperty(d,"openSegments",{enumerable:!0,get:function(){return Kt.openSegments}});Object.defineProperty(d,"sealSegments",{enumerable:!0,get:function(){return Kt.sealSegments}});Object.defineProperty(d,"SegmentError",{enumerable:!0,get:function(){return Kt.SegmentError}});var ro=ga();Object.defineProperty(d,"computeWatermark",{enumerable:!0,get:function(){return ro.computeWatermark}});Object.defineProperty(d,"findLeakSource",{enumerable:!0,get:function(){return ro.findLeakSource}});Object.defineProperty(d,"watermarkSvgOverlay",{enumerable:!0,get:function(){return ro.watermarkSvgOverlay}});var ce=xa();Object.defineProperty(d,"DRAND_LOE_MAINNET",{enumerable:!0,get:function(){return ce.DRAND_LOE_MAINNET}});Object.defineProperty(d,"drandTimeLockDecrypt",{enumerable:!0,get:function(){return ce.drandTimeLockDecrypt}});Object.defineProperty(d,"drandTimeLockEncrypt",{enumerable:!0,get:function(){return ce.drandTimeLockEncrypt}});Object.defineProperty(d,"drandTimeLockOpen",{enumerable:!0,get:function(){return ce.drandTimeLockOpen}});Object.defineProperty(d,"fetchDrandRound",{enumerable:!0,get:function(){return ce.fetchDrandRound}});Object.defineProperty(d,"makeFakeDrandChain",{enumerable:!0,get:function(){return ce.makeFakeDrandChain}});Object.defineProperty(d,"roundForTime",{enumerable:!0,get:function(){return ce.roundForTime}});Object.defineProperty(d,"TimeGateError",{enumerable:!0,get:function(){return ce.TimeGateError}});Object.defineProperty(d,"timeForRound",{enumerable:!0,get:function(){return ce.timeForRound}});Object.defineProperty(d,"timeGateDecrypt",{enumerable:!0,get:function(){return ce.timeGateDecrypt}});Object.defineProperty(d,"timeGateEncrypt",{enumerable:!0,get:function(){return ce.timeGateEncrypt}});var Ue=Ia();Object.defineProperty(d,"appendReceipt",{enumerable:!0,get:function(){return Ue.appendReceipt}});Object.defineProperty(d,"auditChain",{enumerable:!0,get:function(){return Ue.auditChain}});Object.defineProperty(d,"GENESIS_PREV_HASH",{enumerable:!0,get:function(){return Ue.GENESIS_PREV_HASH}});Object.defineProperty(d,"issueGenesisReceipt",{enumerable:!0,get:function(){return Ue.issueGenesisReceipt}});Object.defineProperty(d,"issueReceipt",{enumerable:!0,get:function(){return Ue.issueReceipt}});Object.defineProperty(d,"receiptHash",{enumerable:!0,get:function(){return Ue.receiptHash}});Object.defineProperty(d,"verifyReceipt",{enumerable:!0,get:function(){return Ue.verifyReceipt}});var Fa=$a();Object.defineProperty(d,"recommend",{enumerable:!0,get:function(){return Fa.recommend}});Object.defineProperty(d,"summarise",{enumerable:!0,get:function(){return Fa.summarise}});var Rn=Ra();Object.defineProperty(d,"recommendationToMandate",{enumerable:!0,get:function(){return Rn.recommendationToMandate}});Object.defineProperty(d,"showcaseChips",{enumerable:!0,get:function(){return Rn.showcaseChips}});Object.defineProperty(d,"v3OpenReceiptPayload",{enumerable:!0,get:function(){return Rn.v3OpenReceiptPayload}});Object.defineProperty(d,"v3SealReceiptPayload",{enumerable:!0,get:function(){return Rn.v3SealReceiptPayload}});var Pe=Ka();Object.defineProperty(d,"encodeFragment",{enumerable:!0,get:function(){return Pe.encodeFragment}});Object.defineProperty(d,"decodeFragment",{enumerable:!0,get:function(){return Pe.decodeFragment}});Object.defineProperty(d,"extractProofToken",{enumerable:!0,get:function(){return Pe.extractProofToken}});Object.defineProperty(d,"encodeProofToken",{enumerable:!0,get:function(){return Pe.encodeProofToken}});Object.defineProperty(d,"decodeShareCredential",{enumerable:!0,get:function(){return Pe.decodeShareCredential}});Object.defineProperty(d,"sealBytesForPublicShare",{enumerable:!0,get:function(){return Pe.sealBytesForPublicShare}});Object.defineProperty(d,"openPublicShare",{enumerable:!0,get:function(){return Pe.openPublicShare}});Object.defineProperty(d,"wrapFragmentForShortLink",{enumerable:!0,get:function(){return Pe.wrapFragmentForShortLink}})});import{McpServer as Vf}from"@modelcontextprotocol/sdk/server/mcp.js";import{StdioServerTransport as Gf}from"@modelcontextprotocol/sdk/server/stdio.js";import{z as m}from"zod";import{z as Se}from"zod";import{readdirSync as Qo,readFileSync as ei,statSync as ar}from"node:fs";import{basename as ti,join as Fc}from"node:path";var ye={text:[],header:[],secrets:[]};function Xn(e){for(let t of e.text??[])ye.text.some(n=>n.kind===t.kind)||ye.text.push(t);e.header&&!ye.header.includes(e.header)&&ye.header.push(e.header);for(let t of e.secrets??[])ye.secrets.some(n=>n.id===t.id)||ye.secrets.push(t)}function tn(){return ye.text}function Fo(){return ye.header}function Ho(){return ye.secrets}var nn=[{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 rn(){let e=Ho().filter(t=>!nn.some(n=>n.id===t.id));return[...nn,...e]}var Uo=/node_modules\/|\.next\/|\.test\.|\.spec\.|__tests__\/|\.env\.example$|\.nodata-proof\.json$|\.git\//,hc=[{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 mc(e,t){let n=i=>i.replace(/^[^0-9]*/,"").split(".").map(a=>parseInt(a,10)||0),r=n(e),o=n(t);for(let i=0;i<3;i++){if((r[i]||0)<(o[i]||0))return!0;if((r[i]||0)>(o[i]||0))return!1}return!1}function Vo(e){let t=[],n;try{n=JSON.parse(e)}catch{return t}let r={...n.dependencies??{},...n.devDependencies??{}};for(let[o,i]of Object.entries(r)){let a=(i||"").replace(/^[\^~>=<\s]+/,""),s=hc.find(c=>c.name===o&&mc(a,c.below));s&&t.push({name:o,version:a,vuln:s})}return t}var yc=[{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"}],gc=[{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"}],_c=/^(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,bc=/^שם[ _](?:ה)?(?:קובץ|מוצר|פריט|חברה|ארגון|עסק|פרויקט|גיליון|טבלה|שדה|קטגוריה|סניף|בנק|עיר|רחוב|ישוב|יישוב|מסמך|תוכנית|חבילה|קורס|מחלקה|אתר|דומיין|מותג|ספק|שירות|תפקיד)$|^(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 Re(e){if(!e)return null;let t=e.trim();if(_c.test(t)||/^name$/i.test(t))return null;let n=t.replace(/[\s-]+/g,"_");for(let r of[...gc,...yc])if(r.pattern.test(t)||r.pattern.test(n))return{type:r.type,label:r.label};if(bc.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 Fo()){let o=r(t);if(o)return{type:o.type,label:o.label}}return null}var er={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 on(e){let t=String(e??"").replace(/\D/g,"");if(t.length===0||t.length>9)return!1;let n=t.padStart(9,"0"),r=0;for(let o=0;o<9;o++){let i=parseInt(n[o]??"0",10)*(o%2+1);i>9&&(i-=9),r+=i}return r%10===0&&parseInt(n,10)>0}var ht=/(?:\+972[\s-]?|0)(?:5[0-9]|[2-4]|[89])(?:[\s-]?\d){7}/g;var mt=/\bIL\d{2}\s?(?:\d{4}\s?){4}\d{3}\b/g;function vc(e){let t=String(e??"").replace(/\D/g,"");if(t.length<12||t.length>19)return!1;let n=0,r=!1;for(let o=t.length-1;o>=0;o-=1){let i=parseInt(t[o]??"0",10);r&&(i*=2,i>9&&(i-=9)),n+=i,r=!r}return n%10===0}function Sc(e){let t=String(e??"").replace(/\s/g,"").toUpperCase();if(!/^[A-Z]{2}\d{2}[A-Z0-9]{10,30}$/.test(t))return!1;let n=t.slice(4)+t.slice(0,4),r=0;for(let o of n){let i=o>="A"&&o<="Z"?String(o.charCodeAt(0)-55):o;for(let a of i)r=(r*10+Number(a))%97}return r===1}var Zn="(?<!\\d)(?<!\\d[.,])",Qn="(?!\\d)(?![.,]\\d)",tr=[{subkind:"israeli_id",severity:"high",pattern:new RegExp(`${Zn}\\d{9}${Qn}`,"g"),validate:on,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(`${Zn}[2-6][ -]?(?:\\d[ -]?){11,17}\\d${Qn}`,"g"),validate:vc,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:Sc,hint:"Bank account in IBAN form (mod-97 verified) in plaintext."},{subkind:"israeli_phone",severity:"medium",pattern:new RegExp(`${Zn}(?:\\+972[- ]?|0)(?:[57]\\d|[2-489])[- ]?\\d{3}[- ]?\\d{4}${Qn}`,"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 Go(e){let t=[];for(let n of tr){n.pattern.lastIndex=0;let r=new Set,o,i=0;for(;(o=n.pattern.exec(e))!==null&&(i+=1,!(i>2e5));){let a=o[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 tn()){let r=new Set;for(let o of n.find(e))r.add(e.slice(o.start,o.end).trim());r.size>0&&t.push({subkind:n.kind,severity:n.severity,hint:n.hint,count:r.size})}return t}function qe(e,t){let n=[],r="",o=!1;for(let i=0;i<e.length;i++){let a=e[i];o?a==='"'&&e[i+1]==='"'?(r+='"',i++):a==='"'?o=!1:r+=a:a==='"'?o=!0:a===t?(n.push(r),r=""):r+=a}return n.push(r),n}import{inflateRawSync as $c}from"node:zlib";import{inflateSync as wc}from"node:zlib";var nr=new Set([".pdf"]),Wo=8*1024*1024;function kc(e){let t=e.toString("latin1"),n=new Map,r=/(\d+)\s+(\d+)\s+obj\b/g,o;for(;(o=r.exec(t))!==null;){let i=Number(o[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
|
+
`&&(p+=1);let h=t.indexOf("endstream",p);h>p&&(u=e.subarray(p,h))}else l=t.slice(a,s);n.set(i,{num:i,dict:l,stream:u})}return n}function xc(e){let t=e.toString("latin1").replace(/\s/g,"");t.startsWith("<~")&&(t=t.slice(2));let n=t.indexOf("~>");n>=0&&(t=t.slice(0,n));let r=[],o=0,i=0;for(let a of t){if(a==="z"&&i===0){r.push(0,0,0,0);continue}let s=a.charCodeAt(0)-33;if(s<0||s>84)return null;o=o*85+s,i+=1,i===5&&(r.push(o>>>24&255,o>>>16&255,o>>>8&255,o&255),o=0,i=0)}if(i>0){for(let s=i;s<5;s+=1)o=o*85+84;let a=[o>>>24&255,o>>>16&255,o>>>8&255,o&255];for(let s=0;s<i-1;s+=1)r.push(a[s]??0)}return Buffer.from(r)}function Ec(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 Ac(e){let t=/\/Filter\s*(\[[^\]]*\]|\/\w+)/.exec(e);return!t||!t[1]?[]:[...t[1].matchAll(/\/(\w+)/g)].map(n=>n[1]??"")}function zo(e){if(!e.stream)return null;let t=e.stream;for(let n of Ac(e.dict)){let r=null;if(n==="FlateDecode")try{r=wc(t)}catch{return null}else if(n==="ASCII85Decode")r=xc(t);else if(n==="ASCIIHexDecode")r=Ec(t);else return null;if(r===null)return null;t=r}return t.toString("latin1")}function Tc(e){let t=new Map,n=1,r=/begincodespacerange([\s\S]*?)endcodespacerange/.exec(e);if(r&&r[1]){let c=/<([0-9A-Fa-f]+)>/.exec(r[1]);c&&c[1]&&c[1].length>=4&&(n=2)}let o=c=>{let l="";for(let u=0;u+3<c.length+1;u+=4){let p=parseInt(c.slice(u,u+4),16);Number.isFinite(p)&&p>0&&(l+=String.fromCharCode(p))}return l},i=/beginbfchar([\s\S]*?)endbfchar/g,a;for(;(a=i.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),o(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,u;for(;(u=l.exec(c))!==null;){let p=parseInt(u[1]??"0",16),h=parseInt(u[2]??"0",16),f=parseInt((u[3]??"0").slice(0,4)||"0",16);if(!(h-p>65535))for(let y=p;y<=h;y+=1)t.set(y,String.fromCharCode(f+(y-p)))}}return{map:t,bytes:n}}function Pc(e){let t=new Map,n=new Map,r=[];for(let o of e.values()){let i=/\/Font\s*<<([\s\S]*?)>>/.exec(o.dict);i?.[1]&&r.push(i[1]);let a=/\/Font\s+(\d+)\s+\d+\s+R/.exec(o.dict);if(a){let s=e.get(Number(a[1]));s&&r.push(s.dict)}}for(let o of r){let i=/\/([^\s/<>[\]()]+)\s+(\d+)\s+\d+\s+R/g,a;for(;(a=i.exec(o))!==null;)n.set(a[1]??"",Number(a[2]))}for(let[o,i]of n){let a=e.get(i);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=zo(c);l&&t.set(o,Tc(l))}return t}function Jo(e){let t=[];for(let n=0;n<e.length;n+=1){let r=e[n];if(r!=="\\"){t.push(r.charCodeAt(0)&255);continue}let o=e[n+1];if(o===void 0)break;if(o>="0"&&o<="7"){let 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 i={n:10,r:13,t:9,b:8,f:12};t.push(i[o]??o.charCodeAt(0)&255),n+=1}return t}function Yo(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 qo(e,t){let n=Yo(e);if(n!==null)return n;if(!t)return e.map(o=>String.fromCharCode(o)).join("");let r="";if(t.bytes===2)for(let o=0;o+1<e.length;o+=2){let i=(e[o]??0)<<8|(e[o+1]??0);r+=t.map.get(i)??""}else for(let o of e)r+=t.map.get(o)??String.fromCharCode(o);return r}function Ic(e,t){let n="",r,o=/\/([^\s/<>[\]()]+)\s+[\d.]+\s+Tf|\((?:\\.|[^\\)])*\)|<[0-9A-Fa-f\s]*>|TJ|Tj|'|"/g,i,a="";for(;(i=o.exec(e))!==null;){let s=i[0];if(s.endsWith("Tf")){r=t.get(i[1]??"");continue}if(s==="TJ"||s==="Tj"||s==="'"||s==='"'){a&&(n+=a+`
|
|
17
|
+
`,a="");continue}if(s.startsWith("("))a+=qo(Jo(s.slice(1,-1)),r);else if(s.startsWith("<")){let c=s.slice(1,-1).replace(/\s+/g,""),l=[];for(let u=0;u+1<c.length;u+=2)l.push(parseInt(c.slice(u,u+2),16));a+=qo(l,r)}}return a&&(n+=a+`
|
|
18
|
+
`),n}function Dc(e,t){let n=e.toString("latin1"),r=/\/Info\s+(\d+)\s+\d+\s+R/.exec(n),o=r?t.get(Number(r[1]))?.dict:void 0;if(!o)return"";let i=[],a=/\/(Author|Title|Subject|Keywords|Creator|Producer)\s*(\((?:\\.|[^\\)])*\)|<[0-9A-Fa-f\s]*>)/g,s;for(;(s=a.exec(o))!==null;){let c=s[2]??"";if(c.startsWith("(")){let l=Jo(c.slice(1,-1));i.push(Yo(l)??l.map(u=>String.fromCharCode(u)).join(""))}else{let l=c.slice(1,-1).replace(/\s+/g,""),u="";if(l.toUpperCase().startsWith("FEFF"))for(let p=4;p+3<l.length+1;p+=4)u+=String.fromCharCode(parseInt(l.slice(p,p+4),16));else for(let p=0;p+1<l.length;p+=2)u+=String.fromCharCode(parseInt(l.slice(p,p+2),16));i.push(u)}}return i.join(`
|
|
19
|
+
`)}function Xo(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=kc(e);if(n.size===0)return null;let r=Pc(n),o=[];o.push(Dc(e,n));let i=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=zo(c);if(l===null||!/(TJ|Tj)\b/.test(l))continue;let u=Ic(l,r);if(u.trim().length!==0){if(a+=1,i+u.length>Wo){o.push(u.slice(0,Math.max(0,Wo-i))),s=!0;break}o.push(u),i+=u.length}}return a===0?null:{text:o.join(`
|
|
20
|
+
`),truncated:s,streams:a}}var Zo=new Set([".xlsx",".xlsm",".docx",".pptx"]),rr=8*1024*1024,Nc=101010256,Rc=33639248,Oc=67324752;function or(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)===Nc){n=a;break}if(n<0)return null;let r=e.readUInt16LE(n+10),o=e.readUInt32LE(n+16);if(o>=e.length)return null;let i=[];for(let a=0;a<r&&!(o+46>e.length||e.readUInt32LE(o)!==Rc);a+=1){let s=e.readUInt16LE(o+10),c=e.readUInt32LE(o+20),l=e.readUInt32LE(o+24),u=e.readUInt16LE(o+28),p=e.readUInt16LE(o+30),h=e.readUInt16LE(o+32),f=e.readUInt32LE(o+42),y=e.subarray(o+46,o+46+u).toString("utf8");i.push({name:y,method:s,compSize:c,uncompSize:l,localHeaderOffset:f}),o+=46+u+p+h}return i}function ir(e,t){let n=t.localHeaderOffset;if(n+30>e.length||e.readUInt32LE(n)!==Oc)return null;let r=e.readUInt16LE(n+26),o=e.readUInt16LE(n+28),i=n+30+r+o,a=i+t.compSize;if(a>e.length)return null;let s=e.subarray(i,a);try{if(t.method===0)return Buffer.from(s);if(t.method===8)return $c(s)}catch{return null}return null}function Cc(e,t){return ir(e,t)?.toString("utf8")??null}var Bc={"&":"&","<":"<",">":">",""":'"',"'":"'"};function ze(e){return e.replace(/&(amp|lt|gt|quot|apos);/g,t=>Bc[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 jc(e){return ze(e.replace(/<[^>]*>/g,`
|
|
21
21
|
`)).replace(/\n{2,}/g,`
|
|
22
|
-
`)}function
|
|
23
|
-
`+
|
|
24
|
-
`))}s+
|
|
25
|
-
`),truncated:c,parts:
|
|
26
|
-
`),
|
|
27
|
-
`),
|
|
28
|
-
<title>NoData scan \xB7 ${
|
|
22
|
+
`)}function Kc(e,t,n){let r=new RegExp(`<${t}\\b[^>]*\\b${n}="([^"]*)"`,"g"),o=[],i;for(;(i=r.exec(e))!==null;)i[1]&&o.push(ze(i[1]));return o}function Lc(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 Mc(e,t){let n=or(e);if(!n||n.length===0)return null;let r=new Map(n.map(l=>[l.name,l])),o=Lc(t,n.map(l=>l.name));if(o.length===0)return null;let i=[],a=[],s=0,c=!1;for(let l of o){if(s>=rr){c=!0;break}let u=r.get(l);if(!u)continue;let p=Cc(e,u);if(p===null)continue;let h=jc(p);if(l==="xl/workbook.xml"){let f=Kc(p,"sheet","name");f.length&&(h+=`
|
|
23
|
+
`+f.join(`
|
|
24
|
+
`))}s+h.length>rr&&(h=h.slice(0,Math.max(0,rr-s)),c=!0),h.trim().length!==0&&(i.push(h),a.push(l),s+=h.length)}return i.length===0?null:{text:i.join(`
|
|
25
|
+
`),truncated:c,parts:a}}function Oe(e,t){if(Zo.has(t))return Mc(e,t);if(nr.has(t)){let n=Xo(e);return n?{text:n.text,truncated:n.truncated,parts:[`pdf:${n.streams}-streams`]}:null}return null}var an=new Set([...Zo,...nr]);var sr=10,yt=5e3,Hc=64*1024*1024,cr=32*1024,Uc=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"]),Vc=new Set(["node_modules",".git",".hg",".svn"]),Gc=[{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."}],Wc=[{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 qc(e){let t=e.lastIndexOf(".");return t<0?"":e.slice(t).toLowerCase()}async function gt(e){let t=Date.now(),n=[],r=[],o=0,i=0,a={hit_file_cap:!1,hit_depth_cap:!1,max_files:yt,max_depth:sr,skipped_by_extension:0,documents_extracted:0,documents_truncated:0,documents_unreadable:0,files_too_large:0,files_sampled_only:0,sample_bytes:cr};function s(b){return(b.startsWith(e.target_path)?b.slice(e.target_path.length).replace(/^[\\/]+/,"")||ti(b):b).replace(/\\/g,"/")}function c(b,x,g,_,v){let k=s(b);k!==""&&r.push({target_id:e.target_id,path:k,kind:x,size_bytes:g,modified_at:_?_.toISOString():null,child_count:v})}function l(b,x){n.push({target_id:e.target_id,relative_path:b,finding_kind:x.kind,finding_subkind:x.subkind,severity:x.severity,remediation_hint:x.hint})}function u(b,x,g,_,v){n.push({target_id:e.target_id,relative_path:b,finding_kind:x,finding_subkind:_,severity:g,remediation_hint:v})}function p(b,x){if(o+=1,o>yt){a.hit_file_cap=!0;return}let g=s(b);for(let A of Wc)A.re.test(x)&&l(g,A);let _=qc(x);if(Uc.has(_)){a.skipped_by_extension+=1;return}let v=an.has(_),k=0;try{k=ar(b).size}catch{return}if(v&&k>Hc){a.files_too_large+=1;return}let T;try{let A=ei(b,{flag:"r"});T=v?A:A.subarray(0,cr)}catch{return}i+=1;let P;if(v){let A=Oe(T,_);if(!A){a.documents_unreadable+=1;return}P=A.text,a.documents_extracted+=1,A.truncated&&(a.documents_truncated+=1)}else{let A=0;for(let O=0;O<T.length;O+=1)T[O]===0&&(A+=1);if(T.length>0&&A/T.length>.05)return;P=T.toString("utf8"),k>cr&&(a.files_sampled_only+=1)}let N=new Set;for(let A of Gc)if(A.re.test(P)){let O=`${A.subkind}::${g}`;N.has(O)||(N.add(O),l(g,A))}for(let A of Go(P)){let O=`validated::${A.subkind}::${g}`;N.has(O)||(N.add(O),u(g,"pii_unencrypted",A.severity,A.subkind,`${A.hint} ${A.count} distinct value${A.count===1?"":"s"} in this file.`))}if(!Uo.test(g)){let A=rn(),O=P.split(`
|
|
26
|
+
`),C=Math.min(O.length,2e3);for(let B=0;B<C;B++){let G=O[B];if(!G)continue;let Y=G.trimStart();if(!(Y.startsWith("//")||Y.startsWith("/*")||Y.startsWith("*")||Y.startsWith("#"))&&!/process\.env/.test(G)&&!/\$\{[A-Z_]+/.test(G)){for(let z of A)if(z.pattern.test(G)){let We=`secret::${z.id}::${g}::${B+1}`;if(N.has(We))break;N.add(We),u(g,"hardcoded_secret",z.severity,z.id,`Looks like a ${z.name} hardcoded near line ${B+1}. Move to an env var or secret manager.`);break}}}}if(x==="package.json"&&!g.includes("node_modules"))try{let A=ei(b,"utf8"),O=Vo(A);for(let C of O){let B=`vuln::${C.name}::${g}`;N.has(B)||(N.add(B),u(g,"vulnerable_dependency",C.vuln.severity,C.name,`${C.name}@${C.version} is below ${C.vuln.below} (${C.vuln.cve} \xB7 ${C.vuln.desc}). Bump to ${C.vuln.below} or higher.`))}}catch{}if(_===".csv"||_===".tsv"){let A=_===".tsv"?" ":",",O=P.split(/\r?\n/);if(O.length>0){let C=qe(O[0]??"",A),B=O.slice(1,51).map(G=>qe(G??"",A));C.forEach((G,Y)=>{let z=(G??"").trim();if(!z)return;let Ne=Re(z)?.type??null;if(!Ne){let pt=[];for(let sc of B){let Jn=sc[Y];if(Jn&&Jn.trim().length>0&&pt.push(Jn),pt.length>=50)break}let ft=f(pt);ft&&(Ne=ft)}if(Ne){let pt=er[Ne]??"medium",ft=`header::${g}::${z}::${Ne}`;if(N.has(ft))return;N.add(ft),u(g,"pii_header_match",pt,`${Ne}:${z}`,`Column "${z}" looks like ${Ne} data. Wrap with envelope or move to a vault-backed reference.`)}})}}if(_===".json"&&!x.endsWith(".nodata-proof.json"))try{let A=JSON.parse(P),O=Array.isArray(A)?A[0]:A;if(O&&typeof O=="object")for(let C of Object.keys(O)){let B=Re(C);if(B){let G=er[B.type]??"medium",Y=`jsonkey::${g}::${C}::${B.type}`;if(N.has(Y))continue;N.add(Y),u(g,"pii_header_match",G,`${B.type}:${C}`,`JSON key "${C}" looks like ${B.type} data.`)}}}catch{}/\.(txt|log|md|csv|tsv|json|jsonl|xml|html?|yaml|yml|sql)$/i.test(x)&&h(P,g,N)}function h(b,x,g){let _=b.split(`
|
|
27
|
+
`),v=Math.min(_.length,1e3),k=-1,T=-1,P=-1;for(let N=0;N<v;N++){let A=_[N]??"";if(P<0){let O=A.match(/\b\d{9}\b/);O&&on(O[0])&&(P=N+1)}if(k<0&&(ht.lastIndex=0,ht.test(A)&&(k=N+1)),T<0&&(mt.lastIndex=0,mt.test(A)&&(T=N+1)),P>0&&k>0&&T>0)break}P>0&&!g.has(`ilid::${x}`)&&(g.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.`)),k>0&&!g.has(`ilphone::${x}`)&&(g.add(`ilphone::${x}`),u(x,"israeli_phone_value","high",`near_line:${k}`,`Israeli phone number detected near line ${k}.`)),T>0&&!g.has(`iliban::${x}`)&&(g.add(`iliban::${x}`),u(x,"israeli_iban_value","critical",`near_line:${T}`,`Israeli IBAN (IL prefix) detected near line ${T}.`))}function f(b){if(b.length===0)return null;let x=0,g=0,_=0;for(let k of b)typeof k=="string"&&(on(k)&&x++,ht.lastIndex=0,ht.test(k)&&g++,mt.lastIndex=0,mt.test(k)&&_++);let v=b.length;return x/v>=.3?"id":g/v>=.3?"phone":_/v>=.3?"financial":null}function y(b,x){if(x>sr){a.hit_depth_cap=!0;return}if(o>yt){a.hit_file_cap=!0;return}let g;try{g=Qo(b)}catch{return}for(let _ of g){if(o>yt)return;let v=Fc(b,_),k;try{k=ar(v)}catch{continue}if(!k.isSymbolicLink())if(k.isDirectory()){if(Vc.has(_))continue;let T=null;try{T=Qo(v).length}catch{T=null}c(v,"folder",null,k.mtime??null,T),y(v,x+1)}else k.isFile()&&(c(v,"file",k.size,k.mtime??null,null),p(v,_))}}let S,w=null;try{let b=ar(e.target_path);S=b.isDirectory()||b.isFile(),b.isFile()&&(w={size:b.size,mtime:b.mtime??null})}catch{S=!1}return S?(e.log.info("folder-scanner: starting",{target_label:e.target_label,target_path:e.target_path,max_files:yt,max_depth:sr}),w?(c(e.target_path,"file",w.size,w.mtime,null),p(e.target_path,ti(e.target_path))):y(e.target_path,0),{target_id:e.target_id,target_label:e.target_label,target_path:e.target_path,files_walked:o,files_inspected:i,duration_ms:Date.now()-t,findings:n,inventory:r,coverage:a}):{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:a,error:"target_path_not_found_or_not_directory"}}var _t={info(){}};var Je={critical:4,high:3,medium:2,low:1,info:0},pr=["critical","high","medium","low","info"];function lr(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,(Je[n.severity]??0)>(Je[r.worst]??0)&&(r.worst=n.severity),e.set(t,r)}function dr(e){return[...e.values()].sort((t,n)=>(Je[n.worst]??0)-(Je[t.worst]??0)||n.total-t.total||t.key.localeCompare(n.key))}function Ce(e){let t=e.findings??[],n={},r=new Map,o=new Map,i=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:"";lr(r,c||s.finding_kind,s);let l=s.relative_path.replace(/\\/g,"/"),u=l.includes("/")?l.slice(0,l.indexOf("/")):".";lr(o,u,s),lr(i,l,s)}let a=dr(i);return{total:t.length,bySeverity:n,byType:dr(r),byFolder:dr(o),byFile:a,filesWithFindings:a.map(s=>s.key)}}function le(e){return e.replace(/[&<>"']/g,t=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[t])}function ur(e,t,n){let r=`<tr><th>${le(n)}</th><th>total</th>${pr.map(i=>`<th class="${i}">${i}</th>`).join("")}</tr>`,o=t.map(i=>`<tr><td class="k">${le(i.key)}</td><td>${i.total}</td>${pr.map(a=>`<td>${i.bySeverity[a]??""}</td>`).join("")}</tr>`).join("");return`<h2>${le(e)} <span class="n">${t.length}</span></h2><table>${r}${o}</table>`}function fr(e,t=Ce(e)){let n=pr.filter(s=>t.bySeverity[s]).map(s=>`<span class="pill ${s}">${t.bySeverity[s]} ${s}</span>`).join(" "),r=e.coverage,o=[];r?.hit_file_cap&&o.push(`stopped at the ${r.max_files}-file cap`),r?.hit_depth_cap&&o.push(`folders deeper than ${r.max_depth} levels were not descended`),r?.files_too_large&&o.push(`${r.files_too_large} file(s) too large to read`),r?.documents_unreadable&&o.push(`${r.documents_unreadable} document(s) unreadable`);let i=[...e.findings??[]].sort((s,c)=>(Je[c.severity]??0)-(Je[s.severity]??0)),a=i.map(s=>`<tr><td><span class="pill ${s.severity}">${s.severity}</span></td><td>${le(s.finding_subkind||s.finding_kind)}</td><td class="k">${le(s.relative_path)}</td><td class="h">${le(s.remediation_hint??"")}</td></tr>`).join("");return`<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
|
|
28
|
+
<title>NoData scan \xB7 ${le(e.target_label||e.target_path)}</title>
|
|
29
29
|
<style>
|
|
30
30
|
body{margin:0;background:#FAF7F0;color:#1a1a1a;font:14px/1.5 Inter,Heebo,system-ui,sans-serif}
|
|
31
31
|
main{max-width:1100px;margin:0 auto;padding:28px 18px 60px}
|
|
@@ -38,57 +38,111 @@ td.k{font-family:ui-monospace,Menlo,monospace;font-size:12.5px;word-break:break-
|
|
|
38
38
|
.medium{color:#7a6400}.pill.medium{background:#fbf3cf}.low{color:#445}.pill.low{background:#eef0f4}
|
|
39
39
|
.note{margin-top:18px;color:#666;font-size:12.5px}
|
|
40
40
|
</style></head><body><main>
|
|
41
|
-
<h1>Scan \xB7 ${
|
|
42
|
-
<p class="sub">${
|
|
41
|
+
<h1>Scan \xB7 ${le(e.target_label||e.target_path)}</h1>
|
|
42
|
+
<p class="sub">${le(e.target_path)} \xB7 ${e.files_walked} files walked, ${e.files_inspected} inspected in ${e.duration_ms} ms \xB7 ran on this machine, nothing uploaded</p>
|
|
43
43
|
<p><strong>${t.total}</strong> findings ${n}</p>
|
|
44
|
-
${o.length?`<p class="note">Coverage: ${
|
|
45
|
-
${
|
|
46
|
-
${
|
|
47
|
-
${
|
|
48
|
-
<h2>Every finding <span class="n">${
|
|
49
|
-
<table><tr><th>severity</th><th>type</th><th>file</th><th>what to do</th></tr>${
|
|
44
|
+
${o.length?`<p class="note">Coverage: ${le(o.join("; "))}.</p>`:""}
|
|
45
|
+
${ur("By type",t.byType,"type")}
|
|
46
|
+
${ur("By folder",t.byFolder,"folder")}
|
|
47
|
+
${ur("By file",t.byFile,"file")}
|
|
48
|
+
<h2>Every finding <span class="n">${i.length}</span></h2>
|
|
49
|
+
<table><tr><th>severity</th><th>type</th><th>file</th><th>what to do</th></tr>${a}</table>
|
|
50
50
|
<p class="note">Content-free: this report lists where and what kind \u2014 never a matched value.</p>
|
|
51
|
-
</main></body></html>`}var
|
|
52
|
-
`)?`"${e.replace(/"/g,'""')}"`:e}function
|
|
53
|
-
`),counts:
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
`)
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
`))}),e.registerTool("
|
|
61
|
-
${s.join(`
|
|
62
|
-
`)}
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
`)
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
51
|
+
</main></body></html>`}var ni={israeli_id:"[ID]",credit_card:"[CARD]",iban:"[IBAN]",israeli_phone:"[PHONE]",email:"[EMAIL]"},zc=/[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}/g,Jc=[...tr].sort((e,t)=>+(t.subkind==="iban")-+(e.subkind==="iban"));function sn(e,t,n=1){e[t]=(e[t]??0)+n}function ee(e,t={}){let n=e;for(let r of Jc)r.pattern.lastIndex=0,n=n.replace(r.pattern,o=>r.validate(o)?(sn(t,r.subkind),ni[r.subkind]??`[${r.subkind.toUpperCase()}]`):o);n=n.replace(zc,()=>(sn(t,"email"),ni.email));for(let r of tn()){let o=r.find(n).sort((i,a)=>a.start-i.start);for(let i of o)n=n.slice(0,i.start)+`[${r.kind.toUpperCase()}]`+n.slice(i.end),sn(t,r.kind)}return{text:n,counts:t,columnsHidden:[]}}function hr(){let e=new Map,t={};return(n,r)=>{let o=`${n}\0${r.trim()}`,i=e.get(o);return i===void 0&&(i=t[n]=(t[n]??0)+1,e.set(o,i)),`[${n.toUpperCase()}-${i}]`}}var oi=/^\s*-?\d+(?:\.\d+)?\s*$/;function mr(e){let t=new Set;for(let[n,r]of e){let o=r.filter(a=>oi.test(a));if(o.length<3)continue;o.filter(a=>ee(a).text!==a).length/o.length<.5&&t.add(n)}return t}function ri(e,t){return e.includes(t)||e.includes('"')||e.includes(`
|
|
52
|
+
`)?`"${e.replace(/"/g,'""')}"`:e}function Yc(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 bt(e,t){let n=e.split(/\r?\n/),r=t??Yc(n[0]??""),o=qe(n[0]??"",r),i=o.map(h=>Re(h)),a={},s=hr(),c=n.slice(1).map(h=>h===""?null:qe(h,r)),l=new Map;for(let h of c)h?.forEach((f,y)=>l.set(y,[...l.get(y)??[],f]));let u=mr(l),p=[o.map(h=>ri(h,r)).join(r)];for(let h of c){if(h===null){p.push("");continue}let f=h.map((y,S)=>{let w=i[S];return w&&y.trim()!==""?(sn(a,`column:${w.type}`),s(w.type,y)):u.has(S)&&oi.test(y)?y:ee(y,a).text});p.push(f.map(y=>ri(y,r)).join(r))}return{text:p.join(`
|
|
53
|
+
`),counts:a,columnsHidden:o.filter((h,f)=>i[f])}}import{deflateRawSync as Xc}from"node:zlib";var Zc=/^xl\/(pivotCache|charts|externalLinks)\//,Qc=10;function el(e,t,n=1){e[t]=(e[t]??0)+n}function si(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}function ci(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 ze(n)}function tl(e){return e?[...e.matchAll(/<si\b[^>]*>([\s\S]*?)<\/si>|<si\b[^>]*\/>/g)].map(t=>ci(t[1]??"")):[]}var ii=/<c\b([^>]*?)(?:\/>|>([\s\S]*?)<\/c>)/g;function cn(e,t){let n=new RegExp(`\\b${t}="([^"]*)"`).exec(e);return n?n[1]:null}function yr(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?ci(r[1]):null}if(e.type==="b"||e.type==="e")return null;let n=/<v>([^<]*)<\/v>/.exec(e.inner);return n?ze(n[1]):null}function ai(e,t){return`<c${e.replace(/\s*\bt="[^"]*"/,"")} t="inlineStr"><is><t xml:space="preserve">${si(t)}</t></is></c>`}var nl=(()=>{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 rl(e){let t=4294967295;for(let n=0;n<e.length;n+=1)t=nl[(t^e[n])&255]^t>>>8;return(t^4294967295)>>>0}function li(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):Xc(a.data),u=c?0:8,p=c?0:rl(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 o=Buffer.concat(n),i=Buffer.alloc(22);return i.writeUInt32LE(101010256,0),i.writeUInt16LE(e.length,8),i.writeUInt16LE(e.length,10),i.writeUInt32LE(o.length,12),i.writeUInt32LE(r,16),Buffer.concat([...t,o,i])}function vt(e){let t=or(e);if(!t||t.length===0||t.some(f=>Zc.test(f.name)))return null;let n=new Map;for(let f of t){if(f.name.endsWith("/")){n.set(f.name,Buffer.alloc(0));continue}let y=ir(e,f);if(!y)return null;n.set(f.name,y)}let r=[...n.keys()].filter(f=>/^xl\/worksheets\/sheet\d+\.xml$/.test(f));if(r.length===0)return null;let o=n.get("xl/sharedStrings.xml")?.toString("utf8")??null,i=tl(o),a=new Set,s={},c=new Set,l=hr();for(let f of r){let y=n.get(f).toString("utf8"),S=[];for(let k of y.matchAll(ii)){let T=cn(k[1],"r"),P=T?/^([A-Z]+)(\d+)$/.exec(T):null;if(!P)return null;S.push({full:k[0],attrs:k[1],inner:k[2]??"",col:P[1],row:Number(P[2]),type:cn(k[1],"t")??"n"})}let w=[...new Set(S.map(k=>k.row))].sort((k,T)=>k-T).slice(0,Qc),b=-1,x=new Map;for(let k of w){let T=new Map;for(let P of S.filter(N=>N.row===k)){let N=yr(P,i),A=N?Re(N):null;A&&(T.set(P.col,A.type),c.add(N.trim()))}if(T.size>0){b=k;for(let[P,N]of T)x.set(P,N);break}}let g=new Map;for(let k of S){if(k.type!=="n"||k.row<=b)continue;let T=yr(k,i);T!==null&&g.set(k.col,[...g.get(k.col)??[],T])}let _=mr(g),v=y.replace(ii,(k,T,P)=>{let N=cn(T,"r"),[,A,O]=/^([A-Z]+)(\d+)$/.exec(N),C={full:k,attrs:T,inner:P??"",col:A,row:Number(O),type:cn(T,"t")??"n"},B=yr(C,i),G=()=>{if(C.type==="s"){let We=/<v>([^<]*)<\/v>/.exec(C.inner);We&&a.add(Number(We[1]))}return k};if(B===null||B.trim()==="")return G();let Y=x.get(A);if(Y&&C.row>b)return el(s,`column:${Y}`),ai(T,l(Y,B));if(C.type==="n"&&_.has(A))return G();let z=ee(B,s);return z.text===B?G():ai(T,z.text)});n.set(f,Buffer.from(v,"utf8"))}if(o){let f=-1,y=o.replace(/<si\b[^>]*>[\s\S]*?<\/si>|<si\b[^>]*\/>/g,S=>(f+=1,a.has(f)?S:"<si><t></t></si>"));n.set("xl/sharedStrings.xml",Buffer.from(y,"utf8"))}for(let f of[...n.keys()].filter(y=>/^xl\/comments\d*\.xml$/.test(y))){let S=n.get(f).toString("utf8").replace(/(<t(?:\s[^>]*)?>)([\s\S]*?)(<\/t>)/g,(w,b,x,g)=>{let _=ee(ze(x),s);return`${b}${si(_.text)}${g}`});n.set(f,Buffer.from(S,"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 y=n.get(f);y&&n.set(f,Buffer.from(y.toString("utf8").replace(/<(Override|Relationship)\b[^>]*calcChain[^>]*\/>/g,""),"utf8"))}return{bytes:li(h.map(f=>({name:f,data:n.get(f)}))),counts:s,columnsHidden:[...c]}}var se=Yn(kr(),1);import{homedir as Hl}from"node:os";import{basename as fn,dirname as hn,extname as Ul,join as xt,resolve as pn}from"node:path";import{existsSync as kt,mkdirSync as Vl,readFileSync as Gl,rmSync as Wl,statSync as Er,writeFileSync as Ir}from"node:fs";import{pathToFileURL as Dr}from"node:url";function ve(e){return/\.ndc$/i.test(e)||/\.clean\.[A-Za-z0-9]+$/.test(e)}var Xe=Yn(kr(),1);import{z as Ye}from"zod";import{existsSync as xi,rmSync as Rl,statSync as Ol}from"node:fs";import{dirname as Cl,join as Bl,relative as xr,resolve as jl}from"node:path";import{pathToFileURL as Kl}from"node:url";var Ll={critical:"Restricted",high:"Confidential",medium:"Internal",low:"Internal",info:"Internal"},Ei={critical:4,high:3,medium:2,low:1,info:0},Ai={both:"clean copy to work on + lock the original",protect:"lock",redact:"clean copy to work on",keep:"leave as is"},Ml={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 Ti(e){if(e.finding_kind==="hardcoded_secret")return"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 Ml[t]??t.replace(/_/g," ")}function Fl(e){let t=new Map;for(let o of e)t.set(o.relative_path,[...t.get(o.relative_path)??[],o]);let n=[];for(let[o,i]of t){let a=i.reduce((f,y)=>(Ei[y.severity]??0)>(Ei[f]??0)?y.severity:f,"info"),s=Ll[a]??"Internal",c=i.some(f=>f.finding_kind==="hardcoded_secret"),l=new Map;for(let f of i){let y=Ti(f);l.set(y,Math.max(l.get(y)??0,i.filter(S=>Ti(S)===y&&S.finding_kind===f.finding_kind).length))}let u=[...l].map(([f,y])=>`${y} ${f}`).join(", "),p,h;c?(p="protect",h="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"?(p="both",h="restricted data \u2014 keep a clean copy for work and lock the original away from people and AI"):s==="Confidential"?(p="protect",h="confidential personal data (IDs, accounts) \u2014 lock it; make a clean copy when you need to work on it"):(p="redact",h="internal contact data \u2014 a clean copy is enough to work safely"),n.push({file:o,tier:s,found:u,secret:c,action:p,why:h})}let r={Restricted:0,Confidential:1,Internal:2};return n.sort((o,i)=>r[o.tier]-r[i.tier]||o.file.localeCompare(i.file))}function Pi(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:Ye.string().describe("Folder or file to plan for."),actions:Ye.record(Ye.string(),Ye.enum(["both","protect","redact","keep"])).optional().describe("The user's changes, by relative path."),remove_originals:Ye.boolean().optional().describe("When locking, delete the plaintext original. Default false (originals kept)."),confirm:Ye.boolean().optional().describe("true = the user approved this plan. Omit to show it.")}},async({path:n,actions:r,remove_originals:o,confirm:i})=>{let a=jl(n);if(!xi(a))return{content:[{type:"text",text:`Nothing found at: ${a}`}],isError:!0};let s=Ol(a).isDirectory()?a:Cl(a),c=await t.scan(a),l=Fl(c.findings.filter(g=>!ve(g.relative_path)));if(l.length===0)return{content:[{type:"text",text:`No findings in ${a} \u2014 nothing to decide. ${t.who()}`}]};let u=Object.keys(r??{}).filter(g=>!l.some(_=>_.file===g)),p=l.map(g=>({...g,chosen:r?.[g.file]??g.action,changed:!!r?.[g.file]&&r[g.file]!==g.action})),h=p.map(g=>` [${g.tier}] ${g.file} \u2014 ${g.found}
|
|
54
|
+
\u2192 ${Ai[g.chosen]}${g.changed?` (changed by you; recommended: ${Ai[g.action]})`:` \u2014 ${g.why}`}`+(g.secret?`
|
|
55
|
+
\u26A0 also rotate the credential at its source (NoData cannot do that step)`:""));if(!i)return{content:[{type:"text",text:[`RECOMMENDED POLICY \u2014 nothing changed yet. ${t.who()}`,`${l.length} file(s) with findings under ${a}:`,...h,u.length?`
|
|
56
|
+
Not in the scan (ignored): ${u.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(g=>g!=="").join(`
|
|
57
|
+
`)}]};let f=[],y=[],S=[];for(let g of p){let _=Bl(s,g.file);if(!xi(_)){y.push(` \u2717 ${g.file} \u2014 no longer there`);continue}if(g.chosen==="redact"||g.chosen==="both"){let v=t.cleanCopy(_);"error"in v?y.push(` \u2717 ${g.file} \u2014 ${v.error}`):f.push(` \u2713 ${g.file} \u2192 clean copy ${xr(s,v.outPath)}`)}(g.chosen==="protect"||g.chosen==="both")&&S.push(_),g.chosen==="keep"&&f.push(` \xB7 ${g.file} \u2014 left as is (your choice)`)}let w="";if(S.length){let{key:g}=Xe.ensureDeviceKey(),_=[];for(let k of S)_.push(await Xe.sealFile(k,g)),o&&Rl(k),f.push(` \u{1F512} ${xr(s,k)} \u2192 ${xr(s,k)}.ndc${o?" (original deleted)":""}`);let v=p.map(k=>({file:k.file,tier:k.tier,recommended:k.action,chosen:k.chosen}));w=Xe.writeLocalReceipt(s,{action:"policy-apply",kid:g.kid,removed_plaintext:!!o,files:_,extra:{approved_by:t.who(),surface:"mcp",plan:v}})}let b=p.filter(g=>g.changed).length,x=await t.ack(`${p.length} files \xB7 ${b} changed by the user \xB7 ${S.length} locked`);return{content:[{type:"text",text:[`APPLIED the approved policy \u2014 ${t.who()}`,...f,...y,p.some(g=>g.secret)?"\u26A0 Remember: rotate the exposed credential(s) at their source.":"",w?`Receipt (the plan, hashes, seal ids \u2014 no content): ${Kl(w).href}`:"",`Approval kept in ~/.nodata/acks.jsonl${x?" and recorded at NoData for your organisation":""}.`].filter(Boolean).join(`
|
|
58
|
+
`)}]}})}var J=(e,t=!1)=>({content:[{type:"text",text:e}],...t?{isError:t}:{}}),Ii=xt(Hl(),".nodata","reports"),Ar=25;function ql(){return new Date().toISOString().replace(/[:.]/g,"-").slice(0,19)}function zl(e){return e.replace(/[^A-Za-z0-9_-]+/g,"_").slice(0,60)||"folder"}function Di(e){let t=Ul(e).toLowerCase(),n=Gl(e),r=t===".xlsx"||t===".xlsm"?vt(n):null;if(r){let c=xt(hn(e),`${fn(e,t)}.clean${t}`);return Ir(c,r.bytes,{mode:384}),{outPath:c,result:{text:Oe(r.bytes,t)?.text??"",counts:r.counts,columnsHidden:r.columnsHidden},note:""}}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.":"",i,a=t||".txt";if(t===".csv"||t===".tsv")i=bt(n.toString("utf8"),t===".tsv"?" ":void 0);else if(an.has(t)){let c=Oe(n,t);if(!c)return{error:`Could not read the text of ${e}.`};i=ee(c.text),a=".txt"}else i=ee(n.toString("utf8"));let s=xt(hn(e),`${fn(e,t)}.clean${a}`);return Ir(s,i.text,{mode:384}),{outPath:s,result:i,note:o}}async function Tr(e){return gt({target_id:"mcp",target_label:fn(e),target_path:e,log:_t})}function Pr(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(`
|
|
59
|
+
`)}function Jl(e,t,n,r){if(e.error)return`Could not scan ${e.target_path}: ${e.error}`;let o=["critical","high","medium","low","info"].filter(a=>t.bySeverity[a]).map(a=>`${t.bySeverity[a]} ${a}`).join(" \xB7 "),i=[`SCAN ${e.target_path}`,` ${r} \xB7 ran on this machine, nothing uploaded`,` ${e.files_walked} files walked, ${e.files_inspected} inspected, ${e.duration_ms} ms`,"",`FOUND ${t.total} findings${o?" \u2014 "+o:""} in ${t.filesWithFindings.length} files`];return t.total>0&&(i.push("","BY TYPE (all)",Pr(t.byType,100)),i.push("","BY FOLDER",Pr(t.byFolder,10)),i.push("","WORST FILES",Pr(t.byFile,12))),n&&i.push("","FULL REPORT (every finding, content-free) \u2014 open in a browser:",` ${Dr(n).href}`),t.total>0&&i.push("","NEXT \u2014 same workspace:",` \xB7 RECOMMEND a policy per file (you approve or change it): nodata_plan path: "${e.target_path}"`,` \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"),i.join(`
|
|
60
|
+
`)}function $i(e,t,n=async()=>!1){Pi(e,{who:t,scan:Tr,cleanCopy:Di,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:Se.string().optional().describe("Folder or single file to scan. Default: the directory the server runs in.")}},async({path:o})=>{let i=pn((o??".").trim()||".");if(!kt(i))return J(`Nothing found at: ${i}`);try{let a=await Tr(i),s=Ce(a),c=null;return a.error||(Vl(Ii,{recursive:!0}),c=xt(Ii,`scan-${zl(fn(i))}-${ql()}.html`),Ir(c,fr(a,s),{mode:384})),J(Jl(a,s,c,t()))}catch(a){return J(`Scan failed: ${a instanceof Error?a.message:String(a)}`,!0)}}),e.registerTool("nodata_protect",{description:"LOCK files: seal each one to this device's key as <file>.ndc (AES-256-GCM, the key never leaves this machine; the same format as `nodata protect`, so `nodata open` opens it too). Given a folder, seals only the files the scan finds exposure in; given a file, seals that file. ASKS FIRST: without confirm:true it only lists what would be sealed and changes nothing \u2014 show that list to the user and call again with confirm:true only after they approve. Writes a local receipt (hashes, seal ids) under <folder>/.nodata/receipts. remove:true also deletes the plaintext originals.",inputSchema:{path:Se.string().describe("File or folder to protect."),confirm:Se.boolean().optional().describe("true = do it. Omit to preview."),remove:Se.boolean().optional().describe("Delete the plaintext originals after sealing. Default false.")}},async({path:o,confirm:i,remove:a})=>{let s=pn(o);if(!kt(s))return J(`Not found: ${s}`,!0);let c=Er(s).isDirectory(),l;if(c?l=Ce(await Tr(s)).filesWithFindings.map(w=>xt(s,w)).filter(w=>kt(w)&&Er(w).isFile()&&!ve(w)):l=s.endsWith(".ndc")?[]:[s],l.length===0)return J(`Nothing to seal in ${s} \u2014 no file with findings.`);if(!i){let S=l.slice(0,Ar).map(w=>` \xB7 ${w}`);return l.length>Ar&&S.push(` \u2026 and ${l.length-Ar} more`),J([`PREVIEW \u2014 nothing changed yet. ${t()}`,`Would seal ${l.length} file(s) to this device's key${a?" and DELETE the plaintext originals":" (originals kept)"}:`,...S,"","Ask the user to approve, then call nodata_protect again with confirm: true."].join(`
|
|
61
|
+
`))}let{key:u,created:p}=se.ensureDeviceKey(),h=[];for(let S of l)h.push(await se.sealFile(S,u)),a&&Wl(S);let f=c?s:hn(s),y=se.writeLocalReceipt(f,{action:"protect",kid:u.kid,removed_plaintext:!!a,files:h,extra:{approved_by:t(),surface:"mcp"}});return J([`SEALED ${h.length} file(s) \u2014 ${t()}${p?" \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}`,a?"Plaintext originals deleted.":"Originals are still in place \u2014 run again with remove: true to leave only the sealed copies.",`Receipt (hashes + seal ids, content-free): ${Dr(y).href}`,'Open one again: nodata_open path: "<file>.ndc"'].join(`
|
|
62
|
+
`))}),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:Se.string().describe("The .ndc file to open."),confirm:Se.boolean().optional().describe("true = open it. Omit to preview.")}},async({path:o,confirm:i})=>{let a=pn(o),s=kt(a)?se.readManifest(a):null;if(!s)return J(`Not a NoData sealed file: ${a}`,!0);if(!i)return J(`PREVIEW \u2014 nothing changed yet. ${t()}
|
|
63
|
+
Would open "${s.orig}" (sealed ${s.sealed_at}, device key ${s.kid}) as plaintext next to ${a}.
|
|
64
|
+
Ask the user to approve, then call nodata_open again with confirm: true.`);let c=await se.openFile(a);if(!c.ok){let u=c.error==="wrong_key"?"this device's key is not the one it was sealed to":c.error==="no_device_key"?"this machine has no device key (~/.nodata/device-key.json)":c.error;return J(`Could not open ${a}: ${u}.`,!0)}let l=se.writeLocalReceipt(hn(a),{action:"open",kid:s.kid,removed_plaintext:!1,files:[{path:c.outPath,ndc:a,sha256:c.sha256,sealId:s.token.split(":").pop()??""}],extra:{approved_by:t(),surface:"mcp",hash_matches:c.intact}});return J([`OPENED ${c.outPath} \u2014 ${t()}`,c.intact?"Hash matches what was sealed \u2014 the file is unaltered.":"WARNING: hash differs from the sealed record.",`Receipt: ${Dr(l).href}`].join(`
|
|
65
|
+
`))}),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:Se.string().describe("The file to redact (csv, tsv, txt, md, json, log, docx, xlsx, pptx, pdf)."),return_text:Se.boolean().optional().describe("Also return the clean text for analysis.")}},async({path:o,return_text:i})=>{let a=pn(o);if(!kt(a)||!Er(a).isFile())return J(`Not a file: ${a}`,!0);let s=Di(a);return"error"in s?J(s.error,!0):J(r(s.outPath,s.result,i,s.note))});function r(o,i,a,s=""){let c=Object.entries(i.counts).sort((u,p)=>p[1]-u[1]).map(([u,p])=>` ${String(p).padStart(6)} ${u}`),l=[`CLEAN COPY ${o} \u2014 ${t()} \xB7 original untouched`,s,c.length?`Replaced:
|
|
66
|
+
${c.join(`
|
|
67
|
+
`)}`:"Nothing sensitive detected \u2014 the copy equals the original text.",i.columnsHidden.length?`Columns hidden whole: ${i.columnsHidden.join(", ")}`:""].filter(Boolean);return a&&l.push("",`--- clean text${i.text.length>6e4?" (first 60000 chars)":""} ---`,i.text.slice(0,6e4)),l.join(`
|
|
68
|
+
`)}}var Cn=Yn(Ha(),1);import{z as Ve}from"zod";import{createHash as sp}from"node:crypto";import{existsSync as io,mkdirSync as cp,readFileSync as qa,readdirSync as lp,statSync as Ua,writeFileSync as dp}from"node:fs";import{homedir as up}from"node:os";import{basename as oo,extname as pp,join as za,resolve as fp}from"node:path";var Q=(e,t=!1)=>({content:[{type:"text",text:e}],...t?{isError:t}:{}}),On=za(up(),".nodata","shares"),hp=12*1024*1024,mp={".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 Ja(e){return za(On,`${e.replace(/[^a-f0-9]/gi,"")}.json`)}function Va(e){let t=Ja(e);if(!io(t))return null;try{return JSON.parse(qa(t,"utf8"))}catch{return null}}function Ga(e){let t=e.match(/\/lock\/open\/([a-f0-9]{8,64})/i);return(t?t[1]:e.trim()).toLowerCase()}async function Wa(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 Ya(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:Ve.string().describe("The file to send (up to 12 MB)."),ttl_hours:Ve.number().optional().describe("Hours until the link expires. Default 72, max 168 (7 days)."),max_opens:Ve.number().optional().describe("Opens allowed before it burns itself. Default 3, max 1000."),confirm:Ve.boolean().optional().describe("true = send it. Omit to preview.")}},async({path:o,ttl_hours:i,max_opens:a,confirm:s})=>{let c=fp(o);if(!io(c)||!Ua(c).isFile())return Q(`Not a file: ${c}`,!0);let l=Ua(c).size;if(l>hp)return Q(`${oo(c)} is ${(l/1048576).toFixed(1)} MB; a governed link carries up to 12 MB.`,!0);let u=Math.round(Math.min(Math.max(i??72,1/60),168)*3600),p=Math.round(Math.min(Math.max(a??3,1),1e3));if(!s)return Q([`PREVIEW \u2014 nothing sent yet. ${r()}`,`Would send "${oo(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 ${(u/3600).toFixed(u<3600?2:0)} h, or after ${p} open(s)`," \xB7 revocable any time with nodata_burn; every open is counted","","Ask the user to approve, then call nodata_send again with the same arguments and confirm: true."].join(`
|
|
69
|
+
`));let h=qa(c),f=oo(c),y=mp[pp(c).toLowerCase()]??"application/octet-stream",S=await(0,Cn.sealBytesForPublicShare)({bytes:h,filename:f,contentType:y,ttlSeconds:u,server:t}),w=await(0,Cn.wrapFragmentForShortLink)(S.fragment),b;try{b=await Wa(`${t}/api/lock/public/issue`,{formatVersion:3,lockboxId:S.lockboxId,containerB64:Buffer.from(S.container).toString("base64"),filename:f,contentType:y,ttlSeconds:u,maxOpens:p,wrappedFragmentB64:w.wrappedFragmentB64,wrapIvB64:w.wrapIvB64},await n())}catch(_){return Q(`Could not reach NoData: ${_ instanceof Error?_.message:String(_)}`,!0)}if(b.status>=400||b.body.ok!==!0)return Q(`Send refused (HTTP ${b.status}): ${JSON.stringify(b.body)}`,!0);let x=String(b.body.id),g={id:x,file:c,filename:f,sha256:sp("sha256").update(h).digest("hex"),link:`${t}/lock/open/${x}#${w.wrapKeyB64Url}`,wrap_key_b64url:w.wrapKeyB64Url,expires_at:String(b.body.expiresAt??""),max_opens:p,sent_by:r(),sent_at:new Date().toISOString(),receipt_id:b.body.receipt_id??null,proof_url:b.body.proof_url??null};return cp(On,{recursive:!0}),dp(Ja(x),JSON.stringify(g,null,2)+`
|
|
70
|
+
`,{mode:384}),Q([`SENT "${f}" \u2014 ${r()}`,"Link (give this to the recipient; anyone holding it can open it until it expires or is burned):",` ${g.link}`,`Expires ${g.expires_at} \xB7 max ${p} open(s) \xB7 id ${x}`,g.proof_url?`Proof (signed receipt, public): ${g.proof_url}`:"No receipt: the link was not attributed to an organization.",`Check it: nodata_link_status id: "${x}" \xB7 Revoke it: nodata_burn id: "${x}"`].join(`
|
|
71
|
+
`))}),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:Ve.string().optional().describe("Share id or /lock/open link. Omit to list all.")}},async({id:o})=>{let i=o?[Ga(o)]:io(On)?lp(On).filter(s=>s.endsWith(".json")).map(s=>s.slice(0,-5)):[];if(i.length===0)return Q("No links sent from this machine yet. Send one with nodata_send.");let a=[`LINKS \u2014 ${r()}`];for(let s of i.slice(0,50)){let c=Va(s),l={};try{let p=await fetch(`${t}/api/lock/public/status/${s}`);l=await p.json().catch(()=>({})),p.status===404&&(l={missing:!0})}catch{l={unreachable:!0}}let u=l.missing?"not found":l.unreachable?"status unavailable":l.burned?"BURNED":l.expired?"expired":"live";a.push(` ${s} ${u.padEnd(10)} opens ${l.openCount??"?"}/${l.maxOpens??c?.max_opens??"?"} expires ${l.expiresAt??c?.expires_at??"?"} ${c?c.filename:""}`)}return Q(a.join(`
|
|
72
|
+
`))}),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:Ve.string().describe("Share id or the /lock/open link."),confirm:Ve.boolean().optional().describe("true = burn it. Omit to preview.")}},async({id:o,confirm:i})=>{let a=Ga(o),s=o.match(/#([A-Za-z0-9_-]{43})/)?.[1],c=Va(a),l=c?.wrap_key_b64url??s;if(!l)return Q(`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(!i)return Q(`PREVIEW \u2014 nothing burned yet. ${r()}
|
|
73
|
+
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 u;try{u=await Wa(`${t}/api/lock/public/burn/${a}`,{wrapKeyB64Url:l})}catch(p){return Q(`Could not reach NoData: ${p instanceof Error?p.message:String(p)}`,!0)}return u.status>=400||u.body.ok!==!0?Q(`Burn refused (HTTP ${u.status}): ${JSON.stringify(u.body)}`,!0):Q([`BURNED ${a} \u2014 ${r()}. The ciphertext is zeroed; the link is dead for everyone.`,u.body.proof_url?`Proof (signed receipt, public): ${u.body.proof_url}`:""].filter(Boolean).join(`
|
|
75
|
+
`))})}import{appendFileSync as yp,copyFileSync as Xa,existsSync as uo,mkdirSync as po,readFileSync as fo,statSync as es,writeFileSync as ts}from"node:fs";import{homedir as De}from"node:os";import{basename as gp,extname as ns,isAbsolute as _p,join as Ie,resolve as bp}from"node:path";var vp=new Set([".csv",".tsv",".txt",".md",".json",".log",".xml",".sql",".yaml",".yml",".xlsx",".xlsm",".docx",".pptx",".pdf"]),Sp=50*1024*1024,wp=8,kp={israeli_id:"Israeli ID",credit_card:"card",iban:"IBAN",israeli_phone:"phone",email:"email",secret:"secret"};function rs(e){let t=gp(e).toLowerCase();return vp.has(ns(t))||t===".env"||t.startsWith(".env.")}function xp(e){let t=ns(e).toLowerCase(),n=fo(e),r,o;if(t===".csv"||t===".tsv")o=n.toString("utf8"),r=bt(o,t===".tsv"?" ":void 0).counts;else if(t===".xlsx"||t===".xlsm"||t===".docx"||t===".pptx"||t===".pdf"){let a=t===".xlsx"||t===".xlsm"?vt(n):null;o=Oe(n,t)?.text??"",r=a?a.counts:ee(o).counts}else o=n.toString("utf8"),r=ee(o).counts;let i=nn.filter(a=>a.pattern.test(o)).length;return i&&(r.secret=(r.secret??0)+i),r}function Ep(e){return Object.entries(e).sort((t,n)=>n[1]-t[1]).map(([t,n])=>`${n} ${t.startsWith("column:")?`${t.slice(7)} (column)`:kp[t]??t}`).join(", ")}function Ap(e,t,n){let r=i=>_p(i)?i:bp(n,i),o=i=>{try{return es(i).isFile()}catch{return!1}};if(e==="Read"&&typeof t.file_path=="string")return[r(t.file_path)];if(e==="Grep"&&typeof t.path=="string"&&o(r(t.path)))return[r(t.path)];if(e==="Bash"&&typeof t.command=="string"){let i=t.command.match(/"[^"]*"|'[^']*'|[^\s|;&<>()]+/g)??[],a=[];for(let s of i){let c=r(s.replace(/^['"]|['"]$/g,"").replace(/^~(?=\/)/,De()));if(rs(c)&&o(c)&&!a.includes(c)&&a.push(c),a.length>=wp)break}return a}return[]}function ao(e){return e.replace(/\\+/g,"/")}function Tp(e,t,n,r){let o=[];for(let a of Ap(e,t,n)){if(!rs(a)||ve(a)||!uo(a))continue;let s;try{if(es(a).size>Sp)s=`${ao(a)}: too large to check here (over 50 MB)`;else{let c=xp(a);if(Object.keys(c).length===0)continue;s=`${ao(a)}: ${Ep(c)}`}}catch{s=`${ao(a)}: could not be checked`}o.push(s)}if(o.length===0)return{decision:"allow"};let i=`NoData scanned this on your machine before the assistant reads it:
|
|
76
|
+
${o.join(`
|
|
77
|
+
`)}
|
|
78
|
+
Reading it puts these values in front of the AI. Safer: nodata_redact (a clean copy to work on) or nodata_protect (lock it).`+(r?"":" Allow this read anyway?");return{decision:r?"deny":"ask",reason:i}}function Pp(e){try{let t=Ie(De(),".nodata");po(t,{recursive:!0}),yp(Ie(t,"gate.log"),JSON.stringify({at:new Date().toISOString(),...e})+`
|
|
79
|
+
`,{mode:384})}catch{}}async function os(e){let t=e.includes("--block"),n="";for await(let a of process.stdin)n+=a;let r;try{r=JSON.parse(n)}catch{return}let o=r.tool_name??"",i=Tp(o,r.tool_input??{},r.cwd??process.cwd(),t);i.decision!=="allow"&&(Pp({tool:o,decision:i.decision}),process.stdout.write(JSON.stringify({hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:i.decision,permissionDecisionReason:i.reason}})))}var so=()=>Ie(De(),".nodata","gate.mjs"),ho=()=>Ie(De(),".claude","settings.json"),Za="Read|Grep|Bash",Qa=()=>Ie(De(),".nodata","status.mjs"),co=()=>Ie(De(),".nodata","statusline-prev.json"),is=e=>!!e&&(e.command.includes(".nodata/status.mjs")||e.command.includes(".nodata\\status.mjs")),lo=e=>(e.hooks??[]).some(t=>t.command.includes(".nodata/gate.mjs")||t.command.includes(".nodata\\gate.mjs"));function as(){let e=ho();return uo(e)?JSON.parse(fo(e,"utf8")):{}}function ss(e){po(Ie(De(),".claude"),{recursive:!0}),ts(ho(),JSON.stringify(e,null,2)+`
|
|
80
|
+
`)}function cs(e,t){po(Ie(De(),".nodata"),{recursive:!0}),Xa(e,so());let n=as(),r=n.hooks??={},o=(r.PreToolUse??=[]).filter(i=>!lo(i));return o.push({matcher:Za,hooks:[{type:"command",command:`node "${so().replace(/\\/g,"/")}"${t?" --block":""}`,timeout:30}]}),r.PreToolUse=o,Xa(new URL("./status.js",e),Qa()),n.statusLine&&!is(n.statusLine)&&ts(co(),JSON.stringify(n.statusLine,null,2)+`
|
|
81
|
+
`),n.statusLine={type:"command",command:`node "${Qa().replace(/\\/g,"/")}"`},ss(n),`NoData read gate installed (${t?"block":"ask"} mode).
|
|
82
|
+
hook: ${ho()} \u2192 PreToolUse ${Za}
|
|
83
|
+
scanner: ${so()}
|
|
84
|
+
Before Claude Code reads a data file (csv, xlsx, docx, pdf, .env \u2026), NoData scans it here.
|
|
85
|
+
Findings \u2192 ${t?"the read is refused":"you are asked first"}, with the counts and the safer step.
|
|
86
|
+
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 ls(){let e=as(),t=e.hooks?.PreToolUse;if(!t||!t.some(lo))return"The NoData read gate is not installed.";if(e.hooks.PreToolUse=t.filter(n=>!lo(n)),e.hooks.PreToolUse.length===0&&delete e.hooks.PreToolUse,is(e.statusLine)){let n=uo(co())?JSON.parse(fo(co(),"utf8")):null;n?e.statusLine=n:delete e.statusLine}return ss(e),"NoData read gate removed. Restart Claude Code to unload it."}var Ip=[{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 Dp(e){if(e.length!==9)return!1;let t=e.split("").map(Number),n=0;for(let r=0;r<9;r++){let o=t[r]*(r%2===0?1:2);o>9&&(o-=9),n+=o}return n%10===0}var Bn=class{constructor(t){this.enabledTypes=new Set(t)}detect(t){let n=[],r=new Set;for(let i of Ip)if(this.enabledTypes.has(i.type))for(let a of i.patterns){let s=new RegExp(a.source,a.flags),c;for(;(c=s.exec(t))!==null;){let l=c[0],u=`${i.type}:${c.index}`;if(!r.has(u)){if(r.add(u),i.type==="id_number"){let p=l.replace(/\D/g,"");if(/^\d{9}$/.test(l)&&p.length===9&&!Dp(p))continue}n.push({type:i.type,value:l,startIndex:c.index,endIndex:c.index+l.length,confidence:i.confidence,replacement:i.replacement(l,i.type)})}}}n.sort((i,a)=>i.startIndex-a.startIndex||a.confidence-i.confidence);let o=[];for(let i of n)o.some(s=>i.startIndex<s.endIndex&&i.endIndex>s.startIndex)||o.push(i);return o}};var $p=[{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 ds(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 $p)if(r.phrases?.some(i=>t.includes(i))||r.tokens?.some(i=>n.has(i)))return{type:r.type,label:r.type,labelHe:Np(r.type)};return null}function Np(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"}var us={_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 Op=[{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."}],Cp=/^(?:לקוח|מטופל|מועמד|שם|נהג|מבוטח|תובע|נתבע|שוכר|מחזיק|עו"ד|ד"ר|פרופ'|מר|גברת|חשבון|ח-ן|[בהוכלמש]{0,2}אבחנ[הות]|תאריך לידה|נולד|נולדה|ד\.ל\.|[בהוכלמש]{0,2}גיל)\s*:?\s*/;function Bp(e,t,n,r){if(r==="address")return{start:t,end:n};let o=Cp.exec(e.slice(t,n));return o&&t+o[0].length<n?{start:t+o[0].length,end:n}:{start:t,end:n}}var jp=new Set(["hex-secret-32","base64-secret"]),ps=!1;function fs(){if(ps)return;ps=!0;let e=Op.map(({type:n,kind:r,severity:o,hint:i})=>{let a=new Bn([n]);return{kind:r,severity:o,hint:i,find:s=>a.detect(s).map(c=>Bp(s,c.startIndex,c.endIndex,r))}}),t=us.rules.filter(n=>!jp.has(n.id)).map(n=>({id:n.id,name:n.name,severity:n.severity,pattern:new RegExp(n.pattern)}));Xn({text:e,header:n=>{let r=ds(n);return r?{type:r.type,label:r.labelHe||r.label}:null},secrets:t})}import{z as Up}from"zod";import{existsSync as Vp,mkdirSync as Gp,readFileSync as Wp,writeFileSync as qp}from"node:fs";import{homedir as ys,hostname as jn}from"node:os";import{join as ut}from"node:path";function Ge(e){if(e===null||typeof e!="object")return JSON.stringify(e);if(Array.isArray(e))return"["+e.map(Ge).join(",")+"]";let t=e;return"{"+Object.keys(t).sort().map(r=>JSON.stringify(r)+":"+Ge(t[r])).join(",")+"}"}import{mkdirSync as Kp,readFileSync as mo,writeFileSync as yo,existsSync as go,chmodSync as Lp,statSync as Mp}from"node:fs";import{join as bo}from"node:path";import vo from"node:crypto";function Lt(e){return bo(e,"agent-private-key.pem")}function So(e){return bo(e,"agent-public-key.pem")}function _o(e){return bo(e,"agent-key-meta.json")}function wo(e){Kp(e,{recursive:!0});let t=Lt(e),n=So(e);if(go(t)&&go(n))try{return Fp(e)}catch(r){throw new Error(`agent keystore corrupted at ${e}: ${r.message}`)}return Hp(e)}function Fp(e){let t=mo(Lt(e),"utf8"),n=mo(So(e),"utf8"),r=go(_o(e))?JSON.parse(mo(_o(e),"utf8")):{},o=vo.createPrivateKey({key:t,format:"pem"});if(o.asymmetricKeyType!=="ed25519")throw new Error(`expected ed25519 key, got ${o.asymmetricKeyType}`);return{privateKey:o,publicKeyPem:n,generatedAt:r.generatedAt??new Date(Mp(Lt(e)).mtime).toISOString()}}function Hp(e){let{publicKey:t,privateKey:n}=vo.generateKeyPairSync("ed25519"),r=n.export({type:"pkcs8",format:"pem"}),o=t.export({type:"spki",format:"pem"}),i=new Date().toISOString();if(yo(Lt(e),r,{encoding:"utf8"}),yo(So(e),o,{encoding:"utf8"}),yo(_o(e),JSON.stringify({generatedAt:i},null,2),"utf8"),process.platform!=="win32")try{Lp(Lt(e),384)}catch{}return{privateKey:n,publicKeyPem:o,generatedAt:i}}function Mt(e,t){return vo.sign(null,Buffer.from(t,"utf8"),e.privateKey).toString("hex")}var hs=3e4,Ft=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(hs)})}catch(o){let i=o;if(i?.name==="TimeoutError"||i?.name==="AbortError")throw new Error(`${t} timed out after ${hs}ms (${r})`);let a=i?.cause?.code;throw new Error(`${t} could not reach ${r}${a?` (${a})`:""}: ${i?.message??String(o)}`)}}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=Ge({deployment_id:t.deployment_id,agent_version:t.agent_version,applied_config:t.applied_config??null,discovered_release_version:t.discovered_release_version??null}),o=Mt(n,r),i={...t,signature_hex:o},a=await this.request("/api/capsule/heartbeat",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(i)}),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,...o}=t,i=Ge(o),a=Mt(n,i),s={deployment_id:r,...o,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=Ge(t),o=Mt(n,r),i={...t,signature_hex:o},a=await this.request("/api/capsule/scan/submit",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(i)}),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,...o}=t,i=Ge(o),a=Mt(n,i),s={deployment_id:r,...o,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 ae="2026-09-24-v3";var zp=300*1e3,Jp=1440*60*1e3,Ut=()=>ut(ys(),".nodata"),Kn=()=>ut(Ut(),"capsule.json"),ms=()=>ut(Ut(),"capsule-agents.json"),gs=()=>ut(Ut(),"capsule-key");function Mn(e){try{return Vp(e)?JSON.parse(Wp(e,"utf8")):null}catch{return null}}function Ln(e,t){Gp(Ut(),{recursive:!0}),qp(e,JSON.stringify(t,null,2)+`
|
|
88
|
+
`,{mode:384})}function xo(){return Mn(Kn())}function Yp(e){let t=Date.now(),n=Mn(ms())??{};n[e]=t;let r=Object.fromEntries(Object.entries(n).filter(([,o])=>t-o<Jp));return Ln(ms(),r),Object.keys(r).sort()}function _s(){let t=(Mn(ut(ys(),".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 bs(){return Mn(ut(Ut(),"consent.json"))?.terms_version??null}var Ht=null;async function ko(e){let t=xo();if(!t)return null;let n=Yp(e.agent()),r=new Ft(t.api_base);try{let o=await r.heartbeat({deployment_id:t.deployment_id,agent_version:`mcp-${e.version}`,applied_config:{scan_interval_minutes:Ht?.scan_interval_minutes??1440,release_channel:Ht?.release_channel??"stable",enabled_apps:Ht?.enabled_apps??null,scan_scope:{surface:"mcp",host:jn(),agents:n,gate:_s(),terms_version:bs(),current_terms:ae}}},wo(gs()));Ht=o.desired_config??Ht;let i={...t,last_heartbeat_ok_at:new Date().toISOString(),last_error:null,revoked:!!o.revoked};return Ln(Kn(),i),i}catch(o){let i={...t,last_error:o instanceof Error?o.message.slice(0,200):String(o)};return Ln(Kn(),i),i}}function Eo(e){if(!xo())return;let t=()=>{ko(e)};setTimeout(t,3e3).unref(),setInterval(t,zp).unref()}function Xp(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 vs(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:Up.boolean().optional().describe("true = register this machine. Omit to see status / preview.")}},async({confirm:n})=>{let r=xo();if(r){let h=await ko(t);return{content:[{type:"text",text:[`CAPSULE NODE ${r.deployment_id} \u2014 org ${r.org_id} \xB7 ${t.who()}`,` last verified heartbeat: ${Xp(h?.last_heartbeat_ok_at)}${h?.last_error?` (last error: ${h.last_error})`:""}`,h?.revoked?" \u26A0 The organisation has paused this node.":"",` reported: host ${jn()}, agents, read gate ${_s()??"off"}, terms ${bs()??"not accepted"} \u2014 no content.`].filter(Boolean).join(`
|
|
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 (${jn()}) 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(`
|
|
90
|
+
`)}]};let o=await t.org.token();if(!o)return{content:[{type:"text",text:"No usable org credential \u2014 run nodata_connect."}],isError:!0};let i=await fetch(`${t.org.baseUrl}/api/v1/tenants/${encodeURIComponent(t.org.id)}/capsule/install-token`,{method:"POST",headers:{authorization:`Bearer ${o}`}}),a=await i.json().catch(()=>({}));if(!i.ok||!a.install_token)return{content:[{type:"text",text:`Could not start registration (HTTP ${i.status}): ${a.error??"no install token"}`}],isError:!0};let s=wo(gs()),l=await new Ft(t.org.baseUrl).enroll({install_token:a.install_token,pubkey_pem:s.publicKeyPem,agent_version:`mcp-${t.version}`,agent_kind:"npm_cli"});Ln(Kn(),{deployment_id:l.deployment_id,org_id:t.org.id,api_base:t.org.baseUrl,enrolled_at:new Date().toISOString()});let u=await ko(t);Eo(t);let p=await t.ack(`node ${l.deployment_id} on ${jn()}`);return{content:[{type:"text",text:[`REGISTERED \u2014 this machine is Capsule node ${l.deployment_id} of org ${t.org.id}. ${t.who()}`,` first heartbeat: ${u?.last_heartbeat_ok_at?"verified":`failed (${u?.last_error??"unknown"})`}`," the status line now shows when NoData last verified this node.",`Approval kept in ~/.nodata/acks.jsonl${p?" and recorded at NoData for your organisation":""}.`].join(`
|
|
91
|
+
`)}]}})}import{z as Vt}from"zod";import{spawn as Zp}from"node:child_process";import{createHash as Qp,randomBytes as ef}from"node:crypto";import{existsSync as Ao,mkdirSync as tf,readFileSync as nf,rmSync as rf,statSync as of,writeFileSync as af}from"node:fs";import{homedir as Ss}from"node:os";import{join as ws,resolve as sf}from"node:path";var qt=()=>ws(Ss(),".nodata","secrets.json"),Wt=64*1024,cf=600*1e3,lf=6;function df(){try{return Ao(qt())?JSON.parse(nf(qt(),"utf8")):null}catch{return null}}function uf(e){return new Promise(t=>{let n=process.stdin;if(process.stderr.write(e),!n.isTTY){let i="";n.setEncoding("utf8"),n.on("data",a=>i+=a),n.on("end",()=>t(i.trim()));return}let r="";n.setRawMode(!0),n.resume(),n.setEncoding("utf8");let o=i=>{for(let a of i){if(a==="\r"||a===`
|
|
92
|
+
`)return n.setRawMode(!1),n.pause(),n.off("data",o),process.stderr.write(`
|
|
93
|
+
`),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",o)})}async function ks(e,t){let n=e.indexOf("--project"),r=n>=0?e[n+1]??null:null,o=await uf("Paste your NoData CLI token (ndcs_\u2026; Courier \u2192 \u{1F511} \u05E1\u05D5\u05D3\u05D5\u05EA \u2192 CLI token). It is not shown: ");return o.startsWith("ndcs_")?(tf(ws(Ss(),".nodata"),{recursive:!0}),af(qt(),JSON.stringify({token:o,base_url:t,project:r,saved_at:new Date().toISOString()},null,2)+`
|
|
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 xs(){return Ao(qt())?(rf(qt()),"\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 pf(e,t){let n=e,r=0,o=[];for(let[i,a]of Object.entries(t)){if(!a||a.length<lf)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)]))o.push([c,`[secret:${i}]`])}o.sort((i,a)=>a[0].length-i[0].length);for(let[i,a]of o){let s=n.split(i);s.length>1&&(r+=s.length-1,n=s.join(a))}for(let i of rn()){let a=new RegExp(i.pattern.source,i.pattern.flags.includes("g")?i.pattern.flags:i.pattern.flags+"g");n=n.replace(a,s=>s.startsWith("[secret")?s:(r++,`[secret:${i.id}]`))}return{text:n,blanked:r}}function ff(e){return e.length>Wt?`\u2026 (${e.length-Wt} earlier characters not shown)
|
|
96
|
+
`+e.slice(-Wt):e}function hf(e,t,n,r){return new Promise(o=>{let i=Date.now(),a=Zp(e,{cwd:t,env:n,shell:!0,stdio:["ignore","pipe","pipe"]}),s="",c=!1,l=p=>{if(s+=p.toString("utf8"),s.length>Wt*32){let h=s.slice(-Wt*16);s=h.slice(h.indexOf(`
|
|
97
|
+
`)+1)}};a.stdout.on("data",l),a.stderr.on("data",l);let u=setTimeout(()=>{c=!0,a.kill("SIGTERM")},r);a.on("error",p=>{clearTimeout(u),o({code:null,output:s+`
|
|
98
|
+
${p.message}`,timedOut:c,ms:Date.now()-i})}),a.on("close",p=>{clearTimeout(u),o({code:p,output:s,timedOut:c,ms:Date.now()-i})})})}async function mf(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 Gt=new Map,yf=(e,t,n)=>Qp("sha256").update(`${e}\0${t}\0${n??""}`).digest("hex");function Es(e,t){let n=t.pull??mf;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:Vt.string().min(1).describe("The exact command line to run, e.g. `npm test`."),cwd:Vt.string().optional().describe("Folder to run in. Default: the current folder."),project:Vt.string().optional().describe("Secrets project label. Default: the token's project."),timeout_seconds:Vt.number().int().min(5).max(1800).optional().describe("Default 300."),approval:Vt.string().optional().describe("The code from the preview \u2014 only after the user approved this exact command.")}},async({command:r,cwd:o,project:i,timeout_seconds:a,approval:s})=>{let c=df();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
|
+
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=sf(o??process.cwd());if(!Ao(l)||!of(l).isDirectory())return{content:[{type:"text",text:`No such folder: ${l}`}],isError:!0};let u=i??c.project??null,p=yf(r,l,u),h=[` command: ${r}`,` folder: ${l}`,` secrets: ${u?`project "${u}"`:"the token's secrets"} (values stay hidden from the agent)`].join(`
|
|
101
|
+
`),f;if(e.server.getClientCapabilities()?.elicitation){let g;try{g=(await e.server.elicitInput({message:`NoData \u2014 run this command with your secrets?
|
|
102
|
+
${h}
|
|
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(_){return{content:[{type:"text",text:`NOT RUN \u2014 no approval was received from the user${_ instanceof Error?` (${_.message.slice(0,80)})`:""}. ${t.who()}`}],isError:!0}}if(g!=="accept")return await t.ack(`declined \xB7 ${u??"token project"}`),{content:[{type:"text",text:`NOT RUN \u2014 the user did not approve. ${t.who()}`}]};f="user-dialog"}else{let g=Date.now();for(let[v,k]of Gt)g-k.at>cf&&Gt.delete(v);let _=s?Gt.get(s):void 0;if(!_||_.bind!==p){let v=ef(4).toString("hex");return Gt.set(v,{bind:p,at:g}),{content:[{type:"text",text:[`PREVIEW \u2014 nothing run yet. ${t.who()}`,h,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: "${v}" (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(`
|
|
105
|
+
`)}]}}Gt.delete(s),f="code"}let y=await n(c,u);if("error"in y)return{content:[{type:"text",text:`Could not get the secrets (${y.error}). Nothing was run.`}],isError:!0};let S=Object.keys(y.secrets).sort(),w=await hf(r,l,{...process.env,...y.secrets},(a??300)*1e3),b=pf(w.output,y.secrets),x=await t.ack(`${y.project??"token project"} \xB7 ${S.length} secrets \xB7 exit ${w.code??"none"}${w.timedOut?" (timed out)":""} \xB7 approved by ${f}`);return{content:[{type:"text",text:[`RAN with ${S.length} secret(s) from ${y.project?`project "${y.project}"`:"the token's secrets"} \u2014 ${t.who()}`,` exit ${w.code??"none"}${w.timedOut?" (stopped: timeout)":""} \xB7 ${(w.ms/1e3).toFixed(1)}s \xB7 ${b.blanked} secret value(s) blanked in the output`,S.length?` injected (names only): ${S.join(", ")}`:" no secrets were granted to this token \u2014 the command ran without any",`Approval kept in ~/.nodata/acks.jsonl${x?" and recorded at NoData for your organisation":""}; each released value has its own proof at NoData.`,"","\u2500\u2500 output (secret values blanked) \u2500\u2500",ff(b.text)||"(no output)"].join(`
|
|
106
|
+
`)}],isError:w.code!==0}})}var As=["\u{1F7E3}","\u{1F535}","\u{1F7E0}","\u{1F7E4}","\u{1F7E1}"];function gf(e){let t=0;for(let n of e)t=t*31+n.codePointAt(0)>>>0;return As[t%As.length]}function To(e,t){let n=(e||"agent").toLowerCase().replace(/[^a-z0-9._-]+/g,"-").slice(0,40);return t?`${n}@${t}`:n}function Ts(e){return`${gf(e)} ${e}`}import{z as _f}from"zod";import{createHash as Is}from"node:crypto";import{appendFileSync as bf,existsSync as Ds,mkdirSync as $s,readFileSync as Ns,writeFileSync as vf}from"node:fs";import{homedir as Sf}from"node:os";import{join as Hn}from"node:path";var wf=new Set(["nodata_terms","nodata_get_started","nodata_connect"]),zt=()=>Hn(Sf(),".nodata"),Fn=()=>Hn(zt(),"consent.json");function Un(){try{return Ds(Fn())?JSON.parse(Ns(Fn(),"utf8")):null}catch{return null}}function Vn(){return Un()?.terms_version===ae}function Rs(e){$s(zt(),{recursive:!0}),vf(Fn(),JSON.stringify(e,null,2)+`
|
|
107
|
+
`,{mode:384})}async function Po(e,t){try{let n=await e.token();if(!n)return!1;let r=await fetch(`${e.baseUrl}/api/audit-log`,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${n}`},body:JSON.stringify(t)}),o=await r.json().catch(()=>({}));return r.ok&&o.logged===!0}catch{return!1}}async function Jt(e,t,n,r){let o=new Date().toISOString(),i=Is("sha256").update(`${t}|${n}|${r}|${o}`).digest("hex");try{$s(zt(),{recursive:!0}),bf(Hn(zt(),"acks.jsonl"),JSON.stringify({at:o,context:t,agent:n,detail:r,proof_hash:i})+`
|
|
108
|
+
`,{mode:384})}catch{}return e?Po(e,{action:"action_ack",actionDetail:`${t}:${r}`,agent:n,proofHash:i,tosVersion:ae}):!1}async function kf(e,t){let n=new Date().toISOString(),r=Is("sha256").update(`${ae}|mcp|${t}|${e?.org??""}|${n}`).digest("hex"),o={terms_version:ae,accepted_at:n,agent:t,org:e?.org??null,consent_hash:r,server_recorded:!1};return e&&(o.server_recorded=await Po(e,{action:"tos_accept",tosVersion:ae,context:"mcp",agent:t,proofHash:r})),Rs(o),o}async function Os(e){let t=Un();if(!t||t.terms_version!==ae||t.server_recorded)return;await Po(e,{action:"tos_accept",tosVersion:ae,context:"mcp-sync",agent:t.agent,proofHash:t.consent_hash})&&Rs({...t,org:e.org,server_recorded:!0})}function Ps(e){try{return Ns(Hn(zt(),e),"utf8").split(`
|
|
109
|
+
`).filter(Boolean).length}catch{return 0}}function xf(){return["What is recorded about this machine (all in ~/.nodata, operational only):",` \xB7 consent.json \u2014 ${Ds(Fn())?"your terms acceptance":"none yet"}`,` \xB7 acks.jsonl \u2014 ${Ps("acks.jsonl")} acknowledgement(s), e.g. installing the read gate`,` \xB7 gate.log \u2014 ${Ps("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(`
|
|
110
|
+
`)}var Ef=e=>[`NoData terms ${ae} \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(`
|
|
111
|
+
`);function Cs(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:_f.boolean().optional().describe("true = the user accepts these terms. Omit to show them.")}},async({confirm:o})=>{let i=Un();if(!o){let s=Vn()?`Already accepted by ${i.agent} on ${i.accepted_at}${i.server_recorded?" (recorded at NoData)":" (recorded locally; NoData copy pending)"}.`:i?`Accepted version ${i.terms_version} earlier \u2014 the terms have changed and need accepting again.`:"Not accepted yet.";return{content:[{type:"text",text:`${Ef(r)}
|
|
112
|
+
|
|
113
|
+
${s}
|
|
114
|
+
|
|
115
|
+
${xf()}
|
|
116
|
+
|
|
117
|
+
Ask the user whether they accept, then call nodata_terms again with confirm: true.`}]}}let a=await kf(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 Bs(e){let t=e,n=t.registerTool.bind(e);t.registerTool=(r,o,i)=>n(r,o,async(...a)=>{if(wf.has(r)||Vn())return i(...a);let s=Un();return{content:[{type:"text",text:(s?`NoData's terms changed (you accepted ${s.terms_version}; current is ${ae}).`:"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 Gn}from"zod";import $e from"node:crypto";var Io=Buffer.from([78,68,67,49]),Af=2,Do=36,Yt=32,Tf=64,Pf=12,If=16,Df=4096,$f=256,js=32,$o=8,Nf=1;async function Rf(){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 No(e){let t=new Uint8Array(e.length);return t.set(e),t.buffer}async function Of(e,t){let n=t.trim();if(n.includes("-----BEGIN PUBLIC KEY-----")){let o=n.replace(/-----BEGIN PUBLIC KEY-----/,"").replace(/-----END PUBLIC KEY-----/,"").replace(/\s+/g,"");return e.kem.deserializePublicKey(No(Buffer.from(o,"base64")))}let r=Buffer.from(n.replace(/-/g,"+").replace(/_/g,"/"),"base64");if(r.length!==32)throw new Error(`master pubkey must be a 32-byte X25519 key, got ${r.length} bytes`);return e.kem.deserializePublicKey(No(r))}function Cf(e){let t=$e.createPublicKey({key:e,format:"pem"}).export({format:"der",type:"spki"});if(t.length<Yt)throw new Error("unexpected Ed25519 SPKI DER length");return t.subarray(t.length-Yt)}function Bf(e){return $e.createHash("sha256").update(e,"utf8").digest().subarray(0,$o)}async function Ks(e){let t=Buffer.from(e.filename,"utf8");if(t.length>Df)throw new Error("filename too long");let n=Buffer.from(e.contentType,"utf8");if(n.length>$f)throw new Error("content-type too long");let r=e.receiptId??$e.randomUUID(),o=Buffer.from(r,"utf8");if(o.length!==Do)throw new Error("receiptId must be a 36-char canonical UUID");let i=Cf(e.issuerPubkeyPem);if(i.length!==Yt)throw new Error("issuer pubkey must be 32 bytes");let a=$e.randomBytes(32),s=$e.randomBytes(Pf),c=$e.createCipheriv("aes-256-gcm",a,s),l=Buffer.concat([c.update(e.fileBytes),c.final()]),u=c.getAuthTag();if(u.length!==If)throw new Error("unexpected GCM tag length");let p=$e.createHash("sha256").update(e.fileBytes).digest(),h=await Rf(),f=await Of(h,e.recipientPubkeyB64),y=await h.createSenderContext({recipientPublicKey:f}),S=Buffer.from(y.enc),w=Buffer.from(await y.seal(No(a))),b=Bf(e.recipientPubkeyB64),x=1+$o+2+S.length+2+w.length,g=Io.length+1+Do+Yt+2+t.length+2+n.length+8+js+x,_=Buffer.alloc(g),v=0;Io.copy(_,v),v+=Io.length,_[v++]=Af,o.copy(_,v),v+=Do,i.copy(_,v),v+=Yt,_.writeUInt16LE(t.length,v),v+=2,t.copy(_,v),v+=t.length,_.writeUInt16LE(n.length,v),v+=2,n.copy(_,v),v+=n.length,_.writeBigUInt64LE(BigInt(e.issuedAt??Date.now()),v),v+=8,p.copy(_,v),v+=js,_[v++]=Nf,b.copy(_,v),v+=$o,_.writeUInt16LE(S.length,v),v+=2,S.copy(_,v),v+=S.length,_.writeUInt16LE(w.length,v),v+=2,w.copy(_,v),v+=w.length;let k=$e.sign(null,_,e.issuerPrivateKey);if(k.length!==Tf)throw new Error("header signature must be 64 bytes");let T=Buffer.concat([_,k,s,u,l]),P={relative_path:"",plaintext_sha256:p.toString("hex"),size_bytes:e.fileBytes.length,lockbox_id:e.lockboxId??null,ndc_version:2,recovery_alg:1,recovery_master_fp:b.toString("hex"),header_sig_b64:k.toString("base64"),content_key_b64:a.toString("base64")};return{ndcBytes:T,report:P}}import{createPrivateKey as Ls,createPublicKey as Ms,generateKeyPairSync as jf}from"node:crypto";import{existsSync as Oo,mkdirSync as Kf,readFileSync as Us,rmSync as Lf,statSync as Wn,writeFileSync as Vs}from"node:fs";import{homedir as Fs}from"node:os";import{basename as Xt,extname as Mf,join as Co,resolve as Ff}from"node:path";var me=(e,t=!1)=>({content:[{type:"text",text:e}],...t?{isError:t}:{}}),Zt="mcp-archive",Ro=25,Hs=25*1024*1024,Hf={".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"},Uf={critical:"restricted",high:"confidential",medium:"internal",low:"internal",info:"internal"};function Gs(e,t){if(e){let o=Ls({key:Buffer.from(e,"base64"),format:"der",type:"pkcs8"});return{privateKey:o,publicPem:Ms(o).export({format:"pem",type:"spki"}),label:`device ${t??""}`.trim()}}let n=Co(Fs(),".nodata","issuer-ed25519.json");if(Oo(n)){let o=JSON.parse(Us(n,"utf8")).private_pem,i=Ls(o);return{privateKey:i,publicPem:Ms(i).export({format:"pem",type:"spki"}),label:"this machine"}}let r=jf("ed25519");return Kf(Co(Fs(),".nodata"),{recursive:!0}),Vs(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 Ws(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:Gn.string().describe("File or folder to wrap."),confirm:Gn.boolean().optional().describe("true = wrap it. Omit to preview."),keep_local:Gn.boolean().optional().describe("Also keep <file>.capsule.ndc next to the original. Default true."),remove:Gn.boolean().optional().describe("Delete plaintext originals after upload. Default false.")}},async({path:o,confirm:i,keep_local:a,remove:s})=>{let c=Ff(o);if(!Oo(c))return me(`Not found: ${c}`,!0);let l;if(Wn(c).isDirectory()?l=Ce(await gt({target_id:"mcp",target_label:Xt(c),target_path:c,log:_t})).byFile.map(v=>({path:Co(c,v.key),classification:Uf[v.worst]??"internal"})):l=[{path:c,classification:"confidential"}],l=l.filter(_=>Oo(_.path)&&Wn(_.path).isFile()&&!ve(_.path)),l.length===0)return me(`Nothing to wrap in ${c} \u2014 no file with findings.`);let u=l.filter(_=>Wn(_.path).size>Hs);l=l.filter(_=>Wn(_.path).size<=Hs);let p=await t.get("/api/v1/recovery/pubkey");if(p.status===401||p.status===403)return me(`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 me(`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(!i){let _=l.slice(0,Ro).map(v=>` \xB7 [${v.classification}] ${v.path}`);return l.length>Ro&&_.push(` \u2026 and ${l.length-Ro} more`),me([`PREVIEW \u2014 nothing wrapped yet. ${r()}`,`Would wrap ${l.length} file(s) into the "${Zt}" capsule, sealed to your org master key (fingerprint ${p.body.fingerprint??"?"}):`,..._,u.length?`Skipped (over 25 MB): ${u.map(v=>Xt(v.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 me(`Could not list capsules (HTTP ${f.status}): ${JSON.stringify(f.body)}`,!0);let S=(f.body.capsules??[]).find(_=>_.slug===Zt);if(S&&S.key_mode!=="zk")return me(`A "${Zt}" capsule exists but is not zero-knowledge (key_mode ${String(S.key_mode)}) \u2014 refusing to wrap into it.`,!0);if(!S){let _=await t.post("/api/v1/capsules",{handle:Zt,display_name:"MCP archive",key_mode:"zk",capsule_pubkey:h});if(_.status>=400)return me(`Could not create the archive capsule (HTTP ${_.status}): ${JSON.stringify(_.body)}`,!0);S=_.body}let w=String(S.slug??S.capsule_id??"");if(!w)return me(`Capsule id missing in ${JSON.stringify(S)}`,!0);let b=n(),x=[],g=[];for(let _ of l){let v=Us(_.path),{ndcBytes:k,report:T}=await Ks({fileBytes:v,filename:Xt(_.path),contentType:Hf[Mf(_.path).toLowerCase()]??"application/octet-stream",recipientPubkeyB64:h,issuerPrivateKey:b.privateKey,issuerPubkeyPem:b.publicPem}),P=await t.post(`/api/v1/capsules/${encodeURIComponent(w)}/documents`,{title:Xt(_.path),ndc_b64:k.toString("base64"),classification:_.classification,plaintext_sha256:T.plaintext_sha256,size_bytes:T.size_bytes});if(P.status>=400||P.body.ok!==!0){g.push(` \u2717 ${_.path} \u2014 HTTP ${P.status}: ${JSON.stringify(P.body).slice(0,200)}`);continue}a!==!1&&Vs(`${_.path}.capsule.ndc`,k,{mode:384}),s&&Lf(_.path),x.push(` \u2713 [${_.classification}] ${Xt(_.path)}${P.body.proof_url?` proof: ${P.body.proof_url}`:""}`)}return me([`WRAPPED ${x.length}/${l.length} into "${Zt}" \u2014 ${r()} \xB7 signed by ${b.label}`,...x,...g,"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
|
+
`),g.length>0&&x.length===0)})}import{homedir as ec,hostname as tc}from"node:os";import{join as qn,resolve as Bo}from"node:path";import{existsSync as Lo,readFileSync as nc,writeFileSync as rc,mkdirSync as oc,chmodSync as Wf}from"node:fs";import{spawn as qf}from"node:child_process";import{generateKeyPairSync as zf,createPrivateKey as Jf,sign as Yf,randomBytes as Xf}from"node:crypto";var Qt="1.3.8",ic=qn(ec(),".nodata"),zn=qn(ic,"credentials.json");function Zf(){try{if(!Lo(zn))return null;let e=JSON.parse(nc(zn,"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 qs(e){oc(ic,{recursive:!0});let t=JSON.stringify({...e,saved_at:new Date().toISOString()},null,2);rc(zn,t,{mode:384});try{Wf(zn,384)}catch{}}var Qf=`nodata-mcp v${Qt} \u2014 NoData MCP server
|
|
75
125
|
|
|
76
126
|
ADMIN mode: nodata-mcp --api-key sk_live_...
|
|
77
127
|
AGENT mode: nodata-mcp --grant-token ndca-...
|
|
78
128
|
Options: --base-url <url> (default https://www.nodatacapsule.com)
|
|
79
129
|
--help \xB7 --version
|
|
130
|
+
nodata-mcp install-gate [--block] ask (or refuse) before Claude Code reads a data file with findings
|
|
131
|
+
nodata-mcp uninstall-gate
|
|
132
|
+
nodata-mcp secrets-login [--project <label>] save a secrets CLI token (typed here, never in the chat) for nodata_run
|
|
133
|
+
nodata-mcp secrets-logout
|
|
80
134
|
|
|
81
135
|
Env vars: NODATA_API_KEY \xB7 NODATA_GRANT_TOKEN \xB7 NODATA_BASE_URL
|
|
82
136
|
Get a free API key: https://www.nodatacapsule.com/developers/get-started
|
|
83
|
-
Mint a grant token: POST /api/v1/governance/grant (or the nodata_grant tool).`;function
|
|
84
|
-
${t}`}],isError:!0}}function
|
|
85
|
-
`,{mode:384}),r}function
|
|
86
|
-
Ask the user to add them to that file themselves (not in this chat), then call this tool again.`}],isError:!0};let u=await
|
|
87
|
-
`)}]}}let
|
|
88
|
-
`)}]}}),e.registerTool("nodata_revoke",{description:"Revoke an agent's grant by handle (kills all its active credentials) or by a specific jti. Revocation is mathematics \u2014 the next read 401s and any cached data is governance-dead.",inputSchema:{handle:
|
|
137
|
+
Mint a grant token: POST /api/v1/governance/grant (or the nodata_grant tool).`;function jo(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(Qf),process.exit(0)):e[a]==="--version"||e[a]==="-v"?(console.log(Qt),process.exit(0)):e[a].startsWith("--")&&console.error(`nodata-mcp: unknown option '${e[a]}' (see --help)`);let o=t||n?"flag":"none";!t&&process.env.NODATA_API_KEY&&(t=process.env.NODATA_API_KEY,o="env"),!n&&process.env.NODATA_GRANT_TOKEN&&(n=process.env.NODATA_GRANT_TOKEN,o==="none"&&(o="env")),process.env.NODATA_BASE_URL&&(r=process.env.NODATA_BASE_URL);let i;if(!t&&!n){let a=Zf();a&&(!process.env.NODATA_BASE_URL&&r==="https://www.nodatacapsule.com"&&a.base_url&&(r=a.base_url),a.device?(i=a.device,o="stored"):a.api_key&&(t=a.api_key,o="stored"))}return r=r.replace(/\/+$/,""),{apiKey:t,grantToken:n,baseUrl:r,credentialSource:o,device:i}}var zs=3e4;async function ac(e,t){let n;try{n=await fetch(e,{...t,signal:AbortSignal.timeout(zs)})}catch(o){return{ok:!1,status:0,body:{error:o instanceof Error&&o.name==="TimeoutError"?`Request timed out after ${zs/1e3}s: ${e}`:`Network error reaching ${e}: ${o instanceof Error?o.message:String(o)}`}}}let r;try{r=await n.json()}catch{r={error:`Non-JSON response (HTTP ${n.status})`}}return{ok:n.ok,status:n.status,body:r}}async function en(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 Js(e){return async()=>{let t=await en(e);return"error"in t?null:t.token}}async function V(e,t,n,r){let o=await en(t);return"error"in o?o.error:ac(`${e}${n}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${o.token}`},body:JSON.stringify(r)})}async function Ko(e,t,n,r){let o=await en(t);if("error"in o)return o.error;let i=new URL(`${e}${n}`);for(let[a,s]of Object.entries(r))s!==void 0&&s!==""&&i.searchParams.set(a,s);return ac(i.toString(),{method:"GET",headers:{Authorization:`Bearer ${o.token}`}})}function U(e){let t=JSON.stringify(e.body,null,2);return e.ok?{content:[{type:"text",text:t}]}:{content:[{type:"text",text:`Error (HTTP ${e.status}):
|
|
138
|
+
${t}`}],isError:!0}}function eh(e){let t=e?[Bo(e)]:[Bo(".env.local"),Bo(".env")];if(e&&!Lo(t[0]))return{error:`env file not found: ${t[0]}`};let n={},r=[];for(let i of t)if(Lo(i)){r.push(i);for(let a of nc(i,"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 o=i=>{for(let a of i){let s=n[a]??process.env[a];if(s)return{name:a,value:s}}};return{url:o(["SUPABASE_URL","NEXT_PUBLIC_SUPABASE_URL","VITE_SUPABASE_URL","EXPO_PUBLIC_SUPABASE_URL"]),anon:o(["SUPABASE_ANON_KEY","NEXT_PUBLIC_SUPABASE_ANON_KEY","VITE_SUPABASE_ANON_KEY","EXPO_PUBLIC_SUPABASE_ANON_KEY","SUPABASE_PUBLISHABLE_KEY","NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY"]),jwt:o(["SUPABASE_JWT_SECRET","JWT_SECRET"]),files:r}}function th(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 nh=5*6e4;function rh(){let{publicKey:e,privateKey:t}=zf("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 oh(e,t){let n=Jf({key:Buffer.from(e,"base64"),format:"der",type:"pkcs8"});return Yf(null,Buffer.from(t,"utf8"),n).toString("base64")}function ih(){let e=tc().toLowerCase().replace(/[^a-z0-9-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,20)||"device";return`${/^[a-z]/.test(e)?e:`d-${e}`}-${Xf(3).toString("hex")}`.slice(0,32)}async function ah(e,t,n,r,o){let i=await V(e,t,"/api/v1/attest/devices",{handle:n,label:r,ed25519_pubkey_hex:o});if(i.ok){let a=i.body.org_id??"";return a?{ok:!0,orgId:a}:{ok:!1,status:i.status,error:"enroll response missing org_id"}}return{ok:!1,status:i.status,error:i.body?.error??`HTTP ${i.status}`}}async function sh(e,t){let n=await V(e,"","/api/v1/attest/challenge",{org_id:t.org_id,handle:t.handle});if(!n.ok)throw new Error(`challenge: ${n.body?.error??`HTTP ${n.status}`}`);let{challenge:r,nonce:o}=n.body;if(!r||!o)throw new Error("challenge response malformed");let i=oh(t.private_key_pkcs8_b64,r),a=await V(e,"","/api/v1/attest",{org_id:t.org_id,handle:t.handle,nonce:o,signature:i});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 Ys(e,t){let n=null;return async()=>((!n||Date.now()>=n.expiresAtMs-nh)&&(n=await sh(e,t)),n.token)}function ch(e,t){let n=qn(ec(),".nodata","approvals");oc(n,{recursive:!0});let r=qn(n,`${new Date().toISOString().replace(/[:.]/g,"-").slice(0,19)}-${e}.json`);return rc(r,JSON.stringify({kind:e,approved_at:new Date().toISOString(),...t},null,2)+`
|
|
139
|
+
`,{mode:384}),r}function lh(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:m.string().describe("Your SQL table name"),encrypted_columns:m.array(m.string()).describe("Columns stored as <col>_ct/_iv/_tag triplets"),plaintext_columns:m.array(m.string()).optional().describe("Plaintext metadata/filter columns"),classification_column:m.string().optional().describe("Plaintext column carrying the classification value")}},async({table_name:o,encrypted_columns:i,plaintext_columns:a,classification_column:s})=>{let c=await V(t,n,"/api/v1/governance/tables",{table_name:o,encrypted_columns:i,plaintext_columns:a??[],classification_column:s});return U(c)}),e.registerTool("nodata_connect_source",{description:"Connect the user's own Supabase project as the data source for their registered tables, so granted agents can read metadata through NoData. Reads the project URL, anon key and JWT secret from the user's LOCAL env file (e.g. .env.local) and sends them directly to NoData \u2014 never ask the user to paste a key or secret into the chat, and never print them. Only allowed_tables are readable (deny-by-default).",inputSchema:{allowed_tables:m.array(m.string()).describe("Tables agents may read through this source"),env_file:m.string().optional().describe("Path to the env file holding the Supabase keys (default: .env.local, then .env in the working directory)"),source_url:m.string().optional().describe("Override the project URL (https://<ref>.supabase.co) if the env file lacks it")}},async({allowed_tables:o,env_file:i,source_url:a})=>{let s=eh(i);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("; ")}.
|
|
140
|
+
Ask the user to add them to that file themselves (not in this chat), then call this tool again.`}],isError:!0};let u=await V(t,n,"/api/connector/secrets",{source_url:c,allowed_tables:o,anon_key:s.anon.value,jwt_secret:s.jwt.value}),p={read_from:s.files,variables_used:[s.url?.name,s.anon.name,s.jwt.name].filter(Boolean)};return U({...u,body:{...u.body,...p}})}),e.registerTool("nodata_grant",{description:"Issue ONE AI agent a claim-scoped grant over your data \u2014 claims, not blanket access. Returns a grant_token (shown once) the agent presents to read. Denied columns never decrypt. For one agent over several tables pass `tables` in a single call \u2014 do NOT call this once per table, that creates a separate agent each time. ASKS FIRST: without confirm:true it returns the exact policy change and grants nothing \u2014 show it to the user and call again with confirm:true only after they approve. On confirm, a copy of the approval (who, what, when, the receipt and its proof_url \u2014 never the token) is kept in ~/.nodata/approvals.",inputSchema:{agent:m.string().describe("Agent label (becomes its handle)"),tables:m.array(m.object({table:m.string(),columns:m.array(m.string()).describe("Columns the agent may read in this table"),where:m.record(m.string(),m.union([m.string(),m.number(),m.boolean()])).optional()})).optional().describe("Several tables for the same agent. When set, table/columns/where are ignored."),table:m.string().optional().describe("Single target table (default agent_demo_records)"),columns:m.array(m.string()).optional().describe("Columns the agent may read (single-table form)"),where:m.record(m.string(),m.union([m.string(),m.number(),m.boolean()])).optional().describe("Equality filter (plaintext cols only)"),classifications:m.array(m.string()).optional().describe("Allowed classification values; empty = no gating"),ttl_seconds:m.number().optional().describe("Token lifetime (default 30d, max 1y)"),confirm:m.boolean().optional().describe("true = grant it. Omit to preview the policy change.")}},async({agent:o,tables:i,table:a,columns:s,where:c,classifications:l,ttl_seconds:u,confirm:p})=>{let h={agent:o,...i?{tables:i}:{table:a??"agent_demo_records",columns:s,where:c},classifications:l,ttl_seconds:u};if(!p){let S=(i??[{table:a??"agent_demo_records",columns:s??[],where:c}]).map(b=>` \xB7 ${b.table}: ${(b.columns??[]).join(", ")||"(no columns)"}${b.where?` where ${JSON.stringify(b.where)}`:""}`),w=u?`${Math.round(u/86400*10)/10} days`:"30 days (default)";return{content:[{type:"text",text:[`POLICY CHANGE \u2014 PREVIEW, nothing granted yet. Requested by ${r()}`,`Agent "${o}" would be able to read ONLY:`,...S,`Classifications: ${l?.length?l.join(", "):"not gated"}`,`Valid for: ${w}. 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(`
|
|
141
|
+
`)}]}}let f=await V(t,n,"/api/v1/governance/grant",h);if(f.ok){let y=f.body,S=ch("grant",{approved_by:r(),request:h,result:{handle:y.handle,agent_id:y.agent_id,expires_at:y.expires_at,grant_receipt_id:y.grant_receipt_id,proof_url:y.proof_url}});f.body.approval_copy=S}return U(f)}),e.registerTool("nodata_policy",{description:"The POLICY BOARD: every AI agent in the organization and exactly what it can reach \u2014 tables, columns, classifications \u2014 plus status. Deny-by-default: an agent with no grant reaches nothing. Change it with nodata_grant (asks for approval first) and nodata_revoke (immediate). Content-free: names only, never a value.",inputSchema:{}},async()=>{let o=await Ko(t,n,"/api/v1/agents",{});if(!o.ok)return U(o);let a=o.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,u=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)} ${u}`)}return s.push("",'Change: nodata_grant (preview \u2192 approve) \xB7 nodata_revoke handle: "<agent>" (immediate) \xB7 proofs: nodata_proofs'),{content:[{type:"text",text:s.join(`
|
|
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:m.string().optional().describe("Agent handle to revoke"),jti:m.string().optional().describe("Specific credential jti to revoke"),reason:m.string().optional()}},async({handle:o,jti:i,reason:a})=>{let s=await V(t,n,"/api/v1/governance/revoke",{handle:o,jti:i,reason:a});return U(s)}),e.registerTool("nodata_encrypt",{description:"Encrypt a sensitive field value using Capsule Blind Relay. Returns ciphertext. NoData stores nothing \u2014 the key is embedded in the ciphertext for YOU to store.",inputSchema:{field:m.string(),value:m.string(),context:m.string().optional()}},async({field:o,value:i,context:a})=>{let s={field:o,value:i};return a&&(s.context=a),U(await V(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:m.string(),field:m.string().optional(),requester:m.string().optional()}},async({ciphertext:o,field:i,requester:a})=>{let s={ciphertext:o};return i&&(s.field=i),a&&(s.requester=a),U(await V(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:m.string(),to:m.string().optional(),maxViews:m.number().optional(),ttl:m.string().optional(),burn:m.boolean().optional()}},async({content:o,to:i,maxViews:a,ttl:s,burn:c})=>{let l={content:o};return i&&(l.to=i),a!==void 0&&(l.maxViews=a),s&&(l.ttl=s),c!==void 0&&(l.burn=c),U(await V(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:m.string().optional(),to:m.string().optional(),action:m.string().optional(),limit:m.number().optional()}},async({from:o,to:i,action:a,limit:s})=>{let c={from:o,to:i,action:a,limit:s!==void 0?String(s):void 0};return U(await Ko(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:m.string().optional().describe("Fetch one proof by id"),surface:m.string().optional().describe("Filter, e.g. 'governance.grant', 'agent.read'"),decision:m.string().optional().describe("Filter: 'grant' | 'allow' | 'deny' | 'revoke'"),from:m.string().optional().describe("ISO timestamp"),to:m.string().optional().describe("ISO timestamp"),limit:m.number().optional().describe("1..1000, default 50")}},async({receipt_id:o,surface:i,decision:a,from:s,to:c,limit:l})=>U(await Ko(t,n,"/api/v1/proofs",{receipt_id:o,surface:i,decision:a,from:s,to:c,limit:l!==void 0?String(l):void 0})))}function dh(e,t,n){let r=th(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:m.string().describe("Table to check (must be in your grant)"),columns:m.array(m.string()).describe("Columns you want to reach"),where:m.record(m.string(),m.union([m.string(),m.number(),m.boolean()])).optional().describe("Equality filter (readable columns only)")}},async({table:o,columns:i,where:a})=>{let s=await V(t,n,"/api/access/decide",{resource:{table:o,columns:i,where:a},intent:"read"});return U(s)}),e.registerTool("nodata_retrieve",{description:"Retrieve prompt-ready context for a resource, filtered to exactly what this agent may see. Denied columns are never decrypted; the response includes an accounting of what was withheld (columns + estimated tokens saved) and a signed proof. Prefer this over a raw read when assembling an LLM prompt. Hard-scoped to this server's grant token.",inputSchema:{table:m.string().describe("Table to retrieve from (must be in your grant)"),columns:m.array(m.string()).describe("Columns to include in context"),where:m.record(m.string(),m.union([m.string(),m.number(),m.boolean()])).optional(),top_k:m.number().optional().describe("Max rows (default 50, max 200)")}},async({table:o,columns:i,where:a,top_k:s})=>{let c=await V(t,n,"/api/access/retrieve",{resource:{table:o,columns:i,where:a},top_k:s});return U(c)}),e.registerTool("nodata_read",{description:"Read governed data within this agent's grant. You may only request columns your grant allows \u2014 denied columns never decrypt server-side, and every read emits a cryptographic receipt. This tool is hard-scoped to the grant token this server was started with.",inputSchema:{table:m.string().describe("Table to read (must be in your grant)"),columns:m.array(m.string()).describe("Columns to read (must be in your grant)"),where:m.record(m.string(),m.union([m.string(),m.number(),m.boolean()])).optional(),limit:m.number().optional().describe("Max rows (default 50, max 200)")}},async({table:o,columns:i,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 V(t,n,`/api/agents/${encodeURIComponent(r)}/read`,{table:o,columns:i,where:a,limit:s});return U(c)}),e.registerTool("nodata_use",{description:"Invoke a pre-registered capability (deploy, send, charge, query, \u2026) WITHOUT receiving the secret. The Capsule injects the sealed credential server-side and returns only the result. You may invoke only capabilities your grant allows; the secret never reaches you. Hard-scoped to the grant token this server was started with.",inputSchema:{capability:m.string().describe("Capability name to invoke (must be in your grant, e.g. 'deploy-prod')"),params:m.record(m.string(),m.unknown()).optional().describe("Allowlisted params; unknown keys are dropped server-side"),resource_key:m.string().optional().describe("Optional folder/resource the action targets (enforced against corpus scope)")}},async({capability:o,params:i,resource_key:a})=>{if(!r)return{content:[{type:"text",text:"Error: could not derive agent handle from grant token."}],isError:!0};let s=await V(t,n,`/api/agents/${encodeURIComponent(r)}/use`,{capability:o,params:i,resource_key:a});return U(s)}),e.registerTool("nodata_code_advise",{description:"Ask the blind code advisor to diagnose/fix a bug in a code capsule WITHOUT seeing its source. You receive guidance + a targeted diff + an exposure proof (source never left the boundary); the source is never returned to you. Requires the capsule owner to have granted this agent (scope.fabric_developers). Hard-scoped to this server's grant token.",inputSchema:{capsule_id:m.string().describe("The code capsule to advise on (you must be granted on it)"),question:m.string().optional().describe("What to fix / improve, in natural language"),note:m.string().optional().describe("Extra context for the advisor"),error:m.object({message:m.string().optional(),stack:m.string().optional(),kind:m.string().optional()}).optional().describe("An error the code produced, to guide the fix"),steer:m.string().optional().describe("A steer on a refine turn (e.g. 'no, round half-up')"),prior_diff:m.string().optional().describe("The previously proposed diff, to refine")}},async({capsule_id:o,question:i,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 u=await V(t,n,`/api/agents/${encodeURIComponent(r)}/code-capsule/${encodeURIComponent(o)}/advise`,{question:i,note:a,error:s,steer:c,prior_diff:l});return U(u)}),e.registerTool("nodata_code_patch",{description:"Submit a fix to a code capsule as a SIGNED, queued patch WITHOUT seeing its source. Provide a raw unified `diff`, or a whole-file `replace` ({path, content}) that is diffed server-side against the sealed source. The source is never persisted or returned; you get back a patch id, the diff hash, and a receipt. Requires a capsule grant (scope.fabric_developers). Hard-scoped to this server's grant token.",inputSchema:{capsule_id:m.string().describe("The code capsule to patch (you must be granted on it)"),summary:m.string().optional().describe("Short human-readable summary of the fix"),diff:m.string().optional().describe("A raw unified diff (advanced)"),replace:m.object({path:m.string(),content:m.string()}).optional().describe("Whole-file replacement; the diff is synthesized server-side against sealed source")}},async({capsule_id:o,summary:i,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 V(t,n,`/api/agents/${encodeURIComponent(r)}/code-capsule/${encodeURIComponent(o)}/patch`,{summary:i,diff:a,replace:s});return U(c)})}var Xs=`WHAT NODATA DOES \u2014 in one line:
|
|
89
143
|
Give any agent real power over your data, without the power to leak it.
|
|
90
144
|
(Possession is not permission: it can hold the key and still not read what you didn't allow.)
|
|
91
|
-
`,
|
|
145
|
+
`,uh=`TURN THE DATA TOOLS ON \u2014 3 steps, about a minute, once:
|
|
92
146
|
|
|
93
147
|
1. GET A KEY call nodata_connect (no arguments)
|
|
94
148
|
-> opens the signup in your browser: email + company (~30s), a 12-word
|
|
@@ -101,7 +155,7 @@ Ask the user to add them to that file themselves (not in this chat), then call t
|
|
|
101
155
|
3. ACTIVATE type /mcp (or restart Claude Code) so the tools load.
|
|
102
156
|
|
|
103
157
|
COMING BACK LATER? Nothing to redo \u2014 it starts ready. If the tools look missing, just /mcp.
|
|
104
|
-
`,
|
|
158
|
+
`,ph=`YOUR WORKSPACE \u2014 say it in plain words; anything that changes files or policy asks you first:
|
|
105
159
|
|
|
106
160
|
1. SEE "scan <folder>" -> nodata_scan_folder: the whole result + a full HTML report,
|
|
107
161
|
on this machine, nothing uploads.
|
|
@@ -117,28 +171,30 @@ COMING BACK LATER? Nothing to redo \u2014 it starts ready. If the tools look mis
|
|
|
117
171
|
|
|
118
172
|
Database tables: nodata_register_table + nodata_connect_source, then nodata_grant.
|
|
119
173
|
One secret value: nodata_encrypt, hand it over once: nodata_deliver.
|
|
120
|
-
`,
|
|
174
|
+
`,fh=`WHAT YOU CAN DO \u2014 scoped to your grant; you reach only what it allows, the rest never decrypts:
|
|
121
175
|
|
|
122
176
|
1. PLAN nodata_decide "may I reach X?" -> allow / partial / deny + a signed proof. No data moves.
|
|
123
177
|
2. PULL nodata_retrieve prompt-ready context, allowed fields only, with a receipt.
|
|
124
178
|
(nodata_read for raw governed rows.)
|
|
125
179
|
3. ACT nodata_use run a capability with a secret injected server-side \u2014 you never see it.
|
|
126
|
-
`,
|
|
180
|
+
`,Zs=`STUCK? There's always a next step:
|
|
127
181
|
- Don't see the nodata_* tools? They load when the client starts \u2014 type /mcp or restart.
|
|
128
182
|
(Expected, not an error.)
|
|
129
183
|
- No MCP at all? The same governance runs from one curl, or the guided page:
|
|
130
184
|
https://www.nodatacapsule.com/developers/get-started
|
|
131
|
-
`;function
|
|
185
|
+
`;function Qs(e){return e==="setup"?`You're connected to NoData \u2014 but there's NO key yet, so the data tools are still off.
|
|
132
186
|
|
|
133
187
|
`:e==="agent"?`You're connected to NoData, scoped to one grant token.
|
|
134
188
|
|
|
135
189
|
`:`You're connected to NoData (admin mode). You don't memorize commands \u2014 just ask in plain words.
|
|
136
190
|
|
|
137
|
-
`}function
|
|
138
|
-
|
|
139
|
-
|
|
191
|
+
`}function hh(e){return(e!=="agent"&&!Vn()?`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
|
+
|
|
193
|
+
`:"")+mh(e)}function mh(e){if(e==="setup")return Qs(e)+Xs+`
|
|
194
|
+
`+uh+`
|
|
195
|
+
`+Zs;let t=e==="agent"?fh:ph;return Qs(e)+Xs+`
|
|
140
196
|
`+t+`
|
|
141
|
-
`+
|
|
197
|
+
`+Zs}function yh(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:hh(t)}]}))}var gh="/capsule-api/register";function _h(e){let t=process.platform==="win32",n=process.platform==="darwin"?"open":t?"cmd":"xdg-open",r=t?["/c","start","",e]:[e];try{let o=qf(n,r,{stdio:"ignore",detached:!0});return o.on("error",()=>{}),o.unref(),!0}catch{return!1}}function bh(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:m.string().optional().describe("The org key shown once at signup (ndp_\u2026 or sk_\u2026). Omit on the first call to open signup.")}},async({api_key:n})=>{let r=(n??"").trim();if(!r){let u=t+gh;return{content:[{type:"text",text:(_h(u)?`STEP 1 of 3 \u2014 opened the NoData signup in your browser:
|
|
142
198
|
`:`STEP 1 of 3 \u2014 open the NoData signup in your browser:
|
|
143
199
|
`)+u+`
|
|
144
200
|
|
|
@@ -150,13 +206,16 @@ There, about a minute:
|
|
|
150
206
|
STEP 2 \u2014 come back and call this tool again with the key:
|
|
151
207
|
nodata_connect api_key: "<the key you copied>"
|
|
152
208
|
and I'll save it so you never paste it again. (Then STEP 3: type /mcp to activate.)`}]}}if(!/^(ndp_|sk_)/.test(r))return{content:[{type:"text",text:`That doesn't look like a NoData org key (it should start with ndp_ or sk_).
|
|
153
|
-
Copy the key shown once on the signup page and try again: nodata_connect api_key: "ndp_\u2026".`}]};let{publicKeyHex:o,privateKeyPkcs8B64:
|
|
209
|
+
Copy the key shown once on the signup page and try again: nodata_connect api_key: "ndp_\u2026".`}]};let{publicKeyHex:o,privateKeyPkcs8B64:i}=rh(),a=ih(),s=tc()||"this device",c=await ah(t,r,a,s,o);if(c.ok){try{qs({device:{org_id:c.orgId,handle:a,label:s,private_key_pkcs8_b64:i,public_key_hex:o},base_url:t})}catch(u){return{content:[{type:"text",text:"Enrolled the device, but couldn't save it locally: "+(u instanceof Error?u.message:String(u))}]}}return{content:[{type:"text",text:`STEP 2 done \u2014 this device is enrolled as "${s}" (${a}), and only its PRIVATE key is
|
|
154
210
|
saved at ~/.nodata/credentials.json (readable only by you). The org key you pasted was NOT
|
|
155
211
|
stored: every start now proves possession by signing a fresh challenge and gets a 15-minute token.
|
|
156
212
|
|
|
157
|
-
STEP 3 \u2014 type /mcp (or restart Claude Code) and the admin tools appear. Next time: nothing to do.`}]}}let
|
|
158
|
-
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:(
|
|
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{qs({api_key:r,key_prefix:r.slice(0,12),base_url:t})}catch(u){return{content:[{type:"text",text:"Couldn't save locally: "+(u instanceof Error?u.message:String(u))+`
|
|
214
|
+
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
|
|
159
215
|
server yet, so this is the key-at-rest path). `:`STEP 2 done \u2014 saved your key on this machine (device enrollment didn't succeed: ${c.error}). `)+`Every future start loads it automatically \u2014 no re-register, no re-paste.
|
|
160
216
|
|
|
161
|
-
STEP 3 \u2014 type /mcp (or restart Claude Code) and the admin tools appear. Next time: nothing to do.`}]}})}async function
|
|
162
|
-
|
|
217
|
+
STEP 3 \u2014 type /mcp (or restart Claude Code) and the admin tools appear. Next time: nothing to do.`}]}})}async function vh(){fs();let e=process.argv[2];if(e==="gate")return os(process.argv.slice(3));if(e==="install-gate"||e==="uninstall-gate"){let f=jo([]),y=f.device?Ys(f.baseUrl,f.device):f.apiKey||null,S=y?{baseUrl:f.baseUrl,org:f.device?.org_id??null,token:Js(y)}:null,w=process.argv.includes("--block"),b=e==="install-gate"?cs(new URL("./gate.js",import.meta.url),w):ls(),x=await Jt(S,e==="install-gate"?"read-gate-install":"read-gate-uninstall",To("cli",f.device?.label),w?"block":"ask");process.stdout.write(b+(x?`
|
|
218
|
+
Recorded at NoData for your organisation (operational only).`:"")+`
|
|
219
|
+
`);return}if(e==="secrets-login"||e==="secrets-logout"){let f=e==="secrets-login"?await ks(process.argv.slice(3),jo([]).baseUrl):xs();process.stdout.write(f+`
|
|
220
|
+
`);return}let{apiKey:t,grantToken:n,baseUrl:r,credentialSource:o,device:i}=jo(process.argv.slice(2)),a=n?"agent":t||i?"admin":"setup",s=new Vf({name:a==="agent"?"NoData (agent-scoped)":a==="setup"?"NoData (setup)":"NoData",version:Qt}),c=()=>To(s.server.getClientVersion()?.name,i?.label),l=()=>`${Ts(c())} \xB7 `+(i?`device "${i.label}" (${i.handle}) \xB7 org ${i.org_id}`:t?`org key ${t.slice(0,12)}\u2026`:"not connected \u2014 local only"),u=i?Ys(r,i):t||null,p=u?{baseUrl:r,org:i?.org_id??null,token:Js(u)}:null;if(a!=="agent"&&(Cs(s,p,c,`${r}/terms`),Bs(s),p&&Os(p)),a!=="agent"&&vs(s,{version:Qt,agent:c,who:l,org:i&&p?{id:i.org_id,baseUrl:r,token:p.token}:null,ack:f=>Jt(p,"capsule-node-register",c(),f)}),Eo({version:Qt,agent:c}),u){lh(s,r,u,l),Ya(s,r,async()=>{let y=await en(u);if("error"in y)throw new Error("no usable org credential \u2014 run nodata_connect");return y.token},l);let f=async(y,S,w)=>{let b=await en(u);if("error"in b)return{status:401,body:{error:"no usable org credential \u2014 run nodata_connect"}};let x=await fetch(`${r}${S}`,{method:y,headers:{authorization:`Bearer ${b.token}`,...w?{"content-type":"application/json"}:{}},...w?{body:JSON.stringify(w)}:{}});return{status:x.status,body:await x.json().catch(()=>({}))}};Ws(s,{get:y=>f("GET",y),post:(y,S)=>f("POST",y,S)},()=>Gs(i?.private_key_pkcs8_b64,i?.label),l)}n&&dh(s,r,n),yh(s,a),a!=="agent"&&$i(s,l,f=>Jt(p,"policy-apply",c(),f)),a!=="agent"&&Es(s,{who:l,ack:f=>Jt(p,"secrets-run",c(),f)}),a==="setup"?(bh(s,r),console.error(`nodata-mcp: no credential given \u2014 running in setup mode (data tools disabled).
|
|
221
|
+
Call nodata_connect (opens signup, enrolls this device), or pass --api-key / --grant-token. See --help.`)):i?console.error(`nodata-mcp: loaded device identity "${i.label}" (${i.handle}) \u2014 attest mode; tokens are minted per session.`):o==="stored"&&console.error("nodata-mcp: loaded saved credential from ~/.nodata/credentials.json (admin mode).");let h=new Gf;await s.connect(h)}vh().catch(e=>{console.error("Fatal error:",e),process.exit(1)});
|