verso-cms 0.0.0-stage → 0.1.3

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 (108) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +168 -2
  3. package/bin/verso.js +16 -0
  4. package/editor/door.js +139 -0
  5. package/editor/editor.js +1880 -0
  6. package/editor/elevate.css +2158 -0
  7. package/editor/ext-attrs.js +87 -0
  8. package/editor/ext-blocks.js +422 -0
  9. package/editor/ext-builder.js +819 -0
  10. package/editor/ext-channels.js +574 -0
  11. package/editor/ext-components.js +160 -0
  12. package/editor/ext-history.js +242 -0
  13. package/editor/ext-palette.js +307 -0
  14. package/editor/ext-people.js +345 -0
  15. package/editor/ext-repeaters.js +143 -0
  16. package/editor/ext-screens.js +94 -0
  17. package/editor/ext-site-settings.js +318 -0
  18. package/editor/ext-site-view.js +632 -0
  19. package/editor/ext-tokens.js +1195 -0
  20. package/editor/new-page.js +252 -0
  21. package/editor/rich.js +23 -0
  22. package/package.json +69 -4
  23. package/src/blocks.js +269 -0
  24. package/src/box.js +339 -0
  25. package/src/build.js +210 -0
  26. package/src/cli.js +161 -0
  27. package/src/color.js +137 -0
  28. package/src/components.js +223 -0
  29. package/src/elevate.js +74 -0
  30. package/src/errors.js +46 -0
  31. package/src/extensions/README.md +70 -0
  32. package/src/extensions/blocks.js +294 -0
  33. package/src/extensions/builder.js +734 -0
  34. package/src/extensions/channels.js +341 -0
  35. package/src/extensions/components.js +141 -0
  36. package/src/extensions/history.js +169 -0
  37. package/src/extensions/palette.js +31 -0
  38. package/src/extensions/people.js +113 -0
  39. package/src/extensions/site-settings.js +251 -0
  40. package/src/extensions/site-view.js +381 -0
  41. package/src/extensions/tags.js +15 -0
  42. package/src/extensions/tokens.js +587 -0
  43. package/src/fonts.js +139 -0
  44. package/src/git.js +419 -0
  45. package/src/html-edit.js +942 -0
  46. package/src/images.js +116 -0
  47. package/src/people.js +286 -0
  48. package/src/rich.js +124 -0
  49. package/src/scaffold.js +185 -0
  50. package/src/screens.js +65 -0
  51. package/src/server.js +693 -0
  52. package/src/site.js +618 -0
  53. package/src/template.js +915 -0
  54. package/src/video.js +29 -0
  55. package/starter/Dockerfile +20 -0
  56. package/starter/README.md +49 -0
  57. package/starter/blocks/call-to-action.html +6 -0
  58. package/starter/blocks/features.html +15 -0
  59. package/starter/blocks/hero.html +8 -0
  60. package/starter/blocks/image-and-text.html +8 -0
  61. package/starter/blocks/latest-posts.html +20 -0
  62. package/starter/blocks/post-index.html +30 -0
  63. package/starter/blocks/quote.html +9 -0
  64. package/starter/blocks/site-footer.html +8 -0
  65. package/starter/blocks/site-nav.html +8 -0
  66. package/starter/blocks/tag-list.html +10 -0
  67. package/starter/blocks/tagged-posts.html +19 -0
  68. package/starter/blocks/team.html +15 -0
  69. package/starter/blocks/text.html +4 -0
  70. package/starter/content/404/page.json +21 -0
  71. package/starter/content/about/page.json +65 -0
  72. package/starter/content/journal/designing-for-the-morning-shift/body.html +22 -0
  73. package/starter/content/journal/designing-for-the-morning-shift/checklist.jpg +0 -0
  74. package/starter/content/journal/designing-for-the-morning-shift/cover.jpg +0 -0
  75. package/starter/content/journal/designing-for-the-morning-shift/page.json +17 -0
  76. package/starter/content/journal/page.json +19 -0
  77. package/starter/content/journal/the-first-week/body.html +17 -0
  78. package/starter/content/journal/the-first-week/cover.jpg +0 -0
  79. package/starter/content/journal/the-first-week/page.json +17 -0
  80. package/starter/content/journal/the-first-week/wall-of-cards.jpg +0 -0
  81. package/starter/content/page.json +94 -0
  82. package/starter/content/site.json +88 -0
  83. package/starter/content/studio-table.jpg +0 -0
  84. package/starter/content/topics/page.json +27 -0
  85. package/starter/dockerignore +5 -0
  86. package/starter/elevate/config/design.ts +30 -0
  87. package/starter/elevate/config/elevate.ts +16 -0
  88. package/starter/elevate/config/syntax.ts +6 -0
  89. package/starter/elevate/design/site.ts +9 -0
  90. package/starter/elevate/design/tokens.json +20 -0
  91. package/starter/elevate/extend/fonts.css +1 -0
  92. package/starter/gitignore +6 -0
  93. package/starter/netlify.toml +5 -0
  94. package/starter/parts/.gitkeep +0 -0
  95. package/starter/public/favicon.svg +1 -0
  96. package/starter/templates/page.html +20 -0
  97. package/starter/templates/page.layout.json +23 -0
  98. package/starter/templates/post.html +65 -0
  99. package/starter/verso.defaults.json +33 -0
  100. package/starter-blank/blocks/site-footer.html +3 -0
  101. package/starter-blank/blocks/site-nav.html +8 -0
  102. package/starter-blank/blocks/text.html +4 -0
  103. package/starter-blank/content/404/page.json +18 -0
  104. package/starter-blank/content/page.json +18 -0
  105. package/starter-blank/content/site.json +36 -0
  106. package/starter-blank/elevate/design/tokens.json +10 -0
  107. package/starter-blank/templates/page.html +17 -0
  108. package/starter-blank/verso.defaults.json +26 -0
