How to

Encrypted secrets in your repo

Your test credentials are probably in a chat thread, a .env file someone emailed, and a pile of GitHub secrets nobody can read back. Put them in the repository instead, encrypted with SOPS and age, where your team, your CI and your AI agents can all use them, and nobody has to see them.

Short link: fredlackey.com/sops-age-secrets
MacWindowsCI secrets/test.enc.yaml

The situation

Every team that runs integration tests against a real test environment has the same problem: a handful of credentials that everyone needs and nobody owns. They end up pasted into chat, saved in a .env file that drifts out of date on every laptop, and copied one at a time into GitHub’s secret settings, where you can write a value but never read it back. When someone leaves, nobody is sure what they had.

There’s a better place for them: the repository itself, encrypted. Two small open-source tools make that safe. SOPS is, in its own words, “an editor of encrypted files.” age is “a simple, modern and secure file encryption tool,” and it’s the key type the SOPS docs recommend. Together they let you commit a file whose values are encrypted, so that only the people and machines on a list can read it.

I want to make the case for doing this, show exactly how, and give you a small set of tools so that people on a Mac and people on Windows use the same repository with exactly the same commands.

How it works

SOPS doesn’t encrypt the whole file as one blob. It encrypts each value and leaves the structure readable:

  1. One data key per file. SOPS makes a random 256-bit key for the file.
  2. Each value is encrypted with that data key (AES256-GCM). Key names stay in plain text, so never put a secret in a key name.
  3. age locks the data key once for each person or machine on the list, and stores those copies at the bottom of the file. Any one of them can open it.
  4. A checksum (MAC) covers every value. If someone edits the ciphertext by hand, decryption fails with MAC mismatch.

An encrypted file looks roughly like this (shortened):

API_BASE_URL: ENC[AES256_GCM,data:...,iv:...,tag:...,type:str]
API_CLIENT_ID: ENC[AES256_GCM,data:...,iv:...,tag:...,type:str]
API_CLIENT_SECRET: ENC[AES256_GCM,data:...,iv:...,tag:...,type:str]
sops:
    age:
        - recipient: age1dllsvfjmvwm6m9aw2x67eqtdg2l6zmvc7gxfdja00zspdd36z3tqm2tfj4
          enc: |
            -----BEGIN AGE ENCRYPTED FILE-----
            ...

Two words to keep straight:

  • Recipient: a public key, starting age1…. It’s safe to share, and it goes on the access list in the repo.
  • Identity: a private key, starting AGE-SECRET-KEY-1…. Never share it, and never commit it. It lives in a file on your own machine, outside the repository.

Because only values are encrypted, a pull request that changes a credential shows which key changed, never its value. That one property is what makes this pleasant to live with.

Where it pays off

There are three places this changes how a team works.

Keys used by GitHub Actions
CI needs one GitHub secret, its own age private key, instead of one secret per credential. Adding a new test credential becomes an ordinary pull request: nobody has to go into GitHub’s settings, and the change is reviewed with the code that uses it. The same file works on a laptop and in CI, so “works on my machine” stops being a credentials problem.
AI agents working on your machine
Coding agents such as Claude Code, Codex and Cursor need to run your tests, and your tests need credentials. The rule I recommend is simple: the agent may use secrets; it must never see them. Whatever an agent runs, it reads, and what it reads goes to the model provider and into a transcript on disk. With the helper below, the decrypted values exist only inside the environment of the one command being run. They never land on screen, in a file, or in the conversation.
Scripts you run to read or add values
Nobody hand-edits ciphertext. One small script lists the names, prints a single value for a human, or stores a new one from a hidden prompt, so the value never appears in your shell history or on a command line. The same script runs on macOS, Linux and Windows.

The starter kit

Everything in this article is in a small kit you can drop into a repository. Download the files individually; the kit’s README repeats where each one goes. Files that start with a dot in your repo are named without the dot here, so every web server will hand them over.

DownloadPut it atWhat it does
secret.mjsscripts/secret.mjsThe one helper for every platform
pre-commit.githooks/pre-commitRefuses to commit plaintext into secrets/
gitattributes.txt.gitattributesForces Unix line endings on secrets
gitignore.txt.gitignoreOnly encrypted files may live in secrets/
AGENTS-secrets.txtpaste into AGENTS.mdThe rules for AI agents
claude-settings.json.claude/settings.jsonClaude Code permission rules
action.yml.github/actions/setup-sops/action.ymlInstalls a pinned, checksum-verified sops in CI
integration-tests.yml.github/workflows/integration-tests.ymlThe CI workflow
README.txtfor youWhere everything goes, and first commands

Once it’s set up, the repository looks like this:

