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
9 changes: 1 addition & 8 deletions web/src/lib/security-types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -111,19 +111,13 @@ export interface SecurityRuleView {
custom: boolean;
/** English name. A custom rule's name, in no particular language. */
name: string;
/** Chinese name: every built-in rule has one; custom rules do not. */
name_zh?: string;
/** Why the rule is worth a look (English). Absent where the name says it, and on custom rules. */
why?: string;
/** The same, in Chinese. */
why_zh?: string;
/**
* What a built-in redaction rule finds, as a sentence (English); text in
* backticks is code. Absent on the other guards and on custom rules.
*/
about?: string;
/** The same, in Chinese. */
about_zh?: string;
/**
* Group: the `slug` of one of the guard's `kinds`. Custom rules: `custom`.
*/
Expand All @@ -144,12 +138,11 @@ export interface SecurityRuleView {
replacement?: string | null;
}

/** A group of a guard's rule table, named in both languages. */
/** A group of a guard's rule table, with its English name. */
export interface SecurityKindView {
/** What a rule's `kind` says. */
slug: string;
name: string;
name_zh: string;
}

export interface GuardDetail {
Expand Down
2 changes: 1 addition & 1 deletion web/src/routes/gateway/security/exceptions-panel.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ export function ExceptionsPanel({ detail, canWrite }: { detail: GuardDetail; can
const max = query.data?.max ?? 500;
const full = items.length >= max;
const rule = (e: RedactException) =>
e.rule ? ruleName(i18n.language, detail, e.rule, false, e.rule) : t('contentSecurity.exceptions.noRule');
e.rule ? ruleName(i18n.language, 'redact', detail, e.rule, false, e.rule) : t('contentSecurity.exceptions.noRule');

const addButton = (
<Button
Expand Down
19 changes: 12 additions & 7 deletions web/src/routes/gateway/security/guard-panel.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -244,8 +244,13 @@ function RuleTable({
const lang = i18n.language;
const content = guard === 'content';
const groupKey = (r: SecurityRuleView) => (r.custom ? 'custom' : r.kind);
const groupTitle = (key: string) => kindName(lang, kinds, key);
const shown = rules.filter((r) => matchesSearch(r, viewName(lang, r), query));
const groupTitle = (key: string) => kindName(lang, guard, kinds, key);
const shown = rules.filter((r) =>
matchesSearch(r, viewName(lang, guard, r), query, [
viewName('zh', guard, r),
ruleAbout('zh', guard, r),
]),
);
const columns = content ? 6 : 5;

return (
Expand Down Expand Up @@ -320,7 +325,7 @@ function MatchCell({ guard, r }: { guard: Guard; r: SecurityRuleView }) {
const { i18n } = useTranslation();
const m = r.matcher;
// A built-in redaction rule says what it finds in its own words.
const about = ruleAbout(i18n.language, r);
const about = ruleAbout(i18n.language, guard, r);
if (about) return <About text={about} />;
if (guard === 'redact') return <MatcherText m={m} />;
// Tool and content rules show the pattern itself (how it treats case is
Expand Down Expand Up @@ -353,7 +358,7 @@ function ActionCell({
onAct: (action: RuleAction) => void;
}) {
const { t, i18n } = useTranslation();
const name = viewName(i18n.language, r);
const name = viewName(i18n.language, guard, r);
const action = r.action ?? 'record';
const scope = ruleScope(r);
const label = (a: RuleAction) =>
Expand Down Expand Up @@ -403,10 +408,10 @@ function RuleRow({
actions: RuleActions;
}) {
const { t, i18n } = useTranslation();
const name = viewName(i18n.language, r);
const why = ruleWhy(i18n.language, r);
const name = viewName(i18n.language, guard, r);
const why = ruleWhy(i18n.language, guard, r);
const pattern = patternOf(r)?.pattern;
const about = ruleAbout(i18n.language, r).replaceAll('`', '');
const about = ruleAbout(i18n.language, guard, r).replaceAll('`', '');
const open = () => actions.open(r);
const onKeyDown = (e: KeyboardEvent<HTMLTableRowElement>) => {
if (e.target !== e.currentTarget) return;
Expand Down
225 changes: 225 additions & 0 deletions web/src/routes/gateway/security/guard.zh.json

Large diffs are not rendered by default.

8 changes: 4 additions & 4 deletions web/src/routes/gateway/security/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -156,7 +156,7 @@ export function GatewaySecurityPage() {
function toggle(guard: Guard, rule: SecurityRuleView, enabled: boolean, undoable = true) {
const d = current(guard);
if (!d) return;
const name = viewName(i18n.language, rule);
const name = viewName(i18n.language, guard, rule);
write(guard, withEnabled(d, rule, enabled), true).then(
() =>
toast.success(
Expand Down Expand Up @@ -199,7 +199,7 @@ export function GatewaySecurityPage() {
if (!d) return;
const before = d.rules.find((r) => r.custom === rule.custom && r.id === rule.id)?.action ?? 'record';
if (before === action) return;
const name = viewName(i18n.language, rule);
const name = viewName(i18n.language, guard, rule);
write(guard, withAction(d, rule, action), true).then(
() =>
toast.success(
Expand Down Expand Up @@ -230,7 +230,7 @@ export function GatewaySecurityPage() {
if (!d) return;
await write(guard, withAction(d, rule, action), false);
setDialog(null);
toast.success(t('contentSecurity.toast.ruleSaved', { name: viewName(i18n.language, rule) }));
toast.success(t('contentSecurity.toast.ruleSaved', { name: viewName(i18n.language, guard, rule) }));
}

async function removeCustom(guard: Guard, rule: SecurityRuleView) {
Expand All @@ -257,7 +257,7 @@ export function GatewaySecurityPage() {
guard,
editing: null,
seed: {
name: viewName(i18n.language, rule),
name: viewName(i18n.language, guard, rule),
pattern: written.pattern,
match: written.match,
action: rule.action ?? null,
Expand Down
2 changes: 1 addition & 1 deletion web/src/routes/gateway/security/log-panel.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -167,7 +167,7 @@ function EventRow({ e, detail }: { e: GuardEvent; detail: SecurityDetail | undef
const d = e.detail ?? {};
if (!guard) return null;
const outcome = outcomeOf(t, e.action, d);
const rule = d.rule ? ruleName(i18n.language, detail?.[guard], d.rule, d.custom === true, d.rule_name) : '—';
const rule = d.rule ? ruleName(i18n.language, guard, detail?.[guard], d.rule, d.custom === true, d.rule_name) : '—';
const sources = new Intl.ListFormat(i18n.language, { type: 'conjunction' }).format(sourcesOf(t, d));
const when = new Date(e.created_at);
return (
Expand Down
36 changes: 20 additions & 16 deletions web/src/routes/gateway/security/names.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,9 @@ const rule = (over: Partial<SecurityRuleView>): SecurityRuleView => ({
id: 'groq-key',
custom: false,
name: 'Groq API key',
name_zh: 'Groq API 密钥',
about: 'Starts with `gsk_`',
about_zh: '`gsk_` 开头',
kind: 'ai-services',
matcher: { kind: 'builtin', check: 'groq-key' },
matcher: { kind: 'prefix', prefix: 'gsk_', min_tail: 20 },
enabled: true,
on_by_default: true,
...over,
Expand All @@ -19,24 +17,30 @@ const rule = (over: Partial<SecurityRuleView>): SecurityRuleView => ({
const detail: GuardDetail = {
mode: 'observe',
rules: [rule({})],
kinds: [{ slug: 'ai-services', name: 'AI services', name_zh: 'AI 服务' }],
kinds: [{ slug: 'ai-services', name: 'AI services' }],
}

describe('rule text from the view', () => {
describe('client-owned rule translations', () => {
it('is shown in the console language, English where no Chinese is given', () => {
expect(viewName('zh', rule({}))).toBe('Groq API 密钥')
expect(viewName('en', rule({}))).toBe('Groq API key')
expect(viewName('zh', rule({ name_zh: undefined }))).toBe('Groq API key')
expect(ruleAbout('zh', rule({}))).toBe('`gsk_` 开头')
expect(ruleWhy('zh', rule({ why: 'Because', why_zh: '因为' }))).toBe('因为')
expect(kindName('zh', detail.kinds, 'ai-services')).toBe('AI 服务')
expect(kindName('en', detail.kinds, 'unknown')).toBe('unknown')
expect(viewName('zh', 'redact', rule({}))).toBe('Groq API 密钥')
expect(viewName('en', 'redact', rule({}))).toBe('Groq API key')
expect(viewName('zh', 'redact', rule({ id: 'new-key' }))).toBe('Groq API key')
expect(ruleAbout('zh', 'redact', rule({}))).toBe('`gsk_` 开头,其后至少 20 个字符')
expect(ruleWhy('zh', 'content', rule({ id: 'bidi-controls', why: 'Because' }))).toBe('可使屏幕上的显示顺序与实际字符顺序不一致。')
expect(kindName('zh', 'redact', detail.kinds, 'ai-services')).toBe('AI 服务')
expect(kindName('en', 'redact', detail.kinds, 'unknown')).toBe('unknown')
})

it('names a custom rule by its own name, and a log row by id', () => {
expect(viewName('zh', rule({ id: 'Codename', custom: true, name: 'Codename' }))).toBe('Codename')
expect(ruleName('zh', detail, 'groq-key', false)).toBe('Groq API 密钥')
expect(ruleName('zh', detail, 'gone-rule', false, 'Gone rule')).toBe('Gone rule')
expect(ruleName('zh', undefined, 'gone-rule', false)).toBe('gone-rule')
expect(viewName('zh', 'redact', rule({ id: 'Codename', custom: true, name: 'Codename' }))).toBe('Codename')
expect(ruleName('zh', 'redact', detail, 'groq-key', false)).toBe('Groq API 密钥')
expect(ruleName('zh', 'redact', detail, 'gone-rule', false, 'Gone rule')).toBe('Gone rule')
expect(ruleName('zh', 'redact', undefined, 'gone-rule', false)).toBe('gone-rule')
})

it('resolves a shared ID separately for each guard', () => {
const entry = rule({ id: 'you-are-now' })
expect(viewName('zh', 'inspect_tools', entry)).toBe('重新设定模型身份')
expect(viewName('zh', 'content', entry)).toBe('重新设定身份')
})
})
55 changes: 37 additions & 18 deletions web/src/routes/gateway/security/names.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,17 +3,34 @@ import type {
Guard,
GuardDetail,
GuardMode,
Matcher,
RuleAction,
RuleScope,
SecurityKindView,
SecurityRuleView,
} from '@/lib/security-types';
import CATALOG from './guard.zh.json';

// Names on the security page. A built-in rule's name, reason and
// description, and each group's name, come with the rule view in both
// languages (thinkwatch-core writes them once for both products); the
// console keeps no table of its own. A custom rule's id is the name its
// author gave it.
// Built-in display text is translated by guard and ID. The view supplies
// English fallbacks and custom rules keep their original names.
type RuleCopy = { name: string; why?: string; about?: string };
const catalog: Record<Guard, { rules: Record<string, RuleCopy>; kinds: Record<string, string> }> = CATALOG;

function guardAboutZh(m: Matcher): string | undefined {
if (m.kind !== "prefix" && m.kind !== "prefixes") return undefined;
const prefixes = m.kind === "prefix" ? [{ ...m, tail: "any" }] : m.prefixes;
const groups = new Map<string, { prefixes: string[]; length: number; unit: string }>();
for (const p of prefixes) {
const key = `${p.min_tail}:${p.tail}`;
const unit = p.tail === "hex" ? "十六进制字符" : p.tail === "alnum" ? "字母或数字" : "字符";
const group = groups.get(key) ?? { prefixes: [], length: p.min_tail, unit };
group.prefixes.push(`\`${p.prefix}\``);
groups.set(key, group);
}
return [...groups.values()].map(({ prefixes, length, unit }) =>
`${prefixes.join("、")} 开头,其后至少 ${length} 个${unit}`,
).join(";") || undefined;
}

export function guardName(t: TFunction, guard: Guard): string {
return t(`contentSecurity.guard.${guard}.name`);
Expand All @@ -29,20 +46,19 @@ export function scopeName(t: TFunction, scope: RuleScope): string {
return t(`contentSecurity.scope.${scope}`);
}

/** Whether the console is in Chinese: rule text comes from the server in both languages. */
function zh(lang: string): boolean {
return lang.startsWith('zh');
}

/** The Chinese text in Chinese when there is one, else the English. */
function pick(lang: string, en: string | undefined, cn: string | undefined): string {
return (zh(lang) && cn ? cn : en) ?? '';
function ruleCopy(guard: Guard, id: string): RuleCopy | undefined {
const rules = catalog[guard].rules;
return Object.hasOwn(rules, id) ? rules[id] : undefined;
}

/** A rule's name as the view gives it. A custom rule's id is the name its author gave it. */
export function viewName(lang: string, r: SecurityRuleView): string {
export function viewName(lang: string, guard: Guard, r: SecurityRuleView): string {
if (r.custom) return r.id;
return pick(lang, r.name, r.name_zh) || r.id;
return (zh(lang) ? ruleCopy(guard, r.id)?.name : undefined) ?? (r.name || r.id);
}

/**
Expand All @@ -52,32 +68,35 @@ export function viewName(lang: string, r: SecurityRuleView): string {
*/
export function ruleName(
lang: string,
guard: Guard,
detail: GuardDetail | undefined,
id: string,
custom: boolean,
fallback?: string,
): string {
if (custom) return id;
const r = detail?.rules.find((r) => !r.custom && r.id === id);
return r ? viewName(lang, r) : (fallback ?? id);
return r ? viewName(lang, guard, r) : ((zh(lang) ? ruleCopy(guard, id)?.name : undefined) ?? fallback ?? id);
}

/** Why a built-in rule is worth a look. Empty for rules that carry no reason. */
export function ruleWhy(lang: string, r: SecurityRuleView): string {
export function ruleWhy(lang: string, guard: Guard, r: SecurityRuleView): string {
if (r.custom) return '';
return pick(lang, r.why, r.why_zh);
return (zh(lang) ? ruleCopy(guard, r.id)?.why : undefined) ?? r.why ?? '';
}

/** What a built-in redaction rule finds, as a sentence; backticks mark code. Empty elsewhere. */
export function ruleAbout(lang: string, r: SecurityRuleView): string {
export function ruleAbout(lang: string, guard: Guard, r: SecurityRuleView): string {
if (r.custom) return '';
return pick(lang, r.about, r.about_zh);
return (zh(lang) ? guardAboutZh(r.matcher) ?? ruleCopy(guard, r.id)?.about : undefined) ?? r.about ?? '';
}

/** A rule group's heading, from the guard's view. */
export function kindName(lang: string, kinds: SecurityKindView[] | undefined, slug: string): string {
export function kindName(lang: string, guard: Guard, kinds: SecurityKindView[] | undefined, slug: string): string {
const copy = catalog[guard].kinds;
if (zh(lang) && Object.hasOwn(copy, slug)) return copy[slug] ?? slug;
const k = kinds?.find((k) => k.slug === slug);
return k ? pick(lang, k.name, k.name_zh) : slug;
return k?.name ?? slug;
}

export function actionName(t: TFunction, action: RuleAction): string {
Expand Down
5 changes: 2 additions & 3 deletions web/src/routes/gateway/security/policy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -313,17 +313,16 @@ function literalsOf(m: Matcher): string[] {
* rule's description, prefixes or field names — ignoring case. An empty
* search matches every rule.
*/
export function matchesSearch(r: SecurityRuleView, shownName: string, query: string): boolean {
export function matchesSearch(r: SecurityRuleView, shownName: string, query: string, translations: readonly string[] = []): boolean {
const q = query.trim().toLowerCase();
if (!q) return true;
const pattern = patternOf(r)?.pattern ?? '';
return [
shownName,
r.id,
r.name,
r.name_zh ?? '',
r.about ?? '',
r.about_zh ?? '',
...translations,
pattern,
...literalsOf(r.matcher),
].some((s) => s.toLowerCase().includes(q));
Expand Down
12 changes: 6 additions & 6 deletions web/src/routes/gateway/security/rule-dialogs.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -688,8 +688,8 @@ export function BuiltinRuleDialog({
const [saving, setSaving] = useState(false);
const [error, setError] = useState<string | null>(null);
const trial = useTrial(guard, { sample, rule: rule.id, action });
const why = ruleWhy(lang, rule);
const about = ruleAbout(lang, rule);
const why = ruleWhy(lang, guard, rule);
const about = ruleAbout(lang, guard, rule);
const changed = action !== initial;

async function save() {
Expand All @@ -708,11 +708,11 @@ export function BuiltinRuleDialog({
<DialogContent className="sm:max-w-xl">
<DialogHeader>
<DialogTitle className="flex items-center gap-2">
{viewName(lang, rule)}
{viewName(lang, guard, rule)}
<Badge variant="secondary">{t('contentSecurity.builtinGroup')}</Badge>
</DialogTitle>
<DialogDescription>
{why || t('contentSecurity.dialog.category', { kind: kindName(lang, kinds, rule.kind) })}
{why || t('contentSecurity.dialog.category', { kind: kindName(lang, guard, kinds, rule.kind) })}
</DialogDescription>
</DialogHeader>

Expand Down Expand Up @@ -873,10 +873,10 @@ export function TestDialog({
{hits.map((h, i) => (
<TableRow key={`${h.rule}:${h.start}:${i}`}>
<TableCell className="truncate">
{ruleName(lang, detail, h.rule, h.custom)}
{ruleName(lang, guard, detail, h.rule, h.custom)}
{h.custom && (
<Badge variant="outline" className="ml-1.5">
{kindName(lang, detail?.kinds, 'custom')}
{kindName(lang, guard, detail?.kinds, 'custom')}
</Badge>
)}
</TableCell>
Expand Down
Loading
Loading