domma-cms 1.47.6 → 1.48.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.
@@ -0,0 +1,207 @@
1
+ /**
2
+ * "Bot that writes drafts" - the API token recipe.
3
+ *
4
+ * A bot (Grok, a script, another site) that writes content for a person needs
5
+ * three things to line up, and before this they were three screens apart:
6
+ * a token scoped to the collections it writes, Drafts only on that token, and
7
+ * each collection's API verbs open in token mode. This module decides all of it
8
+ * in one place:
9
+ *
10
+ * recipeCollections() - what the New token screen offers, and why some are not
11
+ * planRecipe() - pure: per collection, what would change (or why not)
12
+ * applyRecipe() - writes the collection changes the plan made
13
+ *
14
+ * Collection changes are only ever widening to TOKEN mode from OFF. A verb that
15
+ * is already open to anyone (public, a role) is left exactly as it is and the
16
+ * plan says so - the recipe never narrows what a site already allows, and never
17
+ * hands the public something it did not have.
18
+ *
19
+ * Drafts only needs a draft status. A collection without one can have it added:
20
+ * a `status` select (draft / published, default published). Existing entries are
21
+ * not touched - they have no status and stay as they are; only what the bot writes
22
+ * is a draft. Displays of such a collection show every entry they always did, so
23
+ * the plan warns that a display should filter on `where_status="published"` to
24
+ * keep the bot's drafts off the page.
25
+ */
26
+ import {getCollection, listCollections, updateCollection} from './collections.js';
27
+ import {PRESET_COLLECTION_SLUGS} from './presetCollections.js';
28
+ import {pluginDenial} from './collectionAccess.js';
29
+ import {resolveArtefactProject} from './projects.js';
30
+ import {draftField, listTokensSanitised, scopeAllows} from './apiTokens.js';
31
+ import {ensureFormForCollection} from './forms.js';
32
+
33
+ export const RECIPE_VERBS = Object.freeze(['create', 'update']);
34
+
35
+ /** The status field the recipe adds. Default published, so a person's own new entries are not hidden. */
36
+ export const ADDED_STATUS_FIELD = Object.freeze({
37
+ name: 'status', label: 'Status', type: 'select', options: ['draft', 'published'], default: 'published'
38
+ });
39
+
40
+ const NEVER = new Set(['roles', 'user-profiles', ...PRESET_COLLECTION_SLUGS]);
41
+
42
+ /**
43
+ * Whether a collection can take part at all, and how its drafts work. Pure.
44
+ *
45
+ * @param {object} schema
46
+ * @returns {{ok: true, drafts: 'has'|'add'} | {ok: false, why: string}}
47
+ */
48
+ export function recipeFit(schema) {
49
+ if (!schema?.slug) return {ok: false, why: 'No such collection.'};
50
+ if (NEVER.has(schema.slug) || schema.systemManaged) return {ok: false, why: 'A built-in collection - a bot may not write to it.'};
51
+ if (draftField(schema)) return {ok: true, drafts: 'has'};
52
+ const status = (schema.fields || []).find(f => f?.name === 'status');
53
+ if (status) return {ok: false, why: 'Its Status field has no draft option, so the bot\'s entries could not be held back.'};
54
+ return {ok: true, drafts: 'add'};
55
+ }
56
+
57
+ /**
58
+ * The plan for one collection: the api block it would end up with and what
59
+ * changed. Pure.
60
+ *
61
+ * @param {object} schema
62
+ * @param {string[]} verbs - from RECIPE_VERBS
63
+ * @param {{addStatus?: boolean}} [opts]
64
+ * @returns {{ok: true, slug: string, api: object, fields: object[]|null, opened: string[], already: string[], left: Array<{verb: string, access: string}>, addsStatus: boolean, warnings: string[]}
65
+ * | {ok: false, slug: string, error: string}}
66
+ */
67
+ export function planRecipe(schema, verbs, {addStatus = false} = {}) {
68
+ const slug = schema?.slug;
69
+ const fit = recipeFit(schema);
70
+ if (!fit.ok) return {ok: false, slug, error: fit.why};
71
+ const bad = (verbs || []).find(v => !RECIPE_VERBS.includes(v));
72
+ if (bad) return {ok: false, slug, error: `A bot recipe may only create or update, not ${bad}.`};
73
+ if (!verbs?.length) return {ok: false, slug, error: 'Choose what the bot may do.'};
74
+ if (fit.drafts === 'add' && !addStatus) {
75
+ return {ok: false, slug, error: 'It has no draft status. Add a Status field so the bot\'s entries can be held as drafts.'};
76
+ }
77
+
78
+ const api = {...(schema.api || {})};
79
+ const opened = [], already = [], left = [];
80
+ for (const verb of verbs) {
81
+ const now = api[verb];
82
+ if (!now?.enabled) { api[verb] = {...(now || {}), enabled: true, access: 'token'}; opened.push(verb); }
83
+ else if (now.access === 'token') already.push(verb);
84
+ else left.push({verb, access: now.access});
85
+ }
86
+ const warnings = [];
87
+ for (const {verb, access} of left) {
88
+ warnings.push(`${verb} is already open to ${access === 'public' ? 'everyone' : `the ${access} role`} - left as it is, so the token's Drafts only does not cover those callers.`);
89
+ }
90
+ const addsStatus = fit.drafts === 'add';
91
+ if (addsStatus) {
92
+ warnings.push('A Status field is added (draft / published). Existing entries are not changed. Pages that show this collection show drafts too unless they filter with where_status="published".');
93
+ }
94
+ if (api.read?.enabled && api.read.access === 'public' && addsStatus) {
95
+ warnings.push('Its public API read returns drafts as well - filter on status, or turn public read off.');
96
+ }
97
+ const fields = addsStatus ? [...(schema.fields || []), {...ADDED_STATUS_FIELD}] : null;
98
+ return {ok: true, slug, api, fields, opened, already, left, addsStatus, warnings};
99
+ }
100
+
101
+ /**
102
+ * The collections a project's bot token could write to, for the New token screen.
103
+ *
104
+ * @param {string} project
105
+ * @param {object} user - the admin; plugin-owned collections they may not manage are left out
106
+ * @returns {Promise<Array<{slug: string, title: string, ok: boolean, drafts?: string, why?: string, hasAuthor: boolean, api: object}>>}
107
+ */
108
+ export async function recipeCollections(project, user) {
109
+ const list = await listCollections();
110
+ const out = [];
111
+ for (const row of list) {
112
+ const schema = await getCollection(row.slug);
113
+ if (!schema || resolveArtefactProject(schema) !== project) continue;
114
+ if (NEVER.has(schema.slug) || schema.systemManaged) continue;
115
+ if (pluginDenial(schema, user)) continue;
116
+ const fit = recipeFit(schema);
117
+ out.push({
118
+ slug: schema.slug,
119
+ title: schema.title || schema.slug,
120
+ ok: fit.ok,
121
+ ...(fit.ok ? {drafts: fit.drafts} : {why: fit.why}),
122
+ hasAuthor: (schema.fields || []).some(f => f?.name === 'authorId'),
123
+ api: {create: schema.api?.create || null, update: schema.api?.update || null}
124
+ });
125
+ }
126
+ return out.sort((a, b) => a.title.localeCompare(b.title));
127
+ }
128
+
129
+ /**
130
+ * Plan a whole recipe against the stored schemas. Refuses (throws) on the first
131
+ * collection that cannot take part, or that is outside the token's project, or
132
+ * whose plugin the admin may not manage - nothing is written in that case.
133
+ *
134
+ * @param {{project: string, collections: Array<{slug: string, verbs: string[], addStatus?: boolean}>, user: object}} input
135
+ * @returns {Promise<object[]>} the per-collection plans
136
+ */
137
+ export async function planRecipeFor({project, collections, user}) {
138
+ if (collections == null || (Array.isArray(collections) && !collections.length)) return [];
139
+ if (!Array.isArray(collections)) throw recipeError('recipe.collections must be a list.');
140
+ const seen = new Set();
141
+ for (const c of collections) {
142
+ if (typeof c?.slug !== 'string' || !c.slug) throw recipeError('Each collection needs its slug.');
143
+ if (seen.has(c.slug)) throw recipeError(`"${c.slug}" is listed twice - list it once with every verb.`);
144
+ seen.add(c.slug);
145
+ }
146
+ const plans = [];
147
+ for (const c of collections) {
148
+ const schema = await getCollection(c.slug);
149
+ if (!schema) throw recipeError(`No collection "${c?.slug}".`);
150
+ if (resolveArtefactProject(schema) !== project) throw recipeError(`"${schema.slug}" is not in the ${project} project, so this token could never use it.`);
151
+ const denial = pluginDenial(schema, user);
152
+ if (denial) throw recipeError(denial, 403);
153
+ const plan = planRecipe(schema, c.verbs, {addStatus: c.addStatus === true});
154
+ if (!plan.ok) throw recipeError(`${schema.title || schema.slug}: ${plan.error}`);
155
+ plans.push({...plan, schema});
156
+ }
157
+ return plans;
158
+ }
159
+
160
+ /**
161
+ * The OTHER tokens a plan would let in. Opening a verb in token mode opens it to
162
+ * every token of the project whose scopes reach the collection - an unscoped one,
163
+ * or one naming the collection without verbs - and those may not be drafts-only.
164
+ * The route refuses until the admin has seen this list and confirmed it.
165
+ *
166
+ * @param {string} project
167
+ * @param {object[]} plans - from planRecipeFor()
168
+ * @returns {Promise<Array<{slug: string, verb: string, tokens: Array<{id: string, name: string, draftsOnly: boolean}>}>>}
169
+ */
170
+ export async function othersLetIn(project, plans) {
171
+ const tokens = (await listTokensSanitised(null, {all: true}))
172
+ .filter(t => t.project === project && t.enabled !== false && !(t.expiresAt && Date.parse(t.expiresAt) <= Date.now()));
173
+ const out = [];
174
+ for (const plan of plans) {
175
+ for (const verb of plan.opened) {
176
+ const who = tokens.filter(t => scopeAllows(t.scopes, plan.slug, verb));
177
+ if (who.length) out.push({slug: plan.slug, verb, tokens: who.map(t => ({id: t.id, name: t.name, draftsOnly: t.draftsOnly === true}))});
178
+ }
179
+ }
180
+ return out;
181
+ }
182
+
183
+ /**
184
+ * Write the plans. The whole schema goes back (updateCollection drops flags such
185
+ * as `bundled` that an update leaves out).
186
+ *
187
+ * @param {object[]} plans - from planRecipeFor()
188
+ * @returns {Promise<Array<{slug: string, opened: string[], already: string[], left: object[], addsStatus: boolean, warnings: string[]}>>}
189
+ */
190
+ export async function applyRecipe(plans) {
191
+ const done = [];
192
+ for (const {schema, slug, api, fields, opened, already, left, addsStatus, warnings} of plans) {
193
+ if (opened.length || addsStatus) {
194
+ const updated = await updateCollection(slug, {...schema, api, ...(fields ? {fields} : {})});
195
+ // As PUT /collections/:slug does: a form linked to the collection gets the new Status field.
196
+ if (addsStatus) { try { await ensureFormForCollection(updated); } catch { /* the save itself succeeded */ } }
197
+ }
198
+ done.push({slug, opened, already, left, addsStatus, warnings});
199
+ }
200
+ return done;
201
+ }
202
+
203
+ function recipeError(message, statusCode = 400) {
204
+ const err = new Error(message);
205
+ err.statusCode = statusCode;
206
+ return err;
207
+ }
@@ -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=20261031-launchers-goto" type="module"></script>
191
+ <script src="/public/js/site.js?v=20261108-safe-goto-2" 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 -->
@@ -0,0 +1,3 @@
1
+ <main class="container dm-token-handover" style="padding: 2rem 0; max-width: 760px;">
2
+ {{body}}
3
+ </main>