|
| 1 | +import fs from 'fs' |
| 2 | +import path from 'path' |
| 3 | +import yaml from 'js-yaml' |
| 4 | +import readFrontmatter from '@/frame/lib/read-frontmatter' |
| 5 | +import { schema } from '@/frame/lib/frontmatter' |
| 6 | + |
| 7 | +const MAX_DIRECTORY_DEPTH = 20 |
| 8 | + |
| 9 | +/** |
| 10 | + * Enhanced recursive markdown file finder with symlink, depth, and root path checks |
| 11 | + */ |
| 12 | +export function findMarkdownFiles( |
| 13 | + dir: string, |
| 14 | + rootDir: string, |
| 15 | + depth: number = 0, |
| 16 | + maxDepth: number = MAX_DIRECTORY_DEPTH, |
| 17 | + visited: Set<string> = new Set(), |
| 18 | +): string[] { |
| 19 | + const markdownFiles: string[] = [] |
| 20 | + let realDir: string |
| 21 | + try { |
| 22 | + realDir = fs.realpathSync(dir) |
| 23 | + } catch { |
| 24 | + // If we can't resolve real path, skip this directory |
| 25 | + return [] |
| 26 | + } |
| 27 | + // Prevent escaping root directory |
| 28 | + if (!realDir.startsWith(rootDir)) { |
| 29 | + return [] |
| 30 | + } |
| 31 | + // Prevent symlink loops |
| 32 | + if (visited.has(realDir)) { |
| 33 | + return [] |
| 34 | + } |
| 35 | + visited.add(realDir) |
| 36 | + // Prevent excessive depth |
| 37 | + if (depth > maxDepth) { |
| 38 | + return [] |
| 39 | + } |
| 40 | + let entries: fs.Dirent[] |
| 41 | + try { |
| 42 | + entries = fs.readdirSync(realDir, { withFileTypes: true }) |
| 43 | + } catch { |
| 44 | + // If we can't read directory, skip |
| 45 | + return [] |
| 46 | + } |
| 47 | + for (const entry of entries) { |
| 48 | + const fullPath = path.join(realDir, entry.name) |
| 49 | + let realFullPath: string |
| 50 | + try { |
| 51 | + realFullPath = fs.realpathSync(fullPath) |
| 52 | + } catch { |
| 53 | + continue |
| 54 | + } |
| 55 | + // Prevent escaping root directory for files |
| 56 | + if (!realFullPath.startsWith(rootDir)) { |
| 57 | + continue |
| 58 | + } |
| 59 | + if (entry.isDirectory()) { |
| 60 | + markdownFiles.push(...findMarkdownFiles(realFullPath, rootDir, depth + 1, maxDepth, visited)) |
| 61 | + } else if (entry.isFile() && entry.name.endsWith('.md')) { |
| 62 | + markdownFiles.push(realFullPath) |
| 63 | + } |
| 64 | + } |
| 65 | + return markdownFiles |
| 66 | +} |
| 67 | + |
| 68 | +interface FrontmatterProperties { |
| 69 | + intro?: string |
| 70 | + [key: string]: unknown |
| 71 | +} |
| 72 | + |
| 73 | +/** |
| 74 | + * Function to merge new frontmatter properties into existing file while preserving formatting. |
| 75 | + * Uses surgical replacement to only modify the specific field(s) being updated, |
| 76 | + * preserving all original YAML formatting for unchanged fields. |
| 77 | + */ |
| 78 | +export function mergeFrontmatterProperties(filePath: string, newPropertiesYaml: string): string { |
| 79 | + const content = fs.readFileSync(filePath, 'utf8') |
| 80 | + const parsed = readFrontmatter(content) |
| 81 | + |
| 82 | + if (parsed.errors && parsed.errors.length > 0) { |
| 83 | + throw new Error( |
| 84 | + `Failed to parse frontmatter: ${parsed.errors.map((e) => e.message).join(', ')}`, |
| 85 | + ) |
| 86 | + } |
| 87 | + |
| 88 | + if (!parsed.content) { |
| 89 | + throw new Error('Failed to parse content from file') |
| 90 | + } |
| 91 | + |
| 92 | + try { |
| 93 | + // Clean up the AI response - remove markdown code blocks if present |
| 94 | + let cleanedYaml = newPropertiesYaml.trim() |
| 95 | + cleanedYaml = cleanedYaml.replace(/^```ya?ml\s*\n/i, '') |
| 96 | + cleanedYaml = cleanedYaml.replace(/\n```\s*$/i, '') |
| 97 | + cleanedYaml = cleanedYaml.trim() |
| 98 | + |
| 99 | + const newProperties = yaml.load(cleanedYaml) as FrontmatterProperties |
| 100 | + |
| 101 | + // Security: Validate against prototype pollution using the official frontmatter schema |
| 102 | + const allowedKeys = Object.keys(schema.properties) |
| 103 | + |
| 104 | + const sanitizedProperties = Object.fromEntries( |
| 105 | + Object.entries(newProperties).filter(([key]) => { |
| 106 | + if (allowedKeys.includes(key)) { |
| 107 | + return true |
| 108 | + } |
| 109 | + console.warn(`Filtered out potentially unsafe frontmatter key: ${key}`) |
| 110 | + return false |
| 111 | + }), |
| 112 | + ) |
| 113 | + |
| 114 | + // Split content into lines for surgical replacement |
| 115 | + const lines = content.split('\n') |
| 116 | + let inFrontmatter = false |
| 117 | + let frontmatterEndIndex = -1 |
| 118 | + |
| 119 | + // Find frontmatter boundaries |
| 120 | + for (let i = 0; i < lines.length; i++) { |
| 121 | + if (lines[i].trim() === '---') { |
| 122 | + if (!inFrontmatter) { |
| 123 | + inFrontmatter = true |
| 124 | + } else { |
| 125 | + frontmatterEndIndex = i |
| 126 | + break |
| 127 | + } |
| 128 | + } |
| 129 | + } |
| 130 | + |
| 131 | + // Replace each field value while preserving everything else |
| 132 | + for (const [key, value] of Object.entries(sanitizedProperties)) { |
| 133 | + const formattedValue = typeof value === 'string' ? `'${value.replace(/'/g, "''")}'` : value |
| 134 | + |
| 135 | + // Find the line with this field |
| 136 | + for (let i = 1; i < frontmatterEndIndex; i++) { |
| 137 | + const line = lines[i] |
| 138 | + if (line.startsWith(`${key}:`)) { |
| 139 | + // Simple replacement: keep the field name and spacing, replace the value |
| 140 | + const colonIndex = line.indexOf(':') |
| 141 | + const leadingSpace = line.substring(colonIndex + 1, colonIndex + 2) // Usually a space |
| 142 | + lines[i] = `${key}:${leadingSpace}${formattedValue}` |
| 143 | + |
| 144 | + // Remove any continuation lines (multi-line values) |
| 145 | + const j = i + 1 |
| 146 | + while (j < frontmatterEndIndex && lines[j].startsWith(' ')) { |
| 147 | + lines.splice(j, 1) |
| 148 | + frontmatterEndIndex-- |
| 149 | + } |
| 150 | + break |
| 151 | + } |
| 152 | + } |
| 153 | + } |
| 154 | + |
| 155 | + return lines.join('\n') |
| 156 | + } catch (error) { |
| 157 | + console.error('Failed to parse AI response as YAML:') |
| 158 | + console.error('Raw AI response:', JSON.stringify(newPropertiesYaml)) |
| 159 | + throw new Error(`Failed to parse new frontmatter properties: ${error}`) |
| 160 | + } |
| 161 | +} |
0 commit comments