From 872b2a2b481cbd1776f6e116ea19d822bbed546c Mon Sep 17 00:00:00 2001 From: Siri Dalugoda <22433736+asiridalugoda@users.noreply.github.com> Date: Wed, 18 Nov 2026 08:22:18 +1300 Subject: [PATCH] fix(schema): generate the token validator at build time The token schema validator was compiled with Ajv when the module loaded. Ajv compiles with `new Function`, so the package threw "EvalError: Code generation from strings disallowed" on import in runtimes that forbid code generation from strings: Cloudflare Workers, strict Content-Security-Policy pages, and Node run with --disallow-code-generation-from-strings. scripts/build-validator.mjs now compiles token.schema.json once, with Ajv's standalone code output, into src/schema/validator.generated.js. The file is committed and regenerated by the prebuild step. validator.ts imports it and formats errors the way Ajv's errorsText did, so HdpSchemaError messages are unchanged. Ajv and ajv-formats move to devDependencies: the one runtime helper the generated code uses is now bundled into dist/, and the published package no longer depends on Ajv. Tests: - tests/unit/dist-no-codegen.test.ts loads dist/index.js and dist/index.mjs under --disallow-code-generation-from-strings, issues and verifies a token, and checks that an invalid token is rejected. Against the previous validator both cases fail with the EvalError above; with this change both pass. - tests/unit/schema-standalone.test.ts fails when the committed generated file no longer matches the schema (checked by editing the schema title without regenerating). CI builds before running tests so the dist test runs instead of being skipped. Versions of @helixar_ai/hdp, hdp-mcp, hdp-cli and hdp-autogen move to 0.2.3. Claude-Session: https://claude.ai/code/session_01Lwur7k4tD9t1MQ7BU2Q4R4 --- .github/workflows/ci.yml | 9 ++-- package-lock.json | 20 ++++++--- package.json | 8 ++-- packages/hdp-autogen-ts/package.json | 2 +- packages/hdp-cli/package.json | 2 +- packages/hdp-mcp/package.json | 2 +- scripts/build-validator.mjs | 52 +++++++++++++++++++++ src/schema/validator.generated.d.ts | 19 ++++++++ src/schema/validator.generated.js | 5 +++ src/schema/validator.ts | 22 +++++---- tests/unit/dist-no-codegen.test.ts | 67 ++++++++++++++++++++++++++++ tests/unit/schema-standalone.test.ts | 22 +++++++++ 12 files changed, 206 insertions(+), 24 deletions(-) create mode 100644 scripts/build-validator.mjs create mode 100644 src/schema/validator.generated.d.ts create mode 100644 src/schema/validator.generated.js create mode 100644 tests/unit/dist-no-codegen.test.ts create mode 100644 tests/unit/schema-standalone.test.ts diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 29ea4ed..8773a00 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -34,12 +34,15 @@ jobs: - name: Typecheck run: npm run typecheck - - name: Run tests - run: npm test - + # Build before testing: tests/unit/dist-no-codegen.test.ts loads the + # built package under --disallow-code-generation-from-strings and is + # skipped when dist/ is absent. - name: Build run: npm run build + - name: Run tests + run: npm test + smoke-npm-consumers: name: Smoke packed npm consumers (Node ${{ matrix.node-version }}) runs-on: ubuntu-latest diff --git a/package-lock.json b/package-lock.json index 11114f0..4a95daa 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "@helixar_ai/hdp", - "version": "0.2.2", + "version": "0.2.3", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@helixar_ai/hdp", - "version": "0.2.2", + "version": "0.2.3", "license": "Apache-2.0", "workspaces": [ "packages/*" @@ -14,8 +14,6 @@ "dependencies": { "@noble/ed25519": "^3.0.1", "@noble/hashes": "^2.0.1", - "ajv": "^8.18.0", - "ajv-formats": "^3.0.1", "json-canonicalize": "2.0.0", "uuid": "^13.0.0", "zod": "^4.3.6" @@ -23,6 +21,8 @@ "devDependencies": { "@types/node": "^25.5.0", "@types/uuid": "^10.0.0", + "ajv": "^8.18.0", + "ajv-formats": "^3.0.1", "tsup": "^8.5.1", "typescript": "^6.0.2", "vitest": "^4.1.1" @@ -1348,6 +1348,7 @@ "version": "8.18.0", "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.18.0.tgz", "integrity": "sha512-PlXPeEWMXMZ7sPYOHqmDyCJzcfNrUr3fGNKtezX14ykXOEIvyK81d+qydx89KY5O71FKMPaQ2vBfBFI5NHR63A==", + "dev": true, "license": "MIT", "dependencies": { "fast-deep-equal": "^3.1.3", @@ -1364,6 +1365,7 @@ "version": "3.0.1", "resolved": "https://registry.npmjs.org/ajv-formats/-/ajv-formats-3.0.1.tgz", "integrity": "sha512-8iUql50EUR+uUcdRQ3HDqa6EVyo3docL8g5WJ3FNcWmu62IbkGUue/pEyLBW8VGKKucTPgqeks4fIU1DA4yowQ==", + "dev": true, "license": "MIT", "dependencies": { "ajv": "^8.0.0" @@ -1581,12 +1583,14 @@ "version": "3.1.3", "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==", + "dev": true, "license": "MIT" }, "node_modules/fast-uri": { "version": "3.1.8", "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.8.tgz", "integrity": "sha512-GZMtZUTNRpOVIECoXwLNZS5xUGE+mVNbTB8h/7Rwh2TFWcBQiPzTgyZi05BF9UMZKkLJv8XBRJTlU7zg8+ZfMg==", + "dev": true, "funding": [ { "type": "github", @@ -1668,6 +1672,7 @@ "version": "1.0.0", "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz", "integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==", + "dev": true, "license": "MIT" }, "node_modules/lightningcss": { @@ -2194,6 +2199,7 @@ "version": "2.0.2", "resolved": "https://registry.npmjs.org/require-from-string/-/require-from-string-2.0.2.tgz", "integrity": "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==", + "dev": true, "license": "MIT", "engines": { "node": ">=0.10.0" @@ -2732,7 +2738,7 @@ }, "packages/hdp-autogen-ts": { "name": "@helixar_ai/hdp-autogen", - "version": "0.2.2", + "version": "0.2.3", "license": "Apache-2.0", "dependencies": { "@helixar_ai/hdp": "file:../.." @@ -2746,7 +2752,7 @@ }, "packages/hdp-cli": { "name": "hdp-validate", - "version": "0.2.2", + "version": "0.2.3", "license": "Apache-2.0", "dependencies": { "@helixar_ai/hdp": "file:../.." @@ -2763,7 +2769,7 @@ }, "packages/hdp-mcp": { "name": "@helixar_ai/hdp-mcp", - "version": "0.2.2", + "version": "0.2.3", "license": "Apache-2.0", "dependencies": { "@helixar_ai/hdp": "file:../.." diff --git a/package.json b/package.json index fe2036d..530b051 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@helixar_ai/hdp", - "version": "0.2.2", + "version": "0.2.3", "description": "", "main": "dist/index.js", "module": "dist/index.mjs", @@ -17,6 +17,8 @@ "doc": "docs" }, "scripts": { + "build:validator": "node scripts/build-validator.mjs", + "prebuild": "npm run build:validator", "build": "tsup src/index.ts --format cjs,esm --dts", "test": "vitest run", "test:watch": "vitest", @@ -37,8 +39,6 @@ "dependencies": { "@noble/ed25519": "^3.0.1", "@noble/hashes": "^2.0.1", - "ajv": "^8.18.0", - "ajv-formats": "^3.0.1", "json-canonicalize": "2.0.0", "uuid": "^13.0.0", "zod": "^4.3.6" @@ -46,6 +46,8 @@ "devDependencies": { "@types/node": "^25.5.0", "@types/uuid": "^10.0.0", + "ajv": "^8.18.0", + "ajv-formats": "^3.0.1", "tsup": "^8.5.1", "typescript": "^6.0.2", "vitest": "^4.1.1" diff --git a/packages/hdp-autogen-ts/package.json b/packages/hdp-autogen-ts/package.json index 8af6baf..10304d0 100644 --- a/packages/hdp-autogen-ts/package.json +++ b/packages/hdp-autogen-ts/package.json @@ -1,6 +1,6 @@ { "name": "@helixar_ai/hdp-autogen", - "version": "0.2.2", + "version": "0.2.3", "description": "HDP middleware for AutoGen — cryptographic audit trail for multi-agent delegation", "type": "module", "main": "dist/index.cjs", diff --git a/packages/hdp-cli/package.json b/packages/hdp-cli/package.json index 2cf2366..ac96ec7 100644 --- a/packages/hdp-cli/package.json +++ b/packages/hdp-cli/package.json @@ -1,6 +1,6 @@ { "name": "hdp-validate", - "version": "0.2.2", + "version": "0.2.3", "description": "CLI validator for HDP (Human Delegation Provenance Protocol) tokens", "type": "module", "bin": { diff --git a/packages/hdp-mcp/package.json b/packages/hdp-mcp/package.json index 99f60d5..5dce9ac 100644 --- a/packages/hdp-mcp/package.json +++ b/packages/hdp-mcp/package.json @@ -1,6 +1,6 @@ { "name": "@helixar_ai/hdp-mcp", - "version": "0.2.2", + "version": "0.2.3", "description": "HDP middleware for MCP (Model Context Protocol) servers", "type": "module", "main": "dist/index.cjs", diff --git a/scripts/build-validator.mjs b/scripts/build-validator.mjs new file mode 100644 index 0000000..3a77acc --- /dev/null +++ b/scripts/build-validator.mjs @@ -0,0 +1,52 @@ +// Generates src/schema/validator.generated.js from src/schema/token.schema.json. +// +// Ajv normally compiles a schema at runtime with `new Function`. Runtimes that +// forbid code generation from strings (Cloudflare Workers, strict +// Content-Security-Policy pages, Node with --disallow-code-generation-from-strings) +// then fail when the package loads. Ajv's standalone mode emits the compiled +// validator as source code instead, so it is compiled once here, at build +// time, and shipped as ordinary JavaScript. +// +// Usage: +// node scripts/build-validator.mjs write the generated file +// import { generate } from './build-validator.mjs' return the text only + +import { createHash } from 'node:crypto' +import { readFileSync, writeFileSync } from 'node:fs' +import { dirname, resolve } from 'node:path' +import { fileURLToPath } from 'node:url' +import Ajv2020 from 'ajv/dist/2020.js' +import addFormats from 'ajv-formats' +import standaloneCode from 'ajv/dist/standalone/index.js' + +const here = dirname(fileURLToPath(import.meta.url)) +export const SCHEMA_PATH = resolve(here, '../src/schema/token.schema.json') +export const OUTPUT_PATH = resolve(here, '../src/schema/validator.generated.js') + +export function generate() { + const schemaText = readFileSync(SCHEMA_PATH, 'utf8') + const schema = JSON.parse(schemaText) + const sha256 = createHash('sha256').update(schemaText).digest('hex') + + // Same options as the former runtime compile (strict: false), plus source + // generation. ESM output so the bundler can emit both the CommonJS and the + // ES module builds from one import graph. + const ajv = new Ajv2020({ strict: false, code: { source: true, esm: true } }) + addFormats(ajv) + const validate = ajv.compile(schema) + const body = standaloneCode(ajv, validate) + + return ( + '// GENERATED FILE. Do not edit by hand.\n' + + '// Source: src/schema/token.schema.json (sha256 ' + sha256 + ')\n' + + '// Generator: scripts/build-validator.mjs (Ajv standalone code).\n' + + '/* eslint-disable */\n' + + body + + '\n' + ) +} + +if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) { + writeFileSync(OUTPUT_PATH, generate()) + console.log('wrote ' + OUTPUT_PATH) +} diff --git a/src/schema/validator.generated.d.ts b/src/schema/validator.generated.d.ts new file mode 100644 index 0000000..e98ea63 --- /dev/null +++ b/src/schema/validator.generated.d.ts @@ -0,0 +1,19 @@ +// Type declaration for the generated validator (scripts/build-validator.mjs). +// Hand-written: Ajv's standalone output is plain JavaScript without types. + +export interface ValidationError { + instancePath: string + schemaPath: string + keyword: string + params: Record + message?: string +} + +export interface ValidateFunction { + (data: unknown): boolean + errors?: ValidationError[] | null +} + +export declare const validate: ValidateFunction +declare const _default: ValidateFunction +export default _default diff --git a/src/schema/validator.generated.js b/src/schema/validator.generated.js new file mode 100644 index 0000000..7986d7b --- /dev/null +++ b/src/schema/validator.generated.js @@ -0,0 +1,5 @@ +// GENERATED FILE. Do not edit by hand. +// Source: src/schema/token.schema.json (sha256 29dde058092b9a09e6035bc42b5caf6f1305561587deecd084e399166ae73cc3) +// Generator: scripts/build-validator.mjs (Ajv standalone code). +/* eslint-disable */ +"use strict";export const validate = validate20;export default validate20;const schema31 = {"$schema":"https://json-schema.org/draft/2020-12/schema","$id":"https://helixar.ai/labs/hdp/schema/0.1/token.json","title":"HDP Token","type":"object","additionalProperties":false,"required":["hdp","header","principal","scope","chain","signature"],"properties":{"hdp":{"type":"string"},"header":{"type":"object","required":["token_id","issued_at","expires_at","session_id","version"],"properties":{"token_id":{"type":"string","format":"uuid","pattern":"^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-4[0-9a-fA-F]{3}-[89aAbB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}$"},"issued_at":{"type":"integer","minimum":0,"maximum":9007199254740991},"expires_at":{"type":"integer","minimum":0,"maximum":9007199254740991},"session_id":{"type":"string","minLength":1},"version":{"type":"string"},"parent_token_id":{"type":"string","format":"uuid"}}},"principal":{"type":"object","required":["id","id_type"],"properties":{"id":{"type":"string"},"id_type":{"type":"string","anyOf":[{"enum":["email","uuid","did","poh","opaque"]},{"pattern":"^x-.+$"}]},"poh_credential":{"type":"string"},"display_name":{"type":"string"},"metadata":{"type":"object"}}},"scope":{"type":"object","required":["intent","data_classification","network_egress","persistence"],"properties":{"intent":{"type":"string"},"authorized_tools":{"type":"array","items":{"type":"string"}},"authorized_resources":{"type":"array","items":{"type":"string"}},"data_classification":{"type":"string","enum":["public","internal","confidential","restricted"]},"network_egress":{"type":"boolean"},"persistence":{"type":"boolean"},"max_hops":{"type":"integer","minimum":1,"maximum":9007199254740991},"constraints":{"type":"array"},"extensions":{"type":"object"}}},"chain":{"type":"array","items":{"type":"object","required":["seq","agent_id","agent_type","timestamp","action_summary","parent_hop","hop_signature"],"properties":{"seq":{"type":"integer","minimum":1,"maximum":9007199254740991},"agent_id":{"type":"string"},"agent_type":{"type":"string"},"agent_fingerprint":{"type":"string"},"timestamp":{"type":"integer","minimum":0,"maximum":9007199254740991},"action_summary":{"type":"string"},"parent_hop":{"type":"integer","minimum":0,"maximum":9007199254740991},"hop_signature":{"type":"string","pattern":"^[A-Za-z0-9_-]{86}$"}}}},"signature":{"type":"object","required":["alg","kid","value"],"properties":{"alg":{"type":"string"},"kid":{"type":"string","minLength":1},"value":{"type":"string","pattern":"^[A-Za-z0-9_-]{86}$"},"signed_fields":{"type":"array","deprecated":true,"prefixItems":[{"const":"header"},{"const":"principal"},{"const":"scope"}],"minItems":3,"maxItems":3}}}}};const formats0 = /^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i;const pattern4 = new RegExp("^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-4[0-9a-fA-F]{3}-[89aAbB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}$", "u");const pattern5 = new RegExp("^x-.+$", "u");const pattern6 = new RegExp("^[A-Za-z0-9_-]{86}$", "u");const func1 = require("ajv/dist/runtime/ucs2length").default;function validate20(data, {instancePath="", parentData, parentDataProperty, rootData=data, dynamicAnchors={}}={}){/*# sourceURL="https://helixar.ai/labs/hdp/schema/0.1/token.json" */;let vErrors = null;let errors = 0;const evaluated0 = validate20.evaluated;if(evaluated0.dynamicProps){evaluated0.props = undefined;}if(evaluated0.dynamicItems){evaluated0.items = undefined;}if(errors === 0){if(data && typeof data == "object" && !Array.isArray(data)){let missing0;if(((((((data.hdp === undefined) && (missing0 = "hdp")) || ((data.header === undefined) && (missing0 = "header"))) || ((data.principal === undefined) && (missing0 = "principal"))) || ((data.scope === undefined) && (missing0 = "scope"))) || ((data.chain === undefined) && (missing0 = "chain"))) || ((data.signature === undefined) && (missing0 = "signature"))){validate20.errors = [{instancePath,schemaPath:"#/required",keyword:"required",params:{missingProperty: missing0},message:"must have required property '"+missing0+"'"}];return false;}else {const _errs1 = errors;for(const key0 in data){if(!((((((key0 === "hdp") || (key0 === "header")) || (key0 === "principal")) || (key0 === "scope")) || (key0 === "chain")) || (key0 === "signature"))){validate20.errors = [{instancePath,schemaPath:"#/additionalProperties",keyword:"additionalProperties",params:{additionalProperty: key0},message:"must NOT have additional properties"}];return false;break;}}if(_errs1 === errors){if(data.hdp !== undefined){const _errs2 = errors;if(typeof data.hdp !== "string"){validate20.errors = [{instancePath:instancePath+"/hdp",schemaPath:"#/properties/hdp/type",keyword:"type",params:{type: "string"},message:"must be string"}];return false;}var valid0 = _errs2 === errors;}else {var valid0 = true;}if(valid0){if(data.header !== undefined){let data1 = data.header;const _errs4 = errors;if(errors === _errs4){if(data1 && typeof data1 == "object" && !Array.isArray(data1)){let missing1;if((((((data1.token_id === undefined) && (missing1 = "token_id")) || ((data1.issued_at === undefined) && (missing1 = "issued_at"))) || ((data1.expires_at === undefined) && (missing1 = "expires_at"))) || ((data1.session_id === undefined) && (missing1 = "session_id"))) || ((data1.version === undefined) && (missing1 = "version"))){validate20.errors = [{instancePath:instancePath+"/header",schemaPath:"#/properties/header/required",keyword:"required",params:{missingProperty: missing1},message:"must have required property '"+missing1+"'"}];return false;}else {if(data1.token_id !== undefined){let data2 = data1.token_id;const _errs6 = errors;if(errors === _errs6){if(errors === _errs6){if(typeof data2 === "string"){if(!pattern4.test(data2)){validate20.errors = [{instancePath:instancePath+"/header/token_id",schemaPath:"#/properties/header/properties/token_id/pattern",keyword:"pattern",params:{pattern: "^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-4[0-9a-fA-F]{3}-[89aAbB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}$"},message:"must match pattern \""+"^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-4[0-9a-fA-F]{3}-[89aAbB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}$"+"\""}];return false;}else {if(!(formats0.test(data2))){validate20.errors = [{instancePath:instancePath+"/header/token_id",schemaPath:"#/properties/header/properties/token_id/format",keyword:"format",params:{format: "uuid"},message:"must match format \""+"uuid"+"\""}];return false;}}}else {validate20.errors = [{instancePath:instancePath+"/header/token_id",schemaPath:"#/properties/header/properties/token_id/type",keyword:"type",params:{type: "string"},message:"must be string"}];return false;}}}var valid1 = _errs6 === errors;}else {var valid1 = true;}if(valid1){if(data1.issued_at !== undefined){let data3 = data1.issued_at;const _errs8 = errors;if(!((typeof data3 == "number") && (!(data3 % 1) && !isNaN(data3)))){validate20.errors = [{instancePath:instancePath+"/header/issued_at",schemaPath:"#/properties/header/properties/issued_at/type",keyword:"type",params:{type: "integer"},message:"must be integer"}];return false;}if(errors === _errs8){if(typeof data3 == "number"){if(data3 > 9007199254740991 || isNaN(data3)){validate20.errors = [{instancePath:instancePath+"/header/issued_at",schemaPath:"#/properties/header/properties/issued_at/maximum",keyword:"maximum",params:{comparison: "<=", limit: 9007199254740991},message:"must be <= 9007199254740991"}];return false;}else {if(data3 < 0 || isNaN(data3)){validate20.errors = [{instancePath:instancePath+"/header/issued_at",schemaPath:"#/properties/header/properties/issued_at/minimum",keyword:"minimum",params:{comparison: ">=", limit: 0},message:"must be >= 0"}];return false;}}}}var valid1 = _errs8 === errors;}else {var valid1 = true;}if(valid1){if(data1.expires_at !== undefined){let data4 = data1.expires_at;const _errs10 = errors;if(!((typeof data4 == "number") && (!(data4 % 1) && !isNaN(data4)))){validate20.errors = [{instancePath:instancePath+"/header/expires_at",schemaPath:"#/properties/header/properties/expires_at/type",keyword:"type",params:{type: "integer"},message:"must be integer"}];return false;}if(errors === _errs10){if(typeof data4 == "number"){if(data4 > 9007199254740991 || isNaN(data4)){validate20.errors = [{instancePath:instancePath+"/header/expires_at",schemaPath:"#/properties/header/properties/expires_at/maximum",keyword:"maximum",params:{comparison: "<=", limit: 9007199254740991},message:"must be <= 9007199254740991"}];return false;}else {if(data4 < 0 || isNaN(data4)){validate20.errors = [{instancePath:instancePath+"/header/expires_at",schemaPath:"#/properties/header/properties/expires_at/minimum",keyword:"minimum",params:{comparison: ">=", limit: 0},message:"must be >= 0"}];return false;}}}}var valid1 = _errs10 === errors;}else {var valid1 = true;}if(valid1){if(data1.session_id !== undefined){let data5 = data1.session_id;const _errs12 = errors;if(errors === _errs12){if(typeof data5 === "string"){if(func1(data5) < 1){validate20.errors = [{instancePath:instancePath+"/header/session_id",schemaPath:"#/properties/header/properties/session_id/minLength",keyword:"minLength",params:{limit: 1},message:"must NOT have fewer than 1 characters"}];return false;}}else {validate20.errors = [{instancePath:instancePath+"/header/session_id",schemaPath:"#/properties/header/properties/session_id/type",keyword:"type",params:{type: "string"},message:"must be string"}];return false;}}var valid1 = _errs12 === errors;}else {var valid1 = true;}if(valid1){if(data1.version !== undefined){const _errs14 = errors;if(typeof data1.version !== "string"){validate20.errors = [{instancePath:instancePath+"/header/version",schemaPath:"#/properties/header/properties/version/type",keyword:"type",params:{type: "string"},message:"must be string"}];return false;}var valid1 = _errs14 === errors;}else {var valid1 = true;}if(valid1){if(data1.parent_token_id !== undefined){let data7 = data1.parent_token_id;const _errs16 = errors;if(errors === _errs16){if(errors === _errs16){if(typeof data7 === "string"){if(!(formats0.test(data7))){validate20.errors = [{instancePath:instancePath+"/header/parent_token_id",schemaPath:"#/properties/header/properties/parent_token_id/format",keyword:"format",params:{format: "uuid"},message:"must match format \""+"uuid"+"\""}];return false;}}else {validate20.errors = [{instancePath:instancePath+"/header/parent_token_id",schemaPath:"#/properties/header/properties/parent_token_id/type",keyword:"type",params:{type: "string"},message:"must be string"}];return false;}}}var valid1 = _errs16 === errors;}else {var valid1 = true;}}}}}}}}else {validate20.errors = [{instancePath:instancePath+"/header",schemaPath:"#/properties/header/type",keyword:"type",params:{type: "object"},message:"must be object"}];return false;}}var valid0 = _errs4 === errors;}else {var valid0 = true;}if(valid0){if(data.principal !== undefined){let data8 = data.principal;const _errs18 = errors;if(errors === _errs18){if(data8 && typeof data8 == "object" && !Array.isArray(data8)){let missing2;if(((data8.id === undefined) && (missing2 = "id")) || ((data8.id_type === undefined) && (missing2 = "id_type"))){validate20.errors = [{instancePath:instancePath+"/principal",schemaPath:"#/properties/principal/required",keyword:"required",params:{missingProperty: missing2},message:"must have required property '"+missing2+"'"}];return false;}else {if(data8.id !== undefined){const _errs20 = errors;if(typeof data8.id !== "string"){validate20.errors = [{instancePath:instancePath+"/principal/id",schemaPath:"#/properties/principal/properties/id/type",keyword:"type",params:{type: "string"},message:"must be string"}];return false;}var valid2 = _errs20 === errors;}else {var valid2 = true;}if(valid2){if(data8.id_type !== undefined){let data10 = data8.id_type;const _errs22 = errors;if(typeof data10 !== "string"){validate20.errors = [{instancePath:instancePath+"/principal/id_type",schemaPath:"#/properties/principal/properties/id_type/type",keyword:"type",params:{type: "string"},message:"must be string"}];return false;}const _errs24 = errors;let valid3 = false;const _errs25 = errors;if(!(((((data10 === "email") || (data10 === "uuid")) || (data10 === "did")) || (data10 === "poh")) || (data10 === "opaque"))){const err0 = {instancePath:instancePath+"/principal/id_type",schemaPath:"#/properties/principal/properties/id_type/anyOf/0/enum",keyword:"enum",params:{allowedValues: schema31.properties.principal.properties.id_type.anyOf[0].enum},message:"must be equal to one of the allowed values"};if(vErrors === null){vErrors = [err0];}else {vErrors.push(err0);}errors++;}var _valid0 = _errs25 === errors;valid3 = valid3 || _valid0;const _errs26 = errors;if(typeof data10 === "string"){if(!pattern5.test(data10)){const err1 = {instancePath:instancePath+"/principal/id_type",schemaPath:"#/properties/principal/properties/id_type/anyOf/1/pattern",keyword:"pattern",params:{pattern: "^x-.+$"},message:"must match pattern \""+"^x-.+$"+"\""};if(vErrors === null){vErrors = [err1];}else {vErrors.push(err1);}errors++;}}var _valid0 = _errs26 === errors;valid3 = valid3 || _valid0;if(!valid3){const err2 = {instancePath:instancePath+"/principal/id_type",schemaPath:"#/properties/principal/properties/id_type/anyOf",keyword:"anyOf",params:{},message:"must match a schema in anyOf"};if(vErrors === null){vErrors = [err2];}else {vErrors.push(err2);}errors++;validate20.errors = vErrors;return false;}else {errors = _errs24;if(vErrors !== null){if(_errs24){vErrors.length = _errs24;}else {vErrors = null;}}}var valid2 = _errs22 === errors;}else {var valid2 = true;}if(valid2){if(data8.poh_credential !== undefined){const _errs27 = errors;if(typeof data8.poh_credential !== "string"){validate20.errors = [{instancePath:instancePath+"/principal/poh_credential",schemaPath:"#/properties/principal/properties/poh_credential/type",keyword:"type",params:{type: "string"},message:"must be string"}];return false;}var valid2 = _errs27 === errors;}else {var valid2 = true;}if(valid2){if(data8.display_name !== undefined){const _errs29 = errors;if(typeof data8.display_name !== "string"){validate20.errors = [{instancePath:instancePath+"/principal/display_name",schemaPath:"#/properties/principal/properties/display_name/type",keyword:"type",params:{type: "string"},message:"must be string"}];return false;}var valid2 = _errs29 === errors;}else {var valid2 = true;}if(valid2){if(data8.metadata !== undefined){let data13 = data8.metadata;const _errs31 = errors;if(!(data13 && typeof data13 == "object" && !Array.isArray(data13))){validate20.errors = [{instancePath:instancePath+"/principal/metadata",schemaPath:"#/properties/principal/properties/metadata/type",keyword:"type",params:{type: "object"},message:"must be object"}];return false;}var valid2 = _errs31 === errors;}else {var valid2 = true;}}}}}}}else {validate20.errors = [{instancePath:instancePath+"/principal",schemaPath:"#/properties/principal/type",keyword:"type",params:{type: "object"},message:"must be object"}];return false;}}var valid0 = _errs18 === errors;}else {var valid0 = true;}if(valid0){if(data.scope !== undefined){let data14 = data.scope;const _errs33 = errors;if(errors === _errs33){if(data14 && typeof data14 == "object" && !Array.isArray(data14)){let missing3;if(((((data14.intent === undefined) && (missing3 = "intent")) || ((data14.data_classification === undefined) && (missing3 = "data_classification"))) || ((data14.network_egress === undefined) && (missing3 = "network_egress"))) || ((data14.persistence === undefined) && (missing3 = "persistence"))){validate20.errors = [{instancePath:instancePath+"/scope",schemaPath:"#/properties/scope/required",keyword:"required",params:{missingProperty: missing3},message:"must have required property '"+missing3+"'"}];return false;}else {if(data14.intent !== undefined){const _errs35 = errors;if(typeof data14.intent !== "string"){validate20.errors = [{instancePath:instancePath+"/scope/intent",schemaPath:"#/properties/scope/properties/intent/type",keyword:"type",params:{type: "string"},message:"must be string"}];return false;}var valid4 = _errs35 === errors;}else {var valid4 = true;}if(valid4){if(data14.authorized_tools !== undefined){let data16 = data14.authorized_tools;const _errs37 = errors;if(errors === _errs37){if(Array.isArray(data16)){var valid5 = true;const len0 = data16.length;for(let i0=0; i0 9007199254740991 || isNaN(data23)){validate20.errors = [{instancePath:instancePath+"/scope/max_hops",schemaPath:"#/properties/scope/properties/max_hops/maximum",keyword:"maximum",params:{comparison: "<=", limit: 9007199254740991},message:"must be <= 9007199254740991"}];return false;}else {if(data23 < 1 || isNaN(data23)){validate20.errors = [{instancePath:instancePath+"/scope/max_hops",schemaPath:"#/properties/scope/properties/max_hops/minimum",keyword:"minimum",params:{comparison: ">=", limit: 1},message:"must be >= 1"}];return false;}}}}var valid4 = _errs51 === errors;}else {var valid4 = true;}if(valid4){if(data14.constraints !== undefined){const _errs53 = errors;if(!(Array.isArray(data14.constraints))){validate20.errors = [{instancePath:instancePath+"/scope/constraints",schemaPath:"#/properties/scope/properties/constraints/type",keyword:"type",params:{type: "array"},message:"must be array"}];return false;}var valid4 = _errs53 === errors;}else {var valid4 = true;}if(valid4){if(data14.extensions !== undefined){let data25 = data14.extensions;const _errs55 = errors;if(!(data25 && typeof data25 == "object" && !Array.isArray(data25))){validate20.errors = [{instancePath:instancePath+"/scope/extensions",schemaPath:"#/properties/scope/properties/extensions/type",keyword:"type",params:{type: "object"},message:"must be object"}];return false;}var valid4 = _errs55 === errors;}else {var valid4 = true;}}}}}}}}}}}else {validate20.errors = [{instancePath:instancePath+"/scope",schemaPath:"#/properties/scope/type",keyword:"type",params:{type: "object"},message:"must be object"}];return false;}}var valid0 = _errs33 === errors;}else {var valid0 = true;}if(valid0){if(data.chain !== undefined){let data26 = data.chain;const _errs57 = errors;if(errors === _errs57){if(Array.isArray(data26)){var valid7 = true;const len2 = data26.length;for(let i2=0; i2 9007199254740991 || isNaN(data28)){validate20.errors = [{instancePath:instancePath+"/chain/" + i2+"/seq",schemaPath:"#/properties/chain/items/properties/seq/maximum",keyword:"maximum",params:{comparison: "<=", limit: 9007199254740991},message:"must be <= 9007199254740991"}];return false;}else {if(data28 < 1 || isNaN(data28)){validate20.errors = [{instancePath:instancePath+"/chain/" + i2+"/seq",schemaPath:"#/properties/chain/items/properties/seq/minimum",keyword:"minimum",params:{comparison: ">=", limit: 1},message:"must be >= 1"}];return false;}}}}var valid8 = _errs61 === errors;}else {var valid8 = true;}if(valid8){if(data27.agent_id !== undefined){const _errs63 = errors;if(typeof data27.agent_id !== "string"){validate20.errors = [{instancePath:instancePath+"/chain/" + i2+"/agent_id",schemaPath:"#/properties/chain/items/properties/agent_id/type",keyword:"type",params:{type: "string"},message:"must be string"}];return false;}var valid8 = _errs63 === errors;}else {var valid8 = true;}if(valid8){if(data27.agent_type !== undefined){const _errs65 = errors;if(typeof data27.agent_type !== "string"){validate20.errors = [{instancePath:instancePath+"/chain/" + i2+"/agent_type",schemaPath:"#/properties/chain/items/properties/agent_type/type",keyword:"type",params:{type: "string"},message:"must be string"}];return false;}var valid8 = _errs65 === errors;}else {var valid8 = true;}if(valid8){if(data27.agent_fingerprint !== undefined){const _errs67 = errors;if(typeof data27.agent_fingerprint !== "string"){validate20.errors = [{instancePath:instancePath+"/chain/" + i2+"/agent_fingerprint",schemaPath:"#/properties/chain/items/properties/agent_fingerprint/type",keyword:"type",params:{type: "string"},message:"must be string"}];return false;}var valid8 = _errs67 === errors;}else {var valid8 = true;}if(valid8){if(data27.timestamp !== undefined){let data32 = data27.timestamp;const _errs69 = errors;if(!((typeof data32 == "number") && (!(data32 % 1) && !isNaN(data32)))){validate20.errors = [{instancePath:instancePath+"/chain/" + i2+"/timestamp",schemaPath:"#/properties/chain/items/properties/timestamp/type",keyword:"type",params:{type: "integer"},message:"must be integer"}];return false;}if(errors === _errs69){if(typeof data32 == "number"){if(data32 > 9007199254740991 || isNaN(data32)){validate20.errors = [{instancePath:instancePath+"/chain/" + i2+"/timestamp",schemaPath:"#/properties/chain/items/properties/timestamp/maximum",keyword:"maximum",params:{comparison: "<=", limit: 9007199254740991},message:"must be <= 9007199254740991"}];return false;}else {if(data32 < 0 || isNaN(data32)){validate20.errors = [{instancePath:instancePath+"/chain/" + i2+"/timestamp",schemaPath:"#/properties/chain/items/properties/timestamp/minimum",keyword:"minimum",params:{comparison: ">=", limit: 0},message:"must be >= 0"}];return false;}}}}var valid8 = _errs69 === errors;}else {var valid8 = true;}if(valid8){if(data27.action_summary !== undefined){const _errs71 = errors;if(typeof data27.action_summary !== "string"){validate20.errors = [{instancePath:instancePath+"/chain/" + i2+"/action_summary",schemaPath:"#/properties/chain/items/properties/action_summary/type",keyword:"type",params:{type: "string"},message:"must be string"}];return false;}var valid8 = _errs71 === errors;}else {var valid8 = true;}if(valid8){if(data27.parent_hop !== undefined){let data34 = data27.parent_hop;const _errs73 = errors;if(!((typeof data34 == "number") && (!(data34 % 1) && !isNaN(data34)))){validate20.errors = [{instancePath:instancePath+"/chain/" + i2+"/parent_hop",schemaPath:"#/properties/chain/items/properties/parent_hop/type",keyword:"type",params:{type: "integer"},message:"must be integer"}];return false;}if(errors === _errs73){if(typeof data34 == "number"){if(data34 > 9007199254740991 || isNaN(data34)){validate20.errors = [{instancePath:instancePath+"/chain/" + i2+"/parent_hop",schemaPath:"#/properties/chain/items/properties/parent_hop/maximum",keyword:"maximum",params:{comparison: "<=", limit: 9007199254740991},message:"must be <= 9007199254740991"}];return false;}else {if(data34 < 0 || isNaN(data34)){validate20.errors = [{instancePath:instancePath+"/chain/" + i2+"/parent_hop",schemaPath:"#/properties/chain/items/properties/parent_hop/minimum",keyword:"minimum",params:{comparison: ">=", limit: 0},message:"must be >= 0"}];return false;}}}}var valid8 = _errs73 === errors;}else {var valid8 = true;}if(valid8){if(data27.hop_signature !== undefined){let data35 = data27.hop_signature;const _errs75 = errors;if(errors === _errs75){if(typeof data35 === "string"){if(!pattern6.test(data35)){validate20.errors = [{instancePath:instancePath+"/chain/" + i2+"/hop_signature",schemaPath:"#/properties/chain/items/properties/hop_signature/pattern",keyword:"pattern",params:{pattern: "^[A-Za-z0-9_-]{86}$"},message:"must match pattern \""+"^[A-Za-z0-9_-]{86}$"+"\""}];return false;}}else {validate20.errors = [{instancePath:instancePath+"/chain/" + i2+"/hop_signature",schemaPath:"#/properties/chain/items/properties/hop_signature/type",keyword:"type",params:{type: "string"},message:"must be string"}];return false;}}var valid8 = _errs75 === errors;}else {var valid8 = true;}}}}}}}}}}else {validate20.errors = [{instancePath:instancePath+"/chain/" + i2,schemaPath:"#/properties/chain/items/type",keyword:"type",params:{type: "object"},message:"must be object"}];return false;}}var valid7 = _errs59 === errors;if(!valid7){break;}}}else {validate20.errors = [{instancePath:instancePath+"/chain",schemaPath:"#/properties/chain/type",keyword:"type",params:{type: "array"},message:"must be array"}];return false;}}var valid0 = _errs57 === errors;}else {var valid0 = true;}if(valid0){if(data.signature !== undefined){let data36 = data.signature;const _errs77 = errors;if(errors === _errs77){if(data36 && typeof data36 == "object" && !Array.isArray(data36)){let missing5;if((((data36.alg === undefined) && (missing5 = "alg")) || ((data36.kid === undefined) && (missing5 = "kid"))) || ((data36.value === undefined) && (missing5 = "value"))){validate20.errors = [{instancePath:instancePath+"/signature",schemaPath:"#/properties/signature/required",keyword:"required",params:{missingProperty: missing5},message:"must have required property '"+missing5+"'"}];return false;}else {if(data36.alg !== undefined){const _errs79 = errors;if(typeof data36.alg !== "string"){validate20.errors = [{instancePath:instancePath+"/signature/alg",schemaPath:"#/properties/signature/properties/alg/type",keyword:"type",params:{type: "string"},message:"must be string"}];return false;}var valid9 = _errs79 === errors;}else {var valid9 = true;}if(valid9){if(data36.kid !== undefined){let data38 = data36.kid;const _errs81 = errors;if(errors === _errs81){if(typeof data38 === "string"){if(func1(data38) < 1){validate20.errors = [{instancePath:instancePath+"/signature/kid",schemaPath:"#/properties/signature/properties/kid/minLength",keyword:"minLength",params:{limit: 1},message:"must NOT have fewer than 1 characters"}];return false;}}else {validate20.errors = [{instancePath:instancePath+"/signature/kid",schemaPath:"#/properties/signature/properties/kid/type",keyword:"type",params:{type: "string"},message:"must be string"}];return false;}}var valid9 = _errs81 === errors;}else {var valid9 = true;}if(valid9){if(data36.value !== undefined){let data39 = data36.value;const _errs83 = errors;if(errors === _errs83){if(typeof data39 === "string"){if(!pattern6.test(data39)){validate20.errors = [{instancePath:instancePath+"/signature/value",schemaPath:"#/properties/signature/properties/value/pattern",keyword:"pattern",params:{pattern: "^[A-Za-z0-9_-]{86}$"},message:"must match pattern \""+"^[A-Za-z0-9_-]{86}$"+"\""}];return false;}}else {validate20.errors = [{instancePath:instancePath+"/signature/value",schemaPath:"#/properties/signature/properties/value/type",keyword:"type",params:{type: "string"},message:"must be string"}];return false;}}var valid9 = _errs83 === errors;}else {var valid9 = true;}if(valid9){if(data36.signed_fields !== undefined){let data40 = data36.signed_fields;const _errs85 = errors;if(errors === _errs85){if(Array.isArray(data40)){if(data40.length > 3){validate20.errors = [{instancePath:instancePath+"/signature/signed_fields",schemaPath:"#/properties/signature/properties/signed_fields/maxItems",keyword:"maxItems",params:{limit: 3},message:"must NOT have more than 3 items"}];return false;}else {if(data40.length < 3){validate20.errors = [{instancePath:instancePath+"/signature/signed_fields",schemaPath:"#/properties/signature/properties/signed_fields/minItems",keyword:"minItems",params:{limit: 3},message:"must NOT have fewer than 3 items"}];return false;}else {const len3 = data40.length;if(len3 > 0){const _errs87 = errors;if("header" !== data40[0]){validate20.errors = [{instancePath:instancePath+"/signature/signed_fields/0",schemaPath:"#/properties/signature/properties/signed_fields/prefixItems/0/const",keyword:"const",params:{allowedValue: "header"},message:"must be equal to constant"}];return false;}var valid10 = _errs87 === errors;}if(valid10){if(len3 > 1){const _errs88 = errors;if("principal" !== data40[1]){validate20.errors = [{instancePath:instancePath+"/signature/signed_fields/1",schemaPath:"#/properties/signature/properties/signed_fields/prefixItems/1/const",keyword:"const",params:{allowedValue: "principal"},message:"must be equal to constant"}];return false;}var valid10 = _errs88 === errors;}if(valid10){if(len3 > 2){const _errs89 = errors;if("scope" !== data40[2]){validate20.errors = [{instancePath:instancePath+"/signature/signed_fields/2",schemaPath:"#/properties/signature/properties/signed_fields/prefixItems/2/const",keyword:"const",params:{allowedValue: "scope"},message:"must be equal to constant"}];return false;}var valid10 = _errs89 === errors;}}}}}}else {validate20.errors = [{instancePath:instancePath+"/signature/signed_fields",schemaPath:"#/properties/signature/properties/signed_fields/type",keyword:"type",params:{type: "array"},message:"must be array"}];return false;}}var valid9 = _errs85 === errors;}else {var valid9 = true;}}}}}}else {validate20.errors = [{instancePath:instancePath+"/signature",schemaPath:"#/properties/signature/type",keyword:"type",params:{type: "object"},message:"must be object"}];return false;}}var valid0 = _errs77 === errors;}else {var valid0 = true;}}}}}}}}}else {validate20.errors = [{instancePath,schemaPath:"#/type",keyword:"type",params:{type: "object"},message:"must be object"}];return false;}}validate20.errors = vErrors;return errors === 0;}validate20.evaluated = {"props":true,"dynamicProps":false,"dynamicItems":false}; diff --git a/src/schema/validator.ts b/src/schema/validator.ts index c7a5f79..9c3d6eb 100644 --- a/src/schema/validator.ts +++ b/src/schema/validator.ts @@ -1,17 +1,23 @@ -import Ajv from 'ajv/dist/2020.js' -import addFormats from 'ajv-formats' -import schema from './token.schema.json' +// The token schema validator is compiled at build time by +// scripts/build-validator.mjs (Ajv standalone code), not at load time. Compiling +// at load time needs runtime code generation, which Cloudflare Workers and +// strict Content-Security-Policy environments refuse, so the package would fail +// to load there. +import { validate, type ValidationError } from './validator.generated.js' import { HdpSchemaError } from '../types/errors.js' -const ajv = new Ajv({ strict: false }) -addFormats(ajv) -const validate = ajv.compile(schema) +// Reproduces Ajv's default errorsText() output ("data ", joined +// with ", "), so error messages are unchanged from the runtime-compiled +// validator. +function formatErrors(errors: ValidationError[] | null | undefined): string { + if (!errors || errors.length === 0) return 'No errors' + return errors.map((e) => `data${e.instancePath} ${e.message}`).join(', ') +} export function validateToken(token: unknown): void { const valid = validate(token) if (!valid) { - const msg = ajv.errorsText(validate.errors) - throw new HdpSchemaError(msg) + throw new HdpSchemaError(formatErrors(validate.errors)) } const candidate = token as { header: { issued_at: number; expires_at: number } } diff --git a/tests/unit/dist-no-codegen.test.ts b/tests/unit/dist-no-codegen.test.ts new file mode 100644 index 0000000..15fc08a --- /dev/null +++ b/tests/unit/dist-no-codegen.test.ts @@ -0,0 +1,67 @@ +// Strict runtimes (Cloudflare Workers, browser extensions, pages with a strict +// Content-Security-Policy) refuse to compile code from strings. Node's +// --disallow-code-generation-from-strings flag applies the same restriction, +// so loading the built package under it shows whether the package can run +// there at all. +// +// The test drives the published entry points in dist/, not src/, because the +// published bundle is what strict runtimes load. It is skipped when dist/ is +// absent; CI builds before testing. + +import { describe, it, expect } from 'vitest' +import { spawnSync } from 'node:child_process' +import { existsSync } from 'node:fs' +import { resolve } from 'node:path' + +const root = resolve(__dirname, '../..') +const distCjs = resolve(root, 'dist/index.js') +const distEsm = resolve(root, 'dist/index.mjs') +const hasDist = existsSync(distCjs) && existsSync(distEsm) + +// Issue a token and verify it, end to end, so the schema validator runs. +const roundTrip = (load: string) => ` + ${load} + ;(async () => { + const { privateKey, publicKey } = await hdp.generateKeyPair() + const token = await hdp.issueToken({ + sessionId: 'sess-strict', + principal: { id: 'usr_strict', id_type: 'opaque' }, + scope: { intent: 'strict runtime check', data_classification: 'public', network_egress: false, persistence: false }, + signingKey: privateKey, + keyId: 'strict-key', + }) + const result = await hdp.verifyToken(token, { publicKey }) + if (!result.valid) throw new Error('round trip did not verify') + let rejected = false + try { hdp.validateToken({ hdp: '0.1' }) } catch (e) { rejected = !!e && e.constructor.name === 'HdpSchemaError' } + if (!rejected) throw new Error('invalid token was not rejected by the schema validator') + console.log('ok') + })().catch((e) => { console.error(e && e.message); process.exit(1) }) +` + +function runStrict(args: string[], code: string) { + return spawnSync( + process.execPath, + ['--disallow-code-generation-from-strings', ...args, code], + { cwd: root, encoding: 'utf8' }, + ) +} + +describe.skipIf(!hasDist)('built package under --disallow-code-generation-from-strings', () => { + it('CommonJS entry loads, issues, verifies, and rejects an invalid token', () => { + const r = runStrict(['-e'], roundTrip(`const hdp = require(${JSON.stringify(distCjs)})`)) + expect(r.stderr).toBe('') + expect(r.stdout.trim()).toBe('ok') + expect(r.status).toBe(0) + }) + + it('ESM entry loads, issues, verifies, and rejects an invalid token', () => { + const r = runStrict( + ['--input-type=module', '-e'], + roundTrip(`const hdp = await import(${JSON.stringify('file://' + distEsm)})`), + ) + expect(r.stderr).toBe('') + expect(r.stdout.trim()).toBe('ok') + expect(r.status).toBe(0) + }) +}) diff --git a/tests/unit/schema-standalone.test.ts b/tests/unit/schema-standalone.test.ts new file mode 100644 index 0000000..a484cbf --- /dev/null +++ b/tests/unit/schema-standalone.test.ts @@ -0,0 +1,22 @@ +// The token schema validator is generated at build time +// (scripts/build-validator.mjs) and committed. This test fails when the +// committed file no longer matches what the generator produces from the +// current schema, for example after an edit to token.schema.json without +// re-running `npm run build:validator`. + +import { describe, it, expect } from 'vitest' +import { readFileSync } from 'node:fs' +import { resolve } from 'node:path' +// @ts-expect-error: plain ESM build script without type declarations +import { generate, OUTPUT_PATH } from '../../scripts/build-validator.mjs' + +describe('generated token schema validator', () => { + it('matches the generator output for the current schema', () => { + const committed = readFileSync(OUTPUT_PATH as string, 'utf8') + expect(committed).toBe((generate as () => string)()) + }) + + it('is written to src/schema/validator.generated.js', () => { + expect(OUTPUT_PATH).toBe(resolve(__dirname, '../../src/schema/validator.generated.js')) + }) +})