Skip to content

dotenv: Cannot stringify and parse JSON strings or values with quotes and apostrophes or newlines #7055

@Macil

Description

@Macil

Describe the bug

@std/dotenv's stringify and parse functions fail to losslessly encode JS string values if they contain both quotes and apostrophes, or quotes and newlines, or quotes and a backslash followed by "n".

One consequence of this is that stringify and parse cannot handle a JSON string, because the string will contain quotes and become wrapped with apostrophes. I'm programmatically generating an env file that contains some JSONified JWKs, and I did not expect the contents of the string to be able to break things; I expected any string value to be properly escaped during stringification so that it parses to the exact original value.

Steps to Reproduce

Here's an example script that tries various combinations:

import { parse, stringify } from "jsr:@std/dotenv";
import { Combination } from "npm:js-combinatorics";

const testChars = ["'", '"', "\\n", "\n"];
let failed = 0;
for (const combination of new Combination(testChars, 2)) {
  const combined = combination.join("");

  const value = `start_${combined}_end`;
  const env = stringify({ TEST_VAR: value });
  const parsed = parse(env).TEST_VAR;

  if (parsed !== value) {
    console.log(`Mismatch with characters: ${JSON.stringify(combined)}`);

    console.log("original:", JSON.stringify(value));
    console.log("parsed:", JSON.stringify(parsed));
    console.log("env:", env);
    console.log();
    failed++;
  }
}

console.log("Failed cases:", failed);
Mismatch with characters: "'\""
original: "start_'\"_end"
parsed: "start_'\\"
env: TEST_VAR="start_'\"_end"

Mismatch with characters: "'\\n"
original: "start_'\\n_end"
parsed: "start_'\n_end"
env: TEST_VAR="start_'\n_end"

Mismatch with characters: "\"\n"
original: "start_\"\n_end"
parsed: "start_\\"
env: TEST_VAR="start_\"\n_end"

Mismatch with characters: "\\n\n"
original: "start_\\n\n_end"
parsed: "start_\n\n_end"
env: TEST_VAR="start_\n\n_end"

Failed cases: 4

Environment

deno 2.7.4 (stable, release, aarch64-apple-darwin)
jsr:@std/dotenv 0.225.6

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions