// HTTP + WebSocket API. All UI↔backend IPC goes through here; no Deno Desktop // bindings exist anywhere (they leak into cross-origin tile frames). import { fromFileUrl, join } from '@std/path'; import mime from 'mime'; import { parseTile, readResource, readTileData, renameTile, writeTileData } from './tilefile.ts'; import { pickOpen, pickSave, revealInFolder } from './dialogs.ts'; import type { ZiranStore } from './store.ts'; import type { CollabProvider } from '../sync/provider.ts'; import type { AtSession } from './atsession.ts'; import { getProfiles, searchActors } from './atprofiles.ts'; const staticRoots = [ join(Deno.cwd(), 'static'), fromFileUrl(new URL('../../static/', import.meta.url)), ]; async function serveStatic(pathname: string): Promise { const rel = pathname === '/' ? '/index.html' : pathname; if (rel.includes('..')) return undefined; for (const root of staticRoots) { try { const bytes = await Deno.readFile(join(root, rel)); return new Response(bytes as BodyInit, { headers: { 'content-type': mime.getType(rel) ?? 'application/octet-stream' }, }); } catch { // next root } } return undefined; } /** Shown for a keyless load of the app root. Deno Desktop performs its own * initial load of the served address before our navigate() can land, and * that load carries no key: booting the real UI there would only produce a * window that 401s on everything. So this page is a skeleton of the real * base window — same banner, same regions — that the keeper loop replaces * with the keyed page, usually within seconds (see keepOnPage in * windows.ts). Only after a long stretch does it admit something is wrong. */ const splash = () => new Response( `Ziran
ziran

Recent

Models

`, { headers: { 'content-type': 'text/html; charset=utf-8', 'cache-control': 'no-store' } }, ); const json = (data: unknown, status = 200) => new Response(JSON.stringify(data), { status, headers: { 'content-type': 'application/json' } }); const err = (message: string, status = 400) => json({ error: message }, status); function iconResponse(tileLike: Parameters[0]): Response { const icon = (tileLike.manifest.model?.icons ?? tileLike.manifest.icons ?? [])[0]; if (!icon) return err('no icon', 404); const bytes = readResource(tileLike, icon.src); if (!bytes) return err('icon resource missing', 404); const entry = tileLike.manifest.resources[icon.src] as Record | undefined; const type = entry?.['content-type'] ?? mime.getType(icon.src) ?? 'application/octet-stream'; return new Response(bytes as BodyInit, { headers: { 'content-type': type, 'cache-control': 'no-cache' }, }); } /** Constant-time string comparison for the bearer token. */ function safeEqual(a: string, b: string): boolean { const enc = new TextEncoder(); const ab = enc.encode(a); const bb = enc.encode(b); if (ab.length !== bb.length || ab.length === 0) return false; let diff = 0; for (let i = 0; i < ab.length; i++) diff |= ab[i]! ^ bb[i]!; return diff === 0; } export function createHandler(store: ZiranStore, sync?: CollabProvider, at?: AtSession): (req: Request) => Promise { return async (req: Request): Promise => { const url = new URL(req.url); const { pathname } = url; // OAuth redirect landing — deliberately outside the /api key gate (the // browser arrives bare); integrity comes from the OAuth state parameter, // which the client library verifies. if (pathname === '/oauth/callback' && at) { try { const { handle, did } = await at.callback(url.searchParams); return new Response( `Signed in — Ziran
Z

You’re signed in as ${handle ?? did}

Head back to Ziran — this tab is done.

