domma-cms 1.48.2 → 1.49.0

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.
@@ -55,6 +55,7 @@ import {formMayCollect, servedType} from '../../services/mediaTypes.js';
55
55
  import {v4 as uuidv4} from 'uuid';
56
56
  import {ago, clip, plural} from '../../services/sidebarBadges.js';
57
57
  import {safeFetch} from '../../services/outbound.js';
58
+ import {verifyFormContext} from '../../services/formContext.js';
58
59
 
59
60
  /**
60
61
  * Detect form↔collection mismatches at save time so admins know BEFORE
@@ -538,6 +539,24 @@ async function cachedStats(form, now) {
538
539
  /** A form's submissions changed (sent, deleted, cleared) or the form went: the next badge reads afresh. */
539
540
  const forgetStats = (slug) => { statsCache.delete(slug); };
540
541
 
542
+ /**
543
+ * Delete one submission as the delete route does - its uploads and the submission counts go with it. For plugins
544
+ * through services/formContext.js removeFormEntry (a person's data being erased). True when it was there.
545
+ *
546
+ * @param {string} slug
547
+ * @param {object} entry - the stored entry (already checked to be this form's)
548
+ * @returns {Promise<boolean>}
549
+ */
550
+ export async function removeFormSubmission(slug, entry) {
551
+ const form = await readForm(slug);
552
+ const target = submissionsCollectionFor(form);
553
+ if (!isSubmissionOf(form, entry)) return false;
554
+ await deleteEntry(target, entry.id);
555
+ await removeSubmissionUploads(form, [entry]);
556
+ forgetStats(slug);
557
+ return true;
558
+ }
559
+
541
560
  export function formsBadge(forms = [], now = Date.now()) {
542
561
  const week = forms.reduce((n, f) => n + (f.stats?.week || 0), 0);
543
562
  const today = forms.reduce((n, f) => n + (f.stats?.today || 0), 0);
@@ -1089,13 +1108,33 @@ export async function formsRoutes(fastify) {
1089
1108
  }
1090
1109
  } catch { /* anonymous submission */ }
1091
1110
 
1111
+ // A form shown in an admin panel (public/js/form-embed.js) carries the context a plugin signed for it
1112
+ // (services/formContext.js). It counts only from a request signed in by a Bearer token whose user the token
1113
+ // was signed for, on this form, before it expires - otherwise the submission is refused, never kept without it.
1114
+ // Nothing else the browser sends reaches the entry's meta: `_context` is not a field and is dropped.
1115
+ let context = null;
1116
+ const hasToken = body._context_token !== undefined && body._context_token !== '';
1117
+ const contextToken = typeof body._context_token === 'string' ? body._context_token : '';
1118
+ delete body._context_token;
1119
+ delete body._context;
1120
+ if (hasToken && !contextToken) return reply.status(400).send({ error: 'This form cannot be sent from here.' });
1121
+ if (contextToken) {
1122
+ const bearer = /^Bearer\s+\S+/i.test(String(request.headers.authorization || ''));
1123
+ if (!bearer || !submittingUser) return reply.status(401).send({ error: 'Sign in again to send this form.' });
1124
+ const checked = verifyFormContext(contextToken, {form: slug, userId: submittingUser.id});
1125
+ if (checked.error === 'expired') return reply.status(400).send({ error: 'This form was open too long - close it and open it again.' });
1126
+ if (checked.error) return reply.status(403).send({ error: 'This form cannot be sent from here.' });
1127
+ context = checked.context;
1128
+ }
1129
+
1092
1130
  // Honeypot check - silently accept if filled (bot detected)
1093
1131
  if (settings.honeypot && body._hp) {
1094
1132
  return { ok: true, message: settings.successMessage, redirect: settings.successRedirect || null };
1095
1133
  }
1096
1134
 
