| 1 | import test, { before, after } from 'node:test' |
| 2 | import assert from 'node:assert/strict' |
| 3 | import { mkdtempSync, rmSync } from 'node:fs' |
| 4 | import { tmpdir } from 'node:os' |
| 5 | import { dirname, join, resolve } from 'node:path' |
| 6 | import { fileURLToPath, pathToFileURL } from 'node:url' |
| 7 | import { build } from 'esbuild' |
| 8 | import { Context } from '@deepseek-ai/cordis' |
| 9 | |
| 10 | const here = dirname(fileURLToPath(import.meta.url)) |
| 11 | const OWNER = Symbol.for('codewhale.extension-host.owner') |
| 12 | |
| 13 | let tmpDir |
| 14 | let DSH_WEBSERVER_ADAPTERS |
| 15 | let MAX_REQUEST_BODY_BYTES |
| 16 | let MAX_RESPONSE_BODY_BYTES |
| 17 | let clearOwnerRoutes |
| 18 | let dispatchPluginRoute |
| 19 | let registeredRouteCount |
| 20 | |
| 21 | before(async () => { |
| 22 | tmpDir = mkdtempSync(join(here, '..', 'node_modules', '.cw-webserver-')) |
| 23 | const outfile = join(tmpDir, 'webserver.mjs') |
| 24 | await build({ |
| 25 | entryPoints: [join(here, '../src/dsh/webserver.ts')], |
| 26 | outfile, |
| 27 | bundle: true, |
| 28 | platform: 'node', |
| 29 | format: 'esm', |
| 30 | packages: 'external', |
| 31 | absWorkingDir: join(here, '..'), |
| 32 | logLevel: 'silent', |
| 33 | }) |
| 34 | const mod = await import(pathToFileURL(outfile).href) |
| 35 | ;({ |
| 36 | DSH_WEBSERVER_ADAPTERS, |
| 37 | MAX_REQUEST_BODY_BYTES, |
| 38 | MAX_RESPONSE_BODY_BYTES, |
| 39 | clearOwnerRoutes, |
| 40 | dispatchPluginRoute, |
| 41 | registeredRouteCount, |
| 42 | } = mod) |
| 43 | }) |
| 44 | |
| 45 | after(() => { |
| 46 | if (tmpDir) rmSync(tmpDir, { recursive: true, force: true }) |
| 47 | }) |
| 48 | |
| 49 | async function createHarness() { |
| 50 | const root = new Context() |
| 51 | const owners = new Map() |
| 52 | const adapterHost = { |
| 53 | tier: 'plugin', |
| 54 | rpc: {}, |
| 55 | ownerOf: (ctx) => ctx[OWNER], |
| 56 | liveInvocation: () => undefined, |
| 57 | brokerTicket: () => { throw new Error('unused') }, |
| 58 | broker: async () => { throw new Error('unused') }, |
| 59 | log: () => {}, |
| 60 | } |
| 61 | for (const adapter of DSH_WEBSERVER_ADAPTERS) { |
| 62 | root.plugin(adapter.define(adapterHost)) |
| 63 | } |
| 64 | await new Promise((resolve) => setTimeout(resolve, 0)) |
| 65 | |
| 66 | function makeOwner(pluginId, token, dataDir) { |
| 67 | const owner = { |
| 68 | ref: { plugin_id: pluginId, owner_token: token, generation: 1 }, |
| 69 | pluginName: pluginId, |
| 70 | fibers: [], |
| 71 | pendingRegistrations: new Set(), |
| 72 | refusals: [], |
| 73 | tools: new Map(), |
| 74 | commands: new Map(), |
| 75 | shellHooks: new Map(), |
| 76 | hooks: new Map(), |
| 77 | promptSections: new Map(), |
| 78 | skillRoots: new Map(), |
| 79 | avatarPacks: new Map(), |
| 80 | mcpDefinitions: new Map(), |
| 81 | entries: new Set(), |
| 82 | dataDir, |
| 83 | state: 'active', |
| 84 | } |
| 85 | owners.set(token, owner) |
| 86 | const ctx = root.extend({ [OWNER]: owner }) |
| 87 | return { owner, ctx } |
| 88 | } |
| 89 | |
| 90 | return { root, owners, makeOwner } |
| 91 | } |
| 92 | |
| 93 | test('webServer exact and prefix routes handle GET/POST JSON round-trip and query strings', async () => { |
| 94 | const { owners, makeOwner } = await createHarness() |
| 95 | const { owner, ctx } = makeOwner('plugin-a', 'tok-a', join(tmpdir(), 'plugin-a')) |
| 96 | try { |
| 97 | const disposeGet = ctx.webServer.register({ |
| 98 | kind: 'exact', |
| 99 | path: '/api/ping', |
| 100 | handler: (req, res) => { |
| 101 | const url = new URL(req.url, 'http://127.0.0.1') |
| 102 | res.writeHead(200, { 'content-type': 'application/json', 'x-echo': req.headers['x-custom'] ?? '' }) |
| 103 | res.end(JSON.stringify({ ok: true, q: url.searchParams.get('name'), remote: req.socket.remoteAddress })) |
| 104 | }, |
| 105 | }) |
| 106 | const disposePost = ctx.webServer.register({ |
| 107 | kind: 'prefix', |
| 108 | path: '/api/items', |
| 109 | handler: async (req, res) => { |
| 110 | const chunks = [] |
| 111 | for await (const chunk of req) chunks.push(chunk) |
| 112 | const parsed = JSON.parse(Buffer.concat(chunks).toString('utf8')) |
| 113 | res.setHeader('content-type', 'application/json') |
| 114 | res.statusCode = 201 |
| 115 | res.end(JSON.stringify({ path: req.url, received: parsed })) |
| 116 | }, |
| 117 | }) |
| 118 | |
| 119 | const getRes = await dispatchPluginRoute( |
| 120 | { owners }, |
| 121 | { |
| 122 | owner: owner.ref, |
| 123 | method: 'GET', |
| 124 | path: '/api/ping', |
| 125 | query: 'name=whale', |
| 126 | headers: [{ name: 'x-custom', value: 'hello' }], |
| 127 | deadline_ms: 5000, |
| 128 | }, |
| 129 | new AbortController().signal, |
| 130 | ) |
| 131 | assert.equal(getRes.matched, true) |
| 132 | assert.equal(getRes.status, 200) |
| 133 | assert.deepEqual(JSON.parse(Buffer.from(getRes.body_base64, 'base64').toString('utf8')), { |
| 134 | ok: true, |
| 135 | q: 'whale', |
| 136 | remote: '127.0.0.1', |
| 137 | }) |
| 138 | assert.ok(getRes.headers.some((h) => h.name === 'x-echo' && h.value === 'hello')) |
| 139 | |
| 140 | const payload = Buffer.from(JSON.stringify({ title: 'Ship 0.10.5' }), 'utf8').toString('base64') |
| 141 | const postRes = await dispatchPluginRoute( |
| 142 | { owners }, |
| 143 | { |
| 144 | owner: owner.ref, |
| 145 | method: 'POST', |
| 146 | path: '/api/items/42', |
| 147 | headers: [{ name: 'content-type', value: 'application/json' }], |
| 148 | body_base64: payload, |
| 149 | deadline_ms: 5000, |
| 150 | }, |
| 151 | new AbortController().signal, |
| 152 | ) |
| 153 | assert.equal(postRes.matched, true) |
| 154 | assert.equal(postRes.status, 201) |
| 155 | assert.deepEqual(JSON.parse(Buffer.from(postRes.body_base64, 'base64').toString('utf8')), { |
| 156 | path: '/api/items/42', |
| 157 | received: { title: 'Ship 0.10.5' }, |
| 158 | }) |
| 159 | |
| 160 | const miss = await dispatchPluginRoute( |
| 161 | { owners }, |
| 162 | { owner: owner.ref, method: 'GET', path: '/api/unknown', headers: [], deadline_ms: 5000 }, |
| 163 | new AbortController().signal, |
| 164 | ) |
| 165 | assert.equal(miss.matched, false) |
| 166 | assert.equal(miss.status, 404) |
| 167 | |
| 168 | disposeGet() |
| 169 | disposePost() |
| 170 | assert.equal(registeredRouteCount('tok-a'), 0) |
| 171 | } finally { |
| 172 | clearOwnerRoutes('tok-a') |
| 173 | } |
| 174 | }) |
| 175 | |
| 176 | test('webServer enforces strict owner isolation between plugins', async () => { |
| 177 | const { owners, makeOwner } = await createHarness() |
| 178 | const a = makeOwner('plugin-a', 'tok-iso-a', join(tmpdir(), 'a')) |
| 179 | const b = makeOwner('plugin-b', 'tok-iso-b', join(tmpdir(), 'b')) |
| 180 | try { |
| 181 | a.ctx.webServer.get('/secret', (_req, res) => { |
| 182 | res.end('from-a') |
| 183 | }) |
| 184 | |
| 185 | const fromB = await dispatchPluginRoute( |
| 186 | { owners }, |
| 187 | { owner: b.owner.ref, method: 'GET', path: '/secret', headers: [], deadline_ms: 5000 }, |
| 188 | new AbortController().signal, |
| 189 | ) |
| 190 | assert.equal(fromB.matched, false) |
| 191 | |
| 192 | const fromA = await dispatchPluginRoute( |
| 193 | { owners }, |
| 194 | { owner: a.owner.ref, method: 'GET', path: '/secret', headers: [], deadline_ms: 5000 }, |
| 195 | new AbortController().signal, |
| 196 | ) |
| 197 | assert.equal(fromA.matched, true) |
| 198 | assert.equal(Buffer.from(fromA.body_base64, 'base64').toString('utf8'), 'from-a') |
| 199 | } finally { |
| 200 | clearOwnerRoutes('tok-iso-a') |
| 201 | clearOwnerRoutes('tok-iso-b') |
| 202 | } |
| 203 | }) |
| 204 | |
| 205 | test('webServer enforces request and response body size caps', async () => { |
| 206 | const { owners, makeOwner } = await createHarness() |
| 207 | const { owner, ctx } = makeOwner('plugin-cap', 'tok-cap', join(tmpdir(), 'cap')) |
| 208 | try { |
| 209 | ctx.webServer.post('/echo', (_req, res) => { |
| 210 | res.end('ok') |
| 211 | }) |
| 212 | ctx.webServer.get('/huge', (_req, res) => { |
| 213 | res.write(Buffer.alloc(MAX_RESPONSE_BODY_BYTES + 1)) |
| 214 | res.end() |
| 215 | }) |
| 216 | |
| 217 | const oversizedReq = Buffer.alloc(MAX_REQUEST_BODY_BYTES + 1).toString('base64') |
| 218 | await assert.rejects( |
| 219 | () => dispatchPluginRoute( |
| 220 | { owners }, |
| 221 | { owner: owner.ref, method: 'POST', path: '/echo', headers: [], body_base64: oversizedReq, deadline_ms: 5000 }, |
| 222 | new AbortController().signal, |
| 223 | ), |
| 224 | /request body exceeds/, |
| 225 | ) |
| 226 | |
| 227 | await assert.rejects( |
| 228 | () => dispatchPluginRoute( |
| 229 | { owners }, |
| 230 | { owner: owner.ref, method: 'GET', path: '/huge', headers: [], deadline_ms: 5000 }, |
| 231 | new AbortController().signal, |
| 232 | ), |
| 233 | /response exceeded/, |
| 234 | ) |
| 235 | } finally { |
| 236 | clearOwnerRoutes('tok-cap') |
| 237 | } |
| 238 | }) |
| 239 | |
| 240 | test('connection.fetch, connection.rpc, requestRejection, sessionTitle, and profileContext work', async () => { |
| 241 | const { owners, makeOwner } = await createHarness() |
| 242 | const extrasDir = resolve(join(tmpdir(), 'plugin-extras')) |
| 243 | const { owner, ctx } = makeOwner('plugin-extras', 'tok-extras', extrasDir) |
| 244 | try { |
| 245 | assert.equal(ctx.connection.isLoopback, true) |
| 246 | assert.equal(ctx.connection.requestRejection({ headers: { host: '127.0.0.1:4319' } }), null) |
| 247 | assert.equal(ctx.connection.requestRejection({ headers: { host: 'evil.example' } })?.status, 403) |
| 248 | assert.equal(ctx.connection.requestRejection({ headers: { host: 'localhost', 'sec-fetch-site': 'cross-site' } })?.status, 403) |
| 249 | |
| 250 | ctx.connection.fetch.register({ |
| 251 | path: '/api/skills', |
| 252 | methods: ['GET'], |
| 253 | fetch: async (request) => new Response(JSON.stringify({ url: request.url }), { |
| 254 | status: 200, |
| 255 | headers: { 'content-type': 'application/json' }, |
| 256 | }), |
| 257 | }) |
| 258 | const fetchRes = await dispatchPluginRoute( |
| 259 | { owners }, |
| 260 | { owner: owner.ref, method: 'GET', path: '/api/skills', query: 'q=rust', headers: [], deadline_ms: 5000 }, |
| 261 | new AbortController().signal, |
| 262 | ) |
| 263 | assert.equal(fetchRes.matched, true) |
| 264 | assert.equal(fetchRes.status, 200) |
| 265 | assert.equal(JSON.parse(Buffer.from(fetchRes.body_base64, 'base64').toString('utf8')).url, 'http://127.0.0.1/api/skills?q=rust') |
| 266 | |
| 267 | ctx.connection.rpc.handle('/arcv', (endpoint, payload) => ({ endpoint, count: payload.n + 1 })) |
| 268 | const rpcRes = await dispatchPluginRoute( |
| 269 | { owners }, |
| 270 | { |
| 271 | owner: owner.ref, |
| 272 | method: 'POST', |
| 273 | path: '/arcv', |
| 274 | headers: [{ name: 'content-type', value: 'application/json' }], |
| 275 | body_base64: Buffer.from(JSON.stringify({ endpoint: 'list', payload: { n: 41 } }), 'utf8').toString('base64'), |
| 276 | deadline_ms: 5000, |
| 277 | }, |
| 278 | new AbortController().signal, |
| 279 | ) |
| 280 | assert.equal(rpcRes.matched, true) |
| 281 | assert.deepEqual(JSON.parse(Buffer.from(rpcRes.body_base64, 'base64').toString('utf8')), { endpoint: 'list', count: 42 }) |
| 282 | |
| 283 | const observed = [] |
| 284 | const disposeTitle = ctx.sessionTitle.register((id, title) => observed.push([id, title])) |
| 285 | ctx.sessionTitle.rename({ id: 'sess-1' }, ' My\nSession ') |
| 286 | assert.equal(ctx.sessionTitle.get('sess-1'), 'My Session') |
| 287 | assert.deepEqual(observed, [['sess-1', 'My Session']]) |
| 288 | disposeTitle() |
| 289 | |
| 290 | assert.equal(ctx.profileContext.name, 'codewhale') |
| 291 | assert.equal(ctx.profileContext.dir, extrasDir) |
| 292 | assert.equal(ctx.profileContext.installAnchor, extrasDir) |
| 293 | } finally { |
| 294 | clearOwnerRoutes('tok-extras') |
| 295 | } |
| 296 | }) |
| 297 | |
| 298 | test('profileContext fails closed without scoped dataDir, sessionTitle is owner-isolated, and fetch streams enforce 8 MiB cap', async () => { |
| 299 | const { owners, makeOwner } = await createHarness() |
| 300 | const a = makeOwner('plugin-sec-a', 'tok-sec-a', join(tmpdir(), 'sec-a')) |
| 301 | const b = makeOwner('plugin-sec-b', 'tok-sec-b', undefined) |
| 302 | try { |
| 303 | assert.throws(() => b.ctx.profileContext.dir, /scoped dataDir/) |
| 304 | assert.throws(() => b.ctx.profileContext.installAnchor, /scoped dataDir/) |
| 305 | |
| 306 | const bEvents = [] |
| 307 | const disposeB = b.ctx.sessionTitle.register((id, title) => bEvents.push([id, title])) |
| 308 | a.ctx.sessionTitle.rename('sess-shared', 'Plugin A Private') |
| 309 | assert.equal(a.ctx.sessionTitle.get('sess-shared'), 'Plugin A Private') |
| 310 | assert.equal(b.ctx.sessionTitle.get('sess-shared'), undefined) |
| 311 | assert.deepEqual(bEvents, []) |
| 312 | disposeB() |
| 313 | |
| 314 | a.ctx.connection.fetch.register({ |
| 315 | path: '/api/stream-huge', |
| 316 | methods: ['GET'], |
| 317 | fetch: () => { |
| 318 | const chunk = new Uint8Array(1024 * 1024) |
| 319 | let sent = 0 |
| 320 | const stream = new ReadableStream({ |
| 321 | pull(controller) { |
| 322 | if (sent >= 9) { |
| 323 | controller.close() |
| 324 | return |
| 325 | } |
| 326 | sent += 1 |
| 327 | controller.enqueue(chunk) |
| 328 | }, |
| 329 | }) |
| 330 | return new Response(stream, { status: 200 }) |
| 331 | }, |
| 332 | }) |
| 333 | |
| 334 | await assert.rejects( |
| 335 | () => dispatchPluginRoute( |
| 336 | { owners }, |
| 337 | { owner: a.owner.ref, method: 'GET', path: '/api/stream-huge', headers: [], deadline_ms: 5000 }, |
| 338 | new AbortController().signal, |
| 339 | ), |
| 340 | /response exceeded/, |
| 341 | ) |
| 342 | } finally { |
| 343 | clearOwnerRoutes('tok-sec-a') |
| 344 | clearOwnerRoutes('tok-sec-b') |
| 345 | } |
| 346 | }) |
| 347 |