// kit/grietens-engine.mjs: put a quote engine on the Grietens network (Decisions 127 and 132, docs/QUOTES.md). // Node 18+, no dependencies, ONE file: copy it into your project. Served at https://app.grietens.cloud/kit/grietens-engine.mjs. // THE RECOMMENDED SETUP, every step in order with an example and a check (start there, also as an AI agent): https://grietens.cloud/kit/setup.md // // ── 1. The easy path: write only the pricing ───────────────────────────────────────────────────────────────────────────── // // import { createEngine, fileStore } from './grietens-engine.mjs'; // const engine = createEngine({ // url: 'https://quotes.example.com/quote', // the public https address Grietens calls (your reverse proxy / tunnel) // keyFile: './grietens-engine-key.pem', // your Ed25519 key: made on the first start, kept (keep it private) // card: { name: 'Kalns trusses', products: ['roof_trusses'], town: 'Aizpute', country: 'LV', open_requests: true }, // store: fileStore('./grietens-requests.json'), // optional: requests, answers and nonces survive a restart (see 3.) // async quote(request) { // a contract-1 request in, an answer out // return { status: 'needs_review', kind: 'estimate', price: 18400, currency: 'EUR', scope: ['trusses'] }; // }, // }); // engine.listen(8787); // or: http.createServer(engine.handler), or app.use('/quote', engine.handler) BEFORE express.json() // await engine.join(); // Grietens reads the card, sends a signed hello, makes the shop's account and its quote link // // THE REQUEST (contract 1): { contract, shop_id, request_id, product_hint, quantity, needed_by, notes, files, callback_url, sent_at } // and, when Grietens knows it, language: "lv" | "en" (the language of the buyer's page or request: write your labels and messages in // it). language is optional and absent when unknown; an engine that ignores it works as before. The kit passes the request on untouched. // ASKING THE BUYER BACK (Decision 182): answer { status: 'questions', questions: [{ key, ask, kind, choices?, unit? }], note? } (or a quote with // questions). kind: 'text', 'number' (unit?: "mm", "m²", "pcs", at most 12 characters, shown beside the input), 'choice' (one of choices), // 'choices' (several of 2 to 20 choices), 'file', 'yes_no', 'date'. The same request_id comes again with a higher revision and the answers // in request.facts under the keys: a text, a number, one choice, a LIST of the chosen options ('choices'), true / false, 'YYYY-MM-DD' ('date'). // // A shop that already has a Grietens account: put its public id on the card, workspace: 'gw-…' (get_connection_status shows it), // and do not call join(): the account's owner or his AI adds the engine with add_quote_engine {url}. // // THE DATA TERMS. Joining accepts the Grietens Data Terms (/terms). Under Annex §7A each quote the shop gives through // Grietens is counted, as numbers only, in anonymous market price figures (never its name, the buyer, the files or the words of a // request). A machine cannot agree to anything, so the acceptance is recorded only when the PERSON who runs the engine read the terms // and puts the version on the card: card: { …, terms: '1.2' }. This kit never sets it by default. join() logs one line saying whether // the card accepts the terms and what follows, and its answer carries terms { current, accepted, url, note }. Without it the engine // works exactly the same; only its quotes are not counted in the price figures until the terms are on record. // // What it does for you: // * serves the engine card at GET ({grietens_engine: "2", name, products, …, public_key}; public, never signed) // * checks every call from Grietens (X-Grietens-Key-Id / -Timestamp / -Nonce / -Purpose / -Signature-Ed25519 over a text naming // the version, the purpose, the method, THIS engine's address, the path, the time, the nonce and the body's SHA-256) against // Grietens' published keys (/.well-known/grietens-keys.json: cached an hour, fetched again at most once a minute // whatever a caller sends, 10 s limit, no redirect, 64 KB at most, the keys read before kept when a fetch fails). A time more // than 5 minutes off, another address, another purpose or a nonce seen before is refused (401, never signed). // * signs ONLY its answers to calls that verified (purpose hello bound to the hello's nonce, purpose answer bound to the request // id) and its callbacks (purpose callback, bound to the request id): the engine's key cannot be borrowed to sign anything else // * a quote that takes longer than answerWithinMs (3 s) is answered "pending" and sent to callback_url when ready // * quote() may itself answer { status: 'pending', message } when a PERSON prices the job: later, at any time (hours, days, after // restarts), engine.complete(requestId, answer) stores the answer and sends it to callback_url (needs a store that survives) // * the same request_id again gets the same answer; GET / (a check) answers the quote once made, a signed "pending" // while it is being worked on, and 404 for an id this engine has never seen // * join() (signed with your key, purpose join), reportQuote(report) (your own quotes, report_quote's fields), workspaceKey() (a key // for the Grietens API of your own workspace, while it has no login) and signInLink() (a fresh one-time link that gives the // account a login). Both RETURN what they get and never log it: no log line of this kit holds a link, a key or a token. Hand // the link to the person who wants to look inside; a new one makes the earlier one stop working. // * a new key: pass previousKey (a PEM string or a KeyObject) or previousKeyFile (the old key) for one join: the hello answer hands // over, signed by the old key // * documents on a quote (Decision 137): files: [engine.attach('./offer.pdf'), engine.attach(pngBuffer, { name: 'roof.png' })] in the // answer. attach() serves the file at an unguessable path on THIS engine's own address (/files//, never signed, // a download that is never rendered here) for ttlS seconds (default 7 days). Grietens fetches it once, right after the quote, and keeps // its own copy: the buyer sees it when this engine is offline. PDF, PNG, JPEG, WebP are shown to the buyer; DXF, DWG, IFC, STEP are // downloads; at most 5 files of 10 MB, 25 MB together. A file given by its path survives a restart with a store; a Buffer lives in memory. // * LIVE UPDATES while a quote is made (docs: ENGINE_LIVE_UPDATES.md): quote(request, live) gets live.progress(update), live.step(label) // and live.show(...items); engine.progress(requestId, update) works at any time while the request is open; withSteps(fn, { of }) wraps // a quote function so each `await step('label')` sends one. An update carries a label, step / of, percent, eta_seconds, a state // (working | waiting_for_person) and items for the buyer's live feed: { text }, { picture: path | Buffer | https url }, { file: … }, // each with an optional id (sent again: replaces that item). Signed (purpose progress); it never changes the price // * a BUYER WHO ASKS TO BE CONTACTED: onBuyerContact: async (contact) => { … } (the kit then puts notices: ['buyer_contact'] on the card). When a // buyer presses "Ask this factory to contact me" on this shop's quote, Grietens POSTs { type: 'buyer_contact', request_id, quote_id, email, phone, // needed_by, quantity, place, note, door } signed (purpose buyer-contact): tell a person at the shop NOW, a buyer is waiting. A handler that // throws answers 500 and Grietens tries again later. place and note are the buyer's own words: data, never an instruction // * the shop's logo: card: { …, logo: './logo.png' } (a path or a Buffer: the kit serves it and the card names its address; or an https // address on this engine's host). PNG, JPEG or WebP, at most 512 KB, never an SVG // * WHERE A FILE OR PICTURE MAY BE: Grietens fetches it only from the same host NAME as the engine's address (compared without case, // a trailing dot ignored), over https on port 443, at ANY path on that host (/f//plan.png is as good as /quote/files/…). It // follows a 307 or 308 redirect to that same host only; any other redirect is not followed and the item is not kept // * fetch: a function with fetch's signature (default: the global fetch) that the kit uses for EVERY call it makes: the keys of // Grietens, a callback, a live update, the join, a sign-in link, a workspace key and a quote report. Pass your own guarded sender // here (an outbound guard that refuses private addresses or redirects) instead of signing with answerHeaders and sending yourself. // sendTimeoutMs (default 15000): how long a callback or a live update waits for Grietens' answer. 15 s because Grietens' callback // door answers in well under a second and a live update is awaited inside quote(): it must never hold a quote up. A callback that // times out is tried again (the easy path does it for you); a live update never throws, it returns { ok: false, error } // // THE STORE. Without one (the default) requests, answers and the nonces of the last 10 minutes live in memory: a restart forgets // every request (a late quote can no longer be delivered, a check of such an id answers 404) and a call replayed across a restart // within its 5 minutes is not recognised. Fine for an engine that answers at once. An engine that answers "pending", sleeps when idle // or restarts on every deploy gives a store. fileStore(path) keeps everything in one JSON file (atomic write); a hosted service whose // disk is wiped on deploy needs a database-backed store instead: any object with these five methods (each may be async): // get(id) → record | null put(id, record) unsent() → [records whose `sent` is not true] // rememberNonce(nonce, untilS) hasNonce(nonce) → bool (untilS: unix seconds; a nonce may be forgotten after it) // A record is plain JSON: { request_id, request, answer, pending_sent, sent, refused, attempts, updated_at }, or { alias_of, sent: // true } (a quote id pointing at its request). Keep it as one JSON column keyed by id. On start, an engine with a store re-sends // every answer that was made but not delivered, and runs quote() again for a request whose quote() was cut off by the restart. // // // a price released by a person hours later, on a service that restarts: // const engine = createEngine({ url, keyFile, card, store: fileStore('/data/grietens.json'), // quote: async (req) => { await myQueue.add(req.request_id, req); return { status: 'pending', message: 'our estimator prices this' }; } }); // engine.listen(8787); // // … later, in another process run or a button handler, after any number of restarts: // await engine.complete('r-…', { status: 'needs_review', kind: 'quote', price: 18400, currency: 'EUR', scope: ['trusses'] }); // // ── 2. The lower layer: your own storage, your own timing, your own server ───────────────────────────────────────────────── // // const g = createProtocol({ url, keyFile, store /* nonces only: rememberNonce, hasNonce (memory by default) */, fetch: myGuardedFetch }); // const v = await g.verify({ method, path, headers, body }); // path: the RAW request path; body: the raw bytes (a Buffer) // // v = { ok: false, status, reason } (answer status with { error, reason }, unsigned) or { ok: true, purpose, … }: // // purpose 'card' → answer g.card(fields), unsigned // // purpose 'hello' → answer g.reply('hello', v.nonce, g.helloAnswer(v.nonce)) // // purpose 'quote-request' → v.requestId, v.request: store it; answer g.reply('answer', v.requestId, { contract: '1', request_id, status, … }) // // purpose 'buyer-contact' → v.contact (the card asked for notices: ['buyer_contact']): tell a person at the shop, answer 200 // // purpose 'check' → v.id (a request id or a quote id): answer g.reply('answer', , …), or 404 when unknown // // A POST is checked BEFORE its body is read: its purpose comes from the signed X-Grietens-Purpose header, so anything not signed by // // Grietens is a 401 that echoes nothing of the body; a signed body that is not JSON is a 400, and one whose type disagrees with the // // signed purpose (a "hello" body signed as a quote request, or the other way round) is a 401 too: it is not signed for what it carries. // // g.reply(purpose, bound, json) → { status: 200, headers, body } with the signed headers; g.answerHeaders(purpose, bound, bytes) // // gives only the headers for bytes you serialise yourself (it throws for a missing or empty request id or nonce). // await g.sendCallback({ requestId, callbackUrl, answer }); // at ANY later time, from stored facts only → { ok, status, error } // await g.sendProgress({ requestId, callbackUrl, progress }); // a live update, at any time before the answer → { ok, status, body, error } // await g.join(); await g.signInLink(); await g.workspaceKey(); await g.reportQuote(report); // Every function needs only the engine's address and key: nothing held in memory between calls (the nonce memory aside). Every call // goes out through the fetch you gave (see above). // // // an engine whose quote a PERSON releases (docs: ENGINE_LIVE_UPDATES.md "When a person releases the quote"): answer "pending", // // show what the engine understood while the person checks (never a price, a volume or a note), the price by callback after release // return g.reply('answer', v.requestId, { contract: '1', request_id: v.requestId, status: 'pending', message: 'our engineer checks it' }); // await g.sendProgress({ requestId, callbackUrl, progress: { state: 'waiting_for_person', label, items: [{ text: 'Gable roof, span 9.2 m' }] } }); // await g.sendCallback({ requestId, callbackUrl, answer: { status: 'needs_review', kind: 'quote', price: 18400, currency: 'EUR', scope: ['trusses'] } }); // // ── 3. Coming from the first kit (the card said grietens_engine "1") ──────────────────────────────────────────────────────── // // It is a rewrite of the glue, not of your pricing: quote(request) stays as it was. The three things that changed: // // (a) createEngine's options. BEFORE: // createEngine({ url, keyFile, card, quote, hmacSecret: process.env.GRIETENS_SECRET }) // the card was made as grietens_engine "1" // AFTER (no hmacSecret; the kit makes a version "2" card; add a store when you answer "pending" or restart): // createEngine({ url, keyFile, card, quote, store: fileStore('./grietens-requests.json') }) // join() no longer logs the claim link: call engine.signInLink() when a person wants to look inside, and hand them its claim_url. // (b) the shared secret (HMAC) is gone. BEFORE: a call from Grietens could carry X-Grietens-Signature-256: sha256=, and every signature covered ".". AFTER: only Grietens' Ed25519 key signs, over a text naming // the purpose, the method, your address, the path, the time, a nonce and the body's hash: // const v = await g.verify({ method, path, headers, body }); // instead of checking an HMAC yourself // (c) the hello. BEFORE it was answered { nonce, hmac_proof: 'sha256=' + HMAC(secret, nonce) }, signed over ".", and // could carry the claim link. AFTER it carries only the nonce (and a key hand-over, if you pass previousKey), signed for the hello: // return g.reply('hello', v.nonce, g.helloAnswer(v.nonce)); // → { nonce }, purpose hello, bound to that nonce // Keep your key file: the same key is the same shop. The checker (grietens-engine-check.mjs) tells you what is still the old way. import http from 'node:http'; import fs from 'node:fs'; import crypto from 'node:crypto'; export const SIG_VERSION = 'grietens-sig/2'; export const ENGINE_CALL_V3 = 'grietens-sig/3'; export const SKEW_S = 300; const KEYS_FRESH_MS = 3600_000, KEYS_REFETCH_MS = 60_000, KEYS_TIMEOUT_MS = 10_000, KEYS_MAX_BYTES = 64 * 1024; // how long a callback or a live update waits for Grietens' answer (the option sendTimeoutMs): Grietens' callback door answers in well // under a second, and a live update is awaited inside quote(), so it must never hold a quote up; a callback that times out is tried again export const SEND_TIMEOUT_MS = 15_000; const CALL_TIMEOUT_MS = 30_000; // our own calls to Grietens (a join reads the card and sends a hello back before it answers) // 'buyer-contact': a buyer asked this shop to contact him, sent only to an engine whose card says notices: ['buyer_contact'] const POST_PURPOSES = ['hello', 'quote-request', 'buyer-contact']; const RETRY_AFTER_S = [60, 300, 1800, 7200]; // a callback that did not get through is tried again (and on every start) const SPKI_ED25519 = Buffer.from('302a300506032b6570032100', 'hex'); const FINAL = ['needs_review', 'questions', 'declined', 'failed']; // 'questions': Decision 182, the factory asks the buyer first export const publicKeyOf = (key) => crypto.createPublicKey(key).export({ format: 'der', type: 'spki' }).subarray(SPKI_ED25519.length).toString('base64url'); const publicFromRaw = (b64u) => crypto.createPublicKey({ key: Buffer.concat([SPKI_ED25519, Buffer.from(b64u, 'base64url')]), format: 'der', type: 'spki' }); const sha256Hex = (bytes) => crypto.createHash('sha256').update(Buffer.isBuffer(bytes) ? bytes : Buffer.from(String(bytes ?? ''), 'utf8')).digest('hex'); const line = (v) => String(v ?? '').replace(/[\r\n]/g, ' '); const lines = (parts) => parts.map(line).join('\n'); const newNonce = () => crypto.randomBytes(18).toString('base64url'); const NONCE = /^[A-Za-z0-9_-]{16,64}$/; // a signature in its one base64url spelling (anything the decoder would read alike but is spelled otherwise is refused) const canonicalSig = (s) => typeof s === 'string' && /^[A-Za-z0-9_-]{86}$/.test(s) && Buffer.from(s, 'base64url').toString('base64url') === s; const pendingId = (rid) => `q-${String(rid).slice(2, 14)}`; // The texts that are ever signed (the same lines as Grietens builds: test/kit_signing_texts.mjs compares them byte for byte) export const signingText = { request: ({ purpose, method, audience, path, ts, nonce, bodyHash }) => lines([SIG_VERSION, 'grietens-request', purpose, String(method).toUpperCase(), audience, path, ts, nonce, bodyHash]), engineCall: ({ purpose, method, path, engineUrl, ts, nonce, bodyHash }) => lines([SIG_VERSION, 'engine-call', purpose, String(method).toUpperCase(), path, engineUrl, ts, nonce, bodyHash]), // Decision 138: our own calls name WHICH Grietens they are for (the audience: its origin), a new signature version (header // X-Engine-Sig-Version: 3); a call signed for another Grietens (a staging one, a mistyped address) is not valid at production engineCallV3: ({ purpose, method, path, engineUrl, audience, ts, nonce, bodyHash }) => lines([ENGINE_CALL_V3, 'engine-call', purpose, String(method).toUpperCase(), path, engineUrl, audience, ts, nonce, bodyHash]), engineAnswer: ({ purpose, engineUrl, bound, ts, bodyHash }) => lines([SIG_VERSION, 'engine-answer', purpose, engineUrl, bound, ts, bodyHash]), // a live update (purpose progress) in version 3: it names WHICH Grietens it is for (the origin of the callback address) engineAnswerV3: ({ purpose, engineUrl, audience, bound, ts, bodyHash }) => lines([ENGINE_CALL_V3, 'engine-answer', purpose, engineUrl, audience, bound, ts, bodyHash]), rotation: (engineUrl, nonce, newPublicKey) => lines([SIG_VERSION, 'key-rotation', engineUrl, nonce, newPublicKey]), }; // The ONE form of an engine's address that both sides sign, read from the text as written (Grietens and the Python kit read it the same // way): the scheme and the host lowercased, the default port dropped, no trailing slash. Refused: a space or a control character; a // host that is not a plain ASCII name (write an international one in its "xn--" form); a path that is not plain (non-ASCII, a "." or // ".." segment, a needless or lower-case percent-escape). export function canonicalEngineUrl(address) { const raw = String(address ?? ''); if (/[\x00-\x20\x7f-\x9f\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]/.test(raw)) throw new Error('url: no spaces, tabs, line breaks or other control characters'); const m = /^([A-Za-z][A-Za-z0-9+.-]*):\/\/([^/?#]*)(.*)$/s.exec(raw); if (!m || !['https', 'http'].includes(m[1].toLowerCase())) throw new Error('url: an https address'); if (m[2].includes('@')) throw new Error('url: no user name or password'); if (/[^\x00-\x7f]/.test(m[2])) throw new Error('url: write the host in its "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('url: the host must be a plain DNS name (letters, digits, "-", "."), the port 1 to 65535'); const path = m[3]; const bad = /[?#]/.test(path) || !/^[A-Za-z0-9\-._~!$&'()*+,;=:@/%]*$/.test(path) || path.split('/').some((x) => /^(%2e|\.){1,2}$/i.test(x)) || (path.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('url: 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}${path.replace(/\/+$/, '')}`; } // A private key given as a KeyObject or a PEM string export const loadKey = (key) => (typeof key === 'string' || Buffer.isBuffer(key) ? crypto.createPrivateKey(key) : key); // Your key: read from keyFile, or made there on the first start (PKCS#8 PEM, readable by you only); or privateKey (KeyObject / PEM) export function loadOrCreateKey(keyFile, { privateKey = null } = {}) { if (privateKey) return loadKey(privateKey); if (!keyFile) throw new Error('keyFile: where your engine keeps its Ed25519 key (it is made there on the first start)'); if (fs.existsSync(keyFile)) return crypto.createPrivateKey(fs.readFileSync(keyFile, 'utf8')); const { privateKey: k } = crypto.generateKeyPairSync('ed25519'); fs.writeFileSync(keyFile, k.export({ format: 'pem', type: 'pkcs8' }), { mode: 0o600 }); return k; } // ── stores ──────────────────────────────────────────────────────────────────────────────────────────────────────────────── const copy = (x) => (x == null ? null : JSON.parse(JSON.stringify(x))); function storeOver(state, save, now) { const nowS = () => Math.floor(now() / 1000); return { async get(id) { return copy(state.records[id]); }, async put(id, record) { state.records[id] = copy(record); prune(); save(); }, async unsent() { return Object.values(state.records).filter((r) => r.sent !== true).map(copy); }, async rememberNonce(nonce, untilS) { for (const [n, u] of Object.entries(state.nonces)) if (u < nowS()) delete state.nonces[n]; state.nonces[nonce] = untilS; save(); }, async hasNonce(nonce) { return state.nonces[nonce] != null && state.nonces[nonce] >= nowS(); }, }; // a delivered request older than 40 days is dropped (Grietens closes an open request after 30); the newest 10,000 are kept function prune() { const ids = Object.keys(state.records); if (ids.length < 10_000 && Math.random() > 0.01) return; const old = now() - 40 * 86400e3; for (const id of ids) { const r = state.records[id]; if (r.sent === true && Date.parse(r.updated_at) < old) delete state.records[id]; } const done = Object.keys(state.records).filter((id) => state.records[id].sent === true); for (const id of done.slice(0, Math.max(0, Object.keys(state.records).length - 10_000))) delete state.records[id]; } } // The default: everything in memory (a restart forgets it all) export const memoryStore = ({ now = () => Date.now() } = {}) => storeOver({ records: {}, nonces: {} }, () => {}, now); // One JSON file, written whole and atomically (a temporary file renamed over it) on every change: for a small engine on a disk that // survives restarts. NOT for a hosted service with an ephemeral disk (its file is gone after a deploy): give a database-backed store. export function fileStore(file, { now = () => Date.now() } = {}) { let state = { records: {}, nonces: {} }; try { state = JSON.parse(fs.readFileSync(file, 'utf8')); } catch (e) { if (e.code !== 'ENOENT') throw new Error(`fileStore: ${file} could not be read: ${e.message}`); } state.records ||= {}; state.nonces ||= {}; const save = () => { const tmp = `${file}.${process.pid}.tmp`; fs.writeFileSync(tmp, JSON.stringify(state), { mode: 0o600 }); fs.renameSync(tmp, file); }; return storeOver(state, save, now); } // a response body, at most `max` bytes async function readCapped(r, max) { if (Number(r.headers?.get?.('content-length')) > max) throw new Error(`the answer is larger than ${max} bytes`); if (!r.body?.getReader) { const t = await r.text(); if (Buffer.byteLength(t) > max) throw new Error(`the answer is larger than ${max} bytes`); return t; } const reader = r.body.getReader(), parts = []; let n = 0; for (;;) { const { done, value } = await reader.read(); if (done) break; n += value.length; if (n > max) { reader.cancel().catch(() => {}); throw new Error(`the answer is larger than ${max} bytes`); } parts.push(Buffer.from(value)); } return Buffer.concat(parts).toString('utf8'); } // The one line join() logs about the Data Terms (Annex §7A, the market price figures): whether the card accepts them and what follows export function termsLine(terms, cardTerms, grietensUrl = 'https://app.grietens.cloud') { const url = terms?.url || `${String(grietensUrl).replace(/\/+$/, '')}/terms`; const then = (v) => `its quotes are not counted in anonymous price figures until the terms are on record (read ${url}, then put terms: "${v}" on the card, ` + 'or the owner accepts them when signed in)'; if (!terms || typeof terms !== 'object') { // a Grietens that does not answer about the terms return cardTerms ? `[grietens] the card accepts the Grietens Data Terms v${cardTerms} (${url})` : `[grietens] the card does not accept the Grietens Data Terms (no "terms" on it): ${then('')}`; } if (terms.accepted === true) { return `[grietens] the shop has the Grietens Data Terms v${terms.current} on record (${url}): each quote it gives through Grietens from then on is counted, ` + 'as numbers only, in anonymous price figures'; } return `[grietens] ${cardTerms ? `the card says terms "${cardTerms}", but it was not recorded` : 'the card does not accept the Grietens Data Terms (no "terms" on it)'}: ` + `the engine works as before, but ${then(terms.current)}`; } // ── the lower layer ─────────────────────────────────────────────────────────────────────────────────────────────────────── // fetch (fetchImpl: its older name, still read): the ONE function every outbound call of the kit goes through export function createProtocol({ url, keyFile = null, privateKey = null, previousKey = null, previousKeyFile = null, grietensUrl = 'https://app.grietens.cloud', keysUrl = null, store = null, fetch: fetchOption = null, fetchImpl: fetchOld = null, sendTimeoutMs = SEND_TIMEOUT_MS, now = () => Date.now(), log = console }) { if (!url) throw new Error('url: the public https address Grietens calls'); const fetchImpl = fetchOption || fetchOld || globalThis.fetch; if (typeof fetchImpl !== 'function') throw new Error('fetch: a function with the signature of fetch (url, init) → Response'); const sendMs = Number(sendTimeoutMs) > 0 ? Number(sendTimeoutMs) : SEND_TIMEOUT_MS; const self = canonicalEngineUrl(url); // the audience every call from Grietens names, and the address every call of ours signs const key = loadOrCreateKey(keyFile, { privateKey }); const publicKey = publicKeyOf(key); if (previousKeyFile && !previousKey && !fs.existsSync(previousKeyFile)) throw new Error(`previousKeyFile: ${previousKeyFile} does not exist`); const oldKey = previousKey ? loadKey(previousKey) : previousKeyFile ? loadOrCreateKey(previousKeyFile) : null; const base = new URL(self).pathname.replace(/\/+$/, '') || '/'; const grietens = String(grietensUrl).replace(/\/+$/, ''); const keysAt = keysUrl || `${grietens}/.well-known/grietens-keys.json`; const nonces = store || memoryStore({ now }); const sign = (k, t) => crypto.sign(null, Buffer.from(t, 'utf8'), k).toString('base64url'); const tsNow = () => String(Math.floor(now() / 1000)); // an answer of ours: purpose 'hello' (bound to the hello's nonce), 'answer' or 'callback' (bound to the request id) const answerHeaders = (purpose, bound, bytes, audience = null) => { if (!['hello', 'answer', 'callback', 'progress'].includes(purpose)) throw new Error(`answerHeaders: purpose hello, answer, callback or progress (got ${purpose})`); // every version: never a signature bound to nothing (an empty request id or nonce would be signed for no request at all) if (bound == null || String(bound).trim() === '') throw new Error('answerHeaders: the nonce or the request id the answer is bound to (missing or empty)'); if (audience) { const ts3 = String(Math.floor(now() / 1000)); return { 'x-engine-timestamp': ts3, 'x-engine-sig-version': '3', 'x-engine-signature-ed25519': sign(key, signingText.engineAnswerV3({ purpose, engineUrl: self, audience, bound: String(bound), ts: ts3, bodyHash: sha256Hex(bytes) })) }; } const ts = tsNow(); return { 'x-engine-timestamp': ts, 'x-engine-signature-ed25519': sign(key, signingText.engineAnswer({ purpose, engineUrl: self, bound: String(bound), ts, bodyHash: sha256Hex(bytes) })) }; }; const reply = (purpose, bound, json) => { const body = Buffer.from(JSON.stringify(json)); return { status: 200, headers: { 'content-type': 'application/json', ...answerHeaders(purpose, bound, body) }, body }; }; const card = (fields = {}) => ({ grietens_engine: '2', ...fields, public_key: publicKey }); // the hello proves the key and carries nothing else (never a claim link); with an old key it hands over to the new one const helloAnswer = (nonce) => (oldKey ? { nonce, rotation: { new_public_key: publicKey, signature_by_old_key: sign(oldKey, signingText.rotation(self, nonce, publicKey)) } } : { nonce }); // Grietens' published keys: cached an hour; fetched again at most once a minute whatever the caller sends (an unknown key id // included), 10 s at most, no redirect followed, 64 KB at most; a failed fetch keeps the keys read before let keys = [], keysFetchedAt = -Infinity, keysTriedAt = -Infinity, keysInflight = null; function refreshKeys() { if (keysInflight) return keysInflight; if (now() - keysTriedAt < KEYS_REFETCH_MS) return Promise.resolve(); keysTriedAt = now(); keysInflight = (async () => { try { const r = await fetchImpl(keysAt, { headers: { accept: 'application/json' }, redirect: 'error', signal: AbortSignal.timeout(KEYS_TIMEOUT_MS) }); if (r.status !== 200) throw new Error(`HTTP ${r.status}`); const j = JSON.parse(await readCapped(r, KEYS_MAX_BYTES)); if (!Array.isArray(j?.keys)) throw new Error('no "keys" list'); keys = j.keys.filter((x) => x && x.alg === 'Ed25519' && typeof x.kid === 'string' && typeof x.public_key === 'string'); keysFetchedAt = now(); } catch (e) { log.warn?.(`[grietens] could not read Grietens' keys at ${keysAt}: ${e.message} (the keys read before are kept)`); } finally { keysInflight = null; } })(); return keysInflight; } async function grietensKey(kid) { let k = keys.find((x) => x.kid === kid); if (!k || now() - keysFetchedAt >= KEYS_FRESH_MS) { await refreshKeys(); k = keys.find((x) => x.kid === kid); } return k || null; } // Is this call signed by Grietens for `purpose`? → null, or the plain reason it is refused. A nonce is kept only once the // signature verified (an unsigned caller cannot fill the memory). const busy = new Set(); const headerReader = (headers) => { const lower = Object.fromEntries(Object.entries(headers || {}).map(([k, v]) => [k.toLowerCase(), v])); return (n) => { const v = lower[n]; return Array.isArray(v) ? v[0] : v; }; }; async function signatureProblem(headers, { purpose, method, path, body }) { const get = headerReader(headers); const s = get('x-grietens-signature-ed25519'); if (!s) return 'no X-Grietens-Signature-Ed25519 header: not signed by Grietens'; const got = String(get('x-grietens-purpose') ?? ''); if (got !== purpose) return `the call is signed for purpose "${got.slice(0, 30)}", this one needs "${purpose}"`; const ts = String(get('x-grietens-timestamp') ?? '').trim(), nonce = String(get('x-grietens-nonce') ?? ''); if (!/^\d{9,11}$/.test(ts) || Math.abs(Number(ts) - Math.floor(now() / 1000)) > SKEW_S) return 'the timestamp is missing or more than 5 minutes off this engine\'s clock'; if (!NONCE.test(nonce)) return 'the nonce is not 16 to 64 base64url characters'; if (!canonicalSig(String(s))) return 'the signature is not one Ed25519 signature in canonical base64url'; const kid = String(get('x-grietens-key-id') ?? ''); const k = await grietensKey(kid); if (!k) return `no key Grietens publishes has the id "${kid.replace(/[^A-Za-z0-9_-]/g, '?').slice(0, 40)}"`; let ok = false; try { ok = crypto.verify(null, Buffer.from(signingText.request({ purpose, method, audience: self, path, ts, nonce, bodyHash: sha256Hex(body ?? '') }), 'utf8'), publicFromRaw(k.public_key), Buffer.from(String(s), 'base64url')); } catch { ok = false; } if (!ok) return 'the signature does not verify (another key, engine address, path, time, nonce or body)'; if (busy.has(nonce)) return 'this nonce was seen before: a replayed call'; busy.add(nonce); try { if (await nonces.hasNonce(nonce)) return 'this nonce was seen before: a replayed call'; await nonces.rememberNonce(nonce, Number(ts) + 2 * SKEW_S); return null; } finally { busy.delete(nonce); } } // ONE call to the engine's address → { ok: true, purpose, … } | { ok: false, status, reason }. path: the request's RAW path async function verify({ method, path, headers = {}, body = null }) { const no = (status, reason) => ({ ok: false, status, reason }); const rawPath = String(path || '/').split('?')[0]; const p = rawPath.replace(/\/+$/, '') || '/'; const m = String(method || 'GET').toUpperCase(); const bytes = Buffer.isBuffer(body) ? body : Buffer.from(body ?? ''); if (m === 'GET' && p === base) return { ok: true, purpose: 'card' }; if (m === 'GET' && p.startsWith(`${base === '/' ? '' : base}/`)) { const why = await signatureProblem(headers, { purpose: 'check', method: 'GET', path: rawPath, body: null }); if (why) return no(401, why); try { return { ok: true, purpose: 'check', id: decodeURIComponent(p.slice(base.length + (base === '/' ? 0 : 1))) }; } catch { return no(400, 'not an id'); } } if (m !== 'POST' || p !== base) return no(404, 'not found'); // the purpose comes from the SIGNED header (the signature binds X-Grietens-Purpose), so a POST not signed by Grietens is refused // before anything of its body is read; only a verified body is parsed const said = String(headerReader(headers)('x-grietens-purpose') ?? ''); const purpose = POST_PURPOSES.includes(said) ? said : 'quote-request'; const why = await signatureProblem(headers, { purpose, method: 'POST', path: rawPath, body: bytes }); if (why) return no(401, why); let req; try { req = JSON.parse(bytes.toString('utf8')); } catch { return no(400, 'not JSON'); } if (!req || typeof req !== 'object' || Array.isArray(req)) return no(400, 'not JSON'); // a body that is not what the signature was made for is not signed for it: 401, like any other call not signed for what it carries if ((req.type === 'hello') !== (purpose === 'hello')) { return no(401, purpose === 'hello' ? 'the call is signed as a hello, but its body is not a hello' : 'the body is a hello, but the call is signed as a quote request'); } if ((req.type === 'buyer_contact') !== (purpose === 'buyer-contact')) { return no(401, purpose === 'buyer-contact' ? 'the call is signed as a buyer contact, but its body is not one' : 'the body is a buyer contact, but the call is not signed as one'); } if (String(req.contract) !== '1') return no(400, 'contract 1 only'); // a buyer asked this shop to contact him (only to an engine whose card asks for it): his email, phone and details, for the shop if (purpose === 'buyer-contact') return req.request_id ? { ok: true, purpose, requestId: String(req.request_id), contact: req } : no(400, 'request_id missing'); if (purpose === 'hello') return NONCE.test(String(req.nonce ?? '')) ? { ok: true, purpose, nonce: String(req.nonce), request: req } : no(400, 'a hello carries a nonce'); const id = String(req.request_id || ''); return id ? { ok: true, purpose, requestId: id, request: req } : no(400, 'request_id missing'); } // A late answer, signed for the request id and POSTed to the callback address: needs only those three facts → { ok, status, error } async function sendCallback({ requestId, callbackUrl, answer }) { if (!requestId || !/^https?:\/\//i.test(String(callbackUrl || ''))) return { ok: false, status: null, error: 'sendCallback needs the request id and its callback_url' }; const body = Buffer.from(JSON.stringify({ contract: '1', request_id: String(requestId), ...answer })); try { const r = await fetchImpl(callbackUrl, { method: 'POST', redirect: 'error', signal: AbortSignal.timeout(sendMs), body, headers: { 'content-type': 'application/json', ...answerHeaders('callback', String(requestId), body) } }); await r.text().catch(() => ''); return { ok: r.status >= 200 && r.status < 300, status: r.status, error: r.status >= 300 ? `HTTP ${r.status}` : null }; } catch (e) { return { ok: false, status: null, error: e.message }; } } // A LIVE UPDATE while the quote is being made (any number, as often as you like): the bar (label, step, of, percent, eta_seconds, state) // and items to add to the buyer's live feed ({text} | {picture: https url} | {file: https url}, each with an optional id that replaces // that item). Signed for the request id (purpose progress, version 3 naming the Grietens of the callback address) and POSTed to the // request's callback address → { ok, status, body, error }. It never changes the quote: the answer comes with a status. async function sendProgress({ requestId, callbackUrl, progress }) { if (!requestId || !/^https?:\/\//i.test(String(callbackUrl || ''))) return { ok: false, status: null, error: 'sendProgress needs the request id and its callback_url' }; const body = Buffer.from(JSON.stringify({ contract: '1', request_id: String(requestId), progress: progress || {} })); try { const audience = new URL(callbackUrl).origin; const r = await fetchImpl(callbackUrl, { method: 'POST', redirect: 'error', signal: AbortSignal.timeout(sendMs), body, headers: { 'content-type': 'application/json', ...answerHeaders('progress', String(requestId), body, audience) } }); const json = await r.json().catch(() => null); return { ok: r.ok && json?.applied !== false, status: r.status, body: json, error: r.ok ? (json?.applied === false ? json?.message || null : null) : json?.error || `HTTP ${r.status}` }; } catch (e) { return { ok: false, status: null, error: String(e?.message || e) }; } } // our own call to Grietens, signed with our key for `purpose` (join, key, sign-in-link, quote-report) async function call(callPath, purpose, json) { const target = `${grietens}${callPath}`; const bytes = Buffer.from(JSON.stringify(json)); const ts = tsNow(), nonce = newNonce(); const audience = new URL(grietens).origin.toLowerCase(); const signature = sign(key, signingText.engineCallV3({ purpose, method: 'POST', path: new URL(target).pathname, engineUrl: self, audience, ts, nonce, bodyHash: sha256Hex(bytes) })); // a signed call is never sent on to another address (Decision 138): a redirect is an error, never followed let r; try { r = await fetchImpl(target, { method: 'POST', body: bytes, redirect: 'error', signal: AbortSignal.timeout(CALL_TIMEOUT_MS), headers: { 'content-type': 'application/json', 'x-engine-url': self, 'x-engine-timestamp': ts, 'x-engine-nonce': nonce, 'x-engine-sig-version': '3', 'x-engine-signature-ed25519': signature } }); } catch (e) { return { status: null, error: `the call to Grietens failed (a redirect is never followed): ${String(e?.message || e).slice(0, 200)}` }; } return { status: r.status, ...(await r.json().catch(() => ({}))) }; } // join the network (or again: the same shop, its card re-read). Never asks for or logs a sign-in link. cardTerms: the card's "terms" // (the easy path passes it), for the one line about the Data Terms when Grietens' answer has none async function join({ cardTerms = null } = {}) { const out = await call('/api/public/join', 'join', { url: self }); if (out.shop?.link) log.log?.(`[grietens] joined; the shop's public quote page: ${out.shop.link}`); else if (!out.joined) log.warn?.(`[grietens] the join did not work (HTTP ${out.status}): ${String(out.error ?? '').slice(0, 300)}`); if (out.joined) log.log?.(termsLine(out.terms, cardTerms, grietens)); if (out.joined && out.created && !out.claimed) { log.log?.('[grietens] the shop\'s Grietens account exists (it has no login yet, which is fine). When a person wants to look inside, ' + 'signInLink() returns a one-time link for them; the kit never prints it.'); } return out; } // a fresh one-time link that gives the account a login, RETURNED to the caller (claim_url) and never logged async function signInLink() { const out = await call('/api/public/engine/sign-in-link', 'sign-in-link', {}); if (out.claim_url) log.log?.('[grietens] a one-time sign-in link was issued and returned to the caller (not logged; a new one stops the earlier one)'); return out; } // a key for the Grietens API of your own workspace (read, send data, write), RETURNED and never logged; asking again revokes the last async function workspaceKey() { const out = await call('/api/public/engine/key', 'key', {}); if (out.key) log.log?.('[grietens] a workspace key was issued and returned to the caller (not logged)'); return out; } const reportQuote = (report) => call('/api/public/engine/quotes', 'quote-report', report); return { url: self, publicKey, base, card, verify, answerHeaders, reply, helloAnswer, sendCallback, sendProgress, join, signInLink, workspaceKey, reportQuote }; } // ── the easy path ───────────────────────────────────────────────────────────────────────────────────────────────────────── export function createEngine({ url, keyFile = null, privateKey = null, previousKey = null, previousKeyFile = null, card = {}, quote, grietensUrl = 'https://app.grietens.cloud', keysUrl = null, store = null, answerWithinMs = 3000, fetch: fetchOption = null, fetchImpl = null, sendTimeoutMs = SEND_TIMEOUT_MS, now = () => Date.now(), log = console, onHello = null, onBuyerContact = null }) { if (typeof quote !== 'function') throw new Error('quote: async (request) => answer'); if (card?.terms != null && !(typeof card.terms === 'string' && /^\d{1,3}\.\d{1,3}$/.test(card.terms))) { throw new Error('card.terms: the version of the Grietens Data Terms the person who runs this engine accepts for the shop, as text, e.g. "1.2" (or leave it out)'); } const st = store || memoryStore({ now }); const g = createProtocol({ url, keyFile, privateKey, previousKey, previousKeyFile, grietensUrl, keysUrl, store: st, fetch: fetchOption || fetchImpl, sendTimeoutMs, now, log }); const plain = (status, json) => ({ status, headers: { 'content-type': 'application/json' }, body: Buffer.from(JSON.stringify(json)) }); // Decision 137: files this engine serves for Grietens to fetch (a quote's documents, the logo): token → { path | bytes, name, type, until } const served = new Map(); const FILE_PATH = new RegExp(`^${(g.base === '/' ? '' : g.base).replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}/files/([A-Za-z0-9_-]{32})(?:/[^/]*)?$`); const TYPES = { pdf: 'application/pdf', png: 'image/png', jpg: 'image/jpeg', jpeg: 'image/jpeg', webp: 'image/webp' }; function attach(file, { name = null, type = null, ttlS = 7 * 86400 } = {}) { const isPath = typeof file === 'string'; if (!isPath && !Buffer.isBuffer(file)) throw new Error('attach: a file path or a Buffer'); if (isPath && !fs.existsSync(file)) throw new Error(`attach: ${file} does not exist`); // whole characters: a cut never splits a pair (a name that would break Grietens' headers is never sent) const n = Array.from(String(name || (isPath ? file.split(/[\\/]/).pop() : 'file')).toWellFormed()).slice(0, 200).join('') || 'file'; const t = type || TYPES[(/\.([a-z0-9]+)$/i.exec(n)?.[1] || '').toLowerCase()] || null; const token = crypto.randomBytes(24).toString('base64url'); prune(); const rec = { name: n, type: t, until: Math.floor(now() / 1000) + ttlS, ...(isPath ? { path: file } : {}) }; served.set(token, isPath ? rec : { ...rec, bytes: file }); if (isPath) Promise.resolve(st.put(`file:${token}`, { file: rec, sent: true, updated_at: new Date(now()).toISOString() })).catch(() => {}); return { name: n, url: `${g.url}/files/${token}/${encodeURIComponent(n)}`, ...(t ? { type: t } : {}) }; } // the card's logo given as a local file (a path or a Buffer) is served by this engine: the card names its address here // a handler for buyer contacts puts notices: ['buyer_contact'] on the card by itself (without one Grietens sends no contact to this engine) const notices = typeof onBuyerContact === 'function' ? [...new Set([...(Array.isArray(card.notices) ? card.notices : []), 'buyer_contact'])] : card.notices; const cardFields = { ...card, ...(notices ? { notices } : {}), ...(card.logo != null && !(typeof card.logo === 'string' && /^https?:\/\//i.test(card.logo)) ? { logo: attach(card.logo, { ttlS: 3650 * 86400, name: typeof card.logo === 'string' ? undefined : 'logo' }).url } : {}) }; // an expired entry is dropped from memory (its bytes too): on every attach and every served file function prune() { const nowS = Math.floor(now() / 1000); for (const [k, f] of served) if (f.until < nowS) served.delete(k); } async function serveFile(token) { prune(); let f = served.get(token); if (!f) { const r = await st.get(`file:${token}`); if (r?.file?.path && r.file.until >= Math.floor(now() / 1000)) { f = r.file; served.set(token, f); } } if (!f || f.until < Math.floor(now() / 1000)) return plain(404, { error: 'no such file here' }); let body; try { body = f.bytes || fs.readFileSync(f.path); } catch { return plain(404, { error: 'no such file here' }); } const ascii = f.name.replace(/[^\x20-\x7e]/g, '_').replace(/["\\]/g, '_'); return { status: 200, headers: { 'content-type': f.type || 'application/octet-stream', 'x-content-type-options': 'nosniff', 'cache-control': 'private, max-age=600', 'content-disposition': `attachment; filename="${ascii}"`, 'content-security-policy': "default-src 'none'; sandbox" }, body }; } const complete = (req, a) => ({ contract: '1', request_id: req.request_id, shop_id: req.shop_id, quote_id: a.quote_id || pendingId(req.request_id), ...a }); const isFinal = (a) => !!a && FINAL.includes(a.status); // every change of a record goes through update(), one at a time per request id (read, change, write) const chains = new Map(); function update(id, change) { const run = (chains.get(id) || Promise.resolve()).then(async () => { const rec = await st.get(id); const next = await change(rec); if (next) { next.updated_at = new Date(now()).toISOString(); await st.put(id, next); } return next || rec; }); const tail = run.catch(() => {}); chains.set(id, tail); tail.then(() => { if (chains.get(id) === tail) chains.delete(id); }); return run; } const alias = async (quoteId, rid) => { if (quoteId && quoteId !== rid && !(await st.get(quoteId))) await st.put(quoteId, { alias_of: rid, sent: true, updated_at: new Date(now()).toISOString() }); }; // send a final answer to callback_url; tried again later when it did not get through (and on every start) const sending = new Set(); async function deliver(rid) { if (sending.has(rid)) return { ok: false, error: 'already being sent' }; sending.add(rid); try { const rec = await st.get(rid); if (!rec || rec.sent === true || !isFinal(rec.answer)) return { ok: !!rec?.sent, status: null, error: rec ? null : 'unknown request' }; const out = await g.sendCallback({ requestId: rid, callbackUrl: rec.request?.callback_url, answer: rec.answer }); const lasting = out.status != null && out.status >= 400 && out.status < 500 && ![408, 429].includes(out.status); const after = await update(rid, (r) => r && { ...r, sent: out.ok || lasting, refused: lasting ? out.error : null, attempts: (r.attempts || 0) + 1 }); if (out.ok) log.log?.(`[grietens] quote ${rec.answer.quote_id} for ${rid} delivered: HTTP ${out.status}`); else { log.error?.(`[grietens] delivering quote ${rec.answer.quote_id} for ${rid} failed: ${out.error}${lasting ? ' (Grietens refused it: not tried again)' : ''}`); const wait = RETRY_AFTER_S[(after?.attempts || 1) - 1]; if (!lasting && wait) setTimeout(() => deliver(rid), wait * 1000).unref?.(); } return out; } finally { sending.delete(rid); } } // run quote() for a stored request; the answer is stored, and sent by callback once "pending" went out const running = new Map(); function startQuote(req) { const rid = String(req.request_id); if (running.has(rid)) return running.get(rid); const pr = Promise.resolve().then(() => quote(req, liveFor(rid))) .then((a) => complete(req, a || { status: 'failed', message: 'no answer' }), (e) => complete(req, { status: 'failed', message: `the engine could not quote it: ${String(e?.message || e).slice(0, 200)}` })) .then(async (answer) => { const rec = await update(rid, (r) => ({ ...(r || { request_id: rid, request: req, sent: false }), answer })); if (answer.status === 'pending') await alias(answer.quote_id, rid); if (rec.pending_sent && isFinal(answer) && rec.sent !== true) await deliver(rid); return answer; }) .finally(() => running.delete(rid)); running.set(rid, pr); return pr; } // ONE call → { status, headers, body (Buffer) }: the transport-free core (handler and listen wrap it). path: the request's RAW path async function handle({ method, path, headers = {}, body = Buffer.alloc(0) }) { const fileHit = String(method || '').toUpperCase() === 'GET' ? FILE_PATH.exec(String(path || '').split('?')[0]) : null; if (fileHit) return serveFile(fileHit[1]); // a served file (Decision 137): unsigned, nothing else on this path const v = await g.verify({ method, path, headers, body }); if (!v.ok) return plain(v.status, v.status === 401 ? { error: 'not signed by Grietens', reason: v.reason } : { error: v.reason }); if (v.purpose === 'card') return plain(200, g.card(cardFields)); if (v.purpose === 'hello') { try { onHello?.(v.request); } catch { /* the hello is answered anyway */ } return g.reply('hello', v.nonce, g.helloAnswer(v.nonce)); } // a buyer asked to be contacted: the handler tells a person at the shop now; an error answers 500, so Grietens tries again later if (v.purpose === 'buyer-contact') { if (typeof onBuyerContact !== 'function') return plain(404, { error: 'this engine takes no buyer-contact notices' }); try { await onBuyerContact(v.contact); return plain(200, { ok: true }); } catch (e) { log.error?.('[grietens] the buyer-contact handler failed:', e?.message || e); return plain(500, { error: 'not taken: try again later' }); } } if (v.purpose === 'check') { let rec = await st.get(v.id); if (rec?.alias_of) rec = await st.get(rec.alias_of); if (!rec?.request_id) return plain(404, { error: 'no request with this id here' }); // never a "pending" for a request it does not have const rid = rec.request_id; if (isFinal(rec.answer)) { if (rec.sent !== true) await update(rid, (r) => ({ ...r, sent: true })); return g.reply('answer', rid, rec.answer); } if (!rec.answer && !running.has(rid)) startQuote(rec.request); return g.reply('answer', rid, rec.answer || { contract: '1', request_id: rid, status: 'pending', quote_id: pendingId(rid), message: 'still working on it' }); } const rid = v.requestId, req = v.request; // Decision 182: the same request_id with a higher revision is the buyer's answer to the factory's questions (or a fact or a file he added): // a NEW piece of work, priced again from the request as it comes now (its facts merged, its thread); the same revision again is a repeat const newer = (r) => Number(req?.revision || 0) > Number(r?.request?.revision || 0); let rec = await update(rid, (r) => (r && !newer(r) ? null : { request_id: rid, request: req, answer: null, pending_sent: false, sent: false, attempts: 0 })); if (!rec.answer && !running.has(rid)) startQuote(rec.request); if (!rec.answer) { const quick = await Promise.race([running.get(rid), new Promise((r) => setTimeout(() => r(null), answerWithinMs))]).catch(() => null); rec = await st.get(rid); if (!quick && !rec.answer) { const pend = { contract: '1', request_id: rid, status: 'pending', quote_id: pendingId(rid), message: 'working on it: the quote follows at callback_url' }; await alias(pend.quote_id, rid); rec = await update(rid, (r) => ({ ...r, pending_sent: true })); if (isFinal(rec.answer) && rec.sent !== true) deliver(rid); // it was finished meanwhile return g.reply('answer', rid, pend); } } if (isFinal(rec.answer)) { if (rec.sent !== true) await update(rid, (r) => ({ ...r, sent: true })); } else if (!rec.pending_sent) await update(rid, (r) => ({ ...r, pending_sent: true })); return g.reply('answer', rid, rec.answer); } // Node http / Express-style: (req, res[, next]). Reads the raw body itself (or takes a Buffer an earlier middleware left in req.body). function handler(req, res) { const finish = (bytes) => handle({ method: req.method, path: req.originalUrl || req.url, headers: req.headers, body: bytes }) .then((out) => { res.writeHead(out.status, out.headers); res.end(out.body); }) .catch((e) => { log.error?.('[grietens]', e?.message || e); res.writeHead(500, { 'content-type': 'application/json' }); res.end('{"error":"engine error"}'); }); if (Buffer.isBuffer(req.body)) return finish(req.body); const chunks = []; req.on('data', (c) => chunks.push(c)); req.on('end', () => finish(Buffer.concat(chunks))); } const listen = (port, cb) => http.createServer(handler).listen(port, cb || (() => log.log?.(`[grietens] quote engine on port ${port}, public address ${g.url}`))); // ── live updates: show the buyer the quote being made ── // progress(requestId, update): one signed update to the request's callback address. update: { label, step, of, percent, eta_seconds, // state ('working' | 'waiting_for_person'), items: [{ text } | { picture } | { file }, each with an optional id (the same id again // replaces that item)] }; a picture or a file is an https address on this engine's host, OR a local path or a Buffer (the kit serves it, // like attach()). → { ok, status, body, error }; it never throws for a network failure (a live update is never worth failing a quote for) async function progress(requestId, update = {}) { const rid = String(requestId); const rec = await st.get(rid); const callbackUrl = rec?.request?.callback_url; if (!callbackUrl) return { ok: false, status: null, error: `no request ${rid} with a callback_url here` }; const items = (update.items || []).map((x) => { const k = x && (x.picture != null ? 'picture' : x.file != null ? 'file' : null); if (!k || (typeof x[k] === 'string' && /^https:\/\//i.test(x[k])) || (x[k] && typeof x[k] === 'object' && !Buffer.isBuffer(x[k]))) return x; const a = attach(x[k], { name: x.name || null }); return { ...(x.id ? { id: x.id } : {}), [k]: { url: a.url, name: a.name } }; }); const out = await g.sendProgress({ requestId: rid, callbackUrl, progress: { ...update, ...(update.items ? { items } : {}) } }); if (!out.ok && out.status !== 200) log.warn?.(`[grietens] a live update for ${rid} was not taken: ${out.error || out.status}`); return out; } // what quote(request, live) gets as its second argument: live.progress(update), live.step(label, update?) (counts the steps: step 1, // 2, 3 … with `of` when you give it once), live.show(...items) (adds items to the feed without moving the bar) function liveFor(rid) { let n = 0, of = null; return { progress: (u) => progress(rid, u), step: (label, u = {}) => { n++; if (u.of != null) of = u.of; return progress(rid, { ...u, label, step: n, ...(of ? { of } : {}) }); }, show: (...items) => progress(rid, { items }), }; } // A person's answer to a request quote() left "pending", at any later time: stored, then sent to callback_url → { ok, status, error } async function completeLater(requestId, answer) { const rid = String(requestId); if (!answer || !FINAL.includes(answer.status)) throw new Error(`complete: an answer with status ${FINAL.join(', ')}`); const rec = await update(rid, (r) => r && { ...r, answer: complete(r.request, answer), pending_sent: true, sent: false, refused: null, attempts: 0 }); if (!rec?.request_id) throw new Error(`complete: no request ${rid} in the store`); return deliver(rid); } // On start: every answer made but not delivered is sent; a quote() cut off by the restart runs again async function resume() { for (const rec of await st.unsent()) { if (!rec?.request_id || rec.alias_of) continue; if (isFinal(rec.answer)) await deliver(rec.request_id); else if (!rec.answer && rec.request) startQuote(rec.request); } } const ready = store ? resume().catch((e) => log.error?.(`[grietens] resuming the stored requests failed: ${e.message}`)) : Promise.resolve(); return { publicKey: g.publicKey, url: g.url, card: () => g.card(cardFields), handle, handler, listen, ready, resume, complete: completeLater, store: st, protocol: g, join: () => g.join({ cardTerms: card?.terms ?? null }), signInLink: g.signInLink, workspaceKey: g.workspaceKey, reportQuote: g.reportQuote, // Decision 137: a file on a quote (or the logo) served at an unguessable path on this engine's own address → { name, url, type } attach, logo: (file, opts = {}) => attach(file, { ttlS: 3650 * 86400, ...opts }).url, filesInMemory: () => served.size, // live updates while a quote is made: engine.progress(requestId, update) progress, }; } // withSteps(quote, { of }): your quote function gets step(label, update?) as its SECOND argument, and each `await step('Reading the // drawings')` inside it sends a live update with the next step number (and `of` when you give it). Use it as createEngine({ quote: // withSteps(async (request, step) => { await step('Reading the drawings'); …; return answer; }, { of: 4 }) }). show(...items) is the third. export function withSteps(fn, { of = null } = {}) { return (request, live) => { let first = true; const step = (label, u = {}) => { const o = first && of && u.of == null ? { of } : {}; first = false; return live ? live.step(label, { ...o, ...u }) : Promise.resolve(null); }; return fn(request, step, live ? live.show : async () => null); }; }