Spaces:
Running
Running
File size: 7,124 Bytes
6f5f15e | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 | import type { Hono } from 'hono';
import { bodyLimit } from 'hono/body-limit';
import * as z from 'zod';
import type * as T from '../../shared/api-types.js';
import type { AppConfig } from '../config.js';
import type { RoomRegistryApi } from '../contracts.js';
import { parseImageDataUrl } from '../state/camera.js';
import { resolveUser } from './userParam.js';
const IMAGE_BODY_LIMIT = 25 * 1024 * 1024; // 25 MiB
const FireEventSchema = z.object({
name: z.enum(['webcam.message', 'webcam.snapshot']),
message: z.string().max(4000).optional(),
snapshot: z.string().optional(),
frozen: z.boolean().optional(),
width: z.number().finite().int().positive().optional(),
height: z.number().finite().int().positive().optional(),
source: z.enum(['ui', 'auto', 'api']).optional(),
});
const EventsConfigPatchSchema = z.object({
pushEnabled: z.boolean().optional(),
pollEnabled: z.boolean().optional(),
heartbeatMs: z.number().finite().positive().optional(),
nextPollMs: z.number().finite().positive().optional(),
});
export interface ApiRoutesDeps {
rooms: RoomRegistryApi;
config: AppConfig;
version: string;
}
export function mountApiRoutes(app: Hono, deps: ApiRoutesDeps): void {
const largeBodyLimit = bodyLimit({
maxSize: IMAGE_BODY_LIMIT,
onError: (c) => c.json({ error: 'Payload too large' }, 413),
});
app.get('/api/health', (c) => {
return c.json({ status: 'ok', version: deps.version });
});
app.get('/api/config', (c) => {
const view: T.AppConfigView = {
version: deps.version,
mode: deps.config.mode,
mcpPath: '/mcp',
mcpHost: deps.config.mcpHost,
mcpHostConfigured: deps.config.mcpHostConfigured,
modernProtocol: '2026-07-28',
legacyFallback: true,
...(deps.config.mode === 'stdio' ? { stdioUser: deps.config.stdioUser } : {}),
};
return c.json(view);
});
app.get('/api/state', (c) => {
const user = resolveUser(c.req.raw);
return c.json(deps.rooms.get(user).snapshot());
});
app.get('/api/stats', (c) => {
return c.json(deps.rooms.stats());
});
app.post('/api/capture/:requestId', largeBodyLimit, async (c) => {
const user = resolveUser(c.req.raw);
const requestId = c.req.param('requestId');
let body: T.CaptureResultRequest;
try {
body = (await c.req.json()) as T.CaptureResultRequest;
} catch {
return c.json({ error: 'Invalid JSON body' }, 400);
}
const ok = deps.rooms.get(user).camera.resolveCapture(requestId, body);
if (!ok) {
return c.json({ error: 'Unknown or expired capture request' }, 404);
}
return c.json({ ok: true });
});
app.post('/api/tabs/:tabId/primary', (c) => {
const user = resolveUser(c.req.raw);
const tabId = c.req.param('tabId');
const ok = deps.rooms.get(user).camera.setPrimary(tabId);
if (!ok) {
return c.json({ error: 'Unknown tab' }, 404);
}
return c.json({ ok: true });
});
app.post('/api/tabs/:tabId/status', async (c) => {
const user = resolveUser(c.req.raw);
const tabId = c.req.param('tabId');
let body: Partial<T.CameraTabView>;
try {
body = (await c.req.json()) as Partial<T.CameraTabView>;
} catch {
return c.json({ error: 'Invalid JSON body' }, 400);
}
deps.rooms.get(user).camera.setStatus(tabId, body);
return c.json({ ok: true });
});
app.post('/api/events/fire', largeBodyLimit, async (c) => {
const user = resolveUser(c.req.raw);
let rawBody: unknown;
try {
rawBody = await c.req.json();
} catch {
return c.json({ error: 'Invalid JSON body' }, 400);
}
const parsedBody = FireEventSchema.safeParse(rawBody);
if (!parsedBody.success) {
return c.json({ error: 'Invalid event payload', details: parsedBody.error.issues }, 400);
}
const body: T.FireEventRequest = parsedBody.data;
let snapshotBytes: Buffer | undefined;
let snapshotMime: string | undefined;
if (body.snapshot) {
try {
const parsed = parseImageDataUrl(body.snapshot);
snapshotBytes = Buffer.from(parsed.base64, 'base64');
snapshotMime = parsed.mimeType;
} catch {
return c.json(
{ error: 'Invalid snapshot data URL (only image/jpeg, image/png, image/webp allowed)' },
400,
);
}
}
const result = deps.rooms.get(user).events.fire({
...body,
snapshotBytes,
snapshotMime,
});
return c.json(result);
});
app.get('/api/events/:eventId/snapshot', (c) => {
const user = resolveUser(c.req.raw);
const eventId = c.req.param('eventId');
const snap = deps.rooms.get(user).events.getSnapshot(eventId);
if (!snap) {
return c.json({ error: 'Snapshot not found' }, 404);
}
return new Response(new Uint8Array(snap.bytes), {
status: 200,
headers: {
'content-type': snap.mimeType,
'cache-control': 'private, max-age=300',
'x-content-type-options': 'nosniff',
'content-security-policy': 'sandbox',
},
});
});
app.patch('/api/events/config', async (c) => {
const user = resolveUser(c.req.raw);
let rawBody: unknown;
try {
rawBody = await c.req.json();
} catch {
return c.json({ error: 'Invalid JSON body' }, 400);
}
const parsedBody = EventsConfigPatchSchema.safeParse(rawBody);
if (!parsedBody.success) {
return c.json({ error: 'Invalid config patch', details: parsedBody.error.issues }, 400);
}
const updated = deps.rooms.get(user).events.setConfig(parsedBody.data);
return c.json(updated);
});
app.post('/api/push/:streamId/drop', (c) => {
const user = resolveUser(c.req.raw);
const streamId = c.req.param('streamId');
const ok = deps.rooms.get(user).events.drop(streamId);
if (!ok) {
return c.json({ error: 'Unknown push stream' }, 404);
}
return c.json({ ok: true });
});
app.post('/api/push/:streamId/revoke', async (c) => {
const user = resolveUser(c.req.raw);
const streamId = c.req.param('streamId');
let reason: string | undefined;
try {
const body = (await c.req.json()) as { reason?: string };
if (typeof body?.reason === 'string') {
reason = body.reason;
}
} catch {
// body is optional
}
const ok = deps.rooms.get(user).events.revokeStream(streamId, reason);
if (!ok) {
return c.json({ error: 'Unknown push stream' }, 404);
}
return c.json({ ok: true });
});
app.post('/api/pollers/:pollerId/revoke', (c) => {
const user = resolveUser(c.req.raw);
const pollerId = c.req.param('pollerId');
const ok = deps.rooms.get(user).events.revokePoller(pollerId);
if (!ok) {
return c.json({ error: 'Unknown poller' }, 404);
}
return c.json({ ok: true });
});
app.post('/api/activity/clear', (c) => {
const user = resolveUser(c.req.raw);
const room = deps.rooms.get(user);
const act = room.activity as { clear?: () => void };
if (typeof act.clear === 'function') {
act.clear();
}
return c.json({ ok: true });
});
}
|