@obfious/js 0.1.12 → 0.1.14

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/express.js CHANGED
@@ -1 +1 @@
1
- var R="x-obfious-key",x="x-obfious-sig",P="x-obfious-ts",C=/\.(json|js|gif|png|woff2|css)$/;var p=class{config;creds;randomValue=null;randomValueCreatedAt=0;constructor(e){this.config={...e,apiUrl:e.apiUrl??"https://api.obfious.com"},this.creds={keyId:e.keyId,secret:e.secret}}async getScriptUrl(){if(this.config.scriptPath)return this.config.scriptPath;let e=await y(this.creds.secret);return this.ensureRandomValue(),`/?${e}=${this.randomValue}`}async getWorkerUrl(){let e=await m(this.creds.secret);return this.ensureRandomValue(),`/?${e}=${this.randomValue}`}async scriptTag(e){let t=await this.getScriptUrl(),r=e?.nonce?` nonce="${e.nonce}"`:"";return`<script src="${t}"${r}></script>`}async protect(e,t){let r=new URL(e.url);if(e.method==="GET"){if(r.pathname==="/")for(let[l]of r.searchParams){if(await T(this.creds.secret,l)){let d=await this.fetchBundle();return{response:new Response(d??'console.error("[obfious] Failed to load bundle from API");',{headers:{"Content-Type":"application/javascript","Cache-Control":d?"private, max-age=300":"no-store"}})}}if(await A(this.creds.secret,l)){let d=await this.fetchWorker();return{response:new Response(d??'console.error("[obfious] Failed to load worker from API");',{headers:{"Content-Type":"application/javascript","Cache-Control":d?"private, max-age=300":"no-store"}})}}}if(this.config.scriptPath&&r.pathname===this.config.scriptPath){let l=await this.fetchBundle();if(l)return{response:new Response(l,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store"}})}}}if(e.method==="POST"&&C.test(r.pathname)){if((e.headers.get("Content-Type")||"")==="application/octet-stream")return{response:await this.forwardStreamToApi(e,r.pathname)};let d=e.clone(),h=new Uint8Array(await d.arrayBuffer());if(h.length>0&&h[0]===91)return{response:await this.forwardToApi(e,r.pathname,h)}}if(this.config.excludePaths?.some(l=>r.pathname.startsWith(l)))return{response:null};if(this.config.includePaths&&!this.config.includePaths.some(l=>r.pathname.startsWith(l)))return{response:null};let n=e.headers.get("x-req-auth");if(!n)return{response:new Response(null,{status:401})};let o=n.indexOf(".");if(o<1)return{response:new Response(null,{status:401})};let i=n.slice(0,o),a=n.slice(o+1),c=S(i);if(!c)return{response:new Response(null,{status:401})};let g=t&&this.config.privateKey?await I(t,this.config.privateKey):void 0,u=await this.validateToken(c,i,a,g);return u.valid?{response:null,deviceId:u.deviceId}:{response:new Response(null,{status:401})}}ensureRandomValue(){(!this.randomValue||Date.now()-this.randomValueCreatedAt>9e5)&&(this.randomValue=O(8),this.randomValueCreatedAt=Date.now())}getIp(e){return this.config.getClientIp?this.config.getClientIp(e):e.headers.get("CF-Connecting-IP")||e.headers.get("X-Forwarded-For")?.split(",")[0]?.trim()||e.headers.get("X-Real-IP")||"unknown"}async fetchBundle(){try{let e=await this.getWorkerUrl(),t=await this.authedFetch("/b",{method:"GET",headers:{"x-obfious-worker-url":e}});return t.ok?await t.text():(console.error(`[obfious] Bundle fetch failed: ${t.status} ${t.statusText}`),null)}catch(e){return console.error("[obfious] Bundle fetch error:",e),null}}async fetchWorker(){try{let e=await this.authedFetch("/w",{method:"GET"});return e.ok?await e.text():(console.error(`[obfious] Worker fetch failed: ${e.status} ${e.statusText}`),null)}catch(e){return console.error("[obfious] Worker fetch error:",e),null}}async forwardToApi(e,t,r){let n={"Content-Type":"application/json","x-obfious-ip":this.getIp(e)};if(this.config.getPlatformSignals)for(let[o,i]of Object.entries(this.config.getPlatformSignals(e)))n[o.replace(/[\r\n]/g,"")]=String(i).replace(/[\r\n]/g,"");return this.authedFetch(t,{method:"POST",headers:n,body:r.buffer})}async forwardStreamToApi(e,t){let r={"Content-Type":"application/octet-stream","x-obfious-ip":this.getIp(e)};if(this.config.getPlatformSignals)for(let[n,o]of Object.entries(this.config.getPlatformSignals(e)))r[n.replace(/[\r\n]/g,"")]=String(o).replace(/[\r\n]/g,"");return this.authedFetch(t,{method:"POST",headers:r,body:e.body??void 0})}async validateToken(e,t,r,n){try{let o={tokenHex:e,signature:r,payload:t};n&&(o.encryptedUser=n);let i=await this.authedFetch("/validate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)});if(!i.ok)return{valid:!1};let a=await i.json();return{valid:a.valid===!0,deviceId:a.deviceId}}catch{return{valid:!1}}}async authedFetch(e,t){let r=`${this.config.apiUrl}${e}`,n=Date.now().toString(),o=(t.method||"GET").toUpperCase(),i=`${n}.${o}.${e}`,a=await k(this.creds.secret,i),c=new Headers(t.headers);return c.set(R,this.creds.keyId),c.set(x,a),c.set(P,n),fetch(r,{...t,headers:c})}};async function y(s,e=0){let t=Math.floor(Date.now()/3e5)+e,r=await crypto.subtle.importKey("raw",new TextEncoder().encode(s),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),n=await crypto.subtle.sign("HMAC",r,new TextEncoder().encode("obfious-bootstrap-v1:"+t));return f(new Uint8Array(n)).slice(0,10)}async function T(s,e){if(e.length!==10||!/^[0-9a-f]{10}$/.test(e))return!1;for(let t of[-1,0,1])if(await y(s,t)===e)return!0;return!1}async function m(s,e=0){let t=Math.floor(Date.now()/3e5)+e,r=t%7+1,n=await crypto.subtle.importKey("raw",new TextEncoder().encode(s),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),o=await crypto.subtle.sign("HMAC",n,new TextEncoder().encode("obfious-worker-v1:"+t)),i=f(new Uint8Array(o)).slice(0,9);return i.slice(0,r)+"w"+i.slice(r)}async function A(s,e){if(e.length!==10)return!1;let t=e.indexOf("w");if(t<1||t>7||e.lastIndexOf("w")!==t)return!1;let r=e.slice(0,t)+e.slice(t+1);if(!/^[0-9a-f]{9}$/.test(r))return!1;for(let n of[-1,0,1])if(await m(s,n)===e)return!0;return!1}function f(s){return Array.from(s,e=>e.toString(16).padStart(2,"0")).join("")}async function k(s,e){let t=await crypto.subtle.importKey("raw",new TextEncoder().encode(s),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),r=await crypto.subtle.sign("HMAC",t,new TextEncoder().encode(e));return f(new Uint8Array(r))}async function I(s,e){let t=await crypto.subtle.importKey("raw",new TextEncoder().encode(e),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),r=await crypto.subtle.sign("HMAC",t,new TextEncoder().encode(s));return f(new Uint8Array(r))}function S(s){try{let e=s.replace(/-/g,"+").replace(/_/g,"/");for(;e.length%4;)e+="=";let t=Uint8Array.from(atob(e),r=>r.charCodeAt(0));return t.length<9||t[0]!==33?null:f(t.slice(1,9))}catch{return null}}function O(s){let e="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",t=crypto.getRandomValues(new Uint8Array(s));return Array.from(t,r=>e[r%e.length]).join("")}import{Readable as w}from"node:stream";function b(s){let e=s.headers["x-forwarded-proto"]||"http",t=s.headers.host||"localhost",r=`${e}://${t}${s.url}`,n=new Headers;for(let[i,a]of Object.entries(s.headers))a&&n.set(i,Array.isArray(a)?a.join(", "):a);let o=s.method!=="GET"&&s.method!=="HEAD";return new Request(r,{method:s.method,headers:n,body:o?w.toWeb(w.from(s)):null,duplex:"half"})}async function v(s,e){let t={};if(e.headers.forEach((r,n)=>{t[n]=r}),s.writeHead(e.status,t),e.body){let r=e.body.getReader();try{for(;;){let{done:n,value:o}=await r.read();if(n)break;s.write(o)}}finally{r.releaseLock()}}s.end()}function V(s){let{creds:e,getUser:t,...r}=s,n=new p({...r,keyId:e.keyId,secret:e.secret,getClientIp:r.getClientIp??(o=>o.headers.get("x-forwarded-for")?.split(",")[0]?.trim()||o.headers.get("x-real-ip")||"unknown"),getPlatformSignals:r.getPlatformSignals??(()=>({}))});return async(o,i,a)=>{try{let c=b(o),g=t?.(o),u=await n.protect(c,g);if(u.response){await v(i,u.response);return}u.deviceId&&(o.obfiousDeviceId=u.deviceId),a()}catch(c){a(c)}}}export{p as Obfious,V as obfiousMiddleware};
1
+ var b="x-obfious-key",v="x-obfious-sig",R="x-obfious-ts",x=/\.(json|js|gif|png|woff2|css)$/;var f=class{config;creds;randomValue=null;randomValueCreatedAt=0;constructor(e){this.config={...e,apiUrl:e.apiUrl??"https://api.obfious.com"},this.creds={keyId:e.keyId,secret:e.secret}}async getScriptUrl(){if(this.config.scriptPath)return this.config.scriptPath;let e=await h(this.creds.secret);return this.ensureRandomValue(),`/?${e}=${this.randomValue}`}async scriptTag(e){let r=await this.getScriptUrl(),t=e?.nonce?` nonce="${e.nonce}"`:"";return`<script src="${r}"${t}></script>`}async protect(e,r){let t=new URL(e.url);if(e.method==="GET"){if(t.pathname==="/"){for(let[d]of t.searchParams)if(await C(this.creds.secret,d)){let u=await this.fetchBundle();return{response:new Response(u??`console.error("[obfious] Failed to load bundle: ${this.lastFetchError}");`,{headers:{"Content-Type":"application/javascript","Cache-Control":u?"private, max-age=300":"no-store"}})}}}if(this.config.scriptPath&&t.pathname===this.config.scriptPath){let d=await this.fetchBundle();if(d)return{response:new Response(d,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store"}})}}}if(e.method==="POST"&&x.test(t.pathname)){let d=e.clone(),u=new Uint8Array(await d.arrayBuffer());if(u.length>0&&u[0]===91)return{response:await this.forwardToApi(e,t.pathname,u)}}if(this.config.excludePaths?.some(d=>t.pathname.startsWith(d)))return{response:null};if(this.config.includePaths&&!this.config.includePaths.some(d=>t.pathname.startsWith(d)))return{response:null};let o=e.headers.get("x-req-auth");if(!o)return{response:new Response(null,{status:401})};let n=o.indexOf(".");if(n<1)return{response:new Response(null,{status:401})};let a=o.slice(0,n),i=o.slice(n+1),c=I(a);if(!c)return{response:new Response(null,{status:401})};let g=r&&this.config.privateKey?await P(r,this.config.privateKey):void 0,l=await this.validateToken(c,a,i,g);return l.valid?{response:null,deviceId:l.deviceId}:{response:new Response(null,{status:401})}}ensureRandomValue(){(!this.randomValue||Date.now()-this.randomValueCreatedAt>9e5)&&(this.randomValue=T(8),this.randomValueCreatedAt=Date.now())}getIp(e){return this.config.getClientIp?this.config.getClientIp(e):e.headers.get("CF-Connecting-IP")||e.headers.get("X-Forwarded-For")?.split(",")[0]?.trim()||e.headers.get("X-Real-IP")||"unknown"}lastFetchError="";async fetchBundle(){try{let e=await this.authedFetch("/b",{method:"GET"});return e.ok?await e.text():(this.lastFetchError=`API returned ${e.status}`,console.error(`[obfious] Bundle fetch failed: ${e.status} ${e.statusText}`),null)}catch(e){return this.lastFetchError=`${e}`,console.error("[obfious] Bundle fetch error:",e),null}}async forwardToApi(e,r,t){let o={"Content-Type":"application/json","x-obfious-ip":this.getIp(e)};if(this.config.getPlatformSignals)for(let[a,i]of Object.entries(this.config.getPlatformSignals(e)))o[a.replace(/[\r\n]/g,"")]=String(i).replace(/[\r\n]/g,"");let n=await this.authedFetch(r,{method:"POST",headers:o,body:t.buffer});if(!n.ok){let a=await n.clone().text().catch(()=>"");console.error(`[obfious] forwardToApi ${r}: ${n.status} ${a}`)}return n}async validateToken(e,r,t,o){try{let n={tokenHex:e,signature:t,payload:r};o&&(n.encryptedUser=o);let a=await this.authedFetch("/validate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!a.ok){let c=await a.text().catch(()=>"");return console.error(`[obfious] Validate failed: ${a.status} ${c}`),{valid:!1}}let i=await a.json();return i.valid!==!0&&console.error(`[obfious] Validate rejected: ${JSON.stringify(i)}`),{valid:i.valid===!0,deviceId:i.deviceId}}catch(n){return console.error("[obfious] Validate error:",n),{valid:!1}}}async authedFetch(e,r){let t=`${this.config.apiUrl}${e}`,o=Date.now().toString(),n=(r.method||"GET").toUpperCase(),a=`${o}.${n}.${e}`,i=await A(this.creds.secret,a),c=new Headers(r.headers);return c.set(b,this.creds.keyId),c.set(v,i),c.set(R,o),fetch(t,{...r,headers:c})}};async function h(s,e=0){let r=Math.floor(Date.now()/3e5)+e,t=await crypto.subtle.importKey("raw",new TextEncoder().encode(s),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),o=await crypto.subtle.sign("HMAC",t,new TextEncoder().encode("obfious-bootstrap-v1:"+r));return p(new Uint8Array(o)).slice(0,10)}async function C(s,e){if(e.length!==10||!/^[0-9a-f]{10}$/.test(e))return!1;for(let r of[-1,0,1])if(await h(s,r)===e)return!0;return!1}function p(s){return Array.from(s,e=>e.toString(16).padStart(2,"0")).join("")}async function A(s,e){let r=await crypto.subtle.importKey("raw",new TextEncoder().encode(s),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),t=await crypto.subtle.sign("HMAC",r,new TextEncoder().encode(e));return p(new Uint8Array(t))}async function P(s,e){let r=await crypto.subtle.importKey("raw",new TextEncoder().encode(e),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),t=await crypto.subtle.sign("HMAC",r,new TextEncoder().encode(s));return p(new Uint8Array(t))}function I(s){try{let e=s.replace(/-/g,"+").replace(/_/g,"/");for(;e.length%4;)e+="=";let r=Uint8Array.from(atob(e),t=>t.charCodeAt(0));return r.length<9||r[0]!==33?null:p(r.slice(1,9))}catch{return null}}function T(s){let e="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",r=crypto.getRandomValues(new Uint8Array(s));return Array.from(r,t=>e[t%e.length]).join("")}import{Readable as y}from"node:stream";function m(s){let e=s.headers["x-forwarded-proto"]||"http",r=s.headers.host||"localhost",t=`${e}://${r}${s.url}`,o=new Headers;for(let[a,i]of Object.entries(s.headers))i&&o.set(a,Array.isArray(i)?i.join(", "):i);let n=s.method!=="GET"&&s.method!=="HEAD";return new Request(t,{method:s.method,headers:o,body:n?y.toWeb(y.from(s)):null,duplex:"half"})}async function w(s,e){let r={};if(e.headers.forEach((t,o)=>{r[o]=t}),s.writeHead(e.status,r),e.body){let t=e.body.getReader();try{for(;;){let{done:o,value:n}=await t.read();if(o)break;s.write(n)}}finally{t.releaseLock()}}s.end()}function U(s){let{creds:e,getUser:r,...t}=s,o=new f({...t,keyId:e.keyId,secret:e.secret,getClientIp:t.getClientIp??(n=>n.headers.get("x-forwarded-for")?.split(",")[0]?.trim()||n.headers.get("x-real-ip")||"unknown"),getPlatformSignals:t.getPlatformSignals??(()=>({}))});return async(n,a,i)=>{try{let c=m(n),g=r?.(n),l=await o.protect(c,g);if(l.response){await w(a,l.response);return}l.deviceId&&(n.obfiousDeviceId=l.deviceId),i()}catch(c){i(c)}}}export{f as Obfious,U as obfiousMiddleware};
package/dist/fastify.js CHANGED
@@ -1 +1 @@
1
- var v="x-obfious-key",x="x-obfious-sig",P="x-obfious-ts",C=/\.(json|js|gif|png|woff2|css)$/;var g=class{config;creds;randomValue=null;randomValueCreatedAt=0;constructor(e){this.config={...e,apiUrl:e.apiUrl??"https://api.obfious.com"},this.creds={keyId:e.keyId,secret:e.secret}}async getScriptUrl(){if(this.config.scriptPath)return this.config.scriptPath;let e=await y(this.creds.secret);return this.ensureRandomValue(),`/?${e}=${this.randomValue}`}async getWorkerUrl(){let e=await m(this.creds.secret);return this.ensureRandomValue(),`/?${e}=${this.randomValue}`}async scriptTag(e){let t=await this.getScriptUrl(),r=e?.nonce?` nonce="${e.nonce}"`:"";return`<script src="${t}"${r}></script>`}async protect(e,t){let r=new URL(e.url);if(e.method==="GET"){if(r.pathname==="/")for(let[c]of r.searchParams){if(await T(this.creds.secret,c)){let u=await this.fetchBundle();return{response:new Response(u??'console.error("[obfious] Failed to load bundle from API");',{headers:{"Content-Type":"application/javascript","Cache-Control":u?"private, max-age=300":"no-store"}})}}if(await A(this.creds.secret,c)){let u=await this.fetchWorker();return{response:new Response(u??'console.error("[obfious] Failed to load worker from API");',{headers:{"Content-Type":"application/javascript","Cache-Control":u?"private, max-age=300":"no-store"}})}}}if(this.config.scriptPath&&r.pathname===this.config.scriptPath){let c=await this.fetchBundle();if(c)return{response:new Response(c,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store"}})}}}if(e.method==="POST"&&C.test(r.pathname)){if((e.headers.get("Content-Type")||"")==="application/octet-stream")return{response:await this.forwardStreamToApi(e,r.pathname)};let u=e.clone(),f=new Uint8Array(await u.arrayBuffer());if(f.length>0&&f[0]===91)return{response:await this.forwardToApi(e,r.pathname,f)}}if(this.config.excludePaths?.some(c=>r.pathname.startsWith(c)))return{response:null};if(this.config.includePaths&&!this.config.includePaths.some(c=>r.pathname.startsWith(c)))return{response:null};let n=e.headers.get("x-req-auth");if(!n)return{response:new Response(null,{status:401})};let i=n.indexOf(".");if(i<1)return{response:new Response(null,{status:401})};let o=n.slice(0,i),a=n.slice(i+1),l=S(o);if(!l)return{response:new Response(null,{status:401})};let h=t&&this.config.privateKey?await I(t,this.config.privateKey):void 0,d=await this.validateToken(l,o,a,h);return d.valid?{response:null,deviceId:d.deviceId}:{response:new Response(null,{status:401})}}ensureRandomValue(){(!this.randomValue||Date.now()-this.randomValueCreatedAt>9e5)&&(this.randomValue=O(8),this.randomValueCreatedAt=Date.now())}getIp(e){return this.config.getClientIp?this.config.getClientIp(e):e.headers.get("CF-Connecting-IP")||e.headers.get("X-Forwarded-For")?.split(",")[0]?.trim()||e.headers.get("X-Real-IP")||"unknown"}async fetchBundle(){try{let e=await this.getWorkerUrl(),t=await this.authedFetch("/b",{method:"GET",headers:{"x-obfious-worker-url":e}});return t.ok?await t.text():(console.error(`[obfious] Bundle fetch failed: ${t.status} ${t.statusText}`),null)}catch(e){return console.error("[obfious] Bundle fetch error:",e),null}}async fetchWorker(){try{let e=await this.authedFetch("/w",{method:"GET"});return e.ok?await e.text():(console.error(`[obfious] Worker fetch failed: ${e.status} ${e.statusText}`),null)}catch(e){return console.error("[obfious] Worker fetch error:",e),null}}async forwardToApi(e,t,r){let n={"Content-Type":"application/json","x-obfious-ip":this.getIp(e)};if(this.config.getPlatformSignals)for(let[i,o]of Object.entries(this.config.getPlatformSignals(e)))n[i.replace(/[\r\n]/g,"")]=String(o).replace(/[\r\n]/g,"");return this.authedFetch(t,{method:"POST",headers:n,body:r.buffer})}async forwardStreamToApi(e,t){let r={"Content-Type":"application/octet-stream","x-obfious-ip":this.getIp(e)};if(this.config.getPlatformSignals)for(let[n,i]of Object.entries(this.config.getPlatformSignals(e)))r[n.replace(/[\r\n]/g,"")]=String(i).replace(/[\r\n]/g,"");return this.authedFetch(t,{method:"POST",headers:r,body:e.body??void 0})}async validateToken(e,t,r,n){try{let i={tokenHex:e,signature:r,payload:t};n&&(i.encryptedUser=n);let o=await this.authedFetch("/validate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)});if(!o.ok)return{valid:!1};let a=await o.json();return{valid:a.valid===!0,deviceId:a.deviceId}}catch{return{valid:!1}}}async authedFetch(e,t){let r=`${this.config.apiUrl}${e}`,n=Date.now().toString(),i=(t.method||"GET").toUpperCase(),o=`${n}.${i}.${e}`,a=await k(this.creds.secret,o),l=new Headers(t.headers);return l.set(v,this.creds.keyId),l.set(x,a),l.set(P,n),fetch(r,{...t,headers:l})}};async function y(s,e=0){let t=Math.floor(Date.now()/3e5)+e,r=await crypto.subtle.importKey("raw",new TextEncoder().encode(s),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),n=await crypto.subtle.sign("HMAC",r,new TextEncoder().encode("obfious-bootstrap-v1:"+t));return p(new Uint8Array(n)).slice(0,10)}async function T(s,e){if(e.length!==10||!/^[0-9a-f]{10}$/.test(e))return!1;for(let t of[-1,0,1])if(await y(s,t)===e)return!0;return!1}async function m(s,e=0){let t=Math.floor(Date.now()/3e5)+e,r=t%7+1,n=await crypto.subtle.importKey("raw",new TextEncoder().encode(s),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),i=await crypto.subtle.sign("HMAC",n,new TextEncoder().encode("obfious-worker-v1:"+t)),o=p(new Uint8Array(i)).slice(0,9);return o.slice(0,r)+"w"+o.slice(r)}async function A(s,e){if(e.length!==10)return!1;let t=e.indexOf("w");if(t<1||t>7||e.lastIndexOf("w")!==t)return!1;let r=e.slice(0,t)+e.slice(t+1);if(!/^[0-9a-f]{9}$/.test(r))return!1;for(let n of[-1,0,1])if(await m(s,n)===e)return!0;return!1}function p(s){return Array.from(s,e=>e.toString(16).padStart(2,"0")).join("")}async function k(s,e){let t=await crypto.subtle.importKey("raw",new TextEncoder().encode(s),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),r=await crypto.subtle.sign("HMAC",t,new TextEncoder().encode(e));return p(new Uint8Array(r))}async function I(s,e){let t=await crypto.subtle.importKey("raw",new TextEncoder().encode(e),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),r=await crypto.subtle.sign("HMAC",t,new TextEncoder().encode(s));return p(new Uint8Array(r))}function S(s){try{let e=s.replace(/-/g,"+").replace(/_/g,"/");for(;e.length%4;)e+="=";let t=Uint8Array.from(atob(e),r=>r.charCodeAt(0));return t.length<9||t[0]!==33?null:p(t.slice(1,9))}catch{return null}}function O(s){let e="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",t=crypto.getRandomValues(new Uint8Array(s));return Array.from(t,r=>e[r%e.length]).join("")}import{Readable as w}from"node:stream";function b(s){let e=s.headers["x-forwarded-proto"]||"http",t=s.headers.host||"localhost",r=`${e}://${t}${s.url}`,n=new Headers;for(let[o,a]of Object.entries(s.headers))a&&n.set(o,Array.isArray(a)?a.join(", "):a);let i=s.method!=="GET"&&s.method!=="HEAD";return new Request(r,{method:s.method,headers:n,body:i?w.toWeb(w.from(s)):null,duplex:"half"})}async function V(s,e){let{creds:t,getUser:r,...n}=e,i=new g({...n,keyId:t.keyId,secret:t.secret,getClientIp:n.getClientIp??(o=>o.headers.get("x-forwarded-for")?.split(",")[0]?.trim()||o.headers.get("x-real-ip")||"unknown"),getPlatformSignals:n.getPlatformSignals??(()=>({}))});s.addHook("onRequest",async(o,a)=>{let l=b(o.raw),h=r?.(o.raw),d=await i.protect(l,h);if(d.response){let c={};d.response.headers.forEach((f,R)=>{c[R]=f});let u=await d.response.text();a.code(d.response.status).headers(c).send(u);return}d.deviceId&&(o.obfiousDeviceId=d.deviceId)})}export{g as Obfious,V as obfiousPlugin};
1
+ var R="x-obfious-key",v="x-obfious-sig",x="x-obfious-ts",P=/\.(json|js|gif|png|woff2|css)$/;var f=class{config;creds;randomValue=null;randomValueCreatedAt=0;constructor(e){this.config={...e,apiUrl:e.apiUrl??"https://api.obfious.com"},this.creds={keyId:e.keyId,secret:e.secret}}async getScriptUrl(){if(this.config.scriptPath)return this.config.scriptPath;let e=await h(this.creds.secret);return this.ensureRandomValue(),`/?${e}=${this.randomValue}`}async scriptTag(e){let t=await this.getScriptUrl(),r=e?.nonce?` nonce="${e.nonce}"`:"";return`<script src="${t}"${r}></script>`}async protect(e,t){let r=new URL(e.url);if(e.method==="GET"){if(r.pathname==="/"){for(let[c]of r.searchParams)if(await C(this.creds.secret,c)){let u=await this.fetchBundle();return{response:new Response(u??`console.error("[obfious] Failed to load bundle: ${this.lastFetchError}");`,{headers:{"Content-Type":"application/javascript","Cache-Control":u?"private, max-age=300":"no-store"}})}}}if(this.config.scriptPath&&r.pathname===this.config.scriptPath){let c=await this.fetchBundle();if(c)return{response:new Response(c,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store"}})}}}if(e.method==="POST"&&P.test(r.pathname)){let c=e.clone(),u=new Uint8Array(await c.arrayBuffer());if(u.length>0&&u[0]===91)return{response:await this.forwardToApi(e,r.pathname,u)}}if(this.config.excludePaths?.some(c=>r.pathname.startsWith(c)))return{response:null};if(this.config.includePaths&&!this.config.includePaths.some(c=>r.pathname.startsWith(c)))return{response:null};let n=e.headers.get("x-req-auth");if(!n)return{response:new Response(null,{status:401})};let i=n.indexOf(".");if(i<1)return{response:new Response(null,{status:401})};let o=n.slice(0,i),a=n.slice(i+1),d=I(o);if(!d)return{response:new Response(null,{status:401})};let g=t&&this.config.privateKey?await T(t,this.config.privateKey):void 0,l=await this.validateToken(d,o,a,g);return l.valid?{response:null,deviceId:l.deviceId}:{response:new Response(null,{status:401})}}ensureRandomValue(){(!this.randomValue||Date.now()-this.randomValueCreatedAt>9e5)&&(this.randomValue=k(8),this.randomValueCreatedAt=Date.now())}getIp(e){return this.config.getClientIp?this.config.getClientIp(e):e.headers.get("CF-Connecting-IP")||e.headers.get("X-Forwarded-For")?.split(",")[0]?.trim()||e.headers.get("X-Real-IP")||"unknown"}lastFetchError="";async fetchBundle(){try{let e=await this.authedFetch("/b",{method:"GET"});return e.ok?await e.text():(this.lastFetchError=`API returned ${e.status}`,console.error(`[obfious] Bundle fetch failed: ${e.status} ${e.statusText}`),null)}catch(e){return this.lastFetchError=`${e}`,console.error("[obfious] Bundle fetch error:",e),null}}async forwardToApi(e,t,r){let n={"Content-Type":"application/json","x-obfious-ip":this.getIp(e)};if(this.config.getPlatformSignals)for(let[o,a]of Object.entries(this.config.getPlatformSignals(e)))n[o.replace(/[\r\n]/g,"")]=String(a).replace(/[\r\n]/g,"");let i=await this.authedFetch(t,{method:"POST",headers:n,body:r.buffer});if(!i.ok){let o=await i.clone().text().catch(()=>"");console.error(`[obfious] forwardToApi ${t}: ${i.status} ${o}`)}return i}async validateToken(e,t,r,n){try{let i={tokenHex:e,signature:r,payload:t};n&&(i.encryptedUser=n);let o=await this.authedFetch("/validate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)});if(!o.ok){let d=await o.text().catch(()=>"");return console.error(`[obfious] Validate failed: ${o.status} ${d}`),{valid:!1}}let a=await o.json();return a.valid!==!0&&console.error(`[obfious] Validate rejected: ${JSON.stringify(a)}`),{valid:a.valid===!0,deviceId:a.deviceId}}catch(i){return console.error("[obfious] Validate error:",i),{valid:!1}}}async authedFetch(e,t){let r=`${this.config.apiUrl}${e}`,n=Date.now().toString(),i=(t.method||"GET").toUpperCase(),o=`${n}.${i}.${e}`,a=await A(this.creds.secret,o),d=new Headers(t.headers);return d.set(R,this.creds.keyId),d.set(v,a),d.set(x,n),fetch(r,{...t,headers:d})}};async function h(s,e=0){let t=Math.floor(Date.now()/3e5)+e,r=await crypto.subtle.importKey("raw",new TextEncoder().encode(s),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),n=await crypto.subtle.sign("HMAC",r,new TextEncoder().encode("obfious-bootstrap-v1:"+t));return p(new Uint8Array(n)).slice(0,10)}async function C(s,e){if(e.length!==10||!/^[0-9a-f]{10}$/.test(e))return!1;for(let t of[-1,0,1])if(await h(s,t)===e)return!0;return!1}function p(s){return Array.from(s,e=>e.toString(16).padStart(2,"0")).join("")}async function A(s,e){let t=await crypto.subtle.importKey("raw",new TextEncoder().encode(s),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),r=await crypto.subtle.sign("HMAC",t,new TextEncoder().encode(e));return p(new Uint8Array(r))}async function T(s,e){let t=await crypto.subtle.importKey("raw",new TextEncoder().encode(e),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),r=await crypto.subtle.sign("HMAC",t,new TextEncoder().encode(s));return p(new Uint8Array(r))}function I(s){try{let e=s.replace(/-/g,"+").replace(/_/g,"/");for(;e.length%4;)e+="=";let t=Uint8Array.from(atob(e),r=>r.charCodeAt(0));return t.length<9||t[0]!==33?null:p(t.slice(1,9))}catch{return null}}function k(s){let e="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",t=crypto.getRandomValues(new Uint8Array(s));return Array.from(t,r=>e[r%e.length]).join("")}import{Readable as y}from"node:stream";function m(s){let e=s.headers["x-forwarded-proto"]||"http",t=s.headers.host||"localhost",r=`${e}://${t}${s.url}`,n=new Headers;for(let[o,a]of Object.entries(s.headers))a&&n.set(o,Array.isArray(a)?a.join(", "):a);let i=s.method!=="GET"&&s.method!=="HEAD";return new Request(r,{method:s.method,headers:n,body:i?y.toWeb(y.from(s)):null,duplex:"half"})}async function H(s,e){let{creds:t,getUser:r,...n}=e,i=new f({...n,keyId:t.keyId,secret:t.secret,getClientIp:n.getClientIp??(o=>o.headers.get("x-forwarded-for")?.split(",")[0]?.trim()||o.headers.get("x-real-ip")||"unknown"),getPlatformSignals:n.getPlatformSignals??(()=>({}))});s.addHook("onRequest",async(o,a)=>{let d=m(o.raw),g=r?.(o.raw),l=await i.protect(d,g);if(l.response){let c={};l.response.headers.forEach((w,b)=>{c[b]=w});let u=await l.response.text();a.code(l.response.status).headers(c).send(u);return}l.deviceId&&(o.obfiousDeviceId=l.deviceId)})}export{f as Obfious,H as obfiousPlugin};
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- var m="x-obfious-key",b="x-obfious-sig",P="x-obfious-ts",T=/\.(json|js|gif|png|woff2|css)$/;var h=class{config;creds;randomValue=null;randomValueCreatedAt=0;constructor(e){this.config={...e,apiUrl:e.apiUrl??"https://api.obfious.com"},this.creds={keyId:e.keyId,secret:e.secret}}async getScriptUrl(){if(this.config.scriptPath)return this.config.scriptPath;let e=await g(this.creds.secret);return this.ensureRandomValue(),`/?${e}=${this.randomValue}`}async getWorkerUrl(){let e=await y(this.creds.secret);return this.ensureRandomValue(),`/?${e}=${this.randomValue}`}async scriptTag(e){let t=await this.getScriptUrl(),r=e?.nonce?` nonce="${e.nonce}"`:"";return`<script src="${t}"${r}></script>`}async protect(e,t){let r=new URL(e.url);if(e.method==="GET"){if(r.pathname==="/")for(let[a]of r.searchParams){if(await v(this.creds.secret,a)){let l=await this.fetchBundle();return{response:new Response(l??'console.error("[obfious] Failed to load bundle from API");',{headers:{"Content-Type":"application/javascript","Cache-Control":l?"private, max-age=300":"no-store"}})}}if(await x(this.creds.secret,a)){let l=await this.fetchWorker();return{response:new Response(l??'console.error("[obfious] Failed to load worker from API");',{headers:{"Content-Type":"application/javascript","Cache-Control":l?"private, max-age=300":"no-store"}})}}}if(this.config.scriptPath&&r.pathname===this.config.scriptPath){let a=await this.fetchBundle();if(a)return{response:new Response(a,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store"}})}}}if(e.method==="POST"&&T.test(r.pathname)){if((e.headers.get("Content-Type")||"")==="application/octet-stream")return{response:await this.forwardStreamToApi(e,r.pathname)};let l=e.clone(),d=new Uint8Array(await l.arrayBuffer());if(d.length>0&&d[0]===91)return{response:await this.forwardToApi(e,r.pathname,d)}}if(this.config.excludePaths?.some(a=>r.pathname.startsWith(a)))return{response:null};if(this.config.includePaths&&!this.config.includePaths.some(a=>r.pathname.startsWith(a)))return{response:null};let n=e.headers.get("x-req-auth");if(!n)return{response:new Response(null,{status:401})};let o=n.indexOf(".");if(o<1)return{response:new Response(null,{status:401})};let i=n.slice(0,o),u=n.slice(o+1),c=R(i);if(!c)return{response:new Response(null,{status:401})};let w=t&&this.config.privateKey?await C(t,this.config.privateKey):void 0,p=await this.validateToken(c,i,u,w);return p.valid?{response:null,deviceId:p.deviceId}:{response:new Response(null,{status:401})}}ensureRandomValue(){(!this.randomValue||Date.now()-this.randomValueCreatedAt>9e5)&&(this.randomValue=k(8),this.randomValueCreatedAt=Date.now())}getIp(e){return this.config.getClientIp?this.config.getClientIp(e):e.headers.get("CF-Connecting-IP")||e.headers.get("X-Forwarded-For")?.split(",")[0]?.trim()||e.headers.get("X-Real-IP")||"unknown"}async fetchBundle(){try{let e=await this.getWorkerUrl(),t=await this.authedFetch("/b",{method:"GET",headers:{"x-obfious-worker-url":e}});return t.ok?await t.text():(console.error(`[obfious] Bundle fetch failed: ${t.status} ${t.statusText}`),null)}catch(e){return console.error("[obfious] Bundle fetch error:",e),null}}async fetchWorker(){try{let e=await this.authedFetch("/w",{method:"GET"});return e.ok?await e.text():(console.error(`[obfious] Worker fetch failed: ${e.status} ${e.statusText}`),null)}catch(e){return console.error("[obfious] Worker fetch error:",e),null}}async forwardToApi(e,t,r){let n={"Content-Type":"application/json","x-obfious-ip":this.getIp(e)};if(this.config.getPlatformSignals)for(let[o,i]of Object.entries(this.config.getPlatformSignals(e)))n[o.replace(/[\r\n]/g,"")]=String(i).replace(/[\r\n]/g,"");return this.authedFetch(t,{method:"POST",headers:n,body:r.buffer})}async forwardStreamToApi(e,t){let r={"Content-Type":"application/octet-stream","x-obfious-ip":this.getIp(e)};if(this.config.getPlatformSignals)for(let[n,o]of Object.entries(this.config.getPlatformSignals(e)))r[n.replace(/[\r\n]/g,"")]=String(o).replace(/[\r\n]/g,"");return this.authedFetch(t,{method:"POST",headers:r,body:e.body??void 0})}async validateToken(e,t,r,n){try{let o={tokenHex:e,signature:r,payload:t};n&&(o.encryptedUser=n);let i=await this.authedFetch("/validate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)});if(!i.ok)return{valid:!1};let u=await i.json();return{valid:u.valid===!0,deviceId:u.deviceId}}catch{return{valid:!1}}}async authedFetch(e,t){let r=`${this.config.apiUrl}${e}`,n=Date.now().toString(),o=(t.method||"GET").toUpperCase(),i=`${n}.${o}.${e}`,u=await A(this.creds.secret,i),c=new Headers(t.headers);return c.set(m,this.creds.keyId),c.set(b,u),c.set(P,n),fetch(r,{...t,headers:c})}};async function g(s,e=0){let t=Math.floor(Date.now()/3e5)+e,r=await crypto.subtle.importKey("raw",new TextEncoder().encode(s),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),n=await crypto.subtle.sign("HMAC",r,new TextEncoder().encode("obfious-bootstrap-v1:"+t));return f(new Uint8Array(n)).slice(0,10)}async function v(s,e){if(e.length!==10||!/^[0-9a-f]{10}$/.test(e))return!1;for(let t of[-1,0,1])if(await g(s,t)===e)return!0;return!1}async function y(s,e=0){let t=Math.floor(Date.now()/3e5)+e,r=t%7+1,n=await crypto.subtle.importKey("raw",new TextEncoder().encode(s),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),o=await crypto.subtle.sign("HMAC",n,new TextEncoder().encode("obfious-worker-v1:"+t)),i=f(new Uint8Array(o)).slice(0,9);return i.slice(0,r)+"w"+i.slice(r)}async function x(s,e){if(e.length!==10)return!1;let t=e.indexOf("w");if(t<1||t>7||e.lastIndexOf("w")!==t)return!1;let r=e.slice(0,t)+e.slice(t+1);if(!/^[0-9a-f]{9}$/.test(r))return!1;for(let n of[-1,0,1])if(await y(s,n)===e)return!0;return!1}function f(s){return Array.from(s,e=>e.toString(16).padStart(2,"0")).join("")}async function A(s,e){let t=await crypto.subtle.importKey("raw",new TextEncoder().encode(s),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),r=await crypto.subtle.sign("HMAC",t,new TextEncoder().encode(e));return f(new Uint8Array(r))}async function C(s,e){let t=await crypto.subtle.importKey("raw",new TextEncoder().encode(e),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),r=await crypto.subtle.sign("HMAC",t,new TextEncoder().encode(s));return f(new Uint8Array(r))}function R(s){try{let e=s.replace(/-/g,"+").replace(/_/g,"/");for(;e.length%4;)e+="=";let t=Uint8Array.from(atob(e),r=>r.charCodeAt(0));return t.length<9||t[0]!==33?null:f(t.slice(1,9))}catch{return null}}function k(s){let e="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",t=crypto.getRandomValues(new Uint8Array(s));return Array.from(t,r=>e[r%e.length]).join("")}export{h as Obfious};
1
+ var y="x-obfious-key",w="x-obfious-sig",m="x-obfious-ts",b=/\.(json|js|gif|png|woff2|css)$/;var f=class{config;creds;randomValue=null;randomValueCreatedAt=0;constructor(e){this.config={...e,apiUrl:e.apiUrl??"https://api.obfious.com"},this.creds={keyId:e.keyId,secret:e.secret}}async getScriptUrl(){if(this.config.scriptPath)return this.config.scriptPath;let e=await p(this.creds.secret);return this.ensureRandomValue(),`/?${e}=${this.randomValue}`}async scriptTag(e){let t=await this.getScriptUrl(),r=e?.nonce?` nonce="${e.nonce}"`:"";return`<script src="${t}"${r}></script>`}async protect(e,t){let r=new URL(e.url);if(e.method==="GET"){if(r.pathname==="/"){for(let[c]of r.searchParams)if(await v(this.creds.secret,c)){let u=await this.fetchBundle();return{response:new Response(u??`console.error("[obfious] Failed to load bundle: ${this.lastFetchError}");`,{headers:{"Content-Type":"application/javascript","Cache-Control":u?"private, max-age=300":"no-store"}})}}}if(this.config.scriptPath&&r.pathname===this.config.scriptPath){let c=await this.fetchBundle();if(c)return{response:new Response(c,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store"}})}}}if(e.method==="POST"&&b.test(r.pathname)){let c=e.clone(),u=new Uint8Array(await c.arrayBuffer());if(u.length>0&&u[0]===91)return{response:await this.forwardToApi(e,r.pathname,u)}}if(this.config.excludePaths?.some(c=>r.pathname.startsWith(c)))return{response:null};if(this.config.includePaths&&!this.config.includePaths.some(c=>r.pathname.startsWith(c)))return{response:null};let n=e.headers.get("x-req-auth");if(!n)return{response:new Response(null,{status:401})};let s=n.indexOf(".");if(s<1)return{response:new Response(null,{status:401})};let i=n.slice(0,s),a=n.slice(s+1),l=x(i);if(!l)return{response:new Response(null,{status:401})};let g=t&&this.config.privateKey?await T(t,this.config.privateKey):void 0,h=await this.validateToken(l,i,a,g);return h.valid?{response:null,deviceId:h.deviceId}:{response:new Response(null,{status:401})}}ensureRandomValue(){(!this.randomValue||Date.now()-this.randomValueCreatedAt>9e5)&&(this.randomValue=P(8),this.randomValueCreatedAt=Date.now())}getIp(e){return this.config.getClientIp?this.config.getClientIp(e):e.headers.get("CF-Connecting-IP")||e.headers.get("X-Forwarded-For")?.split(",")[0]?.trim()||e.headers.get("X-Real-IP")||"unknown"}lastFetchError="";async fetchBundle(){try{let e=await this.authedFetch("/b",{method:"GET"});return e.ok?await e.text():(this.lastFetchError=`API returned ${e.status}`,console.error(`[obfious] Bundle fetch failed: ${e.status} ${e.statusText}`),null)}catch(e){return this.lastFetchError=`${e}`,console.error("[obfious] Bundle fetch error:",e),null}}async forwardToApi(e,t,r){let n={"Content-Type":"application/json","x-obfious-ip":this.getIp(e)};if(this.config.getPlatformSignals)for(let[i,a]of Object.entries(this.config.getPlatformSignals(e)))n[i.replace(/[\r\n]/g,"")]=String(a).replace(/[\r\n]/g,"");let s=await this.authedFetch(t,{method:"POST",headers:n,body:r.buffer});if(!s.ok){let i=await s.clone().text().catch(()=>"");console.error(`[obfious] forwardToApi ${t}: ${s.status} ${i}`)}return s}async validateToken(e,t,r,n){try{let s={tokenHex:e,signature:r,payload:t};n&&(s.encryptedUser=n);let i=await this.authedFetch("/validate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)});if(!i.ok){let l=await i.text().catch(()=>"");return console.error(`[obfious] Validate failed: ${i.status} ${l}`),{valid:!1}}let a=await i.json();return a.valid!==!0&&console.error(`[obfious] Validate rejected: ${JSON.stringify(a)}`),{valid:a.valid===!0,deviceId:a.deviceId}}catch(s){return console.error("[obfious] Validate error:",s),{valid:!1}}}async authedFetch(e,t){let r=`${this.config.apiUrl}${e}`,n=Date.now().toString(),s=(t.method||"GET").toUpperCase(),i=`${n}.${s}.${e}`,a=await A(this.creds.secret,i),l=new Headers(t.headers);return l.set(y,this.creds.keyId),l.set(w,a),l.set(m,n),fetch(r,{...t,headers:l})}};async function p(o,e=0){let t=Math.floor(Date.now()/3e5)+e,r=await crypto.subtle.importKey("raw",new TextEncoder().encode(o),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),n=await crypto.subtle.sign("HMAC",r,new TextEncoder().encode("obfious-bootstrap-v1:"+t));return d(new Uint8Array(n)).slice(0,10)}async function v(o,e){if(e.length!==10||!/^[0-9a-f]{10}$/.test(e))return!1;for(let t of[-1,0,1])if(await p(o,t)===e)return!0;return!1}function d(o){return Array.from(o,e=>e.toString(16).padStart(2,"0")).join("")}async function A(o,e){let t=await crypto.subtle.importKey("raw",new TextEncoder().encode(o),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),r=await crypto.subtle.sign("HMAC",t,new TextEncoder().encode(e));return d(new Uint8Array(r))}async function T(o,e){let t=await crypto.subtle.importKey("raw",new TextEncoder().encode(e),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),r=await crypto.subtle.sign("HMAC",t,new TextEncoder().encode(o));return d(new Uint8Array(r))}function x(o){try{let e=o.replace(/-/g,"+").replace(/_/g,"/");for(;e.length%4;)e+="=";let t=Uint8Array.from(atob(e),r=>r.charCodeAt(0));return t.length<9||t[0]!==33?null:d(t.slice(1,9))}catch{return null}}function P(o){let e="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",t=crypto.getRandomValues(new Uint8Array(o));return Array.from(t,r=>e[r%e.length]).join("")}export{f as Obfious};
package/dist/lambda.js CHANGED
@@ -1 +1 @@
1
- var m="x-obfious-key",b="x-obfious-sig",P="x-obfious-ts",x=/\.(json|js|gif|png|woff2|css)$/;var p=class{config;creds;randomValue=null;randomValueCreatedAt=0;constructor(e){this.config={...e,apiUrl:e.apiUrl??"https://api.obfious.com"},this.creds={keyId:e.keyId,secret:e.secret}}async getScriptUrl(){if(this.config.scriptPath)return this.config.scriptPath;let e=await y(this.creds.secret);return this.ensureRandomValue(),`/?${e}=${this.randomValue}`}async getWorkerUrl(){let e=await w(this.creds.secret);return this.ensureRandomValue(),`/?${e}=${this.randomValue}`}async scriptTag(e){let t=await this.getScriptUrl(),r=e?.nonce?` nonce="${e.nonce}"`:"";return`<script src="${t}"${r}></script>`}async protect(e,t){let r=new URL(e.url);if(e.method==="GET"){if(r.pathname==="/")for(let[c]of r.searchParams){if(await R(this.creds.secret,c)){let u=await this.fetchBundle();return{response:new Response(u??'console.error("[obfious] Failed to load bundle from API");',{headers:{"Content-Type":"application/javascript","Cache-Control":u?"private, max-age=300":"no-store"}})}}if(await C(this.creds.secret,c)){let u=await this.fetchWorker();return{response:new Response(u??'console.error("[obfious] Failed to load worker from API");',{headers:{"Content-Type":"application/javascript","Cache-Control":u?"private, max-age=300":"no-store"}})}}}if(this.config.scriptPath&&r.pathname===this.config.scriptPath){let c=await this.fetchBundle();if(c)return{response:new Response(c,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store"}})}}}if(e.method==="POST"&&x.test(r.pathname)){if((e.headers.get("Content-Type")||"")==="application/octet-stream")return{response:await this.forwardStreamToApi(e,r.pathname)};let u=e.clone(),g=new Uint8Array(await u.arrayBuffer());if(g.length>0&&g[0]===91)return{response:await this.forwardToApi(e,r.pathname,g)}}if(this.config.excludePaths?.some(c=>r.pathname.startsWith(c)))return{response:null};if(this.config.includePaths&&!this.config.includePaths.some(c=>r.pathname.startsWith(c)))return{response:null};let n=e.headers.get("x-req-auth");if(!n)return{response:new Response(null,{status:401})};let i=n.indexOf(".");if(i<1)return{response:new Response(null,{status:401})};let o=n.slice(0,i),d=n.slice(i+1),a=I(o);if(!a)return{response:new Response(null,{status:401})};let f=t&&this.config.privateKey?await T(t,this.config.privateKey):void 0,l=await this.validateToken(a,o,d,f);return l.valid?{response:null,deviceId:l.deviceId}:{response:new Response(null,{status:401})}}ensureRandomValue(){(!this.randomValue||Date.now()-this.randomValueCreatedAt>9e5)&&(this.randomValue=k(8),this.randomValueCreatedAt=Date.now())}getIp(e){return this.config.getClientIp?this.config.getClientIp(e):e.headers.get("CF-Connecting-IP")||e.headers.get("X-Forwarded-For")?.split(",")[0]?.trim()||e.headers.get("X-Real-IP")||"unknown"}async fetchBundle(){try{let e=await this.getWorkerUrl(),t=await this.authedFetch("/b",{method:"GET",headers:{"x-obfious-worker-url":e}});return t.ok?await t.text():(console.error(`[obfious] Bundle fetch failed: ${t.status} ${t.statusText}`),null)}catch(e){return console.error("[obfious] Bundle fetch error:",e),null}}async fetchWorker(){try{let e=await this.authedFetch("/w",{method:"GET"});return e.ok?await e.text():(console.error(`[obfious] Worker fetch failed: ${e.status} ${e.statusText}`),null)}catch(e){return console.error("[obfious] Worker fetch error:",e),null}}async forwardToApi(e,t,r){let n={"Content-Type":"application/json","x-obfious-ip":this.getIp(e)};if(this.config.getPlatformSignals)for(let[i,o]of Object.entries(this.config.getPlatformSignals(e)))n[i.replace(/[\r\n]/g,"")]=String(o).replace(/[\r\n]/g,"");return this.authedFetch(t,{method:"POST",headers:n,body:r.buffer})}async forwardStreamToApi(e,t){let r={"Content-Type":"application/octet-stream","x-obfious-ip":this.getIp(e)};if(this.config.getPlatformSignals)for(let[n,i]of Object.entries(this.config.getPlatformSignals(e)))r[n.replace(/[\r\n]/g,"")]=String(i).replace(/[\r\n]/g,"");return this.authedFetch(t,{method:"POST",headers:r,body:e.body??void 0})}async validateToken(e,t,r,n){try{let i={tokenHex:e,signature:r,payload:t};n&&(i.encryptedUser=n);let o=await this.authedFetch("/validate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)});if(!o.ok)return{valid:!1};let d=await o.json();return{valid:d.valid===!0,deviceId:d.deviceId}}catch{return{valid:!1}}}async authedFetch(e,t){let r=`${this.config.apiUrl}${e}`,n=Date.now().toString(),i=(t.method||"GET").toUpperCase(),o=`${n}.${i}.${e}`,d=await A(this.creds.secret,o),a=new Headers(t.headers);return a.set(m,this.creds.keyId),a.set(b,d),a.set(P,n),fetch(r,{...t,headers:a})}};async function y(s,e=0){let t=Math.floor(Date.now()/3e5)+e,r=await crypto.subtle.importKey("raw",new TextEncoder().encode(s),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),n=await crypto.subtle.sign("HMAC",r,new TextEncoder().encode("obfious-bootstrap-v1:"+t));return h(new Uint8Array(n)).slice(0,10)}async function R(s,e){if(e.length!==10||!/^[0-9a-f]{10}$/.test(e))return!1;for(let t of[-1,0,1])if(await y(s,t)===e)return!0;return!1}async function w(s,e=0){let t=Math.floor(Date.now()/3e5)+e,r=t%7+1,n=await crypto.subtle.importKey("raw",new TextEncoder().encode(s),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),i=await crypto.subtle.sign("HMAC",n,new TextEncoder().encode("obfious-worker-v1:"+t)),o=h(new Uint8Array(i)).slice(0,9);return o.slice(0,r)+"w"+o.slice(r)}async function C(s,e){if(e.length!==10)return!1;let t=e.indexOf("w");if(t<1||t>7||e.lastIndexOf("w")!==t)return!1;let r=e.slice(0,t)+e.slice(t+1);if(!/^[0-9a-f]{9}$/.test(r))return!1;for(let n of[-1,0,1])if(await w(s,n)===e)return!0;return!1}function h(s){return Array.from(s,e=>e.toString(16).padStart(2,"0")).join("")}async function A(s,e){let t=await crypto.subtle.importKey("raw",new TextEncoder().encode(s),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),r=await crypto.subtle.sign("HMAC",t,new TextEncoder().encode(e));return h(new Uint8Array(r))}async function T(s,e){let t=await crypto.subtle.importKey("raw",new TextEncoder().encode(e),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),r=await crypto.subtle.sign("HMAC",t,new TextEncoder().encode(s));return h(new Uint8Array(r))}function I(s){try{let e=s.replace(/-/g,"+").replace(/_/g,"/");for(;e.length%4;)e+="=";let t=Uint8Array.from(atob(e),r=>r.charCodeAt(0));return t.length<9||t[0]!==33?null:h(t.slice(1,9))}catch{return null}}function k(s){let e="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",t=crypto.getRandomValues(new Uint8Array(s));return Array.from(t,r=>e[r%e.length]).join("")}function v(s){let e=s.headers["x-forwarded-proto"]||s.headers["X-Forwarded-Proto"]||"https",t=s.headers.host||s.headers.Host||"localhost",r=`${e}://${t}${s.path}`;if(s.queryStringParameters){let d=new URLSearchParams;for(let[f,l]of Object.entries(s.queryStringParameters))l!=null&&d.set(f,l);let a=d.toString();a&&(r+=`?${a}`)}let n=new Headers;for(let[d,a]of Object.entries(s.headers))a&&n.set(d,a);let o=s.httpMethod!=="GET"&&s.httpMethod!=="HEAD"&&s.body!=null?s.isBase64Encoded?atob(s.body):s.body:null;return new Request(r,{method:s.httpMethod,headers:n,body:o})}async function S(s){let e={};return s.headers.forEach((t,r)=>{e[r]=t}),{statusCode:s.status,headers:e,body:await s.text()}}function H(s,e){let{creds:t,getUser:r,...n}=s,i=new p({...n,keyId:t.keyId,secret:t.secret,getClientIp:n.getClientIp??(o=>o.headers.get("x-lambda-source-ip")||o.headers.get("x-forwarded-for")?.split(",")[0]?.trim()||"unknown"),getPlatformSignals:n.getPlatformSignals??(()=>({}))});return async(o,d)=>{let a=v(o),f=o.requestContext?.identity?.sourceIp||o.headers["x-forwarded-for"]?.split(",")[0]?.trim()||"unknown";a.headers.set("x-lambda-source-ip",f);let l=r?.(o),c=await i.protect(a,l);return c.response?S(c.response):(c.deviceId&&(o.headers["x-obfious-device-id"]=String(c.deviceId)),e(o,d))}}export{p as Obfious,H as obfiousHandler};
1
+ var y="x-obfious-key",m="x-obfious-sig",w="x-obfious-ts",b=/\.(json|js|gif|png|woff2|css)$/;var h=class{config;creds;randomValue=null;randomValueCreatedAt=0;constructor(e){this.config={...e,apiUrl:e.apiUrl??"https://api.obfious.com"},this.creds={keyId:e.keyId,secret:e.secret}}async getScriptUrl(){if(this.config.scriptPath)return this.config.scriptPath;let e=await g(this.creds.secret);return this.ensureRandomValue(),`/?${e}=${this.randomValue}`}async scriptTag(e){let r=await this.getScriptUrl(),s=e?.nonce?` nonce="${e.nonce}"`:"";return`<script src="${r}"${s}></script>`}async protect(e,r){let s=new URL(e.url);if(e.method==="GET"){if(s.pathname==="/"){for(let[d]of s.searchParams)if(await P(this.creds.secret,d)){let l=await this.fetchBundle();return{response:new Response(l??`console.error("[obfious] Failed to load bundle: ${this.lastFetchError}");`,{headers:{"Content-Type":"application/javascript","Cache-Control":l?"private, max-age=300":"no-store"}})}}}if(this.config.scriptPath&&s.pathname===this.config.scriptPath){let d=await this.fetchBundle();if(d)return{response:new Response(d,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store"}})}}}if(e.method==="POST"&&b.test(s.pathname)){let d=e.clone(),l=new Uint8Array(await d.arrayBuffer());if(l.length>0&&l[0]===91)return{response:await this.forwardToApi(e,s.pathname,l)}}if(this.config.excludePaths?.some(d=>s.pathname.startsWith(d)))return{response:null};if(this.config.includePaths&&!this.config.includePaths.some(d=>s.pathname.startsWith(d)))return{response:null};let o=e.headers.get("x-req-auth");if(!o)return{response:new Response(null,{status:401})};let i=o.indexOf(".");if(i<1)return{response:new Response(null,{status:401})};let n=o.slice(0,i),c=o.slice(i+1),a=A(n);if(!a)return{response:new Response(null,{status:401})};let f=r&&this.config.privateKey?await R(r,this.config.privateKey):void 0,u=await this.validateToken(a,n,c,f);return u.valid?{response:null,deviceId:u.deviceId}:{response:new Response(null,{status:401})}}ensureRandomValue(){(!this.randomValue||Date.now()-this.randomValueCreatedAt>9e5)&&(this.randomValue=C(8),this.randomValueCreatedAt=Date.now())}getIp(e){return this.config.getClientIp?this.config.getClientIp(e):e.headers.get("CF-Connecting-IP")||e.headers.get("X-Forwarded-For")?.split(",")[0]?.trim()||e.headers.get("X-Real-IP")||"unknown"}lastFetchError="";async fetchBundle(){try{let e=await this.authedFetch("/b",{method:"GET"});return e.ok?await e.text():(this.lastFetchError=`API returned ${e.status}`,console.error(`[obfious] Bundle fetch failed: ${e.status} ${e.statusText}`),null)}catch(e){return this.lastFetchError=`${e}`,console.error("[obfious] Bundle fetch error:",e),null}}async forwardToApi(e,r,s){let o={"Content-Type":"application/json","x-obfious-ip":this.getIp(e)};if(this.config.getPlatformSignals)for(let[n,c]of Object.entries(this.config.getPlatformSignals(e)))o[n.replace(/[\r\n]/g,"")]=String(c).replace(/[\r\n]/g,"");let i=await this.authedFetch(r,{method:"POST",headers:o,body:s.buffer});if(!i.ok){let n=await i.clone().text().catch(()=>"");console.error(`[obfious] forwardToApi ${r}: ${i.status} ${n}`)}return i}async validateToken(e,r,s,o){try{let i={tokenHex:e,signature:s,payload:r};o&&(i.encryptedUser=o);let n=await this.authedFetch("/validate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)});if(!n.ok){let a=await n.text().catch(()=>"");return console.error(`[obfious] Validate failed: ${n.status} ${a}`),{valid:!1}}let c=await n.json();return c.valid!==!0&&console.error(`[obfious] Validate rejected: ${JSON.stringify(c)}`),{valid:c.valid===!0,deviceId:c.deviceId}}catch(i){return console.error("[obfious] Validate error:",i),{valid:!1}}}async authedFetch(e,r){let s=`${this.config.apiUrl}${e}`,o=Date.now().toString(),i=(r.method||"GET").toUpperCase(),n=`${o}.${i}.${e}`,c=await x(this.creds.secret,n),a=new Headers(r.headers);return a.set(y,this.creds.keyId),a.set(m,c),a.set(w,o),fetch(s,{...r,headers:a})}};async function g(t,e=0){let r=Math.floor(Date.now()/3e5)+e,s=await crypto.subtle.importKey("raw",new TextEncoder().encode(t),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),o=await crypto.subtle.sign("HMAC",s,new TextEncoder().encode("obfious-bootstrap-v1:"+r));return p(new Uint8Array(o)).slice(0,10)}async function P(t,e){if(e.length!==10||!/^[0-9a-f]{10}$/.test(e))return!1;for(let r of[-1,0,1])if(await g(t,r)===e)return!0;return!1}function p(t){return Array.from(t,e=>e.toString(16).padStart(2,"0")).join("")}async function x(t,e){let r=await crypto.subtle.importKey("raw",new TextEncoder().encode(t),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),s=await crypto.subtle.sign("HMAC",r,new TextEncoder().encode(e));return p(new Uint8Array(s))}async function R(t,e){let r=await crypto.subtle.importKey("raw",new TextEncoder().encode(e),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),s=await crypto.subtle.sign("HMAC",r,new TextEncoder().encode(t));return p(new Uint8Array(s))}function A(t){try{let e=t.replace(/-/g,"+").replace(/_/g,"/");for(;e.length%4;)e+="=";let r=Uint8Array.from(atob(e),s=>s.charCodeAt(0));return r.length<9||r[0]!==33?null:p(r.slice(1,9))}catch{return null}}function C(t){let e="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",r=crypto.getRandomValues(new Uint8Array(t));return Array.from(r,s=>e[s%e.length]).join("")}function I(t){let e=t.headers["x-forwarded-proto"]||t.headers["X-Forwarded-Proto"]||"https",r=t.headers.host||t.headers.Host||"localhost",s=`${e}://${r}${t.path}`;if(t.queryStringParameters){let c=new URLSearchParams;for(let[f,u]of Object.entries(t.queryStringParameters))u!=null&&c.set(f,u);let a=c.toString();a&&(s+=`?${a}`)}let o=new Headers;for(let[c,a]of Object.entries(t.headers))a&&o.set(c,a);let n=t.httpMethod!=="GET"&&t.httpMethod!=="HEAD"&&t.body!=null?t.isBase64Encoded?atob(t.body):t.body:null;return new Request(s,{method:t.httpMethod,headers:o,body:n})}async function T(t){let e={};return t.headers.forEach((r,s)=>{e[s]=r}),{statusCode:t.status,headers:e,body:await t.text()}}function S(t,e){let{creds:r,getUser:s,...o}=t,i=new h({...o,keyId:r.keyId,secret:r.secret,getClientIp:o.getClientIp??(n=>n.headers.get("x-lambda-source-ip")||n.headers.get("x-forwarded-for")?.split(",")[0]?.trim()||"unknown"),getPlatformSignals:o.getPlatformSignals??(()=>({}))});return async(n,c)=>{let a=I(n),f=n.requestContext?.identity?.sourceIp||n.headers["x-forwarded-for"]?.split(",")[0]?.trim()||"unknown";a.headers.set("x-lambda-source-ip",f);let u=s?.(n),d=await i.protect(a,u);return d.response?T(d.response):(d.deviceId&&(n.headers["x-obfious-device-id"]=String(d.deviceId)),e(n,c))}}export{h as Obfious,S as obfiousHandler};
package/dist/nextjs.js CHANGED
@@ -1 +1 @@
1
- var m="x-obfious-key",b="x-obfious-sig",x="x-obfious-ts",C=/\.(json|js|gif|png|woff2|css)$/;var d=class{config;creds;randomValue=null;randomValueCreatedAt=0;constructor(e){this.config={...e,apiUrl:e.apiUrl??"https://api.obfious.com"},this.creds={keyId:e.keyId,secret:e.secret}}async getScriptUrl(){if(this.config.scriptPath)return this.config.scriptPath;let e=await h(this.creds.secret);return this.ensureRandomValue(),`/?${e}=${this.randomValue}`}async getWorkerUrl(){let e=await y(this.creds.secret);return this.ensureRandomValue(),`/?${e}=${this.randomValue}`}async scriptTag(e){let t=await this.getScriptUrl(),r=e?.nonce?` nonce="${e.nonce}"`:"";return`<script src="${t}"${r}></script>`}async protect(e,t){let r=new URL(e.url);if(e.method==="GET"){if(r.pathname==="/")for(let[a]of r.searchParams){if(await P(this.creds.secret,a)){let l=await this.fetchBundle();return{response:new Response(l??'console.error("[obfious] Failed to load bundle from API");',{headers:{"Content-Type":"application/javascript","Cache-Control":l?"private, max-age=300":"no-store"}})}}if(await T(this.creds.secret,a)){let l=await this.fetchWorker();return{response:new Response(l??'console.error("[obfious] Failed to load worker from API");',{headers:{"Content-Type":"application/javascript","Cache-Control":l?"private, max-age=300":"no-store"}})}}}if(this.config.scriptPath&&r.pathname===this.config.scriptPath){let a=await this.fetchBundle();if(a)return{response:new Response(a,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store"}})}}}if(e.method==="POST"&&C.test(r.pathname)){if((e.headers.get("Content-Type")||"")==="application/octet-stream")return{response:await this.forwardStreamToApi(e,r.pathname)};let l=e.clone(),p=new Uint8Array(await l.arrayBuffer());if(p.length>0&&p[0]===91)return{response:await this.forwardToApi(e,r.pathname,p)}}if(this.config.excludePaths?.some(a=>r.pathname.startsWith(a)))return{response:null};if(this.config.includePaths&&!this.config.includePaths.some(a=>r.pathname.startsWith(a)))return{response:null};let n=e.headers.get("x-req-auth");if(!n)return{response:new Response(null,{status:401})};let o=n.indexOf(".");if(o<1)return{response:new Response(null,{status:401})};let i=n.slice(0,o),u=n.slice(o+1),c=A(i);if(!c)return{response:new Response(null,{status:401})};let w=t&&this.config.privateKey?await R(t,this.config.privateKey):void 0,g=await this.validateToken(c,i,u,w);return g.valid?{response:null,deviceId:g.deviceId}:{response:new Response(null,{status:401})}}ensureRandomValue(){(!this.randomValue||Date.now()-this.randomValueCreatedAt>9e5)&&(this.randomValue=k(8),this.randomValueCreatedAt=Date.now())}getIp(e){return this.config.getClientIp?this.config.getClientIp(e):e.headers.get("CF-Connecting-IP")||e.headers.get("X-Forwarded-For")?.split(",")[0]?.trim()||e.headers.get("X-Real-IP")||"unknown"}async fetchBundle(){try{let e=await this.getWorkerUrl(),t=await this.authedFetch("/b",{method:"GET",headers:{"x-obfious-worker-url":e}});return t.ok?await t.text():(console.error(`[obfious] Bundle fetch failed: ${t.status} ${t.statusText}`),null)}catch(e){return console.error("[obfious] Bundle fetch error:",e),null}}async fetchWorker(){try{let e=await this.authedFetch("/w",{method:"GET"});return e.ok?await e.text():(console.error(`[obfious] Worker fetch failed: ${e.status} ${e.statusText}`),null)}catch(e){return console.error("[obfious] Worker fetch error:",e),null}}async forwardToApi(e,t,r){let n={"Content-Type":"application/json","x-obfious-ip":this.getIp(e)};if(this.config.getPlatformSignals)for(let[o,i]of Object.entries(this.config.getPlatformSignals(e)))n[o.replace(/[\r\n]/g,"")]=String(i).replace(/[\r\n]/g,"");return this.authedFetch(t,{method:"POST",headers:n,body:r.buffer})}async forwardStreamToApi(e,t){let r={"Content-Type":"application/octet-stream","x-obfious-ip":this.getIp(e)};if(this.config.getPlatformSignals)for(let[n,o]of Object.entries(this.config.getPlatformSignals(e)))r[n.replace(/[\r\n]/g,"")]=String(o).replace(/[\r\n]/g,"");return this.authedFetch(t,{method:"POST",headers:r,body:e.body??void 0})}async validateToken(e,t,r,n){try{let o={tokenHex:e,signature:r,payload:t};n&&(o.encryptedUser=n);let i=await this.authedFetch("/validate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)});if(!i.ok)return{valid:!1};let u=await i.json();return{valid:u.valid===!0,deviceId:u.deviceId}}catch{return{valid:!1}}}async authedFetch(e,t){let r=`${this.config.apiUrl}${e}`,n=Date.now().toString(),o=(t.method||"GET").toUpperCase(),i=`${n}.${o}.${e}`,u=await v(this.creds.secret,i),c=new Headers(t.headers);return c.set(m,this.creds.keyId),c.set(b,u),c.set(x,n),fetch(r,{...t,headers:c})}};async function h(s,e=0){let t=Math.floor(Date.now()/3e5)+e,r=await crypto.subtle.importKey("raw",new TextEncoder().encode(s),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),n=await crypto.subtle.sign("HMAC",r,new TextEncoder().encode("obfious-bootstrap-v1:"+t));return f(new Uint8Array(n)).slice(0,10)}async function P(s,e){if(e.length!==10||!/^[0-9a-f]{10}$/.test(e))return!1;for(let t of[-1,0,1])if(await h(s,t)===e)return!0;return!1}async function y(s,e=0){let t=Math.floor(Date.now()/3e5)+e,r=t%7+1,n=await crypto.subtle.importKey("raw",new TextEncoder().encode(s),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),o=await crypto.subtle.sign("HMAC",n,new TextEncoder().encode("obfious-worker-v1:"+t)),i=f(new Uint8Array(o)).slice(0,9);return i.slice(0,r)+"w"+i.slice(r)}async function T(s,e){if(e.length!==10)return!1;let t=e.indexOf("w");if(t<1||t>7||e.lastIndexOf("w")!==t)return!1;let r=e.slice(0,t)+e.slice(t+1);if(!/^[0-9a-f]{9}$/.test(r))return!1;for(let n of[-1,0,1])if(await y(s,n)===e)return!0;return!1}function f(s){return Array.from(s,e=>e.toString(16).padStart(2,"0")).join("")}async function v(s,e){let t=await crypto.subtle.importKey("raw",new TextEncoder().encode(s),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),r=await crypto.subtle.sign("HMAC",t,new TextEncoder().encode(e));return f(new Uint8Array(r))}async function R(s,e){let t=await crypto.subtle.importKey("raw",new TextEncoder().encode(e),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),r=await crypto.subtle.sign("HMAC",t,new TextEncoder().encode(s));return f(new Uint8Array(r))}function A(s){try{let e=s.replace(/-/g,"+").replace(/_/g,"/");for(;e.length%4;)e+="=";let t=Uint8Array.from(atob(e),r=>r.charCodeAt(0));return t.length<9||t[0]!==33?null:f(t.slice(1,9))}catch{return null}}function k(s){let e="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",t=crypto.getRandomValues(new Uint8Array(s));return Array.from(t,r=>e[r%e.length]).join("")}function O(s){let{creds:e,...t}=s,r=new d({...t,...e?{keyId:e.keyId,secret:e.secret}:{},getClientIp:t.getClientIp??(n=>n.headers.get("x-forwarded-for")?.split(",")[0]?.trim()||n.headers.get("x-real-ip")||"unknown")});return async n=>(await r.protect(n)).response}async function U(s,e){return s.scriptTag({nonce:e})}export{d as Obfious,O as createObfiousMiddleware,U as obfiousScriptTag};
1
+ var y="x-obfious-key",w="x-obfious-sig",m="x-obfious-ts",b=/\.(json|js|gif|png|woff2|css)$/;var d=class{config;creds;randomValue=null;randomValueCreatedAt=0;constructor(e){this.config={...e,apiUrl:e.apiUrl??"https://api.obfious.com"},this.creds={keyId:e.keyId,secret:e.secret}}async getScriptUrl(){if(this.config.scriptPath)return this.config.scriptPath;let e=await g(this.creds.secret);return this.ensureRandomValue(),`/?${e}=${this.randomValue}`}async scriptTag(e){let t=await this.getScriptUrl(),r=e?.nonce?` nonce="${e.nonce}"`:"";return`<script src="${t}"${r}></script>`}async protect(e,t){let r=new URL(e.url);if(e.method==="GET"){if(r.pathname==="/"){for(let[c]of r.searchParams)if(await x(this.creds.secret,c)){let l=await this.fetchBundle();return{response:new Response(l??`console.error("[obfious] Failed to load bundle: ${this.lastFetchError}");`,{headers:{"Content-Type":"application/javascript","Cache-Control":l?"private, max-age=300":"no-store"}})}}}if(this.config.scriptPath&&r.pathname===this.config.scriptPath){let c=await this.fetchBundle();if(c)return{response:new Response(c,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store"}})}}}if(e.method==="POST"&&b.test(r.pathname)){let c=e.clone(),l=new Uint8Array(await c.arrayBuffer());if(l.length>0&&l[0]===91)return{response:await this.forwardToApi(e,r.pathname,l)}}if(this.config.excludePaths?.some(c=>r.pathname.startsWith(c)))return{response:null};if(this.config.includePaths&&!this.config.includePaths.some(c=>r.pathname.startsWith(c)))return{response:null};let s=e.headers.get("x-req-auth");if(!s)return{response:new Response(null,{status:401})};let o=s.indexOf(".");if(o<1)return{response:new Response(null,{status:401})};let i=s.slice(0,o),a=s.slice(o+1),u=R(i);if(!u)return{response:new Response(null,{status:401})};let h=t&&this.config.privateKey?await v(t,this.config.privateKey):void 0,p=await this.validateToken(u,i,a,h);return p.valid?{response:null,deviceId:p.deviceId}:{response:new Response(null,{status:401})}}ensureRandomValue(){(!this.randomValue||Date.now()-this.randomValueCreatedAt>9e5)&&(this.randomValue=P(8),this.randomValueCreatedAt=Date.now())}getIp(e){return this.config.getClientIp?this.config.getClientIp(e):e.headers.get("CF-Connecting-IP")||e.headers.get("X-Forwarded-For")?.split(",")[0]?.trim()||e.headers.get("X-Real-IP")||"unknown"}lastFetchError="";async fetchBundle(){try{let e=await this.authedFetch("/b",{method:"GET"});return e.ok?await e.text():(this.lastFetchError=`API returned ${e.status}`,console.error(`[obfious] Bundle fetch failed: ${e.status} ${e.statusText}`),null)}catch(e){return this.lastFetchError=`${e}`,console.error("[obfious] Bundle fetch error:",e),null}}async forwardToApi(e,t,r){let s={"Content-Type":"application/json","x-obfious-ip":this.getIp(e)};if(this.config.getPlatformSignals)for(let[i,a]of Object.entries(this.config.getPlatformSignals(e)))s[i.replace(/[\r\n]/g,"")]=String(a).replace(/[\r\n]/g,"");let o=await this.authedFetch(t,{method:"POST",headers:s,body:r.buffer});if(!o.ok){let i=await o.clone().text().catch(()=>"");console.error(`[obfious] forwardToApi ${t}: ${o.status} ${i}`)}return o}async validateToken(e,t,r,s){try{let o={tokenHex:e,signature:r,payload:t};s&&(o.encryptedUser=s);let i=await this.authedFetch("/validate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)});if(!i.ok){let u=await i.text().catch(()=>"");return console.error(`[obfious] Validate failed: ${i.status} ${u}`),{valid:!1}}let a=await i.json();return a.valid!==!0&&console.error(`[obfious] Validate rejected: ${JSON.stringify(a)}`),{valid:a.valid===!0,deviceId:a.deviceId}}catch(o){return console.error("[obfious] Validate error:",o),{valid:!1}}}async authedFetch(e,t){let r=`${this.config.apiUrl}${e}`,s=Date.now().toString(),o=(t.method||"GET").toUpperCase(),i=`${s}.${o}.${e}`,a=await C(this.creds.secret,i),u=new Headers(t.headers);return u.set(y,this.creds.keyId),u.set(w,a),u.set(m,s),fetch(r,{...t,headers:u})}};async function g(n,e=0){let t=Math.floor(Date.now()/3e5)+e,r=await crypto.subtle.importKey("raw",new TextEncoder().encode(n),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),s=await crypto.subtle.sign("HMAC",r,new TextEncoder().encode("obfious-bootstrap-v1:"+t));return f(new Uint8Array(s)).slice(0,10)}async function x(n,e){if(e.length!==10||!/^[0-9a-f]{10}$/.test(e))return!1;for(let t of[-1,0,1])if(await g(n,t)===e)return!0;return!1}function f(n){return Array.from(n,e=>e.toString(16).padStart(2,"0")).join("")}async function C(n,e){let t=await crypto.subtle.importKey("raw",new TextEncoder().encode(n),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),r=await crypto.subtle.sign("HMAC",t,new TextEncoder().encode(e));return f(new Uint8Array(r))}async function v(n,e){let t=await crypto.subtle.importKey("raw",new TextEncoder().encode(e),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),r=await crypto.subtle.sign("HMAC",t,new TextEncoder().encode(n));return f(new Uint8Array(r))}function R(n){try{let e=n.replace(/-/g,"+").replace(/_/g,"/");for(;e.length%4;)e+="=";let t=Uint8Array.from(atob(e),r=>r.charCodeAt(0));return t.length<9||t[0]!==33?null:f(t.slice(1,9))}catch{return null}}function P(n){let e="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",t=crypto.getRandomValues(new Uint8Array(n));return Array.from(t,r=>e[r%e.length]).join("")}function I(n){let{creds:e,...t}=n,r=new d({...t,...e?{keyId:e.keyId,secret:e.secret}:{},getClientIp:t.getClientIp??(s=>s.headers.get("x-forwarded-for")?.split(",")[0]?.trim()||s.headers.get("x-real-ip")||"unknown")});return async s=>(await r.protect(s)).response}async function O(n,e){return n.scriptTag({nonce:e})}export{d as Obfious,I as createObfiousMiddleware,O as obfiousScriptTag};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@obfious/js",
3
- "version": "0.1.12",
3
+ "version": "0.1.14",
4
4
  "description": "Obfious anti-bot protection for JavaScript — CF Workers, Next.js, Express, Fastify, Lambda",
5
5
  "type": "module",
6
6
  "exports": {