Supercharge your AI agents with data from the web and beyond. Building the library for superintelligence. π₯
TypeScript aiai-agentsai-crawlerai-scrapingai-searchcrawlerdata-extractionhtml-to-markdownllmmarkdownscraperscrapingweb-crawlerweb-dataweb-data-extractionweb-scraperweb-scrapingweb-searchwebscraping
feat(api): Implement fire-privacy (#3525)
Abimael Martellcab42b1d7a65
diff --git a/apps/api/knip.config.ts b/apps/api/knip.config.tsindex 4f113aed7..ee1316465 100644--- a/apps/api/knip.config.ts+++ b/apps/api/knip.config.ts@@ -19,6 +19,8 @@ const config: KnipConfig = {"src/services/billing/auto_charge.ts","src/services/billing/issue_credits.ts","src/services/billing/stripe.ts",+ // Superseded by the integration proxy added in #3520; kept for now.+ "src/controllers/v0/admin/rotate-api-key.ts",],ignoreDependencies: ["undici-types", "stripe"],};diff --git a/apps/api/src/__tests__/snips/v2/scrape-pii.test.ts b/apps/api/src/__tests__/snips/v2/scrape-pii.test.tsnew file mode 100644index 000000000..8d7dc43dd--- /dev/null+++ b/apps/api/src/__tests__/snips/v2/scrape-pii.test.ts@@ -0,0 +1,210 @@+import { ALLOW_TEST_SUITE_WEBSITE, describeIf, TEST_PRODUCTION } from "../lib";+import {+ Identity,+ idmux,+ scrape,+ scrapeRaw,+ scrapeTimeout,+ scrapeWithFailure,+} from "./lib";++let identity: Identity;++beforeAll(async () => {+ identity = await idmux({+ name: "v2-scrape-pii",+ concurrency: 100,+ credits: 1000000,+ });+}, 10000 + scrapeTimeout);++describeIf(ALLOW_TEST_SUITE_WEBSITE)("V2 Scrape redactPII (schema)", () => {+ it.concurrent(+ "rejects redactPII: true when `pii` is not in formats",+ async () => {+ const res = await scrapeWithFailure(+ {+ url: "https://firecrawl.dev",+ formats: ["markdown"],+ redactPII: true,+ },+ identity,+ );++ expect(res.success).toBe(false);+ expect(res.error).toMatch(/redactPII requires `pii`/);+ },+ scrapeTimeout,+ );++ it.concurrent(+ "rejects redactPII with non-boolean value",+ async () => {+ const res = await scrapeRaw(+ {+ url: "https://firecrawl.dev",+ formats: ["markdown", "pii"],+ // typed as boolean, but we want to confirm the API rejects strings.+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ redactPII: "yes" as any,+ },+ identity,+ );++ expect(res.statusCode).toBe(400);+ expect(res.body.success).toBe(false);+ },+ scrapeTimeout,+ );++ it.concurrent(+ "accepts redactPII as an options object with mode/entities/replaceStyle",+ async () => {+ const res = await scrapeRaw(+ {+ url: "https://firecrawl.dev",+ formats: ["markdown", "pii"],+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ redactPII: {+ mode: "accurate",+ entities: ["EMAIL", "PHONE"],+ replaceStyle: "tag",+ } as any,+ },+ identity,+ );++ // The page may not have PII (so spans can be empty), but the+ // request itself must validate and the response must include+ // the `pii` block.+ expect(res.statusCode).toBe(200);+ expect(res.body.success).toBe(true);+ expect(res.body.data.pii).toBeDefined();+ },+ scrapeTimeout,+ );++ it.concurrent(+ "rejects an unknown mode value",+ async () => {+ const res = await scrapeRaw(+ {+ url: "https://firecrawl.dev",+ formats: ["markdown", "pii"],+ // "model" is the fire-privacy internal mode, not the+ // public surface β must be rejected.+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ redactPII: { mode: "model" } as any,+ },+ identity,+ );++ expect(res.statusCode).toBe(400);+ expect(res.body.success).toBe(false);+ },+ scrapeTimeout,+ );+});++describeIf(TEST_PRODUCTION)("V2 Scrape redactPII (e2e)", () => {+ it(+ "returns pii block with spans and replaces document.markdown with redacted content",+ async () => {+ // A page with named entities and an email so heuristic recognizers fire+ // even when fire-privacy is in heuristics-only mode.+ const data = await scrape(+ {+ url: "https://en.wikipedia.org/wiki/Alan_Turing",+ formats: ["markdown", "pii"],+ redactPII: true,+ },+ identity,+ );++ // Scrape always succeeds regardless of fire-privacy outcome.+ expect(data.pii).toBeDefined();+ expect(["ok", "skipped", "failed"]).toContain(data.pii!.status);++ if (data.pii!.status === "ok") {+ expect(typeof data.pii!.redactedMarkdown).toBe("string");+ // document.markdown is the redacted version, not the raw one.+ expect(data.markdown).toBe(data.pii!.redactedMarkdown);++ expect(data.pii!.spans.length).toBeGreaterThan(0);+ expect(data.pii!.spans[0]).toEqual(+ expect.objectContaining({+ start: expect.any(Number),+ end: expect.any(Number),+ kind: expect.any(String),+ }),+ );+ // counts should sum to the number of spans with a mapped entity.+ const mappedSpanCount = data.pii!.spans.filter(s => s.entity).length;+ const totalCount = Object.values(data.pii!.counts ?? {}).reduce(+ (a, b) => a + (b ?? 0),+ 0,+ );+ expect(totalCount).toBe(mappedSpanCount);+ } else if (data.pii!.status === "failed") {+ expect(data.pii!.redactedMarkdown).toBeNull();+ expect(data.pii!.reason).toBeDefined();+ // Fail closed: no raw markdown leaks through when redaction failed.+ expect(data.markdown).toBeUndefined();+ }+ },+ scrapeTimeout,+ );++ it(+ "fails closed when fire-privacy is unreachable β pii.status is failed, markdown is empty",+ async () => {+ const data = await scrape(+ {+ url: "https://firecrawl.dev",+ formats: ["markdown", "pii"],+ redactPII: true,+ },+ identity,+ );++ expect(data.pii).toBeDefined();+ // We don't pin to a specific outcome β could be ok if fire-privacy+ // is reachable in this environment, or one of skipped/failed otherwise.+ // The contract is: scrape still succeeds (no error response).+ expect(["ok", "skipped", "failed"]).toContain(data.pii!.status);++ if (data.pii!.status === "ok") {+ expect(data.markdown).toBe(data.pii!.redactedMarkdown);+ } else {+ expect(data.pii!.reason).toBeDefined();+ // Markdown is empty on failed / skipped-with-null-redacted; on+ // upstream_skipped / empty_input it passes through (equal to+ // redactedMarkdown). Verify the invariant: markdown matches+ // redactedMarkdown (or is fail-closed empty).+ if (data.pii!.redactedMarkdown === null) {+ expect(data.markdown).toBe("");+ } else {+ expect(data.markdown).toBe(data.pii!.redactedMarkdown);+ }+ }+ },+ scrapeTimeout,+ );++ it(+ "omits pii block when redactPII is false even if `pii` is in formats",+ async () => {+ const data = await scrape(+ {+ url: "https://firecrawl.dev",+ formats: ["markdown", "pii"],+ },+ identity,+ );++ expect(typeof data.markdown).toBe("string");+ expect(data.pii).toBeUndefined();+ },+ scrapeTimeout,+ );+});diff --git a/apps/api/src/config.ts b/apps/api/src/config.tsindex 181578950..e6209ea62 100644--- a/apps/api/src/config.ts+++ b/apps/api/src/config.ts@@ -284,6 +284,10 @@ const configSchema = z.object({// Audio (avgrab)AVGRAB_SERVICE_URL: z.string().optional(),+ // PII Redaction (fire-privacy)+ FIRE_PRIVACY_URL: z.string().optional(),+ FIRE_PRIVACY_TIMEOUT_MS: z.coerce.number().int().positive().default(5000),+NUQ_PREFETCH_WORKER_HEARTBEAT_URL: z.string().optional(),ZDRCLEANER_HEARTBEAT_URL: z.string().optional(),diff --git a/apps/api/src/controllers/v2/__tests__/redactPII-schema.test.ts b/apps/api/src/controllers/v2/__tests__/redactPII-schema.test.tsnew file mode 100644index 000000000..12e27c1d1--- /dev/null+++ b/apps/api/src/controllers/v2/__tests__/redactPII-schema.test.ts@@ -0,0 +1,233 @@+import { scrapeRequestSchema } from "../types";++describe("v2 scrapeRequestSchema β redactPII", () => {+ const baseUrl = "https://example.com";++ // ---- boolean form -------------------------------------------------------++ it("accepts redactPII: true with `pii` in formats", () => {+ const result = scrapeRequestSchema.safeParse({+ url: baseUrl,+ formats: ["markdown", "pii"],+ redactPII: true,+ });+ expect(result.success).toBe(true);+ if (result.success) {+ // `true` normalizes to a defaults object via the Zod transform.+ expect(result.data.redactPII).toMatchObject({+ mode: "accurate",+ replaceStyle: "tag",+ });+ }+ });++ it("accepts redactPII: false with `pii` in formats", () => {+ const result = scrapeRequestSchema.safeParse({+ url: baseUrl,+ formats: ["markdown", "pii"],+ redactPII: false,+ });+ expect(result.success).toBe(true);+ if (result.success) {+ expect(result.data.redactPII).toBeUndefined();+ }+ });++ it("accepts redactPII unset (treated as off)", () => {+ const result = scrapeRequestSchema.safeParse({+ url: baseUrl,+ formats: ["markdown"],+ });+ expect(result.success).toBe(true);+ if (result.success) {+ expect(result.data.redactPII).toBeUndefined();+ }+ });++ it("rejects redactPII: true without `pii` in formats", () => {+ const result = scrapeRequestSchema.safeParse({+ url: baseUrl,+ formats: ["markdown"],+ redactPII: true,+ });+ expect(result.success).toBe(false);+ if (!result.success) {+ const messages = result.error.issues.map(i => i.message).join("\n");+ expect(messages).toMatch(/redactPII requires `pii`/);+ }+ });++ // ---- object form --------------------------------------------------------++ it("accepts an explicit mode in the object form", () => {+ const result = scrapeRequestSchema.safeParse({+ url: baseUrl,+ formats: ["markdown", "pii"],+ redactPII: { mode: "aggressive" },+ });+ expect(result.success).toBe(true);+ if (result.success) {+ expect(result.data.redactPII).toMatchObject({+ mode: "aggressive",+ replaceStyle: "tag",+ });+ }+ });++ it("accepts each documented mode", () => {+ for (const mode of ["accurate", "aggressive", "fast"] as const) {+ const result = scrapeRequestSchema.safeParse({+ url: baseUrl,+ formats: ["markdown", "pii"],+ redactPII: { mode },+ });+ expect(result.success).toBe(true);+ if (result.success && result.data.redactPII) {+ expect(result.data.redactPII.mode).toBe(mode);+ }+ }+ });++ it("rejects an unknown mode", () => {+ const result = scrapeRequestSchema.safeParse({+ url: baseUrl,+ formats: ["markdown", "pii"],+ redactPII: { mode: "model" }, // internal mode name, not exposed+ });+ expect(result.success).toBe(false);+ });++ it("accepts an entities allowlist", () => {+ const result = scrapeRequestSchema.safeParse({+ url: baseUrl,+ formats: ["markdown", "pii"],+ redactPII: { entities: ["EMAIL", "PHONE"] },+ });+ expect(result.success).toBe(true);+ if (result.success && result.data.redactPII) {+ expect(result.data.redactPII.entities).toEqual(["EMAIL", "PHONE"]);+ }+ });++ it("rejects an unknown entity", () => {+ const result = scrapeRequestSchema.safeParse({+ url: baseUrl,+ formats: ["markdown", "pii"],+ redactPII: { entities: ["EMAIL", "NICKNAME"] },+ });+ expect(result.success).toBe(false);+ });++ it("accepts each replaceStyle", () => {+ for (const replaceStyle of ["tag", "mask", "remove"] as const) {+ const result = scrapeRequestSchema.safeParse({+ url: baseUrl,+ formats: ["markdown", "pii"],+ redactPII: { replaceStyle },+ });+ expect(result.success).toBe(true);+ if (result.success && result.data.redactPII) {+ expect(result.data.redactPII.replaceStyle).toBe(replaceStyle);+ }+ }+ });++ it("rejects unknown fields in the object form (strict)", () => {+ const result = scrapeRequestSchema.safeParse({+ url: baseUrl,+ formats: ["markdown", "pii"],+ redactPII: { mode: "accurate", typo: "yes" },+ });+ expect(result.success).toBe(false);+ });++ it("requires `pii` in formats even with the object form", () => {+ const result = scrapeRequestSchema.safeParse({+ url: baseUrl,+ formats: ["markdown"],+ redactPII: { mode: "aggressive" },+ });+ expect(result.success).toBe(false);+ if (!result.success) {+ const messages = result.error.issues.map(i => i.message).join("\n");+ expect(messages).toMatch(/redactPII requires `pii`/);+ }+ });++ // ---- type rejection -----------------------------------------------------++ it("rejects redactPII as a string", () => {+ const result = scrapeRequestSchema.safeParse({+ url: baseUrl,+ formats: ["markdown", "pii"],+ redactPII: "yes",+ });+ expect(result.success).toBe(false);+ });++ it("rejects redactPII as a number", () => {+ const result = scrapeRequestSchema.safeParse({+ url: baseUrl,+ formats: ["markdown", "pii"],+ redactPII: 1,+ });+ expect(result.success).toBe(false);+ });++ // ---- onlyMainContent ------------------------------------------------------++ it("preserves explicit onlyMainContent: false when redactPII is enabled", () => {+ const result = scrapeRequestSchema.safeParse({+ url: baseUrl,+ formats: ["markdown", "pii"],+ redactPII: true,+ onlyMainContent: false,+ });+ expect(result.success).toBe(true);+ if (result.success) {+ expect(result.data.onlyMainContent).toBe(false);+ }+ });++ it("keeps the default onlyMainContent: true when redactPII is enabled", () => {+ const result = scrapeRequestSchema.safeParse({+ url: baseUrl,+ formats: ["markdown", "pii"],+ redactPII: true,+ });+ expect(result.success).toBe(true);+ if (result.success) {+ expect(result.data.onlyMainContent).toBe(true);+ }+ });++ it("leaves onlyMainContent alone when redactPII is unset", () => {+ const result = scrapeRequestSchema.safeParse({+ url: baseUrl,+ formats: ["markdown"],+ onlyMainContent: false,+ });+ expect(result.success).toBe(true);+ if (result.success) {+ expect(result.data.onlyMainContent).toBe(false);+ }+ });++ // ---- formats schema -----------------------------------------------------++ it("accepts `pii` as a string format", () => {+ const result = scrapeRequestSchema.safeParse({+ url: baseUrl,+ formats: ["pii"],+ });+ expect(result.success).toBe(true);+ });++ it("accepts `pii` as an object format", () => {+ const result = scrapeRequestSchema.safeParse({+ url: baseUrl,+ formats: [{ type: "pii" }],+ });+ expect(result.success).toBe(true);+ });+});diff --git a/apps/api/src/controllers/v2/types.ts b/apps/api/src/controllers/v2/types.tsindex 3eb06ea1b..95ba5fb52 100644--- a/apps/api/src/controllers/v2/types.ts+++ b/apps/api/src/controllers/v2/types.ts@@ -439,7 +439,8 @@ export type FormatObject =| QueryFormatWithOptions| { type: "branding" }| { type: "audio" }- | { type: "video" };+ | { type: "video" }+ | { type: "pii" };const pdfModeSchema = z.enum(["fast", "auto", "ocr"]);@@ -538,6 +539,51 @@ const locationSchema = z}).optional();+// Unified entity taxonomy exposed to callers. Maps to fire-privacy's+// internal span kinds (PRIVATE_PERSON / EMAIL_ADDRESS / ACCOUNT_NUMBER /+// etc.) inside the fire-privacy client. Names chosen to match the public+// surface; if a caller asks for "EMAIL" they get email-shaped spans+// regardless of which recognizer found them.+const REDACT_PII_ENTITIES = [+ "PERSON",+ "EMAIL",+ "PHONE",+ "LOCATION",+ "FINANCIAL",+ "SECRET",+] as const;+const redactPIIEntitySchema = z.enum(REDACT_PII_ENTITIES);+export type RedactPIIEntity = z.infer<typeof redactPIIEntitySchema>;++// Public mode names. Mapped to fire-privacy internal modes+// (model / both / heuristics) inside the client; the internal "precise"+// mode is intentionally not exposed.+//+// - accurate (default): model only. Best precision (0.87), F1 (0.73).+// Cleanest redacted output.+// - aggressive: model + Presidio + spaCy. Higher recall (0.73) at the+// cost of precision (0.68). Compliance use cases.+// - fast: Presidio only, no model call. ~2x throughput, lower F1.+const redactPIIOptionsSchema = z.strictObject({+ mode: z.enum(["accurate", "aggressive", "fast"]).default("accurate"),+ entities: z.array(redactPIIEntitySchema).optional(),+ replaceStyle: z.enum(["tag", "mask", "remove"]).default("tag"),+});+export type RedactPIIOptions = z.infer<typeof redactPIIOptionsSchema>;++// Boolean is the common case. Object form is for callers who want to+// tune. After parse: `true` normalizes to defaults; `false` / unset+// β `undefined`. Downstream code only has to check truthiness.+const redactPIISchema = z+ .union([z.boolean(), redactPIIOptionsSchema])+ .optional()+ .transform(v => {+ if (v === undefined || v === false) return undefined;+ if (v === true) return redactPIIOptionsSchema.parse({});+ return v;+ });+// inferred shape: RedactPIIOptions | undefined after the transform+const baseScrapeOptions = z.strictObject({formats: z.preprocess(@@ -568,6 +614,7 @@ const baseScrapeOptions = z.strictObject({queryFormatWithOptions,z.strictObject({ type: z.literal("audio") }),z.strictObject({ type: z.literal("video") }),+ z.strictObject({ type: z.literal("pii") }),]).array().optional()@@ -612,6 +659,7 @@ const baseScrapeOptions = z.strictObject({minAge: z.int().gte(0).optional(),storeInCache: z.boolean().prefault(true),lockdown: z.boolean().prefault(false),+ redactPII: redactPIISchema,profile: z.object({@@ -644,6 +692,17 @@ const waitForRefineOpts = {path: ["waitFor"],};+const redactPIIRefine = (+ obj?: Pick<ScrapeOptionsBase, "redactPII" | "formats">,+): boolean => {+ if (!obj || !obj.redactPII) return true;+ return !!obj.formats?.some(f => f.type === "pii");+};+const redactPIIRefineOpts = {+ message: "redactPII requires `pii` to be included in formats",+ path: ["redactPII"],+};+// Base transform function that handles both nullable and non-nullable cases// Uses generic type to preserve all fields from extended schemasconst extractTransformImpl = <T extends ScrapeOptionsBase | undefined>(@@ -717,6 +776,7 @@ export const scrapeOptions = strictWithMessage(baseScrapeOptions)},).refine(waitForRefine, waitForRefineOpts)+ .refine(redactPIIRefine, redactPIIRefineOpts).transform(extractTransformRequired);export type BaseScrapeOptions = z.infer<typeof baseScrapeOptions>;@@ -800,6 +860,10 @@ const extractOptions = zx => (x.scrapeOptions ? waitForRefine(x.scrapeOptions) : true),waitForRefineOpts,)+ .refine(+ x => (x.scrapeOptions ? redactPIIRefine(x.scrapeOptions) : true),+ redactPIIRefineOpts,+ ).transform(x => ({...x,scrapeOptions: extractTransform(x.scrapeOptions),@@ -870,6 +934,7 @@ const scrapeRequestSchemaBase = baseScrapeOptions.extend({export const scrapeRequestSchema = strictWithMessage(scrapeRequestSchemaBase).refine(waitForRefine, waitForRefineOpts)+ .refine(redactPIIRefine, redactPIIRefineOpts).transform(extractTransformRequired);export type ScrapeRequest = z.infer<typeof scrapeRequestSchema>;@@ -927,6 +992,7 @@ const parseRequestSchemaBase = baseScrapeOptions.extend({export const parseRequestSchema = strictWithMessage(parseRequestSchemaBase).refine(waitForRefine, waitForRefineOpts)+ .refine(redactPIIRefine, redactPIIRefineOpts).transform(x => {const { file, ...scrapeLike } = x;return {@@ -960,6 +1026,7 @@ export const batchScrapeRequestSchema = strictWithMessage(batchScrapeRequestSchemaBase,).refine(waitForRefine, waitForRefineOpts)+ .refine(redactPIIRefine, redactPIIRefineOpts).transform(extractTransformRequired);const batchScrapeRequestSchemaNoURLValidationBase = baseScrapeOptions.extend({@@ -984,6 +1051,7 @@ export const batchScrapeRequestSchemaNoURLValidation = strictWithMessage(batchScrapeRequestSchemaNoURLValidationBase,).refine(waitForRefine, waitForRefineOpts)+ .refine(redactPIIRefine, redactPIIRefineOpts).transform(extractTransformRequired);export type BatchScrapeRequest = z.infer<typeof batchScrapeRequestSchema>;@@ -1048,6 +1116,7 @@ const crawlRequestSchemaBase = crawlerOptions.extend({export const crawlRequestSchema = strictWithMessage(crawlRequestSchemaBase).refine(x => waitForRefine(x.scrapeOptions), waitForRefineOpts)+ .refine(x => redactPIIRefine(x.scrapeOptions), redactPIIRefineOpts).transform(x => {const scrapeOptionsValue = x.scrapeOptions ?? baseScrapeOptions.parse({});return {@@ -1104,6 +1173,58 @@ export const mapRequestSchema = strictWithMessage(mapRequestSchemaBase);export type MapRequest = z.infer<typeof mapRequestSchema>;export type MapRequestInput = z.input<typeof mapRequestSchema>;+export type PIISource = "model" | "heuristics" | "unknown";++export type PIISpan = {+ start: number;+ end: number;+ // Unified entity bucket. Present when `kind` maps onto one of the public+ // entity buckets; omitted when fire-privacy returned a recognizer kind we+ // don't expose (e.g. ORGANIZATION, DATE_TIME). Spans without an entity+ // are dropped under any `entities` allowlist.+ entity?: RedactPIIEntity;+ // Granular recognizer label from fire-privacy (e.g. PRIVATE_PERSON,+ // EMAIL_ADDRESS, ACCOUNT_NUMBER). Useful for audit / debugging; prefer+ // `entity` for taxonomy-level checks.+ kind: string;+ source: PIISource;+ // Confidence in [0, 1] when fire-privacy returned a score. Omitted when+ // the recognizer didn't supply one.+ score?: number;+};++// `ok` β redaction completed; redactedMarkdown is the result.+// `skipped` β redaction was not performed; see `reason` for why.+// redactedMarkdown may be the original text or null.+// `failed` β redaction was attempted but did not produce a usable result;+// see `reason`. redactedMarkdown is null.+type PIIStatus = "ok" | "skipped" | "failed";++// Why redaction was skipped or failed. Always set when status !== "ok".+// empty_input β no markdown to redact, or markdown was whitespace+// too_large β input exceeded the redaction-side byte ceiling+// upstream_skipped β fire-privacy reported model_status: "skipped"+// service_unavailable β fire-privacy returned 503+// timeout β request exceeded the redaction timeout budget+// error β any other failure (5xx, invalid JSON, network)+export type PIIReason =+ | "empty_input"+ | "too_large"+ | "upstream_skipped"+ | "service_unavailable"+ | "timeout"+ | "error";++export type PIIBlock = {+ status: PIIStatus;+ reason?: PIIReason;+ redactedMarkdown: string | null;+ spans: PIISpan[];+ // Count of spans per public entity bucket. Spans whose `kind` doesn't+ // map onto a bucket are not counted. Only non-zero entries are present.+ counts: Partial<Record<RedactPIIEntity, number>>;+};+export type Document = {title?: string;description?: string;@@ -1123,6 +1244,7 @@ export type Document = {highlights?: string;branding?: BrandingProfile;warning?: string;+ pii?: PIIBlock;attributes?: {selector: string;attribute: string;diff --git a/apps/api/src/lib/fire-privacy-chunker.test.ts b/apps/api/src/lib/fire-privacy-chunker.test.tsnew file mode 100644index 000000000..8c88ec8f0--- /dev/null+++ b/apps/api/src/lib/fire-privacy-chunker.test.ts@@ -0,0 +1,102 @@+import { chunkMarkdown, DEFAULT_MAX_CHARS } from "./fire-privacy-chunker";++describe("chunkMarkdown", () => {+ it("returns a single chunk for short input", () => {+ const text = "Hello world.\n\nThis is short.";+ const chunks = chunkMarkdown(text);+ expect(chunks).toHaveLength(1);+ expect(chunks[0].text).toBe(text);+ expect(chunks[0].start).toBe(0);+ });++ it("returns empty array for empty input", () => {+ expect(chunkMarkdown("")).toEqual([]);+ });++ it("preserves exact content across all chunks (concat=identity)", () => {+ const para = "Sentence one. Sentence two. Sentence three.\n\n";+ const text = para.repeat(2000); // ~88KB β forces multiple chunks+ const chunks = chunkMarkdown(text);++ expect(chunks.length).toBeGreaterThan(1);+ expect(chunks.map(c => c.text).join("")).toBe(text);+ // Start offsets line up with cumulative chunk lengths+ let cursor = 0;+ for (const c of chunks) {+ expect(c.start).toBe(cursor);+ cursor += c.text.length;+ }+ });++ it("never exceeds maxChars per chunk", () => {+ const text = "x".repeat(100_000); // no natural break points+ const chunks = chunkMarkdown(text, { maxChars: 1_000 });+ for (const c of chunks) {+ expect(c.text.length).toBeLessThanOrEqual(1_000);+ }+ });++ it("splits at paragraph boundaries when available", () => {+ // Two ~20K-char paragraphs separated by \n\n. With maxChars=28K, the+ // first chunk should end at the paragraph break, not partway through+ // either paragraph.+ const para1 = "A".repeat(20_000);+ const para2 = "B".repeat(20_000);+ const text = `${para1}\n\n${para2}`;+ const chunks = chunkMarkdown(text, { maxChars: 28_000 });++ expect(chunks.length).toBeGreaterThanOrEqual(2);+ // First chunk ends at the paragraph break β its tail should be the+ // two newlines, and the next chunk should start with 'B'.+ expect(chunks[0].text.endsWith("\n\n")).toBe(true);+ expect(chunks[1].text.startsWith("B")).toBe(true);+ });++ it("falls back to sentence boundary when no paragraph break is in range", () => {+ const sentence = "X".repeat(99) + ". ";+ const text = sentence.repeat(300); // ~30K, no \n+ const chunks = chunkMarkdown(text, { maxChars: 10_000 });++ expect(chunks.length).toBeGreaterThan(1);+ for (let i = 0; i < chunks.length - 1; i++) {+ // Each non-final chunk should end at ". " (sentence end + space)+ expect(/[.!?]\s$/.test(chunks[i].text)).toBe(true);+ }+ });++ it("hard-cuts when no safe boundary exists in the upper half", () => {+ // Single 50K-char run with no whitespace or punctuation.+ const text = "z".repeat(50_000);+ const chunks = chunkMarkdown(text, { maxChars: 10_000 });+ expect(chunks.length).toBeGreaterThan(1);+ expect(chunks.map(c => c.text).join("")).toBe(text);+ });++ it("enforces maxBytes for non-ASCII input", () => {+ // Emoji = 4 bytes each in UTF-8. 1000 emoji = 4000 bytes, 1000 chars.+ const text = "π".repeat(1000);+ const chunks = chunkMarkdown(text, { maxChars: 10_000, maxBytes: 1_000 });+ for (const c of chunks) {+ expect(new TextEncoder().encode(c.text).length).toBeLessThanOrEqual(+ 1_000,+ );+ }+ expect(chunks.map(c => c.text).join("")).toBe(text);+ });++ it("uses sensible default for max chunk size", () => {+ // Default should leave headroom below fire-privacy's 32K model window.+ expect(DEFAULT_MAX_CHARS).toBeLessThan(32_000);+ expect(DEFAULT_MAX_CHARS).toBeGreaterThanOrEqual(20_000);+ });++ it("rejects non-positive maxChars (would otherwise infinite-loop)", () => {+ expect(() => chunkMarkdown("abc", { maxChars: 0 })).toThrow(RangeError);+ expect(() => chunkMarkdown("abc", { maxChars: -1 })).toThrow(RangeError);+ });++ it("rejects non-positive maxBytes", () => {+ expect(() => chunkMarkdown("abc", { maxBytes: 0 })).toThrow(RangeError);+ expect(() => chunkMarkdown("abc", { maxBytes: -10 })).toThrow(RangeError);+ });+});diff --git a/apps/api/src/lib/fire-privacy-chunker.ts b/apps/api/src/lib/fire-privacy-chunker.tsnew file mode 100644index 000000000..2dbdf8524--- /dev/null+++ b/apps/api/src/lib/fire-privacy-chunker.ts@@ -0,0 +1,121 @@+// Markdown-aware chunker for fire-privacy /redact.+//+// Splits a long markdown document into pieces small enough to fit+// fire-privacy's request cap (100KB / model truncation @ 32K chars),+// preferring "safe" split points so PII spans rarely straddle chunks.+//+// Split priority (latest match wins inside the upper half of the window):+// 1. paragraph break (\n\n) -- best+// 2. line break (\n)+// 3. sentence end ([.!?]\s)+// 4. whitespace+// 5. hard cut -- only if none of the above appear+//+// Chunks are non-overlapping; concatenating their `text` reproduces the+// input character-for-character. Each chunk carries its start offset+// so the caller can lift per-chunk spans into the source coordinate+// space when merging.++export type Chunk = {+ text: string;+ start: number;+};++// Leave headroom below fire-privacy's `model_max_input_chars` (32K) so+// boundary search can walk backwards to a real paragraph break.+export const DEFAULT_MAX_CHARS = 28_000;+// Leave headroom below fire-privacy's `max_text_bytes` (100K). UTF-8+// markdown is typically ~1 byte/char but non-ASCII spikes can push past;+// we re-validate the per-chunk byte count and shrink if needed.+const DEFAULT_MAX_BYTES = 95_000;++const SENTENCE_END = /[.!?]\s/g;++// Find the latest "safe" index in text[lo..hi] to split, or `hi` if no+// safe boundary is found (caller may hard-cut at `hi`).+function findSafeSplit(text: string, lo: number, hi: number): number {+ const window = text.slice(lo, hi);++ const para = window.lastIndexOf("\n\n");+ if (para > 0) return lo + para + 2;++ const line = window.lastIndexOf("\n");+ if (line > 0) return lo + line + 1;++ // Walk the regex to find the LAST [.!?]\s in the window.+ SENTENCE_END.lastIndex = 0;+ let lastSentenceEnd = -1;+ let match: RegExpExecArray | null;+ while ((match = SENTENCE_END.exec(window)) !== null) {+ lastSentenceEnd = match.index + match[0].length;+ }+ if (lastSentenceEnd > 0) return lo + lastSentenceEnd;++ const space = window.lastIndexOf(" ");+ if (space > 0) return lo + space + 1;++ return hi;+}++function utf8ByteLength(s: string): number {+ // TextEncoder is faster than Buffer.byteLength for large strings in V8+ // and avoids a Buffer allocation per call.+ return new TextEncoder().encode(s).length;+}++type ChunkOptions = {+ maxChars?: number;+ maxBytes?: number;+};++export function chunkMarkdown(text: string, opts?: ChunkOptions): Chunk[] {+ if (text.length === 0) return [];+ const maxChars = opts?.maxChars ?? DEFAULT_MAX_CHARS;+ const maxBytes = opts?.maxBytes ?? DEFAULT_MAX_BYTES;+ // Guard against caller bugs that would otherwise leave the cursor parked+ // at 0 (maxChars β€ 0 β tentativeEnd β€ cursor) and spin forever.+ if (maxChars <= 0) {+ throw new RangeError(`chunkMarkdown: maxChars must be > 0 (got ${maxChars})`);+ }+ if (maxBytes <= 0) {+ throw new RangeError(`chunkMarkdown: maxBytes must be > 0 (got ${maxBytes})`);+ }++ const chunks: Chunk[] = [];+ const n = text.length;+ let cursor = 0;++ while (cursor < n) {+ const tentativeEnd = Math.min(cursor + maxChars, n);++ let safeEnd: number;+ if (tentativeEnd === n) {+ // Whole remainder fits within maxChars β single tail chunk.+ safeEnd = n;+ } else {+ // Constrain the safe-split search to the upper half of the window β+ // prevents pathological cases where the only paragraph break is+ // near the chunk's start and would produce a tiny chunk.+ const lo = cursor + Math.floor(maxChars / 2);+ safeEnd = findSafeSplit(text, lo, tentativeEnd);+ if (safeEnd <= cursor) safeEnd = tentativeEnd;+ }++ let chunkText = text.slice(cursor, safeEnd);++ // Byte-budget enforcement for non-ASCII text. Rare on web markdown+ // but cheap to handle: shrink one char at a time. Done as a `while`+ // because each removed char may straddle a multibyte boundary.+ if (utf8ByteLength(chunkText) > maxBytes) {+ while (utf8ByteLength(chunkText) > maxBytes && chunkText.length > 1) {+ chunkText = chunkText.slice(0, -1);+ }+ safeEnd = cursor + chunkText.length;+ }++ chunks.push({ text: chunkText, start: cursor });+ cursor = safeEnd;+ }++ return chunks;+}diff --git a/apps/api/src/lib/fire-privacy-client.test.ts b/apps/api/src/lib/fire-privacy-client.test.tsnew file mode 100644index 000000000..951a19753--- /dev/null+++ b/apps/api/src/lib/fire-privacy-client.test.ts@@ -0,0 +1,715 @@+import http from "http";+import { AddressInfo } from "net";+import { config } from "../config";+import { redactText } from "./fire-privacy-client";++type Handler = (+ req: http.IncomingMessage,+ res: http.ServerResponse,+) => void | Promise<void>;++let server: http.Server;+let baseUrl: string;+let originalUrl: string | undefined;+let handler: Handler = (_req, res) => {+ res.statusCode = 500;+ res.end();+};++beforeAll(async () => {+ await new Promise<void>(resolve => {+ server = http.createServer((req, res) => {+ void Promise.resolve(handler(req, res)).catch(err => {+ res.statusCode = 500;+ res.end(String(err));+ });+ });+ server.listen(0, "127.0.0.1", () => {+ const addr = server.address() as AddressInfo;+ baseUrl = `http://127.0.0.1:${addr.port}`;+ originalUrl = config.FIRE_PRIVACY_URL;+ config.FIRE_PRIVACY_URL = baseUrl;+ resolve();+ });+ });+});++afterAll(async () => {+ config.FIRE_PRIVACY_URL = originalUrl;+ await new Promise<void>(resolve => server.close(() => resolve()));+});++afterEach(() => {+ handler = (_req, res) => {+ res.statusCode = 500;+ res.end();+ };+});++function withBody(body: unknown, status = 200): Handler {+ return (_req, res) => {+ res.statusCode = status;+ res.setHeader("content-type", "application/json");+ res.end(JSON.stringify(body));+ };+}++describe("redactText", () => {+ it("returns status=ok with redacted_text and spans on 200", async () => {+ handler = withBody({+ redacted_text: "Hi, my name is <PERSON>.",+ spans: [+ {+ start: 15,+ end: 26,+ kind: "PERSON",+ score: 0.9,+ source: "SpacyRecognizer",+ },+ ],+ model_status: "ok",+ });++ const out = await redactText({ text: "Hi, my name is Alice Smith." });++ expect(out.status).toBe("ok");+ expect(out.reason).toBeUndefined();+ expect(out.redactedMarkdown).toBe("Hi, my name is <PERSON>.");+ expect(out.spans).toHaveLength(1);+ expect(out.spans[0]).toMatchObject({+ kind: "PERSON",+ entity: "PERSON",+ source: "heuristics",+ score: 0.9,+ });+ expect(out.counts).toEqual({ PERSON: 1 });+ });++ it("treats absent model_status as ok", async () => {+ handler = withBody({+ redacted_text: "redacted",+ spans: [],+ });++ const out = await redactText({ text: "input" });+ expect(out.status).toBe("ok");+ expect(out.redactedMarkdown).toBe("redacted");+ expect(out.counts).toEqual({});+ });++ it("returns status=skipped with reason=upstream_skipped when model_status is skipped", async () => {+ handler = withBody({+ redacted_text: "",+ spans: [],+ model_status: "skipped",+ });++ const out = await redactText({ text: "input-not-empty" });+ expect(out.status).toBe("skipped");+ expect(out.reason).toBe("upstream_skipped");+ expect(out.redactedMarkdown).toBe("");+ });++ it("short-circuits empty input to skipped with empty_input and no HTTP call", async () => {+ let called = false;+ handler = (_req, res) => {+ called = true;+ res.statusCode = 500;+ res.end();+ };++ const out = await redactText({ text: " \n\t" });+ expect(called).toBe(false);+ expect(out.status).toBe("skipped");+ expect(out.reason).toBe("empty_input");+ expect(out.redactedMarkdown).toBe(" \n\t");+ expect(out.spans).toEqual([]);+ expect(out.counts).toEqual({});+ });++ it("maps 503 to failed/service_unavailable, null markdown", async () => {+ handler = (_req, res) => {+ res.statusCode = 503;+ res.end();+ };++ const out = await redactText({ text: "input" });+ expect(out.status).toBe("failed");+ expect(out.reason).toBe("service_unavailable");+ expect(out.redactedMarkdown).toBeNull();+ expect(out.spans).toEqual([]);+ expect(out.counts).toEqual({});+ });++ it("maps 413 (input too large) to failed/error", async () => {+ handler = (_req, res) => {+ res.statusCode = 413;+ res.end();+ };++ const out = await redactText({ text: "input" });+ expect(out.status).toBe("failed");+ expect(out.reason).toBe("error");+ expect(out.redactedMarkdown).toBeNull();+ });++ it("maps generic 5xx to failed/error", async () => {+ handler = (_req, res) => {+ res.statusCode = 502;+ res.end();+ };++ const out = await redactText({ text: "input" });+ expect(out.status).toBe("failed");+ expect(out.reason).toBe("error");+ expect(out.redactedMarkdown).toBeNull();+ });++ it("returns failed/error when model_status is error", async () => {+ handler = withBody({+ redacted_text: "anything",+ spans: [],+ model_status: "error",+ });++ const out = await redactText({ text: "input" });+ expect(out.status).toBe("failed");+ expect(out.reason).toBe("error");+ expect(out.redactedMarkdown).toBeNull();+ });++ it("returns failed/timeout when fire-privacy exceeds the budget", async () => {+ handler = (_req, res) => {+ // Hang past the timeout.+ setTimeout(() => {+ res.statusCode = 200;+ res.end(+ JSON.stringify({+ redacted_text: "late",+ spans: [],+ model_status: "ok",+ }),+ );+ }, 200);+ };++ const out = await redactText({ text: "input", timeoutMs: 50 });+ expect(out.status).toBe("failed");+ expect(out.reason).toBe("timeout");+ expect(out.redactedMarkdown).toBeNull();+ });++ it("returns failed/error when the URL is unreachable", async () => {+ const originalLocalUrl = config.FIRE_PRIVACY_URL;+ config.FIRE_PRIVACY_URL = "http://127.0.0.1:1";+ try {+ const out = await redactText({ text: "input", timeoutMs: 500 });+ expect(out.status).toBe("failed");+ expect(out.reason).toBe("error");+ expect(out.redactedMarkdown).toBeNull();+ } finally {+ config.FIRE_PRIVACY_URL = originalLocalUrl;+ }+ });++ it("returns failed/error without an HTTP call when FIRE_PRIVACY_URL is unset", async () => {+ let called = false;+ handler = (_req, res) => {+ called = true;+ res.statusCode = 200;+ res.end();+ };+ const originalLocalUrl = config.FIRE_PRIVACY_URL;+ config.FIRE_PRIVACY_URL = undefined;+ try {+ const out = await redactText({ text: "input" });+ expect(called).toBe(false);+ expect(out.status).toBe("failed");+ expect(out.reason).toBe("error");+ expect(out.redactedMarkdown).toBeNull();+ } finally {+ config.FIRE_PRIVACY_URL = originalLocalUrl;+ }+ });++ it("returns failed/error on invalid JSON response", async () => {+ handler = (_req, res) => {+ res.statusCode = 200;+ res.setHeader("content-type", "application/json");+ res.end("{not json");+ };++ const out = await redactText({ text: "input" });+ expect(out.status).toBe("failed");+ expect(out.reason).toBe("error");+ expect(out.redactedMarkdown).toBeNull();+ });++ it("filters malformed spans", async () => {+ handler = withBody({+ redacted_text: "redacted",+ spans: [+ { start: 0, end: 5, kind: "PERSON", score: 0.9, source: "x" },+ { start: "bad", end: 5, kind: "PERSON" },+ null,+ { start: 10, end: 15, kind: "EMAIL_ADDRESS" },+ ],+ });++ const out = await redactText({ text: "input" });+ expect(out.spans).toHaveLength(2);+ expect(out.spans[0].kind).toBe("PERSON");+ expect(out.spans[1].kind).toBe("EMAIL_ADDRESS");+ // No `score` field when fire-privacy didn't supply one.+ expect(out.spans[1].score).toBeUndefined();+ // Opaque source falls back to "unknown".+ expect(out.spans[1].source).toBe("unknown");+ // Counts roll up by entity, not kind.+ expect(out.counts).toEqual({ PERSON: 1, EMAIL: 1 });+ });++ it("attaches public entity bucket to each span; omits when unmapped", async () => {+ handler = withBody({+ redacted_text: "x",+ spans: [+ { start: 0, end: 5, kind: "PRIVATE_PERSON", source: "openai-privacy-filter" },+ { start: 6, end: 10, kind: "EMAIL_ADDRESS", source: "EmailRecognizer" },+ { start: 11, end: 15, kind: "ORGANIZATION", source: "SpacyRecognizer" },+ ],+ });+ const out = await redactText({ text: "input here.." });+ expect(out.spans[0]).toMatchObject({+ kind: "PRIVATE_PERSON",+ entity: "PERSON",+ source: "model",+ });+ expect(out.spans[1]).toMatchObject({+ kind: "EMAIL_ADDRESS",+ entity: "EMAIL",+ source: "heuristics",+ });+ expect(out.spans[2].kind).toBe("ORGANIZATION");+ expect(out.spans[2].entity).toBeUndefined();+ // Unmapped spans don't roll into counts.+ expect(out.counts).toEqual({ PERSON: 1, EMAIL: 1 });+ });++ it("sends mode/operator/language defaults", async () => {+ let captured: Record<string, unknown> | undefined;+ handler = async (req, res) => {+ const chunks: Buffer[] = [];+ for await (const chunk of req) chunks.push(chunk as Buffer);+ captured = JSON.parse(Buffer.concat(chunks).toString());+ res.statusCode = 200;+ res.setHeader("content-type", "application/json");+ res.end(+ JSON.stringify({ redacted_text: "ok", spans: [], model_status: "ok" }),+ );+ };++ await redactText({ text: "input" });+ expect(captured).toMatchObject({+ text: "input",+ mode: "model",+ operator: "replace",+ language: "en",+ });+ });++ // ---- mode + replaceStyle mapping ----------------------------------------++ it("maps each public mode to the fire-privacy internal mode", async () => {+ const cases: Array<+ ["accurate" | "aggressive" | "fast", "model" | "both" | "heuristics"]+ > = [+ ["accurate", "model"],+ ["aggressive", "both"],+ ["fast", "heuristics"],+ ];+ for (const [external, internalMode] of cases) {+ let captured: Record<string, unknown> | undefined;+ handler = async (req, res) => {+ const chunks: Buffer[] = [];+ for await (const chunk of req) chunks.push(chunk as Buffer);+ captured = JSON.parse(Buffer.concat(chunks).toString());+ res.statusCode = 200;+ res.setHeader("content-type", "application/json");+ res.end(+ JSON.stringify({+ redacted_text: "x",+ spans: [],+ model_status: "ok",+ }),+ );+ };+ await redactText({+ text: "x",+ options: { mode: external, replaceStyle: "tag" },+ });+ expect(captured?.mode).toBe(internalMode);+ }+ });++ it("maps each replaceStyle to the fire-privacy operator", async () => {+ const cases: Array<+ ["tag" | "mask" | "remove", "replace" | "mask" | "redact"]+ > = [+ ["tag", "replace"],+ ["mask", "mask"],+ ["remove", "redact"],+ ];+ for (const [external, operator] of cases) {+ let captured: Record<string, unknown> | undefined;+ handler = async (req, res) => {+ const chunks: Buffer[] = [];+ for await (const chunk of req) chunks.push(chunk as Buffer);+ captured = JSON.parse(Buffer.concat(chunks).toString());+ res.statusCode = 200;+ res.setHeader("content-type", "application/json");+ res.end(+ JSON.stringify({+ redacted_text: "x",+ spans: [],+ model_status: "ok",+ }),+ );+ };+ await redactText({+ text: "x",+ options: { mode: "accurate", replaceStyle: external },+ });+ expect(captured?.operator).toBe(operator);+ }+ });++ // ---- entities filter ----------------------------------------------------++ it("filters spans to the requested entities and re-renders markdown", async () => {+ handler = withBody({+ redacted_text:+ "Hi, my name is <PRIVATE_PERSON>. Email me at <EMAIL_ADDRESS>.",+ spans: [+ {+ start: 15,+ end: 26,+ kind: "PRIVATE_PERSON",+ score: 1.0,+ source: "openai-privacy-filter",+ },+ {+ start: 40,+ end: 57,+ kind: "EMAIL_ADDRESS",+ score: 1.0,+ source: "EmailRecognizer",+ },+ ],+ model_status: "ok",+ });++ const source = "Hi, my name is Alice Smith. Email me at [email protected].";+ const out = await redactText({+ text: source,+ options: {+ mode: "accurate",+ replaceStyle: "tag",+ entities: ["EMAIL"],+ },+ });++ expect(out.status).toBe("ok");+ // Person span filtered out; email retained.+ expect(out.spans).toHaveLength(1);+ expect(out.spans[0].kind).toBe("EMAIL_ADDRESS");+ expect(out.spans[0].entity).toBe("EMAIL");+ // Markdown re-rendered from the filtered span set: name stays, email+ // gets replaced with the kind tag.+ expect(out.redactedMarkdown).toBe(+ "Hi, my name is Alice Smith. Email me at <EMAIL_ADDRESS>.",+ );+ expect(out.counts).toEqual({ EMAIL: 1 });+ });++ it("uses upstream redacted_text when no entity filter is set", async () => {+ handler = withBody({+ redacted_text: "<PRIVATE_PERSON>",+ spans: [+ {+ start: 0,+ end: 11,+ kind: "PRIVATE_PERSON",+ score: 1.0,+ source: "openai-privacy-filter",+ },+ ],+ model_status: "ok",+ });++ const out = await redactText({+ text: "Alice Smith",+ options: { mode: "accurate", replaceStyle: "tag" },+ });++ expect(out.redactedMarkdown).toBe("<PRIVATE_PERSON>");+ });++ it("drops spans whose kind doesn't map to any allowed entity", async () => {+ handler = withBody({+ redacted_text: "x",+ spans: [+ // Kind isn't in the unified taxonomy β drops under any allowlist.+ { start: 0, end: 5, kind: "ORGANIZATION", score: 1.0, source: "x" },+ ],+ model_status: "ok",+ });++ const out = await redactText({+ text: "ABCDE end",+ options: {+ mode: "accurate",+ replaceStyle: "tag",+ entities: ["PERSON", "EMAIL"],+ },+ });++ expect(out.spans).toEqual([]);+ expect(out.redactedMarkdown).toBe("ABCDE end");+ expect(out.counts).toEqual({});+ });++ it("re-renders with mask style preserving span length", async () => {+ // Source: "Alice Smith - email [email protected]" (37 chars)+ // Person spans 0..11, email spans 20..37.+ handler = withBody({+ redacted_text: "***********",+ spans: [+ {+ start: 0,+ end: 11,+ kind: "PRIVATE_PERSON",+ score: 1.0,+ source: "openai-privacy-filter",+ },+ {+ start: 20,+ end: 37,+ kind: "EMAIL_ADDRESS",+ score: 1.0,+ source: "EmailRecognizer",+ },+ ],+ model_status: "ok",+ });++ const source = "Alice Smith - email [email protected]";+ const out = await redactText({+ text: source,+ options: {+ mode: "accurate",+ replaceStyle: "mask",+ entities: ["EMAIL"], // filter triggers re-render+ },+ });++ expect(out.redactedMarkdown).toBe("Alice Smith - email *****************");+ });++ // ---- chunked path (input over single-chunk threshold) ------------------++ it("chunks long input and merges spans with corrected offsets", async () => {+ // Build a >28K-char input by repeating a paragraph with a marker name+ // every block. Each chunk handler returns spans local to its own text;+ // the client should lift them into source coordinates.+ const para =+ "Lorem ipsum dolor sit amet. Please contact Alice Carter today.\n\n";+ const text = para.repeat(700); // ~44K chars β multiple chunks+ expect(text.length).toBeGreaterThan(28_000);++ // Per-chunk handler: scan the received text for "Alice Carter" and+ // return spans local to that chunk. The handler echos a redacted_text+ // built from the chunk's input with names replaced.+ handler = async (req, res) => {+ const buf: Buffer[] = [];+ for await (const c of req) buf.push(c as Buffer);+ const { text: chunkText } = JSON.parse(Buffer.concat(buf).toString());+ const localSpans: Array<{+ start: number;+ end: number;+ kind: string;+ score: number;+ source: string;+ }> = [];+ let idx = 0;+ const needle = "Alice Carter";+ while ((idx = chunkText.indexOf(needle, idx)) !== -1) {+ localSpans.push({+ start: idx,+ end: idx + needle.length,+ kind: "PERSON",+ score: 0.95,+ source: "test",+ });+ idx += needle.length;+ }+ const redacted = chunkText.replaceAll(needle, "<PERSON>");+ res.statusCode = 200;+ res.setHeader("content-type", "application/json");+ res.end(+ JSON.stringify({+ redacted_text: redacted,+ spans: localSpans,+ model_status: "ok",+ }),+ );+ };++ const out = await redactText({ text });+ expect(out.status).toBe("ok");+ // Every occurrence of "Alice Carter" in the source text should appear+ // as a span with source-coordinate offsets that match.+ const expectedHits: number[] = [];+ let i = 0;+ while ((i = text.indexOf("Alice Carter", i)) !== -1) {+ expectedHits.push(i);+ i += "Alice Carter".length;+ }+ expect(out.spans.length).toBe(expectedHits.length);+ for (let k = 0; k < expectedHits.length; k++) {+ expect(out.spans[k].start).toBe(expectedHits[k]);+ expect(out.spans[k].end).toBe(expectedHits[k] + "Alice Carter".length);+ // Source-coordinate offsets must point at "Alice Carter" in the source.+ expect(text.slice(out.spans[k].start, out.spans[k].end)).toBe(+ "Alice Carter",+ );+ }+ expect(out.counts.PERSON).toBe(expectedHits.length);+ });++ it("returns skipped/too_large above the byte ceiling without an HTTP call", async () => {+ let called = false;+ handler = (_req, res) => {+ called = true;+ res.statusCode = 500;+ res.end();+ };++ // 260KB β above the 250KB ceiling.+ const text = "x".repeat(260_000);+ const out = await redactText({ text });++ expect(called).toBe(false);+ expect(out.status).toBe("skipped");+ expect(out.reason).toBe("too_large");+ expect(out.redactedMarkdown).toBeNull();+ expect(out.spans).toEqual([]);+ expect(out.counts).toEqual({});+ });++ it("fails the whole response when any chunk errors (all-or-nothing)", async () => {+ // Force a long input that will produce multiple chunks. First chunk+ // returns 200; second chunk returns 503. The merged result must be+ // failed/service_unavailable with no partial spans surfaced.+ const text = "Filler. ".repeat(8000); // ~64K chars+ expect(text.length).toBeGreaterThan(28_000);++ let chunkIndex = 0;+ handler = (_req, res) => {+ const current = chunkIndex++;+ if (current === 0) {+ res.statusCode = 200;+ res.setHeader("content-type", "application/json");+ res.end(+ JSON.stringify({+ redacted_text: "x",+ spans: [+ { start: 0, end: 5, kind: "PERSON", score: 0.9, source: "t" },+ ],+ model_status: "ok",+ }),+ );+ } else {+ res.statusCode = 503;+ res.end();+ }+ };++ const out = await redactText({ text });+ expect(out.status).toBe("failed");+ expect(out.reason).toBe("service_unavailable");+ expect(out.redactedMarkdown).toBeNull();+ expect(out.spans).toEqual([]);+ expect(out.counts).toEqual({});+ });++ it("fans out chunked calls (concurrency > 1)", async () => {+ // 3 chunks. Hold each handler open until all 3 are in flight to+ // prove the client doesn't serialize them.+ const text = "Sentence. ".repeat(7000); // ~70K chars β β₯3 chunks+ let inFlight = 0;+ let maxInFlight = 0;+ const gate: Array<() => void> = [];+ const allInFlight = new Promise<void>(resolve => {+ gate.push(resolve);+ });++ handler = async (_req, res) => {+ inFlight++;+ maxInFlight = Math.max(maxInFlight, inFlight);+ if (inFlight >= 2) gate[0]?.();+ // Wait until at least 2 requests have arrived (proves parallelism)+ await Promise.race([+ allInFlight,+ new Promise<void>(r => setTimeout(r, 200)),+ ]);+ inFlight--;+ res.statusCode = 200;+ res.setHeader("content-type", "application/json");+ res.end(+ JSON.stringify({+ redacted_text: "x",+ spans: [],+ model_status: "ok",+ }),+ );+ };++ const out = await redactText({ text });+ expect(out.status).toBe("ok");+ expect(maxInFlight).toBeGreaterThanOrEqual(2);+ });++ it("re-renders with remove style dropping span characters", async () => {+ handler = withBody({+ redacted_text: "",+ spans: [+ {+ start: 0,+ end: 11,+ kind: "PRIVATE_PERSON",+ score: 1.0,+ source: "openai-privacy-filter",+ },+ {+ start: 20,+ end: 37,+ kind: "EMAIL_ADDRESS",+ score: 1.0,+ source: "EmailRecognizer",+ },+ ],+ model_status: "ok",+ });++ const source = "Alice Smith - email [email protected]";+ const out = await redactText({+ text: source,+ options: {+ mode: "accurate",+ replaceStyle: "remove",+ entities: ["PERSON"],+ },+ });++ expect(out.redactedMarkdown).toBe(" - email [email protected]");+ });+});diff --git a/apps/api/src/lib/fire-privacy-client.ts b/apps/api/src/lib/fire-privacy-client.tsnew file mode 100644index 000000000..211110e79--- /dev/null+++ b/apps/api/src/lib/fire-privacy-client.ts@@ -0,0 +1,438 @@+import { Logger } from "winston";+import { config } from "../config";+import {+ PIIBlock,+ PIIReason,+ PIISource,+ PIISpan,+ RedactPIIOptions,+ type RedactPIIEntity,+} from "../controllers/v2/types";+import { chunkMarkdown, type Chunk } from "./fire-privacy-chunker";++type FirePrivacyResponse = {+ redacted_text?: unknown;+ spans?: unknown;+ model_status?: unknown;+};++type RedactOptions = {+ text: string;+ url?: string;+ timeoutMs?: number;+ logger?: Logger;+ // Caller-provided config. Boolean form is normalized to a defaults+ // object via the Zod transform before reaching here; an unset value+ // wouldn't trigger this code path at all (transformer skips when+ // meta.options.redactPII is falsy).+ options?: RedactPIIOptions;+};++// Mode + replaceStyle map to fire-privacy's `mode` and `operator` fields.+// Keep both sides in sync if either side changes.+const MODE_MAP = {+ accurate: "model",+ aggressive: "both",+ fast: "heuristics",+} as const;++const REPLACE_MAP = {+ tag: "replace",+ mask: "mask",+ remove: "redact",+} as const;++const DEFAULTS = {+ mode: "accurate",+ replaceStyle: "tag",+ language: "en",+} as const;++// Hard ceiling: above this byte count we refuse to redact and return+// `skipped` with reason `too_large` rather than ship partial results.+// Sized from `eval/scaling/` measurements in fire-privacy: 250KB β ~80+// PDF pages, ~10 chunks, ~60s wall at c=3 with the model on. Anything+// larger pushes past the typical scrape budget and starves the fleet.+const MAX_REDACT_BYTES = 250_000;+// Chunks fan out at this concurrency to fire-privacy. The fleet has 6+// pods at saturation; c=3 keeps a single call under 50% of capacity so+// other tenants aren't starved.+const CHUNK_CONCURRENCY = 3;++// Maps a span's `kind` (as returned by either OPF or Presidio) onto the+// unified entity bucket we expose to callers. Kinds we don't recognize+// fall through unmapped β entity filtering treats them as "not in any+// bucket" and drops them when an entity allowlist is in play.+const KIND_TO_ENTITY: Record<string, RedactPIIEntity> = {+ // Person+ PRIVATE_PERSON: "PERSON",+ PERSON: "PERSON",+ PRIVATE_EMAIL: "EMAIL",+ EMAIL_ADDRESS: "EMAIL",+ // Phone+ PRIVATE_PHONE: "PHONE",+ PHONE_NUMBER: "PHONE",+ PHONEIMEI: "PHONE",+ // Location+ PRIVATE_ADDRESS: "LOCATION",+ LOCATION: "LOCATION",+ // Financial+ ACCOUNT_NUMBER: "FINANCIAL",+ CREDIT_CARD: "FINANCIAL",+ IBAN_CODE: "FINANCIAL",+ US_BANK_NUMBER: "FINANCIAL",+ US_SSN: "FINANCIAL",+ US_ITIN: "FINANCIAL",+ CRYPTO: "FINANCIAL",+ // Secret+ SECRET: "SECRET",+ API_KEY: "SECRET",+ PASSWORD: "SECRET",+ US_DRIVER_LICENSE: "SECRET",+ US_PASSPORT: "SECRET",+ MEDICAL_LICENSE: "SECRET",+};++// Classify fire-privacy's per-span `source` string into the public+// taxonomy. OPF spans always carry `openai-privacy-filter`; Presidio+// recognizer names end in `Recognizer`. Anything else is opaque.+function classifySource(raw: unknown): PIISource {+ if (typeof raw !== "string") return "unknown";+ if (raw === "openai-privacy-filter") return "model";+ if (raw.endsWith("Recognizer")) return "heuristics";+ return "unknown";+}++function coerceSpans(value: unknown): PIISpan[] {+ if (!Array.isArray(value)) return [];+ const out: PIISpan[] = [];+ for (const raw of value) {+ if (typeof raw !== "object" || raw === null) continue;+ const r = raw as Record<string, unknown>;+ if (+ typeof r.start !== "number" ||+ typeof r.end !== "number" ||+ typeof r.kind !== "string"+ ) {+ continue;+ }+ const entity = KIND_TO_ENTITY[r.kind];+ const span: PIISpan = {+ start: r.start,+ end: r.end,+ kind: r.kind,+ source: classifySource(r.source),+ };+ if (entity !== undefined) span.entity = entity;+ if (typeof r.score === "number") span.score = r.score;+ out.push(span);+ }+ return out;+}++// Apply an entity allowlist to the span set. When unset, returns the+// spans unchanged. When set, keeps only spans with a mapped `entity`+// that's in the allowlist β unmapped spans drop.+function filterByEntities(+ spans: PIISpan[],+ entities: readonly RedactPIIEntity[] | undefined,+): PIISpan[] {+ if (!entities || entities.length === 0) return spans;+ const allow = new Set(entities);+ return spans.filter(s => s.entity !== undefined && allow.has(s.entity));+}++// Re-render redacted text from the original + a filtered span set when+// fire-privacy's `redacted_text` no longer matches what we want to return+// (i.e. we narrowed the spans via entity filter). Same operator semantics+// as fire-privacy:+// tag β `<KIND>` placeholder per span+// mask β '*' Γ span length+// remove β drop the chars entirely+function renderRedacted(+ text: string,+ spans: PIISpan[],+ replaceStyle: RedactPIIOptions["replaceStyle"],+): string {+ if (spans.length === 0) return text;+ const sorted = [...spans].sort((a, b) => a.start - b.start);+ let out = "";+ let cursor = 0;+ for (const span of sorted) {+ if (span.start < cursor) continue; // overlap with prior span; skip+ if (span.start > text.length) break;+ out += text.slice(cursor, span.start);+ switch (replaceStyle) {+ case "tag":+ out += `<${span.kind}>`;+ break;+ case "mask":+ out += "*".repeat(Math.max(0, span.end - span.start));+ break;+ case "remove":+ break;+ }+ cursor = Math.min(span.end, text.length);+ }+ out += text.slice(cursor);+ return out;+}++function countByEntity(+ spans: PIISpan[],+): Partial<Record<RedactPIIEntity, number>> {+ const out: Partial<Record<RedactPIIEntity, number>> = {};+ for (const span of spans) {+ if (span.entity === undefined) continue;+ out[span.entity] = (out[span.entity] ?? 0) + 1;+ }+ return out;+}++// Result of one /redact call, in source-coordinate space (spans already+// offset by the chunk's start).+type ChunkResult =+ | {+ ok: true;+ spans: PIISpan[];+ redactedText: string;+ // Sticky upstream-skip flag: true if the model returned+ // model_status === "skipped" for this chunk. Surfaces on the+ // merged block when any chunk was skipped upstream.+ upstreamSkipped: boolean;+ }+ | { ok: false; reason: PIIReason };++async function redactOnce(+ chunk: Chunk,+ options: RedactPIIOptions,+ url: string | undefined,+ timeoutMs: number,+ logger: Logger | undefined,+): Promise<ChunkResult> {+ const controller = new AbortController();+ let timedOut = false;+ const timer = setTimeout(() => {+ timedOut = true;+ controller.abort();+ }, timeoutMs);++ let response: Response;+ try {+ response = await fetch(`${config.FIRE_PRIVACY_URL}/redact`, {+ method: "POST",+ headers: { "content-type": "application/json" },+ body: JSON.stringify({+ text: chunk.text,+ mode: MODE_MAP[options.mode],+ operator: REPLACE_MAP[options.replaceStyle],+ language: DEFAULTS.language,+ }),+ signal: controller.signal,+ });+ } catch (err) {+ clearTimeout(timer);+ const reason: PIIReason = timedOut ? "timeout" : "error";+ logger?.warn("fire-privacy request failed", {+ reason,+ url,+ mode: options.mode,+ chunkStart: chunk.start,+ error: err instanceof Error ? err.message : String(err),+ });+ return { ok: false, reason };+ }+ clearTimeout(timer);++ if (!response.ok) {+ const reason: PIIReason =+ response.status === 503 ? "service_unavailable" : "error";+ logger?.warn("fire-privacy returned non-2xx", {+ reason,+ httpStatus: response.status,+ url,+ mode: options.mode,+ chunkStart: chunk.start,+ });+ return { ok: false, reason };+ }++ let body: FirePrivacyResponse;+ try {+ body = (await response.json()) as FirePrivacyResponse;+ } catch (err) {+ logger?.warn("fire-privacy returned invalid JSON", {+ url,+ chunkStart: chunk.start,+ error: err instanceof Error ? err.message : String(err),+ });+ return { ok: false, reason: "error" };+ }++ const upstreamRedacted =+ typeof body.redacted_text === "string" ? body.redacted_text : null;+ const rawSpans = coerceSpans(body.spans);++ if (body.model_status === "error" || upstreamRedacted === null) {+ return { ok: false, reason: "error" };+ }++ // Lift spans into source coordinates.+ const spans = rawSpans.map(s => ({+ ...s,+ start: s.start + chunk.start,+ end: s.end + chunk.start,+ }));++ return {+ ok: true,+ spans,+ redactedText: upstreamRedacted,+ upstreamSkipped: body.model_status === "skipped",+ };+}++// Run chunks against fire-privacy with bounded concurrency. Returns+// results in chunk order (results[i] corresponds to chunks[i]).+async function runChunks(+ chunks: Chunk[],+ options: RedactPIIOptions,+ url: string | undefined,+ timeoutMs: number,+ logger: Logger | undefined,+): Promise<ChunkResult[]> {+ const results = new Array<ChunkResult>(chunks.length);+ let next = 0;++ const worker = async (): Promise<void> => {+ while (true) {+ const i = next++;+ if (i >= chunks.length) return;+ results[i] = await redactOnce(chunks[i], options, url, timeoutMs, logger);+ }+ };++ const workers = Array.from(+ { length: Math.min(CHUNK_CONCURRENCY, chunks.length) },+ () => worker(),+ );+ await Promise.all(workers);+ return results;+}++export async function redactText(opts: RedactOptions): Promise<PIIBlock> {+ const { text, logger } = opts;+ const timeoutMs = opts.timeoutMs ?? config.FIRE_PRIVACY_TIMEOUT_MS;+ const options: RedactPIIOptions = opts.options ?? {+ mode: DEFAULTS.mode,+ replaceStyle: DEFAULTS.replaceStyle,+ };++ // Fire-privacy is an optional service. If it's not configured for this+ // deployment, surface a clear `failed/error` block rather than making+ // a request to `undefined/redact` and letting it fail opaquely.+ if (!config.FIRE_PRIVACY_URL) {+ logger?.warn("redactPII requested but FIRE_PRIVACY_URL is not configured", {+ url: opts.url,+ });+ return {+ status: "failed",+ reason: "error",+ redactedMarkdown: null,+ spans: [],+ counts: {},+ };+ }++ // Empty/whitespace input is a no-op locally β saves a round trip and matches+ // fire-privacy's own "skipped" semantics. We pass the original text through+ // as `redactedMarkdown` since there's nothing to remove.+ if (text.trim().length === 0) {+ return {+ status: "skipped",+ reason: "empty_input",+ redactedMarkdown: text,+ spans: [],+ counts: {},+ };+ }++ // Hard byte ceiling. Anything above this is refused with a dedicated+ // reason so callers can tell "we declined" apart from "we tried and+ // it broke." We measure bytes, not chars, because fire-privacy's+ // request cap is byte-based.+ const inputBytes = new TextEncoder().encode(text).length;+ if (inputBytes > MAX_REDACT_BYTES) {+ logger?.info("fire-privacy input exceeds redaction ceiling", {+ url: opts.url,+ inputBytes,+ maxBytes: MAX_REDACT_BYTES,+ });+ return {+ status: "skipped",+ reason: "too_large",+ redactedMarkdown: null,+ spans: [],+ counts: {},+ };+ }++ const chunks = chunkMarkdown(text);+ const results = await runChunks(chunks, options, opts.url, timeoutMs, logger);++ // All-or-nothing: any chunk failure poisons the whole response. Partial+ // redaction is worse than no redaction β callers can't tell which+ // sections of their markdown are clean. Pick the first non-ok reason+ // so the failure surface (timeout / service_unavailable / error) is+ // preserved end-to-end.+ const firstFailure = results.find(r => !r.ok);+ if (firstFailure && !firstFailure.ok) {+ return {+ status: "failed",+ reason: firstFailure.reason,+ redactedMarkdown: null,+ spans: [],+ counts: {},+ };+ }++ const successes = results.filter(+ (r): r is Extract<ChunkResult, { ok: true }> => r.ok,+ );++ // Merge: spans already lifted into source coordinates by redactOnce.+ const allSpans = successes.flatMap(r => r.spans);+ const spans = filterByEntities(allSpans, options.entities);++ // Re-render when the entity filter pruned spans OR when we have+ // multiple chunks (per-chunk redacted_text concatenations are valid+ // since chunks are non-overlapping, but re-rendering with the same+ // operator yields identical output and keeps one code path for the+ // edge cases β e.g. chunk boundaries inside a span are impossible+ // by construction since spans are produced after we split).+ const concatRedacted = successes.map(r => r.redactedText).join("");+ const redactedMarkdown =+ spans.length === allSpans.length+ ? concatRedacted+ : renderRedacted(text, spans, options.replaceStyle);++ const upstreamSkipped = successes.some(r => r.upstreamSkipped);++ if (upstreamSkipped) {+ return {+ status: "skipped",+ reason: "upstream_skipped",+ redactedMarkdown,+ spans,+ counts: countByEntity(spans),+ };+ }++ return {+ status: "ok",+ redactedMarkdown,+ spans,+ counts: countByEntity(spans),+ };+}diff --git a/apps/api/src/lib/scrape-billing.ts b/apps/api/src/lib/scrape-billing.tsindex 7b5f0dcd3..c033f4680 100644--- a/apps/api/src/lib/scrape-billing.ts+++ b/apps/api/src/lib/scrape-billing.ts@@ -15,6 +15,10 @@ const creditsPerPDFPage = 1;const stealthProxyCostBonus = 4;const unblockedDomainCostBonus = 4;const xTwitterCostBonus = 29;+const redactPIICostBonus = 4;+// Each additional PDF page also gets redacted through fire-privacy, so+// the per-page surcharge mirrors the +4 base β same tier as lockdown.+const redactPIIPdfPageCostBonus = 4;export async function calculateCreditsToBeBilled(options: ScrapeOptions,@@ -103,12 +107,25 @@ export async function calculateCreditsToBeBilled(}const shouldParse = shouldParsePDF(options.parsers);- if (+ const extraPdfPages =shouldParse &&document.metadata?.numPages !== undefined &&document.metadata.numPages > 1- ) {- creditsToBeBilled += creditsPerPDFPage * (document.metadata.numPages - 1);+ ? document.metadata.numPages - 1+ : 0;+ if (extraPdfPages > 0) {+ creditsToBeBilled += creditsPerPDFPage * extraPdfPages;+ }++ if (options.redactPII) {+ // Flat +4 to match lockdown / audio / video / stealth β fire-privacy+ // is a peer premium feature, not a cost-based one. PDF pages all+ // pass through redaction too, so each additional page picks up+ // another +4 on top of the +1 page parse cost.+ creditsToBeBilled += redactPIICostBonus;+ if (extraPdfPages > 0) {+ creditsToBeBilled += redactPIIPdfPageCostBonus * extraPdfPages;+ }}if (diff --git a/apps/api/src/scraper/scrapeURL/transformers/index.ts b/apps/api/src/scraper/scrapeURL/transformers/index.tsindex 9af263688..105bd7d90 100644--- a/apps/api/src/scraper/scrapeURL/transformers/index.ts+++ b/apps/api/src/scraper/scrapeURL/transformers/index.ts@@ -19,6 +19,7 @@ import { performAttributes } from "./performAttributes";import { deriveDiff } from "./diff";import { fetchAudio } from "./audio";import { fetchVideo } from "./video";+import { performRedactPII } from "./redactPII";import { useIndex, useSearchIndex } from "../../../services/index";import { sendDocumentToIndex } from "../engines/index/index";import { sendDocumentToSearchIndex } from "./sendToSearchIndex";@@ -85,6 +86,9 @@ async function deriveMarkdownFromHTML(// - json format requires markdown (for LLM extraction)// - summary format requires markdown (for summarization)// - question/highlights/query formats require markdown (for page-level answers)+ // - pii format redacts markdown (spans are markdown char offsets) β but+ // only when redactPII is actually enabled; otherwise performRedactPII+ // bails immediately and the derived markdown is wasted work.const hasMarkdown = hasFormatOfType(meta.options.formats, "markdown");const hasChangeTracking = hasFormatOfType(meta.options.formats,@@ -95,6 +99,8 @@ async function deriveMarkdownFromHTML(const hasQuestion = hasFormatOfType(meta.options.formats, "question");const hasHighlights = hasFormatOfType(meta.options.formats, "highlights");const hasQuery = hasFormatOfType(meta.options.formats, "query");+ const hasPii =+ hasFormatOfType(meta.options.formats, "pii") && !!meta.options.redactPII;if (!hasMarkdown &&!hasChangeTracking &&@@ -103,6 +109,7 @@ async function deriveMarkdownFromHTML(!hasQuestion &&!hasHighlights &&!hasQuery &&+ !hasPii &&!meta.options.onlyCleanContent) {return document;@@ -494,6 +501,19 @@ function coerceFieldsToFormats(meta: Meta, document: Document): Document {);}+ // pii is only surfaced when both `pii` is in formats and `redactPII: true`.+ // Drop any stale block (e.g. from a cached doc) otherwise so the response+ // matches the documented contract.+ const hasPii = hasFormatOfType(meta.options.formats, "pii");+ const wantPii = !!(hasPii && meta.options.redactPII);+ if (!wantPii && document.pii !== undefined) {+ delete document.pii;+ } else if (wantPii && document.pii === undefined) {+ meta.logger.warn(+ "Request had format: pii with redactPII: true, but there was no pii field in the result.",+ );+ }+if (!hasChangeTracking && document.changeTracking !== undefined) {meta.logger.warn("Removed changeTracking from Document because it wasn't in formats -- this is extremely wasteful and indicates a bug.",@@ -553,6 +573,7 @@ const transformerStack: Transformer[] = [deriveHTMLFromRawHTML,deriveMarkdownFromHTML,performCleanContent,+ performRedactPII,deriveLinksFromHTML,deriveImagesFromHTML,deriveBrandingFromActions,diff --git a/apps/api/src/scraper/scrapeURL/transformers/redactPII.test.ts b/apps/api/src/scraper/scrapeURL/transformers/redactPII.test.tsnew file mode 100644index 000000000..878752b5f--- /dev/null+++ b/apps/api/src/scraper/scrapeURL/transformers/redactPII.test.ts@@ -0,0 +1,90 @@+import { performRedactPII } from "./redactPII";+import { redactText } from "../../../lib/fire-privacy-client";++jest.mock("../../../lib/fire-privacy-client", () => ({+ redactText: jest.fn(),+}));++const mockedRedactText = redactText as jest.MockedFunction<typeof redactText>;++describe("performRedactPII", () => {+ const baseMeta = () =>+ ({+ url: "https://example.com",+ options: {+ formats: [{ type: "markdown" }, { type: "pii" }],+ redactPII: {+ mode: "accurate",+ replaceStyle: "tag",+ },+ },+ logger: {+ debug: jest.fn(),+ info: jest.fn(),+ warn: jest.fn(),+ error: jest.fn(),+ },+ }) as any;+ const baseDocument = (overrides: Record<string, unknown> = {}) =>+ ({+ metadata: {},+ ...overrides,+ }) as any;++ beforeEach(() => {+ mockedRedactText.mockReset();+ });++ it("replaces markdown with redacted markdown", async () => {+ mockedRedactText.mockResolvedValue({+ status: "ok",+ redactedMarkdown: "Hello <PERSON>",+ spans: [],+ counts: {},+ });++ const document = await performRedactPII(+ baseMeta(),+ baseDocument({+ markdown: "Hello Alice",+ }),+ );++ expect(document.markdown).toBe("Hello <PERSON>");+ expect(document.pii?.redactedMarkdown).toBe("Hello <PERSON>");+ });++ it("keeps markdown as an empty string when redaction cannot produce safe output", async () => {+ mockedRedactText.mockResolvedValue({+ status: "failed",+ reason: "error",+ redactedMarkdown: null,+ spans: [],+ counts: {},+ });++ const document = await performRedactPII(+ baseMeta(),+ baseDocument({+ markdown: "Hello Alice",+ }),+ );++ expect(document.markdown).toBe("");+ expect(document.pii?.redactedMarkdown).toBeNull();+ });++ it("keeps downstream markdown consumers safe when source markdown is missing", async () => {+ const document = await performRedactPII(baseMeta(), baseDocument());++ expect(mockedRedactText).not.toHaveBeenCalled();+ expect(document.markdown).toBe("");+ expect(document.pii).toEqual({+ status: "skipped",+ reason: "empty_input",+ redactedMarkdown: null,+ spans: [],+ counts: {},+ });+ });+});diff --git a/apps/api/src/scraper/scrapeURL/transformers/redactPII.ts b/apps/api/src/scraper/scrapeURL/transformers/redactPII.tsnew file mode 100644index 000000000..6384305a9--- /dev/null+++ b/apps/api/src/scraper/scrapeURL/transformers/redactPII.ts@@ -0,0 +1,46 @@+import { Meta } from "..";+import { Document } from "../../../controllers/v2/types";+import { hasFormatOfType } from "../../../lib/format-utils";+import { redactText } from "../../../lib/fire-privacy-client";++export async function performRedactPII(+ meta: Meta,+ document: Document,+): Promise<Document> {+ if (!meta.options.redactPII) return document;+ if (!hasFormatOfType(meta.options.formats, "pii")) return document;++ // pii format requires markdown to redact. If the markdown derivation step+ // ran and produced nothing, we surface that as `skipped` rather than calling+ // fire-privacy with an empty body.+ if (typeof document.markdown !== "string") {+ document.pii = {+ status: "skipped",+ reason: "empty_input",+ redactedMarkdown: null,+ spans: [],+ counts: {},+ };+ document.markdown = "";+ return document;+ }++ document.pii = await redactText({+ text: document.markdown,+ url: meta.url,+ logger: meta.logger,+ // meta.options.redactPII is normalized by the Zod transform β+ // truthy here means it's the options object; falsy was already+ // bailed out of above.+ options: meta.options.redactPII || undefined,+ });++ // Swap raw markdown for the redacted version. Caller asked for PII+ // redaction; leaving the leaky one in `document.markdown` next to+ // `document.pii.redactedMarkdown` is a footgun. On `failed` /+ // `skipped: too_large` (redactedMarkdown === null), fail closed with+ // an empty string so later transformers still receive markdown-shaped input.+ document.markdown = document.pii.redactedMarkdown ?? "";++ return document;+}diff --git a/apps/js-sdk/firecrawl/src/v2/types.ts b/apps/js-sdk/firecrawl/src/v2/types.tsindex 863c9b72e..0dbd41361 100644--- a/apps/js-sdk/firecrawl/src/v2/types.ts+++ b/apps/js-sdk/firecrawl/src/v2/types.ts@@ -14,7 +14,8 @@ export type FormatString =| "attributes"| "branding"| "audio"- | "video";+ | "video"+ | "pii";export interface Viewport {width: number;@@ -205,6 +206,7 @@ export interface ScrapeOptions {minAge?: number;storeInCache?: boolean;lockdown?: boolean;+ redactPII?: boolean | RedactPIIOptions;profile?: {name: string;saveChanges?: boolean;@@ -213,6 +215,70 @@ export interface ScrapeOptions {origin?: string;}+export type RedactPIIEntity =+ | "PERSON"+ | "EMAIL"+ | "PHONE"+ | "LOCATION"+ | "FINANCIAL"+ | "SECRET";++export interface RedactPIIOptions {+ /**+ * accurate (default): model-only redaction. Best precision, cleanest output.+ * aggressive: model + Presidio + spaCy. Higher recall at the cost of precision.+ * fast: Presidio only, no model call. Lower F1, ~2x throughput.+ */+ mode?: "accurate" | "aggressive" | "fast";+ /** Restrict redaction to these entity buckets. Unset means all entities. */+ entities?: RedactPIIEntity[];+ /**+ * tag (default): replace spans with `<KIND>` placeholders.+ * mask: replace spans with `*` of equal length.+ * remove: drop span characters entirely.+ */+ replaceStyle?: "tag" | "mask" | "remove";+}++export type PIISource = "model" | "heuristics" | "unknown";++export interface PIISpan {+ start: number;+ end: number;+ /** Unified entity bucket. Omitted when `kind` doesn't map onto one. */+ entity?: RedactPIIEntity;+ /** Granular recognizer label from fire-privacy. */+ kind: string;+ source: PIISource;+ /** Confidence in [0, 1] when supplied. */+ score?: number;+}++/**+ * - ok: redaction completed; redactedMarkdown is the result.+ * - skipped: redaction was not performed; see `reason`.+ * - failed: redaction was attempted but did not produce a usable result.+ */+export type PIIStatus = "ok" | "skipped" | "failed";++/** Always set when status !== "ok". */+export type PIIReason =+ | "empty_input"+ | "too_large"+ | "upstream_skipped"+ | "service_unavailable"+ | "timeout"+ | "error";++export interface PIIBlock {+ status: PIIStatus;+ reason?: PIIReason;+ redactedMarkdown: string | null;+ spans: PIISpan[];+ /** Span count per entity bucket. Only non-zero entries are present. */+ counts: Partial<Record<RedactPIIEntity, number>>;+}+export type ParseFileData =| Blob| File@@ -483,6 +549,7 @@ export interface Document {warning?: string;changeTracking?: Record<string, unknown>;branding?: BrandingProfile;+ pii?: PIIBlock;}// Pagination configuration for auto-fetching pages from v2 endpoints that return a `next` URLdiff --git a/apps/python-sdk/firecrawl/v2/types.py b/apps/python-sdk/firecrawl/v2/types.pyindex aef032208..8dcec63d2 100644--- a/apps/python-sdk/firecrawl/v2/types.py+++ b/apps/python-sdk/firecrawl/v2/types.py@@ -262,6 +262,66 @@ class BrandingProfile(BaseModel):personality: Optional[Dict[str, Any]] = None+RedactPIIEntity = Literal[+ "PERSON",+ "EMAIL",+ "PHONE",+ "LOCATION",+ "FINANCIAL",+ "SECRET",+]++PIISource = Literal["model", "heuristics", "unknown"]+++class PIISpan(BaseModel):+ """A single PII detection in the source markdown."""++ start: int+ end: int+ # Unified entity bucket. Present when `kind` maps onto one of the+ # public entity buckets; omitted when fire-privacy returned a+ # recognizer kind that doesn't map.+ entity: Optional[RedactPIIEntity] = None+ # Granular recognizer label from fire-privacy (e.g. PRIVATE_PERSON,+ # EMAIL_ADDRESS). Prefer `entity` for taxonomy-level checks.+ kind: str+ source: PIISource+ # Confidence in [0, 1] when the recognizer supplied one.+ score: Optional[float] = None+++# ok β redaction completed; redactedMarkdown is the result.+# skipped β redaction was not performed; see `reason`.+# failed β redaction was attempted but did not produce a usable result;+# see `reason`. redactedMarkdown is None.+PIIStatus = Literal["ok", "skipped", "failed"]++# Always set when status != "ok".+PIIReason = Literal[+ "empty_input",+ "too_large",+ "upstream_skipped",+ "service_unavailable",+ "timeout",+ "error",+]+++class PIIBlock(BaseModel):+ """Result of the PII redaction step."""++ status: PIIStatus+ reason: Optional[PIIReason] = None+ redacted_markdown: Optional[str] = Field(default=None, alias="redactedMarkdown")+ spans: List[PIISpan] = []+ # Span count per public entity bucket. Spans whose `kind` doesn't+ # map onto a bucket are not counted.+ counts: Dict[RedactPIIEntity, int] = {}++ model_config = {"populate_by_name": True}++class Document(BaseModel):"""A scraped document."""@@ -282,6 +342,7 @@ class Document(BaseModel):warning: Optional[str] = Nonechange_tracking: Optional[Dict[str, Any]] = Nonebranding: Optional[BrandingProfile] = None+ pii: Optional[PIIBlock] = None@propertydef metadata_typed(self) -> DocumentMetadata:@@ -408,6 +469,7 @@ FormatString = Literal["query","audio","video",+ "pii",# snake_case versions (user-friendly)"raw_html","change_tracking",@@ -553,6 +615,25 @@ class ScrapeFormats(BaseModel):return normalized_formats+class RedactPIIOptions(BaseModel):+ """Tuning options for the PII redaction step."""++ # accurate (default): model-only. Best precision, cleanest output.+ # aggressive: model + Presidio + spaCy. Higher recall, lower precision.+ # fast: Presidio only, no model call. Lower F1, ~2x throughput.+ mode: Optional[Literal["accurate", "aggressive", "fast"]] = None+ # Restrict redaction to these entity buckets. Unset means all entities.+ entities: Optional[List[RedactPIIEntity]] = None+ # tag (default): replace spans with `<KIND>` placeholders.+ # mask: replace spans with `*` of equal length.+ # remove: drop span characters entirely.+ replace_style: Optional[Literal["tag", "mask", "remove"]] = Field(+ default=None, alias="replaceStyle"+ )++ model_config = {"populate_by_name": True}++class ScrapeOptions(BaseModel):"""Options for scraping operations."""@@ -591,9 +672,14 @@ class ScrapeOptions(BaseModel):min_age: Optional[int] = Nonestore_in_cache: Optional[bool] = Nonelockdown: Optional[bool] = None+ redact_pii: Optional[Union[bool, RedactPIIOptions]] = Field(+ default=None, alias="redactPII"+ )profile: Optional[Dict[str, Any]] = Noneintegration: Optional[str] = None+ model_config = {"populate_by_name": True}+@field_validator("formats")@classmethoddef validate_formats(cls, v):diff --git a/apps/python-sdk/firecrawl/v2/utils/validation.py b/apps/python-sdk/firecrawl/v2/utils/validation.pyindex 3b3fca58e..e5e8e9c56 100644--- a/apps/python-sdk/firecrawl/v2/utils/validation.py+++ b/apps/python-sdk/firecrawl/v2/utils/validation.py@@ -565,13 +565,22 @@ def prepare_scrape_options(options: Optional[ScrapeOptions]) -> Optional[Dict[st"use_mock": "useMock","block_ads": "blockAds","store_in_cache": "storeInCache",- "max_age": "maxAge"+ "max_age": "maxAge",+ "redact_pii": "redactPII",}# Apply field mappingsfor snake_case, camel_case in field_mappings.items():if snake_case in options_data:scrape_data[camel_case] = options_data.pop(snake_case)++ # redactPII may be a nested object whose inner `replace_style` field+ # also needs camel-casing.+ if isinstance(scrape_data.get("redactPII"), dict):+ if "replace_style" in scrape_data["redactPII"]:+ scrape_data["redactPII"]["replaceStyle"] = scrape_data["redactPII"].pop(+ "replace_style"+ )# Handle special casesfor key, value in options_data.items():