Files
ipal-kit/contracts/mail-relay/runner.mjs
T
Radosław SmolińskiandClaude Opus 5.5 2c0262367d IWSN: "Połącz z IWSN" — a person of Intecion connects the site (contract 1.8.0)
- the state block on the e-mail tab (method IWSN): the button while the service offers the confirmation page
  (connectAvailable) or before the site has enrolled; a click asks the site's server for the link
  (POST /api/iapl/mail-relay/connect-link, admin only), which asks the service (POST /v1/connect, enrolling first),
  checks that it begins with the service's own {base}/connect?, and hands it over without storing or logging it;
  the browser opens it in a new tab with noopener noreferrer; the block asks /v1/status every 5 s for 10 min
- states: waiting for confirmation (button), waiting for approval (no page), connected, stopped; 503
  connect-unavailable and 429 said in the admin's language; a load of the panel asks the service while the site waits
- dashboard alert for a waiting site (live); doctor mail-relay-connect (error) — replaces the pending warning and the
  "not enrolled yet" note of mail-relay-state
- opt-out mail.relay.connectButton: false (no button, no route); building blocks requestRelayConnectLink,
  isRelayConnectUrl, RELAY_CONNECT_LINK_PATH; the fake service implements /v1/connect, connectAvailable and
  confirmConnect
- contract copy 1.8.0 (IWDL working tree, checksums match); docs, AGENT.md, setup / upgrade / debug skills, changelog

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-12-01 21:42:23 +01:00

161 lines
7.1 KiB
JavaScript

// 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
}