Skip to content

Commit 27836bc

Browse files
feat(setup): per-org API key variables; stop one org's key reaching another (#83)
## Value **V.A.L.U.E. tier:** small. It changes how every command picks its API key and adds a setup refusal. Not micro: it's a behavior change, and it touches key handling. - **Problem:** an exported `VAPI_PRIVATE_API_KEY` applies to every org and beats each `.env.<org>` file. That is what the docs' coding-agent prompt asks people to do, and a key in a shell profile is the natural way to make setup a single command. It works for one org. Once a second org is connected, it goes wrong without any error: - Every command for the second org uses the first org's key. The only output is `📁 Loaded env file: .env.<org>`, which suggests the file's key was used. - `npm run setup -- <second-org>` writes the first org's key into `.env.<second-org>` and downloads the first org into the second org's folder. - The interactive wizard saves the key you paste, but its download step inherits the exported key, so the same thing happens there. - **Who it affects:** anyone running more than one org from one shell, such as development, staging and production. That's the setup where gitops starts to pay off, and the one a production deploy can reach with the wrong key. - **What changes:** - **Per-org variables.** Every command looks for `VAPI_PRIVATE_API_KEY_<ORG>` first (`acme-dev` → `VAPI_PRIVATE_API_KEY_ACME_DEV`), then `VAPI_PRIVATE_API_KEY`, then `.env.<org>`. Exporting one per org in a shell profile is safe, and setup stays a single command. Org slugs are lowercase letters, digits and hyphens, so two orgs can't map to the same variable name. - **Warn, or refuse.** When the generic variable overrides a *different* key in `.env.<org>`, every command warns on stderr. The warning names both sources, never the values. `setup` refuses outright, because it would write the key and download the org. It also refuses a key that another org's `.env` file already holds. - **Say where the key came from.** Commands print `🔑 Using the API key from the VAPI_PRIVATE_API_KEY_ACME_DEV environment variable` when the key wasn't read from `.env.<org>`. - **Pin the chosen key in child processes.** The wizard's download, and the child runs that `promote` and `check` start, all receive the key that was actually chosen. - **Placeholders count as no key everywhere.** A `.env.example` placeholder no longer gets as far as an HTTP 401. - **Docs:** README, AGENTS.md, the configuration guide, `.env.example` and `setup --help` recommend the per-org name. AGENTS.md tells agents to stop and ask rather than unset variables to silence a warning. - **Unchanged:** CI that sets `VAPI_PRIVATE_API_KEY` for a single org, `VAPI_CHECK_TOKENS` and `VAPI_PROMOTION_TOKENS` all behave as before. `.env.<org>` files still work on their own. **Alignment needed:** none beyond review. [VapiAI/docs#1371](VapiAI/docs#1371) updates docs.vapi.ai to recommend the per-org name and should merge after this. ## Evidence of value | Shell exports org A's key as `VAPI_PRIVATE_API_KEY`; `.env.org-b` holds org B's key | Before | After | | --- | --- | --- | | `npm run <command> -- org-b` | Uses org A's key; prints only "Loaded env file" | Uses org A's key and warns that it overrides `.env.org-b`, naming `VAPI_PRIVATE_API_KEY_ORG_B` as the fix | | `npm run setup -- org-b` | Writes org A's key to `.env.org-b`, downloads org A | Refuses before validating or writing anything | | `npm run setup -- org-b` with `.env.org-a` already holding that key | Same as above | Refuses: "already the key in .env.org-a" | | `VAPI_PRIVATE_API_KEY_ORG_B` exported as well | n/a | Uses org B's key, no warning | - **Tests:** new cases in `api-key.test.ts`, `setup-noninteractive.test.ts` and `org-connection.test.ts`, plus `config-api-key.test.ts`, which runs `validate` to check what a command reports about its key. Every case checks that the key values never appear in output. `tests/no-vapi-api.ts` now also clears per-org variables a developer may have exported. - **Live run** against a production org: `setup -- <org> --resources none` with the real key in `VAPI_PRIVATE_API_KEY_<ORG>` and a fake value in `VAPI_PRIVATE_API_KEY`. Setup used the per-org key, connected, wrote `.env.<org>` and synced bindings. The pull listed all 13 assistants, then stopped on a platform-side 503 from `/eval/simulation/personality` that persisted through retries. That outage is unrelated to this change. ## Testing plan - `npm run build` and `npm test` (562) pass. - **Not covered by tests:** the wizard's download step needs a TTY. After merge, run `npm run setup` in a terminal that exports a different org's `VAPI_PRIVATE_API_KEY`, paste the intended org's key, and check that the downloaded folder holds the intended org's resources. 🤖 Generated with [Claude Code](https://claude.com/claude-code)
2 parents 898a75d + 31232cc commit 27836bc

