Skip to content

aws: Blob encode overflows the call stack on large binary payloads #447

Description

@florianbepunkt

Affected versions: 1.0.0-rc.4
Environment-independent (reproduces anywhere the schema runs; we hit it on Node 22 / AWS Lambda)

The non-streaming Blob schema base64-encodes with btoa(String.fromCharCode(...u)). The spread
passes every byte as a separate function argument, so for any sizeable payload the encode
direction throws:

RangeError: Maximum call stack size exceeded
    at u (@distilled.cloud/aws/src/traits.ts:651)   // encode: (u) => btoa(String.fromCharCode(...u))

Any operation with a large non-streaming Blob request field is therefore unusable. We hit it
on SES SendRawEmail: RawMessage.Data is a plain Blob (services/ses.ts), so every email
carrying a real attachment (a ~50–200 KB PDF) fails 100% of the time. Streaming bodies are
fine — e.g. S3 PutObject.Body is StreamingOutput/HttpPayload, which bypasses this encoder.

Reproduction

import { sendRawEmail } from "@distilled.cloud/aws/ses";

// A raw MIME message with a ~150 KB attachment → RawMessage.Data is a ~200 KB Uint8Array.
await sendRawEmail({ RawMessage: { Data: new Uint8Array(200_000) } /* … */ });
// → RangeError: Maximum call stack size exceeded  (during request encoding, before the wire call)

The threshold is engine-dependent (~10⁵ spread arguments in V8), so small blobs pass and real
attachments fail.

Root cause — src/traits.ts

export const Blob = S.String.pipe(
  S.decodeTo(
    S.instanceOf(Uint8Array),
    SchemaTransformation.transform({
      decode: (s) => Uint8Array.from(atob(s), (c) => c.charCodeAt(0)), // safe: char-by-char, no spread
      encode: (u) => btoa(String.fromCharCode(...u)),                  // ← spreads the whole array
    }),
  ),
);

Suggested fix

Chunk the conversion so no single String.fromCharCode call receives the whole array (keeps the
current btoa approach; portable across Node and browser):

encode: (u) => {
  let s = "";
  for (let i = 0; i < u.length; i += 0x8000) {
    s += String.fromCharCode(...u.subarray(i, i + 0x8000));
  }
  return btoa(s);
},

(Node-only alternative: Buffer.from(u).toString("base64").) The decode side already avoids the
spread and needs no change.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions