Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 6 additions & 3 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
20 changes: 13 additions & 7 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

8 changes: 5 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
@@ -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",
Expand All @@ -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",
Expand All @@ -37,15 +39,15 @@
"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"
},
"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"
Expand Down
2 changes: 1 addition & 1 deletion packages/hdp-autogen-ts/package.json
Original file line number Diff line number Diff line change
@@ -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",
Expand Down
2 changes: 1 addition & 1 deletion packages/hdp-cli/package.json
Original file line number Diff line number Diff line change
@@ -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": {
Expand Down
2 changes: 1 addition & 1 deletion packages/hdp-mcp/package.json
Original file line number Diff line number Diff line change
@@ -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",
Expand Down
52 changes: 52 additions & 0 deletions scripts/build-validator.mjs
Original file line number Diff line number Diff line change
@@ -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)
}
19 changes: 19 additions & 0 deletions src/schema/validator.generated.d.ts
Original file line number Diff line number Diff line change
@@ -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<string, unknown>
message?: string
}

export interface ValidateFunction {
(data: unknown): boolean
errors?: ValidationError[] | null
}

export declare const validate: ValidateFunction
declare const _default: ValidateFunction
export default _default
5 changes: 5 additions & 0 deletions src/schema/validator.generated.js

Large diffs are not rendered by default.

22 changes: 14 additions & 8 deletions src/schema/validator.ts
Original file line number Diff line number Diff line change
@@ -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<path> <message>", 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 } }
Expand Down
67 changes: 67 additions & 0 deletions tests/unit/dist-no-codegen.test.ts
Original file line number Diff line number Diff line change
@@ -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)
})
})
22 changes: 22 additions & 0 deletions tests/unit/schema-standalone.test.ts
Original file line number Diff line number Diff line change
@@ -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'))
})
})
Loading