domma-cms 1.47.2 → 1.47.4
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.
- package/CHANGELOG.md +10 -0
- package/admin/js/lib/form-submissions-arrange.js +1 -1
- package/admin/js/lib/private-files.js +1 -0
- package/admin/js/templates/docs/api-forms.html +10 -1
- package/admin/js/templates/docs/tutorial-forms.html +6 -0
- package/admin/js/views/collection-entries.js +7 -7
- package/admin/js/views/form-submissions.js +2 -2
- package/docs/DommaFeatures.md +44 -6
- package/package.json +1 -1
- package/plugins/free-tier.lock.json +9 -9
- package/plugins/shopping-cart/CHANGELOG.md +4 -0
- package/plugins/shopping-cart/CLAUDE.md +3 -0
- package/plugins/shopping-cart/admin/views/products.js +2 -2
- package/plugins/shopping-cart/plugin.json +1 -1
- package/plugins/shopping-cart/public/lib/products.js +14 -0
- package/plugins/shopping-cart/public/shop.css +21 -2
- package/plugins/shopping-cart/tests/pure.test.js +12 -1
- package/public/js/form-answers.mjs +1 -0
- package/server/routes/api/forms.js +161 -16
- package/server/server.js +15 -1
- package/server/services/email.js +30 -11
- package/server/services/form-uploads-migration.js +254 -0
- package/server/services/formUploads.js +161 -0
- package/server/services/markdown.js +3 -1
|
@@ -194,6 +194,20 @@ export function priceRange(product) {
|
|
|
194
194
|
return {min: Math.min(...prices), max: Math.max(...prices)};
|
|
195
195
|
}
|
|
196
196
|
|
|
197
|
+
/**
|
|
198
|
+
* How many options a product has, for the admin's product list: "Size: 2
|
|
199
|
+
* options", or "2 options" when the option has no name of its own. The name is
|
|
200
|
+
* shown as typed and never pluralised - owners write "Size" as often as "Sizes"
|
|
201
|
+
* or "Units", and adding an "s" gave "2 unitss". '' when there are none.
|
|
202
|
+
*/
|
|
203
|
+
export function optionsText(product) {
|
|
204
|
+
const count = product?.variants?.length || 0;
|
|
205
|
+
if (!count) return '';
|
|
206
|
+
const counted = `${count} ${count === 1 ? 'option' : 'options'}`;
|
|
207
|
+
const name = String(product.optionName || '').trim();
|
|
208
|
+
return !name || /^options?$/i.test(name) ? counted : `${name}: ${counted}`;
|
|
209
|
+
}
|
|
210
|
+
|
|
197
211
|
/**
|
|
198
212
|
* The fields a shopper may see. Never the cost of anything internal: no
|
|
199
213
|
* position, no SKU-level stock numbers beyond "how many can I buy".
|
|
@@ -14,7 +14,11 @@
|
|
|
14
14
|
|
|
15
15
|
body {
|
|
16
16
|
--shop-accent: var(--dm-primary, #4f46e5);
|
|
17
|
-
|
|
17
|
+
/* Text on the accent: the theme's own on-primary colour (every Domma theme
|
|
18
|
+
sets --dm-primary-text - dark on a pale primary, white on a deep one).
|
|
19
|
+
A theme without it gets the browser's contrast pick where it has
|
|
20
|
+
contrast-color() (the @supports below), else white. */
|
|
21
|
+
--shop-accent-ink: var(--dm-primary-text, #fff);
|
|
18
22
|
--shop-bg: var(--dm-surface, #fff);
|
|
19
23
|
--shop-page: var(--dm-background, var(--shop-bg));
|
|
20
24
|
--shop-text: var(--dm-text, #16181d);
|
|
@@ -31,6 +35,9 @@ body {
|
|
|
31
35
|
--shop-shadow-lift: 0 2px 4px rgba(0, 0, 0, .06), 0 18px 40px -16px rgba(0, 0, 0, .35);
|
|
32
36
|
--shop-ease: cubic-bezier(.2, .8, .2, 1);
|
|
33
37
|
}
|
|
38
|
+
@supports (color: contrast-color(red)) {
|
|
39
|
+
body { --shop-accent-ink: var(--dm-primary-text, contrast-color(var(--shop-accent))); }
|
|
40
|
+
}
|
|
34
41
|
|
|
35
42
|
.shop-page { padding-top: 1.5rem; padding-bottom: 4rem; color: var(--shop-text); }
|
|
36
43
|
.shop-page h1, .shop-page h2, .shop-page h3 { color: var(--shop-text); }
|
|
@@ -411,7 +418,19 @@ html.shop-locked { overflow: hidden; }
|
|
|
411
418
|
.shop-page .shop-qty input, .shop-drawer .shop-qty input, .shop-search input {
|
|
412
419
|
background: transparent !important; border: 0 !important; box-shadow: none !important; outline: 0; padding-left: 0; padding-right: 0; margin: 0; min-height: 0; }
|
|
413
420
|
.shop-card-title a, .shop-card-title a:hover, .shop-line-name, .shop-crumbs a, .shop-quick { text-decoration: none !important; }
|
|
414
|
-
.shop-r-get, .shop-r-get:hover, .shop-r-get:visited {
|
|
421
|
+
.shop-r-get, .shop-r-get:hover, .shop-r-get:visited { text-decoration: none !important; }
|
|
422
|
+
/* Links drawn as buttons keep the ink. The CMS's site.css colours every content
|
|
423
|
+
link with `html body .page-body a[href]:not(...)` + !important (specificity
|
|
424
|
+
0,8,5), which turned these into primary text on a primary button - the
|
|
425
|
+
receipt's washed-out Download. An !important declaration in a cascade layer
|
|
426
|
+
beats every unlayered !important one whatever its specificity, so this is
|
|
427
|
+
the one place that wins without a selector arms race. */
|
|
428
|
+
@layer shop-ink {
|
|
429
|
+
.shop-r-get, .shop-r-get:hover, .shop-r-get:visited,
|
|
430
|
+
.shop-buy-button, .shop-buy-button:hover, .shop-buy-button:visited,
|
|
431
|
+
.shop-quick.is-link:hover, .shop-quick.is-link:focus-visible { color: var(--shop-accent-ink) !important; }
|
|
432
|
+
.shop-quick.is-link { color: var(--shop-text) !important; }
|
|
433
|
+
}
|
|
415
434
|
.shop-card-title a:hover { color: var(--shop-accent); }
|
|
416
435
|
|
|
417
436
|
@media (max-width: 640px) {
|
|
@@ -2,7 +2,7 @@ import {test} from 'node:test';
|
|
|
2
2
|
import assert from 'node:assert/strict';
|
|
3
3
|
import {createHmac} from 'node:crypto';
|
|
4
4
|
import {formatMoney, fromMinor, includedTax, percentOf, toMinor} from '../public/lib/money.js';
|
|
5
|
-
import {available, cleanProduct, priceRange, publicProduct, slugify, unitPrice} from '../public/lib/products.js';
|
|
5
|
+
import {available, cleanProduct, optionsText, priceRange, publicProduct, slugify, unitPrice} from '../public/lib/products.js';
|
|
6
6
|
import {canMove, cleanCheckout} from '../public/lib/orders.js';
|
|
7
7
|
import {cleanCharges, cleanCustomLines, cleanLines, priceBasket} from '../lib/pricing.js';
|
|
8
8
|
import {paypalPaid, stripeCreateSession, stripeForm, stripeLineItems, stripeRefund, stripeSessionPaid, stripeVerify} from '../lib/payments.js';
|
|
@@ -48,6 +48,17 @@ test('products: cleaned, slugged, variants and stock', () => {
|
|
|
48
48
|
assert.deepEqual(cleanProduct({name: 'A', price: 1, images: ['javascript:alert(1)', '/media/a.jpg']}).data.images, ['/media/a.jpg']);
|
|
49
49
|
});
|
|
50
50
|
|
|
51
|
+
test('products: the admin list counts options without pluralising their name', () => {
|
|
52
|
+
const two = [{id: 'a'}, {id: 'b'}];
|
|
53
|
+
assert.equal(optionsText({optionName: 'Units', variants: two}), 'Units: 2 options', 'not "2 unitss"');
|
|
54
|
+
assert.equal(optionsText({optionName: 'Sizes', variants: two}), 'Sizes: 2 options', 'not "2 sizess"');
|
|
55
|
+
assert.equal(optionsText({optionName: 'Size', variants: [{id: 'a'}]}), 'Size: 1 option');
|
|
56
|
+
assert.equal(optionsText({optionName: '', variants: two}), '2 options');
|
|
57
|
+
assert.equal(optionsText({optionName: 'Option', variants: two}), '2 options', 'no "Option: 2 options"');
|
|
58
|
+
assert.equal(optionsText({optionName: 'Size', variants: []}), '');
|
|
59
|
+
assert.equal(optionsText({}), '');
|
|
60
|
+
});
|
|
61
|
+
|
|
51
62
|
test('orders: moves, checkout cleaning', () => {
|
|
52
63
|
assert.ok(canMove('paid', 'fulfilled'));
|
|
53
64
|
assert.ok(!canMove('cancelled', 'paid'));
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{fileRefs as c}from"./form-files.mjs";const b={amp:"&",lt:"<",gt:">",quot:'"',apos:"'",nbsp:" ",pound:"\xA3",euro:"\u20AC",copy:"\xA9",reg:"\xAE"};export function plainLabel(e){return String(e).replace(/<[^>]*>/g,"").replace(/&(#x[0-9a-f]+|#\d+|[a-z]+);/gi,(t,n)=>{if(n[0]==="#"){const r=n[1]==="x"||n[1]==="X"?parseInt(n.slice(2),16):parseInt(n.slice(1),10);return Number.isFinite(r)&&r>31?String.fromCodePoint(r):" "}return b[n.toLowerCase()]??t})}function g(e){const t=Array.isArray(e?.options)?e.options:[],n=e?.logic?.cascade;if(!n)return t;const r=Object.values(n.mapping||{}).filter(Array.isArray).flat();return[...t,...r,...Array.isArray(n.defaultOptions)?n.defaultOptions:[]]}function a(e,t){const n=String(t);for(const r of e)if(r&&typeof r=="object"){if(r.value!==void 0&&String(r.value)===n)return plainLabel(r.label!=null&&r.label!==""?r.label:r.value)}else if(r!=null&&String(r)===n)return plainLabel(r)}export function optionLabel(e,t){const n=a(g(e),t);return n===void 0?String(t):n}const A=new Set(["select","multiselect","radio","checkbox-group","chooser"]),x=new Set(["true","on","yes","1"]),h=new Set(["false","off","no","0"]),j=e=>String(e).padStart(2,"0");function p(e){const t=String(e).trim(),n=/^(\d{4})-(\d{2})-(\d{2})(?:[T ](\d{2}):(\d{2})(?::\d{2}(?:\.\d+)?)?)?$/.exec(t);if(!n)return t;const r=`${n[3]}/${n[2]}/${n[1]}`;return n[4]?`${r} ${n[4]}:${n[5]}`:r}function S(e){const t=String(e).trim(),n=/^(\d{1,2}):(\d{2})(?::\d{2}(?:\.\d+)?)?$/.exec(t);return n&&Number(n[1])<24?`${j(n[1])}:${n[2]}`:t}function u(e){if(e==null)return"";if(Array.isArray(e))return e.map(u).filter(Boolean).join(", ");if(typeof e=="boolean")return e?"Yes":"No";const t=c(e);return t.length?t.map(n=>n.name||n.url.split("/").pop()||"file").join(", "):typeof e=="object"?JSON.stringify(e):String(e).trim()}export function answerLabel(e,t){if(t==null||t==="")return"";const n=e&&e.type;if(!n)return u(t);if(n==="file"||c(t).length){const i=c(t);return i.length?i.map(f=>f.name||f.url.split("/").pop()||"file").join(", "):u(t)}if(n==="checkbox"&&!Array.isArray(t)){if(typeof t=="boolean")return t?"Yes":"No";const i=String(t).trim().toLowerCase();return x.has(i)?"Yes":h.has(i)?"No":String(t).trim()}const r=g(e);if(A.has(n)||r.length){const i=Array.isArray(t)?t:[t],f=o=>{if(o==null||o==="")return"";if(typeof o=="object")return u(o);const d=a(r,o);if(d!==void 0)return d;const l=String(o);if(l.includes(",")){const m=l.split(",").map(s=>s.trim()).filter(Boolean),y=m.map(s=>a(r,s));if(m.length&&y.every(s=>s!==void 0))return y.join(", ")}return l.trim()};return i.map(f).filter(Boolean).join(", ")}return n==="date"?Array.isArray(t)?t.map(p).join(", "):p(t):n==="time"?Array.isArray(t)?t.map(S).join(", "):S(t):n==="datetime"||n==="datetime-local"?p(t):u(t)}
|
|
@@ -29,7 +29,7 @@ import {deleteForm, ensureCollectionForForm, ensureFormsDir, listForms, maxSubmi
|
|
|
29
29
|
import {executeAction} from '../../services/actions.js';
|
|
30
30
|
// The same rules the browser draws the buttons by (a Cancel link must be safe).
|
|
31
31
|
import {buttonSettingsProblems, formClassProblems, publicButtonSettings} from '../../../public/js/form-submit.mjs';
|
|
32
|
-
import {cleanUploadName, countRefusal, fileRefusal, submissionTooLarge, fileRules, fileValueText, isFileValue} from '../../../public/js/form-files.mjs';
|
|
32
|
+
import {cleanUploadName, countRefusal, fileRefs, fileRefusal, submissionTooLarge, fileRules, fileValueText, isFileValue} from '../../../public/js/form-files.mjs';
|
|
33
33
|
import {sanitiseCsv} from '../../../public/js/collection-export.mjs';
|
|
34
34
|
import {originOf, trustedOrigin} from '../../services/passwordReset.js';
|
|
35
35
|
import {createTransport, mailFailure, sendFormEmail, TEST_EMAIL_FAILED} from '../../services/email.js';
|
|
@@ -47,9 +47,10 @@ import {
|
|
|
47
47
|
import {getConfig} from '../../config.js';
|
|
48
48
|
import {authenticate, requireAdmin, requirePermission} from '../../middleware/auth.js';
|
|
49
49
|
import {hooks} from '../../services/hooks.js';
|
|
50
|
-
import {parseCookies, SESSION_COOKIE} from '../../services/viewerSession.js';
|
|
50
|
+
import {parseCookies, readSessionToken, SESSION_COOKIE} from '../../services/viewerSession.js';
|
|
51
|
+
import {getUserById} from '../../services/users.js';
|
|
51
52
|
import {pluginDenialFor} from '../../services/collectionAccess.js';
|
|
52
|
-
import {
|
|
53
|
+
import {deleteUpload, disposition, openUpload, parseUploadUrl, saveUpload, servedAs, statUpload, uploadUrl, validParts} from '../../services/formUploads.js';
|
|
53
54
|
import {formMayCollect, servedType} from '../../services/mediaTypes.js';
|
|
54
55
|
import {v4 as uuidv4} from 'uuid';
|
|
55
56
|
import {ago, clip, plural} from '../../services/sidebarBadges.js';
|
|
@@ -252,7 +253,12 @@ function fileFieldsOnly(form, body, pending) {
|
|
|
252
253
|
* Write the files of a submission that passed every check, into the reference objects
|
|
253
254
|
* parseMultipartForm() left in `body`. Only the fields that will be kept are written -
|
|
254
255
|
* nothing a bot, a rate-limited or refused submission or a switched-off field sent
|
|
255
|
-
*
|
|
256
|
+
* is stored.
|
|
257
|
+
*
|
|
258
|
+
* They go to the private store (services/formUploads.js), one folder per submission:
|
|
259
|
+
* content/form-uploads/<form slug>/<upload id>/<8 hex>-<name> - never content/media/,
|
|
260
|
+
* so no visitor's file is public or in the Media library. Each reference's url is the
|
|
261
|
+
* admin-only route that serves it.
|
|
256
262
|
*
|
|
257
263
|
* If one cannot be written, the ones already written for this submission are removed
|
|
258
264
|
* and the error is thrown - a submission keeps all its files or none.
|
|
@@ -260,10 +266,12 @@ function fileFieldsOnly(form, body, pending) {
|
|
|
260
266
|
* @param {Map<string, {buffer: Buffer, filename: string}[]>} pending
|
|
261
267
|
* @param {object} body
|
|
262
268
|
* @param {Set<string>} keep - field names the submission keeps
|
|
263
|
-
* @
|
|
269
|
+
* @param {string} slug - the form's
|
|
270
|
+
* @returns {Promise<{slug: string, id: string, name: string}[]>} what was written (for removeFormFiles)
|
|
264
271
|
*/
|
|
265
|
-
async function saveFormFiles(pending, body, keep) {
|
|
272
|
+
async function saveFormFiles(pending, body, keep, slug) {
|
|
266
273
|
const written = [];
|
|
274
|
+
const uploadId = uuidv4();
|
|
267
275
|
try {
|
|
268
276
|
for (const [name, files] of pending) {
|
|
269
277
|
if (!keep.has(name)) {
|
|
@@ -272,8 +280,8 @@ async function saveFormFiles(pending, body, keep) {
|
|
|
272
280
|
}
|
|
273
281
|
const refs = Array.isArray(body[name]) ? body[name] : [body[name]];
|
|
274
282
|
for (let i = 0; i < files.length; i++) {
|
|
275
|
-
const saved = await
|
|
276
|
-
written.push(saved
|
|
283
|
+
const saved = await saveNewUpload(slug, uploadId, files[i]);
|
|
284
|
+
written.push(saved);
|
|
277
285
|
refs[i].url = saved.url;
|
|
278
286
|
}
|
|
279
287
|
}
|
|
@@ -288,10 +296,10 @@ async function saveFormFiles(pending, body, keep) {
|
|
|
288
296
|
* Write one visitor file under a new name. Never over another file: a clash of the random
|
|
289
297
|
* prefix picks another, and a write that fails part way removes what it wrote.
|
|
290
298
|
*/
|
|
291
|
-
async function
|
|
299
|
+
async function saveNewUpload(slug, uploadId, file) {
|
|
292
300
|
for (let tries = 0; ; tries++) {
|
|
293
301
|
try {
|
|
294
|
-
return await
|
|
302
|
+
return await saveUpload(slug, uploadId, safeFilename(file.filename), file.buffer);
|
|
295
303
|
} catch (err) {
|
|
296
304
|
if (err.code !== 'EEXIST' || tries >= 4) throw err;
|
|
297
305
|
}
|
|
@@ -299,9 +307,71 @@ async function saveNewMedia(file) {
|
|
|
299
307
|
}
|
|
300
308
|
|
|
301
309
|
/** Remove a submission's written files again (it was not stored after all). Never throws. */
|
|
302
|
-
async function removeFormFiles(
|
|
303
|
-
for (const
|
|
304
|
-
try { await
|
|
310
|
+
async function removeFormFiles(written) {
|
|
311
|
+
for (const f of written || []) {
|
|
312
|
+
try { await deleteUpload(f.slug, f.id, f.name); } catch { /* already gone */ }
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
/**
|
|
317
|
+
* The files a form saved for one submission: the references in its file fields
|
|
318
|
+
* to the private store (services/formUploads.js) under THIS form's slug.
|
|
319
|
+
* Nothing else is ever the form's to delete - not another address, a path,
|
|
320
|
+
* another form's folder, a field the form does not define as a file field,
|
|
321
|
+
* and never anything under /media/. A /media/ reference may be an old upload
|
|
322
|
+
* (form-uploads-migration.js moves the real ones into the store at boot) or a
|
|
323
|
+
* reference planted through a public create, a token or an editor pointing at
|
|
324
|
+
* a file a page uses, so it is left alone. Each name is checked again at the
|
|
325
|
+
* file (fileIn, in deleteUpload), so a tampered reference never reaches outside
|
|
326
|
+
* the store.
|
|
327
|
+
*
|
|
328
|
+
* @param {object} form
|
|
329
|
+
* @param {object} entry
|
|
330
|
+
* @returns {{url: string, slug: string, id: string, name: string}[]}
|
|
331
|
+
*/
|
|
332
|
+
export function submissionUploads(form, entry) {
|
|
333
|
+
const out = new Map();
|
|
334
|
+
for (const f of form?.fields || []) {
|
|
335
|
+
if (!f || f.type !== 'file' || !f.name) continue;
|
|
336
|
+
for (const ref of fileRefs(entry?.data?.[f.name])) {
|
|
337
|
+
const up = parseUploadUrl(ref.url);
|
|
338
|
+
if (!up || up.slug !== form.slug) continue;
|
|
339
|
+
out.set(ref.url, {url: ref.url, ...up});
|
|
340
|
+
}
|
|
341
|
+
}
|
|
342
|
+
return [...out.values()];
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
/**
|
|
346
|
+
* After submissions are deleted, delete the files the form saved for them - but
|
|
347
|
+
* not a file another entry left in the collection still links to (an imported
|
|
348
|
+
* or copied entry). If the rest of the collection cannot be read, the files stay:
|
|
349
|
+
* an orphaned upload is better than a broken link. Never throws.
|
|
350
|
+
*
|
|
351
|
+
* @param {object} form
|
|
352
|
+
* @param {object[]} removed - the entries that were deleted
|
|
353
|
+
* @param {{warn: Function}} [log]
|
|
354
|
+
*/
|
|
355
|
+
async function removeSubmissionUploads(form, removed, log = console) {
|
|
356
|
+
const files = new Map((removed || []).flatMap(e => submissionUploads(form, e)).map(u => [u.url, u]));
|
|
357
|
+
if (!files.size) return;
|
|
358
|
+
try {
|
|
359
|
+
const left = await listEntries(submissionsCollectionFor(form), {limit: 0});
|
|
360
|
+
for (const e of left.entries || []) {
|
|
361
|
+
for (const v of Object.values(e?.data || {})) {
|
|
362
|
+
for (const ref of fileRefs(v)) files.delete(ref.url);
|
|
363
|
+
}
|
|
364
|
+
}
|
|
365
|
+
} catch (err) {
|
|
366
|
+
log.warn(`[forms] Kept the files of deleted "${form?.slug}" submissions: the collection could not be read (${err.message})`);
|
|
367
|
+
return;
|
|
368
|
+
}
|
|
369
|
+
for (const up of files.values()) {
|
|
370
|
+
try {
|
|
371
|
+
await deleteUpload(up.slug, up.id, up.name);
|
|
372
|
+
} catch (err) {
|
|
373
|
+
log.warn(`[forms] Could not delete the upload "${up.name}" of a "${form?.slug}" submission: ${err.message}`);
|
|
374
|
+
}
|
|
305
375
|
}
|
|
306
376
|
}
|
|
307
377
|
|
|
@@ -819,17 +889,23 @@ export async function formsRoutes(fastify) {
|
|
|
819
889
|
if (!(await canSeeForm(request.user, form))) return reply.status(404).send({ error: 'Form not found.' });
|
|
820
890
|
if (await refusedPluginTarget(request, reply, form)) return;
|
|
821
891
|
const target = submissionsCollectionFor(form);
|
|
892
|
+
const removed = [];
|
|
822
893
|
try {
|
|
823
894
|
// Its own collection: clear it. A shared one: delete only this form's
|
|
824
895
|
// entries (one at a time - parallel writes to a file collection lose updates).
|
|
896
|
+
const mine = await submissionsOf(form);
|
|
825
897
|
if (target === form.slug) {
|
|
826
898
|
await clearEntries(target);
|
|
899
|
+
removed.push(...mine);
|
|
827
900
|
} else {
|
|
828
|
-
for (const e of
|
|
901
|
+
for (const e of mine) { await deleteEntry(target, e.id); removed.push(e); }
|
|
829
902
|
}
|
|
830
903
|
} catch {
|
|
904
|
+
await removeSubmissionUploads(form, removed, fastify.log);
|
|
831
905
|
return reply.status(404).send({ error: 'Collection not found for this form.' });
|
|
832
906
|
}
|
|
907
|
+
// Their uploads go with them (only the files the form saved for them).
|
|
908
|
+
await removeSubmissionUploads(form, removed, fastify.log);
|
|
833
909
|
forgetStats(slug);
|
|
834
910
|
return { ok: true };
|
|
835
911
|
});
|
|
@@ -850,16 +926,85 @@ export async function formsRoutes(fastify) {
|
|
|
850
926
|
if (!(await canSeeForm(request.user, form))) return reply.status(404).send({ error: 'Form not found.' });
|
|
851
927
|
if (await refusedPluginTarget(request, reply, form)) return;
|
|
852
928
|
const target = submissionsCollectionFor(form);
|
|
929
|
+
let entry;
|
|
853
930
|
try {
|
|
854
|
-
|
|
931
|
+
entry = await getEntry(target, id);
|
|
932
|
+
if (!isSubmissionOf(form, entry)) return reply.status(404).send({ error: 'Submission not found.' });
|
|
855
933
|
await deleteEntry(target, id);
|
|
856
934
|
} catch {
|
|
857
935
|
return reply.status(404).send({ error: 'Submission not found.' });
|
|
858
936
|
}
|
|
937
|
+
// Its uploads go with it (only the files the form saved for it).
|
|
938
|
+
await removeSubmissionUploads(form, [entry], fastify.log);
|
|
859
939
|
forgetStats(slug);
|
|
860
940
|
return { ok: true };
|
|
861
941
|
});
|
|
862
942
|
|
|
943
|
+
// -----------------------------------------------------------------------
|
|
944
|
+
// GET /forms/:slug/uploads/:id/:name - one visitor upload, to a signed-in
|
|
945
|
+
// user who may read the form's submissions (the inbox's own permission),
|
|
946
|
+
// and only while a submission of this form links to it.
|
|
947
|
+
//
|
|
948
|
+
// Signed in means the Bearer token the admin sends, or - for a link opened
|
|
949
|
+
// from the notification email or the entry screen, which a browser follows
|
|
950
|
+
// with no header - the dm_session cookie login sets (services/viewerSession.js).
|
|
951
|
+
// This is a read with no side effects, the one kind of route that cookie
|
|
952
|
+
// may serve. Sent inline only as PNG, JPEG, GIF, WebP or PDF; anything else
|
|
953
|
+
// is an attachment of type application/octet-stream. Always nosniff,
|
|
954
|
+
// private/no-store, and a CSP under which nothing in the file can run.
|
|
955
|
+
// -----------------------------------------------------------------------
|
|
956
|
+
const signedInForFile = async (request, reply) => {
|
|
957
|
+
if (request.headers.authorization) return authenticate(request, reply);
|
|
958
|
+
let decoded = null;
|
|
959
|
+
const raw = readSessionToken(request);
|
|
960
|
+
if (raw) { try { decoded = fastify.jwt.verify(raw); } catch { decoded = null; } }
|
|
961
|
+
if (!decoded || decoded.type !== 'access') {
|
|
962
|
+
const html = /text\/html/i.test(String(request.headers.accept || ''));
|
|
963
|
+
reply.code(401).header('Cache-Control', 'private, no-store').header('X-Content-Type-Options', 'nosniff');
|
|
964
|
+
if (!html) return reply.send({statusCode: 401, error: 'Unauthorised', message: 'Sign in to view this file.'});
|
|
965
|
+
return reply.type('text/html; charset=utf-8').header('Content-Security-Policy', "default-src 'none'; style-src 'unsafe-inline'")
|
|
966
|
+
.send('<!doctype html><meta charset="utf-8"><title>Sign in to view this file</title>'
|
|
967
|
+
+ '<body style="font-family:sans-serif;max-width:32rem;margin:3rem auto;padding:0 1rem">'
|
|
968
|
+
+ '<h1 style="font-size:1.3rem">Sign in to view this file</h1>'
|
|
969
|
+
+ '<p>Files sent with a form are private. <a href="/admin/">Sign in to the admin</a>, then open this link again.</p>');
|
|
970
|
+
}
|
|
971
|
+
request.user = decoded;
|
|
972
|
+
const user = decoded.id ? await getUserById(decoded.id) : null;
|
|
973
|
+
request.user.projects = Array.isArray(user?.projects) ? user.projects : [];
|
|
974
|
+
};
|
|
975
|
+
|
|
976
|
+
fastify.get('/forms/:slug/uploads/:id/:name', {preHandler: [signedInForFile, requirePermission('collections', 'read')]}, async (request, reply) => {
|
|
977
|
+
const {slug, id, name} = request.params;
|
|
978
|
+
reply.header('X-Content-Type-Options', 'nosniff').header('Cache-Control', 'private, no-store');
|
|
979
|
+
const notFound = () => reply.status(404).send({error: 'File not found.'});
|
|
980
|
+
if (!validParts(slug, id, name)) return notFound();
|
|
981
|
+
let form;
|
|
982
|
+
try { form = await readForm(slug); } catch { return notFound(); }
|
|
983
|
+
if (!(await canSeeForm(request.user, form))) return notFound();
|
|
984
|
+
if (await refusedPluginTarget(request, reply, form)) return;
|
|
985
|
+
const url = uploadUrl(slug, id, name);
|
|
986
|
+
let ref = null;
|
|
987
|
+
try {
|
|
988
|
+
for (const e of await submissionsOf(form)) {
|
|
989
|
+
if (!submissionUploads(form, e).some(u => u.url === url)) continue;
|
|
990
|
+
for (const v of Object.values(e.data || {})) ref = ref || fileRefs(v).find(r => r.url === url) || null;
|
|
991
|
+
break;
|
|
992
|
+
}
|
|
993
|
+
} catch { return notFound(); }
|
|
994
|
+
if (!ref) return notFound();
|
|
995
|
+
const st = await statUpload(slug, id, name);
|
|
996
|
+
if (!st) return notFound();
|
|
997
|
+
const {type, inline} = servedAs(name);
|
|
998
|
+
reply.header('Content-Type', type)
|
|
999
|
+
.header('Content-Length', st.size)
|
|
1000
|
+
.header('Content-Disposition', disposition(inline, ref.name || name))
|
|
1001
|
+
.header('Content-Security-Policy', inline && type === 'application/pdf'
|
|
1002
|
+
? "default-src 'none'; style-src 'unsafe-inline'; img-src 'self' data: blob:; object-src 'self'; frame-ancestors 'none'"
|
|
1003
|
+
: "default-src 'none'; img-src 'self' data:; style-src 'unsafe-inline'; frame-ancestors 'none'; sandbox")
|
|
1004
|
+
.header('Cross-Origin-Resource-Policy', 'same-origin');
|
|
1005
|
+
return reply.send(openUpload(st.file));
|
|
1006
|
+
});
|
|
1007
|
+
|
|
863
1008
|
// -----------------------------------------------------------------------
|
|
864
1009
|
// POST /forms/:slug/submissions/:id/spam - flag or unflag one submission.
|
|
865
1010
|
// Merged server-side (updateEntry replaces `data` wholesale), in the field
|
|
@@ -1034,7 +1179,7 @@ export async function formsRoutes(fastify) {
|
|
|
1034
1179
|
let writtenFiles = [];
|
|
1035
1180
|
if (pendingFiles?.size) {
|
|
1036
1181
|
try {
|
|
1037
|
-
writtenFiles = await saveFormFiles(pendingFiles, body, record ? visibleFieldNames : new Set());
|
|
1182
|
+
writtenFiles = await saveFormFiles(pendingFiles, body, record ? visibleFieldNames : new Set(), slug);
|
|
1038
1183
|
} catch (err) {
|
|
1039
1184
|
fastify.log.warn(`[forms] Saving the files of a "${slug}" submission failed: ${err.message}`);
|
|
1040
1185
|
return reply.status(500).send({error: 'Your files could not be saved, so the submission was not sent. Please try again.'});
|
package/server/server.js
CHANGED
|
@@ -366,6 +366,18 @@ try {
|
|
|
366
366
|
app.log.warn(`[collections] Number-field repair skipped: ${err.message}`);
|
|
367
367
|
}
|
|
368
368
|
|
|
369
|
+
// Visitors' form uploads out of content/media/ into the private store - one-shot, resumable.
|
|
370
|
+
try {
|
|
371
|
+
const {migrateFormUploads} = await import('./services/form-uploads-migration.js');
|
|
372
|
+
const r = await migrateFormUploads();
|
|
373
|
+
if (r.ran && (r.entries || r.missing || r.skipped)) {
|
|
374
|
+
app.log.info(`[forms] Form uploads made private: ${r.entries} submission(s) updated, ${r.moved} file(s) moved, ${r.copied} copied (also used elsewhere, so left in Media), ${r.missing} missing, ${r.skipped} skipped`);
|
|
375
|
+
}
|
|
376
|
+
if (r.pending.length) app.log.warn(`[forms] Form-uploads migration will retry next start for: ${r.pending.slice(0, 20).join(', ')}`);
|
|
377
|
+
} catch (err) {
|
|
378
|
+
app.log.warn(`[forms] Form-uploads migration skipped: ${err.message}`);
|
|
379
|
+
}
|
|
380
|
+
|
|
369
381
|
/*
|
|
370
382
|
* An admin change clears the response cache.
|
|
371
383
|
*
|
|
@@ -492,7 +504,9 @@ app.addHook('onSend', async (request, reply) => {
|
|
|
492
504
|
const url = request.raw.url || '';
|
|
493
505
|
if (!url.startsWith('/api/')) return;
|
|
494
506
|
if (url.startsWith('/api/v1/') || url.startsWith('/api/x/') || url.startsWith('/api/content/v1/')) return;
|
|
495
|
-
|
|
507
|
+
// A route that already said private + no-store (a visitor's form upload) keeps it.
|
|
508
|
+
const own = String(reply.getHeader('cache-control') || '');
|
|
509
|
+
reply.header('Cache-Control', /\bprivate\b/.test(own) && /\bno-store\b/.test(own) ? own : 'no-store, must-revalidate');
|
|
496
510
|
reply.header('Pragma', 'no-cache');
|
|
497
511
|
reply.header('Expires', '0');
|
|
498
512
|
if (RUNNING_CMS_VERSION && request.headers.authorization) reply.header('X-Domma-CMS-Version', RUNNING_CMS_VERSION);
|
package/server/services/email.js
CHANGED
|
@@ -6,6 +6,13 @@ import nodemailer from 'nodemailer';
|
|
|
6
6
|
import {signedOnly} from './codePolicy.js';
|
|
7
7
|
import {normaliseMailHost, resolveMailHost} from './mailHost.js';
|
|
8
8
|
import {fileRefs, fileUrl, fileValueText} from '../../public/js/form-files.mjs';
|
|
9
|
+
import {answerLabel} from '../../public/js/form-answers.mjs';
|
|
10
|
+
|
|
11
|
+
/** Form field types that lay a form out rather than ask anything - no row in the email. */
|
|
12
|
+
const LAYOUT_FIELD_TYPES = new Set(['page-break', 'heading', 'paragraph', 'html', 'divider', 'spacer', 'banner']);
|
|
13
|
+
|
|
14
|
+
/** Text for a plain-text email part: line breaks kept, every other control character a space. */
|
|
15
|
+
const plainText = (s) => String(s ?? '').replace(/\r\n?/g, '\n').replace(/[\u0000-\u0008\u000b-\u001f\u007f]/g, ' ');
|
|
9
16
|
|
|
10
17
|
/**
|
|
11
18
|
* What a person is told when mail could not be sent. The mail server's own
|
|
@@ -283,25 +290,31 @@ export async function sendEmail(transport, {from, fromName, to, subject, html, t
|
|
|
283
290
|
* Send an HTML + plain-text form submission notification email.
|
|
284
291
|
* Builds a generic table of field→value pairs from the submitted data.
|
|
285
292
|
*
|
|
286
|
-
*
|
|
287
|
-
*
|
|
288
|
-
*
|
|
293
|
+
* Each answer reads as the admin's submission screen shows it (answerLabel,
|
|
294
|
+
* public/js/form-answers.mjs): an option's label rather than its stored value,
|
|
295
|
+
* Yes/No for a single checkbox, dd/mm/yyyy dates. A file field's value (one
|
|
296
|
+
* reference, or a list from a `multiple` field) is shown as a link per file,
|
|
297
|
+
* made absolute with `baseUrl` (site.json) when the site has one; the link needs
|
|
298
|
+
* sign-in, which the email says. Files are never attached. Everything a
|
|
299
|
+
* visitor or an author wrote is escaped in the HTML part, and the plain-text
|
|
300
|
+
* part carries no control characters but line breaks.
|
|
289
301
|
*
|
|
290
302
|
* @param {import('nodemailer').Transporter} transport
|
|
291
|
-
* @param {{ from: string, fromName: string, to: string, subject: string, formTitle: string, fields: Array<{name: string, label: string, type?: string}>, data: Record<string, unknown>, baseUrl?: string }} opts
|
|
303
|
+
* @param {{ from: string, fromName: string, to: string, subject: string, formTitle: string, fields: Array<{name: string, label: string, type?: string, options?: object[]}>, data: Record<string, unknown>, baseUrl?: string }} opts
|
|
292
304
|
* @returns {Promise<void>}
|
|
293
305
|
* @throws {Error} If sending the email fails.
|
|
294
306
|
*/
|
|
295
307
|
export async function sendFormEmail(transport, { from, fromName, to, subject, formTitle, fields, data, baseUrl = '' }) {
|
|
308
|
+
const asked = (fields || []).filter(f => f && f.name && !LAYOUT_FIELD_TYPES.has(f.type));
|
|
296
309
|
const isFile = (field) => field.type === 'file' && fileRefs(data[field.name]).length > 0;
|
|
297
310
|
const fileLinks = (val) => fileRefs(val).map((f) => {
|
|
298
311
|
const url = fileUrl(f, baseUrl);
|
|
299
312
|
const name = escapeHtml(f.name || url);
|
|
300
313
|
return /^(https?:\/\/|\/)/i.test(url) ? `<a href="${escapeHtml(url)}">${name}</a>` : name;
|
|
301
314
|
}).join('<br>');
|
|
302
|
-
const rows =
|
|
315
|
+
const rows = asked.map(field => {
|
|
303
316
|
const val = data[field.name] ?? '';
|
|
304
|
-
const safe = isFile(field) ? fileLinks(val) : escapeHtml(
|
|
317
|
+
const safe = isFile(field) ? fileLinks(val) : escapeHtml(plainText(answerLabel(field, val))).replace(/\n/g, '<br>');
|
|
305
318
|
const safeLabel = escapeHtml(field.label || field.name);
|
|
306
319
|
return `
|
|
307
320
|
<tr>
|
|
@@ -310,24 +323,30 @@ export async function sendFormEmail(transport, { from, fromName, to, subject, fo
|
|
|
310
323
|
</tr>`.trim();
|
|
311
324
|
}).join('\n');
|
|
312
325
|
|
|
313
|
-
const plainRows =
|
|
326
|
+
const plainRows = asked.map(field => {
|
|
314
327
|
const val = data[field.name] ?? '';
|
|
315
|
-
|
|
328
|
+
const shown = isFile(field) ? fileValueText(val, {base: baseUrl}) : answerLabel(field, val);
|
|
329
|
+
return `${plainText(field.label || field.name)}: ${plainText(shown)}`;
|
|
316
330
|
}).join('\n');
|
|
317
331
|
|
|
332
|
+
// Visitors' files are private (services/formUploads.js): their links open for a signed-in admin only.
|
|
333
|
+
const hasFiles = asked.some(isFile);
|
|
334
|
+
const FILES_NOTE = 'Files sent with the form are private: sign in to the admin to view them.';
|
|
335
|
+
|
|
318
336
|
const html = `
|
|
319
337
|
<!DOCTYPE html>
|
|
320
338
|
<html>
|
|
321
339
|
<body style="font-family:sans-serif;max-width:640px;margin:0 auto;padding:20px;">
|
|
322
340
|
<h2 style="color:#333;margin-bottom:4px;">New Form Submission</h2>
|
|
323
|
-
<p style="color:#888;margin-top:0;font-size:.9rem;">${escapeHtml(formTitle)}</p>
|
|
341
|
+
<p style="color:#888;margin-top:0;font-size:.9rem;">${escapeHtml(formTitle ?? '')}</p>
|
|
324
342
|
<table style="width:100%;border-collapse:collapse;margin-top:16px;">
|
|
325
343
|
${rows}
|
|
326
|
-
</table
|
|
344
|
+
</table>${hasFiles ? `
|
|
345
|
+
<p style="color:#888;font-size:.85rem;margin-top:12px;">${escapeHtml(FILES_NOTE)}</p>` : ''}
|
|
327
346
|
</body>
|
|
328
347
|
</html>`.trim();
|
|
329
348
|
|
|
330
|
-
const text = `New form submission: ${formTitle}\n\n${plainRows}`;
|
|
349
|
+
const text = `New form submission: ${plainText(formTitle ?? '')}\n\n${plainRows}${hasFiles ? `\n\n${FILES_NOTE}` : ''}`;
|
|
331
350
|
|
|
332
351
|
try {
|
|
333
352
|
const info = await transport.sendMail({
|