Repository navigation
Expand file tree
/
Copy pathappearance.js
More file actions
90 lines (88 loc) · 5.87 KB
/
Copy pathappearance.js
File metadata and controls
90 lines (88 loc) · 5.87 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
import fs from 'node:fs'
import path from 'node:path'
import { randomUUID } from 'node:crypto'
const MAX_BYTES = 6 * 1024 * 1024
const formats = new Set(['png', 'jpg', 'webp', 'gif'])
const inside = (root, abs) => abs === root || abs.startsWith(root + path.sep)
function formatOf(bytes) {
if (bytes.subarray(0, 8).equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]))) return 'png'
if (bytes[0] === 255 && bytes[1] === 216 && bytes[2] === 255) return 'jpg'
if (['GIF87a', 'GIF89a'].includes(bytes.subarray(0, 6).toString('ascii'))) return 'gif'
if (bytes.subarray(0, 4).toString('ascii') === 'RIFF' && bytes.subarray(8, 12).toString('ascii') === 'WEBP') return 'webp'
throw new Error('图片内容不是受支持的 PNG、JPEG、WebP 或 GIF')
}
function sourceImage(root, args) {
let bytes, expected
if (args.dataUrl !== undefined) {
const match = /^data:image\/(png|jpeg|jpg|webp|gif);base64,([A-Za-z0-9+/=\s]+)$/.exec(args.dataUrl)
if (!match) throw new Error('需要 PNG、JPEG、WebP 或 GIF 的 base64 data URL')
expected = match[1] === 'jpeg' ? 'jpg' : match[1]
bytes = Buffer.from(match[2].replace(/\s/g, ''), 'base64')
} else {
const rel = String(args.imagePath || '').replace(/\\/g, '/')
if (!rel || path.isAbsolute(rel) || /^[a-z]:/i.test(rel) || /^[a-z][a-z0-9+.-]*:/i.test(rel) || rel.split('/').includes('..')) throw new Error('图片路径必须位于当前笔记库内,不能是远程 URL 或绝对路径')
if (rel.split('/').some((part) => part.startsWith('.')) && !/^\.dsh-notebooks\/(covers|backgrounds|uploads)\//.test(rel)) throw new Error('不能从内部元数据目录导入图片')
expected = path.extname(rel).slice(1).toLowerCase(); if (expected === 'jpeg') expected = 'jpg'
if (!formats.has(expected)) throw new Error('图片路径扩展名不受支持')
const file = fs.realpathSync(path.resolve(root, rel))
if (!inside(root, file) || !fs.statSync(file).isFile()) throw new Error('图片路径越界或不是文件')
if (fs.statSync(file).size > MAX_BYTES) throw new Error('图片不能超过 6MiB')
bytes = fs.readFileSync(file)
}
if (bytes.length > MAX_BYTES) throw new Error('图片不能超过 6MiB')
const format = formatOf(bytes)
if (format !== expected) throw new Error('图片扩展名或 MIME 与内容不一致')
return { bytes, format }
}
export function readAppearance(manifest) {
return { home: { image: manifest.homeBackground || '' }, diary: { image: manifest.diaryCover || '' },
notebooks: (manifest.notebooks || []).map((book) => ({ notebook: book.name, image: book.cover || '' })) }
}
// Caller owns its metadata transaction. Immutable assets never overwrite a
// previous cover; createdFiles is the transaction's cleanup/undo inventory.
export function applyAppearance(root, manifest, args) {
const allowed = new Set(['target', 'notebook', 'dataUrl', 'imagePath', 'clear', 'expectedPath'])
if (Object.keys(args).some((key) => !allowed.has(key))) throw new Error('不支持的外观参数')
if (!['home', 'diary', 'notebook'].includes(args.target)) throw new Error('target 只能是 home、diary 或 notebook')
if (args.notebook !== undefined && args.target !== 'notebook') throw new Error('只有笔记本外观可指定 notebook')
const book = args.target === 'notebook' ? (manifest.notebooks || []).find((item) => item.name === args.notebook) : null
if (args.target === 'notebook' && !book) throw new Error('找不到笔记本')
if (args.clear !== undefined && typeof args.clear !== 'boolean') throw new Error('clear 需要布尔值')
if ([args.dataUrl !== undefined, args.imagePath !== undefined, args.clear === true].filter(Boolean).length !== 1) throw new Error('必须且只能选择 dataUrl、imagePath 或 clear=true')
if (args.dataUrl !== undefined && typeof args.dataUrl !== 'string') throw new Error('dataUrl 需要字符串')
if (args.imagePath !== undefined && typeof args.imagePath !== 'string') throw new Error('imagePath 需要字符串')
const owner = book || manifest
const key = book ? 'cover' : args.target === 'home' ? 'homeBackground' : 'diaryCover'
if (args.expectedPath !== undefined && args.expectedPath !== (owner[key] || '')) throw new Error('外观已被修改,请重新读取后再执行')
const createdFiles = []
let image = ''
if (!args.clear) {
const base = fs.realpathSync(root), source = sourceImage(base, args)
const folder = args.target === 'home' ? 'backgrounds' : 'covers'
const dir = path.join(base, '.dsh-notebooks', folder)
let existing = dir
while (!fs.existsSync(existing)) existing = path.dirname(existing)
if (!inside(base, fs.realpathSync(existing))) throw new Error('图片保存目录越界')
fs.mkdirSync(dir, { recursive: true })
if (!inside(base, fs.realpathSync(dir))) throw new Error('图片保存目录越界')
image = `.dsh-notebooks/${folder}/appearance-${randomUUID()}.${source.format}`
const dest = path.resolve(base, image)
if (!inside(base, dest)) throw new Error('图片目标路径越界')
let fd
try { fd = fs.openSync(dest, 'wx', 0o600); fs.writeFileSync(fd, source.bytes) }
catch (err) { if (fd !== undefined && fs.existsSync(dest)) fs.unlinkSync(dest); throw err }
finally { if (fd !== undefined) fs.closeSync(fd) }
createdFiles.push(image)
}
owner[key] = image
return { target: args.target, ...(book ? { notebook: book.name } : {}), image, createdFiles }
}
export function removeCreatedAppearance(root, files) {
const base = fs.realpathSync(root)
for (const rel of files) {
if (!/^\.dsh-notebooks\/(covers|backgrounds)\/appearance-[0-9a-f-]{36}\.(png|jpg|webp|gif)$/.test(rel)) throw new Error('不是本次生成的外观资源路径')
const abs = path.resolve(base, rel)
if (!inside(base, abs)) throw new Error('外观清理路径越界')
if (fs.existsSync(abs)) { if (!inside(base, fs.realpathSync(abs))) throw new Error('外观清理路径越界'); fs.unlinkSync(abs) }
}
}