openvibers/openvibe.markets Commits

Search by photo (v0.2) (#3)

OP OpenVibers committed 13 days ago · de73eebb20 · 11 files, +254 −16

Plan §L.1 ("photograph a thing → Vision names it → Markets finds it everywhere"). A photo, shrunk to 1024 px
in the browser (its camera data not carried over), goes once to OpenVibe Vision's ask with Markets' own token
(client_credentials, audience openvibe.vision, scope vision.image.ask; Network #1118); the answer, a short
shopping search, is searched ("From your photo: …"). "none" and an unreadable photo are said plainly. Ten
an hour per address and a daily total (a model call each); a cross-site post is refused; without the
secret the button is not shown. Markets keeps nothing of the photo. test/photo.test.js.

Changes

ddiff --git a/.env.example b/.env.example
iindex 559f5b1..fabcaad 100644
---- a/.env.example
++++ b/.env.example
@@@ -4,3 +4,8 @@ HOST=127.0.0.1
# Deals' API over loopback (GET /api/v1/search, Deals #380).
DEALS_URL=http://127.0.0.1:4840
DEALS_TIMEOUT_MS=5000
++# Search by photo (Network #1118: client 'markets', grant vision.image.ask). Off without the secret.
++OV_OAUTH_CLIENT_ID=markets
++OV_OAUTH_CLIENT_SECRET=
++OV_NETWORK_INTERNAL_URL=http://127.0.0.1:4000
++VISION_URL=http://127.0.0.1:5130
ddiff --git a/README.md b/README.md
iindex 9bf2b86..8b08daa 100644
---- a/README.md
++++ b/README.md
@@@ -4,7 +4,7 @@ Every marketplace, one search: **https://openvibe.markets** (plan §L.1).
**Run it:** `npm ci && npm start` (Node 22 or newer) · **Tests:** `npm test` · **Port:** 5294 · **Service id:** `markets`
--## What it does today (v0.1)
++## What it does today (v0.2)
- **One search box.** Words in; results from OpenVibe Deals' offers first (Deals keeps the one product graph: no second
catalogue here). Each result says its store and its source, and its price **as of** when it was seen, never "now";
@@@ -13,10 +13,13 @@ Every marketplace, one search: **https://openvibe.markets** (plan §L.1).
Marketplace, OfferUp, Mercari, Poshmark, Back Market, Swappa and Reverb open their own search with the words already
in, in a new tab. Markets fetches nothing from them and never sees what happens there. As a permitted API or a
licensed feed comes for one (eBay's Browse API, Best Buy's catalogue, affiliate feeds), its listings join the results.
++- **Search by photo.** A photo of the thing (shrunk to 1024 px in the browser, its camera data not carried over) goes
++ once to OpenVibe Vision, which names it as a short shopping search with Markets' own token (Network #1118:
++ `vision.image.ask`); those words are searched. Neither keeps the photo. Ten an hour per address, a daily total.
- **Neutral and private.** A commission never raises a result. Searching needs no account; the words are not kept.
- `GET /api/v1/search?q=` answers `{ q, deals: { ok, total, results }, elsewhere: [{ name, kind, url }] }`.
--Next (plan §L.1's order): eBay and Best Buy through their APIs (keys), Vision image search, affiliate feeds, Compare
++Next (plan §L.1's order): eBay and Best Buy through their APIs (keys), affiliate feeds, Compare
and Reviews, Watch alerts, then sellers and sessions through Link.
## Running
@@@ -27,6 +30,8 @@ and Reviews, Watch alerts, then sellers and sessions through Link.
| `HOST` | 127.0.0.1 |
| `DEALS_URL` | Deals over loopback, `http://127.0.0.1:4840` (`GET /api/v1/search`, Deals #380) |
| `DEALS_TIMEOUT_MS` | 5000 |
++| `OV_OAUTH_CLIENT_ID`, `OV_OAUTH_CLIENT_SECRET` | the `markets` service principal (search by photo; off without the secret) |
++| `OV_NETWORK_INTERNAL_URL`, `VISION_URL` | `http://127.0.0.1:4000`, `http://127.0.0.1:5130` |
Production: `/opt/openvibe.markets`, unit `openvibe-markets.service`, env `/etc/openvibe/markets.env`, vhost
`deploy/nginx/openvibe.markets.conf`; deployed with `ovhost deploy markets`.
ddiff --git a/package-lock.json b/package-lock.json
iindex f7947e4..e32c989 100644
---- a/package-lock.json
++++ b/package-lock.json
@@@ -1,12 +1,12 @@
{
"name": "openvibe-markets",
-- "version": "0.1.0",
++ "version": "0.2.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "openvibe-markets",
-- "version": "0.1.0",
++ "version": "0.2.0",
"license": "AGPL-3.0-only",
"dependencies": {
"express": "^4.21.2",
ddiff --git a/package.json b/package.json
iindex e744eb9..51a2bf8 100644
---- a/package.json
++++ b/package.json
@@@ -1,8 +1,8 @@
{
"name": "openvibe-markets",
-- "version": "0.1.0",
++ "version": "0.2.0",
"private": true,
-- "description": "openvibe.markets: every marketplace, one search (plan §L.1). The surface over OpenVibe Deals, with the marketplaces opened with the search filled in.",
++ "description": "openvibe.markets: every marketplace, one search (plan \u00a7L.1). The surface over OpenVibe Deals, with the marketplaces opened with the search filled in.",
"main": "server/index.js",
"scripts": {
"start": "node server/index.js",
ddiff --git a/public/markets.css b/public/markets.css
iindex abaf5c5..e44ba06 100644
---- a/public/markets.css
++++ b/public/markets.css
@@@ -55,3 +55,15 @@ html[data-ov-motion="off"] .mk-elsewhere a, html[data-ov-motion="off"] .mk-btn {
.mk-card--text .mk-card-price { grid-column: 1; }
.mk-afford { min-height: 44px; padding: 0 2px; }
}
++/* Search by photo (v0.2). */
++.mk-photo { display: flex; flex-wrap: wrap; align-items: center; gap: 8px 12px; margin: 10px 0 0; }
++.mk-photo-btn { position: relative; gap: 8px; }
++.mk-photo-btn input { inset: 0; }
++.mk-photo-said { color: var(--text-secondary, #9aa4b2); font-size: 14px; }
++.mk-photo.is-busy .mk-photo-btn { opacity: .6; pointer-events: none; }
++.mk-photo.is-busy .mk-photo-said { color: var(--text, #e8ecf3); animation: mk-pulse 1.2s ease-in-out infinite; }
++html[data-ov-motion="off"] .mk-photo.is-busy .mk-photo-said { animation: none; }
++@keyframes mk-pulse { 50% { opacity: .55; } }
++.mk-error { padding: 10px 14px; border-radius: 12px; border: 1px solid var(--danger, #b91c1c); color: var(--danger, #fca5a5); }
++.mk-from-photo { margin: 8px 0 0; color: var(--text-secondary, #9aa4b2); }
++.mk-from-photo b { color: var(--text, #e8ecf3); }
ddiff --git a/public/markets.js b/public/markets.js
nnew file mode 100644
iindex 0000000..03b0d8d
---- /dev/null
++++ b/public/markets.js
@@@ -0,0 +1,30 @@
++// OpenVibe.Markets: search by photo. The chosen photo is redrawn at most 1024 px wide as a JPEG (smaller, faster, and
++// the camera's own data, its place included, is not carried over), then sent once for OpenVibe Vision to name.
++(function () {
++ document.addEventListener('change', function (e) {
++ var input = e.target;
++ if (!input || !input.matches || !input.matches('input[data-mk-photo]') || !input.files || !input.files[0]) return;
++ var form = input.closest('form');
++ var out = form && form.querySelector('[data-mk-image]');
++ var said = form && form.querySelector('[data-mk-photo-said]');
++ if (!out) return;
++ var file = input.files[0];
++ if (!/^image\//.test(file.type)) { if (said) said.textContent = 'That is not a photo.'; return; }
++ if (said) said.textContent = 'Looking at your photo…';
++ form.classList.add('is-busy');
++ var url = URL.createObjectURL(file);
++ var img = new Image();
++ img.onload = function () {
++ var scale = Math.min(1, 1024 / Math.max(img.naturalWidth, img.naturalHeight));
++ var c = document.createElement('canvas');
++ c.width = Math.max(1, Math.round(img.naturalWidth * scale));
++ c.height = Math.max(1, Math.round(img.naturalHeight * scale));
++ c.getContext('2d').drawImage(img, 0, 0, c.width, c.height);
++ URL.revokeObjectURL(url);
++ out.value = c.toDataURL('image/jpeg', 0.85);
++ form.submit();
++ };
++ img.onerror = function () { URL.revokeObjectURL(url); form.classList.remove('is-busy'); if (said) said.textContent = 'That photo could not be opened.'; };
++ img.src = url;
++ });
++})();
ddiff --git a/server/app.js b/server/app.js
iindex 53cc3cb..aca8b75 100644
---- a/server/app.js
++++ b/server/app.js
@@@ -17,7 +17,22 @@ const { linksFor } = require('./elsewhere');
const clean = (q) => String(q || '').replace(/\s+/g, ' ').trim().slice(0, 100);
--function createApp({ deals, now = () => Date.now() }) {
++/** At most `max` in a sliding window, per key (and one key for all): search by photo costs a model call. */
++function limiter(max, windowMs) {
++ const seen = new Map();
++ return (key, t) => {
++ const list = (seen.get(key) || []).filter((x) => t - x < windowMs);
++ if (list.length >= max) { seen.set(key, list); return false; }
++ list.push(t);
++ seen.set(key, list);
++ if (seen.size > 20000) seen.delete(seen.keys().next().value);
++ return true;
++ };
++}
++
++function createApp({ deals, vision = null, now = () => Date.now(), photoLimits = { perHour: 10, perDay: 300 } }) {
++ const perAddress = limiter(photoLimits.perHour, 3600e3);
++ const perDay = limiter(photoLimits.perDay, 24 * 3600e3);
const app = express();
app.disable('x-powered-by');
app.set('trust proxy', 'loopback');
@@@ -49,13 +64,26 @@ function createApp({ deals, now = () => Date.now() }) {
app.get('/', handle(async (req, res) => {
const q = clean(req.query.q);
if (q) return res.redirect(302, `/search?q=${encodeURIComponent(q)}`);
-- res.set('Cache-Control', 'public, max-age=300').send(v.home());
++ res.set('Cache-Control', 'public, max-age=300').send(v.home({ photo: Boolean(vision && vision.ready) }));
}));
app.get('/search', handle(async (req, res) => {
const q = clean(req.query.q);
if (!q) return res.redirect(302, '/');
const out = await find(q);
-- res.set({ 'Cache-Control': 'public, max-age=60', 'X-Robots-Tag': 'noindex, follow' }).send(v.results({ q, deals: out.deals, links: out.elsewhere, now: now() }));
++ res.set({ 'Cache-Control': 'public, max-age=60', 'X-Robots-Tag': 'noindex, follow' }).send(v.results({ q, deals: out.deals, links: out.elsewhere, now: now(), fromPhoto: req.query.from === 'photo' }));
++ }));
++ // Search by photo (v0.2): Vision names it, Markets searches the words. Nothing of the photo is kept here.
++ app.post('/photo', express.urlencoded({ extended: false, limit: '3mb' }), handle(async (req, res) => {
++ res.set('Cache-Control', 'no-store');
++ const site = req.get('sec-fetch-site');
++ if (site && site !== 'same-origin') return res.status(403).send(v.home({ photo: true, error: 'A photo search must come from openvibe.markets itself.' }));
++ if (!vision || !vision.ready) return res.status(503).send(v.home({ error: 'Search by photo is not set up here yet.' }));
++ const t = now();
++ if (!perAddress(`ip:${req.ip}`, t)) return res.status(429).send(v.home({ photo: true, error: 'That is ten photos this hour from here. Type the name instead, or try again later.' }));
++ if (!perDay('all', t)) return res.status(429).send(v.home({ photo: true, error: 'Search by photo has had its fill for today. Type the name instead.' }));
++ const out = await vision.name(String(req.body.image || ''));
++ if (!out.ok) return res.status(422).send(v.home({ photo: true, error: out.error }));
++ res.redirect(303, `/search?q=${encodeURIComponent(out.query)}&from=photo`);
}));
app.get('/api/v1/search', handle(async (req, res) => {
const q = clean(req.query.q);
ddiff --git a/server/index.js b/server/index.js
iindex 0400d56..5f76c1b 100644
---- a/server/index.js
++++ b/server/index.js
@@@ -5,9 +5,13 @@
*/
const { createApp } = require('./app');
const { createDeals } = require('./deals');
++const { createVision } = require('./vision');
const env = process.env;
const port = Number(env.PORT || 5294);
const deals = createDeals({ baseUrl: env.DEALS_URL || 'http://127.0.0.1:4840', timeoutMs: Number(env.DEALS_TIMEOUT_MS || 5000) });
--const server = createApp({ deals }).listen(port, env.HOST || '127.0.0.1', () => console.log(`[markets] listening on ${env.HOST || '127.0.0.1'}:${port}`));
++// Search by photo: OpenVibe Vision's ask with Markets' own token (Network #1118); off without a client secret.
++const vision = createVision({ visionUrl: env.VISION_URL || 'http://127.0.0.1:5130', networkUrl: env.OV_NETWORK_INTERNAL_URL || 'http://127.0.0.1:4000',
++ clientId: env.OV_OAUTH_CLIENT_ID || 'markets', clientSecret: env.OV_OAUTH_CLIENT_SECRET || '' });
++const server = createApp({ deals, vision }).listen(port, env.HOST || '127.0.0.1', () => console.log(`[markets] listening on ${env.HOST || '127.0.0.1'}:${port}`));
process.on('SIGTERM', () => server.close(() => process.exit(0)));
ddiff --git a/server/views.js b/server/views.js
iindex 48a3885..e4ef91f 100644
---- a/server/views.js
++++ b/server/views.js
@@@ -44,7 +44,7 @@ function page({ title, body, path = '/', description = 'Every marketplace, one s
name: 'OpenVibe.Markets', siteName: 'OpenVibe.Markets', title, description, canonical: `${SITE}${path}`, robots,
navbar: { service: 'markets', apiBase: 'https://openvibe.network', links: [{ label: 'Search', href: '/' }, { label: 'Deals', href: 'https://openvibe.deals/' }] },
footer: { service: 'markets', variant: 'full', mount: '#ov-footer' },
-- head: `<link rel="stylesheet" href="${serve.url('kit.css')}"><link rel="stylesheet" href="${asset('markets.css')}">`,
++ head: `<link rel="stylesheet" href="${serve.url('kit.css')}"><link rel="stylesheet" href="${asset('markets.css')}"><script src="${asset('markets.js')}" defer></script>`,
body: `<div id="navbar-mount"></div><main id="main" class="ovk-page mk">${body}</main>`,
});
}
@@@ -53,21 +53,27 @@ const searchForm = (q = '') => `<form class="mk-search" method="get" action="/se
<label class="mk-search-box"><span class="mk-sr">What are you looking for?</span><input type="search" name="q" value="${esc(q)}" placeholder="Headphones, a sofa, a used road bike…" maxlength="100" autocomplete="off" required data-ov-trending="own"></label>
<button class="mk-btn mk-btn--primary" type="submit">Search</button></form>`;
--function home() {
++/** Search by photo (v0.2): the photo is shrunk in the browser and sent once for OpenVibe Vision to name. */
++const photoForm = () => `<form class="mk-photo" method="post" action="/photo">
++<input type="hidden" name="image" value="" data-mk-image>
++<label class="mk-btn mk-photo-btn"><input type="file" accept="image/*" capture="environment" data-mk-photo class="mk-sr"><span>Search by photo</span></label>
++<span class="mk-photo-said" role="status" data-mk-photo-said>A photo of the thing itself works best.</span></form>`;
++
++function home({ photo = false, error = null } = {}) {
return page({
title: 'Every marketplace, one search', body: `
<section class="mk-hero"><h1>Every marketplace, one search</h1>
<p class="mk-lede">New, used, refurbished and local. Deals the community found, with every price shown as of when it was seen, and the big marketplaces one tap away with your search already in.</p>
--${searchForm()}</section>
++${error ? `<p class="mk-error" role="alert">${esc(error)}</p>` : ''}${searchForm()}${photo ? photoForm() : ''}</section>
<section class="mk-sec"><h2>Where it looks</h2><ul class="mk-places">${PLACES.map((p) => `<li><b>${esc(p.name)}</b><small>${esc(p.kind)}</small></li>`).join('')}</ul></section>
<ul class="mk-promises">
<li><b>Neutral.</b> A commission never raises a result. Every result says where it is from and when its price was seen.</li>
<li><b>A price is an observation.</b> It is shown as of its time, never as "now".</li>
--<li><b>Nothing about you.</b> Searching needs no account, and your words are not kept.</li>
++<li><b>Nothing about you.</b> Searching needs no account, and your words are not kept. A photo is sent once to OpenVibe Vision to name what it shows; neither keeps the photo.</li>
</ul>` });
}
--function results({ q, deals, links, now = Date.now() }) {
++function results({ q, deals, links, now = Date.now(), fromPhoto = false }) {
// A deal without a picture takes the whole width: no empty square.
const card = (r) => `<li class="mk-card${r.image ? '' : ' mk-card--text'}">${r.image ? `<img class="mk-card-img" src="${esc(r.image)}" alt="" loading="lazy" width="72" height="72">` : ''}
<span class="mk-card-body"><a class="mk-card-title" href="${esc(r.url)}">${esc(r.title)}</a>
@@@ -80,7 +86,7 @@ function results({ q, deals, links, now = Date.now() }) {
: `<p class="mk-empty">${esc(deals.error || 'Deals could not be searched just now.')} The marketplaces below still work.</p>`;
return page({
title: `${q}: every marketplace`, path: `/search?q=${encodeURIComponent(q)}`, robots: 'noindex, follow', body: `
--<header class="mk-head">${searchForm(q)}</header>
++<header class="mk-head">${searchForm(q)}${fromPhoto ? `<p class="mk-from-photo">From your photo: <b>${esc(q)}</b>. Not quite it? Change the words above.</p>` : ''}</header>
<section class="mk-sec" aria-labelledby="mk-deals-h"><h2 id="mk-deals-h">Deals</h2>${found}</section>
<section class="mk-sec" aria-labelledby="mk-else-h"><h2 id="mk-else-h">Search it on</h2>
<ul class="mk-elsewhere">${links.map((l) => `<li><a href="${esc(l.url)}" target="_blank" rel="noopener noreferrer"><b>${esc(l.name)}</b><small>${esc(l.kind)}</small></a></li>`).join('')}</ul>
ddiff --git a/server/vision.js b/server/vision.js
nnew file mode 100644
iindex 0000000..f50245c
---- /dev/null
++++ b/server/vision.js
@@@ -0,0 +1,65 @@
++'use strict';
++/**
++ * Search by photo (plan §L.1: "photograph a thing → Vision names it → Markets finds it everywhere"). OpenVibe.Vision's
++ * ask (POST /api/v1/ask, capability vision.image.ask, Network #1118) names what a picture shows as a short shopping
++ * search; Markets searches those words. Markets keeps nothing of the picture; Vision keeps its hash and the answer's
++ * words, with no person attached (Markets has no sign-in).
++ *
++ * createVision({ visionUrl, networkUrl, clientId, clientSecret, fetchImpl }) → { ready, name(dataUrl) }
++ * name → { ok: true, query } | { ok: false, error } (error is said to the person as it is)
++ * queryOf(text) → the words to search, or null when the picture shows nothing to buy
++ */
++const QUESTION = 'What product is in this picture? Answer with only a short shopping search for it: the brand, the model and what it is, at most eight words. If it is not something people buy, answer exactly: none';
++
++function queryOf(text) {
++ const line = String(text || '').split('\n').map((l) => l.trim()).find(Boolean) || '';
++ const q = line.replace(/^["'“”‘’`*\-\s]+|["'“”‘’`*.\s]+$/g, '').replace(/\s+/g, ' ').slice(0, 80).trim();
++ if (!q || /^none\b/i.test(q) || q.length < 2) return null;
++ return q;
++}
++
++function createVision({ visionUrl, networkUrl, clientId = 'markets', clientSecret, fetchImpl = globalThis.fetch, timeoutMs = 30000 } = {}) {
++ const base = String(visionUrl || '').replace(/\/+$/, '');
++ const net = String(networkUrl || '').replace(/\/+$/, '');
++ const ready = Boolean(base && net && clientSecret);
++ let token = null;
++ let until = 0;
++
++ async function tokenNow() {
++ if (token && Date.now() < until) return token;
++ const res = await fetchImpl(`${net}/oauth/token`, {
++ method: 'POST', redirect: 'error', signal: AbortSignal.timeout(10000),
++ headers: { 'content-type': 'application/x-www-form-urlencoded', accept: 'application/json' },
++ body: new URLSearchParams({ grant_type: 'client_credentials', client_id: clientId, client_secret: clientSecret, audience: 'openvibe.vision', scope: 'vision.image.ask' }).toString(),
++ });
++ const body = await res.json().catch(() => null);
++ if (!res.ok || !body || !body.access_token) throw new Error(`token ${res.status}`);
++ token = body.access_token;
++ until = Date.now() + Math.max(30, (Number(body.expires_in) || 300) - 30) * 1000;
++ return token;
++ }
++
++ async function name(dataUrl) {
++ if (!ready) return { ok: false, error: 'Search by photo is not set up here yet.' };
++ if (!/^data:image\/(jpeg|png|webp);base64,[A-Za-z0-9+/=]+$/.test(String(dataUrl || ''))) return { ok: false, error: 'That is not a photo Markets can read (JPEG, PNG or WebP).' };
++ try {
++ const res = await fetchImpl(`${base}/api/v1/ask`, {
++ method: 'POST', redirect: 'error', signal: AbortSignal.timeout(timeoutMs),
++ headers: { 'content-type': 'application/json', accept: 'application/json', authorization: `Bearer ${await tokenNow()}` },
++ body: JSON.stringify({ task: 'identify', question: QUESTION, image: dataUrl, mode: 'auto' }),
++ });
++ if (res.status === 401 || res.status === 403) { token = null; until = 0; }
++ const body = await res.json().catch(() => null);
++ if (!res.ok || !body || !body.answer) return { ok: false, error: 'OpenVibe Vision could not look at the photo just now.' };
++ const query = queryOf(body.answer.text);
++ if (!query) return { ok: false, error: 'That photo does not seem to show something to buy. Try a closer shot of the thing itself, or type its name.' };
++ return { ok: true, query };
++ } catch {
++ return { ok: false, error: 'OpenVibe Vision did not answer in time. Try again, or type its name.' };
++ }
++ }
++
++ return { ready, name };
++}
++
++module.exports = { createVision, queryOf, QUESTION };
ddiff --git a/test/photo.test.js b/test/photo.test.js
nnew file mode 100644
iindex 0000000..ab67353
---- /dev/null
++++ b/test/photo.test.js
@@@ -0,0 +1,83 @@
++'use strict';
++/**
++ * Search by photo (v0.2; server/vision.js): Markets asks Vision with its own token (client_credentials, audience
++ * openvibe.vision, scope vision.image.ask), turns the answer into words and searches them; "none" and a broken photo
++ * are said plainly; ten photos an hour per address and a daily total; a cross-site post is refused; without a secret
++ * the button is not shown and the route says so.
++ */
++const assert = require('assert');
++const http = require('node:http');
++const { createApp } = require('../server/app');
++const { createVision, queryOf } = require('../server/vision');
++
++assert.strictEqual(queryOf('"Sony WH-1000XM5 wireless headphones."'), 'Sony WH-1000XM5 wireless headphones');
++assert.strictEqual(queryOf('none'), null);
++assert.strictEqual(queryOf('None.'), null);
++assert.strictEqual(queryOf(' \n Lego Technic 42115 Lamborghini \nextra'), 'Lego Technic 42115 Lamborghini');
++
++const JPEG = `data:image/jpeg;base64,${Buffer.from('fake jpeg bytes').toString('base64')}`;
++
++(async () => {
++ const calls = [];
++ let answer = 'Sony WH-1000XM5 wireless headphones';
++ const fake = http.createServer(async (req, res) => {
++ let body = '';
++ for await (const c of req) body += c;
++ calls.push({ path: req.url, auth: req.headers.authorization || null, body });
++ res.setHeader('content-type', 'application/json');
++ if (req.url === '/oauth/token') return res.end(JSON.stringify({ access_token: 'svc-markets', expires_in: 300 }));
++ if (req.url === '/api/v1/ask') { res.statusCode = 201; return res.end(JSON.stringify({ answer: { text: answer, cost_usd: 0.001 } })); }
++ res.statusCode = 404; res.end('{}');
++ });
++ await new Promise((r) => fake.listen(0, '127.0.0.1', r));
++ const at = `http://127.0.0.1:${fake.address().port}`;
++ const deals = { search: async () => ({ ok: true, total: 0, results: [] }) };
++ const vision = createVision({ visionUrl: at, networkUrl: at, clientSecret: 'shh' });
++ const server = createApp({ deals, vision, photoLimits: { perHour: 3, perDay: 5 } }).listen(0, '127.0.0.1');
++ await new Promise((r) => server.once('listening', r));
++ const base = `http://127.0.0.1:${server.address().port}`;
++ const send = (image, site = 'same-origin') => fetch(`${base}/photo`, { method: 'POST', redirect: 'manual', headers: { 'content-type': 'application/x-www-form-urlencoded', 'sec-fetch-site': site }, body: new URLSearchParams({ image }).toString() })
++ .then(async (r) => ({ status: r.status, location: r.headers.get('location'), text: await r.text() }));
++ try {
++ const home = await fetch(`${base}/`).then((r) => r.text());
++ assert.match(home, /Search by photo/);
++ assert.match(home, /src="\/markets\.js\?v=[0-9a-f]{10}"/);
++
++ let r = await send(JPEG);
++ assert.deepStrictEqual([r.status, r.location], [303, '/search?q=Sony%20WH-1000XM5%20wireless%20headphones&from=photo']);
++ const tok = calls.find((c) => c.path === '/oauth/token');
++ assert.deepStrictEqual(Object.fromEntries(new URLSearchParams(tok.body)), { grant_type: 'client_credentials', client_id: 'markets', client_secret: 'shh', audience: 'openvibe.vision', scope: 'vision.image.ask' });
++ const ask = calls.find((c) => c.path === '/api/v1/ask');
++ assert.strictEqual(ask.auth, 'Bearer svc-markets');
++ const sent = JSON.parse(ask.body);
++ assert.deepStrictEqual([sent.task, sent.mode, sent.image], ['identify', 'auto', JPEG]);
++ const page = await fetch(`${base}${r.location}`).then((x) => x.text());
++ assert.match(page, /From your photo: <b>Sony WH-1000XM5 wireless headphones<\/b>/);
++
++ answer = 'none';
++ r = await send(JPEG);
++ assert.strictEqual(r.status, 422);
++ assert.match(r.text, /does not seem to show something to buy/);
++ r = await send('data:text/html;base64,PGI+');
++ assert.match(r.text, /not a photo Markets can read/);
++ r = await send(JPEG);
++ assert.strictEqual(r.status, 429, 'three an hour here (ten in production)');
++ assert.match(r.text, /photos this hour/);
++ r = await send(JPEG, 'cross-site');
++ assert.strictEqual(r.status, 403);
++ assert.strictEqual(calls.filter((c) => c.path === '/oauth/token').length, 1, 'the token is kept for its life');
++
++ // No secret: no button, and the route says so.
++ const off = createApp({ deals, vision: createVision({ visionUrl: at, networkUrl: at, clientSecret: '' }) }).listen(0, '127.0.0.1');
++ await new Promise((x) => off.once('listening', x));
++ const offBase = `http://127.0.0.1:${off.address().port}`;
++ assert.doesNotMatch(await fetch(`${offBase}/`).then((x) => x.text()), /Search by photo/);
++ const o = await fetch(`${offBase}/photo`, { method: 'POST', headers: { 'content-type': 'application/x-www-form-urlencoded', 'sec-fetch-site': 'same-origin' }, body: `image=${encodeURIComponent(JPEG)}` });
++ assert.strictEqual(o.status, 503);
++ off.close();
++ } finally {
++ server.close();
++ fake.close();
++ }
++ console.log('photo: Vision names it with Markets\' own token, the words are searched, "none" and limits said plainly');
++})().catch((err) => { console.error(err); process.exit(1); });