domma-cms 1.47.6 → 1.48.1
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 +13 -0
- package/admin/js/api.js +1 -1
- package/admin/js/app.js +7 -6
- package/admin/js/lib/api-tokens-arrange.js +3 -3
- package/admin/js/lib/topbar-notifications.js +4 -4
- package/admin/js/templates/api-tokens.html +16 -0
- package/admin/js/views/api-tokens.js +33 -6
- package/admin/js/views/page-editor.js +9 -9
- package/docs/api-reference.md +97 -2
- package/docs/screenshots/notifications-sidebar.png +0 -0
- package/package.json +1 -1
- package/public/js/site.js +1 -1
- package/public/js/token-handover-page.mjs +2 -0
- package/public/js/token-handover.mjs +13 -0
- package/server/routes/api/api-tokens.js +116 -4
- package/server/routes/api/collections.js +69 -0
- package/server/routes/api/content-writes.js +334 -0
- package/server/routes/api/pages.js +21 -1
- package/server/routes/public.js +15 -0
- package/server/routes/token-handover-public.js +59 -0
- package/server/server.js +6 -0
- package/server/services/apiTokens.js +61 -16
- package/server/services/content.js +4 -2
- package/server/services/markdown.js +10 -10
- package/server/services/siteGitignore.js +2 -0
- package/server/services/tokenContentPolicy.js +369 -0
- package/server/services/tokenHandovers.js +143 -0
- package/server/services/tokenRecipes.js +207 -0
- package/server/templates/page.html +1 -1
- package/server/templates/token-handover.html +3 -0
|
@@ -0,0 +1,334 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Content API writes - pages, media and blocks from an API token (a bot, a
|
|
3
|
+
* script, another site). Registered with prefix /api:
|
|
4
|
+
*
|
|
5
|
+
* POST /api/content/v1/pages {path, frontmatter?, body?} create a page
|
|
6
|
+
* PUT /api/content/v1/pages/<path> {frontmatter?, body?} change one
|
|
7
|
+
* POST /api/content/v1/media multipart, one file upload a picture or PDF
|
|
8
|
+
* POST /api/content/v1/blocks {name, content, css?} create a block
|
|
9
|
+
* PUT /api/content/v1/blocks/:name {content, css?} change one
|
|
10
|
+
*
|
|
11
|
+
* Token ONLY (Authorization: Bearer dcms_…), and only by a scope that names the
|
|
12
|
+
* verb: `{content: 'pages', verbs: ['create', 'update']}`. A scope without verbs
|
|
13
|
+
* reads, a token without scopes writes nothing (services/apiTokens.js
|
|
14
|
+
* contentScopeAllows). The site's Content API switch is about reading and does
|
|
15
|
+
* not gate these; the token is the opt-in.
|
|
16
|
+
*
|
|
17
|
+
* Drafts only (the token's flag) on each kind:
|
|
18
|
+
* pages - created as `status: draft` whatever was sent; only a draft can be
|
|
19
|
+
* changed, and it stays one. The person publishes it in the editor.
|
|
20
|
+
* media - has no draft state: a file is public at /media/<name> once it is
|
|
21
|
+
* uploaded (unlinked until a page uses it). Never over another file.
|
|
22
|
+
* blocks - a block is live wherever it is used, so a drafts-only token may
|
|
23
|
+
* only CREATE new blocks, never change one.
|
|
24
|
+
*
|
|
25
|
+
* What a token writes into a page or block is held to plain Markdown, simple
|
|
26
|
+
* HTML and the presentational shortcodes (services/tokenContentPolicy.js) - a
|
|
27
|
+
* bot's draft is rendered for the admin who reviews it. Writes are limited per
|
|
28
|
+
* token (WRITE_LIMIT a minute, MEDIA_BYTES_PER_DAY of uploads).
|
|
29
|
+
*
|
|
30
|
+
* Every page/block is bound to the token's project as the reads are. Built-in
|
|
31
|
+
* and Tool-owned pages and blocks are never written. `/` and the 404 page are
|
|
32
|
+
* never written by a token.
|
|
33
|
+
*/
|
|
34
|
+
import {authenticateApiToken, contentScopeAllows, DRAFT_STATUS} from '../../services/apiTokens.js';
|
|
35
|
+
import {createPage, getPage, listPages, saveMedia, updatePage} from '../../services/content.js';
|
|
36
|
+
import {blockNameRefusal, contentRefusal, cssRefusal, renderedContentRefusal} from '../../services/tokenContentPolicy.js';
|
|
37
|
+
import {getBlock, listBlocks, saveBlock} from '../../services/blocks.js';
|
|
38
|
+
import {VIEWS_DIR} from '../../services/views.js';
|
|
39
|
+
import fs from 'node:fs/promises';
|
|
40
|
+
import path from 'node:path';
|
|
41
|
+
import {fileURLToPath} from 'node:url';
|
|
42
|
+
import {CORE_PROJECT_SLUG, getProjectForPage, isProjectEnabled, resolveArtefactProject} from '../../services/projects.js';
|
|
43
|
+
import {getConfig} from '../../config.js';
|
|
44
|
+
|
|
45
|
+
/** A page address a token may write: lowercase slugs, up to five deep, never "/" or the 404 page. */
|
|
46
|
+
const PAGE_PATH = /^\/[a-z0-9][a-z0-9-]{0,79}(\/[a-z0-9][a-z0-9-]{0,79}){0,4}$/;
|
|
47
|
+
const RESERVED_PATHS = new Set(['/404', '/index', '/admin', '/api', '/media', '/public', '/plugins']);
|
|
48
|
+
const MAX_BODY = 200_000;
|
|
49
|
+
const WRITE_LIMIT = 30; // writes a minute, per token
|
|
50
|
+
const MEDIA_BYTES_PER_DAY = 200 * 1024 * 1024; // uploads a day, per token
|
|
51
|
+
|
|
52
|
+
/** Per-token counters - in memory, so a restart forgives; they are a brake, not an account. */
|
|
53
|
+
const writesAt = new Map();
|
|
54
|
+
const bytesOn = new Map();
|
|
55
|
+
export function _resetWriteLimits() { writesAt.clear(); bytesOn.clear(); }
|
|
56
|
+
function mayWrite(tokenId, now = Date.now()) {
|
|
57
|
+
const recent = (writesAt.get(tokenId) || []).filter(t => now - t < 60_000);
|
|
58
|
+
if (recent.length >= WRITE_LIMIT) { writesAt.set(tokenId, recent); return false; }
|
|
59
|
+
recent.push(now);
|
|
60
|
+
writesAt.set(tokenId, recent);
|
|
61
|
+
return true;
|
|
62
|
+
}
|
|
63
|
+
function mayUpload(tokenId, bytes, now = Date.now()) {
|
|
64
|
+
const day = new Date(now).toISOString().slice(0, 10);
|
|
65
|
+
const used = bytesOn.get(tokenId);
|
|
66
|
+
const total = (used?.day === day ? used.bytes : 0) + bytes;
|
|
67
|
+
if (total > MEDIA_BYTES_PER_DAY) return false;
|
|
68
|
+
bytesOn.set(tokenId, {day, bytes: total});
|
|
69
|
+
return true;
|
|
70
|
+
}
|
|
71
|
+
const MAX_BLOCK = 100_000;
|
|
72
|
+
|
|
73
|
+
/** The frontmatter a token may set. Everything else (owner, project, scripts, SEO overrides) is the editor's. */
|
|
74
|
+
const PAGE_FIELDS = {
|
|
75
|
+
title: (v) => typeof v === 'string' && v.trim().length <= 200 ? v.trim() : undefined,
|
|
76
|
+
description: (v) => typeof v === 'string' && v.length <= 500 ? v : undefined,
|
|
77
|
+
excerpt: (v) => typeof v === 'string' && v.length <= 1000 ? v : undefined,
|
|
78
|
+
image: (v) => typeof v === 'string' && /^\/media\/[A-Za-z0-9._-]{1,200}$/.test(v) ? v : undefined,
|
|
79
|
+
tags: (v) => Array.isArray(v) ? v.filter(t => typeof t === 'string' && t.length <= 60).slice(0, 30) : undefined,
|
|
80
|
+
layout: (v) => typeof v === 'string' && layouts().includes(v) ? v : undefined,
|
|
81
|
+
status: (v) => v === 'draft' || v === 'published' ? v : undefined
|
|
82
|
+
};
|
|
83
|
+
function layouts() {
|
|
84
|
+
try { return Object.keys(getConfig('presets') || {}); } catch { return ['default', 'landing', 'blank']; }
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* The frontmatter a token's write keeps, and what it refused. Pure.
|
|
89
|
+
*
|
|
90
|
+
* @param {object} input
|
|
91
|
+
* @returns {{frontmatter: object, ignored: string[]}}
|
|
92
|
+
*/
|
|
93
|
+
export function tokenFrontmatter(input) {
|
|
94
|
+
const frontmatter = {};
|
|
95
|
+
const ignored = [];
|
|
96
|
+
for (const [key, value] of Object.entries(input && typeof input === 'object' && !Array.isArray(input) ? input : {})) {
|
|
97
|
+
const check = PAGE_FIELDS[key];
|
|
98
|
+
const kept = check ? check(value) : undefined;
|
|
99
|
+
if (kept === undefined) ignored.push(key);
|
|
100
|
+
else frontmatter[key] = kept;
|
|
101
|
+
}
|
|
102
|
+
return {frontmatter, ignored};
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/**
|
|
106
|
+
* Whether a token may write a page at this address. Pure.
|
|
107
|
+
*
|
|
108
|
+
* @param {string} urlPath
|
|
109
|
+
* @returns {string|null} why not, or null
|
|
110
|
+
*/
|
|
111
|
+
export function pagePathRefusal(urlPath) {
|
|
112
|
+
if (typeof urlPath !== 'string' || !PAGE_PATH.test(urlPath)) {
|
|
113
|
+
return 'path must look like /news/my-post: lowercase letters, digits and hyphens, up to five parts';
|
|
114
|
+
}
|
|
115
|
+
if (RESERVED_PATHS.has(urlPath) || RESERVED_PATHS.has('/' + urlPath.split('/')[1])) return `${urlPath} cannot be written with a token`;
|
|
116
|
+
return null;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/** What a picture or PDF really is, by its first bytes - never by its name or the sender's say-so. Pure. */
|
|
120
|
+
export function sniffMedia(buf) {
|
|
121
|
+
const b = buf || Buffer.alloc(0);
|
|
122
|
+
const at = (i, ...bytes) => bytes.every((x, j) => b[i + j] === x);
|
|
123
|
+
if (at(0, 0xFF, 0xD8, 0xFF)) return 'jpg';
|
|
124
|
+
if (at(0, 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A)) return 'png';
|
|
125
|
+
if (at(0, 0x47, 0x49, 0x46, 0x38)) return 'gif';
|
|
126
|
+
if (at(0, 0x52, 0x49, 0x46, 0x46) && at(8, 0x57, 0x45, 0x42, 0x50)) return 'webp';
|
|
127
|
+
if (at(4, 0x66, 0x74, 0x79, 0x70) && (at(8, 0x61, 0x76, 0x69, 0x66) || at(8, 0x61, 0x76, 0x69, 0x73))) return 'avif';
|
|
128
|
+
if (at(0, 0x25, 0x50, 0x44, 0x46, 0x2D)) return 'pdf';
|
|
129
|
+
return null;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/** A media file name for an upload: the sender's name, cleaned, with the real extension. Pure. */
|
|
133
|
+
export function mediaName(filename, ext) {
|
|
134
|
+
const base = String(filename || 'upload').replace(/\.[^.]*$/, '').toLowerCase()
|
|
135
|
+
.replace(/[^a-z0-9._-]+/g, '-').replace(/^[-.]+|[-.]+$/g, '').slice(0, 80) || 'upload';
|
|
136
|
+
return `${base}.${ext}`;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
const CONFIG_DIR = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '..', '..', 'config');
|
|
140
|
+
|
|
141
|
+
/** The site's block names - each is a short tag a token may not use. */
|
|
142
|
+
async function blockNames() {
|
|
143
|
+
return (await listBlocks()).map(b => b.name);
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/** Raw JSON files that may name a block: views, site.json, menus. */
|
|
147
|
+
async function configTexts() {
|
|
148
|
+
const texts = [];
|
|
149
|
+
const readAll = async (dir) => {
|
|
150
|
+
let files = [];
|
|
151
|
+
try { files = await fs.readdir(dir); } catch { return; }
|
|
152
|
+
for (const f of files.filter(n => n.endsWith('.json'))) {
|
|
153
|
+
try { texts.push(await fs.readFile(path.join(dir, f), 'utf8')); } catch { /* gone */ }
|
|
154
|
+
}
|
|
155
|
+
};
|
|
156
|
+
await readAll(VIEWS_DIR);
|
|
157
|
+
await readAll(path.join(CONFIG_DIR, 'menus'));
|
|
158
|
+
try { texts.push(await fs.readFile(path.join(CONFIG_DIR, 'site.json'), 'utf8')); } catch { /* none */ }
|
|
159
|
+
return texts;
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/**
|
|
163
|
+
* @param {import('fastify').FastifyInstance} fastify
|
|
164
|
+
*/
|
|
165
|
+
export async function contentWriteRoutes(fastify) {
|
|
166
|
+
/** The token, or the refusal sent (and finished) and null. */
|
|
167
|
+
async function tokenFor(request, reply, resource, verb) {
|
|
168
|
+
const auth = await authenticateApiToken(request, {allows: (scopes) => contentScopeAllows(scopes, resource, verb)});
|
|
169
|
+
if (!auth.ok) { await reply.status(auth.status).send({error: auth.error}); return null; }
|
|
170
|
+
if (!(await isProjectEnabled(auth.token.project))) { await reply.status(404).send({error: 'Not found'}); return null; }
|
|
171
|
+
reply.header('cache-control', 'no-store');
|
|
172
|
+
if (!mayWrite(auth.token.id)) { await reply.status(429).send({error: `At most ${WRITE_LIMIT} writes a minute with one token - wait a moment`}); return null; }
|
|
173
|
+
return auth.token;
|
|
174
|
+
}
|
|
175
|
+
const by = (token) => `token:${token.id}`;
|
|
176
|
+
|
|
177
|
+
// ---- Pages ----------------------------------------------------------------
|
|
178
|
+
|
|
179
|
+
fastify.post('/content/v1/pages', async (request, reply) => {
|
|
180
|
+
const token = await tokenFor(request, reply, 'pages', 'create');
|
|
181
|
+
if (!token) return reply;
|
|
182
|
+
const {path: urlPath, frontmatter: fm, body = ''} = request.body || {};
|
|
183
|
+
const refused = pagePathRefusal(urlPath);
|
|
184
|
+
if (refused) return reply.status(400).send({error: refused});
|
|
185
|
+
if (typeof body !== 'string' || body.length > MAX_BODY) return reply.status(400).send({error: `body must be Markdown text, at most ${MAX_BODY} characters`});
|
|
186
|
+
const names = await blockNames();
|
|
187
|
+
const unsafe = contentRefusal(body, {blockNames: names}) || contentRefusal(JSON.stringify(fm ?? {}), {blockNames: names})
|
|
188
|
+
|| await renderedContentRefusal(body);
|
|
189
|
+
if (unsafe) return reply.status(400).send({error: unsafe});
|
|
190
|
+
if ((await getProjectForPage(urlPath)) !== token.project) {
|
|
191
|
+
return reply.status(403).send({error: "That address is not in this token's project"});
|
|
192
|
+
}
|
|
193
|
+
if (await getPage(urlPath)) return reply.status(409).send({error: `A page already exists at ${urlPath}`});
|
|
194
|
+
const {frontmatter, ignored} = tokenFrontmatter(fm);
|
|
195
|
+
if (!frontmatter.title) return reply.status(400).send({error: 'frontmatter.title is required'});
|
|
196
|
+
if (token.draftsOnly || !frontmatter.status) frontmatter.status = DRAFT_STATUS;
|
|
197
|
+
frontmatter.createdBy = by(token);
|
|
198
|
+
let page;
|
|
199
|
+
try {
|
|
200
|
+
page = await createPage(urlPath, frontmatter, body, {exclusive: true});
|
|
201
|
+
} catch (err) {
|
|
202
|
+
if (err.code === 'EEXIST') return reply.status(409).send({error: `A page already exists at ${urlPath}`});
|
|
203
|
+
throw err;
|
|
204
|
+
}
|
|
205
|
+
return reply.status(201).send({path: urlPath, status: page.status, title: page.title, ...(ignored.length && {ignored})});
|
|
206
|
+
});
|
|
207
|
+
|
|
208
|
+
fastify.put('/content/v1/pages/*', async (request, reply) => {
|
|
209
|
+
const token = await tokenFor(request, reply, 'pages', 'update');
|
|
210
|
+
if (!token) return reply;
|
|
211
|
+
const urlPath = '/' + String(request.params['*'] || '').replace(/\/+$/, '');
|
|
212
|
+
const refused = pagePathRefusal(urlPath);
|
|
213
|
+
if (refused) return reply.status(400).send({error: refused});
|
|
214
|
+
const existing = await getPage(urlPath);
|
|
215
|
+
if (!existing) return reply.status(404).send({error: 'Page not found'});
|
|
216
|
+
if ((await getProjectForPage(urlPath, existing.project)) !== token.project) {
|
|
217
|
+
return reply.status(403).send({error: "That page is not in this token's project"});
|
|
218
|
+
}
|
|
219
|
+
if (existing.plugin) return reply.status(403).send({error: 'That page belongs to a Tool and cannot be written with a token'});
|
|
220
|
+
if (token.draftsOnly && existing.status !== DRAFT_STATUS) {
|
|
221
|
+
return reply.status(403).send({error: 'This token may only change drafts, and this page is not one'});
|
|
222
|
+
}
|
|
223
|
+
// Only the drafts it wrote: a person's own draft (one with a share link, one under review) is theirs.
|
|
224
|
+
if (token.draftsOnly && existing.createdBy !== by(token)) {
|
|
225
|
+
return reply.status(403).send({error: 'This token may only change the drafts it wrote'});
|
|
226
|
+
}
|
|
227
|
+
const {body} = request.body || {};
|
|
228
|
+
if (body !== undefined && (typeof body !== 'string' || body.length > MAX_BODY)) {
|
|
229
|
+
return reply.status(400).send({error: `body must be Markdown text, at most ${MAX_BODY} characters`});
|
|
230
|
+
}
|
|
231
|
+
const names = await blockNames();
|
|
232
|
+
const unsafe = (body !== undefined && contentRefusal(body, {blockNames: names}))
|
|
233
|
+
|| contentRefusal(JSON.stringify(request.body?.frontmatter ?? {}), {blockNames: names})
|
|
234
|
+
|| (body !== undefined && await renderedContentRefusal(body));
|
|
235
|
+
if (unsafe) return reply.status(400).send({error: unsafe});
|
|
236
|
+
const {frontmatter, ignored} = tokenFrontmatter(request.body?.frontmatter);
|
|
237
|
+
if (token.draftsOnly) frontmatter.status = DRAFT_STATUS;
|
|
238
|
+
const page = await updatePage(urlPath, frontmatter, body === undefined ? existing.content : body, {author: `API token ${token.name}`});
|
|
239
|
+
return {path: urlPath, status: page.status, title: page.title, ...(ignored.length && {ignored})};
|
|
240
|
+
});
|
|
241
|
+
|
|
242
|
+
// ---- Media ----------------------------------------------------------------
|
|
243
|
+
|
|
244
|
+
fastify.post('/content/v1/media', async (request, reply) => {
|
|
245
|
+
const token = await tokenFor(request, reply, 'media', 'create');
|
|
246
|
+
if (!token) return reply;
|
|
247
|
+
if (!request.isMultipart?.()) return reply.status(400).send({error: 'Send the file as multipart/form-data (a "file" field)'});
|
|
248
|
+
const part = await request.file();
|
|
249
|
+
if (!part) return reply.status(400).send({error: 'No file uploaded'});
|
|
250
|
+
const chunks = [];
|
|
251
|
+
for await (const chunk of part.file) chunks.push(chunk);
|
|
252
|
+
if (part.file.truncated) return reply.status(413).send({error: 'The file is too large'});
|
|
253
|
+
const buf = Buffer.concat(chunks);
|
|
254
|
+
if (!mayUpload(token.id, buf.length)) return reply.status(429).send({error: 'This token has uploaded as much as it may today'});
|
|
255
|
+
const ext = sniffMedia(buf);
|
|
256
|
+
if (!ext) return reply.status(400).send({error: 'Only pictures (JPEG, PNG, GIF, WebP, AVIF) and PDFs can be uploaded with a token'});
|
|
257
|
+
const wanted = mediaName(part.filename, ext);
|
|
258
|
+
// Never over another file: name-2.png, name-3.png… (exclusive create).
|
|
259
|
+
for (let n = 1; n <= 50; n++) {
|
|
260
|
+
const name = n === 1 ? wanted : wanted.replace(/\.([a-z]+)$/, `-${n}.$1`);
|
|
261
|
+
try {
|
|
262
|
+
const saved = await saveMedia(name, buf, {exclusive: true});
|
|
263
|
+
return reply.status(201).send(saved);
|
|
264
|
+
} catch (err) {
|
|
265
|
+
if (err.code !== 'EEXIST') return reply.status(500).send({error: 'Upload failed'});
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
return reply.status(409).send({error: 'Too many files with that name - choose another'});
|
|
269
|
+
});
|
|
270
|
+
|
|
271
|
+
// ---- Blocks ---------------------------------------------------------------
|
|
272
|
+
|
|
273
|
+
async function checkBlockBody(body) {
|
|
274
|
+
const {content, css} = body || {};
|
|
275
|
+
if (typeof content !== 'string' || !content.trim() || content.length > MAX_BLOCK) return `content must be the block's HTML, at most ${MAX_BLOCK} characters`;
|
|
276
|
+
if (css !== undefined && typeof css !== 'string') return 'css must be a string';
|
|
277
|
+
return contentRefusal(content, {blockNames: await blockNames()}) || (css ? cssRefusal(css) : null)
|
|
278
|
+
|| await renderedContentRefusal(content);
|
|
279
|
+
}
|
|
280
|
+
/** What the site already asks for by block name: pages' and blocks' markup, and its settings. */
|
|
281
|
+
async function blocksAskedFor() {
|
|
282
|
+
const pages = (await listPages()).map(p => String(p.content || ''));
|
|
283
|
+
const blocks = [];
|
|
284
|
+
for (const b of await listBlocks()) {
|
|
285
|
+
try { blocks.push(String((await getBlock(b.name)).content || '')); } catch { /* gone */ }
|
|
286
|
+
}
|
|
287
|
+
return {bodies: [...pages, ...blocks], configs: await configTexts()};
|
|
288
|
+
}
|
|
289
|
+
const blockProject = (block) => resolveArtefactProject({meta: block?.meta || {}});
|
|
290
|
+
|
|
291
|
+
fastify.post('/content/v1/blocks', async (request, reply) => {
|
|
292
|
+
const token = await tokenFor(request, reply, 'blocks', 'create');
|
|
293
|
+
if (!token) return reply;
|
|
294
|
+
const {name, content, css} = request.body || {};
|
|
295
|
+
const bad = await checkBlockBody(request.body);
|
|
296
|
+
if (bad) return reply.status(400).send({error: bad});
|
|
297
|
+
const taken = blockNameRefusal(String(name || ''), await blocksAskedFor());
|
|
298
|
+
if (taken) return reply.status(400).send({error: taken});
|
|
299
|
+
const meta = {createdBy: by(token), ...(token.project !== CORE_PROJECT_SLUG && {project: token.project})};
|
|
300
|
+
try {
|
|
301
|
+
await saveBlock(String(name || ''), content, {css, meta, createOnly: true});
|
|
302
|
+
} catch (err) {
|
|
303
|
+
if (err.code === 'EEXIST') return reply.status(409).send({error: `A block named "${name}" already exists`});
|
|
304
|
+
if (err.code === 'INVALID_NAME' || err.code === 'CSS_TOO_LARGE') return reply.status(400).send({error: err.message});
|
|
305
|
+
throw err;
|
|
306
|
+
}
|
|
307
|
+
return reply.status(201).send({name, ...(token.draftsOnly && {note: 'A block has no draft state: it shows wherever a page uses it.'})});
|
|
308
|
+
});
|
|
309
|
+
|
|
310
|
+
fastify.put('/content/v1/blocks/:name', async (request, reply) => {
|
|
311
|
+
const token = await tokenFor(request, reply, 'blocks', 'update');
|
|
312
|
+
if (!token) return reply;
|
|
313
|
+
if (token.draftsOnly) {
|
|
314
|
+
return reply.status(403).send({error: 'A drafts-only token may only create new blocks - a block is live wherever it is used'});
|
|
315
|
+
}
|
|
316
|
+
const {name} = request.params;
|
|
317
|
+
const bad = await checkBlockBody(request.body);
|
|
318
|
+
if (bad) return reply.status(400).send({error: bad});
|
|
319
|
+
let block;
|
|
320
|
+
try { block = await getBlock(name); } catch (err) {
|
|
321
|
+
if (err.code === 'INVALID_NAME') return reply.status(400).send({error: err.message});
|
|
322
|
+
return reply.status(404).send({error: 'Block not found'});
|
|
323
|
+
}
|
|
324
|
+
if (block.bundled || block.meta?.plugin) return reply.status(403).send({error: 'That block belongs to the CMS or a Tool and cannot be written with a token'});
|
|
325
|
+
if (blockProject(block) !== token.project) return reply.status(403).send({error: "That block is not in this token's project"});
|
|
326
|
+
try {
|
|
327
|
+
await saveBlock(name, request.body.content, {css: request.body.css, meta: {...(block.meta || {}), updatedBy: by(token)}});
|
|
328
|
+
} catch (err) {
|
|
329
|
+
if (err.code === 'CSS_TOO_LARGE') return reply.status(400).send({error: err.message});
|
|
330
|
+
throw err;
|
|
331
|
+
}
|
|
332
|
+
return {name};
|
|
333
|
+
});
|
|
334
|
+
}
|
|
@@ -45,6 +45,26 @@ import {imageHostRoutes} from './image-hosts.js';
|
|
|
45
45
|
import {ago, clip, plural} from '../../services/sidebarBadges.js';
|
|
46
46
|
import {dommaCatalogue} from '../../services/dommaCatalogue.js';
|
|
47
47
|
|
|
48
|
+
/**
|
|
49
|
+
* Whether a preview shows something an API token wrote - the page itself (its
|
|
50
|
+
* stored `createdBy` is `token:<id>`), or a block a token made (`meta.createdBy`).
|
|
51
|
+
* The editor then draws it with no scripts and no same-origin, so content that
|
|
52
|
+
* got past the token content policy still cannot reach the reviewer's session.
|
|
53
|
+
*
|
|
54
|
+
* @param {string} urlPath
|
|
55
|
+
* @param {string} html - the rendered preview
|
|
56
|
+
* @returns {Promise<boolean>}
|
|
57
|
+
*/
|
|
58
|
+
export async function tokenAuthored(urlPath, html) {
|
|
59
|
+
try {
|
|
60
|
+
const stored = await getPage(urlPath);
|
|
61
|
+
if (String(stored?.createdBy || '').startsWith('token:')) return true;
|
|
62
|
+
} catch { /* no page there yet */ }
|
|
63
|
+
const {listBlocks} = await import('../../services/blocks.js');
|
|
64
|
+
const made = (await listBlocks()).filter(b => String(b.meta?.createdBy || '').startsWith('token:')).map(b => b.name);
|
|
65
|
+
return made.some(name => String(html).includes(`data-block="${name}"`));
|
|
66
|
+
}
|
|
67
|
+
|
|
48
68
|
/**
|
|
49
69
|
* The sidebar badge on Pages (its countUrl): the drafts - unpublished work -
|
|
50
70
|
* with a popover of what is published, restricted and recently changed, and
|
|
@@ -128,7 +148,7 @@ export async function pagesRoutes(fastify) {
|
|
|
128
148
|
noTrack: true
|
|
129
149
|
});
|
|
130
150
|
});
|
|
131
|
-
return {html};
|
|
151
|
+
return {html, isolate: await tokenAuthored(urlPath, html)};
|
|
132
152
|
});
|
|
133
153
|
|
|
134
154
|
// --- Share links --------------------------------------------------------
|
package/server/routes/public.js
CHANGED
|
@@ -107,6 +107,19 @@ export async function publicRoutes(fastify) {
|
|
|
107
107
|
return reply.type('text/plain').send(buildRobotsTxt(getBaseUrl(request)));
|
|
108
108
|
});
|
|
109
109
|
|
|
110
|
+
/**
|
|
111
|
+
* A draft an API token wrote is shown to its reviewer in a CSP sandbox: no
|
|
112
|
+
* scripts, an opaque origin. If anything got past the token content policy
|
|
113
|
+
* (services/tokenContentPolicy.js), it still cannot read a session or call the
|
|
114
|
+
* API as whoever is looking. Published pages are not sandboxed - a person has
|
|
115
|
+
* reviewed and published them.
|
|
116
|
+
*/
|
|
117
|
+
function isolateTokenDraft(reply, page) {
|
|
118
|
+
if (!String(page?.createdBy || '').startsWith('token:')) return;
|
|
119
|
+
const csp = reply.getHeader('content-security-policy');
|
|
120
|
+
reply.header('content-security-policy', `${csp ? `${csp}; ` : ''}sandbox allow-popups allow-popups-to-escape-sandbox`);
|
|
121
|
+
}
|
|
122
|
+
|
|
110
123
|
// Share-link preview: one signed token, one page, no account needed.
|
|
111
124
|
//
|
|
112
125
|
// The token rides in the query string, not the path: Fastify caps a route
|
|
@@ -149,6 +162,7 @@ export async function publicRoutes(fastify) {
|
|
|
149
162
|
// Rendered as anonymous on purpose: the recipient has no account, so
|
|
150
163
|
// menus and role-gated shortcodes must show them the least, not the
|
|
151
164
|
// most. The token satisfies this page's own gate and nothing else.
|
|
165
|
+
isolateTokenDraft(reply, page);
|
|
152
166
|
await touchPreviewLink(link.id);
|
|
153
167
|
const html = await renderPage(page, {
|
|
154
168
|
baseUrl: getBaseUrl(request),
|
|
@@ -237,6 +251,7 @@ export async function publicRoutes(fastify) {
|
|
|
237
251
|
// written here would be served to the next anonymous visitor under
|
|
238
252
|
// the same key - and must never be indexed.
|
|
239
253
|
if (isDraft) {
|
|
254
|
+
isolateTokenDraft(reply, page);
|
|
240
255
|
reply.header('cache-control', 'no-store, private');
|
|
241
256
|
reply.header('x-robots-tag', 'noindex, nofollow');
|
|
242
257
|
reply.header('x-dm-cache', 'bypass');
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The one-time API token handover - its page and the single read behind it.
|
|
3
|
+
*
|
|
4
|
+
* GET /_token-handover?h=<id>#k=<key> - the page (no sign-in). The page itself
|
|
5
|
+
* reads nothing: a link checker or a mail
|
|
6
|
+
* scanner that GETs the address uses nothing.
|
|
7
|
+
* POST /api/token-handover/:id/open - answers the ciphertext ONCE, then it is gone
|
|
8
|
+
*
|
|
9
|
+
* The key is only ever in the #fragment, so this server never holds both halves
|
|
10
|
+
* (services/tokenHandovers.js). The page decrypts in the browser
|
|
11
|
+
* (public/js/token-handover-page.mjs) after the person presses Show.
|
|
12
|
+
*/
|
|
13
|
+
import path from 'node:path';
|
|
14
|
+
import fs from 'node:fs';
|
|
15
|
+
import {fileURLToPath} from 'node:url';
|
|
16
|
+
import {renderBlogPage} from '../services/renderer.js';
|
|
17
|
+
import {getBaseUrl} from './public.js';
|
|
18
|
+
import {HANDOVER_PATH, openHandover} from '../services/tokenHandovers.js';
|
|
19
|
+
import {getTokenSanitised} from '../services/apiTokens.js';
|
|
20
|
+
|
|
21
|
+
const HERE = path.dirname(fileURLToPath(import.meta.url));
|
|
22
|
+
const TEMPLATE = path.join(HERE, '..', 'templates', 'token-handover.html');
|
|
23
|
+
const ASSET_V = (() => {
|
|
24
|
+
try { return JSON.parse(fs.readFileSync(path.join(HERE, '..', '..', 'package.json'), 'utf8')).version || '1'; } catch { return '1'; }
|
|
25
|
+
})();
|
|
26
|
+
const GONE = 'This link has already been opened, has expired, or its token was revoked. Ask whoever sent it for a new one.';
|
|
27
|
+
|
|
28
|
+
/** Usable = still there, switched on and not expired. */
|
|
29
|
+
export async function tokenUsable(tokenId, now = Date.now()) {
|
|
30
|
+
const t = await getTokenSanitised(tokenId);
|
|
31
|
+
return Boolean(t && t.enabled !== false && !(t.expiresAt && Date.parse(t.expiresAt) <= now));
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
const BODY = `<h1>An API token for you</h1>
|
|
35
|
+
<p>Someone has sent you an API token for this site. It can be shown <strong>once</strong>: when you press Show,
|
|
36
|
+
this link stops working, so keep the page open until you have saved the token (or the connection file).</p>
|
|
37
|
+
<div data-dm-token-handover><noscript><p>This page needs JavaScript switched on.</p></noscript></div>
|
|
38
|
+
<script type="module" src="/public/js/token-handover-page.mjs?v=${ASSET_V}"></script>`;
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* @param {import('fastify').FastifyInstance} fastify
|
|
42
|
+
*/
|
|
43
|
+
export async function tokenHandoverPublicRoutes(fastify) {
|
|
44
|
+
fastify.get(HANDOVER_PATH, async (request, reply) => {
|
|
45
|
+
reply.header('referrer-policy', 'no-referrer');
|
|
46
|
+
reply.header('cache-control', 'no-store, private');
|
|
47
|
+
reply.header('x-robots-tag', 'noindex, nofollow');
|
|
48
|
+
const html = await renderBlogPage(TEMPLATE, {body: BODY}, {
|
|
49
|
+
title: 'An API token for you', urlPath: HANDOVER_PATH, noindex: true, baseUrl: getBaseUrl(request), injection: false
|
|
50
|
+
});
|
|
51
|
+
return reply.type('text/html; charset=utf-8').send(html);
|
|
52
|
+
});
|
|
53
|
+
|
|
54
|
+
fastify.post('/api/token-handover/:id/open', {config: {rateLimit: {max: 20, timeWindow: '1 minute'}}}, async (request, reply) => {
|
|
55
|
+
const opened = await openHandover(String(request.params.id || ''), tokenUsable);
|
|
56
|
+
if (!opened) return reply.status(404).send({error: GONE});
|
|
57
|
+
return opened;
|
|
58
|
+
});
|
|
59
|
+
}
|
package/server/server.js
CHANGED
|
@@ -537,6 +537,7 @@ const {apiTokensRoutes} = await import('./routes/api/api-tokens.js');
|
|
|
537
537
|
const {apiEndpointsRoutes} = await import('./routes/api/api-endpoints.js');
|
|
538
538
|
const {endpointsPublicRoutes} = await import('./routes/api/endpoints-public.js');
|
|
539
539
|
const {contentPublicRoutes} = await import('./routes/api/content-public.js');
|
|
540
|
+
const {contentWriteRoutes} = await import('./routes/api/content-writes.js');
|
|
540
541
|
const {contentApiRoutes} = await import('./routes/api/content-api.js');
|
|
541
542
|
const {sidebarRoutes} = await import('./routes/api/sidebar.js');
|
|
542
543
|
const {documentationRoutes} = await import('./routes/api/documentation.js');
|
|
@@ -580,6 +581,8 @@ await app.register(apiTokensRoutes, {prefix: '/api'});
|
|
|
580
581
|
await app.register(apiEndpointsRoutes, {prefix: '/api'});
|
|
581
582
|
await app.register(endpointsPublicRoutes, {prefix: '/api'});
|
|
582
583
|
await app.register(contentPublicRoutes, {prefix: '/api'});
|
|
584
|
+
// Token writes on the Content API: pages (drafts), media, blocks - routes/api/content-writes.js.
|
|
585
|
+
await app.register(contentWriteRoutes, {prefix: '/api'});
|
|
583
586
|
await app.register(contentApiRoutes, {prefix: '/api'});
|
|
584
587
|
await app.register(sidebarRoutes, {prefix: '/api'});
|
|
585
588
|
await app.register(documentationRoutes, {prefix: '/api'});
|
|
@@ -812,6 +815,9 @@ await app.register(docsPublicRoutes);
|
|
|
812
815
|
// An instant call's page, /_call/<id> (a reserved prefix, like /_preview) - before the catch-all.
|
|
813
816
|
const { callPublicRoutes } = await import('./routes/call-public.js');
|
|
814
817
|
await app.register(callPublicRoutes);
|
|
818
|
+
// A one-time API token handover, /_token-handover?h=<id>#k=<key> (services/tokenHandovers.js) - before the catch-all.
|
|
819
|
+
const { tokenHandoverPublicRoutes } = await import('./routes/token-handover-public.js');
|
|
820
|
+
await app.register(tokenHandoverPublicRoutes);
|
|
815
821
|
// A staff session from the site's Manager (/_staff/open?ticket=…, services/staffAccess.js) - the one way
|
|
816
822
|
// into a Tool switched off with `staff: true`. A ticket only works on a site its Manager started.
|
|
817
823
|
const { staffAccessRoutes } = await import('./services/staffAccess.js');
|
|
@@ -23,6 +23,22 @@ const VERBS = ['create', 'read', 'update', 'delete'];
|
|
|
23
23
|
* scopes are read-only (the API has no writes yet), so they carry no verbs.
|
|
24
24
|
*/
|
|
25
25
|
export const CONTENT_RESOURCES = Object.freeze(['pages', 'menus', 'site', 'search']);
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* What a `{content}` scope may WRITE, per resource (routes/api/content-writes.js).
|
|
29
|
+
* Writes are only ever granted by naming the verb: a scope without verbs reads,
|
|
30
|
+
* and a token with no scopes at all reads everything but writes nothing - so
|
|
31
|
+
* no token made before writes existed gained them.
|
|
32
|
+
*/
|
|
33
|
+
export const CONTENT_WRITES = Object.freeze({pages: Object.freeze(['create', 'update']), media: Object.freeze(['create']), blocks: Object.freeze(['create', 'update'])});
|
|
34
|
+
|
|
35
|
+
/** Every resource a content scope may name. */
|
|
36
|
+
export const CONTENT_SCOPE_RESOURCES = Object.freeze([...new Set([...CONTENT_RESOURCES, ...Object.keys(CONTENT_WRITES)])]);
|
|
37
|
+
|
|
38
|
+
/** The verbs a content scope on `resource` may carry. */
|
|
39
|
+
export function contentVerbs(resource) {
|
|
40
|
+
return [...(CONTENT_RESOURCES.includes(resource) ? ['read'] : []), ...(CONTENT_WRITES[resource] || [])];
|
|
41
|
+
}
|
|
26
42
|
const LAST_USED_THROTTLE_MS = 60_000;
|
|
27
43
|
|
|
28
44
|
/** In-memory hash → entry cache; null = needs rebuild. */
|
|
@@ -95,8 +111,15 @@ export function validateScopes(scopes) {
|
|
|
95
111
|
for (const s of scopes) {
|
|
96
112
|
if (s && typeof s === 'object' && s.content !== undefined) {
|
|
97
113
|
if (s.collection !== undefined) return 'a scope names either a collection or a content resource, not both';
|
|
98
|
-
if (!
|
|
99
|
-
|
|
114
|
+
if (!CONTENT_SCOPE_RESOURCES.includes(s.content)) return `unknown content resource "${s.content}"`;
|
|
115
|
+
const allowed = contentVerbs(s.content);
|
|
116
|
+
if (s.verbs != null) {
|
|
117
|
+
if (!Array.isArray(s.verbs)) return 'scope verbs must be an array';
|
|
118
|
+
const bad = s.verbs.find(v => !allowed.includes(v));
|
|
119
|
+
if (bad) return `"${s.content}" scopes take ${allowed.join(', ')} - not "${bad}"`;
|
|
120
|
+
} else if (!allowed.includes('read')) {
|
|
121
|
+
return `a "${s.content}" scope must say what it may do (${allowed.join(', ')})`;
|
|
122
|
+
}
|
|
100
123
|
continue;
|
|
101
124
|
}
|
|
102
125
|
if (!s || typeof s !== 'object' || typeof s.collection !== 'string' || !s.collection.trim()) {
|
|
@@ -129,17 +152,20 @@ export function scopeAllows(scopes, collectionSlug, verb) {
|
|
|
129
152
|
}
|
|
130
153
|
|
|
131
154
|
/**
|
|
132
|
-
* Does a token's scope list permit a
|
|
133
|
-
* in the project. A list that names no content
|
|
134
|
-
* scoped to collections is never widened by the
|
|
155
|
+
* Does a token's scope list permit `verb` on a content resource? Empty = read
|
|
156
|
+
* everything in the project, write nothing. A list that names no content
|
|
157
|
+
* resource permits none - a token scoped to collections is never widened by the
|
|
158
|
+
* Content API existing. A content scope without verbs reads only.
|
|
135
159
|
*
|
|
136
160
|
* @param {object[]} scopes
|
|
137
|
-
* @param {string} resource - one of
|
|
161
|
+
* @param {string} resource - one of CONTENT_SCOPE_RESOURCES
|
|
162
|
+
* @param {string} [verb] - read (default) or a CONTENT_WRITES verb
|
|
138
163
|
* @returns {boolean}
|
|
139
164
|
*/
|
|
140
|
-
export function contentScopeAllows(scopes, resource) {
|
|
141
|
-
if (!Array.isArray(scopes) || scopes.length === 0) return
|
|
142
|
-
return scopes.some(s => s.content === resource
|
|
165
|
+
export function contentScopeAllows(scopes, resource, verb = 'read') {
|
|
166
|
+
if (!Array.isArray(scopes) || scopes.length === 0) return verb === 'read';
|
|
167
|
+
return scopes.some(s => s.content === resource
|
|
168
|
+
&& (Array.isArray(s.verbs) && s.verbs.length ? s.verbs : ['read']).includes(verb));
|
|
143
169
|
}
|
|
144
170
|
|
|
145
171
|
/** The status a drafts-only token's writes are held at. */
|
|
@@ -165,7 +191,8 @@ export function draftField(schema) {
|
|
|
165
191
|
/**
|
|
166
192
|
* What a drafts-only token may do to a collection, decided before the write.
|
|
167
193
|
* Create: the row is held as a draft whatever the caller sent. Update: only a
|
|
168
|
-
* row that is a draft now, and it stays one. Delete:
|
|
194
|
+
* row that is a draft now AND that this token wrote, and it stays one. Delete:
|
|
195
|
+
* the same. Reads are
|
|
169
196
|
* not this flag's business (api.read and the scopes decide them).
|
|
170
197
|
*
|
|
171
198
|
* Pure - the route passes the stored row for update/delete.
|
|
@@ -187,6 +214,10 @@ export function draftsOnlyDecision(token, schema, operation, existing = null) {
|
|
|
187
214
|
if (existing.data?.[field] !== DRAFT_STATUS) {
|
|
188
215
|
return {ok: false, status: 403, error: 'This token may only change drafts, and this entry is not one'};
|
|
189
216
|
}
|
|
217
|
+
// Only the drafts it wrote: a person's own draft is theirs, whoever is reviewing it.
|
|
218
|
+
if (existing.meta?.createdBy !== `token:${token.id}`) {
|
|
219
|
+
return {ok: false, status: 403, error: 'This token may only change the drafts it wrote'};
|
|
220
|
+
}
|
|
190
221
|
return {ok: true, field};
|
|
191
222
|
}
|
|
192
223
|
|
|
@@ -219,13 +250,14 @@ export async function authenticateApiToken(request, {project, allows, projectErr
|
|
|
219
250
|
}
|
|
220
251
|
|
|
221
252
|
/**
|
|
222
|
-
*
|
|
253
|
+
* The checks createToken() makes, without making anything - so a caller that
|
|
254
|
+
* changes other things first (the bot recipe opens collections) can be sure the
|
|
255
|
+
* token will be made before it touches them.
|
|
223
256
|
*
|
|
224
|
-
* @param {{name: string, project: string, scopes?: object[], expiresAt?: string|null, draftsOnly?: boolean
|
|
225
|
-
* @returns {Promise<{entry: object, plaintext: string}>} Sanitised entry + plaintext
|
|
257
|
+
* @param {{name: string, project: string, scopes?: object[], expiresAt?: string|null, draftsOnly?: boolean}} input
|
|
226
258
|
* @throws {Error} On validation failure
|
|
227
259
|
*/
|
|
228
|
-
export async function
|
|
260
|
+
export async function checkTokenInput({name, project, scopes = [], expiresAt = null, draftsOnly = false}) {
|
|
229
261
|
if (!name || typeof name !== 'string' || !name.trim()) throw new Error('Token name is required');
|
|
230
262
|
if (!project || typeof project !== 'string') throw new Error('Token project is required');
|
|
231
263
|
if (!await getProject(project)) throw new Error(`Unknown project "${project}"`);
|
|
@@ -233,6 +265,17 @@ export async function createToken({name, project, scopes = [], expiresAt = null,
|
|
|
233
265
|
if (scopeError) throw new Error(scopeError);
|
|
234
266
|
if (expiresAt != null && Number.isNaN(Date.parse(expiresAt))) throw new Error('expiresAt must be a valid date');
|
|
235
267
|
if (draftsOnly != null && typeof draftsOnly !== 'boolean') throw new Error('draftsOnly must be true or false');
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
/**
|
|
271
|
+
* Create a new token. The plaintext is returned ONCE here and never again.
|
|
272
|
+
*
|
|
273
|
+
* @param {{name: string, project: string, scopes?: object[], expiresAt?: string|null, draftsOnly?: boolean, createdBy?: string|null}} input
|
|
274
|
+
* @returns {Promise<{entry: object, plaintext: string}>} Sanitised entry + plaintext
|
|
275
|
+
* @throws {Error} On validation failure
|
|
276
|
+
*/
|
|
277
|
+
export async function createToken({name, project, scopes = [], expiresAt = null, draftsOnly = false, createdBy = null}) {
|
|
278
|
+
await checkTokenInput({name, project, scopes, expiresAt, draftsOnly});
|
|
236
279
|
|
|
237
280
|
const plaintext = 'dcms_' + crypto.randomBytes(32).toString('hex');
|
|
238
281
|
const data = {
|
|
@@ -305,14 +348,16 @@ export async function validateToken(plaintext) {
|
|
|
305
348
|
|
|
306
349
|
/**
|
|
307
350
|
* List tokens the given admin user may see (project access scope applies).
|
|
351
|
+
* `all` skips that filter - for the server's own checks, never for a response.
|
|
308
352
|
*
|
|
309
353
|
* @param {object} user
|
|
354
|
+
* @param {{all?: boolean}} [opts]
|
|
310
355
|
* @returns {Promise<object[]>} Sanitised entries
|
|
311
356
|
*/
|
|
312
|
-
export async function listTokensSanitised(user) {
|
|
357
|
+
export async function listTokensSanitised(user, {all = false} = {}) {
|
|
313
358
|
const {entries} = await listEntries(API_TOKENS_COLLECTION_SLUG, {limit: 0});
|
|
314
359
|
return entries
|
|
315
|
-
.filter(e => canSeeArtefact(user, {meta: {project: e.data?.project}}))
|
|
360
|
+
.filter(e => all || canSeeArtefact(user, {meta: {project: e.data?.project}}))
|
|
316
361
|
.map(sanitise);
|
|
317
362
|
}
|
|
318
363
|
|