1097
- // Timing check - silently accept if submitted too fast (< 2 s, likely a bot)
1098
- if (settings.honeypot && body._t) {
1135
+ // Timing check - silently accept if submitted too fast (< 2 s, likely a bot). Not for a signed-in admin-panel
1136
+ // post with a verified context: a person who answers quickly must not be told "sent" with nothing stored.
1137
+ if (settings.honeypot && body._t && !context) {
1099
1138
  const elapsed = Date.now() - Number(body._t);
1100
1139
  if (!Number.isNaN(elapsed) && elapsed < 2000) {
1101
1140
  return {ok: true, message: settings.successMessage, redirect: settings.successRedirect || null};
@@ -1229,7 +1268,8 @@ export async function formsRoutes(fastify) {
1229
1268
  source: `form:${slug}`,
1230
1269
  createdBy: submittingUser?.id || null,
1231
1270
  excused,
1232
- outcome: ended ? {type: 'ended', trigger: ended.key, field: ended.field} : null
1271
+ outcome: ended ? {type: 'ended', trigger: ended.key, field: ended.field} : null,
1272
+ context
1233
1273
  });
1234
1274
  forgetStats(slug);
1235
1275
  // What a visitor sent is theirs, not the site's content: keep it out of the site repo.
@@ -35,6 +35,7 @@ import {existsSync, readFileSync} from 'node:fs';
35
35
  import {compareVersions, installPlugin} from '../../services/pluginInstaller.js';
36
36
  import {fetchCatalogue, isManaged} from '../../services/managerClient.js';
37
37
  import {packEnvelope, readEnvelope, readManifestFromTarball, tarDirectory} from '../../services/pluginEnvelope.js';
38
+ import {adminAccessFor} from '../../services/adminAccess.js';
38
39
 
39
40
  /**
40
41
  * The version of a plugin currently on disk, or null if the slug is free.
@@ -384,7 +385,17 @@ export async function pluginsRoutes(fastify, opts = {}) {
384
385
 
385
386
  // Return merged admin config (sidebar, routes, views) for enabled plugins
386
387
  fastify.get('/plugins/admin-config', { preHandler: [authenticate] }, async (request) => {
387
- return getAdminPluginConfig(request.user);
388
+ const cfg = await getAdminPluginConfig(request.user);
389
+ // A user their roles confine (role.admin) sees a plugin's screens, not
390
+ // facts about the product: no version, date, author, licence or expiry
391
+ // in its banner (admin/js/lib/plugin-chrome.js).
392
+ if (!adminAccessFor(request.user).adminScope || !cfg?.meta) return cfg;
393
+ const meta = {};
394
+ for (const [view, m] of Object.entries(cfg.meta)) {
395
+ const {version, date, author, licence, expiry, ...rest} = m || {};
396
+ meta[view] = rest;
397
+ }
398
+ return {...cfg, meta};
388
399
  });
389
400
 
390
401
  // ── In-admin code editor (plugins.develop - code execution grade) ──────
@@ -10,9 +10,13 @@
10
10
  * the admin needs a sidebar, and a role without menu-editing rights (a
11
11
  * `candidate`, say) used to get a 403 here and fall back to a hardcoded tree
12
12
  * holding a Menus link they could not open. Items gated by `visibility` are
13
- * dropped on the server, the same way the public navbar drops them; items
14
- * gated by `permission`, and `hidden` items, are dropped by the renderer - it
15
- * needs the hidden ones to know which Tools a menu has hidden.
13
+ * dropped on the server, the same way the public navbar drops them. Items the
14
+ * caller may not use (a permission they lack, a screen outside the scope their
15
+ * roles confine them to) become label-less stubs - redactSidebarMenu() in
16
+ * admin/js/lib/sidebar-grouping.js, the module the renderer filters with, so
17
+ * the two cannot drift. `hidden` items the caller may use still arrive: the
18
+ * renderer needs them to know which Tools a menu has hidden. A confined
19
+ * caller's registered items are only the Tools they may use.
16
20
  *
17
21
  * Auth middlewares are accepted as DI options so tests can supply no-ops.
18
22
  */
@@ -24,6 +28,17 @@ import {isDashboardPro} from '../../services/widgets.js';
24
28
  import {boardName, readPrefs, readSite} from '../../services/dashboardSettings.js';
25
29
  import {frequentProblems, readFrequent, writeFrequent} from '../../services/sidebarFrequent.js';
26
30
  import {sidebarCountRoutes} from './sidebar-counts.js';
31
+ import {adminAccessFor} from '../../services/adminAccess.js';
32
+
33
+ /**
34
+ * The renderer's own placement module (pure). Loaded by path at runtime rather
35
+ * than imported statically: on a child site admin/ is the manager's copy, and
36
+ * an admin/ older than this server - without redactSidebarMenu - must leave
37
+ * the sidebar as it was, not stop the server booting.
38
+ */
39
+ const grouping = await import('../../../admin/js/lib/sidebar-grouping.js')
40
+ .then(m => (typeof m.redactSidebarMenu === 'function' && typeof m.toolsForViewer === 'function' ? m : null))
41
+ .catch(() => null);
27
42
 
28
43
  export const ADMIN_SIDEBAR_SLUG = 'admin-sidebar';
29
44
 
@@ -44,6 +59,17 @@ export async function sidebarRoutes(fastify, opts = {}) {
44
59
  return Array.isArray(next.items) ? {...next, items: relabel(next.items, label)} : next;
45
60
  });
46
61
 
62
+ /**
63
+ * Every enabled Tool's entry this user may see (`visibility`, staff-only),
64
+ * and the ones their renderer is given: the same, less - for a user their
65
+ * roles confine - every Tool they may not use.
66
+ */
67
+ const toolsFor = async (request, access) => {
68
+ const all = await visibleTools(request);
69
+ const delivered = grouping ? grouping.toolsForViewer(all, access.permissions, access.adminScope) : all;
70
+ return {all, delivered};
71
+ };
72
+
47
73
  fastify.get('/sidebar/menu', signedIn, async (request) => {
48
74
  const menu = await getMenu(ADMIN_SIDEBAR_SLUG);
49
75
  if (!menu) return {items: []};
@@ -51,12 +77,27 @@ export async function sidebarRoutes(fastify, opts = {}) {
51
77
  // renderer needs them to place Tools before it drops them. An item
52
78
  // this user may not see (`visibility`) arrives as a label-less hidden
53
79
  // stub for the same reason - see restrictedStub() in menus.js.
54
- const items = withoutHiddenSidebarUrls(filterItemsForUser(menu.items || [], request.user, {keepHidden: true}));
80
+ let items = withoutHiddenSidebarUrls(filterItemsForUser(menu.items || [], request.user, {keepHidden: true}));
55
81
  const label = await dashboardsLabel(request);
56
- return {...menu, items: label ? relabel(items, label) : items};
82
+ if (label) items = relabel(items, label);
83
+ if (grouping) {
84
+ const access = adminAccessFor(request.user);
85
+ const {all} = await toolsFor(request, access);
86
+ items = grouping.redactSidebarMenu(items, {...access, tools: all});
87
+ }
88
+ return {...menu, items};
57
89
  });
58
90
 
59
91
  fastify.get('/sidebar/registered-items', signedIn, async (request) => {
92
+ const access = adminAccessFor(request.user);
93
+ const {all, delivered} = await toolsFor(request, access);
94
+ // The Menus editor and Arrange (`?for=editor`) save the menu, so they need
95
+ // the real Tools - for someone who may change menus, and only then.
96
+ if (request.query?.for === 'editor' && grouping?.canAny(access.permissions, 'menus')) return all;
97
+ return delivered;
98
+ });
99
+
100
+ async function visibleTools(request) {
60
101
  // A Tool that owns `#/` (the fleet manager's Dashboard) registers the entry itself.
61
102
  const boardLabel = await dashboardsLabel(request);
62
103
  return getRegisteredSidebarItems()
@@ -69,7 +110,7 @@ export async function sidebarRoutes(fastify, opts = {}) {
69
110
  .map(entry => Array.isArray(entry.item?.items)
70
111
  ? {...entry, item: {...entry.item, items: filterItemsForUser(entry.item.items, request.user)}}
71
112
  : entry);
72
- });
113
+ }
73
114
 
74
115
  // Each person's own, so it follows them from browser to browser (sidebarFrequent.js).
75
116
  fastify.get('/sidebar/frequent', signedIn, async (request) => readFrequent(request.user));
@@ -0,0 +1,20 @@
1
+ /**
2
+ * What a signed-in user may do in the admin: their permissions (on the union
3
+ * of every role they hold) and the admin scope their roles confine them to
4
+ * (null = the whole admin; see roles.getAdminScope). One function, so
5
+ * /api/auth/permissions - what the browser hides on - and the routes that
6
+ * filter for the caller (the sidebar, the plugin chrome) cannot disagree.
7
+ */
8
+ import {getAdminScope, getPermissionsForRoles} from './roles.js';
9
+ import {getEffectiveRegistry} from './permissionRegistry.js';
10
+ import {getEffectiveRoles} from './userRoles.js';
11
+
12
+ /**
13
+ * @param {object} user - request.user
14
+ * @returns {{roles: string[], permissions: string[], adminScope: {home: string, allow: string[]}|null}}
15
+ */
16
+ export function adminAccessFor(user) {
17
+ const roles = getEffectiveRoles(user);
18
+ const allResources = getEffectiveRegistry().map(r => r.key);
19
+ return {roles, permissions: getPermissionsForRoles(roles, allResources), adminScope: getAdminScope(roles)};
20
+ }
@@ -415,10 +415,11 @@ export async function getEntry(slug, entryId, opts = {}) {
415
415
  * @param {string} [meta.source] - 'admin' | 'api' | 'import' | 'form:{slug}'
416
416
  * @param {string[]} [meta.excused] - required fields this write may leave empty (see validateEntryData)
417
417
  * @param {object} [meta.outcome] - how a form submission ended, stored as meta.outcome
418
+ * @param {object} [meta.context] - a form submission's server-verified context (services/formContext.js), stored as meta.context
418
419
  * @returns {Promise<object>} Created entry
419
420
  * @throws {Error} If validation fails or collection not found
420
421
  */
421
- export async function createEntry(slug, data, { createdBy = null, source = 'admin', excused = [], outcome = null } = {}) {
422
+ export async function createEntry(slug, data, { createdBy = null, source = 'admin', excused = [], outcome = null, context = null } = {}) {
422
423
  const schema = await getCollection(slug);
423
424
  if (!schema) throw new Error(`Collection "${slug}" not found`);
424
425
  data = typedEntryData(schema, data);
@@ -433,7 +434,7 @@ export async function createEntry(slug, data, { createdBy = null, source = 'admi
433
434
  const entry = {
434
435
  id: uuidv4(),
435
436
  data,
436
- meta: { createdAt: now, updatedAt: now, createdBy, source, ...(outcome && {outcome}) }
437
+ meta: { createdAt: now, updatedAt: now, createdBy, source, ...(outcome && {outcome}), ...(context && {context}) }
437
438
  };
438
439
 
439
440
  const adapter = await getAdapter(slug);
@@ -0,0 +1,166 @@
1
+ /**
2
+ * Forms in admin panels - the context a submission is made in, signed by the server, and the entry read back.
3
+ *
4
+ * A plugin shows a Domma Form inside one of its admin panels (public/js/form-embed.js `renderForm`) - the Job Board's
5
+ * right-to-represent step, for example - and needs to know, afterwards, that a given entry was made by THIS user, on
6
+ * THAT form, for THIS record of its own. The browser cannot be trusted with that, so:
7
+ *
8
+ * 1. The plugin's own route signs the context: `signFormContext({form, userId, context})` -> an opaque token
9
+ * (HMAC-SHA256, keyed from JWT_SECRET, domain-separated; expires after `ttlMs`, 30 minutes by default). Signed, NOT
10
+ * secret: the context is base64 JSON the browser can read - never put anything private in it. It can be used more
11
+ * than once while it lasts (each entry carries the same user and context), so a plugin decides which entry counts
12
+ * (the one it is handed and checks, once).
13
+ * 2. The panel renders the form with that token and posts the answers with the user's Bearer token.
14
+ * 3. POST /api/forms/submit/:slug (routes/api/forms.js) accepts a `_context_token` only from a request signed in
15
+ * by an Authorization: Bearer token (never a cookie) whose user is the token's user, for the token's form, before
16
+ * it expires. The verified context is stored as the entry's `meta.context`; nothing the browser sends otherwise
17
+ * reaches `meta` (`_context` is dropped). A bad token refuses the whole submission (400/401/403).
18
+ * An entry edited afterwards (by someone with update rights on the collection) keeps its meta: a plugin that must
19
+ * know the answers are as sent compares `meta.updatedAt` with `meta.createdAt`, or keeps its own copy.
20
+ * 4. The plugin reads the entry back with `readFormEntry(form, entryId)` and checks `meta.createdBy` and
21
+ * `meta.context` against its own records; `removeFormEntry` deletes one and `formEntriesBy` lists one user's
22
+ * (a person's data being erased - also the entries they sent but never used).
23
+ *
24
+ * Context: up to 20 keys (`/^[a-z][a-z0-9_-]{0,39}$/i`), each a string, number or boolean (strings up to 200
25
+ * characters). Anything else is refused when signing.
26
+ *
27
+ * @module services/formContext
28
+ */
29
+ import crypto from 'node:crypto';
30
+ import {readForm} from './forms.js';
31
+ import {getEntry, listEntries} from './collections.js';
32
+ // The forms route's own delete (its uploads and the submission counts go with it). A call-time import: the route imports
33
+ // this module too.
34
+ import {removeFormSubmission} from '../routes/api/forms.js';
35
+
36
+ const TTL_MS = 30 * 60_000;
37
+ const KEY_RE = /^[a-z][a-z0-9_-]{0,39}$/i;
38
+ const SLUG_RE = /^[a-z0-9][a-z0-9-]{0,99}$/;
39
+ const MAX_KEYS = 20;
40
+ /** The longest token signing can make (20 keys of 200 characters, JSON-escaped, base64) is well under this. */
41
+ const MAX_TOKEN = 16000;
42
+
43
+ // Keyed from JWT_SECRET (domain-separated: a context token is never a session token), else per process (tests).
44
+ const KEY = process.env.JWT_SECRET ? `domma-form-context:${process.env.JWT_SECRET}` : crypto.randomBytes(32).toString('hex');
45
+ const mac = (s) => crypto.createHmac('sha256', KEY).update(s).digest('base64url');
46
+
47
+ /**
48
+ * A context as it may be stored: plain keys, scalar values. null when anything is out of shape.
49
+ *
50
+ * @param {object} context
51
+ * @returns {object|null}
52
+ */
53
+ export function cleanContext(context) {
54
+ if (!context || typeof context !== 'object' || Array.isArray(context)) return null;
55
+ const entries = Object.entries(context);
56
+ if (entries.length > MAX_KEYS) return null;
57
+ const out = {};
58
+ for (const [k, v] of entries) {
59
+ if (!KEY_RE.test(k)) return null;
60
+ if (typeof v === 'string') { if (v.length > 200) return null; out[k] = v; }
61
+ else if (typeof v === 'boolean' || (typeof v === 'number' && Number.isFinite(v))) out[k] = v;
62
+ else return null;
63
+ }
64
+ return out;
65
+ }
66
+
67
+ /**
68
+ * Sign a context for one user submitting one form. Server side only - a plugin's route calls it for the signed-in
69
+ * user it is answering.
70
+ *
71
+ * @param {{form: string, userId: string, context: object, ttlMs?: number, now?: number}} o
72
+ * @returns {string} the token
73
+ * @throws {Error} on a bad form slug, user or context
74
+ */
75
+ export function signFormContext({form, userId, context, ttlMs = TTL_MS, now = Date.now()}) {
76
+ if (!SLUG_RE.test(String(form || ''))) throw new Error('signFormContext: a form slug is required');
77
+ if (!userId || typeof userId !== 'string') throw new Error('signFormContext: the user is required');
78
+ const ctx = cleanContext(context);
79
+ if (!ctx) throw new Error('signFormContext: the context must be up to 20 plain keys with string, number or boolean values');
80
+ const body = Buffer.from(JSON.stringify({f: form, u: userId, c: ctx, x: now + Math.max(1000, Math.min(Number(ttlMs) || TTL_MS, 24 * 3600_000))}))
81
+ .toString('base64url');
82
+ return `${body}.${mac(body)}`;
83
+ }
84
+
85
+ /**
86
+ * The context a token carries, if it was signed here, is for this form and this user, and has not expired.
87
+ *
88
+ * @param {string} token
89
+ * @param {{form: string, userId: string, now?: number}} o
90
+ * @returns {{context?: object, error?: string}}
91
+ */
92
+ export function verifyFormContext(token, {form, userId, now = Date.now()}) {
93
+ const s = String(token || '');
94
+ const dot = s.lastIndexOf('.');
95
+ if (dot < 1 || s.length > MAX_TOKEN) return {error: 'bad'};
96
+ const body = s.slice(0, dot);
97
+ const sig = Buffer.from(s.slice(dot + 1));
98
+ const want = Buffer.from(mac(body));
99
+ if (sig.length !== want.length || !crypto.timingSafeEqual(sig, want)) return {error: 'bad'};
100
+ let p;
101
+ try { p = JSON.parse(Buffer.from(body, 'base64url').toString('utf8')); } catch { return {error: 'bad'}; }
102
+ if (p?.f !== form) return {error: 'form'};
103
+ if (!userId || p?.u !== userId) return {error: 'user'};
104
+ if (!(Number(p?.x) > now)) return {error: 'expired'};
105
+ const context = cleanContext(p.c);
106
+ return context ? {context} : {error: 'bad'};
107
+ }
108
+
109
+ /** The collection a form's submissions are stored in (its own, or the one its collection action names). */
110
+ async function targetOf(form) {
111
+ const def = await readForm(form);
112
+ const action = def?.actions?.collection;
113
+ return action?.enabled && action.slug ? action.slug : form;
114
+ }
115
+
116
+ /**
117
+ * One entry of a form, as stored - for a plugin checking what was submitted. null when the form or entry does not
118
+ * exist, or the entry was not made through this form.
119
+ *
120
+ * @param {string} form
121
+ * @param {string} entryId
122
+ * @returns {Promise<{id: string, data: object, meta: object}|null>}
123
+ */
124
+ export async function readFormEntry(form, entryId) {
125
+ if (!SLUG_RE.test(String(form || '')) || !/^[\w-]{1,100}$/.test(String(entryId || ''))) return null;
126
+ try {
127
+ const entry = await getEntry(await targetOf(form), entryId);
128
+ return entry && entry.meta?.source === `form:${form}` ? entry : null;
129
+ } catch {
130
+ return null;
131
+ }
132
+ }
133
+
134
+ /**
135
+ * Delete one entry of a form (a person's data being erased). True when it was there and is gone.
136
+ *
137
+ * @param {string} form
138
+ * @param {string} entryId
139
+ * @returns {Promise<boolean>}
140
+ */
141
+ export async function removeFormEntry(form, entryId) {
142
+ const entry = await readFormEntry(form, entryId);
143
+ if (!entry) return false;
144
+ try {
145
+ return await removeFormSubmission(form, entry);
146
+ } catch {
147
+ return false;
148
+ }
149
+ }
150
+
151
+ /**
152
+ * Every entry one signed-in user made through this form (`meta.createdBy`) - for erasing a person's data.
153
+ *
154
+ * @param {string} form
155
+ * @param {string} userId
156
+ * @returns {Promise<object[]>}
157
+ */
158
+ export async function formEntriesBy(form, userId) {
159
+ if (!SLUG_RE.test(String(form || '')) || !userId) return [];
160
+ try {
161
+ const {entries = []} = await listEntries(await targetOf(form), {limit: 0});
162
+ return entries.filter(e => e.meta?.createdBy === userId && e.meta?.source === `form:${form}`);
163
+ } catch {
164
+ return [];
165
+ }
166
+ }
@@ -188,7 +188,7 @@
188
188
  <script src="/public/js/form-logic-engine.js?v=20261031-forms-reduce-motion" defer></script>
189
189
 
190
190
  <!-- Site initialisation -->
191
- <script src="/public/js/site.js?v=20261108-safe-goto-2" type="module"></script>
191
+ <script src="/public/js/site.js?v=20261109-form-embed" type="module"></script>
192
192
  <script src="/public/js/collection-context.js?v=20261010-utf8-payloads" type="module"></script>
193
193
  {{ctxMenusModule}}
194
194
  <!-- [image zoom] pictures' full-size view - only on a page that has one -->
@@ -200,7 +200,7 @@
200
200
  <script src="/public/js/menu-float.js?v=20260927-float" type="module"></script>
201
201
 
202
202
  <!-- Core Forms renderer -->
203
- <script src="/public/js/forms.js?v=20261031-form-entrance-forms" type="module"></script>
203
+ <script src="/public/js/forms.js?v=20261109-form-embed" type="module"></script>
204
204
 
205
205
  <!-- Core effects runtime -->
206
206
  <script src="/public/js/effects.js?v=20261029-all-cms-fonts" defer></script>