@zk-email/sdk 0.0.23 → 0.0.25
Sign up to get free protection for your applications and to get access to all the features.
- package/dist/index.d.mts +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +2 -2
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +2 -2
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
package/dist/index.d.mts
CHANGED
@@ -141,7 +141,7 @@ type ListBlueprintsOptions = {
|
|
141
141
|
skip?: number;
|
142
142
|
limit?: number;
|
143
143
|
sort?: -1 | 1;
|
144
|
-
status?: Status;
|
144
|
+
status?: Status[];
|
145
145
|
isPublic?: boolean;
|
146
146
|
search?: string;
|
147
147
|
};
|
@@ -149,7 +149,7 @@ type ListBlueprintsOptionsRequest = {
|
|
149
149
|
skip?: number;
|
150
150
|
limit?: number;
|
151
151
|
sort?: -1 | 1;
|
152
|
-
status?: Status;
|
152
|
+
status?: Status[];
|
153
153
|
is_public?: boolean;
|
154
154
|
search?: string;
|
155
155
|
};
|
package/dist/index.d.ts
CHANGED
@@ -141,7 +141,7 @@ type ListBlueprintsOptions = {
|
|
141
141
|
skip?: number;
|
142
142
|
limit?: number;
|
143
143
|
sort?: -1 | 1;
|
144
|
-
status?: Status;
|
144
|
+
status?: Status[];
|
145
145
|
isPublic?: boolean;
|
146
146
|
search?: string;
|
147
147
|
};
|
@@ -149,7 +149,7 @@ type ListBlueprintsOptionsRequest = {
|
|
149
149
|
skip?: number;
|
150
150
|
limit?: number;
|
151
151
|
sort?: -1 | 1;
|
152
|
-
status?: Status;
|
152
|
+
status?: Status[];
|
153
153
|
is_public?: boolean;
|
154
154
|
search?: string;
|
155
155
|
};
|
package/dist/index.js
CHANGED
@@ -1,3 +1,3 @@
|
|
1
|
-
'use strict';Object.defineProperty(exports,'__esModule',{value:true});var viem=require('viem'),chains=require('viem/chains');var b=(o=>(o[o.None=0]="None",o[o.InProgress=1]="InProgress",o[o.Done=2]="Done",o[o.Failed=3]="Failed",o))(b||{});var T="Ov23li0KABFCUsxBEQkn";function v(n,e=T){let t=encodeURIComponent(n);return `https://github.com/login/oauth/authorize?client_id=${e}&scope=user:email&state=${t}`}async function g(n){try{let e=await n.getToken();if(e||(await n.onTokenExpired(),e=await n.getToken()),!e)throw new Error("Failed to get new token");return `Bearer ${e}`}catch(e){throw console.error("Failed to get token from auth"),e}}var w="pk_live_51NXwT8cHf0vYAjQK9LzB3pM6R8gWx2F",x,y=new Promise(n=>{x=n;});console.log("frontend wasm");try{import('@dimidumo/relayer-utils/web').then(async n=>{await n.default(),x(n);}).catch(n=>{console.log("Failed to init WASM: ",n);});}catch{}async function c(n,e,t){try{let r={method:"POST",headers:{"Content-Type":"application/json","x-api-key":w,...t?{Authorization:await g(t)}:{}}};e&&(r.body=JSON.stringify(e));let o=await fetch(n,r),s=await o.json();if(!o.ok)throw new Error(`HTTP error! status: ${o.status}, message: ${s}`);return s}catch(r){throw console.error("POST Error:",r),r}}async function _(n,e,t){try{let r={method:"PATCH",headers:{"Content-Type":"application/json","x-api-key":w,...t?{Authorization:await g(t)}:{}}};e&&(r.body=JSON.stringify(e));let o=await fetch(n,r),s=await o.json();if(!o.ok)throw new Error(`HTTP error! status: ${o.status}, message: ${s}`);return s}catch(r){throw console.error("PATCH Error:",r),r}}async function u(n,e,t){try{let r=n;if(e){let s=new URLSearchParams;Object.entries(e).forEach(([i,a])=>{a&&s.append(i,String(a));}),s.size>0&&(r+=`?${s.toString()}`);}let o=await fetch(r,{method:"GET",headers:{"Content-Type":"application/json","x-api-key":w,...t?{Authorization:await g(t)}:{}}});if(!o.ok)throw new Error(`HTTP error! status: ${o.status}`);return await o.json()}catch(r){throw console.error("GET Error:",r),r}}async function B(n){try{return await(await y).parseEmail(n)}catch(e){throw console.error("Failed to parse email: ",e),e}}async function L(n,e,t=!1){let r=await B(n);if(e.emailBodyMaxLength===void 0||e.emailHeaderMaxLength===void 0)throw new Error("emailBodyMaxLength and emailHeaderMaxLength must be provided");let o=r.canonicalized_body.length>e.emailBodyMaxLength?r.canonicalized_body.substring(0,e.emailBodyMaxLength):r.canonicalized_body,s=r.canonicalized_header.length>e.emailHeaderMaxLength?r.canonicalized_header.substring(0,e.emailHeaderMaxLength):r.canonicalized_header;return await Promise.all(e.decomposedRegexes.map(a=>k(o,s,a,t)))}async function k(n,e,t,r=!1){let o={parts:t.parts.map(d=>({is_public:"isPublic"in d?d.isPublic:d.is_public,regex_def:"regexDef"in d?d.regexDef:d.regex_def}))},s;if(t.location==="body")s=n;else if(t.location==="header")s=e;else throw Error(`Unsupported location ${t.location}`);let i="maxLength"in t?t.maxLength:t.max_length,a=await y,h=a.extractSubstr(s,o,!1);if(h[0].length>i)throw new Error(`Max length of extracted result was exceeded for decomposed regex ${t.name}`);return r?a.extractSubstr(s,o,r):h}async function P(n,e,t,r){try{let o={maxHeaderLength:r.emailHeaderMaxLength,maxBodyLength:r.emailBodyMaxLength,ignoreBodyHashCheck:r.ignoreBodyHashCheck,removeSoftLinesBreaks:r.removeSoftLinebreaks,shaPrecomputeSelector:r.shaPrecomputeSelector},s=await y,i=e.map(h=>({...h,parts:h.parts.map(m=>({is_public:m.isPublic||!!m.is_public,regex_def:m.regexDef||!!m.regex_def}))}));console.log("calling generateCircuitInputsWithDecomposedRegexesAndExternalInputs with"),console.log("eml: ",n),console.log("decomposedRegex: ",i),console.log("externalInputs: ",t),console.log("params: ",r);let a=await s.generateCircuitInputsWithDecomposedRegexesAndExternalInputs(n,i,t,o);return JSON.stringify(Object.fromEntries(a))}catch(o){throw console.error("Failed to generate inputs for proof"),o}}function S(n,e="data"){if(!window&&!document)throw Error("startFilesDownload can only be used in a browser");let t=new Blob([n],{type:"application/json"}),r=URL.createObjectURL(t),o=document.createElement("a");o.href=r,o.download=`${e}.json`,document.body.appendChild(o),o.click(),document.body.removeChild(o),URL.revokeObjectURL(r);}var p=class n{blueprint;props;lastCheckedStatus=null;constructor(e,t){if(!(e instanceof l))throw new Error("Invalid blueprint: must be an instance of Blueprint class");if(this.blueprint=e,!t?.id)throw new Error("A proof must have an id");this.props={status:1,...t};}getId(){return this.props.id}async getProofDataDownloadLink(){if(this.props.status!==2)throw new Error("The proving is not done yet.");let e;try{e=await u(`${this.blueprint.baseUrl}/proof/files/${this.props.id}`);}catch(t){throw console.error("Failed calling GET on /proof/files/:id in getProofDataDownloadLink: ",t),t}return e.url}async startFilesDownload(){if(!window&&!document)throw Error("startFilesDownload can only be used in a browser");let e;try{e=await this.getProofDataDownloadLink();}catch(r){throw console.error("Failed to start download of ZKeys: ",r),r}let t=document.createElement("a");t.href=e,t.download="proof_files.zip",document.body.appendChild(t),t.click(),document.body.removeChild(t);}async checkStatus(){if(this.props.status===2)return this.props.status;if(!this.lastCheckedStatus)this.lastCheckedStatus=new Date;else {let r=new Date().getTime()-this.lastCheckedStatus.getTime();r<500&&await new Promise(o=>setTimeout(o,500-r));}let e;try{e=await u(`${this.blueprint.baseUrl}/proof/status/${this.props.id}`);}catch(t){throw console.error("Failed calling GET /blueprint/status in getStatus(): ",t),t}return this.props.status=e.status,e.status}async verifyOnChain(){}static async getPoofById(e,t){let r;try{r=await u(`${t}/proof/${e}`);}catch(i){throw console.error("Failed calling /proof/:id in getProofById: ",i),i}let o=this.responseToProofProps(r),s=await l.getBlueprintById(r.blueprint_id,t);return new n(s,o)}static responseToProofProps(e){return {id:e.id,blueprintId:e.blueprint_id,status:e.status,input:e.input,proof:e.proof,public:e.public,startedAt:new Date(e.started_at.seconds*1e3),provedAt:e.proved_at?new Date(e.proved_at.seconds*1e3):void 0}}};var f=class{options;blueprint;constructor(e,t){if(t?.isLocal===!0)throw new Error("Local proving is not supported yet");if(!(e instanceof l))throw new Error("Invalid blueprint: must be an instance of Blueprint class");this.blueprint=e,this.options={isLocal:!1,...t||{}};}async generateProof(e){console.log("starting generate proof");let t=await this.generateProofRequest(e);for(console.log("got proof: ",t);![2,3].includes(await t.checkStatus()););return t}async generateProofRequest(e){let t=this.blueprint.getId();if(!t)throw new Error("Blueprint of Proover must be initialized in order to create a Proof");let r;try{let i={emailHeaderMaxLength:this.blueprint.props.emailHeaderMaxLength||256,emailBodyMaxLength:this.blueprint.props.emailBodyMaxLength||2560,ignoreBodyHashCheck:this.blueprint.props.ignoreBodyHashCheck||!1,removeSoftLinebreaks:this.blueprint.props.removeSoftLinebreaks||!0,shaPrecomputeSelector:this.blueprint.props.shaPrecomputeSelector};console.log("generating proof inputs"),r=await P(e,this.blueprint.props.decomposedRegexes,this.blueprint.props.externalInputs||[],i);}catch(i){throw console.error("Failed to generate inputs for proof"),i}console.log("got proof input");let o;try{let i={blueprint_id:t,input:r};o=await c(`${this.blueprint.baseUrl}/proof`,i);}catch(i){throw console.error("Failed calling POST on /proof/ in generateProofRequest: ",i),i}let s=p.responseToProofProps(o);return new p(this.blueprint,s)}};var E=(e=>(e.Circom="circom",e))(E||{}),D=(s=>(s[s.None=0]="None",s[s.Draft=1]="Draft",s[s.InProgress=2]="InProgress",s[s.Done=3]="Done",s[s.Failed=4]="Failed",s))(D||{});var U="0x4200000000000000000000000000000000000006",F=[{constant:!0,inputs:[],name:"totalSupply",outputs:[{name:"",type:"uint256"}],type:"function"}],H=viem.createPublicClient({chain:chains.baseSepolia,transport:viem.http()});async function R(){try{return await H.readContract({address:U,abi:F,functionName:"totalSupply"})}catch(n){throw console.error("Error fetching WETH total supply:",n),n}}var l=class n{props;auth;baseUrl;lastCheckedStatus=null;constructor(e,t,r){this.props={ignoreBodyHashCheck:!1,enableHeaderMasking:!1,enableBodyMasking:!1,isPublic:!0,status:1,...e},this.baseUrl=t,this.auth=r;}addAuth(e){this.auth=e;}static async getBlueprintById(e,t,r){let o;try{o=await u(`${t}/blueprint/${e}`);}catch(a){throw console.error("Failed calling /blueprint/:id in getBlueprintById: ",a),a}let s=this.responseToBlueprintProps(o);return new n(s,t,r)}static responseToBlueprintProps(e){return {id:e.id,title:e.title,description:e.description,slug:e.slug,tags:e.tags,emailQuery:e.email_query,circuitName:e.circuit_name,ignoreBodyHashCheck:e.ignore_body_hash_check,shaPrecomputeSelector:e.sha_precompute_selector,emailBodyMaxLength:e.email_body_max_length,emailHeaderMaxLength:e.email_header_max_length,removeSoftLinebreaks:e.remove_soft_linebreaks,githubUsername:e.github_username,senderDomain:e.sender_domain,enableHeaderMasking:e.enable_header_masking,enableBodyMasking:e.enable_body_masking,zkFramework:e.zk_framework,isPublic:e.is_public,createdAt:new Date(e.created_at.seconds*1e3),updatedAt:new Date(e.updated_at.seconds*1e3),externalInputs:e.external_inputs?.map(r=>({name:r.name,maxLength:r.max_length})),decomposedRegexes:e.decomposed_regexes?.map(r=>({parts:r.parts.map(o=>({isPublic:o.is_public,regexDef:o.regex_def})),name:r.name,maxLength:r.max_length,location:r.location})),status:e.status,verifierContract:{address:e.verifier_contract_address,chain:e.verifier_contract_chain},version:e.version}}static blueprintPropsToRequest(e){return {id:e.id,title:e.title,description:e.description,slug:e.slug,tags:e.tags,email_query:e.emailQuery,circuit_name:e.circuitName,ignore_body_hash_check:e.ignoreBodyHashCheck,sha_precompute_selector:e.shaPrecomputeSelector,email_body_max_length:e.emailBodyMaxLength,email_header_max_length:e.emailHeaderMaxLength,remove_soft_linebreaks:e.removeSoftLinebreaks,github_username:e.githubUsername,sender_domain:e.senderDomain,enable_header_masking:e.enableHeaderMasking,enable_body_masking:e.enableBodyMasking,zk_framework:e.zkFramework,is_public:e.isPublic,external_inputs:e.externalInputs?.map(r=>({name:r.name,max_length:r.maxLength})),decomposed_regexes:e.decomposedRegexes?.map(r=>({parts:r.parts.map(o=>({is_public:o.isPublic||o.is_public,regex_def:o.regexDef||o.regex_def})),name:r.name,max_length:r.maxLength,location:r.location})),verifier_contract_address:e.verifierContract?.address,verifier_contract_chain:e.verifierContract?.chain}}async submitDraft(){if(!this.auth)throw new Error("auth is required, add it with Blueprint.addAuth(auth)");if(this.props.id)throw new Error("Blueprint was already saved");let e=n.blueprintPropsToRequest(this.props),t;try{t=await c(`${this.baseUrl}/blueprint`,e,this.auth);}catch(r){throw console.error("Failed calling POST on /blueprint/ in submitDraft: ",r),r}this.props=n.responseToBlueprintProps(t);}async submitNewVersionDraft(e){if(!this.auth)throw new Error("auth is required, add it with Blueprint.addAuth(auth)");let t=n.blueprintPropsToRequest(e),r;try{r=await c(`${this.baseUrl}/blueprint`,t,this.auth);}catch(o){throw console.error("Failed calling POST on /blueprint/ in submitDraft: ",o),o}this.props=n.responseToBlueprintProps(r);}async submitNewVersion(e){if(!this.auth)throw new Error("auth is required, add it with Blueprint.addAuth(auth)");await this.submitNewVersionDraft(e);try{await c(`${this.baseUrl}/blueprint/compile/${this.props.id}`,null,this.auth);}catch(t){throw console.error("Failed calling POST on /blueprint/compile in submit: ",t),t}}static async listBlueprints(e,t,r){let o={skip:t?.skip,limit:t?.limit,sort:t?.sort,status:t?.status,is_public:t?.isPublic,search:t?.search},s;try{s=await u(`${e}/blueprint`,o);}catch(i){throw console.error("Failed calling POST on /blueprint/ in submitDraft: ",i),i}return s.blueprints?s.blueprints.map(i=>{let a=n.responseToBlueprintProps(i);return new n(a,e,r)}):[]}async submit(){if(!this.auth)throw new Error("auth is required, add it with Blueprint.addAuth(auth)");if(!this.props.id)try{await this.submitDraft();}catch(t){throw console.error("Failed to create blueprint: ",t),t}let e=await this._checkStatus();if(3===e)throw new Error("The circuits are already compiled.");if(2===e)throw new Error("The circuits already being compiled, please wait.");try{await c(`${this.baseUrl}/blueprint/compile/${this.props.id}`,null,this.auth);}catch(t){throw console.error("Failed calling POST on /blueprint/compile in submit: ",t),t}}async _checkStatus(){let e;try{e=await u(`${this.baseUrl}/blueprint/status/${this.props.id}`);}catch(t){throw console.error("Failed calling GET /blueprint/status in getStatus(): ",t),t}return this.props.status=e.status,e.status}async checkStatus(){if(!this.props.id)return this.props.status;if([4,3].includes(this.props.status))return this.props.status;if(!this.lastCheckedStatus)this.lastCheckedStatus=new Date;else {let r=new Date().getTime()-this.lastCheckedStatus.getTime();r<500&&await new Promise(o=>setTimeout(o,500-r));}return await this._checkStatus()}getId(){return this.props.id||null}async getZKeyDownloadLink(){if(this.props.status!==3)throw new Error("The circuits are not compiled yet, nothing to download.");let e;try{e=await u(`${this.baseUrl}/blueprint/zkey/${this.props.id}`),console.log("response: ",e);}catch(t){throw console.error("Failed calling GET on /blueprint/zkey/:id in getZKeyDownloadLink: ",t),t}return e.urls}async startZKeyDownload(){if(!window&&!document)throw Error("startZKeyDownload can only be used in a browser");let e;try{e=await this.getZKeyDownloadLink();}catch(t){throw console.error("Failed to start download of ZKeys: ",t),t}for(let[t,r]of Object.entries(e)){let o=document.createElement("a");o.href=r,o.download=t,document.body.appendChild(o),o.click(),document.body.removeChild(o);}}createProver(){return new f(this)}async verifyProofOnChain(e){try{let t=await R();}catch(t){return console.error("Failed to verify proof on chain: ",t),!1}return !0}getClonedProps(){let e=JSON.parse(JSON.stringify(this.props));return e.createdAt&&(e.createdAt=new Date(e.createdAt)),e.updatedAt&&(e.updatedAt=new Date(e.updatedAt)),e}canUpdate(){return !!(this.props.id&&![3,2].includes(this.props.status))}async update(e){if(!this.auth)throw new Error("auth is required, add it with Blueprint.addAuth(auth)");if(!this.canUpdate())throw new Error("Blueprint already compied, cannot update");let t=n.blueprintPropsToRequest(e),r;try{r=await _(`${this.baseUrl}/blueprint/${this.props.id}`,t,this.auth);}catch(o){throw console.error("Failed calling POST on /blueprint/ in submitDraft: ",o),o}this.props=n.responseToBlueprintProps(r);}async listAllVersions(){if(!this.props.id)throw new Error("Blueprint was not saved yet");let e;try{e=await u(`${this.baseUrl}/blueprint/versions/${encodeURIComponent(this.props.slug)}`);}catch(t){throw console.error("Failed calling GET on /blueprint/versions/:slug in listAllVersions: ",t),t}return e.blueprints.map(t=>{let r=n.responseToBlueprintProps(t);return new n(r,this.baseUrl,this.auth)})}};var De=n=>{let e=n?.baseUrl||"https://conductor.zk.email";return {createBlueprint(t){if(!n&&!n.auth)throw new Error("You need to specify options.auth to use createBlueprint");return new l(t,e,n.auth)},async getBlueprint(t){return l.getBlueprintById(t,e,n?.auth)},async listBlueprints(t){return l.listBlueprints(e,t,n?.auth)},async getProof(t){return p.getPoofById(t,e)}}};
|
2
|
-
exports.Blueprint=l;exports.Proof=
|
1
|
+
'use strict';Object.defineProperty(exports,'__esModule',{value:true});var viem=require('viem'),chains=require('viem/chains');var b=(o=>(o[o.None=0]="None",o[o.InProgress=1]="InProgress",o[o.Done=2]="Done",o[o.Failed=3]="Failed",o))(b||{});var v="Ov23li0KABFCUsxBEQkn";function T(n,e=v){let t=encodeURIComponent(n);return `https://github.com/login/oauth/authorize?client_id=${e}&scope=user:email&state=${t}`}async function g(n){try{let e=await n.getToken();if(e||(await n.onTokenExpired(),e=await n.getToken()),!e)throw new Error("Failed to get new token");return `Bearer ${e}`}catch(e){throw console.error("Failed to get token from auth"),e}}var w="pk_live_51NXwT8cHf0vYAjQK9LzB3pM6R8gWx2F",x,y=new Promise(n=>{x=n;});console.log("frontend wasm");try{import('@dimidumo/relayer-utils/web').then(async n=>{await n.default(),x(n);}).catch(n=>{console.log("Failed to init WASM: ",n);});}catch{}async function d(n,e,t){try{let r={method:"POST",headers:{"Content-Type":"application/json","x-api-key":w,...t?{Authorization:await g(t)}:{}}};e&&(r.body=JSON.stringify(e));let o=await fetch(n,r),s=await o.json();if(!o.ok)throw new Error(`HTTP error! status: ${o.status}, message: ${s}`);return s}catch(r){throw console.error("POST Error:",r),r}}async function _(n,e,t){try{let r={method:"PATCH",headers:{"Content-Type":"application/json","x-api-key":w,...t?{Authorization:await g(t)}:{}}};e&&(r.body=JSON.stringify(e));let o=await fetch(n,r),s=await o.json();if(!o.ok)throw new Error(`HTTP error! status: ${o.status}, message: ${s}`);return s}catch(r){throw console.error("PATCH Error:",r),r}}async function p(n,e,t){try{let r=n;if(e){let s=new URLSearchParams;Object.entries(e).forEach(([i,a])=>{a&&s.append(i,String(a));}),s.size>0&&(r+=`?${s.toString()}`);}let o=await fetch(r,{method:"GET",headers:{"Content-Type":"application/json","x-api-key":w,...t?{Authorization:await g(t)}:{}}});if(!o.ok)throw new Error(`HTTP error! status: ${o.status}`);return await o.json()}catch(r){throw console.error("GET Error:",r),r}}async function B(n){try{return await(await y).parseEmail(n)}catch(e){throw console.error("Failed to parse email: ",e),e}}async function L(n,e,t=!1){console.log("got eml: ",n);let r=await B(n);if(console.log("got parsed email: ",r),e.emailBodyMaxLength===void 0||e.emailHeaderMaxLength===void 0)throw new Error("emailBodyMaxLength and emailHeaderMaxLength must be provided");let o=r.canonicalized_body.length>e.emailBodyMaxLength?r.canonicalized_body.substring(0,e.emailBodyMaxLength):r.canonicalized_body;console.log("body: ",o);let s=r.canonicalized_header.length>e.emailHeaderMaxLength?r.canonicalized_header.substring(0,e.emailHeaderMaxLength):r.canonicalized_header;console.log("header: ",s);let i=await Promise.all(e.decomposedRegexes.map(a=>k(o,s,a,t)));return console.log("output: ",i),i}async function k(n,e,t,r=!1){console.log("testDecomposedRegex: ",t);let o={parts:t.parts.map(m=>({is_public:"isPublic"in m?m.isPublic:m.is_public,regex_def:"regexDef"in m?m.regexDef:m.regex_def}))};console.log("inputDecomposedRegex: ",o);let s;if(t.location==="body")s=n;else if(t.location==="header")s=e;else throw Error(`Unsupported location ${t.location}`);console.log("inputstr: ",s);let i="maxLength"in t?t.maxLength:t.max_length;console.log("maxLength: ",i);let a=await y,h=a.extractSubstr(s,o,!1);if(console.log("privateResult: ",h),h[0].length>i)throw new Error(`Max length of extracted result was exceeded for decomposed regex ${t.name}`);if(!r)return h;let c=a.extractSubstr(s,o,r);return console.log("result: ",c),c}async function P(n,e,t,r){try{let o={maxHeaderLength:r.emailHeaderMaxLength,maxBodyLength:r.emailBodyMaxLength,ignoreBodyHashCheck:r.ignoreBodyHashCheck,removeSoftLinesBreaks:r.removeSoftLinebreaks,shaPrecomputeSelector:r.shaPrecomputeSelector},s=await y,i=e.map(h=>({...h,parts:h.parts.map(c=>({is_public:c.isPublic||!!c.is_public,regex_def:c.regexDef||!!c.regex_def}))}));console.log("calling generateCircuitInputsWithDecomposedRegexesAndExternalInputs with"),console.log("eml: ",n),console.log("decomposedRegex: ",i),console.log("externalInputs: ",t),console.log("params: ",r);let a=await s.generateCircuitInputsWithDecomposedRegexesAndExternalInputs(n,i,t,o);return JSON.stringify(Object.fromEntries(a))}catch(o){throw console.error("Failed to generate inputs for proof"),o}}function S(n,e="data"){if(!window&&!document)throw Error("startFilesDownload can only be used in a browser");let t=new Blob([n],{type:"application/json"}),r=URL.createObjectURL(t),o=document.createElement("a");o.href=r,o.download=`${e}.json`,document.body.appendChild(o),o.click(),document.body.removeChild(o),URL.revokeObjectURL(r);}var u=class n{blueprint;props;lastCheckedStatus=null;constructor(e,t){if(!(e instanceof l))throw new Error("Invalid blueprint: must be an instance of Blueprint class");if(this.blueprint=e,!t?.id)throw new Error("A proof must have an id");this.props={status:1,...t};}getId(){return this.props.id}async getProofDataDownloadLink(){if(this.props.status!==2)throw new Error("The proving is not done yet.");let e;try{e=await p(`${this.blueprint.baseUrl}/proof/files/${this.props.id}`);}catch(t){throw console.error("Failed calling GET on /proof/files/:id in getProofDataDownloadLink: ",t),t}return e.url}async startFilesDownload(){if(!window&&!document)throw Error("startFilesDownload can only be used in a browser");let e;try{e=await this.getProofDataDownloadLink();}catch(r){throw console.error("Failed to start download of ZKeys: ",r),r}let t=document.createElement("a");t.href=e,t.download="proof_files.zip",document.body.appendChild(t),t.click(),document.body.removeChild(t);}async checkStatus(){if(this.props.status===2)return this.props.status;if(!this.lastCheckedStatus)this.lastCheckedStatus=new Date;else {let r=new Date().getTime()-this.lastCheckedStatus.getTime();r<500&&await new Promise(o=>setTimeout(o,500-r));}let e;try{e=await p(`${this.blueprint.baseUrl}/proof/status/${this.props.id}`);}catch(t){throw console.error("Failed calling GET /blueprint/status in getStatus(): ",t),t}return this.props.status=e.status,e.status}async verifyOnChain(){}static async getPoofById(e,t){let r;try{r=await p(`${t}/proof/${e}`);}catch(i){throw console.error("Failed calling /proof/:id in getProofById: ",i),i}let o=this.responseToProofProps(r),s=await l.getBlueprintById(r.blueprint_id,t);return new n(s,o)}static responseToProofProps(e){return {id:e.id,blueprintId:e.blueprint_id,status:e.status,input:e.input,proof:e.proof,public:e.public,startedAt:new Date(e.started_at.seconds*1e3),provedAt:e.proved_at?new Date(e.proved_at.seconds*1e3):void 0}}};var f=class{options;blueprint;constructor(e,t){if(t?.isLocal===!0)throw new Error("Local proving is not supported yet");if(!(e instanceof l))throw new Error("Invalid blueprint: must be an instance of Blueprint class");this.blueprint=e,this.options={isLocal:!1,...t||{}};}async generateProof(e){console.log("starting generate proof");let t=await this.generateProofRequest(e);for(console.log("got proof: ",t);![2,3].includes(await t.checkStatus()););return t}async generateProofRequest(e){let t=this.blueprint.getId();if(!t)throw new Error("Blueprint of Proover must be initialized in order to create a Proof");let r;try{let i={emailHeaderMaxLength:this.blueprint.props.emailHeaderMaxLength||256,emailBodyMaxLength:this.blueprint.props.emailBodyMaxLength||2560,ignoreBodyHashCheck:this.blueprint.props.ignoreBodyHashCheck||!1,removeSoftLinebreaks:this.blueprint.props.removeSoftLinebreaks||!0,shaPrecomputeSelector:this.blueprint.props.shaPrecomputeSelector};console.log("generating proof inputs"),r=await P(e,this.blueprint.props.decomposedRegexes,this.blueprint.props.externalInputs||[],i);}catch(i){throw console.error("Failed to generate inputs for proof"),i}console.log("got proof input");let o;try{let i={blueprint_id:t,input:r};o=await d(`${this.blueprint.baseUrl}/proof`,i);}catch(i){throw console.error("Failed calling POST on /proof/ in generateProofRequest: ",i),i}let s=u.responseToProofProps(o);return new u(this.blueprint,s)}};var E=(e=>(e.Circom="circom",e))(E||{}),D=(s=>(s[s.None=0]="None",s[s.Draft=1]="Draft",s[s.InProgress=2]="InProgress",s[s.Done=3]="Done",s[s.Failed=4]="Failed",s))(D||{});var U="0x4200000000000000000000000000000000000006",F=[{constant:!0,inputs:[],name:"totalSupply",outputs:[{name:"",type:"uint256"}],type:"function"}],H=viem.createPublicClient({chain:chains.baseSepolia,transport:viem.http()});async function R(){try{return await H.readContract({address:U,abi:F,functionName:"totalSupply"})}catch(n){throw console.error("Error fetching WETH total supply:",n),n}}var l=class n{props;auth;baseUrl;lastCheckedStatus=null;constructor(e,t,r){this.props={ignoreBodyHashCheck:!1,enableHeaderMasking:!1,enableBodyMasking:!1,isPublic:!0,status:1,...e},this.baseUrl=t,this.auth=r;}addAuth(e){this.auth=e;}static async getBlueprintById(e,t,r){let o;try{o=await p(`${t}/blueprint/${e}`);}catch(a){throw console.error("Failed calling /blueprint/:id in getBlueprintById: ",a),a}let s=this.responseToBlueprintProps(o);return new n(s,t,r)}static responseToBlueprintProps(e){return {id:e.id,title:e.title,description:e.description,slug:e.slug,tags:e.tags,emailQuery:e.email_query,circuitName:e.circuit_name,ignoreBodyHashCheck:e.ignore_body_hash_check,shaPrecomputeSelector:e.sha_precompute_selector,emailBodyMaxLength:e.email_body_max_length,emailHeaderMaxLength:e.email_header_max_length,removeSoftLinebreaks:e.remove_soft_linebreaks,githubUsername:e.github_username,senderDomain:e.sender_domain,enableHeaderMasking:e.enable_header_masking,enableBodyMasking:e.enable_body_masking,zkFramework:e.zk_framework,isPublic:e.is_public,createdAt:new Date(e.created_at.seconds*1e3),updatedAt:new Date(e.updated_at.seconds*1e3),externalInputs:e.external_inputs?.map(r=>({name:r.name,maxLength:r.max_length})),decomposedRegexes:e.decomposed_regexes?.map(r=>({parts:r.parts.map(o=>({isPublic:o.is_public,regexDef:o.regex_def})),name:r.name,maxLength:r.max_length,location:r.location})),status:e.status,verifierContract:{address:e.verifier_contract_address,chain:e.verifier_contract_chain},version:e.version}}static blueprintPropsToRequest(e){return {id:e.id,title:e.title,description:e.description,slug:e.slug,tags:e.tags,email_query:e.emailQuery,circuit_name:e.circuitName,ignore_body_hash_check:e.ignoreBodyHashCheck,sha_precompute_selector:e.shaPrecomputeSelector,email_body_max_length:e.emailBodyMaxLength,email_header_max_length:e.emailHeaderMaxLength,remove_soft_linebreaks:e.removeSoftLinebreaks,github_username:e.githubUsername,sender_domain:e.senderDomain,enable_header_masking:e.enableHeaderMasking,enable_body_masking:e.enableBodyMasking,zk_framework:e.zkFramework,is_public:e.isPublic,external_inputs:e.externalInputs?.map(r=>({name:r.name,max_length:r.maxLength})),decomposed_regexes:e.decomposedRegexes?.map(r=>({parts:r.parts.map(o=>({is_public:o.isPublic||o.is_public,regex_def:o.regexDef||o.regex_def})),name:r.name,max_length:r.maxLength,location:r.location})),verifier_contract_address:e.verifierContract?.address,verifier_contract_chain:e.verifierContract?.chain}}async submitDraft(){if(!this.auth)throw new Error("auth is required, add it with Blueprint.addAuth(auth)");if(this.props.id)throw new Error("Blueprint was already saved");let e=n.blueprintPropsToRequest(this.props),t;try{t=await d(`${this.baseUrl}/blueprint`,e,this.auth);}catch(r){throw console.error("Failed calling POST on /blueprint/ in submitDraft: ",r),r}this.props=n.responseToBlueprintProps(t);}async submitNewVersionDraft(e){if(!this.auth)throw new Error("auth is required, add it with Blueprint.addAuth(auth)");let t=n.blueprintPropsToRequest(e),r;try{r=await d(`${this.baseUrl}/blueprint`,t,this.auth);}catch(o){throw console.error("Failed calling POST on /blueprint/ in submitDraft: ",o),o}this.props=n.responseToBlueprintProps(r);}async submitNewVersion(e){if(!this.auth)throw new Error("auth is required, add it with Blueprint.addAuth(auth)");await this.submitNewVersionDraft(e);try{await d(`${this.baseUrl}/blueprint/compile/${this.props.id}`,null,this.auth);}catch(t){throw console.error("Failed calling POST on /blueprint/compile in submit: ",t),t}}static async listBlueprints(e,t,r){let o={skip:t?.skip,limit:t?.limit,sort:t?.sort,status:t?.status,is_public:t?.isPublic,search:t?.search},s;try{s=await p(`${e}/blueprint`,o);}catch(i){throw console.error("Failed calling POST on /blueprint/ in submitDraft: ",i),i}return s.blueprints?s.blueprints.map(i=>{let a=n.responseToBlueprintProps(i);return new n(a,e,r)}):[]}async submit(){if(!this.auth)throw new Error("auth is required, add it with Blueprint.addAuth(auth)");if(!this.props.id)try{await this.submitDraft();}catch(t){throw console.error("Failed to create blueprint: ",t),t}let e=await this._checkStatus();if(3===e)throw new Error("The circuits are already compiled.");if(2===e)throw new Error("The circuits already being compiled, please wait.");try{await d(`${this.baseUrl}/blueprint/compile/${this.props.id}`,null,this.auth);}catch(t){throw console.error("Failed calling POST on /blueprint/compile in submit: ",t),t}}async _checkStatus(){let e;try{e=await p(`${this.baseUrl}/blueprint/status/${this.props.id}`);}catch(t){throw console.error("Failed calling GET /blueprint/status in getStatus(): ",t),t}return this.props.status=e.status,e.status}async checkStatus(){if(!this.props.id)return this.props.status;if([4,3].includes(this.props.status))return this.props.status;if(!this.lastCheckedStatus)this.lastCheckedStatus=new Date;else {let r=new Date().getTime()-this.lastCheckedStatus.getTime();r<500&&await new Promise(o=>setTimeout(o,500-r));}return await this._checkStatus()}getId(){return this.props.id||null}async getZKeyDownloadLink(){if(this.props.status!==3)throw new Error("The circuits are not compiled yet, nothing to download.");let e;try{e=await p(`${this.baseUrl}/blueprint/zkey/${this.props.id}`),console.log("response: ",e);}catch(t){throw console.error("Failed calling GET on /blueprint/zkey/:id in getZKeyDownloadLink: ",t),t}return e.urls}async startZKeyDownload(){if(!window&&!document)throw Error("startZKeyDownload can only be used in a browser");let e;try{e=await this.getZKeyDownloadLink();}catch(t){throw console.error("Failed to start download of ZKeys: ",t),t}for(let[t,r]of Object.entries(e)){let o=document.createElement("a");o.href=r,o.download=t,document.body.appendChild(o),o.click(),document.body.removeChild(o);}}createProver(){return new f(this)}async verifyProofOnChain(e){try{let t=await R();}catch(t){return console.error("Failed to verify proof on chain: ",t),!1}return !0}getClonedProps(){let e=JSON.parse(JSON.stringify(this.props));return e.createdAt&&(e.createdAt=new Date(e.createdAt)),e.updatedAt&&(e.updatedAt=new Date(e.updatedAt)),e}canUpdate(){return !!(this.props.id&&![3,2].includes(this.props.status))}async update(e){if(!this.auth)throw new Error("auth is required, add it with Blueprint.addAuth(auth)");if(!this.canUpdate())throw new Error("Blueprint already compied, cannot update");let t=n.blueprintPropsToRequest(e),r;try{r=await _(`${this.baseUrl}/blueprint/${this.props.id}`,t,this.auth);}catch(o){throw console.error("Failed calling POST on /blueprint/ in submitDraft: ",o),o}this.props=n.responseToBlueprintProps(r);}async listAllVersions(){if(!this.props.id)throw new Error("Blueprint was not saved yet");let e;try{e=await p(`${this.baseUrl}/blueprint/versions/${encodeURIComponent(this.props.slug)}`);}catch(t){throw console.error("Failed calling GET on /blueprint/versions/:slug in listAllVersions: ",t),t}return e.blueprints.map(t=>{let r=n.responseToBlueprintProps(t);return new n(r,this.baseUrl,this.auth)})}};var De=n=>{let e=n?.baseUrl||"https://conductor.zk.email";return {createBlueprint(t){if(!n&&!n.auth)throw new Error("You need to specify options.auth to use createBlueprint");return new l(t,e,n.auth)},async getBlueprint(t){return l.getBlueprintById(t,e,n?.auth)},async listBlueprints(t){return l.listBlueprints(e,t,n?.auth)},async getProof(t){return u.getPoofById(t,e)}}};
|
2
|
+
exports.Blueprint=l;exports.Proof=u;exports.ProofStatus=b;exports.Status=D;exports.ZkFramework=E;exports.default=De;exports.generateProofInputs=P;exports.getLoginWithGithubUrl=T;exports.parseEmail=B;exports.startJsonFileDownload=S;exports.testBlueprint=L;exports.testDecomposedRegex=k;//# sourceMappingURL=index.js.map
|
3
3
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"sources":["../src/types/proof.ts","../src/auth.ts","../src/utils.ts","../src/proof.ts","../src/prover.ts","../src/types/blueprint.ts","../src/chain/index.ts","../src/blueprint.ts","../src/index.ts"],"names":["ProofStatus","GITHUB_CLIENT_ID","getLoginWithGithubUrl","callbackUrl","githubClientId","state","getTokenFromAuth","auth","token","err","PUBLIC_SDK_KEY","relayerUtilsResolver","relayerUtils","resolve","rl","post","url","data","request","response","body","error","patch","get","queryParams","fullUrl","searchParams","key","value","parseEmail","eml","testBlueprint","blueprint","revealPrivate","parsedEmail","header","dcr","testDecomposedRegex","decomposedRegex","inputDecomposedRegex","p","inputStr","maxLength","utils","privateResult","generateProofInputs","decomposedRegexes","externalInputs","params","internalParams","decomposedRegexesCleaned","inputs","startJsonFileDownload","json","name","blob","link","Proof","_Proof","props","Blueprint","sinceLastChecked","r","id","baseUrl","proofResponse","proofProps","Prover","options","proof","blueprintId","input","requestData","ZkFramework","Status","WETHContractAddress","WETHContractABI","client","createPublicClient","baseSepolia","http","verifyProofOnChain","_Blueprint","blueprintResponse","blueprintProps","regex","part","newProps","requestOptions","status","urls","result","cloned","src_default","sdkOptions"],"mappings":"6HAGO,IAAKA,CACVA,CAAAA,CAAAA,CAAAA,GAAAA,CAAAA,CAAAA,CAAAA,CAAA,IACAA,CAAAA,CAAAA,CAAAA,CAAAA,MAAAA,CAAAA,CAAAA,CAAAA,CAAAA,CAAA,2BACAA,CAAA,CAAA,CAAA,CAAA,IAAA,CAAA,CAAA,CAAA,CAAA,MAAA,CACAA,CAAA,CAAA,CAAA,CAAA,MAAA,CAAA,CAAA,CAAA,CAAA,QAAA,CAJUA,OAAA,ECAZ,EAAA,IAAMC,CAAmB,CAAA,sBAAA,CAIlB,SAASC,CACdC,CAAAA,CAAAA,CACAC,CAAiBH,CAAAA,CAAAA,CACT,CACR,IAAMI,CAAAA,CAAQ,kBAAmBF,CAAAA,CAAW,EAC5C,OAAO,CAAA,mDAAA,EAAsDC,CAAc,CAAA,wBAAA,EAA2BC,CAAK,CAC7G,CAAA,CAEA,eAAsBC,CAAAA,CAAiBC,EAA6B,CAClE,GAAI,CACF,IAAIC,EAAQ,MAAMD,CAAAA,CAAK,QAAS,EAAA,CAOhC,GALKC,CACH,GAAA,MAAMD,CAAK,CAAA,cAAA,GACXC,CAAQ,CAAA,MAAMD,CAAK,CAAA,QAAA,IAGjB,CAACC,CAAAA,CACH,MAAM,IAAI,MAAM,yBAAyB,CAAA,CAG3C,OAAO,CAAA,OAAA,EAAUA,CAAK,CACxB,CAAA,CAAA,MAASC,CAAK,CAAA,CACZ,cAAQ,KAAM,CAAA,+BAA+B,CACvCA,CAAAA,CACR,CACF,CCjCA,IAAMC,CAAiB,CAAA,0CAAA,CAuBnBC,EACEC,CAA0C,CAAA,IAAI,OAASC,CAAAA,CAAAA,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AAM,QAAS/B,CAAAA,CAAAA,CAA4B,CACzC,OAAON,EAAM,WAAYM,CAAAA,CAAAA,CAAIC,CAAO,CACtC,CACF,CACF","file":"index.js","sourcesContent":["import { ServerDate } from \"./blueprint\";\n\n// According to protobufs\nexport enum ProofStatus {\n None,\n InProgress,\n Done,\n Failed,\n}\n\nexport type ProofProps = {\n id: string;\n blueprintId: string;\n input: string;\n proof?: string;\n public?: string;\n status?: ProofStatus;\n startedAt?: Date;\n provedAt?: Date;\n};\n\nexport type ProofResponse = {\n id: string;\n blueprint_id: string;\n input: string;\n proof?: string;\n public?: string;\n started_at: ServerDate;\n proved_at?: ServerDate;\n status: number;\n};\n\nexport type ProofRequest = {\n blueprint_id: string;\n input: string;\n};\n\nexport type GenerateProofInputsParams = {\n emailHeaderMaxLength: number;\n emailBodyMaxLength: number;\n ignoreBodyHashCheck: boolean;\n removeSoftLinebreaks: boolean;\n shaPrecomputeSelector?: string;\n};\n\nexport type GenerateProofInputsParamsInternal = {\n maxHeaderLength: number;\n maxBodyLength: number;\n ignoreBodyHashCheck: boolean;\n removeSoftLinesBreaks: boolean;\n shaPrecomputeSelector?: string;\n};\n","import { Auth } from \"./types/auth\";\n\n// prod\nconst GITHUB_CLIENT_ID = \"Ov23li0KABFCUsxBEQkn\";\n\n// const GITHUB_CLIENT_ID = \"Ov23liUVyAeZK1bxoAkh\";\n\nexport function getLoginWithGithubUrl(\n callbackUrl: string,\n githubClientId = GITHUB_CLIENT_ID\n): string {\n const state = encodeURIComponent(callbackUrl);\n return `https://github.com/login/oauth/authorize?client_id=${githubClientId}&scope=user:email&state=${state}`;\n}\n\nexport async function getTokenFromAuth(auth: Auth): Promise<string> {\n try {\n let token = await auth.getToken();\n\n if (!token) {\n await auth.onTokenExpired();\n token = await auth.getToken();\n }\n\n if (!token) {\n throw new Error(\"Failed to get new token\");\n }\n\n return `Bearer ${token}`;\n } catch (err) {\n console.error(\"Failed to get token from auth\");\n throw err;\n }\n}\n","const PUBLIC_SDK_KEY = \"pk_live_51NXwT8cHf0vYAjQK9LzB3pM6R8gWx2F\";\n\nimport {\n Blueprint,\n DecomposedRegex,\n DecomposedRegexJson,\n DecomposedRegexPart,\n DecomposedRegexPartJson,\n} from \"./blueprint\";\nimport { Auth } from \"./types/auth\";\nimport { getTokenFromAuth } from \"./auth\";\nimport type * as NodeUtils from \"@dimidumo/relayer-utils/node\";\nimport type * as WebUtils from \"@dimidumo/relayer-utils/web\";\nimport {\n BlueprintProps,\n ExternalInput,\n GenerateProofInputsParams,\n GenerateProofInputsParamsInternal,\n} from \"./types\";\nimport { log } from \"console\";\n\ntype RelayerUtilsType = typeof NodeUtils | typeof WebUtils;\n\nlet relayerUtilsResolver: (value: any) => void;\nconst relayerUtils: Promise<RelayerUtilsType> = new Promise((resolve) => {\n relayerUtilsResolver = resolve;\n});\n\n// @ts-ignore\n// if (typeof window === \"undefined\" || typeof Deno !== \"undefined\") {\nif (false) {\n console.warn(\"Relayer utils won't work when used server side\");\n // console.log(\"Initializing for node\");\n // import(\"@dimidumo/relayer-utils/node\")\n // .then((rl) => {\n // relayerUtilsResolver(rl);\n // })\n // .catch((err) => console.log(\"failed to init WASM on node: \", err));\n} else {\n console.log(\"frontend wasm\");\n try {\n import(\"@dimidumo/relayer-utils/web\")\n .then(async (rl) => {\n // @ts-ignore\n await rl.default();\n relayerUtilsResolver(rl);\n })\n .catch((err) => {\n console.log(\"Failed to init WASM: \", err);\n });\n } catch (err) {}\n}\n\nexport async function post<T>(url: string, data?: object | null, auth?: Auth): Promise<T> {\n try {\n const request: RequestInit = {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"x-api-key\": PUBLIC_SDK_KEY,\n ...(!auth ? {} : { Authorization: await getTokenFromAuth(auth) }),\n },\n };\n\n if (data) {\n request.body = JSON.stringify(data);\n }\n\n const response = await fetch(url, request);\n\n const body = await response.json();\n\n if (!response.ok) {\n throw new Error(`HTTP error! status: ${response.status}, message: ${body}`);\n }\n\n return body;\n } catch (error) {\n // TODO: Handle token expired\n console.error(\"POST Error:\", error);\n throw error;\n }\n}\n\nexport async function patch<T>(url: string, data?: object | null, auth?: Auth): Promise<T> {\n try {\n const request: RequestInit = {\n method: \"PATCH\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"x-api-key\": PUBLIC_SDK_KEY,\n ...(!auth ? {} : { Authorization: await getTokenFromAuth(auth) }),\n },\n };\n\n if (data) {\n request.body = JSON.stringify(data);\n }\n\n const response = await fetch(url, request);\n\n const body = await response.json();\n\n if (!response.ok) {\n throw new Error(`HTTP error! status: ${response.status}, message: ${body}`);\n }\n\n return body;\n } catch (error) {\n console.error(\"PATCH Error:\", error);\n throw error;\n }\n}\n\nexport async function get<T>(url: string, queryParams?: object | null, auth?: Auth): Promise<T> {\n try {\n let fullUrl = url;\n if (queryParams) {\n const searchParams = new URLSearchParams();\n Object.entries(queryParams).forEach(([key, value]) => {\n if (value) {\n searchParams.append(key, String(value));\n }\n });\n if (searchParams.size > 0) {\n fullUrl += `?${searchParams.toString()}`;\n }\n }\n\n const response = await fetch(fullUrl, {\n method: \"GET\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"x-api-key\": PUBLIC_SDK_KEY,\n ...(!auth ? {} : { Authorization: await getTokenFromAuth(auth) }),\n },\n });\n\n if (!response.ok) {\n throw new Error(`HTTP error! status: ${response.status}`);\n }\n\n return await response.json();\n } catch (error) {\n console.error(\"GET Error:\", error);\n throw error;\n }\n}\n\n// Provisional type, delete once libary types\ntype ParsedEmail = {\n canonicalized_header: string;\n canonicalized_body: string;\n signature: number[];\n public_key: any[];\n cleaned_body: string;\n headers: Map<string, string[]>;\n};\n\nexport async function parseEmail(eml: string): Promise<ParsedEmail> {\n try {\n const utils = await relayerUtils;\n const parsedEmail = await utils.parseEmail(eml);\n return parsedEmail as ParsedEmail;\n } catch (err) {\n console.error(\"Failed to parse email: \", err);\n throw err;\n }\n}\n\nexport async function testBlueprint(\n eml: string,\n blueprint: BlueprintProps,\n revealPrivate = false\n): Promise<string[][]> {\n const parsedEmail = await parseEmail(eml);\n\n if (blueprint.emailBodyMaxLength === undefined || blueprint.emailHeaderMaxLength === undefined) {\n throw new Error(\"emailBodyMaxLength and emailHeaderMaxLength must be provided\");\n }\n\n const body =\n parsedEmail.canonicalized_body.length > blueprint.emailBodyMaxLength\n ? parsedEmail.canonicalized_body.substring(0, blueprint.emailBodyMaxLength)\n : parsedEmail.canonicalized_body;\n const header =\n parsedEmail.canonicalized_header.length > blueprint.emailHeaderMaxLength\n ? parsedEmail.canonicalized_header.substring(0, blueprint.emailHeaderMaxLength)\n : parsedEmail.canonicalized_header;\n\n const output = await Promise.all(\n blueprint.decomposedRegexes.map((dcr: DecomposedRegex) =>\n testDecomposedRegex(body, header, dcr, revealPrivate)\n )\n );\n\n return output;\n}\n\nexport async function testDecomposedRegex(\n body: string,\n header: string,\n decomposedRegex: DecomposedRegex | DecomposedRegexJson,\n revealPrivate = false\n): Promise<string[]> {\n const inputDecomposedRegex = {\n parts: decomposedRegex.parts.map((p: DecomposedRegexPart | DecomposedRegexPartJson) => ({\n is_public: \"isPublic\" in p ? p.isPublic : p.is_public,\n regex_def: \"regexDef\" in p ? p.regexDef : p.regex_def,\n })),\n };\n\n let inputStr: string;\n if (decomposedRegex.location === \"body\") {\n inputStr = body;\n } else if (decomposedRegex.location === \"header\") {\n inputStr = header;\n } else {\n throw Error(`Unsupported location ${decomposedRegex.location}`);\n }\n\n const maxLength =\n \"maxLength\" in decomposedRegex ? decomposedRegex.maxLength : decomposedRegex.max_length;\n\n const utils = await relayerUtils;\n const privateResult = utils.extractSubstr(inputStr, inputDecomposedRegex, false);\n\n if (privateResult[0].length > maxLength) {\n throw new Error(\n `Max length of extracted result was exceeded for decomposed regex ${decomposedRegex.name}`\n );\n }\n\n if (!revealPrivate) {\n return privateResult;\n }\n\n const result = utils.extractSubstr(inputStr, inputDecomposedRegex, revealPrivate);\n return result;\n}\n\nexport async function generateProofInputs(\n eml: string,\n decomposedRegexes: DecomposedRegex[],\n externalInputs: ExternalInput[],\n params: GenerateProofInputsParams\n): Promise<string> {\n try {\n const internalParams: GenerateProofInputsParamsInternal = {\n maxHeaderLength: params.emailHeaderMaxLength,\n maxBodyLength: params.emailBodyMaxLength,\n ignoreBodyHashCheck: params.ignoreBodyHashCheck,\n removeSoftLinesBreaks: params.removeSoftLinebreaks,\n shaPrecomputeSelector: params.shaPrecomputeSelector,\n };\n\n const utils = await relayerUtils;\n // console.log(\"got relayer utils\");\n // console.log(\"actually creating proof inputs with params: \", internalParams);\n\n const decomposedRegexesCleaned = decomposedRegexes.map((dcr) => {\n return {\n ...dcr,\n parts: dcr.parts.map((p) => ({\n // @ts-ignore\n is_public: p.isPublic || !!p.is_public,\n // @ts-ignore\n regex_def: p.regexDef || !!p.regex_def,\n })),\n };\n });\n\n console.log(\"calling generateCircuitInputsWithDecomposedRegexesAndExternalInputs with\");\n console.log(\"eml: \", eml);\n console.log(\"decomposedRegex: \", decomposedRegexesCleaned);\n console.log(\"externalInputs: \", externalInputs);\n console.log(\"params: \", params);\n\n const inputs = await utils.generateCircuitInputsWithDecomposedRegexesAndExternalInputs(\n eml,\n decomposedRegexesCleaned,\n externalInputs,\n internalParams\n );\n\n return JSON.stringify(Object.fromEntries(inputs));\n } catch (err) {\n console.error(\"Failed to generate inputs for proof\");\n throw err;\n }\n}\n\nexport function startJsonFileDownload(json: string, name = \"data\") {\n if (!window && !document) {\n throw Error(\"startFilesDownload can only be used in a browser\");\n }\n\n const blob = new Blob([json], { type: \"application/json\" });\n const url = URL.createObjectURL(blob);\n\n const link = document.createElement(\"a\");\n link.href = url;\n link.download = `${name}.json`;\n document.body.appendChild(link);\n link.click();\n document.body.removeChild(link);\n URL.revokeObjectURL(url);\n}\n","import { Blueprint, Status } from \"./blueprint\";\nimport { ProofProps, ProofResponse, ProofStatus } from \"./types/proof\";\nimport { get } from \"./utils\";\n\n/**\n * A generated proof. You get get proof data and verify proofs on chain.\n */\nexport class Proof {\n blueprint: Blueprint;\n props: ProofProps;\n private lastCheckedStatus: Date | null = null;\n\n constructor(blueprint: Blueprint, props: ProofProps) {\n if (!(blueprint instanceof Blueprint)) {\n throw new Error(\"Invalid blueprint: must be an instance of Blueprint class\");\n }\n this.blueprint = blueprint;\n\n if (!props?.id) {\n throw new Error(\"A proof must have an id\");\n }\n\n this.props = {\n status: ProofStatus.InProgress,\n ...props,\n };\n }\n\n getId(): string {\n return this.props.id;\n }\n\n /**\n * Returns a download link for the files of the proof.\n * @returns The the url to download a zip of the proof files.\n */\n async getProofDataDownloadLink(): Promise<string> {\n if (this.props.status !== ProofStatus.Done) {\n throw new Error(\"The proving is not done yet.\");\n }\n\n let response: { url: string };\n try {\n response = await get<{ url: string }>(\n `${this.blueprint.baseUrl}/proof/files/${this.props.id}`\n );\n } catch (err) {\n console.error(\"Failed calling GET on /proof/files/:id in getProofDataDownloadLink: \", err);\n throw err;\n }\n\n return response.url;\n }\n\n async startFilesDownload() {\n if (!window && !document) {\n throw Error(\"startFilesDownload can only be used in a browser\");\n }\n\n let url: string;\n try {\n url = await this.getProofDataDownloadLink();\n } catch (err) {\n console.error(\"Failed to start download of ZKeys: \", err);\n throw err;\n }\n\n const link = document.createElement(\"a\");\n link.href = url;\n link.download = \"proof_files.zip\"; // Set the desired filename\n document.body.appendChild(link);\n link.click();\n document.body.removeChild(link);\n }\n\n /**\n * Checks the status of proof.\n * checkStatus can be used in a while(await checkStatus()) loop, since it will wait a fixed\n * amount of time before the second time you call it.\n * @returns A promise with the Status.\n */\n async checkStatus(): Promise<ProofStatus> {\n if (this.props.status === ProofStatus.Done) {\n return this.props.status;\n }\n\n // Waits for a fixed period of time before you can call checkStatus again\n // This enables you to put checkStatus in a while(await checkStatu()) loop\n if (!this.lastCheckedStatus) {\n this.lastCheckedStatus = new Date();\n } else {\n const waitTime = 500;\n const sinceLastChecked = new Date().getTime() - this.lastCheckedStatus.getTime();\n if (sinceLastChecked < waitTime) {\n await new Promise((r) => setTimeout(r, waitTime - sinceLastChecked));\n }\n }\n\n // Check status\n let response: { status: ProofStatus };\n try {\n response = await get<{ status: ProofStatus }>(\n `${this.blueprint.baseUrl}/proof/status/${this.props.id}`\n );\n } catch (err) {\n console.error(\"Failed calling GET /blueprint/status in getStatus(): \", err);\n throw err;\n }\n\n this.props.status = response.status;\n return response.status;\n }\n\n async verifyOnChain() {}\n\n /**\n * Fetches an existing Proof from the database.\n * @param id - Id of the Proof.\n * @returns A promise that resolves to a new instance of Proof.\n */\n public static async getPoofById(id: string, baseUrl: string): Promise<Proof> {\n let proofResponse: ProofResponse;\n try {\n proofResponse = await get<ProofResponse>(`${baseUrl}/proof/${id}`);\n } catch (err) {\n console.error(\"Failed calling /proof/:id in getProofById: \", err);\n throw err;\n }\n\n const proofProps = this.responseToProofProps(proofResponse);\n const blueprint = await Blueprint.getBlueprintById(proofResponse.blueprint_id, baseUrl);\n\n return new Proof(blueprint, proofProps);\n }\n\n public static responseToProofProps(response: ProofResponse): ProofProps {\n const props: ProofProps = {\n id: response.id,\n blueprintId: response.blueprint_id,\n status: response.status as ProofStatus,\n input: response.input,\n proof: response.proof,\n public: response.public,\n startedAt: new Date(response.started_at.seconds * 1000),\n provedAt: response.proved_at ? new Date(response.proved_at.seconds * 1000) : undefined,\n };\n return props;\n }\n}\n","import { Blueprint } from \"./blueprint\";\nimport { Proof } from \"./proof\";\nimport {\n GenerateProofInputsParams,\n ProofProps,\n ProofRequest,\n ProofResponse,\n ProofStatus,\n} from \"./types/proof\";\nimport { ProverOptions } from \"./types/prover\";\nimport { generateProofInputs, post } from \"./utils\";\n\n/**\n * Represents a Prover generated from a blueprint that can generate Proofs\n */\nexport class Prover {\n options: ProverOptions;\n blueprint: Blueprint;\n\n constructor(blueprint: Blueprint, options?: ProverOptions) {\n if (options?.isLocal === true) {\n throw new Error(\"Local proving is not supported yet\");\n }\n\n if (!(blueprint instanceof Blueprint)) {\n throw new Error(\"Invalid blueprint: must be an instance of Blueprint class\");\n }\n\n this.blueprint = blueprint;\n\n // Use defaults for unset fields\n this.options = {\n isLocal: false,\n ...(!!options ? options : {}),\n };\n }\n\n // TODO: Add parsed email input\n /**\n * Generates a proof for a given email.\n * @param eml - Email to prove agains the blueprint of this Prover.\n * @returns A promise that resolves to a new instance of Proof. The Proof will have the status\n * Done or Failed.\n */\n async generateProof(eml: string): Promise<Proof> {\n console.log(\"starting generate proof\");\n const proof = await this.generateProofRequest(eml);\n console.log(\"got proof: \", proof);\n\n // Wait for proof to finish\n while (![ProofStatus.Done, ProofStatus.Failed].includes(await proof.checkStatus())) {}\n return proof;\n }\n\n // TODO: Add parsed email input\n /**\n * Starts proving for a given email.\n * @param eml - Email to prove agains the blueprint of this Prover.\n * @returns A promise that resolves to a new instance of Proof. The Proof will have the status\n * InProgress.\n */\n async generateProofRequest(eml: string): Promise<Proof> {\n const blueprintId = this.blueprint.getId();\n if (!blueprintId) {\n throw new Error(\"Blueprint of Proover must be initialized in order to create a Proof\");\n }\n\n let input: string;\n try {\n // TODO: Do we use defaults?\n const params: GenerateProofInputsParams = {\n emailHeaderMaxLength: this.blueprint.props.emailHeaderMaxLength || 256,\n emailBodyMaxLength: this.blueprint.props.emailBodyMaxLength || 2560,\n ignoreBodyHashCheck: this.blueprint.props.ignoreBodyHashCheck || false,\n removeSoftLinebreaks: this.blueprint.props.removeSoftLinebreaks || true,\n shaPrecomputeSelector: this.blueprint.props.shaPrecomputeSelector,\n };\n console.log(\"generating proof inputs\");\n input = await generateProofInputs(\n eml,\n this.blueprint.props.decomposedRegexes,\n this.blueprint.props.externalInputs || [],\n params\n );\n } catch (err) {\n console.error(\"Failed to generate inputs for proof\");\n throw err;\n }\n\n console.log(\"got proof input\");\n let response: ProofResponse;\n try {\n const requestData: ProofRequest = {\n blueprint_id: blueprintId,\n input,\n };\n\n response = await post<ProofResponse>(`${this.blueprint.baseUrl}/proof`, requestData);\n } catch (err) {\n console.error(\"Failed calling POST on /proof/ in generateProofRequest: \", err);\n throw err;\n }\n\n const proofProps = Proof.responseToProofProps(response);\n return new Proof(this.blueprint, proofProps);\n }\n}\n","export type BlueprintProps = {\n id?: string;\n title: string;\n description?: string;\n slug?: string;\n tags?: string[];\n emailQuery?: string;\n circuitName: string;\n ignoreBodyHashCheck?: boolean;\n shaPrecomputeSelector?: string;\n emailBodyMaxLength?: number;\n emailHeaderMaxLength?: number;\n removeSoftLinebreaks?: boolean;\n githubUsername?: string;\n senderDomain?: string;\n enableHeaderMasking?: boolean;\n enableBodyMasking?: boolean;\n zkFramework?: ZkFramework;\n isPublic?: boolean;\n createdAt?: Date;\n updatedAt?: Date;\n externalInputs?: ExternalInput[];\n decomposedRegexes: DecomposedRegex[];\n status?: Status;\n verifierContract?: VerifierContract;\n version?: number;\n};\n\nexport type DecomposedRegex = {\n parts: DecomposedRegexPart[];\n name: string;\n maxLength: number;\n location: \"body\" | \"header\";\n};\n\nexport type DecomposedRegexPart = {\n isPublic: boolean;\n regexDef: string;\n};\n\nexport type DecomposedRegexJson = {\n parts: DecomposedRegexPartJson[];\n name: string;\n max_length: number;\n location: \"body\" | \"header\";\n};\n\nexport type DecomposedRegexPartJson = {\n is_public: boolean;\n regex_def: string;\n};\n\nexport type ExternalInput = {\n name: string;\n maxLength: number;\n};\n\nexport enum ZkFramework {\n Circom = \"circom\",\n}\n\n// According to protobufs\nexport enum Status {\n None,\n Draft,\n InProgress,\n Done,\n Failed,\n}\n\nexport type VerifierContract = {\n address?: string;\n chain: number;\n};\n\nexport type BlueprintRequest = {\n id?: string;\n title: string;\n description?: string;\n slug?: string;\n tags?: string[];\n email_query?: string;\n circuit_name?: string;\n ignore_body_hash_check?: boolean;\n sha_precompute_selector?: string;\n email_body_max_length?: number;\n email_header_max_length?: number;\n remove_soft_linebreaks?: boolean;\n // TODO: Make non ? after login with github\n github_username?: string;\n sender_domain?: string;\n enable_header_masking?: boolean;\n enable_body_masking?: boolean;\n zk_framework?: string;\n is_public?: boolean;\n external_inputs?: ExternalInputResponse[];\n decomposed_regexes: DecomposedRegexResponse[];\n status?: string;\n verifier_contract_address?: string;\n verifier_contract_chain?: number;\n version?: number;\n};\n\nexport type BlueprintResponse = {\n id: string;\n title: string;\n description: string;\n slug: string;\n tags: string[];\n email_query: string;\n circuit_name: string;\n ignore_body_hash_check: boolean;\n sha_precompute_selector: string;\n email_body_max_length: number;\n email_header_max_length?: number;\n remove_soft_linebreaks?: boolean;\n github_username?: string;\n sender_domain: string;\n enable_header_masking?: boolean;\n enable_body_masking?: boolean;\n zk_framework: string;\n is_public: boolean;\n created_at: ServerDate;\n updated_at: ServerDate;\n external_inputs: ExternalInputResponse[];\n decomposed_regexes: DecomposedRegexResponse[];\n status: number;\n verifier_contract_address: string;\n verifier_contract_chain: number;\n version: number;\n};\n\nexport type ServerDate = {\n seconds: number;\n nanos: number;\n};\n\nexport type ExternalInputResponse = {\n name: string;\n max_length: number;\n};\n\nexport type DecomposedRegexResponse = {\n parts: DecomposedRegexPartResponse[];\n name: string;\n max_length: number;\n location: \"body\" | \"header\";\n};\n\nexport type DecomposedRegexPartResponse = {\n is_public: boolean;\n regex_def: string;\n};\n\nexport type ListBlueprintsOptions = {\n skip?: number;\n limit?: number;\n sort?: -1 | 1;\n status?: Status;\n isPublic?: boolean;\n search?: string;\n};\n\nexport type ListBlueprintsOptionsRequest = {\n skip?: number;\n limit?: number;\n sort?: -1 | 1;\n status?: Status;\n is_public?: boolean;\n search?: string;\n};\n\nexport type DownloadUrls = Record<string, string>;\n","import { createPublicClient, http } from \"viem\";\nimport { baseSepolia } from \"viem/chains\";\n\nconst WETHContractAddress = \"0x4200000000000000000000000000000000000006\";\n\nconst WETHContractABI = [\n {\n constant: true,\n inputs: [],\n name: \"totalSupply\",\n outputs: [{ name: \"\", type: \"uint256\" }],\n type: \"function\",\n },\n] as const;\n\nconst client = createPublicClient({\n chain: baseSepolia,\n transport: http(),\n});\n\nexport async function verifyProofOnChain() {\n try {\n const totalSupply = await client.readContract({\n address: WETHContractAddress,\n abi: WETHContractABI,\n functionName: \"totalSupply\",\n });\n\n return totalSupply;\n } catch (error) {\n console.error(\"Error fetching WETH total supply:\", error);\n throw error;\n }\n}\n","import { Proof } from \"viem/_types/types/proof\";\nimport { Prover } from \"./prover\";\nimport {\n BlueprintProps,\n BlueprintRequest,\n BlueprintResponse,\n DownloadUrls,\n ListBlueprintsOptions,\n ListBlueprintsOptionsRequest,\n Status,\n ZkFramework,\n} from \"./types/blueprint\";\nimport { get, patch, post } from \"./utils\";\nimport { verifyProofOnChain } from \"./chain\";\nimport { Auth } from \"./types/auth\";\n\n/**\n * Represents a Regex Blueprint including the decomposed regex access to the circuit.\n */\nexport class Blueprint {\n // TODO: Implement getter and setter pattern\n props: BlueprintProps;\n auth?: Auth;\n baseUrl: string;\n\n private lastCheckedStatus: Date | null = null;\n\n constructor(props: BlueprintProps, baseUrl: string, auth?: Auth) {\n // Use defaults for unset fields\n this.props = {\n ignoreBodyHashCheck: false,\n enableHeaderMasking: false,\n enableBodyMasking: false,\n isPublic: true,\n status: Status.Draft,\n ...props,\n };\n\n this.baseUrl = baseUrl;\n this.auth = auth;\n }\n\n addAuth(auth: Auth) {\n this.auth = auth;\n }\n\n /**\n * Fetches an existing RegexBlueprint from the database.\n * @param {string} id - Id of the RegexBlueprint.\n * @returns A promise that resolves to a new instance of RegexBlueprint.\n */\n public static async getBlueprintById(\n id: string,\n baseUrl: string,\n auth?: Auth\n ): Promise<Blueprint> {\n let blueprintResponse: BlueprintResponse;\n try {\n blueprintResponse = await get<BlueprintResponse>(`${baseUrl}/blueprint/${id}`);\n } catch (err) {\n console.error(\"Failed calling /blueprint/:id in getBlueprintById: \", err);\n throw err;\n }\n\n const blueprintProps = this.responseToBlueprintProps(blueprintResponse);\n\n const blueprint = new Blueprint(blueprintProps, baseUrl, auth);\n\n return blueprint;\n }\n\n // Maps the blueprint API response to the BlueprintProps\n private static responseToBlueprintProps(response: BlueprintResponse): BlueprintProps {\n const props: BlueprintProps = {\n id: response.id,\n title: response.title,\n description: response.description,\n slug: response.slug,\n tags: response.tags,\n emailQuery: response.email_query,\n circuitName: response.circuit_name,\n ignoreBodyHashCheck: response.ignore_body_hash_check,\n shaPrecomputeSelector: response.sha_precompute_selector,\n emailBodyMaxLength: response.email_body_max_length,\n emailHeaderMaxLength: response.email_header_max_length,\n removeSoftLinebreaks: response.remove_soft_linebreaks,\n githubUsername: response.github_username,\n senderDomain: response.sender_domain,\n enableHeaderMasking: response.enable_header_masking,\n enableBodyMasking: response.enable_body_masking,\n zkFramework: response.zk_framework as ZkFramework,\n isPublic: response.is_public,\n createdAt: new Date(response.created_at.seconds * 1000),\n updatedAt: new Date(response.updated_at.seconds * 1000),\n externalInputs: response.external_inputs?.map((input) => ({\n name: input.name,\n maxLength: input.max_length,\n })),\n decomposedRegexes: response.decomposed_regexes?.map((regex) => ({\n parts: regex.parts.map((part) => ({\n isPublic: part.is_public,\n regexDef: part.regex_def,\n })),\n name: regex.name,\n maxLength: regex.max_length,\n location: regex.location,\n })),\n status: response.status as Status,\n verifierContract: {\n address: response.verifier_contract_address,\n chain: response.verifier_contract_chain,\n },\n version: response.version,\n };\n\n return props;\n }\n\n // Maps the BlueprintProps to the BlueprintResponse\n private static blueprintPropsToRequest(props: BlueprintProps): BlueprintRequest {\n const response: BlueprintRequest = {\n id: props.id,\n title: props.title,\n description: props.description,\n slug: props.slug,\n tags: props.tags,\n email_query: props.emailQuery,\n circuit_name: props.circuitName,\n ignore_body_hash_check: props.ignoreBodyHashCheck,\n sha_precompute_selector: props.shaPrecomputeSelector,\n email_body_max_length: props.emailBodyMaxLength,\n email_header_max_length: props.emailHeaderMaxLength,\n remove_soft_linebreaks: props.removeSoftLinebreaks,\n github_username: props.githubUsername,\n sender_domain: props.senderDomain,\n enable_header_masking: props.enableHeaderMasking,\n enable_body_masking: props.enableBodyMasking,\n zk_framework: props.zkFramework,\n is_public: props.isPublic,\n external_inputs: props.externalInputs?.map((input) => ({\n name: input.name,\n max_length: input.maxLength,\n })),\n decomposed_regexes: props.decomposedRegexes?.map((regex) => ({\n parts: regex.parts.map((part) => ({\n // @ts-ignore\n is_public: part.isPublic || part.is_public,\n // @ts-ignore\n regex_def: part.regexDef || part.regex_def,\n })),\n name: regex.name,\n max_length: regex.maxLength,\n location: regex.location,\n })),\n verifier_contract_address: props.verifierContract?.address,\n verifier_contract_chain: props.verifierContract?.chain,\n };\n\n return response;\n }\n\n /**\n * Submits a new RegexBlueprint to the registry as draft.\n * This does not compile the circuits yet and you will still be able to make changes.\n * @returns A promise. Once it resolves, `getId` can be called.\n */\n public async submitDraft() {\n if (!this.auth) {\n throw new Error(\"auth is required, add it with Blueprint.addAuth(auth)\");\n }\n\n if (this.props.id) {\n throw new Error(\"Blueprint was already saved\");\n }\n\n const requestData = Blueprint.blueprintPropsToRequest(this.props);\n\n let response: BlueprintResponse;\n try {\n response = await post<BlueprintResponse>(`${this.baseUrl}/blueprint`, requestData, this.auth);\n } catch (err) {\n console.error(\"Failed calling POST on /blueprint/ in submitDraft: \", err);\n throw err;\n }\n\n this.props = Blueprint.responseToBlueprintProps(response);\n }\n\n /**\n * Submits a new version of the RegexBlueprint to the registry as draft.\n * This does not compile the circuits yet and you will still be able to make changes.\n * @param newProps - The updated blueprint props.\n * @returns A promise. Once it resolves, the current Blueprint will be replaced with the new one.\n */\n public async submitNewVersionDraft(newProps: BlueprintProps) {\n if (!this.auth) {\n throw new Error(\"auth is required, add it with Blueprint.addAuth(auth)\");\n }\n\n const requestData = Blueprint.blueprintPropsToRequest(newProps);\n\n let response: BlueprintResponse;\n try {\n response = await post<BlueprintResponse>(`${this.baseUrl}/blueprint`, requestData, this.auth);\n } catch (err) {\n console.error(\"Failed calling POST on /blueprint/ in submitDraft: \", err);\n throw err;\n }\n\n this.props = Blueprint.responseToBlueprintProps(response);\n }\n\n /**\n * Submits a new version of the blueprint. This will save the new blueprint version\n * and start the compilation.\n * This will also overwrite the current Blueprint with its new version, even if the last\n * version was not compiled yet.\n * @param newProps - The updated blueprint props.\n */\n async submitNewVersion(newProps: BlueprintProps) {\n if (!this.auth) {\n throw new Error(\"auth is required, add it with Blueprint.addAuth(auth)\");\n }\n\n await this.submitNewVersionDraft(newProps);\n\n // We don't check the status here, since we are compiling directly after submiting the draft.\n\n // Submit compile request\n try {\n await post<{ status: Status }>(\n `${this.baseUrl}/blueprint/compile/${this.props.id}`,\n null,\n this.auth\n );\n } catch (err) {\n // We don't set the status here, since the api call can't fail due to the actual job failing\n // It can only due to connectivity issues or the job runner not being available\n console.error(\"Failed calling POST on /blueprint/compile in submit: \", err);\n throw err;\n }\n }\n\n /**\n * Lists blueblueprints, only including the latest version per unique slug.\n * @param options - Options to filter the blueprints by.\n * @returns A promise. Once it resolves, `getId` can be called.\n */\n public static async listBlueprints(\n baseUrl: string,\n options?: ListBlueprintsOptions,\n auth?: Auth\n ): Promise<Blueprint[]> {\n const requestOptions: ListBlueprintsOptionsRequest = {\n skip: options?.skip,\n limit: options?.limit,\n sort: options?.sort,\n status: options?.status,\n is_public: options?.isPublic,\n search: options?.search,\n };\n\n let response: { blueprints?: BlueprintResponse[] };\n try {\n response = await get<{ blueprints?: BlueprintResponse[] }>(\n `${baseUrl}/blueprint`,\n requestOptions\n );\n } catch (err) {\n console.error(\"Failed calling POST on /blueprint/ in submitDraft: \", err);\n throw err;\n }\n\n if (!response.blueprints) {\n return [];\n }\n\n return response.blueprints.map((blueprintResponse) => {\n const blueprintProps = Blueprint.responseToBlueprintProps(blueprintResponse);\n return new Blueprint(blueprintProps, baseUrl, auth);\n });\n }\n\n /**\n * Submits a blueprint. This will save the blueprint if it didn't exist before\n * and start the compilation.\n */\n async submit() {\n if (!this.auth) {\n throw new Error(\"auth is required, add it with Blueprint.addAuth(auth)\");\n }\n\n // If the blueprint wasn't save yet, we save it first to db\n if (!this.props.id) {\n try {\n await this.submitDraft();\n } catch (err) {\n console.error(\"Failed to create blueprint: \", err);\n throw err;\n }\n }\n\n const status = await this._checkStatus();\n\n // TODO: Should we allow retry on failed?\n if (Status.Done === status) {\n throw new Error(\"The circuits are already compiled.\");\n }\n if (Status.InProgress === status) {\n throw new Error(\"The circuits already being compiled, please wait.\");\n }\n\n // Submit compile request\n try {\n await post<{ status: Status }>(\n `${this.baseUrl}/blueprint/compile/${this.props.id}`,\n null,\n this.auth\n );\n } catch (err) {\n // We don't set the status here, since the api call can't fail due to the actual job failing\n // It can only due to connectivity issues or the job runner not being available\n console.error(\"Failed calling POST on /blueprint/compile in submit: \", err);\n throw err;\n }\n }\n\n // Request status from server and updates props.status\n private async _checkStatus(): Promise<Status> {\n let response: { status: Status };\n try {\n response = await get<{ status: Status }>(`${this.baseUrl}/blueprint/status/${this.props.id}`);\n } catch (err) {\n console.error(\"Failed calling GET /blueprint/status in getStatus(): \", err);\n throw err;\n }\n\n this.props.status = response.status;\n return response.status;\n }\n\n /**\n * Checks the status of blueprint.\n * checkStatus can be used in a while(await checkStatus()) loop, since it will wait a fixed\n * amount of time the second time you call it.\n * @returns A promise with the Status.\n */\n async checkStatus(): Promise<Status> {\n // Blueprint wasn't saved yet, return default status\n if (!this.props.id) {\n return this.props.status!;\n }\n\n if ([Status.Failed, Status.Done].includes(this.props.status!)) {\n return this.props.status!;\n }\n\n // Waits for a fixed period of time before you can call checkStatus again\n // This enables you to put checkStatus in a while(await checkStatus()) loop\n if (!this.lastCheckedStatus) {\n this.lastCheckedStatus = new Date();\n } else {\n // TODO: change for prod to one minute\n const waitTime = 0.5 * 1_000; // TODO: should be one minute;\n const sinceLastChecked = new Date().getTime() - this.lastCheckedStatus.getTime();\n if (sinceLastChecked < waitTime) {\n await new Promise((r) => setTimeout(r, waitTime - sinceLastChecked));\n }\n }\n\n const status = await this._checkStatus();\n\n return status;\n }\n\n /**\n * Get the id of the blueprint.\n * @returns The id of the blueprint. If it was not saved yet, return null.\n */\n getId(): string | null {\n return this.props.id || null;\n }\n\n /**\n * Returns a download link for the ZKeys of the blueprint.\n * @returns The the url to download the ZKeys.\n */\n async getZKeyDownloadLink(): Promise<DownloadUrls> {\n if (this.props.status !== Status.Done) {\n throw new Error(\"The circuits are not compiled yet, nothing to download.\");\n }\n\n let response: { urls: DownloadUrls };\n try {\n response = await get<{ urls: DownloadUrls }>(\n `${this.baseUrl}/blueprint/zkey/${this.props.id}`\n );\n console.log(\"response: \", response);\n } catch (err) {\n console.error(\"Failed calling GET on /blueprint/zkey/:id in getZKeyDownloadLink: \", err);\n throw err;\n }\n\n return response.urls;\n }\n\n /**\n * Directly starts a download of the ZKeys in the browser.\n * Must be called within a user action, like a button click.\n */\n async startZKeyDownload() {\n if (!window && !document) {\n throw Error(\"startZKeyDownload can only be used in a browser\");\n }\n\n let urls: DownloadUrls;\n try {\n urls = await this.getZKeyDownloadLink();\n } catch (err) {\n console.error(\"Failed to start download of ZKeys: \", err);\n throw err;\n }\n\n for (const [name, url] of Object.entries(urls)) {\n const link = document.createElement(\"a\");\n link.href = url;\n link.download = name; // Set the desired filename\n document.body.appendChild(link);\n link.click();\n document.body.removeChild(link);\n }\n }\n\n /**\n * Creates an instance of Prover with which you can create proofs.\n * @returns An instance of Prover.\n */\n createProver() {\n return new Prover(this);\n }\n\n /**\n * Verifies a proof on chain.\n * @param proof - The generated proof you want to verify.\n * @returns A true if the verification was successfull, false if it failed.\n */\n async verifyProofOnChain(proof: Proof): Promise<boolean> {\n try {\n const result = await verifyProofOnChain();\n } catch (err) {\n console.error(\"Failed to verify proof on chain: \", err);\n return false;\n }\n return true;\n }\n\n /**\n * Returns a deep cloned version of the Blueprints props.\n * This can be used to update properties and then to use them with createNewVersion.\n * @param proof - The generated proof you want to verify.\n * @returns A true if the verification was successfull, false if it failed.\n */\n getClonedProps(): BlueprintProps {\n const cloned = JSON.parse(JSON.stringify(this.props));\n\n // Conver date strings\n if (cloned.createdAt) {\n cloned.createdAt = new Date(cloned.createdAt);\n }\n if (cloned.updatedAt) {\n cloned.updatedAt = new Date(cloned.updatedAt);\n }\n\n return cloned;\n }\n\n /**\n * Returns true if the blueprint can be updated. A blueprint can be updated if the circuits\n * haven't beed compiled yet, i.e. the status is not Done. The blueprint also must be saved\n * already before it can be updated.\n * @returns true if it can be updated\n */\n canUpdate(): boolean {\n return !!(this.props.id && ![Status.Done, Status.InProgress].includes(this.props.status!));\n }\n\n /**\n * Updates an existing blueprint that is not compiled yet.\n * @param newProps - The props the blueprint should be updated to.\n * @returns a promise.\n */\n async update(newProps: BlueprintProps) {\n if (!this.auth) {\n throw new Error(\"auth is required, add it with Blueprint.addAuth(auth)\");\n }\n\n if (!this.canUpdate()) {\n throw new Error(\"Blueprint already compied, cannot update\");\n }\n\n const requestData = Blueprint.blueprintPropsToRequest(newProps);\n\n let response: BlueprintResponse;\n try {\n response = await patch<BlueprintResponse>(\n `${this.baseUrl}/blueprint/${this.props.id}`,\n requestData,\n this.auth\n );\n } catch (err) {\n console.error(\"Failed calling POST on /blueprint/ in submitDraft: \", err);\n throw err;\n }\n\n this.props = Blueprint.responseToBlueprintProps(response);\n }\n\n async listAllVersions(): Promise<Blueprint[]> {\n if (!this.props.id) {\n throw new Error(\"Blueprint was not saved yet\");\n }\n let response: { blueprints: BlueprintResponse[] };\n try {\n response = await get<{ blueprints: BlueprintResponse[] }>(\n `${this.baseUrl}/blueprint/versions/${encodeURIComponent(this.props.slug!)}`\n );\n } catch (err) {\n console.error(\"Failed calling GET on /blueprint/versions/:slug in listAllVersions: \", err);\n throw err;\n }\n\n return response.blueprints.map((blueprintResponse) => {\n const blueprintProps = Blueprint.responseToBlueprintProps(blueprintResponse);\n return new Blueprint(blueprintProps, this.baseUrl, this.auth);\n });\n }\n}\n\n// export {\n// BlueprintProps,\n// DecomposedRegex,\n// DecomposedRegexPart,\n// ExternalInput,\n// ZkFramework,\n// Status,\n// VerifierContract,\n// RevealHeaderFields,\n// } from \"./types/blueprint\";\n\nexport * from \"./types/blueprint\";\n","import { Blueprint, BlueprintProps, ListBlueprintsOptions } from \"./blueprint\";\nimport { Proof } from \"./proof\";\nimport { SdkOptions } from \"./types/sdk\";\n\n// Export Types\nexport * from \"./types/blueprint\";\nexport { Blueprint } from \"./blueprint\";\nexport * from \"./types/proof\";\nexport { Proof } from \"./proof\";\nexport type { Auth } from \"./types/auth\";\n\n// Exports that don't need initialization or options\nexport {\n testDecomposedRegex,\n parseEmail,\n startJsonFileDownload,\n generateProofInputs,\n testBlueprint,\n} from \"./utils\";\nexport { getLoginWithGithubUrl } from \"./auth\";\n\n// Exported sdk, functions that need initialization\nexport default (sdkOptions?: SdkOptions) => {\n const baseUrl = sdkOptions?.baseUrl || \"https://conductor.zk.email\";\n return {\n createBlueprint(props: BlueprintProps) {\n if (!sdkOptions && !sdkOptions!.auth) {\n throw new Error(\"You need to specify options.auth to use createBlueprint\");\n }\n const blueprint = new Blueprint(props, baseUrl, sdkOptions!.auth);\n return blueprint;\n },\n async getBlueprint(id: string): Promise<Blueprint> {\n return Blueprint.getBlueprintById(id, baseUrl, sdkOptions?.auth);\n },\n async listBlueprints(options?: ListBlueprintsOptions): Promise<Blueprint[]> {\n return Blueprint.listBlueprints(baseUrl, options, sdkOptions?.auth);\n },\n async getProof(id: string): Promise<Proof> {\n return Proof.getPoofById(id, baseUrl);\n },\n };\n};\n"]}
|
1
|
+
{"version":3,"sources":["../src/types/proof.ts","../src/auth.ts","../src/utils.ts","../src/proof.ts","../src/prover.ts","../src/types/blueprint.ts","../src/chain/index.ts","../src/blueprint.ts","../src/index.ts"],"names":["ProofStatus","GITHUB_CLIENT_ID","getLoginWithGithubUrl","callbackUrl","githubClientId","state","getTokenFromAuth","auth","token","err","PUBLIC_SDK_KEY","relayerUtilsResolver","relayerUtils","resolve","rl","post","url","data","request","response","body","error","patch","get","queryParams","fullUrl","searchParams","key","value","parseEmail","eml","testBlueprint","blueprint","revealPrivate","parsedEmail","header","output","dcr","testDecomposedRegex","decomposedRegex","inputDecomposedRegex","p","inputStr","maxLength","utils","privateResult","result","generateProofInputs","decomposedRegexes","externalInputs","params","internalParams","decomposedRegexesCleaned","inputs","startJsonFileDownload","json","name","blob","link","Proof","_Proof","props","Blueprint","sinceLastChecked","r","id","baseUrl","proofResponse","proofProps","Prover","options","proof","blueprintId","input","requestData","ZkFramework","Status","WETHContractAddress","WETHContractABI","client","createPublicClient","baseSepolia","http","verifyProofOnChain","_Blueprint","blueprintResponse","blueprintProps","regex","part","newProps","requestOptions","status","urls","cloned","src_default","sdkOptions"],"mappings":"6HAGO,IAAKA,OACVA,CAAA,CAAA,CAAA,CAAA,IAAA,CAAA,CAAA,CAAA,CAAA,MAAA,CACAA,CAAA,CAAA,CAAA,CAAA,UAAA,CAAA,CAAA,CAAA,CAAA,YAAA,CACAA,IAAA,IACAA,CAAAA,CAAAA,CAAAA,CAAAA,MAAAA,CAAAA,CAAAA,CAAAA,CAAAA,CAAA,MAJUA,CAAAA,CAAAA,CAAAA,CAAAA,QAAAA,CAAAA,CAAAA,CAAAA,EAAAA,CAAAA,EAAA,ICAZ,IAAMC,CAAAA,CAAmB,sBAIlB,CAAA,SAASC,EACdC,CACAC,CAAAA,CAAAA,CAAiBH,CACT,CAAA,CACR,IAAMI,CAAQ,CAAA,kBAAA,CAAmBF,CAAW,CAAA,CAC5C,OAAO,CAAsDC,mDAAAA,EAAAA,CAAc,CAA2BC,wBAAAA,EAAAA,CAAK,EAC7G,CAEA,eAAsBC,CAAiBC,CAAAA,CAAAA,CAA6B,CAClE,GAAI,CACF,IAAIC,CAAAA,CAAQ,MAAMD,CAAK,CAAA,QAAA,EAOvB,CAAA,GALKC,IACH,MAAMD,CAAAA,CAAK,cAAe,EAAA,CAC1BC,EAAQ,MAAMD,CAAAA,CAAK,QAAS,EAAA,CAAA,CAG1B,CAACC,CACH,CAAA,MAAM,IAAI,KAAA,CAAM,yBAAyB,CAG3C,CAAA,OAAO,CAAUA,OAAAA,EAAAA,CAAK,EACxB,CAASC,MAAAA,CAAAA,CAAK,CACZ,MAAA,OAAA,CAAQ,MAAM,+BAA+B,CAAA,CACvCA,CACR,CACF,CCjCA,IAAMC,CAAiB,CAAA,0CAAA,CAuBnBC,CACEC,CAAAA,CAAAA,CAA0C,IAAI,OAASC,CAAAA,CAAA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kC,CAAc,EAAA,CAACA,EAAY,IAC9B,CAAA,MAAM,IAAI,KAAA,CAAM,yDAAyD,CAG3E,CAAA,OADkB,IAAIjC,CAAUD,CAAAA,CAAAA,CAAOK,EAAS6B,CAAY,CAAA,IAAI,CAElE,CAAA,CACA,MAAM,YAAa9B,CAAAA,CAAAA,CAAgC,CACjD,OAAOH,EAAU,gBAAiBG,CAAAA,CAAAA,CAAIC,CAAS6B,CAAAA,CAAAA,EAAY,IAAI,CACjE,CAAA,CACA,MAAM,cAAA,CAAezB,EAAuD,CAC1E,OAAOR,CAAU,CAAA,cAAA,CAAeI,EAASI,CAASyB,CAAAA,CAAAA,EAAY,IAAI,CACpE,EACA,MAAM,QAAA,CAAS9B,CAA4B,CAAA,CACzC,OAAON,CAAM,CAAA,WAAA,CAAYM,EAAIC,CAAO,CACtC,CACF,CACF","file":"index.js","sourcesContent":["import { ServerDate } from \"./blueprint\";\n\n// According to protobufs\nexport enum ProofStatus {\n None,\n InProgress,\n Done,\n Failed,\n}\n\nexport type ProofProps = {\n id: string;\n blueprintId: string;\n input: string;\n proof?: string;\n public?: string;\n status?: ProofStatus;\n startedAt?: Date;\n provedAt?: Date;\n};\n\nexport type ProofResponse = {\n id: string;\n blueprint_id: string;\n input: string;\n proof?: string;\n public?: string;\n started_at: ServerDate;\n proved_at?: ServerDate;\n status: number;\n};\n\nexport type ProofRequest = {\n blueprint_id: string;\n input: string;\n};\n\nexport type GenerateProofInputsParams = {\n emailHeaderMaxLength: number;\n emailBodyMaxLength: number;\n ignoreBodyHashCheck: boolean;\n removeSoftLinebreaks: boolean;\n shaPrecomputeSelector?: string;\n};\n\nexport type GenerateProofInputsParamsInternal = {\n maxHeaderLength: number;\n maxBodyLength: number;\n ignoreBodyHashCheck: boolean;\n removeSoftLinesBreaks: boolean;\n shaPrecomputeSelector?: string;\n};\n","import { Auth } from \"./types/auth\";\n\n// prod\nconst GITHUB_CLIENT_ID = \"Ov23li0KABFCUsxBEQkn\";\n\n// const GITHUB_CLIENT_ID = \"Ov23liUVyAeZK1bxoAkh\";\n\nexport function getLoginWithGithubUrl(\n callbackUrl: string,\n githubClientId = GITHUB_CLIENT_ID\n): string {\n const state = encodeURIComponent(callbackUrl);\n return `https://github.com/login/oauth/authorize?client_id=${githubClientId}&scope=user:email&state=${state}`;\n}\n\nexport async function getTokenFromAuth(auth: Auth): Promise<string> {\n try {\n let token = await auth.getToken();\n\n if (!token) {\n await auth.onTokenExpired();\n token = await auth.getToken();\n }\n\n if (!token) {\n throw new Error(\"Failed to get new token\");\n }\n\n return `Bearer ${token}`;\n } catch (err) {\n console.error(\"Failed to get token from auth\");\n throw err;\n }\n}\n","const PUBLIC_SDK_KEY = \"pk_live_51NXwT8cHf0vYAjQK9LzB3pM6R8gWx2F\";\n\nimport {\n Blueprint,\n DecomposedRegex,\n DecomposedRegexJson,\n DecomposedRegexPart,\n DecomposedRegexPartJson,\n} from \"./blueprint\";\nimport { Auth } from \"./types/auth\";\nimport { getTokenFromAuth } from \"./auth\";\nimport type * as NodeUtils from \"@dimidumo/relayer-utils/node\";\nimport type * as WebUtils from \"@dimidumo/relayer-utils/web\";\nimport {\n BlueprintProps,\n ExternalInput,\n GenerateProofInputsParams,\n GenerateProofInputsParamsInternal,\n} from \"./types\";\nimport { log } from \"console\";\n\ntype RelayerUtilsType = typeof NodeUtils | typeof WebUtils;\n\nlet relayerUtilsResolver: (value: any) => void;\nconst relayerUtils: Promise<RelayerUtilsType> = new Promise((resolve) => {\n relayerUtilsResolver = resolve;\n});\n\n// @ts-ignore\n// if (typeof window === \"undefined\" || typeof Deno !== \"undefined\") {\nif (false) {\n console.warn(\"Relayer utils won't work when used server side\");\n // console.log(\"Initializing for node\");\n // import(\"@dimidumo/relayer-utils/node\")\n // .then((rl) => {\n // relayerUtilsResolver(rl);\n // })\n // .catch((err) => console.log(\"failed to init WASM on node: \", err));\n} else {\n console.log(\"frontend wasm\");\n try {\n import(\"@dimidumo/relayer-utils/web\")\n .then(async (rl) => {\n // @ts-ignore\n await rl.default();\n relayerUtilsResolver(rl);\n })\n .catch((err) => {\n console.log(\"Failed to init WASM: \", err);\n });\n } catch (err) {}\n}\n\nexport async function post<T>(url: string, data?: object | null, auth?: Auth): Promise<T> {\n try {\n const request: RequestInit = {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"x-api-key\": PUBLIC_SDK_KEY,\n ...(!auth ? {} : { Authorization: await getTokenFromAuth(auth) }),\n },\n };\n\n if (data) {\n request.body = JSON.stringify(data);\n }\n\n const response = await fetch(url, request);\n\n const body = await response.json();\n\n if (!response.ok) {\n throw new Error(`HTTP error! status: ${response.status}, message: ${body}`);\n }\n\n return body;\n } catch (error) {\n // TODO: Handle token expired\n console.error(\"POST Error:\", error);\n throw error;\n }\n}\n\nexport async function patch<T>(url: string, data?: object | null, auth?: Auth): Promise<T> {\n try {\n const request: RequestInit = {\n method: \"PATCH\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"x-api-key\": PUBLIC_SDK_KEY,\n ...(!auth ? {} : { Authorization: await getTokenFromAuth(auth) }),\n },\n };\n\n if (data) {\n request.body = JSON.stringify(data);\n }\n\n const response = await fetch(url, request);\n\n const body = await response.json();\n\n if (!response.ok) {\n throw new Error(`HTTP error! status: ${response.status}, message: ${body}`);\n }\n\n return body;\n } catch (error) {\n console.error(\"PATCH Error:\", error);\n throw error;\n }\n}\n\nexport async function get<T>(url: string, queryParams?: object | null, auth?: Auth): Promise<T> {\n try {\n let fullUrl = url;\n if (queryParams) {\n const searchParams = new URLSearchParams();\n Object.entries(queryParams).forEach(([key, value]) => {\n if (value) {\n searchParams.append(key, String(value));\n }\n });\n if (searchParams.size > 0) {\n fullUrl += `?${searchParams.toString()}`;\n }\n }\n\n const response = await fetch(fullUrl, {\n method: \"GET\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"x-api-key\": PUBLIC_SDK_KEY,\n ...(!auth ? {} : { Authorization: await getTokenFromAuth(auth) }),\n },\n });\n\n if (!response.ok) {\n throw new Error(`HTTP error! status: ${response.status}`);\n }\n\n return await response.json();\n } catch (error) {\n console.error(\"GET Error:\", error);\n throw error;\n }\n}\n\n// Provisional type, delete once libary types\ntype ParsedEmail = {\n canonicalized_header: string;\n canonicalized_body: string;\n signature: number[];\n public_key: any[];\n cleaned_body: string;\n headers: Map<string, string[]>;\n};\n\nexport async function parseEmail(eml: string): Promise<ParsedEmail> {\n try {\n const utils = await relayerUtils;\n const parsedEmail = await utils.parseEmail(eml);\n return parsedEmail as ParsedEmail;\n } catch (err) {\n console.error(\"Failed to parse email: \", err);\n throw err;\n }\n}\n\nexport async function testBlueprint(\n eml: string,\n blueprint: BlueprintProps,\n revealPrivate = false\n): Promise<string[][]> {\n console.log(\"got eml: \", eml);\n const parsedEmail = await parseEmail(eml);\n console.log(\"got parsed email: \", parsedEmail);\n\n if (blueprint.emailBodyMaxLength === undefined || blueprint.emailHeaderMaxLength === undefined) {\n throw new Error(\"emailBodyMaxLength and emailHeaderMaxLength must be provided\");\n }\n\n const body =\n parsedEmail.canonicalized_body.length > blueprint.emailBodyMaxLength\n ? parsedEmail.canonicalized_body.substring(0, blueprint.emailBodyMaxLength)\n : parsedEmail.canonicalized_body;\n console.log(\"body: \", body);\n const header =\n parsedEmail.canonicalized_header.length > blueprint.emailHeaderMaxLength\n ? parsedEmail.canonicalized_header.substring(0, blueprint.emailHeaderMaxLength)\n : parsedEmail.canonicalized_header;\n console.log(\"header: \", header);\n\n const output = await Promise.all(\n blueprint.decomposedRegexes.map((dcr: DecomposedRegex) =>\n testDecomposedRegex(body, header, dcr, revealPrivate)\n )\n );\n console.log(\"output: \", output);\n\n return output;\n}\n\nexport async function testDecomposedRegex(\n body: string,\n header: string,\n decomposedRegex: DecomposedRegex | DecomposedRegexJson,\n revealPrivate = false\n): Promise<string[]> {\n console.log(\"testDecomposedRegex: \", decomposedRegex);\n const inputDecomposedRegex = {\n parts: decomposedRegex.parts.map((p: DecomposedRegexPart | DecomposedRegexPartJson) => ({\n is_public: \"isPublic\" in p ? p.isPublic : p.is_public,\n regex_def: \"regexDef\" in p ? p.regexDef : p.regex_def,\n })),\n };\n console.log(\"inputDecomposedRegex: \", inputDecomposedRegex);\n\n let inputStr: string;\n if (decomposedRegex.location === \"body\") {\n inputStr = body;\n } else if (decomposedRegex.location === \"header\") {\n inputStr = header;\n } else {\n throw Error(`Unsupported location ${decomposedRegex.location}`);\n }\n\n console.log(\"inputstr: \", inputStr);\n\n const maxLength =\n \"maxLength\" in decomposedRegex ? decomposedRegex.maxLength : decomposedRegex.max_length;\n console.log(\"maxLength: \", maxLength);\n\n const utils = await relayerUtils;\n const privateResult = utils.extractSubstr(inputStr, inputDecomposedRegex, false);\n console.log(\"privateResult: \", privateResult);\n\n if (privateResult[0].length > maxLength) {\n throw new Error(\n `Max length of extracted result was exceeded for decomposed regex ${decomposedRegex.name}`\n );\n }\n\n if (!revealPrivate) {\n return privateResult;\n }\n\n const result = utils.extractSubstr(inputStr, inputDecomposedRegex, revealPrivate);\n console.log(\"result: \", result);\n return result;\n}\n\nexport async function generateProofInputs(\n eml: string,\n decomposedRegexes: DecomposedRegex[],\n externalInputs: ExternalInput[],\n params: GenerateProofInputsParams\n): Promise<string> {\n try {\n const internalParams: GenerateProofInputsParamsInternal = {\n maxHeaderLength: params.emailHeaderMaxLength,\n maxBodyLength: params.emailBodyMaxLength,\n ignoreBodyHashCheck: params.ignoreBodyHashCheck,\n removeSoftLinesBreaks: params.removeSoftLinebreaks,\n shaPrecomputeSelector: params.shaPrecomputeSelector,\n };\n\n const utils = await relayerUtils;\n // console.log(\"got relayer utils\");\n // console.log(\"actually creating proof inputs with params: \", internalParams);\n\n const decomposedRegexesCleaned = decomposedRegexes.map((dcr) => {\n return {\n ...dcr,\n parts: dcr.parts.map((p) => ({\n // @ts-ignore\n is_public: p.isPublic || !!p.is_public,\n // @ts-ignore\n regex_def: p.regexDef || !!p.regex_def,\n })),\n };\n });\n\n console.log(\"calling generateCircuitInputsWithDecomposedRegexesAndExternalInputs with\");\n console.log(\"eml: \", eml);\n console.log(\"decomposedRegex: \", decomposedRegexesCleaned);\n console.log(\"externalInputs: \", externalInputs);\n console.log(\"params: \", params);\n\n const inputs = await utils.generateCircuitInputsWithDecomposedRegexesAndExternalInputs(\n eml,\n decomposedRegexesCleaned,\n externalInputs,\n internalParams\n );\n\n return JSON.stringify(Object.fromEntries(inputs));\n } catch (err) {\n console.error(\"Failed to generate inputs for proof\");\n throw err;\n }\n}\n\nexport function startJsonFileDownload(json: string, name = \"data\") {\n if (!window && !document) {\n throw Error(\"startFilesDownload can only be used in a browser\");\n }\n\n const blob = new Blob([json], { type: \"application/json\" });\n const url = URL.createObjectURL(blob);\n\n const link = document.createElement(\"a\");\n link.href = url;\n link.download = `${name}.json`;\n document.body.appendChild(link);\n link.click();\n document.body.removeChild(link);\n URL.revokeObjectURL(url);\n}\n","import { Blueprint, Status } from \"./blueprint\";\nimport { ProofProps, ProofResponse, ProofStatus } from \"./types/proof\";\nimport { get } from \"./utils\";\n\n/**\n * A generated proof. You get get proof data and verify proofs on chain.\n */\nexport class Proof {\n blueprint: Blueprint;\n props: ProofProps;\n private lastCheckedStatus: Date | null = null;\n\n constructor(blueprint: Blueprint, props: ProofProps) {\n if (!(blueprint instanceof Blueprint)) {\n throw new Error(\"Invalid blueprint: must be an instance of Blueprint class\");\n }\n this.blueprint = blueprint;\n\n if (!props?.id) {\n throw new Error(\"A proof must have an id\");\n }\n\n this.props = {\n status: ProofStatus.InProgress,\n ...props,\n };\n }\n\n getId(): string {\n return this.props.id;\n }\n\n /**\n * Returns a download link for the files of the proof.\n * @returns The the url to download a zip of the proof files.\n */\n async getProofDataDownloadLink(): Promise<string> {\n if (this.props.status !== ProofStatus.Done) {\n throw new Error(\"The proving is not done yet.\");\n }\n\n let response: { url: string };\n try {\n response = await get<{ url: string }>(\n `${this.blueprint.baseUrl}/proof/files/${this.props.id}`\n );\n } catch (err) {\n console.error(\"Failed calling GET on /proof/files/:id in getProofDataDownloadLink: \", err);\n throw err;\n }\n\n return response.url;\n }\n\n async startFilesDownload() {\n if (!window && !document) {\n throw Error(\"startFilesDownload can only be used in a browser\");\n }\n\n let url: string;\n try {\n url = await this.getProofDataDownloadLink();\n } catch (err) {\n console.error(\"Failed to start download of ZKeys: \", err);\n throw err;\n }\n\n const link = document.createElement(\"a\");\n link.href = url;\n link.download = \"proof_files.zip\"; // Set the desired filename\n document.body.appendChild(link);\n link.click();\n document.body.removeChild(link);\n }\n\n /**\n * Checks the status of proof.\n * checkStatus can be used in a while(await checkStatus()) loop, since it will wait a fixed\n * amount of time before the second time you call it.\n * @returns A promise with the Status.\n */\n async checkStatus(): Promise<ProofStatus> {\n if (this.props.status === ProofStatus.Done) {\n return this.props.status;\n }\n\n // Waits for a fixed period of time before you can call checkStatus again\n // This enables you to put checkStatus in a while(await checkStatu()) loop\n if (!this.lastCheckedStatus) {\n this.lastCheckedStatus = new Date();\n } else {\n const waitTime = 500;\n const sinceLastChecked = new Date().getTime() - this.lastCheckedStatus.getTime();\n if (sinceLastChecked < waitTime) {\n await new Promise((r) => setTimeout(r, waitTime - sinceLastChecked));\n }\n }\n\n // Check status\n let response: { status: ProofStatus };\n try {\n response = await get<{ status: ProofStatus }>(\n `${this.blueprint.baseUrl}/proof/status/${this.props.id}`\n );\n } catch (err) {\n console.error(\"Failed calling GET /blueprint/status in getStatus(): \", err);\n throw err;\n }\n\n this.props.status = response.status;\n return response.status;\n }\n\n async verifyOnChain() {}\n\n /**\n * Fetches an existing Proof from the database.\n * @param id - Id of the Proof.\n * @returns A promise that resolves to a new instance of Proof.\n */\n public static async getPoofById(id: string, baseUrl: string): Promise<Proof> {\n let proofResponse: ProofResponse;\n try {\n proofResponse = await get<ProofResponse>(`${baseUrl}/proof/${id}`);\n } catch (err) {\n console.error(\"Failed calling /proof/:id in getProofById: \", err);\n throw err;\n }\n\n const proofProps = this.responseToProofProps(proofResponse);\n const blueprint = await Blueprint.getBlueprintById(proofResponse.blueprint_id, baseUrl);\n\n return new Proof(blueprint, proofProps);\n }\n\n public static responseToProofProps(response: ProofResponse): ProofProps {\n const props: ProofProps = {\n id: response.id,\n blueprintId: response.blueprint_id,\n status: response.status as ProofStatus,\n input: response.input,\n proof: response.proof,\n public: response.public,\n startedAt: new Date(response.started_at.seconds * 1000),\n provedAt: response.proved_at ? new Date(response.proved_at.seconds * 1000) : undefined,\n };\n return props;\n }\n}\n","import { Blueprint } from \"./blueprint\";\nimport { Proof } from \"./proof\";\nimport {\n GenerateProofInputsParams,\n ProofProps,\n ProofRequest,\n ProofResponse,\n ProofStatus,\n} from \"./types/proof\";\nimport { ProverOptions } from \"./types/prover\";\nimport { generateProofInputs, post } from \"./utils\";\n\n/**\n * Represents a Prover generated from a blueprint that can generate Proofs\n */\nexport class Prover {\n options: ProverOptions;\n blueprint: Blueprint;\n\n constructor(blueprint: Blueprint, options?: ProverOptions) {\n if (options?.isLocal === true) {\n throw new Error(\"Local proving is not supported yet\");\n }\n\n if (!(blueprint instanceof Blueprint)) {\n throw new Error(\"Invalid blueprint: must be an instance of Blueprint class\");\n }\n\n this.blueprint = blueprint;\n\n // Use defaults for unset fields\n this.options = {\n isLocal: false,\n ...(!!options ? options : {}),\n };\n }\n\n // TODO: Add parsed email input\n /**\n * Generates a proof for a given email.\n * @param eml - Email to prove agains the blueprint of this Prover.\n * @returns A promise that resolves to a new instance of Proof. The Proof will have the status\n * Done or Failed.\n */\n async generateProof(eml: string): Promise<Proof> {\n console.log(\"starting generate proof\");\n const proof = await this.generateProofRequest(eml);\n console.log(\"got proof: \", proof);\n\n // Wait for proof to finish\n while (![ProofStatus.Done, ProofStatus.Failed].includes(await proof.checkStatus())) {}\n return proof;\n }\n\n // TODO: Add parsed email input\n /**\n * Starts proving for a given email.\n * @param eml - Email to prove agains the blueprint of this Prover.\n * @returns A promise that resolves to a new instance of Proof. The Proof will have the status\n * InProgress.\n */\n async generateProofRequest(eml: string): Promise<Proof> {\n const blueprintId = this.blueprint.getId();\n if (!blueprintId) {\n throw new Error(\"Blueprint of Proover must be initialized in order to create a Proof\");\n }\n\n let input: string;\n try {\n // TODO: Do we use defaults?\n const params: GenerateProofInputsParams = {\n emailHeaderMaxLength: this.blueprint.props.emailHeaderMaxLength || 256,\n emailBodyMaxLength: this.blueprint.props.emailBodyMaxLength || 2560,\n ignoreBodyHashCheck: this.blueprint.props.ignoreBodyHashCheck || false,\n removeSoftLinebreaks: this.blueprint.props.removeSoftLinebreaks || true,\n shaPrecomputeSelector: this.blueprint.props.shaPrecomputeSelector,\n };\n console.log(\"generating proof inputs\");\n input = await generateProofInputs(\n eml,\n this.blueprint.props.decomposedRegexes,\n this.blueprint.props.externalInputs || [],\n params\n );\n } catch (err) {\n console.error(\"Failed to generate inputs for proof\");\n throw err;\n }\n\n console.log(\"got proof input\");\n let response: ProofResponse;\n try {\n const requestData: ProofRequest = {\n blueprint_id: blueprintId,\n input,\n };\n\n response = await post<ProofResponse>(`${this.blueprint.baseUrl}/proof`, requestData);\n } catch (err) {\n console.error(\"Failed calling POST on /proof/ in generateProofRequest: \", err);\n throw err;\n }\n\n const proofProps = Proof.responseToProofProps(response);\n return new Proof(this.blueprint, proofProps);\n }\n}\n","export type BlueprintProps = {\n id?: string;\n title: string;\n description?: string;\n slug?: string;\n tags?: string[];\n emailQuery?: string;\n circuitName: string;\n ignoreBodyHashCheck?: boolean;\n shaPrecomputeSelector?: string;\n emailBodyMaxLength?: number;\n emailHeaderMaxLength?: number;\n removeSoftLinebreaks?: boolean;\n githubUsername?: string;\n senderDomain?: string;\n enableHeaderMasking?: boolean;\n enableBodyMasking?: boolean;\n zkFramework?: ZkFramework;\n isPublic?: boolean;\n createdAt?: Date;\n updatedAt?: Date;\n externalInputs?: ExternalInput[];\n decomposedRegexes: DecomposedRegex[];\n status?: Status;\n verifierContract?: VerifierContract;\n version?: number;\n};\n\nexport type DecomposedRegex = {\n parts: DecomposedRegexPart[];\n name: string;\n maxLength: number;\n location: \"body\" | \"header\";\n};\n\nexport type DecomposedRegexPart = {\n isPublic: boolean;\n regexDef: string;\n};\n\nexport type DecomposedRegexJson = {\n parts: DecomposedRegexPartJson[];\n name: string;\n max_length: number;\n location: \"body\" | \"header\";\n};\n\nexport type DecomposedRegexPartJson = {\n is_public: boolean;\n regex_def: string;\n};\n\nexport type ExternalInput = {\n name: string;\n maxLength: number;\n};\n\nexport enum ZkFramework {\n Circom = \"circom\",\n}\n\n// According to protobufs\nexport enum Status {\n None,\n Draft,\n InProgress,\n Done,\n Failed,\n}\n\nexport type VerifierContract = {\n address?: string;\n chain: number;\n};\n\nexport type BlueprintRequest = {\n id?: string;\n title: string;\n description?: string;\n slug?: string;\n tags?: string[];\n email_query?: string;\n circuit_name?: string;\n ignore_body_hash_check?: boolean;\n sha_precompute_selector?: string;\n email_body_max_length?: number;\n email_header_max_length?: number;\n remove_soft_linebreaks?: boolean;\n // TODO: Make non ? after login with github\n github_username?: string;\n sender_domain?: string;\n enable_header_masking?: boolean;\n enable_body_masking?: boolean;\n zk_framework?: string;\n is_public?: boolean;\n external_inputs?: ExternalInputResponse[];\n decomposed_regexes: DecomposedRegexResponse[];\n status?: string;\n verifier_contract_address?: string;\n verifier_contract_chain?: number;\n version?: number;\n};\n\nexport type BlueprintResponse = {\n id: string;\n title: string;\n description: string;\n slug: string;\n tags: string[];\n email_query: string;\n circuit_name: string;\n ignore_body_hash_check: boolean;\n sha_precompute_selector: string;\n email_body_max_length: number;\n email_header_max_length?: number;\n remove_soft_linebreaks?: boolean;\n github_username?: string;\n sender_domain: string;\n enable_header_masking?: boolean;\n enable_body_masking?: boolean;\n zk_framework: string;\n is_public: boolean;\n created_at: ServerDate;\n updated_at: ServerDate;\n external_inputs: ExternalInputResponse[];\n decomposed_regexes: DecomposedRegexResponse[];\n status: number;\n verifier_contract_address: string;\n verifier_contract_chain: number;\n version: number;\n};\n\nexport type ServerDate = {\n seconds: number;\n nanos: number;\n};\n\nexport type ExternalInputResponse = {\n name: string;\n max_length: number;\n};\n\nexport type DecomposedRegexResponse = {\n parts: DecomposedRegexPartResponse[];\n name: string;\n max_length: number;\n location: \"body\" | \"header\";\n};\n\nexport type DecomposedRegexPartResponse = {\n is_public: boolean;\n regex_def: string;\n};\n\nexport type ListBlueprintsOptions = {\n skip?: number;\n limit?: number;\n sort?: -1 | 1;\n status?: Status[];\n isPublic?: boolean;\n search?: string;\n};\n\nexport type ListBlueprintsOptionsRequest = {\n skip?: number;\n limit?: number;\n sort?: -1 | 1;\n status?: Status[];\n is_public?: boolean;\n search?: string;\n};\n\nexport type DownloadUrls = Record<string, string>;\n","import { createPublicClient, http } from \"viem\";\nimport { baseSepolia } from \"viem/chains\";\n\nconst WETHContractAddress = \"0x4200000000000000000000000000000000000006\";\n\nconst WETHContractABI = [\n {\n constant: true,\n inputs: [],\n name: \"totalSupply\",\n outputs: [{ name: \"\", type: \"uint256\" }],\n type: \"function\",\n },\n] as const;\n\nconst client = createPublicClient({\n chain: baseSepolia,\n transport: http(),\n});\n\nexport async function verifyProofOnChain() {\n try {\n const totalSupply = await client.readContract({\n address: WETHContractAddress,\n abi: WETHContractABI,\n functionName: \"totalSupply\",\n });\n\n return totalSupply;\n } catch (error) {\n console.error(\"Error fetching WETH total supply:\", error);\n throw error;\n }\n}\n","import { Proof } from \"viem/_types/types/proof\";\nimport { Prover } from \"./prover\";\nimport {\n BlueprintProps,\n BlueprintRequest,\n BlueprintResponse,\n DownloadUrls,\n ListBlueprintsOptions,\n ListBlueprintsOptionsRequest,\n Status,\n ZkFramework,\n} from \"./types/blueprint\";\nimport { get, patch, post } from \"./utils\";\nimport { verifyProofOnChain } from \"./chain\";\nimport { Auth } from \"./types/auth\";\n\n/**\n * Represents a Regex Blueprint including the decomposed regex access to the circuit.\n */\nexport class Blueprint {\n // TODO: Implement getter and setter pattern\n props: BlueprintProps;\n auth?: Auth;\n baseUrl: string;\n\n private lastCheckedStatus: Date | null = null;\n\n constructor(props: BlueprintProps, baseUrl: string, auth?: Auth) {\n // Use defaults for unset fields\n this.props = {\n ignoreBodyHashCheck: false,\n enableHeaderMasking: false,\n enableBodyMasking: false,\n isPublic: true,\n status: Status.Draft,\n ...props,\n };\n\n this.baseUrl = baseUrl;\n this.auth = auth;\n }\n\n addAuth(auth: Auth) {\n this.auth = auth;\n }\n\n /**\n * Fetches an existing RegexBlueprint from the database.\n * @param {string} id - Id of the RegexBlueprint.\n * @returns A promise that resolves to a new instance of RegexBlueprint.\n */\n public static async getBlueprintById(\n id: string,\n baseUrl: string,\n auth?: Auth\n ): Promise<Blueprint> {\n let blueprintResponse: BlueprintResponse;\n try {\n blueprintResponse = await get<BlueprintResponse>(`${baseUrl}/blueprint/${id}`);\n } catch (err) {\n console.error(\"Failed calling /blueprint/:id in getBlueprintById: \", err);\n throw err;\n }\n\n const blueprintProps = this.responseToBlueprintProps(blueprintResponse);\n\n const blueprint = new Blueprint(blueprintProps, baseUrl, auth);\n\n return blueprint;\n }\n\n // Maps the blueprint API response to the BlueprintProps\n private static responseToBlueprintProps(response: BlueprintResponse): BlueprintProps {\n const props: BlueprintProps = {\n id: response.id,\n title: response.title,\n description: response.description,\n slug: response.slug,\n tags: response.tags,\n emailQuery: response.email_query,\n circuitName: response.circuit_name,\n ignoreBodyHashCheck: response.ignore_body_hash_check,\n shaPrecomputeSelector: response.sha_precompute_selector,\n emailBodyMaxLength: response.email_body_max_length,\n emailHeaderMaxLength: response.email_header_max_length,\n removeSoftLinebreaks: response.remove_soft_linebreaks,\n githubUsername: response.github_username,\n senderDomain: response.sender_domain,\n enableHeaderMasking: response.enable_header_masking,\n enableBodyMasking: response.enable_body_masking,\n zkFramework: response.zk_framework as ZkFramework,\n isPublic: response.is_public,\n createdAt: new Date(response.created_at.seconds * 1000),\n updatedAt: new Date(response.updated_at.seconds * 1000),\n externalInputs: response.external_inputs?.map((input) => ({\n name: input.name,\n maxLength: input.max_length,\n })),\n decomposedRegexes: response.decomposed_regexes?.map((regex) => ({\n parts: regex.parts.map((part) => ({\n isPublic: part.is_public,\n regexDef: part.regex_def,\n })),\n name: regex.name,\n maxLength: regex.max_length,\n location: regex.location,\n })),\n status: response.status as Status,\n verifierContract: {\n address: response.verifier_contract_address,\n chain: response.verifier_contract_chain,\n },\n version: response.version,\n };\n\n return props;\n }\n\n // Maps the BlueprintProps to the BlueprintResponse\n private static blueprintPropsToRequest(props: BlueprintProps): BlueprintRequest {\n const response: BlueprintRequest = {\n id: props.id,\n title: props.title,\n description: props.description,\n slug: props.slug,\n tags: props.tags,\n email_query: props.emailQuery,\n circuit_name: props.circuitName,\n ignore_body_hash_check: props.ignoreBodyHashCheck,\n sha_precompute_selector: props.shaPrecomputeSelector,\n email_body_max_length: props.emailBodyMaxLength,\n email_header_max_length: props.emailHeaderMaxLength,\n remove_soft_linebreaks: props.removeSoftLinebreaks,\n github_username: props.githubUsername,\n sender_domain: props.senderDomain,\n enable_header_masking: props.enableHeaderMasking,\n enable_body_masking: props.enableBodyMasking,\n zk_framework: props.zkFramework,\n is_public: props.isPublic,\n external_inputs: props.externalInputs?.map((input) => ({\n name: input.name,\n max_length: input.maxLength,\n })),\n decomposed_regexes: props.decomposedRegexes?.map((regex) => ({\n parts: regex.parts.map((part) => ({\n // @ts-ignore\n is_public: part.isPublic || part.is_public,\n // @ts-ignore\n regex_def: part.regexDef || part.regex_def,\n })),\n name: regex.name,\n max_length: regex.maxLength,\n location: regex.location,\n })),\n verifier_contract_address: props.verifierContract?.address,\n verifier_contract_chain: props.verifierContract?.chain,\n };\n\n return response;\n }\n\n /**\n * Submits a new RegexBlueprint to the registry as draft.\n * This does not compile the circuits yet and you will still be able to make changes.\n * @returns A promise. Once it resolves, `getId` can be called.\n */\n public async submitDraft() {\n if (!this.auth) {\n throw new Error(\"auth is required, add it with Blueprint.addAuth(auth)\");\n }\n\n if (this.props.id) {\n throw new Error(\"Blueprint was already saved\");\n }\n\n const requestData = Blueprint.blueprintPropsToRequest(this.props);\n\n let response: BlueprintResponse;\n try {\n response = await post<BlueprintResponse>(`${this.baseUrl}/blueprint`, requestData, this.auth);\n } catch (err) {\n console.error(\"Failed calling POST on /blueprint/ in submitDraft: \", err);\n throw err;\n }\n\n this.props = Blueprint.responseToBlueprintProps(response);\n }\n\n /**\n * Submits a new version of the RegexBlueprint to the registry as draft.\n * This does not compile the circuits yet and you will still be able to make changes.\n * @param newProps - The updated blueprint props.\n * @returns A promise. Once it resolves, the current Blueprint will be replaced with the new one.\n */\n public async submitNewVersionDraft(newProps: BlueprintProps) {\n if (!this.auth) {\n throw new Error(\"auth is required, add it with Blueprint.addAuth(auth)\");\n }\n\n const requestData = Blueprint.blueprintPropsToRequest(newProps);\n\n let response: BlueprintResponse;\n try {\n response = await post<BlueprintResponse>(`${this.baseUrl}/blueprint`, requestData, this.auth);\n } catch (err) {\n console.error(\"Failed calling POST on /blueprint/ in submitDraft: \", err);\n throw err;\n }\n\n this.props = Blueprint.responseToBlueprintProps(response);\n }\n\n /**\n * Submits a new version of the blueprint. This will save the new blueprint version\n * and start the compilation.\n * This will also overwrite the current Blueprint with its new version, even if the last\n * version was not compiled yet.\n * @param newProps - The updated blueprint props.\n */\n async submitNewVersion(newProps: BlueprintProps) {\n if (!this.auth) {\n throw new Error(\"auth is required, add it with Blueprint.addAuth(auth)\");\n }\n\n await this.submitNewVersionDraft(newProps);\n\n // We don't check the status here, since we are compiling directly after submiting the draft.\n\n // Submit compile request\n try {\n await post<{ status: Status }>(\n `${this.baseUrl}/blueprint/compile/${this.props.id}`,\n null,\n this.auth\n );\n } catch (err) {\n // We don't set the status here, since the api call can't fail due to the actual job failing\n // It can only due to connectivity issues or the job runner not being available\n console.error(\"Failed calling POST on /blueprint/compile in submit: \", err);\n throw err;\n }\n }\n\n /**\n * Lists blueblueprints, only including the latest version per unique slug.\n * @param options - Options to filter the blueprints by.\n * @returns A promise. Once it resolves, `getId` can be called.\n */\n public static async listBlueprints(\n baseUrl: string,\n options?: ListBlueprintsOptions,\n auth?: Auth\n ): Promise<Blueprint[]> {\n const requestOptions: ListBlueprintsOptionsRequest = {\n skip: options?.skip,\n limit: options?.limit,\n sort: options?.sort,\n status: options?.status,\n is_public: options?.isPublic,\n search: options?.search,\n };\n\n let response: { blueprints?: BlueprintResponse[] };\n try {\n response = await get<{ blueprints?: BlueprintResponse[] }>(\n `${baseUrl}/blueprint`,\n requestOptions\n );\n } catch (err) {\n console.error(\"Failed calling POST on /blueprint/ in submitDraft: \", err);\n throw err;\n }\n\n if (!response.blueprints) {\n return [];\n }\n\n return response.blueprints.map((blueprintResponse) => {\n const blueprintProps = Blueprint.responseToBlueprintProps(blueprintResponse);\n return new Blueprint(blueprintProps, baseUrl, auth);\n });\n }\n\n /**\n * Submits a blueprint. This will save the blueprint if it didn't exist before\n * and start the compilation.\n */\n async submit() {\n if (!this.auth) {\n throw new Error(\"auth is required, add it with Blueprint.addAuth(auth)\");\n }\n\n // If the blueprint wasn't save yet, we save it first to db\n if (!this.props.id) {\n try {\n await this.submitDraft();\n } catch (err) {\n console.error(\"Failed to create blueprint: \", err);\n throw err;\n }\n }\n\n const status = await this._checkStatus();\n\n // TODO: Should we allow retry on failed?\n if (Status.Done === status) {\n throw new Error(\"The circuits are already compiled.\");\n }\n if (Status.InProgress === status) {\n throw new Error(\"The circuits already being compiled, please wait.\");\n }\n\n // Submit compile request\n try {\n await post<{ status: Status }>(\n `${this.baseUrl}/blueprint/compile/${this.props.id}`,\n null,\n this.auth\n );\n } catch (err) {\n // We don't set the status here, since the api call can't fail due to the actual job failing\n // It can only due to connectivity issues or the job runner not being available\n console.error(\"Failed calling POST on /blueprint/compile in submit: \", err);\n throw err;\n }\n }\n\n // Request status from server and updates props.status\n private async _checkStatus(): Promise<Status> {\n let response: { status: Status };\n try {\n response = await get<{ status: Status }>(`${this.baseUrl}/blueprint/status/${this.props.id}`);\n } catch (err) {\n console.error(\"Failed calling GET /blueprint/status in getStatus(): \", err);\n throw err;\n }\n\n this.props.status = response.status;\n return response.status;\n }\n\n /**\n * Checks the status of blueprint.\n * checkStatus can be used in a while(await checkStatus()) loop, since it will wait a fixed\n * amount of time the second time you call it.\n * @returns A promise with the Status.\n */\n async checkStatus(): Promise<Status> {\n // Blueprint wasn't saved yet, return default status\n if (!this.props.id) {\n return this.props.status!;\n }\n\n if ([Status.Failed, Status.Done].includes(this.props.status!)) {\n return this.props.status!;\n }\n\n // Waits for a fixed period of time before you can call checkStatus again\n // This enables you to put checkStatus in a while(await checkStatus()) loop\n if (!this.lastCheckedStatus) {\n this.lastCheckedStatus = new Date();\n } else {\n // TODO: change for prod to one minute\n const waitTime = 0.5 * 1_000; // TODO: should be one minute;\n const sinceLastChecked = new Date().getTime() - this.lastCheckedStatus.getTime();\n if (sinceLastChecked < waitTime) {\n await new Promise((r) => setTimeout(r, waitTime - sinceLastChecked));\n }\n }\n\n const status = await this._checkStatus();\n\n return status;\n }\n\n /**\n * Get the id of the blueprint.\n * @returns The id of the blueprint. If it was not saved yet, return null.\n */\n getId(): string | null {\n return this.props.id || null;\n }\n\n /**\n * Returns a download link for the ZKeys of the blueprint.\n * @returns The the url to download the ZKeys.\n */\n async getZKeyDownloadLink(): Promise<DownloadUrls> {\n if (this.props.status !== Status.Done) {\n throw new Error(\"The circuits are not compiled yet, nothing to download.\");\n }\n\n let response: { urls: DownloadUrls };\n try {\n response = await get<{ urls: DownloadUrls }>(\n `${this.baseUrl}/blueprint/zkey/${this.props.id}`\n );\n console.log(\"response: \", response);\n } catch (err) {\n console.error(\"Failed calling GET on /blueprint/zkey/:id in getZKeyDownloadLink: \", err);\n throw err;\n }\n\n return response.urls;\n }\n\n /**\n * Directly starts a download of the ZKeys in the browser.\n * Must be called within a user action, like a button click.\n */\n async startZKeyDownload() {\n if (!window && !document) {\n throw Error(\"startZKeyDownload can only be used in a browser\");\n }\n\n let urls: DownloadUrls;\n try {\n urls = await this.getZKeyDownloadLink();\n } catch (err) {\n console.error(\"Failed to start download of ZKeys: \", err);\n throw err;\n }\n\n for (const [name, url] of Object.entries(urls)) {\n const link = document.createElement(\"a\");\n link.href = url;\n link.download = name; // Set the desired filename\n document.body.appendChild(link);\n link.click();\n document.body.removeChild(link);\n }\n }\n\n /**\n * Creates an instance of Prover with which you can create proofs.\n * @returns An instance of Prover.\n */\n createProver() {\n return new Prover(this);\n }\n\n /**\n * Verifies a proof on chain.\n * @param proof - The generated proof you want to verify.\n * @returns A true if the verification was successfull, false if it failed.\n */\n async verifyProofOnChain(proof: Proof): Promise<boolean> {\n try {\n const result = await verifyProofOnChain();\n } catch (err) {\n console.error(\"Failed to verify proof on chain: \", err);\n return false;\n }\n return true;\n }\n\n /**\n * Returns a deep cloned version of the Blueprints props.\n * This can be used to update properties and then to use them with createNewVersion.\n * @param proof - The generated proof you want to verify.\n * @returns A true if the verification was successfull, false if it failed.\n */\n getClonedProps(): BlueprintProps {\n const cloned = JSON.parse(JSON.stringify(this.props));\n\n // Conver date strings\n if (cloned.createdAt) {\n cloned.createdAt = new Date(cloned.createdAt);\n }\n if (cloned.updatedAt) {\n cloned.updatedAt = new Date(cloned.updatedAt);\n }\n\n return cloned;\n }\n\n /**\n * Returns true if the blueprint can be updated. A blueprint can be updated if the circuits\n * haven't beed compiled yet, i.e. the status is not Done. The blueprint also must be saved\n * already before it can be updated.\n * @returns true if it can be updated\n */\n canUpdate(): boolean {\n return !!(this.props.id && ![Status.Done, Status.InProgress].includes(this.props.status!));\n }\n\n /**\n * Updates an existing blueprint that is not compiled yet.\n * @param newProps - The props the blueprint should be updated to.\n * @returns a promise.\n */\n async update(newProps: BlueprintProps) {\n if (!this.auth) {\n throw new Error(\"auth is required, add it with Blueprint.addAuth(auth)\");\n }\n\n if (!this.canUpdate()) {\n throw new Error(\"Blueprint already compied, cannot update\");\n }\n\n const requestData = Blueprint.blueprintPropsToRequest(newProps);\n\n let response: BlueprintResponse;\n try {\n response = await patch<BlueprintResponse>(\n `${this.baseUrl}/blueprint/${this.props.id}`,\n requestData,\n this.auth\n );\n } catch (err) {\n console.error(\"Failed calling POST on /blueprint/ in submitDraft: \", err);\n throw err;\n }\n\n this.props = Blueprint.responseToBlueprintProps(response);\n }\n\n async listAllVersions(): Promise<Blueprint[]> {\n if (!this.props.id) {\n throw new Error(\"Blueprint was not saved yet\");\n }\n let response: { blueprints: BlueprintResponse[] };\n try {\n response = await get<{ blueprints: BlueprintResponse[] }>(\n `${this.baseUrl}/blueprint/versions/${encodeURIComponent(this.props.slug!)}`\n );\n } catch (err) {\n console.error(\"Failed calling GET on /blueprint/versions/:slug in listAllVersions: \", err);\n throw err;\n }\n\n return response.blueprints.map((blueprintResponse) => {\n const blueprintProps = Blueprint.responseToBlueprintProps(blueprintResponse);\n return new Blueprint(blueprintProps, this.baseUrl, this.auth);\n });\n }\n}\n\n// export {\n// BlueprintProps,\n// DecomposedRegex,\n// DecomposedRegexPart,\n// ExternalInput,\n// ZkFramework,\n// Status,\n// VerifierContract,\n// RevealHeaderFields,\n// } from \"./types/blueprint\";\n\nexport * from \"./types/blueprint\";\n","import { Blueprint, BlueprintProps, ListBlueprintsOptions } from \"./blueprint\";\nimport { Proof } from \"./proof\";\nimport { SdkOptions } from \"./types/sdk\";\n\n// Export Types\nexport * from \"./types/blueprint\";\nexport { Blueprint } from \"./blueprint\";\nexport * from \"./types/proof\";\nexport { Proof } from \"./proof\";\nexport type { Auth } from \"./types/auth\";\n\n// Exports that don't need initialization or options\nexport {\n testDecomposedRegex,\n parseEmail,\n startJsonFileDownload,\n generateProofInputs,\n testBlueprint,\n} from \"./utils\";\nexport { getLoginWithGithubUrl } from \"./auth\";\n\n// Exported sdk, functions that need initialization\nexport default (sdkOptions?: SdkOptions) => {\n const baseUrl = sdkOptions?.baseUrl || \"https://conductor.zk.email\";\n return {\n createBlueprint(props: BlueprintProps) {\n if (!sdkOptions && !sdkOptions!.auth) {\n throw new Error(\"You need to specify options.auth to use createBlueprint\");\n }\n const blueprint = new Blueprint(props, baseUrl, sdkOptions!.auth);\n return blueprint;\n },\n async getBlueprint(id: string): Promise<Blueprint> {\n return Blueprint.getBlueprintById(id, baseUrl, sdkOptions?.auth);\n },\n async listBlueprints(options?: ListBlueprintsOptions): Promise<Blueprint[]> {\n return Blueprint.listBlueprints(baseUrl, options, sdkOptions?.auth);\n },\n async getProof(id: string): Promise<Proof> {\n return Proof.getPoofById(id, baseUrl);\n },\n };\n};\n"]}
|
package/dist/index.mjs
CHANGED
@@ -1,3 +1,3 @@
|
|
1
|
-
import {createPublicClient,http}from'viem';import {baseSepolia}from'viem/chains';var b=(o=>(o[o.None=0]="None",o[o.InProgress=1]="InProgress",o[o.Done=2]="Done",o[o.Failed=3]="Failed",o))(b||{});var T="Ov23li0KABFCUsxBEQkn";function v(n,e=T){let t=encodeURIComponent(n);return `https://github.com/login/oauth/authorize?client_id=${e}&scope=user:email&state=${t}`}async function g(n){try{let e=await n.getToken();if(e||(await n.onTokenExpired(),e=await n.getToken()),!e)throw new Error("Failed to get new token");return `Bearer ${e}`}catch(e){throw console.error("Failed to get token from auth"),e}}var w="pk_live_51NXwT8cHf0vYAjQK9LzB3pM6R8gWx2F",x,y=new Promise(n=>{x=n;});console.log("frontend wasm");try{import('@dimidumo/relayer-utils/web').then(async n=>{await n.default(),x(n);}).catch(n=>{console.log("Failed to init WASM: ",n);});}catch{}async function c(n,e,t){try{let r={method:"POST",headers:{"Content-Type":"application/json","x-api-key":w,...t?{Authorization:await g(t)}:{}}};e&&(r.body=JSON.stringify(e));let o=await fetch(n,r),s=await o.json();if(!o.ok)throw new Error(`HTTP error! status: ${o.status}, message: ${s}`);return s}catch(r){throw console.error("POST Error:",r),r}}async function _(n,e,t){try{let r={method:"PATCH",headers:{"Content-Type":"application/json","x-api-key":w,...t?{Authorization:await g(t)}:{}}};e&&(r.body=JSON.stringify(e));let o=await fetch(n,r),s=await o.json();if(!o.ok)throw new Error(`HTTP error! status: ${o.status}, message: ${s}`);return s}catch(r){throw console.error("PATCH Error:",r),r}}async function u(n,e,t){try{let r=n;if(e){let s=new URLSearchParams;Object.entries(e).forEach(([i,a])=>{a&&s.append(i,String(a));}),s.size>0&&(r+=`?${s.toString()}`);}let o=await fetch(r,{method:"GET",headers:{"Content-Type":"application/json","x-api-key":w,...t?{Authorization:await g(t)}:{}}});if(!o.ok)throw new Error(`HTTP error! status: ${o.status}`);return await o.json()}catch(r){throw console.error("GET Error:",r),r}}async function B(n){try{return await(await y).parseEmail(n)}catch(e){throw console.error("Failed to parse email: ",e),e}}async function L(n,e,t=!1){let r=await B(n);if(e.emailBodyMaxLength===void 0||e.emailHeaderMaxLength===void 0)throw new Error("emailBodyMaxLength and emailHeaderMaxLength must be provided");let o=r.canonicalized_body.length>e.emailBodyMaxLength?r.canonicalized_body.substring(0,e.emailBodyMaxLength):r.canonicalized_body,s=r.canonicalized_header.length>e.emailHeaderMaxLength?r.canonicalized_header.substring(0,e.emailHeaderMaxLength):r.canonicalized_header;return await Promise.all(e.decomposedRegexes.map(a=>k(o,s,a,t)))}async function k(n,e,t,r=!1){let o={parts:t.parts.map(d=>({is_public:"isPublic"in d?d.isPublic:d.is_public,regex_def:"regexDef"in d?d.regexDef:d.regex_def}))},s;if(t.location==="body")s=n;else if(t.location==="header")s=e;else throw Error(`Unsupported location ${t.location}`);let i="maxLength"in t?t.maxLength:t.max_length,a=await y,h=a.extractSubstr(s,o,!1);if(h[0].length>i)throw new Error(`Max length of extracted result was exceeded for decomposed regex ${t.name}`);return r?a.extractSubstr(s,o,r):h}async function P(n,e,t,r){try{let o={maxHeaderLength:r.emailHeaderMaxLength,maxBodyLength:r.emailBodyMaxLength,ignoreBodyHashCheck:r.ignoreBodyHashCheck,removeSoftLinesBreaks:r.removeSoftLinebreaks,shaPrecomputeSelector:r.shaPrecomputeSelector},s=await y,i=e.map(h=>({...h,parts:h.parts.map(m=>({is_public:m.isPublic||!!m.is_public,regex_def:m.regexDef||!!m.regex_def}))}));console.log("calling generateCircuitInputsWithDecomposedRegexesAndExternalInputs with"),console.log("eml: ",n),console.log("decomposedRegex: ",i),console.log("externalInputs: ",t),console.log("params: ",r);let a=await s.generateCircuitInputsWithDecomposedRegexesAndExternalInputs(n,i,t,o);return JSON.stringify(Object.fromEntries(a))}catch(o){throw console.error("Failed to generate inputs for proof"),o}}function S(n,e="data"){if(!window&&!document)throw Error("startFilesDownload can only be used in a browser");let t=new Blob([n],{type:"application/json"}),r=URL.createObjectURL(t),o=document.createElement("a");o.href=r,o.download=`${e}.json`,document.body.appendChild(o),o.click(),document.body.removeChild(o),URL.revokeObjectURL(r);}var p=class n{blueprint;props;lastCheckedStatus=null;constructor(e,t){if(!(e instanceof l))throw new Error("Invalid blueprint: must be an instance of Blueprint class");if(this.blueprint=e,!t?.id)throw new Error("A proof must have an id");this.props={status:1,...t};}getId(){return this.props.id}async getProofDataDownloadLink(){if(this.props.status!==2)throw new Error("The proving is not done yet.");let e;try{e=await u(`${this.blueprint.baseUrl}/proof/files/${this.props.id}`);}catch(t){throw console.error("Failed calling GET on /proof/files/:id in getProofDataDownloadLink: ",t),t}return e.url}async startFilesDownload(){if(!window&&!document)throw Error("startFilesDownload can only be used in a browser");let e;try{e=await this.getProofDataDownloadLink();}catch(r){throw console.error("Failed to start download of ZKeys: ",r),r}let t=document.createElement("a");t.href=e,t.download="proof_files.zip",document.body.appendChild(t),t.click(),document.body.removeChild(t);}async checkStatus(){if(this.props.status===2)return this.props.status;if(!this.lastCheckedStatus)this.lastCheckedStatus=new Date;else {let r=new Date().getTime()-this.lastCheckedStatus.getTime();r<500&&await new Promise(o=>setTimeout(o,500-r));}let e;try{e=await u(`${this.blueprint.baseUrl}/proof/status/${this.props.id}`);}catch(t){throw console.error("Failed calling GET /blueprint/status in getStatus(): ",t),t}return this.props.status=e.status,e.status}async verifyOnChain(){}static async getPoofById(e,t){let r;try{r=await u(`${t}/proof/${e}`);}catch(i){throw console.error("Failed calling /proof/:id in getProofById: ",i),i}let o=this.responseToProofProps(r),s=await l.getBlueprintById(r.blueprint_id,t);return new n(s,o)}static responseToProofProps(e){return {id:e.id,blueprintId:e.blueprint_id,status:e.status,input:e.input,proof:e.proof,public:e.public,startedAt:new Date(e.started_at.seconds*1e3),provedAt:e.proved_at?new Date(e.proved_at.seconds*1e3):void 0}}};var f=class{options;blueprint;constructor(e,t){if(t?.isLocal===!0)throw new Error("Local proving is not supported yet");if(!(e instanceof l))throw new Error("Invalid blueprint: must be an instance of Blueprint class");this.blueprint=e,this.options={isLocal:!1,...t||{}};}async generateProof(e){console.log("starting generate proof");let t=await this.generateProofRequest(e);for(console.log("got proof: ",t);![2,3].includes(await t.checkStatus()););return t}async generateProofRequest(e){let t=this.blueprint.getId();if(!t)throw new Error("Blueprint of Proover must be initialized in order to create a Proof");let r;try{let i={emailHeaderMaxLength:this.blueprint.props.emailHeaderMaxLength||256,emailBodyMaxLength:this.blueprint.props.emailBodyMaxLength||2560,ignoreBodyHashCheck:this.blueprint.props.ignoreBodyHashCheck||!1,removeSoftLinebreaks:this.blueprint.props.removeSoftLinebreaks||!0,shaPrecomputeSelector:this.blueprint.props.shaPrecomputeSelector};console.log("generating proof inputs"),r=await P(e,this.blueprint.props.decomposedRegexes,this.blueprint.props.externalInputs||[],i);}catch(i){throw console.error("Failed to generate inputs for proof"),i}console.log("got proof input");let o;try{let i={blueprint_id:t,input:r};o=await c(`${this.blueprint.baseUrl}/proof`,i);}catch(i){throw console.error("Failed calling POST on /proof/ in generateProofRequest: ",i),i}let s=p.responseToProofProps(o);return new p(this.blueprint,s)}};var E=(e=>(e.Circom="circom",e))(E||{}),D=(s=>(s[s.None=0]="None",s[s.Draft=1]="Draft",s[s.InProgress=2]="InProgress",s[s.Done=3]="Done",s[s.Failed=4]="Failed",s))(D||{});var U="0x4200000000000000000000000000000000000006",F=[{constant:!0,inputs:[],name:"totalSupply",outputs:[{name:"",type:"uint256"}],type:"function"}],H=createPublicClient({chain:baseSepolia,transport:http()});async function R(){try{return await H.readContract({address:U,abi:F,functionName:"totalSupply"})}catch(n){throw console.error("Error fetching WETH total supply:",n),n}}var l=class n{props;auth;baseUrl;lastCheckedStatus=null;constructor(e,t,r){this.props={ignoreBodyHashCheck:!1,enableHeaderMasking:!1,enableBodyMasking:!1,isPublic:!0,status:1,...e},this.baseUrl=t,this.auth=r;}addAuth(e){this.auth=e;}static async getBlueprintById(e,t,r){let o;try{o=await u(`${t}/blueprint/${e}`);}catch(a){throw console.error("Failed calling /blueprint/:id in getBlueprintById: ",a),a}let s=this.responseToBlueprintProps(o);return new n(s,t,r)}static responseToBlueprintProps(e){return {id:e.id,title:e.title,description:e.description,slug:e.slug,tags:e.tags,emailQuery:e.email_query,circuitName:e.circuit_name,ignoreBodyHashCheck:e.ignore_body_hash_check,shaPrecomputeSelector:e.sha_precompute_selector,emailBodyMaxLength:e.email_body_max_length,emailHeaderMaxLength:e.email_header_max_length,removeSoftLinebreaks:e.remove_soft_linebreaks,githubUsername:e.github_username,senderDomain:e.sender_domain,enableHeaderMasking:e.enable_header_masking,enableBodyMasking:e.enable_body_masking,zkFramework:e.zk_framework,isPublic:e.is_public,createdAt:new Date(e.created_at.seconds*1e3),updatedAt:new Date(e.updated_at.seconds*1e3),externalInputs:e.external_inputs?.map(r=>({name:r.name,maxLength:r.max_length})),decomposedRegexes:e.decomposed_regexes?.map(r=>({parts:r.parts.map(o=>({isPublic:o.is_public,regexDef:o.regex_def})),name:r.name,maxLength:r.max_length,location:r.location})),status:e.status,verifierContract:{address:e.verifier_contract_address,chain:e.verifier_contract_chain},version:e.version}}static blueprintPropsToRequest(e){return {id:e.id,title:e.title,description:e.description,slug:e.slug,tags:e.tags,email_query:e.emailQuery,circuit_name:e.circuitName,ignore_body_hash_check:e.ignoreBodyHashCheck,sha_precompute_selector:e.shaPrecomputeSelector,email_body_max_length:e.emailBodyMaxLength,email_header_max_length:e.emailHeaderMaxLength,remove_soft_linebreaks:e.removeSoftLinebreaks,github_username:e.githubUsername,sender_domain:e.senderDomain,enable_header_masking:e.enableHeaderMasking,enable_body_masking:e.enableBodyMasking,zk_framework:e.zkFramework,is_public:e.isPublic,external_inputs:e.externalInputs?.map(r=>({name:r.name,max_length:r.maxLength})),decomposed_regexes:e.decomposedRegexes?.map(r=>({parts:r.parts.map(o=>({is_public:o.isPublic||o.is_public,regex_def:o.regexDef||o.regex_def})),name:r.name,max_length:r.maxLength,location:r.location})),verifier_contract_address:e.verifierContract?.address,verifier_contract_chain:e.verifierContract?.chain}}async submitDraft(){if(!this.auth)throw new Error("auth is required, add it with Blueprint.addAuth(auth)");if(this.props.id)throw new Error("Blueprint was already saved");let e=n.blueprintPropsToRequest(this.props),t;try{t=await c(`${this.baseUrl}/blueprint`,e,this.auth);}catch(r){throw console.error("Failed calling POST on /blueprint/ in submitDraft: ",r),r}this.props=n.responseToBlueprintProps(t);}async submitNewVersionDraft(e){if(!this.auth)throw new Error("auth is required, add it with Blueprint.addAuth(auth)");let t=n.blueprintPropsToRequest(e),r;try{r=await c(`${this.baseUrl}/blueprint`,t,this.auth);}catch(o){throw console.error("Failed calling POST on /blueprint/ in submitDraft: ",o),o}this.props=n.responseToBlueprintProps(r);}async submitNewVersion(e){if(!this.auth)throw new Error("auth is required, add it with Blueprint.addAuth(auth)");await this.submitNewVersionDraft(e);try{await c(`${this.baseUrl}/blueprint/compile/${this.props.id}`,null,this.auth);}catch(t){throw console.error("Failed calling POST on /blueprint/compile in submit: ",t),t}}static async listBlueprints(e,t,r){let o={skip:t?.skip,limit:t?.limit,sort:t?.sort,status:t?.status,is_public:t?.isPublic,search:t?.search},s;try{s=await u(`${e}/blueprint`,o);}catch(i){throw console.error("Failed calling POST on /blueprint/ in submitDraft: ",i),i}return s.blueprints?s.blueprints.map(i=>{let a=n.responseToBlueprintProps(i);return new n(a,e,r)}):[]}async submit(){if(!this.auth)throw new Error("auth is required, add it with Blueprint.addAuth(auth)");if(!this.props.id)try{await this.submitDraft();}catch(t){throw console.error("Failed to create blueprint: ",t),t}let e=await this._checkStatus();if(3===e)throw new Error("The circuits are already compiled.");if(2===e)throw new Error("The circuits already being compiled, please wait.");try{await c(`${this.baseUrl}/blueprint/compile/${this.props.id}`,null,this.auth);}catch(t){throw console.error("Failed calling POST on /blueprint/compile in submit: ",t),t}}async _checkStatus(){let e;try{e=await u(`${this.baseUrl}/blueprint/status/${this.props.id}`);}catch(t){throw console.error("Failed calling GET /blueprint/status in getStatus(): ",t),t}return this.props.status=e.status,e.status}async checkStatus(){if(!this.props.id)return this.props.status;if([4,3].includes(this.props.status))return this.props.status;if(!this.lastCheckedStatus)this.lastCheckedStatus=new Date;else {let r=new Date().getTime()-this.lastCheckedStatus.getTime();r<500&&await new Promise(o=>setTimeout(o,500-r));}return await this._checkStatus()}getId(){return this.props.id||null}async getZKeyDownloadLink(){if(this.props.status!==3)throw new Error("The circuits are not compiled yet, nothing to download.");let e;try{e=await u(`${this.baseUrl}/blueprint/zkey/${this.props.id}`),console.log("response: ",e);}catch(t){throw console.error("Failed calling GET on /blueprint/zkey/:id in getZKeyDownloadLink: ",t),t}return e.urls}async startZKeyDownload(){if(!window&&!document)throw Error("startZKeyDownload can only be used in a browser");let e;try{e=await this.getZKeyDownloadLink();}catch(t){throw console.error("Failed to start download of ZKeys: ",t),t}for(let[t,r]of Object.entries(e)){let o=document.createElement("a");o.href=r,o.download=t,document.body.appendChild(o),o.click(),document.body.removeChild(o);}}createProver(){return new f(this)}async verifyProofOnChain(e){try{let t=await R();}catch(t){return console.error("Failed to verify proof on chain: ",t),!1}return !0}getClonedProps(){let e=JSON.parse(JSON.stringify(this.props));return e.createdAt&&(e.createdAt=new Date(e.createdAt)),e.updatedAt&&(e.updatedAt=new Date(e.updatedAt)),e}canUpdate(){return !!(this.props.id&&![3,2].includes(this.props.status))}async update(e){if(!this.auth)throw new Error("auth is required, add it with Blueprint.addAuth(auth)");if(!this.canUpdate())throw new Error("Blueprint already compied, cannot update");let t=n.blueprintPropsToRequest(e),r;try{r=await _(`${this.baseUrl}/blueprint/${this.props.id}`,t,this.auth);}catch(o){throw console.error("Failed calling POST on /blueprint/ in submitDraft: ",o),o}this.props=n.responseToBlueprintProps(r);}async listAllVersions(){if(!this.props.id)throw new Error("Blueprint was not saved yet");let e;try{e=await u(`${this.baseUrl}/blueprint/versions/${encodeURIComponent(this.props.slug)}`);}catch(t){throw console.error("Failed calling GET on /blueprint/versions/:slug in listAllVersions: ",t),t}return e.blueprints.map(t=>{let r=n.responseToBlueprintProps(t);return new n(r,this.baseUrl,this.auth)})}};var De=n=>{let e=n?.baseUrl||"https://conductor.zk.email";return {createBlueprint(t){if(!n&&!n.auth)throw new Error("You need to specify options.auth to use createBlueprint");return new l(t,e,n.auth)},async getBlueprint(t){return l.getBlueprintById(t,e,n?.auth)},async listBlueprints(t){return l.listBlueprints(e,t,n?.auth)},async getProof(t){return p.getPoofById(t,e)}}};
|
2
|
-
export{l as Blueprint,
|
1
|
+
import {createPublicClient,http}from'viem';import {baseSepolia}from'viem/chains';var b=(o=>(o[o.None=0]="None",o[o.InProgress=1]="InProgress",o[o.Done=2]="Done",o[o.Failed=3]="Failed",o))(b||{});var v="Ov23li0KABFCUsxBEQkn";function T(n,e=v){let t=encodeURIComponent(n);return `https://github.com/login/oauth/authorize?client_id=${e}&scope=user:email&state=${t}`}async function g(n){try{let e=await n.getToken();if(e||(await n.onTokenExpired(),e=await n.getToken()),!e)throw new Error("Failed to get new token");return `Bearer ${e}`}catch(e){throw console.error("Failed to get token from auth"),e}}var w="pk_live_51NXwT8cHf0vYAjQK9LzB3pM6R8gWx2F",x,y=new Promise(n=>{x=n;});console.log("frontend wasm");try{import('@dimidumo/relayer-utils/web').then(async n=>{await n.default(),x(n);}).catch(n=>{console.log("Failed to init WASM: ",n);});}catch{}async function d(n,e,t){try{let r={method:"POST",headers:{"Content-Type":"application/json","x-api-key":w,...t?{Authorization:await g(t)}:{}}};e&&(r.body=JSON.stringify(e));let o=await fetch(n,r),s=await o.json();if(!o.ok)throw new Error(`HTTP error! status: ${o.status}, message: ${s}`);return s}catch(r){throw console.error("POST Error:",r),r}}async function _(n,e,t){try{let r={method:"PATCH",headers:{"Content-Type":"application/json","x-api-key":w,...t?{Authorization:await g(t)}:{}}};e&&(r.body=JSON.stringify(e));let o=await fetch(n,r),s=await o.json();if(!o.ok)throw new Error(`HTTP error! status: ${o.status}, message: ${s}`);return s}catch(r){throw console.error("PATCH Error:",r),r}}async function p(n,e,t){try{let r=n;if(e){let s=new URLSearchParams;Object.entries(e).forEach(([i,a])=>{a&&s.append(i,String(a));}),s.size>0&&(r+=`?${s.toString()}`);}let o=await fetch(r,{method:"GET",headers:{"Content-Type":"application/json","x-api-key":w,...t?{Authorization:await g(t)}:{}}});if(!o.ok)throw new Error(`HTTP error! status: ${o.status}`);return await o.json()}catch(r){throw console.error("GET Error:",r),r}}async function B(n){try{return await(await y).parseEmail(n)}catch(e){throw console.error("Failed to parse email: ",e),e}}async function L(n,e,t=!1){console.log("got eml: ",n);let r=await B(n);if(console.log("got parsed email: ",r),e.emailBodyMaxLength===void 0||e.emailHeaderMaxLength===void 0)throw new Error("emailBodyMaxLength and emailHeaderMaxLength must be provided");let o=r.canonicalized_body.length>e.emailBodyMaxLength?r.canonicalized_body.substring(0,e.emailBodyMaxLength):r.canonicalized_body;console.log("body: ",o);let s=r.canonicalized_header.length>e.emailHeaderMaxLength?r.canonicalized_header.substring(0,e.emailHeaderMaxLength):r.canonicalized_header;console.log("header: ",s);let i=await Promise.all(e.decomposedRegexes.map(a=>k(o,s,a,t)));return console.log("output: ",i),i}async function k(n,e,t,r=!1){console.log("testDecomposedRegex: ",t);let o={parts:t.parts.map(m=>({is_public:"isPublic"in m?m.isPublic:m.is_public,regex_def:"regexDef"in m?m.regexDef:m.regex_def}))};console.log("inputDecomposedRegex: ",o);let s;if(t.location==="body")s=n;else if(t.location==="header")s=e;else throw Error(`Unsupported location ${t.location}`);console.log("inputstr: ",s);let i="maxLength"in t?t.maxLength:t.max_length;console.log("maxLength: ",i);let a=await y,h=a.extractSubstr(s,o,!1);if(console.log("privateResult: ",h),h[0].length>i)throw new Error(`Max length of extracted result was exceeded for decomposed regex ${t.name}`);if(!r)return h;let c=a.extractSubstr(s,o,r);return console.log("result: ",c),c}async function P(n,e,t,r){try{let o={maxHeaderLength:r.emailHeaderMaxLength,maxBodyLength:r.emailBodyMaxLength,ignoreBodyHashCheck:r.ignoreBodyHashCheck,removeSoftLinesBreaks:r.removeSoftLinebreaks,shaPrecomputeSelector:r.shaPrecomputeSelector},s=await y,i=e.map(h=>({...h,parts:h.parts.map(c=>({is_public:c.isPublic||!!c.is_public,regex_def:c.regexDef||!!c.regex_def}))}));console.log("calling generateCircuitInputsWithDecomposedRegexesAndExternalInputs with"),console.log("eml: ",n),console.log("decomposedRegex: ",i),console.log("externalInputs: ",t),console.log("params: ",r);let a=await s.generateCircuitInputsWithDecomposedRegexesAndExternalInputs(n,i,t,o);return JSON.stringify(Object.fromEntries(a))}catch(o){throw console.error("Failed to generate inputs for proof"),o}}function S(n,e="data"){if(!window&&!document)throw Error("startFilesDownload can only be used in a browser");let t=new Blob([n],{type:"application/json"}),r=URL.createObjectURL(t),o=document.createElement("a");o.href=r,o.download=`${e}.json`,document.body.appendChild(o),o.click(),document.body.removeChild(o),URL.revokeObjectURL(r);}var u=class n{blueprint;props;lastCheckedStatus=null;constructor(e,t){if(!(e instanceof l))throw new Error("Invalid blueprint: must be an instance of Blueprint class");if(this.blueprint=e,!t?.id)throw new Error("A proof must have an id");this.props={status:1,...t};}getId(){return this.props.id}async getProofDataDownloadLink(){if(this.props.status!==2)throw new Error("The proving is not done yet.");let e;try{e=await p(`${this.blueprint.baseUrl}/proof/files/${this.props.id}`);}catch(t){throw console.error("Failed calling GET on /proof/files/:id in getProofDataDownloadLink: ",t),t}return e.url}async startFilesDownload(){if(!window&&!document)throw Error("startFilesDownload can only be used in a browser");let e;try{e=await this.getProofDataDownloadLink();}catch(r){throw console.error("Failed to start download of ZKeys: ",r),r}let t=document.createElement("a");t.href=e,t.download="proof_files.zip",document.body.appendChild(t),t.click(),document.body.removeChild(t);}async checkStatus(){if(this.props.status===2)return this.props.status;if(!this.lastCheckedStatus)this.lastCheckedStatus=new Date;else {let r=new Date().getTime()-this.lastCheckedStatus.getTime();r<500&&await new Promise(o=>setTimeout(o,500-r));}let e;try{e=await p(`${this.blueprint.baseUrl}/proof/status/${this.props.id}`);}catch(t){throw console.error("Failed calling GET /blueprint/status in getStatus(): ",t),t}return this.props.status=e.status,e.status}async verifyOnChain(){}static async getPoofById(e,t){let r;try{r=await p(`${t}/proof/${e}`);}catch(i){throw console.error("Failed calling /proof/:id in getProofById: ",i),i}let o=this.responseToProofProps(r),s=await l.getBlueprintById(r.blueprint_id,t);return new n(s,o)}static responseToProofProps(e){return {id:e.id,blueprintId:e.blueprint_id,status:e.status,input:e.input,proof:e.proof,public:e.public,startedAt:new Date(e.started_at.seconds*1e3),provedAt:e.proved_at?new Date(e.proved_at.seconds*1e3):void 0}}};var f=class{options;blueprint;constructor(e,t){if(t?.isLocal===!0)throw new Error("Local proving is not supported yet");if(!(e instanceof l))throw new Error("Invalid blueprint: must be an instance of Blueprint class");this.blueprint=e,this.options={isLocal:!1,...t||{}};}async generateProof(e){console.log("starting generate proof");let t=await this.generateProofRequest(e);for(console.log("got proof: ",t);![2,3].includes(await t.checkStatus()););return t}async generateProofRequest(e){let t=this.blueprint.getId();if(!t)throw new Error("Blueprint of Proover must be initialized in order to create a Proof");let r;try{let i={emailHeaderMaxLength:this.blueprint.props.emailHeaderMaxLength||256,emailBodyMaxLength:this.blueprint.props.emailBodyMaxLength||2560,ignoreBodyHashCheck:this.blueprint.props.ignoreBodyHashCheck||!1,removeSoftLinebreaks:this.blueprint.props.removeSoftLinebreaks||!0,shaPrecomputeSelector:this.blueprint.props.shaPrecomputeSelector};console.log("generating proof inputs"),r=await P(e,this.blueprint.props.decomposedRegexes,this.blueprint.props.externalInputs||[],i);}catch(i){throw console.error("Failed to generate inputs for proof"),i}console.log("got proof input");let o;try{let i={blueprint_id:t,input:r};o=await d(`${this.blueprint.baseUrl}/proof`,i);}catch(i){throw console.error("Failed calling POST on /proof/ in generateProofRequest: ",i),i}let s=u.responseToProofProps(o);return new u(this.blueprint,s)}};var E=(e=>(e.Circom="circom",e))(E||{}),D=(s=>(s[s.None=0]="None",s[s.Draft=1]="Draft",s[s.InProgress=2]="InProgress",s[s.Done=3]="Done",s[s.Failed=4]="Failed",s))(D||{});var U="0x4200000000000000000000000000000000000006",F=[{constant:!0,inputs:[],name:"totalSupply",outputs:[{name:"",type:"uint256"}],type:"function"}],H=createPublicClient({chain:baseSepolia,transport:http()});async function R(){try{return await H.readContract({address:U,abi:F,functionName:"totalSupply"})}catch(n){throw console.error("Error fetching WETH total supply:",n),n}}var l=class n{props;auth;baseUrl;lastCheckedStatus=null;constructor(e,t,r){this.props={ignoreBodyHashCheck:!1,enableHeaderMasking:!1,enableBodyMasking:!1,isPublic:!0,status:1,...e},this.baseUrl=t,this.auth=r;}addAuth(e){this.auth=e;}static async getBlueprintById(e,t,r){let o;try{o=await p(`${t}/blueprint/${e}`);}catch(a){throw console.error("Failed calling /blueprint/:id in getBlueprintById: ",a),a}let s=this.responseToBlueprintProps(o);return new n(s,t,r)}static responseToBlueprintProps(e){return {id:e.id,title:e.title,description:e.description,slug:e.slug,tags:e.tags,emailQuery:e.email_query,circuitName:e.circuit_name,ignoreBodyHashCheck:e.ignore_body_hash_check,shaPrecomputeSelector:e.sha_precompute_selector,emailBodyMaxLength:e.email_body_max_length,emailHeaderMaxLength:e.email_header_max_length,removeSoftLinebreaks:e.remove_soft_linebreaks,githubUsername:e.github_username,senderDomain:e.sender_domain,enableHeaderMasking:e.enable_header_masking,enableBodyMasking:e.enable_body_masking,zkFramework:e.zk_framework,isPublic:e.is_public,createdAt:new Date(e.created_at.seconds*1e3),updatedAt:new Date(e.updated_at.seconds*1e3),externalInputs:e.external_inputs?.map(r=>({name:r.name,maxLength:r.max_length})),decomposedRegexes:e.decomposed_regexes?.map(r=>({parts:r.parts.map(o=>({isPublic:o.is_public,regexDef:o.regex_def})),name:r.name,maxLength:r.max_length,location:r.location})),status:e.status,verifierContract:{address:e.verifier_contract_address,chain:e.verifier_contract_chain},version:e.version}}static blueprintPropsToRequest(e){return {id:e.id,title:e.title,description:e.description,slug:e.slug,tags:e.tags,email_query:e.emailQuery,circuit_name:e.circuitName,ignore_body_hash_check:e.ignoreBodyHashCheck,sha_precompute_selector:e.shaPrecomputeSelector,email_body_max_length:e.emailBodyMaxLength,email_header_max_length:e.emailHeaderMaxLength,remove_soft_linebreaks:e.removeSoftLinebreaks,github_username:e.githubUsername,sender_domain:e.senderDomain,enable_header_masking:e.enableHeaderMasking,enable_body_masking:e.enableBodyMasking,zk_framework:e.zkFramework,is_public:e.isPublic,external_inputs:e.externalInputs?.map(r=>({name:r.name,max_length:r.maxLength})),decomposed_regexes:e.decomposedRegexes?.map(r=>({parts:r.parts.map(o=>({is_public:o.isPublic||o.is_public,regex_def:o.regexDef||o.regex_def})),name:r.name,max_length:r.maxLength,location:r.location})),verifier_contract_address:e.verifierContract?.address,verifier_contract_chain:e.verifierContract?.chain}}async submitDraft(){if(!this.auth)throw new Error("auth is required, add it with Blueprint.addAuth(auth)");if(this.props.id)throw new Error("Blueprint was already saved");let e=n.blueprintPropsToRequest(this.props),t;try{t=await d(`${this.baseUrl}/blueprint`,e,this.auth);}catch(r){throw console.error("Failed calling POST on /blueprint/ in submitDraft: ",r),r}this.props=n.responseToBlueprintProps(t);}async submitNewVersionDraft(e){if(!this.auth)throw new Error("auth is required, add it with Blueprint.addAuth(auth)");let t=n.blueprintPropsToRequest(e),r;try{r=await d(`${this.baseUrl}/blueprint`,t,this.auth);}catch(o){throw console.error("Failed calling POST on /blueprint/ in submitDraft: ",o),o}this.props=n.responseToBlueprintProps(r);}async submitNewVersion(e){if(!this.auth)throw new Error("auth is required, add it with Blueprint.addAuth(auth)");await this.submitNewVersionDraft(e);try{await d(`${this.baseUrl}/blueprint/compile/${this.props.id}`,null,this.auth);}catch(t){throw console.error("Failed calling POST on /blueprint/compile in submit: ",t),t}}static async listBlueprints(e,t,r){let o={skip:t?.skip,limit:t?.limit,sort:t?.sort,status:t?.status,is_public:t?.isPublic,search:t?.search},s;try{s=await p(`${e}/blueprint`,o);}catch(i){throw console.error("Failed calling POST on /blueprint/ in submitDraft: ",i),i}return s.blueprints?s.blueprints.map(i=>{let a=n.responseToBlueprintProps(i);return new n(a,e,r)}):[]}async submit(){if(!this.auth)throw new Error("auth is required, add it with Blueprint.addAuth(auth)");if(!this.props.id)try{await this.submitDraft();}catch(t){throw console.error("Failed to create blueprint: ",t),t}let e=await this._checkStatus();if(3===e)throw new Error("The circuits are already compiled.");if(2===e)throw new Error("The circuits already being compiled, please wait.");try{await d(`${this.baseUrl}/blueprint/compile/${this.props.id}`,null,this.auth);}catch(t){throw console.error("Failed calling POST on /blueprint/compile in submit: ",t),t}}async _checkStatus(){let e;try{e=await p(`${this.baseUrl}/blueprint/status/${this.props.id}`);}catch(t){throw console.error("Failed calling GET /blueprint/status in getStatus(): ",t),t}return this.props.status=e.status,e.status}async checkStatus(){if(!this.props.id)return this.props.status;if([4,3].includes(this.props.status))return this.props.status;if(!this.lastCheckedStatus)this.lastCheckedStatus=new Date;else {let r=new Date().getTime()-this.lastCheckedStatus.getTime();r<500&&await new Promise(o=>setTimeout(o,500-r));}return await this._checkStatus()}getId(){return this.props.id||null}async getZKeyDownloadLink(){if(this.props.status!==3)throw new Error("The circuits are not compiled yet, nothing to download.");let e;try{e=await p(`${this.baseUrl}/blueprint/zkey/${this.props.id}`),console.log("response: ",e);}catch(t){throw console.error("Failed calling GET on /blueprint/zkey/:id in getZKeyDownloadLink: ",t),t}return e.urls}async startZKeyDownload(){if(!window&&!document)throw Error("startZKeyDownload can only be used in a browser");let e;try{e=await this.getZKeyDownloadLink();}catch(t){throw console.error("Failed to start download of ZKeys: ",t),t}for(let[t,r]of Object.entries(e)){let o=document.createElement("a");o.href=r,o.download=t,document.body.appendChild(o),o.click(),document.body.removeChild(o);}}createProver(){return new f(this)}async verifyProofOnChain(e){try{let t=await R();}catch(t){return console.error("Failed to verify proof on chain: ",t),!1}return !0}getClonedProps(){let e=JSON.parse(JSON.stringify(this.props));return e.createdAt&&(e.createdAt=new Date(e.createdAt)),e.updatedAt&&(e.updatedAt=new Date(e.updatedAt)),e}canUpdate(){return !!(this.props.id&&![3,2].includes(this.props.status))}async update(e){if(!this.auth)throw new Error("auth is required, add it with Blueprint.addAuth(auth)");if(!this.canUpdate())throw new Error("Blueprint already compied, cannot update");let t=n.blueprintPropsToRequest(e),r;try{r=await _(`${this.baseUrl}/blueprint/${this.props.id}`,t,this.auth);}catch(o){throw console.error("Failed calling POST on /blueprint/ in submitDraft: ",o),o}this.props=n.responseToBlueprintProps(r);}async listAllVersions(){if(!this.props.id)throw new Error("Blueprint was not saved yet");let e;try{e=await p(`${this.baseUrl}/blueprint/versions/${encodeURIComponent(this.props.slug)}`);}catch(t){throw console.error("Failed calling GET on /blueprint/versions/:slug in listAllVersions: ",t),t}return e.blueprints.map(t=>{let r=n.responseToBlueprintProps(t);return new n(r,this.baseUrl,this.auth)})}};var De=n=>{let e=n?.baseUrl||"https://conductor.zk.email";return {createBlueprint(t){if(!n&&!n.auth)throw new Error("You need to specify options.auth to use createBlueprint");return new l(t,e,n.auth)},async getBlueprint(t){return l.getBlueprintById(t,e,n?.auth)},async listBlueprints(t){return l.listBlueprints(e,t,n?.auth)},async getProof(t){return u.getPoofById(t,e)}}};
|
2
|
+
export{l as Blueprint,u as Proof,b as ProofStatus,D as Status,E as ZkFramework,De as default,P as generateProofInputs,T as getLoginWithGithubUrl,B as parseEmail,S as startJsonFileDownload,L as testBlueprint,k as testDecomposedRegex};//# sourceMappingURL=index.mjs.map
|
3
3
|
//# sourceMappingURL=index.mjs.map
|
package/dist/index.mjs.map
CHANGED
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"sources":["../src/types/proof.ts","../src/auth.ts","../src/utils.ts","../src/proof.ts","../src/prover.ts","../src/types/blueprint.ts","../src/chain/index.ts","../src/blueprint.ts","../src/index.ts"],"names":["ProofStatus","GITHUB_CLIENT_ID","getLoginWithGithubUrl","callbackUrl","githubClientId","state","getTokenFromAuth","auth","token","err","PUBLIC_SDK_KEY","relayerUtilsResolver","relayerUtils","resolve","rl","post","url","data","request","response","body","error","patch","get","queryParams","fullUrl","searchParams","key","value","parseEmail","eml","testBlueprint","blueprint","revealPrivate","parsedEmail","header","dcr","testDecomposedRegex","decomposedRegex","inputDecomposedRegex","p","inputStr","maxLength","utils","privateResult","generateProofInputs","decomposedRegexes","externalInputs","params","internalParams","decomposedRegexesCleaned","inputs","startJsonFileDownload","json","name","blob","link","Proof","_Proof","props","Blueprint","sinceLastChecked","r","id","baseUrl","proofResponse","proofProps","Prover","options","proof","blueprintId","input","requestData","ZkFramework","Status","WETHContractAddress","WETHContractABI","client","createPublicClient","baseSepolia","http","verifyProofOnChain","_Blueprint","blueprintResponse","blueprintProps","regex","part","newProps","requestOptions","status","urls","result","cloned","src_default","sdkOptions"],"mappings":"iFAGO,IAAKA,CACVA,CAAAA,CAAAA,CAAAA,GAAAA,CAAAA,CAAAA,CAAAA,CAAA,IACAA,CAAAA,CAAAA,CAAAA,CAAAA,MAAAA,CAAAA,CAAAA,CAAAA,CAAAA,CAAA,2BACAA,CAAA,CAAA,CAAA,CAAA,IAAA,CAAA,CAAA,CAAA,CAAA,MAAA,CACAA,CAAA,CAAA,CAAA,CAAA,MAAA,CAAA,CAAA,CAAA,CAAA,QAAA,CAJUA,OAAA,ECAZ,EAAA,IAAMC,CAAmB,CAAA,sBAAA,CAIlB,SAASC,CACdC,CAAAA,CAAAA,CACAC,CAAiBH,CAAAA,CAAAA,CACT,CACR,IAAMI,CAAAA,CAAQ,kBAAmBF,CAAAA,CAAW,EAC5C,OAAO,CAAA,mDAAA,EAAsDC,CAAc,CAAA,wBAAA,EAA2BC,CAAK,CAC7G,CAAA,CAEA,eAAsBC,CAAAA,CAAiBC,EAA6B,CAClE,GAAI,CACF,IAAIC,EAAQ,MAAMD,CAAAA,CAAK,QAAS,EAAA,CAOhC,GALKC,CACH,GAAA,MAAMD,CAAK,CAAA,cAAA,GACXC,CAAQ,CAAA,MAAMD,CAAK,CAAA,QAAA,IAGjB,CAACC,CAAAA,CACH,MAAM,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AgC,CAAA,CACjD,OAAOH,CAAAA,CAAU,iBAAiBG,CAAIC,CAAAA,CAAAA,CAAS8B,CAAY,EAAA,IAAI,CACjE,CACA,CAAA,MAAM,cAAe1B,CAAAA,CAAAA,CAAuD,CAC1E,OAAOR,CAAAA,CAAU,cAAeI,CAAAA,CAAAA,CAASI,EAAS0B,CAAY,EAAA,IAAI,CACpE,CAAA,CACA,MAAM,QAAS/B,CAAAA,CAAAA,CAA4B,CACzC,OAAON,EAAM,WAAYM,CAAAA,CAAAA,CAAIC,CAAO,CACtC,CACF,CACF","file":"index.mjs","sourcesContent":["import { ServerDate } from \"./blueprint\";\n\n// According to protobufs\nexport enum ProofStatus {\n None,\n InProgress,\n Done,\n Failed,\n}\n\nexport type ProofProps = {\n id: string;\n blueprintId: string;\n input: string;\n proof?: string;\n public?: string;\n status?: ProofStatus;\n startedAt?: Date;\n provedAt?: Date;\n};\n\nexport type ProofResponse = {\n id: string;\n blueprint_id: string;\n input: string;\n proof?: string;\n public?: string;\n started_at: ServerDate;\n proved_at?: ServerDate;\n status: number;\n};\n\nexport type ProofRequest = {\n blueprint_id: string;\n input: string;\n};\n\nexport type GenerateProofInputsParams = {\n emailHeaderMaxLength: number;\n emailBodyMaxLength: number;\n ignoreBodyHashCheck: boolean;\n removeSoftLinebreaks: boolean;\n shaPrecomputeSelector?: string;\n};\n\nexport type GenerateProofInputsParamsInternal = {\n maxHeaderLength: number;\n maxBodyLength: number;\n ignoreBodyHashCheck: boolean;\n removeSoftLinesBreaks: boolean;\n shaPrecomputeSelector?: string;\n};\n","import { Auth } from \"./types/auth\";\n\n// prod\nconst GITHUB_CLIENT_ID = \"Ov23li0KABFCUsxBEQkn\";\n\n// const GITHUB_CLIENT_ID = \"Ov23liUVyAeZK1bxoAkh\";\n\nexport function getLoginWithGithubUrl(\n callbackUrl: string,\n githubClientId = GITHUB_CLIENT_ID\n): string {\n const state = encodeURIComponent(callbackUrl);\n return `https://github.com/login/oauth/authorize?client_id=${githubClientId}&scope=user:email&state=${state}`;\n}\n\nexport async function getTokenFromAuth(auth: Auth): Promise<string> {\n try {\n let token = await auth.getToken();\n\n if (!token) {\n await auth.onTokenExpired();\n token = await auth.getToken();\n }\n\n if (!token) {\n throw new Error(\"Failed to get new token\");\n }\n\n return `Bearer ${token}`;\n } catch (err) {\n console.error(\"Failed to get token from auth\");\n throw err;\n }\n}\n","const PUBLIC_SDK_KEY = \"pk_live_51NXwT8cHf0vYAjQK9LzB3pM6R8gWx2F\";\n\nimport {\n Blueprint,\n DecomposedRegex,\n DecomposedRegexJson,\n DecomposedRegexPart,\n DecomposedRegexPartJson,\n} from \"./blueprint\";\nimport { Auth } from \"./types/auth\";\nimport { getTokenFromAuth } from \"./auth\";\nimport type * as NodeUtils from \"@dimidumo/relayer-utils/node\";\nimport type * as WebUtils from \"@dimidumo/relayer-utils/web\";\nimport {\n BlueprintProps,\n ExternalInput,\n GenerateProofInputsParams,\n GenerateProofInputsParamsInternal,\n} from \"./types\";\nimport { log } from \"console\";\n\ntype RelayerUtilsType = typeof NodeUtils | typeof WebUtils;\n\nlet relayerUtilsResolver: (value: any) => void;\nconst relayerUtils: Promise<RelayerUtilsType> = new Promise((resolve) => {\n relayerUtilsResolver = resolve;\n});\n\n// @ts-ignore\n// if (typeof window === \"undefined\" || typeof Deno !== \"undefined\") {\nif (false) {\n console.warn(\"Relayer utils won't work when used server side\");\n // console.log(\"Initializing for node\");\n // import(\"@dimidumo/relayer-utils/node\")\n // .then((rl) => {\n // relayerUtilsResolver(rl);\n // })\n // .catch((err) => console.log(\"failed to init WASM on node: \", err));\n} else {\n console.log(\"frontend wasm\");\n try {\n import(\"@dimidumo/relayer-utils/web\")\n .then(async (rl) => {\n // @ts-ignore\n await rl.default();\n relayerUtilsResolver(rl);\n })\n .catch((err) => {\n console.log(\"Failed to init WASM: \", err);\n });\n } catch (err) {}\n}\n\nexport async function post<T>(url: string, data?: object | null, auth?: Auth): Promise<T> {\n try {\n const request: RequestInit = {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"x-api-key\": PUBLIC_SDK_KEY,\n ...(!auth ? {} : { Authorization: await getTokenFromAuth(auth) }),\n },\n };\n\n if (data) {\n request.body = JSON.stringify(data);\n }\n\n const response = await fetch(url, request);\n\n const body = await response.json();\n\n if (!response.ok) {\n throw new Error(`HTTP error! status: ${response.status}, message: ${body}`);\n }\n\n return body;\n } catch (error) {\n // TODO: Handle token expired\n console.error(\"POST Error:\", error);\n throw error;\n }\n}\n\nexport async function patch<T>(url: string, data?: object | null, auth?: Auth): Promise<T> {\n try {\n const request: RequestInit = {\n method: \"PATCH\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"x-api-key\": PUBLIC_SDK_KEY,\n ...(!auth ? {} : { Authorization: await getTokenFromAuth(auth) }),\n },\n };\n\n if (data) {\n request.body = JSON.stringify(data);\n }\n\n const response = await fetch(url, request);\n\n const body = await response.json();\n\n if (!response.ok) {\n throw new Error(`HTTP error! status: ${response.status}, message: ${body}`);\n }\n\n return body;\n } catch (error) {\n console.error(\"PATCH Error:\", error);\n throw error;\n }\n}\n\nexport async function get<T>(url: string, queryParams?: object | null, auth?: Auth): Promise<T> {\n try {\n let fullUrl = url;\n if (queryParams) {\n const searchParams = new URLSearchParams();\n Object.entries(queryParams).forEach(([key, value]) => {\n if (value) {\n searchParams.append(key, String(value));\n }\n });\n if (searchParams.size > 0) {\n fullUrl += `?${searchParams.toString()}`;\n }\n }\n\n const response = await fetch(fullUrl, {\n method: \"GET\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"x-api-key\": PUBLIC_SDK_KEY,\n ...(!auth ? {} : { Authorization: await getTokenFromAuth(auth) }),\n },\n });\n\n if (!response.ok) {\n throw new Error(`HTTP error! status: ${response.status}`);\n }\n\n return await response.json();\n } catch (error) {\n console.error(\"GET Error:\", error);\n throw error;\n }\n}\n\n// Provisional type, delete once libary types\ntype ParsedEmail = {\n canonicalized_header: string;\n canonicalized_body: string;\n signature: number[];\n public_key: any[];\n cleaned_body: string;\n headers: Map<string, string[]>;\n};\n\nexport async function parseEmail(eml: string): Promise<ParsedEmail> {\n try {\n const utils = await relayerUtils;\n const parsedEmail = await utils.parseEmail(eml);\n return parsedEmail as ParsedEmail;\n } catch (err) {\n console.error(\"Failed to parse email: \", err);\n throw err;\n }\n}\n\nexport async function testBlueprint(\n eml: string,\n blueprint: BlueprintProps,\n revealPrivate = false\n): Promise<string[][]> {\n const parsedEmail = await parseEmail(eml);\n\n if (blueprint.emailBodyMaxLength === undefined || blueprint.emailHeaderMaxLength === undefined) {\n throw new Error(\"emailBodyMaxLength and emailHeaderMaxLength must be provided\");\n }\n\n const body =\n parsedEmail.canonicalized_body.length > blueprint.emailBodyMaxLength\n ? parsedEmail.canonicalized_body.substring(0, blueprint.emailBodyMaxLength)\n : parsedEmail.canonicalized_body;\n const header =\n parsedEmail.canonicalized_header.length > blueprint.emailHeaderMaxLength\n ? parsedEmail.canonicalized_header.substring(0, blueprint.emailHeaderMaxLength)\n : parsedEmail.canonicalized_header;\n\n const output = await Promise.all(\n blueprint.decomposedRegexes.map((dcr: DecomposedRegex) =>\n testDecomposedRegex(body, header, dcr, revealPrivate)\n )\n );\n\n return output;\n}\n\nexport async function testDecomposedRegex(\n body: string,\n header: string,\n decomposedRegex: DecomposedRegex | DecomposedRegexJson,\n revealPrivate = false\n): Promise<string[]> {\n const inputDecomposedRegex = {\n parts: decomposedRegex.parts.map((p: DecomposedRegexPart | DecomposedRegexPartJson) => ({\n is_public: \"isPublic\" in p ? p.isPublic : p.is_public,\n regex_def: \"regexDef\" in p ? p.regexDef : p.regex_def,\n })),\n };\n\n let inputStr: string;\n if (decomposedRegex.location === \"body\") {\n inputStr = body;\n } else if (decomposedRegex.location === \"header\") {\n inputStr = header;\n } else {\n throw Error(`Unsupported location ${decomposedRegex.location}`);\n }\n\n const maxLength =\n \"maxLength\" in decomposedRegex ? decomposedRegex.maxLength : decomposedRegex.max_length;\n\n const utils = await relayerUtils;\n const privateResult = utils.extractSubstr(inputStr, inputDecomposedRegex, false);\n\n if (privateResult[0].length > maxLength) {\n throw new Error(\n `Max length of extracted result was exceeded for decomposed regex ${decomposedRegex.name}`\n );\n }\n\n if (!revealPrivate) {\n return privateResult;\n }\n\n const result = utils.extractSubstr(inputStr, inputDecomposedRegex, revealPrivate);\n return result;\n}\n\nexport async function generateProofInputs(\n eml: string,\n decomposedRegexes: DecomposedRegex[],\n externalInputs: ExternalInput[],\n params: GenerateProofInputsParams\n): Promise<string> {\n try {\n const internalParams: GenerateProofInputsParamsInternal = {\n maxHeaderLength: params.emailHeaderMaxLength,\n maxBodyLength: params.emailBodyMaxLength,\n ignoreBodyHashCheck: params.ignoreBodyHashCheck,\n removeSoftLinesBreaks: params.removeSoftLinebreaks,\n shaPrecomputeSelector: params.shaPrecomputeSelector,\n };\n\n const utils = await relayerUtils;\n // console.log(\"got relayer utils\");\n // console.log(\"actually creating proof inputs with params: \", internalParams);\n\n const decomposedRegexesCleaned = decomposedRegexes.map((dcr) => {\n return {\n ...dcr,\n parts: dcr.parts.map((p) => ({\n // @ts-ignore\n is_public: p.isPublic || !!p.is_public,\n // @ts-ignore\n regex_def: p.regexDef || !!p.regex_def,\n })),\n };\n });\n\n console.log(\"calling generateCircuitInputsWithDecomposedRegexesAndExternalInputs with\");\n console.log(\"eml: \", eml);\n console.log(\"decomposedRegex: \", decomposedRegexesCleaned);\n console.log(\"externalInputs: \", externalInputs);\n console.log(\"params: \", params);\n\n const inputs = await utils.generateCircuitInputsWithDecomposedRegexesAndExternalInputs(\n eml,\n decomposedRegexesCleaned,\n externalInputs,\n internalParams\n );\n\n return JSON.stringify(Object.fromEntries(inputs));\n } catch (err) {\n console.error(\"Failed to generate inputs for proof\");\n throw err;\n }\n}\n\nexport function startJsonFileDownload(json: string, name = \"data\") {\n if (!window && !document) {\n throw Error(\"startFilesDownload can only be used in a browser\");\n }\n\n const blob = new Blob([json], { type: \"application/json\" });\n const url = URL.createObjectURL(blob);\n\n const link = document.createElement(\"a\");\n link.href = url;\n link.download = `${name}.json`;\n document.body.appendChild(link);\n link.click();\n document.body.removeChild(link);\n URL.revokeObjectURL(url);\n}\n","import { Blueprint, Status } from \"./blueprint\";\nimport { ProofProps, ProofResponse, ProofStatus } from \"./types/proof\";\nimport { get } from \"./utils\";\n\n/**\n * A generated proof. You get get proof data and verify proofs on chain.\n */\nexport class Proof {\n blueprint: Blueprint;\n props: ProofProps;\n private lastCheckedStatus: Date | null = null;\n\n constructor(blueprint: Blueprint, props: ProofProps) {\n if (!(blueprint instanceof Blueprint)) {\n throw new Error(\"Invalid blueprint: must be an instance of Blueprint class\");\n }\n this.blueprint = blueprint;\n\n if (!props?.id) {\n throw new Error(\"A proof must have an id\");\n }\n\n this.props = {\n status: ProofStatus.InProgress,\n ...props,\n };\n }\n\n getId(): string {\n return this.props.id;\n }\n\n /**\n * Returns a download link for the files of the proof.\n * @returns The the url to download a zip of the proof files.\n */\n async getProofDataDownloadLink(): Promise<string> {\n if (this.props.status !== ProofStatus.Done) {\n throw new Error(\"The proving is not done yet.\");\n }\n\n let response: { url: string };\n try {\n response = await get<{ url: string }>(\n `${this.blueprint.baseUrl}/proof/files/${this.props.id}`\n );\n } catch (err) {\n console.error(\"Failed calling GET on /proof/files/:id in getProofDataDownloadLink: \", err);\n throw err;\n }\n\n return response.url;\n }\n\n async startFilesDownload() {\n if (!window && !document) {\n throw Error(\"startFilesDownload can only be used in a browser\");\n }\n\n let url: string;\n try {\n url = await this.getProofDataDownloadLink();\n } catch (err) {\n console.error(\"Failed to start download of ZKeys: \", err);\n throw err;\n }\n\n const link = document.createElement(\"a\");\n link.href = url;\n link.download = \"proof_files.zip\"; // Set the desired filename\n document.body.appendChild(link);\n link.click();\n document.body.removeChild(link);\n }\n\n /**\n * Checks the status of proof.\n * checkStatus can be used in a while(await checkStatus()) loop, since it will wait a fixed\n * amount of time before the second time you call it.\n * @returns A promise with the Status.\n */\n async checkStatus(): Promise<ProofStatus> {\n if (this.props.status === ProofStatus.Done) {\n return this.props.status;\n }\n\n // Waits for a fixed period of time before you can call checkStatus again\n // This enables you to put checkStatus in a while(await checkStatu()) loop\n if (!this.lastCheckedStatus) {\n this.lastCheckedStatus = new Date();\n } else {\n const waitTime = 500;\n const sinceLastChecked = new Date().getTime() - this.lastCheckedStatus.getTime();\n if (sinceLastChecked < waitTime) {\n await new Promise((r) => setTimeout(r, waitTime - sinceLastChecked));\n }\n }\n\n // Check status\n let response: { status: ProofStatus };\n try {\n response = await get<{ status: ProofStatus }>(\n `${this.blueprint.baseUrl}/proof/status/${this.props.id}`\n );\n } catch (err) {\n console.error(\"Failed calling GET /blueprint/status in getStatus(): \", err);\n throw err;\n }\n\n this.props.status = response.status;\n return response.status;\n }\n\n async verifyOnChain() {}\n\n /**\n * Fetches an existing Proof from the database.\n * @param id - Id of the Proof.\n * @returns A promise that resolves to a new instance of Proof.\n */\n public static async getPoofById(id: string, baseUrl: string): Promise<Proof> {\n let proofResponse: ProofResponse;\n try {\n proofResponse = await get<ProofResponse>(`${baseUrl}/proof/${id}`);\n } catch (err) {\n console.error(\"Failed calling /proof/:id in getProofById: \", err);\n throw err;\n }\n\n const proofProps = this.responseToProofProps(proofResponse);\n const blueprint = await Blueprint.getBlueprintById(proofResponse.blueprint_id, baseUrl);\n\n return new Proof(blueprint, proofProps);\n }\n\n public static responseToProofProps(response: ProofResponse): ProofProps {\n const props: ProofProps = {\n id: response.id,\n blueprintId: response.blueprint_id,\n status: response.status as ProofStatus,\n input: response.input,\n proof: response.proof,\n public: response.public,\n startedAt: new Date(response.started_at.seconds * 1000),\n provedAt: response.proved_at ? new Date(response.proved_at.seconds * 1000) : undefined,\n };\n return props;\n }\n}\n","import { Blueprint } from \"./blueprint\";\nimport { Proof } from \"./proof\";\nimport {\n GenerateProofInputsParams,\n ProofProps,\n ProofRequest,\n ProofResponse,\n ProofStatus,\n} from \"./types/proof\";\nimport { ProverOptions } from \"./types/prover\";\nimport { generateProofInputs, post } from \"./utils\";\n\n/**\n * Represents a Prover generated from a blueprint that can generate Proofs\n */\nexport class Prover {\n options: ProverOptions;\n blueprint: Blueprint;\n\n constructor(blueprint: Blueprint, options?: ProverOptions) {\n if (options?.isLocal === true) {\n throw new Error(\"Local proving is not supported yet\");\n }\n\n if (!(blueprint instanceof Blueprint)) {\n throw new Error(\"Invalid blueprint: must be an instance of Blueprint class\");\n }\n\n this.blueprint = blueprint;\n\n // Use defaults for unset fields\n this.options = {\n isLocal: false,\n ...(!!options ? options : {}),\n };\n }\n\n // TODO: Add parsed email input\n /**\n * Generates a proof for a given email.\n * @param eml - Email to prove agains the blueprint of this Prover.\n * @returns A promise that resolves to a new instance of Proof. The Proof will have the status\n * Done or Failed.\n */\n async generateProof(eml: string): Promise<Proof> {\n console.log(\"starting generate proof\");\n const proof = await this.generateProofRequest(eml);\n console.log(\"got proof: \", proof);\n\n // Wait for proof to finish\n while (![ProofStatus.Done, ProofStatus.Failed].includes(await proof.checkStatus())) {}\n return proof;\n }\n\n // TODO: Add parsed email input\n /**\n * Starts proving for a given email.\n * @param eml - Email to prove agains the blueprint of this Prover.\n * @returns A promise that resolves to a new instance of Proof. The Proof will have the status\n * InProgress.\n */\n async generateProofRequest(eml: string): Promise<Proof> {\n const blueprintId = this.blueprint.getId();\n if (!blueprintId) {\n throw new Error(\"Blueprint of Proover must be initialized in order to create a Proof\");\n }\n\n let input: string;\n try {\n // TODO: Do we use defaults?\n const params: GenerateProofInputsParams = {\n emailHeaderMaxLength: this.blueprint.props.emailHeaderMaxLength || 256,\n emailBodyMaxLength: this.blueprint.props.emailBodyMaxLength || 2560,\n ignoreBodyHashCheck: this.blueprint.props.ignoreBodyHashCheck || false,\n removeSoftLinebreaks: this.blueprint.props.removeSoftLinebreaks || true,\n shaPrecomputeSelector: this.blueprint.props.shaPrecomputeSelector,\n };\n console.log(\"generating proof inputs\");\n input = await generateProofInputs(\n eml,\n this.blueprint.props.decomposedRegexes,\n this.blueprint.props.externalInputs || [],\n params\n );\n } catch (err) {\n console.error(\"Failed to generate inputs for proof\");\n throw err;\n }\n\n console.log(\"got proof input\");\n let response: ProofResponse;\n try {\n const requestData: ProofRequest = {\n blueprint_id: blueprintId,\n input,\n };\n\n response = await post<ProofResponse>(`${this.blueprint.baseUrl}/proof`, requestData);\n } catch (err) {\n console.error(\"Failed calling POST on /proof/ in generateProofRequest: \", err);\n throw err;\n }\n\n const proofProps = Proof.responseToProofProps(response);\n return new Proof(this.blueprint, proofProps);\n }\n}\n","export type BlueprintProps = {\n id?: string;\n title: string;\n description?: string;\n slug?: string;\n tags?: string[];\n emailQuery?: string;\n circuitName: string;\n ignoreBodyHashCheck?: boolean;\n shaPrecomputeSelector?: string;\n emailBodyMaxLength?: number;\n emailHeaderMaxLength?: number;\n removeSoftLinebreaks?: boolean;\n githubUsername?: string;\n senderDomain?: string;\n enableHeaderMasking?: boolean;\n enableBodyMasking?: boolean;\n zkFramework?: ZkFramework;\n isPublic?: boolean;\n createdAt?: Date;\n updatedAt?: Date;\n externalInputs?: ExternalInput[];\n decomposedRegexes: DecomposedRegex[];\n status?: Status;\n verifierContract?: VerifierContract;\n version?: number;\n};\n\nexport type DecomposedRegex = {\n parts: DecomposedRegexPart[];\n name: string;\n maxLength: number;\n location: \"body\" | \"header\";\n};\n\nexport type DecomposedRegexPart = {\n isPublic: boolean;\n regexDef: string;\n};\n\nexport type DecomposedRegexJson = {\n parts: DecomposedRegexPartJson[];\n name: string;\n max_length: number;\n location: \"body\" | \"header\";\n};\n\nexport type DecomposedRegexPartJson = {\n is_public: boolean;\n regex_def: string;\n};\n\nexport type ExternalInput = {\n name: string;\n maxLength: number;\n};\n\nexport enum ZkFramework {\n Circom = \"circom\",\n}\n\n// According to protobufs\nexport enum Status {\n None,\n Draft,\n InProgress,\n Done,\n Failed,\n}\n\nexport type VerifierContract = {\n address?: string;\n chain: number;\n};\n\nexport type BlueprintRequest = {\n id?: string;\n title: string;\n description?: string;\n slug?: string;\n tags?: string[];\n email_query?: string;\n circuit_name?: string;\n ignore_body_hash_check?: boolean;\n sha_precompute_selector?: string;\n email_body_max_length?: number;\n email_header_max_length?: number;\n remove_soft_linebreaks?: boolean;\n // TODO: Make non ? after login with github\n github_username?: string;\n sender_domain?: string;\n enable_header_masking?: boolean;\n enable_body_masking?: boolean;\n zk_framework?: string;\n is_public?: boolean;\n external_inputs?: ExternalInputResponse[];\n decomposed_regexes: DecomposedRegexResponse[];\n status?: string;\n verifier_contract_address?: string;\n verifier_contract_chain?: number;\n version?: number;\n};\n\nexport type BlueprintResponse = {\n id: string;\n title: string;\n description: string;\n slug: string;\n tags: string[];\n email_query: string;\n circuit_name: string;\n ignore_body_hash_check: boolean;\n sha_precompute_selector: string;\n email_body_max_length: number;\n email_header_max_length?: number;\n remove_soft_linebreaks?: boolean;\n github_username?: string;\n sender_domain: string;\n enable_header_masking?: boolean;\n enable_body_masking?: boolean;\n zk_framework: string;\n is_public: boolean;\n created_at: ServerDate;\n updated_at: ServerDate;\n external_inputs: ExternalInputResponse[];\n decomposed_regexes: DecomposedRegexResponse[];\n status: number;\n verifier_contract_address: string;\n verifier_contract_chain: number;\n version: number;\n};\n\nexport type ServerDate = {\n seconds: number;\n nanos: number;\n};\n\nexport type ExternalInputResponse = {\n name: string;\n max_length: number;\n};\n\nexport type DecomposedRegexResponse = {\n parts: DecomposedRegexPartResponse[];\n name: string;\n max_length: number;\n location: \"body\" | \"header\";\n};\n\nexport type DecomposedRegexPartResponse = {\n is_public: boolean;\n regex_def: string;\n};\n\nexport type ListBlueprintsOptions = {\n skip?: number;\n limit?: number;\n sort?: -1 | 1;\n status?: Status;\n isPublic?: boolean;\n search?: string;\n};\n\nexport type ListBlueprintsOptionsRequest = {\n skip?: number;\n limit?: number;\n sort?: -1 | 1;\n status?: Status;\n is_public?: boolean;\n search?: string;\n};\n\nexport type DownloadUrls = Record<string, string>;\n","import { createPublicClient, http } from \"viem\";\nimport { baseSepolia } from \"viem/chains\";\n\nconst WETHContractAddress = \"0x4200000000000000000000000000000000000006\";\n\nconst WETHContractABI = [\n {\n constant: true,\n inputs: [],\n name: \"totalSupply\",\n outputs: [{ name: \"\", type: \"uint256\" }],\n type: \"function\",\n },\n] as const;\n\nconst client = createPublicClient({\n chain: baseSepolia,\n transport: http(),\n});\n\nexport async function verifyProofOnChain() {\n try {\n const totalSupply = await client.readContract({\n address: WETHContractAddress,\n abi: WETHContractABI,\n functionName: \"totalSupply\",\n });\n\n return totalSupply;\n } catch (error) {\n console.error(\"Error fetching WETH total supply:\", error);\n throw error;\n }\n}\n","import { Proof } from \"viem/_types/types/proof\";\nimport { Prover } from \"./prover\";\nimport {\n BlueprintProps,\n BlueprintRequest,\n BlueprintResponse,\n DownloadUrls,\n ListBlueprintsOptions,\n ListBlueprintsOptionsRequest,\n Status,\n ZkFramework,\n} from \"./types/blueprint\";\nimport { get, patch, post } from \"./utils\";\nimport { verifyProofOnChain } from \"./chain\";\nimport { Auth } from \"./types/auth\";\n\n/**\n * Represents a Regex Blueprint including the decomposed regex access to the circuit.\n */\nexport class Blueprint {\n // TODO: Implement getter and setter pattern\n props: BlueprintProps;\n auth?: Auth;\n baseUrl: string;\n\n private lastCheckedStatus: Date | null = null;\n\n constructor(props: BlueprintProps, baseUrl: string, auth?: Auth) {\n // Use defaults for unset fields\n this.props = {\n ignoreBodyHashCheck: false,\n enableHeaderMasking: false,\n enableBodyMasking: false,\n isPublic: true,\n status: Status.Draft,\n ...props,\n };\n\n this.baseUrl = baseUrl;\n this.auth = auth;\n }\n\n addAuth(auth: Auth) {\n this.auth = auth;\n }\n\n /**\n * Fetches an existing RegexBlueprint from the database.\n * @param {string} id - Id of the RegexBlueprint.\n * @returns A promise that resolves to a new instance of RegexBlueprint.\n */\n public static async getBlueprintById(\n id: string,\n baseUrl: string,\n auth?: Auth\n ): Promise<Blueprint> {\n let blueprintResponse: BlueprintResponse;\n try {\n blueprintResponse = await get<BlueprintResponse>(`${baseUrl}/blueprint/${id}`);\n } catch (err) {\n console.error(\"Failed calling /blueprint/:id in getBlueprintById: \", err);\n throw err;\n }\n\n const blueprintProps = this.responseToBlueprintProps(blueprintResponse);\n\n const blueprint = new Blueprint(blueprintProps, baseUrl, auth);\n\n return blueprint;\n }\n\n // Maps the blueprint API response to the BlueprintProps\n private static responseToBlueprintProps(response: BlueprintResponse): BlueprintProps {\n const props: BlueprintProps = {\n id: response.id,\n title: response.title,\n description: response.description,\n slug: response.slug,\n tags: response.tags,\n emailQuery: response.email_query,\n circuitName: response.circuit_name,\n ignoreBodyHashCheck: response.ignore_body_hash_check,\n shaPrecomputeSelector: response.sha_precompute_selector,\n emailBodyMaxLength: response.email_body_max_length,\n emailHeaderMaxLength: response.email_header_max_length,\n removeSoftLinebreaks: response.remove_soft_linebreaks,\n githubUsername: response.github_username,\n senderDomain: response.sender_domain,\n enableHeaderMasking: response.enable_header_masking,\n enableBodyMasking: response.enable_body_masking,\n zkFramework: response.zk_framework as ZkFramework,\n isPublic: response.is_public,\n createdAt: new Date(response.created_at.seconds * 1000),\n updatedAt: new Date(response.updated_at.seconds * 1000),\n externalInputs: response.external_inputs?.map((input) => ({\n name: input.name,\n maxLength: input.max_length,\n })),\n decomposedRegexes: response.decomposed_regexes?.map((regex) => ({\n parts: regex.parts.map((part) => ({\n isPublic: part.is_public,\n regexDef: part.regex_def,\n })),\n name: regex.name,\n maxLength: regex.max_length,\n location: regex.location,\n })),\n status: response.status as Status,\n verifierContract: {\n address: response.verifier_contract_address,\n chain: response.verifier_contract_chain,\n },\n version: response.version,\n };\n\n return props;\n }\n\n // Maps the BlueprintProps to the BlueprintResponse\n private static blueprintPropsToRequest(props: BlueprintProps): BlueprintRequest {\n const response: BlueprintRequest = {\n id: props.id,\n title: props.title,\n description: props.description,\n slug: props.slug,\n tags: props.tags,\n email_query: props.emailQuery,\n circuit_name: props.circuitName,\n ignore_body_hash_check: props.ignoreBodyHashCheck,\n sha_precompute_selector: props.shaPrecomputeSelector,\n email_body_max_length: props.emailBodyMaxLength,\n email_header_max_length: props.emailHeaderMaxLength,\n remove_soft_linebreaks: props.removeSoftLinebreaks,\n github_username: props.githubUsername,\n sender_domain: props.senderDomain,\n enable_header_masking: props.enableHeaderMasking,\n enable_body_masking: props.enableBodyMasking,\n zk_framework: props.zkFramework,\n is_public: props.isPublic,\n external_inputs: props.externalInputs?.map((input) => ({\n name: input.name,\n max_length: input.maxLength,\n })),\n decomposed_regexes: props.decomposedRegexes?.map((regex) => ({\n parts: regex.parts.map((part) => ({\n // @ts-ignore\n is_public: part.isPublic || part.is_public,\n // @ts-ignore\n regex_def: part.regexDef || part.regex_def,\n })),\n name: regex.name,\n max_length: regex.maxLength,\n location: regex.location,\n })),\n verifier_contract_address: props.verifierContract?.address,\n verifier_contract_chain: props.verifierContract?.chain,\n };\n\n return response;\n }\n\n /**\n * Submits a new RegexBlueprint to the registry as draft.\n * This does not compile the circuits yet and you will still be able to make changes.\n * @returns A promise. Once it resolves, `getId` can be called.\n */\n public async submitDraft() {\n if (!this.auth) {\n throw new Error(\"auth is required, add it with Blueprint.addAuth(auth)\");\n }\n\n if (this.props.id) {\n throw new Error(\"Blueprint was already saved\");\n }\n\n const requestData = Blueprint.blueprintPropsToRequest(this.props);\n\n let response: BlueprintResponse;\n try {\n response = await post<BlueprintResponse>(`${this.baseUrl}/blueprint`, requestData, this.auth);\n } catch (err) {\n console.error(\"Failed calling POST on /blueprint/ in submitDraft: \", err);\n throw err;\n }\n\n this.props = Blueprint.responseToBlueprintProps(response);\n }\n\n /**\n * Submits a new version of the RegexBlueprint to the registry as draft.\n * This does not compile the circuits yet and you will still be able to make changes.\n * @param newProps - The updated blueprint props.\n * @returns A promise. Once it resolves, the current Blueprint will be replaced with the new one.\n */\n public async submitNewVersionDraft(newProps: BlueprintProps) {\n if (!this.auth) {\n throw new Error(\"auth is required, add it with Blueprint.addAuth(auth)\");\n }\n\n const requestData = Blueprint.blueprintPropsToRequest(newProps);\n\n let response: BlueprintResponse;\n try {\n response = await post<BlueprintResponse>(`${this.baseUrl}/blueprint`, requestData, this.auth);\n } catch (err) {\n console.error(\"Failed calling POST on /blueprint/ in submitDraft: \", err);\n throw err;\n }\n\n this.props = Blueprint.responseToBlueprintProps(response);\n }\n\n /**\n * Submits a new version of the blueprint. This will save the new blueprint version\n * and start the compilation.\n * This will also overwrite the current Blueprint with its new version, even if the last\n * version was not compiled yet.\n * @param newProps - The updated blueprint props.\n */\n async submitNewVersion(newProps: BlueprintProps) {\n if (!this.auth) {\n throw new Error(\"auth is required, add it with Blueprint.addAuth(auth)\");\n }\n\n await this.submitNewVersionDraft(newProps);\n\n // We don't check the status here, since we are compiling directly after submiting the draft.\n\n // Submit compile request\n try {\n await post<{ status: Status }>(\n `${this.baseUrl}/blueprint/compile/${this.props.id}`,\n null,\n this.auth\n );\n } catch (err) {\n // We don't set the status here, since the api call can't fail due to the actual job failing\n // It can only due to connectivity issues or the job runner not being available\n console.error(\"Failed calling POST on /blueprint/compile in submit: \", err);\n throw err;\n }\n }\n\n /**\n * Lists blueblueprints, only including the latest version per unique slug.\n * @param options - Options to filter the blueprints by.\n * @returns A promise. Once it resolves, `getId` can be called.\n */\n public static async listBlueprints(\n baseUrl: string,\n options?: ListBlueprintsOptions,\n auth?: Auth\n ): Promise<Blueprint[]> {\n const requestOptions: ListBlueprintsOptionsRequest = {\n skip: options?.skip,\n limit: options?.limit,\n sort: options?.sort,\n status: options?.status,\n is_public: options?.isPublic,\n search: options?.search,\n };\n\n let response: { blueprints?: BlueprintResponse[] };\n try {\n response = await get<{ blueprints?: BlueprintResponse[] }>(\n `${baseUrl}/blueprint`,\n requestOptions\n );\n } catch (err) {\n console.error(\"Failed calling POST on /blueprint/ in submitDraft: \", err);\n throw err;\n }\n\n if (!response.blueprints) {\n return [];\n }\n\n return response.blueprints.map((blueprintResponse) => {\n const blueprintProps = Blueprint.responseToBlueprintProps(blueprintResponse);\n return new Blueprint(blueprintProps, baseUrl, auth);\n });\n }\n\n /**\n * Submits a blueprint. This will save the blueprint if it didn't exist before\n * and start the compilation.\n */\n async submit() {\n if (!this.auth) {\n throw new Error(\"auth is required, add it with Blueprint.addAuth(auth)\");\n }\n\n // If the blueprint wasn't save yet, we save it first to db\n if (!this.props.id) {\n try {\n await this.submitDraft();\n } catch (err) {\n console.error(\"Failed to create blueprint: \", err);\n throw err;\n }\n }\n\n const status = await this._checkStatus();\n\n // TODO: Should we allow retry on failed?\n if (Status.Done === status) {\n throw new Error(\"The circuits are already compiled.\");\n }\n if (Status.InProgress === status) {\n throw new Error(\"The circuits already being compiled, please wait.\");\n }\n\n // Submit compile request\n try {\n await post<{ status: Status }>(\n `${this.baseUrl}/blueprint/compile/${this.props.id}`,\n null,\n this.auth\n );\n } catch (err) {\n // We don't set the status here, since the api call can't fail due to the actual job failing\n // It can only due to connectivity issues or the job runner not being available\n console.error(\"Failed calling POST on /blueprint/compile in submit: \", err);\n throw err;\n }\n }\n\n // Request status from server and updates props.status\n private async _checkStatus(): Promise<Status> {\n let response: { status: Status };\n try {\n response = await get<{ status: Status }>(`${this.baseUrl}/blueprint/status/${this.props.id}`);\n } catch (err) {\n console.error(\"Failed calling GET /blueprint/status in getStatus(): \", err);\n throw err;\n }\n\n this.props.status = response.status;\n return response.status;\n }\n\n /**\n * Checks the status of blueprint.\n * checkStatus can be used in a while(await checkStatus()) loop, since it will wait a fixed\n * amount of time the second time you call it.\n * @returns A promise with the Status.\n */\n async checkStatus(): Promise<Status> {\n // Blueprint wasn't saved yet, return default status\n if (!this.props.id) {\n return this.props.status!;\n }\n\n if ([Status.Failed, Status.Done].includes(this.props.status!)) {\n return this.props.status!;\n }\n\n // Waits for a fixed period of time before you can call checkStatus again\n // This enables you to put checkStatus in a while(await checkStatus()) loop\n if (!this.lastCheckedStatus) {\n this.lastCheckedStatus = new Date();\n } else {\n // TODO: change for prod to one minute\n const waitTime = 0.5 * 1_000; // TODO: should be one minute;\n const sinceLastChecked = new Date().getTime() - this.lastCheckedStatus.getTime();\n if (sinceLastChecked < waitTime) {\n await new Promise((r) => setTimeout(r, waitTime - sinceLastChecked));\n }\n }\n\n const status = await this._checkStatus();\n\n return status;\n }\n\n /**\n * Get the id of the blueprint.\n * @returns The id of the blueprint. If it was not saved yet, return null.\n */\n getId(): string | null {\n return this.props.id || null;\n }\n\n /**\n * Returns a download link for the ZKeys of the blueprint.\n * @returns The the url to download the ZKeys.\n */\n async getZKeyDownloadLink(): Promise<DownloadUrls> {\n if (this.props.status !== Status.Done) {\n throw new Error(\"The circuits are not compiled yet, nothing to download.\");\n }\n\n let response: { urls: DownloadUrls };\n try {\n response = await get<{ urls: DownloadUrls }>(\n `${this.baseUrl}/blueprint/zkey/${this.props.id}`\n );\n console.log(\"response: \", response);\n } catch (err) {\n console.error(\"Failed calling GET on /blueprint/zkey/:id in getZKeyDownloadLink: \", err);\n throw err;\n }\n\n return response.urls;\n }\n\n /**\n * Directly starts a download of the ZKeys in the browser.\n * Must be called within a user action, like a button click.\n */\n async startZKeyDownload() {\n if (!window && !document) {\n throw Error(\"startZKeyDownload can only be used in a browser\");\n }\n\n let urls: DownloadUrls;\n try {\n urls = await this.getZKeyDownloadLink();\n } catch (err) {\n console.error(\"Failed to start download of ZKeys: \", err);\n throw err;\n }\n\n for (const [name, url] of Object.entries(urls)) {\n const link = document.createElement(\"a\");\n link.href = url;\n link.download = name; // Set the desired filename\n document.body.appendChild(link);\n link.click();\n document.body.removeChild(link);\n }\n }\n\n /**\n * Creates an instance of Prover with which you can create proofs.\n * @returns An instance of Prover.\n */\n createProver() {\n return new Prover(this);\n }\n\n /**\n * Verifies a proof on chain.\n * @param proof - The generated proof you want to verify.\n * @returns A true if the verification was successfull, false if it failed.\n */\n async verifyProofOnChain(proof: Proof): Promise<boolean> {\n try {\n const result = await verifyProofOnChain();\n } catch (err) {\n console.error(\"Failed to verify proof on chain: \", err);\n return false;\n }\n return true;\n }\n\n /**\n * Returns a deep cloned version of the Blueprints props.\n * This can be used to update properties and then to use them with createNewVersion.\n * @param proof - The generated proof you want to verify.\n * @returns A true if the verification was successfull, false if it failed.\n */\n getClonedProps(): BlueprintProps {\n const cloned = JSON.parse(JSON.stringify(this.props));\n\n // Conver date strings\n if (cloned.createdAt) {\n cloned.createdAt = new Date(cloned.createdAt);\n }\n if (cloned.updatedAt) {\n cloned.updatedAt = new Date(cloned.updatedAt);\n }\n\n return cloned;\n }\n\n /**\n * Returns true if the blueprint can be updated. A blueprint can be updated if the circuits\n * haven't beed compiled yet, i.e. the status is not Done. The blueprint also must be saved\n * already before it can be updated.\n * @returns true if it can be updated\n */\n canUpdate(): boolean {\n return !!(this.props.id && ![Status.Done, Status.InProgress].includes(this.props.status!));\n }\n\n /**\n * Updates an existing blueprint that is not compiled yet.\n * @param newProps - The props the blueprint should be updated to.\n * @returns a promise.\n */\n async update(newProps: BlueprintProps) {\n if (!this.auth) {\n throw new Error(\"auth is required, add it with Blueprint.addAuth(auth)\");\n }\n\n if (!this.canUpdate()) {\n throw new Error(\"Blueprint already compied, cannot update\");\n }\n\n const requestData = Blueprint.blueprintPropsToRequest(newProps);\n\n let response: BlueprintResponse;\n try {\n response = await patch<BlueprintResponse>(\n `${this.baseUrl}/blueprint/${this.props.id}`,\n requestData,\n this.auth\n );\n } catch (err) {\n console.error(\"Failed calling POST on /blueprint/ in submitDraft: \", err);\n throw err;\n }\n\n this.props = Blueprint.responseToBlueprintProps(response);\n }\n\n async listAllVersions(): Promise<Blueprint[]> {\n if (!this.props.id) {\n throw new Error(\"Blueprint was not saved yet\");\n }\n let response: { blueprints: BlueprintResponse[] };\n try {\n response = await get<{ blueprints: BlueprintResponse[] }>(\n `${this.baseUrl}/blueprint/versions/${encodeURIComponent(this.props.slug!)}`\n );\n } catch (err) {\n console.error(\"Failed calling GET on /blueprint/versions/:slug in listAllVersions: \", err);\n throw err;\n }\n\n return response.blueprints.map((blueprintResponse) => {\n const blueprintProps = Blueprint.responseToBlueprintProps(blueprintResponse);\n return new Blueprint(blueprintProps, this.baseUrl, this.auth);\n });\n }\n}\n\n// export {\n// BlueprintProps,\n// DecomposedRegex,\n// DecomposedRegexPart,\n// ExternalInput,\n// ZkFramework,\n// Status,\n// VerifierContract,\n// RevealHeaderFields,\n// } from \"./types/blueprint\";\n\nexport * from \"./types/blueprint\";\n","import { Blueprint, BlueprintProps, ListBlueprintsOptions } from \"./blueprint\";\nimport { Proof } from \"./proof\";\nimport { SdkOptions } from \"./types/sdk\";\n\n// Export Types\nexport * from \"./types/blueprint\";\nexport { Blueprint } from \"./blueprint\";\nexport * from \"./types/proof\";\nexport { Proof } from \"./proof\";\nexport type { Auth } from \"./types/auth\";\n\n// Exports that don't need initialization or options\nexport {\n testDecomposedRegex,\n parseEmail,\n startJsonFileDownload,\n generateProofInputs,\n testBlueprint,\n} from \"./utils\";\nexport { getLoginWithGithubUrl } from \"./auth\";\n\n// Exported sdk, functions that need initialization\nexport default (sdkOptions?: SdkOptions) => {\n const baseUrl = sdkOptions?.baseUrl || \"https://conductor.zk.email\";\n return {\n createBlueprint(props: BlueprintProps) {\n if (!sdkOptions && !sdkOptions!.auth) {\n throw new Error(\"You need to specify options.auth to use createBlueprint\");\n }\n const blueprint = new Blueprint(props, baseUrl, sdkOptions!.auth);\n return blueprint;\n },\n async getBlueprint(id: string): Promise<Blueprint> {\n return Blueprint.getBlueprintById(id, baseUrl, sdkOptions?.auth);\n },\n async listBlueprints(options?: ListBlueprintsOptions): Promise<Blueprint[]> {\n return Blueprint.listBlueprints(baseUrl, options, sdkOptions?.auth);\n },\n async getProof(id: string): Promise<Proof> {\n return Proof.getPoofById(id, baseUrl);\n },\n };\n};\n"]}
|
1
|
+
{"version":3,"sources":["../src/types/proof.ts","../src/auth.ts","../src/utils.ts","../src/proof.ts","../src/prover.ts","../src/types/blueprint.ts","../src/chain/index.ts","../src/blueprint.ts","../src/index.ts"],"names":["ProofStatus","GITHUB_CLIENT_ID","getLoginWithGithubUrl","callbackUrl","githubClientId","state","getTokenFromAuth","auth","token","err","PUBLIC_SDK_KEY","relayerUtilsResolver","relayerUtils","resolve","rl","post","url","data","request","response","body","error","patch","get","queryParams","fullUrl","searchParams","key","value","parseEmail","eml","testBlueprint","blueprint","revealPrivate","parsedEmail","header","output","dcr","testDecomposedRegex","decomposedRegex","inputDecomposedRegex","p","inputStr","maxLength","utils","privateResult","result","generateProofInputs","decomposedRegexes","externalInputs","params","internalParams","decomposedRegexesCleaned","inputs","startJsonFileDownload","json","name","blob","link","Proof","_Proof","props","Blueprint","sinceLastChecked","r","id","baseUrl","proofResponse","proofProps","Prover","options","proof","blueprintId","input","requestData","ZkFramework","Status","WETHContractAddress","WETHContractABI","client","createPublicClient","baseSepolia","http","verifyProofOnChain","_Blueprint","blueprintResponse","blueprintProps","regex","part","newProps","requestOptions","status","urls","cloned","src_default","sdkOptions"],"mappings":"iFAGO,IAAKA,OACVA,CAAA,CAAA,CAAA,CAAA,IAAA,CAAA,CAAA,CAAA,CAAA,MAAA,CACAA,CAAA,CAAA,CAAA,CAAA,UAAA,CAAA,CAAA,CAAA,CAAA,YAAA,CACAA,IAAA,IACAA,CAAAA,CAAAA,CAAAA,CAAAA,MAAAA,CAAAA,CAAAA,CAAAA,CAAAA,CAAA,MAJUA,CAAAA,CAAAA,CAAAA,CAAAA,QAAAA,CAAAA,CAAAA,CAAAA,EAAAA,CAAAA,EAAA,ICAZ,IAAMC,CAAAA,CAAmB,sBAIlB,CAAA,SAASC,EACdC,CACAC,CAAAA,CAAAA,CAAiBH,CACT,CAAA,CACR,IAAMI,CAAQ,CAAA,kBAAA,CAAmBF,CAAW,CAAA,CAC5C,OAAO,CAAsDC,mDAAAA,EAAAA,CAAc,CAA2BC,wBAAAA,EAAAA,CAAK,EAC7G,CAEA,eAAsBC,CAAiBC,CAAAA,CAAAA,CAA6B,CAClE,GAAI,CACF,IAAIC,CAAAA,CAAQ,MAAMD,CAAK,CAAA,QAAA,EAOvB,CAAA,GALKC,IACH,MAAMD,CAAAA,CAAK,cAAe,EAAA,CAC1BC,EAAQ,MAAMD,CAAAA,CAAK,QAAS,EAAA,CAAA,CAG1B,CAACC,CACH,CAAA,MAAM,IAAI,KAAA,CA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AUE,CAAAA,CAAAA,CAAgB,IAAK,CAAA,OAAA,CAAS,KAAK,IAAI,CAC9D,CAAC,CACH,CACF,EClgBA,IAAOQ,EAASC,CAAAA,CAAAA,EAA4B,CAC1C,IAAM7B,CAAAA,CAAU6B,CAAY,EAAA,OAAA,EAAW,6BACvC,OAAO,CACL,eAAgBlC,CAAAA,CAAAA,CAAuB,CACrC,GAAI,CAACkC,CAAc,EAAA,CAACA,EAAY,IAC9B,CAAA,MAAM,IAAI,KAAA,CAAM,yDAAyD,CAG3E,CAAA,OADkB,IAAIjC,CAAUD,CAAAA,CAAAA,CAAOK,EAAS6B,CAAY,CAAA,IAAI,CAElE,CAAA,CACA,MAAM,YAAa9B,CAAAA,CAAAA,CAAgC,CACjD,OAAOH,EAAU,gBAAiBG,CAAAA,CAAAA,CAAIC,CAAS6B,CAAAA,CAAAA,EAAY,IAAI,CACjE,CAAA,CACA,MAAM,cAAA,CAAezB,EAAuD,CAC1E,OAAOR,CAAU,CAAA,cAAA,CAAeI,EAASI,CAASyB,CAAAA,CAAAA,EAAY,IAAI,CACpE,EACA,MAAM,QAAA,CAAS9B,CAA4B,CAAA,CACzC,OAAON,CAAM,CAAA,WAAA,CAAYM,EAAIC,CAAO,CACtC,CACF,CACF","file":"index.mjs","sourcesContent":["import { ServerDate } from \"./blueprint\";\n\n// According to protobufs\nexport enum ProofStatus {\n None,\n InProgress,\n Done,\n Failed,\n}\n\nexport type ProofProps = {\n id: string;\n blueprintId: string;\n input: string;\n proof?: string;\n public?: string;\n status?: ProofStatus;\n startedAt?: Date;\n provedAt?: Date;\n};\n\nexport type ProofResponse = {\n id: string;\n blueprint_id: string;\n input: string;\n proof?: string;\n public?: string;\n started_at: ServerDate;\n proved_at?: ServerDate;\n status: number;\n};\n\nexport type ProofRequest = {\n blueprint_id: string;\n input: string;\n};\n\nexport type GenerateProofInputsParams = {\n emailHeaderMaxLength: number;\n emailBodyMaxLength: number;\n ignoreBodyHashCheck: boolean;\n removeSoftLinebreaks: boolean;\n shaPrecomputeSelector?: string;\n};\n\nexport type GenerateProofInputsParamsInternal = {\n maxHeaderLength: number;\n maxBodyLength: number;\n ignoreBodyHashCheck: boolean;\n removeSoftLinesBreaks: boolean;\n shaPrecomputeSelector?: string;\n};\n","import { Auth } from \"./types/auth\";\n\n// prod\nconst GITHUB_CLIENT_ID = \"Ov23li0KABFCUsxBEQkn\";\n\n// const GITHUB_CLIENT_ID = \"Ov23liUVyAeZK1bxoAkh\";\n\nexport function getLoginWithGithubUrl(\n callbackUrl: string,\n githubClientId = GITHUB_CLIENT_ID\n): string {\n const state = encodeURIComponent(callbackUrl);\n return `https://github.com/login/oauth/authorize?client_id=${githubClientId}&scope=user:email&state=${state}`;\n}\n\nexport async function getTokenFromAuth(auth: Auth): Promise<string> {\n try {\n let token = await auth.getToken();\n\n if (!token) {\n await auth.onTokenExpired();\n token = await auth.getToken();\n }\n\n if (!token) {\n throw new Error(\"Failed to get new token\");\n }\n\n return `Bearer ${token}`;\n } catch (err) {\n console.error(\"Failed to get token from auth\");\n throw err;\n }\n}\n","const PUBLIC_SDK_KEY = \"pk_live_51NXwT8cHf0vYAjQK9LzB3pM6R8gWx2F\";\n\nimport {\n Blueprint,\n DecomposedRegex,\n DecomposedRegexJson,\n DecomposedRegexPart,\n DecomposedRegexPartJson,\n} from \"./blueprint\";\nimport { Auth } from \"./types/auth\";\nimport { getTokenFromAuth } from \"./auth\";\nimport type * as NodeUtils from \"@dimidumo/relayer-utils/node\";\nimport type * as WebUtils from \"@dimidumo/relayer-utils/web\";\nimport {\n BlueprintProps,\n ExternalInput,\n GenerateProofInputsParams,\n GenerateProofInputsParamsInternal,\n} from \"./types\";\nimport { log } from \"console\";\n\ntype RelayerUtilsType = typeof NodeUtils | typeof WebUtils;\n\nlet relayerUtilsResolver: (value: any) => void;\nconst relayerUtils: Promise<RelayerUtilsType> = new Promise((resolve) => {\n relayerUtilsResolver = resolve;\n});\n\n// @ts-ignore\n// if (typeof window === \"undefined\" || typeof Deno !== \"undefined\") {\nif (false) {\n console.warn(\"Relayer utils won't work when used server side\");\n // console.log(\"Initializing for node\");\n // import(\"@dimidumo/relayer-utils/node\")\n // .then((rl) => {\n // relayerUtilsResolver(rl);\n // })\n // .catch((err) => console.log(\"failed to init WASM on node: \", err));\n} else {\n console.log(\"frontend wasm\");\n try {\n import(\"@dimidumo/relayer-utils/web\")\n .then(async (rl) => {\n // @ts-ignore\n await rl.default();\n relayerUtilsResolver(rl);\n })\n .catch((err) => {\n console.log(\"Failed to init WASM: \", err);\n });\n } catch (err) {}\n}\n\nexport async function post<T>(url: string, data?: object | null, auth?: Auth): Promise<T> {\n try {\n const request: RequestInit = {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"x-api-key\": PUBLIC_SDK_KEY,\n ...(!auth ? {} : { Authorization: await getTokenFromAuth(auth) }),\n },\n };\n\n if (data) {\n request.body = JSON.stringify(data);\n }\n\n const response = await fetch(url, request);\n\n const body = await response.json();\n\n if (!response.ok) {\n throw new Error(`HTTP error! status: ${response.status}, message: ${body}`);\n }\n\n return body;\n } catch (error) {\n // TODO: Handle token expired\n console.error(\"POST Error:\", error);\n throw error;\n }\n}\n\nexport async function patch<T>(url: string, data?: object | null, auth?: Auth): Promise<T> {\n try {\n const request: RequestInit = {\n method: \"PATCH\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"x-api-key\": PUBLIC_SDK_KEY,\n ...(!auth ? {} : { Authorization: await getTokenFromAuth(auth) }),\n },\n };\n\n if (data) {\n request.body = JSON.stringify(data);\n }\n\n const response = await fetch(url, request);\n\n const body = await response.json();\n\n if (!response.ok) {\n throw new Error(`HTTP error! status: ${response.status}, message: ${body}`);\n }\n\n return body;\n } catch (error) {\n console.error(\"PATCH Error:\", error);\n throw error;\n }\n}\n\nexport async function get<T>(url: string, queryParams?: object | null, auth?: Auth): Promise<T> {\n try {\n let fullUrl = url;\n if (queryParams) {\n const searchParams = new URLSearchParams();\n Object.entries(queryParams).forEach(([key, value]) => {\n if (value) {\n searchParams.append(key, String(value));\n }\n });\n if (searchParams.size > 0) {\n fullUrl += `?${searchParams.toString()}`;\n }\n }\n\n const response = await fetch(fullUrl, {\n method: \"GET\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"x-api-key\": PUBLIC_SDK_KEY,\n ...(!auth ? {} : { Authorization: await getTokenFromAuth(auth) }),\n },\n });\n\n if (!response.ok) {\n throw new Error(`HTTP error! status: ${response.status}`);\n }\n\n return await response.json();\n } catch (error) {\n console.error(\"GET Error:\", error);\n throw error;\n }\n}\n\n// Provisional type, delete once libary types\ntype ParsedEmail = {\n canonicalized_header: string;\n canonicalized_body: string;\n signature: number[];\n public_key: any[];\n cleaned_body: string;\n headers: Map<string, string[]>;\n};\n\nexport async function parseEmail(eml: string): Promise<ParsedEmail> {\n try {\n const utils = await relayerUtils;\n const parsedEmail = await utils.parseEmail(eml);\n return parsedEmail as ParsedEmail;\n } catch (err) {\n console.error(\"Failed to parse email: \", err);\n throw err;\n }\n}\n\nexport async function testBlueprint(\n eml: string,\n blueprint: BlueprintProps,\n revealPrivate = false\n): Promise<string[][]> {\n console.log(\"got eml: \", eml);\n const parsedEmail = await parseEmail(eml);\n console.log(\"got parsed email: \", parsedEmail);\n\n if (blueprint.emailBodyMaxLength === undefined || blueprint.emailHeaderMaxLength === undefined) {\n throw new Error(\"emailBodyMaxLength and emailHeaderMaxLength must be provided\");\n }\n\n const body =\n parsedEmail.canonicalized_body.length > blueprint.emailBodyMaxLength\n ? parsedEmail.canonicalized_body.substring(0, blueprint.emailBodyMaxLength)\n : parsedEmail.canonicalized_body;\n console.log(\"body: \", body);\n const header =\n parsedEmail.canonicalized_header.length > blueprint.emailHeaderMaxLength\n ? parsedEmail.canonicalized_header.substring(0, blueprint.emailHeaderMaxLength)\n : parsedEmail.canonicalized_header;\n console.log(\"header: \", header);\n\n const output = await Promise.all(\n blueprint.decomposedRegexes.map((dcr: DecomposedRegex) =>\n testDecomposedRegex(body, header, dcr, revealPrivate)\n )\n );\n console.log(\"output: \", output);\n\n return output;\n}\n\nexport async function testDecomposedRegex(\n body: string,\n header: string,\n decomposedRegex: DecomposedRegex | DecomposedRegexJson,\n revealPrivate = false\n): Promise<string[]> {\n console.log(\"testDecomposedRegex: \", decomposedRegex);\n const inputDecomposedRegex = {\n parts: decomposedRegex.parts.map((p: DecomposedRegexPart | DecomposedRegexPartJson) => ({\n is_public: \"isPublic\" in p ? p.isPublic : p.is_public,\n regex_def: \"regexDef\" in p ? p.regexDef : p.regex_def,\n })),\n };\n console.log(\"inputDecomposedRegex: \", inputDecomposedRegex);\n\n let inputStr: string;\n if (decomposedRegex.location === \"body\") {\n inputStr = body;\n } else if (decomposedRegex.location === \"header\") {\n inputStr = header;\n } else {\n throw Error(`Unsupported location ${decomposedRegex.location}`);\n }\n\n console.log(\"inputstr: \", inputStr);\n\n const maxLength =\n \"maxLength\" in decomposedRegex ? decomposedRegex.maxLength : decomposedRegex.max_length;\n console.log(\"maxLength: \", maxLength);\n\n const utils = await relayerUtils;\n const privateResult = utils.extractSubstr(inputStr, inputDecomposedRegex, false);\n console.log(\"privateResult: \", privateResult);\n\n if (privateResult[0].length > maxLength) {\n throw new Error(\n `Max length of extracted result was exceeded for decomposed regex ${decomposedRegex.name}`\n );\n }\n\n if (!revealPrivate) {\n return privateResult;\n }\n\n const result = utils.extractSubstr(inputStr, inputDecomposedRegex, revealPrivate);\n console.log(\"result: \", result);\n return result;\n}\n\nexport async function generateProofInputs(\n eml: string,\n decomposedRegexes: DecomposedRegex[],\n externalInputs: ExternalInput[],\n params: GenerateProofInputsParams\n): Promise<string> {\n try {\n const internalParams: GenerateProofInputsParamsInternal = {\n maxHeaderLength: params.emailHeaderMaxLength,\n maxBodyLength: params.emailBodyMaxLength,\n ignoreBodyHashCheck: params.ignoreBodyHashCheck,\n removeSoftLinesBreaks: params.removeSoftLinebreaks,\n shaPrecomputeSelector: params.shaPrecomputeSelector,\n };\n\n const utils = await relayerUtils;\n // console.log(\"got relayer utils\");\n // console.log(\"actually creating proof inputs with params: \", internalParams);\n\n const decomposedRegexesCleaned = decomposedRegexes.map((dcr) => {\n return {\n ...dcr,\n parts: dcr.parts.map((p) => ({\n // @ts-ignore\n is_public: p.isPublic || !!p.is_public,\n // @ts-ignore\n regex_def: p.regexDef || !!p.regex_def,\n })),\n };\n });\n\n console.log(\"calling generateCircuitInputsWithDecomposedRegexesAndExternalInputs with\");\n console.log(\"eml: \", eml);\n console.log(\"decomposedRegex: \", decomposedRegexesCleaned);\n console.log(\"externalInputs: \", externalInputs);\n console.log(\"params: \", params);\n\n const inputs = await utils.generateCircuitInputsWithDecomposedRegexesAndExternalInputs(\n eml,\n decomposedRegexesCleaned,\n externalInputs,\n internalParams\n );\n\n return JSON.stringify(Object.fromEntries(inputs));\n } catch (err) {\n console.error(\"Failed to generate inputs for proof\");\n throw err;\n }\n}\n\nexport function startJsonFileDownload(json: string, name = \"data\") {\n if (!window && !document) {\n throw Error(\"startFilesDownload can only be used in a browser\");\n }\n\n const blob = new Blob([json], { type: \"application/json\" });\n const url = URL.createObjectURL(blob);\n\n const link = document.createElement(\"a\");\n link.href = url;\n link.download = `${name}.json`;\n document.body.appendChild(link);\n link.click();\n document.body.removeChild(link);\n URL.revokeObjectURL(url);\n}\n","import { Blueprint, Status } from \"./blueprint\";\nimport { ProofProps, ProofResponse, ProofStatus } from \"./types/proof\";\nimport { get } from \"./utils\";\n\n/**\n * A generated proof. You get get proof data and verify proofs on chain.\n */\nexport class Proof {\n blueprint: Blueprint;\n props: ProofProps;\n private lastCheckedStatus: Date | null = null;\n\n constructor(blueprint: Blueprint, props: ProofProps) {\n if (!(blueprint instanceof Blueprint)) {\n throw new Error(\"Invalid blueprint: must be an instance of Blueprint class\");\n }\n this.blueprint = blueprint;\n\n if (!props?.id) {\n throw new Error(\"A proof must have an id\");\n }\n\n this.props = {\n status: ProofStatus.InProgress,\n ...props,\n };\n }\n\n getId(): string {\n return this.props.id;\n }\n\n /**\n * Returns a download link for the files of the proof.\n * @returns The the url to download a zip of the proof files.\n */\n async getProofDataDownloadLink(): Promise<string> {\n if (this.props.status !== ProofStatus.Done) {\n throw new Error(\"The proving is not done yet.\");\n }\n\n let response: { url: string };\n try {\n response = await get<{ url: string }>(\n `${this.blueprint.baseUrl}/proof/files/${this.props.id}`\n );\n } catch (err) {\n console.error(\"Failed calling GET on /proof/files/:id in getProofDataDownloadLink: \", err);\n throw err;\n }\n\n return response.url;\n }\n\n async startFilesDownload() {\n if (!window && !document) {\n throw Error(\"startFilesDownload can only be used in a browser\");\n }\n\n let url: string;\n try {\n url = await this.getProofDataDownloadLink();\n } catch (err) {\n console.error(\"Failed to start download of ZKeys: \", err);\n throw err;\n }\n\n const link = document.createElement(\"a\");\n link.href = url;\n link.download = \"proof_files.zip\"; // Set the desired filename\n document.body.appendChild(link);\n link.click();\n document.body.removeChild(link);\n }\n\n /**\n * Checks the status of proof.\n * checkStatus can be used in a while(await checkStatus()) loop, since it will wait a fixed\n * amount of time before the second time you call it.\n * @returns A promise with the Status.\n */\n async checkStatus(): Promise<ProofStatus> {\n if (this.props.status === ProofStatus.Done) {\n return this.props.status;\n }\n\n // Waits for a fixed period of time before you can call checkStatus again\n // This enables you to put checkStatus in a while(await checkStatu()) loop\n if (!this.lastCheckedStatus) {\n this.lastCheckedStatus = new Date();\n } else {\n const waitTime = 500;\n const sinceLastChecked = new Date().getTime() - this.lastCheckedStatus.getTime();\n if (sinceLastChecked < waitTime) {\n await new Promise((r) => setTimeout(r, waitTime - sinceLastChecked));\n }\n }\n\n // Check status\n let response: { status: ProofStatus };\n try {\n response = await get<{ status: ProofStatus }>(\n `${this.blueprint.baseUrl}/proof/status/${this.props.id}`\n );\n } catch (err) {\n console.error(\"Failed calling GET /blueprint/status in getStatus(): \", err);\n throw err;\n }\n\n this.props.status = response.status;\n return response.status;\n }\n\n async verifyOnChain() {}\n\n /**\n * Fetches an existing Proof from the database.\n * @param id - Id of the Proof.\n * @returns A promise that resolves to a new instance of Proof.\n */\n public static async getPoofById(id: string, baseUrl: string): Promise<Proof> {\n let proofResponse: ProofResponse;\n try {\n proofResponse = await get<ProofResponse>(`${baseUrl}/proof/${id}`);\n } catch (err) {\n console.error(\"Failed calling /proof/:id in getProofById: \", err);\n throw err;\n }\n\n const proofProps = this.responseToProofProps(proofResponse);\n const blueprint = await Blueprint.getBlueprintById(proofResponse.blueprint_id, baseUrl);\n\n return new Proof(blueprint, proofProps);\n }\n\n public static responseToProofProps(response: ProofResponse): ProofProps {\n const props: ProofProps = {\n id: response.id,\n blueprintId: response.blueprint_id,\n status: response.status as ProofStatus,\n input: response.input,\n proof: response.proof,\n public: response.public,\n startedAt: new Date(response.started_at.seconds * 1000),\n provedAt: response.proved_at ? new Date(response.proved_at.seconds * 1000) : undefined,\n };\n return props;\n }\n}\n","import { Blueprint } from \"./blueprint\";\nimport { Proof } from \"./proof\";\nimport {\n GenerateProofInputsParams,\n ProofProps,\n ProofRequest,\n ProofResponse,\n ProofStatus,\n} from \"./types/proof\";\nimport { ProverOptions } from \"./types/prover\";\nimport { generateProofInputs, post } from \"./utils\";\n\n/**\n * Represents a Prover generated from a blueprint that can generate Proofs\n */\nexport class Prover {\n options: ProverOptions;\n blueprint: Blueprint;\n\n constructor(blueprint: Blueprint, options?: ProverOptions) {\n if (options?.isLocal === true) {\n throw new Error(\"Local proving is not supported yet\");\n }\n\n if (!(blueprint instanceof Blueprint)) {\n throw new Error(\"Invalid blueprint: must be an instance of Blueprint class\");\n }\n\n this.blueprint = blueprint;\n\n // Use defaults for unset fields\n this.options = {\n isLocal: false,\n ...(!!options ? options : {}),\n };\n }\n\n // TODO: Add parsed email input\n /**\n * Generates a proof for a given email.\n * @param eml - Email to prove agains the blueprint of this Prover.\n * @returns A promise that resolves to a new instance of Proof. The Proof will have the status\n * Done or Failed.\n */\n async generateProof(eml: string): Promise<Proof> {\n console.log(\"starting generate proof\");\n const proof = await this.generateProofRequest(eml);\n console.log(\"got proof: \", proof);\n\n // Wait for proof to finish\n while (![ProofStatus.Done, ProofStatus.Failed].includes(await proof.checkStatus())) {}\n return proof;\n }\n\n // TODO: Add parsed email input\n /**\n * Starts proving for a given email.\n * @param eml - Email to prove agains the blueprint of this Prover.\n * @returns A promise that resolves to a new instance of Proof. The Proof will have the status\n * InProgress.\n */\n async generateProofRequest(eml: string): Promise<Proof> {\n const blueprintId = this.blueprint.getId();\n if (!blueprintId) {\n throw new Error(\"Blueprint of Proover must be initialized in order to create a Proof\");\n }\n\n let input: string;\n try {\n // TODO: Do we use defaults?\n const params: GenerateProofInputsParams = {\n emailHeaderMaxLength: this.blueprint.props.emailHeaderMaxLength || 256,\n emailBodyMaxLength: this.blueprint.props.emailBodyMaxLength || 2560,\n ignoreBodyHashCheck: this.blueprint.props.ignoreBodyHashCheck || false,\n removeSoftLinebreaks: this.blueprint.props.removeSoftLinebreaks || true,\n shaPrecomputeSelector: this.blueprint.props.shaPrecomputeSelector,\n };\n console.log(\"generating proof inputs\");\n input = await generateProofInputs(\n eml,\n this.blueprint.props.decomposedRegexes,\n this.blueprint.props.externalInputs || [],\n params\n );\n } catch (err) {\n console.error(\"Failed to generate inputs for proof\");\n throw err;\n }\n\n console.log(\"got proof input\");\n let response: ProofResponse;\n try {\n const requestData: ProofRequest = {\n blueprint_id: blueprintId,\n input,\n };\n\n response = await post<ProofResponse>(`${this.blueprint.baseUrl}/proof`, requestData);\n } catch (err) {\n console.error(\"Failed calling POST on /proof/ in generateProofRequest: \", err);\n throw err;\n }\n\n const proofProps = Proof.responseToProofProps(response);\n return new Proof(this.blueprint, proofProps);\n }\n}\n","export type BlueprintProps = {\n id?: string;\n title: string;\n description?: string;\n slug?: string;\n tags?: string[];\n emailQuery?: string;\n circuitName: string;\n ignoreBodyHashCheck?: boolean;\n shaPrecomputeSelector?: string;\n emailBodyMaxLength?: number;\n emailHeaderMaxLength?: number;\n removeSoftLinebreaks?: boolean;\n githubUsername?: string;\n senderDomain?: string;\n enableHeaderMasking?: boolean;\n enableBodyMasking?: boolean;\n zkFramework?: ZkFramework;\n isPublic?: boolean;\n createdAt?: Date;\n updatedAt?: Date;\n externalInputs?: ExternalInput[];\n decomposedRegexes: DecomposedRegex[];\n status?: Status;\n verifierContract?: VerifierContract;\n version?: number;\n};\n\nexport type DecomposedRegex = {\n parts: DecomposedRegexPart[];\n name: string;\n maxLength: number;\n location: \"body\" | \"header\";\n};\n\nexport type DecomposedRegexPart = {\n isPublic: boolean;\n regexDef: string;\n};\n\nexport type DecomposedRegexJson = {\n parts: DecomposedRegexPartJson[];\n name: string;\n max_length: number;\n location: \"body\" | \"header\";\n};\n\nexport type DecomposedRegexPartJson = {\n is_public: boolean;\n regex_def: string;\n};\n\nexport type ExternalInput = {\n name: string;\n maxLength: number;\n};\n\nexport enum ZkFramework {\n Circom = \"circom\",\n}\n\n// According to protobufs\nexport enum Status {\n None,\n Draft,\n InProgress,\n Done,\n Failed,\n}\n\nexport type VerifierContract = {\n address?: string;\n chain: number;\n};\n\nexport type BlueprintRequest = {\n id?: string;\n title: string;\n description?: string;\n slug?: string;\n tags?: string[];\n email_query?: string;\n circuit_name?: string;\n ignore_body_hash_check?: boolean;\n sha_precompute_selector?: string;\n email_body_max_length?: number;\n email_header_max_length?: number;\n remove_soft_linebreaks?: boolean;\n // TODO: Make non ? after login with github\n github_username?: string;\n sender_domain?: string;\n enable_header_masking?: boolean;\n enable_body_masking?: boolean;\n zk_framework?: string;\n is_public?: boolean;\n external_inputs?: ExternalInputResponse[];\n decomposed_regexes: DecomposedRegexResponse[];\n status?: string;\n verifier_contract_address?: string;\n verifier_contract_chain?: number;\n version?: number;\n};\n\nexport type BlueprintResponse = {\n id: string;\n title: string;\n description: string;\n slug: string;\n tags: string[];\n email_query: string;\n circuit_name: string;\n ignore_body_hash_check: boolean;\n sha_precompute_selector: string;\n email_body_max_length: number;\n email_header_max_length?: number;\n remove_soft_linebreaks?: boolean;\n github_username?: string;\n sender_domain: string;\n enable_header_masking?: boolean;\n enable_body_masking?: boolean;\n zk_framework: string;\n is_public: boolean;\n created_at: ServerDate;\n updated_at: ServerDate;\n external_inputs: ExternalInputResponse[];\n decomposed_regexes: DecomposedRegexResponse[];\n status: number;\n verifier_contract_address: string;\n verifier_contract_chain: number;\n version: number;\n};\n\nexport type ServerDate = {\n seconds: number;\n nanos: number;\n};\n\nexport type ExternalInputResponse = {\n name: string;\n max_length: number;\n};\n\nexport type DecomposedRegexResponse = {\n parts: DecomposedRegexPartResponse[];\n name: string;\n max_length: number;\n location: \"body\" | \"header\";\n};\n\nexport type DecomposedRegexPartResponse = {\n is_public: boolean;\n regex_def: string;\n};\n\nexport type ListBlueprintsOptions = {\n skip?: number;\n limit?: number;\n sort?: -1 | 1;\n status?: Status[];\n isPublic?: boolean;\n search?: string;\n};\n\nexport type ListBlueprintsOptionsRequest = {\n skip?: number;\n limit?: number;\n sort?: -1 | 1;\n status?: Status[];\n is_public?: boolean;\n search?: string;\n};\n\nexport type DownloadUrls = Record<string, string>;\n","import { createPublicClient, http } from \"viem\";\nimport { baseSepolia } from \"viem/chains\";\n\nconst WETHContractAddress = \"0x4200000000000000000000000000000000000006\";\n\nconst WETHContractABI = [\n {\n constant: true,\n inputs: [],\n name: \"totalSupply\",\n outputs: [{ name: \"\", type: \"uint256\" }],\n type: \"function\",\n },\n] as const;\n\nconst client = createPublicClient({\n chain: baseSepolia,\n transport: http(),\n});\n\nexport async function verifyProofOnChain() {\n try {\n const totalSupply = await client.readContract({\n address: WETHContractAddress,\n abi: WETHContractABI,\n functionName: \"totalSupply\",\n });\n\n return totalSupply;\n } catch (error) {\n console.error(\"Error fetching WETH total supply:\", error);\n throw error;\n }\n}\n","import { Proof } from \"viem/_types/types/proof\";\nimport { Prover } from \"./prover\";\nimport {\n BlueprintProps,\n BlueprintRequest,\n BlueprintResponse,\n DownloadUrls,\n ListBlueprintsOptions,\n ListBlueprintsOptionsRequest,\n Status,\n ZkFramework,\n} from \"./types/blueprint\";\nimport { get, patch, post } from \"./utils\";\nimport { verifyProofOnChain } from \"./chain\";\nimport { Auth } from \"./types/auth\";\n\n/**\n * Represents a Regex Blueprint including the decomposed regex access to the circuit.\n */\nexport class Blueprint {\n // TODO: Implement getter and setter pattern\n props: BlueprintProps;\n auth?: Auth;\n baseUrl: string;\n\n private lastCheckedStatus: Date | null = null;\n\n constructor(props: BlueprintProps, baseUrl: string, auth?: Auth) {\n // Use defaults for unset fields\n this.props = {\n ignoreBodyHashCheck: false,\n enableHeaderMasking: false,\n enableBodyMasking: false,\n isPublic: true,\n status: Status.Draft,\n ...props,\n };\n\n this.baseUrl = baseUrl;\n this.auth = auth;\n }\n\n addAuth(auth: Auth) {\n this.auth = auth;\n }\n\n /**\n * Fetches an existing RegexBlueprint from the database.\n * @param {string} id - Id of the RegexBlueprint.\n * @returns A promise that resolves to a new instance of RegexBlueprint.\n */\n public static async getBlueprintById(\n id: string,\n baseUrl: string,\n auth?: Auth\n ): Promise<Blueprint> {\n let blueprintResponse: BlueprintResponse;\n try {\n blueprintResponse = await get<BlueprintResponse>(`${baseUrl}/blueprint/${id}`);\n } catch (err) {\n console.error(\"Failed calling /blueprint/:id in getBlueprintById: \", err);\n throw err;\n }\n\n const blueprintProps = this.responseToBlueprintProps(blueprintResponse);\n\n const blueprint = new Blueprint(blueprintProps, baseUrl, auth);\n\n return blueprint;\n }\n\n // Maps the blueprint API response to the BlueprintProps\n private static responseToBlueprintProps(response: BlueprintResponse): BlueprintProps {\n const props: BlueprintProps = {\n id: response.id,\n title: response.title,\n description: response.description,\n slug: response.slug,\n tags: response.tags,\n emailQuery: response.email_query,\n circuitName: response.circuit_name,\n ignoreBodyHashCheck: response.ignore_body_hash_check,\n shaPrecomputeSelector: response.sha_precompute_selector,\n emailBodyMaxLength: response.email_body_max_length,\n emailHeaderMaxLength: response.email_header_max_length,\n removeSoftLinebreaks: response.remove_soft_linebreaks,\n githubUsername: response.github_username,\n senderDomain: response.sender_domain,\n enableHeaderMasking: response.enable_header_masking,\n enableBodyMasking: response.enable_body_masking,\n zkFramework: response.zk_framework as ZkFramework,\n isPublic: response.is_public,\n createdAt: new Date(response.created_at.seconds * 1000),\n updatedAt: new Date(response.updated_at.seconds * 1000),\n externalInputs: response.external_inputs?.map((input) => ({\n name: input.name,\n maxLength: input.max_length,\n })),\n decomposedRegexes: response.decomposed_regexes?.map((regex) => ({\n parts: regex.parts.map((part) => ({\n isPublic: part.is_public,\n regexDef: part.regex_def,\n })),\n name: regex.name,\n maxLength: regex.max_length,\n location: regex.location,\n })),\n status: response.status as Status,\n verifierContract: {\n address: response.verifier_contract_address,\n chain: response.verifier_contract_chain,\n },\n version: response.version,\n };\n\n return props;\n }\n\n // Maps the BlueprintProps to the BlueprintResponse\n private static blueprintPropsToRequest(props: BlueprintProps): BlueprintRequest {\n const response: BlueprintRequest = {\n id: props.id,\n title: props.title,\n description: props.description,\n slug: props.slug,\n tags: props.tags,\n email_query: props.emailQuery,\n circuit_name: props.circuitName,\n ignore_body_hash_check: props.ignoreBodyHashCheck,\n sha_precompute_selector: props.shaPrecomputeSelector,\n email_body_max_length: props.emailBodyMaxLength,\n email_header_max_length: props.emailHeaderMaxLength,\n remove_soft_linebreaks: props.removeSoftLinebreaks,\n github_username: props.githubUsername,\n sender_domain: props.senderDomain,\n enable_header_masking: props.enableHeaderMasking,\n enable_body_masking: props.enableBodyMasking,\n zk_framework: props.zkFramework,\n is_public: props.isPublic,\n external_inputs: props.externalInputs?.map((input) => ({\n name: input.name,\n max_length: input.maxLength,\n })),\n decomposed_regexes: props.decomposedRegexes?.map((regex) => ({\n parts: regex.parts.map((part) => ({\n // @ts-ignore\n is_public: part.isPublic || part.is_public,\n // @ts-ignore\n regex_def: part.regexDef || part.regex_def,\n })),\n name: regex.name,\n max_length: regex.maxLength,\n location: regex.location,\n })),\n verifier_contract_address: props.verifierContract?.address,\n verifier_contract_chain: props.verifierContract?.chain,\n };\n\n return response;\n }\n\n /**\n * Submits a new RegexBlueprint to the registry as draft.\n * This does not compile the circuits yet and you will still be able to make changes.\n * @returns A promise. Once it resolves, `getId` can be called.\n */\n public async submitDraft() {\n if (!this.auth) {\n throw new Error(\"auth is required, add it with Blueprint.addAuth(auth)\");\n }\n\n if (this.props.id) {\n throw new Error(\"Blueprint was already saved\");\n }\n\n const requestData = Blueprint.blueprintPropsToRequest(this.props);\n\n let response: BlueprintResponse;\n try {\n response = await post<BlueprintResponse>(`${this.baseUrl}/blueprint`, requestData, this.auth);\n } catch (err) {\n console.error(\"Failed calling POST on /blueprint/ in submitDraft: \", err);\n throw err;\n }\n\n this.props = Blueprint.responseToBlueprintProps(response);\n }\n\n /**\n * Submits a new version of the RegexBlueprint to the registry as draft.\n * This does not compile the circuits yet and you will still be able to make changes.\n * @param newProps - The updated blueprint props.\n * @returns A promise. Once it resolves, the current Blueprint will be replaced with the new one.\n */\n public async submitNewVersionDraft(newProps: BlueprintProps) {\n if (!this.auth) {\n throw new Error(\"auth is required, add it with Blueprint.addAuth(auth)\");\n }\n\n const requestData = Blueprint.blueprintPropsToRequest(newProps);\n\n let response: BlueprintResponse;\n try {\n response = await post<BlueprintResponse>(`${this.baseUrl}/blueprint`, requestData, this.auth);\n } catch (err) {\n console.error(\"Failed calling POST on /blueprint/ in submitDraft: \", err);\n throw err;\n }\n\n this.props = Blueprint.responseToBlueprintProps(response);\n }\n\n /**\n * Submits a new version of the blueprint. This will save the new blueprint version\n * and start the compilation.\n * This will also overwrite the current Blueprint with its new version, even if the last\n * version was not compiled yet.\n * @param newProps - The updated blueprint props.\n */\n async submitNewVersion(newProps: BlueprintProps) {\n if (!this.auth) {\n throw new Error(\"auth is required, add it with Blueprint.addAuth(auth)\");\n }\n\n await this.submitNewVersionDraft(newProps);\n\n // We don't check the status here, since we are compiling directly after submiting the draft.\n\n // Submit compile request\n try {\n await post<{ status: Status }>(\n `${this.baseUrl}/blueprint/compile/${this.props.id}`,\n null,\n this.auth\n );\n } catch (err) {\n // We don't set the status here, since the api call can't fail due to the actual job failing\n // It can only due to connectivity issues or the job runner not being available\n console.error(\"Failed calling POST on /blueprint/compile in submit: \", err);\n throw err;\n }\n }\n\n /**\n * Lists blueblueprints, only including the latest version per unique slug.\n * @param options - Options to filter the blueprints by.\n * @returns A promise. Once it resolves, `getId` can be called.\n */\n public static async listBlueprints(\n baseUrl: string,\n options?: ListBlueprintsOptions,\n auth?: Auth\n ): Promise<Blueprint[]> {\n const requestOptions: ListBlueprintsOptionsRequest = {\n skip: options?.skip,\n limit: options?.limit,\n sort: options?.sort,\n status: options?.status,\n is_public: options?.isPublic,\n search: options?.search,\n };\n\n let response: { blueprints?: BlueprintResponse[] };\n try {\n response = await get<{ blueprints?: BlueprintResponse[] }>(\n `${baseUrl}/blueprint`,\n requestOptions\n );\n } catch (err) {\n console.error(\"Failed calling POST on /blueprint/ in submitDraft: \", err);\n throw err;\n }\n\n if (!response.blueprints) {\n return [];\n }\n\n return response.blueprints.map((blueprintResponse) => {\n const blueprintProps = Blueprint.responseToBlueprintProps(blueprintResponse);\n return new Blueprint(blueprintProps, baseUrl, auth);\n });\n }\n\n /**\n * Submits a blueprint. This will save the blueprint if it didn't exist before\n * and start the compilation.\n */\n async submit() {\n if (!this.auth) {\n throw new Error(\"auth is required, add it with Blueprint.addAuth(auth)\");\n }\n\n // If the blueprint wasn't save yet, we save it first to db\n if (!this.props.id) {\n try {\n await this.submitDraft();\n } catch (err) {\n console.error(\"Failed to create blueprint: \", err);\n throw err;\n }\n }\n\n const status = await this._checkStatus();\n\n // TODO: Should we allow retry on failed?\n if (Status.Done === status) {\n throw new Error(\"The circuits are already compiled.\");\n }\n if (Status.InProgress === status) {\n throw new Error(\"The circuits already being compiled, please wait.\");\n }\n\n // Submit compile request\n try {\n await post<{ status: Status }>(\n `${this.baseUrl}/blueprint/compile/${this.props.id}`,\n null,\n this.auth\n );\n } catch (err) {\n // We don't set the status here, since the api call can't fail due to the actual job failing\n // It can only due to connectivity issues or the job runner not being available\n console.error(\"Failed calling POST on /blueprint/compile in submit: \", err);\n throw err;\n }\n }\n\n // Request status from server and updates props.status\n private async _checkStatus(): Promise<Status> {\n let response: { status: Status };\n try {\n response = await get<{ status: Status }>(`${this.baseUrl}/blueprint/status/${this.props.id}`);\n } catch (err) {\n console.error(\"Failed calling GET /blueprint/status in getStatus(): \", err);\n throw err;\n }\n\n this.props.status = response.status;\n return response.status;\n }\n\n /**\n * Checks the status of blueprint.\n * checkStatus can be used in a while(await checkStatus()) loop, since it will wait a fixed\n * amount of time the second time you call it.\n * @returns A promise with the Status.\n */\n async checkStatus(): Promise<Status> {\n // Blueprint wasn't saved yet, return default status\n if (!this.props.id) {\n return this.props.status!;\n }\n\n if ([Status.Failed, Status.Done].includes(this.props.status!)) {\n return this.props.status!;\n }\n\n // Waits for a fixed period of time before you can call checkStatus again\n // This enables you to put checkStatus in a while(await checkStatus()) loop\n if (!this.lastCheckedStatus) {\n this.lastCheckedStatus = new Date();\n } else {\n // TODO: change for prod to one minute\n const waitTime = 0.5 * 1_000; // TODO: should be one minute;\n const sinceLastChecked = new Date().getTime() - this.lastCheckedStatus.getTime();\n if (sinceLastChecked < waitTime) {\n await new Promise((r) => setTimeout(r, waitTime - sinceLastChecked));\n }\n }\n\n const status = await this._checkStatus();\n\n return status;\n }\n\n /**\n * Get the id of the blueprint.\n * @returns The id of the blueprint. If it was not saved yet, return null.\n */\n getId(): string | null {\n return this.props.id || null;\n }\n\n /**\n * Returns a download link for the ZKeys of the blueprint.\n * @returns The the url to download the ZKeys.\n */\n async getZKeyDownloadLink(): Promise<DownloadUrls> {\n if (this.props.status !== Status.Done) {\n throw new Error(\"The circuits are not compiled yet, nothing to download.\");\n }\n\n let response: { urls: DownloadUrls };\n try {\n response = await get<{ urls: DownloadUrls }>(\n `${this.baseUrl}/blueprint/zkey/${this.props.id}`\n );\n console.log(\"response: \", response);\n } catch (err) {\n console.error(\"Failed calling GET on /blueprint/zkey/:id in getZKeyDownloadLink: \", err);\n throw err;\n }\n\n return response.urls;\n }\n\n /**\n * Directly starts a download of the ZKeys in the browser.\n * Must be called within a user action, like a button click.\n */\n async startZKeyDownload() {\n if (!window && !document) {\n throw Error(\"startZKeyDownload can only be used in a browser\");\n }\n\n let urls: DownloadUrls;\n try {\n urls = await this.getZKeyDownloadLink();\n } catch (err) {\n console.error(\"Failed to start download of ZKeys: \", err);\n throw err;\n }\n\n for (const [name, url] of Object.entries(urls)) {\n const link = document.createElement(\"a\");\n link.href = url;\n link.download = name; // Set the desired filename\n document.body.appendChild(link);\n link.click();\n document.body.removeChild(link);\n }\n }\n\n /**\n * Creates an instance of Prover with which you can create proofs.\n * @returns An instance of Prover.\n */\n createProver() {\n return new Prover(this);\n }\n\n /**\n * Verifies a proof on chain.\n * @param proof - The generated proof you want to verify.\n * @returns A true if the verification was successfull, false if it failed.\n */\n async verifyProofOnChain(proof: Proof): Promise<boolean> {\n try {\n const result = await verifyProofOnChain();\n } catch (err) {\n console.error(\"Failed to verify proof on chain: \", err);\n return false;\n }\n return true;\n }\n\n /**\n * Returns a deep cloned version of the Blueprints props.\n * This can be used to update properties and then to use them with createNewVersion.\n * @param proof - The generated proof you want to verify.\n * @returns A true if the verification was successfull, false if it failed.\n */\n getClonedProps(): BlueprintProps {\n const cloned = JSON.parse(JSON.stringify(this.props));\n\n // Conver date strings\n if (cloned.createdAt) {\n cloned.createdAt = new Date(cloned.createdAt);\n }\n if (cloned.updatedAt) {\n cloned.updatedAt = new Date(cloned.updatedAt);\n }\n\n return cloned;\n }\n\n /**\n * Returns true if the blueprint can be updated. A blueprint can be updated if the circuits\n * haven't beed compiled yet, i.e. the status is not Done. The blueprint also must be saved\n * already before it can be updated.\n * @returns true if it can be updated\n */\n canUpdate(): boolean {\n return !!(this.props.id && ![Status.Done, Status.InProgress].includes(this.props.status!));\n }\n\n /**\n * Updates an existing blueprint that is not compiled yet.\n * @param newProps - The props the blueprint should be updated to.\n * @returns a promise.\n */\n async update(newProps: BlueprintProps) {\n if (!this.auth) {\n throw new Error(\"auth is required, add it with Blueprint.addAuth(auth)\");\n }\n\n if (!this.canUpdate()) {\n throw new Error(\"Blueprint already compied, cannot update\");\n }\n\n const requestData = Blueprint.blueprintPropsToRequest(newProps);\n\n let response: BlueprintResponse;\n try {\n response = await patch<BlueprintResponse>(\n `${this.baseUrl}/blueprint/${this.props.id}`,\n requestData,\n this.auth\n );\n } catch (err) {\n console.error(\"Failed calling POST on /blueprint/ in submitDraft: \", err);\n throw err;\n }\n\n this.props = Blueprint.responseToBlueprintProps(response);\n }\n\n async listAllVersions(): Promise<Blueprint[]> {\n if (!this.props.id) {\n throw new Error(\"Blueprint was not saved yet\");\n }\n let response: { blueprints: BlueprintResponse[] };\n try {\n response = await get<{ blueprints: BlueprintResponse[] }>(\n `${this.baseUrl}/blueprint/versions/${encodeURIComponent(this.props.slug!)}`\n );\n } catch (err) {\n console.error(\"Failed calling GET on /blueprint/versions/:slug in listAllVersions: \", err);\n throw err;\n }\n\n return response.blueprints.map((blueprintResponse) => {\n const blueprintProps = Blueprint.responseToBlueprintProps(blueprintResponse);\n return new Blueprint(blueprintProps, this.baseUrl, this.auth);\n });\n }\n}\n\n// export {\n// BlueprintProps,\n// DecomposedRegex,\n// DecomposedRegexPart,\n// ExternalInput,\n// ZkFramework,\n// Status,\n// VerifierContract,\n// RevealHeaderFields,\n// } from \"./types/blueprint\";\n\nexport * from \"./types/blueprint\";\n","import { Blueprint, BlueprintProps, ListBlueprintsOptions } from \"./blueprint\";\nimport { Proof } from \"./proof\";\nimport { SdkOptions } from \"./types/sdk\";\n\n// Export Types\nexport * from \"./types/blueprint\";\nexport { Blueprint } from \"./blueprint\";\nexport * from \"./types/proof\";\nexport { Proof } from \"./proof\";\nexport type { Auth } from \"./types/auth\";\n\n// Exports that don't need initialization or options\nexport {\n testDecomposedRegex,\n parseEmail,\n startJsonFileDownload,\n generateProofInputs,\n testBlueprint,\n} from \"./utils\";\nexport { getLoginWithGithubUrl } from \"./auth\";\n\n// Exported sdk, functions that need initialization\nexport default (sdkOptions?: SdkOptions) => {\n const baseUrl = sdkOptions?.baseUrl || \"https://conductor.zk.email\";\n return {\n createBlueprint(props: BlueprintProps) {\n if (!sdkOptions && !sdkOptions!.auth) {\n throw new Error(\"You need to specify options.auth to use createBlueprint\");\n }\n const blueprint = new Blueprint(props, baseUrl, sdkOptions!.auth);\n return blueprint;\n },\n async getBlueprint(id: string): Promise<Blueprint> {\n return Blueprint.getBlueprintById(id, baseUrl, sdkOptions?.auth);\n },\n async listBlueprints(options?: ListBlueprintsOptions): Promise<Blueprint[]> {\n return Blueprint.listBlueprints(baseUrl, options, sdkOptions?.auth);\n },\n async getProof(id: string): Promise<Proof> {\n return Proof.getPoofById(id, baseUrl);\n },\n };\n};\n"]}
|