Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
- **A complete support flow:** embed a branded widget with citations, handoff, feedback, cards, carousels, quick replies, and bounded forms.
- **A team inbox:** route work with agent presence, capacity limits, and response or resolution targets.
- **Operational visibility:** review knowledge gaps, model use, cost, latency, prompt releases, and retrieval evaluations.
- **Privacy controls:** choose whether email, phone, payment-card, and credential values are redacted from new transcripts and before AI or tool requests.
- **Self-hosted by design:** run on PostgreSQL with pgvector and connect a supported hosted or local model provider.

## See the product
Expand Down
14 changes: 14 additions & 0 deletions apps/admin/src/features/bots/bots.spec.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ const BOT: BotDto = {
rerankingEnabled: false,
queryRewritingEnabled: false,
answerVerificationEnabled: false,
piiRedactionCategories: [],
noAnswerBehavior: 'offer_handoff',
handoffEnabled: true,
automaticHandoffSummaries: false,
Expand Down Expand Up @@ -341,6 +342,19 @@ describe('BotModelForm', () => {
});

describe('BotBehaviorForm', () => {
it('saves the selected privacy redaction categories', async () => {
const calls = mockApi(botRoutes());
renderWithQuery(asRole(ADMIN, <BotBehaviorForm workspaceId={WS} botId={BOT_ID} />));

await userEvent.click(await screen.findByRole('checkbox', { name: 'Email addresses' }));
await userEvent.click(screen.getByRole('button', { name: strings.bots.save }));

await screen.findByText(strings.bots.saved);
expect(calls.find((call) => call.method === 'PATCH')?.body).toMatchObject({
piiRedactionCategories: ['email'],
});
});

it('lets an admin opt the bot into privacy-aware follow-up query rewriting', async () => {
const calls = mockApi(botRoutes());
renderWithQuery(asRole(ADMIN, <BotBehaviorForm workspaceId={WS} botId={BOT_ID} />));
Expand Down
57 changes: 53 additions & 4 deletions apps/admin/src/features/bots/components/bot-behavior-form.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,12 @@ import { Label } from '@/components/ui/label';
import { Skeleton } from '@/components/ui/skeleton';
import { errorMessage } from '@/lib/error-message';
import { strings } from '@/strings';
import { NO_ANSWER_BEHAVIORS, type NoAnswerBehavior } from '@app/shared';
import {
NO_ANSWER_BEHAVIORS,
PII_REDACTION_CATEGORIES,
type NoAnswerBehavior,
type PiiRedactionCategory,
} from '@app/shared';

import { useBot, useUpdateBot } from '../api';
import { normalizeOrigins } from '../origin';
Expand All @@ -33,6 +38,9 @@ export function BotBehaviorForm({ workspaceId, botId }: { workspaceId: string; b
const [rerankingEnabled, setRerankingEnabled] = useState<boolean | null>(null);
const [queryRewritingEnabled, setQueryRewritingEnabled] = useState<boolean | null>(null);
const [answerVerificationEnabled, setAnswerVerificationEnabled] = useState<boolean | null>(null);
const [piiRedactionCategories, setPiiRedactionCategories] = useState<
PiiRedactionCategory[] | null
>(null);
const [temperature, setTemperature] = useState<string | null>(null);
const [maxOutputTokens, setMaxOutputTokens] = useState<string | null>(null);
const [dailySpendCap, setDailySpendCap] = useState<string | null>(null);
Expand Down Expand Up @@ -67,6 +75,7 @@ export function BotBehaviorForm({ workspaceId, botId }: { workspaceId: string; b
rerankingEnabled: rerankingEnabled ?? data.rerankingEnabled,
queryRewritingEnabled: queryRewritingEnabled ?? data.queryRewritingEnabled,
answerVerificationEnabled: answerVerificationEnabled ?? data.answerVerificationEnabled,
piiRedactionCategories: piiRedactionCategories ?? data.piiRedactionCategories,
temperature: Number(temperature ?? data.temperature),
maxOutputTokens: Number(maxOutputTokens ?? data.maxOutputTokens),
dailySpendCapUsd:
Expand Down Expand Up @@ -231,9 +240,10 @@ export function BotBehaviorForm({ workspaceId, botId }: { workspaceId: string; b
</label>
<p className="text-xs text-muted-foreground">
Off by default. When enabled, the configured chat provider receives up to two recent
visitor messages after basic email, phone, and long-number redaction. The request is used
only to form a search query; it is not saved in traces. A timeout or invalid result keeps
the original search query. Provider usage may add cost.
visitor messages after basic email, phone, and long-number redaction. Privacy categories
selected below also apply across model requests. The rewrite request is used only to form
a search query and is not saved in traces. A timeout or invalid result keeps the original
search query. Provider usage may add cost.
</p>
<label className="flex items-center gap-2 text-sm">
<input
Expand All @@ -254,6 +264,45 @@ export function BotBehaviorForm({ workspaceId, botId }: { workspaceId: string; b
</p>
</fieldset>

<fieldset className="space-y-3 rounded-md border p-3">
<legend className="px-1 text-sm font-medium">Privacy and data sharing</legend>
<p className="text-xs text-muted-foreground">
Selected values are replaced before transcript storage and before text is sent to AI
providers or configured tools. This also applies to older conversation history. Redaction
is automatic and cannot be reversed.
</p>
{PII_REDACTION_CATEGORIES.map((category) => {
const selected = piiRedactionCategories ?? data.piiRedactionCategories;
const labels: Record<PiiRedactionCategory, string> = {
email: 'Email addresses',
phone: 'Phone numbers',
payment_card: 'Payment card numbers',
credentials: 'Passwords, API keys, and access tokens',
};
return (
<label key={category} className="flex items-center gap-2 text-sm">
<input
type="checkbox"
checked={selected.includes(category)}
disabled={!isAdmin}
onChange={(event) => {
setPiiRedactionCategories(
event.target.checked
? [...selected, category]
: selected.filter((value) => value !== category),
);
}}
/>
{labels[category]}
</label>
);
})}
<p className="text-xs text-muted-foreground">
Detection covers common formats and can miss obfuscated or unusual values. Existing stored
messages are not rewritten; they are redacted whenever included in an AI or tool request.
</p>
</fieldset>

<div className="grid grid-cols-2 gap-4">
<div className="space-y-2">
<Label htmlFor="bot-temperature">{strings.bots.temperature}</Label>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ const BOT_DTO: BotDto = {
rerankingEnabled: false,
queryRewritingEnabled: false,
answerVerificationEnabled: false,
piiRedactionCategories: [],
noAnswerBehavior: 'offer_handoff',
handoffEnabled: true,
csatEnabled: true,
Expand Down
32 changes: 32 additions & 0 deletions apps/api/src/common/pii-redaction.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
// SPDX-License-Identifier: AGPL-3.0-only
import { describe, expect, it } from 'vitest';

import { redactPii, redactUnknown } from './pii-redaction';

describe('PII redaction', () => {
it('redacts only selected categories', () => {
expect(redactPii('Use person@example.com or +1 (555) 123-4567', ['email'])).toBe(
'Use [REDACTED: EMAIL] or +1 (555) 123-4567',
);
});

it('redacts card numbers only when their checksum is valid', () => {
expect(redactPii('Card 4111 1111 1111 1111, ref 4111 1111 1111 1112', ['payment_card'])).toBe(
'Card [REDACTED: PAYMENT CARD], ref 4111 1111 1111 1112',
);
});

it('redacts labeled secrets, bearer values and JWTs', () => {
const jwt = 'eyJabcdefgh.abcdefgh.abcdefgh';
expect(redactPii(`password=hunter2 Bearer abc.def api_key:xyz ${jwt}`, ['credentials'])).toBe(
'password=[REDACTED: CREDENTIAL] Bearer [REDACTED: CREDENTIAL] api_key=[REDACTED: CREDENTIAL] [REDACTED: CREDENTIAL]',
);
});

it('redacts nested provider snapshots without changing non-text values', () => {
expect(redactUnknown({ body: ['person@example.com', 3], ok: true }, ['email'])).toEqual({
body: ['[REDACTED: EMAIL]', 3],
ok: true,
});
});
});
57 changes: 57 additions & 0 deletions apps/api/src/common/pii-redaction.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
// SPDX-License-Identifier: AGPL-3.0-only
import type { PiiRedactionCategory } from '@app/shared';

const EMAIL = /\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}\b/gi;
const PAYMENT_CARD = /\b(?:\d[ -]?){12,18}\d\b/g;
const PHONE = /(?:\+?\d[\d(). -]{7,}\d)/g;
const LABELED_SECRET =
/\b(password|passcode|secret|api[_ -]?key|access[_ -]?token|refresh[_ -]?token)\s*[:=]\s*([^\s,;]+)/gi;
const BEARER_TOKEN = /\bBearer\s+[A-Z0-9._~+/-]+=*/gi;
const JWT = /\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\b/g;

function hasLuhnChecksum(value: string): boolean {
const digits = value.replace(/\D/g, '');
let sum = 0;
let double = false;
for (let index = digits.length - 1; index >= 0; index -= 1) {
const digit = Number(digits[index]);
const transformed = double ? digit * 2 : digit;
sum += transformed > 9 ? transformed - 9 : transformed;
double = !double;
}
return digits.length >= 13 && digits.length <= 19 && sum % 10 === 0;
}

/** Replaces selected common identifiers with stable markers before storage or external calls. */
export function redactPii(text: string, categories: readonly PiiRedactionCategory[]): string {
if (categories.length === 0) return text;
let output = text;
if (categories.includes('email')) output = output.replace(EMAIL, '[REDACTED: EMAIL]');
if (categories.includes('payment_card')) {
output = output.replace(PAYMENT_CARD, (candidate) =>
hasLuhnChecksum(candidate) ? '[REDACTED: PAYMENT CARD]' : candidate,
);
}
if (categories.includes('phone')) output = output.replace(PHONE, '[REDACTED: PHONE]');
if (categories.includes('credentials')) {
output = output
.replace(LABELED_SECRET, (_match, label: string) => `${label}=[REDACTED: CREDENTIAL]`)
.replace(BEARER_TOKEN, 'Bearer [REDACTED: CREDENTIAL]')
.replace(JWT, '[REDACTED: CREDENTIAL]');
}
return output;
}

export function redactUnknown(
value: unknown,
categories: readonly PiiRedactionCategory[],
): unknown {
if (typeof value === 'string') return redactPii(value, categories);
if (Array.isArray(value)) return value.map((item) => redactUnknown(item, categories));
if (value !== null && typeof value === 'object') {
return Object.fromEntries(
Object.entries(value).map(([key, item]) => [key, redactUnknown(item, categories)]),
);
}
return value;
}
16 changes: 16 additions & 0 deletions apps/api/src/db/migrations/1794880000000-pii-redaction.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
// SPDX-License-Identifier: AGPL-3.0-only
import type { MigrationInterface, QueryRunner } from 'typeorm';

export class PiiRedaction1794880000000 implements MigrationInterface {
name = 'PiiRedaction1794880000000';

async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(
`ALTER TABLE "bots" ADD "pii_redaction_categories" text array NOT NULL DEFAULT '{}'`,
);
}

async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(`ALTER TABLE "bots" DROP COLUMN "pii_redaction_categories"`);
}
}
16 changes: 12 additions & 4 deletions apps/api/src/modules/agent-assist/handoff-summary.processor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { escapeAgentAssistText, handoffSummarySchema } from '@app/shared';
import { Clock } from '../../common/clock';
import { newId } from '../../common/ids';
import { parseModelJson } from '../../common/model-json';
import { redactPii, redactUnknown } from '../../common/pii-redaction';
import { asBotId, asCredentialId, asWorkspaceId } from '../../db/ids';
import type { JobHandler } from '../../jobs';
import { JobProcessor } from '../../jobs';
Expand Down Expand Up @@ -56,10 +57,12 @@ export class HandoffSummaryProcessor implements JobHandler<{
daily_spend_cap_usd: string | null;
chat_credential_id: string;
chat_model: string;
pii_redaction_categories?: import('@app/shared').PiiRedactionCategory[] | null;
}[]
>(
`SELECT id, deleted_at, agent_assist_enabled, automatic_handoff_summaries,
monthly_spend_cap_usd, daily_spend_cap_usd, chat_credential_id, chat_model
monthly_spend_cap_usd, daily_spend_cap_usd, chat_credential_id, chat_model,
pii_redaction_categories
FROM bots WHERE workspace_id = $1 AND id = $2`,
[workspaceId, payload.botId],
);
Expand Down Expand Up @@ -107,7 +110,9 @@ export class HandoffSummaryProcessor implements JobHandler<{
);
let transcript = messages
.map((message) => {
const text = escapeAgentAssistText(message.content.slice(0, 2_000));
const text = escapeAgentAssistText(
redactPii(message.content.slice(0, 2_000), bot.pii_redaction_categories ?? []),
);
return `<message role="${message.role}" id="${message.id}">${text}</message>`;
})
.join('\n');
Expand All @@ -133,7 +138,10 @@ export class HandoffSummaryProcessor implements JobHandler<{
for await (const delta of result.textStream) output += delta;
const final = await result.final;
const json = parseModelJson(output);
const content = handoffSummarySchema.parse(json);
const content = redactUnknown(
handoffSummarySchema.parse(json),
bot.pii_redaction_categories ?? [],
) as ReturnType<typeof handoffSummarySchema.parse>;
const elapsed = this.clock.now().getTime() - started;
const providerRows = await this.ds.query<{ provider: string }[]>(
`SELECT provider FROM provider_credentials WHERE workspace_id = $1 AND id = $2`,
Expand Down Expand Up @@ -169,7 +177,7 @@ export class HandoffSummaryProcessor implements JobHandler<{
topScore: null,
decision: 'answered',
decisionReason: 'handoff_summary',
requestSnapshot: final.requestSnapshot,
requestSnapshot: redactUnknown(final.requestSnapshot, bot.pii_redaction_categories ?? []),
toolCalls: null,
inputTokens: final.inputTokens,
outputTokens: final.outputTokens,
Expand Down
13 changes: 8 additions & 5 deletions apps/api/src/modules/agent-assist/reply-suggestions.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import {
import { Clock } from '../../common/clock';
import { AppError } from '../../common/errors';
import { newId } from '../../common/ids';
import { redactPii } from '../../common/pii-redaction';
import { AUDIT_LOG, type AuditWriter } from '../../common/ports/audit';
import { asBotId, asCredentialId, type UserId, type WorkspaceId } from '../../db/ids';
import { Llm } from '../../providers';
Expand Down Expand Up @@ -60,7 +61,8 @@ export class ReplySuggestionsService {
`SELECT id, name, deleted_at, agent_assist_enabled, suggested_replies_enabled,
chat_credential_id, chat_model, embedding_credential_id, embedding_model,
embedding_dim, retrieval_threshold, temperature, max_output_tokens,
monthly_spend_cap_usd, daily_spend_cap_usd, allowed_origins, allowed_link_domains
monthly_spend_cap_usd, daily_spend_cap_usd, allowed_origins, allowed_link_domains,
pii_redaction_categories
FROM bots WHERE workspace_id = $1 AND id = $2`,
[workspaceId, botId],
);
Expand Down Expand Up @@ -165,7 +167,7 @@ export class ReplySuggestionsService {
const retrieved = await this.retrieval.retrieve(
workspaceId,
retrievalBot,
latestVisitor.content.slice(0, 4_000),
redactPii(latestVisitor.content.slice(0, 4_000), bot.pii_redaction_categories ?? []),
new AbortController().signal,
{ bill: false },
);
Expand Down Expand Up @@ -193,13 +195,13 @@ export class ReplySuggestionsService {
const sources = used
.map(
(chunk, index) =>
`<source n="${String(index + 1)}" title="${escapeAgentAssistText(chunk.title)}">${escapeAgentAssistText(chunk.content.slice(0, 3_000))}</source>`,
`<source n="${String(index + 1)}" title="${escapeAgentAssistText(redactPii(chunk.title, bot.pii_redaction_categories ?? []))}">${escapeAgentAssistText(redactPii(chunk.content.slice(0, 3_000), bot.pii_redaction_categories ?? []))}</source>`,
)
.join('\n');
const transcript = messages
.map(
(message) =>
`<message role="${message.role}">${escapeAgentAssistText(message.content.slice(0, 1_500))}</message>`,
`<message role="${message.role}">${escapeAgentAssistText(redactPii(message.content.slice(0, 1_500), bot.pii_redaction_categories ?? []))}</message>`,
)
.join('\n')
.slice(-12_000);
Expand Down Expand Up @@ -233,7 +235,7 @@ export class ReplySuggestionsService {
}));
const parsed = parseCitations(raw, citations);
const draft = applyLinkPolicy(
parsed.text,
redactPii(parsed.text, bot.pii_redaction_categories ?? []),
buildAllowedLinkHosts({
usedSourceUrls: used.map((chunk) => chunk.url),
allowedOrigins: bot.allowed_origins,
Expand Down Expand Up @@ -484,6 +486,7 @@ interface SuggestionBotRow {
daily_spend_cap_usd: string | null;
allowed_origins: string[];
allowed_link_domains: string[];
pii_redaction_categories?: import('@app/shared').PiiRedactionCategory[] | null;
}

interface SuggestionMessageRow {
Expand Down
6 changes: 5 additions & 1 deletion apps/api/src/modules/bots/bot.entity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import {
} from 'typeorm';

import { NO_ANSWER_BEHAVIORS, type NoAnswerBehavior } from '@app/shared';
import type { EvalGate } from '@app/shared';
import type { EvalGate, PiiRedactionCategory } from '@app/shared';

import type { WorkspaceId } from '../../db/ids';
import { TenantEntity } from '../../db/tenant-entity';
Expand Down Expand Up @@ -173,6 +173,10 @@ export class BotEntity extends TenantEntity {
@Column({ type: 'boolean', default: false })
answerVerificationEnabled!: boolean;

/** Sensitive visitor text categories hidden from stored transcripts and external calls. */
@Column({ type: 'text', array: true, default: () => "'{}'" })
piiRedactionCategories!: PiiRedactionCategory[];

/** Sampling temperature for answers (spec §9.2). */
@Column({ type: 'real', default: 0.2 })
temperature!: number;
Expand Down
1 change: 1 addition & 0 deletions apps/api/src/modules/bots/bots.mapper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ export function toBotDto(bot: BotEntity): BotDto {
rerankingEnabled: bot.rerankingEnabled,
queryRewritingEnabled: bot.queryRewritingEnabled,
answerVerificationEnabled: bot.answerVerificationEnabled,
piiRedactionCategories: bot.piiRedactionCategories,
noAnswerBehavior: bot.noAnswerBehavior,
handoffEnabled: bot.handoffEnabled,
csatEnabled: bot.csatEnabled,
Expand Down
Loading