| 1 | import { test, before, after } from 'node:test' |
| 2 | import assert from 'node:assert/strict' |
| 3 | import { createHash } from 'node:crypto' |
| 4 | import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' |
| 5 | import { tmpdir } from 'node:os' |
| 6 | import { dirname, join } from 'node:path' |
| 7 | import { fileURLToPath, pathToFileURL } from 'node:url' |
| 8 | import { Context } from '@deepseek-ai/cordis' |
| 9 | import { build } from 'esbuild' |
| 10 | import { activate, startHost, FIXTURES } from './harness.mjs' |
| 11 | |
| 12 | const here = dirname(fileURLToPath(import.meta.url)) |
| 13 | const hash = (value) => createHash('sha256').update(value).digest('hex') |
| 14 | |
| 15 | let tempBuildDir |
| 16 | let cotModule |
| 17 | let compositionModule |
| 18 | let networkModule |
| 19 | |
| 20 | before(async () => { |
| 21 | tempBuildDir = mkdtempSync(join(here, '..', 'node_modules', '.cw-cot-translation-')) |
| 22 | const buildModule = async (entry, outName) => { |
| 23 | const outfile = join(tempBuildDir, outName) |
| 24 | await build({ |
| 25 | entryPoints: [join(here, entry)], |
| 26 | outfile, |
| 27 | bundle: true, |
| 28 | platform: 'node', |
| 29 | format: 'esm', |
| 30 | packages: 'external', |
| 31 | absWorkingDir: join(here, '..'), |
| 32 | logLevel: 'silent', |
| 33 | }) |
| 34 | return import(pathToFileURL(outfile).href) |
| 35 | } |
| 36 | ;[cotModule, compositionModule, networkModule] = await Promise.all([ |
| 37 | buildModule('../src/dsh/cot-translation.ts', 'cot-translation.mjs'), |
| 38 | buildModule('../src/dsh/composition.ts', 'composition.mjs'), |
| 39 | buildModule('../src/dsh/network.ts', 'network.mjs'), |
| 40 | ]) |
| 41 | }) |
| 42 | |
| 43 | after(() => { |
| 44 | if (tempBuildDir) rmSync(tempBuildDir, { recursive: true, force: true }) |
| 45 | }) |
| 46 | |
| 47 | function temporaryDir(t) { |
| 48 | const dir = mkdtempSync(join(tmpdir(), 'cw-cot-test-')) |
| 49 | t.after(() => rmSync(dir, { recursive: true, force: true })) |
| 50 | return dir |
| 51 | } |
| 52 | |
| 53 | function brokerHost(responder) { |
| 54 | const calls = [] |
| 55 | return { |
| 56 | calls, |
| 57 | host: { |
| 58 | tier: 'plugin', |
| 59 | broker: async (_ctx, service, method, input) => { |
| 60 | calls.push({ service, method, input }) |
| 61 | return responder(input, { service, method, calls }) |
| 62 | }, |
| 63 | }, |
| 64 | } |
| 65 | } |
| 66 | |
| 67 | async function mountTranslator(t, responder, config = {}) { |
| 68 | const { host, calls } = brokerHost(responder) |
| 69 | const Credentials = networkModule.credentialsAdapter.define(host) |
| 70 | const ctx = new Context() |
| 71 | t.after(() => ctx.fiber.dispose()) |
| 72 | const llmCalls = [] |
| 73 | ctx.provide('llm') |
| 74 | ctx.set('llm', { |
| 75 | complete: async (input) => { |
| 76 | llmCalls.push(input) |
| 77 | throw new Error('llm.complete must never be called by cot-translation bridge') |
| 78 | }, |
| 79 | }) |
| 80 | await ctx.plugin(Credentials) |
| 81 | await ctx.plugin(cotModule.reviewedCotTranslationModule(), config) |
| 82 | return { ctx, translator: ctx.translator, calls, llmCalls } |
| 83 | } |
| 84 | |
| 85 | async function mountTranslatorWithFetch(t, fetchImpl, config = {}) { |
| 86 | const ctx = new Context() |
| 87 | t.after(() => ctx.fiber.dispose()) |
| 88 | ctx.provide('credentials') |
| 89 | ctx.set('credentials', { fetch: fetchImpl }) |
| 90 | ctx.provide('llm') |
| 91 | ctx.set('llm', { |
| 92 | complete: async () => { |
| 93 | throw new Error('llm.complete must never be called by cot-translation bridge') |
| 94 | }, |
| 95 | }) |
| 96 | await ctx.plugin(cotModule.reviewedCotTranslationModule(), config) |
| 97 | return { ctx, translator: ctx.translator } |
| 98 | } |
| 99 | |
| 100 | function jsonBrokerResponse(status, payload, url = 'https://example.invalid/translate') { |
| 101 | return { |
| 102 | status, |
| 103 | url, |
| 104 | redirected: false, |
| 105 | headers: [['content-type', 'application/json']], |
| 106 | body_base64: Buffer.from(JSON.stringify(payload), 'utf8').toString('base64'), |
| 107 | } |
| 108 | } |
| 109 | |
| 110 | test('the bundle installed but off sends nothing', async (t) => { |
| 111 | const host = await startHost() |
| 112 | t.after(() => host.stop()) |
| 113 | const dir = temporaryDir(t) |
| 114 | const patchPath = join(FIXTURES, 'cot-translation', 'cordis.patch.yml') |
| 115 | const patchSource = readFileSync(patchPath, 'utf8') |
| 116 | const disabledLayer = patchSource.replace( |
| 117 | /^(\s*-\s*id:\s*\S+)/gm, |
| 118 | '$1\n disabled: true', |
| 119 | ) |
| 120 | const spec = { |
| 121 | version: 1, |
| 122 | layers: [{ path: 'cordis.patch.yml', sha256: hash(disabledLayer), source: disabledLayer }], |
| 123 | modules: [], |
| 124 | files: {}, |
| 125 | } |
| 126 | writeFileSync(join(dir, 'composition.json'), JSON.stringify(spec)) |
| 127 | const entry = join(dir, 'index.mjs') |
| 128 | writeFileSync( |
| 129 | entry, |
| 130 | `import { mountReviewedComposition } from '@codewhale/dsh-composition'; import spec from './composition.json' with { type: 'json' }; export async function apply(ctx) { await mountReviewedComposition(ctx, new URL('./', import.meta.url).href, spec) }`, |
| 131 | ) |
| 132 | const { ref, result } = await activate(host, 'cot-translation-off', entry, { data_dir: dir }) |
| 133 | assert.equal(result.status, 'ok', result.diagnostic) |
| 134 | assert.deepEqual(host.coreCalls, []) |
| 135 | assert.deepEqual(host.registry, []) |
| 136 | assert.deepEqual(await host.call('ext/deactivate', { owner: ref }), { disposed: true, leaked: [] }) |
| 137 | }) |
| 138 | |
| 139 | test('without its row_bridges entry no package resolves to the bridge', async (t) => { |
| 140 | const pkg = '@deepseek-ai/dsh-experimental-translator' |
| 141 | assert.equal(compositionModule.hasReviewedRowBridge(pkg), false) |
| 142 | assert.equal(compositionModule.hasReviewedRowBridge('__proto__'), false) |
| 143 | assert.equal(compositionModule.hasReviewedRowBridge('constructor'), false) |
| 144 | |
| 145 | const ctx = new Context() |
| 146 | compositionModule.installCompositionLoader(ctx) |
| 147 | t.after(() => ctx.fiber.dispose()) |
| 148 | for (const candidate of [pkg, 'toString']) { |
| 149 | const layer = `- insert:\n - id: check\n name: ${JSON.stringify(candidate)}\n` |
| 150 | await assert.rejects( |
| 151 | compositionModule.mountReviewedComposition( |
| 152 | ctx, |
| 153 | new URL('./', pathToFileURL(join(FIXTURES, 'cot-translation', 'package.json'))).href, |
| 154 | { version: 1, layers: [{ path: 'cordis.patch.yml', sha256: hash(layer), source: layer }], modules: [], files: {} }, |
| 155 | ), |
| 156 | /composition row "check" failed activation|absent from the reviewed module closure/, |
| 157 | ) |
| 158 | } |
| 159 | |
| 160 | const host = await startHost() |
| 161 | t.after(() => host.stop()) |
| 162 | const dir = temporaryDir(t) |
| 163 | const enabledLayer = [ |
| 164 | '- insert:', |
| 165 | ' - id: translator', |
| 166 | ` name: ${JSON.stringify(pkg)}`, |
| 167 | ' config: {}', |
| 168 | ].join('\n') |
| 169 | const spec = { |
| 170 | version: 1, |
| 171 | layers: [{ path: 'cordis.patch.yml', sha256: hash(enabledLayer), source: enabledLayer }], |
| 172 | modules: [], |
| 173 | files: {}, |
| 174 | } |
| 175 | writeFileSync(join(dir, 'composition.json'), JSON.stringify(spec)) |
| 176 | const entry = join(dir, 'index.mjs') |
| 177 | writeFileSync( |
| 178 | entry, |
| 179 | `import { mountReviewedComposition } from '@codewhale/dsh-composition'; import spec from './composition.json' with { type: 'json' }; export async function apply(ctx) { await mountReviewedComposition(ctx, new URL('./', import.meta.url).href, spec) }`, |
| 180 | ) |
| 181 | const { result } = await activate(host, 'cot-translation-unbridged', entry, { data_dir: dir }) |
| 182 | assert.equal(result.status, 'failed') |
| 183 | assert.match( |
| 184 | result.diagnostic, |
| 185 | /composition row "translator" failed activation|absent from the reviewed module closure/, |
| 186 | ) |
| 187 | assert.deepEqual(host.coreCalls, []) |
| 188 | }) |
| 189 | |
| 190 | test('bing and google requests go only through the network broker', async (t) => { |
| 191 | const originalFetch = globalThis.fetch |
| 192 | globalThis.fetch = async () => { |
| 193 | throw new Error('global fetch must never be called') |
| 194 | } |
| 195 | t.after(() => { |
| 196 | globalThis.fetch = originalFetch |
| 197 | }) |
| 198 | |
| 199 | const bingFixture = JSON.parse( |
| 200 | readFileSync(join(FIXTURES, 'cot-translation', 'bing-response.json'), 'utf8'), |
| 201 | ) |
| 202 | const googleFixture = [[['Hello from Google', '你好世界', null, null, 1]], null, 'zh-CN'] |
| 203 | |
| 204 | const { translator, calls, llmCalls } = await mountTranslator(t, (input) => { |
| 205 | const parsedUrl = new URL(input.url) |
| 206 | if (parsedUrl.hostname === 'edge.microsoft.com') { |
| 207 | return jsonBrokerResponse(200, bingFixture, input.url) |
| 208 | } |
| 209 | if (parsedUrl.hostname === 'translate.googleapis.com') { |
| 210 | return jsonBrokerResponse(200, googleFixture, input.url) |
| 211 | } |
| 212 | throw new Error(`unexpected broker url: ${input.url}`) |
| 213 | }) |
| 214 | |
| 215 | assert.deepEqual(await translator.availableProviders(), ['bing', 'google']) |
| 216 | assert.equal(calls.length, 0) |
| 217 | |
| 218 | const bingSpec = translator.resolve({ |
| 219 | text: '思考过程', |
| 220 | sourceLanguage: 'zh-CN', |
| 221 | targetLanguage: 'en', |
| 222 | provider: 'bing', |
| 223 | sessionId: 'sess-123', |
| 224 | }) |
| 225 | assert.equal(bingSpec.sessionId, 'sess-123') |
| 226 | const bingOut = await translator.translate(bingSpec) |
| 227 | assert.equal(bingOut, 'Hello from Bing') |
| 228 | |
| 229 | const googleSpec = translator.resolve({ |
| 230 | text: '你好世界', |
| 231 | sourceLanguage: 'zh-Hans', |
| 232 | targetLanguage: 'zh-Hant', |
| 233 | provider: 'google', |
| 234 | }) |
| 235 | const googleOut = await translator.translate(googleSpec) |
| 236 | assert.equal(googleOut, 'Hello from Google') |
| 237 | |
| 238 | assert.equal(calls.length, 2) |
| 239 | assert.deepEqual(calls.map((c) => [c.service, c.method]), [ |
| 240 | ['network', 'fetch'], |
| 241 | ['network', 'fetch'], |
| 242 | ]) |
| 243 | assert.equal( |
| 244 | calls[0].input.url, |
| 245 | 'https://edge.microsoft.com/translate/translatetext?from=zh-Hans&to=en&isEnterpriseClient=false', |
| 246 | ) |
| 247 | assert.equal(calls[0].input.method, 'POST') |
| 248 | assert.equal( |
| 249 | Buffer.from(calls[0].input.body_base64, 'base64').toString('utf8'), |
| 250 | JSON.stringify(['思考过程']), |
| 251 | ) |
| 252 | |
| 253 | assert.equal( |
| 254 | calls[1].input.url, |
| 255 | 'https://translate.googleapis.com/translate_a/single', |
| 256 | ) |
| 257 | assert.equal(calls[1].input.method, 'POST') |
| 258 | assert.equal( |
| 259 | Buffer.from(calls[1].input.body_base64, 'base64').toString('utf8'), |
| 260 | 'client=gtx&sl=zh-CN&tl=zh-TW&dt=t&q=%E4%BD%A0%E5%A5%BD%E4%B8%96%E7%95%8C', |
| 261 | ) |
| 262 | assert.deepEqual(llmCalls, []) |
| 263 | }) |
| 264 | |
| 265 | test('a translate call with no ticket is refused and sends nothing', async (t) => { |
| 266 | const originalFetch = globalThis.fetch |
| 267 | let globalFetchCount = 0 |
| 268 | globalThis.fetch = async () => { |
| 269 | globalFetchCount += 1 |
| 270 | throw new Error('global fetch must never be called') |
| 271 | } |
| 272 | t.after(() => { |
| 273 | globalThis.fetch = originalFetch |
| 274 | }) |
| 275 | |
| 276 | const { translator, calls } = await mountTranslator(t, () => { |
| 277 | const err = new Error('network broker call requires an active ticket') |
| 278 | throw err |
| 279 | }) |
| 280 | |
| 281 | const spec = translator.resolve({ |
| 282 | text: 'private reasoning content', |
| 283 | targetLanguage: 'en', |
| 284 | provider: 'bing', |
| 285 | }) |
| 286 | await assert.rejects(translator.translate(spec), (err) => { |
| 287 | assert.equal(err instanceof cotModule.TranslationError, true) |
| 288 | assert.equal(err.code, 'TRANSLATION_REQUEST_FAILED') |
| 289 | assert.equal(err.message.includes('private reasoning content'), false) |
| 290 | return true |
| 291 | }) |
| 292 | assert.equal(calls.length, 1) |
| 293 | assert.equal(globalFetchCount, 0) |
| 294 | |
| 295 | const host = await startHost() |
| 296 | t.after(() => host.stop()) |
| 297 | const dir = temporaryDir(t) |
| 298 | const entry = join(dir, 'require-services.mjs') |
| 299 | const required = cotModule.reviewedCotTranslationModule().inject |
| 300 | assert.deepEqual(required, ['credentials', 'llm']) |
| 301 | writeFileSync( |
| 302 | entry, |
| 303 | `export const inject = ${JSON.stringify(required)}\nexport async function apply(ctx) {\n await ctx.credentials.fetch('https://www.bing.com/translator', { method: 'GET' })\n}\n`, |
| 304 | ) |
| 305 | const { result } = await activate(host, 'cot-translation-no-grants', entry, { data_dir: dir }) |
| 306 | assert.equal(result.status, 'failed') |
| 307 | assert.match(result.diagnostic, /broker is only available to a live tool invocation|no broker ticket|refused/i) |
| 308 | assert.deepEqual(host.coreCalls, []) |
| 309 | }) |
| 310 | |
| 311 | test('a refused send answers TRANSLATION_REQUEST_FAILED and keeps no text', async (t) => { |
| 312 | const secretSource = 'CONFIDENTIAL_COT_TEXT_ABC' |
| 313 | const leakedUpstreamBody = 'UPSTREAM_BODY_TOKEN_XYZ' |
| 314 | const { translator } = await mountTranslator(t, () => { |
| 315 | throw new Error(`broker rejected: ${secretSource} :: ${leakedUpstreamBody}`) |
| 316 | }) |
| 317 | |
| 318 | const spec = translator.resolve({ |
| 319 | text: secretSource, |
| 320 | targetLanguage: 'en', |
| 321 | provider: 'bing', |
| 322 | }) |
| 323 | await assert.rejects(translator.translate(spec), (err) => { |
| 324 | assert.equal(err instanceof cotModule.TranslationError, true) |
| 325 | assert.equal(err.code, 'TRANSLATION_REQUEST_FAILED') |
| 326 | assert.equal(err.message.includes(secretSource), false) |
| 327 | assert.equal(err.message.includes(leakedUpstreamBody), false) |
| 328 | return true |
| 329 | }) |
| 330 | |
| 331 | const { translator: httpTranslator } = await mountTranslator(t, () => ({ |
| 332 | status: 502, |
| 333 | url: 'https://edge.microsoft.com/translate/translatetext', |
| 334 | redirected: false, |
| 335 | headers: [['content-type', 'text/plain']], |
| 336 | body_base64: Buffer.from(leakedUpstreamBody, 'utf8').toString('base64'), |
| 337 | })) |
| 338 | await assert.rejects( |
| 339 | httpTranslator.translate({ |
| 340 | text: secretSource, |
| 341 | sourceLanguage: 'auto', |
| 342 | targetLanguage: 'en', |
| 343 | provider: 'bing', |
| 344 | }), |
| 345 | (err) => { |
| 346 | assert.equal(err.code, 'TRANSLATION_HTTP_ERROR') |
| 347 | assert.equal(err.message.includes(secretSource), false) |
| 348 | assert.equal(err.message.includes(leakedUpstreamBody), false) |
| 349 | return true |
| 350 | }, |
| 351 | ) |
| 352 | |
| 353 | await assert.rejects( |
| 354 | cotModule.cotTranslationTranslate( |
| 355 | translator, |
| 356 | { provider: 'bing', targetLanguage: 'en' }, |
| 357 | { text: secretSource, targetLanguage: 'en', provider: 'bing' }, |
| 358 | ), |
| 359 | (err) => { |
| 360 | assert.equal(err.code, 'cotTranslation/failed') |
| 361 | assert.deepEqual(err.data, {}) |
| 362 | assert.equal(err.message, 'Translation failed') |
| 363 | assert.equal(err.message.includes(secretSource), false) |
| 364 | assert.equal(err.message.includes(leakedUpstreamBody), false) |
| 365 | return true |
| 366 | }, |
| 367 | ) |
| 368 | }) |
| 369 | |
| 370 | test('an over-limit fragment is refused before any send', async (t) => { |
| 371 | const { translator, calls } = await mountTranslator( |
| 372 | t, |
| 373 | () => { |
| 374 | throw new Error('broker must not be reached for over-limit input') |
| 375 | }, |
| 376 | { maxTextChars: 10 }, |
| 377 | ) |
| 378 | assert.equal(translator.maxTextChars, 10) |
| 379 | const tooLong = '0123456789a' |
| 380 | assert.throws( |
| 381 | () => translator.resolve({ text: tooLong, targetLanguage: 'en', provider: 'bing' }), |
| 382 | (err) => { |
| 383 | assert.equal(err.code, 'TRANSLATION_TEXT_LIMIT') |
| 384 | assert.equal(err.message.includes(tooLong), false) |
| 385 | return true |
| 386 | }, |
| 387 | ) |
| 388 | await assert.rejects( |
| 389 | translator.translate({ |
| 390 | text: tooLong, |
| 391 | sourceLanguage: 'auto', |
| 392 | targetLanguage: 'en', |
| 393 | provider: 'bing', |
| 394 | }), |
| 395 | (err) => { |
| 396 | assert.equal(err.code, 'TRANSLATION_TEXT_LIMIT') |
| 397 | assert.equal(err.message.includes(tooLong), false) |
| 398 | return true |
| 399 | }, |
| 400 | ) |
| 401 | assert.equal( |
| 402 | await translator.translate({ |
| 403 | text: '', |
| 404 | sourceLanguage: 'auto', |
| 405 | targetLanguage: 'en', |
| 406 | provider: 'bing', |
| 407 | }), |
| 408 | '', |
| 409 | ) |
| 410 | assert.equal(calls.length, 0) |
| 411 | }) |
| 412 | |
| 413 | test("paid routes follow the design page's rule", async (t) => { |
| 414 | const { translator, calls, llmCalls } = await mountTranslator(t, () => { |
| 415 | throw new Error('paid routes must never reach the network broker') |
| 416 | }) |
| 417 | |
| 418 | const available = await translator.availableProviders() |
| 419 | assert.deepEqual(available, ['bing', 'google']) |
| 420 | assert.equal(available.includes('deepseek-account'), false) |
| 421 | assert.equal(available.includes('deepseek-official'), false) |
| 422 | |
| 423 | for (const provider of ['deepseek-account', 'deepseek-official']) { |
| 424 | const spec = translator.resolve({ |
| 425 | text: 'reason carefully', |
| 426 | targetLanguage: 'en', |
| 427 | provider, |
| 428 | }) |
| 429 | assert.equal(spec.provider, provider) |
| 430 | await assert.rejects(translator.translate(spec), (err) => { |
| 431 | assert.equal(err instanceof cotModule.TranslationError, true) |
| 432 | assert.equal(err.code, 'TRANSLATION_UNAVAILABLE') |
| 433 | return true |
| 434 | }) |
| 435 | } |
| 436 | assert.equal(calls.length, 0) |
| 437 | assert.deepEqual(llmCalls, []) |
| 438 | }) |
| 439 | |
| 440 | test('cancelling a translation aborts its broker call', async (t) => { |
| 441 | const { translator, calls } = await mountTranslator(t, () => new Promise(() => {})) |
| 442 | |
| 443 | const controller = new AbortController() |
| 444 | const reason = new Error('user cancelled translation') |
| 445 | const pending = translator.translate( |
| 446 | { |
| 447 | text: 'cancel this request', |
| 448 | sourceLanguage: 'auto', |
| 449 | targetLanguage: 'en', |
| 450 | provider: 'bing', |
| 451 | }, |
| 452 | controller.signal, |
| 453 | ) |
| 454 | await new Promise((resolve) => setTimeout(resolve, 10)) |
| 455 | assert.equal(calls.length, 1) |
| 456 | controller.abort(reason) |
| 457 | await assert.rejects(pending, (err) => err === reason) |
| 458 | |
| 459 | const preAborted = new AbortController() |
| 460 | preAborted.abort(reason) |
| 461 | await assert.rejects( |
| 462 | cotModule.cotTranslationTranslate( |
| 463 | translator, |
| 464 | { provider: 'bing', targetLanguage: 'en' }, |
| 465 | { text: 'never sent', targetLanguage: 'en', provider: 'bing' }, |
| 466 | preAborted.signal, |
| 467 | ), |
| 468 | (err) => err === reason, |
| 469 | ) |
| 470 | assert.equal(calls.length, 1) |
| 471 | |
| 472 | const { translator: timeoutTranslator } = await mountTranslator( |
| 473 | t, |
| 474 | () => new Promise(() => {}), |
| 475 | { timeoutMs: 15 }, |
| 476 | ) |
| 477 | await assert.rejects( |
| 478 | timeoutTranslator.translate({ |
| 479 | text: 'slow upstream', |
| 480 | sourceLanguage: 'auto', |
| 481 | targetLanguage: 'en', |
| 482 | provider: 'bing', |
| 483 | }), |
| 484 | (err) => err.code === 'TRANSLATION_TIMEOUT', |
| 485 | ) |
| 486 | }) |
| 487 | |
| 488 | test('the host half accepts only the selected provider and language', async (t) => { |
| 489 | const bingFixture = JSON.parse( |
| 490 | readFileSync(join(FIXTURES, 'cot-translation', 'bing-response.json'), 'utf8'), |
| 491 | ) |
| 492 | const { translator, calls } = await mountTranslator(t, (input) => |
| 493 | jsonBrokerResponse(200, bingFixture, input.url), |
| 494 | ) |
| 495 | |
| 496 | const config = { provider: 'bing', targetLanguage: 'en' } |
| 497 | const limits = await cotModule.cotTranslationLimits(translator, config) |
| 498 | assert.deepEqual(limits, { |
| 499 | maxTextChars: 4000, |
| 500 | preferences: { provider: 'bing', targetLanguage: 'en' }, |
| 501 | availableProviders: ['bing', 'google'], |
| 502 | }) |
| 503 | |
| 504 | await assert.rejects( |
| 505 | cotModule.cotTranslationTranslate(translator, config, { |
| 506 | text: 'bonjour', |
| 507 | targetLanguage: 'en', |
| 508 | provider: 'google', |
| 509 | }), |
| 510 | (err) => err.code === 'cotTranslation/failed', |
| 511 | ) |
| 512 | |
| 513 | await assert.rejects( |
| 514 | cotModule.cotTranslationTranslate(translator, config, { |
| 515 | text: 'bonjour', |
| 516 | targetLanguage: 'fr', |
| 517 | provider: 'bing', |
| 518 | }), |
| 519 | (err) => err.code === 'cotTranslation/failed', |
| 520 | ) |
| 521 | assert.equal(calls.length, 0) |
| 522 | |
| 523 | const translated = await cotModule.cotTranslationTranslate(translator, config, { |
| 524 | text: '你好', |
| 525 | targetLanguage: 'en', |
| 526 | }) |
| 527 | assert.equal(translated, 'Hello from Bing') |
| 528 | assert.equal(calls.length, 1) |
| 529 | |
| 530 | const autoLanguageTranslated = await cotModule.cotTranslationTranslate( |
| 531 | translator, |
| 532 | { provider: 'bing', targetLanguage: 'auto' }, |
| 533 | { text: '你好', targetLanguage: 'ja', provider: 'bing' }, |
| 534 | ) |
| 535 | assert.equal(autoLanguageTranslated, 'Hello from Bing') |
| 536 | assert.equal(calls.length, 2) |
| 537 | }) |
| 538 | |
| 539 | test('committed cot-translation fixture carries expected metadata and LF endings', () => { |
| 540 | const dir = join(FIXTURES, 'cot-translation') |
| 541 | const manifest = JSON.parse(readFileSync(join(dir, 'tarballs-manifest.json'), 'utf8')) |
| 542 | assert.equal(manifest.tarballs.length, 3) |
| 543 | for (const name of [ |
| 544 | '.gitattributes', |
| 545 | 'package.json', |
| 546 | 'cordis.patch.yml', |
| 547 | 'LICENSE', |
| 548 | 'tarballs-manifest.json', |
| 549 | 'bing-response.json', |
| 550 | ]) { |
| 551 | const raw = readFileSync(join(dir, name), 'utf8') |
| 552 | assert.equal(raw.includes('\r\n'), false, `${name} must use LF line endings`) |
| 553 | } |
| 554 | }) |
| 555 | |
| 556 | test('endpoint validation, schemas, resolve validation, redirects, stream cleanup, and disposal fail closed', async (t) => { |
| 557 | for (const bad of [ |
| 558 | 'ftp://example.com/translate', |
| 559 | 'https://user:pass@example.com/translate', |
| 560 | 'https://example.com/translate#frag', |
| 561 | ]) { |
| 562 | assert.throws( |
| 563 | () => cotModule.TranslatorConfigSchema({ bingEndpoint: bad }), |
| 564 | /HTTP\(S\) URL without credentials or a fragment/, |
| 565 | ) |
| 566 | } |
| 567 | |
| 568 | for (const allowed of [ |
| 569 | 'http://example.com/translate', |
| 570 | 'https://example.com/translate?foo=bar', |
| 571 | ]) { |
| 572 | assert.equal( |
| 573 | cotModule.TranslatorConfigSchema({ bingEndpoint: allowed }).bingEndpoint, |
| 574 | allowed, |
| 575 | ) |
| 576 | } |
| 577 | |
| 578 | const httpEndpoint = 'http://edge.microsoft.com/translate/translatetext?region=global' |
| 579 | const { translator: unreviewedHttpTranslator, calls: httpEndpointCalls } = |
| 580 | await mountTranslator( |
| 581 | t, |
| 582 | () => { |
| 583 | throw new Error('unreviewed_site') |
| 584 | }, |
| 585 | { bingEndpoint: httpEndpoint }, |
| 586 | ) |
| 587 | await assert.rejects( |
| 588 | unreviewedHttpTranslator.translate({ |
| 589 | text: 'sensitive http text', |
| 590 | sourceLanguage: 'auto', |
| 591 | targetLanguage: 'en', |
| 592 | provider: 'bing', |
| 593 | }), |
| 594 | (err) => |
| 595 | err instanceof cotModule.TranslationError && |
| 596 | err.code === 'TRANSLATION_REQUEST_FAILED' && |
| 597 | !err.message.includes('sensitive http text'), |
| 598 | ) |
| 599 | assert.equal(httpEndpointCalls.length, 1) |
| 600 | assert.equal( |
| 601 | httpEndpointCalls[0].input.url, |
| 602 | 'http://edge.microsoft.com/translate/translatetext?region=global&to=en&isEnterpriseClient=false', |
| 603 | ) |
| 604 | |
| 605 | assert.throws(() => cotModule.TranslatorConfigSchema({ maxTextChars: 1048577 })) |
| 606 | assert.throws(() => cotModule.TranslatorConfigSchema({ maxResponseBytes: 8 * 1024 * 1024 + 1 })) |
| 607 | |
| 608 | for (const badLang of ['', 'en us', 'zh_CN']) { |
| 609 | assert.throws(() => cotModule.CotTranslationConfigSchema({ targetLanguage: badLang })) |
| 610 | } |
| 611 | assert.equal(cotModule.CotTranslationConfigSchema({ targetLanguage: 'zh-Hans' }).targetLanguage, 'zh-Hans') |
| 612 | |
| 613 | const { translator: validatorTranslator } = await mountTranslator(t, () => { |
| 614 | throw new Error('validation should fail before network') |
| 615 | }) |
| 616 | for (const badReq of [ |
| 617 | { text: 'hi', targetLanguage: 'en', sourceLanguage: 42 }, |
| 618 | { text: 'hi', targetLanguage: 'en', sourceLanguage: ' ' }, |
| 619 | { text: 'hi', targetLanguage: 'en', sessionId: 99 }, |
| 620 | { text: 'hi', targetLanguage: 'en', sessionId: ' ' }, |
| 621 | ]) { |
| 622 | assert.throws( |
| 623 | () => validatorTranslator.resolve(badReq), |
| 624 | (err) => err instanceof cotModule.TranslationError && err.code === 'TRANSLATION_INVALID_RESPONSE', |
| 625 | ) |
| 626 | } |
| 627 | |
| 628 | const isolateCtx = new Context() |
| 629 | compositionModule.installCompositionLoader(isolateCtx) |
| 630 | t.after(() => isolateCtx.fiber.dispose()) |
| 631 | for (const isolateValue of [{ translator: 'shared' }, { translator: true }]) { |
| 632 | const badLayer = `- insert:\n - id: rogue\n name: ./rogue.mjs\n isolate: ${JSON.stringify(isolateValue)}\n` |
| 633 | await assert.rejects( |
| 634 | compositionModule.mountReviewedComposition( |
| 635 | isolateCtx, |
| 636 | new URL('./', pathToFileURL(join(FIXTURES, 'cot-translation', 'package.json'))).href, |
| 637 | { |
| 638 | version: 1, |
| 639 | layers: [{ path: 'cordis.patch.yml', sha256: hash(badLayer), source: badLayer }], |
| 640 | modules: [], |
| 641 | files: {}, |
| 642 | }, |
| 643 | ), |
| 644 | /cannot override translator isolation/, |
| 645 | ) |
| 646 | } |
| 647 | |
| 648 | const { translator: redirectTranslator } = await mountTranslator(t, () => ({ |
| 649 | status: 200, |
| 650 | url: 'https://evil.example/bounce', |
| 651 | redirected: true, |
| 652 | headers: [['content-type', 'application/json']], |
| 653 | body_base64: Buffer.from('[]', 'utf8').toString('base64'), |
| 654 | })) |
| 655 | await assert.rejects( |
| 656 | redirectTranslator.translate({ |
| 657 | text: 'hello', |
| 658 | sourceLanguage: 'auto', |
| 659 | targetLanguage: 'en', |
| 660 | provider: 'bing', |
| 661 | }), |
| 662 | (err) => err instanceof cotModule.TranslationError && err.code === 'TRANSLATION_REQUEST_FAILED', |
| 663 | ) |
| 664 | |
| 665 | const { translator: oversized } = await mountTranslator( |
| 666 | t, |
| 667 | () => jsonBrokerResponse(200, { huge: 'x'.repeat(200) }), |
| 668 | { maxResponseBytes: 32 }, |
| 669 | ) |
| 670 | await assert.rejects( |
| 671 | oversized.translate({ |
| 672 | text: 'hello', |
| 673 | sourceLanguage: 'auto', |
| 674 | targetLanguage: 'en', |
| 675 | provider: 'bing', |
| 676 | }), |
| 677 | (err) => err.code === 'TRANSLATION_RESPONSE_LIMIT', |
| 678 | ) |
| 679 | |
| 680 | const { translator: badJson } = await mountTranslator(t, () => ({ |
| 681 | status: 200, |
| 682 | url: 'https://edge.microsoft.com/translate/translatetext', |
| 683 | redirected: false, |
| 684 | headers: [['content-type', 'application/json']], |
| 685 | body_base64: Buffer.from('{not-json', 'utf8').toString('base64'), |
| 686 | })) |
| 687 | await assert.rejects( |
| 688 | badJson.translate({ |
| 689 | text: 'hello', |
| 690 | sourceLanguage: 'auto', |
| 691 | targetLanguage: 'en', |
| 692 | provider: 'bing', |
| 693 | }), |
| 694 | (err) => err.code === 'TRANSLATION_INVALID_RESPONSE', |
| 695 | ) |
| 696 | |
| 697 | const trackedReaderResponse = (behavior) => { |
| 698 | const state = { cancelCalls: 0, releaseCalls: 0 } |
| 699 | const response = { |
| 700 | ok: true, |
| 701 | status: 200, |
| 702 | redirected: false, |
| 703 | body: { |
| 704 | getReader() { |
| 705 | if (behavior === 'locked') throw new TypeError('ReadableStream is locked') |
| 706 | return { |
| 707 | read() { |
| 708 | if (behavior === 'error') return Promise.reject(new Error('stream broken')) |
| 709 | return new Promise(() => {}) |
| 710 | }, |
| 711 | cancel() { |
| 712 | state.cancelCalls += 1 |
| 713 | return Promise.resolve() |
| 714 | }, |
| 715 | releaseLock() { |
| 716 | state.releaseCalls += 1 |
| 717 | }, |
| 718 | } |
| 719 | }, |
| 720 | cancel() { |
| 721 | state.cancelCalls += 1 |
| 722 | return Promise.resolve() |
| 723 | }, |
| 724 | }, |
| 725 | } |
| 726 | return { response, state } |
| 727 | } |
| 728 | |
| 729 | const abortDouble = trackedReaderResponse('hang') |
| 730 | const { translator: streamAbortTranslator } = await mountTranslatorWithFetch( |
| 731 | t, |
| 732 | async () => abortDouble.response, |
| 733 | ) |
| 734 | const abortController = new AbortController() |
| 735 | const streamReason = new Error('abort stream') |
| 736 | const abortRun = streamAbortTranslator.translate( |
| 737 | { text: 'hi', sourceLanguage: 'auto', targetLanguage: 'en', provider: 'bing' }, |
| 738 | abortController.signal, |
| 739 | ) |
| 740 | await new Promise((resolve) => setTimeout(resolve, 10)) |
| 741 | abortController.abort(streamReason) |
| 742 | await assert.rejects(abortRun, (err) => err === streamReason) |
| 743 | assert.equal(abortDouble.state.cancelCalls, 1) |
| 744 | assert.equal(abortDouble.state.releaseCalls, 1) |
| 745 | |
| 746 | const timeoutDouble = trackedReaderResponse('hang') |
| 747 | const { translator: streamTimeoutTranslator } = await mountTranslatorWithFetch( |
| 748 | t, |
| 749 | async () => timeoutDouble.response, |
| 750 | { timeoutMs: 15 }, |
| 751 | ) |
| 752 | await assert.rejects( |
| 753 | streamTimeoutTranslator.translate({ |
| 754 | text: 'hi', |
| 755 | sourceLanguage: 'auto', |
| 756 | targetLanguage: 'en', |
| 757 | provider: 'bing', |
| 758 | }), |
| 759 | (err) => err instanceof cotModule.TranslationError && err.code === 'TRANSLATION_TIMEOUT', |
| 760 | ) |
| 761 | assert.equal(timeoutDouble.state.cancelCalls, 1) |
| 762 | assert.equal(timeoutDouble.state.releaseCalls, 1) |
| 763 | |
| 764 | const errorDouble = trackedReaderResponse('error') |
| 765 | const { translator: streamErrorTranslator } = await mountTranslatorWithFetch( |
| 766 | t, |
| 767 | async () => errorDouble.response, |
| 768 | ) |
| 769 | await assert.rejects( |
| 770 | streamErrorTranslator.translate({ |
| 771 | text: 'hi', |
| 772 | sourceLanguage: 'auto', |
| 773 | targetLanguage: 'en', |
| 774 | provider: 'bing', |
| 775 | }), |
| 776 | (err) => err instanceof cotModule.TranslationError && err.code === 'TRANSLATION_REQUEST_FAILED', |
| 777 | ) |
| 778 | assert.equal(errorDouble.state.cancelCalls, 1) |
| 779 | assert.equal(errorDouble.state.releaseCalls, 1) |
| 780 | |
| 781 | const lockedDouble = trackedReaderResponse('locked') |
| 782 | const { translator: lockedTranslator } = await mountTranslatorWithFetch( |
| 783 | t, |
| 784 | async () => lockedDouble.response, |
| 785 | ) |
| 786 | await assert.rejects( |
| 787 | lockedTranslator.translate({ |
| 788 | text: 'hi', |
| 789 | sourceLanguage: 'auto', |
| 790 | targetLanguage: 'en', |
| 791 | provider: 'bing', |
| 792 | }), |
| 793 | (err) => err instanceof cotModule.TranslationError && err.code === 'TRANSLATION_REQUEST_FAILED', |
| 794 | ) |
| 795 | |
| 796 | const { ctx: disposeCancelCtx, translator: disposeCancelTranslator } = |
| 797 | await mountTranslatorWithFetch(t, async () => ({ |
| 798 | ok: false, |
| 799 | status: 503, |
| 800 | redirected: false, |
| 801 | body: { |
| 802 | cancel() { |
| 803 | return new Promise(() => {}) |
| 804 | }, |
| 805 | }, |
| 806 | })) |
| 807 | const failingHttp = disposeCancelTranslator.translate({ |
| 808 | text: 'hanging cancel', |
| 809 | sourceLanguage: 'auto', |
| 810 | targetLanguage: 'en', |
| 811 | provider: 'bing', |
| 812 | }) |
| 813 | await new Promise((resolve) => setTimeout(resolve, 10)) |
| 814 | await Promise.race([ |
| 815 | disposeCancelCtx.fiber.dispose(), |
| 816 | new Promise((_, reject) => |
| 817 | setTimeout(() => reject(new Error('dispose stalled on hanging cancel')), 1000), |
| 818 | ), |
| 819 | ]) |
| 820 | await assert.rejects(failingHttp, /disposed/) |
| 821 | |
| 822 | const { ctx: disposeCtx, translator: disposeTranslator } = await mountTranslator( |
| 823 | t, |
| 824 | () => new Promise(() => {}), |
| 825 | ) |
| 826 | const inflight = disposeTranslator.translate({ |
| 827 | text: 'dispose while pending', |
| 828 | sourceLanguage: 'auto', |
| 829 | targetLanguage: 'en', |
| 830 | provider: 'bing', |
| 831 | }) |
| 832 | await new Promise((resolve) => setTimeout(resolve, 10)) |
| 833 | await disposeCtx.fiber.dispose() |
| 834 | await assert.rejects(inflight, /disposed/) |
| 835 | |
| 836 | let resolveLateFetch |
| 837 | let lateBodyCancelled = 0 |
| 838 | const { translator: lateTranslator } = await mountTranslatorWithFetch( |
| 839 | t, |
| 840 | () => |
| 841 | new Promise((resolve) => { |
| 842 | resolveLateFetch = resolve |
| 843 | }), |
| 844 | ) |
| 845 | const lateAbort = new AbortController() |
| 846 | const lateRun = lateTranslator.translate( |
| 847 | { text: 'late response', sourceLanguage: 'auto', targetLanguage: 'en', provider: 'bing' }, |
| 848 | lateAbort.signal, |
| 849 | ) |
| 850 | await new Promise((resolve) => setTimeout(resolve, 10)) |
| 851 | lateAbort.abort(new Error('abort before fetch settles')) |
| 852 | await assert.rejects(lateRun, /abort before fetch settles/) |
| 853 | resolveLateFetch({ |
| 854 | ok: true, |
| 855 | status: 200, |
| 856 | redirected: false, |
| 857 | body: { |
| 858 | cancel() { |
| 859 | lateBodyCancelled += 1 |
| 860 | return Promise.resolve() |
| 861 | }, |
| 862 | }, |
| 863 | }) |
| 864 | await new Promise((resolve) => setTimeout(resolve, 10)) |
| 865 | assert.equal(lateBodyCancelled, 1) |
| 866 | }) |
| 867 |