tmh, the TeachMeHIPAA CLI

Stripe CLI: research notes for teachmehipaa-cli

Sources: the stripe/stripe-cli source at commit 78a032ff933e9924ff306123fbe373c1ee885c55 (2026-11-13), shallow-cloned to ~/scratch/stripe-src/stripe-cli, plus docs.stripe.com/cli/* (fetched 2026-11-15). Code links are pinned to that commit (https://github.com/stripe/stripe-cli/blob/78a032ff…/<path>). Repo files were read as data. Nothing was built or run.

Note: docs.stripe.com/stripe-cli/* now redirects to docs.stripe.com/cli/*. The old /stripe-cli/telemetry and /stripe-cli/keys pages are gone (404), so the telemetry claims below come from source code only.

TL;DR

  1. Go (go.mod says go 1.27.3), cobra + viper + pflag, TOML config at ~/.config/stripe/config.toml, OS keyring through zalando/go-keyring with a 0600 file fallback.
  2. Resource commands (stripe customers create --name=…) are generated by go generate from a CLI-specific OpenAPI file. The generator depends on Stripe’s own x-stripeOperations extension (method_name, method_on). Generic NewOperationCmd executors do the actual work at runtime.
  3. Custom methods are ordinary sub-verbs: stripe charges capture <id>, stripe payment_intents confirm <id>. Path params become positional args. Body params become --kebab-flags, and -d key[nested]=v is the escape hatch.
  4. Login used to be a browser “pairing code” flow that minted a 90-day restricted key. It is now RFC 8628 device-code OAuth against access.stripe.com, with a refresh token in the keyring and silent refresh. --interactive still lets you paste a key, and --non-interactive prints JSON for agents.
  5. listen depends on Stripe server infrastructure. POST /v1/stripecli/sessions returns a websocket URL and a whsec_ secret. Stripe signs each event server-side, and the CLI passes the headers through to --forward-to.
  6. trigger is a client-side fixture runner: embedded JSON sequences of API calls with ${step:path} references. It creates real objects, and the events come out of that as a side effect.
  7. There is no auto-pagination: only --limit / --starting-after / --ending-before. Other request flags: -i sets Idempotency-Key, -v/--stripe-version, --stripe-account, -e expand, -s show headers, --dry-run, --live.
  8. Output is pretty-printed, colorized JSON on a TTY and raw JSON otherwise. There is no --format on API calls; --format json exists only for listen and logs tail. Non-401 HTTP errors print the body and appear to exit 0.
  9. Telemetry goes to r.stripe.com/0 and Sentry. Opt out with STRIPE_CLI_TELEMETRY_OPTOUT=1 or DO_NOT_TRACK=1. Self-update is signed and applies only to script installs. Plugins are HashiCorp go-plugin over gRPC.
  10. Releases go through three GoReleaser configs: Homebrew tap, Scoop, winget, deb/rpm on Artifactory, Docker Hub multi-arch, npm optionalDeps wrapper, macOS notarization, and RSA-signed checksums.

1. Repo layout, language, dependencies

2. Command inventory

Registered in init() of pkg/cmd/root.go:

Command What it does Source
login (list, switch) Browser/device auth. --interactive pastes a key, --non-interactive prints JSON, --complete <poll-url>, --new-session pkg/cmd/login.go
logout, reauth, whoami, switch Revoke session, change granted permissions, show identity and authorized accounts, pick an account or sandbox (live/test) pkg/cmd/logout.go, reauth.go, whoami.go, switch.go
listen Webhook forwarding over a websocket (section 6) pkg/cmd/listen.go
trigger <event> Runs an embedded fixture that produces the event pkg/cmd/trigger.go
fixtures <file> Runs a user-supplied fixture JSON pkg/cmd/fixtures.go
logs tail Live API request log stream over a websocket, with --filter-* flags and --format json pkg/cmd/logs/tail.go
events resend <id> Handwritten override of the generated events resource. Posts /v1/events/{event}/retry and adds for_stripecli=true unless --webhook-endpoint is given pkg/cmd/resource/events_resend.go
get / post / delete <path or id> Raw HTTP verbs. get ch_123 infers the path from the ID prefix. Also available under stripe preview pkg/cmd/http.go, get.go
<resource> <operation> Generated from OpenAPI (section 3). Also stripe v2 … and stripe preview … namespaces. stripe resources lists them pkg/cmd/resources/resources_gen.go
open <shortcut> Opens Dashboard or docs pages from a static map pkg/cmd/open.go
config --list, --set, --unset, -e edit, --remove-profile pkg/cmd/config.go
completion Writes bash, zsh or fish scripts (no PowerShell flag) pkg/cmd/completion.go
version (-v) Prints the version and checks GitHub for a newer release pkg/cmd/version.go
docs, docs api, docs search Renders docs.stripe.com in the terminal pkg/cmd/docs/
sandboxes (create, claim, list, delete) Provisions a claimable sandbox without a browser, aimed at agents pkg/cmd/sandbox.go
plugin (install, upgrade, uninstall, list, auto-update) Plugin management (section 8) pkg/cmd/plugin/
agent setup, daemon, data, reporting, feedback, community, provision, postinstall Agent tooling, gRPC daemon, metrics/Sigma previews, misc pkg/cmd/agent.go, daemon.go
samples, serve, status, terminal quickstart Removed in v1.51.0. They remain as hidden stubs that print guidance and exit non-zero pkg/cmd/samples.go

The global --map [tree|compact|paths|json] flag prints the whole command tree, which is useful for agents (pkg/cmd/map.go). Agent detection runs throughout the CLI: AIAgentHelpAnnotationKey adds help text for agents, and useragent.DetectAIAgent switches login to non-interactive mode (pkg/cmd/root.go, pkg/cmd/login.go).

3. Resource commands generated from OpenAPI

4. Auth and login

5. Output, errors, exit codes

6. listen and trigger

7. Pagination, idempotency, versioning, expand

All of these are registered in Base.InitFlags (pkg/requests/base.go):

8. Self-update, version check, telemetry, plugins

9. Distribution and release

10. Testing, CI, project docs


Adopt / Adapt / Skip for teachmehipaa-cli

Our API, from ~/scratch/tmh-sdks/openapi/openapi.developer.json, has these properties:

Stripe CLI capability Verdict teachmehipaa-cli mapping
Cobra + Viper + TOML config, XDG path, 0600 Adopt ~/.config/teachmehipaa/config.toml with [profiles.<name>] (start with the v2 nested layout so no migration is needed later). --profile/-p, env TMH_PROFILE.
Spec-driven resource commands (go generate → generated wiring + OperationSpec table + generic executor) Adopt (pattern) / Adapt (input) Stripe’s generator depends on x-stripeOperations, which we don’t have. Derive from tag + operationId instead: tag → resource (enrollments), operationId minus the noun → verb (createEnrollment→create, cancelEnrollment→cancel, resendEnrollmentInvite→resend-invite). Add an optional x-tmh-cli: {resource, verb, hidden} override instead of a hand switch like GetResourceCmdName. Path params become positional args, but orgId becomes a persistent --org flag / profile default because nearly every path starts with it.
AIP-136 custom methods as sub-verbs Adopt tmh enrollments cancel <id> → POST …/enrollments/{id}:cancel. Collection-level methods (enrollments:batch, :import, :export) become tmh enrollments batch. Escape the colon correctly in path templating.
Body params as --kebab flags, nested as dotted, -d key[sub]=v escape hatch Adapt Our bodies are JSON, so follow Stripe’s v2 path (BuildDataForV2Request): flags plus -d path.to.key=value assembled into JSON, plus --data @file.json / - for stdin. Skip the form-encoding (v1) path entirely.
get/post/delete <path> raw verbs Adopt tmh api <METHOD> <path> (gh-style) or tmh get/post/patch/put/delete. We need PATCH and PUT, which Stripe lacks at the top level. No ID-prefix inference unless our IDs become prefixed.
stripe login browser pairing → restricted key / device code Adapt Two modes. (a) tmh login = auth-code + PKCE (S256) through a loopback redirect (http://127.0.0.1:<random>/callback) to console.teachmehipaa.com/oauth/authorize. The rotating refresh token goes in the keyring, with silent refresh like refreshOAuthToken. Add --no-browser that prints the URL (and a paste-the-code fallback), plus --non-interactive JSON {browser_url, next_step} for agents, copying Stripe’s two-step design. (b) tmh login --client-credentials (or TMH_CLIENT_ID/TMH_CLIENT_SECRET env) stores the client id and secret in the keyring and mints a 15-min JWT on demand, caching it in memory or keyring with its exp. There’s no refresh token, so we just re-run the grant. Device code (RFC 8628) would need a new server endpoint; consider it later.
Rotating-refresh handling Adopt + fix Copy the logic: store a new refresh token when one is returned, wipe on invalid_grant, retry once on 401. Use a cross-process file lock (flock on ~/.config/teachmehipaa/.refresh.lock) instead of Stripe’s in-process sync.Mutex, because a rotating token raced by two shells logs the user out.
Keyring with 0600 file fallback + warning Adopt Never write secrets to the TOML. Stripe writes test keys in plaintext; skip that.
--live per-command flag (default test) Adapt --sandbox vs live per profile (environment = "sandbox"\|"live" → base URL), plus a --sandbox override flag. Print a context banner the way PrintActiveContextBanner does, and require confirmation for live DELETE or cancel-type custom methods (copy the DELETE confirm, -y/--yes to skip).
Pretty and colorized JSON on TTY, raw when piped Adopt + extend Add --output json\|yaml\|table and --jq <expr> / --template (gh-style), which Stripe lacks for API calls. Honor NO_COLOR.
Exit 0 on non-401 HTTP errors Skip (do better) Parse problem+json and render title/detail/errors[] to stderr. Map exit codes: 0 ok, 1 generic, 2 usage, 3 auth (401/403), 4 not found, 5 conflict/precondition (409/412), 6 validation (422), 7 rate-limited, 8 server. Keep the raw body available via --output json.
-s/--show-headers, --dry-run, -H custom header, --log-level Adopt Add --verbose that dumps request and response with Authorization redacted. --dry-run with a redacted token, exactly like BuildDryRunOutput.
Manual cursor flags only Adapt Generate --limit and --cursor (or --after for events). Add --all/--page-limit N, which follows nextCursor and streams NDJSON. Stripe has no auto-pager; ours should.
-i/--idempotency Adopt + extend --idempotency-key. Auto-generate a UUIDv4 for every POST to an operation whose spec declares the idempotencyKey header, and print it with --verbose so retries can reuse it. Stripe doesn’t auto-generate.
--stripe-version pinned from the spec info.version Adapt Pin the generated spec version in User-Agent/X-TMH-Client for diagnostics. We version by URL (/v1), so we don’t need a version flag.
-e/--expand Adapt Map onto our include query param where the spec has it (e.g. listEnrollments). Generated automatically as a normal flag.
AIP-151 LROs New (no Stripe analog) For operations returning an Operation (:import, :export, :batch), add --wait that polls getOperation with backoff and a spinner, then prints the result or the problem. Add tmh operations get <id> / tmh operations wait <id>. Exports end in a download, so add --out <file> (Stripe’s PDF auto-save is the precedent).
listen (server websocket relay; Stripe signs server-side) Adapt (major) We have no relay. Build tmh events tail: poll GET /organizations/{orgId}/events?after=<cursor>&type=… (cursor persisted per profile so restarts resume), print one line per event or NDJSON with --output json, and filter with --type a,b. --forward-to <url> POSTs each event locally and re-signs it locally: generate a per-profile local secret (tmh events tail --print-secret, stable across restarts like Stripe’s whsec_) and compute x-tmh-signature the same way production does. The signature covers the forward-to path+query, so compute it per destination. That lets the user’s verifier run unchanged against the local secret. Show the local status like Stripe’s webhook_response. Latency is the poll interval (2–5 s default, --interval). A server-side SSE or websocket relay could come later.
events resend Adapt Map to webhook-subscriptions redrive / test (already AIP-136 verbs in the spec). Locally, add tmh events forward <eventId> --forward-to … to replay one event from the pull log through the local re-signer.
trigger (fixture runner creating real objects) Adapt tmh trigger enrollment.created runs embedded fixture JSON against sandbox only (create learner → create enrollment → :cancel…), using the same ${step:path} reference syntax. Or call webhook-subscriptions:test where a synthetic event is fine. Refuse to run against live.
fixtures <file> Adopt (later) Same engine as trigger, for seeding sandbox orgs.
logs tail (request log websocket) Skip (for now) We have no request-log stream API. Revisit if we expose one. audit-events list --all covers part of it.
open shortcuts Adopt (cheap) tmh open console\|docs\|api-clients\|webhooks → static URL map.
config --set/--list/--edit, whoami, logout (revoke), switch Adopt whoami calls GET /auth/introspection. logout revokes the refresh token and clears the keyring. switch changes the default org for partner (multi-org) tokens via listPartnerOrganizations.
completion Adopt + extend cobra bash/zsh/fish plus PowerShell (Stripe omits it).
--map json / agent annotations / non-interactive auto-detect Adopt Cheap, and our API’s audience includes AI agents.
samples, serve, status, sandboxes create, docs, data, reporting, daemon/gRPC Skip Stripe-specific or already deprecated (samples/serve/status removed in v1.51.0).
Plugin system (go-plugin + gRPC + manifest) Skip (v1) Heavy. If ever needed, use gh-style tmh-<name> executables found on PATH.
Version check (GitHub API, 24 h cache, grace period, install-method advice, *_NO_UPDATE_CHECK) Adopt Same, with TMH_NO_UPDATE_CHECK.
Signed self-update (script installs only) Adapt (phase 2) Copy the model: RSA- or ed25519-signed checksums, verify before swap, never cross a major version, TMH_NO_AUTO_UPDATE. Ship the install script with signature checks first.
Telemetry (r.stripe.com + Sentry, flag names only, *_TELEMETRY_OPTOUT, DO_NOT_TRACK) Adapt HIPAA context: telemetry off by default (or opt-in on first run), never send org/learner IDs, honor DO_NOT_TRACK and TMH_TELEMETRY_OPTOUT. If enabled, send command path + flag names + version/os/arch + http outcome bucket, and send it to our own PostHog proxy, not a third party.
GoReleaser: Homebrew tap, Scoop, winget, deb/rpm, Docker multi-arch, npm optionalDeps shim, macOS notarize, signed checksums Adopt (staged) v1: GitHub Releases + Homebrew tap (teachmehipaa/homebrew-tap) + signed checksums + macOS notarization + install script. v1.1: Scoop, winget, npm shim (@teachmehipaa/cli, which fits our Node users), Docker ghcr.io/teachmehipaa/cli. Skip Artifactory deb/rpm until someone asks. Add Windows Authenticode, which Stripe lacks.
Canary E2E against the compiled binary + offline subset; 3-OS CI matrix; generator diff check Adopt Offline canaries against a mock server built from the spec (e.g. Prism) plus a sandbox suite. CI fails if go generate output differs from what’s committed.
Spec sync bot PR Adopt Workflow pulls openapi.developer.json from the platform repo, regenerates, and opens a PR.

Language recommendation

Go, as a standalone binary, with its own thin generated client. Don’t layer it on one of our SDKs.

  1. Distribution decides it. A CLI’s main job is installing everywhere. Go cross-compiles static binaries (CGO only for the macOS keychain, as Stripe does with CGO_ENABLED=1 on darwin) of about 15 MB. GoReleaser then gives us Homebrew, Scoop, winget, deb/rpm, Docker, notarization and signed checksums from YAML we can copy almost line for line from .goreleaser/*.yml. A Bun --compile binary built from teachmehipaa-node is roughly 60–100 MB and has weaker keyring support (it needs native addons or shelling out to security/secret-tool).
  2. Proven parts exist. cobra, viper, zalando/go-keyring, pkg/browser, golang.org/x/oauth2 (PKCE and client-credentials built in), gorilla/websocket, testify. Stripe, gh and flyctl show the shape. We can lift Stripe’s patterns (generated OperationSpec table + generic executor, keyring fallback, non-interactive login JSON, signed self-update) directly. Stripe’s code is Apache-2.0, so keep attribution if we copy anything.
  3. The SDKs don’t fit the CLI’s job. None of our SDK repos (node/python/ruby/java/dotnet) is built yet, and a CLI needs a dynamic executor driven by spec metadata, not typed per-method SDK calls. Stripe’s CLI doesn’t use stripe-go either; it has its own pkg/requests. Our generator would output the cobra wiring plus an OperationSpec table from openapi.developer.json. Shared HTTP behavior (auth, retries, problem+json, idempotency) is about 1–2k lines of Go.
  4. Trade-off to accept: our team writes TypeScript, not Go. Because about 70% of the command surface is generated, the handwritten Go is mostly auth, events tail, --wait, and output. If Go staffing is a hard no, the fallback is TypeScript on Bun, compiled with bun build --compile, reusing @tmh/api-contracts Zod schemas for validation. Expect bigger binaries and hand-rolled packaging (no GoReleaser equivalent).