openvibers/openvibe.markets serverapp.js

app.js

main 7.6 KB · 116 lines · javascript

1'use strict';
2/**
3 * OpenVibe.Markets (plan §L.1): every marketplace, one search. The surface and the search orchestrator; Deals keeps the
4 * product graph (no second catalogue), and the marketplaces with no permitted feed yet are opened with the search filled
5 * in.
6 *
7 * createApp({ deals, now }) → an Express app
8 * deals: server/deals.js's client ({ search(q, { limit }) })
9 *
10 * Pages: / (the search), /search?q= (results; noindex). API: GET /api/v1/search?q= → { q, deals, elsewhere }.
11 * No account, no cookie, nothing kept: the words are not logged or stored.
12 */
13const express = require('express');
14const path = require('node:path');
15const v = require('./views');
16const { linksFor } = require('./elsewhere');
17
18const clean = (q) => String(q || '').replace(/\s+/g, ' ').trim().slice(0, 100);
19
20/** At most `max` in a sliding window, per key (and one key for all): search by photo costs a model call. */
21function limiter(max, windowMs) {
22 const seen = new Map();
23 return (key, t) => {
24 const list = (seen.get(key) || []).filter((x) => t - x < windowMs);
25 if (list.length >= max) { seen.set(key, list); return false; }
26 list.push(t);
27 seen.set(key, list);
28 if (seen.size > 20000) seen.delete(seen.keys().next().value);
29 return true;
30 };
31}
32
33function createApp({ deals, vision = null, now = () => Date.now(), photoLimits = { perHour: 10, perDay: 300 } }) {
34 const perAddress = limiter(photoLimits.perHour, 3600e3);
35 const perDay = limiter(photoLimits.perDay, 24 * 3600e3);
36 const app = express();
37 app.disable('x-powered-by');
38 app.set('trust proxy', 'loopback');
39 try {
40 const release = require('openvibe-shared/release').createRelease({ service: 'markets', root: path.join(__dirname, '..') });
41 require('openvibe-shared/metrics').instrument(app, { service: 'markets', release: release.release });
42 app.get('/release.json', release.handler);
43 } catch { /* metrics are optional in tests */ }
44 app.use((req, res, next) => {
45 res.set({ 'X-Content-Type-Options': 'nosniff', 'Referrer-Policy': 'strict-origin-when-cross-origin', 'X-Frame-Options': 'DENY' });
46 next();
47 });
48 app.get('/api/health', (_req, res) => res.json({ status: 'ok', service: 'markets' }));
49 app.get('/api/ready', (_req, res) => res.json({ status: 'ok', service: 'markets' }));
50 // Every page crawlable, by every bot, AI included (the owner, 2026-11-21: "Everything should be just crawlable"); a search
51 // here reads OpenVibe Deals only, so it is no cost to open. The site had no sitemap.
52 const seo = require('openvibe-shared/seo');
53 app.get('/robots.txt', (_req, res) => res.type('text').set('Cache-Control', 'public, max-age=3600').send(seo.robotsTxt({ disallow: ['/auth/'], sitemaps: ['https://openvibe.markets/sitemap.xml'] })));
54 app.get('/sitemap.xml', (_req, res) => res.type('application/xml').set('Cache-Control', 'public, max-age=3600').send(seo.sitemapXml([{ loc: 'https://openvibe.markets/', changefreq: 'daily', priority: 1.0 }])));
55 app.get('/llms.txt', (_req, res) => res.type('text').send([
56 '# OpenVibe.Markets', '', '> Every marketplace, one search: OpenVibe Deals\' offers (each price as of its time) and the big marketplaces opened with the search filled in.', '',
57 '- Search: https://openvibe.markets/search?q=<words>', '- API: GET https://openvibe.markets/api/v1/search?q=<words> → { q, deals: { ok, total, results }, elsewhere: [{ name, kind, url }] }', '',
58 '## Optional', '', '- [Full text (llms-full.txt)](https://openvibe.markets/llms-full.txt): the home page as words', '',
59 ].join('\n')));
60 // The full text for language models (SEO-33): the home page as Markdown from its own render (11-28: /llms-full.txt
61 // was a 404 to agents, tools/llms-check.js).
62 app.get('/llms-full.txt', (_req, res) => {
63 const words = require('openvibe-shared/agent-layer').markdownTwin({ html: v.home({ photo: Boolean(vision && vision.ready) }), canonical: 'https://openvibe.markets/' }).replace(/^---[\s\S]*?\n---\n/, '').trim();
64 res.type('text').set('Cache-Control', 'public, max-age=3600').send(seo.llmsFull({
65 site: { name: 'OpenVibe.Markets', url: 'https://openvibe.markets' },
66 summary: 'Every marketplace, one search: OpenVibe Deals\' offers (each price as of its time) and the big marketplaces opened with the search filled in.',
67 sections: [{ title: 'OpenVibe.Markets', url: '/', body: words }],
68 }));
69 });
70 app.use(express.static(path.join(__dirname, '..', 'public'), { maxAge: '1h' }));
71 app.use('/shared', require('openvibe-shared/serve').handler());
72
73 async function find(q) {
74 const [found] = await Promise.all([deals.search(q, { limit: 24 })]);
75 return { deals: found, elsewhere: linksFor(q) };
76 }
77 const handle = (fn) => (req, res, next) => Promise.resolve(fn(req, res)).catch(next);
78
79 app.get('/', handle(async (req, res) => {
80 const q = clean(req.query.q);
81 if (q) return res.redirect(302, `/search?q=${encodeURIComponent(q)}`);
82 res.set('Cache-Control', 'public, max-age=300').send(v.home({ photo: Boolean(vision && vision.ready) }));
83 }));
84 app.get('/search', handle(async (req, res) => {
85 const q = clean(req.query.q);
86 if (!q) return res.redirect(302, '/');
87 const out = await find(q);
88 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' }));
89 }));
90 // Search by photo (v0.2): Vision names it, Markets searches the words. Nothing of the photo is kept here.
91 app.post('/photo', express.urlencoded({ extended: false, limit: '3mb' }), handle(async (req, res) => {
92 res.set('Cache-Control', 'no-store');
93 const site = req.get('sec-fetch-site');
94 if (site && site !== 'same-origin') return res.status(403).send(v.home({ photo: true, error: 'A photo search must come from openvibe.markets itself.' }));
95 if (!vision || !vision.ready) return res.status(503).send(v.home({ error: 'Search by photo is not set up here yet.' }));
96 const t = now();
97 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.' }));
98 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.' }));
99 const out = await vision.name(String(req.body.image || ''));
100 if (!out.ok) return res.status(422).send(v.home({ photo: true, error: out.error }));
101 res.redirect(303, `/search?q=${encodeURIComponent(out.query)}&from=photo`);
102 }));
103 app.get('/api/v1/search', handle(async (req, res) => {
104 const q = clean(req.query.q);
105 if (!q) return res.status(422).json({ error: 'Say what to search for (?q=).', code: 'markets.search.words' });
106 const out = await find(q);
107 res.set('Cache-Control', 'public, max-age=60').json({ q, deals: out.deals, elsewhere: out.elsewhere });
108 }));
109 app.use((req, res) => res.status(404).send(v.page({ title: 'Not here', robots: 'noindex, follow', body: '<p class="mk-empty">No such page. <a href="/">Search every marketplace</a>.</p>' })));
110 // eslint-disable-next-line no-unused-vars
111 app.use((err, _req, res, _next) => { console.error('[markets]', err && err.message); res.status(500).send(v.page({ title: 'Something went wrong', robots: 'noindex', body: '<p class="mk-empty">Something went wrong. <a href="/">Try again</a>.</p>' })); });
112 return app;
113}
114
115module.exports = { createApp };
116