@netacea/cloudflare 5.2.31 → 5.2.32

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.
Files changed (2) hide show
  1. package/dist/index.js +1 -1
  2. package/package.json +4 -4
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}function n(e){if(e.__esModule)return e;var t=e.default;if("function"==typeof t){var i=function e(){return this instanceof e?Reflect.construct(t,arguments,this.constructor):t.apply(this,arguments)};i.prototype=t.prototype}else i={};return Object.defineProperty(i,"__esModule",{value:!0}),Object.keys(e).forEach((function(t){var a=Object.getOwnPropertyDescriptor(e,t);Object.defineProperty(i,t,a.get?a:{enumerable:!0,get:function(){return e[t]}})})),i}var r,c,h,u,p={},d={};!function(e){e.ORIGIN="ORIGIN",e.HTTP="HTTP",e.KINESIS="KINESIS",e.NATIVE="NATIVE"}(r||(r={})),function(e){e.V1="V1",e.V2="V2"}(c||(c={})),function(e){e.MITIGATE="MITIGATE",e.INJECT="INJECT",e.INGEST="INGEST"}(h||(h={})),function(e){e.CAPTCHA_GET="captcha_get",e.CAPTCHA_POST="captcha_post",e.EXPIRED_SESSION="expired_session",e.FORCED_REVALIDATION="forced_revalidation",e.INVALID_SESSION="invalid_session",e.IP_CHANGE="ip_change",e.NO_SESSION="no_session"}(u||(u={}));const l=3e3;const m="_/@#/",g={none:"",block:"block",captcha:"captcha",allow:"allow",captchaPass:"captchapass"},y={0:g.none,1:g.block,2:g.none,3:g.block,4:g.block},f={1:g.captcha,2:g.captchaPass,3:g.captcha,4:g.allow,5:g.captcha},C={clientIP:"cip",userId:"uid",gracePeriod:"grp",cookieId:"cid",match:"mat",mitigate:"mit",captcha:"cap",issueTimestamp:"ist",issueReason:"isr"},v={checkAllPostRequests:"fCAPR"};var k=Object.freeze({__proto__:null,COOKIEDELIMITER:m,bestMitigationCaptchaMap:f,bestMitigationMap:y,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:g,netaceaCookieV3KeyMap:C,netaceaCookieV3OptionalKeyMap:v,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 S="1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".split(""),I=/^(.*)_\/@#\/(.*)_\/@#\/(.*)_\/@#\/(.*)_\/@#\/((\d)(\d)(\d))$/;function T(e){if(void 0===e)return;const t=e.match(I);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 A(t=16,i=S){const a=e.randomBytes(t-1);return`c${Array.from(a).map((e=>i[e%i.length])).join("")}`}function N(i,a){const s=e.createHmac("sha256",a);return s.update(i),t.Buffer.from(s.digest("hex")).toString("base64")}function b(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(C).find((e=>C[e]===t));void 0===o&&(o=Object.keys(v).find((e=>v[e]===t)));let n=""===s?void 0:Number(s);void 0!==n&&isNaN(n)&&(n=s),i[o]=n}return i}function w(){return{mitata:void 0,requiresReissue:!1,isExpired:!1,shouldExpire:!1,isSameIP:!1,isPrimaryHashValid:!1,captcha:0,match:0,mitigate:0,issueReason:u.NO_SESSION}}function E(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 P(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 x(e){const t=P([e.otherAttributes??"",`Max-Age=${e.maxAgeAttribute??86400}`,"Path=/"].join("; "));return`${e.cookieName}=${e.cookieValue}; ${t}`}const _={cookie:{attributes:Object.freeze({__proto__:null,configureCookiesDomain:function(e,t){let i=e=P(e??"",!0),a=t=P(t??"",!0);if(void 0!==e&&void 0!==t){const s=E(e,"Domain"),o=E(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=E(e,"Domain");void 0!==t&&(a=`Domain=${t}`)}else if(void 0===e&&void 0!==t){const e=E(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=E(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:E,removeDuplicateAttrs:P}),netaceaSession:Object.freeze({__proto__:null,createNetaceaCaptchaSetCookieString:function(e){return x({...e,cookieName:e.cookieName??"_mitatacaptcha"})},createNetaceaSetCookieString:function(e){return x({...e,cookieName:e.cookieName??"_mitata"})},createSetCookieString:x})}};var M=n(Object.freeze({__proto__:null,get NetaceaCookieV3IssueReason(){return u},get NetaceaIngestType(){return r},get NetaceaLogVersion(){return c},get NetaceaMitigationType(){return h},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=T(e);if(void 0!==s){const e=[s.expiry,s.userId,s.ipHash,s.mitigationType].join(m),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=N(t+"|"+s.expiry,i),u=s.ipHash===h;return{mitata:s,requiresReissue:o||!u,isExpired:o,shouldExpire:c,isSameIP:u,isPrimaryHashValid:s.signature===N(e,i),match:s.match,mitigate:s.mitigate,captcha:s.captcha}}return a},checkNetaceaCookieV3:function(e,t){if(void 0===e||""===e)return w();const i=b(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 w()},configureMitataExpiry:function(e,t){return void 0===t?e===h.INGEST?3600:60:t},cookieIsNetaceaV3Format:function(e){return void 0!==e&&e.split("&").map((e=>e.split("=")[0])).filter((e=>!Object.values(v).includes(e))).every((e=>Object.values(C).includes(e)))},correctTimeout:function(e){return e<=0?l:e},createMitataCookie:function(e,t,i,a,s="000"){void 0===t&&(t=A());const o=[i,t,N(e+"|"+String(i),a),s].join(m);return`${N(o,a)}${m}${o}`},createNetaceaCookieV3:function(e){return Object.entries(e).filter((([e,t])=>void 0!==t)).map((([e,t])=>e in v?`${v[e]}=${encodeURIComponent(t)}`:`${C[e]}=${encodeURIComponent(t)}`)).join("&")},defaultInvalidResponse:w,dictionary:k,generateId:A,hexSha256:N,ingestIgnoredIpValue:"ignored",lib:_,matchMitataCookie:T,matchNetaceaCookieV3:b,objectIsNetaceaCookieV3:function(e){if("object"!=typeof e||null===e)return!1;for(const t of Object.keys(C)){if(!(t in e))return!1;if(void 0===e[t])return!1}return!0},safeParseInt:function(e,t=0){return isNaN(e)?t:parseInt(e)},warmupCookie:{cookie:"MzBkZDEwYjc0ZmIyMzQ4YmY0OTlhNTkyNjY0MDRjMjhjNmQ5Y2RlYjVkYzVkMDQyZmEzODU4MDBiN2MwNTk1OQ==_/@#/1653044256_/@#/UUID_/@#/NjEyOWIzY2JiMjE5NjcwMThlYjg5NDYzY2YyMDZlYjE0ZDg2NTRjYmMxODg5Y2I4Y2U2NGFjZDAxOTdhMGFmNA==_/@#/000",secretKey:"EXAMPLE_SECRET_KEY",clientIP:"192.168.0.1"}})),R={},O={},H={},K={},j=function(e){return new D(e)};function D(e){this.capacity=0|e,this.map=Object.create(null),this.list=new q}function q(){this.firstNode=null,this.lastNode=null}function V(e,t){this.key=e,this.val=t,this.prev=null,this.next=null}D.prototype.get=function(e){var t=this.map[e];if(null!=t)return this.used(t),t.val},D.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 V(e,t),this.map[e]=i,this.capacity--}return this.used(i),!0},D.prototype.used=function(e){this.list.moveToFront(e)},D.prototype.prune=function(){var e=this.list.pop();null!=e&&(delete this.map[e.key],this.capacity++)},q.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))},q.prototype.pop=function(){var e=this.lastNode;return null!=e&&this.remove(e),e},q.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=K,o=i,n=a,r=e,c=j(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 d(e){return p(encodeURIComponent(e))}var l={authorization:!0,connection:!0,"x-amzn-trace-id":!0,"user-agent":!0,expect:!0,"presigned-expires":!0,range:!0};function m(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}m.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},m.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},m.prototype.createHost=function(){var e=this.isSingleRegion()?"":"."+this.region;return("ses"===this.service?"email":this.service)+e+".amazonaws.com"},m.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)},m.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},m.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},m.prototype.getDate=function(){return this.getDateTime().substr(0,8)},m.prototype.authHeader=function(){return["AWS4-HMAC-SHA256 Credential="+this.credentials.accessKeyId+"/"+this.credentialString(),"SignedHeaders="+this.signedHeaders(),"Signature="+this.signature()].join(", ")},m.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")},m.prototype.stringToSign=function(){return["AWS4-HMAC-SHA256",this.getDateTime(),this.credentialString(),u(this.canonicalString(),"hex")].join("\n")},m.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[d(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(d).sort().forEach((function(t){p.push(e+"="+t)})):p.push(e+"="+d(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(d(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")},m.prototype.canonicalHeaders=function(){var e=this.request.headers;return Object.keys(e).filter((function(e){return null==l[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")},m.prototype.signedHeaders=function(){return Object.keys(this.request.headers).map((function(e){return e.toLowerCase()})).filter((function(e){return null==l[e]})).sort().join(";")},m.prototype.credentialString=function(){return[this.getDate(),this.region,this.service,"aws4_request"].join("/")},m.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}},m.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}},m.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=m,s.sign=function(e,t){return new m(e,t).sign()}}();var $={};Object.defineProperty($,"__esModule",{value:!0}),$.API_VERSION=$.REGION=$.PAYLOAD_TYPE=$.STATE=void 0,$.STATE={ACTIVE:"ACTIVE",UPDATING:"UPDATING",CREATING:"CREATING",DELETING:"DELETING"},$.PAYLOAD_TYPE="string",$.REGION="eu-west-1",$.API_VERSION="2013-12-02",Object.defineProperty(H,"__esModule",{value:!0});const U=K,z=$;H.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 U.sign({service:"kinesis",body:JSON.stringify(o),headers:{"Content-Type":"application/x-amz-json-1.1","X-Amz-Target":"Kinesis_20131202.PutRecords"},region:z.REGION},{accessKeyId:a,secretAccessKey:s})}},Object.defineProperty(O,"__esModule",{value:!0});const L=H;O.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=L.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(R,"__esModule",{value:!0});const G=O;R.default=G.default;var F={name:"@netacea/cloudflare",version:"5.2.31",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 -r tsconfig-paths/register './tests/tape/*.test.ts'","test:integration":"npx nyc mocha --timeout 60000 -r ts-node/register -r tsconfig-paths/register './tests/mocha/*.test.ts'","test:integration:no-clean":"npx nyc --no-clean mocha --timeout 60000 -r ts-node/register -r tsconfig-paths/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:"npx tsc --project tsconfig.build.json && npm run rollup"},author:"Jack Scotson <jack.scotson@netacea.com> (https://netacea.com)",publishConfig:{access:"public"},license:"ISC",dependencies:{"@netacea/kinesisingest":"^1.5.31","@netacea/netaceaintegrationbase":"^2.0.13",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","tsconfig-paths":"^4.2.0",typescript:"^5.2.2"},gitHead:"44fa8764ea8699496a39bcccbbe5280b54b77362"},X={};Object.defineProperty(X,"__esModule",{value:!0}),X.fetch=void 0,X.fetch=globalThis.fetch.bind(globalThis);var Y={};Object.defineProperty(Y,"__esModule",{value:!0}),Y.decrypt=Y.encrypt=void 0;const W=s;Y.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)},Y.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||!Boolean(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()},Object.defineProperty(d,"__esModule",{value:!0});const J=M,Z=R,Q=F,ee=X,te=Y,ie=B,{configureCookiesDomain:ae}=J.lib.cookie.attributes;d.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=J.NetaceaMitigationType.INGEST,captchaSiteKey:r,captchaSecretKey:c,ingestType:h=J.NetaceaIngestType.HTTP,kinesis:u,logVersion:p,mitataCookieExpirySeconds:d,netaceaCookieExpirySeconds:l,netaceaCookieName:m,netaceaCaptchaCookieName:g,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:J.NetaceaIngestType.HTTP,this.logVersion=null!=p?p:J.NetaceaLogVersion.V1,this.ingestType===J.NetaceaIngestType.KINESIS&&(void 0===u?console.warn(`NETACEA WARN: no kinesis args provided, when ingestType is ${this.ingestType}`):this.kinesis=new Z.default({...u,apiKey:this.apiKey})),void 0===r&&void 0===c||(this.captchaSiteKey=r,this.captchaSecretKey=c),this.timeout=(0,J.correctTimeout)(a),this.netaceaCookieName=null!=m?m:"_mitata",this.netaceaCaptchaCookieName=null!=g?g:"_mitatacaptcha";const{cookieAttributes:v,captchaCookieAttributes:k}=ae(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===J.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=await this.timeoutCheck(this.runMitigation(e.request),this.timeout);return await this.handleResponse(e.request,i,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,ie.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 ingest(e,t){var i,a,s;const o=null!==(i=await this.getNetaceaCookieFromResponse(t))&&void 0!==i?i:await this.getNetaceaCookieFromRequest(e),{match:n,mitigate:r,captcha:c}=null!==(a=(0,J.matchMitataCookie)(null!=o?o:""))&&void 0!==a?a:{match:0,mitigate:0,captcha:0},{sessionStatus:h}=this.findBestMitigation(n,r,c,this.isUrlCaptchaPost(e.url,e.method)),u=String(null===(s=e.cf)||void 0===s?void 0:s.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:u,referer:this.getHeaderValueOrDefault(e.headers,"referer"),requestTime:"0",sessionStatus:h,status:t.status.toString(),userAgent:this.getHeaderValueOrDefault(e.headers,"user-agent","-"),mitataCookie:o,integrationType:Q.name.replace("@netacea/",""),integrationVersion:Q.version,xForwardedFor:this.getHeaderValueOrDefault(e.headers,"x-forwarded-for")})}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,J.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,ee.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===J.NetaceaMitigationType.MITIGATE){if(void 0!==t.response)return t.response}else this.mitigationType===J.NetaceaMitigationType.INJECT&&(e=this.addHeadersToRequest(e,t));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}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,ie.getCaptchaPageContentType)(null!==(s=e.headers.get("Accept"))&&void 0!==s?s:void 0):(0,ie.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,te.encrypt)(e,this.cookieEncryptionKey):e}async decryptCookieValue(e){return void 0!==this.cookieEncryptionKey?await(0,te.decrypt)(e,this.cookieEncryptionKey):e}async runMitigation(e){try{switch(this.mitigationType){case J.NetaceaMitigationType.MITIGATE:return await this.mitigate(e);case J.NetaceaMitigationType.INJECT:return await this.inject(e);case J.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){const t=e.headers.getSetCookie(),i=`${this.netaceaCookieName}=`;for(const e of t)if(e.startsWith(i))return await this.readCookie(this.netaceaCookieName,e)}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===J.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}){var m;const g=new Date;let y;"/"!==s[0]&&(s=`/${s}`);const f=s.split("?");f.length>1&&(y=`?${f[1]}`);const C=f[0],v=null===(m=(0,J.matchMitataCookie)(h))||void 0===m?void 0:m.userId;return{status:i,method:a,bytes_sent:(0,J.safeParseInt)(r),referrer:""===n?void 0:n,request:`${a} ${C}${null!=y?y:""} ${o}`,request_time:(0,J.safeParseInt)(c),integration_type:p,integration_version:d,client:e,user_agent:t,bc_type:""===u?void 0:u,hour:g.getUTCHours(),minute:g.getUTCMinutes(),"@timestamp":g.toISOString().replace("Z","+00:00"),path:C,protocol:o,query:y,user_id:v,x_forwarded_for:l}}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}){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}}constructWebLog(e){return e.bytesSent=""===e.bytesSent?"0":e.bytesSent,this.logVersion===J.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,m;if(void 0===this.secretKey)throw new Error("Secret key is required to mitigate");const g=(0,J.checkMitataCookie)(e,t,this.secretKey);if(!g.isPrimaryHashValid||g.requiresReissue){const e=await this.makeMitigateAPICall(null===(n=g.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=g.mitata)||void 0===r?void 0:r.userId,h,u,p,e.mitataMaxAge)],m=e.eventId}else c=-1,h=g.match,u=g.mitigate,p=g.captcha,d=void 0,l=[];return this.composeResult(d,l,c,h,u,p,!1,m)}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,J.createMitataCookie)(e,t,c,this.secretKey,h);return this.encryptedCookies.includes(this.netaceaCookieName)&&(u=await this.encryptCookieValue(u)),J.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[J.dictionary.netaceaHeaders.mitataCaptcha];const i=parseInt(e[J.dictionary.netaceaHeaders.mitataCaptchaExpiry]);if(void 0!==t)return this.encryptedCookies.includes(this.netaceaCaptchaCookieName)&&(t=await this.encryptCookieValue(t)),J.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,J.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[J.dictionary.netaceaHeaders.match]),n=parseInt(e.headers[J.dictionary.netaceaHeaders.mitigate]),r=parseInt(e.headers[J.dictionary.netaceaHeaders.captcha]);let c=parseInt(e.headers[J.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[J.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,ie.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:[J.dictionary.mitigationTypes.block,J.dictionary.mitigationTypes.captcha].includes(c.mitigation)};if(this.mitigationType===J.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=J.dictionary.matchMap[e])&&void 0!==s?s:r+"_";c+=null!==(o=J.dictionary.mitigateMap[t])&&void 0!==o?o:r;let h=J.dictionary.bestMitigationMap[t];if(0!==i){c+=","+(null!==(n=J.dictionary.captchaMap[i])&&void 0!==n?n:r);const e=J.dictionary.bestMitigationCaptchaMap[i];void 0!==e&&(h=e)}return this.mitigationType===J.NetaceaMitigationType.INJECT&&(h=J.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,ie.isUrlCaptchaGet)(e.url,e.method,this.netaceaCaptchaPath)){const t=await(0,ie.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(J.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,J.checkMitataCookie)(a,J.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=d;var i=M;Object.defineProperty(e,"NetaceaMitigationType",{enumerable:!0,get:function(){return i.NetaceaMitigationType}}),e.default=t.default}(p);var se=o(p);module.exports=se;
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}function n(e){if(e.__esModule)return e;var t=e.default;if("function"==typeof t){var i=function e(){return this instanceof e?Reflect.construct(t,arguments,this.constructor):t.apply(this,arguments)};i.prototype=t.prototype}else i={};return Object.defineProperty(i,"__esModule",{value:!0}),Object.keys(e).forEach((function(t){var a=Object.getOwnPropertyDescriptor(e,t);Object.defineProperty(i,t,a.get?a:{enumerable:!0,get:function(){return e[t]}})})),i}var r,c,h,u,p={},d={};!function(e){e.ORIGIN="ORIGIN",e.HTTP="HTTP",e.KINESIS="KINESIS",e.NATIVE="NATIVE"}(r||(r={})),function(e){e.V1="V1",e.V2="V2"}(c||(c={})),function(e){e.MITIGATE="MITIGATE",e.INJECT="INJECT",e.INGEST="INGEST"}(h||(h={})),function(e){e.CAPTCHA_GET="captcha_get",e.CAPTCHA_POST="captcha_post",e.EXPIRED_SESSION="expired_session",e.FORCED_REVALIDATION="forced_revalidation",e.INVALID_SESSION="invalid_session",e.IP_CHANGE="ip_change",e.NO_SESSION="no_session"}(u||(u={}));const l=3e3;const m="_/@#/",g={none:"",block:"block",captcha:"captcha",allow:"allow",captchaPass:"captchapass"},y={0:g.none,1:g.block,2:g.none,3:g.block,4:g.block},f={1:g.captcha,2:g.captchaPass,3:g.captcha,4:g.allow,5:g.captcha},C={clientIP:"cip",userId:"uid",gracePeriod:"grp",cookieId:"cid",match:"mat",mitigate:"mit",captcha:"cap",issueTimestamp:"ist",issueReason:"isr"},v={checkAllPostRequests:"fCAPR"};var k=Object.freeze({__proto__:null,COOKIEDELIMITER:m,bestMitigationCaptchaMap:f,bestMitigationMap:y,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:g,netaceaCookieV3KeyMap:C,netaceaCookieV3OptionalKeyMap:v,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 S="1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".split(""),I=/^(.*)_\/@#\/(.*)_\/@#\/(.*)_\/@#\/(.*)_\/@#\/((\d)(\d)(\d))$/;function T(e){if(void 0===e)return;const t=e.match(I);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 A(t=16,i=S){const a=e.randomBytes(t-1);return`c${Array.from(a).map((e=>i[e%i.length])).join("")}`}function N(i,a){const s=e.createHmac("sha256",a);return s.update(i),t.Buffer.from(s.digest("hex")).toString("base64")}function b(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(C).find((e=>C[e]===t));void 0===o&&(o=Object.keys(v).find((e=>v[e]===t)));let n=""===s?void 0:Number(s);void 0!==n&&isNaN(n)&&(n=s),i[o]=n}return i}function w(){return{mitata:void 0,requiresReissue:!1,isExpired:!1,shouldExpire:!1,isSameIP:!1,isPrimaryHashValid:!1,captcha:0,match:0,mitigate:0,issueReason:u.NO_SESSION}}function E(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 P(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 x(e){const t=P([e.otherAttributes??"",`Max-Age=${e.maxAgeAttribute??86400}`,"Path=/"].join("; "));return`${e.cookieName}=${e.cookieValue}; ${t}`}const _={cookie:{attributes:Object.freeze({__proto__:null,configureCookiesDomain:function(e,t){let i=e=P(e??"",!0),a=t=P(t??"",!0);if(void 0!==e&&void 0!==t){const s=E(e,"Domain"),o=E(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=E(e,"Domain");void 0!==t&&(a=`Domain=${t}`)}else if(void 0===e&&void 0!==t){const e=E(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=E(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:E,removeDuplicateAttrs:P}),netaceaSession:Object.freeze({__proto__:null,createNetaceaCaptchaSetCookieString:function(e){return x({...e,cookieName:e.cookieName??"_mitatacaptcha"})},createNetaceaSetCookieString:function(e){return x({...e,cookieName:e.cookieName??"_mitata"})},createSetCookieString:x})}};var M=n(Object.freeze({__proto__:null,get NetaceaCookieV3IssueReason(){return u},get NetaceaIngestType(){return r},get NetaceaLogVersion(){return c},get NetaceaMitigationType(){return h},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=T(e);if(void 0!==s){const e=[s.expiry,s.userId,s.ipHash,s.mitigationType].join(m),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=N(t+"|"+s.expiry,i),u=s.ipHash===h;return{mitata:s,requiresReissue:o||!u,isExpired:o,shouldExpire:c,isSameIP:u,isPrimaryHashValid:s.signature===N(e,i),match:s.match,mitigate:s.mitigate,captcha:s.captcha}}return a},checkNetaceaCookieV3:function(e,t){if(void 0===e||""===e)return w();const i=b(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 w()},configureMitataExpiry:function(e,t){return void 0===t?e===h.INGEST?3600:60:t},cookieIsNetaceaV3Format:function(e){return void 0!==e&&e.split("&").map((e=>e.split("=")[0])).filter((e=>!Object.values(v).includes(e))).every((e=>Object.values(C).includes(e)))},correctTimeout:function(e){return e<=0?l:e},createMitataCookie:function(e,t,i,a,s="000"){void 0===t&&(t=A());const o=[i,t,N(e+"|"+String(i),a),s].join(m);return`${N(o,a)}${m}${o}`},createNetaceaCookieV3:function(e){return Object.entries(e).filter((([e,t])=>void 0!==t)).map((([e,t])=>e in v?`${v[e]}=${encodeURIComponent(t)}`:`${C[e]}=${encodeURIComponent(t)}`)).join("&")},defaultInvalidResponse:w,dictionary:k,generateId:A,hexSha256:N,ingestIgnoredIpValue:"ignored",lib:_,matchMitataCookie:T,matchNetaceaCookieV3:b,objectIsNetaceaCookieV3:function(e){if("object"!=typeof e||null===e)return!1;for(const t of Object.keys(C)){if(!(t in e))return!1;if(void 0===e[t])return!1}return!0},safeParseInt:function(e,t=0){return isNaN(e)?t:parseInt(e)},warmupCookie:{cookie:"MzBkZDEwYjc0ZmIyMzQ4YmY0OTlhNTkyNjY0MDRjMjhjNmQ5Y2RlYjVkYzVkMDQyZmEzODU4MDBiN2MwNTk1OQ==_/@#/1653044256_/@#/UUID_/@#/NjEyOWIzY2JiMjE5NjcwMThlYjg5NDYzY2YyMDZlYjE0ZDg2NTRjYmMxODg5Y2I4Y2U2NGFjZDAxOTdhMGFmNA==_/@#/000",secretKey:"EXAMPLE_SECRET_KEY",clientIP:"192.168.0.1"}})),R={},O={},H={},K={},j=function(e){return new D(e)};function D(e){this.capacity=0|e,this.map=Object.create(null),this.list=new q}function q(){this.firstNode=null,this.lastNode=null}function V(e,t){this.key=e,this.val=t,this.prev=null,this.next=null}D.prototype.get=function(e){var t=this.map[e];if(null!=t)return this.used(t),t.val},D.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 V(e,t),this.map[e]=i,this.capacity--}return this.used(i),!0},D.prototype.used=function(e){this.list.moveToFront(e)},D.prototype.prune=function(){var e=this.list.pop();null!=e&&(delete this.map[e.key],this.capacity++)},q.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))},q.prototype.pop=function(){var e=this.lastNode;return null!=e&&this.remove(e),e},q.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=K,o=i,n=a,r=e,c=j(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 d(e){return p(encodeURIComponent(e))}var l={authorization:!0,connection:!0,"x-amzn-trace-id":!0,"user-agent":!0,expect:!0,"presigned-expires":!0,range:!0};function m(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}m.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},m.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},m.prototype.createHost=function(){var e=this.isSingleRegion()?"":"."+this.region;return("ses"===this.service?"email":this.service)+e+".amazonaws.com"},m.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)},m.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},m.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},m.prototype.getDate=function(){return this.getDateTime().substr(0,8)},m.prototype.authHeader=function(){return["AWS4-HMAC-SHA256 Credential="+this.credentials.accessKeyId+"/"+this.credentialString(),"SignedHeaders="+this.signedHeaders(),"Signature="+this.signature()].join(", ")},m.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")},m.prototype.stringToSign=function(){return["AWS4-HMAC-SHA256",this.getDateTime(),this.credentialString(),u(this.canonicalString(),"hex")].join("\n")},m.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[d(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(d).sort().forEach((function(t){p.push(e+"="+t)})):p.push(e+"="+d(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(d(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")},m.prototype.canonicalHeaders=function(){var e=this.request.headers;return Object.keys(e).filter((function(e){return null==l[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")},m.prototype.signedHeaders=function(){return Object.keys(this.request.headers).map((function(e){return e.toLowerCase()})).filter((function(e){return null==l[e]})).sort().join(";")},m.prototype.credentialString=function(){return[this.getDate(),this.region,this.service,"aws4_request"].join("/")},m.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}},m.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}},m.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=m,s.sign=function(e,t){return new m(e,t).sign()}}();var $={};Object.defineProperty($,"__esModule",{value:!0}),$.API_VERSION=$.REGION=$.PAYLOAD_TYPE=$.STATE=void 0,$.STATE={ACTIVE:"ACTIVE",UPDATING:"UPDATING",CREATING:"CREATING",DELETING:"DELETING"},$.PAYLOAD_TYPE="string",$.REGION="eu-west-1",$.API_VERSION="2013-12-02",Object.defineProperty(H,"__esModule",{value:!0});const U=K,z=$;H.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 U.sign({service:"kinesis",body:JSON.stringify(o),headers:{"Content-Type":"application/x-amz-json-1.1","X-Amz-Target":"Kinesis_20131202.PutRecords"},region:z.REGION},{accessKeyId:a,secretAccessKey:s})}},Object.defineProperty(O,"__esModule",{value:!0});const L=H;O.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=L.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(R,"__esModule",{value:!0});const G=O;R.default=G.default;var F={name:"@netacea/cloudflare",version:"5.2.32",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 -r tsconfig-paths/register './tests/tape/*.test.ts'","test:integration":"npx nyc mocha --timeout 60000 -r ts-node/register -r tsconfig-paths/register './tests/mocha/*.test.ts'","test:integration:no-clean":"npx nyc --no-clean mocha --timeout 60000 -r ts-node/register -r tsconfig-paths/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:"npx tsc --project tsconfig.build.json && npm run rollup"},author:"Jack Scotson <jack.scotson@netacea.com> (https://netacea.com)",publishConfig:{access:"public"},license:"ISC",dependencies:{"@netacea/kinesisingest":"^1.5.32","@netacea/netaceaintegrationbase":"^2.0.14",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","tsconfig-paths":"^4.2.0",typescript:"^5.2.2"},gitHead:"6faaa2912715ce66712ac984918f7b31b24a9187"},X={};Object.defineProperty(X,"__esModule",{value:!0}),X.fetch=void 0,X.fetch=globalThis.fetch.bind(globalThis);var Y={};Object.defineProperty(Y,"__esModule",{value:!0}),Y.decrypt=Y.encrypt=void 0;const W=s;Y.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)},Y.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||!Boolean(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()},Object.defineProperty(d,"__esModule",{value:!0});const J=M,Z=R,Q=F,ee=X,te=Y,ie=B,{configureCookiesDomain:ae}=J.lib.cookie.attributes;d.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=J.NetaceaMitigationType.INGEST,captchaSiteKey:r,captchaSecretKey:c,ingestType:h=J.NetaceaIngestType.HTTP,kinesis:u,logVersion:p,mitataCookieExpirySeconds:d,netaceaCookieExpirySeconds:l,netaceaCookieName:m,netaceaCaptchaCookieName:g,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:J.NetaceaIngestType.HTTP,this.logVersion=null!=p?p:J.NetaceaLogVersion.V1,this.ingestType===J.NetaceaIngestType.KINESIS&&(void 0===u?console.warn(`NETACEA WARN: no kinesis args provided, when ingestType is ${this.ingestType}`):this.kinesis=new Z.default({...u,apiKey:this.apiKey})),void 0===r&&void 0===c||(this.captchaSiteKey=r,this.captchaSecretKey=c),this.timeout=(0,J.correctTimeout)(a),this.netaceaCookieName=null!=m?m:"_mitata",this.netaceaCaptchaCookieName=null!=g?g:"_mitatacaptcha";const{cookieAttributes:v,captchaCookieAttributes:k}=ae(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===J.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=await this.timeoutCheck(this.runMitigation(e.request),this.timeout);return await this.handleResponse(e.request,i,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,ie.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 ingest(e,t){var i,a,s;const o=null!==(i=await this.getNetaceaCookieFromResponse(t))&&void 0!==i?i:await this.getNetaceaCookieFromRequest(e),{match:n,mitigate:r,captcha:c}=null!==(a=(0,J.matchMitataCookie)(null!=o?o:""))&&void 0!==a?a:{match:0,mitigate:0,captcha:0},{sessionStatus:h}=this.findBestMitigation(n,r,c,this.isUrlCaptchaPost(e.url,e.method)),u=String(null===(s=e.cf)||void 0===s?void 0:s.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:u,referer:this.getHeaderValueOrDefault(e.headers,"referer"),requestTime:"0",sessionStatus:h,status:t.status.toString(),userAgent:this.getHeaderValueOrDefault(e.headers,"user-agent","-"),mitataCookie:o,integrationType:Q.name.replace("@netacea/",""),integrationVersion:Q.version,xForwardedFor:this.getHeaderValueOrDefault(e.headers,"x-forwarded-for")})}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,J.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,ee.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===J.NetaceaMitigationType.MITIGATE){if(void 0!==t.response)return t.response}else this.mitigationType===J.NetaceaMitigationType.INJECT&&(e=this.addHeadersToRequest(e,t));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}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,ie.getCaptchaPageContentType)(null!==(s=e.headers.get("Accept"))&&void 0!==s?s:void 0):(0,ie.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,te.encrypt)(e,this.cookieEncryptionKey):e}async decryptCookieValue(e){return void 0!==this.cookieEncryptionKey?await(0,te.decrypt)(e,this.cookieEncryptionKey):e}async runMitigation(e){try{switch(this.mitigationType){case J.NetaceaMitigationType.MITIGATE:return await this.mitigate(e);case J.NetaceaMitigationType.INJECT:return await this.inject(e);case J.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){const t=e.headers.getSetCookie(),i=`${this.netaceaCookieName}=`;for(const e of t)if(e.startsWith(i))return await this.readCookie(this.netaceaCookieName,e)}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===J.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}){var m;const g=new Date;let y;"/"!==s[0]&&(s=`/${s}`);const f=s.split("?");f.length>1&&(y=`?${f[1]}`);const C=f[0],v=null===(m=(0,J.matchMitataCookie)(h))||void 0===m?void 0:m.userId;return{status:i,method:a,bytes_sent:(0,J.safeParseInt)(r),referrer:""===n?void 0:n,request:`${a} ${C}${null!=y?y:""} ${o}`,request_time:(0,J.safeParseInt)(c),integration_type:p,integration_version:d,client:e,user_agent:t,bc_type:""===u?void 0:u,hour:g.getUTCHours(),minute:g.getUTCMinutes(),"@timestamp":g.toISOString().replace("Z","+00:00"),path:C,protocol:o,query:y,user_id:v,x_forwarded_for:l}}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}){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}}constructWebLog(e){return e.bytesSent=""===e.bytesSent?"0":e.bytesSent,this.logVersion===J.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,m;if(void 0===this.secretKey)throw new Error("Secret key is required to mitigate");const g=(0,J.checkMitataCookie)(e,t,this.secretKey);if(!g.isPrimaryHashValid||g.requiresReissue){const e=await this.makeMitigateAPICall(null===(n=g.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=g.mitata)||void 0===r?void 0:r.userId,h,u,p,e.mitataMaxAge)],m=e.eventId}else c=-1,h=g.match,u=g.mitigate,p=g.captcha,d=void 0,l=[];return this.composeResult(d,l,c,h,u,p,!1,m)}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,J.createMitataCookie)(e,t,c,this.secretKey,h);return this.encryptedCookies.includes(this.netaceaCookieName)&&(u=await this.encryptCookieValue(u)),J.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[J.dictionary.netaceaHeaders.mitataCaptcha];const i=parseInt(e[J.dictionary.netaceaHeaders.mitataCaptchaExpiry]);if(void 0!==t)return this.encryptedCookies.includes(this.netaceaCaptchaCookieName)&&(t=await this.encryptCookieValue(t)),J.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,J.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[J.dictionary.netaceaHeaders.match]),n=parseInt(e.headers[J.dictionary.netaceaHeaders.mitigate]),r=parseInt(e.headers[J.dictionary.netaceaHeaders.captcha]);let c=parseInt(e.headers[J.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[J.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,ie.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:[J.dictionary.mitigationTypes.block,J.dictionary.mitigationTypes.captcha].includes(c.mitigation)};if(this.mitigationType===J.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=J.dictionary.matchMap[e])&&void 0!==s?s:r+"_";c+=null!==(o=J.dictionary.mitigateMap[t])&&void 0!==o?o:r;let h=J.dictionary.bestMitigationMap[t];if(0!==i){c+=","+(null!==(n=J.dictionary.captchaMap[i])&&void 0!==n?n:r);const e=J.dictionary.bestMitigationCaptchaMap[i];void 0!==e&&(h=e)}return this.mitigationType===J.NetaceaMitigationType.INJECT&&(h=J.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,ie.isUrlCaptchaGet)(e.url,e.method,this.netaceaCaptchaPath)){const t=await(0,ie.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(J.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,J.checkMitataCookie)(a,J.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=d;var i=M;Object.defineProperty(e,"NetaceaMitigationType",{enumerable:!0,get:function(){return i.NetaceaMitigationType}}),e.default=t.default}(p);var se=o(p);module.exports=se;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@netacea/cloudflare",
3
- "version": "5.2.31",
3
+ "version": "5.2.32",
4
4
  "description": "Netacea Cloudflare CDN Integration",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -23,8 +23,8 @@
23
23
  },
24
24
  "license": "ISC",
25
25
  "dependencies": {
26
- "@netacea/kinesisingest": "^1.5.31",
27
- "@netacea/netaceaintegrationbase": "^2.0.13",
26
+ "@netacea/kinesisingest": "^1.5.32",
27
+ "@netacea/netaceaintegrationbase": "^2.0.14",
28
28
  "jose": "^4.11.2"
29
29
  },
30
30
  "devDependencies": {
@@ -56,5 +56,5 @@
56
56
  "tsconfig-paths": "^4.2.0",
57
57
  "typescript": "^5.2.2"
58
58
  },
59
- "gitHead": "44fa8764ea8699496a39bcccbbe5280b54b77362"
59
+ "gitHead": "6faaa2912715ce66712ac984918f7b31b24a9187"
60
60
  }