import { Hono } from "hono"; import { cors } from "hono/cors"; import { Container, getContainer, switchPort } from "@cloudflare/containers"; import { paymentMiddleware, x402ResourceServer } from "@x402/hono"; import { render as renderMystText, fromOxa as oxaRecordToMystText } from "@nandithebull/myst-oxa"; import { HTTPFacilitatorClient } from "@x402/core/server"; import { ExactEvmScheme } from "@x402/evm/exact/server"; import { createWorker } from "@atmo-dev/contrail/worker"; import { Contrail } from "@atmo-dev/contrail"; import { markInProcess } from "@atmo-dev/contrail/server"; import type { Network, Price } from "@x402/core/types"; import { config } from "./contrail.config.js"; import { lexicons } from "../lexicons/generated/index.js"; import { CONFIG_PAGE } from "./config-page.js"; import { DOC_PAGE } from "./doc-page.js"; import { EDIT_PAGE } from "./edit-page.js"; import { LANDING_PAGE } from "./landing-page.js"; import { createPublicClient, http } from "viem"; import { base } from "viem/chains"; import { normalize, namehash } from "viem/ens"; const BASE_MAINNET: Network = "eip155:8453"; const DEFAULT_PRICE: Price = "$0.01"; const JUPYTER_SESSION_TTL_SECONDS = 60 * 60; const JUPYTER_SESSION_ID_RE = /^[a-zA-Z0-9_-]{16,96}$/; function escHtml(s: string): string { return s.replace(/&/g, "&").replace(//g, ">").replace(/"/g, """); } const baseClient = createPublicClient({ chain: base, transport: http("https://mainnet.base.org"), }); const L2_RESOLVER = "0xC6d566A56A1aFf6508b41f6c90ff131615583BCD" as const; interface PaymentConfig { address: string; price?: string; network?: string; } interface OwnerPayment { address: string; price: Price; } interface Env { DB: D1Database; JUPYTER_CONTAINER?: DurableObjectNamespace; JUPYTER_CONTAINER_ENABLED?: string; MONETIZATION_ENABLED?: string; X402_FACILITATOR_URL?: string; JUPYTER_KERNEL_NAME?: string; } type ProxyContext = { req: { raw: Request; header: (n: string) => string | undefined; url: string }; env: Env; }; type JupyterProxyContext = { req: { raw: Request; url: string; path: string; method: string }; }; const contrailWorker = createWorker(config, { lexicons }); const contrail = new Contrail(config); let contrailReady = false; export class JupyterContainer extends Container { defaultPort = 8888; sleepAfter = "10m"; } async function ensureContrailReady(db: D1Database): Promise { if (contrailReady) return; await contrail.init(db); contrailReady = true; } let app: Hono<{ Bindings: Env }> | null = null; const OAUTH_CLIENT_METADATA = { client_id: "https://science.latha.org/oauth-client-metadata.json", client_name: "Scientific Appview", client_uri: "https://science.latha.org", redirect_uris: ["https://science.latha.org/"], scope: "atproto transition:generic", grant_types: ["authorization_code", "refresh_token"], response_types: ["code"], token_endpoint_auth_method: "none", application_type: "web", dpop_bound_access_tokens: true, }; /** Look up a DID's payment config from the indexed records_paymentConfig table. */ async function lookupPaymentConfig(db: D1Database, did: string): Promise { const row = await db .prepare( "SELECT record->>'address' as address, record->>'price' as price, record->>'network' as network FROM records_paymentConfig WHERE did = ? LIMIT 1" ) .bind(did) .first(); return row; } /** Resolve a handle to a DID via the contrail identities table. */ async function resolveHandle(db: D1Database, handle: string): Promise { const normalizedHandle = normalizeDocActor(handle); const row = await db .prepare("SELECT did FROM identities WHERE handle = ? LIMIT 1") .bind(normalizedHandle) .first<{ did: string }>(); if (row?.did) return row.did; try { const res = await fetch( `https://public.api.bsky.app/xrpc/com.atproto.identity.resolveHandle?handle=${encodeURIComponent(normalizedHandle)}` ); if (!res.ok) return null; const data = await res.json() as { did?: string }; return data.did ?? null; } catch { return null; } } /** Resolve an actor param (DID or handle) to a DID. */ async function resolveActor(db: D1Database, actor: string): Promise { if (actor.startsWith("did:")) return actor; return resolveHandle(db, actor); } function normalizeDocActor(actor: string): string { return actor.startsWith("@") ? actor.slice(1) : actor; } function canonicalDocPath(actor: string, rkey: string): string { return `/doc/${encodeURIComponent(actor)}/${encodeURIComponent(rkey)}`; } async function resolveDidHandle(db: D1Database, did: string): Promise { const row = await db .prepare("SELECT handle FROM identities WHERE did = ? LIMIT 1") .bind(did) .first<{ handle: string | null }>(); if (row?.handle) return row.handle; try { const plcRes = await fetch(`https://plc.directory/${did}`); if (!plcRes.ok) return null; const doc = await plcRes.json() as { alsoKnownAs?: string[] }; const aka = doc.alsoKnownAs?.[0]; if (typeof aka === "string" && aka.startsWith("at://")) { return aka.slice(5); } } catch { // Ignore PLC lookup failures and fall back to the DID path. } return null; } /** Extract the owner DID from a space URI like ats://did:plc:.../pub.oxa.document.space/ */ function ownerFromSpaceUri(uri: string): string | null { const match = uri.match(/^ats:\/\/(did:[^/]+)/); return match?.[1] ?? null; } /** Resolve a Base Name (e.g. nandi.base.eth) directly on Base L2. */ async function resolveEnsOnBase(name: string): Promise { try { const node = namehash(normalize(name)); const result = await baseClient.readContract({ address: L2_RESOLVER, abi: [{ name: "addr", type: "function", stateMutability: "view", inputs: [{ type: "bytes32" }], outputs: [{ type: "address" }], }], functionName: "addr", args: [node], }); const addr = result as `0x${string}`; return addr && addr !== "0x0000000000000000000000000000000000000000" ? addr : null; } catch { return null; } } const USDC_BASE_CONTRACT = "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913" as const; const TRANSFER_EVENT_SIG = "0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"; /** Check Base RPC for recent USDC Transfer events to the given address. */ async function checkOnChainPayment( recipientAddress: string, requiredAtomicAmount: string ): Promise<{ txHash: string } | null> { try { // Get current block number const blockRes = await fetch("https://mainnet.base.org", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "eth_blockNumber", params: [], }), }); const blockData = await blockRes.json() as any; const latestBlock = parseInt(blockData.result, 16); const fromBlock = Math.max(0, latestBlock - 200); // ~10 min window // Pad recipient address to 32 bytes for topic2 (indexed `to` param) const paddedAddr = recipientAddress.toLowerCase().replace("0x", "").padStart(64, "0"); // Query Transfer events const logsRes = await fetch("https://mainnet.base.org", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ jsonrpc: "2.0", id: 2, method: "eth_getLogs", params: [ { fromBlock: "0x" + fromBlock.toString(16), toBlock: "latest", address: USDC_BASE_CONTRACT, topics: [TRANSFER_EVENT_SIG, null, "0x" + paddedAddr], }, ], }), }); const logsData = await logsRes.json() as any; const logs = logsData.result as any[]; if (!logs?.length) return null; const required = BigInt(requiredAtomicAmount); for (const log of logs) { // data field is the amount (uint256) const amount = BigInt(log.data); if (amount >= required) { return { txHash: log.transactionHash }; } } return null; } catch { return null; } } /** Check D1 for a cached on-chain payment (bypasses x402 if found). */ async function checkCachedPayment( db: D1Database, spaceUri: string, ownerAddress: string ): Promise { try { await db.exec( "CREATE TABLE IF NOT EXISTS payments (spaceUri TEXT NOT NULL, address TEXT NOT NULL, txHash TEXT NOT NULL, amount TEXT NOT NULL, expiresAt INTEGER NOT NULL, PRIMARY KEY (spaceUri, address))" ); const row = await db .prepare("SELECT expiresAt FROM payments WHERE spaceUri = ? AND address = ?") .bind(spaceUri, ownerAddress.toLowerCase()) .first(); return !!row && (row.expiresAt as number) > Date.now() / 1000; } catch { return false; } } /** Resolve the owner payment config for a space read request. */ async function resolveOwnerPayment(db: D1Database, spaceUri: string): Promise { const ownerDid = ownerFromSpaceUri(spaceUri); if (!ownerDid) return null; const cfg = await lookupPaymentConfig(db, ownerDid); if (!cfg?.address) return null; // Resolve ENS name if not a hex address let address = cfg.address; if (!address.startsWith("0x")) { const resolved = await resolveEnsOnBase(address); if (!resolved || resolved.length !== 42) return null; // can't resolve ENS, skip payment address = resolved; } else if (address.length !== 42) { return null; // invalid hex address } return { address, price: (cfg.price as Price) ?? DEFAULT_PRICE, }; } function jupyterWsUrl(requestUrl: string): string { const url = new URL(requestUrl); url.protocol = url.protocol === "https:" ? "wss:" : "ws:"; url.pathname = "/jupyter/"; url.search = ""; return url.toString(); } function jupyterContainersEnabled(env: Env): boolean { return env.JUPYTER_CONTAINER_ENABLED === "true" && !!env.JUPYTER_CONTAINER; } function randomToken(): string { const bytes = new Uint8Array(32); crypto.getRandomValues(bytes); return btoa(String.fromCharCode(...bytes)).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, ""); } function normalizeJupyterSessionId(value: string | null | undefined): string { if (value && JUPYTER_SESSION_ID_RE.test(value)) return value; return crypto.randomUUID().replace(/-/g, ""); } async function ensureJupyterSessionTable(db: D1Database): Promise { await db.exec( "CREATE TABLE IF NOT EXISTS jupyter_sessions (sessionId TEXT PRIMARY KEY, token TEXT NOT NULL, expiresAt INTEGER NOT NULL, createdAt INTEGER NOT NULL)" ); } async function getOrCreateJupyterSession( db: D1Database, requestedSessionId?: string | null ): Promise<{ sessionId: string; token: string; expiresAt: number }> { await ensureJupyterSessionTable(db); const sessionId = normalizeJupyterSessionId(requestedSessionId); const now = Math.floor(Date.now() / 1000); const existing = await db .prepare("SELECT token, expiresAt FROM jupyter_sessions WHERE sessionId = ?") .bind(sessionId) .first<{ token: string; expiresAt: number }>(); if (existing && existing.expiresAt > now) { return { sessionId, token: existing.token, expiresAt: existing.expiresAt }; } const token = randomToken(); const expiresAt = now + JUPYTER_SESSION_TTL_SECONDS; await db .prepare("INSERT OR REPLACE INTO jupyter_sessions (sessionId, token, expiresAt, createdAt) VALUES (?, ?, ?, ?)") .bind(sessionId, token, expiresAt, now) .run(); return { sessionId, token, expiresAt }; } async function validateJupyterSession(db: D1Database, sessionId: string, request: Request): Promise { if (!JUPYTER_SESSION_ID_RE.test(sessionId)) return false; await ensureJupyterSessionTable(db); const url = new URL(request.url); const auth = request.headers.get("authorization") ?? ""; const provided = url.searchParams.get("token") ?? (auth.toLowerCase().startsWith("token ") ? auth.slice(6).trim() : null) ?? (auth.toLowerCase().startsWith("bearer ") ? auth.slice(7).trim() : null); if (!provided) return false; const row = await db .prepare("SELECT token, expiresAt FROM jupyter_sessions WHERE sessionId = ?") .bind(sessionId) .first<{ token: string; expiresAt: number }>(); return !!row && row.expiresAt > Date.now() / 1000 && row.token === provided; } function jupyterSessionWsUrl(requestUrl: string, sessionId: string): string { const url = new URL(jupyterWsUrl(requestUrl)); url.pathname = `/jupyter/${sessionId}/`; return url.toString(); } async function proxyJupyterRequest( c: JupyterProxyContext, container: DurableObjectStub, sessionId: string ): Promise { const incoming = new URL(c.req.url); const rest = c.req.path.slice(`/jupyter/${sessionId}`.length).replace(/^\//, ""); const upstream = new URL(`/${rest}${incoming.search}`, "http://jupyter.internal"); const headers = new Headers(c.req.raw.headers); headers.delete("host"); headers.delete("cf-connecting-ip"); headers.delete("cf-ipcountry"); headers.delete("cf-ray"); headers.delete("cf-visitor"); headers.set("origin", "http://jupyter.internal"); const method = c.req.method; const init: RequestInit = { method, headers, body: method === "GET" || method === "HEAD" ? undefined : c.req.raw.body, redirect: "manual" }; let response: Response; try { response = await container.fetch(switchPort(new Request(upstream.toString(), init), 8888)); } catch (err) { const message = err instanceof Error ? err.message : String(err); console.error(`[jupyter] container fetch failed for ${rest}: ${message}`); // For list endpoints, return 200 with empty data so thebe stops retrying. // For everything else, return 502 with a clear error. if (method === "GET" && (rest.startsWith("api/kernels?") || rest.startsWith("api/sessions?"))) { return Response.json([], { status: 200 }); } return Response.json({ error: "JupyterContainerUnreachable", message: "The Jupyter container is not responding. It may be cold-starting or crashed.", detail: message, retryAfter: 10, }, { status: 502 }); } if ((response as Response & { webSocket?: WebSocket | null }).webSocket) { return response; } // Wrap 500s from the container with a helpful message. // For list endpoints, return 200 with empty data so thebe stops retrying. if (response.status >= 500) { let detail = ""; try { detail = await response.clone().text(); } catch { /* ignore */ } console.error(`[jupyter] container returned ${response.status} for ${rest}: ${detail.slice(0, 200)}`); if (method === "GET" && (rest.startsWith("api/kernels?") || rest.startsWith("api/sessions?"))) { return Response.json([], { status: 200 }); } return Response.json({ error: "JupyterContainerError", message: response.status === 503 ? "The Jupyter container is still starting up. Wait a moment and try again." : "The Jupyter container returned an error. It may be cold-starting or the kernel crashed.", status: response.status, detail: detail.slice(0, 500), retryAfter: 10, }, { status: response.status }); } const responseHeaders = new Headers(response.headers); const location = responseHeaders.get("location"); if (location) { const rewritten = new URL(location, upstream); if (rewritten.origin === upstream.origin) { responseHeaders.set( "location", `/jupyter/${sessionId}${rewritten.pathname}${rewritten.search}${rewritten.hash}` ); } } return new Response(response.body, { status: response.status, statusText: response.statusText, headers: responseHeaders, }); } function buildApp(env: Env): Hono<{ Bindings: Env }> { const app = new Hono<{ Bindings: Env }>(); const db = env.DB; app.use("*", cors()); const facilitatorUrl = env.X402_FACILITATOR_URL ?? "https://x402.org/facilitator"; const facilitator = new HTTPFacilitatorClient({ url: facilitatorUrl }); const server = new x402ResourceServer(facilitator); server.register(BASE_MAINNET, new ExactEvmScheme()); // Landing page // Landing page — server-rendered document list from D1 app.get("/", async (c) => { const db = c.env.DB as D1Database; await ensureContrailReady(db); let docsJson = "[]"; try { const rows = await db .prepare("SELECT record, did, rkey FROM records_document ORDER BY time_us DESC LIMIT 20") .all<{ record: string; did: string; rkey: string }>(); const docs = (rows.results || []).map(r => { try { const value = JSON.parse(r.record); return { did: r.did, rkey: r.rkey, uri: `at://${r.did}/pub.oxa.document/${r.rkey}`, title: value?.title?.text || value?.title || "Untitled" }; } catch { return null; } }).filter(Boolean); // Resolve handles for all DIDs const dids = [...new Set(docs.map((d: any) => d.did))]; if (dids.length > 0) { const placeholders = dids.map(() => "?").join(","); const handleRows = await db .prepare(`SELECT did, handle FROM identities WHERE did IN (${placeholders})`) .bind(...dids) .all<{ did: string; handle: string | null }>(); const handleMap = new Map((handleRows.results || []).map(r => [r.did, r.handle])); for (const doc of docs) { (doc as any).handle = handleMap.get((doc as any).did) || null; } } docsJson = JSON.stringify(docs); } catch { /* empty list is fine */ } const page = LANDING_PAGE.replace("", ``); return c.html(page); }); // OAuth client metadata (required by ATProto OAuth spec) app.get("/oauth-client-metadata.json", (c) => c.json(OAUTH_CLIENT_METADATA)); // Payment config UI (feature-gated) app.get("/config", (c) => { if (!(c.env.MONETIZATION_ENABLED === "true")) return c.notFound(); return c.html(CONFIG_PAGE); }); async function renderPublicDocPage(c: any, actor: string, rkey: string): Promise { const db = c.env.DB as D1Database; await ensureContrailReady(db); const normalizedActor = normalizeDocActor(actor); const did = await resolveActor(db, normalizedActor); if (!did) return c.notFound(); const row = await db .prepare("SELECT record, did FROM records_document WHERE did = ? AND rkey = ? LIMIT 1") .bind(did, rkey) .first<{ record: string; did: string }>(); if (!row?.record) return c.notFound(); const canonicalHandle = await resolveDidHandle(db, row.did); if (canonicalHandle && normalizedActor !== canonicalHandle) { return c.redirect(canonicalDocPath(canonicalHandle, rkey), 302); } let recordJson = "null"; let title = "Document"; let authorHandle = canonicalHandle || (normalizedActor.startsWith("did:") ? "" : normalizedActor); let renderedHtml = ""; try { const value = JSON.parse(row.record); recordJson = JSON.stringify({ value, did: row.did }); title = value?.title?.text || value?.title || "Untitled"; authorHandle = canonicalHandle || (normalizedActor.startsWith("did:") ? "" : normalizedActor); // Render HTML server-side const mystText = oxaRecordToMystText(value); renderedHtml = renderMystText(title, mystText); } catch { // Keep the default placeholder state if the record can't be parsed. } const page = DOC_PAGE .replace("", ``) .replace("Document", `${escHtml(title)} — science.latha.org`) .replace('
', `
${renderedHtml}`); return c.html(page); } // Document page — server-rendered from D1 app.get("/doc/:actor/:rkey", async (c) => { const actor = c.req.param("actor"); const rkey = c.req.param("rkey"); if (!actor || !rkey) return c.notFound(); return renderPublicDocPage(c, actor, rkey); }); app.get("/doc", async (c) => { const spaceUri = c.req.query("spaceUri"); if (spaceUri) return c.html(DOC_PAGE); const uri = c.req.query("uri"); const author = c.req.query("author"); const rkey = c.req.query("rkey"); if (uri || (author && rkey)) { let actor = author || ""; let docRkey = rkey || ""; if (uri) { const uriParts = uri.replace("at://", "").split("/"); actor = uriParts[0] || ""; docRkey = uriParts[2] || ""; } if (!actor || !docRkey) return c.notFound(); return renderPublicDocPage(c, actor, docRkey); } return c.notFound(); }); app.get("/edit", (c) => c.html(EDIT_PAGE)); // Index a record into D1 immediately (called after PDS write so search works without waiting for firehose) app.post("/api/index-record", async (c) => { const body = await c.req.json<{ did: string; rkey: string; record: string; cid?: string }>(); if (!body.did || !body.rkey || !body.record) return c.json({ error: "Missing did, rkey, or record" }, 400); const db = c.env.DB as D1Database; await ensureContrailReady(db); const uri = `at://${body.did}/pub.oxa.document/${body.rkey}`; const now = Date.now(); const time_us = now * 1000; const indexed_at = new Date(now).toISOString(); const cid = body.cid || ""; const recordStr = typeof body.record === "string" ? body.record : JSON.stringify(body.record); try { await db.batch([ db.prepare( `INSERT INTO records_document (uri, did, rkey, cid, record, time_us, indexed_at) VALUES (?, ?, ?, ?, ?, ?, ?) ON CONFLICT(uri) DO UPDATE SET cid = excluded.cid, record = excluded.record, time_us = excluded.time_us, indexed_at = excluded.indexed_at` ).bind(uri, body.did, body.rkey, cid, recordStr, time_us, indexed_at), db.prepare(`DELETE FROM fts_document WHERE uri = ?`).bind(uri), ]); // Insert FTS content try { const value = JSON.parse(recordStr); const title = value?.title?.text || value?.title || ""; if (typeof title === "string" && title.length > 0) { await db.prepare("INSERT INTO fts_document (uri, content) VALUES (?, ?)").bind(uri, title).run(); } } catch { /* no FTS is fine */ } // Upsert identity const handleRow = await db.prepare("SELECT handle FROM identities WHERE did = ? LIMIT 1").bind(body.did).first<{ handle: string | null }>(); if (!handleRow) { await db.prepare("INSERT OR IGNORE INTO identities (did, handle, pds) VALUES (?, ?, '')").bind(body.did, "").run(); } return c.json({ ok: true, uri }); } catch (e: any) { return c.json({ error: e.message }, 500); } }); // Proxy public record reads from the user's PDS. // Serve records from D1 index (contrail's records_document table) with PDS fallback. app.get("/api/record", async (c) => { const repo = c.req.query("repo"); const collection = c.req.query("collection"); const rkey = c.req.query("rkey"); if (!repo || !collection || !rkey) { return c.json({ error: "Missing repo, collection, or rkey" }, 400); } // Try D1 first const db = c.env.DB as D1Database; await ensureContrailReady(db); const shortName = collection === "pub.oxa.document" ? "document" : collection === "org.latha.paymentConfig" ? "paymentConfig" : null; if (shortName) { const row = await db .prepare(`SELECT record FROM records_${shortName} WHERE did = ? AND rkey = ? LIMIT 1`) .bind(repo, rkey) .first<{ record: string }>(); if (row?.record) { try { const value = JSON.parse(row.record); return c.json({ uri: `at://${repo}/${collection}/${rkey}`, did: repo, rkey, value }); } catch { /* fall through to PDS */ } } } // Fallback: proxy to PDS let pdsUrl: string; if (repo.startsWith("did:plc:")) { try { const plcRes = await fetch(`https://plc.directory/${repo}`); const plcData = await plcRes.json() as { service?: { type: string; serviceEndpoint: string }[] }; const atprotoService = (plcData.service || []).find((s: any) => s.type === "AtprotoPersonalDataServer" || s.serviceEndpoint?.includes("bsky")); if (!atprotoService?.serviceEndpoint) { return c.json({ error: "No ATProto PDS endpoint found for DID" }, 404); } pdsUrl = atprotoService.serviceEndpoint; } catch { return c.json({ error: "Failed to resolve DID" }, 502); } } else if (repo.startsWith("did:web:")) { const domain = repo.replace("did:web:", ""); pdsUrl = `https://${domain}`; } else { return c.json({ error: "Unsupported DID method" }, 400); } const recordUrl = `${pdsUrl}/xrpc/com.atproto.repo.getRecord?repo=${encodeURIComponent(repo)}&collection=${encodeURIComponent(collection)}&rkey=${encodeURIComponent(rkey)}`; const recordRes = await fetch(recordUrl); return new Response(recordRes.body, { status: recordRes.status, headers: { "Content-Type": "application/json", "Access-Control-Allow-Origin": "*" }, }); }); // Resolve DID to handle using contrail's identities table, with PLC fallback. app.get("/api/resolve-handle", async (c) => { const did = c.req.query("did"); if (!did) return c.json({ error: "Missing did" }, 400); const db = c.env.DB as D1Database; await ensureContrailReady(db); const handle = await resolveDidHandle(db, did); return c.json({ did, handle }); }); // Resolve handle to DID for canonical doc URLs. app.get("/api/resolve-did", async (c) => { const handle = c.req.query("handle"); if (!handle) return c.json({ error: "Missing handle" }, 400); const db = c.env.DB as D1Database; await ensureContrailReady(db); const did = await resolveActor(db, normalizeDocActor(handle)); if (!did) return c.json({ handle, did: null }, 404); return c.json({ handle, did }); }); // Backend Jupyter container config/proxy. The Worker is the same-origin // access layer; the actual Jupyter Server runs in a Cloudflare Container. app.get("/api/jupyter/config", (c) => { const enabled = jupyterContainersEnabled(env); return c.json({ enabled, baseUrl: null, wsUrl: null, kernelName: env.JUPYTER_KERNEL_NAME ?? "python3", }); }); // Diagnostic endpoint: fetch Jupyter server state directly app.get("/api/jupyter/debug", async (c) => { if (!jupyterContainersEnabled(env) || !env.JUPYTER_CONTAINER) { return c.json({ error: "containers disabled" }); } const container = getContainer(env.JUPYTER_CONTAINER, "shared-jupyter"); const results: Record = {}; try { // Server status const statusRes = await container.fetch(switchPort(new Request("http://jupyter.internal/api/status"), 8888)); results.status = { code: statusRes.status, body: await statusRes.text().catch(() => "") }; } catch (e) { results.status = { error: String(e) }; } try { // List kernels const kernelsRes = await container.fetch(switchPort(new Request("http://jupyter.internal/api/kernels"), 8888)); results.kernels = { code: kernelsRes.status, body: await kernelsRes.text().catch(() => "") }; } catch (e) { results.kernels = { error: String(e) }; } try { // List sessions const sessionsRes = await container.fetch(switchPort(new Request("http://jupyter.internal/api/sessions"), 8888)); results.sessions = { code: sessionsRes.status, body: await sessionsRes.text().catch(() => "") }; } catch (e) { results.sessions = { error: String(e) }; } try { // Kernel specs const specsRes = await container.fetch(switchPort(new Request("http://jupyter.internal/api/kernelspecs"), 8888)); results.kernelspecs = { code: specsRes.status, body: await specsRes.text().catch(() => "").then(t => t.slice(0, 2000)) }; } catch (e) { results.kernelspecs = { error: String(e) }; } return c.json(results); }); // Diagnostic: read Jupyter server log file via log server on 8889 // ?name=xxx to target the same container instance as a session app.get("/api/jupyter/logs", async (c) => { if (!jupyterContainersEnabled(env) || !env.JUPYTER_CONTAINER) { return c.json({ error: "containers disabled" }); } const name = c.req.query("name") ?? "shared-jupyter"; const container = getContainer(env.JUPYTER_CONTAINER, name); try { const logRes = await container.fetch(switchPort(new Request("http://jupyter.internal:8889/logs"), 8889)); return c.text(await logRes.text()); } catch (e) { return c.json({ error: String(e) }); } }); // Diagnostic: process list from container app.get("/api/jupyter/ps", async (c) => { if (!jupyterContainersEnabled(env) || !env.JUPYTER_CONTAINER) { return c.json({ error: "containers disabled" }); } const name = c.req.query("name") ?? "shared-jupyter"; const container = getContainer(env.JUPYTER_CONTAINER, name); try { const psRes = await container.fetch(switchPort(new Request("http://jupyter.internal:8889/ps"), 8889)); return c.text(await psRes.text()); } catch (e) { return c.json({ error: String(e) }); } }); app.get("/api/jupyter/diag", async (c) => { if (!jupyterContainersEnabled(env) || !env.JUPYTER_CONTAINER) { return c.json({ error: "containers disabled" }); } const name = c.req.query("name") ?? "shared-jupyter"; const container = getContainer(env.JUPYTER_CONTAINER, name); try { const diagRes = await container.fetch(switchPort(new Request("http://jupyter.internal:8889/diag"), 8889)); return c.json(await diagRes.json()); } catch (e) { return c.json({ error: String(e) }); } }); app.get("/api/jupyter/execute", async (c) => { if (!jupyterContainersEnabled(env) || !env.JUPYTER_CONTAINER) { return c.json({ error: "containers disabled" }); } const code = c.req.query("code") ?? "print(1+1)"; const name = c.req.query("name") ?? "shared-jupyter"; const container = getContainer(env.JUPYTER_CONTAINER, name); try { const execRes = await container.fetch(switchPort(new Request(`http://jupyter.internal:8889/execute?code=${encodeURIComponent(code)}`), 8889)); return c.json(await execRes.json()); } catch (e) { return c.json({ error: String(e) }); } }); app.get("/api/jupyter/kick", async (c) => { if (!jupyterContainersEnabled(env) || !env.JUPYTER_CONTAINER) { return c.json({ error: "containers disabled" }); } const name = c.req.query("name") ?? "shared-jupyter"; const container = getContainer(env.JUPYTER_CONTAINER, name); try { const kickRes = await container.fetch(switchPort(new Request("http://jupyter.internal:8889/kick"), 8889)); return c.json(await kickRes.json()); } catch (e) { return c.json({ error: String(e) }); } }); app.post("/api/jupyter/session", async (c) => { if (!jupyterContainersEnabled(env) || !env.JUPYTER_CONTAINER) { return c.json({ enabled: false, error: "JupyterBackendDisabled" }, 404); } const body = await c.req.json().catch(() => ({})) as { sessionId?: string }; const session = await getOrCreateJupyterSession(db, body.sessionId); // Use a shared container for all sessions to avoid hitting max_instances const container = getContainer(env.JUPYTER_CONTAINER, "shared-jupyter"); const kernelName = env.JUPYTER_KERNEL_NAME ?? "python3"; // Stream NDJSON progress to the frontend so the user can see // what the container is doing while they wait. const stream = new ReadableStream({ async start(controller) { const encoder = new TextEncoder(); const send = (data: Record) => { controller.enqueue(encoder.encode(JSON.stringify(data) + "\n")); }; const fail = (error: string, message: string) => { send({ status: "error", error, message }); controller.close(); }; // Phase 1: poll until the Jupyter API is ready send({ status: "warming", phase: "container", message: "Waking container..." }); let containerReady = false; const maxWarmup = 40; for (let i = 0; i < maxWarmup; i++) { try { const [kernelsRes, sessionsRes] = await Promise.all([ container.fetch(switchPort(new Request("http://jupyter.internal/api/kernels"), 8888)), container.fetch(switchPort(new Request("http://jupyter.internal/api/sessions"), 8888)), ]); if (kernelsRes.ok && sessionsRes.ok) { containerReady = true; send({ status: "warming", phase: "container", message: `Container ready (${i + 1} attempts)` }); console.log(`[jupyter] API ready after ${i + 1} attempts`); break; } send({ status: "warming", phase: "container", attempt: i + 1, message: `kernels=${kernelsRes.status}, sessions=${sessionsRes.status}`, kernelsBody: await kernelsRes.text().catch(() => ""), sessionsBody: await sessionsRes.text().catch(() => "") }); } catch (err) { const msg = err instanceof Error ? err.message : String(err); send({ status: "warming", phase: "container", attempt: i + 1, message: msg }); if (msg.includes("Containers have not been enabled") || msg.includes("not been enabled for this Durable Object")) { fail("JupyterContainerNotConfigured", "Containers are not enabled for this deployment."); return; } } await new Promise(r => setTimeout(r, 500)); } if (!containerReady) { fail("JupyterContainerTimeout", "Container did not become ready."); return; } // Check for an existing kernel we can reuse let kernelId = ""; let kernelReady = false; try { const listRes = await container.fetch(switchPort(new Request("http://jupyter.internal/api/kernels"), 8888)); if (listRes.ok) { const kernels = await listRes.json() as { id: string; execution_state?: string; name: string }[]; const match = kernels.find(k => k.name === kernelName); if (match) { kernelId = match.id; kernelReady = match.execution_state === "idle"; send({ status: "warming", phase: "kernel", message: `Reusing existing kernel ${kernelId} (state: ${match.execution_state ?? "unknown"})` }); console.log(`[jupyter] reusing kernel ${kernelId}`); } } } catch { /* best effort */ } if (!kernelId) { // No existing kernel -- start one send({ status: "warming", phase: "kernel", message: "Starting kernel..." }); try { const startRes = await container.fetch(switchPort(new Request("http://jupyter.internal/api/kernels", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ name: kernelName }), }), 8888)); if (!startRes.ok) { const detail = await startRes.text().catch(() => ""); fail("JupyterKernelStartFailed", `Kernel start returned ${startRes.status}: ${detail.slice(0, 200)}`); return; } const kernel = await startRes.json() as { id: string }; kernelId = kernel.id; send({ status: "warming", phase: "kernel", message: `Kernel ${kernelId} started, waiting for idle...` }); } catch (err) { fail("JupyterKernelError", `Kernel start failed: ${err instanceof Error ? err.message : String(err)}`); return; } } // Phase 3: ensure kernel is idle // In Cloudflare Containers, the Jupyter server's ZMQ ROUTER/DEALER // connection to the kernel doesn't complete until a WebSocket client // connects. We send a kernel_info_request directly via ZMQ to trigger // the kernel to transition from "starting" to "idle". if (!kernelReady) { await new Promise(r => setTimeout(r, 1000)); send({ status: "warming", phase: "kernel", message: "Kicking kernel into idle..." }); // Retry kick up to 3 times for (let attempt = 0; attempt < 3; attempt++) { try { const kickRes = await container.fetch(switchPort(new Request("http://jupyter.internal:8889/kick"), 8889)); const kickData = await kickRes.json() as Record; if (kickData.ok) { kernelReady = true; send({ status: "warming", phase: "kernel", message: "Kernel info received, kernel is idle" }); console.log(`[jupyter] kernel ${kernelId} kicked to idle`); break; } else { send({ status: "warming", phase: "kernel", message: `Kick attempt ${attempt + 1} failed: ${kickData.error || "unknown"}` }); } } catch (err) { send({ status: "warming", phase: "kernel", message: `Kick attempt ${attempt + 1} error: ${err instanceof Error ? err.message : String(err)}` }); } if (attempt < 2) await new Promise(r => setTimeout(r, 2000)); } } // Fallback: poll for idle state (in case the kick worked but the Jupyter // server hasn't updated yet) if (!kernelReady) { send({ status: "warming", phase: "kernel", message: "Polling for idle state..." }); const maxKernelWait = 20; for (let i = 0; i < maxKernelWait; i++) { try { const kRes = await container.fetch(switchPort(new Request(`http://jupyter.internal/api/kernels/${kernelId}`), 8888)); if (!kRes.ok) { const body = await kRes.text().catch(() => ""); fail("JupyterKernelDied", `Kernel returned ${kRes.status}: ${body.slice(0, 500)}`); return; } const kState = await kRes.json() as Record; if (kState.execution_state === "idle") { kernelReady = true; send({ status: "warming", phase: "kernel", message: `Kernel idle (${i + 1} checks)` }); console.log(`[jupyter] kernel ${kernelId} idle after ${i + 1} checks`); break; } send({ status: "warming", phase: "kernel", attempt: i + 1, state: kState.execution_state as string, message: `Kernel state: ${kState.execution_state}`, last_activity: kState.last_activity || null, connections: kState.connections ?? null }); } catch (err) { send({ status: "warming", phase: "kernel", attempt: i + 1, message: `Error: ${err instanceof Error ? err.message : String(err)}` }); } await new Promise(r => setTimeout(r, 500)); } } // Final fallback: check heartbeat if (!kernelReady) { send({ status: "warming", phase: "kernel", message: "Kernel stuck in starting, checking heartbeat..." }); try { const diagRes = await container.fetch(switchPort(new Request("http://jupyter.internal:8889/diag"), 8889)); const diag = await diagRes.json() as Record; if (diag.hb_ok) { send({ status: "warming", phase: "kernel", message: "Heartbeat OK -- kernel is alive, proceeding despite starting state" }); console.log(`[jupyter] kernel ${kernelId} heartbeat OK, proceeding without idle`); kernelReady = true; } } catch { /* best effort */ } } if (!kernelReady) { // Try to get container logs for debugging try { const logRes = await container.fetch(switchPort(new Request("http://jupyter.internal:8889/logs"), 8889)); const logs = await logRes.text(); send({ status: "warming", phase: "kernel", message: `Container logs (last 2000 chars):\n${logs.slice(-2000)}` }); } catch (e) { send({ status: "warming", phase: "kernel", message: `Failed to get logs: ${e}` }); } try { const psRes = await container.fetch(switchPort(new Request("http://jupyter.internal:8889/ps"), 8889)); const ps = await psRes.text(); send({ status: "warming", phase: "kernel", message: `Process list:\n${ps}` }); } catch (e) { send({ status: "warming", phase: "kernel", message: `Failed to get ps: ${e}` }); } fail("JupyterKernelTimeout", `Kernel ${kernelId} never reached idle state.`); return; } // Done: send the session config send({ status: "ready", enabled: true, sessionId: session.sessionId, token: session.token, expiresAt: session.expiresAt, baseUrl: `/jupyter/${session.sessionId}/`, wsUrl: jupyterSessionWsUrl(c.req.url, session.sessionId), kernelName, }); controller.close(); }, }); return new Response(stream, { headers: { "Content-Type": "application/x-ndjson", "X-Accel-Buffering": "no", "Cache-Control": "no-cache", }, }); }); app.all("/jupyter/:session/*", async (c) => { if (!jupyterContainersEnabled(env) || !env.JUPYTER_CONTAINER) { return c.json({ error: "JupyterBackendDisabled" }, 404); } const sessionId = c.req.param("session"); if (!(await validateJupyterSession(db, sessionId, c.req.raw))) { return c.json({ error: "Forbidden" }, 403); } const container = getContainer(env.JUPYTER_CONTAINER, "shared-jupyter"); return proxyJupyterRequest(c, container, sessionId); }); // Payment gate for space read endpoints. app.use("/xrpc/pub.oxa.space.listRecords", async (c, next) => { const spaceUri = c.req.query("spaceUri"); if (!spaceUri) return next(); const owner = await resolveOwnerPayment(db, spaceUri); if (!owner) return next(); // Check D1 for a cached on-chain payment const paid = await checkCachedPayment(db, spaceUri, owner.address); if (paid) return next(); const routeKey = `${c.req.method} ${c.req.path}` as `GET ${string}`; const routes = { [routeKey]: { accepts: [ { scheme: "exact", network: BASE_MAINNET, payTo: owner.address, price: owner.price, }, ], description: "Paid access to space documents", }, }; return paymentMiddleware(routes, server)(c, next); }); app.use("/xrpc/pub.oxa.space.getRecord", async (c, next) => { const spaceUri = c.req.query("spaceUri"); if (!spaceUri) return next(); const owner = await resolveOwnerPayment(db, spaceUri); if (!owner) return next(); // Check D1 for a cached on-chain payment const paid = await checkCachedPayment(db, spaceUri, owner.address); if (paid) return next(); const routeKey = `${c.req.method} ${c.req.path}` as `GET ${string}`; const routes = { [routeKey]: { accepts: [ { scheme: "exact", network: BASE_MAINNET, payTo: owner.address, price: owner.price, }, ], description: "Paid access to space document", }, }; return paymentMiddleware(routes, server)(c, next); }); // --- Space proxy routes --- // Browser sends X-Auth-DID header; worker dispatches internally via markInProcess. const SPACE = `${config.namespace}.space`; const INVITE = `${config.namespace}.invite`; /** Proxy a space XRPC call internally with in-process auth. */ async function proxySpaceCall( c: ProxyContext, xrpcPath: string, method: string, body?: unknown ): Promise { const did = c.req.header("X-Auth-DID"); if (!did) return new Response(JSON.stringify({ error: "AuthRequired", message: "X-Auth-DID header required" }), { status: 401, headers: { "content-type": "application/json" } }); const url = new URL(`/xrpc/${xrpcPath}`, "http://localhost"); const init: RequestInit = { method }; if (body !== undefined) { init.headers = { "Content-Type": "application/json" }; init.body = JSON.stringify(body); } if (method === "GET") { for (const [k, v] of new URL(c.req.url).searchParams) { url.searchParams.set(k, v); } } const req = markInProcess(new Request(url.toString(), init), did); return contrailWorker.fetch(req, c.env as unknown as Record); } /** Proxy a space XRPC call with an explicit DID (for payment bypass). */ async function proxySpaceCallAs( c: ProxyContext, xrpcPath: string, method: string, did: string, body?: unknown ): Promise { const url = new URL(`/xrpc/${xrpcPath}`, "http://localhost"); const init: RequestInit = { method }; if (body !== undefined) { init.headers = { "Content-Type": "application/json" }; init.body = JSON.stringify(body); } if (method === "GET") { for (const [k, v] of new URL(c.req.url).searchParams) { url.searchParams.set(k, v); } } const req = markInProcess(new Request(url.toString(), init), did); return contrailWorker.fetch(req, c.env as unknown as Record); } // --- Browse all spaces (no auth required) --- app.get("/api/spaces/browse", async (c) => { const viewerDid = c.req.header("X-Auth-DID") ?? null; const limit = Math.min(Number(c.req.query("limit") ?? 50), 200); // Ensure space_names table exists before LEFT JOIN await db.exec("CREATE TABLE IF NOT EXISTS space_names (spaceUri TEXT PRIMARY KEY, name TEXT NOT NULL)"); // Query all non-deleted spaces with LEFT JOIN on membership and display names const { results } = await db .prepare( `SELECT s.uri, s.owner_did, s.type, s.key, s.service_did, s.created_at, m.did AS member_did, n.name AS display_name FROM spaces s LEFT JOIN spaces_members m ON m.space_uri = s.uri AND m.did = ? LEFT JOIN space_names n ON n.spaceUri = s.uri WHERE s.deleted_at IS NULL ORDER BY s.created_at DESC LIMIT ?` ) .bind(viewerDid ?? "", limit) .all(); // Collect unique owner DIDs to batch-resolve payment configs const ownerDids = [...new Set(results.map((r: any) => r.owner_did as string))]; const paymentMap = new Map(); if (ownerDids.length > 0) { const placeholders = ownerDids.map(() => "?").join(","); const rows = await db .prepare( `SELECT did, record->>'address' as address, record->>'price' as price FROM records_paymentConfig WHERE did IN (${placeholders})` ) .bind(...ownerDids) .all(); for (const row of rows.results) { if (row.address) paymentMap.set(row.did, { address: row.address, price: row.price ?? "$0.01" }); } } const spaces = results.map((r: any) => { const isMember = r.owner_did === viewerDid || r.member_did != null; const payment = paymentMap.get(r.owner_did); return { uri: r.uri, ownerDid: r.owner_did, type: r.type, key: r.key, displayName: r.display_name || r.key, serviceDid: r.service_did, createdAt: r.created_at, viewerIsMember: isMember, requiresPayment: !isMember && !!payment, paymentConfig: !isMember && payment ? payment : undefined, }; }); return c.json({ spaces }); }); app.post("/api/spaces/create", async (c) => { const body = await c.req.json().catch(() => ({})); return proxySpaceCall(c, `${SPACE}.createSpace`, "POST", body); }); app.get("/api/spaces/list", async (c) => { return proxySpaceCall(c, `${SPACE}.listSpaces`, "GET"); }); app.get("/api/spaces/get", async (c) => { return proxySpaceCall(c, `${SPACE}.getSpace`, "GET"); }); app.post("/api/spaces/put-record", async (c) => { const body = await c.req.json().catch(() => ({})); return proxySpaceCall(c, `${SPACE}.putRecord`, "POST", body); }); app.get("/api/spaces/list-records", async (c) => { const spaceUri = c.req.query("spaceUri"); const res = await proxySpaceCall(c, `${SPACE}.listRecords`, "GET"); if (res.status === 403) { if (spaceUri) { const owner = await resolveOwnerPayment(db, spaceUri); if (owner) { return c.json({ error: "PaymentRequired", message: "This space requires payment for non-members", payTo: owner.address, network: BASE_MAINNET, price: owner.price, }, 402); } } } return res; }); app.get("/api/spaces/get-record", async (c) => { const spaceUri = c.req.query("spaceUri"); const res = await proxySpaceCall(c, `${SPACE}.getRecord`, "GET"); if (res.status === 403) { if (spaceUri) { const owner = await resolveOwnerPayment(db, spaceUri); if (owner) { return c.json({ error: "PaymentRequired", message: "This space requires payment for non-members", payTo: owner.address, network: BASE_MAINNET, price: owner.price, }, 402); } } } return res; }); app.post("/api/spaces/create-invite", async (c) => { const body = await c.req.json().catch(() => ({})); return proxySpaceCall(c, `${INVITE}.create`, "POST", body); }); app.post("/api/spaces/add-member", async (c) => { const body = await c.req.json().catch(() => ({})); return proxySpaceCall(c, `${SPACE}.addMember`, "POST", body); }); app.get("/api/spaces/members", async (c) => { return proxySpaceCall(c, `${SPACE}.listMembers`, "GET"); }); app.post("/api/spaces/remove-member", async (c) => { const body = await c.req.json().catch(() => ({})); return proxySpaceCall(c, `${SPACE}.removeMember`, "POST", body); }); app.post("/api/spaces/leave", async (c) => { const body = await c.req.json().catch(() => ({})); return proxySpaceCall(c, `${SPACE}.leaveSpace`, "POST", body); }); app.get("/api/spaces/invites", async (c) => { return proxySpaceCall(c, `${INVITE}.list`, "GET"); }); app.post("/api/spaces/revoke-invite", async (c) => { const body = await c.req.json().catch(() => ({})); return proxySpaceCall(c, `${INVITE}.revoke`, "POST", body); }); app.post("/api/spaces/redeem-invite", async (c) => { const body = await c.req.json().catch(() => ({})); return proxySpaceCall(c, `${INVITE}.redeem`, "POST", body); }); app.post("/api/spaces/delete-record", async (c) => { const body = await c.req.json().catch(() => ({})); return proxySpaceCall(c, `${SPACE}.deleteRecord`, "POST", body); }); // Rename space (owner-only, stored in D1 space_names table) app.post("/api/spaces/rename", async (c) => { const did = c.req.header("X-Auth-DID"); if (!did) return c.json({ error: "AuthRequired" }, 401); const body = await c.req.json().catch(() => ({})) as { spaceUri?: string; name?: string }; if (!body.spaceUri || !body.name) return c.json({ error: "spaceUri and name required" }, 400); // Verify ownership const space = await db .prepare("SELECT owner_did FROM spaces WHERE uri = ? AND deleted_at IS NULL") .bind(body.spaceUri) .first(); if (!space || space.owner_did !== did) return c.json({ error: "Forbidden" }, 403); await db.exec("CREATE TABLE IF NOT EXISTS space_names (spaceUri TEXT PRIMARY KEY, name TEXT NOT NULL)"); await db .prepare("INSERT OR REPLACE INTO space_names (spaceUri, name) VALUES (?, ?)") .bind(body.spaceUri, body.name) .run(); return c.json({ ok: true }); }); // Delete space (owner-only, soft delete via deleted_at) app.post("/api/spaces/delete", async (c) => { const did = c.req.header("X-Auth-DID"); if (!did) return c.json({ error: "AuthRequired" }, 401); const body = await c.req.json().catch(() => ({})) as { spaceUri?: string }; if (!body.spaceUri) return c.json({ error: "spaceUri required" }, 400); // Verify ownership const space = await db .prepare("SELECT owner_did FROM spaces WHERE uri = ? AND deleted_at IS NULL") .bind(body.spaceUri) .first(); if (!space || space.owner_did !== did) return c.json({ error: "Forbidden" }, 403); await db .prepare("UPDATE spaces SET deleted_at = strftime('%s','now') WHERE uri = ?") .bind(body.spaceUri) .run(); // Clean up display name await db .prepare("DELETE FROM space_names WHERE spaceUri = ?") .bind(body.spaceUri) .run() .catch(() => {}); return c.json({ ok: true }); }); // ENS resolution for payment UI (on-demand, not in browse hot path) app.get("/api/resolve-ens", async (c) => { const name = c.req.query("name"); if (!name) return c.json({ error: "name required" }, 400); const address = await resolveEnsOnBase(name); if (!address) return c.json({ error: "resolution failed" }, 404); return c.json({ address }); }); // Check on-chain USDC payment for QR/wallet flow app.get("/api/check-payment", async (c) => { if (c.env.MONETIZATION_ENABLED !== "true") return c.json({ error: "Monetization disabled" }, 404); const address = c.req.query("address"); const amount = c.req.query("amount"); const spaceUri = c.req.query("spaceUri"); const did = c.req.query("did"); if (!address || !amount || !spaceUri) { return c.json({ error: "address, amount, spaceUri required" }, 400); } // Init payments table await db.exec( "CREATE TABLE IF NOT EXISTS payments (spaceUri TEXT NOT NULL, address TEXT NOT NULL, txHash TEXT NOT NULL, amount TEXT NOT NULL, expiresAt INTEGER NOT NULL, PRIMARY KEY (spaceUri, address))" ); // Check D1 cache first const cached = await db .prepare("SELECT txHash, expiresAt FROM payments WHERE spaceUri = ? AND address = ?") .bind(spaceUri, address.toLowerCase()) .first(); if (cached && (cached.expiresAt as number) > Date.now() / 1000) { // Already paid — ensure membership if (did) { const ownerDid = ownerFromSpaceUri(spaceUri); if (ownerDid) { await proxySpaceCallAs(c, `${SPACE}.addMember`, "POST", ownerDid, { spaceUri, did }).catch(() => {}); } } return c.json({ paid: true, txHash: cached.txHash as string }); } // Poll Base RPC for USDC Transfer events to this address const paid = await checkOnChainPayment(address, amount); if (paid) { const expiresAt = Math.floor(Date.now() / 1000) + 3600; // 1 hour await db .prepare( "INSERT OR REPLACE INTO payments (spaceUri, address, txHash, amount, expiresAt) VALUES (?, ?, ?, ?, ?)" ) .bind(spaceUri, address.toLowerCase(), paid.txHash, amount, expiresAt) .run(); // Payment confirmed — add user as space member if (did) { const ownerDid = ownerFromSpaceUri(spaceUri); if (ownerDid) { await proxySpaceCallAs(c, `${SPACE}.addMember`, "POST", ownerDid, { spaceUri, did }).catch(() => {}); } } return c.json({ paid: true, txHash: paid.txHash }); } return c.json({ paid: false }); }); // Crawl endpoint: trigger immediate ingest app.post("/xrpc/com.atproto.sync.requestCrawl", async (c) => { let body: { hostname?: string; did?: string }; try { body = await c.req.json(); } catch { body = {}; } const did = body.did; const hostname = body.hostname; if (!did && !hostname) { return c.json({ error: "BadRequest", message: "Provide did or hostname" }, 400); } // Resolve hostname to DID if needed let targetDid = did ?? null; if (!targetDid && hostname) { targetDid = await resolveActor(db, hostname); if (!targetDid) { return c.json({ error: "NotFound", message: `Could not resolve handle: ${hostname}` }, 404); } } // Run ingest cycle and return await ensureContrailReady(db); await contrail.ingest({}, db); return c.json({ ok: true, did: targetDid }); }); // All routes pass through to contrail app.all("*", async (c) => { const response = await contrailWorker.fetch( c.req.raw, c.env as unknown as Record ); return response; }); return app; } export default { fetch(request: Request, env: Env): Response | Promise { app ??= buildApp(env); return app.fetch(request, env); }, scheduled(event: ScheduledEvent, env: Env, ctx: ExecutionContext) { return contrailWorker.scheduled( event, env as unknown as Record, ctx ); }, };