-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvalidate.mjs
More file actions
executable file
·185 lines (150 loc) · 4.56 KB
/
validate.mjs
File metadata and controls
executable file
·185 lines (150 loc) · 4.56 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
#!/usr/bin/env node
import fs from 'node:fs/promises'
import path from 'node:path'
import { fileURLToPath } from 'node:url'
const __filename = fileURLToPath(import.meta.url)
export async function validateDeck(deckDir) {
const root = path.resolve(deckDir)
const errors = []
const warnings = []
const manifestPath = path.join(root, 'htmlslide.json')
let manifest
try {
manifest = JSON.parse(await fs.readFile(manifestPath, 'utf8'))
} catch (error) {
return {
ok: false,
errors: [`Missing or invalid htmlslide.json: ${error.message}`],
warnings,
}
}
if (manifest.version !== '1.0') {
errors.push('htmlslide.json version must be "1.0".')
}
if (!manifest.title || typeof manifest.title !== 'string') {
errors.push('htmlslide.json title is required.')
}
if (!Array.isArray(manifest.slides) || manifest.slides.length === 0) {
errors.push('htmlslide.json slides must be a non-empty array.')
}
const slideIds = new Set()
const slides = Array.isArray(manifest.slides) ? manifest.slides : []
for (let index = 0; index < slides.length; index++) {
const slide = slides[index]
const label = `slides[${index}]`
if (!slide || typeof slide !== 'object') {
errors.push(`${label} must be an object.`)
continue
}
if (slide.id) {
if (slideIds.has(slide.id)) {
errors.push(`${label}.id is duplicated: ${slide.id}`)
}
slideIds.add(slide.id)
}
if (!slide.src || typeof slide.src !== 'string') {
errors.push(`${label}.src is required.`)
continue
}
if (isUnsafeRelativePath(slide.src)) {
errors.push(`${label}.src is unsafe: ${slide.src}`)
continue
}
if (!/\.html?$/i.test(slide.src)) {
errors.push(`${label}.src must point to .html or .htm: ${slide.src}`)
continue
}
const slidePath = path.join(root, slide.src)
let html
try {
html = await fs.readFile(slidePath, 'utf8')
} catch {
errors.push(`${label}.src does not exist: ${slide.src}`)
continue
}
if (!isCompleteHtml(html)) {
warnings.push(`${slide.src} is not a complete HTML document.`)
}
const refs = collectLocalRefs(html)
for (const ref of refs) {
if (isExternalUrl(ref)) {
warnings.push(`${slide.src} references remote resource: ${ref}`)
continue
}
const resolvedRef = normalizeRelativePath(path.posix.join(path.posix.dirname(slide.src), cleanUrl(ref)))
if (isUnsafeRelativePath(resolvedRef)) {
errors.push(`${slide.src} has unsafe local reference: ${ref}`)
continue
}
try {
await fs.access(path.join(root, resolvedRef))
} catch {
errors.push(`${slide.src} references missing asset: ${ref}`)
}
}
}
return {
ok: errors.length === 0,
errors,
warnings: Array.from(new Set(warnings)),
}
}
function collectLocalRefs(html) {
const refs = []
const attrRegex = /\b(?:src|href)=("([^"]+)"|'([^']+)')/gi
const cssRegex = /url\((["']?)([^"')]+)\1\)/gi
let match
while ((match = attrRegex.exec(html))) {
refs.push(match[2] ?? match[3])
}
while ((match = cssRegex.exec(html))) {
refs.push(match[2])
}
return refs.filter((ref) => ref && !ref.startsWith('#') && !/^(mailto:|tel:)/i.test(ref))
}
function isCompleteHtml(html) {
const trimmed = html.trim().toLowerCase()
return trimmed.startsWith('<!doctype html') || trimmed.startsWith('<html')
}
function isExternalUrl(value) {
return /^(https?:|data:|blob:|\/\/)/i.test(value)
}
function cleanUrl(value) {
return decodeURIComponent(value.split('#')[0].split('?')[0])
}
function normalizeRelativePath(value) {
const parts = []
for (const part of value.replace(/\\/g, '/').split('/')) {
if (!part || part === '.') continue
if (part === '..') {
parts.pop()
} else {
parts.push(part)
}
}
return parts.join('/')
}
function isUnsafeRelativePath(value) {
const normalized = value.replace(/\\/g, '/')
return normalized.startsWith('/') || normalized.split('/').some((part) => part === '..')
}
async function main() {
const deckDir = process.argv[2] || 'examples/basic-deck'
const result = await validateDeck(deckDir)
for (const warning of result.warnings) {
console.warn(`warning: ${warning}`)
}
for (const error of result.errors) {
console.error(`error: ${error}`)
}
if (!result.ok) {
process.exit(1)
}
console.log(`HTMLSlide package is valid: ${path.resolve(deckDir)}`)
}
if (process.argv[1] === __filename) {
main().catch((error) => {
console.error(error)
process.exit(1)
})
}