inlaycms 0.4.0 → 0.5.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 (131) hide show
  1. package/README.md +18 -709
  2. package/assets/admin/admin.css +1 -1
  3. package/assets/admin/editor.js +63 -46
  4. package/assets/site/consent.js +1 -0
  5. package/dist/adapters/admin/context.d.ts +1 -1
  6. package/dist/adapters/admin/context.js +1 -0
  7. package/dist/adapters/admin/routes.d.ts +2 -0
  8. package/dist/adapters/admin/routes.js +2 -0
  9. package/dist/adapters/admin/screens/backups.js +2 -2
  10. package/dist/adapters/admin/screens/editor.js +2 -1
  11. package/dist/adapters/admin/screens/integrations.d.ts +4 -0
  12. package/dist/adapters/admin/screens/integrations.js +140 -0
  13. package/dist/adapters/admin/screens/lists.js +2 -1
  14. package/dist/adapters/admin/screens/releases.js +1 -1
  15. package/dist/adapters/admin/views/layout.js +3 -0
  16. package/dist/adapters/cli/bin.js +8 -3
  17. package/dist/adapters/mcp/tools/read.js +17 -2
  18. package/dist/adapters/mcp/tools/write.js +4 -0
  19. package/dist/adapters/site/cache.d.ts +8 -2
  20. package/dist/adapters/site/cache.js +13 -4
  21. package/dist/adapters/site/code-files.d.ts +44 -0
  22. package/dist/adapters/site/code-files.js +212 -0
  23. package/dist/adapters/site/consent.d.ts +9 -0
  24. package/dist/adapters/site/consent.js +26 -0
  25. package/dist/adapters/site/context.d.ts +5 -0
  26. package/dist/adapters/site/context.js +97 -20
  27. package/dist/adapters/site/csp.d.ts +11 -0
  28. package/dist/adapters/site/csp.js +36 -0
  29. package/dist/adapters/site/head.js +1 -14
  30. package/dist/adapters/site/headers.d.ts +5 -2
  31. package/dist/adapters/site/headers.js +13 -6
  32. package/dist/adapters/site/integrations.d.ts +48 -0
  33. package/dist/adapters/site/integrations.js +118 -0
  34. package/dist/adapters/site/media-routes.d.ts +2 -0
  35. package/dist/adapters/site/media-routes.js +2 -1
  36. package/dist/adapters/site/plugin.d.ts +2 -0
  37. package/dist/adapters/site/plugin.js +64 -34
  38. package/dist/adapters/site/render.d.ts +31 -14
  39. package/dist/adapters/site/render.js +26 -5
  40. package/dist/adapters/site/routes.d.ts +3 -0
  41. package/dist/adapters/site/routes.js +7 -3
  42. package/dist/adapters/site/scripts.d.ts +6 -0
  43. package/dist/adapters/site/scripts.js +27 -0
  44. package/dist/core/auth/roles.d.ts +1 -1
  45. package/dist/core/auth/roles.js +1 -0
  46. package/dist/core/boot.d.ts +2 -0
  47. package/dist/core/boot.js +3 -0
  48. package/dist/core/content/shipped-input.js +1 -2
  49. package/dist/core/content/validate.d.ts +7 -0
  50. package/dist/core/content/validate.js +24 -1
  51. package/dist/core/core.d.ts +29 -0
  52. package/dist/core/core.js +10 -2
  53. package/dist/core/db/migrate.js +2 -0
  54. package/dist/core/db/migrations/0008_integrations.d.ts +3 -0
  55. package/dist/core/db/migrations/0008_integrations.js +11 -0
  56. package/dist/core/db/schema.d.ts +11 -0
  57. package/dist/core/export/export.js +4 -0
  58. package/dist/core/export/format.d.ts +11 -0
  59. package/dist/core/export/format.js +4 -0
  60. package/dist/core/export/import.js +2 -1
  61. package/dist/core/export/replace.d.ts +6 -1
  62. package/dist/core/export/replace.js +4 -1
  63. package/dist/core/export/report.d.ts +6 -0
  64. package/dist/core/export/report.js +7 -0
  65. package/dist/core/fields/builtins.d.ts +4 -0
  66. package/dist/core/fields/builtins.js +11 -1
  67. package/dist/core/fields/widgets.js +5 -1
  68. package/dist/core/integrations/integrations.d.ts +32 -0
  69. package/dist/core/integrations/integrations.js +80 -0
  70. package/dist/core/integrations/warnings.d.ts +4 -0
  71. package/dist/core/integrations/warnings.js +29 -0
  72. package/dist/core/media/store.d.ts +2 -0
  73. package/dist/core/media/store.js +17 -1
  74. package/dist/core/media/variants.d.ts +14 -0
  75. package/dist/core/media/variants.js +54 -0
  76. package/dist/core/messages/en.d.ts +73 -0
  77. package/dist/core/messages/en.js +73 -0
  78. package/dist/core/registry/code-image.d.ts +16 -0
  79. package/dist/core/registry/code-image.js +13 -0
  80. package/dist/core/registry/define.d.ts +7 -0
  81. package/dist/core/registry/define.js +2 -0
  82. package/dist/core/registry/designed.d.ts +6 -0
  83. package/dist/core/registry/designed.js +8 -0
  84. package/dist/core/registry/integration.d.ts +48 -0
  85. package/dist/core/registry/integration.js +29 -0
  86. package/dist/core/registry/js.d.ts +9 -0
  87. package/dist/core/registry/js.js +39 -0
  88. package/dist/core/registry/registry.js +46 -0
  89. package/dist/core/registry/render.d.ts +39 -4
  90. package/dist/core/release/bundle.d.ts +3 -1
  91. package/dist/core/release/bundle.js +169 -11
  92. package/dist/core/release/manifest.d.ts +29 -1
  93. package/dist/core/release/manifest.js +26 -1
  94. package/dist/core/release/pack.js +13 -2
  95. package/dist/core/release/pointer.js +14 -3
  96. package/dist/core/release/read.d.ts +2 -0
  97. package/dist/core/release/read.js +1 -0
  98. package/dist/core/report.d.ts +3 -0
  99. package/dist/core/richtext/headings.d.ts +10 -0
  100. package/dist/core/richtext/headings.js +37 -0
  101. package/dist/core/richtext/html.d.ts +10 -1
  102. package/dist/core/richtext/html.js +17 -6
  103. package/dist/core/richtext/markdown-text.d.ts +24 -0
  104. package/dist/core/richtext/markdown-text.js +38 -0
  105. package/dist/core/richtext/markdown.js +44 -3
  106. package/dist/core/richtext/schema.d.ts +12 -3
  107. package/dist/core/richtext/schema.js +34 -0
  108. package/dist/core/site/live.d.ts +6 -0
  109. package/dist/core/site/live.js +25 -0
  110. package/dist/host/app.d.ts +2 -0
  111. package/dist/host/app.js +1 -0
  112. package/dist/host/diff.d.ts +11 -0
  113. package/dist/host/diff.js +40 -0
  114. package/dist/host/drain.d.ts +12 -0
  115. package/dist/host/drain.js +34 -0
  116. package/dist/host/ipc.d.ts +2 -0
  117. package/dist/host/ipc.js +5 -1
  118. package/dist/host/preview-worker.js +2 -2
  119. package/dist/host/primary.js +15 -4
  120. package/dist/host/push.js +1 -1
  121. package/dist/host/serve.js +1 -1
  122. package/dist/host/store.d.ts +1 -2
  123. package/dist/host/store.js +32 -6
  124. package/dist/host/worker.js +6 -0
  125. package/dist/image-modules.d.ts +29 -0
  126. package/dist/image-modules.js +1 -0
  127. package/dist/index.d.ts +7 -1
  128. package/dist/index.js +4 -0
  129. package/dist/site.d.ts +8 -1
  130. package/dist/site.js +5 -0
  131. package/package.json +5 -1
