@getsupertab/supertab-connect-sdk 1.1.0 → 1.2.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 +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var te=Object.create;var x=Object.defineProperty;var re=Object.getOwnPropertyDescriptor;var ne=Object.getOwnPropertyNames;var se=Object.getPrototypeOf,oe=Object.prototype.hasOwnProperty;var ie=(t,e)=>{for(var n in e)x(t,n,{get:e[n],enumerable:!0})},H=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of ne(e))!oe.call(t,s)&&s!==n&&x(t,s,{get:()=>e[s],enumerable:!(r=re(e,s))||r.enumerable});return t};var w=(t,e,n)=>(n=t!=null?te(se(t)):{},H(e||!t||!t.__esModule?x(n,"default",{value:t,enumerable:!0}):n,t)),ae=t=>H(x({},"__esModule",{value:!0}),t);var Le={};ie(Le,{CDNStatusDescription:()=>I,EnforcementMode:()=>T,HandlerAction:()=>L,LicenseTokenInvalidReason:()=>S,SupertabConnect:()=>q,defaultBotDetector:()=>Q});module.exports=ae(Le);var T=(r=>(r.DISABLED="disabled",r.SOFT="soft",r.STRICT="strict",r))(T||{}),S=(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))(S||{}),b="stc-backend",L=(n=>(n.ALLOW="allow",n.BLOCK="block",n))(L||{}),I=(o=>(o.Unauthorized="Unauthorized",o.PaymentRequired="Payment Required",o.Forbidden="Forbidden",o.ServiceUnavailable="Service Unavailable",o.Error="Error",o))(I||{});function k(t){let e=null;return()=>(e||(e=t()),e)}var K=k(()=>import("jose/jwt/verify")),A=k(()=>import("jose/jwt/decode")),$=k(()=>import("jose/decode/protected_header")),ce=k(()=>import("jose/key/import")),le=k(()=>import("jose/jwt/sign"));var C=new Map;function ue(t,e){let n=C.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"),C.delete(t),null)}async function de(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 fe(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 pe(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 he(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 B({clientId:t,clientSecret:e,resourceUrl:n,debug:r}){let s=`${t}:${n}`,o=ue(s,r);if(o)return o;let c=await fe(n,r);r&&console.debug(`Fetched license.xml (${c.length} chars)`);let i=pe(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=he(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 de(l,p,r);try{let{decodeJwt:g}=await A(),R=g(f);R.exp&&C.set(s,{token:f,exp:R.exp})}catch{r&&console.debug("Failed to decode token for caching, skipping cache")}return f}var U=new Map,ge=48*60*60*1e3,E=class extends Error{constructor(e){super(`No matching platform key found: ${e}`),this.name="JwksKeyNotFoundError"}};function me(){let t={method:"GET"};return globalThis.fastly&&(t={...t,backend:b}),t}async function ye({cacheKey:t,url:e,debug:n,failureMessage:r,logLabel:s}){let o=U.get(t);if(o&&Date.now()-o.cachedAt<ge)return o.data;try{let c=await fetch(e,me());if(!c.ok)throw new Error(`${r}: ${c.status}`);let i=await c.json();return U.set(t,{data:i,cachedAt:Date.now()}),i}catch(c){throw n&&console.error(s,c),c}}async function V(t,e){let n=`${t}/.well-known/jwks.json/platform`;return e&&console.debug(`Fetching platform JWKS from URL: ${n}`),ye({cacheKey:"platform_jwks",url:n,debug:e,failureMessage:"Failed to fetch platform JWKS",logLabel:"Error fetching platform JWKS:"})}function J(){U.clear()}async function W({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 v=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 D({licenseToken:t,requestUrl:e,supertabBaseUrl:n,debug:r}){let{decodeProtectedHeader:s}=await $(),{decodeJwt:o}=await A(),{jwtVerify:c}=await K();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?v(d):void 0,f=v(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=v(e);if(!g.some(h=>{let m=v(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 F=async()=>{let h;try{h=await V(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 Z=await c(t,async O=>{let N=h.keys.find(ee=>ee.kid===O.kid);if(!N)throw new E(O.kid);return N},{issuer:d,algorithms:[i.alg],clockTolerance:"1m"});return{valid:!0,licenseId:l,payload:Z.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 F()}catch(h){if(h instanceof E)return r&&console.debug("Key not found in cached JWKS, clearing cache and retrying..."),J(),await F();throw h}}function M({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 j(t){let e=M({requestUrl:t});return{action:"allow",headers:{Link:`<${e}>; rel="license"; type="application/rsl+xml"`,"X-RSL-Status":"token_required","X-RSL-Reason":"missing"}}}function Re(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 be(t){return t.replace(/[\r\n]/g,"").replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function _({reason:t,error:e,requestUrl:n}){let{rslError:r,status:s}=Re(t),o=be(e),c=M({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 Ee(){let t={method:"GET"};return globalThis.fastly&&(t={...t,backend:b}),t}async function G(t,e){try{let n=`${t}/merchants/systems/${e}/license.xml`,r=await fetch(n,Ee());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 P(t){let e=await D({licenseToken:t.token,requestUrl:t.url,supertabBaseUrl:t.supertabBaseUrl,debug:t.debug}),n=W({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):await n,e}async function X(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 z(t,e,n,r){if(r&&new URL(e.url).pathname==="/license.xml")return await G(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 we(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 Y(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:we(c.status),headers:i,body:c.body}}return n}function Q(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 D({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 P({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 P({token:s,url:o,userAgent:c,supertabBaseUrl:u.baseUrl,debug:this.debug,apiKey:this.apiKey,ctx:n});return a.valid?{action:"allow"}:_({reason:a.reason,error:a.error,requestUrl:o})}if(!(this.botDetector?.(e,n)??!1))return{action:"allow"};switch(this.enforcement){case"strict":return _({reason:"missing_license_token",error:"Authorization header missing or malformed",requestUrl:o});case"soft":return j(o);default:return{action:"allow"}}}static async obtainLicenseToken(e){return B({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 X(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 z(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 Y(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 q=u;0&&(module.exports={CDNStatusDescription,EnforcementMode,HandlerAction,LicenseTokenInvalidReason,SupertabConnect,defaultBotDetector});
|
|
1
|
+
"use strict";var re=Object.create;var k=Object.defineProperty;var ne=Object.getOwnPropertyDescriptor;var se=Object.getOwnPropertyNames;var oe=Object.getPrototypeOf,ie=Object.prototype.hasOwnProperty;var ae=(r,e)=>{for(var n in e)k(r,n,{get:e[n],enumerable:!0})},H=(r,e,n,t)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of se(e))!ie.call(r,s)&&s!==n&&k(r,s,{get:()=>e[s],enumerable:!(t=ne(e,s))||t.enumerable});return r};var w=(r,e,n)=>(n=r!=null?re(oe(r)):{},H(e||!r||!r.__esModule?k(n,"default",{value:r,enumerable:!0}):n,r)),ce=r=>H(k({},"__esModule",{value:!0}),r);var xe={};ae(xe,{CDNStatusDescription:()=>I,EnforcementMode:()=>T,HandlerAction:()=>L,LicenseTokenInvalidReason:()=>S,SupertabConnect:()=>q,defaultBotDetector:()=>Z});module.exports=ce(xe);var T=(t=>(t.DISABLED="disabled",t.SOFT="soft",t.STRICT="strict",t))(T||{}),S=(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))(S||{}),b="stc-backend",L=(n=>(n.ALLOW="allow",n.BLOCK="block",n))(L||{}),I=(o=>(o.Unauthorized="Unauthorized",o.PaymentRequired="Payment Required",o.Forbidden="Forbidden",o.ServiceUnavailable="Service Unavailable",o.Error="Error",o))(I||{});function x(r){let e=null;return()=>(e||(e=r()),e)}var $=x(()=>import("jose/jwt/verify")),A=x(()=>import("jose/jwt/decode")),K=x(()=>import("jose/decode/protected_header")),le=x(()=>import("jose/key/import")),ue=x(()=>import("jose/jwt/sign"));function B(r,e){let n=!1,t=r;t.endsWith("$")&&(n=!0,t=t.slice(0,-1));let s=t.includes("*"),c=t.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*"),i;return n?i=`^${c}$`:s?i=`^${c}`:t==="/"?i="^/":i=`^${c}(/|$)`,new RegExp(i).test(e)?t.replace(/\*/g,"").length:-1}var C=new Map;function de(r,e){let n=C.get(r);if(!n)return null;let t=Math.floor(Date.now()/1e3);return n.exp>t+30?(e&&console.debug(`Using cached license token (expires in ${n.exp-t}s)`),n.token):(e&&console.debug("Cached license token expired or expiring soon, refreshing"),C.delete(r),null)}async function fe(r,e,n){try{let t=await fetch(r,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 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(t){throw n&&console.error("Error generating license token:",t),t}}async function pe(r,e){let t=`${new URL(r).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 he(r,e){let n=[],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(r))!==null;){i++;let l=a[1],d=a[2],f=l.match(s),h=l.match(o),g=d.match(c);if(f&&h&&g)n.push({urlPattern:f[1],server:h[1],licenseXml:g[0]});else if(e){let R=[!f&&"url",!h&&"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 ge(r,e,n){let t=new URL(e),s=t.host,o=t.pathname;n&&console.debug(`Matching resource URL: ${e} (host=${s}, path=${o})`);let c=null,i=-1;for(let a of r){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;let f=B(d,o);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 V({clientId:r,clientSecret:e,resourceUrl:n,debug:t}){let s=`${r}:${n}`,o=de(s,t);if(o)return o;let c=await pe(n,t);t&&console.debug(`Fetched license.xml (${c.length} chars)`);let i=he(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=ge(i,n,t);if(!a){if(t){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}`)}t&&(console.debug("Matched content block for resource URL:",n),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}),f={method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json",Authorization:"Basic "+btoa(`${r}:${e}`)},body:d.toString()},h=await fe(l,f,t);try{let{decodeJwt:g}=await A(),R=g(h);R.exp&&C.set(s,{token:h,exp:R.exp})}catch{t&&console.debug("Failed to decode token for caching, skipping cache")}return h}var U=new Map,me=48*60*60*1e3,E=class extends Error{constructor(e){super(`No matching platform key found: ${e}`),this.name="JwksKeyNotFoundError"}};function ye(){let r={method:"GET"};return globalThis.fastly&&(r={...r,backend:b}),r}async function Re({cacheKey:r,url:e,debug:n,failureMessage:t,logLabel:s}){let o=U.get(r);if(o&&Date.now()-o.cachedAt<me)return o.data;try{let c=await fetch(e,ye());if(!c.ok)throw new Error(`${t}: ${c.status}`);let i=await c.json();return U.set(r,{data:i,cachedAt:Date.now()}),i}catch(c){throw n&&console.error(s,c),c}}async function J(r,e){let n=`${r}/.well-known/jwks.json/platform`;return e&&console.debug(`Fetching platform JWKS from URL: ${n}`),Re({cacheKey:"platform_jwks",url:n,debug:e,failureMessage:"Failed to fetch platform JWKS",logLabel:"Error fetching platform JWKS:"})}function W(){U.clear()}async function M({apiKey:r,baseUrl:e,eventName:n,properties:t,licenseId:s,debug:o=!1}){let c={event_name:n,license_id:s,properties:t};try{let i={method:"POST",headers:{Authorization:`Bearer ${r}`,"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 v=r=>r.trim().replace(/\/+$/,"");function y(r){switch(r){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 _({licenseToken:r,requestUrl:e,supertabBaseUrl:n,debug:t}){let{decodeProtectedHeader:s}=await K(),{decodeJwt:o}=await A(),{jwtVerify:c}=await $();if(!r)return{valid:!1,reason:"missing_license_token",error:y("missing_license_token")};let i;try{i=s(r)}catch(p){return t&&console.error("Invalid license JWT header:",p),{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(r)}catch(p){return t&&console.error("Invalid license JWT payload:",p),{valid:!1,reason:"invalid_license_payload",error:y("invalid_license_payload")}}let l=a.license_id,d=a.iss,f=d?v(d):void 0,h=v(n);if(!f||!f.startsWith(h))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(p=>typeof p=="string"):typeof a.aud=="string"?[a.aud]:[],R=v(e);if(!g.some(p=>{let m=v(p);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 F=async()=>{let p;try{p=await J(n,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 ee=await c(r,async O=>{let N=p.keys.find(te=>te.kid===O.kid);if(!N)throw new E(O.kid);return N},{issuer:d,algorithms:[i.alg],clockTolerance:"1m"});return{valid:!0,licenseId:l,payload:ee.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 F()}catch(p){if(p instanceof E)return t&&console.debug("Key not found in cached JWKS, clearing cache and retrying..."),W(),await F();throw p}}function j({requestUrl:r}){try{let e=new URL(r);return`${e.protocol}//${e.host}/license.xml`}catch(e){return console.error("[SupertabConnect] generateLicenseLink failed to parse URL:",e),"/license.xml"}}function G(r){let e=j({requestUrl:r});return{action:"allow",headers:{Link:`<${e}>; rel="license"; type="application/rsl+xml"`,"X-RSL-Status":"token_required","X-RSL-Reason":"missing"}}}function be(r){switch(r){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 Ee(r){return r.replace(/[\r\n]/g,"").replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function P({reason:r,error:e,requestUrl:n}){let{rslError:t,status:s}=be(r),o=Ee(e),c=j({requestUrl:n});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 we(){let r={method:"GET"};return globalThis.fastly&&(r={...r,backend:b}),r}async function X(r,e){try{let n=`${r}/merchants/systems/${e}/license.xml`,t=await fetch(n,we());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(n){return console.error("[SupertabConnect] hostRSLicenseXML failed:",n),new Response("Bad Gateway",{status:502})}}async function D(r){let e=await _({licenseToken:r.token,requestUrl:r.url,supertabBaseUrl:r.supertabBaseUrl,debug:r.debug}),n=M({apiKey:r.apiKey,baseUrl:r.supertabBaseUrl,eventName:e.valid?"license_used":e.reason,properties:{page_url:r.url,user_agent:r.userAgent,verification_status:e.valid?"valid":"invalid",verification_reason:e.valid?"success":e.reason},licenseId:e.licenseId,debug:r.debug});return r.ctx?.waitUntil?r.ctx.waitUntil(n):await n,e}async function z(r,e,n){let t=await r.handleRequest(e,n);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 Y(r,e,n,t){if(t&&new URL(e.url).pathname==="/license.xml")return await X(t.baseUrl,t.merchantSystemUrn);let s=await r.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 Le(r){switch(r){case 401:return"Unauthorized";case 402:return"Payment Required";case 403:return"Forbidden";case 503:return"Service Unavailable";default:return"Error"}}async function Q(r,e){let n=e.Records[0].cf.request,t=n.headers?.["x-original-request-url"]?.[0]?.value,s=`${n.headers.host[0].value}${n.uri}`,o=`https://${t||s}${n.querystring?"?"+n.querystring:""}`,c=new Headers;Object.entries(n.headers).forEach(([l,d])=>{d.forEach(({value:f})=>c.append(l,f))});let i=new Request(o,{method:n.method,headers:c}),a=await r.handleRequest(i);if(a.action==="block"){let l={};return Object.entries(a.headers).forEach(([d,f])=>{l[d.toLowerCase()]=[{key:d,value:f}]}),{status:a.status.toString(),statusDescription:Le(a.status),headers:l,body:a.body}}return n}function Z(r){let e=r.headers.get("User-Agent")||"",n=r.headers.get("accept")||"",t=r.headers.get("sec-ch-ua"),s=r.headers.get("accept-language"),o=r.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,f=!n||!s,h=typeof o=="number"&&o<30;return(i.includes("safari")||i.includes("mozilla"))&&l&&d?!1:a||l||f||h}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,t=await _({licenseToken:e.token,requestUrl:e.resourceUrl,supertabBaseUrl:n,debug:e.debug??!1});return t.valid?{valid:!0}:{valid:!1,error:t.error}}async verifyAndRecord(e){let n=await D({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 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 D({token:s,url:o,userAgent:c,supertabBaseUrl:u.baseUrl,debug:this.debug,apiKey:this.apiKey,ctx:n});return a.valid?{action:"allow"}:P({reason:a.reason,error:a.error,requestUrl:o})}if(!(this.botDetector?.(e,n)??!1))return{action:"allow"};switch(this.enforcement){case"strict":return P({reason:"missing_license_token",error:"Authorization header missing or malformed",requestUrl:o});case"soft":return G(o);default:return{action:"allow"}}}static async obtainLicenseToken(e){return V({clientId:e.clientId,clientSecret:e.clientSecret,resourceUrl:e.resourceUrl,debug:e.debug})}static async cloudflareHandleRequests(e,n,t,s){try{let o=new u({apiKey:n.MERCHANT_API_KEY,botDetector:s?.botDetector,enforcement:s?.enforcement});return await z(o,e,t)}catch(o){return console.error("[SupertabConnect] cloudflareHandleRequests failed:",o),await fetch(e)}}static async fastlyHandleRequests(e,n,t,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 Y(i,e,t,a)}catch(o){return console.error("[SupertabConnect] fastlyHandleRequests failed:",o),await fetch(e,{backend:t})}}static async cloudfrontHandleRequests(e,n){let t=e?.Records?.[0]?.cf?.request??{};try{if(!t.headers?.["x-license-auth"])return t;let o=new u({apiKey:n.apiKey,enforcement:n.enforcement});return await Q(o,e)}catch(s){return console.error("[SupertabConnect] cloudfrontHandleRequests failed:",s),t}}};u.baseUrl="https://api-connect.supertab.co",u._instance=null;var q=u;0&&(module.exports={CDNStatusDescription,EnforcementMode,HandlerAction,LicenseTokenInvalidReason,SupertabConnect,defaultBotDetector});
|
|
2
2
|
//# sourceMappingURL=index.cjs.map
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/types.ts","../src/jose.ts","../src/customer.ts","../src/jwks.ts","../src/events.ts","../src/license.ts","../src/cdn.ts","../src/bots.ts"],"sourcesContent":["import {\n SupertabConnectConfig,\n EnforcementMode,\n BotDetector,\n HandlerAction,\n HandlerResult,\n LicenseTokenInvalidReason,\n CDNStatusDescription,\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, CDNStatusDescription };\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\nexport enum CDNStatusDescription {\n Unauthorized = \"Unauthorized\",\n PaymentRequired = \"Payment Required\",\n Forbidden = \"Forbidden\",\n ServiceUnavailable = \"Service Unavailable\",\n Error = \"Error\",\n}\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?: CDNStatusDescription;\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 } else {\n await eventPromise;\n }\n\n return verification;\n}\n","import {\n HandlerAction,\n HandlerResult,\n ExecutionContext,\n CDNStatusDescription,\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): CDNStatusDescription {\n switch (status) {\n case 401: return CDNStatusDescription.Unauthorized;\n case 402: return CDNStatusDescription.PaymentRequired;\n case 403: return CDNStatusDescription.Forbidden;\n case 503: return CDNStatusDescription.ServiceUnavailable;\n default: return CDNStatusDescription.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,0BAAAE,EAAA,oBAAAC,EAAA,kBAAAC,EAAA,8BAAAC,EAAA,oBAAAC,EAAA,uBAAAC,IAAA,eAAAC,GAAAR,ICEO,IAAKS,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,IASAC,OACVA,EAAA,aAAe,eACfA,EAAA,gBAAkB,mBAClBA,EAAA,UAAY,YACZA,EAAA,mBAAqB,sBACrBA,EAAA,MAAQ,QALEA,OAAA,ICxEZ,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,I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ACX,QAAS1B,EAAgB,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","CDNStatusDescription","EnforcementMode","HandlerAction","LicenseTokenInvalidReason","SupertabConnect","defaultBotDetector","__toCommonJS","EnforcementMode","LicenseTokenInvalidReason","FASTLY_BACKEND","HandlerAction","CDNStatusDescription","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"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/types.ts","../src/jose.ts","../src/url-pattern.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 CDNStatusDescription,\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, CDNStatusDescription };\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 an origin-request LambdaEdge function.\n * @param event The CloudFront origin-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 const request = event?.Records?.[0]?.cf?.request as TRequest ?? {} as CloudFrontRequestResult<TRequest>;\n try {\n const license_auth_header = request.headers?.[\"x-license-auth\"];\n if (!license_auth_header) {\n // No license auth header means the request is either from a human or from an unidentifiable bot.\n // No reasons to waste compute resources on the rest of the checks.\n return request;\n }\n const instance = new SupertabConnect({\n apiKey: options.apiKey,\n enforcement: options.enforcement\n });\n return await handleCloudfrontRequest(instance, event);\n } catch (err) {\n console.error(\"[SupertabConnect] cloudfrontHandleRequests failed:\", err);\n return request;\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\nexport enum CDNStatusDescription {\n Unauthorized = \"Unauthorized\",\n PaymentRequired = \"Payment Required\",\n Forbidden = \"Forbidden\",\n ServiceUnavailable = \"Service Unavailable\",\n Error = \"Error\",\n}\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?: CDNStatusDescription;\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","/**\n * Match a URL path against a robots.txt-style pattern.\n *\n * - `*` matches zero or more characters (including `/`)\n * - Trailing `$` anchors the match to the end of the path\n * - Without `$`, patterns without `*` match as prefix at segment boundaries\n * (e.g. `/content` matches `/content/article` but not `/content-other`)\n * - Without `$`, patterns with `*` are prefix-matched from the start\n *\n * Returns specificity (number of literal characters) on match, or -1 on no match.\n */\nexport function scorePathPattern(pattern: string, path: string): number {\n let anchored = false;\n let pat = pattern;\n\n if (pat.endsWith(\"$\")) {\n anchored = true;\n pat = pat.slice(0, -1);\n }\n\n const hasWildcard = pat.includes(\"*\");\n\n // Escape regex special chars (except *) and treat them as literals\n const escaped = pat.replace(/[.+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n // Converts wildcard * to regex equivalent .*\n const regexBody = escaped.replace(/\\*/g, \".*\");\n\n let regexStr: string;\n if (anchored) {\n regexStr = `^${regexBody}$`;\n } else if (hasWildcard) {\n regexStr = `^${regexBody}`;\n } else {\n // No wildcards, no anchor: prefix match at segment boundary\n // Special case: \"/\" matches all paths\n if (pat === \"/\") {\n regexStr = `^/`;\n } else {\n regexStr = `^${regexBody}(/|$)`;\n }\n }\n\n if (new RegExp(regexStr).test(path)) {\n return pat.replace(/\\*/g, \"\").length;\n }\n\n return -1;\n}\n","import { loadKeyImport, loadJwtSign, loadDecodeJwt } from \"./jose\";\nimport { scorePathPattern } from \"./url-pattern\";\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 // Exact match — highest priority, return immediately\n if (patternPath === path) {\n if (debug) {\n console.debug(`Exact match found: ${block.urlPattern}`);\n }\n return block;\n }\n\n // Pattern match (wildcards, prefix, anchored)\n const specificity = scorePathPattern(patternPath, path);\n if (specificity > bestSpecificity) {\n bestSpecificity = specificity;\n bestMatch = block;\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 } else {\n await eventPromise;\n }\n\n return verification;\n}\n","import {\n HandlerAction,\n HandlerResult,\n ExecutionContext,\n CDNStatusDescription,\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): CDNStatusDescription {\n switch (status) {\n case 401: return CDNStatusDescription.Unauthorized;\n case 402: return CDNStatusDescription.PaymentRequired;\n case 403: return CDNStatusDescription.Forbidden;\n case 503: return CDNStatusDescription.ServiceUnavailable;\n default: return CDNStatusDescription.Error;\n }\n}\n\n/**\n * Handles an Origin request in CloudFront. Expects X-Original-Request-URL header to contain the original viewer request URL.\n * @param handler\n * @param event\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 viewerRequestUrl = cfRequest.headers?.[\"x-original-request-url\"]?.[0]?.value;\n const originRequestUrl = `${cfRequest.headers.host[0].value}${cfRequest.uri}`;\n const url = `https://${viewerRequestUrl ? viewerRequestUrl : originRequestUrl}${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,0BAAAE,EAAA,oBAAAC,EAAA,kBAAAC,EAAA,8BAAAC,EAAA,oBAAAC,EAAA,uBAAAC,IAAA,eAAAC,GAAAR,ICEO,IAAKS,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,EAAi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EAC4C,CAC5C,IAAMK,EAAUmB,GAAO,UAAU,CAAC,GAAG,IAAI,SAAuB,CAAC,EACjE,GAAI,CAEF,GAAI,CADwBnB,EAAQ,UAAU,gBAAgB,EAI5D,OAAOA,EAET,IAAMU,EAAW,IAAInB,EAAgB,CACnC,OAAQI,EAAQ,OAChB,YAAaA,EAAQ,WACvB,CAAC,EACD,OAAO,MAAMyB,EAAwBV,EAAUS,CAAK,CACtD,OAASP,EAAK,CACZ,eAAQ,MAAM,qDAAsDA,CAAG,EAChEZ,CACT,CACF,CACF,EAhUaT,EAEI,QAAkB,kCAFtBA,EAOI,UAAoC,KAP9C,IAAM8B,EAAN9B","names":["index_exports","__export","CDNStatusDescription","EnforcementMode","HandlerAction","LicenseTokenInvalidReason","SupertabConnect","defaultBotDetector","__toCommonJS","EnforcementMode","LicenseTokenInvalidReason","FASTLY_BACKEND","HandlerAction","CDNStatusDescription","lazyImport","load","cached","loadJwtVerify","loadDecodeJwt","loadDecodeProtectedHeader","loadKeyImport","loadJwtSign","scorePathPattern","pattern","path","anchored","pat","hasWildcard","regexBody","regexStr","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","specificity","scorePathPattern","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","viewerRequestUrl","originRequestUrl","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
|
@@ -233,8 +233,8 @@ declare class SupertabConnect {
|
|
|
233
233
|
static fastlyHandleRequests(request: Request, merchantApiKey: string, originBackend: string, options?: FastlyHandlerOptions): Promise<Response>;
|
|
234
234
|
/**
|
|
235
235
|
* Handle incoming requests for AWS CloudFront Lambda@Edge.
|
|
236
|
-
* Use as the handler for
|
|
237
|
-
* @param event The CloudFront
|
|
236
|
+
* Use as the handler for an origin-request LambdaEdge function.
|
|
237
|
+
* @param event The CloudFront origin-request event
|
|
238
238
|
* @param options Configuration including apiKey and optional botDetector/enforcement
|
|
239
239
|
*/
|
|
240
240
|
static cloudfrontHandleRequests<TRequest extends Record<string, any>>(event: CloudFrontRequestEvent<TRequest>, options: CloudfrontHandlerOptions): Promise<CloudFrontRequestResult<TRequest>>;
|
package/dist/index.d.ts
CHANGED
|
@@ -233,8 +233,8 @@ declare class SupertabConnect {
|
|
|
233
233
|
static fastlyHandleRequests(request: Request, merchantApiKey: string, originBackend: string, options?: FastlyHandlerOptions): Promise<Response>;
|
|
234
234
|
/**
|
|
235
235
|
* Handle incoming requests for AWS CloudFront Lambda@Edge.
|
|
236
|
-
* Use as the handler for
|
|
237
|
-
* @param event The CloudFront
|
|
236
|
+
* Use as the handler for an origin-request LambdaEdge function.
|
|
237
|
+
* @param event The CloudFront origin-request event
|
|
238
238
|
* @param options Configuration including apiKey and optional botDetector/enforcement
|
|
239
239
|
*/
|
|
240
240
|
static cloudfrontHandleRequests<TRequest extends Record<string, any>>(event: CloudFrontRequestEvent<TRequest>, options: CloudfrontHandlerOptions): Promise<CloudFrontRequestResult<TRequest>>;
|
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var q=(t=>(t.DISABLED="disabled",t.SOFT="soft",t.STRICT="strict",t))(q||{}),S=(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))(S||{}),b="stc-backend",L=(r=>(r.ALLOW="allow",r.BLOCK="block",r))(L||{}),I=(s=>(s.Unauthorized="Unauthorized",s.PaymentRequired="Payment Required",s.Forbidden="Forbidden",s.ServiceUnavailable="Service Unavailable",s.Error="Error",s))(I||{});function w(n){let e=null;return()=>(e||(e=n()),e)}var F=w(()=>import("jose/jwt/verify")),k=w(()=>import("jose/jwt/decode")),O=w(()=>import("jose/decode/protected_header")),Y=w(()=>import("jose/key/import")),Q=w(()=>import("jose/jwt/sign"));var A=new Map;function Z(n,e){let r=A.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"),A.delete(n),null)}async function ee(n,e,r){try{let t=await fetch(n,e);if(!t.ok){let s=await t.text().catch(()=>""),c=`Failed to obtain license token: ${t.status} ${t.statusText}${s?` - ${s}`:""}`;throw new Error(c)}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 te(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 re(n,e){let r=[],t=/<content\s([^>]*)>([\s\S]*?)<\/content>/gi,o=/url\s*=\s*"([^"]*)"/i,s=/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(o),f=l.match(s),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 ne(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 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!==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: ${a.urlPattern}`),a;if(d.endsWith("/*")){let p=d.slice(0,-1);if(s.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 N({clientId:n,clientSecret:e,resourceUrl:r,debug:t}){let o=`${n}:${r}`,s=Z(o,t);if(s)return s;let c=await te(r,t);t&&console.debug(`Fetched license.xml (${c.length} chars)`);let i=re(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=ne(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 ee(l,p,t);try{let{decodeJwt:g}=await k(),R=g(f);R.exp&&A.set(o,{token:f,exp:R.exp})}catch{t&&console.debug("Failed to decode token for caching, skipping cache")}return f}var v=new Map,se=48*60*60*1e3,E=class extends Error{constructor(e){super(`No matching platform key found: ${e}`),this.name="JwksKeyNotFoundError"}};function oe(){let n={method:"GET"};return globalThis.fastly&&(n={...n,backend:b}),n}async function ie({cacheKey:n,url:e,debug:r,failureMessage:t,logLabel:o}){let s=v.get(n);if(s&&Date.now()-s.cachedAt<se)return s.data;try{let c=await fetch(e,oe());if(!c.ok)throw new Error(`${t}: ${c.status}`);let i=await c.json();return v.set(n,{data:i,cachedAt:Date.now()}),i}catch(c){throw r&&console.error(o,c),c}}async function H(n,e){let r=`${n}/.well-known/jwks.json/platform`;return e&&console.debug(`Fetching platform JWKS from URL: ${r}`),ie({cacheKey:"platform_jwks",url:r,debug:e,failureMessage:"Failed to fetch platform JWKS",logLabel:"Error fetching platform JWKS:"})}function K(){v.clear()}async function $({apiKey:n,baseUrl:e,eventName:r,properties:t,licenseId:o,debug:s=!1}){let c={event_name:r,license_id:o,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&&s&&console.error(`Failed to record event: ${a.status}`)}catch(i){s&&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 T({licenseToken:n,requestUrl:e,supertabBaseUrl:r,debug:t}){let{decodeProtectedHeader:o}=await O(),{decodeJwt:s}=await k(),{jwtVerify:c}=await F();if(!n)return{valid:!1,reason:"missing_license_token",error:y("missing_license_token")};let i;try{i=o(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=s(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 D=async()=>{let h;try{h=await H(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 X=await c(n,async _=>{let P=h.keys.find(z=>z.kid===_.kid);if(!P)throw new E(_.kid);return P},{issuer:d,algorithms:[i.alg],clockTolerance:"1m"});return{valid:!0,licenseId:l,payload:X.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 D()}catch(h){if(h instanceof E)return t&&console.debug("Key not found in cached JWKS, clearing cache and retrying..."),K(),await D();throw h}}function B({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 V(n){let e=B({requestUrl:n});return{action:"allow",headers:{Link:`<${e}>; rel="license"; type="application/rsl+xml"`,"X-RSL-Status":"token_required","X-RSL-Reason":"missing"}}}function ae(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 ce(n){return n.replace(/[\r\n]/g,"").replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function C({reason:n,error:e,requestUrl:r}){let{rslError:t,status:o}=ae(n),s=ce(e),c=B({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:`<${c}>; rel="license"; type="application/rsl+xml"`}}}function le(){let n={method:"GET"};return globalThis.fastly&&(n={...n,backend:b}),n}async function J(n,e){try{let r=`${n}/merchants/systems/${e}/license.xml`,t=await fetch(r,le());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 U(n){let e=await T({licenseToken:n.token,requestUrl:n.url,supertabBaseUrl:n.supertabBaseUrl,debug:n.debug}),r=$({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):await r,e}async function W(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[c,i]of Object.entries(t.headers))s.headers.set(c,i);return s}return o}async function M(n,e,r,t){if(t&&new URL(e.url).pathname==="/license.xml")return await J(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 c=new Response(s.body,s);for(let[i,a]of Object.entries(o.headers))c.headers.set(i,a);return c}return s}function ue(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 j(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,a])=>{a.forEach(({value:l})=>o.append(i,l))});let s=new Request(t,{method:r.method,headers:o}),c=await n.handleRequest(s);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:ue(c.status),headers:i,body:c.body}}return r}function de(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,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||!o,f=typeof s=="number"&&s<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 T({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 U({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,c=e.headers.get("User-Agent")||"unknown";if(o){if(this.enforcement==="disabled")return{action:"allow"};let a=await U({token:o,url:s,userAgent:c,supertabBaseUrl:u.baseUrl,debug:this.debug,apiKey:this.apiKey,ctx:r});return a.valid?{action:"allow"}:C({reason:a.reason,error:a.error,requestUrl:s})}if(!(this.botDetector?.(e,r)??!1))return{action:"allow"};switch(this.enforcement){case"strict":return C({reason:"missing_license_token",error:"Authorization header missing or malformed",requestUrl:s});case"soft":return V(s);default:return{action:"allow"}}}static async obtainLicenseToken(e){return N({clientId:e.clientId,clientSecret:e.clientSecret,resourceUrl:e.resourceUrl,debug:e.debug})}static async cloudflareHandleRequests(e,r,t,o){try{let s=new u({apiKey:r.MERCHANT_API_KEY,botDetector:o?.botDetector,enforcement:o?.enforcement});return await W(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:c}=o??{},i=new u({apiKey:r,botDetector:s,enforcement:c}),a;return o?.enableRSL&&(a={baseUrl:u.baseUrl,merchantSystemUrn:o.merchantSystemUrn}),await M(i,e,t,a)}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 j(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 G=u;export{I as CDNStatusDescription,q as EnforcementMode,L as HandlerAction,S as LicenseTokenInvalidReason,G as SupertabConnect,de as defaultBotDetector};
|
|
1
|
+
var q=(t=>(t.DISABLED="disabled",t.SOFT="soft",t.STRICT="strict",t))(q||{}),S=(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))(S||{}),b="stc-backend",L=(r=>(r.ALLOW="allow",r.BLOCK="block",r))(L||{}),I=(s=>(s.Unauthorized="Unauthorized",s.PaymentRequired="Payment Required",s.Forbidden="Forbidden",s.ServiceUnavailable="Service Unavailable",s.Error="Error",s))(I||{});function w(n){let e=null;return()=>(e||(e=n()),e)}var F=w(()=>import("jose/jwt/verify")),x=w(()=>import("jose/jwt/decode")),O=w(()=>import("jose/decode/protected_header")),Q=w(()=>import("jose/key/import")),Z=w(()=>import("jose/jwt/sign"));function N(n,e){let r=!1,t=n;t.endsWith("$")&&(r=!0,t=t.slice(0,-1));let o=t.includes("*"),c=t.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*"),i;return r?i=`^${c}$`:o?i=`^${c}`:t==="/"?i="^/":i=`^${c}(/|$)`,new RegExp(i).test(e)?t.replace(/\*/g,"").length:-1}var A=new Map;function ee(n,e){let r=A.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"),A.delete(n),null)}async function te(n,e,r){try{let t=await fetch(n,e);if(!t.ok){let s=await t.text().catch(()=>""),c=`Failed to obtain license token: ${t.status} ${t.statusText}${s?` - ${s}`:""}`;throw new Error(c)}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 re(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 ne(n,e){let r=[],t=/<content\s([^>]*)>([\s\S]*?)<\/content>/gi,o=/url\s*=\s*"([^"]*)"/i,s=/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],f=l.match(o),h=l.match(s),g=d.match(c);if(f&&h&&g)r.push({urlPattern:f[1],server:h[1],licenseXml:g[0]});else if(e){let R=[!f&&"url",!h&&"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 se(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 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!==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: ${a.urlPattern}`),a;let f=N(d,s);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 H({clientId:n,clientSecret:e,resourceUrl:r,debug:t}){let o=`${n}:${r}`,s=ee(o,t);if(s)return s;let c=await re(r,t);t&&console.debug(`Fetched license.xml (${c.length} chars)`);let i=ne(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=se(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}),f={method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json",Authorization:"Basic "+btoa(`${n}:${e}`)},body:d.toString()},h=await te(l,f,t);try{let{decodeJwt:g}=await x(),R=g(h);R.exp&&A.set(o,{token:h,exp:R.exp})}catch{t&&console.debug("Failed to decode token for caching, skipping cache")}return h}var v=new Map,oe=48*60*60*1e3,E=class extends Error{constructor(e){super(`No matching platform key found: ${e}`),this.name="JwksKeyNotFoundError"}};function ie(){let n={method:"GET"};return globalThis.fastly&&(n={...n,backend:b}),n}async function ae({cacheKey:n,url:e,debug:r,failureMessage:t,logLabel:o}){let s=v.get(n);if(s&&Date.now()-s.cachedAt<oe)return s.data;try{let c=await fetch(e,ie());if(!c.ok)throw new Error(`${t}: ${c.status}`);let i=await c.json();return v.set(n,{data:i,cachedAt:Date.now()}),i}catch(c){throw r&&console.error(o,c),c}}async function $(n,e){let r=`${n}/.well-known/jwks.json/platform`;return e&&console.debug(`Fetching platform JWKS from URL: ${r}`),ae({cacheKey:"platform_jwks",url:r,debug:e,failureMessage:"Failed to fetch platform JWKS",logLabel:"Error fetching platform JWKS:"})}function K(){v.clear()}async function B({apiKey:n,baseUrl:e,eventName:r,properties:t,licenseId:o,debug:s=!1}){let c={event_name:r,license_id:o,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&&s&&console.error(`Failed to record event: ${a.status}`)}catch(i){s&&console.error("Error recording event:",i)}}var k=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 T({licenseToken:n,requestUrl:e,supertabBaseUrl:r,debug:t}){let{decodeProtectedHeader:o}=await O(),{decodeJwt:s}=await x(),{jwtVerify:c}=await F();if(!n)return{valid:!1,reason:"missing_license_token",error:y("missing_license_token")};let i;try{i=o(n)}catch(p){return t&&console.error("Invalid license JWT header:",p),{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=s(n)}catch(p){return t&&console.error("Invalid license JWT payload:",p),{valid:!1,reason:"invalid_license_payload",error:y("invalid_license_payload")}}let l=a.license_id,d=a.iss,f=d?k(d):void 0,h=k(r);if(!f||!f.startsWith(h))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(p=>typeof p=="string"):typeof a.aud=="string"?[a.aud]:[],R=k(e);if(!g.some(p=>{let m=k(p);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 _=async()=>{let p;try{p=await $(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 z=await c(n,async P=>{let D=p.keys.find(Y=>Y.kid===P.kid);if(!D)throw new E(P.kid);return D},{issuer:d,algorithms:[i.alg],clockTolerance:"1m"});return{valid:!0,licenseId:l,payload:z.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 _()}catch(p){if(p instanceof E)return t&&console.debug("Key not found in cached JWKS, clearing cache and retrying..."),K(),await _();throw p}}function V({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 J(n){let e=V({requestUrl:n});return{action:"allow",headers:{Link:`<${e}>; rel="license"; type="application/rsl+xml"`,"X-RSL-Status":"token_required","X-RSL-Reason":"missing"}}}function ce(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 le(n){return n.replace(/[\r\n]/g,"").replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function C({reason:n,error:e,requestUrl:r}){let{rslError:t,status:o}=ce(n),s=le(e),c=V({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:`<${c}>; rel="license"; type="application/rsl+xml"`}}}function ue(){let n={method:"GET"};return globalThis.fastly&&(n={...n,backend:b}),n}async function W(n,e){try{let r=`${n}/merchants/systems/${e}/license.xml`,t=await fetch(r,ue());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 U(n){let e=await T({licenseToken:n.token,requestUrl:n.url,supertabBaseUrl:n.supertabBaseUrl,debug:n.debug}),r=B({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):await r,e}async function M(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[c,i]of Object.entries(t.headers))s.headers.set(c,i);return s}return o}async function j(n,e,r,t){if(t&&new URL(e.url).pathname==="/license.xml")return await W(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 c=new Response(s.body,s);for(let[i,a]of Object.entries(o.headers))c.headers.set(i,a);return c}return s}function de(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 G(n,e){let r=e.Records[0].cf.request,t=r.headers?.["x-original-request-url"]?.[0]?.value,o=`${r.headers.host[0].value}${r.uri}`,s=`https://${t||o}${r.querystring?"?"+r.querystring:""}`,c=new Headers;Object.entries(r.headers).forEach(([l,d])=>{d.forEach(({value:f})=>c.append(l,f))});let i=new Request(s,{method:r.method,headers:c}),a=await n.handleRequest(i);if(a.action==="block"){let l={};return Object.entries(a.headers).forEach(([d,f])=>{l[d.toLowerCase()]=[{key:d,value:f}]}),{status:a.status.toString(),statusDescription:de(a.status),headers:l,body:a.body}}return r}function fe(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,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,f=!r||!o,h=typeof s=="number"&&s<30;return(i.includes("safari")||i.includes("mozilla"))&&l&&d?!1:a||l||f||h}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 T({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 U({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,c=e.headers.get("User-Agent")||"unknown";if(o){if(this.enforcement==="disabled")return{action:"allow"};let a=await U({token:o,url:s,userAgent:c,supertabBaseUrl:u.baseUrl,debug:this.debug,apiKey:this.apiKey,ctx:r});return a.valid?{action:"allow"}:C({reason:a.reason,error:a.error,requestUrl:s})}if(!(this.botDetector?.(e,r)??!1))return{action:"allow"};switch(this.enforcement){case"strict":return C({reason:"missing_license_token",error:"Authorization header missing or malformed",requestUrl:s});case"soft":return J(s);default:return{action:"allow"}}}static async obtainLicenseToken(e){return H({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 M(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:c}=o??{},i=new u({apiKey:r,botDetector:s,enforcement:c}),a;return o?.enableRSL&&(a={baseUrl:u.baseUrl,merchantSystemUrn:o.merchantSystemUrn}),await j(i,e,t,a)}catch(s){return console.error("[SupertabConnect] fastlyHandleRequests failed:",s),await fetch(e,{backend:t})}}static async cloudfrontHandleRequests(e,r){let t=e?.Records?.[0]?.cf?.request??{};try{if(!t.headers?.["x-license-auth"])return t;let s=new u({apiKey:r.apiKey,enforcement:r.enforcement});return await G(s,e)}catch(o){return console.error("[SupertabConnect] cloudfrontHandleRequests failed:",o),t}}};u.baseUrl="https://api-connect.supertab.co",u._instance=null;var X=u;export{I as CDNStatusDescription,q as EnforcementMode,L as HandlerAction,S as LicenseTokenInvalidReason,X as SupertabConnect,fe 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":["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\nexport enum CDNStatusDescription {\n Unauthorized = \"Unauthorized\",\n PaymentRequired = \"Payment Required\",\n Forbidden = \"Forbidden\",\n ServiceUnavailable = \"Service Unavailable\",\n Error = \"Error\",\n}\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?: CDNStatusDescription;\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 } else {\n await eventPromise;\n }\n\n return verification;\n}\n","import {\n HandlerAction,\n HandlerResult,\n ExecutionContext,\n CDNStatusDescription,\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): CDNStatusDescription {\n switch (status) {\n case 401: return CDNStatusDescription.Unauthorized;\n case 402: return CDNStatusDescription.PaymentRequired;\n case 403: return CDNStatusDescription.Forbidden;\n case 503: return CDNStatusDescription.ServiceUnavailable;\n default: return CDNStatusDescription.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 CDNStatusDescription,\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, CDNStatusDescription };\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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nforcementMode","LicenseTokenInvalidReason","FASTLY_BACKEND","HandlerAction","CDNStatusDescription","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"]}
|
|
1
|
+
{"version":3,"sources":["../src/types.ts","../src/jose.ts","../src/url-pattern.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\nexport enum CDNStatusDescription {\n Unauthorized = \"Unauthorized\",\n PaymentRequired = \"Payment Required\",\n Forbidden = \"Forbidden\",\n ServiceUnavailable = \"Service Unavailable\",\n Error = \"Error\",\n}\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?: CDNStatusDescription;\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","/**\n * Match a URL path against a robots.txt-style pattern.\n *\n * - `*` matches zero or more characters (including `/`)\n * - Trailing `$` anchors the match to the end of the path\n * - Without `$`, patterns without `*` match as prefix at segment boundaries\n * (e.g. `/content` matches `/content/article` but not `/content-other`)\n * - Without `$`, patterns with `*` are prefix-matched from the start\n *\n * Returns specificity (number of literal characters) on match, or -1 on no match.\n */\nexport function scorePathPattern(pattern: string, path: string): number {\n let anchored = false;\n let pat = pattern;\n\n if (pat.endsWith(\"$\")) {\n anchored = true;\n pat = pat.slice(0, -1);\n }\n\n const hasWildcard = pat.includes(\"*\");\n\n // Escape regex special chars (except *) and treat them as literals\n const escaped = pat.replace(/[.+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n // Converts wildcard * to regex equivalent .*\n const regexBody = escaped.replace(/\\*/g, \".*\");\n\n let regexStr: string;\n if (anchored) {\n regexStr = `^${regexBody}$`;\n } else if (hasWildcard) {\n regexStr = `^${regexBody}`;\n } else {\n // No wildcards, no anchor: prefix match at segment boundary\n // Special case: \"/\" matches all paths\n if (pat === \"/\") {\n regexStr = `^/`;\n } else {\n regexStr = `^${regexBody}(/|$)`;\n }\n }\n\n if (new RegExp(regexStr).test(path)) {\n return pat.replace(/\\*/g, \"\").length;\n }\n\n return -1;\n}\n","import { loadKeyImport, loadJwtSign, loadDecodeJwt } from \"./jose\";\nimport { scorePathPattern } from \"./url-pattern\";\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 // Exact match — highest priority, return immediately\n if (patternPath === path) {\n if (debug) {\n console.debug(`Exact match found: ${block.urlPattern}`);\n }\n return block;\n }\n\n // Pattern match (wildcards, prefix, anchored)\n const specificity = scorePathPattern(patternPath, path);\n if (specificity > bestSpecificity) {\n bestSpecificity = specificity;\n bestMatch = block;\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 } else {\n await eventPromise;\n }\n\n return verification;\n}\n","import {\n HandlerAction,\n HandlerResult,\n ExecutionContext,\n CDNStatusDescription,\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): CDNStatusDescription {\n switch (status) {\n case 401: return CDNStatusDescription.Unauthorized;\n case 402: return CDNStatusDescription.PaymentRequired;\n case 403: return CDNStatusDescription.Forbidden;\n case 503: return CDNStatusDescription.ServiceUnavailable;\n default: return CDNStatusDescription.Error;\n }\n}\n\n/**\n * Handles an Origin request in CloudFront. Expects X-Original-Request-URL header to contain the original viewer request URL.\n * @param handler\n * @param event\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 viewerRequestUrl = cfRequest.headers?.[\"x-original-request-url\"]?.[0]?.value;\n const originRequestUrl = `${cfRequest.headers.host[0].value}${cfRequest.uri}`;\n const url = `https://${viewerRequestUrl ? viewerRequestUrl : originRequestUrl}${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 CDNStatusDescription,\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, CDNStatusDescription };\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 an origin-request LambdaEdge function.\n * @param event The CloudFront origin-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 const request = event?.Records?.[0]?.cf?.request as TRequest ?? {} as CloudFrontRequestResult<TRequest>;\n try {\n const license_auth_header = request.headers?.[\"x-license-auth\"];\n if (!license_auth_header) {\n // No license auth header means the request is either from a human or from an unidentifiable bot.\n // No reasons to waste compute resources on the rest of the checks.\n return request;\n }\n const instance = new SupertabConnect({\n apiKey: options.apiKey,\n enforcement: options.enforcement\n });\n return await handleCloudfrontRequest(instance, event);\n } catch (err) {\n console.error(\"[SupertabConnect] cloudfrontHandleRequests failed:\", err);\n return request;\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,IASAC,OACVA,EAAA,aAAe,eACfA,EAAA,gBAAkB,mBAClBA,EAAA,UAAY,YACZA,EAAA,mBAAqB,sBACrBA,EAAA,MAAQ,QALEA,OAAA,ICxEZ,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,ECL5D,SAASQ,EAAiBC,EAAiBC,EAAsB,CACtE,IAAIC,EAAW,GACXC,EAAMH,EAENG,EAAI,SAAS,GAAG,IAClBD,EAAW,GACXC,EAAMA,EAAI,MAAM,EAAG,EAAE,GAGvB,IAAMC,EAAcD,EAAI,SAAS,GAAG,EAK9BE,EAFUF,EAAI,QAAQ,qBAAsB,MAAM,EAE9B,QAAQ,MAAO,IAAI,EAEzCG,EAeJ,OAdIJ,EACFI,EAAW,IAAID,CA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AAAoB,EAAa,YAAAC,CAAY,EAAIrB,GAAW,CAAC,EAE3Ce,EAAW,IAAInB,EAAgB,CACnC,OAAQsB,EACR,YAAAE,EACA,YAAAC,CACF,CAAC,EAEGC,EACJ,OAAItB,GAAS,YACXsB,EAAa,CACX,QAAS1B,EAAgB,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,IAAMK,EAAUmB,GAAO,UAAU,CAAC,GAAG,IAAI,SAAuB,CAAC,EACjE,GAAI,CAEF,GAAI,CADwBnB,EAAQ,UAAU,gBAAgB,EAI5D,OAAOA,EAET,IAAMU,EAAW,IAAInB,EAAgB,CACnC,OAAQI,EAAQ,OAChB,YAAaA,EAAQ,WACvB,CAAC,EACD,OAAO,MAAMyB,EAAwBV,EAAUS,CAAK,CACtD,OAASP,EAAK,CACZ,eAAQ,MAAM,qDAAsDA,CAAG,EAChEZ,CACT,CACF,CACF,EAhUaT,EAEI,QAAkB,kCAFtBA,EAOI,UAAoC,KAP9C,IAAM8B,EAAN9B","names":["EnforcementMode","LicenseTokenInvalidReason","FASTLY_BACKEND","HandlerAction","CDNStatusDescription","lazyImport","load","cached","loadJwtVerify","loadDecodeJwt","loadDecodeProtectedHeader","loadKeyImport","loadJwtSign","scorePathPattern","pattern","path","anchored","pat","hasWildcard","regexBody","regexStr","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","specificity","scorePathPattern","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","viewerRequestUrl","originRequestUrl","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"]}
|