// Start with ID_CLIENT_ID / ID_CLIENT_SECRET in the environment. Local example only. import http from "node:http"; import { randomBytes } from "node:crypto"; import { begin, finish, metadata, profile } from "./client.mjs"; const issuer = process.env.ID_ISSUER || "https://id.3306.ai", port = Number(process.env.PORT || 8071); const origin = "http://127.0.0.1:" + port, client = process.env.ID_CLIENT_ID, secret = process.env.ID_CLIENT_SECRET; if (!client || !secret) throw Error("Set ID_CLIENT_ID and ID_CLIENT_SECRET"); const store = new Map(), fresh = () => randomBytes(32).toString("base64url"); const cookie = (res, id) => res.setHeader("Set-Cookie", "demo_id=" + id + "; Path=/; HttpOnly; SameSite=Lax; Max-Age=600"); http .createServer(async (req, res) => { res.setHeader("Cache-Control", "no-store"); res.setHeader("Referrer-Policy", "no-referrer"); const url = new URL(req.url, origin); const id = /\bdemo_id=([\w-]+)/.exec(req.headers.cookie || "")?.[1]; const current = store.get(id); for (const [key, s] of store) if (s.expires < Date.now()) store.delete(key); const go = (to) => { res.writeHead(303, { Location: to }); res.end(); }; try { if (url.pathname === "/login") { const md = await metadata(issuer); const { url: to, transaction } = await begin( md, client, origin + "/callback", url.searchParams.get("lang") || "en", ); const sid = fresh(); store.set(sid, { transaction, expires: transaction.expires }); cookie(res, sid); return go(to); } if (url.pathname === "/callback") { store.delete(id); if (!current?.transaction || current.expires < Date.now()) throw Error("Expired"); const md = await metadata(issuer); const session = await finish(md, url.searchParams, current.transaction, secret); const sid = fresh(); store.set(sid, { session, expires: Date.now() + 600000 }); cookie(res, sid); return go("/"); } if (url.pathname === "/me") { if (!store.has(id) || !current.session) throw Error("Sign in required"); const data = await profile(await metadata(issuer), current.session.access, current.session.sub); res.setHeader("Content-Type", "application/json"); return res.end(JSON.stringify(data)); } if (url.pathname !== "/") { res.writeHead(404); return res.end(); } res.setHeader("Content-Type", "text/html; charset=utf-8"); res.end( '