@prunellejs/cms 0.0.0-stage → 0.7.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,415 @@
1
+ // FormData parsing, coercion, no-JS repeatable row actions, YAML serialization, and safe file-path resolution.
2
+
3
+ import type { ContentCollectionDescriptor } from 'prunelle/config'
4
+ import type { CmsField } from './schema'
5
+ import { existsSync, lstatSync, readlinkSync, realpathSync } from 'node:fs'
6
+ import { dirname, resolve } from 'node:path'
7
+ import { isInside } from 'prunelle/config'
8
+ import { mergeFrontmatterYaml, serializeFrontmatterYaml } from './yaml-serialize'
9
+
10
+ const FORBIDDEN_PATH_SEGMENTS = new Set(['__proto__', 'constructor', 'prototype'])
11
+
12
+ const SAFE_LOCALE_RE = /^[a-zA-Z0-9_-]{1,32}$/
13
+ // Content serves any file name in the collection folder, so a segment only refuses what could escape or break it.
14
+ const UNSAFE_SLUG_CHAR_RE = /[\0-\x1F\x7F\\]/
15
+ const MAX_SLUG_SEGMENT_BYTES = 252 // 255 minus the `.md` suffix
16
+ const MAX_ENTRY_PATH_BYTES = 4000 // PATH_MAX 4096 minus room for the temp file of a save
17
+ const MAX_REPEATABLE_ROWS = 500
18
+
19
+ export interface ParsedRowAction {
20
+ readonly op: 'add' | 'remove' | 'up' | 'down'
21
+ readonly path: string
22
+ readonly index?: number | undefined
23
+ }
24
+
25
+ export interface ResolvedEntryPath {
26
+ readonly ok: true
27
+ readonly filePath: string
28
+ readonly slug: string
29
+ readonly locale?: string | undefined
30
+ }
31
+
32
+ export interface EntryPathError {
33
+ readonly ok: false
34
+ readonly status: 400 | 403
35
+ readonly message: string
36
+ /** Set when the slug is too long: shown as a field error on the slug. */
37
+ readonly tooLong?: true | undefined
38
+ }
39
+
40
+ /** Validates a slug (allowing nested `a/b/c` paths) and rejects traversal, empty segments, and unsafe characters. */
41
+ export function validateSlug(raw: string): { ok: true, slug: string } | { ok: false, message: string, tooLong?: true } {
42
+ const trimmed = raw.trim()
43
+ if (trimmed.length === 0)
44
+ return { ok: false, message: 'Slug is required.' }
45
+ if (UNSAFE_SLUG_CHAR_RE.test(trimmed) || !trimmed.isWellFormed())
46
+ return { ok: false, message: 'Slug contains invalid path characters.' }
47
+ const clean = trimmed.replace(/\.(?:md|markdown)$/i, '')
48
+ const segments = clean.split('/')
49
+ for (const seg of segments) {
50
+ if (seg.length === 0 || seg === '.' || seg === '..' || seg === '__proto__')
51
+ return { ok: false, message: `Slug segment "${seg}" is invalid.` }
52
+ if (Buffer.byteLength(seg) > MAX_SLUG_SEGMENT_BYTES)
53
+ return { ok: false, message: `Slug segment is too long (${MAX_SLUG_SEGMENT_BYTES} bytes at most).`, tooLong: true }
54
+ }
55
+ return { ok: true, slug: segments.join('/') }
56
+ }
57
+
58
+ /** Validates a locale identifier against safe characters and optional collection allowlist. */
59
+ export function validateLocale(
60
+ col: ContentCollectionDescriptor,
61
+ rawLocale: string | undefined,
62
+ ): { ok: true, locale: string | undefined } | { ok: false, message: string } {
63
+ if (!col.localized)
64
+ return { ok: true, locale: undefined }
65
+ const locale = (rawLocale ?? '').trim() || col.defaultLocale
66
+ if (!SAFE_LOCALE_RE.test(locale))
67
+ return { ok: false, message: `Invalid locale "${locale}".` }
68
+ if (col.locales !== undefined && col.locales.length > 0 && !col.locales.includes(locale))
69
+ return { ok: false, message: `Unknown locale "${locale}" for collection "${col.name}".` }
70
+ return { ok: true, locale }
71
+ }
72
+
73
+ function closestExistingDir(targetPath: string): string {
74
+ let cur = dirname(targetPath)
75
+ while (!existsSync(cur)) {
76
+ const parent = dirname(cur)
77
+ if (parent === cur)
78
+ break
79
+ cur = parent
80
+ }
81
+ return cur
82
+ }
83
+
84
+ function isPathConfined(targetPath: string, baseDir: string, realBase: string, depth = 0): boolean {
85
+ if (depth > 16)
86
+ return false
87
+ const realAncestor = realpathSync(closestExistingDir(targetPath))
88
+ if (!isInside(realBase, realAncestor, { orSame: true }))
89
+ return false
90
+
91
+ let cur = targetPath
92
+ while (cur !== baseDir && isInside(baseDir, cur)) {
93
+ try {
94
+ const stat = lstatSync(cur)
95
+ if (stat.isSymbolicLink()) {
96
+ const allowSame = cur !== targetPath
97
+ if (existsSync(cur)) {
98
+ if (!isInside(realBase, realpathSync(cur), { orSame: allowSame }))
99
+ return false
100
+ }
101
+ else {
102
+ const realParent = realpathSync(dirname(cur))
103
+ const linkTarget = resolve(realParent, readlinkSync(cur))
104
+ if (!isInside(realBase, linkTarget, { orSame: allowSame }))
105
+ return false
106
+ if (!isPathConfined(linkTarget, realBase, realBase, depth + 1))
107
+ return false
108
+ }
109
+ }
110
+ }
111
+ catch (err) {
112
+ const code = (err as NodeJS.ErrnoException).code
113
+ if (code !== 'ENOENT' && code !== 'ENOTDIR')
114
+ return false
115
+ }
116
+ const parent = dirname(cur)
117
+ if (parent === cur)
118
+ break
119
+ cur = parent
120
+ }
121
+ return true
122
+ }
123
+
124
+ /** Resolves a Markdown file path strictly confined inside `col.dir`, preventing path and symlink traversal. */
125
+ export function resolveEntryFilePath(
126
+ col: ContentCollectionDescriptor,
127
+ rawSlug: string,
128
+ rawLocale: string | undefined,
129
+ existingFile?: string | undefined,
130
+ ): ResolvedEntryPath | EntryPathError {
131
+ if (col.dir === undefined)
132
+ return { ok: false, status: 403, message: `Collection "${col.name}" is read-only (no filesystem directory).` }
133
+
134
+ const slugCheck = validateSlug(rawSlug)
135
+ if (!slugCheck.ok)
136
+ return { ok: false, status: 400, message: slugCheck.message, tooLong: slugCheck.tooLong }
137
+
138
+ const localeCheck = validateLocale(col, rawLocale)
139
+ if (!localeCheck.ok)
140
+ return { ok: false, status: 400, message: localeCheck.message }
141
+
142
+ const baseDir = resolve(col.dir)
143
+ const candidate = existingFile !== undefined
144
+ ? resolve(existingFile)
145
+ : resolve(
146
+ baseDir,
147
+ ...(localeCheck.locale !== undefined ? [localeCheck.locale] : []),
148
+ `${slugCheck.slug}.md`,
149
+ )
150
+
151
+ if (!isInside(baseDir, candidate))
152
+ return { ok: false, status: 400, message: 'Refused path outside collection directory.' }
153
+ if (Buffer.byteLength(candidate) > MAX_ENTRY_PATH_BYTES)
154
+ return { ok: false, status: 400, message: 'Slug is too long for this collection folder.', tooLong: true }
155
+
156
+ if (existsSync(baseDir)) {
157
+ const realBase = realpathSync(baseDir)
158
+ if (!isPathConfined(candidate, baseDir, realBase))
159
+ return { ok: false, status: 403, message: 'Refused symlink escaping collection directory.' }
160
+ }
161
+
162
+ return { ok: true, filePath: candidate, slug: slugCheck.slug, locale: localeCheck.locale }
163
+ }
164
+
165
+ function getStringField(formData: FormData, name: string): string | null {
166
+ const val = formData.get(name)
167
+ return typeof val === 'string' ? val : null
168
+ }
169
+
170
+ function findObjectArrayCount(formData: FormData, fieldName: string): number {
171
+ let count = 0
172
+ const declared = getStringField(formData, `__rows:${fieldName}`)
173
+ if (declared !== null) {
174
+ const parsed = Number.parseInt(declared, 10)
175
+ if (Number.isFinite(parsed) && parsed > 0)
176
+ count = Math.min(parsed, MAX_REPEATABLE_ROWS)
177
+ }
178
+ const prefix = `${fieldName}[`
179
+ for (const key of formData.keys()) {
180
+ if (!key.startsWith(prefix))
181
+ continue
182
+ const closeIdx = key.indexOf(']', prefix.length)
183
+ if (closeIdx === -1)
184
+ continue
185
+ const idx = Number.parseInt(key.slice(prefix.length, closeIdx), 10)
186
+ if (Number.isFinite(idx) && idx >= 0 && idx < MAX_REPEATABLE_ROWS)
187
+ count = Math.max(count, idx + 1)
188
+ }
189
+ return count
190
+ }
191
+
192
+ function parseFieldEntry(formData: FormData, field: CmsField, name: string): { value: unknown, present: boolean } {
193
+ switch (field.kind) {
194
+ case 'boolean': {
195
+ const raw = getStringField(formData, name)
196
+ return { value: raw === 'true' || raw === 'on' || raw === '1', present: raw !== null }
197
+ }
198
+ case 'number':
199
+ case 'integer': {
200
+ const raw = getStringField(formData, name)
201
+ if (raw === null)
202
+ return { value: undefined, present: false }
203
+ const trimmed = raw.trim()
204
+ if (trimmed === '')
205
+ return { value: undefined, present: false }
206
+ const num = Number(trimmed)
207
+ return { value: Number.isFinite(num) ? num : raw, present: true }
208
+ }
209
+ case 'enum': {
210
+ const raw = getStringField(formData, name)
211
+ if (raw === null || (raw === '' && !field.required))
212
+ return { value: undefined, present: false }
213
+ if (raw === '')
214
+ return { value: '', present: false }
215
+ if (field.enumType === 'number') {
216
+ const num = Number(raw)
217
+ return { value: Number.isFinite(num) ? num : raw, present: true }
218
+ }
219
+ return { value: raw, present: true }
220
+ }
221
+ case 'tags': {
222
+ const all = formData.getAll(name).filter((v): v is string => typeof v === 'string')
223
+ if (all.length === 0)
224
+ return { value: undefined, present: false }
225
+ const tags: string[] = []
226
+ for (const chunk of all) {
227
+ for (const item of chunk.split(/[,\r\n]+/)) {
228
+ const clean = item.trim()
229
+ if (clean.length > 0)
230
+ tags.push(clean)
231
+ }
232
+ }
233
+ return { value: tags, present: tags.length > 0 }
234
+ }
235
+ case 'object': {
236
+ const nested: Record<string, unknown> = {}
237
+ let hasAny = false
238
+ for (const child of field.fields ?? []) {
239
+ const entry = parseFieldEntry(formData, child, `${name}.${child.key}`)
240
+ if (entry.value !== undefined)
241
+ nested[child.key] = entry.value
242
+ if (entry.present)
243
+ hasAny = true
244
+ }
245
+ if (hasAny || field.required)
246
+ return { value: nested, present: hasAny }
247
+ return { value: undefined, present: false }
248
+ }
249
+ case 'object-array': {
250
+ const count = findObjectArrayCount(formData, name)
251
+ const rows: Record<string, unknown>[] = []
252
+ for (let i = 0; i < count; i++) {
253
+ const row: Record<string, unknown> = {}
254
+ for (const child of field.fields ?? []) {
255
+ const entry = parseFieldEntry(formData, child, `${name}[${i}].${child.key}`)
256
+ if (entry.value !== undefined)
257
+ row[child.key] = entry.value
258
+ }
259
+ rows.push(row)
260
+ }
261
+ if (rows.length === 0 && !field.required && getStringField(formData, `__rows:${name}`) === null)
262
+ return { value: undefined, present: false }
263
+ return { value: rows, present: rows.length > 0 }
264
+ }
265
+ default: {
266
+ const raw = getStringField(formData, name)
267
+ if (raw === null)
268
+ return { value: undefined, present: false }
269
+ if (raw === '' && !field.required)
270
+ return { value: undefined, present: false }
271
+ return { value: raw, present: raw !== '' }
272
+ }
273
+ }
274
+ }
275
+
276
+ /** Parses submitted FormData into a structured frontmatter object according to `fields`. */
277
+ export function parseFormSubmission(formData: FormData, fields: readonly CmsField[]): Record<string, unknown> {
278
+ const out: Record<string, unknown> = {}
279
+ for (const field of fields) {
280
+ const { value } = parseFieldEntry(formData, field, field.key)
281
+ if (value !== undefined)
282
+ out[field.key] = value
283
+ }
284
+ return out
285
+ }
286
+
287
+ /** Parses a `__cms_action` submit button value (`add:<path>`, `remove:<path>:<idx>`, `up:<path>:<idx>`, `down:<path>:<idx>`). */
288
+ export function parseRowAction(raw: string | null): ParsedRowAction | undefined {
289
+ if (raw === null || raw.length === 0)
290
+ return undefined
291
+ const parts = raw.split(':')
292
+ const op = parts[0]
293
+ const path = parts[1]
294
+ if (!path)
295
+ return undefined
296
+ if (op === 'add')
297
+ return { op, path }
298
+ if (op === 'remove' || op === 'up' || op === 'down') {
299
+ const idx = Number.parseInt(parts[2] ?? '', 10)
300
+ if (!Number.isFinite(idx) || idx < 0)
301
+ return undefined
302
+ return { op, path, index: idx }
303
+ }
304
+ return undefined
305
+ }
306
+
307
+ function hasForbiddenPathSegment(segments: readonly string[]): boolean {
308
+ return segments.some(seg => FORBIDDEN_PATH_SEGMENTS.has(seg))
309
+ }
310
+
311
+ function getAtPath(obj: Record<string, unknown>, segments: readonly string[]): unknown {
312
+ if (hasForbiddenPathSegment(segments))
313
+ return undefined
314
+ let cur: unknown = obj
315
+ for (const seg of segments) {
316
+ if (cur === null || typeof cur !== 'object' || Array.isArray(cur) || !Object.hasOwn(cur, seg))
317
+ return undefined
318
+ cur = (cur as Record<string, unknown>)[seg]
319
+ }
320
+ return cur
321
+ }
322
+
323
+ function setAtPath(obj: Record<string, unknown>, segments: readonly string[], value: unknown): void {
324
+ if (segments.length === 0 || hasForbiddenPathSegment(segments))
325
+ return
326
+ let cur: Record<string, unknown> = obj
327
+ for (let i = 0; i < segments.length - 1; i++) {
328
+ const seg = segments[i]!
329
+ const next = Object.hasOwn(cur, seg) ? cur[seg] : undefined
330
+ if (next === null || typeof next !== 'object' || Array.isArray(next)) {
331
+ const created: Record<string, unknown> = {}
332
+ cur[seg] = created
333
+ cur = created
334
+ }
335
+ else {
336
+ cur = next as Record<string, unknown>
337
+ }
338
+ }
339
+ const last = segments[segments.length - 1]
340
+ if (last !== undefined)
341
+ cur[last] = value
342
+ }
343
+
344
+ /** Applies a no-JS repeatable row action (`add`, `remove`, `up`, `down`) to parsed form data. */
345
+ export function applyRowAction(data: Record<string, unknown>, action: ParsedRowAction): void {
346
+ const segments = action.path.split('.').filter(Boolean)
347
+ if (segments.length === 0 || hasForbiddenPathSegment(segments))
348
+ return
349
+ const existing = getAtPath(data, segments)
350
+ const rows = Array.isArray(existing) ? [...existing] : []
351
+ if (action.op === 'add') {
352
+ if (rows.length < MAX_REPEATABLE_ROWS)
353
+ rows.push({})
354
+ }
355
+ else if (action.op === 'remove' && action.index !== undefined && action.index < rows.length) {
356
+ rows.splice(action.index, 1)
357
+ }
358
+ else if (action.op === 'up' && action.index !== undefined && action.index > 0 && action.index < rows.length) {
359
+ const tmp = rows[action.index - 1]
360
+ rows[action.index - 1] = rows[action.index]
361
+ rows[action.index] = tmp
362
+ }
363
+ else if (action.op === 'down' && action.index !== undefined && action.index >= 0 && action.index + 1 < rows.length) {
364
+ const tmp = rows[action.index + 1]
365
+ rows[action.index + 1] = rows[action.index]
366
+ rows[action.index] = tmp
367
+ }
368
+ setAtPath(data, segments, rows)
369
+ }
370
+
371
+ /** Normalizes dotted issue paths (`items.0.title`) to bracketed input names (`items[0].title`). */
372
+ export function normalizeFieldErrorPath(path: string): string {
373
+ return path.replace(/\.(\d+)(?=\.|$)/g, '[$1]')
374
+ }
375
+
376
+ export { serializeFrontmatterYaml }
377
+
378
+ /** Returns the form path of the first key or string holding a lone UTF-16 surrogate, which would write a file that no longer parses. */
379
+ export function findLoneSurrogate(value: unknown, path = ''): string | undefined {
380
+ if (typeof value === 'string')
381
+ return value.isWellFormed() ? undefined : path
382
+ if (value === null || typeof value !== 'object')
383
+ return undefined
384
+ const entries: [string, unknown][] = Array.isArray(value)
385
+ ? value.map((item, i) => [`[${i}]`, item])
386
+ : Object.entries(value as Record<string, unknown>)
387
+ for (const [key, child] of entries) {
388
+ const childPath = Array.isArray(value) ? `${path}${key}` : (path === '' ? key : `${path}.${key}`)
389
+ if (!Array.isArray(value) && !key.isWellFormed())
390
+ return childPath
391
+ const found = findLoneSurrogate(child, childPath)
392
+ if (found !== undefined)
393
+ return found
394
+ }
395
+ return undefined
396
+ }
397
+
398
+ export interface ExistingEntrySource {
399
+ readonly source: string
400
+ /** Keys the form edits; others are left untouched. Undefined means every key. */
401
+ readonly owned?: ReadonlySet<string> | undefined
402
+ }
403
+
404
+ /** Serializes frontmatter and Markdown body into a `.md` file string, editing `existing` in place when given. */
405
+ export function serializeMarkdownEntry(data: Record<string, unknown>, body: string, existing?: ExistingEntrySource): string {
406
+ const merged = existing === undefined ? undefined : mergeFrontmatterYaml(existing.source, data, existing.owned)
407
+ const yaml = merged ?? serializeFrontmatterYaml(data)
408
+ const normalizedBody = body.replace(/\r\n/g, '\n')
409
+ const trimmedBody = normalizedBody.endsWith('\n') || normalizedBody.length === 0
410
+ ? normalizedBody
411
+ : `${normalizedBody}\n`
412
+ return yaml.length > 0
413
+ ? `---\n${yaml}\n---\n\n${trimmedBody}`
414
+ : `---\n---\n\n${trimmedBody}`
415
+ }
package/src/guard.ts ADDED
@@ -0,0 +1,23 @@
1
+ // The access guard, kept apart from the editor so the plugin entry loads nothing else outside dev.
2
+
3
+ import type { RequestContext } from 'prunelle/server'
4
+
5
+ export type CmsGuard = (ctx: RequestContext) => boolean | Response | Promise<boolean | Response>
6
+
7
+ export function textResponse(text: string, status: number): Response {
8
+ return new Response(text, {
9
+ status,
10
+ headers: { 'content-type': 'text/plain; charset=utf-8' },
11
+ })
12
+ }
13
+
14
+ export async function runGuard(guard: CmsGuard | undefined, ctx: RequestContext): Promise<Response | undefined> {
15
+ if (guard === undefined)
16
+ return undefined
17
+ const decision = await guard(ctx)
18
+ if (decision instanceof Response)
19
+ return decision
20
+ if (decision === false)
21
+ return textResponse('Forbidden', 403)
22
+ return undefined
23
+ }