| 1 | /** |
| 2 | * Sandboxed Engine-brokered DSH webServer, connection, sessionTitle, and |
| 3 | * profileContext adapters. |
| 4 | * |
| 5 | * Integration hookup (2 lines, owned by `dsh-host` / integration wave): |
| 6 | * 1. In `crates/engine/extension-host/src/dsh/adapters.ts`: |
| 7 | * import { DSH_WEBSERVER_ADAPTERS } from './webserver.ts' |
| 8 | * // spread `...DSH_WEBSERVER_ADAPTERS` into `DSH_ADAPTERS` |
| 9 | * 2. In both `compatibility.json` copies (`crates/engine/extension-host/src/dsh/compatibility.json` |
| 10 | * and `crates/plugins/assets/dsh-compatibility.json`): |
| 11 | * add `"webServer"`, `"connection"`, `"sessionTitle"`, `"profileContext"` to |
| 12 | * BOTH `provided_services.dsh` AND `refused_services`. |
| 13 | */ |
| 14 | import { EventEmitter } from 'node:events' |
| 15 | import { isAbsolute, resolve } from 'node:path' |
| 16 | import { Service } from '@deepseek-ai/cordis' |
| 17 | import { |
| 18 | ErrorCode, |
| 19 | type PluginRouteDispatchParams, |
| 20 | type PluginRouteDispatchResult, |
| 21 | type PluginRouteHeaderWire, |
| 22 | } from '../protocol.ts' |
| 23 | import type { HostRoot, OwnerRecord } from '../root.ts' |
| 24 | import { RpcError } from '../rpc.ts' |
| 25 | import type { DshAdapter } from './adapters.ts' |
| 26 | |
| 27 | export const MAX_REQUEST_BODY_BYTES = 4 * 1024 * 1024 |
| 28 | export const MAX_RESPONSE_BODY_BYTES = 8 * 1024 * 1024 |
| 29 | export const MAX_ROUTE_DEADLINE_MS = 15_000 |
| 30 | const MAX_ROUTES_PER_OWNER = 256 |
| 31 | const MAX_SESSION_TITLES = 1024 |
| 32 | const ALLOWED_METHODS = new Set(['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS']) |
| 33 | |
| 34 | export interface NodeLikeRequest extends EventEmitter { |
| 35 | method: string |
| 36 | url: string |
| 37 | headers: Record<string, string> |
| 38 | httpVersion: string |
| 39 | socket: { remoteAddress: string } |
| 40 | connection: { remoteAddress: string } |
| 41 | readableEnded: boolean |
| 42 | destroyed: boolean |
| 43 | destroy(): this |
| 44 | [Symbol.asyncIterator](): AsyncGenerator<Buffer, void, unknown> |
| 45 | } |
| 46 | |
| 47 | export interface NodeLikeResponse extends EventEmitter { |
| 48 | statusCode: number |
| 49 | statusMessage: string |
| 50 | headersSent: boolean |
| 51 | writableEnded: boolean |
| 52 | finished: boolean |
| 53 | setHeader(name: string, value: string | number | readonly string[]): this |
| 54 | getHeader(name: string): string | string[] | undefined |
| 55 | getHeaders(): Record<string, string | string[]> |
| 56 | hasHeader(name: string): boolean |
| 57 | removeHeader(name: string): void |
| 58 | writeHead( |
| 59 | statusCode: number, |
| 60 | statusMessageOrHeaders?: string | Record<string, string | number | readonly string[]>, |
| 61 | maybeHeaders?: Record<string, string | number | readonly string[]>, |
| 62 | ): this |
| 63 | flushHeaders(): void |
| 64 | write(chunk: string | Uint8Array | Buffer, encoding?: BufferEncoding, cb?: () => void): boolean |
| 65 | end( |
| 66 | chunk?: string | Uint8Array | Buffer | (() => void), |
| 67 | encoding?: BufferEncoding | (() => void), |
| 68 | cb?: () => void, |
| 69 | ): this |
| 70 | } |
| 71 | |
| 72 | export type NodeRouteHandler = (req: NodeLikeRequest, res: NodeLikeResponse) => void | Promise<void> |
| 73 | |
| 74 | export interface WebRouteInput { |
| 75 | kind?: 'exact' | 'prefix' |
| 76 | path: string |
| 77 | method?: string |
| 78 | methods?: readonly string[] |
| 79 | handler: NodeRouteHandler |
| 80 | } |
| 81 | |
| 82 | export interface FetchRouteInput { |
| 83 | path: string |
| 84 | methods?: readonly string[] |
| 85 | requestBody?: string |
| 86 | fetch: (request: Request) => Response | Promise<Response> |
| 87 | } |
| 88 | |
| 89 | interface StoredRoute { |
| 90 | readonly id: number |
| 91 | readonly ownerToken: string |
| 92 | readonly kind: 'exact' | 'prefix' |
| 93 | readonly path: string |
| 94 | readonly methods: ReadonlySet<string> | undefined |
| 95 | readonly mode: 'node' | 'fetch' | 'rpc' |
| 96 | readonly nodeHandler?: NodeRouteHandler |
| 97 | readonly fetchHandler?: (request: Request) => Response | Promise<Response> |
| 98 | readonly rpcHandler?: (endpoint: string, payload: unknown) => unknown | Promise<unknown> |
| 99 | } |
| 100 | |
| 101 | let nextRouteId = 1 |
| 102 | const routesByOwner = new Map<string, StoredRoute[]>() |
| 103 | |
| 104 | function normalizePath(raw: unknown): string { |
| 105 | if (typeof raw !== 'string' || raw.length === 0 || raw.length > 1024 || /[\x00-\x1f\x7f]/.test(raw)) { |
| 106 | throw new RpcError(ErrorCode.InvalidParams, 'route path must be a non-empty single-line string') |
| 107 | } |
| 108 | const withSlash = raw.startsWith('/') ? raw : `/${raw}` |
| 109 | if (withSlash.length > 1 && withSlash.endsWith('/')) { |
| 110 | return withSlash.slice(0, -1) |
| 111 | } |
| 112 | return withSlash |
| 113 | } |
| 114 | |
| 115 | function normalizeMethods(method?: unknown, methods?: unknown): ReadonlySet<string> | undefined { |
| 116 | const list: string[] = [] |
| 117 | if (typeof method === 'string' && method.trim() !== '') { |
| 118 | list.push(method.trim().toUpperCase()) |
| 119 | } |
| 120 | if (Array.isArray(methods)) { |
| 121 | for (const item of methods) { |
| 122 | if (typeof item === 'string' && item.trim() !== '') { |
| 123 | list.push(item.trim().toUpperCase()) |
| 124 | } |
| 125 | } |
| 126 | } |
| 127 | return list.length > 0 ? new Set(list) : undefined |
| 128 | } |
| 129 | |
| 130 | function addOwnerRoute(owner: OwnerRecord, route: Omit<StoredRoute, 'id' | 'ownerToken'>): () => void { |
| 131 | const ownerToken = owner.ref.owner_token |
| 132 | let list = routesByOwner.get(ownerToken) |
| 133 | if (!list) { |
| 134 | list = [] |
| 135 | routesByOwner.set(ownerToken, list) |
| 136 | } |
| 137 | if (list.length >= MAX_ROUTES_PER_OWNER) { |
| 138 | throw new RpcError(ErrorCode.Refused, `owner exceeded ${MAX_ROUTES_PER_OWNER} registered routes`) |
| 139 | } |
| 140 | const stored: StoredRoute = { ...route, id: nextRouteId++, ownerToken } |
| 141 | list.push(stored) |
| 142 | let disposed = false |
| 143 | return () => { |
| 144 | if (disposed) return |
| 145 | disposed = true |
| 146 | const current = routesByOwner.get(ownerToken) |
| 147 | if (!current) return |
| 148 | const index = current.findIndex((entry) => entry.id === stored.id) |
| 149 | if (index >= 0) current.splice(index, 1) |
| 150 | if (current.length === 0) routesByOwner.delete(ownerToken) |
| 151 | } |
| 152 | } |
| 153 | |
| 154 | export function clearOwnerRoutes(ownerToken: string): void { |
| 155 | routesByOwner.delete(ownerToken) |
| 156 | } |
| 157 | |
| 158 | export function registeredRouteCount(ownerToken: string): number { |
| 159 | return routesByOwner.get(ownerToken)?.length ?? 0 |
| 160 | } |
| 161 | |
| 162 | function isLoopbackHostHeader(raw: string | undefined): boolean { |
| 163 | if (!raw) return true |
| 164 | const trimmed = raw.trim().toLowerCase() |
| 165 | if (trimmed === '') return true |
| 166 | let host = trimmed |
| 167 | if (host.startsWith('[')) { |
| 168 | const close = host.indexOf(']') |
| 169 | if (close < 0) return false |
| 170 | host = host.slice(1, close) |
| 171 | } else { |
| 172 | const colon = host.indexOf(':') |
| 173 | if (colon >= 0) host = host.slice(0, colon) |
| 174 | } |
| 175 | if (host === 'localhost' || host.endsWith('.localhost') || host === '::1') return true |
| 176 | const match = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(host) |
| 177 | if (!match) return false |
| 178 | const octets = match.slice(1).map(Number) |
| 179 | return octets[0] === 127 && octets.every((n) => n >= 0 && n <= 255) |
| 180 | } |
| 181 | |
| 182 | function checkRequestRejection(req: { headers?: Record<string, string | string[] | undefined> } | undefined): { status: number; message: string } | null { |
| 183 | if (!req || !req.headers) return null |
| 184 | const hostHeader = req.headers.host |
| 185 | const host = Array.isArray(hostHeader) ? hostHeader[0] : hostHeader |
| 186 | if (!isLoopbackHostHeader(host)) { |
| 187 | return { status: 403, message: 'forbidden: host is not loopback' } |
| 188 | } |
| 189 | const fetchSiteHeader = req.headers['sec-fetch-site'] |
| 190 | const fetchSite = Array.isArray(fetchSiteHeader) ? fetchSiteHeader[0] : fetchSiteHeader |
| 191 | if (typeof fetchSite === 'string' && fetchSite.toLowerCase() === 'cross-site') { |
| 192 | return { status: 403, message: 'forbidden: cross-site request rejected' } |
| 193 | } |
| 194 | return null |
| 195 | } |
| 196 | |
| 197 | function createNodeRequest( |
| 198 | method: string, |
| 199 | url: string, |
| 200 | headers: Record<string, string>, |
| 201 | body: Buffer, |
| 202 | ): NodeLikeRequest { |
| 203 | const emitter = new EventEmitter() as NodeLikeRequest |
| 204 | emitter.method = method |
| 205 | emitter.url = url |
| 206 | emitter.headers = { host: '127.0.0.1', ...headers } |
| 207 | emitter.httpVersion = '1.1' |
| 208 | emitter.socket = { remoteAddress: '127.0.0.1' } |
| 209 | emitter.connection = emitter.socket |
| 210 | emitter.readableEnded = false |
| 211 | emitter.destroyed = false |
| 212 | let streamed = false |
| 213 | |
| 214 | const emitBody = () => { |
| 215 | if (streamed || emitter.destroyed) return |
| 216 | streamed = true |
| 217 | queueMicrotask(() => { |
| 218 | if (emitter.destroyed) return |
| 219 | if (body.length > 0) emitter.emit('data', body) |
| 220 | emitter.readableEnded = true |
| 221 | emitter.emit('end') |
| 222 | }) |
| 223 | } |
| 224 | |
| 225 | const origOn = emitter.on.bind(emitter) |
| 226 | emitter.on = ((event: string | symbol, listener: (...args: any[]) => void) => { |
| 227 | origOn(event, listener) |
| 228 | if (event === 'data' || event === 'end') emitBody() |
| 229 | return emitter |
| 230 | }) as typeof emitter.on |
| 231 | |
| 232 | emitter.destroy = () => { |
| 233 | emitter.destroyed = true |
| 234 | return emitter |
| 235 | } |
| 236 | |
| 237 | emitter[Symbol.asyncIterator] = async function* () { |
| 238 | streamed = true |
| 239 | if (body.length > 0 && !emitter.destroyed) { |
| 240 | yield body |
| 241 | } |
| 242 | emitter.readableEnded = true |
| 243 | } |
| 244 | |
| 245 | return emitter |
| 246 | } |
| 247 | |
| 248 | function createNodeResponse(onFinish: () => void): { |
| 249 | res: NodeLikeResponse |
| 250 | result: () => { status: number; headers: PluginRouteHeaderWire[]; body: Buffer } |
| 251 | } { |
| 252 | const emitter = new EventEmitter() as NodeLikeResponse |
| 253 | const headerMap = new Map<string, string[]>() |
| 254 | const chunks: Buffer[] = [] |
| 255 | let totalBytes = 0 |
| 256 | |
| 257 | const setOneHeader = (name: string, value: string | number | readonly string[]) => { |
| 258 | const key = String(name).trim().toLowerCase() |
| 259 | if (!key) return |
| 260 | if (Array.isArray(value)) { |
| 261 | headerMap.set(key, value.map((v) => String(v))) |
| 262 | } else { |
| 263 | headerMap.set(key, [String(value)]) |
| 264 | } |
| 265 | } |
| 266 | |
| 267 | const appendChunk = (chunk: string | Uint8Array | Buffer, encoding?: BufferEncoding) => { |
| 268 | const buf = Buffer.isBuffer(chunk) |
| 269 | ? chunk |
| 270 | : typeof chunk === 'string' |
| 271 | ? Buffer.from(chunk, encoding ?? 'utf8') |
| 272 | : Buffer.from(chunk) |
| 273 | totalBytes += buf.length |
| 274 | if (totalBytes > MAX_RESPONSE_BODY_BYTES) { |
| 275 | throw new RpcError(ErrorCode.ExecutionFailed, `plugin route response exceeded ${MAX_RESPONSE_BODY_BYTES} bytes`) |
| 276 | } |
| 277 | if (buf.length > 0) chunks.push(buf) |
| 278 | } |
| 279 | |
| 280 | emitter.statusCode = 200 |
| 281 | emitter.statusMessage = 'OK' |
| 282 | emitter.headersSent = false |
| 283 | emitter.writableEnded = false |
| 284 | emitter.finished = false |
| 285 | |
| 286 | emitter.setHeader = (name, value) => { |
| 287 | setOneHeader(name, value) |
| 288 | return emitter |
| 289 | } |
| 290 | emitter.getHeader = (name) => { |
| 291 | const values = headerMap.get(String(name).toLowerCase()) |
| 292 | if (!values) return undefined |
| 293 | return values.length === 1 ? values[0] : [...values] |
| 294 | } |
| 295 | emitter.getHeaders = () => { |
| 296 | const out: Record<string, string | string[]> = {} |
| 297 | for (const [k, v] of headerMap) out[k] = v.length === 1 ? v[0] : [...v] |
| 298 | return out |
| 299 | } |
| 300 | emitter.hasHeader = (name) => headerMap.has(String(name).toLowerCase()) |
| 301 | emitter.removeHeader = (name) => { |
| 302 | headerMap.delete(String(name).toLowerCase()) |
| 303 | } |
| 304 | emitter.writeHead = (statusCode, statusMessageOrHeaders, maybeHeaders) => { |
| 305 | emitter.statusCode = statusCode |
| 306 | let headersObj: Record<string, string | number | readonly string[]> | undefined |
| 307 | if (typeof statusMessageOrHeaders === 'string') { |
| 308 | emitter.statusMessage = statusMessageOrHeaders |
| 309 | headersObj = maybeHeaders |
| 310 | } else { |
| 311 | headersObj = statusMessageOrHeaders |
| 312 | } |
| 313 | if (headersObj && typeof headersObj === 'object') { |
| 314 | for (const [k, v] of Object.entries(headersObj)) { |
| 315 | if (v !== undefined) setOneHeader(k, v) |
| 316 | } |
| 317 | } |
| 318 | emitter.headersSent = true |
| 319 | return emitter |
| 320 | } |
| 321 | emitter.flushHeaders = () => { |
| 322 | emitter.headersSent = true |
| 323 | } |
| 324 | emitter.write = (chunk, encoding, cb) => { |
| 325 | if (emitter.writableEnded) return false |
| 326 | emitter.headersSent = true |
| 327 | appendChunk(chunk, encoding) |
| 328 | cb?.() |
| 329 | return true |
| 330 | } |
| 331 | emitter.end = (chunk, encoding, cb) => { |
| 332 | if (emitter.writableEnded) return emitter |
| 333 | let callback = cb |
| 334 | if (typeof chunk === 'function') { |
| 335 | callback = chunk |
| 336 | } else if (chunk !== undefined) { |
| 337 | const enc = typeof encoding === 'function' ? undefined : encoding |
| 338 | if (typeof encoding === 'function') callback = encoding |
| 339 | appendChunk(chunk, enc) |
| 340 | } |
| 341 | emitter.headersSent = true |
| 342 | emitter.writableEnded = true |
| 343 | emitter.finished = true |
| 344 | callback?.() |
| 345 | emitter.emit('finish') |
| 346 | onFinish() |
| 347 | return emitter |
| 348 | } |
| 349 | |
| 350 | return { |
| 351 | res: emitter, |
| 352 | result: () => { |
| 353 | const headers: PluginRouteHeaderWire[] = [] |
| 354 | for (const [name, values] of headerMap) { |
| 355 | for (const value of values) { |
| 356 | headers.push({ name, value }) |
| 357 | } |
| 358 | } |
| 359 | return { |
| 360 | status: emitter.statusCode, |
| 361 | headers, |
| 362 | body: Buffer.concat(chunks, totalBytes), |
| 363 | } |
| 364 | }, |
| 365 | } |
| 366 | } |
| 367 | |
| 368 | function matchRoute(ownerToken: string, method: string, path: string): StoredRoute | undefined { |
| 369 | const routes = routesByOwner.get(ownerToken) |
| 370 | if (!routes || routes.length === 0) return undefined |
| 371 | const upperMethod = method.toUpperCase() |
| 372 | const methodMatches = (route: StoredRoute) => !route.methods || route.methods.has(upperMethod) |
| 373 | |
| 374 | for (const route of routes) { |
| 375 | if (route.kind === 'exact' && route.path === path && methodMatches(route)) { |
| 376 | return route |
| 377 | } |
| 378 | } |
| 379 | let bestPrefix: StoredRoute | undefined |
| 380 | for (const route of routes) { |
| 381 | if (route.kind !== 'prefix' || !methodMatches(route)) continue |
| 382 | const matches = |
| 383 | route.path === '/' |
| 384 | || path === route.path |
| 385 | || path.startsWith(`${route.path}/`) |
| 386 | if (matches && (!bestPrefix || route.path.length > bestPrefix.path.length)) { |
| 387 | bestPrefix = route |
| 388 | } |
| 389 | } |
| 390 | return bestPrefix |
| 391 | } |
| 392 | |
| 393 | async function readBoundedResponseBody(response: Response): Promise<Buffer> { |
| 394 | if (!response.body) return Buffer.alloc(0) |
| 395 | const reader = response.body.getReader() |
| 396 | const chunks: Buffer[] = [] |
| 397 | let total = 0 |
| 398 | try { |
| 399 | while (true) { |
| 400 | const { done, value } = await reader.read() |
| 401 | if (done) break |
| 402 | if (!value || value.byteLength === 0) continue |
| 403 | total += value.byteLength |
| 404 | if (total > MAX_RESPONSE_BODY_BYTES) { |
| 405 | await reader.cancel().catch(() => undefined) |
| 406 | throw new RpcError(ErrorCode.ExecutionFailed, `plugin route response exceeded ${MAX_RESPONSE_BODY_BYTES} bytes`) |
| 407 | } |
| 408 | chunks.push(Buffer.from(value.buffer, value.byteOffset, value.byteLength)) |
| 409 | } |
| 410 | return Buffer.concat(chunks, total) |
| 411 | } finally { |
| 412 | reader.releaseLock() |
| 413 | } |
| 414 | } |
| 415 | |
| 416 | async function runFetchRoute( |
| 417 | route: StoredRoute, |
| 418 | method: string, |
| 419 | urlPath: string, |
| 420 | headers: Record<string, string>, |
| 421 | body: Buffer, |
| 422 | signal: AbortSignal, |
| 423 | ): Promise<PluginRouteDispatchResult> { |
| 424 | const init: RequestInit = { |
| 425 | method, |
| 426 | headers, |
| 427 | signal, |
| 428 | ...(method !== 'GET' && method !== 'HEAD' && body.length > 0 ? { body: new Uint8Array(body) } : {}), |
| 429 | } |
| 430 | const request = new Request(`http://127.0.0.1${urlPath}`, init) |
| 431 | const response = await route.fetchHandler!(request) |
| 432 | const bytes = await readBoundedResponseBody(response) |
| 433 | const outHeaders: PluginRouteHeaderWire[] = [] |
| 434 | response.headers.forEach((value, name) => { |
| 435 | outHeaders.push({ name, value }) |
| 436 | }) |
| 437 | return { |
| 438 | matched: true, |
| 439 | status: response.status, |
| 440 | headers: outHeaders, |
| 441 | ...(bytes.length > 0 ? { body_base64: bytes.toString('base64') } : {}), |
| 442 | } |
| 443 | } |
| 444 | |
| 445 | async function runRpcRoute( |
| 446 | route: StoredRoute, |
| 447 | path: string, |
| 448 | body: Buffer, |
| 449 | ): Promise<PluginRouteDispatchResult> { |
| 450 | let parsed: any = {} |
| 451 | if (body.length > 0) { |
| 452 | try { |
| 453 | parsed = JSON.parse(body.toString('utf8')) |
| 454 | } catch { |
| 455 | const errBody = Buffer.from(JSON.stringify({ error: 'invalid JSON RPC payload' }), 'utf8') |
| 456 | return { |
| 457 | matched: true, |
| 458 | status: 400, |
| 459 | headers: [{ name: 'content-type', value: 'application/json; charset=utf-8' }], |
| 460 | body_base64: errBody.toString('base64'), |
| 461 | } |
| 462 | } |
| 463 | } |
| 464 | const suffix = path.length > route.path.length ? path.slice(route.path.length + 1) : '' |
| 465 | const endpoint = suffix || (typeof parsed?.endpoint === 'string' ? parsed.endpoint : '') |
| 466 | const payload = suffix ? parsed : (parsed?.payload ?? {}) |
| 467 | const result = await route.rpcHandler!(endpoint, payload) |
| 468 | const outBuf = Buffer.from(JSON.stringify(result === undefined ? null : result), 'utf8') |
| 469 | if (outBuf.length > MAX_RESPONSE_BODY_BYTES) { |
| 470 | throw new RpcError(ErrorCode.ExecutionFailed, `plugin RPC response exceeded ${MAX_RESPONSE_BODY_BYTES} bytes`) |
| 471 | } |
| 472 | return { |
| 473 | matched: true, |
| 474 | status: 200, |
| 475 | headers: [{ name: 'content-type', value: 'application/json; charset=utf-8' }], |
| 476 | body_base64: outBuf.toString('base64'), |
| 477 | } |
| 478 | } |
| 479 | |
| 480 | export async function dispatchPluginRoute( |
| 481 | host: Pick<HostRoot, 'owners'>, |
| 482 | params: PluginRouteDispatchParams, |
| 483 | signal: AbortSignal, |
| 484 | runWithOwner: <T>(owner: OwnerRecord, fn: () => Promise<T>) => Promise<T> = (_owner, fn) => fn(), |
| 485 | ): Promise<PluginRouteDispatchResult> { |
| 486 | const owner = host.owners.get(params.owner.owner_token) |
| 487 | if ( |
| 488 | !owner |
| 489 | || owner.state !== 'active' |
| 490 | || owner.disposing |
| 491 | || owner.ref.plugin_id !== params.owner.plugin_id |
| 492 | || owner.ref.generation !== params.owner.generation |
| 493 | ) { |
| 494 | throw new RpcError(ErrorCode.NotAvailable, `plugin owner ${params.owner.plugin_id} is not active`) |
| 495 | } |
| 496 | const method = params.method.toUpperCase() |
| 497 | if (!ALLOWED_METHODS.has(method)) { |
| 498 | throw new RpcError(ErrorCode.InvalidParams, `unsupported HTTP method ${params.method}`) |
| 499 | } |
| 500 | const normalizedPath = normalizePath(params.path) |
| 501 | if (params.body_base64 && params.body_base64.length > Math.ceil(MAX_REQUEST_BODY_BYTES / 3) * 4 + 4) { |
| 502 | throw new RpcError(ErrorCode.InvalidParams, `request body exceeds ${MAX_REQUEST_BODY_BYTES} bytes`) |
| 503 | } |
| 504 | const body = params.body_base64 ? Buffer.from(params.body_base64, 'base64') : Buffer.alloc(0) |
| 505 | if (body.length > MAX_REQUEST_BODY_BYTES) { |
| 506 | throw new RpcError(ErrorCode.InvalidParams, `request body exceeds ${MAX_REQUEST_BODY_BYTES} bytes`) |
| 507 | } |
| 508 | const route = matchRoute(owner.ref.owner_token, method, normalizedPath) |
| 509 | if (!route) { |
| 510 | return { matched: false, status: 404, headers: [] } |
| 511 | } |
| 512 | const headers: Record<string, string> = {} |
| 513 | for (const h of params.headers) { |
| 514 | const key = h.name.trim().toLowerCase() |
| 515 | if (!key) continue |
| 516 | headers[key] = key in headers ? `${headers[key]}, ${h.value}` : h.value |
| 517 | } |
| 518 | const urlPath = params.query ? `${normalizedPath}?${params.query}` : normalizedPath |
| 519 | const deadlineMs = Math.min(Math.max(params.deadline_ms || MAX_ROUTE_DEADLINE_MS, 100), MAX_ROUTE_DEADLINE_MS) |
| 520 | const timeoutController = new AbortController() |
| 521 | const timer = setTimeout(() => timeoutController.abort(), deadlineMs) |
| 522 | timer.unref?.() |
| 523 | const combinedSignal = AbortSignal.any([signal, timeoutController.signal]) |
| 524 | let onOuterAbort: (() => void) | undefined |
| 525 | |
| 526 | try { |
| 527 | const run = runWithOwner(owner, async () => { |
| 528 | if (route.mode === 'fetch') { |
| 529 | return runFetchRoute(route, method, urlPath, headers, body, combinedSignal) |
| 530 | } |
| 531 | if (route.mode === 'rpc') { |
| 532 | return runRpcRoute(route, normalizedPath, body) |
| 533 | } |
| 534 | let resolveDone!: () => void |
| 535 | const donePromise = new Promise<void>((resolve) => { |
| 536 | resolveDone = resolve |
| 537 | }) |
| 538 | const req = createNodeRequest(method, urlPath, headers, body) |
| 539 | const { res, result } = createNodeResponse(resolveDone) |
| 540 | const handlerReturn = route.nodeHandler!(req, res) |
| 541 | await Promise.resolve(handlerReturn) |
| 542 | if (!res.writableEnded) { |
| 543 | let onInnerAbort: (() => void) | undefined |
| 544 | try { |
| 545 | await Promise.race([ |
| 546 | donePromise, |
| 547 | new Promise<never>((_, reject) => { |
| 548 | onInnerAbort = () => reject(new RpcError(ErrorCode.Cancelled, 'plugin route timed out or cancelled')) |
| 549 | if (combinedSignal.aborted) onInnerAbort() |
| 550 | else combinedSignal.addEventListener('abort', onInnerAbort, { once: true }) |
| 551 | }), |
| 552 | ]) |
| 553 | } finally { |
| 554 | if (onInnerAbort) combinedSignal.removeEventListener('abort', onInnerAbort) |
| 555 | } |
| 556 | } |
| 557 | const out = result() |
| 558 | return { |
| 559 | matched: true, |
| 560 | status: out.status, |
| 561 | headers: out.headers, |
| 562 | ...(out.body.length > 0 ? { body_base64: out.body.toString('base64') } : {}), |
| 563 | } satisfies PluginRouteDispatchResult |
| 564 | }) |
| 565 | |
| 566 | const aborted = new Promise<never>((_, reject) => { |
| 567 | onOuterAbort = () => reject(new RpcError(ErrorCode.Cancelled, 'plugin route timed out or cancelled')) |
| 568 | if (combinedSignal.aborted) onOuterAbort() |
| 569 | else combinedSignal.addEventListener('abort', onOuterAbort, { once: true }) |
| 570 | }) |
| 571 | return await Promise.race([run, aborted]) |
| 572 | } finally { |
| 573 | if (onOuterAbort) combinedSignal.removeEventListener('abort', onOuterAbort) |
| 574 | clearTimeout(timer) |
| 575 | } |
| 576 | } |
| 577 | |
| 578 | export const webServerAdapter: DshAdapter = { |
| 579 | service: 'webServer', |
| 580 | define(host) { |
| 581 | class WebServerService extends Service { |
| 582 | readonly host = '127.0.0.1' |
| 583 | readonly port = 0 |
| 584 | readonly basePath = '' |
| 585 | |
| 586 | constructor(ctx: any) { |
| 587 | super(ctx, 'webServer') |
| 588 | } |
| 589 | |
| 590 | getOrigin(): string { |
| 591 | return 'http://127.0.0.1' |
| 592 | } |
| 593 | |
| 594 | register(route: WebRouteInput): () => void { |
| 595 | const owner = host.ownerOf(this.ctx) |
| 596 | if (!owner) throw new Error('webServer.register called outside a plugin owner') |
| 597 | if (!route || typeof route !== 'object' || typeof route.handler !== 'function') { |
| 598 | throw new RpcError(ErrorCode.InvalidParams, 'webServer.register requires { path, handler }') |
| 599 | } |
| 600 | const kind = route.kind === 'prefix' ? 'prefix' : 'exact' |
| 601 | const path = normalizePath(route.path) |
| 602 | const methods = normalizeMethods(route.method, route.methods) |
| 603 | return (this.ctx as any).effect( |
| 604 | () => addOwnerRoute(owner, { kind, path, methods, mode: 'node', nodeHandler: route.handler }), |
| 605 | `webServer.register(${kind}:${path})`, |
| 606 | ) |
| 607 | } |
| 608 | |
| 609 | registerRoute(route: WebRouteInput): () => void { |
| 610 | return this.register(route) |
| 611 | } |
| 612 | |
| 613 | route(path: string, handler: NodeRouteHandler): () => void { |
| 614 | return this.register({ kind: 'exact', path, handler }) |
| 615 | } |
| 616 | |
| 617 | get(path: string, handler: NodeRouteHandler): () => void { |
| 618 | return this.register({ kind: 'exact', path, method: 'GET', handler }) |
| 619 | } |
| 620 | |
| 621 | post(path: string, handler: NodeRouteHandler): () => void { |
| 622 | return this.register({ kind: 'exact', path, method: 'POST', handler }) |
| 623 | } |
| 624 | |
| 625 | put(path: string, handler: NodeRouteHandler): () => void { |
| 626 | return this.register({ kind: 'exact', path, method: 'PUT', handler }) |
| 627 | } |
| 628 | |
| 629 | patch(path: string, handler: NodeRouteHandler): () => void { |
| 630 | return this.register({ kind: 'exact', path, method: 'PATCH', handler }) |
| 631 | } |
| 632 | |
| 633 | delete(path: string, handler: NodeRouteHandler): () => void { |
| 634 | return this.register({ kind: 'exact', path, method: 'DELETE', handler }) |
| 635 | } |
| 636 | |
| 637 | use(pathOrHandler: string | NodeRouteHandler, maybeHandler?: NodeRouteHandler): () => void { |
| 638 | if (typeof pathOrHandler === 'function') { |
| 639 | return this.register({ kind: 'prefix', path: '/', handler: pathOrHandler }) |
| 640 | } |
| 641 | if (typeof maybeHandler !== 'function') { |
| 642 | throw new RpcError(ErrorCode.InvalidParams, 'webServer.use requires a handler function') |
| 643 | } |
| 644 | return this.register({ kind: 'prefix', path: pathOrHandler, handler: maybeHandler }) |
| 645 | } |
| 646 | |
| 647 | registerUpgrade(_spec?: unknown): () => void { |
| 648 | return () => {} |
| 649 | } |
| 650 | |
| 651 | tapIndex(_fn?: unknown): () => void { |
| 652 | return () => {} |
| 653 | } |
| 654 | } |
| 655 | Object.freeze(WebServerService.prototype) |
| 656 | return WebServerService |
| 657 | }, |
| 658 | } |
| 659 | |
| 660 | export const connectionAdapter: DshAdapter = { |
| 661 | service: 'connection', |
| 662 | define(host) { |
| 663 | class ConnectionService extends Service { |
| 664 | readonly isLoopback = true |
| 665 | readonly connected = true |
| 666 | readonly baseUrl = 'http://127.0.0.1' |
| 667 | |
| 668 | constructor(ctx: any) { |
| 669 | super(ctx, 'connection') |
| 670 | } |
| 671 | |
| 672 | requestRejection(req?: { headers?: Record<string, string | string[] | undefined> }) { |
| 673 | return checkRequestRejection(req) |
| 674 | } |
| 675 | |
| 676 | get fetch() { |
| 677 | const ctx = this.ctx |
| 678 | return { |
| 679 | register: (route: FetchRouteInput): () => void => { |
| 680 | const owner = host.ownerOf(ctx) |
| 681 | if (!owner) throw new Error('connection.fetch.register called outside a plugin owner') |
| 682 | if (!route || typeof route !== 'object' || typeof route.fetch !== 'function') { |
| 683 | throw new RpcError(ErrorCode.InvalidParams, 'connection.fetch.register requires { path, fetch }') |
| 684 | } |
| 685 | const path = normalizePath(route.path) |
| 686 | const methods = normalizeMethods(undefined, route.methods) |
| 687 | return (ctx as any).effect( |
| 688 | () => addOwnerRoute(owner, { kind: 'prefix', path, methods, mode: 'fetch', fetchHandler: route.fetch }), |
| 689 | `connection.fetch.register(${path})`, |
| 690 | ) |
| 691 | }, |
| 692 | } |
| 693 | } |
| 694 | |
| 695 | get rpc() { |
| 696 | const ctx = this.ctx |
| 697 | return { |
| 698 | handle: ( |
| 699 | channel: string, |
| 700 | handler: (endpoint: string, payload: unknown) => unknown | Promise<unknown>, |
| 701 | _options?: unknown, |
| 702 | ): () => void => { |
| 703 | const owner = host.ownerOf(ctx) |
| 704 | if (!owner) throw new Error('connection.rpc.handle called outside a plugin owner') |
| 705 | if (typeof handler !== 'function') { |
| 706 | throw new RpcError(ErrorCode.InvalidParams, 'connection.rpc.handle requires a handler function') |
| 707 | } |
| 708 | const path = normalizePath(channel) |
| 709 | return (ctx as any).effect( |
| 710 | () => addOwnerRoute(owner, { kind: 'prefix', path, methods: new Set(['POST']), mode: 'rpc', rpcHandler: handler }), |
| 711 | `connection.rpc.handle(${path})`, |
| 712 | ) |
| 713 | }, |
| 714 | } |
| 715 | } |
| 716 | |
| 717 | onReady(cb: () => void): () => void { |
| 718 | if (typeof cb === 'function') queueMicrotask(cb) |
| 719 | return () => {} |
| 720 | } |
| 721 | |
| 722 | onNotification(_cb: (...args: unknown[]) => void): () => void { |
| 723 | return () => {} |
| 724 | } |
| 725 | } |
| 726 | Object.freeze(ConnectionService.prototype) |
| 727 | return ConnectionService |
| 728 | }, |
| 729 | } |
| 730 | |
| 731 | function extractSessionId(session: unknown): string | undefined { |
| 732 | if (typeof session === 'string' && session.trim() !== '') return session.trim() |
| 733 | if (!session || typeof session !== 'object') return undefined |
| 734 | const obj = session as Record<string, unknown> |
| 735 | if (typeof obj.id === 'string' && obj.id.trim() !== '') return obj.id.trim() |
| 736 | if (typeof obj.sessionId === 'string' && obj.sessionId.trim() !== '') return obj.sessionId.trim() |
| 737 | const header = obj.header |
| 738 | if (header && typeof header === 'object' && typeof (header as Record<string, unknown>).id === 'string') { |
| 739 | const id = ((header as Record<string, unknown>).id as string).trim() |
| 740 | if (id !== '') return id |
| 741 | } |
| 742 | return undefined |
| 743 | } |
| 744 | |
| 745 | export const sessionTitleAdapter: DshAdapter = { |
| 746 | service: 'sessionTitle', |
| 747 | define(host) { |
| 748 | const titlesByOwner = new Map<string, Map<string, string>>() |
| 749 | const listenersByOwner = new Map<string, Set<(sessionId: string, title: string) => void>>() |
| 750 | |
| 751 | const requireOwnerToken = (ctx: unknown): string => { |
| 752 | const owner = host.ownerOf(ctx) |
| 753 | if (!owner || owner.state === 'disposed' || owner.disposing) { |
| 754 | throw new RpcError(ErrorCode.NotAvailable, 'sessionTitle requires an active plugin owner') |
| 755 | } |
| 756 | return owner.ref.owner_token |
| 757 | } |
| 758 | |
| 759 | class SessionTitleService extends Service { |
| 760 | constructor(ctx: any) { |
| 761 | super(ctx, 'sessionTitle') |
| 762 | } |
| 763 | |
| 764 | get(session: unknown): string | undefined { |
| 765 | const ownerToken = requireOwnerToken(this.ctx) |
| 766 | const id = extractSessionId(session) |
| 767 | return id ? titlesByOwner.get(ownerToken)?.get(id) : undefined |
| 768 | } |
| 769 | |
| 770 | rename(session: unknown, title: unknown): string { |
| 771 | const ownerToken = requireOwnerToken(this.ctx) |
| 772 | const id = extractSessionId(session) |
| 773 | if (!id) throw new RpcError(ErrorCode.InvalidParams, 'sessionTitle.rename requires a session or session id') |
| 774 | if (typeof title !== 'string') throw new RpcError(ErrorCode.InvalidParams, 'sessionTitle.rename requires a string title') |
| 775 | const cleaned = title.replace(/[\r\n\t]+/g, ' ').trim().slice(0, 256) |
| 776 | if (!cleaned) throw new RpcError(ErrorCode.InvalidParams, 'sessionTitle.rename requires a non-empty title') |
| 777 | let titles = titlesByOwner.get(ownerToken) |
| 778 | if (!titles) { |
| 779 | titles = new Map() |
| 780 | titlesByOwner.set(ownerToken, titles) |
| 781 | } |
| 782 | if (!titles.has(id) && titles.size >= MAX_SESSION_TITLES) { |
| 783 | const oldest = titles.keys().next().value |
| 784 | if (oldest !== undefined) titles.delete(oldest) |
| 785 | } |
| 786 | titles.set(id, cleaned) |
| 787 | const listeners = listenersByOwner.get(ownerToken) |
| 788 | if (listeners) { |
| 789 | for (const listener of listeners) { |
| 790 | try { |
| 791 | listener(id, cleaned) |
| 792 | } catch { |
| 793 | // Listener failures stay isolated. |
| 794 | } |
| 795 | } |
| 796 | } |
| 797 | return cleaned |
| 798 | } |
| 799 | |
| 800 | register(listener: (sessionId: string, title: string) => void): () => void { |
| 801 | const ownerToken = requireOwnerToken(this.ctx) |
| 802 | if (typeof listener !== 'function') { |
| 803 | throw new RpcError(ErrorCode.InvalidParams, 'sessionTitle.register requires a function') |
| 804 | } |
| 805 | return (this.ctx as any).effect(() => { |
| 806 | let listeners = listenersByOwner.get(ownerToken) |
| 807 | if (!listeners) { |
| 808 | listeners = new Set() |
| 809 | listenersByOwner.set(ownerToken, listeners) |
| 810 | } |
| 811 | listeners.add(listener) |
| 812 | return () => { |
| 813 | const current = listenersByOwner.get(ownerToken) |
| 814 | if (!current) return |
| 815 | current.delete(listener) |
| 816 | if (current.size === 0) listenersByOwner.delete(ownerToken) |
| 817 | } |
| 818 | }, 'sessionTitle.register') |
| 819 | } |
| 820 | } |
| 821 | Object.freeze(SessionTitleService.prototype) |
| 822 | return SessionTitleService |
| 823 | }, |
| 824 | } |
| 825 | |
| 826 | export const profileContextAdapter: DshAdapter = { |
| 827 | service: 'profileContext', |
| 828 | define(host) { |
| 829 | class ProfileContextService extends Service { |
| 830 | readonly name = 'codewhale' |
| 831 | readonly packageManager = 'npm' |
| 832 | |
| 833 | constructor(ctx: any) { |
| 834 | super(ctx, 'profileContext') |
| 835 | } |
| 836 | |
| 837 | get dir(): string { |
| 838 | const owner = host.ownerOf(this.ctx) |
| 839 | if (!owner?.dataDir || !isAbsolute(owner.dataDir)) { |
| 840 | throw new RpcError(ErrorCode.NotAvailable, 'profileContext requires an active owner with a scoped dataDir') |
| 841 | } |
| 842 | return resolve(owner.dataDir) |
| 843 | } |
| 844 | |
| 845 | get installAnchor(): string { |
| 846 | return this.dir |
| 847 | } |
| 848 | } |
| 849 | Object.freeze(ProfileContextService.prototype) |
| 850 | return ProfileContextService |
| 851 | }, |
| 852 | } |
| 853 | |
| 854 | export const DSH_WEBSERVER_ADAPTERS: readonly DshAdapter[] = [ |
| 855 | webServerAdapter, |
| 856 | connectionAdapter, |
| 857 | sessionTitleAdapter, |
| 858 | profileContextAdapter, |
| 859 | ] |
| 860 |