Monorepo for Aesthetic.Computer aesthetic.computer
at main 1065 lines 42 kB view raw
1// lith — AC monolith server 2// Wraps Netlify function handlers in Express routes + serves static files. 3 4// Shim awslambda before anything imports @netlify/functions. 5// Netlify's stream() calls awslambda.streamifyResponse() at wrap time, 6// which doesn't exist outside AWS Lambda. This shim adapts the 3-arg 7// streaming function (event, responseStream, context) back to a normal 8// 2-arg handler (event, context) that returns {statusCode, headers, body}. 9import { PassThrough } from "stream"; 10import { Readable } from "stream"; 11 12if (typeof globalThis.awslambda === "undefined") { 13 globalThis.awslambda = { 14 streamifyResponse: (wrappedFn) => { 15 // wrappedFn expects (event, responseStream, context). 16 // It calls the real handler(event, context) internally, then pipes 17 // the body to responseStream via pipeline(). We provide a PassThrough 18 // as the responseStream and return it as the response body. 19 return async (event, context) => { 20 const pt = new PassThrough(); 21 22 // Promise that resolves when HttpResponseStream.from() is called 23 // inside wrappedFn, giving us the response metadata (statusCode, headers). 24 let resolveMetadata; 25 const metadataPromise = new Promise((r) => { resolveMetadata = r; }); 26 pt._resolveMetadata = resolveMetadata; 27 28 // Start the pipeline (don't await — data streams to pt asynchronously) 29 wrappedFn(event, pt, context).catch((err) => { 30 if (!pt.destroyed) pt.destroy(err); 31 }); 32 33 const metadata = await metadataPromise; 34 const webStream = Readable.toWeb(pt); 35 36 return { ...metadata, body: webStream }; 37 }; 38 }, 39 HttpResponseStream: { 40 from: (stream, metadata) => { 41 // Signal metadata to the adapter above 42 if (stream._resolveMetadata) stream._resolveMetadata(metadata || {}); 43 return stream; 44 }, 45 }, 46 }; 47} 48 49import express from "express"; 50import { readdirSync, readFileSync, existsSync, mkdirSync, writeFileSync } from "fs"; 51import { join, dirname } from "path"; 52import { fileURLToPath } from "url"; 53import { createServer as createHttpsServer } from "https"; 54import { createServer as createHttpServer } from "http"; 55import { resolveFunctionName } from "./route-resolution.mjs"; 56 57const __dirname = dirname(fileURLToPath(import.meta.url)); 58const SYSTEM = join(__dirname, "..", "system"); 59const PUBLIC = join(SYSTEM, "public"); 60const FN_DIR = join(SYSTEM, "netlify", "functions"); 61 62// Load .env from system/ if present (handles special chars in values) 63const envPath = join(SYSTEM, ".env"); 64if (existsSync(envPath)) { 65 for (const line of readFileSync(envPath, "utf-8").split("\n")) { 66 if (!line || line.startsWith("#")) continue; 67 const idx = line.indexOf("="); 68 if (idx === -1) continue; 69 const key = line.slice(0, idx).trim(); 70 const val = line.slice(idx + 1).trim(); 71 if (key && !process.env[key]) process.env[key] = val; 72 } 73} 74 75const PORT = process.env.PORT || 8888; 76const DEV = process.env.NODE_ENV !== "production"; 77 78// Tell functions we're in dev mode (so index.mjs uses cwd instead of /var/task) 79if (DEV) { 80 process.env.CONTEXT = process.env.CONTEXT || "dev"; 81 process.env.NETLIFY_DEV = process.env.NETLIFY_DEV || "true"; 82} 83 84// Set cwd to system/ so relative paths in functions resolve correctly 85process.chdir(SYSTEM); 86 87// SSL certs for local dev (same ones Netlify local context uses) 88const SSL_CERT = join(__dirname, "..", "ssl-dev", "localhost.pem"); 89const SSL_KEY = join(__dirname, "..", "ssl-dev", "localhost-key.pem"); 90const HAS_SSL = existsSync(SSL_CERT) && existsSync(SSL_KEY); 91 92const app = express(); 93const BOOT_TIME = Date.now(); 94 95// --- Response cache for hot GET endpoints --- 96const responseCache = new Map(); // key → { body, headers, statusCode, expires } 97const CACHE_TTLS = { 98 "handle-colors": 60_000, // 1 min (colors rarely change) 99 "version": 30_000, // 30s (git state) 100 "handles": 60_000, // 1 min 101 "mood": 30_000, // 30s 102 "tv": 30_000, // 30s 103 "keeps-config": 300_000, // 5 min (contract addresses) 104 "kidlisp-count": 60_000, // 1 min 105 "playlist": 60_000, // 1 min 106 "clock": 0, // never cache (it's a clock) 107}; 108 109// Clean expired entries every 30s 110setInterval(() => { 111 const now = Date.now(); 112 for (const [k, v] of responseCache) { 113 if (v.expires < now) responseCache.delete(k); 114 } 115}, 30_000); 116 117// --- Function stats & error log --- 118const fnStats = {}; // { fnName: { calls, errors, totalMs, lastCall, lastError } } 119const errorLog = []; // [{ time, fn, status, error, path, method }] 120const requestLog = []; // [{ time, fn, ms, status, path, method }] 121const MAX_ERROR_LOG = 500; 122const MAX_REQUEST_LOG = 1000; 123 124function recordCall(name, ms, status, path, method, error) { 125 if (!fnStats[name]) fnStats[name] = { calls: 0, errors: 0, totalMs: 0, lastCall: null, lastError: null }; 126 const s = fnStats[name]; 127 s.calls++; 128 s.totalMs += ms; 129 s.lastCall = new Date().toISOString(); 130 131 requestLog.unshift({ time: s.lastCall, fn: name, ms: Math.round(ms), status, path, method }); 132 if (requestLog.length > MAX_REQUEST_LOG) requestLog.length = MAX_REQUEST_LOG; 133 134 if (error || status >= 500) { 135 s.errors++; 136 s.lastError = new Date().toISOString(); 137 errorLog.unshift({ time: s.lastError, fn: name, status, error: error || `HTTP ${status}`, path, method }); 138 if (errorLog.length > MAX_ERROR_LOG) errorLog.length = MAX_ERROR_LOG; 139 } 140} 141 142function captureRawBody(req, _res, buf) { 143 if (buf?.length) req.rawBody = Buffer.from(buf); 144} 145 146// --- Body parsing --- 147app.use(express.json({ limit: "50mb", verify: captureRawBody })); 148app.use(express.urlencoded({ extended: true, limit: "50mb", verify: captureRawBody })); 149app.use(express.raw({ type: "*/*", limit: "50mb", verify: captureRawBody })); 150 151// --- CORS (mirrors Netlify _headers) --- 152app.use((req, res, next) => { 153 res.set("Access-Control-Allow-Origin", "*"); 154 res.set( 155 "Access-Control-Allow-Headers", 156 "Content-Type, Authorization, X-Requested-With", 157 ); 158 res.set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS"); 159 if (req.method === "OPTIONS") return res.sendStatus(204); 160 next(); 161}); 162// --- Host-based rewrites that Netlify previously handled --- 163app.use((req, _res, next) => { 164 const host = (req.headers.host || "").split(":")[0].toLowerCase(); 165 166 // Preserve branded notepat.com URLs while serving the /notepat piece. 167 if ((host === "notepat.com" || host === "www.notepat.com") && req.path === "/") { 168 req.url = "/notepat" + (req.url === "/" ? "" : req.url.slice(req.path.length)); 169 } 170 171 next(); 172}); 173 174// --- Load Netlify functions --- 175const functions = {}; 176 177// Scripts that call process.exit() at import time — not API functions. 178const SKIP = new Set(["backfill-painting-codes", "test-tv-hits"]); 179 180for (const file of readdirSync(FN_DIR)) { 181 if (!file.endsWith(".mjs") && !file.endsWith(".js")) continue; 182 const name = file.replace(/\.(mjs|js)$/, ""); 183 if (SKIP.has(name)) continue; 184 try { 185 const mod = await import(join(FN_DIR, file)); 186 if (mod.handler) { 187 // Netlify Functions v1: export { handler } 188 functions[name] = mod.handler; 189 } else if (mod.default && typeof mod.default === "function") { 190 // Netlify Functions v2: export default async (req) => { ... } 191 // Wrap v2 handler to match v1 event/context signature 192 const v2fn = mod.default; 193 functions[name] = async (event, context) => { 194 // V2 functions receive a Request-like object; build one from the event 195 const url = event.rawUrl || `http://localhost${event.path || "/"}`; 196 const req = new Request(url, { 197 method: event.httpMethod, 198 headers: event.headers, 199 body: event.httpMethod !== "GET" && event.httpMethod !== "HEAD" ? event.body : undefined, 200 }); 201 req.query = event.queryStringParameters; 202 const resp = await v2fn(req, context); 203 // V2 returns a Web Response object 204 const body = await resp.text(); 205 const headers = {}; 206 resp.headers.forEach((v, k) => { headers[k] = v; }); 207 return { statusCode: resp.status, headers, body }; 208 }; 209 } 210 } catch (err) { 211 console.warn(` skip: ${name} (${err.message})`); 212 } 213} 214 215console.log(`Loaded ${Object.keys(functions).length} functions`); 216 217// --- Netlify event adapter --- 218function toEvent(req) { 219 // Reconstruct body as string (Netlify handlers expect string or null). 220 // Prefer rawBody when available — it preserves the exact bytes the client 221 // sent, which is critical for webhook signature verification (Stripe, etc.). 222 let body = null; 223 if (req.rawBody) { 224 body = Buffer.isBuffer(req.rawBody) 225 ? req.rawBody.toString("utf-8") 226 : String(req.rawBody); 227 } else if (req.body) { 228 const contentType = (req.headers["content-type"] || "").toLowerCase(); 229 body = 230 typeof req.body === "string" 231 ? req.body 232 : Buffer.isBuffer(req.body) 233 ? req.body.toString("utf-8") 234 // Preserve HTML form posts as urlencoded strings so legacy handlers 235 // using URLSearchParams(event.body) continue to work after lith. 236 : contentType.includes("application/x-www-form-urlencoded") 237 ? new URLSearchParams( 238 Object.entries(req.body).flatMap(([key, value]) => 239 Array.isArray(value) 240 ? value.map((item) => [key, item]) 241 : [[key, value]], 242 ), 243 ).toString() 244 : JSON.stringify(req.body); 245 } 246 247 return { 248 httpMethod: req.method, 249 headers: req.headers, 250 body, 251 rawBody: req.rawBody ?? req.body, 252 queryStringParameters: req.query || {}, 253 path: req.path, 254 rawUrl: `${req.protocol}://${req.get("host")}${req.originalUrl}`, 255 isBase64Encoded: false, 256 }; 257} 258 259// --- Function handler --- 260async function handleFunction(req, res) { 261 const name = req.params.fn; 262 const handler = functions[name]; 263 if (!handler) { 264 recordCall(name || "unknown", 0, 404, req.path, req.method, "Function not found"); 265 return res.status(404).send("Function not found: " + name); 266 } 267 268 // Check response cache (GET only, with matching query string) 269 const ttl = CACHE_TTLS[name]; 270 if (ttl && req.method === "GET") { 271 const cacheKey = `${name}:${req.originalUrl}`; 272 const cached = responseCache.get(cacheKey); 273 if (cached && cached.expires > Date.now()) { 274 recordCall(name, 0, cached.statusCode, req.path, req.method, null); 275 if (cached.headers) res.set(cached.headers); 276 res.set("X-Lith-Cache", "HIT"); 277 return res.status(cached.statusCode).send(cached.body); 278 } 279 } 280 281 const t0 = Date.now(); 282 try { 283 const event = toEvent(req); 284 const context = { clientContext: {} }; 285 const result = await handler(event, context); 286 287 const statusCode = result.statusCode || 200; 288 const ms = Date.now() - t0; 289 recordCall(name, ms, statusCode, req.path, req.method, statusCode >= 500 ? result.body : null); 290 291 if (result.headers) res.set(result.headers); 292 if (result.multiValueHeaders) { 293 for (const [k, vals] of Object.entries(result.multiValueHeaders)) { 294 for (const v of vals) res.append(k, v); 295 } 296 } 297 298 // Handle ReadableStream bodies (from streaming functions like ask, keep-mint) 299 if (result.body && typeof result.body === "object" && typeof result.body.getReader === "function") { 300 res.status(statusCode); 301 const reader = result.body.getReader(); 302 const pump = async () => { 303 while (true) { 304 const { done, value } = await reader.read(); 305 if (done) { res.end(); return; } 306 res.write(value); 307 } 308 }; 309 return pump().catch((err) => { 310 console.error(`fn/${name} stream error:`, err); 311 res.end(); 312 }); 313 } 314 315 // Store in cache if cacheable 316 if (ttl && req.method === "GET" && statusCode < 400) { 317 const cacheKey = `${name}:${req.originalUrl}`; 318 responseCache.set(cacheKey, { 319 body: result.isBase64Encoded ? Buffer.from(result.body, "base64") : result.body, 320 headers: result.headers, 321 statusCode, 322 expires: Date.now() + ttl, 323 }); 324 } 325 326 if (result.isBase64Encoded) { 327 res.status(statusCode).send(Buffer.from(result.body, "base64")); 328 } else { 329 res.status(statusCode).send(result.body); 330 } 331 } catch (err) { 332 const ms = Date.now() - t0; 333 recordCall(name, ms, 500, req.path, req.method, err.message); 334 console.error(`fn/${name} error:`, err); 335 res.status(500).send("Internal Server Error"); 336 } 337} 338 339// Resolve function name from URL params 340function resolveFunction(req) { 341 return resolveFunctionName(req.params.fn, req.params.rest, functions); 342} 343 344// --- Function handler (updated to use resolveFunction) --- 345async function handleFunctionResolved(req, res) { 346 req.params.fn = resolveFunction(req); 347 return handleFunction(req, res); 348} 349 350// --- Deploy webhook (POST /lith/deploy?secret=...) --- 351import { execFile } from "child_process"; 352import { createHmac, timingSafeEqual } from "crypto"; 353const DEPLOY_SECRET = process.env.DEPLOY_SECRET || ""; 354const DEPLOY_BRANCHES = (process.env.DEPLOY_BRANCHES || process.env.DEPLOY_BRANCH || "main,master") 355 .split(",") 356 .map((branch) => branch.trim()) 357 .filter(Boolean); 358const DEFAULT_DEPLOY_BRANCH = DEPLOY_BRANCHES[0] || "main"; 359let deployInProgress = false; 360let queuedDeployBranch = null; 361 362function normalizeDeployBranch(branch) { 363 if (typeof branch !== "string") return null; 364 const trimmed = branch.trim(); 365 if (!trimmed) return null; 366 if (!/^[A-Za-z0-9._/-]+$/.test(trimmed)) return null; 367 return trimmed; 368} 369 370function branchFromRef(ref) { 371 if (typeof ref !== "string") return null; 372 const prefix = "refs/heads/"; 373 if (!ref.startsWith(prefix)) return null; 374 return normalizeDeployBranch(ref.slice(prefix.length)); 375} 376 377function requestedDeployBranch(req) { 378 const fromRef = branchFromRef(req.body?.ref); 379 if (fromRef) return fromRef; 380 return ( 381 normalizeDeployBranch(req.query.branch) || 382 normalizeDeployBranch(req.headers["x-deploy-branch"]) || 383 DEFAULT_DEPLOY_BRANCH 384 ); 385} 386 387function verifyDeploy(req) { 388 // GitHub HMAC signature (webhook secret) 389 const sig = req.headers["x-hub-signature-256"]; 390 if (sig && DEPLOY_SECRET) { 391 const rawBody = Buffer.isBuffer(req.rawBody) 392 ? req.rawBody 393 : Buffer.from( 394 typeof req.body === "string" ? req.body : JSON.stringify(req.body ?? {}), 395 "utf8", 396 ); 397 const hmac = createHmac("sha256", DEPLOY_SECRET) 398 .update(rawBody) 399 .digest("hex"); 400 const expected = `sha256=${hmac}`; 401 if (sig.length === expected.length && 402 timingSafeEqual(Buffer.from(sig), Buffer.from(expected))) { 403 return true; 404 } 405 } 406 // Fallback: query param or header (manual triggers) 407 const plain = req.query.secret || req.headers["x-deploy-secret"]; 408 return plain === DEPLOY_SECRET; 409} 410 411function runDeploy(branch) { 412 deployInProgress = true; 413 console.log(`[deploy] starting branch=${branch}`); 414 415 execFile( 416 "/opt/ac/lith/webhook.sh", 417 { 418 timeout: 120000, 419 env: { ...process.env, DEPLOY_BRANCH: branch }, 420 }, 421 (err, stdout, stderr) => { 422 deployInProgress = false; 423 424 if (stdout?.trim()) { 425 console.log(`[deploy][${branch}] ${stdout.trim()}`); 426 } 427 if (stderr?.trim()) { 428 console.error(`[deploy][${branch}] ${stderr.trim()}`); 429 } 430 if (err) { 431 console.error(`[deploy] failed for ${branch}:`, err.message); 432 } 433 434 if (queuedDeployBranch) { 435 const nextBranch = queuedDeployBranch; 436 queuedDeployBranch = null; 437 setImmediate(() => runDeploy(nextBranch)); 438 } 439 }, 440 ); 441} 442 443app.post("/lith/deploy", (req, res) => { 444 if (!DEPLOY_SECRET || !verifyDeploy(req)) { 445 return res.status(401).send("Unauthorized"); 446 } 447 448 const githubEvent = req.headers["x-github-event"]; 449 if (githubEvent === "ping") { 450 return res.send("pong"); 451 } 452 if (githubEvent && githubEvent !== "push") { 453 return res.send(`Ignored GitHub event: ${githubEvent}`); 454 } 455 456 const ref = req.body?.ref; 457 const branch = requestedDeployBranch(req); 458 if (!DEPLOY_BRANCHES.includes(branch)) { 459 const detail = ref || branch; 460 return res.send(`Ignored non-deploy branch: ${detail}`); 461 } 462 463 if (deployInProgress) { 464 queuedDeployBranch = branch; 465 return res.status(202).send(`Deploy queued for ${branch}`); 466 } 467 468 runDeploy(branch); 469 res.status(202).send(`Deploy started for ${branch}`); 470}); 471 472// --- Routes --- 473 474app.get(["/lith", "/lith/"], (_req, res) => { 475 res.redirect(302, "/lith/stats"); 476}); 477 478// --- Lith stats API (consumed by silo dashboard) --- 479app.get("/lith/stats", (req, res) => { 480 const uptime = Math.floor((Date.now() - BOOT_TIME) / 1000); 481 const mem = process.memoryUsage(); 482 const sorted = Object.entries(fnStats) 483 .map(([name, s]) => ({ name, ...s, avgMs: s.calls ? Math.round(s.totalMs / s.calls) : 0 })) 484 .sort((a, b) => b.calls - a.calls); 485 486 res.json({ 487 uptime, 488 boot: new Date(BOOT_TIME).toISOString(), 489 functionsLoaded: Object.keys(functions).length, 490 memory: { rss: Math.round(mem.rss / 1048576), heap: Math.round(mem.heapUsed / 1048576) }, 491 totals: { 492 calls: sorted.reduce((s, f) => s + f.calls, 0), 493 errors: sorted.reduce((s, f) => s + f.errors, 0), 494 }, 495 functions: sorted, 496 }); 497}); 498 499app.get("/lith/errors", (req, res) => { 500 const limit = Math.min(parseInt(req.query.limit) || 100, MAX_ERROR_LOG); 501 res.json({ errors: errorLog.slice(0, limit), total: errorLog.length }); 502}); 503 504app.get("/lith/requests", (req, res) => { 505 const limit = Math.min(parseInt(req.query.limit) || 100, MAX_REQUEST_LOG); 506 const fn = req.query.fn; 507 const filtered = fn ? requestLog.filter((r) => r.fn === fn) : requestLog; 508 res.json({ requests: filtered.slice(0, limit), total: filtered.length }); 509}); 510 511// --- Caddy access log summary (for silo dashboard) --- 512app.get("/lith/traffic", async (req, res) => { 513 try { 514 const logPath = "/var/log/caddy/access.log"; 515 const lines = readFileSync(logPath, "utf-8").trim().split("\n").filter(Boolean); 516 const recent = lines.slice(-500); // last 500 entries 517 const byPath = {}, byHost = {}, byStatus = {}; 518 let total = 0; 519 520 for (const line of recent) { 521 try { 522 const d = JSON.parse(line); 523 const r = d.request || {}; 524 const uri = (r.uri || "/").split("?")[0]; 525 const host = r.host || "unknown"; 526 const status = String(d.status || 0); 527 // Aggregate by first path segment 528 const seg = "/" + (uri.split("/")[1] || ""); 529 byPath[seg] = (byPath[seg] || 0) + 1; 530 byHost[host] = (byHost[host] || 0) + 1; 531 byStatus[status] = (byStatus[status] || 0) + 1; 532 total++; 533 } catch {} 534 } 535 536 const sortDesc = (obj) => Object.entries(obj).sort((a, b) => b[1] - a[1]); 537 res.json({ 538 total, 539 logLines: lines.length, 540 byPath: sortDesc(byPath).slice(0, 30), 541 byHost: sortDesc(byHost).slice(0, 20), 542 byStatus: sortDesc(byStatus), 543 }); 544 } catch (err) { 545 res.json({ total: 0, error: err.message }); 546 } 547}); 548 549// --- Farcaster Frame endpoint for KidLisp pieces --- 550app.get("/frame/:piece", async (req, res) => { 551 const piece = req.params.piece.startsWith("$") ? req.params.piece : `$${req.params.piece}`; 552 const code = piece.slice(1); 553 const base = "https://aesthetic.computer"; 554 const pieceUrl = `${base}/${piece}`; 555 const keepUrl = `https://keep.kidlisp.com/${code}`; 556 557 // Try to get thumbnail from oven cache 558 const thumbUrl = `https://oven.aesthetic.computer/grab/webp/600/400/${piece}`; 559 // Fallback OG image 560 const ogImage = `https://oven.aesthetic.computer/kidlisp-og.png`; 561 562 const frameEmbed = JSON.stringify({ 563 version: "1", 564 imageUrl: thumbUrl, 565 button: { 566 title: `View ${piece}`, 567 action: { 568 type: "launch_frame", 569 url: pieceUrl, 570 name: `KidLisp ${piece}`, 571 splashImageUrl: "https://assets.aesthetic.computer/kidlisp-favicon.gif", 572 splashBackgroundColor: "#000000", 573 }, 574 }, 575 }); 576 577 res.setHeader("Content-Type", "text/html; charset=utf-8"); 578 res.send(`<!DOCTYPE html> 579<html> 580<head> 581 <meta charset="utf-8"> 582 <meta property="og:title" content="${piece} — KidLisp" /> 583 <meta property="og:description" content="A KidLisp piece on Aesthetic Computer" /> 584 <meta property="og:image" content="${thumbUrl}" /> 585 <meta property="og:url" content="${pieceUrl}" /> 586 <meta property="fc:frame" content='${frameEmbed.replace(/'/g, "&#39;")}' /> 587 <meta name="fc:frame" content='${frameEmbed.replace(/'/g, "&#39;")}' /> 588 <title>${piece} — KidLisp</title> 589</head> 590<body> 591 <h1>${piece}</h1> 592 <p><a href="${pieceUrl}">View on Aesthetic Computer</a></p> 593 <p><a href="${keepUrl}">Keep on KidLisp</a></p> 594</body> 595</html>`); 596}); 597 598// --- /api/os-release-upload (ports Netlify edge function os-release-upload.js) --- 599app.post("/api/os-release-upload", async (req, res) => { 600 const { createHmac } = await import("crypto"); 601 602 // Auth: verify AC token 603 const authHeader = req.headers["authorization"] || ""; 604 const token = authHeader.startsWith("Bearer ") ? authHeader.slice(7).trim() : ""; 605 if (!token) return res.status(401).json({ error: "Missing Authorization: Bearer <ac_token>" }); 606 607 let user; 608 try { 609 const uiRes = await fetch("https://hi.aesthetic.computer/userinfo", { 610 headers: { Authorization: `Bearer ${token}` }, 611 }); 612 if (!uiRes.ok) throw new Error(`Auth0 ${uiRes.status}`); 613 user = await uiRes.json(); 614 } catch (err) { 615 return res.status(401).json({ error: `Auth failed: ${err.message}` }); 616 } 617 618 const userSub = user.sub || "unknown"; 619 const userName = user.name || user.nickname || userSub; 620 621 const accessKey = process.env.DO_SPACES_KEY || process.env.ART_KEY; 622 const secretKey = process.env.DO_SPACES_SECRET || process.env.ART_SECRET; 623 if (!accessKey || !secretKey) return res.status(503).json({ error: "Spaces creds not configured" }); 624 625 const bucket = "releases-aesthetic-computer"; 626 const host = `${bucket}.sfo3.digitaloceanspaces.com`; 627 628 const buildName = req.headers["x-build-name"] || `upload-${Date.now()}`; 629 const gitHash = req.headers["x-git-hash"] || "unknown"; 630 const buildTs = req.headers["x-build-ts"] || new Date().toISOString().slice(0, 16); 631 const commitMsg = req.headers["x-commit-msg"] || ""; 632 const version = `${buildName} ${gitHash}-${buildTs}`; 633 634 function presignUrl(key, contentType, expiresSec = 900) { 635 const expires = Math.floor(Date.now() / 1000) + expiresSec; 636 const stringToSign = `PUT\n\n${contentType}\n${expires}\nx-amz-acl:public-read\n/${bucket}/${key}`; 637 const sig = createHmac("sha1", secretKey).update(stringToSign).digest("base64"); 638 return `https://${host}/${key}?AWSAccessKeyId=${encodeURIComponent(accessKey)}&Expires=${expires}&Signature=${encodeURIComponent(sig)}&x-amz-acl=public-read`; 639 } 640 641 async function s3Put(key, body, contentType) { 642 const dateStr = new Date().toUTCString(); 643 const stringToSign = `PUT\n\n${contentType}\n${dateStr}\nx-amz-acl:public-read\n/${bucket}/${key}`; 644 const sig = createHmac("sha1", secretKey).update(stringToSign).digest("base64"); 645 const putRes = await fetch(`https://${host}/${key}`, { 646 method: "PUT", 647 headers: { Date: dateStr, "Content-Type": contentType, "x-amz-acl": "public-read", Authorization: `AWS ${accessKey}:${sig}` }, 648 body: typeof body === "string" ? body : body, 649 }); 650 if (!putRes.ok) { 651 const text = await putRes.text(); 652 throw new Error(`S3 PUT ${key}: ${putRes.status} ${text.slice(0, 200)}`); 653 } 654 } 655 656 async function loadMachineTokenSecret() { 657 try { 658 const connStr = process.env.MONGODB_CONNECTION_STRING; 659 if (!connStr) return null; 660 const { MongoClient } = await import("mongodb"); 661 const client = new MongoClient(connStr); 662 await client.connect(); 663 const dbName = process.env.MONGODB_NAME || "aesthetic"; 664 const doc = await client.db(dbName).collection("secrets").findOne({ _id: "machine-token" }); 665 await client.close(); 666 return doc?.secret || null; 667 } catch (e) { 668 console.error("[os-release-upload] Failed to load machine-token secret:", e.message); 669 return null; 670 } 671 } 672 673 async function generateDeviceToken(sub, handle) { 674 const secret = await loadMachineTokenSecret(); 675 if (!secret) return null; 676 const payload = { sub, handle, iat: Math.floor(Date.now() / 1000) }; 677 const payloadB64 = Buffer.from(JSON.stringify(payload)).toString("base64url"); 678 const sigB64 = createHmac("sha256", secret).update(payloadB64).digest("base64url"); 679 return `${payloadB64}.${sigB64}`; 680 } 681 682 const isFinalize = req.headers["x-finalize"] === "true"; 683 684 if (isFinalize) { 685 const sha256 = req.headers["x-sha256"] || "unknown"; 686 const size = parseInt(req.headers["x-size"] || "0", 10); 687 try { 688 const versionWithSize = `${version}\n${size}`; 689 await Promise.all([ 690 s3Put("os/native-notepat-latest.version", versionWithSize, "text/plain"), 691 s3Put("os/native-notepat-latest.sha256", sha256, "text/plain"), 692 ]); 693 let releases = { releases: [] }; 694 try { 695 const existing = await fetch(`https://${host}/os/releases.json`); 696 if (existing.ok) releases = await existing.json(); 697 } catch { /* first release */ } 698 const userHandle = req.headers["x-handle"] || user.nickname || user.name || userName; 699 releases.releases = releases.releases || []; 700 for (const r of releases.releases) r.deprecated = true; 701 releases.releases.unshift({ 702 version, name: buildName, sha256, size, git_hash: gitHash, build_ts: buildTs, 703 commit_msg: commitMsg, user: userSub, handle: userHandle, 704 url: `https://${host}/os/native-notepat-latest.vmlinuz`, 705 archive_url: `https://${host}/os/builds/${buildName}.vmlinuz`, 706 }); 707 releases.releases = releases.releases.slice(0, 50); 708 releases.latest = version; 709 releases.latest_name = buildName; 710 const deviceToken = await generateDeviceToken(userSub, userHandle); 711 if (deviceToken) releases.device_token = deviceToken; 712 await s3Put("os/releases.json", JSON.stringify(releases, null, 2), "application/json"); 713 return res.json({ ok: true, name: buildName, version, sha256, size, url: `https://${host}/os/native-notepat-latest.vmlinuz`, user: userSub, userName, deviceToken: !!deviceToken }); 714 } catch (err) { 715 return res.status(500).json({ error: `Finalize failed: ${err.message}` }); 716 } 717 } 718 719 if (req.headers["x-versioned-upload"] === "true") { 720 try { 721 const versionedKey = req.headers["x-versioned-key"] || `os/builds/${buildName}.vmlinuz`; 722 return res.json({ step: "versioned-upload", versioned_put_url: presignUrl(versionedKey, "application/octet-stream", 1800), key: versionedKey, user: userSub }); 723 } catch (err) { 724 return res.status(500).json({ error: `Versioned presign failed: ${err.message}` }); 725 } 726 } 727 728 if (req.headers["x-manifest-upload"] === "true") { 729 try { 730 return res.json({ step: "manifest-upload", manifest_put_url: presignUrl("os/latest-manifest.json", "application/json"), user: userSub }); 731 } catch (err) { 732 return res.status(500).json({ error: `Manifest presign failed: ${err.message}` }); 733 } 734 } 735 736 if (req.headers["x-template-upload"] === "true") { 737 try { 738 return res.json({ step: "template-upload", image_put_url: presignUrl("os/native-notepat-latest.img", "application/octet-stream"), user: userSub }); 739 } catch (err) { 740 return res.status(500).json({ error: `Template presign failed: ${err.message}` }); 741 } 742 } 743 744 // Step 1: Return presigned URL for vmlinuz upload 745 try { 746 return res.json({ step: "upload", vmlinuz_put_url: presignUrl("os/native-notepat-latest.vmlinuz", "application/octet-stream"), version, user: userSub, userName }); 747 } catch (err) { 748 return res.status(500).json({ error: `Presign failed: ${err.message}` }); 749 } 750}); 751 752// --- /api/os-image (ports Netlify edge function os-image.js) --- 753app.get("/api/os-image", async (req, res) => { 754 const authHeader = req.headers["authorization"] || ""; 755 if (!authHeader) return res.status(401).json({ error: "Authorization required. Log in at aesthetic.computer first." }); 756 757 try { 758 const search = new URLSearchParams(req.query || {}).toString(); 759 const ovenUrl = "https://oven.aesthetic.computer/os-image" + (search ? `?${search}` : ""); 760 const ovenRes = await fetch(ovenUrl, { 761 headers: { Authorization: authHeader }, 762 }); 763 res.status(ovenRes.status); 764 res.set("Content-Type", ovenRes.headers.get("content-type") || "application/octet-stream"); 765 if (ovenRes.headers.get("content-disposition")) res.set("Content-Disposition", ovenRes.headers.get("content-disposition")); 766 if (ovenRes.headers.get("content-length")) res.set("Content-Length", ovenRes.headers.get("content-length")); 767 if (ovenRes.headers.get("x-ac-os-requested-layout")) res.set("X-AC-OS-Requested-Layout", ovenRes.headers.get("x-ac-os-requested-layout")); 768 if (ovenRes.headers.get("x-ac-os-layout")) res.set("X-AC-OS-Layout", ovenRes.headers.get("x-ac-os-layout")); 769 if (ovenRes.headers.get("x-ac-os-fallback")) res.set("X-AC-OS-Fallback", ovenRes.headers.get("x-ac-os-fallback")); 770 if (ovenRes.headers.get("x-ac-os-fallback-reason")) res.set("X-AC-OS-Fallback-Reason", ovenRes.headers.get("x-ac-os-fallback-reason")); 771 res.set("Access-Control-Allow-Origin", "*"); 772 const { Readable } = await import("stream"); 773 Readable.fromWeb(ovenRes.body).pipe(res); 774 } catch (err) { 775 return res.status(502).json({ error: `Oven unavailable: ${err.message}` }); 776 } 777}); 778 779// --- /media/* handler (ports Netlify edge function media.js) --- 780app.all("/media/*rest", async (req, res) => { 781 const parts = req.path.split("/").filter(Boolean); // ["media", ...] 782 parts.shift(); // remove "media" 783 const resourcePath = parts.join("/"); 784 785 if (!resourcePath) return res.status(404).send("Missing media path"); 786 787 // Content type from extension 788 const ext = resourcePath.split(".").pop()?.toLowerCase(); 789 const ctMap = { png: "image/png", jpg: "image/jpeg", jpeg: "image/jpeg", gif: "image/gif", webp: "image/webp", zip: "application/zip", mp4: "video/mp4", json: "application/json", mjs: "text/javascript", svg: "image/svg+xml" }; 790 791 // Helper: build a clean event for calling functions internally 792 function mediaEvent(path, query) { 793 return { 794 httpMethod: "GET", 795 headers: req.headers, 796 body: null, 797 queryStringParameters: query, 798 path, 799 rawUrl: `${req.protocol}://${req.get("host")}${path}`, 800 isBase64Encoded: false, 801 }; 802 } 803 804 // /media/tapes/CODE → get-tape function → redirect to DO Spaces 805 if (parts[0] === "tapes" && parts[1]) { 806 const code = parts[1].replace(/\.zip$/, ""); 807 try { 808 const result = await functions["get-tape"](mediaEvent("/api/get-tape", { code }), {}); 809 if (result.statusCode === 200) { 810 const tape = JSON.parse(result.body); 811 const bucket = tape.bucket || "art-aesthetic-computer"; 812 const key = tape.user ? `${tape.user}/${tape.slug}.zip` : `${tape.slug}.zip`; 813 return res.redirect(302, `https://${bucket}.sfo3.digitaloceanspaces.com/${key}`); 814 } 815 } catch {} 816 return res.status(404).send("Tape not found"); 817 } 818 819 // /media/paintings/CODE → get-painting function → redirect 820 if (parts[0] === "paintings" && parts[1]) { 821 const code = parts[1].replace(/\.(png|zip)$/, ""); 822 try { 823 const result = await functions["get-painting"]?.(mediaEvent("/api/get-painting", { code }), {}); 824 if (result?.statusCode === 200) { 825 const painting = JSON.parse(result.body); 826 const bucket = painting.user ? "user-aesthetic-computer" : "art-aesthetic-computer"; 827 const slug = painting.slug?.split(":")[0] || painting.slug; 828 const key = painting.user ? `${painting.user}/${slug}.png` : `${slug}.png`; 829 return res.redirect(302, `https://${bucket}.sfo3.digitaloceanspaces.com/${key}`); 830 } 831 } catch {} 832 return res.status(404).send("Painting not found"); 833 } 834 835 // /media/@handle/type/slug → resolve user ID → redirect to DO Spaces 836 if (parts[0]?.startsWith("@") || parts[0]?.match(/^ac[a-z0-9]+$/i)) { 837 const userIdentifier = parts[0]; 838 const subPath = parts.slice(1).join("/"); 839 840 // Resolve user ID via user function directly 841 try { 842 const query = userIdentifier.match(/^ac[a-z0-9]+$/i) 843 ? { code: userIdentifier } 844 : { from: userIdentifier }; 845 const event = { 846 httpMethod: "GET", 847 headers: req.headers, 848 body: null, 849 queryStringParameters: query, 850 path: "/user", 851 rawUrl: `${req.protocol}://${req.get("host")}/user`, 852 isBase64Encoded: false, 853 }; 854 const result = await functions["user"](event, {}); 855 if (result.statusCode === 200) { 856 const user = JSON.parse(result.body); 857 const userId = user.sub; 858 if (userId) { 859 const fullPath = `${userId}/${subPath}`; 860 const baseUrl = ext === "mjs" 861 ? "https://user-aesthetic-computer.sfo3.digitaloceanspaces.com" 862 : "https://user.aesthetic.computer"; 863 const encoded = fullPath.split("/").map(encodeURIComponent).join("/"); 864 return res.redirect(302, `${baseUrl}/${encoded}`); 865 } 866 } 867 } catch (err) { 868 console.error("media user resolve error:", err.message); 869 } 870 return res.status(404).send("User media not found"); 871 } 872 873 // Direct file path → proxy to DO Spaces 874 const baseUrl = ext === "mjs" 875 ? "https://user-aesthetic-computer.sfo3.digitaloceanspaces.com" 876 : "https://user.aesthetic.computer"; 877 const encoded = resourcePath.split("/").map(encodeURIComponent).join("/"); 878 return res.redirect(302, `${baseUrl}/${encoded}`); 879}); 880 881// API functions (matches Netlify redirect rules) 882app.all("/api/:fn", handleFunctionResolved); 883app.all("/api/:fn/*rest", handleFunctionResolved); 884app.all("/.netlify/functions/:fn", handleFunction); 885 886// Non-/api/ function routes (from netlify.toml) 887function directFn(fnName) { 888 return (req, res) => { req.params = { fn: fnName }; return handleFunction(req, res); }; 889} 890app.all("/handle", directFn("handle")); 891app.all("/user", directFn("user")); 892app.all("/run", directFn("run")); 893app.all("/reload/*rest", directFn("reload")); 894app.all("/session/*rest", directFn("session")); 895app.all("/authorized", directFn("authorized")); 896app.all("/handles", directFn("handles")); 897app.all("/redirect-proxy", directFn("redirect-proxy")); 898app.all("/redirect-proxy-sotce", directFn("redirect-proxy")); 899// Local dev upload fallback (used when S3 credentials are missing). 900app.all("/local-upload/:filename", (req, res) => { 901 if (req.method === "OPTIONS") return res.sendStatus(204); 902 const body = req.rawBody || req.body; 903 if (!body || body.length === 0) { 904 console.error("❌ Local upload: empty body for", req.params.filename); 905 return res.status(400).send("Empty body"); 906 } 907 const dir = join(dirname(fileURLToPath(import.meta.url)), "..", "local-uploads"); 908 mkdirSync(dir, { recursive: true }); 909 const filepath = join(dir, req.params.filename); 910 writeFileSync(filepath, body); 911 console.log("📁 Local upload saved:", filepath, `(${body.length} bytes)`); 912 res.status(200).send("OK"); 913}); 914app.use("/local-uploads", express.static(join(dirname(fileURLToPath(import.meta.url)), "..", "local-uploads"))); 915app.all("/presigned-upload-url/*rest", directFn("presigned-url")); 916app.all("/presigned-download-url/*rest", directFn("presigned-url")); 917app.all("/docs", directFn("docs")); 918app.all("/docs.json", directFn("docs")); 919app.all("/docs/*rest", directFn("docs")); 920app.all("/media-collection", directFn("media-collection")); 921app.all("/media-collection/*rest", directFn("media-collection")); 922app.all("/device-login", directFn("device-login")); 923app.all("/device-auth", directFn("device-auth")); 924app.all("/mcp", directFn("mcp-remote")); 925app.all("/m4l-plugins", directFn("m4l-plugins")); 926app.all("/slash", directFn("slash")); 927app.all("/sotce-blog/*rest", directFn("sotce-blog")); 928app.all("/profile/*rest", directFn("profile")); 929 930// Static files 931app.use(express.static(PUBLIC, { extensions: ["html"], dotfiles: "allow" })); 932 933// --- keeps-social: SSR meta tags for social crawlers on keep/buy.kidlisp.com --- 934const CRAWLER_RE = /twitterbot|facebookexternalhit|linkedinbot|slackbot|discordbot|telegrambot|whatsapp|applebot/i; 935const OBJKT_GRAPHQL = "https://data.objkt.com/v3/graphql"; 936 937async function keepsSocialMiddleware(req, res, next) { 938 const host = (req.headers.host || "").split(":")[0].toLowerCase(); 939 const isBuy = host.includes("buy.kidlisp.com"); 940 const isKeep = host.includes("keep.kidlisp.com"); 941 if (!isBuy && !isKeep) return next(); 942 943 const seg = req.path.replace(/^\/+/, "").split("/")[0]; 944 if (!seg.startsWith("$") || seg.length < 2) return next(); 945 946 const ua = req.headers["user-agent"] || ""; 947 if (!CRAWLER_RE.test(ua)) return next(); 948 949 const code = seg.slice(1); 950 try { 951 const [tokenData, ogImage] = await Promise.all([ 952 fetchKeepsTokenData(code), 953 resolveKeepsImageUrl(`https://oven.aesthetic.computer/preview/1200x630/$${code}.png`), 954 ]); 955 956 // Get the HTML from the index function 957 if (!functions["index"]) return next(); 958 const event = toEvent(req); 959 const result = await functions["index"](event, { clientContext: {} }); 960 let html = result.body || ""; 961 962 const title = `$${code}`; 963 const subdomain = isBuy ? "buy" : "keep"; 964 const description = buildKeepsDescription(tokenData, isBuy); 965 const permalink = `https://${subdomain}.kidlisp.com/$${code}`; 966 967 html = html.replace(/<meta property="og:url"[^>]*\/>/, `<meta property="og:url" content="${permalink}" />`); 968 html = html.replace(/<meta property="og:title"[^>]*\/>/, `<meta property="og:title" content="${escapeAttr(title)}" />`); 969 html = html.replace(/<meta property="og:description"[^>]*\/>/, `<meta property="og:description" content="${escapeAttr(description)}" />`); 970 html = html.replace(/<meta property="og:image" content="[^"]*"[^>]*\/>/, `<meta property="og:image" content="${ogImage}" />`); 971 html = html.replace(/<meta name="twitter:title"[^>]*\/>/, `<meta name="twitter:title" content="${escapeAttr(title)}" />`); 972 html = html.replace(/<meta name="twitter:description"[^>]*\/>/, `<meta name="twitter:description" content="${escapeAttr(description)}" />`); 973 html = html.replace(/<meta name="twitter:image" content="[^"]*"[^>]*\/>/, `<meta name="twitter:image" content="${ogImage}" />`); 974 975 res.set("Content-Type", "text/html; charset=utf-8"); 976 res.set("Cache-Control", "public, max-age=3600"); 977 return res.status(200).send(html); 978 } catch (err) { 979 console.error("[keeps-social] error:", err); 980 return next(); 981 } 982} 983 984async function fetchKeepsTokenData(code) { 985 const contract = "KT1Q1irsjSZ7EfUN4qHzAB2t7xLBPsAWYwBB"; 986 const query = `query { token(where: { fa_contract: { _eq: "${contract}" } name: { _eq: "$${code}" } }) { token_id name thumbnail_uri } listing_active(where: { fa_contract: { _eq: "${contract}" } token: { name: { _eq: "$${code}" } } } order_by: { price_xtz: asc } limit: 1) { price_xtz seller_address } }`; 987 const r = await fetch(OBJKT_GRAPHQL, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ query }) }); 988 if (!r.ok) return null; 989 const json = await r.json(); 990 const tokens = json?.data?.token || []; 991 if (tokens.length === 0) return null; 992 return { token: tokens[0], listing: (json?.data?.listing_active || [])[0] || null }; 993} 994 995function buildKeepsDescription(tokenData, isBuy) { 996 if (!tokenData) return isBuy ? "Buy KidLisp generative art on Tezos." : "KidLisp generative art preserved on Tezos."; 997 const { listing } = tokenData; 998 if (listing) { 999 const xtz = (Number(listing.price_xtz) / 1_000_000).toFixed(2); 1000 return isBuy ? `Buy now — ${xtz} XTZ | KidLisp generative art on Tezos` : `For Sale — ${xtz} XTZ | KidLisp generative art on Tezos`; 1001 } 1002 return isBuy ? "Buy KidLisp generative art on Tezos." : "KidLisp generative art preserved on Tezos."; 1003} 1004 1005function escapeAttr(str) { 1006 return str.replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/</g, "&lt;").replace(/>/g, "&gt;"); 1007} 1008 1009async function resolveKeepsImageUrl(url) { 1010 try { 1011 const r = await fetch(url, { method: "HEAD", redirect: "follow" }); 1012 if (r.ok && r.url) return r.url; 1013 } catch (e) { 1014 console.error("[keeps-social] image resolve error:", e); 1015 } 1016 return url; 1017} 1018 1019app.use(keepsSocialMiddleware); 1020 1021// SPA fallback → index function 1022app.use(async (req, res) => { 1023 if (functions["index"]) { 1024 req.params = { fn: "index" }; 1025 return handleFunction(req, res); 1026 } 1027 res.status(404).send("Not found"); 1028}); 1029 1030// --- Start server --- 1031let server; 1032if (DEV && HAS_SSL) { 1033 const opts = { 1034 cert: readFileSync(SSL_CERT), 1035 key: readFileSync(SSL_KEY), 1036 }; 1037 server = createHttpsServer(opts, app).listen(PORT, () => { 1038 console.log(`lith listening on https://localhost:${PORT}`); 1039 }); 1040} else { 1041 server = createHttpServer(app).listen(PORT, () => { 1042 console.log(`lith listening on http://localhost:${PORT}`); 1043 }); 1044} 1045 1046// --- Graceful shutdown --- 1047// On SIGTERM (sent by systemctl restart), stop accepting new connections 1048// and wait for in-flight requests to finish before exiting. 1049const DRAIN_TIMEOUT = 10_000; // 10s max wait 1050 1051function gracefulShutdown(signal) { 1052 console.log(`[lith] ${signal} received, draining connections...`); 1053 server.close(() => { 1054 console.log("[lith] all connections drained, exiting"); 1055 process.exit(0); 1056 }); 1057 // Force exit if connections don't drain in time 1058 setTimeout(() => { 1059 console.warn("[lith] drain timeout, forcing exit"); 1060 process.exit(1); 1061 }, DRAIN_TIMEOUT).unref(); 1062} 1063 1064process.on("SIGTERM", () => gracefulShutdown("SIGTERM")); 1065process.on("SIGINT", () => gracefulShutdown("SIGINT"));