18 files changed

Lines changed: 453 additions & 65 deletions

‎.env.example‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,9 @@
1616
# Required: Vapi private API key for the organization you are syncing to.
1717
# Get one at https://dashboard.vapi.ai/org/api-keys → "Private API Keys" (not a public key).
1818
# (Older setups used VAPI_TOKEN — still accepted, VAPI_PRIVATE_API_KEY wins if both are set.)
19+
# To keep keys in your shell instead, export one per org under the org's own
20+
# name, e.g. VAPI_PRIVATE_API_KEY_MY_ORG for my-org. Don't export the generic
21+
# VAPI_PRIVATE_API_KEY in a shell profile: it overrides every org's file.
1922
VAPI_PRIVATE_API_KEY=your-vapi-private-key-here
2023

2124
# Optional: API base URL — defaults to US (https://api.vapi.ai).

‎AGENTS.md‎

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,7 @@ plain `npm run pull` (it never overwrites local edits), `npm run push -- <org>
5353
**2. Never handle API keys.** Don't ask the human to paste a key into chat,
5454
don't print or read out `.env.*` files, never pass a key as a command-line
5555
argument, and never commit `.env.*`. Keys live in `.env.<org>` (gitignored)
56-
or the environment.
56+
or the environment, as `VAPI_PRIVATE_API_KEY_<ORG>`.
5757

5858
**3. Reference resources by ID, never by UUID.** A resource's ID is its path
5959
under the type folder without the extension (`tools/lookup-patient.yml` is
@@ -98,9 +98,12 @@ wizard needs a terminal. Instead:
9898
1. `nvm use` (or check `node --version` satisfies `engines` in `package.json`), then `npm ci`.
9999
2. **Get the API key without handling it.** Ask the human to create
100100
`.env.<org>` from `.env.example` and put a Vapi **private API key** in
101-
`VAPI_PRIVATE_API_KEY`, or confirm it's already exported. Point them to
102-
https://dashboard.vapi.ai/org/api-keys → **Private API Keys** (a public key
103-
won't work).
101+
`VAPI_PRIVATE_API_KEY`, or confirm it's already exported as
102+
`VAPI_PRIVATE_API_KEY_<ORG>` (`acme-dev` → `VAPI_PRIVATE_API_KEY_ACME_DEV`).
103+
Point them to https://dashboard.vapi.ai/org/api-keys → **Private API Keys**
104+
(a public key won't work). If setup or a command reports a different key in
105+
`.env.<org>`, stop and tell the human: the exported key may be another
106+
org's. Don't unset variables or edit `.env` files to silence it.
104107
3. Ask whether to download the org's existing resources:
105108
- Managing an existing org → `npm run setup -- <org>` (`--resources all`, the default).
106109
- Authoring from scratch → `npm run setup -- <org> --resources none` (state only, no files).

‎README.md‎

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -120,10 +120,20 @@ run commands without one, so pass the org name to skip every prompt:
120120
cp .env.example .env.my-org # then paste the private API key into VAPI_PRIVATE_API_KEY
121121
npm run setup -- my-org
122122

123-
# Option B — the key is already in the environment (CI secret, shell export)
124-
VAPI_PRIVATE_API_KEY=... npm run setup -- my-org
123+
# Option B — the key is already exported under the org's own name (for example in your shell profile)
124+
export VAPI_PRIVATE_API_KEY_MY_ORG=...
125+
npm run setup -- my-org
125126
```
126127

