Skip to content

Supercharge your AI agents with data from the web and beyond. Building the library for superintelligence. 🔥

feat(api): relay structured user-facing errors from the media service (#4103)

Abimael Martell8627119f3947
diff --git a/apps/api/src/controllers/v1/scrape.ts b/apps/api/src/controllers/v1/scrape.ts
index 1d76d7d3c..99a9bc7cf 100644
--- a/apps/api/src/controllers/v1/scrape.ts
+++ b/apps/api/src/controllers/v1/scrape.ts
@@ -306,6 +306,14 @@ export async function scrapeController(
});
}
+ if (e.code === "SCRAPE_MEDIA_ACCESS_DENIED") {
+ return res.status(403).json({
+ success: false,
+ code: e.code,
+ error: e.message,
+ });
+ }
+
return res.status(e.code === "SCRAPE_TIMEOUT" ? 408 : 500).json({
success: false,
code: e.code,
diff --git a/apps/api/src/controllers/v2/scrape.ts b/apps/api/src/controllers/v2/scrape.ts
index fb2bd2c7e..32d514da1 100644
--- a/apps/api/src/controllers/v2/scrape.ts
+++ b/apps/api/src/controllers/v2/scrape.ts
@@ -458,6 +458,17 @@ export async function scrapeController(
});
}
+ if (e.code === "SCRAPE_MEDIA_ACCESS_DENIED") {
+ setSpanAttributes(span, {
+ "scrape.status_code": 403,
+ });
+ return res.status(403).json({
+ success: false,
+ code: e.code,
+ error: e.message,
+ });
+ }
+
const statusCode = e.code === "SCRAPE_TIMEOUT" ? 408 : 500;
setSpanAttributes(span, {
"scrape.status_code": statusCode,
diff --git a/apps/api/src/lib/error-serde.ts b/apps/api/src/lib/error-serde.ts
index aaa59db8e..2be6cba18 100644
--- a/apps/api/src/lib/error-serde.ts
+++ b/apps/api/src/lib/error-serde.ts
@@ -33,6 +33,7 @@ import {
BrandingNotSupportedError,
AudioUnsupportedUrlError,
VideoUnsupportedUrlError,
+ MediaAccessDeniedError,
XTwitterConfigurationError,
} from "../scraper/scrapeURL/error";
import { UnsafeDomainBlockedError } from "./threat-protection/error";
@@ -70,6 +71,7 @@ const errorMap: Record<ErrorCodes, any> = {
CRAWL_DENIAL: CrawlDenialError,
SCRAPE_AUDIO_UNSUPPORTED_URL: AudioUnsupportedUrlError,
SCRAPE_VIDEO_UNSUPPORTED_URL: VideoUnsupportedUrlError,
+ SCRAPE_MEDIA_ACCESS_DENIED: MediaAccessDeniedError,
SCRAPE_X_TWITTER_CONFIGURATION_ERROR: XTwitterConfigurationError,
MAP_FAILED: MapFailedError,
unsafe_domain_blocked: UnsafeDomainBlockedError,
diff --git a/apps/api/src/lib/error.ts b/apps/api/src/lib/error.ts
index d77a878f8..f906e7ee2 100644
--- a/apps/api/src/lib/error.ts
+++ b/apps/api/src/lib/error.ts
@@ -28,6 +28,7 @@ export type ErrorCodes =
| "AGENT_INDEX_ONLY"
| "SCRAPE_AUDIO_UNSUPPORTED_URL"
| "SCRAPE_VIDEO_UNSUPPORTED_URL"
+ | "SCRAPE_MEDIA_ACCESS_DENIED"
| "SCRAPE_X_TWITTER_CONFIGURATION_ERROR"
| "PARSE_UNSUPPORTED_OPTIONS"
| "CRAWL_DENIAL"
diff --git a/apps/api/src/scraper/scrapeURL/error.ts b/apps/api/src/scraper/scrapeURL/error.ts
index 5f90f25cc..1e28043bd 100644
--- a/apps/api/src/scraper/scrapeURL/error.ts
+++ b/apps/api/src/scraper/scrapeURL/error.ts
@@ -535,6 +535,52 @@ export class AudioUnsupportedUrlError extends TransportableError {
}
}
+export class MediaAccessDeniedError extends TransportableError {
+ constructor(message?: string) {
+ super(
+ "SCRAPE_MEDIA_ACCESS_DENIED",
+ message ??
+ "Access to the requested content was denied, so it cannot be retrieved.",
+ );
+ }
+
+ serialize() {
+ return super.serialize();
+ }
+
+ static deserialize(
+ _: ErrorCodes,
+ data: ReturnType<typeof this.prototype.serialize>,
+ ) {
+ const x = new MediaAccessDeniedError(data.message);
+ x.stack = data.stack;
+ return x;
+ }
+}
+
+const MAX_MEDIA_SERVICE_MESSAGE_LENGTH = 500;
+
+// The media service reports terminal, user-facing failures as a structured
+// error body ({ detail: { code, message } }, in contrast to its string detail
+// for internal failures); relay the curated message to the user.
+export function throwIfMediaAccessDenied(errorBody: unknown): void {
+ if (
+ typeof errorBody === "object" &&
+ errorBody !== null &&
+ "detail" in errorBody &&
+ typeof errorBody.detail === "object" &&
+ errorBody.detail !== null &&
+ "code" in errorBody.detail &&
+ typeof errorBody.detail.code === "string" &&
+ "message" in errorBody.detail &&
+ typeof errorBody.detail.message === "string"
+ ) {
+ throw new MediaAccessDeniedError(
+ errorBody.detail.message.slice(0, MAX_MEDIA_SERVICE_MESSAGE_LENGTH),
+ );
+ }
+}
+
export class VideoUnsupportedUrlError extends TransportableError {
constructor(message?: string) {
super(
diff --git a/apps/api/src/scraper/scrapeURL/postprocessors/youtube.ts b/apps/api/src/scraper/scrapeURL/postprocessors/youtube.ts
index e05ffe442..f0733f3fe 100644
--- a/apps/api/src/scraper/scrapeURL/postprocessors/youtube.ts
+++ b/apps/api/src/scraper/scrapeURL/postprocessors/youtube.ts
@@ -2,6 +2,7 @@ import { config } from "../../../config";
import type { BrowserCookie, Meta } from "..";
import type { Postprocessor } from ".";
import type { EngineScrapeResult } from "../engines";
+import { throwIfMediaAccessDenied } from "../error";
type YouTubeMetadataResponse = {
thumbnail_image: {
@@ -117,6 +118,7 @@ async function getYouTubeMetadata(
const error = await response
.json()
.catch(() => ({ detail: "Unknown error" }));
+ throwIfMediaAccessDenied(error);
throw new Error(`YouTube metadata extraction failed: ${error.detail}`);
}
diff --git a/apps/api/src/scraper/scrapeURL/transformers/__tests__/audio.test.ts b/apps/api/src/scraper/scrapeURL/transformers/__tests__/audio.test.ts
index 78cc4ccbf..ec6591116 100644
--- a/apps/api/src/scraper/scrapeURL/transformers/__tests__/audio.test.ts
+++ b/apps/api/src/scraper/scrapeURL/transformers/__tests__/audio.test.ts
@@ -1,4 +1,5 @@
import { fetchAudio } from "../audio";
+import { MediaAccessDeniedError } from "../../error";
import { config } from "../../../../config";
describe("fetchAudio lockdown guard", () => {
@@ -109,6 +110,82 @@ describe("fetchAudio lockdown guard", () => {
});
});
+ it("relays the message when the service reports a structured user-facing error", async () => {
+ const fetchSpy = vi.fn(async (url: string, _init?: RequestInit) => {
+ if (url.endsWith("/supported-urls")) {
+ return {
+ ok: true,
+ json: async () => ({ regex: "https://example\\.com/audio" }),
+ };
+ }
+
+ return {
+ ok: false,
+ status: 403,
+ json: async () => ({
+ detail: {
+ code: "content_unavailable",
+ message:
+ "This content requires an authenticated session to access.",
+ },
+ }),
+ };
+ });
+ global.fetch = fetchSpy as any;
+ config.AVGRAB_SERVICE_URL = "https://avgrab.example";
+
+ const meta: any = {
+ url: "https://example.com/audio",
+ options: {
+ lockdown: false,
+ formats: [{ type: "audio" }],
+ },
+ logger: { warn: vi.fn(), info: vi.fn(), debug: vi.fn() },
+ };
+
+ const error = await fetchAudio(meta, {} as any).catch(e => e);
+ expect(error).toBeInstanceOf(MediaAccessDeniedError);
+ expect(error.code).toBe("SCRAPE_MEDIA_ACCESS_DENIED");
+ expect(error.message).toBe(
+ "This content requires an authenticated session to access.",
+ );
+ });
+
+ it("keeps the generic error for other service failures", async () => {
+ const fetchSpy = vi.fn(async (url: string, _init?: RequestInit) => {
+ if (url.endsWith("/supported-urls")) {
+ return {
+ ok: true,
+ json: async () => ({ regex: "https://example\\.com/audio" }),
+ };
+ }
+
+ return {
+ ok: false,
+ status: 400,
+ json: async () => ({ detail: "Download failed: some other error" }),
+ };
+ });
+ global.fetch = fetchSpy as any;
+ config.AVGRAB_SERVICE_URL = "https://avgrab.example";
+
+ const meta: any = {
+ url: "https://example.com/audio",
+ options: {
+ lockdown: false,
+ formats: [{ type: "audio" }],
+ },
+ logger: { warn: vi.fn(), info: vi.fn(), debug: vi.fn() },
+ };
+
+ const error = await fetchAudio(meta, {} as any).catch(e => e);
+ expect(error).toBeInstanceOf(Error);
+ expect(error).not.toBeInstanceOf(MediaAccessDeniedError);
+ expect(error.message).toBe(
+ "Audio download failed: Download failed: some other error",
+ );
+ });
+
it("omits cookies from the avgrab request when no audio cookies are available", async () => {
const fetchSpy = mockSuccessfulAvgrab();
diff --git a/apps/api/src/scraper/scrapeURL/transformers/audio.ts b/apps/api/src/scraper/scrapeURL/transformers/audio.ts
index 046078cb6..977d5ab26 100644
--- a/apps/api/src/scraper/scrapeURL/transformers/audio.ts
+++ b/apps/api/src/scraper/scrapeURL/transformers/audio.ts
@@ -2,7 +2,7 @@ import { Meta } from "..";
import { Document } from "../../../controllers/v2/types";
import { config } from "../../../config";
import { hasFormatOfType } from "../../../lib/format-utils";
-import { AudioUnsupportedUrlError } from "../error";
+import { AudioUnsupportedUrlError, throwIfMediaAccessDenied } from "../error";
let cachedUrlRegex: RegExp | null = null;
let cacheTimestamp = 0;
@@ -78,6 +78,7 @@ export async function fetchAudio(
const error = await response
.json()
.catch(() => ({ detail: "Unknown error" }));
+ throwIfMediaAccessDenied(error);
throw new Error(`Audio download failed: ${error.detail}`);
}
diff --git a/apps/api/src/scraper/scrapeURL/transformers/video.ts b/apps/api/src/scraper/scrapeURL/transformers/video.ts
index 63880558c..b45a06e94 100644
--- a/apps/api/src/scraper/scrapeURL/transformers/video.ts
+++ b/apps/api/src/scraper/scrapeURL/transformers/video.ts
@@ -2,6 +2,7 @@ import { Meta } from "..";
import { Document, VideoItem } from "../../../controllers/v2/types";
import { config } from "../../../config";
import { hasFormatOfType } from "../../../lib/format-utils";
+import { throwIfMediaAccessDenied } from "../error";
let cachedUrlRegex: RegExp | null = null;
let cacheTimestamp = 0;
@@ -176,6 +177,7 @@ async function fetchLegacyVideoIfSupported(meta: Meta, document: Document) {
const error = await response
.json()
.catch(() => ({ detail: "Unknown error" }));
+ throwIfMediaAccessDenied(error);
throw new Error(`Video download failed: ${error.detail}`);
}