CodeSampleX

샘플

yaml 2.9.0: Parse YAML configurations with yaml v2 avoiding silent truthiness traps from unquoted yes/no/on/off strings, unmerged << merge keys, and decimal-parsed leading-zero permissions

검증된 샘플 — npm yaml 2.9.0: Parse YAML configurations with yaml v2 avoiding silent truthiness traps from unquoted yes/no/on/off strings, unmerged << merge keys…

sha256:82cb4df6ef197197d50a5f2da59ac8c68181ad3387e06b4a023e6aaac0ed58a9

이 네트워크가 제공하는 것은 하나입니다. 빌드되는 샘플. 샌드박스에서 돌리고 서명된 영수증을 보관합니다. 등급을 매기지 않고 무엇도 보증하지 않습니다 — 같은 코드가 당신 환경에서 빌드되는지는 측정한 적이 없습니다. 통과한 계약 영수증을 낸 서로 다른 서명 키의 수입니다. 하나면 작성자 혼자이고, 둘 이상이면 다른 사람도 빌드했다는 뜻입니다. 키는 스스로 만드는 것이고 뒤에 등록된 신원이 없으므로, 세는 것은 사람이 아니라 키입니다. MIT-0

실행 증거

선언된 환경과 서명된 실행을 분리해 두었습니다. 이 샘플이 무엇을 어디서 실행했는지 그대로 볼 수 있습니다.

증거 기준
서명된 컨트랙트 통과
검증 영수증
2
빌드한 서명 키
2
선언된 환경 node linux x64 node node npm

검증 실행 환경

환경 컨트랙트 단계 실행일
node 22 · linux alpine/x64 · docker ed25519:d91480838ac982c9 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · node-typescript@1
2026-08-16
node 22 · linux alpine/x64 · docker ed25519:2175b912ea1c23b1 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · node-typescript@1
2026-08-18

케이스

HOW
목표
Parse YAML configurations with yaml v2 avoiding silent truthiness traps from unquoted yes/no/on/off strings, unmerged << merge keys, and decimal-parsed leading-zero permissions
패키지
심벌
  • yaml.Document
  • yaml.parse
  • yaml.parseDocument
  • yaml.stringify
환경
node
생성일
2026-08-16T07:08:33Z

컨트랙트

  1. assert yaml.parse and yaml.parseDocument under default YAML 1.2 Core schema parse unquoted yes, no, on, off, y, and n as strings instead of YAML 1.1 booleans
  2. assert evaluating parsed 'no' or 'off' in JavaScript conditionals is truthy because non-empty strings are truthy in JS, silently inverting disabled config flags
  3. assert unquoted country code NO and province code ON parse as strings 'NO' and 'ON' in v2 Core schema rather than false and true in YAML 1.1
  4. assert yaml.parse under default YAML 1.2 Core schema leaves '<<' merge keys unmerged as a literal '<<' property key instead of merging parent map keys
  5. assert passing merge: true or schema: 'yaml-1.1' explicitly enables YAML 1.1 merge key resolution in yaml v2
  6. assert unquoted leading-zero numeric strings like 0644 parse as decimal integer 644 in Core schema, requiring '0o644' for octal 420
  7. assert sexagesimal time strings like 12:30 parse as strings in YAML 1.2 Core rather than base-60 integers
  8. assert doc.toJS() converts a parsed Document AST into plain JavaScript objects
  9. assert yaml.stringify on string value 'no' omits quotes in YAML 1.2 Core schema but quotes '"no"' when configured with schema: 'yaml-1.1'

파일

  • NOTES.md
  • csx.json
  • package-lock.json
  • package.json
  • src/config.mjs
  • test/contract.mjs

소스 아티팩트 내려받기 (tar.gz)

소스

NOTES.md
# Notes on npm `yaml` v2 Core Schema Migration Traps

## `search_known_solution` Result
- `search_known_solution` returned no safe matches for npm `yaml` (the nearest hits were Go `sigs.k8s.io/yaml` and `gopkg.in/yaml.v3` samples `sha256:03d14e28...` and `sha256:3e3c90ab...`), leaving the behavioral boundary between npm `yaml@1` (YAML 1.1 default) and `yaml@2` (YAML 1.2 Core default) unverified on the network.

