@getsupertab/supertab-connect-sdk 0.1.0-beta.32 → 0.1.0-beta.33
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 +73 -11
- package/dist/index.d.ts +73 -11
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/package.json +5 -3
package/dist/index.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var w=Object.defineProperty;var P=Object.getOwnPropertyDescriptor;var N=Object.getOwnPropertyNames;var C=Object.prototype.hasOwnProperty;var x=(r,e)=>{for(var t in e)w(r,t,{get:e[t],enumerable:!0})},D=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of N(e))!C.call(r,i)&&i!==t&&w(r,i,{get:()=>e[i],enumerable:!(n=P(e,i))||n.enumerable});return r};var q=r=>D(w({},"__esModule",{value:!0}),r);var $={};x($,{SupertabConnect:()=>A});module.exports=q($);var f="stc-backend";var L=require("jose");async function F(r,e,t){try{let n=await fetch(r,e);if(!n.ok){let s=await n.text().catch(()=>""),o=`Failed to obtain license token: ${n.status} ${n.statusText}${s?` - ${s}`:""}`;throw new Error(o)}let i;try{i=await n.json()}catch(s){throw t&&console.error("Failed to parse license token response as JSON:",s),new Error("Failed to parse license token response as JSON")}if(!i?.access_token)throw new Error("License token response missing access_token");return i.access_token}catch(n){throw t&&console.error("Error generating license token:",n),n}}async function v({clientId:r,clientSecret:e,tokenEndpoint:t,resourceUrl:n,licenseXml:i,debug:s}){let o=new URLSearchParams({grant_type:"client_credentials",license:i,resource:n}),p={method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json",Authorization:"Basic "+btoa(`${r}:${e}`)},body:o.toString()};return F(t,p,s)}var m=require("jose");var E=new Map;function K(){let r={method:"GET"};return globalThis?.fastly&&(r={...r,backend:f}),r}async function O({cacheKey:r,url:e,debug:t,failureMessage:n,logLabel:i}){if(!E.has(r))try{let s=await fetch(e,K());if(!s.ok)throw new Error(`${n}: ${s.status}`);let o=await s.json();E.set(r,o)}catch(s){throw t&&console.error(i,s),s}return E.get(r)}async function T(r,e){let t=`${r}/.well-known/jwks.json/platform`;return console.log("Fetching platform JWKS from:",t),O({cacheKey:"platform_jwks",url:t,debug:e,failureMessage:"Failed to fetch platform JWKS",logLabel:"Error fetching platform JWKS:"})}var I=r=>r.replace(/\/+$/,"");async function b({licenseToken:r,requestUrl:e,supertabBaseUrl:t,debug:n}){if(!r)return{valid:!1,reason:"missing_license_token"};let i;try{i=(0,m.decodeProtectedHeader)(r)}catch(a){return n&&console.error("Invalid license JWT header:",a),{valid:!1,reason:"invalid_license_header"}}if(i.alg!=="ES256")return n&&console.error("Unsupported license JWT alg:",i.alg),{valid:!1,reason:"invalid_license_algorithm"};let s;try{s=(0,m.decodeJwt)(r)}catch(a){return n&&console.error("Invalid license JWT payload:",a),{valid:!1,reason:"invalid_license_payload"}}let o=s.license_id,p=s.iss;if(!p||!p.startsWith(t))return n&&console.error("Invalid license JWT issuer:",p),{valid:!1,reason:"invalid_license_issuer",licenseId:o};let d=Array.isArray(s.aud)?s.aud.filter(a=>typeof a=="string"):typeof s.aud=="string"?[s.aud]:[],g=I(e);if(!d.some(a=>{let u=I(a);return u?g.startsWith(u):!1}))return n&&console.error("License JWT audience does not match request URL:",s.aud),{valid:!1,reason:"invalid_license_audience",licenseId:o};try{let a=await T(t,n),h=await(0,m.jwtVerify)(r,async y=>{let k=a.keys.find(U=>U.kid===y.kid);if(!k)throw new Error(`No matching platform key found: ${y.kid}`);return k},{issuer:p,algorithms:[i.alg],clockTolerance:"1m"});return{valid:!0,licenseId:o,payload:h.payload}}catch(a){return n&&console.error("License JWT verification failed:",a),a instanceof Error&&a.message?.includes("exp")?{valid:!1,reason:"license_token_expired",licenseId:o}:{valid:!1,reason:"license_signature_verification_failed",licenseId:o}}}function J({requestUrl:r}){let e=new URL(r);return`${e.protocol}//${e.host}/license.xml`}async function R({licenseToken:r,url:e,userAgent:t,ctx:n,supertabBaseUrl:i,merchantSystemUrn:s,debug:o,recordEvent:p}){let d=await b({licenseToken:r,requestUrl:e,supertabBaseUrl:i,debug:o});async function g(l){let a={page_url:e,user_agent:t,verification_status:d.valid?"valid":"invalid",verification_reason:d.reason||"success"},u=p(l,a,d.licenseId);return n?.waitUntil&&n.waitUntil(u),u}if(!d.valid){await g(d.reason||"license_token_verification_failed");let l="invalid_request",a="Access to this resource requires a license";switch(d.reason){case"missing_license_token":l="invalid_request",a="Access to this resource requires a license";break;case"license_token_expired":l="invalid_token",a="The license token has expired";break;case"license_signature_verification_failed":l="invalid_token",a="The license token signature is invalid";break;case"invalid_license_header":l="invalid_token",a="The license token header is invalid";break;case"invalid_license_payload":l="invalid_token",a="The license token payload is invalid";break;case"invalid_license_issuer":l="invalid_token",a="The license token issuer is invalid";break;case"invalid_license_audience":l="invalid_token",a="The license token audience is invalid";break;default:l="invalid_request",a="Access to this resource requires a license"}let u=J({requestUrl:e}),h=`${i}/docs/errors#${l}`,y=new Headers({"Content-Type":"text/plain; charset=UTF-8","WWW-Authenticate":`License error="${l}", error_description="${a}", error_uri="${h}"`,Link:`${u}; rel="license"; type="application/rsl+xml"`}),k=`Access to this resource requires a valid license token. Error: ${l} - ${a}`;return new Response(k,{status:401,headers:y})}return await g("license_used"),new Response("\u2705 License Token Access granted",{status:200,headers:new Headers({"Content-Type":"application/json"})})}function H(){let r={method:"GET"};return globalThis?.fastly&&(r={...r,backend:f}),r}async function S(r,e){let t=`${r}/merchants/systems/${e}/license.xml`,n=await fetch(t,H());if(!n.ok)return new Response("License not found",{status:404});let i=await n.text();return new Response(i,{status:200,headers:new Headers({"Content-Type":"application/xml"})})}var _=!0,c=class c{constructor(e,t=!1){if(!t&&c._instance){if(!(e.apiKey===c._instance.apiKey&&e.merchantSystemUrn===c._instance.merchantSystemUrn))throw new Error("Cannot create a new instance with different configuration. Use resetInstance to clear the existing instance.");return c._instance}if(t&&c._instance&&c.resetInstance(),!e.apiKey||!e.merchantSystemUrn)throw new Error("Missing required configuration: apiKey and merchantSystemUrn are required");this.apiKey=e.apiKey,this.merchantSystemUrn=e.merchantSystemUrn,c._instance=this}static resetInstance(){c._instance=null}static setBaseUrl(e){c.baseUrl=e}async verifyLicenseToken(e,t){return b({licenseToken:e,requestUrl:t,supertabBaseUrl:c.baseUrl,debug:_})}async recordEvent(e,t={},n){let i={event_name:e,merchant_system_urn:this.merchantSystemUrn?this.merchantSystemUrn:"",license_id:n,properties:t};try{let s={method:"POST",headers:{Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify(i)};globalThis?.fastly&&(s={...s,backend:f});let o=await fetch(`${c.baseUrl}/events`,s);o.ok||console.log(`Failed to record event: ${o.status}`)}catch(s){console.log("Error recording event:",s)}}static checkIfBotRequest(e){let t=e.headers.get("User-Agent")||"",n=e.headers.get("accept")||"",i=e.headers.get("sec-ch-ua"),s=e.headers.get("accept-language"),o=e.cf?.botManagement?.score,p=["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"],d=t.toLowerCase(),g=p.some(y=>d.includes(y)),l=t.toLowerCase().includes("headless")||t.toLowerCase().includes("puppeteer")||!i,a=!t.toLowerCase().includes("headless")||!t.toLowerCase().includes("puppeteer")||!i,u=!n||!s,h=typeof o=="number"&&o<30;return console.log("Bot Detection Details:",{botUaMatch:g,headlessIndicators:l,missingHeaders:u,lowBotScore:h,botScore:o}),(d.includes("safari")||d.includes("mozilla"))&&l&&a?!1:g||l||u||h}static async cloudflareHandleRequests(e,t,n){let{MERCHANT_SYSTEM_URN:i,MERCHANT_API_KEY:s}=t;return new c({apiKey:s,merchantSystemUrn:i}).handleRequest(e,c.checkIfBotRequest,n)}static async fastlyHandleRequests(e,t,n,i=!1){let s=new c({apiKey:n,merchantSystemUrn:t});return i&&new URL(e.url).pathname==="/license.xml"?await S(c.baseUrl,t):s.handleRequest(e,c.checkIfBotRequest,null)}async handleRequest(e,t,n){let i=e.headers.get("Authorization")||"",s=i.startsWith("License ")?i.slice(8):"",o=e.url,p=e.headers.get("User-Agent")||"unknown";return t&&!t(e,n)?new Response("\u2705 Non-Bot Content Access granted",{status:200,headers:new Headers({"Content-Type":"application/json"})}):R({licenseToken:s,url:o,userAgent:p,ctx:n,supertabBaseUrl:c.baseUrl,merchantSystemUrn:this.merchantSystemUrn,debug:_,recordEvent:(d,g,l)=>this.recordEvent(d,g,l)})}static async obtainLicenseToken(e,t,n,i){let s=c.baseUrl+"/rsl/token";return v({clientId:e,clientSecret:t,tokenEndpoint:s,resourceUrl:n,licenseXml:i,debug:_})}};c.baseUrl="https://api-connect.supertab.co",c._instance=null;var A=c;0&&(module.exports={SupertabConnect});
|
|
1
|
+
"use strict";var H=Object.create;var R=Object.defineProperty;var W=Object.getOwnPropertyDescriptor;var M=Object.getOwnPropertyNames;var V=Object.getPrototypeOf,j=Object.prototype.hasOwnProperty;var X=(n,e)=>{for(var r in e)R(n,r,{get:e[r],enumerable:!0})},P=(n,e,r,t)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of M(e))!j.call(n,s)&&s!==r&&R(n,s,{get:()=>e[s],enumerable:!(t=W(e,s))||t.enumerable});return n};var G=(n,e,r)=>(r=n!=null?H(V(n)):{},P(e||!n||!n.__esModule?R(r,"default",{value:n,enumerable:!0}):r,n)),z=n=>P(R({},"__esModule",{value:!0}),n);var oe={};X(oe,{EnforcementMode:()=>L,HandlerAction:()=>y,SupertabConnect:()=>U,defaultBotDetector:()=>K});module.exports=z(oe);var L=(t=>(t.DISABLED="disabled",t.SOFT="soft",t.STRICT="strict",t))(L||{});var g="stc-backend",y=(r=>(r.ALLOW="allow",r.BLOCK="block",r))(y||{});var E=null;function v(){return E||(E=import("jose")),E}async function Y(n,e,r){try{let t=await fetch(n,e);if(!t.ok){let o=await t.text().catch(()=>""),i=`Failed to obtain license token: ${t.status} ${t.statusText}${o?` - ${o}`:""}`;throw new Error(i)}let s;try{s=await t.json()}catch(o){throw r&&console.error("Failed to parse license token response as JSON:",o),new Error("Failed to parse license token response as JSON")}if(!s?.access_token)throw new Error("License token response missing access_token");return s.access_token}catch(t){throw r&&console.error("Error generating license token:",t),t}}async function Q(n,e){let t=`${new URL(n).origin}/license.xml`,s=await fetch(t);if(!s.ok)throw e&&console.error(`Failed to fetch license.xml from ${t}: ${s.status}`),new Error(`Failed to fetch license.xml from ${t}: ${s.status}`);let o=await s.text();return e&&console.debug("Fetched license.xml from",t),o}function Z(n,e){let r=[],t=/<content\s([^>]*)>([\s\S]*?)<\/content>/gi,s=/url\s*=\s*"([^"]*)"/i,o=/server\s*=\s*"([^"]*)"/i,i=/<license[^>]*>[\s\S]*?<\/license>/i,a=0,c;for(;(c=t.exec(n))!==null;){a++;let l=c[1],d=c[2],f=l.match(s),h=l.match(o),m=d.match(i);if(f&&h&&m)r.push({urlPattern:f[1],server:h[1],licenseXml:m[0]});else if(e){let w=[!f&&"url",!h&&"server",!m&&"<license>"].filter(Boolean).join(", ");console.debug(`Skipping <content> element #${a}: missing ${w}`)}}return e&&console.debug(`Found ${a} <content> element(s), ${r.length} valid`),r}function ee(n,e,r){let t=new URL(e),s=t.host,o=t.pathname;r&&console.debug(`Matching resource URL: ${e} (host=${s}, path=${o})`);let i=null,a=-1;for(let c of n){let l;try{l=new URL(c.urlPattern)}catch{r&&console.debug(`Skipping block with invalid URL pattern: ${c.urlPattern}`);continue}if(l.host!==s){r&&console.debug(`Skipping block: host mismatch (pattern=${l.host}, resource=${s})`);continue}let d=l.pathname;if(d===o)return r&&console.debug(`Exact match found: ${c.urlPattern}`),c;if(d.endsWith("/*")){let f=d.slice(0,-1);if(o.startsWith(f)){let h=f.length;h>a&&(a=h,i=c)}}}return r&&console.debug(i?`Wildcard match found: ${i.urlPattern} (specificity=${a})`:`No matching content block found for ${e}`),i}async function C({clientId:n,clientSecret:e,resourceUrl:r,debug:t}){let s=await Q(r,t);t&&console.debug(`Fetched license.xml (${s.length} chars)`);let o=Z(s,t);if(o.length===0)throw t&&console.error("No valid <content> elements with <license> found in license.xml"),new Error("No valid <content> elements with <license> found in license.xml");let i=ee(o,r,t);if(!i){if(t){let d=o.map(f=>f.urlPattern).join(", ");console.error(`No <content> element matches resource URL: ${r}. Available patterns: ${d}`)}throw new Error(`No <content> element in license.xml matches resource URL: ${r}`)}t&&(console.debug("Matched content block for resource URL:",r),console.debug("Using license XML:",i.licenseXml));let a=i.server+"/token";t&&console.debug(`Requesting license token from ${a}`);let c=new URLSearchParams({grant_type:"client_credentials",license:i.licenseXml,resource:i.urlPattern}),l={method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json",Authorization:"Basic "+btoa(`${n}:${e}`)},body:c.toString()};return Y(a,l,t)}var A=new Map;function te(){let n={method:"GET"};return globalThis?.fastly&&(n={...n,backend:g}),n}async function ne({cacheKey:n,url:e,debug:r,failureMessage:t,logLabel:s}){if(!A.has(n))try{let o=await fetch(e,te());if(!o.ok)throw new Error(`${t}: ${o.status}`);let i=await o.json();A.set(n,i)}catch(o){throw r&&console.error(s,o),o}return A.get(n)}async function D(n,e){let r=`${n}/.well-known/jwks.json/platform`;return e&&console.debug(`Fetching platform JWKS from URL: ${r}`),ne({cacheKey:"platform_jwks",url:r,debug:e,failureMessage:"Failed to fetch platform JWKS",logLabel:"Error fetching platform JWKS:"})}var k=n=>n.trim().replace(/\/+$/,"");async function S({licenseToken:n,requestUrl:e,supertabBaseUrl:r,debug:t}){let{decodeProtectedHeader:s,decodeJwt:o,jwtVerify:i}=await v();if(!n)return{valid:!1,reason:"missing_license_token"};let a;try{a=s(n)}catch(p){return t&&console.error("Invalid license JWT header:",p),{valid:!1,reason:"invalid_license_header"}}if(a.alg!=="ES256")return t&&console.error("Unsupported license JWT alg:",a.alg),{valid:!1,reason:"invalid_license_algorithm"};let c;try{c=o(n)}catch(p){return t&&console.error("Invalid license JWT payload:",p),{valid:!1,reason:"invalid_license_payload"}}let l=c.license_id,d=c.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",licenseId:l};let m=Array.isArray(c.aud)?c.aud.filter(p=>typeof p=="string"):typeof c.aud=="string"?[c.aud]:[],w=k(e);if(!m.some(p=>{let b=k(p);return b?w.startsWith(b):!1}))return t&&console.error("License JWT audience does not match request URL:",c.aud),{valid:!1,reason:"invalid_license_audience",licenseId:l};let _;try{_=await D(r,t)}catch(p){return t&&console.error("Failed to fetch platform JWKS:",p),{valid:!1,reason:"server_error",licenseId:l}}try{let b=await i(n,async I=>{let x=_.keys.find(q=>q.kid===I.kid);if(!x)throw new Error(`No matching platform key found: ${I.kid}`);return x},{issuer:d,algorithms:[a.alg],clockTolerance:"1m"});return{valid:!0,licenseId:l,payload:b.payload}}catch(p){return t&&console.error("License JWT verification failed:",p),p instanceof Error&&p.message?.includes("exp")?{valid:!1,reason:"license_token_expired",licenseId:l}:{valid:!1,reason:"license_signature_verification_failed",licenseId:l}}}function B({requestUrl:n}){let e=new URL(n);return`${e.protocol}//${e.host}/license.xml`}function N(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 T({reason:n,requestUrl:e,supertabBaseUrl:r}){let t,s,o;switch(n){case"missing_license_token":o=401,t="invalid_request",s="Authorization header missing or malformed";break;case"invalid_license_algorithm":o=401,t="invalid_request",s="Unsupported token algorithm";break;case"license_token_expired":o=401,t="invalid_token",s="The license token has expired";break;case"license_signature_verification_failed":o=401,t="invalid_token",s="The license token signature is invalid";break;case"invalid_license_header":o=401,t="invalid_token",s="The license token header is malformed";break;case"invalid_license_payload":o=401,t="invalid_token",s="The license token payload is malformed";break;case"invalid_license_issuer":o=401,t="invalid_token",s="The license token issuer is not recognized";break;case"invalid_license_audience":o=403,t="insufficient_scope",s="The license does not grant access to this resource";break;case"server_error":o=503,t="server_error",s="The server encountered an error validating the license";break;default:o=401,t="invalid_token",s="License token missing, expired, revoked, or malformed"}let i=B({requestUrl:e});return{action:"block",status:o,body:`Access to this resource requires a valid license token. Error: ${t} - ${s}`,headers:{"Content-Type":"text/plain; charset=UTF-8","WWW-Authenticate":`License error="${t}", error_description="${s}"`,Link:`<${i}>; rel="license"; type="application/rsl+xml"`}}}function se(){let n={method:"GET"};return globalThis?.fastly&&(n={...n,backend:g}),n}async function $(n,e){let r=`${n}/merchants/systems/${e}/license.xml`,t=await fetch(r,se());if(!t.ok)return new Response("License not found",{status:404});let s=await t.text();return new Response(s,{status:200,headers:new Headers({"Content-Type":"application/xml"})})}async function O(n){let e=await S({licenseToken:n.token,requestUrl:n.url,supertabBaseUrl:n.supertabBaseUrl,debug:n.debug});if(n.recordEvent){let r=e.valid?"license_used":e.reason,t={page_url:n.url,user_agent:n.userAgent,verification_status:e.valid?"valid":"invalid",verification_reason:e.valid?"success":e.reason},s=n.recordEvent(r,t,e.licenseId);n.ctx?.waitUntil&&n.ctx.waitUntil(s)}return e.valid?{action:"allow"}:T({reason:e.reason,requestUrl:n.url,supertabBaseUrl:n.supertabBaseUrl})}async function F(n,e,r){let t=await n.handleRequest(e,r);if(t.action==="block")return new Response(t.body,{status:t.status,headers:new Headers(t.headers)});let s=await fetch(e);if(t.headers){let o=new Response(s.body,s);for(let[i,a]of Object.entries(t.headers))o.headers.set(i,a);return o}return s}async function J(n,e,r,t){if(t&&new URL(e.url).pathname==="/license.xml")return await $(t.baseUrl,t.merchantSystemUrn);let s=await n.handleRequest(e);if(s.action==="block")return new Response(s.body,{status:s.status,headers:new Headers(s.headers)});let o=await fetch(e,{backend:r});if(s.headers){let i=new Response(o.body,o);for(let[a,c]of Object.entries(s.headers))i.headers.set(a,c);return i}return o}function K(n){let e=n.headers.get("User-Agent")||"",r=n.headers.get("accept")||"",t=n.headers.get("sec-ch-ua"),s=n.headers.get("accept-language"),o=n.cf?.botManagement?.score,i=["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"],a=e.toLowerCase(),c=i.some(m=>a.includes(m)),l=e.toLowerCase().includes("headless")||e.toLowerCase().includes("puppeteer")||!t,d=!e.toLowerCase().includes("headless")&&!e.toLowerCase().includes("puppeteer")&&!t,f=!r||!s,h=typeof o=="number"&&o<30;return(a.includes("safari")||a.includes("mozilla"))&&l&&d?!1:c||l||f||h}var u=class u{constructor(e,r=!1){if(!r&&u._instance){if(!(e.apiKey===u._instance.apiKey&&e.merchantSystemUrn===u._instance.merchantSystemUrn))throw new Error("Cannot create a new instance with different configuration. Use resetInstance to clear the existing instance.");return u._instance}if(r&&u._instance&&u.resetInstance(),!e.apiKey||!e.merchantSystemUrn)throw new Error("Missing required configuration: apiKey and merchantSystemUrn are required");this.apiKey=e.apiKey,this.merchantSystemUrn=e.merchantSystemUrn,this.enforcement=e.enforcement??"soft",this.botDetector=e.botDetector,this.debug=e.debug??!1,u._instance=this}static resetInstance(){u._instance=null}static setBaseUrl(e){u.baseUrl=e}static getBaseUrl(){return u.baseUrl}async verifyLicenseToken(e,r){return S({licenseToken:e,requestUrl:r,supertabBaseUrl:u.baseUrl,debug:this.debug})}async recordEvent(e,r={},t){let s={event_name:e,merchant_system_urn:this.merchantSystemUrn?this.merchantSystemUrn:"",license_id:t,properties:r};try{let o={method:"POST",headers:{Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify(s)};globalThis?.fastly&&(o={...o,backend:g});let i=await fetch(`${u.baseUrl}/events`,o);i.ok||console.log(`Failed to record event: ${i.status}`)}catch(o){console.log("Error recording event:",o)}}async handleRequest(e,r){let t=e.headers.get("Authorization")||"",s=t.startsWith("License ")?t.slice(8):null,o=e.url,i=e.headers.get("User-Agent")||"unknown";if(s)return this.enforcement==="disabled"?{action:"allow"}:O({token:s,url:o,userAgent:i,supertabBaseUrl:u.baseUrl,debug:this.debug,recordEvent:this.recordEvent.bind(this),ctx:r});if(!(this.botDetector?.(e,r)??!1))return{action:"allow"};switch(this.enforcement){case"strict":return T({reason:"missing_license_token",requestUrl:o,supertabBaseUrl:u.baseUrl});case"soft":return N(o);default:return{action:"allow"}}}static async obtainLicenseToken(e,r,t,s=!1){return C({clientId:e,clientSecret:r,resourceUrl:t,debug:s})}static async cloudflareHandleRequests(e,r,t){let s=new u({apiKey:r.MERCHANT_API_KEY,merchantSystemUrn:r.MERCHANT_SYSTEM_URN});return F(s,e,t)}static async fastlyHandleRequests(e,r,t,s,o){let{enableRSL:i=!1,botDetector:a,enforcement:c}=o??{},l=new u({apiKey:t,merchantSystemUrn:r,botDetector:a,enforcement:c});return J(l,e,s,i?{baseUrl:u.baseUrl,merchantSystemUrn:r}:void 0)}};u.baseUrl="https://api-connect.supertab.co",u._instance=null;var U=u;0&&(module.exports={EnforcementMode,HandlerAction,SupertabConnect,defaultBotDetector});
|
|
2
2
|
//# sourceMappingURL=index.cjs.map
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/types.ts","../src/customer.ts","../src/license.ts","../src/jwks.ts"],"sourcesContent":["import {\n SupertabConnectConfig,\n Env,\n EventPayload,\n FASTLY_BACKEND,\n LicenseTokenVerificationResult,\n} from \"./types\";\nimport { obtainLicenseToken as obtainLicenseTokenHelper } from \"./customer\";\nimport {\n baseLicenseHandleRequest as baseLicenseHandleRequestHelper,\n hostRSLicenseXML as hostRSLicenseXMLHelper,\n verifyLicenseToken as verifyLicenseTokenHelper,\n} from \"./license\";\n\nexport type { Env } from \"./types\";\n\nconst debug = true; // Set to true for debugging purposes\n\n/**\n * SupertabConnect class provides higher level methods\n * for using Supertab Connect within supported CDN integrations\n * as well as more specialized methods to customarily verify JWT tokens and record events.\n */\nexport class SupertabConnect {\n private apiKey?: string;\n private static baseUrl: string = \"https://api-connect.supertab.co\";\n private merchantSystemUrn!: string;\n\n private static _instance: SupertabConnect | null = null;\n\n public constructor(config: SupertabConnectConfig, reset: boolean = false) {\n if (!reset && SupertabConnect._instance) {\n // If reset was not requested and an instance conflicts with the provided config, throw an error\n if (\n !(\n config.apiKey === SupertabConnect._instance.apiKey &&\n config.merchantSystemUrn ===\n SupertabConnect._instance.merchantSystemUrn\n )\n ) {\n throw new Error(\n \"Cannot create a new instance with different configuration. Use resetInstance to clear the existing instance.\"\n );\n }\n\n // If an instance already exists and reset is not requested, just return the existing instance\n return SupertabConnect._instance;\n }\n if (reset && SupertabConnect._instance) {\n // ...and if reset is requested and required, clear the existing instance first\n SupertabConnect.resetInstance();\n }\n\n if (!config.apiKey || !config.merchantSystemUrn) {\n throw new Error(\n \"Missing required configuration: apiKey and merchantSystemUrn are required\"\n );\n }\n this.apiKey = config.apiKey;\n this.merchantSystemUrn = config.merchantSystemUrn;\n\n // Register this as the singleton instance\n SupertabConnect._instance = this;\n }\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 * Verify a license token\n * @param licenseToken The license token to verify\n * @param requestUrl The URL of the request being made\n * @returns A promise that resolves with the verification result\n */\n async verifyLicenseToken(\n licenseToken: string,\n requestUrl: string\n ): Promise<LicenseTokenVerificationResult> {\n return verifyLicenseTokenHelper({\n licenseToken,\n requestUrl,\n supertabBaseUrl: SupertabConnect.baseUrl,\n debug,\n });\n }\n\n /**\n * Records an analytics event\n * @param eventName Name of the event to record\n * @param properties Additional properties to include with the event\n * @param licenseId Optional license ID associated with the event\n * @returns Promise that resolves when the event is recorded\n */\n async recordEvent(\n eventName: string,\n properties: Record<string, any> = {},\n licenseId?: string\n ): Promise<void> {\n const payload: EventPayload = {\n event_name: eventName,\n merchant_system_urn: this.merchantSystemUrn ? this.merchantSystemUrn : \"\",\n license_id: licenseId,\n properties,\n };\n\n try {\n let options: any = {\n method: \"POST\",\n headers: {\n Authorization: `Bearer ${this.apiKey}`,\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(payload),\n };\n // @ts-ignore\n if (globalThis?.fastly) {\n options = { ...options, backend: FASTLY_BACKEND };\n }\n const response = await fetch(\n `${SupertabConnect.baseUrl}/events`,\n options\n );\n\n if (!response.ok) {\n console.log(`Failed to record event: ${response.status}`);\n }\n } catch (error) {\n console.log(\"Error recording event:\", error);\n }\n }\n\n\n static checkIfBotRequest(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 userAgent.toLowerCase().includes(\"headless\") ||\n userAgent.toLowerCase().includes(\"puppeteer\") ||\n !secChUa;\n\n const only_sec_ch_ua_missing =\n !userAgent.toLowerCase().includes(\"headless\") ||\n !userAgent.toLowerCase().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 console.log(\"Bot Detection Details:\", {\n botUaMatch,\n headlessIndicators,\n missingHeaders,\n lowBotScore,\n botScore,\n });\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 && only_sec_ch_ua_missing) {\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\n static async cloudflareHandleRequests(\n request: Request,\n env: Env,\n ctx: any\n ): Promise<Response> {\n // Validate required env variables\n const { MERCHANT_SYSTEM_URN, MERCHANT_API_KEY } = env;\n\n // Prepare or get the SupertabConnect instance\n const supertabConnect = new SupertabConnect({\n apiKey: MERCHANT_API_KEY,\n merchantSystemUrn: MERCHANT_SYSTEM_URN,\n });\n\n // Handle the request, including bot detection, token verification and recording the event\n return supertabConnect.handleRequest(\n request,\n SupertabConnect.checkIfBotRequest,\n ctx\n );\n }\n\n static async fastlyHandleRequests(\n request: Request,\n merchantSystemUrn: string,\n merchantApiKey: string,\n enableRSL: boolean = false,\n ): Promise<Response> {\n // Prepare or get the SupertabConnect instance\n const supertabConnect = new SupertabConnect({\n apiKey: merchantApiKey,\n merchantSystemUrn: merchantSystemUrn,\n });\n\n if (enableRSL) {\n if (new URL(request.url).pathname === \"/license.xml\") {\n return await hostRSLicenseXMLHelper(\n SupertabConnect.baseUrl,\n merchantSystemUrn\n );\n }\n }\n\n // Handle the request, including bot detection, token verification and recording the event\n return supertabConnect.handleRequest(\n request,\n SupertabConnect.checkIfBotRequest,\n null\n );\n }\n\n async handleRequest(\n request: Request,\n botDetectionHandler?: (request: Request, ctx?: any) => boolean,\n ctx?: any\n ): Promise<Response> {\n // 1. Extract license token, URL, and user agent from the request\n const auth = request.headers.get(\"Authorization\") || \"\";\n const licenseToken = auth.startsWith(\"License \") ? auth.slice(8) : \"\";\n const url = request.url;\n const user_agent = request.headers.get(\"User-Agent\") || \"unknown\";\n\n // 2. Handle bot detection if provided\n if (botDetectionHandler && !botDetectionHandler(request, ctx)) {\n return new Response(\"✅ Non-Bot Content Access granted\", {\n status: 200,\n headers: new Headers({ \"Content-Type\": \"application/json\" }),\n });\n }\n\n // 3. Handle the license token request\n return baseLicenseHandleRequestHelper({\n licenseToken,\n url,\n userAgent: user_agent,\n ctx,\n supertabBaseUrl: SupertabConnect.baseUrl,\n merchantSystemUrn: this.merchantSystemUrn,\n debug,\n recordEvent: (\n eventName: string,\n properties?: Record<string, any>,\n licenseId?: string\n ) => this.recordEvent(eventName, properties, licenseId),\n });\n }\n\n /**\n * Request a license token from the Supertab Connect token endpoint.\n * @param clientId OAuth client identifier.\n * @param clientSecret OAuth client secret for client_credentials flow.\n * @param resourceUrl Resource URL attempting to access with a License.\n * @param licenseXml XML license document to include in the request payload.\n * @returns Promise resolving to the issued license access token string.\n */\n static async obtainLicenseToken(\n clientId: string,\n clientSecret: string,\n resourceUrl: string,\n licenseXml: string\n ): Promise<string> {\n const tokenEndpoint = SupertabConnect.baseUrl + \"/rsl/token\";\n return obtainLicenseTokenHelper({\n clientId,\n clientSecret,\n tokenEndpoint,\n resourceUrl,\n licenseXml,\n debug,\n });\n }\n}\n","export interface SupertabConnectConfig {\n apiKey: string;\n merchantSystemUrn: string;\n}\n\n/**\n * Defines the shape for environment variables (used in CloudFlare integration).\n * These are used to identify and authenticate the Merchant System with the Supertab Connect API.\n */\nexport interface Env {\n\t/** The unique identifier for the merchant system. */\n\tMERCHANT_SYSTEM_URN: string;\n\t/** The API key for authenticating with the Supertab Connect. */\n\tMERCHANT_API_KEY: string;\n\t[key: string]: string;\n}\n\nexport interface EventPayload {\n event_name: string;\n license_id?: string;\n merchant_system_urn: string;\n properties: Record<string, any>;\n}\n\nexport interface LicenseTokenVerificationResult {\n valid: boolean;\n reason?: string;\n licenseId?: string;\n payload?: any;\n}\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}\n\nexport const FASTLY_BACKEND = \"stc-backend\";\n\nexport interface FetchOptions extends RequestInit {\n // Fastly-specific extension for backend routing\n backend?: string;\n}","import { importPKCS8, SignJWT } from \"jose\";\n\ntype SupportedAlg = \"RS256\" | \"ES256\";\n\ntype GenerateLicenseTokenParams = {\n clientId: string;\n kid: string;\n privateKeyPem: string;\n tokenEndpoint: string;\n resourceUrl: string;\n licenseXml: string;\n debug?: boolean;\n};\n\ntype ObtainLicenseTokenParams = {\n clientId: string;\n clientSecret: string;\n tokenEndpoint: string;\n resourceUrl: string;\n licenseXml: string;\n debug?: boolean;\n};\n\nasync function retrieveLicenseToken(\n tokenEndpoint: string,\n requestOptions: RequestInit,\n debug: boolean | undefined\n) {\n try {\n const response = await fetch(tokenEndpoint, requestOptions);\n\n if (!response.ok) {\n const errorBody = await response.text().catch(() => \"\");\n const errorMessage = `Failed to obtain license token: ${\n response.status\n } ${response.statusText}${errorBody ? ` - ${errorBody}` : \"\"}`;\n throw new Error(errorMessage);\n }\n\n let data: any;\n try {\n data = await response.json();\n } catch (parseError) {\n if (debug) {\n console.error(\n \"Failed to parse license token response as JSON:\",\n parseError\n );\n }\n throw new Error(\"Failed to parse license token response as JSON\");\n }\n\n if (!data?.access_token) {\n throw new Error(\"License token response missing access_token\");\n }\n\n return data.access_token;\n } catch (error) {\n if (debug) {\n console.error(\"Error generating license token:\", error);\n }\n throw error;\n }\n}\n\nasync function importKeyForAlgs(\n privateKeyPem: string,\n debug: boolean | undefined\n): Promise<{ key: CryptoKey; alg: SupportedAlg }> {\n const 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 { 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\nexport async function obtainLicenseToken({\n clientId,\n clientSecret,\n tokenEndpoint,\n resourceUrl,\n licenseXml,\n debug,\n}: ObtainLicenseTokenParams): Promise<string> {\n const payload = new URLSearchParams({\n grant_type: \"client_credentials\",\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 Authorization: \"Basic \" + btoa(`${clientId}:${clientSecret}`),\n },\n body: payload.toString(),\n };\n\n return retrieveLicenseToken(tokenEndpoint, requestOptions, debug);\n}\n\nexport type { GenerateLicenseTokenParams, ObtainLicenseTokenParams };\n","import {\n decodeProtectedHeader,\n decodeJwt,\n JWTPayload,\n JWTHeaderParameters,\n jwtVerify,\n} from \"jose\";\nimport {\n LicenseTokenInvalidReason,\n LicenseTokenVerificationResult,\n FASTLY_BACKEND,\n FetchOptions,\n} from \"./types\";\nimport { fetchPlatformJwks } from \"./jwks\";\n\nconst stripTrailingSlash = (value: string) => value.replace(/\\/+$/, \"\");\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 if (!licenseToken) {\n return {\n valid: false,\n reason: 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 };\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 };\n }\n\n let payload: JWTPayload;\n try {\n payload = decodeJwt(licenseToken);\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 };\n }\n\n // @ts-ignore\n const licenseId: string | undefined = payload.license_id;\n\n const issuer: string | undefined = payload.iss;\n if (!issuer || !issuer.startsWith(supertabBaseUrl)) {\n if (debug) {\n console.error(\"Invalid license JWT issuer:\", issuer);\n }\n return {\n valid: false,\n reason: 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 licenseId,\n };\n }\n\n try {\n const jwks = await fetchPlatformJwks(supertabBaseUrl, debug);\n\n const getKey = async (jwtHeader: JWTHeaderParameters) => {\n const jwk = jwks.keys.find((key: any) => key.kid === jwtHeader.kid);\n if (!jwk) {\n throw new Error(`No matching platform key found: ${jwtHeader.kid}`);\n }\n return jwk;\n };\n\n const result = await jwtVerify(licenseToken, getKey, {\n issuer,\n algorithms: [header.alg],\n clockTolerance: \"1m\",\n });\n\n return {\n valid: true,\n licenseId,\n payload: result.payload,\n };\n } catch (error) {\n if (debug) {\n console.error(\"License JWT verification failed:\", error);\n }\n\n if (error instanceof Error && error.message?.includes(\"exp\")) {\n return {\n valid: false,\n reason: LicenseTokenInvalidReason.EXPIRED,\n licenseId,\n };\n }\n\n return {\n valid: false,\n reason: LicenseTokenInvalidReason.SIGNATURE_VERIFICATION_FAILED,\n licenseId,\n };\n }\n}\n\nexport function generateLicenseLink({\n requestUrl,\n}: {\n requestUrl: string;\n}): string {\n const baseURL = new URL(requestUrl);\n return `${baseURL.protocol}//${baseURL.host}/license.xml`;\n}\n\ntype RecordEventFn = (\n eventName: string,\n properties?: Record<string, any>,\n licenseId?: string\n) => Promise<void>;\n\ntype BaseLicenseHandleRequestParams = {\n licenseToken: string;\n url: string;\n userAgent: string;\n ctx: any;\n supertabBaseUrl: string;\n merchantSystemUrn?: string;\n debug: boolean;\n recordEvent: RecordEventFn;\n};\n\nexport async function baseLicenseHandleRequest({\n licenseToken,\n url,\n userAgent,\n ctx,\n supertabBaseUrl,\n merchantSystemUrn,\n debug,\n recordEvent,\n}: BaseLicenseHandleRequestParams): Promise<Response> {\n const verification = await verifyLicenseToken({\n licenseToken,\n requestUrl: url,\n supertabBaseUrl,\n debug,\n });\n\n async function recordLicenseEvent(eventName: string) {\n const eventProperties = {\n page_url: url,\n user_agent: userAgent,\n verification_status: verification.valid ? \"valid\" : \"invalid\",\n verification_reason: verification.reason || \"success\",\n };\n\n const eventPromise = recordEvent(\n eventName,\n eventProperties,\n verification.licenseId\n );\n\n if (ctx?.waitUntil) {\n ctx.waitUntil(eventPromise);\n }\n\n return eventPromise;\n }\n\n if (!verification.valid) {\n await recordLicenseEvent(\n verification.reason || \"license_token_verification_failed\"\n );\n\n let rslError = \"invalid_request\";\n let errorDescription = \"Access to this resource requires a license\";\n\n switch (verification.reason) {\n case LicenseTokenInvalidReason.MISSING_TOKEN:\n rslError = \"invalid_request\";\n errorDescription = \"Access to this resource requires a license\";\n break;\n case LicenseTokenInvalidReason.EXPIRED:\n rslError = \"invalid_token\";\n errorDescription = \"The license token has expired\";\n break;\n case LicenseTokenInvalidReason.SIGNATURE_VERIFICATION_FAILED:\n rslError = \"invalid_token\";\n errorDescription = \"The license token signature is invalid\";\n break;\n case LicenseTokenInvalidReason.INVALID_HEADER:\n rslError = \"invalid_token\";\n errorDescription = \"The license token header is invalid\";\n break;\n case LicenseTokenInvalidReason.INVALID_PAYLOAD:\n rslError = \"invalid_token\";\n errorDescription = \"The license token payload is invalid\";\n break;\n case LicenseTokenInvalidReason.INVALID_ISSUER:\n rslError = \"invalid_token\";\n errorDescription = \"The license token issuer is invalid\";\n break;\n case LicenseTokenInvalidReason.INVALID_AUDIENCE:\n rslError = \"invalid_token\";\n errorDescription = \"The license token audience is invalid\";\n break;\n default:\n rslError = \"invalid_request\";\n errorDescription = \"Access to this resource requires a license\";\n }\n\n const licenseLink = generateLicenseLink({\n requestUrl: url,\n });\n const errorUri = `${supertabBaseUrl}/docs/errors#${rslError}`;\n\n const headers = new Headers({\n \"Content-Type\": \"text/plain; charset=UTF-8\",\n \"WWW-Authenticate\": `License error=\"${rslError}\", error_description=\"${errorDescription}\", error_uri=\"${errorUri}\"`,\n Link: `${licenseLink}; rel=\"license\"; type=\"application/rsl+xml\"`,\n });\n\n const responseBody = `Access to this resource requires a valid license token. Error: ${rslError} - ${errorDescription}`;\n\n return new Response(responseBody, {\n status: 401,\n headers,\n });\n }\n\n await recordLicenseEvent(\"license_used\");\n return new Response(\"✅ License Token Access granted\", {\n status: 200,\n headers: new Headers({ \"Content-Type\": \"application/json\" }),\n });\n}\n\nfunction buildFetchOptions(): FetchOptions {\n let options: FetchOptions = { method: \"GET\" };\n // @ts-ignore - backend is a Fastly-specific extension\n if (globalThis?.fastly) {\n options = { ...options, backend: FASTLY_BACKEND };\n }\n return options;\n}\n\nexport async function hostRSLicenseXML(\n supertabBaseUrl: string,\n merchantSystemUrn: string\n): Promise<Response> {\n const licenseUrl = `${supertabBaseUrl}/merchants/systems/${merchantSystemUrn}/license.xml`;\n const response = await fetch(licenseUrl, buildFetchOptions());\n\n if (!response.ok) {\n return new Response(\"License not found\", { status: 404 });\n }\n\n const licenseXml = await response.text();\n\n return new Response(licenseXml, {\n status: 200,\n headers: new Headers({ \"Content-Type\": \"application/xml\" }),\n });\n}\n","import { FASTLY_BACKEND, FetchOptions } from \"./types\";\n\nconst jwksCache = new Map<string, any>();\n\ntype JwksCacheKey = string;\n\ntype FetchJwksParams = {\n cacheKey: JwksCacheKey;\n url: string;\n debug: boolean;\n failureMessage: string;\n logLabel: string;\n};\n\nfunction buildFetchOptions(): FetchOptions {\n let options: FetchOptions = { method: \"GET\" };\n // @ts-ignore - backend is a Fastly-specific extension\n if (globalThis?.fastly) {\n options = { ...options, backend: FASTLY_BACKEND };\n }\n return options;\n}\n\nasync function fetchAndCacheJwks({\n cacheKey,\n url,\n debug,\n failureMessage,\n logLabel,\n}: FetchJwksParams): Promise<any> {\n if (!jwksCache.has(cacheKey)) {\n try {\n const response = await fetch(url, buildFetchOptions());\n\n if (!response.ok) {\n throw new Error(`${failureMessage}: ${response.status}`);\n }\n\n const jwksData = await response.json();\n jwksCache.set(cacheKey, jwksData);\n } catch (error) {\n if (debug) {\n console.error(logLabel, error);\n }\n throw error;\n }\n }\n\n return jwksCache.get(cacheKey);\n}\n\nexport async function fetchPlatformJwks(\n baseUrl: string,\n debug: boolean\n): Promise<any> {\n const jwksUrl = `${baseUrl}/.well-known/jwks.json/platform`;\n console.log(\"Fetching platform JWKS from:\", jwksUrl);\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"],"mappings":"yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,qBAAAE,IAAA,eAAAC,EAAAH,GC0CO,IAAMI,EAAiB,cC1C9B,IAAAC,EAAqC,gBAuBrC,eAAeC,EACXC,EACAC,EACAC,EACF,CACA,GAAI,CACF,IAAMC,EAAW,MAAM,MAAMH,EAAeC,CAAc,EAE1D,GAAI,CAACE,EAAS,GAAI,CAChB,IAAMC,EAAY,MAAMD,EAAS,KAAK,EAAE,MAAM,IAAM,EAAE,EAChDE,EAAe,mCACnBF,EAAS,MACX,IAAIA,EAAS,UAAU,GAAGC,EAAY,MAAMA,CAAS,GAAK,EAAE,GAC5D,MAAM,IAAI,MAAMC,CAAY,CAC9B,CAEA,IAAIC,EACJ,GAAI,CACFA,EAAO,MAAMH,EAAS,KAAK,CAC7B,OAASI,EAAY,CACnB,MAAIL,GACF,QAAQ,MACN,kDACAK,CACF,EAEI,IAAI,MAAM,gDAAgD,CAClE,CAEA,GAAI,CAACD,GAAM,aACT,MAAM,IA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AgB,QAAU,aAChD,OAAO+C,EAAyB,CAC9B,SAAAL,EACA,aAAAC,EACA,cAAAG,EACA,YAAAF,EACA,WAAAC,EACA,MAAA9C,CACF,CAAC,CACH,CACF,EA5SaC,EAEI,QAAkB,kCAFtBA,EAKI,UAAoC,KAL9C,IAAMgD,EAANhD","names":["index_exports","__export","SupertabConnect","__toCommonJS","FASTLY_BACKEND","import_jose","retrieveLicenseToken","tokenEndpoint","requestOptions","debug","response","errorBody","errorMessage","data","parseError","error","obtainLicenseToken","clientId","clientSecret","tokenEndpoint","resourceUrl","licenseXml","debug","payload","requestOptions","retrieveLicenseToken","import_jose","jwksCache","buildFetchOptions","options","FASTLY_BACKEND","fetchAndCacheJwks","cacheKey","url","debug","failureMessage","logLabel","response","jwksData","error","fetchPlatformJwks","baseUrl","jwksUrl","stripTrailingSlash","value","verifyLicenseToken","licenseToken","requestUrl","supertabBaseUrl","debug","header","error","payload","licenseId","issuer","audienceValues","entry","requestUrlNormalized","normalizedAudience","jwks","fetchPlatformJwks","result","jwtHeader","jwk","key","generateLicenseLink","baseURL","baseLicenseHandleRequest","url","userAgent","ctx","merchantSystemUrn","recordEvent","verification","recordLicenseEvent","eventName","eventProperties","eventPromise","rslError","errorDescription","licenseLink","errorUri","headers","responseBody","buildFetchOptions","options","FASTLY_BACKEND","hostRSLicenseXML","licenseUrl","response","licenseXml","debug","_SupertabConnect","config","reset","url","licenseToken","requestUrl","verifyLicenseToken","eventName","properties","licenseId","payload","options","FASTLY_BACKEND","response","error","request","userAgent","accept","secChUa","acceptLanguage","botScore","botList","lowerCaseUserAgent","botUaMatch","bot","headlessIndicators","only_sec_ch_ua_missing","missingHeaders","lowBotScore","env","ctx","MERCHANT_SYSTEM_URN","MERCHANT_API_KEY","merchantSystemUrn","merchantApiKey","enableRSL","supertabConnect","hostRSLicenseXML","botDetectionHandler","auth","user_agent","baseLicenseHandleRequest","clientId","clientSecret","resourceUrl","licenseXml","tokenEndpoint","obtainLicenseToken","SupertabConnect"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/types.ts","../src/jose.ts","../src/customer.ts","../src/jwks.ts","../src/license.ts","../src/cdn.ts","../src/bots.ts"],"sourcesContent":["import {\n SupertabConnectConfig,\n EnforcementMode,\n BotDetector,\n HandlerAction,\n HandlerResult,\n EventPayload,\n FASTLY_BACKEND,\n LicenseTokenInvalidReason,\n LicenseTokenVerificationResult,\n Env,\n} from \"./types\";\nimport { obtainLicenseToken as obtainLicenseTokenHelper } from \"./customer\";\nimport {\n buildBlockResult,\n buildSignalResult,\n verifyLicenseToken as verifyLicenseTokenHelper,\n validateTokenAndBuildResult,\n} from \"./license\";\nimport { handleCloudflareRequest, handleFastlyRequest } from \"./cdn\";\n\nexport { EnforcementMode, HandlerAction };\nexport type { Env, BotDetector, HandlerResult };\nexport { defaultBotDetector } from \"./bots\";\n\n/**\n * SupertabConnect class provides higher level methods\n * for using Supertab Connect within supported CDN integrations\n * as well as more specialized methods to customarily verify JWT tokens and record events.\n */\nexport class SupertabConnect {\n private apiKey?: string;\n private static baseUrl: string = \"https://api-connect.supertab.co\";\n private merchantSystemUrn!: string;\n private enforcement!: EnforcementMode;\n private botDetector?: BotDetector;\n private debug!: boolean;\n\n private static _instance: SupertabConnect | null = null;\n\n public constructor(config: SupertabConnectConfig, reset: boolean = false) {\n if (!reset && SupertabConnect._instance) {\n // If reset was not requested and an instance conflicts with the provided config, throw an error\n if (\n !(\n config.apiKey === SupertabConnect._instance.apiKey &&\n config.merchantSystemUrn ===\n SupertabConnect._instance.merchantSystemUrn\n )\n ) {\n throw new Error(\n \"Cannot create a new instance with different configuration. Use resetInstance to clear the existing instance.\"\n );\n }\n\n // If an instance already exists and reset is not requested, just return the existing instance\n return SupertabConnect._instance;\n }\n if (reset && SupertabConnect._instance) {\n // ...and if reset is requested and required, clear the existing instance first\n SupertabConnect.resetInstance();\n }\n\n if (!config.apiKey || !config.merchantSystemUrn) {\n throw new Error(\n \"Missing required configuration: apiKey and merchantSystemUrn are required\"\n );\n }\n this.apiKey = config.apiKey;\n this.merchantSystemUrn = config.merchantSystemUrn;\n this.enforcement = config.enforcement ?? EnforcementMode.SOFT;\n this.botDetector = config.botDetector;\n this.debug = config.debug ?? false;\n\n // Register this as the singleton instance\n SupertabConnect._instance = this;\n }\n\n 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 * Verify a license token\n * @param licenseToken The license token to verify\n * @param requestUrl The URL of the request being made\n * @returns A promise that resolves with the verification result\n */\n async verifyLicenseToken(\n licenseToken: string,\n requestUrl: string\n ): Promise<LicenseTokenVerificationResult> {\n return verifyLicenseTokenHelper({\n licenseToken,\n requestUrl,\n supertabBaseUrl: SupertabConnect.baseUrl,\n debug: this.debug,\n });\n }\n\n /**\n * Records an analytics event\n * @param eventName Name of the event to record\n * @param properties Additional properties to include with the event\n * @param licenseId Optional license ID associated with the event\n * @returns Promise that resolves when the event is recorded\n */\n async recordEvent(\n eventName: string,\n properties: Record<string, any> = {},\n licenseId?: string\n ): Promise<void> {\n const payload: EventPayload = {\n event_name: eventName,\n merchant_system_urn: this.merchantSystemUrn ? this.merchantSystemUrn : \"\",\n license_id: licenseId,\n properties,\n };\n\n try {\n let options: any = {\n method: \"POST\",\n headers: {\n Authorization: `Bearer ${this.apiKey}`,\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(payload),\n };\n // @ts-ignore\n if (globalThis?.fastly) {\n options = { ...options, backend: FASTLY_BACKEND };\n }\n const response = await fetch(\n `${SupertabConnect.baseUrl}/events`,\n options\n );\n\n if (!response.ok) {\n console.log(`Failed to record event: ${response.status}`);\n }\n } catch (error) {\n console.log(\"Error recording event:\", error);\n }\n }\n\n async handleRequest(request: Request, ctx?: any): 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 return validateTokenAndBuildResult({\n token,\n url,\n userAgent,\n supertabBaseUrl: SupertabConnect.baseUrl,\n debug: this.debug,\n recordEvent: this.recordEvent.bind(this),\n ctx,\n });\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 requestUrl: url,\n supertabBaseUrl: SupertabConnect.baseUrl,\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 * Automatically fetches and parses license.xml from the resource URL's origin,\n * using the token endpoint specified in the matching content element's server attribute.\n * @param clientId OAuth client identifier.\n * @param clientSecret OAuth client secret for client_credentials flow.\n * @param resourceUrl Resource URL attempting to access with a License.\n * @param debug Enable debug logging (default: false).\n * @returns Promise resolving to the issued license access token string.\n */\n static async obtainLicenseToken(\n clientId: string,\n clientSecret: string,\n resourceUrl: string,\n debug: boolean = false\n ): Promise<string> {\n return obtainLicenseTokenHelper({\n clientId,\n clientSecret,\n resourceUrl,\n debug,\n });\n }\n\n /**\n * Handle incoming requests for Cloudflare Workers.\n */\n static async cloudflareHandleRequests(\n request: Request,\n env: Env,\n ctx: any\n ): Promise<Response> {\n const instance = new SupertabConnect({\n apiKey: env.MERCHANT_API_KEY,\n merchantSystemUrn: env.MERCHANT_SYSTEM_URN,\n });\n return handleCloudflareRequest(instance, request, ctx);\n }\n\n /**\n * Handle incoming requests for Fastly Compute.\n */\n static async fastlyHandleRequests(\n request: Request,\n merchantSystemUrn: string,\n merchantApiKey: string,\n originBackend: string,\n options?: {\n enableRSL?: boolean;\n botDetector?: BotDetector;\n enforcement?: EnforcementMode;\n }\n ): Promise<Response> {\n const { enableRSL = false, botDetector, enforcement } = options ?? {};\n\n const instance = new SupertabConnect({\n apiKey: merchantApiKey,\n merchantSystemUrn: merchantSystemUrn,\n botDetector,\n enforcement,\n });\n\n return handleFastlyRequest(\n instance,\n request,\n originBackend,\n enableRSL\n ? {\n baseUrl: SupertabConnect.baseUrl,\n merchantSystemUrn,\n }\n : undefined\n );\n }\n}\n","export enum EnforcementMode {\n DISABLED = \"disabled\",\n SOFT = \"soft\",\n STRICT = \"strict\",\n}\n\nexport type BotDetector = (request: Request, ctx?: any) => boolean;\n\nexport interface SupertabConnectConfig {\n apiKey: string;\n merchantSystemUrn: string;\n enforcement?: EnforcementMode;\n botDetector?: BotDetector;\n debug?: boolean;\n}\n\n/**\n * Defines the shape for environment variables (used in CloudFlare integration).\n * These are used to identify and authenticate the Merchant System with the Supertab Connect API.\n */\nexport interface Env {\n\t/** The unique identifier for the merchant system. */\n\tMERCHANT_SYSTEM_URN: string;\n\t/** The API key for authenticating with the Supertab Connect. */\n\tMERCHANT_API_KEY: string;\n\t[key: string]: string;\n}\n\nexport interface EventPayload {\n event_name: string;\n license_id?: string;\n merchant_system_urn: string;\n properties: Record<string, any>;\n}\n\nexport type LicenseTokenVerificationResult =\n | { valid: true; licenseId?: string; payload: any }\n | { valid: false; reason: LicenseTokenInvalidReason; licenseId?: string };\n\nexport enum LicenseTokenInvalidReason {\n MISSING_TOKEN = \"missing_license_token\",\n INVALID_HEADER = \"invalid_license_header\",\n INVALID_ALG = \"invalid_license_algorithm\",\n INVALID_PAYLOAD = \"invalid_license_payload\",\n INVALID_ISSUER = \"invalid_license_issuer\",\n SIGNATURE_VERIFICATION_FAILED = \"license_signature_verification_failed\",\n EXPIRED = \"license_token_expired\",\n INVALID_AUDIENCE = \"invalid_license_audience\",\n SERVER_ERROR = \"server_error\",\n}\n\nexport const FASTLY_BACKEND = \"stc-backend\";\n\nexport interface FetchOptions extends RequestInit {\n // Fastly-specific extension for backend routing\n backend?: string;\n}\n\nexport enum HandlerAction {\n ALLOW = \"allow\",\n BLOCK = \"block\",\n}\n\nexport type HandlerResult =\n | { action: HandlerAction.ALLOW; headers?: Record<string, string> }\n | { action: HandlerAction.BLOCK; status: number; body: string; headers: Record<string, string> };","type JoseModule = typeof import(\"jose\");\n\nlet joseModulePromise: Promise<JoseModule> | null = null;\n\n/**\n * Lazily load the ESM-only `jose` package so the CommonJS build can call it via dynamic import.\n */\nexport function loadJose(): Promise<JoseModule> {\n if (!joseModulePromise) {\n joseModulePromise = import(\"jose\");\n }\n return joseModulePromise;\n}\n","import { loadJose } from \"./jose\";\n\ntype SupportedAlg = \"RS256\" | \"ES256\";\n\ntype GenerateLicenseTokenParams = {\n clientId: string;\n kid: string;\n privateKeyPem: string;\n tokenEndpoint: string;\n resourceUrl: string;\n licenseXml: string;\n debug?: boolean;\n};\n\ntype ObtainLicenseTokenParams = {\n clientId: string;\n clientSecret: string;\n resourceUrl: string;\n debug?: boolean;\n};\n\ntype ContentBlock = {\n urlPattern: string;\n licenseXml: string;\n server: string;\n};\n\nasync function retrieveLicenseToken(\n tokenEndpoint: string,\n requestOptions: RequestInit,\n debug: boolean | undefined\n) {\n try {\n const response = await fetch(tokenEndpoint, requestOptions);\n\n if (!response.ok) {\n const errorBody = await response.text().catch(() => \"\");\n const errorMessage = `Failed to obtain license token: ${\n response.status\n } ${response.statusText}${errorBody ? ` - ${errorBody}` : \"\"}`;\n throw new Error(errorMessage);\n }\n\n let data: any;\n try {\n data = await response.json();\n } catch (parseError) {\n if (debug) {\n console.error(\n \"Failed to parse license token response as JSON:\",\n parseError\n );\n }\n throw new Error(\"Failed to parse license token response as JSON\");\n }\n\n if (!data?.access_token) {\n throw new Error(\"License token response missing access_token\");\n }\n\n return data.access_token;\n } catch (error) {\n if (debug) {\n console.error(\"Error generating license token:\", error);\n }\n throw error;\n }\n}\n\nasync function importKeyForAlgs(\n privateKeyPem: string,\n debug: boolean | undefined\n): Promise<{ key: CryptoKey; alg: SupportedAlg }> {\n const { importPKCS8 } = await loadJose();\n const supportedAlgs: SupportedAlg[] = [\"ES256\", \"RS256\"];\n\n for (const algorithm of supportedAlgs) {\n try {\n const key = await importPKCS8(privateKeyPem, algorithm);\n return { key, alg: algorithm };\n } catch (importError) {\n if (debug) {\n console.debug(\n `Private key did not import using ${algorithm}, retrying...`,\n importError\n );\n }\n }\n }\n\n throw new Error(\n \"Unsupported private key format. Expected RSA or P-256 EC private key.\"\n );\n}\n\n// Temporarily not exporting this function to reflect only client credentials flow being supported\nasync function generateLicenseToken({\n clientId,\n kid,\n privateKeyPem,\n tokenEndpoint,\n resourceUrl,\n licenseXml,\n debug,\n}: GenerateLicenseTokenParams): Promise<string> {\n const { SignJWT } = await loadJose();\n const { key, alg } = await importKeyForAlgs(privateKeyPem, debug);\n const now = Math.floor(Date.now() / 1000);\n\n const clientAssertion = await new SignJWT({})\n .setProtectedHeader({ alg, kid })\n .setIssuer(clientId)\n .setSubject(clientId)\n .setIssuedAt(now)\n .setExpirationTime(now + 300)\n .setAudience(tokenEndpoint)\n .sign(key);\n\n const payload = new URLSearchParams({\n grant_type: \"rsl\",\n client_assertion_type:\n \"urn:ietf:params:oauth:client-assertion-type:jwt-bearer\",\n client_assertion: clientAssertion,\n license: licenseXml,\n resource: resourceUrl,\n });\n\n const requestOptions: RequestInit = {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/x-www-form-urlencoded\",\n Accept: \"application/json\",\n },\n body: payload.toString(),\n };\n\n return retrieveLicenseToken(tokenEndpoint, requestOptions, debug);\n}\n\nasync function fetchLicenseXml(\n resourceUrl: string,\n debug: boolean | undefined\n): Promise<string> {\n const origin = new URL(resourceUrl).origin;\n const licenseXmlUrl = `${origin}/license.xml`;\n\n const response = await fetch(licenseXmlUrl);\n if (!response.ok) {\n if (debug) {\n console.error(`Failed to fetch license.xml from ${licenseXmlUrl}: ${response.status}`);\n }\n throw new Error(\n `Failed to fetch license.xml from ${licenseXmlUrl}: ${response.status}`\n );\n }\n\n const xml = await response.text();\n if (debug) {\n console.debug(\"Fetched license.xml from\", licenseXmlUrl);\n }\n return xml;\n}\n\nfunction parseContentElements(xml: string, debug?: boolean): ContentBlock[] {\n const contentBlocks: ContentBlock[] = [];\n const contentRegex = /<content\\s([^>]*)>([\\s\\S]*?)<\\/content>/gi;\n const urlRegex = /url\\s*=\\s*\"([^\"]*)\"/i;\n const serverRegex = /server\\s*=\\s*\"([^\"]*)\"/i;\n const licenseRegex = /<license[^>]*>[\\s\\S]*?<\\/license>/i;\n\n let elementCount = 0;\n let match;\n while ((match = contentRegex.exec(xml)) !== null) {\n elementCount++;\n const attrs = match[1];\n const body = match[2];\n const urlMatch = attrs.match(urlRegex);\n const serverMatch = attrs.match(serverRegex);\n const licenseMatch = body.match(licenseRegex);\n\n if (urlMatch && serverMatch && licenseMatch) {\n contentBlocks.push({\n urlPattern: urlMatch[1],\n server: serverMatch[1],\n licenseXml: licenseMatch[0],\n });\n } else if (debug) {\n const missing = [\n !urlMatch && \"url\",\n !serverMatch && \"server\",\n !licenseMatch && \"<license>\",\n ].filter(Boolean).join(\", \");\n console.debug(`Skipping <content> element #${elementCount}: missing ${missing}`);\n }\n }\n\n if (debug) {\n console.debug(`Found ${elementCount} <content> element(s), ${contentBlocks.length} valid`);\n }\n\n return contentBlocks;\n}\n\nfunction findBestMatchingContent(\n contentBlocks: ContentBlock[],\n resourceUrl: string,\n debug?: boolean\n): ContentBlock | null {\n const parsed = new URL(resourceUrl);\n const host = parsed.host;\n const path = parsed.pathname;\n\n if (debug) {\n console.debug(`Matching resource URL: ${resourceUrl} (host=${host}, path=${path})`);\n }\n\n let bestMatch: ContentBlock | null = null;\n let bestSpecificity = -1;\n\n for (const block of contentBlocks) {\n let patternUrl: URL;\n try {\n patternUrl = new URL(block.urlPattern);\n } catch {\n if (debug) {\n console.debug(`Skipping block with invalid URL pattern: ${block.urlPattern}`);\n }\n continue;\n }\n\n if (patternUrl.host !== host) {\n if (debug) {\n console.debug(`Skipping block: host mismatch (pattern=${patternUrl.host}, resource=${host})`);\n }\n continue;\n }\n\n const patternPath = patternUrl.pathname;\n\n if (patternPath === path) {\n if (debug) {\n console.debug(`Exact match found: ${block.urlPattern}`);\n }\n return block;\n }\n\n if (patternPath.endsWith(\"/*\")) {\n const prefix = patternPath.slice(0, -1); // remove trailing *\n if (path.startsWith(prefix)) {\n const specificity = prefix.length;\n if (specificity > bestSpecificity) {\n bestSpecificity = specificity;\n bestMatch = block;\n }\n }\n }\n }\n\n if (debug) {\n if (bestMatch) {\n console.debug(`Wildcard match found: ${bestMatch.urlPattern} (specificity=${bestSpecificity})`);\n } else {\n console.debug(`No matching content block found for ${resourceUrl}`);\n }\n }\n\n return bestMatch;\n}\n\nexport { parseContentElements, findBestMatchingContent };\nexport type { ContentBlock };\n\nexport async function obtainLicenseToken({\n clientId,\n clientSecret,\n resourceUrl,\n debug,\n}: ObtainLicenseTokenParams): Promise<string> {\n const xml = await fetchLicenseXml(resourceUrl, debug);\n if (debug) {\n console.debug(`Fetched license.xml (${xml.length} chars)`);\n }\n const contentBlocks = parseContentElements(xml, debug);\n\n if (contentBlocks.length === 0) {\n if (debug) {\n console.error(\"No valid <content> elements with <license> found in license.xml\");\n }\n throw new Error(\n \"No valid <content> elements with <license> found in license.xml\"\n );\n }\n\n const matchedContent = findBestMatchingContent(contentBlocks, resourceUrl, debug);\n if (!matchedContent) {\n if (debug) {\n const patterns = contentBlocks.map(b => b.urlPattern).join(\", \");\n console.error(`No <content> element matches resource URL: ${resourceUrl}. Available patterns: ${patterns}`);\n }\n throw new Error(\n `No <content> element in license.xml matches resource URL: ${resourceUrl}`\n );\n }\n\n if (debug) {\n console.debug(\"Matched content block for resource URL:\", resourceUrl);\n console.debug(\"Using license XML:\", matchedContent.licenseXml);\n }\n\n const tokenEndpoint = matchedContent.server + '/token';\n if (debug) {\n console.debug(`Requesting license token from ${tokenEndpoint}`);\n }\n\n const payload = new URLSearchParams({\n grant_type: \"client_credentials\",\n license: matchedContent.licenseXml,\n resource: matchedContent.urlPattern,\n });\n\n const requestOptions: RequestInit = {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/x-www-form-urlencoded\",\n Accept: \"application/json\",\n Authorization: \"Basic \" + btoa(`${clientId}:${clientSecret}`),\n },\n body: payload.toString(),\n };\n\n return retrieveLicenseToken(tokenEndpoint, requestOptions, debug);\n}\n\nexport type { ObtainLicenseTokenParams };\n","import { FASTLY_BACKEND, FetchOptions } from \"./types\";\n\nconst jwksCache = new Map<string, any>();\n\ntype JwksCacheKey = string;\n\ntype FetchJwksParams = {\n cacheKey: JwksCacheKey;\n url: string;\n debug: boolean;\n failureMessage: string;\n logLabel: string;\n};\n\nfunction buildFetchOptions(): FetchOptions {\n let options: FetchOptions = { method: \"GET\" };\n // @ts-ignore - backend is a Fastly-specific extension\n if (globalThis?.fastly) {\n options = { ...options, backend: FASTLY_BACKEND };\n }\n return options;\n}\n\nasync function fetchAndCacheJwks({\n cacheKey,\n url,\n debug,\n failureMessage,\n logLabel,\n}: FetchJwksParams): Promise<any> {\n if (!jwksCache.has(cacheKey)) {\n try {\n const response = await fetch(url, buildFetchOptions());\n\n if (!response.ok) {\n throw new Error(`${failureMessage}: ${response.status}`);\n }\n\n const jwksData = await response.json();\n jwksCache.set(cacheKey, jwksData);\n } catch (error) {\n if (debug) {\n console.error(logLabel, error);\n }\n throw error;\n }\n }\n\n return jwksCache.get(cacheKey);\n}\n\nexport async function fetchPlatformJwks(\n baseUrl: string,\n debug: boolean\n): Promise<any> {\n const jwksUrl = `${baseUrl}/.well-known/jwks.json/platform`;\n if (debug) {\n console.debug(`Fetching platform JWKS from URL: ${jwksUrl}`);\n }\n\n return fetchAndCacheJwks({\n cacheKey: \"platform_jwks\",\n url: jwksUrl,\n debug,\n failureMessage: \"Failed to fetch platform JWKS\",\n logLabel: \"Error fetching platform JWKS:\",\n });\n}\n\nexport function clearJwksCache(): void {\n jwksCache.clear();\n}\n","import type { JWTPayload, JWTHeaderParameters } from \"jose\";\nimport { loadJose } from \"./jose\";\n\ninterface LicenseJWTPayload extends JWTPayload {\n license_id?: string;\n}\nimport {\n HandlerAction,\n HandlerResult,\n LicenseTokenInvalidReason,\n LicenseTokenVerificationResult,\n FASTLY_BACKEND,\n FetchOptions,\n} from \"./types\";\nimport { fetchPlatformJwks } from \"./jwks\";\n\nexport type EventRecorder = (\n eventName: string,\n properties: Record<string, any>,\n licenseId?: string\n) => Promise<void>;\n\nconst stripTrailingSlash = (value: string) => value.trim().replace(/\\/+$/, \"\");\n\nexport type VerifyLicenseTokenParams = {\n licenseToken: string;\n requestUrl: string;\n supertabBaseUrl: string;\n debug: boolean;\n};\n\nexport async function verifyLicenseToken({\n licenseToken,\n requestUrl,\n supertabBaseUrl,\n debug,\n}: VerifyLicenseTokenParams): Promise<LicenseTokenVerificationResult> {\n const { decodeProtectedHeader, decodeJwt, jwtVerify } = await loadJose();\n\n if (!licenseToken) {\n return {\n valid: false,\n reason: LicenseTokenInvalidReason.MISSING_TOKEN,\n };\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 };\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 };\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 };\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 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 licenseId,\n };\n }\n\n let jwks;\n try {\n jwks = await fetchPlatformJwks(supertabBaseUrl, debug);\n } catch (error) {\n if (debug) {\n console.error(\"Failed to fetch platform JWKS:\", error);\n }\n return {\n valid: false,\n reason: LicenseTokenInvalidReason.SERVER_ERROR,\n licenseId,\n };\n }\n\n try {\n const getKey = async (jwtHeader: JWTHeaderParameters) => {\n const jwk = jwks.keys.find((key: any) => key.kid === jwtHeader.kid);\n if (!jwk) {\n throw new Error(`No matching platform key found: ${jwtHeader.kid}`);\n }\n return jwk;\n };\n\n const result = await jwtVerify(licenseToken, getKey, {\n issuer,\n algorithms: [header.alg],\n clockTolerance: \"1m\",\n });\n\n return {\n valid: true,\n licenseId,\n payload: result.payload,\n };\n } catch (error) {\n if (debug) {\n console.error(\"License JWT verification failed:\", error);\n }\n\n if (error instanceof Error && error.message?.includes(\"exp\")) {\n return {\n valid: false,\n reason: LicenseTokenInvalidReason.EXPIRED,\n licenseId,\n };\n }\n\n return {\n valid: false,\n reason: LicenseTokenInvalidReason.SIGNATURE_VERIFICATION_FAILED,\n licenseId,\n };\n }\n}\n\nexport function generateLicenseLink({\n requestUrl,\n}: {\n requestUrl: string;\n}): string {\n const baseURL = new URL(requestUrl);\n return `${baseURL.protocol}//${baseURL.host}/license.xml`;\n}\n\n/**\n * Build a HandlerResult that signals a missing token in soft enforcement mode.\n * Returns headers indicating a license is required without blocking the request.\n */\nexport function buildSignalResult(requestUrl: string): HandlerResult {\n const licenseLink = generateLicenseLink({ requestUrl });\n return {\n action: HandlerAction.ALLOW,\n headers: {\n Link: `<${licenseLink}>; rel=\"license\"; type=\"application/rsl+xml\"`,\n \"X-RSL-Status\": \"token_required\",\n \"X-RSL-Reason\": \"missing\",\n },\n };\n}\nexport function buildBlockResult({\n reason,\n requestUrl,\n supertabBaseUrl,\n}: {\n reason: LicenseTokenInvalidReason | string;\n requestUrl: string;\n supertabBaseUrl: string;\n}): HandlerResult {\n let rslError: string;\n let errorDescription: string;\n let status: number;\n\n switch (reason) {\n // 401 — invalid_request: missing or malformed request\n case LicenseTokenInvalidReason.MISSING_TOKEN:\n status = 401;\n rslError = \"invalid_request\";\n errorDescription = \"Authorization header missing or malformed\";\n break;\n case LicenseTokenInvalidReason.INVALID_ALG:\n status = 401;\n rslError = \"invalid_request\";\n errorDescription = \"Unsupported token algorithm\";\n break;\n\n // 401 — invalid_token: token exists but is bad\n case LicenseTokenInvalidReason.EXPIRED:\n status = 401;\n rslError = \"invalid_token\";\n errorDescription = \"The license token has expired\";\n break;\n case LicenseTokenInvalidReason.SIGNATURE_VERIFICATION_FAILED:\n status = 401;\n rslError = \"invalid_token\";\n errorDescription = \"The license token signature is invalid\";\n break;\n case LicenseTokenInvalidReason.INVALID_HEADER:\n status = 401;\n rslError = \"invalid_token\";\n errorDescription = \"The license token header is malformed\";\n break;\n case LicenseTokenInvalidReason.INVALID_PAYLOAD:\n status = 401;\n rslError = \"invalid_token\";\n errorDescription = \"The license token payload is malformed\";\n break;\n case LicenseTokenInvalidReason.INVALID_ISSUER:\n status = 401;\n rslError = \"invalid_token\";\n errorDescription = \"The license token issuer is not recognized\";\n break;\n // 403 — insufficient_scope: valid token, wrong resource/usage\n case LicenseTokenInvalidReason.INVALID_AUDIENCE:\n status = 403;\n rslError = \"insufficient_scope\";\n errorDescription = \"The license does not grant access to this resource\";\n break;\n // 503 — server-side validation failure\n case LicenseTokenInvalidReason.SERVER_ERROR:\n status = 503;\n rslError = \"server_error\";\n errorDescription = \"The server encountered an error validating the license\";\n break;\n\n default:\n status = 401;\n rslError = \"invalid_token\";\n errorDescription = \"License token missing, expired, revoked, or malformed\";\n }\n\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} - ${errorDescription}`,\n headers: {\n \"Content-Type\": \"text/plain; charset=UTF-8\",\n \"WWW-Authenticate\": `License error=\"${rslError}\", error_description=\"${errorDescription}\"`,\n Link: `<${licenseLink}>; rel=\"license\"; type=\"application/rsl+xml\"`,\n },\n };\n}\n\nfunction buildFetchOptions(): FetchOptions {\n let options: FetchOptions = { method: \"GET\" };\n // @ts-ignore - backend is a Fastly-specific extension\n if (globalThis?.fastly) {\n options = { ...options, backend: FASTLY_BACKEND };\n }\n return options;\n}\n\nexport async function hostRSLicenseXML(\n supertabBaseUrl: string,\n merchantSystemUrn: string\n): Promise<Response> {\n const licenseUrl = `${supertabBaseUrl}/merchants/systems/${merchantSystemUrn}/license.xml`;\n const response = await fetch(licenseUrl, buildFetchOptions());\n\n if (!response.ok) {\n return new Response(\"License not found\", { status: 404 });\n }\n\n const licenseXml = await response.text();\n\n return new Response(licenseXml, {\n status: 200,\n headers: new Headers({ \"Content-Type\": \"application/xml\" }),\n });\n}\n\nexport type ValidateTokenParams = {\n token: string;\n url: string;\n userAgent: string;\n supertabBaseUrl: string;\n debug: boolean;\n recordEvent?: EventRecorder;\n ctx?: any;\n};\n\nexport async function validateTokenAndBuildResult(\n params: ValidateTokenParams\n): Promise<HandlerResult> {\n const verification = await verifyLicenseToken({\n licenseToken: params.token,\n requestUrl: params.url,\n supertabBaseUrl: params.supertabBaseUrl,\n debug: params.debug,\n });\n\n if (params.recordEvent) {\n const eventName = verification.valid\n ? \"license_used\"\n : verification.reason;\n\n const eventProperties = {\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\n const eventPromise = params.recordEvent(\n eventName,\n eventProperties,\n verification.licenseId\n );\n\n if (params.ctx?.waitUntil) {\n params.ctx.waitUntil(eventPromise);\n }\n }\n\n if (!verification.valid) {\n return buildBlockResult({\n reason: verification.reason,\n requestUrl: params.url,\n supertabBaseUrl: params.supertabBaseUrl,\n });\n }\n\n return { action: HandlerAction.ALLOW };\n}\n","import { HandlerAction, HandlerResult } 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?: any): Promise<HandlerResult>;\n}\n\nexport async function handleCloudflareRequest(\n handler: RequestHandler,\n request: Request,\n ctx: any\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","/**\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 userAgent.toLowerCase().includes(\"headless\") ||\n userAgent.toLowerCase().includes(\"puppeteer\") ||\n !secChUa;\n\n const isBrowserMissingSecChUa =\n !userAgent.toLowerCase().includes(\"headless\") &&\n !userAgent.toLowerCase().includes(\"puppeteer\") &&\n !secChUa;\n\n // 3. Suspicious header gaps — many bots omit these\n const missingHeaders = !accept || !acceptLanguage;\n\n // 4. Cloudflare bot score check (if available)\n const lowBotScore = typeof botScore === \"number\" && botScore < 30;\n\n // Safari and Mozilla special case\n if (\n lowerCaseUserAgent.includes(\"safari\") ||\n lowerCaseUserAgent.includes(\"mozilla\")\n ) {\n // Safari is not a bot, but it may be headless\n if (headlessIndicators && isBrowserMissingSecChUa) {\n return false; // Likely not a bot, but missing a Sec-CH-UA header\n }\n }\n\n // Final decision\n return botUaMatch || headlessIndicators || missingHeaders || lowBotScore;\n}\n"],"mappings":"0jBAAA,IAAAA,GAAA,GAAAC,EAAAD,GAAA,qBAAAE,EAAA,kBAAAC,EAAA,oBAAAC,EAAA,uBAAAC,IAAA,eAAAC,EAAAN,ICAO,IAAKO,OACVA,EAAA,SAAW,WACXA,EAAA,KAAO,OACPA,EAAA,OAAS,SAHCA,OAAA,IAmDL,IAAMC,EAAiB,cAOlBC,OACVA,EAAA,MAAQ,QACRA,EAAA,MAAQ,QAFEA,OAAA,ICxDZ,IAAIC,EAAgD,KAK7C,SAASC,GAAgC,CAC9C,OAAKD,IACHA,EAAoB,OAAO,MAAM,GAE5BA,CACT,CCeA,eAAeE,EACXC,EACAC,EACAC,EACF,CACA,GAAI,CACF,IAAMC,EAAW,MAAM,MAAMH,EAAeC,CAAc,EAE1D,GAAI,CAACE,EAAS,GAAI,CAChB,IAAMC,EAAY,MAAMD,EAAS,KAAK,EAAE,MAAM,IAAM,EAAE,EAChDE,EAAe,mCACnBF,EAAS,MACX,IAAIA,EAAS,UAAU,GAAGC,EAAY,MAAMA,CAAS,GAAK,EAAE,GAC5D,MAAM,IAAI,MAAMC,CAAY,CAC9B,CAEA,IAAIC,EACJ,GAAI,CACFA,EAAO,MAAMH,EAAS,KAAK,CAC7B,OAASI,EAAY,CACnB,MAAIL,GACF,QAAQ,MACN,kDACAK,CACF,EAEI,IAAI,MAAM,gDAAgD,CAClE,CAEA,GAAI,C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,QACjC,MAAO,KAAK,MACZ,YAAa,KAAK,YAAY,KAAK,IAAI,EACvC,IAAAgB,CACF,CAAC,EAMH,GAAI,EAFU,KAAK,cAAcD,EAASC,CAAG,GAAK,IAGhD,MAAO,CAAE,cAA4B,EAIvC,OAAQ,KAAK,YAAa,CACxB,aACE,OAAOK,EAAiB,CACtB,+BACA,WAAYlB,EACZ,gBAAiBH,EAAgB,OACnC,CAAC,EACH,WACE,OAAOsB,EAAkBnB,CAAG,EAC9B,QACE,MAAO,CAAE,cAA4B,CACzC,CACF,CAYA,aAAa,mBACXoB,EACAC,EACAC,EACAC,EAAiB,GACA,CACjB,OAAOC,EAAyB,CAC9B,SAAAJ,EACA,aAAAC,EACA,YAAAC,EACA,MAAAC,CACF,CAAC,CACH,CAKA,aAAa,yBACXX,EACAa,EACAZ,EACmB,CACnB,IAAMa,EAAW,IAAI7B,EAAgB,CACnC,OAAQ4B,EAAI,iBACZ,kBAAmBA,EAAI,mBACzB,CAAC,EACD,OAAOE,EAAwBD,EAAUd,EAASC,CAAG,CACvD,CAKA,aAAa,qBACXD,EACAgB,EACAC,EACAC,EACAtB,EAKmB,CACnB,GAAM,CAAE,UAAAuB,EAAY,GAAO,YAAAC,EAAa,YAAAC,CAAY,EAAIzB,GAAW,CAAC,EAE9DkB,EAAW,IAAI7B,EAAgB,CACnC,OAAQgC,EACR,kBAAmBD,EACnB,YAAAI,EACA,YAAAC,CACF,CAAC,EAED,OAAOC,EACLR,EACAd,EACAkB,EACAC,EACI,CACE,QAASlC,EAAgB,QACzB,kBAAA+B,CACF,EACA,MACN,CACF,CACF,EAvPa/B,EAEI,QAAkB,kCAFtBA,EAQI,UAAoC,KAR9C,IAAMsC,EAANtC","names":["index_exports","__export","EnforcementMode","HandlerAction","SupertabConnect","defaultBotDetector","__toCommonJS","EnforcementMode","FASTLY_BACKEND","HandlerAction","joseModulePromise","loadJose","retrieveLicenseToken","tokenEndpoint","requestOptions","debug","response","errorBody","errorMessage","data","parseError","error","fetchLicenseXml","resourceUrl","debug","licenseXmlUrl","response","xml","parseContentElements","contentBlocks","contentRegex","urlRegex","serverRegex","licenseRegex","elementCount","match","attrs","body","urlMatch","serverMatch","licenseMatch","missing","findBestMatchingContent","parsed","host","path","bestMatch","bestSpecificity","block","patternUrl","patternPath","prefix","specificity","obtainLicenseToken","clientId","clientSecret","resourceUrl","debug","xml","fetchLicenseXml","contentBlocks","parseContentElements","matchedContent","findBestMatchingContent","patterns","b","tokenEndpoint","payload","requestOptions","retrieveLicenseToken","jwksCache","buildFetchOptions","options","FASTLY_BACKEND","fetchAndCacheJwks","cacheKey","url","debug","failureMessage","logLabel","response","jwksData","error","fetchPlatformJwks","baseUrl","jwksUrl","stripTrailingSlash","value","verifyLicenseToken","licenseToken","requestUrl","supertabBaseUrl","debug","decodeProtectedHeader","decodeJwt","jwtVerify","loadJose","header","error","payload","licenseId","issuer","normalizedIssuer","normalizedBaseUrl","audienceValues","entry","requestUrlNormalized","normalizedAudience","jwks","fetchPlatformJwks","result","jwtHeader","jwk","key","generateLicenseLink","baseURL","buildSignalResult","licenseLink","buildBlockResult","reason","rslError","errorDescription","status","buildFetchOptions","options","FASTLY_BACKEND","hostRSLicenseXML","merchantSystemUrn","licenseUrl","response","licenseXml","validateTokenAndBuildResult","params","verification","eventName","eventProperties","eventPromise","handleCloudflareRequest","handler","request","ctx","result","originResponse","response","key","value","handleFastlyRequest","originBackend","rslOptions","hostRSLicenseXML","defaultBotDetector","request","userAgent","accept","secChUa","acceptLanguage","botScore","botList","lowerCaseUserAgent","botUaMatch","bot","headlessIndicators","isBrowserMissingSecChUa","missingHeaders","lowBotScore","_SupertabConnect","config","reset","url","licenseToken","requestUrl","verifyLicenseToken","eventName","properties","licenseId","payload","options","FASTLY_BACKEND","response","error","request","ctx","auth","token","userAgent","validateTokenAndBuildResult","buildBlockResult","buildSignalResult","clientId","clientSecret","resourceUrl","debug","obtainLicenseToken","env","instance","handleCloudflareRequest","merchantSystemUrn","merchantApiKey","originBackend","enableRSL","botDetector","enforcement","handleFastlyRequest","SupertabConnect"]}
|
package/dist/index.d.cts
CHANGED
|
@@ -1,6 +1,15 @@
|
|
|
1
|
+
declare enum EnforcementMode {
|
|
2
|
+
DISABLED = "disabled",
|
|
3
|
+
SOFT = "soft",
|
|
4
|
+
STRICT = "strict"
|
|
5
|
+
}
|
|
6
|
+
type BotDetector = (request: Request, ctx?: any) => boolean;
|
|
1
7
|
interface SupertabConnectConfig {
|
|
2
8
|
apiKey: string;
|
|
3
9
|
merchantSystemUrn: string;
|
|
10
|
+
enforcement?: EnforcementMode;
|
|
11
|
+
botDetector?: BotDetector;
|
|
12
|
+
debug?: boolean;
|
|
4
13
|
}
|
|
5
14
|
/**
|
|
6
15
|
* Defines the shape for environment variables (used in CloudFlare integration).
|
|
@@ -13,12 +22,47 @@ interface Env {
|
|
|
13
22
|
MERCHANT_API_KEY: string;
|
|
14
23
|
[key: string]: string;
|
|
15
24
|
}
|
|
16
|
-
|
|
17
|
-
valid:
|
|
18
|
-
|
|
25
|
+
type LicenseTokenVerificationResult = {
|
|
26
|
+
valid: true;
|
|
27
|
+
licenseId?: string;
|
|
28
|
+
payload: any;
|
|
29
|
+
} | {
|
|
30
|
+
valid: false;
|
|
31
|
+
reason: LicenseTokenInvalidReason;
|
|
19
32
|
licenseId?: string;
|
|
20
|
-
|
|
33
|
+
};
|
|
34
|
+
declare enum LicenseTokenInvalidReason {
|
|
35
|
+
MISSING_TOKEN = "missing_license_token",
|
|
36
|
+
INVALID_HEADER = "invalid_license_header",
|
|
37
|
+
INVALID_ALG = "invalid_license_algorithm",
|
|
38
|
+
INVALID_PAYLOAD = "invalid_license_payload",
|
|
39
|
+
INVALID_ISSUER = "invalid_license_issuer",
|
|
40
|
+
SIGNATURE_VERIFICATION_FAILED = "license_signature_verification_failed",
|
|
41
|
+
EXPIRED = "license_token_expired",
|
|
42
|
+
INVALID_AUDIENCE = "invalid_license_audience",
|
|
43
|
+
SERVER_ERROR = "server_error"
|
|
21
44
|
}
|
|
45
|
+
declare enum HandlerAction {
|
|
46
|
+
ALLOW = "allow",
|
|
47
|
+
BLOCK = "block"
|
|
48
|
+
}
|
|
49
|
+
type HandlerResult = {
|
|
50
|
+
action: HandlerAction.ALLOW;
|
|
51
|
+
headers?: Record<string, string>;
|
|
52
|
+
} | {
|
|
53
|
+
action: HandlerAction.BLOCK;
|
|
54
|
+
status: number;
|
|
55
|
+
body: string;
|
|
56
|
+
headers: Record<string, string>;
|
|
57
|
+
};
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* Default bot detection logic using multiple signals.
|
|
61
|
+
* Checks User-Agent patterns, headless browser indicators, missing headers, and Cloudflare bot scores.
|
|
62
|
+
* @param request The incoming request to analyze
|
|
63
|
+
* @returns true if the request appears to be from a bot, false otherwise
|
|
64
|
+
*/
|
|
65
|
+
declare function defaultBotDetector(request: Request): boolean;
|
|
22
66
|
|
|
23
67
|
/**
|
|
24
68
|
* SupertabConnect class provides higher level methods
|
|
@@ -29,6 +73,9 @@ declare class SupertabConnect {
|
|
|
29
73
|
private apiKey?;
|
|
30
74
|
private static baseUrl;
|
|
31
75
|
private merchantSystemUrn;
|
|
76
|
+
private enforcement;
|
|
77
|
+
private botDetector?;
|
|
78
|
+
private debug;
|
|
32
79
|
private static _instance;
|
|
33
80
|
constructor(config: SupertabConnectConfig, reset?: boolean);
|
|
34
81
|
static resetInstance(): void;
|
|
@@ -36,6 +83,10 @@ declare class SupertabConnect {
|
|
|
36
83
|
* Override the default base URL for API requests (intended for local development/testing).
|
|
37
84
|
*/
|
|
38
85
|
static setBaseUrl(url: string): void;
|
|
86
|
+
/**
|
|
87
|
+
* Get the current base URL for API requests.
|
|
88
|
+
*/
|
|
89
|
+
static getBaseUrl(): string;
|
|
39
90
|
/**
|
|
40
91
|
* Verify a license token
|
|
41
92
|
* @param licenseToken The license token to verify
|
|
@@ -51,19 +102,30 @@ declare class SupertabConnect {
|
|
|
51
102
|
* @returns Promise that resolves when the event is recorded
|
|
52
103
|
*/
|
|
53
104
|
recordEvent(eventName: string, properties?: Record<string, any>, licenseId?: string): Promise<void>;
|
|
54
|
-
|
|
55
|
-
static cloudflareHandleRequests(request: Request, env: Env, ctx: any): Promise<Response>;
|
|
56
|
-
static fastlyHandleRequests(request: Request, merchantSystemUrn: string, merchantApiKey: string, enableRSL?: boolean): Promise<Response>;
|
|
57
|
-
handleRequest(request: Request, botDetectionHandler?: (request: Request, ctx?: any) => boolean, ctx?: any): Promise<Response>;
|
|
105
|
+
handleRequest(request: Request, ctx?: any): Promise<HandlerResult>;
|
|
58
106
|
/**
|
|
59
107
|
* Request a license token from the Supertab Connect token endpoint.
|
|
108
|
+
* Automatically fetches and parses license.xml from the resource URL's origin,
|
|
109
|
+
* using the token endpoint specified in the matching content element's server attribute.
|
|
60
110
|
* @param clientId OAuth client identifier.
|
|
61
111
|
* @param clientSecret OAuth client secret for client_credentials flow.
|
|
62
112
|
* @param resourceUrl Resource URL attempting to access with a License.
|
|
63
|
-
* @param
|
|
113
|
+
* @param debug Enable debug logging (default: false).
|
|
64
114
|
* @returns Promise resolving to the issued license access token string.
|
|
65
115
|
*/
|
|
66
|
-
static obtainLicenseToken(clientId: string, clientSecret: string, resourceUrl: string,
|
|
116
|
+
static obtainLicenseToken(clientId: string, clientSecret: string, resourceUrl: string, debug?: boolean): Promise<string>;
|
|
117
|
+
/**
|
|
118
|
+
* Handle incoming requests for Cloudflare Workers.
|
|
119
|
+
*/
|
|
120
|
+
static cloudflareHandleRequests(request: Request, env: Env, ctx: any): Promise<Response>;
|
|
121
|
+
/**
|
|
122
|
+
* Handle incoming requests for Fastly Compute.
|
|
123
|
+
*/
|
|
124
|
+
static fastlyHandleRequests(request: Request, merchantSystemUrn: string, merchantApiKey: string, originBackend: string, options?: {
|
|
125
|
+
enableRSL?: boolean;
|
|
126
|
+
botDetector?: BotDetector;
|
|
127
|
+
enforcement?: EnforcementMode;
|
|
128
|
+
}): Promise<Response>;
|
|
67
129
|
}
|
|
68
130
|
|
|
69
|
-
export { type Env, SupertabConnect };
|
|
131
|
+
export { type BotDetector, EnforcementMode, type Env, HandlerAction, type HandlerResult, SupertabConnect, defaultBotDetector };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,6 +1,15 @@
|
|
|
1
|
+
declare enum EnforcementMode {
|
|
2
|
+
DISABLED = "disabled",
|
|
3
|
+
SOFT = "soft",
|
|
4
|
+
STRICT = "strict"
|
|
5
|
+
}
|
|
6
|
+
type BotDetector = (request: Request, ctx?: any) => boolean;
|
|
1
7
|
interface SupertabConnectConfig {
|
|
2
8
|
apiKey: string;
|
|
3
9
|
merchantSystemUrn: string;
|
|
10
|
+
enforcement?: EnforcementMode;
|
|
11
|
+
botDetector?: BotDetector;
|
|
12
|
+
debug?: boolean;
|
|
4
13
|
}
|
|
5
14
|
/**
|
|
6
15
|
* Defines the shape for environment variables (used in CloudFlare integration).
|
|
@@ -13,12 +22,47 @@ interface Env {
|
|
|
13
22
|
MERCHANT_API_KEY: string;
|
|
14
23
|
[key: string]: string;
|
|
15
24
|
}
|
|
16
|
-
|
|
17
|
-
valid:
|
|
18
|
-
|
|
25
|
+
type LicenseTokenVerificationResult = {
|
|
26
|
+
valid: true;
|
|
27
|
+
licenseId?: string;
|
|
28
|
+
payload: any;
|
|
29
|
+
} | {
|
|
30
|
+
valid: false;
|
|
31
|
+
reason: LicenseTokenInvalidReason;
|
|
19
32
|
licenseId?: string;
|
|
20
|
-
|
|
33
|
+
};
|
|
34
|
+
declare enum LicenseTokenInvalidReason {
|
|
35
|
+
MISSING_TOKEN = "missing_license_token",
|
|
36
|
+
INVALID_HEADER = "invalid_license_header",
|
|
37
|
+
INVALID_ALG = "invalid_license_algorithm",
|
|
38
|
+
INVALID_PAYLOAD = "invalid_license_payload",
|
|
39
|
+
INVALID_ISSUER = "invalid_license_issuer",
|
|
40
|
+
SIGNATURE_VERIFICATION_FAILED = "license_signature_verification_failed",
|
|
41
|
+
EXPIRED = "license_token_expired",
|
|
42
|
+
INVALID_AUDIENCE = "invalid_license_audience",
|
|
43
|
+
SERVER_ERROR = "server_error"
|
|
21
44
|
}
|
|
45
|
+
declare enum HandlerAction {
|
|
46
|
+
ALLOW = "allow",
|
|
47
|
+
BLOCK = "block"
|
|
48
|
+
}
|
|
49
|
+
type HandlerResult = {
|
|
50
|
+
action: HandlerAction.ALLOW;
|
|
51
|
+
headers?: Record<string, string>;
|
|
52
|
+
} | {
|
|
53
|
+
action: HandlerAction.BLOCK;
|
|
54
|
+
status: number;
|
|
55
|
+
body: string;
|
|
56
|
+
headers: Record<string, string>;
|
|
57
|
+
};
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* Default bot detection logic using multiple signals.
|
|
61
|
+
* Checks User-Agent patterns, headless browser indicators, missing headers, and Cloudflare bot scores.
|
|
62
|
+
* @param request The incoming request to analyze
|
|
63
|
+
* @returns true if the request appears to be from a bot, false otherwise
|
|
64
|
+
*/
|
|
65
|
+
declare function defaultBotDetector(request: Request): boolean;
|
|
22
66
|
|
|
23
67
|
/**
|
|
24
68
|
* SupertabConnect class provides higher level methods
|
|
@@ -29,6 +73,9 @@ declare class SupertabConnect {
|
|
|
29
73
|
private apiKey?;
|
|
30
74
|
private static baseUrl;
|
|
31
75
|
private merchantSystemUrn;
|
|
76
|
+
private enforcement;
|
|
77
|
+
private botDetector?;
|
|
78
|
+
private debug;
|
|
32
79
|
private static _instance;
|
|
33
80
|
constructor(config: SupertabConnectConfig, reset?: boolean);
|
|
34
81
|
static resetInstance(): void;
|
|
@@ -36,6 +83,10 @@ declare class SupertabConnect {
|
|
|
36
83
|
* Override the default base URL for API requests (intended for local development/testing).
|
|
37
84
|
*/
|
|
38
85
|
static setBaseUrl(url: string): void;
|
|
86
|
+
/**
|
|
87
|
+
* Get the current base URL for API requests.
|
|
88
|
+
*/
|
|
89
|
+
static getBaseUrl(): string;
|
|
39
90
|
/**
|
|
40
91
|
* Verify a license token
|
|
41
92
|
* @param licenseToken The license token to verify
|
|
@@ -51,19 +102,30 @@ declare class SupertabConnect {
|
|
|
51
102
|
* @returns Promise that resolves when the event is recorded
|
|
52
103
|
*/
|
|
53
104
|
recordEvent(eventName: string, properties?: Record<string, any>, licenseId?: string): Promise<void>;
|
|
54
|
-
|
|
55
|
-
static cloudflareHandleRequests(request: Request, env: Env, ctx: any): Promise<Response>;
|
|
56
|
-
static fastlyHandleRequests(request: Request, merchantSystemUrn: string, merchantApiKey: string, enableRSL?: boolean): Promise<Response>;
|
|
57
|
-
handleRequest(request: Request, botDetectionHandler?: (request: Request, ctx?: any) => boolean, ctx?: any): Promise<Response>;
|
|
105
|
+
handleRequest(request: Request, ctx?: any): Promise<HandlerResult>;
|
|
58
106
|
/**
|
|
59
107
|
* Request a license token from the Supertab Connect token endpoint.
|
|
108
|
+
* Automatically fetches and parses license.xml from the resource URL's origin,
|
|
109
|
+
* using the token endpoint specified in the matching content element's server attribute.
|
|
60
110
|
* @param clientId OAuth client identifier.
|
|
61
111
|
* @param clientSecret OAuth client secret for client_credentials flow.
|
|
62
112
|
* @param resourceUrl Resource URL attempting to access with a License.
|
|
63
|
-
* @param
|
|
113
|
+
* @param debug Enable debug logging (default: false).
|
|
64
114
|
* @returns Promise resolving to the issued license access token string.
|
|
65
115
|
*/
|
|
66
|
-
static obtainLicenseToken(clientId: string, clientSecret: string, resourceUrl: string,
|
|
116
|
+
static obtainLicenseToken(clientId: string, clientSecret: string, resourceUrl: string, debug?: boolean): Promise<string>;
|
|
117
|
+
/**
|
|
118
|
+
* Handle incoming requests for Cloudflare Workers.
|
|
119
|
+
*/
|
|
120
|
+
static cloudflareHandleRequests(request: Request, env: Env, ctx: any): Promise<Response>;
|
|
121
|
+
/**
|
|
122
|
+
* Handle incoming requests for Fastly Compute.
|
|
123
|
+
*/
|
|
124
|
+
static fastlyHandleRequests(request: Request, merchantSystemUrn: string, merchantApiKey: string, originBackend: string, options?: {
|
|
125
|
+
enableRSL?: boolean;
|
|
126
|
+
botDetector?: BotDetector;
|
|
127
|
+
enforcement?: EnforcementMode;
|
|
128
|
+
}): Promise<Response>;
|
|
67
129
|
}
|
|
68
130
|
|
|
69
|
-
export { type Env, SupertabConnect };
|
|
131
|
+
export { type BotDetector, EnforcementMode, type Env, HandlerAction, type HandlerResult, SupertabConnect, defaultBotDetector };
|
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var f="stc-backend";import{importPKCS8 as K,SignJWT as O}from"jose";async function R(i,e,t){try{let n=await fetch(i,e);if(!n.ok){let s=await n.text().catch(()=>""),o=`Failed to obtain license token: ${n.status} ${n.statusText}${s?` - ${s}`:""}`;throw new Error(o)}let r;try{r=await n.json()}catch(s){throw t&&console.error("Failed to parse license token response as JSON:",s),new Error("Failed to parse license token response as JSON")}if(!r?.access_token)throw new Error("License token response missing access_token");return r.access_token}catch(n){throw t&&console.error("Error generating license token:",n),n}}async function b({clientId:i,clientSecret:e,tokenEndpoint:t,resourceUrl:n,licenseXml:r,debug:s}){let o=new URLSearchParams({grant_type:"client_credentials",license:r,resource:n}),p={method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json",Authorization:"Basic "+btoa(`${i}:${e}`)},body:o.toString()};return R(t,p,s)}import{decodeProtectedHeader as P,decodeJwt as N,jwtVerify as C}from"jose";var k=new Map;function S(){let i={method:"GET"};return globalThis?.fastly&&(i={...i,backend:f}),i}async function U({cacheKey:i,url:e,debug:t,failureMessage:n,logLabel:r}){if(!k.has(i))try{let s=await fetch(e,S());if(!s.ok)throw new Error(`${n}: ${s.status}`);let o=await s.json();k.set(i,o)}catch(s){throw t&&console.error(r,s),s}return k.get(i)}async function _(i,e){let t=`${i}/.well-known/jwks.json/platform`;return console.log("Fetching platform JWKS from:",t),U({cacheKey:"platform_jwks",url:t,debug:e,failureMessage:"Failed to fetch platform JWKS",logLabel:"Error fetching platform JWKS:"})}var A=i=>i.replace(/\/+$/,"");async function w({licenseToken:i,requestUrl:e,supertabBaseUrl:t,debug:n}){if(!i)return{valid:!1,reason:"missing_license_token"};let r;try{r=P(i)}catch(a){return n&&console.error("Invalid license JWT header:",a),{valid:!1,reason:"invalid_license_header"}}if(r.alg!=="ES256")return n&&console.error("Unsupported license JWT alg:",r.alg),{valid:!1,reason:"invalid_license_algorithm"};let s;try{s=N(i)}catch(a){return n&&console.error("Invalid license JWT payload:",a),{valid:!1,reason:"invalid_license_payload"}}let o=s.license_id,p=s.iss;if(!p||!p.startsWith(t))return n&&console.error("Invalid license JWT issuer:",p),{valid:!1,reason:"invalid_license_issuer",licenseId:o};let d=Array.isArray(s.aud)?s.aud.filter(a=>typeof a=="string"):typeof s.aud=="string"?[s.aud]:[],g=A(e);if(!d.some(a=>{let u=A(a);return u?g.startsWith(u):!1}))return n&&console.error("License JWT audience does not match request URL:",s.aud),{valid:!1,reason:"invalid_license_audience",licenseId:o};try{let a=await _(t,n),h=await C(i,async y=>{let m=a.keys.find(I=>I.kid===y.kid);if(!m)throw new Error(`No matching platform key found: ${y.kid}`);return m},{issuer:p,algorithms:[r.alg],clockTolerance:"1m"});return{valid:!0,licenseId:o,payload:h.payload}}catch(a){return n&&console.error("License JWT verification failed:",a),a instanceof Error&&a.message?.includes("exp")?{valid:!1,reason:"license_token_expired",licenseId:o}:{valid:!1,reason:"license_signature_verification_failed",licenseId:o}}}function x({requestUrl:i}){let e=new URL(i);return`${e.protocol}//${e.host}/license.xml`}async function L({licenseToken:i,url:e,userAgent:t,ctx:n,supertabBaseUrl:r,merchantSystemUrn:s,debug:o,recordEvent:p}){let d=await w({licenseToken:i,requestUrl:e,supertabBaseUrl:r,debug:o});async function g(l){let a={page_url:e,user_agent:t,verification_status:d.valid?"valid":"invalid",verification_reason:d.reason||"success"},u=p(l,a,d.licenseId);return n?.waitUntil&&n.waitUntil(u),u}if(!d.valid){await g(d.reason||"license_token_verification_failed");let l="invalid_request",a="Access to this resource requires a license";switch(d.reason){case"missing_license_token":l="invalid_request",a="Access to this resource requires a license";break;case"license_token_expired":l="invalid_token",a="The license token has expired";break;case"license_signature_verification_failed":l="invalid_token",a="The license token signature is invalid";break;case"invalid_license_header":l="invalid_token",a="The license token header is invalid";break;case"invalid_license_payload":l="invalid_token",a="The license token payload is invalid";break;case"invalid_license_issuer":l="invalid_token",a="The license token issuer is invalid";break;case"invalid_license_audience":l="invalid_token",a="The license token audience is invalid";break;default:l="invalid_request",a="Access to this resource requires a license"}let u=x({requestUrl:e}),h=`${r}/docs/errors#${l}`,y=new Headers({"Content-Type":"text/plain; charset=UTF-8","WWW-Authenticate":`License error="${l}", error_description="${a}", error_uri="${h}"`,Link:`${u}; rel="license"; type="application/rsl+xml"`}),m=`Access to this resource requires a valid license token. Error: ${l} - ${a}`;return new Response(m,{status:401,headers:y})}return await g("license_used"),new Response("\u2705 License Token Access granted",{status:200,headers:new Headers({"Content-Type":"application/json"})})}function D(){let i={method:"GET"};return globalThis?.fastly&&(i={...i,backend:f}),i}async function v(i,e){let t=`${i}/merchants/systems/${e}/license.xml`,n=await fetch(t,D());if(!n.ok)return new Response("License not found",{status:404});let r=await n.text();return new Response(r,{status:200,headers:new Headers({"Content-Type":"application/xml"})})}var E=!0,c=class c{constructor(e,t=!1){if(!t&&c._instance){if(!(e.apiKey===c._instance.apiKey&&e.merchantSystemUrn===c._instance.merchantSystemUrn))throw new Error("Cannot create a new instance with different configuration. Use resetInstance to clear the existing instance.");return c._instance}if(t&&c._instance&&c.resetInstance(),!e.apiKey||!e.merchantSystemUrn)throw new Error("Missing required configuration: apiKey and merchantSystemUrn are required");this.apiKey=e.apiKey,this.merchantSystemUrn=e.merchantSystemUrn,c._instance=this}static resetInstance(){c._instance=null}static setBaseUrl(e){c.baseUrl=e}async verifyLicenseToken(e,t){return w({licenseToken:e,requestUrl:t,supertabBaseUrl:c.baseUrl,debug:E})}async recordEvent(e,t={},n){let r={event_name:e,merchant_system_urn:this.merchantSystemUrn?this.merchantSystemUrn:"",license_id:n,properties:t};try{let s={method:"POST",headers:{Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify(r)};globalThis?.fastly&&(s={...s,backend:f});let o=await fetch(`${c.baseUrl}/events`,s);o.ok||console.log(`Failed to record event: ${o.status}`)}catch(s){console.log("Error recording event:",s)}}static checkIfBotRequest(e){let t=e.headers.get("User-Agent")||"",n=e.headers.get("accept")||"",r=e.headers.get("sec-ch-ua"),s=e.headers.get("accept-language"),o=e.cf?.botManagement?.score,p=["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"],d=t.toLowerCase(),g=p.some(y=>d.includes(y)),l=t.toLowerCase().includes("headless")||t.toLowerCase().includes("puppeteer")||!r,a=!t.toLowerCase().includes("headless")||!t.toLowerCase().includes("puppeteer")||!r,u=!n||!s,h=typeof o=="number"&&o<30;return console.log("Bot Detection Details:",{botUaMatch:g,headlessIndicators:l,missingHeaders:u,lowBotScore:h,botScore:o}),(d.includes("safari")||d.includes("mozilla"))&&l&&a?!1:g||l||u||h}static async cloudflareHandleRequests(e,t,n){let{MERCHANT_SYSTEM_URN:r,MERCHANT_API_KEY:s}=t;return new c({apiKey:s,merchantSystemUrn:r}).handleRequest(e,c.checkIfBotRequest,n)}static async fastlyHandleRequests(e,t,n,r=!1){let s=new c({apiKey:n,merchantSystemUrn:t});return r&&new URL(e.url).pathname==="/license.xml"?await v(c.baseUrl,t):s.handleRequest(e,c.checkIfBotRequest,null)}async handleRequest(e,t,n){let r=e.headers.get("Authorization")||"",s=r.startsWith("License ")?r.slice(8):"",o=e.url,p=e.headers.get("User-Agent")||"unknown";return t&&!t(e,n)?new Response("\u2705 Non-Bot Content Access granted",{status:200,headers:new Headers({"Content-Type":"application/json"})}):L({licenseToken:s,url:o,userAgent:p,ctx:n,supertabBaseUrl:c.baseUrl,merchantSystemUrn:this.merchantSystemUrn,debug:E,recordEvent:(d,g,l)=>this.recordEvent(d,g,l)})}static async obtainLicenseToken(e,t,n,r){let s=c.baseUrl+"/rsl/token";return b({clientId:e,clientSecret:t,tokenEndpoint:s,resourceUrl:n,licenseXml:r,debug:E})}};c.baseUrl="https://api-connect.supertab.co",c._instance=null;var T=c;export{T as SupertabConnect};
|
|
1
|
+
var _=(e=>(e.DISABLED="disabled",e.SOFT="soft",e.STRICT="strict",e))(_||{});var g="stc-backend",b=(s=>(s.ALLOW="allow",s.BLOCK="block",s))(b||{});var w=null;function L(){return w||(w=import("jose")),w}async function J(r,t,s){try{let e=await fetch(r,t);if(!e.ok){let o=await e.text().catch(()=>""),i=`Failed to obtain license token: ${e.status} ${e.statusText}${o?` - ${o}`:""}`;throw new Error(i)}let n;try{n=await e.json()}catch(o){throw s&&console.error("Failed to parse license token response as JSON:",o),new Error("Failed to parse license token response as JSON")}if(!n?.access_token)throw new Error("License token response missing access_token");return n.access_token}catch(e){throw s&&console.error("Error generating license token:",e),e}}async function K(r,t){let e=`${new URL(r).origin}/license.xml`,n=await fetch(e);if(!n.ok)throw t&&console.error(`Failed to fetch license.xml from ${e}: ${n.status}`),new Error(`Failed to fetch license.xml from ${e}: ${n.status}`);let o=await n.text();return t&&console.debug("Fetched license.xml from",e),o}function q(r,t){let s=[],e=/<content\s([^>]*)>([\s\S]*?)<\/content>/gi,n=/url\s*=\s*"([^"]*)"/i,o=/server\s*=\s*"([^"]*)"/i,i=/<license[^>]*>[\s\S]*?<\/license>/i,a=0,c;for(;(c=e.exec(r))!==null;){a++;let l=c[1],d=c[2],f=l.match(n),h=l.match(o),m=d.match(i);if(f&&h&&m)s.push({urlPattern:f[1],server:h[1],licenseXml:m[0]});else if(t){let k=[!f&&"url",!h&&"server",!m&&"<license>"].filter(Boolean).join(", ");console.debug(`Skipping <content> element #${a}: missing ${k}`)}}return t&&console.debug(`Found ${a} <content> element(s), ${s.length} valid`),s}function H(r,t,s){let e=new URL(t),n=e.host,o=e.pathname;s&&console.debug(`Matching resource URL: ${t} (host=${n}, path=${o})`);let i=null,a=-1;for(let c of r){let l;try{l=new URL(c.urlPattern)}catch{s&&console.debug(`Skipping block with invalid URL pattern: ${c.urlPattern}`);continue}if(l.host!==n){s&&console.debug(`Skipping block: host mismatch (pattern=${l.host}, resource=${n})`);continue}let d=l.pathname;if(d===o)return s&&console.debug(`Exact match found: ${c.urlPattern}`),c;if(d.endsWith("/*")){let f=d.slice(0,-1);if(o.startsWith(f)){let h=f.length;h>a&&(a=h,i=c)}}}return s&&console.debug(i?`Wildcard match found: ${i.urlPattern} (specificity=${a})`:`No matching content block found for ${t}`),i}async function I({clientId:r,clientSecret:t,resourceUrl:s,debug:e}){let n=await K(s,e);e&&console.debug(`Fetched license.xml (${n.length} chars)`);let o=q(n,e);if(o.length===0)throw e&&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 i=H(o,s,e);if(!i){if(e){let d=o.map(f=>f.urlPattern).join(", ");console.error(`No <content> element matches resource URL: ${s}. Available patterns: ${d}`)}throw new Error(`No <content> element in license.xml matches resource URL: ${s}`)}e&&(console.debug("Matched content block for resource URL:",s),console.debug("Using license XML:",i.licenseXml));let a=i.server+"/token";e&&console.debug(`Requesting license token from ${a}`);let c=new URLSearchParams({grant_type:"client_credentials",license:i.licenseXml,resource:i.urlPattern}),l={method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json",Authorization:"Basic "+btoa(`${r}:${t}`)},body:c.toString()};return J(a,l,e)}var E=new Map;function W(){let r={method:"GET"};return globalThis?.fastly&&(r={...r,backend:g}),r}async function M({cacheKey:r,url:t,debug:s,failureMessage:e,logLabel:n}){if(!E.has(r))try{let o=await fetch(t,W());if(!o.ok)throw new Error(`${e}: ${o.status}`);let i=await o.json();E.set(r,i)}catch(o){throw s&&console.error(n,o),o}return E.get(r)}async function x(r,t){let s=`${r}/.well-known/jwks.json/platform`;return t&&console.debug(`Fetching platform JWKS from URL: ${s}`),M({cacheKey:"platform_jwks",url:s,debug:t,failureMessage:"Failed to fetch platform JWKS",logLabel:"Error fetching platform JWKS:"})}var R=r=>r.trim().replace(/\/+$/,"");async function v({licenseToken:r,requestUrl:t,supertabBaseUrl:s,debug:e}){let{decodeProtectedHeader:n,decodeJwt:o,jwtVerify:i}=await L();if(!r)return{valid:!1,reason:"missing_license_token"};let a;try{a=n(r)}catch(p){return e&&console.error("Invalid license JWT header:",p),{valid:!1,reason:"invalid_license_header"}}if(a.alg!=="ES256")return e&&console.error("Unsupported license JWT alg:",a.alg),{valid:!1,reason:"invalid_license_algorithm"};let c;try{c=o(r)}catch(p){return e&&console.error("Invalid license JWT payload:",p),{valid:!1,reason:"invalid_license_payload"}}let l=c.license_id,d=c.iss,f=d?R(d):void 0,h=R(s);if(!f||!f.startsWith(h))return e&&console.error("License JWT issuer is missing or malformed:",d),{valid:!1,reason:"invalid_license_issuer",licenseId:l};let m=Array.isArray(c.aud)?c.aud.filter(p=>typeof p=="string"):typeof c.aud=="string"?[c.aud]:[],k=R(t);if(!m.some(p=>{let y=R(p);return y?k.startsWith(y):!1}))return e&&console.error("License JWT audience does not match request URL:",c.aud),{valid:!1,reason:"invalid_license_audience",licenseId:l};let S;try{S=await x(s,e)}catch(p){return e&&console.error("Failed to fetch platform JWKS:",p),{valid:!1,reason:"server_error",licenseId:l}}try{let y=await i(r,async T=>{let U=S.keys.find(F=>F.kid===T.kid);if(!U)throw new Error(`No matching platform key found: ${T.kid}`);return U},{issuer:d,algorithms:[a.alg],clockTolerance:"1m"});return{valid:!0,licenseId:l,payload:y.payload}}catch(p){return e&&console.error("License JWT verification failed:",p),p instanceof Error&&p.message?.includes("exp")?{valid:!1,reason:"license_token_expired",licenseId:l}:{valid:!1,reason:"license_signature_verification_failed",licenseId:l}}}function P({requestUrl:r}){let t=new URL(r);return`${t.protocol}//${t.host}/license.xml`}function C(r){let t=P({requestUrl:r});return{action:"allow",headers:{Link:`<${t}>; rel="license"; type="application/rsl+xml"`,"X-RSL-Status":"token_required","X-RSL-Reason":"missing"}}}function A({reason:r,requestUrl:t,supertabBaseUrl:s}){let e,n,o;switch(r){case"missing_license_token":o=401,e="invalid_request",n="Authorization header missing or malformed";break;case"invalid_license_algorithm":o=401,e="invalid_request",n="Unsupported token algorithm";break;case"license_token_expired":o=401,e="invalid_token",n="The license token has expired";break;case"license_signature_verification_failed":o=401,e="invalid_token",n="The license token signature is invalid";break;case"invalid_license_header":o=401,e="invalid_token",n="The license token header is malformed";break;case"invalid_license_payload":o=401,e="invalid_token",n="The license token payload is malformed";break;case"invalid_license_issuer":o=401,e="invalid_token",n="The license token issuer is not recognized";break;case"invalid_license_audience":o=403,e="insufficient_scope",n="The license does not grant access to this resource";break;case"server_error":o=503,e="server_error",n="The server encountered an error validating the license";break;default:o=401,e="invalid_token",n="License token missing, expired, revoked, or malformed"}let i=P({requestUrl:t});return{action:"block",status:o,body:`Access to this resource requires a valid license token. Error: ${e} - ${n}`,headers:{"Content-Type":"text/plain; charset=UTF-8","WWW-Authenticate":`License error="${e}", error_description="${n}"`,Link:`<${i}>; rel="license"; type="application/rsl+xml"`}}}function j(){let r={method:"GET"};return globalThis?.fastly&&(r={...r,backend:g}),r}async function D(r,t){let s=`${r}/merchants/systems/${t}/license.xml`,e=await fetch(s,j());if(!e.ok)return new Response("License not found",{status:404});let n=await e.text();return new Response(n,{status:200,headers:new Headers({"Content-Type":"application/xml"})})}async function B(r){let t=await v({licenseToken:r.token,requestUrl:r.url,supertabBaseUrl:r.supertabBaseUrl,debug:r.debug});if(r.recordEvent){let s=t.valid?"license_used":t.reason,e={page_url:r.url,user_agent:r.userAgent,verification_status:t.valid?"valid":"invalid",verification_reason:t.valid?"success":t.reason},n=r.recordEvent(s,e,t.licenseId);r.ctx?.waitUntil&&r.ctx.waitUntil(n)}return t.valid?{action:"allow"}:A({reason:t.reason,requestUrl:r.url,supertabBaseUrl:r.supertabBaseUrl})}async function N(r,t,s){let e=await r.handleRequest(t,s);if(e.action==="block")return new Response(e.body,{status:e.status,headers:new Headers(e.headers)});let n=await fetch(t);if(e.headers){let o=new Response(n.body,n);for(let[i,a]of Object.entries(e.headers))o.headers.set(i,a);return o}return n}async function $(r,t,s,e){if(e&&new URL(t.url).pathname==="/license.xml")return await D(e.baseUrl,e.merchantSystemUrn);let n=await r.handleRequest(t);if(n.action==="block")return new Response(n.body,{status:n.status,headers:new Headers(n.headers)});let o=await fetch(t,{backend:s});if(n.headers){let i=new Response(o.body,o);for(let[a,c]of Object.entries(n.headers))i.headers.set(a,c);return i}return o}function X(r){let t=r.headers.get("User-Agent")||"",s=r.headers.get("accept")||"",e=r.headers.get("sec-ch-ua"),n=r.headers.get("accept-language"),o=r.cf?.botManagement?.score,i=["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"],a=t.toLowerCase(),c=i.some(m=>a.includes(m)),l=t.toLowerCase().includes("headless")||t.toLowerCase().includes("puppeteer")||!e,d=!t.toLowerCase().includes("headless")&&!t.toLowerCase().includes("puppeteer")&&!e,f=!s||!n,h=typeof o=="number"&&o<30;return(a.includes("safari")||a.includes("mozilla"))&&l&&d?!1:c||l||f||h}var u=class u{constructor(t,s=!1){if(!s&&u._instance){if(!(t.apiKey===u._instance.apiKey&&t.merchantSystemUrn===u._instance.merchantSystemUrn))throw new Error("Cannot create a new instance with different configuration. Use resetInstance to clear the existing instance.");return u._instance}if(s&&u._instance&&u.resetInstance(),!t.apiKey||!t.merchantSystemUrn)throw new Error("Missing required configuration: apiKey and merchantSystemUrn are required");this.apiKey=t.apiKey,this.merchantSystemUrn=t.merchantSystemUrn,this.enforcement=t.enforcement??"soft",this.botDetector=t.botDetector,this.debug=t.debug??!1,u._instance=this}static resetInstance(){u._instance=null}static setBaseUrl(t){u.baseUrl=t}static getBaseUrl(){return u.baseUrl}async verifyLicenseToken(t,s){return v({licenseToken:t,requestUrl:s,supertabBaseUrl:u.baseUrl,debug:this.debug})}async recordEvent(t,s={},e){let n={event_name:t,merchant_system_urn:this.merchantSystemUrn?this.merchantSystemUrn:"",license_id:e,properties:s};try{let o={method:"POST",headers:{Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify(n)};globalThis?.fastly&&(o={...o,backend:g});let i=await fetch(`${u.baseUrl}/events`,o);i.ok||console.log(`Failed to record event: ${i.status}`)}catch(o){console.log("Error recording event:",o)}}async handleRequest(t,s){let e=t.headers.get("Authorization")||"",n=e.startsWith("License ")?e.slice(8):null,o=t.url,i=t.headers.get("User-Agent")||"unknown";if(n)return this.enforcement==="disabled"?{action:"allow"}:B({token:n,url:o,userAgent:i,supertabBaseUrl:u.baseUrl,debug:this.debug,recordEvent:this.recordEvent.bind(this),ctx:s});if(!(this.botDetector?.(t,s)??!1))return{action:"allow"};switch(this.enforcement){case"strict":return A({reason:"missing_license_token",requestUrl:o,supertabBaseUrl:u.baseUrl});case"soft":return C(o);default:return{action:"allow"}}}static async obtainLicenseToken(t,s,e,n=!1){return I({clientId:t,clientSecret:s,resourceUrl:e,debug:n})}static async cloudflareHandleRequests(t,s,e){let n=new u({apiKey:s.MERCHANT_API_KEY,merchantSystemUrn:s.MERCHANT_SYSTEM_URN});return N(n,t,e)}static async fastlyHandleRequests(t,s,e,n,o){let{enableRSL:i=!1,botDetector:a,enforcement:c}=o??{},l=new u({apiKey:e,merchantSystemUrn:s,botDetector:a,enforcement:c});return $(l,t,n,i?{baseUrl:u.baseUrl,merchantSystemUrn:s}:void 0)}};u.baseUrl="https://api-connect.supertab.co",u._instance=null;var O=u;export{_ as EnforcementMode,b as HandlerAction,O as SupertabConnect,X as defaultBotDetector};
|
|
2
2
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/types.ts","../src/customer.ts","../src/license.ts","../src/jwks.ts","../src/index.ts"],"sourcesContent":["export interface SupertabConnectConfig {\n apiKey: string;\n merchantSystemUrn: string;\n}\n\n/**\n * Defines the shape for environment variables (used in CloudFlare integration).\n * These are used to identify and authenticate the Merchant System with the Supertab Connect API.\n */\nexport interface Env {\n\t/** The unique identifier for the merchant system. */\n\tMERCHANT_SYSTEM_URN: string;\n\t/** The API key for authenticating with the Supertab Connect. */\n\tMERCHANT_API_KEY: string;\n\t[key: string]: string;\n}\n\nexport interface EventPayload {\n event_name: string;\n license_id?: string;\n merchant_system_urn: string;\n properties: Record<string, any>;\n}\n\nexport interface LicenseTokenVerificationResult {\n valid: boolean;\n reason?: string;\n licenseId?: string;\n payload?: any;\n}\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}\n\nexport const FASTLY_BACKEND = \"stc-backend\";\n\nexport interface FetchOptions extends RequestInit {\n // Fastly-specific extension for backend routing\n backend?: string;\n}","import { importPKCS8, SignJWT } from \"jose\";\n\ntype SupportedAlg = \"RS256\" | \"ES256\";\n\ntype GenerateLicenseTokenParams = {\n clientId: string;\n kid: string;\n privateKeyPem: string;\n tokenEndpoint: string;\n resourceUrl: string;\n licenseXml: string;\n debug?: boolean;\n};\n\ntype ObtainLicenseTokenParams = {\n clientId: string;\n clientSecret: string;\n tokenEndpoint: string;\n resourceUrl: string;\n licenseXml: string;\n debug?: boolean;\n};\n\nasync function retrieveLicenseToken(\n tokenEndpoint: string,\n requestOptions: RequestInit,\n debug: boolean | undefined\n) {\n try {\n const response = await fetch(tokenEndpoint, requestOptions);\n\n if (!response.ok) {\n const errorBody = await response.text().catch(() => \"\");\n const errorMessage = `Failed to obtain license token: ${\n response.status\n } ${response.statusText}${errorBody ? ` - ${errorBody}` : \"\"}`;\n throw new Error(errorMessage);\n }\n\n let data: any;\n try {\n data = await response.json();\n } catch (parseError) {\n if (debug) {\n console.error(\n \"Failed to parse license token response as JSON:\",\n parseError\n );\n }\n throw new Error(\"Failed to parse license token response as JSON\");\n }\n\n if (!data?.access_token) {\n throw new Error(\"License token response missing access_token\");\n }\n\n return data.access_token;\n } catch (error) {\n if (debug) {\n console.error(\"Error generating license token:\", error);\n }\n throw error;\n }\n}\n\nasync function importKeyForAlgs(\n privateKeyPem: string,\n debug: boolean | undefined\n): Promise<{ key: CryptoKey; alg: SupportedAlg }> {\n const 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 { 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\nexport async function obtainLicenseToken({\n clientId,\n clientSecret,\n tokenEndpoint,\n resourceUrl,\n licenseXml,\n debug,\n}: ObtainLicenseTokenParams): Promise<string> {\n const payload = new URLSearchParams({\n grant_type: \"client_credentials\",\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 Authorization: \"Basic \" + btoa(`${clientId}:${clientSecret}`),\n },\n body: payload.toString(),\n };\n\n return retrieveLicenseToken(tokenEndpoint, requestOptions, debug);\n}\n\nexport type { GenerateLicenseTokenParams, ObtainLicenseTokenParams };\n","import {\n decodeProtectedHeader,\n decodeJwt,\n JWTPayload,\n JWTHeaderParameters,\n jwtVerify,\n} from \"jose\";\nimport {\n LicenseTokenInvalidReason,\n LicenseTokenVerificationResult,\n FASTLY_BACKEND,\n FetchOptions,\n} from \"./types\";\nimport { fetchPlatformJwks } from \"./jwks\";\n\nconst stripTrailingSlash = (value: string) => value.replace(/\\/+$/, \"\");\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 if (!licenseToken) {\n return {\n valid: false,\n reason: 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 };\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 };\n }\n\n let payload: JWTPayload;\n try {\n payload = decodeJwt(licenseToken);\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 };\n }\n\n // @ts-ignore\n const licenseId: string | undefined = payload.license_id;\n\n const issuer: string | undefined = payload.iss;\n if (!issuer || !issuer.startsWith(supertabBaseUrl)) {\n if (debug) {\n console.error(\"Invalid license JWT issuer:\", issuer);\n }\n return {\n valid: false,\n reason: 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 licenseId,\n };\n }\n\n try {\n const jwks = await fetchPlatformJwks(supertabBaseUrl, debug);\n\n const getKey = async (jwtHeader: JWTHeaderParameters) => {\n const jwk = jwks.keys.find((key: any) => key.kid === jwtHeader.kid);\n if (!jwk) {\n throw new Error(`No matching platform key found: ${jwtHeader.kid}`);\n }\n return jwk;\n };\n\n const result = await jwtVerify(licenseToken, getKey, {\n issuer,\n algorithms: [header.alg],\n clockTolerance: \"1m\",\n });\n\n return {\n valid: true,\n licenseId,\n payload: result.payload,\n };\n } catch (error) {\n if (debug) {\n console.error(\"License JWT verification failed:\", error);\n }\n\n if (error instanceof Error && error.message?.includes(\"exp\")) {\n return {\n valid: false,\n reason: LicenseTokenInvalidReason.EXPIRED,\n licenseId,\n };\n }\n\n return {\n valid: false,\n reason: LicenseTokenInvalidReason.SIGNATURE_VERIFICATION_FAILED,\n licenseId,\n };\n }\n}\n\nexport function generateLicenseLink({\n requestUrl,\n}: {\n requestUrl: string;\n}): string {\n const baseURL = new URL(requestUrl);\n return `${baseURL.protocol}//${baseURL.host}/license.xml`;\n}\n\ntype RecordEventFn = (\n eventName: string,\n properties?: Record<string, any>,\n licenseId?: string\n) => Promise<void>;\n\ntype BaseLicenseHandleRequestParams = {\n licenseToken: string;\n url: string;\n userAgent: string;\n ctx: any;\n supertabBaseUrl: string;\n merchantSystemUrn?: string;\n debug: boolean;\n recordEvent: RecordEventFn;\n};\n\nexport async function baseLicenseHandleRequest({\n licenseToken,\n url,\n userAgent,\n ctx,\n supertabBaseUrl,\n merchantSystemUrn,\n debug,\n recordEvent,\n}: BaseLicenseHandleRequestParams): Promise<Response> {\n const verification = await verifyLicenseToken({\n licenseToken,\n requestUrl: url,\n supertabBaseUrl,\n debug,\n });\n\n async function recordLicenseEvent(eventName: string) {\n const eventProperties = {\n page_url: url,\n user_agent: userAgent,\n verification_status: verification.valid ? \"valid\" : \"invalid\",\n verification_reason: verification.reason || \"success\",\n };\n\n const eventPromise = recordEvent(\n eventName,\n eventProperties,\n verification.licenseId\n );\n\n if (ctx?.waitUntil) {\n ctx.waitUntil(eventPromise);\n }\n\n return eventPromise;\n }\n\n if (!verification.valid) {\n await recordLicenseEvent(\n verification.reason || \"license_token_verification_failed\"\n );\n\n let rslError = \"invalid_request\";\n let errorDescription = \"Access to this resource requires a license\";\n\n switch (verification.reason) {\n case LicenseTokenInvalidReason.MISSING_TOKEN:\n rslError = \"invalid_request\";\n errorDescription = \"Access to this resource requires a license\";\n break;\n case LicenseTokenInvalidReason.EXPIRED:\n rslError = \"invalid_token\";\n errorDescription = \"The license token has expired\";\n break;\n case LicenseTokenInvalidReason.SIGNATURE_VERIFICATION_FAILED:\n rslError = \"invalid_token\";\n errorDescription = \"The license token signature is invalid\";\n break;\n case LicenseTokenInvalidReason.INVALID_HEADER:\n rslError = \"invalid_token\";\n errorDescription = \"The license token header is invalid\";\n break;\n case LicenseTokenInvalidReason.INVALID_PAYLOAD:\n rslError = \"invalid_token\";\n errorDescription = \"The license token payload is invalid\";\n break;\n case LicenseTokenInvalidReason.INVALID_ISSUER:\n rslError = \"invalid_token\";\n errorDescription = \"The license token issuer is invalid\";\n break;\n case LicenseTokenInvalidReason.INVALID_AUDIENCE:\n rslError = \"invalid_token\";\n errorDescription = \"The license token audience is invalid\";\n break;\n default:\n rslError = \"invalid_request\";\n errorDescription = \"Access to this resource requires a license\";\n }\n\n const licenseLink = generateLicenseLink({\n requestUrl: url,\n });\n const errorUri = `${supertabBaseUrl}/docs/errors#${rslError}`;\n\n const headers = new Headers({\n \"Content-Type\": \"text/plain; charset=UTF-8\",\n \"WWW-Authenticate\": `License error=\"${rslError}\", error_description=\"${errorDescription}\", error_uri=\"${errorUri}\"`,\n Link: `${licenseLink}; rel=\"license\"; type=\"application/rsl+xml\"`,\n });\n\n const responseBody = `Access to this resource requires a valid license token. Error: ${rslError} - ${errorDescription}`;\n\n return new Response(responseBody, {\n status: 401,\n headers,\n });\n }\n\n await recordLicenseEvent(\"license_used\");\n return new Response(\"✅ License Token Access granted\", {\n status: 200,\n headers: new Headers({ \"Content-Type\": \"application/json\" }),\n });\n}\n\nfunction buildFetchOptions(): FetchOptions {\n let options: FetchOptions = { method: \"GET\" };\n // @ts-ignore - backend is a Fastly-specific extension\n if (globalThis?.fastly) {\n options = { ...options, backend: FASTLY_BACKEND };\n }\n return options;\n}\n\nexport async function hostRSLicenseXML(\n supertabBaseUrl: string,\n merchantSystemUrn: string\n): Promise<Response> {\n const licenseUrl = `${supertabBaseUrl}/merchants/systems/${merchantSystemUrn}/license.xml`;\n const response = await fetch(licenseUrl, buildFetchOptions());\n\n if (!response.ok) {\n return new Response(\"License not found\", { status: 404 });\n }\n\n const licenseXml = await response.text();\n\n return new Response(licenseXml, {\n status: 200,\n headers: new Headers({ \"Content-Type\": \"application/xml\" }),\n });\n}\n","import { FASTLY_BACKEND, FetchOptions } from \"./types\";\n\nconst jwksCache = new Map<string, any>();\n\ntype JwksCacheKey = string;\n\ntype FetchJwksParams = {\n cacheKey: JwksCacheKey;\n url: string;\n debug: boolean;\n failureMessage: string;\n logLabel: string;\n};\n\nfunction buildFetchOptions(): FetchOptions {\n let options: FetchOptions = { method: \"GET\" };\n // @ts-ignore - backend is a Fastly-specific extension\n if (globalThis?.fastly) {\n options = { ...options, backend: FASTLY_BACKEND };\n }\n return options;\n}\n\nasync function fetchAndCacheJwks({\n cacheKey,\n url,\n debug,\n failureMessage,\n logLabel,\n}: FetchJwksParams): Promise<any> {\n if (!jwksCache.has(cacheKey)) {\n try {\n const response = await fetch(url, buildFetchOptions());\n\n if (!response.ok) {\n throw new Error(`${failureMessage}: ${response.status}`);\n }\n\n const jwksData = await response.json();\n jwksCache.set(cacheKey, jwksData);\n } catch (error) {\n if (debug) {\n console.error(logLabel, error);\n }\n throw error;\n }\n }\n\n return jwksCache.get(cacheKey);\n}\n\nexport async function fetchPlatformJwks(\n baseUrl: string,\n debug: boolean\n): Promise<any> {\n const jwksUrl = `${baseUrl}/.well-known/jwks.json/platform`;\n console.log(\"Fetching platform JWKS from:\", jwksUrl);\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 {\n SupertabConnectConfig,\n Env,\n EventPayload,\n FASTLY_BACKEND,\n LicenseTokenVerificationResult,\n} from \"./types\";\nimport { obtainLicenseToken as obtainLicenseTokenHelper } from \"./customer\";\nimport {\n baseLicenseHandleRequest as baseLicenseHandleRequestHelper,\n hostRSLicenseXML as hostRSLicenseXMLHelper,\n verifyLicenseToken as verifyLicenseTokenHelper,\n} from \"./license\";\n\nexport type { Env } from \"./types\";\n\nconst debug = true; // Set to true for debugging purposes\n\n/**\n * SupertabConnect class provides higher level methods\n * for using Supertab Connect within supported CDN integrations\n * as well as more specialized methods to customarily verify JWT tokens and record events.\n */\nexport class SupertabConnect {\n private apiKey?: string;\n private static baseUrl: string = \"https://api-connect.supertab.co\";\n private merchantSystemUrn!: string;\n\n private static _instance: SupertabConnect | null = null;\n\n public constructor(config: SupertabConnectConfig, reset: boolean = false) {\n if (!reset && SupertabConnect._instance) {\n // If reset was not requested and an instance conflicts with the provided config, throw an error\n if (\n !(\n config.apiKey === SupertabConnect._instance.apiKey &&\n config.merchantSystemUrn ===\n SupertabConnect._instance.merchantSystemUrn\n )\n ) {\n throw new Error(\n \"Cannot create a new instance with different configuration. Use resetInstance to clear the existing instance.\"\n );\n }\n\n // If an instance already exists and reset is not requested, just return the existing instance\n return SupertabConnect._instance;\n }\n if (reset && SupertabConnect._instance) {\n // ...and if reset is requested and required, clear the existing instance first\n SupertabConnect.resetInstance();\n }\n\n if (!config.apiKey || !config.merchantSystemUrn) {\n throw new Error(\n \"Missing required configuration: apiKey and merchantSystemUrn are required\"\n );\n }\n this.apiKey = config.apiKey;\n this.merchantSystemUrn = config.merchantSystemUrn;\n\n // Register this as the singleton instance\n SupertabConnect._instance = this;\n }\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 * Verify a license token\n * @param licenseToken The license token to verify\n * @param requestUrl The URL of the request being made\n * @returns A promise that resolves with the verification result\n */\n async verifyLicenseToken(\n licenseToken: string,\n requestUrl: string\n ): Promise<LicenseTokenVerificationResult> {\n return verifyLicenseTokenHelper({\n licenseToken,\n requestUrl,\n supertabBaseUrl: SupertabConnect.baseUrl,\n debug,\n });\n }\n\n /**\n * Records an analytics event\n * @param eventName Name of the event to record\n * @param properties Additional properties to include with the event\n * @param licenseId Optional license ID associated with the event\n * @returns Promise that resolves when the event is recorded\n */\n async recordEvent(\n eventName: string,\n properties: Record<string, any> = {},\n licenseId?: string\n ): Promise<void> {\n const payload: EventPayload = {\n event_name: eventName,\n merchant_system_urn: this.merchantSystemUrn ? this.merchantSystemUrn : \"\",\n license_id: licenseId,\n properties,\n };\n\n try {\n let options: any = {\n method: \"POST\",\n headers: {\n Authorization: `Bearer ${this.apiKey}`,\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(payload),\n };\n // @ts-ignore\n if (globalThis?.fastly) {\n options = { ...options, backend: FASTLY_BACKEND };\n }\n const response = await fetch(\n `${SupertabConnect.baseUrl}/events`,\n options\n );\n\n if (!response.ok) {\n console.log(`Failed to record event: ${response.status}`);\n }\n } catch (error) {\n console.log(\"Error recording event:\", error);\n }\n }\n\n\n static checkIfBotRequest(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 userAgent.toLowerCase().includes(\"headless\") ||\n userAgent.toLowerCase().includes(\"puppeteer\") ||\n !secChUa;\n\n const only_sec_ch_ua_missing =\n !userAgent.toLowerCase().includes(\"headless\") ||\n !userAgent.toLowerCase().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 console.log(\"Bot Detection Details:\", {\n botUaMatch,\n headlessIndicators,\n missingHeaders,\n lowBotScore,\n botScore,\n });\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 && only_sec_ch_ua_missing) {\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\n static async cloudflareHandleRequests(\n request: Request,\n env: Env,\n ctx: any\n ): Promise<Response> {\n // Validate required env variables\n const { MERCHANT_SYSTEM_URN, MERCHANT_API_KEY } = env;\n\n // Prepare or get the SupertabConnect instance\n const supertabConnect = new SupertabConnect({\n apiKey: MERCHANT_API_KEY,\n merchantSystemUrn: MERCHANT_SYSTEM_URN,\n });\n\n // Handle the request, including bot detection, token verification and recording the event\n return supertabConnect.handleRequest(\n request,\n SupertabConnect.checkIfBotRequest,\n ctx\n );\n }\n\n static async fastlyHandleRequests(\n request: Request,\n merchantSystemUrn: string,\n merchantApiKey: string,\n enableRSL: boolean = false,\n ): Promise<Response> {\n // Prepare or get the SupertabConnect instance\n const supertabConnect = new SupertabConnect({\n apiKey: merchantApiKey,\n merchantSystemUrn: merchantSystemUrn,\n });\n\n if (enableRSL) {\n if (new URL(request.url).pathname === \"/license.xml\") {\n return await hostRSLicenseXMLHelper(\n SupertabConnect.baseUrl,\n merchantSystemUrn\n );\n }\n }\n\n // Handle the request, including bot detection, token verification and recording the event\n return supertabConnect.handleRequest(\n request,\n SupertabConnect.checkIfBotRequest,\n null\n );\n }\n\n async handleRequest(\n request: Request,\n botDetectionHandler?: (request: Request, ctx?: any) => boolean,\n ctx?: any\n ): Promise<Response> {\n // 1. Extract license token, URL, and user agent from the request\n const auth = request.headers.get(\"Authorization\") || \"\";\n const licenseToken = auth.startsWith(\"License \") ? auth.slice(8) : \"\";\n const url = request.url;\n const user_agent = request.headers.get(\"User-Agent\") || \"unknown\";\n\n // 2. Handle bot detection if provided\n if (botDetectionHandler && !botDetectionHandler(request, ctx)) {\n return new Response(\"✅ Non-Bot Content Access granted\", {\n status: 200,\n headers: new Headers({ \"Content-Type\": \"application/json\" }),\n });\n }\n\n // 3. Handle the license token request\n return baseLicenseHandleRequestHelper({\n licenseToken,\n url,\n userAgent: user_agent,\n ctx,\n supertabBaseUrl: SupertabConnect.baseUrl,\n merchantSystemUrn: this.merchantSystemUrn,\n debug,\n recordEvent: (\n eventName: string,\n properties?: Record<string, any>,\n licenseId?: string\n ) => this.recordEvent(eventName, properties, licenseId),\n });\n }\n\n /**\n * Request a license token from the Supertab Connect token endpoint.\n * @param clientId OAuth client identifier.\n * @param clientSecret OAuth client secret for client_credentials flow.\n * @param resourceUrl Resource URL attempting to access with a License.\n * @param licenseXml XML license document to include in the request payload.\n * @returns Promise resolving to the issued license access token string.\n */\n static async obtainLicenseToken(\n clientId: string,\n clientSecret: string,\n resourceUrl: string,\n licenseXml: string\n ): Promise<string> {\n const tokenEndpoint = SupertabConnect.baseUrl + \"/rsl/token\";\n return obtainLicenseTokenHelper({\n clientId,\n clientSecret,\n tokenEndpoint,\n resourceUrl,\n licenseXml,\n debug,\n });\n }\n}\n"],"mappings":"AA0CO,IAAMA,EAAiB,cC1C9B,OAAS,eAAAC,EAAa,WAAAC,MAAe,OAuBrC,eAAeC,EACXC,EACAC,EACAC,EACF,CACA,GAAI,CACF,IAAMC,EAAW,MAAM,MAAMH,EAAeC,CAAc,EAE1D,GAAI,CAACE,EAAS,GAAI,CAChB,IAAMC,EAAY,MAAMD,EAAS,KAAK,EAAE,MAAM,IAAM,EAAE,EAChDE,EAAe,mCACnBF,EAAS,MACX,IAAIA,EAAS,UAAU,GAAGC,EAAY,MAAM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C,EAIIW,EAA+B,CACpC,aAAArC,EACA,IAAAD,EACA,UAAWqC,EACX,IAAAV,EACA,gBAAiB9B,EAAgB,QACjC,kBAAmB,KAAK,kBACxB,MAAAD,EACA,YAAa,CACXQ,EACAC,EACAC,IACG,KAAK,YAAYF,EAAWC,EAAYC,CAAS,CACxD,CAAC,CACH,CAUA,aAAa,mBACXiC,EACAC,EACAC,EACAC,EACiB,CACjB,IAAMC,EAAgB9C,EAAgB,QAAU,aAChD,OAAO+C,EAAyB,CAC9B,SAAAL,EACA,aAAAC,EACA,cAAAG,EACA,YAAAF,EACA,WAAAC,EACA,MAAA9C,CACF,CAAC,CACH,CACF,EA5SaC,EAEI,QAAkB,kCAFtBA,EAKI,UAAoC,KAL9C,IAAMgD,EAANhD","names":["FASTLY_BACKEND","importPKCS8","SignJWT","retrieveLicenseToken","tokenEndpoint","requestOptions","debug","response","errorBody","errorMessage","data","parseError","error","obtainLicenseToken","clientId","clientSecret","tokenEndpoint","resourceUrl","licenseXml","debug","payload","requestOptions","retrieveLicenseToken","decodeProtectedHeader","decodeJwt","jwtVerify","jwksCache","buildFetchOptions","options","FASTLY_BACKEND","fetchAndCacheJwks","cacheKey","url","debug","failureMessage","logLabel","response","jwksData","error","fetchPlatformJwks","baseUrl","jwksUrl","stripTrailingSlash","value","verifyLicenseToken","licenseToken","requestUrl","supertabBaseUrl","debug","header","decodeProtectedHeader","error","payload","decodeJwt","licenseId","issuer","audienceValues","entry","requestUrlNormalized","normalizedAudience","jwks","fetchPlatformJwks","result","jwtVerify","jwtHeader","jwk","key","generateLicenseLink","baseURL","baseLicenseHandleRequest","url","userAgent","ctx","merchantSystemUrn","recordEvent","verification","recordLicenseEvent","eventName","eventProperties","eventPromise","rslError","errorDescription","licenseLink","errorUri","headers","responseBody","buildFetchOptions","options","FASTLY_BACKEND","hostRSLicenseXML","licenseUrl","response","licenseXml","debug","_SupertabConnect","config","reset","url","licenseToken","requestUrl","verifyLicenseToken","eventName","properties","licenseId","payload","options","FASTLY_BACKEND","response","error","request","userAgent","accept","secChUa","acceptLanguage","botScore","botList","lowerCaseUserAgent","botUaMatch","bot","headlessIndicators","only_sec_ch_ua_missing","missingHeaders","lowBotScore","env","ctx","MERCHANT_SYSTEM_URN","MERCHANT_API_KEY","merchantSystemUrn","merchantApiKey","enableRSL","supertabConnect","hostRSLicenseXML","botDetectionHandler","auth","user_agent","baseLicenseHandleRequest","clientId","clientSecret","resourceUrl","licenseXml","tokenEndpoint","obtainLicenseToken","SupertabConnect"]}
|
|
1
|
+
{"version":3,"sources":["../src/types.ts","../src/jose.ts","../src/customer.ts","../src/jwks.ts","../src/license.ts","../src/cdn.ts","../src/bots.ts","../src/index.ts"],"sourcesContent":["export enum EnforcementMode {\n DISABLED = \"disabled\",\n SOFT = \"soft\",\n STRICT = \"strict\",\n}\n\nexport type BotDetector = (request: Request, ctx?: any) => boolean;\n\nexport interface SupertabConnectConfig {\n apiKey: string;\n merchantSystemUrn: string;\n enforcement?: EnforcementMode;\n botDetector?: BotDetector;\n debug?: boolean;\n}\n\n/**\n * Defines the shape for environment variables (used in CloudFlare integration).\n * These are used to identify and authenticate the Merchant System with the Supertab Connect API.\n */\nexport interface Env {\n\t/** The unique identifier for the merchant system. */\n\tMERCHANT_SYSTEM_URN: string;\n\t/** The API key for authenticating with the Supertab Connect. */\n\tMERCHANT_API_KEY: string;\n\t[key: string]: string;\n}\n\nexport interface EventPayload {\n event_name: string;\n license_id?: string;\n merchant_system_urn: string;\n properties: Record<string, any>;\n}\n\nexport type LicenseTokenVerificationResult =\n | { valid: true; licenseId?: string; payload: any }\n | { valid: false; reason: LicenseTokenInvalidReason; licenseId?: string };\n\nexport enum LicenseTokenInvalidReason {\n MISSING_TOKEN = \"missing_license_token\",\n INVALID_HEADER = \"invalid_license_header\",\n INVALID_ALG = \"invalid_license_algorithm\",\n INVALID_PAYLOAD = \"invalid_license_payload\",\n INVALID_ISSUER = \"invalid_license_issuer\",\n SIGNATURE_VERIFICATION_FAILED = \"license_signature_verification_failed\",\n EXPIRED = \"license_token_expired\",\n INVALID_AUDIENCE = \"invalid_license_audience\",\n SERVER_ERROR = \"server_error\",\n}\n\nexport const FASTLY_BACKEND = \"stc-backend\";\n\nexport interface FetchOptions extends RequestInit {\n // Fastly-specific extension for backend routing\n backend?: string;\n}\n\nexport enum HandlerAction {\n ALLOW = \"allow\",\n BLOCK = \"block\",\n}\n\nexport type HandlerResult =\n | { action: HandlerAction.ALLOW; headers?: Record<string, string> }\n | { action: HandlerAction.BLOCK; status: number; body: string; headers: Record<string, string> };","type JoseModule = typeof import(\"jose\");\n\nlet joseModulePromise: Promise<JoseModule> | null = null;\n\n/**\n * Lazily load the ESM-only `jose` package so the CommonJS build can call it via dynamic import.\n */\nexport function loadJose(): Promise<JoseModule> {\n if (!joseModulePromise) {\n joseModulePromise = import(\"jose\");\n }\n return joseModulePromise;\n}\n","import { loadJose } from \"./jose\";\n\ntype SupportedAlg = \"RS256\" | \"ES256\";\n\ntype GenerateLicenseTokenParams = {\n clientId: string;\n kid: string;\n privateKeyPem: string;\n tokenEndpoint: string;\n resourceUrl: string;\n licenseXml: string;\n debug?: boolean;\n};\n\ntype ObtainLicenseTokenParams = {\n clientId: string;\n clientSecret: string;\n resourceUrl: string;\n debug?: boolean;\n};\n\ntype ContentBlock = {\n urlPattern: string;\n licenseXml: string;\n server: string;\n};\n\nasync function retrieveLicenseToken(\n tokenEndpoint: string,\n requestOptions: RequestInit,\n debug: boolean | undefined\n) {\n try {\n const response = await fetch(tokenEndpoint, requestOptions);\n\n if (!response.ok) {\n const errorBody = await response.text().catch(() => \"\");\n const errorMessage = `Failed to obtain license token: ${\n response.status\n } ${response.statusText}${errorBody ? ` - ${errorBody}` : \"\"}`;\n throw new Error(errorMessage);\n }\n\n let data: any;\n try {\n data = await response.json();\n } catch (parseError) {\n if (debug) {\n console.error(\n \"Failed to parse license token response as JSON:\",\n parseError\n );\n }\n throw new Error(\"Failed to parse license token response as JSON\");\n }\n\n if (!data?.access_token) {\n throw new Error(\"License token response missing access_token\");\n }\n\n return data.access_token;\n } catch (error) {\n if (debug) {\n console.error(\"Error generating license token:\", error);\n }\n throw error;\n }\n}\n\nasync function importKeyForAlgs(\n privateKeyPem: string,\n debug: boolean | undefined\n): Promise<{ key: CryptoKey; alg: SupportedAlg }> {\n const { importPKCS8 } = await loadJose();\n const supportedAlgs: SupportedAlg[] = [\"ES256\", \"RS256\"];\n\n for (const algorithm of supportedAlgs) {\n try {\n const key = await importPKCS8(privateKeyPem, algorithm);\n return { key, alg: algorithm };\n } catch (importError) {\n if (debug) {\n console.debug(\n `Private key did not import using ${algorithm}, retrying...`,\n importError\n );\n }\n }\n }\n\n throw new Error(\n \"Unsupported private key format. Expected RSA or P-256 EC private key.\"\n );\n}\n\n// Temporarily not exporting this function to reflect only client credentials flow being supported\nasync function generateLicenseToken({\n clientId,\n kid,\n privateKeyPem,\n tokenEndpoint,\n resourceUrl,\n licenseXml,\n debug,\n}: GenerateLicenseTokenParams): Promise<string> {\n const { SignJWT } = await loadJose();\n const { key, alg } = await importKeyForAlgs(privateKeyPem, debug);\n const now = Math.floor(Date.now() / 1000);\n\n const clientAssertion = await new SignJWT({})\n .setProtectedHeader({ alg, kid })\n .setIssuer(clientId)\n .setSubject(clientId)\n .setIssuedAt(now)\n .setExpirationTime(now + 300)\n .setAudience(tokenEndpoint)\n .sign(key);\n\n const payload = new URLSearchParams({\n grant_type: \"rsl\",\n client_assertion_type:\n \"urn:ietf:params:oauth:client-assertion-type:jwt-bearer\",\n client_assertion: clientAssertion,\n license: licenseXml,\n resource: resourceUrl,\n });\n\n const requestOptions: RequestInit = {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/x-www-form-urlencoded\",\n Accept: \"application/json\",\n },\n body: payload.toString(),\n };\n\n return retrieveLicenseToken(tokenEndpoint, requestOptions, debug);\n}\n\nasync function fetchLicenseXml(\n resourceUrl: string,\n debug: boolean | undefined\n): Promise<string> {\n const origin = new URL(resourceUrl).origin;\n const licenseXmlUrl = `${origin}/license.xml`;\n\n const response = await fetch(licenseXmlUrl);\n if (!response.ok) {\n if (debug) {\n console.error(`Failed to fetch license.xml from ${licenseXmlUrl}: ${response.status}`);\n }\n throw new Error(\n `Failed to fetch license.xml from ${licenseXmlUrl}: ${response.status}`\n );\n }\n\n const xml = await response.text();\n if (debug) {\n console.debug(\"Fetched license.xml from\", licenseXmlUrl);\n }\n return xml;\n}\n\nfunction parseContentElements(xml: string, debug?: boolean): ContentBlock[] {\n const contentBlocks: ContentBlock[] = [];\n const contentRegex = /<content\\s([^>]*)>([\\s\\S]*?)<\\/content>/gi;\n const urlRegex = /url\\s*=\\s*\"([^\"]*)\"/i;\n const serverRegex = /server\\s*=\\s*\"([^\"]*)\"/i;\n const licenseRegex = /<license[^>]*>[\\s\\S]*?<\\/license>/i;\n\n let elementCount = 0;\n let match;\n while ((match = contentRegex.exec(xml)) !== null) {\n elementCount++;\n const attrs = match[1];\n const body = match[2];\n const urlMatch = attrs.match(urlRegex);\n const serverMatch = attrs.match(serverRegex);\n const licenseMatch = body.match(licenseRegex);\n\n if (urlMatch && serverMatch && licenseMatch) {\n contentBlocks.push({\n urlPattern: urlMatch[1],\n server: serverMatch[1],\n licenseXml: licenseMatch[0],\n });\n } else if (debug) {\n const missing = [\n !urlMatch && \"url\",\n !serverMatch && \"server\",\n !licenseMatch && \"<license>\",\n ].filter(Boolean).join(\", \");\n console.debug(`Skipping <content> element #${elementCount}: missing ${missing}`);\n }\n }\n\n if (debug) {\n console.debug(`Found ${elementCount} <content> element(s), ${contentBlocks.length} valid`);\n }\n\n return contentBlocks;\n}\n\nfunction findBestMatchingContent(\n contentBlocks: ContentBlock[],\n resourceUrl: string,\n debug?: boolean\n): ContentBlock | null {\n const parsed = new URL(resourceUrl);\n const host = parsed.host;\n const path = parsed.pathname;\n\n if (debug) {\n console.debug(`Matching resource URL: ${resourceUrl} (host=${host}, path=${path})`);\n }\n\n let bestMatch: ContentBlock | null = null;\n let bestSpecificity = -1;\n\n for (const block of contentBlocks) {\n let patternUrl: URL;\n try {\n patternUrl = new URL(block.urlPattern);\n } catch {\n if (debug) {\n console.debug(`Skipping block with invalid URL pattern: ${block.urlPattern}`);\n }\n continue;\n }\n\n if (patternUrl.host !== host) {\n if (debug) {\n console.debug(`Skipping block: host mismatch (pattern=${patternUrl.host}, resource=${host})`);\n }\n continue;\n }\n\n const patternPath = patternUrl.pathname;\n\n if (patternPath === path) {\n if (debug) {\n console.debug(`Exact match found: ${block.urlPattern}`);\n }\n return block;\n }\n\n if (patternPath.endsWith(\"/*\")) {\n const prefix = patternPath.slice(0, -1); // remove trailing *\n if (path.startsWith(prefix)) {\n const specificity = prefix.length;\n if (specificity > bestSpecificity) {\n bestSpecificity = specificity;\n bestMatch = block;\n }\n }\n }\n }\n\n if (debug) {\n if (bestMatch) {\n console.debug(`Wildcard match found: ${bestMatch.urlPattern} (specificity=${bestSpecificity})`);\n } else {\n console.debug(`No matching content block found for ${resourceUrl}`);\n }\n }\n\n return bestMatch;\n}\n\nexport { parseContentElements, findBestMatchingContent };\nexport type { ContentBlock };\n\nexport async function obtainLicenseToken({\n clientId,\n clientSecret,\n resourceUrl,\n debug,\n}: ObtainLicenseTokenParams): Promise<string> {\n const xml = await fetchLicenseXml(resourceUrl, debug);\n if (debug) {\n console.debug(`Fetched license.xml (${xml.length} chars)`);\n }\n const contentBlocks = parseContentElements(xml, debug);\n\n if (contentBlocks.length === 0) {\n if (debug) {\n console.error(\"No valid <content> elements with <license> found in license.xml\");\n }\n throw new Error(\n \"No valid <content> elements with <license> found in license.xml\"\n );\n }\n\n const matchedContent = findBestMatchingContent(contentBlocks, resourceUrl, debug);\n if (!matchedContent) {\n if (debug) {\n const patterns = contentBlocks.map(b => b.urlPattern).join(\", \");\n console.error(`No <content> element matches resource URL: ${resourceUrl}. Available patterns: ${patterns}`);\n }\n throw new Error(\n `No <content> element in license.xml matches resource URL: ${resourceUrl}`\n );\n }\n\n if (debug) {\n console.debug(\"Matched content block for resource URL:\", resourceUrl);\n console.debug(\"Using license XML:\", matchedContent.licenseXml);\n }\n\n const tokenEndpoint = matchedContent.server + '/token';\n if (debug) {\n console.debug(`Requesting license token from ${tokenEndpoint}`);\n }\n\n const payload = new URLSearchParams({\n grant_type: \"client_credentials\",\n license: matchedContent.licenseXml,\n resource: matchedContent.urlPattern,\n });\n\n const requestOptions: RequestInit = {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/x-www-form-urlencoded\",\n Accept: \"application/json\",\n Authorization: \"Basic \" + btoa(`${clientId}:${clientSecret}`),\n },\n body: payload.toString(),\n };\n\n return retrieveLicenseToken(tokenEndpoint, requestOptions, debug);\n}\n\nexport type { ObtainLicenseTokenParams };\n","import { FASTLY_BACKEND, FetchOptions } from \"./types\";\n\nconst jwksCache = new Map<string, any>();\n\ntype JwksCacheKey = string;\n\ntype FetchJwksParams = {\n cacheKey: JwksCacheKey;\n url: string;\n debug: boolean;\n failureMessage: string;\n logLabel: string;\n};\n\nfunction buildFetchOptions(): FetchOptions {\n let options: FetchOptions = { method: \"GET\" };\n // @ts-ignore - backend is a Fastly-specific extension\n if (globalThis?.fastly) {\n options = { ...options, backend: FASTLY_BACKEND };\n }\n return options;\n}\n\nasync function fetchAndCacheJwks({\n cacheKey,\n url,\n debug,\n failureMessage,\n logLabel,\n}: FetchJwksParams): Promise<any> {\n if (!jwksCache.has(cacheKey)) {\n try {\n const response = await fetch(url, buildFetchOptions());\n\n if (!response.ok) {\n throw new Error(`${failureMessage}: ${response.status}`);\n }\n\n const jwksData = await response.json();\n jwksCache.set(cacheKey, jwksData);\n } catch (error) {\n if (debug) {\n console.error(logLabel, error);\n }\n throw error;\n }\n }\n\n return jwksCache.get(cacheKey);\n}\n\nexport async function fetchPlatformJwks(\n baseUrl: string,\n debug: boolean\n): Promise<any> {\n const jwksUrl = `${baseUrl}/.well-known/jwks.json/platform`;\n if (debug) {\n console.debug(`Fetching platform JWKS from URL: ${jwksUrl}`);\n }\n\n return fetchAndCacheJwks({\n cacheKey: \"platform_jwks\",\n url: jwksUrl,\n debug,\n failureMessage: \"Failed to fetch platform JWKS\",\n logLabel: \"Error fetching platform JWKS:\",\n });\n}\n\nexport function clearJwksCache(): void {\n jwksCache.clear();\n}\n","import type { JWTPayload, JWTHeaderParameters } from \"jose\";\nimport { loadJose } from \"./jose\";\n\ninterface LicenseJWTPayload extends JWTPayload {\n license_id?: string;\n}\nimport {\n HandlerAction,\n HandlerResult,\n LicenseTokenInvalidReason,\n LicenseTokenVerificationResult,\n FASTLY_BACKEND,\n FetchOptions,\n} from \"./types\";\nimport { fetchPlatformJwks } from \"./jwks\";\n\nexport type EventRecorder = (\n eventName: string,\n properties: Record<string, any>,\n licenseId?: string\n) => Promise<void>;\n\nconst stripTrailingSlash = (value: string) => value.trim().replace(/\\/+$/, \"\");\n\nexport type VerifyLicenseTokenParams = {\n licenseToken: string;\n requestUrl: string;\n supertabBaseUrl: string;\n debug: boolean;\n};\n\nexport async function verifyLicenseToken({\n licenseToken,\n requestUrl,\n supertabBaseUrl,\n debug,\n}: VerifyLicenseTokenParams): Promise<LicenseTokenVerificationResult> {\n const { decodeProtectedHeader, decodeJwt, jwtVerify } = await loadJose();\n\n if (!licenseToken) {\n return {\n valid: false,\n reason: LicenseTokenInvalidReason.MISSING_TOKEN,\n };\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 };\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 };\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 };\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 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 licenseId,\n };\n }\n\n let jwks;\n try {\n jwks = await fetchPlatformJwks(supertabBaseUrl, debug);\n } catch (error) {\n if (debug) {\n console.error(\"Failed to fetch platform JWKS:\", error);\n }\n return {\n valid: false,\n reason: LicenseTokenInvalidReason.SERVER_ERROR,\n licenseId,\n };\n }\n\n try {\n const getKey = async (jwtHeader: JWTHeaderParameters) => {\n const jwk = jwks.keys.find((key: any) => key.kid === jwtHeader.kid);\n if (!jwk) {\n throw new Error(`No matching platform key found: ${jwtHeader.kid}`);\n }\n return jwk;\n };\n\n const result = await jwtVerify(licenseToken, getKey, {\n issuer,\n algorithms: [header.alg],\n clockTolerance: \"1m\",\n });\n\n return {\n valid: true,\n licenseId,\n payload: result.payload,\n };\n } catch (error) {\n if (debug) {\n console.error(\"License JWT verification failed:\", error);\n }\n\n if (error instanceof Error && error.message?.includes(\"exp\")) {\n return {\n valid: false,\n reason: LicenseTokenInvalidReason.EXPIRED,\n licenseId,\n };\n }\n\n return {\n valid: false,\n reason: LicenseTokenInvalidReason.SIGNATURE_VERIFICATION_FAILED,\n licenseId,\n };\n }\n}\n\nexport function generateLicenseLink({\n requestUrl,\n}: {\n requestUrl: string;\n}): string {\n const baseURL = new URL(requestUrl);\n return `${baseURL.protocol}//${baseURL.host}/license.xml`;\n}\n\n/**\n * Build a HandlerResult that signals a missing token in soft enforcement mode.\n * Returns headers indicating a license is required without blocking the request.\n */\nexport function buildSignalResult(requestUrl: string): HandlerResult {\n const licenseLink = generateLicenseLink({ requestUrl });\n return {\n action: HandlerAction.ALLOW,\n headers: {\n Link: `<${licenseLink}>; rel=\"license\"; type=\"application/rsl+xml\"`,\n \"X-RSL-Status\": \"token_required\",\n \"X-RSL-Reason\": \"missing\",\n },\n };\n}\nexport function buildBlockResult({\n reason,\n requestUrl,\n supertabBaseUrl,\n}: {\n reason: LicenseTokenInvalidReason | string;\n requestUrl: string;\n supertabBaseUrl: string;\n}): HandlerResult {\n let rslError: string;\n let errorDescription: string;\n let status: number;\n\n switch (reason) {\n // 401 — invalid_request: missing or malformed request\n case LicenseTokenInvalidReason.MISSING_TOKEN:\n status = 401;\n rslError = \"invalid_request\";\n errorDescription = \"Authorization header missing or malformed\";\n break;\n case LicenseTokenInvalidReason.INVALID_ALG:\n status = 401;\n rslError = \"invalid_request\";\n errorDescription = \"Unsupported token algorithm\";\n break;\n\n // 401 — invalid_token: token exists but is bad\n case LicenseTokenInvalidReason.EXPIRED:\n status = 401;\n rslError = \"invalid_token\";\n errorDescription = \"The license token has expired\";\n break;\n case LicenseTokenInvalidReason.SIGNATURE_VERIFICATION_FAILED:\n status = 401;\n rslError = \"invalid_token\";\n errorDescription = \"The license token signature is invalid\";\n break;\n case LicenseTokenInvalidReason.INVALID_HEADER:\n status = 401;\n rslError = \"invalid_token\";\n errorDescription = \"The license token header is malformed\";\n break;\n case LicenseTokenInvalidReason.INVALID_PAYLOAD:\n status = 401;\n rslError = \"invalid_token\";\n errorDescription = \"The license token payload is malformed\";\n break;\n case LicenseTokenInvalidReason.INVALID_ISSUER:\n status = 401;\n rslError = \"invalid_token\";\n errorDescription = \"The license token issuer is not recognized\";\n break;\n // 403 — insufficient_scope: valid token, wrong resource/usage\n case LicenseTokenInvalidReason.INVALID_AUDIENCE:\n status = 403;\n rslError = \"insufficient_scope\";\n errorDescription = \"The license does not grant access to this resource\";\n break;\n // 503 — server-side validation failure\n case LicenseTokenInvalidReason.SERVER_ERROR:\n status = 503;\n rslError = \"server_error\";\n errorDescription = \"The server encountered an error validating the license\";\n break;\n\n default:\n status = 401;\n rslError = \"invalid_token\";\n errorDescription = \"License token missing, expired, revoked, or malformed\";\n }\n\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} - ${errorDescription}`,\n headers: {\n \"Content-Type\": \"text/plain; charset=UTF-8\",\n \"WWW-Authenticate\": `License error=\"${rslError}\", error_description=\"${errorDescription}\"`,\n Link: `<${licenseLink}>; rel=\"license\"; type=\"application/rsl+xml\"`,\n },\n };\n}\n\nfunction buildFetchOptions(): FetchOptions {\n let options: FetchOptions = { method: \"GET\" };\n // @ts-ignore - backend is a Fastly-specific extension\n if (globalThis?.fastly) {\n options = { ...options, backend: FASTLY_BACKEND };\n }\n return options;\n}\n\nexport async function hostRSLicenseXML(\n supertabBaseUrl: string,\n merchantSystemUrn: string\n): Promise<Response> {\n const licenseUrl = `${supertabBaseUrl}/merchants/systems/${merchantSystemUrn}/license.xml`;\n const response = await fetch(licenseUrl, buildFetchOptions());\n\n if (!response.ok) {\n return new Response(\"License not found\", { status: 404 });\n }\n\n const licenseXml = await response.text();\n\n return new Response(licenseXml, {\n status: 200,\n headers: new Headers({ \"Content-Type\": \"application/xml\" }),\n });\n}\n\nexport type ValidateTokenParams = {\n token: string;\n url: string;\n userAgent: string;\n supertabBaseUrl: string;\n debug: boolean;\n recordEvent?: EventRecorder;\n ctx?: any;\n};\n\nexport async function validateTokenAndBuildResult(\n params: ValidateTokenParams\n): Promise<HandlerResult> {\n const verification = await verifyLicenseToken({\n licenseToken: params.token,\n requestUrl: params.url,\n supertabBaseUrl: params.supertabBaseUrl,\n debug: params.debug,\n });\n\n if (params.recordEvent) {\n const eventName = verification.valid\n ? \"license_used\"\n : verification.reason;\n\n const eventProperties = {\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\n const eventPromise = params.recordEvent(\n eventName,\n eventProperties,\n verification.licenseId\n );\n\n if (params.ctx?.waitUntil) {\n params.ctx.waitUntil(eventPromise);\n }\n }\n\n if (!verification.valid) {\n return buildBlockResult({\n reason: verification.reason,\n requestUrl: params.url,\n supertabBaseUrl: params.supertabBaseUrl,\n });\n }\n\n return { action: HandlerAction.ALLOW };\n}\n","import { HandlerAction, HandlerResult } 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?: any): Promise<HandlerResult>;\n}\n\nexport async function handleCloudflareRequest(\n handler: RequestHandler,\n request: Request,\n ctx: any\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","/**\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 userAgent.toLowerCase().includes(\"headless\") ||\n userAgent.toLowerCase().includes(\"puppeteer\") ||\n !secChUa;\n\n const isBrowserMissingSecChUa =\n !userAgent.toLowerCase().includes(\"headless\") &&\n !userAgent.toLowerCase().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 EventPayload,\n FASTLY_BACKEND,\n LicenseTokenInvalidReason,\n LicenseTokenVerificationResult,\n Env,\n} from \"./types\";\nimport { obtainLicenseToken as obtainLicenseTokenHelper } from \"./customer\";\nimport {\n buildBlockResult,\n buildSignalResult,\n verifyLicenseToken as verifyLicenseTokenHelper,\n validateTokenAndBuildResult,\n} from \"./license\";\nimport { handleCloudflareRequest, handleFastlyRequest } from \"./cdn\";\n\nexport { EnforcementMode, HandlerAction };\nexport type { Env, BotDetector, HandlerResult };\nexport { defaultBotDetector } from \"./bots\";\n\n/**\n * SupertabConnect class provides higher level methods\n * for using Supertab Connect within supported CDN integrations\n * as well as more specialized methods to customarily verify JWT tokens and record events.\n */\nexport class SupertabConnect {\n private apiKey?: string;\n private static baseUrl: string = \"https://api-connect.supertab.co\";\n private merchantSystemUrn!: string;\n private enforcement!: EnforcementMode;\n private botDetector?: BotDetector;\n private debug!: boolean;\n\n private static _instance: SupertabConnect | null = null;\n\n public constructor(config: SupertabConnectConfig, reset: boolean = false) {\n if (!reset && SupertabConnect._instance) {\n // If reset was not requested and an instance conflicts with the provided config, throw an error\n if (\n !(\n config.apiKey === SupertabConnect._instance.apiKey &&\n config.merchantSystemUrn ===\n SupertabConnect._instance.merchantSystemUrn\n )\n ) {\n throw new Error(\n \"Cannot create a new instance with different configuration. Use resetInstance to clear the existing instance.\"\n );\n }\n\n // If an instance already exists and reset is not requested, just return the existing instance\n return SupertabConnect._instance;\n }\n if (reset && SupertabConnect._instance) {\n // ...and if reset is requested and required, clear the existing instance first\n SupertabConnect.resetInstance();\n }\n\n if (!config.apiKey || !config.merchantSystemUrn) {\n throw new Error(\n \"Missing required configuration: apiKey and merchantSystemUrn are required\"\n );\n }\n this.apiKey = config.apiKey;\n this.merchantSystemUrn = config.merchantSystemUrn;\n this.enforcement = config.enforcement ?? EnforcementMode.SOFT;\n this.botDetector = config.botDetector;\n this.debug = config.debug ?? false;\n\n // Register this as the singleton instance\n SupertabConnect._instance = this;\n }\n\n 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 * Verify a license token\n * @param licenseToken The license token to verify\n * @param requestUrl The URL of the request being made\n * @returns A promise that resolves with the verification result\n */\n async verifyLicenseToken(\n licenseToken: string,\n requestUrl: string\n ): Promise<LicenseTokenVerificationResult> {\n return verifyLicenseTokenHelper({\n licenseToken,\n requestUrl,\n supertabBaseUrl: SupertabConnect.baseUrl,\n debug: this.debug,\n });\n }\n\n /**\n * Records an analytics event\n * @param eventName Name of the event to record\n * @param properties Additional properties to include with the event\n * @param licenseId Optional license ID associated with the event\n * @returns Promise that resolves when the event is recorded\n */\n async recordEvent(\n eventName: string,\n properties: Record<string, any> = {},\n licenseId?: string\n ): Promise<void> {\n const payload: EventPayload = {\n event_name: eventName,\n merchant_system_urn: this.merchantSystemUrn ? this.merchantSystemUrn : \"\",\n license_id: licenseId,\n properties,\n };\n\n try {\n let options: any = {\n method: \"POST\",\n headers: {\n Authorization: `Bearer ${this.apiKey}`,\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(payload),\n };\n // @ts-ignore\n if (globalThis?.fastly) {\n options = { ...options, backend: FASTLY_BACKEND };\n }\n const response = await fetch(\n `${SupertabConnect.baseUrl}/events`,\n options\n );\n\n if (!response.ok) {\n console.log(`Failed to record event: ${response.status}`);\n }\n } catch (error) {\n console.log(\"Error recording event:\", error);\n }\n }\n\n async handleRequest(request: Request, ctx?: any): 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 return validateTokenAndBuildResult({\n token,\n url,\n userAgent,\n supertabBaseUrl: SupertabConnect.baseUrl,\n debug: this.debug,\n recordEvent: this.recordEvent.bind(this),\n ctx,\n });\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 requestUrl: url,\n supertabBaseUrl: SupertabConnect.baseUrl,\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 * Automatically fetches and parses license.xml from the resource URL's origin,\n * using the token endpoint specified in the matching content element's server attribute.\n * @param clientId OAuth client identifier.\n * @param clientSecret OAuth client secret for client_credentials flow.\n * @param resourceUrl Resource URL attempting to access with a License.\n * @param debug Enable debug logging (default: false).\n * @returns Promise resolving to the issued license access token string.\n */\n static async obtainLicenseToken(\n clientId: string,\n clientSecret: string,\n resourceUrl: string,\n debug: boolean = false\n ): Promise<string> {\n return obtainLicenseTokenHelper({\n clientId,\n clientSecret,\n resourceUrl,\n debug,\n });\n }\n\n /**\n * Handle incoming requests for Cloudflare Workers.\n */\n static async cloudflareHandleRequests(\n request: Request,\n env: Env,\n ctx: any\n ): Promise<Response> {\n const instance = new SupertabConnect({\n apiKey: env.MERCHANT_API_KEY,\n merchantSystemUrn: env.MERCHANT_SYSTEM_URN,\n });\n return handleCloudflareRequest(instance, request, ctx);\n }\n\n /**\n * Handle incoming requests for Fastly Compute.\n */\n static async fastlyHandleRequests(\n request: Request,\n merchantSystemUrn: string,\n merchantApiKey: string,\n originBackend: string,\n options?: {\n enableRSL?: boolean;\n botDetector?: BotDetector;\n enforcement?: EnforcementMode;\n }\n ): Promise<Response> {\n const { enableRSL = false, botDetector, enforcement } = options ?? {};\n\n const instance = new SupertabConnect({\n apiKey: merchantApiKey,\n merchantSystemUrn: merchantSystemUrn,\n botDetector,\n enforcement,\n });\n\n return handleFastlyRequest(\n instance,\n request,\n originBackend,\n enableRSL\n ? {\n baseUrl: SupertabConnect.baseUrl,\n merchantSystemUrn,\n }\n : undefined\n );\n }\n}\n"],"mappings":"AAAO,IAAKA,OACVA,EAAA,SAAW,WACXA,EAAA,KAAO,OACPA,EAAA,OAAS,SAHCA,OAAA,IAmDL,IAAMC,EAAiB,cAOlBC,OACVA,EAAA,MAAQ,QACRA,EAAA,MAAQ,QAFEA,OAAA,ICxDZ,IAAIC,EAAgD,KAK7C,SAASC,GAAgC,CAC9C,OAAKD,IACHA,EAAoB,OAAO,MAAM,GAE5BA,CACT,CCeA,eAAeE,EACXC,EACAC,EACAC,EACF,CACA,GAAI,CACF,IAAMC,EAAW,MAAM,MAAMH,EAAeC,CAAc,EAE1D,GAAI,CAACE,EAAS,GAAI,CAChB,IAAMC,EAAY,MAAMD,EAAS,KAAK,EAAE,MAAM,IAAM,EAAE,EAChDE,EAAe,mCACnBF,EAAS,MACX,IAAIA,EAAS,UAAU,GAAGC,EAAY,MAAMA,CAAS,GAAK,EAAE,GA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AoC,KAR9C,IAAMsC,EAANtC","names":["EnforcementMode","FASTLY_BACKEND","HandlerAction","joseModulePromise","loadJose","retrieveLicenseToken","tokenEndpoint","requestOptions","debug","response","errorBody","errorMessage","data","parseError","error","fetchLicenseXml","resourceUrl","debug","licenseXmlUrl","response","xml","parseContentElements","contentBlocks","contentRegex","urlRegex","serverRegex","licenseRegex","elementCount","match","attrs","body","urlMatch","serverMatch","licenseMatch","missing","findBestMatchingContent","parsed","host","path","bestMatch","bestSpecificity","block","patternUrl","patternPath","prefix","specificity","obtainLicenseToken","clientId","clientSecret","resourceUrl","debug","xml","fetchLicenseXml","contentBlocks","parseContentElements","matchedContent","findBestMatchingContent","patterns","b","tokenEndpoint","payload","requestOptions","retrieveLicenseToken","jwksCache","buildFetchOptions","options","FASTLY_BACKEND","fetchAndCacheJwks","cacheKey","url","debug","failureMessage","logLabel","response","jwksData","error","fetchPlatformJwks","baseUrl","jwksUrl","stripTrailingSlash","value","verifyLicenseToken","licenseToken","requestUrl","supertabBaseUrl","debug","decodeProtectedHeader","decodeJwt","jwtVerify","loadJose","header","error","payload","licenseId","issuer","normalizedIssuer","normalizedBaseUrl","audienceValues","entry","requestUrlNormalized","normalizedAudience","jwks","fetchPlatformJwks","result","jwtHeader","jwk","key","generateLicenseLink","baseURL","buildSignalResult","licenseLink","buildBlockResult","reason","rslError","errorDescription","status","buildFetchOptions","options","FASTLY_BACKEND","hostRSLicenseXML","merchantSystemUrn","licenseUrl","response","licenseXml","validateTokenAndBuildResult","params","verification","eventName","eventProperties","eventPromise","handleCloudflareRequest","handler","request","ctx","result","originResponse","response","key","value","handleFastlyRequest","originBackend","rslOptions","hostRSLicenseXML","defaultBotDetector","request","userAgent","accept","secChUa","acceptLanguage","botScore","botList","lowerCaseUserAgent","botUaMatch","bot","headlessIndicators","isBrowserMissingSecChUa","missingHeaders","lowBotScore","_SupertabConnect","config","reset","url","licenseToken","requestUrl","verifyLicenseToken","eventName","properties","licenseId","payload","options","FASTLY_BACKEND","response","error","request","ctx","auth","token","userAgent","validateTokenAndBuildResult","buildBlockResult","buildSignalResult","clientId","clientSecret","resourceUrl","debug","obtainLicenseToken","env","instance","handleCloudflareRequest","merchantSystemUrn","merchantApiKey","originBackend","enableRSL","botDetector","enforcement","handleFastlyRequest","SupertabConnect"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@getsupertab/supertab-connect-sdk",
|
|
3
|
-
"version": "0.1.0-beta.
|
|
3
|
+
"version": "0.1.0-beta.33",
|
|
4
4
|
"description": "Supertab Connect SDK (beta)",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.cjs",
|
|
@@ -25,7 +25,8 @@
|
|
|
25
25
|
"prepublishOnly": "npm run build",
|
|
26
26
|
"scripts": {
|
|
27
27
|
"build": "tsup",
|
|
28
|
-
"dev": "tsup --watch"
|
|
28
|
+
"dev": "tsup --watch",
|
|
29
|
+
"test": "vitest run"
|
|
29
30
|
},
|
|
30
31
|
"keywords": [
|
|
31
32
|
"supertab",
|
|
@@ -37,7 +38,8 @@
|
|
|
37
38
|
"devDependencies": {
|
|
38
39
|
"@types/node": "^18.0.0",
|
|
39
40
|
"tsup": "^8.5.0",
|
|
40
|
-
"typescript": "^5.0.0"
|
|
41
|
+
"typescript": "^5.0.0",
|
|
42
|
+
"vitest": "^3.2.4"
|
|
41
43
|
},
|
|
42
44
|
"dependencies": {
|
|
43
45
|
"jose": "^6.0.11"
|