@prunellejs/cms 0.0.0-stage → 0.7.3

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,469 @@
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
+ const TAG_NEEDS_QUOTE_RE = /[,"\r\n]|^\s|\s$/
19
+
20
+ /** Formats a tags array for a single text input, CSV-quoting any tag with commas, quotes, line breaks, or outer spaces. */
21
+ export function formatTagsInput(value: unknown): string {
22
+ if (!Array.isArray(value))
23
+ return String(value)
24
+ return value.map((item) => {
25
+ const str = String(item)
26
+ return TAG_NEEDS_QUOTE_RE.test(str) ? `"${str.replaceAll('"', '""')}"` : str
27
+ }).join(', ')
28
+ }
29
+
30
+ /** Parses a comma/newline-separated tags string, honoring RFC 4180 double-quoted tags so commas inside a tag stay intact. */
31
+ export function parseTagsInput(raw: string): string[] {
32
+ const tags: string[] = []
33
+ const len = raw.length
34
+ let i = 0
35
+ while (i < len) {
36
+ while (i < len && (raw[i] === ' ' || raw[i] === '\t' || raw[i] === ',' || raw[i] === '\r' || raw[i] === '\n'))
37
+ i++
38
+ if (i >= len)
39
+ break
40
+ if (raw[i] === '"') {
41
+ i++
42
+ let val = ''
43
+ while (i < len) {
44
+ const ch = raw[i]!
45
+ if (ch === '"') {
46
+ if (raw[i + 1] === '"') {
47
+ val += '"'
48
+ i += 2
49
+ continue
50
+ }
51
+ i++
52
+ break
53
+ }
54
+ val += ch
55
+ i++
56
+ }
57
+ let tail = ''
58
+ while (i < len && raw[i] !== ',' && raw[i] !== '\r' && raw[i] !== '\n') {
59
+ tail += raw[i]!
60
+ i++
61
+ }
62
+ const combined = tail.trim().length > 0 ? `${val}${tail.trimEnd()}` : val
63
+ if (combined.length > 0)
64
+ tags.push(combined)
65
+ }
66
+ else {
67
+ const start = i
68
+ while (i < len && raw[i] !== ',' && raw[i] !== '\r' && raw[i] !== '\n')
69
+ i++
70
+ const clean = raw.slice(start, i).trim()
71
+ if (clean.length > 0)
72
+ tags.push(clean)
73
+ }
74
+ }
75
+ return tags
76
+ }
77
+
78
+ export interface ParsedRowAction {
79
+ readonly op: 'add' | 'remove' | 'up' | 'down'
80
+ readonly path: string
81
+ readonly index?: number | undefined
82
+ }
83
+
84
+ export interface ResolvedEntryPath {
85
+ readonly ok: true
86
+ readonly filePath: string
87
+ readonly slug: string
88
+ readonly locale?: string | undefined
89
+ }
90
+
91
+ export interface EntryPathError {
92
+ readonly ok: false
93
+ readonly status: 400 | 403
94
+ readonly message: string
95
+ /** Set when the slug is too long: shown as a field error on the slug. */
96
+ readonly tooLong?: true | undefined
97
+ }
98
+
99
+ /** Validates a slug (allowing nested `a/b/c` paths) and rejects traversal, empty segments, and unsafe characters. */
100
+ export function validateSlug(raw: string): { ok: true, slug: string } | { ok: false, message: string, tooLong?: true } {
101
+ const trimmed = raw.trim()
102
+ if (trimmed.length === 0)
103
+ return { ok: false, message: 'Slug is required.' }
104
+ if (UNSAFE_SLUG_CHAR_RE.test(trimmed) || !trimmed.isWellFormed())
105
+ return { ok: false, message: 'Slug contains invalid path characters.' }
106
+ const clean = trimmed.replace(/\.(?:md|markdown)$/i, '')
107
+ const segments = clean.split('/')
108
+ for (const seg of segments) {
109
+ if (seg.length === 0 || seg === '.' || seg === '..' || seg === '__proto__')
110
+ return { ok: false, message: `Slug segment "${seg}" is invalid.` }
111
+ if (Buffer.byteLength(seg) > MAX_SLUG_SEGMENT_BYTES)
112
+ return { ok: false, message: `Slug segment is too long (${MAX_SLUG_SEGMENT_BYTES} bytes at most).`, tooLong: true }
113
+ }
114
+ return { ok: true, slug: segments.join('/') }
115
+ }
116
+
117
+ /** Validates a locale identifier against safe characters and optional collection allowlist. */
118
+ export function validateLocale(
119
+ col: ContentCollectionDescriptor,
120
+ rawLocale: string | undefined,
121
+ ): { ok: true, locale: string | undefined } | { ok: false, message: string } {
122
+ if (!col.localized)
123
+ return { ok: true, locale: undefined }
124
+ const locale = (rawLocale ?? '').trim() || col.defaultLocale
125
+ if (!SAFE_LOCALE_RE.test(locale))
126
+ return { ok: false, message: `Invalid locale "${locale}".` }
127
+ if (col.locales !== undefined && col.locales.length > 0 && !col.locales.includes(locale))
128
+ return { ok: false, message: `Unknown locale "${locale}" for collection "${col.name}".` }
129
+ return { ok: true, locale }
130
+ }
131
+
132
+ function closestExistingDir(targetPath: string): string {
133
+ let cur = dirname(targetPath)
134
+ while (!existsSync(cur)) {
135
+ const parent = dirname(cur)
136
+ if (parent === cur)
137
+ break
138
+ cur = parent
139
+ }
140
+ return cur
141
+ }
142
+
143
+ function isPathConfined(targetPath: string, baseDir: string, realBase: string, depth = 0): boolean {
144
+ if (depth > 16)
145
+ return false
146
+ const realAncestor = realpathSync(closestExistingDir(targetPath))
147
+ if (!isInside(realBase, realAncestor, { orSame: true }))
148
+ return false
149
+
150
+ let cur = targetPath
151
+ while (cur !== baseDir && isInside(baseDir, cur)) {
152
+ try {
153
+ const stat = lstatSync(cur)
154
+ if (stat.isSymbolicLink()) {
155
+ const allowSame = cur !== targetPath
156
+ if (existsSync(cur)) {
157
+ if (!isInside(realBase, realpathSync(cur), { orSame: allowSame }))
158
+ return false
159
+ }
160
+ else {
161
+ const realParent = realpathSync(dirname(cur))
162
+ const linkTarget = resolve(realParent, readlinkSync(cur))
163
+ if (!isInside(realBase, linkTarget, { orSame: allowSame }))
164
+ return false
165
+ if (!isPathConfined(linkTarget, realBase, realBase, depth + 1))
166
+ return false
167
+ }
168
+ }
169
+ }
170
+ catch (err) {
171
+ const code = (err as NodeJS.ErrnoException).code
172
+ if (code !== 'ENOENT' && code !== 'ENOTDIR')
173
+ return false
174
+ }
175
+ const parent = dirname(cur)
176
+ if (parent === cur)
177
+ break
178
+ cur = parent
179
+ }
180
+ return true
181
+ }
182
+
183
+ /** Resolves a Markdown file path strictly confined inside `col.dir`, preventing path and symlink traversal. */
184
+ export function resolveEntryFilePath(
185
+ col: ContentCollectionDescriptor,
186
+ rawSlug: string,
187
+ rawLocale: string | undefined,
188
+ existingFile?: string | undefined,
189
+ ): ResolvedEntryPath | EntryPathError {
190
+ if (col.dir === undefined)
191
+ return { ok: false, status: 403, message: `Collection "${col.name}" is read-only (no filesystem directory).` }
192
+
193
+ const slugCheck = validateSlug(rawSlug)
194
+ if (!slugCheck.ok)
195
+ return { ok: false, status: 400, message: slugCheck.message, tooLong: slugCheck.tooLong }
196
+
197
+ const localeCheck = validateLocale(col, rawLocale)
198
+ if (!localeCheck.ok)
199
+ return { ok: false, status: 400, message: localeCheck.message }
200
+
201
+ const baseDir = resolve(col.dir)
202
+ const candidate = existingFile !== undefined
203
+ ? resolve(existingFile)
204
+ : resolve(
205
+ baseDir,
206
+ ...(localeCheck.locale !== undefined ? [localeCheck.locale] : []),
207
+ `${slugCheck.slug}.md`,
208
+ )
209
+
210
+ if (!isInside(baseDir, candidate))
211
+ return { ok: false, status: 400, message: 'Refused path outside collection directory.' }
212
+ if (Buffer.byteLength(candidate) > MAX_ENTRY_PATH_BYTES)
213
+ return { ok: false, status: 400, message: 'Slug is too long for this collection folder.', tooLong: true }
214
+
215
+ if (existsSync(baseDir)) {
216
+ const realBase = realpathSync(baseDir)
217
+ if (!isPathConfined(candidate, baseDir, realBase))
218
+ return { ok: false, status: 403, message: 'Refused symlink escaping collection directory.' }
219
+ }
220
+
221
+ return { ok: true, filePath: candidate, slug: slugCheck.slug, locale: localeCheck.locale }
222
+ }
223
+
224
+ function getStringField(formData: FormData, name: string): string | null {
225
+ const val = formData.get(name)
226
+ return typeof val === 'string' ? val : null
227
+ }
228
+
229
+ function findObjectArrayCount(formData: FormData, fieldName: string): number {
230
+ let count = 0
231
+ const declared = getStringField(formData, `__rows:${fieldName}`)
232
+ if (declared !== null) {
233
+ const parsed = Number.parseInt(declared, 10)
234
+ if (Number.isFinite(parsed) && parsed > 0)
235
+ count = Math.min(parsed, MAX_REPEATABLE_ROWS)
236
+ }
237
+ const prefix = `${fieldName}[`
238
+ for (const key of formData.keys()) {
239
+ if (!key.startsWith(prefix))
240
+ continue
241
+ const closeIdx = key.indexOf(']', prefix.length)
242
+ if (closeIdx === -1)
243
+ continue
244
+ const idx = Number.parseInt(key.slice(prefix.length, closeIdx), 10)
245
+ if (Number.isFinite(idx) && idx >= 0 && idx < MAX_REPEATABLE_ROWS)
246
+ count = Math.max(count, idx + 1)
247
+ }
248
+ return count
249
+ }
250
+
251
+ function parseFieldEntry(formData: FormData, field: CmsField, name: string): { value: unknown, present: boolean } {
252
+ switch (field.kind) {
253
+ case 'boolean': {
254
+ const raw = getStringField(formData, name)
255
+ return { value: raw === 'true' || raw === 'on' || raw === '1', present: raw !== null }
256
+ }
257
+ case 'number':
258
+ case 'integer': {
259
+ const raw = getStringField(formData, name)
260
+ if (raw === null)
261
+ return { value: undefined, present: false }
262
+ const trimmed = raw.trim()
263
+ if (trimmed === '')
264
+ return { value: undefined, present: false }
265
+ const num = Number(trimmed)
266
+ return { value: Number.isFinite(num) ? num : raw, present: true }
267
+ }
268
+ case 'enum': {
269
+ const raw = getStringField(formData, name)
270
+ if (raw === null || (raw === '' && !field.required))
271
+ return { value: undefined, present: false }
272
+ if (raw === '')
273
+ return { value: '', present: false }
274
+ if (field.enumType === 'number') {
275
+ const num = Number(raw)
276
+ return { value: Number.isFinite(num) ? num : raw, present: true }
277
+ }
278
+ return { value: raw, present: true }
279
+ }
280
+ case 'tags': {
281
+ const all = formData.getAll(name).filter((v): v is string => typeof v === 'string')
282
+ if (all.length === 0)
283
+ return { value: undefined, present: false }
284
+ const tags: string[] = []
285
+ for (const chunk of all)
286
+ tags.push(...parseTagsInput(chunk))
287
+ return { value: tags, present: tags.length > 0 }
288
+ }
289
+ case 'object': {
290
+ const nested: Record<string, unknown> = {}
291
+ let hasAny = false
292
+ for (const child of field.fields ?? []) {
293
+ const entry = parseFieldEntry(formData, child, `${name}.${child.key}`)
294
+ if (entry.value !== undefined)
295
+ nested[child.key] = entry.value
296
+ if (entry.present)
297
+ hasAny = true
298
+ }
299
+ if (hasAny || field.required)
300
+ return { value: nested, present: hasAny }
301
+ return { value: undefined, present: false }
302
+ }
303
+ case 'object-array': {
304
+ const count = findObjectArrayCount(formData, name)
305
+ const rows: Record<string, unknown>[] = []
306
+ for (let i = 0; i < count; i++) {
307
+ const row: Record<string, unknown> = {}
308
+ for (const child of field.fields ?? []) {
309
+ const entry = parseFieldEntry(formData, child, `${name}[${i}].${child.key}`)
310
+ if (entry.value !== undefined)
311
+ row[child.key] = entry.value
312
+ }
313
+ rows.push(row)
314
+ }
315
+ if (rows.length === 0 && !field.required && getStringField(formData, `__rows:${name}`) === null)
316
+ return { value: undefined, present: false }
317
+ return { value: rows, present: rows.length > 0 }
318
+ }
319
+ default: {
320
+ const raw = getStringField(formData, name)
321
+ if (raw === null)
322
+ return { value: undefined, present: false }
323
+ if (raw === '' && !field.required)
324
+ return { value: undefined, present: false }
325
+ return { value: raw, present: raw !== '' }
326
+ }
327
+ }
328
+ }
329
+
330
+ /** Parses submitted FormData into a structured frontmatter object according to `fields`. */
331
+ export function parseFormSubmission(formData: FormData, fields: readonly CmsField[]): Record<string, unknown> {
332
+ const out: Record<string, unknown> = {}
333
+ for (const field of fields) {
334
+ const { value } = parseFieldEntry(formData, field, field.key)
335
+ if (value !== undefined)
336
+ out[field.key] = value
337
+ }
338
+ return out
339
+ }
340
+
341
+ /** Parses a `__cms_action` submit button value (`add:<path>`, `remove:<path>:<idx>`, `up:<path>:<idx>`, `down:<path>:<idx>`). */
342
+ export function parseRowAction(raw: string | null): ParsedRowAction | undefined {
343
+ if (raw === null || raw.length === 0)
344
+ return undefined
345
+ const parts = raw.split(':')
346
+ const op = parts[0]
347
+ const path = parts[1]
348
+ if (!path)
349
+ return undefined
350
+ if (op === 'add')
351
+ return { op, path }
352
+ if (op === 'remove' || op === 'up' || op === 'down') {
353
+ const idx = Number.parseInt(parts[2] ?? '', 10)
354
+ if (!Number.isFinite(idx) || idx < 0)
355
+ return undefined
356
+ return { op, path, index: idx }
357
+ }
358
+ return undefined
359
+ }
360
+
361
+ function hasForbiddenPathSegment(segments: readonly string[]): boolean {
362
+ return segments.some(seg => FORBIDDEN_PATH_SEGMENTS.has(seg))
363
+ }
364
+
365
+ function getAtPath(obj: Record<string, unknown>, segments: readonly string[]): unknown {
366
+ if (hasForbiddenPathSegment(segments))
367
+ return undefined
368
+ let cur: unknown = obj
369
+ for (const seg of segments) {
370
+ if (cur === null || typeof cur !== 'object' || Array.isArray(cur) || !Object.hasOwn(cur, seg))
371
+ return undefined
372
+ cur = (cur as Record<string, unknown>)[seg]
373
+ }
374
+ return cur
375
+ }
376
+
377
+ function setAtPath(obj: Record<string, unknown>, segments: readonly string[], value: unknown): void {
378
+ if (segments.length === 0 || hasForbiddenPathSegment(segments))
379
+ return
380
+ let cur: Record<string, unknown> = obj
381
+ for (let i = 0; i < segments.length - 1; i++) {
382
+ const seg = segments[i]!
383
+ const next = Object.hasOwn(cur, seg) ? cur[seg] : undefined
384
+ if (next === null || typeof next !== 'object' || Array.isArray(next)) {
385
+ const created: Record<string, unknown> = {}
386
+ cur[seg] = created
387
+ cur = created
388
+ }
389
+ else {
390
+ cur = next as Record<string, unknown>
391
+ }
392
+ }
393
+ const last = segments[segments.length - 1]
394
+ if (last !== undefined)
395
+ cur[last] = value
396
+ }
397
+
398
+ /** Applies a no-JS repeatable row action (`add`, `remove`, `up`, `down`) to parsed form data. */
399
+ export function applyRowAction(data: Record<string, unknown>, action: ParsedRowAction): void {
400
+ const segments = action.path.split('.').filter(Boolean)
401
+ if (segments.length === 0 || hasForbiddenPathSegment(segments))
402
+ return
403
+ const existing = getAtPath(data, segments)
404
+ const rows = Array.isArray(existing) ? [...existing] : []
405
+ if (action.op === 'add') {
406
+ if (rows.length < MAX_REPEATABLE_ROWS)
407
+ rows.push({})
408
+ }
409
+ else if (action.op === 'remove' && action.index !== undefined && action.index < rows.length) {
410
+ rows.splice(action.index, 1)
411
+ }
412
+ else if (action.op === 'up' && action.index !== undefined && action.index > 0 && action.index < rows.length) {
413
+ const tmp = rows[action.index - 1]
414
+ rows[action.index - 1] = rows[action.index]
415
+ rows[action.index] = tmp
416
+ }
417
+ else if (action.op === 'down' && action.index !== undefined && action.index >= 0 && action.index + 1 < rows.length) {
418
+ const tmp = rows[action.index + 1]
419
+ rows[action.index + 1] = rows[action.index]
420
+ rows[action.index] = tmp
421
+ }
422
+ setAtPath(data, segments, rows)
423
+ }
424
+
425
+ /** Normalizes dotted issue paths (`items.0.title`) to bracketed input names (`items[0].title`). */
426
+ export function normalizeFieldErrorPath(path: string): string {
427
+ return path.replace(/\.(\d+)(?=\.|$)/g, '[$1]')
428
+ }
429
+
430
+ export { serializeFrontmatterYaml }
431
+
432
+ /** 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. */
433
+ export function findLoneSurrogate(value: unknown, path = ''): string | undefined {
434
+ if (typeof value === 'string')
435
+ return value.isWellFormed() ? undefined : path
436
+ if (value === null || typeof value !== 'object')
437
+ return undefined
438
+ const entries: [string, unknown][] = Array.isArray(value)
439
+ ? value.map((item, i) => [`[${i}]`, item])
440
+ : Object.entries(value as Record<string, unknown>)
441
+ for (const [key, child] of entries) {
442
+ const childPath = Array.isArray(value) ? `${path}${key}` : (path === '' ? key : `${path}.${key}`)
443
+ if (!Array.isArray(value) && !key.isWellFormed())
444
+ return childPath
445
+ const found = findLoneSurrogate(child, childPath)
446
+ if (found !== undefined)
447
+ return found
448
+ }
449
+ return undefined
450
+ }
451
+
452
+ export interface ExistingEntrySource {
453
+ readonly source: string
454
+ /** Keys the form edits; others are left untouched. Undefined means every key. */
455
+ readonly owned?: ReadonlySet<string> | undefined
456
+ }
457
+
458
+ /** Serializes frontmatter and Markdown body into a `.md` file string, editing `existing` in place when given. */
459
+ export function serializeMarkdownEntry(data: Record<string, unknown>, body: string, existing?: ExistingEntrySource): string {
460
+ const merged = existing === undefined ? undefined : mergeFrontmatterYaml(existing.source, data, existing.owned)
461
+ const yaml = merged ?? serializeFrontmatterYaml(data)
462
+ const normalizedBody = body.replace(/\r\n/g, '\n')
463
+ const trimmedBody = normalizedBody.endsWith('\n') || normalizedBody.length === 0
464
+ ? normalizedBody
465
+ : `${normalizedBody}\n`
466
+ return yaml.length > 0
467
+ ? `---\n${yaml}\n---\n\n${trimmedBody}`
468
+ : `---\n---\n\n${trimmedBody}`
469
+ }
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
+ }