@obfious/js 0.1.10 → 0.1.11
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 +1 -1
- package/dist/fastify.js +1 -1
- package/dist/index.d.ts +6 -4
- package/dist/lambda.js +1 -1
- package/dist/nextjs.d.ts +3 -3
- package/dist/nextjs.js +1 -1
- package/package.json +1 -1
package/dist/express.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var R="x-obfious-key",x="x-obfious-sig",C="x-obfious-ts",P=/\.(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();if(d)return{response:new Response(d,{headers:{"Content-Type":"application/javascript","Cache-Control":"private, max-age=300"}})};break}if(await A(this.creds.secret,l)){let d=await this.fetchWorker();if(d)return{response:new Response(d,{headers:{"Content-Type":"application/javascript","Cache-Control":"private, max-age=300"}})};break}}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"&&P.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 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),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():null}catch{return null}}async fetchWorker(){try{let e=await this.authedFetch("/w",{method:"GET"});return e.ok?await e.text():null}catch{return null}}async forwardToApi(e,t,r){let s={"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)))s[o.replace(/[\r\n]/g,"")]=String(i).replace(/[\r\n]/g,"");return this.authedFetch(t,{method:"POST",headers:s,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[s,o]of Object.entries(this.config.getPlatformSignals(e)))r[s.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,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)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}`,s=Date.now().toString(),o=(t.method||"GET").toUpperCase(),i=`${s}.${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(C,s),fetch(r,{...t,headers:c})}};async function y(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 T(n,e){if(e.length!==10||!/^[0-9a-f]{10}$/.test(e))return!1;for(let t of[-1,0,1])if(await y(n,t)===e)return!0;return!1}async function m(n,e=0){let t=Math.floor(Date.now()/3e5)+e,r=t%7+1,s=await crypto.subtle.importKey("raw",new TextEncoder().encode(n),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),o=await crypto.subtle.sign("HMAC",s,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(n,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 s of[-1,0,1])if(await m(n,s)===e)return!0;return!1}function f(n){return Array.from(n,e=>e.toString(16).padStart(2,"0")).join("")}async function k(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 I(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 S(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 O(n){let e="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",t=crypto.getRandomValues(new Uint8Array(n));return Array.from(t,r=>e[r%e.length]).join("")}import{Readable as w}from"node:stream";function b(n){let e=n.headers["x-forwarded-proto"]||"http",t=n.headers.host||"localhost",r=`${e}://${t}${n.url}`,s=new Headers;for(let[i,a]of Object.entries(n.headers))a&&s.set(i,Array.isArray(a)?a.join(", "):a);let o=n.method!=="GET"&&n.method!=="HEAD";return new Request(r,{method:n.method,headers:s,body:o?w.toWeb(w.from(n)):null,duplex:"half"})}async function v(n,e){let t={};if(e.headers.forEach((r,s)=>{t[s]=r}),n.writeHead(e.status,t),e.body){let r=e.body.getReader();try{for(;;){let{done:s,value:o}=await r.read();if(s)break;n.write(o)}}finally{r.releaseLock()}}n.end()}function V(n){let{creds:e,getUser:t,...r}=n,s=new p({...r,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 s.protect(c,
|
|
1
|
+
var R="x-obfious-key",x="x-obfious-sig",C="x-obfious-ts",P=/\.(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();if(d)return{response:new Response(d,{headers:{"Content-Type":"application/javascript","Cache-Control":"private, max-age=300"}})};break}if(await A(this.creds.secret,l)){let d=await this.fetchWorker();if(d)return{response:new Response(d,{headers:{"Content-Type":"application/javascript","Cache-Control":"private, max-age=300"}})};break}}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"&&P.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 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),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():null}catch{return null}}async fetchWorker(){try{let e=await this.authedFetch("/w",{method:"GET"});return e.ok?await e.text():null}catch{return null}}async forwardToApi(e,t,r){let s={"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)))s[o.replace(/[\r\n]/g,"")]=String(i).replace(/[\r\n]/g,"");return this.authedFetch(t,{method:"POST",headers:s,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[s,o]of Object.entries(this.config.getPlatformSignals(e)))r[s.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,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)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}`,s=Date.now().toString(),o=(t.method||"GET").toUpperCase(),i=`${s}.${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(C,s),fetch(r,{...t,headers:c})}};async function y(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 T(n,e){if(e.length!==10||!/^[0-9a-f]{10}$/.test(e))return!1;for(let t of[-1,0,1])if(await y(n,t)===e)return!0;return!1}async function m(n,e=0){let t=Math.floor(Date.now()/3e5)+e,r=t%7+1,s=await crypto.subtle.importKey("raw",new TextEncoder().encode(n),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),o=await crypto.subtle.sign("HMAC",s,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(n,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 s of[-1,0,1])if(await m(n,s)===e)return!0;return!1}function f(n){return Array.from(n,e=>e.toString(16).padStart(2,"0")).join("")}async function k(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 I(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 S(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 O(n){let e="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",t=crypto.getRandomValues(new Uint8Array(n));return Array.from(t,r=>e[r%e.length]).join("")}import{Readable as w}from"node:stream";function b(n){let e=n.headers["x-forwarded-proto"]||"http",t=n.headers.host||"localhost",r=`${e}://${t}${n.url}`,s=new Headers;for(let[i,a]of Object.entries(n.headers))a&&s.set(i,Array.isArray(a)?a.join(", "):a);let o=n.method!=="GET"&&n.method!=="HEAD";return new Request(r,{method:n.method,headers:s,body:o?w.toWeb(w.from(n)):null,duplex:"half"})}async function v(n,e){let t={};if(e.headers.forEach((r,s)=>{t[s]=r}),n.writeHead(e.status,t),e.body){let r=e.body.getReader();try{for(;;){let{done:s,value:o}=await r.read();if(s)break;n.write(o)}}finally{r.releaseLock()}}n.end()}function V(n){let{creds:e,getUser:t,...r}=n,s=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 s.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};
|
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(),n=e?.nonce?` nonce="${e.nonce}"`:"";return`<script src="${t}"${n}></script>`}async protect(e,t){let n=new URL(e.url);if(e.method==="GET"){if(n.pathname==="/")for(let[c]of n.searchParams){if(await T(this.creds.secret,c)){let u=await this.fetchBundle();if(u)return{response:new Response(u,{headers:{"Content-Type":"application/javascript","Cache-Control":"private, max-age=300"}})};break}if(await
|
|
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(),n=e?.nonce?` nonce="${e.nonce}"`:"";return`<script src="${t}"${n}></script>`}async protect(e,t){let n=new URL(e.url);if(e.method==="GET"){if(n.pathname==="/")for(let[c]of n.searchParams){if(await T(this.creds.secret,c)){let u=await this.fetchBundle();if(u)return{response:new Response(u,{headers:{"Content-Type":"application/javascript","Cache-Control":"private, max-age=300"}})};break}if(await k(this.creds.secret,c)){let u=await this.fetchWorker();if(u)return{response:new Response(u,{headers:{"Content-Type":"application/javascript","Cache-Control":"private, max-age=300"}})};break}}if(this.config.scriptPath&&n.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(n.pathname)){if((e.headers.get("Content-Type")||"")==="application/octet-stream")return{response:await this.forwardStreamToApi(e,n.pathname)};let u=e.clone(),f=new Uint8Array(await u.arrayBuffer());if(f.length>0&&f[0]===91)return{response:await this.forwardToApi(e,n.pathname,f)}}if(this.config.excludePaths?.some(c=>n.pathname.startsWith(c)))return{response:null};if(this.config.includePaths&&!this.config.includePaths.some(c=>n.pathname.startsWith(c)))return{response:null};let s=e.headers.get("x-req-auth");if(!s)return{response:new Response(null,{status:401})};let i=s.indexOf(".");if(i<1)return{response:new Response(null,{status:401})};let o=s.slice(0,i),a=s.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():null}catch{return null}}async fetchWorker(){try{let e=await this.authedFetch("/w",{method:"GET"});return e.ok?await e.text():null}catch{return null}}async forwardToApi(e,t,n){let s={"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)))s[i.replace(/[\r\n]/g,"")]=String(o).replace(/[\r\n]/g,"");return this.authedFetch(t,{method:"POST",headers:s,body:n.buffer})}async forwardStreamToApi(e,t){let n={"Content-Type":"application/octet-stream","x-obfious-ip":this.getIp(e)};if(this.config.getPlatformSignals)for(let[s,i]of Object.entries(this.config.getPlatformSignals(e)))n[s.replace(/[\r\n]/g,"")]=String(i).replace(/[\r\n]/g,"");return this.authedFetch(t,{method:"POST",headers:n,body:e.body??void 0})}async validateToken(e,t,n,s){try{let i={tokenHex:e,signature:n,payload:t};s&&(i.encryptedUser=s);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 n=`${this.config.apiUrl}${e}`,s=Date.now().toString(),i=(t.method||"GET").toUpperCase(),o=`${s}.${i}.${e}`,a=await A(this.creds.secret,o),l=new Headers(t.headers);return l.set(v,this.creds.keyId),l.set(x,a),l.set(P,s),fetch(n,{...t,headers:l})}};async function y(r,e=0){let t=Math.floor(Date.now()/3e5)+e,n=await crypto.subtle.importKey("raw",new TextEncoder().encode(r),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),s=await crypto.subtle.sign("HMAC",n,new TextEncoder().encode("obfious-bootstrap-v1:"+t));return p(new Uint8Array(s)).slice(0,10)}async function T(r,e){if(e.length!==10||!/^[0-9a-f]{10}$/.test(e))return!1;for(let t of[-1,0,1])if(await y(r,t)===e)return!0;return!1}async function m(r,e=0){let t=Math.floor(Date.now()/3e5)+e,n=t%7+1,s=await crypto.subtle.importKey("raw",new TextEncoder().encode(r),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),i=await crypto.subtle.sign("HMAC",s,new TextEncoder().encode("obfious-worker-v1:"+t)),o=p(new Uint8Array(i)).slice(0,9);return o.slice(0,n)+"w"+o.slice(n)}async function k(r,e){if(e.length!==10)return!1;let t=e.indexOf("w");if(t<1||t>7||e.lastIndexOf("w")!==t)return!1;let n=e.slice(0,t)+e.slice(t+1);if(!/^[0-9a-f]{9}$/.test(n))return!1;for(let s of[-1,0,1])if(await m(r,s)===e)return!0;return!1}function p(r){return Array.from(r,e=>e.toString(16).padStart(2,"0")).join("")}async function A(r,e){let t=await crypto.subtle.importKey("raw",new TextEncoder().encode(r),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),n=await crypto.subtle.sign("HMAC",t,new TextEncoder().encode(e));return p(new Uint8Array(n))}async function I(r,e){let t=await crypto.subtle.importKey("raw",new TextEncoder().encode(e),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),n=await crypto.subtle.sign("HMAC",t,new TextEncoder().encode(r));return p(new Uint8Array(n))}function S(r){try{let e=r.replace(/-/g,"+").replace(/_/g,"/");for(;e.length%4;)e+="=";let t=Uint8Array.from(atob(e),n=>n.charCodeAt(0));return t.length<9||t[0]!==33?null:p(t.slice(1,9))}catch{return null}}function O(r){let e="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",t=crypto.getRandomValues(new Uint8Array(r));return Array.from(t,n=>e[n%e.length]).join("")}import{Readable as w}from"node:stream";function b(r){let e=r.headers["x-forwarded-proto"]||"http",t=r.headers.host||"localhost",n=`${e}://${t}${r.url}`,s=new Headers;for(let[o,a]of Object.entries(r.headers))a&&s.set(o,Array.isArray(a)?a.join(", "):a);let i=r.method!=="GET"&&r.method!=="HEAD";return new Request(n,{method:r.method,headers:s,body:i?w.toWeb(w.from(r)):null,duplex:"half"})}async function V(r,e){let{creds:t,getUser:n,...s}=e,i=new g({...s,keyId:t.keyId,secret:t.secret,getClientIp:s.getClientIp??(o=>o.headers.get("x-forwarded-for")?.split(",")[0]?.trim()||o.headers.get("x-real-ip")||"unknown"),getPlatformSignals:s.getPlatformSignals??(()=>({}))});r.addHook("onRequest",async(o,a)=>{let l=b(o.raw),h=n?.(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};
|
package/dist/index.d.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
export interface ObfiousConfig {
|
|
2
|
+
keyId: string;
|
|
3
|
+
secret: string;
|
|
2
4
|
apiUrl?: string;
|
|
3
|
-
stableString?: string;
|
|
4
5
|
scriptPath?: string;
|
|
5
6
|
includePaths?: string[];
|
|
6
7
|
excludePaths?: string[];
|
|
@@ -17,8 +18,9 @@ export interface ProtectResult {
|
|
|
17
18
|
deviceId?: string;
|
|
18
19
|
}
|
|
19
20
|
export declare class Obfious {
|
|
20
|
-
constructor(config
|
|
21
|
-
|
|
21
|
+
constructor(config: ObfiousConfig);
|
|
22
|
+
getScriptUrl(): Promise<string>;
|
|
23
|
+
getWorkerUrl(): Promise<string>;
|
|
22
24
|
scriptTag(opts?: { nonce?: string }): Promise<string>;
|
|
23
|
-
protect(request: Request,
|
|
25
|
+
protect(request: Request, user?: string): Promise<ProtectResult>;
|
|
24
26
|
}
|
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 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 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 l=await this.fetchBundle();if(l)return{response:new Response(l,{headers:{"Content-Type":"application/javascript","Cache-Control":"private, max-age=300"}})};break}if(await C(this.creds.secret,c)){let l=await this.fetchWorker();if(l)return{response:new Response(l,{headers:{"Content-Type":"application/javascript","Cache-Control":"private, max-age=300"}})};break}}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 l=e.clone(),h=new Uint8Array(await l.arrayBuffer());if(h.length>0&&h[0]===91)return{response:await this.forwardToApi(e,r.pathname,h)}}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=k(o);if(!a)return{response:new Response(null,{status:401})};let f=t&&this.config.privateKey?await T(t,this.config.privateKey):void 0,u=await this.validateToken(a,o,d,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=I(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():null}catch{return null}}async fetchWorker(){try{let e=await this.authedFetch("/w",{method:"GET"});return e.ok?await e.text():null}catch{return 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 p(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=p(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 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 k(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 I(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,u]of Object.entries(s.queryStringParameters))u!=null&&d.set(f,u);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 g({...n,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 u=r?.(o),c=await i.protect(a,
|
|
1
|
+
var m="x-obfious-key",b="x-obfious-sig",P="x-obfious-ts",x=/\.(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 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 l=await this.fetchBundle();if(l)return{response:new Response(l,{headers:{"Content-Type":"application/javascript","Cache-Control":"private, max-age=300"}})};break}if(await C(this.creds.secret,c)){let l=await this.fetchWorker();if(l)return{response:new Response(l,{headers:{"Content-Type":"application/javascript","Cache-Control":"private, max-age=300"}})};break}}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 l=e.clone(),h=new Uint8Array(await l.arrayBuffer());if(h.length>0&&h[0]===91)return{response:await this.forwardToApi(e,r.pathname,h)}}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=k(o);if(!a)return{response:new Response(null,{status:401})};let f=t&&this.config.privateKey?await T(t,this.config.privateKey):void 0,u=await this.validateToken(a,o,d,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=I(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():null}catch{return null}}async fetchWorker(){try{let e=await this.authedFetch("/w",{method:"GET"});return e.ok?await e.text():null}catch{return 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 p(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=p(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 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 k(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 I(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,u]of Object.entries(s.queryStringParameters))u!=null&&d.set(f,u);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 g({...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 u=r?.(o),c=await i.protect(a,u);return c.response?S(c.response):(c.deviceId&&(o.headers["x-obfious-device-id"]=String(c.deviceId)),e(o,d))}}export{g as Obfious,H as obfiousHandler};
|
package/dist/nextjs.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { Obfious, ObfiousConfig, ObfiousCreds, ProtectResult } from "@obfious/js";
|
|
2
2
|
export { Obfious, ObfiousConfig, ObfiousCreds, ProtectResult };
|
|
3
|
-
export interface
|
|
4
|
-
creds
|
|
3
|
+
export interface ObfiousNextjsConfig extends ObfiousConfig {
|
|
4
|
+
creds?: ObfiousCreds;
|
|
5
5
|
}
|
|
6
|
-
export declare function createObfiousMiddleware(config:
|
|
6
|
+
export declare function createObfiousMiddleware(config: ObfiousNextjsConfig): (request: Request) => Promise<Response | null>;
|
|
7
7
|
export declare function obfiousScriptTag(obfious: Obfious, nonce?: string): Promise<string>;
|
package/dist/nextjs.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var m="x-obfious-key",b="x-obfious-sig",
|
|
1
|
+
var m="x-obfious-key",b="x-obfious-sig",C="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 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();if(l)return{response:new Response(l,{headers:{"Content-Type":"application/javascript","Cache-Control":"private, max-age=300"}})};break}if(await T(this.creds.secret,a)){let l=await this.fetchWorker();if(l)return{response:new Response(l,{headers:{"Content-Type":"application/javascript","Cache-Control":"private, max-age=300"}})};break}}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"&&x.test(r.pathname)){if((e.headers.get("Content-Type")||"")==="application/octet-stream")return{response:await this.forwardStreamToApi(e,r.pathname)};let l=e.clone(),g=new Uint8Array(await l.arrayBuffer());if(g.length>0&&g[0]===91)return{response:await this.forwardToApi(e,r.pathname,g)}}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 i=n.indexOf(".");if(i<1)return{response:new Response(null,{status:401})};let o=n.slice(0,i),u=n.slice(i+1),c=A(o);if(!c)return{response:new Response(null,{status:401})};let w=t&&this.config.privateKey?await R(t,this.config.privateKey):void 0,d=await this.validateToken(c,o,u,w);return d.valid?{response:null,deviceId:d.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():null}catch{return null}}async fetchWorker(){try{let e=await this.authedFetch("/w",{method:"GET"});return e.ok?await e.text():null}catch{return 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 u=await o.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(),i=(t.method||"GET").toUpperCase(),o=`${n}.${i}.${e}`,u=await v(this.creds.secret,o),c=new Headers(t.headers);return c.set(m,this.creds.keyId),c.set(b,u),c.set(C,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"]),i=await crypto.subtle.sign("HMAC",n,new TextEncoder().encode("obfious-worker-v1:"+t)),o=f(new Uint8Array(i)).slice(0,9);return o.slice(0,r)+"w"+o.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 p({...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{p as Obfious,O as createObfiousMiddleware,U as obfiousScriptTag};
|