// 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 ? `` : ''} ${esc(title)} · Salon booking
${body}
`; const STATUS = { pending_approval: ['wait', 'Waiting for the salon to confirm'], submitted: ['wait', 'Sent to the salon’s agent'], working: ['wait', 'The salon’s agent is on it'], input_required: ['wait', 'The salon has a question'], completed: ['ok', 'Answered'], rejected: ['bad', 'The salon said no'], failed: ['bad', 'It didn’t go through'], canceled: ['bad', 'Cancelled'], }; const DONE = new Set(['completed', 'rejected', 'failed', 'canceled']); /** Salons to pick from: the demo salon in test mode, or the ones that connected. */ const salonList = () => TEST ? [{ agent: 'demo-salon', name: 'Demo salon', description: 'Test mode: answers at once with made-up data.' }] : Object.entries(salons).map(([agent, s]) => ({ agent, name: s.name, description: s.description })); function home(s) { const list = salonList(); const who = s?.role === 'customer' || TEST ? `

${TEST ? 'test mode You book as your app’s test agent.' : `Booking as your agent @${esc(s.agent)}. Sign out`}

` : `
Book with your agent

Connect your OpenNodd agent; your bookings go from it to the salon’s agent.

Connect my agent
`; const salonsHtml = list.length ? list.map((x) => `
${esc(x.name)}
@${esc(x.agent)}${x.description ? ` · ${esc(x.description)}` : ''}
${s?.role === 'customer' || TEST ? `Book` : ''}
`).join('') : '

No salons yet.

'; const owner = TEST ? '' : s?.role === 'salon' ? `

Your bookings

Your salon is listed. See bookings · Sign out

` : `

Run a salon?

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', `

Book a salon

${who}

Salons

${salonsHtml}${owner}`); } function bookForm(agent, error = '') { const salon = salonList().find((x) => x.agent === agent); if (!salon) return null; const today = new Date().toISOString().slice(0, 10); return page('Book', `

← Salons

${esc(salon.name)}

${error ? `` : ''}

Your agent sends this to @${esc(agent)}. The salon confirms, or suggests another time.

`); } 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', `

← Salons

Your booking

${esc(words)}

You asked @${esc(task.to)}: ${esc(task.body)}

${task.result ? `

Salon: ${esc(task.result)}

` : ''} ${done ? '' : '

This page refreshes by itself.

'}
`, done ? 0 : 3); } async function salonBookings(s) { const { tasks } = await nodd(s.token, 'GET', '/v1/tasks?box=inbox'); const rows = tasks.filter((t) => t.kind === 'task').slice(0, 30); return page('Bookings', `

← Salons

Bookings

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 `
${esc(words)}
${esc(t.body)}
from @${esc(t.from)}
`; }).join('') : '

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', '

That didn’t work

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', '

No such salon

')); } const f = await form(req); if (!salonList().some((x) => x.agent === agent)) return send(res, 404, page('Not found', '

No such salon

')); if (!f.day || !f.time || !f.name?.trim()) return send(res, 400, bookForm(agent, 'Pick a day and time, and give a name.')); const when = new Date(`${f.day}T${f.time}`).toLocaleString('en-GB', { weekday: 'short', day: 'numeric', month: 'short', hour: '2-digit', minute: '2-digit' }); const body = `Booking request: ${String(f.service).slice(0, 40)} on ${when} for ${f.name.trim().slice(0, 60)}. Please confirm, or suggest another time.`; try { const { task } = await nodd(token, 'POST', '/v1/tasks', { to: agent, kind: 'task', body }); return go(res, `/booking/${encodeURIComponent(task.id)}`); } catch (e) { if (e.status === 401 && !TEST) { s.token = null; return go(res, '/connect?as=customer'); } return send(res, 502, bookForm(agent, e.code === 'out_of_credits' ? 'This app is out of credits for now. Try again later.' : `It didn’t go through: ${e.message}`)); } } const bookingMatch = /^\/booking\/([^/]+)$/.exec(url.pathname); if (bookingMatch && token) return send(res, 200, await bookingPage(token, decodeURIComponent(bookingMatch[1]))); // Salons: their bookings through this app. if (url.pathname === '/bookings' && s?.role === 'salon' && s.token) return send(res, 200, await salonBookings(s)); return go(res, '/'); } catch (e) { console.error(e); return send(res, 500, page('Error', `

Something went wrong

${esc(e.message)}

Back

`)); } }); server.listen(PORT, () => console.log(`Salon booking on ${APP_URL} (${TEST ? 'test mode: the demo salon' : 'live'}), using ${NODD}`));