128+
**Several orgs, one shell.** Every command looks for the org's key in this
129+
order: `VAPI_PRIVATE_API_KEY_<ORG>` (the org name upper-cased, hyphens as
130+
underscores: `acme-dev` → `VAPI_PRIVATE_API_KEY_ACME_DEV`), then
131+
`VAPI_PRIVATE_API_KEY`, then `.env.<org>`. Export the per-org name, not
132+
`VAPI_PRIVATE_API_KEY`: the generic name applies to every org, so one org's
133+
key would be used for all of them. When it overrides a different key in
134+
`.env.<org>`, commands warn and setup refuses. A CI job that works in one
135+
org can keep using `VAPI_PRIVATE_API_KEY`.
136+
127137
| Option | Default | Meaning |
128138
| --- | --- | --- |
129139
| `--region us\|eu` | `VAPI_BASE_URL` if set, else auto-detect (US, then EU) | Which Vapi API to use |

‎docs/guides/configuration.md‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,22 @@ A variable already set in your shell or CI environment takes precedence over
1515
the file. `.env.<org>.local` and `.env.local` are also read, after
1616
`.env.<org>`, and only fill in variables that are still unset.
1717

18+
### Keys in your shell
19+
20+
Commands look for an org's key in this order:
21+
22+
1. `VAPI_PRIVATE_API_KEY_<ORG>`: the org name upper-cased, with hyphens as
23+
underscores (`acme-dev` → `VAPI_PRIVATE_API_KEY_ACME_DEV`).
24+
2. `VAPI_PRIVATE_API_KEY` (or `VAPI_TOKEN`) in the environment.
25+
3. `VAPI_PRIVATE_API_KEY` (or `VAPI_TOKEN`) in `.env.<org>`.
26+
27+
To keep keys in your shell profile, export one `VAPI_PRIVATE_API_KEY_<ORG>`
28+
per org. Don't export `VAPI_PRIVATE_API_KEY` there: it applies to every org,
29+
so one org's key would be used for all of them. When the generic variable
30+
overrides a different key in `.env.<org>`, commands print a warning and
31+
`npm run setup` refuses to continue. Setup also refuses a key that another
32+
org's `.env` file already holds.
33+
1834
## CI and workflow settings
1935

2036
Set these in GitHub under **Settings → Secrets and variables → Actions**.

‎src/api-key.ts‎

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,12 +33,77 @@ export function resolveApiKey(...sources: Vars[]): string | undefined {
3333
return undefined;
3434
}
3535

