@getsupertab/supertab-connect-sdk 0.1.0-beta.38 → 2.0.0

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 CHANGED
@@ -1,2 +1,2 @@
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 n in e)w(t,n,{get:e[n],enumerable:!0})},P=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Y(e))!Z.call(t,s)&&s!==n&&w(t,s,{get:()=>e[s],enumerable:!(r=z(e,s))||r.enumerable});return t};var y=(t,e,n)=>(n=t!=null?X(Q(t)):{},P(e||!t||!t.__esModule?w(n,"default",{value:t,enumerable:!0}):n,t)),te=t=>P(w({},"__esModule",{value:!0}),t);var ge={};ee(ge,{EnforcementMode:()=>x,HandlerAction:()=>b,SupertabConnect:()=>C,defaultBotDetector:()=>j});module.exports=te(ge);var x=(r=>(r.DISABLED="disabled",r.SOFT="soft",r.STRICT="strict",r))(x||{});var R="stc-backend",b=(n=>(n.ALLOW="allow",n.BLOCK="block",n))(b||{});function E(t){let e=null;return()=>(e||(e=t()),e)}var q=E(()=>import("jose/jwt/verify")),F=E(()=>import("jose/jwt/decode")),N=E(()=>import("jose/decode/protected_header")),re=E(()=>import("jose/key/import")),ne=E(()=>import("jose/jwt/sign"));async function se(t,e,n){try{let r=await fetch(t,e);if(!r.ok){let o=await r.text().catch(()=>""),a=`Failed to obtain license token: ${r.status} ${r.statusText}${o?` - ${o}`:""}`;throw new Error(a)}let s;try{s=await r.json()}catch(o){throw n&&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(r){throw n&&console.error("Error generating license token:",r),r}}async function oe(t,e){let r=`${new URL(t).origin}/license.xml`,s=await fetch(r);if(!s.ok)throw e&&console.error(`Failed to fetch license.xml from ${r}: ${s.status}`),new Error(`Failed to fetch license.xml from ${r}: ${s.status}`);let o=await s.text();return e&&console.debug("Fetched license.xml from",r),o}function ie(t,e){let n=[],r=/<content\s([^>]*)>([\s\S]*?)<\/content>/gi,s=/url\s*=\s*"([^"]*)"/i,o=/server\s*=\s*"([^"]*)"/i,a=/<license[^>]*>[\s\S]*?<\/license>/i,i=0,c;for(;(c=r.exec(t))!==null;){i++;let l=c[1],d=c[2],p=l.match(s),g=l.match(o),m=d.match(a);if(p&&g&&m)n.push({urlPattern:p[1],server:g[1],licenseXml:m[0]});else if(e){let A=[!p&&"url",!g&&"server",!m&&"<license>"].filter(Boolean).join(", ");console.debug(`Skipping <content> element #${i}: missing ${A}`)}}return e&&console.debug(`Found ${i} <content> element(s), ${n.length} valid`),n}function ae(t,e,n){let r=new URL(e),s=r.host,o=r.pathname;n&&console.debug(`Matching resource URL: ${e} (host=${s}, path=${o})`);let a=null,i=-1;for(let c of t){let l;try{l=new URL(c.urlPattern)}catch{n&&console.debug(`Skipping block with invalid URL pattern: ${c.urlPattern}`);continue}if(l.host!==s){n&&console.debug(`Skipping block: host mismatch (pattern=${l.host}, resource=${s})`);continue}let d=l.pathname;if(d===o)return n&&console.debug(`Exact match found: ${c.urlPattern}`),c;if(d.endsWith("/*")){let p=d.slice(0,-1);if(o.startsWith(p)){let g=p.length;g>i&&(i=g,a=c)}}}return n&&console.debug(a?`Wildcard match found: ${a.urlPattern} (specificity=${i})`:`No matching content block found for ${e}`),a}async function O({clientId:t,clientSecret:e,resourceUrl:n,debug:r}){let s=await oe(n,r);r&&console.debug(`Fetched license.xml (${s.length} chars)`);let o=ie(s,r);if(o.length===0)throw r&&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,n,r);if(!a){if(r){let d=o.map(p=>p.urlPattern).join(", ");console.error(`No <content> element matches resource URL: ${n}. Available patterns: ${d}`)}throw new Error(`No <content> element in license.xml matches resource URL: ${n}`)}r&&(console.debug("Matched content block for resource URL:",n),console.debug("Using license XML:",a.licenseXml));let i=a.server+"/token";r&&console.debug(`Requesting license token from ${i}`);let c=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:c.toString()};return se(i,l,r)}var k=new Map;function ce(){let t={method:"GET"};return globalThis?.fastly&&(t={...t,backend:R}),t}async function le({cacheKey:t,url:e,debug:n,failureMessage:r,logLabel:s}){if(!k.has(t))try{let o=await fetch(e,ce());if(!o.ok)throw new Error(`${r}: ${o.status}`);let a=await o.json();k.set(t,a)}catch(o){throw n&&console.error(s,o),o}return k.get(t)}async function H(t,e){let n=`${t}/.well-known/jwks.json/platform`;return e&&console.debug(`Fetching platform JWKS from URL: ${n}`),le({cacheKey:"platform_jwks",url:n,debug:e,failureMessage:"Failed to fetch platform JWKS",logLabel:"Error fetching platform JWKS:"})}async function B({apiKey:t,baseUrl:e,eventName:n,properties:r,licenseId:s,debug:o=!1}){let a={event_name:n,license_id:s,properties:r};try{let i={method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify(a)};globalThis?.fastly&&(i={...i,backend:R});let c=await fetch(`${e}/events`,i);!c.ok&&o&&console.error(`Failed to record event: ${c.status}`)}catch(i){o&&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 S({licenseToken:t,requestUrl:e,supertabBaseUrl:n,debug:r}){let{decodeProtectedHeader:s}=await N(),{decodeJwt:o}=await F(),{jwtVerify:a}=await q();if(!t)return{valid:!1,reason:"missing_license_token",error:h("missing_license_token")};let i;try{i=s(t)}catch(f){return r&&console.error("Invalid license JWT header:",f),{valid:!1,reason:"invalid_license_header",error:h("invalid_license_header")}}if(i.alg!=="ES256")return r&&console.error("Unsupported license JWT alg:",i.alg),{valid:!1,reason:"invalid_license_algorithm",error:h("invalid_license_algorithm")};let c;try{c=o(t)}catch(f){return r&&console.error("Invalid license JWT payload:",f),{valid:!1,reason:"invalid_license_payload",error:h("invalid_license_payload")}}let l=c.license_id,d=c.iss,p=d?I(d):void 0,g=I(n);if(!p||!p.startsWith(g))return r&&console.error("License JWT issuer is missing or malformed:",d),{valid:!1,reason:"invalid_license_issuer",error:h("invalid_license_issuer"),licenseId:l};let m=Array.isArray(c.aud)?c.aud.filter(f=>typeof f=="string"):typeof c.aud=="string"?[c.aud]:[],A=I(e);if(!m.some(f=>{let L=I(f);return L?A.startsWith(L):!1}))return r&&console.error("License JWT audience does not match request URL:",c.aud),{valid:!1,reason:"invalid_license_audience",error:h("invalid_license_audience"),licenseId:l};let U;try{U=await H(n,r)}catch(f){return r&&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 D=>{let _=U.keys.find(G=>G.kid===D.kid);if(!_)throw new Error(`No matching platform key found: ${D.kid}`);return _},{issuer:d,algorithms:[i.alg],clockTolerance:"1m"});return{valid:!0,licenseId:l,payload:L.payload}}catch(f){return r&&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 K({requestUrl:t}){try{let e=new URL(t);return`${e.protocol}//${e.host}/license.xml`}catch(e){return console.error("[SupertabConnect] generateLicenseLink failed to parse URL:",e),"/license.xml"}}function V(t){let e=K({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 v({reason:t,error:e,requestUrl:n}){let{rslError:r,status:s}=de(t),o=fe(e),a=K({requestUrl:n});return{action:"block",status:s,body:`Access to this resource requires a valid license token. Error: ${r} - ${e}`,headers:{"Content-Type":"text/plain; charset=UTF-8","WWW-Authenticate":`License error="${r}", error_description="${o}"`,Link:`<${a}>; rel="license"; type="application/rsl+xml"`}}}function pe(){let t={method:"GET"};return globalThis?.fastly&&(t={...t,backend:R}),t}async function $(t,e){try{let n=`${t}/merchants/systems/${e}/license.xml`,r=await fetch(n,pe());if(!r.ok)return new Response("License not found",{status:404});let s=await r.text();return new Response(s,{status:200,headers:new Headers({"Content-Type":"application/xml"})})}catch(n){return console.error("[SupertabConnect] hostRSLicenseXML failed:",n),new Response("Bad Gateway",{status:502})}}async function T(t){let e=await S({licenseToken:t.token,requestUrl:t.url,supertabBaseUrl:t.supertabBaseUrl,debug:t.debug}),n=B({apiKey:t.apiKey,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(n),e}async function W(t,e,n){let r=await t.handleRequest(e,n);if(r.action==="block")return new Response(r.body,{status:r.status,headers:new Headers(r.headers)});let s=await fetch(e);if(r.headers){let o=new Response(s.body,s);for(let[a,i]of Object.entries(r.headers))o.headers.set(a,i);return o}return s}async function J(t,e,n,r){if(r&&new URL(e.url).pathname==="/license.xml")return await $(r.baseUrl,r.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:n});if(s.headers){let a=new Response(o.body,o);for(let[i,c]of Object.entries(s.headers))a.headers.set(i,c);return a}return o}async function M(t,e){let n=e.Records[0].cf.request,r=`https://${n.headers.host[0].value}${n.uri}${n.querystring?"?"+n.querystring:""}`,s=new Headers;Object.entries(n.headers).forEach(([i,c])=>{c.forEach(({value:l})=>s.append(i,l))});let o=new Request(r,{method:n.method,headers:s}),a=await t.handleRequest(o);if(a.action==="block"){let i={};return Object.entries(a.headers).forEach(([c,l])=>{i[c.toLowerCase()]=[{key:c,value:l}]}),{status:a.status.toString(),statusDescription:a.status===401?"Unauthorized":"Payment Required",headers:i,body:a.body}}return n}function j(t){let e=t.headers.get("User-Agent")||"",n=t.headers.get("accept")||"",r=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"],i=e.toLowerCase(),c=a.some(m=>i.includes(m)),l=i.includes("headless")||i.includes("puppeteer")||!r,d=!i.includes("headless")&&!i.includes("puppeteer")&&!r,p=!n||!s,g=typeof o=="number"&&o<30;return(i.includes("safari")||i.includes("mozilla"))&&l&&d?!1:c||l||p||g}var u=class u{constructor(e,n=!1){if(!n&&u._instance){if(e.apiKey!==u._instance.apiKey)throw new Error("Cannot create a new instance with different configuration. Use resetInstance to clear the existing instance.");return u._instance}if(n&&u._instance&&u.resetInstance(),!e.apiKey)throw new Error("Missing required configuration: apiKey is required");this.apiKey=e.apiKey,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 n=e.baseUrl??u.baseUrl,r=await S({licenseToken:e.token,requestUrl:e.resourceUrl,supertabBaseUrl:n,debug:e.debug??!1});return r.valid?{valid:!0}:{valid:!1,error:r.error}}async verifyAndRecord(e){let n=await T({token:e.token,url:e.resourceUrl,userAgent:e.userAgent??"unknown",supertabBaseUrl:u.baseUrl,debug:e.debug??this.debug,apiKey:this.apiKey,ctx:e.ctx});return n.valid?{valid:!0}:{valid:!1,error:n.error}}async handleRequest(e,n){let r=e.headers.get("Authorization")||"",s=r.startsWith("License ")?r.slice(8):null,o=e.url,a=e.headers.get("User-Agent")||"unknown";if(s){if(this.enforcement==="disabled")return{action:"allow"};let c=await T({token:s,url:o,userAgent:a,supertabBaseUrl:u.baseUrl,debug:this.debug,apiKey:this.apiKey,ctx:n});return c.valid?{action:"allow"}:v({reason:c.reason,error:c.error,requestUrl:o})}if(!(this.botDetector?.(e,n)??!1))return{action:"allow"};switch(this.enforcement){case"strict":return v({reason:"missing_license_token",error:"Authorization header missing or malformed",requestUrl:o});case"soft":return V(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,n,r,s){try{let o=new u({apiKey:n.MERCHANT_API_KEY,botDetector:s?.botDetector,enforcement:s?.enforcement});return await W(o,e,r)}catch(o){return console.error("[SupertabConnect] cloudflareHandleRequests failed:",o),await fetch(e)}}static async fastlyHandleRequests(e,n,r,s){try{let{botDetector:o,enforcement:a}=s??{},i=new u({apiKey:n,botDetector:o,enforcement:a}),c;return s?.enableRSL&&(c={baseUrl:u.baseUrl,merchantSystemUrn:s.merchantSystemUrn}),await J(i,e,r,c)}catch(o){return console.error("[SupertabConnect] fastlyHandleRequests failed:",o),await fetch(e,{backend:r})}}static async cloudfrontHandleRequests(e,n){try{let r=new u({apiKey:n.apiKey,botDetector:n.botDetector,enforcement:n.enforcement});return await M(r,e)}catch(r){return console.error("[SupertabConnect] cloudfrontHandleRequests failed:",r),e?.Records?.[0]?.cf?.request??{}}}};u.baseUrl="https://api-connect.supertab.co",u._instance=null;var C=u;0&&(module.exports={EnforcementMode,HandlerAction,SupertabConnect,defaultBotDetector});
1
+ "use strict";var ee=Object.create;var x=Object.defineProperty;var te=Object.getOwnPropertyDescriptor;var re=Object.getOwnPropertyNames;var ne=Object.getPrototypeOf,se=Object.prototype.hasOwnProperty;var oe=(t,e)=>{for(var n in e)x(t,n,{get:e[n],enumerable:!0})},N=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of re(e))!se.call(t,s)&&s!==n&&x(t,s,{get:()=>e[s],enumerable:!(r=te(e,s))||r.enumerable});return t};var w=(t,e,n)=>(n=t!=null?ee(ne(t)):{},N(e||!t||!t.__esModule?x(n,"default",{value:t,enumerable:!0}):n,t)),ie=t=>N(x({},"__esModule",{value:!0}),t);var we={};oe(we,{EnforcementMode:()=>v,HandlerAction:()=>L,LicenseTokenInvalidReason:()=>I,SupertabConnect:()=>P,defaultBotDetector:()=>Y});module.exports=ie(we);var v=(r=>(r.DISABLED="disabled",r.SOFT="soft",r.STRICT="strict",r))(v||{}),I=(l=>(l.MISSING_TOKEN="missing_license_token",l.INVALID_HEADER="invalid_license_header",l.INVALID_ALG="invalid_license_algorithm",l.INVALID_PAYLOAD="invalid_license_payload",l.INVALID_ISSUER="invalid_license_issuer",l.SIGNATURE_VERIFICATION_FAILED="license_signature_verification_failed",l.EXPIRED="license_token_expired",l.INVALID_AUDIENCE="invalid_license_audience",l.SERVER_ERROR="server_error",l))(I||{}),b="stc-backend",L=(n=>(n.ALLOW="allow",n.BLOCK="block",n))(L||{});function k(t){let e=null;return()=>(e||(e=t()),e)}var H=k(()=>import("jose/jwt/verify")),S=k(()=>import("jose/jwt/decode")),K=k(()=>import("jose/decode/protected_header")),ae=k(()=>import("jose/key/import")),ce=k(()=>import("jose/jwt/sign"));var T=new Map;function le(t,e){let n=T.get(t);if(!n)return null;let r=Math.floor(Date.now()/1e3);return n.exp>r+30?(e&&console.debug(`Using cached license token (expires in ${n.exp-r}s)`),n.token):(e&&console.debug("Cached license token expired or expiring soon, refreshing"),T.delete(t),null)}async function ue(t,e,n){try{let r=await fetch(t,e);if(!r.ok){let o=await r.text().catch(()=>""),c=`Failed to obtain license token: ${r.status} ${r.statusText}${o?` - ${o}`:""}`;throw new Error(c)}let s;try{s=await r.json()}catch(o){throw n&&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(r){throw n&&console.error("Error generating license token:",r),r}}async function de(t,e){let r=`${new URL(t).origin}/license.xml`,s=await fetch(r);if(!s.ok)throw e&&console.error(`Failed to fetch license.xml from ${r}: ${s.status}`),new Error(`Failed to fetch license.xml from ${r}: ${s.status}`);let o=await s.text();return e&&console.debug("Fetched license.xml from",r),o}function fe(t,e){let n=[],r=/<content\s([^>]*)>([\s\S]*?)<\/content>/gi,s=/url\s*=\s*"([^"]*)"/i,o=/server\s*=\s*"([^"]*)"/i,c=/<license[^>]*>[\s\S]*?<\/license>/i,i=0,a;for(;(a=r.exec(t))!==null;){i++;let l=a[1],d=a[2],p=l.match(s),f=l.match(o),g=d.match(c);if(p&&f&&g)n.push({urlPattern:p[1],server:f[1],licenseXml:g[0]});else if(e){let R=[!p&&"url",!f&&"server",!g&&"<license>"].filter(Boolean).join(", ");console.debug(`Skipping <content> element #${i}: missing ${R}`)}}return e&&console.debug(`Found ${i} <content> element(s), ${n.length} valid`),n}function pe(t,e,n){let r=new URL(e),s=r.host,o=r.pathname;n&&console.debug(`Matching resource URL: ${e} (host=${s}, path=${o})`);let c=null,i=-1;for(let a of t){let l;try{l=new URL(a.urlPattern)}catch{n&&console.debug(`Skipping block with invalid URL pattern: ${a.urlPattern}`);continue}if(l.host!==s){n&&console.debug(`Skipping block: host mismatch (pattern=${l.host}, resource=${s})`);continue}let d=l.pathname;if(d===o)return n&&console.debug(`Exact match found: ${a.urlPattern}`),a;if(d.endsWith("/*")){let p=d.slice(0,-1);if(o.startsWith(p)){let f=p.length;f>i&&(i=f,c=a)}}}return n&&console.debug(c?`Wildcard match found: ${c.urlPattern} (specificity=${i})`:`No matching content block found for ${e}`),c}async function $({clientId:t,clientSecret:e,resourceUrl:n,debug:r}){let s=`${t}:${n}`,o=le(s,r);if(o)return o;let c=await de(n,r);r&&console.debug(`Fetched license.xml (${c.length} chars)`);let i=fe(c,r);if(i.length===0)throw r&&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=pe(i,n,r);if(!a){if(r){let g=i.map(R=>R.urlPattern).join(", ");console.error(`No <content> element matches resource URL: ${n}. Available patterns: ${g}`)}throw new Error(`No <content> element in license.xml matches resource URL: ${n}`)}r&&(console.debug("Matched content block for resource URL:",n),console.debug("Using license XML:",a.licenseXml));let l=a.server+"/token";r&&console.debug(`Requesting license token from ${l}`);let d=new URLSearchParams({grant_type:"client_credentials",license:a.licenseXml,resource:a.urlPattern}),p={method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json",Authorization:"Basic "+btoa(`${t}:${e}`)},body:d.toString()},f=await ue(l,p,r);try{let{decodeJwt:g}=await S(),R=g(f);R.exp&&T.set(s,{token:f,exp:R.exp})}catch{r&&console.debug("Failed to decode token for caching, skipping cache")}return f}var C=new Map,he=48*60*60*1e3,E=class extends Error{constructor(e){super(`No matching platform key found: ${e}`),this.name="JwksKeyNotFoundError"}};function ge(){let t={method:"GET"};return globalThis.fastly&&(t={...t,backend:b}),t}async function me({cacheKey:t,url:e,debug:n,failureMessage:r,logLabel:s}){let o=C.get(t);if(o&&Date.now()-o.cachedAt<he)return o.data;try{let c=await fetch(e,ge());if(!c.ok)throw new Error(`${r}: ${c.status}`);let i=await c.json();return C.set(t,{data:i,cachedAt:Date.now()}),i}catch(c){throw n&&console.error(s,c),c}}async function B(t,e){let n=`${t}/.well-known/jwks.json/platform`;return e&&console.debug(`Fetching platform JWKS from URL: ${n}`),me({cacheKey:"platform_jwks",url:n,debug:e,failureMessage:"Failed to fetch platform JWKS",logLabel:"Error fetching platform JWKS:"})}function V(){C.clear()}async function J({apiKey:t,baseUrl:e,eventName:n,properties:r,licenseId:s,debug:o=!1}){let c={event_name:n,license_id:s,properties:r};try{let i={method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify(c)};globalThis.fastly&&(i={...i,backend:b});let a=await fetch(`${e}/events`,i);!a.ok&&o&&console.error(`Failed to record event: ${a.status}`)}catch(i){o&&console.error("Error recording event:",i)}}var A=t=>t.trim().replace(/\/+$/,"");function y(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 U({licenseToken:t,requestUrl:e,supertabBaseUrl:n,debug:r}){let{decodeProtectedHeader:s}=await K(),{decodeJwt:o}=await S(),{jwtVerify:c}=await H();if(!t)return{valid:!1,reason:"missing_license_token",error:y("missing_license_token")};let i;try{i=s(t)}catch(h){return r&&console.error("Invalid license JWT header:",h),{valid:!1,reason:"invalid_license_header",error:y("invalid_license_header")}}if(i.alg!=="ES256")return r&&console.error("Unsupported license JWT alg:",i.alg),{valid:!1,reason:"invalid_license_algorithm",error:y("invalid_license_algorithm")};let a;try{a=o(t)}catch(h){return r&&console.error("Invalid license JWT payload:",h),{valid:!1,reason:"invalid_license_payload",error:y("invalid_license_payload")}}let l=a.license_id,d=a.iss,p=d?A(d):void 0,f=A(n);if(!p||!p.startsWith(f))return r&&console.error("License JWT issuer is missing or malformed:",d),{valid:!1,reason:"invalid_license_issuer",error:y("invalid_license_issuer"),licenseId:l};let g=Array.isArray(a.aud)?a.aud.filter(h=>typeof h=="string"):typeof a.aud=="string"?[a.aud]:[],R=A(e);if(!g.some(h=>{let m=A(h);return m?R.startsWith(m):!1}))return r&&console.error("License JWT audience does not match request URL:",a.aud),{valid:!1,reason:"invalid_license_audience",error:y("invalid_license_audience"),licenseId:l};let q=async()=>{let h;try{h=await B(n,r)}catch(m){return r&&console.error("Failed to fetch platform JWKS:",m),{valid:!1,reason:"server_error",error:y("server_error"),licenseId:l}}try{let Q=await c(t,async F=>{let O=h.keys.find(Z=>Z.kid===F.kid);if(!O)throw new E(F.kid);return O},{issuer:d,algorithms:[i.alg],clockTolerance:"1m"});return{valid:!0,licenseId:l,payload:Q.payload}}catch(m){if(r&&console.error("License JWT verification failed:",m),m instanceof E)throw m;return m instanceof Error&&m.message?.includes("exp")?{valid:!1,reason:"license_token_expired",error:y("license_token_expired"),licenseId:l}:{valid:!1,reason:"license_signature_verification_failed",error:y("license_signature_verification_failed"),licenseId:l}}};try{return await q()}catch(h){if(h instanceof E)return r&&console.debug("Key not found in cached JWKS, clearing cache and retrying..."),V(),await q();throw h}}function W({requestUrl:t}){try{let e=new URL(t);return`${e.protocol}//${e.host}/license.xml`}catch(e){return console.error("[SupertabConnect] generateLicenseLink failed to parse URL:",e),"/license.xml"}}function M(t){let e=W({requestUrl:t});return{action:"allow",headers:{Link:`<${e}>; rel="license"; type="application/rsl+xml"`,"X-RSL-Status":"token_required","X-RSL-Reason":"missing"}}}function ye(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 Re(t){return t.replace(/[\r\n]/g,"").replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function D({reason:t,error:e,requestUrl:n}){let{rslError:r,status:s}=ye(t),o=Re(e),c=W({requestUrl:n});return{action:"block",status:s,body:`Access to this resource requires a valid license token. Error: ${r} - ${e}`,headers:{"Content-Type":"text/plain; charset=UTF-8","WWW-Authenticate":`License error="${r}", error_description="${o}"`,Link:`<${c}>; rel="license"; type="application/rsl+xml"`}}}function be(){let t={method:"GET"};return globalThis.fastly&&(t={...t,backend:b}),t}async function j(t,e){try{let n=`${t}/merchants/systems/${e}/license.xml`,r=await fetch(n,be());if(!r.ok)return new Response("License not found",{status:404});let s=await r.text();return new Response(s,{status:200,headers:new Headers({"Content-Type":"application/xml"})})}catch(n){return console.error("[SupertabConnect] hostRSLicenseXML failed:",n),new Response("Bad Gateway",{status:502})}}async function _(t){let e=await U({licenseToken:t.token,requestUrl:t.url,supertabBaseUrl:t.supertabBaseUrl,debug:t.debug}),n=J({apiKey:t.apiKey,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(n),e}async function G(t,e,n){let r=await t.handleRequest(e,n);if(r.action==="block")return new Response(r.body,{status:r.status,headers:new Headers(r.headers)});let s=await fetch(e);if(r.headers){let o=new Response(s.body,s);for(let[c,i]of Object.entries(r.headers))o.headers.set(c,i);return o}return s}async function X(t,e,n,r){if(r&&new URL(e.url).pathname==="/license.xml")return await j(r.baseUrl,r.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:n});if(s.headers){let c=new Response(o.body,o);for(let[i,a]of Object.entries(s.headers))c.headers.set(i,a);return c}return o}function Ee(t){switch(t){case 401:return"Unauthorized";case 402:return"Payment Required";case 403:return"Forbidden";case 503:return"Service Unavailable";default:return"Error"}}async function z(t,e){let n=e.Records[0].cf.request,r=`https://${n.headers.host[0].value}${n.uri}${n.querystring?"?"+n.querystring:""}`,s=new Headers;Object.entries(n.headers).forEach(([i,a])=>{a.forEach(({value:l})=>s.append(i,l))});let o=new Request(r,{method:n.method,headers:s}),c=await t.handleRequest(o);if(c.action==="block"){let i={};return Object.entries(c.headers).forEach(([a,l])=>{i[a.toLowerCase()]=[{key:a,value:l}]}),{status:c.status.toString(),statusDescription:Ee(c.status),headers:i,body:c.body}}return n}function Y(t){let e=t.headers.get("User-Agent")||"",n=t.headers.get("accept")||"",r=t.headers.get("sec-ch-ua"),s=t.headers.get("accept-language"),o=t.cf?.botManagement?.score,c=["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"],i=e.toLowerCase(),a=c.some(g=>i.includes(g)),l=i.includes("headless")||i.includes("puppeteer")||!r,d=!i.includes("headless")&&!i.includes("puppeteer")&&!r,p=!n||!s,f=typeof o=="number"&&o<30;return(i.includes("safari")||i.includes("mozilla"))&&l&&d?!1:a||l||p||f}var u=class u{constructor(e,n=!1){if(!n&&u._instance){if(e.apiKey!==u._instance.apiKey)throw new Error("Cannot create a new instance with different configuration. Use resetInstance to clear the existing instance.");return u._instance}if(n&&u._instance&&u.resetInstance(),!e.apiKey)throw new Error("Missing required configuration: apiKey is required");this.apiKey=e.apiKey,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 n=e.baseUrl??u.baseUrl,r=await U({licenseToken:e.token,requestUrl:e.resourceUrl,supertabBaseUrl:n,debug:e.debug??!1});return r.valid?{valid:!0}:{valid:!1,error:r.error}}async verifyAndRecord(e){let n=await _({token:e.token,url:e.resourceUrl,userAgent:e.userAgent??"unknown",supertabBaseUrl:u.baseUrl,debug:e.debug??this.debug,apiKey:this.apiKey,ctx:e.ctx});return n.valid?{valid:!0}:{valid:!1,error:n.error}}async handleRequest(e,n){let r=e.headers.get("Authorization")||"",s=r.startsWith("License ")?r.slice(8):null,o=e.url,c=e.headers.get("User-Agent")||"unknown";if(s){if(this.enforcement==="disabled")return{action:"allow"};let a=await _({token:s,url:o,userAgent:c,supertabBaseUrl:u.baseUrl,debug:this.debug,apiKey:this.apiKey,ctx:n});return a.valid?{action:"allow"}:D({reason:a.reason,error:a.error,requestUrl:o})}if(!(this.botDetector?.(e,n)??!1))return{action:"allow"};switch(this.enforcement){case"strict":return D({reason:"missing_license_token",error:"Authorization header missing or malformed",requestUrl:o});case"soft":return M(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,n,r,s){try{let o=new u({apiKey:n.MERCHANT_API_KEY,botDetector:s?.botDetector,enforcement:s?.enforcement});return await G(o,e,r)}catch(o){return console.error("[SupertabConnect] cloudflareHandleRequests failed:",o),await fetch(e)}}static async fastlyHandleRequests(e,n,r,s){try{let{botDetector:o,enforcement:c}=s??{},i=new u({apiKey:n,botDetector:o,enforcement:c}),a;return s?.enableRSL&&(a={baseUrl:u.baseUrl,merchantSystemUrn:s.merchantSystemUrn}),await X(i,e,r,a)}catch(o){return console.error("[SupertabConnect] fastlyHandleRequests failed:",o),await fetch(e,{backend:r})}}static async cloudfrontHandleRequests(e,n){try{let r=new u({apiKey:n.apiKey,botDetector:n.botDetector,enforcement:n.enforcement});return await z(r,e)}catch(r){return console.error("[SupertabConnect] cloudfrontHandleRequests failed:",r),e?.Records?.[0]?.cf?.request??{}}}};u.baseUrl="https://api-connect.supertab.co",u._instance=null;var P=u;0&&(module.exports={EnforcementMode,HandlerAction,LicenseTokenInvalidReason,SupertabConnect,defaultBotDetector});
2
2
  //# sourceMappingURL=index.cjs.map
@@ -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 FastlyHandlerOptions,\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 FastlyHandlerOptions,\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 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\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 (config.apiKey !== SupertabConnect._instance.apiKey) {\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) {\n throw new Error(\n \"Missing required configuration: apiKey is required\"\n );\n }\n this.apiKey = config.apiKey;\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 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 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 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\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 try {\n const instance = new SupertabConnect({\n apiKey: env.MERCHANT_API_KEY,\n botDetector: options?.botDetector,\n enforcement: options?.enforcement,\n });\n return await handleCloudflareRequest(instance, request, ctx);\n } catch (err) {\n console.error(\"[SupertabConnect] cloudflareHandleRequests failed:\", err);\n return await fetch(request);\n }\n }\n\n /**\n * Handle incoming requests for Fastly Compute.\n * @param request The incoming Fastly request\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.merchantSystemUrn Required when enableRSL is true; the merchant system URN used to fetch license.xml\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 merchantApiKey: string,\n originBackend: string,\n options?: FastlyHandlerOptions\n ): Promise<Response> {\n try {\n const { botDetector, enforcement } = options ?? {};\n\n const instance = new SupertabConnect({\n apiKey: merchantApiKey,\n botDetector,\n enforcement,\n });\n\n let rslOptions: { baseUrl: string; merchantSystemUrn: string } | undefined;\n if (options?.enableRSL) {\n rslOptions = {\n baseUrl: SupertabConnect.baseUrl,\n merchantSystemUrn: options.merchantSystemUrn,\n };\n }\n\n return await handleFastlyRequest(\n instance,\n request,\n originBackend,\n rslOptions\n );\n } catch (err) {\n console.error(\"[SupertabConnect] fastlyHandleRequests failed:\", err);\n return await fetch(request, { backend: originBackend } as RequestInit);\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 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 try {\n const instance = new SupertabConnect({\n apiKey: options.apiKey,\n botDetector: options.botDetector,\n enforcement: options.enforcement,\n });\n return await handleCloudfrontRequest(instance, event);\n } catch (err) {\n console.error(\"[SupertabConnect] cloudfrontHandleRequests failed:\", err);\n return event?.Records?.[0]?.cf?.request as TRequest ?? {} as CloudFrontRequestResult<TRequest>;\n }\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 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 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 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 botDetector?: BotDetector;\n enforcement?: EnforcementMode;\n}\n\nexport type RSLVerificationResult = {\n valid: boolean;\n error?: string;\n};\n\ninterface FastlyHandlerBaseOptions {\n botDetector?: BotDetector;\n enforcement?: EnforcementMode;\n}\n\ninterface FastlyHandlerWithRSL extends FastlyHandlerBaseOptions {\n enableRSL: true;\n merchantSystemUrn: string;\n}\n\ninterface FastlyHandlerWithoutRSL extends FastlyHandlerBaseOptions {\n enableRSL?: false;\n merchantSystemUrn?: never;\n}\n\nexport type FastlyHandlerOptions = FastlyHandlerWithRSL | FastlyHandlerWithoutRSL;\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 baseUrl,\n eventName,\n properties,\n licenseId,\n debug = false,\n}: {\n apiKey: 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 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 try {\n const baseURL = new URL(requestUrl);\n return `${baseURL.protocol}//${baseURL.host}/license.xml`;\n } catch (err) {\n console.error(\"[SupertabConnect] generateLicenseLink failed to parse URL:\", err);\n return \"/license.xml\";\n }\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 try {\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 } catch (err) {\n console.error(\"[SupertabConnect] hostRSLicenseXML failed:\", err);\n return new Response(\"Bad Gateway\", { status: 502 });\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 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 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,GAAA,qBAAAE,EAAA,kBAAAC,EAAA,oBAAAC,EAAA,uBAAAC,IAAA,eAAAC,GAAAN,ICAO,IAAKO,OACVA,EAAA,SAAW,WACXA,EAAA,KAAO,OACPA,EAAA,OAAS,SAHCA,OAAA,IAmDL,IAAMC,EAAiB,cAOlBC,OACVA,EAAA,MAAQ,QACRA,EAAA,MAAQ,QAFEA,OAAA,ICxDZ,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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EACAc,EACAG,CACF,CACF,OAASL,EAAK,CACZ,eAAQ,MAAM,iDAAkDA,CAAG,EAC5D,MAAM,MAAMZ,EAAS,CAAE,QAASc,CAAc,CAAgB,CACvE,CACF,CAQA,aAAa,yBACXK,EACAxB,EAC4C,CAC5C,GAAI,CACF,IAAMe,EAAW,IAAInB,EAAgB,CACnC,OAAQI,EAAQ,OAChB,YAAaA,EAAQ,YACrB,YAAaA,EAAQ,WACvB,CAAC,EACD,OAAO,MAAMyB,EAAwBV,EAAUS,CAAK,CACtD,OAASP,EAAK,CACZ,eAAQ,MAAM,qDAAsDA,CAAG,EAChEO,GAAO,UAAU,CAAC,GAAG,IAAI,SAAuB,CAAC,CAC1D,CACF,CACF,EA1Ta5B,EAEI,QAAkB,kCAFtBA,EAOI,UAAoC,KAP9C,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","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","err","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","err","merchantApiKey","originBackend","botDetector","enforcement","rslOptions","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 FastlyHandlerOptions,\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, LicenseTokenInvalidReason };\nexport type {\n SupertabConnectConfig,\n RSLVerificationResult,\n ExecutionContext,\n Env,\n BotDetector,\n HandlerResult,\n FastlyHandlerOptions,\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 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\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 (config.apiKey !== SupertabConnect._instance.apiKey) {\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) {\n throw new Error(\n \"Missing required configuration: apiKey is required\"\n );\n }\n this.apiKey = config.apiKey;\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 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 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 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\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 try {\n const instance = new SupertabConnect({\n apiKey: env.MERCHANT_API_KEY,\n botDetector: options?.botDetector,\n enforcement: options?.enforcement,\n });\n return await handleCloudflareRequest(instance, request, ctx);\n } catch (err) {\n console.error(\"[SupertabConnect] cloudflareHandleRequests failed:\", err);\n return await fetch(request);\n }\n }\n\n /**\n * Handle incoming requests for Fastly Compute.\n * @param request The incoming Fastly request\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.merchantSystemUrn Required when enableRSL is true; the merchant system URN used to fetch license.xml\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 merchantApiKey: string,\n originBackend: string,\n options?: FastlyHandlerOptions\n ): Promise<Response> {\n try {\n const { botDetector, enforcement } = options ?? {};\n\n const instance = new SupertabConnect({\n apiKey: merchantApiKey,\n botDetector,\n enforcement,\n });\n\n let rslOptions: { baseUrl: string; merchantSystemUrn: string } | undefined;\n if (options?.enableRSL) {\n rslOptions = {\n baseUrl: SupertabConnect.baseUrl,\n merchantSystemUrn: options.merchantSystemUrn,\n };\n }\n\n return await handleFastlyRequest(\n instance,\n request,\n originBackend,\n rslOptions\n );\n } catch (err) {\n console.error(\"[SupertabConnect] fastlyHandleRequests failed:\", err);\n return await fetch(request, { backend: originBackend } as RequestInit);\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 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 try {\n const instance = new SupertabConnect({\n apiKey: options.apiKey,\n botDetector: options.botDetector,\n enforcement: options.enforcement,\n });\n return await handleCloudfrontRequest(instance, event);\n } catch (err) {\n console.error(\"[SupertabConnect] cloudfrontHandleRequests failed:\", err);\n return event?.Records?.[0]?.cf?.request as TRequest ?? {} as CloudFrontRequestResult<TRequest>;\n }\n }\n}\n","import type { JWTPayload } from \"jose\";\n\nexport enum EnforcementMode {\n DISABLED = \"disabled\",\n SOFT = \"soft\",\n STRICT = \"strict\",\n}\n\nexport interface ExecutionContext {\n waitUntil(promise: Promise<void>): void;\n}\n\nexport type BotDetector = (request: Request, ctx?: ExecutionContext) => boolean;\n\nexport interface SupertabConnectConfig {\n apiKey: 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 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 properties: Record<string, string>;\n}\n\nexport type LicenseTokenVerificationResult =\n | { valid: true; licenseId?: string; payload: JWTPayload }\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\ndeclare global {\n // eslint-disable-next-line no-var\n var fastly: object | undefined;\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 botDetector?: BotDetector;\n enforcement?: EnforcementMode;\n}\n\nexport type RSLVerificationResult = {\n valid: boolean;\n error?: string;\n};\n\ninterface FastlyHandlerBaseOptions {\n botDetector?: BotDetector;\n enforcement?: EnforcementMode;\n}\n\ninterface FastlyHandlerWithRSL extends FastlyHandlerBaseOptions {\n enableRSL: true;\n merchantSystemUrn: string;\n}\n\ninterface FastlyHandlerWithoutRSL extends FastlyHandlerBaseOptions {\n enableRSL?: false;\n merchantSystemUrn?: never;\n}\n\nexport type FastlyHandlerOptions = FastlyHandlerWithRSL | FastlyHandlerWithoutRSL;\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, loadDecodeJwt } from \"./jose\";\n\ntype SupportedAlg = \"RS256\" | \"ES256\";\n\ntype CachedToken = { token: string; exp: number };\n\n// In-memory cache for license tokens, keyed by \"clientId:resourceUrl\"\nconst licenseTokenCache = new Map<string, CachedToken>();\n\nfunction getCachedToken(\n cacheKey: string,\n debug?: boolean\n): string | null {\n const cached = licenseTokenCache.get(cacheKey);\n if (!cached) return null;\n\n const now = Math.floor(Date.now() / 1000);\n if (cached.exp > now + 30) {\n if (debug) {\n console.debug(\n `Using cached license token (expires in ${cached.exp - now}s)`\n );\n }\n return cached.token;\n }\n\n if (debug) {\n console.debug(\"Cached license token expired or expiring soon, refreshing\");\n }\n licenseTokenCache.delete(cacheKey);\n return null;\n}\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: { access_token?: string };\n try {\n data = await response.json() as { access_token?: string };\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 cacheKey = `${clientId}:${resourceUrl}`;\n const cached = getCachedToken(cacheKey, debug);\n if (cached) return cached;\n\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 const token = await retrieveLicenseToken(tokenEndpoint, requestOptions, debug);\n\n try {\n const { decodeJwt } = await loadDecodeJwt();\n const claims = decodeJwt(token);\n if (claims.exp) {\n licenseTokenCache.set(cacheKey, { token, exp: claims.exp });\n }\n } catch {\n if (debug) {\n console.debug(\"Failed to decode token for caching, skipping cache\");\n }\n }\n\n return token;\n}\n\nexport type { ObtainLicenseTokenParams };\n","import type { JSONWebKeySet } from \"jose\";\nimport { FASTLY_BACKEND, FetchOptions } from \"./types\";\n\ntype JwksCacheEntry = { data: JSONWebKeySet; cachedAt: number };\nconst jwksCache = new Map<string, JwksCacheEntry>();\nconst JWKS_CACHE_TTL_MS = 48 * 60 * 60 * 1000; // 48 hours\n\nexport class JwksKeyNotFoundError extends Error {\n constructor(kid: string | undefined) {\n super(`No matching platform key found: ${kid}`);\n this.name = \"JwksKeyNotFoundError\";\n }\n}\n\ntype FetchJwksParams = {\n cacheKey: string;\n url: string;\n debug: boolean;\n failureMessage: string;\n logLabel: string;\n};\n\nfunction buildFetchOptions(): FetchOptions {\n let options: FetchOptions = { method: \"GET\" };\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<JSONWebKeySet> {\n const cached = jwksCache.get(cacheKey);\n if (cached && (Date.now() - cached.cachedAt) < JWKS_CACHE_TTL_MS) {\n return cached.data;\n }\n\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() as JSONWebKeySet;\n jwksCache.set(cacheKey, { data: jwksData, cachedAt: Date.now() });\n return jwksData;\n } catch (error) {\n if (debug) {\n console.error(logLabel, error);\n }\n throw error;\n }\n}\n\nexport async function fetchPlatformJwks(\n baseUrl: string,\n debug: boolean\n): Promise<JSONWebKeySet> {\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, FetchOptions } from \"./types\";\n\nexport async function recordEvent({\n apiKey,\n baseUrl,\n eventName,\n properties,\n licenseId,\n debug = false,\n}: {\n apiKey: string;\n baseUrl: string;\n eventName: string;\n properties: Record<string, string>;\n licenseId?: string;\n debug?: boolean;\n}): Promise<void> {\n const payload: EventPayload = {\n event_name: eventName,\n license_id: licenseId,\n properties,\n };\n\n try {\n let options: FetchOptions = {\n method: \"POST\",\n headers: {\n Authorization: `Bearer ${apiKey}`,\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(payload),\n };\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, clearJwksCache, JwksKeyNotFoundError } 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 const verify = async (): Promise<LicenseTokenVerificationResult> => {\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) => key.kid === jwtHeader.kid);\n if (!jwk) {\n throw new JwksKeyNotFoundError(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 JwksKeyNotFoundError) {\n throw 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\n try {\n return await verify();\n } catch (error) {\n if (error instanceof JwksKeyNotFoundError) {\n if (debug) {\n console.debug(\"Key not found in cached JWKS, clearing cache and retrying...\");\n }\n clearJwksCache();\n return await verify();\n }\n throw error;\n }\n}\n\nexport function generateLicenseLink({\n requestUrl,\n}: {\n requestUrl: string;\n}): string {\n try {\n const baseURL = new URL(requestUrl);\n return `${baseURL.protocol}//${baseURL.host}/license.xml`;\n } catch (err) {\n console.error(\"[SupertabConnect] generateLicenseLink failed to parse URL:\", err);\n return \"/license.xml\";\n }\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 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 try {\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 } catch (err) {\n console.error(\"[SupertabConnect] hostRSLicenseXML failed:\", err);\n return new Response(\"Bad Gateway\", { status: 502 });\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 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 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\nfunction statusDescription(status: number): string {\n switch (status) {\n case 401: return \"Unauthorized\";\n case 402: return \"Payment Required\";\n case 403: return \"Forbidden\";\n case 503: return \"Service Unavailable\";\n default: return \"Error\";\n }\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: statusDescription(result.status),\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":"skBAAA,IAAAA,GAAA,GAAAC,GAAAD,GAAA,qBAAAE,EAAA,kBAAAC,EAAA,8BAAAC,EAAA,oBAAAC,EAAA,uBAAAC,IAAA,eAAAC,GAAAP,ICEO,IAAKQ,OACVA,EAAA,SAAW,WACXA,EAAA,KAAO,OACPA,EAAA,OAAS,SAHCA,OAAA,IAuCAC,OACVA,EAAA,cAAgB,wBAChBA,EAAA,eAAiB,yBACjBA,EAAA,YAAc,4BACdA,EAAA,gBAAkB,0BAClBA,EAAA,eAAiB,yBACjBA,EAAA,8BAAgC,wCAChCA,EAAA,QAAU,wBACVA,EAAA,iBAAmB,2BACnBA,EAAA,aAAe,eATLA,OAAA,IAiBCC,EAAiB,cAOlBC,OACVA,EAAA,MAAQ,QACRA,EAAA,MAAQ,QAFEA,OAAA,IC/DZ,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,GAAgBN,EAAW,IAAM,OAAO,iBAAiB,CAAC,EAC1DO,GAAcP,EAAW,IAAM,OAAO,eAAe,CAAC,ECTnE,IAAMQ,EAAoB,IAAI,IAE9B,SAASC,GACPC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QACzB,kBAAmBI,EAAQ,iBAC7B,GAGK,MAAMuB,EACXR,EACAV,EACAc,EACAG,CACF,CACF,OAASL,EAAK,CACZ,eAAQ,MAAM,iDAAkDA,CAAG,EAC5D,MAAM,MAAMZ,EAAS,CAAE,QAASc,CAAc,CAAgB,CACvE,CACF,CAQA,aAAa,yBACXK,EACAxB,EAC4C,CAC5C,GAAI,CACF,IAAMe,EAAW,IAAInB,EAAgB,CACnC,OAAQI,EAAQ,OAChB,YAAaA,EAAQ,YACrB,YAAaA,EAAQ,WACvB,CAAC,EACD,OAAO,MAAMyB,EAAwBV,EAAUS,CAAK,CACtD,OAASP,EAAK,CACZ,eAAQ,MAAM,qDAAsDA,CAAG,EAChEO,GAAO,UAAU,CAAC,GAAG,IAAI,SAAuB,CAAC,CAC1D,CACF,CACF,EA1Ta5B,EAEI,QAAkB,kCAFtBA,EAOI,UAAoC,KAP9C,IAAM8B,EAAN9B","names":["index_exports","__export","EnforcementMode","HandlerAction","LicenseTokenInvalidReason","SupertabConnect","defaultBotDetector","__toCommonJS","EnforcementMode","LicenseTokenInvalidReason","FASTLY_BACKEND","HandlerAction","lazyImport","load","cached","loadJwtVerify","loadDecodeJwt","loadDecodeProtectedHeader","loadKeyImport","loadJwtSign","licenseTokenCache","getCachedToken","cacheKey","debug","cached","now","retrieveLicenseToken","tokenEndpoint","requestOptions","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","cacheKey","cached","getCachedToken","xml","fetchLicenseXml","contentBlocks","parseContentElements","matchedContent","findBestMatchingContent","patterns","b","tokenEndpoint","payload","requestOptions","token","retrieveLicenseToken","decodeJwt","loadDecodeJwt","claims","licenseTokenCache","jwksCache","JWKS_CACHE_TTL_MS","JwksKeyNotFoundError","kid","buildFetchOptions","options","FASTLY_BACKEND","fetchAndCacheJwks","cacheKey","url","debug","failureMessage","logLabel","cached","response","jwksData","error","fetchPlatformJwks","baseUrl","jwksUrl","clearJwksCache","recordEvent","apiKey","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","verify","jwks","fetchPlatformJwks","result","jwtHeader","jwk","key","JwksKeyNotFoundError","clearJwksCache","generateLicenseLink","baseURL","err","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","statusDescription","status","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","err","merchantApiKey","originBackend","botDetector","enforcement","rslOptions","handleFastlyRequest","event","handleCloudfrontRequest","SupertabConnect"]}
package/dist/index.d.cts CHANGED
@@ -4,7 +4,7 @@ declare enum EnforcementMode {
4
4
  STRICT = "strict"
5
5
  }
6
6
  interface ExecutionContext {
7
- waitUntil(promise: Promise<any>): void;
7
+ waitUntil(promise: Promise<void>): void;
8
8
  }
9
9
  type BotDetector = (request: Request, ctx?: ExecutionContext) => boolean;
10
10
  interface SupertabConnectConfig {
@@ -22,6 +22,20 @@ interface Env {
22
22
  MERCHANT_API_KEY: string;
23
23
  [key: string]: string;
24
24
  }
25
+ declare enum LicenseTokenInvalidReason {
26
+ MISSING_TOKEN = "missing_license_token",
27
+ INVALID_HEADER = "invalid_license_header",
28
+ INVALID_ALG = "invalid_license_algorithm",
29
+ INVALID_PAYLOAD = "invalid_license_payload",
30
+ INVALID_ISSUER = "invalid_license_issuer",
31
+ SIGNATURE_VERIFICATION_FAILED = "license_signature_verification_failed",
32
+ EXPIRED = "license_token_expired",
33
+ INVALID_AUDIENCE = "invalid_license_audience",
34
+ SERVER_ERROR = "server_error"
35
+ }
36
+ declare global {
37
+ var fastly: object | undefined;
38
+ }
25
39
  declare enum HandlerAction {
26
40
  ALLOW = "allow",
27
41
  BLOCK = "block"
@@ -219,4 +233,4 @@ declare class SupertabConnect {
219
233
  static cloudfrontHandleRequests<TRequest extends Record<string, any>>(event: CloudFrontRequestEvent<TRequest>, options: CloudfrontHandlerOptions): Promise<CloudFrontRequestResult<TRequest>>;
220
234
  }
221
235
 
222
- export { type BotDetector, type CloudFrontRequestEvent, type CloudFrontRequestResult, type CloudfrontHandlerOptions, EnforcementMode, type Env, type ExecutionContext, type FastlyHandlerOptions, HandlerAction, type HandlerResult, type RSLVerificationResult, SupertabConnect, defaultBotDetector };
236
+ export { type BotDetector, type CloudFrontRequestEvent, type CloudFrontRequestResult, type CloudfrontHandlerOptions, EnforcementMode, type Env, type ExecutionContext, type FastlyHandlerOptions, HandlerAction, type HandlerResult, LicenseTokenInvalidReason, type RSLVerificationResult, SupertabConnect, type SupertabConnectConfig, defaultBotDetector };
package/dist/index.d.ts CHANGED
@@ -4,7 +4,7 @@ declare enum EnforcementMode {
4
4
  STRICT = "strict"
5
5
  }
6
6
  interface ExecutionContext {
7
- waitUntil(promise: Promise<any>): void;
7
+ waitUntil(promise: Promise<void>): void;
8
8
  }
9
9
  type BotDetector = (request: Request, ctx?: ExecutionContext) => boolean;
10
10
  interface SupertabConnectConfig {
@@ -22,6 +22,20 @@ interface Env {
22
22
  MERCHANT_API_KEY: string;
23
23
  [key: string]: string;
24
24
  }
25
+ declare enum LicenseTokenInvalidReason {
26
+ MISSING_TOKEN = "missing_license_token",
27
+ INVALID_HEADER = "invalid_license_header",
28
+ INVALID_ALG = "invalid_license_algorithm",
29
+ INVALID_PAYLOAD = "invalid_license_payload",
30
+ INVALID_ISSUER = "invalid_license_issuer",
31
+ SIGNATURE_VERIFICATION_FAILED = "license_signature_verification_failed",
32
+ EXPIRED = "license_token_expired",
33
+ INVALID_AUDIENCE = "invalid_license_audience",
34
+ SERVER_ERROR = "server_error"
35
+ }
36
+ declare global {
37
+ var fastly: object | undefined;
38
+ }
25
39
  declare enum HandlerAction {
26
40
  ALLOW = "allow",
27
41
  BLOCK = "block"
@@ -219,4 +233,4 @@ declare class SupertabConnect {
219
233
  static cloudfrontHandleRequests<TRequest extends Record<string, any>>(event: CloudFrontRequestEvent<TRequest>, options: CloudfrontHandlerOptions): Promise<CloudFrontRequestResult<TRequest>>;
220
234
  }
221
235
 
222
- export { type BotDetector, type CloudFrontRequestEvent, type CloudFrontRequestResult, type CloudfrontHandlerOptions, EnforcementMode, type Env, type ExecutionContext, type FastlyHandlerOptions, HandlerAction, type HandlerResult, type RSLVerificationResult, SupertabConnect, defaultBotDetector };
236
+ export { type BotDetector, type CloudFrontRequestEvent, type CloudFrontRequestResult, type CloudfrontHandlerOptions, EnforcementMode, type Env, type ExecutionContext, type FastlyHandlerOptions, HandlerAction, type HandlerResult, LicenseTokenInvalidReason, type RSLVerificationResult, SupertabConnect, type SupertabConnectConfig, defaultBotDetector };
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 R="stc-backend",E=(r=>(r.ALLOW="allow",r.BLOCK="block",r))(E||{});function y(n){let e=null;return()=>(e||(e=n()),e)}var U=y(()=>import("jose/jwt/verify")),D=y(()=>import("jose/jwt/decode")),_=y(()=>import("jose/decode/protected_header")),J=y(()=>import("jose/key/import")),M=y(()=>import("jose/jwt/sign"));async function j(n,e,r){try{let t=await fetch(n,e);if(!t.ok){let s=await t.text().catch(()=>""),a=`Failed to obtain license token: ${t.status} ${t.statusText}${s?` - ${s}`:""}`;throw new Error(a)}let o;try{o=await t.json()}catch(s){throw r&&console.error("Failed to parse license token response as JSON:",s),new Error("Failed to parse license token response as JSON")}if(!o?.access_token)throw new Error("License token response missing access_token");return o.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`,o=await fetch(t);if(!o.ok)throw e&&console.error(`Failed to fetch license.xml from ${t}: ${o.status}`),new Error(`Failed to fetch license.xml from ${t}: ${o.status}`);let s=await o.text();return e&&console.debug("Fetched license.xml from",t),s}function X(n,e){let r=[],t=/<content\s([^>]*)>([\s\S]*?)<\/content>/gi,o=/url\s*=\s*"([^"]*)"/i,s=/server\s*=\s*"([^"]*)"/i,a=/<license[^>]*>[\s\S]*?<\/license>/i,i=0,c;for(;(c=t.exec(n))!==null;){i++;let l=c[1],d=c[2],p=l.match(o),g=l.match(s),m=d.match(a);if(p&&g&&m)r.push({urlPattern:p[1],server:g[1],licenseXml:m[0]});else if(e){let w=[!p&&"url",!g&&"server",!m&&"<license>"].filter(Boolean).join(", ");console.debug(`Skipping <content> element #${i}: missing ${w}`)}}return e&&console.debug(`Found ${i} <content> element(s), ${r.length} valid`),r}function z(n,e,r){let t=new URL(e),o=t.host,s=t.pathname;r&&console.debug(`Matching resource URL: ${e} (host=${o}, path=${s})`);let a=null,i=-1;for(let c of n){let l;try{l=new URL(c.urlPattern)}catch{r&&console.debug(`Skipping block with invalid URL pattern: ${c.urlPattern}`);continue}if(l.host!==o){r&&console.debug(`Skipping block: host mismatch (pattern=${l.host}, resource=${o})`);continue}let d=l.pathname;if(d===s)return r&&console.debug(`Exact match found: ${c.urlPattern}`),c;if(d.endsWith("/*")){let p=d.slice(0,-1);if(s.startsWith(p)){let g=p.length;g>i&&(i=g,a=c)}}}return r&&console.debug(a?`Wildcard match found: ${a.urlPattern} (specificity=${i})`:`No matching content block found for ${e}`),a}async function P({clientId:n,clientSecret:e,resourceUrl:r,debug:t}){let o=await G(r,t);t&&console.debug(`Fetched license.xml (${o.length} chars)`);let s=X(o,t);if(s.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(s,r,t);if(!a){if(t){let d=s.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 i=a.server+"/token";t&&console.debug(`Requesting license token from ${i}`);let c=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:c.toString()};return j(i,l,t)}var I=new Map;function Y(){let n={method:"GET"};return globalThis?.fastly&&(n={...n,backend:R}),n}async function Q({cacheKey:n,url:e,debug:r,failureMessage:t,logLabel:o}){if(!I.has(n))try{let s=await fetch(e,Y());if(!s.ok)throw new Error(`${t}: ${s.status}`);let a=await s.json();I.set(n,a)}catch(s){throw r&&console.error(o,s),s}return I.get(n)}async function q(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 F({apiKey:n,baseUrl:e,eventName:r,properties:t,licenseId:o,debug:s=!1}){let a={event_name:r,license_id:o,properties:t};try{let i={method:"POST",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"},body:JSON.stringify(a)};globalThis?.fastly&&(i={...i,backend:R});let c=await fetch(`${e}/events`,i);!c.ok&&s&&console.error(`Failed to record event: ${c.status}`)}catch(i){s&&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:o}=await _(),{decodeJwt:s}=await D(),{jwtVerify:a}=await U();if(!n)return{valid:!1,reason:"missing_license_token",error:h("missing_license_token")};let i;try{i=o(n)}catch(f){return t&&console.error("Invalid license JWT header:",f),{valid:!1,reason:"invalid_license_header",error:h("invalid_license_header")}}if(i.alg!=="ES256")return t&&console.error("Unsupported license JWT alg:",i.alg),{valid:!1,reason:"invalid_license_algorithm",error:h("invalid_license_algorithm")};let c;try{c=s(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=c.license_id,d=c.iss,p=d?L(d):void 0,g=L(r);if(!p||!p.startsWith(g))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 m=Array.isArray(c.aud)?c.aud.filter(f=>typeof f=="string"):typeof c.aud=="string"?[c.aud]:[],w=L(e);if(!m.some(f=>{let b=L(f);return b?w.startsWith(b):!1}))return t&&console.error("License JWT audience does not match request URL:",c.aud),{valid:!1,reason:"invalid_license_audience",error:h("invalid_license_audience"),licenseId:l};let S;try{S=await q(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 v=>{let T=S.keys.find(W=>W.kid===v.kid);if(!T)throw new Error(`No matching platform key found: ${v.kid}`);return T},{issuer:d,algorithms:[i.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 N({requestUrl:n}){try{let e=new URL(n);return`${e.protocol}//${e.host}/license.xml`}catch(e){return console.error("[SupertabConnect] generateLicenseLink failed to parse URL:",e),"/license.xml"}}function O(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 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 x({reason:n,error:e,requestUrl:r}){let{rslError:t,status:o}=ee(n),s=te(e),a=N({requestUrl:r});return{action:"block",status:o,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="${s}"`,Link:`<${a}>; rel="license"; type="application/rsl+xml"`}}}function re(){let n={method:"GET"};return globalThis?.fastly&&(n={...n,backend:R}),n}async function H(n,e){try{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 o=await t.text();return new Response(o,{status:200,headers:new Headers({"Content-Type":"application/xml"})})}catch(r){return console.error("[SupertabConnect] hostRSLicenseXML failed:",r),new Response("Bad Gateway",{status:502})}}async function k(n){let e=await A({licenseToken:n.token,requestUrl:n.url,supertabBaseUrl:n.supertabBaseUrl,debug:n.debug}),r=F({apiKey:n.apiKey,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 B(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 o=await fetch(e);if(t.headers){let s=new Response(o.body,o);for(let[a,i]of Object.entries(t.headers))s.headers.set(a,i);return s}return o}async function K(n,e,r,t){if(t&&new URL(e.url).pathname==="/license.xml")return await H(t.baseUrl,t.merchantSystemUrn);let o=await n.handleRequest(e);if(o.action==="block")return new Response(o.body,{status:o.status,headers:new Headers(o.headers)});let s=await fetch(e,{backend:r});if(o.headers){let a=new Response(s.body,s);for(let[i,c]of Object.entries(o.headers))a.headers.set(i,c);return a}return s}async function V(n,e){let r=e.Records[0].cf.request,t=`https://${r.headers.host[0].value}${r.uri}${r.querystring?"?"+r.querystring:""}`,o=new Headers;Object.entries(r.headers).forEach(([i,c])=>{c.forEach(({value:l})=>o.append(i,l))});let s=new Request(t,{method:r.method,headers:o}),a=await n.handleRequest(s);if(a.action==="block"){let i={};return Object.entries(a.headers).forEach(([c,l])=>{i[c.toLowerCase()]=[{key:c,value:l}]}),{status:a.status.toString(),statusDescription:a.status===401?"Unauthorized":"Payment Required",headers:i,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"),o=n.headers.get("accept-language"),s=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"],i=e.toLowerCase(),c=a.some(m=>i.includes(m)),l=i.includes("headless")||i.includes("puppeteer")||!t,d=!i.includes("headless")&&!i.includes("puppeteer")&&!t,p=!r||!o,g=typeof s=="number"&&s<30;return(i.includes("safari")||i.includes("mozilla"))&&l&&d?!1:c||l||p||g}var u=class u{constructor(e,r=!1){if(!r&&u._instance){if(e.apiKey!==u._instance.apiKey)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)throw new Error("Missing required configuration: apiKey is required");this.apiKey=e.apiKey,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,ctx:e.ctx});return r.valid?{valid:!0}:{valid:!1,error:r.error}}async handleRequest(e,r){let t=e.headers.get("Authorization")||"",o=t.startsWith("License ")?t.slice(8):null,s=e.url,a=e.headers.get("User-Agent")||"unknown";if(o){if(this.enforcement==="disabled")return{action:"allow"};let c=await k({token:o,url:s,userAgent:a,supertabBaseUrl:u.baseUrl,debug:this.debug,apiKey:this.apiKey,ctx:r});return c.valid?{action:"allow"}:x({reason:c.reason,error:c.error,requestUrl:s})}if(!(this.botDetector?.(e,r)??!1))return{action:"allow"};switch(this.enforcement){case"strict":return x({reason:"missing_license_token",error:"Authorization header missing or malformed",requestUrl:s});case"soft":return O(s);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,o){try{let s=new u({apiKey:r.MERCHANT_API_KEY,botDetector:o?.botDetector,enforcement:o?.enforcement});return await B(s,e,t)}catch(s){return console.error("[SupertabConnect] cloudflareHandleRequests failed:",s),await fetch(e)}}static async fastlyHandleRequests(e,r,t,o){try{let{botDetector:s,enforcement:a}=o??{},i=new u({apiKey:r,botDetector:s,enforcement:a}),c;return o?.enableRSL&&(c={baseUrl:u.baseUrl,merchantSystemUrn:o.merchantSystemUrn}),await K(i,e,t,c)}catch(s){return console.error("[SupertabConnect] fastlyHandleRequests failed:",s),await fetch(e,{backend:t})}}static async cloudfrontHandleRequests(e,r){try{let t=new u({apiKey:r.apiKey,botDetector:r.botDetector,enforcement:r.enforcement});return await V(t,e)}catch(t){return console.error("[SupertabConnect] cloudfrontHandleRequests failed:",t),e?.Records?.[0]?.cf?.request??{}}}};u.baseUrl="https://api-connect.supertab.co",u._instance=null;var $=u;export{C as EnforcementMode,E as HandlerAction,$ as SupertabConnect,ne as defaultBotDetector};
1
+ var P=(t=>(t.DISABLED="disabled",t.SOFT="soft",t.STRICT="strict",t))(P||{}),I=(l=>(l.MISSING_TOKEN="missing_license_token",l.INVALID_HEADER="invalid_license_header",l.INVALID_ALG="invalid_license_algorithm",l.INVALID_PAYLOAD="invalid_license_payload",l.INVALID_ISSUER="invalid_license_issuer",l.SIGNATURE_VERIFICATION_FAILED="license_signature_verification_failed",l.EXPIRED="license_token_expired",l.INVALID_AUDIENCE="invalid_license_audience",l.SERVER_ERROR="server_error",l))(I||{}),b="stc-backend",L=(r=>(r.ALLOW="allow",r.BLOCK="block",r))(L||{});function w(n){let e=null;return()=>(e||(e=n()),e)}var q=w(()=>import("jose/jwt/verify")),k=w(()=>import("jose/jwt/decode")),F=w(()=>import("jose/decode/protected_header")),z=w(()=>import("jose/key/import")),Y=w(()=>import("jose/jwt/sign"));var S=new Map;function Q(n,e){let r=S.get(n);if(!r)return null;let t=Math.floor(Date.now()/1e3);return r.exp>t+30?(e&&console.debug(`Using cached license token (expires in ${r.exp-t}s)`),r.token):(e&&console.debug("Cached license token expired or expiring soon, refreshing"),S.delete(n),null)}async function Z(n,e,r){try{let t=await fetch(n,e);if(!t.ok){let o=await t.text().catch(()=>""),c=`Failed to obtain license token: ${t.status} ${t.statusText}${o?` - ${o}`:""}`;throw new Error(c)}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 ee(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 te(n,e){let r=[],t=/<content\s([^>]*)>([\s\S]*?)<\/content>/gi,s=/url\s*=\s*"([^"]*)"/i,o=/server\s*=\s*"([^"]*)"/i,c=/<license[^>]*>[\s\S]*?<\/license>/i,i=0,a;for(;(a=t.exec(n))!==null;){i++;let l=a[1],d=a[2],p=l.match(s),f=l.match(o),g=d.match(c);if(p&&f&&g)r.push({urlPattern:p[1],server:f[1],licenseXml:g[0]});else if(e){let R=[!p&&"url",!f&&"server",!g&&"<license>"].filter(Boolean).join(", ");console.debug(`Skipping <content> element #${i}: missing ${R}`)}}return e&&console.debug(`Found ${i} <content> element(s), ${r.length} valid`),r}function re(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 c=null,i=-1;for(let a of n){let l;try{l=new URL(a.urlPattern)}catch{r&&console.debug(`Skipping block with invalid URL pattern: ${a.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: ${a.urlPattern}`),a;if(d.endsWith("/*")){let p=d.slice(0,-1);if(o.startsWith(p)){let f=p.length;f>i&&(i=f,c=a)}}}return r&&console.debug(c?`Wildcard match found: ${c.urlPattern} (specificity=${i})`:`No matching content block found for ${e}`),c}async function O({clientId:n,clientSecret:e,resourceUrl:r,debug:t}){let s=`${n}:${r}`,o=Q(s,t);if(o)return o;let c=await ee(r,t);t&&console.debug(`Fetched license.xml (${c.length} chars)`);let i=te(c,t);if(i.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=re(i,r,t);if(!a){if(t){let g=i.map(R=>R.urlPattern).join(", ");console.error(`No <content> element matches resource URL: ${r}. Available patterns: ${g}`)}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 l=a.server+"/token";t&&console.debug(`Requesting license token from ${l}`);let d=new URLSearchParams({grant_type:"client_credentials",license:a.licenseXml,resource:a.urlPattern}),p={method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json",Authorization:"Basic "+btoa(`${n}:${e}`)},body:d.toString()},f=await Z(l,p,t);try{let{decodeJwt:g}=await k(),R=g(f);R.exp&&S.set(s,{token:f,exp:R.exp})}catch{t&&console.debug("Failed to decode token for caching, skipping cache")}return f}var A=new Map,ne=48*60*60*1e3,E=class extends Error{constructor(e){super(`No matching platform key found: ${e}`),this.name="JwksKeyNotFoundError"}};function se(){let n={method:"GET"};return globalThis.fastly&&(n={...n,backend:b}),n}async function oe({cacheKey:n,url:e,debug:r,failureMessage:t,logLabel:s}){let o=A.get(n);if(o&&Date.now()-o.cachedAt<ne)return o.data;try{let c=await fetch(e,se());if(!c.ok)throw new Error(`${t}: ${c.status}`);let i=await c.json();return A.set(n,{data:i,cachedAt:Date.now()}),i}catch(c){throw r&&console.error(s,c),c}}async function N(n,e){let r=`${n}/.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:"})}function H(){A.clear()}async function K({apiKey:n,baseUrl:e,eventName:r,properties:t,licenseId:s,debug:o=!1}){let c={event_name:r,license_id:s,properties:t};try{let i={method:"POST",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"},body:JSON.stringify(c)};globalThis.fastly&&(i={...i,backend:b});let a=await fetch(`${e}/events`,i);!a.ok&&o&&console.error(`Failed to record event: ${a.status}`)}catch(i){o&&console.error("Error recording event:",i)}}var x=n=>n.trim().replace(/\/+$/,"");function y(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 v({licenseToken:n,requestUrl:e,supertabBaseUrl:r,debug:t}){let{decodeProtectedHeader:s}=await F(),{decodeJwt:o}=await k(),{jwtVerify:c}=await q();if(!n)return{valid:!1,reason:"missing_license_token",error:y("missing_license_token")};let i;try{i=s(n)}catch(h){return t&&console.error("Invalid license JWT header:",h),{valid:!1,reason:"invalid_license_header",error:y("invalid_license_header")}}if(i.alg!=="ES256")return t&&console.error("Unsupported license JWT alg:",i.alg),{valid:!1,reason:"invalid_license_algorithm",error:y("invalid_license_algorithm")};let a;try{a=o(n)}catch(h){return t&&console.error("Invalid license JWT payload:",h),{valid:!1,reason:"invalid_license_payload",error:y("invalid_license_payload")}}let l=a.license_id,d=a.iss,p=d?x(d):void 0,f=x(r);if(!p||!p.startsWith(f))return t&&console.error("License JWT issuer is missing or malformed:",d),{valid:!1,reason:"invalid_license_issuer",error:y("invalid_license_issuer"),licenseId:l};let g=Array.isArray(a.aud)?a.aud.filter(h=>typeof h=="string"):typeof a.aud=="string"?[a.aud]:[],R=x(e);if(!g.some(h=>{let m=x(h);return m?R.startsWith(m):!1}))return t&&console.error("License JWT audience does not match request URL:",a.aud),{valid:!1,reason:"invalid_license_audience",error:y("invalid_license_audience"),licenseId:l};let U=async()=>{let h;try{h=await N(r,t)}catch(m){return t&&console.error("Failed to fetch platform JWKS:",m),{valid:!1,reason:"server_error",error:y("server_error"),licenseId:l}}try{let G=await c(n,async D=>{let _=h.keys.find(X=>X.kid===D.kid);if(!_)throw new E(D.kid);return _},{issuer:d,algorithms:[i.alg],clockTolerance:"1m"});return{valid:!0,licenseId:l,payload:G.payload}}catch(m){if(t&&console.error("License JWT verification failed:",m),m instanceof E)throw m;return m instanceof Error&&m.message?.includes("exp")?{valid:!1,reason:"license_token_expired",error:y("license_token_expired"),licenseId:l}:{valid:!1,reason:"license_signature_verification_failed",error:y("license_signature_verification_failed"),licenseId:l}}};try{return await U()}catch(h){if(h instanceof E)return t&&console.debug("Key not found in cached JWKS, clearing cache and retrying..."),H(),await U();throw h}}function $({requestUrl:n}){try{let e=new URL(n);return`${e.protocol}//${e.host}/license.xml`}catch(e){return console.error("[SupertabConnect] generateLicenseLink failed to parse URL:",e),"/license.xml"}}function B(n){let e=$({requestUrl:n});return{action:"allow",headers:{Link:`<${e}>; rel="license"; type="application/rsl+xml"`,"X-RSL-Status":"token_required","X-RSL-Reason":"missing"}}}function ie(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 ae(n){return n.replace(/[\r\n]/g,"").replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function T({reason:n,error:e,requestUrl:r}){let{rslError:t,status:s}=ie(n),o=ae(e),c=$({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:`<${c}>; rel="license"; type="application/rsl+xml"`}}}function ce(){let n={method:"GET"};return globalThis.fastly&&(n={...n,backend:b}),n}async function V(n,e){try{let r=`${n}/merchants/systems/${e}/license.xml`,t=await fetch(r,ce());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"})})}catch(r){return console.error("[SupertabConnect] hostRSLicenseXML failed:",r),new Response("Bad Gateway",{status:502})}}async function C(n){let e=await v({licenseToken:n.token,requestUrl:n.url,supertabBaseUrl:n.supertabBaseUrl,debug:n.debug}),r=K({apiKey:n.apiKey,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 J(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[c,i]of Object.entries(t.headers))o.headers.set(c,i);return o}return s}async function W(n,e,r,t){if(t&&new URL(e.url).pathname==="/license.xml")return await V(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 c=new Response(o.body,o);for(let[i,a]of Object.entries(s.headers))c.headers.set(i,a);return c}return o}function le(n){switch(n){case 401:return"Unauthorized";case 402:return"Payment Required";case 403:return"Forbidden";case 503:return"Service Unavailable";default:return"Error"}}async function M(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(([i,a])=>{a.forEach(({value:l})=>s.append(i,l))});let o=new Request(t,{method:r.method,headers:s}),c=await n.handleRequest(o);if(c.action==="block"){let i={};return Object.entries(c.headers).forEach(([a,l])=>{i[a.toLowerCase()]=[{key:a,value:l}]}),{status:c.status.toString(),statusDescription:le(c.status),headers:i,body:c.body}}return r}function ue(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,c=["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"],i=e.toLowerCase(),a=c.some(g=>i.includes(g)),l=i.includes("headless")||i.includes("puppeteer")||!t,d=!i.includes("headless")&&!i.includes("puppeteer")&&!t,p=!r||!s,f=typeof o=="number"&&o<30;return(i.includes("safari")||i.includes("mozilla"))&&l&&d?!1:a||l||p||f}var u=class u{constructor(e,r=!1){if(!r&&u._instance){if(e.apiKey!==u._instance.apiKey)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)throw new Error("Missing required configuration: apiKey is required");this.apiKey=e.apiKey,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 v({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 C({token:e.token,url:e.resourceUrl,userAgent:e.userAgent??"unknown",supertabBaseUrl:u.baseUrl,debug:e.debug??this.debug,apiKey:this.apiKey,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,c=e.headers.get("User-Agent")||"unknown";if(s){if(this.enforcement==="disabled")return{action:"allow"};let a=await C({token:s,url:o,userAgent:c,supertabBaseUrl:u.baseUrl,debug:this.debug,apiKey:this.apiKey,ctx:r});return a.valid?{action:"allow"}:T({reason:a.reason,error:a.error,requestUrl:o})}if(!(this.botDetector?.(e,r)??!1))return{action:"allow"};switch(this.enforcement){case"strict":return T({reason:"missing_license_token",error:"Authorization header missing or malformed",requestUrl:o});case"soft":return B(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,t,s){try{let o=new u({apiKey:r.MERCHANT_API_KEY,botDetector:s?.botDetector,enforcement:s?.enforcement});return await J(o,e,t)}catch(o){return console.error("[SupertabConnect] cloudflareHandleRequests failed:",o),await fetch(e)}}static async fastlyHandleRequests(e,r,t,s){try{let{botDetector:o,enforcement:c}=s??{},i=new u({apiKey:r,botDetector:o,enforcement:c}),a;return s?.enableRSL&&(a={baseUrl:u.baseUrl,merchantSystemUrn:s.merchantSystemUrn}),await W(i,e,t,a)}catch(o){return console.error("[SupertabConnect] fastlyHandleRequests failed:",o),await fetch(e,{backend:t})}}static async cloudfrontHandleRequests(e,r){try{let t=new u({apiKey:r.apiKey,botDetector:r.botDetector,enforcement:r.enforcement});return await M(t,e)}catch(t){return console.error("[SupertabConnect] cloudfrontHandleRequests failed:",t),e?.Records?.[0]?.cf?.request??{}}}};u.baseUrl="https://api-connect.supertab.co",u._instance=null;var j=u;export{P as EnforcementMode,L as HandlerAction,I as LicenseTokenInvalidReason,j as SupertabConnect,ue 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 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 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 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 botDetector?: BotDetector;\n enforcement?: EnforcementMode;\n}\n\nexport type RSLVerificationResult = {\n valid: boolean;\n error?: string;\n};\n\ninterface FastlyHandlerBaseOptions {\n botDetector?: BotDetector;\n enforcement?: EnforcementMode;\n}\n\ninterface FastlyHandlerWithRSL extends FastlyHandlerBaseOptions {\n enableRSL: true;\n merchantSystemUrn: string;\n}\n\ninterface FastlyHandlerWithoutRSL extends FastlyHandlerBaseOptions {\n enableRSL?: false;\n merchantSystemUrn?: never;\n}\n\nexport type FastlyHandlerOptions = FastlyHandlerWithRSL | FastlyHandlerWithoutRSL;\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 baseUrl,\n eventName,\n properties,\n licenseId,\n debug = false,\n}: {\n apiKey: 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 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 try {\n const baseURL = new URL(requestUrl);\n return `${baseURL.protocol}//${baseURL.host}/license.xml`;\n } catch (err) {\n console.error(\"[SupertabConnect] generateLicenseLink failed to parse URL:\", err);\n return \"/license.xml\";\n }\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 try {\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 } catch (err) {\n console.error(\"[SupertabConnect] hostRSLicenseXML failed:\", err);\n return new Response(\"Bad Gateway\", { status: 502 });\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 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 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 FastlyHandlerOptions,\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 FastlyHandlerOptions,\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 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\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 (config.apiKey !== SupertabConnect._instance.apiKey) {\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) {\n throw new Error(\n \"Missing required configuration: apiKey is required\"\n );\n }\n this.apiKey = config.apiKey;\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 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 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 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\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 try {\n const instance = new SupertabConnect({\n apiKey: env.MERCHANT_API_KEY,\n botDetector: options?.botDetector,\n enforcement: options?.enforcement,\n });\n return await handleCloudflareRequest(instance, request, ctx);\n } catch (err) {\n console.error(\"[SupertabConnect] cloudflareHandleRequests failed:\", err);\n return await fetch(request);\n }\n }\n\n /**\n * Handle incoming requests for Fastly Compute.\n * @param request The incoming Fastly request\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.merchantSystemUrn Required when enableRSL is true; the merchant system URN used to fetch license.xml\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 merchantApiKey: string,\n originBackend: string,\n options?: FastlyHandlerOptions\n ): Promise<Response> {\n try {\n const { botDetector, enforcement } = options ?? {};\n\n const instance = new SupertabConnect({\n apiKey: merchantApiKey,\n botDetector,\n enforcement,\n });\n\n let rslOptions: { baseUrl: string; merchantSystemUrn: string } | undefined;\n if (options?.enableRSL) {\n rslOptions = {\n baseUrl: SupertabConnect.baseUrl,\n merchantSystemUrn: options.merchantSystemUrn,\n };\n }\n\n return await handleFastlyRequest(\n instance,\n request,\n originBackend,\n rslOptions\n );\n } catch (err) {\n console.error(\"[SupertabConnect] fastlyHandleRequests failed:\", err);\n return await fetch(request, { backend: originBackend } as RequestInit);\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 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 try {\n const instance = new SupertabConnect({\n apiKey: options.apiKey,\n botDetector: options.botDetector,\n enforcement: options.enforcement,\n });\n return await handleCloudfrontRequest(instance, event);\n } catch (err) {\n console.error(\"[SupertabConnect] cloudfrontHandleRequests failed:\", err);\n return event?.Records?.[0]?.cf?.request as TRequest ?? {} as CloudFrontRequestResult<TRequest>;\n }\n }\n}\n"],"mappings":"AAAO,IAAKA,OACVA,EAAA,SAAW,WACXA,EAAA,KAAO,OACPA,EAAA,OAAS,SAHCA,OAAA,IAmDL,IAAMC,EAAiB,cAOlBC,OACVA,EAAA,MAAQ,QACRA,EAAA,MAAQ,QAFEA,OAAA,ICxDZ,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,EAA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,CAAG,EAC5D,MAAM,MAAMZ,EAAS,CAAE,QAASc,CAAc,CAAgB,CACvE,CACF,CAQA,aAAa,yBACXK,EACAxB,EAC4C,CAC5C,GAAI,CACF,IAAMe,EAAW,IAAInB,EAAgB,CACnC,OAAQI,EAAQ,OAChB,YAAaA,EAAQ,YACrB,YAAaA,EAAQ,WACvB,CAAC,EACD,OAAO,MAAMyB,EAAwBV,EAAUS,CAAK,CACtD,OAASP,EAAK,CACZ,eAAQ,MAAM,qDAAsDA,CAAG,EAChEO,GAAO,UAAU,CAAC,GAAG,IAAI,SAAuB,CAAC,CAC1D,CACF,CACF,EA1Ta5B,EAEI,QAAkB,kCAFtBA,EAOI,UAAoC,KAP9C,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","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","err","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","err","merchantApiKey","originBackend","botDetector","enforcement","rslOptions","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":["import type { JWTPayload } from \"jose\";\n\nexport enum EnforcementMode {\n DISABLED = \"disabled\",\n SOFT = \"soft\",\n STRICT = \"strict\",\n}\n\nexport interface ExecutionContext {\n waitUntil(promise: Promise<void>): void;\n}\n\nexport type BotDetector = (request: Request, ctx?: ExecutionContext) => boolean;\n\nexport interface SupertabConnectConfig {\n apiKey: 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 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 properties: Record<string, string>;\n}\n\nexport type LicenseTokenVerificationResult =\n | { valid: true; licenseId?: string; payload: JWTPayload }\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\ndeclare global {\n // eslint-disable-next-line no-var\n var fastly: object | undefined;\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 botDetector?: BotDetector;\n enforcement?: EnforcementMode;\n}\n\nexport type RSLVerificationResult = {\n valid: boolean;\n error?: string;\n};\n\ninterface FastlyHandlerBaseOptions {\n botDetector?: BotDetector;\n enforcement?: EnforcementMode;\n}\n\ninterface FastlyHandlerWithRSL extends FastlyHandlerBaseOptions {\n enableRSL: true;\n merchantSystemUrn: string;\n}\n\ninterface FastlyHandlerWithoutRSL extends FastlyHandlerBaseOptions {\n enableRSL?: false;\n merchantSystemUrn?: never;\n}\n\nexport type FastlyHandlerOptions = FastlyHandlerWithRSL | FastlyHandlerWithoutRSL;\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, loadDecodeJwt } from \"./jose\";\n\ntype SupportedAlg = \"RS256\" | \"ES256\";\n\ntype CachedToken = { token: string; exp: number };\n\n// In-memory cache for license tokens, keyed by \"clientId:resourceUrl\"\nconst licenseTokenCache = new Map<string, CachedToken>();\n\nfunction getCachedToken(\n cacheKey: string,\n debug?: boolean\n): string | null {\n const cached = licenseTokenCache.get(cacheKey);\n if (!cached) return null;\n\n const now = Math.floor(Date.now() / 1000);\n if (cached.exp > now + 30) {\n if (debug) {\n console.debug(\n `Using cached license token (expires in ${cached.exp - now}s)`\n );\n }\n return cached.token;\n }\n\n if (debug) {\n console.debug(\"Cached license token expired or expiring soon, refreshing\");\n }\n licenseTokenCache.delete(cacheKey);\n return null;\n}\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: { access_token?: string };\n try {\n data = await response.json() as { access_token?: string };\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 cacheKey = `${clientId}:${resourceUrl}`;\n const cached = getCachedToken(cacheKey, debug);\n if (cached) return cached;\n\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 const token = await retrieveLicenseToken(tokenEndpoint, requestOptions, debug);\n\n try {\n const { decodeJwt } = await loadDecodeJwt();\n const claims = decodeJwt(token);\n if (claims.exp) {\n licenseTokenCache.set(cacheKey, { token, exp: claims.exp });\n }\n } catch {\n if (debug) {\n console.debug(\"Failed to decode token for caching, skipping cache\");\n }\n }\n\n return token;\n}\n\nexport type { ObtainLicenseTokenParams };\n","import type { JSONWebKeySet } from \"jose\";\nimport { FASTLY_BACKEND, FetchOptions } from \"./types\";\n\ntype JwksCacheEntry = { data: JSONWebKeySet; cachedAt: number };\nconst jwksCache = new Map<string, JwksCacheEntry>();\nconst JWKS_CACHE_TTL_MS = 48 * 60 * 60 * 1000; // 48 hours\n\nexport class JwksKeyNotFoundError extends Error {\n constructor(kid: string | undefined) {\n super(`No matching platform key found: ${kid}`);\n this.name = \"JwksKeyNotFoundError\";\n }\n}\n\ntype FetchJwksParams = {\n cacheKey: string;\n url: string;\n debug: boolean;\n failureMessage: string;\n logLabel: string;\n};\n\nfunction buildFetchOptions(): FetchOptions {\n let options: FetchOptions = { method: \"GET\" };\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<JSONWebKeySet> {\n const cached = jwksCache.get(cacheKey);\n if (cached && (Date.now() - cached.cachedAt) < JWKS_CACHE_TTL_MS) {\n return cached.data;\n }\n\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() as JSONWebKeySet;\n jwksCache.set(cacheKey, { data: jwksData, cachedAt: Date.now() });\n return jwksData;\n } catch (error) {\n if (debug) {\n console.error(logLabel, error);\n }\n throw error;\n }\n}\n\nexport async function fetchPlatformJwks(\n baseUrl: string,\n debug: boolean\n): Promise<JSONWebKeySet> {\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, FetchOptions } from \"./types\";\n\nexport async function recordEvent({\n apiKey,\n baseUrl,\n eventName,\n properties,\n licenseId,\n debug = false,\n}: {\n apiKey: string;\n baseUrl: string;\n eventName: string;\n properties: Record<string, string>;\n licenseId?: string;\n debug?: boolean;\n}): Promise<void> {\n const payload: EventPayload = {\n event_name: eventName,\n license_id: licenseId,\n properties,\n };\n\n try {\n let options: FetchOptions = {\n method: \"POST\",\n headers: {\n Authorization: `Bearer ${apiKey}`,\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(payload),\n };\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, clearJwksCache, JwksKeyNotFoundError } 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 const verify = async (): Promise<LicenseTokenVerificationResult> => {\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) => key.kid === jwtHeader.kid);\n if (!jwk) {\n throw new JwksKeyNotFoundError(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 JwksKeyNotFoundError) {\n throw 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\n try {\n return await verify();\n } catch (error) {\n if (error instanceof JwksKeyNotFoundError) {\n if (debug) {\n console.debug(\"Key not found in cached JWKS, clearing cache and retrying...\");\n }\n clearJwksCache();\n return await verify();\n }\n throw error;\n }\n}\n\nexport function generateLicenseLink({\n requestUrl,\n}: {\n requestUrl: string;\n}): string {\n try {\n const baseURL = new URL(requestUrl);\n return `${baseURL.protocol}//${baseURL.host}/license.xml`;\n } catch (err) {\n console.error(\"[SupertabConnect] generateLicenseLink failed to parse URL:\", err);\n return \"/license.xml\";\n }\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 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 try {\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 } catch (err) {\n console.error(\"[SupertabConnect] hostRSLicenseXML failed:\", err);\n return new Response(\"Bad Gateway\", { status: 502 });\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 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 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\nfunction statusDescription(status: number): string {\n switch (status) {\n case 401: return \"Unauthorized\";\n case 402: return \"Payment Required\";\n case 403: return \"Forbidden\";\n case 503: return \"Service Unavailable\";\n default: return \"Error\";\n }\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: statusDescription(result.status),\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 FastlyHandlerOptions,\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, LicenseTokenInvalidReason };\nexport type {\n SupertabConnectConfig,\n RSLVerificationResult,\n ExecutionContext,\n Env,\n BotDetector,\n HandlerResult,\n FastlyHandlerOptions,\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 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\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 (config.apiKey !== SupertabConnect._instance.apiKey) {\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) {\n throw new Error(\n \"Missing required configuration: apiKey is required\"\n );\n }\n this.apiKey = config.apiKey;\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 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 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 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\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 try {\n const instance = new SupertabConnect({\n apiKey: env.MERCHANT_API_KEY,\n botDetector: options?.botDetector,\n enforcement: options?.enforcement,\n });\n return await handleCloudflareRequest(instance, request, ctx);\n } catch (err) {\n console.error(\"[SupertabConnect] cloudflareHandleRequests failed:\", err);\n return await fetch(request);\n }\n }\n\n /**\n * Handle incoming requests for Fastly Compute.\n * @param request The incoming Fastly request\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.merchantSystemUrn Required when enableRSL is true; the merchant system URN used to fetch license.xml\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 merchantApiKey: string,\n originBackend: string,\n options?: FastlyHandlerOptions\n ): Promise<Response> {\n try {\n const { botDetector, enforcement } = options ?? {};\n\n const instance = new SupertabConnect({\n apiKey: merchantApiKey,\n botDetector,\n enforcement,\n });\n\n let rslOptions: { baseUrl: string; merchantSystemUrn: string } | undefined;\n if (options?.enableRSL) {\n rslOptions = {\n baseUrl: SupertabConnect.baseUrl,\n merchantSystemUrn: options.merchantSystemUrn,\n };\n }\n\n return await handleFastlyRequest(\n instance,\n request,\n originBackend,\n rslOptions\n );\n } catch (err) {\n console.error(\"[SupertabConnect] fastlyHandleRequests failed:\", err);\n return await fetch(request, { backend: originBackend } as RequestInit);\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 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 try {\n const instance = new SupertabConnect({\n apiKey: options.apiKey,\n botDetector: options.botDetector,\n enforcement: options.enforcement,\n });\n return await handleCloudfrontRequest(instance, event);\n } catch (err) {\n console.error(\"[SupertabConnect] cloudfrontHandleRequests failed:\", err);\n return event?.Records?.[0]?.cf?.request as TRequest ?? {} as CloudFrontRequestResult<TRequest>;\n }\n }\n}\n"],"mappings":"AAEO,IAAKA,OACVA,EAAA,SAAW,WACXA,EAAA,KAAO,OACPA,EAAA,OAAS,SAHCA,OAAA,IAuCAC,OACVA,EAAA,cAAgB,wBAChBA,EAAA,eAAiB,yBACjBA,EAAA,YAAc,4BACdA,EAAA,gBAAkB,0BAClBA,EAAA,eAAiB,yBACjBA,EAAA,8BAAgC,wCAChCA,EAAA,QAAU,wBACVA,EAAA,iBAAmB,2BACnBA,EAAA,aAAe,eATLA,OAAA,IAiBCC,EAAiB,cAOlBC,OACVA,EAAA,MAAQ,QACRA,EAAA,MAAQ,QAFEA,OAAA,IC/DZ,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,ECTnE,IAAMQ,EAAoB,IAAI,IAE9B,SAASC,EACPC,EACAC,EACe,CACf,IAAMC,EAASJ,EAAkB,IAAIE,CAAQ,EAC7C,GAAI,CAACE,EAAQ,OAAO,KAEpB,IAAMC,EAAM,KAAK,MAAM,KAAK,IAAI,EAAI,GAAI,EACxC,OAAID,EAAO,IAAMC,EAAM,IACjBF,GACF,QAAQ,MACN,0CAA0CC,EAAO,IAAMC,CAAG,IAC5D,EAEKD,EAAO,Q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,EAAW,IAAInB,EAAgB,CACnC,OAAQI,EAAQ,OAChB,YAAaA,EAAQ,YACrB,YAAaA,EAAQ,WACvB,CAAC,EACD,OAAO,MAAMyB,EAAwBV,EAAUS,CAAK,CACtD,OAASP,EAAK,CACZ,eAAQ,MAAM,qDAAsDA,CAAG,EAChEO,GAAO,UAAU,CAAC,GAAG,IAAI,SAAuB,CAAC,CAC1D,CACF,CACF,EA1Ta5B,EAEI,QAAkB,kCAFtBA,EAOI,UAAoC,KAP9C,IAAM8B,EAAN9B","names":["EnforcementMode","LicenseTokenInvalidReason","FASTLY_BACKEND","HandlerAction","lazyImport","load","cached","loadJwtVerify","loadDecodeJwt","loadDecodeProtectedHeader","loadKeyImport","loadJwtSign","licenseTokenCache","getCachedToken","cacheKey","debug","cached","now","retrieveLicenseToken","tokenEndpoint","requestOptions","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","cacheKey","cached","getCachedToken","xml","fetchLicenseXml","contentBlocks","parseContentElements","matchedContent","findBestMatchingContent","patterns","b","tokenEndpoint","payload","requestOptions","token","retrieveLicenseToken","decodeJwt","loadDecodeJwt","claims","licenseTokenCache","jwksCache","JWKS_CACHE_TTL_MS","JwksKeyNotFoundError","kid","buildFetchOptions","options","FASTLY_BACKEND","fetchAndCacheJwks","cacheKey","url","debug","failureMessage","logLabel","cached","response","jwksData","error","fetchPlatformJwks","baseUrl","jwksUrl","clearJwksCache","recordEvent","apiKey","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","verify","jwks","fetchPlatformJwks","result","jwtHeader","jwk","key","JwksKeyNotFoundError","clearJwksCache","generateLicenseLink","baseURL","err","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","statusDescription","status","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","err","merchantApiKey","originBackend","botDetector","enforcement","rslOptions","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.38",
3
+ "version": "2.0.0",
4
4
  "description": "Supertab Connect SDK (beta)",
5
5
  "type": "module",
6
6
  "main": "./dist/index.cjs",