`, { headers: { 'content-type': 'text/html; charset=utf-8' } }, ); } catch (e) { return new Response(`sign-in failed: ${(e as Error).message}`, { status: 400 }); } } // The API is for the shell UI only, two gates deep: // 1. Bearer token, minted at launch and known only to pages the server // itself navigated to (any local process can reach 127.0.0.1 — the // token is what keeps them out). // 2. Origin check: tile frames run on *.localhost origins; their fetches // are intercepted by the tile service worker, but WebSocket (and any // SW-registration failure) would reach us directly. if (pathname.startsWith('/api/')) { const provided = req.headers.get('x-ziran-key') ?? url.searchParams.get('key') ?? ''; if (!safeEqual(provided, store.apiKey)) return err('unauthorized', 401); const origin = req.headers.get('origin'); if (origin && origin !== url.origin) return err('forbidden', 403); } if (pathname === '/api/events' && req.headers.get('upgrade') === 'websocket') { const { socket, response } = Deno.upgradeWebSocket(req); store.addSocket(socket, url.searchParams.get('win') ?? undefined); return response; } try { if (pathname === '/api/state') return json(store.snapshot()); if (pathname === '/api/pick') return json(await pickOpen()); if (pathname === '/api/pick-save') { return json(await pickSave(url.searchParams.get('name') ?? 'document.tile')); } // Opening a document also gives it a window (unless it already has one, // in which case that window is the answer). A record whose page has no // live socket and which is past its boot window is a zombie — its OS // window was closed and the disconnect grace hasn't fired yet — so it // is replaced rather than pointed at. const windowed = (info: Awaited>) => { const existing = store.windows.find((w) => w.panes.some((p) => p.tabs.includes(info.id))); if (existing) { const booting = Date.now() - existing.createdAt < 5000; if (store.hasLiveSockets(existing.id) || booting) { for (const p of existing.panes) if (p.tabs.includes(info.id)) p.active = info.id; store.broadcast(); // Surface the window rather than making the person hunt for it. const focused = store.focusOsWindow?.(existing.id) ?? false; return json({ doc: info, win: existing, url: store.windowUrl(existing.id), existing: true, focused }); } // Replace the zombie: create the new window first so the document // stays referenced while the stale record is dropped. const win = store.createWindow([info.id]); store.closeWindow(existing.id); return json({ doc: info, win, url: store.windowUrl(win.id), existing: false }); } const win = store.createWindow([info.id]); return json({ doc: info, win, url: store.windowUrl(win.id), existing: false }); }; if (pathname === '/api/docs/open' && req.method === 'POST') { const { path } = await req.json(); if (typeof path !== 'string' || !path) return err('path required'); return windowed(await store.openPath(path)); } if (pathname === '/api/docs/from-model' && req.method === 'POST') { const { modelId } = await req.json(); return windowed(await store.createFromModel(modelId)); } // A plain double-launch: the new process asks us to come forward, then // exits instead of booting a twin over the same data dir (see the // single-instance guard at the top of main.ts). if (pathname === '/api/raise' && req.method === 'POST') { store.focusOsWindow?.('main'); return json({ ok: true }); } // A ziran:// link or .tile file handed over by a second invocation of // the app (see the hand-off at the top of main.ts). Failures surface // IN the app — the person clicked something and deserves better than // nothing happening anywhere. if (pathname === '/api/deeplink' && req.method === 'POST') { const { arg } = await req.json(); if (typeof arg !== 'string' || !arg) return err('arg required'); try { const invite = arg.match(/^ziran:\/\/invite\/([0-9a-f]+)$/); if (invite) { if (!sync) return err('sync unavailable', 503); const { path } = await sync.accept(invite[1]!); return windowed(await store.openPath(path)); } // A space link (Spaces provider): adopt the doc straight from its ref. if (arg.startsWith('ziran://space?')) { if (!sync || !('adopt' in sync)) return err('space links need the Spaces provider', 503); const params = new URL(arg).searchParams; const ref = params.get('ref'); const docRkey = params.get('doc'); if (!ref || !docRkey) return err('malformed space link'); const { path } = await (sync as unknown as { adopt(space: string, docRkey: string): Promise<{ path: string }>; }).adopt(ref, docRkey); return windowed(await store.openPath(path)); } if (arg.endsWith('.tile')) { return windowed(await store.openPath(await Deno.realPath(arg))); } return err('unrecognized link'); } catch (e) { store.focusOsWindow?.('main'); store.broadcastEvent({ type: 'notice', message: (e as Error).message }); return err((e as Error).message); } } if (pathname === '/api/import' && req.method === 'POST') { const name = url.searchParams.get('name') ?? 'imported.tile'; const bytes = new Uint8Array(await req.arrayBuffer()); if (!bytes.length) return err('empty import'); return windowed(await store.importBytes(name, bytes)); } const winBounds = pathname.match(/^\/api\/windows\/([\w-]+)\/bounds$/); if (winBounds && req.method === 'POST') { const b = await req.json(); if ([b.x, b.y, b.w, b.h].every((n: unknown) => Number.isFinite(n))) { store.updateBounds(winBounds[1]!, { x: b.x, y: b.y, w: b.w, h: b.h }); } return json({ ok: true }); } const winOp = pathname.match(/^\/api\/windows\/([\w-]+)\/op$/); if (winOp && req.method === 'POST') { const winId = winOp[1]!; const body = await req.json(); switch (body.op) { case 'activate': store.activateTab(winId, body.paneId, body.docId); break; case 'close-tab': store.closeTab(winId, body.paneId, body.docId); break; case 'close': store.closeWindow(winId); break; case 'move-tab': store.moveTab(winId, body.paneId, body.docId, body.dstWinId, body.dstPaneId); break; case 'merge': store.mergeWindows(winId, body.dstWinId); break; case 'split-merge': store.splitMerge(winId, body.dstWinId, body.side === 'left' ? 'left' : 'right'); break; case 'split-within': store.splitWithin(winId); break; case 'tear-off': { const win = store.tearOff(winId, body.paneId, body.docId); return win ? json({ win, url: store.windowUrl(win.id) }) : err('cannot tear off'); } case 'ratio': store.setRatio(winId, Number(body.value)); break; default: return err(`unknown op ${body.op}`); } return json({ ok: true }); } const recentIcon = pathname.match(/^\/api\/recents\/([0-9a-f]+)\/icon$/); if (recentIcon) { const entry = store.recents.find((r) => r.id === recentIcon[1]); if (!entry) return err('unknown recent', 404); return iconResponse(await parseTile(entry.path, { verify: false })); } const recentDelete = pathname.match(/^\/api\/recents\/([0-9a-f]+)$/); if (recentDelete && req.method === 'DELETE') { await store.removeRecent(recentDelete[1]!); return json({ ok: true }); } if (pathname === '/api/reveal' && req.method === 'POST') { const { path } = await req.json(); if (typeof path !== 'string' || !path) return err('path required'); const known = store.recents.some((r) => r.path === path) || [...store.open.values()].some((d) => d.info.path === path); if (!known) return err('unknown path', 404); return json({ ok: await revealInFolder(path) }); } // Delete a document for real: withdrawn from its space first (when it // was shared from here), then closed everywhere and removed from disk. const docDelete = pathname.match(/^\/api\/docs\/([0-9a-f]+)$/); if (docDelete && req.method === 'DELETE') { const id = docDelete[1]!; if (sync && 'withdraw' in sync) { await (sync as unknown as { withdraw(id: string): Promise }).withdraw(id) .catch((e) => console.warn('could not withdraw from its space:', (e as Error).message)); } const gone = await store.deleteDoc(id); if (!gone) return err('unknown document', 404); return json({ ok: true }); } const docMatch = pathname.match(/^\/api\/docs\/([0-9a-f]+)\/(.+)$/); if (docMatch) { const [, id, rest] = docMatch; const doc = store.doc(id!); if (!doc) return err('unknown document', 404); if (rest === 'bundle.tile') { return new Response(doc.tile.bytes as BodyInit, { headers: { 'content-type': 'application/vnd.ipld.car', 'cache-control': 'no-cache' }, }); } if (rest === 'icon') return iconResponse(doc.tile); if (rest === 'rename' && req.method === 'POST') { const { name } = await req.json(); if (typeof name !== 'string' || !name.trim()) return err('name required'); await renameTile(doc.info.path, name); return json(await store.refresh(id!)); } if (rest === 'move' && req.method === 'POST') { const { dest } = await req.json(); if (typeof dest !== 'string' || !dest.trim()) return err('dest required'); return json(await store.moveDoc(id!, dest)); } const dataMatch = rest!.match(/^data\/([\w.-]+)$/); if (dataMatch) { const name = dataMatch[1]!; if (req.method === 'PUT') { await writeTileData(doc.info.path, name, new Uint8Array(await req.arrayBuffer())); await store.refresh(id!); // The tile's persisted state IS the sync snapshot (advances the // catch-up point and uploads for late joiners). await sync?.onLocalDataWrite(id!); return json({ ok: true }); } const bytes = await readTileData(doc.info.path, name); if (!bytes) return err('no data', 404); return new Response(bytes as BodyInit, { headers: { 'content-type': 'application/octet-stream' }, }); } // ——— collaboration (the UI bridge; tiles never reach these) ——— if (rest === 'sync/share' && req.method === 'POST') { if (!sync) return err('sync unavailable', 503); // Spaces: which space to go live into (or a new one's name). const body = await req.json().catch(() => ({})); await sync.share(id!, { space: typeof body.space === 'string' ? body.space : undefined, newSpaceName: typeof body.newSpaceName === 'string' ? body.newSpaceName : undefined, }); return json({ ok: true }); } if (rest === 'sync/publish' && req.method === 'POST') { if (!sync || !('publish' in sync)) return err('publishing is not available here', 503); await (sync as unknown as { publish(id: string): Promise }).publish(id!); return json({ ok: true }); } if (rest === 'sync/invite' && req.method === 'POST') { if (!sync) return err('sync unavailable', 503); const { did, role } = await req.json(); if (typeof did !== 'string' || !did.trim()) return err('their identity is required'); if (typeof role !== 'string' || !role.trim()) return err('a role is required'); const { invitation, link } = await sync.invite(id!, did.trim(), role); return json({ invitation, link }); } if (rest === 'sync/role' && req.method === 'POST') { if (!sync || !('setRole' in sync)) return err('role changes are not available here', 503); const { did, role } = await req.json(); if (typeof did !== 'string' || typeof role !== 'string') return err('did and role required'); await (sync as unknown as { setRole(id: string, did: string, role: string): Promise }) .setRole(id!, did, role); return json({ ok: true }); } if (rest === 'sync/remove' && req.method === 'POST') { if (!sync || !('removeMember' in sync)) return err('member removal is not available here', 503); const { did } = await req.json(); if (typeof did !== 'string') return err('did required'); await (sync as unknown as { removeMember(id: string, did: string): Promise }) .removeMember(id!, did); return json({ ok: true }); } if (rest === 'sync/attach' && req.method === 'POST') { if (!sync) return json({ shared: false }); const at = sync.attach(id!); return json(at ? { shared: true, ...at } : { shared: false }); } if (rest === 'sync/send' && req.method === 'POST') { if (!sync) return err('sync unavailable', 503); const { b64 } = await req.json(); return json({ seq: await sync.send(id!, String(b64 ?? '')) }); } if (rest === 'sync/ephemeral' && req.method === 'POST') { if (!sync) return err('sync unavailable', 503); const { b64 } = await req.json(); sync.ephemeral(id!, String(b64 ?? '')); return json({ ok: true }); } } if (pathname === '/api/sync/retry' && req.method === 'POST') { if (!sync) return err('sync unavailable', 503); sync.retryNow(); return json({ ok: true }); } // Instantiate a document discovered in a space (another member's — or // another of this account's devices'). Spaces provider only. if (pathname === '/api/sync/adopt' && req.method === 'POST') { if (!sync || !('adopt' in sync)) return err('adopting from a space is not available here', 503); const { space, docRkey } = await req.json(); if (typeof space !== 'string' || typeof docRkey !== 'string') return err('space and docRkey required'); const { path } = await (sync as unknown as { adopt(space: string, docRkey: string): Promise<{ path: string }>; }).adopt(space, docRkey); return windowed(await store.openPath(path)); } if (pathname === '/api/at/signin' && req.method === 'POST') { if (!at) return err('sign-in unavailable', 503); const { identifier } = await req.json(); if (typeof identifier !== 'string' || !identifier.trim()) return err('your handle is required'); return json({ url: await at.signIn(identifier) }); } if (pathname === '/api/at/avatar') { const avatar = at?.avatar; if (!avatar) return err('no avatar', 404); return new Response(avatar.bytes as BodyInit, { headers: { 'content-type': avatar.type, 'cache-control': 'no-cache' }, }); } if (pathname === '/api/at/signout' && req.method === 'POST') { if (!at) return err('sign-in unavailable', 503); await at.signOut(); return json({ ok: true }); } // Who these DIDs are as people (display name, handle, avatar URL) — // read from each person's own repo, cached server-side. if (pathname === '/api/at/profiles') { const dids = (url.searchParams.get('dids') ?? '').split(',').filter((d) => d.startsWith('did:')); if (!dids.length) return json({ profiles: [] }); return json({ profiles: await getProfiles(dids) }); } // Handle typeahead for the invite field. if (pathname === '/api/at/search') { return json({ actors: await searchActors(url.searchParams.get('q') ?? '') }); } // Tokens are hex (relay) or record rkeys (spaces TIDs). const inviteAct = pathname.match(/^\/api\/invitations\/([\w.~-]+)\/(accept|dismiss)$/); if (inviteAct && req.method === 'POST') { if (!sync) return err('sync unavailable', 503); const token = inviteAct[1]!; if (inviteAct[2] === 'dismiss') { sync.dismiss(token); return json({ ok: true }); } // Accept = download, verify, open — then a window like any other doc. const { path } = await sync.accept(token); return windowed(await store.openPath(path)); } const modelFrom = pathname.match(/^\/api\/models\/from\/([0-9a-f]+)$/); if (modelFrom && req.method === 'POST') { return json(await store.saveAsModel(modelFrom[1]!)); } const modelMatch = pathname.match(/^\/api\/models\/([^/]+)\/(icon)$/); if (modelMatch) { const model = store.modelById(decodeURIComponent(modelMatch[1]!)); if (!model) return err('unknown model', 404); return iconResponse(await parseTile(model.path, { verify: false })); } const modelDelete = pathname.match(/^\/api\/models\/([^/]+)$/); if (modelDelete && req.method === 'DELETE') { await store.removeModel(decodeURIComponent(modelDelete[1]!)); return json({ ok: true }); } if (pathname.startsWith('/api/')) return err('not found', 404); } catch (e) { return err((e as Error).message, 500); } // A bare load of the app root (no key at all) is the runtime's own // pre-navigate load: hold it with the splash rather than booting a UI // that cannot talk to the backend. A *wrong* key still gets the real UI, // which says plainly that the window is out of date. if (pathname === '/' && !url.searchParams.has('key')) return splash(); return (await serveStatic(pathname)) ?? new Response('not found', { status: 404 }); }; }