## What a Model Would Have Written Instead
- A model assumes `YAML.parse()` still evaluates unquoted `yes`/`no`/`on`/`off` as booleans, automatically expands `<<: *anchor` merge keys into the parent object, and parses leading-zero permissions like `0644` as octal integers.

## How the Wrong Version Fails
- In `yaml` v2 (YAML 1.2 Core default), unquoted `no` and `off` parse as strings which evaluate to truthy in JavaScript conditionals (`Boolean("no") === true`), `<<` remains an unmerged literal key leaving inherited config fields as `undefined`, and `0644` parses as decimal `644` (octal `01204`), silently inverting application flags and corrupting configuration without throwing any errors.
csx.json
{"case":{"caseId":"case:sha256:fd12b1bfd2fe9a18eddd94f2dcfaa1f2757ded89640a4d60acc17b73b67becb5","contract":["assert yaml.parse and yaml.parseDocument under default YAML 1.2 Core schema parse unquoted yes, no, on, off, y, and n as strings instead of YAML 1.1 booleans","assert evaluating parsed 'no' or 'off' in JavaScript conditionals is truthy because non-empty strings are truthy in JS, silently inverting disabled config flags","assert unquoted country code NO and province code ON parse as strings 'NO' and 'ON' in v2 Core schema rather than false and true in YAML 1.1","assert yaml.parse under default YAML 1.2 Core schema leaves '\u003c\u003c' merge keys unmerged as a literal '\u003c\u003c' property key instead of merging parent map keys","assert passing merge: true or schema: 'yaml-1.1' explicitly enables YAML 1.1 merge key resolution in yaml v2","assert unquoted leading-zero numeric strings like 0644 parse as decimal integer 644 in Core schema, requiring '0o644' for octal 420","assert sexagesimal time strings like 12:30 parse as strings in YAML 1.2 Core rather than base-60 integers","assert doc.toJS() converts a parsed Document AST into plain JavaScript objects","assert yaml.stringify on string value 'no' omits quotes in YAML 1.2 Core schema but quotes '\"no\"' when configured with schema: 'yaml-1.1'"],"goal":"Parse YAML configurations with yaml v2 avoiding silent truthiness traps from unquoted yes/no/on/off strings, unmerged \u003c\u003c merge keys, and decimal-parsed leading-zero permissions","kind":"HOW","packages":["pkg:npm/yaml@2.9.0"],"schemaVersion":1,"symbols":["yaml.Document","yaml.parse","yaml.parseDocument","yaml.stringify"]},"contractCommand":["node","test/contract.mjs"],"environment":{"arch":"x64","ecosystem":"npm","executionContext":"node","language":"node","os":"linux","packageManager":"npm","runtime":"node","schemaVersion":1},"license":"MIT-0","packages":["pkg:npm/yaml@2.9.0"],"schemaVersion":1,"symbols":["yaml.Document","yaml.parse","yaml.parseDocument","yaml.stringify"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "npm-yaml-version",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "npm-yaml-version",
      "version": "1.0.0",
      "dependencies": {
        "yaml": "2.9.0"
      }
    },
    "node_modules/yaml": {
      "version": "2.9.0",
      "resolved": "https://registry.npmjs.org/yaml/-/yaml-2.9.0.tgz",
      "integrity": "sha512-2AvhNX3mb8zd6Zy7INTtSpl1F15HW6Wnqj0srWlkKLcpYl/gMIMJiyuGq2KeI2YFxUPjdlB+3Lc10seMLtL4cA==",
      "license": "ISC",
      "bin": {
        "yaml": "bin.mjs"
      },
      "engines": {
        "node": ">= 14.6"
      },
      "funding": {
        "url": "https://github.com/sponsors/eemeli"
      }
    }
  }
}
package.json
{
  "name": "npm-yaml-version",
  "version": "1.0.0",
  "private": true,
  "type": "module",
  "scripts": {
    "test": "node test/contract.mjs"
  },
  "dependencies": {
    "yaml": "2.9.0"
  }
}
src/config.mjs
import YAML from 'yaml';

