CodeSampleX

Пример

dompurify 3.3.1: version, isSupported, isValidAttribute

Проверенный пример — npm dompurify 3.3.1: version, isSupported, isValidAttribute. Контракт выполнен на node 22 · linux debian/x64 · docker и пройден.

sha256:56109dfc5505cd925adf37ead5f463726992a80414ca529ac40886b89406afc8

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

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

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

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

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

Окружение Контракт Этапы Запуск
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-11

Кейс

HOW
Цель
verify pkg:npm/dompurify@3.3.1
Пакеты
Символы
  • DOMPurify
  • DOMPurify.version
  • DOMPurify.isSupported
  • DOMPurify.isValidAttribute
  • DOMPurify.sanitize
  • DOMPurify.setConfig
  • DOMPurify.clearConfig
  • DOMPurify.addHook
  • DOMPurify.removeHook
  • DOMPurify.removeAllHooks
Окружение
node 22.23.2
Создан
2026-09-11T06:34:41Z

Контракт

  1. DOMPurify exports a factory function with version 3.3.1 and isSupported false when no DOM window is present
  2. DOMPurify factory returns itself when invoked without window
  3. DOMPurify factory accepts a custom window implementation and returns a configured DOMPurify instance with isSupported true
  4. DOMPurify instance validates safe HTML tag attributes such as href and src via isValidAttribute
  5. DOMPurify instance rejects dangerous event handlers such as onclick, onerror, and onload via isValidAttribute
  6. DOMPurify instance rejects dangerous javascript URI schemes in href attributes via isValidAttribute
  7. DOMPurify instance registers and removes lifecycle hooks before and after sanitization
  8. DOMPurify instance accepts custom configuration via setConfig and resets configuration via clearConfig
  9. DOMPurify instance sanitizes string content through the DOM sanitization pipeline

Файлы

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

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

