CodeSampleX

Ejemplo

pkijs 3.4.0

Muestra verificada para npm pkijs 3.4.0. El contrato se ejecutó en node 22 · linux alpine/x64 · docker y pasó: initializeCryptoEngine configures pkijs to use…

sha256:88f9fbbb1f01c32d448630d753bb80efcd0320d1f1a015caf6b4e75eee1a4df8

Esta red ofrece una sola cosa: una muestra que compila. La ejecutó en un sandbox y guardó el recibo firmado. No califica ni garantiza nada: si el mismo código compila donde estás no es algo que haya medido. Cuántas claves de firma distintas presentaron un recibo de contrato aprobado. Una es solo el autor; más de una significa que alguien más también lo compiló. Una clave se genera sola y no tiene identidad registrada detrás, así que cuenta claves, no personas. MIT-0

Evidencia de ejecución

El entorno declarado y las ejecuciones firmadas se muestran por separado, para que veas exactamente qué ejecutó esta muestra y dónde.

Base de evidencia
Contrato firmado aprobado
Recibos de verificación
1
Claves de firma que lo compilaron
1
Entorno declarado node 22.23 linux 24 · ubuntu · glibc 2.39 x64 node 22.23 javascript npm 10

Entornos de las ejecuciones de verificación

Entorno Contrato Etapas Ejecución
node 22 · linux alpine/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · node-typescript@1node:22-alpine@sha256:c610fcdfb1d5…
2026-08-27

Caso

HOW
Objetivo
verify pkg:npm/pkijs@3.4.0
Paquetes
Entorno
node 22.23.2
Creado
2026-08-27T20:29:05Z

Contrato

  1. initializeCryptoEngine configures pkijs to use WebCrypto crypto and subtle engines
  2. createSelfSignedCertificate creates and signs a valid X.509 v3 certificate with subject, issuer, and validity dates
  3. encodeCertificate serializes a Certificate instance into a BER ArrayBuffer schema
  4. decodeCertificate parses a BER ArrayBuffer into a valid Certificate instance with matching properties
  5. verifyCertificate returns true for valid self-signed certificates and false for mismatched issuer signatures
  6. BasicConstraints extension is correctly configured with cA flag and pathLenConstraint

Archivos

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

Descargar el artefacto de código fuente (tar.gz)

