| 81 | CLOUD_AGENT_REPORT_QUEUE: Queue<CloudAgentQueueReport>; |
| 82 | USER_KILO_FACADE: DurableObjectNamespace<UserKiloFacade>; |
| 83 | SANDBOX_CONTROL: Env['SANDBOX_CONTROL']; |
| 84 | SANDBOX_SESSION: Env['SANDBOX_SESSION']; |
| 85 | NEXTAUTH_SECRET: Env['NEXTAUTH_SECRET']; |
| 86 | }; |
| 87 | |
| 88 | function routeToUserKiloFacade(request: Request, env: TestEnv, userId: string): Promise<Response> { |
| 89 | const facade = env.USER_KILO_FACADE.get(env.USER_KILO_FACADE.idFromName(userId)); |
| 90 | const headers = new Headers(request.headers); |
| 91 | headers.set(KILO_FACADE_USER_ID_HEADER, userId); |
| 92 | headers.set(KILO_FACADE_AUTH_TOKEN_HEADER, 'test-token'); |
| 93 | return facade.fetch(new Request(request, { headers })); |
| 94 | } |
| 95 | |
| 96 | function createTerminalUpgradeRequest( |
| 97 | request: Request, |
| 98 | role: 'browser' | 'wrapper', |
| 99 | ptyId: string |
| 100 | ): Request { |
| 101 | const url = new URL(request.url); |
| 102 | url.pathname = `/terminal/${role}`; |
| 103 | url.search = ''; |
| 104 | url.searchParams.set('ptyId', ptyId); |
| 105 | const headers = new Headers({ Upgrade: 'websocket' }); |
| 106 | if (role === 'wrapper') { |
| 107 | const authorization = request.headers.get('Authorization'); |
| 108 | if (authorization !== null) headers.set('Authorization', authorization); |
| 109 | } |
| 110 | return new Request(url, { method: 'GET', headers }); |
| 111 | } |
| 112 | |
| 113 | function isTerminalRouteIdentity(ownerId: string, sessionId: string, ptyId: string): boolean { |
| 114 | return ( |
| 115 | ownerId.length > 0 && |
| 116 | sessionId.startsWith('workspace_') && |
| 117 | SESSION_ID_RE.test(sessionId) && |
| 118 | terminalPtyIdSchema.safeParse(ptyId).success |
| 119 | ); |
| 120 | } |
| 121 | |
| 122 | export default { |
| 123 | async fetch(request: Request, env: TestEnv): Promise<Response> { |
| 124 | const url = new URL(request.url); |
| 125 | |
| 126 | if (url.pathname.startsWith('/sandbox-control/')) { |
| 127 | const sandboxId = decodeURIComponent(url.pathname.slice('/sandbox-control/'.length)); |
| 128 | return admitSandboxWrapperUpgrade(request, env, sandboxId); |
| 129 | } |
| 130 | |
| 131 | if (url.pathname.startsWith('/sandbox-control-v2/')) { |
| 132 | const upgradeHeader = request.headers.get('Upgrade'); |
| 133 | if (upgradeHeader?.toLowerCase() !== 'websocket') { |
| 134 | return new Response('Expected WebSocket upgrade', { status: 426 }); |
| 135 | } |
| 136 | const sandboxId = decodeURIComponent(url.pathname.slice('/sandbox-control-v2/'.length)); |
| 137 | if (!sandboxId || sandboxId.includes('/') || !isSandboxControlId(sandboxId)) { |
| 138 | return new Response('Invalid sandboxId', { status: 400 }); |
| 139 | } |
| 140 | return env.SANDBOX_CONTROL.getByName(sandboxId).fetch(request); |