CodeSampleX

Пример

asn1js 3.0.10: Boolean

Проверенный пример — npm asn1js 3.0.10: Boolean. Контракт выполнен на node 22 · linux debian/x64 · docker и пройден: asn1js.Boolean constructs boolean ASN.1…

sha256:c3ab9b52782b58d723f9ff17dffb49fbe433a6c00d71f36d2dd5b6f360e9432e

Эта сеть предлагает одно: образец, который собирается. Она запустила его в песочнице и сохранила подписанную квитанцию. Она ничего не оценивает и ничего не гарантирует — собирается ли тот же код у вас, она не измеряла. Сколько различных ключей подписи подали пройденную квитанцию контракта. Один — только автор; больше одного — значит, кто-то ещё тоже собрал. Ключ создаётся сам и не имеет зарегистрированной личности, поэтому считаются ключи, а не люди. MIT-0

Свидетельства выполнения

Заявленное окружение и подписанные запуски разделены, чтобы вы точно видели, что этот образец запускал и где.

Основа свидетельства
Подписанный контракт пройден
Квитанции проверки
1
Ключи подписи, собравшие его
1
Заявленная среда linux 24 · ubuntu · glibc 2.39 x64 npm

Среды запусков проверки

Окружение Контракт Этапы Запуск
node 22 · linux debian/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · node-typescript@1node:22@sha256:8a34c4ab3ea2…
2026-09-04

Кейс

HOW
Цель
verify asn1js.Boolean in pkg:npm/asn1js@3.0.10
Пакеты
Символы
  • asn1js.Boolean
Создан
2026-09-04T08:02:43Z

Контракт

  1. asn1js.Boolean constructs boolean ASN.1 elements and provides getValue and setValue accessors
  2. asn1js.Boolean toBER encodes true as 0x0101ff and false as 0x010100 in BER/DER format
  3. asn1js.fromBER decodes BER boolean buffers into asn1js.Boolean instances preserving boolean truth values
  4. asn1js.verifySchema validates BER boolean elements against asn1js.Boolean schemas and rejects mismatched types

Файлы

  • .npmrc
  • PROMPT.md
  • csx.json
  • package-lock.json
  • package.json
  • spec.json
  • src/index.js
  • test/contract.js

Скачать артефакт с исходным кодом (tar.gz)

Исходный код

.npmrc
update-notifier=false
audit=false
fund=false
PROMPT.md
Clean-room public code sample — generation instructions

Write a brand-new, minimal, self-contained code sample in this clean-room directory.
Do not copy, paraphrase, or reference any existing project source. Work only from this spec.

A csx.json manifest scaffold already exists. Do not recreate it from memory. Preserve its case.goal, packages and symbols; fill its empty case.contract with exact assertions and correct its environment, commands and verifierAdapter for the files you generate.

Goal: verify asn1js.Boolean in pkg:npm/asn1js@3.0.10
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/asn1js@3.0.10
Demonstrate these symbols/APIs:
  - asn1js.Boolean

Rules:
  - One focused purpose; the smallest project that proves the goal.
  - Include a contract test (test/contract.*) that runs OFFLINE and exits 0 exactly when the goal behavior works.
  - Pin every dependency with a lockfile so resolution is reproducible.
  - No secrets, credentials, or tokens. No real URLs (only example.com or localhost). No absolute paths.
  - No personal names, emails, company names, or project identifiers of any kind.
  - No binaries and no generated output (node_modules, dist, target, venv, .git, .env).
  - Keep it under 200 files and 256KB packed.