package/src/images.js ADDED
@@ -0,0 +1,116 @@
1
+ // Image sizes, read from the files themselves and remembered until the file
2
+ // changes, so pages can say how big each image is before it loads.
3
+
4
+ import fs from 'fs';
5
+ import path from 'path';
6
+ import { imageSize as readSize } from 'image-size';
7
+ import { createHash } from 'crypto';
8
+
9
+ const cache = new Map();
10
+
11
+ // Where a page's image is on disk: beside the page, or in content/ itself
12
+ // when its name starts with "/" (an image the whole site shares).
13
+ export function imagePath(page, file) {
14
+ if (!String(file).startsWith('/')) return path.join(page.dir, file);
15
+ let dir = page.dir;
16
+ while (path.basename(dir) !== 'content' && path.dirname(dir) !== dir) dir = path.dirname(dir);
17
+ return path.join(dir, file.slice(1));
18
+ }
19
+
20
+ export function imageSize(page, file) {
21
+ const full = imagePath(page, file);
22
+ try {
23
+ const stat = fs.statSync(full);
24
+ const key = `${full}:${stat.mtimeMs}:${stat.size}`;
25
+ if (!cache.has(key)) {
26
+ const { width, height } = readSize(fs.readFileSync(full));
27
+ cache.set(key, width && height ? { width, height } : null);
28
+ }
29
+ return cache.get(key);
30
+ } catch {
31
+ return null;
32
+ }
33
+ }
34
+
35
+ // What a file really is, from its first bytes, whatever its name says.
36
+ export function sniffImage(buffer) {
37
+ const b = buffer;
38
+ if (b.length > 3 && b[0] === 0xff && b[1] === 0xd8 && b[2] === 0xff) return 'jpg';
39
+ if (b.length > 8 && b.slice(0, 8).equals(Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]))) return 'png';
40
+ if (b.length > 6 && /^GIF8[79]a/.test(b.slice(0, 6).toString('latin1'))) return 'gif';
41
+ if (b.length > 12 && b.slice(0, 4).toString('latin1') === 'RIFF' && b.slice(8, 12).toString('latin1') === 'WEBP') return 'webp';
42
+ if (b.length > 12 && b.slice(4, 8).toString('latin1') === 'ftyp' && /avi[fs]/.test(b.slice(8, 12).toString('latin1'))) return 'avif';
43
+ return null;
44
+ }
45
+
46
+ // ════ Smaller copies for the built site ════
47
+ // Wide JPEGs and PNGs get copies at these widths (never wider than the
48
+ // original), so phones download a fraction of the bytes. Pure JavaScript
49
+ // (jimp), no native modules. Copies are kept in .verso-cache/ keyed by the
50
+ // file's contents, so a rebuild only resizes what changed. GIF, WebP and AVIF
51
+ // are used as they are.
52
+
53
+ export const RESIZE_WIDTHS = [640, 1024, 1600];
54
+ export const RESIZE_FROM = 800;
55
+ export const SIZES = '(min-width: 64rem) 64rem, 100vw';
56
+ export const resizeStats = { made: 0, cached: 0 };
57
+
58
+ let jimp = null;
59
+ const loadJimp = async () => {
60
+ if (!jimp) jimp = (await import('jimp')).Jimp;
61
+ return jimp;
62
+ };
63
+ const sha = (buf) => createHash('sha1').update(buf).digest('hex').slice(0, 20);
64
+
65
+ // Writes the copies into outDir and returns [{ width, file }], smallest first.
66
+ export async function resizedCopies(srcPath, outDir, file, { cacheDir, taken = [], warn = () => {} }) {
67
+ const ext = path.extname(file).toLowerCase();
68
+ if (!['.jpg', '.jpeg', '.png'].includes(ext)) return [];
69
+ const buf = fs.readFileSync(srcPath);
70
+ let size;
71
+ try {
72
+ size = readSize(buf);
73
+ } catch {
74
+ return [];
75
+ }
76
+ if (!size?.width || size.width <= RESIZE_FROM) return [];
77
+ const key = sha(buf);
78
+ const base = file.slice(0, -ext.length);
79
+ const out = [];
80
+ let img = null;
81
+ for (const width of RESIZE_WIDTHS.filter((w) => w < size.width)) {
82
+ const name = `${base}-${width}${ext}`;
83
+ if (taken.includes(name)) continue; // the page already has a file with that name
84
+ const cached = path.join(cacheDir, `${key}-${width}${ext}`);
85
+ if (fs.existsSync(cached)) {
86
+ resizeStats.cached += 1;
87
+ } else {
88
+ try {
89
+ if (!img) img = await (await loadJimp()).read(buf);
90
+ const copy = img.clone();
91
+ copy.resize({ w: width });
92
+ const data = ext === '.png' ? await copy.getBuffer('image/png') : await copy.getBuffer('image/jpeg', { quality: 82 });
93
+ fs.mkdirSync(cacheDir, { recursive: true });
94
+ fs.writeFileSync(cached, data);
95
+ resizeStats.made += 1;
96
+ } catch (err) {
97
+ warn(`Couldn't make smaller copies of ${file} (${err.message}). The original is used.`);
98
+ return [];
99
+ }
100
+ }
101
+ fs.copyFileSync(cached, path.join(outDir, name));
102
+ out.push({ width, file: name });
103
+ }
104
+ return out;
105
+ }
106
+
107
+ // Adds srcset and sizes to every <img> whose address has smaller copies.
108
+ export function addSrcset(html, copies) {
109
+ return html.replace(/<img\b[^>]*>/gi, (tag) => {
110
+ if (/\ssrcset\s*=/i.test(tag)) return tag;
111
+ const src = /\ssrc="([^"]+)"/i.exec(tag);
112
+ const set = src && copies.get(src[1]);
113
+ if (!set) return tag;
114
+ return tag.replace(/\s*\/?>$/, (end) => ` srcset="${set}" sizes="${SIZES}"${end}`);
115
+ });
116
+ }
package/src/people.js ADDED
@@ -0,0 +1,286 @@
1
+ // The people who can edit a site that's running as a box (verso serve).
2
+ //
3
+ // Everything is kept in one file, .verso/people.json, which never goes into
4
+ // git: who they are, a salted scrypt hash of each password, and the links
5
+ // (invites, new-password links, the first owner's setup link) that are still
6
+ // waiting to be used. Sessions are signed cookies, so there's no session
7
+ // store to keep or lose.
8
+
9
+ import fs from 'node:fs';
10
+ import path from 'node:path';
11
+ import { randomBytes, scrypt, createHmac, createHash, timingSafeEqual } from 'node:crypto';
12
+ import { VersoError } from './errors.js';
13
+
14
+ export const ROLES = {
15
+ owner: { label: 'Owner', can: 'Can change everything: words, pages, the design, and who can edit.' },
16
+ editor: { label: 'Editor', can: 'Can change words, pictures, blocks and pages, and publish.' },
17
+ };
18
+
19
+ const DAY = 24 * 60 * 60 * 1000;
20
+ const SESSION_DAYS = 30;
21
+ const LINK_DAYS = 7;
22
+ const MAX_TRIES = 5;
23
+ const LOCK_MINUTES = 15;
24
+ export const COOKIE = 'verso';
25
+
26
+ const b64 = (buf) => Buffer.from(buf).toString('base64url');
27
+ const sha = (text) => createHash('sha256').update(String(text)).digest('hex');
28
+ const token = (bytes = 32) => b64(randomBytes(bytes));
29
+ const same = (a, b) => {
30
+ const x = Buffer.from(String(a));
31
+ const y = Buffer.from(String(b));
32
+ return x.length === y.length && timingSafeEqual(x, y);
33
+ };
34
+ const hashPassword = (password, salt) =>
35
+ new Promise((resolve, reject) => {
36
+ scrypt(String(password).normalize('NFKC'), Buffer.from(salt, 'hex'), 64, (err, key) => (err ? reject(err) : resolve(key.toString('hex'))));
37
+ });
38
+
39
+ const cleanName = (name) => String(name ?? '').replace(/\s+/g, ' ').trim().slice(0, 80);
40
+ const cleanEmail = (email) => String(email ?? '').trim().toLowerCase().slice(0, 200);
41
+ const isEmail = (email) => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
42
+
43
+ // "Ada Lovelace" → "AL"; "ada" → "A".
44
+ export const initials = (name) => {
45
+ const words = cleanName(name).split(' ').filter(Boolean);
46
+ if (!words.length) return '?';
47
+ return (words[0][0] + (words.length > 1 ? words[words.length - 1][0] : '')).toUpperCase();
48
+ };
49
+
50
+ export function checkPassword(password, { email = '', name = '' } = {}) {
51
+ const p = String(password ?? '');
52
+ if (p.length < 8) throw new VersoError('Use a password of at least 8 characters.');
53
+ if (p.length > 200) throw new VersoError('That password is too long. Keep it under 200 characters.');
54
+ if (email && p.toLowerCase() === email.toLowerCase()) throw new VersoError('Your password can\'t be your email address.');
55
+ if (name && p.toLowerCase() === name.toLowerCase()) throw new VersoError('Your password can\'t be your name.');
56
+ if (/^(.)\1+$/.test(p) || ['password', '12345678', '123456789', 'qwertyui', 'qwertyuiop', 'letmein123'].includes(p.toLowerCase())) {
57
+ throw new VersoError('That password is too easy to guess. Try a few words together.');
58
+ }
59
+ return p;
60
+ }
61
+
62
+ export function openPeople(root, { now = () => Date.now() } = {}) {
63
+ const dir = path.join(root, '.verso');
64
+ const file = path.join(dir, 'people.json');
65
+
66
+ const read = () => {
67
+ try {
68
+ const data = JSON.parse(fs.readFileSync(file, 'utf8'));
69
+ return { secret: data.secret, people: data.people || [], links: data.links || [] };
70
+ } catch {
71
+ return null;
72
+ }
73
+ };
74
+ const write = (data) => {
75
+ fs.mkdirSync(dir, { recursive: true });
76
+ const tmp = `${file}.${process.pid}.tmp`;
77
+ fs.writeFileSync(tmp, `${JSON.stringify(data, null, 2)}\n`, { mode: 0o600 });
78
+ fs.renameSync(tmp, file);
79
+ };
80
+ const load = () => {
81
+ let data = read();
82
+ if (!data || !data.secret) {
83
+ data = { secret: randomBytes(32).toString('hex'), people: data?.people || [], links: data?.links || [] };
84
+ write(data);
85
+ }
86
+ // Links that have run out are dropped whenever the file is next read.
87
+ const live = data.links.filter((l) => l.expires > now());
88
+ if (live.length !== data.links.length) { data.links = live; write(data); }
89
+ return data;
90
+ };
91
+
92
+ const shown = (p) => ({ id: p.id, name: p.name, email: p.email, role: p.role, initials: initials(p.name), created: p.created, seen: p.seen || null });
93
+ const owners = (data) => data.people.filter((p) => p.role === 'owner');
94
+ const byId = (data, id) => data.people.find((p) => p.id === id);
95
+ const sign = (data, text) => createHmac('sha256', data.secret).update(text).digest('base64url');
96
+
97
+ // ════ Sessions ════
98
+ const cookieFor = (person) => {
99
+ const data = load();
100
+ const expires = now() + SESSION_DAYS * DAY;
101
+ const body = `${person.id}.${expires}`;
102
+ return { value: `${body}.${sign(data, `${body}.${byId(data, person.id).stamp}`)}`, maxAge: SESSION_DAYS * DAY / 1000 };
103
+ };
104
+ const fromCookie = (value) => {
105
+ const [id, expires, mac] = String(value || '').split('.');
106
+ if (!id || !expires || !mac || !(Number(expires) > now())) return null;
107
+ const data = load();
108
+ const person = byId(data, id);
109
+ if (!person || !same(mac, sign(data, `${id}.${expires}.${person.stamp}`))) return null;
110
+ // Halfway through its life, a session is due a fresh cookie.
111
+ return { ...shown(person), renew: Number(expires) - now() < (SESSION_DAYS / 2) * DAY };
112
+ };
113
+
114
+ // ════ Signing in ════
115
+ // Wrong guesses are counted twice over: for one address from one place,
116
+ // and for the address from anywhere, since a guesser can pretend to be
117
+ // in many places. Either count locks that door for a while.
118
+ const tries = new Map(); // "email|ip" and "email|" → { count, until }
119
+ const miss = (key, limit) => {
120
+ const t = tries.get(key);
121
+ const count = (t && t.until === 0 && now() - t.at < LOCK_MINUTES * 60000 ? t.count : 0) + 1;
122
+ tries.set(key, count >= limit ? { count: 0, until: now() + LOCK_MINUTES * 60000, at: now() } : { count, until: 0, at: t && t.until === 0 && count > 1 ? t.at : now() });
123
+ };
124
+ const signIn = async (email, password, ip = '') => {
125
+ const key = `${cleanEmail(email)}|${ip}`;
126
+ const anywhere = `${cleanEmail(email)}|`;
127
+ if ([key, anywhere].some((k) => tries.get(k)?.until > now())) {
128
+ throw new VersoError(`Too many tries. Wait ${LOCK_MINUTES} minutes, or ask an owner of this site for a new link.`);
129
+ }
130
+ const data = load();
131
+ const person = data.people.find((p) => p.email === cleanEmail(email));
132
+ // Hash even when nobody has that email, so the answer takes as long.
133
+ const hash = await hashPassword(password, person ? person.salt : '00'.repeat(16));
134
+ if (!person || !same(hash, person.hash)) {
135
+ miss(key, MAX_TRIES);
136
+ if (ip) miss(anywhere, MAX_TRIES * 4);
137
+ throw new VersoError('That email and password don\'t match.');
138
+ }
139
+ tries.delete(key);
140
+ person.seen = new Date(now()).toISOString();
141
+ write(data);
142
+ return shown(person);
143
+ };
144
+
145
+ // ════ Links: invites, new passwords, the first owner ════
146
+ const makeLink = (data, link) => {
147
+ const raw = token();
148
+ data.links.push({ id: token(6), hash: sha(raw), created: new Date(now()).toISOString(), expires: now() + LINK_DAYS * DAY, ...link });
149
+ return raw;
150
+ };
151
+ const findLink = (data, raw) => data.links.find((l) => same(l.hash, sha(raw)));
152
+
153
+ // The link that makes the first owner. Made fresh each time it's asked
154
+ // for, so an old one in a log can't be used.
155
+ const setupLink = () => {
156
+ const data = load();
157
+ data.links = data.links.filter((l) => l.kind !== 'setup');
158
+ const raw = makeLink(data, { kind: 'setup', role: 'owner' });
159
+ write(data);
160
+ return `/edit/join?t=${raw}`;
161
+ };
162
+
163
+ const invite = ({ name, email, role = 'editor' }, by) => {
164
+ const data = load();
165
+ const clean = { name: cleanName(name), email: cleanEmail(email), role };
166
+ if (!clean.name) throw new VersoError('Add their name.');
167
+ if (!isEmail(clean.email)) throw new VersoError('That doesn\'t look like an email address.');
168
+ if (!ROLES[role]) throw new VersoError('Choose Owner or Editor.');
169
+ if (data.people.some((p) => p.email === clean.email)) throw new VersoError(`${clean.email} can already edit this site.`);
170
+ // Inviting the same address again replaces the earlier invite.
171
+ data.links = data.links.filter((l) => !(l.kind === 'invite' && l.email === clean.email));
172
+ const raw = makeLink(data, { kind: 'invite', ...clean, by: by?.name || '' });
173
+ write(data);
174
+ return { link: `/edit/join?t=${raw}`, ...clean };
175
+ };
176
+
177
+ const resetLink = (id, by) => {
178
+ const data = load();
179
+ const person = byId(data, id);
180
+ if (!person) throw new VersoError('That person can no longer edit this site.');
181
+ data.links = data.links.filter((l) => !(l.kind === 'reset' && l.person === id));
182
+ const raw = makeLink(data, { kind: 'reset', person: id, name: person.name, email: person.email, by: by?.name || '' });
183
+ write(data);
184
+ return { link: `/edit/join?t=${raw}`, name: person.name, email: person.email };
185
+ };
186
+
187
+ // What a link is for, without using it up: shown on the page it opens.
188
+ const peek = (raw) => {
189
+ const link = findLink(load(), raw);
190
+ if (!link) return null;
191
+ return { kind: link.kind, name: link.name || '', email: link.email || '', role: link.role || '', by: link.by || '' };
192
+ };
193
+
194
+ // Use a link: become a person, or set a new password.
195
+ const accept = async (raw, { name, email, password }) => {
196
+ const data = load();
197
+ const link = findLink(data, raw);
198
+ if (!link) throw new VersoError('This link has been used or has run out. Ask an owner of the site for a new one.');
199
+ let person;
200
+ if (link.kind === 'reset') {
201
+ person = byId(data, link.person);
202
+ if (!person) throw new VersoError('That person can no longer edit this site.');
203
+ checkPassword(password, person);
204
+ } else {
205
+ const who = { name: cleanName(name || link.name), email: cleanEmail(link.kind === 'setup' ? email : link.email) };
206
+ if (!who.name) throw new VersoError('Add your name.');
207
+ if (!isEmail(who.email)) throw new VersoError('That doesn\'t look like an email address.');
208
+ if (data.people.some((p) => p.email === who.email)) throw new VersoError(`${who.email} can already edit this site. Sign in instead.`);
209
+ checkPassword(password, who);
210
+ person = { id: token(9), ...who, role: link.role, created: new Date(now()).toISOString() };
211
+ data.people.push(person);
212
+ }
213
+ person.salt = randomBytes(16).toString('hex');
214
+ person.hash = await hashPassword(password, person.salt);
215
+ person.stamp = token(9); // signs every other browser out
216
+ person.seen = new Date(now()).toISOString();
217
+ data.links = data.links.filter((l) => l !== link);
218
+ write(data);
219
+ return shown(person);
220
+ };
221
+
222
+ const changePassword = async (id, current, next) => {
223
+ const data = load();
224
+ const person = byId(data, id);
225
+ if (!person) throw new VersoError('You can no longer edit this site.');
226
+ if (!same(await hashPassword(current, person.salt), person.hash)) throw new VersoError('That isn\'t your current password.');
227
+ checkPassword(next, person);
228
+ person.salt = randomBytes(16).toString('hex');
229
+ person.hash = await hashPassword(next, person.salt);
230
+ person.stamp = token(9);
231
+ write(data);
232
+ return shown(person);
233
+ };
234
+
235
+ // ════ Managing people ════
236
+ const setRole = (id, role) => {
237
+ const data = load();
238
+ const person = byId(data, id);
239
+ if (!person) throw new VersoError('That person can no longer edit this site.');
240
+ if (!ROLES[role]) throw new VersoError('Choose Owner or Editor.');
241
+ if (person.role === 'owner' && role !== 'owner' && owners(data).length === 1) {
242
+ throw new VersoError('A site needs at least one owner. Make someone else an owner first.');
243
+ }
244
+ person.role = role;
245
+ write(data);
246
+ return shown(person);
247
+ };
248
+
249
+ const remove = (id) => {
250
+ const data = load();
251
+ const person = byId(data, id);
252
+ if (!person) return null;
253
+ if (person.role === 'owner' && owners(data).length === 1) {
254
+ throw new VersoError('A site needs at least one owner. Make someone else an owner first.');
255
+ }
256
+ data.people = data.people.filter((p) => p !== person);
257
+ data.links = data.links.filter((l) => l.person !== id);
258
+ write(data);
259
+ return shown(person);
260
+ };
261
+
262
+ const cancelLink = (linkId) => {
263
+ const data = load();
264
+ const before = data.links.length;
265
+ data.links = data.links.filter((l) => l.id !== linkId);
266
+ if (data.links.length !== before) write(data);
267
+ return data.links.length !== before;
268
+ };
269
+
270
+ const list = () => {
271
+ const data = load();
272
+ return {
273
+ people: data.people.map(shown).sort((a, b) => (a.role === b.role ? a.name.localeCompare(b.name) : a.role === 'owner' ? -1 : 1)),
274
+ waiting: data.links.filter((l) => l.kind === 'invite').map((l) => ({
275
+ id: l.id, name: l.name, email: l.email, role: l.role, initials: initials(l.name), days: Math.max(1, Math.ceil((l.expires - now()) / DAY)),
276
+ })),
277
+ };
278
+ };
279
+
280
+ return {
281
+ file,
282
+ any: () => load().people.length > 0,
283
+ get: (id) => { const p = byId(load(), id); return p ? shown(p) : null; },
284
+ cookieFor, fromCookie, signIn, setupLink, invite, resetLink, peek, accept, changePassword, setRole, remove, cancelLink, list,
285
+ };
286
+ }
package/src/rich.js ADDED
@@ -0,0 +1,124 @@
1
+ // Rich text is stored as clean HTML, one file per field, with bare tags and
2
+ // no classes. Each field turns on only the tools it allows:
3
+ //
4
+ // {{ body:rich:headings:lists:links:images:tables:quotes:callouts:embeds }}
5
+ //
6
+ // Paragraphs, bold and italic are always on. Everything is checked against
7
+ // those tools when it's saved, and the site's Elevate classes are added only
8
+ // when the page is rendered (see "rich" in verso.json).
9
+
10
+ import sanitizeHtml from 'sanitize-html';
11
+ import { EMBED_SRC, videoEmbedUrl } from './video.js';
12
+
13
+ const TOOL_TAGS = {
14
+ headings: ['h2', 'h3', 'h4'],
15
+ lists: ['ul', 'ol', 'li'],
16
+ links: ['a'],
17
+ images: ['figure', 'img', 'figcaption'],
18
+ tables: ['table', 'thead', 'tbody', 'tr', 'th', 'td'],
19
+ quotes: ['blockquote'],
20
+ callouts: ['aside'],
21
+ embeds: ['figure', 'iframe', 'figcaption'],
22
+ code: ['pre', 'code'],
23
+ };
24
+ const BASE_TAGS = ['p', 'br', 'strong', 'em'];
25
+
26
+ // Every element rich text can contain, for the class map and for docs.
27
+ export const RICH_ELEMENTS = [...new Set([...BASE_TAGS.filter((t) => t !== 'br'), ...Object.values(TOOL_TAGS).flat()])];
28
+
29
+ // An image in rich text is a file in the page's own folder.
30
+ export const IMAGE_FILE = /^[a-zA-Z0-9][a-zA-Z0-9._-]*\.(jpe?g|png|gif|webp|avif)$/i;
31
+
32
+ export { EMBED_SRC, videoEmbedUrl };
33
+
34
+ export function sanitizeRich(html, tools = []) {
35
+ const allowed = [...BASE_TAGS, ...tools.flatMap((t) => TOOL_TAGS[t] || [])];
36
+ const clean = sanitizeHtml(String(html || ''), {
37
+ allowedTags: allowed,
38
+ allowedAttributes: {
39
+ a: ['href'],
40
+ img: ['src', 'alt'],
41
+ th: ['colspan', 'rowspan'],
42
+ td: ['colspan', 'rowspan'],
43
+ iframe: ['src', 'title', 'loading', 'allowfullscreen'],
44
+ code: ['data-lang'],
45
+ },
46
+ allowedIframeHostnames: ['www.youtube-nocookie.com', 'player.vimeo.com'],
47
+ allowIframeRelativeUrls: false,
48
+ allowedSchemes: ['http', 'https', 'mailto', 'tel'],
49
+ allowedSchemesAppliedToAttributes: ['href'],
50
+ allowProtocolRelative: false,
51
+ // Pasted headings become the nearest allowed level, or paragraphs.
52
+ transformTags: {
53
+ ...(tools.includes('headings')
54
+ ? { b: 'strong', i: 'em', h1: 'h2', h5: 'h4', h6: 'h4', div: 'p' }
55
+ : { b: 'strong', i: 'em', h1: 'p', h2: 'p', h3: 'p', h4: 'p', h5: 'p', h6: 'p', div: 'p' }),
56
+ // Video links become one canonical address, lazy-loaded.
57
+ iframe: (tagName, attribs) => {
58
+ const src = videoEmbedUrl(attribs.src) || attribs.src || '';
59
+ const title = String(attribs.title || (src.includes('vimeo') ? 'Vimeo video' : 'YouTube video')).slice(0, 300);
60
+ return { tagName, attribs: { src, title, loading: 'lazy', allowfullscreen: '' } };
61
+ },
62
+ },
63
+ exclusiveFilter: (frame) =>
64
+ (frame.tag === 'img' && !IMAGE_FILE.test(frame.attribs.src || '')) ||
65
+ (frame.tag === 'iframe' && !EMBED_SRC.test(frame.attribs.src || '')),
66
+ nonTextTags: ['style', 'script', 'textarea', 'option', 'noscript', 'template'],
67
+ });
68
+ return format(clean);
69
+ }
70
+
71
+ // One top-level block per line, so git diffs show what changed.
72
+ function format(html) {
73
+ // Code blocks keep their whitespace exactly, so set them aside first.
74
+ const blocks = [];
75
+ const held = html.replace(/<pre>[\s\S]*?<\/pre>/g, (m) => `\u0000${blocks.push(m) - 1}\u0000`);
76
+ return held
77
+ .replace(/>\s*\n\s*</g, '><')
78
+ .replace(/<\/(p|h2|h3|h4|ul|ol|blockquote|aside|figure|table|pre)>(?!$)/g, '</$1>\n')
79
+ .replace(/\u0000(\d+)\u0000/g, (m, i) => `${blocks[Number(i)]}\n`)
80
+ .replace(/\n+$/, '')
81
+ .trim();
82
+ }
83
+
84
+ export function richIsEmpty(html) {
85
+ const s = String(html || '');
86
+ return !/<(img|iframe)\b/i.test(s) && s.replace(/<[^>]*>/g, '').replace(/&nbsp;|\s/g, '') === '';
87
+ }
88
+
89
+ const escapeAttr = (v) => String(v).replace(/&/g, '&amp;').replace(/"/g, '&quot;').replace(/</g, '&lt;');
90
+
91
+ // Adds the site's classes to each element, and turns image file names into
92
+ // addresses with their size, so the page doesn't jump as images load.
93
+ export function applyRichClasses(html, classes = {}, { base = '/', imageSize = null } = {}) {
94
+ // "pre code" styles the code inside a code block apart from inline code.
95
+ let inPre = 0;
96
+ return String(html || '').replace(/<(\/?)([a-z][a-z0-9]*)(\s[^>]*)?>/gi, (whole, close, tag, attrs = '') => {
97
+ const name = tag.toLowerCase();
98
+ if (name === 'pre') inPre += close ? -1 : 1;
99
+ if (close) return whole;
100
+ let extra = '';
101
+ if (name === 'img') {
102
+ attrs = attrs.replace(/\ssrc="([^"]*)"/, (m, src) => {
103
+ if (!IMAGE_FILE.test(src)) return m;
104
+ const size = imageSize ? imageSize(src) : null;
105
+ return ` src="${escapeAttr(base + encodeURIComponent(src))}"${size ? ` width="${size.width}" height="${size.height}"` : ''} loading="lazy" decoding="async"`;
106
+ });
107
+ }
108
+ const cls = name === 'code' && inPre > 0 && 'pre code' in classes ? classes['pre code'] : classes[name];
109
+ if (cls) extra = ` class="${escapeAttr(cls)}"`;
110
+ return `<${tag}${extra}${attrs}>`;
111
+ });
112
+ }
113
+
114
+ // Checks the class map in verso.json: only known elements.
115
+ export function checkRichClasses(map) {
116
+ const problems = [];
117
+ if (map == null) return problems;
118
+ if (typeof map !== 'object' || Array.isArray(map)) return ['"rich" should map element names to class strings, like { "p": "text:ink" }.'];
119
+ Object.entries(map).forEach(([tag, cls]) => {
120
+ if (!RICH_ELEMENTS.includes(tag) && tag !== 'pre code') problems.push(`"${tag}" isn't an element rich text can contain. Use: ${RICH_ELEMENTS.join(', ')}.`);
121
+ else if (typeof cls !== 'string') problems.push(`The classes for "${tag}" should be a string.`);
122
+ });
123
+ return problems;
124
+ }