// Contract test runner for the Intecion Notifications Webservice. // No dependency. Works in Node 20+ and in the Workers runtime (uses only WebCrypto, btoa and TextEncoder). // How to use it: README.md, "The examples and the runner". export const CONTRACT_VERSION = '1.8.0' export class ContractError extends Error { constructor(exampleId, message) { super(`[${exampleId}] ${message}`) this.name = 'ContractError' this.exampleId = exampleId } } /** The confirmation a site's confirm endpoint answers with: lowercase hex SHA-256 of nonce + "." + token. */ export async function confirmationFor(nonce, token) { const bytes = new TextEncoder().encode(`${nonce}.${token}`) const digest = await crypto.subtle.digest('SHA-256', bytes) return [...new Uint8Array(digest)].map((b) => b.toString(16).padStart(2, '0')).join('') } /** Base64 of `n` zero bytes, built without holding the bytes. */ export function base64OfBytes(n) { const full = Math.floor(n / 3) const rest = n % 3 return 'AAAA'.repeat(full) + (rest === 1 ? 'AA==' : rest === 2 ? 'AAA=' : '') } /** Replace {{name}} and { "$base64Bytes": n } everywhere in a value. Unknown names are an error. */ export function expand(value, vars, exampleId = '?') { if (typeof value === 'string') { return value.replace(/\{\{([A-Za-z]+)\}\}/g, (_, name) => { if (vars[name] === undefined || vars[name] === null) { throw new ContractError(exampleId, `the driver's arrange() gave no value for {{${name}}}`) } return String(vars[name]) }) } if (Array.isArray(value)) return value.map((v) => expand(v, vars, exampleId)) if (value && typeof value === 'object') { if (typeof value.$base64Bytes === 'number') return base64OfBytes(value.$base64Bytes) const out = {} for (const [k, v] of Object.entries(value)) out[k] = expand(v, vars, exampleId) return out } return value } /** Every field of `expected` must be in `actual` with that value; `actual` may have more. Arrays must be equal. */ export function subsetMismatch(actual, expected, path = '') { if (expected === null || typeof expected !== 'object') { return Object.is(actual, expected) ? null : `${path || 'value'}: expected ${JSON.stringify(expected)}, got ${JSON.stringify(actual)}` } if (Array.isArray(expected)) { if (!Array.isArray(actual) || actual.length !== expected.length) { return `${path || 'value'}: expected ${JSON.stringify(expected)}, got ${JSON.stringify(actual)}` } for (let i = 0; i < expected.length; i++) { const m = subsetMismatch(actual[i], expected[i], `${path}[${i}]`) if (m) return m } return null } if (actual === null || typeof actual !== 'object') { return `${path || 'value'}: expected an object, got ${JSON.stringify(actual)}` } for (const [k, v] of Object.entries(expected)) { const m = subsetMismatch(actual[k], v, path ? `${path}.${k}` : k) if (m) return m } return null } function headerLookup(headers) { const out = {} for (const [k, v] of Object.entries(headers ?? {})) out[k.toLowerCase()] = v return out } /** * Run one example (direction site-to-service) against a driver. Throws ContractError on the first mismatch. * Returns { request, response, vars } for further checks by the caller. */ export async function runExample(example, driver) { const id = example.id if (example.direction === 'service-to-site') { throw new ContractError(id, 'this example describes the call-back; use runCallbackExample()') } const given = example.given ?? {} const vars = (await driver.arrange(given, example)) ?? {} const headers = expand(example.request.headers ?? {}, given.token === 'none' ? { ...vars, token: '' } : vars, id) if (given.token === 'none') delete headers.authorization const body = example.request.body === undefined ? undefined : expand(example.request.body, vars, id) if (example.request.schema && driver.validate) { const problems = driver.validate(example.request.schema, body) if (problems.length) throw new ContractError(id, `the example's request does not match ${example.request.schema}: ${problems.join('; ')}`) } const request = { method: example.request.method, path: example.request.path, headers, body } const response = await driver.request(request) if (response.status !== example.response.status) { throw new ContractError(id, `status: expected ${example.response.status}, got ${response.status} ${JSON.stringify(response.body)}`) } if (example.response.schema && driver.validate) { const problems = driver.validate(example.response.schema, response.body) if (problems.length) throw new ContractError(id, `the answer does not match ${example.response.schema}: ${problems.join('; ')}`) } if (example.response.body !== undefined) { const m = subsetMismatch(response.body, expand(example.response.body, vars, id)) if (m) throw new ContractError(id, `body: ${m}`) } if (response.body && response.body.ok === false) { const got = headerLookup(response.headers) if (typeof response.body.retryAfter === 'number' && got['retry-after'] !== undefined && String(got['retry-after']) !== String(response.body.retryAfter)) { throw new ContractError(id, `Retry-After header (${got['retry-after']}) differs from retryAfter (${response.body.retryAfter})`) } if (example.client && typeof example.client.retry === 'boolean' && response.body.retryable !== example.client.retry) { throw new ContractError(id, `retryable: expected ${example.client.retry}, got ${response.body.retryable}`) } } const cors = headerLookup(response.headers)['access-control-allow-origin'] if (cors !== undefined) throw new ContractError(id, 'the service must not send CORS headers') if (example.then && driver.mails) { const mails = await driver.mails() if (typeof example.then.mails === 'number' && mails.length !== example.then.mails) { throw new ContractError(id, `mails handed to the back end: expected ${example.then.mails}, got ${mails.length}`) } if (example.then.mail) { const m = subsetMismatch(mails[0], expand(example.then.mail, vars, id), 'mail') if (m) throw new ContractError(id, m) } } return { request, response, vars } } /** * Run a call-back example against a site's confirm endpoint. * `site.prepare(body)` makes the site hold (or not hold) the nonce; `site.confirm(request)` calls the endpoint. */ export async function runCallbackExample(example, site) { const id = example.id if (example.direction !== 'service-to-site') throw new ContractError(id, 'not a call-back example') const holds = example.response.status === 200 await site.prepare({ ...example.request.body, held: holds }) const response = await site.confirm({ ...example.request }) if (response.status !== example.response.status) { throw new ContractError(id, `status: expected ${example.response.status}, got ${response.status}`) } if (holds) { const expected = await confirmationFor(example.request.body.nonce, example.request.body.token) if (!response.body || response.body.confirmation !== expected) { throw new ContractError(id, 'the confirmation is not hex SHA-256 of nonce + "." + token') } } return response }