Repository navigation
Expand file tree
/
Copy pathserver.js
More file actions
430 lines (380 loc) · 15.3 KB
/
Copy pathserver.js
File metadata and controls
430 lines (380 loc) · 15.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
// BLOOMWIRE — an agent-ready storefront demonstration.
// One process, no database, no build step: `npm install && npm start`.
import express from 'express';
import { readFileSync } from 'node:fs';
import { join, dirname } from 'node:path';
import { fileURLToPath } from 'node:url';
import { publish, sseHandler, recentEvents } from './lib/bus.js';
import {
searchProducts,
getProduct,
cartView,
addToCart,
removeFromCart,
clearCart,
getOrder,
} from './lib/store.js';
import { ucpRouter, ucpDiscovery } from './lib/ucp.js';
import { checkoutViaUCP } from './lib/checkout.js';
import {
createSession,
getSession,
pendingSessions,
activeSessions,
resolveSession,
publicView,
sessionByToken,
} from './lib/sessions.js';
import { skills, getSkill, skillsIndexJson } from './lib/skills.js';
import { robotsTxt, llmsTxt, sitemapXml } from './lib/discovery.js';
import { layout } from './lib/html.js';
import { homePage } from './pages/home.js';
import { shopPage, productPage } from './pages/shop.js';
import { skillsPage, skillDetailPage } from './pages/skills.js';
import { authPage } from './pages/auth.js';
import { protocolsPage } from './pages/protocols.js';
const __dirname = dirname(fileURLToPath(import.meta.url));
const PORT = Number(process.env.PORT || 4180);
const SELF_ORIGIN = `http://127.0.0.1:${PORT}`;
// Count the WebMCP tools the client registers, straight from the source file,
// so the SSR pages never drift from reality.
const TOOL_COUNT = (() => {
try {
const src = readFileSync(join(__dirname, 'public', 'js', 'agent.js'), 'utf8');
return (src.match(/^\s{4}\{\s*$\n^\s{6}name: '/gm) || src.match(/name: '[a-z_]+',/g) || []).length || 11;
} catch {
return 11;
}
})();
const app = express();
app.disable('x-powered-by');
/* ---------------- shared middleware ---------------- */
app.use((req, res, next) => {
req.bwStart = performance.now();
// minimal cookie session for the cart
const cookies = Object.fromEntries(
(req.headers.cookie || '')
.split(';')
.map((c) => c.trim().split('='))
.filter((kv) => kv.length === 2)
);
req.bwSession = cookies.bw_session;
if (!req.bwSession) {
req.bwSession = crypto.randomUUID();
res.setHeader('Set-Cookie', `bw_session=${req.bwSession}; Path=/; SameSite=Lax; Max-Age=604800`);
}
next();
});
function publicOrigin(req) {
if (process.env.PUBLIC_ORIGIN) return process.env.PUBLIC_ORIGIN.replace(/\/$/, '');
const proto = req.get('x-forwarded-proto') || req.protocol || 'http';
return `${proto}://${req.get('host')}`;
}
function classifyVisitor(req) {
const raw = req.get('user-agent') || '';
const agentish = /bot|gpt|claude|codex|gemini|agent|perplexity|python|curl|httpx|node-fetch|headless/i.test(raw);
// compress the UA to its most telling token — feeds are for reading
const m = raw.match(
/(GPTBot|OAI-SearchBot|ChatGPT-User|ClaudeBot|Claude-User|Claude-SearchBot|PerplexityBot|Google-Extended|codex[\w-]*|HeadlessChrome|curl\/[\d.]+|python-\w+\/?[\d.]*|httpx|node|Firefox|Edg|Chrome\/[\d.]+|Safari)/i
);
const ua = m ? m[0] : raw.slice(0, 40) || '(no user-agent)';
return { agentish, ua };
}
function pageView(req, title) {
const { agentish, ua } = classifyVisitor(req);
publish({
source: 'system',
kind: 'lifecycle',
tone: agentish ? 'agent' : 'info',
title: `${agentish ? '🤖 ' : ''}GET ${req.path}`,
detail: `${title} · ${agentish ? 'agent-like visitor' : 'visitor'} · ${ua}`,
});
}
function cart(req) {
return cartView(req.bwSession);
}
/* Suppress duplicate feed entries for calls the WebMCP layer already beacons. */
function fromToolLayer(req) {
return req.get('x-bw-source') === 'webmcp';
}
/* auth.md promise: authorized calls are attributed to the agent by name. */
function attributed(req, detail) {
const m = (req.get('authorization') || '').match(/^Bearer\s+(\S+)/i);
const session = m && sessionByToken(m[1]);
return session ? `${detail} · by ${session.agent_name} 🔓` : detail;
}
/* ---------------- pages ---------------- */
app.get('/', (req, res) => {
pageView(req, 'Home');
res.send(homePage(req, { cartCount: cart(req).item_count, toolCount: TOOL_COUNT, skillCount: skills.length }));
});
app.get('/shop', (req, res) => {
pageView(req, 'Shop');
res.send(shopPage(req, { products: searchProducts(), cart: cart(req) }));
});
app.get('/shop/:slug', (req, res, next) => {
const product = getProduct(req.params.slug);
if (!product) return next();
pageView(req, product.name);
res.send(productPage(req, { product, cart: cart(req) }));
});
app.get('/skills', (req, res) => {
pageView(req, 'Agent Skills');
res.send(skillsPage(req, { skills, cartCount: cart(req).item_count }));
});
app.get('/skills/index.json', (req, res) => {
if (!fromToolLayer(req)) {
publish({ source: 'skills', kind: 'api', tone: 'info', title: 'skills index fetched', detail: `${skills.length} skills · ${classifyVisitor(req).ua}` });
}
res.json(skillsIndexJson(publicOrigin(req)));
});
app.get('/skills/:name', (req, res, next) => {
const skill = getSkill(req.params.name);
if (!skill) return next();
pageView(req, `Skill · ${skill.name}`);
res.send(skillDetailPage(req, { skill, cartCount: cart(req).item_count }));
});
app.get('/skills/:name/SKILL.md', (req, res, next) => {
const skill = getSkill(req.params.name);
if (!skill) return next();
if (!fromToolLayer(req)) {
publish({ source: 'skills', kind: 'api', tone: 'agent', title: `📖 SKILL.md fetched · ${skill.name}`, detail: `${skill.bytes} bytes of expertise served · ${classifyVisitor(req).ua}` });
}
res.type('text/markdown; charset=utf-8').send(skill.markdown);
});
app.get('/auth', (req, res) => {
pageView(req, 'Agent Auth');
res.send(
authPage(req, {
pending: pendingSessions().map((s) => publicView(s)),
active: activeSessions().map((s) => publicView(s)),
authMd: readAuthMd(req),
cartCount: cart(req).item_count,
})
);
});
app.get('/protocols', (req, res) => {
pageView(req, 'Protocol Dossier');
res.send(protocolsPage(req, { cartCount: cart(req).item_count, toolCount: TOOL_COUNT, skillCount: skills.length }));
});
/* ---------------- discovery surface ---------------- */
import { authMdContent } from './lib/authmd.js';
function readAuthMd(req) {
return authMdContent(publicOrigin(req));
}
for (const path of ['/auth.md', '/.well-known/auth.md']) {
app.get(path, (req, res) => {
publish({ source: 'auth', kind: 'api', tone: 'agent', title: '📜 auth.md contract fetched', detail: classifyVisitor(req).ua });
res.type('text/markdown; charset=utf-8').send(readAuthMd(req));
});
}
app.get('/.well-known/ucp', (req, res) => {
publish({ source: 'ucp', kind: 'api', tone: 'info', title: 'UCP discovery read', detail: `merchant profile served · ${classifyVisitor(req).ua}` });
res.json(ucpDiscovery(publicOrigin(req)));
});
app.get('/robots.txt', (req, res) => {
publish({ source: 'discovery', kind: 'api', tone: 'info', title: 'robots.txt read', detail: `agents welcomed by name · ${classifyVisitor(req).ua}` });
res.type('text/plain; charset=utf-8').send(robotsTxt(publicOrigin(req)));
});
app.get('/llms.txt', (req, res) => {
if (!fromToolLayer(req)) {
publish({ source: 'discovery', kind: 'api', tone: 'agent', title: '🗺 llms.txt map fetched', detail: classifyVisitor(req).ua });
}
res.type('text/markdown; charset=utf-8').send(llmsTxt(publicOrigin(req)));
});
app.get('/sitemap.xml', (req, res) => {
res.type('application/xml').send(sitemapXml(publicOrigin(req)));
});
/* ---------------- storefront API (cookie-scoped) ---------------- */
const api = express.Router();
api.use(express.json({ limit: '64kb' }));
api.get('/products', (req, res) => {
const maxPrice = req.query.max_price != null ? Number(req.query.max_price) : undefined;
const results = searchProducts(req.query.query || '', {
maxPrice: Number.isFinite(maxPrice) ? maxPrice : undefined,
tag: req.query.tag || undefined,
});
if (!fromToolLayer(req)) {
publish({ source: 'commerce', kind: 'api', tone: 'info', title: 'catalog searched', detail: attributed(req, `${results.length} match(es) · ${classifyVisitor(req).ua}`) });
}
res.json({ count: results.length, products: results.map(productJson) });
});
api.get('/products/:id', (req, res) => {
const product = getProduct(req.params.id);
if (!product) return res.status(404).json({ error: `unknown product "${req.params.id}"` });
if (!fromToolLayer(req)) {
publish({ source: 'commerce', kind: 'api', tone: 'info', title: `product read · ${product.slug}`, detail: attributed(req, classifyVisitor(req).ua) });
}
res.json({ product: productJson(product) });
});
api.post('/cart/items', (req, res) => {
try {
const updated = addToCart(req.bwSession, req.body?.product, req.body?.qty ?? 1);
const product = getProduct(req.body?.product);
if (!fromToolLayer(req)) {
publish({ source: 'commerce', kind: 'api', tone: 'ok', title: `cart + ${product.slug}`, detail: attributed(req, `now ${updated.item_count} item(s) · $${(updated.total / 100).toFixed(2)}`) });
}
res.json({ added: product.sku, cart: updated });
} catch (err) {
res.status(err.status || 400).json({ error: err.message });
}
});
api.get('/cart', (req, res) => {
res.json({ cart: cart(req) });
});
api.delete('/cart/items/:id', (req, res) => {
try {
const qty = req.query.qty != null ? Number(req.query.qty) : null;
const updated = removeFromCart(req.bwSession, req.params.id, qty);
if (!fromToolLayer(req)) {
publish({ source: 'commerce', kind: 'api', tone: 'ok', title: `cart − ${req.params.id}`, detail: attributed(req, `now ${updated.item_count} item(s)`) });
}
res.json({ cart: updated });
} catch (err) {
res.status(err.status || 400).json({ error: err.message });
}
});
api.delete('/cart', (req, res) => {
res.json({ cart: clearCart(req.bwSession) });
});
api.post('/checkout', async (req, res) => {
try {
const result = await checkoutViaUCP({
cartSessionId: req.bwSession,
name: req.body?.name,
email: req.body?.email,
origin: SELF_ORIGIN,
});
res.json(result);
} catch (err) {
res.status(err.status || 500).json({ error: err.message });
}
});
api.get('/orders/:id', (req, res) => {
const order = getOrder(req.params.id);
if (!order) return res.status(404).json({ error: `unknown order "${req.params.id}"` });
res.json({ order });
});
/* ---------------- agent auth sessions ---------------- */
api.post('/agent/sessions', (req, res) => {
const session = createSession({ agent_name: req.body?.agent_name, scopes: req.body?.scopes });
publish({
source: 'auth',
kind: 'api',
tone: 'warn',
title: `🔑 ${session.agent_name} requests a session`,
detail: `code ${session.user_code} awaiting human approval at /auth · scopes: ${session.scopes.join(' ')}`,
});
res.status(201).json({ session: publicView(session) });
});
api.get('/agent/sessions', (req, res) => {
res.json({
pending: pendingSessions().map((s) => publicView(s)),
active: activeSessions().map((s) => publicView(s)),
});
});
api.get('/agent/sessions/:id', (req, res) => {
const session = getSession(req.params.id);
if (!session) return res.status(404).json({ error: `unknown session "${req.params.id}"` });
if (session.status === 'approved' && !session.token_delivered) {
session.token_delivered = true;
publish({ source: 'auth', kind: 'api', tone: 'ok', title: `🔓 token delivered to ${session.agent_name}`, detail: `scopes: ${session.scopes.join(' ')} · expires ${session.token_expires_at}` });
}
res.json({ session: publicView(session, { includeToken: true }) });
});
api.post('/agent/sessions/:id/approve', (req, res) => {
const wasPending = getSession(req.params.id)?.status === 'pending';
const session = resolveSession(req.params.id, true);
if (!session) return res.status(404).json({ error: `unknown session "${req.params.id}"` });
if (wasPending) {
publish({ source: 'auth', kind: 'api', tone: 'ok', title: `✅ human approved ${session.agent_name}`, detail: `code ${session.user_code} · scopes granted: ${session.scopes.join(' ')}` });
}
res.json({ session: publicView(session) });
});
api.post('/agent/sessions/:id/deny', (req, res) => {
const wasPending = getSession(req.params.id)?.status === 'pending';
const session = resolveSession(req.params.id, false);
if (!session) return res.status(404).json({ error: `unknown session "${req.params.id}"` });
if (wasPending) {
publish({ source: 'auth', kind: 'api', tone: 'warn', title: `⛔ human denied ${session.agent_name}`, detail: `code ${session.user_code}` });
}
res.json({ session: publicView(session) });
});
/* ---------------- telemetry ---------------- */
api.get('/telemetry/stream', sseHandler);
api.get('/telemetry/recent', (req, res) => {
res.json({ events: recentEvents(50) });
});
api.post('/telemetry', (req, res) => {
const b = req.body || {};
if (typeof b.tool !== 'string' || b.tool.length > 60) return res.status(400).json({ error: 'bad beacon' });
publish({
source: 'webmcp',
kind: 'tool_call',
tone: b.ok ? 'agent' : 'warn',
title: `${b.ok ? '⚡' : '✕'} ${b.tool}`,
detail: String(b.summary || '').slice(0, 160) + ` · ${Math.round(b.ms || 0)}ms`,
meta: { cid: String(b.cid || '').slice(0, 20), args: truncate(b.args) },
});
res.status(202).json({ ok: true });
});
app.use('/api', api);
/* ---------------- UCP merchant endpoints (root-mounted per spec) ---------------- */
app.use(ucpRouter());
/* ---------------- static ---------------- */
app.use(express.static(join(__dirname, 'public'), { maxAge: '5m' }));
/* ---------------- 404 + errors ---------------- */
app.use((req, res) => {
if (req.path.startsWith('/api/') || req.accepts(['html', 'json']) === 'json') {
return res.status(404).json({ error: `no route for ${req.method} ${req.path}`, map: '/llms.txt' });
}
res.status(404).send(
layout({
title: '404 — Bloomwire',
description: 'Nothing grows here.',
path: req.path,
req,
cartCount: cart(req).item_count,
content: `<section class="chapter"><div class="wrap">
<header class="ch-head">
<p class="ch-num" aria-hidden="true">404</p>
<h2>Nothing grows here</h2>
<p class="ch-lede">Dead end for humans and agents alike. The map at <a href="/llms.txt"><code>/llms.txt</code></a> lists every living route.</p>
</header>
<a class="btn" href="/">Back to the greenhouse</a>
</div></section>`,
})
);
});
// eslint-disable-next-line no-unused-vars
app.use((err, req, res, next) => {
console.error(err);
if (res.headersSent) return;
res.status(err.status || 500).json({ error: err.message || 'internal error' });
});
function productJson(p) {
return {
sku: p.sku,
slug: p.slug,
name: p.name,
price: p.price,
currency: 'USD',
tagline: p.tagline,
description: p.description,
tags: p.tags,
stock: p.stock,
url: `/shop/${p.slug}`,
};
}
function truncate(obj) {
try {
const s = JSON.stringify(obj);
return s.length > 200 ? s.slice(0, 200) + '…' : JSON.parse(s);
} catch {
return undefined;
}
}
app.listen(PORT, () => {
publish({ source: 'system', kind: 'lifecycle', tone: 'ok', title: 'bloomwire online', detail: `listening on :${PORT} · ${TOOL_COUNT} WebMCP tools · ${skills.length} skills` });
console.log(`bloomwire → http://localhost:${PORT}`);
});