The question says it all.
How do I keep my GitHub token safe when scripts push code for me?
1 answer
Chosen as the best answer
Use a fine-grained token that only covers the repos your script needs and has an expiry date. Keep it in a .env file that git ignores, send it as a header instead of putting it in the URL, check every push for secrets, and if you think it leaked, revoke it right away.
Scripts that push for you are where tokens leak, because nobody is watching when they run. This is the setup we use.
Give it the least power possible
On GitHub, create a fine-grained personal access token, not a classic one. Give it access only to the repos it pushes to, with Contents set to read and write. Set an expiry date, even a long one, and note it down. If it ever leaks, the damage stays small and ends on a known day.
Keep it out of your code
Put it in a
.envfile next to your scripts, and add.envto.gitignorebefore you create the file. Load it only when needed:set -a; . ./.env; set +aDon't paste it into a script, a README, an issue, or any chat that does not need it.
Don't put it in the remote URL
https://TOKEN@github.com/you/repo.gitis handy, but that URL ends up in.git/config, shell history and error messages. Send it as a header for the one push instead:AUTH=$(printf 'x-access-token:%s' "$GITHUB_TOKEN" | base64 -w0) git -c http.extraHeader="Authorization: Basic $AUTH" push https://github.com/you/repo.git mainThe token only lives in memory for that command.
Check before every push
Have the script stop if the files contain anything that looks like a secret:
.envfiles, keystores, private keys, or token-shaped text (GitHub tokens start withghporgithub_pat). Also turn on GitHub's secret scanning and push protection for your repos.If it might have leaked
Don't wait to be sure. Revoke it on GitHub, make a new one, update your
.env, and look through the repo's recent activity. Rewriting git history does not help much: treat anything that reached a public place as already copied.
Your answer
Know the answer? Sign in and share it. Useful answers earn points.
Sign in to answer