Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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<InboxPlacementTestDeleted | null>`, 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

Expand Down
7 changes: 6 additions & 1 deletion src/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -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("<!doctype html") ||
Expand Down Expand Up @@ -462,6 +462,7 @@ export async function createRequest({
secrets = [],
regionalWarningState = null,
messageOnlyIsFailure = false,
emptyIsSuccess = false,
}) {
const url = buildRequestUrl({ batch, bulkBase, bulkURLs, apiBaseURL, baseURL, path, params });
requireHttpsUrl(url, "request URL");
Expand Down Expand Up @@ -515,6 +516,10 @@ export async function createRequest({
}

const status = responseStatus(response);
// Only for calls documented to answer 204 No Content (Inbox Placement DELETE).
if (emptyIsSuccess && status >= 200 && status < 300 && !String(finalResult).trim()) {
return null;
}
const contentType = responseContentType(response);
if (
looksLikeHtml(finalResult) ||
Expand Down
19 changes: 17 additions & 2 deletions src/warmup.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
import {
apiError,
checkApiKey,
looksLikeHtml,
pathSegment,
redactSecrets,
requireHttpsUrl,
Expand Down Expand Up @@ -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);
}
Expand Down Expand Up @@ -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;
Expand Down
10 changes: 7 additions & 3 deletions src/zero-bounce.js
Original file line number Diff line number Diff line change
Expand Up @@ -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],
Expand Down Expand Up @@ -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();
Expand All @@ -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 */
Expand Down
76 changes: 68 additions & 8 deletions tests/offline-api.test.js
Original file line number Diff line number Diff line change
@@ -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 = (() => {
Expand Down Expand Up @@ -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
Expand All @@ -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,
Expand All @@ -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 () => {
Expand Down
2 changes: 1 addition & 1 deletion tests/ts-consumer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -299,7 +299,7 @@ async function inboxPlacement(): Promise<void> {
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;
Expand Down
80 changes: 80 additions & 0 deletions tests/warmup-offline.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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 = `<!DOCTYPE html><html><head><title>Just a moment ${KEY}</title></head><body>${"x".repeat(5000)}</body></html>`;
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", `<html><head><title>${detail}</title></head></html>`],
"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);
Expand Down
7 changes: 5 additions & 2 deletions zeroBounceSDK.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -969,8 +969,11 @@ export class ZeroBounceSDK {
*/
listInboxPlacementTests(options?: ListInboxPlacementTestsOptions | null): Promise<unknown>;

/** Inbox Placement Tester: delete a finished test. DELETE /api/ipt/test/{id} */
deleteInboxPlacementTest(testId: string | number): Promise<InboxPlacementTestDeleted>;
/**
* 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<InboxPlacementTestDeleted | null>;

/** Inbox Placement Tester: the webhook saved on this API key. GET /api/ipt/webhook */
getInboxPlacementWebhook(): Promise<InboxPlacementWebhookResponse>;
Expand Down
Loading