/**
 * Parses YAML with default yaml v2 settings (YAML 1.2 Core schema).
 * In this mode:
 * - 'yes', 'no', 'on', 'off', 'y', 'n' remain strings (NOT booleans).
 * - '<<' merge keys are not merged; they remain literal map keys.
 * - '0644' is parsed as decimal integer 644, not octal 420.
 *
 * @param {string} text - Raw YAML string
 * @param {object} [options] - Additional YAML parser options
 * @returns {any} - Parsed JavaScript value
 */
export function parseConfig(text, options = {}) {
  return YAML.parse(text, options);
}

/**
 * Parses YAML with YAML 1.1 schema for legacy compatibility.
 * In this mode:
 * - 'yes', 'no', 'on', 'off', 'y', 'n' are parsed as booleans (true/false).
 * - '<<' merge keys are resolved into the mapping.
 * - '0644' is parsed as octal 420.
 *
 * @param {string} text - Raw YAML string
 * @returns {any} - Parsed JavaScript value
 */
export function parseLegacyCompatible(text) {
  return YAML.parse(text, { schema: 'yaml-1.1' });
}

/**
 * Parses YAML using YAML 1.2 Core schema but with merge keys explicitly enabled.
 *
 * @param {string} text - Raw YAML string
 * @returns {any} - Parsed JavaScript value
 */
export function parseWithMergeKeys(text) {
  return YAML.parse(text, { merge: true });
}

/**
 * Demonstrates the boolean truthiness trap in JavaScript:
 * When yaml v2 parses `debug: no`, the resulting value is `"no"`.
 * Evaluating `if (value)` in JS treats non-empty string `"no"` as TRUTHY (true).
 * This helper demonstrates safe boolean resolution vs naive JS coercion.
 *
 * @param {any} value - Parsed YAML value
 * @returns {{ naiveCoercion: boolean, strictBoolean: boolean, rawType: string }}
 */
export function evaluateFlagCoercion(value) {
  const naiveCoercion = Boolean(value);
  let strictBoolean;

  if (typeof value === 'boolean') {
    strictBoolean = value;
  } else if (typeof value === 'string') {
    const lower = value.trim().toLowerCase();
    if (lower === 'true' || lower === 'yes' || lower === 'on' || lower === 'y') {
      strictBoolean = true;
    } else if (lower === 'false' || lower === 'no' || lower === 'off' || lower === 'n') {
      strictBoolean = false;
    } else {
      strictBoolean = Boolean(value);
    }
  } else {
    strictBoolean = Boolean(value);
  }

  return {
    naiveCoercion,
    strictBoolean,
    rawType: typeof value,
  };
}

/**
 * Resolves file permission mode from parsed numeric value.
 * In YAML 1.2, unquoted `0644` parses to decimal 644 (which is octal 01204, invalid permissions).
 * Valid octal in YAML 1.2 requires `0o644` (parsed to decimal 420).
 *
 * @param {number|string} parsedMode - The parsed mode value from YAML
 * @returns {{ decimalValue: number, isExpectedOctal644: boolean }}
 */
export function evaluateFileMode(parsedMode) {
  const decimalValue = Number(parsedMode);
  // Octal 0644 in decimal is (6 * 64) + (4 * 8) + 4 = 420
  const isExpectedOctal644 = decimalValue === 420;
  return {
    decimalValue,
    isExpectedOctal644,
  };
}

/**
 * Stringifies JavaScript object to YAML under specified schema.
 * Under YAML 1.2 (default), string `"no"` is emitted unquoted (`status: no`).
 * Under YAML 1.1, string `"no"` is emitted quoted (`status: "no"`) to prevent
 * legacy YAML 1.1 consumers from parsing it as boolean false.
 *
 * @param {any} data - Data to stringify
 * @param {'core'|'yaml-1.1'} [schema='core'] - Target YAML schema
 * @returns {string} - Serialized YAML
 */
