@netacea/cloudflare 5.2.42 → 5.2.44
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +1 -1
- package/package.json +24 -59
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var e=require("crypto"),t=require("buffer"),i=require("url"),a=require("querystring"),s=require("jose");function o(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var n={},r={},c={};!function(i){var a,s,o,n,r=e,c=t;i.NetaceaIngestType=void 0,(a=i.NetaceaIngestType||(i.NetaceaIngestType={})).ORIGIN="ORIGIN",a.HTTP="HTTP",a.KINESIS="KINESIS",a.NATIVE="NATIVE",i.NetaceaLogVersion=void 0,(s=i.NetaceaLogVersion||(i.NetaceaLogVersion={})).V1="V1",s.V2="V2",i.NetaceaMitigationType=void 0,(o=i.NetaceaMitigationType||(i.NetaceaMitigationType={})).MITIGATE="MITIGATE",o.INJECT="INJECT",o.INGEST="INGEST",i.NetaceaCookieV3IssueReason=void 0,(n=i.NetaceaCookieV3IssueReason||(i.NetaceaCookieV3IssueReason={})).CAPTCHA_GET="captcha_get",n.CAPTCHA_POST="captcha_post",n.EXPIRED_SESSION="expired_session",n.FORCED_REVALIDATION="forced_revalidation",n.INVALID_SESSION="invalid_session",n.IP_CHANGE="ip_change",n.NO_SESSION="no_session";const h=3e3;const u="_/@#/",p={none:"",block:"block",captcha:"captcha",allow:"allow",captchaPass:"captchapass"},d={0:p.none,1:p.block,2:p.none,3:p.block,4:p.block},l={1:p.captcha,2:p.captchaPass,3:p.captcha,4:p.allow,5:p.captcha},g={clientIP:"cip",userId:"uid",gracePeriod:"grp",cookieId:"cid",match:"mat",mitigate:"mit",captcha:"cap",issueTimestamp:"ist",issueReason:"isr"},m={checkAllPostRequests:"fCAPR"};var y=Object.freeze({__proto__:null,COOKIEDELIMITER:u,bestMitigationCaptchaMap:l,bestMitigationMap:d,captchaMap:{0:"",1:"captcha_serve",2:"captcha_pass",3:"captcha_fail",4:"captcha_cookiepass",5:"captcha_cookiefail"},captchaStatusCodes:{"":0,captchaServe:1,captchaPass:2,captchaFail:3,captchaCookiePass:4,captchaCookieFail:5},matchMap:{0:"",1:"ua_",2:"ip_",3:"visitor_",4:"datacenter_",5:"sev_",6:"organisation_",7:"asn_",8:"country_",9:"combination_"},mitigateMap:{0:"",1:"blocked",2:"allow",3:"hardblocked",4:"block"},mitigationTypes:p,netaceaCookieV3KeyMap:g,netaceaCookieV3OptionalKeyMap:m,netaceaHeaders:{match:"x-netacea-match",mitigate:"x-netacea-mitigate",captcha:"x-netacea-captcha",mitata:"x-netacea-mitata-value",mitataExpiry:"x-netacea-mitata-expiry",mitataCaptcha:"x-netacea-mitatacaptcha-value",mitataCaptchaExpiry:"x-netacea-mitatacaptcha-expiry",eventId:"x-netacea-event-id"},netaceaSettingsMap:{checkAllPostRequests:"checkAllPostRequests"}});const f="1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".split(""),C=/^(.*)_\/@#\/(.*)_\/@#\/(.*)_\/@#\/(.*)_\/@#\/((\d)(\d)(\d))$/;function v(e){if(void 0===e)return;const t=e.match(C);if(null!=t){const[,e,i,a,s,o,n,r,c]=t;return{signature:e,expiry:i,userId:a,ipHash:s,mitigationType:o,match:parseInt(n),mitigate:parseInt(r),captcha:parseInt(c)}}}function k(e=16,t=f){const i=r.randomBytes(e-1);return`c${Array.from(i).map((e=>t[e%t.length])).join("")}`}function S(e,t){const i=r.createHmac("sha256",t);return i.update(e),c.Buffer.from(i.digest("hex")).toString("base64")}function I(e){if(void 0===e||""===e)return;const t=e.split("&"),i={clientIP:"",userId:"",cookieId:"",gracePeriod:0,match:0,mitigate:0,captcha:0,issueTimestamp:0,issueReason:"",checkAllPostRequests:void 0};for(const e of t){const[t,a]=e.split("="),s=decodeURIComponent(a);let o=Object.keys(g).find((e=>g[e]===t));void 0===o&&(o=Object.keys(m).find((e=>m[e]===t)));let n=""===s?void 0:Number(s);void 0!==n&&isNaN(n)&&(n=s),i[o]=n}return i}function N(){return{mitata:void 0,requiresReissue:!1,isExpired:!1,shouldExpire:!1,isSameIP:!1,isPrimaryHashValid:!1,captcha:0,match:0,mitigate:0,issueReason:i.NetaceaCookieV3IssueReason.NO_SESSION}}function T(e,t){const i=e.split(";").map((e=>e.trim())).filter((e=>e.toLowerCase().startsWith(t.toLowerCase())))[0];return void 0!==i&&i.length>0?i?.replace(`${t}=`,""):void 0}function A(e,t=!1){if(""===e)return"";return e.replace(/ /g,"").split(";").map((e=>e.charAt(0).toUpperCase()+e.slice(1))).filter((e=>""!==e.trim())).filter(((e,i,a)=>{const s=e=>e.split("=")[0],o=s(e),n=a.map(s);return t?i===n.lastIndexOf(o):i===n.indexOf(o)})).join("; ")}function w(e){const t=A([e.otherAttributes??"",`Max-Age=${e.maxAgeAttribute??86400}`,"Path=/"].join("; "));return`${e.cookieName}=${e.cookieValue}; ${t}`}const b={cookie:{attributes:Object.freeze({__proto__:null,configureCookiesDomain:function(e,t){let i=e=A(e??"",!0),a=t=A(t??"",!0);if(void 0!==e&&void 0!==t){const s=T(e,"Domain"),o=T(t,"Domain");void 0!==s&&void 0!==o?a=t.replace(o,s):void 0!==s&&void 0===o?a=t+(""!==t?`; Domain=${s}`:`Domain=${s}`):void 0===s&&void 0!==o&&(i=e+(""!==e?`; Domain=${o}`:`Domain=${o}`))}else if(void 0!==e&&void 0===t){const t=T(e,"Domain");void 0!==t&&(a=`Domain=${t}`)}else if(void 0===e&&void 0!==t){const e=T(t,"Domain");void 0!==e&&(i=`Domain=${e}`)}return{cookieAttributes:""!==i?i:void 0,captchaCookieAttributes:""!==a?a:void 0}},extractAndRemoveCookieAttr:function(e,t){const i=T(e,t);if(void 0!==i){return{extractedAttribute:i,cookieAttributes:e.replace(/ /g,"").replace(`${t}=${i}`,"").split(";").filter((e=>e.length>0)).join("; ")}}return{extractedAttribute:void 0,cookieAttributes:e}},extractCookieAttr:T,removeDuplicateAttrs:A}),netaceaSession:Object.freeze({__proto__:null,createNetaceaCaptchaSetCookieString:function(e){return w({...e,cookieName:e.cookieName??"_mitatacaptcha"})},createNetaceaSetCookieString:function(e){return w({...e,cookieName:e.cookieName??"_mitata"})},createSetCookieString:w})}};i.checkMitataCookie=function(e,t,i){const a={mitata:void 0,requiresReissue:!1,isExpired:!1,shouldExpire:!1,isSameIP:!1,isPrimaryHashValid:!1,captcha:0,match:0,mitigate:0};if("string"!=typeof e||""===e)return a;const s=v(e);if(void 0!==s){const e=[s.expiry,s.userId,s.ipHash,s.mitigationType].join(u),a=Math.floor(Date.now()/1e3),o=parseInt(s.expiry)<a,n=[1,3,5].includes(s.captcha),r=3===s.mitigate,c=n||r,h=S(t+"|"+s.expiry,i),p=s.ipHash===h;return{mitata:s,requiresReissue:o||!p,isExpired:o,shouldExpire:c,isSameIP:p,isPrimaryHashValid:s.signature===S(e,i),match:s.match,mitigate:s.mitigate,captcha:s.captcha}}return a},i.checkNetaceaCookieV3=function(e,t){if(void 0===e||""===e)return N();const i=I(e);if(void 0!==i){const e=Math.floor(Date.now()/1e3),a=i.issueTimestamp+i.gracePeriod<e,s=t===i.clientIP,o=[1,3,5].includes(i.captcha),n=3===i.mitigate;return{mitata:i,requiresReissue:a||!s,isExpired:a,shouldExpire:o||n,isSameIP:s,isPrimaryHashValid:!0,match:i.match,mitigate:i.mitigate,captcha:i.captcha,issueReason:i.issueReason}}return N()},i.configureMitataExpiry=function(e,t){return void 0===t?e===i.NetaceaMitigationType.INGEST?3600:60:t},i.cookieIsNetaceaV3Format=function(e){return void 0!==e&&e.split("&").map((e=>e.split("=")[0])).filter((e=>!Object.values(m).includes(e))).every((e=>Object.values(g).includes(e)))},i.correctTimeout=function(e){return e<=0?h:e},i.createMitataCookie=function(e,t,i,a,s="000"){void 0===t&&(t=k());const o=[i,t,S(e+"|"+String(i),a),s].join(u);return`${S(o,a)}${u}${o}`},i.createNetaceaCookieV3=function(e){return Object.entries(e).filter((([e,t])=>void 0!==t)).map((([e,t])=>e in m?`${m[e]}=${encodeURIComponent(t)}`:`${g[e]}=${encodeURIComponent(t)}`)).join("&")},i.defaultInvalidResponse=N,i.dictionary=y,i.generateId=k,i.hexSha256=S,i.ingestIgnoredIpValue="ignored",i.lib=b,i.matchMitataCookie=v,i.matchNetaceaCookieV3=I,i.objectIsNetaceaCookieV3=function(e){if("object"!=typeof e||null===e)return!1;for(const t of Object.keys(g)){if(!(t in e))return!1;if(void 0===e[t])return!1}return!0},i.safeParseInt=function(e,t=0){return isNaN(e)?t:parseInt(e)},i.warmupCookie={cookie:"MzBkZDEwYjc0ZmIyMzQ4YmY0OTlhNTkyNjY0MDRjMjhjNmQ5Y2RlYjVkYzVkMDQyZmEzODU4MDBiN2MwNTk1OQ==_/@#/1653044256_/@#/UUID_/@#/NjEyOWIzY2JiMjE5NjcwMThlYjg5NDYzY2YyMDZlYjE0ZDg2NTRjYmMxODg5Y2I4Y2U2NGFjZDAxOTdhMGFmNA==_/@#/000",secretKey:"EXAMPLE_SECRET_KEY",clientIP:"192.168.0.1"}}(c);var h={},u={},p={},d={},l=function(e){return new g(e)};function g(e){this.capacity=0|e,this.map=Object.create(null),this.list=new m}function m(){this.firstNode=null,this.lastNode=null}function y(e,t){this.key=e,this.val=t,this.prev=null,this.next=null}g.prototype.get=function(e){var t=this.map[e];if(null!=t)return this.used(t),t.val},g.prototype.set=function(e,t){var i=this.map[e];if(null!=i)i.val=t;else{if(this.capacity||this.prune(),!this.capacity)return!1;i=new y(e,t),this.map[e]=i,this.capacity--}return this.used(i),!0},g.prototype.used=function(e){this.list.moveToFront(e)},g.prototype.prune=function(){var e=this.list.pop();null!=e&&(delete this.map[e.key],this.capacity++)},m.prototype.moveToFront=function(e){this.firstNode!=e&&(this.remove(e),null==this.firstNode?(this.firstNode=e,this.lastNode=e,e.prev=null,e.next=null):(e.prev=null,e.next=this.firstNode,e.next.prev=e,this.firstNode=e))},m.prototype.pop=function(){var e=this.lastNode;return null!=e&&this.remove(e),e},m.prototype.remove=function(e){this.firstNode==e?this.firstNode=e.next:null!=e.prev&&(e.prev.next=e.next),this.lastNode==e?this.lastNode=e.prev:null!=e.next&&(e.next.prev=e.prev)},function(t){var s=d,o=i,n=a,r=e,c=l(1e3);function h(e,t,i){return r.createHmac("sha256",e).update(t,"utf8").digest(i)}function u(e,t){return r.createHash("sha256").update(e,"utf8").digest(t)}function p(e){return e.replace(/[!'()*]/g,(function(e){return"%"+e.charCodeAt(0).toString(16).toUpperCase()}))}function g(e){return p(encodeURIComponent(e))}var m={authorization:!0,connection:!0,"x-amzn-trace-id":!0,"user-agent":!0,expect:!0,"presigned-expires":!0,range:!0};function y(e,t){"string"==typeof e&&(e=o.parse(e));var i=e.headers=e.headers||{},a=(!this.service||!this.region)&&this.matchHost(e.hostname||e.host||i.Host||i.host);this.request=e,this.credentials=t||this.defaultCredentials(),this.service=e.service||a[0]||"",this.region=e.region||a[1]||"us-east-1","email"===this.service&&(this.service="ses"),!e.method&&e.body&&(e.method="POST"),i.Host||i.host||(i.Host=e.hostname||e.host||this.createHost(),e.port&&(i.Host+=":"+e.port)),e.hostname||e.host||(e.hostname=i.Host||i.host),this.isCodeCommitGit="codecommit"===this.service&&"GIT"===e.method}y.prototype.matchHost=function(e){var t=((e||"").match(/([^\.]+)\.(?:([^\.]*)\.)?amazonaws\.com(\.cn)?$/)||[]).slice(1,3);if("es"===t[1]&&(t=t.reverse()),"s3"==t[1])t[0]="s3",t[1]="us-east-1";else for(var i=0;i<2;i++)if(/^s3-/.test(t[i])){t[1]=t[i].slice(3),t[0]="s3";break}return t},y.prototype.isSingleRegion=function(){return["s3","sdb"].indexOf(this.service)>=0&&"us-east-1"===this.region||["cloudfront","ls","route53","iam","importexport","sts"].indexOf(this.service)>=0},y.prototype.createHost=function(){var e=this.isSingleRegion()?"":"."+this.region;return("ses"===this.service?"email":this.service)+e+".amazonaws.com"},y.prototype.prepareRequest=function(){this.parsePath();var e,t=this.request,i=t.headers;t.signQuery?(this.parsedPath.query=e=this.parsedPath.query||{},this.credentials.sessionToken&&(e["X-Amz-Security-Token"]=this.credentials.sessionToken),"s3"!==this.service||e["X-Amz-Expires"]||(e["X-Amz-Expires"]=86400),e["X-Amz-Date"]?this.datetime=e["X-Amz-Date"]:e["X-Amz-Date"]=this.getDateTime(),e["X-Amz-Algorithm"]="AWS4-HMAC-SHA256",e["X-Amz-Credential"]=this.credentials.accessKeyId+"/"+this.credentialString(),e["X-Amz-SignedHeaders"]=this.signedHeaders()):(t.doNotModifyHeaders||this.isCodeCommitGit||(!t.body||i["Content-Type"]||i["content-type"]||(i["Content-Type"]="application/x-www-form-urlencoded; charset=utf-8"),!t.body||i["Content-Length"]||i["content-length"]||(i["Content-Length"]=Buffer.byteLength(t.body)),!this.credentials.sessionToken||i["X-Amz-Security-Token"]||i["x-amz-security-token"]||(i["X-Amz-Security-Token"]=this.credentials.sessionToken),"s3"!==this.service||i["X-Amz-Content-Sha256"]||i["x-amz-content-sha256"]||(i["X-Amz-Content-Sha256"]=u(this.request.body||"","hex")),i["X-Amz-Date"]||i["x-amz-date"]?this.datetime=i["X-Amz-Date"]||i["x-amz-date"]:i["X-Amz-Date"]=this.getDateTime()),delete i.Authorization,delete i.authorization)},y.prototype.sign=function(){return this.parsedPath||this.prepareRequest(),this.request.signQuery?this.parsedPath.query["X-Amz-Signature"]=this.signature():this.request.headers.Authorization=this.authHeader(),this.request.path=this.formatPath(),this.request},y.prototype.getDateTime=function(){if(!this.datetime){var e=this.request.headers,t=new Date(e.Date||e.date||new Date);this.datetime=t.toISOString().replace(/[:\-]|\.\d{3}/g,""),this.isCodeCommitGit&&(this.datetime=this.datetime.slice(0,-1))}return this.datetime},y.prototype.getDate=function(){return this.getDateTime().substr(0,8)},y.prototype.authHeader=function(){return["AWS4-HMAC-SHA256 Credential="+this.credentials.accessKeyId+"/"+this.credentialString(),"SignedHeaders="+this.signedHeaders(),"Signature="+this.signature()].join(", ")},y.prototype.signature=function(){var e,t,i,a=this.getDate(),s=[this.credentials.secretAccessKey,a,this.region,this.service].join(),o=c.get(s);return o||(e=h("AWS4"+this.credentials.secretAccessKey,a),t=h(e,this.region),i=h(t,this.service),o=h(i,"aws4_request"),c.set(s,o)),h(o,this.stringToSign(),"hex")},y.prototype.stringToSign=function(){return["AWS4-HMAC-SHA256",this.getDateTime(),this.credentialString(),u(this.canonicalString(),"hex")].join("\n")},y.prototype.canonicalString=function(){this.parsedPath||this.prepareRequest();var e,t=this.parsedPath.path,i=this.parsedPath.query,a=this.request.headers,s="",o="s3"!==this.service,n="s3"===this.service||this.request.doNotEncodePath,r="s3"===this.service,c="s3"===this.service;if(e="s3"===this.service&&this.request.signQuery?"UNSIGNED-PAYLOAD":this.isCodeCommitGit?"":a["X-Amz-Content-Sha256"]||a["x-amz-content-sha256"]||u(this.request.body||"","hex"),i){var h=Object.keys(i).reduce((function(e,t){return t?(e[g(t)]=Array.isArray(i[t])&&c?i[t][0]:i[t],e):e}),{}),p=[];Object.keys(h).sort().forEach((function(e){Array.isArray(h[e])?h[e].map(g).sort().forEach((function(t){p.push(e+"="+t)})):p.push(e+"="+g(h[e]))})),s=p.join("&")}return"/"!==t&&(o&&(t=t.replace(/\/{2,}/g,"/")),"/"!==(t=t.split("/").reduce((function(e,t){return o&&".."===t?e.pop():o&&"."===t||(n&&(t=decodeURIComponent(t.replace(/\+/g," "))),e.push(g(t))),e}),[]).join("/"))[0]&&(t="/"+t),r&&(t=t.replace(/%2F/g,"/"))),[this.request.method||"GET",t,s,this.canonicalHeaders()+"\n",this.signedHeaders(),e].join("\n")},y.prototype.canonicalHeaders=function(){var e=this.request.headers;return Object.keys(e).filter((function(e){return null==m[e.toLowerCase()]})).sort((function(e,t){return e.toLowerCase()<t.toLowerCase()?-1:1})).map((function(t){return t.toLowerCase()+":"+e[t].toString().trim().replace(/\s+/g," ")})).join("\n")},y.prototype.signedHeaders=function(){return Object.keys(this.request.headers).map((function(e){return e.toLowerCase()})).filter((function(e){return null==m[e]})).sort().join(";")},y.prototype.credentialString=function(){return[this.getDate(),this.region,this.service,"aws4_request"].join("/")},y.prototype.defaultCredentials=function(){var e=process.env;return{accessKeyId:e.AWS_ACCESS_KEY_ID||e.AWS_ACCESS_KEY,secretAccessKey:e.AWS_SECRET_ACCESS_KEY||e.AWS_SECRET_KEY,sessionToken:e.AWS_SESSION_TOKEN}},y.prototype.parsePath=function(){var e=this.request.path||"/";/[^0-9A-Za-z;,/?:@&=+$\-_.!~*'()#%]/.test(e)&&(e=encodeURI(decodeURI(e)));var t=e.indexOf("?"),i=null;t>=0&&(i=n.parse(e.slice(t+1)),e=e.slice(0,t)),this.parsedPath={path:e,query:i}},y.prototype.formatPath=function(){var e=this.parsedPath.path,t=this.parsedPath.query;return t?(null!=t[""]&&delete t[""],e+"?"+p(n.stringify(t))):e},s.RequestSigner=y,s.sign=function(e,t){return new y(e,t).sign()}}();var f={};Object.defineProperty(f,"__esModule",{value:!0}),f.API_VERSION=f.REGION=f.PAYLOAD_TYPE=f.STATE=void 0,f.STATE={ACTIVE:"ACTIVE",UPDATING:"UPDATING",CREATING:"CREATING",DELETING:"DELETING"},f.PAYLOAD_TYPE="string",f.REGION="eu-west-1",f.API_VERSION="2013-12-02",Object.defineProperty(p,"__esModule",{value:!0});const C=d,v=f;p.default=class{static batchArrayForKinesis(e,t){const i=[];for(let a=0;a<e.length;a+=t){const s=e.slice(a,a+t);i.push({Data:Buffer.from(JSON.stringify(s)).toString("base64"),PartitionKey:Date.now().toString()})}return i}static signRequest(e,t,i){const{accessKeyId:a,secretAccessKey:s}=e,o={Records:this.batchArrayForKinesis(t,i),PartitionKey:Date.now().toString(),StreamName:e.streamName};return C.sign({service:"kinesis",body:JSON.stringify(o),headers:{"Content-Type":"application/x-amz-json-1.1","X-Amz-Target":"Kinesis_20131202.PutRecords"},region:v.REGION},{accessKeyId:a,secretAccessKey:s})}},Object.defineProperty(u,"__esModule",{value:!0});const k=p;u.default=class{constructor({kinesisStreamName:e,kinesisAccessKey:t,kinesisSecretKey:i,maxLogAgeSeconds:a,logBatchSize:s}){this.logBatchSize=20,this.maxLogAgeSeconds=10,this.logCache=[],this.intervalSet=!1,this.kinesisStreamName=e,this.kinesisAccessKey=t,this.kinesisSecretKey=i,void 0!==a&&a<this.maxLogAgeSeconds&&a>0&&(this.maxLogAgeSeconds=a),void 0!==s&&(this.logBatchSize=s)}async putToKinesis(e){if(0===this.logCache.length)return;const t=[...this.logCache];this.logCache=[];try{const i=k.default.signRequest({streamName:this.kinesisStreamName,accessKeyId:this.kinesisAccessKey,secretAccessKey:this.kinesisSecretKey},t,this.logBatchSize);await e({headers:i.headers,host:`https://${i.hostname}`,method:i.method,path:i.path,body:i.body})}catch(e){this.logCache.push(...t),console.error(e)}}async ingest(e,t){if(this.logCache.push(e),this.intervalSet||(this.intervalSet=!0,await async function(e){await new Promise((t=>{setTimeout(t,e)}))}(1e3*this.maxLogAgeSeconds),await this.putToKinesis(t),this.intervalSet=!1),this.logCache.length>=this.logBatchSize)return await this.putToKinesis(t)}},Object.defineProperty(h,"__esModule",{value:!0});const S=u;h.default=S.default;var I={name:"@netacea/cloudflare",version:"5.2.42",description:"Netacea Cloudflare CDN Integration",main:"dist/index.js",types:"dist/index.d.ts",files:["dist/"],scripts:{test:"npm run test:unit && npm run test:integration:no-clean","test:unit":"npx nyc tape -r ts-node/register './tests/tape/*.test.ts'","test:integration":"npx nyc mocha --timeout 60000 -r ts-node/register './tests/mocha/*.test.ts'","test:integration:no-clean":"npx nyc --no-clean mocha --timeout 60000 -r ts-node/register './tests/mocha/*.test.ts'",lint:"npx eslint . --ext ts","lint:fix":"npx eslint . --ext ts --fix",rollup:"npx rollup -c rollup.config.mjs && npx rollup -c rollup-types.config.mjs",prepublishOnly:"npm run build",build:"npx tsc --project tsconfig.build.json && npm run rollup"},author:"Netacea <npm@netacea.com> (https://netacea.com)",publishConfig:{access:"public"},license:"ISC",dependencies:{"@netacea/kinesisingest":"^1.5.42","@netacea/netaceaintegrationbase":"^2.0.24",jose:"^4.11.2"},devDependencies:{"@cloudflare/workers-types":"^4.20231025.0","@netacea/netaceaintegrationtestrunner":"^1.8.21","@rollup/plugin-commonjs":"^25.0.0","@rollup/plugin-json":"^6.0.0","@rollup/plugin-node-resolve":"^15.1.0","@rollup/plugin-replace":"^5.0.2","@rollup/plugin-terser":"^0.4.3","@rollup/plugin-typescript":"^11.1.1","@types/chai":"^4.3.5","@types/mocha":"^10.0.1","@types/node":"^20.9.1","@types/node-fetch":"^2.5.7","@types/proxyquire":"^1.3.28","@types/sinon":"^9.0.8","@types/tape":"^4.13.0",chai:"^4.3.7",mocha:"^10.2.0",nyc:"^15.1.0",proxyquire:"^2.1.3",rollup:"^3.23.0","rollup-plugin-dts":"^6.0.2","rollup-plugin-node-externals":"^6.1.1",sinon:"^9.1.0",tape:"^5.0.1","ts-node":"^10.9.1",typescript:"^5.2.2"},gitHead:"ce3df71d2ea60c17fb83a888c6a9cb2411c6a943"},N={};Object.defineProperty(N,"__esModule",{value:!0}),N.fetch=void 0,N.fetch=globalThis.fetch.bind(globalThis);var T={};Object.defineProperty(T,"__esModule",{value:!0}),T.decrypt=T.encrypt=void 0;const A=s;T.encrypt=async function(e,t){const i=A.base64url.decode(t),a=(new TextEncoder).encode(e);return await new A.CompactEncrypt(a).setProtectedHeader({alg:"dir",enc:"A256GCM"}).encrypt(i)},T.decrypt=async function(e,t){const i=A.base64url.decode(t),{plaintext:a}=await A.compactDecrypt(e,i,{keyManagementAlgorithms:["dir"],contentEncryptionAlgorithms:["A256GCM"]});return(new TextDecoder).decode(a)};var w={};Object.defineProperty(w,"__esModule",{value:!0}),w.isUrlCaptchaGet=w.getTrackingId=w.modifyCaptchaJsonResponse=w.getCaptchaPageContentType=void 0,w.getCaptchaPageContentType=function(e){if(void 0===e)return"text/html";const t=e.toLowerCase(),i=t.includes("application/html")||t.includes("text/html"),a=t.includes("application/json");return!i&&a?"application/json":"text/html"},w.modifyCaptchaJsonResponse=async function(e,t,i){const a=e.length>0?JSON.parse(e).trackingId:void 0,{hostname:s}=new URL(i);return t.length<2||void 0===a?"":JSON.stringify({captchaRelativeURL:`${t}?trackingId=${a}`,captchaAbsoluteURL:`https://${s}${t}?trackingId=${a}`})},w.getTrackingId=async function(e){try{const{searchParams:t}=new URL(e);return t.get("trackingId")}catch(e){return null}},w.isUrlCaptchaGet=async function(e,t,i){if(void 0===i||!i)return!1;i.startsWith("/")||(i="/"+i);const{pathname:a,search:s}=new URL(e);return a.includes(i)&&s.includes("trackingId")&&"get"===t.toLowerCase()};var b={};async function x(e,t){const i=(new TextEncoder).encode(t),a=await crypto.subtle.digest(e,i);return Array.from(new Uint8Array(a)).map((e=>e.toString(16).padStart(2,"0"))).join("")}function E(e){const t=[];return e.forEach(((e,i)=>{const a=i.toLowerCase();"cookie"===a||"referer"===a||a.startsWith("x-netacea-")||t.push(i)})),t.join(",")}async function P(e){let t="";try{t=await x("SHA-256",e)}catch(e){t=""}return t}Object.defineProperty(b,"__esModule",{value:!0}),b.hashCookieNames=b.hashHeaders=b.extractHeaderNames=b.hashString=void 0,b.hashString=x,b.extractHeaderNames=E,b.hashHeaders=async function(e){const t=E(e);return await P(t)},b.hashCookieNames=async function(e){const t=e.join(",");return await P(t)};var M={};Object.defineProperty(M,"__esModule",{value:!0}),M.addIngestOriginHeaders=void 0;const R=I;M.addIngestOriginHeaders=function(e,t,i){e.headers.set("x-netacea-integration-type",R.name.replace("@netacea/","")),e.headers.set("x-netacea-integration-version",R.version),e.headers.set("x-netacea-userid",i),e.headers.set("x-netacea-bc-type",t)},Object.defineProperty(r,"__esModule",{value:!0});const _=c,H=h,O=I,K=N,j=T,q=w,D=b,V=M,{configureCookiesDomain:$}=_.lib.cookie.attributes;r.default=class{constructor(e){this.encryptedCookies=[],this.enableDynamicCaptchaContentType=!1;const{apiKey:t,secretKey:i,timeout:a=3e3,mitigationServiceUrl:s="https://mitigations.netacea.net",ingestServiceUrl:o="https://ingest.netacea.net",mitigationType:n=_.NetaceaMitigationType.INGEST,captchaSiteKey:r,captchaSecretKey:c,ingestType:h=_.NetaceaIngestType.HTTP,kinesis:u,logVersion:p,mitataCookieExpirySeconds:d,netaceaCookieExpirySeconds:l,netaceaCookieName:g,netaceaCaptchaCookieName:m,enableDynamicCaptchaContentType:y=!1,captchaHeader:f,netaceaCaptchaPath:C}=e;if(null==t)throw new Error("apiKey is a required parameter");this.apiKey=t,this.secretKey=i,this.mitigationServiceUrl=s,this.ingestServiceUrl=o,this.mitigationType=n,this.ingestType=null!=h?h:_.NetaceaIngestType.HTTP,this.logVersion=null!=p?p:_.NetaceaLogVersion.V1,this.ingestType===_.NetaceaIngestType.KINESIS&&(void 0===u?console.warn(`NETACEA WARN: no kinesis args provided, when ingestType is ${this.ingestType}`):this.kinesis=new H.default({...u,apiKey:this.apiKey})),void 0===r&&void 0===c||(this.captchaSiteKey=r,this.captchaSecretKey=c),this.timeout=(0,_.correctTimeout)(a),this.netaceaCookieName=null!=g?g:"_mitata",this.netaceaCaptchaCookieName=null!=m?m:"_mitatacaptcha";const{cookieAttributes:v,captchaCookieAttributes:k}=$(e.netaceaCookieAttributes,e.netaceaCaptchaCookieAttributes);this.netaceaCookieAttributes=null!=v?v:"",this.netaceaCaptchaCookieAttributes=null!=k?k:"",this.encryptedCookies=[this.netaceaCookieName,this.netaceaCaptchaCookieName],this.mitataCookieExpirySeconds=function(e,t){return void 0===t?e===_.NetaceaMitigationType.INGEST?3600:60:t}(n,null!=l?l:d),this.cookieEncryptionKey=e.cookieEncryptionKey,Boolean(C)&&"string"==typeof C&&(this.netaceaCaptchaPath=C.startsWith("/")?C:`/${C}`),void 0!==this.netaceaCaptchaPath&&(this.enableDynamicCaptchaContentType="boolean"==typeof y?y:"true"===y),this.captchaHeader=f}async run(e,t){const i=new Request(e.request),a=await this.timeoutCheck(this.runMitigation(i),this.timeout);return await this.handleResponse(i,a,t)}async inject(e){const t=await this.getMitigationResponse(e);return{injectHeaders:t.injectHeaders,sessionStatus:t.sessionStatus,setCookie:t.setCookie}}async mitigate(e){const t=await this.getMitigationResponse(e);if(t.mitigated){const i=new Headers;if(!await(0,q.isUrlCaptchaGet)(e.url,e.method,this.netaceaCaptchaPath))for(const e of t.setCookie)i.append("set-cookie",e);let a="Forbidden";return"captcha"===t.mitigation&&(void 0!==this.captchaHeader&&i.append(this.captchaHeader.name,this.captchaHeader.value),i.append("content-type","text/html; charset=UTF-8"),a=t.body),{response:new Response(a,{status:403,statusText:"Forbidden",headers:i}),setCookie:t.setCookie,sessionStatus:t.sessionStatus}}if(this.isUrlCaptchaPost(e.url,e.method)){const e=new Headers;for(const i of t.setCookie)e.append("set-cookie",i);return{response:new Response(t.body,{status:200,statusText:"OK",headers:e}),setCookie:t.setCookie,sessionStatus:t.sessionStatus}}return{setCookie:t.setCookie,sessionStatus:t.sessionStatus}}async getNetaceaSession(e,t){var i;const a=void 0!==t?await this.getNetaceaCookieFromResponse(t):void 0,s=null!=a?a:await this.getNetaceaCookieFromRequest(e),{headers:o}=e,n=await(0,D.hashHeaders)(o),r=this.getHeaderValuesArray(o,"cookie").map((e=>e.split("=")[0])).flat(),c=await(0,D.hashCookieNames)(r),h=""===n?n:`h_${n.substring(1,15)}`,u=""===c?c:`c_${c.substring(1,15)}`,{match:p,mitigate:d,captcha:l,userId:g}=null!==(i=(0,_.matchMitataCookie)(null!=s?s:""))&&void 0!==i?i:{match:0,mitigate:0,captcha:0,userId:""},{sessionStatus:m}=this.findBestMitigation(p,d,l,this.isUrlCaptchaPost(e.url,e.method));return{userId:g,sessionStatus:m,netaceaCookie:s,headerFingerprint:h,cookieFingerprint:u}}async ingest(e,t){var i;const{sessionStatus:a,netaceaCookie:s,headerFingerprint:o,cookieFingerprint:n}=await this.getNetaceaSession(e,t),r=String(null===(i=e.cf)||void 0===i?void 0:i.httpProtocol);return await this.callIngest({bytesSent:this.getHeaderValueOrDefault(t.headers,"content-length","0"),ip:this.getHeaderValueOrDefault(e.headers,"cf-connecting-ip"),method:e.method,path:new URL(e.url).pathname,protocol:r,referer:this.getHeaderValueOrDefault(e.headers,"referer"),requestTime:"0",sessionStatus:a,status:t.status.toString(),userAgent:this.getHeaderValueOrDefault(e.headers,"user-agent","-"),mitataCookie:s,integrationType:O.name.replace("@netacea/",""),integrationVersion:O.version,xForwardedFor:this.getHeaderValueOrDefault(e.headers,"x-forwarded-for"),headerFingerprint:o,cookieFingerprint:n})}async handleGetCaptchaRequest(e,t,i,a,s,o,n){var r;if(void 0===this.secretKey)throw new Error("Secret key is required to mitigate");const c=(0,_.checkMitataCookie)(e,t,this.secretKey),h=await this.makeMitigateAPICall(null===(r=c.mitata)||void 0===r?void 0:r.userId,t,i,n,a,!0,s,o);return{body:h.body,apiCallStatus:h.status,setCookie:[],sessionStatus:"",mitigation:"captcha",mitigated:!0}}async makeRequest({host:e,method:t,path:i,headers:a,body:s}){const o=`${e}${i}`,n=new Request(o,{method:t,body:s,headers:a}),r=await(0,K.fetch)(o,n),c={};return r.headers.forEach(((e,t)=>{null!==e&&(c[t]=e)})),{status:r.status,body:await r.text(),headers:c}}addHeadersToResponse(e,t){var i;if(void 0===t)return e;const a=null!==(i=e.headers.get("set-cookie"))&&void 0!==i?i:"",s=new Headers(e.headers);if(void 0!==t.setCookie)for(const e of t.setCookie)a.includes(e.split("=")[0])||s.append("set-cookie",e);return new Response(e.body,{headers:s,status:e.status,statusText:e.statusText})}addHeadersToRequest(e,t){if(void 0===t.injectHeaders)return e;const i=new Headers(e.headers);for(const[e,a]of Object.entries(t.injectHeaders))i.set(e,a);return new Request(e,{headers:i})}async handleResponse(e,t,i){if(void 0!==t)if(this.mitigationType===_.NetaceaMitigationType.MITIGATE){if(void 0!==t.response)return t.response}else this.mitigationType===_.NetaceaMitigationType.INJECT&&(e=this.addHeadersToRequest(e,t));if(this.ingestType===_.NetaceaIngestType.ORIGIN){const{sessionStatus:i,userId:a}=await this.getNetaceaSession(e,t);(0,V.addIngestOriginHeaders)(e,i,a)}const a=await i(e);return this.addHeadersToResponse(a,t)}getHeaderValueOrDefault(e,t,i=""){var a;return null!==(a=e.get(t))&&void 0!==a?a:i}getHeaderValuesArray(e,t){var i,a;return null!==(a=null===(i=e.get(t))||void 0===i?void 0:i.split(/; ?/))&&void 0!==a?a:[]}async getMitigationResponse(e){var t,i,a,s;const o=e.headers.get("cookie"),n=null!==(t=await this.readCookie(this.netaceaCookieName,o))&&void 0!==t?t:"",r=await this.readCookie(this.netaceaCaptchaCookieName,o),c=null!==(i=e.headers.get("cf-connecting-ip"))&&void 0!==i?i:"",h=null!==(a=e.headers.get("user-agent"))&&void 0!==a?a:"",u=this.enableDynamicCaptchaContentType?(0,q.getCaptchaPageContentType)(null!==(s=e.headers.get("Accept"))&&void 0!==s?s:void 0):(0,q.getCaptchaPageContentType)();return await this.processMitigateRequest({clientIp:c,getBodyFn:async()=>await Promise.resolve(e.body),method:e.method,mitata:n,mitataCaptcha:r,url:e.url,userAgent:h,captchaPageContentType:u})}async timeoutCheck(e,t){return await Promise.race([e,new Promise(((e,i)=>{setTimeout((()=>e(void 0)),t)}))])}getCookieHeader(e){return e.headers.get("cookie")}async encryptCookieValue(e){return void 0!==this.cookieEncryptionKey?await(0,j.encrypt)(e,this.cookieEncryptionKey):e}async decryptCookieValue(e){return void 0!==this.cookieEncryptionKey?await(0,j.decrypt)(e,this.cookieEncryptionKey):e}async runMitigation(e){try{switch(this.mitigationType){case _.NetaceaMitigationType.MITIGATE:return await this.mitigate(e);case _.NetaceaMitigationType.INJECT:return await this.inject(e);case _.NetaceaMitigationType.INGEST:return await this.processIngest(e);default:throw new Error(`Netacea Error: Mitigation type ${this.mitigationType} not recognised`)}}catch(e){return e instanceof Error&&console.error("Netacea FAILOPEN Error:",e,e.stack),{injectHeaders:{"x-netacea-captcha":"0","x-netacea-match":"0","x-netacea-mitigate":"0"},sessionStatus:""}}}async readCookie(e,t){if(null==t)return;if("string"==typeof t)return await this.readCookie(e,t.split(";"));const i=`${e}=`;for(const a of t){const t=a.split(";")[0].trimStart();if(t.startsWith(i)){const a=t.slice(i.length);if(this.encryptedCookies.includes(e))try{return await this.decryptCookieValue(a)}catch(e){return}return a}}}async getNetaceaCookieFromResponse(e){if(void 0===e)return;const t=e instanceof Response?e.headers.getSetCookie():e.setCookie;if(void 0!==t){const e=`${this.netaceaCookieName}=`;for(const i of t)if(i.startsWith(e))return await this.readCookie(this.netaceaCookieName,i)}}async getNetaceaCookieFromRequest(e){var t;const i=this.getHeaderValueOrDefault(e.headers,"cookie");return null!==(t=await this.readCookie(this.netaceaCookieName,i))&&void 0!==t?t:""}async callIngest(e){const t=this.constructWebLog(e);if(this.ingestType===_.NetaceaIngestType.KINESIS){if(void 0===this.kinesis)return void console.error("Netacea Error: Unable to log as Kinesis has not been defined.");try{await this.kinesis.ingest({...t,apiKey:this.apiKey},this.makeRequest)}catch(e){console.error("NETACEA Error: ",e.message)}}else{const e={"X-Netacea-API-Key":this.apiKey,"content-type":"application/json"},i=await this.makeIngestApiCall(e,t);if(200!==i.status)throw this.APIError(i)}}async makeIngestApiCall(e,t){return await this.makeRequest({host:this.ingestServiceUrl,method:"POST",path:"/",headers:e,body:JSON.stringify(t),timeout:this.timeout})}constructV2WebLog({ip:e,userAgent:t,status:i,method:a,path:s,protocol:o,referer:n,bytesSent:r,requestTime:c,mitataCookie:h,sessionStatus:u,integrationType:p,integrationVersion:d,xForwardedFor:l,headerFingerprint:g,cookieFingerprint:m}){var y;const f=new Date;let C;"/"!==s[0]&&(s=`/${s}`);const v=s.split("?");v.length>1&&(C=`?${v[1]}`);const k=v[0],S=null===(y=(0,_.matchMitataCookie)(h))||void 0===y?void 0:y.userId;return{status:i,method:a,bytes_sent:(0,_.safeParseInt)(r),referrer:""===n?void 0:n,request:`${a} ${k}${null!=C?C:""} ${o}`,request_time:(0,_.safeParseInt)(c),integration_type:p,integration_version:d,client:e,user_agent:t,bc_type:""===u?void 0:u,hour:f.getUTCHours(),minute:f.getUTCMinutes(),"@timestamp":f.toISOString().replace("Z","+00:00"),path:k,protocol:o,query:C,user_id:S,x_forwarded_for:l,optional:{headerFingerprint:g,cookieFingerprint:m}}}constructV1WebLog({ip:e,userAgent:t,status:i,method:a,path:s,protocol:o,referer:n,bytesSent:r,requestTime:c,mitataCookie:h,sessionStatus:u,integrationType:p,integrationVersion:d,xForwardedFor:l,headerFingerprint:g,cookieFingerprint:m}){return{Request:`${a} ${s} ${o}`,TimeLocal:(new Date).toUTCString(),RealIp:e,UserAgent:t,Status:i,RequestTime:null==c?void 0:c.toString(),BytesSent:null==r?void 0:r.toString(),Referer:""===n?"-":n,NetaceaUserIdCookie:null!=h?h:"",NetaceaMitigationApplied:null!=u?u:"",IntegrationType:null!=p?p:"",IntegrationVersion:null!=d?d:"",XForwardedFor:l,optional:{headerFingerprint:g,cookieFingerprint:m}}}constructWebLog(e){return e.bytesSent=""===e.bytesSent?"0":e.bytesSent,this.logVersion===_.NetaceaLogVersion.V2?this.constructV2WebLog(e):this.constructV1WebLog(e)}async check(e,t,i,a,s,o){var n,r;let c,h,u,p,d,l,g;if(void 0===this.secretKey)throw new Error("Secret key is required to mitigate");const m=(0,_.checkMitataCookie)(e,t,this.secretKey);if(!m.isPrimaryHashValid||m.requiresReissue){const e=await this.makeMitigateAPICall(null===(n=m.mitata)||void 0===n?void 0:n.userId,t,i,o,a,!1,null,s);c=e.status,h=e.match,u=e.mitigate,p=e.captcha,d=e.body,l=[await this.createMitata(t,null===(r=m.mitata)||void 0===r?void 0:r.userId,h,u,p,e.mitataMaxAge)],g=e.eventId}else c=-1,h=m.match,u=m.mitigate,p=m.captcha,d=void 0,l=[];return this.composeResult(d,l,c,h,u,p,!1,g)}async createMitata(e,t,i,a,s,o=86400,n=void 0){const r=[1,3,5].includes(s)||3===a?-60:this.mitataCookieExpirySeconds,c=null!=n?n:Math.floor(Date.now()/1e3)+r;if(void 0===this.secretKey)throw new Error("Cannot build cookie without secret key.");const h=[i,a,s].join("");let u=(0,_.createMitataCookie)(e,t,c,this.secretKey,h);return this.encryptedCookies.includes(this.netaceaCookieName)&&(u=await this.encryptCookieValue(u)),_.lib.cookie.netaceaSession.createNetaceaSetCookieString({cookieName:this.netaceaCookieName,cookieValue:u,otherAttributes:this.netaceaCookieAttributes})}async processCaptcha(e,t,i,a){const{status:s,match:o,mitigate:n,captcha:r,body:c,setCookie:h}=await this.makeCaptchaAPICall(e,t,i,a);return this.composeResult(c,h,s,o,n,r,!0)}async getMitataCaptchaFromHeaders(e){let t=e[_.dictionary.netaceaHeaders.mitataCaptcha];const i=parseInt(e[_.dictionary.netaceaHeaders.mitataCaptchaExpiry]);if(void 0!==t)return this.encryptedCookies.includes(this.netaceaCaptchaCookieName)&&(t=await this.encryptCookieValue(t)),_.lib.cookie.netaceaSession.createNetaceaCaptchaSetCookieString({cookieName:this.netaceaCaptchaCookieName,cookieValue:t,maxAgeAttribute:String(i),otherAttributes:this.netaceaCaptchaCookieAttributes})}async makeCaptchaAPICall(e,t,i,a){const s={"X-Netacea-API-Key":this.apiKey,"X-Netacea-Client-IP":t,"user-agent":i,"Content-Type":"application/x-www-form-urlencoded; charset=UTF-8"},o=(0,_.matchMitataCookie)(e);void 0!==o&&(s["X-Netacea-UserId"]=o.userId),void 0!==this.captchaSiteKey&&void 0!==this.captchaSecretKey&&(s["X-Netacea-Captcha-Site-Key"]=this.captchaSiteKey,s["X-Netacea-Captcha-Secret-Key"]=this.captchaSecretKey);const n=await this.makeRequest({host:this.mitigationServiceUrl,path:"/AtaVerifyCaptcha",headers:s,method:"POST",body:a,timeout:this.timeout});return await this.getApiCallResponseFromResponse(n,null==o?void 0:o.userId,t,"")}async getApiCallResponseFromResponse(e,t,i,a){var s;if(200!==e.status)throw this.APIError(e);const o=parseInt(e.headers[_.dictionary.netaceaHeaders.match]),n=parseInt(e.headers[_.dictionary.netaceaHeaders.mitigate]),r=parseInt(e.headers[_.dictionary.netaceaHeaders.captcha]);let c=parseInt(e.headers[_.dictionary.netaceaHeaders.mitataExpiry]);isNaN(c)&&(c=86400);const h=[await this.createMitata(i,t,o,n,r,c),await this.getMitataCaptchaFromHeaders(e.headers)].filter((e=>void 0!==e)),u=e.headers[_.dictionary.netaceaHeaders.eventId];if("application/json"===(null===(s=e.headers["content-type"])||void 0===s?void 0:s.toLowerCase())){if(void 0===this.netaceaCaptchaPath)throw new Error("netaceaCaptchaPath and URL must be defined to handle JSON captcha");e.body=await(0,q.modifyCaptchaJsonResponse)(e.body,this.netaceaCaptchaPath,a)}return{status:e.status,match:o,mitigate:n,captcha:r,setCookie:h,body:e.body,eventId:u,mitataMaxAge:c}}async buildCookieFromValues(e,t,i,a="/"){if(this.encryptedCookies.includes(e)){return`${e}=${await this.encryptCookieValue(t)}; Max-Age=${i}; Path=${a}`}return`${e}=${t}; Max-Age=${i}; Path=${a}`}buildCookieHeader(e){let t="",i="";for(const a in e){const s=e[a];void 0!==s&&(t=`${t}${i}${a}=${s}`,i="; ")}return t}async makeMitigateAPICall(e,t,i,a,s,o,n,r){const c={"X-Netacea-API-Key":this.apiKey,"X-Netacea-Client-IP":t,"user-agent":i,cookie:this.buildCookieHeader({_mitatacaptcha:a})};void 0!==e&&(c["X-Netacea-UserId"]=e),void 0!==this.captchaSiteKey&&void 0!==this.captchaSecretKey&&(c["X-Netacea-Captcha-Site-Key"]=this.captchaSiteKey,c["X-Netacea-Captcha-Secret-Key"]=this.captchaSecretKey),c["X-Netacea-Captcha-Content-Type"]=s;const h=await this.makeRequest({host:this.mitigationServiceUrl,path:o?"/captcha"+(null!==n?`?trackingId=${n}`:""):"/",headers:c,method:"GET",timeout:this.timeout});return await this.getApiCallResponseFromResponse(h,e,t,r)}composeResult(e,t,i,a,s,o,n,r){const c=this.findBestMitigation(a,s,o,n),h={body:e,apiCallStatus:i,setCookie:t,sessionStatus:c.sessionStatus,mitigation:c.mitigation,mitigated:[_.dictionary.mitigationTypes.block,_.dictionary.mitigationTypes.captcha].includes(c.mitigation)};if(this.mitigationType===_.NetaceaMitigationType.INJECT){const e={"x-netacea-match":c.parts.match.toString(),"x-netacea-mitigate":c.parts.mitigate.toString(),"x-netacea-captcha":c.parts.captcha.toString()};void 0!==r&&(e["x-netacea-event-id"]=r),h.injectHeaders=e}return h}findBestMitigation(e,t,i,a){var s,o,n;const r="unknown";a||(2===i?i=4:3===i&&(i=5));let c=null!==(s=_.dictionary.matchMap[e])&&void 0!==s?s:r+"_";c+=null!==(o=_.dictionary.mitigateMap[t])&&void 0!==o?o:r;let h=_.dictionary.bestMitigationMap[t];if(0!==i){c+=","+(null!==(n=_.dictionary.captchaMap[i])&&void 0!==n?n:r);const e=_.dictionary.bestMitigationCaptchaMap[i];void 0!==e&&(h=e)}return this.mitigationType===_.NetaceaMitigationType.INJECT&&(h=_.dictionary.mitigationTypes.none),{sessionStatus:c,mitigation:h,parts:{match:e,mitigate:t,captcha:i}}}APIError(e){let t="Unknown error";switch(e.status){case 403:t="Invalid credentials";break;case 500:t="Server error";break;case 502:t="Bad Gateway";break;case 503:t="Service Unavailable";break;case 400:t="Invalid request"}return new Error(`Error reaching Netacea API (${t}), status: ${e.status}`)}isUrlCaptchaPost(e,t){return e.includes("/AtaVerifyCaptcha")&&"post"===t.toLowerCase()}async processMitigateRequest(e){if(await(0,q.isUrlCaptchaGet)(e.url,e.method,this.netaceaCaptchaPath)){const t=await(0,q.getTrackingId)(e.url);return await this.handleGetCaptchaRequest(e.mitata,e.clientIp,e.userAgent,e.captchaPageContentType,t,e.url,e.mitataCaptcha)}return this.isUrlCaptchaPost(e.url,e.method)?await this.processCaptcha(e.mitata,e.clientIp,e.userAgent,await e.getBodyFn()):await this.check(e.mitata,e.clientIp,e.userAgent,e.captchaPageContentType,e.url,e.mitataCaptcha)}async setIngestOnlyMitataCookie(e){return{sessionStatus:"",setCookie:[await this.createMitata(_.ingestIgnoredIpValue,e,0,0,0,86400)]}}async processIngest(e){var t;if(void 0===this.secretKey)throw new Error("Secret key is required for ingest");const i=this.getCookieHeader(e),a=await this.readCookie(this.netaceaCookieName,i),s=(0,_.checkMitataCookie)(a,_.ingestIgnoredIpValue,this.secretKey);return s.isPrimaryHashValid?s.requiresReissue?await this.setIngestOnlyMitataCookie(null===(t=s.mitata)||void 0===t?void 0:t.userId):{sessionStatus:"",setCookie:[]}:await this.setIngestOnlyMitataCookie(void 0)}},function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.NetaceaMitigationType=void 0;const t=r;var i=c;Object.defineProperty(e,"NetaceaMitigationType",{enumerable:!0,get:function(){return i.NetaceaMitigationType}}),e.default=t.default}(n);var U=o(n);module.exports=U;
|
|
1
|
+
"use strict";var e=require("crypto"),t=require("buffer"),i=require("url"),a=require("querystring"),s=require("jose");function o(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var n={},r={},c={};!function(i){var a,s,o,n,r=e,c=t;i.NetaceaIngestType=void 0,(a=i.NetaceaIngestType||(i.NetaceaIngestType={})).ORIGIN="ORIGIN",a.HTTP="HTTP",a.KINESIS="KINESIS",a.NATIVE="NATIVE",i.NetaceaLogVersion=void 0,(s=i.NetaceaLogVersion||(i.NetaceaLogVersion={})).V1="V1",s.V2="V2",i.NetaceaMitigationType=void 0,(o=i.NetaceaMitigationType||(i.NetaceaMitigationType={})).MITIGATE="MITIGATE",o.INJECT="INJECT",o.INGEST="INGEST",i.NetaceaCookieV3IssueReason=void 0,(n=i.NetaceaCookieV3IssueReason||(i.NetaceaCookieV3IssueReason={})).CAPTCHA_GET="captcha_get",n.CAPTCHA_POST="captcha_post",n.EXPIRED_SESSION="expired_session",n.FORCED_REVALIDATION="forced_revalidation",n.INVALID_SESSION="invalid_session",n.IP_CHANGE="ip_change",n.NO_SESSION="no_session";const h=3e3;const u="_/@#/",p={none:"",block:"block",captcha:"captcha",allow:"allow",captchaPass:"captchapass"},d={0:p.none,1:p.block,2:p.none,3:p.block,4:p.block},l={1:p.captcha,2:p.captchaPass,3:p.captcha,4:p.allow,5:p.captcha},g={clientIP:"cip",userId:"uid",gracePeriod:"grp",cookieId:"cid",match:"mat",mitigate:"mit",captcha:"cap",issueTimestamp:"ist",issueReason:"isr"},m={checkAllPostRequests:"fCAPR"};var y=Object.freeze({__proto__:null,COOKIEDELIMITER:u,bestMitigationCaptchaMap:l,bestMitigationMap:d,captchaMap:{0:"",1:"captcha_serve",2:"captcha_pass",3:"captcha_fail",4:"captcha_cookiepass",5:"captcha_cookiefail"},captchaStatusCodes:{"":0,captchaServe:1,captchaPass:2,captchaFail:3,captchaCookiePass:4,captchaCookieFail:5},matchMap:{0:"",1:"ua_",2:"ip_",3:"visitor_",4:"datacenter_",5:"sev_",6:"organisation_",7:"asn_",8:"country_",9:"combination_"},mitigateMap:{0:"",1:"blocked",2:"allow",3:"hardblocked",4:"block"},mitigationTypes:p,netaceaCookieV3KeyMap:g,netaceaCookieV3OptionalKeyMap:m,netaceaHeaders:{match:"x-netacea-match",mitigate:"x-netacea-mitigate",captcha:"x-netacea-captcha",mitata:"x-netacea-mitata-value",mitataExpiry:"x-netacea-mitata-expiry",mitataCaptcha:"x-netacea-mitatacaptcha-value",mitataCaptchaExpiry:"x-netacea-mitatacaptcha-expiry",eventId:"x-netacea-event-id"},netaceaSettingsMap:{checkAllPostRequests:"checkAllPostRequests"}});const f="1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".split(""),C=/^(.*)_\/@#\/(.*)_\/@#\/(.*)_\/@#\/(.*)_\/@#\/((\d)(\d)(\d))$/;function v(e){if(void 0===e)return;const t=e.match(C);if(null!=t){const[,e,i,a,s,o,n,r,c]=t;return{signature:e,expiry:i,userId:a,ipHash:s,mitigationType:o,match:parseInt(n),mitigate:parseInt(r),captcha:parseInt(c)}}}function k(e=16,t=f){const i=r.randomBytes(e-1);return`c${Array.from(i).map((e=>t[e%t.length])).join("")}`}function S(e,t){const i=r.createHmac("sha256",t);return i.update(e),c.Buffer.from(i.digest("hex")).toString("base64")}function I(e){if(void 0===e||""===e)return;const t=e.split("&"),i={clientIP:"",userId:"",cookieId:"",gracePeriod:0,match:0,mitigate:0,captcha:0,issueTimestamp:0,issueReason:"",checkAllPostRequests:void 0};for(const e of t){const[t,a]=e.split("="),s=decodeURIComponent(a);let o=Object.keys(g).find((e=>g[e]===t));void 0===o&&(o=Object.keys(m).find((e=>m[e]===t)));let n=""===s?void 0:Number(s);void 0!==n&&isNaN(n)&&(n=s),i[o]=n}return i}function N(){return{mitata:void 0,requiresReissue:!1,isExpired:!1,shouldExpire:!1,isSameIP:!1,isPrimaryHashValid:!1,captcha:0,match:0,mitigate:0,issueReason:i.NetaceaCookieV3IssueReason.NO_SESSION}}function T(e,t){const i=e.split(";").map((e=>e.trim())).filter((e=>e.toLowerCase().startsWith(t.toLowerCase())))[0];return void 0!==i&&i.length>0?i?.replace(`${t}=`,""):void 0}function A(e,t=!1){if(""===e)return"";return e.replace(/ /g,"").split(";").map((e=>e.charAt(0).toUpperCase()+e.slice(1))).filter((e=>""!==e.trim())).filter(((e,i,a)=>{const s=e=>e.split("=")[0],o=s(e),n=a.map(s);return t?i===n.lastIndexOf(o):i===n.indexOf(o)})).join("; ")}function w(e){const t=A([e.otherAttributes??"",`Max-Age=${e.maxAgeAttribute??86400}`,"Path=/"].join("; "));return`${e.cookieName}=${e.cookieValue}; ${t}`}const b={cookie:{attributes:Object.freeze({__proto__:null,configureCookiesDomain:function(e,t){let i=e=A(e??"",!0),a=t=A(t??"",!0);if(void 0!==e&&void 0!==t){const s=T(e,"Domain"),o=T(t,"Domain");void 0!==s&&void 0!==o?a=t.replace(o,s):void 0!==s&&void 0===o?a=t+(""!==t?`; Domain=${s}`:`Domain=${s}`):void 0===s&&void 0!==o&&(i=e+(""!==e?`; Domain=${o}`:`Domain=${o}`))}else if(void 0!==e&&void 0===t){const t=T(e,"Domain");void 0!==t&&(a=`Domain=${t}`)}else if(void 0===e&&void 0!==t){const e=T(t,"Domain");void 0!==e&&(i=`Domain=${e}`)}return{cookieAttributes:""!==i?i:void 0,captchaCookieAttributes:""!==a?a:void 0}},extractAndRemoveCookieAttr:function(e,t){const i=T(e,t);if(void 0!==i){return{extractedAttribute:i,cookieAttributes:e.replace(/ /g,"").replace(`${t}=${i}`,"").split(";").filter((e=>e.length>0)).join("; ")}}return{extractedAttribute:void 0,cookieAttributes:e}},extractCookieAttr:T,removeDuplicateAttrs:A}),netaceaSession:Object.freeze({__proto__:null,createNetaceaCaptchaSetCookieString:function(e){return w({...e,cookieName:e.cookieName??"_mitatacaptcha"})},createNetaceaSetCookieString:function(e){return w({...e,cookieName:e.cookieName??"_mitata"})},createSetCookieString:w})}};i.checkMitataCookie=function(e,t,i){const a={mitata:void 0,requiresReissue:!1,isExpired:!1,shouldExpire:!1,isSameIP:!1,isPrimaryHashValid:!1,captcha:0,match:0,mitigate:0};if("string"!=typeof e||""===e)return a;const s=v(e);if(void 0!==s){const e=[s.expiry,s.userId,s.ipHash,s.mitigationType].join(u),a=Math.floor(Date.now()/1e3),o=parseInt(s.expiry)<a,n=[1,3,5].includes(s.captcha),r=3===s.mitigate,c=n||r,h=S(t+"|"+s.expiry,i),p=s.ipHash===h;return{mitata:s,requiresReissue:o||!p,isExpired:o,shouldExpire:c,isSameIP:p,isPrimaryHashValid:s.signature===S(e,i),match:s.match,mitigate:s.mitigate,captcha:s.captcha}}return a},i.checkNetaceaCookieV3=function(e,t){if(void 0===e||""===e)return N();const i=I(e);if(void 0!==i){const e=Math.floor(Date.now()/1e3),a=i.issueTimestamp+i.gracePeriod<e,s=t===i.clientIP,o=[1,3,5].includes(i.captcha),n=3===i.mitigate;return{mitata:i,requiresReissue:a||!s,isExpired:a,shouldExpire:o||n,isSameIP:s,isPrimaryHashValid:!0,match:i.match,mitigate:i.mitigate,captcha:i.captcha,issueReason:i.issueReason}}return N()},i.configureMitataExpiry=function(e,t){return void 0===t?e===i.NetaceaMitigationType.INGEST?3600:60:t},i.cookieIsNetaceaV3Format=function(e){return void 0!==e&&e.split("&").map((e=>e.split("=")[0])).filter((e=>!Object.values(m).includes(e))).every((e=>Object.values(g).includes(e)))},i.correctTimeout=function(e){return e<=0?h:e},i.createMitataCookie=function(e,t,i,a,s="000"){void 0===t&&(t=k());const o=[i,t,S(e+"|"+String(i),a),s].join(u);return`${S(o,a)}${u}${o}`},i.createNetaceaCookieV3=function(e){return Object.entries(e).filter((([e,t])=>void 0!==t)).map((([e,t])=>e in m?`${m[e]}=${encodeURIComponent(t)}`:`${g[e]}=${encodeURIComponent(t)}`)).join("&")},i.defaultInvalidResponse=N,i.dictionary=y,i.generateId=k,i.hexSha256=S,i.ingestIgnoredIpValue="ignored",i.lib=b,i.matchMitataCookie=v,i.matchNetaceaCookieV3=I,i.objectIsNetaceaCookieV3=function(e){if("object"!=typeof e||null===e)return!1;for(const t of Object.keys(g)){if(!(t in e))return!1;if(void 0===e[t])return!1}return!0},i.safeParseInt=function(e,t=0){return isNaN(e)?t:parseInt(e)},i.warmupCookie={cookie:"MzBkZDEwYjc0ZmIyMzQ4YmY0OTlhNTkyNjY0MDRjMjhjNmQ5Y2RlYjVkYzVkMDQyZmEzODU4MDBiN2MwNTk1OQ==_/@#/1653044256_/@#/UUID_/@#/NjEyOWIzY2JiMjE5NjcwMThlYjg5NDYzY2YyMDZlYjE0ZDg2NTRjYmMxODg5Y2I4Y2U2NGFjZDAxOTdhMGFmNA==_/@#/000",secretKey:"EXAMPLE_SECRET_KEY",clientIP:"192.168.0.1"}}(c);var h={},u={},p={},d={},l=function(e){return new g(e)};function g(e){this.capacity=0|e,this.map=Object.create(null),this.list=new m}function m(){this.firstNode=null,this.lastNode=null}function y(e,t){this.key=e,this.val=t,this.prev=null,this.next=null}g.prototype.get=function(e){var t=this.map[e];if(null!=t)return this.used(t),t.val},g.prototype.set=function(e,t){var i=this.map[e];if(null!=i)i.val=t;else{if(this.capacity||this.prune(),!this.capacity)return!1;i=new y(e,t),this.map[e]=i,this.capacity--}return this.used(i),!0},g.prototype.used=function(e){this.list.moveToFront(e)},g.prototype.prune=function(){var e=this.list.pop();null!=e&&(delete this.map[e.key],this.capacity++)},m.prototype.moveToFront=function(e){this.firstNode!=e&&(this.remove(e),null==this.firstNode?(this.firstNode=e,this.lastNode=e,e.prev=null,e.next=null):(e.prev=null,e.next=this.firstNode,e.next.prev=e,this.firstNode=e))},m.prototype.pop=function(){var e=this.lastNode;return null!=e&&this.remove(e),e},m.prototype.remove=function(e){this.firstNode==e?this.firstNode=e.next:null!=e.prev&&(e.prev.next=e.next),this.lastNode==e?this.lastNode=e.prev:null!=e.next&&(e.next.prev=e.prev)},function(t){var s=d,o=i,n=a,r=e,c=l(1e3);function h(e,t,i){return r.createHmac("sha256",e).update(t,"utf8").digest(i)}function u(e,t){return r.createHash("sha256").update(e,"utf8").digest(t)}function p(e){return e.replace(/[!'()*]/g,(function(e){return"%"+e.charCodeAt(0).toString(16).toUpperCase()}))}function g(e){return p(encodeURIComponent(e))}var m={authorization:!0,connection:!0,"x-amzn-trace-id":!0,"user-agent":!0,expect:!0,"presigned-expires":!0,range:!0};function y(e,t){"string"==typeof e&&(e=o.parse(e));var i=e.headers=e.headers||{},a=(!this.service||!this.region)&&this.matchHost(e.hostname||e.host||i.Host||i.host);this.request=e,this.credentials=t||this.defaultCredentials(),this.service=e.service||a[0]||"",this.region=e.region||a[1]||"us-east-1","email"===this.service&&(this.service="ses"),!e.method&&e.body&&(e.method="POST"),i.Host||i.host||(i.Host=e.hostname||e.host||this.createHost(),e.port&&(i.Host+=":"+e.port)),e.hostname||e.host||(e.hostname=i.Host||i.host),this.isCodeCommitGit="codecommit"===this.service&&"GIT"===e.method}y.prototype.matchHost=function(e){var t=((e||"").match(/([^\.]+)\.(?:([^\.]*)\.)?amazonaws\.com(\.cn)?$/)||[]).slice(1,3);if("es"===t[1]&&(t=t.reverse()),"s3"==t[1])t[0]="s3",t[1]="us-east-1";else for(var i=0;i<2;i++)if(/^s3-/.test(t[i])){t[1]=t[i].slice(3),t[0]="s3";break}return t},y.prototype.isSingleRegion=function(){return["s3","sdb"].indexOf(this.service)>=0&&"us-east-1"===this.region||["cloudfront","ls","route53","iam","importexport","sts"].indexOf(this.service)>=0},y.prototype.createHost=function(){var e=this.isSingleRegion()?"":"."+this.region;return("ses"===this.service?"email":this.service)+e+".amazonaws.com"},y.prototype.prepareRequest=function(){this.parsePath();var e,t=this.request,i=t.headers;t.signQuery?(this.parsedPath.query=e=this.parsedPath.query||{},this.credentials.sessionToken&&(e["X-Amz-Security-Token"]=this.credentials.sessionToken),"s3"!==this.service||e["X-Amz-Expires"]||(e["X-Amz-Expires"]=86400),e["X-Amz-Date"]?this.datetime=e["X-Amz-Date"]:e["X-Amz-Date"]=this.getDateTime(),e["X-Amz-Algorithm"]="AWS4-HMAC-SHA256",e["X-Amz-Credential"]=this.credentials.accessKeyId+"/"+this.credentialString(),e["X-Amz-SignedHeaders"]=this.signedHeaders()):(t.doNotModifyHeaders||this.isCodeCommitGit||(!t.body||i["Content-Type"]||i["content-type"]||(i["Content-Type"]="application/x-www-form-urlencoded; charset=utf-8"),!t.body||i["Content-Length"]||i["content-length"]||(i["Content-Length"]=Buffer.byteLength(t.body)),!this.credentials.sessionToken||i["X-Amz-Security-Token"]||i["x-amz-security-token"]||(i["X-Amz-Security-Token"]=this.credentials.sessionToken),"s3"!==this.service||i["X-Amz-Content-Sha256"]||i["x-amz-content-sha256"]||(i["X-Amz-Content-Sha256"]=u(this.request.body||"","hex")),i["X-Amz-Date"]||i["x-amz-date"]?this.datetime=i["X-Amz-Date"]||i["x-amz-date"]:i["X-Amz-Date"]=this.getDateTime()),delete i.Authorization,delete i.authorization)},y.prototype.sign=function(){return this.parsedPath||this.prepareRequest(),this.request.signQuery?this.parsedPath.query["X-Amz-Signature"]=this.signature():this.request.headers.Authorization=this.authHeader(),this.request.path=this.formatPath(),this.request},y.prototype.getDateTime=function(){if(!this.datetime){var e=this.request.headers,t=new Date(e.Date||e.date||new Date);this.datetime=t.toISOString().replace(/[:\-]|\.\d{3}/g,""),this.isCodeCommitGit&&(this.datetime=this.datetime.slice(0,-1))}return this.datetime},y.prototype.getDate=function(){return this.getDateTime().substr(0,8)},y.prototype.authHeader=function(){return["AWS4-HMAC-SHA256 Credential="+this.credentials.accessKeyId+"/"+this.credentialString(),"SignedHeaders="+this.signedHeaders(),"Signature="+this.signature()].join(", ")},y.prototype.signature=function(){var e,t,i,a=this.getDate(),s=[this.credentials.secretAccessKey,a,this.region,this.service].join(),o=c.get(s);return o||(e=h("AWS4"+this.credentials.secretAccessKey,a),t=h(e,this.region),i=h(t,this.service),o=h(i,"aws4_request"),c.set(s,o)),h(o,this.stringToSign(),"hex")},y.prototype.stringToSign=function(){return["AWS4-HMAC-SHA256",this.getDateTime(),this.credentialString(),u(this.canonicalString(),"hex")].join("\n")},y.prototype.canonicalString=function(){this.parsedPath||this.prepareRequest();var e,t=this.parsedPath.path,i=this.parsedPath.query,a=this.request.headers,s="",o="s3"!==this.service,n="s3"===this.service||this.request.doNotEncodePath,r="s3"===this.service,c="s3"===this.service;if(e="s3"===this.service&&this.request.signQuery?"UNSIGNED-PAYLOAD":this.isCodeCommitGit?"":a["X-Amz-Content-Sha256"]||a["x-amz-content-sha256"]||u(this.request.body||"","hex"),i){var h=Object.keys(i).reduce((function(e,t){return t?(e[g(t)]=Array.isArray(i[t])&&c?i[t][0]:i[t],e):e}),{}),p=[];Object.keys(h).sort().forEach((function(e){Array.isArray(h[e])?h[e].map(g).sort().forEach((function(t){p.push(e+"="+t)})):p.push(e+"="+g(h[e]))})),s=p.join("&")}return"/"!==t&&(o&&(t=t.replace(/\/{2,}/g,"/")),"/"!==(t=t.split("/").reduce((function(e,t){return o&&".."===t?e.pop():o&&"."===t||(n&&(t=decodeURIComponent(t.replace(/\+/g," "))),e.push(g(t))),e}),[]).join("/"))[0]&&(t="/"+t),r&&(t=t.replace(/%2F/g,"/"))),[this.request.method||"GET",t,s,this.canonicalHeaders()+"\n",this.signedHeaders(),e].join("\n")},y.prototype.canonicalHeaders=function(){var e=this.request.headers;return Object.keys(e).filter((function(e){return null==m[e.toLowerCase()]})).sort((function(e,t){return e.toLowerCase()<t.toLowerCase()?-1:1})).map((function(t){return t.toLowerCase()+":"+e[t].toString().trim().replace(/\s+/g," ")})).join("\n")},y.prototype.signedHeaders=function(){return Object.keys(this.request.headers).map((function(e){return e.toLowerCase()})).filter((function(e){return null==m[e]})).sort().join(";")},y.prototype.credentialString=function(){return[this.getDate(),this.region,this.service,"aws4_request"].join("/")},y.prototype.defaultCredentials=function(){var e=process.env;return{accessKeyId:e.AWS_ACCESS_KEY_ID||e.AWS_ACCESS_KEY,secretAccessKey:e.AWS_SECRET_ACCESS_KEY||e.AWS_SECRET_KEY,sessionToken:e.AWS_SESSION_TOKEN}},y.prototype.parsePath=function(){var e=this.request.path||"/";/[^0-9A-Za-z;,/?:@&=+$\-_.!~*'()#%]/.test(e)&&(e=encodeURI(decodeURI(e)));var t=e.indexOf("?"),i=null;t>=0&&(i=n.parse(e.slice(t+1)),e=e.slice(0,t)),this.parsedPath={path:e,query:i}},y.prototype.formatPath=function(){var e=this.parsedPath.path,t=this.parsedPath.query;return t?(null!=t[""]&&delete t[""],e+"?"+p(n.stringify(t))):e},s.RequestSigner=y,s.sign=function(e,t){return new y(e,t).sign()}}();var f={};Object.defineProperty(f,"__esModule",{value:!0}),f.API_VERSION=f.REGION=f.PAYLOAD_TYPE=f.STATE=void 0,f.STATE={ACTIVE:"ACTIVE",UPDATING:"UPDATING",CREATING:"CREATING",DELETING:"DELETING"},f.PAYLOAD_TYPE="string",f.REGION="eu-west-1",f.API_VERSION="2013-12-02",Object.defineProperty(p,"__esModule",{value:!0}),p.signRequest=void 0;const C=d,v=f;function k(e,t){const i=[];for(let a=0;a<e.length;a+=t){const s=e.slice(a,a+t);i.push({Data:Buffer.from(JSON.stringify(s)).toString("base64"),PartitionKey:Date.now().toString()})}return i}p.signRequest=function(e,t,i){const{accessKeyId:a,secretAccessKey:s}=e,o={Records:k(t,i),PartitionKey:Date.now().toString(),StreamName:e.streamName};return C.sign({service:"kinesis",body:JSON.stringify(o),headers:{"Content-Type":"application/x-amz-json-1.1","X-Amz-Target":"Kinesis_20131202.PutRecords"},region:v.REGION},{accessKeyId:a,secretAccessKey:s})},Object.defineProperty(u,"__esModule",{value:!0});const S=p;u.default=class{constructor({kinesisStreamName:e,kinesisAccessKey:t,kinesisSecretKey:i,maxLogAgeSeconds:a,logBatchSize:s}){this.logBatchSize=20,this.maxLogAgeSeconds=10,this.logCache=[],this.intervalSet=!1,this.kinesisStreamName=e,this.kinesisAccessKey=t,this.kinesisSecretKey=i,void 0!==a&&a<this.maxLogAgeSeconds&&a>0&&(this.maxLogAgeSeconds=a),void 0!==s&&(this.logBatchSize=s)}async putToKinesis(e){if(0===this.logCache.length)return;const t=[...this.logCache];this.logCache=[];try{const i=(0,S.signRequest)({streamName:this.kinesisStreamName,accessKeyId:this.kinesisAccessKey,secretAccessKey:this.kinesisSecretKey},t,this.logBatchSize);await e({headers:i.headers,host:`https://${i.hostname}`,method:i.method,path:i.path,body:i.body})}catch(e){this.logCache.push(...t),console.error(e)}}async ingest(e,t){this.logCache.push(e),this.intervalSet||(this.intervalSet=!0,await async function(e){await new Promise((t=>{setTimeout(t,e)}))}(1e3*this.maxLogAgeSeconds),await this.putToKinesis(t),this.intervalSet=!1),this.logCache.length>=this.logBatchSize&&await this.putToKinesis(t)}},Object.defineProperty(h,"__esModule",{value:!0});const I=u;h.default=I.default;var N={name:"@netacea/cloudflare",version:"5.2.44",description:"Netacea Cloudflare CDN Integration",main:"dist/index.js",types:"dist/index.d.ts",files:["dist/"],scripts:{test:"npm run test:unit && npm run test:integration:no-clean","test:unit":"npx nyc tape -r ts-node/register './tests/tape/*.test.ts'","test:integration":"npx nyc mocha --timeout 60000 -r ts-node/register './tests/mocha/*.test.ts'","test:integration:no-clean":"npx nyc --no-clean mocha --timeout 60000 -r ts-node/register './tests/mocha/*.test.ts'",lint:"npx eslint . --ext ts","lint:fix":"npx eslint . --ext ts --fix",rollup:"npx rollup -c rollup.config.mjs && npx rollup -c rollup-types.config.mjs",prepublishOnly:"npm run build",build:"npx tsc --project tsconfig.build.json && npm run rollup",postpack:"npx netacea-bundler postpack",prepack:"npx netacea-bundler prepack"},author:"Netacea <npm@netacea.com> (https://netacea.com)",publishConfig:{access:"public"},license:"ISC",dependencies:{"@netacea/kinesisingest":"^1.5.44","@netacea/netaceaintegrationbase":"^2.0.26",jose:"^4.11.2"},devDependencies:{"@cloudflare/workers-types":"^4.20231025.0","@netacea/bundler":"^1.0.0","@netacea/netaceaintegrationtestrunner":"^1.8.21","@rollup/plugin-commonjs":"^25.0.0","@rollup/plugin-json":"^6.0.0","@rollup/plugin-node-resolve":"^15.1.0","@rollup/plugin-replace":"^5.0.2","@rollup/plugin-terser":"^0.4.3","@rollup/plugin-typescript":"^11.1.1","@types/chai":"^4.3.5","@types/mocha":"^10.0.1","@types/node":"^20.9.1","@types/node-fetch":"^2.5.7","@types/proxyquire":"^1.3.28","@types/sinon":"^9.0.8","@types/tape":"^4.13.0",chai:"^4.3.7",mocha:"^10.2.0",nyc:"^15.1.0",proxyquire:"^2.1.3",rollup:"^3.23.0","rollup-plugin-dts":"^6.0.2","rollup-plugin-node-externals":"^6.1.1",sinon:"^9.1.0",tape:"^5.0.1","ts-node":"^10.9.1",typescript:"^5.2.2"},gitHead:"6b8dc377316ba9526910e1f44f17fbee44e4a51d"},T={};Object.defineProperty(T,"__esModule",{value:!0}),T.fetch=void 0,T.fetch=globalThis.fetch.bind(globalThis);var A={};Object.defineProperty(A,"__esModule",{value:!0}),A.decrypt=A.encrypt=void 0;const w=s;A.encrypt=async function(e,t){const i=w.base64url.decode(t),a=(new TextEncoder).encode(e);return await new w.CompactEncrypt(a).setProtectedHeader({alg:"dir",enc:"A256GCM"}).encrypt(i)},A.decrypt=async function(e,t){const i=w.base64url.decode(t),{plaintext:a}=await w.compactDecrypt(e,i,{keyManagementAlgorithms:["dir"],contentEncryptionAlgorithms:["A256GCM"]});return(new TextDecoder).decode(a)};var b={};Object.defineProperty(b,"__esModule",{value:!0}),b.isUrlCaptchaGet=b.getTrackingId=b.modifyCaptchaJsonResponse=b.getCaptchaPageContentType=void 0,b.getCaptchaPageContentType=function(e){if(void 0===e)return"text/html";const t=e.toLowerCase(),i=t.includes("application/html")||t.includes("text/html"),a=t.includes("application/json");return!i&&a?"application/json":"text/html"},b.modifyCaptchaJsonResponse=async function(e,t,i){const a=e.length>0?JSON.parse(e).trackingId:void 0,{hostname:s}=new URL(i);return t.length<2||void 0===a?"":JSON.stringify({captchaRelativeURL:`${t}?trackingId=${a}`,captchaAbsoluteURL:`https://${s}${t}?trackingId=${a}`})},b.getTrackingId=async function(e){try{const{searchParams:t}=new URL(e);return t.get("trackingId")}catch(e){return null}},b.isUrlCaptchaGet=async function(e,t,i){if(void 0===i||""===i)return!1;i.startsWith("/")||(i="/"+i);const{pathname:a,search:s}=new URL(e);return a.includes(i)&&s.includes("trackingId")&&"get"===t.toLowerCase()};var x={};async function E(e,t){const i=(new TextEncoder).encode(t),a=await crypto.subtle.digest(e,i);return Array.from(new Uint8Array(a)).map((e=>e.toString(16).padStart(2,"0"))).join("")}function P(e){const t=[];return e.forEach(((e,i)=>{const a=i.toLowerCase();"cookie"===a||"referer"===a||a.startsWith("x-netacea-")||t.push(i)})),t.join(",")}async function M(e){let t="";try{t=await E("SHA-256",e)}catch(e){t=""}return t}Object.defineProperty(x,"__esModule",{value:!0}),x.hashCookieNames=x.hashHeaders=x.extractHeaderNames=x.hashString=void 0,x.hashString=E,x.extractHeaderNames=P,x.hashHeaders=async function(e){const t=P(e);return await M(t)},x.hashCookieNames=async function(e){const t=e.join(",");return await M(t)};var R={};Object.defineProperty(R,"__esModule",{value:!0}),R.addIngestOriginHeaders=void 0;const _=N;R.addIngestOriginHeaders=function(e,t,i){e.headers.set("x-netacea-integration-type",_.name.replace("@netacea/","")),e.headers.set("x-netacea-integration-version",_.version),e.headers.set("x-netacea-userid",i),e.headers.set("x-netacea-bc-type",t)},Object.defineProperty(r,"__esModule",{value:!0});const H=c,O=h,j=N,K=T,q=A,D=b,V=x,$=R,{configureCookiesDomain:U}=H.lib.cookie.attributes;r.default=class{constructor(e){this.encryptedCookies=[],this.enableDynamicCaptchaContentType=!1;const{apiKey:t,secretKey:i,timeout:a=3e3,mitigationServiceUrl:s="https://mitigations.netacea.net",ingestServiceUrl:o="https://ingest.netacea.net",mitigationType:n=H.NetaceaMitigationType.INGEST,captchaSiteKey:r,captchaSecretKey:c,ingestType:h=H.NetaceaIngestType.HTTP,kinesis:u,logVersion:p,mitataCookieExpirySeconds:d,netaceaCookieExpirySeconds:l,netaceaCookieName:g,netaceaCaptchaCookieName:m,enableDynamicCaptchaContentType:y=!1,captchaHeader:f,netaceaCaptchaPath:C}=e;if(null==t)throw new Error("apiKey is a required parameter");this.apiKey=t,this.secretKey=i,this.mitigationServiceUrl=s,this.ingestServiceUrl=o,this.mitigationType=n,this.ingestType=null!=h?h:H.NetaceaIngestType.HTTP,this.logVersion=null!=p?p:H.NetaceaLogVersion.V1,this.ingestType===H.NetaceaIngestType.KINESIS&&(void 0===u?console.warn(`NETACEA WARN: no kinesis args provided, when ingestType is ${this.ingestType}`):this.kinesis=new O.default({...u,apiKey:this.apiKey})),void 0===r&&void 0===c||(this.captchaSiteKey=r,this.captchaSecretKey=c),this.timeout=(0,H.correctTimeout)(a),this.netaceaCookieName=null!=g?g:"_mitata",this.netaceaCaptchaCookieName=null!=m?m:"_mitatacaptcha";const{cookieAttributes:v,captchaCookieAttributes:k}=U(e.netaceaCookieAttributes,e.netaceaCaptchaCookieAttributes);this.netaceaCookieAttributes=null!=v?v:"",this.netaceaCaptchaCookieAttributes=null!=k?k:"",this.encryptedCookies=[this.netaceaCookieName,this.netaceaCaptchaCookieName],this.mitataCookieExpirySeconds=function(e,t){return void 0===t?e===H.NetaceaMitigationType.INGEST?3600:60:t}(n,null!=l?l:d),this.cookieEncryptionKey=e.cookieEncryptionKey,Boolean(C)&&"string"==typeof C&&(this.netaceaCaptchaPath=C.startsWith("/")?C:`/${C}`),void 0!==this.netaceaCaptchaPath&&(this.enableDynamicCaptchaContentType="boolean"==typeof y?y:"true"===y),this.captchaHeader=f}async run(e,t){const i=new Request(e.request),a=await this.timeoutCheck(this.runMitigation(i),this.timeout);return await this.handleResponse(i,a,t)}async inject(e){const t=await this.getMitigationResponse(e);return{injectHeaders:t.injectHeaders,sessionStatus:t.sessionStatus,setCookie:t.setCookie}}async mitigate(e){const t=await this.getMitigationResponse(e);if(t.mitigated){const i=new Headers;if(!await(0,D.isUrlCaptchaGet)(e.url,e.method,this.netaceaCaptchaPath))for(const e of t.setCookie)i.append("set-cookie",e);let a="Forbidden";return"captcha"===t.mitigation&&(void 0!==this.captchaHeader&&i.append(this.captchaHeader.name,this.captchaHeader.value),i.append("content-type","text/html; charset=UTF-8"),a=t.body),{response:new Response(a,{status:403,statusText:"Forbidden",headers:i}),setCookie:t.setCookie,sessionStatus:t.sessionStatus}}if(this.isUrlCaptchaPost(e.url,e.method)){const e=new Headers;for(const i of t.setCookie)e.append("set-cookie",i);return{response:new Response(t.body,{status:200,statusText:"OK",headers:e}),setCookie:t.setCookie,sessionStatus:t.sessionStatus}}return{setCookie:t.setCookie,sessionStatus:t.sessionStatus}}async getNetaceaSession(e,t){var i;const a=void 0!==t?await this.getNetaceaCookieFromResponse(t):void 0,s=null!=a?a:await this.getNetaceaCookieFromRequest(e),{headers:o}=e,n=await(0,V.hashHeaders)(o),r=this.getHeaderValuesArray(o,"cookie").map((e=>e.split("=")[0])).flat(),c=await(0,V.hashCookieNames)(r),h=""===n?n:`h_${n.substring(1,15)}`,u=""===c?c:`c_${c.substring(1,15)}`,{match:p,mitigate:d,captcha:l,userId:g}=null!==(i=(0,H.matchMitataCookie)(null!=s?s:""))&&void 0!==i?i:{match:0,mitigate:0,captcha:0,userId:""},{sessionStatus:m}=this.findBestMitigation(p,d,l,this.isUrlCaptchaPost(e.url,e.method));return{userId:g,sessionStatus:m,netaceaCookie:s,headerFingerprint:h,cookieFingerprint:u}}async ingest(e,t){var i;const{sessionStatus:a,netaceaCookie:s,headerFingerprint:o,cookieFingerprint:n}=await this.getNetaceaSession(e,t),r=String(null===(i=e.cf)||void 0===i?void 0:i.httpProtocol);await this.callIngest({bytesSent:this.getHeaderValueOrDefault(t.headers,"content-length","0"),ip:this.getHeaderValueOrDefault(e.headers,"cf-connecting-ip"),method:e.method,path:new URL(e.url).pathname,protocol:r,referer:this.getHeaderValueOrDefault(e.headers,"referer"),requestTime:"0",sessionStatus:a,status:t.status.toString(),userAgent:this.getHeaderValueOrDefault(e.headers,"user-agent","-"),mitataCookie:s,integrationType:j.name.replace("@netacea/",""),integrationVersion:j.version,xForwardedFor:this.getHeaderValueOrDefault(e.headers,"x-forwarded-for"),headerFingerprint:o,cookieFingerprint:n})}async handleGetCaptchaRequest(e,t,i,a,s,o,n){var r;if(void 0===this.secretKey)throw new Error("Secret key is required to mitigate");const c=(0,H.checkMitataCookie)(e,t,this.secretKey),h=await this.makeMitigateAPICall(null===(r=c.mitata)||void 0===r?void 0:r.userId,t,i,n,a,!0,s,o);return{body:h.body,apiCallStatus:h.status,setCookie:[],sessionStatus:"",mitigation:"captcha",mitigated:!0}}async makeRequest({host:e,method:t,path:i,headers:a,body:s}){const o=`${e}${i}`,n=new Request(o,{method:t,body:s,headers:a}),r=await(0,K.fetch)(o,n),c={};return r.headers.forEach(((e,t)=>{null!==e&&(c[t]=e)})),{status:r.status,body:await r.text(),headers:c}}addHeadersToResponse(e,t){var i;if(void 0===t)return e;const a=null!==(i=e.headers.get("set-cookie"))&&void 0!==i?i:"",s=new Headers(e.headers);if(void 0!==t.setCookie)for(const e of t.setCookie)a.includes(e.split("=")[0])||s.append("set-cookie",e);return new Response(e.body,{headers:s,status:e.status,statusText:e.statusText})}addHeadersToRequest(e,t){if(void 0===t.injectHeaders)return e;const i=new Headers(e.headers);for(const[e,a]of Object.entries(t.injectHeaders))i.set(e,a);return new Request(e,{headers:i})}async handleResponse(e,t,i){if(void 0!==t)if(this.mitigationType===H.NetaceaMitigationType.MITIGATE){if(void 0!==t.response)return t.response}else this.mitigationType===H.NetaceaMitigationType.INJECT&&(e=this.addHeadersToRequest(e,t));if(this.ingestType===H.NetaceaIngestType.ORIGIN){const{sessionStatus:i,userId:a}=await this.getNetaceaSession(e,t);(0,$.addIngestOriginHeaders)(e,i,a)}const a=await i(e);return this.addHeadersToResponse(a,t)}getHeaderValueOrDefault(e,t,i=""){var a;return null!==(a=e.get(t))&&void 0!==a?a:i}getHeaderValuesArray(e,t){var i,a;return null!==(a=null===(i=e.get(t))||void 0===i?void 0:i.split(/; ?/))&&void 0!==a?a:[]}async getMitigationResponse(e){var t,i,a,s;const o=e.headers.get("cookie"),n=null!==(t=await this.readCookie(this.netaceaCookieName,o))&&void 0!==t?t:"",r=await this.readCookie(this.netaceaCaptchaCookieName,o),c=null!==(i=e.headers.get("cf-connecting-ip"))&&void 0!==i?i:"",h=null!==(a=e.headers.get("user-agent"))&&void 0!==a?a:"",u=this.enableDynamicCaptchaContentType?(0,D.getCaptchaPageContentType)(null!==(s=e.headers.get("Accept"))&&void 0!==s?s:void 0):(0,D.getCaptchaPageContentType)();return await this.processMitigateRequest({clientIp:c,getBodyFn:async()=>await Promise.resolve(e.body),method:e.method,mitata:n,mitataCaptcha:r,url:e.url,userAgent:h,captchaPageContentType:u})}async timeoutCheck(e,t){return await Promise.race([e,new Promise(((e,i)=>{setTimeout((()=>{e(void 0)}),t)}))])}getCookieHeader(e){return e.headers.get("cookie")}async encryptCookieValue(e){return void 0!==this.cookieEncryptionKey?await(0,q.encrypt)(e,this.cookieEncryptionKey):e}async decryptCookieValue(e){return void 0!==this.cookieEncryptionKey?await(0,q.decrypt)(e,this.cookieEncryptionKey):e}async runMitigation(e){try{switch(this.mitigationType){case H.NetaceaMitigationType.MITIGATE:return await this.mitigate(e);case H.NetaceaMitigationType.INJECT:return await this.inject(e);case H.NetaceaMitigationType.INGEST:return await this.processIngest(e);default:throw new Error(`Netacea Error: Mitigation type ${this.mitigationType} not recognised`)}}catch(e){return e instanceof Error&&console.error("Netacea FAILOPEN Error:",e,e.stack),{injectHeaders:{"x-netacea-captcha":"0","x-netacea-match":"0","x-netacea-mitigate":"0"},sessionStatus:""}}}async readCookie(e,t){if(null==t)return;if("string"==typeof t)return await this.readCookie(e,t.split(";"));const i=`${e}=`;for(const a of t){const t=a.split(";")[0].trimStart();if(t.startsWith(i)){const a=t.slice(i.length);if(this.encryptedCookies.includes(e))try{return await this.decryptCookieValue(a)}catch(e){return}return a}}}async getNetaceaCookieFromResponse(e){if(void 0===e)return;const t=e instanceof Response?e.headers.getSetCookie():e.setCookie;if(void 0!==t){const e=`${this.netaceaCookieName}=`;for(const i of t)if(i.startsWith(e))return await this.readCookie(this.netaceaCookieName,i)}}async getNetaceaCookieFromRequest(e){var t;const i=this.getHeaderValueOrDefault(e.headers,"cookie");return null!==(t=await this.readCookie(this.netaceaCookieName,i))&&void 0!==t?t:""}async callIngest(e){const t=this.constructWebLog(e);if(this.ingestType===H.NetaceaIngestType.KINESIS){if(void 0===this.kinesis)return void console.error("Netacea Error: Unable to log as Kinesis has not been defined.");try{await this.kinesis.ingest({...t,apiKey:this.apiKey},this.makeRequest)}catch(e){console.error("NETACEA Error: ",e.message)}}else{const e={"X-Netacea-API-Key":this.apiKey,"content-type":"application/json"},i=await this.makeIngestApiCall(e,t);if(200!==i.status)throw this.APIError(i)}}async makeIngestApiCall(e,t){return await this.makeRequest({host:this.ingestServiceUrl,method:"POST",path:"/",headers:e,body:JSON.stringify(t),timeout:this.timeout})}constructV2WebLog({ip:e,userAgent:t,status:i,method:a,path:s,protocol:o,referer:n,bytesSent:r,requestTime:c,mitataCookie:h,sessionStatus:u,integrationType:p,integrationVersion:d,xForwardedFor:l,headerFingerprint:g,cookieFingerprint:m}){var y;const f=new Date;let C;"/"!==s[0]&&(s=`/${s}`);const v=s.split("?");v.length>1&&(C=`?${v[1]}`);const k=v[0],S=null===(y=(0,H.matchMitataCookie)(h))||void 0===y?void 0:y.userId;return{status:i,method:a,bytes_sent:(0,H.safeParseInt)(r),referrer:""===n?void 0:n,request:`${a} ${k}${null!=C?C:""} ${o}`,request_time:(0,H.safeParseInt)(c),integration_type:p,integration_version:d,client:e,user_agent:t,bc_type:""===u?void 0:u,hour:f.getUTCHours(),minute:f.getUTCMinutes(),"@timestamp":f.toISOString().replace("Z","+00:00"),path:k,protocol:o,query:C,user_id:S,x_forwarded_for:l,optional:{headerFingerprint:g,cookieFingerprint:m}}}constructV1WebLog({ip:e,userAgent:t,status:i,method:a,path:s,protocol:o,referer:n,bytesSent:r,requestTime:c,mitataCookie:h,sessionStatus:u,integrationType:p,integrationVersion:d,xForwardedFor:l,headerFingerprint:g,cookieFingerprint:m}){return{Request:`${a} ${s} ${o}`,TimeLocal:(new Date).toUTCString(),RealIp:e,UserAgent:t,Status:i,RequestTime:null==c?void 0:c.toString(),BytesSent:null==r?void 0:r.toString(),Referer:""===n?"-":n,NetaceaUserIdCookie:null!=h?h:"",NetaceaMitigationApplied:null!=u?u:"",IntegrationType:null!=p?p:"",IntegrationVersion:null!=d?d:"",XForwardedFor:l,optional:{headerFingerprint:g,cookieFingerprint:m}}}constructWebLog(e){return e.bytesSent=""===e.bytesSent?"0":e.bytesSent,this.logVersion===H.NetaceaLogVersion.V2?this.constructV2WebLog(e):this.constructV1WebLog(e)}async check(e,t,i,a,s,o){var n,r;let c,h,u,p,d,l,g;if(void 0===this.secretKey)throw new Error("Secret key is required to mitigate");const m=(0,H.checkMitataCookie)(e,t,this.secretKey);if(!m.isPrimaryHashValid||m.requiresReissue){const e=await this.makeMitigateAPICall(null===(n=m.mitata)||void 0===n?void 0:n.userId,t,i,o,a,!1,null,s);c=e.status,h=e.match,u=e.mitigate,p=e.captcha,d=e.body,l=[await this.createMitata(t,null===(r=m.mitata)||void 0===r?void 0:r.userId,h,u,p,e.mitataMaxAge)],g=e.eventId}else c=-1,h=m.match,u=m.mitigate,p=m.captcha,d=void 0,l=[];return this.composeResult(d,l,c,h,u,p,!1,g)}async createMitata(e,t,i,a,s,o=86400,n=void 0){const r=[1,3,5].includes(s)||3===a?-60:this.mitataCookieExpirySeconds,c=null!=n?n:Math.floor(Date.now()/1e3)+r;if(void 0===this.secretKey)throw new Error("Cannot build cookie without secret key.");const h=[i,a,s].join("");let u=(0,H.createMitataCookie)(e,t,c,this.secretKey,h);return this.encryptedCookies.includes(this.netaceaCookieName)&&(u=await this.encryptCookieValue(u)),H.lib.cookie.netaceaSession.createNetaceaSetCookieString({cookieName:this.netaceaCookieName,cookieValue:u,otherAttributes:this.netaceaCookieAttributes})}async processCaptcha(e,t,i,a){const{status:s,match:o,mitigate:n,captcha:r,body:c,setCookie:h}=await this.makeCaptchaAPICall(e,t,i,a);return this.composeResult(c,h,s,o,n,r,!0)}async getMitataCaptchaFromHeaders(e){let t=e[H.dictionary.netaceaHeaders.mitataCaptcha];const i=parseInt(e[H.dictionary.netaceaHeaders.mitataCaptchaExpiry]);if(void 0!==t)return this.encryptedCookies.includes(this.netaceaCaptchaCookieName)&&(t=await this.encryptCookieValue(t)),H.lib.cookie.netaceaSession.createNetaceaCaptchaSetCookieString({cookieName:this.netaceaCaptchaCookieName,cookieValue:t,maxAgeAttribute:String(i),otherAttributes:this.netaceaCaptchaCookieAttributes})}async makeCaptchaAPICall(e,t,i,a){const s={"X-Netacea-API-Key":this.apiKey,"X-Netacea-Client-IP":t,"user-agent":i,"Content-Type":"application/x-www-form-urlencoded; charset=UTF-8"},o=(0,H.matchMitataCookie)(e);void 0!==o&&(s["X-Netacea-UserId"]=o.userId),void 0!==this.captchaSiteKey&&void 0!==this.captchaSecretKey&&(s["X-Netacea-Captcha-Site-Key"]=this.captchaSiteKey,s["X-Netacea-Captcha-Secret-Key"]=this.captchaSecretKey);const n=await this.makeRequest({host:this.mitigationServiceUrl,path:"/AtaVerifyCaptcha",headers:s,method:"POST",body:a,timeout:this.timeout});return await this.getApiCallResponseFromResponse(n,null==o?void 0:o.userId,t,"")}async getApiCallResponseFromResponse(e,t,i,a){var s;if(200!==e.status)throw this.APIError(e);const o=parseInt(e.headers[H.dictionary.netaceaHeaders.match]),n=parseInt(e.headers[H.dictionary.netaceaHeaders.mitigate]),r=parseInt(e.headers[H.dictionary.netaceaHeaders.captcha]);let c=parseInt(e.headers[H.dictionary.netaceaHeaders.mitataExpiry]);isNaN(c)&&(c=86400);const h=[await this.createMitata(i,t,o,n,r,c),await this.getMitataCaptchaFromHeaders(e.headers)].filter((e=>void 0!==e)),u=e.headers[H.dictionary.netaceaHeaders.eventId];if("application/json"===(null===(s=e.headers["content-type"])||void 0===s?void 0:s.toLowerCase())){if(void 0===this.netaceaCaptchaPath)throw new Error("netaceaCaptchaPath and URL must be defined to handle JSON captcha");e.body=await(0,D.modifyCaptchaJsonResponse)(e.body,this.netaceaCaptchaPath,a)}return{status:e.status,match:o,mitigate:n,captcha:r,setCookie:h,body:e.body,eventId:u,mitataMaxAge:c}}async buildCookieFromValues(e,t,i,a="/"){if(this.encryptedCookies.includes(e)){return`${e}=${await this.encryptCookieValue(t)}; Max-Age=${i}; Path=${a}`}return`${e}=${t}; Max-Age=${i}; Path=${a}`}buildCookieHeader(e){let t="",i="";for(const a in e){const s=e[a];void 0!==s&&(t=`${t}${i}${a}=${s}`,i="; ")}return t}async makeMitigateAPICall(e,t,i,a,s,o,n,r){const c={"X-Netacea-API-Key":this.apiKey,"X-Netacea-Client-IP":t,"user-agent":i,cookie:this.buildCookieHeader({_mitatacaptcha:a})};void 0!==e&&(c["X-Netacea-UserId"]=e),void 0!==this.captchaSiteKey&&void 0!==this.captchaSecretKey&&(c["X-Netacea-Captcha-Site-Key"]=this.captchaSiteKey,c["X-Netacea-Captcha-Secret-Key"]=this.captchaSecretKey),c["X-Netacea-Captcha-Content-Type"]=s;const h=await this.makeRequest({host:this.mitigationServiceUrl,path:o?"/captcha"+(null!==n?`?trackingId=${n}`:""):"/",headers:c,method:"GET",timeout:this.timeout});return await this.getApiCallResponseFromResponse(h,e,t,r)}composeResult(e,t,i,a,s,o,n,r){const c=this.findBestMitigation(a,s,o,n),h={body:e,apiCallStatus:i,setCookie:t,sessionStatus:c.sessionStatus,mitigation:c.mitigation,mitigated:[H.dictionary.mitigationTypes.block,H.dictionary.mitigationTypes.captcha].includes(c.mitigation)};if(this.mitigationType===H.NetaceaMitigationType.INJECT){const e={"x-netacea-match":c.parts.match.toString(),"x-netacea-mitigate":c.parts.mitigate.toString(),"x-netacea-captcha":c.parts.captcha.toString()};void 0!==r&&(e["x-netacea-event-id"]=r),h.injectHeaders=e}return h}findBestMitigation(e,t,i,a){var s,o,n;const r="unknown";a||(2===i?i=4:3===i&&(i=5));let c=null!==(s=H.dictionary.matchMap[e])&&void 0!==s?s:r+"_";c+=null!==(o=H.dictionary.mitigateMap[t])&&void 0!==o?o:r;let h=H.dictionary.bestMitigationMap[t];if(0!==i){c+=","+(null!==(n=H.dictionary.captchaMap[i])&&void 0!==n?n:r);const e=H.dictionary.bestMitigationCaptchaMap[i];void 0!==e&&(h=e)}return this.mitigationType===H.NetaceaMitigationType.INJECT&&(h=H.dictionary.mitigationTypes.none),{sessionStatus:c,mitigation:h,parts:{match:e,mitigate:t,captcha:i}}}APIError(e){let t="Unknown error";switch(e.status){case 403:t="Invalid credentials";break;case 500:t="Server error";break;case 502:t="Bad Gateway";break;case 503:t="Service Unavailable";break;case 400:t="Invalid request"}return new Error(`Error reaching Netacea API (${t}), status: ${e.status}`)}isUrlCaptchaPost(e,t){return e.includes("/AtaVerifyCaptcha")&&"post"===t.toLowerCase()}async processMitigateRequest(e){if(await(0,D.isUrlCaptchaGet)(e.url,e.method,this.netaceaCaptchaPath)){const t=await(0,D.getTrackingId)(e.url);return await this.handleGetCaptchaRequest(e.mitata,e.clientIp,e.userAgent,e.captchaPageContentType,t,e.url,e.mitataCaptcha)}return this.isUrlCaptchaPost(e.url,e.method)?await this.processCaptcha(e.mitata,e.clientIp,e.userAgent,await e.getBodyFn()):await this.check(e.mitata,e.clientIp,e.userAgent,e.captchaPageContentType,e.url,e.mitataCaptcha)}async setIngestOnlyMitataCookie(e){return{sessionStatus:"",setCookie:[await this.createMitata(H.ingestIgnoredIpValue,e,0,0,0,86400)]}}async processIngest(e){var t;if(void 0===this.secretKey)throw new Error("Secret key is required for ingest");const i=this.getCookieHeader(e),a=await this.readCookie(this.netaceaCookieName,i),s=(0,H.checkMitataCookie)(a,H.ingestIgnoredIpValue,this.secretKey);return s.isPrimaryHashValid?s.requiresReissue?await this.setIngestOnlyMitataCookie(null===(t=s.mitata)||void 0===t?void 0:t.userId):{sessionStatus:"",setCookie:[]}:await this.setIngestOnlyMitataCookie(void 0)}},function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.NetaceaMitigationType=void 0;const t=r;var i=c;Object.defineProperty(e,"NetaceaMitigationType",{enumerable:!0,get:function(){return i.NetaceaMitigationType}}),e.default=t.default}(n);var L=o(n);module.exports=L;
|
package/package.json
CHANGED
|
@@ -1,60 +1,25 @@
|
|
|
1
1
|
{
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
"
|
|
15
|
-
"
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
"
|
|
19
|
-
"
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
"dependencies": {
|
|
27
|
-
"@netacea/kinesisingest": "^1.5.42",
|
|
28
|
-
"@netacea/netaceaintegrationbase": "^2.0.24",
|
|
29
|
-
"jose": "^4.11.2"
|
|
30
|
-
},
|
|
31
|
-
"devDependencies": {
|
|
32
|
-
"@cloudflare/workers-types": "^4.20231025.0",
|
|
33
|
-
"@netacea/netaceaintegrationtestrunner": "^1.8.21",
|
|
34
|
-
"@rollup/plugin-commonjs": "^25.0.0",
|
|
35
|
-
"@rollup/plugin-json": "^6.0.0",
|
|
36
|
-
"@rollup/plugin-node-resolve": "^15.1.0",
|
|
37
|
-
"@rollup/plugin-replace": "^5.0.2",
|
|
38
|
-
"@rollup/plugin-terser": "^0.4.3",
|
|
39
|
-
"@rollup/plugin-typescript": "^11.1.1",
|
|
40
|
-
"@types/chai": "^4.3.5",
|
|
41
|
-
"@types/mocha": "^10.0.1",
|
|
42
|
-
"@types/node": "^20.9.1",
|
|
43
|
-
"@types/node-fetch": "^2.5.7",
|
|
44
|
-
"@types/proxyquire": "^1.3.28",
|
|
45
|
-
"@types/sinon": "^9.0.8",
|
|
46
|
-
"@types/tape": "^4.13.0",
|
|
47
|
-
"chai": "^4.3.7",
|
|
48
|
-
"mocha": "^10.2.0",
|
|
49
|
-
"nyc": "^15.1.0",
|
|
50
|
-
"proxyquire": "^2.1.3",
|
|
51
|
-
"rollup": "^3.23.0",
|
|
52
|
-
"rollup-plugin-dts": "^6.0.2",
|
|
53
|
-
"rollup-plugin-node-externals": "^6.1.1",
|
|
54
|
-
"sinon": "^9.1.0",
|
|
55
|
-
"tape": "^5.0.1",
|
|
56
|
-
"ts-node": "^10.9.1",
|
|
57
|
-
"typescript": "^5.2.2"
|
|
58
|
-
},
|
|
59
|
-
"gitHead": "ce3df71d2ea60c17fb83a888c6a9cb2411c6a943"
|
|
60
|
-
}
|
|
2
|
+
"name": "@netacea/cloudflare",
|
|
3
|
+
"version": "5.2.44",
|
|
4
|
+
"description": "Netacea Cloudflare CDN Integration",
|
|
5
|
+
"main": "dist/index.js",
|
|
6
|
+
"types": "dist/index.d.ts",
|
|
7
|
+
"files": [
|
|
8
|
+
"dist/"
|
|
9
|
+
],
|
|
10
|
+
"scripts": {
|
|
11
|
+
"prepack": "npx netacea-bundler prepack",
|
|
12
|
+
"postpack": "npx netacea-bundler postpack"
|
|
13
|
+
},
|
|
14
|
+
"author": "Netacea <npm@netacea.com> (https://netacea.com)",
|
|
15
|
+
"publishConfig": {
|
|
16
|
+
"access": "public"
|
|
17
|
+
},
|
|
18
|
+
"license": "ISC",
|
|
19
|
+
"dependencies": {
|
|
20
|
+
"@netacea/kinesisingest": "^1.5.44",
|
|
21
|
+
"@netacea/netaceaintegrationbase": "^2.0.26",
|
|
22
|
+
"jose": "^4.11.2"
|
|
23
|
+
},
|
|
24
|
+
"gitHead": "6b8dc377316ba9526910e1f44f17fbee44e4a51d"
|
|
25
|
+
}
|