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.
207 lines
8.2 KiB
TypeScript
207 lines
8.2 KiB
TypeScript
// packages/core/src/dictionary-policy.ts
|
|
// 사용자 사전 편집 정책 — 순수 함수만 둔다 (DB/IPC/UI 의존 없음).
|
|
// 데스크톱 DictionaryService(쓰기 규칙)와 DictionaryPage(폼 → 요청 변환)가 같은 규칙을 공유한다.
|
|
|
|
import { D3ROError, ErrorCode } from './errors'
|
|
import { charLength } from './instruction-policy'
|
|
import type { DictionaryAddParams, DictionaryEntry, DictionaryUpdateParams } from './types'
|
|
|
|
export type DictionaryCategory = DictionaryEntry['category']
|
|
|
|
/**
|
|
* 서버 쓰기 제약 — 마이그레이션 20260821000005 의 normalize_dictionary_word 트리거와 같다:
|
|
* char_length(btrim(word)) ≤ 120, char_length(btrim(pronunciation)) ≤ 200 (코드 포인트 기준).
|
|
* 로컬이 이보다 긴 값을 받아들이면 서버가 22023 으로 거부하고, 아웃박스가 재시도 끝에 항목을 영구 보류해
|
|
* 다른 기기로 동기화되지 않는다. 모바일 사전 서비스·서버 포터빌리티 가져오기도 같은 값을 쓴다.
|
|
*/
|
|
export const DICTIONARY_LIMITS = { word: 120, pronunciation: 200 } as const
|
|
|
|
export type DictionaryLimitField = keyof typeof DICTIONARY_LIMITS
|
|
|
|
/** 사전 항목을 저장할 수 없는 이유 */
|
|
export type DictionaryWriteProblem =
|
|
| { reason: 'empty-word' }
|
|
| { reason: 'too-long'; field: DictionaryLimitField; max: number }
|
|
|
|
/** 정규화한 값이 서버 길이 제한을 넘으면 그 문제, 아니면 null. */
|
|
export function dictionaryLengthProblem(
|
|
field: DictionaryLimitField,
|
|
normalized: string | null | undefined
|
|
): DictionaryWriteProblem | null {
|
|
if (normalized === null || normalized === undefined) return null
|
|
const max = DICTIONARY_LIMITS[field]
|
|
return charLength(normalized) > max ? { reason: 'too-long', field, max } : null
|
|
}
|
|
|
|
/** 단어를 정규화한다. 공백뿐이면 null (= 유효하지 않음). 길이 제한은 validateDictionaryDraft 가 본다. */
|
|
export function normalizeDictionaryWord(raw: string): string | null {
|
|
const word = raw.trim()
|
|
return word.length > 0 ? word : null
|
|
}
|
|
|
|
/**
|
|
* 단어의 식별 키 — 같은 카테고리에서 이 키가 같으면 같은 단어다.
|
|
* 서버 유일 인덱스 `(user_id, lower(btrim(word)), category)` 와 같은 규칙(대소문자 무시).
|
|
* 로컬이 'API' 와 'api' 를 따로 받아들이면, 동기화 때 서버 충돌(23505)로 로컬 행이 서버 행으로
|
|
* 대체되며 사용자가 넣은 표기와 발음이 조용히 사라진다.
|
|
*/
|
|
export function dictionaryIdentityKey(word: string): string {
|
|
return word.trim().toLowerCase()
|
|
}
|
|
|
|
/** 같은 카테고리의 기존 단어 중 식별 키가 같은 첫 항목 (excludeId 는 자기 자신 제외용) */
|
|
export function findDictionaryIdentityConflict<T extends { id: string; word: string }>(
|
|
word: string,
|
|
candidates: readonly T[],
|
|
excludeId?: string
|
|
): T | null {
|
|
const key = dictionaryIdentityKey(word)
|
|
return candidates.find((c) => c.id !== excludeId && dictionaryIdentityKey(c.word) === key) ?? null
|
|
}
|
|
|
|
/**
|
|
* 발음 입력을 정규화한다.
|
|
* - undefined → undefined: "변경 없음"
|
|
* - null 또는 공백뿐인 문자열 → null: "발음 지우기"
|
|
* - 그 외 → 앞뒤 공백을 제거한 값
|
|
*/
|
|
export function normalizeDictionaryPronunciation(
|
|
raw: string | null | undefined
|
|
): string | null | undefined {
|
|
if (raw === undefined) return undefined
|
|
if (raw === null) return null
|
|
const pronunciation = raw.trim()
|
|
return pronunciation.length > 0 ? pronunciation : null
|
|
}
|
|
|
|
/** DB에 그대로 쓸 수 있는 부분 갱신 값. 키가 없으면 해당 필드는 바꾸지 않는다. */
|
|
export interface DictionaryUpdatePatch {
|
|
word?: string
|
|
pronunciation?: string | null
|
|
category?: DictionaryCategory
|
|
}
|
|
|
|
export type DictionaryUpdatePatchResult =
|
|
| { ok: true; patch: DictionaryUpdatePatch }
|
|
| ({ ok: false } & DictionaryWriteProblem)
|
|
|
|
/** 갱신 요청을 검증·정규화해 쓰기 패치로 바꾼다. 준 필드만 검사한다(빈 단어·서버 길이 초과 거부). */
|
|
export function buildDictionaryUpdatePatch(
|
|
params: DictionaryUpdateParams
|
|
): DictionaryUpdatePatchResult {
|
|
const patch: DictionaryUpdatePatch = {}
|
|
if (params.word !== undefined) {
|
|
const word = normalizeDictionaryWord(params.word)
|
|
if (word === null) return { ok: false, reason: 'empty-word' }
|
|
const tooLong = dictionaryLengthProblem('word', word)
|
|
if (tooLong) return { ok: false, ...tooLong }
|
|
patch.word = word
|
|
}
|
|
const pronunciation = normalizeDictionaryPronunciation(params.pronunciation)
|
|
if (pronunciation !== undefined) {
|
|
const tooLong = dictionaryLengthProblem('pronunciation', pronunciation)
|
|
if (tooLong) return { ok: false, ...tooLong }
|
|
patch.pronunciation = pronunciation
|
|
}
|
|
if (params.category !== undefined) patch.category = params.category
|
|
return { ok: true, patch }
|
|
}
|
|
|
|
/** 새 항목의 정규화된 쓰기 값 */
|
|
export interface DictionaryDraft {
|
|
word: string
|
|
pronunciation: string | null
|
|
}
|
|
|
|
export type DictionaryDraftResult =
|
|
| { ok: true; draft: DictionaryDraft }
|
|
| ({ ok: false } & DictionaryWriteProblem)
|
|
|
|
/**
|
|
* 새 항목(추가·가져오기)을 검증·정규화한다 (순수 함수).
|
|
* 빈 단어와 서버 길이 제한을 넘는 단어·발음을 거부한다 — 서버 트리거와 같은 기준.
|
|
*/
|
|
export function validateDictionaryDraft(input: {
|
|
word: string
|
|
pronunciation?: string | null
|
|
}): DictionaryDraftResult {
|
|
const word = normalizeDictionaryWord(input.word)
|
|
if (word === null) return { ok: false, reason: 'empty-word' }
|
|
const wordProblem = dictionaryLengthProblem('word', word)
|
|
if (wordProblem) return { ok: false, ...wordProblem }
|
|
const pronunciation = normalizeDictionaryPronunciation(input.pronunciation) ?? null
|
|
const pronunciationProblem = dictionaryLengthProblem('pronunciation', pronunciation)
|
|
if (pronunciationProblem) return { ok: false, ...pronunciationProblem }
|
|
return { ok: true, draft: { word, pronunciation } }
|
|
}
|
|
|
|
/**
|
|
* 쓰기 문제를 IPC 로 넘길 D3ROError 로 바꾼다.
|
|
* details 의 field·max 로 UI 가 어떤 필드가 몇 자를 넘었는지 보여줄 수 있다.
|
|
*/
|
|
export function dictionaryWriteProblemError(problem: DictionaryWriteProblem): D3ROError {
|
|
if (problem.reason === 'empty-word') {
|
|
return new D3ROError(ErrorCode.DictionaryImportInvalidFormat, 'Dictionary word is empty', {
|
|
reason: problem.reason,
|
|
field: 'word'
|
|
})
|
|
}
|
|
return new D3ROError(
|
|
ErrorCode.DictionaryImportInvalidFormat,
|
|
`Dictionary ${problem.field} exceeds ${problem.max} characters`,
|
|
{ reason: problem.reason, field: problem.field, max: problem.max }
|
|
)
|
|
}
|
|
|
|
/** SQLite UNIQUE 제약 위반 여부 (better-sqlite3 오류 메시지 기준). */
|
|
export function isUniqueConstraintViolation(err: unknown): boolean {
|
|
const message = err instanceof Error ? err.message : String(err)
|
|
return /unique/i.test(message)
|
|
}
|
|
|
|
/** 추가/편집 다이얼로그의 입력값. */
|
|
export interface DictionaryFormValues {
|
|
word: string
|
|
pronunciation: string
|
|
}
|
|
|
|
/** 새 단어 추가 요청: 빈 발음은 보내지 않는다. */
|
|
export function toDictionaryAddParams(form: DictionaryFormValues): DictionaryAddParams {
|
|
const pronunciation = normalizeDictionaryPronunciation(form.pronunciation)
|
|
return {
|
|
word: form.word.trim(),
|
|
...(pronunciation ? { pronunciation } : {})
|
|
}
|
|
}
|
|
|
|
/** 편집 요청: 비운 발음은 null로 보내 "지우기"를 명시한다. */
|
|
export function toDictionaryUpdateParams(
|
|
id: string,
|
|
form: DictionaryFormValues
|
|
): DictionaryUpdateParams {
|
|
return {
|
|
id,
|
|
word: form.word.trim(),
|
|
pronunciation: normalizeDictionaryPronunciation(form.pronunciation) ?? null
|
|
}
|
|
}
|
|
|
|
/** 사전 저장 실패를 사용자 메시지 i18n 키로 바꾼다. */
|
|
export type DictionarySaveErrorKey =
|
|
| 'mobile.dictionary.error.duplicate'
|
|
| 'mobile.dictionary.error.notFound'
|
|
| 'mobile.dictionary.error.validation'
|
|
| 'mobile.dictionary.error.server'
|
|
|
|
export function dictionarySaveErrorKey(code: ErrorCode): DictionarySaveErrorKey {
|
|
switch (code) {
|
|
case ErrorCode.DictionaryDuplicate:
|
|
return 'mobile.dictionary.error.duplicate'
|
|
case ErrorCode.DictionaryNotFound:
|
|
return 'mobile.dictionary.error.notFound'
|
|
case ErrorCode.DictionaryImportInvalidFormat:
|
|
return 'mobile.dictionary.error.validation'
|
|
default:
|
|
return 'mobile.dictionary.error.server'
|
|
}
|
|
}
|