@nodatachat/mcp 1.0.0 → 1.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE.md +105 -105
- package/README.md +187 -161
- package/dist/index.js +108 -54
- package/package.json +57 -49
package/dist/index.js
CHANGED
|
@@ -1,24 +1,77 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
/*! @nodatachat/mcp 1.
|
|
3
|
-
import{McpServer as gt}from"@modelcontextprotocol/sdk/server/mcp.js";import{StdioServerTransport as mt}from"@modelcontextprotocol/sdk/server/stdio.js";import{z as c}from"zod";import{readdirSync as _e,readFileSync as ve,statSync as J}from"node:fs";import{join as ct}from"node:path";var ie=[{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"}],ae=/node_modules\/|\.next\/|\.test\.|\.spec\.|__tests__\/|\.env\.example$|\.nodata-proof\.json$|\.git\//,Oe=[{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 De(e,t){let n=o=>o.replace(/^[^0-9]*/,"").split(".").map(a=>parseInt(a,10)||0),i=n(e),r=n(t);for(let o=0;o<3;o++){if((i[o]||0)<(r[o]||0))return!0;if((i[o]||0)>(r[o]||0))return!1}return!1}function oe(e){let t=[],n;try{n=JSON.parse(e)}catch{return t}let i={...n.dependencies??{},...n.devDependencies??{}};for(let[r,o]of Object.entries(i)){let a=(o||"").replace(/^[\^~>=<\s]+/,""),s=Oe.find(l=>l.name===r&&De(a,l.below));s&&t.push({name:r,version:a,vuln:s})}return t}var Le=[{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"}],Fe=[{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"}],je=/^(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 W(e){if(!e)return null;let t=e.trim();if(je.test(t)||/^name$/i.test(t))return null;for(let n of[...Fe,...Le])if(n.pattern.test(t))return{type:n.type,label:n.label};return null}var G={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 B(e){let t=String(e??"").replace(/\D/g,"");if(t.length===0||t.length>9)return!1;let n=t.padStart(9,"0"),i=0;for(let r=0;r<9;r++){let o=parseInt(n[r]??"0",10)*(r%2+1);o>9&&(o-=9),i+=o}return i%10===0&&parseInt(n,10)>0}var F=/(?:\+972[\s-]?|0)(?:5[0-9]|[2-4]|[89])(?:[\s-]?\d){7}/g;var j=/\bIL\d{2}\s?(?:\d{4}\s?){4}\d{3}\b/g;function Me(e){let t=String(e??"").replace(/\D/g,"");if(t.length<12||t.length>19)return!1;let n=0,i=!1;for(let r=t.length-1;r>=0;r-=1){let o=parseInt(t[r]??"0",10);i&&(o*=2,o>9&&(o-=9)),n+=o,i=!i}return n%10===0}function Be(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),i=0;for(let r of n){let o=r>="A"&&r<="Z"?String(r.charCodeAt(0)-55):r;for(let a of o)i=(i*10+Number(a))%97}return i===1}var H="(?<![\\d.,])",V="(?![\\d.,])",Ue=[{subkind:"israeli_id",severity:"high",pattern:new RegExp(`${H}\\d{9}${V}`,"g"),validate:B,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(`${H}(?:\\d[ -]?){12,18}\\d${V}`,"g"),validate:Me,hint:"Payment card number (Luhn verified) in plaintext. This is PCI scope."},{subkind:"iban",severity:"high",pattern:/\b[A-Z]{2}\d{2}[A-Z0-9]{10,30}\b/g,validate:Be,hint:"Bank account in IBAN form (mod-97 verified) in plaintext."},{subkind:"israeli_phone",severity:"medium",pattern:new RegExp(`${H}(?:\\+972[- ]?|0)(?:5\\d|[2-489])[- ]?\\d{3}[- ]?\\d{4}${V}`,"g"),validate:e=>{let t=e.replace(/\D/g,"").replace(/^972/,"0");return t.length===10&&t.startsWith("0")},hint:"Israeli phone number in plaintext."}];function se(e){let t=[];for(let n of Ue){n.pattern.lastIndex=0;let i=new Set,r,o=0;for(;(r=n.pattern.exec(e))!==null&&(o+=1,!(o>2e5));){let a=r[0];if(n.validate(a)&&i.add(a.replace(/[\s-]/g,"")),i.size>=1e5)break}i.size>0&&t.push({subkind:n.subkind,severity:n.severity,hint:n.hint,count:i.size})}return t}function Z(e,t){let n=[],i="",r=!1;for(let o=0;o<e.length;o++){let a=e[o];r?a==='"'&&e[o+1]==='"'?(i+='"',o++):a==='"'?r=!1:i+=a:a==='"'?r=!0:a===t?(n.push(i),i=""):i+=a}return n.push(i),n}import{inflateRawSync as Je}from"node:zlib";import{inflateSync as ze}from"node:zlib";var Y=new Set([".pdf"]),ce=8*1024*1024;function Ke(e){let t=e.toString("latin1"),n=new Map,i=/(\d+)\s+(\d+)\s+obj\b/g,r;for(;(r=i.exec(t))!==null;){let o=Number(r[1]),a=i.lastIndex,s=t.indexOf("endobj",a);if(s<0)continue;let l=t.indexOf("stream",a),d,p=null;if(l>=0&&l<s){d=t.slice(a,l);let f=l+6;t[f]==="\r"&&(f+=1),t[f]===`
|
|
4
|
-
|
|
5
|
-
`,
|
|
6
|
-
|
|
7
|
-
`)}function fe(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=Ke(e);if(n.size===0)return null;let i=Ze(n),r=[];r.push(Xe(e,n));let o=0,a=0,s=!1;for(let l of n.values()){if(!l.stream||/\/Subtype|\/Type\s*\/(XObject|Font|Metadata)|\/FontFile/.test(l.dict))continue;let d=de(l);if(d===null||!/(TJ|Tj)\b/.test(d))continue;let p=Ye(d,i);if(p.trim().length!==0){if(a+=1,o+p.length>ce){r.push(p.slice(0,Math.max(0,ce-o))),s=!0;break}r.push(p),o+=p.length}}return a===0?null:{text:r.join(`
|
|
8
|
-
`),truncated:s,streams:a}}var he=new Set([".xlsx",".xlsm",".docx",".pptx"]),X=8*1024*1024,qe=101010256,Qe=33639248,et=67324752;function tt(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)===qe){n=a;break}if(n<0)return null;let i=e.readUInt16LE(n+10),r=e.readUInt32LE(n+16);if(r>=e.length)return null;let o=[];for(let a=0;a<i&&!(r+46>e.length||e.readUInt32LE(r)!==Qe);a+=1){let s=e.readUInt16LE(r+10),l=e.readUInt32LE(r+20),d=e.readUInt32LE(r+24),p=e.readUInt16LE(r+28),f=e.readUInt16LE(r+30),S=e.readUInt16LE(r+32),P=e.readUInt32LE(r+42),R=e.subarray(r+46,r+46+p).toString("utf8");o.push({name:R,method:s,compSize:l,uncompSize:d,localHeaderOffset:P}),r+=46+p+f+S}return o}function nt(e,t){let n=t.localHeaderOffset;if(n+30>e.length||e.readUInt32LE(n)!==et)return null;let i=e.readUInt16LE(n+26),r=e.readUInt16LE(n+28),o=n+30+i+r,a=o+t.compSize;if(a>e.length)return null;let s=e.subarray(o,a);try{if(t.method===0)return s.toString("utf8");if(t.method===8)return Je(s).toString("utf8")}catch{return null}return null}var rt={"&":"&","<":"<",">":">",""":'"',"'":"'"};function ge(e){return e.replace(/&(amp|lt|gt|quot|apos);/g,t=>rt[t]??t).replace(/&#(\d+);/g,(t,n)=>{let i=Number(n);return i>0&&i<1114112?String.fromCodePoint(i):""}).replace(/&#x([0-9a-fA-F]+);/g,(t,n)=>{let i=parseInt(n,16);return i>0&&i<1114112?String.fromCodePoint(i):""})}function it(e){return ge(e.replace(/<[^>]*>/g,`
|
|
2
|
+
/*! @nodatachat/mcp 1.3.0 | Copyright 2026 Capsule Ltd. | FSL-1.1-ALv2 | see LICENSE.md */
|
|
3
|
+
import{createRequire as __ndReq}from"node:module";const require=__ndReq(import.meta.url);
|
|
4
|
+
var za=Object.create;var Er=Object.defineProperty;var Ya=Object.getOwnPropertyDescriptor;var Xa=Object.getOwnPropertyNames;var Za=Object.getPrototypeOf,Qa=Object.prototype.hasOwnProperty;var A=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,n)=>(typeof require<"u"?require:t)[n]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var O=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var ei=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Xa(t))!Qa.call(e,o)&&o!==n&&Er(e,o,{get:()=>t[o],enumerable:!(r=Ya(t,o))||r.enumerable});return e};var kr=(e,t,n)=>(n=e!=null?za(Za(e)):{},ei(t||!e||!e.__esModule?Er(n,"default",{value:e,enumerable:!0}):n,e));var kn=O(Y=>{"use strict";Object.defineProperty(Y,"__esModule",{value:!0});Y.MAX_SEALED_BYTES=void 0;Y.kidForPublicKey=Gr;Y.deriveKeyPairFromSeed=Ui;Y.generateSeed=Hi;Y.buildEnvInfo=Vi;Y.sealDek=Gi;Y.openSealedDek=qi;Y.decodeSealHeader=qr;var Ur=A("crypto"),Lr=A("@hpke/core"),Ki=A("@hpke/dhkem-x25519"),ji=A("@hpke/chacha20poly1305"),Mi=A("@noble/curves/ed25519.js"),Fi=A("@noble/hashes/hkdf.js"),Li=A("@noble/hashes/sha2.js"),Dt=new Lr.CipherSuite({kem:new Ki.DhkemX25519HkdfSha256,kdf:new Lr.HkdfSha256,aead:new ji.Chacha20Poly1305}),Hr=1,Vr=1;Y.MAX_SEALED_BYTES=4096;function Gr(e){return(0,Ur.createHash)("sha256").update(e).digest("hex").slice(0,16)}function Ui(e){if(e.length<16)throw new Error("seed too short (need at least 16 bytes)");let t=new TextEncoder().encode("protect.env.x25519.v1"),n=Buffer.from((0,Fi.hkdf)(Li.sha256,e,new Uint8Array(0),t,32)),r=Buffer.from(Mi.x25519.scalarMultBase(n));return{secretKey:n,publicKey:r,kid:Gr(r)}}function Hi(){return(0,Ur.randomBytes)(32)}function Vi(e){return Buffer.from(`protect.env.v3|${e}`,"utf8")}async function Gi(e,t,n){if(e.length!==32)throw new Error("sealDek: DEK must be 32 bytes");if(t.length!==32)throw new Error("sealDek: public key must be 32 bytes");let r=await Dt.kem.deserializePublicKey(Te(t)),o=await Dt.createSenderContext({recipientPublicKey:r,info:Te(n)}),a=Buffer.from(await o.seal(Te(e),new ArrayBuffer(0))),i=Buffer.from(o.enc),s=Buffer.alloc(6+i.length+a.length);return s[0]=Hr,s[1]=Vr,s.writeUInt16BE(i.length,2),s.writeUInt16BE(a.length,4),i.copy(s,6),a.copy(s,6+i.length),s}async function qi(e,t,n){let r=qr(e),o=e.subarray(6,6+r.encLen),a=e.subarray(6+r.encLen),i=await Dt.kem.deserializePrivateKey(Te(t)),s=await Dt.createRecipientContext({recipientKey:i,enc:Te(o),info:Te(n)});return Buffer.from(await s.open(Te(a)))}function qr(e){if(e.length<6)throw new Error("sealed bytes too short");if(e.length>Y.MAX_SEALED_BYTES)throw new Error("sealed bytes too long");let t=e[0],n=e[1];if(t!==Hr)throw new Error(`unsupported seal version 0x${t.toString(16)}`);if(n!==Vr)throw new Error(`unsupported HPKE suite 0x${n.toString(16)}`);let r=e.readUInt16BE(2),o=e.readUInt16BE(4);if(e.length!==6+r+o)throw new Error("sealed length mismatch");if(r!==32)throw new Error("unexpected KEM enc length (X25519 is 32 bytes)");if(o<16)throw new Error("ciphertext shorter than the AEAD tag");return{ver:t,suite:n,encLen:r,ctLen:o}}function Te(e){return e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength)}});var Jr=O(pe=>{"use strict";Object.defineProperty(pe,"__esModule",{value:!0});pe.V3_PREFIX=void 0;pe.sealValue=Wi;pe.formatToken=Ji;pe.parseToken=Wr;pe.openValue=zi;var Ot=A("crypto"),Nt=kn();pe.V3_PREFIX="aes256gcm:v3:";async function Wi(e,t){let n=(0,Ot.randomBytes)(32),r=(0,Ot.randomBytes)(12),o=(0,Ot.createCipheriv)("aes-256-gcm",n,r),a=Buffer.concat([o.update(e,"utf8"),o.final()]),i=Buffer.concat([a,o.getAuthTag()]),s=await(0,Nt.sealDek)(n,t.publicKey,(0,Nt.buildEnvInfo)(t.kid));return n.fill(0),{sealedDekB64:s.toString("base64"),iv:r,cipher:i}}function Ji(e,t){return`${pe.V3_PREFIX}${e.iv.toString("base64")}:${e.cipher.toString("base64")}:${t}`}function Wr(e){let t=e.split(":");if(t.length!==5||t[0]!=="aes256gcm"||t[1]!=="v3")throw new Error("not a v3 token");let[,,n,r,o]=t;if(!o)throw new Error("v3 token has no seal id");let a=Buffer.from(n,"base64"),i=Buffer.from(r,"base64");if(a.length!==12)throw new Error("v3 token has a malformed iv");if(i.length<17)throw new Error("v3 token ciphertext is too short");return{iv:a,cipher:i,sealId:o}}async function zi(e,t,n){let{iv:r,cipher:o}=Wr(e),a=await(0,Nt.openSealedDek)(Buffer.from(t,"base64"),n.secretKey,(0,Nt.buildEnvInfo)(n.kid)),i=o.subarray(o.length-16),s=o.subarray(0,o.length-16),l=(0,Ot.createDecipheriv)("aes-256-gcm",a,r);l.setAuthTag(i);try{return Buffer.concat([l.update(s),l.final()]).toString("utf8")}finally{a.fill(0)}}});var Zr=O(V=>{"use strict";var Yi=V&&V.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n);var o=Object.getOwnPropertyDescriptor(t,n);(!o||("get"in o?!t.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,o)}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),Xi=V&&V.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),An=V&&V.__importStar||(function(){var e=function(t){return e=Object.getOwnPropertyNames||function(n){var r=[];for(var o in n)Object.prototype.hasOwnProperty.call(n,o)&&(r[r.length]=o);return r},e(t)};return function(t){if(t&&t.__esModule)return t;var n={};if(t!=null)for(var r=e(t),o=0;o<r.length;o++)r[o]!=="default"&&Yi(n,t,r[o]);return Xi(n,t),n}})();Object.defineProperty(V,"__esModule",{value:!0});V.deviceKeyPath=Qi;V.hasDeviceKey=es;V.loadDeviceKey=ts;V.createDeviceKey=ns;V.importDeviceKey=rs;V.exportSeedHex=os;V.deviceKeyIsExposed=as;var W=An(A("fs")),Zi=An(A("os")),zr=An(A("path")),it=kn(),xn=zr.join(Zi.homedir(),".nodata"),M=zr.join(xn,"device-key.json");function Qi(){return M}function Yr(){let e=process.env.NODATA_DEVICE_SEED;if(!e)return null;let t=e.trim();if(!/^[0-9a-fA-F]{64}$/.test(t))throw new Error("NODATA_DEVICE_SEED must be 64 hex characters (32 bytes)");return Buffer.from(t,"hex")}function es(){return Yr()!==null||W.existsSync(M)}function ts(){let e=Yr();if(e)return(0,it.deriveKeyPairFromSeed)(e);if(!W.existsSync(M))return null;let t;try{t=JSON.parse(W.readFileSync(M,"utf-8"))}catch{throw new Error(`Device key file is unreadable: ${M}`)}if(!t.seed_hex||!/^[0-9a-f]{64}$/i.test(t.seed_hex))throw new Error(`Device key file is malformed (bad seed): ${M}`);let n=(0,it.deriveKeyPairFromSeed)(Buffer.from(t.seed_hex,"hex"));if(t.kid&&t.kid!==n.kid)throw new Error(`Device key file is inconsistent: stored kid ${t.kid} does not match the seed (${n.kid}).`);return n}function ns(e={}){if(W.existsSync(M)&&!e.force)throw new Error(`A device key already exists at ${M}. Replacing it makes every existing v3 seal unopenable. Back up the seed first (nodata key export), then pass --force.`);let t=(0,it.generateSeed)(),n=(0,it.deriveKeyPairFromSeed)(t);return Xr(t,n),n}function rs(e,t={}){let n=e.trim().replace(/\s+/g,"");if(!/^[0-9a-fA-F]{64}$/.test(n))throw new Error("Seed must be 64 hex characters (32 bytes).");if(W.existsSync(M)&&!t.force)throw new Error(`A device key already exists at ${M}. Pass --force to replace it.`);let r=Buffer.from(n,"hex"),o=(0,it.deriveKeyPairFromSeed)(r);return Xr(r,o),o}function os(){if(!W.existsSync(M))throw new Error("No device key file to export.");return JSON.parse(W.readFileSync(M,"utf-8")).seed_hex}function Xr(e,t){W.existsSync(xn)||W.mkdirSync(xn,{recursive:!0});let n={version:1,kid:t.kid,pubkey_hex:t.publicKey.toString("hex"),seed_hex:e.toString("hex"),created_at:new Date().toISOString()};W.writeFileSync(M,JSON.stringify(n,null,2)+`
|
|
5
|
+
`,{mode:384});try{W.chmodSync(M,384)}catch{}}function as(){if(process.platform==="win32"||!W.existsSync(M))return!1;try{return(W.statSync(M).mode&63)!==0}catch{return!1}}});var to=O(J=>{"use strict";var is=J&&J.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n);var o=Object.getOwnPropertyDescriptor(t,n);(!o||("get"in o?!t.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,o)}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),ss=J&&J.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),Qr=J&&J.__importStar||(function(){var e=function(t){return e=Object.getOwnPropertyNames||function(n){var r=[];for(var o in n)Object.prototype.hasOwnProperty.call(n,o)&&(r[r.length]=o);return r},e(t)};return function(t){if(t&&t.__esModule)return t;var n={};if(t!=null)for(var r=e(t),o=0;o<r.length;o++)r[o]!=="default"&&is(n,t,r[o]);return ss(n,t),n}})();Object.defineProperty(J,"__esModule",{value:!0});J.ensureDeviceKey=cs;J.sealFile=ls;J.readManifest=eo;J.openFile=ds;J.writeLocalReceipt=us;var Tn=A("crypto"),ye=A("fs"),st=A("path"),Pn=Qr(Jr()),Dn=Qr(Zr());function cs(){let e=Dn.loadDeviceKey();return e?{key:e,created:!1}:{key:Dn.createDeviceKey(),created:!0}}async function ls(e,t,n){let r=(0,ye.readFileSync)(e),o=(0,Tn.createHash)("sha256").update(r).digest("hex"),a=n??"local-"+(0,Tn.randomUUID)(),i=await Pn.sealValue(r.toString("base64"),t),s={v:3,alg:"aes256gcm:v3",kid:t.kid,orig:(0,st.basename)(e),enc:"base64",token:Pn.formatToken(i,a),sealed_dek:i.sealedDekB64,sha256:o,sealed_at:new Date().toISOString()},l=e+".ndc";return(0,ye.writeFileSync)(l,JSON.stringify(s,null,2)+`
|
|
6
|
+
`,{mode:384}),{path:e,ndc:l,sha256:o,sealId:a}}function eo(e){try{let t=JSON.parse((0,ye.readFileSync)(e,"utf8"));return t.alg==="aes256gcm:v3"&&t.token&&t.sealed_dek?t:null}catch{return null}}async function ds(e,t){if(!(0,ye.existsSync)(e))return{ok:!1,error:"not_found"};let n=eo(e);if(!n)return{ok:!1,error:"not_a_seal"};let r=t===void 0?Dn.loadDeviceKey():t;if(!r)return{ok:!1,error:"no_device_key"};let o;try{o=await Pn.openValue(n.token,n.sealed_dek,r)}catch{return{ok:!1,error:"wrong_key"}}let a=Buffer.from(o,"base64"),i=e.endsWith(".ndc")?e.slice(0,-4):e+".opened";(0,ye.existsSync)(i)&&(i=i+".opened"),(0,ye.writeFileSync)(i,a);let s=(0,Tn.createHash)("sha256").update(a).digest("hex")===n.sha256;return{ok:!0,outPath:i,sha256:n.sha256,intact:s}}function us(e,t){let n=(0,st.join)(e,".nodata","receipts");(0,ye.mkdirSync)(n,{recursive:!0});let r={action:t.action,at:new Date().toISOString(),governed:"local",device_kid:t.kid,removed_plaintext:t.removed_plaintext,files:t.files.map(a=>({path:(0,st.relative)(e,a.path),sha256:a.sha256,seal_id:a.sealId,sealed:(0,st.basename)(a.ndc)})),...t.extra??{}},o=(0,st.join)(n,`${t.action}-${Date.now()}.json`);return(0,ye.writeFileSync)(o,JSON.stringify(r,null,2)+`
|
|
7
|
+
`),o}});var Pe=O(Kn=>{"use strict";Object.defineProperty(Kn,"__esModule",{value:!0});var lt=class{static async generateKeyPair(){let t=await crypto.subtle.generateKey({name:"RSA-OAEP",modulusLength:4096,publicExponent:new Uint8Array([1,0,1]),hash:"SHA-256"},!0,["encrypt","decrypt"]),n=await crypto.subtle.exportKey("jwk",t.publicKey),r=await crypto.subtle.exportKey("jwk",t.privateKey);return{publicKeyJwk:n,privateKeyJwk:r}}static async encryptMessage(t,n){let r=await crypto.subtle.importKey("jwk",n,{name:"RSA-OAEP",hash:"SHA-256"},!1,["encrypt"]),o=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!0,["encrypt","decrypt"]),a=crypto.getRandomValues(new Uint8Array(12)),i=new TextEncoder().encode(t),s=await crypto.subtle.encrypt({name:"AES-GCM",iv:a,tagLength:128},o,i),l=await crypto.subtle.exportKey("raw",o),d=await crypto.subtle.encrypt({name:"RSA-OAEP"},r,l);return{encrypted_blob:this.arrayBufferToBase64(s),encrypted_aes_key:this.arrayBufferToBase64(d),iv:this.arrayBufferToBase64(a)}}static async decryptMessage(t,n){let r=await crypto.subtle.importKey("jwk",n,{name:"RSA-OAEP",hash:"SHA-256"},!1,["decrypt"]),o=this.base64ToArrayBuffer(t.encrypted_aes_key),a=await crypto.subtle.decrypt({name:"RSA-OAEP"},r,o),i=await crypto.subtle.importKey("raw",a,{name:"AES-GCM",length:256},!1,["decrypt"]),s=this.base64ToArrayBuffer(t.iv),l=this.base64ToArrayBuffer(t.encrypted_blob),d=await crypto.subtle.decrypt({name:"AES-GCM",iv:s,tagLength:128},i,l);return new TextDecoder().decode(d)}static async encryptFile(t,n){let r=await t.arrayBuffer(),o=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!0,["encrypt","decrypt"]),a=crypto.getRandomValues(new Uint8Array(12)),i=await crypto.subtle.encrypt({name:"AES-GCM",iv:a,tagLength:128},o,r),s=JSON.stringify({name:t.name,type:t.type,size:t.size,lastModified:t.lastModified}),l=crypto.getRandomValues(new Uint8Array(12)),d=await crypto.subtle.encrypt({name:"AES-GCM",iv:l,tagLength:128},o,new TextEncoder().encode(s)),u=await crypto.subtle.importKey("jwk",n,{name:"RSA-OAEP",hash:"SHA-256"},!1,["encrypt"]),p=await crypto.subtle.exportKey("raw",o),h=await crypto.subtle.encrypt({name:"RSA-OAEP"},u,p);return{encrypted_file:this.arrayBufferToBase64(i),encrypted_file_key:this.arrayBufferToBase64(h),iv:this.arrayBufferToBase64(a),encrypted_metadata:this.arrayBufferToBase64(d),metadata_iv:this.arrayBufferToBase64(l),encrypted_size:i.byteLength}}static async importKeyFromFragment(t){let n=t.replace(/-/g,"+").replace(/_/g,"/"),r=this.base64ToArrayBuffer(n.padEnd(Math.ceil(n.length/4)*4,"="));if(r.byteLength!==32)throw new Error("channel key must be 32 bytes");return crypto.subtle.importKey("raw",r,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}static async deriveKeyFromOTP(t,n,r="SHA-512"){let o=await crypto.subtle.importKey("raw",new TextEncoder().encode(t),"PBKDF2",!1,["deriveBits","deriveKey"]);return await crypto.subtle.deriveKey({name:"PBKDF2",salt:new TextEncoder().encode(n),iterations:31e4,hash:r},o,{name:"AES-GCM",length:256},!0,["encrypt","decrypt"])}static async encryptWithDerivedKey(t,n){let r=crypto.getRandomValues(new Uint8Array(12)),o=new TextEncoder().encode(t),a=await crypto.subtle.encrypt({name:"AES-GCM",iv:r,tagLength:128},n,o);return{encrypted:this.arrayBufferToBase64(a),iv:this.arrayBufferToBase64(r)}}static async decryptWithDerivedKey(t,n,r){let o=this.base64ToArrayBuffer(t),a=this.base64ToArrayBuffer(n),i=await crypto.subtle.decrypt({name:"AES-GCM",iv:a,tagLength:128},r,o);return new TextDecoder().decode(i)}static async sha256Hex(t){let n=t instanceof Uint8Array?t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength):t,r=await crypto.subtle.digest("SHA-256",n);return Array.from(new Uint8Array(r)).map(o=>o.toString(16).padStart(2,"0")).join("")}static async encryptFileWithDerivedKey(t,n){let r=await t.arrayBuffer(),o=await this.sha256Hex(r),a=crypto.getRandomValues(new Uint8Array(12)),i=await crypto.subtle.encrypt({name:"AES-GCM",iv:a,tagLength:128},n,r),s=JSON.stringify({name:t.name,type:t.type,size:t.size,lastModified:t.lastModified}),l=crypto.getRandomValues(new Uint8Array(12)),d=await crypto.subtle.encrypt({name:"AES-GCM",iv:l,tagLength:128},n,new TextEncoder().encode(s));return{encrypted_file:this.arrayBufferToBase64(i),iv:this.arrayBufferToBase64(a),encrypted_metadata:this.arrayBufferToBase64(d),metadata_iv:this.arrayBufferToBase64(l),encrypted_size:i.byteLength,plaintext_sha256:o,ciphertext_sha256:await this.sha256Hex(i)}}static async decryptFileBytesWithDerivedKey(t,n,r){let o=this.base64ToArrayBuffer(n);return crypto.subtle.decrypt({name:"AES-GCM",iv:o,tagLength:128},r,t)}static async decryptFileWithDerivedKey(t,n,r){let o=this.base64ToArrayBuffer(t),a=this.base64ToArrayBuffer(n);return crypto.subtle.decrypt({name:"AES-GCM",iv:a,tagLength:128},r,o)}static async deriveSeedKey(t,n="SHA-512"){let r=t.trim().toLowerCase(),o=await crypto.subtle.importKey("raw",new TextEncoder().encode(r),"PBKDF2",!1,["deriveBits","deriveKey"]);return await crypto.subtle.deriveKey({name:"PBKDF2",salt:new TextEncoder().encode(this.SEED_SALT),iterations:this.PBKDF2_ITERATIONS,hash:n},o,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}static async exportKeyWithSeed(t,n){let r=await crypto.subtle.exportKey("jwk",t),o=new TextEncoder().encode(JSON.stringify(r)),a=crypto.getRandomValues(new Uint8Array(12)),i=await crypto.subtle.encrypt({name:"AES-GCM",iv:a,tagLength:128},n,o),s=new Uint8Array(a.byteLength+i.byteLength);return s.set(a,0),s.set(new Uint8Array(i),a.byteLength),s.buffer}static async importKeyWithSeed(t,n){let r=new Uint8Array(t),o=r.slice(0,12),a=r.slice(12),i=await crypto.subtle.decrypt({name:"AES-GCM",iv:o,tagLength:128},n,a),s=new TextDecoder().decode(i),l=JSON.parse(s),d=await crypto.subtle.importKey("jwk",l,{name:"RSA-OAEP",hash:"SHA-256"},!0,["decrypt"]);return new Uint8Array(i).fill(0),d}static async hashPhone(t){let n=new TextEncoder().encode(t.replace(/\D/g,"")),r=await crypto.subtle.digest("SHA-256",n);return Array.from(new Uint8Array(r)).map(o=>o.toString(16).padStart(2,"0")).join("")}static arrayBufferToBase64(t){let n=new Uint8Array(t),r=32768,o=[];for(let a=0;a<n.length;a+=r)o.push(String.fromCharCode(...n.subarray(a,a+r)));return btoa(o.join(""))}static async encryptFileToBytesWithDerivedKey(t,n){let r=await t.arrayBuffer(),o=await this.sha256Hex(r),a=crypto.getRandomValues(new Uint8Array(12)),i=await crypto.subtle.encrypt({name:"AES-GCM",iv:a,tagLength:128},n,r),s=JSON.stringify({name:t.name,type:t.type,size:t.size,lastModified:t.lastModified}),l=crypto.getRandomValues(new Uint8Array(12)),d=await crypto.subtle.encrypt({name:"AES-GCM",iv:l,tagLength:128},n,new TextEncoder().encode(s));return{ciphertext:i,iv:this.arrayBufferToBase64(a),encrypted_metadata:this.arrayBufferToBase64(d),metadata_iv:this.arrayBufferToBase64(l),encrypted_size:i.byteLength,plaintext_sha256:o,ciphertext_sha256:await this.sha256Hex(i)}}static base64ToArrayBuffer(t){let n=atob(t),r=new Uint8Array(n.length);for(let o=0;o<n.length;o++)r[o]=n.charCodeAt(o);return r.buffer}static wipeFromMemory(t){new Uint8Array(t).fill(0)}};lt.PBKDF2_ITERATIONS=31e4;lt.SEED_SALT="NoDataChat-Seed-v1";Kn.default=lt});var so=O(Rt=>{"use strict";Object.defineProperty(Rt,"__esModule",{value:!0});Rt.solveProofOfWork=vs;Rt.verifyProofOfWork=ws;function Ss(e){let t=new Uint8Array(e),n="";for(let r=0;r<t.length;r++)n+=t[r].toString(16).padStart(2,"0");return n}async function io(e){let t=new TextEncoder().encode(e),n=await crypto.subtle.digest("SHA-256",t);return Ss(n)}async function vs(e,t=4){if(t<1||t>16)throw new Error("Difficulty must be between 1 and 16");let n="0".repeat(t),r=0;for(;;){let o=e+r.toString(),a=await io(o);if(a.startsWith(n))return{nonce:r,hash:a};if(r++,r>2e9)throw new Error("Proof of work exceeded maximum attempts")}}async function ws(e,t,n=4){if(n<1||n>16)return!1;let r="0".repeat(n),o=e+t.toString();return(await io(o)).startsWith(r)}});var Mn=O(je=>{"use strict";var Es=je&&je.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(je,"__esModule",{value:!0});je.NoDataEmail=void 0;var ie=Es(Pe()),jn=class{static async seal(t,n,r,o,a,i={}){let{encrypt_subject:s=!0,ttl_hours:l=72,attachments:d=[]}=i,u=await ie.default.encryptMessage(o,a),p=r,h=!1;if(s){let v=await ie.default.encryptMessage(r,a);p=JSON.stringify(v),h=!0}let m=[];for(let v of d){let k=await ie.default.encryptFile(v,a);m.push({encrypted_file:k})}return{from_alias:t,to:n,subject:p,subject_encrypted:h,body:u,attachments:m,sealed_at:new Date().toISOString(),ttl_hours:l,envelope_id:crypto.randomUUID(),crypto_version:"0.2.0"}}static async open(t,n){let r=await ie.default.decryptMessage(t.body,n),o=t.subject;if(t.subject_encrypted){let i=JSON.parse(t.subject);o=await ie.default.decryptMessage(i,n)}let a=[];for(let i of t.attachments){let{encrypted_file:s}=i,l=ie.default.base64ToArrayBuffer(s.metadata_iv),d=ie.default.base64ToArrayBuffer(s.encrypted_metadata),u=ie.default.base64ToArrayBuffer(s.encrypted_file_key),p=await crypto.subtle.importKey("jwk",n,{name:"RSA-OAEP",hash:"SHA-256"},!1,["decrypt"]),h=await crypto.subtle.decrypt({name:"RSA-OAEP"},p,u),m=await crypto.subtle.importKey("raw",h,{name:"AES-GCM",length:256},!1,["decrypt"]),v=await crypto.subtle.decrypt({name:"AES-GCM",iv:l,tagLength:128},m,d),k=JSON.parse(new TextDecoder().decode(v)),S=ie.default.base64ToArrayBuffer(s.iv),_=ie.default.base64ToArrayBuffer(s.encrypted_file),w=await crypto.subtle.decrypt({name:"AES-GCM",iv:S,tagLength:128},m,_);a.push({filename:k.name,mime_type:k.type,data:w,size:k.size})}return{subject:o,body:r,attachments:a,sealed_at:t.sealed_at,ttl_hours:t.ttl_hours,envelope_id:t.envelope_id}}static isExpired(t){let r=new Date(t.sealed_at).getTime()+t.ttl_hours*60*60*1e3;return Date.now()>r}static toMimeBody(t,n){let r=JSON.stringify(t),o=btoa(unescape(encodeURIComponent(r)));return['Content-Type: multipart/mixed; boundary="nodata-boundary"',"","--nodata-boundary","Content-Type: text/html; charset=utf-8","",'<div style="font-family:system-ui;padding:24px;text-align:center">',"<h2>This email is encrypted with Capsule</h2>","<p>The sender used end-to-end encryption. To read this message:</p>",`<a href="${n}?env=${t.envelope_id}" `,'style="display:inline-block;padding:12px 24px;background:#000;color:#fff;','border-radius:8px;text-decoration:none;font-weight:600">',"Open Encrypted Email</a>",'<p style="color:#888;font-size:12px;margin-top:16px">',"Powered by Capsule — Nothing is ever stored. Ever.</p>","</div>","--nodata-boundary",'Content-Type: application/x-nodata-envelope; name="envelope.nodata"',"Content-Transfer-Encoding: base64",'Content-Disposition: attachment; filename="envelope.nodata"',"",o,"--nodata-boundary--"].join(`\r
|
|
8
|
+
`)}};je.NoDataEmail=jn});var Un=O(Me=>{"use strict";var ks=Me&&Me.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(Me,"__esModule",{value:!0});Me.NoDataWebhook=void 0;var Fn=ks(Pe()),Ln=class{static async encrypt(t,n,r,o){let{event_type:a,source:i,ttl_seconds:s=3600}=o,l=JSON.stringify(t),d=await Fn.default.encryptMessage(l,n),u=new Date().toISOString(),p=crypto.randomUUID(),h=`${p}.${u}.${d.encrypted_blob}`,m=await this.hmacSign(h,r);return{encrypted_event:d,event_type:a,source:i,signature:m,timestamp:u,delivery_id:p,ttl_seconds:s,crypto_version:"0.2.0"}}static async verify(t,n){let r=`${t.delivery_id}.${t.timestamp}.${t.encrypted_event.encrypted_blob}`,o=await this.hmacSign(r,n),a=new TextEncoder().encode(t.signature),i=new TextEncoder().encode(o),s=a.length^i.length,l=Math.min(a.length,i.length);for(let m=0;m<l;m++)s|=a[m]^i[m];let d=s===0,p=new Date(t.timestamp).getTime()+t.ttl_seconds*1e3,h=Date.now()>p;return{valid:d,expired:h,event_type:t.event_type,source:t.source,delivery_id:t.delivery_id}}static async decrypt(t,n){let r=await Fn.default.decryptMessage(t.encrypted_event,n);return JSON.parse(r)}static async verifyAndDecrypt(t,n,r){let o=await this.verify(t,r);if(!o.valid)throw new Error(`[NoDataWebhook] Invalid signature for delivery ${o.delivery_id}`);if(o.expired)throw new Error(`[NoDataWebhook] Payload expired for delivery ${o.delivery_id}`);return{data:await this.decrypt(t,n),delivery_id:o.delivery_id,event_type:o.event_type}}static async hmacSign(t,n){let r=await crypto.subtle.importKey("raw",new TextEncoder().encode(n),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),o=await crypto.subtle.sign("HMAC",r,new TextEncoder().encode(t));return Fn.default.arrayBufferToBase64(o)}};Me.NoDataWebhook=Ln});var Vn=O(Fe=>{"use strict";var xs=Fe&&Fe.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(Fe,"__esModule",{value:!0});Fe.NoDataSystems=void 0;var $t=xs(Pe()),Hn=class{static async encryptRecord(t,n,r,o,a,i){let s=[],l={};for(let[d,u]of Object.entries(r))if(o.sensitive.includes(d)){let p=typeof u=="string"?u:JSON.stringify(u),h=await $t.default.encryptMessage(p,a),m=await this.hashValue(p);s.push({value:h,search_hash:m,field_name:d,encrypted_at:new Date().toISOString()})}else l[d]=u;return{record_id:t,record_type:n,encrypted_fields:s,clear_fields:l,encrypted_by:i,created_at:new Date().toISOString(),crypto_version:"0.2.0"}}static async decryptRecord(t,n){let r={...t.clear_fields};for(let o of t.encrypted_fields){let a=await $t.default.decryptMessage(o.value,n);try{r[o.field_name]=JSON.parse(a)}catch{r[o.field_name]=a}}return{record_id:t.record_id,record_type:t.record_type,fields:r,created_at:t.created_at}}static async searchByHash(t,n,r){let o=await this.hashValue(r);return t.filter(a=>a.encrypted_fields.some(i=>i.field_name===n&&i.search_hash===o))}static async encryptField(t,n,r){let o=typeof n=="string"?n:JSON.stringify(n),a=await $t.default.encryptMessage(o,r),i=await this.hashValue(o);return{value:a,search_hash:i,field_name:t,encrypted_at:new Date().toISOString()}}static async decryptField(t,n){let r=await $t.default.decryptMessage(t.value,n);try{return JSON.parse(r)}catch{return r}}static createSchema(t,n){return{sensitive:n,clear:t.filter(r=>!n.includes(r))}}static async hashValue(t){let n=`nodatachat:field:${t}`,r=new TextEncoder().encode(n),o=await crypto.subtle.digest("SHA-256",r);return Array.from(new Uint8Array(o)).map(a=>a.toString(16).padStart(2,"0")).join("")}};Fe.NoDataSystems=Hn});var qn=O(Le=>{"use strict";var As=Le&&Le.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(Le,"__esModule",{value:!0});Le.NoDataForms=void 0;var se=As(Pe()),Gn=class{static async encryptSubmission(t,n,r,o,a={}){let{ttl_hours:i=0,view_once:s=!1,attachments:l=[]}=a,d={},u={};for(let S of n)S.sensitive!==!1?d[S.name]=S.value:u[S.name]=S.value;let p=JSON.stringify(n.map(S=>({name:S.name,value:S.value}))),h=await this.sha256(p),m=await se.default.encryptMessage(JSON.stringify(d),r),v=[];for(let S of l){let _=await se.default.encryptFile(S,r);v.push(_)}let k=n.map(S=>S.name);return{submission_id:crypto.randomUUID(),form_id:t,encrypted_fields:m,clear_fields:u,attachments:v,integrity_hash:h,field_order:k,submitter_id:o,submitted_at:new Date().toISOString(),ttl_hours:i,view_once:s,crypto_version:"0.2.0"}}static async decryptSubmission(t,n){let r=await se.default.decryptMessage(t.encrypted_fields,n),o=JSON.parse(r),a={...t.clear_fields,...o},s=(t.field_order||Object.keys(a).sort()).map(p=>({name:p,value:a[p]})),d=await this.sha256(JSON.stringify(s))===t.integrity_hash,u=[];for(let p of t.attachments){let h=await crypto.subtle.importKey("jwk",n,{name:"RSA-OAEP",hash:"SHA-256"},!1,["decrypt"]),m=await crypto.subtle.decrypt({name:"RSA-OAEP"},h,se.default.base64ToArrayBuffer(p.encrypted_file_key)),v=await crypto.subtle.importKey("raw",m,{name:"AES-GCM",length:256},!1,["decrypt"]),k=await crypto.subtle.decrypt({name:"AES-GCM",iv:se.default.base64ToArrayBuffer(p.metadata_iv),tagLength:128},v,se.default.base64ToArrayBuffer(p.encrypted_metadata)),S=JSON.parse(new TextDecoder().decode(k)),_=await crypto.subtle.decrypt({name:"AES-GCM",iv:se.default.base64ToArrayBuffer(p.iv),tagLength:128},v,se.default.base64ToArrayBuffer(p.encrypted_file));u.push({filename:S.name,mime_type:S.type,data:_,size:S.size})}return{submission_id:t.submission_id,form_id:t.form_id,fields:a,attachments:u,integrity_valid:d,submitted_at:t.submitted_at}}static isExpired(t){if(t.ttl_hours===0)return!1;let r=new Date(t.submitted_at).getTime()+t.ttl_hours*60*60*1e3;return Date.now()>r}static async encryptGrade(t,n,r,o,a=0){let i=await se.default.encryptMessage(JSON.stringify(t),n),s=await this.sha256(`nodatachat:student:${t.student_id}`);return{encrypted_grade:i,student_hash:s,course_id:r,term:o,delivery_id:crypto.randomUUID(),delivered_at:new Date().toISOString(),ttl_hours:a,crypto_version:"0.2.0"}}static async decryptGrade(t,n){let r=await se.default.decryptMessage(t.encrypted_grade,n);return JSON.parse(r)}static async sha256(t){let n=new TextEncoder().encode(t),r=await crypto.subtle.digest("SHA-256",n);return Array.from(new Uint8Array(r)).map(o=>o.toString(16).padStart(2,"0")).join("")}};Le.NoDataForms=Gn});var co=O(Ue=>{"use strict";var Ts=Ue&&Ue.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(Ue,"__esModule",{value:!0});Ue.NoDataSDK=void 0;var Bt=Ts(Pe()),ge=Mn(),_e=Un(),X=Vn(),ce=qn(),Wn=class{static async init(t={}){let n;return t.keyPair?n=t.keyPair:(n=await Bt.default.generateKeyPair(),t.onKeysGenerated&&await t.onKeysGenerated(n)),{publicKey:n.publicKeyJwk,email:{seal:ge.NoDataEmail.seal.bind(ge.NoDataEmail),open:ge.NoDataEmail.open.bind(ge.NoDataEmail),isExpired:ge.NoDataEmail.isExpired.bind(ge.NoDataEmail),toMimeBody:ge.NoDataEmail.toMimeBody.bind(ge.NoDataEmail)},webhook:{encrypt:_e.NoDataWebhook.encrypt.bind(_e.NoDataWebhook),verify:_e.NoDataWebhook.verify.bind(_e.NoDataWebhook),decrypt:_e.NoDataWebhook.decrypt.bind(_e.NoDataWebhook),verifyAndDecrypt:_e.NoDataWebhook.verifyAndDecrypt.bind(_e.NoDataWebhook)},systems:{encryptRecord:X.NoDataSystems.encryptRecord.bind(X.NoDataSystems),decryptRecord:X.NoDataSystems.decryptRecord.bind(X.NoDataSystems),searchByHash:X.NoDataSystems.searchByHash.bind(X.NoDataSystems),encryptField:X.NoDataSystems.encryptField.bind(X.NoDataSystems),decryptField:X.NoDataSystems.decryptField.bind(X.NoDataSystems),createSchema:X.NoDataSystems.createSchema.bind(X.NoDataSystems)},forms:{encryptSubmission:ce.NoDataForms.encryptSubmission.bind(ce.NoDataForms),decryptSubmission:ce.NoDataForms.decryptSubmission.bind(ce.NoDataForms),isExpired:ce.NoDataForms.isExpired.bind(ce.NoDataForms),encryptGrade:ce.NoDataForms.encryptGrade.bind(ce.NoDataForms),decryptGrade:ce.NoDataForms.decryptGrade.bind(ce.NoDataForms)},crypto:Bt.default}}static async quickEncrypt(t,n){let r=typeof t=="string"?t:JSON.stringify(t),o=await Bt.default.encryptMessage(r,n);return JSON.stringify(o)}static async quickDecrypt(t,n){let r=JSON.parse(t),o=await Bt.default.decryptMessage(r,n);try{return JSON.parse(o)}catch{return o}}};Ue.NoDataSDK=Wn});var lo=O(Z=>{"use strict";Object.defineProperty(Z,"__esModule",{value:!0});Z.NoDataSDK=Z.NoDataForms=Z.NoDataSystems=Z.NoDataWebhook=Z.NoDataEmail=void 0;var Ps=Mn();Object.defineProperty(Z,"NoDataEmail",{enumerable:!0,get:function(){return Ps.NoDataEmail}});var Ds=Un();Object.defineProperty(Z,"NoDataWebhook",{enumerable:!0,get:function(){return Ds.NoDataWebhook}});var Os=Vn();Object.defineProperty(Z,"NoDataSystems",{enumerable:!0,get:function(){return Os.NoDataSystems}});var Ns=qn();Object.defineProperty(Z,"NoDataForms",{enumerable:!0,get:function(){return Ns.NoDataForms}});var Is=co();Object.defineProperty(Z,"NoDataSDK",{enumerable:!0,get:function(){return Is.NoDataSDK}})});var Ve=O(T=>{"use strict";Object.defineProperty(T,"__esModule",{value:!0});T.PQ_SIZES=T.NDC_WIRE_V03=T.NDC_WIRE_V1=T.NDC_V03_RATCHET_DOMAIN=T.NDC_V03_CONTENT_KEY_DOMAIN=T.NDC_V03_KEM_DOMAIN=T.PQ_SUITE=void 0;T.generateHybridKemKeypair=Cs;T.deriveHybridKemKeypairFromSeed=Rs;T.hybridKemEncapsulate=$s;T.hybridKemDecapsulate=Bs;T.deriveContentKey=Ks;T.ratchetAdvance=js;T.generateHybridSigKeypair=Ms;T.hybridSign=Fs;T.hybridVerify=Ls;T.generateMlDsa65Keypair=Us;T.mlDsa65SignDetached=Hs;T.mlDsa65VerifyDetached=Vs;var be=A("@noble/curves/ed25519.js"),dt=A("@noble/hashes/sha2.js"),ut=A("@noble/hashes/hkdf.js"),Kt=A("@noble/post-quantum/ml-kem.js"),He=A("@noble/post-quantum/ml-dsa.js");T.PQ_SUITE={KEM:"X25519+ML-KEM-768",SIG:"Ed25519+ML-DSA-65",AEAD:"AES-256-GCM",KDF:"HKDF-SHA-256"};T.NDC_V03_KEM_DOMAIN="NDC-v0.3-hybrid-kem";T.NDC_V03_CONTENT_KEY_DOMAIN="NDC-v0.3-content-key";T.NDC_V03_RATCHET_DOMAIN="NDC-ratchet";T.NDC_WIRE_V1=1;T.NDC_WIRE_V03=2;function uo(...e){let t=0;for(let o of e)t+=o.length;let n=new Uint8Array(t),r=0;for(let o of e)n.set(o,r),r+=o.length;return n}function pt(e){return new TextEncoder().encode(e)}function po(e,t,n,r){let o=uo(e,t),a=uo(pt(T.NDC_V03_KEM_DOMAIN),n,r);return(0,ut.hkdf)(dt.sha256,o,new Uint8Array(0),a,32)}function Cs(){let{secretKey:e,publicKey:t}=be.x25519.keygen(),{publicKey:n,secretKey:r}=Kt.ml_kem768.keygen();return{publicKey:{x25519:t,mlKem:n},secretKey:{x25519:e,mlKem:r}}}function Rs(e){if(e.length<32)throw new Error("seed too short (need >=32 bytes)");let t=(0,ut.hkdf)(dt.sha256,e,new Uint8Array(0),pt("ndc-hybrid-kem-x25519-v1"),32),n=(0,ut.hkdf)(dt.sha256,e,new Uint8Array(0),pt("ndc-hybrid-kem-mlkem768-v1"),64),r=be.x25519.getPublicKey(t),{publicKey:o,secretKey:a}=Kt.ml_kem768.keygen(n);return{publicKey:{x25519:r,mlKem:o},secretKey:{x25519:t,mlKem:a}}}function $s(e){let{secretKey:t,publicKey:n}=be.x25519.keygen(),r=be.x25519.getSharedSecret(t,e.x25519),{cipherText:o,sharedSecret:a}=Kt.ml_kem768.encapsulate(e.mlKem),i=po(a,r,n,e.x25519);return{ciphertext:{ctClassical:n,ctPq:o},sharedSecret:i,ephemeralX25519Pk:n}}function Bs(e,t,n){let r=be.x25519.getSharedSecret(e.x25519,n.ctClassical),o=Kt.ml_kem768.decapsulate(n.ctPq,e.mlKem);return po(o,r,n.ctClassical,t)}function Ks(e){return(0,ut.hkdf)(dt.sha256,e,new Uint8Array(0),pt(T.NDC_V03_CONTENT_KEY_DOMAIN),32)}function js(e,t){return(0,ut.hkdf)(dt.sha256,e,t,pt(T.NDC_V03_RATCHET_DOMAIN),32)}function Ms(){let{secretKey:e,publicKey:t}=be.ed25519.keygen(),{publicKey:n,secretKey:r}=He.ml_dsa65.keygen();return{publicKey:{ed25519:t,mlDsa:n},secretKey:{ed25519:e,mlDsa:r}}}function Fs(e,t){return{ed25519:be.ed25519.sign(t,e.ed25519),mlDsa:He.ml_dsa65.sign(t,e.mlDsa)}}function Ls(e,t,n){return be.ed25519.verify(n.ed25519,t,e.ed25519)?He.ml_dsa65.verify(n.mlDsa,t,e.mlDsa):!1}function Us(){let{publicKey:e,secretKey:t}=He.ml_dsa65.keygen();return{publicKey:e,secretKey:t}}function Hs(e,t){return He.ml_dsa65.sign(t,e)}function Vs(e,t,n){return He.ml_dsa65.verify(n,t,e)}T.PQ_SIZES={X25519_PK:32,X25519_SK:32,ML_KEM_768_PK:1184,ML_KEM_768_SK:2400,ML_KEM_768_CT:1088,ED25519_PK:32,ED25519_SK:32,ED25519_SIG:64,ML_DSA_65_PK:1952,ML_DSA_65_SK:4032,ML_DSA_65_SIG:3309,HYBRID_SHARED_SECRET:32}});var Mt=O(P=>{"use strict";Object.defineProperty(P,"__esModule",{value:!0});P.deriveContentKey=P.ContainerV3Error=P.CONTAINER_HEADER_MAX_BYTES=P.CONTAINER_FIXED_PREFIX_BYTES=P.CONTAINER_MAGIC=void 0;P.canonicalJson=jt;P.headerSigningBytes=Jn;P.signContainerHeader=mo;P.verifyContainerHeader=go;P.encodeContainerV3=_o;P.decodeContainerV3=bo;P.sealHybrid=Ys;P.openHybrid=Xs;var Gs=A("@noble/hashes/hkdf.js"),qs=A("@noble/hashes/sha2.js"),K=Ve();Object.defineProperty(P,"deriveContentKey",{enumerable:!0,get:function(){return K.deriveContentKey}});P.CONTAINER_MAGIC=new Uint8Array([78,68,76,66]);P.CONTAINER_FIXED_PREFIX_BYTES=8;P.CONTAINER_HEADER_MAX_BYTES=16777215;var Ws="NDC-v0.3-wrap-key",F=class extends Error{constructor(t,n){super(n),this.name="ContainerV3Error",this.code=t}};P.ContainerV3Error=F;var fe=e=>{if(typeof Buffer<"u")return Buffer.from(e).toString("base64");let t="";for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return btoa(t)},De=e=>{if(typeof Buffer<"u")return new Uint8Array(Buffer.from(e,"base64"));let t=atob(e),n=new Uint8Array(t.length);for(let r=0;r<t.length;r++)n[r]=t.charCodeAt(r);return n},yo=e=>{let t="";for(let n=0;n<e.length;n++)t+=e[n].toString(16).padStart(2,"0");return t};function jt(e){if(e===null||typeof e!="object")return JSON.stringify(e);if(Array.isArray(e))return"["+e.map(jt).join(",")+"]";let t=e;return"{"+Object.keys(t).sort().map(r=>JSON.stringify(r)+":"+jt(t[r])).join(",")+"}"}function Jn(e){let t={...e};return delete t.sig,new TextEncoder().encode(jt(t))}function mo(e,t,n){let r=(0,K.hybridSign)(n.secretKey,Jn(e));return{...e,sig:{signer_kid:t,ed25519:fe(r.ed25519),ml_dsa_65:fe(r.mlDsa)}}}function go(e,t){let n={ed25519:De(e.sig.ed25519),mlDsa:De(e.sig.ml_dsa_65)};return(0,K.hybridVerify)(t,Jn(e),n)}var Js=["lockbox_id","format_version","profile","suite","server","kem","wrapped_content_key","iv","tag","bearer","dpop_required","ciphertext_sha256","issued_at","cache_ttl_seconds","original_filename","original_content_type","sig"];function zs(e){if(!e||typeof e!="object")throw new F("header_schema_mismatch","header is not an object");let t=e;for(let r of Js)if(t[r]===void 0)throw new F("header_schema_mismatch",`header missing required field: ${String(r)}`);if(t.format_version!==3)throw new F("unsupported_version",`format_version ${t.format_version} unknown`);if(t.profile!=="pq-hybrid")throw new F("suite_unknown",`profile must be 'pq-hybrid', got '${String(t.profile)}'`);let n=t.suite;if(n.kem!==K.PQ_SUITE.KEM||n.sig!==K.PQ_SUITE.SIG||n.aead!==K.PQ_SUITE.AEAD||n.kdf!==K.PQ_SUITE.KDF)throw new F("suite_unknown",`suite mismatch: viewer supports ${JSON.stringify(K.PQ_SUITE)}, header has ${JSON.stringify(n)}`)}function _o(e,t){let n=new TextEncoder().encode(JSON.stringify(e));if(n.length>P.CONTAINER_HEADER_MAX_BYTES)throw new F("header_schema_mismatch",`header too large (${n.length} bytes; max 16 MB)`);let r=new Uint8Array(P.CONTAINER_FIXED_PREFIX_BYTES+n.length+t.length);return r.set(P.CONTAINER_MAGIC,0),r[4]=K.NDC_WIRE_V03,r[5]=n.length>>16&255,r[6]=n.length>>8&255,r[7]=n.length&255,r.set(n,P.CONTAINER_FIXED_PREFIX_BYTES),r.set(t,P.CONTAINER_FIXED_PREFIX_BYTES+n.length),r}function bo(e){if(e.length<P.CONTAINER_FIXED_PREFIX_BYTES)throw new F("header_truncated",`container truncated: ${e.length} bytes (need \u2265 ${P.CONTAINER_FIXED_PREFIX_BYTES})`);for(let o=0;o<4;o++)if(e[o]!==P.CONTAINER_MAGIC[o])throw new F("bad_magic",`bad magic: expected NDLB, got ${yo(e.slice(0,4))}`);if(e[4]!==K.NDC_WIRE_V03)throw new F("unsupported_version",`expected wire version 0x${K.NDC_WIRE_V03.toString(16)}, got 0x${e[4].toString(16)}`);let t=e[5]<<16|e[6]<<8|e[7],n=P.CONTAINER_FIXED_PREFIX_BYTES+t;if(e.length<n)throw new F("header_truncated",`header truncated: declared ${t}, only ${e.length-P.CONTAINER_FIXED_PREFIX_BYTES} bytes left`);let r;try{r=JSON.parse(new TextDecoder("utf-8").decode(e.slice(P.CONTAINER_FIXED_PREFIX_BYTES,n)))}catch(o){throw new F("header_invalid_json",`header JSON parse failed: ${o.message}`)}return zs(r),{header:r,ciphertextWithTag:e.slice(n)}}var Oe=e=>e;async function fo(e,t,n){let r=await crypto.subtle.importKey("raw",Oe(e),{name:"AES-GCM"},!1,["encrypt"]),o=await crypto.subtle.encrypt({name:"AES-GCM",iv:Oe(t)},r,Oe(n));return new Uint8Array(o)}async function ho(e,t,n){let r=await crypto.subtle.importKey("raw",Oe(e),{name:"AES-GCM"},!1,["decrypt"]),o=await crypto.subtle.decrypt({name:"AES-GCM",iv:Oe(t)},r,Oe(n));return new Uint8Array(o)}function So(e){return(0,Gs.hkdf)(qs.sha256,e,new Uint8Array(0),new TextEncoder().encode(Ws),32)}async function vo(e){let t=await crypto.subtle.digest("SHA-256",Oe(e));return yo(new Uint8Array(t))}async function Ys(e){let t=crypto.getRandomValues(new Uint8Array(32)),n=crypto.getRandomValues(new Uint8Array(12)),r=await fo(t,n,e.plaintext),o=r.slice(r.length-16),a=r.slice(0,r.length-16),i=(0,K.hybridKemEncapsulate)(e.recipientPublicKey),s=So(i.sharedSecret),l=crypto.getRandomValues(new Uint8Array(12)),d=await fo(s,l,t),u=await vo(a),p={lockbox_id:e.meta.lockbox_id,format_version:3,profile:"pq-hybrid",suite:{kem:K.PQ_SUITE.KEM,sig:K.PQ_SUITE.SIG,aead:K.PQ_SUITE.AEAD,kdf:K.PQ_SUITE.KDF},server:e.meta.server,kem:{recipient_kid:e.recipientKid,ct_classical:fe(i.ciphertext.ctClassical),ct_pq:fe(i.ciphertext.ctPq),ephemeral_x25519_pk:fe(i.ephemeralX25519Pk)},wrapped_content_key:{wrapped:fe(d),wrap_iv:fe(l)},iv:fe(n),tag:fe(o),bearer:e.meta.bearer,dpop_required:e.meta.dpop_required,ratchet_state:e.meta.ratchet_state,tee_attestation_url:e.meta.tee_attestation_url,original_filename:e.meta.original_filename,original_content_type:e.meta.original_content_type,ciphertext_sha256:u,issued_at:new Date().toISOString(),cache_ttl_seconds:e.meta.cache_ttl_seconds},h=mo(p,e.signerKid,e.signerKeypair),m=_o(h,r);return t.fill(0),{container:m,header:h,serverState:{lockbox_id:e.meta.lockbox_id,kem_ct_classical_b64:h.kem.ct_classical,kem_ct_pq_b64:h.kem.ct_pq,wrapped_content_key_b64:h.wrapped_content_key.wrapped,wrap_iv_b64:h.wrapped_content_key.wrap_iv}}}async function Xs(e){let{header:t,ciphertextWithTag:n}=bo(e.container);if(!go(t,e.signerPublicKey))throw new F("signature_invalid","hybrid signature verification failed");let r=n.slice(0,n.length-16),o=await vo(r);if(o!==t.ciphertext_sha256)throw new F("integrity_mismatch",`ciphertext sha256 mismatch: expected ${t.ciphertext_sha256.slice(0,16)}\u2026, got ${o.slice(0,16)}\u2026`);let a={ctClassical:De(t.kem.ct_classical),ctPq:De(t.kem.ct_pq)},i=(0,K.hybridKemDecapsulate)(e.recipientSecretKey,e.recipientPublicX25519,a),s=So(i),l=De(t.wrapped_content_key.wrapped),d=De(t.wrapped_content_key.wrap_iv),u=await ho(s,d,l),p=De(t.iv),h=await ho(u,p,n);return u.fill(0),{plaintext:h,header:t}}});var Yn=O(qe=>{"use strict";Object.defineProperty(qe,"__esModule",{value:!0});qe.publicJwkFromBytes=Eo;qe.jwkThumbprint=ko;qe.createDpop=Qs;qe.verifyDpop=tc;var wo=A("@noble/curves/ed25519.js"),Zs=A("@noble/hashes/sha2.js"),Ge=e=>{if(typeof Buffer<"u")return Buffer.from(e).toString("base64").replace(/=+$/,"").replace(/\+/g,"-").replace(/\//g,"_");let t="";for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return btoa(t).replace(/=+$/,"").replace(/\+/g,"-").replace(/\//g,"_")},Ft=e=>{let t=e.replace(/-/g,"+").replace(/_/g,"/"),n=t.length%4?4-t.length%4:0,r=t+"=".repeat(n);if(typeof Buffer<"u")return new Uint8Array(Buffer.from(r,"base64"));let o=atob(r),a=new Uint8Array(o.length);for(let i=0;i<o.length;i++)a[i]=o.charCodeAt(i);return a},ft=e=>new TextEncoder().encode(e);function Eo(e){if(e.length!==32)throw new Error(`expected 32-byte Ed25519 public key, got ${e.length}`);return{kty:"OKP",crv:"Ed25519",x:Ge(e)}}function ko(e){let t=`{"crv":"${e.crv}","kty":"${e.kty}","x":"${e.x}"}`,n=(0,Zs.sha256)(ft(t));return Ge(n)}function Qs(e){let n={typ:"dpop+jwt",alg:"EdDSA",jwk:Eo(e.publicKey)},r={htm:e.htm.toUpperCase(),htu:zn(e.htu),jti:e.jti??ec(),iat:e.iat??Math.floor(Date.now()/1e3)};e.nonce&&(r.nonce=e.nonce);let o=Ge(ft(JSON.stringify(n))),a=Ge(ft(JSON.stringify(r))),i=`${o}.${a}`,s=wo.ed25519.sign(ft(i),e.secretKey);return`${i}.${Ge(s)}`}function ec(){return Ge(crypto.getRandomValues(new Uint8Array(16)))}function zn(e){try{let t=new URL(e);return`${t.protocol}//${t.host}${t.pathname}`}catch{return e}}async function tc(e,t){let n=e.split(".");if(n.length!==3)return L("malformed","expected three JWT parts");let[r,o,a]=n,i;try{i=JSON.parse(new TextDecoder().decode(Ft(r)))}catch{return L("bad_header","header is not valid base64url JSON")}if(i.typ!=="dpop+jwt")return L("bad_typ",`typ must be 'dpop+jwt', got '${String(i.typ)}'`);if(i.alg!=="EdDSA")return L("bad_alg",`alg must be 'EdDSA', got '${String(i.alg)}'`);if(!i.jwk||i.jwk.kty!=="OKP"||i.jwk.crv!=="Ed25519")return L("bad_header","jwk must be an Ed25519 OKP key");let s=ko(i.jwk);if(s!==t.expectedJkt)return L("jkt_mismatch",`jkt does not match registered key: expected ${t.expectedJkt.slice(0,12)}\u2026, got ${s.slice(0,12)}\u2026`);let l;try{l=JSON.parse(new TextDecoder().decode(Ft(o)))}catch{return L("bad_payload","payload is not valid base64url JSON")}if(l.htm!==t.expectedHtm.toUpperCase())return L("htm_mismatch",`htm '${l.htm}' \u2260 expected '${t.expectedHtm.toUpperCase()}'`);if(l.htu!==zn(t.expectedHtu))return L("htu_mismatch",`htu '${l.htu}' \u2260 expected '${zn(t.expectedHtu)}'`);if(t.expectedNonce!==void 0&&l.nonce!==t.expectedNonce)return L("nonce_mismatch","DPoP nonce does not match server-issued nonce");let d=Math.floor(Date.now()/1e3),u=t.maxAgeSeconds??30;if(typeof l.iat!="number")return L("bad_payload","iat missing or not a number");if(l.iat>d+5)return L("iat_in_future",`iat ${l.iat} > now+skew`);if(d-l.iat>u)return L("iat_too_old",`iat ${l.iat} older than ${u}s`);let p;try{p=Ft(i.jwk.x)}catch{return L("bad_header","jwk.x is not base64url")}let h=Ft(a),m=ft(`${r}.${o}`);return wo.ed25519.verify(h,m,p)?await t.isJtiFresh(l.jti)?{ok:!0,jti:l.jti,iat:l.iat}:L("replay",`jti ${l.jti} was already seen`):L("signature_invalid","Ed25519 signature does not verify")}function L(e,t){return{ok:!1,code:e,reason:t}}});var No=O(b=>{"use strict";Object.defineProperty(b,"__esModule",{value:!0});b.ABSORB_STATUS=b.DELTA_KIND=b.RCPT_TOTAL_LEN=b.RCPT_SIGNED_LEN=b.PVE_TOTAL_LEN=b.PVE_SIGNED_LEN=b.RCPT_VERSION=b.PVE_VERSION=b.RCPT_MAGIC=b.PVE_MAGIC=void 0;b.deltaIdFromUuid=ac;b.uuidFromDeltaId=ic;b.originJktForPublicKey=yt;b.encodePveSignedBytes=To;b.signPve=sc;b.parsePve=Po;b.pveHash=cc;b.verifyPve=lc;b.encodeReceiptSignedBytes=Do;b.signReceipt=dc;b.parseReceipt=Oo;b.verifyReceipt=uc;var Lt=A("@noble/curves/ed25519.js"),nc=A("@noble/hashes/sha2.js"),xo=Yn();b.PVE_MAGIC=new Uint8Array([80,86,69,49]);b.RCPT_MAGIC=new Uint8Array([82,67,86,49]);b.PVE_VERSION=1;b.RCPT_VERSION=1;b.PVE_SIGNED_LEN=160;b.PVE_TOTAL_LEN=b.PVE_SIGNED_LEN+64;b.RCPT_SIGNED_LEN=78;b.RCPT_TOTAL_LEN=b.RCPT_SIGNED_LEN+64;var Ao=new Uint8Array(32);b.DELTA_KIND={relay:1,ndc:2,v4section:3,chatmsg:4};b.ABSORB_STATUS={decrypted_ok:1,verified_only:2,denied:3};function rc(e){if(typeof Buffer<"u")return Buffer.from(e).toString("base64").replace(/=+$/,"").replace(/\+/g,"-").replace(/\//g,"_");let t="";for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return btoa(t).replace(/=+$/,"").replace(/\+/g,"-").replace(/\//g,"_")}function oc(e){let t=e.replace(/-/g,"+").replace(/_/g,"/"),n=t.length%4?4-t.length%4:0,r=t+"=".repeat(n);if(typeof Buffer<"u")return new Uint8Array(Buffer.from(r,"base64"));let o=atob(r),a=new Uint8Array(o.length);for(let i=0;i<o.length;i++)a[i]=o.charCodeAt(i);return a}function Qn(e,t){if(e.length!==t.length)return!1;let n=0;for(let r=0;r<e.length;r++)n|=e[r]^t[r];return n===0}function ht(e){for(let t=0;t<e.length;t++)if(e[t]!==0)return!1;return!0}function Xn(e){if(e==null)return Ao;if(e instanceof Uint8Array){if(e.length!==32)throw new Error(`jkt bytes must be 32, got ${e.length}`);return e}let t=oc(e);if(t.length!==32)throw new Error(`jkt must decode to 32 bytes, got ${t.length}`);return t}function Zn(e){return ht(e)?null:rc(e)}function ac(e){let t=e.replace(/-/g,"");if(t.length!==32)throw new Error(`expected a 16-byte UUID, got '${e}'`);let n=new Uint8Array(16);for(let r=0;r<16;r++)n[r]=parseInt(t.slice(r*2,r*2+2),16);return n}function ic(e){if(e.length!==16)throw new Error(`expected 16 bytes, got ${e.length}`);let t=Array.from(e,n=>n.toString(16).padStart(2,"0")).join("");return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}function yt(e){return(0,xo.jwkThumbprint)((0,xo.publicJwkFromBytes)(e))}function To(e){if(e.deltaId.length!==16)throw new Error("delta_id must be 16 bytes");if(e.ciphertextSha256.length!==32)throw new Error("ciphertext_sha256 must be 32 bytes");if(e.classification<0||e.classification>65535)throw new Error("classification must fit in uint16");let t=new Uint8Array(b.PVE_SIGNED_LEN),n=new DataView(t.buffer),r=0;return t.set(b.PVE_MAGIC,r),r+=4,t[r]=b.PVE_VERSION,r+=1,t[r]=e.deltaKind,r+=1,t.set(e.deltaId,r),r+=16,t.set(e.ciphertextSha256,r),r+=32,t.set(Xn(e.originJkt),r),r+=32,t.set(Xn(e.destJkt??null),r),r+=32,t.set(e.prevDeltaHash??Ao,r),r+=32,n.setUint16(r,e.classification,!1),r+=2,n.setBigUint64(r,BigInt(e.issuedAt),!1),r+=8,t}function sc(e,t){let n=yt(e.originPublicKey),r=To({deltaKind:e.deltaKind,deltaId:e.deltaId,ciphertextSha256:e.ciphertextSha256,originJkt:n,destJkt:e.destJkt??null,prevDeltaHash:e.prevDeltaHash??null,classification:e.classification,issuedAt:e.issuedAt??Date.now()}),o=Lt.ed25519.sign(r,t),a=new Uint8Array(b.PVE_TOTAL_LEN);return a.set(r,0),a.set(o,b.PVE_SIGNED_LEN),a}function Po(e){if(e.length!==b.PVE_TOTAL_LEN)throw new Error(`PVE must be ${b.PVE_TOTAL_LEN} bytes, got ${e.length}`);if(!Qn(e.subarray(0,4),b.PVE_MAGIC))throw new Error("bad PVE magic");let t=new DataView(e.buffer,e.byteOffset,e.byteLength),n=4,r=e[n];n+=1;let o=e[n];n+=1;let a=e.slice(n,n+16);n+=16;let i=e.slice(n,n+32);n+=32;let s=e.slice(n,n+32);n+=32;let l=e.slice(n,n+32);n+=32;let d=e.slice(n,n+32);n+=32;let u=t.getUint16(n,!1);n+=2;let p=Number(t.getBigUint64(n,!1));n+=8;let h=e.slice(0,b.PVE_SIGNED_LEN),m=e.slice(b.PVE_SIGNED_LEN,b.PVE_TOTAL_LEN),v=Zn(s);if(v===null)throw new Error("origin_jkt must not be zero");return{fields:{version:r,deltaKind:o,deltaId:a,ciphertextSha256:i,originJkt:v,destJkt:Zn(l),prevDeltaHash:ht(d)?null:d,classification:u,issuedAt:p},signedBytes:h,originSig:m,broadcast:ht(l),genesis:ht(d)}}function cc(e){return(0,nc.sha256)(e)}function lc(e,t){let n;try{n=Po(e)}catch(o){let a=o instanceof Error?o.message:String(o);return a.includes("magic")?{ok:!1,code:"bad_magic",reason:a}:{ok:!1,code:"malformed",reason:a}}if(n.fields.version!==b.PVE_VERSION)return{ok:!1,code:"bad_version",reason:`unsupported PVE version ${n.fields.version}`};let r;try{r=yt(t)}catch(o){return{ok:!1,code:"malformed",reason:o instanceof Error?o.message:String(o)}}return r!==n.fields.originJkt?{ok:!1,code:"jkt_mismatch",reason:`presented key thumbprint ${r.slice(0,12)}\u2026 \u2260 committed origin_jkt ${n.fields.originJkt.slice(0,12)}\u2026`}:Lt.ed25519.verify(n.originSig,n.signedBytes,t)?{ok:!0,parsed:n}:{ok:!1,code:"signature_invalid",reason:"Ed25519 origin signature does not verify"}}function Do(e){if(e.pveHash.length!==32)throw new Error("pve_hash must be 32 bytes");let t=Xn(e.destJkt);if(ht(t))throw new Error("receipt dest_jkt must not be zero");let n=new Uint8Array(b.RCPT_SIGNED_LEN),r=new DataView(n.buffer),o=0;return n.set(b.RCPT_MAGIC,o),o+=4,n[o]=b.RCPT_VERSION,o+=1,n.set(e.pveHash,o),o+=32,n.set(t,o),o+=32,n[o]=e.absorbStatus,o+=1,r.setBigUint64(o,BigInt(e.absorbedAt),!1),o+=8,n}function dc(e,t){let n=yt(e.destPublicKey),r=Do({pveHash:e.pveHash,destJkt:n,absorbStatus:e.absorbStatus,absorbedAt:e.absorbedAt??Date.now()}),o=Lt.ed25519.sign(r,t),a=new Uint8Array(b.RCPT_TOTAL_LEN);return a.set(r,0),a.set(o,b.RCPT_SIGNED_LEN),a}function Oo(e){if(e.length!==b.RCPT_TOTAL_LEN)throw new Error(`receipt must be ${b.RCPT_TOTAL_LEN} bytes, got ${e.length}`);if(!Qn(e.subarray(0,4),b.RCPT_MAGIC))throw new Error("bad receipt magic");let t=new DataView(e.buffer,e.byteOffset,e.byteLength),n=4,r=e[n];n+=1;let o=e.slice(n,n+32);n+=32;let a=e.slice(n,n+32);n+=32;let i=e[n];n+=1;let s=Number(t.getBigUint64(n,!1));n+=8;let l=Zn(a);if(l===null)throw new Error("receipt dest_jkt must not be zero");return{fields:{version:r,pveHash:o,destJkt:l,absorbStatus:i,absorbedAt:s},signedBytes:e.slice(0,b.RCPT_SIGNED_LEN),destSig:e.slice(b.RCPT_SIGNED_LEN,b.RCPT_TOTAL_LEN)}}function uc(e,t,n){let r;try{r=Oo(e)}catch(a){let i=a instanceof Error?a.message:String(a);return i.includes("magic")?{ok:!1,code:"bad_magic",reason:i}:{ok:!1,code:"malformed",reason:i}}if(r.fields.version!==b.RCPT_VERSION)return{ok:!1,code:"bad_version",reason:`unsupported receipt version ${r.fields.version}`};let o;try{o=yt(t)}catch(a){return{ok:!1,code:"malformed",reason:a instanceof Error?a.message:String(a)}}return o!==r.fields.destJkt?{ok:!1,code:"jkt_mismatch",reason:`presented key thumbprint ${o.slice(0,12)}\u2026 \u2260 committed dest_jkt ${r.fields.destJkt.slice(0,12)}\u2026`}:n!==void 0&&!Qn(n,r.fields.pveHash)?{ok:!1,code:"pve_hash_mismatch",reason:"receipt does not acknowledge the expected PVE"}:Lt.ed25519.verify(r.destSig,r.signedBytes,t)?{ok:!0,parsed:r}:{ok:!1,code:"signature_invalid",reason:"Ed25519 destination signature does not verify"}}});var Co=O(mt=>{"use strict";Object.defineProperty(mt,"__esModule",{value:!0});mt.stepRatchet=pc;mt.replayRatchet=fc;mt.destroyKey=hc;var Io=Ve();function pc(e,t){if(t.length!==32)throw new Error(`ratchet token must be 32 bytes, got ${t.length}`);return{nextContentKey:(0,Io.ratchetAdvance)(e.contentKey,t),openCount:e.openCount+1}}function fc(e,t){let n=[e],r=e;for(let o of t)r=(0,Io.ratchetAdvance)(r,o),n.push(r);return n}function hc(e){e.fill(0)}});var nr=O(We=>{"use strict";Object.defineProperty(We,"__esModule",{value:!0});We.__coseInternals=void 0;We.verifyCoseSign1Es384=gc;We.decodeAttestationPayload=_c;var yc=A("@noble/curves/nist.js"),mc=A("@noble/hashes/sha2.js"),er=class{constructor(t){this.b=t,this.p=0}u8(){if(this.p>=this.b.length)throw new Error("cbor: truncated");return this.b[this.p++]}uN(t){let n=0;for(let r=0;r<t;r++)n=n*256+this.u8();return n}len(t){if(t<24)return t;if(t===24)return this.u8();if(t===25)return this.uN(2);if(t===26)return this.uN(4);if(t===27){let n=this.uN(4),r=this.uN(4);return n*4294967296+r}throw new Error(`cbor: unsupported additional info ${t}`)}read(){let t=this.u8(),n=t>>5,r=t&31;switch(n){case 0:return this.len(r);case 1:return-1-this.len(r);case 2:{let o=this.len(r),a=this.b.subarray(this.p,this.p+o);if(a.length!==o)throw new Error("cbor: bstr truncated");return this.p+=o,a.slice()}case 3:{let o=this.len(r),a=this.b.subarray(this.p,this.p+o);if(a.length!==o)throw new Error("cbor: tstr truncated");return this.p+=o,new TextDecoder("utf-8").decode(a)}case 4:{let o=this.len(r),a=[];for(let i=0;i<o;i++)a.push(this.read());return a}case 5:{let o=this.len(r),a=new Map;for(let i=0;i<o;i++){let s=this.read(),l=this.read();a.set(s,l)}return a}case 6:return this.len(r),this.read();case 7:if(r===20)return!1;if(r===21)return!0;if(r===22||r===23)return null;throw new Error(`cbor: unsupported simple/float ${r}`);default:throw new Error(`cbor: unknown major ${n}`)}}};function tr(e){return new er(e).read()}function Ht(e,t){let n=e<<5;return t<24?Uint8Array.of(n|t):t<=255?Uint8Array.of(n|24,t):t<=65535?Uint8Array.of(n|25,t>>8&255,t&255):Uint8Array.of(n|26,t>>>24&255,t>>16&255,t>>8&255,t&255)}function Vt(...e){let t=e.reduce((o,a)=>o+a.length,0),n=new Uint8Array(t),r=0;for(let o of e)n.set(o,r),r+=o.length;return n}function Ut(e){return Vt(Ht(2,e.length),e)}function Ro(e){let t=new TextEncoder().encode(e);return Vt(Ht(3,t.length),t)}function $o(e,t){return Vt(Ht(4,4),Ro("Signature1"),Ut(e),Ut(new Uint8Array(0)),Ut(t))}function gc(e,t){let n;try{n=tr(e)}catch(d){return{ok:!1,code:"malformed",reason:`cbor decode failed: ${d.message}`}}if(!Array.isArray(n)||n.length!==4)return{ok:!1,code:"bad_structure",reason:"COSE_Sign1 must be a 4-element array"};let[r,,o,a]=n;if(!(r instanceof Uint8Array))return{ok:!1,code:"bad_structure",reason:"protected header must be a byte string"};if(!(o instanceof Uint8Array)||o.length===0)return{ok:!1,code:"no_payload",reason:"detached/empty payload is not supported"};if(!(a instanceof Uint8Array))return{ok:!1,code:"bad_structure",reason:"signature must be a byte string"};if(a.length!==96)return{ok:!1,code:"bad_signature_len",reason:`expected 96-byte ES384 sig, got ${a.length}`};let i=$o(r,o),s=(0,mc.sha384)(i),l=!1;try{l=yc.p384.verify(a,s,t,{prehash:!1})}catch(d){return{ok:!1,code:"signature_invalid",reason:`verify threw: ${d.message}`}}return l?{ok:!0,payload:o}:{ok:!1,code:"signature_invalid",reason:"ECDSA P-384 verification failed"}}function _c(e){try{let t=tr(e);return t instanceof Map?t:null}catch{return null}}We.__coseInternals={sig1Structure:$o,encBstr:Ut,encText:Ro,encHead:Ht,concat:Vt,decodeCbor:tr}});var Bo=O(gt=>{"use strict";Object.defineProperty(gt,"__esModule",{value:!0});gt.parseAttestation=Sc;gt.verifyAttestation=vc;gt.fetchAttestation=wc;var bc=nr();function Sc(e){try{let t=new TextDecoder("utf-8").decode(e),n=JSON.parse(t);return n.vendor?n.module_id?!n.pcrs||typeof n.pcrs!="object"?{error:"missing pcrs"}:typeof n.timestamp!="number"?{error:"missing timestamp"}:typeof n.user_data_sha256!="string"?{error:"missing user_data_sha256"}:{vendor:n.vendor,module_id:n.module_id,pcrs:n.pcrs,timestamp:n.timestamp,user_data_sha256:n.user_data_sha256,raw:e}:{error:"missing module_id"}:{error:"missing vendor"}}catch(t){return{error:`parse failed: ${t.message}`}}}function vc(e,t){if(e.vendor!==t.vendor)return{ok:!1,code:"vendor_mismatch",reason:`vendor '${e.vendor}' \u2260 expected '${t.vendor}'`};if(e.module_id!==t.module_id)return{ok:!1,code:"module_id_mismatch",reason:`module_id mismatch (got '${e.module_id.slice(0,16)}\u2026')`};for(let[a,i]of Object.entries(t.pcrs))if(e.pcrs[a]!==i)return{ok:!1,code:"pcr_mismatch",reason:`PCR ${a}: got '${(e.pcrs[a]??"").slice(0,16)}\u2026', expected '${i.slice(0,16)}\u2026'`};if(e.user_data_sha256!==t.expected_user_data_sha256)return{ok:!1,code:"user_data_mismatch",reason:"attested user_data does not match presented key"};let n=Math.floor(Date.now()/1e3),r=t.maxAgeSeconds??600;if(e.timestamp>n+30)return{ok:!1,code:"in_future",reason:`attestation timestamp ${e.timestamp} > now+30s`};if(n-e.timestamp>r)return{ok:!1,code:"expired",reason:`attestation ${n-e.timestamp}s old (max ${r}s)`};let o=!1;if(t.cose){if(!t.trustedLeafPubKey)return{ok:!1,code:"signature_invalid",reason:"cose supplied without trustedLeafPubKey \u2014 cannot verify, refusing"};let a=(0,bc.verifyCoseSign1Es384)(t.cose,t.trustedLeafPubKey);if(!a.ok)return{ok:!1,code:"signature_invalid",reason:`cose: ${a.code}: ${a.reason}`};o=!0}return{ok:!0,vendor:e.vendor,module_id:e.module_id,signature_verified:o}}async function wc(e){let n=await(e.fetchImpl??fetch)(e.attestationUrl,{method:"GET"});if(!n.ok)throw new Error(`attestation fetch failed: ${n.status} ${n.statusText}`);return new Uint8Array(await n.arrayBuffer())}});var Mo=O(Je=>{"use strict";Object.defineProperty(Je,"__esModule",{value:!0});Je.splitSecret=Ac;Je.combineShares=Tc;Je.serializeShare=Oc;Je.deserializeShare=Nc;var Ne=null,Ie=null;function Ko(){if(Ne&&Ie)return;Ne=new Uint8Array(512),Ie=new Uint8Array(256);let e=1;for(let t=0;t<255;t++){Ne[t]=e,Ie[e]=t;let n=e<<1;n&256&&(n^=283),n^=e,e=n&255}for(let t=255;t<512;t++)Ne[t]=Ne[t-255]}function Gt(e,t){return e===0||t===0?0:(Ko(),Ne[Ie[e]+Ie[t]])}function Ec(e,t){if(e===0)return 0;if(t===0)throw new Error("division by zero in GF(2^8)");Ko();let n=Ie[e]-Ie[t];return Ne[n<0?n+255:n]}function jo(e,t){return e^t}function kc(e,t){let n=0;for(let r=e.length-1;r>=0;r--)n=jo(Gt(n,t),e[r]);return n}var xc=e=>crypto.getRandomValues(new Uint8Array(e));function Ac(e,t){if(t.k<2)throw new Error("threshold k must be \u2265 2");if(t.n<t.k)throw new Error(`total shares n (${t.n}) must be \u2265 threshold k (${t.k})`);if(t.n>255)throw new Error("total shares n must be \u2264 255 (limit of GF(2^8))");if(e.length===0)throw new Error("secret must be non-empty");let n=t.randomBytes??xc,r=[];for(let o=1;o<=t.n;o++)r.push({x:o,y:new Uint8Array(e.length)});for(let o=0;o<e.length;o++){let a=new Uint8Array(t.k);a[0]=e[o];let i=n(t.k-1);for(let s=1;s<t.k;s++)a[s]=i[s-1];for(let s=0;s<t.n;s++)r[s].y[o]=kc(a,r[s].x)}return r}function Tc(e){if(e.length<2)throw new Error("need at least 2 shares to reconstruct");let t=e[0].y.length;for(let o of e){if(o.y.length!==t)throw new Error("shares have inconsistent length");if(o.x===0)throw new Error("share x must not be 0")}let n=new Set;for(let o of e){if(n.has(o.x))throw new Error(`duplicate share x=${o.x}`);n.add(o.x)}let r=new Uint8Array(t);for(let o=0;o<t;o++){let a=0;for(let i=0;i<e.length;i++){let s=1,l=1;for(let u=0;u<e.length;u++)i!==u&&(s=Gt(s,e[u].x),l=Gt(l,e[i].x^e[u].x));let d=Ec(s,l);a=jo(a,Gt(e[i].y[o],d))}r[o]=a}return r}var Pc=e=>{if(typeof Buffer<"u")return Buffer.from(e).toString("base64");let t="";for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return btoa(t)},Dc=e=>{if(typeof Buffer<"u")return new Uint8Array(Buffer.from(e,"base64"));let t=atob(e),n=new Uint8Array(t.length);for(let r=0;r<t.length;r++)n[r]=t.charCodeAt(r);return n};function Oc(e){return{x:e.x,y_b64:Pc(e.y)}}function Nc(e){return{x:e.x,y:Dc(e.y_b64)}}});var Ho=O(Se=>{"use strict";Object.defineProperty(Se,"__esModule",{value:!0});Se.SegmentError=void 0;Se.sealSegments=Bc;Se.openSegments=Kc;Se.manifestDigest=jc;Se.buildCapability=Mc;var rr=A("@noble/hashes/sha2.js"),Ic="pq-hybrid-segments",Cc="AES-256-GCM",ze=e=>e,Fo=e=>{if(typeof Buffer<"u")return Buffer.from(e).toString("base64");let t="";for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return btoa(t)},Lo=e=>{if(typeof Buffer<"u")return new Uint8Array(Buffer.from(e,"base64"));let t=atob(e),n=new Uint8Array(t.length);for(let r=0;r<t.length;r++)n[r]=t.charCodeAt(r);return n},Uo=e=>{let t="";for(let n=0;n<e.length;n++)t+=e[n].toString(16).padStart(2,"0");return t};async function Rc(e,t,n){let r=await crypto.subtle.importKey("raw",ze(e),{name:"AES-GCM"},!1,["encrypt"]),o=await crypto.subtle.encrypt({name:"AES-GCM",iv:ze(t)},r,ze(n));return new Uint8Array(o)}async function $c(e,t,n){let r=await crypto.subtle.importKey("raw",ze(e),{name:"AES-GCM"},!1,["decrypt"]),o=await crypto.subtle.decrypt({name:"AES-GCM",iv:ze(t)},r,ze(n));return new Uint8Array(o)}var Ce=class extends Error{constructor(t,n){super(n),this.name="SegmentError",this.code=t}};Se.SegmentError=Ce;async function Bc(e){let t=new Set;for(let o of e){if(t.has(o.segment_id))throw new Ce("duplicate_segment_id",`segment_id '${o.segment_id}' appears twice`);t.add(o.segment_id)}let n=[],r=[];for(let o of e){let a=crypto.getRandomValues(new Uint8Array(32)),i=crypto.getRandomValues(new Uint8Array(12)),s=await Rc(a,i,o.plaintext),l=s.slice(0,s.length-16),d=Uo((0,rr.sha256)(l));n.push({segment_id:o.segment_id,key:a}),r.push({segment_id:o.segment_id,label:o.label,content_type:o.content_type,iv_b64:Fo(i),ciphertext_b64:Fo(s),ciphertext_sha256:d})}return{manifest:{profile:Ic,aead:Cc,segments:r},keys:n}}async function Kc(e,t){let n=new Map;for(let o of t.keys)n.set(o.segment_id,o.key);let r=[];for(let o of e.segments){if(!t.allowed_segment_ids.includes(o.segment_id))continue;let a=n.get(o.segment_id);if(!a)throw new Ce("key_missing",`capability lists ${o.segment_id} as allowed but holds no key for it`);let i=Lo(o.ciphertext_b64),s=i.slice(0,i.length-16);if(Uo((0,rr.sha256)(s))!==o.ciphertext_sha256)throw new Ce("integrity_mismatch",`segment ${o.segment_id}: ciphertext sha256 mismatch`);let d=Lo(o.iv_b64),u=await $c(a,d,i);r.push({segment_id:o.segment_id,label:o.label,content_type:o.content_type,plaintext:u})}return r}function jc(e){let t=e.segments.map(r=>({id:r.segment_id,h:r.ciphertext_sha256})),n=JSON.stringify({profile:e.profile,aead:e.aead,segments:t});return(0,rr.sha256)(new TextEncoder().encode(n))}function Mc(e,t,n){let r=new Set(t),o=n.filter(a=>r.has(a.segment_id));if(o.length!==t.length){let a=t.filter(i=>!o.find(s=>s.segment_id===i));throw new Ce("segment_not_found",`cannot build capability \u2014 no key for: ${a.join(", ")}`)}return{recipient_kid:e,allowed_segment_ids:t,keys:o}}});var qo=O(_t=>{"use strict";Object.defineProperty(_t,"__esModule",{value:!0});_t.computeWatermark=Go;_t.findLeakSource=Uc;_t.watermarkSvgOverlay=Hc;var Fc=A("@noble/hashes/hmac.js"),Lc=A("@noble/hashes/sha2.js");function Go(e){let t=[e.recipientId,e.lockboxId,String(e.openCount),String(e.iat)].join("|"),n=(0,Fc.hmac)(Lc.sha256,e.tenantSecret,new TextEncoder().encode(t)),r=Vo(n.slice(0,16)),o=Vo(n.slice(0,4)),a=new Date(e.iat*1e3).toISOString().slice(0,10),i=`${e.recipientId} \xB7 ${a} \xB7 ${o}`;return{short_hex:o,full_hex:r,display_label:i}}function Uc(e,t,n){let r=e.toLowerCase();for(let o of n){let a=Go({tenantSecret:t,...o});if(r===a.full_hex)return{matched:!0,candidate:o,matched_on:"full_hex"};if(r===a.short_hex)return{matched:!0,candidate:o,matched_on:"short_hex"}}return{matched:!1,reason:"no_candidate_matched"}}function Hc(e,t){let n=t?.width??800,r=t?.height??1e3,o=t?.opacity??.1,i=(s=>s.replace(/[<>&"]/g,l=>({"<":"<",">":">","&":"&",'"':"""})[l]))(e.display_label);return`<svg xmlns="http://www.w3.org/2000/svg" width="${n}" height="${r}" pointer-events="none">
|
|
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})">${i}</text>
|
|
11
|
+
<text x="${n/2}" y="${r*.5}" transform="rotate(-30 ${n/2} ${r*.5})">${i}</text>
|
|
12
|
+
<text x="${n/2}" y="${r*.8}" transform="rotate(-30 ${n/2} ${r*.8})">${i}</text>
|
|
13
|
+
</g>
|
|
14
|
+
<text x="${n-12}" y="${r-8}" font-family="monospace" font-size="10" fill="#000" opacity="${o*2}" text-anchor="end">${e.short_hex}</text>
|
|
15
|
+
</svg>`}function Vo(e){let t="";for(let n=0;n<e.length;n++)t+=e[n].toString(16).padStart(2,"0");return t}});var Qo=O(G=>{"use strict";Object.defineProperty(G,"__esModule",{value:!0});G.DRAND_LOE_MAINNET=G.TimeGateError=void 0;G.timeGateEncrypt=Vc;G.timeGateDecrypt=Gc;G.roundForTime=qc;G.timeForRound=Wc;G.drandTimeLockEncrypt=zc;G.drandTimeLockDecrypt=Xo;G.makeFakeDrandChain=Yc;G.fetchDrandRound=Zo;G.drandTimeLockOpen=Zc;var le=A("@noble/curves/bls12-381.js"),Jt=A("@noble/hashes/sha2.js"),ve=e=>e,Jo="NDC-v0.3-server-time-gate";async function Vc(e){let t=crypto.getRandomValues(new Uint8Array(12)),n=new TextEncoder().encode(`${Jo}|${e.notBeforeUnixSec}`),r=await crypto.subtle.importKey("raw",ve(e.serverWrapKey),{name:"AES-GCM"},!1,["encrypt"]),o=await crypto.subtle.encrypt({name:"AES-GCM",iv:ve(t),additionalData:ve(n)},r,ve(e.plaintext));return{variant:"server-attested",notBeforeUnixSec:e.notBeforeUnixSec,iv_b64:qt(t),ciphertext_b64:qt(new Uint8Array(o))}}var bt=class extends Error{constructor(t,n){super(n),this.name="TimeGateError",this.code=t}};G.TimeGateError=bt;async function Gc(e){if(e.currentUnixSec<e.ciphertext.notBeforeUnixSec)throw new bt("not_yet",`time-gate not yet open: now ${e.currentUnixSec} < notBefore ${e.ciphertext.notBeforeUnixSec}`);let t=new TextEncoder().encode(`${Jo}|${e.ciphertext.notBeforeUnixSec}`),n=await crypto.subtle.importKey("raw",ve(e.serverWrapKey),{name:"AES-GCM"},!1,["decrypt"]);try{let r=await crypto.subtle.decrypt({name:"AES-GCM",iv:ve(Wt(e.ciphertext.iv_b64)),additionalData:ve(t)},n,ve(Wt(e.ciphertext.ciphertext_b64)));return new Uint8Array(r)}catch{throw new bt("tamper_detected","AES-GCM authentication tag failed \u2014 ciphertext or AAD tampered")}}G.DRAND_LOE_MAINNET={publicKeyHex:"868f005eb8e6e4ca0a47c8a77ceaa5309a47978a7c71bc5cce96366b5d7a569937c529eeda66c7293784a9402801af31",chainHashHex:"8990e7a9aaed2ffed73dbd7092123d6f289930540d7651336225dc172e51b2ce",genesisUnixSec:1595431050,periodSec:30,hashDst:"BLS_SIG_BLS12381G2_XMD:SHA-256_SSWU_RO_NUL_"};function qc(e,t){return e<=t.genesisUnixSec?1:Math.ceil((e-t.genesisUnixSec)/t.periodSec)}function Wc(e,t){return t.genesisUnixSec+e*t.periodSec}function zo(e){let t=new Uint8Array(8),n=e;for(let r=7;r>=0;r--)t[r]=n&255,n=Math.floor(n/256);return(0,Jt.sha256)(t)}function Yo(e){let t=new Uint8Array(576),n=0;for(let r of[e.c0,e.c1])for(let o of[r.c0,r.c1,r.c2])for(let a of[o.c0,o.c1])Jc(a,t,n,48),n+=48;return t}function Jc(e,t,n,r){let o=e,a=BigInt(255),i=BigInt(8);for(let s=r-1;s>=0;s--)t[n+s]=Number(o&a),o>>=i}function zc(e,t,n,r){if(e.length!==32)throw new Error(`drand-IBE expects a 32-byte content key, got ${e.length}`);let o=le.bls12_381.G1.Point,a=le.bls12_381.fields.Fr,i=o.fromBytes(n),s;do s=Qc(crypto.getRandomValues(new Uint8Array(32)))%a.ORDER;while(s===BigInt(0));let l=o.BASE.multiply(s),d=le.bls12_381.longSignatures.hash(zo(t),r.hashDst),u=i.multiply(s),p=le.bls12_381.pairing(u,d,!0),h=(0,Jt.sha256)(Yo(p)),m=new Uint8Array(32);for(let v=0;v<32;v++)m[v]=e[v]^h[v];return{variant:"drand-ibe",chainHashHex:r.chainHashHex,round:t,u_b64:qt(l.toBytes()),v_b64:qt(m)}}function Xo(e){if(e.ciphertext.variant!=="drand-ibe")throw new Error("not a drand-IBE ciphertext");if(e.ciphertext.chainHashHex!==e.chain.chainHashHex)throw new Error("chain hash mismatch \u2014 ciphertext sealed to a different drand chain");let n=le.bls12_381.G1.Point.fromBytes(Wt(e.ciphertext.u_b64)),r=le.bls12_381.longSignatures.Signature.fromBytes(e.roundSignature),o=le.bls12_381.pairing(n,r,!0),a=(0,Jt.sha256)(Yo(o)),i=Wt(e.ciphertext.v_b64);if(i.length!==32)throw new Error("drand-IBE V must be 32 bytes");let s=new Uint8Array(32);for(let l=0;l<32;l++)s[l]=i[l]^a[l];return s}function Yc(e){let t;if(e&&e.length===48)t=e;else{t=new Uint8Array(48);let a=e??crypto.getRandomValues(new Uint8Array(48));t.set(a.slice(0,48),0)}let{secretKey:n,publicKey:r}=le.bls12_381.longSignatures.keygen(t),o={publicKeyHex:Wo(r.toBytes()),chainHashHex:Wo((0,Jt.sha256)(r.toBytes())),genesisUnixSec:17e8,periodSec:30,hashDst:"BLS_SIG_BLS12381G2_XMD:SHA-256_SSWU_RO_NUL_"};return{config:o,publicKey:r.toBytes(),signRound(a){let i=le.bls12_381.longSignatures.hash(zo(a),o.hashDst);return le.bls12_381.longSignatures.sign(i,n).toBytes()}}}function Wo(e){let t="";for(let n=0;n<e.length;n++)t+=e[n].toString(16).padStart(2,"0");return t}function Xc(e){if(e.length%2!==0)throw new Error("hex must have even length");let t=new Uint8Array(e.length/2);for(let n=0;n<t.length;n++)t[n]=parseInt(e.substr(n*2,2),16);return t}async function Zo(e,t,n={}){let r=n.fetchImpl??fetch,o=n.timeoutMs??8e3,a=`${t.replace(/\/$/,"")}/public/${e}`,i,s;typeof AbortController<"u"&&(i=new AbortController,s=setTimeout(()=>i.abort(),o));let l;try{l=await r(a,{signal:i?.signal})}finally{s&&clearTimeout(s)}if(!l.ok)throw new Error(`drand fetch failed: ${a} \u2192 HTTP ${l.status}`);let d=await l.json();if(typeof d.round!="number"||typeof d.signature!="string"||typeof d.randomness!="string")throw new Error(`drand response malformed at ${a}`);let u=Xc(d.signature);if(u.length!==96)throw new Error(`drand signature wrong length: expected 96 bytes (compressed G2), got ${u.length}`);return{round:d.round,randomness_hex:d.randomness,signature_bytes:u,previous_signature_hex:d.previous_signature}}async function Zc(e,t,n,r={}){let o=await Zo(e.round,t,r);return Xo({ciphertext:e,roundSignature:o.signature_bytes,chain:n})}function qt(e){if(typeof Buffer<"u")return Buffer.from(e).toString("base64");let t="";for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return btoa(t)}function Wt(e){if(typeof Buffer<"u")return new Uint8Array(Buffer.from(e,"base64"));let t=atob(e),n=new Uint8Array(t.length);for(let r=0;r<t.length;r++)n[r]=t.charCodeAt(r);return n}function Qc(e){let t=BigInt(0),n=BigInt(8);for(let r=0;r<e.length;r++)t=t<<n|BigInt(e[r]);return t}});var oa=O(Q=>{"use strict";Object.defineProperty(Q,"__esModule",{value:!0});Q.GENESIS_PREV_HASH=void 0;Q.receiptHash=ar;Q.issueReceipt=ir;Q.verifyReceipt=ra;Q.auditChain=nl;Q.issueGenesisReceipt=rl;Q.appendReceipt=ol;var el=A("@noble/hashes/sha2.js"),or=Mt(),na=Ve();Q.GENESIS_PREV_HASH="0".repeat(64);var ea=e=>{if(typeof Buffer<"u")return Buffer.from(e).toString("base64");let t="";for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return btoa(t)},ta=e=>{if(typeof Buffer<"u")return new Uint8Array(Buffer.from(e,"base64"));let t=atob(e),n=new Uint8Array(t.length);for(let r=0;r<t.length;r++)n[r]=t.charCodeAt(r);return n},tl=e=>{let t="";for(let n=0;n<e.length;n++)t+=e[n].toString(16).padStart(2,"0");return t};function ar(e){return tl((0,el.sha256)(new TextEncoder().encode((0,or.canonicalJson)(e))))}function ir(e){let t={event_type:e.event_type,sequence:e.sequence,iat:e.iat??new Date().toISOString(),lockbox_id:e.lockbox_id,prev_hash:e.prev_hash,payload:e.payload},n=new TextEncoder().encode((0,or.canonicalJson)(t)),r=(0,na.hybridSign)(e.signing_key.secretKey,n);return{body:t,sig:{signer_kid:e.signer_kid,ed25519_b64:ea(r.ed25519),ml_dsa_65_b64:ea(r.mlDsa)}}}function ra(e,t){let n=new TextEncoder().encode((0,or.canonicalJson)(e.body)),r={ed25519:ta(e.sig.ed25519_b64),mlDsa:ta(e.sig.ml_dsa_65_b64)};return(0,na.hybridVerify)(t,n,r)}function nl(e,t,n=1){if(e.length===0)return{ok:!0,receipts_checked:0};let r=n,o=n===1?Q.GENESIS_PREV_HASH:null;for(let a of e){if(a.body.sequence!==r)return{ok:!1,code:a.body.sequence<r?"duplicate_sequence":"out_of_order",at_sequence:a.body.sequence,reason:`expected sequence ${r}, got ${a.body.sequence}`};if(o!==null&&a.body.prev_hash!==o)return{ok:!1,code:r===1?"missing_genesis":"broken_prev_hash",at_sequence:a.body.sequence,reason:`prev_hash mismatch: expected ${o.slice(0,16)}\u2026, got ${a.body.prev_hash.slice(0,16)}\u2026`};if(!ra(a,t))return{ok:!1,code:"bad_signature",at_sequence:a.body.sequence,reason:"hybrid signature does not verify"};o=ar(a.body),r+=1}return{ok:!0,receipts_checked:e.length}}function rl(e){return ir({event_type:e.initial_event,lockbox_id:e.lockbox_id,prev_hash:Q.GENESIS_PREV_HASH,sequence:1,payload:e.initial_payload,signer_kid:e.signer_kid,signing_key:e.signing_key,iat:e.iat})}function ol(e,t){return ir({...t,prev_hash:ar(e.body),sequence:e.body.sequence+1})}});var ia=O(zt=>{"use strict";Object.defineProperty(zt,"__esModule",{value:!0});zt.recommend=dl;zt.summarise=ul;var al={healthcare:{mode:"mode-4h",ttlSeconds:3600,forensicWatermark:!0,teeAttestation:!0,rationale:"HIPAA \xB7 BAA \xB7 per-recipient attribution required"},insurance:{mode:"mode-4",ttlSeconds:28800,forensicWatermark:!0,teeAttestation:!1,rationale:"Adjusters need offline access during field visits"},bank:{mode:"mode-4h",ttlSeconds:3600,forensicWatermark:!0,teeAttestation:!1,rationale:"SOX \xB7 per-open audit \xB7 forward secrecy on signed mandates"},legal:{mode:"mode-4p",ttlSeconds:86400,forensicWatermark:!0,teeAttestation:!1,rationale:"Client privilege \xB7 approval-quorum patterns common"},government:{mode:"mode-4h",ttlSeconds:3600,forensicWatermark:!0,teeAttestation:!0,rationale:"Classified \xB7 per-open attestation \xB7 k-of-N release"},media:{mode:"mode-4p",ttlSeconds:604800,forensicWatermark:!0,teeAttestation:!1,rationale:"Source protection \xB7 leak attribution \xB7 light verification UX"},hr:{mode:"mode-4",ttlSeconds:86400,forensicWatermark:!0,teeAttestation:!1,rationale:"Performance reviews \xB7 separation packages \xB7 low compliance"},smb:{mode:"mode-4",ttlSeconds:604800,forensicWatermark:!1,teeAttestation:!1,rationale:"Cost-sensitive \xB7 low compliance overhead"}},il={"medical-phi":{minMode:"mode-4h",maxTtlSeconds:3600,watermarkRequired:!0,selectiveDisclosure:!0,thresholdSuggested:!1,teeRequired:!0},"financial-statements":{minMode:"mode-4",maxTtlSeconds:28800,watermarkRequired:!0,selectiveDisclosure:!0,thresholdSuggested:!0,teeRequired:!1},"identity-documents":{minMode:"mode-4h",maxTtlSeconds:3600,watermarkRequired:!0,selectiveDisclosure:!0,thresholdSuggested:!1,teeRequired:!0},"legal-contracts":{minMode:"mode-4p",maxTtlSeconds:86400,watermarkRequired:!0,selectiveDisclosure:!0,thresholdSuggested:!0,teeRequired:!1},"board-materials":{minMode:"mode-4p",maxTtlSeconds:86400,watermarkRequired:!0,selectiveDisclosure:!0,thresholdSuggested:!0,teeRequired:!1},"source-code":{minMode:"mode-4h",maxTtlSeconds:3600,watermarkRequired:!0,selectiveDisclosure:!0,thresholdSuggested:!1,teeRequired:!0},marketing:{minMode:"mode-4",maxTtlSeconds:604800,watermarkRequired:!1,selectiveDisclosure:!1,thresholdSuggested:!1,teeRequired:!1},"internal-memo":{minMode:"mode-4",maxTtlSeconds:86400,watermarkRequired:!1,selectiveDisclosure:!1,thresholdSuggested:!1,teeRequired:!1},"live-ops-data":{minMode:"mode-4",maxTtlSeconds:86400,watermarkRequired:!1,selectiveDisclosure:!1,thresholdSuggested:!1,teeRequired:!1}},sl={email:{deliveryMode:"attachment",adapters:["gmail","outlook","smtp"],notes:[]},chat:{deliveryMode:"link",adapters:["whatsapp","telegram","slack","teams"],notes:["Send the ndc:// link only; file bytes never traverse the chat provider"]},"cloud-share":{deliveryMode:"link",adapters:["drive","sharepoint","dropbox","box"],notes:[]},sftp:{deliveryMode:"attachment",adapters:["sftp","ftps"],notes:["Legacy partners often require this"]},sms:{deliveryMode:"link",adapters:["sms-short-link"],notes:["Link only; SMS cannot carry binary"]},voice:{deliveryMode:"link",adapters:["voice-readback"],notes:["Voice carries the unlock factor, not the content"]},"web-portal":{deliveryMode:"link",adapters:["web-portal-pickup","embed-iframe"],notes:[]},"qr-physical":{deliveryMode:"in-person",adapters:["qr-code","usb-handoff","airdrop"],notes:["Recipient must scan / plug in physically"]},webhook:{deliveryMode:"attachment",adapters:["webhook-push"],notes:["B2B server-to-server only"]}},cl=[{channel:"chat",fileClass:"medical-phi",note:"PHI over chat \u2192 link only; never attach the bytes"},{channel:"chat",fileClass:"identity-documents",note:"ID documents over chat \u2192 link only"},{channel:"chat",fileClass:"legal-contracts",note:"Legal contracts over chat are discouraged; use email/portal"},{channel:"chat",fileClass:"board-materials",note:"Board materials over chat are discouraged; use email/portal"},{channel:"chat",fileClass:"source-code",note:"Source code over chat is discouraged; use cloud-share/portal"},{channel:"cloud-share",fileClass:"identity-documents",note:"ID documents on cloud share discouraged; prefer email or portal"},{channel:"sms",fileClass:"medical-phi",note:"PHI over SMS is not compliant; reroute to web-portal"},{channel:"voice",fileClass:"medical-phi",note:"Voice only carries the unlock; the bytes must travel another channel"}],aa={"mode-4":1,"mode-4p":2,"mode-4h":3,"mode-6":4};function ll(e,t){return aa[e]>=aa[t]?e:t}function dl(e){let t=al[e.orgType],n=il[e.fileClass],r=sl[e.channel],o=ll(t.mode,n.minMode);e.recipientLacksPasskey&&o==="mode-4h"&&(o="mode-4p");let a=Math.min(t.ttlSeconds,n.maxTtlSeconds),i={forensicWatermark:t.forensicWatermark||n.watermarkRequired,selectiveDisclosureSegments:n.selectiveDisclosure||!!e.perRecipientPolicy,thresholdKofN:e.multipleApproversRequired??null,teeAttestation:t.teeAttestation||n.teeRequired,perOpenRatchet:o==="mode-4h"||o==="mode-4p"||o==="mode-6",dpopRequired:o!=="mode-4",timelockDrand:!!e.timeLockUnixSec&&!!e.timeLockDecentralized,timelockServerGate:!!e.timeLockUnixSec&&!e.timeLockDecentralized},s={...r,adapterCandidates:[...r.adapters]},l=[...s.notes],d=cl.find(u=>u.channel===e.channel&&u.fileClass===e.fileClass);return d&&(l.unshift(`\u26A0 ${d.note}`),s.deliveryMode==="attachment"&&(s.deliveryMode="link")),e.fileClass==="live-ops-data"&&e.channel==="email"&&l.push("Live ops data over email is non-standard; consider webhook-push or web-portal."),{sensitivityMode:o,cacheTtlSeconds:a,features:i,delivery:{deliveryMode:s.deliveryMode,adapterCandidates:s.adapterCandidates},notes:l}}function ul(e){let t=[e.sensitivityMode,`TTL ${e.cacheTtlSeconds}s`];return e.features.forensicWatermark&&t.push("watermark"),e.features.selectiveDisclosureSegments&&t.push("segments"),e.features.thresholdKofN&&t.push(`threshold ${e.features.thresholdKofN.k}-of-${e.features.thresholdKofN.n}`),e.features.teeAttestation&&t.push("TEE"),e.features.perOpenRatchet&&t.push("ratchet"),e.features.dpopRequired&&t.push("DPoP"),e.features.timelockDrand?t.push("drand-tlock"):e.features.timelockServerGate&&t.push("server-timegate"),t.push(`via ${e.delivery.deliveryMode} (${e.delivery.adapterCandidates.join("/")})`),t.join(" \xB7 ")}});var ca=O(Ye=>{"use strict";Object.defineProperty(Ye,"__esModule",{value:!0});Ye.recommendationToMandate=ml;Ye.v3SealReceiptPayload=gl;Ye.v3OpenReceiptPayload=_l;Ye.showcaseChips=bl;function pl(e){switch(e){case"mode-4":return"name_email";case"mode-4p":return"name_email";case"mode-4h":return"hardware_attest";case"mode-6":return"name_email_phone"}}function fl(e){return e.features.dpopRequired?"device_mfa":e.sensitivityMode==="mode-4h"?"first_device":e.sensitivityMode==="mode-4"?"any":"first_device"}function hl(e){return e.delivery.deliveryMode==="attachment"?"file":e.delivery.deliveryMode==="link"?"link":"view_only"}function sa(e){let t=e.delivery.adapterCandidates;return t.some(n=>n==="outlook"||n==="sharepoint"||n==="teams")?"m365":t.some(n=>n==="webhook-push"||n==="web-portal-pickup"||n==="embed-iframe")?"in_app":"capsule"}function yl(e){let t=sa(e);return t==="m365"?"m365_only":t==="in_app"?"in_app":"any"}function ml(e){let{recommendation:t,source:n}=e,r=t.sensitivityMode==="mode-6",o=n.timeLockUnixSec?new Date(n.timeLockUnixSec*1e3).toISOString():null;return{time:{ttl_seconds:t.cacheTtlSeconds,burn_after_first_read:r,unlock_at:o,max_opens:r?1:null},identity:{capture:pl(t.sensitivityMode),claim_required:t.sensitivityMode!=="mode-4",allow_magic_link:t.sensitivityMode==="mode-4",allowed_emails:null},device:{binding:fl(t),listed_fingerprints:null},channel:{delivery:hl(t),route:sa(t),channel_constraint:yl(t)},burn:{crypto_shred_on_burn:!0,mdm_wipe_webhook:!1,undo_window_s:0,dual_control:!!t.features.thresholdKofN},encrypt:{mode:"hpke",vault_mirror:t.features.teeAttestation,scoped_key_release:!0},proof:{signing:"ed25519",anchor:t.features.teeAttestation?"rekor":"none",c2pa_in_file:!1,ndc_seal:!0},watermark:{visible:t.features.forensicWatermark,forensic:t.features.forensicWatermark,content:t.features.forensicWatermark?"recipient_id":null,custom_text:null,forensics_lookup:t.features.forensicWatermark},ndc_v3_extensions:{profile:"pq-hybrid",suite:{kem:"X25519+ML-KEM-768",sig:"Ed25519+ML-DSA-65",aead:"AES-256-GCM",kdf:"HKDF-SHA-256"},dpop_required:t.features.dpopRequired,ratchet_enabled:t.features.perOpenRatchet,tee_attestation_required:t.features.teeAttestation,threshold_k_of_n:t.features.thresholdKofN,segments_enabled:t.features.selectiveDisclosureSegments,timelock_drand:t.features.timelockDrand,timelock_server_gate:t.features.timelockServerGate,timelock_unix_sec:n.timeLockUnixSec??null}}}function gl(e){return{event_kind:"ndc_v3_sealed",lockbox_id:e.lockbox_id,ciphertext_sha256:e.ciphertext_sha256,recipient_kid:e.recipient_kid,signer_kid:e.signer_kid,mandate:e.mandate,bytes_sealed:e.bytes_sealed,issued_at:e.issued_at??new Date().toISOString()}}function _l(e){return{event_kind:"ndc_v3_opened",lockbox_id:e.lockbox_id,ratchet_sequence:e.ratchet_sequence,dpop_jkt:e.dpop_jkt,ip_hash:e.ip_hash,opened_at:e.opened_at??new Date().toISOString()}}function bl(e){let t=[],n=e.ndc_v3_extensions;return t.push("PQ-hybrid"),n.dpop_required&&t.push("DPoP"),n.ratchet_enabled&&t.push("per-open ratchet"),e.watermark.forensic&&t.push("forensic watermark"),n.segments_enabled&&t.push("selective disclosure"),n.threshold_k_of_n&&t.push(`${n.threshold_k_of_n.k}-of-${n.threshold_k_of_n.n} quorum`),n.tee_attestation_required&&t.push("TEE attest"),n.timelock_drand?t.push("drand time-lock"):n.timelock_server_gate&&t.push("server time-gate"),e.time.burn_after_first_read&&t.push("burn-after-read"),t}});var fa=O(de=>{"use strict";Object.defineProperty(de,"__esModule",{value:!0});de.encodeFragment=pa;de.decodeFragment=Sl;de.extractProofToken=vl;de.encodeProofToken=wl;de.decodeShareCredential=El;de.sealBytesForPublicShare=Al;de.openPublicShare=Tl;de.wrapFragmentForShortLink=Pl;var la=Ve(),da=Mt();function we(e){let t="";for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return btoa(t)}function St(e){let t=atob(e),n=new Uint8Array(t.length);for(let r=0;r<t.length;r++)n[r]=t.charCodeAt(r);return n}function ua(e){return we(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function pa(e){return encodeURIComponent(JSON.stringify(e))}function Sl(e){let t=JSON.parse(decodeURIComponent(e));if(t.v!==3)throw new Error(`fragment version unsupported: ${t.v}`);return t}function vl(e){return{v:3,kind:"proof",n:e.n,t:e.t,spe:e.spe,spm:e.spm}}function wl(e){return encodeURIComponent(JSON.stringify(e))}function El(e){let t=e.trim(),n=t.indexOf("#"),r=n>=0?t.slice(n+1):t,o;try{o=JSON.parse(decodeURIComponent(r))}catch(a){throw new Error(`credential parse failed: ${a.message??"invalid_json"}`)}if(o.v!==3)throw new Error(`credential version unsupported: ${String(o.v)}`);return o.kind==="proof"?{kind:"proof",value:o}:{kind:"fragment",value:o}}function kl(){let e=new Uint8Array(16);crypto.getRandomValues(e);let t="";for(let n=0;n<e.length;n++)t+=e[n].toString(16).padStart(2,"0");return t}function xl(){let e=new Uint8Array(32);return crypto.getRandomValues(e),ua(e)}async function Al(e){let t=e.bytes,n={name:e.filename,type:e.contentType},r=(0,la.generateHybridKemKeypair)(),o=(0,la.generateHybridSigKeypair)(),a=kl(),i=xl(),s=await(0,da.sealHybrid)({plaintext:t,recipientPublicKey:r.publicKey,recipientKid:`ephemeral-${a}`,signerKeypair:o,signerKid:`lock-${a}`,meta:{lockbox_id:a,server:e.server,bearer:i,original_filename:n.name,original_content_type:n.type||"application/octet-stream",cache_ttl_seconds:e.ttlSeconds,dpop_required:!1,tee_attestation_url:null,ratchet_state:null}}),l=pa({v:3,n:n.name,t:n.type||"application/octet-stream",rsx:we(r.secretKey.x25519),rsm:we(r.secretKey.mlKem),rpx:we(r.publicKey.x25519),spe:we(o.publicKey.ed25519),spm:we(o.publicKey.mlDsa)});return{container:s.container,fragment:l,lockboxId:a}}async function Tl(e){let t={x25519:St(e.fragment.rsx),mlKem:St(e.fragment.rsm)},n=St(e.fragment.rpx),r={ed25519:St(e.fragment.spe),mlDsa:St(e.fragment.spm)},{plaintext:o,header:a}=await(0,da.openHybrid)({container:e.container,recipientSecretKey:t,recipientPublicX25519:n,signerPublicKey:r});return{plaintext:o,filename:a.original_filename||e.fragment.n,contentType:a.original_content_type||e.fragment.t,signerKid:a.sig.signer_kid,issuedAt:a.issued_at,ciphertextSha256:a.ciphertext_sha256}}async function Pl(e){let t=crypto.getRandomValues(new Uint8Array(32)),n=crypto.getRandomValues(new Uint8Array(12)),r=new TextEncoder().encode(e),o=new ArrayBuffer(32);new Uint8Array(o).set(t);let a=new ArrayBuffer(12);new Uint8Array(a).set(n);let i=new ArrayBuffer(r.byteLength);new Uint8Array(i).set(r);let s=await crypto.subtle.importKey("raw",o,{name:"AES-GCM"},!1,["encrypt"]),l=new Uint8Array(await crypto.subtle.encrypt({name:"AES-GCM",iv:a},s,i));return{wrapKeyB64Url:ua(t),wrappedFragmentB64:we(l),wrapIvB64:we(n)}}});var ga=O(c=>{"use strict";var Dl=c&&c.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(c,"__esModule",{value:!0});c.PVE_SIGNED_LEN=c.RCPT_VERSION=c.PVE_VERSION=c.RCPT_MAGIC=c.PVE_MAGIC=c.verifyDpop=c.publicJwkFromBytes=c.jwkThumbprint=c.createDpop=c.verifyContainerHeader=c.signContainerHeader=c.sealHybrid=c.openHybrid=c.headerSigningBytes=c.encodeContainerV3=c.decodeContainerV3=c.ContainerV3Error=c.CONTAINER_HEADER_MAX_BYTES=c.CONTAINER_FIXED_PREFIX_BYTES=c.CONTAINER_MAGIC=c.canonicalJson=c.NDC_V03_RATCHET_DOMAIN=c.NDC_V03_CONTENT_KEY_DOMAIN=c.NDC_V03_KEM_DOMAIN=c.NDC_WIRE_V03=c.NDC_WIRE_V1=c.PQ_SIZES=c.PQ_SUITE=c.ratchetAdvance=c.deriveContentKey=c.mlDsa65VerifyDetached=c.mlDsa65SignDetached=c.generateMlDsa65Keypair=c.hybridVerify=c.hybridSign=c.hybridKemDecapsulate=c.hybridKemEncapsulate=c.generateHybridSigKeypair=c.deriveHybridKemKeypairFromSeed=c.generateHybridKemKeypair=c.ALGORITHMS=c.CRYPTO_VERSION=c.NoDataSDK=c.NoDataForms=c.NoDataSystems=c.NoDataWebhook=c.NoDataEmail=c.verifyProofOfWork=c.solveProofOfWork=c.NoDataCrypto=void 0;c.auditChain=c.appendReceipt=c.timeGateEncrypt=c.timeGateDecrypt=c.timeForRound=c.TimeGateError=c.roundForTime=c.makeFakeDrandChain=c.fetchDrandRound=c.drandTimeLockOpen=c.drandTimeLockEncrypt=c.drandTimeLockDecrypt=c.DRAND_LOE_MAINNET=c.watermarkSvgOverlay=c.findLeakSource=c.computeWatermark=c.SegmentError=c.sealSegments=c.openSegments=c.manifestDigest=c.buildCapability=c.splitSecret=c.serializeShare=c.deserializeShare=c.combineShares=c.decodeAttestationPayload=c.verifyCoseSign1Es384=c.verifyAttestation=c.parseAttestation=c.fetchAttestation=c.stepRatchet=c.replayRatchet=c.destroyKey=c.verifyReceiptDelta=c.parseReceiptDelta=c.signReceiptDelta=c.encodeReceiptDeltaSignedBytes=c.verifyPve=c.pveHash=c.parsePve=c.signPve=c.encodePveSignedBytes=c.originJktForPublicKey=c.uuidFromDeltaId=c.deltaIdFromUuid=c.ABSORB_STATUS=c.DELTA_KIND=c.RCPT_TOTAL_LEN=c.RCPT_SIGNED_LEN=c.PVE_TOTAL_LEN=void 0;c.wrapFragmentForShortLink=c.openPublicShare=c.sealBytesForPublicShare=c.decodeShareCredential=c.encodeProofToken=c.extractProofToken=c.decodeFragment=c.encodeFragment=c.v3SealReceiptPayload=c.v3OpenReceiptPayload=c.showcaseChips=c.recommendationToMandate=c.summarise=c.recommend=c.verifyReceipt=c.receiptHash=c.issueReceipt=c.issueGenesisReceipt=c.GENESIS_PREV_HASH=void 0;var Ol=Pe();Object.defineProperty(c,"NoDataCrypto",{enumerable:!0,get:function(){return Dl(Ol).default}});var ha=so();Object.defineProperty(c,"solveProofOfWork",{enumerable:!0,get:function(){return ha.solveProofOfWork}});Object.defineProperty(c,"verifyProofOfWork",{enumerable:!0,get:function(){return ha.verifyProofOfWork}});var vt=lo();Object.defineProperty(c,"NoDataEmail",{enumerable:!0,get:function(){return vt.NoDataEmail}});Object.defineProperty(c,"NoDataWebhook",{enumerable:!0,get:function(){return vt.NoDataWebhook}});Object.defineProperty(c,"NoDataSystems",{enumerable:!0,get:function(){return vt.NoDataSystems}});Object.defineProperty(c,"NoDataForms",{enumerable:!0,get:function(){return vt.NoDataForms}});Object.defineProperty(c,"NoDataSDK",{enumerable:!0,get:function(){return vt.NoDataSDK}});c.CRYPTO_VERSION="0.2.0";c.ALGORITHMS={ENCRYPTION:"AES-256-GCM",KEY_EXCHANGE:"RSA-OAEP-4096",KEY_DERIVATION:"PBKDF2-SHA256-310K",SIGNING:"Ed25519",HASHING:"SHA-256",PROOF_OF_WORK:"SHA-256-NONCE"};var B=Ve();Object.defineProperty(c,"generateHybridKemKeypair",{enumerable:!0,get:function(){return B.generateHybridKemKeypair}});Object.defineProperty(c,"deriveHybridKemKeypairFromSeed",{enumerable:!0,get:function(){return B.deriveHybridKemKeypairFromSeed}});Object.defineProperty(c,"generateHybridSigKeypair",{enumerable:!0,get:function(){return B.generateHybridSigKeypair}});Object.defineProperty(c,"hybridKemEncapsulate",{enumerable:!0,get:function(){return B.hybridKemEncapsulate}});Object.defineProperty(c,"hybridKemDecapsulate",{enumerable:!0,get:function(){return B.hybridKemDecapsulate}});Object.defineProperty(c,"hybridSign",{enumerable:!0,get:function(){return B.hybridSign}});Object.defineProperty(c,"hybridVerify",{enumerable:!0,get:function(){return B.hybridVerify}});Object.defineProperty(c,"generateMlDsa65Keypair",{enumerable:!0,get:function(){return B.generateMlDsa65Keypair}});Object.defineProperty(c,"mlDsa65SignDetached",{enumerable:!0,get:function(){return B.mlDsa65SignDetached}});Object.defineProperty(c,"mlDsa65VerifyDetached",{enumerable:!0,get:function(){return B.mlDsa65VerifyDetached}});Object.defineProperty(c,"deriveContentKey",{enumerable:!0,get:function(){return B.deriveContentKey}});Object.defineProperty(c,"ratchetAdvance",{enumerable:!0,get:function(){return B.ratchetAdvance}});Object.defineProperty(c,"PQ_SUITE",{enumerable:!0,get:function(){return B.PQ_SUITE}});Object.defineProperty(c,"PQ_SIZES",{enumerable:!0,get:function(){return B.PQ_SIZES}});Object.defineProperty(c,"NDC_WIRE_V1",{enumerable:!0,get:function(){return B.NDC_WIRE_V1}});Object.defineProperty(c,"NDC_WIRE_V03",{enumerable:!0,get:function(){return B.NDC_WIRE_V03}});Object.defineProperty(c,"NDC_V03_KEM_DOMAIN",{enumerable:!0,get:function(){return B.NDC_V03_KEM_DOMAIN}});Object.defineProperty(c,"NDC_V03_CONTENT_KEY_DOMAIN",{enumerable:!0,get:function(){return B.NDC_V03_CONTENT_KEY_DOMAIN}});Object.defineProperty(c,"NDC_V03_RATCHET_DOMAIN",{enumerable:!0,get:function(){return B.NDC_V03_RATCHET_DOMAIN}});var ee=Mt();Object.defineProperty(c,"canonicalJson",{enumerable:!0,get:function(){return ee.canonicalJson}});Object.defineProperty(c,"CONTAINER_MAGIC",{enumerable:!0,get:function(){return ee.CONTAINER_MAGIC}});Object.defineProperty(c,"CONTAINER_FIXED_PREFIX_BYTES",{enumerable:!0,get:function(){return ee.CONTAINER_FIXED_PREFIX_BYTES}});Object.defineProperty(c,"CONTAINER_HEADER_MAX_BYTES",{enumerable:!0,get:function(){return ee.CONTAINER_HEADER_MAX_BYTES}});Object.defineProperty(c,"ContainerV3Error",{enumerable:!0,get:function(){return ee.ContainerV3Error}});Object.defineProperty(c,"decodeContainerV3",{enumerable:!0,get:function(){return ee.decodeContainerV3}});Object.defineProperty(c,"encodeContainerV3",{enumerable:!0,get:function(){return ee.encodeContainerV3}});Object.defineProperty(c,"headerSigningBytes",{enumerable:!0,get:function(){return ee.headerSigningBytes}});Object.defineProperty(c,"openHybrid",{enumerable:!0,get:function(){return ee.openHybrid}});Object.defineProperty(c,"sealHybrid",{enumerable:!0,get:function(){return ee.sealHybrid}});Object.defineProperty(c,"signContainerHeader",{enumerable:!0,get:function(){return ee.signContainerHeader}});Object.defineProperty(c,"verifyContainerHeader",{enumerable:!0,get:function(){return ee.verifyContainerHeader}});var Yt=Yn();Object.defineProperty(c,"createDpop",{enumerable:!0,get:function(){return Yt.createDpop}});Object.defineProperty(c,"jwkThumbprint",{enumerable:!0,get:function(){return Yt.jwkThumbprint}});Object.defineProperty(c,"publicJwkFromBytes",{enumerable:!0,get:function(){return Yt.publicJwkFromBytes}});Object.defineProperty(c,"verifyDpop",{enumerable:!0,get:function(){return Yt.verifyDpop}});var R=No();Object.defineProperty(c,"PVE_MAGIC",{enumerable:!0,get:function(){return R.PVE_MAGIC}});Object.defineProperty(c,"RCPT_MAGIC",{enumerable:!0,get:function(){return R.RCPT_MAGIC}});Object.defineProperty(c,"PVE_VERSION",{enumerable:!0,get:function(){return R.PVE_VERSION}});Object.defineProperty(c,"RCPT_VERSION",{enumerable:!0,get:function(){return R.RCPT_VERSION}});Object.defineProperty(c,"PVE_SIGNED_LEN",{enumerable:!0,get:function(){return R.PVE_SIGNED_LEN}});Object.defineProperty(c,"PVE_TOTAL_LEN",{enumerable:!0,get:function(){return R.PVE_TOTAL_LEN}});Object.defineProperty(c,"RCPT_SIGNED_LEN",{enumerable:!0,get:function(){return R.RCPT_SIGNED_LEN}});Object.defineProperty(c,"RCPT_TOTAL_LEN",{enumerable:!0,get:function(){return R.RCPT_TOTAL_LEN}});Object.defineProperty(c,"DELTA_KIND",{enumerable:!0,get:function(){return R.DELTA_KIND}});Object.defineProperty(c,"ABSORB_STATUS",{enumerable:!0,get:function(){return R.ABSORB_STATUS}});Object.defineProperty(c,"deltaIdFromUuid",{enumerable:!0,get:function(){return R.deltaIdFromUuid}});Object.defineProperty(c,"uuidFromDeltaId",{enumerable:!0,get:function(){return R.uuidFromDeltaId}});Object.defineProperty(c,"originJktForPublicKey",{enumerable:!0,get:function(){return R.originJktForPublicKey}});Object.defineProperty(c,"encodePveSignedBytes",{enumerable:!0,get:function(){return R.encodePveSignedBytes}});Object.defineProperty(c,"signPve",{enumerable:!0,get:function(){return R.signPve}});Object.defineProperty(c,"parsePve",{enumerable:!0,get:function(){return R.parsePve}});Object.defineProperty(c,"pveHash",{enumerable:!0,get:function(){return R.pveHash}});Object.defineProperty(c,"verifyPve",{enumerable:!0,get:function(){return R.verifyPve}});Object.defineProperty(c,"encodeReceiptDeltaSignedBytes",{enumerable:!0,get:function(){return R.encodeReceiptSignedBytes}});Object.defineProperty(c,"signReceiptDelta",{enumerable:!0,get:function(){return R.signReceipt}});Object.defineProperty(c,"parseReceiptDelta",{enumerable:!0,get:function(){return R.parseReceipt}});Object.defineProperty(c,"verifyReceiptDelta",{enumerable:!0,get:function(){return R.verifyReceipt}});var sr=Co();Object.defineProperty(c,"destroyKey",{enumerable:!0,get:function(){return sr.destroyKey}});Object.defineProperty(c,"replayRatchet",{enumerable:!0,get:function(){return sr.replayRatchet}});Object.defineProperty(c,"stepRatchet",{enumerable:!0,get:function(){return sr.stepRatchet}});var cr=Bo();Object.defineProperty(c,"fetchAttestation",{enumerable:!0,get:function(){return cr.fetchAttestation}});Object.defineProperty(c,"parseAttestation",{enumerable:!0,get:function(){return cr.parseAttestation}});Object.defineProperty(c,"verifyAttestation",{enumerable:!0,get:function(){return cr.verifyAttestation}});var ya=nr();Object.defineProperty(c,"verifyCoseSign1Es384",{enumerable:!0,get:function(){return ya.verifyCoseSign1Es384}});Object.defineProperty(c,"decodeAttestationPayload",{enumerable:!0,get:function(){return ya.decodeAttestationPayload}});var Xt=Mo();Object.defineProperty(c,"combineShares",{enumerable:!0,get:function(){return Xt.combineShares}});Object.defineProperty(c,"deserializeShare",{enumerable:!0,get:function(){return Xt.deserializeShare}});Object.defineProperty(c,"serializeShare",{enumerable:!0,get:function(){return Xt.serializeShare}});Object.defineProperty(c,"splitSecret",{enumerable:!0,get:function(){return Xt.splitSecret}});var wt=Ho();Object.defineProperty(c,"buildCapability",{enumerable:!0,get:function(){return wt.buildCapability}});Object.defineProperty(c,"manifestDigest",{enumerable:!0,get:function(){return wt.manifestDigest}});Object.defineProperty(c,"openSegments",{enumerable:!0,get:function(){return wt.openSegments}});Object.defineProperty(c,"sealSegments",{enumerable:!0,get:function(){return wt.sealSegments}});Object.defineProperty(c,"SegmentError",{enumerable:!0,get:function(){return wt.SegmentError}});var lr=qo();Object.defineProperty(c,"computeWatermark",{enumerable:!0,get:function(){return lr.computeWatermark}});Object.defineProperty(c,"findLeakSource",{enumerable:!0,get:function(){return lr.findLeakSource}});Object.defineProperty(c,"watermarkSvgOverlay",{enumerable:!0,get:function(){return lr.watermarkSvgOverlay}});var ne=Qo();Object.defineProperty(c,"DRAND_LOE_MAINNET",{enumerable:!0,get:function(){return ne.DRAND_LOE_MAINNET}});Object.defineProperty(c,"drandTimeLockDecrypt",{enumerable:!0,get:function(){return ne.drandTimeLockDecrypt}});Object.defineProperty(c,"drandTimeLockEncrypt",{enumerable:!0,get:function(){return ne.drandTimeLockEncrypt}});Object.defineProperty(c,"drandTimeLockOpen",{enumerable:!0,get:function(){return ne.drandTimeLockOpen}});Object.defineProperty(c,"fetchDrandRound",{enumerable:!0,get:function(){return ne.fetchDrandRound}});Object.defineProperty(c,"makeFakeDrandChain",{enumerable:!0,get:function(){return ne.makeFakeDrandChain}});Object.defineProperty(c,"roundForTime",{enumerable:!0,get:function(){return ne.roundForTime}});Object.defineProperty(c,"TimeGateError",{enumerable:!0,get:function(){return ne.TimeGateError}});Object.defineProperty(c,"timeForRound",{enumerable:!0,get:function(){return ne.timeForRound}});Object.defineProperty(c,"timeGateDecrypt",{enumerable:!0,get:function(){return ne.timeGateDecrypt}});Object.defineProperty(c,"timeGateEncrypt",{enumerable:!0,get:function(){return ne.timeGateEncrypt}});var Re=oa();Object.defineProperty(c,"appendReceipt",{enumerable:!0,get:function(){return Re.appendReceipt}});Object.defineProperty(c,"auditChain",{enumerable:!0,get:function(){return Re.auditChain}});Object.defineProperty(c,"GENESIS_PREV_HASH",{enumerable:!0,get:function(){return Re.GENESIS_PREV_HASH}});Object.defineProperty(c,"issueGenesisReceipt",{enumerable:!0,get:function(){return Re.issueGenesisReceipt}});Object.defineProperty(c,"issueReceipt",{enumerable:!0,get:function(){return Re.issueReceipt}});Object.defineProperty(c,"receiptHash",{enumerable:!0,get:function(){return Re.receiptHash}});Object.defineProperty(c,"verifyReceipt",{enumerable:!0,get:function(){return Re.verifyReceipt}});var ma=ia();Object.defineProperty(c,"recommend",{enumerable:!0,get:function(){return ma.recommend}});Object.defineProperty(c,"summarise",{enumerable:!0,get:function(){return ma.summarise}});var Zt=ca();Object.defineProperty(c,"recommendationToMandate",{enumerable:!0,get:function(){return Zt.recommendationToMandate}});Object.defineProperty(c,"showcaseChips",{enumerable:!0,get:function(){return Zt.showcaseChips}});Object.defineProperty(c,"v3OpenReceiptPayload",{enumerable:!0,get:function(){return Zt.v3OpenReceiptPayload}});Object.defineProperty(c,"v3SealReceiptPayload",{enumerable:!0,get:function(){return Zt.v3SealReceiptPayload}});var Ee=fa();Object.defineProperty(c,"encodeFragment",{enumerable:!0,get:function(){return Ee.encodeFragment}});Object.defineProperty(c,"decodeFragment",{enumerable:!0,get:function(){return Ee.decodeFragment}});Object.defineProperty(c,"extractProofToken",{enumerable:!0,get:function(){return Ee.extractProofToken}});Object.defineProperty(c,"encodeProofToken",{enumerable:!0,get:function(){return Ee.encodeProofToken}});Object.defineProperty(c,"decodeShareCredential",{enumerable:!0,get:function(){return Ee.decodeShareCredential}});Object.defineProperty(c,"sealBytesForPublicShare",{enumerable:!0,get:function(){return Ee.sealBytesForPublicShare}});Object.defineProperty(c,"openPublicShare",{enumerable:!0,get:function(){return Ee.openPublicShare}});Object.defineProperty(c,"wrapFragmentForShortLink",{enumerable:!0,get:function(){return Ee.wrapFragmentForShortLink}})});import{McpServer as od}from"@modelcontextprotocol/sdk/server/mcp.js";import{StdioServerTransport as ad}from"@modelcontextprotocol/sdk/server/stdio.js";import{z as f}from"zod";import{z as me}from"zod";import{readdirSync as Kr,readFileSync as jr,statSync as hn}from"node:fs";import{join as Pi}from"node:path";var xr=[{id:"aws-access-key",name:"AWS Access Key",pattern:/(?:^|[^A-Z0-9])AKIA[A-Z2-7]{16}(?:[^A-Z2-7]|$)/,severity:"critical"},{id:"aws-secret-key",name:"AWS Secret Key",pattern:/(?:aws_secret_access_key|aws_secret_key|secret_access_key)\s*[=:]\s*['"]?[A-Za-z0-9/+=]{40}['"]?/,severity:"critical"},{id:"gcp-api-key",name:"GCP API Key",pattern:/AIza[0-9A-Za-z_-]{35}/,severity:"critical"},{id:"gcp-service-account",name:"GCP Service Account",pattern:/"type"\s*:\s*"service_account"/,severity:"critical"},{id:"github-token",name:"GitHub Token",pattern:/gh[pousr]_[0-9a-zA-Z]{36,}/,severity:"critical"},{id:"github-fine-grained",name:"GitHub Fine-Grained Token",pattern:/github_pat_[0-9a-zA-Z_]{22,}/,severity:"critical"},{id:"gitlab-token",name:"GitLab Token",pattern:/glpat-[0-9a-zA-Z_-]{20,}/,severity:"critical"},{id:"stripe-secret",name:"Stripe Secret Key",pattern:/sk_live_[0-9a-zA-Z]{24,}/,severity:"critical"},{id:"stripe-restricted",name:"Stripe Restricted Key",pattern:/rk_live_[0-9a-zA-Z]{24,}/,severity:"critical"},{id:"slack-token",name:"Slack Token",pattern:/xox[baprs]-[0-9a-zA-Z-]{10,}/,severity:"high"},{id:"slack-webhook",name:"Slack Webhook",pattern:/hooks\.slack\.com\/services\/T[0-9A-Z]{8,}\/B[0-9A-Z]{8,}\/[0-9a-zA-Z]{24}/,severity:"high"},{id:"twilio-api-key",name:"Twilio API Key",pattern:/SK[0-9a-fA-F]{32}/,severity:"high"},{id:"sendgrid-api-key",name:"SendGrid API Key",pattern:/SG\.[0-9a-zA-Z_-]{22}\.[0-9a-zA-Z_-]{43}/,severity:"critical"},{id:"postgres-uri",name:"PostgreSQL Connection String",pattern:/postgres(?:ql)?:\/\/[^\s'"]{10,}/,severity:"critical"},{id:"mongodb-uri",name:"MongoDB Connection String",pattern:/mongodb(?:\+srv)?:\/\/[^\s'"]{10,}/,severity:"critical"},{id:"redis-uri",name:"Redis Connection String",pattern:/redis(?:s)?:\/\/[^\s'"]{10,}/,severity:"high"},{id:"openai-key",name:"OpenAI API Key",pattern:/sk-[0-9a-zA-Z]{20,}T3BlbkFJ[0-9a-zA-Z]{20,}/,severity:"critical"},{id:"anthropic-key",name:"Anthropic API Key",pattern:/sk-ant-[0-9a-zA-Z_-]{40,}/,severity:"critical"},{id:"firebase-key",name:"Firebase API Key",pattern:/AIza[0-9A-Za-z_-]{35}/,severity:"high"},{id:"supabase-key",name:"Supabase Service Key",pattern:/eyJ[0-9a-zA-Z_-]{100,}/,severity:"critical"},{id:"private-key",name:"Private Key",pattern:/-----BEGIN (?:RSA |EC |DSA |OPENSSH )?PRIVATE KEY-----/,severity:"critical"},{id:"jwt-secret",name:"JWT/Generic Secret",pattern:/(?:jwt_secret|JWT_SECRET|secret_key|SECRET_KEY|api_secret|API_SECRET)\s*[=:]\s*['"][^'"]{8,}['"]/,severity:"high"},{id:"password-in-code",name:"Password in Code",pattern:/(?:password|passwd|pwd)\s*[=:]\s*['"][^'"]{8,}['"]/,severity:"high"},{id:"bearer-token",name:"Bearer Token in Code",pattern:/['"]Bearer\s+[0-9a-zA-Z._-]{20,}['"]/,severity:"high"}],Ar=/node_modules\/|\.next\/|\.test\.|\.spec\.|__tests__\/|\.env\.example$|\.nodata-proof\.json$|\.git\//,ti=[{name:"lodash",below:"4.17.21",severity:"critical",cve:"CVE-2021-23337",desc:"Command injection via template"},{name:"minimist",below:"1.2.6",severity:"critical",cve:"CVE-2021-44906",desc:"Prototype pollution"},{name:"json5",below:"2.2.2",severity:"high",cve:"CVE-2022-46175",desc:"Prototype pollution"},{name:"express",below:"4.19.2",severity:"high",cve:"CVE-2024-29041",desc:"Open redirect"},{name:"path-to-regexp",below:"6.3.0",severity:"high",cve:"CVE-2024-45296",desc:"ReDoS"},{name:"sanitize-html",below:"2.12.1",severity:"high",cve:"CVE-2024-21501",desc:"XSS bypass"},{name:"dompurify",below:"3.0.9",severity:"high",cve:"CVE-2024-45801",desc:"mXSS"},{name:"jsonwebtoken",below:"9.0.0",severity:"critical",cve:"CVE-2022-23529",desc:"Key confusion attack"},{name:"jose",below:"4.15.5",severity:"high",cve:"CVE-2024-28176",desc:"DoS via JWE"},{name:"axios",below:"1.6.0",severity:"high",cve:"CVE-2023-45857",desc:"CSRF cookie leak"},{name:"node-fetch",below:"2.6.7",severity:"high",cve:"CVE-2022-0235",desc:"Header leak on redirect"},{name:"serialize-javascript",below:"6.0.2",severity:"critical",cve:"CVE-2024-11831",desc:"XSS via serialization"},{name:"xml2js",below:"0.6.0",severity:"high",cve:"CVE-2023-0842",desc:"Prototype pollution"},{name:"next",below:"14.1.1",severity:"high",cve:"CVE-2024-34350",desc:"SSRF via headers"},{name:"sharp",below:"0.32.6",severity:"high",cve:"CVE-2023-4863",desc:"libwebp heap overflow"},{name:"multer",below:"1.4.5",severity:"high",cve:"CVE-2022-24434",desc:"Prototype pollution"},{name:"tough-cookie",below:"4.1.3",severity:"medium",cve:"CVE-2023-26136",desc:"Prototype pollution"},{name:"semver",below:"7.5.4",severity:"medium",cve:"CVE-2022-25883",desc:"ReDoS"},{name:"ip",below:"2.0.1",severity:"critical",cve:"CVE-2024-29415",desc:"SSRF bypass via octal IP"},{name:"tar",below:"6.2.1",severity:"high",cve:"CVE-2024-28863",desc:"DoS via path traversal"}];function ni(e,t){let n=a=>a.replace(/^[^0-9]*/,"").split(".").map(i=>parseInt(i,10)||0),r=n(e),o=n(t);for(let a=0;a<3;a++){if((r[a]||0)<(o[a]||0))return!0;if((r[a]||0)>(o[a]||0))return!1}return!1}function Tr(e){let t=[],n;try{n=JSON.parse(e)}catch{return t}let r={...n.dependencies??{},...n.devDependencies??{}};for(let[o,a]of Object.entries(r)){let i=(a||"").replace(/^[\^~>=<\s]+/,""),s=ti.find(l=>l.name===o&&ni(i,l.below));s&&t.push({name:o,version:i,vuln:s})}return t}var ri=[{pattern:/^(full_?name|first_?name|last_?name|spouse_?name|beneficiary_?name)$/i,type:"name",label:"Person name"},{pattern:/^(email|e_?mail|email_?address)$/i,type:"email",label:"Email address"},{pattern:/^(phone|mobile|telephone|phone_?number|cell_?phone)$/i,type:"phone",label:"Phone number"},{pattern:/^(id_?number|identity|ssn|social_?security|national_?id|teudat_?zehut)$/i,type:"id",label:"ID number"},{pattern:/^(address|street_?address|home_?address)$/i,type:"address",label:"Address"},{pattern:/^(date_?of_?birth|dob|birth_?date|birthday)$/i,type:"dob",label:"Date of birth"},{pattern:/^(bank_?account|iban|account_?number|bank_?details|routing_?number)$/i,type:"financial",label:"Bank account"},{pattern:/^(credit_?card|card_?number|cvv|cc_?number)$/i,type:"financial",label:"Credit card"},{pattern:/^(salary|income|commission|premium|compensation)$/i,type:"financial",label:"Salary / income"},{pattern:/^(medical_?info|health_?conditions|diagnosis|medication|prescription)$/i,type:"medical",label:"Medical"},{pattern:/^(passport|passport_?number|passport_?id)$/i,type:"id",label:"Passport"},{pattern:/^(driver_?license|drivers_?license|dl_?number)$/i,type:"id",label:"Driver license"},{pattern:/^(tax_?id|tin|vat_?number|ein)$/i,type:"financial",label:"Tax ID"},{pattern:/^(insurance_?number|policy_?number|member_?id)$/i,type:"id",label:"Insurance/Policy"},{pattern:/^(biometric|fingerprint|face_?id|retina)$/i,type:"biometric",label:"Biometric"},{pattern:/^(latitude|longitude|lat|lng|geo_?location|coordinates)$/i,type:"location",label:"Geolocation"}],oi=[{pattern:/^(?:שם|שם_מלא|שם פרטי|שם_פרטי|שם משפחה|שם_משפחה|שם הלקוח|שם בן זוג|שם המבוטח|שם המוטב|שם הילד|שם הקטין)$/i,type:"name",label:"\u05E9\u05DD \u05D0\u05D3\u05DD"},{pattern:/^(?:ת"ז|ת\.ז|ת ז|תז|תעודת זהות|תעודת_זהות|מספר זהות|מס' זהות|teudat_zehut|tz|israeli_id|il_id)$/i,type:"id",label:"\u05EA\u05E2\u05D5\u05D3\u05EA \u05D6\u05D4\u05D5\u05EA"},{pattern:/^(?:דרכון|מספר דרכון|רישיון נהיגה|רישיון_נהיגה|רשיון נהיגה)$/i,type:"id",label:"\u05D3\u05E8\u05DB\u05D5\u05DF/\u05E8\u05D9\u05E9\u05D9\u05D5\u05DF"},{pattern:/^(?:מייל|דוא"ל|דוא_ל|דואר אלקטרוני|אימייל|כתובת מייל)$/i,type:"email",label:"\u05D3\u05D5\u05D0\u05E8 \u05D0\u05DC\u05E7\u05D8\u05E8\u05D5\u05E0\u05D9"},{pattern:/^(?:טלפון|טל'|נייד|פלאפון|סלולרי|מספר טלפון|טלפון נייד)$/i,type:"phone",label:"\u05DE\u05E1\u05E4\u05E8 \u05D8\u05DC\u05E4\u05D5\u05DF"},{pattern:/^(?:כתובת|כתובת מגורים|רחוב|מס בית|עיר|ישוב|יישוב|מיקוד|כתובת מלאה|מען)$/i,type:"address",label:"\u05DB\u05EA\u05D5\u05D1\u05EA"},{pattern:/^(?:תאריך לידה|ת לידה|תאריך הולדת|יום הולדת|גיל)$/i,type:"dob",label:"\u05EA\u05D0\u05E8\u05D9\u05DA \u05DC\u05D9\u05D3\u05D4"},{pattern:/^(?:חשבון בנק|מספר חשבון|מס חשבון|בנק|סניף|iban|iban_il)$/i,type:"financial",label:"\u05D7\u05E9\u05D1\u05D5\u05DF \u05D1\u05E0\u05E7"},{pattern:/^(?:כרטיס אשראי|מספר אשראי|cvv|אשראי)$/i,type:"financial",label:"\u05DB\u05E8\u05D8\u05D9\u05E1 \u05D0\u05E9\u05E8\u05D0\u05D9"},{pattern:/^(?:שכר|משכורת|הכנסה|פרמיה|שכר ברוטו|שכר נטו|תגמול|בונוס|פיצוי)$/i,type:"financial",label:"\u05E9\u05DB\u05E8/\u05D4\u05DB\u05E0\u05E1\u05D4"},{pattern:/^(?:אבחון|אבחנה|מחלה|תרופה|מרשם|בדיקה רפואית|מצב רפואי|חיסון|רגישות|אלרגיה|סוג דם)$/i,type:"medical",label:"\u05DE\u05D9\u05D3\u05E2 \u05E8\u05E4\u05D5\u05D0\u05D9"},{pattern:/^(?:מספר פוליסה|מס פוליסה|פוליסה|מספר חבר|מספר ביטוח)$/i,type:"id",label:"\u05E4\u05D5\u05DC\u05D9\u05E1\u05D4/\u05D7\u05D1\u05E8\u05D5\u05EA"},{pattern:/^(?:שם הילד|תעודת זהות של ילד|ילדים|קטין|מספר ילדים|תעודת לידה)$/i,type:"minor_data",label:"\u05DE\u05D9\u05D3\u05E2 \u05E2\u05DC \u05E7\u05D8\u05D9\u05DF"},{pattern:/^(?:דת|לאום|מין|נטייה מינית|השקפה פוליטית|מצב משפחתי|עדה|מוצא)$/i,type:"sensitive_personal",label:"\u05DE\u05D9\u05D3\u05E2 \u05D0\u05D9\u05E9\u05D9 \u05E8\u05D2\u05D9\u05E9"},{pattern:/^(?:מספר רכב|מס רכב|לוחית רישוי|מספר רישוי)$/i,type:"tracking",label:"\u05DE\u05E1\u05E4\u05E8 \u05E8\u05DB\u05D1"}],ai=/^(id|uuid|created_?at|updated_?at|deleted_?at|status|type|category|description|title|slug|url|path|key|value|enabled|active|public|version|metadata|config|settings|data|content|note|comment|label|color|icon)$/i;function Qe(e){if(!e)return null;let t=e.trim();if(ai.test(t)||/^name$/i.test(t))return null;for(let n of[...oi,...ri])if(n.pattern.test(t))return{type:n.type,label:n.label};return null}var dn={id:"critical",financial:"critical",medical:"critical",biometric:"critical",minor_data:"critical",sensitive_personal:"critical",email:"high",phone:"high",name:"high",address:"high",dob:"high",tracking:"medium",location:"medium"};function At(e){let t=String(e??"").replace(/\D/g,"");if(t.length===0||t.length>9)return!1;let n=t.padStart(9,"0"),r=0;for(let o=0;o<9;o++){let a=parseInt(n[o]??"0",10)*(o%2+1);a>9&&(a-=9),r+=a}return r%10===0&&parseInt(n,10)>0}var et=/(?:\+972[\s-]?|0)(?:5[0-9]|[2-4]|[89])(?:[\s-]?\d){7}/g;var tt=/\bIL\d{2}\s?(?:\d{4}\s?){4}\d{3}\b/g;function ii(e){let t=String(e??"").replace(/\D/g,"");if(t.length<12||t.length>19)return!1;let n=0,r=!1;for(let o=t.length-1;o>=0;o-=1){let a=parseInt(t[o]??"0",10);r&&(a*=2,a>9&&(a-=9)),n+=a,r=!r}return n%10===0}function si(e){let t=String(e??"").replace(/\s/g,"").toUpperCase();if(!/^[A-Z]{2}\d{2}[A-Z0-9]{10,30}$/.test(t))return!1;let n=t.slice(4)+t.slice(0,4),r=0;for(let o of n){let a=o>="A"&&o<="Z"?String(o.charCodeAt(0)-55):o;for(let i of a)r=(r*10+Number(i))%97}return r===1}var cn="(?<!\\d)(?<!\\d[.,])",ln="(?!\\d)(?![.,]\\d)",un=[{subkind:"israeli_id",severity:"high",pattern:new RegExp(`${cn}\\d{9}${ln}`,"g"),validate:At,hint:"Israeli national ID (check digit verified) in plaintext. Encrypt the column or mask it at rest."},{subkind:"credit_card",severity:"critical",pattern:new RegExp(`${cn}(?:\\d[ -]?){12,18}\\d${ln}`,"g"),validate:ii,hint:"Payment card number (Luhn verified) in plaintext. This is PCI scope."},{subkind:"iban",severity:"high",pattern:/\b[A-Z]{2}\d{2}[A-Z0-9]{10,30}\b/g,validate:si,hint:"Bank account in IBAN form (mod-97 verified) in plaintext."},{subkind:"israeli_phone",severity:"medium",pattern:new RegExp(`${cn}(?:\\+972[- ]?|0)(?:5\\d|[2-489])[- ]?\\d{3}[- ]?\\d{4}${ln}`,"g"),validate:e=>{let t=e.replace(/\D/g,"").replace(/^972/,"0");return t.length===10&&t.startsWith("0")},hint:"Israeli phone number in plaintext."}];function Pr(e){let t=[];for(let n of un){n.pattern.lastIndex=0;let r=new Set,o,a=0;for(;(o=n.pattern.exec(e))!==null&&(a+=1,!(a>2e5));){let i=o[0];if(n.validate(i)&&r.add(i.replace(/[\s-]/g,"")),r.size>=1e5)break}r.size>0&&t.push({subkind:n.subkind,severity:n.severity,hint:n.hint,count:r.size})}return t}function Be(e,t){let n=[],r="",o=!1;for(let a=0;a<e.length;a++){let i=e[a];o?i==='"'&&e[a+1]==='"'?(r+='"',a++):i==='"'?o=!1:r+=i:i==='"'?o=!0:i===t?(n.push(r),r=""):r+=i}return n.push(r),n}import{inflateRawSync as gi}from"node:zlib";import{inflateSync as ci}from"node:zlib";var pn=new Set([".pdf"]),Dr=8*1024*1024;function li(e){let t=e.toString("latin1"),n=new Map,r=/(\d+)\s+(\d+)\s+obj\b/g,o;for(;(o=r.exec(t))!==null;){let a=Number(o[1]),i=r.lastIndex,s=t.indexOf("endobj",i);if(s<0)continue;let l=t.indexOf("stream",i),d,u=null;if(l>=0&&l<s){d=t.slice(i,l);let p=l+6;t[p]==="\r"&&(p+=1),t[p]===`
|
|
16
|
+
`&&(p+=1);let h=t.indexOf("endstream",p);h>p&&(u=e.subarray(p,h))}else d=t.slice(i,s);n.set(a,{num:a,dict:d,stream:u})}return n}function di(e){let t=e.toString("latin1").replace(/\s/g,"");t.startsWith("<~")&&(t=t.slice(2));let n=t.indexOf("~>");n>=0&&(t=t.slice(0,n));let r=[],o=0,a=0;for(let i of t){if(i==="z"&&a===0){r.push(0,0,0,0);continue}let s=i.charCodeAt(0)-33;if(s<0||s>84)return null;o=o*85+s,a+=1,a===5&&(r.push(o>>>24&255,o>>>16&255,o>>>8&255,o&255),o=0,a=0)}if(a>0){for(let s=a;s<5;s+=1)o=o*85+84;let i=[o>>>24&255,o>>>16&255,o>>>8&255,o&255];for(let s=0;s<a-1;s+=1)r.push(i[s]??0)}return Buffer.from(r)}function ui(e){let t=e.toString("latin1").replace(/\s/g,"").split(">")[0]??"",n=t.length%2?t+"0":t;return/^[0-9A-Fa-f]*$/.test(n)?Buffer.from(n,"hex"):null}function pi(e){let t=/\/Filter\s*(\[[^\]]*\]|\/\w+)/.exec(e);return!t||!t[1]?[]:[...t[1].matchAll(/\/(\w+)/g)].map(n=>n[1]??"")}function Nr(e){if(!e.stream)return null;let t=e.stream;for(let n of pi(e.dict)){let r=null;if(n==="FlateDecode")try{r=ci(t)}catch{return null}else if(n==="ASCII85Decode")r=di(t);else if(n==="ASCIIHexDecode")r=ui(t);else return null;if(r===null)return null;t=r}return t.toString("latin1")}function fi(e){let t=new Map,n=1,r=/begincodespacerange([\s\S]*?)endcodespacerange/.exec(e);if(r&&r[1]){let l=/<([0-9A-Fa-f]+)>/.exec(r[1]);l&&l[1]&&l[1].length>=4&&(n=2)}let o=l=>{let d="";for(let u=0;u+3<l.length+1;u+=4){let p=parseInt(l.slice(u,u+4),16);Number.isFinite(p)&&p>0&&(d+=String.fromCharCode(p))}return d},a=/beginbfchar([\s\S]*?)endbfchar/g,i;for(;(i=a.exec(e))!==null;){let l=/<([0-9A-Fa-f]+)>\s*<([0-9A-Fa-f]*)>/g,d;for(;(d=l.exec(i[1]??""))!==null;)t.set(parseInt(d[1]??"0",16),o(d[2]??""))}let s=/beginbfrange([\s\S]*?)endbfrange/g;for(;(i=s.exec(e))!==null;){let l=i[1]??"",d=/<([0-9A-Fa-f]+)>\s*<([0-9A-Fa-f]+)>\s*<([0-9A-Fa-f]*)>/g,u;for(;(u=d.exec(l))!==null;){let p=parseInt(u[1]??"0",16),h=parseInt(u[2]??"0",16),m=parseInt((u[3]??"0").slice(0,4)||"0",16);if(!(h-p>65535))for(let v=p;v<=h;v+=1)t.set(v,String.fromCharCode(m+(v-p)))}}return{map:t,bytes:n}}function hi(e){let t=new Map,n=new Map,r=[];for(let o of e.values()){let a=/\/Font\s*<<([\s\S]*?)>>/.exec(o.dict);a?.[1]&&r.push(a[1]);let i=/\/Font\s+(\d+)\s+\d+\s+R/.exec(o.dict);if(i){let s=e.get(Number(i[1]));s&&r.push(s.dict)}}for(let o of r){let a=/\/([^\s/<>[\]()]+)\s+(\d+)\s+\d+\s+R/g,i;for(;(i=a.exec(o))!==null;)n.set(i[1]??"",Number(i[2]))}for(let[o,a]of n){let i=e.get(a);if(!i)continue;let s=/\/ToUnicode\s+(\d+)\s+\d+\s+R/.exec(i.dict);if(!s)continue;let l=e.get(Number(s[1]));if(!l)continue;let d=Nr(l);d&&t.set(o,fi(d))}return t}function Ir(e){let t=[];for(let n=0;n<e.length;n+=1){let r=e[n];if(r!=="\\"){t.push(r.charCodeAt(0)&255);continue}let o=e[n+1];if(o===void 0)break;if(o>="0"&&o<="7"){let i="",s=n+1;for(;s<e.length&&i.length<3&&e[s]>="0"&&e[s]<="7";)i+=e[s],s+=1;t.push(parseInt(i,8)&255),n=s-1;continue}let a={n:10,r:13,t:9,b:8,f:12};t.push(a[o]??o.charCodeAt(0)&255),n+=1}return t}function Cr(e){if(e.length<2||e[0]!==254||e[1]!==255)return null;let t="";for(let n=2;n+1<e.length;n+=2)t+=String.fromCharCode((e[n]??0)<<8|(e[n+1]??0));return t}function Or(e,t){let n=Cr(e);if(n!==null)return n;if(!t)return e.map(o=>String.fromCharCode(o)).join("");let r="";if(t.bytes===2)for(let o=0;o+1<e.length;o+=2){let a=(e[o]??0)<<8|(e[o+1]??0);r+=t.map.get(a)??""}else for(let o of e)r+=t.map.get(o)??String.fromCharCode(o);return r}function yi(e,t){let n="",r,o=/\/([^\s/<>[\]()]+)\s+[\d.]+\s+Tf|\((?:\\.|[^\\)])*\)|<[0-9A-Fa-f\s]*>|TJ|Tj|'|"/g,a,i="";for(;(a=o.exec(e))!==null;){let s=a[0];if(s.endsWith("Tf")){r=t.get(a[1]??"");continue}if(s==="TJ"||s==="Tj"||s==="'"||s==='"'){i&&(n+=i+`
|
|
17
|
+
`,i="");continue}if(s.startsWith("("))i+=Or(Ir(s.slice(1,-1)),r);else if(s.startsWith("<")){let l=s.slice(1,-1).replace(/\s+/g,""),d=[];for(let u=0;u+1<l.length;u+=2)d.push(parseInt(l.slice(u,u+2),16));i+=Or(d,r)}}return i&&(n+=i+`
|
|
18
|
+
`),n}function mi(e,t){let n=e.toString("latin1"),r=/\/Info\s+(\d+)\s+\d+\s+R/.exec(n),o=r?t.get(Number(r[1]))?.dict:void 0;if(!o)return"";let a=[],i=/\/(Author|Title|Subject|Keywords|Creator|Producer)\s*(\((?:\\.|[^\\)])*\)|<[0-9A-Fa-f\s]*>)/g,s;for(;(s=i.exec(o))!==null;){let l=s[2]??"";if(l.startsWith("(")){let d=Ir(l.slice(1,-1));a.push(Cr(d)??d.map(u=>String.fromCharCode(u)).join(""))}else{let d=l.slice(1,-1).replace(/\s+/g,""),u="";if(d.toUpperCase().startsWith("FEFF"))for(let p=4;p+3<d.length+1;p+=4)u+=String.fromCharCode(parseInt(d.slice(p,p+4),16));else for(let p=0;p+1<d.length;p+=2)u+=String.fromCharCode(parseInt(d.slice(p,p+2),16));a.push(u)}}return a.join(`
|
|
19
|
+
`)}function Rr(e){if(!e.subarray(0,8).toString("latin1").startsWith("%PDF-")||e.toString("latin1",0,Math.min(e.length,4096)).includes("/Encrypt"))return null;let n=li(e);if(n.size===0)return null;let r=hi(n),o=[];o.push(mi(e,n));let a=0,i=0,s=!1;for(let l of n.values()){if(!l.stream||/\/Subtype|\/Type\s*\/(XObject|Font|Metadata)|\/FontFile/.test(l.dict))continue;let d=Nr(l);if(d===null||!/(TJ|Tj)\b/.test(d))continue;let u=yi(d,r);if(u.trim().length!==0){if(i+=1,a+u.length>Dr){o.push(u.slice(0,Math.max(0,Dr-a))),s=!0;break}o.push(u),a+=u.length}}return i===0?null:{text:o.join(`
|
|
20
|
+
`),truncated:s,streams:i}}var $r=new Set([".xlsx",".xlsm",".docx",".pptx"]),fn=8*1024*1024,_i=101010256,bi=33639248,Si=67324752;function vi(e){let t=Math.min(e.length,67584),n=-1;for(let i=e.length-22;i>=e.length-t&&i>=0;i-=1)if(e.readUInt32LE(i)===_i){n=i;break}if(n<0)return null;let r=e.readUInt16LE(n+10),o=e.readUInt32LE(n+16);if(o>=e.length)return null;let a=[];for(let i=0;i<r&&!(o+46>e.length||e.readUInt32LE(o)!==bi);i+=1){let s=e.readUInt16LE(o+10),l=e.readUInt32LE(o+20),d=e.readUInt32LE(o+24),u=e.readUInt16LE(o+28),p=e.readUInt16LE(o+30),h=e.readUInt16LE(o+32),m=e.readUInt32LE(o+42),v=e.subarray(o+46,o+46+u).toString("utf8");a.push({name:v,method:s,compSize:l,uncompSize:d,localHeaderOffset:m}),o+=46+u+p+h}return a}function wi(e,t){let n=t.localHeaderOffset;if(n+30>e.length||e.readUInt32LE(n)!==Si)return null;let r=e.readUInt16LE(n+26),o=e.readUInt16LE(n+28),a=n+30+r+o,i=a+t.compSize;if(i>e.length)return null;let s=e.subarray(a,i);try{if(t.method===0)return s.toString("utf8");if(t.method===8)return gi(s).toString("utf8")}catch{return null}return null}var Ei={"&":"&","<":"<",">":">",""":'"',"'":"'"};function Br(e){return e.replace(/&(amp|lt|gt|quot|apos);/g,t=>Ei[t]??t).replace(/&#(\d+);/g,(t,n)=>{let r=Number(n);return r>0&&r<1114112?String.fromCodePoint(r):""}).replace(/&#x([0-9a-fA-F]+);/g,(t,n)=>{let r=parseInt(n,16);return r>0&&r<1114112?String.fromCodePoint(r):""})}function ki(e){return Br(e.replace(/<[^>]*>/g,`
|
|
9
21
|
`)).replace(/\n{2,}/g,`
|
|
10
|
-
`)}function
|
|
11
|
-
`+
|
|
12
|
-
`))}s+
|
|
13
|
-
`),truncated:l,parts:
|
|
14
|
-
`),
|
|
15
|
-
`),
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
+
`)}function xi(e,t,n){let r=new RegExp(`<${t}\\b[^>]*\\b${n}="([^"]*)"`,"g"),o=[],a;for(;(a=r.exec(e))!==null;)a[1]&&o.push(Br(a[1]));return o}function Ai(e,t){let n=[];for(let r of t)(r==="docProps/core.xml"||r==="docProps/app.xml")&&n.push(r);if(e===".xlsx"||e===".xlsm")for(let r of t)(r==="xl/sharedStrings.xml"||r==="xl/workbook.xml"||/^xl\/worksheets\/sheet\d+\.xml$/.test(r)||/^xl\/comments\d*\.xml$/.test(r))&&n.push(r);else if(e===".docx")for(let r of t)(r==="word/document.xml"||/^word\/(header|footer|footnotes|endnotes|comments)\d*\.xml$/.test(r))&&n.push(r);else if(e===".pptx")for(let r of t)/^ppt\/(slides|notesSlides)\/(slide|notesSlide)\d+\.xml$/.test(r)&&n.push(r);return n}function Ti(e,t){let n=vi(e);if(!n||n.length===0)return null;let r=new Map(n.map(d=>[d.name,d])),o=Ai(t,n.map(d=>d.name));if(o.length===0)return null;let a=[],i=[],s=0,l=!1;for(let d of o){if(s>=fn){l=!0;break}let u=r.get(d);if(!u)continue;let p=wi(e,u);if(p===null)continue;let h=ki(p);if(d==="xl/workbook.xml"){let m=xi(p,"sheet","name");m.length&&(h+=`
|
|
23
|
+
`+m.join(`
|
|
24
|
+
`))}s+h.length>fn&&(h=h.slice(0,Math.max(0,fn-s)),l=!0),h.trim().length!==0&&(a.push(h),i.push(d),s+=h.length)}return a.length===0?null:{text:a.join(`
|
|
25
|
+
`),truncated:l,parts:i}}function Tt(e,t){if($r.has(t))return Ti(e,t);if(pn.has(t)){let n=Rr(e);return n?{text:n.text,truncated:n.truncated,parts:[`pdf:${n.streams}-streams`]}:null}return null}var Pt=new Set([...$r,...pn]);var yn=10,nt=5e3,Di=64*1024*1024,mn=32*1024,Oi=new Set([".exe",".dll",".so",".dylib",".msi",".bin",".iso",".zip",".tar",".gz",".7z",".rar",".png",".jpg",".jpeg",".gif",".bmp",".tif",".tiff",".webp",".ico",".mp3",".mp4",".mov",".avi",".mkv",".wav",".flac",".ogg",".psd",".ai",".fla",".dwg",".dxf",".sqlite",".sqlite3",".db",".pyc",".class"]),Ni=new Set(["node_modules",".git",".hg",".svn"]),Ii=[{re:/\b\d{3}-\d{2}-\d{4}\b/,kind:"pii_unencrypted",subkind:"ssn",severity:"high",hint:"US Social Security Number pattern in plaintext."},{re:/\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}\b/i,kind:"pii_unencrypted",subkind:"email",severity:"low",hint:"Email addresses in plaintext."},{re:/(passport|teudat.?zehut|(?<![א-ת])תעודת.?זהות(?![א-ת])|(?<![א-ת])ת["'׳״]?\.?ז(?![א-ת]))/i,kind:"pii_unencrypted",subkind:"passport_keyword",severity:"medium",hint:"Filename / content references passport / national-ID keyword."}],Ci=[{re:/(salary|payroll|משכורת|ssn|social.?security|passport|דרכון|תעודת.?זהות)/i,kind:"pii_unencrypted",subkind:"sensitive_filename",severity:"medium",hint:"Filename suggests sensitive PII content."},{re:/\.(env|env\.local|pem|key|p12|pfx)$/i,kind:"pii_unencrypted",subkind:"secret_file",severity:"high",hint:"File extension implies secret / credential bundle in plaintext."}];function Ri(e){let t=e.lastIndexOf(".");return t<0?"":e.slice(t).toLowerCase()}async function rt(e){let t=Date.now(),n=[],r=[],o=0,a=0,i={hit_file_cap:!1,hit_depth_cap:!1,max_files:nt,max_depth:yn,skipped_by_extension:0,documents_extracted:0,documents_truncated:0,documents_unreadable:0,files_too_large:0,files_sampled_only:0,sample_bytes:mn};function s(S){return(S.startsWith(e.target_path)?S.slice(e.target_path.length).replace(/^[\\/]+/,""):S).replace(/\\/g,"/")}function l(S,_,w,x,y){let g=s(S);g!==""&&r.push({target_id:e.target_id,path:g,kind:_,size_bytes:w,modified_at:x?x.toISOString():null,child_count:y})}function d(S,_){n.push({target_id:e.target_id,relative_path:S,finding_kind:_.kind,finding_subkind:_.subkind,severity:_.severity,remediation_hint:_.hint})}function u(S,_,w,x,y){n.push({target_id:e.target_id,relative_path:S,finding_kind:_,finding_subkind:x,severity:w,remediation_hint:y})}function p(S,_){if(o+=1,o>nt){i.hit_file_cap=!0;return}let w=s(S);for(let E of Ci)E.re.test(_)&&d(w,E);let x=Ri(_);if(Oi.has(x)){i.skipped_by_extension+=1;return}let y=Pt.has(x),g=0;try{g=hn(S).size}catch{return}if(y&&g>Di){i.files_too_large+=1;return}let N;try{let E=jr(S,{flag:"r"});N=y?E:E.subarray(0,mn)}catch{return}a+=1;let $;if(y){let E=Tt(N,x);if(!E){i.documents_unreadable+=1;return}$=E.text,i.documents_extracted+=1,E.truncated&&(i.documents_truncated+=1)}else{let E=0;for(let I=0;I<N.length;I+=1)N[I]===0&&(E+=1);if(N.length>0&&E/N.length>.05)return;$=N.toString("utf8"),g>mn&&(i.files_sampled_only+=1)}let D=new Set;for(let E of Ii)if(E.re.test($)){let I=`${E.subkind}::${w}`;D.has(I)||(D.add(I),d(w,E))}for(let E of Pr($)){let I=`validated::${E.subkind}::${w}`;D.has(I)||(D.add(I),u(w,"pii_unencrypted",E.severity,E.subkind,`${E.hint} ${E.count} distinct value${E.count===1?"":"s"} in this file.`))}if(!Ar.test(w)){let E=$.split(`
|
|
26
|
+
`),I=Math.min(E.length,2e3);for(let C=0;C<I;C++){let j=E[C];if(!j)continue;let re=j.trimStart();if(!(re.startsWith("//")||re.startsWith("/*")||re.startsWith("*")||re.startsWith("#"))&&!/process\.env/.test(j)&&!/\$\{[A-Z_]+/.test(j)){for(let oe of xr)if(oe.pattern.test(j)){let he=`secret::${oe.id}::${w}::${C+1}`;if(D.has(he))break;D.add(he),u(w,"hardcoded_secret",oe.severity,oe.id,`Looks like a ${oe.name} hardcoded near line ${C+1}. Move to an env var or secret manager.`);break}}}}if(_==="package.json"&&!w.includes("node_modules"))try{let E=jr(S,"utf8"),I=Tr(E);for(let C of I){let j=`vuln::${C.name}::${w}`;D.has(j)||(D.add(j),u(w,"vulnerable_dependency",C.vuln.severity,C.name,`${C.name}@${C.version} is below ${C.vuln.below} (${C.vuln.cve} \xB7 ${C.vuln.desc}). Bump to ${C.vuln.below} or higher.`))}}catch{}if(x===".csv"||x===".tsv"){let E=x===".tsv"?" ":",",I=$.split(/\r?\n/);if(I.length>0){let C=Be(I[0]??"",E),j=I.slice(1,51).map(re=>Be(re??"",E));C.forEach((re,oe)=>{let he=(re??"").trim();if(!he)return;let xe=Qe(he)?.type??null;if(!xe){let Xe=[];for(let Ja of j){let sn=Ja[oe];if(sn&&sn.trim().length>0&&Xe.push(sn),Xe.length>=50)break}let Ze=m(Xe);Ze&&(xe=Ze)}if(xe){let Xe=dn[xe]??"medium",Ze=`header::${w}::${he}::${xe}`;if(D.has(Ze))return;D.add(Ze),u(w,"pii_header_match",Xe,`${xe}:${he}`,`Column "${he}" looks like ${xe} data. Wrap with envelope or move to a vault-backed reference.`)}})}}if(x===".json"&&!_.endsWith(".nodata-proof.json"))try{let E=JSON.parse($),I=Array.isArray(E)?E[0]:E;if(I&&typeof I=="object")for(let C of Object.keys(I)){let j=Qe(C);if(j){let re=dn[j.type]??"medium",oe=`jsonkey::${w}::${C}::${j.type}`;if(D.has(oe))continue;D.add(oe),u(w,"pii_header_match",re,`${j.type}:${C}`,`JSON key "${C}" looks like ${j.type} data.`)}}}catch{}/\.(txt|log|md|csv|tsv|json|jsonl|xml|html?|yaml|yml|sql)$/i.test(_)&&h($,w,D)}function h(S,_,w){let x=S.split(`
|
|
27
|
+
`),y=Math.min(x.length,1e3),g=-1,N=-1,$=-1;for(let D=0;D<y;D++){let E=x[D]??"";if($<0){let I=E.match(/\b\d{9}\b/);I&&At(I[0])&&($=D+1)}if(g<0&&(et.lastIndex=0,et.test(E)&&(g=D+1)),N<0&&(tt.lastIndex=0,tt.test(E)&&(N=D+1)),$>0&&g>0&&N>0)break}$>0&&!w.has(`ilid::${_}`)&&(w.add(`ilid::${_}`),u(_,"israeli_id_value","critical",`near_line:${$}`,`Israeli ID with valid Luhn checksum detected near line ${$}. Strong signal that real customer IDs are in plaintext.`)),g>0&&!w.has(`ilphone::${_}`)&&(w.add(`ilphone::${_}`),u(_,"israeli_phone_value","high",`near_line:${g}`,`Israeli phone number detected near line ${g}.`)),N>0&&!w.has(`iliban::${_}`)&&(w.add(`iliban::${_}`),u(_,"israeli_iban_value","critical",`near_line:${N}`,`Israeli IBAN (IL prefix) detected near line ${N}.`))}function m(S){if(S.length===0)return null;let _=0,w=0,x=0;for(let g of S)typeof g=="string"&&(At(g)&&_++,et.lastIndex=0,et.test(g)&&w++,tt.lastIndex=0,tt.test(g)&&x++);let y=S.length;return _/y>=.3?"id":w/y>=.3?"phone":x/y>=.3?"financial":null}function v(S,_){if(_>yn){i.hit_depth_cap=!0;return}if(o>nt){i.hit_file_cap=!0;return}let w;try{w=Kr(S)}catch{return}for(let x of w){if(o>nt)return;let y=Pi(S,x),g;try{g=hn(y)}catch{continue}if(!g.isSymbolicLink())if(g.isDirectory()){if(Ni.has(x))continue;let N=null;try{N=Kr(y).length}catch{N=null}l(y,"folder",null,g.mtime??null,N),v(y,_+1)}else g.isFile()&&(l(y,"file",g.size,g.mtime??null,null),p(y,x))}}let k;try{k=hn(e.target_path).isDirectory()}catch{k=!1}return k?(e.log.info("folder-scanner: starting",{target_label:e.target_label,target_path:e.target_path,max_files:nt,max_depth:yn}),v(e.target_path,0),{target_id:e.target_id,target_label:e.target_label,target_path:e.target_path,files_walked:o,files_inspected:a,duration_ms:Date.now()-t,findings:n,inventory:r,coverage:i}):{target_id:e.target_id,target_label:e.target_label,target_path:e.target_path,files_walked:0,files_inspected:0,duration_ms:Date.now()-t,findings:[],inventory:[],coverage:i,error:"target_path_not_found_or_not_directory"}}var ot={info(){}};var Ke={critical:4,high:3,medium:2,low:1,info:0},Sn=["critical","high","medium","low","info"];function gn(e,t,n){let r=e.get(t)??{key:t,total:0,worst:"info",bySeverity:{}};r.total+=1,r.bySeverity[n.severity]=(r.bySeverity[n.severity]??0)+1,(Ke[n.severity]??0)>(Ke[r.worst]??0)&&(r.worst=n.severity),e.set(t,r)}function _n(e){return[...e.values()].sort((t,n)=>(Ke[n.worst]??0)-(Ke[t.worst]??0)||n.total-t.total||t.key.localeCompare(n.key))}function Ae(e){let t=e.findings??[],n={},r=new Map,o=new Map,a=new Map;for(let s of t){n[s.severity]=(n[s.severity]??0)+1;let l=s.finding_subkind&&!/^near_line/.test(s.finding_subkind)?s.finding_subkind:"";gn(r,l||s.finding_kind,s);let d=s.relative_path.replace(/\\/g,"/"),u=d.includes("/")?d.slice(0,d.indexOf("/")):".";gn(o,u,s),gn(a,d,s)}let i=_n(a);return{total:t.length,bySeverity:n,byType:_n(r),byFolder:_n(o),byFile:i,filesWithFindings:i.map(s=>s.key)}}function ae(e){return e.replace(/[&<>"']/g,t=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[t])}function bn(e,t,n){let r=`<tr><th>${ae(n)}</th><th>total</th>${Sn.map(a=>`<th class="${a}">${a}</th>`).join("")}</tr>`,o=t.map(a=>`<tr><td class="k">${ae(a.key)}</td><td>${a.total}</td>${Sn.map(i=>`<td>${a.bySeverity[i]??""}</td>`).join("")}</tr>`).join("");return`<h2>${ae(e)} <span class="n">${t.length}</span></h2><table>${r}${o}</table>`}function vn(e,t=Ae(e)){let n=Sn.filter(s=>t.bySeverity[s]).map(s=>`<span class="pill ${s}">${t.bySeverity[s]} ${s}</span>`).join(" "),r=e.coverage,o=[];r?.hit_file_cap&&o.push(`stopped at the ${r.max_files}-file cap`),r?.hit_depth_cap&&o.push(`folders deeper than ${r.max_depth} levels were not descended`),r?.files_too_large&&o.push(`${r.files_too_large} file(s) too large to read`),r?.documents_unreadable&&o.push(`${r.documents_unreadable} document(s) unreadable`);let a=[...e.findings??[]].sort((s,l)=>(Ke[l.severity]??0)-(Ke[s.severity]??0)),i=a.map(s=>`<tr><td><span class="pill ${s.severity}">${s.severity}</span></td><td>${ae(s.finding_subkind||s.finding_kind)}</td><td class="k">${ae(s.relative_path)}</td><td class="h">${ae(s.remediation_hint??"")}</td></tr>`).join("");return`<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
|
|
28
|
+
<title>NoData scan \xB7 ${ae(e.target_label||e.target_path)}</title>
|
|
29
|
+
<style>
|
|
30
|
+
body{margin:0;background:#FAF7F0;color:#1a1a1a;font:14px/1.5 Inter,Heebo,system-ui,sans-serif}
|
|
31
|
+
main{max-width:1100px;margin:0 auto;padding:28px 18px 60px}
|
|
32
|
+
h1{font-size:22px;margin:0 0 4px}h2{font-size:16px;margin:28px 0 8px}.n{color:#8A6B2D;font-weight:500}
|
|
33
|
+
.sub{color:#666;margin:0 0 14px}table{border-collapse:collapse;width:100%;background:#fff;border:1px solid #E9E1D2}
|
|
34
|
+
th,td{padding:6px 9px;border-bottom:1px solid #F0EADF;text-align:left;vertical-align:top}th{font-size:12px;color:#666;background:#FBF8F2}
|
|
35
|
+
td.k{font-family:ui-monospace,Menlo,monospace;font-size:12.5px;word-break:break-all}td.h{color:#555;font-size:12.5px}
|
|
36
|
+
.pill{display:inline-block;border-radius:999px;padding:1px 9px;font-size:12px;font-weight:600;background:#eee}
|
|
37
|
+
.critical{color:#8b1c1c}.pill.critical{background:#fde2e2}.high{color:#9a4b00}.pill.high{background:#feecd9}
|
|
38
|
+
.medium{color:#7a6400}.pill.medium{background:#fbf3cf}.low{color:#445}.pill.low{background:#eef0f4}
|
|
39
|
+
.note{margin-top:18px;color:#666;font-size:12.5px}
|
|
40
|
+
</style></head><body><main>
|
|
41
|
+
<h1>Scan \xB7 ${ae(e.target_label||e.target_path)}</h1>
|
|
42
|
+
<p class="sub">${ae(e.target_path)} \xB7 ${e.files_walked} files walked, ${e.files_inspected} inspected in ${e.duration_ms} ms \xB7 ran on this machine, nothing uploaded</p>
|
|
43
|
+
<p><strong>${t.total}</strong> findings ${n}</p>
|
|
44
|
+
${o.length?`<p class="note">Coverage: ${ae(o.join("; "))}.</p>`:""}
|
|
45
|
+
${bn("By type",t.byType,"type")}
|
|
46
|
+
${bn("By folder",t.byFolder,"folder")}
|
|
47
|
+
${bn("By file",t.byFile,"file")}
|
|
48
|
+
<h2>Every finding <span class="n">${a.length}</span></h2>
|
|
49
|
+
<table><tr><th>severity</th><th>type</th><th>file</th><th>what to do</th></tr>${i}</table>
|
|
50
|
+
<p class="note">Content-free: this report lists where and what kind \u2014 never a matched value.</p>
|
|
51
|
+
</main></body></html>`}var Mr={israeli_id:"[ID]",credit_card:"[CARD]",iban:"[IBAN]",israeli_phone:"[PHONE]",email:"[EMAIL]"},$i=/[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}/g;function wn(e,t,n=1){e[t]=(e[t]??0)+n}function at(e,t={}){let n=e;for(let r of un)r.pattern.lastIndex=0,n=n.replace(r.pattern,o=>r.validate(o)?(wn(t,r.subkind),Mr[r.subkind]??`[${r.subkind.toUpperCase()}]`):o);return n=n.replace($i,()=>(wn(t,"email"),Mr.email)),{text:n,counts:t,columnsHidden:[]}}function Fr(e,t){return e.includes(t)||e.includes('"')||e.includes(`
|
|
52
|
+
`)?`"${e.replace(/"/g,'""')}"`:e}function Bi(e){let t=(e.match(/\t/g)??[]).length,n=(e.match(/;/g)??[]).length,r=(e.match(/,/g)??[]).length;return t>r&&t>=n?" ":n>r?";":","}function En(e,t){let n=e.split(/\r?\n/),r=t??Bi(n[0]??""),o=Be(n[0]??"",r),a=o.map(l=>Qe(l)),i={},s=[o.map(l=>Fr(l,r)).join(r)];for(let l of n.slice(1)){if(l===""){s.push(l);continue}let d=Be(l,r).map((u,p)=>{let h=a[p];return h&&u.trim()!==""?(wn(i,`column:${h.type}`),`[${h.type.toUpperCase()}]`):at(u,i).text});s.push(d.map(u=>Fr(u,r)).join(r))}return{text:s.join(`
|
|
53
|
+
`),counts:i,columnsHidden:o.filter((l,d)=>a[d])}}var te=kr(to(),1);import{homedir as ps}from"node:os";import{basename as Rn,dirname as On,extname as fs,join as Ct,resolve as It}from"node:path";import{existsSync as ct,mkdirSync as hs,readFileSync as ys,rmSync as ms,statSync as Nn,writeFileSync as no}from"node:fs";import{pathToFileURL as $n}from"node:url";var q=(e,t=!1)=>({content:[{type:"text",text:e}],...t?{isError:t}:{}}),ro=Ct(ps(),".nodata","reports"),In=25;function Bn(e){return/\.ndc$/i.test(e)||/\.clean\.[A-Za-z0-9]+$/.test(e)}function gs(){return new Date().toISOString().replace(/[:.]/g,"-").slice(0,19)}function _s(e){return e.replace(/[^A-Za-z0-9_-]+/g,"_").slice(0,60)||"folder"}async function oo(e){return rt({target_id:"mcp",target_label:Rn(e),target_path:e,log:ot})}function Cn(e,t){let n=e.slice(0,t).map(r=>` ${String(r.total).padStart(6)} ${r.worst.padEnd(8)} ${r.key}`);return e.length>t&&n.push(` \u2026 ${e.length-t} more in the full report`),n.join(`
|
|
54
|
+
`)}function bs(e,t,n,r){if(e.error)return`Could not scan ${e.target_path}: ${e.error}`;let o=["critical","high","medium","low","info"].filter(i=>t.bySeverity[i]).map(i=>`${t.bySeverity[i]} ${i}`).join(" \xB7 "),a=[`SCAN ${e.target_path}`,` ${r} \xB7 ran on this machine, nothing uploaded`,` ${e.files_walked} files walked, ${e.files_inspected} inspected, ${e.duration_ms} ms`,"",`FOUND ${t.total} findings${o?" \u2014 "+o:""} in ${t.filesWithFindings.length} files`];return t.total>0&&(a.push("","BY TYPE (all)",Cn(t.byType,100)),a.push("","BY FOLDER",Cn(t.byFolder,10)),a.push("","WORST FILES",Cn(t.byFile,12))),n&&a.push("","FULL REPORT (every finding, content-free) \u2014 open in a browser:",` ${$n(n).href}`),t.total>0&&a.push("","NEXT \u2014 same workspace:",` \xB7 LOCK the ${t.filesWithFindings.length} files with findings: nodata_protect path: "${e.target_path}" (asks before it changes anything)`,' \xB7 WORK on a clean copy (values replaced by [CARD], [ID] \u2026): nodata_redact path: "<file>"'," \xB7 A database table instead of files: nodata_register_table \u2192 nodata_grant"),a.join(`
|
|
55
|
+
`)}function ao(e,t){e.registerTool("nodata_scan_folder",{description:"SEE what's sensitive. Scans a LOCAL folder for hardcoded secrets and unencrypted PII (checksum-validated Israeli ID, Luhn credit card, IBAN, phones), reading PDF and Office files too, entirely on this machine. Returns the WHOLE result \u2014 counts by type, by folder and by file \u2014 and writes a full content-free HTML report (every finding) to ~/.nodata/reports, with a link to open it. Then offers the next step in the same workspace: nodata_protect (lock the files with findings) or nodata_redact (a clean copy to work on). Call this when the user asks to scan/audit/check a folder.",inputSchema:{path:me.string().optional().describe("Folder to scan. Default: the directory the server runs in.")}},async({path:n})=>{let r=It((n??".").trim()||".");if(!ct(r))return q(`No folder found at: ${r}`);try{let o=await oo(r),a=Ae(o),i=null;return o.error||(hs(ro,{recursive:!0}),i=Ct(ro,`scan-${_s(Rn(r))}-${gs()}.html`),no(i,vn(o,a),{mode:384})),q(bs(o,a,i,t()))}catch(o){return q(`Scan failed: ${o instanceof Error?o.message:String(o)}`,!0)}}),e.registerTool("nodata_protect",{description:"LOCK files: seal each one to this device's key as <file>.ndc (AES-256-GCM, the key never leaves this machine; the same format as `nodata protect`, so `nodata open` opens it too). Given a folder, seals only the files the scan finds exposure in; given a file, seals that file. ASKS FIRST: without confirm:true it only lists what would be sealed and changes nothing \u2014 show that list to the user and call again with confirm:true only after they approve. Writes a local receipt (hashes, seal ids) under <folder>/.nodata/receipts. remove:true also deletes the plaintext originals.",inputSchema:{path:me.string().describe("File or folder to protect."),confirm:me.boolean().optional().describe("true = do it. Omit to preview."),remove:me.boolean().optional().describe("Delete the plaintext originals after sealing. Default false.")}},async({path:n,confirm:r,remove:o})=>{let a=It(n);if(!ct(a))return q(`Not found: ${a}`,!0);let i=Nn(a).isDirectory(),s;if(i?s=Ae(await oo(a)).filesWithFindings.map(v=>Ct(a,v)).filter(v=>ct(v)&&Nn(v).isFile()&&!Bn(v)):s=a.endsWith(".ndc")?[]:[a],s.length===0)return q(`Nothing to seal in ${a} \u2014 no file with findings.`);if(!r){let m=s.slice(0,In).map(v=>` \xB7 ${v}`);return s.length>In&&m.push(` \u2026 and ${s.length-In} more`),q([`PREVIEW \u2014 nothing changed yet. ${t()}`,`Would seal ${s.length} file(s) to this device's key${o?" and DELETE the plaintext originals":" (originals kept)"}:`,...m,"","Ask the user to approve, then call nodata_protect again with confirm: true."].join(`
|
|
56
|
+
`))}let{key:l,created:d}=te.ensureDeviceKey(),u=[];for(let m of s)u.push(await te.sealFile(m,l)),o&&ms(m);let p=i?a:On(a),h=te.writeLocalReceipt(p,{action:"protect",kid:l.kid,removed_plaintext:!!o,files:u,extra:{approved_by:t(),surface:"mcp"}});return q([`SEALED ${u.length} file(s) \u2014 ${t()}${d?" \xB7 a new device key was created at ~/.nodata/device-key.json (back it up: without it these files cannot be opened)":""}`,`device key id: ${l.kid}`,o?"Plaintext originals deleted.":"Originals are still in place \u2014 run again with remove: true to leave only the sealed copies.",`Receipt (hashes + seal ids, content-free): ${$n(h).href}`,'Open one again: nodata_open path: "<file>.ndc"'].join(`
|
|
57
|
+
`))}),e.registerTool("nodata_open",{description:"RELEASE a sealed file: open <file>.ndc back to its original next to it (never overwrites), with this device's key, and check its hash matches what was sealed. ASKS FIRST: without confirm:true it only says what would be opened. Writes a local receipt.",inputSchema:{path:me.string().describe("The .ndc file to open."),confirm:me.boolean().optional().describe("true = open it. Omit to preview.")}},async({path:n,confirm:r})=>{let o=It(n),a=ct(o)?te.readManifest(o):null;if(!a)return q(`Not a NoData sealed file: ${o}`,!0);if(!r)return q(`PREVIEW \u2014 nothing changed yet. ${t()}
|
|
58
|
+
Would open "${a.orig}" (sealed ${a.sealed_at}, device key ${a.kid}) as plaintext next to ${o}.
|
|
59
|
+
Ask the user to approve, then call nodata_open again with confirm: true.`);let i=await te.openFile(o);if(!i.ok){let l=i.error==="wrong_key"?"this device's key is not the one it was sealed to":i.error==="no_device_key"?"this machine has no device key (~/.nodata/device-key.json)":i.error;return q(`Could not open ${o}: ${l}.`,!0)}let s=te.writeLocalReceipt(On(o),{action:"open",kid:a.kid,removed_plaintext:!1,files:[{path:i.outPath,ndc:o,sha256:i.sha256,sealId:a.token.split(":").pop()??""}],extra:{approved_by:t(),surface:"mcp",hash_matches:i.intact}});return q([`OPENED ${i.outPath} \u2014 ${t()}`,i.intact?"Hash matches what was sealed \u2014 the file is unaltered.":"WARNING: hash differs from the sealed record.",`Receipt: ${$n(s).href}`].join(`
|
|
60
|
+
`))}),e.registerTool("nodata_redact",{description:"WORK on the rest: make a clean copy of a file with every sensitive value replaced by a typed token ([CARD], [ID], [IBAN], [PHONE], [EMAIL]); in CSV/TSV a column whose header names personal data is hidden whole, so rows and columns still line up. Same detectors as the scan. The original is untouched; the copy is written next to it as <name>.clean.<ext> (Office/PDF \u2192 .clean.txt). return_text:true also returns the clean text (up to 60 KB) so it can be analysed right here \u2014 it contains no detected value.",inputSchema:{path:me.string().describe("The file to redact (csv, tsv, txt, md, json, log, docx, xlsx, pptx, pdf)."),return_text:me.boolean().optional().describe("Also return the clean text for analysis.")}},async({path:n,return_text:r})=>{let o=It(n);if(!ct(o)||!Nn(o).isFile())return q(`Not a file: ${o}`,!0);let a=fs(o).toLowerCase(),i=ys(o),s,l=a||".txt";if(a===".csv"||a===".tsv")s=En(i.toString("utf8"),a===".tsv"?" ":void 0);else if(Pt.has(a)){let h=Tt(i,a);if(!h)return q(`Could not read the text of ${o}.`,!0);s=at(h.text),l=".txt"}else s=at(i.toString("utf8"));let d=Ct(On(o),`${Rn(o,a)}.clean${l}`);no(d,s.text,{mode:384});let u=Object.entries(s.counts).sort((h,m)=>m[1]-h[1]).map(([h,m])=>` ${String(m).padStart(6)} ${h}`),p=[`CLEAN COPY ${d} \u2014 ${t()} \xB7 original untouched`,u.length?`Replaced:
|
|
61
|
+
${u.join(`
|
|
62
|
+
`)}`:"Nothing sensitive detected \u2014 the copy equals the original text.",s.columnsHidden.length?`Columns hidden whole: ${s.columnsHidden.join(", ")}`:""].filter(Boolean);return r&&p.push("",`--- clean text${s.text.length>6e4?" (first 60000 chars)":""} ---`,s.text.slice(0,6e4)),q(p.join(`
|
|
63
|
+
`))})}var en=kr(ga(),1);import{z as $e}from"zod";import{createHash as Nl}from"node:crypto";import{existsSync as ur,mkdirSync as Il,readFileSync as wa,readdirSync as Cl,statSync as _a,writeFileSync as Rl}from"node:fs";import{homedir as $l}from"node:os";import{basename as dr,extname as Bl,join as Ea,resolve as Kl}from"node:path";var z=(e,t=!1)=>({content:[{type:"text",text:e}],...t?{isError:t}:{}}),Qt=Ea($l(),".nodata","shares"),jl=12*1024*1024,Ml={".pdf":"application/pdf",".txt":"text/plain",".csv":"text/csv",".md":"text/markdown",".json":"application/json",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".docx":"application/vnd.openxmlformats-officedocument.wordprocessingml.document",".xlsx":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",".pptx":"application/vnd.openxmlformats-officedocument.presentationml.presentation"};function ka(e){return Ea(Qt,`${e.replace(/[^a-f0-9]/gi,"")}.json`)}function ba(e){let t=ka(e);if(!ur(t))return null;try{return JSON.parse(wa(t,"utf8"))}catch{return null}}function Sa(e){let t=e.match(/\/lock\/open\/([a-f0-9]{8,64})/i);return(t?t[1]:e.trim()).toLowerCase()}async function va(e,t,n){let r=await fetch(e,{method:"POST",headers:{"content-type":"application/json",...n?{authorization:`Bearer ${n}`}:{}},body:JSON.stringify(t)});return{status:r.status,body:await r.json().catch(()=>({}))}}function xa(e,t,n,r){e.registerTool("nodata_send",{description:"SEND a file as a governed link: encrypted on this machine (post-quantum hybrid), stored by NoData only as ciphertext \u2014 the key rides in the link's #fragment, which NoData never receives. Expires after ttl and after max_opens opens; can be burned (nodata_burn) at any time, after which nobody can open it again. Filed under your organization with a signed receipt and a proof_url. ASKS FIRST: without confirm:true it only shows what would be sent. Returns the link to hand to the recipient.",inputSchema:{path:$e.string().describe("The file to send (up to 12 MB)."),ttl_hours:$e.number().optional().describe("Hours until the link expires. Default 72, max 168 (7 days)."),max_opens:$e.number().optional().describe("Opens allowed before it burns itself. Default 3, max 1000."),confirm:$e.boolean().optional().describe("true = send it. Omit to preview.")}},async({path:o,ttl_hours:a,max_opens:i,confirm:s})=>{let l=Kl(o);if(!ur(l)||!_a(l).isFile())return z(`Not a file: ${l}`,!0);let d=_a(l).size;if(d>jl)return z(`${dr(l)} is ${(d/1048576).toFixed(1)} MB; a governed link carries up to 12 MB.`,!0);let u=Math.round(Math.min(Math.max(a??72,1/60),168)*3600),p=Math.round(Math.min(Math.max(i??3,1),1e3));if(!s)return z([`PREVIEW \u2014 nothing sent yet. ${r()}`,`Would send "${dr(l)}" (${(d/1024).toFixed(1)} KB) as a governed link:`," \xB7 encrypted here; NoData stores only ciphertext and never gets the key",` \xB7 expires in ${(u/3600).toFixed(u<3600?2:0)} h, or after ${p} open(s)`," \xB7 revocable any time with nodata_burn; every open is counted","","Ask the user to approve, then call nodata_send again with the same arguments and confirm: true."].join(`
|
|
64
|
+
`));let h=wa(l),m=dr(l),v=Ml[Bl(l).toLowerCase()]??"application/octet-stream",k=await(0,en.sealBytesForPublicShare)({bytes:h,filename:m,contentType:v,ttlSeconds:u,server:t}),S=await(0,en.wrapFragmentForShortLink)(k.fragment),_;try{_=await va(`${t}/api/lock/public/issue`,{formatVersion:3,lockboxId:k.lockboxId,containerB64:Buffer.from(k.container).toString("base64"),filename:m,contentType:v,ttlSeconds:u,maxOpens:p,wrappedFragmentB64:S.wrappedFragmentB64,wrapIvB64:S.wrapIvB64},await n())}catch(y){return z(`Could not reach NoData: ${y instanceof Error?y.message:String(y)}`,!0)}if(_.status>=400||_.body.ok!==!0)return z(`Send refused (HTTP ${_.status}): ${JSON.stringify(_.body)}`,!0);let w=String(_.body.id),x={id:w,file:l,filename:m,sha256:Nl("sha256").update(h).digest("hex"),link:`${t}/lock/open/${w}#${S.wrapKeyB64Url}`,wrap_key_b64url:S.wrapKeyB64Url,expires_at:String(_.body.expiresAt??""),max_opens:p,sent_by:r(),sent_at:new Date().toISOString(),receipt_id:_.body.receipt_id??null,proof_url:_.body.proof_url??null};return Il(Qt,{recursive:!0}),Rl(ka(w),JSON.stringify(x,null,2)+`
|
|
65
|
+
`,{mode:384}),z([`SENT "${m}" \u2014 ${r()}`,"Link (give this to the recipient; anyone holding it can open it until it expires or is burned):",` ${x.link}`,`Expires ${x.expires_at} \xB7 max ${p} open(s) \xB7 id ${w}`,x.proof_url?`Proof (signed receipt, public): ${x.proof_url}`:"No receipt: the link was not attributed to an organization.",`Check it: nodata_link_status id: "${w}" \xB7 Revoke it: nodata_burn id: "${w}"`].join(`
|
|
66
|
+
`))}),e.registerTool("nodata_link_status",{description:"STATUS of links sent with nodata_send: opens so far, expiry, whether burned. Pass an id or link for one; omit to list every link sent from this machine.",inputSchema:{id:$e.string().optional().describe("Share id or /lock/open link. Omit to list all.")}},async({id:o})=>{let a=o?[Sa(o)]:ur(Qt)?Cl(Qt).filter(s=>s.endsWith(".json")).map(s=>s.slice(0,-5)):[];if(a.length===0)return z("No links sent from this machine yet. Send one with nodata_send.");let i=[`LINKS \u2014 ${r()}`];for(let s of a.slice(0,50)){let l=ba(s),d={};try{let p=await fetch(`${t}/api/lock/public/status/${s}`);d=await p.json().catch(()=>({})),p.status===404&&(d={missing:!0})}catch{d={unreachable:!0}}let u=d.missing?"not found":d.unreachable?"status unavailable":d.burned?"BURNED":d.expired?"expired":"live";i.push(` ${s} ${u.padEnd(10)} opens ${d.openCount??"?"}/${d.maxOpens??l?.max_opens??"?"} expires ${d.expiresAt??l?.expires_at??"?"} ${l?l.filename:""}`)}return z(i.join(`
|
|
67
|
+
`))}),e.registerTool("nodata_burn",{description:"BURN a link sent with nodata_send: the stored ciphertext is zeroed, so nobody \u2014 the recipient, a forwarded copy, NoData \u2014 can open it again. Irreversible. ASKS FIRST: without confirm:true it only says what would be burned. Returns the signed burn receipt and its proof_url.",inputSchema:{id:$e.string().describe("Share id or the /lock/open link."),confirm:$e.boolean().optional().describe("true = burn it. Omit to preview.")}},async({id:o,confirm:a})=>{let i=Sa(o),s=o.match(/#([A-Za-z0-9_-]{43})/)?.[1],l=ba(i),d=l?.wrap_key_b64url??s;if(!d)return z(`No burn key for ${i} on this machine. Pass the full link (it carries the key after #), or burn it from the machine that sent it.`,!0);if(!a)return z(`PREVIEW \u2014 nothing burned yet. ${r()}
|
|
68
|
+
Would burn ${l?`"${l.filename}" `:""}(${i}). After this NOBODY can open it again \u2014 irreversible.
|
|
69
|
+
Ask the user to approve, then call nodata_burn again with confirm: true.`);let u;try{u=await va(`${t}/api/lock/public/burn/${i}`,{wrapKeyB64Url:d})}catch(p){return z(`Could not reach NoData: ${p instanceof Error?p.message:String(p)}`,!0)}return u.status>=400||u.body.ok!==!0?z(`Burn refused (HTTP ${u.status}): ${JSON.stringify(u.body)}`,!0):z([`BURNED ${i} \u2014 ${r()}. The ciphertext is zeroed; the link is dead for everyone.`,u.body.proof_url?`Proof (signed receipt, public): ${u.body.proof_url}`:""].filter(Boolean).join(`
|
|
70
|
+
`))})}import{z as tn}from"zod";import ke from"node:crypto";var pr=Buffer.from([78,68,67,49]),Fl=2,fr=36,Et=32,Ll=64,Ul=12,Hl=16,Vl=4096,Gl=256,Aa=32,hr=8,ql=1;async function Wl(){let[{CipherSuite:e,HkdfSha256:t},{DhkemX25519HkdfSha256:n},{Chacha20Poly1305:r}]=await Promise.all([import("@hpke/core"),import("@hpke/dhkem-x25519"),import("@hpke/chacha20poly1305")]);return new e({kem:new n,kdf:new t,aead:new r})}function yr(e){let t=new Uint8Array(e.length);return t.set(e),t.buffer}async function Jl(e,t){let n=t.trim();if(n.includes("-----BEGIN PUBLIC KEY-----")){let o=n.replace(/-----BEGIN PUBLIC KEY-----/,"").replace(/-----END PUBLIC KEY-----/,"").replace(/\s+/g,"");return e.kem.deserializePublicKey(yr(Buffer.from(o,"base64")))}let r=Buffer.from(n.replace(/-/g,"+").replace(/_/g,"/"),"base64");if(r.length!==32)throw new Error(`master pubkey must be a 32-byte X25519 key, got ${r.length} bytes`);return e.kem.deserializePublicKey(yr(r))}function zl(e){let t=ke.createPublicKey({key:e,format:"pem"}).export({format:"der",type:"spki"});if(t.length<Et)throw new Error("unexpected Ed25519 SPKI DER length");return t.subarray(t.length-Et)}function Yl(e){return ke.createHash("sha256").update(e,"utf8").digest().subarray(0,hr)}async function Ta(e){let t=Buffer.from(e.filename,"utf8");if(t.length>Vl)throw new Error("filename too long");let n=Buffer.from(e.contentType,"utf8");if(n.length>Gl)throw new Error("content-type too long");let r=e.receiptId??ke.randomUUID(),o=Buffer.from(r,"utf8");if(o.length!==fr)throw new Error("receiptId must be a 36-char canonical UUID");let a=zl(e.issuerPubkeyPem);if(a.length!==Et)throw new Error("issuer pubkey must be 32 bytes");let i=ke.randomBytes(32),s=ke.randomBytes(Ul),l=ke.createCipheriv("aes-256-gcm",i,s),d=Buffer.concat([l.update(e.fileBytes),l.final()]),u=l.getAuthTag();if(u.length!==Hl)throw new Error("unexpected GCM tag length");let p=ke.createHash("sha256").update(e.fileBytes).digest(),h=await Wl(),m=await Jl(h,e.recipientPubkeyB64),v=await h.createSenderContext({recipientPublicKey:m}),k=Buffer.from(v.enc),S=Buffer.from(await v.seal(yr(i))),_=Yl(e.recipientPubkeyB64),w=1+hr+2+k.length+2+S.length,x=pr.length+1+fr+Et+2+t.length+2+n.length+8+Aa+w,y=Buffer.alloc(x),g=0;pr.copy(y,g),g+=pr.length,y[g++]=Fl,o.copy(y,g),g+=fr,a.copy(y,g),g+=Et,y.writeUInt16LE(t.length,g),g+=2,t.copy(y,g),g+=t.length,y.writeUInt16LE(n.length,g),g+=2,n.copy(y,g),g+=n.length,y.writeBigUInt64LE(BigInt(e.issuedAt??Date.now()),g),g+=8,p.copy(y,g),g+=Aa,y[g++]=ql,_.copy(y,g),g+=hr,y.writeUInt16LE(k.length,g),g+=2,k.copy(y,g),g+=k.length,y.writeUInt16LE(S.length,g),g+=2,S.copy(y,g),g+=S.length;let N=ke.sign(null,y,e.issuerPrivateKey);if(N.length!==Ll)throw new Error("header signature must be 64 bytes");let $=Buffer.concat([y,N,s,u,d]),D={relative_path:"",plaintext_sha256:p.toString("hex"),size_bytes:e.fileBytes.length,lockbox_id:e.lockboxId??null,ndc_version:2,recovery_alg:1,recovery_master_fp:_.toString("hex"),header_sig_b64:N.toString("base64"),content_key_b64:i.toString("base64")};return{ndcBytes:$,report:D}}import{createPrivateKey as Pa,createPublicKey as Da,generateKeyPairSync as Xl}from"node:crypto";import{existsSync as gr,mkdirSync as Zl,readFileSync as Ia,rmSync as Ql,statSync as nn,writeFileSync as Ca}from"node:fs";import{homedir as Oa}from"node:os";import{basename as kt,extname as ed,join as _r,resolve as td}from"node:path";var ue=(e,t=!1)=>({content:[{type:"text",text:e}],...t?{isError:t}:{}}),xt="mcp-archive",mr=25,Na=25*1024*1024,nd={".pdf":"application/pdf",".txt":"text/plain",".csv":"text/csv",".md":"text/markdown",".json":"application/json",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".docx":"application/vnd.openxmlformats-officedocument.wordprocessingml.document",".xlsx":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",".pptx":"application/vnd.openxmlformats-officedocument.presentationml.presentation"},rd={critical:"restricted",high:"confidential",medium:"internal",low:"internal",info:"internal"};function Ra(e,t){if(e){let o=Pa({key:Buffer.from(e,"base64"),format:"der",type:"pkcs8"});return{privateKey:o,publicPem:Da(o).export({format:"pem",type:"spki"}),label:`device ${t??""}`.trim()}}let n=_r(Oa(),".nodata","issuer-ed25519.json");if(gr(n)){let o=JSON.parse(Ia(n,"utf8")).private_pem,a=Pa(o);return{privateKey:a,publicPem:Da(a).export({format:"pem",type:"spki"}),label:"this machine"}}let r=Xl("ed25519");return Zl(_r(Oa(),".nodata"),{recursive:!0}),Ca(n,JSON.stringify({private_pem:r.privateKey.export({format:"pem",type:"pkcs8"})},null,2)+`
|
|
71
|
+
`,{mode:384}),{privateKey:r.privateKey,publicPem:r.publicKey.export({format:"pem",type:"spki"}),label:"this machine"}}function $a(e,t,n,r){e.registerTool("nodata_wrap",{description:"WRAP files into your organization's sovereign archive (a zero-knowledge capsule): each file is encrypted ON THIS MACHINE to the public half of your org master key \u2014 the 12 words from signup \u2014 and only ciphertext is uploaded. NoData can never open it; your 12 words (or recovery file) always can, even if this computer is lost or NoData is offline. Each document gets a signed receipt and proof_url. Given a folder, wraps the files the scan finds exposure in (classified by severity); given a file, wraps that file. ASKS FIRST: without confirm:true it only lists what would be wrapped. keep_local:true (default) also writes <file>.capsule.ndc next to the original; remove:true deletes the plaintext originals after a successful upload.",inputSchema:{path:tn.string().describe("File or folder to wrap."),confirm:tn.boolean().optional().describe("true = wrap it. Omit to preview."),keep_local:tn.boolean().optional().describe("Also keep <file>.capsule.ndc next to the original. Default true."),remove:tn.boolean().optional().describe("Delete plaintext originals after upload. Default false.")}},async({path:o,confirm:a,keep_local:i,remove:s})=>{let l=td(o);if(!gr(l))return ue(`Not found: ${l}`,!0);let d;if(nn(l).isDirectory()?d=Ae(await rt({target_id:"mcp",target_label:kt(l),target_path:l,log:ot})).byFile.map(g=>({path:_r(l,g.key),classification:rd[g.worst]??"internal"})):d=[{path:l,classification:"confidential"}],d=d.filter(y=>gr(y.path)&&nn(y.path).isFile()&&!Bn(y.path)),d.length===0)return ue(`Nothing to wrap in ${l} \u2014 no file with findings.`);let u=d.filter(y=>nn(y.path).size>Na);d=d.filter(y=>nn(y.path).size<=Na);let p=await t.get("/api/v1/recovery/pubkey");if(p.status===401||p.status===403)return ue(`Not authorized to read the org key (HTTP ${p.status}). Connect with nodata_connect.`,!0);let h=typeof p.body.pubkeyB64=="string"?p.body.pubkeyB64:null;if(!h)return ue(`Your organization has no master key yet \u2014 the 12-word recovery setup was not completed, so there is nothing to wrap to.
|
|
72
|
+
Finish it once in the console (Recovery setup), then wrap again. NoData never sees the words.`,!0);if(!a){let y=d.slice(0,mr).map(g=>` \xB7 [${g.classification}] ${g.path}`);return d.length>mr&&y.push(` \u2026 and ${d.length-mr} more`),ue([`PREVIEW \u2014 nothing wrapped yet. ${r()}`,`Would wrap ${d.length} file(s) into the "${xt}" capsule, sealed to your org master key (fingerprint ${p.body.fingerprint??"?"}):`,...y,u.length?`Skipped (over 25 MB): ${u.map(g=>kt(g.path)).join(", ")}`:"",`Encrypted here; only ciphertext is uploaded. Opens with your 12 words \u2014 never with NoData.${s?" Plaintext originals WILL BE DELETED after upload.":""}`,"","Ask the user to approve, then call nodata_wrap again with the same arguments and confirm: true."].filter(Boolean).join(`
|
|
73
|
+
`))}let m=await t.get("/api/v1/capsules");if(m.status>=400)return ue(`Could not list capsules (HTTP ${m.status}): ${JSON.stringify(m.body)}`,!0);let k=(m.body.capsules??[]).find(y=>y.slug===xt);if(k&&k.key_mode!=="zk")return ue(`A "${xt}" capsule exists but is not zero-knowledge (key_mode ${String(k.key_mode)}) \u2014 refusing to wrap into it.`,!0);if(!k){let y=await t.post("/api/v1/capsules",{handle:xt,display_name:"MCP archive",key_mode:"zk",capsule_pubkey:h});if(y.status>=400)return ue(`Could not create the archive capsule (HTTP ${y.status}): ${JSON.stringify(y.body)}`,!0);k=y.body}let S=String(k.slug??k.capsule_id??"");if(!S)return ue(`Capsule id missing in ${JSON.stringify(k)}`,!0);let _=n(),w=[],x=[];for(let y of d){let g=Ia(y.path),{ndcBytes:N,report:$}=await Ta({fileBytes:g,filename:kt(y.path),contentType:nd[ed(y.path).toLowerCase()]??"application/octet-stream",recipientPubkeyB64:h,issuerPrivateKey:_.privateKey,issuerPubkeyPem:_.publicPem}),D=await t.post(`/api/v1/capsules/${encodeURIComponent(S)}/documents`,{title:kt(y.path),ndc_b64:N.toString("base64"),classification:y.classification,plaintext_sha256:$.plaintext_sha256,size_bytes:$.size_bytes});if(D.status>=400||D.body.ok!==!0){x.push(` \u2717 ${y.path} \u2014 HTTP ${D.status}: ${JSON.stringify(D.body).slice(0,200)}`);continue}i!==!1&&Ca(`${y.path}.capsule.ndc`,N,{mode:384}),s&&Ql(y.path),w.push(` \u2713 [${y.classification}] ${kt(y.path)}${D.body.proof_url?` proof: ${D.body.proof_url}`:""}`)}return ue([`WRAPPED ${w.length}/${d.length} into "${xt}" \u2014 ${r()} \xB7 signed by ${_.label}`,...w,...x,"Sealed to your org master key: NoData stores ciphertext only and cannot open it. Your 12 words (or recovery file) open every document.",i!==!1?"Local copies: <file>.capsule.ndc next to each original.":"",s?"Plaintext originals deleted (only for files that uploaded).":""].filter(Boolean).join(`
|
|
74
|
+
`),x.length>0&&w.length===0)})}import{homedir as La,hostname as Ua}from"node:os";import{join as rn,resolve as br}from"node:path";import{existsSync as vr,readFileSync as Ha,writeFileSync as Va,mkdirSync as Ga,chmodSync as id}from"node:fs";import{spawn as sd}from"node:child_process";import{generateKeyPairSync as cd,createPrivateKey as ld,sign as dd,randomBytes as ud}from"node:crypto";var wr="1.3.0",qa=rn(La(),".nodata"),on=rn(qa,"credentials.json");function pd(){try{if(!vr(on))return null;let e=JSON.parse(Ha(on,"utf8"));if(!e)return null;let t=e.device&&typeof e.device.private_key_pkcs8_b64=="string",n=typeof e.api_key=="string"&&e.api_key;return t||n?e:null}catch{return null}}function Ba(e){Ga(qa,{recursive:!0});let t=JSON.stringify({...e,saved_at:new Date().toISOString()},null,2);Va(on,t,{mode:384});try{id(on,384)}catch{}}var fd=`nodata-mcp v${wr} \u2014 NoData MCP server
|
|
22
75
|
|
|
23
76
|
ADMIN mode: nodata-mcp --api-key sk_live_...
|
|
24
77
|
AGENT mode: nodata-mcp --grant-token ndca-...
|
|
@@ -27,11 +80,15 @@ import{McpServer as gt}from"@modelcontextprotocol/sdk/server/mcp.js";import{Stdi
|
|
|
27
80
|
|
|
28
81
|
Env vars: NODATA_API_KEY \xB7 NODATA_GRANT_TOKEN \xB7 NODATA_BASE_URL
|
|
29
82
|
Get a free API key: https://www.nodatacapsule.com/developers/get-started
|
|
30
|
-
Mint a grant token: POST /api/v1/governance/grant (or the nodata_grant tool).`;function
|
|
31
|
-
${t}`}],isError:!0}}function Nt(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 Ot=5*6e4;function Dt(){let{publicKey:e,privateKey:t}=Et("ed25519"),n=e.export({format:"der",type:"spki"}),i=t.export({format:"der",type:"pkcs8"});return{publicKeyHex:n.subarray(-32).toString("hex"),privateKeyPkcs8B64:i.toString("base64")}}function Lt(e,t){let n=Tt({key:Buffer.from(e,"base64"),format:"der",type:"pkcs8"});return At(null,Buffer.from(t,"utf8"),n).toString("base64")}function Ft(){let e=Ae().toLowerCase().replace(/[^a-z0-9-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,20)||"device";return`${/^[a-z]/.test(e)?e:`d-${e}`}-${It(3).toString("hex")}`.slice(0,32)}async function jt(e,t,n,i,r){let o=await A(e,t,"/api/v1/attest/devices",{handle:n,label:i,ed25519_pubkey_hex:r});if(o.ok){let a=o.body.org_id??"";return a?{ok:!0,orgId:a}:{ok:!1,status:o.status,error:"enroll response missing org_id"}}return{ok:!1,status:o.status,error:o.body?.error??`HTTP ${o.status}`}}async function Mt(e,t){let n=await A(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:i,nonce:r}=n.body;if(!i||!r)throw new Error("challenge response malformed");let o=Lt(t.private_key_pkcs8_b64,i),a=await A(e,"","/api/v1/attest",{org_id:t.org_id,handle:t.handle,nonce:r,signature:o});if(!a.ok)throw new Error(`attest: ${a.body?.error??`HTTP ${a.status}`}`);let s=a.body;if(!s.allowed||!s.access_token)throw new Error(`attestation rejected: ${s.reason??"denied"}`);return{token:s.access_token,expiresAtMs:s.expires_at?Date.parse(s.expires_at):Date.now()+15*6e4}}function Bt(e,t){let n=null;return async()=>((!n||Date.now()>=n.expiresAtMs-Ot)&&(n=await Mt(e,t)),n.token)}function xe(e,t,n){e.registerTool("nodata_register_table",{description:"Register one of your own tables as AI-agent-readable ('connect your data'). Declares which columns are encrypted (per-column key release) and which are plaintext metadata. After this, grants can target the table.",inputSchema:{table_name:c.string().describe("Your SQL table name"),encrypted_columns:c.array(c.string()).describe("Columns stored as <col>_ct/_iv/_tag triplets"),plaintext_columns:c.array(c.string()).optional().describe("Plaintext metadata/filter columns"),classification_column:c.string().optional().describe("Plaintext column carrying the classification value")}},async({table_name:i,encrypted_columns:r,plaintext_columns:o,classification_column:a})=>{let s=await A(t,n,"/api/v1/governance/tables",{table_name:i,encrypted_columns:r,plaintext_columns:o??[],classification_column:a});return I(s)}),e.registerTool("nodata_grant",{description:"Issue an 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.",inputSchema:{agent:c.string().describe("Agent label (becomes its handle)"),table:c.string().optional().describe("Target table (default agent_demo_records)"),columns:c.array(c.string()).describe("Columns the agent may read"),where:c.record(c.string(),c.union([c.string(),c.number(),c.boolean()])).optional().describe("Equality filter (plaintext cols only)"),classifications:c.array(c.string()).optional().describe("Allowed classification values; empty = no gating"),ttl_seconds:c.number().optional().describe("Token lifetime (default 30d, max 1y)")}},async({agent:i,table:r,columns:o,where:a,classifications:s,ttl_seconds:l})=>{let d=await A(t,n,"/api/v1/governance/grant",{agent:i,table:r,columns:o,where:a,classifications:s,ttl_seconds:l});return I(d)}),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:c.string().optional().describe("Agent handle to revoke"),jti:c.string().optional().describe("Specific credential jti to revoke"),reason:c.string().optional()}},async({handle:i,jti:r,reason:o})=>{let a=await A(t,n,"/api/v1/governance/revoke",{handle:i,jti:r,reason:o});return I(a)}),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:c.string(),value:c.string(),context:c.string().optional()}},async({field:i,value:r,context:o})=>{let a={field:i,value:r};return o&&(a.context=o),I(await A(t,n,"/api/v1/encrypt",a))}),e.registerTool("nodata_decrypt",{description:"Decrypt a Capsule ciphertext back to plaintext (aes256gcm:v1:iv:cipher:key format).",inputSchema:{ciphertext:c.string(),field:c.string().optional(),requester:c.string().optional()}},async({ciphertext:i,field:r,requester:o})=>{let a={ciphertext:i};return r&&(a.field=r),o&&(a.requester=o),I(await A(t,n,"/api/v1/decrypt",a))}),e.registerTool("nodata_deliver",{description:"Create a burn-after-read secure link for delivering sensitive content. Returns a view URL and OTP.",inputSchema:{content:c.string(),to:c.string().optional(),maxViews:c.number().optional(),ttl:c.string().optional(),burn:c.boolean().optional()}},async({content:i,to:r,maxViews:o,ttl:a,burn:s})=>{let l={content:i};return r&&(l.to=r),o!==void 0&&(l.maxViews=o),a&&(l.ttl=a),s!==void 0&&(l.burn=s),I(await A(t,n,"/api/v1/deliver",l))}),e.registerTool("nodata_evidence",{description:"Retrieve the audit trail of governance/encryption events. Metadata only \u2014 never content, keys, or plaintext.",inputSchema:{from:c.string().optional(),to:c.string().optional(),action:c.string().optional(),limit:c.number().optional()}},async({from:i,to:r,action:o,limit:a})=>{let s={from:i,to:r,action:o,limit:a!==void 0?String(a):void 0};return I(await Pt(t,n,"/api/v1/evidence",s))})}function Ut(e,t,n){let i=Nt(n);i||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:c.string().describe("Table to check (must be in your grant)"),columns:c.array(c.string()).describe("Columns you want to reach"),where:c.record(c.string(),c.union([c.string(),c.number(),c.boolean()])).optional().describe("Equality filter (readable columns only)")}},async({table:r,columns:o,where:a})=>{let s=await A(t,n,"/api/access/decide",{resource:{table:r,columns:o,where:a},intent:"read"});return I(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:c.string().describe("Table to retrieve from (must be in your grant)"),columns:c.array(c.string()).describe("Columns to include in context"),where:c.record(c.string(),c.union([c.string(),c.number(),c.boolean()])).optional(),top_k:c.number().optional().describe("Max rows (default 50, max 200)")}},async({table:r,columns:o,where:a,top_k:s})=>{let l=await A(t,n,"/api/access/retrieve",{resource:{table:r,columns:o,where:a},top_k:s});return I(l)}),e.registerTool("nodata_read",{description:"Read governed data within this agent's grant. You may only request columns your grant allows \u2014 denied columns never decrypt server-side, and every read emits a cryptographic receipt. This tool is hard-scoped to the grant token this server was started with.",inputSchema:{table:c.string().describe("Table to read (must be in your grant)"),columns:c.array(c.string()).describe("Columns to read (must be in your grant)"),where:c.record(c.string(),c.union([c.string(),c.number(),c.boolean()])).optional(),limit:c.number().optional().describe("Max rows (default 50, max 200)")}},async({table:r,columns:o,where:a,limit:s})=>{if(!i)return{content:[{type:"text",text:"Error: could not derive agent handle from grant token."}],isError:!0};let l=await A(t,n,`/api/agents/${encodeURIComponent(i)}/read`,{table:r,columns:o,where:a,limit:s});return I(l)}),e.registerTool("nodata_use",{description:"Invoke a pre-registered capability (deploy, send, charge, query, \u2026) WITHOUT receiving the secret. The Capsule injects the sealed credential server-side and returns only the result. You may invoke only capabilities your grant allows; the secret never reaches you. Hard-scoped to the grant token this server was started with.",inputSchema:{capability:c.string().describe("Capability name to invoke (must be in your grant, e.g. 'deploy-prod')"),params:c.record(c.string(),c.unknown()).optional().describe("Allowlisted params; unknown keys are dropped server-side"),resource_key:c.string().optional().describe("Optional folder/resource the action targets (enforced against corpus scope)")}},async({capability:r,params:o,resource_key:a})=>{if(!i)return{content:[{type:"text",text:"Error: could not derive agent handle from grant token."}],isError:!0};let s=await A(t,n,`/api/agents/${encodeURIComponent(i)}/use`,{capability:r,params:o,resource_key:a});return I(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:c.string().describe("The code capsule to advise on (you must be granted on it)"),question:c.string().optional().describe("What to fix / improve, in natural language"),note:c.string().optional().describe("Extra context for the advisor"),error:c.object({message:c.string().optional(),stack:c.string().optional(),kind:c.string().optional()}).optional().describe("An error the code produced, to guide the fix"),steer:c.string().optional().describe("A steer on a refine turn (e.g. 'no, round half-up')"),prior_diff:c.string().optional().describe("The previously proposed diff, to refine")}},async({capsule_id:r,question:o,note:a,error:s,steer:l,prior_diff:d})=>{if(!i)return{content:[{type:"text",text:"Error: could not derive agent handle from grant token."}],isError:!0};let p=await A(t,n,`/api/agents/${encodeURIComponent(i)}/code-capsule/${encodeURIComponent(r)}/advise`,{question:o,note:a,error:s,steer:l,prior_diff:d});return I(p)}),e.registerTool("nodata_code_patch",{description:"Submit a fix to a code capsule as a SIGNED, queued patch WITHOUT seeing its source. Provide a raw unified `diff`, or a whole-file `replace` ({path, content}) that is diffed server-side against the sealed source. The source is never persisted or returned; you get back a patch id, the diff hash, and a receipt. Requires a capsule grant (scope.fabric_developers). Hard-scoped to this server's grant token.",inputSchema:{capsule_id:c.string().describe("The code capsule to patch (you must be granted on it)"),summary:c.string().optional().describe("Short human-readable summary of the fix"),diff:c.string().optional().describe("A raw unified diff (advanced)"),replace:c.object({path:c.string(),content:c.string()}).optional().describe("Whole-file replacement; the diff is synthesized server-side against sealed source")}},async({capsule_id:r,summary:o,diff:a,replace:s})=>{if(!i)return{content:[{type:"text",text:"Error: could not derive agent handle from grant token."}],isError:!0};let l=await A(t,n,`/api/agents/${encodeURIComponent(i)}/code-capsule/${encodeURIComponent(r)}/patch`,{summary:o,diff:a,replace:s});return I(l)})}var Se=`WHAT NODATA DOES \u2014 in one line:
|
|
83
|
+
Mint a grant token: POST /api/v1/governance/grant (or the nodata_grant tool).`;function hd(e){let t="",n="",r="https://www.nodatacapsule.com";for(let i=0;i<e.length;i++)e[i]==="--api-key"&&e[i+1]?t=e[++i]:e[i]==="--grant-token"&&e[i+1]?n=e[++i]:e[i]==="--base-url"&&e[i+1]?r=e[++i]:e[i]==="--help"||e[i]==="-h"?(console.log(fd),process.exit(0)):e[i]==="--version"||e[i]==="-v"?(console.log(wr),process.exit(0)):e[i].startsWith("--")&&console.error(`nodata-mcp: unknown option '${e[i]}' (see --help)`);let o=t||n?"flag":"none";!t&&process.env.NODATA_API_KEY&&(t=process.env.NODATA_API_KEY,o="env"),!n&&process.env.NODATA_GRANT_TOKEN&&(n=process.env.NODATA_GRANT_TOKEN,o==="none"&&(o="env")),process.env.NODATA_BASE_URL&&(r=process.env.NODATA_BASE_URL);let a;if(!t&&!n){let i=pd();i&&(!process.env.NODATA_BASE_URL&&r==="https://www.nodatacapsule.com"&&i.base_url&&(r=i.base_url),i.device?(a=i.device,o="stored"):i.api_key&&(t=i.api_key,o="stored"))}return r=r.replace(/\/+$/,""),{apiKey:t,grantToken:n,baseUrl:r,credentialSource:o,device:a}}var Ka=3e4;async function Wa(e,t){let n;try{n=await fetch(e,{...t,signal:AbortSignal.timeout(Ka)})}catch(o){return{ok:!1,status:0,body:{error:o instanceof Error&&o.name==="TimeoutError"?`Request timed out after ${Ka/1e3}s: ${e}`:`Network error reaching ${e}: ${o instanceof Error?o.message:String(o)}`}}}let r;try{r=await n.json()}catch{r={error:`Non-JSON response (HTTP ${n.status})`}}return{ok:n.ok,status:n.status,body:r}}async function an(e){if(typeof e=="string")return{token:e};try{return{token:await e()}}catch(t){return{error:{ok:!1,status:0,body:{error:`Could not obtain an access token: ${t instanceof Error?t.message:String(t)}`}}}}}async function H(e,t,n,r){let o=await an(t);return"error"in o?o.error:Wa(`${e}${n}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${o.token}`},body:JSON.stringify(r)})}async function Sr(e,t,n,r){let o=await an(t);if("error"in o)return o.error;let a=new URL(`${e}${n}`);for(let[i,s]of Object.entries(r))s!==void 0&&s!==""&&a.searchParams.set(i,s);return Wa(a.toString(),{method:"GET",headers:{Authorization:`Bearer ${o.token}`}})}function U(e){let t=JSON.stringify(e.body,null,2);return e.ok?{content:[{type:"text",text:t}]}:{content:[{type:"text",text:`Error (HTTP ${e.status}):
|
|
84
|
+
${t}`}],isError:!0}}function yd(e){let t=e?[br(e)]:[br(".env.local"),br(".env")];if(e&&!vr(t[0]))return{error:`env file not found: ${t[0]}`};let n={},r=[];for(let a of t)if(vr(a)){r.push(a);for(let i of Ha(a,"utf8").split(/\r?\n/)){let s=i.match(/^\s*(?:export\s+)?([A-Z0-9_]+)\s*=\s*(.*)\s*$/);!s||s[1]in n||(n[s[1]]=s[2].replace(/^(['"])(.*)\1$/,"$2").trim())}}let o=a=>{for(let i of a){let s=n[i]??process.env[i];if(s)return{name:i,value:s}}};return{url:o(["SUPABASE_URL","NEXT_PUBLIC_SUPABASE_URL","VITE_SUPABASE_URL","EXPO_PUBLIC_SUPABASE_URL"]),anon:o(["SUPABASE_ANON_KEY","NEXT_PUBLIC_SUPABASE_ANON_KEY","VITE_SUPABASE_ANON_KEY","EXPO_PUBLIC_SUPABASE_ANON_KEY","SUPABASE_PUBLISHABLE_KEY","NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY"]),jwt:o(["SUPABASE_JWT_SECRET","JWT_SECRET"]),files:r}}function md(e){try{let n=(e.startsWith("ndca-")?e.slice(5):e).split(".")[1];return n?JSON.parse(Buffer.from(n.replace(/-/g,"+").replace(/_/g,"/"),"base64").toString("utf8")).handle??null:null}catch{return null}}var gd=5*6e4;function _d(){let{publicKey:e,privateKey:t}=cd("ed25519"),n=e.export({format:"der",type:"spki"}),r=t.export({format:"der",type:"pkcs8"});return{publicKeyHex:n.subarray(-32).toString("hex"),privateKeyPkcs8B64:r.toString("base64")}}function bd(e,t){let n=ld({key:Buffer.from(e,"base64"),format:"der",type:"pkcs8"});return dd(null,Buffer.from(t,"utf8"),n).toString("base64")}function Sd(){let e=Ua().toLowerCase().replace(/[^a-z0-9-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,20)||"device";return`${/^[a-z]/.test(e)?e:`d-${e}`}-${ud(3).toString("hex")}`.slice(0,32)}async function vd(e,t,n,r,o){let a=await H(e,t,"/api/v1/attest/devices",{handle:n,label:r,ed25519_pubkey_hex:o});if(a.ok){let i=a.body.org_id??"";return i?{ok:!0,orgId:i}:{ok:!1,status:a.status,error:"enroll response missing org_id"}}return{ok:!1,status:a.status,error:a.body?.error??`HTTP ${a.status}`}}async function wd(e,t){let n=await H(e,"","/api/v1/attest/challenge",{org_id:t.org_id,handle:t.handle});if(!n.ok)throw new Error(`challenge: ${n.body?.error??`HTTP ${n.status}`}`);let{challenge:r,nonce:o}=n.body;if(!r||!o)throw new Error("challenge response malformed");let a=bd(t.private_key_pkcs8_b64,r),i=await H(e,"","/api/v1/attest",{org_id:t.org_id,handle:t.handle,nonce:o,signature:a});if(!i.ok)throw new Error(`attest: ${i.body?.error??`HTTP ${i.status}`}`);let s=i.body;if(!s.allowed||!s.access_token)throw new Error(`attestation rejected: ${s.reason??"denied"}`);return{token:s.access_token,expiresAtMs:s.expires_at?Date.parse(s.expires_at):Date.now()+15*6e4}}function Ed(e,t){let n=null;return async()=>((!n||Date.now()>=n.expiresAtMs-gd)&&(n=await wd(e,t)),n.token)}function kd(e,t){let n=rn(La(),".nodata","approvals");Ga(n,{recursive:!0});let r=rn(n,`${new Date().toISOString().replace(/[:.]/g,"-").slice(0,19)}-${e}.json`);return Va(r,JSON.stringify({kind:e,approved_at:new Date().toISOString(),...t},null,2)+`
|
|
85
|
+
`,{mode:384}),r}function xd(e,t,n,r){e.registerTool("nodata_register_table",{description:"Register one of your own tables as AI-agent-readable. This writes POLICY only: it declares which columns are sensitive (released per-column only if their ciphertext exists) and which are plaintext metadata. It does NOT encrypt or change anything in the user's database \u2014 never tell the user their data is now encrypted. Relay the response's `message` and `next_steps` verbatim. After this, grants can target the table.",inputSchema:{table_name:f.string().describe("Your SQL table name"),encrypted_columns:f.array(f.string()).describe("Columns stored as <col>_ct/_iv/_tag triplets"),plaintext_columns:f.array(f.string()).optional().describe("Plaintext metadata/filter columns"),classification_column:f.string().optional().describe("Plaintext column carrying the classification value")}},async({table_name:o,encrypted_columns:a,plaintext_columns:i,classification_column:s})=>{let l=await H(t,n,"/api/v1/governance/tables",{table_name:o,encrypted_columns:a,plaintext_columns:i??[],classification_column:s});return U(l)}),e.registerTool("nodata_connect_source",{description:"Connect the user's own Supabase project as the data source for their registered tables, so granted agents can read metadata through NoData. Reads the project URL, anon key and JWT secret from the user's LOCAL env file (e.g. .env.local) and sends them directly to NoData \u2014 never ask the user to paste a key or secret into the chat, and never print them. Only allowed_tables are readable (deny-by-default).",inputSchema:{allowed_tables:f.array(f.string()).describe("Tables agents may read through this source"),env_file:f.string().optional().describe("Path to the env file holding the Supabase keys (default: .env.local, then .env in the working directory)"),source_url:f.string().optional().describe("Override the project URL (https://<ref>.supabase.co) if the env file lacks it")}},async({allowed_tables:o,env_file:a,source_url:i})=>{let s=yd(a);if("error"in s)return{content:[{type:"text",text:`Error: ${s.error}`}],isError:!0};let l=i??s.url?.value,d=[l?null:"project URL (SUPABASE_URL / NEXT_PUBLIC_SUPABASE_URL)",s.anon?null:"anon key (SUPABASE_ANON_KEY / NEXT_PUBLIC_SUPABASE_ANON_KEY)",s.jwt?null:"JWT secret (SUPABASE_JWT_SECRET \xB7 Supabase \u2192 Settings \u2192 API \u2192 JWT secret)"].filter(Boolean);if(d.length>0)return{content:[{type:"text",text:`Not sent. Missing in ${s.files.join(", ")||"the environment"}: ${d.join("; ")}.
|
|
86
|
+
Ask the user to add them to that file themselves (not in this chat), then call this tool again.`}],isError:!0};let u=await H(t,n,"/api/connector/secrets",{source_url:l,allowed_tables:o,anon_key:s.anon.value,jwt_secret:s.jwt.value}),p={read_from:s.files,variables_used:[s.url?.name,s.anon.name,s.jwt.name].filter(Boolean)};return U({...u,body:{...u.body,...p}})}),e.registerTool("nodata_grant",{description:"Issue ONE AI agent a claim-scoped grant over your data \u2014 claims, not blanket access. Returns a grant_token (shown once) the agent presents to read. Denied columns never decrypt. For one agent over several tables pass `tables` in a single call \u2014 do NOT call this once per table, that creates a separate agent each time. ASKS FIRST: without confirm:true it returns the exact policy change and grants nothing \u2014 show it to the user and call again with confirm:true only after they approve. On confirm, a copy of the approval (who, what, when, the receipt and its proof_url \u2014 never the token) is kept in ~/.nodata/approvals.",inputSchema:{agent:f.string().describe("Agent label (becomes its handle)"),tables:f.array(f.object({table:f.string(),columns:f.array(f.string()).describe("Columns the agent may read in this table"),where:f.record(f.string(),f.union([f.string(),f.number(),f.boolean()])).optional()})).optional().describe("Several tables for the same agent. When set, table/columns/where are ignored."),table:f.string().optional().describe("Single target table (default agent_demo_records)"),columns:f.array(f.string()).optional().describe("Columns the agent may read (single-table form)"),where:f.record(f.string(),f.union([f.string(),f.number(),f.boolean()])).optional().describe("Equality filter (plaintext cols only)"),classifications:f.array(f.string()).optional().describe("Allowed classification values; empty = no gating"),ttl_seconds:f.number().optional().describe("Token lifetime (default 30d, max 1y)"),confirm:f.boolean().optional().describe("true = grant it. Omit to preview the policy change.")}},async({agent:o,tables:a,table:i,columns:s,where:l,classifications:d,ttl_seconds:u,confirm:p})=>{let h={agent:o,...a?{tables:a}:{table:i??"agent_demo_records",columns:s,where:l},classifications:d,ttl_seconds:u};if(!p){let k=(a??[{table:i??"agent_demo_records",columns:s??[],where:l}]).map(_=>` \xB7 ${_.table}: ${(_.columns??[]).join(", ")||"(no columns)"}${_.where?` where ${JSON.stringify(_.where)}`:""}`),S=u?`${Math.round(u/86400*10)/10} days`:"30 days (default)";return{content:[{type:"text",text:[`POLICY CHANGE \u2014 PREVIEW, nothing granted yet. Requested by ${r()}`,`Agent "${o}" would be able to read ONLY:`,...k,`Classifications: ${d?.length?d.join(", "):"not gated"}`,`Valid for: ${S}. Every other column stays sealed and every read is receipted.`,"","Ask the user to approve this change, then call nodata_grant again with the same arguments and confirm: true."].join(`
|
|
87
|
+
`)}]}}let m=await H(t,n,"/api/v1/governance/grant",h);if(m.ok){let v=m.body,k=kd("grant",{approved_by:r(),request:h,result:{handle:v.handle,agent_id:v.agent_id,expires_at:v.expires_at,grant_receipt_id:v.grant_receipt_id,proof_url:v.proof_url}});m.body.approval_copy=k}return U(m)}),e.registerTool("nodata_policy",{description:"The POLICY BOARD: every AI agent in the organization and exactly what it can reach \u2014 tables, columns, classifications \u2014 plus status. Deny-by-default: an agent with no grant reaches nothing. Change it with nodata_grant (asks for approval first) and nodata_revoke (immediate). Content-free: names only, never a value.",inputSchema:{}},async()=>{let o=await Sr(t,n,"/api/v1/agents",{});if(!o.ok)return U(o);let i=o.body.agents??[],s=[`POLICY BOARD \u2014 ${r()}`,`${i.length} agent(s). Deny-by-default: no grant \u21D2 no access.`,""];for(let l of i){let d=l.scope,u=d?d.grants===0?"reaches nothing":`${d.tables_allowed.join(", ")||"(tables)"} \u2192 ${d.columns_allowed.join(", ")||"(no columns)"} \xB7 classifications: ${d.unrestricted_classifications?"not gated":d.classifications_allowed.join(", ")||"none"}`:"scope unavailable";s.push(` ${String(l.handle??l.name).padEnd(24)} ${String(l.status??"").padEnd(8)} ${u}`)}return s.push("",'Change: nodata_grant (preview \u2192 approve) \xB7 nodata_revoke handle: "<agent>" (immediate) \xB7 proofs: nodata_proofs'),{content:[{type:"text",text:s.join(`
|
|
88
|
+
`)}]}}),e.registerTool("nodata_revoke",{description:"Revoke an agent's grant by handle (kills all its active credentials) or by a specific jti. Revocation is mathematics \u2014 the next read 401s and any cached data is governance-dead.",inputSchema:{handle:f.string().optional().describe("Agent handle to revoke"),jti:f.string().optional().describe("Specific credential jti to revoke"),reason:f.string().optional()}},async({handle:o,jti:a,reason:i})=>{let s=await H(t,n,"/api/v1/governance/revoke",{handle:o,jti:a,reason:i});return U(s)}),e.registerTool("nodata_encrypt",{description:"Encrypt a sensitive field value using Capsule Blind Relay. Returns ciphertext. NoData stores nothing \u2014 the key is embedded in the ciphertext for YOU to store.",inputSchema:{field:f.string(),value:f.string(),context:f.string().optional()}},async({field:o,value:a,context:i})=>{let s={field:o,value:a};return i&&(s.context=i),U(await H(t,n,"/api/v1/encrypt",s))}),e.registerTool("nodata_decrypt",{description:"Decrypt a Capsule ciphertext back to plaintext (aes256gcm:v1:iv:cipher:key format).",inputSchema:{ciphertext:f.string(),field:f.string().optional(),requester:f.string().optional()}},async({ciphertext:o,field:a,requester:i})=>{let s={ciphertext:o};return a&&(s.field=a),i&&(s.requester=i),U(await H(t,n,"/api/v1/decrypt",s))}),e.registerTool("nodata_deliver",{description:"Create a burn-after-read secure link for delivering sensitive content. Returns a view URL and OTP.",inputSchema:{content:f.string(),to:f.string().optional(),maxViews:f.number().optional(),ttl:f.string().optional(),burn:f.boolean().optional()}},async({content:o,to:a,maxViews:i,ttl:s,burn:l})=>{let d={content:o};return a&&(d.to=a),i!==void 0&&(d.maxViews=i),s&&(d.ttl=s),l!==void 0&&(d.burn=l),U(await H(t,n,"/api/v1/deliver",d))}),e.registerTool("nodata_evidence",{description:"Field-level encrypt/decrypt/deliver events (field_access_log). Requires the Engine scope on the key. For the signed decision-receipt chain \u2014 grants, agent reads, denials \u2014 use nodata_proofs instead, which every org key can call. Metadata only.",inputSchema:{from:f.string().optional(),to:f.string().optional(),action:f.string().optional(),limit:f.number().optional()}},async({from:o,to:a,action:i,limit:s})=>{let l={from:o,to:a,action:i,limit:s!==void 0?String(s):void 0};return U(await Sr(t,n,"/api/v1/evidence",l))}),e.registerTool("nodata_proofs",{description:"List your organization's signed proofs: every grant, agent read and denial, newest first. Content-free (labels, hashes, timestamps). Each proof can be verified by anyone, without an account, by POSTing {proof_id: <its receipt_id>} to /api/access/verify. The response's `plan` says which proof types the user's plan includes and which need an upgrade (with the plan name) \u2014 relay it as is.",inputSchema:{receipt_id:f.string().optional().describe("Fetch one proof by id"),surface:f.string().optional().describe("Filter, e.g. 'governance.grant', 'agent.read'"),decision:f.string().optional().describe("Filter: 'grant' | 'allow' | 'deny' | 'revoke'"),from:f.string().optional().describe("ISO timestamp"),to:f.string().optional().describe("ISO timestamp"),limit:f.number().optional().describe("1..1000, default 50")}},async({receipt_id:o,surface:a,decision:i,from:s,to:l,limit:d})=>U(await Sr(t,n,"/api/v1/proofs",{receipt_id:o,surface:a,decision:i,from:s,to:l,limit:d!==void 0?String(d):void 0})))}function Ad(e,t,n){let r=md(n);r||console.error("nodata-mcp: warning \u2014 could not derive an agent handle from the grant token (expected ndca-<jwt> with a 'handle' claim). nodata_decide/nodata_retrieve will work; nodata_read/nodata_use will fail until a valid grant token is provided."),e.registerTool("nodata_decide",{description:"Ask whether this agent MAY reach a resource, WITHOUT reading it. Returns a decision (allow / degrade / deny), the reachable column subset, an access-distance cost, and a signed proof \u2014 never any data. Use it to plan: check reachability before you retrieve. Hard-scoped to this server's grant token.",inputSchema:{table:f.string().describe("Table to check (must be in your grant)"),columns:f.array(f.string()).describe("Columns you want to reach"),where:f.record(f.string(),f.union([f.string(),f.number(),f.boolean()])).optional().describe("Equality filter (readable columns only)")}},async({table:o,columns:a,where:i})=>{let s=await H(t,n,"/api/access/decide",{resource:{table:o,columns:a,where:i},intent:"read"});return U(s)}),e.registerTool("nodata_retrieve",{description:"Retrieve prompt-ready context for a resource, filtered to exactly what this agent may see. Denied columns are never decrypted; the response includes an accounting of what was withheld (columns + estimated tokens saved) and a signed proof. Prefer this over a raw read when assembling an LLM prompt. Hard-scoped to this server's grant token.",inputSchema:{table:f.string().describe("Table to retrieve from (must be in your grant)"),columns:f.array(f.string()).describe("Columns to include in context"),where:f.record(f.string(),f.union([f.string(),f.number(),f.boolean()])).optional(),top_k:f.number().optional().describe("Max rows (default 50, max 200)")}},async({table:o,columns:a,where:i,top_k:s})=>{let l=await H(t,n,"/api/access/retrieve",{resource:{table:o,columns:a,where:i},top_k:s});return U(l)}),e.registerTool("nodata_read",{description:"Read governed data within this agent's grant. You may only request columns your grant allows \u2014 denied columns never decrypt server-side, and every read emits a cryptographic receipt. This tool is hard-scoped to the grant token this server was started with.",inputSchema:{table:f.string().describe("Table to read (must be in your grant)"),columns:f.array(f.string()).describe("Columns to read (must be in your grant)"),where:f.record(f.string(),f.union([f.string(),f.number(),f.boolean()])).optional(),limit:f.number().optional().describe("Max rows (default 50, max 200)")}},async({table:o,columns:a,where:i,limit:s})=>{if(!r)return{content:[{type:"text",text:"Error: could not derive agent handle from grant token."}],isError:!0};let l=await H(t,n,`/api/agents/${encodeURIComponent(r)}/read`,{table:o,columns:a,where:i,limit:s});return U(l)}),e.registerTool("nodata_use",{description:"Invoke a pre-registered capability (deploy, send, charge, query, \u2026) WITHOUT receiving the secret. The Capsule injects the sealed credential server-side and returns only the result. You may invoke only capabilities your grant allows; the secret never reaches you. Hard-scoped to the grant token this server was started with.",inputSchema:{capability:f.string().describe("Capability name to invoke (must be in your grant, e.g. 'deploy-prod')"),params:f.record(f.string(),f.unknown()).optional().describe("Allowlisted params; unknown keys are dropped server-side"),resource_key:f.string().optional().describe("Optional folder/resource the action targets (enforced against corpus scope)")}},async({capability:o,params:a,resource_key:i})=>{if(!r)return{content:[{type:"text",text:"Error: could not derive agent handle from grant token."}],isError:!0};let s=await H(t,n,`/api/agents/${encodeURIComponent(r)}/use`,{capability:o,params:a,resource_key:i});return U(s)}),e.registerTool("nodata_code_advise",{description:"Ask the blind code advisor to diagnose/fix a bug in a code capsule WITHOUT seeing its source. You receive guidance + a targeted diff + an exposure proof (source never left the boundary); the source is never returned to you. Requires the capsule owner to have granted this agent (scope.fabric_developers). Hard-scoped to this server's grant token.",inputSchema:{capsule_id:f.string().describe("The code capsule to advise on (you must be granted on it)"),question:f.string().optional().describe("What to fix / improve, in natural language"),note:f.string().optional().describe("Extra context for the advisor"),error:f.object({message:f.string().optional(),stack:f.string().optional(),kind:f.string().optional()}).optional().describe("An error the code produced, to guide the fix"),steer:f.string().optional().describe("A steer on a refine turn (e.g. 'no, round half-up')"),prior_diff:f.string().optional().describe("The previously proposed diff, to refine")}},async({capsule_id:o,question:a,note:i,error:s,steer:l,prior_diff:d})=>{if(!r)return{content:[{type:"text",text:"Error: could not derive agent handle from grant token."}],isError:!0};let u=await H(t,n,`/api/agents/${encodeURIComponent(r)}/code-capsule/${encodeURIComponent(o)}/advise`,{question:a,note:i,error:s,steer:l,prior_diff:d});return U(u)}),e.registerTool("nodata_code_patch",{description:"Submit a fix to a code capsule as a SIGNED, queued patch WITHOUT seeing its source. Provide a raw unified `diff`, or a whole-file `replace` ({path, content}) that is diffed server-side against the sealed source. The source is never persisted or returned; you get back a patch id, the diff hash, and a receipt. Requires a capsule grant (scope.fabric_developers). Hard-scoped to this server's grant token.",inputSchema:{capsule_id:f.string().describe("The code capsule to patch (you must be granted on it)"),summary:f.string().optional().describe("Short human-readable summary of the fix"),diff:f.string().optional().describe("A raw unified diff (advanced)"),replace:f.object({path:f.string(),content:f.string()}).optional().describe("Whole-file replacement; the diff is synthesized server-side against sealed source")}},async({capsule_id:o,summary:a,diff:i,replace:s})=>{if(!r)return{content:[{type:"text",text:"Error: could not derive agent handle from grant token."}],isError:!0};let l=await H(t,n,`/api/agents/${encodeURIComponent(r)}/code-capsule/${encodeURIComponent(o)}/patch`,{summary:a,diff:i,replace:s});return U(l)})}var ja=`WHAT NODATA DOES \u2014 in one line:
|
|
32
89
|
Give any agent real power over your data, without the power to leak it.
|
|
33
90
|
(Possession is not permission: it can hold the key and still not read what you didn't allow.)
|
|
34
|
-
`,
|
|
91
|
+
`,Td=`TURN THE DATA TOOLS ON \u2014 3 steps, about a minute, once:
|
|
35
92
|
|
|
36
93
|
1. GET A KEY call nodata_connect (no arguments)
|
|
37
94
|
-> opens the signup in your browser: email + company (~30s), a 12-word
|
|
@@ -44,42 +101,46 @@ ${t}`}],isError:!0}}function Nt(e){try{let n=(e.startsWith("ndca-")?e.slice(5):e
|
|
|
44
101
|
3. ACTIVATE type /mcp (or restart Claude Code) so the tools load.
|
|
45
102
|
|
|
46
103
|
COMING BACK LATER? Nothing to redo \u2014 it starts ready. If the tools look missing, just /mcp.
|
|
47
|
-
`,
|
|
48
|
-
|
|
49
|
-
1. SEE
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
104
|
+
`,Pd=`YOUR WORKSPACE \u2014 say it in plain words; anything that changes files or policy asks you first:
|
|
105
|
+
|
|
106
|
+
1. SEE "scan <folder>" -> nodata_scan_folder: the whole result + a full HTML report,
|
|
107
|
+
on this machine, nothing uploads.
|
|
108
|
+
2. LOCK "lock what it found" -> nodata_protect: seals those files to this device (.ndc).
|
|
109
|
+
3. WORK "clean copy of <file>" -> nodata_redact: values become [CARD], [ID] \u2026 \u2014 analyse the rest.
|
|
110
|
+
4. RELEASE "open <file>.ndc" -> nodata_open, hash-checked.
|
|
111
|
+
5. POLICY "who can read what?" -> nodata_policy \xB7 change it: nodata_grant (preview, then approve)
|
|
112
|
+
\xB7 nodata_revoke (immediate).
|
|
113
|
+
6. PROVE "show me the proofs" -> nodata_proofs: every grant / read / deny, each with a proof_url.
|
|
114
|
+
7. SEND "send <file> to \u2026" -> nodata_send: a governed link \u2014 revocable (nodata_burn), opens counted
|
|
115
|
+
(nodata_link_status), NoData never holds the key.
|
|
116
|
+
8. ARCHIVE "archive <folder>" -> nodata_wrap: sealed to your 12-word org key; NoData can never open it.
|
|
117
|
+
|
|
118
|
+
Database tables: nodata_register_table + nodata_connect_source, then nodata_grant.
|
|
119
|
+
One secret value: nodata_encrypt, hand it over once: nodata_deliver.
|
|
120
|
+
`,Dd=`WHAT YOU CAN DO \u2014 scoped to your grant; you reach only what it allows, the rest never decrypts:
|
|
60
121
|
|
|
61
122
|
1. PLAN nodata_decide "may I reach X?" -> allow / partial / deny + a signed proof. No data moves.
|
|
62
123
|
2. PULL nodata_retrieve prompt-ready context, allowed fields only, with a receipt.
|
|
63
124
|
(nodata_read for raw governed rows.)
|
|
64
125
|
3. ACT nodata_use run a capability with a secret injected server-side \u2014 you never see it.
|
|
65
|
-
`,
|
|
126
|
+
`,Ma=`STUCK? There's always a next step:
|
|
66
127
|
- Don't see the nodata_* tools? They load when the client starts \u2014 type /mcp or restart.
|
|
67
128
|
(Expected, not an error.)
|
|
68
129
|
- No MCP at all? The same governance runs from one curl, or the guided page:
|
|
69
130
|
https://www.nodatacapsule.com/developers/get-started
|
|
70
|
-
`;function
|
|
131
|
+
`;function Fa(e){return e==="setup"?`You're connected to NoData \u2014 but there's NO key yet, so the data tools are still off.
|
|
71
132
|
|
|
72
133
|
`:e==="agent"?`You're connected to NoData, scoped to one grant token.
|
|
73
134
|
|
|
74
135
|
`:`You're connected to NoData (admin mode). You don't memorize commands \u2014 just ask in plain words.
|
|
75
136
|
|
|
76
|
-
`}function
|
|
77
|
-
`+
|
|
78
|
-
`+
|
|
137
|
+
`}function Od(e){if(e==="setup")return Fa(e)+ja+`
|
|
138
|
+
`+Td+`
|
|
139
|
+
`+Ma;let t=e==="agent"?Dd:Pd;return Fa(e)+ja+`
|
|
79
140
|
`+t+`
|
|
80
|
-
`+
|
|
141
|
+
`+Ma}function Nd(e,t){e.registerTool("nodata_get_started",{description:"Call this FIRST (no arguments). NoData in one line: what you can achieve \u2014 an agent that cannot leak, a look at what is already exposed, a secret we cannot read \u2014 with the single next step for each, and how to recover if the tools or MCP seem stuck. If the user asks what NoData can do, how to start, or why the tools are missing, call this and relay it.",inputSchema:{}},async()=>({content:[{type:"text",text:Od(t)}]}))}var Id="/capsule-api/register";function Cd(e){let t=process.platform==="win32",n=process.platform==="darwin"?"open":t?"cmd":"xdg-open",r=t?["/c","start","",e]:[e];try{let o=sd(n,r,{stdio:"ignore",detached:!0});return o.on("error",()=>{}),o.unref(),!0}catch{return!1}}function Rd(e,t){e.registerTool("nodata_connect",{description:"Switch NoData's data tools on. Step 1: call with NO arguments to open the free signup in a browser (email + company, ~30s \u2014 also where your 12-word recovery phrase + email verification happen); it shows an ORG KEY once. Step 2: call this tool again with that key as `api_key` and it is saved on this machine, so every later start comes up ready with nothing to retype. Step 3: type /mcp (or restart) so the client loads the tools.",inputSchema:{api_key:f.string().optional().describe("The org key shown once at signup (ndp_\u2026 or sk_\u2026). Omit on the first call to open signup.")}},async({api_key:n})=>{let r=(n??"").trim();if(!r){let u=t+Id;return{content:[{type:"text",text:(Cd(u)?`STEP 1 of 3 \u2014 opened the NoData signup in your browser:
|
|
81
142
|
`:`STEP 1 of 3 \u2014 open the NoData signup in your browser:
|
|
82
|
-
`)+
|
|
143
|
+
`)+u+`
|
|
83
144
|
|
|
84
145
|
There, about a minute:
|
|
85
146
|
- email + company (a personal email is fine for the sandbox)
|
|
@@ -88,21 +149,14 @@ There, about a minute:
|
|
|
88
149
|
|
|
89
150
|
STEP 2 \u2014 come back and call this tool again with the key:
|
|
90
151
|
nodata_connect api_key: "<the key you copied>"
|
|
91
|
-
and I'll save it so you never paste it again. (Then STEP 3: type /mcp to activate.)`}]}}if(!/^(ndp_|sk_)/.test(
|
|
92
|
-
Copy the key shown once on the signup page and try again: nodata_connect api_key: "ndp_\u2026".`}]};let{publicKeyHex:
|
|
152
|
+
and I'll save it so you never paste it again. (Then STEP 3: type /mcp to activate.)`}]}}if(!/^(ndp_|sk_)/.test(r))return{content:[{type:"text",text:`That doesn't look like a NoData org key (it should start with ndp_ or sk_).
|
|
153
|
+
Copy the key shown once on the signup page and try again: nodata_connect api_key: "ndp_\u2026".`}]};let{publicKeyHex:o,privateKeyPkcs8B64:a}=_d(),i=Sd(),s=Ua()||"this device",l=await vd(t,r,i,s,o);if(l.ok){try{Ba({device:{org_id:l.orgId,handle:i,label:s,private_key_pkcs8_b64:a,public_key_hex:o},base_url:t})}catch(u){return{content:[{type:"text",text:"Enrolled the device, but couldn't save it locally: "+(u instanceof Error?u.message:String(u))}]}}return{content:[{type:"text",text:`STEP 2 done \u2014 this device is enrolled as "${s}" (${i}), and only its PRIVATE key is
|
|
93
154
|
saved at ~/.nodata/credentials.json (readable only by you). The org key you pasted was NOT
|
|
94
155
|
stored: every start now proves possession by signing a fresh challenge and gets a 15-minute token.
|
|
95
156
|
|
|
96
|
-
STEP 3 \u2014 type /mcp (or restart Claude Code) and the admin tools appear. Next time: nothing to do.`}]}}let d=l.status===404||l.status===0;try{
|
|
157
|
+
STEP 3 \u2014 type /mcp (or restart Claude Code) and the admin tools appear. Next time: nothing to do.`}]}}let d=l.status===404||l.status===0;try{Ba({api_key:r,key_prefix:r.slice(0,12),base_url:t})}catch(u){return{content:[{type:"text",text:"Couldn't save locally: "+(u instanceof Error?u.message:String(u))+`
|
|
97
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:(d?`STEP 2 done \u2014 saved your key on this machine (device attestation isn't available on this
|
|
98
159
|
server yet, so this is the key-at-rest path). `:`STEP 2 done \u2014 saved your key on this machine (device enrollment didn't succeed: ${l.error}). `)+`Every future start loads it automatically \u2014 no re-register, no re-paste.
|
|
99
160
|
|
|
100
|
-
STEP 3 \u2014 type /mcp (or restart Claude Code) and the admin tools appear. Next time: nothing to do.`}]}})}function
|
|
101
|
-
|
|
102
|
-
GOVERN what it surfaced \u2014 same journey, inside this command:
|
|
103
|
-
\xB7 CHOOSE what an agent may read: nodata_register_table then nodata_grant (denied columns never decrypt)
|
|
104
|
-
\xB7 PROVE every access afterwards: nodata_evidence
|
|
105
|
-
|
|
106
|
-
Want a standalone deep scan any time? npx @nodatachat/nodata scan <folder> (this same engine).`}function Jt(e){e.registerTool("nodata_scan_folder",{description:"SEE what's sensitive before you govern it. Scans a LOCAL folder for hardcoded secrets and unencrypted PII (checksum-validated \u2014 Israeli ID / Luhn credit-card / IBAN) with NoData's deep content scanner, reading PDFs and Office files too, ENTIRELY on this machine \u2014 nothing uploads, no credential needed. Returns the findings by file and severity plus the first fix, then points at nodata_register_table + nodata_grant to govern what it found. If the user asks to scan / audit / check a folder or repo for sensitive data, secrets, or exposure, call this.",inputSchema:{path:c.string().optional().describe("Folder to scan (absolute or relative). Default: the directory the server runs in.")}},async({path:t})=>{let n=(t??".").trim()||".",i=_t(n);if(!$e(i))return{content:[{type:"text",text:`No folder found at: ${i}
|
|
107
|
-
Pass an existing path, e.g. nodata_scan_folder path: "."`}]};try{let r=await ee({target_id:"mcp",target_label:vt(i),target_path:i,log:te});return{content:[{type:"text",text:Xt(r)}]}}catch(r){return{content:[{type:"text",text:`Scan failed: ${r instanceof Error?r.message:String(r)}`}],isError:!0}}})}async function qt(){let{apiKey:e,grantToken:t,baseUrl:n,credentialSource:i,device:r}=Rt(process.argv.slice(2)),o=t?"agent":e||r?"admin":"setup",a=new gt({name:o==="agent"?"NoData (agent-scoped)":o==="setup"?"NoData (setup)":"NoData",version:re});r?xe(a,n,Bt(n,r)):e&&xe(a,n,e),t&&Ut(a,n,t),Wt(a,o),o!=="agent"&&Jt(a),o==="setup"?(Yt(a,n),console.error(`nodata-mcp: no credential given \u2014 running in setup mode (data tools disabled).
|
|
108
|
-
Call nodata_connect (opens signup, enrolls this device), or pass --api-key / --grant-token. See --help.`)):r?console.error(`nodata-mcp: loaded device identity "${r.label}" (${r.handle}) \u2014 attest mode; tokens are minted per session.`):i==="stored"&&console.error("nodata-mcp: loaded saved credential from ~/.nodata/credentials.json (admin mode).");let s=new mt;await a.connect(s)}qt().catch(e=>{console.error("Fatal error:",e),process.exit(1)});
|
|
161
|
+
STEP 3 \u2014 type /mcp (or restart Claude Code) and the admin tools appear. Next time: nothing to do.`}]}})}async function $d(){let{apiKey:e,grantToken:t,baseUrl:n,credentialSource:r,device:o}=hd(process.argv.slice(2)),a=t?"agent":e||o?"admin":"setup",i=new od({name:a==="agent"?"NoData (agent-scoped)":a==="setup"?"NoData (setup)":"NoData",version:wr}),s=()=>o?`device "${o.label}" (${o.handle}) \xB7 org ${o.org_id}`:e?`org key ${e.slice(0,12)}\u2026`:"not connected \u2014 local only",l=o?Ed(n,o):e||null;if(l){xd(i,n,l,s),xa(i,n,async()=>{let p=await an(l);if("error"in p)throw new Error("no usable org credential \u2014 run nodata_connect");return p.token},s);let u=async(p,h,m)=>{let v=await an(l);if("error"in v)return{status:401,body:{error:"no usable org credential \u2014 run nodata_connect"}};let k=await fetch(`${n}${h}`,{method:p,headers:{authorization:`Bearer ${v.token}`,...m?{"content-type":"application/json"}:{}},...m?{body:JSON.stringify(m)}:{}});return{status:k.status,body:await k.json().catch(()=>({}))}};$a(i,{get:p=>u("GET",p),post:(p,h)=>u("POST",p,h)},()=>Ra(o?.private_key_pkcs8_b64,o?.label),s)}t&&Ad(i,n,t),Nd(i,a),a!=="agent"&&ao(i,s),a==="setup"?(Rd(i,n),console.error(`nodata-mcp: no credential given \u2014 running in setup mode (data tools disabled).
|
|
162
|
+
Call nodata_connect (opens signup, enrolls this device), or pass --api-key / --grant-token. See --help.`)):o?console.error(`nodata-mcp: loaded device identity "${o.label}" (${o.handle}) \u2014 attest mode; tokens are minted per session.`):r==="stored"&&console.error("nodata-mcp: loaded saved credential from ~/.nodata/credentials.json (admin mode).");let d=new ad;await i.connect(d)}$d().catch(e=>{console.error("Fatal error:",e),process.exit(1)});
|