.gitattributes
.gitignore
.sops.yaml                      generated from .sops/recipients.txt (don't hand-edit)
.sops/recipients.txt            "age1... name" per line: the access list, reviewed in PRs
secrets/README.md               plain text: what lives here and how to get access
secrets/test.enc.yaml           the encrypted shared test credentials
scripts/secret.mjs              one helper for macOS, Linux and Windows
.githooks/pre-commit            blocks plaintext in secrets/
AGENTS.md                       rules for AI agents (CLAUDE.md contains @AGENTS.md)
.claude/settings.json           permission rules for Claude Code
.github/actions/setup-sops/action.yml
.github/workflows/integration-tests.yml

Two choices in that layout matter. Secret files are named secrets/*.enc.yaml, YAML with flat UPPER_SNAKE names, because .env-format files with Windows line endings fail to decrypt (sops issues #904 and #1157) and YAML doesn’t. And .sops/recipients.txt is the source of truth for who has access; the helper writes .sops.yaml from it, so nobody hand-edits YAML when people join or leave.

Set up a Mac or a Windows machine

Everyone does this once. After this step, every command in the article is identical on both platforms.

StepmacOS (zsh)Windows (PowerShell 7)
Installbrew install sops age node gitwinget install --id SecretsOPerationS.SOPS -e
winget install --id FiloSottile.age -e
winget install --id OpenJS.NodeJS.LTS -e
winget install --id Git.Git -e
winget install --id Microsoft.PowerShell -e
Then open a new terminal.
Or—Scoop: scoop install sops; scoop bucket add extras; scoop install age
Chocolatey: choco install sops age.portable -y (there’s no package named age)
Checksops --version --disable-version-check should say 3.13.3 or later; age --version should say v1.3.2. Use at least sops 3.13.3: it fixes a MAC bug.
Your keynode scripts/secret.mjs init-key — the same command on both. Never create a key file with >.
Where it lands~/Library/Application Support/sops/age/keys.txt (or under $XDG_CONFIG_HOME if you set it)%AppData%\sops\age\keys.txt, according to the sops source
Editor for editWorks as is. Optional: export SOPS_EDITOR="code --wait"Required: [Environment]::SetEnvironmentVariable('SOPS_EDITOR','code --wait','User'). Notepad doesn’t work (sops #1118).
Everything elsenode scripts/secret.mjs … — identical

Two mistakes I’d warn every new person about:

  • On a Mac, following a Linux tutorial and saving the key in ~/.config/sops/age/. sops won’t look there unless XDG_CONFIG_HOME is set. init-key puts it in the right place.
  • On Windows, writing the key with Windows PowerShell 5.1’s > or Out-File. That produces UTF-16 or a byte-order mark, and sops then either ignores the file and claims it “did not find keys,” or fails to parse it. Let each tool write its own files, and use PowerShell 7.

The helper: one script for everyone

The heart of the kit is scripts/secret.mjs, a single Node script with no npm dependencies. I chose Node over a pair of Bash and PowerShell scripts on purpose: a matching pair always drifts apart, and Node passes arguments to sops as a list, so there are no quoting differences between zsh, PowerShell and cmd.exe. Run it from the repository root:

node scripts/secret.mjs doctor                      check tools, your key, line endings, and that you can decrypt
node scripts/secret.mjs init-key                    create your personal age key in the default location
node scripts/secret.mjs list                        show secret NAMES (never values)
node scripts/secret.mjs get API_CLIENT_ID           print one value                      (humans only)
node scripts/secret.mjs set API_CLIENT_SECRET       store a value from a hidden prompt   (humans only)
node scripts/secret.mjs unset OLD_NAME              remove one value                     (humans only)
node scripts/secret.mjs edit                        open the whole file in your editor   (humans only)
node scripts/secret.mjs run -- npm test             run a command with the secrets as environment variables
node scripts/secret.mjs check                       CI: every file is encrypted to the current recipients
node scripts/secret.mjs add-recipient age1... "dana laptop"
node scripts/secret.mjs remove-recipient "bob laptop"

A few things it does for you that are easy to get wrong by hand:

  • set never takes the value as an argument. It asks twice, with nothing shown on screen, and refuses an empty or mismatched answer. You can also pipe a value in, for example from your password manager’s command-line tool. Either way it never reaches your shell history.
  • set creates the file if it’s missing, encrypted from the start, without writing plaintext to disk.
  • run hands the values to the child command but not the key. It removes SOPS_AGE_KEY, SOPS_AGE_KEY_FILE and SOPS_AGE_KEY_CMD from the child’s environment, so the command you run can use the secrets but can’t decrypt anything itself.
  • add-recipient and remove-recipient rewrite the access list and .sops.yaml, then re-key every file. Removing someone also rotates the data key.
  • The generated .sops.yaml works on Windows. sops matches its path rule against native paths, so Windows sees secrets\test.enc.yaml with a backslash, and a rule written with only / never matches. The helper always writes ^secrets[/\\].*\.enc\.(ya?ml|json|env)$.

Its limits: names that contain a dot can’t be addressed, run exports only top-level values, and secrets/ is treated as one flat folder. Keep the file flat and simple and none of that matters.

Show the whole script
#!/usr/bin/env node
// secret.mjs - one secrets helper for macOS, Linux and Windows. No npm dependencies.
// Run from the repository root:  node scripts/secret.mjs <command> [args]
//   doctor                           check tools, your key, line endings, and that you can decrypt
//   init-key                         create your personal age key in the default location
//   list                             show secret NAMES (never values)
//   get <name>                       print one value                      (humans only)
//   set <name>                       store a value from a hidden prompt or stdin (humans only)
//   unset <name>                     remove one value                     (humans only)
//   edit                             open the whole file in your editor   (humans only)
//   run -- <cmd> [args...]           run a command with every top-level secret as an env var
//   check                            CI: every file in secrets/ is encrypted to the current recipients
//   add-recipient <age1...> <name>   add a teammate or CI key, then re-key every file
//   remove-recipient <name|age1...>  remove a key, re-key and rotate (then change the real credentials!)
// File: $SECRETS_FILE, default secrets/test.enc.yaml
import { spawnSync } from 'node:child_process';
import { existsSync, readFileSync, writeFileSync, mkdirSync, readdirSync } from 'node:fs';
import { homedir } from 'node:os';
import { join, dirname } from 'node:path';

const SECRETS_FILE = process.env.SECRETS_FILE || 'secrets/test.enc.yaml';
const RECIPIENTS = '.sops/recipients.txt'; // "age1... name" per line: the source of truth
const SECRET_NAME = /\.enc\.(ya?ml|json|env)$/;
const isWin = process.platform === 'win32';

function sh(cmd, args, opts = {}) {
  // Arguments go in an array, so no shell is involved and quoting is identical
  // in zsh, bash, PowerShell and cmd.exe.
  const r = spawnSync(cmd, args, { encoding: 'utf8', ...opts });
  if (r.error) throw new Error(`${cmd} not found on PATH (${r.error.code})`);
  return r;
}
function must(r, what) {
  if (r.status !== 0) { process.stderr.write(r.stderr || ''); throw new Error(`${what} failed`); }
  return r.stdout;
}

// Where sops looks for keys.txt by default (mirrors getsops/sops age/keysource.go).
function defaultKeyFile() {
  if (isWin) return join(process.env.APPDATA, 'sops', 'age', 'keys.txt');
  if (process.env.XDG_CONFIG_HOME) return join(process.env.XDG_CONFIG_HOME, 'sops', 'age', 'keys.txt');
  if (process.platform === 'darwin') return join(homedir(), 'Library', 'Application Support', 'sops', 'age', 'keys.txt');
  return join(homedir(), '.config', 'sops', 'age', 'keys.txt');
}
const keyFile = () => process.env.SOPS_AGE_KEY_FILE || defaultKeyFile();

// "db.password" -> ["db"]["password"]  (numbers become list indexes)
const toIndex = (p) => p.split('.').map((k) => (/^\d+$/.test(k) ? `[${k}]` : `[${JSON.stringify(k)}]`)).join('');

function decryptJson(file = SECRETS_FILE) {
  return JSON.parse(must(sh('sops', ['decrypt', '--output-type', 'json', file]), `decrypt ${file}`));
}
function names(obj, prefix = '') {
  return Object.entries(obj).flatMap(([k, v]) =>
    v && typeof v === 'object' && !Array.isArray(v) ? names(v, `${prefix}${k}.`) : [`${prefix}${k}`]);
}
// Create an empty encrypted file without ever writing plaintext to disk.
function ensureFile() {
  if (existsSync(SECRETS_FILE)) return;
  mkdirSync(dirname(SECRETS_FILE), { recursive: true });
  const out = must(sh('sops', ['encrypt', '--filename-override', SECRETS_FILE], { input: '{}' }), 'create');
  writeFileSync(SECRETS_FILE, out);
}

// Hidden prompt: one answer per label, read key by key with nothing echoed.
function promptHidden(labels) {
  return new Promise((resolve) => {
    const { stdin } = process; const answers = []; let v = '';
    process.stderr.write(labels[0]);
    stdin.setRawMode(true); stdin.setEncoding('utf8'); stdin.resume();
    const onData = (chunk) => {
      for (const ch of chunk) {
        if (ch === '\u0003') { stdin.setRawMode(false); process.exit(130); } // Ctrl+C
        if (ch === '\r' || ch === '\n') {
          process.stderr.write('\n'); answers.push(v); v = '';
          if (answers.length === labels.length) {
            stdin.off('data', onData); stdin.setRawMode(false); stdin.pause(); return resolve(answers);
          }
          process.stderr.write(labels[answers.length]); continue;
        }
        v = ch === '\u007f' || ch === '\b' ? v.slice(0, -1) : v + ch;
      }
    };
    stdin.on('data', onData);
  });
}
async function readValue() {
  let v;
  if (process.stdin.isTTY) {
    const [a, b] = await promptHidden(['Value (hidden): ', 'Again: ']);
    if (a !== b) throw new Error('values did not match');
    v = a;
  } else { // piped, e.g. from a password manager CLI
    const chunks = []; for await (const c of process.stdin) chunks.push(c);
    v = Buffer.concat(chunks).toString('utf8').replace(/\r?\n$/, '');
  }
  if (!v) throw new Error('empty value refused');
  return v;
}

function readRecipients() {
  if (!existsSync(RECIPIENTS)) return [];
  return readFileSync(RECIPIENTS, 'utf8').split(/\r?\n/).map((l) => l.trim())
    .filter((l) => l && !l.startsWith('#'))
    .map((l) => { const [key, ...n] = l.split(/\s+/); return { key, name: n.join(' ') }; });
}
const secretFiles = () => (existsSync('secrets') ? readdirSync('secrets') : [])
  .filter((f) => SECRET_NAME.test(f)).map((f) => join('secrets', f));

function writeRecipients(list, { rotate = false } = {}) {
  mkdirSync(dirname(RECIPIENTS), { recursive: true });
  writeFileSync(RECIPIENTS, '# age public key, then a name. Change with secret.mjs add-recipient/remove-recipient.\n' +
    list.map((r) => `${r.key} ${r.name}`).join('\n') + '\n');
  // [/\\] matches both separators: sops matches path_regex against native
  // paths, so Windows sees "secrets\x.enc.yaml" (getsops/sops#2237).
  writeFileSync('.sops.yaml', '# GENERATED by scripts/secret.mjs from .sops/recipients.txt - do not edit by hand\n' +
    'creation_rules:\n  - path_regex: ^secrets[/\\\\].*\\.enc\\.(ya?ml|json|env)$\n    age:\n' +
    list.map((r) => `      - ${r.key} # ${r.name}`).join('\n') + '\n');
  for (const f of secretFiles()) {
    must(sh('sops', ['updatekeys', '-y', f], { stdio: ['ignore', 'pipe', 'pipe'] }), `updatekeys ${f}`);
    // updatekeys keeps the old data key. After a removal, rotate it so the
    // removed key cannot read values written from now on.
    if (rotate) must(sh('sops', ['rotate', '-i', f]), `rotate ${f}`);
  }
}

function check() {
  let ok = true;
  const expected = readRecipients().map((r) => r.key).sort().join(' ');
  const tracked = must(sh('git', ['ls-files', '-z', '--', 'secrets']), 'git ls-files').split('\0').filter(Boolean);
  for (const f of tracked) {
    if (/(^|\/)(README\.md|\.gitkeep)$/.test(f)) continue;
    if (!SECRET_NAME.test(f)) { console.log(`FAIL  ${f}: files in secrets/ must be named *.enc.yaml|json|env`); ok = false; continue; }
    const st = sh('sops', ['filestatus', f]); // exits 0 for plaintext too, so read the JSON
    let enc = false; try { enc = JSON.parse(st.stdout).encrypted === true; } catch {}
    if (!enc) { console.log(`FAIL  ${f} is not SOPS-encrypted`); ok = false; continue; }
    const actual = [...new Set([...readFileSync(f, 'utf8').matchAll(/recipient[":= ]+(age1[0-9a-z]+)/g)].map((m) => m[1]))].sort().join(' ');
    if (actual !== expected) { console.log(`DRIFT ${f}: recipients differ from ${RECIPIENTS}; re-run add-recipient or remove-recipient`); ok = false; continue; }
    console.log(`ok    ${f}`);
  }
  process.exitCode = ok ? 0 : 1;
}

function doctor() {
  let ok = true;
  const check = (label, pass, hint = '') => { console.log(`${pass ? 'OK  ' : 'FAIL'} ${label}${!pass && hint ? `\n     -> ${hint}` : ''}`); ok &&= pass; };
  for (const [tool, args] of [['sops', ['--version', '--disable-version-check']], ['age-keygen', ['--version']]]) {
    let r; try { r = sh(tool, args); } catch { r = null; }
    check(r ? r.stdout.split('\n')[0] : `${tool} missing`, !!r && r.status === 0,
      isWin ? 'winget install --id SecretsOPerationS.SOPS -e; winget install --id FiloSottile.age -e' : 'brew install sops age');
  }
  const kf = keyFile();
  let pub = null;
  if (process.env.SOPS_AGE_KEY || process.env.SOPS_AGE_KEY_CMD) check('key supplied via environment variable', true);
  else if (!existsSync(kf)) check(`key file ${kf}`, false, 'run: node scripts/secret.mjs init-key');
  else {
    const buf = readFileSync(kf);
    check(`key file ${kf} has no BOM and is not UTF-16`, ![0xef, 0xff, 0xfe].includes(buf[0]),
      'probably written by PowerShell 5.1 ">" or Out-File; recreate it with age-keygen -o');
    const r = sh('age-keygen', ['-y', kf]);
    pub = r.status === 0 ? r.stdout.trim() : null;
    check(`your public key ${pub || '(could not read)'}`, !!pub);
  }
  if (pub) check(`your public key is listed in ${RECIPIENTS}`, readRecipients().some((r) => r.key === pub),
    'send your PUBLIC key (never keys.txt) to a teammate who can run add-recipient');
  const eol = sh('git', ['check-attr', 'eol', '--', SECRETS_FILE]).stdout.trim();
  check(`.gitattributes forces LF for secrets (${eol})`, /eol: lf$/.test(eol), 'add to .gitattributes:  secrets/** text eol=lf');
  if (existsSync(SECRETS_FILE)) check(`can decrypt ${SECRETS_FILE}`, sh('sops', ['decrypt', SECRETS_FILE]).status === 0);
  process.exitCode = ok ? 0 : 1;
}

const [cmd, ...rest] = process.argv.slice(2);
try {
  switch (cmd) {
    case 'doctor': doctor(); break;
    case 'init-key': {
      const kf = keyFile();
      if (existsSync(kf)) { console.log(`Key already exists: ${kf}`); break; }
      mkdirSync(dirname(kf), { recursive: true });
      must(sh('age-keygen', ['-o', kf], { stdio: ['ignore', 'inherit', 'inherit'] }), 'age-keygen');
      console.log(`Private key saved to ${kf}. Back it up. Share ONLY the public key above.`);
      break; }
    case 'list': console.log(names(decryptJson()).join('\n')); break;
    case 'get': {
      if (!rest[0]) throw new Error('usage: get <name>');
      process.stdout.write(must(sh('sops', ['decrypt', '--extract', toIndex(rest[0]), SECRETS_FILE]), 'get'));
      if (process.stdout.isTTY) process.stdout.write('\n');
      break; }
    case 'set': {
      if (rest.length !== 1) throw new Error('usage: set <name>   (the value is prompted for, never an argument)');
      const value = await readValue();
      ensureFile();
      // sops set wants JSON, so send the raw text as a JSON string on stdin.
      must(sh('sops', ['set', '--value-stdin', SECRETS_FILE, toIndex(rest[0])], { input: JSON.stringify(value) }), 'set');
      console.error(`Updated ${rest[0]} in ${SECRETS_FILE}`); break; }
    case 'unset': {
      if (!rest[0]) throw new Error('usage: unset <name>');
      must(sh('sops', ['unset', SECRETS_FILE, toIndex(rest[0])]), 'unset');
      console.error(`Removed ${rest[0]} from ${SECRETS_FILE}`); break; }
    case 'edit': {
      const r = sh('sops', ['edit', SECRETS_FILE], { stdio: 'inherit' });
      if (r.status !== 0 && r.status !== 200) throw new Error('edit failed'); // 200 = no changes
      break; }
    case 'run': {
      const argv = rest[0] === '--' ? rest.slice(1) : rest;
      if (!argv.length) throw new Error('usage: run -- <command> [args...]');
      const env = { ...process.env };
      // The child gets the secrets, but never the key that decrypts them.
      for (const k of ['SOPS_AGE_KEY', 'SOPS_AGE_KEY_FILE', 'SOPS_AGE_KEY_CMD']) delete env[k];
      for (const [k, v] of Object.entries(decryptJson())) if (v !== null && typeof v !== 'object') env[k] = String(v);
      // Windows needs a shell to start npm.cmd and other .cmd/.bat files. Pass one
      // command string there (Node warns about args arrays with shell:true, DEP0190).
      const r = isWin
        ? spawnSync(argv.map((a) => (/[\s"]/.test(a) ? `"${a.replace(/"/g, '\\"')}"` : a)).join(' '), { stdio: 'inherit', env, shell: true })
        : spawnSync(argv[0], argv.slice(1), { stdio: 'inherit', env });
      if (r.error) throw new Error(`${argv[0]}: ${r.error.code}`);
      process.exitCode = r.status ?? 1; break; }
    case 'check': check(); break;
    case 'add-recipient': {
      const [key, ...name] = rest;
      if (!/^age1[0-9a-z]+$/.test(key || '') || !name.length) throw new Error('usage: add-recipient <age1...> <name>');
      writeRecipients([...readRecipients().filter((r) => r.key !== key), { key, name: name.join(' ') }]);
      console.log(`Added ${name.join(' ')}. Commit .sops/recipients.txt, .sops.yaml and secrets/.`); break; }
    case 'remove-recipient': {
      const who = rest.join(' '); const list = readRecipients();
      const keep = list.filter((r) => r.name !== who && r.key !== who);
      if (keep.length === list.length) throw new Error(`no recipient matches "${who}"`);
      if (!keep.length) throw new Error('refusing to remove the last recipient');
      writeRecipients(keep, { rotate: true });
      console.log('Removed and rotated. Old commits are still readable with the removed key: change the real credentials now.'); break; }
    default:
      console.log(readFileSync(new URL(import.meta.url), 'utf8').split('\n').slice(1, 15).map((l) => l.replace(/^\/\/ ?/, '')).join('\n'));
      if (cmd) process.exitCode = 1;
  }
} catch (e) { console.error(`secret: ${e.message}`); process.exitCode = 1; }

Worked example: shared test credentials

Here’s the whole life cycle for the most common case: a test environment whose API credentials the team and CI all share. The file is secrets/test.enc.yaml, with three values.

1. The first person sets it up

  1. Install the tools (above) and copy the kit into the repository.
  2. Make your key: node scripts/secret.mjs init-key. Note the age1… public key it prints.
  3. Add yourself: node scripts/secret.mjs add-recipient age1… "fred laptop"
  4. Make a key for CI and add its public half the same way, as "github actions". The commands are in the CI section below.
  5. Add the values. Each one prompts twice, with nothing shown on screen.
  6. Turn on the hook and commit: .sops/, .sops.yaml, secrets/, the scripts, the hook and the workflow.
node scripts/secret.mjs set API_BASE_URL
node scripts/secret.mjs set API_CLIENT_ID
node scripts/secret.mjs set API_CLIENT_SECRET
git config core.hooksPath .githooks

The generated .sops.yaml looks like this. Don’t edit it; edit the access list through the helper.

# GENERATED by scripts/secret.mjs from .sops/recipients.txt - do not edit by hand
creation_rules:
  - path_regex: ^secrets[/\\].*\.enc\.(ya?ml|json|env)$
    age:
      - age1dllsvfjmvwm6m9aw2x67eqtdg2l6zmvc7gxfdja00zspdd36z3tqm2tfj4 # fred laptop
      - age1yuazqjv5xwg9va4pjgt8vfcuyzzv3tse359cqur49l8u6dak2ptqlzr5zx # github actions

Keep at least two recipients at all times, such as a person and CI. Better still, keep a third, offline backup key in a password manager. If every private key is lost, so is the data.

2. Daily use

node scripts/secret.mjs run -- npm run test:integration

That runs your tests with exactly the values CI uses. list shows what names exist, and set NAME changes one. Every change goes through a pull request that shows the name, never the value.

3. Onboarding a teammate

  1. The newcomer installs the tools and runs init-key. They send only the public key, over any channel; public keys aren’t secret.
  2. An existing member runs add-recipient age1… "dana laptop" on a branch and opens a pull request. The diff is one line in recipients.txt, one in .sops.yaml, and one new entry per secret file. It has to be an existing member, because re-keying has to decrypt the data key first. You can’t add yourself.
  3. After the merge, the newcomer pulls and runs node scripts/secret.mjs doctor. Every line should say OK.

4. CI with GitHub Actions

CI gets its own age key, and only its private half goes into GitHub, as one secret named SOPS_AGE_KEY on an environment called test:

age-keygen -o ci-age-key.txt                       # prints the public key -> add-recipient
grep '^AGE-SECRET-KEY-' ci-age-key.txt | gh secret set SOPS_AGE_KEY --env test
rm ci-age-key.txt                                  # or keep it offline in a password manager

Store only the AGE-SECRET-KEY-1… line. GitHub warns that structured blobs make hiding the secret in logs much less likely to work. CI doesn’t need the age tool at all, because sops has age built in. It does need sops, and I install it from a pinned release with its checksum written into the repo, so it can only change through a reviewed pull request:

name: Setup sops (pinned)
description: Install a pinned sops release and verify its SHA-256.
inputs:
  version:
    default: v3.13.3
  sha256:
    default: e5bec3346a873ae91d871550f3e698c1aad962aff462a080e40f25fde17fef6b
runs:
  using: composite
  steps:
    - shell: bash
      env:
        SOPS_VERSION: ${{ inputs.version }}
        SOPS_SHA256: ${{ inputs.sha256 }}
      run: |
        set -euo pipefail
        tmp="$(mktemp -d)"
        curl -fsSL -o "$tmp/sops" \
          "https://github.com/getsops/sops/releases/download/${SOPS_VERSION}/sops-${SOPS_VERSION}.linux.amd64"
        echo "${SOPS_SHA256}  $tmp/sops" | sha256sum -c -
        sudo install -m 0755 "$tmp/sops" /usr/local/bin/sops
        rm -rf "$tmp"
        sops --version --disable-version-check

I didn’t use a marketplace action for this. The two I looked at default to “latest,” I found no checksum verification in either, and any third-party action in the job can read the key. This one is for x64 runners; arm64 needs the .linux.arm64 file and its own hash. To upgrade, change version and sha256 in a pull request.

Then the workflow. Change npm run test:integration to whatever your project uses:

name: integration-tests
on:
  push:
    branches: [main]
  pull_request:
  workflow_dispatch:
permissions:
  contents: read
jobs:
  secrets-hygiene:            # needs no secrets, so it also runs on fork PRs
    runs-on: ubuntu-24.04
    steps:
      - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
        with:
          persist-credentials: false
      - uses: ./.github/actions/setup-sops
      - run: node scripts/secret.mjs check

  integration:
    needs: secrets-hygiene
    if: >-
      github.actor != 'dependabot[bot]' &&
      (github.event_name != 'pull_request' ||
       github.event.pull_request.head.repo.full_name == github.repository)
    runs-on: ubuntu-24.04
    environment: test
    concurrency:
      group: integration-test-env
      cancel-in-progress: false
    steps:
      - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
        with:
          persist-credentials: false
      - uses: ./.github/actions/setup-sops
      - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
        with:
          node-version: 22
          cache: npm
      - run: npm ci
      - name: Mask decrypted values
        env:
          SOPS_AGE_KEY: ${{ secrets.SOPS_AGE_KEY }}
        run: |
          sops decrypt --output-type json secrets/test.enc.yaml \
            | jq -r '.. | strings' \
            | while IFS= read -r line; do [ -n "$line" ] && echo "::add-mask::$line"; done
      - name: Integration tests
        env:
          SOPS_AGE_KEY: ${{ secrets.SOPS_AGE_KEY }}
        run: node scripts/secret.mjs run -- npm run test:integration

Why each piece is there:

  • Two jobs. The hygiene job runs check on every pull request, forks included, and needs no key. The integration job is the only one that decrypts.
  • Least privilege. permissions: contents: read limits the job’s token, and persist-credentials: false stops checkout from leaving it in .git/config.
  • The if: skips Dependabot and pull requests from forks. They don’t get secrets anyway, so this avoids a confusing decrypt failure.
  • concurrency stops two runs from using the one shared test environment at the same time.
  • Masking. Decrypted values aren’t GitHub secrets, so GitHub won’t hide them in logs on its own. The mask step registers each one before anything else can print it. Do this in every job that decrypts, and never pass values through $GITHUB_ENV or step outputs.
  • The key only where it’s needed. SOPS_AGE_KEY is set on the two steps that use it, never written to disk, and stripped from the test process by run.
  • Never “fix” fork pull requests with pull_request_target. That trigger has secrets and must not check out untrusted code.

One trade-off to decide on purpose: anyone with write access can push a branch that changes the workflow to leak the key. You can restrict the test environment to main (which also stops pull requests from running integration tests), require a reviewer to approve each run, or accept the risk, since people with write access are usually recipients already. Check your plan, too: required reviewers on GitHub Free, Pro and Team work only in public repositories, and environment secrets in private repositories need Pro or Team.

5. Offboarding: order matters

  1. Remove the key: node scripts/secret.mjs remove-recipient "bob laptop". This re-keys and rotates every file. Merge it.
  2. Then change the real credentials at the test service, and store the new ones with set. The SOPS docs are explicit about the order: “if you put in new credentials before completing this step, the compromised key could still have access to those.”

Step two is not optional. Git keeps every old version of the file, and a removed key still decrypts every old commit. Removing someone protects only what you write from now on. The person probably also has the values on their machine or in their memory. The only real fix is new credentials.

6. Rotation

  • The data key: run sops rotate -i secrets/test.enc.yaml on a regular schedule; the SOPS docs recommend renewing it. remove-recipient already does this.
  • The CI key: treat it like offboarding a person. Make a new key, add-recipient it, remove-recipient the old one, update the SOPS_AGE_KEY secret, and change the real credentials if the old key may have leaked.
  • Any value that was ever printed to a log, a chat or an agent transcript: rotate that credential.

Guardrails for AI agents

Here’s the idea again, because it’s the reason I like this setup so much right now: the agent may use secrets; it must never see them. In practice that comes down to six habits:

  1. Plaintext exists only inside a child process’s environment, through secret.mjs run. Never on screen, in a file, or in a command argument.
  2. The key lives outside the repo, at the operating system’s default path. Don’t export SOPS_AGE_KEY in a shell an agent uses: every command the agent runs would inherit it.
  3. Allow agents only exact commands: list, plus specific run -- <command> lines. Deny get, set, edit and raw sops.
  4. Write the rules down in AGENTS.md, which most agents read.
  5. Back it up with the pre-commit hook and the CI check.
  6. Rotate anything that was printed.

Paste this into your AGENTS.md. Codex reads AGENTS.md directly. Claude Code reads CLAUDE.md, so create one containing the single line @AGENTS.md and it imports the same rules.

## Secrets (SOPS + age)

Secrets live encrypted in `secrets/*.enc.yaml`. The decryption key is on the developer's
machine, outside this repository. You may USE secrets; you must never SEE them.

Do:
- Run anything that needs secrets through `node scripts/secret.mjs run -- <command>`.
  Example: `node scripts/secret.mjs run -- npm run test:integration`
- Use `node scripts/secret.mjs list` to see which secret names exist (it never prints values).
- If a secret is missing or wrong, stop and ask the developer to run
  `node scripts/secret.mjs set <name>` themselves. Tell them the name; never ask for the value.

Never:
- Run `sops` directly, or `node scripts/secret.mjs get|set|unset|edit`.
- Print environment variables (`env`, `printenv`, `echo $VAR`, `console.log(process.env)`).
- Read the age key file (`keys.txt`) or anything under `~/.config/sops`,
  `~/Library/Application Support/sops`, or `%AppData%\sops`.
- Write decrypted values to a file, log, commit, test fixture, or chat message.
- Hard-code a secret value in code, even temporarily.
- Edit `secrets/*.enc.yaml` or `.sops.yaml` by hand.

If you see a secret value in any output, stop, tell the developer which value it was,
and do not repeat it. It must be rotated.

For Claude Code, the kit’s .claude/settings.json turns those rules into permissions. Change the run line to your own test command:

{
  "$schema": "https://json.schemastore.org/claude-code-settings.json",
  "permissions": {
    "deny": [
      "Read(~/.config/sops/age/**)",
      "Read(~/Library/Application Support/sops/age/**)",
      "Read(keys.txt)", "Read(*.agekey)", "Read(*.dec.*)",
      "Read(./.env)", "Read(./.env.*)",
      "Bash(sops *)",
      "Bash(node scripts/secret.mjs get *)", "Bash(node scripts/secret.mjs set *)",
      "Bash(node scripts/secret.mjs unset *)", "Bash(node scripts/secret.mjs edit*)",
      "Bash(env)", "Bash(printenv*)"
    ],
    "allow": [
      "Bash(node scripts/secret.mjs list)",
      "Bash(node scripts/secret.mjs run -- npm run test:integration)"
    ]
  }
}
  • Keep the allow rules exact. A wildcard such as run * would also approve run -- env, which prints every value.
  • Deny rules apply right away; committed allow rules wait until each teammate trusts the folder.
  • Read rules cover Claude Code’s own file tools plus cat, head, tail, sed, tee and redirections. They don’t cover grep -r, or a Python or Node script that opens files itself.
  • The key paths in the deny list are the macOS and Linux ones. I haven’t verified the equivalent rule for the Windows path yet, so on Windows lean on the other habits.

Codex uses AGENTS.md. Its docs say it keeps environment variables named like *KEY*, *SECRET* and *TOKEN* by default, and drops them only when shell_environment_policy.ignore_default_excludes = false, which is one more reason not to keep the age key in an environment variable. Cursor’s own docs say .cursorignore “cannot block” terminal access, so there rely on the key living outside the project, on approving terminal commands, and on AGENTS.md.

An honest limit. These rules prevent accidents. They aren’t a wall against a determined agent: one allowed to run run -- npm test could try run -- env. What actually stops that is approving exact commands, or an operating-system sandbox that hides the key. Claude Code’s sandbox does this on macOS and Linux (it isn’t available on native Windows):

{ "sandbox": { "enabled": true, "allowUnsandboxedCommands": false,
  "filesystem": { "denyRead": ["~/.config/sops/age", "~/Library/Application Support/sops/age"] } } }

The cost is that nothing the agent runs can decrypt, run included, so a person runs those commands. Choose per project: permission rules for convenience, or the sandbox for strength.

Keeping plaintext out

Three layers make sure only ciphertext ever reaches the repository. First, .gitattributes forces Unix line endings on everything sops reads, whatever each person’s Git settings say. If files were committed before you added it, run git add --renormalize . once.

* text=auto
secrets/**    text eol=lf
.sops.yaml    text eol=lf
.sops/**      text eol=lf
.githooks/**  text eol=lf

Second, .gitignore lets only encrypted files into secrets/ and keeps decrypted copies and keys out everywhere:

# Only encrypted files may live in secrets/
secrets/*
!secrets/*.enc.yaml
!secrets/*.enc.json
!secrets/*.enc.env
!secrets/README.md
# Decrypted copies and keys never get committed
*.dec.*
*.decrypted.*
.env
.env.*
!.env.example
keys.txt
*.agekey

Third, a pre-commit hook checks the staged copy of every file in secrets/ and refuses anything that isn’t encrypted or isn’t named *.enc.yaml, *.enc.json or *.enc.env:

#!/usr/bin/env bash
# .githooks/pre-commit - refuse to commit plaintext into secrets/.
# Enable once per clone:  git config core.hooksPath .githooks
set -euo pipefail
fail=0
while IFS= read -r -d '' f; do
  case "$f" in secrets/README.md|secrets/.gitkeep) continue ;; esac
  case "$f" in
    *.enc.yaml|*.enc.yml|*.enc.json|*.enc.env) ;;
    *) echo "pre-commit: $f must be named *.enc.yaml, *.enc.json or *.enc.env" >&2; fail=1; continue ;;
  esac
  # Check the STAGED copy (what will be committed), not the working tree.
  if ! git show ":$f" | grep -qE '^sops:|"sops": *\{|^sops_'; then
    echo "pre-commit: $f looks like PLAINTEXT. Encrypt it before committing." >&2; fail=1
  fi
done < <(git diff --cached --name-only -z --diff-filter=ACMR -- secrets/)
exit "$fail"

Hooks aren’t cloned, so each person runs git config core.hooksPath .githooks once per clone. Hooks can also be skipped with --no-verify, which is why CI runs check as the backstop. If someone adds the hook on Windows, they should mark it executable with git update-index --chmod=+x .githooks/pre-commit.

Gotchas worth knowing

  • Names aren’t encrypted, and neither are file names or structure. The rough length of each value is visible too.
  • Encrypt every value, which is the default. sops’s encrypted_regex is case-sensitive and fails silently: ^(password|token)$ encrypts nothing in a file whose key is DB_PASSWORD.
  • Editing .sops.yaml doesn’t re-key existing files. The helper re-keys for you, and check catches files that drifted.
  • sops filestatus exits 0 even for plaintext. Read its JSON instead, as check does.
  • sops set wants JSON, and a flag placed after the file name is ignored with only a warning. The helper handles both.
  • sops edit writes plaintext to a temporary file while you edit, and returns status 200 when nothing changed.
  • Merge conflicts are awkward, because the checksum changes on every edit. Keep secret files small, and split them by audience.
  • Masking hides more than secrets, such as URLs in logs. Keep plain settings outside secrets/, and keep very short values like 1 or true out of the secrets file.
  • Decrypting Git diffs (a diff=sopsdiffer setup) show real values. Keep that out of CI and away from agents.

When not to use this

SOPS and age are an encrypted file, not a secrets manager. There are no access logs, no per-value permissions (a recipient can read the whole file), no short-lived credentials, and revoking access is manual. The private key is just a file, so anything running as you can read it. And Git history is forever. That makes it a great fit for shared test and development credentials, and non-production configuration that a team and CI both need, and a poor fit for these:

If you needUse instead
Production or high-value credentialsGitHub secrets, or better, OIDC short-lived tokens. A replaced GitHub secret is gone; ciphertext in Git lives forever.
CI-only values no person needs, such as deploy or signing keysGitHub secrets
Instant revocation, audit logs, rotation at scaleVault or a cloud secret manager. SOPS can use their KMS keys as recipients.
A team that won’t manage keysGitHub secrets
The simplest tool for a .env-only teamdotenvx is a fair alternative. By default it uses one shared private key per environment.
Whole-file encryption you already usegit-crypt works, but diffs are unreadable, it’s built around GPG, and it can’t revoke access.

Tested so far

I want to be clear about what’s been run and what hasn’t. The helper and the pre-commit hook were tested on macOS with sops 3.13.3, age 1.3.2 and throwaway keys: creating keys, adding and removing recipients, setting values through the hidden prompt and through a pipe, run passing values but not the key, check catching plaintext and drift, onboarding, and offboarding, including confirming that a removed key still opens old commits.

Not yet run: anything on Windows (the hidden prompt, run starting .cmd programs, the %AppData% key path, and the hook under Git for Windows), and the composite action and workflow in GitHub Actions. They follow the documentation closely, but treat them as a careful starting point and try them in your own repository before you depend on them.

Need a hand?

Bringing this to a team

Setting this up in one repository is quick. Rolling it out across a team’s repositories, CI and AI agents, with keys people actually keep track of, is where I can help.

Start a conversation