domma-cms 1.47.3 → 1.47.5

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,161 @@
1
+ /**
2
+ * Form uploads - the private store for files visitors send with a form.
3
+ *
4
+ * A visitor's file (a CV, a right-to-work document, a photo of a fault) is not
5
+ * site content: it is kept out of content/media/ - so it is neither served at
6
+ * /media/ to anyone with the address nor listed in the admin's Media library -
7
+ * and out of the site repo. Layout:
8
+ *
9
+ * content/form-uploads/<form slug>/<upload id>/<8 hex>-<cleaned name>
10
+ *
11
+ * The upload id is one uuid per submission (the entry id is not known until
12
+ * the entry is written, after its files), or the entry id for a file moved here
13
+ * by form-uploads-migration.js. Every path is built with fileIn
14
+ * (services/safePath.js), one plain segment at a time, so no stored reference
15
+ * can name a file outside this folder.
16
+ *
17
+ * A submission stores each file as {url, name, size, mime}, where url is the
18
+ * admin-only route that serves it (routes/api/forms.js):
19
+ *
20
+ * /api/forms/<form slug>/uploads/<upload id>/<stored name>
21
+ *
22
+ * @module services/formUploads
23
+ */
24
+ import fs from 'fs/promises';
25
+ import {createReadStream, existsSync, mkdirSync, writeFileSync} from 'fs';
26
+ import path from 'path';
27
+ import {config} from '../config.js';
28
+ import {fileIn} from './safePath.js';
29
+
30
+ /** content/form-uploads - beside content/media, never inside it. */
31
+ export function formUploadsRoot() {
32
+ return path.join(path.dirname(path.resolve(config.content.mediaDir)), 'form-uploads');
33
+ }
34
+
35
+ /** An upload id: a uuid for a new submission, an entry id for a migrated one. */
36
+ const UPLOAD_ID = /^[A-Za-z0-9_-]{1,80}$/;
37
+ /** A stored name: eight hex characters, a dash and the cleaned upload name (cleanUploadName). */
38
+ const STORED_NAME = /^[0-9a-f]{8}-[\w.-]{1,200}$/;
39
+
40
+ /** Whether the three parts of a private reference have the shapes this store writes. */
41
+ export function validParts(slug, id, name) {
42
+ return typeof slug === 'string' && slug !== '' && UPLOAD_ID.test(String(id || ''))
43
+ && STORED_NAME.test(String(name || '')) && name !== '.' && name !== '..';
44
+ }
45
+
46
+ /**
47
+ * The file for slug/id/name, inside the store. Throws (statusCode 404) for any
48
+ * part that is not one plain segment of the expected shape.
49
+ */
50
+ export function uploadPath(slug, id, name, root = formUploadsRoot()) {
51
+ if (!validParts(slug, id, name)) {
52
+ throw Object.assign(new Error('Not found'), {statusCode: 404, code: 'ENOENT'});
53
+ }
54
+ return fileIn(fileIn(fileIn(root, slug), id), name);
55
+ }
56
+
57
+ /** The route a stored reference points at. */
58
+ export function uploadUrl(slug, id, name) {
59
+ return `/api/forms/${encodeURIComponent(slug)}/uploads/${encodeURIComponent(id)}/${encodeURIComponent(name)}`;
60
+ }
61
+
62
+ const URL_RE = /^\/api\/forms\/([^/?#]+)\/uploads\/([^/?#]+)\/([^/?#]+)$/;
63
+
64
+ /**
65
+ * The parts of a private reference's url, or null when it is not one (or has
66
+ * parts of the wrong shape).
67
+ *
68
+ * @param {string} url
69
+ * @returns {{slug: string, id: string, name: string}|null}
70
+ */
71
+ export function parseUploadUrl(url) {
72
+ const m = URL_RE.exec(String(url || ''));
73
+ if (!m) return null;
74
+ let slug, id, name;
75
+ try { [slug, id, name] = m.slice(1).map(decodeURIComponent); } catch { return null; }
76
+ return validParts(slug, id, name) ? {slug, id, name} : null;
77
+ }
78
+
79
+ /**
80
+ * Keep the store out of git: a `*` .gitignore inside it (so a site repo
81
+ * never commits a visitor's file, whatever its own .gitignore says). Never throws.
82
+ */
83
+ export function keepUploadsOutOfGit(root = formUploadsRoot()) {
84
+ try {
85
+ mkdirSync(root, {recursive: true});
86
+ const ignore = path.join(root, '.gitignore');
87
+ if (!existsSync(ignore)) writeFileSync(ignore, '# Visitors\' form uploads - private, never committed.\n*\n');
88
+ } catch { /* never fail a submission over this */ }
89
+ }
90
+
91
+ /**
92
+ * Write one file of a submission. Never over another file: EEXIST is thrown for
93
+ * the caller to pick another name, and a write that fails part way is removed.
94
+ *
95
+ * @returns {Promise<{slug: string, id: string, name: string, url: string}>}
96
+ */
97
+ export async function saveUpload(slug, id, name, buffer, root = formUploadsRoot()) {
98
+ const file = uploadPath(slug, id, name, root);
99
+ keepUploadsOutOfGit(root);
100
+ await fs.mkdir(path.dirname(file), {recursive: true});
101
+ try {
102
+ await fs.writeFile(file, buffer, {flag: 'wx'});
103
+ } catch (err) {
104
+ if (err.code !== 'EEXIST') await fs.rm(file, {force: true}).catch(() => {});
105
+ throw err;
106
+ }
107
+ return {slug, id, name, url: uploadUrl(slug, id, name)};
108
+ }
109
+
110
+ /**
111
+ * A stored file to serve: its path and size, or null when it is not there (or
112
+ * is not a regular file).
113
+ */
114
+ export async function statUpload(slug, id, name, root = formUploadsRoot()) {
115
+ let file;
116
+ try { file = uploadPath(slug, id, name, root); } catch { return null; }
117
+ try {
118
+ const st = await fs.lstat(file);
119
+ return st.isFile() ? {file, size: st.size} : null;
120
+ } catch { return null; }
121
+ }
122
+
123
+ export const openUpload = (file) => createReadStream(file);
124
+
125
+ /**
126
+ * Delete one stored file, and its submission folder once empty. Answers false
127
+ * when there was nothing to delete. Throws (404) for a reference of the wrong shape.
128
+ */
129
+ export async function deleteUpload(slug, id, name, root = formUploadsRoot()) {
130
+ const file = uploadPath(slug, id, name, root);
131
+ let st;
132
+ try { st = await fs.lstat(file); } catch (err) { if (err.code === 'ENOENT') return false; throw err; }
133
+ if (!st.isFile()) return false;
134
+ await fs.unlink(file);
135
+ await fs.rmdir(path.dirname(file)).catch(() => {}); // only when empty
136
+ return true;
137
+ }
138
+
139
+ /**
140
+ * How a file is sent: inline only for the kinds a browser shows without
141
+ * running anything (PNG, JPEG, GIF, WebP, PDF), as an attachment otherwise.
142
+ *
143
+ * @param {string} name - the stored name
144
+ * @returns {{type: string, inline: boolean}}
145
+ */
146
+ export function servedAs(name) {
147
+ const ext = path.extname(String(name || '')).toLowerCase();
148
+ const inline = {'.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.gif': 'image/gif',
149
+ '.webp': 'image/webp', '.pdf': 'application/pdf'}[ext];
150
+ return inline ? {type: inline, inline: true} : {type: 'application/octet-stream', inline: false};
151
+ }
152
+
153
+ /**
154
+ * A Content-Disposition value: `inline` or `attachment`, an ASCII fallback
155
+ * name and the UTF-8 one (RFC 6266 / 5987).
156
+ */
157
+ export function disposition(inline, displayName) {
158
+ const raw = String(displayName || 'file').replace(/[\u0000-\u001f\u007f"\\/]/g, '_').slice(0, 200) || 'file';
159
+ const ascii = raw.replace(/[^\x20-\x7e]/g, '_');
160
+ return `${inline ? 'inline' : 'attachment'}; filename="${ascii}"; filename*=UTF-8''${encodeURIComponent(raw)}`;
161
+ }