leakray 0.1.0 → 0.1.1

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/README.md CHANGED
@@ -71,4 +71,4 @@ jobs:
71
71
  ## Web App
72
72
 
73
73
  Prefer a browser UI, interactive 16-check matrix, and Grade A+ README badge?
74
- Visit **[LeakRay Web](https://leakray.leakray-app.workers.dev)**.
74
+ Visit **[LeakRay Web](https://leakray.dev)**.
package/dist/cli.mjs CHANGED
@@ -96,7 +96,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
96
96
  `),matchedPattern:"missing-sri"},humanFix:['1. Add `integrity="sha384-..."` and `crossorigin="anonymous"` to every pinned third-party `<script>` and `<link rel="stylesheet">` tag.',"2. Alternatively, self-host or bundle third-party libraries through your build pipeline so they are served from your own origin.","3. Pin external CDN assets to immutable versioned URLs before generating SRI hashes (e.g., via `openssl dgst -sha384 -binary file.js | openssl base64 -A`)."].join(`
97
97
  `),aiFixPrompt:`LeakRay detected ${t.length} third-party script/stylesheet resource(s) loaded without Subresource Integrity (SRI) on ${i}: ${c.join(", ")}. Update these tags to include valid \`integrity="sha384-..."\` and \`crossorigin="anonymous"\` attributes, or bundle/self-host them in my project.`,references:["https://developer.mozilla.org/en-US/docs/Web/Security/Subresource_Integrity","https://www.srihash.org/"]}]}};var Lg=/https:\/\/([a-z0-9-]+)\.supabase\.co\b/gi,Zg=/\beyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\b/g,j_=new Set(["users","user","profiles","profile","orders","order","payments","payment","customers","customer","invoices","invoice","transactions","accounts","billing","subscriptions","secrets","api_keys","tokens","credentials"]);function A_(e){try{let r=JSON.parse(e);if(typeof r!="object"||r===null||Array.isArray(r))return[];let i=r,o=new Set,t=i.paths;if(typeof t=="object"&&t!==null&&!Array.isArray(t))for(let s of Object.keys(t)){let u=s.replace(/^\/+/,"").split("/")[0]?.toLowerCase();u&&o.add(u)}let n=i.definitions;if(typeof n=="object"&&n!==null&&!Array.isArray(n))for(let s of Object.keys(n))o.add(s.toLowerCase());let a=[];for(let s of o)j_.has(s)&&a.push(s);return a.sort()}catch{return[]}}var bd={id:"supabase-context-check",name:"Supabase Public Context & PostgREST Exposure",category:"baas",async run(e){let r=[{location:e.initialResponse.url,body:e.initialResponse.body},...e.inlineScripts.map(c=>({location:`${e.initialResponse.url}#inline-script-${c.index}`,body:c.body})),...e.jsBundles.map(c=>({location:c.url,body:c.body}))],i=null,o=e.initialResponse.url,t=null;for(let c of r){if(!i){let d=new RegExp(Lg.source,Lg.flags).exec(c.body);d?.[0]&&(i=d[0].toLowerCase(),o=c.location)}if(!t){let l=new RegExp(Zg.source,Zg.flags),d;for(;(d=l.exec(c.body))!==null;){let m=d[0];if(!m)continue;let p=tn(m);if(p&&p.role==="anon"){t=m;break}}}}if(!i)return[];let n=[{id:A("supabase-context-check","anon-info"),ruleId:"supabase-context-check",category:"baas",severity:"info",title:"Supabase Client Detected \u2014 Verify Row-Level Security (RLS)",summary:t?`Detected Supabase project (${i}) with a public anon key in client code. The anon key is intentionally public, so database security relies entirely on PostgreSQL Row-Level Security (RLS).`:`Detected Supabase project (${i}) referenced in client code. Ensure Row-Level Security (RLS) is enabled on every public table.`,impact:"The Supabase anon key is designed to be safe in browsers only when RLS policies restrict every table. Any table without RLS enabled is readable or writable by anyone using the public URL and anon key.",evidence:{location:o,redactedSnippet:t?`${i} (anon key: ${Be(t)})`:i,matchedPattern:"supabase-url"},humanFix:["1. Open your Supabase Dashboard \u2192 Authentication \u2192 Policies (or Database \u2192 Tables).","2. Confirm that **Row Level Security (RLS)** is enabled on every table in the `public` schema.","3. Ensure each table has explicit `SELECT`, `INSERT`, `UPDATE`, and `DELETE` policies scoped to `auth.uid()` where appropriate."].join(`
98
98
  `),aiFixPrompt:`LeakRay detected a Supabase client pointing to ${i}. Audit my Supabase SQL migrations and schema in this repo to verify that \`ALTER TABLE ... ENABLE ROW LEVEL SECURITY;\` and least-privilege RLS policies are configured on every public table.`,references:["https://supabase.com/docs/guides/database/postgres/row-level-security","https://supabase.com/docs/guides/api/api-keys"]}],a=`${i}/rest/v1/`,s={accept:"application/openapi+json"};t&&(s.apikey=t);let u=await e.fetchOnce(a,{method:"GET",headers:s});if(u&&u.status===200){let c=A_(u.body);c.length>0&&n.push({id:A("supabase-context-check","postgrest-openapi"),ruleId:"supabase-context-check",category:"baas",severity:"high",title:"Supabase PostgREST Exposes Sensitive Table Definitions Publicly",summary:`The public PostgREST OpenAPI endpoint (${a}) lists sensitive-looking tables (${c.join(", ")}) to unauthenticated anon requests.`,impact:"Exposing sensitive table schemas on the public `public` schema increases attack surface and often indicates tables that may be missing strict Row-Level Security (RLS) policies or should be moved to a private schema.",evidence:{location:u.url,redactedSnippet:`Exposed tables: ${c.join(", ")}`,matchedPattern:"postgrest-openapi-sensitive-tables"},humanFix:[`1. Verify strict Row-Level Security (RLS) policies on: ${c.join(", ")}.`,"2. Move internal/sensitive tables out of the exposed `public` schema into a private schema (e.g., `private`), or restrict API exposed schemas in Supabase Dashboard \u2192 Settings \u2192 API.","3. Revoke `anon` role grants (`REVOKE ALL ON TABLE ... FROM anon;`) for tables that unauthenticated visitors should never access."].join(`
99
- `),aiFixPrompt:`LeakRay detected that Supabase PostgREST at ${a} publicly lists sensitive tables (${c.join(", ")}) for the anon role. Write a Supabase SQL migration that enables RLS on these tables, revokes unnecessary \`anon\` grants, and restricts access to authenticated owners via \`auth.uid()\`.`,references:["https://supabase.com/docs/guides/database/postgres/row-level-security","https://supabase.com/docs/guides/api/securing-your-api"]})}return n}};var mo=[vd,pd,ad,sd,cd,od,bd,fd,ud,hd,id,$d,nd,td,yd,gd],_d=mo.map(({id:e,name:r,category:i})=>({id:e,name:r,category:i}));var Vg={critical:0,high:1,medium:2,low:3,info:4};async function xd(e){let r=Date.now(),i=e.rules??mo,o=await ed({targetUrl:e.targetUrl,normalizedHost:e.normalizedHost,fetcher:e.fetcher,signal:e.signal}),t=await Promise.allSettled(i.map(l=>l.run(o))),n=[],a=new Set;for(let l of t)if(l.status==="fulfilled")for(let d of l.value)a.has(d.id)||(a.add(d.id),n.push(d));n.sort((l,d)=>{let m=Vg[l.severity]-Vg[d.severity];return m!==0?m:l.id.localeCompare(d.id)});let{score:s,grade:u}=Wl(n),c=Math.max(0,Date.now()-r);return{score:s,grade:u,detectedStack:o.detectedStack,findings:n,durationMs:c}}var Yt="0.1.0",kd="https://leakray.leakray-app.workers.dev",Fg={critical:0,high:1,medium:2,low:3,info:4};function T_(e){return je.includes(e)}function O_(e,r){let i=e.trim();if(!i)throw new Error("URL cannot be empty.");let o=/^https?:\/\//i.test(i)?i:/^(localhost|127\.0\.0\.1|\[::1\])(?::\d+)?(?:\/|$)/i.test(i)?`http://${i}`:`https://${i}`;if(!r){let a=Qr(o);if(qt(a.normalizedHost))throw new Error(`Refusing to scan private or local host "${a.normalizedHost}" without --allow-local.`);return{targetUrl:a.targetUrl,normalizedHost:a.normalizedHost}}let t;try{t=new URL(o)}catch{throw new Error(`Invalid URL: "${e}"`)}if(t.protocol!=="http:"&&t.protocol!=="https:")throw new Error("Only http:// and https:// URLs are supported.");if(t.username||t.password)throw new Error("URLs with embedded credentials are not supported.");t.hash="";let n=t.hostname.toLowerCase().replace(/\.$/,"");return{targetUrl:t.toString(),normalizedHost:n}}function Mg(e,r=process.env){let i=null,o=!1,t=!1,n=!1,a=null,s=2e4,u=!!r.NO_COLOR;for(let c=0;c<e.length;c+=1){let l=e[c];if(l){if(l==="-h"||l==="--help")return{kind:"help"};if(l==="-v"||l==="--version")return{kind:"version"};if(l==="--allow-local"){o=!0;continue}if(l==="--json"){t=!0;continue}if(l==="--ai-prompt"){n=!0;continue}if(l==="--no-color"){u=!0;continue}if(l==="--fail-on"||l.startsWith("--fail-on=")){let d=l.includes("=")?l.slice(10):e[++c],m=d?.toLowerCase()??"";if(!T_(m))return{kind:"error",message:`Invalid --fail-on severity "${d??""}". Expected one of: ${je.join(", ")}.`};a=m;continue}if(l==="--timeout"||l.startsWith("--timeout=")){let d=l.includes("=")?l.slice(10):e[++c],m=Number(d);if(!Number.isFinite(m)||m<1e3||m>12e4)return{kind:"error",message:`Invalid --timeout "${d??""}". Expected milliseconds between 1000 and 120000.`};s=Math.round(m);continue}if(l.startsWith("-"))return{kind:"error",message:`Unknown option "${l}". Run "leakray --help" for usage.`};if(i!==null)return{kind:"error",message:`Unexpected extra argument "${l}". Provide a single target URL.`};i=l}}if(!i)return{kind:"help"};try{let{targetUrl:c,normalizedHost:l}=O_(i,o);return{kind:"run",options:{targetUrl:c,normalizedHost:l,allowLocal:o,json:t,aiPrompt:n,failOn:a,timeoutMs:s,noColor:u}}}catch(c){return{kind:"error",message:c instanceof Error?c.message:"Invalid target URL."}}}function Jg(e,r){if(!r)return!1;let i=Fg[r];return e.some(o=>Fg[o.severity]<=i)}function Bg(){return[`LeakRay v${Yt} \u2014 Passive URL security scanner (16 read-only checks)`,"","Usage:"," npx leakray <url> [options]","","Examples:"," npx leakray https://myapp.com"," npx leakray http://localhost:3000 --allow-local"," npx leakray https://preview.myapp.com --fail-on high"," npx leakray https://myapp.com --ai-prompt"," npx leakray https://myapp.com --json","","Options:"," --allow-local Allow scanning localhost / private network URLs"," --fail-on <severity> Exit with code 1 if any finding >= severity"," (critical | high | medium | low | info)"," --ai-prompt Print copy-paste AI fix prompts for Cursor/Claude Code"," --json Output machine-readable JSON"," --timeout <ms> Overall scan timeout in ms (default: 20000)"," --no-color Disable ANSI colors"," -v, --version Print version"," -h, --help Show this help","",`Web scanner & docs: ${kd}/cli`].join(`
99
+ `),aiFixPrompt:`LeakRay detected that Supabase PostgREST at ${a} publicly lists sensitive tables (${c.join(", ")}) for the anon role. Write a Supabase SQL migration that enables RLS on these tables, revokes unnecessary \`anon\` grants, and restricts access to authenticated owners via \`auth.uid()\`.`,references:["https://supabase.com/docs/guides/database/postgres/row-level-security","https://supabase.com/docs/guides/api/securing-your-api"]})}return n}};var mo=[vd,pd,ad,sd,cd,od,bd,fd,ud,hd,id,$d,nd,td,yd,gd],_d=mo.map(({id:e,name:r,category:i})=>({id:e,name:r,category:i}));var Vg={critical:0,high:1,medium:2,low:3,info:4};async function xd(e){let r=Date.now(),i=e.rules??mo,o=await ed({targetUrl:e.targetUrl,normalizedHost:e.normalizedHost,fetcher:e.fetcher,signal:e.signal}),t=await Promise.allSettled(i.map(l=>l.run(o))),n=[],a=new Set;for(let l of t)if(l.status==="fulfilled")for(let d of l.value)a.has(d.id)||(a.add(d.id),n.push(d));n.sort((l,d)=>{let m=Vg[l.severity]-Vg[d.severity];return m!==0?m:l.id.localeCompare(d.id)});let{score:s,grade:u}=Wl(n),c=Math.max(0,Date.now()-r);return{score:s,grade:u,detectedStack:o.detectedStack,findings:n,durationMs:c}}var Yt="0.1.1",kd="https://leakray.dev",Fg={critical:0,high:1,medium:2,low:3,info:4};function T_(e){return je.includes(e)}function O_(e,r){let i=e.trim();if(!i)throw new Error("URL cannot be empty.");let o=/^https?:\/\//i.test(i)?i:/^(localhost|127\.0\.0\.1|\[::1\])(?::\d+)?(?:\/|$)/i.test(i)?`http://${i}`:`https://${i}`;if(!r){let a=Qr(o);if(qt(a.normalizedHost))throw new Error(`Refusing to scan private or local host "${a.normalizedHost}" without --allow-local.`);return{targetUrl:a.targetUrl,normalizedHost:a.normalizedHost}}let t;try{t=new URL(o)}catch{throw new Error(`Invalid URL: "${e}"`)}if(t.protocol!=="http:"&&t.protocol!=="https:")throw new Error("Only http:// and https:// URLs are supported.");if(t.username||t.password)throw new Error("URLs with embedded credentials are not supported.");t.hash="";let n=t.hostname.toLowerCase().replace(/\.$/,"");return{targetUrl:t.toString(),normalizedHost:n}}function Mg(e,r=process.env){let i=null,o=!1,t=!1,n=!1,a=null,s=2e4,u=!!r.NO_COLOR;for(let c=0;c<e.length;c+=1){let l=e[c];if(l){if(l==="-h"||l==="--help")return{kind:"help"};if(l==="-v"||l==="--version")return{kind:"version"};if(l==="--allow-local"){o=!0;continue}if(l==="--json"){t=!0;continue}if(l==="--ai-prompt"){n=!0;continue}if(l==="--no-color"){u=!0;continue}if(l==="--fail-on"||l.startsWith("--fail-on=")){let d=l.includes("=")?l.slice(10):e[++c],m=d?.toLowerCase()??"";if(!T_(m))return{kind:"error",message:`Invalid --fail-on severity "${d??""}". Expected one of: ${je.join(", ")}.`};a=m;continue}if(l==="--timeout"||l.startsWith("--timeout=")){let d=l.includes("=")?l.slice(10):e[++c],m=Number(d);if(!Number.isFinite(m)||m<1e3||m>12e4)return{kind:"error",message:`Invalid --timeout "${d??""}". Expected milliseconds between 1000 and 120000.`};s=Math.round(m);continue}if(l.startsWith("-"))return{kind:"error",message:`Unknown option "${l}". Run "leakray --help" for usage.`};if(i!==null)return{kind:"error",message:`Unexpected extra argument "${l}". Provide a single target URL.`};i=l}}if(!i)return{kind:"help"};try{let{targetUrl:c,normalizedHost:l}=O_(i,o);return{kind:"run",options:{targetUrl:c,normalizedHost:l,allowLocal:o,json:t,aiPrompt:n,failOn:a,timeoutMs:s,noColor:u}}}catch(c){return{kind:"error",message:c instanceof Error?c.message:"Invalid target URL."}}}function Jg(e,r){if(!r)return!1;let i=Fg[r];return e.some(o=>Fg[o.severity]<=i)}function Bg(){return[`LeakRay v${Yt} \u2014 Passive URL security scanner (16 read-only checks)`,"","Usage:"," npx leakray <url> [options]","","Examples:"," npx leakray https://myapp.com"," npx leakray http://localhost:3000 --allow-local"," npx leakray https://preview.myapp.com --fail-on high"," npx leakray https://myapp.com --ai-prompt"," npx leakray https://myapp.com --json","","Options:"," --allow-local Allow scanning localhost / private network URLs"," --fail-on <severity> Exit with code 1 if any finding >= severity"," (critical | high | medium | low | info)"," --ai-prompt Print copy-paste AI fix prompts for Cursor/Claude Code"," --json Output machine-readable JSON"," --timeout <ms> Overall scan timeout in ms (default: 20000)"," --no-color Disable ANSI colors"," -v, --version Print version"," -h, --help Show this help","",`Web scanner & docs: ${kd}/cli`].join(`
100
100
  `)}import{lookup as D_}from"node:dns/promises";function N_(e){return e===301||e===302||e===303||e===307||e===308}async function U_(e,r){if(e.protocol!=="http:"&&e.protocol!=="https:")throw new Error(`Unsupported protocol "${e.protocol}".`);if(e.username||e.password)throw new Error("URLs with embedded credentials are not allowed.");if(r)return;let i=e.hostname.toLowerCase().replace(/^\[|\]$/g,"");if(qt(i))throw new Error(`Blocked private/reserved host "${i}". Pass --allow-local to scan local apps.`);let o=await D_(i,{all:!0});if(o.length===0)throw new Error(`Could not resolve DNS for "${i}".`);for(let t of o)if(t.family===4?Xt(t.address):uo(t.address))throw new Error(`Blocked private IP ${t.address} for "${i}". Pass --allow-local to scan local apps.`)}async function E_(e,r){if(!e.body)return{body:"",truncated:!1};let i=e.body.getReader(),o=[],t=0,n=!1;try{for(;;){let{done:u,value:c}=await i.read();if(u)break;if(!c||c.byteLength===0)continue;let l=r-t;if(l<=0){n=!0,await i.cancel();break}if(c.byteLength>l){o.push(c.subarray(0,l)),t+=l,n=!0,await i.cancel();break}o.push(c),t+=c.byteLength}}finally{i.releaseLock()}let a=new Uint8Array(t),s=0;for(let u of o)a.set(u,s),s+=u.byteLength;return{body:new TextDecoder("utf-8",{fatal:!1}).decode(a),truncated:n}}function C_(e){let r={};if(e.forEach((i,o)=>{let t=o.toLowerCase();r[t]=t in r?`${r[t]}, ${i}`:i}),typeof e.getSetCookie=="function"){let i=e.getSetCookie();i.length>0&&(r["set-cookie"]=i.join(", "))}return r}function Hg(e){let r=e.timeoutMs??ke.perRequestTimeoutMs,i=e.maxResponseBytes??ke.maxResponseBytes,o=e.maxRedirects??ke.maxRedirects,t=e.userAgent??$o;return{async fetch(n,a={}){let s=a.method??"GET";if(s!=="GET"&&s!=="HEAD")throw new Error("LeakRay only performs passive GET/HEAD requests.");let u=new URL(n),c=0;for(;;){await U_(u,e.allowLocal);let l=[AbortSignal.timeout(r)];a.signal&&l.push(a.signal);let d=AbortSignal.any(l),m=await fetch(u.toString(),{method:s,headers:{"user-agent":t,accept:"text/html,application/xhtml+xml,application/json,text/javascript,*/*;q=0.8",...a.headers},redirect:"manual",signal:d}),p=C_(m.headers);if(N_(m.status)&&p.location){if(await m.body?.cancel(),c>=o)throw new Error(`Exceeded max redirects (${o}).`);u=new URL(p.location,u),c+=1;continue}let{body:v,truncated:y}=s==="HEAD"?{body:"",truncated:!1}:await E_(m,i);return{url:u.toString(),status:m.status,headers:p,body:v,truncated:y}}}}}function R_(e){if(!e){let i=o=>o;return{bold:i,dim:i,green:i,teal:i,yellow:i,orange:i,red:i,blue:i}}let r=i=>o=>`\x1B[${i}m${o}\x1B[0m`;return{bold:r("1"),dim:r("2"),green:r("32"),teal:r("36"),yellow:r("33"),orange:r("38;5;208"),red:r("31"),blue:r("34")}}function L_(e,r){let i=e.toUpperCase().padEnd(8);switch(e){case"critical":return r.bold(r.red(i));case"high":return r.bold(r.orange(i));case"medium":return r.bold(r.yellow(i));case"low":return r.green(i);case"info":return r.blue(i)}}function Z_(e,r,i){let o=`${r}/100 (${e})`;return e==="A+"||e==="A"?i.bold(i.green(o)):e==="B"||e==="C"?i.bold(i.yellow(o)):i.bold(i.red(o))}function V_(e){let r=[...e.detectedStack.frameworks,...e.detectedStack.hosting,...e.detectedStack.baas,...e.detectedStack.payments,...e.detectedStack.other];return r.length>0?r.join(" \xB7 "):"Generic web app"}function Kg(e){let{targetUrl:r,result:i,aiPrompt:o,useColor:t}=e,n=R_(t),a=[],s=_d.length,u=new Set(i.findings.filter(l=>l.severity!=="info").map(l=>l.ruleId)),c=Math.max(0,s-u.size);if(a.push(""),a.push(`${n.bold(n.teal("LeakRay"))} ${n.dim(`v${Yt} \xB7 Passive URL Security Scanner`)}`),a.push(n.dim("\u2500".repeat(62))),a.push(` Target : ${n.bold(r)}`),a.push(` Score : ${Z_(i.grade,i.score,n)}`),a.push(` Checks : ${c}/${s} passed \xB7 ${i.findings.length} finding${i.findings.length===1?"":"s"} \xB7 ${(i.durationMs/1e3).toFixed(2)}s`),a.push(` Stack : ${V_(i)}`),a.push(n.dim("\u2500".repeat(62))),i.findings.length===0)a.push(""),a.push(` ${n.green("\u2713")} No issues detected across all ${s} passive checks.`);else{a.push("");for(let l of i.findings){if(a.push(` ${L_(l.severity,n)} ${n.bold(l.title)} ${n.dim(`[${l.ruleId}]`)}`),l.evidence?.location&&a.push(` ${n.dim("Where:")} ${l.evidence.location}`),l.evidence?.redactedSnippet&&a.push(` ${n.dim("Proof:")} ${l.evidence.redactedSnippet}`),a.push(` ${n.dim("Fix:")} ${l.humanFix}`),o&&l.aiFixPrompt){a.push(` ${n.teal("AI Fix Prompt:")}`);for(let d of l.aiFixPrompt.split(`
101
101
  `))a.push(` ${n.dim(d)}`)}a.push("")}}return a.push(n.dim("\u2500".repeat(62))),a.push(` ${n.dim("Shareable report & Grade A+ badge:")} ${kd}`),a.push(""),a.join(`
102
102
  `)}async function F_(){let e=Mg(process.argv.slice(2));if(e.kind==="help"){process.stdout.write(`${Bg()}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "leakray",
3
- "version": "0.1.0",
3
+ "version": "0.1.1",
4
4
  "description": "Zero-config passive URL security scanner for modern full-stack and AI-built web apps (Next.js, Vite, Supabase, Firebase, Stripe).",
5
5
  "keywords": [
6
6
  "security",
@@ -16,7 +16,7 @@
16
16
  "env",
17
17
  "audit"
18
18
  ],
19
- "homepage": "https://leakray.leakray-app.workers.dev/cli",
19
+ "homepage": "https://leakray.dev/cli",
20
20
  "repository": {
21
21
  "type": "git",
22
22
  "url": "https://github.com/mahmoudghonem/leakray.git",