36+
/** Placeholder values copied from .env.example should not count as a token. */
37+
export function isPlaceholderToken(token: string): boolean {
38+
return /^your-.*-here$/i.test(token) || token === "<your-key>";
39+
}
40+
41+
/**
42+
* The org's own key variable: `acme-dev` → VAPI_PRIVATE_API_KEY_ACME_DEV.
43+
* Org slugs are lowercase letters, digits and hyphens, so the mapping can't
44+
* collide. Unlike the generic name, one of these per org can be exported from
45+
* a shell profile without one org's key leaking into another org's commands.
46+
*/
47+
export function orgApiKeyVar(org: string): string {
48+
return `${API_KEY_VAR}_${org.toUpperCase().replace(/[^A-Z0-9]/g, "_")}`;
49+
}
50+
51+
export interface OrgApiKey {
52+
token: string;
53+
/** Where the key came from, for logs: a variable name or `.env.<org>`. */
54+
source: string;
55+
/** Set when an exported generic key overrides a different key in `.env.<org>`. */
56+
warning?: string;
57+
}
58+
59+
function usable(value: string | undefined): string | undefined {
60+
const trimmed = value?.trim();
61+
return trimmed && !isPlaceholderToken(trimmed) ? trimmed : undefined;
62+
}
63+
64+
/**
65+
* Resolve one org's key. In order: VAPI_PRIVATE_API_KEY_<ORG> in the
66+
* environment, then the generic VAPI_PRIVATE_API_KEY / VAPI_TOKEN in the
67+
* environment (how CI passes a secret), then the org's .env file values.
68+
*
69+
* The generic exported name applies to every org, so when it overrides a
70+
* different key in `.env.<org>` that is almost always a key for another org.
71+
* The result carries a warning naming both sources (never the values).
72+
*/
73+
export function resolveOrgApiKey(
74+
org: string,
75+
env: Vars,
76+
file: Vars,
77+
): OrgApiKey | undefined {
78+
const orgVar = orgApiKeyVar(org);
79+
const fromOrgVar = usable(env[orgVar]);
80+
if (fromOrgVar) return { token: fromOrgVar, source: `the ${orgVar} environment variable` };
81+
82+
const fromFile = usable(file[API_KEY_VAR]) ?? usable(file[LEGACY_API_KEY_VAR]);
83+
for (const name of [API_KEY_VAR, LEGACY_API_KEY_VAR]) {
84+
const fromEnv = usable(env[name]);
85+
if (!fromEnv) continue;
86+
const resolved: OrgApiKey = { token: fromEnv, source: `the ${name} environment variable` };
87+
if (fromFile && fromFile !== fromEnv) {
88+
resolved.warning =
89+
`Using the key in the ${name} environment variable, not the different key in .env.${org}.\n` +
90+
` An exported ${name} applies to every org, so it may belong to another org.\n` +
91+
` Unset it, or export ${orgVar} to choose this org's key explicitly.`;
92+
}
93+
return resolved;
94+
}
95+
96+
if (fromFile) return { token: fromFile, source: `.env.${org}` };
97+
return undefined;
98+
}
99+
36100
/** Human-readable fix-it text for a missing key. */
37101
export function missingApiKeyMessage(org: string): string {
38102
return [
39103
`No Vapi private API key found for org "${org}".`,
40104
` Copy a private key from ${API_KEYS_URL} (Private API Keys section),`,
41105
` then add it to .env.${org} as: ${API_KEY_VAR}=<your private API key>`,
106+
` or export ${orgApiKeyVar(org)}=<your private API key> in your shell.`,
42107
` (${LEGACY_API_KEY_VAR} is still accepted for existing setups.)`,
43108
].join("\n");
44109
}

‎src/call.ts‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { missingApiKeyMessage, resolveApiKey } from "./api-key.ts";
1+
import { missingApiKeyMessage, resolveOrgApiKey } from "./api-key.ts";
22
import { execSync } from "child_process";
33
import { existsSync, readFileSync } from "fs";
44
import { createRequire } from "module";
@@ -149,7 +149,9 @@ function loadEnvFile(env: string): { token: string; baseUrl: string } {
149149
}
150150
}
151151

152-
const token = resolveApiKey(process.env, envVars);
152+
const resolved = resolveOrgApiKey(env, process.env, envVars);
153+
if (resolved?.warning) console.warn(`⚠️ ${resolved.warning}`);
154+
const token = resolved?.token;
153155
const baseUrl =
154156
process.env.VAPI_BASE_URL || envVars.VAPI_BASE_URL || "https://api.vapi.ai";
155157

‎src/config.ts‎

