diff --git a/README.md b/README.md index a8d24a4..ba2e03d 100644 --- a/README.md +++ b/README.md @@ -73,6 +73,8 @@ Run `bun run import:reference /path/to/reference-checkout` to reproduce the impo Reference settings describe per-connection values such as a region, tenant host, or account identifier. Related caveats describe limits in the reference definition. Hosts supply the values and implement the corresponding setup. +Generation and import check credential fields, HTTPS endpoint templates, and event verifier definitions. An invalid definition reports the field that needs attention. These checks establish structure. Vendor compatibility and credential permissions require separate verification. + For a new entry or route, include the vendor documentation for its endpoint and authentication in the pull request. Tests use no service accounts or API keys. The integration order is providers, connectors for agent tools, triggers for incoming events, and channels for conversations. diff --git a/scripts/catalog-yaml.mjs b/scripts/catalog-yaml.mjs index f492b99..51baf4e 100644 --- a/scripts/catalog-yaml.mjs +++ b/scripts/catalog-yaml.mjs @@ -23,6 +23,158 @@ export const referenceSurfaces = ["api", "mcp", "cli", "events", "channel"] const credentialTypes = ["oauth", "oauth_discovered", "secret", "client_credentials"] const settingId = /^[a-z][a-z0-9_]*$/u const gapCapability = /^[a-z]+(?:\.[a-z0-9_]+)+$/u +const placeholder = /\{[A-Za-z][A-Za-z0-9_.-]*\}/gu +const nonempty = value => typeof value === "string" && value.trim() !== "" + +function requireText(value, path) { + if (!nonempty(value)) throw new Error(`${path}: expected nonempty text`) +} + +function requireHttps(value, path) { + if (typeof value === "string" && value.startsWith("https://") && !/\s/u.test(value)) { + const sample = value.replace(placeholder, "example.invalid") + if (!/[{}]/u.test(sample) && URL.canParse(sample) && new URL(sample).hostname !== "") return + } + throw new Error(`${path}: expected an HTTPS URL or a balanced HTTPS template`) +} + +function validateCredential(credential, path) { + if (!isMapping(credential) || !credentialTypes.includes(credential.type)) { + throw new Error(`${path}.type: expected a recognized credential type`) + } + requireText(credential.label, `${path}.label`) + if (credential.type === "secret") { + if (!Array.isArray(credential.fields) || credential.fields.length === 0) { + throw new Error(`${path}.fields: expected a nonempty field array`) + } + const fieldIds = new Set() + for (const [index, field] of credential.fields.entries()) { + const at = `${path}.fields.${index}` + if (!isMapping(field)) throw new Error(`${at}: expected a field mapping`) + requireText(field.id, `${at}.id`) + requireText(field.label, `${at}.label`) + if (fieldIds.has(field.id)) throw new Error(`${at}.id: duplicate credential field`) + fieldIds.add(field.id) + if (field.secret !== undefined && typeof field.secret !== "boolean") { + throw new Error(`${at}.secret: expected a boolean`) + } + } + return + } + if (credential.type === "oauth") requireHttps(credential.authorization_url, `${path}.authorization_url`) + if (credential.type === "oauth_discovered") requireHttps(credential.discover, `${path}.discover`) + if (credential.type !== "oauth_discovered" || credential.token_url !== undefined) { + requireHttps(credential.token_url, `${path}.token_url`) + } + if (credential.scopes !== undefined && + (!Array.isArray(credential.scopes) || credential.scopes.some(scope => typeof scope !== "string"))) { + throw new Error(`${path}.scopes: expected an array of strings`) + } +} + +function validateAccepts(accepts, path) { + if (accepts === undefined) return + if (!Array.isArray(accepts)) throw new Error(`${path}: expected an array`) + for (const [index, acceptance] of accepts.entries()) { + const at = `${path}.${index}` + if (!isMapping(acceptance)) throw new Error(`${at}: expected an acceptance mapping`) + requireText(acceptance.credential, `${at}.credential`) + const { send } = acceptance + if (send === undefined) continue + validateSend(send, `${at}.send`) + } +} + +function validateSend(send, path) { + if (!isMapping(send)) throw new Error(`${path}: expected a send mapping`) + if (send.basic !== undefined) { + if (!isMapping(send.basic)) throw new Error(`${path}.basic: expected username and password`) + requireText(send.basic.username, `${path}.basic.username`) + if (typeof send.basic.password !== "string") throw new Error(`${path}.basic.password: expected text`) + return + } + if (send.path !== undefined) { + if (typeof send.path !== "string" || !/^\/[^/?#.]*\{[A-Za-z0-9_]+\}[^/?#.]*$/u.test(send.path)) { + throw new Error(`${path}.path: expected a single path segment with a credential placeholder`) + } + return + } + requireText(send.header, `${path}.header`) + if (typeof send.value !== "string") throw new Error(`${path}.value: expected text`) +} + +function requireTolerance(value, path) { + if (value !== "host" && (!Number.isFinite(value) || value < 0)) { + throw new Error(`${path}: expected a nonnegative number or host`) + } +} + +function validateTimestamp(timestamp, path) { + if (!isMapping(timestamp)) throw new Error(`${path}: expected timestamp settings`) + if (timestamp.unit !== "s" && timestamp.unit !== "ms") { + throw new Error(`${path}.unit: expected s or ms`) + } + requireTolerance(timestamp.tolerance_seconds, `${path}.tolerance_seconds`) + if (timestamp.value !== undefined) requireText(timestamp.value, `${path}.value`) +} + +function validateVerifier(verifier, path) { + if (!isMapping(verifier)) throw new Error(`${path}: expected a verifier mapping`) + switch (verifier.type) { + case "hmac_sha1": + case "hmac_sha256": + case "ed25519": + requireText(verifier.encoding, `${path}.encoding`) + requireText(verifier.signed_content, `${path}.signed_content`) + if (verifier.header === undefined) { + requireText(verifier.body_field, `${path}.body_field`) + } else { + requireText(verifier.header, `${path}.header`) + requireText(verifier.header_format, `${path}.header_format`) + } + break + case "token": + if (verifier.body_field === undefined) requireText(verifier.header, `${path}.header`) + else requireText(verifier.body_field, `${path}.body_field`) + break + case "standard_webhooks": + requireTolerance(verifier.tolerance_seconds, `${path}.tolerance_seconds`) + break + case "jwt": + case "jws": + for (const key of ["header", "algorithm", "issuer"]) { + requireText(verifier[key], `${path}.${key}`) + } + if (verifier.type === "jwt") requireText(verifier.keys, `${path}.keys`) + if (!isMapping(verifier.claims)) throw new Error(`${path}.claims: expected a mapping`) + break + default: + throw new Error(`${path}.type: expected a recognized verifier`) + } + if (verifier.timestamp !== undefined) validateTimestamp(verifier.timestamp, `${path}.timestamp`) +} + +function validateSurface(name, surface, path) { + validateAccepts(surface.accepts, `${path}.accepts`) + if (name === "mcp") requireHttps(surface.url, `${path}.url`) + if (name === "api") { + for (const key of ["base_url", "url", "description"]) { + if (surface[key] !== undefined) requireHttps(surface[key], `${path}.${key}`) + } + } + if (name === "channel" && surface.base !== undefined && + !/^\{body\.[A-Za-z][A-Za-z0-9_.-]*\}$/u.test(surface.base)) { + requireHttps(surface.base, `${path}.base`) + } + if (name === "events") { + validateVerifier(surface.verify, `${path}.verify`) + if (surface.more_verify !== undefined) { + if (!Array.isArray(surface.more_verify)) throw new Error(`${path}.more_verify: expected an array`) + surface.more_verify.forEach((verifier, index) => + validateVerifier(verifier, `${path}.more_verify.${index}`)) + } + } +} function validateSettingReferences(value, declared, path) { if (typeof value === "string") { @@ -69,15 +221,16 @@ function validateSettings(reference) { } } -function validateCredentialReferences(value, credentials) { +function validateCredentialReferences(value, credentials, path) { if (value === null || typeof value !== "object") return for (const [key, field] of Object.entries(value)) { + const at = `${path}.${key}` if (key === "credential") { if (typeof field !== "string" || !Object.hasOwn(credentials, field)) { - throw new Error(`Unknown credential ${String(field)}`) + throw new Error(`${at}: expected a declared credential`) } } else { - validateCredentialReferences(field, credentials) + validateCredentialReferences(field, credentials, at) } } } @@ -101,9 +254,7 @@ export function validateReference(reference, folder, file) { } for (const [name, credential] of Object.entries(reference.credentials)) { - if (!isMapping(credential) || !credentialTypes.includes(credential.type)) { - throw new Error(`Invalid credential ${name}`) - } + validateCredential(credential, `reference.credentials.${name}`) } for (const [name, source] of Object.entries(reference.sources)) { if ( @@ -122,16 +273,19 @@ export function validateReference(reference, folder, file) { (reference.kind !== "direct" && reference.kind !== "gateway") || !Array.isArray(reference.speaks) || reference.speaks.length === 0 || - reference.speaks.some(protocol => - !isMapping(protocol) || - typeof protocol.format !== "string" || - typeof protocol.base_url !== "string", - ) || (reference.models !== undefined && !isMapping(reference.models)) ) { throw new Error("Invalid provider protocols") } - validateCredentialReferences({ speaks: reference.speaks, models: reference.models }, reference.credentials) + for (const [index, protocol] of reference.speaks.entries()) { + const at = `reference.speaks.${index}` + if (!isMapping(protocol)) throw new Error(`${at}: expected a protocol mapping`) + requireText(protocol.format, `${at}.format`) + requireHttps(protocol.base_url, `${at}.base_url`) + } + validateCredentialReferences( + { speaks: reference.speaks, models: reference.models }, reference.credentials, "reference", + ) return } @@ -148,11 +302,11 @@ export function validateReference(reference, folder, file) { !referenceSurfaces.includes(name) || (name === "cli" ? !Array.isArray(surface) || surface.length === 0 || !surface.every(isMapping) - : !isMapping(surface)) || - (name === "mcp" && typeof surface.url !== "string") + : !isMapping(surface)) ) { throw new Error(`Invalid service surface ${name}`) } + validateSurface(name, surface, `reference.surfaces.${name}`) } - validateCredentialReferences(reference.surfaces, reference.credentials) + validateCredentialReferences(reference.surfaces, reference.credentials, "reference.surfaces") } diff --git a/test/reference-validation.test.mjs b/test/reference-validation.test.mjs new file mode 100644 index 0000000..beddb8d --- /dev/null +++ b/test/reference-validation.test.mjs @@ -0,0 +1,149 @@ +import assert from "node:assert/strict" +import { readdirSync, readFileSync } from "node:fs" +import { test } from "node:test" +import { readDefinition, validateReference } from "../scripts/catalog-yaml.mjs" +import { projectReference } from "../scripts/reference-import.mjs" +import { inputRecord, provider, service } from "./fixtures/reference-import/fixture.mjs" + +const catalogUrl = new URL("../catalog/", import.meta.url) +const catalog = ["providers", "services", "triggers"].flatMap(folder => { + const directory = new URL(`${folder}/`, catalogUrl) + return readdirSync(directory).filter(file => file.endsWith(".yaml")).map(file => ({ + folder, + file, + ...readDefinition(file, readFileSync(new URL(file, directory), "utf8")), + })) +}) + +test("all reference YAML satisfies the generator's structural checks", () => { + for (const { folder, file, reference } of catalog) { + assert.doesNotThrow(() => validateReference(reference, folder, file), `${folder}/${file}`) + } +}) + +function referenceFixture() { + const input = service("example") + Object.assign(input.credentials, { + oauth: { type: "oauth", label: "OAuth", authorization_url: "https://auth.example.com/start", token_url: "https://auth.example.com/token" }, + dynamic: { type: "oauth_discovered", label: "Discovery", discover: "https://example.com/mcp" }, + client: { type: "client_credentials", label: "Service account", token_url: "https://auth.example.com/token" }, + }) + input.surfaces.api = { base_url: "https://example.com", accepts: [{ credential: "oauth", send: { header: "Authorization", value: "Bearer {token}" } }] } + input.surfaces.events = { verify: { type: "hmac_sha256", encoding: "hex", signed_content: "{body}", + header: "x-signature", header_format: "{signature}", timestamp: { unit: "ms", tolerance_seconds: "host" } } } + const record = inputRecord(input) + return projectReference(input, record) +} + +const wrongFields = [ + ["credentials.oauth.label", ""], + ["credentials.oauth.authorization_url", undefined], + ["credentials.oauth.token_url", undefined], + ["credentials.oauth.scopes", "read"], + ["credentials.dynamic.discover", undefined], + ["credentials.client.token_url", "http://example.com"], + ["credentials.client.scopes", [42]], + ["credentials.secret.fields", []], + ["credentials.secret.fields.0", "token"], + ["credentials.secret.fields.0.id", ""], + ["credentials.secret.fields.0.label", ""], + ["credentials.secret.fields.0.secret", "yes"], + ["credentials.secret.fields.1", { id: "token", label: "Duplicate" }], + ["surfaces.mcp.url", "https://"], + ["surfaces.mcp.url", "https://{tenant/mcp"], + ["surfaces.mcp.url", "https://{invalid placeholder}/mcp"], + ["surfaces.api.base_url", "http://example.com"], + ["surfaces.api.accepts", { credential: "oauth" }], + ["surfaces.api.accepts.0", "oauth"], + ["surfaces.api.accepts.0.credential", "unknown"], + ["surfaces.api.accepts.0.send.header", ""], + ["surfaces.api.accepts.0.send.value", 42], + ["surfaces.events.verify", undefined], + ["surfaces.events.verify", {}], + ["surfaces.events.verify.type", "unknown"], + ["surfaces.events.verify.encoding", ""], + ["surfaces.events.verify.signed_content", false], + ["surfaces.events.verify.header_format", undefined], + ["surfaces.events.verify.timestamp.unit", "minutes"], + ["surfaces.events.verify.timestamp.tolerance_seconds", -1], + ["surfaces.events.verify.timestamp.tolerance_seconds", Infinity], + ["surfaces.events.verify.timestamp.value", {}], +] + +test("required credential, endpoint, and verifier fields identify their path on failure", async t => { + const valid = referenceFixture() + validateReference(valid, "services", "example.yaml") + for (const [path, replacement] of wrongFields) { + await t.test(`invalid ${path} ${String(replacement)}`, () => { + const malformed = structuredClone(valid) + const segments = path.split(".") + const key = segments.pop() + const parent = segments.reduce((value, segment) => value[segment], malformed) + if (replacement === undefined) delete parent[key] + else parent[key] = replacement + assert.throws(() => validateReference(malformed, "services", "example.yaml"), error => { + const expectedPath = `reference.${path}` + assert.ok(error.message.includes(expectedPath), error.message) + return true + }) + }) + } +}) + +test("provider protocol bases are URLs and preserve valid address placeholders", () => { + const input = provider("model") + const record = inputRecord(input, "a".repeat(40), "providers") + const reference = projectReference(input, record) + validateReference(reference, record.folder, record.file) + reference.speaks[0].base_url = "https://example.com/{account_id}}/v1" + assert.throws(() => validateReference(reference, record.folder, record.file), /reference\.speaks\.0\.base_url/u) +}) + +test("preserves source variants for compound signatures, body tokens, and token claims", () => { + for (const [id, type] of [ + ["mailgun", "hmac_sha256"], ["persona", "hmac_sha256"], ["zoho-crm", "token"], + ["render", "standard_webhooks"], ["gmail", "jwt"], ["netlify", "jws"], ["discord", "ed25519"], + ]) { + const { reference, folder, file } = catalog.find(entry => entry.id === id) + assert.equal(reference.surfaces.events.verify.type, type) + validateReference(reference, folder, file) + } + const teams = catalog.find(entry => entry.id === "microsoft-teams") + assert.equal(teams.reference.surfaces.channel.base, "{body.serviceUrl}") + validateReference(teams.reference, teams.folder, teams.file) +}) + +test("verification variants require their own fields", async t => { + for (const [id, path, value] of [ + ["mailgun", "body_field", undefined], + ["zoho-crm", "body_field", ""], + ["render", "tolerance_seconds", "unknown"], + ["gmail", "keys", ""], + ["gmail", "claims", []], + ["netlify", "algorithm", ""], + ["netlify", "issuer", undefined], + ]) { + await t.test(`${id} ${path}`, () => { + const { reference, folder, file } = catalog.find(entry => entry.id === id) + const malformed = structuredClone(reference) + malformed.surfaces.events.verify[path] = value + assert.throws(() => validateReference(malformed, folder, file), error => + error.message.includes(`reference.surfaces.events.verify.${path}`)) + }) + } +}) + +test("preserves the upstream Basic and path credential send forms", () => { + for (const [id, variant, malformed] of [ + ["mailgun", "basic", { username: "example", password: false }], + ["telegram", "path", "/multiple/segments/{token}"], + ]) { + const { reference, folder, file } = catalog.find(entry => entry.id === id) + const entry = structuredClone(reference) + const send = entry.surfaces.api.accepts.find(acceptance => acceptance.send?.[variant] !== undefined).send + validateReference(entry, folder, file) + send[variant] = malformed + assert.throws(() => validateReference(entry, folder, file), error => + error.message.includes(`send.${variant}`)) + } +})