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.
This commit is contained in:
parent
2428ede03d
commit
ba9ef9741e
161 changed files with 17056 additions and 2379 deletions
|
|
@ -16,11 +16,16 @@ import { containsPattern } from '../db/like-pattern'
|
|||
import {
|
||||
buildDictionaryUpdatePatch,
|
||||
dictionaryIdentityKey,
|
||||
dictionaryWriteProblemError,
|
||||
findDictionaryIdentityConflict,
|
||||
isUniqueConstraintViolation,
|
||||
normalizeDictionaryPronunciation,
|
||||
normalizeDictionaryWord
|
||||
validateDictionaryDraft
|
||||
} from '@d3ro/core/dictionary-policy'
|
||||
import {
|
||||
parseDictionaryFile,
|
||||
serializeDictionary,
|
||||
toDictionaryImportRow
|
||||
} from './dictionary/dictionary-file-codec'
|
||||
import type {
|
||||
DictionaryEntry,
|
||||
DictionaryQueryParams,
|
||||
|
|
@ -37,90 +42,6 @@ const logger = getLogger('DictionaryService')
|
|||
|
||||
let isShowingDictionarySaveDialog = false
|
||||
|
||||
const DICTIONARY_CSV_HEADER = [
|
||||
'word',
|
||||
'pronunciation',
|
||||
'category',
|
||||
'usageCount',
|
||||
'createdAt',
|
||||
'updatedAt'
|
||||
] as const
|
||||
|
||||
function csvCell(value: unknown): string {
|
||||
const text = value === null || value === undefined ? '' : String(value)
|
||||
const escaped = text.replace(/"/g, '""')
|
||||
const needsQuotes = /[",\r\n]/.test(escaped) || /^[=+\-@]/.test(escaped)
|
||||
return needsQuotes ? `"${escaped}"` : escaped
|
||||
}
|
||||
|
||||
function parseCsvRows(input: string): string[][] {
|
||||
const rows: string[][] = []
|
||||
let row: string[] = []
|
||||
let field = ''
|
||||
let inQuotes = false
|
||||
for (let i = 0; i < input.length; i += 1) {
|
||||
const char = input[i]
|
||||
if (inQuotes) {
|
||||
if (char === '"') {
|
||||
if (input[i + 1] === '"') {
|
||||
field += '"'
|
||||
i += 1
|
||||
} else {
|
||||
inQuotes = false
|
||||
}
|
||||
} else {
|
||||
field += char
|
||||
}
|
||||
continue
|
||||
}
|
||||
if (char === '"') {
|
||||
inQuotes = true
|
||||
} else if (char === ',') {
|
||||
row.push(field)
|
||||
field = ''
|
||||
} else if (char === '\n') {
|
||||
row.push(field)
|
||||
rows.push(row)
|
||||
row = []
|
||||
field = ''
|
||||
} else if (char === '\r') {
|
||||
// skip CR; LF terminates the row
|
||||
} else {
|
||||
field += char
|
||||
}
|
||||
}
|
||||
if (field.length > 0 || row.length > 0) {
|
||||
row.push(field)
|
||||
rows.push(row)
|
||||
}
|
||||
return rows.filter((candidate) => candidate.some((cell) => cell.trim().length > 0))
|
||||
}
|
||||
|
||||
function pickString(source: Record<string, unknown>, keys: string[]): string | null {
|
||||
for (const key of keys) {
|
||||
const value = source[key]
|
||||
if (typeof value === 'string' && value.trim().length > 0) return value.trim()
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
function pickNumber(source: Record<string, unknown>, keys: string[]): number | null {
|
||||
for (const key of keys) {
|
||||
const value = source[key]
|
||||
if (typeof value === 'number' && Number.isFinite(value)) return value
|
||||
if (typeof value === 'string' && value.trim() !== '') {
|
||||
const parsed = Number(value)
|
||||
if (Number.isFinite(parsed)) return parsed
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
function normalizeCategory(value: string | null): DictionaryEntry['category'] {
|
||||
if (value === 'auto' || value === 'technical' || value === 'user') return value
|
||||
return 'user'
|
||||
}
|
||||
|
||||
type DictionaryDb = Pick<ReturnType<typeof getDatabase>, 'select'>
|
||||
|
||||
/**
|
||||
|
|
@ -160,10 +81,11 @@ function findImportDuplicate(
|
|||
|
||||
class DictionaryService {
|
||||
add(params: DictionaryAddParams): DictionaryEntry {
|
||||
const word = normalizeDictionaryWord(params.word)
|
||||
if (!word) {
|
||||
throw new D3ROError(ErrorCode.DictionaryImportInvalidFormat, 'Dictionary word is empty')
|
||||
}
|
||||
// 빈 단어·서버 길이 제한(단어 120·발음 200자) 초과는 저장 전에 거부한다 — 받아들이면 로컬에만 남고
|
||||
// 서버가 22023 으로 거부해 아웃박스에 영구 보류된다(다른 기기로 동기화되지 않음).
|
||||
const validated = validateDictionaryDraft(params)
|
||||
if (!validated.ok) throw dictionaryWriteProblemError(validated)
|
||||
const { word, pronunciation } = validated.draft
|
||||
|
||||
const db = getDatabase()
|
||||
const now = Date.now()
|
||||
|
|
@ -177,7 +99,7 @@ class DictionaryService {
|
|||
const entry: NewDictionary = {
|
||||
id,
|
||||
word,
|
||||
pronunciation: normalizeDictionaryPronunciation(params.pronunciation) ?? null,
|
||||
pronunciation,
|
||||
category,
|
||||
usageCount: 0,
|
||||
lastUsedAt: null,
|
||||
|
|
@ -201,9 +123,7 @@ class DictionaryService {
|
|||
|
||||
update(params: DictionaryUpdateParams): DictionaryEntry | null {
|
||||
const result = buildDictionaryUpdatePatch(params)
|
||||
if (!result.ok) {
|
||||
throw new D3ROError(ErrorCode.DictionaryImportInvalidFormat, 'Dictionary word is empty')
|
||||
}
|
||||
if (!result.ok) throw dictionaryWriteProblemError(result)
|
||||
|
||||
const db = getDatabase()
|
||||
const existing = db.select().from(dictionary).where(eq(dictionary.id, params.id)).get()
|
||||
|
|
@ -334,8 +254,7 @@ class DictionaryService {
|
|||
.all()
|
||||
.map((row) => this._toEntry(row))
|
||||
|
||||
const content =
|
||||
params.format === 'csv' ? this._serializeCsv(entries) : this._serializeJson(entries)
|
||||
const content = serializeDictionary(entries, params.format)
|
||||
const defaultName = `d3ro-dictionary-${new Date().toISOString().slice(0, 10)}.${params.format}`
|
||||
|
||||
if (isShowingDictionarySaveDialog) {
|
||||
|
|
@ -398,7 +317,7 @@ class DictionaryService {
|
|||
|
||||
let parsed: Array<Record<string, unknown>>
|
||||
try {
|
||||
parsed = params.format === 'json' ? this._parseJson(raw) : this._parseCsv(raw)
|
||||
parsed = parseDictionaryFile(raw, params.format)
|
||||
} catch (err) {
|
||||
if (err instanceof D3ROError) throw err
|
||||
const message = err instanceof Error ? err.message : String(err)
|
||||
|
|
@ -413,37 +332,25 @@ class DictionaryService {
|
|||
const outcome: DictionaryImportResult = { imported: 0, skipped: 0, errors: 0 }
|
||||
|
||||
db.transaction((tx) => {
|
||||
for (const row of parsed) {
|
||||
const word = pickString(row, ['word'])
|
||||
if (!word) {
|
||||
for (const record of parsed) {
|
||||
// 빈 단어·서버 길이 제한 초과 행은 오류로 센다 — 로컬에만 남고 동기화되지 않는 항목을 만들지 않는다
|
||||
const candidate = toDictionaryImportRow(record, now)
|
||||
if (!candidate.ok) {
|
||||
outcome.errors += 1
|
||||
continue
|
||||
}
|
||||
const category = normalizeCategory(pickString(row, ['category']))
|
||||
const { row } = candidate
|
||||
// 대소문자만 다른 단어도 같은 단어로 본다(서버 유일성과 같은 기준)
|
||||
const existing = findImportDuplicate(tx, word, category)
|
||||
const existing = findImportDuplicate(tx, row.word, row.category)
|
||||
if (existing) {
|
||||
outcome.skipped += 1
|
||||
continue
|
||||
}
|
||||
|
||||
const createdAt = pickNumber(row, ['createdAt', 'created_at'])
|
||||
const updatedAt = pickNumber(row, ['updatedAt', 'updated_at'])
|
||||
const usageCount = pickNumber(row, ['usageCount', 'usage_count'])
|
||||
const lastUsedAt = pickNumber(row, ['lastUsedAt', 'last_used_at'])
|
||||
const id = crypto.randomUUID()
|
||||
try {
|
||||
tx.insert(dictionary)
|
||||
.values({
|
||||
id,
|
||||
word,
|
||||
pronunciation: pickString(row, ['pronunciation']),
|
||||
category,
|
||||
usageCount: usageCount !== null && usageCount >= 0 ? Math.floor(usageCount) : 0,
|
||||
lastUsedAt,
|
||||
createdAt: createdAt ?? now,
|
||||
updatedAt: updatedAt ?? createdAt ?? now
|
||||
})
|
||||
.values({ id, ...row })
|
||||
.run()
|
||||
outcome.imported += 1
|
||||
void getCloudSyncService().pushOne('dictionary', id)
|
||||
|
|
@ -459,64 +366,6 @@ class DictionaryService {
|
|||
return outcome
|
||||
}
|
||||
|
||||
private _serializeJson(entries: DictionaryEntry[]): string {
|
||||
return JSON.stringify({ entries }, null, 2)
|
||||
}
|
||||
|
||||
private _serializeCsv(entries: DictionaryEntry[]): string {
|
||||
const lines = [DICTIONARY_CSV_HEADER.join(',')]
|
||||
for (const entry of entries) {
|
||||
lines.push(
|
||||
[
|
||||
csvCell(entry.word),
|
||||
csvCell(entry.pronunciation ?? ''),
|
||||
csvCell(entry.category),
|
||||
csvCell(entry.usageCount),
|
||||
csvCell(entry.createdAt),
|
||||
csvCell(entry.updatedAt)
|
||||
].join(',')
|
||||
)
|
||||
}
|
||||
return `\uFEFF${lines.join('\r\n')}\r\n`
|
||||
}
|
||||
|
||||
private _parseJson(raw: string): Array<Record<string, unknown>> {
|
||||
const data: unknown = JSON.parse(raw)
|
||||
let list: unknown
|
||||
if (Array.isArray(data)) {
|
||||
list = data
|
||||
} else if (
|
||||
data &&
|
||||
typeof data === 'object' &&
|
||||
Array.isArray((data as { entries?: unknown }).entries)
|
||||
) {
|
||||
list = (data as { entries: unknown[] }).entries
|
||||
} else {
|
||||
throw new Error('expected an array or an object with an "entries" array')
|
||||
}
|
||||
return (list as unknown[]).filter(
|
||||
(item): item is Record<string, unknown> => !!item && typeof item === 'object'
|
||||
)
|
||||
}
|
||||
|
||||
private _parseCsv(raw: string): Array<Record<string, unknown>> {
|
||||
const rows = parseCsvRows(raw.replace(/^\uFEFF/, ''))
|
||||
if (rows.length === 0) {
|
||||
throw new Error('empty CSV')
|
||||
}
|
||||
const header = rows[0].map((cell) => cell.trim())
|
||||
if (!header.includes('word')) {
|
||||
throw new Error('missing "word" column')
|
||||
}
|
||||
return rows.slice(1).map((cells) => {
|
||||
const record: Record<string, unknown> = {}
|
||||
header.forEach((key, index) => {
|
||||
record[key] = cells[index] ?? ''
|
||||
})
|
||||
return record
|
||||
})
|
||||
}
|
||||
|
||||
dispose(): void {
|
||||
logger.info('DictionaryService disposed')
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue