Cooper Maruyama
丸山

half-stack developer

Simple Typechecks for SOPS in Typescript

I've always hated .env files. The repo typically ships with a .env.example which you copy and then manually fill in each value, usually missing some, and most likely run into some runtime exception because you forgot one.

Even worse, every time someone on the team adds a new environment variable, everyone's app breaks on the next pull until they also add the value.

This is why https://getsops.io has been one of my favorite utilities I've recently been using. The only issue is that your code doesn't know which keys are actually defined in the SOPS files themselves. But there's actually a dead simple way to solve that problem without having to add any libraries or anything.

At some point recently, Typescript added native support for JSON, meaning that if you import foo from "./foo.json", the foo object will have its keys typed, so your type checked can yell at you if you use a key that doesn't exist.

The first requirement is that you stop using .yaml or .env as the extension for your SOPS files. Using JSON instead now has a real upside.

The next step depends on how you perform decryption. If you do sops exec-env secrets.json 'npm start', then you can do something like this:

// env.ts
import type * as Secrets from "./secrets.json"

declare global {
  namespace NodeJS {
    interface ProcessEnv extends Record<keyof typeof Secrets, string> {}
  }
}

process.env.FOO // typed, will complain if doesn't exist