// kit/grietens-engine-check.mjs: test a quote engine WITHOUT a running Grietens (Decisions 127 and 132, docs/QUOTES.md). // ONE file, Node 18+, nothing but Node's own modules: copy it next to your engine. Served at // https://app.grietens.cloud/kit/grietens-engine-check.mjs. The recommended setup it reports on: https://grietens.cloud/kit/setup.md // // node grietens-engine-check.mjs --url http://localhost:8787/quote // // It plays Grietens' part with a THROWAWAY Ed25519 key pair it makes now and serves itself at // /.well-known/grietens-keys.json: start your engine with its Grietens address set to the checker (for the kit: // grietensUrl / GRIETENS_URL = http://127.0.0.1:8799). Then it // * reads the engine card (GET --url, not signed) and checks its fields (an optional "workspace": the public id of the Grietens // account that adds the engine from inside with add_quote_engine; an optional "terms": the Data Terms version the person who runs // the engine accepts for the shop, which it reports), // * sends a signed hello and checks the answer carries the nonce and is signed with the CARD's key for THIS hello (purpose hello, // the engine's address, the nonce); that the same hello sent again, a request signed 10 minutes ago, one signed with another key // and one signed for another engine's address are refused, and that a refusal is never signed, // * sends a signed request and checks the FIRST answer is contract 1 and signed for that request (purpose answer, its request id), // * waits for the finished quote: the engine's callback (checked: purpose callback, the request id) or by asking GET / // (each check answer checked: purpose answer, the request id), and asks once for an id the engine never got (it should say 404), // * sends the same request again (the same quote, signed again). // * Decision 166: sends two more requests shaped as Grietens sends them, one with "facts" ({ key: text, number or true / false }) and // one with a file link the checker serves itself (a small PDF, as a real link: fetch it at once), and checks each is answered in // contract 1, signed for its request, and finished as a quote or a decline: "failed", an error or no answer fails the check. // * shows every LIVE UPDATE the engine sends while it works (a {"progress": …} body to the callback address: its label, step, percent and // the items it adds to the buyer's feed) and checks each is signed for the request (purpose progress, version 2 or 3 naming this // checker as the audience): Grietens ignores an unsigned one. Each PICTURE and FILE a live update names is fetched as Grietens fetches it // (the same host name as the engine's address, any path; https on 443, except that against a local http engine the checker allows // its own scheme and port; a 307 / 308 to that same host followed, any other redirect not; at most 10 MB an item, 100 MB a request // (and 256 KB of text a request: past it Grietens drops the oldest items from the buyer's view); // the bytes decide, a `picture` must be a PNG, JPEG or WebP picture) and printed: kept (kind, size), or why Grietens would not keep // it and what to fix. An item that would not be kept fails the check. // * sends the request's optional "language" ("lv" or "en", the language of the buyer's page: --language), and warns when an UNSIGNED // POST that is not JSON is answered with anything but 401 (the current kits refuse it before reading its body). // * Decision 137: fetches every file the quote lists and the card's logo as Grietens does (from the engine's own host, no redirect to // another host, the bytes decide: PDF, PNG, JPEG, WebP shown; DXF, DWG, IFC, STEP downloads; at most 5 files, 10 MB each, 25 MB together; // a logo at most 512 KB and never an SVG). // * when the card asks for it ("notices": ["buyer_contact"]), sends one made-up buyer-contact notice, signed as Grietens signs it (purpose // buyer-contact), and checks the engine answers 2xx, // * ends with a "Recommended setup" report: one line per item of https://grietens.cloud/kit/setup.md, done or todo with the fix in a few // words. Advice only: it never changes the result or the exit code. // Each signature that fails is named: which answer, and what it should have been bound to. Exit code 0 = every MUST passed. // // --url
the engine's address. http://localhost is fine HERE; Grietens itself calls only public https on 443. // --product product_hint (default roof_trusses) --notes --needed-by --quantity // --language lv|en|none the request's "language" (default en; none leaves it out, as Grietens does when it does not know it) // --file a file link to send (repeat for more). Your engine must fetch it at once: real links live 60 minutes. // --wait how long to wait for a pending quote (default 1500 = 25 minutes) // --callback-base where YOUR ENGINE can reach this checker (default http://127.0.0.1:: right when both run on one // machine). With an engine on another machine and no tunnel, the checker still gets the quote by asking. // --port the checker's port: its published keys and the callback door (default 8799) // --cold the engine may be asleep (hosting that sleeps when idle): the first call may take up to 60 s here, and // when it took longer than 10 s the checker says what Grietens does with such an engine // --keys accepted and ignored (keys are the only way this checker speaks) // // The signed texts below are the ones Grietens builds, byte for byte (test/kit_signing_texts.mjs in the Grietens code base compares // them with the server's own code for a table of cases). import http from 'node:http'; import crypto from 'node:crypto'; import fs from 'node:fs'; import path from 'node:path'; import { fileURLToPath } from 'node:url'; export const CONTRACT = '1'; export const SIG_VERSION = 'grietens-sig/2'; export const ENGINE_CALL_V3 = 'grietens-sig/3'; // Decision 138: an engine's own call names its audience (the Grietens origin) export const KEY_SKEW_S = 300; export const QUOTE_LIMITS = Object.freeze({ timeoutMs: 10_000, attempts: 4, retryAfterS: Object.freeze([20, 120, 600]), text: 4000, word: 500, words: 200 }); export const ANSWER_STATUSES = Object.freeze(['pending', 'needs_review', 'questions', 'declined', 'failed']); // 'questions': Decision 182 const QUOTE_KINDS = ['estimate', 'quote']; const SPKI_ED25519 = Buffer.from('302a300506032b6570032100', 'hex'); const B64U32 = /^[A-Za-z0-9_-]{43}$/; const NONCE = /^[A-Za-z0-9_-]{16,64}$/; // ── the signed texts ────────────────────────────────────────────────────────────────────────────────────────────────────── const line = (v) => String(v ?? '').replace(/[\r\n]/g, ' '); const lines = (parts) => parts.map(line).join('\n'); export const sha256Hex = (bytes) => crypto.createHash('sha256').update(Buffer.isBuffer(bytes) ? bytes : Buffer.from(String(bytes ?? ''), 'utf8')).digest('hex'); export const signingText = { request: ({ purpose, method, audience, path: p, ts, nonce, bodyHash }) => lines([SIG_VERSION, 'grietens-request', purpose, String(method).toUpperCase(), audience, p, ts, nonce, bodyHash]), engineCall: ({ purpose, method, path: p, engineUrl, ts, nonce, bodyHash }) => lines([SIG_VERSION, 'engine-call', purpose, String(method).toUpperCase(), p, engineUrl, ts, nonce, bodyHash]), engineCallV3: ({ purpose, method, path: p, engineUrl, audience, ts, nonce, bodyHash }) => lines([ENGINE_CALL_V3, 'engine-call', purpose, String(method).toUpperCase(), p, engineUrl, audience, ts, nonce, bodyHash]), engineAnswer: ({ purpose, engineUrl, bound, ts, bodyHash }) => lines([SIG_VERSION, 'engine-answer', purpose, engineUrl, bound, ts, bodyHash]), rotation: (engineUrl, nonce, newPublicKey) => lines([SIG_VERSION, 'key-rotation', engineUrl, nonce, newPublicKey]), }; // The ONE form of an engine's address both sides sign (the same rules as Grietens and both kits; test/fixtures/engine-addresses.json) export function canonicalEngineUrl(text) { const raw = String(text ?? ''); if (/[\x00-\x20\x7f-\x9f\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]/.test(raw)) throw new Error('an engine address may not hold a space, a tab, a line break or another control character'); const m = /^([A-Za-z][A-Za-z0-9+.-]*):\/\/([^/?#]*)(.*)$/s.exec(raw); if (!m || !['https', 'http'].includes(m[1].toLowerCase())) throw new Error('that is not an https address'); if (m[2].includes('@')) throw new Error('an address with a user name or password in it is not allowed'); if (/[^\x00-\x7f]/.test(m[2])) throw new Error('write the host of an engine address in its plain "xn--" form (IDNA)'); const h = /^([A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)*)\.?(?::([0-9]{1,5}))?$/.exec(m[2]); const n = h && h[2] !== undefined ? Number(h[2]) : null; if (!h || (n !== null && (n < 1 || n > 65535))) throw new Error('the host must be a plain DNS name (letters, digits, "-", "."), the port 1 to 65535'); const p = m[3]; const bad = /[?#]/.test(p) || !/^[A-Za-z0-9\-._~!$&'()*+,;=:@/%]*$/.test(p) || p.split('/').some((x) => /^(%2e|\.){1,2}$/i.test(x)) || (p.match(/%(..)?/g) || []).some((e) => !/^%[0-9A-F]{2}$/.test(e) || /[A-Za-z0-9\-._~]/.test(String.fromCharCode(parseInt(e.slice(1), 16)))); if (bad) throw new Error('no query or fragment, and the path must be plain ASCII, with no "." or ".." segment and no needless percent-escape'); const scheme = m[1].toLowerCase(); const port = n === null || n === (scheme === 'https' ? 443 : 80) ? '' : `:${n}`; return `${scheme}://${h[1].toLowerCase()}${port}${p.replace(/\/+$/, '')}`; } // ── keys and signatures ─────────────────────────────────────────────────────────────────────────────────────────────────── export const isPublicKey = (s) => typeof s === 'string' && B64U32.test(s) && Buffer.from(s, 'base64url').length === 32; const publicKeyObject = (b64u) => crypto.createPublicKey({ key: Buffer.concat([SPKI_ED25519, Buffer.from(b64u, 'base64url')]), format: 'der', type: 'spki' }); const rawPublicKey = (k) => crypto.createPublicKey(k).export({ format: 'der', type: 'spki' }).subarray(SPKI_ED25519.length).toString('base64url'); const canonicalSig = (s) => typeof s === 'string' && /^[A-Za-z0-9_-]{86}$/.test(s) && Buffer.from(s, 'base64url').toString('base64url') === s; export const newNonce = () => crypto.randomBytes(18).toString('base64url'); export const newRequestId = () => `r-${crypto.randomBytes(10).toString('hex')}`; // a throwaway key pair, as Grietens publishes its own: { kid, privateKey, publicKey (raw, base64url) } export function keyPair() { const { privateKey } = crypto.generateKeyPairSync('ed25519'); const publicKey = rawPublicKey(privateKey); return { kid: `g1-${crypto.createHash('sha256').update(Buffer.from(publicKey, 'base64url')).digest('base64url').slice(0, 16)}`, privateKey, publicKey }; } const signText = (privateKey, t) => crypto.sign(null, Buffer.from(t, 'utf8'), privateKey).toString('base64url'); // Grietens → an engine: the five headers of one call (purpose quote-request | hello | check; body: the bytes sent, a GET none) export function requestHeaders(pair, { purpose, method, audience, path: p, body = null, nowMs = Date.now(), nonce = newNonce() }) { const ts = String(Math.floor(nowMs / 1000)); return { 'x-grietens-key-id': pair.kid, 'x-grietens-timestamp': ts, 'x-grietens-nonce': nonce, 'x-grietens-purpose': purpose, 'x-grietens-signature-ed25519': signText(pair.privateKey, signingText.request({ purpose, method, audience, path: p, ts, nonce, bodyHash: sha256Hex(body ?? '') })) }; } // An engine's answer: purpose hello (bound to the hello's nonce), answer, callback or progress (bound to the request id) → null, or why not. // version '3' (X-Engine-Sig-Version): the text names the audience, the Grietens it is for (here: this checker's own origin) export function engineAnswerProblem(publicKey, { purpose, engineUrl, bound, ts, sig, body, nowMs = Date.now(), version = null, audience = null }) { if (!sig) return 'it carries no X-Engine-Signature-Ed25519 header'; const t = String(ts ?? '').trim(); if (!/^\d{9,11}$/.test(t)) return 'its X-Engine-Timestamp is missing or not unix seconds'; if (Math.abs(Number(t) - Math.floor(nowMs / 1000)) > KEY_SKEW_S) return 'its X-Engine-Timestamp is more than 5 minutes off'; if (!canonicalSig(String(sig))) return 'its signature is not one Ed25519 signature in canonical base64url'; let ok = false; try { const text = String(version ?? '').trim() === '3' ? [ENGINE_CALL_V3, 'engine-answer', purpose, engineUrl, audience, bound, t, sha256Hex(body)].map((v) => String(v ?? '').replace(/[\r\n]/g, ' ')).join('\n') : signingText.engineAnswer({ purpose, engineUrl, bound, ts: t, bodyHash: sha256Hex(body) }); ok = crypto.verify(null, Buffer.from(text, 'utf8'), publicKeyObject(publicKey), Buffer.from(String(sig), 'base64url')); } catch { ok = false; } return ok ? null : `its signature does not verify with the card's key for purpose ${purpose}, the address ${engineUrl}, bound to ${bound} and these exact bytes`; } export const engineAnswerOk = (publicKey, o) => isPublicKey(publicKey) && !!o.bound && !engineAnswerProblem(publicKey, o); // ── what an engine says (the same rules as Grietens' parser) ───────────────────────────────────────────────────────────────── const num = (v) => (typeof v === 'number' && Number.isFinite(v) ? v : typeof v === 'string' && v.trim() !== '' && Number.isFinite(Number(v)) ? Number(v) : null); const words = (v) => (Array.isArray(v) ? v.filter((x) => typeof x === 'string' && x.trim()).map((x) => x.trim().slice(0, QUOTE_LIMITS.word)).slice(0, QUOTE_LIMITS.words) : null); const obj = (v) => (v && typeof v === 'object' && !Array.isArray(v) ? v : null); function isoDate(v) { const m = /^(\d{4})-(\d{2})-(\d{2})(?:$|T)/.exec(String(v).trim()); if (!m) return undefined; const d = new Date(Date.UTC(+m[1], +m[2] - 1, +m[3])); return d.getUTCFullYear() === +m[1] && d.getUTCMonth() === +m[2] - 1 && d.getUTCDate() === +m[3] ? `${m[1]}-${m[2]}-${m[3]}` : undefined; } // Decision 138: the same bounds as Grietens' parser (lib/quotes/contract.js ANSWER_BOUNDS) const ANSWER_BOUNDS = { priceMax: 1e9, leadDaysMax: 3650, validDaysMax: 731, keysMax: 50, keyChars: 60, valueChars: 2000, objectBytes: 8192 }; const KNOWN = new Set(['contract', 'quote_id', 'request_id', 'shop_id', 'status', 'kind', 'price', 'range', 'currency', 'scope', 'assumptions', 'not_included', 'quantities', 'lead_time_days', 'lead_time_source', 'valid_until', 'artifacts', 'message', 'files', 'questions', 'note']); // Decision 182: what the factory asks the buyer back, as the server reads it (lib/quotes/contract.js parseQuestions): 1 to 10 of {key, ask, kind}, // key a fact key, ask 1 to 300 characters, kind text | number (an optional unit, at most 12 characters) | choice (2 to 20 choices) | choices // (several of 2 to 20 choices; the answer is a list) | file | yes_no | date (the answer is YYYY-MM-DD), one key once → the problem, or null export const QUESTION_KINDS = Object.freeze(['text', 'number', 'choice', 'choices', 'file', 'yes_no', 'date']); export function questionsProblem(raw) { if (!Array.isArray(raw) || !raw.length) return 'questions is a list of {key, ask, kind} (at least one)'; if (raw.length > 10) return 'questions: at most 10 at a time'; const seen = new Set(); for (const [i, q] of raw.entries()) { if (!q || typeof q !== 'object' || Array.isArray(q)) return `questions[${i}] is not {key, ask, kind}`; const key = typeof q.key === 'string' ? q.key.trim().normalize('NFC') : ''; if (!key || [...key].length > 60 || !/^[\p{L}\p{N}][\p{L}\p{M}\p{N}_.-]*$/u.test(key)) return `questions[${i}].key is a fact key (letters, digits and _ . -, at most 60)`; if (typeof q.ask !== 'string' || !q.ask.trim() || q.ask.trim().length > 300) return `questions[${i}].ask is the question in plain words, 1 to 300 characters`; const kind = String(q.kind ?? 'text').trim().toLowerCase(); if (!QUESTION_KINDS.includes(kind)) return `questions[${i}].kind is one of ${QUESTION_KINDS.join(', ')}`; if ((kind === 'choice' || kind === 'choices') && !(Array.isArray(q.choices) && q.choices.length >= 2 && q.choices.length <= 20)) return `questions[${i}].choices: a ${kind} question lists 2 to 20 choices`; if (kind === 'number' && q.unit != null && q.unit !== '' && !(typeof q.unit === 'string' && q.unit.trim() && [...q.unit.trim()].length <= 12)) return `questions[${i}].unit is a short unit in plain text, 1 to 12 characters (e.g. "mm", "m²", "pcs")`; if (seen.has(key)) return `questions[${i}].key ${key} is asked twice`; seen.add(key); } return null; } const amount = (v) => { const n = num(v); return n != null && n > 0 && n <= ANSWER_BOUNDS.priceMax ? n : null; }; function boundedObject(v, value) { if (!v || typeof v !== 'object' || Array.isArray(v)) return null; const out = {}; for (const [k, x] of Object.entries(v).slice(0, ANSWER_BOUNDS.keysMax)) { const key = String(k).trim().slice(0, ANSWER_BOUNDS.keyChars); const val = value(x); if (key && val != null) out[key] = val; } return Object.keys(out).length && JSON.stringify(out).length <= ANSWER_BOUNDS.objectBytes ? out : null; } const quantityOf = (x) => { const n = num(x); return n != null && n >= 0 && n <= 1e12 ? n : null; }; const linkOf = (x) => (typeof x === 'string' && x.length <= ANSWER_BOUNDS.valueChars && /^https:\/\/[^\s<>"']+$/i.test(x.trim()) ? x.trim() : null); function quoteValues(a, warnings, { nowMs = Date.now() } = {}) { const v = {}; if (a.price != null) { v.price = amount(a.price); if (v.price == null) warnings.push(`price is not a number above 0 and at most ${ANSWER_BOUNDS.priceMax}: left out`); } if (a.range != null) { const lo = Array.isArray(a.range) ? amount(a.range[0]) : null, hi = Array.isArray(a.range) ? amount(a.range[1]) : null; if (lo == null || hi == null || lo > hi || a.range.length !== 2) warnings.push('range is not [low, high], both above 0 and low ≤ high: left out'); else { v.range_low = lo; v.range_high = hi; } } if (a.currency != null) { const c = String(a.currency).trim().toUpperCase(); if (/^[A-Z]{3}$/.test(c)) v.currency = c; else warnings.push('currency is not a three-letter code (EUR): left out'); } for (const k of ['scope', 'assumptions']) if (a[k] != null) { const w = words(a[k]); if (w) v[k] = w; else warnings.push(`${k} is not a list of words: left out`); } if (a.not_included != null && !words(a.not_included)) warnings.push('not_included is not a list of words: left out'); if (a.quantities != null) { const o = boundedObject(a.quantities, quantityOf); if (o) v.quantities = o; else warnings.push('quantities is not an object of numbers (at most 50, 8 KB): left out'); } if (a.artifacts != null) { const o = boundedObject(a.artifacts, linkOf); if (o) v.artifacts = o; else warnings.push('artifacts is not an object of https links (at most 50, 8 KB): left out'); } if (a.lead_time_days != null) { const n = num(a.lead_time_days); if (n != null && n >= 0 && n <= ANSWER_BOUNDS.leadDaysMax) v.lead_time_days = Math.round(n); else warnings.push(`lead_time_days is not a number of days from 0 to ${ANSWER_BOUNDS.leadDaysMax}: left out`); } if (a.valid_until != null) { const d = isoDate(a.valid_until), t = d ? Date.parse(`${d}T00:00:00Z`) : NaN; if (d && t >= nowMs - 86400e3 * 2 && t <= nowMs + 86400e3 * ANSWER_BOUNDS.validDaysMax) v.valid_until = d; else warnings.push('valid_until is not a date (YYYY-MM-DD) from today to two years ahead: left out'); } if (a.kind != null) { const k = String(a.kind).trim().toLowerCase(); if (QUOTE_KINDS.includes(k)) v.kind = k; else warnings.push(`kind is ${QUOTE_KINDS.join(' or ')}: left out (an estimate)`); } return v; } // Decision 137: the files an answer lists ({name?, url, type?}); Grietens fetches each from the engine's own host and keeps its copy const ANSWER_FILE_LIMITS = { entries: 20, name: 200, url: 1000 }; export function parseAnswerFiles(raw, warnings = []) { if (raw == null) return []; if (!Array.isArray(raw)) { warnings.push('files is not a list of {name, url, type}: left out'); return []; } const out = []; if (raw.length > ANSWER_FILE_LIMITS.entries) warnings.push(`files lists ${raw.length} entries: only the first ${ANSWER_FILE_LIMITS.entries} are read`); raw.slice(0, ANSWER_FILE_LIMITS.entries).forEach((f, i) => { if (!f || typeof f !== 'object' || Array.isArray(f) || typeof f.url !== 'string') { warnings.push(`files[${i}] has no url: left out`); return; } const url = f.url.trim(); let u = null; try { u = new URL(url); } catch { u = null; } if (!u || !/^https?:$/.test(u.protocol) || u.username || u.password || url.length > ANSWER_FILE_LIMITS.url) { warnings.push(`files[${i}].url is not a web address of at most ${ANSWER_FILE_LIMITS.url} characters: left out`); return; } const last = (() => { try { return decodeURIComponent(u.pathname.split('/').filter(Boolean).pop() || ''); } catch { return ''; } })(); const name = Array.from(String(typeof f.name === 'string' && f.name.trim() ? f.name : last || 'file').replace(/[\u0000-\u001f\u007f]/g, ' ').replace(/\s+/g, ' ').trim() .toWellFormed()).slice(0, ANSWER_FILE_LIMITS.name).join('') || 'file'; // whole characters: a cut never splits a pair const type = typeof f.type === 'string' && f.type.trim() ? f.type.trim().toLowerCase().slice(0, 100) : null; out.push({ name, url: u.toString(), type }); }); return out; } // What Grietens makes of a file's BYTES (the same rules as its server: test/kit_signing_texts.mjs compares them) → { kind: // 'picture' | 'pdf' | 'download', ext } or { refused: why }. At most 10 MB a file, 5 files and 25 MB an answer. export const QUOTE_FILE_LIMITS = Object.freeze({ files: 5, bytes: 10 * 1024 * 1024, total: 25 * 1024 * 1024 }); // the shared sniffer's rules (lib/open-requests/files.js): a drawing needs its real opening, and no file whose first kilobytes hold an // HTML or script tag is taken const CAD_OPENING = { step: /^\uFEFF?\s*ISO-10303-21;/, ifc: /^\uFEFF?\s*ISO-10303-21;/, dxf: /^(?:\uFEFF?\s*(?:0\s*\r?\n\s*SECTION\b|999\s*\r?\n)|AutoCAD Binary DXF\r\n\x1a\x00)/, dwg: /^(?:AC1\d{3}|AC[12]\.\d|MC0\.0)/, }; const HTML_TAG = /<(?:!doctype\s+html|html|head|body|script|iframe|frame|frameset|object|embed|svg|img|meta|link|style|form|base|math|video|audio|a\s[^>]{0,200}href)[\s>/]/i; export function fileKind(b, name = '') { const starts = (bytes, at = 0) => bytes.every((x, i) => b[at + i] === x); if (!Buffer.isBuffer(b) || !b.length) return { refused: 'the file is empty' }; if (b.length > QUOTE_FILE_LIMITS.bytes) return { refused: 'the file is larger than 10 MB' }; const ext = (/\.([A-Za-z0-9]{1,6})$/.exec(String(name).trim())?.[1] || '').toLowerCase(); if ((starts([0x4d, 0x5a]) && b.subarray(0, 64).includes(0)) || starts([0x7f, 0x45, 0x4c, 0x46]) || starts([0xfe, 0xed, 0xfa]) || starts([0xce, 0xfa, 0xed, 0xfe]) || starts([0xcf, 0xfa, 0xed, 0xfe]) || starts([0xca, 0xfe, 0xba, 0xbe]) || starts([0x23, 0x21]) || starts([0x50, 0x4b]) || starts([0x1f, 0x8b]) || starts([0x37, 0x7a, 0xbc, 0xaf]) || starts([0x52, 0x61, 0x72, 0x21]) || /^\s*<(!doctype html|html|script|svg|\?xml)\b/i.test(b.subarray(0, 512).toString('utf8')) || HTML_TAG.test(b.subarray(0, 4096).toString('latin1'))) { return { refused: 'programs, scripts, archives and web pages are not taken: send a PDF, a photo or a drawing' }; } if (starts([0x25, 0x50, 0x44, 0x46, 0x2d])) return { kind: 'pdf', ext: 'pdf' }; // %PDF- at the very first byte if (starts([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])) return { kind: 'picture', ext: 'png' }; if (starts([0xff, 0xd8, 0xff])) return { kind: 'picture', ext: 'jpg' }; if (starts([0x52, 0x49, 0x46, 0x46]) && b.subarray(8, 12).toString('latin1') === 'WEBP') return { kind: 'picture', ext: 'webp' }; if (b.subarray(4, 8).toString('latin1') === 'ftyp') { const brand = b.subarray(8, 12).toString('latin1'); if (['heic', 'heix', 'hevc', 'hevx', 'heim', 'heis'].includes(brand)) return { kind: 'download', ext: 'heic' }; if (['mif1', 'msf1'].includes(brand)) return { kind: 'download', ext: 'heif' }; return { refused: 'that kind of file is not taken here' }; } const cad = { dwg: 'dwg', dxf: 'dxf', ifc: 'ifc', step: 'step', stp: 'step' }[ext]; // a text drawing saved as UTF-8 with a byte-order mark opens after its three mark bytes (as the server reads it) const cadHead = b[0] === 0xef && b[1] === 0xbb && b[2] === 0xbf ? b.subarray(3, 1027) : b.subarray(0, 1024); if (cad && !CAD_OPENING[cad].test(cadHead.toString('latin1'))) return { refused: 'that kind of file is not taken here' }; return cad ? { kind: 'download', ext: cad } : { refused: /^(exe|dll|bat|cmd|ps1|vbs|js|mjs|jar|sh|py|php|msi|apk|zip|rar|7z|gz|tar|html?|svg|xml)$/.test(ext) ? 'programs, scripts, archives and web pages are not taken: send a PDF, a photo or a drawing' : 'that kind of file is not taken here' }; } // Where Grietens fetches a file or a live picture from (the server's rule, test/kit_signing_texts.mjs compares them): https on port 443, // on the SAME host NAME as the engine's address (lowercased, a trailing dot dropped), at any path → null, or why not. local: the checker // plays Grietens against a local http engine, so there the engine's own scheme and port are allowed too (Grietens itself needs https on 443) export const FILE_HOST_WORDS = Object.freeze({ host: "the file is not on the engine's own host: Grietens fetches files only from the host name of the address the engine joined at (any path on it)", https: 'the file address must be https on port 443', }); const hostOf = (h) => String(h || '').toLowerCase().replace(/\.$/, ''); export function fileAddressProblem(fileUrl, engineHost, { local = null } = {}) { let u; try { u = new URL(fileUrl); } catch { return FILE_HOST_WORDS.https; } const sameHost = !!engineHost && hostOf(u.hostname) === hostOf(engineHost); if (local && sameHost && u.protocol === local.protocol && u.port === local.port) return null; if (u.protocol !== 'https:' || (u.port && u.port !== '443')) return FILE_HOST_WORDS.https; return sameHost ? null : FILE_HOST_WORDS.host; } // What Grietens keeps a file's or a live item's bytes as (the server's keptAs): { kind, ext } or { refused }; pictureOnly: a live update's // `picture` item must be a picture by its bytes export const PICTURE_ONLY_WORDS = 'this item is a picture: the file is not a PNG, JPEG or WebP picture, so it was not kept'; export function keptAs(b, name = '', { pictureOnly = false } = {}) { const k = fileKind(b, name); if (k.refused) return k; return pictureOnly && k.kind !== 'picture' ? { refused: PICTURE_ONLY_WORDS } : k; } export const LIVE_FILE_LIMITS = Object.freeze({ bytes: 10 * 1024 * 1024, perRequest: 100 * 1024 * 1024 }); // → { ok: true, answer: { status, quote_id, request_id, message, values, warnings, files } } | { ok: false, problem } export function parseAnswer(json, { requestId = null } = {}) { if (!json || typeof json !== 'object' || Array.isArray(json)) return { ok: false, problem: 'the answer is not a JSON object' }; if (json.contract != null && String(json.contract) !== CONTRACT) return { ok: false, problem: `the answer speaks contract ${String(json.contract).slice(0, 20)}, not ${CONTRACT}` }; const status = String(json.status ?? ''); if (!ANSWER_STATUSES.includes(status)) return { ok: false, problem: `the answer's status must be one of ${ANSWER_STATUSES.join(', ')} (got ${JSON.stringify(json.status ?? null).slice(0, 40)})` }; if (json.request_id != null && requestId && String(json.request_id) !== requestId) return { ok: false, problem: `the answer is for another request (${String(json.request_id).slice(0, 40)})` }; const warnings = []; // Decision 138: a quote id is a plain identifier (it becomes the check address's last segment) let quoteId = json.quote_id == null || json.quote_id === '' ? null : String(json.quote_id).slice(0, 200); if (quoteId != null && !(/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,199}$/.test(quoteId) && !quoteId.includes('..'))) { warnings.push('quote_id is not a plain identifier (letters, digits, - _ . :): left out'); quoteId = null; } const values = quoteValues(json, warnings); const unknown = Object.keys(json).filter((k) => !KNOWN.has(k)); if (unknown.length) warnings.push(`fields outside the contract were left out: ${unknown.slice(0, 10).map((k) => String(k).slice(0, 40)).join(', ')}`); const files = parseAnswerFiles(json.files, warnings); return { ok: true, answer: { status, quote_id: quoteId, request_id: json.request_id == null ? null : String(json.request_id), message: json.message == null ? null : String(json.message).slice(0, QUOTE_LIMITS.text), values, warnings, files } }; } export function missingForReview(values) { if (values.price == null) return "the engine's quote has no price"; if (!values.currency) return "the engine's quote has no currency"; if (!values.scope?.length) return "the engine's quote has no scope"; return null; } // The engine card (the same required fields and rules as Grietens' join) → { ok: true, card } | { ok: false, problem } const COMPANY = /^[\p{L}\p{N}][\p{L}\p{M}\p{N} .,&'’"„“”«»()\-\/+:#]*$/u; const cleanCompany = (v) => { const s = String(v ?? '').normalize('NFC').replace(/\s+/g, ' ').trim(); return s.length >= 2 && s.length <= 100 && COMPANY.test(s) ? s : null; }; const oneLine = (s, n) => String(s ?? '').replace(/[\p{C}\p{Zl}\p{Zp}]/gu, ' ').replace(/\s+/g, ' ').trim().slice(0, n); const NOTICES = ['buyer_contact']; const CARD = { products: 50, product: 60, about: 300, town: 120, website: 300, logo: 500, languages: ['en', 'lv'] }; export function parseCard(json) { const no = (problem) => ({ ok: false, problem }); if (!json || typeof json !== 'object' || Array.isArray(json)) return no('it is not a JSON object'); if (String(json.grietens_engine ?? '') !== '2') return no('"grietens_engine" must be "2" (the card format with the domain-separated signatures)'); const name = cleanCompany(json.name); if (!name) return no('"name" must be the shop\'s name, 2 to 100 characters (letters, digits, spaces and . , & \' " ( ) - / + : #)'); if (!Array.isArray(json.products) || !json.products.length) return no('"products" must be a list of the product words the engine quotes, e.g. ["roof_trusses"]'); if (json.products.length > CARD.products) return no(`"products": at most ${CARD.products} words`); const products = [...new Set(json.products.map((p) => (typeof p === 'string' ? p.trim().toLowerCase() : '')))]; if (products.some((p) => !p || p.length > CARD.product || !/^[\p{L}\p{N}][\p{L}\p{N} _./-]*$/u.test(p))) return no(`"products": each word 1 to ${CARD.product} letters, digits, spaces, "_", ".", "/" or "-"`); if (!isPublicKey(json.public_key)) return no('"public_key" must be the engine\'s Ed25519 public key, base64url of the raw 32 bytes (43 characters)'); const card = { grietens_engine: '2', name, products, public_key: json.public_key }; const text = (k, max) => { if (json[k] == null || json[k] === '') return null; if (typeof json[k] !== 'string') throw new Error(`"${k}" must be text`); const t = oneLine(json[k], max + 1); if (t.length > max) throw new Error(`"${k}": at most ${max} characters`); return t || null; }; try { card.town = text('town', CARD.town); card.about = text('about', CARD.about); const country = text('country', 2); if (country != null && !/^[A-Za-z]{2}$/.test(country)) throw new Error('"country" must be the 2-letter ISO code, e.g. "LV"'); card.country = country ? country.toUpperCase() : null; const lang = text('language', 5); if (lang != null && !CARD.languages.includes(lang.toLowerCase())) throw new Error(`"language" must be ${CARD.languages.join(' or ')}`); card.language = lang ? lang.toLowerCase() : null; const web = text('website', CARD.website); if (web != null) { let u; try { u = new URL(/^https?:\/\//i.test(web) ? web : `https://${web}`); } catch { throw new Error('"website" is not a web address'); } if (!/^https?:$/.test(u.protocol) || !u.hostname.includes('.') || u.username || u.password) throw new Error('"website" must be an http(s) web address'); card.website = u.toString(); } else card.website = null; // the shop's logo: a PNG, JPEG or WebP on the engine's own host (Grietens fetches it once and keeps its own copy) const logo = text('logo', CARD.logo); if (logo != null) { let u; try { u = new URL(logo); } catch { throw new Error('"logo" is not a web address'); } if (!/^https?:$/.test(u.protocol) || u.username || u.password) throw new Error('"logo" must be the https address of a PNG, JPEG or WebP picture on the engine\'s own host'); card.logo = u.toString(); } else card.logo = null; if (json.delivery_radius_km != null) { const r = Number(json.delivery_radius_km); if (typeof json.delivery_radius_km === 'boolean' || !(Number.isFinite(r) && r > 0 && r <= 5000)) throw new Error('"delivery_radius_km" must be a number of km above 0 (at most 5000)'); card.delivery_radius_km = r; } else card.delivery_radius_km = null; if (json.open_requests != null && typeof json.open_requests !== 'boolean') throw new Error('"open_requests" must be true or false'); card.open_requests = json.open_requests === true; // the Grietens account that adds this engine from inside (add_quote_engine), by its public id; without it the engine joins as its own shop if (json.workspace != null && json.workspace !== '') { if (typeof json.workspace !== 'string' || !/^gw-[a-z2-7]{16}$/.test(json.workspace)) { throw new Error('"workspace" must be the public id of the Grietens account that adds this engine ("gw-" and 16 letters and digits: get_connection_status shows it)'); } card.workspace = json.workspace; } else card.workspace = null; // the Data Terms version the person who runs this engine accepts for the shop (Annex §7A: its quotes in anonymous price figures) if (json.terms != null && json.terms !== '') { if (typeof json.terms !== 'string' || !/^\d{1,3}\.\d{1,3}$/.test(json.terms)) { throw new Error('"terms" must be the version of the Grietens Data Terms the person who runs this engine accepts for the shop, as text, e.g. "1.2"'); } card.terms = json.terms; } else card.terms = null; // the notices this engine asks Grietens to send ("buyer_contact": a buyer asked the shop to contact him); unknown words refuse the card if (json.notices != null && (!Array.isArray(json.notices) || json.notices.length > 5 || json.notices.some((x) => typeof x !== 'string'))) { throw new Error('"notices" must be a list of at most 5 notice words, e.g. ["buyer_contact"]'); } const badNotice = (json.notices || []).find((x) => !NOTICES.includes(x)); if (badNotice !== undefined) throw new Error(`"notices": "${String(badNotice).slice(0, 40)}" is not a notice Grietens sends (known: ${NOTICES.join(', ')})`); card.notices = [...new Set(json.notices || [])]; // Decision 182: per product word the facts the shop needs to price it ({product: [{key, ask, kind, choices?}]}), each list as the server reads questions card.needs = null; if (json.needs != null) { if (typeof json.needs !== 'object' || Array.isArray(json.needs)) throw new Error('"needs": needs is {"": [{key, ask, kind}, …]}, per product the facts the shop needs to price it'); const out = {}; for (const [k, list] of Object.entries(json.needs)) { const p = String(k).trim().toLowerCase(); if (!card.products.includes(p)) throw new Error(`"needs": needs names "${p.slice(0, 60)}", which is not one of the products listed`); const qp = questionsProblem(list); if (qp) throw new Error(`"needs": needs.${p.slice(0, 60)}: ${qp.replace(/^questions/, 'the list')}`); const clean = (t) => Array.from(String(t).replace(/[\u0000-\u001f\u007f]/g, ' ').replace(/\s+/g, ' ').trim()).slice(0, 300).join(''); out[p] = list.map((q) => { const kind = String(q.kind ?? 'text').trim().toLowerCase(); return { key: q.key.trim().normalize('NFC'), ask: clean(q.ask), kind, ...(kind === 'choice' || kind === 'choices' ? { choices: [...new Set(q.choices.map((c) => clean(c).slice(0, 100)).filter(Boolean))] } : {}), ...(kind === 'number' && typeof q.unit === 'string' && q.unit.trim() ? { unit: clean(q.unit) } : {}) }; }); } if (Object.keys(out).length) card.needs = out; } } catch (e) { return no(e.message); } return { ok: true, card }; } // the line the checker prints about the card's "terms" export const termsInfo = (card) => (card?.terms ? `info the card accepts the Grietens Data Terms v${card.terms} ("terms"): once it joins, its quotes given through Grietens are counted, as numbers only, in anonymous price figures` : 'info the card names no Data Terms version ("terms"): it joins and works as before, but its quotes are not counted in anonymous price figures until the shop ' + 'accepts the terms (the person who runs the engine reads /terms on Grietens and puts "terms": "" on the card, or the owner accepts them when signed in)'); // ── the recommended setup report (advice: it never changes the result or the exit code) ───────────────────────────────── // a text item shown as a tidy row on the buyer's page: a key of at most 24 characters, ONE colon, a value (the page's own rule) export const isKeyValue = (t) => { const s = String(t ?? ''); const i = s.indexOf(':'); const k = s.slice(0, i).trim(), v = s.slice(i + 1).trim(); return i > 0 && s.indexOf(':', i + 1) < 0 && k.length <= 24 && !k.includes('\n') && !!v && v.slice(0, 2) !== '//'; }; const LV_LETTERS = /[āčēģīķļņšūžĀČĒĢĪĶĻŅŠŪŽ]/; // rec: { card, logo: 'kept' | 'refused' | 'none', fileKinds, firstStatus, contact, updates: [progress] }; language: the --language given, or null export function setupReport(rec, { language = null } = {}) { const c = rec.card || {}; const ups = rec.updates || []; const items = ups.flatMap((p) => (Array.isArray(p?.items) ? p.items : [])); const texts = items.filter((x) => x && typeof x.text === 'string').map((x) => x.text); const words = [...ups.map((p) => p?.label).filter(Boolean), ...texts]; const lines = []; const line = (done, what, fix) => lines.push(`${done ? 'done ' : 'todo '} ${what}${done ? '' : `: ${fix}`}`); line(!!c.about, 'the card: about', 'put "about": "" on the card'); line(!!c.website, 'the card: website', 'put "website": "https://…" on the card'); line(rec.logo === 'kept', 'the card: logo, fetchable, a PNG, JPEG or WebP', rec.logo === 'refused' ? 'the logo was not kept (see the warning above): serve a PNG, JPEG or WebP of at most 512 KB on the engine\'s own host' : 'put "logo" on the card (the kit takes a local file)'); line(rec.fileKinds.length > 0, 'the answer carries files', 'put the offer and the drawings in the answer\'s "files" (the kit: files: [engine.attach(\'./offer.pdf\')]), never only as live items'); line(rec.fileKinds.includes('pdf'), 'the answer carries the offer as a PDF', 'attach the offer as a PDF with its fonts embedded'); line(ups.length > 0, 'live updates while the quote is made', 'send live updates (the kit: live.step(label), live.show(...items))'); line(items.some((x) => x && x.picture != null), 'a picture in the live updates', 'show what the engine understood as a picture early, redrawn under one id'); line(ups.some((p) => p?.step != null && p?.of != null), 'a step count in the live updates', 'send step and of (the kit: withSteps(fn, { of }))'); line(texts.length > 0 && texts.every(isKeyValue), 'live texts as "Key: value"', 'one fact per text item, a short key and ONE colon: { text: "Span: 9.2 m" }'); if (language === 'lv' || language === 'en') { const lvSeen = words.some((w) => LV_LETTERS.test(w)); line(language === 'lv' ? lvSeen : !lvSeen, `labels and texts in the request's language (${language})`, 'write labels, texts and the message in request.language'); } if (rec.firstStatus === 'pending') line(ups.some((p) => p?.state === 'waiting_for_person'), 'waiting_for_person while a person checks', 'when a person releases the quote, send state: "waiting_for_person" while he checks'); line(rec.contact === true, 'told when a buyer asks to be contacted', 'put "notices": ["buyer_contact"] on the card (the kit: onBuyerContact) and answer the notice 2xx, or check list_alerts with the workspace key'); lines.push(`info the card: terms: ${c.terms ? `"${c.terms}" (the shop's decision, recorded at the join)` : 'none (the shop\'s decision: without it everything works, its quotes are only not counted in the price figures)'}`); const todo = lines.filter((l) => l.startsWith('todo')).length; return ['', `Recommended setup (advice only: it never changes the result; every step: https://grietens.cloud/kit/setup.md): ${todo ? `${todo} to do` : 'complete'}`, ...lines]; } // ── the check ───────────────────────────────────────────────────────────────────────────────────────────────────────────── // argv: the command line options (see the top) → the exit code (0 = every MUST passed); out: where the lines go export async function main(argv = process.argv.slice(2), { out = (s) => console.log(s) } = {}) { const opt = (name, dflt = null) => { const i = argv.indexOf(`--${name}`); return i >= 0 && argv[i + 1] != null ? argv[i + 1] : dflt; }; const all = (name) => argv.flatMap((a, i) => (a === `--${name}` && argv[i + 1] != null ? [argv[i + 1]] : [])); const URL_TEXT = opt('url'); if (!URL_TEXT) { out('Usage: node grietens-engine-check.mjs --url [--port 8799] [--product roof_trusses] [--file ] [--wait 1500] [--cold]'); return 2; } let AUDIENCE; try { AUDIENCE = canonicalEngineUrl(URL_TEXT); } catch (e) { out(`FAIL the address ${URL_TEXT}: ${e.message}`); return 1; } const engine = new URL(AUDIENCE); const PORT = Number(opt('port', 8799)); const WAIT_S = Number(opt('wait', 1500)); const BASE = String(opt('callback-base', `http://127.0.0.1:${PORT}`)).replace(/\/+$/, ''); const COLD = argv.includes('--cold'); const COLD_MS = 60_000; const GRIETENS = keyPair(), IMPOSTOR = keyPair(); // the second signs the "wrong key" request under the first one's key id if (process.env.QUOTE_ENGINE_SECRET) out('note QUOTE_ENGINE_SECRET is ignored: the shared-secret check is gone, this checker speaks only keys (Decision 132).'); if (engine.protocol !== 'https:') out(`note ${engine.origin} is not https: fine for this check, but Grietens only calls public https addresses.`); let must = 0, failed = 0, warned = 0; // the facts of the recommended setup report at the end (advice only: never a pass, a fail or the exit code) const rec = { card: null, logo: 'none', fileKinds: [], firstStatus: null, contact: null, updates: [] }; const pass = (t) => { must++; out(`pass ${t}`); }; const fail = (t) => { must++; failed++; out(`FAIL ${t}`); }; const warn = (t) => { warned++; out(`warn ${t}`); }; const mustBe = (cond, t, why = '') => (cond ? pass(t) : fail(`${t}${why ? `: ${why}` : ''}`)); const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); let cardKey = null; // one signature MUST: which answer, bound to what, and why it failed const signedFor = (what, purpose, bound, ts, sig, body) => { const why = engineAnswerProblem(cardKey, { purpose, engineUrl: AUDIENCE, bound, ts, sig, body }); mustBe(!why, `${what} is signed with the card's key (purpose ${purpose}, bound to ${bound})`, why ? `${what}: ${why}` : ''); return !why; }; // the checker's own door: its published key, and the callback door const callbacks = new Map(); // request id → { json, problem, ts, sig, bytes } const live = new Map(); // request id → the live updates received ({ why, json }) const liveFetches = []; // the live pictures and files being fetched as Grietens would (awaited before the summary) const liveBytes = new Map(); // request id → bytes of live pictures and files kept so far // Decision 166: the request's file link, served here as Grietens serves one (a small PDF behind an unguessable path) const FILE_PATH = `/files/${crypto.randomBytes(12).toString('hex')}/drawing.pdf`; const TEST_PDF = Buffer.from('%PDF-1.4\n1 0 obj<>endobj 2 0 obj<>endobj\ntrailer<>\n%%EOF\n', 'latin1'); let fileFetches = 0; const server = http.createServer((req, res) => { const chunks = []; req.on('data', (c) => chunks.push(c)); req.on('end', () => { const done = (status, body) => { res.writeHead(status, { 'content-type': 'application/json' }); res.end(JSON.stringify(body)); }; const pathname = new URL(req.url, 'http://x').pathname; if (req.method === 'GET' && pathname === '/.well-known/grietens-keys.json') return done(200, { keys: [{ kid: GRIETENS.kid, alg: 'Ed25519', public_key: GRIETENS.publicKey, use: 'quote-requests' }] }); if (req.method === 'GET' && pathname === FILE_PATH) { fileFetches++; res.writeHead(200, { 'content-type': 'application/pdf' }); return res.end(TEST_PDF); } const m = /^\/cb\/(r-[0-9a-f]{20})$/.exec(pathname); if (req.method !== 'POST' || !m) return done(403, { ok: false, error: 'This callback link is not valid.' }); const bytes = Buffer.concat(chunks); let json = null; try { json = JSON.parse(bytes.toString('utf8')); } catch { callbacks.set(m[1], { problem: 'the callback body is not JSON' }); return done(400, { ok: false, error: 'The body is not JSON.' }); } // a live update (no status, a progress object): shown as it comes, its signature checked; it never counts as the quote if (json && typeof json === 'object' && json.status === undefined && json.progress && typeof json.progress === 'object') { const p = json.progress, n = (live.get(m[1]) || []).length + 1; const why = cardKey ? engineAnswerProblem(cardKey, { purpose: 'progress', engineUrl: AUDIENCE, bound: m[1], ts: req.headers['x-engine-timestamp'], sig: req.headers['x-engine-signature-ed25519'], body: bytes, version: req.headers['x-engine-sig-version'], audience: new URL(BASE).origin }) : 'the card was not read'; live.set(m[1], [...(live.get(m[1]) || []), { why, json }]); const items = Array.isArray(p.items) ? p.items : []; const kinds = ['text', 'picture', 'file'].map((k) => [k, items.filter((x) => x && x[k] != null).length]).filter(([, c]) => c).map(([k, c]) => `${c} ${k}`).join(', '); out(`live update ${n}${why ? ' (NOT SIGNED RIGHT: Grietens ignores it)' : ''}: ${[p.label ? `"${String(p.label).slice(0, 80)}"` : null, p.step != null ? `step ${p.step}${p.of ? ` of ${p.of}` : ''}` : null, p.percent != null ? `${p.percent}%` : null, p.state && p.state !== 'working' ? p.state : null, kinds || null].filter(Boolean).join(' · ') || '(empty)'}`); // Grietens fetches each picture and file of a SIGNED update at once: so does the checker (an unsigned one is ignored, nothing fetched) if (!why) items.forEach((x, i) => { const k = x && (x.picture != null ? 'picture' : x.file != null ? 'file' : null); if (k) liveFetches.push(checkLiveItem(m[1], n, i, k, x[k])); }); return done(200, why ? { ok: true, applied: false, event: 'unsigned' } : { ok: true, applied: true, event: 'progress' }); } callbacks.set(m[1], { json, bytes, ts: req.headers['x-engine-timestamp'], sig: req.headers['x-engine-signature-ed25519'] }); return done(200, { ok: true, applied: true }); }); }); try { await new Promise((ok, no) => server.listen(PORT, ok).on('error', no)); } catch (e) { out(`FAIL the checker could not listen on port ${PORT}: ${e.message}`); return 1; } const coldNote = (s) => out(`note the first answer took ${s} s, longer than the ${QUOTE_LIMITS.timeoutMs / 1000} s Grietens waits: Grietens would count ` + `this call as not answered and try again by itself with the SAME request_id after ${QUOTE_LIMITS.retryAfterS.map((x) => (x < 60 ? `${x} s` : `${x / 60} min`)).join(', ')} ` + `(${QUOTE_LIMITS.attempts} calls in all), so a sleeping engine still gets the request once it is awake. Once awake, answer "pending" within a few ` + 'seconds and send the quote to callback_url.'); async function send(body, { wrong = false, stale = false, nonce = undefined, audience = AUDIENCE, timeoutMs = QUOTE_LIMITS.timeoutMs } = {}) { const bytes = Buffer.from(JSON.stringify(body), 'utf8'); const started = Date.now(); const headers = requestHeaders(wrong ? { ...IMPOSTOR, kid: GRIETENS.kid } : GRIETENS, { purpose: body.type === 'hello' ? 'hello' : 'quote-request', method: 'POST', audience, path: engine.pathname, body: bytes, nowMs: Date.now() - (stale ? 600_000 : 0), ...(nonce ? { nonce } : {}) }); const res = await fetch(engine, { method: 'POST', redirect: 'manual', signal: AbortSignal.timeout(timeoutMs), headers: { 'content-type': 'application/json', ...headers, 'x-grietens-request-id': body.request_id || 'hello' }, body: bytes }); const text = await res.text(); let json = null; try { json = JSON.parse(text); } catch { /* reported by the caller */ } return { status: res.status, ms: Date.now() - started, text, json, headers: res.headers, sentNonce: headers['x-grietens-nonce'] }; } async function ask(id) { const p = `${engine.pathname.replace(/\/+$/, '')}/${encodeURIComponent(id)}`; const res = await fetch(new URL(p, engine), { redirect: 'manual', signal: AbortSignal.timeout(QUOTE_LIMITS.timeoutMs), headers: { ...requestHeaders(GRIETENS, { purpose: 'check', method: 'GET', audience: AUDIENCE, path: p }), 'x-grietens-request-id': id } }); const text = await res.text(); let json = null; try { json = JSON.parse(text); } catch { /* not JSON */ } return { status: res.status, text, json, headers: res.headers, path: p }; } // the request's optional language (Decision 145): the language of the buyer's page, lv or en; absent when Grietens does not know it const LANGUAGE = String(opt('language', 'en')).toLowerCase(); if (!['lv', 'en', 'none'].includes(LANGUAGE)) { out('Usage: --language lv, en or none'); server.close(); return 2; } const requestOf = (id) => ({ contract: CONTRACT, shop_id: opt('shop', 'test-shop'), request_id: id, product_hint: opt('product', 'roof_trusses'), quantity: opt('quantity') == null ? 1 : Number(opt('quantity')), needed_by: opt('needed-by'), notes: opt('notes', 'A test request from grietens-engine-check.'), files: all('file').map((u) => ({ name: decodeURIComponent(new URL(u).pathname.split('/').pop() || 'file'), url: u, content_type: null, bytes: null })), ...(LANGUAGE === 'none' ? {} : { language: LANGUAGE }), callback_url: `${BASE}/cb/${id}`, sent_at: new Date().toISOString() }); function judgeQuote(json, how) { const p = parseAnswer(json, {}); if (!p.ok) return fail(`the finished quote (${how}) is a contract-1 answer: ${p.problem}`); if (p.answer.status !== 'needs_review') return fail(`the finished quote (${how}) has status needs_review (got ${p.answer.status})`); const missing = missingForReview(p.answer.values); mustBe(!missing, `the finished quote (${how}) has a price, a currency and a scope`, missing || ''); for (const w of p.answer.warnings) warn(`the quote: ${w}`); const v = p.answer.values; if (v.range_low == null) warn('no range [low, high]: Grietens shows how sure a price is from it'); if (!v.assumptions?.length) warn('no assumptions: say what was guessed because the files did not'); if (!v.quantities) warn('no quantities: they are what a finished job is later checked against'); if (!v.valid_until) warn('no valid_until date'); if (!p.answer.quote_id) warn('no quote_id: Grietens then uses the request id as the quote id'); if (json?.kind == null) warn('no kind: Grietens shows the figure as an "estimate" (send kind: "quote" when it is a firm quote)'); if (p.answer.files?.length) quoteFiles = p.answer.files; return p.answer; } // Decision 137: the files a quote lists, fetched as Grietens fetches them (from the engine's own host, no redirect to another host, // the bytes decide); a file Grietens would not keep is named with why (the quote itself is kept either way) let quoteFiles = []; // a fetch as Grietens makes it: no redirect followed except a 307 / 308 to the same host, at most `max` bytes. Each problem comes with // `fix`: what the engine should change const LOCAL = engine.protocol === 'https:' ? null : { protocol: engine.protocol, port: engine.port }; async function fetchLike(u, max) { let url = u; for (let hop = 0; hop < 5; hop++) { let r; try { r = await fetch(url, { redirect: 'manual', signal: AbortSignal.timeout(15_000) }); } catch (e) { return { problem: `it could not be fetched (${String(e?.cause?.code || e?.message || e).slice(0, 120)})`, fix: `make sure ${url} answers 200 with the file to anyone, without a login, for as long as the request is open (a picture or a file given to the kit as a path or bytes is served for you)` }; } if (r.status >= 300 && r.status < 400 && r.headers.get('location')) { const next = new URL(r.headers.get('location'), url); if (![307, 308].includes(r.status) || hostOf(next.hostname) !== hostOf(engine.hostname)) { return { problem: `it redirects (${r.status}) to ${next.host}: Grietens follows only a 307 or 308 to the same host`, fix: 'answer the file at the address you name, or redirect with a 307 / 308 on the same host' }; } url = next; continue; } if (!r.ok) return { problem: `it answered HTTP ${r.status}`, fix: `make sure ${url} answers 200 with the file to anyone, without a login, for as long as the request is open` }; const buf = Buffer.from(await r.arrayBuffer()); return buf.length > max ? { problem: `it is larger than ${max >= 1048576 ? `${Math.round(max / 1048576)} MB` : `${Math.round(max / 1024)} KB`}`, fix: 'make it smaller' } : { buf }; } return { problem: 'more than 5 redirects', fix: 'answer the file at the address you name' }; } const sizeText = (n) => (n >= 1048576 ? `${(n / 1048576).toFixed(1)} MB` : `${Math.max(1, Math.round(n / 1024))} KB`); // one picture or file of a live update, fetched and judged as Grietens does (lib/quotes/files.js: the address, the fetch, the bytes) async function checkLiveItem(rid, n, i, kind, raw) { const f = parseAnswerFiles([typeof raw === 'string' ? { url: raw } : raw], [])[0]; const what = `live ${kind} ${f ? `"${f.name.slice(0, 80)}"` : `#${i + 1}`} (update ${n})`; const no = (why, fix) => fail(`${what} is kept by Grietens: not kept, ${why}${fix ? `. To fix: ${fix}` : ''}`); if (!f) return no(`it is not {url, name?} with a web address`, 'give the picture or file as an https address on the engine\'s host, or as { url, name }'); const where = fileAddressProblem(f.url, engine.hostname, { local: LOCAL }); if (where) return no(where, where === FILE_HOST_WORDS.host ? `serve it from ${engine.hostname} (any path there is fine)` : `serve it over https on port 443 from ${engine.hostname}`); const left = LIVE_FILE_LIMITS.perRequest - (liveBytes.get(rid) || 0); if (left <= 0) return no('this request\'s live pictures and files already hold 100 MB', 'send fewer or smaller pictures'); const got = await fetchLike(new URL(f.url), Math.min(LIVE_FILE_LIMITS.bytes, left)).catch((e) => ({ problem: e.message })); if (got.problem) return no(got.problem, got.fix); const k = keptAs(got.buf, f.name, { pictureOnly: kind === 'picture' }); if (k.refused) return no(k.refused, kind === 'picture' ? 'send a PNG, JPEG or WebP picture (an SVG, a web page or a PDF is never shown as a picture; send a PDF as a file)' : 'send a PDF, a picture or a drawing (DXF, DWG, IFC, STEP)'); liveBytes.set(rid, (liveBytes.get(rid) || 0) + got.buf.length); return pass(`${what} is kept by Grietens: ${k.kind === 'picture' ? 'a picture' : k.kind === 'pdf' ? 'a PDF' : 'a download'} (${k.ext.toUpperCase()}, ${sizeText(got.buf.length)})`); } async function checkFiles(files) { if (!files.length) return; if (files.length > QUOTE_FILE_LIMITS.files) warn(`the quote lists ${files.length} files: Grietens keeps the first ${QUOTE_FILE_LIMITS.files}`); let total = 0; for (const f of files.slice(0, QUOTE_FILE_LIMITS.files)) { const u = new URL(f.url); const where = fileAddressProblem(u.toString(), engine.hostname, { local: LOCAL }); if (where === FILE_HOST_WORDS.host) { fail(`the file ${f.name} is on the engine's own host (${engine.hostname}): it is on ${u.hostname}, so Grietens does not fetch it (any path on ${engine.hostname} is fine)`); continue; } if (where) { fail(`the file ${f.name} is an https address on port 443`); continue; } const got = await fetchLike(u, QUOTE_FILE_LIMITS.bytes).catch((e) => ({ problem: e.message })); if (got.problem) { fail(`the file ${f.name} can be fetched as Grietens fetches it: ${got.problem}${got.fix ? `. To fix: ${got.fix}` : ''}`); continue; } total += got.buf.length; const k = fileKind(got.buf, f.name); if (k.refused) fail(`the file ${f.name} is a file Grietens keeps: ${k.refused}`); else if (total > QUOTE_FILE_LIMITS.total) fail(`the files of one answer are at most ${QUOTE_FILE_LIMITS.total / 1048576} MB together`); else { rec.fileKinds.push(k.kind); pass(`the file ${f.name} is kept by Grietens as ${k.kind === 'picture' ? 'a picture (shown)' : k.kind === 'pdf' ? 'a PDF (shown as a card)' : `a download (${k.ext})`}`); } } } try { // 0. the engine card and the hello, as a join does them const c = await fetch(engine, { headers: { accept: 'application/json' }, signal: AbortSignal.timeout(COLD ? COLD_MS : QUOTE_LIMITS.timeoutMs) }) .then(async (r) => ({ status: r.status, signed: r.headers.has('x-engine-signature-ed25519'), json: await r.json().catch(() => null) })).catch((e) => ({ error: e.message })); if (c.error) { fail(`the engine card is served at GET ${engine.href}: ${c.error}`); throw new Error('stop'); } const pc = parseCard(c.json); mustBe(c.status === 200 && pc.ok, 'GET answers the engine card (grietens_engine "2", name, products, public_key)', pc.problem || `HTTP ${c.status}`); if (!pc.ok) throw new Error('stop'); cardKey = pc.card.public_key; rec.card = pc.card; out(`info the card: ${pc.card.name}, ${pc.card.products.join(', ')}${pc.card.town ? `, ${pc.card.town}` : ''}${pc.card.open_requests ? ', open requests: yes' : ''}`); out(termsInfo(pc.card)); mustBe(!c.signed, 'the card is not signed (the engine signs only its answers to calls that verified)'); // Decision 137: the shop's logo, as Grietens fetches it (from the engine's own host; PNG, JPEG or WebP; at most 512 KB). A logo that // fails never fails a join, so this is a warning if (pc.card.logo) { const lu = new URL(pc.card.logo); const got = hostOf(lu.hostname) !== hostOf(engine.hostname) ? { problem: `it is on ${lu.hostname}, not on the engine's own host ${engine.hostname} (any path there is fine)` } : await fetchLike(lu, 512 * 1024).catch((e) => ({ problem: e.message })); const k = got.buf ? fileKind(got.buf, lu.pathname) : null; rec.logo = got.problem || k?.kind !== 'picture' ? 'refused' : 'kept'; if (got.problem) warn(`the logo on the card is not kept by Grietens: ${got.problem}`); else if (k.kind !== 'picture') warn('the logo on the card is not kept by Grietens: it is a PNG, JPEG or WebP picture (an SVG is refused)'); else pass(`the logo on the card is a ${k.ext.toUpperCase()} Grietens keeps (${Math.round(got.buf.length / 1024)} KB)`); } const nonce = newNonce(); const hello = { contract: CONTRACT, type: 'hello', nonce, grietens_keys_url: `${BASE}/.well-known/grietens-keys.json`, sent_at: new Date().toISOString() }; const h = await send(hello).catch((e) => ({ error: e.message })); if (h.error) { fail(`the engine answers a hello: ${h.error}`); throw new Error('stop'); } mustBe(h.status === 200 && h.json?.nonce === nonce, 'a signed hello is answered at once with its nonce (never as a quote request)', `HTTP ${h.status}: ${String(h.text).slice(0, 200)}`); signedFor('the hello answer', 'hello', nonce, h.headers.get('x-engine-timestamp'), h.headers.get('x-engine-signature-ed25519'), Buffer.from(h.text, 'utf8')); const replay = await send(hello, { nonce: h.sentNonce }).catch((e) => ({ error: e.message })); mustBe(!replay.error && (replay.status === 401 || replay.status === 403), 'the same signed call sent again (its nonce seen) is refused (401 or 403)', replay.error || `got HTTP ${replay.status}`); mustBe(!replay.headers?.get?.('x-engine-signature-ed25519'), 'an error answer is not signed with the engine key'); const stale = await send(requestOf(newRequestId()), { stale: true }).catch((e) => ({ error: e.message })); mustBe(!stale.error && (stale.status === 401 || stale.status === 403), 'a request signed 10 minutes ago is refused (401 or 403)', stale.error || `got HTTP ${stale.status}`); const other = await send({ ...hello, nonce: newNonce() }, { audience: 'https://another-engine.example/quote' }).catch((e) => ({ error: e.message })); mustBe(!other.error && (other.status === 401 || other.status === 403), 'a call signed for another engine\'s address is refused (401 or 403)', other.error || `got HTTP ${other.status}`); // Decision 145: an unsigned POST is refused before its body is read (a warning only: an engine on an older kit answers 400 "not JSON") const junk = await fetch(engine, { method: 'POST', redirect: 'manual', signal: AbortSignal.timeout(QUOTE_LIMITS.timeoutMs), headers: { 'content-type': 'text/plain' }, body: 'not json at all' }) .then(async (r) => ({ status: r.status, text: await r.text() })).catch((e) => ({ error: e.message })); if (!junk.error && junk.status !== 401 && junk.status !== 403) warn(`an unsigned POST that is not JSON was answered HTTP ${junk.status}: refuse anything not signed by Grietens with 401 before reading its body (the current kits do)`); else if (!junk.error && /not json at all/.test(junk.text)) warn('the refusal of an unsigned POST repeats its body: say only why it was refused'); // 1. a wrong key must be refused (with --cold this call may also wake the engine) const bad = await send(requestOf(newRequestId()), { wrong: true, timeoutMs: COLD ? COLD_MS : QUOTE_LIMITS.timeoutMs }).catch((e) => ({ error: e.message })); if (COLD && bad.ms > QUOTE_LIMITS.timeoutMs) coldNote(Math.round(bad.ms / 1000)); if (bad.error) fail(`the engine answers at ${engine.href}: ${bad.error}`); else mustBe(bad.status === 401 || bad.status === 403, 'a request signed with another key is refused (401 or 403)', `got HTTP ${bad.status}`); // 2. a signed request is answered in time, in contract 1, signed for this request const id = newRequestId(); const first = await send(requestOf(id)).catch((e) => ({ error: e.name === 'TimeoutError' ? `no answer within ${QUOTE_LIMITS.timeoutMs / 1000} s` : e.message })); if (first.error) { fail(`a signed request is answered: ${first.error}`); if (/no answer within/.test(first.error)) out('note Grietens does not fail such a call at once: it tries again by itself (an engine that sleeps). Run again with --cold to see how long it takes to wake.'); throw new Error('stop'); } mustBe(first.status >= 200 && first.status < 300, `a signed request is answered with HTTP 2xx (in ${first.ms} ms)`, `got HTTP ${first.status}: ${first.text.slice(0, 200)}`); mustBe(!!first.json, 'the answer is JSON', first.text.slice(0, 200)); const p = first.json ? parseAnswer(first.json, { requestId: id }) : { ok: false, problem: 'not JSON' }; mustBe(p.ok, 'the answer is a contract-1 answer', p.problem || ''); if (!p.ok) throw new Error('stop'); signedFor('the first answer to the request', 'answer', id, first.headers.get('x-engine-timestamp'), first.headers.get('x-engine-signature-ed25519'), Buffer.from(first.text, 'utf8')); if (first.ms > 5000) warn(`the answer took ${first.ms} ms: answer "pending" within about 5 s and deliver the quote later`); rec.firstStatus = p.answer.status; out(`info the engine answered "${p.answer.status}"${p.answer.message ? `: ${p.answer.message.slice(0, 120)}` : ''}`); // 3. the finished quote let quoteId = p.answer.quote_id; if (p.answer.status === 'needs_review') { const a = judgeQuote(first.json, 'in the first answer'); quoteId = a?.quote_id ?? quoteId; if (first.json.questions != null) { const qp = questionsProblem(first.json.questions); if (qp) warn(`the questions beside the quote are left out by Grietens: ${qp}`); else out(`info the quote asks the buyer ${first.json.questions.length} question(s) that would firm it up`); } } else if (p.answer.status === 'questions') { // Decision 182: a question-only answer (no price yet): the buyer is asked first, and the engine is called again with his answers (revision) const qp = questionsProblem(first.json.questions); mustBe(!qp, `a question-only answer is well-formed (${Array.isArray(first.json.questions) ? first.json.questions.length : 0} question(s) for the buyer)`, qp || ''); out('info Grietens shows the questions to the buyer and sends the request again with the same request_id, revision 1 and his answers in facts'); } else if (p.answer.status === 'declined' || p.answer.status === 'failed') { mustBe(!!p.answer.message, `a "${p.answer.status}" answer says why (message)`); warn(`the engine ${p.answer.status} this test request, so no quote was checked: try other --product / --file values`); } else { if (!quoteId) warn('a pending answer without quote_id: Grietens can then only ask with the request id'); const asked = quoteId || id; out(`info waiting up to ${WAIT_S} s for the quote: a callback to ${BASE}/cb/${id}, or by asking GET ${engine.pathname.replace(/\/+$/, '')}/${asked}`); const until = Date.now() + WAIT_S * 1000; let got = null, checkedSig = false, askedOk = false; while (Date.now() < until && !got) { const cb = callbacks.get(id); if (cb?.problem) { fail(`the callback: ${cb.problem}`); callbacks.delete(id); } else if (cb) { signedFor('the callback', 'callback', id, cb.ts, cb.sig, cb.bytes); got = { json: cb.json, how: 'by callback' }; break; } const r = await ask(asked).catch(() => null); if (r?.status === 200) { askedOk = true; // the first check answer's signature is a MUST; later ones are checked too, and only a failure is reported again if (!checkedSig) { checkedSig = true; signedFor(`the check answer (GET ${r.path})`, 'answer', id, r.headers.get('x-engine-timestamp'), r.headers.get('x-engine-signature-ed25519'), Buffer.from(r.text, 'utf8')); } else if (engineAnswerProblem(cardKey, { purpose: 'answer', engineUrl: AUDIENCE, bound: id, ts: r.headers.get('x-engine-timestamp'), sig: r.headers.get('x-engine-signature-ed25519'), body: Buffer.from(r.text, 'utf8') })) { signedFor(`a later check answer (GET ${r.path})`, 'answer', id, r.headers.get('x-engine-timestamp'), r.headers.get('x-engine-signature-ed25519'), Buffer.from(r.text, 'utf8')); } if (r.json && r.json.status && r.json.status !== 'pending') { got = { json: r.json, how: 'asked with GET' }; break; } } await sleep(2000); } if (!got) fail(`the finished quote arrived within ${WAIT_S} s (by callback or by asking)`); else { pass(`the finished quote arrived (${got.how})`); if (!askedOk) warn(`GET ${engine.pathname.replace(/\/+$/, '')}/${asked} did not answer 200: Grietens cannot ask this engine for a pending quote`); const a = judgeQuote(got.json, got.how); quoteId = a?.quote_id ?? quoteId; } } // the live updates this request got while it was made (optional: an engine need not send any). One that came for none of the // requests is said ONCE, after every request (below): the setup lines read the live updates of every request the checker sent const ups = live.get(id) || []; const unsignedOf = (list) => `${list.filter((u) => u.why).length} of ${list.length} were not (${list.find((u) => u.why).why})`; if (ups.some((u) => u.why)) fail(`every live update is signed for its request (purpose progress): ${unsignedOf(ups)}`); else if (ups.length) pass(`${ups.length} live update${ups.length === 1 ? '' : 's'} came while the quote was made, each signed for the request`); await Promise.all(liveFetches); // the live pictures and files, judged as they came await checkFiles(quoteFiles); rec.updates = ups.filter((u) => !u.why).map((u) => u.json.progress); // a buyer who asks to be contacted: one made-up notice, signed as Grietens signs it, when the card asks for it (purpose buyer-contact) if (rec.card?.notices?.includes('buyer_contact')) { const nb = Buffer.from(JSON.stringify({ contract: CONTRACT, type: 'buyer_contact', request_id: id, quote_id: quoteId || null, email: 'buyer@example.com', phone: '+371 20000000', needed_by: null, quantity: null, place: 'Aizpute', note: 'A made-up contact from grietens-engine-check.', door: 'open', buyer_words: ['place', 'note'], sent_at: new Date().toISOString() }), 'utf8'); const nr = await fetch(engine, { method: 'POST', redirect: 'manual', signal: AbortSignal.timeout(QUOTE_LIMITS.timeoutMs), body: nb, headers: { 'content-type': 'application/json', ...requestHeaders(GRIETENS, { purpose: 'buyer-contact', method: 'POST', audience: AUDIENCE, path: engine.pathname, body: nb }), 'x-grietens-request-id': id } }) .then((r) => ({ status: r.status })).catch((e) => ({ error: e.message })); rec.contact = !nr.error && nr.status >= 200 && nr.status < 300; mustBe(rec.contact, 'the card asks for buyer contacts: a signed buyer-contact notice is answered 2xx', nr.error || `got HTTP ${nr.status}`); } // an id the engine never got: 404 (a "pending" there claims a request it does not have; Grietens treats it as still pending) const unknown = await ask(newRequestId()).catch((e) => ({ error: e.message })); if (unknown.error) warn(`GET / was not answered: ${unknown.error}`); else if (unknown.status === 404) pass('a check of an id the engine never got is answered 404'); else warn(`a check of an id the engine never got answered HTTP ${unknown.status}: answer 404 (an engine must not say "pending" for a request it does not have)`); // 4. the same request again gives the same quote, signed again if (quoteId) { const again = await send(requestOf(id)).catch(() => null); const pa = again?.json ? parseAnswer(again.json, { requestId: id }) : null; if (pa?.ok && pa.answer.quote_id && pa.answer.quote_id !== quoteId) warn(`the same request_id sent again got another quote_id (${pa.answer.quote_id}, first ${quoteId}): answer a repeat with the same quote`); else if (pa?.ok) pass('the same request_id sent again does not make a second quote'); else warn('the same request_id sent again was not answered with a contract-1 answer'); if (pa?.ok) signedFor('the answer to the repeated request', 'answer', id, again.headers.get('x-engine-timestamp'), again.headers.get('x-engine-signature-ed25519'), Buffer.from(again.text, 'utf8')); } // 5. Decision 166: requests as Grietens really sends them, with facts and with a file link; finished as a quote or a decline, never "failed" for (const [what, extra] of [['facts', { facts: { material: 'pine', finish: 'planed', span_m: 9.2, delivery: true } }], ['a file link', { files: [{ name: 'drawing.pdf', url: `${BASE}${FILE_PATH}`, content_type: 'application/pdf', bytes: TEST_PDF.length }] }]]) { const rid = newRequestId(); const r = await send({ ...requestOf(rid), ...extra }).catch((e) => ({ error: e.name === 'TimeoutError' ? `no answer within ${QUOTE_LIMITS.timeoutMs / 1000} s` : e.message })); const pr = r.json ? parseAnswer(r.json, { requestId: rid }) : null; if (r.error || r.status < 200 || r.status >= 300 || !pr?.ok) { fail(`a request with ${what} is answered in contract 1: ${r.error || pr?.problem || `HTTP ${r.status}: ${String(r.text).slice(0, 200)}`}`); continue; } signedFor(`the first answer to the request with ${what}`, 'answer', rid, r.headers.get('x-engine-timestamp'), r.headers.get('x-engine-signature-ed25519'), Buffer.from(r.text, 'utf8')); let last = r.json; for (const until = Date.now() + Math.min(WAIT_S, 120) * 1000; last?.status === 'pending' && Date.now() < until;) { await sleep(1000); const cb = callbacks.get(rid); if (cb?.json) last = cb.json; else { const a = await ask(last.quote_id || rid).catch(() => null); if (a?.status === 200 && a.json?.status && a.json.status !== 'pending') last = a.json; } } const fin = last ? parseAnswer(last, {}) : null; const why = !fin?.ok ? (fin?.problem || 'no answer') : fin.answer.status === 'pending' ? `still pending after ${Math.min(WAIT_S, 120)} s` : fin.answer.status === 'failed' ? `the engine failed it${fin.answer.message ? ` ("${fin.answer.message.slice(0, 160)}")` : ''}: an engine must read a request that carries ${what}` : fin.answer.status === 'needs_review' ? missingForReview(fin.answer.values) : null; mustBe(!why, `a request with ${what}, as Grietens sends it, is finished as a quote or a decline (${fin?.answer?.status || 'none'})`, why || ''); } out(fileFetches ? `info the engine fetched the request's file link (${fileFetches}×)` : 'info the engine did not fetch the request\'s file link: fine when it reads no files; a real link works 60 minutes, so fetch it at once when it does'); await Promise.all(liveFetches); // the live pictures and files of these two requests too // the live updates of EVERY request sent, in one statement (Decision 172: never "none came", then a list of them, then advice to add them) const later = [...live.entries()].filter(([k]) => k !== id).flatMap(([, v]) => v); if (later.some((u) => u.why)) fail(`every live update of the later requests is signed for its request (purpose progress): ${unsignedOf(later)}`); if (!ups.length && !later.length) out('info no live updates came for any request (optional: an engine may show the buyer the quote being made, see the kit)'); else if (!ups.length) out(`info no live updates came for the first request; ${later.length} came for the later ones`); rec.updates = [...ups, ...later].filter((u) => !u.why).map((u) => u.json.progress); } catch (e) { if (e.message !== 'stop') fail(`the check ran: ${e.message}`); } server.closeAllConnections?.(); await new Promise((r) => server.close(r)); // the recommended setup (https://grietens.cloud/kit/setup.md): one line per item, advice only, after every check if (rec.card) for (const l of setupReport(rec, { language: argv.includes('--language') ? LANGUAGE : null })) out(l); out(`\n${failed ? 'NOT PASSED' : 'PASSED'}: ${must - failed} of ${must} checks, ${warned} warning(s).`); return failed ? 1 : 0; } // run when started as a program (not when imported) const started = process.argv[1] ? path.resolve(process.argv[1]) : ''; const here = fileURLToPath(import.meta.url); const same = (a, b) => { try { a = fs.realpathSync(a); b = fs.realpathSync(b); } catch { /* compare as given */ } return process.platform === 'win32' ? a.toLowerCase() === b.toLowerCase() : a === b; }; if (started && same(started, here)) process.exitCode = await main(); // exitCode, not exit(): Windows asserts on an exit while handles close