{"record":{"id":"9bd44de6a12c1493","repo":"mastra-ai/mastra","slug":"invalid-env-key-key","errorCode":null,"errorMessage":"Invalid ENV key: ${key}","messagePattern":"Invalid ENV key: (.+?)","errorType":"validation","errorClass":"Error","httpStatus":null,"severity":"error","filePath":"packages/cli/src/services/service.env.ts","lineNumber":19,"sourceCode":"import * as fs from 'node:fs/promises';\n\nexport abstract class EnvService {\n  abstract getEnvValue(key: string): Promise<string | null>;\n  abstract setEnvValue(key: string, value: string): Promise<void>;\n}\n\nfunction escapeRegExp(value: string): string {\n  return value.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n}\n\nexport class FileEnvService extends EnvService {\n  private static readonly ENV_KEY_REGEX = /^[A-Za-z_][A-Za-z0-9_]*$/;\n\n  private readonly filePath: string;\n\n  private validateEnvEntry(key: string, value: string): void {\n    if (!FileEnvService.ENV_KEY_REGEX.test(key)) {\n      throw new Error(`Invalid ENV key: ${key}`);\n    }\n    if (/[\\r\\n]/.test(value)) {\n      throw new Error(`Invalid ENV value for ${key}: multiline values are not supported.`);\n    }\n  }\n\n  constructor(filePath: string) {\n    super();\n    this.filePath = filePath;\n  }\n\n  private envLineRegex(key: string, captureValue = false): RegExp {\n    const pattern = captureValue ? `^${escapeRegExp(key)}=(.*)$` : `^${escapeRegExp(key)}=.*$`;\n    return new RegExp(pattern, 'm');\n  }\n\n  private async updateEnvData({\n    key,","sourceCodeStart":1,"sourceCodeEnd":37,"githubUrl":"https://github.com/mastra-ai/mastra/blob/75dd419e613fe9c39f846ffc500716141b74fda6/packages/cli/src/services/service.env.ts#L1-L37","documentation":"FileEnvService.validateEnvEntry throws this when an environment variable key being written to a .env file does not match ^[A-Za-z_][A-Za-z0-9_]*$. Keys must start with a letter or underscore and contain only letters, digits, and underscores, since .env files are simple KEY=VALUE text parsed by shell-compatible tooling. This guard prevents writing an unparseable or dangerous entry into the env file.","triggerScenarios":"Calling updateEnvData (which delegates to validateEnvEntry) with a key containing hyphens, dots, spaces, leading digits, an '=' sign, or an empty string — e.g. programmatic writes like envService.updateEnvData({ 'my-key': 'v' }) or keys derived from untrusted input.","commonSituations":"Migrating config that used hyphenated names (my-key) instead of env-style names (MY_KEY); injecting user-supplied keys without sanitizing; accidentally passing a whole 'KEY=value' string as the key; empty key from a bad split.","solutions":["Rename the key to uppercase snake_case, e.g. my-key -> MY_KEY","Strip invalid characters and sanitize before writing: key.replace(/[^A-Za-z0-9_]/g, '_').replace(/^[0-9]+/, '')","Ensure the key is non-empty and does not embed '=' or whitespace","Validate keys with the same regex in your own code before calling updateEnvData"],"exampleFix":"// before\nawait service.updateEnvData({ 'my-key': 'value' });\n// after\nawait service.updateEnvData({ MY_KEY: 'value' });","handlingStrategy":"validation","validationCode":"const ENV_KEY_REGEX = /^[A-Za-z_][A-Za-z0-9_]*$/;\nfunction assertValidEnvKey(key: string) {\n  if (!ENV_KEY_REGEX.test(key)) throw new Error(`Invalid ENV key: ${key}`);\n}","typeGuard":"const isValidEnvKey = (key: string): boolean => /^[A-Za-z_][A-Za-z0-9_]*$/.test(key);","tryCatchPattern":"try {\n  await service.updateEnvData(entries);\n} catch (e) {\n  if (e instanceof Error && e.message.startsWith('Invalid ENV key')) {\n    console.error(`Fix key format (must match ^[A-Za-z_][A-Za-z0-9_]*$): ${e.message}`);\n  } else throw e;\n}","preventionTips":["Always sanitize/normalize keys to UPPER_SNAKE_CASE before writing env entries","Never pass raw 'KEY=value' strings as keys","Validate user- or external-supplied keys with the same regex before persisting","Add a unit test covering hyphens, dots, leading digits, and empty keys"],"tags":["env","validation","cli-services"],"backgroundTag":"invalid-env-key","analyzedSha":"75dd419e613fe9c39f846ffc500716141b74fda6","analyzedAt":"2026-08-30T00:15:31.844Z","schemaVersion":2},"datasetVersion":"2026-08-30T03:17:51.788Z"}