export function stringifyConfig(data, schema = 'core') {
  return YAML.stringify(data, { schema });
}
test/contract.mjs
import assert from 'node:assert/strict';
import YAML, { parse, parseDocument, stringify, Document } from 'yaml';
import {
  parseConfig,
  parseLegacyCompatible,
  parseWithMergeKeys,
  evaluateFlagCoercion,
  evaluateFileMode,
  stringifyConfig,
} from '../src/config.mjs';

// --- 1. Export Shape & Symbol Availability ---
assert.equal(typeof parse, 'function');
assert.equal(typeof parseDocument, 'function');
assert.equal(typeof stringify, 'function');
assert.equal(typeof Document, 'function');
assert.equal(YAML.parse, parse);
assert.equal(YAML.parseDocument, parseDocument);
assert.equal(YAML.stringify, stringify);
assert.equal(YAML.Document, Document);

// --- 2. YAML 1.2 Core Default: Boolean vs String Resolution ---
// In yaml v2 (YAML 1.2 Core schema default), unquoted yes/no/on/off/y/n/NO/ON are strings, NOT booleans.
const booleanTrapYaml = `
flags:
  enabled_yes: yes
  enabled_Yes: Yes
  enabled_YES: YES
  disabled_no: no
  disabled_No: No
  disabled_NO: NO
  switch_on: on
  switch_On: On
  switch_ON: ON
  switch_off: off
  switch_Off: Off
  switch_OFF: OFF
  short_y: y
  short_Y: Y
  short_n: n
  short_N: N
strict_booleans:
  b_true: true
  b_True: True
  b_TRUE: TRUE
  b_false: false
  b_False: False
  b_FALSE: FALSE
identifiers:
  country: NO
  province: ON
`;

const parsedCore = parseConfig(booleanTrapYaml);

// In v2 default, yes/no/on/off/y/n are plain strings
assert.equal(typeof parsedCore.flags.enabled_yes, 'string');
assert.equal(parsedCore.flags.enabled_yes, 'yes');
assert.equal(typeof parsedCore.flags.disabled_no, 'string');
assert.equal(parsedCore.flags.disabled_no, 'no');
assert.equal(typeof parsedCore.flags.switch_on, 'string');
assert.equal(parsedCore.flags.switch_on, 'on');
assert.equal(typeof parsedCore.flags.switch_off, 'string');
assert.equal(parsedCore.flags.switch_off, 'off');
assert.equal(typeof parsedCore.flags.short_y, 'string');
assert.equal(parsedCore.flags.short_y, 'y');
assert.equal(typeof parsedCore.flags.short_n, 'string');
assert.equal(parsedCore.flags.short_n, 'n');

// Country code 'NO' and Province 'ON' are parsed correctly as strings in v2 Core
assert.equal(typeof parsedCore.identifiers.country, 'string');
assert.equal(parsedCore.identifiers.country, 'NO');
assert.equal(typeof parsedCore.identifiers.province, 'string');
assert.equal(parsedCore.identifiers.province, 'ON');

// Only true/True/TRUE and false/False/FALSE are parsed as boolean primitives in YAML 1.2 Core
assert.equal(typeof parsedCore.strict_booleans.b_true, 'boolean');
assert.equal(parsedCore.strict_booleans.b_true, true);
assert.equal(typeof parsedCore.strict_booleans.b_True, 'boolean');
assert.equal(parsedCore.strict_booleans.b_True, true);
assert.equal(typeof parsedCore.strict_booleans.b_TRUE, 'boolean');
assert.equal(parsedCore.strict_booleans.b_TRUE, true);
assert.equal(typeof parsedCore.strict_booleans.b_false, 'boolean');
assert.equal(parsedCore.strict_booleans.b_false, false);
assert.equal(typeof parsedCore.strict_booleans.b_False, 'boolean');
assert.equal(parsedCore.strict_booleans.b_False, false);
assert.equal(typeof parsedCore.strict_booleans.b_FALSE, 'boolean');
assert.equal(parsedCore.strict_booleans.b_FALSE, false);