Исходный код

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/dompurify@3.3.1
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/dompurify@3.3.1

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:ef375d04738378adfefd6dc9fa0434a4e18e7af54490a45804f9f1081d850b57","contract":["DOMPurify exports a factory function with version 3.3.1 and isSupported false when no DOM window is present","DOMPurify factory returns itself when invoked without window","DOMPurify factory accepts a custom window implementation and returns a configured DOMPurify instance with isSupported true","DOMPurify instance validates safe HTML tag attributes such as href and src via isValidAttribute","DOMPurify instance rejects dangerous event handlers such as onclick, onerror, and onload via isValidAttribute","DOMPurify instance rejects dangerous javascript URI schemes in href attributes via isValidAttribute","DOMPurify instance registers and removes lifecycle hooks before and after sanitization","DOMPurify instance accepts custom configuration via setConfig and resets configuration via clearConfig","DOMPurify instance sanitizes string content through the DOM sanitization pipeline"],"goal":"verify pkg:npm/dompurify@3.3.1","kind":"HOW","packages":["pkg:npm/dompurify@3.3.1"],"schemaVersion":1,"symbols":["DOMPurify","DOMPurify.version","DOMPurify.isSupported","DOMPurify.isValidAttribute","DOMPurify.sanitize","DOMPurify.setConfig","DOMPurify.clearConfig","DOMPurify.addHook","DOMPurify.removeHook","DOMPurify.removeAllHooks"]},"contractCommand":["node","test/contract.mjs"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"npm","executionContext":"node","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/dompurify@3.3.1"],"schemaVersion":1,"subject":"pkg:npm/dompurify@3.3.1","symbols":["DOMPurify","DOMPurify.version","DOMPurify.isSupported","DOMPurify.isValidAttribute","DOMPurify.sanitize","DOMPurify.setConfig","DOMPurify.clearConfig","DOMPurify.addHook","DOMPurify.removeHook","DOMPurify.removeAllHooks"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "sample-dompurify",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-dompurify",
      "version": "1.0.0",
      "dependencies": {
        "dompurify": "3.3.1"
      }
    },
    "node_modules/@types/trusted-types": {
      "version": "2.0.7",
      "resolved": "https://registry.npmjs.org/@types/trusted-types/-/trusted-types-2.0.7.tgz",
      "integrity": "sha512-ScaPdn1dQczgbl0QFTeTOmVHFULt394XJgOQNoyVhZ6r2vLnMLJfBPd53SB52T/3G36VI1/g2MZaX0cwDuXsfw==",
      "license": "MIT",
      "optional": true
    },
    "node_modules/dompurify": {
      "version": "3.3.1",
      "resolved": "https://registry.npmjs.org/dompurify/-/dompurify-3.3.1.tgz",
      "integrity": "sha512-qkdCKzLNtrgPFP1Vo+98FRzJnBRGe4ffyCea9IwHB1fyxPOeNTHpLKYGd4Uk9xvNoH0ZoOjwZxNptyMwqrId1Q==",
      "license": "(MPL-2.0 OR Apache-2.0)",
      "optionalDependencies": {
        "@types/trusted-types": "^2.0.7"
      }
    }
  }
}
package.json
{
  "name": "sample-dompurify",
  "version": "1.0.0",
  "private": true,
  "type": "module",
  "dependencies": {
    "dompurify": "3.3.1"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pkg:npm/dompurify@3.3.1",
  "kind": "HOW",
  "packages": [
    "pkg:npm/dompurify@3.3.1"
  ]
}
test/contract.mjs
import assert from 'node:assert/strict';
import DOMPurify from 'dompurify';

// 1. DOMPurify exports a factory function with version 3.3.1 and isSupported false when no DOM window is present
assert.equal(typeof DOMPurify, 'function');
assert.equal(DOMPurify.version, '3.3.1');
assert.equal(DOMPurify.isSupported, false);
assert.deepEqual(DOMPurify.removed, []);

// 2. DOMPurify factory returns itself when invoked without window
const factorySelf = DOMPurify();
assert.equal(typeof factorySelf, 'function');
assert.equal(factorySelf.isSupported, false);
assert.equal(factorySelf.version, '3.3.1');

// Setup mock DOM environment for headless Node.js verification
function createMockDOM() {
  function Node() {}
  Node.DOCUMENT_NODE = 9;
  Node.ELEMENT_NODE = 1;
  Node.TEXT_NODE = 3;
  Node.COMMENT_NODE = 8;
  Node.DOCUMENT_FRAGMENT_NODE = 11;

  function Element(name) {
    this.nodeName = (name || '').toUpperCase();
    this.tagName = this.nodeName;
    this.nodeType = Node.ELEMENT_NODE;
    this.childNodes = [];
    this.attributes = [];
    this.parentNode = null;
    this.ownerDocument = null;
    this.namespaceURI = 'http://www.w3.org/1999/xhtml';
  }
  Element.prototype = Object.create(Node.prototype);
  Element.prototype.cloneNode = function() { return new Element(this.nodeName); };
  Element.prototype.remove = function() {
    if (this.parentNode) {
      const idx = this.parentNode.childNodes.indexOf(this);
      if (idx !== -1) this.parentNode.childNodes.splice(idx, 1);
      this.parentNode = null;
    }
  };
  Element.prototype.removeChild = function(child) {
    const idx = this.childNodes.indexOf(child);
    if (idx !== -1) this.childNodes.splice(idx, 1);
    child.parentNode = null;
    return child;
  };
  Element.prototype.insertBefore = function(newNode, refNode) {
    this.childNodes.push(newNode);
    newNode.parentNode = this;
    return newNode;
  };
  Element.prototype.hasChildNodes = function() { return this.childNodes.length > 0; };
  Element.prototype.getAttribute = function(name) { return null; };
  Element.prototype.setAttribute = function(name, value) {};
  Element.prototype.removeAttribute = function(name) {};
  Element.prototype.hasAttribute = function(name) { return false; };
  Object.defineProperty(Element.prototype, 'nextSibling', { get() { return null; } });

  function Document() {
    this.nodeType = 9;
    this.documentElement = new Element('HTML');
    this.body = new Element('BODY');
    this.body.parentNode = this.documentElement;
    this.documentElement.childNodes.push(this.body);
    this.createNodeIterator = function(root) {
      return { nextNode: () => null };
    };
    this.implementation = {
      createDocument: () => new Document(),
      createHTMLDocument: () => new Document()
    };
  }
  Document.prototype = Object.create(Node.prototype);
  Document.prototype.createElement = function(tag) {
    const el = new Element(tag);
    el.ownerDocument = this;
    return el;
  };
  Document.prototype.createDocumentFragment = function() {
    const frag = new Node();
    frag.nodeType = Node.DOCUMENT_FRAGMENT_NODE;
    frag.childNodes = [];
    return frag;
  };
  Document.prototype.createTextNode = function(text) {
    const t = new Node();
    t.nodeType = Node.TEXT_NODE;
    t.nodeValue = text;
    return t;
  };
  Document.prototype.getElementsByTagName = function(tag) {
    if (tag.toLowerCase() === 'body') return [this.body];
    if (tag.toLowerCase() === 'html') return [this.documentElement];
    return [];
  };
  Document.prototype.importNode = function(node, deep) { return node; };

  return {
    document: new Document(),
    Element: Element,
    Node: Node,
    DocumentFragment: function() {},
    NodeFilter: {
      SHOW_ELEMENT: 1,
      SHOW_COMMENT: 128,
      SHOW_TEXT: 4,
      SHOW_PROCESSING_INSTRUCTION: 64,
      SHOW_CDATA_SECTION: 8
    },
    NamedNodeMap: function() {},
    HTMLFormElement: function() {}
  };
}

const mockWindow = createMockDOM();
const purify = DOMPurify(mockWindow);

// 3. DOMPurify factory accepts a custom window implementation and returns a configured DOMPurify instance with isSupported true
assert.equal(purify.isSupported, true);
assert.equal(purify.version, '3.3.1');
assert.equal(typeof purify.sanitize, 'function');
assert.equal(typeof purify.isValidAttribute, 'function');
assert.equal(typeof purify.addHook, 'function');
assert.equal(typeof purify.setConfig, 'function');

// 4. DOMPurify instance validates safe HTML tag attributes such as href and src via isValidAttribute
assert.equal(purify.isValidAttribute('a', 'href', 'https://example.com'), true);
assert.equal(purify.isValidAttribute('img', 'src', 'https://example.com/image.png'), true);
assert.equal(purify.isValidAttribute('div', 'title', 'Helpful description'), true);

// 5. DOMPurify instance rejects dangerous event handlers such as onclick, onerror, and onload via isValidAttribute
assert.equal(purify.isValidAttribute('a', 'onclick', 'alert(1)'), false);
assert.equal(purify.isValidAttribute('img', 'onerror', 'alert(1)'), false);
assert.equal(purify.isValidAttribute('body', 'onload', 'alert(1)'), false);

// 6. DOMPurify instance rejects dangerous javascript URI schemes in href attributes via isValidAttribute
assert.equal(purify.isValidAttribute('a', 'href', 'javascript:alert(1)'), false);
assert.equal(purify.isValidAttribute('a', 'href', 'jav\tascript:alert(1)'), false);

// 7. DOMPurify instance registers and removes lifecycle hooks before and after sanitization
let hookInvoked = false;
const hookCallback = (node, data) => { hookInvoked = true; };
purify.addHook('beforeSanitizeElements', hookCallback);
const detachedHook = purify.removeHook('beforeSanitizeElements', hookCallback);
assert.equal(detachedHook, hookCallback);
purify.removeAllHooks();

// 8. DOMPurify instance accepts custom configuration via setConfig and resets configuration via clearConfig
purify.setConfig({ ALLOWED_TAGS: ['b', 'i'], ALLOWED_ATTR: ['style'] });
purify.clearConfig();

// 9. DOMPurify instance sanitizes string content through the DOM sanitization pipeline
const sanitizedString = purify.sanitize('Clean safe markup string');
assert.equal(sanitizedString, 'Clean safe markup string');

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

аноним