n8n-nodes-remove-ac 1.0.0 → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -3,15 +3,15 @@
3
3
  Official zero-dependency **[n8n](https://n8n.io)** community node for **[remove.ac](https://remove.ac)** — drop-in `/v1.0/removebg` Cloud GPU background removal ahead of the **December 1, 2026** `remove.bg` standalone site and self-serve `/v1.0/removebg` API shutdown.
4
4
 
5
5
  - **Migration Guide (`remove.bg` → `remove.ac`):** https://remove.ac/guides/n8n-make-shopify-background-removal-api
6
- - **API Keys & 1 Free Welcome Credit:** https://remove.ac/api-info
6
+ - **API Keys & 10 Full-Resolution Welcome Credits (Valid 30 Days):** https://remove.ac/api-info
7
7
  - **Free On-Device Browser WASM Workbench (50-Image Batch ZIP):** https://remove.ac
8
8
 
9
9
  ---
10
10
 
11
11
  ## Why Use `n8n-nodes-remove-ac`?
12
12
 
13
- 1. **Drop-In Replacement for Deprecated `Remove.bg` Workflows:** Accepts upstream n8n binary items (`data`) or public image URLs and outputs ready-to-upload cutout binaries (`PNG`, `WebP`, `JPG`, `ZIP`) plus `X-Foreground-*` bounding-box metadata.
14
- 2. **Automatic `> 4 MB` Zero-Disk GPU Streaming (Up to `25 MB / 40 MP`):** Large studio product photos automatically negotiate a 180-second single-use HMAC ticket (`POST /v1.0/removebg/ticket`) to bypass serverless payload caps without persisting source or output pixels to disk.
13
+ 1. **Drop-In Replacement for Deprecated `Remove.bg` Workflows:** Accepts upstream n8n binary items (`data`) or public image URLs, supports custom background image binaries (`bgImageBinaryProperty` / `bg_image_file`) or URLs (`bgImageUrl`), and outputs ready-to-upload cutout binaries (`Auto`, `PNG`, `WebP`, `JPG`, `ZIP`) plus `X-Foreground-*` bounding-box metadata.
14
+ 2. **Automatic `> 4 MB` Zero-Disk GPU Streaming (Up to `25 MB / 50 MP`):** Large studio product photos across `25mp`, `50mp`, `full`, and `auto` tiers automatically negotiate a 180-second single-use HMAC ticket (`POST /v1.0/removebg/ticket`) to bypass serverless payload caps without persisting source or output pixels to disk.
15
15
  3. **AI Agent Tool Ready (`usableAsTool: true`):** Works both as a standard pipeline transform node and as a callable tool inside n8n AI Agent workflows.
16
16
  4. **Zero External Runtime Dependencies & SSRF Hardened:** Built strictly on Node.js built-in primitives and n8n's `httpRequest` helper with IPv4/IPv6/NAT64/DNS private-network blocking.
17
17
 
@@ -22,14 +22,14 @@ Official zero-dependency **[n8n](https://n8n.io)** community node for **[remove.
22
22
  1. Open your self-hosted or desktop n8n instance.
23
23
  2. Go to **Settings → Community Nodes → Install**.
24
24
  3. Enter **`n8n-nodes-remove-ac`**, accept the prompt, and click **Install**.
25
- 4. Create a **remove.ac API** credential using your `rac_live_...` API key from https://remove.ac/api-info (verified email accounts receive **1 free credit**; non-expiring packs start at `$9 / 10` credits, monthly plans down to `$0.158 / image`; failed or timed-out calls cost `0` credits).
25
+ 4. Create a **remove.ac API** credential using your `rac_live_...` API key from https://remove.ac/api-info (verified email accounts receive **10 full-resolution welcome credits (valid 30 days)**; non-expiring packs start at `$9 / 10` credits, monthly plans down to `$0.158 / image`; failed or timed-out calls cost `0` credits).
26
26
 
27
27
  ---
28
28
 
29
29
  ## Operations
30
30
 
31
31
  - **Remove Background (`removeBackground`)**
32
- - **Binary Data:** Reads any upstream binary property (default `data`) up to `25 MB` and writes the transparent cutout binary + `json.removeAc` metadata (`creditsCharged`, `width`, `height`, `foregroundTop/Left/Width/Height`).
32
+ - **Binary Data:** Reads any upstream binary property (default `data`) up to `25 MB / 50 MP` (plus optional `bgImageBinaryProperty` or `bgImageUrl` background compositing) and writes the transparent or composited cutout binary + `json.removeAc` metadata (`creditsCharged`, `width`, `height`, `foregroundTop/Left/Width/Height`).
33
33
  - **Image URL:** Sends a validated public `https://` / `http://` URL to `POST /v1.0/removebg` and outputs the cutout binary.
34
34
  - **Get Account Balance (`getAccount`)**
35
35
  - Queries `GET /v1.0/account` and returns `totalCredits` + full account breakdown.
@@ -19,7 +19,7 @@ class RemoveAcApi {
19
19
  required: true,
20
20
  placeholder: "rac_live_...",
21
21
  description:
22
- "Your remove.ac API key. Verified email accounts include 1 free welcome credit at https://remove.ac/api-info.",
22
+ "Your remove.ac API key. Verified email accounts include 10 full-resolution welcome credits (valid 30 days) at https://remove.ac/api-info.",
23
23
  },
24
24
  {
25
25
  displayName: "Base URL",
@@ -1,5 +1,21 @@
1
1
  import type { IExecuteFunctions, INodeExecutionData, INodeType, INodeTypeDescription } from "n8n-workflow";
2
2
 
3
+ export declare function parseImageDimensions(
4
+ input: Uint8Array | ArrayBuffer
5
+ ): { width: number; height: number } | null;
6
+ export declare function isPrivateIpv4(ip: string): boolean;
7
+ export declare function isPrivateIpv6(ip: string): boolean;
8
+ export declare function validatePublicUrl(
9
+ rawUrl: string,
10
+ options?: { requireHttps?: boolean; lookupFn?: unknown }
11
+ ): Promise<URL>;
12
+ export declare function toNodeBuffer(val: unknown): Buffer | null;
13
+ export declare function formatErrorBody(rawBody: unknown): string;
14
+ export declare function normalizeShadowOptions(additional?: Record<string, unknown>): {
15
+ multipart: Record<string, string>;
16
+ json: Record<string, string | boolean>;
17
+ };
18
+
3
19
  export declare class RemoveAc implements INodeType {
4
20
  description: INodeTypeDescription;
5
21
  execute(this: IExecuteFunctions): Promise<INodeExecutionData[][]>;
@@ -1,6 +1,9 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.RemoveAc =
4
+ exports.normalizeShadowOptions =
5
+ exports.formatErrorBody =
6
+ exports.toNodeBuffer =
4
7
  exports.validatePublicUrl =
5
8
  exports.isPrivateIpv6 =
6
9
  exports.isPrivateIpv4 =
@@ -14,6 +17,11 @@ const net = require("node:net");
14
17
  const DEFAULT_BASE_URL = "https://remove.ac";
15
18
  const DIRECT_THRESHOLD_BYTES = 4 * 1024 * 1024;
16
19
  const MAX_UPLOAD_BYTES = 25 * 1024 * 1024;
20
+ const MAX_DIRECT_BODY_BYTES = 32 * 1024 * 1024;
21
+ const MAX_COMBINED_IMAGE_BYTES = MAX_DIRECT_BODY_BYTES - 65536;
22
+ const MAX_IMAGE_PIXELS = 50_000_000;
23
+ const MAX_IMAGE_SIDE = 50_000;
24
+ const MAX_REMOTE_REDIRECTS = 3;
17
25
  const DIRECT_RGBA_PNG_PIXELS = 5_000_000;
18
26
  const DIRECT_CROPPED_RGBA_PNG_PIXELS = 10_000_000;
19
27
 
@@ -297,6 +305,8 @@ function shouldPreFlightViaTicket(bytes, size, format, channels, crop) {
297
305
  else if (size === "medium") effectivePixels = Math.min(inputPixels, 1_500_000);
298
306
  else if (size === "hd") effectivePixels = Math.min(inputPixels, 4_000_000);
299
307
  else if (size === "4k") effectivePixels = Math.min(inputPixels, 10_000_000);
308
+ else if (size === "25mp") effectivePixels = Math.min(inputPixels, 25_000_000);
309
+ else effectivePixels = Math.min(inputPixels, 50_000_000);
300
310
  return effectivePixels > (crop ? DIRECT_CROPPED_RGBA_PNG_PIXELS : DIRECT_RGBA_PNG_PIXELS);
301
311
  }
302
312
 
@@ -310,20 +320,112 @@ function deriveSubIdempotencyKey(idem, suffix) {
310
320
  return `${trimmed.slice(0, 180)}:${hash}:${suffix}`;
311
321
  }
312
322
 
313
- function buildMultipartFormData(fields, filePart) {
323
+ function toNodeBuffer(val) {
324
+ if (Buffer.isBuffer(val)) return val;
325
+ if (val instanceof ArrayBuffer) return Buffer.from(val);
326
+ if (ArrayBuffer.isView(val)) {
327
+ return Buffer.from(val.buffer, val.byteOffset, val.byteLength);
328
+ }
329
+ if (typeof val === "string") return Buffer.from(val, "utf8");
330
+ return null;
331
+ }
332
+ exports.toNodeBuffer = toNodeBuffer;
333
+
334
+ function formatErrorBody(rawBody) {
335
+ if (rawBody === undefined || rawBody === null) return "";
336
+ if (typeof rawBody === "string") return rawBody;
337
+ if (Buffer.isBuffer(rawBody)) return rawBody.toString("utf8");
338
+ if (rawBody instanceof ArrayBuffer) return Buffer.from(rawBody).toString("utf8");
339
+ if (ArrayBuffer.isView(rawBody)) {
340
+ return Buffer.from(rawBody.buffer, rawBody.byteOffset, rawBody.byteLength).toString("utf8");
341
+ }
342
+ try {
343
+ return JSON.stringify(rawBody);
344
+ } catch {
345
+ return String(rawBody);
346
+ }
347
+ }
348
+ exports.formatErrorBody = formatErrorBody;
349
+
350
+ function validateAndParseImageDimensions(bytes, label) {
351
+ const dims = parseImageDimensions(bytes);
352
+ if (dims) {
353
+ const pixels = dims.width * dims.height;
354
+ if (pixels > MAX_IMAGE_PIXELS || dims.width > MAX_IMAGE_SIDE || dims.height > MAX_IMAGE_SIDE) {
355
+ const mp = (pixels / 1_000_000).toFixed(1);
356
+ throw new Error(
357
+ `${label} resolution ${dims.width}x${dims.height} (${mp} MP) exceeds remove.ac 50 MP / 50,000px maximum.`
358
+ );
359
+ }
360
+ }
361
+ return dims;
362
+ }
363
+
364
+ function assertCombinedMultipartWithinLimit(fgBytes, bgImgBytes) {
365
+ if (
366
+ fgBytes &&
367
+ bgImgBytes &&
368
+ fgBytes.byteLength + bgImgBytes.byteLength > MAX_COMBINED_IMAGE_BYTES
369
+ ) {
370
+ throw new Error(
371
+ `Combined foreground (${fgBytes.byteLength} bytes) and background (${bgImgBytes.byteLength} bytes) exceed remove.ac 32 MB direct upload stream limit.`
372
+ );
373
+ }
374
+ }
375
+
376
+ function normalizeShadowOptions(additional = {}) {
377
+ const rawShadowType =
378
+ typeof additional.shadowType === "string" ? additional.shadowType.trim().toLowerCase() : "";
379
+ if (rawShadowType === "none") {
380
+ return {
381
+ multipart: { add_shadow: "false", shadow_type: "none" },
382
+ json: { add_shadow: false, shadow_type: "none" },
383
+ };
384
+ }
385
+ if (additional.addShadow === false) {
386
+ return {
387
+ multipart: { add_shadow: "false" },
388
+ json: { add_shadow: false },
389
+ };
390
+ }
391
+ if (rawShadowType) {
392
+ return {
393
+ multipart: { add_shadow: "true", shadow_type: rawShadowType },
394
+ json: { add_shadow: true, shadow_type: rawShadowType },
395
+ };
396
+ }
397
+ if (additional.addShadow === true) {
398
+ return {
399
+ multipart: { add_shadow: "true" },
400
+ json: { add_shadow: true },
401
+ };
402
+ }
403
+ return { multipart: {}, json: {} };
404
+ }
405
+ exports.normalizeShadowOptions = normalizeShadowOptions;
406
+
407
+ function buildMultipartFormData(fields, filePart, extraFileParts = []) {
314
408
  const boundary = `----RemoveAcN8n${crypto.randomBytes(16).toString("hex")}`;
315
409
  const chunks = [];
410
+ const allFileParts = [filePart, ...(Array.isArray(extraFileParts) ? extraFileParts : [])].filter(
411
+ Boolean
412
+ );
316
413
 
317
- if (filePart) {
318
- const safeName = String(filePart.fileName || "image.png").replace(/[\r\n"\\]/g, "_");
319
- const safeMime = String(filePart.mimeType || "application/octet-stream").replace(/[\r\n]/g, "");
414
+ for (const part of allFileParts) {
415
+ const safeField = String(part.fieldName || "image_file").replace(/[\r\n"\\]/g, "_");
416
+ const safeName = String(part.fileName || "image.png").replace(/[\r\n"\\]/g, "_");
417
+ const safeMime = String(part.mimeType || "application/octet-stream").replace(/[\r\n]/g, "");
418
+ const partBuf = toNodeBuffer(part.buffer);
419
+ if (!partBuf) {
420
+ throw new Error(`Invalid binary buffer for multipart field '${safeField}'.`);
421
+ }
320
422
  chunks.push(
321
423
  Buffer.from(
322
- `--${boundary}\r\nContent-Disposition: form-data; name="${filePart.fieldName}"; filename="${safeName}"\r\nContent-Type: ${safeMime}\r\n\r\n`,
424
+ `--${boundary}\r\nContent-Disposition: form-data; name="${safeField}"; filename="${safeName}"\r\nContent-Type: ${safeMime}\r\n\r\n`,
323
425
  "utf8"
324
426
  )
325
427
  );
326
- chunks.push(Buffer.from(filePart.buffer));
428
+ chunks.push(partBuf);
327
429
  chunks.push(Buffer.from("\r\n", "utf8"));
328
430
  }
329
431
 
@@ -374,7 +476,7 @@ class RemoveAc {
374
476
  version: 1,
375
477
  subtitle: '={{$parameter["operation"]}}',
376
478
  description:
377
- "Remove image backgrounds via remove.ac (/v1.0/removebg drop-in API + up to 25 MB zero-disk GPU streaming).",
479
+ "Remove image backgrounds via remove.ac (/v1.0/removebg drop-in API + up to 25 MB / 50 MP zero-disk GPU streaming).",
378
480
  defaults: {
379
481
  name: "remove.ac",
380
482
  },
@@ -482,8 +584,10 @@ class RemoveAc {
482
584
  },
483
585
  },
484
586
  options: [
485
- { name: "Full (Up to 25 MB / 40 MP)", value: "full" },
486
- { name: "Auto", value: "auto" },
587
+ { name: "Full (Up to 25 MB / 50 MP)", value: "full" },
588
+ { name: "Auto (Up to 50 MP)", value: "auto" },
589
+ { name: "50 MP (Up to 50 MP)", value: "50mp" },
590
+ { name: "25 MP (Up to 25 MP)", value: "25mp" },
487
591
  { name: "4K (Up to 10 MP)", value: "4k" },
488
592
  { name: "HD (Up to 4 MP)", value: "hd" },
489
593
  { name: "Medium (Up to 1.5 MP)", value: "medium" },
@@ -503,6 +607,7 @@ class RemoveAc {
503
607
  },
504
608
  },
505
609
  options: [
610
+ { name: "Auto", value: "auto" },
506
611
  { name: "PNG (Transparent)", value: "png" },
507
612
  { name: "WebP", value: "webp" },
508
613
  { name: "JPG", value: "jpg" },
@@ -530,6 +635,24 @@ class RemoveAc {
530
635
  placeholder: "FFFFFF",
531
636
  description: "Solid hex background color (e.g. FFFFFF for marketplace white).",
532
637
  },
638
+ {
639
+ displayName: "Background Image Binary Field",
640
+ name: "bgImageBinaryProperty",
641
+ type: "string",
642
+ default: "",
643
+ placeholder: "bgData",
644
+ description:
645
+ "Optional name of an upstream binary property containing a custom background image (up to 25 MB / 50 MP, uploaded as bg_image_file).",
646
+ },
647
+ {
648
+ displayName: "Background Image URL",
649
+ name: "bgImageUrl",
650
+ type: "string",
651
+ default: "",
652
+ placeholder: "https://example.com/studio-backdrop.jpg",
653
+ description:
654
+ "Optional public HTTP/HTTPS URL of a custom background image to composite behind the subject (sent as bg_image_url).",
655
+ },
533
656
  {
534
657
  displayName: "Crop Transparent Padding",
535
658
  name: "crop",
@@ -637,13 +760,7 @@ class RemoveAc {
637
760
  ? acctResp.body
638
761
  : acctResp;
639
762
  if (acctStatus < 200 || acctStatus >= 300) {
640
- const errTxt =
641
- typeof acctRawBody === "string"
642
- ? acctRawBody
643
- : Buffer.isBuffer(acctRawBody)
644
- ? acctRawBody.toString("utf8")
645
- : JSON.stringify(acctRawBody ?? "");
646
- throw new Error(`[HTTP ${acctStatus}] ${errTxt}`);
763
+ throw new Error(`[HTTP ${acctStatus}] ${formatErrorBody(acctRawBody)}`);
647
764
  }
648
765
  const bodyObj = typeof acctRawBody === "string" ? JSON.parse(acctRawBody) : acctRawBody;
649
766
  const totalCredits = extractTotalCredits(bodyObj);
@@ -666,16 +783,56 @@ class RemoveAc {
666
783
  const crop = Boolean(additional.crop);
667
784
  const idem = `n8n-${crypto.randomUUID()}`;
668
785
 
786
+ const rawBgColor = String(additional.bgColor || "").trim().replace(/^#/, "");
787
+ const rawBgBinaryProp = String(additional.bgImageBinaryProperty || "").trim();
788
+ const rawBgUrl = String(additional.bgImageUrl || "").trim();
789
+ const bgSourceCount =
790
+ (rawBgColor ? 1 : 0) + (rawBgBinaryProp ? 1 : 0) + (rawBgUrl ? 1 : 0);
791
+ if (bgSourceCount > 1) {
792
+ throw new Error(
793
+ "Specify at most one of Background Color, Background Image Binary Field, or Background Image URL."
794
+ );
795
+ }
796
+
797
+ let bgBytes = null;
798
+ let bgFileName = "bg-image.png";
799
+ let bgMimeType = "application/octet-stream";
800
+ let bgUrl = null;
801
+ let bgDims = null;
802
+
803
+ if (rawBgBinaryProp) {
804
+ const bgMeta = this.helpers.assertBinaryData(i, rawBgBinaryProp);
805
+ bgBytes = toNodeBuffer(await this.helpers.getBinaryDataBuffer(i, rawBgBinaryProp));
806
+ if (!bgBytes || bgBytes.byteLength === 0) {
807
+ throw new Error(`Background binary property '${rawBgBinaryProp}' is empty.`);
808
+ }
809
+ if (bgBytes.byteLength > MAX_UPLOAD_BYTES) {
810
+ throw new Error(
811
+ `Background image exceeds remove.ac 25 MB limit (${bgBytes.byteLength} bytes).`
812
+ );
813
+ }
814
+ bgDims = validateAndParseImageDimensions(bgBytes, "Background image");
815
+ bgFileName = bgMeta.fileName || "bg-image.png";
816
+ bgMimeType = bgMeta.mimeType || "application/octet-stream";
817
+ } else if (rawBgUrl) {
818
+ const validatedBg = await validatePublicUrl(rawBgUrl, {
819
+ requireHttps: false,
820
+ lookupFn,
821
+ });
822
+ bgUrl = validatedBg.toString();
823
+ }
824
+
669
825
  let sourceBytes = null;
670
826
  let sourceFileName = "image.png";
671
827
  let sourceMimeType = "image/png";
672
828
  let sourceUrl = null;
829
+ let fgDims = null;
673
830
 
674
831
  if (inputSource === "binary") {
675
832
  const binaryPropertyName = this.getNodeParameter("binaryPropertyName", i);
676
833
  const binaryMeta = this.helpers.assertBinaryData(i, binaryPropertyName);
677
- sourceBytes = Buffer.from(await this.helpers.getBinaryDataBuffer(i, binaryPropertyName));
678
- if (sourceBytes.byteLength === 0) {
834
+ sourceBytes = toNodeBuffer(await this.helpers.getBinaryDataBuffer(i, binaryPropertyName));
835
+ if (!sourceBytes || sourceBytes.byteLength === 0) {
679
836
  throw new Error(`Input binary property '${binaryPropertyName}' is empty.`);
680
837
  }
681
838
  if (sourceBytes.byteLength > MAX_UPLOAD_BYTES) {
@@ -683,6 +840,8 @@ class RemoveAc {
683
840
  `Input image exceeds remove.ac 25 MB limit (${sourceBytes.byteLength} bytes).`
684
841
  );
685
842
  }
843
+ fgDims = validateAndParseImageDimensions(sourceBytes, "Input image");
844
+ assertCombinedMultipartWithinLimit(sourceBytes, bgBytes);
686
845
  sourceFileName = binaryMeta.fileName || "image.png";
687
846
  sourceMimeType = binaryMeta.mimeType || "application/octet-stream";
688
847
  } else {
@@ -696,29 +855,154 @@ class RemoveAc {
696
855
  sourceFileName = urlPath;
697
856
  }
698
857
 
858
+ const fetchRemoteImageBytes = async (initialUrl) => {
859
+ let currentUrl = initialUrl;
860
+ for (let hop = 0; hop <= MAX_REMOTE_REDIRECTS; hop++) {
861
+ const validated = await validatePublicUrl(currentUrl, {
862
+ requireHttps: false,
863
+ lookupFn,
864
+ });
865
+ currentUrl = validated.toString();
866
+
867
+ const imgRes = await this.helpers.httpRequest({
868
+ method: "GET",
869
+ url: currentUrl,
870
+ headers: {
871
+ Accept: "image/*,*/*;q=0.8",
872
+ },
873
+ encoding: "arraybuffer",
874
+ json: false,
875
+ disableFollowRedirect: true,
876
+ sendCredentialsOnCrossOriginRedirect: false,
877
+ returnFullResponse: true,
878
+ ignoreHttpStatusErrors: true,
879
+ });
880
+
881
+ const status =
882
+ imgRes && typeof imgRes.statusCode === "number" ? imgRes.statusCode : 200;
883
+ const rawBody =
884
+ imgRes && typeof imgRes === "object" && "statusCode" in imgRes
885
+ ? imgRes.body
886
+ : imgRes;
887
+ const respHeaders = (imgRes && imgRes.headers) || {};
888
+
889
+ if ([301, 302, 303, 307, 308].includes(status)) {
890
+ const location = readHeader(respHeaders, "location").trim();
891
+ if (!location) {
892
+ throw new Error(`Remote image redirect [HTTP ${status}] missing Location header.`);
893
+ }
894
+ if (hop === MAX_REMOTE_REDIRECTS) {
895
+ throw new Error(
896
+ `Remote image URL exceeded maximum redirect limit (${MAX_REMOTE_REDIRECTS}).`
897
+ );
898
+ }
899
+ currentUrl = new URL(location, currentUrl).toString();
900
+ continue;
901
+ }
902
+
903
+ if (status < 200 || status >= 300) {
904
+ throw new Error(
905
+ `Failed to fetch remote image [HTTP ${status}]: ${formatErrorBody(rawBody)}`
906
+ );
907
+ }
908
+
909
+ const fetchedBuf = toNodeBuffer(rawBody);
910
+ if (!fetchedBuf || fetchedBuf.byteLength === 0) {
911
+ throw new Error("Remote image response body is empty.");
912
+ }
913
+ if (fetchedBuf.byteLength > MAX_UPLOAD_BYTES) {
914
+ throw new Error(
915
+ `Remote image exceeds remove.ac 25 MB limit (${fetchedBuf.byteLength} bytes).`
916
+ );
917
+ }
918
+ const dims = validateAndParseImageDimensions(fetchedBuf, "Remote input image");
919
+ const contentType = readHeader(respHeaders, "content-type").split(";")[0].trim();
920
+ return {
921
+ buffer: fetchedBuf,
922
+ mimeType: contentType || "application/octet-stream",
923
+ dims,
924
+ };
925
+ }
926
+ throw new Error(
927
+ `Remote image URL exceeded maximum redirect limit (${MAX_REMOTE_REDIRECTS}).`
928
+ );
929
+ };
930
+
931
+ const ensureSourceBytesForTicket = async () => {
932
+ if (!sourceBytes) {
933
+ if (!sourceUrl) {
934
+ throw new Error("Missing binary or URL input source for ticket stream.");
935
+ }
936
+ const fetched = await fetchRemoteImageBytes(sourceUrl);
937
+ sourceBytes = fetched.buffer;
938
+ sourceMimeType = fetched.mimeType;
939
+ fgDims = fetched.dims;
940
+ }
941
+ assertCombinedMultipartWithinLimit(sourceBytes, bgBytes);
942
+ };
943
+
944
+ const bgFilePart = bgBytes
945
+ ? [
946
+ {
947
+ fieldName: "bg_image_file",
948
+ fileName: bgFileName,
949
+ mimeType: bgMimeType,
950
+ buffer: bgBytes,
951
+ },
952
+ ]
953
+ : [];
954
+
955
+ const shadowOpts = normalizeShadowOptions(additional);
956
+
699
957
  const optionFields = {
700
958
  size,
701
959
  format,
702
960
  channels,
703
961
  ...(additional.type && additional.type !== "auto" ? { type: additional.type } : {}),
704
- ...(additional.bgColor ? { bg_color: String(additional.bgColor).replace(/^#/, "") } : {}),
962
+ ...(rawBgColor ? { bg_color: rawBgColor } : {}),
963
+ ...(bgUrl ? { bg_image_url: bgUrl } : {}),
705
964
  ...(additional.crop !== undefined ? { crop: String(Boolean(additional.crop)) } : {}),
706
- ...(additional.addShadow !== undefined ? { add_shadow: String(Boolean(additional.addShadow)) } : {}),
707
- ...(additional.shadowType && additional.addShadow ? { shadow_type: additional.shadowType } : {}),
965
+ ...shadowOpts.multipart,
708
966
  };
709
967
 
710
968
  const runTicketStream = async (suffix) => {
969
+ await ensureSourceBytesForTicket();
970
+
971
+ const mp = buildMultipartFormData(
972
+ {},
973
+ {
974
+ fieldName: "image_file",
975
+ fileName: sourceFileName,
976
+ mimeType: sourceMimeType,
977
+ buffer: sourceBytes,
978
+ },
979
+ bgFilePart
980
+ );
981
+ if (mp.body.byteLength > MAX_DIRECT_BODY_BYTES) {
982
+ throw new Error(
983
+ `Multipart direct upload payload (${mp.body.byteLength} bytes) exceeds remove.ac 32 MB stream limit.`
984
+ );
985
+ }
986
+
711
987
  const ticketPayload = {
712
988
  foregroundSha256: sha256Hex(sourceBytes),
713
989
  foregroundByteLength: sourceBytes.byteLength,
990
+ ...(fgDims ? { width: fgDims.width, height: fgDims.height } : {}),
714
991
  size,
715
992
  format,
716
993
  channels,
717
994
  ...(additional.type && additional.type !== "auto" ? { type: additional.type } : {}),
718
- ...(additional.bgColor ? { bg_color: String(additional.bgColor).replace(/^#/, "") } : {}),
995
+ ...(rawBgColor ? { bg_color: rawBgColor } : {}),
996
+ ...(bgUrl ? { bg_image_url: bgUrl } : {}),
997
+ ...(bgBytes
998
+ ? {
999
+ bgImageSha256: sha256Hex(bgBytes),
1000
+ bgImageByteLength: bgBytes.byteLength,
1001
+ ...(bgDims ? { bgWidth: bgDims.width, bgHeight: bgDims.height } : {}),
1002
+ }
1003
+ : {}),
719
1004
  ...(additional.crop !== undefined ? { crop: Boolean(additional.crop) } : {}),
720
- ...(additional.addShadow !== undefined ? { add_shadow: Boolean(additional.addShadow) } : {}),
721
- ...(additional.shadowType && additional.addShadow ? { shadow_type: additional.shadowType } : {}),
1005
+ ...shadowOpts.json,
722
1006
  };
723
1007
 
724
1008
  const ticketRes = await this.helpers.httpRequest({
@@ -743,115 +1027,228 @@ class RemoveAc {
743
1027
  ? ticketRes.body
744
1028
  : ticketRes;
745
1029
  if (ticketStatus < 200 || ticketStatus >= 300) {
746
- const errTxt =
747
- typeof ticketRawBody === "string"
748
- ? ticketRawBody
749
- : Buffer.isBuffer(ticketRawBody)
750
- ? ticketRawBody.toString("utf8")
751
- : JSON.stringify(ticketRawBody ?? "");
752
- throw new Error(`[HTTP ${ticketStatus}] ${errTxt}`);
1030
+ throw new Error(`[HTTP ${ticketStatus}] ${formatErrorBody(ticketRawBody)}`);
753
1031
  }
754
1032
  const tJson = typeof ticketRawBody === "string" ? JSON.parse(ticketRawBody) : ticketRawBody;
755
- if (!tJson || !tJson.data || !tJson.data.directEndpoint || !tJson.data.ticket) {
1033
+ const tData =
1034
+ tJson && typeof tJson === "object" && tJson.data && typeof tJson.data === "object"
1035
+ ? tJson.data
1036
+ : tJson;
1037
+
1038
+ const holdId = String((tData && (tData.holdId ?? tData.lock_id)) || "").trim();
1039
+ const releaseToken = String(
1040
+ (tData && (tData.releaseToken ?? tData.release_token)) || ""
1041
+ ).trim();
1042
+ const rawReleaseEndpoint = String(
1043
+ (tData && (tData.releaseEndpoint ?? tData.release_endpoint)) ||
1044
+ `${baseUrl}/v1.0/removebg/ticket/release`
1045
+ ).trim();
1046
+
1047
+ let holdReleased = false;
1048
+ const releaseTicketHold = async () => {
1049
+ if (holdReleased || !holdId || !releaseToken) return false;
1050
+ holdReleased = true;
1051
+ let safeReleaseUrl = `${baseUrl}/v1.0/removebg/ticket/release`;
1052
+ try {
1053
+ const parsedRel = new URL(rawReleaseEndpoint);
1054
+ if (parsedRel.origin === baseUrl) {
1055
+ if (!allowLoopback) {
1056
+ await validatePublicUrl(parsedRel.toString(), {
1057
+ requireHttps: true,
1058
+ lookupFn,
1059
+ });
1060
+ }
1061
+ safeReleaseUrl = parsedRel.toString();
1062
+ } else if (!allowLoopback) {
1063
+ await validatePublicUrl(`${baseUrl}/v1.0/removebg/ticket/release`, {
1064
+ requireHttps: true,
1065
+ lookupFn,
1066
+ });
1067
+ }
1068
+ } catch {
1069
+ safeReleaseUrl = `${baseUrl}/v1.0/removebg/ticket/release`;
1070
+ }
1071
+ try {
1072
+ const relRes = await this.helpers.httpRequest({
1073
+ method: "POST",
1074
+ url: safeReleaseUrl,
1075
+ headers: {
1076
+ "Content-Type": "application/json",
1077
+ "X-Api-Key": apiKey,
1078
+ },
1079
+ body: { holdId, releaseToken },
1080
+ json: true,
1081
+ disableFollowRedirect: true,
1082
+ sendCredentialsOnCrossOriginRedirect: false,
1083
+ returnFullResponse: true,
1084
+ ignoreHttpStatusErrors: true,
1085
+ });
1086
+ const relStatus =
1087
+ relRes && typeof relRes.statusCode === "number" ? relRes.statusCode : 200;
1088
+ return relStatus >= 200 && relStatus < 300;
1089
+ } catch {
1090
+ return false;
1091
+ }
1092
+ };
1093
+
1094
+ if (
1095
+ !tData ||
1096
+ typeof tData.directEndpoint !== "string" ||
1097
+ !tData.directEndpoint.trim() ||
1098
+ typeof tData.ticket !== "string" ||
1099
+ !tData.ticket.trim()
1100
+ ) {
1101
+ await releaseTicketHold();
756
1102
  throw new Error("Invalid /v1.0/removebg/ticket response from remove.ac");
757
1103
  }
758
1104
 
759
- const directEndpoint = String(tJson.data.directEndpoint);
1105
+ const directEndpoint = tData.directEndpoint.trim();
760
1106
  if (!allowLoopback) {
761
- await validatePublicUrl(directEndpoint, {
762
- requireHttps: true,
763
- lookupFn,
764
- });
1107
+ try {
1108
+ await validatePublicUrl(directEndpoint, {
1109
+ requireHttps: true,
1110
+ lookupFn,
1111
+ });
1112
+ } catch (epErr) {
1113
+ await releaseTicketHold();
1114
+ throw epErr;
1115
+ }
765
1116
  }
766
1117
 
767
- const mp = buildMultipartFormData({}, {
768
- fieldName: "image_file",
769
- fileName: sourceFileName,
770
- mimeType: sourceMimeType,
771
- buffer: sourceBytes,
772
- });
773
-
774
- const dRes = await this.helpers.httpRequest({
775
- method: "POST",
776
- url: directEndpoint,
777
- headers: {
778
- Authorization: `Bearer ${tJson.data.ticket}`,
779
- "Content-Type": `multipart/form-data; boundary=${mp.boundary}`,
780
- },
781
- body: mp.body,
782
- encoding: "arraybuffer",
783
- json: false,
784
- disableFollowRedirect: true,
785
- sendCredentialsOnCrossOriginRedirect: false,
786
- returnFullResponse: true,
787
- ignoreHttpStatusErrors: true,
788
- });
1118
+ let dRes;
1119
+ try {
1120
+ dRes = await this.helpers.httpRequest({
1121
+ method: "POST",
1122
+ url: directEndpoint,
1123
+ headers: {
1124
+ Authorization: `Bearer ${tData.ticket.trim()}`,
1125
+ "Content-Type": `multipart/form-data; boundary=${mp.boundary}`,
1126
+ },
1127
+ body: mp.body,
1128
+ encoding: "arraybuffer",
1129
+ json: false,
1130
+ disableFollowRedirect: true,
1131
+ sendCredentialsOnCrossOriginRedirect: false,
1132
+ returnFullResponse: true,
1133
+ ignoreHttpStatusErrors: true,
1134
+ });
1135
+ } catch (netErr) {
1136
+ await releaseTicketHold();
1137
+ throw netErr;
1138
+ }
789
1139
 
790
- if (dRes.statusCode < 200 || dRes.statusCode >= 300) {
791
- const errTxt = Buffer.from(dRes.body || "").toString("utf8");
792
- throw new Error(`[HTTP ${dRes.statusCode}] ${errTxt}`);
1140
+ const dStatus =
1141
+ dRes && typeof dRes.statusCode === "number" ? dRes.statusCode : 200;
1142
+ if (dStatus < 200 || dStatus >= 300) {
1143
+ if (
1144
+ (dStatus >= 300 && dStatus < 400) ||
1145
+ dStatus === 400 ||
1146
+ dStatus === 413 ||
1147
+ (dStatus >= 502 && dStatus <= 504)
1148
+ ) {
1149
+ await releaseTicketHold();
1150
+ }
1151
+ const dBody =
1152
+ dRes && typeof dRes === "object" && "statusCode" in dRes ? dRes.body : dRes;
1153
+ throw new Error(`[HTTP ${dStatus}] ${formatErrorBody(dBody)}`);
793
1154
  }
794
1155
  return dRes;
795
1156
  };
796
1157
 
797
1158
  let rawResponse;
798
- const needsTicketUpfront =
799
- sourceBytes &&
800
- (sourceBytes.byteLength > DIRECT_THRESHOLD_BYTES ||
801
- shouldPreFlightViaTicket(sourceBytes, size, format, channels, crop));
1159
+ const needsTicketUpfront = Boolean(
1160
+ additional.direct ||
1161
+ (bgBytes && bgBytes.byteLength > DIRECT_THRESHOLD_BYTES) ||
1162
+ (sourceBytes &&
1163
+ (sourceBytes.byteLength > DIRECT_THRESHOLD_BYTES ||
1164
+ (bgBytes && sourceBytes.byteLength + bgBytes.byteLength > DIRECT_THRESHOLD_BYTES) ||
1165
+ shouldPreFlightViaTicket(sourceBytes, size, format, channels, crop)))
1166
+ );
802
1167
 
803
1168
  if (needsTicketUpfront) {
804
1169
  rawResponse = await runTicketStream("direct");
805
1170
  } else {
806
1171
  const mp = sourceUrl
807
- ? buildMultipartFormData({ ...optionFields, image_url: sourceUrl }, null)
808
- : buildMultipartFormData(optionFields, {
809
- fieldName: "image_file",
810
- fileName: sourceFileName,
811
- mimeType: sourceMimeType,
812
- buffer: sourceBytes,
813
- });
1172
+ ? buildMultipartFormData({ ...optionFields, image_url: sourceUrl }, null, bgFilePart)
1173
+ : buildMultipartFormData(
1174
+ optionFields,
1175
+ {
1176
+ fieldName: "image_file",
1177
+ fileName: sourceFileName,
1178
+ mimeType: sourceMimeType,
1179
+ buffer: sourceBytes,
1180
+ },
1181
+ bgFilePart
1182
+ );
814
1183
 
815
- const directRes = await this.helpers.httpRequest({
816
- method: "POST",
817
- url: `${baseUrl}/v1.0/removebg`,
818
- headers: {
819
- "X-Api-Key": apiKey,
820
- "Idempotency-Key": idem,
821
- "Content-Type": `multipart/form-data; boundary=${mp.boundary}`,
822
- },
823
- body: mp.body,
824
- encoding: "arraybuffer",
825
- json: false,
826
- disableFollowRedirect: true,
827
- sendCredentialsOnCrossOriginRedirect: false,
828
- returnFullResponse: true,
829
- ignoreHttpStatusErrors: true,
830
- });
831
-
832
- if (directRes.statusCode === 413 && sourceBytes) {
833
- rawResponse = await runTicketStream("fallback413");
834
- } else if (directRes.statusCode < 200 || directRes.statusCode >= 300) {
835
- const errTxt = Buffer.from(directRes.body || "").toString("utf8");
836
- throw new Error(`[HTTP ${directRes.statusCode}] ${errTxt}`);
1184
+ if (mp.body.byteLength > DIRECT_THRESHOLD_BYTES) {
1185
+ rawResponse = await runTicketStream("direct");
837
1186
  } else {
838
- rawResponse = directRes;
1187
+ const directRes = await this.helpers.httpRequest({
1188
+ method: "POST",
1189
+ url: `${baseUrl}/v1.0/removebg`,
1190
+ headers: {
1191
+ "X-Api-Key": apiKey,
1192
+ "Idempotency-Key": idem,
1193
+ "Content-Type": `multipart/form-data; boundary=${mp.boundary}`,
1194
+ },
1195
+ body: mp.body,
1196
+ encoding: "arraybuffer",
1197
+ json: false,
1198
+ disableFollowRedirect: true,
1199
+ sendCredentialsOnCrossOriginRedirect: false,
1200
+ returnFullResponse: true,
1201
+ ignoreHttpStatusErrors: true,
1202
+ });
1203
+
1204
+ if (directRes.statusCode === 413 && (sourceBytes || sourceUrl)) {
1205
+ rawResponse = await runTicketStream("fallback413");
1206
+ } else if (directRes.statusCode < 200 || directRes.statusCode >= 300) {
1207
+ throw new Error(`[HTTP ${directRes.statusCode}] ${formatErrorBody(directRes.body)}`);
1208
+ } else {
1209
+ rawResponse = directRes;
1210
+ }
839
1211
  }
840
1212
  }
841
1213
 
842
- const cutoutBuffer = Buffer.from(rawResponse.body);
1214
+ const cutoutBuffer = toNodeBuffer(rawResponse.body);
1215
+ if (!cutoutBuffer) {
1216
+ throw new Error("Received empty or unsupported binary response from remove.ac.");
1217
+ }
843
1218
  const respHeaders = rawResponse.headers || {};
844
- const outExt =
845
- format === "jpg" ? "jpg" : format === "webp" ? "webp" : format === "zip" ? "zip" : "png";
1219
+ const rawContentType = readHeader(respHeaders, "content-type")
1220
+ .split(";")[0]
1221
+ .trim()
1222
+ .toLowerCase();
846
1223
  const defaultMime =
847
- format === "jpg"
1224
+ format === "jpg" || format === "jpeg"
848
1225
  ? "image/jpeg"
849
1226
  : format === "webp"
850
1227
  ? "image/webp"
851
1228
  : format === "zip"
852
1229
  ? "application/zip"
853
1230
  : "image/png";
854
- const outMime = readHeader(respHeaders, "content-type") || defaultMime;
1231
+ const outMime = rawContentType || defaultMime;
1232
+ let outExt;
1233
+ if (format === "auto" || format === "jpg" || format === "jpeg") {
1234
+ if (outMime === "image/jpeg" || outMime === "image/jpg") {
1235
+ outExt = "jpg";
1236
+ } else if (outMime === "image/webp") {
1237
+ outExt = "webp";
1238
+ } else if (outMime === "application/zip" || outMime === "application/x-zip-compressed") {
1239
+ outExt = "zip";
1240
+ } else if (format === "jpg" || format === "jpeg") {
1241
+ outExt = "jpg";
1242
+ } else {
1243
+ outExt = "png";
1244
+ }
1245
+ } else if (format === "webp") {
1246
+ outExt = "webp";
1247
+ } else if (format === "zip") {
1248
+ outExt = "zip";
1249
+ } else {
1250
+ outExt = "png";
1251
+ }
855
1252
  const stem = sourceFileName.replace(/\.[^.]+$/, "") || "image";
856
1253
  const outFileName = `${stem}-nobg.${outExt}`;
857
1254
 
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "n8n-nodes-remove-ac",
3
- "version": "1.0.0",
4
- "description": "Official zero-dependency n8n community node for remove.ac (/v1.0/removebg drop-in background removal + up to 25 MB zero-disk GPU streaming).",
3
+ "version": "1.0.1",
4
+ "description": "Official zero-dependency n8n community node for remove.ac (/v1.0/removebg drop-in background removal + up to 25 MB / 50 MP zero-disk GPU streaming).",
5
5
  "keywords": [
6
6
  "n8n-community-node-package",
7
7
  "remove.ac",