cc-safety-net 2.1.0 → 2.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.
@@ -1,8 +1,8 @@
1
1
  // cc-safety-net managed Amp plugin. Do not edit. Reinstall with: npx -y cc-safety-net install --amp
2
- // version: 2.1.0
2
+ // version: 2.1.1
3
3
  // @bun
4
4
  var Pw=Object.defineProperty;var kw=(e)=>e;function Aw(e,t){this[e]=kw.bind(null,t)}var mn=(e,t)=>{for(var n in t)Pw(e,n,{get:t[n],enumerable:!0,configurable:!0,set:Aw.bind(t,n)})};import{randomBytes as CR}from"crypto";import{appendFileSync as wR,mkdirSync as RR}from"fs";import{homedir as ER,userInfo as PR}from"os";import{isAbsolute as kR,join as Il}from"path";var Tw=[/\bgh[pousr]_[A-Za-z0-9]{20,}\b/g,/\bgithub_pat_[A-Za-z0-9_]{20,}\b/g,/\bglpat-[A-Za-z0-9_-]{20,}\b/g,/\bxox[abeprs]-[A-Za-z0-9-]{20,}\b/g,/\bnpm_[A-Za-z0-9_]{20,}\b/g,/\bpypi-[A-Za-z0-9_-]{20,}\b/g,/\b[rs]k_(?:live|test)_[A-Za-z0-9_]{20,}\b/g,/\bsk-[A-Za-z0-9_-]{20,}\b/g,/\bsk_[A-Za-z0-9]{20,}\b/g,/\bgsk_[A-Za-z0-9]{52,}\b/g,/\bxai-[A-Za-z0-9_-]{80,}\b/g,/\bpplx-[A-Za-z0-9_-]{20,}\b/g,/\bbastn_[A-Za-z0-9]{16,}\b/g,/\btgp_v1_[A-Za-z0-9_-]{43,}\b/g,/\bflp_[A-Za-z0-9]{10,}\b/g,/\bwfr_[A-Za-z0-9]{20,}\b/g,/\bfwp?_[A-Za-z0-9_-]{20,}\b/g,/\btp-[A-Za-z0-9_-]{20,}\b/g,/\bpsk-[A-Za-z0-9_-]{8,}-[A-Za-z0-9_-]{8,}\b/g,/\b[a-f0-9]{32}\.[A-Za-z0-9]{16}\b/g];function kt(e){let t=e.replace(/\b((?:DATABASE|POSTGRES|POSTGRESQL|MYSQL|MARIADB|REDIS|MONGO(?:DB)?|DB)_DSN|CONNECTION_STRING)=("[^"]*"|'[^']*'|[^\s]+(?:\s+[A-Z_][A-Z0-9_]*=[^\s]+)*)/gi,"$1=<redacted>").replace(/\b((?:DATABASE|POSTGRES|POSTGRESQL|MYSQL|MARIADB|REDIS|MONGO(?:DB)?|DB)_(?:URL|URI|CONNECTION_STRING))=("[^"]*"|'[^']*'|[^\s]+)/gi,"$1=<redacted>").replace(/\b([A-Z0-9_]*(?:TOKEN|SECRET|PASSWORD|PASS|KEY|CREDENTIALS)[A-Z0-9_]*)=("[^"]*"|'[^']*'|[^\s]+)/gi,"$1=<redacted>");return Iw(t)}function Iw(e){let t=e.replace(/-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?-----END [A-Z ]*PRIVATE KEY-----/gi,"<redacted>").replace(/((?:(['"])(?:authorization|cookie|x-api-key|api-key)\2|(?:authorization|cookie|x-api-key|api-key))\s*:\s*)(['"])(?:\\[^\r\n]|(?!\3)[^\\\r\n])*\3/gi,"$1$3<redacted>$3").replace(/(['"]?\s*(?:authorization|cookie|x-api-key|api-key)\s*:(?!\s*(?:"<redacted>"|'<redacted>'))\s*)([^'"\r\n]+)(['"]?)/gi,"$1<redacted>$3").replace(/\b([a-z][a-z0-9+.-]*:\/\/)([^\s/:@]+):([^\s@/]+)@/gi,"$1<redacted>:<redacted>@").replace(/\b([a-z][a-z0-9+.-]*:\/\/)([^\s/@:]+)@/gi,"$1<redacted>@").replace(/(^|[\s?&;|])((?:x-amz-signature|x-goog-signature|sig|signature)=)(?:"[^"\r\n]*"|'[^'\r\n]*'|[^&#\s'"`;|<>()]*)/gi,"$1$2<redacted>").replace(/(^|\s)((?:-u|--user)(?:\s+|=))([^\s:]+):([^\s]+)/g,"$1$2<redacted>:<redacted>");for(let n of Tw)t=t.replace(n,"<redacted>");return t.replace(/\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{6,}\.[A-Za-z0-9_-]{6,}\b/g,"<redacted>").replace(/\b(?:AKIA|ASIA)[A-Z0-9]{16}\b/g,"<redacted>")}import{lstatSync as Hh,readdirSync as uR,readFileSync as Yh,rmdirSync as dR,statSync as Vh,unlinkSync as mR,utimesSync as fR,writeFileSync as pR}from"fs";import{dirname as gR,join as qn}from"path";var Ti=30,Sl=1,xl=365;function Ii(e){if(typeof e!=="number"||!Number.isInteger(e))return 30;if(e<1)return 1;return e>365?365:e}import{homedir as Kw}from"os";import{dirname as Ut,isAbsolute as Yw,join as jt,relative as Jw,resolve as Tt,sep as Xw}from"path";import{closeSync as Ow,constants as Oh,fstatSync as zw,fsyncSync as GM,lstatSync as zh,mkdirSync as ZM,openSync as Nw,readdirSync as BM,readFileSync as Dw,realpathSync as Oi,renameSync as UM,rmdirSync as jM,statSync as $w,unlinkSync as HM,writeFileSync as VM}from"fs";import{isAbsolute as Nh,join as Dh,normalize as Mw,parse as Lw,relative as _l,resolve as Cl,sep as wl}from"path";var Ww=Symbol("PolicyFilesystemScope"),Fw=Symbol("PolicyFilesystemTarget"),Gw=Oh.O_NOFOLLOW??0;class ae extends Error{constructor(e){super(`Unable to access ${e} filesystem safely.`);this.name="PolicyFilesystemError"}}function Bt(e,t){return{[Ww]:!0,root:Cl(e),label:t}}function $h(e,t){let n=Mw(t);if(t===""||Nh(t)||n===".."||n.startsWith(`..${wl}`))throw new ae(e.label);return{[Fw]:!0,scope:e,relativePath:n,path:Dh(e.root,n)}}function At(e,t){let n=_l(e.root,Cl(t));return $h(e,n)}function Ni(e,t="rules policy"){let n=Cl(e),r=Lw(n).dir;return $h(Bt(r,t),_l(r,n))}function fn(e){try{if(!zi(e,!1).exists)return null;let n=Nw(e.path,Oh.O_RDONLY|Gw);try{let r=zw(n);if(!r.isFile())throw new ae(e.scope.label);let o=Dw(n,"utf-8"),i=zh(e.path);if(!i.isFile()||i.isSymbolicLink()||r.dev!==i.dev||r.ino!==i.ino)throw new ae(e.scope.label);return zi(e,!1),o}finally{Ow(n)}}catch(t){Uw(e.scope.label,t)}}function Mh(e,t){if(e.path===t.path)return!0;try{if(!zi(e,!1).exists||!zi(t,!1).exists)return!1;return Oi(e.path)===Oi(t.path)}catch(n){if(n instanceof ae)throw n;throw new ae(e.scope.label)}}function zi(e,t,n="file"){let r=Zw(e.scope);if(!r)return{exists:!1};let o=e.relativePath.split(wl);for(let i of o.keys()){let s=Dh(e.scope.root,...o.slice(0,i+1)),a=Lh(s);if(!a){if(i===o.length-1&&t)return{exists:!1};return{exists:!1}}if(a.isSymbolicLink())throw new ae(e.scope.label);if(i<o.length-1&&!a.isDirectory())throw new ae(e.scope.label);if(i===o.length-1&&(n==="file"?!a.isFile():!a.isDirectory()))throw new ae(e.scope.label);Bw(r,Oi(s),e.scope.label)}return{exists:!0}}function Zw(e){if(!Lh(e.root))return null;if(!$w(e.root).isDirectory())throw new ae(e.label);return Oi(e.root)}function Bw(e,t,n){let r=_l(e,t);if(r===".."||r.startsWith(`..${wl}`)||Nh(r))throw new ae(n)}function Lh(e){try{return zh(e)}catch(t){if(jw(t)&&t.code==="ENOENT")return null;throw t}}function Uw(e,t){if(t instanceof ae)throw t;throw new ae(e)}function jw(e){return e instanceof Error&&"code"in e}var ut=/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/,Rl="rulebook.json",El=".cc-safety-net/rules";var Wh=/^([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+)#(.+)$/;var Hw=/^[A-Za-z0-9._-]+$/,Vw=".cc-safety-net/rules".replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),qw="rulebook.json".replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),Fh=new RegExp(`^${Vw}/(${ut.source.slice(1,-1)})/${qw}$`);function Gh(e){return`.cc-safety-net/rules/${e}/rulebook.json`}function Xr(e){if($i(e))try{return Di(e),null}catch(t){return t instanceof Error?t.message:String(t)}return ut.test(e)?null:`Local rulebook sources must be bare names matching ${ut}: ${e}`}function Di(e){if(e.startsWith("github:"))throw Error(`Invalid rulebook source: ${e}`);let t=e.match(Wh);if(!t?.[1]||!t[2]||!t[3])throw Error(`Invalid GitHub rulebook source: ${e}`);let[n,r,...o]=t[3].split("/");if(!n||!Hw.test(n))throw Error(`GitHub rulebook refs must be a single path segment: ${e}`);if(!r||o.length>0||!ut.test(r))throw Error(`GitHub rulebook sources must be owner/repo#ref/<rulebook-name>: ${e}`);return{owner:t[1],repo:t[2],ref:n,path:Gh(r),name:r}}function $i(e){return Wh.test(e)}var Bh="rule.json",Mi="policy.json",Qw="rule.lock";var Uh=".cc-safety-net",eR="rules",Zh="cache",tR="CC_SAFETY_NET_HOME",Ht="`cc-safety-net rule sync`";function nR(e){return Tt(e??process.cwd(),El)}function rR(e){return jt(nR(e),Bh)}function pn(e){return e?.userConfigDir??(e?.userConfigPath?Ut(e.userConfigPath):jt(oR(),eR))}function oR(){let e=process.env[tR];return e?Tt(e):jt(Kw(),Uh)}function iR(e){return jt(pn(e),Bh)}function Qr(e){return jt(Ut(e),Qw)}function jh(e){let t=e.userConfigPath??iR(e),n=e.projectConfigPath??rR(e.cwd),r=sR(t,e),o=aR(n,e);return{userConfigPath:t,projectConfigPath:n,userLockPath:Qr(t),projectLockPath:Qr(n),userScope:r,projectScope:o,userConfigTarget:At(r,t),projectConfigTarget:At(o,n),userLockTarget:At(r,Qr(t)),projectLockTarget:At(o,Qr(n))}}function sR(e,t){let n=t.userConfigPath?Ut(Ut(Tt(t.userConfigPath))):Ut(Tt(t.userConfigDir??pn(t)));return Bt(n,"user policy")}function aR(e,t){let n=Tt(t.cwd??process.cwd()),r=Tt(e),o=Jw(n,r);if(o!==".."&&!o.startsWith(`..${Xw}`)&&!Yw(o))return Bt(n,"project policy");return Bt(Ut(Ut(r)),"project policy")}function Pl(e,t){let n=e.digest.startsWith("sha256:")?e.digest.slice(7):e.digest;return jt(lR(t),"rulebooks",`${cR(e)}--${n.slice(0,12)}`,Rl)}function kl(e,t){let n=t;return{cacheConfigDir:e,cwd:t.cwd,global:n.global}}function cR(e){return(e.kind==="github"&&e.display_ref?`${e.owner}/${e.repo}#${e.display_ref}/${e.name}`:e.spec).toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"rulebook"}function lR(e){let t=e?.cacheConfigDir??pn(e),n=e;if(n&&!n.global&&n.cwd&&Tt(t)===Tt(n.cwd))return jt(Tt(n.cwd),Uh,Zh);return jt(Ut(t),Zh)}var Tl=86400000,hR=".last-prune",yR=/^\d{4}-\d{2}$/,bR=/^((\d{4}-\d{2})-\d{2})-.+\.jsonl$/,qh=(e)=>Math.floor(e/Tl);function vR(e){try{let t=qn(gR(pn(e)),Mi),n=JSON.parse(Yh(t,"utf-8"));return Ii(n?.audit?.retention_days)}catch{return Ti}}function Jh(e,t=()=>new Date){try{let n=t().getTime();if(!Vh(e,{throwIfNoEntry:!1})?.isDirectory())return;let r=qn(e,hR),o=Vh(r,{throwIfNoEntry:!1})?.mtimeMs;if(o!==void 0&&qh(o)===qh(n))return;let i=n-vR()*Tl,s=new Date(n).toISOString().slice(0,7);for(let a of Al(e)){if(a.isDirectory()){SR(qn(e,a.name),i,s);continue}if(a.isFile()&&a.name.endsWith(".jsonl"))xR(qn(e,a.name),i)}pR(r,"",{mode:384}),fR(r,n/1000,n/1000)}catch{}}function SR(e,t,n){for(let r of Al(e)){if(!r.isDirectory()||!yR.test(r.name))continue;let o=qn(e,r.name);for(let i of Al(o)){if(!i.isFile())continue;let s=bR.exec(i.name);if(!s||s[2]!==r.name)continue;let a=Date.parse(`${s[1]}T00:00:00.000Z`)+Tl;if(!Number.isFinite(a)||a>=t)continue;Xh(qn(o,i.name))}if(r.name!==n)Kh(o)}Kh(e)}function xR(e,t){try{let n=Hh(e);if(n.mtimeMs>=t)return;let r=Yh(e,"utf-8").split(`
5
- `).filter((o)=>o.trim()).map(_R);if(r.length===0)return;if(r.some((o)=>o===void 0||o>=t))return;if(Hh(e).mtimeMs!==n.mtimeMs)return;Xh(e)}catch{}}function _R(e){try{let t=JSON.parse(e).ts,n=typeof t==="string"?Date.parse(t):Number.NaN;return Number.isFinite(n)?n:void 0}catch{return}}function Al(e){try{return uR(e,{withFileTypes:!0,encoding:"utf8"})}catch{return[]}}function Xh(e){try{mR(e)}catch{}}function Kh(e){try{dR(e)}catch{}}var AR="2.1.0",TR=1e4,IR=2000,OR=256,zR=32768;function NR(e){let t=e.trim();if(!t)return null;let n=t.replace(/[^A-Za-z0-9_.-]+/g,"_");if(n=n.replace(/^[._-]+|[._-]+$/g,"").slice(0,128),!n||n==="."||n==="..")return null;return n}function DR(e){return(e??"").replace(/[^A-Za-z0-9]/g,"-").slice(0,180)||"no-cwd"}function Ol(e,t,n,r,o,i={}){let s=NR(e);if(!s)return;let a=i.homeDir??Qh();if(!a)return;let c=$R(a);if(!c)return;try{let l=(i.now??(()=>new Date))().toISOString(),u=Li(kt(t),i.failureStage?Number.POSITIVE_INFINITY:TR),d=Li(kt(n),IR),f=i.toolName?Li(kt(i.toolName),OR):void 0,m=o===null?void 0:Li(kt(o),zR),p=Il(c,DR(m?.value??null),l.slice(0,7));RR(p,{recursive:!0,mode:448});let h=Il(p,`${l.slice(0,10)}-${s}.jsonl`),b={ts:l,id:(i.createId??(()=>CR(8).toString("hex")))(),v:AR,sessionId:s,decision:i.decision??"deny",agent:i.agent,shape:i.shape,level:i.level,configFallback:i.configFallback,toolName:f?.value,command:u.value,segment:d.value,...u.truncated||d.truncated||f?.truncated||m?.truncated?{truncated:!0}:{},reason:r,ruleId:i.ruleId,intent:i.intent,failureStage:i.failureStage,errorCode:i.errorCode,cwd:m?.value??null};wR(h,`${JSON.stringify(b)}
5
+ `).filter((o)=>o.trim()).map(_R);if(r.length===0)return;if(r.some((o)=>o===void 0||o>=t))return;if(Hh(e).mtimeMs!==n.mtimeMs)return;Xh(e)}catch{}}function _R(e){try{let t=JSON.parse(e).ts,n=typeof t==="string"?Date.parse(t):Number.NaN;return Number.isFinite(n)?n:void 0}catch{return}}function Al(e){try{return uR(e,{withFileTypes:!0,encoding:"utf8"})}catch{return[]}}function Xh(e){try{mR(e)}catch{}}function Kh(e){try{dR(e)}catch{}}var AR="2.1.1",TR=1e4,IR=2000,OR=256,zR=32768;function NR(e){let t=e.trim();if(!t)return null;let n=t.replace(/[^A-Za-z0-9_.-]+/g,"_");if(n=n.replace(/^[._-]+|[._-]+$/g,"").slice(0,128),!n||n==="."||n==="..")return null;return n}function DR(e){return(e??"").replace(/[^A-Za-z0-9]/g,"-").slice(0,180)||"no-cwd"}function Ol(e,t,n,r,o,i={}){let s=NR(e);if(!s)return;let a=i.homeDir??Qh();if(!a)return;let c=$R(a);if(!c)return;try{let l=(i.now??(()=>new Date))().toISOString(),u=Li(kt(t),i.failureStage?Number.POSITIVE_INFINITY:TR),d=Li(kt(n),IR),f=i.toolName?Li(kt(i.toolName),OR):void 0,m=o===null?void 0:Li(kt(o),zR),p=Il(c,DR(m?.value??null),l.slice(0,7));RR(p,{recursive:!0,mode:448});let h=Il(p,`${l.slice(0,10)}-${s}.jsonl`),b={ts:l,id:(i.createId??(()=>CR(8).toString("hex")))(),v:AR,sessionId:s,decision:i.decision??"deny",agent:i.agent,shape:i.shape,level:i.level,configFallback:i.configFallback,toolName:f?.value,command:u.value,segment:d.value,...u.truncated||d.truncated||f?.truncated||m?.truncated?{truncated:!0}:{},reason:r,ruleId:i.ruleId,intent:i.intent,failureStage:i.failureStage,errorCode:i.errorCode,cwd:m?.value??null};wR(h,`${JSON.stringify(b)}
6
6
  `,{encoding:"utf-8",mode:384}),Jh(c,i.now)}catch{}}function Li(e,t){return{value:e.slice(0,t),truncated:e.length>t}}function Qh(e=process.env.CC_SAFETY_NET_AUDIT_HOME||process.env.HOME){let t=e||ER()||PR().homedir;return t&&kR(t)?t:null}function $R(e=Qh()){return e?Il(e,".cc-safety-net","logs"):null}function ty(e,t,n,r=!0,o){if(t.decision.kind==="allow"){if(!n||e.route.kind!=="command")return;let a=ey(e);return{decision:"allow",command:a,segment:a,reason:"allowed",cwd:e.context.executionCwd,toolName:e.toolName,level:t.level,...t.configFallback?{configFallback:!0}:{}}}let i=t.decision.evidence.find((a)=>a.kind==="command"),s=i?.command??(r?ey(e):"");return{decision:"deny",command:s,segment:i?.segment??s,reason:t.decision.reason,cwd:e.context.executionCwd,toolName:e.toolName,level:t.level,...t.configFallback?{configFallback:!0}:{},ruleId:t.decision.ruleId,intent:t.decision.intent,failureStage:o?.stage,errorCode:o?.errorCode}}function ey(e){return"command"in e?e.command??"":""}function ny(e,t,n){if(!e)return;let r;try{r=t()}catch{return}if(typeof r!=="string"||!r.trim())return;Ol(r,e.command,e.segment,e.reason,e.cwd,{homeDir:n.homeDir,decision:e.decision,agent:n.agent,shape:n.shape,level:e.level,configFallback:e.configFallback,toolName:e.toolName,ruleId:e.ruleId,intent:e.intent,failureStage:e.failureStage,errorCode:e.errorCode})}function ry(e,t,n){let r;try{r=t()}catch{return}if(typeof r!=="string"||!r.trim())return;Ol(r,e.command??"",e.segment??e.command??"",e.reason,n.cwd??null,{homeDir:n.homeDir,decision:"deny",agent:n.agent,shape:n.shape,toolName:n.toolName??e.toolName,ruleId:e.ruleId,intent:e.intent})}import{accessSync as _1,constants as C1,realpathSync as UR,statSync as jR}from"fs";import{isAbsolute as Nl,relative as HR,resolve as oy,sep as VR}from"path";import{dirname as MR,isAbsolute as LR,parse as WR,sep as FR}from"path";function Vt(e,t=process.platform){if(t!=="win32")return!1;return(e[0]==="/"||e[0]==="\\")&&(e[1]==="/"||e[1]==="\\")}function qt(e,t,n){if(Vt(t))throw Error("Unsupported Windows namespace path");let r=LR(t)?ZR(t):"",o=r||e;for(let i of BR(r?t.slice(r.length):t)){if(i===""||i===".")continue;if(i===".."){o=MR(o);continue}let s=GR(o,i),a=n.entryKind(s),c=a==="symlink"?n.realpath(s):s;if(a==="missing"||c===null)throw Error(`Cannot resolve path component: ${s}`);o=c}return o}function GR(e,t){return e.endsWith("/")||e.endsWith("\\")?`${e}${t}`:`${e}${FR}${t}`}function ZR(e){return WR(e).root}function BR(e){let t=process.platform==="win32"?/[\\/]+/:/\/+/;return e.split(t)}function Dl(e,t){if(Vt(e))return;let n=t.flatMap((o)=>zl(o));if(!n[0])return;let r=zl(Nl(e)?e:oy(n[0],e))[0];if(!r)return;return n.some((o)=>sy(r,o))?r:void 0}function iy(e,t){if(Vt(e))return;return zl(Nl(e)?e:oy(t,e))[0]}function zl(e){try{let t=UR(e);return jR(t).isDirectory()?[t]:[]}catch{return[]}}function sy(e,t){let n=HR(t,e);return n===""||n!==".."&&!n.startsWith(`..${VR}`)&&!Nl(n)}var Kt="Command could not be safely analyzed (strict mode). Simplify the command and retry, or ask the user to verify.",It="Command exceeds maximum recursion depth and cannot be safely analyzed. Flatten the nesting and retry.",ay="CC Safety Net could not validate the command because its structure exceeds safe analysis limits.",cy="CC Safety Net could not analyze the command because it exceeds safe analysis limits. Simplify or split the command and retry.",Wi="CC Safety Net failed closed because command analysis failed unexpectedly. This is not caused by your command. Report it to the user.";function uy(e){let{reason:t,command:n,segment:r,toolName:o}=e,i=e.maxLen??200,s=e.redact??((c)=>c),a=`BLOCKED by CC Safety Net
7
7
 
8
8
  Reason: ${s(t)}`;if(e.ruleId)a+=`