From 9b665ec5634f0468c3ca96daf68e4bfc4279f99c Mon Sep 17 00:00:00 2001 From: Brian O'Kelley Date: Mon, 14 Sep 2026 14:53:21 +0000 Subject: [PATCH] feat(negotiation): complete schema-derived proposal verification --- .../proposal-verifier-schema-contracts.md | 7 + docs/guides/BUYER-QUICKSTART-3.2.md | 5 + docs/guides/PROPOSAL-TERMS-VERIFICATION.md | 153 +++++ docs/llms.txt | 2 + docs/migration-adcp-3.1-to-3.2-proposals.md | 5 + package.json | 13 + scripts/check-package-size.mjs | 4 +- scripts/generate-agent-docs.ts | 4 + scripts/verify-package.mjs | 2 + .../negotiation/commercial-terms-keywords.ts | 115 ++++ .../negotiation/commercial-terms-schema.ts | 227 +++++++ .../negotiation/commercial-terms-semantics.ts | 130 ++++ src/lib/negotiation/verification.ts | 208 +++--- src/lib/validation/schema-loader.ts | 69 +- .../proposal-commercial-terms/README.md | 19 + .../beta8-schema.json.gz | Bin 0 -> 35730 bytes .../proposal-commercial-terms/beta8.json | 36 ++ .../proposal-commercial-terms/current.json | 109 ++++ .../rc3-product-purchase-validation.json | 9 + test/lib/proposal-commercial-terms.test.js | 606 ++++++++++++++++++ .../proposal-negotiation-validation.test.js | 37 +- 21 files changed, 1592 insertions(+), 168 deletions(-) create mode 100644 .changeset/proposal-verifier-schema-contracts.md create mode 100644 docs/guides/PROPOSAL-TERMS-VERIFICATION.md create mode 100644 src/lib/negotiation/commercial-terms-keywords.ts create mode 100644 src/lib/negotiation/commercial-terms-schema.ts create mode 100644 src/lib/negotiation/commercial-terms-semantics.ts create mode 100644 test/fixtures/proposal-commercial-terms/README.md create mode 100644 test/fixtures/proposal-commercial-terms/beta8-schema.json.gz create mode 100644 test/fixtures/proposal-commercial-terms/beta8.json create mode 100644 test/fixtures/proposal-commercial-terms/current.json create mode 100644 test/fixtures/proposal-commercial-terms/rc3-product-purchase-validation.json create mode 100644 test/lib/proposal-commercial-terms.test.js diff --git a/.changeset/proposal-verifier-schema-contracts.md b/.changeset/proposal-verifier-schema-contracts.md new file mode 100644 index 000000000..afb01a179 --- /dev/null +++ b/.changeset/proposal-verifier-schema-contracts.md @@ -0,0 +1,7 @@ +--- +'@adcp/sdk': minor +--- + +Expose the standalone proposal commercial-terms verifier through `@adcp/sdk/negotiation/verification` with ESM/CJS types. Fail closed on unsupported schema keywords, cross-bundle references, and changed validation contracts throughout the commercial-terms schema graph. Preserve digest-first exhaustive comparison and legacy opaque contract-reference behavior, and document runtime schema coupling and upstream shim retirement. + +Enforce schema-declared targeting disjointness, geographic label membership, language-tag grammar, and IANA timezone annotations before comparing terms, with validators isolated from ordinary SDK schema validation. Pin extensible-enum annotations while preserving explicit enum membership for binding snapshots. diff --git a/docs/guides/BUYER-QUICKSTART-3.2.md b/docs/guides/BUYER-QUICKSTART-3.2.md index dd26f2788..2bea3b80f 100644 --- a/docs/guides/BUYER-QUICKSTART-3.2.md +++ b/docs/guides/BUYER-QUICKSTART-3.2.md @@ -106,5 +106,10 @@ request_proposals → refine_proposals → accept_proposal those values locally. See the [type summary](../TYPE-SUMMARY.md#request_proposals) for exact request shapes. +Before acceptance, compare the complete reviewed commercial snapshot with +`verifyProposalCommercialTerms` from `@adcp/sdk/negotiation/verification`. +See [proposal term verification](./PROPOSAL-TERMS-VERIFICATION.md) for digest +integrity, schema-version selection, and typed mismatch paths. + For compatibility behavior with AdCP 3.0/3.1 sellers, see [Media-buy 3.2 compatibility](./MEDIA-BUY-3.2-COMPATIBILITY.md). diff --git a/docs/guides/PROPOSAL-TERMS-VERIFICATION.md b/docs/guides/PROPOSAL-TERMS-VERIFICATION.md new file mode 100644 index 000000000..2f999dd67 --- /dev/null +++ b/docs/guides/PROPOSAL-TERMS-VERIFICATION.md @@ -0,0 +1,153 @@ +# Verify proposal terms before acceptance + +Use the standalone buyer API to compare a seller's proposal with the **complete +commercial terms the buyer reviewed**. The existing root exports remain available. + +```ts +import { + verifyProposalCommercialTerms, + assertProposalCommercialTerms, + type ProposalCommercialTermsMismatch, +} from '@adcp/sdk/negotiation/verification'; + +const result = verifyProposalCommercialTerms(proposal, reviewedCommercialTerms, { + adcpVersion: sellerAdcpVersion, // seller-served release; defaults to the SDK schema pin +}); +if (!result.ok) { + for (const mismatch of result.mismatches) { + console.error(mismatch.kind, mismatch.path, mismatch.message); + } + // Stop acceptance, including when result.truncated is true. +} else { + // Continue the buyer's status, expiry, governance, and acceptance checks. +} + +// Alternatively, throws ProposalCommercialTermsVerificationError on failure. +assertProposalCommercialTerms(proposal, reviewedCommercialTerms, { + adcpVersion: sellerAdcpVersion, +}); +``` + +This is a synchronous, tree-shakeable **Node.js** entry point with ESM and CJS +declarations. It loads local schema bundles and uses Node crypto. It neither +constructs a protocol client nor contacts an agent or a contract URL. Browser +applications should perform this verification in their buyer backend; this entry +does not bundle Node polyfills or a browser schema store. + +## Verification order and mismatch paths + +The verifier first bounds the supplied JSON tree, then verifies `terms_digest` +against `sha256:` plus base64url SHA-256 of RFC 8785 JCS `commercial_terms`. +A digest failure returns only `digest_mismatch` at `/terms_digest`, before reading +the selected schema or the expected terms. This checks content integrity; a +matching digest by itself does not mean the buyer agreed to the contents. + +Both complete snapshots must satisfy the same schema. The comparison includes +every admitted value recursively: price, currency, aggregate and purchase flights, +purchases, budgets, change rights, status scope, service modes, SLA, opaque +conditions, contract pointers, and nested extension data. Object key order is +irrelevant. Array order and the difference between absence and presence remain +binding. Schema errors return `invalid_terms` with the affected subject; comparisons +return `missing`, `unexpected`, or `changed` with RFC 6901 JSON Pointers such as +`/commercial_terms/purchases/0/pricing/fixed_price`. Pointers escape `/` as `~1` +and `~` as `~0`. Diagnostics omit field values and are bounded; paths preserve +property names. Schema-support failures identify the affected schema location. + +Package IDs assigned during execution are outside the commercial envelope. The +canonical schema uses ordered `purchases`; the verifier does not silently turn a +legacy `packages` array into purchases. Narrative, allocation, and display fields +outside `commercial_terms` cannot substitute for the reviewed snapshot. + +## Runtime schema coupling and additions + +The comparison shape comes from the selected bundle's +`media-buy/commercial-terms.json` and its references, including `patternProperties` +and open extension objects. There is no SDK binding-field list. A new optional +field requires both an installed matching schema and an explicitly reviewed +snapshot containing that field; otherwise verification fails. An equal unknown +field outside the selected schema fails too. Never build the expected snapshot by +blindly copying the unreviewed candidate. + +For binding snapshots, enum values must be listed in the selected schema even +when taxonomy annotations advertise extensibility. `x-extensible` and `x-pattern` +do not relax this conservative pre-acceptance policy; changed annotations require +review. An unknown industry value therefore needs an updated matching enum bundle. + +Unknown schema keywords, a different schema dialect, cross-bundle references, and +changed `x-adcp-validation` contracts return `unsupported_schema`, even for equal +snapshots. The reviewed semantic annotations in +`src/lib/negotiation/commercial-terms-semantics.ts` are deliberately separate from +the runtime field shape. Explanatory `description` and `spec` metadata may change; +normative rule values, including prose inside `verifier_constraints`, require +review. Historical omissions are recorded in release-scoped semantic profiles. +On a schema upgrade, audit new annotations and implement +any required pre-acceptance behavior before updating that semantic support record. +Pricing integrity and portable change-term consistency checks run before the diff. +Schema-selected checks also reject contradictory place/region targeting, place +labels without a matching identifier, malformed language tags, and timezones +absent from the runtime's IANA database where the schema declares that check. +Bare string fields such as `budget_cap_timezone` receive only their schema-declared +validation. These checks run only on the applicable schema +branch; an `inventory_local` daypart remains valid. These specialized validators +are cached separately from ordinary SDK schema validators. +Preserving an opaque condition or contract pointer does not evaluate that +condition, resolve the contract, or grant permission to execute an action. + +Pass the seller-served release. Full prerelease pins remain exact; release-precision +pins such as `3.2-rc.2` resolve to their installed bundle. Stable patch selection +follows the SDK loader's minor-line compatibility rules. `schemaVersion` records +the actual selected release. Missing bundles return `schema_unavailable`. There is +no network fallback, downgrade, field stripping, or automatic version projection. +External roots must retain the reviewed semantic graph. Canonical root-relative +schema IDs work, as do `latest` IDs when a matching root `index.json` pins the release. +Schema documents and support audits are cached together with validator state. +Treat an active schema root as immutable; registering a replacement root or +restarting the application refreshes all three. Timezone and language checks +use the runtime's ICU data; Python implementations should test against their +supported locale and timezone databases as well as the portable fixtures. +Use the same module format for external-root registration and verification: +the SDK's ESM and CJS module graphs maintain separate loader state. +The bundle must have unambiguous schema identities throughout its registered +documents; identical published mirrors are allowed, conflicting definitions fail closed. + +The reviewed rc.3 semantic profile removes the direct `buy_products` offer-matching +annotation from product purchases while retaining accepted-snapshot preservation +and pricing identity. That change is scoped to the exact rc.3 release; it does not +weaken the rc.2 contract or automatically approve future annotation changes. + +The released `3.2.0-beta.8` bundle has commercial terms but no `change_terms`; +it rejects that later field. The pinned 3.1 bundle has no canonical commercial +envelope and returns `schema_unavailable`. Existing 3.1 action readers continue +to treat `available_actions[].terms_ref` as opaque. A proposal's +`change_terms[].terms_ref` is a contract reference and may differ from `term_id`. +Only a live 3.2 action carrying `change_term_id` and its compatibility `terms_ref` +alias has an equality obligation. Joining those actions to accepted terms belongs +to Part A of [#2664](https://github.com/adcontextprotocol/adcp-client/issues/2664); +this pre-acceptance API does not infer that join or grant authority from a legacy +pointer that happens to resemble a term ID. + +## Upstream coordination and Python parity + +The initial Part B implementation landed in SDK +[#2757](https://github.com/adcontextprotocol/adcp-client/pull/2757). Upstream +[`adcp#6794`](https://github.com/adcontextprotocol/adcp/pull/6794), implementing RFC +[#6750](https://github.com/adcontextprotocol/adcp/issues/6750), temporarily patched +the installed SDK's `dist/lib/negotiation/verification.{js,mjs}` allowlist in +`scripts/overlay-compliance-cache.sh` to admit `change_terms`. + +That coordination is already complete: +[`adcp#7018`](https://github.com/adcontextprotocol/adcp/pull/7018) upgraded to +`@adcp/sdk@14.0.0-beta.16`, deleted the overlay, and switched storyboard runs to +public `schemaRoot`/`complianceDir` options. Current upstream pins SDK rc.35. +No companion patch-removal PR remains necessary. When upstream consumes this +hardening, update its SDK pin and lockfile together and run `test:sdk-shims` plus +the current and frozen compatibility storyboard matrices; do not restore a dist +patch to bypass an unsupported semantic contract. + +Python tracking remains +[`adcp-client-python#1067`](https://github.com/adcontextprotocol/adcp-client-python/issues/1067). +Parity requires digest-first rejection, complete schema-admitted comparison, +ordered-array behavior, precise escaped pointers, failure on unreviewed schema +semantics, and the same absence/opaque-reference/version behavior. The fixtures +under `test/fixtures/proposal-commercial-terms` are portable JSON. Part A's unified +action assessment and seller resolver remain separate work. diff --git a/docs/llms.txt b/docs/llms.txt index 0aa6d6600..dca24913b 100644 --- a/docs/llms.txt +++ b/docs/llms.txt @@ -18,6 +18,7 @@ SDK 14 requires Node.js `^20.19.0 || >=22.12.0`; install the newest v14 prerelea SDK 14 is compact-lifecycle first: `list_products → buy_products → control_media_buy`, with `request_proposals → refine_proposals → accept_proposal` when terms need negotiation. - **Buyer** (calling a seller): read `docs/guides/BUYER-QUICKSTART-3.2.md` first. +- **Before proposal acceptance:** use `verifyProposalCommercialTerms` from `@adcp/sdk/negotiation/verification` with a complete, independently reviewed snapshot and the seller-served schema version. Never use an unreviewed candidate as its own expected terms. See `docs/guides/PROPOSAL-TERMS-VERIFICATION.md`. - **Seller** (implementing an agent that others call): read `docs/guides/SELLER-QUICKSTART-3.2.md` first, then `docs/guides/BUILD-AN-AGENT.md` for the complete framework surface. - **Upgrading an existing application:** read `docs/migration-13-to-14.md`; established 3.0/3.1 tools remain supported as an explicit compatibility path. @@ -2079,6 +2080,7 @@ These docs are available locally in the repo and hosted at https://adcontextprot |------|-----------|--------| | Full type signatures | docs/TYPE-SUMMARY.md | [link](https://adcontextprotocol.github.io/adcp-client/TYPE-SUMMARY.md) | | Buyer quick start (AdCP 3.2) | docs/guides/BUYER-QUICKSTART-3.2.md | [link](https://adcontextprotocol.github.io/adcp-client/guides/BUYER-QUICKSTART-3.2.md) | +| Verify proposal terms before acceptance | docs/guides/PROPOSAL-TERMS-VERIFICATION.md | [link](https://adcontextprotocol.github.io/adcp-client/guides/PROPOSAL-TERMS-VERIFICATION.md) | | Seller quick start (AdCP 3.2) | docs/guides/SELLER-QUICKSTART-3.2.md | [link](https://adcontextprotocol.github.io/adcp-client/guides/SELLER-QUICKSTART-3.2.md) | | Production durability checklist | docs/guides/PRODUCTION-DURABILITY.md | [link](https://adcontextprotocol.github.io/adcp-client/guides/PRODUCTION-DURABILITY.md) | | Persistent notification subscriptions | docs/guides/PERSISTENT-NOTIFICATION-RUNTIME.md | [link](https://adcontextprotocol.github.io/adcp-client/guides/PERSISTENT-NOTIFICATION-RUNTIME.md) | diff --git a/docs/migration-adcp-3.1-to-3.2-proposals.md b/docs/migration-adcp-3.1-to-3.2-proposals.md index 40b7bc40c..abe06e8bd 100644 --- a/docs/migration-adcp-3.1-to-3.2-proposals.md +++ b/docs/migration-adcp-3.1-to-3.2-proposals.md @@ -30,6 +30,11 @@ Pass the result through `unwrapVerifiedRefineProposals(result, request)` or use Exact transport retries reuse the same request and key. A changed refinement is a new intent and must use a fresh key; `ProposalNegotiator.changedRequest()` enforces that split. Check the committed proposal's `expires_at` immediately before `accept_proposal`/`buy_products`. +Use the standalone `verifyProposalCommercialTerms` API to compare the complete +buyer-reviewed commercial snapshot before acceptance. See +[proposal term verification](./guides/PROPOSAL-TERMS-VERIFICATION.md) for the +schema-version coupling and preservation of legacy opaque contract references. + If `lifecycle_tools` omits `refine_proposals`, translate supported requests to the legacy `get_products({ buying_mode: 'refine', refine: [...] })` flow. Free-text `ask` maps to the legacy proposal ask. Product include/omit actions map directly. Hard constraints require explicit adapter policy: legacy discovery cannot guarantee the 3.2 hard-constraint semantics, so verify the returned proposal locally or report the dimension as unsupported. When that fallback sends a proposal refinement with `action: 'finalize'`, it diff --git a/package.json b/package.json index e98f90d88..75ab34d72 100644 --- a/package.json +++ b/package.json @@ -366,6 +366,16 @@ "default": "./dist/lib/reporting/ledger/index.js" } }, + "./negotiation/verification": { + "import": { + "types": "./dist/lib/negotiation/verification.d.mts", + "default": "./dist/lib/negotiation/verification.mjs" + }, + "require": { + "types": "./dist/lib/negotiation/verification.d.ts", + "default": "./dist/lib/negotiation/verification.js" + } + }, "./package.json": "./package.json" }, "typesVersions": { @@ -474,6 +484,9 @@ ], "types/*": [ "dist/lib/types/*.d.ts" + ], + "negotiation/verification": [ + "dist/lib/negotiation/verification.d.ts" ] } }, diff --git a/scripts/check-package-size.mjs b/scripts/check-package-size.mjs index fb9fdcda8..3d3e667b2 100644 --- a/scripts/check-package-size.mjs +++ b/scripts/check-package-size.mjs @@ -27,7 +27,9 @@ const MAX_UNPACKED_PACKAGE_BYTES = 120 * 1024 * 1024; // cross-SDK consumer-status vector adds one published JSON artifact. // Account-feed adoption adds five runtime/declaration module sets (20 files) // and one migration guide. Byte budgets remain unchanged. -const MAX_PACKED_FILE_COUNT = 6_016; +// The standalone proposal verifier adds twelve helper module artifacts and +// one buyer guide; byte budgets remain unchanged. +const MAX_PACKED_FILE_COUNT = 6_029; const MAX_BUNDLED_SCHEMA_BYTES = 1280 * 1024; const MAX_CJS_SCHEMA_DECLARATION_BYTES = 45 * 1024 * 1024; const MAX_ESM_SCHEMA_FACADE_BYTES = 1024; diff --git a/scripts/generate-agent-docs.ts b/scripts/generate-agent-docs.ts index 2c28bc750..58f716c0d 100644 --- a/scripts/generate-agent-docs.ts +++ b/scripts/generate-agent-docs.ts @@ -615,6 +615,9 @@ function generateLlmsTxt( ); ln(); ln(`- **Buyer** (calling a seller): read \`docs/guides/BUYER-QUICKSTART-3.2.md\` first.`); + ln( + `- **Before proposal acceptance:** use \`verifyProposalCommercialTerms\` from \`@adcp/sdk/negotiation/verification\` with a complete, independently reviewed snapshot and the seller-served schema version. Never use an unreviewed candidate as its own expected terms. See \`docs/guides/PROPOSAL-TERMS-VERIFICATION.md\`.` + ); ln( `- **Seller** (implementing an agent that others call): read \`docs/guides/SELLER-QUICKSTART-3.2.md\` first, then \`docs/guides/BUILD-AN-AGENT.md\` for the complete framework surface.` ); @@ -1287,6 +1290,7 @@ function generateLlmsTxt( const docLinks: [string, string][] = [ ['Full type signatures', 'TYPE-SUMMARY.md'], ['Buyer quick start (AdCP 3.2)', 'guides/BUYER-QUICKSTART-3.2.md'], + ['Verify proposal terms before acceptance', 'guides/PROPOSAL-TERMS-VERIFICATION.md'], ['Seller quick start (AdCP 3.2)', 'guides/SELLER-QUICKSTART-3.2.md'], ['Production durability checklist', 'guides/PRODUCTION-DURABILITY.md'], ['Persistent notification subscriptions', 'guides/PERSISTENT-NOTIFICATION-RUNTIME.md'], diff --git a/scripts/verify-package.mjs b/scripts/verify-package.mjs index fac68a1a1..f8901a922 100644 --- a/scripts/verify-package.mjs +++ b/scripts/verify-package.mjs @@ -141,6 +141,7 @@ try { 'package/docs/migration-12-to-14.md', 'package/docs/migration-13-to-14.md', 'package/docs/migration-12-to-13.md', + 'package/docs/guides/PROPOSAL-TERMS-VERIFICATION.md', 'package/MIGRATION-v8.md', ]; for (const guide of requiredGuides) { @@ -268,6 +269,7 @@ try { { specifier: '@adcp/sdk/server', symbol: 'A2AInvocationError' }, { specifier: '@adcp/sdk/signing/server', symbol: 'resolveAgent' }, { specifier: '@adcp/sdk/testing', symbol: 'mergeSeedProductLegacy' }, + { specifier: '@adcp/sdk/negotiation/verification', symbol: 'verifyProposalCommercialTerms' }, { specifier: '@adcp/sdk/schemas', symbol: 'CreativeAssetSchema' }, ]; diff --git a/src/lib/negotiation/commercial-terms-keywords.ts b/src/lib/negotiation/commercial-terms-keywords.ts new file mode 100644 index 000000000..67cb07cff --- /dev/null +++ b/src/lib/negotiation/commercial-terms-keywords.ts @@ -0,0 +1,115 @@ +import type { ErrorObject, FuncKeywordDefinition, KeywordDefinition } from 'ajv'; +import { canonicalize } from '../utils/jcs'; + +type RecordValue = Record; +function record(value: unknown): value is RecordValue { + return value !== null && typeof value === 'object' && !Array.isArray(value); +} +function pointer(value: string): string { + return value.replaceAll('~', '~0').replaceAll('/', '~1'); +} + +// The schema support audit runs first. This keyword therefore sees only the +// reviewed contracts, on the actual schema-selected branch and instance path. +// Pricing and change-right cross-purchase checks remain in verification.ts. +function validate( + metadata: RecordValue, + data: unknown, + _schema?: unknown, + context?: { instancePath: string; parentData?: unknown } +): boolean { + validate.errors = undefined; + function fail(suffix: string, message: string): false { + validate.errors = [ + { + keyword: 'x-adcp-validation', + instancePath: `${context?.instancePath ?? ''}${suffix}`, + schemaPath: '', + params: {}, + message, + }, + ]; + return false; + } + if (record(metadata.disjoint_place_fields) && record(data)) { + const { include, exclude, identity } = metadata.disjoint_place_fields; + if (typeof include === 'string' && typeof exclude === 'string' && Array.isArray(identity)) { + const included = new Set(); + const includedAreas = data[include]; + const excludedAreas = data[exclude]; + const key = (area: RecordValue, value: unknown) => + canonicalize(identity.map(field => (field === 'value' ? value : (area[String(field)] ?? null)))); + if (Array.isArray(includedAreas)) { + for (const area of includedAreas) { + if (record(area) && Array.isArray(area.values)) { + for (const value of area.values) included.add(key(area, value)); + } + } + } + if (Array.isArray(excludedAreas)) { + for (const [index, area] of excludedAreas.entries()) { + if (record(area) && Array.isArray(area.values)) { + for (const [valueIndex, value] of area.values.entries()) { + if (included.has(key(area, value))) + return fail( + `/${pointer(exclude)}/${index}/values/${valueIndex}`, + 'included and excluded place identities must be disjoint' + ); + } + } + } + } + } + } + if (typeof metadata.disjoint_with === 'string' && Array.isArray(data) && record(context?.parentData)) { + const included = context.parentData[metadata.disjoint_with]; + if (Array.isArray(included)) { + const keys = new Set(included.map(value => canonicalize(value))); + const overlap = data.findIndex(value => keys.has(canonicalize(value))); + if (overlap !== -1) return fail(`/${overlap}`, 'included and excluded regions must be disjoint'); + } + } + if (record(metadata.map_keys_subset_of_array) && record(data)) { + const { map_field, array_field } = metadata.map_keys_subset_of_array; + if (typeof map_field === 'string' && typeof array_field === 'string') { + const labels = data[map_field]; + const values = data[array_field]; + if (record(labels) && Array.isArray(values)) { + const keys = new Set(values); + for (const key of Object.keys(labels)) { + if (!keys.has(key)) + return fail(`/${pointer(map_field)}/${pointer(key)}`, 'label keys must identify a declared value'); + } + } + } + } + if (metadata.iana_timezone !== undefined && typeof data === 'string') { + try { + new Intl.DateTimeFormat('en', { timeZone: data }); + } catch { + return fail('', 'timezone must resolve in the runtime IANA timezone database'); + } + } + if ( + record(metadata.verifier_constraints) && + metadata.verifier_constraints.well_formed === 'rfc5646' && + typeof data === 'string' + ) { + // AJV enforces the AdCP casing/extension pattern. Intl additionally rejects + // duplicate variants and extension singletons. Private-use-only tags are + // valid RFC 5646 but intentionally unsupported by Intl's locale API. + if (!/^x(?:-[a-z0-9]{1,8})+$/.test(data)) { + try { + Intl.getCanonicalLocales(data); + } catch { + return fail('', 'language tag must satisfy RFC 5646 grammar'); + } + } + } + return true; +} +validate.errors = undefined as ErrorObject[] | undefined; + +export const COMMERCIAL_TERMS_KEYWORDS: ReadonlyArray = Object.freeze([ + Object.freeze({ keyword: 'x-adcp-validation', schemaType: 'object', errors: true, validate }), +]); diff --git a/src/lib/negotiation/commercial-terms-schema.ts b/src/lib/negotiation/commercial-terms-schema.ts new file mode 100644 index 000000000..169637c83 --- /dev/null +++ b/src/lib/negotiation/commercial-terms-schema.ts @@ -0,0 +1,227 @@ +import { canonicalize } from '../utils/jcs'; +import { + ABSENT_COMMERCIAL_CONTRACTS_BY_RELEASE, + REVIEWED_COMMERCIAL_TERMS_SEMANTICS, + REVIEWED_COMMERCIAL_ENUM_ANNOTATIONS, + COMMERCIAL_SEMANTIC_OVERRIDES_BY_RELEASE, +} from './commercial-terms-semantics'; +import { fullFormats } from 'ajv-formats/dist/formats.js'; +import { toReleasePrecisionWire } from '../validation/schema-loader'; + +type Schema = Readonly>; + +// JSON Schema Draft-07 vocabulary and reviewed annotation-only keywords. +// This is intentionally a schema-language list, never a commercial-field list. +const KEYWORDS = new Set([ + '$id', + '$ref', + '$schema', + '$comment', + 'title', + 'description', + 'default', + 'examples', + 'type', + 'enum', + 'const', + 'multipleOf', + 'maximum', + 'exclusiveMaximum', + 'minimum', + 'exclusiveMinimum', + 'maxLength', + 'minLength', + 'pattern', + 'format', + 'items', + 'additionalItems', + 'maxItems', + 'minItems', + 'uniqueItems', + 'contains', + 'maxProperties', + 'minProperties', + 'required', + 'properties', + 'patternProperties', + 'additionalProperties', + 'dependencies', + 'propertyNames', + 'if', + 'then', + 'else', + 'allOf', + 'anyOf', + 'oneOf', + 'not', + 'definitions', + 'readOnly', + 'writeOnly', + 'contentMediaType', + 'contentEncoding', + 'deprecated', + 'discriminator', + 'enumDescriptions', + 'x-adcp-schema-uri', + 'x-adcp-validation', + 'x-added-in', + 'x-entity', + 'x-extensible', + 'x-pattern', + 'x-status', +]); + +/** Audit the whole reachable schema before trusting AJV's permissive compilation. */ +export function commercialTermsSchemaSupportError( + schema: Schema, + version: string, + load: (ref: string) => Schema | undefined +): string | undefined { + const rootRef = 'media-buy/commercial-terms.json'; + if (typeof schema.$id !== 'string') return 'commercial-terms schema must declare its identity'; + const rootId = new URL(schema.$id, 'https://adcontextprotocol.org'); + if ( + rootId.origin !== 'https://adcontextprotocol.org' || + rootId.hash || + rootId.search || + !/^\/schemas\/[^/]+\/media-buy\/commercial-terms\.json$/.test(rootId.pathname) + ) + return 'unsupported commercial-terms schema identity'; + const prefix = rootId.href.slice(0, -rootRef.length); + const declaredVersion = rootId.pathname.match(/\/schemas\/([^/]+)\//)![1]!; + const schemaVersion = declaredVersion === 'latest' ? load('index.json')?.adcp_version : declaredVersion; + if (typeof schemaVersion !== 'string') return 'latest schema identities require a release-pinned bundle index'; + if (schemaVersion !== version && toReleasePrecisionWire(schemaVersion) !== version) { + return 'commercial-terms schema identity does not match the selected release'; + } + const reviewedSemantics = { + ...REVIEWED_COMMERCIAL_TERMS_SEMANTICS, + ...(Object.hasOwn(COMMERCIAL_SEMANTIC_OVERRIDES_BY_RELEASE, schemaVersion) + ? COMMERCIAL_SEMANTIC_OVERRIDES_BY_RELEASE[schemaVersion] + : {}), + }; + const seen = new Set(); + const locations = new Set(); + + function failure(message: string, location: string): string { + return `${message} at ${Array.from(location).slice(0, 256).join('')}`; + } + + function contract(value: unknown): string { + // Explanatory metadata is not a verifier rule. Prose inside an actual + // verifier_constraints value remains normative and requires review. + if (value && typeof value === 'object' && !Array.isArray(value)) { + return canonicalize( + Object.fromEntries(Object.entries(value).filter(([key]) => key !== 'description' && key !== 'spec')) + ); + } + return canonicalize(value); + } + + function visit(node: unknown, location: string, document: string): string | undefined { + locations.add(location); + if (typeof node === 'boolean') { + return !Object.hasOwn(reviewedSemantics, location) && + !Object.hasOwn(REVIEWED_COMMERCIAL_ENUM_ANNOTATIONS, location) + ? undefined + : failure('removed commercial-term validation semantics', location); + } + if (!node || typeof node !== 'object' || Array.isArray(node)) return failure('invalid schema node', location); + const value = node as Schema; + const unknownKeyword = Object.keys(value).find(key => !KEYWORDS.has(key)); + if (unknownKeyword !== undefined) return failure('unsupported schema keyword', `${location}/${unknownKeyword}`); + if (value.format !== undefined && (typeof value.format !== 'string' || !Object.hasOwn(fullFormats, value.format))) { + return failure('unsupported schema format', `${location}/format`); + } + if (value.$schema !== undefined && value.$schema !== 'http://json-schema.org/draft-07/schema#') { + return failure('unsupported schema dialect', `${location}/$schema`); + } + if ( + value.$id !== undefined && + (typeof value.$id !== 'string' || new URL(value.$id, `${prefix}${document}`).href !== `${prefix}${document}`) + ) + return failure('schema identity does not match the selected bundle', `${location}/$id`); + const semantics = value['x-adcp-validation']; + const reviewed = Object.hasOwn(reviewedSemantics, location) ? reviewedSemantics[location] : undefined; + if (semantics !== undefined || reviewed !== undefined) { + if (semantics === undefined || reviewed === undefined || contract(semantics) !== contract(reviewed)) { + return failure('unreviewed commercial-term validation semantics', `${location}/x-adcp-validation`); + } + } + const enumAnnotations = Object.fromEntries( + Object.entries(value).filter(([key]) => key === 'x-extensible' || key === 'x-pattern') + ); + const reviewedEnum = Object.hasOwn(REVIEWED_COMMERCIAL_ENUM_ANNOTATIONS, location) + ? REVIEWED_COMMERCIAL_ENUM_ANNOTATIONS[location] + : undefined; + if (reviewedEnum !== undefined || Object.keys(enumAnnotations).length > 0) { + if (canonicalize(enumAnnotations) !== canonicalize(reviewedEnum ?? {})) { + return failure('unreviewed commercial-term enum annotations', location); + } + } + if (typeof value.$ref === 'string') { + const url = new URL(value.$ref, `${prefix}${document}`); + if (!url.href.startsWith(prefix) || url.search) + return failure('schema reference leaves the selected bundle', `${location}/$ref`); + const ref = url.href.slice(prefix.length).split('#')[0]!; + if (!seen.has(ref)) { + seen.add(ref); + const dependency = load(ref); + if (!dependency) return failure('referenced schema is unavailable', ref); + const error = visit(dependency, ref, ref); + if (error) return error; + } + } + for (const key of ['properties', 'patternProperties', 'definitions', 'dependencies']) { + const children = value[key]; + if (children && typeof children === 'object' && !Array.isArray(children)) { + for (const [name, child] of Object.entries(children)) { + if (key === 'dependencies' && Array.isArray(child)) continue; + const error = visit(child, `${location}/${key}/${name}`, document); + if (error) return error; + } + } + } + for (const key of [ + 'items', + 'additionalItems', + 'additionalProperties', + 'contains', + 'propertyNames', + 'if', + 'then', + 'else', + 'not', + 'allOf', + 'anyOf', + 'oneOf', + ]) { + const child = value[key]; + if (child === undefined) continue; + if (Array.isArray(child)) { + for (const [index, branch] of child.entries()) { + const error = visit(branch, `${location}/${key}/${index}`, document); + if (error) return error; + } + } else { + const error = visit(child, `${location}/${key}`, document); + if (error) return error; + } + } + return undefined; + } + + seen.add('media-buy/commercial-terms.json'); + const error = visit(schema, 'media-buy/commercial-terms.json', 'media-buy/commercial-terms.json'); + if (error) return error; + for (const location of [...Object.keys(reviewedSemantics), ...Object.keys(REVIEWED_COMMERCIAL_ENUM_ANNOTATIONS)]) { + if (locations.has(location)) continue; + if ( + Object.hasOwn(ABSENT_COMMERCIAL_CONTRACTS_BY_RELEASE, schemaVersion) && + ABSENT_COMMERCIAL_CONTRACTS_BY_RELEASE[schemaVersion]?.includes(location) + ) + continue; + return failure('removed commercial-term validation semantics', location); + } + return undefined; +} diff --git a/src/lib/negotiation/commercial-terms-semantics.ts b/src/lib/negotiation/commercial-terms-semantics.ts new file mode 100644 index 000000000..9d616bd09 --- /dev/null +++ b/src/lib/negotiation/commercial-terms-semantics.ts @@ -0,0 +1,130 @@ +/** + * Reviewed non-JSON-Schema semantics from the 3.2 beta.8 / rc.2 / rc.3 bundles. + * These are semantic contracts, NOT a binding-field allowlist: properties and + * comparison always come from the selected runtime schema. Additions to these + * annotations require a deliberate implementation/review instead of AJV silently + * ignoring a new contract. See docs/guides/PROPOSAL-TERMS-VERIFICATION.md. + */ +export const REVIEWED_COMMERCIAL_TERMS_SEMANTICS: Readonly> = { + 'media-buy/commercial-terms.json': { + verifier_constraints: { + pricing_integrity: { + pricing_option_ids: 'each_purchase.pricing_option_id_equals_pricing.pricing_option_id', + purchase_currencies: 'all_purchase.pricing.currency_equal', + total_budget_currency: 'when_total_budget_present_equals_purchase_pricing_currency', + monetary_fields: 'purchase_budget_min_spend_and_bidding_use_purchase_pricing_currency', + on_violation: 'reject_proposal_or_commitment', + }, + }, + }, + 'media-buy/commercial-terms.json/properties/purchases': { + verifier_constraints: { + resolved_purchase_terms: + 'Each purchase carries resolved start_time and end_time. Applicable measurement_terms and performance_standards are copied from the published offer or negotiated successor; omission means no such terms apply.', + }, + }, + 'media-buy/product-purchase.json': { + verifier_constraints: { + direct_purchase_terms: + 'On buy_products, supplied start_time, end_time, measurement_terms, and performance_standards MUST exactly match the selected published offer; omission inherits that offer.', + accepted_snapshot_terms: + 'Inside canonical-proposal.commercial_terms, each purchase MUST carry resolved start_time and end_time and MUST preserve every applicable measurement term and performance standard. Omission of measurement_terms or performance_standards means the accepted offer declared none.', + pricing_identity: { + pricing_option_id: 'equals_pricing.pricing_option_id_when_pricing_present', + on_violation: 'reject_before_commitment', + }, + }, + }, + 'core/targeting.json': { + disjoint_place_fields: { + include: 'geo_places', + exclude: 'geo_places_exclude', + identity: ['country', 'system', 'place_type', 'value'], + }, + description: + 'JSON Schema draft-07 cannot compare values across sibling arrays. Conformance tooling MUST reject any place identity present in both geo_places and geo_places_exclude. Catalog version is deliberately not part of place identity: a stable ID cannot be both included and excluded by assigning different versions.', + }, + 'core/targeting.json/properties/geo_regions_exclude': { + disjoint_with: 'geo_regions', + spec: 'docs/media-buy/advanced-topics/targeting.mdx#geo_regions_exclude', + }, + 'core/geo-place-area.json': { + map_keys_subset_of_array: { + map_field: 'value_labels', + array_field: 'values', + }, + description: + 'Every value_labels key MUST also appear in values. JSON Schema draft-07 cannot express this sibling-field key membership constraint, so conformance tooling must enforce it.', + }, + 'core/locale-tag.json': { + verifier_constraints: { + well_formed: 'rfc5646', + semantic_scope: 'language_identity_only', + canonical_wire_profile: 'adcp_bcp47_casing', + rfc5646_comparison: 'case_insensitive', + non_profile: 'reject', + }, + spec: 'docs/protocol/language-and-localization.mdx#one-language-tag-primitive', + }, + 'core/iana-timezone.json': { + iana_timezone: 'value_must_resolve_in_the_implementations_supported_IANA_TZDB', + }, + 'media-buy/commercial-terms.json/properties/change_terms': { + unique_by: 'action', + }, + 'media-buy/change-term.json': { + verifier_constraints: { + allowed_statuses: + 'Every value is a non-terminal MediaBuy status. The current buy projection omits the action outside these statuses without extinguishing the negotiated right.', + constraint_action_compatibility: { + budget: [ + 'increase_budget', + 'decrease_budget', + 'reallocate_budget', + 'update_budget_allocation', + 'update_spend_target', + ], + flight: ['extend_flight', 'shorten_flight', 'update_flight_dates'], + package_count: ['add_packages', 'remove_packages'], + effective_timing: ['pause', 'resume', 'cancel'], + on_violation: 'reject_proposal', + }, + constraint_currency: 'Every monetary constraint currency equals the commercial terms purchase currency.', + constraint_consistency: + 'Minimum result does not exceed maximum result; earliest timestamp does not exceed latest timestamp.', + }, + }, +}; + +/** Contracts absent from a deliberately supported historical schema graph. */ +export const ABSENT_COMMERCIAL_CONTRACTS_BY_RELEASE: Readonly> = { + '3.2.0-beta.8': [ + 'media-buy/commercial-terms.json/properties/change_terms', + 'media-buy/change-term.json', + 'core/iana-timezone.json', + ], +}; + +/** rc.3 removes direct buy_products matching from the accepted snapshot contract. */ +export const COMMERCIAL_SEMANTIC_OVERRIDES_BY_RELEASE: Readonly>>> = { + '3.2.0-rc.3': { + 'media-buy/product-purchase.json': { + verifier_constraints: { + accepted_snapshot_terms: + 'Inside canonical-proposal.commercial_terms, each purchase MUST carry resolved start_time and end_time and MUST preserve every applicable measurement term and performance standard. Omission of measurement_terms or performance_standards means the accepted offer declared none.', + pricing_identity: { + pricing_option_id: 'equals_pricing.pricing_option_id_when_pricing_present', + on_violation: 'reject_before_commitment', + }, + }, + }, + }, +}; + +/** Binding snapshots keep JSON Schema enum membership even for extensible taxonomies. */ +export const REVIEWED_COMMERCIAL_ENUM_ANNOTATIONS: Readonly>>> = { + 'enums/advertiser-industry.json': { + 'x-extensible': true, + 'x-pattern': '^[a-z][a-z0-9_]+(\\.[a-z][a-z0-9_]+)?$', + }, +}; diff --git a/src/lib/negotiation/verification.ts b/src/lib/negotiation/verification.ts index 82f4dae0f..342deb06a 100644 --- a/src/lib/negotiation/verification.ts +++ b/src/lib/negotiation/verification.ts @@ -3,6 +3,19 @@ import { MAX_JSON_DEPTH } from '../utils/json-depth'; import { canonicalize } from '../utils/jcs'; import { getSchemaDocumentByRef, getSchemaValidatorByRef } from '../validation/schema-loader'; import { ADCP_VERSION } from '../version'; +import { commercialTermsSchemaSupportError } from './commercial-terms-schema'; +import { COMMERCIAL_TERMS_KEYWORDS } from './commercial-terms-keywords'; +export type { + CanonicalProposal, + ProposalCommercialTermsMismatch, + ProposalCommercialTermsVerificationResult, + ProposalVerificationIssue, + ProposalVerificationResult, + RefineProposalsCompletedResponse, + RefineProposalsRequest, + RefineProposalsResponse, + VerifyProposalCommercialTermsOptions, +} from './types'; import type { CanonicalProposal, ProposalCommercialTermsMismatch, @@ -27,6 +40,9 @@ const MAX_COMMERCIAL_TERMS_BYTES = 256 * 1024; const MAX_COMMERCIAL_TERMS_NODES = 50_000; const MAX_COMMERCIAL_TERMS_MISMATCHES = 100; const MAX_COMMERCIAL_TERMS_DIAGNOSTIC_BYTES = 64 * 1024; +// Loader identities are immutable and scoped by bundle/root. Replacing or +// resetting a bundle produces fresh identities and therefore fresh audits. +const commercialSchemaSupport = new WeakMap(); export class ProposalResponseVerificationError extends Error { readonly issues: ProposalVerificationIssue[]; @@ -70,7 +86,13 @@ export class ProposalCommercialTermsVerificationError extends Error { * should pass the seller-served release through `adcpVersion`, and must ship * that matching bundle. A newly added optional commercial field is therefore * compared automatically when present instead of being omitted by a stale SDK - * allowlist. + * allowlist. It fails closed unless the buyer's complete reviewed snapshot also + * contains that field. Unknown schema keywords or changed non-structural + * validation contracts require explicit SDK support, even for equal snapshots. + * No version projection, field stripping, or contract-reference resolution is + * performed. A 3.1 bundle without commercial_terms returns schema_unavailable. + * This Node.js API loads local bundles; importing it does not load a client or + * contact the seller. See @adcp/sdk/negotiation/verification. * * The proposal's `terms_digest` is checked before schema validation or field * comparison. A digest failure returns only `digest_mismatch`, preventing a @@ -128,15 +150,52 @@ export function verifyProposalCommercialTerms( let validator: ReturnType; try { document = getSchemaDocumentByRef('media-buy/commercial-terms.json', adcpVersion); - validator = getSchemaValidatorByRef('media-buy/commercial-terms.json', adcpVersion); } catch { return schemaUnavailableResult(); } - if (!document || !validator) { + if (!document) { return schemaUnavailableResult(); } - const schemaVersion = document.resolvedVersion; + const declaredSchemaVersion = + (typeof document.schema.$id === 'string' && + /\/schemas\/([^/]+)\/media-buy\/commercial-terms\.json$/.exec(document.schema.$id)?.[1]) || + undefined; + const schemaVersion = + declaredSchemaVersion && declaredSchemaVersion !== 'latest' ? declaredSchemaVersion : document.resolvedVersion; + try { + let supportError = commercialSchemaSupport.get(document.schema); + if (supportError === undefined) { + supportError = + commercialTermsSchemaSupportError( + document.schema, + document.resolvedVersion, + ref => getSchemaDocumentByRef(ref, adcpVersion)?.schema + ) ?? null; + commercialSchemaSupport.set(document.schema, supportError); + } + if (supportError) { + return { + ok: false, + schemaVersion, + mismatches: [{ kind: 'unsupported_schema', path: '/commercial_terms', message: supportError }], + }; + } + validator = getSchemaValidatorByRef('media-buy/commercial-terms.json', adcpVersion, COMMERCIAL_TERMS_KEYWORDS); + } catch { + return { + ok: false, + schemaVersion, + mismatches: [ + { + kind: 'unsupported_schema', + path: '/commercial_terms', + message: 'the selected commercial-terms schema could not be audited or compiled', + }, + ], + }; + } + if (!validator) return schemaUnavailableResult(); const schemaProperties = isRecord(document.schema.properties) ? document.schema.properties : undefined; if (!schemaProperties || document.schema.additionalProperties !== false) { return { @@ -211,20 +270,6 @@ export function verifyProposalCommercialTerms( return invalidTermsResult('proposal', '/commercial_terms', 'commercial terms must be objects', schemaVersion); } - const semanticSupportError = commercialTermsSemanticSupportError(document.schema, changeTermSchema); - if (semanticSupportError) { - return { - ok: false, - schemaVersion, - mismatches: [ - { - kind: 'unsupported_schema', - path: '/commercial_terms', - message: semanticSupportError, - }, - ], - }; - } const actualSemanticIssues = validateCommercialTermsSemantics(actual, document.schema, changeTermSchema); if (actualSemanticIssues.length > 0) { const truncated = actualSemanticIssues.length > MAX_COMMERCIAL_TERMS_MISMATCHES; @@ -256,9 +301,9 @@ export function verifyProposalCommercialTerms( }; } - // Derive the exhaustive top-level comparison allowlist from the selected - // schema. Nested values are recursively compared in full after AJV has - // proved that both trees satisfy the same schema bundle. + // The selected schema admits fields (including patternProperties); the + // union of both validated trees ensures no admitted binding value is lost. + // Compare recursively, including open extension objects and ordered arrays. const comparisonFields = new Set([...Object.keys(actual), ...Object.keys(expected)]); const mismatchState = { truncated: false, diagnosticBytes: 0 }; for (const field of [...comparisonFields].sort()) { @@ -1347,8 +1392,12 @@ function commercialTermsComplexityError(value: unknown): string | undefined { } } - const descriptors = Object.getOwnPropertyDescriptors(current.value); - for (const [key, descriptor] of Object.entries(descriptors)) { + const keys = Object.keys(current.value); + if (nodes + keys.length > MAX_COMMERCIAL_TERMS_NODES) { + return 'commercial terms exceed the 50,000-node complexity limit'; + } + for (const key of keys) { + const descriptor = Object.getOwnPropertyDescriptor(current.value, key)!; if (!descriptor.enumerable) continue; if (!('value' in descriptor)) return 'commercial terms must contain data properties only'; stringBytes += Buffer.byteLength(key, 'utf8'); @@ -1359,64 +1408,6 @@ function commercialTermsComplexityError(value: unknown): string | undefined { return undefined; } -const PRICING_INTEGRITY_CONSTRAINTS = { - pricing_option_ids: 'each_purchase.pricing_option_id_equals_pricing.pricing_option_id', - purchase_currencies: 'all_purchase.pricing.currency_equal', - total_budget_currency: 'when_total_budget_present_equals_purchase_pricing_currency', - monetary_fields: 'purchase_budget_min_spend_and_bidding_use_purchase_pricing_currency', - on_violation: 'reject_proposal_or_commitment', -} as const; - -function commercialTermsSemanticSupportError( - schema: Readonly>, - changeTermSchema: Readonly> | undefined -): string | undefined { - const validation = schema['x-adcp-validation']; - if (validation !== undefined) { - if (!isRecord(validation)) return 'commercial-terms x-adcp-validation metadata must be an object'; - const constraints = validation.verifier_constraints; - if (constraints !== undefined) { - if (!isRecord(constraints)) return 'commercial-terms verifier_constraints metadata must be an object'; - const constraintKeys = Object.keys(constraints); - if (constraintKeys.some(key => key !== 'pricing_integrity')) { - return 'commercial-terms schema declares verifier constraints this SDK does not understand'; - } - if (constraints.pricing_integrity !== undefined) { - if (!isRecord(constraints.pricing_integrity)) { - return 'commercial-terms pricing_integrity metadata must be an object'; - } - const actual = constraints.pricing_integrity; - const expectedKeys = Object.keys(PRICING_INTEGRITY_CONSTRAINTS); - if ( - Object.keys(actual).length !== expectedKeys.length || - expectedKeys.some( - key => actual[key] !== PRICING_INTEGRITY_CONSTRAINTS[key as keyof typeof PRICING_INTEGRITY_CONSTRAINTS] - ) - ) { - return 'commercial-terms schema declares unsupported pricing_integrity constraints'; - } - } - } - } - - const properties = schema.properties; - if (!isRecord(properties)) return undefined; - const changeTermsProperty = properties.change_terms; - if (!isRecord(changeTermsProperty)) return undefined; - const changeTermsValidation = changeTermsProperty['x-adcp-validation']; - if (changeTermsValidation !== undefined) { - if ( - !isRecord(changeTermsValidation) || - Object.keys(changeTermsValidation).length !== 1 || - changeTermsValidation.unique_by !== 'action' - ) { - return 'commercial-terms schema declares unsupported change_terms validation metadata'; - } - } - if (!changeTermSchema) return 'commercial-terms schema is missing its change-term schema'; - return changeTermSemanticSupportError(changeTermSchema); -} - function validateCommercialTermsSemantics( terms: Record, schema: Readonly>, @@ -1430,6 +1421,9 @@ function validateCommercialTermsSemantics( const issues: Array<{ path: string; message: string }> = []; if (!Array.isArray(terms.purchases)) return issues; + // Budget, min-spend, and bidding amounts in the reviewed schemas are scalar + // amounts in this shared currency. Their closed schemas reject a separate + // currency property; there is no second denomination to compare here. let purchaseCurrency: string | undefined; for (const [index, purchase] of terms.purchases.entries()) { if (!isRecord(purchase) || !isRecord(purchase.pricing)) continue; @@ -1468,54 +1462,6 @@ function validateCommercialTermsSemantics( return issues; } -function changeTermSemanticSupportError(schema: Readonly>): string | undefined { - const validation = schema['x-adcp-validation']; - if (!isRecord(validation) || !isRecord(validation.verifier_constraints)) { - return 'change-term schema is missing verifier constraint metadata'; - } - const constraints = validation.verifier_constraints; - const expectedKeys = new Set([ - 'allowed_statuses', - 'constraint_action_compatibility', - 'constraint_currency', - 'constraint_consistency', - ]); - if ( - Object.keys(constraints).length !== expectedKeys.size || - Object.keys(constraints).some(key => !expectedKeys.has(key)) - ) { - return 'change-term schema declares verifier constraints this SDK does not understand'; - } - if ( - constraints.allowed_statuses !== - 'Every value is a non-terminal MediaBuy status. The current buy projection omits the action outside these statuses without extinguishing the negotiated right.' || - constraints.constraint_currency !== - 'Every monetary constraint currency equals the commercial terms purchase currency.' || - constraints.constraint_consistency !== - 'Minimum result does not exceed maximum result; earliest timestamp does not exceed latest timestamp.' - ) { - return 'change-term schema declares unsupported verifier constraint semantics'; - } - const compatibility = constraints.constraint_action_compatibility; - if (!isRecord(compatibility) || compatibility.on_violation !== 'reject_proposal') { - return 'change-term schema declares unsupported action compatibility metadata'; - } - for (const [kind, actions] of Object.entries(CHANGE_TERM_ACTIONS_BY_CONSTRAINT)) { - const declared = compatibility[kind]; - if ( - !Array.isArray(declared) || - declared.length !== actions.size || - declared.some(action => typeof action !== 'string' || !actions.has(action)) - ) { - return 'change-term schema declares unsupported action compatibility metadata'; - } - } - if (Object.keys(compatibility).some(key => key !== 'on_violation' && !(key in CHANGE_TERM_ACTIONS_BY_CONSTRAINT))) { - return 'change-term schema declares unsupported action compatibility metadata'; - } - return undefined; -} - function validateChangeTermSemantics( terms: unknown[], purchaseCurrency: string | undefined, @@ -1538,7 +1484,7 @@ function validateChangeTermSemantics( if (typeof action === 'string' && !CHANGE_TERM_ACTIONS_BY_CONSTRAINT[kind]?.has(action)) { issues.push({ path: `${path}/constraints/kind`, - message: `${String(kind)} constraints are not compatible with action ${action}`, + message: 'constraint kind is not compatible with the change action', }); } for (const key of ['max_delta_amount', 'min_result_amount', 'max_result_amount'] as const) { @@ -1546,7 +1492,7 @@ function validateChangeTermSemantics( if (purchaseCurrency !== undefined && isRecord(money) && money.currency !== purchaseCurrency) { issues.push({ path: `${path}/constraints/${key}/currency`, - message: `constraint currency must equal ${purchaseCurrency}`, + message: 'constraint currency must equal the purchase currency', }); } } diff --git a/src/lib/validation/schema-loader.ts b/src/lib/validation/schema-loader.ts index dbd5fd472..a6dd9e27f 100644 --- a/src/lib/validation/schema-loader.ts +++ b/src/lib/validation/schema-loader.ts @@ -13,11 +13,12 @@ * unchanged. */ -import Ajv, { type ValidateFunction } from 'ajv'; +import Ajv, { type KeywordDefinition, type ValidateFunction } from 'ajv'; import addFormats from 'ajv-formats'; import { AsyncLocalStorage } from 'async_hooks'; import { readdirSync, readFileSync, existsSync } from 'fs'; import path from 'path'; +import { isDeepStrictEqual } from 'node:util'; import { ADCP_VERSION } from '../version'; import { ConfigurationError } from '../errors'; import { hasBundledSchemaStore, listBundledSchemaFiles, loadBundledSchemaFile } from './bundled-schema-store'; @@ -354,6 +355,11 @@ interface LoaderState { const states: Map = new Map(); const schemaRefValidators = new Map(); +const keywordSchemaRefValidators = new WeakMap< + ReadonlyArray, + { generation: number; validators: Map } +>(); +let keywordCacheGeneration = 0; const externalSchemaRoots: Map = new Map(); const scopedExternalSchemaRoots = new AsyncLocalStorage>(); @@ -362,6 +368,7 @@ function stateCacheKey(bundleKey: string, root: string): string { } function clearStatesForBundle(bundleKey: string): void { + keywordCacheGeneration++; for (const [stateKey, state] of states) { if (state.version === bundleKey) states.delete(stateKey); } @@ -923,9 +930,30 @@ export function getSchemaDocumentByRef( const file = path.join(state.root, normalized); if (!existsSync(file)) return undefined; + // Bundle documents are immutable for the lifetime of their loader state, + // just like compiled validators. Freeze shared documents so domain audits + // can memoize by identity without allowing callers to mutate a schema. + const readDocument = (ref: string): Record => { + const key = `document::${ref}`; + let schema = state.rawSchemas.get(key); + if (!schema) { + schema = loadJson(path.join(state.root, ref)); + const pending: unknown[] = [schema]; + while (pending.length > 0) { + const value = pending.pop(); + if (value && typeof value === 'object') { + for (const child of Object.values(value)) pending.push(child); + Object.freeze(value); + } + } + state.rawSchemas.set(key, schema); + } + return schema; + }; + let resolvedVersion = state.version; try { - const index = loadJson(path.join(state.root, 'index.json')) as Record; + const index = readDocument('index.json'); if (typeof index.adcp_version === 'string') resolvedVersion = index.adcp_version; } catch { // Legacy/external bundles may omit index.json; the loader key remains an @@ -937,7 +965,7 @@ export function getSchemaDocumentByRef( requestedVersion: version, bundleKey: state.version, resolvedVersion, - schema: loadJson(file), + schema: readDocument(normalized), }; } @@ -948,7 +976,8 @@ export function getSchemaDocumentByRef( */ export function getSchemaValidatorByRef( schemaRef: string, - version: string = ADCP_VERSION + version: string = ADCP_VERSION, + keywords?: ReadonlyArray ): ValidateFunction | undefined { // Keep remote schema-ref validation out of the shared tool-validator AJV, // which intentionally collects all errors for developer diagnostics. @@ -957,8 +986,19 @@ export function getSchemaValidatorByRef( const normalized = normalizeSchemaRef(schemaRef); if (!normalized) return undefined; + // Keep domain-specific keyword validators isolated from ordinary schema-ref + // validation. Callers retain an immutable keyword array for cache reuse. + let cache = schemaRefValidators; + if (keywords) { + let entry = keywordSchemaRefValidators.get(keywords); + if (!entry || entry.generation !== keywordCacheGeneration) { + entry = { generation: keywordCacheGeneration, validators: new Map() }; + keywordSchemaRefValidators.set(keywords, entry); + } + cache = entry.validators; + } const cacheKey = `${stateCacheKey(bundleKey, root)}\0schema-ref::${normalized}`; - const cached = schemaRefValidators.get(cacheKey); + const cached = cache.get(cacheKey); if (cached) return cached; const file = path.join(root, normalized); @@ -977,8 +1017,10 @@ export function getSchemaValidatorByRef( allowUnionTypes: true, }); addFormats(ajv); + for (const keyword of keywords ?? []) ajv.addKeyword(keyword); + const rawSchema = loadJson(file); const dependencySchemas: LoadedSchema[] = []; - const registeredIds = new Set(); + const registeredIds = new Map(); for (const schemaFile of walkJsonFiles(root)) { if (schemaFile.includes(`${path.sep}bundled${path.sep}`)) continue; if ( @@ -988,17 +1030,25 @@ export function getSchemaValidatorByRef( } if (schemaFile === file) continue; const schema = loadJson(schemaFile); + if (keywords && typeof schema.$id === 'string') { + const previous = schema.$id === rawSchema.$id ? rawSchema : registeredIds.get(schema.$id); + // Bundles intentionally mirror async-response refs. Identical copies + // are harmless; conflicting definitions must not shadow audited files. + if (previous && !isDeepStrictEqual(previous, schema)) { + throw new ConfigurationError('Schema keyword validation requires unambiguous schema identities', 'schemaRoot'); + } + if (schema.$id === rawSchema.$id) continue; + } if (typeof schema.$id === 'string' && !registeredIds.has(schema.$id)) { - registeredIds.add(schema.$id); + registeredIds.set(schema.$id, schema); dependencySchemas.push(schema); } } if (dependencySchemas.length > 0) { ajv.addSchema(dependencySchemas); } - const rawSchema = loadJson(file); const compiled = ajv.compile(rawSchema); - schemaRefValidators.set(cacheKey, compiled); + cache.set(cacheKey, compiled); return compiled; } @@ -1208,6 +1258,7 @@ export function _resetValidationLoader(version?: string): void { if (version === undefined) { states.clear(); schemaRefValidators.clear(); + keywordCacheGeneration++; } else { clearStatesForBundle(resolveBundleKey(version)); } diff --git a/test/fixtures/proposal-commercial-terms/README.md b/test/fixtures/proposal-commercial-terms/README.md new file mode 100644 index 000000000..872a3383b --- /dev/null +++ b/test/fixtures/proposal-commercial-terms/README.md @@ -0,0 +1,19 @@ +# Proposal commercial-term verification fixtures + +`current.json` exercises the pinned AdCP 3.2.0-rc.2 commercial envelope, including +all four portable constraint kinds. `beta8.json` is its pre-change-rights snapshot. +Values are deterministic test fixtures, never fallback agent responses. + +`beta8-schema.json.gz` freezes the complete reachable Draft-07 schema graph rooted +at `media-buy/commercial-terms.json` from the signed **3.2.0-beta.8** distribution +downloaded by `npm run sync-schemas -- 3.2.0-beta.8`. It contains a JSON map keyed by +schema path, plus an index with the release identity. Schema contents, IDs, and +references are unmodified; only JSON whitespace/key ordering and gzip packaging +differ. Tests unpack it into an isolated temporary schema root, so CI never +silently validates the old fixture against the latest schema or requires a +network fetch for this old release. + +`rc3-product-purchase-validation.json` is the unmodified `x-adcp-validation` +annotation from the released AdCP 3.2.0-rc.3 `media-buy/product-purchase.json`. +It isolates the removal of the direct-purchase contract from accepted snapshots +and checks that supporting rc.3 does not weaken the rc.2 semantic profile. diff --git a/test/fixtures/proposal-commercial-terms/beta8-schema.json.gz b/test/fixtures/proposal-commercial-terms/beta8-schema.json.gz new file mode 100644 index 0000000000000000000000000000000000000000..289fd1796c5dd3113700b626ec11c8b397329ce7 GIT binary patch literal 35730 zcmV(#K;*w4iwFP!00002|Lna9a~s!{DEwD$aZ*Ln0U%PA?S%a1p3$VjRH>SHm3ii`~|IT{v?F9=dP)S}*s$vm9_g&Av{=PTP3;QS`sw;RG z-mudd3}s%Nn;bvGdiys~y0B&*B?SyJw^@vX!zl2I8)?5ZRa8uEg}=@0_$tbhayGyv zC%EJpPMsHcmT+iuTU5&*qnU+GRLi;D``FvdGy7_?ck;{cdr=%GxXdVh&5tIw+&ig? zh3)Cf^v&;kvf3fu&hL%Gc^j;*U(W3qj%V!l7aUlX!+BYgWM&-AV3*U(Zw1y*>pR&i zs{%iN)GvMqc*)8NfANcGUeJX<%~4d^c-_D-a$)~_krWm-^9%pl3kQGyv3HlVft%|- z6n{_isDL}D;0*BLEw&1e4G9`rJN;`NPB!kgx5wjby+WOKt5f6c@GI{>zK6GxD#h2% z944B-hFi`@f3xEXm&FKM!SJI6VeD;^#rf^7D8Y(>??(;R0Ym*%&*{_1mV~syDgalj zt31xre7ZDI7MnEBuSe1N+VJv9#EqDU3hWfA4ZjqXi^3vg4$Si`8l^DuxX8=0uP6tP z12Po}?81zeW)@u&Nm?;;RYX|{kJEtfaK@+v>T~&r!cH#Dq{wIHGKbB~lHZt)PV*?G zqq{T*qs7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9g5VC4_q^nXvD}ue+$I$GNuY|1}$~)R|H_a!o*U^~WP8r@XukhEP=i&C2 zbJlrj0T$?NAlvlxZMNchqQ*xTH@G~dE}N10h})XfCUk}MO^_-BuCO$+S zL#3Q;Zp47yvzc2bJsCXrg_FJ`3UiV0AcSFy`gtki zDYqEYVN2g)E6-`wc3+!8+w9fp4JDFDgL2iVC2|F5u!kG1cj{oDmg}KnYd@hol%2lu zK?~lqEYx}dSYs|w85bVRj+iPZhiP`4>95Xs5=wu-8y)`1P}D?CTu4?TR&aZUd$-Mw zh?<5oYW4=Scsx?DP|X|B>LH!q10)}xPzaJ%2;7m@tOh1ZLFaboT}JeltJOT5U}?lL zPiTIOy^#$v03rFmKv+DC4QE^hTNlkmlgY_kG%eSL9j}FF%T}I6V~v$Q<5iwyFR&th zL3qcl7c@HYfhW$AOj?hTX2pSd%xMKoo-6tCtBE!D;h{mUklzQRTh-LVouH$Ed)w}Qcm~L z?*{S9XCaG-F)qT-h3cjjA~VTetygP3yq_GQkpnaiW8QuJ>OKYjyj+wQGQL7XoYQH( z40;HGnaXJi_mwK2VT%Dc#!^Vxi@J$PePl(JFcC=AsButEK1@a)$4{*@vj50@1v3;@ z{p^jmrz7``Vda-=x%I~|;#&F-Kz>-`Akw}-Nr30Oz7Dt>th+c)h7eO<$EkI4`on-A zo-9hw7m@cKfD zZ50_c2&*H10C)7GI_Vf7NrT9J_h~FQ?aF35>lRIRlwAIaB8vh3 ({ commercial_terms: terms, terms_digest: proposalTermsDigest(terms) }); + +test('public CommonJS and ESM verifier entries work without constructing a client', async () => { + const manifest = require('../../package.json'); + assert.deepEqual(manifest.typesVersions['*']['negotiation/verification'], ['dist/lib/negotiation/verification.d.ts']); + for (const condition of Object.values(manifest.exports['./negotiation/verification'])) { + for (const file of Object.values(condition)) assert.ok(fs.existsSync(path.resolve(__dirname, '../..', file)), file); + } + const esm = await import('@adcp/sdk/negotiation/verification'); + assert.deepEqual(verify(candidate(current), current), { ok: true, schemaVersion: ADCP_VERSION, mismatches: [] }); + assert.deepEqual(esm.verifyProposalCommercialTerms(candidate(current), current), verify(candidate(current), current)); + const bundled = await build({ + stdin: { + contents: "export { verifyProposalCommercialTerms } from '@adcp/sdk/negotiation/verification'", + resolveDir: process.cwd(), + sourcefile: 'buyer.mjs', + }, + bundle: true, + format: 'esm', + platform: 'node', + write: false, + metafile: true, + }); + assert.ok( + Object.keys(bundled.metafile.inputs).every( + file => !/protocols\/|TaskExecutor|AdCPClient|negotiation\/(buyer|seller|orchestrator)\./.test(file) + ) + ); + assert.ok(!bundled.outputFiles[0].text.includes('function verifyRefineProposalsResponse')); +}); + +for (const field of ['start_time', 'end_time']) { + test(`accepted purchases require resolved ${field} even when both snapshots omit it`, () => { + const terms = structuredClone(current); + delete terms.purchases[0][field]; + const result = verify(candidate(terms), terms); + assert.equal(result.mismatches[0].kind, 'invalid_terms'); + assert.equal(result.mismatches[0].path, `/commercial_terms/purchases/0/${field}`); + }); +} + +// Each mutation preserves JSON Schema validity, isolating exhaustive comparison +// from shape validation. The paths are a buyer-visible contract. +const changes = [ + [ + 'price', + t => { + t.purchases[0].pricing.fixed_price = 9; + }, + '/purchases/0/pricing/fixed_price', + ], + [ + 'currency', + t => { + t.purchases[0].pricing.currency = 'EUR'; + t.total_budget.currency = 'EUR'; + for (const key of ['max_delta_amount', 'min_result_amount', 'max_result_amount']) + t.change_terms[0].constraints[key].currency = 'EUR'; + }, + '/purchases/0/pricing/currency', + ], + [ + 'flight start', + t => { + t.start_time = '2027-01-02T00:00:00Z'; + }, + '/start_time', + ], + [ + 'flight end', + t => { + t.end_time = '2027-02-02T00:00:00Z'; + }, + '/end_time', + ], + [ + 'package flight', + t => { + t.purchases[0].end_time = '2027-02-02T00:00:00Z'; + }, + '/purchases/0/end_time', + ], + [ + 'package authorization', + t => { + t.purchases[0].agency_estimate_number = 'replacement'; + }, + '/purchases/0/agency_estimate_number', + ], + [ + 'contract reference', + t => { + t.change_terms[0].terms_ref = 'other-contract'; + }, + '/change_terms/0/terms_ref', + ], + [ + 'purchase order', + t => { + t.purchase_order_ref = 'other-order'; + }, + '/purchase_order_ref', + ], + [ + 'mode', + t => { + t.change_terms[0].service_mode = 'seller_managed'; + }, + '/change_terms/0/service_mode', + ], + [ + 'status scope', + t => { + t.change_terms[0].allowed_statuses[1] = 'pending_start'; + }, + '/change_terms/0/allowed_statuses/1', + ], + [ + 'SLA', + t => { + t.change_terms[0].processing_sla.completion_max = 'P1D'; + }, + '/change_terms/0/processing_sla/completion_max', + ], + [ + 'opaque condition', + t => { + t.change_terms[0].conditions[0] = 'different_condition'; + }, + '/change_terms/0/conditions/0', + ], + [ + 'budget constraint', + t => { + t.change_terms[0].constraints.max_delta_percent = 30; + }, + '/change_terms/0/constraints/max_delta_percent', + ], + [ + 'flight constraint', + t => { + t.change_terms[1].constraints.max_change.interval = 8; + }, + '/change_terms/1/constraints/max_change/interval', + ], + [ + 'package count', + t => { + t.change_terms[2].constraints.max_result_count = 4; + }, + '/change_terms/2/constraints/max_result_count', + ], + [ + 'effective timing', + t => { + t.change_terms[3].constraints.minimum_notice.interval = 10; + }, + '/change_terms/3/constraints/minimum_notice/interval', + ], + [ + 'extension JSON Pointer escaping', + t => { + t.purchases[0].ext.vendor['binding/key~name'].rate = 2; + }, + '/purchases/0/ext/vendor/binding~1key~0name/rate', + ], +]; +for (const [name, mutate, suffix] of changes) { + test(`recursive comparison covers ${name}`, () => { + const offered = structuredClone(current); + mutate(offered); + const result = verify(candidate(offered), current); + assert.equal(result.ok, false); + assert.ok( + result.mismatches.some(m => m.kind === 'changed' && m.path === `/commercial_terms${suffix}`), + JSON.stringify(result) + ); + }); +} + +test('array order, added purchases, and removed rights are binding', () => { + const offered = structuredClone(current); + offered.purchases.push(structuredClone(offered.purchases[0])); + offered.change_terms.pop(); + assert.deepEqual( + verify(candidate(offered), current).mismatches.map(m => [m.kind, m.path]), + [ + ['missing', '/commercial_terms/change_terms/3'], + ['unexpected', '/commercial_terms/purchases/1'], + ] + ); + const reordered = structuredClone(current); + reordered.change_terms.reverse(); + assert.equal(verify(candidate(reordered), current).ok, false); +}); + +test('unknown fields fail closed at root and nested scopes even in identical snapshots', () => { + for (const mutate of [ + t => { + t.future_contract = 'unknown'; + }, + t => { + t.purchases[0].future_contract = 'unknown'; + }, + t => { + t.change_terms[0].future_contract = 'unknown'; + }, + ]) { + const terms = structuredClone(current); + mutate(terms); + const result = verify(candidate(terms), terms); + assert.equal(result.ok, false); + assert.equal(result.mismatches[0].kind, 'invalid_terms'); + assert.ok(result.mismatches[0].path.endsWith('/future_contract')); + } +}); + +test('digest failure precedes schema selection and access to the expected snapshot', () => { + const expected = new Proxy( + {}, + { + ownKeys() { + throw new Error('expected snapshot accessed'); + }, + } + ); + const proposed = candidate(current); + proposed.commercial_terms = { unknown_binding: true }; + assert.deepEqual( + verify(proposed, expected, { adcpVersion: 'unknown' }).mismatches.map(m => m.kind), + ['digest_mismatch'] + ); +}); + +test('3.1 has no canonical commercial envelope and cannot acquire 3.2 authority by projection', () => { + assert.equal(verify(candidate(beta8), beta8, { adcpVersion: '3.1.18' }).mismatches[0].kind, 'schema_unavailable'); + // A proposal change term's terms_ref is a contract pointer, never its term_id. + assert.notEqual(current.change_terms[0].terms_ref, current.change_terms[0].term_id); + assert.equal(verify(candidate(current), current).ok, true); +}); + +test('an older 3.2 bundle admits its own envelope and rejects projected change rights', () => { + // Fixture keeps this version test independent of optional caches on adopters' machines. + const root = fs.mkdtempSync(path.join(os.tmpdir(), 'proposal-beta8-')); + const documents = JSON.parse( + require('node:zlib').gunzipSync( + fs.readFileSync(path.resolve(__dirname, '../fixtures/proposal-commercial-terms/beta8-schema.json.gz')) + ) + ); + try { + for (const [ref, schema] of Object.entries(documents)) { + const file = path.join(root, ref); + fs.mkdirSync(path.dirname(file), { recursive: true }); + fs.writeFileSync(file, JSON.stringify(schema)); + } + withExternalSchemaRoot('3.2.0-beta.8', root, () => { + assert.equal(verify(candidate(beta8), beta8, { adcpVersion: '3.2.0-beta.8' }).ok, true); + const result = verify(candidate(current), current, { adcpVersion: '3.2.0-beta.8' }); + assert.equal(result.ok, false); + assert.equal(result.mismatches[0].path, '/commercial_terms/change_terms'); + }); + } finally { + fs.rmSync(root, { recursive: true, force: true }); + } +}); + +function withChangedSchema(change, run) { + const root = fs.mkdtempSync(path.join(os.tmpdir(), 'proposal-schema-')); + try { + fs.cpSync(path.resolve(__dirname, '../../schemas/cache', ADCP_VERSION), root, { + recursive: true, + filter: source => !['bundled', 'mcp'].includes(path.basename(source)), + }); + const ref = 'media-buy/commercial-terms.json'; + const schema = JSON.parse(fs.readFileSync(path.join(root, ref), 'utf8')); + change(schema, root); + fs.writeFileSync(path.join(root, ref), JSON.stringify(schema)); + return withExternalSchemaRoot(ADCP_VERSION, root, () => run(root)); + } finally { + fs.rmSync(root, { recursive: true, force: true }); + } +} + +test('new schema fields require an explicitly reviewed complete snapshot', () => { + withChangedSchema( + schema => { + schema.properties.future_contract = { + type: 'object', + properties: { fee: { type: 'number' } }, + additionalProperties: false, + }; + }, + () => { + const terms = { ...current, future_contract: { fee: 123 } }; + assert.equal(verify(candidate(terms), current).mismatches[0].kind, 'unexpected'); + assert.equal(verify(candidate(terms), terms).ok, true); + assert.equal( + verify(candidate(terms), { ...terms, future_contract: { fee: 124 } }).mismatches[0].path, + '/commercial_terms/future_contract/fee' + ); + } + ); +}); + +test('release-precision external roots can use schema identity without an index', () => { + withChangedSchema( + (schema, root) => fs.rmSync(path.join(root, 'index.json')), + root => { + const release = toReleasePrecisionWire(ADCP_VERSION); + const result = withExternalSchemaRoot(release, root, () => + verify(candidate(current), current, { adcpVersion: release }) + ); + assert.equal(result.ok, true); + assert.equal(result.schemaVersion, ADCP_VERSION); + } + ); +}); + +for (const kind of ['release-pinned latest', 'root-relative']) { + test(`external bundles support ${kind} schema identities`, () => { + const rewrite = value => { + if (typeof value === 'string') { + return kind === 'root-relative' + ? value.replace('https://adcontextprotocol.org/schemas/', '/schemas/') + : value.replace(`/schemas/${ADCP_VERSION}/`, '/schemas/latest/'); + } + if (Array.isArray(value)) return value.map(rewrite); + if (value && typeof value === 'object') + return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, rewrite(v)])); + return value; + }; + withChangedSchema( + (schema, root) => { + for (const file of fs.readdirSync(root, { recursive: true })) { + if (!file.endsWith('.json')) continue; + const target = path.join(root, file); + fs.writeFileSync(target, JSON.stringify(rewrite(JSON.parse(fs.readFileSync(target, 'utf8'))))); + } + Object.assign(schema, rewrite(schema)); + }, + () => + assert.deepEqual(verify(candidate(current), current), { ok: true, schemaVersion: ADCP_VERSION, mismatches: [] }) + ); + }); +} + +test('extensible taxonomies retain explicit enum membership for binding snapshots', () => { + const terms = { ...current, advertiser_industry: 'pet_care.veterinary_services' }; + const result = verify(candidate(terms), terms); + assert.equal(result.ok, false); + assert.equal(result.mismatches[0].kind, 'invalid_terms'); + assert.equal(result.mismatches[0].path, '/commercial_terms/advertiser_industry'); +}); + +test('schema audit caches use immutable documents and refresh with loader state', () => { + const { getSchemaDocumentByRef, _resetValidationLoader } = require('../../dist/lib/validation/schema-loader.js'); + withChangedSchema( + () => {}, + root => { + const ref = 'media-buy/commercial-terms.json'; + const before = getSchemaDocumentByRef(ref).schema; + assert.equal(verify(candidate(current), current).ok, true); + assert.equal(getSchemaDocumentByRef(ref).schema, before); + assert.equal(Object.isFrozen(before.properties.purchases), true); + const changed = JSON.parse(fs.readFileSync(path.join(root, ref), 'utf8')); + changed.properties.total_budget.futureBindingRule = true; + fs.writeFileSync(path.join(root, ref), JSON.stringify(changed)); + _resetValidationLoader(ADCP_VERSION); + assert.notEqual(getSchemaDocumentByRef(ref).schema, before); + assert.equal(verify(candidate(current), current).mismatches[0].kind, 'unsupported_schema'); + } + ); +}); + +test('loader reset recompiles ordinary and keyword validators after a supported schema change', () => { + const { getSchemaValidatorByRef, _resetValidationLoader } = require('../../dist/lib/validation/schema-loader.js'); + withChangedSchema( + () => {}, + root => { + const ref = 'media-buy/commercial-terms.json'; + assert.equal(getSchemaValidatorByRef(ref)(current), true); + assert.equal(verify(candidate(current), current).ok, true); + const schema = JSON.parse(fs.readFileSync(path.join(root, ref), 'utf8')); + schema.properties.purchase_order_ref.maxLength = 1; + fs.writeFileSync(path.join(root, ref), JSON.stringify(schema)); + _resetValidationLoader(ADCP_VERSION); + assert.equal(getSchemaValidatorByRef(ref)(current), false); + const result = verify(candidate(current), current); + assert.equal(result.mismatches[0].kind, 'invalid_terms'); + assert.equal(result.mismatches[0].path, '/commercial_terms/purchase_order_ref'); + } + ); +}); + +test('rc.3 deliberately supports the revised accepted-snapshot contract without weakening rc.2', () => { + const { getSchemaDocumentByRef } = require('../../dist/lib/validation/schema-loader.js'); + const { commercialTermsSchemaSupportError } = require('../../dist/lib/negotiation/commercial-terms-schema.js'); + const contract = require('../fixtures/proposal-commercial-terms/rc3-product-purchase-validation.json'); + for (const version of ['3.2.0-rc.2', '3.2.0-rc.3']) { + const load = ref => { + const source = getSchemaDocumentByRef(ref)?.schema; + if (!source) return undefined; + const document = JSON.parse( + JSON.stringify(source).replaceAll(`/schemas/${ADCP_VERSION}/`, `/schemas/${version}/`) + ); + if (ref === 'media-buy/product-purchase.json') document['x-adcp-validation'] = contract; + return document; + }; + const error = commercialTermsSchemaSupportError(load('media-buy/commercial-terms.json'), version, load); + if (version === '3.2.0-rc.3') assert.equal(error, undefined); + else assert.match(error, /unreviewed commercial-term validation semantics/); + } +}); + +test('explanatory schema metadata edits do not change the accepted contract', () => { + withChangedSchema( + (schema, root) => { + const file = path.join(root, 'core/targeting.json'); + const targeting = JSON.parse(fs.readFileSync(file, 'utf8')); + targeting['x-adcp-validation'].description = 'Editorial clarification of the same structured rule.'; + targeting['x-adcp-validation'].spec = 'docs/updated-location.mdx'; + fs.writeFileSync(file, JSON.stringify(targeting)); + }, + () => assert.equal(verify(candidate(current), current).ok, true) + ); +}); + +test('a duplicate schema identity cannot shadow the audited document', () => { + withChangedSchema( + (schema, root) => { + fs.writeFileSync( + path.join(root, 'core/aaa-shadow.json'), + JSON.stringify({ + $id: schema.properties.brand.$ref, + type: 'object', + additionalProperties: true, + }) + ); + }, + () => { + const result = verify(candidate(current), current); + assert.equal(result.ok, false); + assert.equal(result.mismatches[0].kind, 'unsupported_schema'); + } + ); +}); + +test('the support guard rejects a root identity inconsistent with the selected release', () => { + const { getSchemaDocumentByRef } = require('../../dist/lib/validation/schema-loader.js'); + const { commercialTermsSchemaSupportError } = require('../../dist/lib/negotiation/commercial-terms-schema.js'); + const document = getSchemaDocumentByRef('media-buy/commercial-terms.json'); + assert.match( + commercialTermsSchemaSupportError(document.schema, '3.1.18', () => { + assert.fail('a mismatched root must fail before dependency traversal'); + }), + /identity does not match the selected release/ + ); +}); + +for (const [name, change] of [ + ...['x-extensible', 'x-pattern'].map(keyword => [ + `changed ${keyword} enum annotation`, + (schema, root) => { + const file = path.join(root, 'enums/advertiser-industry.json'); + const taxonomy = JSON.parse(fs.readFileSync(file, 'utf8')); + delete taxonomy[keyword]; + fs.writeFileSync(file, JSON.stringify(taxonomy)); + }, + ]), + [ + 'removed semantic dependency', + (schema, root) => { + const file = path.join(root, 'core/targeting.json'); + const targeting = JSON.parse(fs.readFileSync(file, 'utf8')); + targeting.properties.language.items = { type: 'string' }; + fs.writeFileSync(file, JSON.stringify(targeting)); + }, + ], + [ + 'boolean replacement of a reviewed contract', + schema => { + schema.properties.purchases = true; + }, + ], + [ + 'deletion of a reviewed contract location', + schema => { + delete schema.properties.purchases; + schema.required = schema.required.filter(key => key !== 'purchases'); + }, + ], + [ + 'removed validation contract', + schema => { + delete schema['x-adcp-validation']; + }, + ], + [ + 'unknown format', + schema => { + schema.properties.end_time.format = 'future-binding-format'; + }, + ], + [ + 'new validation contract', + schema => { + schema.properties.total_budget['x-adcp-validation'] = { verifier_constraints: { future: 'reject' } }; + }, + ], + [ + 'unknown schema keyword', + schema => { + schema.properties.total_budget.futureBindingRule = true; + }, + ], + [ + 'new dialect keyword', + schema => { + schema.unevaluatedProperties = false; + }, + ], + [ + 'referenced schema drift', + (schema, root) => { + const file = path.join(root, 'media-buy/change-term-constraints.json'); + const dependency = JSON.parse(fs.readFileSync(file, 'utf8')); + dependency.oneOf[0].properties.max_delta_percent.futureBindingRule = true; + fs.writeFileSync(file, JSON.stringify(dependency)); + }, + ], + [ + 'cross-version reference', + schema => { + schema.properties.brand.$ref = schema.properties.brand.$ref.replace(ADCP_VERSION, '3.1.18'); + }, + ], +]) { + test(`equal terms fail closed for ${name}`, () => { + withChangedSchema(change, () => { + const result = verify(candidate(current), current); + assert.equal(result.ok, false); + assert.equal(result.mismatches[0].kind, 'unsupported_schema'); + }); + }); +} + +const place = { country: 'US', system: 'geonames', place_type: 'city', values: ['5128581'] }; +for (const [name, targeting, suffix] of [ + [ + 'overlapping places', + { geo_places: [place], geo_places_exclude: [{ ...place, system_version: 'another-catalog' }] }, + '/geo_places_exclude/0/values/0', + ], + ['overlapping regions', { geo_regions: ['US-NY'], geo_regions_exclude: ['US-NY'] }, '/geo_regions_exclude/0'], + [ + 'unknown place labels', + { geo_places: [{ ...place, value_labels: { 'not/a~value': 'unbound label' } }] }, + '/geo_places/0/value_labels/not~1a~0value', + ], + ['duplicate language variants', { language: ['en-abcde-abcde'] }, '/language/0'], +]) { + test(`equal snapshots reject ${name} with a precise schema-selected path`, () => { + const terms = structuredClone(current); + terms.purchases[0].targeting_overlay = targeting; + const result = verify(candidate(terms), terms); + assert.equal(result.ok, false); + assert.equal(result.mismatches[0].keyword, 'x-adcp-validation'); + assert.equal(result.mismatches[0].path, `/commercial_terms/purchases/0/targeting_overlay${suffix}`); + }); +} + +test('timezone semantics apply only to the matching schema branch', () => { + for (const [zone, expected] of [ + ['UTC', true], + ['inventory_local', true], + ['Unknown/Timezone', false], + ]) { + const terms = structuredClone(current); + terms.purchases[0].targeting_overlay = { + daypart_targets: [{ days: ['monday'], start_hour: 6, end_hour: 10, timezone: zone }], + language: ['en-US', 'x-private'], + }; + assert.equal(verify(candidate(terms), terms).ok, expected, zone); + } +}); + +test('commercial keyword validation cannot poison ordinary schema-ref validators', () => { + const { getSchemaValidatorByRef } = require('../../dist/lib/validation/schema-loader.js'); + const raw = getSchemaValidatorByRef('media-buy/commercial-terms.json'); + const terms = structuredClone(current); + terms.purchases[0].targeting_overlay = { geo_regions: ['US-NY'], geo_regions_exclude: ['US-NY'] }; + assert.equal(raw(terms), true); + assert.equal(verify(candidate(terms), terms).ok, false); + assert.equal(getSchemaValidatorByRef('media-buy/commercial-terms.json')(terms), true); +}); diff --git a/test/lib/proposal-negotiation-validation.test.js b/test/lib/proposal-negotiation-validation.test.js index 75dc00f36..6782addcb 100644 --- a/test/lib/proposal-negotiation-validation.test.js +++ b/test/lib/proposal-negotiation-validation.test.js @@ -289,33 +289,16 @@ test('commercial-terms verifier rejects fields outside the selected schema', () test('commercial-terms verifier derives newly added binding fields from the selected bundle', () => { const schemaRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'adcp-commercial-terms-schema-')); try { - const mediaBuyDir = path.join(schemaRoot, 'media-buy'); - fs.mkdirSync(mediaBuyDir, { recursive: true }); - fs.writeFileSync(path.join(schemaRoot, 'index.json'), JSON.stringify({ adcp_version: ADCP_VERSION })); - fs.writeFileSync( - path.join(mediaBuyDir, 'commercial-terms.json'), - JSON.stringify({ - $schema: 'http://json-schema.org/draft-07/schema#', - $id: `https://adcontextprotocol.org/schemas/${ADCP_VERSION}/media-buy/commercial-terms.json`, - type: 'object', - properties: { - brand: { type: 'object' }, - purchases: { type: 'array', minItems: 1 }, - start_time: { type: 'string' }, - end_time: { type: 'string' }, - future_binding: { type: 'string' }, - }, - patternProperties: { '^x_': { type: 'string' } }, - required: ['brand', 'purchases', 'start_time', 'end_time'], - additionalProperties: false, - }) - ); - const reviewed = { - brand: { domain: 'buyer.example' }, - purchases: [{}], - start_time: 'asap', - end_time: '2027-02-01T00:00:00Z', - }; + fs.cpSync(path.resolve(__dirname, '../../schemas/cache', ADCP_VERSION), schemaRoot, { + recursive: true, + filter: source => !['bundled', 'mcp'].includes(path.basename(source)), + }); + const schemaFile = path.join(schemaRoot, 'media-buy/commercial-terms.json'); + const schema = JSON.parse(fs.readFileSync(schemaFile, 'utf8')); + schema.properties.future_binding = { type: 'string' }; + schema.patternProperties = { '^x_': { type: 'string' } }; + fs.writeFileSync(schemaFile, JSON.stringify(schema)); + const reviewed = commercialTerms(); const offered = { ...reviewed, future_binding: 'new-contract-value',