Open History to see the last commit
1import { randomUUID } from 'node:crypto';
2import { importSPKI, jwtVerify } from 'jose';
3import type { AgentTask } from '@glow/contracts';
4import { runTask } from './run.ts';
5
6let busy = false;
7export function assertSandboxEnvironment(env: NodeJS.ProcessEnv) {
8 const forbidden = ['DATABASE_URL', 'DATABASE_URL_UNPOOLED', 'NEON_API_KEY', 'NEON_AI_GATEWAY_TOKEN', 'AWS_SECRET_ACCESS_KEY', 'AWS_ACCESS_KEY_ID', 'GLOW_SIGNING_KEY', 'NEON_REALTIME_SECRET', 'BETTER_AUTH_SECRET'];
9 if (forbidden.some(name => env[name] && env[name] !== 'disabled')) throw new Error('The coding worker must not receive database, platform, or service credentials');
10}
11export async function handleInvocation(request: Request): Promise<Response> {
12 if (new URL(request.url).pathname === '/health') return Response.json({ ok: true, version: 'glow-1', busy });
13 if (request.method !== 'POST' || !new URL(request.url).pathname.endsWith('/invoke')) return new Response('Not found', { status: 404 });
14 if (!process.env.GLOW_VERIFY_KEY || !process.env.GLOW_API_URL) return new Response('Worker is not configured', { status: 503 });
15 assertSandboxEnvironment(process.env);
16 const token = request.headers.get('authorization')?.replace(/^Bearer /, '') ?? '';
17 try {
18 const key = await importSPKI(process.env.GLOW_VERIFY_KEY.replaceAll('\\n', '\n'), 'EdDSA');
19 await jwtVerify(token, key, { issuer: 'neon-glow', audience: 'dispatch', algorithms: ['EdDSA'] });
20 } catch { return new Response('Unauthorized', { status: 401 }); }
21 if (busy) return new Response('This worker is busy; retry through the durable queue', { status: 409 });
22 busy = true;
23 try {
24 const response = await fetch(`${process.env.GLOW_API_URL}/internal/activate`, { method: 'POST', headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json' }, body: JSON.stringify({ invocationId: randomUUID(), activationKey: randomUUID() }), redirect: 'error', signal: AbortSignal.timeout(15_000) });
25 if (!response.ok) return new Response('Activation rejected', { status: response.status });
26 await runTask(await response.json() as AgentTask, process.env.GLOW_API_URL);
27 return Response.json({ ok: true });
28 } catch (error) {
29 console.error('Coding invocation ended:', error instanceof Error ? error.name : 'error');
30 return Response.json({ error: 'The change did not complete' }, { status: 500 });
31 } finally { busy = false; }
32}