d3ro-voice/apps/desktop/src/main/services/voice-command-policy.ts
Yun Chan ba9ef9741e fix: red-team round 3 hardening across desktop, mobile, core and server
Batch of red-team r3 fixes that were in the working tree before the
2026-09-28 design overhaul, committed as one unit with their tests.

- desktop main: STT timeouts and sidecar, voice recording store, sync
  (credentials, audio, knowledge reindex, push gates), runtime
  provisioner, update policy, AltGr keybindings, voice-command policy,
  dictionary file codec/limits, meeting transcript condensing and a
  local recording ledger so interrupted-session recovery only closes
  meetings this device recorded (a phone's live meeting is left alone).
- mobile: login CSRF via implicit token callbacks rejected, account
  deletion/retention, durable queue retention, knowledge realtime
  without unfiltered DELETE, meeting re-record failure paths, cloud STT
  client, preferences store/resync.
- core: text chunking splits long unbroken transcripts to fit, template
  field policy, dictionary limits, meeting markdown inline handling.
- server: payple webhook policy and cancellation order scope, meeting
  document generation quota, team RPC null-role guard, unified LLM
  quota in-flight accounting, knowledge chunk vector index, meeting
  re-record failure paths (migrations 20260929*).
- ci: portable/runtime feed gates, update-policy schema, Forgejo file
  delete and alias planning.

Four older tests are updated to the new contracts rather than the old
behavior: token-pair auth callbacks are rejected, knowledge realtime no
longer subscribes to DELETE, long transcript lines are split, and
meeting recovery requires the local recording ledger for empty rows.
2026-09-28 20:45:52 +09:00

245 lines
8.4 KiB
TypeScript

// src/main/services/voice-command-policy.ts
// 음성 단축키의 순수 정책: 기본 키워드 테이블, 키워드 매칭, 저장된 레거시 기본값 이관.
// IO(electron-store, logger)에 의존하지 않으므로 표 형태로 단위 테스트한다.
import type {
VoiceCommandRule,
VoiceCommandKeyword,
KeywordMatchMode
} from '@d3ro/core/types'
// ============================================================
// 기본 키워드 (프리셋 명령어용)
// ============================================================
export interface DefaultKeywordEntry {
instructionId: string
keywords: ReadonlyArray<VoiceCommandKeyword>
priority: number
}
function prefixKeywords(words: ReadonlyArray<string>): VoiceCommandKeyword[] {
return words.map((keyword) => ({ keyword, matchMode: 'prefix' as const }))
}
/**
* 기본 키워드는 명령형(동사형)만 쓴다. '요약', '번역', '설명', 'explain' 같은
* 맨 명사는 "요약 보고서 첨부해서 보내드립니다." 같은 일반 받아쓰기 문장의 첫 단어로
* 흔히 나오므로, prefix로 매칭하면 받아쓴 문장이 LLM 변환 결과로 바뀌고 첫 단어가 사라진다.
* 긴 키워드를 먼저 둔다 (같은 규칙 안에서 앞의 키워드부터 검사한다).
*/
export const DEFAULT_VOICE_COMMAND_KEYWORDS: ReadonlyArray<DefaultKeywordEntry> = [
{
instructionId: 'builtin-translate',
keywords: prefixKeywords([
'영어로 번역해 주세요',
'영어로 번역해주세요',
'영어로 번역해 줘',
'영어로 번역해줘',
'번역해 주세요',
'번역해주세요',
'번역해 줘',
'번역해줘',
'translate this'
]),
priority: 0
},
{
instructionId: 'builtin-summarize',
keywords: prefixKeywords([
'요약해 주세요',
'요약해주세요',
'요약해 줘',
'요약해줘',
'summarize this'
]),
priority: 1
},
{
instructionId: 'builtin-formal',
keywords: prefixKeywords([
'다듬어 주세요',
'다듬어주세요',
'다듬어 줘',
'다듬어줘',
'polish this'
]),
priority: 2
},
{
instructionId: 'builtin-explain-code',
keywords: prefixKeywords([
'설명해 주세요',
'설명해주세요',
'설명해 줘',
'설명해줘',
'explain this'
]),
priority: 3
}
]
/**
* 이전 버전이 첫 실행 때 저장한 기본 키워드. 저장소에 이 목록이 그대로 남아 있으면
* (사용자가 손대지 않은 기본값) 새 기본값으로 교체한다.
*/
const LEGACY_DEFAULT_KEYWORDS: Readonly<Record<string, ReadonlyArray<string>>> = {
'builtin-translate': ['번역해줘', '번역', '영어로', 'translate'],
'builtin-summarize': ['요약해줘', '요약', 'summarize'],
'builtin-formal': ['다듬어줘', '다듬기', 'polish'],
'builtin-explain-code': ['설명해줘', '설명', 'explain']
}
// ============================================================
// 키워드 매칭
// ============================================================
export interface KeywordMatchResult {
matched: boolean
cleanedText: string
}
// 공백·구두점 (따옴표/괄호 포함). 키워드 경계 판정에 쓴다.
const WORD_BOUNDARY = /[\s,.!?;:'"()[\]{}\-/…~]/
// 키워드를 잘라낸 자리에 남는 구분 기호. 여는/닫는 따옴표·괄호는 내용의 일부이므로 남긴다.
const LEADING_SEPARATORS = /^[\s,.!?;:\-/…~–—]+/
const TRAILING_SEPARATORS = /[\s,;:\-/…~–—]+$/
// 변환할 내용이 실제로 있는지: 글자나 숫자가 하나라도 있어야 한다.
const HAS_CONTENT = /[\p{L}\p{N}]/u
export function isWordBoundary(char: string): boolean {
return WORD_BOUNDARY.test(char)
}
function noMatch(trimmed: string): KeywordMatchResult {
return { matched: false, cleanedText: trimmed }
}
function withContent(cleaned: string, trimmed: string): KeywordMatchResult {
// 명령어만 말하고 대상 내용이 없으면 명령으로 보지 않는다 ('요약해줘.' → 원문 그대로 받아쓰기).
if (!HAS_CONTENT.test(cleaned)) return noMatch(trimmed)
return { matched: true, cleanedText: cleaned }
}
/**
* 텍스트에서 키워드를 매칭하고, 매칭된 키워드를 제거한 정리된 텍스트를 반환한다.
* 키워드 앞뒤의 공백/구두점 경계를 존중하고, 키워드를 뺀 뒤 변환할 내용이 남아야 매칭으로 본다.
*/
export function matchKeyword(
text: string,
keyword: string,
mode: KeywordMatchMode
): KeywordMatchResult {
const trimmed = text.trim()
const lowerText = trimmed.toLowerCase()
const lowerKeyword = keyword.toLowerCase()
if (lowerKeyword.length === 0 || lowerKeyword.length !== keyword.length) {
// 빈 키워드, 또는 소문자 변환으로 길이가 바뀌는 키워드는 오프셋을 신뢰할 수 없다
return noMatch(trimmed)
}
const keywordLength = lowerKeyword.length
switch (mode) {
case 'prefix': {
if (!lowerText.startsWith(lowerKeyword)) return noMatch(trimmed)
const afterKeyword = trimmed.charAt(keywordLength)
if (afterKeyword !== '' && !isWordBoundary(afterKeyword)) return noMatch(trimmed)
const cleaned = trimmed.slice(keywordLength).replace(LEADING_SEPARATORS, '')
return withContent(cleaned, trimmed)
}
case 'suffix': {
if (!lowerText.endsWith(lowerKeyword)) return noMatch(trimmed)
const beforeKeyword = trimmed.charAt(trimmed.length - keywordLength - 1)
if (beforeKeyword !== '' && !isWordBoundary(beforeKeyword)) return noMatch(trimmed)
const cleaned = trimmed
.slice(0, trimmed.length - keywordLength)
.replace(TRAILING_SEPARATORS, '')
return withContent(cleaned, trimmed)
}
case 'contains': {
const index = lowerText.indexOf(lowerKeyword)
if (index === -1) return noMatch(trimmed)
// contains 모드에서는 경계 검사 없이 첫 번째 매칭만 제거
const before = trimmed.slice(0, index)
const after = trimmed.slice(index + keywordLength)
const cleaned = (before + after).replace(/\s{2,}/g, ' ').trim()
return withContent(cleaned, trimmed)
}
}
}
export interface RuleMatch {
rule: VoiceCommandRule
keyword: string
cleanedText: string
}
/**
* 활성 규칙을 priority 오름차순(0이 가장 높음)으로 검사해 첫 매칭을 돌려준다.
*/
export function findRuleMatch(
text: string,
rules: ReadonlyArray<VoiceCommandRule>
): RuleMatch | null {
const trimmed = text.trim()
if (trimmed.length === 0) return null
const sortedRules = rules
.filter((r) => r.enabled && r.keywords.length > 0)
.sort((a, b) => a.priority - b.priority)
for (const rule of sortedRules) {
for (const kw of rule.keywords) {
const result = matchKeyword(trimmed, kw.keyword, kw.matchMode)
if (result.matched) {
return { rule, keyword: kw.keyword, cleanedText: result.cleanedText }
}
}
}
return null
}
// ============================================================
// 기본값 생성 / 레거시 이관
// ============================================================
export function buildDefaultRules(createId: () => string): VoiceCommandRule[] {
return DEFAULT_VOICE_COMMAND_KEYWORDS.map((entry) => ({
id: createId(),
instructionId: entry.instructionId,
keywords: entry.keywords.map((kw) => ({ ...kw })),
enabled: true,
priority: entry.priority
}))
}
function isUntouchedLegacyDefault(rule: VoiceCommandRule): boolean {
const legacy = LEGACY_DEFAULT_KEYWORDS[rule.instructionId]
if (!legacy || rule.keywords.length !== legacy.length) return false
return rule.keywords.every(
(kw, i) => kw.matchMode === 'prefix' && kw.keyword === legacy[i]
)
}
/**
* 이전 버전이 저장한, 사용자가 손대지 않은 맨 명사 기본 키워드를 새 명령형 기본값으로 바꾼다.
* 사용자가 IPC로 바꾼 키워드는 그대로 둔다. migrated는 교체한 규칙 수다.
*/
export function migrateLegacyDefaultRules(
rules: ReadonlyArray<VoiceCommandRule>
): { rules: VoiceCommandRule[]; migrated: number } {
let migrated = 0
const next = rules.map((rule) => {
if (!isUntouchedLegacyDefault(rule)) return rule
const entry = DEFAULT_VOICE_COMMAND_KEYWORDS.find(
(e) => e.instructionId === rule.instructionId
)
if (!entry) return rule
migrated++
return { ...rule, keywords: entry.keywords.map((kw) => ({ ...kw })) }
})
return { rules: next, migrated }
}