SPB Git

Repository Public

server.mjs 18.4 KB 395 lines javascript

1/**2 * =============================================================================3 *                  SP BOUCHER | INFRASTRUCTURE & AUTOMATION4 *             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project          : MacLustr Identity8 * File             : integrations/demo-marketplace/server.mjs9 * Module           : integrations10 * Repository       : https://git.spboucher.ai/maclustr-identity11 * Project Website  : https://identity.spboucher.ai12 * Created          : 2026-12-0113 * Last Modified    : 2026-12-0114 *15 * Author           : Simon-Pierre Boucher16 * Position         : Professor of Finance17 * Institution      : Université du Québec en Outaouais (UQO)18 * Organization     : SP Boucher19 * Website          : https://spboucher.ai20 * Git              : https://git.spboucher.ai21 *22 * Preferred Contact: admin@spboucher.ai23 * Technical Contact: dev@spboucher.ai24 * Security/Admin   : admin@spboucher.ai25 *26 * Copyright (c) 202627 * Simon-Pierre Boucher28 * All rights reserved where applicable. This file is governed by the29 * applicable project license, copyright notices and relevant law.30 * Existing third-party rights and notices remain unaffected.31 *32 * License          : None specified (no license file in this repository)33 *34 * Do not embed credentials, private keys, access tokens,35 * certificates or confidential personal information.36 *37 * =============================================================================38 * END OF SP BOUCHER SOURCE HEADER39 * =============================================================================40 */4142/**43 * Brocante — demo marketplace integrating MacLustr Identity with the TypeScript SDK.44 *45 * What it shows:46 *   - the secret key lives in this server process only; the browser receives a session URL, nothing else;47 *   - "publish a listing" is refused SERVER-SIDE until the seller has a valid verification;48 *   - a draft can be written before verifying (draft-before-verify);49 *   - a webhook endpoint with signature verification on the raw body and event-id deduplication;50 *   - fail closed: when the identity service cannot be reached, the gated action stays refused.51 *52 * Demo shortcuts, not for production: unsigned login cookie, JSON file as a database, /api/debug/* endpoints.53 */54import { createServer } from "node:http";55import { randomBytes } from "node:crypto";56import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";57import { dirname, join } from "node:path";58import { fileURLToPath } from "node:url";59import { MacLustrIdentity, MacLustrIdentityError, SignatureVerificationError, isDecisionEvent, isSessionEvent, sessionEndedWithoutDecision } from "@maclustr/identity";6061const DIR = dirname(fileURLToPath(import.meta.url));6263/* ------------------------------------------------------------------ configuration (server-side only) */6465function loadEnvFile(file) {66  if (!existsSync(file)) return;67  for (const line of readFileSync(file, "utf8").split("\n")) {68    const m = /^([A-Z0-9_]+)=(.*)$/.exec(line.trim());69    if (m && process.env[m[1]] === undefined) process.env[m[1]] = m[2];70  }71}72loadEnvFile(join(DIR, ".env.local"));7374const PORT = Number(process.env.PORT ?? 8881);75const IDENTITY_URL = process.env.MLID_BASE_URL ?? "http://localhost:8870";76const WEBHOOK_SECRET = process.env.MLID_WEBHOOK_SECRET;77const STATE_FILE = process.env.DEMO_STATE_FILE ?? join(DIR, "data", "state.json");78if (!process.env.MLID_SECRET_KEY || !WEBHOOK_SECRET) {79  console.error("Missing MLID_SECRET_KEY / MLID_WEBHOOK_SECRET. Run ./setup.sh first.");80  process.exit(1);81}8283const identity = new MacLustrIdentity({84  apiKey: process.env.MLID_SECRET_KEY,85  baseUrl: IDENTITY_URL,86  timeoutMs: Number(process.env.MLID_TIMEOUT_MS ?? 5000),87  maxRetries: Number(process.env.MLID_MAX_RETRIES ?? 1),88});8990/* ------------------------------------------------------------------ storage (a JSON file stands in for a database) */9192const USERS = {93  ana: { id: "ana", name: "Ana (Atelier Ana)" },94  ben: { id: "ben", name: "Ben (Vinyles du Plateau)" },95  chloe: { id: "chloe", name: "Chloe (Velos Chloe)" },96};97/** Opaque identifier sent to the identity service: no name, no e-mail. */98const externalId = (userId) => `mk_${userId}`;99const userFromExternal = (ext) => (typeof ext === "string" && ext.startsWith("mk_") ? USERS[ext.slice(3)] : undefined);100101const state = { identity: {}, pending: {}, listings: [], events: {}, rejected_webhooks: 0 };102if (existsSync(STATE_FILE)) Object.assign(state, JSON.parse(readFileSync(STATE_FILE, "utf8")));103function save() {104  mkdirSync(dirname(STATE_FILE), { recursive: true });105  writeFileSync(STATE_FILE + ".tmp", JSON.stringify(state, null, 2));106  renameSync(STATE_FILE + ".tmp", STATE_FILE);107}108109/**110 * The only identity data this application keeps about a user:111 * verification_id, status, assurance_level, expires_at (plus bookkeeping). No document, no image, no name.112 */113function storeVerification(userId, v, source, eventCreated = Math.floor(Date.now() / 1000)) {114  // Deliveries are at-least-once and unordered. The rules below never rely on this server's clock:115  const current = state.identity[userId];116  if (current && current.verification_id === v.verification_id) {117    if (current.status === "revoked" && v.status !== "revoked") return false; // a revocation is final118    if (v.status === "manual_review" && current.status !== "manual_review") return false; // a decision never goes back "under review"119    if (source === "webhook" && current.updated_by === "webhook" && eventCreated < current.event_created) return false; // older event delivered late120  } else if (current && v.created_at && current.verification_created_at && Date.parse(v.created_at) < Date.parse(current.verification_created_at)) {121    return false; // an event about an older verification, delivered after a newer one122  }123  state.identity[userId] = {124    verification_id: v.verification_id,125    verification_created_at: v.created_at ?? (current && current.verification_id === v.verification_id ? current.verification_created_at : null) ?? null,126    status: v.status,127    assurance_level: v.assurance_level ?? null,128    expires_at: v.expires_at ?? null,129    updated_by: source,130    event_created: eventCreated,131  };132  save();133  return true;134}135136/**137 * A session ended without a decision (`verification.cancelled`: cancelled by us or consent withdrawn by the person;138 * `verification.expired`). Nothing was verified: the person may simply start again.139 *   - the pending session is forgotten;140 *   - a record still "under review" for that same session is closed: the review will never conclude (consent141 *     withdrawn during the manual review). A "verified" record of an earlier session is left untouched.142 */143function sessionEnded(userId, session, eventCreated) {144  if (state.pending[userId] === session.id) delete state.pending[userId];145  const current = state.identity[userId];146  if (current && current.status === "manual_review" && session.verification_id && current.verification_id === session.verification_id) {147    state.identity[userId] = { ...current, status: "inconclusive", assurance_level: null, updated_by: "webhook", event_created: eventCreated };148  }149  save();150}151152const locallyVerified = (userId) => {153  const r = state.identity[userId];154  return Boolean(r && r.status === "verified" && (!r.expires_at || Date.parse(r.expires_at) > Date.now()));155};156157/* ------------------------------------------------------------------ the gate */158159/**160 * Decides whether a user may publish. Two conditions, both required:161 *   1. our own record says "verified" and is not expired;162 *   2. the identity service confirms, right now, that this verification is still valid (catches a revocation163 *      whose webhook has not arrived yet).164 * Any failure to reach the service refuses the action: fail closed.165 */166async function publishGate(userId) {167  const record = state.identity[userId];168  if (!locallyVerified(userId)) {169    const pending = record && record.status === "manual_review";170    return { allowed: false, http: 403, error: pending ? "identity_verification_pending" : "identity_verification_required" };171  }172  try {173    const live = await identity.verifications.status(record.verification_id);174    if (!live.valid) {175      storeVerification(userId, { ...record, created_at: record.verification_created_at, status: live.status, expires_at: live.expires_at }, "api");176      return { allowed: false, http: 403, error: "identity_verification_required" };177    }178    return { allowed: true };179  } catch (e) {180    console.error(`[gate] identity service unavailable: ${e instanceof MacLustrIdentityError ? e.code : e}`);181    return { allowed: false, http: 503, error: "identity_unavailable" };182  }183}184185/* ------------------------------------------------------------------ http helpers */186187function send(res, status, body, headers = {}) {188  const payload = typeof body === "string" || Buffer.isBuffer(body) ? body : JSON.stringify(body);189  res.writeHead(status, {190    "Content-Type": typeof body === "string" || Buffer.isBuffer(body) ? "text/plain; charset=utf-8" : "application/json",191    "Cache-Control": "no-store",192    "X-Content-Type-Options": "nosniff",193    "Referrer-Policy": "no-referrer",194    ...headers,195  });196  res.end(payload);197}198199async function readRaw(req, limit = 256 * 1024) {200  const chunks = [];201  let size = 0;202  for await (const chunk of req) {203    size += chunk.length;204    if (size > limit) throw Object.assign(new Error("payload too large"), { http: 413 });205    chunks.push(chunk);206  }207  return Buffer.concat(chunks);208}209210async function readJson(req) {211  const raw = await readRaw(req);212  if (!raw.length) return {};213  try {214    return JSON.parse(raw.toString("utf8"));215  } catch {216    throw Object.assign(new Error("invalid JSON"), { http: 400 });217  }218}219220function currentUser(req) {221  const m = /(?:^|;\s*)mk_user=([a-z]+)/.exec(req.headers.cookie ?? "");222  return m ? USERS[m[1]] : undefined;223}224225const STATIC = {226  "/": ["public/index.html", "text/html; charset=utf-8"],227  "/app.js": ["public/app.js", "text/javascript; charset=utf-8"],228  "/styles.css": ["public/styles.css", "text/css; charset=utf-8"],229  // The browser entry of the SDK, served as is. It contains no key and takes none.230  "/vendor/maclustr-identity-browser.js": ["node_modules/@maclustr/identity/dist/browser.js", "text/javascript; charset=utf-8"],231};232const identityOrigin = new URL(IDENTITY_URL).origin;233const CSP = `default-src 'self'; frame-src ${identityOrigin}; style-src 'self'; script-src 'self'; img-src 'self' data:; object-src 'none'; base-uri 'none'; frame-ancestors 'none'`;234235function publicUser(userId) {236  const r = state.identity[userId];237  return {238    id: userId,239    name: USERS[userId].name,240    identity: r ? { status: r.status, assurance_level: r.assurance_level, expires_at: r.expires_at, updated_by: r.updated_by } : { status: "unverified" },241    identity_verified: locallyVerified(userId),242    can_publish: locallyVerified(userId),243    // Anything but "verified" or "under review" can be retried with a new session (refused, not conclusive,244    // expired, cancelled, revoked, never started).245    can_start_verification: !locallyVerified(userId) && !(r && r.status === "manual_review"),246    pending_session: state.pending[userId] ?? null,247  };248}249250/* ------------------------------------------------------------------ routes */251252async function route(req, res) {253  const url = new URL(req.url, `http://localhost:${PORT}`);254  const path = url.pathname;255  const method = req.method ?? "GET";256257  if (method === "GET" && STATIC[path]) {258    const [file, type] = STATIC[path];259    return send(res, 200, readFileSync(join(DIR, file)), { "Content-Type": type, "Content-Security-Policy": CSP });260  }261  if (method === "GET" && path === "/health") return send(res, 200, { status: "ok", app: "demo-marketplace" });262263  /* --- webhook: authenticated by its signature, not by a cookie --- */264  if (method === "POST" && path === "/webhooks/identity") {265    const raw = await readRaw(req); // exact bytes: the signature does not survive JSON.parse + JSON.stringify266    let event;267    try {268      event = await identity.webhooks.constructEvent(raw, req.headers["mlid-signature"], WEBHOOK_SECRET);269    } catch (e) {270      if (!(e instanceof SignatureVerificationError)) throw e;271      state.rejected_webhooks += 1;272      save();273      return send(res, 400, { error: "invalid_signature" });274    }275    if (state.events[event.id]) return send(res, 200, { received: true, duplicate: true }); // at-least-once delivery: one event id is processed once276    // The signature is valid: from here on the answer is 200, even for an event type or an object this version does277    // not know (a later service version may add some). Answering an error would only make the service retry it.278    const obj = event.data && typeof event.data.object === "object" && event.data.object ? event.data.object : {};279    const created = Number.isFinite(event.created) ? event.created : Math.floor(Date.now() / 1000);280    const user = userFromExternal(obj.external_user_id);281    if (user && isDecisionEvent(event) && typeof obj.verification_id === "string") {282      // Decision events: verified, manual_review, rejected, revoked, inconclusive (for example reason283      // `review_not_completed`: the review was not completed in time). Only "verified" opens the gate.284      storeVerification(user.id, obj, "webhook", created);285    } else if (user && isSessionEvent(event) && sessionEndedWithoutDecision(event)) {286      sessionEnded(user.id, obj, created);287    }288    // Recorded last: if the processing above fails, the redelivery is processed again instead of being skipped.289    state.events[event.id] = { type: event.type, external_user_id: obj.external_user_id ?? null, object_id: (isDecisionEvent(event) ? obj.verification_id : obj.id) ?? null, at: created };290    save();291    return send(res, 200, { received: true });292  }293294  /* --- public pages data: what anyone can see --- */295  if (method === "GET" && path === "/api/public/listings") {296    return send(res, 200, {297      listings: state.listings298        .filter((l) => l.status === "published")299        .map((l) => ({ id: l.id, title: l.title, price: l.price, seller: USERS[l.user].name, seller_identity_verified: locallyVerified(l.user) })),300    });301  }302  if (method === "GET" && path === "/api/users") return send(res, 200, { users: Object.values(USERS) });303304  /* --- fake login --- */305  if (method === "POST" && path === "/api/login") {306    const body = await readJson(req);307    if (!USERS[body.user]) return send(res, 400, { error: "unknown_user" });308    return send(res, 200, publicUser(body.user), { "Set-Cookie": `mk_user=${body.user}; Path=/; HttpOnly; SameSite=Lax` });309  }310  if (method === "POST" && path === "/api/logout") return send(res, 200, { ok: true }, { "Set-Cookie": "mk_user=; Path=/; Max-Age=0" });311312  /* --- demo-only introspection used by integrations/e2e --- */313  if (method === "GET" && path === "/api/debug/events") return send(res, 200, { events: state.events, rejected_webhooks: state.rejected_webhooks });314315  /* --- everything below needs a signed-in user --- */316  const user = currentUser(req);317  if (!path.startsWith("/api/")) return send(res, 404, { error: "not_found" });318  if (!user) return send(res, 401, { error: "sign_in_required" });319320  if (method === "GET" && path === "/api/me") {321    return send(res, 200, { ...publicUser(user.id), listings: state.listings.filter((l) => l.user === user.id) });322  }323324  // Draft before verify: writing a draft never requires a verification.325  if (method === "POST" && path === "/api/listings") {326    const body = await readJson(req);327    const title = String(body.title ?? "").trim().slice(0, 80);328    const price = Number(body.price);329    if (!title || !Number.isFinite(price) || price < 0) return send(res, 400, { error: "invalid_listing" });330    const listing = { id: `l_${randomBytes(5).toString("hex")}`, user: user.id, title, price: Math.round(price * 100) / 100, status: "draft" };331    state.listings.push(listing);332    save();333    return send(res, 201, listing);334  }335336  // The gated action.337  const publish = /^\/api\/listings\/([a-z0-9_]+)\/publish$/.exec(path);338  if (method === "POST" && publish) {339    const listing = state.listings.find((l) => l.id === publish[1] && l.user === user.id);340    if (!listing) return send(res, 404, { error: "not_found" });341    const gate = await publishGate(user.id);342    if (!gate.allowed) return send(res, gate.http, { error: gate.error, listing });343    listing.status = "published";344    save();345    return send(res, 200, listing);346  }347348  // Creates the verification session. Only the hosted URL is returned to the browser.349  if (method === "POST" && path === "/api/identity/session") {350    try {351      const session = await identity.verificationSessions.create({352        purpose: "Publish listings on Brocante",353        external_user_id: externalId(user.id),354        locale: "en-CA",355        metadata: { app: "demo-marketplace" },356      });357      state.pending[user.id] = session.id;358      save();359      return send(res, 200, { url: session.url, session_id: session.id });360    } catch (e) {361      const requestId = e instanceof MacLustrIdentityError ? e.requestId : undefined;362      console.error(`[session] could not create a verification session: ${e instanceof MacLustrIdentityError ? e.code : e}`);363      return send(res, 503, { error: "identity_unavailable", request_id: requestId });364    }365  }366367  // Optional catch-up when a webhook is late: asks the identity service for the user's current state.368  if (method === "POST" && path === "/api/identity/refresh") {369    try {370      const v = await identity.isUserVerified(externalId(user.id));371      if (v) storeVerification(user.id, v, "api");372      else {373        const sid = state.pending[user.id];374        const session = sid ? await identity.verificationSessions.retrieve(sid) : null;375        if (session?.verification_id) storeVerification(user.id, await identity.verifications.retrieve(session.verification_id), "api");376      }377      return send(res, 200, publicUser(user.id));378    } catch {379      return send(res, 503, { error: "identity_unavailable", ...publicUser(user.id) });380    }381  }382383  return send(res, 404, { error: "not_found" });384}385386const server = createServer((req, res) => {387  route(req, res).catch((e) => {388    if (!e.http) console.error("[error]", e);389    if (!res.headersSent) send(res, e.http ?? 500, { error: e.http ? e.message : "internal_error" });390    else res.end();391  });392});393server.listen(PORT, "127.0.0.1", () => console.log(`demo-marketplace on http://localhost:${PORT} (identity service: ${IDENTITY_URL})`));394for (const sig of ["SIGINT", "SIGTERM"]) process.on(sig, () => server.close(() => process.exit(0)));395
Files main
Menu

Theme