csx.json
{"case":{"caseId":"case:sha256:ddff303703b7d8bccd07ae3953d3ad593bbffc6824fa07121ad0872b632c9754","contract":["asn1js.Boolean constructs boolean ASN.1 elements and provides getValue and setValue accessors","asn1js.Boolean toBER encodes true as 0x0101ff and false as 0x010100 in BER/DER format","asn1js.fromBER decodes BER boolean buffers into asn1js.Boolean instances preserving boolean truth values","asn1js.verifySchema validates BER boolean elements against asn1js.Boolean schemas and rejects mismatched types"],"goal":"verify asn1js.Boolean in pkg:npm/asn1js@3.0.10","kind":"HOW","packages":["pkg:npm/asn1js@3.0.10"],"schemaVersion":1,"symbols":["asn1js.Boolean"]},"contractCommand":["node","test/contract.js"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"npm","libc":"glibc","libcVersion":"2.39","os":"linux","osVersionBucket":"24","packageManager":"npm","schemaVersion":1},"license":"MIT-0","packages":["pkg:npm/asn1js@3.0.10"],"schemaVersion":1,"subject":"pkg:npm/asn1js@3.0.10","symbols":["asn1js.Boolean"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "sample-asn1js-boolean",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-asn1js-boolean",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "asn1js": "3.0.10"
      }
    },
    "node_modules/asn1js": {
      "version": "3.0.10",
      "resolved": "https://registry.npmjs.org/asn1js/-/asn1js-3.0.10.tgz",
      "integrity": "sha512-S2s3aOytiKdFRdulw2qPE51MzjzVOisppcVv7jVFR+Kw0kxwvFrDcYA0h7Ndqbmj0HkMIXYWaoj7fli8kgx1eg==",
      "license": "BSD-3-Clause",
      "dependencies": {
        "pvtsutils": "^1.3.6",
        "pvutils": "^1.1.5",
        "tslib": "^2.8.1"
      },
      "engines": {
        "node": ">=12.0.0"
      }
    },
    "node_modules/pvtsutils": {
      "version": "1.3.6",
      "resolved": "https://registry.npmjs.org/pvtsutils/-/pvtsutils-1.3.6.tgz",
      "integrity": "sha512-PLgQXQ6H2FWCaeRak8vvk1GW462lMxB5s3Jm673N82zI4vqtVUPuZdffdZbPDFRoU8kAhItWFtPCWiPpp4/EDg==",
      "license": "MIT",
      "dependencies": {
        "tslib": "^2.8.1"
      }
    },
    "node_modules/pvutils": {
      "version": "1.2.0",
      "resolved": "https://registry.npmjs.org/pvutils/-/pvutils-1.2.0.tgz",
      "integrity": "sha512-BbubeCEyTuQjVMakvJQ/Sxbc93F2pwmbsxONT/ZRrwU7Ua38d8unYTwXpTVLAKJ4BDuH9IGztCjQcd/N/39Dvg==",
      "license": "MIT",
      "engines": {
        "node": ">=16.0.0"
      }
    },
    "node_modules/tslib": {
      "version": "2.8.1",
      "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz",
      "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==",
      "license": "0BSD"
    }
  }
}
package.json
{
  "name": "sample-asn1js-boolean",
  "version": "1.0.0",
  "private": true,
  "description": "Clean-room verification sample for asn1js.Boolean",
  "main": "src/index.js",
  "scripts": {
    "test": "node test/contract.js"
  },
  "dependencies": {
    "asn1js": "3.0.10"
  },
  "license": "MIT-0"
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify asn1js.Boolean in pkg:npm/asn1js@3.0.10",
  "kind": "HOW",
  "packages": [
    "pkg:npm/asn1js@3.0.10"
  ],
  "symbols": [
    "asn1js.Boolean"
  ]
}
src/index.js
'use strict';

const asn1js = require('asn1js');

/**
 * Creates an ASN.1 Boolean instance.
 * @param {boolean} value
 * @returns {asn1js.Boolean}
 */
function createBoolean(value) {
  return new asn1js.Boolean({ value });
}

/**
 * Encodes a boolean value into a BER ArrayBuffer.
 * @param {boolean} value
 * @returns {ArrayBuffer}
 */
function encodeBoolean(value) {
  const boolBlock = new asn1js.Boolean({ value });
  return boolBlock.toBER();
}

/**
 * Decodes a BER buffer into a boolean value.
 * @param {ArrayBuffer|Uint8Array} inputBuffer
 * @returns {boolean}
 */
function decodeBoolean(inputBuffer) {
  const decoded = asn1js.fromBER(inputBuffer);
  if (decoded.offset === -1) {
    throw new Error('Failed to decode BER buffer');
  }
  if (!(decoded.result instanceof asn1js.Boolean)) {
    throw new TypeError('Decoded block is not an ASN.1 Boolean');
  }
  return decoded.result.getValue();
}

/**
 * Creates a Boolean schema element for structure validation.
 * @param {string} name
 * @returns {asn1js.Boolean}
 */
function createBooleanSchema(name) {
  return new asn1js.Boolean({ name });
}

/**
 * Verifies a BER buffer against a schema.
 * @param {ArrayBuffer|Uint8Array} inputBuffer
 * @param {asn1js.BaseBlock} schema
 * @returns {{ verified: boolean, result: any }}
 */
function verifyBooleanSchema(inputBuffer, schema) {
  return asn1js.verifySchema(inputBuffer, schema);
}

module.exports = {
  createBoolean,
  encodeBoolean,
  decodeBoolean,
  createBooleanSchema,
  verifyBooleanSchema,
  asn1js
};
test/contract.js
'use strict';

const assert = require('node:assert');
const asn1js = require('asn1js');
const {
  createBoolean,
  encodeBoolean,
  decodeBoolean,
  createBooleanSchema,
  verifyBooleanSchema
} = require('../src/index.js');