@@ -0,0 +1,118 @@
1
+ import { t } from '../../core/messages/index.js';
2
+ import { escapeHtml, renderToString } from '../../jsx/html.js';
3
+ import { buildCsp } from './csp.js';
4
+ /**
5
+ * `generation`: changes on every live change (the page cache's), so a change to the settings is seen on the next call.
6
+ * `log`: where render failures go.
7
+ */
8
+ export function createSiteIntegrations(opts) {
9
+ const { core, site, generation, consentUrl, log } = opts;
10
+ const ownPolicy = Object.keys(site.headers).some((name) => name.toLowerCase() === 'content-security-policy');
11
+ let memo = null;
12
+ function active() {
13
+ const current = generation();
14
+ if (memo !== null && memo.generation === current)
15
+ return memo.active;
16
+ const read = core.activeIntegrations();
17
+ memo = { generation: current, active: read };
18
+ // A failed read isn't remembered: the next call tries again.
19
+ read.catch(() => {
20
+ if (memo?.active === read)
21
+ memo = null;
22
+ });
23
+ return read;
24
+ }
25
+ return {
26
+ active,
27
+ async policy(hashes) {
28
+ if (ownPolicy)
29
+ return null;
30
+ // When the settings can't be read, no integration's sources are allowed: the policy fails closed.
31
+ const integrations = (await active().catch(() => [])).map((a) => a.def.csp);
32
+ return buildCsp({ site: site.csp, integrations, ...(hashes && { hashes }) });
33
+ },
34
+ consentUrl,
35
+ async render(page, script) {
36
+ let list;
37
+ try {
38
+ list = await active();
39
+ }
40
+ catch (error) {
41
+ log(error, t('log.integrationsUnreadable'));
42
+ return { head: '', bodyStart: '', bodyEnd: '' };
43
+ }
44
+ return renderIntegrations(list, page, script, {
45
+ consentUrl,
46
+ log: (name, error) => log(error, t('log.integrationFailed', { name })),
47
+ });
48
+ },
49
+ };
50
+ }
51
+ const SLOTS = ['head', 'bodyStart', 'bodyEnd'];
52
+ /**
53
+ * Each of `active`'s slots rendered for `page`, in order, skipping in preview the ones without `preview: true`. A
54
+ * gated integration's output is wrapped in an inert `<template data-inlay-consent>`, and `head` then ends with the
55
+ * consent script. An integration whose render throws is logged and left out of this page.
56
+ */
57
+ export async function renderIntegrations(active, page, script, opts) {
58
+ const out = { head: '', bodyStart: '', bodyEnd: '' };
59
+ let gated = false;
60
+ for (const { def, values } of active) {
61
+ if (page.preview && !def.preview)
62
+ continue;
63
+ const own = { head: '', bodyStart: '', bodyEnd: '' };
64
+ try {
65
+ for (const slot of SLOTS) {
66
+ const render = def[slot];
67
+ if (render)
68
+ own[slot] = await renderToString(render(values, { ...page, script }));
69
+ }
70
+ }
71
+ catch (error) {
72
+ opts.log(def.name, error);
73
+ continue;
74
+ }
75
+ for (const slot of SLOTS) {
76
+ const html = own[slot];
77
+ if (html === '')
78
+ continue;
79
+ if (def.consent === undefined) {
80
+ out[slot] += html;
81
+ }
82
+ else {
83
+ out[slot] += `<template data-inlay-consent="${escapeHtml(def.consent)}">${html}</template>`;
84
+ gated = true;
85
+ }
86
+ }
87
+ }
88
+ if (gated)
89
+ out.head += `<script src="${escapeHtml(opts.consentUrl)}" defer></script>`;
90
+ return out;
91
+ }
92
+ const BODY = /<body\b[^>]*>/i;
93
+ /**
94
+ * `html` with `rendered.head` before its first `</head>`, `bodyStart` right after its `<body>` and `bodyEnd` before
95
+ * its last `</body>`. A slot whose marker is missing is left out.
96
+ */
97
+ export function injectIntegrations(html, rendered) {
98
+ const inserts = [];
99
+ const head = html.search(/<\/head>/i);
100
+ if (head >= 0 && rendered.head !== '')
101
+ inserts.push({ at: head, text: rendered.head });
102
+ const body = BODY.exec(html);
103
+ if (body && rendered.bodyStart !== '')
104
+ inserts.push({ at: body.index + body[0].length, text: rendered.bodyStart });
105
+ let end = -1;
106
+ for (const match of html.matchAll(/<\/body>/gi))
107
+ end = match.index;
108
+ if (end >= 0 && rendered.bodyEnd !== '')
109
+ inserts.push({ at: end, text: rendered.bodyEnd });
110
+ inserts.sort((a, b) => a.at - b.at);
111
+ let out = '';
112
+ let from = 0;
113
+ for (const { at, text } of inserts) {
114
+ out += html.slice(from, at) + text;
115
+ from = at;
116
+ }
117
+ return out + html.slice(from);
118
+ }
@@ -1,4 +1,6 @@
1
1
  import type { FastifyInstance } from 'fastify';
