Skip to content

Commit 22ba559

Browse files
authored
fix(i18n): translate security rules in the web console
Resolve built-in rule names and descriptions by stable IDs and group slugs so Core can publish English metadata.
1 parent ea3373c commit 22ba559

11 files changed

Lines changed: 317 additions & 77 deletions

File tree

‎web/src/lib/security-types.ts‎

Lines changed: 1 addition & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -111,19 +111,13 @@ export interface SecurityRuleView {
111111
custom: boolean;
112112
/** English name. A custom rule's name, in no particular language. */
113113
name: string;
114-
/** Chinese name: every built-in rule has one; custom rules do not. */
115-
name_zh?: string;
116114
/** Why the rule is worth a look (English). Absent where the name says it, and on custom rules. */
117115
why?: string;
118-
/** The same, in Chinese. */
119-
why_zh?: string;
120116
/**
121117
* What a built-in redaction rule finds, as a sentence (English); text in
122118
* backticks is code. Absent on the other guards and on custom rules.
123119
*/
124120
about?: string;
125-
/** The same, in Chinese. */
126-
about_zh?: string;
127121
/**
128122
* Group: the `slug` of one of the guard's `kinds`. Custom rules: `custom`.
129123
*/
@@ -144,12 +138,11 @@ export interface SecurityRuleView {
144138
replacement?: string | null;
145139
}
146140

147-
/** A group of a guard's rule table, named in both languages. */
141+
/** A group of a guard's rule table, with its English name. */
148142
export interface SecurityKindView {
149143
/** What a rule's `kind` says. */
150144
slug: string;
151145
name: string;
152-
name_zh: string;
153146
}
154147

155148
export interface GuardDetail {

‎web/src/routes/gateway/security/exceptions-panel.tsx‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,7 @@ export function ExceptionsPanel({ detail, canWrite }: { detail: GuardDetail; can
5656
const max = query.data?.max ?? 500;
5757
const full = items.length >= max;
5858
const rule = (e: RedactException) =>
59-
e.rule ? ruleName(i18n.language, detail, e.rule, false, e.rule) : t('contentSecurity.exceptions.noRule');
59+
e.rule ? ruleName(i18n.language, 'redact', detail, e.rule, false, e.rule) : t('contentSecurity.exceptions.noRule');
6060

6161
const addButton = (
6262
<Button

‎web/src/routes/gateway/security/guard-panel.tsx‎

Lines changed: 12 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -244,8 +244,13 @@ function RuleTable({
244244
const lang = i18n.language;
245245
const content = guard === 'content';
246246
const groupKey = (r: SecurityRuleView) => (r.custom ? 'custom' : r.kind);
247-
const groupTitle = (key: string) => kindName(lang, kinds, key);
248-
const shown = rules.filter((r) => matchesSearch(r, viewName(lang, r), query));
247+
const groupTitle = (key: string) => kindName(lang, guard, kinds, key);
248+
const shown = rules.filter((r) =>
249+
matchesSearch(r, viewName(lang, guard, r), query, [
250+
viewName('zh', guard, r),
251+
ruleAbout('zh', guard, r),
252+
]),
253+
);
249254
const columns = content ? 6 : 5;
250255

251256
return (
@@ -320,7 +325,7 @@ function MatchCell({ guard, r }: { guard: Guard; r: SecurityRuleView }) {
320325
const { i18n } = useTranslation();
321326
const m = r.matcher;
322327
// A built-in redaction rule says what it finds in its own words.
323-
const about = ruleAbout(i18n.language, r);
328+
const about = ruleAbout(i18n.language, guard, r);
324329
if (about) return <About text={about} />;
325330
if (guard === 'redact') return <MatcherText m={m} />;
326331
// Tool and content rules show the pattern itself (how it treats case is
@@ -353,7 +358,7 @@ function ActionCell({
353358
onAct: (action: RuleAction) => void;
354359
}) {
355360
const { t, i18n } = useTranslation();
356-
const name = viewName(i18n.language, r);
361+
const name = viewName(i18n.language, guard, r);
357362
const action = r.action ?? 'record';
358363
const scope = ruleScope(r);
359364
const label = (a: RuleAction) =>
@@ -403,10 +408,10 @@ function RuleRow({
403408
actions: RuleActions;
404409
}) {
405410
const { t, i18n } = useTranslation();
406-
const name = viewName(i18n.language, r);
407-
const why = ruleWhy(i18n.language, r);
411+
const name = viewName(i18n.language, guard, r);
412+
const why = ruleWhy(i18n.language, guard, r);
408413
const pattern = patternOf(r)?.pattern;
409-
const about = ruleAbout(i18n.language, r).replaceAll('`', '');
414+
const about = ruleAbout(i18n.language, guard, r).replaceAll('`', '');
410415
const open = () => actions.open(r);
411416
const onKeyDown = (e: KeyboardEvent<HTMLTableRowElement>) => {
412417
if (e.target !== e.currentTarget) return;

‎web/src/routes/gateway/security/guard.zh.json‎

Lines changed: 225 additions & 0 deletions
Large diffs are not rendered by default.

‎web/src/routes/gateway/security/index.tsx‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -156,7 +156,7 @@ export function GatewaySecurityPage() {
156156
function toggle(guard: Guard, rule: SecurityRuleView, enabled: boolean, undoable = true) {
157157
const d = current(guard);
158158
if (!d) return;
159-
const name = viewName(i18n.language, rule);
159+
const name = viewName(i18n.language, guard, rule);
160160
write(guard, withEnabled(d, rule, enabled), true).then(
161161
() =>
162162
toast.success(
@@ -199,7 +199,7 @@ export function GatewaySecurityPage() {
199199
if (!d) return;
200200
const before = d.rules.find((r) => r.custom === rule.custom && r.id === rule.id)?.action ?? 'record';
201201
if (before === action) return;
202-
const name = viewName(i18n.language, rule);
202+
const name = viewName(i18n.language, guard, rule);
203203
write(guard, withAction(d, rule, action), true).then(
204204
() =>
205205
toast.success(
@@ -230,7 +230,7 @@ export function GatewaySecurityPage() {
230230
if (!d) return;
231231
await write(guard, withAction(d, rule, action), false);
232232
setDialog(null);
233-
toast.success(t('contentSecurity.toast.ruleSaved', { name: viewName(i18n.language, rule) }));
233+
toast.success(t('contentSecurity.toast.ruleSaved', { name: viewName(i18n.language, guard, rule) }));
234234
}
235235

236236
async function removeCustom(guard: Guard, rule: SecurityRuleView) {
@@ -257,7 +257,7 @@ export function GatewaySecurityPage() {
257257
guard,
258258
editing: null,
259259
seed: {
260-
name: viewName(i18n.language, rule),
260+
name: viewName(i18n.language, guard, rule),
261261
pattern: written.pattern,
262262
match: written.match,
263263
action: rule.action ?? null,

‎web/src/routes/gateway/security/log-panel.tsx‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -167,7 +167,7 @@ function EventRow({ e, detail }: { e: GuardEvent; detail: SecurityDetail | undef
167167
const d = e.detail ?? {};
168168
if (!guard) return null;
169169
const outcome = outcomeOf(t, e.action, d);
170-
const rule = d.rule ? ruleName(i18n.language, detail?.[guard], d.rule, d.custom === true, d.rule_name) : '—';
170+
const rule = d.rule ? ruleName(i18n.language, guard, detail?.[guard], d.rule, d.custom === true, d.rule_name) : '—';
171171
const sources = new Intl.ListFormat(i18n.language, { type: 'conjunction' }).format(sourcesOf(t, d));
172172
const when = new Date(e.created_at);
173173
return (

‎web/src/routes/gateway/security/names.test.ts‎

Lines changed: 20 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -6,11 +6,9 @@ const rule = (over: Partial<SecurityRuleView>): SecurityRuleView => ({
66
id: 'groq-key',
77
custom: false,
88
name: 'Groq API key',
9-
name_zh: 'Groq API 密钥',
109
about: 'Starts with `gsk_`',
11-
about_zh: '`gsk_` 开头',
1210
kind: 'ai-services',
13-
matcher: { kind: 'builtin', check: 'groq-key' },
11+
matcher: { kind: 'prefix', prefix: 'gsk_', min_tail: 20 },
1412
enabled: true,
1513
on_by_default: true,
1614
...over,
@@ -19,24 +17,30 @@ const rule = (over: Partial<SecurityRuleView>): SecurityRuleView => ({
1917
const detail: GuardDetail = {
2018
mode: 'observe',
2119
rules: [rule({})],
22-
kinds: [{ slug: 'ai-services', name: 'AI services', name_zh: 'AI 服务' }],
20+
kinds: [{ slug: 'ai-services', name: 'AI services' }],
2321
}
2422

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

3634
it('names a custom rule by its own name, and a log row by id', () => {
37-
expect(viewName('zh', rule({ id: 'Codename', custom: true, name: 'Codename' }))).toBe('Codename')
38-
expect(ruleName('zh', detail, 'groq-key', false)).toBe('Groq API 密钥')
39-
expect(ruleName('zh', detail, 'gone-rule', false, 'Gone rule')).toBe('Gone rule')
40-
expect(ruleName('zh', undefined, 'gone-rule', false)).toBe('gone-rule')
35+
expect(viewName('zh', 'redact', rule({ id: 'Codename', custom: true, name: 'Codename' }))).toBe('Codename')
36+
expect(ruleName('zh', 'redact', detail, 'groq-key', false)).toBe('Groq API 密钥')
37+
expect(ruleName('zh', 'redact', detail, 'gone-rule', false, 'Gone rule')).toBe('Gone rule')
38+
expect(ruleName('zh', 'redact', undefined, 'gone-rule', false)).toBe('gone-rule')
39+
})
40+
41+
it('resolves a shared ID separately for each guard', () => {
42+
const entry = rule({ id: 'you-are-now' })
43+
expect(viewName('zh', 'inspect_tools', entry)).toBe('重新设定模型身份')
44+
expect(viewName('zh', 'content', entry)).toBe('重新设定身份')
4145
})
4246
})

‎web/src/routes/gateway/security/names.ts‎

Lines changed: 37 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -3,17 +3,34 @@ import type {
33
Guard,
44
GuardDetail,
55
GuardMode,
6+
Matcher,
67
RuleAction,
78
RuleScope,
89
SecurityKindView,
910
SecurityRuleView,
1011
} from '@/lib/security-types';
12+
import CATALOG from './guard.zh.json';
1113

12-
// Names on the security page. A built-in rule's name, reason and
13-
// description, and each group's name, come with the rule view in both
14-
// languages (thinkwatch-core writes them once for both products); the
15-
// console keeps no table of its own. A custom rule's id is the name its
16-
// author gave it.
14+
// Built-in display text is translated by guard and ID. The view supplies
15+
// English fallbacks and custom rules keep their original names.
16+
type RuleCopy = { name: string; why?: string; about?: string };
17+
const catalog: Record<Guard, { rules: Record<string, RuleCopy>; kinds: Record<string, string> }> = CATALOG;
18+
19+
function guardAboutZh(m: Matcher): string | undefined {
20+
if (m.kind !== "prefix" && m.kind !== "prefixes") return undefined;
21+
const prefixes = m.kind === "prefix" ? [{ ...m, tail: "any" }] : m.prefixes;
22+
const groups = new Map<string, { prefixes: string[]; length: number; unit: string }>();
23+
for (const p of prefixes) {
24+
const key = `${p.min_tail}:${p.tail}`;
25+
const unit = p.tail === "hex" ? "十六进制字符" : p.tail === "alnum" ? "字母或数字" : "字符";
26+
const group = groups.get(key) ?? { prefixes: [], length: p.min_tail, unit };
27+
group.prefixes.push(`\`${p.prefix}\``);
28+
groups.set(key, group);
29+
}
30+
return [...groups.values()].map(({ prefixes, length, unit }) =>
31+
`${prefixes.join("、")} 开头,其后至少 ${length} 个${unit}`,
32+
).join(";") || undefined;
33+
}
1734

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

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

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

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

4864
/**
@@ -52,32 +68,35 @@ export function viewName(lang: string, r: SecurityRuleView): string {
5268
*/
5369
export function ruleName(
5470
lang: string,
71+
guard: Guard,
5572
detail: GuardDetail | undefined,
5673
id: string,
5774
custom: boolean,
5875
fallback?: string,
5976
): string {
6077
if (custom) return id;
6178
const r = detail?.rules.find((r) => !r.custom && r.id === id);
62-
return r ? viewName(lang, r) : (fallback ?? id);
79+
return r ? viewName(lang, guard, r) : ((zh(lang) ? ruleCopy(guard, id)?.name : undefined) ?? fallback ?? id);
6380
}
6481

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

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

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

83102
export function actionName(t: TFunction, action: RuleAction): string {

‎web/src/routes/gateway/security/policy.ts‎

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -313,17 +313,16 @@ function literalsOf(m: Matcher): string[] {
313313
* rule's description, prefixes or field names — ignoring case. An empty
314314
* search matches every rule.
315315
*/
316-
export function matchesSearch(r: SecurityRuleView, shownName: string, query: string): boolean {
316+
export function matchesSearch(r: SecurityRuleView, shownName: string, query: string, translations: readonly string[] = []): boolean {
317317
const q = query.trim().toLowerCase();
318318
if (!q) return true;
319319
const pattern = patternOf(r)?.pattern ?? '';
320320
return [
321321
shownName,
322322
r.id,
323323
r.name,
324-
r.name_zh ?? '',
325324
r.about ?? '',
326-
r.about_zh ?? '',
325+
...translations,
327326
pattern,
328327
...literalsOf(r.matcher),
329328
].some((s) => s.toLowerCase().includes(q));

‎web/src/routes/gateway/security/rule-dialogs.tsx‎

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -688,8 +688,8 @@ export function BuiltinRuleDialog({
688688
const [saving, setSaving] = useState(false);
689689
const [error, setError] = useState<string | null>(null);
690690
const trial = useTrial(guard, { sample, rule: rule.id, action });
691-
const why = ruleWhy(lang, rule);
692-
const about = ruleAbout(lang, rule);
691+
const why = ruleWhy(lang, guard, rule);
692+
const about = ruleAbout(lang, guard, rule);
693693
const changed = action !== initial;
694694

695695
async function save() {
@@ -708,11 +708,11 @@ export function BuiltinRuleDialog({
708708
<DialogContent className="sm:max-w-xl">
709709
<DialogHeader>
710710
<DialogTitle className="flex items-center gap-2">
711-
{viewName(lang, rule)}
711+
{viewName(lang, guard, rule)}
712712
<Badge variant="secondary">{t('contentSecurity.builtinGroup')}</Badge>
713713
</DialogTitle>
714714
<DialogDescription>
715-
{why || t('contentSecurity.dialog.category', { kind: kindName(lang, kinds, rule.kind) })}
715+
{why || t('contentSecurity.dialog.category', { kind: kindName(lang, guard, kinds, rule.kind) })}
716716
</DialogDescription>
717717
</DialogHeader>
718718

@@ -873,10 +873,10 @@ export function TestDialog({
873873
{hits.map((h, i) => (
874874
<TableRow key={`${h.rule}:${h.start}:${i}`}>
875875
<TableCell className="truncate">
876-
{ruleName(lang, detail, h.rule, h.custom)}
876+
{ruleName(lang, guard, detail, h.rule, h.custom)}
877877
{h.custom && (
878878
<Badge variant="outline" className="ml-1.5">
879-
{kindName(lang, detail?.kinds, 'custom')}
879+
{kindName(lang, guard, detail?.kinds, 'custom')}
880880
</Badge>
881881
)}
882882
</TableCell>

0 commit comments

Comments
 (0)