@getsupertab/supertab-connect-sdk 0.1.0-beta.35 → 0.1.0-beta.37
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.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +8 -1
- package/dist/index.d.ts +8 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/package.json +5 -1
package/dist/index.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var W=Object.create;var b=Object.defineProperty;var j=Object.getOwnPropertyDescriptor;var G=Object.getOwnPropertyNames;var X=Object.getPrototypeOf,z=Object.prototype.hasOwnProperty;var Y=(t,e)=>{for(var r in e)b(t,r,{get:e[r],enumerable:!0})},P=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of G(e))!z.call(t,s)&&s!==r&&b(t,s,{get:()=>e[s],enumerable:!(n=j(e,s))||n.enumerable});return t};var Q=(t,e,r)=>(r=t!=null?W(X(t)):{},P(e||!t||!t.__esModule?b(r,"default",{value:t,enumerable:!0}):r,t)),Z=t=>P(b({},"__esModule",{value:!0}),t);var ue={};Y(ue,{EnforcementMode:()=>I,HandlerAction:()=>R,SupertabConnect:()=>T,defaultBotDetector:()=>J});module.exports=Z(ue);var I=(n=>(n.DISABLED="disabled",n.SOFT="soft",n.STRICT="strict",n))(I||{});var y="stc-backend",R=(r=>(r.ALLOW="allow",r.BLOCK="block",r))(R||{});var w=null;function S(){return w||(w=import("jose")),w}async function ee(t,e,r){try{let n=await fetch(t,e);if(!n.ok){let o=await n.text().catch(()=>""),a=`Failed to obtain license token: ${n.status} ${n.statusText}${o?` - ${o}`:""}`;throw new Error(a)}let s;try{s=await n.json()}catch(o){throw r&&console.error("Failed to parse license token response as JSON:",o),new Error("Failed to parse license token response as JSON")}if(!s?.access_token)throw new Error("License token response missing access_token");return s.access_token}catch(n){throw r&&console.error("Error generating license token:",n),n}}async function te(t,e){let n=`${new URL(t).origin}/license.xml`,s=await fetch(n);if(!s.ok)throw e&&console.error(`Failed to fetch license.xml from ${n}: ${s.status}`),new Error(`Failed to fetch license.xml from ${n}: ${s.status}`);let o=await s.text();return e&&console.debug("Fetched license.xml from",n),o}function re(t,e){let r=[],n=/<content\s([^>]*)>([\s\S]*?)<\/content>/gi,s=/url\s*=\s*"([^"]*)"/i,o=/server\s*=\s*"([^"]*)"/i,a=/<license[^>]*>[\s\S]*?<\/license>/i,c=0,i;for(;(i=n.exec(t))!==null;){c++;let l=i[1],d=i[2],p=l.match(s),m=l.match(o),g=d.match(a);if(p&&m&&g)r.push({urlPattern:p[1],server:m[1],licenseXml:g[0]});else if(e){let A=[!p&&"url",!m&&"server",!g&&"<license>"].filter(Boolean).join(", ");console.debug(`Skipping <content> element #${c}: missing ${A}`)}}return e&&console.debug(`Found ${c} <content> element(s), ${r.length} valid`),r}function ne(t,e,r){let n=new URL(e),s=n.host,o=n.pathname;r&&console.debug(`Matching resource URL: ${e} (host=${s}, path=${o})`);let a=null,c=-1;for(let i of t){let l;try{l=new URL(i.urlPattern)}catch{r&&console.debug(`Skipping block with invalid URL pattern: ${i.urlPattern}`);continue}if(l.host!==s){r&&console.debug(`Skipping block: host mismatch (pattern=${l.host}, resource=${s})`);continue}let d=l.pathname;if(d===o)return r&&console.debug(`Exact match found: ${i.urlPattern}`),i;if(d.endsWith("/*")){let p=d.slice(0,-1);if(o.startsWith(p)){let m=p.length;m>c&&(c=m,a=i)}}}return r&&console.debug(a?`Wildcard match found: ${a.urlPattern} (specificity=${c})`:`No matching content block found for ${e}`),a}async function N({clientId:t,clientSecret:e,resourceUrl:r,debug:n}){let s=await te(r,n);n&&console.debug(`Fetched license.xml (${s.length} chars)`);let o=re(s,n);if(o.length===0)throw n&&console.error("No valid <content> elements with <license> found in license.xml"),new Error("No valid <content> elements with <license> found in license.xml");let a=ne(o,r,n);if(!a){if(n){let d=o.map(p=>p.urlPattern).join(", ");console.error(`No <content> element matches resource URL: ${r}. Available patterns: ${d}`)}throw new Error(`No <content> element in license.xml matches resource URL: ${r}`)}n&&(console.debug("Matched content block for resource URL:",r),console.debug("Using license XML:",a.licenseXml));let c=a.server+"/token";n&&console.debug(`Requesting license token from ${c}`);let i=new URLSearchParams({grant_type:"client_credentials",license:a.licenseXml,resource:a.urlPattern}),l={method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json",Authorization:"Basic "+btoa(`${t}:${e}`)},body:i.toString()};return ee(c,l,n)}var k=new Map;function se(){let t={method:"GET"};return globalThis?.fastly&&(t={...t,backend:y}),t}async function oe({cacheKey:t,url:e,debug:r,failureMessage:n,logLabel:s}){if(!k.has(t))try{let o=await fetch(e,se());if(!o.ok)throw new Error(`${n}: ${o.status}`);let a=await o.json();k.set(t,a)}catch(o){throw r&&console.error(s,o),o}return k.get(t)}async function q(t,e){let r=`${t}/.well-known/jwks.json/platform`;return e&&console.debug(`Fetching platform JWKS from URL: ${r}`),oe({cacheKey:"platform_jwks",url:r,debug:e,failureMessage:"Failed to fetch platform JWKS",logLabel:"Error fetching platform JWKS:"})}async function F({apiKey:t,merchantSystemUrn:e,baseUrl:r,eventName:n,properties:s,licenseId:o,debug:a=!1}){let c={event_name:n,merchant_system_urn:e,license_id:o,properties:s};try{let i={method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify(c)};globalThis?.fastly&&(i={...i,backend:y});let l=await fetch(`${r}/events`,i);!l.ok&&a&&console.error(`Failed to record event: ${l.status}`)}catch(i){a&&console.error("Error recording event:",i)}}var L=t=>t.trim().replace(/\/+$/,"");function h(t){switch(t){case"missing_license_token":return"Authorization header missing or malformed";case"invalid_license_algorithm":return"Unsupported token algorithm";case"license_token_expired":return"The license token has expired";case"license_signature_verification_failed":return"The license token signature is invalid";case"invalid_license_header":return"The license token header is malformed";case"invalid_license_payload":return"The license token payload is malformed";case"invalid_license_issuer":return"The license token issuer is not recognized";case"invalid_license_audience":return"The license does not grant access to this resource";case"server_error":return"The server encountered an error validating the license";default:return"License token missing, expired, revoked, or malformed"}}async function x({licenseToken:t,requestUrl:e,supertabBaseUrl:r,debug:n}){let{decodeProtectedHeader:s,decodeJwt:o,jwtVerify:a}=await S();if(!t)return{valid:!1,reason:"missing_license_token",error:h("missing_license_token")};let c;try{c=s(t)}catch(f){return n&&console.error("Invalid license JWT header:",f),{valid:!1,reason:"invalid_license_header",error:h("invalid_license_header")}}if(c.alg!=="ES256")return n&&console.error("Unsupported license JWT alg:",c.alg),{valid:!1,reason:"invalid_license_algorithm",error:h("invalid_license_algorithm")};let i;try{i=o(t)}catch(f){return n&&console.error("Invalid license JWT payload:",f),{valid:!1,reason:"invalid_license_payload",error:h("invalid_license_payload")}}let l=i.license_id,d=i.iss,p=d?L(d):void 0,m=L(r);if(!p||!p.startsWith(m))return n&&console.error("License JWT issuer is missing or malformed:",d),{valid:!1,reason:"invalid_license_issuer",error:h("invalid_license_issuer"),licenseId:l};let g=Array.isArray(i.aud)?i.aud.filter(f=>typeof f=="string"):typeof i.aud=="string"?[i.aud]:[],A=L(e);if(!g.some(f=>{let E=L(f);return E?A.startsWith(E):!1}))return n&&console.error("License JWT audience does not match request URL:",i.aud),{valid:!1,reason:"invalid_license_audience",error:h("invalid_license_audience"),licenseId:l};let C;try{C=await q(r,n)}catch(f){return n&&console.error("Failed to fetch platform JWKS:",f),{valid:!1,reason:"server_error",error:h("server_error"),licenseId:l}}try{let E=await a(t,async _=>{let D=C.keys.find(M=>M.kid===_.kid);if(!D)throw new Error(`No matching platform key found: ${_.kid}`);return D},{issuer:d,algorithms:[c.alg],clockTolerance:"1m"});return{valid:!0,licenseId:l,payload:E.payload}}catch(f){return n&&console.error("License JWT verification failed:",f),f instanceof Error&&f.message?.includes("exp")?{valid:!1,reason:"license_token_expired",error:h("license_token_expired"),licenseId:l}:{valid:!1,reason:"license_signature_verification_failed",error:h("license_signature_verification_failed"),licenseId:l}}}function O({requestUrl:t}){let e=new URL(t);return`${e.protocol}//${e.host}/license.xml`}function $(t){let e=O({requestUrl:t});return{action:"allow",headers:{Link:`<${e}>; rel="license"; type="application/rsl+xml"`,"X-RSL-Status":"token_required","X-RSL-Reason":"missing"}}}function ae(t){switch(t){case"missing_license_token":case"invalid_license_algorithm":return{rslError:"invalid_request",status:401};case"license_token_expired":case"license_signature_verification_failed":case"invalid_license_header":case"invalid_license_payload":case"invalid_license_issuer":return{rslError:"invalid_token",status:401};case"invalid_license_audience":return{rslError:"insufficient_scope",status:403};case"server_error":return{rslError:"server_error",status:503};default:return{rslError:"invalid_token",status:401}}}function ce(t){return t.replace(/[\r\n]/g,"").replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function U({reason:t,error:e,requestUrl:r}){let{rslError:n,status:s}=ae(t),o=ce(e),a=O({requestUrl:r});return{action:"block",status:s,body:`Access to this resource requires a valid license token. Error: ${n} - ${e}`,headers:{"Content-Type":"text/plain; charset=UTF-8","WWW-Authenticate":`License error="${n}", error_description="${o}"`,Link:`<${a}>; rel="license"; type="application/rsl+xml"`}}}function le(){let t={method:"GET"};return globalThis?.fastly&&(t={...t,backend:y}),t}async function B(t,e){let r=`${t}/merchants/systems/${e}/license.xml`,n=await fetch(r,le());if(!n.ok)return new Response("License not found",{status:404});let s=await n.text();return new Response(s,{status:200,headers:new Headers({"Content-Type":"application/xml"})})}async function v(t){let e=await x({licenseToken:t.token,requestUrl:t.url,supertabBaseUrl:t.supertabBaseUrl,debug:t.debug}),r=F({apiKey:t.apiKey,merchantSystemUrn:t.merchantSystemUrn,baseUrl:t.supertabBaseUrl,eventName:e.valid?"license_used":e.reason,properties:{page_url:t.url,user_agent:t.userAgent,verification_status:e.valid?"valid":"invalid",verification_reason:e.valid?"success":e.reason},licenseId:e.licenseId,debug:t.debug});return t.ctx?.waitUntil&&t.ctx.waitUntil(r),e}async function H(t,e,r){let n=await t.handleRequest(e,r);if(n.action==="block")return new Response(n.body,{status:n.status,headers:new Headers(n.headers)});let s=await fetch(e);if(n.headers){let o=new Response(s.body,s);for(let[a,c]of Object.entries(n.headers))o.headers.set(a,c);return o}return s}async function K(t,e,r,n){if(n&&new URL(e.url).pathname==="/license.xml")return await B(n.baseUrl,n.merchantSystemUrn);let s=await t.handleRequest(e);if(s.action==="block")return new Response(s.body,{status:s.status,headers:new Headers(s.headers)});let o=await fetch(e,{backend:r});if(s.headers){let a=new Response(o.body,o);for(let[c,i]of Object.entries(s.headers))a.headers.set(c,i);return a}return o}async function V(t,e){let r=e.Records[0].cf.request,n=`https://${r.headers.host[0].value}${r.uri}${r.querystring?"?"+r.querystring:""}`,s=new Headers;Object.entries(r.headers).forEach(([c,i])=>{i.forEach(({value:l})=>s.append(c,l))});let o=new Request(n,{method:r.method,headers:s}),a=await t.handleRequest(o);if(a.action==="block"){let c={};return Object.entries(a.headers).forEach(([i,l])=>{c[i.toLowerCase()]=[{key:i,value:l}]}),{status:a.status.toString(),statusDescription:a.status===401?"Unauthorized":"Payment Required",headers:c,body:a.body}}return r}function J(t){let e=t.headers.get("User-Agent")||"",r=t.headers.get("accept")||"",n=t.headers.get("sec-ch-ua"),s=t.headers.get("accept-language"),o=t.cf?.botManagement?.score,a=["chatgpt-user","perplexitybot","gptbot","anthropic-ai","ccbot","claude-web","claudebot","cohere-ai","youbot","diffbot","oai-searchbot","meta-externalagent","timpibot","amazonbot","bytespider","perplexity-user","googlebot","bot","curl","wget"],c=e.toLowerCase(),i=a.some(g=>c.includes(g)),l=c.includes("headless")||c.includes("puppeteer")||!n,d=!c.includes("headless")&&!c.includes("puppeteer")&&!n,p=!r||!s,m=typeof o=="number"&&o<30;return(c.includes("safari")||c.includes("mozilla"))&&l&&d?!1:i||l||p||m}var u=class u{constructor(e,r=!1){if(!r&&u._instance){if(!(e.apiKey===u._instance.apiKey&&e.merchantSystemUrn===u._instance.merchantSystemUrn))throw new Error("Cannot create a new instance with different configuration. Use resetInstance to clear the existing instance.");return u._instance}if(r&&u._instance&&u.resetInstance(),!e.apiKey||!e.merchantSystemUrn)throw new Error("Missing required configuration: apiKey and merchantSystemUrn are required");this.apiKey=e.apiKey,this.merchantSystemUrn=e.merchantSystemUrn,this.enforcement=e.enforcement??"soft",this.botDetector=e.botDetector,this.debug=e.debug??!1,u._instance=this}static resetInstance(){u._instance=null}static setBaseUrl(e){u.baseUrl=e}static getBaseUrl(){return u.baseUrl}static async verify(e){let r=e.baseUrl??u.baseUrl,n=await x({licenseToken:e.token,requestUrl:e.resourceUrl,supertabBaseUrl:r,debug:e.debug??!1});return n.valid?{valid:!0}:{valid:!1,error:n.error}}async verifyAndRecord(e){let r=await v({token:e.token,url:e.resourceUrl,userAgent:e.userAgent??"unknown",supertabBaseUrl:u.baseUrl,debug:e.debug??this.debug,apiKey:this.apiKey,merchantSystemUrn:this.merchantSystemUrn,ctx:e.ctx});return r.valid?{valid:!0}:{valid:!1,error:r.error}}async handleRequest(e,r){let n=e.headers.get("Authorization")||"",s=n.startsWith("License ")?n.slice(8):null,o=e.url,a=e.headers.get("User-Agent")||"unknown";if(s){if(this.enforcement==="disabled")return{action:"allow"};let i=await v({token:s,url:o,userAgent:a,supertabBaseUrl:u.baseUrl,debug:this.debug,apiKey:this.apiKey,merchantSystemUrn:this.merchantSystemUrn,ctx:r});return i.valid?{action:"allow"}:U({reason:i.reason,error:i.error,requestUrl:o})}if(!(this.botDetector?.(e,r)??!1))return{action:"allow"};switch(this.enforcement){case"strict":return U({reason:"missing_license_token",error:"Authorization header missing or malformed",requestUrl:o});case"soft":return $(o);default:return{action:"allow"}}}static async obtainLicenseToken(e){return N({clientId:e.clientId,clientSecret:e.clientSecret,resourceUrl:e.resourceUrl,debug:e.debug})}static async cloudflareHandleRequests(e,r,n){let s=new u({apiKey:r.MERCHANT_API_KEY,merchantSystemUrn:r.MERCHANT_SYSTEM_URN});return H(s,e,n)}static async fastlyHandleRequests(e,r,n,s,o){let{enableRSL:a=!1,botDetector:c,enforcement:i}=o??{},l=new u({apiKey:n,merchantSystemUrn:r,botDetector:c,enforcement:i});return K(l,e,s,a?{baseUrl:u.baseUrl,merchantSystemUrn:r}:void 0)}static async cloudfrontHandleRequests(e,r){let n=new u({apiKey:r.apiKey,merchantSystemUrn:r.merchantSystemUrn,botDetector:r.botDetector,enforcement:r.enforcement});return V(n,e)}};u.baseUrl="https://api-connect.supertab.co",u._instance=null;var T=u;0&&(module.exports={EnforcementMode,HandlerAction,SupertabConnect,defaultBotDetector});
|
|
1
|
+
"use strict";var X=Object.create;var w=Object.defineProperty;var z=Object.getOwnPropertyDescriptor;var Y=Object.getOwnPropertyNames;var Q=Object.getPrototypeOf,Z=Object.prototype.hasOwnProperty;var ee=(t,e)=>{for(var r in e)w(t,r,{get:e[r],enumerable:!0})},P=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Y(e))!Z.call(t,s)&&s!==r&&w(t,s,{get:()=>e[s],enumerable:!(n=z(e,s))||n.enumerable});return t};var R=(t,e,r)=>(r=t!=null?X(Q(t)):{},P(e||!t||!t.__esModule?w(r,"default",{value:t,enumerable:!0}):r,t)),te=t=>P(w({},"__esModule",{value:!0}),t);var me={};ee(me,{EnforcementMode:()=>S,HandlerAction:()=>b,SupertabConnect:()=>T,defaultBotDetector:()=>j});module.exports=te(me);var S=(n=>(n.DISABLED="disabled",n.SOFT="soft",n.STRICT="strict",n))(S||{});var y="stc-backend",b=(r=>(r.ALLOW="allow",r.BLOCK="block",r))(b||{});function E(t){let e=null;return()=>(e||(e=t()),e)}var N=E(()=>import("jose/jwt/verify")),q=E(()=>import("jose/jwt/decode")),F=E(()=>import("jose/decode/protected_header")),re=E(()=>import("jose/key/import")),ne=E(()=>import("jose/jwt/sign"));async function se(t,e,r){try{let n=await fetch(t,e);if(!n.ok){let o=await n.text().catch(()=>""),a=`Failed to obtain license token: ${n.status} ${n.statusText}${o?` - ${o}`:""}`;throw new Error(a)}let s;try{s=await n.json()}catch(o){throw r&&console.error("Failed to parse license token response as JSON:",o),new Error("Failed to parse license token response as JSON")}if(!s?.access_token)throw new Error("License token response missing access_token");return s.access_token}catch(n){throw r&&console.error("Error generating license token:",n),n}}async function oe(t,e){let n=`${new URL(t).origin}/license.xml`,s=await fetch(n);if(!s.ok)throw e&&console.error(`Failed to fetch license.xml from ${n}: ${s.status}`),new Error(`Failed to fetch license.xml from ${n}: ${s.status}`);let o=await s.text();return e&&console.debug("Fetched license.xml from",n),o}function ie(t,e){let r=[],n=/<content\s([^>]*)>([\s\S]*?)<\/content>/gi,s=/url\s*=\s*"([^"]*)"/i,o=/server\s*=\s*"([^"]*)"/i,a=/<license[^>]*>[\s\S]*?<\/license>/i,c=0,i;for(;(i=n.exec(t))!==null;){c++;let l=i[1],d=i[2],p=l.match(s),m=l.match(o),g=d.match(a);if(p&&m&&g)r.push({urlPattern:p[1],server:m[1],licenseXml:g[0]});else if(e){let A=[!p&&"url",!m&&"server",!g&&"<license>"].filter(Boolean).join(", ");console.debug(`Skipping <content> element #${c}: missing ${A}`)}}return e&&console.debug(`Found ${c} <content> element(s), ${r.length} valid`),r}function ae(t,e,r){let n=new URL(e),s=n.host,o=n.pathname;r&&console.debug(`Matching resource URL: ${e} (host=${s}, path=${o})`);let a=null,c=-1;for(let i of t){let l;try{l=new URL(i.urlPattern)}catch{r&&console.debug(`Skipping block with invalid URL pattern: ${i.urlPattern}`);continue}if(l.host!==s){r&&console.debug(`Skipping block: host mismatch (pattern=${l.host}, resource=${s})`);continue}let d=l.pathname;if(d===o)return r&&console.debug(`Exact match found: ${i.urlPattern}`),i;if(d.endsWith("/*")){let p=d.slice(0,-1);if(o.startsWith(p)){let m=p.length;m>c&&(c=m,a=i)}}}return r&&console.debug(a?`Wildcard match found: ${a.urlPattern} (specificity=${c})`:`No matching content block found for ${e}`),a}async function O({clientId:t,clientSecret:e,resourceUrl:r,debug:n}){let s=await oe(r,n);n&&console.debug(`Fetched license.xml (${s.length} chars)`);let o=ie(s,n);if(o.length===0)throw n&&console.error("No valid <content> elements with <license> found in license.xml"),new Error("No valid <content> elements with <license> found in license.xml");let a=ae(o,r,n);if(!a){if(n){let d=o.map(p=>p.urlPattern).join(", ");console.error(`No <content> element matches resource URL: ${r}. Available patterns: ${d}`)}throw new Error(`No <content> element in license.xml matches resource URL: ${r}`)}n&&(console.debug("Matched content block for resource URL:",r),console.debug("Using license XML:",a.licenseXml));let c=a.server+"/token";n&&console.debug(`Requesting license token from ${c}`);let i=new URLSearchParams({grant_type:"client_credentials",license:a.licenseXml,resource:a.urlPattern}),l={method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json",Authorization:"Basic "+btoa(`${t}:${e}`)},body:i.toString()};return se(c,l,n)}var k=new Map;function ce(){let t={method:"GET"};return globalThis?.fastly&&(t={...t,backend:y}),t}async function le({cacheKey:t,url:e,debug:r,failureMessage:n,logLabel:s}){if(!k.has(t))try{let o=await fetch(e,ce());if(!o.ok)throw new Error(`${n}: ${o.status}`);let a=await o.json();k.set(t,a)}catch(o){throw r&&console.error(s,o),o}return k.get(t)}async function H(t,e){let r=`${t}/.well-known/jwks.json/platform`;return e&&console.debug(`Fetching platform JWKS from URL: ${r}`),le({cacheKey:"platform_jwks",url:r,debug:e,failureMessage:"Failed to fetch platform JWKS",logLabel:"Error fetching platform JWKS:"})}async function K({apiKey:t,merchantSystemUrn:e,baseUrl:r,eventName:n,properties:s,licenseId:o,debug:a=!1}){let c={event_name:n,merchant_system_urn:e,license_id:o,properties:s};try{let i={method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify(c)};globalThis?.fastly&&(i={...i,backend:y});let l=await fetch(`${r}/events`,i);!l.ok&&a&&console.error(`Failed to record event: ${l.status}`)}catch(i){a&&console.error("Error recording event:",i)}}var I=t=>t.trim().replace(/\/+$/,"");function h(t){switch(t){case"missing_license_token":return"Authorization header missing or malformed";case"invalid_license_algorithm":return"Unsupported token algorithm";case"license_token_expired":return"The license token has expired";case"license_signature_verification_failed":return"The license token signature is invalid";case"invalid_license_header":return"The license token header is malformed";case"invalid_license_payload":return"The license token payload is malformed";case"invalid_license_issuer":return"The license token issuer is not recognized";case"invalid_license_audience":return"The license does not grant access to this resource";case"server_error":return"The server encountered an error validating the license";default:return"License token missing, expired, revoked, or malformed"}}async function x({licenseToken:t,requestUrl:e,supertabBaseUrl:r,debug:n}){let{decodeProtectedHeader:s}=await F(),{decodeJwt:o}=await q(),{jwtVerify:a}=await N();if(!t)return{valid:!1,reason:"missing_license_token",error:h("missing_license_token")};let c;try{c=s(t)}catch(f){return n&&console.error("Invalid license JWT header:",f),{valid:!1,reason:"invalid_license_header",error:h("invalid_license_header")}}if(c.alg!=="ES256")return n&&console.error("Unsupported license JWT alg:",c.alg),{valid:!1,reason:"invalid_license_algorithm",error:h("invalid_license_algorithm")};let i;try{i=o(t)}catch(f){return n&&console.error("Invalid license JWT payload:",f),{valid:!1,reason:"invalid_license_payload",error:h("invalid_license_payload")}}let l=i.license_id,d=i.iss,p=d?I(d):void 0,m=I(r);if(!p||!p.startsWith(m))return n&&console.error("License JWT issuer is missing or malformed:",d),{valid:!1,reason:"invalid_license_issuer",error:h("invalid_license_issuer"),licenseId:l};let g=Array.isArray(i.aud)?i.aud.filter(f=>typeof f=="string"):typeof i.aud=="string"?[i.aud]:[],A=I(e);if(!g.some(f=>{let L=I(f);return L?A.startsWith(L):!1}))return n&&console.error("License JWT audience does not match request URL:",i.aud),{valid:!1,reason:"invalid_license_audience",error:h("invalid_license_audience"),licenseId:l};let C;try{C=await H(r,n)}catch(f){return n&&console.error("Failed to fetch platform JWKS:",f),{valid:!1,reason:"server_error",error:h("server_error"),licenseId:l}}try{let L=await a(t,async _=>{let D=C.keys.find(G=>G.kid===_.kid);if(!D)throw new Error(`No matching platform key found: ${_.kid}`);return D},{issuer:d,algorithms:[c.alg],clockTolerance:"1m"});return{valid:!0,licenseId:l,payload:L.payload}}catch(f){return n&&console.error("License JWT verification failed:",f),f instanceof Error&&f.message?.includes("exp")?{valid:!1,reason:"license_token_expired",error:h("license_token_expired"),licenseId:l}:{valid:!1,reason:"license_signature_verification_failed",error:h("license_signature_verification_failed"),licenseId:l}}}function V({requestUrl:t}){let e=new URL(t);return`${e.protocol}//${e.host}/license.xml`}function $(t){let e=V({requestUrl:t});return{action:"allow",headers:{Link:`<${e}>; rel="license"; type="application/rsl+xml"`,"X-RSL-Status":"token_required","X-RSL-Reason":"missing"}}}function de(t){switch(t){case"missing_license_token":case"invalid_license_algorithm":return{rslError:"invalid_request",status:401};case"license_token_expired":case"license_signature_verification_failed":case"invalid_license_header":case"invalid_license_payload":case"invalid_license_issuer":return{rslError:"invalid_token",status:401};case"invalid_license_audience":return{rslError:"insufficient_scope",status:403};case"server_error":return{rslError:"server_error",status:503};default:return{rslError:"invalid_token",status:401}}}function fe(t){return t.replace(/[\r\n]/g,"").replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function U({reason:t,error:e,requestUrl:r}){let{rslError:n,status:s}=de(t),o=fe(e),a=V({requestUrl:r});return{action:"block",status:s,body:`Access to this resource requires a valid license token. Error: ${n} - ${e}`,headers:{"Content-Type":"text/plain; charset=UTF-8","WWW-Authenticate":`License error="${n}", error_description="${o}"`,Link:`<${a}>; rel="license"; type="application/rsl+xml"`}}}function pe(){let t={method:"GET"};return globalThis?.fastly&&(t={...t,backend:y}),t}async function B(t,e){let r=`${t}/merchants/systems/${e}/license.xml`,n=await fetch(r,pe());if(!n.ok)return new Response("License not found",{status:404});let s=await n.text();return new Response(s,{status:200,headers:new Headers({"Content-Type":"application/xml"})})}async function v(t){let e=await x({licenseToken:t.token,requestUrl:t.url,supertabBaseUrl:t.supertabBaseUrl,debug:t.debug}),r=K({apiKey:t.apiKey,merchantSystemUrn:t.merchantSystemUrn,baseUrl:t.supertabBaseUrl,eventName:e.valid?"license_used":e.reason,properties:{page_url:t.url,user_agent:t.userAgent,verification_status:e.valid?"valid":"invalid",verification_reason:e.valid?"success":e.reason},licenseId:e.licenseId,debug:t.debug});return t.ctx?.waitUntil&&t.ctx.waitUntil(r),e}async function J(t,e,r){let n=await t.handleRequest(e,r);if(n.action==="block")return new Response(n.body,{status:n.status,headers:new Headers(n.headers)});let s=await fetch(e);if(n.headers){let o=new Response(s.body,s);for(let[a,c]of Object.entries(n.headers))o.headers.set(a,c);return o}return s}async function W(t,e,r,n){if(n&&new URL(e.url).pathname==="/license.xml")return await B(n.baseUrl,n.merchantSystemUrn);let s=await t.handleRequest(e);if(s.action==="block")return new Response(s.body,{status:s.status,headers:new Headers(s.headers)});let o=await fetch(e,{backend:r});if(s.headers){let a=new Response(o.body,o);for(let[c,i]of Object.entries(s.headers))a.headers.set(c,i);return a}return o}async function M(t,e){let r=e.Records[0].cf.request,n=`https://${r.headers.host[0].value}${r.uri}${r.querystring?"?"+r.querystring:""}`,s=new Headers;Object.entries(r.headers).forEach(([c,i])=>{i.forEach(({value:l})=>s.append(c,l))});let o=new Request(n,{method:r.method,headers:s}),a=await t.handleRequest(o);if(a.action==="block"){let c={};return Object.entries(a.headers).forEach(([i,l])=>{c[i.toLowerCase()]=[{key:i,value:l}]}),{status:a.status.toString(),statusDescription:a.status===401?"Unauthorized":"Payment Required",headers:c,body:a.body}}return r}function j(t){let e=t.headers.get("User-Agent")||"",r=t.headers.get("accept")||"",n=t.headers.get("sec-ch-ua"),s=t.headers.get("accept-language"),o=t.cf?.botManagement?.score,a=["chatgpt-user","perplexitybot","gptbot","anthropic-ai","ccbot","claude-web","claudebot","cohere-ai","youbot","diffbot","oai-searchbot","meta-externalagent","timpibot","amazonbot","bytespider","perplexity-user","googlebot","bot","curl","wget"],c=e.toLowerCase(),i=a.some(g=>c.includes(g)),l=c.includes("headless")||c.includes("puppeteer")||!n,d=!c.includes("headless")&&!c.includes("puppeteer")&&!n,p=!r||!s,m=typeof o=="number"&&o<30;return(c.includes("safari")||c.includes("mozilla"))&&l&&d?!1:i||l||p||m}var u=class u{constructor(e,r=!1){if(!r&&u._instance){if(!(e.apiKey===u._instance.apiKey&&e.merchantSystemUrn===u._instance.merchantSystemUrn))throw new Error("Cannot create a new instance with different configuration. Use resetInstance to clear the existing instance.");return u._instance}if(r&&u._instance&&u.resetInstance(),!e.apiKey||!e.merchantSystemUrn)throw new Error("Missing required configuration: apiKey and merchantSystemUrn are required");this.apiKey=e.apiKey,this.merchantSystemUrn=e.merchantSystemUrn,this.enforcement=e.enforcement??"soft",this.botDetector=e.botDetector,this.debug=e.debug??!1,u._instance=this}static resetInstance(){u._instance=null}static setBaseUrl(e){u.baseUrl=e}static getBaseUrl(){return u.baseUrl}static async verify(e){let r=e.baseUrl??u.baseUrl,n=await x({licenseToken:e.token,requestUrl:e.resourceUrl,supertabBaseUrl:r,debug:e.debug??!1});return n.valid?{valid:!0}:{valid:!1,error:n.error}}async verifyAndRecord(e){let r=await v({token:e.token,url:e.resourceUrl,userAgent:e.userAgent??"unknown",supertabBaseUrl:u.baseUrl,debug:e.debug??this.debug,apiKey:this.apiKey,merchantSystemUrn:this.merchantSystemUrn,ctx:e.ctx});return r.valid?{valid:!0}:{valid:!1,error:r.error}}async handleRequest(e,r){let n=e.headers.get("Authorization")||"",s=n.startsWith("License ")?n.slice(8):null,o=e.url,a=e.headers.get("User-Agent")||"unknown";if(s){if(this.enforcement==="disabled")return{action:"allow"};let i=await v({token:s,url:o,userAgent:a,supertabBaseUrl:u.baseUrl,debug:this.debug,apiKey:this.apiKey,merchantSystemUrn:this.merchantSystemUrn,ctx:r});return i.valid?{action:"allow"}:U({reason:i.reason,error:i.error,requestUrl:o})}if(!(this.botDetector?.(e,r)??!1))return{action:"allow"};switch(this.enforcement){case"strict":return U({reason:"missing_license_token",error:"Authorization header missing or malformed",requestUrl:o});case"soft":return $(o);default:return{action:"allow"}}}static async obtainLicenseToken(e){return O({clientId:e.clientId,clientSecret:e.clientSecret,resourceUrl:e.resourceUrl,debug:e.debug})}static async cloudflareHandleRequests(e,r,n,s){let o=new u({apiKey:r.MERCHANT_API_KEY,merchantSystemUrn:r.MERCHANT_SYSTEM_URN,botDetector:s?.botDetector,enforcement:s?.enforcement});return J(o,e,n)}static async fastlyHandleRequests(e,r,n,s,o){let{enableRSL:a=!1,botDetector:c,enforcement:i}=o??{},l=new u({apiKey:n,merchantSystemUrn:r,botDetector:c,enforcement:i});return W(l,e,s,a?{baseUrl:u.baseUrl,merchantSystemUrn:r}:void 0)}static async cloudfrontHandleRequests(e,r){let n=new u({apiKey:r.apiKey,merchantSystemUrn:r.merchantSystemUrn,botDetector:r.botDetector,enforcement:r.enforcement});return M(n,e)}};u.baseUrl="https://api-connect.supertab.co",u._instance=null;var T=u;0&&(module.exports={EnforcementMode,HandlerAction,SupertabConnect,defaultBotDetector});
|
|
2
2
|
//# sourceMappingURL=index.cjs.map
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/types.ts","../src/jose.ts","../src/customer.ts","../src/jwks.ts","../src/events.ts","../src/license.ts","../src/cdn.ts","../src/bots.ts"],"sourcesContent":["import {\n SupertabConnectConfig,\n EnforcementMode,\n BotDetector,\n HandlerAction,\n HandlerResult,\n LicenseTokenInvalidReason,\n RSLVerificationResult,\n ExecutionContext,\n Env,\n} from \"./types\";\nimport { obtainLicenseToken as obtainLicenseTokenHelper } from \"./customer\";\nimport {\n buildBlockResult,\n buildSignalResult,\n verifyLicenseToken as verifyLicenseTokenHelper,\n verifyAndRecordEvent,\n} from \"./license\";\nimport {\n handleCloudflareRequest,\n handleFastlyRequest,\n handleCloudfrontRequest,\n} from \"./cdn\";\nimport {\n CloudFrontRequestEvent,\n CloudFrontRequestResult,\n CloudfrontHandlerOptions,\n} from \"./types\";\n\nexport { EnforcementMode, HandlerAction };\nexport type {\n RSLVerificationResult,\n ExecutionContext,\n Env,\n BotDetector,\n HandlerResult,\n CloudFrontRequestEvent,\n CloudFrontRequestResult,\n CloudfrontHandlerOptions,\n};\nexport { defaultBotDetector } from \"./bots\";\n\n/**\n * SupertabConnect class provides higher level methods\n * for using Supertab Connect within supported CDN integrations\n * as well as more specialized methods to customarily verify JWT tokens and record events.\n */\nexport class SupertabConnect {\n private apiKey?: string;\n private static baseUrl: string = \"https://api-connect.supertab.co\";\n private merchantSystemUrn!: string;\n private enforcement!: EnforcementMode;\n private botDetector?: BotDetector;\n private debug!: boolean;\n\n private static _instance: SupertabConnect | null = null;\n\n /**\n * Create a new SupertabConnect instance (singleton).\n * Returns the existing instance if one exists with the same config.\n * @param config SDK configuration including apiKey and merchantSystemUrn\n * @param reset Pass true to replace an existing instance with different config\n * @throws If an instance with different config already exists and reset is false\n */\n public constructor(config: SupertabConnectConfig, reset: boolean = false) {\n if (!reset && SupertabConnect._instance) {\n // If reset was not requested and an instance conflicts with the provided config, throw an error\n if (\n !(\n config.apiKey === SupertabConnect._instance.apiKey &&\n config.merchantSystemUrn ===\n SupertabConnect._instance.merchantSystemUrn\n )\n ) {\n throw new Error(\n \"Cannot create a new instance with different configuration. Use resetInstance to clear the existing instance.\"\n );\n }\n\n // If an instance already exists and reset is not requested, just return the existing instance\n return SupertabConnect._instance;\n }\n if (reset && SupertabConnect._instance) {\n // ...and if reset is requested and required, clear the existing instance first\n SupertabConnect.resetInstance();\n }\n\n if (!config.apiKey || !config.merchantSystemUrn) {\n throw new Error(\n \"Missing required configuration: apiKey and merchantSystemUrn are required\"\n );\n }\n this.apiKey = config.apiKey;\n this.merchantSystemUrn = config.merchantSystemUrn;\n this.enforcement = config.enforcement ?? EnforcementMode.SOFT;\n this.botDetector = config.botDetector;\n this.debug = config.debug ?? false;\n\n // Register this as the singleton instance\n SupertabConnect._instance = this;\n }\n\n /**\n * Clear the singleton instance, allowing a new one to be created with different config.\n */\n public static resetInstance(): void {\n SupertabConnect._instance = null;\n }\n\n /**\n * Override the default base URL for API requests (intended for local development/testing).\n */\n public static setBaseUrl(url: string): void {\n SupertabConnect.baseUrl = url;\n }\n\n /**\n * Get the current base URL for API requests.\n */\n public static getBaseUrl(): string {\n return SupertabConnect.baseUrl;\n }\n\n /**\n * Pure token verification — verifies a license token without recording any events.\n * @param options.token The license token to verify\n * @param options.resourceUrl The URL of the resource being accessed\n * @param options.baseUrl Optional override for the Supertab Connect API base URL\n * @param options.debug Enable debug logging (default: false)\n * @returns A promise that resolves with the verification result\n */\n static async verify(options: {\n token: string;\n resourceUrl: string;\n baseUrl?: string;\n debug?: boolean;\n }): Promise<RSLVerificationResult> {\n const baseUrl = options.baseUrl ?? SupertabConnect.baseUrl;\n\n const result = await verifyLicenseTokenHelper({\n licenseToken: options.token,\n requestUrl: options.resourceUrl,\n supertabBaseUrl: baseUrl,\n debug: options.debug ?? false,\n });\n\n if (result.valid) {\n return { valid: true };\n }\n\n return { valid: false, error: result.error };\n }\n\n /**\n * Verify a license token and record an analytics event.\n * Uses the instance's apiKey and merchantSystemUrn for event recording.\n * @param options.token The license token to verify\n * @param options.resourceUrl The URL of the resource being accessed\n * @param options.userAgent Optional user agent string for event recording\n * @param options.debug Enable debug logging (default: false)\n * @param options.ctx Optional execution context with waitUntil for non-blocking event recording\n * @returns A promise that resolves with the verification result\n */\n async verifyAndRecord(options: {\n token: string;\n resourceUrl: string;\n userAgent?: string;\n debug?: boolean;\n ctx?: ExecutionContext;\n }): Promise<RSLVerificationResult> {\n const result = await verifyAndRecordEvent({\n token: options.token,\n url: options.resourceUrl,\n userAgent: options.userAgent ?? \"unknown\",\n supertabBaseUrl: SupertabConnect.baseUrl,\n debug: options.debug ?? this.debug,\n apiKey: this.apiKey!,\n merchantSystemUrn: this.merchantSystemUrn,\n ctx: options.ctx,\n });\n\n if (result.valid) {\n return { valid: true };\n }\n\n return { valid: false, error: result.error };\n }\n\n /**\n * Handle an incoming request by extracting the license token, verifying it, and recording an analytics event.\n * When no token is present, bot detection and enforcement mode determine the response.\n * @param request The incoming HTTP request\n * @param ctx Execution context for non-blocking event recording.\n * Pass this from your platform (e.g. Cloudflare Workers)\n * @returns A promise that resolves with the handler result indicating ALLOW or BLOCK request\n */\n async handleRequest(request: Request, ctx?: ExecutionContext): Promise<HandlerResult> {\n const auth = request.headers.get(\"Authorization\") || \"\";\n const token = auth.startsWith(\"License \") ? auth.slice(8) : null;\n const url = request.url;\n const userAgent = request.headers.get(\"User-Agent\") || \"unknown\";\n\n // Token present → ALWAYS validate, regardless of mode or bot detection\n if (token) {\n if (this.enforcement === EnforcementMode.DISABLED) {\n return { action: HandlerAction.ALLOW };\n }\n const verification = await verifyAndRecordEvent({\n token,\n url,\n userAgent,\n supertabBaseUrl: SupertabConnect.baseUrl,\n debug: this.debug,\n apiKey: this.apiKey!,\n merchantSystemUrn: this.merchantSystemUrn,\n ctx,\n });\n if (!verification.valid) {\n return buildBlockResult({\n reason: verification.reason,\n error: verification.error,\n requestUrl: url,\n });\n }\n return { action: HandlerAction.ALLOW };\n }\n\n // No token from here on\n const isBot = this.botDetector?.(request, ctx) ?? false;\n\n if (!isBot) {\n return { action: HandlerAction.ALLOW };\n }\n\n // Bot detected, no token — enforcement mode decides\n switch (this.enforcement) {\n case EnforcementMode.STRICT:\n return buildBlockResult({\n reason: LicenseTokenInvalidReason.MISSING_TOKEN,\n error: \"Authorization header missing or malformed\",\n requestUrl: url,\n });\n case EnforcementMode.SOFT:\n return buildSignalResult(url);\n default: // DISABLED\n return { action: HandlerAction.ALLOW };\n }\n }\n\n /**\n * Request a license token from the Supertab Connect token endpoint.\n * @param options.clientId OAuth client identifier.\n * @param options.clientSecret OAuth client secret for client_credentials flow.\n * @param options.resourceUrl Resource URL attempting to access with a License.\n * @param options.debug Enable debug logging (default: false).\n * @returns Promise resolving to the issued license access token string.\n */\n static async obtainLicenseToken(options: {\n clientId: string;\n clientSecret: string;\n resourceUrl: string;\n debug?: boolean;\n }): Promise<string> {\n return obtainLicenseTokenHelper({\n clientId: options.clientId,\n clientSecret: options.clientSecret,\n resourceUrl: options.resourceUrl,\n debug: options.debug,\n });\n }\n\n /**\n * Handle incoming requests for Cloudflare Workers.\n * Pass this directly as your Worker's fetch handler.\n * @param request The incoming Worker request\n * @param env Worker environment bindings containing MERCHANT_API_KEY and MERCHANT_SYSTEM_URN\n * @param ctx Worker execution context for non-blocking event recording\n */\n static async cloudflareHandleRequests(\n request: Request,\n env: Env,\n ctx: ExecutionContext\n ): Promise<Response> {\n const instance = new SupertabConnect({\n apiKey: env.MERCHANT_API_KEY,\n merchantSystemUrn: env.MERCHANT_SYSTEM_URN,\n });\n return handleCloudflareRequest(instance, request, ctx);\n }\n\n /**\n * Handle incoming requests for Fastly Compute.\n * @param request The incoming Fastly request\n * @param merchantSystemUrn The merchant system URN for identification\n * @param merchantApiKey The merchant API key for authentication\n * @param originBackend The Fastly backend name to forward allowed requests to\n * @param options.enableRSL Serve license.xml at /license.xml for RSL-compliant clients (default: false)\n * @param options.botDetector Custom bot detection function\n * @param options.enforcement Enforcement mode (default: SOFT)\n */\n static async fastlyHandleRequests(\n request: Request,\n merchantSystemUrn: string,\n merchantApiKey: string,\n originBackend: string,\n options?: {\n enableRSL?: boolean;\n botDetector?: BotDetector;\n enforcement?: EnforcementMode;\n }\n ): Promise<Response> {\n const { enableRSL = false, botDetector, enforcement } = options ?? {};\n\n const instance = new SupertabConnect({\n apiKey: merchantApiKey,\n merchantSystemUrn: merchantSystemUrn,\n botDetector,\n enforcement,\n });\n\n return handleFastlyRequest(\n instance,\n request,\n originBackend,\n enableRSL\n ? {\n baseUrl: SupertabConnect.baseUrl,\n merchantSystemUrn,\n }\n : undefined\n );\n }\n\n /**\n * Handle incoming requests for AWS CloudFront Lambda@Edge.\n * Use as the handler for a viewer-request LambdaEdge function.\n * @param event The CloudFront viewer-request event\n * @param options Configuration including apiKey, merchantSystemUrn, and optional botDetector/enforcement\n */\n static async cloudfrontHandleRequests<TRequest extends Record<string, any>>(\n event: CloudFrontRequestEvent<TRequest>,\n options: CloudfrontHandlerOptions\n ): Promise<CloudFrontRequestResult<TRequest>> {\n const instance = new SupertabConnect({\n apiKey: options.apiKey,\n merchantSystemUrn: options.merchantSystemUrn,\n botDetector: options.botDetector,\n enforcement: options.enforcement,\n });\n return handleCloudfrontRequest(instance, event);\n }\n}\n","export enum EnforcementMode {\n DISABLED = \"disabled\",\n SOFT = \"soft\",\n STRICT = \"strict\",\n}\n\nexport interface ExecutionContext {\n waitUntil(promise: Promise<any>): void;\n}\n\nexport type BotDetector = (request: Request, ctx?: ExecutionContext) => boolean;\n\nexport interface SupertabConnectConfig {\n apiKey: string;\n merchantSystemUrn: string;\n enforcement?: EnforcementMode;\n botDetector?: BotDetector;\n debug?: boolean;\n}\n\n/**\n * Defines the shape for environment variables (used in CloudFlare integration).\n * These are used to identify and authenticate the Merchant System with the Supertab Connect API.\n */\nexport interface Env {\n\t/** The unique identifier for the merchant system. */\n\tMERCHANT_SYSTEM_URN: string;\n\t/** The API key for authenticating with the Supertab Connect. */\n\tMERCHANT_API_KEY: string;\n\t[key: string]: string;\n}\n\nexport interface EventPayload {\n event_name: string;\n license_id?: string;\n merchant_system_urn: string;\n properties: Record<string, any>;\n}\n\nexport type LicenseTokenVerificationResult =\n | { valid: true; licenseId?: string; payload: any }\n | { valid: false; reason: LicenseTokenInvalidReason; error: string; licenseId?: string };\n\nexport enum LicenseTokenInvalidReason {\n MISSING_TOKEN = \"missing_license_token\",\n INVALID_HEADER = \"invalid_license_header\",\n INVALID_ALG = \"invalid_license_algorithm\",\n INVALID_PAYLOAD = \"invalid_license_payload\",\n INVALID_ISSUER = \"invalid_license_issuer\",\n SIGNATURE_VERIFICATION_FAILED = \"license_signature_verification_failed\",\n EXPIRED = \"license_token_expired\",\n INVALID_AUDIENCE = \"invalid_license_audience\",\n SERVER_ERROR = \"server_error\",\n}\n\nexport const FASTLY_BACKEND = \"stc-backend\";\n\nexport interface FetchOptions extends RequestInit {\n // Fastly-specific extension for backend routing\n backend?: string;\n}\n\nexport enum HandlerAction {\n ALLOW = \"allow\",\n BLOCK = \"block\",\n}\n\nexport type HandlerResult =\n | { action: HandlerAction.ALLOW; headers?: Record<string, string> }\n | { action: HandlerAction.BLOCK; status: number; body: string; headers: Record<string, string> };\n\n// CloudFront Lambda@Edge types\n// Uses permissive types to be compatible with aws-lambda package types\nexport interface CloudFrontHeaders {\n [key: string]: Array<{ key?: string; value: string }>;\n}\n\nexport interface CloudFrontResultResponse {\n status: string;\n statusDescription?: string;\n headers?: CloudFrontHeaders;\n bodyEncoding?: \"text\" | \"base64\";\n body?: string;\n}\n\n// CloudFrontRequestEvent uses a generic request type to accept aws-lambda's CloudFrontRequest\nexport interface CloudFrontRequestEvent<TRequest = Record<string, any>> {\n Records: Array<{\n cf: {\n config?: {\n distributionDomainName?: string;\n distributionId?: string;\n eventType?: string;\n requestId?: string;\n };\n request: TRequest & {\n uri: string;\n method: string;\n querystring: string;\n headers: CloudFrontHeaders;\n };\n };\n }>;\n}\n\n// Result can be either the original request (pass-through) or a response\n// Using generic to preserve the original request type for pass-through\nexport type CloudFrontRequestResult<TRequest = Record<string, any>> = TRequest | CloudFrontResultResponse;\n\nexport interface CloudfrontHandlerOptions {\n apiKey: string;\n merchantSystemUrn: string;\n botDetector?: BotDetector;\n enforcement?: EnforcementMode;\n}\n\nexport type RSLVerificationResult = {\n valid: boolean;\n error?: string;\n};\n","type JoseModule = typeof import(\"jose\");\n\nlet joseModulePromise: Promise<JoseModule> | null = null;\n\n/**\n * Lazily load the ESM-only `jose` package so the CommonJS build can call it via dynamic import.\n */\nexport function loadJose(): Promise<JoseModule> {\n if (!joseModulePromise) {\n joseModulePromise = import(\"jose\");\n }\n return joseModulePromise;\n}\n","import { loadJose } from \"./jose\";\n\ntype SupportedAlg = \"RS256\" | \"ES256\";\n\ntype GenerateLicenseTokenParams = {\n clientId: string;\n kid: string;\n privateKeyPem: string;\n tokenEndpoint: string;\n resourceUrl: string;\n licenseXml: string;\n debug?: boolean;\n};\n\ntype ObtainLicenseTokenParams = {\n clientId: string;\n clientSecret: string;\n resourceUrl: string;\n debug?: boolean;\n};\n\ntype ContentBlock = {\n urlPattern: string;\n licenseXml: string;\n server: string;\n};\n\nasync function retrieveLicenseToken(\n tokenEndpoint: string,\n requestOptions: RequestInit,\n debug: boolean | undefined\n) {\n try {\n const response = await fetch(tokenEndpoint, requestOptions);\n\n if (!response.ok) {\n const errorBody = await response.text().catch(() => \"\");\n const errorMessage = `Failed to obtain license token: ${\n response.status\n } ${response.statusText}${errorBody ? ` - ${errorBody}` : \"\"}`;\n throw new Error(errorMessage);\n }\n\n let data: any;\n try {\n data = await response.json();\n } catch (parseError) {\n if (debug) {\n console.error(\n \"Failed to parse license token response as JSON:\",\n parseError\n );\n }\n throw new Error(\"Failed to parse license token response as JSON\");\n }\n\n if (!data?.access_token) {\n throw new Error(\"License token response missing access_token\");\n }\n\n return data.access_token;\n } catch (error) {\n if (debug) {\n console.error(\"Error generating license token:\", error);\n }\n throw error;\n }\n}\n\nasync function importKeyForAlgs(\n privateKeyPem: string,\n debug: boolean | undefined\n): Promise<{ key: CryptoKey; alg: SupportedAlg }> {\n const { importPKCS8 } = await loadJose();\n const supportedAlgs: SupportedAlg[] = [\"ES256\", \"RS256\"];\n\n for (const algorithm of supportedAlgs) {\n try {\n const key = await importPKCS8(privateKeyPem, algorithm);\n return { key, alg: algorithm };\n } catch (importError) {\n if (debug) {\n console.debug(\n `Private key did not import using ${algorithm}, retrying...`,\n importError\n );\n }\n }\n }\n\n throw new Error(\n \"Unsupported private key format. Expected RSA or P-256 EC private key.\"\n );\n}\n\n// Temporarily not exporting this function to reflect only client credentials flow being supported\nasync function generateLicenseToken({\n clientId,\n kid,\n privateKeyPem,\n tokenEndpoint,\n resourceUrl,\n licenseXml,\n debug,\n}: GenerateLicenseTokenParams): Promise<string> {\n const { SignJWT } = await loadJose();\n const { key, alg } = await importKeyForAlgs(privateKeyPem, debug);\n const now = Math.floor(Date.now() / 1000);\n\n const clientAssertion = await new SignJWT({})\n .setProtectedHeader({ alg, kid })\n .setIssuer(clientId)\n .setSubject(clientId)\n .setIssuedAt(now)\n .setExpirationTime(now + 300)\n .setAudience(tokenEndpoint)\n .sign(key);\n\n const payload = new URLSearchParams({\n grant_type: \"rsl\",\n client_assertion_type:\n \"urn:ietf:params:oauth:client-assertion-type:jwt-bearer\",\n client_assertion: clientAssertion,\n license: licenseXml,\n resource: resourceUrl,\n });\n\n const requestOptions: RequestInit = {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/x-www-form-urlencoded\",\n Accept: \"application/json\",\n },\n body: payload.toString(),\n };\n\n return retrieveLicenseToken(tokenEndpoint, requestOptions, debug);\n}\n\nasync function fetchLicenseXml(\n resourceUrl: string,\n debug: boolean | undefined\n): Promise<string> {\n const origin = new URL(resourceUrl).origin;\n const licenseXmlUrl = `${origin}/license.xml`;\n\n const response = await fetch(licenseXmlUrl);\n if (!response.ok) {\n if (debug) {\n console.error(`Failed to fetch license.xml from ${licenseXmlUrl}: ${response.status}`);\n }\n throw new Error(\n `Failed to fetch license.xml from ${licenseXmlUrl}: ${response.status}`\n );\n }\n\n const xml = await response.text();\n if (debug) {\n console.debug(\"Fetched license.xml from\", licenseXmlUrl);\n }\n return xml;\n}\n\nfunction parseContentElements(xml: string, debug?: boolean): ContentBlock[] {\n const contentBlocks: ContentBlock[] = [];\n const contentRegex = /<content\\s([^>]*)>([\\s\\S]*?)<\\/content>/gi;\n const urlRegex = /url\\s*=\\s*\"([^\"]*)\"/i;\n const serverRegex = /server\\s*=\\s*\"([^\"]*)\"/i;\n const licenseRegex = /<license[^>]*>[\\s\\S]*?<\\/license>/i;\n\n let elementCount = 0;\n let match;\n while ((match = contentRegex.exec(xml)) !== null) {\n elementCount++;\n const attrs = match[1];\n const body = match[2];\n const urlMatch = attrs.match(urlRegex);\n const serverMatch = attrs.match(serverRegex);\n const licenseMatch = body.match(licenseRegex);\n\n if (urlMatch && serverMatch && licenseMatch) {\n contentBlocks.push({\n urlPattern: urlMatch[1],\n server: serverMatch[1],\n licenseXml: licenseMatch[0],\n });\n } else if (debug) {\n const missing = [\n !urlMatch && \"url\",\n !serverMatch && \"server\",\n !licenseMatch && \"<license>\",\n ].filter(Boolean).join(\", \");\n console.debug(`Skipping <content> element #${elementCount}: missing ${missing}`);\n }\n }\n\n if (debug) {\n console.debug(`Found ${elementCount} <content> element(s), ${contentBlocks.length} valid`);\n }\n\n return contentBlocks;\n}\n\nfunction findBestMatchingContent(\n contentBlocks: ContentBlock[],\n resourceUrl: string,\n debug?: boolean\n): ContentBlock | null {\n const parsed = new URL(resourceUrl);\n const host = parsed.host;\n const path = parsed.pathname;\n\n if (debug) {\n console.debug(`Matching resource URL: ${resourceUrl} (host=${host}, path=${path})`);\n }\n\n let bestMatch: ContentBlock | null = null;\n let bestSpecificity = -1;\n\n for (const block of contentBlocks) {\n let patternUrl: URL;\n try {\n patternUrl = new URL(block.urlPattern);\n } catch {\n if (debug) {\n console.debug(`Skipping block with invalid URL pattern: ${block.urlPattern}`);\n }\n continue;\n }\n\n if (patternUrl.host !== host) {\n if (debug) {\n console.debug(`Skipping block: host mismatch (pattern=${patternUrl.host}, resource=${host})`);\n }\n continue;\n }\n\n const patternPath = patternUrl.pathname;\n\n if (patternPath === path) {\n if (debug) {\n console.debug(`Exact match found: ${block.urlPattern}`);\n }\n return block;\n }\n\n if (patternPath.endsWith(\"/*\")) {\n const prefix = patternPath.slice(0, -1); // remove trailing *\n if (path.startsWith(prefix)) {\n const specificity = prefix.length;\n if (specificity > bestSpecificity) {\n bestSpecificity = specificity;\n bestMatch = block;\n }\n }\n }\n }\n\n if (debug) {\n if (bestMatch) {\n console.debug(`Wildcard match found: ${bestMatch.urlPattern} (specificity=${bestSpecificity})`);\n } else {\n console.debug(`No matching content block found for ${resourceUrl}`);\n }\n }\n\n return bestMatch;\n}\n\nexport { parseContentElements, findBestMatchingContent };\nexport type { ContentBlock };\n\nexport async function obtainLicenseToken({\n clientId,\n clientSecret,\n resourceUrl,\n debug,\n}: ObtainLicenseTokenParams): Promise<string> {\n const xml = await fetchLicenseXml(resourceUrl, debug);\n if (debug) {\n console.debug(`Fetched license.xml (${xml.length} chars)`);\n }\n const contentBlocks = parseContentElements(xml, debug);\n\n if (contentBlocks.length === 0) {\n if (debug) {\n console.error(\"No valid <content> elements with <license> found in license.xml\");\n }\n throw new Error(\n \"No valid <content> elements with <license> found in license.xml\"\n );\n }\n\n const matchedContent = findBestMatchingContent(contentBlocks, resourceUrl, debug);\n if (!matchedContent) {\n if (debug) {\n const patterns = contentBlocks.map(b => b.urlPattern).join(\", \");\n console.error(`No <content> element matches resource URL: ${resourceUrl}. Available patterns: ${patterns}`);\n }\n throw new Error(\n `No <content> element in license.xml matches resource URL: ${resourceUrl}`\n );\n }\n\n if (debug) {\n console.debug(\"Matched content block for resource URL:\", resourceUrl);\n console.debug(\"Using license XML:\", matchedContent.licenseXml);\n }\n\n const tokenEndpoint = matchedContent.server + '/token';\n if (debug) {\n console.debug(`Requesting license token from ${tokenEndpoint}`);\n }\n\n const payload = new URLSearchParams({\n grant_type: \"client_credentials\",\n license: matchedContent.licenseXml,\n resource: matchedContent.urlPattern,\n });\n\n const requestOptions: RequestInit = {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/x-www-form-urlencoded\",\n Accept: \"application/json\",\n Authorization: \"Basic \" + btoa(`${clientId}:${clientSecret}`),\n },\n body: payload.toString(),\n };\n\n return retrieveLicenseToken(tokenEndpoint, requestOptions, debug);\n}\n\nexport type { ObtainLicenseTokenParams };\n","import { FASTLY_BACKEND, FetchOptions } from \"./types\";\n\nconst jwksCache = new Map<string, any>();\n\ntype JwksCacheKey = string;\n\ntype FetchJwksParams = {\n cacheKey: JwksCacheKey;\n url: string;\n debug: boolean;\n failureMessage: string;\n logLabel: string;\n};\n\nfunction buildFetchOptions(): FetchOptions {\n let options: FetchOptions = { method: \"GET\" };\n // @ts-ignore - backend is a Fastly-specific extension\n if (globalThis?.fastly) {\n options = { ...options, backend: FASTLY_BACKEND };\n }\n return options;\n}\n\nasync function fetchAndCacheJwks({\n cacheKey,\n url,\n debug,\n failureMessage,\n logLabel,\n}: FetchJwksParams): Promise<any> {\n if (!jwksCache.has(cacheKey)) {\n try {\n const response = await fetch(url, buildFetchOptions());\n\n if (!response.ok) {\n throw new Error(`${failureMessage}: ${response.status}`);\n }\n\n const jwksData = await response.json();\n jwksCache.set(cacheKey, jwksData);\n } catch (error) {\n if (debug) {\n console.error(logLabel, error);\n }\n throw error;\n }\n }\n\n return jwksCache.get(cacheKey);\n}\n\nexport async function fetchPlatformJwks(\n baseUrl: string,\n debug: boolean\n): Promise<any> {\n const jwksUrl = `${baseUrl}/.well-known/jwks.json/platform`;\n if (debug) {\n console.debug(`Fetching platform JWKS from URL: ${jwksUrl}`);\n }\n\n return fetchAndCacheJwks({\n cacheKey: \"platform_jwks\",\n url: jwksUrl,\n debug,\n failureMessage: \"Failed to fetch platform JWKS\",\n logLabel: \"Error fetching platform JWKS:\",\n });\n}\n\nexport function clearJwksCache(): void {\n jwksCache.clear();\n}\n","import { EventPayload, FASTLY_BACKEND } from \"./types\";\n\nexport async function recordEvent({\n apiKey,\n merchantSystemUrn,\n baseUrl,\n eventName,\n properties,\n licenseId,\n debug = false,\n}: {\n apiKey: string;\n merchantSystemUrn: string;\n baseUrl: string;\n eventName: string;\n properties: Record<string, any>;\n licenseId?: string;\n debug?: boolean;\n}): Promise<void> {\n const payload: EventPayload = {\n event_name: eventName,\n merchant_system_urn: merchantSystemUrn,\n license_id: licenseId,\n properties,\n };\n\n try {\n let options: any = {\n method: \"POST\",\n headers: {\n Authorization: `Bearer ${apiKey}`,\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(payload),\n };\n // @ts-ignore\n if (globalThis?.fastly) {\n options = { ...options, backend: FASTLY_BACKEND };\n }\n const response = await fetch(`${baseUrl}/events`, options);\n\n if (!response.ok && debug) {\n console.error(`Failed to record event: ${response.status}`);\n }\n } catch (error) {\n if (debug) {\n console.error(\"Error recording event:\", error);\n }\n }\n}\n","import type { JWTPayload, JWTHeaderParameters } from \"jose\";\nimport { loadJose } from \"./jose\";\n\ninterface LicenseJWTPayload extends JWTPayload {\n license_id?: string;\n}\nimport {\n ExecutionContext,\n HandlerAction,\n HandlerResult,\n LicenseTokenInvalidReason,\n LicenseTokenVerificationResult,\n FASTLY_BACKEND,\n FetchOptions,\n} from \"./types\";\nimport { fetchPlatformJwks } from \"./jwks\";\nimport { recordEvent } from \"./events\";\n\nconst stripTrailingSlash = (value: string) => value.trim().replace(/\\/+$/, \"\");\n\nfunction reasonToErrorDescription(reason: LicenseTokenInvalidReason): string {\n switch (reason) {\n case LicenseTokenInvalidReason.MISSING_TOKEN:\n return \"Authorization header missing or malformed\";\n case LicenseTokenInvalidReason.INVALID_ALG:\n return \"Unsupported token algorithm\";\n case LicenseTokenInvalidReason.EXPIRED:\n return \"The license token has expired\";\n case LicenseTokenInvalidReason.SIGNATURE_VERIFICATION_FAILED:\n return \"The license token signature is invalid\";\n case LicenseTokenInvalidReason.INVALID_HEADER:\n return \"The license token header is malformed\";\n case LicenseTokenInvalidReason.INVALID_PAYLOAD:\n return \"The license token payload is malformed\";\n case LicenseTokenInvalidReason.INVALID_ISSUER:\n return \"The license token issuer is not recognized\";\n case LicenseTokenInvalidReason.INVALID_AUDIENCE:\n return \"The license does not grant access to this resource\";\n case LicenseTokenInvalidReason.SERVER_ERROR:\n return \"The server encountered an error validating the license\";\n default:\n return \"License token missing, expired, revoked, or malformed\";\n }\n}\n\nexport type VerifyLicenseTokenParams = {\n licenseToken: string;\n requestUrl: string;\n supertabBaseUrl: string;\n debug: boolean;\n};\n\nexport async function verifyLicenseToken({\n licenseToken,\n requestUrl,\n supertabBaseUrl,\n debug,\n}: VerifyLicenseTokenParams): Promise<LicenseTokenVerificationResult> {\n const { decodeProtectedHeader, decodeJwt, jwtVerify } = await loadJose();\n\n if (!licenseToken) {\n return {\n valid: false,\n reason: LicenseTokenInvalidReason.MISSING_TOKEN,\n error: reasonToErrorDescription(LicenseTokenInvalidReason.MISSING_TOKEN),\n };\n }\n\n let header: JWTHeaderParameters;\n try {\n header = decodeProtectedHeader(licenseToken) as JWTHeaderParameters;\n } catch (error) {\n if (debug) {\n console.error(\"Invalid license JWT header:\", error);\n }\n return {\n valid: false,\n reason: LicenseTokenInvalidReason.INVALID_HEADER,\n error: reasonToErrorDescription(LicenseTokenInvalidReason.INVALID_HEADER),\n };\n }\n\n if (header.alg !== \"ES256\") {\n if (debug) {\n console.error(\"Unsupported license JWT alg:\", header.alg);\n }\n return {\n valid: false,\n reason: LicenseTokenInvalidReason.INVALID_ALG,\n error: reasonToErrorDescription(LicenseTokenInvalidReason.INVALID_ALG),\n };\n }\n\n let payload: LicenseJWTPayload;\n try {\n payload = decodeJwt(licenseToken) as LicenseJWTPayload;\n } catch (error) {\n if (debug) {\n console.error(\"Invalid license JWT payload:\", error);\n }\n return {\n valid: false,\n reason: LicenseTokenInvalidReason.INVALID_PAYLOAD,\n error: reasonToErrorDescription(LicenseTokenInvalidReason.INVALID_PAYLOAD),\n };\n }\n\n const licenseId: string | undefined = payload.license_id;\n\n const issuer: string | undefined = payload.iss;\n const normalizedIssuer = issuer ? stripTrailingSlash(issuer) : undefined;\n const normalizedBaseUrl = stripTrailingSlash(supertabBaseUrl);\n\n if (!normalizedIssuer || !normalizedIssuer.startsWith(normalizedBaseUrl)) {\n if (debug) {\n console.error(\"License JWT issuer is missing or malformed:\", issuer);\n }\n return {\n valid: false,\n reason: LicenseTokenInvalidReason.INVALID_ISSUER,\n error: reasonToErrorDescription(LicenseTokenInvalidReason.INVALID_ISSUER),\n licenseId,\n };\n }\n\n const audienceValues = Array.isArray(payload.aud)\n ? payload.aud.filter((entry): entry is string => typeof entry === \"string\")\n : typeof payload.aud === \"string\"\n ? [payload.aud]\n : [];\n\n const requestUrlNormalized = stripTrailingSlash(requestUrl);\n const matchesRequestUrl = audienceValues.some((value) => {\n const normalizedAudience = stripTrailingSlash(value);\n if (!normalizedAudience) return false;\n return requestUrlNormalized.startsWith(normalizedAudience);\n });\n\n if (!matchesRequestUrl) {\n if (debug) {\n console.error(\n \"License JWT audience does not match request URL:\",\n payload.aud\n );\n }\n return {\n valid: false,\n reason: LicenseTokenInvalidReason.INVALID_AUDIENCE,\n error: reasonToErrorDescription(LicenseTokenInvalidReason.INVALID_AUDIENCE),\n licenseId,\n };\n }\n\n let jwks;\n try {\n jwks = await fetchPlatformJwks(supertabBaseUrl, debug);\n } catch (error) {\n if (debug) {\n console.error(\"Failed to fetch platform JWKS:\", error);\n }\n return {\n valid: false,\n reason: LicenseTokenInvalidReason.SERVER_ERROR,\n error: reasonToErrorDescription(LicenseTokenInvalidReason.SERVER_ERROR),\n licenseId,\n };\n }\n\n try {\n const getKey = async (jwtHeader: JWTHeaderParameters) => {\n const jwk = jwks.keys.find((key: any) => key.kid === jwtHeader.kid);\n if (!jwk) {\n throw new Error(`No matching platform key found: ${jwtHeader.kid}`);\n }\n return jwk;\n };\n\n const result = await jwtVerify(licenseToken, getKey, {\n issuer,\n algorithms: [header.alg],\n clockTolerance: \"1m\",\n });\n\n return {\n valid: true,\n licenseId,\n payload: result.payload,\n };\n } catch (error) {\n if (debug) {\n console.error(\"License JWT verification failed:\", error);\n }\n\n if (error instanceof Error && error.message?.includes(\"exp\")) {\n return {\n valid: false,\n reason: LicenseTokenInvalidReason.EXPIRED,\n error: reasonToErrorDescription(LicenseTokenInvalidReason.EXPIRED),\n licenseId,\n };\n }\n\n return {\n valid: false,\n reason: LicenseTokenInvalidReason.SIGNATURE_VERIFICATION_FAILED,\n error: reasonToErrorDescription(LicenseTokenInvalidReason.SIGNATURE_VERIFICATION_FAILED),\n licenseId,\n };\n }\n}\n\nexport function generateLicenseLink({\n requestUrl,\n}: {\n requestUrl: string;\n}): string {\n const baseURL = new URL(requestUrl);\n return `${baseURL.protocol}//${baseURL.host}/license.xml`;\n}\n\n/**\n * Build a HandlerResult that signals a missing token in soft enforcement mode.\n * Returns headers indicating a license is required without blocking the request.\n */\nexport function buildSignalResult(requestUrl: string): HandlerResult {\n const licenseLink = generateLicenseLink({ requestUrl });\n return {\n action: HandlerAction.ALLOW,\n headers: {\n Link: `<${licenseLink}>; rel=\"license\"; type=\"application/rsl+xml\"`,\n \"X-RSL-Status\": \"token_required\",\n \"X-RSL-Reason\": \"missing\",\n },\n };\n}\n\nfunction reasonToRslError(reason: LicenseTokenInvalidReason | string): { rslError: string; status: number } {\n switch (reason) {\n case LicenseTokenInvalidReason.MISSING_TOKEN:\n case LicenseTokenInvalidReason.INVALID_ALG:\n return { rslError: \"invalid_request\", status: 401 };\n case LicenseTokenInvalidReason.EXPIRED:\n case LicenseTokenInvalidReason.SIGNATURE_VERIFICATION_FAILED:\n case LicenseTokenInvalidReason.INVALID_HEADER:\n case LicenseTokenInvalidReason.INVALID_PAYLOAD:\n case LicenseTokenInvalidReason.INVALID_ISSUER:\n return { rslError: \"invalid_token\", status: 401 };\n case LicenseTokenInvalidReason.INVALID_AUDIENCE:\n return { rslError: \"insufficient_scope\", status: 403 };\n case LicenseTokenInvalidReason.SERVER_ERROR:\n return { rslError: \"server_error\", status: 503 };\n default:\n return { rslError: \"invalid_token\", status: 401 };\n }\n}\n\n/**\n * Sanitize a string for safe use in an HTTP header quoted-string (RFC 7230).\n * Strips CR/LF to prevent header injection and escapes backslashes and quotes.\n */\nfunction sanitizeHeaderValue(value: string): string {\n return value\n .replace(/[\\r\\n]/g, \"\")\n .replace(/\\\\/g, \"\\\\\\\\\")\n .replace(/\"/g, '\\\\\"');\n}\n\nexport function buildBlockResult({\n reason,\n error,\n requestUrl,\n}: {\n reason: LicenseTokenInvalidReason | string;\n error: string;\n requestUrl: string;\n}): HandlerResult {\n const { rslError, status } = reasonToRslError(reason);\n const errorDescription = sanitizeHeaderValue(error);\n const licenseLink = generateLicenseLink({ requestUrl });\n\n return {\n action: HandlerAction.BLOCK,\n status,\n body: `Access to this resource requires a valid license token. Error: ${rslError} - ${error}`,\n headers: {\n \"Content-Type\": \"text/plain; charset=UTF-8\",\n \"WWW-Authenticate\": `License error=\"${rslError}\", error_description=\"${errorDescription}\"`,\n Link: `<${licenseLink}>; rel=\"license\"; type=\"application/rsl+xml\"`,\n },\n };\n}\n\nfunction buildFetchOptions(): FetchOptions {\n let options: FetchOptions = { method: \"GET\" };\n // @ts-ignore - backend is a Fastly-specific extension\n if (globalThis?.fastly) {\n options = { ...options, backend: FASTLY_BACKEND };\n }\n return options;\n}\n\nexport async function hostRSLicenseXML(\n supertabBaseUrl: string,\n merchantSystemUrn: string\n): Promise<Response> {\n const licenseUrl = `${supertabBaseUrl}/merchants/systems/${merchantSystemUrn}/license.xml`;\n const response = await fetch(licenseUrl, buildFetchOptions());\n\n if (!response.ok) {\n return new Response(\"License not found\", { status: 404 });\n }\n\n const licenseXml = await response.text();\n\n return new Response(licenseXml, {\n status: 200,\n headers: new Headers({ \"Content-Type\": \"application/xml\" }),\n });\n}\n\nexport type VerifyAndRecordEventParams = {\n token: string;\n url: string;\n userAgent: string;\n supertabBaseUrl: string;\n debug: boolean;\n apiKey: string;\n merchantSystemUrn: string;\n ctx?: ExecutionContext;\n};\n\nexport async function verifyAndRecordEvent(\n params: VerifyAndRecordEventParams\n): Promise<LicenseTokenVerificationResult> {\n const verification = await verifyLicenseToken({\n licenseToken: params.token,\n requestUrl: params.url,\n supertabBaseUrl: params.supertabBaseUrl,\n debug: params.debug,\n });\n\n const eventPromise = recordEvent({\n apiKey: params.apiKey,\n merchantSystemUrn: params.merchantSystemUrn,\n baseUrl: params.supertabBaseUrl,\n eventName: verification.valid ? \"license_used\" : verification.reason,\n properties: {\n page_url: params.url,\n user_agent: params.userAgent,\n verification_status: verification.valid ? \"valid\" : \"invalid\",\n verification_reason: verification.valid ? \"success\" : verification.reason,\n },\n licenseId: verification.licenseId,\n debug: params.debug,\n });\n if (params.ctx?.waitUntil) {\n params.ctx.waitUntil(eventPromise);\n }\n\n return verification;\n}\n","import {\n HandlerAction,\n HandlerResult,\n ExecutionContext,\n CloudFrontHeaders,\n CloudFrontRequestEvent,\n CloudFrontRequestResult,\n} from \"./types\";\nimport { hostRSLicenseXML } from \"./license\";\n\n// Interface for what the CDN handlers need - avoids circular dependency\ninterface RequestHandler {\n handleRequest(request: Request, ctx?: ExecutionContext): Promise<HandlerResult>;\n}\n\nexport async function handleCloudflareRequest(\n handler: RequestHandler,\n request: Request,\n ctx: ExecutionContext\n): Promise<Response> {\n const result = await handler.handleRequest(request, ctx);\n\n if (result.action === HandlerAction.BLOCK) {\n return new Response(result.body, {\n status: result.status,\n headers: new Headers(result.headers),\n });\n }\n\n // action === HandlerAction.ALLOW\n const originResponse = await fetch(request);\n\n if (result.headers) {\n const response = new Response(originResponse.body, originResponse);\n for (const [key, value] of Object.entries(result.headers)) {\n response.headers.set(key, value);\n }\n return response;\n }\n\n return originResponse;\n}\n\nexport async function handleFastlyRequest(\n handler: RequestHandler,\n request: Request,\n originBackend: string,\n rslOptions?: {\n baseUrl: string;\n merchantSystemUrn: string;\n }\n): Promise<Response> {\n if (rslOptions && new URL(request.url).pathname === \"/license.xml\") {\n return await hostRSLicenseXML(\n rslOptions.baseUrl,\n rslOptions.merchantSystemUrn\n );\n }\n\n const result = await handler.handleRequest(request);\n\n if (result.action === HandlerAction.BLOCK) {\n return new Response(result.body, {\n status: result.status,\n headers: new Headers(result.headers),\n });\n }\n\n // action === HandlerAction.ALLOW\n const originResponse = await fetch(request, {\n backend: originBackend,\n } as RequestInit);\n\n if (result.headers) {\n const response = new Response(originResponse.body, originResponse);\n for (const [key, value] of Object.entries(result.headers)) {\n response.headers.set(key, value);\n }\n return response;\n }\n\n return originResponse;\n}\n\nexport async function handleCloudfrontRequest<TRequest extends Record<string, any>>(\n handler: RequestHandler,\n event: CloudFrontRequestEvent<TRequest>\n): Promise<CloudFrontRequestResult<TRequest>> {\n const cfRequest = event.Records[0].cf.request;\n\n // Convert CloudFront request to Web API Request\n const url = `https://${cfRequest.headers.host[0].value}${cfRequest.uri}${cfRequest.querystring ? \"?\" + cfRequest.querystring : \"\"}`;\n\n const headers = new Headers();\n Object.entries(cfRequest.headers).forEach(([key, values]) => {\n values.forEach(({ value }) => headers.append(key, value));\n });\n\n const webRequest = new Request(url, {\n method: cfRequest.method,\n headers: headers,\n });\n\n const result = await handler.handleRequest(webRequest);\n\n if (result.action === HandlerAction.BLOCK) {\n const responseHeaders: CloudFrontHeaders = {};\n Object.entries(result.headers).forEach(([key, value]) => {\n responseHeaders[key.toLowerCase()] = [{ key, value }];\n });\n\n return {\n status: result.status.toString(),\n statusDescription:\n result.status === 401 ? \"Unauthorized\" : \"Payment Required\",\n headers: responseHeaders,\n body: result.body,\n };\n }\n\n // Allow request to continue to origin\n return cfRequest;\n}\n","/**\n * Default bot detection logic using multiple signals.\n * Checks User-Agent patterns, headless browser indicators, missing headers, and Cloudflare bot scores.\n * @param request The incoming request to analyze\n * @returns true if the request appears to be from a bot, false otherwise\n */\nexport function defaultBotDetector(request: Request): boolean {\n const userAgent = request.headers.get(\"User-Agent\") || \"\";\n const accept = request.headers.get(\"accept\") || \"\";\n const secChUa = request.headers.get(\"sec-ch-ua\");\n const acceptLanguage = request.headers.get(\"accept-language\");\n const botScore = (request as any).cf?.botManagement?.score;\n\n const botList = [\n \"chatgpt-user\",\n \"perplexitybot\",\n \"gptbot\",\n \"anthropic-ai\",\n \"ccbot\",\n \"claude-web\",\n \"claudebot\",\n \"cohere-ai\",\n \"youbot\",\n \"diffbot\",\n \"oai-searchbot\",\n \"meta-externalagent\",\n \"timpibot\",\n \"amazonbot\",\n \"bytespider\",\n \"perplexity-user\",\n \"googlebot\",\n \"bot\",\n \"curl\",\n \"wget\",\n ];\n // 1. Basic substring check from known list\n const lowerCaseUserAgent = userAgent.toLowerCase();\n const botUaMatch = botList.some((bot) => lowerCaseUserAgent.includes(bot));\n\n // 2. Headless browser detection\n const headlessIndicators =\n lowerCaseUserAgent.includes(\"headless\") ||\n lowerCaseUserAgent.includes(\"puppeteer\") ||\n !secChUa;\n\n const isBrowserMissingSecChUa =\n !lowerCaseUserAgent.includes(\"headless\") &&\n !lowerCaseUserAgent.includes(\"puppeteer\") &&\n !secChUa;\n\n // 3. Suspicious header gaps — many bots omit these\n const missingHeaders = !accept || !acceptLanguage;\n\n // 4. Cloudflare bot score check (if available)\n const lowBotScore = typeof botScore === \"number\" && botScore < 30;\n\n // Safari and Mozilla special case\n if (\n lowerCaseUserAgent.includes(\"safari\") ||\n lowerCaseUserAgent.includes(\"mozilla\")\n ) {\n // Safari is not a bot, but it may be headless\n if (headlessIndicators && isBrowserMissingSecChUa) {\n return false; // Likely not a bot, but missing a Sec-CH-UA header\n }\n }\n\n // Final decision\n return botUaMatch || headlessIndicators || missingHeaders || lowBotScore;\n}\n"],"mappings":"0jBAAA,IAAAA,GAAA,GAAAC,EAAAD,GAAA,qBAAAE,EAAA,kBAAAC,EAAA,oBAAAC,EAAA,uBAAAC,IAAA,eAAAC,EAAAN,ICAO,IAAKO,OACVA,EAAA,SAAW,WACXA,EAAA,KAAO,OACPA,EAAA,OAAS,SAHCA,OAAA,IAuDL,IAAMC,EAAiB,cAOlBC,OACVA,EAAA,MAAQ,QACRA,EAAA,MAAQ,QAFEA,OAAA,IC5DZ,IAAIC,EAAgD,KAK7C,SAASC,GAAgC,CAC9C,OAAKD,IACHA,EAAoB,OAAO,MAAM,GAE5BA,CACT,CCeA,eAAeE,GACXC,EACAC,EACAC,EACF,CACA,GAAI,CACF,IAAMC,EAAW,MAAM,MAAMH,EAAeC,CAAc,EAE1D,GAAI,CAACE,EAAS,GAAI,CAChB,IAAMC,EAAY,MAAMD,EAAS,KAAK,EAAE,MAAM,IAAM,EAAE,EAChDE,EAAe,mCACnBF,EAAS,MACX,IAAIA,EAAS,UAAU,GAAGC,EAAY,MAAMA,CAAS,GAAK,EAAE,GAC5D,MAAM,IAAI,MAAMC,CAAY,CAC9B,CAEA,IAAIC,EACJ,GAAI,CACFA,EAAO,MAAMH,EAAS,KAAK,CAC7B,OAASI,EAAY,CACnB,MAAIL,GACF,QAAQ,MACN,kDACAK,CACF,EAEI,IAAI,MAAM,gDAAgD,CAClE,CAEA,GAAI,CAACD,GAAM,aACT,MAAM,IAAI,MAAM,6CAA6C,EAG/D,OAAOA,EAAK,YACd,OAASE,EAAO,CACd,MAAIN,GACF,QAAQ,MAAM,kCAAmCM,CAAK,EAElDA,CAC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YA,aAAa,qBACXD,EACAY,EACAC,EACAC,EACAnB,EAKmB,CACnB,GAAM,CAAE,UAAAoB,EAAY,GAAO,YAAAC,EAAa,YAAAC,CAAY,EAAItB,GAAW,CAAC,EAE9De,EAAW,IAAInB,EAAgB,CACnC,OAAQsB,EACR,kBAAmBD,EACnB,YAAAI,EACA,YAAAC,CACF,CAAC,EAED,OAAOC,EACLR,EACAV,EACAc,EACAC,EACI,CACE,QAASxB,EAAgB,QACzB,kBAAAqB,CACF,EACA,MACN,CACF,CAQA,aAAa,yBACXO,EACAxB,EAC4C,CAC5C,IAAMe,EAAW,IAAInB,EAAgB,CACnC,OAAQI,EAAQ,OAChB,kBAAmBA,EAAQ,kBAC3B,YAAaA,EAAQ,YACrB,YAAaA,EAAQ,WACvB,CAAC,EACD,OAAOyB,EAAwBV,EAAUS,CAAK,CAChD,CACF,EAhTa5B,EAEI,QAAkB,kCAFtBA,EAQI,UAAoC,KAR9C,IAAM8B,EAAN9B","names":["index_exports","__export","EnforcementMode","HandlerAction","SupertabConnect","defaultBotDetector","__toCommonJS","EnforcementMode","FASTLY_BACKEND","HandlerAction","joseModulePromise","loadJose","retrieveLicenseToken","tokenEndpoint","requestOptions","debug","response","errorBody","errorMessage","data","parseError","error","fetchLicenseXml","resourceUrl","debug","licenseXmlUrl","response","xml","parseContentElements","contentBlocks","contentRegex","urlRegex","serverRegex","licenseRegex","elementCount","match","attrs","body","urlMatch","serverMatch","licenseMatch","missing","findBestMatchingContent","parsed","host","path","bestMatch","bestSpecificity","block","patternUrl","patternPath","prefix","specificity","obtainLicenseToken","clientId","clientSecret","resourceUrl","debug","xml","fetchLicenseXml","contentBlocks","parseContentElements","matchedContent","findBestMatchingContent","patterns","b","tokenEndpoint","payload","requestOptions","retrieveLicenseToken","jwksCache","buildFetchOptions","options","FASTLY_BACKEND","fetchAndCacheJwks","cacheKey","url","debug","failureMessage","logLabel","response","jwksData","error","fetchPlatformJwks","baseUrl","jwksUrl","recordEvent","apiKey","merchantSystemUrn","baseUrl","eventName","properties","licenseId","debug","payload","options","FASTLY_BACKEND","response","error","stripTrailingSlash","value","reasonToErrorDescription","reason","verifyLicenseToken","licenseToken","requestUrl","supertabBaseUrl","debug","decodeProtectedHeader","decodeJwt","jwtVerify","loadJose","header","error","payload","licenseId","issuer","normalizedIssuer","normalizedBaseUrl","audienceValues","entry","requestUrlNormalized","normalizedAudience","jwks","fetchPlatformJwks","result","jwtHeader","jwk","key","generateLicenseLink","baseURL","buildSignalResult","licenseLink","reasonToRslError","sanitizeHeaderValue","buildBlockResult","rslError","status","errorDescription","buildFetchOptions","options","FASTLY_BACKEND","hostRSLicenseXML","merchantSystemUrn","licenseUrl","response","licenseXml","verifyAndRecordEvent","params","verification","eventPromise","recordEvent","handleCloudflareRequest","handler","request","ctx","result","originResponse","response","key","value","handleFastlyRequest","originBackend","rslOptions","hostRSLicenseXML","handleCloudfrontRequest","event","cfRequest","url","headers","values","webRequest","responseHeaders","defaultBotDetector","request","userAgent","accept","secChUa","acceptLanguage","botScore","botList","lowerCaseUserAgent","botUaMatch","bot","headlessIndicators","isBrowserMissingSecChUa","missingHeaders","lowBotScore","_SupertabConnect","config","reset","url","options","baseUrl","result","verifyLicenseToken","verifyAndRecordEvent","request","ctx","auth","token","userAgent","verification","buildBlockResult","buildSignalResult","obtainLicenseToken","env","instance","handleCloudflareRequest","merchantSystemUrn","merchantApiKey","originBackend","enableRSL","botDetector","enforcement","handleFastlyRequest","event","handleCloudfrontRequest","SupertabConnect"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/types.ts","../src/jose.ts","../src/customer.ts","../src/jwks.ts","../src/events.ts","../src/license.ts","../src/cdn.ts","../src/bots.ts"],"sourcesContent":["import {\n SupertabConnectConfig,\n EnforcementMode,\n BotDetector,\n HandlerAction,\n HandlerResult,\n LicenseTokenInvalidReason,\n RSLVerificationResult,\n ExecutionContext,\n Env,\n} from \"./types\";\nimport { obtainLicenseToken as obtainLicenseTokenHelper } from \"./customer\";\nimport {\n buildBlockResult,\n buildSignalResult,\n verifyLicenseToken as verifyLicenseTokenHelper,\n verifyAndRecordEvent,\n} from \"./license\";\nimport {\n handleCloudflareRequest,\n handleFastlyRequest,\n handleCloudfrontRequest,\n} from \"./cdn\";\nimport {\n CloudFrontRequestEvent,\n CloudFrontRequestResult,\n CloudfrontHandlerOptions,\n} from \"./types\";\n\nexport { EnforcementMode, HandlerAction };\nexport type {\n RSLVerificationResult,\n ExecutionContext,\n Env,\n BotDetector,\n HandlerResult,\n CloudFrontRequestEvent,\n CloudFrontRequestResult,\n CloudfrontHandlerOptions,\n};\nexport { defaultBotDetector } from \"./bots\";\n\n/**\n * SupertabConnect class provides higher level methods\n * for using Supertab Connect within supported CDN integrations\n * as well as more specialized methods to customarily verify JWT tokens and record events.\n */\nexport class SupertabConnect {\n private apiKey?: string;\n private static baseUrl: string = \"https://api-connect.supertab.co\";\n private merchantSystemUrn!: string;\n private enforcement!: EnforcementMode;\n private botDetector?: BotDetector;\n private debug!: boolean;\n\n private static _instance: SupertabConnect | null = null;\n\n /**\n * Create a new SupertabConnect instance (singleton).\n * Returns the existing instance if one exists with the same config.\n * @param config SDK configuration including apiKey and merchantSystemUrn\n * @param reset Pass true to replace an existing instance with different config\n * @throws If an instance with different config already exists and reset is false\n */\n public constructor(config: SupertabConnectConfig, reset: boolean = false) {\n if (!reset && SupertabConnect._instance) {\n // If reset was not requested and an instance conflicts with the provided config, throw an error\n if (\n !(\n config.apiKey === SupertabConnect._instance.apiKey &&\n config.merchantSystemUrn ===\n SupertabConnect._instance.merchantSystemUrn\n )\n ) {\n throw new Error(\n \"Cannot create a new instance with different configuration. Use resetInstance to clear the existing instance.\"\n );\n }\n\n // If an instance already exists and reset is not requested, just return the existing instance\n return SupertabConnect._instance;\n }\n if (reset && SupertabConnect._instance) {\n // ...and if reset is requested and required, clear the existing instance first\n SupertabConnect.resetInstance();\n }\n\n if (!config.apiKey || !config.merchantSystemUrn) {\n throw new Error(\n \"Missing required configuration: apiKey and merchantSystemUrn are required\"\n );\n }\n this.apiKey = config.apiKey;\n this.merchantSystemUrn = config.merchantSystemUrn;\n this.enforcement = config.enforcement ?? EnforcementMode.SOFT;\n this.botDetector = config.botDetector;\n this.debug = config.debug ?? false;\n\n // Register this as the singleton instance\n SupertabConnect._instance = this;\n }\n\n /**\n * Clear the singleton instance, allowing a new one to be created with different config.\n */\n public static resetInstance(): void {\n SupertabConnect._instance = null;\n }\n\n /**\n * Override the default base URL for API requests (intended for local development/testing).\n */\n public static setBaseUrl(url: string): void {\n SupertabConnect.baseUrl = url;\n }\n\n /**\n * Get the current base URL for API requests.\n */\n public static getBaseUrl(): string {\n return SupertabConnect.baseUrl;\n }\n\n /**\n * Pure token verification — verifies a license token without recording any events.\n * @param options.token The license token to verify\n * @param options.resourceUrl The URL of the resource being accessed\n * @param options.baseUrl Optional override for the Supertab Connect API base URL\n * @param options.debug Enable debug logging (default: false)\n * @returns A promise that resolves with the verification result\n */\n static async verify(options: {\n token: string;\n resourceUrl: string;\n baseUrl?: string;\n debug?: boolean;\n }): Promise<RSLVerificationResult> {\n const baseUrl = options.baseUrl ?? SupertabConnect.baseUrl;\n\n const result = await verifyLicenseTokenHelper({\n licenseToken: options.token,\n requestUrl: options.resourceUrl,\n supertabBaseUrl: baseUrl,\n debug: options.debug ?? false,\n });\n\n if (result.valid) {\n return { valid: true };\n }\n\n return { valid: false, error: result.error };\n }\n\n /**\n * Verify a license token and record an analytics event.\n * Uses the instance's apiKey and merchantSystemUrn for event recording.\n * @param options.token The license token to verify\n * @param options.resourceUrl The URL of the resource being accessed\n * @param options.userAgent Optional user agent string for event recording\n * @param options.debug Enable debug logging (default: false)\n * @param options.ctx Optional execution context with waitUntil for non-blocking event recording\n * @returns A promise that resolves with the verification result\n */\n async verifyAndRecord(options: {\n token: string;\n resourceUrl: string;\n userAgent?: string;\n debug?: boolean;\n ctx?: ExecutionContext;\n }): Promise<RSLVerificationResult> {\n const result = await verifyAndRecordEvent({\n token: options.token,\n url: options.resourceUrl,\n userAgent: options.userAgent ?? \"unknown\",\n supertabBaseUrl: SupertabConnect.baseUrl,\n debug: options.debug ?? this.debug,\n apiKey: this.apiKey!,\n merchantSystemUrn: this.merchantSystemUrn,\n ctx: options.ctx,\n });\n\n if (result.valid) {\n return { valid: true };\n }\n\n return { valid: false, error: result.error };\n }\n\n /**\n * Handle an incoming request by extracting the license token, verifying it, and recording an analytics event.\n * When no token is present, bot detection and enforcement mode determine the response.\n * @param request The incoming HTTP request\n * @param ctx Execution context for non-blocking event recording.\n * Pass this from your platform (e.g. Cloudflare Workers)\n * @returns A promise that resolves with the handler result indicating ALLOW or BLOCK request\n */\n async handleRequest(request: Request, ctx?: ExecutionContext): Promise<HandlerResult> {\n const auth = request.headers.get(\"Authorization\") || \"\";\n const token = auth.startsWith(\"License \") ? auth.slice(8) : null;\n const url = request.url;\n const userAgent = request.headers.get(\"User-Agent\") || \"unknown\";\n\n // Token present → ALWAYS validate, regardless of mode or bot detection\n if (token) {\n if (this.enforcement === EnforcementMode.DISABLED) {\n return { action: HandlerAction.ALLOW };\n }\n const verification = await verifyAndRecordEvent({\n token,\n url,\n userAgent,\n supertabBaseUrl: SupertabConnect.baseUrl,\n debug: this.debug,\n apiKey: this.apiKey!,\n merchantSystemUrn: this.merchantSystemUrn,\n ctx,\n });\n if (!verification.valid) {\n return buildBlockResult({\n reason: verification.reason,\n error: verification.error,\n requestUrl: url,\n });\n }\n return { action: HandlerAction.ALLOW };\n }\n\n // No token from here on\n const isBot = this.botDetector?.(request, ctx) ?? false;\n\n if (!isBot) {\n return { action: HandlerAction.ALLOW };\n }\n\n // Bot detected, no token — enforcement mode decides\n switch (this.enforcement) {\n case EnforcementMode.STRICT:\n return buildBlockResult({\n reason: LicenseTokenInvalidReason.MISSING_TOKEN,\n error: \"Authorization header missing or malformed\",\n requestUrl: url,\n });\n case EnforcementMode.SOFT:\n return buildSignalResult(url);\n default: // DISABLED\n return { action: HandlerAction.ALLOW };\n }\n }\n\n /**\n * Request a license token from the Supertab Connect token endpoint.\n * @param options.clientId OAuth client identifier.\n * @param options.clientSecret OAuth client secret for client_credentials flow.\n * @param options.resourceUrl Resource URL attempting to access with a License.\n * @param options.debug Enable debug logging (default: false).\n * @returns Promise resolving to the issued license access token string.\n */\n static async obtainLicenseToken(options: {\n clientId: string;\n clientSecret: string;\n resourceUrl: string;\n debug?: boolean;\n }): Promise<string> {\n return obtainLicenseTokenHelper({\n clientId: options.clientId,\n clientSecret: options.clientSecret,\n resourceUrl: options.resourceUrl,\n debug: options.debug,\n });\n }\n\n /**\n * Handle incoming requests for Cloudflare Workers.\n * Pass this directly as your Worker's fetch handler.\n * @param request The incoming Worker request\n * @param env Worker environment bindings containing MERCHANT_API_KEY and MERCHANT_SYSTEM_URN\n * @param ctx Worker execution context for non-blocking event recording\n * @param options Optional configuration items\n * @param options.botDetector Custom bot detection function\n * @param options.enforcement Enforcement mode (default: SOFT)\n */\n static async cloudflareHandleRequests(\n request: Request,\n env: Env,\n ctx: ExecutionContext,\n options?: {\n botDetector?: BotDetector;\n enforcement?: EnforcementMode;\n }\n ): Promise<Response> {\n const instance = new SupertabConnect({\n apiKey: env.MERCHANT_API_KEY,\n merchantSystemUrn: env.MERCHANT_SYSTEM_URN,\n botDetector: options?.botDetector,\n enforcement: options?.enforcement,\n });\n return handleCloudflareRequest(instance, request, ctx);\n }\n\n /**\n * Handle incoming requests for Fastly Compute.\n * @param request The incoming Fastly request\n * @param merchantSystemUrn The merchant system URN for identification\n * @param merchantApiKey The merchant API key for authentication\n * @param originBackend The Fastly backend name to forward allowed requests to\n * @param options Optional configuration items\n * @param options.enableRSL Serve license.xml at /license.xml for RSL-compliant clients (default: false)\n * @param options.botDetector Custom bot detection function\n * @param options.enforcement Enforcement mode (default: SOFT)\n */\n static async fastlyHandleRequests(\n request: Request,\n merchantSystemUrn: string,\n merchantApiKey: string,\n originBackend: string,\n options?: {\n enableRSL?: boolean;\n botDetector?: BotDetector;\n enforcement?: EnforcementMode;\n }\n ): Promise<Response> {\n const { enableRSL = false, botDetector, enforcement } = options ?? {};\n\n const instance = new SupertabConnect({\n apiKey: merchantApiKey,\n merchantSystemUrn: merchantSystemUrn,\n botDetector,\n enforcement,\n });\n\n return handleFastlyRequest(\n instance,\n request,\n originBackend,\n enableRSL\n ? {\n baseUrl: SupertabConnect.baseUrl,\n merchantSystemUrn,\n }\n : undefined\n );\n }\n\n /**\n * Handle incoming requests for AWS CloudFront Lambda@Edge.\n * Use as the handler for a viewer-request LambdaEdge function.\n * @param event The CloudFront viewer-request event\n * @param options Configuration including apiKey, merchantSystemUrn, and optional botDetector/enforcement\n */\n static async cloudfrontHandleRequests<TRequest extends Record<string, any>>(\n event: CloudFrontRequestEvent<TRequest>,\n options: CloudfrontHandlerOptions\n ): Promise<CloudFrontRequestResult<TRequest>> {\n const instance = new SupertabConnect({\n apiKey: options.apiKey,\n merchantSystemUrn: options.merchantSystemUrn,\n botDetector: options.botDetector,\n enforcement: options.enforcement,\n });\n return handleCloudfrontRequest(instance, event);\n }\n}\n","export enum EnforcementMode {\n DISABLED = \"disabled\",\n SOFT = \"soft\",\n STRICT = \"strict\",\n}\n\nexport interface ExecutionContext {\n waitUntil(promise: Promise<any>): void;\n}\n\nexport type BotDetector = (request: Request, ctx?: ExecutionContext) => boolean;\n\nexport interface SupertabConnectConfig {\n apiKey: string;\n merchantSystemUrn: string;\n enforcement?: EnforcementMode;\n botDetector?: BotDetector;\n debug?: boolean;\n}\n\n/**\n * Defines the shape for environment variables (used in CloudFlare integration).\n * These are used to identify and authenticate the Merchant System with the Supertab Connect API.\n */\nexport interface Env {\n\t/** The unique identifier for the merchant system. */\n\tMERCHANT_SYSTEM_URN: string;\n\t/** The API key for authenticating with the Supertab Connect. */\n\tMERCHANT_API_KEY: string;\n\t[key: string]: string;\n}\n\nexport interface EventPayload {\n event_name: string;\n license_id?: string;\n merchant_system_urn: string;\n properties: Record<string, any>;\n}\n\nexport type LicenseTokenVerificationResult =\n | { valid: true; licenseId?: string; payload: any }\n | { valid: false; reason: LicenseTokenInvalidReason; error: string; licenseId?: string };\n\nexport enum LicenseTokenInvalidReason {\n MISSING_TOKEN = \"missing_license_token\",\n INVALID_HEADER = \"invalid_license_header\",\n INVALID_ALG = \"invalid_license_algorithm\",\n INVALID_PAYLOAD = \"invalid_license_payload\",\n INVALID_ISSUER = \"invalid_license_issuer\",\n SIGNATURE_VERIFICATION_FAILED = \"license_signature_verification_failed\",\n EXPIRED = \"license_token_expired\",\n INVALID_AUDIENCE = \"invalid_license_audience\",\n SERVER_ERROR = \"server_error\",\n}\n\nexport const FASTLY_BACKEND = \"stc-backend\";\n\nexport interface FetchOptions extends RequestInit {\n // Fastly-specific extension for backend routing\n backend?: string;\n}\n\nexport enum HandlerAction {\n ALLOW = \"allow\",\n BLOCK = \"block\",\n}\n\nexport type HandlerResult =\n | { action: HandlerAction.ALLOW; headers?: Record<string, string> }\n | { action: HandlerAction.BLOCK; status: number; body: string; headers: Record<string, string> };\n\n// CloudFront Lambda@Edge types\n// Uses permissive types to be compatible with aws-lambda package types\nexport interface CloudFrontHeaders {\n [key: string]: Array<{ key?: string; value: string }>;\n}\n\nexport interface CloudFrontResultResponse {\n status: string;\n statusDescription?: string;\n headers?: CloudFrontHeaders;\n bodyEncoding?: \"text\" | \"base64\";\n body?: string;\n}\n\n// CloudFrontRequestEvent uses a generic request type to accept aws-lambda's CloudFrontRequest\nexport interface CloudFrontRequestEvent<TRequest = Record<string, any>> {\n Records: Array<{\n cf: {\n config?: {\n distributionDomainName?: string;\n distributionId?: string;\n eventType?: string;\n requestId?: string;\n };\n request: TRequest & {\n uri: string;\n method: string;\n querystring: string;\n headers: CloudFrontHeaders;\n };\n };\n }>;\n}\n\n// Result can be either the original request (pass-through) or a response\n// Using generic to preserve the original request type for pass-through\nexport type CloudFrontRequestResult<TRequest = Record<string, any>> = TRequest | CloudFrontResultResponse;\n\nexport interface CloudfrontHandlerOptions {\n apiKey: string;\n merchantSystemUrn: string;\n botDetector?: BotDetector;\n enforcement?: EnforcementMode;\n}\n\nexport type RSLVerificationResult = {\n valid: boolean;\n error?: string;\n};\n","// Per-subpath lazy loaders for jose — each caches its own promise to avoid redundant imports.\n\nfunction lazyImport<T>(load: () => Promise<T>): () => Promise<T> {\n let cached: Promise<T> | null = null;\n return () => {\n if (!cached) {\n cached = load();\n }\n return cached;\n };\n}\n\nexport const loadJwtVerify = lazyImport(() => import(\"jose/jwt/verify\"));\nexport const loadDecodeJwt = lazyImport(() => import(\"jose/jwt/decode\"));\nexport const loadDecodeProtectedHeader = lazyImport(() => import(\"jose/decode/protected_header\"));\nexport const loadKeyImport = lazyImport(() => import(\"jose/key/import\"));\nexport const loadJwtSign = lazyImport(() => import(\"jose/jwt/sign\"));\n","import { loadKeyImport, loadJwtSign } from \"./jose\";\n\ntype SupportedAlg = \"RS256\" | \"ES256\";\n\ntype GenerateLicenseTokenParams = {\n clientId: string;\n kid: string;\n privateKeyPem: string;\n tokenEndpoint: string;\n resourceUrl: string;\n licenseXml: string;\n debug?: boolean;\n};\n\ntype ObtainLicenseTokenParams = {\n clientId: string;\n clientSecret: string;\n resourceUrl: string;\n debug?: boolean;\n};\n\ntype ContentBlock = {\n urlPattern: string;\n licenseXml: string;\n server: string;\n};\n\nasync function retrieveLicenseToken(\n tokenEndpoint: string,\n requestOptions: RequestInit,\n debug: boolean | undefined\n) {\n try {\n const response = await fetch(tokenEndpoint, requestOptions);\n\n if (!response.ok) {\n const errorBody = await response.text().catch(() => \"\");\n const errorMessage = `Failed to obtain license token: ${\n response.status\n } ${response.statusText}${errorBody ? ` - ${errorBody}` : \"\"}`;\n throw new Error(errorMessage);\n }\n\n let data: any;\n try {\n data = await response.json();\n } catch (parseError) {\n if (debug) {\n console.error(\n \"Failed to parse license token response as JSON:\",\n parseError\n );\n }\n throw new Error(\"Failed to parse license token response as JSON\");\n }\n\n if (!data?.access_token) {\n throw new Error(\"License token response missing access_token\");\n }\n\n return data.access_token;\n } catch (error) {\n if (debug) {\n console.error(\"Error generating license token:\", error);\n }\n throw error;\n }\n}\n\nasync function importKeyForAlgs(\n privateKeyPem: string,\n debug: boolean | undefined\n): Promise<{ key: CryptoKey; alg: SupportedAlg }> {\n const { importPKCS8 } = await loadKeyImport();\n const supportedAlgs: SupportedAlg[] = [\"ES256\", \"RS256\"];\n\n for (const algorithm of supportedAlgs) {\n try {\n const key = await importPKCS8(privateKeyPem, algorithm);\n return { key, alg: algorithm };\n } catch (importError) {\n if (debug) {\n console.debug(\n `Private key did not import using ${algorithm}, retrying...`,\n importError\n );\n }\n }\n }\n\n throw new Error(\n \"Unsupported private key format. Expected RSA or P-256 EC private key.\"\n );\n}\n\n// Temporarily not exporting this function to reflect only client credentials flow being supported\nasync function generateLicenseToken({\n clientId,\n kid,\n privateKeyPem,\n tokenEndpoint,\n resourceUrl,\n licenseXml,\n debug,\n}: GenerateLicenseTokenParams): Promise<string> {\n const { SignJWT } = await loadJwtSign();\n const { key, alg } = await importKeyForAlgs(privateKeyPem, debug);\n const now = Math.floor(Date.now() / 1000);\n\n const clientAssertion = await new SignJWT({})\n .setProtectedHeader({ alg, kid })\n .setIssuer(clientId)\n .setSubject(clientId)\n .setIssuedAt(now)\n .setExpirationTime(now + 300)\n .setAudience(tokenEndpoint)\n .sign(key);\n\n const payload = new URLSearchParams({\n grant_type: \"rsl\",\n client_assertion_type:\n \"urn:ietf:params:oauth:client-assertion-type:jwt-bearer\",\n client_assertion: clientAssertion,\n license: licenseXml,\n resource: resourceUrl,\n });\n\n const requestOptions: RequestInit = {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/x-www-form-urlencoded\",\n Accept: \"application/json\",\n },\n body: payload.toString(),\n };\n\n return retrieveLicenseToken(tokenEndpoint, requestOptions, debug);\n}\n\nasync function fetchLicenseXml(\n resourceUrl: string,\n debug: boolean | undefined\n): Promise<string> {\n const origin = new URL(resourceUrl).origin;\n const licenseXmlUrl = `${origin}/license.xml`;\n\n const response = await fetch(licenseXmlUrl);\n if (!response.ok) {\n if (debug) {\n console.error(`Failed to fetch license.xml from ${licenseXmlUrl}: ${response.status}`);\n }\n throw new Error(\n `Failed to fetch license.xml from ${licenseXmlUrl}: ${response.status}`\n );\n }\n\n const xml = await response.text();\n if (debug) {\n console.debug(\"Fetched license.xml from\", licenseXmlUrl);\n }\n return xml;\n}\n\nfunction parseContentElements(xml: string, debug?: boolean): ContentBlock[] {\n const contentBlocks: ContentBlock[] = [];\n const contentRegex = /<content\\s([^>]*)>([\\s\\S]*?)<\\/content>/gi;\n const urlRegex = /url\\s*=\\s*\"([^\"]*)\"/i;\n const serverRegex = /server\\s*=\\s*\"([^\"]*)\"/i;\n const licenseRegex = /<license[^>]*>[\\s\\S]*?<\\/license>/i;\n\n let elementCount = 0;\n let match;\n while ((match = contentRegex.exec(xml)) !== null) {\n elementCount++;\n const attrs = match[1];\n const body = match[2];\n const urlMatch = attrs.match(urlRegex);\n const serverMatch = attrs.match(serverRegex);\n const licenseMatch = body.match(licenseRegex);\n\n if (urlMatch && serverMatch && licenseMatch) {\n contentBlocks.push({\n urlPattern: urlMatch[1],\n server: serverMatch[1],\n licenseXml: licenseMatch[0],\n });\n } else if (debug) {\n const missing = [\n !urlMatch && \"url\",\n !serverMatch && \"server\",\n !licenseMatch && \"<license>\",\n ].filter(Boolean).join(\", \");\n console.debug(`Skipping <content> element #${elementCount}: missing ${missing}`);\n }\n }\n\n if (debug) {\n console.debug(`Found ${elementCount} <content> element(s), ${contentBlocks.length} valid`);\n }\n\n return contentBlocks;\n}\n\nfunction findBestMatchingContent(\n contentBlocks: ContentBlock[],\n resourceUrl: string,\n debug?: boolean\n): ContentBlock | null {\n const parsed = new URL(resourceUrl);\n const host = parsed.host;\n const path = parsed.pathname;\n\n if (debug) {\n console.debug(`Matching resource URL: ${resourceUrl} (host=${host}, path=${path})`);\n }\n\n let bestMatch: ContentBlock | null = null;\n let bestSpecificity = -1;\n\n for (const block of contentBlocks) {\n let patternUrl: URL;\n try {\n patternUrl = new URL(block.urlPattern);\n } catch {\n if (debug) {\n console.debug(`Skipping block with invalid URL pattern: ${block.urlPattern}`);\n }\n continue;\n }\n\n if (patternUrl.host !== host) {\n if (debug) {\n console.debug(`Skipping block: host mismatch (pattern=${patternUrl.host}, resource=${host})`);\n }\n continue;\n }\n\n const patternPath = patternUrl.pathname;\n\n if (patternPath === path) {\n if (debug) {\n console.debug(`Exact match found: ${block.urlPattern}`);\n }\n return block;\n }\n\n if (patternPath.endsWith(\"/*\")) {\n const prefix = patternPath.slice(0, -1); // remove trailing *\n if (path.startsWith(prefix)) {\n const specificity = prefix.length;\n if (specificity > bestSpecificity) {\n bestSpecificity = specificity;\n bestMatch = block;\n }\n }\n }\n }\n\n if (debug) {\n if (bestMatch) {\n console.debug(`Wildcard match found: ${bestMatch.urlPattern} (specificity=${bestSpecificity})`);\n } else {\n console.debug(`No matching content block found for ${resourceUrl}`);\n }\n }\n\n return bestMatch;\n}\n\nexport { parseContentElements, findBestMatchingContent };\nexport type { ContentBlock };\n\nexport async function obtainLicenseToken({\n clientId,\n clientSecret,\n resourceUrl,\n debug,\n}: ObtainLicenseTokenParams): Promise<string> {\n const xml = await fetchLicenseXml(resourceUrl, debug);\n if (debug) {\n console.debug(`Fetched license.xml (${xml.length} chars)`);\n }\n const contentBlocks = parseContentElements(xml, debug);\n\n if (contentBlocks.length === 0) {\n if (debug) {\n console.error(\"No valid <content> elements with <license> found in license.xml\");\n }\n throw new Error(\n \"No valid <content> elements with <license> found in license.xml\"\n );\n }\n\n const matchedContent = findBestMatchingContent(contentBlocks, resourceUrl, debug);\n if (!matchedContent) {\n if (debug) {\n const patterns = contentBlocks.map(b => b.urlPattern).join(\", \");\n console.error(`No <content> element matches resource URL: ${resourceUrl}. Available patterns: ${patterns}`);\n }\n throw new Error(\n `No <content> element in license.xml matches resource URL: ${resourceUrl}`\n );\n }\n\n if (debug) {\n console.debug(\"Matched content block for resource URL:\", resourceUrl);\n console.debug(\"Using license XML:\", matchedContent.licenseXml);\n }\n\n const tokenEndpoint = matchedContent.server + '/token';\n if (debug) {\n console.debug(`Requesting license token from ${tokenEndpoint}`);\n }\n\n const payload = new URLSearchParams({\n grant_type: \"client_credentials\",\n license: matchedContent.licenseXml,\n resource: matchedContent.urlPattern,\n });\n\n const requestOptions: RequestInit = {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/x-www-form-urlencoded\",\n Accept: \"application/json\",\n Authorization: \"Basic \" + btoa(`${clientId}:${clientSecret}`),\n },\n body: payload.toString(),\n };\n\n return retrieveLicenseToken(tokenEndpoint, requestOptions, debug);\n}\n\nexport type { ObtainLicenseTokenParams };\n","import { FASTLY_BACKEND, FetchOptions } from \"./types\";\n\nconst jwksCache = new Map<string, any>();\n\ntype JwksCacheKey = string;\n\ntype FetchJwksParams = {\n cacheKey: JwksCacheKey;\n url: string;\n debug: boolean;\n failureMessage: string;\n logLabel: string;\n};\n\nfunction buildFetchOptions(): FetchOptions {\n let options: FetchOptions = { method: \"GET\" };\n // @ts-ignore - backend is a Fastly-specific extension\n if (globalThis?.fastly) {\n options = { ...options, backend: FASTLY_BACKEND };\n }\n return options;\n}\n\nasync function fetchAndCacheJwks({\n cacheKey,\n url,\n debug,\n failureMessage,\n logLabel,\n}: FetchJwksParams): Promise<any> {\n if (!jwksCache.has(cacheKey)) {\n try {\n const response = await fetch(url, buildFetchOptions());\n\n if (!response.ok) {\n throw new Error(`${failureMessage}: ${response.status}`);\n }\n\n const jwksData = await response.json();\n jwksCache.set(cacheKey, jwksData);\n } catch (error) {\n if (debug) {\n console.error(logLabel, error);\n }\n throw error;\n }\n }\n\n return jwksCache.get(cacheKey);\n}\n\nexport async function fetchPlatformJwks(\n baseUrl: string,\n debug: boolean\n): Promise<any> {\n const jwksUrl = `${baseUrl}/.well-known/jwks.json/platform`;\n if (debug) {\n console.debug(`Fetching platform JWKS from URL: ${jwksUrl}`);\n }\n\n return fetchAndCacheJwks({\n cacheKey: \"platform_jwks\",\n url: jwksUrl,\n debug,\n failureMessage: \"Failed to fetch platform JWKS\",\n logLabel: \"Error fetching platform JWKS:\",\n });\n}\n\nexport function clearJwksCache(): void {\n jwksCache.clear();\n}\n","import { EventPayload, FASTLY_BACKEND } from \"./types\";\n\nexport async function recordEvent({\n apiKey,\n merchantSystemUrn,\n baseUrl,\n eventName,\n properties,\n licenseId,\n debug = false,\n}: {\n apiKey: string;\n merchantSystemUrn: string;\n baseUrl: string;\n eventName: string;\n properties: Record<string, any>;\n licenseId?: string;\n debug?: boolean;\n}): Promise<void> {\n const payload: EventPayload = {\n event_name: eventName,\n merchant_system_urn: merchantSystemUrn,\n license_id: licenseId,\n properties,\n };\n\n try {\n let options: any = {\n method: \"POST\",\n headers: {\n Authorization: `Bearer ${apiKey}`,\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(payload),\n };\n // @ts-ignore\n if (globalThis?.fastly) {\n options = { ...options, backend: FASTLY_BACKEND };\n }\n const response = await fetch(`${baseUrl}/events`, options);\n\n if (!response.ok && debug) {\n console.error(`Failed to record event: ${response.status}`);\n }\n } catch (error) {\n if (debug) {\n console.error(\"Error recording event:\", error);\n }\n }\n}\n","import type { JWTPayload, JWTHeaderParameters } from \"jose\";\nimport { loadJwtVerify, loadDecodeJwt, loadDecodeProtectedHeader } from \"./jose\";\n\ninterface LicenseJWTPayload extends JWTPayload {\n license_id?: string;\n}\nimport {\n ExecutionContext,\n HandlerAction,\n HandlerResult,\n LicenseTokenInvalidReason,\n LicenseTokenVerificationResult,\n FASTLY_BACKEND,\n FetchOptions,\n} from \"./types\";\nimport { fetchPlatformJwks } from \"./jwks\";\nimport { recordEvent } from \"./events\";\n\nconst stripTrailingSlash = (value: string) => value.trim().replace(/\\/+$/, \"\");\n\nfunction reasonToErrorDescription(reason: LicenseTokenInvalidReason): string {\n switch (reason) {\n case LicenseTokenInvalidReason.MISSING_TOKEN:\n return \"Authorization header missing or malformed\";\n case LicenseTokenInvalidReason.INVALID_ALG:\n return \"Unsupported token algorithm\";\n case LicenseTokenInvalidReason.EXPIRED:\n return \"The license token has expired\";\n case LicenseTokenInvalidReason.SIGNATURE_VERIFICATION_FAILED:\n return \"The license token signature is invalid\";\n case LicenseTokenInvalidReason.INVALID_HEADER:\n return \"The license token header is malformed\";\n case LicenseTokenInvalidReason.INVALID_PAYLOAD:\n return \"The license token payload is malformed\";\n case LicenseTokenInvalidReason.INVALID_ISSUER:\n return \"The license token issuer is not recognized\";\n case LicenseTokenInvalidReason.INVALID_AUDIENCE:\n return \"The license does not grant access to this resource\";\n case LicenseTokenInvalidReason.SERVER_ERROR:\n return \"The server encountered an error validating the license\";\n default:\n return \"License token missing, expired, revoked, or malformed\";\n }\n}\n\nexport type VerifyLicenseTokenParams = {\n licenseToken: string;\n requestUrl: string;\n supertabBaseUrl: string;\n debug: boolean;\n};\n\nexport async function verifyLicenseToken({\n licenseToken,\n requestUrl,\n supertabBaseUrl,\n debug,\n}: VerifyLicenseTokenParams): Promise<LicenseTokenVerificationResult> {\n const { decodeProtectedHeader } = await loadDecodeProtectedHeader();\n const { decodeJwt } = await loadDecodeJwt();\n const { jwtVerify } = await loadJwtVerify();\n\n if (!licenseToken) {\n return {\n valid: false,\n reason: LicenseTokenInvalidReason.MISSING_TOKEN,\n error: reasonToErrorDescription(LicenseTokenInvalidReason.MISSING_TOKEN),\n };\n }\n\n let header: JWTHeaderParameters;\n try {\n header = decodeProtectedHeader(licenseToken) as JWTHeaderParameters;\n } catch (error) {\n if (debug) {\n console.error(\"Invalid license JWT header:\", error);\n }\n return {\n valid: false,\n reason: LicenseTokenInvalidReason.INVALID_HEADER,\n error: reasonToErrorDescription(LicenseTokenInvalidReason.INVALID_HEADER),\n };\n }\n\n if (header.alg !== \"ES256\") {\n if (debug) {\n console.error(\"Unsupported license JWT alg:\", header.alg);\n }\n return {\n valid: false,\n reason: LicenseTokenInvalidReason.INVALID_ALG,\n error: reasonToErrorDescription(LicenseTokenInvalidReason.INVALID_ALG),\n };\n }\n\n let payload: LicenseJWTPayload;\n try {\n payload = decodeJwt(licenseToken) as LicenseJWTPayload;\n } catch (error) {\n if (debug) {\n console.error(\"Invalid license JWT payload:\", error);\n }\n return {\n valid: false,\n reason: LicenseTokenInvalidReason.INVALID_PAYLOAD,\n error: reasonToErrorDescription(LicenseTokenInvalidReason.INVALID_PAYLOAD),\n };\n }\n\n const licenseId: string | undefined = payload.license_id;\n\n const issuer: string | undefined = payload.iss;\n const normalizedIssuer = issuer ? stripTrailingSlash(issuer) : undefined;\n const normalizedBaseUrl = stripTrailingSlash(supertabBaseUrl);\n\n if (!normalizedIssuer || !normalizedIssuer.startsWith(normalizedBaseUrl)) {\n if (debug) {\n console.error(\"License JWT issuer is missing or malformed:\", issuer);\n }\n return {\n valid: false,\n reason: LicenseTokenInvalidReason.INVALID_ISSUER,\n error: reasonToErrorDescription(LicenseTokenInvalidReason.INVALID_ISSUER),\n licenseId,\n };\n }\n\n const audienceValues = Array.isArray(payload.aud)\n ? payload.aud.filter((entry): entry is string => typeof entry === \"string\")\n : typeof payload.aud === \"string\"\n ? [payload.aud]\n : [];\n\n const requestUrlNormalized = stripTrailingSlash(requestUrl);\n const matchesRequestUrl = audienceValues.some((value) => {\n const normalizedAudience = stripTrailingSlash(value);\n if (!normalizedAudience) return false;\n return requestUrlNormalized.startsWith(normalizedAudience);\n });\n\n if (!matchesRequestUrl) {\n if (debug) {\n console.error(\n \"License JWT audience does not match request URL:\",\n payload.aud\n );\n }\n return {\n valid: false,\n reason: LicenseTokenInvalidReason.INVALID_AUDIENCE,\n error: reasonToErrorDescription(LicenseTokenInvalidReason.INVALID_AUDIENCE),\n licenseId,\n };\n }\n\n let jwks;\n try {\n jwks = await fetchPlatformJwks(supertabBaseUrl, debug);\n } catch (error) {\n if (debug) {\n console.error(\"Failed to fetch platform JWKS:\", error);\n }\n return {\n valid: false,\n reason: LicenseTokenInvalidReason.SERVER_ERROR,\n error: reasonToErrorDescription(LicenseTokenInvalidReason.SERVER_ERROR),\n licenseId,\n };\n }\n\n try {\n const getKey = async (jwtHeader: JWTHeaderParameters) => {\n const jwk = jwks.keys.find((key: any) => key.kid === jwtHeader.kid);\n if (!jwk) {\n throw new Error(`No matching platform key found: ${jwtHeader.kid}`);\n }\n return jwk;\n };\n\n const result = await jwtVerify(licenseToken, getKey, {\n issuer,\n algorithms: [header.alg],\n clockTolerance: \"1m\",\n });\n\n return {\n valid: true,\n licenseId,\n payload: result.payload,\n };\n } catch (error) {\n if (debug) {\n console.error(\"License JWT verification failed:\", error);\n }\n\n if (error instanceof Error && error.message?.includes(\"exp\")) {\n return {\n valid: false,\n reason: LicenseTokenInvalidReason.EXPIRED,\n error: reasonToErrorDescription(LicenseTokenInvalidReason.EXPIRED),\n licenseId,\n };\n }\n\n return {\n valid: false,\n reason: LicenseTokenInvalidReason.SIGNATURE_VERIFICATION_FAILED,\n error: reasonToErrorDescription(LicenseTokenInvalidReason.SIGNATURE_VERIFICATION_FAILED),\n licenseId,\n };\n }\n}\n\nexport function generateLicenseLink({\n requestUrl,\n}: {\n requestUrl: string;\n}): string {\n const baseURL = new URL(requestUrl);\n return `${baseURL.protocol}//${baseURL.host}/license.xml`;\n}\n\n/**\n * Build a HandlerResult that signals a missing token in soft enforcement mode.\n * Returns headers indicating a license is required without blocking the request.\n */\nexport function buildSignalResult(requestUrl: string): HandlerResult {\n const licenseLink = generateLicenseLink({ requestUrl });\n return {\n action: HandlerAction.ALLOW,\n headers: {\n Link: `<${licenseLink}>; rel=\"license\"; type=\"application/rsl+xml\"`,\n \"X-RSL-Status\": \"token_required\",\n \"X-RSL-Reason\": \"missing\",\n },\n };\n}\n\nfunction reasonToRslError(reason: LicenseTokenInvalidReason | string): { rslError: string; status: number } {\n switch (reason) {\n case LicenseTokenInvalidReason.MISSING_TOKEN:\n case LicenseTokenInvalidReason.INVALID_ALG:\n return { rslError: \"invalid_request\", status: 401 };\n case LicenseTokenInvalidReason.EXPIRED:\n case LicenseTokenInvalidReason.SIGNATURE_VERIFICATION_FAILED:\n case LicenseTokenInvalidReason.INVALID_HEADER:\n case LicenseTokenInvalidReason.INVALID_PAYLOAD:\n case LicenseTokenInvalidReason.INVALID_ISSUER:\n return { rslError: \"invalid_token\", status: 401 };\n case LicenseTokenInvalidReason.INVALID_AUDIENCE:\n return { rslError: \"insufficient_scope\", status: 403 };\n case LicenseTokenInvalidReason.SERVER_ERROR:\n return { rslError: \"server_error\", status: 503 };\n default:\n return { rslError: \"invalid_token\", status: 401 };\n }\n}\n\n/**\n * Sanitize a string for safe use in an HTTP header quoted-string (RFC 7230).\n * Strips CR/LF to prevent header injection and escapes backslashes and quotes.\n */\nfunction sanitizeHeaderValue(value: string): string {\n return value\n .replace(/[\\r\\n]/g, \"\")\n .replace(/\\\\/g, \"\\\\\\\\\")\n .replace(/\"/g, '\\\\\"');\n}\n\nexport function buildBlockResult({\n reason,\n error,\n requestUrl,\n}: {\n reason: LicenseTokenInvalidReason | string;\n error: string;\n requestUrl: string;\n}): HandlerResult {\n const { rslError, status } = reasonToRslError(reason);\n const errorDescription = sanitizeHeaderValue(error);\n const licenseLink = generateLicenseLink({ requestUrl });\n\n return {\n action: HandlerAction.BLOCK,\n status,\n body: `Access to this resource requires a valid license token. Error: ${rslError} - ${error}`,\n headers: {\n \"Content-Type\": \"text/plain; charset=UTF-8\",\n \"WWW-Authenticate\": `License error=\"${rslError}\", error_description=\"${errorDescription}\"`,\n Link: `<${licenseLink}>; rel=\"license\"; type=\"application/rsl+xml\"`,\n },\n };\n}\n\nfunction buildFetchOptions(): FetchOptions {\n let options: FetchOptions = { method: \"GET\" };\n // @ts-ignore - backend is a Fastly-specific extension\n if (globalThis?.fastly) {\n options = { ...options, backend: FASTLY_BACKEND };\n }\n return options;\n}\n\nexport async function hostRSLicenseXML(\n supertabBaseUrl: string,\n merchantSystemUrn: string\n): Promise<Response> {\n const licenseUrl = `${supertabBaseUrl}/merchants/systems/${merchantSystemUrn}/license.xml`;\n const response = await fetch(licenseUrl, buildFetchOptions());\n\n if (!response.ok) {\n return new Response(\"License not found\", { status: 404 });\n }\n\n const licenseXml = await response.text();\n\n return new Response(licenseXml, {\n status: 200,\n headers: new Headers({ \"Content-Type\": \"application/xml\" }),\n });\n}\n\nexport type VerifyAndRecordEventParams = {\n token: string;\n url: string;\n userAgent: string;\n supertabBaseUrl: string;\n debug: boolean;\n apiKey: string;\n merchantSystemUrn: string;\n ctx?: ExecutionContext;\n};\n\nexport async function verifyAndRecordEvent(\n params: VerifyAndRecordEventParams\n): Promise<LicenseTokenVerificationResult> {\n const verification = await verifyLicenseToken({\n licenseToken: params.token,\n requestUrl: params.url,\n supertabBaseUrl: params.supertabBaseUrl,\n debug: params.debug,\n });\n\n const eventPromise = recordEvent({\n apiKey: params.apiKey,\n merchantSystemUrn: params.merchantSystemUrn,\n baseUrl: params.supertabBaseUrl,\n eventName: verification.valid ? \"license_used\" : verification.reason,\n properties: {\n page_url: params.url,\n user_agent: params.userAgent,\n verification_status: verification.valid ? \"valid\" : \"invalid\",\n verification_reason: verification.valid ? \"success\" : verification.reason,\n },\n licenseId: verification.licenseId,\n debug: params.debug,\n });\n if (params.ctx?.waitUntil) {\n params.ctx.waitUntil(eventPromise);\n }\n\n return verification;\n}\n","import {\n HandlerAction,\n HandlerResult,\n ExecutionContext,\n CloudFrontHeaders,\n CloudFrontRequestEvent,\n CloudFrontRequestResult,\n} from \"./types\";\nimport { hostRSLicenseXML } from \"./license\";\n\n// Interface for what the CDN handlers need - avoids circular dependency\ninterface RequestHandler {\n handleRequest(request: Request, ctx?: ExecutionContext): Promise<HandlerResult>;\n}\n\nexport async function handleCloudflareRequest(\n handler: RequestHandler,\n request: Request,\n ctx: ExecutionContext\n): Promise<Response> {\n const result = await handler.handleRequest(request, ctx);\n\n if (result.action === HandlerAction.BLOCK) {\n return new Response(result.body, {\n status: result.status,\n headers: new Headers(result.headers),\n });\n }\n\n // action === HandlerAction.ALLOW\n const originResponse = await fetch(request);\n\n if (result.headers) {\n const response = new Response(originResponse.body, originResponse);\n for (const [key, value] of Object.entries(result.headers)) {\n response.headers.set(key, value);\n }\n return response;\n }\n\n return originResponse;\n}\n\nexport async function handleFastlyRequest(\n handler: RequestHandler,\n request: Request,\n originBackend: string,\n rslOptions?: {\n baseUrl: string;\n merchantSystemUrn: string;\n }\n): Promise<Response> {\n if (rslOptions && new URL(request.url).pathname === \"/license.xml\") {\n return await hostRSLicenseXML(\n rslOptions.baseUrl,\n rslOptions.merchantSystemUrn\n );\n }\n\n const result = await handler.handleRequest(request);\n\n if (result.action === HandlerAction.BLOCK) {\n return new Response(result.body, {\n status: result.status,\n headers: new Headers(result.headers),\n });\n }\n\n // action === HandlerAction.ALLOW\n const originResponse = await fetch(request, {\n backend: originBackend,\n } as RequestInit);\n\n if (result.headers) {\n const response = new Response(originResponse.body, originResponse);\n for (const [key, value] of Object.entries(result.headers)) {\n response.headers.set(key, value);\n }\n return response;\n }\n\n return originResponse;\n}\n\nexport async function handleCloudfrontRequest<TRequest extends Record<string, any>>(\n handler: RequestHandler,\n event: CloudFrontRequestEvent<TRequest>\n): Promise<CloudFrontRequestResult<TRequest>> {\n const cfRequest = event.Records[0].cf.request;\n\n // Convert CloudFront request to Web API Request\n const url = `https://${cfRequest.headers.host[0].value}${cfRequest.uri}${cfRequest.querystring ? \"?\" + cfRequest.querystring : \"\"}`;\n\n const headers = new Headers();\n Object.entries(cfRequest.headers).forEach(([key, values]) => {\n values.forEach(({ value }) => headers.append(key, value));\n });\n\n const webRequest = new Request(url, {\n method: cfRequest.method,\n headers: headers,\n });\n\n const result = await handler.handleRequest(webRequest);\n\n if (result.action === HandlerAction.BLOCK) {\n const responseHeaders: CloudFrontHeaders = {};\n Object.entries(result.headers).forEach(([key, value]) => {\n responseHeaders[key.toLowerCase()] = [{ key, value }];\n });\n\n return {\n status: result.status.toString(),\n statusDescription:\n result.status === 401 ? \"Unauthorized\" : \"Payment Required\",\n headers: responseHeaders,\n body: result.body,\n };\n }\n\n // Allow request to continue to origin\n return cfRequest;\n}\n","/**\n * Default bot detection logic using multiple signals.\n * Checks User-Agent patterns, headless browser indicators, missing headers, and Cloudflare bot scores.\n * @param request The incoming request to analyze\n * @returns true if the request appears to be from a bot, false otherwise\n */\nexport function defaultBotDetector(request: Request): boolean {\n const userAgent = request.headers.get(\"User-Agent\") || \"\";\n const accept = request.headers.get(\"accept\") || \"\";\n const secChUa = request.headers.get(\"sec-ch-ua\");\n const acceptLanguage = request.headers.get(\"accept-language\");\n const botScore = (request as any).cf?.botManagement?.score;\n\n const botList = [\n \"chatgpt-user\",\n \"perplexitybot\",\n \"gptbot\",\n \"anthropic-ai\",\n \"ccbot\",\n \"claude-web\",\n \"claudebot\",\n \"cohere-ai\",\n \"youbot\",\n \"diffbot\",\n \"oai-searchbot\",\n \"meta-externalagent\",\n \"timpibot\",\n \"amazonbot\",\n \"bytespider\",\n \"perplexity-user\",\n \"googlebot\",\n \"bot\",\n \"curl\",\n \"wget\",\n ];\n // 1. Basic substring check from known list\n const lowerCaseUserAgent = userAgent.toLowerCase();\n const botUaMatch = botList.some((bot) => lowerCaseUserAgent.includes(bot));\n\n // 2. Headless browser detection\n const headlessIndicators =\n lowerCaseUserAgent.includes(\"headless\") ||\n lowerCaseUserAgent.includes(\"puppeteer\") ||\n !secChUa;\n\n const isBrowserMissingSecChUa =\n !lowerCaseUserAgent.includes(\"headless\") &&\n !lowerCaseUserAgent.includes(\"puppeteer\") &&\n !secChUa;\n\n // 3. Suspicious header gaps — many bots omit these\n const missingHeaders = !accept || !acceptLanguage;\n\n // 4. Cloudflare bot score check (if available)\n const lowBotScore = typeof botScore === \"number\" && botScore < 30;\n\n // Safari and Mozilla special case\n if (\n lowerCaseUserAgent.includes(\"safari\") ||\n lowerCaseUserAgent.includes(\"mozilla\")\n ) {\n // Safari is not a bot, but it may be headless\n if (headlessIndicators && isBrowserMissingSecChUa) {\n return false; // Likely not a bot, but missing a Sec-CH-UA header\n }\n }\n\n // Final decision\n return botUaMatch || headlessIndicators || missingHeaders || lowBotScore;\n}\n"],"mappings":"4jBAAA,IAAAA,GAAA,GAAAC,GAAAD,GAA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Aad,GAAS,YACtB,YAAaA,GAAS,WACxB,CAAC,EACD,OAAOgB,EAAwBD,EAAUV,EAASC,CAAG,CACvD,CAaA,aAAa,qBACXD,EACAY,EACAC,EACAC,EACAnB,EAKmB,CACnB,GAAM,CAAE,UAAAoB,EAAY,GAAO,YAAAC,EAAa,YAAAC,CAAY,EAAItB,GAAW,CAAC,EAE9De,EAAW,IAAInB,EAAgB,CACnC,OAAQsB,EACR,kBAAmBD,EACnB,YAAAI,EACA,YAAAC,CACF,CAAC,EAED,OAAOC,EACLR,EACAV,EACAc,EACAC,EACI,CACE,QAASxB,EAAgB,QACzB,kBAAAqB,CACF,EACA,MACN,CACF,CAQA,aAAa,yBACXO,EACAxB,EAC4C,CAC5C,IAAMe,EAAW,IAAInB,EAAgB,CACnC,OAAQI,EAAQ,OAChB,kBAAmBA,EAAQ,kBAC3B,YAAaA,EAAQ,YACrB,YAAaA,EAAQ,WACvB,CAAC,EACD,OAAOyB,EAAwBV,EAAUS,CAAK,CAChD,CACF,EA1Ta5B,EAEI,QAAkB,kCAFtBA,EAQI,UAAoC,KAR9C,IAAM8B,EAAN9B","names":["index_exports","__export","EnforcementMode","HandlerAction","SupertabConnect","defaultBotDetector","__toCommonJS","EnforcementMode","FASTLY_BACKEND","HandlerAction","lazyImport","load","cached","loadJwtVerify","loadDecodeJwt","loadDecodeProtectedHeader","loadKeyImport","loadJwtSign","retrieveLicenseToken","tokenEndpoint","requestOptions","debug","response","errorBody","errorMessage","data","parseError","error","fetchLicenseXml","resourceUrl","debug","licenseXmlUrl","response","xml","parseContentElements","contentBlocks","contentRegex","urlRegex","serverRegex","licenseRegex","elementCount","match","attrs","body","urlMatch","serverMatch","licenseMatch","missing","findBestMatchingContent","parsed","host","path","bestMatch","bestSpecificity","block","patternUrl","patternPath","prefix","specificity","obtainLicenseToken","clientId","clientSecret","resourceUrl","debug","xml","fetchLicenseXml","contentBlocks","parseContentElements","matchedContent","findBestMatchingContent","patterns","b","tokenEndpoint","payload","requestOptions","retrieveLicenseToken","jwksCache","buildFetchOptions","options","FASTLY_BACKEND","fetchAndCacheJwks","cacheKey","url","debug","failureMessage","logLabel","response","jwksData","error","fetchPlatformJwks","baseUrl","jwksUrl","recordEvent","apiKey","merchantSystemUrn","baseUrl","eventName","properties","licenseId","debug","payload","options","FASTLY_BACKEND","response","error","stripTrailingSlash","value","reasonToErrorDescription","reason","verifyLicenseToken","licenseToken","requestUrl","supertabBaseUrl","debug","decodeProtectedHeader","loadDecodeProtectedHeader","decodeJwt","loadDecodeJwt","jwtVerify","loadJwtVerify","header","error","payload","licenseId","issuer","normalizedIssuer","normalizedBaseUrl","audienceValues","entry","requestUrlNormalized","normalizedAudience","jwks","fetchPlatformJwks","result","jwtHeader","jwk","key","generateLicenseLink","baseURL","buildSignalResult","licenseLink","reasonToRslError","sanitizeHeaderValue","buildBlockResult","rslError","status","errorDescription","buildFetchOptions","options","FASTLY_BACKEND","hostRSLicenseXML","merchantSystemUrn","licenseUrl","response","licenseXml","verifyAndRecordEvent","params","verification","eventPromise","recordEvent","handleCloudflareRequest","handler","request","ctx","result","originResponse","response","key","value","handleFastlyRequest","originBackend","rslOptions","hostRSLicenseXML","handleCloudfrontRequest","event","cfRequest","url","headers","values","webRequest","responseHeaders","defaultBotDetector","request","userAgent","accept","secChUa","acceptLanguage","botScore","botList","lowerCaseUserAgent","botUaMatch","bot","headlessIndicators","isBrowserMissingSecChUa","missingHeaders","lowBotScore","_SupertabConnect","config","reset","url","options","baseUrl","result","verifyLicenseToken","verifyAndRecordEvent","request","ctx","auth","token","userAgent","verification","buildBlockResult","buildSignalResult","obtainLicenseToken","env","instance","handleCloudflareRequest","merchantSystemUrn","merchantApiKey","originBackend","enableRSL","botDetector","enforcement","handleFastlyRequest","event","handleCloudfrontRequest","SupertabConnect"]}
|
package/dist/index.d.cts
CHANGED
|
@@ -182,14 +182,21 @@ declare class SupertabConnect {
|
|
|
182
182
|
* @param request The incoming Worker request
|
|
183
183
|
* @param env Worker environment bindings containing MERCHANT_API_KEY and MERCHANT_SYSTEM_URN
|
|
184
184
|
* @param ctx Worker execution context for non-blocking event recording
|
|
185
|
+
* @param options Optional configuration items
|
|
186
|
+
* @param options.botDetector Custom bot detection function
|
|
187
|
+
* @param options.enforcement Enforcement mode (default: SOFT)
|
|
185
188
|
*/
|
|
186
|
-
static cloudflareHandleRequests(request: Request, env: Env, ctx: ExecutionContext
|
|
189
|
+
static cloudflareHandleRequests(request: Request, env: Env, ctx: ExecutionContext, options?: {
|
|
190
|
+
botDetector?: BotDetector;
|
|
191
|
+
enforcement?: EnforcementMode;
|
|
192
|
+
}): Promise<Response>;
|
|
187
193
|
/**
|
|
188
194
|
* Handle incoming requests for Fastly Compute.
|
|
189
195
|
* @param request The incoming Fastly request
|
|
190
196
|
* @param merchantSystemUrn The merchant system URN for identification
|
|
191
197
|
* @param merchantApiKey The merchant API key for authentication
|
|
192
198
|
* @param originBackend The Fastly backend name to forward allowed requests to
|
|
199
|
+
* @param options Optional configuration items
|
|
193
200
|
* @param options.enableRSL Serve license.xml at /license.xml for RSL-compliant clients (default: false)
|
|
194
201
|
* @param options.botDetector Custom bot detection function
|
|
195
202
|
* @param options.enforcement Enforcement mode (default: SOFT)
|
package/dist/index.d.ts
CHANGED
|
@@ -182,14 +182,21 @@ declare class SupertabConnect {
|
|
|
182
182
|
* @param request The incoming Worker request
|
|
183
183
|
* @param env Worker environment bindings containing MERCHANT_API_KEY and MERCHANT_SYSTEM_URN
|
|
184
184
|
* @param ctx Worker execution context for non-blocking event recording
|
|
185
|
+
* @param options Optional configuration items
|
|
186
|
+
* @param options.botDetector Custom bot detection function
|
|
187
|
+
* @param options.enforcement Enforcement mode (default: SOFT)
|
|
185
188
|
*/
|
|
186
|
-
static cloudflareHandleRequests(request: Request, env: Env, ctx: ExecutionContext
|
|
189
|
+
static cloudflareHandleRequests(request: Request, env: Env, ctx: ExecutionContext, options?: {
|
|
190
|
+
botDetector?: BotDetector;
|
|
191
|
+
enforcement?: EnforcementMode;
|
|
192
|
+
}): Promise<Response>;
|
|
187
193
|
/**
|
|
188
194
|
* Handle incoming requests for Fastly Compute.
|
|
189
195
|
* @param request The incoming Fastly request
|
|
190
196
|
* @param merchantSystemUrn The merchant system URN for identification
|
|
191
197
|
* @param merchantApiKey The merchant API key for authentication
|
|
192
198
|
* @param originBackend The Fastly backend name to forward allowed requests to
|
|
199
|
+
* @param options Optional configuration items
|
|
193
200
|
* @param options.enableRSL Serve license.xml at /license.xml for RSL-compliant clients (default: false)
|
|
194
201
|
* @param options.botDetector Custom bot detection function
|
|
195
202
|
* @param options.enforcement Enforcement mode (default: SOFT)
|
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var C=(t=>(t.DISABLED="disabled",t.SOFT="soft",t.STRICT="strict",t))(C||{});var y="stc-backend",E=(r=>(r.ALLOW="allow",r.BLOCK="block",r))(E||{});var A=null;function I(){return A||(A=import("jose")),A}async function V(n,e,r){try{let t=await fetch(n,e);if(!t.ok){let o=await t.text().catch(()=>""),a=`Failed to obtain license token: ${t.status} ${t.statusText}${o?` - ${o}`:""}`;throw new Error(a)}let s;try{s=await t.json()}catch(o){throw r&&console.error("Failed to parse license token response as JSON:",o),new Error("Failed to parse license token response as JSON")}if(!s?.access_token)throw new Error("License token response missing access_token");return s.access_token}catch(t){throw r&&console.error("Error generating license token:",t),t}}async function J(n,e){let t=`${new URL(n).origin}/license.xml`,s=await fetch(t);if(!s.ok)throw e&&console.error(`Failed to fetch license.xml from ${t}: ${s.status}`),new Error(`Failed to fetch license.xml from ${t}: ${s.status}`);let o=await s.text();return e&&console.debug("Fetched license.xml from",t),o}function M(n,e){let r=[],t=/<content\s([^>]*)>([\s\S]*?)<\/content>/gi,s=/url\s*=\s*"([^"]*)"/i,o=/server\s*=\s*"([^"]*)"/i,a=/<license[^>]*>[\s\S]*?<\/license>/i,c=0,i;for(;(i=t.exec(n))!==null;){c++;let l=i[1],d=i[2],p=l.match(s),m=l.match(o),g=d.match(a);if(p&&m&&g)r.push({urlPattern:p[1],server:m[1],licenseXml:g[0]});else if(e){let L=[!p&&"url",!m&&"server",!g&&"<license>"].filter(Boolean).join(", ");console.debug(`Skipping <content> element #${c}: missing ${L}`)}}return e&&console.debug(`Found ${c} <content> element(s), ${r.length} valid`),r}function W(n,e,r){let t=new URL(e),s=t.host,o=t.pathname;r&&console.debug(`Matching resource URL: ${e} (host=${s}, path=${o})`);let a=null,c=-1;for(let i of n){let l;try{l=new URL(i.urlPattern)}catch{r&&console.debug(`Skipping block with invalid URL pattern: ${i.urlPattern}`);continue}if(l.host!==s){r&&console.debug(`Skipping block: host mismatch (pattern=${l.host}, resource=${s})`);continue}let d=l.pathname;if(d===o)return r&&console.debug(`Exact match found: ${i.urlPattern}`),i;if(d.endsWith("/*")){let p=d.slice(0,-1);if(o.startsWith(p)){let m=p.length;m>c&&(c=m,a=i)}}}return r&&console.debug(a?`Wildcard match found: ${a.urlPattern} (specificity=${c})`:`No matching content block found for ${e}`),a}async function _({clientId:n,clientSecret:e,resourceUrl:r,debug:t}){let s=await J(r,t);t&&console.debug(`Fetched license.xml (${s.length} chars)`);let o=M(s,t);if(o.length===0)throw t&&console.error("No valid <content> elements with <license> found in license.xml"),new Error("No valid <content> elements with <license> found in license.xml");let a=W(o,r,t);if(!a){if(t){let d=o.map(p=>p.urlPattern).join(", ");console.error(`No <content> element matches resource URL: ${r}. Available patterns: ${d}`)}throw new Error(`No <content> element in license.xml matches resource URL: ${r}`)}t&&(console.debug("Matched content block for resource URL:",r),console.debug("Using license XML:",a.licenseXml));let c=a.server+"/token";t&&console.debug(`Requesting license token from ${c}`);let i=new URLSearchParams({grant_type:"client_credentials",license:a.licenseXml,resource:a.urlPattern}),l={method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json",Authorization:"Basic "+btoa(`${n}:${e}`)},body:i.toString()};return V(c,l,t)}var w=new Map;function j(){let n={method:"GET"};return globalThis?.fastly&&(n={...n,backend:y}),n}async function G({cacheKey:n,url:e,debug:r,failureMessage:t,logLabel:s}){if(!w.has(n))try{let o=await fetch(e,j());if(!o.ok)throw new Error(`${t}: ${o.status}`);let a=await o.json();w.set(n,a)}catch(o){throw r&&console.error(s,o),o}return w.get(n)}async function D(n,e){let r=`${n}/.well-known/jwks.json/platform`;return e&&console.debug(`Fetching platform JWKS from URL: ${r}`),G({cacheKey:"platform_jwks",url:r,debug:e,failureMessage:"Failed to fetch platform JWKS",logLabel:"Error fetching platform JWKS:"})}async function P({apiKey:n,merchantSystemUrn:e,baseUrl:r,eventName:t,properties:s,licenseId:o,debug:a=!1}){let c={event_name:t,merchant_system_urn:e,license_id:o,properties:s};try{let i={method:"POST",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"},body:JSON.stringify(c)};globalThis?.fastly&&(i={...i,backend:y});let l=await fetch(`${r}/events`,i);!l.ok&&a&&console.error(`Failed to record event: ${l.status}`)}catch(i){a&&console.error("Error recording event:",i)}}var b=n=>n.trim().replace(/\/+$/,"");function h(n){switch(n){case"missing_license_token":return"Authorization header missing or malformed";case"invalid_license_algorithm":return"Unsupported token algorithm";case"license_token_expired":return"The license token has expired";case"license_signature_verification_failed":return"The license token signature is invalid";case"invalid_license_header":return"The license token header is malformed";case"invalid_license_payload":return"The license token payload is malformed";case"invalid_license_issuer":return"The license token issuer is not recognized";case"invalid_license_audience":return"The license does not grant access to this resource";case"server_error":return"The server encountered an error validating the license";default:return"License token missing, expired, revoked, or malformed"}}async function S({licenseToken:n,requestUrl:e,supertabBaseUrl:r,debug:t}){let{decodeProtectedHeader:s,decodeJwt:o,jwtVerify:a}=await I();if(!n)return{valid:!1,reason:"missing_license_token",error:h("missing_license_token")};let c;try{c=s(n)}catch(f){return t&&console.error("Invalid license JWT header:",f),{valid:!1,reason:"invalid_license_header",error:h("invalid_license_header")}}if(c.alg!=="ES256")return t&&console.error("Unsupported license JWT alg:",c.alg),{valid:!1,reason:"invalid_license_algorithm",error:h("invalid_license_algorithm")};let i;try{i=o(n)}catch(f){return t&&console.error("Invalid license JWT payload:",f),{valid:!1,reason:"invalid_license_payload",error:h("invalid_license_payload")}}let l=i.license_id,d=i.iss,p=d?b(d):void 0,m=b(r);if(!p||!p.startsWith(m))return t&&console.error("License JWT issuer is missing or malformed:",d),{valid:!1,reason:"invalid_license_issuer",error:h("invalid_license_issuer"),licenseId:l};let g=Array.isArray(i.aud)?i.aud.filter(f=>typeof f=="string"):typeof i.aud=="string"?[i.aud]:[],L=b(e);if(!g.some(f=>{let R=b(f);return R?L.startsWith(R):!1}))return t&&console.error("License JWT audience does not match request URL:",i.aud),{valid:!1,reason:"invalid_license_audience",error:h("invalid_license_audience"),licenseId:l};let U;try{U=await D(r,t)}catch(f){return t&&console.error("Failed to fetch platform JWKS:",f),{valid:!1,reason:"server_error",error:h("server_error"),licenseId:l}}try{let R=await a(n,async v=>{let T=U.keys.find(K=>K.kid===v.kid);if(!T)throw new Error(`No matching platform key found: ${v.kid}`);return T},{issuer:d,algorithms:[c.alg],clockTolerance:"1m"});return{valid:!0,licenseId:l,payload:R.payload}}catch(f){return t&&console.error("License JWT verification failed:",f),f instanceof Error&&f.message?.includes("exp")?{valid:!1,reason:"license_token_expired",error:h("license_token_expired"),licenseId:l}:{valid:!1,reason:"license_signature_verification_failed",error:h("license_signature_verification_failed"),licenseId:l}}}function N({requestUrl:n}){let e=new URL(n);return`${e.protocol}//${e.host}/license.xml`}function q(n){let e=N({requestUrl:n});return{action:"allow",headers:{Link:`<${e}>; rel="license"; type="application/rsl+xml"`,"X-RSL-Status":"token_required","X-RSL-Reason":"missing"}}}function z(n){switch(n){case"missing_license_token":case"invalid_license_algorithm":return{rslError:"invalid_request",status:401};case"license_token_expired":case"license_signature_verification_failed":case"invalid_license_header":case"invalid_license_payload":case"invalid_license_issuer":return{rslError:"invalid_token",status:401};case"invalid_license_audience":return{rslError:"insufficient_scope",status:403};case"server_error":return{rslError:"server_error",status:503};default:return{rslError:"invalid_token",status:401}}}function Y(n){return n.replace(/[\r\n]/g,"").replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function k({reason:n,error:e,requestUrl:r}){let{rslError:t,status:s}=z(n),o=Y(e),a=N({requestUrl:r});return{action:"block",status:s,body:`Access to this resource requires a valid license token. Error: ${t} - ${e}`,headers:{"Content-Type":"text/plain; charset=UTF-8","WWW-Authenticate":`License error="${t}", error_description="${o}"`,Link:`<${a}>; rel="license"; type="application/rsl+xml"`}}}function Q(){let n={method:"GET"};return globalThis?.fastly&&(n={...n,backend:y}),n}async function F(n,e){let r=`${n}/merchants/systems/${e}/license.xml`,t=await fetch(r,Q());if(!t.ok)return new Response("License not found",{status:404});let s=await t.text();return new Response(s,{status:200,headers:new Headers({"Content-Type":"application/xml"})})}async function x(n){let e=await S({licenseToken:n.token,requestUrl:n.url,supertabBaseUrl:n.supertabBaseUrl,debug:n.debug}),r=P({apiKey:n.apiKey,merchantSystemUrn:n.merchantSystemUrn,baseUrl:n.supertabBaseUrl,eventName:e.valid?"license_used":e.reason,properties:{page_url:n.url,user_agent:n.userAgent,verification_status:e.valid?"valid":"invalid",verification_reason:e.valid?"success":e.reason},licenseId:e.licenseId,debug:n.debug});return n.ctx?.waitUntil&&n.ctx.waitUntil(r),e}async function O(n,e,r){let t=await n.handleRequest(e,r);if(t.action==="block")return new Response(t.body,{status:t.status,headers:new Headers(t.headers)});let s=await fetch(e);if(t.headers){let o=new Response(s.body,s);for(let[a,c]of Object.entries(t.headers))o.headers.set(a,c);return o}return s}async function $(n,e,r,t){if(t&&new URL(e.url).pathname==="/license.xml")return await F(t.baseUrl,t.merchantSystemUrn);let s=await n.handleRequest(e);if(s.action==="block")return new Response(s.body,{status:s.status,headers:new Headers(s.headers)});let o=await fetch(e,{backend:r});if(s.headers){let a=new Response(o.body,o);for(let[c,i]of Object.entries(s.headers))a.headers.set(c,i);return a}return o}async function B(n,e){let r=e.Records[0].cf.request,t=`https://${r.headers.host[0].value}${r.uri}${r.querystring?"?"+r.querystring:""}`,s=new Headers;Object.entries(r.headers).forEach(([c,i])=>{i.forEach(({value:l})=>s.append(c,l))});let o=new Request(t,{method:r.method,headers:s}),a=await n.handleRequest(o);if(a.action==="block"){let c={};return Object.entries(a.headers).forEach(([i,l])=>{c[i.toLowerCase()]=[{key:i,value:l}]}),{status:a.status.toString(),statusDescription:a.status===401?"Unauthorized":"Payment Required",headers:c,body:a.body}}return r}function Z(n){let e=n.headers.get("User-Agent")||"",r=n.headers.get("accept")||"",t=n.headers.get("sec-ch-ua"),s=n.headers.get("accept-language"),o=n.cf?.botManagement?.score,a=["chatgpt-user","perplexitybot","gptbot","anthropic-ai","ccbot","claude-web","claudebot","cohere-ai","youbot","diffbot","oai-searchbot","meta-externalagent","timpibot","amazonbot","bytespider","perplexity-user","googlebot","bot","curl","wget"],c=e.toLowerCase(),i=a.some(g=>c.includes(g)),l=c.includes("headless")||c.includes("puppeteer")||!t,d=!c.includes("headless")&&!c.includes("puppeteer")&&!t,p=!r||!s,m=typeof o=="number"&&o<30;return(c.includes("safari")||c.includes("mozilla"))&&l&&d?!1:i||l||p||m}var u=class u{constructor(e,r=!1){if(!r&&u._instance){if(!(e.apiKey===u._instance.apiKey&&e.merchantSystemUrn===u._instance.merchantSystemUrn))throw new Error("Cannot create a new instance with different configuration. Use resetInstance to clear the existing instance.");return u._instance}if(r&&u._instance&&u.resetInstance(),!e.apiKey||!e.merchantSystemUrn)throw new Error("Missing required configuration: apiKey and merchantSystemUrn are required");this.apiKey=e.apiKey,this.merchantSystemUrn=e.merchantSystemUrn,this.enforcement=e.enforcement??"soft",this.botDetector=e.botDetector,this.debug=e.debug??!1,u._instance=this}static resetInstance(){u._instance=null}static setBaseUrl(e){u.baseUrl=e}static getBaseUrl(){return u.baseUrl}static async verify(e){let r=e.baseUrl??u.baseUrl,t=await S({licenseToken:e.token,requestUrl:e.resourceUrl,supertabBaseUrl:r,debug:e.debug??!1});return t.valid?{valid:!0}:{valid:!1,error:t.error}}async verifyAndRecord(e){let r=await x({token:e.token,url:e.resourceUrl,userAgent:e.userAgent??"unknown",supertabBaseUrl:u.baseUrl,debug:e.debug??this.debug,apiKey:this.apiKey,merchantSystemUrn:this.merchantSystemUrn,ctx:e.ctx});return r.valid?{valid:!0}:{valid:!1,error:r.error}}async handleRequest(e,r){let t=e.headers.get("Authorization")||"",s=t.startsWith("License ")?t.slice(8):null,o=e.url,a=e.headers.get("User-Agent")||"unknown";if(s){if(this.enforcement==="disabled")return{action:"allow"};let i=await x({token:s,url:o,userAgent:a,supertabBaseUrl:u.baseUrl,debug:this.debug,apiKey:this.apiKey,merchantSystemUrn:this.merchantSystemUrn,ctx:r});return i.valid?{action:"allow"}:k({reason:i.reason,error:i.error,requestUrl:o})}if(!(this.botDetector?.(e,r)??!1))return{action:"allow"};switch(this.enforcement){case"strict":return k({reason:"missing_license_token",error:"Authorization header missing or malformed",requestUrl:o});case"soft":return q(o);default:return{action:"allow"}}}static async obtainLicenseToken(e){return _({clientId:e.clientId,clientSecret:e.clientSecret,resourceUrl:e.resourceUrl,debug:e.debug})}static async cloudflareHandleRequests(e,r,t){let s=new u({apiKey:r.MERCHANT_API_KEY,merchantSystemUrn:r.MERCHANT_SYSTEM_URN});return O(s,e,t)}static async fastlyHandleRequests(e,r,t,s,o){let{enableRSL:a=!1,botDetector:c,enforcement:i}=o??{},l=new u({apiKey:t,merchantSystemUrn:r,botDetector:c,enforcement:i});return $(l,e,s,a?{baseUrl:u.baseUrl,merchantSystemUrn:r}:void 0)}static async cloudfrontHandleRequests(e,r){let t=new u({apiKey:r.apiKey,merchantSystemUrn:r.merchantSystemUrn,botDetector:r.botDetector,enforcement:r.enforcement});return B(t,e)}};u.baseUrl="https://api-connect.supertab.co",u._instance=null;var H=u;export{C as EnforcementMode,E as HandlerAction,H as SupertabConnect,Z as defaultBotDetector};
|
|
1
|
+
var T=(t=>(t.DISABLED="disabled",t.SOFT="soft",t.STRICT="strict",t))(T||{});var y="stc-backend",E=(r=>(r.ALLOW="allow",r.BLOCK="block",r))(E||{});function R(n){let e=null;return()=>(e||(e=n()),e)}var C=R(()=>import("jose/jwt/verify")),_=R(()=>import("jose/jwt/decode")),D=R(()=>import("jose/decode/protected_header")),W=R(()=>import("jose/key/import")),M=R(()=>import("jose/jwt/sign"));async function j(n,e,r){try{let t=await fetch(n,e);if(!t.ok){let o=await t.text().catch(()=>""),a=`Failed to obtain license token: ${t.status} ${t.statusText}${o?` - ${o}`:""}`;throw new Error(a)}let s;try{s=await t.json()}catch(o){throw r&&console.error("Failed to parse license token response as JSON:",o),new Error("Failed to parse license token response as JSON")}if(!s?.access_token)throw new Error("License token response missing access_token");return s.access_token}catch(t){throw r&&console.error("Error generating license token:",t),t}}async function G(n,e){let t=`${new URL(n).origin}/license.xml`,s=await fetch(t);if(!s.ok)throw e&&console.error(`Failed to fetch license.xml from ${t}: ${s.status}`),new Error(`Failed to fetch license.xml from ${t}: ${s.status}`);let o=await s.text();return e&&console.debug("Fetched license.xml from",t),o}function X(n,e){let r=[],t=/<content\s([^>]*)>([\s\S]*?)<\/content>/gi,s=/url\s*=\s*"([^"]*)"/i,o=/server\s*=\s*"([^"]*)"/i,a=/<license[^>]*>[\s\S]*?<\/license>/i,c=0,i;for(;(i=t.exec(n))!==null;){c++;let l=i[1],d=i[2],p=l.match(s),m=l.match(o),g=d.match(a);if(p&&m&&g)r.push({urlPattern:p[1],server:m[1],licenseXml:g[0]});else if(e){let w=[!p&&"url",!m&&"server",!g&&"<license>"].filter(Boolean).join(", ");console.debug(`Skipping <content> element #${c}: missing ${w}`)}}return e&&console.debug(`Found ${c} <content> element(s), ${r.length} valid`),r}function z(n,e,r){let t=new URL(e),s=t.host,o=t.pathname;r&&console.debug(`Matching resource URL: ${e} (host=${s}, path=${o})`);let a=null,c=-1;for(let i of n){let l;try{l=new URL(i.urlPattern)}catch{r&&console.debug(`Skipping block with invalid URL pattern: ${i.urlPattern}`);continue}if(l.host!==s){r&&console.debug(`Skipping block: host mismatch (pattern=${l.host}, resource=${s})`);continue}let d=l.pathname;if(d===o)return r&&console.debug(`Exact match found: ${i.urlPattern}`),i;if(d.endsWith("/*")){let p=d.slice(0,-1);if(o.startsWith(p)){let m=p.length;m>c&&(c=m,a=i)}}}return r&&console.debug(a?`Wildcard match found: ${a.urlPattern} (specificity=${c})`:`No matching content block found for ${e}`),a}async function P({clientId:n,clientSecret:e,resourceUrl:r,debug:t}){let s=await G(r,t);t&&console.debug(`Fetched license.xml (${s.length} chars)`);let o=X(s,t);if(o.length===0)throw t&&console.error("No valid <content> elements with <license> found in license.xml"),new Error("No valid <content> elements with <license> found in license.xml");let a=z(o,r,t);if(!a){if(t){let d=o.map(p=>p.urlPattern).join(", ");console.error(`No <content> element matches resource URL: ${r}. Available patterns: ${d}`)}throw new Error(`No <content> element in license.xml matches resource URL: ${r}`)}t&&(console.debug("Matched content block for resource URL:",r),console.debug("Using license XML:",a.licenseXml));let c=a.server+"/token";t&&console.debug(`Requesting license token from ${c}`);let i=new URLSearchParams({grant_type:"client_credentials",license:a.licenseXml,resource:a.urlPattern}),l={method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json",Authorization:"Basic "+btoa(`${n}:${e}`)},body:i.toString()};return j(c,l,t)}var I=new Map;function Y(){let n={method:"GET"};return globalThis?.fastly&&(n={...n,backend:y}),n}async function Q({cacheKey:n,url:e,debug:r,failureMessage:t,logLabel:s}){if(!I.has(n))try{let o=await fetch(e,Y());if(!o.ok)throw new Error(`${t}: ${o.status}`);let a=await o.json();I.set(n,a)}catch(o){throw r&&console.error(s,o),o}return I.get(n)}async function N(n,e){let r=`${n}/.well-known/jwks.json/platform`;return e&&console.debug(`Fetching platform JWKS from URL: ${r}`),Q({cacheKey:"platform_jwks",url:r,debug:e,failureMessage:"Failed to fetch platform JWKS",logLabel:"Error fetching platform JWKS:"})}async function q({apiKey:n,merchantSystemUrn:e,baseUrl:r,eventName:t,properties:s,licenseId:o,debug:a=!1}){let c={event_name:t,merchant_system_urn:e,license_id:o,properties:s};try{let i={method:"POST",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"},body:JSON.stringify(c)};globalThis?.fastly&&(i={...i,backend:y});let l=await fetch(`${r}/events`,i);!l.ok&&a&&console.error(`Failed to record event: ${l.status}`)}catch(i){a&&console.error("Error recording event:",i)}}var L=n=>n.trim().replace(/\/+$/,"");function h(n){switch(n){case"missing_license_token":return"Authorization header missing or malformed";case"invalid_license_algorithm":return"Unsupported token algorithm";case"license_token_expired":return"The license token has expired";case"license_signature_verification_failed":return"The license token signature is invalid";case"invalid_license_header":return"The license token header is malformed";case"invalid_license_payload":return"The license token payload is malformed";case"invalid_license_issuer":return"The license token issuer is not recognized";case"invalid_license_audience":return"The license does not grant access to this resource";case"server_error":return"The server encountered an error validating the license";default:return"License token missing, expired, revoked, or malformed"}}async function A({licenseToken:n,requestUrl:e,supertabBaseUrl:r,debug:t}){let{decodeProtectedHeader:s}=await D(),{decodeJwt:o}=await _(),{jwtVerify:a}=await C();if(!n)return{valid:!1,reason:"missing_license_token",error:h("missing_license_token")};let c;try{c=s(n)}catch(f){return t&&console.error("Invalid license JWT header:",f),{valid:!1,reason:"invalid_license_header",error:h("invalid_license_header")}}if(c.alg!=="ES256")return t&&console.error("Unsupported license JWT alg:",c.alg),{valid:!1,reason:"invalid_license_algorithm",error:h("invalid_license_algorithm")};let i;try{i=o(n)}catch(f){return t&&console.error("Invalid license JWT payload:",f),{valid:!1,reason:"invalid_license_payload",error:h("invalid_license_payload")}}let l=i.license_id,d=i.iss,p=d?L(d):void 0,m=L(r);if(!p||!p.startsWith(m))return t&&console.error("License JWT issuer is missing or malformed:",d),{valid:!1,reason:"invalid_license_issuer",error:h("invalid_license_issuer"),licenseId:l};let g=Array.isArray(i.aud)?i.aud.filter(f=>typeof f=="string"):typeof i.aud=="string"?[i.aud]:[],w=L(e);if(!g.some(f=>{let b=L(f);return b?w.startsWith(b):!1}))return t&&console.error("License JWT audience does not match request URL:",i.aud),{valid:!1,reason:"invalid_license_audience",error:h("invalid_license_audience"),licenseId:l};let x;try{x=await N(r,t)}catch(f){return t&&console.error("Failed to fetch platform JWKS:",f),{valid:!1,reason:"server_error",error:h("server_error"),licenseId:l}}try{let b=await a(n,async U=>{let v=x.keys.find(J=>J.kid===U.kid);if(!v)throw new Error(`No matching platform key found: ${U.kid}`);return v},{issuer:d,algorithms:[c.alg],clockTolerance:"1m"});return{valid:!0,licenseId:l,payload:b.payload}}catch(f){return t&&console.error("License JWT verification failed:",f),f instanceof Error&&f.message?.includes("exp")?{valid:!1,reason:"license_token_expired",error:h("license_token_expired"),licenseId:l}:{valid:!1,reason:"license_signature_verification_failed",error:h("license_signature_verification_failed"),licenseId:l}}}function F({requestUrl:n}){let e=new URL(n);return`${e.protocol}//${e.host}/license.xml`}function O(n){let e=F({requestUrl:n});return{action:"allow",headers:{Link:`<${e}>; rel="license"; type="application/rsl+xml"`,"X-RSL-Status":"token_required","X-RSL-Reason":"missing"}}}function ee(n){switch(n){case"missing_license_token":case"invalid_license_algorithm":return{rslError:"invalid_request",status:401};case"license_token_expired":case"license_signature_verification_failed":case"invalid_license_header":case"invalid_license_payload":case"invalid_license_issuer":return{rslError:"invalid_token",status:401};case"invalid_license_audience":return{rslError:"insufficient_scope",status:403};case"server_error":return{rslError:"server_error",status:503};default:return{rslError:"invalid_token",status:401}}}function te(n){return n.replace(/[\r\n]/g,"").replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function S({reason:n,error:e,requestUrl:r}){let{rslError:t,status:s}=ee(n),o=te(e),a=F({requestUrl:r});return{action:"block",status:s,body:`Access to this resource requires a valid license token. Error: ${t} - ${e}`,headers:{"Content-Type":"text/plain; charset=UTF-8","WWW-Authenticate":`License error="${t}", error_description="${o}"`,Link:`<${a}>; rel="license"; type="application/rsl+xml"`}}}function re(){let n={method:"GET"};return globalThis?.fastly&&(n={...n,backend:y}),n}async function H(n,e){let r=`${n}/merchants/systems/${e}/license.xml`,t=await fetch(r,re());if(!t.ok)return new Response("License not found",{status:404});let s=await t.text();return new Response(s,{status:200,headers:new Headers({"Content-Type":"application/xml"})})}async function k(n){let e=await A({licenseToken:n.token,requestUrl:n.url,supertabBaseUrl:n.supertabBaseUrl,debug:n.debug}),r=q({apiKey:n.apiKey,merchantSystemUrn:n.merchantSystemUrn,baseUrl:n.supertabBaseUrl,eventName:e.valid?"license_used":e.reason,properties:{page_url:n.url,user_agent:n.userAgent,verification_status:e.valid?"valid":"invalid",verification_reason:e.valid?"success":e.reason},licenseId:e.licenseId,debug:n.debug});return n.ctx?.waitUntil&&n.ctx.waitUntil(r),e}async function K(n,e,r){let t=await n.handleRequest(e,r);if(t.action==="block")return new Response(t.body,{status:t.status,headers:new Headers(t.headers)});let s=await fetch(e);if(t.headers){let o=new Response(s.body,s);for(let[a,c]of Object.entries(t.headers))o.headers.set(a,c);return o}return s}async function V(n,e,r,t){if(t&&new URL(e.url).pathname==="/license.xml")return await H(t.baseUrl,t.merchantSystemUrn);let s=await n.handleRequest(e);if(s.action==="block")return new Response(s.body,{status:s.status,headers:new Headers(s.headers)});let o=await fetch(e,{backend:r});if(s.headers){let a=new Response(o.body,o);for(let[c,i]of Object.entries(s.headers))a.headers.set(c,i);return a}return o}async function $(n,e){let r=e.Records[0].cf.request,t=`https://${r.headers.host[0].value}${r.uri}${r.querystring?"?"+r.querystring:""}`,s=new Headers;Object.entries(r.headers).forEach(([c,i])=>{i.forEach(({value:l})=>s.append(c,l))});let o=new Request(t,{method:r.method,headers:s}),a=await n.handleRequest(o);if(a.action==="block"){let c={};return Object.entries(a.headers).forEach(([i,l])=>{c[i.toLowerCase()]=[{key:i,value:l}]}),{status:a.status.toString(),statusDescription:a.status===401?"Unauthorized":"Payment Required",headers:c,body:a.body}}return r}function ne(n){let e=n.headers.get("User-Agent")||"",r=n.headers.get("accept")||"",t=n.headers.get("sec-ch-ua"),s=n.headers.get("accept-language"),o=n.cf?.botManagement?.score,a=["chatgpt-user","perplexitybot","gptbot","anthropic-ai","ccbot","claude-web","claudebot","cohere-ai","youbot","diffbot","oai-searchbot","meta-externalagent","timpibot","amazonbot","bytespider","perplexity-user","googlebot","bot","curl","wget"],c=e.toLowerCase(),i=a.some(g=>c.includes(g)),l=c.includes("headless")||c.includes("puppeteer")||!t,d=!c.includes("headless")&&!c.includes("puppeteer")&&!t,p=!r||!s,m=typeof o=="number"&&o<30;return(c.includes("safari")||c.includes("mozilla"))&&l&&d?!1:i||l||p||m}var u=class u{constructor(e,r=!1){if(!r&&u._instance){if(!(e.apiKey===u._instance.apiKey&&e.merchantSystemUrn===u._instance.merchantSystemUrn))throw new Error("Cannot create a new instance with different configuration. Use resetInstance to clear the existing instance.");return u._instance}if(r&&u._instance&&u.resetInstance(),!e.apiKey||!e.merchantSystemUrn)throw new Error("Missing required configuration: apiKey and merchantSystemUrn are required");this.apiKey=e.apiKey,this.merchantSystemUrn=e.merchantSystemUrn,this.enforcement=e.enforcement??"soft",this.botDetector=e.botDetector,this.debug=e.debug??!1,u._instance=this}static resetInstance(){u._instance=null}static setBaseUrl(e){u.baseUrl=e}static getBaseUrl(){return u.baseUrl}static async verify(e){let r=e.baseUrl??u.baseUrl,t=await A({licenseToken:e.token,requestUrl:e.resourceUrl,supertabBaseUrl:r,debug:e.debug??!1});return t.valid?{valid:!0}:{valid:!1,error:t.error}}async verifyAndRecord(e){let r=await k({token:e.token,url:e.resourceUrl,userAgent:e.userAgent??"unknown",supertabBaseUrl:u.baseUrl,debug:e.debug??this.debug,apiKey:this.apiKey,merchantSystemUrn:this.merchantSystemUrn,ctx:e.ctx});return r.valid?{valid:!0}:{valid:!1,error:r.error}}async handleRequest(e,r){let t=e.headers.get("Authorization")||"",s=t.startsWith("License ")?t.slice(8):null,o=e.url,a=e.headers.get("User-Agent")||"unknown";if(s){if(this.enforcement==="disabled")return{action:"allow"};let i=await k({token:s,url:o,userAgent:a,supertabBaseUrl:u.baseUrl,debug:this.debug,apiKey:this.apiKey,merchantSystemUrn:this.merchantSystemUrn,ctx:r});return i.valid?{action:"allow"}:S({reason:i.reason,error:i.error,requestUrl:o})}if(!(this.botDetector?.(e,r)??!1))return{action:"allow"};switch(this.enforcement){case"strict":return S({reason:"missing_license_token",error:"Authorization header missing or malformed",requestUrl:o});case"soft":return O(o);default:return{action:"allow"}}}static async obtainLicenseToken(e){return P({clientId:e.clientId,clientSecret:e.clientSecret,resourceUrl:e.resourceUrl,debug:e.debug})}static async cloudflareHandleRequests(e,r,t,s){let o=new u({apiKey:r.MERCHANT_API_KEY,merchantSystemUrn:r.MERCHANT_SYSTEM_URN,botDetector:s?.botDetector,enforcement:s?.enforcement});return K(o,e,t)}static async fastlyHandleRequests(e,r,t,s,o){let{enableRSL:a=!1,botDetector:c,enforcement:i}=o??{},l=new u({apiKey:t,merchantSystemUrn:r,botDetector:c,enforcement:i});return V(l,e,s,a?{baseUrl:u.baseUrl,merchantSystemUrn:r}:void 0)}static async cloudfrontHandleRequests(e,r){let t=new u({apiKey:r.apiKey,merchantSystemUrn:r.merchantSystemUrn,botDetector:r.botDetector,enforcement:r.enforcement});return $(t,e)}};u.baseUrl="https://api-connect.supertab.co",u._instance=null;var B=u;export{T as EnforcementMode,E as HandlerAction,B as SupertabConnect,ne as defaultBotDetector};
|
|
2
2
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/types.ts","../src/jose.ts","../src/customer.ts","../src/jwks.ts","../src/events.ts","../src/license.ts","../src/cdn.ts","../src/bots.ts","../src/index.ts"],"sourcesContent":["export enum EnforcementMode {\n DISABLED = \"disabled\",\n SOFT = \"soft\",\n STRICT = \"strict\",\n}\n\nexport interface ExecutionContext {\n waitUntil(promise: Promise<any>): void;\n}\n\nexport type BotDetector = (request: Request, ctx?: ExecutionContext) => boolean;\n\nexport interface SupertabConnectConfig {\n apiKey: string;\n merchantSystemUrn: string;\n enforcement?: EnforcementMode;\n botDetector?: BotDetector;\n debug?: boolean;\n}\n\n/**\n * Defines the shape for environment variables (used in CloudFlare integration).\n * These are used to identify and authenticate the Merchant System with the Supertab Connect API.\n */\nexport interface Env {\n\t/** The unique identifier for the merchant system. */\n\tMERCHANT_SYSTEM_URN: string;\n\t/** The API key for authenticating with the Supertab Connect. */\n\tMERCHANT_API_KEY: string;\n\t[key: string]: string;\n}\n\nexport interface EventPayload {\n event_name: string;\n license_id?: string;\n merchant_system_urn: string;\n properties: Record<string, any>;\n}\n\nexport type LicenseTokenVerificationResult =\n | { valid: true; licenseId?: string; payload: any }\n | { valid: false; reason: LicenseTokenInvalidReason; error: string; licenseId?: string };\n\nexport enum LicenseTokenInvalidReason {\n MISSING_TOKEN = \"missing_license_token\",\n INVALID_HEADER = \"invalid_license_header\",\n INVALID_ALG = \"invalid_license_algorithm\",\n INVALID_PAYLOAD = \"invalid_license_payload\",\n INVALID_ISSUER = \"invalid_license_issuer\",\n SIGNATURE_VERIFICATION_FAILED = \"license_signature_verification_failed\",\n EXPIRED = \"license_token_expired\",\n INVALID_AUDIENCE = \"invalid_license_audience\",\n SERVER_ERROR = \"server_error\",\n}\n\nexport const FASTLY_BACKEND = \"stc-backend\";\n\nexport interface FetchOptions extends RequestInit {\n // Fastly-specific extension for backend routing\n backend?: string;\n}\n\nexport enum HandlerAction {\n ALLOW = \"allow\",\n BLOCK = \"block\",\n}\n\nexport type HandlerResult =\n | { action: HandlerAction.ALLOW; headers?: Record<string, string> }\n | { action: HandlerAction.BLOCK; status: number; body: string; headers: Record<string, string> };\n\n// CloudFront Lambda@Edge types\n// Uses permissive types to be compatible with aws-lambda package types\nexport interface CloudFrontHeaders {\n [key: string]: Array<{ key?: string; value: string }>;\n}\n\nexport interface CloudFrontResultResponse {\n status: string;\n statusDescription?: string;\n headers?: CloudFrontHeaders;\n bodyEncoding?: \"text\" | \"base64\";\n body?: string;\n}\n\n// CloudFrontRequestEvent uses a generic request type to accept aws-lambda's CloudFrontRequest\nexport interface CloudFrontRequestEvent<TRequest = Record<string, any>> {\n Records: Array<{\n cf: {\n config?: {\n distributionDomainName?: string;\n distributionId?: string;\n eventType?: string;\n requestId?: string;\n };\n request: TRequest & {\n uri: string;\n method: string;\n querystring: string;\n headers: CloudFrontHeaders;\n };\n };\n }>;\n}\n\n// Result can be either the original request (pass-through) or a response\n// Using generic to preserve the original request type for pass-through\nexport type CloudFrontRequestResult<TRequest = Record<string, any>> = TRequest | CloudFrontResultResponse;\n\nexport interface CloudfrontHandlerOptions {\n apiKey: string;\n merchantSystemUrn: string;\n botDetector?: BotDetector;\n enforcement?: EnforcementMode;\n}\n\nexport type RSLVerificationResult = {\n valid: boolean;\n error?: string;\n};\n","type JoseModule = typeof import(\"jose\");\n\nlet joseModulePromise: Promise<JoseModule> | null = null;\n\n/**\n * Lazily load the ESM-only `jose` package so the CommonJS build can call it via dynamic import.\n */\nexport function loadJose(): Promise<JoseModule> {\n if (!joseModulePromise) {\n joseModulePromise = import(\"jose\");\n }\n return joseModulePromise;\n}\n","import { loadJose } from \"./jose\";\n\ntype SupportedAlg = \"RS256\" | \"ES256\";\n\ntype GenerateLicenseTokenParams = {\n clientId: string;\n kid: string;\n privateKeyPem: string;\n tokenEndpoint: string;\n resourceUrl: string;\n licenseXml: string;\n debug?: boolean;\n};\n\ntype ObtainLicenseTokenParams = {\n clientId: string;\n clientSecret: string;\n resourceUrl: string;\n debug?: boolean;\n};\n\ntype ContentBlock = {\n urlPattern: string;\n licenseXml: string;\n server: string;\n};\n\nasync function retrieveLicenseToken(\n tokenEndpoint: string,\n requestOptions: RequestInit,\n debug: boolean | undefined\n) {\n try {\n const response = await fetch(tokenEndpoint, requestOptions);\n\n if (!response.ok) {\n const errorBody = await response.text().catch(() => \"\");\n const errorMessage = `Failed to obtain license token: ${\n response.status\n } ${response.statusText}${errorBody ? ` - ${errorBody}` : \"\"}`;\n throw new Error(errorMessage);\n }\n\n let data: any;\n try {\n data = await response.json();\n } catch (parseError) {\n if (debug) {\n console.error(\n \"Failed to parse license token response as JSON:\",\n parseError\n );\n }\n throw new Error(\"Failed to parse license token response as JSON\");\n }\n\n if (!data?.access_token) {\n throw new Error(\"License token response missing access_token\");\n }\n\n return data.access_token;\n } catch (error) {\n if (debug) {\n console.error(\"Error generating license token:\", error);\n }\n throw error;\n }\n}\n\nasync function importKeyForAlgs(\n privateKeyPem: string,\n debug: boolean | undefined\n): Promise<{ key: CryptoKey; alg: SupportedAlg }> {\n const { importPKCS8 } = await loadJose();\n const supportedAlgs: SupportedAlg[] = [\"ES256\", \"RS256\"];\n\n for (const algorithm of supportedAlgs) {\n try {\n const key = await importPKCS8(privateKeyPem, algorithm);\n return { key, alg: algorithm };\n } catch (importError) {\n if (debug) {\n console.debug(\n `Private key did not import using ${algorithm}, retrying...`,\n importError\n );\n }\n }\n }\n\n throw new Error(\n \"Unsupported private key format. Expected RSA or P-256 EC private key.\"\n );\n}\n\n// Temporarily not exporting this function to reflect only client credentials flow being supported\nasync function generateLicenseToken({\n clientId,\n kid,\n privateKeyPem,\n tokenEndpoint,\n resourceUrl,\n licenseXml,\n debug,\n}: GenerateLicenseTokenParams): Promise<string> {\n const { SignJWT } = await loadJose();\n const { key, alg } = await importKeyForAlgs(privateKeyPem, debug);\n const now = Math.floor(Date.now() / 1000);\n\n const clientAssertion = await new SignJWT({})\n .setProtectedHeader({ alg, kid })\n .setIssuer(clientId)\n .setSubject(clientId)\n .setIssuedAt(now)\n .setExpirationTime(now + 300)\n .setAudience(tokenEndpoint)\n .sign(key);\n\n const payload = new URLSearchParams({\n grant_type: \"rsl\",\n client_assertion_type:\n \"urn:ietf:params:oauth:client-assertion-type:jwt-bearer\",\n client_assertion: clientAssertion,\n license: licenseXml,\n resource: resourceUrl,\n });\n\n const requestOptions: RequestInit = {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/x-www-form-urlencoded\",\n Accept: \"application/json\",\n },\n body: payload.toString(),\n };\n\n return retrieveLicenseToken(tokenEndpoint, requestOptions, debug);\n}\n\nasync function fetchLicenseXml(\n resourceUrl: string,\n debug: boolean | undefined\n): Promise<string> {\n const origin = new URL(resourceUrl).origin;\n const licenseXmlUrl = `${origin}/license.xml`;\n\n const response = await fetch(licenseXmlUrl);\n if (!response.ok) {\n if (debug) {\n console.error(`Failed to fetch license.xml from ${licenseXmlUrl}: ${response.status}`);\n }\n throw new Error(\n `Failed to fetch license.xml from ${licenseXmlUrl}: ${response.status}`\n );\n }\n\n const xml = await response.text();\n if (debug) {\n console.debug(\"Fetched license.xml from\", licenseXmlUrl);\n }\n return xml;\n}\n\nfunction parseContentElements(xml: string, debug?: boolean): ContentBlock[] {\n const contentBlocks: ContentBlock[] = [];\n const contentRegex = /<content\\s([^>]*)>([\\s\\S]*?)<\\/content>/gi;\n const urlRegex = /url\\s*=\\s*\"([^\"]*)\"/i;\n const serverRegex = /server\\s*=\\s*\"([^\"]*)\"/i;\n const licenseRegex = /<license[^>]*>[\\s\\S]*?<\\/license>/i;\n\n let elementCount = 0;\n let match;\n while ((match = contentRegex.exec(xml)) !== null) {\n elementCount++;\n const attrs = match[1];\n const body = match[2];\n const urlMatch = attrs.match(urlRegex);\n const serverMatch = attrs.match(serverRegex);\n const licenseMatch = body.match(licenseRegex);\n\n if (urlMatch && serverMatch && licenseMatch) {\n contentBlocks.push({\n urlPattern: urlMatch[1],\n server: serverMatch[1],\n licenseXml: licenseMatch[0],\n });\n } else if (debug) {\n const missing = [\n !urlMatch && \"url\",\n !serverMatch && \"server\",\n !licenseMatch && \"<license>\",\n ].filter(Boolean).join(\", \");\n console.debug(`Skipping <content> element #${elementCount}: missing ${missing}`);\n }\n }\n\n if (debug) {\n console.debug(`Found ${elementCount} <content> element(s), ${contentBlocks.length} valid`);\n }\n\n return contentBlocks;\n}\n\nfunction findBestMatchingContent(\n contentBlocks: ContentBlock[],\n resourceUrl: string,\n debug?: boolean\n): ContentBlock | null {\n const parsed = new URL(resourceUrl);\n const host = parsed.host;\n const path = parsed.pathname;\n\n if (debug) {\n console.debug(`Matching resource URL: ${resourceUrl} (host=${host}, path=${path})`);\n }\n\n let bestMatch: ContentBlock | null = null;\n let bestSpecificity = -1;\n\n for (const block of contentBlocks) {\n let patternUrl: URL;\n try {\n patternUrl = new URL(block.urlPattern);\n } catch {\n if (debug) {\n console.debug(`Skipping block with invalid URL pattern: ${block.urlPattern}`);\n }\n continue;\n }\n\n if (patternUrl.host !== host) {\n if (debug) {\n console.debug(`Skipping block: host mismatch (pattern=${patternUrl.host}, resource=${host})`);\n }\n continue;\n }\n\n const patternPath = patternUrl.pathname;\n\n if (patternPath === path) {\n if (debug) {\n console.debug(`Exact match found: ${block.urlPattern}`);\n }\n return block;\n }\n\n if (patternPath.endsWith(\"/*\")) {\n const prefix = patternPath.slice(0, -1); // remove trailing *\n if (path.startsWith(prefix)) {\n const specificity = prefix.length;\n if (specificity > bestSpecificity) {\n bestSpecificity = specificity;\n bestMatch = block;\n }\n }\n }\n }\n\n if (debug) {\n if (bestMatch) {\n console.debug(`Wildcard match found: ${bestMatch.urlPattern} (specificity=${bestSpecificity})`);\n } else {\n console.debug(`No matching content block found for ${resourceUrl}`);\n }\n }\n\n return bestMatch;\n}\n\nexport { parseContentElements, findBestMatchingContent };\nexport type { ContentBlock };\n\nexport async function obtainLicenseToken({\n clientId,\n clientSecret,\n resourceUrl,\n debug,\n}: ObtainLicenseTokenParams): Promise<string> {\n const xml = await fetchLicenseXml(resourceUrl, debug);\n if (debug) {\n console.debug(`Fetched license.xml (${xml.length} chars)`);\n }\n const contentBlocks = parseContentElements(xml, debug);\n\n if (contentBlocks.length === 0) {\n if (debug) {\n console.error(\"No valid <content> elements with <license> found in license.xml\");\n }\n throw new Error(\n \"No valid <content> elements with <license> found in license.xml\"\n );\n }\n\n const matchedContent = findBestMatchingContent(contentBlocks, resourceUrl, debug);\n if (!matchedContent) {\n if (debug) {\n const patterns = contentBlocks.map(b => b.urlPattern).join(\", \");\n console.error(`No <content> element matches resource URL: ${resourceUrl}. Available patterns: ${patterns}`);\n }\n throw new Error(\n `No <content> element in license.xml matches resource URL: ${resourceUrl}`\n );\n }\n\n if (debug) {\n console.debug(\"Matched content block for resource URL:\", resourceUrl);\n console.debug(\"Using license XML:\", matchedContent.licenseXml);\n }\n\n const tokenEndpoint = matchedContent.server + '/token';\n if (debug) {\n console.debug(`Requesting license token from ${tokenEndpoint}`);\n }\n\n const payload = new URLSearchParams({\n grant_type: \"client_credentials\",\n license: matchedContent.licenseXml,\n resource: matchedContent.urlPattern,\n });\n\n const requestOptions: RequestInit = {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/x-www-form-urlencoded\",\n Accept: \"application/json\",\n Authorization: \"Basic \" + btoa(`${clientId}:${clientSecret}`),\n },\n body: payload.toString(),\n };\n\n return retrieveLicenseToken(tokenEndpoint, requestOptions, debug);\n}\n\nexport type { ObtainLicenseTokenParams };\n","import { FASTLY_BACKEND, FetchOptions } from \"./types\";\n\nconst jwksCache = new Map<string, any>();\n\ntype JwksCacheKey = string;\n\ntype FetchJwksParams = {\n cacheKey: JwksCacheKey;\n url: string;\n debug: boolean;\n failureMessage: string;\n logLabel: string;\n};\n\nfunction buildFetchOptions(): FetchOptions {\n let options: FetchOptions = { method: \"GET\" };\n // @ts-ignore - backend is a Fastly-specific extension\n if (globalThis?.fastly) {\n options = { ...options, backend: FASTLY_BACKEND };\n }\n return options;\n}\n\nasync function fetchAndCacheJwks({\n cacheKey,\n url,\n debug,\n failureMessage,\n logLabel,\n}: FetchJwksParams): Promise<any> {\n if (!jwksCache.has(cacheKey)) {\n try {\n const response = await fetch(url, buildFetchOptions());\n\n if (!response.ok) {\n throw new Error(`${failureMessage}: ${response.status}`);\n }\n\n const jwksData = await response.json();\n jwksCache.set(cacheKey, jwksData);\n } catch (error) {\n if (debug) {\n console.error(logLabel, error);\n }\n throw error;\n }\n }\n\n return jwksCache.get(cacheKey);\n}\n\nexport async function fetchPlatformJwks(\n baseUrl: string,\n debug: boolean\n): Promise<any> {\n const jwksUrl = `${baseUrl}/.well-known/jwks.json/platform`;\n if (debug) {\n console.debug(`Fetching platform JWKS from URL: ${jwksUrl}`);\n }\n\n return fetchAndCacheJwks({\n cacheKey: \"platform_jwks\",\n url: jwksUrl,\n debug,\n failureMessage: \"Failed to fetch platform JWKS\",\n logLabel: \"Error fetching platform JWKS:\",\n });\n}\n\nexport function clearJwksCache(): void {\n jwksCache.clear();\n}\n","import { EventPayload, FASTLY_BACKEND } from \"./types\";\n\nexport async function recordEvent({\n apiKey,\n merchantSystemUrn,\n baseUrl,\n eventName,\n properties,\n licenseId,\n debug = false,\n}: {\n apiKey: string;\n merchantSystemUrn: string;\n baseUrl: string;\n eventName: string;\n properties: Record<string, any>;\n licenseId?: string;\n debug?: boolean;\n}): Promise<void> {\n const payload: EventPayload = {\n event_name: eventName,\n merchant_system_urn: merchantSystemUrn,\n license_id: licenseId,\n properties,\n };\n\n try {\n let options: any = {\n method: \"POST\",\n headers: {\n Authorization: `Bearer ${apiKey}`,\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(payload),\n };\n // @ts-ignore\n if (globalThis?.fastly) {\n options = { ...options, backend: FASTLY_BACKEND };\n }\n const response = await fetch(`${baseUrl}/events`, options);\n\n if (!response.ok && debug) {\n console.error(`Failed to record event: ${response.status}`);\n }\n } catch (error) {\n if (debug) {\n console.error(\"Error recording event:\", error);\n }\n }\n}\n","import type { JWTPayload, JWTHeaderParameters } from \"jose\";\nimport { loadJose } from \"./jose\";\n\ninterface LicenseJWTPayload extends JWTPayload {\n license_id?: string;\n}\nimport {\n ExecutionContext,\n HandlerAction,\n HandlerResult,\n LicenseTokenInvalidReason,\n LicenseTokenVerificationResult,\n FASTLY_BACKEND,\n FetchOptions,\n} from \"./types\";\nimport { fetchPlatformJwks } from \"./jwks\";\nimport { recordEvent } from \"./events\";\n\nconst stripTrailingSlash = (value: string) => value.trim().replace(/\\/+$/, \"\");\n\nfunction reasonToErrorDescription(reason: LicenseTokenInvalidReason): string {\n switch (reason) {\n case LicenseTokenInvalidReason.MISSING_TOKEN:\n return \"Authorization header missing or malformed\";\n case LicenseTokenInvalidReason.INVALID_ALG:\n return \"Unsupported token algorithm\";\n case LicenseTokenInvalidReason.EXPIRED:\n return \"The license token has expired\";\n case LicenseTokenInvalidReason.SIGNATURE_VERIFICATION_FAILED:\n return \"The license token signature is invalid\";\n case LicenseTokenInvalidReason.INVALID_HEADER:\n return \"The license token header is malformed\";\n case LicenseTokenInvalidReason.INVALID_PAYLOAD:\n return \"The license token payload is malformed\";\n case LicenseTokenInvalidReason.INVALID_ISSUER:\n return \"The license token issuer is not recognized\";\n case LicenseTokenInvalidReason.INVALID_AUDIENCE:\n return \"The license does not grant access to this resource\";\n case LicenseTokenInvalidReason.SERVER_ERROR:\n return \"The server encountered an error validating the license\";\n default:\n return \"License token missing, expired, revoked, or malformed\";\n }\n}\n\nexport type VerifyLicenseTokenParams = {\n licenseToken: string;\n requestUrl: string;\n supertabBaseUrl: string;\n debug: boolean;\n};\n\nexport async function verifyLicenseToken({\n licenseToken,\n requestUrl,\n supertabBaseUrl,\n debug,\n}: VerifyLicenseTokenParams): Promise<LicenseTokenVerificationResult> {\n const { decodeProtectedHeader, decodeJwt, jwtVerify } = await loadJose();\n\n if (!licenseToken) {\n return {\n valid: false,\n reason: LicenseTokenInvalidReason.MISSING_TOKEN,\n error: reasonToErrorDescription(LicenseTokenInvalidReason.MISSING_TOKEN),\n };\n }\n\n let header: JWTHeaderParameters;\n try {\n header = decodeProtectedHeader(licenseToken) as JWTHeaderParameters;\n } catch (error) {\n if (debug) {\n console.error(\"Invalid license JWT header:\", error);\n }\n return {\n valid: false,\n reason: LicenseTokenInvalidReason.INVALID_HEADER,\n error: reasonToErrorDescription(LicenseTokenInvalidReason.INVALID_HEADER),\n };\n }\n\n if (header.alg !== \"ES256\") {\n if (debug) {\n console.error(\"Unsupported license JWT alg:\", header.alg);\n }\n return {\n valid: false,\n reason: LicenseTokenInvalidReason.INVALID_ALG,\n error: reasonToErrorDescription(LicenseTokenInvalidReason.INVALID_ALG),\n };\n }\n\n let payload: LicenseJWTPayload;\n try {\n payload = decodeJwt(licenseToken) as LicenseJWTPayload;\n } catch (error) {\n if (debug) {\n console.error(\"Invalid license JWT payload:\", error);\n }\n return {\n valid: false,\n reason: LicenseTokenInvalidReason.INVALID_PAYLOAD,\n error: reasonToErrorDescription(LicenseTokenInvalidReason.INVALID_PAYLOAD),\n };\n }\n\n const licenseId: string | undefined = payload.license_id;\n\n const issuer: string | undefined = payload.iss;\n const normalizedIssuer = issuer ? stripTrailingSlash(issuer) : undefined;\n const normalizedBaseUrl = stripTrailingSlash(supertabBaseUrl);\n\n if (!normalizedIssuer || !normalizedIssuer.startsWith(normalizedBaseUrl)) {\n if (debug) {\n console.error(\"License JWT issuer is missing or malformed:\", issuer);\n }\n return {\n valid: false,\n reason: LicenseTokenInvalidReason.INVALID_ISSUER,\n error: reasonToErrorDescription(LicenseTokenInvalidReason.INVALID_ISSUER),\n licenseId,\n };\n }\n\n const audienceValues = Array.isArray(payload.aud)\n ? payload.aud.filter((entry): entry is string => typeof entry === \"string\")\n : typeof payload.aud === \"string\"\n ? [payload.aud]\n : [];\n\n const requestUrlNormalized = stripTrailingSlash(requestUrl);\n const matchesRequestUrl = audienceValues.some((value) => {\n const normalizedAudience = stripTrailingSlash(value);\n if (!normalizedAudience) return false;\n return requestUrlNormalized.startsWith(normalizedAudience);\n });\n\n if (!matchesRequestUrl) {\n if (debug) {\n console.error(\n \"License JWT audience does not match request URL:\",\n payload.aud\n );\n }\n return {\n valid: false,\n reason: LicenseTokenInvalidReason.INVALID_AUDIENCE,\n error: reasonToErrorDescription(LicenseTokenInvalidReason.INVALID_AUDIENCE),\n licenseId,\n };\n }\n\n let jwks;\n try {\n jwks = await fetchPlatformJwks(supertabBaseUrl, debug);\n } catch (error) {\n if (debug) {\n console.error(\"Failed to fetch platform JWKS:\", error);\n }\n return {\n valid: false,\n reason: LicenseTokenInvalidReason.SERVER_ERROR,\n error: reasonToErrorDescription(LicenseTokenInvalidReason.SERVER_ERROR),\n licenseId,\n };\n }\n\n try {\n const getKey = async (jwtHeader: JWTHeaderParameters) => {\n const jwk = jwks.keys.find((key: any) => key.kid === jwtHeader.kid);\n if (!jwk) {\n throw new Error(`No matching platform key found: ${jwtHeader.kid}`);\n }\n return jwk;\n };\n\n const result = await jwtVerify(licenseToken, getKey, {\n issuer,\n algorithms: [header.alg],\n clockTolerance: \"1m\",\n });\n\n return {\n valid: true,\n licenseId,\n payload: result.payload,\n };\n } catch (error) {\n if (debug) {\n console.error(\"License JWT verification failed:\", error);\n }\n\n if (error instanceof Error && error.message?.includes(\"exp\")) {\n return {\n valid: false,\n reason: LicenseTokenInvalidReason.EXPIRED,\n error: reasonToErrorDescription(LicenseTokenInvalidReason.EXPIRED),\n licenseId,\n };\n }\n\n return {\n valid: false,\n reason: LicenseTokenInvalidReason.SIGNATURE_VERIFICATION_FAILED,\n error: reasonToErrorDescription(LicenseTokenInvalidReason.SIGNATURE_VERIFICATION_FAILED),\n licenseId,\n };\n }\n}\n\nexport function generateLicenseLink({\n requestUrl,\n}: {\n requestUrl: string;\n}): string {\n const baseURL = new URL(requestUrl);\n return `${baseURL.protocol}//${baseURL.host}/license.xml`;\n}\n\n/**\n * Build a HandlerResult that signals a missing token in soft enforcement mode.\n * Returns headers indicating a license is required without blocking the request.\n */\nexport function buildSignalResult(requestUrl: string): HandlerResult {\n const licenseLink = generateLicenseLink({ requestUrl });\n return {\n action: HandlerAction.ALLOW,\n headers: {\n Link: `<${licenseLink}>; rel=\"license\"; type=\"application/rsl+xml\"`,\n \"X-RSL-Status\": \"token_required\",\n \"X-RSL-Reason\": \"missing\",\n },\n };\n}\n\nfunction reasonToRslError(reason: LicenseTokenInvalidReason | string): { rslError: string; status: number } {\n switch (reason) {\n case LicenseTokenInvalidReason.MISSING_TOKEN:\n case LicenseTokenInvalidReason.INVALID_ALG:\n return { rslError: \"invalid_request\", status: 401 };\n case LicenseTokenInvalidReason.EXPIRED:\n case LicenseTokenInvalidReason.SIGNATURE_VERIFICATION_FAILED:\n case LicenseTokenInvalidReason.INVALID_HEADER:\n case LicenseTokenInvalidReason.INVALID_PAYLOAD:\n case LicenseTokenInvalidReason.INVALID_ISSUER:\n return { rslError: \"invalid_token\", status: 401 };\n case LicenseTokenInvalidReason.INVALID_AUDIENCE:\n return { rslError: \"insufficient_scope\", status: 403 };\n case LicenseTokenInvalidReason.SERVER_ERROR:\n return { rslError: \"server_error\", status: 503 };\n default:\n return { rslError: \"invalid_token\", status: 401 };\n }\n}\n\n/**\n * Sanitize a string for safe use in an HTTP header quoted-string (RFC 7230).\n * Strips CR/LF to prevent header injection and escapes backslashes and quotes.\n */\nfunction sanitizeHeaderValue(value: string): string {\n return value\n .replace(/[\\r\\n]/g, \"\")\n .replace(/\\\\/g, \"\\\\\\\\\")\n .replace(/\"/g, '\\\\\"');\n}\n\nexport function buildBlockResult({\n reason,\n error,\n requestUrl,\n}: {\n reason: LicenseTokenInvalidReason | string;\n error: string;\n requestUrl: string;\n}): HandlerResult {\n const { rslError, status } = reasonToRslError(reason);\n const errorDescription = sanitizeHeaderValue(error);\n const licenseLink = generateLicenseLink({ requestUrl });\n\n return {\n action: HandlerAction.BLOCK,\n status,\n body: `Access to this resource requires a valid license token. Error: ${rslError} - ${error}`,\n headers: {\n \"Content-Type\": \"text/plain; charset=UTF-8\",\n \"WWW-Authenticate\": `License error=\"${rslError}\", error_description=\"${errorDescription}\"`,\n Link: `<${licenseLink}>; rel=\"license\"; type=\"application/rsl+xml\"`,\n },\n };\n}\n\nfunction buildFetchOptions(): FetchOptions {\n let options: FetchOptions = { method: \"GET\" };\n // @ts-ignore - backend is a Fastly-specific extension\n if (globalThis?.fastly) {\n options = { ...options, backend: FASTLY_BACKEND };\n }\n return options;\n}\n\nexport async function hostRSLicenseXML(\n supertabBaseUrl: string,\n merchantSystemUrn: string\n): Promise<Response> {\n const licenseUrl = `${supertabBaseUrl}/merchants/systems/${merchantSystemUrn}/license.xml`;\n const response = await fetch(licenseUrl, buildFetchOptions());\n\n if (!response.ok) {\n return new Response(\"License not found\", { status: 404 });\n }\n\n const licenseXml = await response.text();\n\n return new Response(licenseXml, {\n status: 200,\n headers: new Headers({ \"Content-Type\": \"application/xml\" }),\n });\n}\n\nexport type VerifyAndRecordEventParams = {\n token: string;\n url: string;\n userAgent: string;\n supertabBaseUrl: string;\n debug: boolean;\n apiKey: string;\n merchantSystemUrn: string;\n ctx?: ExecutionContext;\n};\n\nexport async function verifyAndRecordEvent(\n params: VerifyAndRecordEventParams\n): Promise<LicenseTokenVerificationResult> {\n const verification = await verifyLicenseToken({\n licenseToken: params.token,\n requestUrl: params.url,\n supertabBaseUrl: params.supertabBaseUrl,\n debug: params.debug,\n });\n\n const eventPromise = recordEvent({\n apiKey: params.apiKey,\n merchantSystemUrn: params.merchantSystemUrn,\n baseUrl: params.supertabBaseUrl,\n eventName: verification.valid ? \"license_used\" : verification.reason,\n properties: {\n page_url: params.url,\n user_agent: params.userAgent,\n verification_status: verification.valid ? \"valid\" : \"invalid\",\n verification_reason: verification.valid ? \"success\" : verification.reason,\n },\n licenseId: verification.licenseId,\n debug: params.debug,\n });\n if (params.ctx?.waitUntil) {\n params.ctx.waitUntil(eventPromise);\n }\n\n return verification;\n}\n","import {\n HandlerAction,\n HandlerResult,\n ExecutionContext,\n CloudFrontHeaders,\n CloudFrontRequestEvent,\n CloudFrontRequestResult,\n} from \"./types\";\nimport { hostRSLicenseXML } from \"./license\";\n\n// Interface for what the CDN handlers need - avoids circular dependency\ninterface RequestHandler {\n handleRequest(request: Request, ctx?: ExecutionContext): Promise<HandlerResult>;\n}\n\nexport async function handleCloudflareRequest(\n handler: RequestHandler,\n request: Request,\n ctx: ExecutionContext\n): Promise<Response> {\n const result = await handler.handleRequest(request, ctx);\n\n if (result.action === HandlerAction.BLOCK) {\n return new Response(result.body, {\n status: result.status,\n headers: new Headers(result.headers),\n });\n }\n\n // action === HandlerAction.ALLOW\n const originResponse = await fetch(request);\n\n if (result.headers) {\n const response = new Response(originResponse.body, originResponse);\n for (const [key, value] of Object.entries(result.headers)) {\n response.headers.set(key, value);\n }\n return response;\n }\n\n return originResponse;\n}\n\nexport async function handleFastlyRequest(\n handler: RequestHandler,\n request: Request,\n originBackend: string,\n rslOptions?: {\n baseUrl: string;\n merchantSystemUrn: string;\n }\n): Promise<Response> {\n if (rslOptions && new URL(request.url).pathname === \"/license.xml\") {\n return await hostRSLicenseXML(\n rslOptions.baseUrl,\n rslOptions.merchantSystemUrn\n );\n }\n\n const result = await handler.handleRequest(request);\n\n if (result.action === HandlerAction.BLOCK) {\n return new Response(result.body, {\n status: result.status,\n headers: new Headers(result.headers),\n });\n }\n\n // action === HandlerAction.ALLOW\n const originResponse = await fetch(request, {\n backend: originBackend,\n } as RequestInit);\n\n if (result.headers) {\n const response = new Response(originResponse.body, originResponse);\n for (const [key, value] of Object.entries(result.headers)) {\n response.headers.set(key, value);\n }\n return response;\n }\n\n return originResponse;\n}\n\nexport async function handleCloudfrontRequest<TRequest extends Record<string, any>>(\n handler: RequestHandler,\n event: CloudFrontRequestEvent<TRequest>\n): Promise<CloudFrontRequestResult<TRequest>> {\n const cfRequest = event.Records[0].cf.request;\n\n // Convert CloudFront request to Web API Request\n const url = `https://${cfRequest.headers.host[0].value}${cfRequest.uri}${cfRequest.querystring ? \"?\" + cfRequest.querystring : \"\"}`;\n\n const headers = new Headers();\n Object.entries(cfRequest.headers).forEach(([key, values]) => {\n values.forEach(({ value }) => headers.append(key, value));\n });\n\n const webRequest = new Request(url, {\n method: cfRequest.method,\n headers: headers,\n });\n\n const result = await handler.handleRequest(webRequest);\n\n if (result.action === HandlerAction.BLOCK) {\n const responseHeaders: CloudFrontHeaders = {};\n Object.entries(result.headers).forEach(([key, value]) => {\n responseHeaders[key.toLowerCase()] = [{ key, value }];\n });\n\n return {\n status: result.status.toString(),\n statusDescription:\n result.status === 401 ? \"Unauthorized\" : \"Payment Required\",\n headers: responseHeaders,\n body: result.body,\n };\n }\n\n // Allow request to continue to origin\n return cfRequest;\n}\n","/**\n * Default bot detection logic using multiple signals.\n * Checks User-Agent patterns, headless browser indicators, missing headers, and Cloudflare bot scores.\n * @param request The incoming request to analyze\n * @returns true if the request appears to be from a bot, false otherwise\n */\nexport function defaultBotDetector(request: Request): boolean {\n const userAgent = request.headers.get(\"User-Agent\") || \"\";\n const accept = request.headers.get(\"accept\") || \"\";\n const secChUa = request.headers.get(\"sec-ch-ua\");\n const acceptLanguage = request.headers.get(\"accept-language\");\n const botScore = (request as any).cf?.botManagement?.score;\n\n const botList = [\n \"chatgpt-user\",\n \"perplexitybot\",\n \"gptbot\",\n \"anthropic-ai\",\n \"ccbot\",\n \"claude-web\",\n \"claudebot\",\n \"cohere-ai\",\n \"youbot\",\n \"diffbot\",\n \"oai-searchbot\",\n \"meta-externalagent\",\n \"timpibot\",\n \"amazonbot\",\n \"bytespider\",\n \"perplexity-user\",\n \"googlebot\",\n \"bot\",\n \"curl\",\n \"wget\",\n ];\n // 1. Basic substring check from known list\n const lowerCaseUserAgent = userAgent.toLowerCase();\n const botUaMatch = botList.some((bot) => lowerCaseUserAgent.includes(bot));\n\n // 2. Headless browser detection\n const headlessIndicators =\n lowerCaseUserAgent.includes(\"headless\") ||\n lowerCaseUserAgent.includes(\"puppeteer\") ||\n !secChUa;\n\n const isBrowserMissingSecChUa =\n !lowerCaseUserAgent.includes(\"headless\") &&\n !lowerCaseUserAgent.includes(\"puppeteer\") &&\n !secChUa;\n\n // 3. Suspicious header gaps — many bots omit these\n const missingHeaders = !accept || !acceptLanguage;\n\n // 4. Cloudflare bot score check (if available)\n const lowBotScore = typeof botScore === \"number\" && botScore < 30;\n\n // Safari and Mozilla special case\n if (\n lowerCaseUserAgent.includes(\"safari\") ||\n lowerCaseUserAgent.includes(\"mozilla\")\n ) {\n // Safari is not a bot, but it may be headless\n if (headlessIndicators && isBrowserMissingSecChUa) {\n return false; // Likely not a bot, but missing a Sec-CH-UA header\n }\n }\n\n // Final decision\n return botUaMatch || headlessIndicators || missingHeaders || lowBotScore;\n}\n","import {\n SupertabConnectConfig,\n EnforcementMode,\n BotDetector,\n HandlerAction,\n HandlerResult,\n LicenseTokenInvalidReason,\n RSLVerificationResult,\n ExecutionContext,\n Env,\n} from \"./types\";\nimport { obtainLicenseToken as obtainLicenseTokenHelper } from \"./customer\";\nimport {\n buildBlockResult,\n buildSignalResult,\n verifyLicenseToken as verifyLicenseTokenHelper,\n verifyAndRecordEvent,\n} from \"./license\";\nimport {\n handleCloudflareRequest,\n handleFastlyRequest,\n handleCloudfrontRequest,\n} from \"./cdn\";\nimport {\n CloudFrontRequestEvent,\n CloudFrontRequestResult,\n CloudfrontHandlerOptions,\n} from \"./types\";\n\nexport { EnforcementMode, HandlerAction };\nexport type {\n RSLVerificationResult,\n ExecutionContext,\n Env,\n BotDetector,\n HandlerResult,\n CloudFrontRequestEvent,\n CloudFrontRequestResult,\n CloudfrontHandlerOptions,\n};\nexport { defaultBotDetector } from \"./bots\";\n\n/**\n * SupertabConnect class provides higher level methods\n * for using Supertab Connect within supported CDN integrations\n * as well as more specialized methods to customarily verify JWT tokens and record events.\n */\nexport class SupertabConnect {\n private apiKey?: string;\n private static baseUrl: string = \"https://api-connect.supertab.co\";\n private merchantSystemUrn!: string;\n private enforcement!: EnforcementMode;\n private botDetector?: BotDetector;\n private debug!: boolean;\n\n private static _instance: SupertabConnect | null = null;\n\n /**\n * Create a new SupertabConnect instance (singleton).\n * Returns the existing instance if one exists with the same config.\n * @param config SDK configuration including apiKey and merchantSystemUrn\n * @param reset Pass true to replace an existing instance with different config\n * @throws If an instance with different config already exists and reset is false\n */\n public constructor(config: SupertabConnectConfig, reset: boolean = false) {\n if (!reset && SupertabConnect._instance) {\n // If reset was not requested and an instance conflicts with the provided config, throw an error\n if (\n !(\n config.apiKey === SupertabConnect._instance.apiKey &&\n config.merchantSystemUrn ===\n SupertabConnect._instance.merchantSystemUrn\n )\n ) {\n throw new Error(\n \"Cannot create a new instance with different configuration. Use resetInstance to clear the existing instance.\"\n );\n }\n\n // If an instance already exists and reset is not requested, just return the existing instance\n return SupertabConnect._instance;\n }\n if (reset && SupertabConnect._instance) {\n // ...and if reset is requested and required, clear the existing instance first\n SupertabConnect.resetInstance();\n }\n\n if (!config.apiKey || !config.merchantSystemUrn) {\n throw new Error(\n \"Missing required configuration: apiKey and merchantSystemUrn are required\"\n );\n }\n this.apiKey = config.apiKey;\n this.merchantSystemUrn = config.merchantSystemUrn;\n this.enforcement = config.enforcement ?? EnforcementMode.SOFT;\n this.botDetector = config.botDetector;\n this.debug = config.debug ?? false;\n\n // Register this as the singleton instance\n SupertabConnect._instance = this;\n }\n\n /**\n * Clear the singleton instance, allowing a new one to be created with different config.\n */\n public static resetInstance(): void {\n SupertabConnect._instance = null;\n }\n\n /**\n * Override the default base URL for API requests (intended for local development/testing).\n */\n public static setBaseUrl(url: string): void {\n SupertabConnect.baseUrl = url;\n }\n\n /**\n * Get the current base URL for API requests.\n */\n public static getBaseUrl(): string {\n return SupertabConnect.baseUrl;\n }\n\n /**\n * Pure token verification — verifies a license token without recording any events.\n * @param options.token The license token to verify\n * @param options.resourceUrl The URL of the resource being accessed\n * @param options.baseUrl Optional override for the Supertab Connect API base URL\n * @param options.debug Enable debug logging (default: false)\n * @returns A promise that resolves with the verification result\n */\n static async verify(options: {\n token: string;\n resourceUrl: string;\n baseUrl?: string;\n debug?: boolean;\n }): Promise<RSLVerificationResult> {\n const baseUrl = options.baseUrl ?? SupertabConnect.baseUrl;\n\n const result = await verifyLicenseTokenHelper({\n licenseToken: options.token,\n requestUrl: options.resourceUrl,\n supertabBaseUrl: baseUrl,\n debug: options.debug ?? false,\n });\n\n if (result.valid) {\n return { valid: true };\n }\n\n return { valid: false, error: result.error };\n }\n\n /**\n * Verify a license token and record an analytics event.\n * Uses the instance's apiKey and merchantSystemUrn for event recording.\n * @param options.token The license token to verify\n * @param options.resourceUrl The URL of the resource being accessed\n * @param options.userAgent Optional user agent string for event recording\n * @param options.debug Enable debug logging (default: false)\n * @param options.ctx Optional execution context with waitUntil for non-blocking event recording\n * @returns A promise that resolves with the verification result\n */\n async verifyAndRecord(options: {\n token: string;\n resourceUrl: string;\n userAgent?: string;\n debug?: boolean;\n ctx?: ExecutionContext;\n }): Promise<RSLVerificationResult> {\n const result = await verifyAndRecordEvent({\n token: options.token,\n url: options.resourceUrl,\n userAgent: options.userAgent ?? \"unknown\",\n supertabBaseUrl: SupertabConnect.baseUrl,\n debug: options.debug ?? this.debug,\n apiKey: this.apiKey!,\n merchantSystemUrn: this.merchantSystemUrn,\n ctx: options.ctx,\n });\n\n if (result.valid) {\n return { valid: true };\n }\n\n return { valid: false, error: result.error };\n }\n\n /**\n * Handle an incoming request by extracting the license token, verifying it, and recording an analytics event.\n * When no token is present, bot detection and enforcement mode determine the response.\n * @param request The incoming HTTP request\n * @param ctx Execution context for non-blocking event recording.\n * Pass this from your platform (e.g. Cloudflare Workers)\n * @returns A promise that resolves with the handler result indicating ALLOW or BLOCK request\n */\n async handleRequest(request: Request, ctx?: ExecutionContext): Promise<HandlerResult> {\n const auth = request.headers.get(\"Authorization\") || \"\";\n const token = auth.startsWith(\"License \") ? auth.slice(8) : null;\n const url = request.url;\n const userAgent = request.headers.get(\"User-Agent\") || \"unknown\";\n\n // Token present → ALWAYS validate, regardless of mode or bot detection\n if (token) {\n if (this.enforcement === EnforcementMode.DISABLED) {\n return { action: HandlerAction.ALLOW };\n }\n const verification = await verifyAndRecordEvent({\n token,\n url,\n userAgent,\n supertabBaseUrl: SupertabConnect.baseUrl,\n debug: this.debug,\n apiKey: this.apiKey!,\n merchantSystemUrn: this.merchantSystemUrn,\n ctx,\n });\n if (!verification.valid) {\n return buildBlockResult({\n reason: verification.reason,\n error: verification.error,\n requestUrl: url,\n });\n }\n return { action: HandlerAction.ALLOW };\n }\n\n // No token from here on\n const isBot = this.botDetector?.(request, ctx) ?? false;\n\n if (!isBot) {\n return { action: HandlerAction.ALLOW };\n }\n\n // Bot detected, no token — enforcement mode decides\n switch (this.enforcement) {\n case EnforcementMode.STRICT:\n return buildBlockResult({\n reason: LicenseTokenInvalidReason.MISSING_TOKEN,\n error: \"Authorization header missing or malformed\",\n requestUrl: url,\n });\n case EnforcementMode.SOFT:\n return buildSignalResult(url);\n default: // DISABLED\n return { action: HandlerAction.ALLOW };\n }\n }\n\n /**\n * Request a license token from the Supertab Connect token endpoint.\n * @param options.clientId OAuth client identifier.\n * @param options.clientSecret OAuth client secret for client_credentials flow.\n * @param options.resourceUrl Resource URL attempting to access with a License.\n * @param options.debug Enable debug logging (default: false).\n * @returns Promise resolving to the issued license access token string.\n */\n static async obtainLicenseToken(options: {\n clientId: string;\n clientSecret: string;\n resourceUrl: string;\n debug?: boolean;\n }): Promise<string> {\n return obtainLicenseTokenHelper({\n clientId: options.clientId,\n clientSecret: options.clientSecret,\n resourceUrl: options.resourceUrl,\n debug: options.debug,\n });\n }\n\n /**\n * Handle incoming requests for Cloudflare Workers.\n * Pass this directly as your Worker's fetch handler.\n * @param request The incoming Worker request\n * @param env Worker environment bindings containing MERCHANT_API_KEY and MERCHANT_SYSTEM_URN\n * @param ctx Worker execution context for non-blocking event recording\n */\n static async cloudflareHandleRequests(\n request: Request,\n env: Env,\n ctx: ExecutionContext\n ): Promise<Response> {\n const instance = new SupertabConnect({\n apiKey: env.MERCHANT_API_KEY,\n merchantSystemUrn: env.MERCHANT_SYSTEM_URN,\n });\n return handleCloudflareRequest(instance, request, ctx);\n }\n\n /**\n * Handle incoming requests for Fastly Compute.\n * @param request The incoming Fastly request\n * @param merchantSystemUrn The merchant system URN for identification\n * @param merchantApiKey The merchant API key for authentication\n * @param originBackend The Fastly backend name to forward allowed requests to\n * @param options.enableRSL Serve license.xml at /license.xml for RSL-compliant clients (default: false)\n * @param options.botDetector Custom bot detection function\n * @param options.enforcement Enforcement mode (default: SOFT)\n */\n static async fastlyHandleRequests(\n request: Request,\n merchantSystemUrn: string,\n merchantApiKey: string,\n originBackend: string,\n options?: {\n enableRSL?: boolean;\n botDetector?: BotDetector;\n enforcement?: EnforcementMode;\n }\n ): Promise<Response> {\n const { enableRSL = false, botDetector, enforcement } = options ?? {};\n\n const instance = new SupertabConnect({\n apiKey: merchantApiKey,\n merchantSystemUrn: merchantSystemUrn,\n botDetector,\n enforcement,\n });\n\n return handleFastlyRequest(\n instance,\n request,\n originBackend,\n enableRSL\n ? {\n baseUrl: SupertabConnect.baseUrl,\n merchantSystemUrn,\n }\n : undefined\n );\n }\n\n /**\n * Handle incoming requests for AWS CloudFront Lambda@Edge.\n * Use as the handler for a viewer-request LambdaEdge function.\n * @param event The CloudFront viewer-request event\n * @param options Configuration including apiKey, merchantSystemUrn, and optional botDetector/enforcement\n */\n static async cloudfrontHandleRequests<TRequest extends Record<string, any>>(\n event: CloudFrontRequestEvent<TRequest>,\n options: CloudfrontHandlerOptions\n ): Promise<CloudFrontRequestResult<TRequest>> {\n const instance = new SupertabConnect({\n apiKey: options.apiKey,\n merchantSystemUrn: options.merchantSystemUrn,\n botDetector: options.botDetector,\n enforcement: options.enforcement,\n });\n return handleCloudfrontRequest(instance, event);\n }\n}\n"],"mappings":"AAAO,IAAKA,OACVA,EAAA,SAAW,WACXA,EAAA,KAAO,OACPA,EAAA,OAAS,SAHCA,OAAA,IAuDL,IAAMC,EAAiB,cAOlBC,OACVA,EAAA,MAAQ,QACRA,EAAA,MAAQ,QAFEA,OAAA,IC5DZ,IAAIC,EAAgD,KAK7C,SAASC,GAAgC,CAC9C,OAAKD,IACHA,EAAoB,OAAO,MAAM,GAE5BA,CACT,CCeA,eAAeE,EACXC,EACAC,EACAC,EACF,CACA,GAAI,CACF,IAAMC,EAAW,MAAM,MAAMH,EAAeC,CAAc,EAE1D,GAAI,CAACE,EAAS,GAAI,CAChB,IAAMC,EAAY,MAAMD,EAAS,KAAK,EAAE,MAAM,IAAM,EAAE,EAChDE,EAAe,mCACnBF,EAAS,MACX,IAAIA,EAAS,UAAU,GAAGC,EAAY,MAAMA,CAAS,GAAK,EAAE,GAC5D,MAAM,IAAI,MAAMC,CAAY,CAC9B,CAEA,IAAIC,EACJ,GAAI,CACFA,EAAO,MAAMH,EAAS,KAAK,CAC7B,OAASI,EAAY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AaA,EAAQ,YACrB,MAAOA,EAAQ,KACjB,CAAC,CACH,CASA,aAAa,yBACXK,EACAS,EACAR,EACmB,CACnB,IAAMS,EAAW,IAAInB,EAAgB,CACnC,OAAQkB,EAAI,iBACZ,kBAAmBA,EAAI,mBACzB,CAAC,EACD,OAAOE,EAAwBD,EAAUV,EAASC,CAAG,CACvD,CAYA,aAAa,qBACXD,EACAY,EACAC,EACAC,EACAnB,EAKmB,CACnB,GAAM,CAAE,UAAAoB,EAAY,GAAO,YAAAC,EAAa,YAAAC,CAAY,EAAItB,GAAW,CAAC,EAE9De,EAAW,IAAInB,EAAgB,CACnC,OAAQsB,EACR,kBAAmBD,EACnB,YAAAI,EACA,YAAAC,CACF,CAAC,EAED,OAAOC,EACLR,EACAV,EACAc,EACAC,EACI,CACE,QAASxB,EAAgB,QACzB,kBAAAqB,CACF,EACA,MACN,CACF,CAQA,aAAa,yBACXO,EACAxB,EAC4C,CAC5C,IAAMe,EAAW,IAAInB,EAAgB,CACnC,OAAQI,EAAQ,OAChB,kBAAmBA,EAAQ,kBAC3B,YAAaA,EAAQ,YACrB,YAAaA,EAAQ,WACvB,CAAC,EACD,OAAOyB,EAAwBV,EAAUS,CAAK,CAChD,CACF,EAhTa5B,EAEI,QAAkB,kCAFtBA,EAQI,UAAoC,KAR9C,IAAM8B,EAAN9B","names":["EnforcementMode","FASTLY_BACKEND","HandlerAction","joseModulePromise","loadJose","retrieveLicenseToken","tokenEndpoint","requestOptions","debug","response","errorBody","errorMessage","data","parseError","error","fetchLicenseXml","resourceUrl","debug","licenseXmlUrl","response","xml","parseContentElements","contentBlocks","contentRegex","urlRegex","serverRegex","licenseRegex","elementCount","match","attrs","body","urlMatch","serverMatch","licenseMatch","missing","findBestMatchingContent","parsed","host","path","bestMatch","bestSpecificity","block","patternUrl","patternPath","prefix","specificity","obtainLicenseToken","clientId","clientSecret","resourceUrl","debug","xml","fetchLicenseXml","contentBlocks","parseContentElements","matchedContent","findBestMatchingContent","patterns","b","tokenEndpoint","payload","requestOptions","retrieveLicenseToken","jwksCache","buildFetchOptions","options","FASTLY_BACKEND","fetchAndCacheJwks","cacheKey","url","debug","failureMessage","logLabel","response","jwksData","error","fetchPlatformJwks","baseUrl","jwksUrl","recordEvent","apiKey","merchantSystemUrn","baseUrl","eventName","properties","licenseId","debug","payload","options","FASTLY_BACKEND","response","error","stripTrailingSlash","value","reasonToErrorDescription","reason","verifyLicenseToken","licenseToken","requestUrl","supertabBaseUrl","debug","decodeProtectedHeader","decodeJwt","jwtVerify","loadJose","header","error","payload","licenseId","issuer","normalizedIssuer","normalizedBaseUrl","audienceValues","entry","requestUrlNormalized","normalizedAudience","jwks","fetchPlatformJwks","result","jwtHeader","jwk","key","generateLicenseLink","baseURL","buildSignalResult","licenseLink","reasonToRslError","sanitizeHeaderValue","buildBlockResult","rslError","status","errorDescription","buildFetchOptions","options","FASTLY_BACKEND","hostRSLicenseXML","merchantSystemUrn","licenseUrl","response","licenseXml","verifyAndRecordEvent","params","verification","eventPromise","recordEvent","handleCloudflareRequest","handler","request","ctx","result","originResponse","response","key","value","handleFastlyRequest","originBackend","rslOptions","hostRSLicenseXML","handleCloudfrontRequest","event","cfRequest","url","headers","values","webRequest","responseHeaders","defaultBotDetector","request","userAgent","accept","secChUa","acceptLanguage","botScore","botList","lowerCaseUserAgent","botUaMatch","bot","headlessIndicators","isBrowserMissingSecChUa","missingHeaders","lowBotScore","_SupertabConnect","config","reset","url","options","baseUrl","result","verifyLicenseToken","verifyAndRecordEvent","request","ctx","auth","token","userAgent","verification","buildBlockResult","buildSignalResult","obtainLicenseToken","env","instance","handleCloudflareRequest","merchantSystemUrn","merchantApiKey","originBackend","enableRSL","botDetector","enforcement","handleFastlyRequest","event","handleCloudfrontRequest","SupertabConnect"]}
|
|
1
|
+
{"version":3,"sources":["../src/types.ts","../src/jose.ts","../src/customer.ts","../src/jwks.ts","../src/events.ts","../src/license.ts","../src/cdn.ts","../src/bots.ts","../src/index.ts"],"sourcesContent":["export enum EnforcementMode {\n DISABLED = \"disabled\",\n SOFT = \"soft\",\n STRICT = \"strict\",\n}\n\nexport interface ExecutionContext {\n waitUntil(promise: Promise<any>): void;\n}\n\nexport type BotDetector = (request: Request, ctx?: ExecutionContext) => boolean;\n\nexport interface SupertabConnectConfig {\n apiKey: string;\n merchantSystemUrn: string;\n enforcement?: EnforcementMode;\n botDetector?: BotDetector;\n debug?: boolean;\n}\n\n/**\n * Defines the shape for environment variables (used in CloudFlare integration).\n * These are used to identify and authenticate the Merchant System with the Supertab Connect API.\n */\nexport interface Env {\n\t/** The unique identifier for the merchant system. */\n\tMERCHANT_SYSTEM_URN: string;\n\t/** The API key for authenticating with the Supertab Connect. */\n\tMERCHANT_API_KEY: string;\n\t[key: string]: string;\n}\n\nexport interface EventPayload {\n event_name: string;\n license_id?: string;\n merchant_system_urn: string;\n properties: Record<string, any>;\n}\n\nexport type LicenseTokenVerificationResult =\n | { valid: true; licenseId?: string; payload: any }\n | { valid: false; reason: LicenseTokenInvalidReason; error: string; licenseId?: string };\n\nexport enum LicenseTokenInvalidReason {\n MISSING_TOKEN = \"missing_license_token\",\n INVALID_HEADER = \"invalid_license_header\",\n INVALID_ALG = \"invalid_license_algorithm\",\n INVALID_PAYLOAD = \"invalid_license_payload\",\n INVALID_ISSUER = \"invalid_license_issuer\",\n SIGNATURE_VERIFICATION_FAILED = \"license_signature_verification_failed\",\n EXPIRED = \"license_token_expired\",\n INVALID_AUDIENCE = \"invalid_license_audience\",\n SERVER_ERROR = \"server_error\",\n}\n\nexport const FASTLY_BACKEND = \"stc-backend\";\n\nexport interface FetchOptions extends RequestInit {\n // Fastly-specific extension for backend routing\n backend?: string;\n}\n\nexport enum HandlerAction {\n ALLOW = \"allow\",\n BLOCK = \"block\",\n}\n\nexport type HandlerResult =\n | { action: HandlerAction.ALLOW; headers?: Record<string, string> }\n | { action: HandlerAction.BLOCK; status: number; body: string; headers: Record<string, string> };\n\n// CloudFront Lambda@Edge types\n// Uses permissive types to be compatible with aws-lambda package types\nexport interface CloudFrontHeaders {\n [key: string]: Array<{ key?: string; value: string }>;\n}\n\nexport interface CloudFrontResultResponse {\n status: string;\n statusDescription?: string;\n headers?: CloudFrontHeaders;\n bodyEncoding?: \"text\" | \"base64\";\n body?: string;\n}\n\n// CloudFrontRequestEvent uses a generic request type to accept aws-lambda's CloudFrontRequest\nexport interface CloudFrontRequestEvent<TRequest = Record<string, any>> {\n Records: Array<{\n cf: {\n config?: {\n distributionDomainName?: string;\n distributionId?: string;\n eventType?: string;\n requestId?: string;\n };\n request: TRequest & {\n uri: string;\n method: string;\n querystring: string;\n headers: CloudFrontHeaders;\n };\n };\n }>;\n}\n\n// Result can be either the original request (pass-through) or a response\n// Using generic to preserve the original request type for pass-through\nexport type CloudFrontRequestResult<TRequest = Record<string, any>> = TRequest | CloudFrontResultResponse;\n\nexport interface CloudfrontHandlerOptions {\n apiKey: string;\n merchantSystemUrn: string;\n botDetector?: BotDetector;\n enforcement?: EnforcementMode;\n}\n\nexport type RSLVerificationResult = {\n valid: boolean;\n error?: string;\n};\n","// Per-subpath lazy loaders for jose — each caches its own promise to avoid redundant imports.\n\nfunction lazyImport<T>(load: () => Promise<T>): () => Promise<T> {\n let cached: Promise<T> | null = null;\n return () => {\n if (!cached) {\n cached = load();\n }\n return cached;\n };\n}\n\nexport const loadJwtVerify = lazyImport(() => import(\"jose/jwt/verify\"));\nexport const loadDecodeJwt = lazyImport(() => import(\"jose/jwt/decode\"));\nexport const loadDecodeProtectedHeader = lazyImport(() => import(\"jose/decode/protected_header\"));\nexport const loadKeyImport = lazyImport(() => import(\"jose/key/import\"));\nexport const loadJwtSign = lazyImport(() => import(\"jose/jwt/sign\"));\n","import { loadKeyImport, loadJwtSign } from \"./jose\";\n\ntype SupportedAlg = \"RS256\" | \"ES256\";\n\ntype GenerateLicenseTokenParams = {\n clientId: string;\n kid: string;\n privateKeyPem: string;\n tokenEndpoint: string;\n resourceUrl: string;\n licenseXml: string;\n debug?: boolean;\n};\n\ntype ObtainLicenseTokenParams = {\n clientId: string;\n clientSecret: string;\n resourceUrl: string;\n debug?: boolean;\n};\n\ntype ContentBlock = {\n urlPattern: string;\n licenseXml: string;\n server: string;\n};\n\nasync function retrieveLicenseToken(\n tokenEndpoint: string,\n requestOptions: RequestInit,\n debug: boolean | undefined\n) {\n try {\n const response = await fetch(tokenEndpoint, requestOptions);\n\n if (!response.ok) {\n const errorBody = await response.text().catch(() => \"\");\n const errorMessage = `Failed to obtain license token: ${\n response.status\n } ${response.statusText}${errorBody ? ` - ${errorBody}` : \"\"}`;\n throw new Error(errorMessage);\n }\n\n let data: any;\n try {\n data = await response.json();\n } catch (parseError) {\n if (debug) {\n console.error(\n \"Failed to parse license token response as JSON:\",\n parseError\n );\n }\n throw new Error(\"Failed to parse license token response as JSON\");\n }\n\n if (!data?.access_token) {\n throw new Error(\"License token response missing access_token\");\n }\n\n return data.access_token;\n } catch (error) {\n if (debug) {\n console.error(\"Error generating license token:\", error);\n }\n throw error;\n }\n}\n\nasync function importKeyForAlgs(\n privateKeyPem: string,\n debug: boolean | undefined\n): Promise<{ key: CryptoKey; alg: SupportedAlg }> {\n const { importPKCS8 } = await loadKeyImport();\n const supportedAlgs: SupportedAlg[] = [\"ES256\", \"RS256\"];\n\n for (const algorithm of supportedAlgs) {\n try {\n const key = await importPKCS8(privateKeyPem, algorithm);\n return { key, alg: algorithm };\n } catch (importError) {\n if (debug) {\n console.debug(\n `Private key did not import using ${algorithm}, retrying...`,\n importError\n );\n }\n }\n }\n\n throw new Error(\n \"Unsupported private key format. Expected RSA or P-256 EC private key.\"\n );\n}\n\n// Temporarily not exporting this function to reflect only client credentials flow being supported\nasync function generateLicenseToken({\n clientId,\n kid,\n privateKeyPem,\n tokenEndpoint,\n resourceUrl,\n licenseXml,\n debug,\n}: GenerateLicenseTokenParams): Promise<string> {\n const { SignJWT } = await loadJwtSign();\n const { key, alg } = await importKeyForAlgs(privateKeyPem, debug);\n const now = Math.floor(Date.now() / 1000);\n\n const clientAssertion = await new SignJWT({})\n .setProtectedHeader({ alg, kid })\n .setIssuer(clientId)\n .setSubject(clientId)\n .setIssuedAt(now)\n .setExpirationTime(now + 300)\n .setAudience(tokenEndpoint)\n .sign(key);\n\n const payload = new URLSearchParams({\n grant_type: \"rsl\",\n client_assertion_type:\n \"urn:ietf:params:oauth:client-assertion-type:jwt-bearer\",\n client_assertion: clientAssertion,\n license: licenseXml,\n resource: resourceUrl,\n });\n\n const requestOptions: RequestInit = {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/x-www-form-urlencoded\",\n Accept: \"application/json\",\n },\n body: payload.toString(),\n };\n\n return retrieveLicenseToken(tokenEndpoint, requestOptions, debug);\n}\n\nasync function fetchLicenseXml(\n resourceUrl: string,\n debug: boolean | undefined\n): Promise<string> {\n const origin = new URL(resourceUrl).origin;\n const licenseXmlUrl = `${origin}/license.xml`;\n\n const response = await fetch(licenseXmlUrl);\n if (!response.ok) {\n if (debug) {\n console.error(`Failed to fetch license.xml from ${licenseXmlUrl}: ${response.status}`);\n }\n throw new Error(\n `Failed to fetch license.xml from ${licenseXmlUrl}: ${response.status}`\n );\n }\n\n const xml = await response.text();\n if (debug) {\n console.debug(\"Fetched license.xml from\", licenseXmlUrl);\n }\n return xml;\n}\n\nfunction parseContentElements(xml: string, debug?: boolean): ContentBlock[] {\n const contentBlocks: ContentBlock[] = [];\n const contentRegex = /<content\\s([^>]*)>([\\s\\S]*?)<\\/content>/gi;\n const urlRegex = /url\\s*=\\s*\"([^\"]*)\"/i;\n const serverRegex = /server\\s*=\\s*\"([^\"]*)\"/i;\n const licenseRegex = /<license[^>]*>[\\s\\S]*?<\\/license>/i;\n\n let elementCount = 0;\n let match;\n while ((match = contentRegex.exec(xml)) !== null) {\n elementCount++;\n const attrs = match[1];\n const body = match[2];\n const urlMatch = attrs.match(urlRegex);\n const serverMatch = attrs.match(serverRegex);\n const licenseMatch = body.match(licenseRegex);\n\n if (urlMatch && serverMatch && licenseMatch) {\n contentBlocks.push({\n urlPattern: urlMatch[1],\n server: serverMatch[1],\n licenseXml: licenseMatch[0],\n });\n } else if (debug) {\n const missing = [\n !urlMatch && \"url\",\n !serverMatch && \"server\",\n !licenseMatch && \"<license>\",\n ].filter(Boolean).join(\", \");\n console.debug(`Skipping <content> element #${elementCount}: missing ${missing}`);\n }\n }\n\n if (debug) {\n console.debug(`Found ${elementCount} <content> element(s), ${contentBlocks.length} valid`);\n }\n\n return contentBlocks;\n}\n\nfunction findBestMatchingContent(\n contentBlocks: ContentBlock[],\n resourceUrl: string,\n debug?: boolean\n): ContentBlock | null {\n const parsed = new URL(resourceUrl);\n const host = parsed.host;\n const path = parsed.pathname;\n\n if (debug) {\n console.debug(`Matching resource URL: ${resourceUrl} (host=${host}, path=${path})`);\n }\n\n let bestMatch: ContentBlock | null = null;\n let bestSpecificity = -1;\n\n for (const block of contentBlocks) {\n let patternUrl: URL;\n try {\n patternUrl = new URL(block.urlPattern);\n } catch {\n if (debug) {\n console.debug(`Skipping block with invalid URL pattern: ${block.urlPattern}`);\n }\n continue;\n }\n\n if (patternUrl.host !== host) {\n if (debug) {\n console.debug(`Skipping block: host mismatch (pattern=${patternUrl.host}, resource=${host})`);\n }\n continue;\n }\n\n const patternPath = patternUrl.pathname;\n\n if (patternPath === path) {\n if (debug) {\n console.debug(`Exact match found: ${block.urlPattern}`);\n }\n return block;\n }\n\n if (patternPath.endsWith(\"/*\")) {\n const prefix = patternPath.slice(0, -1); // remove trailing *\n if (path.startsWith(prefix)) {\n const specificity = prefix.length;\n if (specificity > bestSpecificity) {\n bestSpecificity = specificity;\n bestMatch = block;\n }\n }\n }\n }\n\n if (debug) {\n if (bestMatch) {\n console.debug(`Wildcard match found: ${bestMatch.urlPattern} (specificity=${bestSpecificity})`);\n } else {\n console.debug(`No matching content block found for ${resourceUrl}`);\n }\n }\n\n return bestMatch;\n}\n\nexport { parseContentElements, findBestMatchingContent };\nexport type { ContentBlock };\n\nexport async function obtainLicenseToken({\n clientId,\n clientSecret,\n resourceUrl,\n debug,\n}: ObtainLicenseTokenParams): Promise<string> {\n const xml = await fetchLicenseXml(resourceUrl, debug);\n if (debug) {\n console.debug(`Fetched license.xml (${xml.length} chars)`);\n }\n const contentBlocks = parseContentElements(xml, debug);\n\n if (contentBlocks.length === 0) {\n if (debug) {\n console.error(\"No valid <content> elements with <license> found in license.xml\");\n }\n throw new Error(\n \"No valid <content> elements with <license> found in license.xml\"\n );\n }\n\n const matchedContent = findBestMatchingContent(contentBlocks, resourceUrl, debug);\n if (!matchedContent) {\n if (debug) {\n const patterns = contentBlocks.map(b => b.urlPattern).join(\", \");\n console.error(`No <content> element matches resource URL: ${resourceUrl}. Available patterns: ${patterns}`);\n }\n throw new Error(\n `No <content> element in license.xml matches resource URL: ${resourceUrl}`\n );\n }\n\n if (debug) {\n console.debug(\"Matched content block for resource URL:\", resourceUrl);\n console.debug(\"Using license XML:\", matchedContent.licenseXml);\n }\n\n const tokenEndpoint = matchedContent.server + '/token';\n if (debug) {\n console.debug(`Requesting license token from ${tokenEndpoint}`);\n }\n\n const payload = new URLSearchParams({\n grant_type: \"client_credentials\",\n license: matchedContent.licenseXml,\n resource: matchedContent.urlPattern,\n });\n\n const requestOptions: RequestInit = {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/x-www-form-urlencoded\",\n Accept: \"application/json\",\n Authorization: \"Basic \" + btoa(`${clientId}:${clientSecret}`),\n },\n body: payload.toString(),\n };\n\n return retrieveLicenseToken(tokenEndpoint, requestOptions, debug);\n}\n\nexport type { ObtainLicenseTokenParams };\n","import { FASTLY_BACKEND, FetchOptions } from \"./types\";\n\nconst jwksCache = new Map<string, any>();\n\ntype JwksCacheKey = string;\n\ntype FetchJwksParams = {\n cacheKey: JwksCacheKey;\n url: string;\n debug: boolean;\n failureMessage: string;\n logLabel: string;\n};\n\nfunction buildFetchOptions(): FetchOptions {\n let options: FetchOptions = { method: \"GET\" };\n // @ts-ignore - backend is a Fastly-specific extension\n if (globalThis?.fastly) {\n options = { ...options, backend: FASTLY_BACKEND };\n }\n return options;\n}\n\nasync function fetchAndCacheJwks({\n cacheKey,\n url,\n debug,\n failureMessage,\n logLabel,\n}: FetchJwksParams): Promise<any> {\n if (!jwksCache.has(cacheKey)) {\n try {\n const response = await fetch(url, buildFetchOptions());\n\n if (!response.ok) {\n throw new Error(`${failureMessage}: ${response.status}`);\n }\n\n const jwksData = await response.json();\n jwksCache.set(cacheKey, jwksData);\n } catch (error) {\n if (debug) {\n console.error(logLabel, error);\n }\n throw error;\n }\n }\n\n return jwksCache.get(cacheKey);\n}\n\nexport async function fetchPlatformJwks(\n baseUrl: string,\n debug: boolean\n): Promise<any> {\n const jwksUrl = `${baseUrl}/.well-known/jwks.json/platform`;\n if (debug) {\n console.debug(`Fetching platform JWKS from URL: ${jwksUrl}`);\n }\n\n return fetchAndCacheJwks({\n cacheKey: \"platform_jwks\",\n url: jwksUrl,\n debug,\n failureMessage: \"Failed to fetch platform JWKS\",\n logLabel: \"Error fetching platform JWKS:\",\n });\n}\n\nexport function clearJwksCache(): void {\n jwksCache.clear();\n}\n","import { EventPayload, FASTLY_BACKEND } from \"./types\";\n\nexport async function recordEvent({\n apiKey,\n merchantSystemUrn,\n baseUrl,\n eventName,\n properties,\n licenseId,\n debug = false,\n}: {\n apiKey: string;\n merchantSystemUrn: string;\n baseUrl: string;\n eventName: string;\n properties: Record<string, any>;\n licenseId?: string;\n debug?: boolean;\n}): Promise<void> {\n const payload: EventPayload = {\n event_name: eventName,\n merchant_system_urn: merchantSystemUrn,\n license_id: licenseId,\n properties,\n };\n\n try {\n let options: any = {\n method: \"POST\",\n headers: {\n Authorization: `Bearer ${apiKey}`,\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(payload),\n };\n // @ts-ignore\n if (globalThis?.fastly) {\n options = { ...options, backend: FASTLY_BACKEND };\n }\n const response = await fetch(`${baseUrl}/events`, options);\n\n if (!response.ok && debug) {\n console.error(`Failed to record event: ${response.status}`);\n }\n } catch (error) {\n if (debug) {\n console.error(\"Error recording event:\", error);\n }\n }\n}\n","import type { JWTPayload, JWTHeaderParameters } from \"jose\";\nimport { loadJwtVerify, loadDecodeJwt, loadDecodeProtectedHeader } from \"./jose\";\n\ninterface LicenseJWTPayload extends JWTPayload {\n license_id?: string;\n}\nimport {\n ExecutionContext,\n HandlerAction,\n HandlerResult,\n LicenseTokenInvalidReason,\n LicenseTokenVerificationResult,\n FASTLY_BACKEND,\n FetchOptions,\n} from \"./types\";\nimport { fetchPlatformJwks } from \"./jwks\";\nimport { recordEvent } from \"./events\";\n\nconst stripTrailingSlash = (value: string) => value.trim().replace(/\\/+$/, \"\");\n\nfunction reasonToErrorDescription(reason: LicenseTokenInvalidReason): string {\n switch (reason) {\n case LicenseTokenInvalidReason.MISSING_TOKEN:\n return \"Authorization header missing or malformed\";\n case LicenseTokenInvalidReason.INVALID_ALG:\n return \"Unsupported token algorithm\";\n case LicenseTokenInvalidReason.EXPIRED:\n return \"The license token has expired\";\n case LicenseTokenInvalidReason.SIGNATURE_VERIFICATION_FAILED:\n return \"The license token signature is invalid\";\n case LicenseTokenInvalidReason.INVALID_HEADER:\n return \"The license token header is malformed\";\n case LicenseTokenInvalidReason.INVALID_PAYLOAD:\n return \"The license token payload is malformed\";\n case LicenseTokenInvalidReason.INVALID_ISSUER:\n return \"The license token issuer is not recognized\";\n case LicenseTokenInvalidReason.INVALID_AUDIENCE:\n return \"The license does not grant access to this resource\";\n case LicenseTokenInvalidReason.SERVER_ERROR:\n return \"The server encountered an error validating the license\";\n default:\n return \"License token missing, expired, revoked, or malformed\";\n }\n}\n\nexport type VerifyLicenseTokenParams = {\n licenseToken: string;\n requestUrl: string;\n supertabBaseUrl: string;\n debug: boolean;\n};\n\nexport async function verifyLicenseToken({\n licenseToken,\n requestUrl,\n supertabBaseUrl,\n debug,\n}: VerifyLicenseTokenParams): Promise<LicenseTokenVerificationResult> {\n const { decodeProtectedHeader } = await loadDecodeProtectedHeader();\n const { decodeJwt } = await loadDecodeJwt();\n const { jwtVerify } = await loadJwtVerify();\n\n if (!licenseToken) {\n return {\n valid: false,\n reason: LicenseTokenInvalidReason.MISSING_TOKEN,\n error: reasonToErrorDescription(LicenseTokenInvalidReason.MISSING_TOKEN),\n };\n }\n\n let header: JWTHeaderParameters;\n try {\n header = decodeProtectedHeader(licenseToken) as JWTHeaderParameters;\n } catch (error) {\n if (debug) {\n console.error(\"Invalid license JWT header:\", error);\n }\n return {\n valid: false,\n reason: LicenseTokenInvalidReason.INVALID_HEADER,\n error: reasonToErrorDescription(LicenseTokenInvalidReason.INVALID_HEADER),\n };\n }\n\n if (header.alg !== \"ES256\") {\n if (debug) {\n console.error(\"Unsupported license JWT alg:\", header.alg);\n }\n return {\n valid: false,\n reason: LicenseTokenInvalidReason.INVALID_ALG,\n error: reasonToErrorDescription(LicenseTokenInvalidReason.INVALID_ALG),\n };\n }\n\n let payload: LicenseJWTPayload;\n try {\n payload = decodeJwt(licenseToken) as LicenseJWTPayload;\n } catch (error) {\n if (debug) {\n console.error(\"Invalid license JWT payload:\", error);\n }\n return {\n valid: false,\n reason: LicenseTokenInvalidReason.INVALID_PAYLOAD,\n error: reasonToErrorDescription(LicenseTokenInvalidReason.INVALID_PAYLOAD),\n };\n }\n\n const licenseId: string | undefined = payload.license_id;\n\n const issuer: string | undefined = payload.iss;\n const normalizedIssuer = issuer ? stripTrailingSlash(issuer) : undefined;\n const normalizedBaseUrl = stripTrailingSlash(supertabBaseUrl);\n\n if (!normalizedIssuer || !normalizedIssuer.startsWith(normalizedBaseUrl)) {\n if (debug) {\n console.error(\"License JWT issuer is missing or malformed:\", issuer);\n }\n return {\n valid: false,\n reason: LicenseTokenInvalidReason.INVALID_ISSUER,\n error: reasonToErrorDescription(LicenseTokenInvalidReason.INVALID_ISSUER),\n licenseId,\n };\n }\n\n const audienceValues = Array.isArray(payload.aud)\n ? payload.aud.filter((entry): entry is string => typeof entry === \"string\")\n : typeof payload.aud === \"string\"\n ? [payload.aud]\n : [];\n\n const requestUrlNormalized = stripTrailingSlash(requestUrl);\n const matchesRequestUrl = audienceValues.some((value) => {\n const normalizedAudience = stripTrailingSlash(value);\n if (!normalizedAudience) return false;\n return requestUrlNormalized.startsWith(normalizedAudience);\n });\n\n if (!matchesRequestUrl) {\n if (debug) {\n console.error(\n \"License JWT audience does not match request URL:\",\n payload.aud\n );\n }\n return {\n valid: false,\n reason: LicenseTokenInvalidReason.INVALID_AUDIENCE,\n error: reasonToErrorDescription(LicenseTokenInvalidReason.INVALID_AUDIENCE),\n licenseId,\n };\n }\n\n let jwks;\n try {\n jwks = await fetchPlatformJwks(supertabBaseUrl, debug);\n } catch (error) {\n if (debug) {\n console.error(\"Failed to fetch platform JWKS:\", error);\n }\n return {\n valid: false,\n reason: LicenseTokenInvalidReason.SERVER_ERROR,\n error: reasonToErrorDescription(LicenseTokenInvalidReason.SERVER_ERROR),\n licenseId,\n };\n }\n\n try {\n const getKey = async (jwtHeader: JWTHeaderParameters) => {\n const jwk = jwks.keys.find((key: any) => key.kid === jwtHeader.kid);\n if (!jwk) {\n throw new Error(`No matching platform key found: ${jwtHeader.kid}`);\n }\n return jwk;\n };\n\n const result = await jwtVerify(licenseToken, getKey, {\n issuer,\n algorithms: [header.alg],\n clockTolerance: \"1m\",\n });\n\n return {\n valid: true,\n licenseId,\n payload: result.payload,\n };\n } catch (error) {\n if (debug) {\n console.error(\"License JWT verification failed:\", error);\n }\n\n if (error instanceof Error && error.message?.includes(\"exp\")) {\n return {\n valid: false,\n reason: LicenseTokenInvalidReason.EXPIRED,\n error: reasonToErrorDescription(LicenseTokenInvalidReason.EXPIRED),\n licenseId,\n };\n }\n\n return {\n valid: false,\n reason: LicenseTokenInvalidReason.SIGNATURE_VERIFICATION_FAILED,\n error: reasonToErrorDescription(LicenseTokenInvalidReason.SIGNATURE_VERIFICATION_FAILED),\n licenseId,\n };\n }\n}\n\nexport function generateLicenseLink({\n requestUrl,\n}: {\n requestUrl: string;\n}): string {\n const baseURL = new URL(requestUrl);\n return `${baseURL.protocol}//${baseURL.host}/license.xml`;\n}\n\n/**\n * Build a HandlerResult that signals a missing token in soft enforcement mode.\n * Returns headers indicating a license is required without blocking the request.\n */\nexport function buildSignalResult(requestUrl: string): HandlerResult {\n const licenseLink = generateLicenseLink({ requestUrl });\n return {\n action: HandlerAction.ALLOW,\n headers: {\n Link: `<${licenseLink}>; rel=\"license\"; type=\"application/rsl+xml\"`,\n \"X-RSL-Status\": \"token_required\",\n \"X-RSL-Reason\": \"missing\",\n },\n };\n}\n\nfunction reasonToRslError(reason: LicenseTokenInvalidReason | string): { rslError: string; status: number } {\n switch (reason) {\n case LicenseTokenInvalidReason.MISSING_TOKEN:\n case LicenseTokenInvalidReason.INVALID_ALG:\n return { rslError: \"invalid_request\", status: 401 };\n case LicenseTokenInvalidReason.EXPIRED:\n case LicenseTokenInvalidReason.SIGNATURE_VERIFICATION_FAILED:\n case LicenseTokenInvalidReason.INVALID_HEADER:\n case LicenseTokenInvalidReason.INVALID_PAYLOAD:\n case LicenseTokenInvalidReason.INVALID_ISSUER:\n return { rslError: \"invalid_token\", status: 401 };\n case LicenseTokenInvalidReason.INVALID_AUDIENCE:\n return { rslError: \"insufficient_scope\", status: 403 };\n case LicenseTokenInvalidReason.SERVER_ERROR:\n return { rslError: \"server_error\", status: 503 };\n default:\n return { rslError: \"invalid_token\", status: 401 };\n }\n}\n\n/**\n * Sanitize a string for safe use in an HTTP header quoted-string (RFC 7230).\n * Strips CR/LF to prevent header injection and escapes backslashes and quotes.\n */\nfunction sanitizeHeaderValue(value: string): string {\n return value\n .replace(/[\\r\\n]/g, \"\")\n .replace(/\\\\/g, \"\\\\\\\\\")\n .replace(/\"/g, '\\\\\"');\n}\n\nexport function buildBlockResult({\n reason,\n error,\n requestUrl,\n}: {\n reason: LicenseTokenInvalidReason | string;\n error: string;\n requestUrl: string;\n}): HandlerResult {\n const { rslError, status } = reasonToRslError(reason);\n const errorDescription = sanitizeHeaderValue(error);\n const licenseLink = generateLicenseLink({ requestUrl });\n\n return {\n action: HandlerAction.BLOCK,\n status,\n body: `Access to this resource requires a valid license token. Error: ${rslError} - ${error}`,\n headers: {\n \"Content-Type\": \"text/plain; charset=UTF-8\",\n \"WWW-Authenticate\": `License error=\"${rslError}\", error_description=\"${errorDescription}\"`,\n Link: `<${licenseLink}>; rel=\"license\"; type=\"application/rsl+xml\"`,\n },\n };\n}\n\nfunction buildFetchOptions(): FetchOptions {\n let options: FetchOptions = { method: \"GET\" };\n // @ts-ignore - backend is a Fastly-specific extension\n if (globalThis?.fastly) {\n options = { ...options, backend: FASTLY_BACKEND };\n }\n return options;\n}\n\nexport async function hostRSLicenseXML(\n supertabBaseUrl: string,\n merchantSystemUrn: string\n): Promise<Response> {\n const licenseUrl = `${supertabBaseUrl}/merchants/systems/${merchantSystemUrn}/license.xml`;\n const response = await fetch(licenseUrl, buildFetchOptions());\n\n if (!response.ok) {\n return new Response(\"License not found\", { status: 404 });\n }\n\n const licenseXml = await response.text();\n\n return new Response(licenseXml, {\n status: 200,\n headers: new Headers({ \"Content-Type\": \"application/xml\" }),\n });\n}\n\nexport type VerifyAndRecordEventParams = {\n token: string;\n url: string;\n userAgent: string;\n supertabBaseUrl: string;\n debug: boolean;\n apiKey: string;\n merchantSystemUrn: string;\n ctx?: ExecutionContext;\n};\n\nexport async function verifyAndRecordEvent(\n params: VerifyAndRecordEventParams\n): Promise<LicenseTokenVerificationResult> {\n const verification = await verifyLicenseToken({\n licenseToken: params.token,\n requestUrl: params.url,\n supertabBaseUrl: params.supertabBaseUrl,\n debug: params.debug,\n });\n\n const eventPromise = recordEvent({\n apiKey: params.apiKey,\n merchantSystemUrn: params.merchantSystemUrn,\n baseUrl: params.supertabBaseUrl,\n eventName: verification.valid ? \"license_used\" : verification.reason,\n properties: {\n page_url: params.url,\n user_agent: params.userAgent,\n verification_status: verification.valid ? \"valid\" : \"invalid\",\n verification_reason: verification.valid ? \"success\" : verification.reason,\n },\n licenseId: verification.licenseId,\n debug: params.debug,\n });\n if (params.ctx?.waitUntil) {\n params.ctx.waitUntil(eventPromise);\n }\n\n return verification;\n}\n","import {\n HandlerAction,\n HandlerResult,\n ExecutionContext,\n CloudFrontHeaders,\n CloudFrontRequestEvent,\n CloudFrontRequestResult,\n} from \"./types\";\nimport { hostRSLicenseXML } from \"./license\";\n\n// Interface for what the CDN handlers need - avoids circular dependency\ninterface RequestHandler {\n handleRequest(request: Request, ctx?: ExecutionContext): Promise<HandlerResult>;\n}\n\nexport async function handleCloudflareRequest(\n handler: RequestHandler,\n request: Request,\n ctx: ExecutionContext\n): Promise<Response> {\n const result = await handler.handleRequest(request, ctx);\n\n if (result.action === HandlerAction.BLOCK) {\n return new Response(result.body, {\n status: result.status,\n headers: new Headers(result.headers),\n });\n }\n\n // action === HandlerAction.ALLOW\n const originResponse = await fetch(request);\n\n if (result.headers) {\n const response = new Response(originResponse.body, originResponse);\n for (const [key, value] of Object.entries(result.headers)) {\n response.headers.set(key, value);\n }\n return response;\n }\n\n return originResponse;\n}\n\nexport async function handleFastlyRequest(\n handler: RequestHandler,\n request: Request,\n originBackend: string,\n rslOptions?: {\n baseUrl: string;\n merchantSystemUrn: string;\n }\n): Promise<Response> {\n if (rslOptions && new URL(request.url).pathname === \"/license.xml\") {\n return await hostRSLicenseXML(\n rslOptions.baseUrl,\n rslOptions.merchantSystemUrn\n );\n }\n\n const result = await handler.handleRequest(request);\n\n if (result.action === HandlerAction.BLOCK) {\n return new Response(result.body, {\n status: result.status,\n headers: new Headers(result.headers),\n });\n }\n\n // action === HandlerAction.ALLOW\n const originResponse = await fetch(request, {\n backend: originBackend,\n } as RequestInit);\n\n if (result.headers) {\n const response = new Response(originResponse.body, originResponse);\n for (const [key, value] of Object.entries(result.headers)) {\n response.headers.set(key, value);\n }\n return response;\n }\n\n return originResponse;\n}\n\nexport async function handleCloudfrontRequest<TRequest extends Record<string, any>>(\n handler: RequestHandler,\n event: CloudFrontRequestEvent<TRequest>\n): Promise<CloudFrontRequestResult<TRequest>> {\n const cfRequest = event.Records[0].cf.request;\n\n // Convert CloudFront request to Web API Request\n const url = `https://${cfRequest.headers.host[0].value}${cfRequest.uri}${cfRequest.querystring ? \"?\" + cfRequest.querystring : \"\"}`;\n\n const headers = new Headers();\n Object.entries(cfRequest.headers).forEach(([key, values]) => {\n values.forEach(({ value }) => headers.append(key, value));\n });\n\n const webRequest = new Request(url, {\n method: cfRequest.method,\n headers: headers,\n });\n\n const result = await handler.handleRequest(webRequest);\n\n if (result.action === HandlerAction.BLOCK) {\n const responseHeaders: CloudFrontHeaders = {};\n Object.entries(result.headers).forEach(([key, value]) => {\n responseHeaders[key.toLowerCase()] = [{ key, value }];\n });\n\n return {\n status: result.status.toString(),\n statusDescription:\n result.status === 401 ? \"Unauthorized\" : \"Payment Required\",\n headers: responseHeaders,\n body: result.body,\n };\n }\n\n // Allow request to continue to origin\n return cfRequest;\n}\n","/**\n * Default bot detection logic using multiple signals.\n * Checks User-Agent patterns, headless browser indicators, missing headers, and Cloudflare bot scores.\n * @param request The incoming request to analyze\n * @returns true if the request appears to be from a bot, false otherwise\n */\nexport function defaultBotDetector(request: Request): boolean {\n const userAgent = request.headers.get(\"User-Agent\") || \"\";\n const accept = request.headers.get(\"accept\") || \"\";\n const secChUa = request.headers.get(\"sec-ch-ua\");\n const acceptLanguage = request.headers.get(\"accept-language\");\n const botScore = (request as any).cf?.botManagement?.score;\n\n const botList = [\n \"chatgpt-user\",\n \"perplexitybot\",\n \"gptbot\",\n \"anthropic-ai\",\n \"ccbot\",\n \"claude-web\",\n \"claudebot\",\n \"cohere-ai\",\n \"youbot\",\n \"diffbot\",\n \"oai-searchbot\",\n \"meta-externalagent\",\n \"timpibot\",\n \"amazonbot\",\n \"bytespider\",\n \"perplexity-user\",\n \"googlebot\",\n \"bot\",\n \"curl\",\n \"wget\",\n ];\n // 1. Basic substring check from known list\n const lowerCaseUserAgent = userAgent.toLowerCase();\n const botUaMatch = botList.some((bot) => lowerCaseUserAgent.includes(bot));\n\n // 2. Headless browser detection\n const headlessIndicators =\n lowerCaseUserAgent.includes(\"headless\") ||\n lowerCaseUserAgent.includes(\"puppeteer\") ||\n !secChUa;\n\n const isBrowserMissingSecChUa =\n !lowerCaseUserAgent.includes(\"headless\") &&\n !lowerCaseUserAgent.includes(\"puppeteer\") &&\n !secChUa;\n\n // 3. Suspicious header gaps — many bots omit these\n const missingHeaders = !accept || !acceptLanguage;\n\n // 4. Cloudflare bot score check (if available)\n const lowBotScore = typeof botScore === \"number\" && botScore < 30;\n\n // Safari and Mozilla special case\n if (\n lowerCaseUserAgent.includes(\"safari\") ||\n lowerCaseUserAgent.includes(\"mozilla\")\n ) {\n // Safari is not a bot, but it may be headless\n if (headlessIndicators && isBrowserMissingSecChUa) {\n return false; // Likely not a bot, but missing a Sec-CH-UA header\n }\n }\n\n // Final decision\n return botUaMatch || headlessIndicators || missingHeaders || lowBotScore;\n}\n","import {\n SupertabConnectConfig,\n EnforcementMode,\n BotDetector,\n HandlerAction,\n HandlerResult,\n LicenseTokenInvalidReason,\n RSLVerificationResult,\n ExecutionContext,\n Env,\n} from \"./types\";\nimport { obtainLicenseToken as obtainLicenseTokenHelper } from \"./customer\";\nimport {\n buildBlockResult,\n buildSignalResult,\n verifyLicenseToken as verifyLicenseTokenHelper,\n verifyAndRecordEvent,\n} from \"./license\";\nimport {\n handleCloudflareRequest,\n handleFastlyRequest,\n handleCloudfrontRequest,\n} from \"./cdn\";\nimport {\n CloudFrontRequestEvent,\n CloudFrontRequestResult,\n CloudfrontHandlerOptions,\n} from \"./types\";\n\nexport { EnforcementMode, HandlerAction };\nexport type {\n RSLVerificationResult,\n ExecutionContext,\n Env,\n BotDetector,\n HandlerResult,\n CloudFrontRequestEvent,\n CloudFrontRequestResult,\n CloudfrontHandlerOptions,\n};\nexport { defaultBotDetector } from \"./bots\";\n\n/**\n * SupertabConnect class provides higher level methods\n * for using Supertab Connect within supported CDN integrations\n * as well as more specialized methods to customarily verify JWT tokens and record events.\n */\nexport class SupertabConnect {\n private apiKey?: string;\n private static baseUrl: string = \"https://api-connect.supertab.co\";\n private merchantSystemUrn!: string;\n private enforcement!: EnforcementMode;\n private botDetector?: BotDetector;\n private debug!: boolean;\n\n private static _instance: SupertabConnect | null = null;\n\n /**\n * Create a new SupertabConnect instance (singleton).\n * Returns the existing instance if one exists with the same config.\n * @param config SDK configuration including apiKey and merchantSystemUrn\n * @param reset Pass true to replace an existing instance with different config\n * @throws If an instance with different config already exists and reset is false\n */\n public constructor(config: SupertabConnectConfig, reset: boolean = false) {\n if (!reset && SupertabConnect._instance) {\n // If reset was not requested and an instance conflicts with the provided config, throw an error\n if (\n !(\n config.apiKey === SupertabConnect._instance.apiKey &&\n config.merchantSystemUrn ===\n SupertabConnect._instance.merchantSystemUrn\n )\n ) {\n throw new Error(\n \"Cannot create a new instance with different configuration. Use resetInstance to clear the existing instance.\"\n );\n }\n\n // If an instance already exists and reset is not requested, just return the existing instance\n return SupertabConnect._instance;\n }\n if (reset && SupertabConnect._instance) {\n // ...and if reset is requested and required, clear the existing instance first\n SupertabConnect.resetInstance();\n }\n\n if (!config.apiKey || !config.merchantSystemUrn) {\n throw new Error(\n \"Missing required configuration: apiKey and merchantSystemUrn are required\"\n );\n }\n this.apiKey = config.apiKey;\n this.merchantSystemUrn = config.merchantSystemUrn;\n this.enforcement = config.enforcement ?? EnforcementMode.SOFT;\n this.botDetector = config.botDetector;\n this.debug = config.debug ?? false;\n\n // Register this as the singleton instance\n SupertabConnect._instance = this;\n }\n\n /**\n * Clear the singleton instance, allowing a new one to be created with different config.\n */\n public static resetInstance(): void {\n SupertabConnect._instance = null;\n }\n\n /**\n * Override the default base URL for API requests (intended for local development/testing).\n */\n public static setBaseUrl(url: string): void {\n SupertabConnect.baseUrl = url;\n }\n\n /**\n * Get the current base URL for API requests.\n */\n public static getBaseUrl(): string {\n return SupertabConnect.baseUrl;\n }\n\n /**\n * Pure token verification — verifies a license token without recording any events.\n * @param options.token The license token to verify\n * @param options.resourceUrl The URL of the resource being accessed\n * @param options.baseUrl Optional override for the Supertab Connect API base URL\n * @param options.debug Enable debug logging (default: false)\n * @returns A promise that resolves with the verification result\n */\n static async verify(options: {\n token: string;\n resourceUrl: string;\n baseUrl?: string;\n debug?: boolean;\n }): Promise<RSLVerificationResult> {\n const baseUrl = options.baseUrl ?? SupertabConnect.baseUrl;\n\n const result = await verifyLicenseTokenHelper({\n licenseToken: options.token,\n requestUrl: options.resourceUrl,\n supertabBaseUrl: baseUrl,\n debug: options.debug ?? false,\n });\n\n if (result.valid) {\n return { valid: true };\n }\n\n return { valid: false, error: result.error };\n }\n\n /**\n * Verify a license token and record an analytics event.\n * Uses the instance's apiKey and merchantSystemUrn for event recording.\n * @param options.token The license token to verify\n * @param options.resourceUrl The URL of the resource being accessed\n * @param options.userAgent Optional user agent string for event recording\n * @param options.debug Enable debug logging (default: false)\n * @param options.ctx Optional execution context with waitUntil for non-blocking event recording\n * @returns A promise that resolves with the verification result\n */\n async verifyAndRecord(options: {\n token: string;\n resourceUrl: string;\n userAgent?: string;\n debug?: boolean;\n ctx?: ExecutionContext;\n }): Promise<RSLVerificationResult> {\n const result = await verifyAndRecordEvent({\n token: options.token,\n url: options.resourceUrl,\n userAgent: options.userAgent ?? \"unknown\",\n supertabBaseUrl: SupertabConnect.baseUrl,\n debug: options.debug ?? this.debug,\n apiKey: this.apiKey!,\n merchantSystemUrn: this.merchantSystemUrn,\n ctx: options.ctx,\n });\n\n if (result.valid) {\n return { valid: true };\n }\n\n return { valid: false, error: result.error };\n }\n\n /**\n * Handle an incoming request by extracting the license token, verifying it, and recording an analytics event.\n * When no token is present, bot detection and enforcement mode determine the response.\n * @param request The incoming HTTP request\n * @param ctx Execution context for non-blocking event recording.\n * Pass this from your platform (e.g. Cloudflare Workers)\n * @returns A promise that resolves with the handler result indicating ALLOW or BLOCK request\n */\n async handleRequest(request: Request, ctx?: ExecutionContext): Promise<HandlerResult> {\n const auth = request.headers.get(\"Authorization\") || \"\";\n const token = auth.startsWith(\"License \") ? auth.slice(8) : null;\n const url = request.url;\n const userAgent = request.headers.get(\"User-Agent\") || \"unknown\";\n\n // Token present → ALWAYS validate, regardless of mode or bot detection\n if (token) {\n if (this.enforcement === EnforcementMode.DISABLED) {\n return { action: HandlerAction.ALLOW };\n }\n const verification = await verifyAndRecordEvent({\n token,\n url,\n userAgent,\n supertabBaseUrl: SupertabConnect.baseUrl,\n debug: this.debug,\n apiKey: this.apiKey!,\n merchantSystemUrn: this.merchantSystemUrn,\n ctx,\n });\n if (!verification.valid) {\n return buildBlockResult({\n reason: verification.reason,\n error: verification.error,\n requestUrl: url,\n });\n }\n return { action: HandlerAction.ALLOW };\n }\n\n // No token from here on\n const isBot = this.botDetector?.(request, ctx) ?? false;\n\n if (!isBot) {\n return { action: HandlerAction.ALLOW };\n }\n\n // Bot detected, no token — enforcement mode decides\n switch (this.enforcement) {\n case EnforcementMode.STRICT:\n return buildBlockResult({\n reason: LicenseTokenInvalidReason.MISSING_TOKEN,\n error: \"Authorization header missing or malformed\",\n requestUrl: url,\n });\n case EnforcementMode.SOFT:\n return buildSignalResult(url);\n default: // DISABLED\n return { action: HandlerAction.ALLOW };\n }\n }\n\n /**\n * Request a license token from the Supertab Connect token endpoint.\n * @param options.clientId OAuth client identifier.\n * @param options.clientSecret OAuth client secret for client_credentials flow.\n * @param options.resourceUrl Resource URL attempting to access with a License.\n * @param options.debug Enable debug logging (default: false).\n * @returns Promise resolving to the issued license access token string.\n */\n static async obtainLicenseToken(options: {\n clientId: string;\n clientSecret: string;\n resourceUrl: string;\n debug?: boolean;\n }): Promise<string> {\n return obtainLicenseTokenHelper({\n clientId: options.clientId,\n clientSecret: options.clientSecret,\n resourceUrl: options.resourceUrl,\n debug: options.debug,\n });\n }\n\n /**\n * Handle incoming requests for Cloudflare Workers.\n * Pass this directly as your Worker's fetch handler.\n * @param request The incoming Worker request\n * @param env Worker environment bindings containing MERCHANT_API_KEY and MERCHANT_SYSTEM_URN\n * @param ctx Worker execution context for non-blocking event recording\n * @param options Optional configuration items\n * @param options.botDetector Custom bot detection function\n * @param options.enforcement Enforcement mode (default: SOFT)\n */\n static async cloudflareHandleRequests(\n request: Request,\n env: Env,\n ctx: ExecutionContext,\n options?: {\n botDetector?: BotDetector;\n enforcement?: EnforcementMode;\n }\n ): Promise<Response> {\n const instance = new SupertabConnect({\n apiKey: env.MERCHANT_API_KEY,\n merchantSystemUrn: env.MERCHANT_SYSTEM_URN,\n botDetector: options?.botDetector,\n enforcement: options?.enforcement,\n });\n return handleCloudflareRequest(instance, request, ctx);\n }\n\n /**\n * Handle incoming requests for Fastly Compute.\n * @param request The incoming Fastly request\n * @param merchantSystemUrn The merchant system URN for identification\n * @param merchantApiKey The merchant API key for authentication\n * @param originBackend The Fastly backend name to forward allowed requests to\n * @param options Optional configuration items\n * @param options.enableRSL Serve license.xml at /license.xml for RSL-compliant clients (default: false)\n * @param options.botDetector Custom bot detection function\n * @param options.enforcement Enforcement mode (default: SOFT)\n */\n static async fastlyHandleRequests(\n request: Request,\n merchantSystemUrn: string,\n merchantApiKey: string,\n originBackend: string,\n options?: {\n enableRSL?: boolean;\n botDetector?: BotDetector;\n enforcement?: EnforcementMode;\n }\n ): Promise<Response> {\n const { enableRSL = false, botDetector, enforcement } = options ?? {};\n\n const instance = new SupertabConnect({\n apiKey: merchantApiKey,\n merchantSystemUrn: merchantSystemUrn,\n botDetector,\n enforcement,\n });\n\n return handleFastlyRequest(\n instance,\n request,\n originBackend,\n enableRSL\n ? {\n baseUrl: SupertabConnect.baseUrl,\n merchantSystemUrn,\n }\n : undefined\n );\n }\n\n /**\n * Handle incoming requests for AWS CloudFront Lambda@Edge.\n * Use as the handler for a viewer-request LambdaEdge function.\n * @param event The CloudFront viewer-request event\n * @param options Configuration including apiKey, merchantSystemUrn, and optional botDetector/enforcement\n */\n static async cloudfrontHandleRequests<TRequest extends Record<string, any>>(\n event: CloudFrontRequestEvent<TRequest>,\n options: CloudfrontHandlerOptions\n ): Promise<CloudFrontRequestResult<TRequest>> {\n const instance = new SupertabConnect({\n apiKey: options.apiKey,\n merchantSystemUrn: options.merchantSystemUrn,\n botDetector: options.botDetector,\n enforcement: options.enforcement,\n });\n return handleCloudfrontRequest(instance, event);\n }\n}\n"],"mappings":"AAAO,IAAKA,OACVA,EAAA,SAAW,WACXA,EAAA,KAAO,OACPA,EAAA,OAAS,SAHCA,OAAA,IAuDL,IAAMC,EAAiB,cAOlBC,OACVA,EAAA,MAAQ,QACRA,EAAA,MAAQ,QAFEA,OAAA,IC5DZ,SAASC,EAAcC,EAA0C,CAC/D,IAAIC,EAA4B,KAChC,MAAO,KACAA,IACHA,EAASD,EAAK,GAETC,EAEX,CAEO,IAAMC,EAAgBH,EAAW,IAAM,OAAO,iBAAiB,CAAC,EAC1DI,EAAgBJ,EAAW,IAAM,OAAO,iBAAiB,CAAC,EAC1DK,EAA4BL,EAAW,IAAM,OAAO,8BAA8B,CAAC,EACnFM,EAAgBN,EAAW,IAAM,OAAO,iBAAiB,CAAC,EAC1DO,EAAcP,EAAW,IAAM,OAAO,eAAe,CAAC,ECWnE,eAAeQ,EACXC,EACAC,EACAC,EACF,CACA,GAAI,CACF,IAAMC,EAAW,MAAM,MAAMH,EAAeC,CAAc,EAE1D,GAAI,CAACE,EAAS,GAAI,CAChB,IAAMC,EAAY,MAAMD,EAAS,KAAK,EAAE,MAAM,IAAM,EAAE,EAChDE,EAAe,mCACnBF,EAAS,MACX,IAAIA,EAAS,UAAU,GAAGC,EAAY,MAAMA,CAAS,GAAK,EAAE,GAC5D,MAAM,IAAI,MAAMC,CAAY,CAC9B,CAEA,IAAIC,EACJ,GAAI,CACFA,EAAO,MAAMH,EAAS,KAAK,CAC7B,OAASI,EAAY,CACnB,MAAIL,GACF,QAAQ,MACN,kDACAK,CACF,EAEI,IAAI,MAAM,gDAAgD,CAClE,CAEA,GAAI,CAACD,GAAM,aACT,MAAM,IAAI,MAAM,6CAA6C,EAG/D,OAAOA,EAAK,YACd,OAASE,EAAO,CACd,MAAIN,GACF,QAAQ,MAAM,kCAAm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ACnC,OAAQkB,EAAI,iBACZ,kBAAmBA,EAAI,oBACvB,YAAad,GAAS,YACtB,YAAaA,GAAS,WACxB,CAAC,EACD,OAAOgB,EAAwBD,EAAUV,EAASC,CAAG,CACvD,CAaA,aAAa,qBACXD,EACAY,EACAC,EACAC,EACAnB,EAKmB,CACnB,GAAM,CAAE,UAAAoB,EAAY,GAAO,YAAAC,EAAa,YAAAC,CAAY,EAAItB,GAAW,CAAC,EAE9De,EAAW,IAAInB,EAAgB,CACnC,OAAQsB,EACR,kBAAmBD,EACnB,YAAAI,EACA,YAAAC,CACF,CAAC,EAED,OAAOC,EACLR,EACAV,EACAc,EACAC,EACI,CACE,QAASxB,EAAgB,QACzB,kBAAAqB,CACF,EACA,MACN,CACF,CAQA,aAAa,yBACXO,EACAxB,EAC4C,CAC5C,IAAMe,EAAW,IAAInB,EAAgB,CACnC,OAAQI,EAAQ,OAChB,kBAAmBA,EAAQ,kBAC3B,YAAaA,EAAQ,YACrB,YAAaA,EAAQ,WACvB,CAAC,EACD,OAAOyB,EAAwBV,EAAUS,CAAK,CAChD,CACF,EA1Ta5B,EAEI,QAAkB,kCAFtBA,EAQI,UAAoC,KAR9C,IAAM8B,EAAN9B","names":["EnforcementMode","FASTLY_BACKEND","HandlerAction","lazyImport","load","cached","loadJwtVerify","loadDecodeJwt","loadDecodeProtectedHeader","loadKeyImport","loadJwtSign","retrieveLicenseToken","tokenEndpoint","requestOptions","debug","response","errorBody","errorMessage","data","parseError","error","fetchLicenseXml","resourceUrl","debug","licenseXmlUrl","response","xml","parseContentElements","contentBlocks","contentRegex","urlRegex","serverRegex","licenseRegex","elementCount","match","attrs","body","urlMatch","serverMatch","licenseMatch","missing","findBestMatchingContent","parsed","host","path","bestMatch","bestSpecificity","block","patternUrl","patternPath","prefix","specificity","obtainLicenseToken","clientId","clientSecret","resourceUrl","debug","xml","fetchLicenseXml","contentBlocks","parseContentElements","matchedContent","findBestMatchingContent","patterns","b","tokenEndpoint","payload","requestOptions","retrieveLicenseToken","jwksCache","buildFetchOptions","options","FASTLY_BACKEND","fetchAndCacheJwks","cacheKey","url","debug","failureMessage","logLabel","response","jwksData","error","fetchPlatformJwks","baseUrl","jwksUrl","recordEvent","apiKey","merchantSystemUrn","baseUrl","eventName","properties","licenseId","debug","payload","options","FASTLY_BACKEND","response","error","stripTrailingSlash","value","reasonToErrorDescription","reason","verifyLicenseToken","licenseToken","requestUrl","supertabBaseUrl","debug","decodeProtectedHeader","loadDecodeProtectedHeader","decodeJwt","loadDecodeJwt","jwtVerify","loadJwtVerify","header","error","payload","licenseId","issuer","normalizedIssuer","normalizedBaseUrl","audienceValues","entry","requestUrlNormalized","normalizedAudience","jwks","fetchPlatformJwks","result","jwtHeader","jwk","key","generateLicenseLink","baseURL","buildSignalResult","licenseLink","reasonToRslError","sanitizeHeaderValue","buildBlockResult","rslError","status","errorDescription","buildFetchOptions","options","FASTLY_BACKEND","hostRSLicenseXML","merchantSystemUrn","licenseUrl","response","licenseXml","verifyAndRecordEvent","params","verification","eventPromise","recordEvent","handleCloudflareRequest","handler","request","ctx","result","originResponse","response","key","value","handleFastlyRequest","originBackend","rslOptions","hostRSLicenseXML","handleCloudfrontRequest","event","cfRequest","url","headers","values","webRequest","responseHeaders","defaultBotDetector","request","userAgent","accept","secChUa","acceptLanguage","botScore","botList","lowerCaseUserAgent","botUaMatch","bot","headlessIndicators","isBrowserMissingSecChUa","missingHeaders","lowBotScore","_SupertabConnect","config","reset","url","options","baseUrl","result","verifyLicenseToken","verifyAndRecordEvent","request","ctx","auth","token","userAgent","verification","buildBlockResult","buildSignalResult","obtainLicenseToken","env","instance","handleCloudflareRequest","merchantSystemUrn","merchantApiKey","originBackend","enableRSL","botDetector","enforcement","handleFastlyRequest","event","handleCloudfrontRequest","SupertabConnect"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@getsupertab/supertab-connect-sdk",
|
|
3
|
-
"version": "0.1.0-beta.
|
|
3
|
+
"version": "0.1.0-beta.37",
|
|
4
4
|
"description": "Supertab Connect SDK (beta)",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.cjs",
|
|
@@ -35,6 +35,10 @@
|
|
|
35
35
|
],
|
|
36
36
|
"author": "Supertab (https://supertab.co)",
|
|
37
37
|
"homepage": "https://supertab-connect.mintlify.app/introduction/about-supertab-connect",
|
|
38
|
+
"repository": {
|
|
39
|
+
"type": "git",
|
|
40
|
+
"url": "https://github.com/getsupertab/connect-sdk-typescript"
|
|
41
|
+
},
|
|
38
42
|
"license": "MIT",
|
|
39
43
|
"devDependencies": {
|
|
40
44
|
"@types/node": "^18.0.0",
|