Skip to content

Add more robust base64 check #786

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
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
28 changes: 24 additions & 4 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -458,11 +458,31 @@ export const TextResourceContentsSchema = ResourceContentsSchema.extend({
text: z.string(),
});


/**
* A Zod schema for validating Base64 strings that is more performant and
* robust for very large inputs than the default regex-based check. It avoids
* stack overflows by using the native `atob` function for validation.
*/
const Base64Schema = z.string().refine(
(val) => {
try {
// atob throws a DOMException if the string contains characters
// that are not part of the Base64 character set.
atob(val);
return true;
} catch {
return false;
}
},
{ message: "Invalid Base64 string" },
);

export const BlobResourceContentsSchema = ResourceContentsSchema.extend({
/**
* A base64-encoded string representing the binary data of the item.
*/
blob: z.string().base64(),
blob: Base64Schema,
});

/**
Expand Down Expand Up @@ -718,7 +738,7 @@ export const ImageContentSchema = z
/**
* The base64-encoded image data.
*/
data: z.string().base64(),
data: Base64Schema,
/**
* The MIME type of the image. Different providers may support different image types.
*/
Expand All @@ -741,7 +761,7 @@ export const AudioContentSchema = z
/**
* The base64-encoded audio data.
*/
data: z.string().base64(),
data: Base64Schema,
/**
* The MIME type of the audio. Different providers may support different audio types.
*/
Expand Down Expand Up @@ -894,7 +914,7 @@ export const ToolSchema = BaseMetadataSchema.extend({
})
.passthrough(),
/**
* An optional JSON Schema object defining the structure of the tool's output returned in
* An optional JSON Schema object defining the structure of the tool's output returned in
* the structuredContent field of a CallToolResult.
*/
outputSchema: z.optional(
Expand Down