Lines changed: 21 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { missingApiKeyMessage, resolveApiKey } from "./api-key.ts";
1+
import { missingApiKeyMessage, resolveOrgApiKey } from "./api-key.ts";
22
import { existsSync, readFileSync } from "fs";
33
import { basename, dirname, join, relative, resolve } from "path";
44
import { fileURLToPath } from "url";
@@ -215,7 +215,10 @@ function parseFlags(): {
215215
// Environment File Loading
216216
// ─────────────────────────────────────────────────────────────────────────────
217217

218-
function loadEnvFile(env: string, baseDir: string): void {
218+
// Returns the files' own values (first file wins), so key resolution can tell
219+
// a key from .env.<org> apart from one that was exported in the shell.
220+
function loadEnvFile(env: string, baseDir: string): Record<string, string> {
221+
const fileVars: Record<string, string> = {};
219222
const envFiles = [
220223
join(baseDir, `.env.${env}`), // e.g. .env.my-org
221224
join(baseDir, `.env.${env}.local`), // e.g. .env.my-org.local (local overrides)
@@ -243,6 +246,7 @@ function loadEnvFile(env: string, baseDir: string): void {
243246
value = value.slice(1, -1);
244247
}
245248

249+
if (fileVars[key] === undefined) fileVars[key] = value;
246250
// Only set if not already defined (env vars take precedence)
247251
if (process.env[key] === undefined) {
248252
process.env[key] = value;
@@ -251,6 +255,7 @@ function loadEnvFile(env: string, baseDir: string): void {
251255
console.log(`📁 Loaded env file: ${basename(envFile)}`);
252256
}
253257
}
258+
return fileVars;
254259
}
255260

256261
// ─────────────────────────────────────────────────────────────────────────────
@@ -273,23 +278,29 @@ export const {
273278
applyFilter: APPLY_FILTER,
274279
} = parseFlags();
275280

276-
// The private API key: VAPI_PRIVATE_API_KEY (canonical) or VAPI_TOKEN (legacy).
277-
// Capture the real environment before .env files are merged in, so an
278-
// exported key of either name still beats a key in the .env file.
279-
const ENV_API_KEY = resolveApiKey(process.env);
281+
// The private API key. Capture the real environment before .env files are
282+
// merged in, so an exported key still beats a key in the .env file:
283+
// VAPI_PRIVATE_API_KEY_<ORG>, then VAPI_PRIVATE_API_KEY / VAPI_TOKEN, then
284+
// .env.<org>. See resolveOrgApiKey.
285+
const SHELL_ENV = { ...process.env };
280286

281-
loadEnvFile(VAPI_ENV, BASE_DIR);
287+
const ENV_FILE_VARS = loadEnvFile(VAPI_ENV, BASE_DIR);
288+
const API_KEY = resolveOrgApiKey(VAPI_ENV, SHELL_ENV, ENV_FILE_VARS);
282289

283290
// API configuration
284-
export const VAPI_TOKEN = ENV_API_KEY ?? resolveApiKey(process.env);
291+
export const VAPI_TOKEN = API_KEY?.token;
285292
export const VAPI_BASE_URL = process.env.VAPI_BASE_URL || "https://api.vapi.ai";
286293

287294
if (!VAPI_TOKEN) {
288295
console.error(`❌ ${missingApiKeyMessage(VAPI_ENV)}`);
289296
process.exit(1);
290297
}
291-
// Some call sites read process.env.VAPI_TOKEN directly; keep them working
292-
// when only VAPI_PRIVATE_API_KEY was provided.
298+
if (API_KEY?.warning) console.warn(`⚠️ ${API_KEY.warning}`);
299+
else if (API_KEY && API_KEY.source !== `.env.${VAPI_ENV}`)
300+
console.log(`🔑 Using the API key from ${API_KEY.source}`);
301+
// Some call sites read the variables directly; keep them on the key chosen
302+
// above, so code reading the generic name can't see another org's key.
303+
process.env.VAPI_PRIVATE_API_KEY = VAPI_TOKEN;
293304
process.env.VAPI_TOKEN = VAPI_TOKEN;
294305

295306
// Paths

‎src/interactive.ts‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { missingApiKeyMessage, resolveApiKey } from "./api-key.ts";
1+
import { missingApiKeyMessage, resolveOrgApiKey } from "./api-key.ts";
22
import { confirm, select } from "@inquirer/prompts";
33
import { execSync } from "child_process";
44
import { existsSync, readdirSync, readFileSync, statSync } from "fs";
@@ -166,7 +166,9 @@ function loadOrgEnv(slug: string): { token: string; baseUrl: string } {
166166
vars[trimmed.slice(0, eq).trim()] = val;
167167
}
168168

169-
const token = resolveApiKey(vars);
169+
const resolved = resolveOrgApiKey(slug, process.env, vars);
170+
if (resolved?.warning) console.warn(`⚠️ ${resolved.warning}`);
171+
const token = resolved?.token;
170172
if (!token) {
171173
throw new Error(missingApiKeyMessage(slug));
172174
}

‎src/org-connection.ts‎

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
import { spawnSync } from "node:child_process";
77
import { existsSync, readFileSync } from "node:fs";
88
import { resolve } from "node:path";
9-
import { resolveApiKey } from "./api-key.ts";
9+
import { orgApiKeyVar, resolveApiKey } from "./api-key.ts";
1010

1111
export interface OrgConnection {
1212
token: string;
@@ -69,10 +69,11 @@ export function connectionLoad(args: ConnectionLoadArgs): OrgConnection {
6969
VAPI_PRIVATE_API_KEY: envValue(envContent, "VAPI_PRIVATE_API_KEY"),
7070
VAPI_TOKEN: envValue(envContent, "VAPI_TOKEN"),
7171
});
72-
const token = tokens.get(org) ?? envToken;
72+
const token =
73+
tokens.get(org) ?? (process.env[orgApiKeyVar(org)]?.trim() || envToken);
7374
if (!token)
7475
throw new Error(
75-
`Missing token for org ${org}; set ${tokensEnvName} or .env.${org}`,
76+
`Missing token for org ${org}; set ${tokensEnvName}, ${orgApiKeyVar(org)} or .env.${org}`,
7677
);
7778
return {
7879
token,
@@ -96,6 +97,8 @@ export function childRun(run: ChildRunArgs): void {
9697
...process.env,
9798
VAPI_PRIVATE_API_KEY: connection.token,
9899
VAPI_TOKEN: connection.token,
100+
// The child resolves the per-org variable first, so pin it too.
101+
[orgApiKeyVar(org)]: connection.token,
99102
};
100103
if (connection.baseUrl) environment.VAPI_BASE_URL = connection.baseUrl;
101104
if (!connection.baseUrl) delete environment.VAPI_BASE_URL;

‎src/rollback-cmd.ts‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88
// Self-contained (does not import config.ts) so it can run in isolation
99
// without triggering the global CLI parser.
1010

11-
import { missingApiKeyMessage, resolveApiKey } from "./api-key.ts";
11+
import { missingApiKeyMessage, resolveOrgApiKey } from "./api-key.ts";
1212
import { existsSync, readFileSync } from "fs";
1313
import { dirname, join } from "path";
1414
import { fileURLToPath } from "url";
@@ -49,7 +49,9 @@ function loadEnvFile(env: string): RollbackEnv {
4949
if (envVars[key] === undefined) envVars[key] = value;
5050
}
5151
}
52-
const token = resolveApiKey(process.env, envVars);
52+
const resolved = resolveOrgApiKey(env, process.env, envVars);
53+
if (resolved?.warning) console.warn(`⚠️ ${resolved.warning}`);
54+
const token = resolved?.token;
5355
const baseUrl =
5456
process.env.VAPI_BASE_URL || envVars.VAPI_BASE_URL || "https://api.vapi.ai";
5557
if (!token) {

0 commit comments

Comments
 (0)