import { createHash, randomBytes } from 'node:crypto'
import { readFileSync } from 'node:fs'
import { createServer } from 'node:http'
process.loadEnvFile('.env')
const env = process.env
const API = env.PINCAST_API || 'https://api.pincast.fm/v1'
const ISSUER = env.PINCAST_SIGNIN_ISSUER
const PORT = Number(env.PORT) || 3000
const REDIRECT_URI = `http://localhost:${PORT}/callback`
const SET_ID = 'old-town-lanterns'
const CARD = 'lantern:ferry-steps'
// The API doesn't send a set's cards back, so the app keeps its own copy.
const setCards = JSON.parse(readFileSync('data/set.json', 'utf8')).cards
const titleOf = key => setCards.find(card => card.key === key)?.title ?? key
// One session per browser, held in memory. A real app keeps them in its own store.
const sessions = new Map()
const random = size => randomBytes(size).toString('base64url')
const sidOf = req => /(?:^|;\s*)sid=([\w-]+)/.exec(req.headers.cookie ?? '')?.[1]
const sessionOf = req => sessions.get(sidOf(req))
function openSession(res, data = {}) {
const sid = random(24)
sessions.set(sid, data)
// On https, add Secure to this cookie.
res.setHeader('Set-Cookie', `sid=${sid}; HttpOnly; SameSite=Lax; Path=/`)
return data
}
const escapeHtml = text => String(text).replace(/[&<>"']/g, c => `&#${c.charCodeAt(0)};`)
function send(res, status, body) {
res.writeHead(status, { 'Content-Type': 'text/html; charset=utf-8' })
res.end(`<!doctype html><meta name="viewport" content="width=device-width, initial-scale=1">
<title>Lantern Walk</title><body style="font: 16px/1.5 system-ui; max-width: 32rem; margin: 2rem auto; padding: 0 1rem">${body}`)
}
// Every Pincast call goes through here, from the server, with the key in a header.
async function api(method, path, body) {
const res = await fetch(`${API}${path}`, {
method,
headers: { 'X-Pincast-Key': env.PINCAST_KEY, ...(body ? { 'Content-Type': 'application/json' } : {}) },
body: body ? JSON.stringify(body) : undefined,
signal: AbortSignal.timeout(8000),
})
const answer = await res.json().catch(() => null)
if (!res.ok) throw new Error(`${method} ${path} answered ${res.status}: ${answer?.data?.fix ?? answer?.message}`)
return answer
}
function startSignIn(req, res) {
const session = sessionOf(req) ?? openSession(res)
session.state = random(18)
session.verifier = random(32)
const url = new URL(`${ISSUER}/auth`)
url.search = new URLSearchParams({
client_id: env.PINCAST_SIGNIN_CLIENT_ID,
redirect_uri: REDIRECT_URI,
response_type: 'code',
scope: 'openid offline_access profile',
state: session.state,
code_challenge: createHash('sha256').update(session.verifier).digest('base64url'),
code_challenge_method: 'S256',
prompt: 'consent',
})
res.writeHead(302, { Location: url.href }).end()
}
async function exchangeCode(code, verifier) {
const client = `${env.PINCAST_SIGNIN_CLIENT_ID}:${env.PINCAST_SIGNIN_CLIENT_SECRET}`
const res = await fetch(`${ISSUER}/token`, {
method: 'POST',
headers: {
Authorization: `Basic ${Buffer.from(client).toString('base64')}`,
'Content-Type': 'application/x-www-form-urlencoded',
},
body: new URLSearchParams({
grant_type: 'authorization_code',
code,
redirect_uri: REDIRECT_URI,
code_verifier: verifier,
}),
signal: AbortSignal.timeout(8000),
})
const tokens = await res.json().catch(() => ({}))
if (!res.ok || !tokens.id_token) throw new Error(`The code exchange answered ${res.status}: ${tokens.error}`)
return tokens
}
async function finishSignIn(req, res, query) {
const session = sessionOf(req)
if (!session?.state || query.get('state') !== session.state) {
return send(res, 400, '<p>This sign-in has expired. <a href="/signin">Sign in again</a>.</p>')
}
const { verifier } = session
delete session.state
delete session.verifier
if (query.get('error')) return send(res, 200, '<p>You didn\'t sign in. <a href="/">Back</a>.</p>')
const tokens = await exchangeCode(query.get('code'), verifier)
// Once per sign-in: this links the person to your app, so your key can record their collects.
const { person } = await api('POST', '/people', { token: tokens.id_token })
const { username } = JSON.parse(Buffer.from(tokens.id_token.split('.')[1], 'base64url'))
// A new session id at sign-in, so an id set before it can't carry over.
sessions.delete(sidOf(req))
openSession(res, { person, name: username ?? person })
res.writeHead(303, { Location: '/' }).end()
}
async function home(req, res) {
const session = sessionOf(req)
if (!session?.person) return send(res, 200, '<p><a href="/signin">Sign in with Pincast</a></p>')
const actor = encodeURIComponent(session.person)
const { cards } = await api('GET', `/sets/${SET_ID}/collects?actor=${actor}`)
const held = cards.map(card => `<li>${escapeHtml(titleOf(card.key))}</li>`).join('')
send(res, 200, `<p>Signed in as ${escapeHtml(session.name)}.</p>
<form method="post" action="/collect"><button>Collect ${escapeHtml(titleOf(CARD))}</button></form>
<h2>Your cards</h2><ul>${held || '<li>None yet.</li>'}</ul>`)
}
async function collect(req, res) {
const session = sessionOf(req)
if (!session?.person) return res.writeHead(303, { Location: '/' }).end()
await api('POST', `/sets/${SET_ID}/collects`, {
card: CARD,
actor: { id: session.person, source: 'logto' },
at: new Date().toISOString(),
})
res.writeHead(303, { Location: '/' }).end()
}
createServer(async (req, res) => {
const url = new URL(req.url, `http://localhost:${PORT}`)
const route = `${req.method} ${url.pathname}`
try {
if (route === 'GET /') return await home(req, res)
if (route === 'GET /signin') return startSignIn(req, res)
if (route === 'GET /callback') return await finishSignIn(req, res, url.searchParams)
if (route === 'POST /collect') return await collect(req, res)
res.writeHead(404).end()
} catch (error) {
console.error(error.message)
send(res, 500, '<p>Something went wrong. The server\'s terminal says what.</p>')
}
}).listen(PORT, 'localhost', () => console.log(`Lantern Walk: http://localhost:${PORT}`))