// 1. Boolean element construction, getValue, and setValue accessors
const bTrue = new asn1js.Boolean({ value: true });
assert.strictEqual(bTrue.getValue(), true, 'bTrue.getValue() must return true');
assert.strictEqual(bTrue.valueBlock.value, true, 'bTrue.valueBlock.value must be true');

const bFalse = new asn1js.Boolean({ value: false });
assert.strictEqual(bFalse.getValue(), false, 'bFalse.getValue() must return false');
assert.strictEqual(bFalse.valueBlock.value, false, 'bFalse.valueBlock.value must be false');

bFalse.setValue(true);
assert.strictEqual(bFalse.getValue(), true, 'setValue(true) must update value');
assert.strictEqual(bFalse.valueBlock.value, true, 'valueBlock.value must update after setValue(true)');

bFalse.setValue(false);
assert.strictEqual(bFalse.getValue(), false, 'setValue(false) must update value');
assert.strictEqual(bFalse.valueBlock.value, false, 'valueBlock.value must update after setValue(false)');

// 2. toBER encoding into standard BER/DER bytes
const berTrue = new asn1js.Boolean({ value: true }).toBER();
assert(berTrue instanceof ArrayBuffer, 'toBER must return ArrayBuffer');
assert.deepStrictEqual(
  Array.from(new Uint8Array(berTrue)),
  [0x01, 0x01, 0xff],
  'BER encoding of true must be [0x01, 0x01, 0xff]'
);

const berFalse = new asn1js.Boolean({ value: false }).toBER();
assert(berFalse instanceof ArrayBuffer, 'toBER must return ArrayBuffer');
assert.deepStrictEqual(
  Array.from(new Uint8Array(berFalse)),
  [0x01, 0x01, 0x00],
  'BER encoding of false must be [0x01, 0x01, 0x00]'
);

// 3. fromBER decoding into asn1js.Boolean instances
const decTrue = asn1js.fromBER(berTrue);
assert.strictEqual(decTrue.offset, 3, 'fromBER must consume 3 bytes for boolean true');
assert(decTrue.result instanceof asn1js.Boolean, 'decoded result must be asn1js.Boolean');
assert.strictEqual(decTrue.result.getValue(), true, 'decoded boolean value must be true');

const decFalse = asn1js.fromBER(berFalse);
assert.strictEqual(decFalse.offset, 3, 'fromBER must consume 3 bytes for boolean false');
assert(decFalse.result instanceof asn1js.Boolean, 'decoded result must be asn1js.Boolean');
assert.strictEqual(decFalse.result.getValue(), false, 'decoded boolean value must be false');

// ITU-T X.690 allows any non-zero value as true in BER
const berNonZero = new Uint8Array([0x01, 0x01, 0x01]).buffer;
const decNonZero = asn1js.fromBER(berNonZero);
assert(decNonZero.result instanceof asn1js.Boolean, 'decoded result must be asn1js.Boolean');
assert.strictEqual(decNonZero.result.getValue(), true, 'non-zero octet must decode to true');

// Invalid/truncated buffer handling
const truncated = new Uint8Array([0x01, 0x01]).buffer;
const decTrunc = asn1js.fromBER(truncated);
assert.strictEqual(decTrunc.offset, -1, 'truncated buffer must return offset -1');

// 4. Schema verification with asn1js.verifySchema
const schema = new asn1js.Boolean({ name: 'flag' });
const resValid = asn1js.verifySchema(berTrue, schema);
assert.strictEqual(resValid.verified, true, 'schema verification must pass for boolean buffer');
assert.strictEqual(resValid.result.flag.getValue(), true, 'schema result must contain flag');

const wrongSchema = new asn1js.Integer({ name: 'flag' });
const resInvalid = asn1js.verifySchema(berTrue, wrongSchema);
assert.strictEqual(resInvalid.verified, false, 'schema verification must fail for mismatched type');

// 5. Helper functions from src/index.js
const createdTrue = createBoolean(true);
assert(createdTrue instanceof asn1js.Boolean, 'createBoolean must return asn1js.Boolean');
assert.strictEqual(createdTrue.getValue(), true);

const encodedTrue = encodeBoolean(true);
assert(encodedTrue instanceof ArrayBuffer);
assert.strictEqual(decodeBoolean(encodedTrue), true);

const encodedFalse = encodeBoolean(false);
assert(encodedFalse instanceof ArrayBuffer);
assert.strictEqual(decodeBoolean(encodedFalse), false);

const boolSchema = createBooleanSchema('active');
const validated = verifyBooleanSchema(encodedTrue, boolSchema);
assert.strictEqual(validated.verified, true);
assert.strictEqual(validated.result.active.getValue(), true);

console.log('Contract tests passed successfully.');

Исходный сидер

аноним