Código fuente

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 pkg:npm/pkijs@3.4.0
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/pkijs@3.4.0

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:12569cee0527b8154d7fc71fcace04a8efc1ead70c3216cbb45ee329f887576a","contract":["initializeCryptoEngine configures pkijs to use WebCrypto crypto and subtle engines","createSelfSignedCertificate creates and signs a valid X.509 v3 certificate with subject, issuer, and validity dates","encodeCertificate serializes a Certificate instance into a BER ArrayBuffer schema","decodeCertificate parses a BER ArrayBuffer into a valid Certificate instance with matching properties","verifyCertificate returns true for valid self-signed certificates and false for mismatched issuer signatures","BasicConstraints extension is correctly configured with cA flag and pathLenConstraint"],"goal":"verify pkg:npm/pkijs@3.4.0","kind":"HOW","packages":["pkg:npm/pkijs@3.4.0"],"schemaVersion":1},"contractCommand":["node","test/contract.mjs"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"npm","language":"javascript","libc":"glibc","libcVersion":"2.39","moduleSystem":"esm","os":"linux","osVersionBucket":"24","packageManager":"npm","packageManagerVersion":"10.9.8","runtime":"node","runtimeVersion":"22.23.2","schemaVersion":1},"license":"MIT-0","packages":["pkg:npm/pkijs@3.4.0"],"schemaVersion":1,"subject":"pkg:npm/pkijs@3.4.0","verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "sample-pkijs",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-pkijs",
      "version": "1.0.0",
      "dependencies": {
        "pkijs": "3.4.0"
      }
    },
    "node_modules/@noble/hashes": {
      "version": "1.4.0",
      "resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-1.4.0.tgz",
      "integrity": "sha512-V1JJ1WTRUqHHrOSh597hURcMqVKVGL/ea3kv0gSnEdsEZ0/+VyPghM1lMNGc00z7CIQorSvbKpuJkxvuHbvdbg==",
      "license": "MIT",
      "engines": {
        "node": ">= 16"
      },
      "funding": {
        "url": "https://paulmillr.com/funding/"
      }
    },
    "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/bytestreamjs": {
      "version": "2.0.1",
      "resolved": "https://registry.npmjs.org/bytestreamjs/-/bytestreamjs-2.0.1.tgz",
      "integrity": "sha512-U1Z/ob71V/bXfVABvNr/Kumf5VyeQRBEm6Txb0PQ6S7V5GpBM3w4Cbqz/xPDicR5tN0uvDifng8C+5qECeGwyQ==",
      "license": "BSD-3-Clause",
      "engines": {
        "node": ">=6.0.0"
      }
    },
    "node_modules/pkijs": {
      "version": "3.4.0",
      "resolved": "https://registry.npmjs.org/pkijs/-/pkijs-3.4.0.tgz",
      "integrity": "sha512-emEcLuomt2j03vxD54giVB4SxTjnsqkU692xZOZXHDVoYyypEm+b3jpiTcc+Cf+myooc+/Ly0z01jqeNHVgJGw==",
      "license": "BSD-3-Clause",
      "dependencies": {
        "@noble/hashes": "1.4.0",
        "asn1js": "^3.0.6",
        "bytestreamjs": "^2.0.1",
        "pvtsutils": "^1.3.6",
        "pvutils": "^1.1.3",
        "tslib": "^2.8.1"
      },
      "engines": {
        "node": ">=16.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-pkijs",
  "version": "1.0.0",
  "private": true,
  "description": "Clean-room verification of pkijs X.509 certificate generation, encoding, decoding, and cryptographic verification",
  "type": "module",
  "main": "src/index.js",
  "dependencies": {
    "pkijs": "3.4.0"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pkg:npm/pkijs@3.4.0",
  "kind": "HOW",
  "packages": [
    "pkg:npm/pkijs@3.4.0"
  ]
}
src/index.js
import * as pkijs from 'pkijs';
import * as asn1js from 'asn1js';

/**
 * Initialize and set the global pkijs crypto engine using WebCrypto.
 * @param {Crypto} [customCrypto] - Optional custom WebCrypto implementation.
 * @returns {pkijs.AbstractCryptoEngine} The configured crypto engine instance.
 */
export function initializeCryptoEngine(customCrypto = globalThis.crypto) {
  const engine = new pkijs.CryptoEngine({
    name: 'webcrypto',
    crypto: customCrypto,
    subtle: customCrypto.subtle
  });
  pkijs.setEngine('webcrypto', engine);
  return pkijs.getEngine();
}

/**
 * Create and self-sign an X.509 v3 certificate.
 * @param {object} options
 * @param {string} [options.commonName="example.com"] - Common Name for Subject and Issuer.
 * @param {number} [options.serialNumber=1] - Serial number of the certificate.
 * @param {number} [options.validityDays=365] - Certificate validity period in days.
 * @param {CryptoKeyPair} options.keyPair - WebCrypto CryptoKeyPair containing publicKey and privateKey.
 * @param {string} [options.hashAlgorithm="SHA-256"] - Hash algorithm for the signature.
 * @returns {Promise<pkijs.Certificate>}
 */
export async function createSelfSignedCertificate({
  commonName = 'example.com',
  serialNumber = 1,
  validityDays = 365,
  keyPair,
  hashAlgorithm = 'SHA-256'
}) {
  initializeCryptoEngine();

  const certificate = new pkijs.Certificate();
  certificate.version = 2; // X.509 v3
  certificate.serialNumber = new asn1js.Integer({ value: serialNumber });

  certificate.issuer.typesAndValues.push(
    new pkijs.AttributeTypeAndValue({
      type: '2.5.4.3', // Common Name OID
      value: new asn1js.Utf8String({ value: commonName })
    })
  );

  certificate.subject.typesAndValues.push(
    new pkijs.AttributeTypeAndValue({
      type: '2.5.4.3', // Common Name OID
      value: new asn1js.Utf8String({ value: commonName })
    })
  );

  const notBefore = new Date();
  const notAfter = new Date(notBefore.getTime() + validityDays * 24 * 60 * 60 * 1000);
  certificate.notBefore.value = notBefore;
  certificate.notAfter.value = notAfter;

  const basicConstraints = new pkijs.BasicConstraints({
    cA: true,
    pathLenConstraint: 2
  });

  certificate.extensions = [
    new pkijs.Extension({
      extnID: '2.5.29.19', // Basic Constraints OID
      critical: true,
      extnValue: basicConstraints.toSchema().toBER(false),
      parsedValue: basicConstraints
    })
  ];

  await certificate.subjectPublicKeyInfo.importKey(keyPair.publicKey);
  await certificate.sign(keyPair.privateKey, hashAlgorithm);

  return certificate;
}

/**
 * Serialize a Certificate instance into a BER-encoded ArrayBuffer.
 * @param {pkijs.Certificate} certificate
 * @returns {ArrayBuffer}
 */
export function encodeCertificate(certificate) {
  return certificate.toSchema().toBER(false);
}

/**
 * Parse a BER-encoded ArrayBuffer into a Certificate instance.
 * @param {ArrayBuffer} berBuffer
 * @returns {pkijs.Certificate}
 */
export function decodeCertificate(berBuffer) {
  return pkijs.Certificate.fromBER(berBuffer);
}

/**
 * Verify a certificate's digital signature.
 * @param {pkijs.Certificate} certificate - The certificate to verify.
 * @param {pkijs.Certificate} [issuerCertificate] - Optional issuer certificate (defaults to self-verification).
 * @returns {Promise<boolean>} True if signature is valid, false otherwise.
 */
export async function verifyCertificate(certificate, issuerCertificate) {
  initializeCryptoEngine();
  return await certificate.verify(issuerCertificate);
}

export {
  pkijs,
  asn1js
};
test/contract.mjs
import assert from 'node:assert';
import {
  initializeCryptoEngine,
  createSelfSignedCertificate,
  encodeCertificate,
  decodeCertificate,
  verifyCertificate,
  pkijs
} from '../src/index.js';

// 1. Initialize crypto engine and verify configuration
const engine = initializeCryptoEngine();
assert.strictEqual(typeof engine, 'object', 'Engine should be an object');
assert.strictEqual(engine.name, 'webcrypto', 'Engine name should be webcrypto');
assert.strictEqual(pkijs.getEngine().name, 'webcrypto', 'getEngine should return the configured engine');

// 2. Generate ECDSA key pairs for signing and verification
const algorithm = { name: 'ECDSA', namedCurve: 'P-256' };
const primaryKeyPair = await globalThis.crypto.subtle.generateKey(algorithm, true, ['sign', 'verify']);
const secondaryKeyPair = await globalThis.crypto.subtle.generateKey(algorithm, true, ['sign', 'verify']);

// 3. Create self-signed certificate and verify properties
const cert = await createSelfSignedCertificate({
  commonName: 'example.com',
  serialNumber: 42,
  validityDays: 180,
  keyPair: primaryKeyPair,
  hashAlgorithm: 'SHA-256'
});

assert.strictEqual(cert.version, 2, 'Certificate version should be 2 (X.509 v3)');
assert.strictEqual(cert.serialNumber.valueBlock.valueDec, 42, 'Serial number should match 42');
assert.strictEqual(cert.issuer.typesAndValues.length, 1, 'Issuer should have 1 attribute');
assert.strictEqual(cert.issuer.typesAndValues[0].type, '2.5.4.3', 'Issuer attribute should be Common Name OID');
assert.strictEqual(cert.issuer.typesAndValues[0].value.valueBlock.value, 'example.com', 'Issuer CN should be example.com');
assert.strictEqual(cert.subject.typesAndValues[0].value.valueBlock.value, 'example.com', 'Subject CN should be example.com');

// 4. Verify BasicConstraints extension configuration
assert.strictEqual(cert.extensions.length, 1, 'Extensions should contain 1 extension');
assert.strictEqual(cert.extensions[0].extnID, '2.5.29.19', 'Extension OID should be BasicConstraints');
assert.strictEqual(cert.extensions[0].critical, true, 'BasicConstraints should be marked critical');
assert.strictEqual(cert.extensions[0].parsedValue.cA, true, 'BasicConstraints cA should be true');
assert.strictEqual(cert.extensions[0].parsedValue.pathLenConstraint, 2, 'BasicConstraints pathLenConstraint should be 2');

// 5. Serialize Certificate to BER ArrayBuffer
const berBuffer = encodeCertificate(cert);
assert.strictEqual(berBuffer instanceof ArrayBuffer, true, 'encodeCertificate should return ArrayBuffer');
assert.ok(berBuffer.byteLength > 0, 'BER buffer length should be greater than 0');

// 6. Deserialize BER ArrayBuffer back into Certificate
const decodedCert = decodeCertificate(berBuffer);
assert.strictEqual(decodedCert instanceof pkijs.Certificate, true, 'decodeCertificate should return Certificate instance');
assert.strictEqual(decodedCert.version, 2, 'Decoded certificate version should match');
assert.strictEqual(decodedCert.serialNumber.valueBlock.valueDec, 42, 'Decoded serial number should match');
assert.strictEqual(decodedCert.issuer.typesAndValues[0].value.valueBlock.value, 'example.com', 'Decoded issuer CN should match');

// 7. Verify cryptographic signature (positive case)
const isSelfValid = await verifyCertificate(decodedCert);
assert.strictEqual(isSelfValid, true, 'Self-signed certificate verification should succeed');

// 8. Verify cryptographic signature against mismatched issuer (negative case)
const mismatchedCert = await createSelfSignedCertificate({
  commonName: 'mismatched.org',
  serialNumber: 99,
  validityDays: 180,
  keyPair: secondaryKeyPair,
  hashAlgorithm: 'SHA-256'
});

const isMismatchedValid = await verifyCertificate(decodedCert, mismatchedCert);
assert.strictEqual(isMismatchedValid, false, 'Verification against mismatched issuer should fail');

console.log('All pkijs contract assertions passed successfully.');

Seeder de origen

anónimo