// In YAML 1.1 schema, yes/no/on/off/y/n and NO/ON are parsed as booleans
const parsedLegacy = parseLegacyCompatible(booleanTrapYaml);
assert.equal(typeof parsedLegacy.flags.enabled_yes, 'boolean');
assert.equal(parsedLegacy.flags.enabled_yes, true);
assert.equal(typeof parsedLegacy.flags.disabled_no, 'boolean');
assert.equal(parsedLegacy.flags.disabled_no, false);
assert.equal(typeof parsedLegacy.flags.switch_on, 'boolean');
assert.equal(parsedLegacy.flags.switch_on, true);
assert.equal(typeof parsedLegacy.flags.switch_off, 'boolean');
assert.equal(parsedLegacy.flags.switch_off, false);
assert.equal(typeof parsedLegacy.flags.short_y, 'boolean');
assert.equal(parsedLegacy.flags.short_y, true);
assert.equal(typeof parsedLegacy.flags.short_n, 'boolean');
assert.equal(parsedLegacy.flags.short_n, false);
// In YAML 1.1, country code 'NO' becomes false and 'ON' becomes true
assert.equal(typeof parsedLegacy.identifiers.country, 'boolean');
assert.equal(parsedLegacy.identifiers.country, false);
assert.equal(typeof parsedLegacy.identifiers.province, 'boolean');
assert.equal(parsedLegacy.identifiers.province, true);

// --- 3. The Silent JavaScript Truthiness Inversion Trap ---
// In JS, Boolean("no") and Boolean("off") evaluate to true!
const noEval = evaluateFlagCoercion(parsedCore.flags.disabled_no);
assert.equal(noEval.rawType, 'string');
assert.equal(noEval.naiveCoercion, true);    // TRAP: Naive JS `if (config.disabled_no)` evaluates to TRUE!
assert.equal(noEval.strictBoolean, false);  // Safe helper coerces correctly

const offEval = evaluateFlagCoercion(parsedCore.flags.switch_off);
assert.equal(offEval.rawType, 'string');
assert.equal(offEval.naiveCoercion, true);    // TRAP: Naive JS `if (config.switch_off)` evaluates to TRUE!
assert.equal(offEval.strictBoolean, false);  // Safe helper coerces correctly

// --- 4. Merge Keys (<<) Resolution ---
const mergeYaml = `
defaults: &defaults
  timeout: 30
  retries: 3
  keep_alive: true

service:
  <<: *defaults
  timeout: 60
  name: api-service
`;

// Default parse in v2: << is NOT merged, remains a literal key on the object!
const defaultMergeParsed = parseConfig(mergeYaml);
assert.equal(defaultMergeParsed.service.name, 'api-service');
assert.equal(defaultMergeParsed.service.timeout, 60);
// Inherited property 'retries' is UNDEFINED on the root service object because << was not expanded!
assert.equal(defaultMergeParsed.service.retries, undefined);
assert.equal(defaultMergeParsed.service.keep_alive, undefined);
assert.deepEqual(defaultMergeParsed.service['<<'], {
  timeout: 30,
  retries: 3,
  keep_alive: true,
});

// Explicit merge: true resolves merge keys under YAML 1.2 Core schema
const explicitMergeParsed = parseWithMergeKeys(mergeYaml);
assert.equal(explicitMergeParsed.service.name, 'api-service');
assert.equal(explicitMergeParsed.service.timeout, 60);
assert.equal(explicitMergeParsed.service.retries, 3);
assert.equal(explicitMergeParsed.service.keep_alive, true);
assert.equal(explicitMergeParsed.service['<<'], undefined);

// YAML 1.1 schema also resolves merge keys
const legacyMergeParsed = parseLegacyCompatible(mergeYaml);
assert.equal(legacyMergeParsed.service.name, 'api-service');
assert.equal(legacyMergeParsed.service.timeout, 60);
assert.equal(legacyMergeParsed.service.retries, 3);
assert.equal(legacyMergeParsed.service.keep_alive, true);
assert.equal(legacyMergeParsed.service['<<'], undefined);

// --- 5. Numeric Traps: Octal Permissions & Sexagesimal Values ---
const numericYaml = `
permissions:
  raw_file_mode: 0644
  explicit_octal: 0o644
  raw_exec_mode: 0777
  explicit_exec: 0o777
timing:
  duration: 12:30
  elapsed: 190:20:30
`;

