diff --git a/package.json b/package.json index c3b68b7..2f0b63f 100644 --- a/package.json +++ b/package.json @@ -11,6 +11,7 @@ }, "scripts": { "test": "ALLOW_HTTP_AUTH=\"true\" DEEPL_KEY=123 tap test/*.test.js", + "test-translate": "ALLOW_HTTP_AUTH=\"true\" TRANSLATION_PROVIDER=mock tap test/translate.test.js", "debug-test": "ALLOW_HTTP_AUTH=\"true\" DEEPL_KEY=123 tap test/*.test.js --timeout=2400", "start": "node src/index.js", "mock_deepl": "node test_utils/mock_deepl.js", diff --git a/src/translate.js b/src/translate.js index a691274..c46e8ed 100644 --- a/src/translate.js +++ b/src/translate.js @@ -100,12 +100,22 @@ async function translate_payload(api, res, payload, trans_id) { delete api.translation.queue[trans_id] } +function payload_is_data(q) { + try { + return Object.keys(JSON.parse(q)).length > 0 + } catch { + return false + } +} + async function handle_translate(api, req, res) { let id try { const source = req.query.source.toUpperCase() const target = req.query.target.toUpperCase() const q = req.query.q + if (payload_is_data(q)) + return util.invalid_request(res, `payload is data`) const payload = { source, target, q } const validation_res = await validate_payload(payload) if (validation_res.ok === false) diff --git a/test/translate.test.js b/test/translate.test.js index 6785cf1..081ce15 100644 --- a/test/translate.test.js +++ b/test/translate.test.js @@ -29,6 +29,28 @@ tap.test('translate_payload - Existing translation in database (mocked db)', asy t.end(); }); +tap.test(`translate_payload - reject json data (mocked server)`, async (t) => { + const api = await generate_test_api(t, { + simulate_existing_translation_in_db: false, + simulate_account_found_in_db: true, + }); + + const payload = JSON.stringify({"hello": 1}) + const expected_result = { + error: "payload is data", + }; + + const url = `/translate?source=EN&target=JA&q=${encodeURIComponent(payload)}` + const test_data = await generate_test_request_data(api, url) + + const res = await api.test_request + .get(url) + .set('Authorization', 'Nostr ' + test_data.auth_note_base64) + + t.same(res.statusCode, 400, 'Response should be 400'); + t.same(res.body, expected_result, 'Response should match expected value'); +}) + tap.test('translate_payload - New translation (mocked server)', async (t) => { const api = await generate_test_api(t, { simulate_existing_translation_in_db: false, @@ -158,11 +180,11 @@ async function generate_test_api(t, config) { return api; } -async function generate_test_request_data(api) { +async function generate_test_request_data(api, q) { let test_privkey = '10a9842fadc0aae2a649a1b707bf97e48c787b8517af4728ba3ec304089451be'; let test_pubkey = nostr.getPublicKey(test_privkey); - let query_url = '/translate?source=EN&target=JA&q=Hello' + let query_url = q || '/translate?source=EN&target=JA&q=Hello' let full_query_url = api.router.base_url + query_url; let auth_note_template = {