domma-cms 1.47.5 → 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.
Files changed (44) hide show
  1. package/CHANGELOG.md +13 -0
  2. package/CLAUDE.md +4 -0
  3. package/admin/js/api.js +1 -1
  4. package/admin/js/lib/api-tokens-arrange.js +3 -3
  5. package/admin/js/templates/api-tokens.html +16 -0
  6. package/admin/js/views/api-tokens.js +33 -6
  7. package/admin/js/views/page-editor.js +9 -9
  8. package/docs/DommaFeatures.md +2 -0
  9. package/docs/api-reference.md +97 -2
  10. package/docs/plugin-development.md +27 -1
  11. package/package.json +1 -1
  12. package/plugins/free-tier.lock.json +13 -11
  13. package/plugins/shopping-cart/CHANGELOG.md +6 -0
  14. package/plugins/shopping-cart/CLAUDE.md +7 -1
  15. package/plugins/shopping-cart/lib/render.js +16 -3
  16. package/plugins/shopping-cart/plugin.js +15 -3
  17. package/plugins/shopping-cart/plugin.json +1 -1
  18. package/plugins/shopping-cart/public/cart.js +17 -1
  19. package/plugins/shopping-cart/public/lib/orders.js +23 -0
  20. package/plugins/shopping-cart/public/shop.css +3 -1
  21. package/plugins/shopping-cart/tests/account-scope.test.js +102 -0
  22. package/plugins/shopping-cart/tests/accounts.test.js +1 -1
  23. package/plugins/shopping-cart/tests/checkout-wording.test.js +58 -0
  24. package/public/js/site.js +1 -1
  25. package/public/js/token-handover-page.mjs +2 -0
  26. package/public/js/token-handover.mjs +13 -0
  27. package/server/routes/api/api-tokens.js +116 -4
  28. package/server/routes/api/collections.js +69 -0
  29. package/server/routes/api/content-writes.js +334 -0
  30. package/server/routes/api/pages.js +21 -1
  31. package/server/routes/public.js +15 -0
  32. package/server/routes/token-handover-public.js +59 -0
  33. package/server/server.js +6 -0
  34. package/server/services/apiTokens.js +61 -16
  35. package/server/services/content.js +4 -2
  36. package/server/services/markdown.js +10 -10
  37. package/server/services/pluginScope.js +26 -0
  38. package/server/services/plugins.js +3 -2
  39. package/server/services/siteGitignore.js +2 -0
  40. package/server/services/tokenContentPolicy.js +369 -0
  41. package/server/services/tokenHandovers.js +143 -0
  42. package/server/services/tokenRecipes.js +207 -0
  43. package/server/templates/page.html +1 -1
  44. package/server/templates/token-handover.html +3 -0
