Repository navigation
fix(media): notas de voz y fotos de WhatsApp vía Zernio (401) #85
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
Open
santmun
wants to merge
3
commits into
main
Choose a base branch
from
cursor/zernio-media-auth-a12a
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,29 @@ | ||
| import type { Env } from "../env"; | ||
| import { fetchInboundMedia, type ZernioEnv } from "./zernio"; | ||
|
|
||
| export interface CapturedMedia { | ||
| bytes: Uint8Array; | ||
| contentType: string; | ||
| } | ||
|
|
||
| export class MediaFetchError extends Error { | ||
| constructor(readonly status: number) { | ||
| super(`media fetch failed: ${status}`); | ||
| this.name = "MediaFetchError"; | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * Baja los bytes de un adjunto entrante (nota de voz, foto). | ||
| * Zernio exige Authorization; fetchInboundMedia la pone solo en su host. | ||
| */ | ||
| export async function captureIncomingMedia(url: string, env: ZernioEnv & Partial<Env>): Promise<CapturedMedia> { | ||
| const res = await fetchInboundMedia(url, env); | ||
| if (!res.ok) throw new MediaFetchError(res.status); | ||
| const bytes = new Uint8Array(await res.arrayBuffer()); | ||
| const contentType = (res.headers.get("content-type") || "application/octet-stream") | ||
| .split(";")[0] | ||
| .trim() | ||
| .toLowerCase(); | ||
| return { bytes, contentType: contentType || "application/octet-stream" }; | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,44 @@ | ||
| // Textos que el bot guarda cuando NO pudo leer el audio o la foto. | ||
| // No son palabras del cliente: un fallo de descarga (401 de Zernio, red, etc.) | ||
| // deja el mismo placeholder en cada intento. Si el anti-bot los cuenta como | ||
| // "el mismo mensaje repetido", 3 notas de voz pausan a una persona real. | ||
|
|
||
| export const AUDIO_NOT_UNDERSTOOD = "(no pude entender el audio)"; | ||
| export const AUDIO_EMPTY = "(audio sin transcripción)"; | ||
| export const IMAGE_NOT_SEEN = "(no pude ver la imagen)"; | ||
| /** Lo que se guarda cuando la foto llega sin texto del cliente. No es un fallo. */ | ||
| export const IMAGE_NO_CAPTION = "(imagen sin caption)"; | ||
|
|
||
| const PLACEHOLDERS = new Set( | ||
| [AUDIO_NOT_UNDERSTOOD, AUDIO_EMPTY, IMAGE_NOT_SEEN].map((s) => s.toLowerCase()), | ||
| ); | ||
|
|
||
| /** | ||
| * True cuando el texto guardado es solo avisos de fallo de media, no palabras | ||
| * del cliente. Varios audios en el mismo buffer quedan en líneas separadas | ||
| * con el mismo placeholder: eso también cuenta. | ||
| */ | ||
| export function isMediaFailurePlaceholder(text: string): boolean { | ||
| const stripped = text.replace(/\n?\[IMAGE_URL: .+?\]/gi, "").trim(); | ||
| if (!stripped) return false; | ||
| const parts = stripped | ||
| .split(/\n+/) | ||
| .map((s) => s.trim().toLowerCase()) | ||
| .filter(Boolean); | ||
| return parts.length > 0 && parts.every((p) => PLACEHOLDERS.has(p)); | ||
| } | ||
|
|
||
| /** | ||
| * Texto que queda guardado si la foto no se pudo bajar. Una foto sin texto | ||
| * del cliente pasa a ser solo el aviso de fallo. Si el cliente sí escribió | ||
| * algo, ese texto se conserva y el aviso va en otra línea: sigue contando | ||
| * para la detección de bots. | ||
| */ | ||
| export function textAfterImageFetchFailure(cleanText: string): string { | ||
| const caption = cleanText | ||
| .split(/\n+/) | ||
| .map((s) => s.trim()) | ||
| .filter((s) => s && s.toLowerCase() !== IMAGE_NO_CAPTION.toLowerCase()) | ||
| .join("\n"); | ||
| return caption ? `${caption}\n${IMAGE_NOT_SEEN}` : IMAGE_NOT_SEEN; | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,17 +1,36 @@ | ||
| import type { ModelMessage } from "ai"; | ||
| import type { Env } from "../env"; | ||
| import { captureIncomingMedia } from "./boveda"; | ||
| import { isZernioMediaUrl } from "./zernio"; | ||
|
|
||
| /** URL pública (el modelo la baja) o bytes ya descargados (Zernio, que exige Bearer). */ | ||
| export type ModelImageInput = string | { bytes: Uint8Array; mediaType: string }; | ||
|
|
||
| export function buildMultimodalUserMessage( | ||
| text: string | undefined, | ||
| imageUrl: string | undefined, | ||
| image?: ModelImageInput, | ||
| ): ModelMessage { | ||
| if (!imageUrl) { | ||
| if (!image) { | ||
| return { role: "user", content: text ?? "" }; | ||
| } | ||
| const imagePart = | ||
| typeof image === "string" | ||
| ? { type: "image" as const, image: new URL(image) } | ||
| : { type: "image" as const, image: image.bytes, mediaType: image.mediaType }; | ||
| return { | ||
| role: "user", | ||
| content: [ | ||
| { type: "image", image: new URL(imageUrl) }, | ||
| ...(text ? [{ type: "text" as const, text }] : []), | ||
| ], | ||
| content: [imagePart, ...(text ? [{ type: "text" as const, text }] : [])], | ||
| }; | ||
| } | ||
|
|
||
| /** | ||
| * Prepara la foto para el modelo. Las URLs de Zernio no son públicas: hay que | ||
| * bajar los bytes con el Bearer y pasarlos como imagen. Una URL de Telegram, | ||
| * Meta o el proxy firmado de WhatsApp Cloud se deja como URL. | ||
| */ | ||
| export async function describeImage(imageUrl: string, env: Env): Promise<ModelImageInput> { | ||
| if (!isZernioMediaUrl(imageUrl, env)) return imageUrl; | ||
| const captured = await captureIncomingMedia(imageUrl, env); | ||
| const mediaType = captured.contentType.startsWith("image/") ? captured.contentType : "image/jpeg"; | ||
| return { bytes: captured.bytes, mediaType }; | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,65 @@ | ||
| import type { Env } from "../env"; | ||
| import { egressFetch, sanitizeHeaderValue } from "../http/egress"; | ||
|
|
||
| /** | ||
| * Hosts a los que SÍ se les puede mandar ZERNIO_API_KEY. | ||
| * Cualquier otro host (CDN de Telegram, Graph de Meta, un webhook ajeno) | ||
| * recibe el fetch sin Authorization: la llave no sale de Zernio. | ||
| */ | ||
| const ZERNIO_SUFFIX = "zernio.com"; | ||
|
|
||
| export type ZernioEnv = Pick<Env, "ZERNIO_API_KEY" | "ZERNIO_API_BASE">; | ||
|
|
||
| export function isZernioMediaUrl(rawUrl: string, env: ZernioEnv): boolean { | ||
| let url: URL; | ||
| try { | ||
| url = new URL(rawUrl); | ||
| } catch { | ||
| return false; | ||
| } | ||
| // La llave solo viaja por HTTPS. Un http://zernio.com la filtraría en claro. | ||
| if (url.protocol !== "https:") return false; | ||
| const host = url.hostname.toLowerCase(); | ||
| if (host === ZERNIO_SUFFIX || host.endsWith(`.${ZERNIO_SUFFIX}`)) return true; | ||
| const base = env.ZERNIO_API_BASE?.trim(); | ||
| if (!base) return false; | ||
| try { | ||
| const baseUrl = new URL(base.includes("://") ? base : `https://${base}`); | ||
| return baseUrl.protocol === "https:" && host === baseUrl.hostname.toLowerCase(); | ||
| } catch { | ||
| return false; | ||
| } | ||
| } | ||
|
|
||
| function authHeaders(url: string, env: ZernioEnv): Headers { | ||
| const headers = new Headers(); | ||
| if (!isZernioMediaUrl(url, env)) return headers; | ||
| const key = sanitizeHeaderValue(env.ZERNIO_API_KEY ?? ""); | ||
| if (!key) return headers; | ||
| headers.set("Authorization", `Bearer ${key}`); | ||
| return headers; | ||
| } | ||
|
|
||
| /** | ||
| * GET de un adjunto entrante. El Bearer de Zernio se añade solo si el host | ||
| * de ESTA url es Zernio. Un redirect a otro origen se sigue sin la llave | ||
| * (el endpoint de media responde 200 con el binario; el corte es por si acaso). | ||
| */ | ||
| export async function fetchInboundMedia(url: string, env: ZernioEnv): Promise<Response> { | ||
| const headers = authHeaders(url, env); | ||
| const first = await egressFetch(url, { headers, redirect: "manual" }); | ||
| if (first.status < 300 || first.status >= 400) return first; | ||
| const loc = first.headers.get("location"); | ||
| if (!loc) return first; | ||
| let next: URL; | ||
| try { | ||
| next = new URL(loc, url); | ||
| } catch { | ||
| return first; | ||
| } | ||
| const sameOrigin = next.origin === new URL(url).origin; | ||
| return egressFetch(next, { | ||
| headers: sameOrigin ? headers : new Headers(), | ||
| redirect: "follow", | ||
| }); | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.