2
2
  import type { Core } from '../../core/core.js';
3
+ /** A variant's file name: `<width>.<format>`. */
4
+ export declare const VARIANT: RegExp;
3
5
  /** `GET /media/:id` (the original) and `GET /media/:id/:width.:format` (a resized variant). */
4
6
  export declare function registerMediaRoutes(app: FastifyInstance, core: Core): void;
@@ -2,7 +2,8 @@ import { createReadStream } from 'node:fs';
2
2
  import { InlayError } from '../../core/errors.js';
3
3
  import { isRasterImage } from '../../core/media/detect.js';
4
4
  import { t } from '../../core/messages/index.js';
5
- const VARIANT = /^([1-9][0-9]{0,4})\.(webp|avif|jpeg|png)$/;
5
+ /** A variant's file name: `<width>.<format>`. */
6
+ export const VARIANT = /^([1-9][0-9]{0,4})\.(webp|avif|jpeg|png)$/;
6
7
  /** RFC 5987 `ext-value` encoding for `filename*`. */
7
8
  function encodeFilename(name) {
8
9
  return encodeURIComponent(name).replace(/['()*]/g, (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`);
@@ -51,6 +51,8 @@ export interface InlayOptions {
51
51
  host?: HostApi;
52
52
  /** A loaded release's shipped files, by source as written in the site. */
53
53
  shippedFiles?: ReadonlyMap<string, string>;
54
+ /** As `shippedFiles`, only the images `.md` files the site imports name. */
55
+ codeFiles?: ReadonlyMap<string, string>;
54
56
  /**
55
57
  * Nothing can be changed: every write through the core is refused with `error.previewReadOnly`, and the admin and
56
58
  * `/api/auth` answer their write requests (other than logging in and out) with 403. Boot still applies shipped
@@ -20,16 +20,19 @@ import { fetchRemoteFile } from '../mcp/fetch-url.js';
20
20
  import { registerMcpRoute } from '../mcp/route.js';
21
21
  import { createInlayMcpHandler } from '../mcp/server.js';
22
22
  import { sendWebResponse, toWebRequest } from '../web.js';
23
+ import { loadConsentAsset, registerConsentRoute } from './consent.js';
23
24
  import { publicAssets } from './assets.js';
24
25
  import { cacheControl, etagMatches, PageCache, response } from './cache.js';
25
26
  import { createRenderContext } from './context.js';
26
27
  import { registerSiteHeaders, siteHeaders } from './headers.js';
28
+ import { createSiteIntegrations } from './integrations.js';
27
29
  import { startBackupSchedule } from './backup-schedule.js';
28
30
  import { isLockedRequest, registerSiteLockGate, registerUnlockRoute } from './lock.js';
31
+ import { codeFilesFor, registerCodeFileRoutes } from './code-files.js';
29
32
  import { registerMediaRoutes } from './media-routes.js';
30
33
  import { registerPublicRoutes } from './public.js';
31
34
  import { previewLink, readPreview, registerPreviewRoutes } from './preview.js';
32
- import { catalogPage, renderPage } from './render.js';
35
+ import { catalogPage, renderPageResult } from './render.js';
33
36
  import { registerReleaseRoutes } from './routes.js';
34
37
  import { renderSitemap } from './sitemap.js';
35
38
  /** Where tests find the plugin's `AuthService` on `app.inlay`; not part of the public API. */
@@ -116,7 +119,7 @@ function createApi(core, cache, service, opts) {
116
119
  };
117
120
  return Object.defineProperty(api, AUTH, { value: service, enumerable: false });
118
121
  }
119
- function registerSiteRoutes(app, core, cache, opts) {
122
+ function registerSiteRoutes(app, core, cache, integrations, opts) {
120
123
  const { registry } = core;
121
124
  const { notFound } = registry.site;
122
125
  const { baseUrl, cdn, assets } = opts;
@@ -125,9 +128,13 @@ function registerSiteRoutes(app, core, cache, opts) {
125
128
  if (notFound !== null) {
126
129
  const doc = await core.liveSingleton(notFound, locale, { state });
127
130
  if (doc)
128
- return renderPage(core, doc, { state, page: 1, baseUrl, assets, ...banner });
131
+ return renderPageResult(core, doc, { state, page: 1, baseUrl, assets, integrations, ...banner });
129
132
  }
130
- return catalogPage('site.notFound.title', 'site.notFound');
133
+ return { html: catalogPage('site.notFound.title', 'site.notFound'), scriptHashes: [] };
134
+ }
135
+ /** `page` as a response carrying its own content-security-policy, when Inlay sets one. */
136
+ async function pageResponse(status, page) {
137
+ return response(status, page.html, HTML, (await integrations.policy(page.scriptHashes)) ?? undefined);
131
138
  }
132
139
  function localeOf(rawPath) {
133
140
  const path = normalizePath(rawPath);
@@ -139,29 +146,34 @@ function registerSiteRoutes(app, core, cache, opts) {
139
146
  if (hit !== undefined)
140
147
  reply.header('x-inlay-cache', hit ? 'hit' : 'miss');
141
148
  reply.header('cache-control', control).header('vary', 'Cookie').header('etag', res.etag);
149
+ if (res.csp !== undefined)
150
+ reply.header('content-security-policy', res.csp);
142
151
  if (etagMatches(request.headers['if-none-match'], res.etag))
143
152
  return reply.code(304).send();
144
153
  return reply.code(res.status).type(res.type).send(res.body);
145
154
  }
146
155
  /** Preview responses are never stored or revalidated. */
147
- function sendPreview(reply, status, body) {
148
- return reply.code(status).type(HTML).send(body);
156
+ async function sendPreview(reply, status, page) {
157
+ const csp = await integrations.policy(page.scriptHashes);
158
+ if (csp !== null)
159
+ reply.header('content-security-policy', csp);
160
+ return reply.code(status).type(HTML).send(page.html);
149
161
  }
150
162
  /** Serves `key` from the cache, or renders it and stores the result unless a live change landed meanwhile. */
151
- async function cached(request, reply, key, status, type, render) {
163
+ async function cached(request, reply, key, render) {
152
164
  if (!cache)
153
- return send(request, reply, response(status, await render(), type), undefined);
165
+ return send(request, reply, await render(), undefined);
154
166
  const hit = cache.get(key);
155
167
  if (hit)
156
168
  return send(request, reply, hit, true);
157
169
  const generation = cache.generation;
158
- const res = response(status, await render(), type);
170
+ const res = await render();
159
171
  cache.set(key, res, generation);
160
172
  return send(request, reply, res, false);
161
173
  }
162
174
  const missing = async (request, reply, locale, state) => state === 'preview'
163
175
  ? sendPreview(reply, 404, await notFoundPage(locale, state))
164
- : cached(request, reply, `404:${locale}`, 404, HTML, () => notFoundPage(locale, state));
176
+ : cached(request, reply, `404:${locale}`, async () => pageResponse(404, await notFoundPage(locale, state)));
165
177
  /** A cookie that previews a staged release reaches this app only when that preview isn't available: the live site answers. */
166
178
  function stateOf(request) {
167
179
  if (request.headers.cookie === undefined)
@@ -202,10 +214,10 @@ function registerSiteRoutes(app, core, cache, opts) {
202
214
  }
203
215
  }
204
216
  if (match.kind === 'page') {
205
- const html = await renderPage(core, match.document, { state, page: pageNumber, baseUrl, assets, ...banner });
217
+ const page = await renderPageResult(core, match.document, { state, page: pageNumber, baseUrl, assets, integrations, ...banner });
206
218
  if (preview)
207
- return sendPreview(reply, 200, html);
208
- const res = response(200, html, HTML);
219
+ return await sendPreview(reply, 200, page);
220
+ const res = await pageResponse(200, page);
209
221
  if (cache && key !== null) {
210
222
  cache.set(key, res, generation);
211
223
  return send(request, reply, res, false);
@@ -229,7 +241,7 @@ function registerSiteRoutes(app, core, cache, opts) {
229
241
  // A site that is down has no sitemap to give: an empty one would tell search engines its pages are gone.
230
242
  app.get('/sitemap.xml', async (request, reply) => opts.noSite === 'unavailable'
231
243
  ? unavailable(request, reply)
232
- : cached(request, reply, 'sitemap.xml', 200, 'application/xml', async () => renderSitemap(await core.sitemapEntries(), baseUrl)));
244
+ : cached(request, reply, 'sitemap.xml', async () => response(200, renderSitemap(await core.sitemapEntries(), baseUrl), 'application/xml')));
233
245
  app.get('/robots.txt', async (request, reply) => {
234
246
  reply.type('text/plain; charset=utf-8');
235
247
  if (isLockedRequest(request))
@@ -325,6 +337,7 @@ const plugin = async (app, opts) => {
325
337
  ...(opts.now && { now: opts.now }),
326
338
  ...(opts.content && { content: opts.content }),
327
339
  ...(opts.shippedFiles && { shippedFiles: opts.shippedFiles }),
340
+ ...(opts.codeFiles && { codeFiles: opts.codeFiles }),
328
341
  auth: { secret, baseUrl, ...(opts.rateLimit !== undefined && { rateLimit: opts.rateLimit }) },
329
342
  });
330
343
  const { db, report, auth } = booted;
@@ -350,12 +363,42 @@ const plugin = async (app, opts) => {
350
363
  }
351
364
  }
352
365
  const core = opts.readOnly ? readOnlyCore(booted.core) : booted.core;
353
- for (const warning of report.warnings)
354
- app.log.warn('document' in warning ? { document: warning.document } : { redirect: warning.redirect }, warning.message);
366
+ for (const warning of report.warnings) {
367
+ if ('document' in warning)
368
+ app.log.warn({ document: warning.document }, warning.message);
369
+ else if ('redirect' in warning)
370
+ app.log.warn({ redirect: warning.redirect }, warning.message);
371
+ else
372
+ app.log.warn(warning.message);
373
+ }
355
374
  for (const warning of report.shipped.warnings ?? [])
356
375
  app.log.warn(warning.message);
357
376
  const now = opts.now ?? (() => new Date());
358
- registerSiteHeaders(app, siteHeaders(baseUrl, registry.site.headers));
377
+ // A commit from another connection (the other worker during a `serve` swap, a second `inlaycms dev`) changes
378
+ // data_version; this connection's own writes don't, and the live ones among them clear the cache below.
379
+ let seen = dataVersion(db);
380
+ const changedElsewhere = () => {
381
+ const version = dataVersion(db);
382
+ if (version === seen)
383
+ return false;
384
+ seen = version;
385
+ return true;
386
+ };
387
+ const cache = opts.cache === false ? undefined : new PageCache(opts.cache?.maxEntries ?? 500, changedElsewhere);
388
+ // Without a page cache, an empty one still counts live changes, so the integrations' settings are read again after one.
389
+ const generations = cache ?? new PageCache(0, changedElsewhere);
390
+ const stopGenerations = core.onLiveChange(() => generations.clear());
391
+ app.addHook('onClose', async () => stopGenerations());
392
+ const consentAsset = await loadConsentAsset();
393
+ registerConsentRoute(app, consentAsset);
394
+ const siteIntegrations = createSiteIntegrations({
395
+ core,
396
+ site: registry.site,
397
+ generation: () => generations.generation,
398
+ consentUrl: consentAsset.url,
399
+ log: (err, message) => app.log.error({ err }, message),
400
+ });
401
+ registerSiteHeaders(app, siteHeaders(baseUrl, registry.site.headers), () => siteIntegrations.policy());
359
402
  const lockOptions = { db, service: auth, secret, baseUrl, now, publicPaths };
360
403
  registerSiteLockGate(app, { ...lockOptions, ...(opts.preview === 'forced' && opts.release && { release: opts.release.id }) });
361
404
  registerUnlockRoute(app, { ...lockOptions, rateLimit: opts.rateLimit !== false });
@@ -375,21 +418,6 @@ const plugin = async (app, opts) => {
375
418
  await db.destroy();
376
419
  });
377
420
  const siteAssets = publicAssets(opts.publicDir ?? null);
378
- // A commit from another connection (the other worker during a `serve` swap, a second `inlaycms dev`) changes
379
- // data_version; this connection's own writes don't, and the live ones among them clear the cache below.
380
- let seen = dataVersion(db);
381
- const changedElsewhere = () => {
382
- const version = dataVersion(db);
383
- if (version === seen)
384
- return false;
385
- seen = version;
386
- return true;
387
- };
388
- const cache = opts.cache === false ? undefined : new PageCache(opts.cache?.maxEntries ?? 500, changedElsewhere);
389
- if (cache) {
390
- const stop = core.onLiveChange(() => cache.clear());
391
- app.addHook('onClose', async () => stop());
392
- }
393
421
  if (baseUrl.startsWith('https:') && !app.initialConfig.https)
394
422
  warnWithoutTrustProxy(app, baseUrl);
395
423
  app.decorate('inlay', createApi(core, cache, auth, { baseUrl, secret, now, host: opts.host ?? null, assets: siteAssets }));
@@ -415,6 +443,7 @@ const plugin = async (app, opts) => {
415
443
  release: opts.release ?? null,
416
444
  ...(opts.readOnly && { readOnly: true }),
417
445
  ...(opts.releasesDir !== undefined && { releasesDir: opts.releasesDir }),
446
+ mediaDir: opts.media ?? next('media'),
418
447
  ...(opts.trustedKeys && { trustedKeys: opts.trustedKeys }),
419
448
  ...(opts.adminHost && { host: opts.adminHost }),
420
449
  });
@@ -439,11 +468,12 @@ const plugin = async (app, opts) => {
439
468
  },
440
469
  });
441
470
  registerMediaRoutes(app, core);
471
+ registerCodeFileRoutes(app, codeFilesFor(core), core);
442
472
  if (opts.publicDir !== undefined)
443
473
  registerPublicRoutes(app, { dir: opts.publicDir, maxAge: opts.publicMaxAge ?? 3600 });
444
- registerReleaseRoutes(app, { core, registry, baseUrl, assets: siteAssets, secrets: opts.secrets ?? {}, fetch: opts.fetch ?? ((input, init) => globalThis.fetch(input, init)), log: app.log, preview: opts.preview === 'forced' });
474
+ registerReleaseRoutes(app, { core, registry, baseUrl, assets: siteAssets, integrations: siteIntegrations, secrets: opts.secrets ?? {}, fetch: opts.fetch ?? ((input, init) => globalThis.fetch(input, init)), log: app.log, preview: opts.preview === 'forced' });
445
475
  registerPreviewRoutes(app, { secret, baseUrl, now });
446
- registerSiteRoutes(app, core, cache, {
476
+ registerSiteRoutes(app, core, cache, siteIntegrations, {
447
477
  baseUrl,
448
478
  secret,
449
479
  now,
@@ -4,23 +4,34 @@ import type { TemplateDef } from '../../core/registry/define.js';
4
4
  import type { ContentIssue, DocumentData, LiveDocument, LiveState } from '../../core/types.js';
5
5
  import { type SafeHtml } from '../../jsx/html.js';
6
6
  import type { PublicAssets } from './assets.js';
7
+ import { type SiteIntegrations } from './integrations.js';
7
8
  export declare const PREVIEW_EXIT_PATH = "/_inlay/preview/exit";
8
9
  /** A page Inlay renders itself (in the catalog's language), with `body` (Inlay-built HTML) under its `title` heading. */
9
10
  export declare function inlayPage(title: string, body: SafeHtml): string;
10
11
  /** A page Inlay renders itself, in the catalog's language. */
11
12
  export declare function catalogPage(titleId: MessageId, bodyId: MessageId): string;
12
- /**
13
- * Renders `doc` through its template, with its enabled slots rendered by their blocks. Render errors propagate.
14
- * In preview the page gets the preview banner (naming `release`, the name of the staged release previewed, when
15
- * given), and a draft that fails strict validation gets a list of its problems instead of its template.
16
- */
17
- export declare function renderPage(core: Core, doc: LiveDocument, opts: {
13
+ /** A rendered page and the `'sha256-…'` hashes of the inline scripts it wrote through `ctx.script`. */
14
+ export interface RenderedPage {
15
+ html: string;
16
+ scriptHashes: string[];
17
+ }
18
+ type PageOptions = {
18
19
  state: LiveState;
19
20
  page: number;
20
21
  baseUrl: string;
21
22
  release?: string;
22
23
  assets?: PublicAssets;
23
- }): Promise<string>;
24
+ /** Renders the site's active integrations into the page; without it, none are. */
25
+ integrations?: SiteIntegrations;
26
+ };
27
+ /**
28
+ * Renders `doc` through its template, with its enabled slots rendered by their blocks. Render errors propagate.
29
+ * In preview the page gets the preview banner (naming `release`, the name of the staged release previewed, when
30
+ * given), and a draft that fails strict validation gets a list of its problems instead of its template.
31
+ */
32
+ export declare function renderPage(core: Core, doc: LiveDocument, opts: PageOptions): Promise<string>;
33
+ /** `renderPage`, with the hashes of the page's inline scripts. */
34
+ export declare function renderPageResult(core: Core, doc: LiveDocument, opts: PageOptions): Promise<RenderedPage>;
24
35
  export type PaneResult = {
25
36
  ok: true;
26
37
  html: string;
@@ -35,16 +46,22 @@ export declare function renderPane(core: Core, doc: LiveDocument, opts: {
35
46
  page: number;
36
47
  baseUrl: string;
37
48
  }): Promise<PaneResult>;
38
- /**
39
- * `template` rendered with `data` (already read with `fill`) as a published page at `path` that no document backs,
40
- * such as one a route returns: no canonical link and no alternates. Its title is the `title` field when that is
41
- * text, else the template's label or name. Render errors propagate.
42
- */
43
- export declare function renderTemplateData(core: Core, template: TemplateDef, data: DocumentData, opts: {
49
+ type TemplateDataOptions = {
44
50
  locale: string;
45
51
  path: string;
46
52
  baseUrl: string;
47
53
  canonical?: string | null;
48
54
  assets?: PublicAssets;
49
55
  preview?: boolean;
50
- }): Promise<string>;
56
+ /** Renders the site's active integrations into the page; without it, none are. */
57
+ integrations?: SiteIntegrations;
58
+ };
59
+ /**
60
+ * `template` rendered with `data` (already read with `fill`) as a published page at `path` that no document backs,
61
+ * such as one a route returns: no canonical link and no alternates. Its title is the `title` field when that is
62
+ * text, else the template's label or name. Render errors propagate.
63
+ */
64
+ export declare function renderTemplateData(core: Core, template: TemplateDef, data: DocumentData, opts: TemplateDataOptions): Promise<string>;
65
+ /** `renderTemplateData`, with the hashes of the page's inline scripts. */
66
+ export declare function renderTemplateResult(core: Core, template: TemplateDef, data: DocumentData, opts: TemplateDataOptions): Promise<RenderedPage>;
67
+ export {};
@@ -5,6 +5,7 @@ import { t } from '../../core/messages/index.js';
5
5
  import { escapeHtml, raw, renderToString, toHtml } from '../../jsx/html.js';
6
6
  import { createRenderContext } from './context.js';
7
7
  import { buildHead, injectHead } from './head.js';
8
+ import { injectIntegrations } from './integrations.js';
8
9
  import { isHomePath, mediaShareImage, pageTitle, resolveSeoDefaults } from './seo.js';
9
10
  const DOCTYPE = /^\s*<!doctype\s/i;
10
11
  const BODY = /<body\b[^>]*>/i;
@@ -52,6 +53,10 @@ function withPreviewBanner(html, release) {
52
53
  * given), and a draft that fails strict validation gets a list of its problems instead of its template.
53
54
  */
54
55
  export async function renderPage(core, doc, opts) {
56
+ return (await renderPageResult(core, doc, opts)).html;
57
+ }
58
+ /** `renderPage`, with the hashes of the page's inline scripts. */
59
+ export async function renderPageResult(core, doc, opts) {
55
60
  const { release, ...render } = opts;
56
61
  if (render.state !== 'preview')
57
62
  return renderTemplate(core, doc, render);
@@ -59,9 +64,10 @@ export async function renderPage(core, doc, opts) {
59
64
  if (!checked.ok) {
60
65
  const items = checked.issues.map((issue) => `<li>${escapeHtml(issue.message)}</li>`).join('');
61
66
  const body = raw(`<p>${escapeHtml(t('preview.incomplete'))}</p><ul>${items}</ul>`);
62
- return withPreviewBanner(catalogDocument('preview.incomplete.title', body), release);
67
+ return { html: withPreviewBanner(catalogDocument('preview.incomplete.title', body), release), scriptHashes: [] };
63
68
  }
64
- return withPreviewBanner(await renderTemplate(core, doc, render), release);
69
+ const rendered = await renderTemplate(core, doc, render);
70
+ return { html: withPreviewBanner(rendered.html, release), scriptHashes: rendered.scriptHashes };
65
71
  }
66
72
  export const SLOT_START = (key) => `<!--inlay:slot ${key}-->`;
67
73
  export const SLOT_END = (key) => `<!--/inlay:slot ${key}-->`;
@@ -73,7 +79,7 @@ export async function renderPane(core, doc, opts) {
73
79
  const checked = validateContent(core.registry, doc.type, doc.data, 'strict');
74
80
  if (!checked.ok)
75
81
  return { ok: false, issues: checked.issues };
76
- return { ok: true, html: await renderTemplate(core, doc, { ...opts, state: 'preview' }, { pane: true }) };
82
+ return { ok: true, html: (await renderTemplate(core, doc, { ...opts, state: 'preview' }, { pane: true })).html };
77
83
  }
78
84
  /** `template` rendered with `data` and its enabled slots rendered by their blocks: the page before its head is added. */
79
85
  async function renderBody(template, data, page, ctx, internal) {
@@ -95,6 +101,12 @@ async function renderBody(template, data, page, ctx, internal) {
95
101
  return renderToString(template.render({ fields: data.fields, slots, data: slotData, page }, ctx));
96
102
  }
97
103
  const withDoctype = (html) => (DOCTYPE.test(html) ? html : `<!doctype html>${html}`);
104
+ /** `html` with the active integrations rendered for `page` through `ctx.script`, when `integrations` is given. */
105
+ async function withIntegrations(html, integrations, page, ctx) {
106
+ if (!integrations)
107
+ return html;
108
+ return injectIntegrations(html, await integrations.render(page, ctx.script));
109
+ }
98
110
  async function renderTemplate(core, doc, opts, internal = {}) {
99
111
  const { template } = core.registry.getType(doc.type);
100
112
  if (!template.render)
@@ -147,7 +159,10 @@ async function renderTemplate(core, doc, opts, internal = {}) {
147
159
  out = `${out.slice(0, at)}<base href="${escapeHtml(doc.path)}">${out.slice(at)}`;
148
160
  }
149
161
  }
150
- return withDoctype(out);
162
+ if (!internal.pane) {
163
+ out = await withIntegrations(out, opts.integrations, { path: page.path, locale: doc.locale, preview: ctx.preview }, ctx);
164
+ }
165
+ return { html: withDoctype(out), scriptHashes: ctx.scriptHashes() };
151
166
  }
152
167
  /**
153
168
  * `template` rendered with `data` (already read with `fill`) as a published page at `path` that no document backs,
@@ -155,6 +170,10 @@ async function renderTemplate(core, doc, opts, internal = {}) {
155
170
  * text, else the template's label or name. Render errors propagate.
156
171
  */
157
172
  export async function renderTemplateData(core, template, data, opts) {
173
+ return (await renderTemplateResult(core, template, data, opts)).html;
174
+ }
175
+ /** `renderTemplateData`, with the hashes of the page's inline scripts. */
176
+ export async function renderTemplateResult(core, template, data, opts) {
158
177
  const ctx = createRenderContext(core, {
159
178
  locale: opts.locale,
160
179
  state: 'published',
@@ -192,7 +211,9 @@ export async function renderTemplateData(core, template, data, opts) {
192
211
  preview: opts.preview === true,
193
212
  collected: ctx.headTags(),
194
213
  });
195
- return withDoctype(injectHead(html, head));
214
+ const at = { path: opts.path, locale: opts.locale, preview: opts.preview === true };
215
+ const out = await withIntegrations(injectHead(html, head), opts.integrations, at, ctx);
216
+ return { html: withDoctype(out), scriptHashes: ctx.scriptHashes() };
196
217
  }
197
218
  /** The value of the first top-level field marked by `f.seo()`. */
198
219
  function seoValue(fields, values) {
@@ -2,11 +2,14 @@ import type { FastifyBaseLogger, FastifyInstance } from 'fastify';
2
2
  import type { Core } from '../../core/core.js';
3
3
  import type { Registry } from '../../core/registry/registry.js';
4
4
  import { type PublicAssets } from './assets.js';
5
+ import type { SiteIntegrations } from './integrations.js';
5
6
  export interface ReleaseRouteOptions {
6
7
  core: Core;
7
8
  registry: Registry;
8
9
  baseUrl: string;
9
10
  assets?: PublicAssets;
11
+ /** Renders the active integrations into a rendered template's page, and gives it its content-security-policy. */
12
+ integrations?: SiteIntegrations;
10
13
  /** The site is a staged release's forced preview: its renders stay noindex, with no canonical. */
11
14
  preview?: boolean;
12
15
  /** Host-supplied secret values; a route sees only the ones its site declares. */
@@ -4,7 +4,7 @@ import { t } from '../../core/messages/index.js';
4
4
  import { encodePath } from '../../core/site/paths.js';
5
5
  import { publicAssets } from './assets.js';
6
6
  import { queryApi } from './context.js';
7
- import { catalogPage, renderTemplateData } from './render.js';
7
+ import { catalogPage, renderTemplateResult } from './render.js';
8
8
  const BODY_LIMIT = 1024 * 1024;
9
9
  const HTML = 'text/html; charset=utf-8';
10
10
  /** Headers a route never sees: routes run anonymous. */
@@ -113,8 +113,12 @@ export function registerReleaseRoutes(app, opts) {
113
113
  const read = templateRegistry(registry, template);
114
114
  const doc = readData(read, template.name, normalizeContent(read, template.name, data), { fill: true }).data;
115
115
  const canonical = route.sitemap === true && request.url.split('?')[0] === encodePath(route.path) ? route.path : null;
116
- const html = await renderTemplateData(core, template, doc, { locale, path: route.path, baseUrl, canonical, assets, preview: opts.preview === true });
117
- return { status: o.status ?? 200, headers: { 'content-type': HTML }, body: html };
116
+ const rendered = await renderTemplateResult(core, template, doc, { locale, path: route.path, baseUrl, canonical, assets, preview: opts.preview === true, ...(opts.integrations && { integrations: opts.integrations }) });
117
+ const csp = (await opts.integrations?.policy(rendered.scriptHashes)) ?? null;
118
+ const headers = { 'content-type': HTML };
119
+ if (csp !== null)
120
+ headers['content-security-policy'] = csp;
121
+ return { status: o.status ?? 200, headers, body: rendered.html };
118
122
  },
119
123
  fetch: opts.fetch,
120
124
  secrets,
@@ -0,0 +1,6 @@
1
+ import type { ScriptApi } from '../../core/registry/render.js';
2
+ /** The `ctx.script` of one render, and the `'sha256-…'` hashes of the inline scripts it wrote, in call order. */
3
+ export declare function createScriptCollector(): {
4
+ api: ScriptApi;
5
+ hashes(): string[];
6
+ };
@@ -0,0 +1,27 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { InlayError } from '../../core/errors.js';
3
+ import { isSafeUrl } from '../../core/fields/define.js';
4
+ import { JsCode } from '../../core/registry/js.js';
5
+ import { escapeHtml, raw } from '../../jsx/html.js';
6
+ const UNSAFE_CODE = /<\/script|<!--/i;
7
+ /** The `ctx.script` of one render, and the `'sha256-…'` hashes of the inline scripts it wrote, in call order. */
8
+ export function createScriptCollector() {
9
+ const hashes = new Set();
10
+ const api = (input) => {
11
+ if (typeof input === 'string' || input instanceof JsCode) {
12
+ // the browser hashes the text as it parsed it: line breaks as \n, and NUL replaced, so NUL is refused
13
+ const code = (typeof input === 'string' ? input : input.code).replace(/\r\n?/g, '\n');
14
+ if (UNSAFE_CODE.test(code) || code.includes('\u0000'))
15
+ throw new InlayError('config', 'config.scriptCode');
16
+ hashes.add(`'sha256-${createHash('sha256').update(code).digest('base64')}'`);
17
+ return raw(`<script>${code}</script>`);
18
+ }
19
+ const { src } = input;
20
+ const ok = isSafeUrl(src) && (/^https:\/\//i.test(src) || (src.startsWith('/') && !src.startsWith('//')));
21
+ if (!ok)
22
+ throw new InlayError('config', 'config.scriptSrc', { src });
23
+ const type = input.type === 'module' ? ' type="module"' : '';
24
+ return raw(`<script${type} src="${escapeHtml(src)}"${input.async ? ' async' : ''}${input.defer ? ' defer' : ''}></script>`);
25
+ };
26
+ return { api, hashes: () => [...hashes] };
27
+ }
@@ -1,5 +1,5 @@
1
1
  import type { Actor, Ctx, RevisionSource, Role } from '../types.js';
2
- export type Action = 'content.read' | 'content.write' | 'content.publish' | 'entry.delete' | 'entry.restore' | 'backup.create' | 'backup.read' | 'content.export' | 'content.import' | 'media.write' | 'redirects.write' | 'users.manage' | 'site.protect' | 'release.push' | 'release.activate' | 'release.manage';
2
+ export type Action = 'content.read' | 'content.write' | 'content.publish' | 'entry.delete' | 'entry.restore' | 'backup.create' | 'backup.read' | 'content.export' | 'content.import' | 'media.write' | 'redirects.write' | 'users.manage' | 'site.protect' | 'integrations.manage' | 'release.push' | 'release.activate' | 'release.manage';
3
3
  export declare function can(role: Role, action: Action): boolean;
4
4
  /** Whether an API key may push releases: its user is an owner now and the key was made with the `release:push` permission. */
5
5
  export declare function canPush(actor: Actor, permissions: {
@@ -9,6 +9,7 @@ const OWNER_ONLY = new Set([
9
9
  'content.import',
10
10
  'users.manage',
11
11
  'site.protect',
12
+ 'integrations.manage',
12
13
  'release.push',
13
14
  'release.activate',
14
15
  'release.manage',
@@ -26,6 +26,8 @@ export interface BootOptions {
26
26
  content?: 'apply' | 'none';
27
27
  /** A loaded release's shipped files, by source as written in the site. */
28
28
  shippedFiles?: ReadonlyMap<string, string>;
29
+ /** As `shippedFiles`, only the images `.md` files the site imports name. */
30
+ codeFiles?: ReadonlyMap<string, string>;
29
31
  }
30
32
  export interface BootResult {
31
33
  core: Core;
package/dist/core/boot.js CHANGED
@@ -7,6 +7,7 @@ import { createCore } from './core.js';
7
7
  import { openDatabase } from './db/connection.js';
8
8
  import { migrateSystem, pendingSystemMigrations } from './db/migrate.js';
9
9
  import { InlayError } from './errors.js';
10
+ import { policyWarnings } from './integrations/warnings.js';
10
11
  import { t } from './messages/index.js';
11
12
  import { formatReport } from './report.js';
12
13
  /**
@@ -55,6 +56,7 @@ export async function upgradeDatabase(db, core, systemMigrations, auth, opts = {
55
56
  for (const from of await core.codeRedirectLoops()) {
56
57
  report.warnings.push({ code: 'redirect_loop', message: t('report.redirectLoop', { from }), redirect: { from } });
57
58
  }
59
+ report.warnings.push(...policyWarnings(core.registry.site));
58
60
  return report;
59
61
  }
60
62
  /** True for a database that has never been set up: no content tables yet. */
@@ -115,6 +117,7 @@ export async function bootInlay(opts) {
115
117
  ...(opts.uploads && { uploads: opts.uploads }),
116
118
  ...(opts.now && { now: opts.now }),
117
119
  ...(opts.shippedFiles && { shippedFiles: opts.shippedFiles }),
120
+ ...(opts.codeFiles && { codeFiles: opts.codeFiles }),
118
121
  });
119
122
  const auth = opts.auth ? createAuthService({ db, ...opts.auth }) : null;
120
123
  const systemMigrations = await pendingSystemMigrations(db);