← Files Atbash SafetyARCHIVED FILE
runtime/install-hook.cjs
15.5 KB · Nov 22, 2026 · 12:12 UTC
#!/usr/bin/env node
"use strict";var ue=require("node:fs"),le=require("node:path");var g=require("node:fs"),ae=require("node:os"),u=require("node:path");var a=require("node:fs"),J=require("node:child_process"),R=require("node:os"),f=require("node:path"),N="pre-tool-use.cjs",he="*",fe=35;var _="Checking action with Atbash",c=class extends Error{};function p(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var pe=/^[A-Za-z0-9 _.:/+@()-]+$/,me=/^[A-Za-z0-9 _.:/+@()\\-]+$/;function A(e,t,n="hook path"){if(!(t==="win32"?me:pe).test(e)){let s=n==="hook path"?"move the plugin to a plain path.":"run the installer with a node installed under a plain path.";throw new c(`The ${n} ${JSON.stringify(e)} contains a character a shell could interpret (allowed: letters, digits, space, _ . : / + @ ( ) -${t==="win32"?" and \\":""}); `+s)}}function M(e,t){if(!(0,f.isAbsolute)(e)||!(0,a.existsSync)(e))throw new c(`The node interpreter path ${JSON.stringify(e)} is not an existing absolute path.`);let n=(0,a.realpathSync)(e);return A(n,t,"node interpreter path"),n}function D(e,t){let n=(0,f.join)(e,N);if(!(0,a.existsSync)(n))throw new c(`No ${N} next to this installer (looked at ${n}); run the installer that ships in the plugin's runtime directory.`);let o=(0,a.realpathSync)(n);return A(o,t),o}function U(e,t,n){A(e,t),A(n,t,"node interpreter path");let o=i=>i.replaceAll("/","\\"),s=t==="win32"?`& "${o(n)}" "${o(e)}"`:`"${n}" "${e}"`,r={type:"command",command:s,...t==="win32"?{commandWindows:s}:{},timeout:fe,statusMessage:_};return{matcher:he,hooks:[r]}}var ge=/^\s*(&\s+)?(?:node|"([^"]+)")\s+"([^"]+)"(?:\s+.*)?$/s;function W(e){if(typeof e!="string")return;let t=ge.exec(e);if(!(t===null||t[3]===void 0))return{callOperator:t[1]!==void 0,interpreter:t[2],script:t[3]}}function F(e){return W(e)?.script}function j(e,t){return t==="win32"?e.replaceAll("\\","/").toLowerCase():e}function ke(e,t){if(p(e))return t==="win32"?e.commandWindows??e.command:e.command}function $(e,t){if(!p(e))return!1;let n=j(t.hookScript,t.platform),o=F(ke(e,t.platform));return o!==void 0&&j(o,t.platform)===n}function we(e,t){return!p(e)||$(e,t)?!1:e.statusMessage===_?!0:[e.command,e.commandWindows].some(n=>{let o=F(n);return o!==void 0&&/[\\/]pre-tool-use\.cjs$/.test(o)})}function G(e,t,n,o){for(let s of e.hooks)for(let r of[s.command,s.commandWindows]){if(r===void 0)continue;let i=W(r);if(i===void 0)throw new c(`The hook command ${JSON.stringify(r)} does not parse back to a script path.`);if(!(0,a.existsSync)(i.script))throw new c(`The hook command ${JSON.stringify(r)} names a file that does not exist.`);let h=(0,a.realpathSync)(i.script);if(h!==t)throw new c(`The hook command ${JSON.stringify(r)} resolves to ${h}, not to ${t}.`);if(i.interpreter===void 0||!(0,f.isAbsolute)(i.interpreter))throw new c(`The hook command ${JSON.stringify(r)} does not name an absolute interpreter.`);if(!(0,a.existsSync)(i.interpreter))throw new c(`The hook command ${JSON.stringify(r)} names an interpreter that does not exist.`);let d=(0,a.realpathSync)(i.interpreter);if(d!==n)throw new c(`The hook command ${JSON.stringify(r)}: the interpreter resolves to ${d}, not to ${n}.`);if(i.callOperator!==(o==="win32"))throw new c(o==="win32"?`The hook command ${JSON.stringify(r)} lacks the PowerShell call operator; Codex on Windows would evaluate it as a string and run nothing.`:`The hook command ${JSON.stringify(r)} carries a call operator that sh would read as a background job.`)}}function X(e,t){return Array.isArray(e.hooks)&&e.hooks.some(n=>$(n,t))}function ye(e){let t=e instanceof Error?e.message:"",n=/at position \d+(?: \(line \d+ column \d+\))?/.exec(t)?.[0];if(n!==void 0)return`syntax error ${n}`;if(/end of JSON input/i.test(t))return"unexpected end of input";let o=/Unexpected token '(.)'/u.exec(t)?.[1];return o===void 0?"syntax error":/^[\x20-\x7e]$/.test(o)?`syntax error near token '${o}'`:`syntax error near U+${(o.codePointAt(0)??0).toString(16).toUpperCase().padStart(4,"0")}`}function B(e,t){let n;try{n=JSON.parse(e)}catch(o){throw new c(`${t} is not valid JSON (${ye(o)}); fix or remove it first.`)}if(!p(n))throw new c(`${t} must contain a JSON object at the top level.`);if(n.hooks!==void 0){if(!p(n.hooks))throw new c(`${t}: "hooks" must be an object keyed by event name.`);let o=n.hooks.PreToolUse;if(o!==void 0){if(!Array.isArray(o))throw new c(`${t}: "hooks.PreToolUse" must be an array of matcher groups.`);o.forEach((s,r)=>{if(!p(s))throw new c(`${t}: "hooks.PreToolUse[${r}]" must be an object.`);if(s.hooks!==void 0&&!Array.isArray(s.hooks))throw new c(`${t}: "hooks.PreToolUse[${r}].hooks" must be an array of hooks.`)})}}return n}function O(e){return e.hooks?.PreToolUse??[]}function be(e){return O(e).flatMap(t=>Array.isArray(t.hooks)?t.hooks:[])}function K(e,t){return e.flatMap(n=>{if(!X(n,t))return[n];let o=n.hooks.filter(s=>!$(s,t));return o.length===0?[]:[{...n,hooks:o}]})}function L(e,t){let n={...e.hooks??{}};return t===void 0?delete n.PreToolUse:n.PreToolUse=t,{...e,hooks:n}}function z(e,t){return O(e).some(n=>X(n,t))}function Y(e,t){let n=be(e).filter(o=>!$(o,t));return{foreignHooks:n,otherEvents:Object.keys(e.hooks??{}).filter(o=>o!=="PreToolUse"),lookalikes:n.filter(o=>we(o,t))}}var xe={hook_event_name:"PreToolUse",tool_name:"probe",tool_input:{},cwd:".",permission_mode:"default",session_id:"install-probe",model:"probe",tool_use_id:"probe",transcript_path:null,turn_id:"probe"},Se=15e3;function Ae(e){let t=e.SystemRoot??e.SYSTEMROOT??"C:\\Windows";return(0,f.join)(t,"System32","WindowsPowerShell","v1.0","powershell.exe")}function Z(e,t,n=Se){let o=e.hooks[0];if(o===void 0)throw new c("the registered command could not be executed by the host shell: the entry has no hook");let s=t==="win32"?[...new Set([o.commandWindows??o.command,o.command])]:[o.command];for(let r of s)Oe(r,t,n)}function $e(e){return e===null||e.length===0?"":e.includes(0)?e.toString("utf16le"):e.toString("utf8")}function Oe(e,t,n){let o=d=>{throw new c(`the registered command could not be executed by the host shell: ${d} (command: ${e})`)},s=(0,a.mkdtempSync)((0,f.join)((0,R.tmpdir)(),"atbash-probe-home-")),r={PATH:"",HOME:s,USERPROFILE:s,ATBASH_CODEX_TIMEOUT_MS:"invalid",ATBASH_HOOK_DEADLINE_MS:""};for(let d of["SystemRoot","SYSTEMROOT","SystemDrive","TEMP","TMP","TMPDIR"]){let l=process.env[d];l!==void 0&&(r[d]=l)}t==="win32"&&(r.PATHEXT=process.env.PATHEXT??".COM;.EXE;.BAT;.CMD");let[i,h]=t==="win32"?[Ae(process.env),["-NoProfile","-NonInteractive","-Command",e]]:["/bin/sh",["-c",e]];try{let d=(0,J.spawnSync)(i,h,{input:JSON.stringify(xe),encoding:null,env:r,cwd:s,timeout:n,windowsHide:!0}),l=d.error?.code;if(d.error!==void 0&&!(l==="EPIPE"&&d.status!==null))return o(l==="ETIMEDOUT"?`no decision within ${n} ms`:d.error.message);if(d.status!==0){let x=$e(d.stderr).trim().split(/\r?\n/)[0]?.slice(0,200)??"";return o(`exit ${d.status??`signal ${d.signal??"unknown"}`}${x===""?"":` (${x})`}`)}let y=d.stdout??Buffer.alloc(0),m;try{m=new TextDecoder("utf-8",{fatal:!0}).decode(y)}catch{return o("stdout is not UTF-8")}if(m.includes("\0"))return o("stdout is not UTF-8");let k;try{k=JSON.parse(m.trim())}catch{return o("stdout is not one JSON object")}let b=p(k)&&p(k.hookSpecificOutput)?k.hookSpecificOutput.permissionDecision:void 0;if(b!=="deny")return o(`stdout is not a deny decision (permissionDecision: ${JSON.stringify(b)})`)}finally{try{(0,a.rmSync)(s,{force:!0,recursive:!0,maxRetries:3})}catch{}}}function V(e,t,n){let o=K(O(e),n);return L(e,[...o,t])}function q(e,t){let n=K(O(e),t);return L(e,n.length===0?void 0:n)}function Q(e){return`${JSON.stringify(e,null,2)}
`}function ee(e){let t;try{t=(0,a.lstatSync)(e)}catch{t=void 0}if(t!==void 0)try{return(0,a.realpathSync)(e)}catch{throw new c(`${e} is a link to a file that does not exist; fix the link first.`)}let n=(0,f.dirname)(e);return(0,a.existsSync)(n)?(0,f.join)((0,a.realpathSync)(n),(0,f.basename)(e)):e}function te(e,t){if(t==="win32")return!1;try{return((0,a.statSync)(e).mode&18)!==0}catch{return!1}}function H(e){try{let t=(0,a.statSync)(e);return{dev:t.dev,ino:t.ino,ctimeMs:t.ctimeMs}}catch{return}}function ve(e,t){return e!==void 0&&t!==void 0&&e.dev===t.dev&&e.ino===t.ino&&e.ctimeMs===t.ctimeMs}function ne(e,t,n){let o=(0,f.dirname)(e);(0,a.mkdirSync)(o,{mode:448,recursive:!0});let s=(0,f.join)(o,`.${(0,f.basename)(e)}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`);try{(0,a.writeFileSync)(s,t,{encoding:"utf8",flag:"wx",mode:384}),n.platform!=="win32"&&(0,a.chmodSync)(s,384),n.beforeSwap?.();let r=(0,a.existsSync)(e)?(0,a.readFileSync)(e,"utf8"):void 0,i=n.expectedIdentity!==void 0&&!ve(H(e),n.expectedIdentity);if(r!==n.expectedExisting||i)throw new c(`${e} changed while the installer was running; re-run it to work from the current contents.`);(0,a.renameSync)(s,e)}catch(r){throw(0,a.rmSync)(s,{force:!0}),r}}var oe=0,Te=1,Pe=2,re=`Usage: node install-hook.cjs [--dry-run] [--uninstall] [--scope user|project] [--dir <path>]
Registers the Atbash PreToolUse hook in a Codex hooks file, because Codex 0.154+ does not run
hooks shipped inside a plugin. Nothing is written until the file is validated.
--scope user (default) write <codex home>/hooks.json; codex home is --dir, else
$CODEX_HOME, else ~/.codex
--scope project write <project>/.codex/hooks.json (read by Codex only when it is started in
that very directory - a subdirectory session is not covered); the project is --dir, else the current
directory
--dir <path> the Codex home (user scope) or project directory (project scope)
--dry-run print the Atbash entry that would be written and write nothing
--uninstall remove only the Atbash entry
-h, --help show this help
Exit codes: 0 done (or nothing to do), 1 refused or failed (the file was left as it was), 2 usage.
`,Ee=new Set(["--scope","--dir"]);function He(e){let t={scope:"user",dryRun:!1,uninstall:!1,help:!1},n=new Map;for(let r=0;r<e.length;r+=1){let i=e[r]??"";if(i==="-h"||i==="--help"){t.help=!0;continue}if(i==="--dry-run"){t.dryRun=!0;continue}if(i==="--uninstall"){t.uninstall=!0;continue}let h=i.indexOf("="),d=h===-1?i:i.slice(0,h);if(!Ee.has(d))return{ok:!1,message:`Unknown argument: ${i}`};let l;if(h!==-1?l=i.slice(h+1):(l=e[r+1],r+=1),l===void 0||l===""||l.startsWith("-"))return{ok:!1,message:`${d} needs a value.`};if(n.has(d))return{ok:!1,message:`${d} was given more than once.`};n.set(d,l)}let o=n.get("--scope");if(o!==void 0){if(o!=="user"&&o!=="project")return{ok:!1,message:`--scope must be "user" or "project", not ${JSON.stringify(o)}.`};t.scope=o}let s=n.get("--dir");return s!==void 0&&(t.dir=s),{ok:!0,options:t}}function Ie(e,t,{cwd:n,env:o,home:s}){if(e==="project")return(0,u.resolve)(n,t??n,".codex","hooks.json");let r=o.CODEX_HOME,i=t!==void 0?(0,u.resolve)(n,t):r!==void 0&&r.trim()!==""?(0,u.resolve)(n,r):(0,u.resolve)(s,".codex");return(0,u.resolve)(i,"hooks.json")}function se(e){let t=[],n=e;for(;!(0,g.existsSync)(n);){let o=(0,u.dirname)(n);if(o===n)return e;t.unshift((0,u.basename)(n)),n=o}return(0,u.join)((0,g.realpathSync)(n),...t)}function Ce(e,t){let n=D(t.runtimeDir,t.platform),o=M(t.nodePath,t.platform),s={hookScript:n,platform:t.platform},r=Ie(e.scope,e.dir,t),i=ee(r);if(e.scope==="project"){let C=se((0,u.resolve)(t.cwd,e.dir??t.cwd)),E=(0,u.relative)(C,se(i));if(E===""||E.startsWith("..")||(0,u.isAbsolute)(E))throw new c(`${r} resolves to ${i}, outside the project directory ${C}; a project hooks file must live inside its project - fix the link first.`)}let h=(0,g.existsSync)(i)?(0,g.readFileSync)(i,"utf8"):void 0,d=h===void 0?void 0:H(i),l=h===void 0?{}:B(h,r),y=z(l,s),m=Y(l,s),k={foreignHooks:m.foreignHooks.length,otherEvents:m.otherEvents.length},b=m.lookalikes.map(()=>`${r} has a PreToolUse hook that looks like Atbash's (the Atbash status message, or a script called pre-tool-use.cjs) but does not run this plugin's hook script; it is not provably Atbash's and was left alone. If it is a stale entry from a plugin that moved, remove it by hand.`),x=te((0,u.dirname)(i),t.platform)?[`${(0,u.dirname)(i)} is writable by other users; anyone who can write there can replace this hook. Consider chmod 700.`]:[],I={hooksPath:r,target:i,hookScript:n,interpreter:o,kept:k,notes:b,warnings:x},v,S,w;if(e.uninstall){if(!y)return{...I,action:"not-installed",text:h??"",written:!1};v=q(l,s),S="removed"}else w=U(n,t.platform,o),G(w,n,o,t.platform),Z(w,t.platform),v=V(l,w,s),S=y?"updated":"installed";let T=Q(v),P={...I,...w===void 0?{}:{entry:w},text:T};return T===h?{...P,action:"unchanged",written:!1}:e.dryRun?{...P,action:S,written:!1}:(ne(i,T,{platform:t.platform,expectedExisting:h,expectedIdentity:d,...t.beforeSwap===void 0?{}:{beforeSwap:t.beforeSwap}}),{...P,action:S,written:!0})}var Ne=`Codex 0.154+ does not run hooks shipped inside a plugin (\`codex features list\` reports
\`plugin_hooks: removed\`), so this hooks file is what enforces Atbash. Two steps remain, and
both are yours:
1. Restart Codex so it reads the hooks file.
2. In Codex, run /hooks and trust the Atbash PreToolUse hook. Codex does not run an
untrusted hook.
Configure ~/.config/atbash/config.json first if you have not (ask $atbash-setup); with no
configuration the hook denies every tool call.
`;function ie(e,t){return`${e} ${t}${e===1?"":"s"}`}function je(e,t){let n=[],o=`${e.hooksPath} (${t.scope} scope)`,s=`${ie(e.kept.foreignHooks,"foreign PreToolUse hook")} and ${ie(e.kept.otherEvents,"other event")} kept.`,r=e.action!=="unchanged"&&e.action!=="not-installed";switch(t.dryRun&&r&&(n.push("Dry run: nothing was written."),e.entry!==void 0&&(n.push(`${o} would gain this PreToolUse entry:`),n.push(""),n.push(JSON.stringify(e.entry,null,2)),n.push(""))),e.action){case"installed":n.push(`${t.dryRun?"Would install":"Installed"} the Atbash hook in ${o}. ${s}`);break;case"updated":n.push(`${t.dryRun?"Would replace":"Replaced"} the existing Atbash hook in ${o}. ${s}`);break;case"unchanged":n.push(`The Atbash hook is already ${t.uninstall?"absent from":"installed in"} ${o}; nothing to change.`);break;case"removed":n.push(`${t.dryRun?"Would remove":"Removed"} the Atbash hook from ${o}. ${s}`);break;case"not-installed":n.push(`No Atbash hook in ${o}; nothing to remove.`);break}return e.target!==e.hooksPath&&n.push(` (${e.hooksPath} is a link; the file behind it, ${e.target}, is the one updated)`),t.uninstall?e.action==="removed"&&n.push("Restart Codex so it stops running the hook."):(n.push(` hook command: ${e.entry?.hooks[0]?.command??""}`),n.push(` interpreter: ${e.interpreter} (the node that ran this installer; the hook does not depend on PATH)`),n.push(` verified: ${e.entry===void 0||!e.entry.hooks[0]?.command.startsWith("&")?"sh":"Windows PowerShell"} ran this exact command with no PATH and no configuration, and it answered with a deny`),n.push(""),n.push(Ne.trimEnd())),`${n.join(`
`)}
`}function de(e,t,n){let o=He(e);if(!o.ok)return n.stderr(`${o.message}
${re}`),Pe;if(o.options.help)return n.stdout(re),oe;try{let s=Ce(o.options,t);for(let r of s.notes)n.stderr(`note: ${r}
`);for(let r of s.warnings)n.stderr(`warning: ${r}
`);return n.stdout(je(s,o.options)),oe}catch(s){let r=s instanceof c,i=s instanceof Error?s.message:String(s);return n.stderr(`${r?"Refused":"Failed"}: ${i}
Nothing was written.
`),Te}}function ce(){return{cwd:process.cwd(),env:process.env,home:(0,ae.homedir)()}}function Je(){let e=process.argv[1];if(e===void 0){process.stderr.write(`install-hook must be started as a script (node install-hook.cjs).
`),process.exitCode=1;return}process.exitCode=de(process.argv.slice(2),{...ce(),runtimeDir:(0,le.dirname)((0,ue.realpathSync)(e)),platform:process.platform,nodePath:process.execPath},{stdout:t=>process.stdout.write(t),stderr:t=>process.stderr.write(t)})}Je();
SHA-256: f4fdd9a99561f49f43abc042f7bf6fa1f31e8206cdaf873b4a5a23f3569e75e2