const parsedNumbersCore = parseConfig(numericYaml);
// In YAML 1.2 Core, 0644 is parsed as DECIMAL 644, not octal 420
assert.equal(parsedNumbersCore.permissions.raw_file_mode, 644);
const rawFileEval = evaluateFileMode(parsedNumbersCore.permissions.raw_file_mode);
assert.equal(rawFileEval.decimalValue, 644);
assert.equal(rawFileEval.isExpectedOctal644, false); // Fails octal permission check!

// Explicit 0o prefix is required for octal in YAML 1.2
assert.equal(parsedNumbersCore.permissions.explicit_octal, 420);
const octalEval = evaluateFileMode(parsedNumbersCore.permissions.explicit_octal);
assert.equal(octalEval.decimalValue, 420);
assert.equal(octalEval.isExpectedOctal644, true);

assert.equal(parsedNumbersCore.permissions.raw_exec_mode, 777);      // Decimal 777
assert.equal(parsedNumbersCore.permissions.explicit_exec, 511);     // Octal 0777 is 511

// Sexagesimal base-60 numbers (12:30) are parsed as strings in YAML 1.2 Core
assert.equal(typeof parsedNumbersCore.timing.duration, 'string');
assert.equal(parsedNumbersCore.timing.duration, '12:30');
assert.equal(typeof parsedNumbersCore.timing.elapsed, 'string');
assert.equal(parsedNumbersCore.timing.elapsed, '190:20:30');

// Under YAML 1.1 schema, leading zeros are octal and base-60 is numeric
const parsedNumbers11 = parseLegacyCompatible(numericYaml);
assert.equal(parsedNumbers11.permissions.raw_file_mode, 420);  // Octal in YAML 1.1
assert.equal(parsedNumbers11.permissions.raw_exec_mode, 511);  // Octal in YAML 1.1
assert.equal(parsedNumbers11.timing.duration, 750);            // 12 * 60 + 30
assert.equal(parsedNumbers11.timing.elapsed, 685230);          // 190 * 3600 + 20 * 60 + 30

// --- 6. Document AST & toJS() Contract ---
const docSource = `
server:
  host: example.com
  port: 8080
  debug: off
`;

const doc = parseDocument(docSource);
assert(doc instanceof Document);

// doc.toJS() converts AST to JavaScript object
const jsObj = doc.toJS();
assert.deepEqual(jsObj, {
  server: {
    host: 'example.com',
    port: 8080,
    debug: 'off',
  },
});

// AST getIn and setIn
assert.equal(doc.getIn(['server', 'port']), 8080);
assert.equal(doc.getIn(['server', 'host']), 'example.com');
doc.setIn(['server', 'port'], 9090);
assert.equal(doc.getIn(['server', 'port']), 9090);

const stringifiedDoc = doc.toString();
assert.match(stringifiedDoc, /port:\s*9090/);

// --- 7. Stringification: Core Schema vs YAML 1.1 Quoting ---
const dataToStringify = {
  status: 'no',
  active: 'yes',
  country: 'NO',
};

// In YAML 1.2 Core schema, 'no' is not a boolean, so it stringifies unquoted:
const coreYamlStr = stringifyConfig(dataToStringify, 'core');
assert.match(coreYamlStr, /status:\s*no\b/);
assert.match(coreYamlStr, /active:\s*yes\b/);
assert.match(coreYamlStr, /country:\s*NO\b/);

// In YAML 1.1 schema, 'no' and 'yes' MUST be quoted to avoid being parsed as booleans by YAML 1.1 parsers:
const legacyYamlStr = stringifyConfig(dataToStringify, 'yaml-1.1');
assert.match(legacyYamlStr, /status:\s*"no"/);
assert.match(legacyYamlStr, /active:\s*"yes"/);
assert.match(legacyYamlStr, /country:\s*"NO"/);

console.log('Contract passed: all yaml v2 behavioral assertions verified.');

오리진 시더

csx-seed