(()=>{var a={};a.id=8433,a.ids=[8433],a.modules={261:a=>{"use strict";a.exports=require("next/dist/shared/lib/router/utils/app-paths")},3295:a=>{"use strict";a.exports=require("next/dist/server/app-render/after-task-async-storage.external.js")},8578:(a,b,c)=>{"use strict";let d=c(33873),e=c(29021),f=c(15296),{execFileSync:g}=c(79646),{MITM_DIR:h}=c(82193),i=d.join(h,"rootCA.key"),j=d.join(h,"rootCA.crt"),k=d.join(h,"rootCA.csr"),l=d.join(h,"rootCA.csr.cnf"),m=d.join(h,"rootCA.pending.key"),n=d.join(h,"backup");function o(){e.existsSync(h)||e.mkdirSync(h,{recursive:!0})}function p(a,b){let c=String(a||"").trim();if(!c)throw Error(`${b} is empty`);return`${c}
`}function q(a){return f.md.sha256.create().update(f.pki.publicKeyToPem(a),"utf8").digest().toHex()}function r(a){let b=a.getExtension("basicConstraints"),c=a.getExtension("keyUsage");return!!b?.cA&&(!c||!0===c.keyCertSign)}function s(a,b){if(q(a.publicKey)!==q(function(a){if(!a?.n||!a?.e)throw Error("Only RSA private keys are supported for MITM Root CA");return f.pki.setRsaPublicKey(a.n,a.e)}(b)))throw Error("Certificate public key does not match private key")}function t(){o();let a=e.existsSync(i),b=e.existsSync(j);if(!a&&!b)return null;e.mkdirSync(n,{recursive:!0});let c=new Date().toISOString().replace(/[:.]/g,"-"),f={key:d.join(n,`rootCA.${c}.key`),cert:d.join(n,`rootCA.${c}.crt`)};return a&&e.copyFileSync(i,f.key),b&&e.copyFileSync(j,f.cert),f}function u(a,b="Certificate"){try{return f.pki.certificateFromPem(p(a,b))}catch(a){throw Error(`${b} is not a valid PEM certificate: ${a.message}`)}}function v(a,b="Private key"){try{return f.pki.privateKeyFromPem(p(a,b))}catch(a){throw Error(`${b} is not a valid PEM private key: ${a.message}`)}}function w(a){try{let b=f.pki.certificateFromPem(e.readFileSync(a,"utf8")),c=new Date(Date.now()+2592e6);return b.validity.notAfter<c}catch{return!0}}function x(){let a=e.existsSync(j),b=e.existsSync(i),c={certExists:a,keyExists:b,csrExists:e.existsSync(k),pendingKeyExists:e.existsSync(m),certPath:j,keyPath:i,csrPath:k,pendingKeyPath:m};if(!a)return c;try{let a=u(e.readFileSync(j,"utf8")),b=a.subject.attributes.map(a=>`${a.shortName||a.name}=${a.value}`).join(", "),d=a.issuer.attributes.map(a=>`${a.shortName||a.name}=${a.value}`).join(", ");c.subject=b,c.issuer=d,c.serialNumber=a.serialNumber,c.notBefore=a.validity.notBefore.toISOString(),c.notAfter=a.validity.notAfter.toISOString(),c.expiredOrExpiringSoon=w(j),c.isCa=r(a),c.isSelfSigned=b===d,c.fingerprint=q(a.publicKey)}catch(a){c.error=a.message}return c}function y(a,b){return String(a||b||"").replace(/[\r\n]+/g," ").replace(/[\\]/g,"\\\\").trim()||String(b||"")}a.exports={generateRootCA:async function a(){let a=e.existsSync(i)&&e.existsSync(j);if(a&&!w(j))return console.log("✅ Root CA already exists"),{key:i,cert:j};if(a){console.log("\uD83D\uDD10 Root CA expired or expiring soon — regenerating...");try{e.unlinkSync(i)}catch{}try{e.unlinkSync(j)}catch{}}o(),console.log("\uD83D\uDD10 Generating Root CA certificate...");let b=f.pki.rsa.generateKeyPair(2048),c=f.pki.createCertificate();c.publicKey=b.publicKey,c.serialNumber="01",c.validity.notBefore=new Date,c.validity.notAfter=new Date,c.validity.notAfter.setFullYear(c.validity.notBefore.getFullYear()+10);let d=[{name:"commonName",value:"Blue Router Gateway Root CA"},{name:"organizationName",value:"Blue Router Gateway"},{name:"countryName",value:"VN"}];c.setSubject(d),c.setIssuer(d),c.setExtensions([{name:"basicConstraints",cA:!0,critical:!0},{name:"keyUsage",keyCertSign:!0,cRLSign:!0,critical:!0},{name:"subjectKeyIdentifier"}]),c.sign(b.privateKey,f.md.sha256.create());let g=f.pki.privateKeyToPem(b.privateKey),h=f.pki.certificateToPem(c);return e.writeFileSync(i,g,{mode:384}),e.writeFileSync(j,h),console.log("✅ Root CA generated successfully"),{key:i,cert:j}},importRootCAPair:function({certPem:a,keyPem:b}){o();let c=p(a,"Certificate"),d=p(b,"Private key"),f=u(c);if(s(f,v(d)),!r(f))throw Error("Certificate must be a CA certificate with basicConstraints CA:true and keyCertSign usage");if(f.validity.notAfter<new Date)throw Error("Certificate is already expired");let g=t();e.writeFileSync(i,d,{mode:384}),e.writeFileSync(j,c);try{e.unlinkSync(k)}catch{}try{e.unlinkSync(m)}catch{}return{key:i,cert:j,backup:g,info:x()}},generateRootCACsr:function({commonName:a,organizationName:b,countryName:c}={}){if(o(),function(){try{return g("openssl",["version"],{stdio:"ignore"}),!0}catch{return!1}}())return function({commonName:a,organizationName:b,countryName:c}={}){let d=y(a,"Fujinet 9Router MITM CA"),f=y(b,"Fujinet"),h=y(c,"VN").slice(0,2).toUpperCase()||"VN",i=`[ req ]
default_bits       = 4096
prompt             = no
distinguished_name = dn
req_extensions     = v3_ca

[ dn ]
C  = ${h}
O  = ${f}
OU = AI Gateway
CN = ${d}

[ v3_ca ]
basicConstraints = critical, CA:true, pathlen:0
keyUsage = critical, keyCertSign, cRLSign
subjectKeyIdentifier = hash
`,j=t();e.writeFileSync(l,i,"utf8");try{g("openssl",["genrsa","-out",m,"4096"],{stdio:["ignore","pipe","pipe"]}),g("openssl",["req","-new","-key",m,"-out",k,"-config",l],{stdio:["ignore","pipe","pipe"]});try{e.chmodSync(m,384)}catch{}return{csr:k,pendingKey:m,config:l,backup:j}}catch(b){try{e.unlinkSync(m)}catch{}try{e.unlinkSync(k)}catch{}let a=b?.stderr?String(b.stderr).trim():"";throw Error(`OpenSSL CSR generation failed${a?`: ${a}`:""}`)}}({commonName:a,organizationName:b,countryName:c});let d=[{name:"commonName",value:String(a||"Fujinet 9Router MITM CA").trim()||"Fujinet 9Router MITM CA"},{name:"organizationName",value:String(b||"Fujinet").trim()||"Fujinet"},{name:"organizationalUnitName",value:"AI Gateway"}],h=String(c||"VN").trim().slice(0,2).toUpperCase();h&&d.push({name:"countryName",value:h});let i=f.pki.rsa.generateKeyPair(4096),j=f.pki.createCertificationRequest();if(j.publicKey=i.publicKey,j.setSubject(d),j.sign(i.privateKey,f.md.sha256.create()),!j.verify())throw Error("Generated CSR failed verification");let n=t(),p=f.pki.certificationRequestToPem(j),q=f.pki.privateKeyToPem(i.privateKey);return e.writeFileSync(m,q,{mode:384}),e.writeFileSync(k,p),{csr:k,pendingKey:m,backup:n}},importSignedRootCACert:function({certPem:a}){if(o(),!e.existsSync(m))throw Error("No pending CSR private key found. Generate a CSR first.");let b=p(a,"Signed certificate"),c=u(b,"Signed certificate");if(s(c,v(e.readFileSync(m,"utf8"),"Pending private key")),!r(c))throw Error("Signed certificate must be a CA certificate with CA:true and keyCertSign usage");if(c.validity.notAfter<new Date)throw Error("Signed certificate is already expired");let d=t();e.copyFileSync(m,i);try{e.chmodSync(i,384)}catch{}e.writeFileSync(j,b);try{e.unlinkSync(k)}catch{}try{e.unlinkSync(m)}catch{}return{key:i,cert:j,backup:d,info:x()}},loadRootCA:function(){if(!e.existsSync(i)||!e.existsSync(j))throw Error("Root CA not found. Generate it first.");let a=e.readFileSync(i,"utf8"),b=e.readFileSync(j,"utf8");return{key:f.pki.privateKeyFromPem(a),cert:f.pki.certificateFromPem(b)}},generateLeafCert:function(a,b){let c=f.pki.rsa.generateKeyPair(2048),d=f.pki.createCertificate();return d.publicKey=c.publicKey,d.serialNumber=Math.floor(1e6*Math.random()).toString(),d.validity.notBefore=new Date,d.validity.notAfter=new Date,d.validity.notAfter.setFullYear(d.validity.notBefore.getFullYear()+1),d.setSubject([{name:"commonName",value:a}]),d.setIssuer(b.cert.subject.attributes),d.setExtensions([{name:"basicConstraints",cA:!1},{name:"keyUsage",digitalSignature:!0,keyEncipherment:!0},{name:"extKeyUsage",serverAuth:!0,clientAuth:!0},{name:"subjectAltName",altNames:[{type:2,value:a},{type:2,value:`*.${a}`}]}]),d.sign(b.key,f.md.sha256.create()),{key:f.pki.privateKeyToPem(c.privateKey),cert:f.pki.certificateToPem(d)}},isCertExpired:w,readRootCAInfo:x,ROOT_CA_CERT_PATH:j,ROOT_CA_KEY_PATH:i,ROOT_CA_CSR_PATH:k,ROOT_CA_PENDING_KEY_PATH:m}},10846:a=>{"use strict";a.exports=require("next/dist/compiled/next-server/app-page.runtime.prod.js")},21820:a=>{"use strict";a.exports=require("os")},29021:a=>{"use strict";a.exports=require("fs")},29294:a=>{"use strict";a.exports=require("next/dist/server/app-render/work-async-storage.external.js")},33873:a=>{"use strict";a.exports=require("path")},44870:a=>{"use strict";a.exports=require("next/dist/compiled/next-server/app-route.runtime.prod.js")},55511:a=>{"use strict";a.exports=require("crypto")},63033:a=>{"use strict";a.exports=require("next/dist/server/app-render/work-unit-async-storage.external.js")},78335:()=>{},79646:a=>{"use strict";a.exports=require("child_process")},82193:(a,b,c)=>{"use strict";let d=c(29021),e=c(33873),f=c(21820),g="9router";function h(){return"win32"===process.platform?e.join(process.env.APPDATA||e.join(f.homedir(),"AppData","Roaming"),g):e.join(f.homedir(),`.${g}`)}let i=function(){let a=process.env.DATA_DIR;if(!a)return h();try{return d.mkdirSync(a,{recursive:!0}),a}catch(b){if(b?.code==="EACCES"||b?.code==="EPERM")return console.warn(`[DATA_DIR] '${a}' not writable → fallback ~/.${g}`),h();throw b}}(),j=e.join(i,"mitm");a.exports={DATA_DIR:i,MITM_DIR:j}},82988:(a,b,c)=>{"use strict";c.r(b),c.d(b,{handler:()=>I,patchFetch:()=>H,routeModule:()=>D,serverHooks:()=>G,workAsyncStorage:()=>E,workUnitAsyncStorage:()=>F});var d={};c.r(d),c.d(d,{GET:()=>B,POST:()=>C});var e=c(19225),f=c(84006),g=c(8317),h=c(99373),i=c(34775),j=c(24235),k=c(261),l=c(54365),m=c(90771),n=c(73461),o=c(67798),p=c(92280),q=c(62018),r=c(45696),s=c(47929),t=c(86439),u=c(37527),v=c(23211),w=c(8578),x=c(29021),y=c.n(x);function z({body:a,filename:b}){return new v.NextResponse(a,{headers:{"Content-Type":"application/x-pem-file; charset=utf-8","Content-Disposition":`attachment; filename="${b}"`,"Cache-Control":"no-store"}})}function A(a,b){return y().existsSync(a)?y().readFileSync(a,"utf8"):v.NextResponse.json({error:`${b} not found`},{status:404})}async function B(a){try{let{searchParams:b}=new URL(a.url),c=b.get("download");if("csr"===c){let a=A(w.ROOT_CA_CSR_PATH,"CSR");if("string"!=typeof a)return a;return z({body:a,filename:"9router-root-ca.csr"})}if("cert"===c){let a=A(w.ROOT_CA_CERT_PATH,"Root CA certificate");if("string"!=typeof a)return a;return z({body:a,filename:"9router-root-ca.crt"})}return v.NextResponse.json({success:!0,rootCA:(0,w.readRootCAInfo)()})}catch(a){return v.NextResponse.json({error:a.message||"Failed to read Root CA status"},{status:500})}}async function C(a){try{let b=await a.json(),c=String(b?.action||"").trim();if("upload-pair"===c){let a=(0,w.importRootCAPair)({certPem:b.certPem,keyPem:b.keyPem});return v.NextResponse.json({success:!0,action:c,rootCA:a.info})}if("generate-csr"===c){let a=(0,w.generateRootCACsr)({commonName:b.commonName,organizationName:b.organizationName,countryName:b.countryName});return v.NextResponse.json({success:!0,action:c,csrExists:!0,csrPath:a.csr,rootCA:(0,w.readRootCAInfo)()})}if("upload-signed-cert"===c){let a=(0,w.importSignedRootCACert)({certPem:b.certPem});return v.NextResponse.json({success:!0,action:c,rootCA:a.info})}return v.NextResponse.json({error:"action must be upload-pair, generate-csr, or upload-signed-cert"},{status:400})}catch(a){return v.NextResponse.json({error:a.message||"Failed to update Root CA"},{status:500})}}let D=new e.AppRouteRouteModule({definition:{kind:f.RouteKind.APP_ROUTE,page:"/api/cli-tools/antigravity-mitm/root-ca/route",pathname:"/api/cli-tools/antigravity-mitm/root-ca",filename:"route",bundlePath:"app/api/cli-tools/antigravity-mitm/root-ca/route"},distDir:".next-cli-build",relativeProjectDir:"",resolvedPagePath:"D:\\OneDrive - homeviet\\9router\\src\\app\\api\\cli-tools\\antigravity-mitm\\root-ca\\route.js",nextConfigOutput:"standalone",userland:d,...{}}),{workAsyncStorage:E,workUnitAsyncStorage:F,serverHooks:G}=D;function H(){return(0,g.patchFetch)({workAsyncStorage:E,workUnitAsyncStorage:F})}async function I(a,b,c){c.requestMeta&&(0,h.setRequestMeta)(a,c.requestMeta),D.isDev&&(0,h.addRequestMeta)(a,"devRequestTimingInternalsEnd",process.hrtime.bigint());let d="/api/cli-tools/antigravity-mitm/root-ca/route";"/index"===d&&(d="/");let e=await D.prepare(a,b,{srcPage:d,multiZoneDraftMode:!1});if(!e)return b.statusCode=400,b.end("Bad Request"),null==c.waitUntil||c.waitUntil.call(c,Promise.resolve()),null;let{buildId:g,deploymentId:v,params:w,nextConfig:x,parsedUrl:y,isDraftMode:z,prerenderManifest:A,routerServerContext:B,isOnDemandRevalidate:C,revalidateOnlyGenerated:E,resolvedPathname:F,clientReferenceManifest:G,serverActionsManifest:H}=e,I=(0,k.normalizeAppPath)(d),J=!!(A.dynamicRoutes[I]||A.routes[F]),K=async()=>((null==B?void 0:B.render404)?await B.render404(a,b,y,!1):b.end("This page could not be found"),null);if(J&&!z){let a=!!A.routes[F],b=A.dynamicRoutes[I];if(b&&!1===b.fallback&&!a){if(x.adapterPath)return await K();throw new t.NoFallbackError}}let L=null;!J||D.isDev||z||(L="/index"===(L=F)?"/":L);let M=!0===D.isDev||!J,N=J&&!M;H&&G&&(0,j.setManifestsSingleton)({page:d,clientReferenceManifest:G,serverActionsManifest:H});let O=a.method||"GET",P=(0,i.getTracer)(),Q=P.getActiveScopeSpan(),R=!!(null==B?void 0:B.isWrappedByNextServer),S=!!(0,h.getRequestMeta)(a,"minimalMode"),T=(0,h.getRequestMeta)(a,"incrementalCache")||await D.getIncrementalCache(a,x,A,S);null==T||T.resetRequestCache(),globalThis.__incrementalCache=T;let U={params:w,previewProps:A.preview,renderOpts:{experimental:{authInterrupts:!!x.experimental.authInterrupts},cacheComponents:!!x.cacheComponents,supportsDynamicResponse:M,incrementalCache:T,cacheLifeProfiles:x.cacheLife,waitUntil:c.waitUntil,onClose:a=>{b.on("close",a)},onAfterTaskError:void 0,onInstrumentationRequestError:(b,c,d,e)=>D.onRequestError(a,b,d,e,B)},sharedContext:{buildId:g,deploymentId:v}},V=new l.NodeNextRequest(a),W=new l.NodeNextResponse(b),X=m.NextRequestAdapter.fromNodeNextRequest(V,(0,m.signalFromNodeResponse)(b));try{let e,g=async a=>D.handle(X,U).finally(()=>{if(!a)return;a.setAttributes({"http.status_code":b.statusCode,"next.rsc":!1});let c=P.getRootSpanAttributes();if(!c)return;if(c.get("next.span_type")!==n.BaseServerSpan.handleRequest)return void console.warn(`Unexpected root span type '${c.get("next.span_type")}'. Please report this Next.js issue https://github.com/vercel/next.js`);let f=c.get("next.route");if(f){let b=`${O} ${f}`;a.setAttributes({"next.route":f,"http.route":f,"next.span_name":b}),a.updateName(b),e&&e!==a&&(e.setAttribute("http.route",f),e.updateName(b))}else a.updateName(`${O} ${d}`)}),h=async e=>{var h,i;let j=async({previousCacheEntry:f})=>{try{if(!S&&C&&E&&!f)return b.statusCode=404,b.setHeader("x-nextjs-cache","REVALIDATED"),b.end("This page could not be found"),null;let d=await g(e);a.fetchMetrics=U.renderOpts.fetchMetrics;let h=U.renderOpts.pendingWaitUntil;h&&c.waitUntil&&(c.waitUntil(h),h=void 0);let i=U.renderOpts.collectedTags;if(!J)return await (0,p.I)(V,W,d,U.renderOpts.pendingWaitUntil),null;{let a=await d.blob(),b=(0,q.toNodeOutgoingHttpHeaders)(d.headers);i&&(b[s.NEXT_CACHE_TAGS_HEADER]=i),!b["content-type"]&&a.type&&(b["content-type"]=a.type);let c=void 0!==U.renderOpts.collectedRevalidate&&!(U.renderOpts.collectedRevalidate>=s.INFINITE_CACHE)&&U.renderOpts.collectedRevalidate,e=void 0===U.renderOpts.collectedExpire||U.renderOpts.collectedExpire>=s.INFINITE_CACHE?void 0:U.renderOpts.collectedExpire;return{value:{kind:u.CachedRouteKind.APP_ROUTE,status:d.status,body:Buffer.from(await a.arrayBuffer()),headers:b},cacheControl:{revalidate:c,expire:e}}}}catch(b){throw(null==f?void 0:f.isStale)&&await D.onRequestError(a,b,{routerKind:"App Router",routePath:d,routeType:"route",revalidateReason:(0,o.c)({isStaticGeneration:N,isOnDemandRevalidate:C})},!1,B),b}},k=await D.handleResponse({req:a,nextConfig:x,cacheKey:L,routeKind:f.RouteKind.APP_ROUTE,isFallback:!1,prerenderManifest:A,isRoutePPREnabled:!1,isOnDemandRevalidate:C,revalidateOnlyGenerated:E,responseGenerator:j,waitUntil:c.waitUntil,isMinimalMode:S});if(!J)return null;if((null==k||null==(h=k.value)?void 0:h.kind)!==u.CachedRouteKind.APP_ROUTE)throw Object.defineProperty(Error(`Invariant: app-route received invalid cache entry ${null==k||null==(i=k.value)?void 0:i.kind}`),"__NEXT_ERROR_CODE",{value:"E701",enumerable:!1,configurable:!0});S||b.setHeader("x-nextjs-cache",C?"REVALIDATED":k.isMiss?"MISS":k.isStale?"STALE":"HIT"),z&&b.setHeader("Cache-Control","private, no-cache, no-store, max-age=0, must-revalidate");let l=(0,q.fromNodeOutgoingHttpHeaders)(k.value.headers);return S&&J||l.delete(s.NEXT_CACHE_TAGS_HEADER),!k.cacheControl||b.getHeader("Cache-Control")||l.get("Cache-Control")||l.set("Cache-Control",(0,r.getCacheControlHeader)(k.cacheControl)),await (0,p.I)(V,W,new Response(k.value.body,{headers:l,status:k.value.status||200})),null};R&&Q?await h(Q):(e=P.getActiveScopeSpan(),await P.withPropagatedContext(a.headers,()=>P.trace(n.BaseServerSpan.handleRequest,{spanName:`${O} ${d}`,kind:i.SpanKind.SERVER,attributes:{"http.method":O,"http.target":a.url}},h),void 0,!R))}catch(b){if(b instanceof t.NoFallbackError||await D.onRequestError(a,b,{routerKind:"App Router",routePath:I,routeType:"route",revalidateReason:(0,o.c)({isStaticGeneration:N,isOnDemandRevalidate:C})},!1,B),J)throw b;return await (0,p.I)(V,W,new Response(null,{status:500})),null}}},86439:a=>{"use strict";a.exports=require("next/dist/shared/lib/no-fallback-error.external")},96487:()=>{}};var b=require("../../../../../webpack-runtime.js");b.C(a);var c=b.X(0,[4741,1813,5296],()=>b(b.s=82988));module.exports=c})();