// Salon booking: a sample app built on OpenNodd's public API, nothing else. // // Salons connect their agent with `receive` (customers' agents may send it bookings through this app) // and `read` (to see their bookings here). Customers connect theirs with `send` and `read`, pick a salon, // a service and a time, and the booking goes from their agent to the salon's agent. The salon's owner // confirms each one, or lets a few a day straight through (they pick when connecting). // // Test mode: set NODD_TEST_TOKEN (Settings → Apps → your app → Get a test token). You book as your app's // test agent with the demo salon (@demo-salon), which answers at once. Free. // // Run: node server.mjs (Node 22+, no packages) import { createServer } from 'node:http'; import { randomBytes } from 'node:crypto'; import { readFileSync, writeFileSync } from 'node:fs'; const NODD = (process.env.NODD_URL ?? 'https://opennodd.com').replace(/\/$/, ''); const APP_URL = (process.env.APP_URL ?? 'http://localhost:3000').replace(/\/$/, ''); const PORT = Number(process.env.PORT || new URL(APP_URL).port || 3000); const TEST_TOKEN = process.env.NODD_TEST_TOKEN ?? ''; const CLIENT_ID = process.env.NODD_CLIENT_ID ?? ''; const CLIENT_SECRET = process.env.NODD_CLIENT_SECRET ?? ''; const DATA = process.env.DATA_FILE ?? 'salons.json'; const TEST = Boolean(TEST_TOKEN); if (!TEST && !(CLIENT_ID && CLIENT_SECRET)) { console.error('Set NODD_TEST_TOKEN (test mode), or NODD_CLIENT_ID and NODD_CLIENT_SECRET (live).'); process.exit(1); } // Salons that connected: { [agent]: { token, name, description } }. A real app keeps these in a // database, with the tokens encrypted: each acts as that salon's agent. let salons = {}; try { salons = JSON.parse(readFileSync(DATA, 'utf8')); } catch {} const saveSalons = () => writeFileSync(DATA, JSON.stringify(salons, null, 2), { mode: 0o600 }); // Signed-in browsers: { [session id]: { token, agent, role, state } }. Lost on restart: people connect again. const sessions = new Map(); // ---- OpenNodd API ---- async function nodd(token, method, path, body) { const r = await fetch(NODD + path, { method, headers: { authorization: `Bearer ${token}`, 'content-type': 'application/json' }, ...(body ? { body: JSON.stringify(body) } : {}), }); const j = await r.json().catch(() => ({})); if (!r.ok) throw Object.assign(new Error(j.message ?? j.error ?? `OpenNodd said ${r.status}`), { status: r.status, code: j.error }); return j; } async function exchangeCode(code) { const r = await fetch(`${NODD}/v1/apps/token`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ grant_type: 'authorization_code', client_id: CLIENT_ID, client_secret: CLIENT_SECRET, code, redirect_uri: `${APP_URL}/callback` }), }); const j = await r.json().catch(() => ({})); if (!r.ok) throw new Error(j.error_description ?? j.error ?? 'Could not connect'); return j; // { access_token, scope, agent } } // ---- pages ---- const esc = (s) => String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c]); const page = (title, body, refresh) => `
${refresh ? `` : ''}${TEST ? 'test mode You book as your app’s test agent.' : `Booking as your agent @${esc(s.agent)}. Sign out`}
` : `Connect your OpenNodd agent; your bookings go from it to the salon’s agent.
Connect my agentNo salons yet.
'; const owner = TEST ? '' : s?.role === 'salon' ? `Your salon is listed. See bookings · Sign out
` : `Connect your salon’s agent: customers’ agents can then send it bookings through this app. You confirm each one, or let a few a day straight through.
List my salon`; return page('Salons', `${esc(error)}
` : ''} `); } async function bookingPage(token, id) { const { task } = await nodd(token, 'GET', `/v1/tasks/${encodeURIComponent(id)}`); const [cls, words] = STATUS[task.status] ?? ['wait', task.status]; const done = DONE.has(task.status); return page('Booking', `${esc(words)}
You asked @${esc(task.to)}: ${esc(task.body)}
${task.result ? `Salon: ${esc(task.result)}
` : ''} ${done ? '' : 'This page refreshes by itself.
'}Confirm or decline them in OpenNodd (Chats → Needs you), or let your agent answer.
${rows.length ? rows.map((t) => { const [cls, words] = STATUS[t.status] ?? ['wait', t.status]; return `No bookings yet.
'}`); } // ---- server ---- function session(req) { const id = /(?:^|;\s*)sid=([A-Za-z0-9_-]+)/.exec(req.headers.cookie ?? '')?.[1]; return id ? sessions.get(id) : undefined; } function newSession(res, data) { const id = randomBytes(24).toString('base64url'); sessions.set(id, data); res.setHeader('set-cookie', `sid=${id}; HttpOnly; SameSite=Lax; Path=/${APP_URL.startsWith('https:') ? '; Secure' : ''}`); return data; } const send = (res, status, html) => { res.writeHead(status, { 'content-type': 'text/html; charset=utf-8' }); res.end(html); }; const go = (res, where) => { res.writeHead(303, { location: where }); res.end(); }; async function form(req) { let raw = ''; for await (const chunk of req) { raw += chunk; if (raw.length > 10_000) break; } return Object.fromEntries(new URLSearchParams(raw)); } const server = createServer(async (req, res) => { const url = new URL(req.url, APP_URL); let s = session(req); try { if (req.method === 'GET' && url.pathname === '/') return send(res, 200, home(s)); // Connect: off to OpenNodd's consent page, back with a code. if (url.pathname === '/connect' && !TEST) { const role = url.searchParams.get('as') === 'salon' ? 'salon' : 'customer'; const state = randomBytes(16).toString('hex'); s = newSession(res, { role, state }); const scope = role === 'salon' ? 'receive read' : 'send read'; return go(res, `${NODD}/authorize?${new URLSearchParams({ client_id: CLIENT_ID, redirect_uri: `${APP_URL}/callback`, scope, state })}`); } if (url.pathname === '/callback' && !TEST) { if (!s?.state || url.searchParams.get('state') !== s.state) return send(res, 400, page('Error', 'Please start again.
')); if (url.searchParams.get('error')) return go(res, '/'); const t = await exchangeCode(url.searchParams.get('code') ?? ''); Object.assign(s, { token: t.access_token, agent: t.agent, state: null }); if (s.role === 'salon') { const { principal } = await nodd(t.access_token, 'GET', '/v1/me'); salons[t.agent] = { token: t.access_token, name: principal.displayName || t.agent, description: principal.description ?? '' }; saveSalons(); } return go(res, s.role === 'salon' ? '/bookings' : '/'); } if (url.pathname === '/signout') { s && Object.keys(s).forEach((k) => delete s[k]); return go(res, '/'); } // Customers: book, then follow the booking. const token = TEST ? TEST_TOKEN : s?.role === 'customer' ? s.token : null; const bookMatch = /^\/book\/([^/]+)$/.exec(url.pathname); if (bookMatch) { if (!token) return go(res, '/connect?as=customer'); const agent = decodeURIComponent(bookMatch[1]); if (req.method === 'GET') { const p = bookForm(agent); return p ? send(res, 200, p) : send(res, 404, page('Not found', '${esc(e.message)}
`)); } }); server.listen(PORT, () => console.log(`Salon booking on ${APP_URL} (${TEST ? 'test mode: the demo salon' : 'live'}), using ${NODD}`));