diff --git a/CHANGELOG.md b/CHANGELOG.md index e4a1dbf..51d7391 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,6 +17,25 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 threw, a caller that caught the error sent its next requests to the EU host with `key-B`, and a fresh client whose `init` threw on an `http://` base URL still held the key. +- `ZeroBounceWarmup` redacts a failure to read the response body (for example + a connection closed mid-body) like every other error. In 4.0.1 and earlier + that error was rethrown as it came from `fetch`, so a `fetch` implementation + that quotes the request or the key in it passed the key to the caller. + +### Fixed + +- `deleteInboxPlacementTest` resolves to `null` when the API answers with an + empty 2xx (204 No Content or an empty 200), as the Python, Rust and PHP SDKs + do. 4.0.1 rejected that success with "Empty response from ZeroBounce (HTTP + 204)". Every other call still rejects an empty 2xx, and an empty error + answer still rejects with its status. The declared return type is now + `Promise`, so TypeScript code that assigns + the result to `InboxPlacementTestDeleted` under `strictNullChecks` needs a + null check. +- `ZeroBounceWarmup.downloadSeeds` and `downloadStatistics` reject an HTML page + (served as `text/html`, or an HTML body under any content type, such as a + proxy or challenge page) with a `ZBApiError` carrying the HTTP status. 4.0.1 + resolved it as if it were the CSV text. ## [4.0.1] - 2026-11-11 diff --git a/src/utils.js b/src/utils.js index 5f24ec0..1ff8bd5 100644 --- a/src/utils.js +++ b/src/utils.js @@ -164,7 +164,7 @@ function responseContentType(response) { return String(response.headers.get("content-type") || "").toLowerCase(); } -function looksLikeHtml(body) { +export function looksLikeHtml(body) { const head = String(body).slice(0, 2000).toLowerCase(); return ( head.includes("= 200 && status < 300 && !String(finalResult).trim()) { + return null; + } const contentType = responseContentType(response); if ( looksLikeHtml(finalResult) || diff --git a/src/warmup.js b/src/warmup.js index 2001482..a788dd0 100644 --- a/src/warmup.js +++ b/src/warmup.js @@ -13,6 +13,7 @@ import { apiError, checkApiKey, + looksLikeHtml, pathSegment, redactSecrets, requireHttpsUrl, @@ -124,7 +125,15 @@ export class ZeroBounceWarmup { status ); } - const body = typeof response.text === "function" ? await response.text() : ""; + let body = ""; + try { + if (typeof response.text === "function") body = await response.text(); + } catch (error) { + // A body cut short can quote the request, so it is raised redacted, on its own. + const name = error && error.name ? error.name : "Error"; + const message = error && error.message ? error.message : String(error); + throw new Error(redactSecrets(`${name}: ${message}`, all)); + } if (status > 299) { throw apiError(redactSecrets(warmupMessage(body, status), all), status); } @@ -152,7 +161,13 @@ export class ZeroBounceWarmup { response && response.headers && typeof response.headers.get === "function" ? String(response.headers.get("content-type") || "").toLowerCase() : ""; - if (!String(body).trim() || contentType.includes("application/json")) { + // A JSON answer or an HTML page (a proxy or challenge page) is never the CSV. + if ( + !String(body).trim() || + contentType.includes("application/json") || + contentType.includes("text/html") || + looksLikeHtml(body) + ) { throw apiError(redactSecrets(warmupMessage(body, status), [this._api_key]), status); } return body; diff --git a/src/zero-bounce.js b/src/zero-bounce.js index 944a44f..a090369 100644 --- a/src/zero-bounce.js +++ b/src/zero-bounce.js @@ -1400,12 +1400,13 @@ export class ZeroBounceSDK { // INBOX PLACEMENT TESTER (bulkapi.zerobounce.net/api/ipt) // The API key goes in an Authorization: Bearer header and bodies are JSON with camelCase fields. - _iptRequest(requestType, path, { params = null, jsonBody = null } = {}) { + _iptRequest(requestType, path, { params = null, jsonBody = null, emptyIsSuccess = false } = {}) { return createRequest({ requestType, path, params, jsonBody, + emptyIsSuccess, // Documented auth for this API is a Bearer header, not an api_key query. bearerToken: this._api_key, secrets: [this._api_key], @@ -1549,7 +1550,7 @@ export class ZeroBounceSDK { return this._iptRequest("GET", "/tests", { params }); } - /** Delete a finished test. DELETE /test/{id} */ + /** Delete a finished test. DELETE /test/{id}. Resolves to null on an empty 2xx (204 No Content). */ async deleteInboxPlacementTest(testId) { if (!this._initialized) { notInitialized(); @@ -1559,7 +1560,10 @@ export class ZeroBounceSDK { parameterIsMissing("testId"); return; } - return this._iptRequest("DELETE", `/test/${encodeURIComponent(String(testId).trim())}`); + // A 204 No Content (or an empty 200) is a success: it resolves to null. + return this._iptRequest("DELETE", `/test/${encodeURIComponent(String(testId).trim())}`, { + emptyIsSuccess: true, + }); } /** The webhook URL saved on this API key. GET /webhook */ diff --git a/tests/offline-api.test.js b/tests/offline-api.test.js index a18a4d9..98a843e 100644 --- a/tests/offline-api.test.js +++ b/tests/offline-api.test.js @@ -1,6 +1,7 @@ /** * Offline API suite. Replaces global fetch; no network and no real API key. */ +import { inspect } from "util"; import { ZeroBounceSDK } from "../src/zero-bounce.js"; const HTML_PAGE = (() => { @@ -446,11 +447,22 @@ describe("offline API", () => { const forms = [key, encodeURIComponent(key), escape(key)]; const sdk = client(key); jest.spyOn(console, "warn").mockImplementation(() => {}); + // [status, content type, body]: API and proxy answers that quote the key. const echoes = { - "success false": (detail) => JSON.stringify({ success: false, message: `rejected ${detail}` }), - "error field": (detail) => JSON.stringify({ error: `rejected ${detail}` }), - "HTTP 400": (detail) => JSON.stringify({ message: `rejected ${detail}` }), + "success false": (detail) => [200, "application/json", JSON.stringify({ success: false, message: `rejected ${detail}` })], + "error field": (detail) => [200, "application/json", JSON.stringify({ error: `rejected ${detail}` })], + "dead key": (detail) => [200, "application/json", JSON.stringify({ error: `Invalid API key ${detail}` })], + "not JSON on 2xx": (detail) => [200, "application/json", `rejected ${detail}`], + "message only": (detail) => [200, "application/json", JSON.stringify({ Message: `rejected ${detail}` })], + "HTTP 400": (detail) => [400, "application/json", JSON.stringify({ message: `rejected ${detail}` })], + "HTTP 400 error": (detail) => [400, "application/json", JSON.stringify({ error: `rejected ${detail}` })], + "HTTP 400 text": (detail) => [400, "text/plain", `Bad Request: GET /v2/x?api_key=${key} ${detail}`], }; + // A message-only body is a result everywhere but email finder and domain + // search (validate's greylist answer), so only those must reject on it. + const mustReject = (failure, name) => failure !== "message only" || /^(findEmail|guessFormat)/.test(name); + const finderNames = callAll(sdk).map(([name]) => name).filter((name) => mustReject("message only", name)); + expect(finderNames.length).toBeGreaterThanOrEqual(5); for (const failure of ["fetch", "body", ...Object.keys(echoes)]) { for (const [name, run] of callAll(sdk)) { // Some fetch implementations and polyfills quote the request URL, or @@ -459,9 +471,8 @@ describe("offline API", () => { const detail = `${forms.join(" ")} ${url}`; if (failure === "fetch") throw new TypeError(`fetch failed: ${detail}`); if (echoes[failure]) { - const body = echoes[failure](detail); - const status = failure === "HTTP 400" ? 400 : 200; - return { status, headers: { get: () => "application/json" }, text: async () => body }; + const [status, contentType, body] = echoes[failure](detail); + return { status, headers: { get: () => contentType }, text: async () => body }; } return { status: 200, @@ -475,12 +486,61 @@ describe("offline API", () => { try { await run(); } catch (error) { - message = `${error.message}\n${error.stack}`; + // Every field, the stack and any cause, not only the message. + message = `${error.message}\n${error.stack}\n${inspect(error, { showHidden: true, depth: 5 })}`; } const leaked = message !== null && forms.some((form) => message.includes(form)); - expect({ name, failure, rejected: message !== null, leaked }).toEqual({ name, failure, rejected: true, leaked: false }); + expect({ name, failure, rejected: message !== null || !mustReject(failure, name), leaked }).toEqual({ + name, + failure, + rejected: true, + leaked: false, + }); + } + } + }); + + it("resolves an empty 2xx to deleteInboxPlacementTest as null, and rejects every other empty answer with its status", async () => { + const sdk = client("parity-key"); + const answerWith = (status, body = "") => { + global.fetch = async () => ({ + status, + headers: { get: () => (body ? "application/json" : null) }, + text: async () => body, + }); + }; + const settle = async (run) => { + try { + return { resolved: await run() }; + } catch (error) { + return { status: error.statusCode, message: error.message }; + } + }; + const iptCalls = callAll(sdk).filter(([, , , , path]) => path.startsWith("/api/ipt/")); + expect(iptCalls.map(([name]) => name)).toContain("deleteInboxPlacementTest"); + for (const [name, run] of iptCalls) { + for (const [status, body] of [[204, ""], [200, ""], [200, " \n"]]) { + answerWith(status, body); + const expected = + name === "deleteInboxPlacementTest" + ? { resolved: null } + : { status, message: `Empty response from ZeroBounce (HTTP ${status})` }; + expect({ name, status, outcome: await settle(run) }).toEqual({ name, status, outcome: expected }); } } + // An empty error answer is still an error with its status, on DELETE too. + for (const status of [404, 500]) { + answerWith(status); + expect(await settle(() => sdk.deleteInboxPlacementTest("t-1"))).toEqual({ + status, + message: `Empty response from ZeroBounce (HTTP ${status})`, + }); + } + // A JSON answer to DELETE is still returned as it is. + answerWith(200, '{"id":"t-1","status":"deleted"}'); + expect(await settle(() => sdk.deleteInboxPlacementTest("t-1"))).toEqual({ + resolved: { id: "t-1", status: "deleted" }, + }); }); it("uses the regional host selected in init", async () => { diff --git a/tests/ts-consumer.ts b/tests/ts-consumer.ts index d5466b8..690234d 100644 --- a/tests/ts-consumer.ts +++ b/tests/ts-consumer.ts @@ -299,7 +299,7 @@ async function inboxPlacement(): Promise { const seeds: string[] = created.emailAddressList; const result: InboxPlacementTestResult = await zb.getInboxPlacementTest(created.id); const status: "running" | "finished" = result.status; - const deleted: InboxPlacementTestDeleted = await zb.deleteInboxPlacementTest(created.id); + const deleted: InboxPlacementTestDeleted | null = await zb.deleteInboxPlacementTest(created.id); const webhook: InboxPlacementWebhookResponse = await zb.getInboxPlacementWebhook(); const webhookUrl: string = webhook.webhookUrl; void seeds; diff --git a/tests/warmup-offline.test.js b/tests/warmup-offline.test.js index 1e53086..4f50c6e 100644 --- a/tests/warmup-offline.test.js +++ b/tests/warmup-offline.test.js @@ -2,6 +2,7 @@ * Offline suite for the Warmup API client. Replaces global fetch; no network * and no real key. */ +import { inspect } from "util"; import { ZeroBounceWarmup } from "../src/warmup.js"; const KEY = "warmup-test-key"; @@ -467,6 +468,85 @@ describe("Warmup API client", () => { } }); + it("rejects a download answered with an HTML page instead of returning it as CSV text", async () => { + const c = new ZeroBounceWarmup(KEY); + const page = `Just a moment ${KEY}${"x".repeat(5000)}`; + for (const [name, call] of [ + ["downloadSeeds", () => c.downloadSeeds()], + ["downloadStatistics", () => c.downloadStatistics("sender@example.com")], + ]) { + // A proxy or challenge page, served as HTML or mislabelled as CSV. + for (const contentType of ["text/html; charset=UTF-8", "text/csv"]) { + installFake({ body: page, contentType }); + const error = await rejects(call()); + expect([name, contentType, error.message, error.statusCode]).toEqual([ + name, + contentType, + "ZeroBounce returned an HTML error page instead of an API response.", + 200, + ]); + } + } + }); + + it("keeps every form of the key out of every error, on every public method", async () => { + // A key whose URL-encoded and escape() forms differ from the raw one. + const key = "warmup-secret+key/1"; + const forms = [key, encodeURIComponent(key), escape(key)]; + const detail = `${forms.join(" ")} https://warmup-api.zerobounce.net/api/v1/warmup?API-Key=${encodeURIComponent(key)}`; + // [status, content type, body], or a body read that fails. + const echoes = { + "2xx error JSON": [200, "application/json", JSON.stringify({ error: `Invalid API key ${detail}` })], + "2xx success false": [200, "application/json", JSON.stringify({ success: false, message: `rejected ${detail}` })], + "2xx not JSON": [200, "text/plain", `rejected ${detail}`], + "2xx HTML": [200, "text/html", `${detail}`], + "4xx JSON": [400, "application/json", JSON.stringify({ error: `rejected ${detail}` })], + "4xx text": [400, "text/plain", `Bad Request: ${detail}`], + "body read": null, + }; + // Which answers each kind of method must reject; on the others a JSON + // method or a download may resolve with the body as its result. + const downloads = publicWarmupMethods().filter((name) => name.startsWith("download")); + expect(downloads).toEqual(["downloadSeeds", "downloadStatistics"]); + const mustReject = (echo, name) => + echo.startsWith("4xx") || + echo === "body read" || + echo === "2xx HTML" || + (downloads.includes(name) ? echo.startsWith("2xx error") || echo.startsWith("2xx success") : echo === "2xx not JSON"); + const covered = new Set(); + for (const [echo, answer] of Object.entries(echoes)) { + for (const [name, call] of allWarmupCalls(new ZeroBounceWarmup(key))) { + global.fetch = async () => { + if (!answer) { + return { + status: 200, + headers: { get: () => "application/json" }, + text: async () => { + throw new TypeError(`terminated: ${detail}`); + }, + }; + } + return httpResponse(answer[0], answer[2], answer[1]); + }; + let text = null; + try { + await call(); + } catch (error) { + text = `${error.message}\n${error.stack}\n${inspect(error, { showHidden: true, depth: 5 })}`; + } + const leaked = text !== null && forms.some((form) => text.includes(form)); + expect({ name, echo, rejected: text !== null || !mustReject(echo, name), leaked }).toEqual({ + name, + echo, + rejected: true, + leaked: false, + }); + covered.add(name); + } + } + expect([...covered].sort()).toEqual(publicWarmupMethods()); + }); + it("does not follow a redirect", async () => { installFake({ status: 302, body: "" }); const c = new ZeroBounceWarmup(KEY); diff --git a/zeroBounceSDK.d.ts b/zeroBounceSDK.d.ts index f134e0e..7fbae40 100644 --- a/zeroBounceSDK.d.ts +++ b/zeroBounceSDK.d.ts @@ -969,8 +969,11 @@ export class ZeroBounceSDK { */ listInboxPlacementTests(options?: ListInboxPlacementTestsOptions | null): Promise; - /** Inbox Placement Tester: delete a finished test. DELETE /api/ipt/test/{id} */ - deleteInboxPlacementTest(testId: string | number): Promise; + /** + * Inbox Placement Tester: delete a finished test. DELETE /api/ipt/test/{id}. + * Resolves to null when the API answers with an empty 2xx (204 No Content). + */ + deleteInboxPlacementTest(testId: string | number): Promise; /** Inbox Placement Tester: the webhook saved on this API key. GET /api/ipt/webhook */ getInboxPlacementWebhook(): Promise;