@@ -0,0 +1,143 @@
1
+ /**
2
+ * Token handovers - a one-time link that carries a new API token to the
3
+ * person or bot it is for, so the token itself is never pasted into an email
4
+ * or a chat.
5
+ *
6
+ * The server never sees the token. The admin's browser encrypts the
7
+ * connection details (token included) with a random AES-GCM key and sends
8
+ * only the ciphertext here. The key travels in the link's #fragment, which
9
+ * browsers never send to a server, so what is stored in
10
+ * content/token-handovers.json is useless on its own - a copy of the file, a
11
+ * backup or a log line gives nobody the token.
12
+ *
13
+ * A handover opens ONCE (the record is deleted as it is read) and only within
14
+ * its lifetime (24 hours at most). It also dies with its token: revoked or
15
+ * switched off, the link opens nothing.
16
+ */
17
+ import fs from 'node:fs/promises';
18
+ import path from 'node:path';
19
+ import crypto from 'node:crypto';
20
+ import {config} from '../config.js';
21
+
22
+ const STORE_PATH = () => path.join(config.content.contentDir, 'token-handovers.json');
23
+
24
+ export const HANDOVER_PATH = '/_token-handover';
25
+ export const DEFAULT_LIFETIME_MS = 24 * 3_600_000;
26
+ /** The longest a handover link lives - the same as the default: a link is for now, not for later. */
27
+ export const MAX_LIFETIME_MS = DEFAULT_LIFETIME_MS;
28
+ /** A connection file is well under 2 KB; the cap only stops the store being used as a dump. */
29
+ export const MAX_CIPHERTEXT = 16_384;
30
+ const B64URL = /^[A-Za-z0-9_-]+$/;
31
+ const ID_RE = /^[A-Za-z0-9_-]{32}$/;
32
+
33
+ /** Serialises reads-then-writes, so one link can never be opened twice at once. */
34
+ let chain = Promise.resolve();
35
+ function locked(fn) {
36
+ const run = chain.then(fn, fn);
37
+ chain = run.catch(() => {});
38
+ return run;
39
+ }
40
+
41
+ async function readStore() {
42
+ try {
43
+ const parsed = JSON.parse(await fs.readFile(STORE_PATH(), 'utf8'));
44
+ return Array.isArray(parsed) ? parsed : [];
45
+ } catch {
46
+ return [];
47
+ }
48
+ }
49
+
50
+ async function writeStore(rows, now = Date.now()) {
51
+ const kept = rows.filter(r => Date.parse(r.expiresAt) > now);
52
+ await fs.mkdir(path.dirname(STORE_PATH()), {recursive: true});
53
+ const tmp = `${STORE_PATH()}.${process.pid}.tmp`;
54
+ await fs.writeFile(tmp, JSON.stringify(kept, null, 2), {encoding: 'utf8', mode: 0o600});
55
+ await fs.rename(tmp, STORE_PATH());
56
+ }
57
+
58
+ /**
59
+ * Check what the browser sent. Pure.
60
+ *
61
+ * @param {{ciphertext?: unknown, iv?: unknown, lifetimeHours?: unknown}} body
62
+ * @returns {{ok: true, ciphertext: string, iv: string, lifetimeMs: number} | {ok: false, error: string}}
63
+ */
64
+ export function checkHandoverInput(body) {
65
+ const {ciphertext, iv, lifetimeHours} = body || {};
66
+ if (typeof ciphertext !== 'string' || !ciphertext || !B64URL.test(ciphertext)) return {ok: false, error: 'ciphertext must be base64url'};
67
+ if (ciphertext.length > MAX_CIPHERTEXT) return {ok: false, error: 'ciphertext is too large'};
68
+ if (typeof iv !== 'string' || !B64URL.test(iv) || iv.length !== 16) return {ok: false, error: 'iv must be 12 bytes, base64url'};
69
+ let lifetimeMs = DEFAULT_LIFETIME_MS;
70
+ if (lifetimeHours != null) {
71
+ const h = Number(lifetimeHours);
72
+ if (!Number.isFinite(h) || h <= 0) return {ok: false, error: 'lifetimeHours must be a positive number'};
73
+ lifetimeMs = Math.min(Math.round(h * 3_600_000), MAX_LIFETIME_MS);
74
+ }
75
+ return {ok: true, ciphertext, iv, lifetimeMs};
76
+ }
77
+
78
+ /**
79
+ * Store a handover for a token. The caller has already checked the token
80
+ * exists and that the admin may see it.
81
+ *
82
+ * @param {{tokenId: string, ciphertext: string, iv: string, lifetimeMs?: number, createdBy?: string|null}} input
83
+ * @returns {Promise<{id: string, expiresAt: string}>}
84
+ */
85
+ export function createHandover({tokenId, ciphertext, iv, lifetimeMs = DEFAULT_LIFETIME_MS, createdBy = null}, now = Date.now()) {
86
+ return locked(async () => {
87
+ const id = crypto.randomBytes(24).toString('base64url');
88
+ const expiresAt = new Date(now + lifetimeMs).toISOString();
89
+ const rows = await readStore();
90
+ rows.push({id, tokenId, ciphertext, iv, expiresAt, createdAt: new Date(now).toISOString(), createdBy});
91
+ await writeStore(rows, now);
92
+ return {id, expiresAt};
93
+ });
94
+ }
95
+
96
+ /**
97
+ * Open a handover: answer its ciphertext and delete it, so it can never be
98
+ * read again. Null when it does not exist, has expired, or its token is no
99
+ * longer usable (`tokenUsable(tokenId)` false) - the record goes either way.
100
+ *
101
+ * @param {string} id
102
+ * @param {(tokenId: string) => Promise<boolean>} tokenUsable
103
+ * @returns {Promise<{ciphertext: string, iv: string, expiresAt: string} | null>}
104
+ */
105
+ export function openHandover(id, tokenUsable, now = Date.now()) {
106
+ if (typeof id !== 'string' || !ID_RE.test(id)) return Promise.resolve(null);
107
+ return locked(async () => {
108
+ const rows = await readStore();
109
+ const row = rows.find(r => r.id === id);
110
+ if (!row) return null;
111
+ await writeStore(rows.filter(r => r !== row), now);
112
+ if (!(Date.parse(row.expiresAt) > now)) return null;
113
+ if (!(await tokenUsable(row.tokenId))) return null;
114
+ return {ciphertext: row.ciphertext, iv: row.iv, expiresAt: row.expiresAt};
115
+ });
116
+ }
117
+
118
+ /**
119
+ * Drop every handover of a token (on revoke). Not required for safety -
120
+ * openHandover() refuses a dead token - but it keeps the store honest.
121
+ *
122
+ * @param {string} tokenId
123
+ */
124
+ export function dropHandoversFor(tokenId) {
125
+ return locked(async () => {
126
+ const rows = await readStore();
127
+ const kept = rows.filter(r => r.tokenId !== tokenId);
128
+ if (kept.length !== rows.length) await writeStore(kept);
129
+ });
130
+ }
131
+
132
+ /**
133
+ * How many unopened handovers a token has, and when the last one expires -
134
+ * for the admin list. Never returns ids (an id plus the key is the token).
135
+ *
136
+ * @param {string} tokenId
137
+ * @returns {Promise<{pending: number, until: string|null}>}
138
+ */
139
+ export async function handoverStatus(tokenId, now = Date.now()) {
140
+ const rows = (await readStore()).filter(r => r.tokenId === tokenId && Date.parse(r.expiresAt) > now);
141
+ const until = rows.map(r => r.expiresAt).sort().at(-1) || null;
142
+ return {pending: rows.length, until};
143
+ }
@@ -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>