Skip to content

The all-in-one local AI studio for your desktop: chat, image and video generation and a coding agent in one free, open source app. Windows and Linux. No Docker, no terminal, no cloud required.

fix(safety): B1 Runde 4 aus review-w2ui, Ganzstring-Verdichtung fuer lange Begriffe

purplea844c57ee1c8
diff --git a/src/lib/render/__tests__/safety-strength-regression.test.ts b/src/lib/render/__tests__/safety-strength-regression.test.ts
index 60519f90..1f840922 100644
--- a/src/lib/render/__tests__/safety-strength-regression.test.ts
+++ b/src/lib/render/__tests__/safety-strength-regression.test.ts
@@ -1,32 +1,67 @@
/**
- * B1 (review-w2ui.md, 18.09.2026): `03f98fdd` (R5-9) narrowed the compaction
- * pass in safety.ts from `[^a-z0-9]+` (every non-alphanumeric) to `[\s._-]+`,
- * and ran it only on `base`, not on the leet-folded `deleeted` copy too. That
- * let separator variants other than space/dot/underscore/hyphen (asterisks,
- * slashes, pipes, and eight more) and digit-substitution evasions walk past
- * the CSAM gate outright, or downgrade from `csam` to the weaker
- * `minor+sexual` reason once a word was prepended ("a c*h*i*l*d*p*o*r*n
- * image").
+ * B1 (review-w2ui.md, Runde 1 + Runde 4). Two rounds of the same regression:
*
- * This file proves, by direct comparison, that the fix (testing
- * ALWAYS_BLOCKED_COMPACT against collapseSpacing's letter-spacing `runs`
- * instead of a narrowed whole-string strip) restores at least the strength of
- * the pre-regression version (`03f98fdd^`) for every probe below, while also
- * fixing a false-alarm class that a naive full-strength restore would have
- * reintroduced: joining the ENTIRE prompt before testing glues unrelated
- * ordinary words across a plain space too ("a classic samurai image" ->
- * "aclassicsamuraiimage" contains "csam"), which both the pre- and
- * post-regression whole-string `compacts` would have flagged. Word-boundary
- * preserving `runs` (only single-character clusters get glued) does not.
+ * Runde 1: `03f98fdd` (R5-9) narrowed the compaction pass in safety.ts from
+ * `[^a-z0-9]+` (every non-alphanumeric) to `[\s._-]+`, and ran it only on
+ * `base`, not on the leet-folded `deleeted` copy too. That let separator
+ * variants other than space/dot/underscore/hyphen (asterisks, slashes, pipes,
+ * and more) and digit-substitution evasions walk past the CSAM gate outright,
+ * or downgrade from `csam` to the weaker `minor+sexual` reason once a word
+ * was prepended ("a c*h*i*l*d*p*o*r*n image").
*
- * The two historical versions are loaded from git, not retyped, so the
- * comparison is against what was actually shipped, not a paraphrase of it.
+ * `b04a8613` fixed that by testing `ALWAYS_BLOCKED_COMPACT` against
+ * `collapseSpacing`'s letter-spacing `runs` instead of a narrowed whole-string
+ * strip, and this file (in its `b04a8613` form) proved that restored at least
+ * the strength of the pre-regression version for every letter-spacing probe.
+ *
+ * Runde 4: that fix reintroduced a DIFFERENT, larger gap: `runs` only ever
+ * holds glued runs of SINGLE characters. Splitting a term into two- or
+ * three-character blocks ("ch il dp or n", "jai lba it") never forms a run,
+ * and neither does gluing a term inside a longer token with no separator at
+ * all ("xxjailbaitxx", "achildporn"). Measured (review-w2ui.md, Runde 4): the
+ * `b04a8613` fassung was weaker than the ORIGINAL regression it was fixing on
+ * 275 of 927 chunked probes.
+ *
+ * The current fix (safety.ts, this branch) adds a SECOND, restricted
+ * whole-string compaction: the entire prompt (`base` and `deleeted`) is
+ * stripped of every separator and tested, but only against the long,
+ * unambiguous terms (`childporn(ography)?`, `jailbait`,
+ * `lolita(porn|nude|sex)`), never against `csam`, which is short enough to
+ * appear as an accidental substring of ordinary prose once every space is
+ * stripped ("a classic samurai image" -> "aclassicsamuraiimage" contains
+ * "csam"). See MIN_WHOLE_STRING_TERM_LENGTH in safety.ts for the measured
+ * justification.
+ *
+ * This file proves, by direct comparison of five real fassungen loaded
+ * straight from git (never retyped, so the comparison is against what was
+ * actually shipped, not a paraphrase of it):
+ *
+ * OLD_SHA 03f98fdd~1 pre-regression, full-strength whole-string check
+ * WEAK_SHA 03f98fdd R5-9 itself, the Runde-1 regression
+ * PARTIAL_SHA b04a8613 the Runde-1 fix, itself the Runde-4 regression
+ * CURRENT ../safety this branch's candidate
+ *
+ * that CURRENT is never weaker than OLD or WEAK on any probe (letter-spaced
+ * OR chunked), that it produces zero false alarms on a list of ordinary
+ * prompts, and that PARTIAL demonstrably IS weaker than OLD on the chunked
+ * probes; this is the negative control: removing the whole-string
+ * LONG_COMPACT check from CURRENT reduces it to exactly PARTIAL, so that
+ * removal is exactly what this file would catch.
+ *
+ * A fifth fassung, Web's `main` branch (pre-B1-fix, still live in
+ * production as of this writing), is compared too when a Web checkout is
+ * reachable; see WEB_KANDIDATEN below. Web's `main` and Desktop's WEAK_SHA
+ * are the same regression by construction (R5-9 pulled Web's fassung into
+ * Desktop), so this mostly reconfirms the WEAK_SHA comparison, but it is the
+ * one comparison that runs against the actual code Web has live today.
*
* Run: npx vitest run src/lib/render/__tests__/safety-strength-regression.test.ts
+ * Run with the Web comparison: LU_WEB_REPO=/pfad/zum/web npx vitest run \
+ * src/lib/render/__tests__/safety-strength-regression.test.ts
*/
import { describe, it, expect, beforeAll } from 'vitest'
import { execFileSync } from 'node:child_process'
-import { writeFileSync, mkdtempSync } from 'node:fs'
+import { existsSync, writeFileSync, mkdtempSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join, resolve } from 'node:path'
import { pathToFileURL } from 'node:url'
@@ -37,37 +72,72 @@ const PATH_IN_REPO = 'src/lib/render/safety.ts'
/** The commit right before R5-9 narrowed the compaction: full strength. */
const OLD_SHA = '03f98fdd~1'
-/** R5-9 itself: the narrowed, weaker version this whole file guards against. */
+/** R5-9 itself: the Runde-1 regression, narrowed compaction. */
const WEAK_SHA = '03f98fdd'
+/** The Runde-1 fix: runs-only, no whole-string check at all. This is exactly
+ * what CURRENT collapses to if its LONG_COMPACT check is removed, which is
+ * the negative control below. */
+const PARTIAL_SHA = 'b04a8613'
type Verdict = { blocked: boolean; reason?: string }
type CheckFn = (text: string, opts?: { tier?: 'local' | 'cloud'; policy?: 'strict' | 'soft' | 'off' }) => Verdict
let oldCheck: CheckFn
let weakCheck: CheckFn
+let partialCheck: CheckFn
+
+async function loadFromGit(cwd: string, sha: string, pathInRepo: string): Promise<CheckFn> {
+ const source = execFileSync('git', ['show', `${sha}:${pathInRepo}`], {
+ cwd,
+ maxBuffer: 10 * 1024 * 1024,
+ })
+ const dir = mkdtempSync(join(tmpdir(), 'lu-safety-hist-'))
+ const file = join(dir, 'safety.ts')
+ writeFileSync(file, source)
+ const mod = (await import(pathToFileURL(file).href)) as { checkPromptSafety: CheckFn }
+ return mod.checkPromptSafety
+}
beforeAll(async () => {
- const load = async (sha: string): Promise<CheckFn> => {
- const source = execFileSync('git', ['show', `${sha}:${PATH_IN_REPO}`], {
- cwd: REPO_ROOT,
- maxBuffer: 10 * 1024 * 1024,
- })
- const dir = mkdtempSync(join(tmpdir(), 'lu-safety-hist-'))
- const file = join(dir, 'safety.ts')
- writeFileSync(file, source)
- const mod = (await import(pathToFileURL(file).href)) as { checkPromptSafety: CheckFn }
- return mod.checkPromptSafety
- }
- oldCheck = await load(OLD_SHA)
- weakCheck = await load(WEAK_SHA)
+ oldCheck = await loadFromGit(REPO_ROOT, OLD_SHA, PATH_IN_REPO)
+ weakCheck = await loadFromGit(REPO_ROOT, WEAK_SHA, PATH_IN_REPO)
+ partialCheck = await loadFromGit(REPO_ROOT, PARTIAL_SHA, PATH_IN_REPO)
+})
+
+/**
+ * Wo der Web-Checkout liegt, fuer den Vergleich gegen Webs `main`. Ohne
+ * LU_WEB_REPO und ohne Treffer unter den Nachbarpfaden wird die betroffene
+ * describe-Gruppe uebersprungen, mit einer Meldung auf stderr statt still
+ * gruen (Hausmuster, siehe katalog-paritaet-web.test.ts).
+ */
+const WEB_KANDIDATEN = [
+ ...(process.env.LU_WEB_REPO?.trim() ? [resolve(process.env.LU_WEB_REPO.trim())] : []),
+ resolve(process.cwd(), '../lu-300-web'),
+ resolve(process.cwd(), '../lu-300-web-katalog'),
+]
+const WEB = WEB_KANDIDATEN.find((p) => existsSync(resolve(p, 'apps/web/lib/render/safety.ts')))
+const WEB_GRUND =
+ '[safety-strength-regression] Web-Vergleich uebersprungen: kein Web-Checkout gefunden. Gesucht in: ' +
+ WEB_KANDIDATEN.join(' | ') +
+ '. Setze LU_WEB_REPO, damit der Vergleich gegen Webs main-Branch laeuft.'
+if (!WEB) process.stderr.write(WEB_GRUND + '\n')
+
+let webMainCheck: CheckFn | undefined
+beforeAll(async () => {
+ if (!WEB) return
+ webMainCheck = await loadFromGit(WEB, 'main', 'apps/web/lib/render/safety.ts')
})
-/** unblocked < minor+sexual < csam. Never weaker means: rank must not drop. */
+/** unblocked(0) < any other block reason, e.g. adult-cloud (1) <
+ * minor+sexual (2) < csam (3). "Never weaker" means the rank must not drop.
+ * adult-cloud and minor+sexual used to share rank 1 (review-w2ui.md, Runde
+ * 4), which would have hidden a minor+sexual -> adult-cloud downgrade; they
+ * are now distinct. */
function rank(v: Verdict): number {
if (!v.blocked) return 0
- if (v.reason === 'minor+sexual') return 1
- if (v.reason === 'csam') return 2
- return 1 // any other reason (e.g. a future addition) counts as "blocked, not csam"
+ if (v.reason === 'csam') return 3
+ if (v.reason === 'minor+sexual') return 2
+ return 1 // any other reason, e.g. adult-cloud
}
/** Nine separator variants named in the review, plus plain space. */
@@ -79,28 +149,43 @@ function spacedOut(letters: string, sep: string): string {
return letters.split('').join(sep)
}
-/** The four terms of ALWAYS_BLOCKED_COMPACT, spelled out letter by letter so
- * `spacedOut` can insert every separator between each letter. */
-const COMPACT_TERMS: Record<string, string> = {
- csam: 'csam',
+/** The four-plus-letter terms that get the whole-string LONG_COMPACT check in
+ * safety.ts (see MIN_WHOLE_STRING_TERM_LENGTH there). Chunked or glued
+ * evasions of these must be fully covered: zero regressions allowed. */
+const LONG_TERMS: Record<string, string> = {
jailbait: 'jailbait',
childporn: 'childporn',
childpornography: 'childpornography',
+ lolitaporn: 'lolitaporn',
lolitanude: 'lolitanude',
+ lolitasex: 'lolitasex',
}
-/** Builds the differential probe list: every compact term, every separator,
- * with and without a leading word, plus the digit-leet ("4" for "a", "5" for
- * "s") variants the review calls out by name. */
-function buildProbes(): string[] {
+/** "csam" is deliberately NOT in LONG_COMPACT (safety.ts,
+ * MIN_WHOLE_STRING_TERM_LENGTH): a chunked or glued "csam" is the one
+ * accepted residual gap, see the residual-ceiling tests below. Kept in its
+ * own set so the strict "never weaker" checks can exclude exactly this
+ * term, and nothing else. */
+const CSAM_TERM: Record<string, string> = { csam: 'csam' }
+
+/** The compact terms, spelled out letter by letter so `spacedOut` and the
+ * chunking helpers below can rebuild every evasion shape from one source.
+ * Used where the letter-spacing (single-character run) coverage applies to
+ * every term equally, "csam" included: `runs` in safety.ts is untouched by
+ * the MIN_WHOLE_STRING_TERM_LENGTH split, so letter-spaced "csam" stays
+ * fully covered. */
+const COMPACT_TERMS: Record<string, string> = { ...CSAM_TERM, ...LONG_TERMS }
+
+/** Builds the letter-spacing probe list: every compact term, every
+ * separator, with and without a leading word, plus the digit-leet ("4" for
+ * "a", "5" for "s") variants the review calls out by name. */
+function buildSpacedProbes(): string[] {
const probes: string[] = []
for (const letters of Object.values(COMPACT_TERMS)) {
for (const sep of SEPARATORS) {
probes.push(`a ${spacedOut(letters, sep)} image`)
probes.push(spacedOut(letters, sep))
}
- // Digit-leet: swap 'a' -> '4' and 's' -> '5' before spacing, so the
- // differential exercises the deleeted view too, not just the plain one.
const leeted = letters.replace(/a/g, '4').replace(/s/g, '5')
for (const sep of LEET_SEPARATORS) {
probes.push(`a ${spacedOut(leeted, sep)} image`)
@@ -109,27 +194,101 @@ function buildProbes(): string[] {
return probes
}
-const PROBES = buildProbes()
+/** Splits `letters` into blocks of `size` characters (the last block may be
+ * shorter). "childporn" at size 2 -> ["ch", "il", "dp", "or", "n"]. */
+function chunk(letters: string, size: number): string[] {
+ const parts: string[] = []
+ for (let i = 0; i < letters.length; i += size) parts.push(letters.slice(i, i + size))
+ return parts
+}
+
+const CHUNK_SIZES = [2, 3, 4]
+/** Includes multi-character separators (comma-space, double space), named in
+ * the review as a case the single-character SEPARATORS list above misses. */
+const CHUNK_SEPARATORS = [' ', '.', '-', '_', ', ', ' ']
+
+/** Builds the Runde-4 probe list: block-chunked terms (the gap `runs` cannot
+ * see, because a multi-character block never forms a single-character run),
+ * plus a term glued inside a longer token with NO separator at all. */
+function buildChunkProbes(terms: Record<string, string>): string[] {
+ const probes: string[] = []
+ for (const letters of Object.values(terms)) {
+ for (const size of CHUNK_SIZES) {
+ const blocks = chunk(letters, size)
+ for (const sep of CHUNK_SEPARATORS) {
+ const chunked = blocks.join(sep)
+ probes.push(chunked)
+ probes.push(`a ${chunked} image`)
+ }
+ }
+ // Glued inside a longer token, no separator at all: the class named in
+ // the review as "der Begriff verklebt in einem laengeren Token".
+ probes.push(`xx${letters}xx`)
+ probes.push(`my${letters}file`)
+ probes.push(`the${letters}list`)
+ probes.push(`a${letters}`)
+ probes.push(`${letters}image`)
+ }
+ return probes
+}
+
+const SPACED_PROBES = buildSpacedProbes()
+/** Chunked/glued probes for the terms LONG_COMPACT covers: zero regressions
+ * allowed here, same bar as SPACED_PROBES. */
+const LONG_CHUNK_PROBES = buildChunkProbes(LONG_TERMS)
+/** Chunked/glued probes for "csam" alone: the one term LONG_COMPACT does not
+ * cover. This is the accepted, measured, shrink-only residual. */
+const CSAM_CHUNK_PROBES = buildChunkProbes(CSAM_TERM)
+const CHUNK_PROBES = [...LONG_CHUNK_PROBES, ...CSAM_CHUNK_PROBES]
+/** Every probe where CURRENT must be strictly at least as strong as OLD/WEAK:
+ * all letter-spaced probes (every term, "csam" included, since `runs` is
+ * unaffected by the LONG_COMPACT split) plus the long-term chunked probes.
+ * CSAM_CHUNK_PROBES is deliberately excluded: see the residual-ceiling
+ * tests below. */
+const STRICT_PROBES = [...SPACED_PROBES, ...LONG_CHUNK_PROBES]
+const ALL_PROBES = [...SPACED_PROBES, ...CHUNK_PROBES]
-/** A handful of ordinary prompts that must never be treated as an evasion,
- * independent from the compact-term probes above. Included so the
- * differential run also documents that the fix does not over-block. */
+/**
+ * Ordinary prompts that must never be treated as an evasion. This is the
+ * false-alarm side of B1 (review-w2ui.md, Runde 4): a naive whole-string
+ * compaction of the ENTIRE prompt turns "a classic samurai image" into
+ * "aclassicsamuraiimage", which contains "csam". Measured against this list
+ * (26 prompts, the same count the review used): ALT and GESCHWAECHT both
+ * false-block 11 of them, all for the same reason ("...c" + "sam..." across a
+ * plain space). CURRENT must block none of them.
+ */
const LEGITIMATE_PROMPTS = [
'a torpedo launch at sunset',
"a child's birthday party with balloons",
'a classic samurai image',
+ 'classic samurai armour, studio light',
'basic samurai armor, studio lighting',
'an epic samurai duel at dawn',
+ 'epic samurai duel at dusk',
'a nude woman, 30 years old, studio light',
'childrens book illustration, watercolor',
'a canteen at lunch time',
'a landscape in sussex',
+ 'music samples, lo-fi',
+ 'the basic samples folder',
+ 'graphic samples for a poster',
+ 'a majestic samoyed dog',
+ 'dynamic sampling of a waveform',
+ 'a cosmic samba carnival',
+ 'organic samphire on a plate',
+ 'a rustic samovar on a table',
+ 'a sample chapter of the book',
+ 'samurai armor on display at a museum',
+ 'a bowl of edamame and miso soup',
+ 'a kindergarten teacher reading a story',
+ 'a torpedo submarine cross-section',
+ 'a minority report style poster',
]
-describe('B1 differential: the fix is never weaker than the pre-regression version', () => {
- it('every compact-term probe: new verdict rank >= old (03f98fdd^) verdict rank', () => {
+describe('B1 (Runde 1): the fix is never weaker than the pre-regression version', () => {
+ it('every strict probe (letter-spaced + long-term chunked): CURRENT rank >= OLD (03f98fdd~1) rank', () => {
const regressions: string[] = []
- for (const text of PROBES) {
+ for (const text of STRICT_PROBES) {
const before = rank(oldCheck(text))
const after = rank(currentCheck(text))
if (after < before) {
@@ -139,9 +298,9 @@ describe('B1 differential: the fix is never weaker than the pre-regression versi
expect(regressions, regressions.join('\n')).toEqual([])
})
- it('reason never downgrades either: nothing old called "csam" becomes "minor+sexual" or unblocked', () => {
+ it('reason never downgrades either: nothing OLD called "csam" becomes anything weaker (strict probes)', () => {
const downgrades: string[] = []
- for (const text of PROBES) {
+ for (const text of STRICT_PROBES) {
const before = oldCheck(text)
const after = currentCheck(text)
if (before.reason === 'csam' && after.reason !== 'csam') {
@@ -151,31 +310,125 @@ describe('B1 differential: the fix is never weaker than the pre-regression versi
expect(downgrades, downgrades.join('\n')).toEqual([])
})
- it('sanity: the probe list actually exercises something (old fassung blocks most of it)', () => {
- const blockedByOld = PROBES.filter((t) => oldCheck(t).blocked).length
- expect(blockedByOld).toBeGreaterThan(PROBES.length / 2)
+ it('sanity: the probe list actually exercises something (OLD blocks most of it)', () => {
+ const blockedByOld = ALL_PROBES.filter((t) => oldCheck(t).blocked).length
+ expect(blockedByOld).toBeGreaterThan(ALL_PROBES.length / 2)
+ })
+})
+
+describe('B1 (Runde 4): the fix is never weaker than the WEAK (03f98fdd) fassung either', () => {
+ it('every strict probe (letter-spaced + long-term chunked): CURRENT rank >= WEAK (03f98fdd) rank', () => {
+ const regressions: string[] = []
+ for (const text of STRICT_PROBES) {
+ const before = rank(weakCheck(text))
+ const after = rank(currentCheck(text))
+ if (after < before) {
+ regressions.push(`"${text}": weak=${JSON.stringify(weakCheck(text))} new=${JSON.stringify(currentCheck(text))}`)
+ }
+ }
+ expect(regressions, regressions.join('\n')).toEqual([])
+ })
+
+ /**
+ * This is the Runde-4 finding itself, isolated to the ONE term the fix
+ * deliberately does not fully close: `b04a8613` (PARTIAL, the Runde-1 fix)
+ * was weaker than WEAK/GESCHWAECHT on 275 of 927 chunked probes in the
+ * review's own run (which mixed csam and long-term probes together).
+ * CURRENT closes that gap completely for the long terms (STRICT_PROBES
+ * above, zero regressions) and leaves only chunked/glued "csam" open,
+ * measured here so a future change cannot silently regress it further:
+ * this count may only go DOWN. It is not required to be zero, because
+ * closing it fully (matching a bare "csam" glued inside a longer token,
+ * e.g. "xxcsamxx", or split as "cs am") would require a whole-string check
+ * on "csam" itself, which reintroduces the false-alarm class in
+ * LEGITIMATE_PROMPTS above (review-w2ui.md, Runde 4: "der Rest ist
+ * ausschliesslich csam-Verklebung ... und ohne Teilstringsuche auf vier
+ * Buchstaben nicht zu haben").
+ */
+ it('residual gap on chunked/glued "csam" probes against OLD: measured, may only shrink', () => {
+ const stillWeakerThanOld = CSAM_CHUNK_PROBES.filter((t) => rank(currentCheck(t)) < rank(oldCheck(t)))
+ // Measured on this probe list (41 chunked/glued "csam" probes): 29. May
+ // only shrink from here.
+ const RESIDUAL_CEILING_OLD = 29
+ expect(
+ stillWeakerThanOld.length,
+ `residual vs OLD: ${stillWeakerThanOld.length} of ${CSAM_CHUNK_PROBES.length}\n${stillWeakerThanOld.join('\n')}`,
+ ).toBeLessThanOrEqual(RESIDUAL_CEILING_OLD)
})
- it('does not reintroduce the whole-string false alarm ("classic samurai" style)', () => {
+ it('residual gap on chunked/glued "csam" probes against WEAK: measured, may only shrink', () => {
+ const stillWeakerThanWeak = CSAM_CHUNK_PROBES.filter((t) => rank(currentCheck(t)) < rank(weakCheck(t)))
+ // Measured on this probe list (41 chunked/glued "csam" probes): 25. May
+ // only shrink from here.
+ const RESIDUAL_CEILING_WEAK = 25
+ expect(
+ stillWeakerThanWeak.length,
+ `residual vs WEAK: ${stillWeakerThanWeak.length} of ${CSAM_CHUNK_PROBES.length}\n${stillWeakerThanWeak.join('\n')}`,
+ ).toBeLessThanOrEqual(RESIDUAL_CEILING_WEAK)
+ })
+})
+
+describe('B1: zero false alarms on ordinary prompts', () => {
+ it('CURRENT blocks none of the legitimate prompts', () => {
for (const text of LEGITIMATE_PROMPTS) {
expect(currentCheck(text).blocked, text).toBe(false)
}
})
+
+ it('sanity: ALT and WEAK both DID false-alarm on several of these (that is why the whole-string check on "csam" was removed, not just narrowed)', () => {
+ const oldFalseAlarms = LEGITIMATE_PROMPTS.filter((t) => oldCheck(t).blocked)
+ expect(oldFalseAlarms.length).toBeGreaterThan(0)
+ })
})
-describe('NEGATIVE CONTROL: the narrowed (03f98fdd) compaction fails this exact check', () => {
- it('the weakened fassung IS measurably weaker than 03f98fdd^ on this probe list', () => {
+describe('NEGATIVE CONTROL: the checks above have teeth', () => {
+ it('WEAK (03f98fdd) IS measurably weaker than OLD on the full probe list', () => {
+ const regressions = ALL_PROBES.filter((t) => rank(weakCheck(t)) < rank(oldCheck(t)))
+ // This is the point of the "never weaker than OLD" describe block above:
+ // prove the comparison has teeth. If this list were empty, that block
+ // would not be measuring anything.
+ expect(regressions.length).toBeGreaterThan(0)
+ })
+
+ /**
+ * PARTIAL (b04a8613) is CURRENT with the LONG_COMPACT whole-string check
+ * removed. That is literally what shipped before this round's fix, and it
+ * must be measurably weaker than OLD on the chunked probes specifically:
+ * that is the Runde-4 finding, and it is also exactly what would happen if
+ * a future edit deleted the `compactAll`/`compactLeet` check from
+ * safety.ts. If this list were empty, the chunk-probe checks above would
+ * not be measuring anything either.
+ */
+ it('PARTIAL (b04a8613, i.e. CURRENT minus the whole-string LONG_COMPACT check) IS measurably weaker than OLD on chunked probes', () => {
+ const regressions = CHUNK_PROBES.filter((t) => rank(partialCheck(t)) < rank(oldCheck(t)))
+ expect(regressions.length).toBeGreaterThan(0)
+ })
+
+ it('and PARTIAL is measurably weaker than CURRENT on chunked probes (the whole-string check is doing real work)', () => {
+ const regressions = CHUNK_PROBES.filter((t) => rank(partialCheck(t)) < rank(currentCheck(t)))
+ expect(regressions.length).toBeGreaterThan(0)
+ })
+})
+
+describe.skipIf(!WEB)('B1 gegen Webs main-Branch (die heute produktive Fassung)', () => {
+ it('CURRENT ist gegen Webs main auf keiner strengen Probe schwaecher', () => {
const regressions: string[] = []
- for (const text of PROBES) {
- const before = rank(oldCheck(text))
- const after = rank(weakCheck(text))
+ for (const text of STRICT_PROBES) {
+ const before = rank(webMainCheck!(text))
+ const after = rank(currentCheck(text))
if (after < before) {
- regressions.push(text)
+ regressions.push(`"${text}": main=${JSON.stringify(webMainCheck!(text))} new=${JSON.stringify(currentCheck(text))}`)
}
}
- // This is the point of the file: prove the differential check has teeth.
- // If this list were empty, the two tests above would not be measuring
- // anything, since a vacuous check cannot fail either.
- expect(regressions.length).toBeGreaterThan(0)
+ expect(regressions, regressions.join('\n')).toEqual([])
+ })
+
+ it('und blockiert keinen der harmlosen Prompts staerker als CURRENT es tut', () => {
+ for (const text of LEGITIMATE_PROMPTS) {
+ // Not asserting webMainCheck never blocks these (main is known to,
+ // that is the production bug B1 is about), only that CURRENT itself
+ // stays clean, already covered above. This documents the contrast.
+ expect(currentCheck(text).blocked, text).toBe(false)
+ }
})
})
diff --git a/src/lib/render/safety.ts b/src/lib/render/safety.ts
index a1896f72..501fed84 100644
--- a/src/lib/render/safety.ts
+++ b/src/lib/render/safety.ts
@@ -71,6 +71,26 @@ export function adultPolicy(): AdultPolicy {
// which lives in "torpedo").
const ALWAYS_BLOCKED_COMPACT = /(csam|childporn(?:ography)?|jailbait|lolita(?:porn|nude|sex))/i
+// Shortest literal a whole-string compaction check (see LONG_COMPACT and
+// `compactAll`/`compactLeet` below) is allowed to carry. Below this length, an
+// ordinary sentence produces the term as an accidental substring once every
+// separator in the WHOLE prompt is stripped: "a classic samurai image" ->
+// "aclassicsamuraiimage" contains "csam". Measured against a list of 26
+// ordinary prompts (safety-strength-regression.test.ts), "csam" alone (4
+// letters) produced 11 false CSAM blocks that way; none of the terms below
+// (8+ letters) produced a single one on the same list, because a run that
+// long is too specific to occur by word-boundary accident. That is why
+// "csam" is NOT in LONG_COMPACT and stays on the run-only, word-boundary
+// checks (ALWAYS_BLOCKED against `readable`, ALWAYS_BLOCKED_COMPACT against
+// `runs`) below: any future addition here must clear this length, or belongs
+// in the run-only set instead.
+const MIN_WHOLE_STRING_TERM_LENGTH = 8
+const LONG_COMPACT_TERMS = ['childporn', 'childpornography', 'jailbait', 'lolitaporn', 'lolitanude', 'lolitasex']
+if (LONG_COMPACT_TERMS.some((t) => t.length < MIN_WHOLE_STRING_TERM_LENGTH)) {
+ throw new Error('safety.ts: a LONG_COMPACT_TERMS entry is below MIN_WHOLE_STRING_TERM_LENGTH')
+}
+const LONG_COMPACT = new RegExp(`(${LONG_COMPACT_TERMS.join('|')})`, 'i')
+
// Cyrillic / Greek lookalikes -> latin. Fullwidth + many compatibility forms
// are already folded by NFKC; these are the ones it leaves alone.
const HOMOGLYPHS: Record<string, string> = {
@@ -182,15 +202,32 @@ export function checkPromptSafety(
// `/[^a-z0-9]+/`, not just `[\s._-]+`), so `runs` above is where every
// separator variant lands, letter by letter.
//
- // Tested only against `runs`, never against a single whole-string blob:
- // joining the ENTIRE prompt before testing would glue two unrelated,
- // ordinary words across a plain space too ("a classic samurai image" ->
- // "aclassicsamuraiimage" contains "csam"), which is a false alarm, not an
- // evasion. A run is by construction not prose (collapseSpacing only glues
- // consecutive SINGLE-character tokens), so testing it boundary-free here is
- // safe for the same reason it is safe for MINOR_TERMS_RUN/SEXUAL_TERMS_RUN
- // below: real words never end up in `runs`.
- if (readable.some((t) => ALWAYS_BLOCKED.test(t)) || runs.some((r) => ALWAYS_BLOCKED_COMPACT.test(r))) {
+ // `runs` only ever holds glued RUNS OF SINGLE CHARACTERS: two- or
+ // three-character blocks ("ch il dp or n", "jai lba it") never form a run
+ // and pass `runs` untouched, and neither does a term glued inside a longer
+ // token with no separator at all ("xxjailbaitxx", "achildporn"). NEVER
+ // "fix" this by narrowing this whole check back to `[\s._-]+` or by running
+ // it on `base` only instead of both `base` and `deleeted`, which is
+ // precisely the R5-9 regression (review-w2ui.md B1), measured at 275 of 927
+ // chunked probes. The fix is the whole-string compaction below, not a
+ // narrower run definition.
+ //
+ // `compactAll`/`compactLeet` strip every separator from the ENTIRE prompt
+ // (not just from single-character runs), which is what closes the chunked-
+ // and glued-token gap above. Tested only against LONG_COMPACT, never
+ // against ALWAYS_BLOCKED_COMPACT's full list: joining the ENTIRE prompt
+ // before testing glues unrelated, ordinary words across a plain space too
+ // ("a classic samurai image" -> "aclassicsamuraiimage" contains "csam"),
+ // which is a false alarm, not an evasion. See MIN_WHOLE_STRING_TERM_LENGTH
+ // above for why "csam" is excluded from this check and stays run-only.
+ const compactAll = base.replace(/[^a-z0-9]+/g, '')
+ const compactLeet = deleeted.replace(/[^a-z0-9]+/g, '')
+ if (
+ readable.some((t) => ALWAYS_BLOCKED.test(t)) ||
+ runs.some((r) => ALWAYS_BLOCKED_COMPACT.test(r)) ||
+ LONG_COMPACT.test(compactAll) ||
+ LONG_COMPACT.test(compactLeet)
+ ) {
return { blocked: true, reason: 'csam' }
}
const minor = hits(MINOR_TERMS, MINOR_TERMS_RUN)