inlaycms 0.0.0-stage → 0.2.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.
- package/LICENSE +21 -0
- package/README.md +469 -2
- package/assets/admin/admin.css +2 -0
- package/assets/admin/admin.js +1 -0
- package/assets/admin/editor.js +125 -0
- package/dist/adapters/admin/activity.d.ts +17 -0
- package/dist/adapters/admin/activity.js +59 -0
- package/dist/adapters/admin/assets.d.ts +14 -0
- package/dist/adapters/admin/assets.js +64 -0
- package/dist/adapters/admin/attention.d.ts +15 -0
- package/dist/adapters/admin/attention.js +34 -0
- package/dist/adapters/admin/context.d.ts +40 -0
- package/dist/adapters/admin/context.js +142 -0
- package/dist/adapters/admin/form/walk.d.ts +61 -0
- package/dist/adapters/admin/form/walk.js +565 -0
- package/dist/adapters/admin/pages.d.ts +38 -0
- package/dist/adapters/admin/pages.js +66 -0
- package/dist/adapters/admin/publish.d.ts +12 -0
- package/dist/adapters/admin/publish.js +195 -0
- package/dist/adapters/admin/routes.d.ts +47 -0
- package/dist/adapters/admin/routes.js +255 -0
- package/dist/adapters/admin/screens/backups.d.ts +11 -0
- package/dist/adapters/admin/screens/backups.js +223 -0
- package/dist/adapters/admin/screens/dashboard.d.ts +4 -0
- package/dist/adapters/admin/screens/dashboard.js +160 -0
- package/dist/adapters/admin/screens/editor.d.ts +67 -0
- package/dist/adapters/admin/screens/editor.js +416 -0
- package/dist/adapters/admin/screens/history.d.ts +4 -0
- package/dist/adapters/admin/screens/history.js +105 -0
- package/dist/adapters/admin/screens/lists.d.ts +4 -0
- package/dist/adapters/admin/screens/lists.js +297 -0
- package/dist/adapters/admin/screens/media.d.ts +20 -0
- package/dist/adapters/admin/screens/media.js +186 -0
- package/dist/adapters/admin/screens/pickers.d.ts +29 -0
- package/dist/adapters/admin/screens/pickers.js +134 -0
- package/dist/adapters/admin/screens/preview-pane.d.ts +10 -0
- package/dist/adapters/admin/screens/preview-pane.js +74 -0
- package/dist/adapters/admin/screens/redirects.d.ts +4 -0
- package/dist/adapters/admin/screens/redirects.js +137 -0
- package/dist/adapters/admin/screens/releases.d.ts +7 -0
- package/dist/adapters/admin/screens/releases.js +287 -0
- package/dist/adapters/admin/screens/search.d.ts +22 -0
- package/dist/adapters/admin/screens/search.js +113 -0
- package/dist/adapters/admin/screens/security.d.ts +4 -0
- package/dist/adapters/admin/screens/security.js +85 -0
- package/dist/adapters/admin/screens/users.d.ts +4 -0
- package/dist/adapters/admin/screens/users.js +330 -0
- package/dist/adapters/admin/theme.d.ts +1 -0
- package/dist/adapters/admin/theme.js +1 -0
- package/dist/adapters/admin/translations.d.ts +16 -0
- package/dist/adapters/admin/translations.js +23 -0
- package/dist/adapters/admin/upload.d.ts +8 -0
- package/dist/adapters/admin/upload.js +116 -0
- package/dist/adapters/admin/views/data-table.d.ts +82 -0
- package/dist/adapters/admin/views/data-table.js +117 -0
- package/dist/adapters/admin/views/icons.d.ts +48 -0
- package/dist/adapters/admin/views/icons.js +47 -0
- package/dist/adapters/admin/views/layout.d.ts +51 -0
- package/dist/adapters/admin/views/layout.js +145 -0
- package/dist/adapters/admin/views/sheet.d.ts +15 -0
- package/dist/adapters/admin/views/sheet.js +6 -0
- package/dist/adapters/admin/views/status.d.ts +32 -0
- package/dist/adapters/admin/views/status.js +74 -0
- package/dist/adapters/auth/handler.d.ts +10 -0
- package/dist/adapters/auth/handler.js +63 -0
- package/dist/adapters/auth/request.d.ts +8 -0
- package/dist/adapters/auth/request.js +14 -0
- package/dist/adapters/cli/bin.d.ts +2 -0
- package/dist/adapters/cli/bin.js +42 -0
- package/dist/adapters/cli/main.d.ts +7 -0
- package/dist/adapters/cli/main.js +982 -0
- package/dist/adapters/cli/remote.d.ts +52 -0
- package/dist/adapters/cli/remote.js +161 -0
- package/dist/adapters/mcp/agent-refs.d.ts +9 -0
- package/dist/adapters/mcp/agent-refs.js +25 -0
- package/dist/adapters/mcp/documents.d.ts +15 -0
- package/dist/adapters/mcp/documents.js +26 -0
- package/dist/adapters/mcp/fetch-url.d.ts +19 -0
- package/dist/adapters/mcp/fetch-url.js +244 -0
- package/dist/adapters/mcp/request-state.d.ts +15 -0
- package/dist/adapters/mcp/request-state.js +38 -0
- package/dist/adapters/mcp/results.d.ts +20 -0
- package/dist/adapters/mcp/results.js +61 -0
- package/dist/adapters/mcp/route.d.ts +34 -0
- package/dist/adapters/mcp/route.js +52 -0
- package/dist/adapters/mcp/server.d.ts +44 -0
- package/dist/adapters/mcp/server.js +49 -0
- package/dist/adapters/mcp/tools/history.d.ts +5 -0
- package/dist/adapters/mcp/tools/history.js +84 -0
- package/dist/adapters/mcp/tools/media.d.ts +5 -0
- package/dist/adapters/mcp/tools/media.js +102 -0
- package/dist/adapters/mcp/tools/publish.d.ts +5 -0
- package/dist/adapters/mcp/tools/publish.js +157 -0
- package/dist/adapters/mcp/tools/read.d.ts +5 -0
- package/dist/adapters/mcp/tools/read.js +279 -0
- package/dist/adapters/mcp/tools/redirects.d.ts +5 -0
- package/dist/adapters/mcp/tools/redirects.js +74 -0
- package/dist/adapters/mcp/tools/write.d.ts +5 -0
- package/dist/adapters/mcp/tools/write.js +304 -0
- package/dist/adapters/site/backup-schedule.d.ts +8 -0
- package/dist/adapters/site/backup-schedule.js +31 -0
- package/dist/adapters/site/cache.d.ts +29 -0
- package/dist/adapters/site/cache.js +63 -0
- package/dist/adapters/site/context.d.ts +29 -0
- package/dist/adapters/site/context.js +278 -0
- package/dist/adapters/site/head.d.ts +23 -0
- package/dist/adapters/site/head.js +44 -0
- package/dist/adapters/site/limiter.d.ts +17 -0
- package/dist/adapters/site/limiter.js +39 -0
- package/dist/adapters/site/lock.d.ts +30 -0
- package/dist/adapters/site/lock.js +143 -0
- package/dist/adapters/site/media-routes.d.ts +4 -0
- package/dist/adapters/site/media-routes.js +55 -0
- package/dist/adapters/site/plugin.d.ts +122 -0
- package/dist/adapters/site/plugin.js +436 -0
- package/dist/adapters/site/preview.d.ts +36 -0
- package/dist/adapters/site/preview.js +82 -0
- package/dist/adapters/site/public.d.ts +6 -0
- package/dist/adapters/site/public.js +87 -0
- package/dist/adapters/site/render.d.ts +45 -0
- package/dist/adapters/site/render.js +191 -0
- package/dist/adapters/site/routes.d.ts +17 -0
- package/dist/adapters/site/routes.js +125 -0
- package/dist/adapters/site/sitemap.d.ts +10 -0
- package/dist/adapters/site/sitemap.js +10 -0
- package/dist/adapters/web.d.ts +22 -0
- package/dist/adapters/web.js +75 -0
- package/dist/config.d.ts +21 -0
- package/dist/config.js +58 -0
- package/dist/core/agent/format.d.ts +62 -0
- package/dist/core/agent/format.js +211 -0
- package/dist/core/agent/schema.d.ts +6 -0
- package/dist/core/agent/schema.js +86 -0
- package/dist/core/archive.d.ts +12 -0
- package/dist/core/archive.js +72 -0
- package/dist/core/auth/auth.d.ts +4911 -0
- package/dist/core/auth/auth.js +61 -0
- package/dist/core/auth/roles.d.ts +10 -0
- package/dist/core/auth/roles.js +38 -0
- package/dist/core/auth/service.d.ts +118 -0
- package/dist/core/auth/service.js +424 -0
- package/dist/core/auth/upload-token.d.ts +8 -0
- package/dist/core/auth/upload-token.js +27 -0
- package/dist/core/backup/backup.d.ts +28 -0
- package/dist/core/backup/backup.js +126 -0
- package/dist/core/backup/restore.d.ts +41 -0
- package/dist/core/backup/restore.js +264 -0
- package/dist/core/backup/schedule.d.ts +12 -0
- package/dist/core/backup/schedule.js +29 -0
- package/dist/core/boot.d.ts +63 -0
- package/dist/core/boot.js +141 -0
- package/dist/core/check.d.ts +32 -0
- package/dist/core/check.js +111 -0
- package/dist/core/content/activity.d.ts +8 -0
- package/dist/core/content/activity.js +101 -0
- package/dist/core/content/delete.d.ts +5 -0
- package/dist/core/content/delete.js +100 -0
- package/dist/core/content/diff.d.ts +6 -0
- package/dist/core/content/diff.js +129 -0
- package/dist/core/content/dry-run.d.ts +24 -0
- package/dist/core/content/dry-run.js +69 -0
- package/dist/core/content/gaps.d.ts +25 -0
- package/dist/core/content/gaps.js +50 -0
- package/dist/core/content/hidden.d.ts +33 -0
- package/dist/core/content/hidden.js +103 -0
- package/dist/core/content/history.d.ts +15 -0
- package/dist/core/content/history.js +62 -0
- package/dist/core/content/patch.d.ts +40 -0
- package/dist/core/content/patch.js +287 -0
- package/dist/core/content/path.d.ts +6 -0
- package/dist/core/content/path.js +38 -0
- package/dist/core/content/publish.d.ts +26 -0
- package/dist/core/content/publish.js +211 -0
- package/dist/core/content/read.d.ts +99 -0
- package/dist/core/content/read.js +141 -0
- package/dist/core/content/reader.d.ts +37 -0
- package/dist/core/content/reader.js +195 -0
- package/dist/core/content/refs.d.ts +44 -0
- package/dist/core/content/refs.js +161 -0
- package/dist/core/content/release-migrations.d.ts +12 -0
- package/dist/core/content/release-migrations.js +154 -0
- package/dist/core/content/save.d.ts +25 -0
- package/dist/core/content/save.js +87 -0
- package/dist/core/content/schema.d.ts +22 -0
- package/dist/core/content/schema.js +127 -0
- package/dist/core/content/search.d.ts +8 -0
- package/dist/core/content/search.js +89 -0
- package/dist/core/content/shipped-input.d.ts +39 -0
- package/dist/core/content/shipped-input.js +221 -0
- package/dist/core/content/shipped.d.ts +112 -0
- package/dist/core/content/shipped.js +437 -0
- package/dist/core/content/slug.d.ts +23 -0
- package/dist/core/content/slug.js +182 -0
- package/dist/core/content/stats.d.ts +11 -0
- package/dist/core/content/stats.js +30 -0
- package/dist/core/content/translate.d.ts +3 -0
- package/dist/core/content/translate.js +68 -0
- package/dist/core/content/usages.d.ts +13 -0
- package/dist/core/content/usages.js +70 -0
- package/dist/core/content/validate.d.ts +21 -0
- package/dist/core/content/validate.js +124 -0
- package/dist/core/content/write.d.ts +10 -0
- package/dist/core/content/write.js +93 -0
- package/dist/core/core.d.ts +227 -0
- package/dist/core/core.js +251 -0
- package/dist/core/db/connection.d.ts +6 -0
- package/dist/core/db/connection.js +12 -0
- package/dist/core/db/migrate.d.ts +9 -0
- package/dist/core/db/migrate.js +42 -0
- package/dist/core/db/migrations/0001_content.d.ts +2 -0
- package/dist/core/db/migrations/0001_content.js +69 -0
- package/dist/core/db/migrations/0002_media.d.ts +2 -0
- package/dist/core/db/migrations/0002_media.js +26 -0
- package/dist/core/db/migrations/0003_redirects.d.ts +2 -0
- package/dist/core/db/migrations/0003_redirects.js +19 -0
- package/dist/core/db/migrations/0004_token_cutoffs.d.ts +3 -0
- package/dist/core/db/migrations/0004_token_cutoffs.js +8 -0
- package/dist/core/db/migrations/0005_site_lock.d.ts +3 -0
- package/dist/core/db/migrations/0005_site_lock.js +10 -0
- package/dist/core/db/migrations/0006_releases.d.ts +3 -0
- package/dist/core/db/migrations/0006_releases.js +34 -0
- package/dist/core/db/schema.d.ts +155 -0
- package/dist/core/db/schema.js +1 -0
- package/dist/core/errors.d.ts +27 -0
- package/dist/core/errors.js +15 -0
- package/dist/core/export/export.d.ts +17 -0
- package/dist/core/export/export.js +185 -0
- package/dist/core/export/format.d.ts +241 -0
- package/dist/core/export/format.js +106 -0
- package/dist/core/export/import.d.ts +54 -0
- package/dist/core/export/import.js +180 -0
- package/dist/core/export/read.d.ts +16 -0
- package/dist/core/export/read.js +234 -0
- package/dist/core/export/replace.d.ts +17 -0
- package/dist/core/export/replace.js +36 -0
- package/dist/core/export/report.d.ts +55 -0
- package/dist/core/export/report.js +50 -0
- package/dist/core/export/schema.d.ts +8 -0
- package/dist/core/export/schema.js +47 -0
- package/dist/core/export/stage.d.ts +25 -0
- package/dist/core/export/stage.js +192 -0
- package/dist/core/fields/builtins.d.ts +70 -0
- package/dist/core/fields/builtins.js +335 -0
- package/dist/core/fields/define.d.ts +86 -0
- package/dist/core/fields/define.js +34 -0
- package/dist/core/fields/walk.d.ts +49 -0
- package/dist/core/fields/walk.js +270 -0
- package/dist/core/fields/widgets.d.ts +27 -0
- package/dist/core/fields/widgets.js +330 -0
- package/dist/core/fields/zod-internals.d.ts +29 -0
- package/dist/core/fields/zod-internals.js +28 -0
- package/dist/core/media/detect.d.ts +5 -0
- package/dist/core/media/detect.js +66 -0
- package/dist/core/media/labels.d.ts +6 -0
- package/dist/core/media/labels.js +17 -0
- package/dist/core/media/library.d.ts +45 -0
- package/dist/core/media/library.js +239 -0
- package/dist/core/media/store.d.ts +11 -0
- package/dist/core/media/store.js +49 -0
- package/dist/core/media/variants.d.ts +10 -0
- package/dist/core/media/variants.js +59 -0
- package/dist/core/messages/en.d.ts +1278 -0
- package/dist/core/messages/en.js +1287 -0
- package/dist/core/messages/index.d.ts +7 -0
- package/dist/core/messages/index.js +14 -0
- package/dist/core/preview.d.ts +16 -0
- package/dist/core/preview.js +42 -0
- package/dist/core/redirects/collapse.d.ts +68 -0
- package/dist/core/redirects/collapse.js +153 -0
- package/dist/core/redirects/csv.d.ts +15 -0
- package/dist/core/redirects/csv.js +68 -0
- package/dist/core/redirects/redirects.d.ts +58 -0
- package/dist/core/redirects/redirects.js +545 -0
- package/dist/core/registry/content.d.ts +26 -0
- package/dist/core/registry/content.js +9 -0
- package/dist/core/registry/define.d.ts +145 -0
- package/dist/core/registry/define.js +41 -0
- package/dist/core/registry/migration.d.ts +44 -0
- package/dist/core/registry/migration.js +4 -0
- package/dist/core/registry/registry.d.ts +18 -0
- package/dist/core/registry/registry.js +255 -0
- package/dist/core/registry/render.d.ts +98 -0
- package/dist/core/registry/render.js +1 -0
- package/dist/core/registry/route.d.ts +42 -0
- package/dist/core/registry/route.js +3 -0
- package/dist/core/release/bundle.d.ts +21 -0
- package/dist/core/release/bundle.js +252 -0
- package/dist/core/release/keys.d.ts +11 -0
- package/dist/core/release/keys.js +60 -0
- package/dist/core/release/manifest.d.ts +103 -0
- package/dist/core/release/manifest.js +138 -0
- package/dist/core/release/pack.d.ts +20 -0
- package/dist/core/release/pack.js +97 -0
- package/dist/core/release/pointer.d.ts +19 -0
- package/dist/core/release/pointer.js +53 -0
- package/dist/core/release/read.d.ts +59 -0
- package/dist/core/release/read.js +256 -0
- package/dist/core/report.d.ts +31 -0
- package/dist/core/report.js +37 -0
- package/dist/core/richtext/html.d.ts +15 -0
- package/dist/core/richtext/html.js +81 -0
- package/dist/core/richtext/markdown.d.ts +19 -0
- package/dist/core/richtext/markdown.js +951 -0
- package/dist/core/richtext/schema.d.ts +98 -0
- package/dist/core/richtext/schema.js +275 -0
- package/dist/core/site/live.d.ts +56 -0
- package/dist/core/site/live.js +145 -0
- package/dist/core/site/paths.d.ts +15 -0
- package/dist/core/site/paths.js +64 -0
- package/dist/core/site/resolve.d.ts +9 -0
- package/dist/core/site/resolve.js +202 -0
- package/dist/core/site/sitemap.d.ts +11 -0
- package/dist/core/site/sitemap.js +24 -0
- package/dist/core/site-lock/site-lock.d.ts +21 -0
- package/dist/core/site-lock/site-lock.js +65 -0
- package/dist/core/site-lock/token.d.ts +7 -0
- package/dist/core/site-lock/token.js +24 -0
- package/dist/core/theme.d.ts +22 -0
- package/dist/core/theme.js +133 -0
- package/dist/core/types.d.ts +253 -0
- package/dist/core/types.js +1 -0
- package/dist/core/version.d.ts +1 -0
- package/dist/core/version.js +5 -0
- package/dist/host/activate.d.ts +53 -0
- package/dist/host/activate.js +162 -0
- package/dist/host/app.d.ts +46 -0
- package/dist/host/app.js +129 -0
- package/dist/host/bin.d.ts +5 -0
- package/dist/host/bin.js +8 -0
- package/dist/host/config.d.ts +36 -0
- package/dist/host/config.js +152 -0
- package/dist/host/dev.d.ts +10 -0
- package/dist/host/dev.js +293 -0
- package/dist/host/diff.d.ts +78 -0
- package/dist/host/diff.js +346 -0
- package/dist/host/hooks.d.ts +41 -0
- package/dist/host/hooks.js +49 -0
- package/dist/host/ipc.d.ts +123 -0
- package/dist/host/ipc.js +61 -0
- package/dist/host/preview-proxy.d.ts +24 -0
- package/dist/host/preview-proxy.js +154 -0
- package/dist/host/preview-worker.d.ts +42 -0
- package/dist/host/preview-worker.js +242 -0
- package/dist/host/primary.d.ts +38 -0
- package/dist/host/primary.js +357 -0
- package/dist/host/push.d.ts +125 -0
- package/dist/host/push.js +420 -0
- package/dist/host/serve.d.ts +16 -0
- package/dist/host/serve.js +150 -0
- package/dist/host/store.d.ts +48 -0
- package/dist/host/store.js +109 -0
- package/dist/host/worker.d.ts +67 -0
- package/dist/host/worker.js +310 -0
- package/dist/index.d.ts +47 -0
- package/dist/index.js +32 -0
- package/dist/jsx/html.d.ts +16 -0
- package/dist/jsx/html.js +65 -0
- package/dist/jsx/jsx-dev-runtime.d.ts +4 -0
- package/dist/jsx/jsx-dev-runtime.js +5 -0
- package/dist/jsx/jsx-runtime.d.ts +17 -0
- package/dist/jsx/jsx-runtime.js +41 -0
- package/dist/site.d.ts +17 -0
- package/dist/site.js +14 -0
- package/package.json +111 -3
|
@@ -0,0 +1,436 @@
|
|
|
1
|
+
import { dirname, join } from 'node:path';
|
|
2
|
+
import fp from 'fastify-plugin';
|
|
3
|
+
import { DEFAULT_KEEP, SCHEDULE_INTERVAL_MS } from '../../core/backup/schedule.js';
|
|
4
|
+
import { bootInlay } from '../../core/boot.js';
|
|
5
|
+
import { readOnlyCore } from '../../core/core.js';
|
|
6
|
+
import { InlayError } from '../../core/errors.js';
|
|
7
|
+
import { DEFAULT_MAX_BYTES, DEFAULT_UPLOAD_TYPES } from '../../core/media/detect.js';
|
|
8
|
+
import { t } from '../../core/messages/index.js';
|
|
9
|
+
import { buildRegistry } from '../../core/registry/registry.js';
|
|
10
|
+
import { encodePath, normalizePath, splitLocale } from '../../core/site/paths.js';
|
|
11
|
+
import { loadAdminAssets } from '../admin/assets.js';
|
|
12
|
+
import { registerAdminRoutes } from '../admin/routes.js';
|
|
13
|
+
import { resolveTheme, themeContrastProblems } from '../admin/theme.js';
|
|
14
|
+
import { registerAuthHandler } from '../auth/handler.js';
|
|
15
|
+
import { AUTH_BASE_PATH } from '../../core/auth/auth.js';
|
|
16
|
+
import { LOGIN_PATH } from '../auth/request.js';
|
|
17
|
+
import { fetchRemoteFile } from '../mcp/fetch-url.js';
|
|
18
|
+
import { registerMcpRoute } from '../mcp/route.js';
|
|
19
|
+
import { createInlayMcpHandler } from '../mcp/server.js';
|
|
20
|
+
import { sendWebResponse, toWebRequest } from '../web.js';
|
|
21
|
+
import { cacheControl, etagMatches, PageCache, response } from './cache.js';
|
|
22
|
+
import { createRenderContext } from './context.js';
|
|
23
|
+
import { startBackupSchedule } from './backup-schedule.js';
|
|
24
|
+
import { isLockedRequest, registerSiteLockGate, registerUnlockRoute } from './lock.js';
|
|
25
|
+
import { registerMediaRoutes } from './media-routes.js';
|
|
26
|
+
import { registerPublicRoutes } from './public.js';
|
|
27
|
+
import { previewLink, readPreview, registerPreviewRoutes } from './preview.js';
|
|
28
|
+
import { catalogPage, renderPage } from './render.js';
|
|
29
|
+
import { registerReleaseRoutes } from './routes.js';
|
|
30
|
+
import { renderSitemap } from './sitemap.js';
|
|
31
|
+
/** Where tests find the plugin's `AuthService` on `app.inlay`; not part of the public API. */
|
|
32
|
+
export const AUTH = Symbol('inlay.auth');
|
|
33
|
+
const HTML = 'text/html; charset=utf-8';
|
|
34
|
+
const PAGE = /^[1-9][0-9]{0,8}$/;
|
|
35
|
+
/** The origin of `value` when it's an absolute http(s) URL with nothing after the host. */
|
|
36
|
+
function checkBaseUrl(value) {
|
|
37
|
+
const fail = () => new InlayError('config', 'config.baseUrl', { value: String(value) });
|
|
38
|
+
if (typeof value !== 'string')
|
|
39
|
+
throw fail();
|
|
40
|
+
let url;
|
|
41
|
+
try {
|
|
42
|
+
url = new URL(value);
|
|
43
|
+
}
|
|
44
|
+
catch {
|
|
45
|
+
throw fail();
|
|
46
|
+
}
|
|
47
|
+
const bare = url.pathname === '/' && url.search === '' && url.hash === '' && url.username === '' && url.password === '';
|
|
48
|
+
if ((url.protocol !== 'https:' && url.protocol !== 'http:') || !bare || !/^https?:\/\/[^/?#]+\/?$/i.test(value)) {
|
|
49
|
+
throw fail();
|
|
50
|
+
}
|
|
51
|
+
return url.origin;
|
|
52
|
+
}
|
|
53
|
+
function checkOptions(opts, registry) {
|
|
54
|
+
const baseUrl = checkBaseUrl(opts.baseUrl);
|
|
55
|
+
if (typeof opts.secret !== 'string' || opts.secret.length < 32)
|
|
56
|
+
throw new InlayError('config', 'config.secret');
|
|
57
|
+
const keep = opts.backupSchedule === false ? undefined : opts.backupSchedule?.keep;
|
|
58
|
+
if (keep !== undefined && (!Number.isInteger(keep) || keep < 1)) {
|
|
59
|
+
throw new InlayError('config', 'config.backupKeep', { value: String(keep) });
|
|
60
|
+
}
|
|
61
|
+
for (const def of registry.types.values()) {
|
|
62
|
+
const routed = def.kind === 'singleton' ? def.path !== null : def.kind === 'collection' && (def.route !== null || def.customPaths);
|
|
63
|
+
if (routed && !def.template.render)
|
|
64
|
+
throw new InlayError('config', 'config.renderMissing', { name: def.template.name });
|
|
65
|
+
}
|
|
66
|
+
return baseUrl;
|
|
67
|
+
}
|
|
68
|
+
function splitUrl(url) {
|
|
69
|
+
const q = url.indexOf('?');
|
|
70
|
+
return q === -1 ? { path: url, search: '' } : { path: url.slice(0, q), search: url.slice(q) };
|
|
71
|
+
}
|
|
72
|
+
function createApi(core, cache, service, opts) {
|
|
73
|
+
const { baseUrl } = opts;
|
|
74
|
+
const context = (locale) => createRenderContext(core, {
|
|
75
|
+
locale: locale ?? core.registry.defaultLocale,
|
|
76
|
+
state: 'published',
|
|
77
|
+
page: 1,
|
|
78
|
+
baseUrl,
|
|
79
|
+
alternates: [],
|
|
80
|
+
});
|
|
81
|
+
const api = {
|
|
82
|
+
core,
|
|
83
|
+
async getDocument(type, opts = {}) {
|
|
84
|
+
const def = core.registry.getType(type);
|
|
85
|
+
const ctx = context(opts.locale);
|
|
86
|
+
if (def.kind === 'collection') {
|
|
87
|
+
const { slug } = opts;
|
|
88
|
+
if (slug === undefined)
|
|
89
|
+
return null;
|
|
90
|
+
const found = await ctx.query(type, { filter: (e) => e.slug === slug, limit: 1 });
|
|
91
|
+
return found.items[0] ?? null;
|
|
92
|
+
}
|
|
93
|
+
const doc = await core.liveSingleton(type, ctx.locale);
|
|
94
|
+
if (!doc)
|
|
95
|
+
return null;
|
|
96
|
+
await ctx.preload([doc]);
|
|
97
|
+
const [entry] = await ctx.entries(doc.groupId);
|
|
98
|
+
return entry ?? null;
|
|
99
|
+
},
|
|
100
|
+
async query(collection, opts = {}) {
|
|
101
|
+
const { locale, ...rest } = opts;
|
|
102
|
+
return (await context(locale).query(collection, rest));
|
|
103
|
+
},
|
|
104
|
+
previewUrl(path = '/') {
|
|
105
|
+
return previewLink(opts, path);
|
|
106
|
+
},
|
|
107
|
+
clearCache() {
|
|
108
|
+
cache?.clear();
|
|
109
|
+
},
|
|
110
|
+
host: opts.host,
|
|
111
|
+
};
|
|
112
|
+
return Object.defineProperty(api, AUTH, { value: service, enumerable: false });
|
|
113
|
+
}
|
|
114
|
+
function registerSiteRoutes(app, core, cache, opts) {
|
|
115
|
+
const { registry } = core;
|
|
116
|
+
const { notFound } = registry.site;
|
|
117
|
+
const { baseUrl, cdn } = opts;
|
|
118
|
+
const banner = opts.release === undefined ? {} : { release: opts.release };
|
|
119
|
+
async function notFoundPage(locale, state) {
|
|
120
|
+
if (notFound !== null) {
|
|
121
|
+
const doc = await core.liveSingleton(notFound, locale, { state });
|
|
122
|
+
if (doc)
|
|
123
|
+
return renderPage(core, doc, { state, page: 1, baseUrl, ...banner });
|
|
124
|
+
}
|
|
125
|
+
return catalogPage('site.notFound.title', 'site.notFound');
|
|
126
|
+
}
|
|
127
|
+
function localeOf(rawPath) {
|
|
128
|
+
const path = normalizePath(rawPath);
|
|
129
|
+
return path === null ? registry.defaultLocale : splitLocale(registry, path).locale;
|
|
130
|
+
}
|
|
131
|
+
const control = cacheControl(cdn);
|
|
132
|
+
/** Sends a published response with the headers shared caches need, or a 304 when the client already has it. */
|
|
133
|
+
function send(request, reply, res, hit) {
|
|
134
|
+
if (hit !== undefined)
|
|
135
|
+
reply.header('x-inlay-cache', hit ? 'hit' : 'miss');
|
|
136
|
+
reply.header('cache-control', control).header('vary', 'Cookie').header('etag', res.etag);
|
|
137
|
+
if (etagMatches(request.headers['if-none-match'], res.etag))
|
|
138
|
+
return reply.code(304).send();
|
|
139
|
+
return reply.code(res.status).type(res.type).send(res.body);
|
|
140
|
+
}
|
|
141
|
+
/** Preview responses are never stored or revalidated. */
|
|
142
|
+
function sendPreview(reply, status, body) {
|
|
143
|
+
return reply.code(status).type(HTML).send(body);
|
|
144
|
+
}
|
|
145
|
+
/** Serves `key` from the cache, or renders it and stores the result unless a live change landed meanwhile. */
|
|
146
|
+
async function cached(request, reply, key, status, type, render) {
|
|
147
|
+
if (!cache)
|
|
148
|
+
return send(request, reply, response(status, await render(), type), undefined);
|
|
149
|
+
const hit = cache.get(key);
|
|
150
|
+
if (hit)
|
|
151
|
+
return send(request, reply, hit, true);
|
|
152
|
+
const generation = cache.generation;
|
|
153
|
+
const res = response(status, await render(), type);
|
|
154
|
+
cache.set(key, res, generation);
|
|
155
|
+
return send(request, reply, res, false);
|
|
156
|
+
}
|
|
157
|
+
const missing = async (request, reply, locale, state) => state === 'preview'
|
|
158
|
+
? sendPreview(reply, 404, await notFoundPage(locale, state))
|
|
159
|
+
: cached(request, reply, `404:${locale}`, 404, HTML, () => notFoundPage(locale, state));
|
|
160
|
+
/** A cookie that previews a staged release reaches this app only when that preview isn't available: the live site answers. */
|
|
161
|
+
function stateOf(request) {
|
|
162
|
+
if (request.headers.cookie === undefined)
|
|
163
|
+
return 'published';
|
|
164
|
+
const found = readPreview(request, opts.secret, opts.now());
|
|
165
|
+
return found.release === null ? found.state : 'published';
|
|
166
|
+
}
|
|
167
|
+
async function handle(request, reply) {
|
|
168
|
+
const { path, search } = splitUrl(request.url);
|
|
169
|
+
const state = opts.preview === 'forced' ? 'preview' : stateOf(request);
|
|
170
|
+
const preview = state === 'preview';
|
|
171
|
+
if (preview)
|
|
172
|
+
reply.header('cache-control', 'no-store').header('x-robots-tag', 'noindex');
|
|
173
|
+
try {
|
|
174
|
+
const params = new URLSearchParams(search);
|
|
175
|
+
const pageParam = params.get('page');
|
|
176
|
+
if (pageParam !== null && !PAGE.test(pageParam))
|
|
177
|
+
return await missing(request, reply, localeOf(path), state);
|
|
178
|
+
const pageNumber = Number(pageParam ?? 1);
|
|
179
|
+
const normalized = normalizePath(path);
|
|
180
|
+
const canonical = normalized !== null && encodePath(normalized) === path;
|
|
181
|
+
const key = preview || normalized === null || !canonical
|
|
182
|
+
? null
|
|
183
|
+
: pageNumber > 1
|
|
184
|
+
? `${normalized}?page=${pageNumber}`
|
|
185
|
+
: normalized;
|
|
186
|
+
const hit = key === null ? undefined : cache?.get(key);
|
|
187
|
+
if (hit)
|
|
188
|
+
return send(request, reply, hit, true);
|
|
189
|
+
const generation = cache?.generation ?? 0;
|
|
190
|
+
const match = await core.resolvePath(path, { state });
|
|
191
|
+
if (match.kind === 'redirect' && match.location.startsWith('/') && !match.location.startsWith('//')) {
|
|
192
|
+
return reply.redirect(`${match.location}${search}`, match.status);
|
|
193
|
+
}
|
|
194
|
+
if (match.kind === 'page') {
|
|
195
|
+
const html = await renderPage(core, match.document, { state, page: pageNumber, baseUrl, ...banner });
|
|
196
|
+
if (preview)
|
|
197
|
+
return sendPreview(reply, 200, html);
|
|
198
|
+
const res = response(200, html, HTML);
|
|
199
|
+
if (cache && key !== null) {
|
|
200
|
+
cache.set(key, res, generation);
|
|
201
|
+
return send(request, reply, res, false);
|
|
202
|
+
}
|
|
203
|
+
return send(request, reply, res, undefined);
|
|
204
|
+
}
|
|
205
|
+
if (match.kind === 'not_found' && match.loop) {
|
|
206
|
+
request.log.warn({ loop: match.loop }, t('log.redirectLoop', { path, rules: match.loop.join(', ') }));
|
|
207
|
+
}
|
|
208
|
+
return await missing(request, reply, match.kind === 'not_found' ? match.locale : registry.defaultLocale, state);
|
|
209
|
+
}
|
|
210
|
+
catch (err) {
|
|
211
|
+
request.log.error({ err }, t('log.renderFailed', { path }));
|
|
212
|
+
return reply.code(500).type(HTML).send(catalogPage('site.error.title', 'site.error'));
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
async function unavailable(_request, reply) {
|
|
216
|
+
reply.header('cache-control', 'no-store').header('retry-after', '60');
|
|
217
|
+
return reply.code(503).type(HTML).send(catalogPage('site.unavailable.title', 'site.unavailable'));
|
|
218
|
+
}
|
|
219
|
+
// A site that is down has no sitemap to give: an empty one would tell search engines its pages are gone.
|
|
220
|
+
app.get('/sitemap.xml', async (request, reply) => opts.noSite === 'unavailable'
|
|
221
|
+
? unavailable(request, reply)
|
|
222
|
+
: cached(request, reply, 'sitemap.xml', 200, 'application/xml', async () => renderSitemap(await core.sitemapEntries(), baseUrl)));
|
|
223
|
+
app.get('/robots.txt', async (request, reply) => {
|
|
224
|
+
reply.type('text/plain; charset=utf-8');
|
|
225
|
+
if (isLockedRequest(request))
|
|
226
|
+
return reply.header('cache-control', 'no-store').send('User-agent: *\nDisallow: /\n');
|
|
227
|
+
return reply.send(`User-agent: *\nDisallow: /_inlay/\nSitemap: ${baseUrl}/sitemap.xml\n`);
|
|
228
|
+
});
|
|
229
|
+
async function noSite(_request, reply) {
|
|
230
|
+
reply.header('cache-control', 'no-store').header('x-robots-tag', 'noindex');
|
|
231
|
+
return reply.code(200).type(HTML).send(catalogPage('site.noSite.title', 'site.noSite'));
|
|
232
|
+
}
|
|
233
|
+
const content = opts.noSite === 'empty' ? noSite : opts.noSite === 'unavailable' ? unavailable : handle;
|
|
234
|
+
app.get('/', content);
|
|
235
|
+
app.get('/*', content);
|
|
236
|
+
}
|
|
237
|
+
/**
|
|
238
|
+
* Logs one warning when Fastify's `trustProxy` isn't set on a site served over https by something else (most likely
|
|
239
|
+
* a reverse proxy): better-auth's login limits key on the client IP. Fastify doesn't expose `trustProxy` on
|
|
240
|
+
* `initialConfig`, but `request.ips` exists only when it is set, so the first request tells.
|
|
241
|
+
*/
|
|
242
|
+
function warnWithoutTrustProxy(app, baseUrl) {
|
|
243
|
+
let checked = false;
|
|
244
|
+
app.addHook('onRequest', async (request) => {
|
|
245
|
+
if (checked)
|
|
246
|
+
return;
|
|
247
|
+
checked = true;
|
|
248
|
+
if (request.ips === undefined)
|
|
249
|
+
app.log.warn(t('log.noTrustProxy', { baseUrl }));
|
|
250
|
+
});
|
|
251
|
+
}
|
|
252
|
+
const SAFE_METHODS = new Set(['GET', 'HEAD', 'OPTIONS']);
|
|
253
|
+
const under = (path, prefix) => path === prefix || path.startsWith(`${prefix}/`);
|
|
254
|
+
/**
|
|
255
|
+
* Whether a write to `path` changes something: anything under the admin or `/api/auth` but logging in and out. `route`
|
|
256
|
+
* is the matched route, which Fastify finds for a percent-encoded path too (`/%61dmin/x` is the `/admin/x` route).
|
|
257
|
+
*/
|
|
258
|
+
function isWrite(path, route) {
|
|
259
|
+
const admin = under(path, '/admin') || (route !== undefined && under(route, '/admin'));
|
|
260
|
+
const auth = under(path, AUTH_BASE_PATH) || (route !== undefined && under(route, AUTH_BASE_PATH));
|
|
261
|
+
if (admin)
|
|
262
|
+
return path !== LOGIN_PATH && path !== '/admin/logout';
|
|
263
|
+
if (auth)
|
|
264
|
+
return !under(path, `${AUTH_BASE_PATH}/sign-in`) && path !== `${AUTH_BASE_PATH}/sign-out`;
|
|
265
|
+
return false;
|
|
266
|
+
}
|
|
267
|
+
/** For a read-only site: the admin's and `/api/auth`'s write requests answer 403, except logging in and out. */
|
|
268
|
+
function refuseWrites(app) {
|
|
269
|
+
app.addHook('onRequest', async (request, reply) => {
|
|
270
|
+
if (SAFE_METHODS.has(request.method))
|
|
271
|
+
return;
|
|
272
|
+
// As better-auth reads it: `.`, `..` and `%2e` segments resolved.
|
|
273
|
+
let path;
|
|
274
|
+
try {
|
|
275
|
+
path = new URL(splitUrl(request.url).path, 'http://inlay.invalid').pathname;
|
|
276
|
+
}
|
|
277
|
+
catch {
|
|
278
|
+
path = splitUrl(request.url).path;
|
|
279
|
+
}
|
|
280
|
+
if (!isWrite(path, request.routeOptions.url))
|
|
281
|
+
return;
|
|
282
|
+
return reply
|
|
283
|
+
.code(403)
|
|
284
|
+
.header('cache-control', 'no-store')
|
|
285
|
+
.type(HTML)
|
|
286
|
+
.send(catalogPage('preview.readOnly.title', 'error.previewReadOnly'));
|
|
287
|
+
});
|
|
288
|
+
}
|
|
289
|
+
/** For a forced preview: nothing it answers may be kept by a browser or a shared cache, nor revalidated later. */
|
|
290
|
+
function neverStore(app) {
|
|
291
|
+
app.addHook('onSend', async (_request, reply, payload) => {
|
|
292
|
+
reply.header('cache-control', 'no-store').removeHeader('etag').removeHeader('last-modified').removeHeader('expires');
|
|
293
|
+
return payload;
|
|
294
|
+
});
|
|
295
|
+
}
|
|
296
|
+
const plugin = async (app, opts) => {
|
|
297
|
+
const registry = buildRegistry(opts.site);
|
|
298
|
+
const baseUrl = checkOptions(opts, registry);
|
|
299
|
+
const { admin, publicPaths } = registry.site;
|
|
300
|
+
const theme = resolveTheme(admin.theme);
|
|
301
|
+
const assets = await loadAdminAssets();
|
|
302
|
+
if (typeof admin.theme === 'object') {
|
|
303
|
+
for (const { pair, ratio } of themeContrastProblems(admin.theme.colors, admin.theme.base)) {
|
|
304
|
+
app.log.warn(t('log.adminContrast', { first: pair[0], second: pair[1], ratio: ratio.toFixed(2) }));
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
const next = (dir) => join(dirname(opts.db), dir);
|
|
308
|
+
const { secret } = opts;
|
|
309
|
+
const booted = await bootInlay({
|
|
310
|
+
site: opts.site,
|
|
311
|
+
db: opts.db,
|
|
312
|
+
backups: opts.backups ?? next('backups'),
|
|
313
|
+
media: opts.media ?? next('media'),
|
|
314
|
+
...(opts.uploads && { uploads: opts.uploads }),
|
|
315
|
+
...(opts.now && { now: opts.now }),
|
|
316
|
+
...(opts.content && { content: opts.content }),
|
|
317
|
+
...(opts.shippedFiles && { shippedFiles: opts.shippedFiles }),
|
|
318
|
+
auth: { secret, baseUrl, ...(opts.rateLimit !== undefined && { rateLimit: opts.rateLimit }) },
|
|
319
|
+
});
|
|
320
|
+
const { db, report, auth } = booted;
|
|
321
|
+
// A release's preview runs its migration functions on its copy, as activation would, before it turns read-only.
|
|
322
|
+
if (opts.readOnly && opts.release && opts.site.migrations.length > 0) {
|
|
323
|
+
let running = null;
|
|
324
|
+
const tracked = opts.site.migrations.map((m) => ({
|
|
325
|
+
name: m.name,
|
|
326
|
+
run: async (ctx) => {
|
|
327
|
+
running = m.name;
|
|
328
|
+
await m.run(ctx);
|
|
329
|
+
running = null;
|
|
330
|
+
},
|
|
331
|
+
}));
|
|
332
|
+
try {
|
|
333
|
+
await booted.core.runReleaseMigrations(opts.release.id, tracked);
|
|
334
|
+
}
|
|
335
|
+
catch (e) {
|
|
336
|
+
await db.destroy();
|
|
337
|
+
if (running === null || e instanceof InlayError)
|
|
338
|
+
throw e;
|
|
339
|
+
throw new InlayError('release', 'error.releaseMigration', { name: running, problem: e instanceof Error ? e.message : String(e) });
|
|
340
|
+
}
|
|
341
|
+
}
|
|
342
|
+
const core = opts.readOnly ? readOnlyCore(booted.core) : booted.core;
|
|
343
|
+
for (const warning of report.warnings)
|
|
344
|
+
app.log.warn({ document: warning.document }, warning.message);
|
|
345
|
+
for (const warning of report.shipped.warnings ?? [])
|
|
346
|
+
app.log.warn(warning.message);
|
|
347
|
+
const now = opts.now ?? (() => new Date());
|
|
348
|
+
const lockOptions = { db, service: auth, secret, baseUrl, now, publicPaths };
|
|
349
|
+
registerSiteLockGate(app, { ...lockOptions, ...(opts.preview === 'forced' && opts.release && { release: opts.release.id }) });
|
|
350
|
+
registerUnlockRoute(app, { ...lockOptions, rateLimit: opts.rateLimit !== false });
|
|
351
|
+
let schedule;
|
|
352
|
+
if (opts.backupSchedule !== false) {
|
|
353
|
+
const keep = opts.backupSchedule?.keep ?? DEFAULT_KEEP;
|
|
354
|
+
app.addHook('onReady', async () => {
|
|
355
|
+
schedule = startBackupSchedule(async () => {
|
|
356
|
+
const made = await core.scheduledBackup(keep);
|
|
357
|
+
if (made)
|
|
358
|
+
app.log.info({ backup: made.path }, t(made.reason === 'scheduled' ? 'log.scheduledBackup' : 'log.publishBackup'));
|
|
359
|
+
}, { intervalMs: SCHEDULE_INTERVAL_MS, onError: (err) => app.log.error({ err }, t('log.scheduledBackupFailed')) });
|
|
360
|
+
});
|
|
361
|
+
}
|
|
362
|
+
app.addHook('onClose', async () => {
|
|
363
|
+
await schedule?.stop();
|
|
364
|
+
await db.destroy();
|
|
365
|
+
});
|
|
366
|
+
const cache = opts.cache === false ? undefined : new PageCache(opts.cache?.maxEntries ?? 500);
|
|
367
|
+
if (cache) {
|
|
368
|
+
const stop = core.onLiveChange(() => cache.clear());
|
|
369
|
+
app.addHook('onClose', async () => stop());
|
|
370
|
+
}
|
|
371
|
+
if (baseUrl.startsWith('https:') && !app.initialConfig.https)
|
|
372
|
+
warnWithoutTrustProxy(app, baseUrl);
|
|
373
|
+
app.decorate('inlay', createApi(core, cache, auth, { baseUrl, secret, now, host: opts.host ?? null }));
|
|
374
|
+
registerAuthHandler(app, { service: auth, baseUrl });
|
|
375
|
+
if (opts.readOnly)
|
|
376
|
+
refuseWrites(app);
|
|
377
|
+
if (opts.preview === 'forced')
|
|
378
|
+
neverStore(app);
|
|
379
|
+
const uploads = {
|
|
380
|
+
maxBytes: opts.uploads?.maxBytes ?? DEFAULT_MAX_BYTES,
|
|
381
|
+
types: opts.uploads?.types ?? DEFAULT_UPLOAD_TYPES,
|
|
382
|
+
};
|
|
383
|
+
registerAdminRoutes(app, {
|
|
384
|
+
service: auth,
|
|
385
|
+
core,
|
|
386
|
+
baseUrl,
|
|
387
|
+
secret,
|
|
388
|
+
now,
|
|
389
|
+
uploads,
|
|
390
|
+
branding: { name: admin.name ?? t('admin.title'), ...(admin.logo !== undefined && { logo: admin.logo }), theme },
|
|
391
|
+
assets,
|
|
392
|
+
db,
|
|
393
|
+
release: opts.release ?? null,
|
|
394
|
+
...(opts.readOnly && { readOnly: true }),
|
|
395
|
+
...(opts.releasesDir !== undefined && { releasesDir: opts.releasesDir }),
|
|
396
|
+
...(opts.trustedKeys && { trustedKeys: opts.trustedKeys }),
|
|
397
|
+
...(opts.adminHost && { host: opts.adminHost }),
|
|
398
|
+
});
|
|
399
|
+
const mcp = createInlayMcpHandler({
|
|
400
|
+
core,
|
|
401
|
+
baseUrl,
|
|
402
|
+
secret,
|
|
403
|
+
now,
|
|
404
|
+
fetchFile: (url, o) => fetchRemoteFile(url, o),
|
|
405
|
+
uploads: { maxBytes: uploads.maxBytes },
|
|
406
|
+
log: (err) => app.log.error({ err }, t('log.mcpFailed')),
|
|
407
|
+
release: opts.release ?? null,
|
|
408
|
+
});
|
|
409
|
+
app.addHook('onClose', async () => mcp.close());
|
|
410
|
+
registerMcpRoute(app, {
|
|
411
|
+
service: auth,
|
|
412
|
+
baseUrl,
|
|
413
|
+
handle: async (request, reply, authInfo) => {
|
|
414
|
+
const body = request.body === undefined ? undefined : JSON.stringify(request.body);
|
|
415
|
+
const res = await mcp.fetch(toWebRequest(request, baseUrl, { ...(body !== undefined && { body }) }), { authInfo });
|
|
416
|
+
return sendWebResponse(reply, res);
|
|
417
|
+
},
|
|
418
|
+
});
|
|
419
|
+
registerMediaRoutes(app, core);
|
|
420
|
+
if (opts.publicDir !== undefined)
|
|
421
|
+
registerPublicRoutes(app, { dir: opts.publicDir, maxAge: opts.publicMaxAge ?? 3600 });
|
|
422
|
+
registerReleaseRoutes(app, { core, registry, baseUrl, secrets: opts.secrets ?? {}, log: app.log });
|
|
423
|
+
registerPreviewRoutes(app, { secret, baseUrl, now });
|
|
424
|
+
registerSiteRoutes(app, core, cache, {
|
|
425
|
+
baseUrl,
|
|
426
|
+
secret,
|
|
427
|
+
now,
|
|
428
|
+
...(opts.cdn && { cdn: opts.cdn }),
|
|
429
|
+
...(opts.noSite && { noSite: opts.noSite }),
|
|
430
|
+
...(opts.preview && { preview: opts.preview }),
|
|
431
|
+
// Only a staged release's preview names its release in the banner; the live site's preview links to publishing.
|
|
432
|
+
...(opts.preview === 'forced' && opts.release && { release: opts.release.name }),
|
|
433
|
+
});
|
|
434
|
+
};
|
|
435
|
+
/** The Fastify plugin: boots the content core and serves the public site. */
|
|
436
|
+
export const inlay = fp(plugin, { name: 'inlaycms', fastify: '5.x' });
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import type { FastifyInstance, FastifyReply, FastifyRequest } from 'fastify';
|
|
2
|
+
import type { LiveState } from '../../core/types.js';
|
|
3
|
+
export declare const PREVIEW_COOKIE = "inlay_preview";
|
|
4
|
+
export declare const PREVIEW_PATH = "/_inlay/preview";
|
|
5
|
+
/**
|
|
6
|
+
* A link that turns preview on for 24 hours and opens `path` (a decoded site path, default `/`): of the live site's
|
|
7
|
+
* drafts, or with `release` of that staged release.
|
|
8
|
+
*/
|
|
9
|
+
export declare function previewLink(opts: {
|
|
10
|
+
baseUrl: string;
|
|
11
|
+
secret: string;
|
|
12
|
+
now: () => Date;
|
|
13
|
+
}, path?: string, link?: {
|
|
14
|
+
release?: string;
|
|
15
|
+
}): string;
|
|
16
|
+
/**
|
|
17
|
+
* What the request's preview cookie says: `'preview'` when it carries a valid one, otherwise `'published'`, and the
|
|
18
|
+
* staged release it previews (null for the live site's drafts or without a cookie).
|
|
19
|
+
*/
|
|
20
|
+
export declare function readPreview(request: FastifyRequest, secret: string, now: Date): {
|
|
21
|
+
state: LiveState;
|
|
22
|
+
release: string | null;
|
|
23
|
+
};
|
|
24
|
+
/** `'preview'` when the request carries a valid preview cookie (of the live site or of a release), otherwise `'published'`. */
|
|
25
|
+
export declare function previewState(request: FastifyRequest, secret: string, now: Date): LiveState;
|
|
26
|
+
/** Turns preview off for this browser. */
|
|
27
|
+
export declare function clearPreviewCookie(reply: FastifyReply, baseUrl: string): void;
|
|
28
|
+
/**
|
|
29
|
+
* `GET /_inlay/preview?token&path` turns preview on for this browser (the cookie is the token, so it names the
|
|
30
|
+
* release a release link previews); `GET /_inlay/preview/exit` turns it off.
|
|
31
|
+
*/
|
|
32
|
+
export declare function registerPreviewRoutes(app: FastifyInstance, opts: {
|
|
33
|
+
secret: string;
|
|
34
|
+
baseUrl: string;
|
|
35
|
+
now: () => Date;
|
|
36
|
+
}): void;
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
import { createPreviewToken, verifyPreviewToken } from '../../core/preview.js';
|
|
2
|
+
import { encodePath, normalizePath } from '../../core/site/paths.js';
|
|
3
|
+
import { catalogPage, PREVIEW_EXIT_PATH } from './render.js';
|
|
4
|
+
export const PREVIEW_COOKIE = 'inlay_preview';
|
|
5
|
+
export const PREVIEW_PATH = '/_inlay/preview';
|
|
6
|
+
/** The value of the `name` cookie in the request's `Cookie` header, if any. */
|
|
7
|
+
function readCookie(request, name) {
|
|
8
|
+
const header = request.headers.cookie;
|
|
9
|
+
if (typeof header !== 'string')
|
|
10
|
+
return undefined;
|
|
11
|
+
for (const part of header.split(';')) {
|
|
12
|
+
const eq = part.indexOf('=');
|
|
13
|
+
if (eq !== -1 && part.slice(0, eq).trim() === name)
|
|
14
|
+
return part.slice(eq + 1).trim();
|
|
15
|
+
}
|
|
16
|
+
return undefined;
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* A link that turns preview on for 24 hours and opens `path` (a decoded site path, default `/`): of the live site's
|
|
20
|
+
* drafts, or with `release` of that staged release.
|
|
21
|
+
*/
|
|
22
|
+
export function previewLink(opts, path = '/', link = {}) {
|
|
23
|
+
const token = createPreviewToken(opts.secret, opts.now(), link.release === undefined ? {} : { release: link.release });
|
|
24
|
+
const query = new URLSearchParams({ token, path: encodePath(path) });
|
|
25
|
+
return `${opts.baseUrl}${PREVIEW_PATH}?${query.toString()}`;
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* What the request's preview cookie says: `'preview'` when it carries a valid one, otherwise `'published'`, and the
|
|
29
|
+
* staged release it previews (null for the live site's drafts or without a cookie).
|
|
30
|
+
*/
|
|
31
|
+
export function readPreview(request, secret, now) {
|
|
32
|
+
const token = readCookie(request, PREVIEW_COOKIE);
|
|
33
|
+
const valid = token === undefined ? null : verifyPreviewToken(secret, token, now);
|
|
34
|
+
return valid === null ? { state: 'published', release: null } : { state: 'preview', release: valid.release };
|
|
35
|
+
}
|
|
36
|
+
/** `'preview'` when the request carries a valid preview cookie (of the live site or of a release), otherwise `'published'`. */
|
|
37
|
+
export function previewState(request, secret, now) {
|
|
38
|
+
return readPreview(request, secret, now).state;
|
|
39
|
+
}
|
|
40
|
+
/** `raw` when it's a clean, encoded site-relative path, otherwise `/`. */
|
|
41
|
+
function safeTarget(raw) {
|
|
42
|
+
if (typeof raw !== 'string')
|
|
43
|
+
return '/';
|
|
44
|
+
const normalized = normalizePath(raw);
|
|
45
|
+
return normalized !== null && encodePath(normalized) === raw ? raw : '/';
|
|
46
|
+
}
|
|
47
|
+
/** Turns preview off for this browser. */
|
|
48
|
+
export function clearPreviewCookie(reply, baseUrl) {
|
|
49
|
+
setCookie(reply, '', 0, baseUrl.startsWith('https:'));
|
|
50
|
+
}
|
|
51
|
+
function setCookie(reply, value, maxAge, secure) {
|
|
52
|
+
const parts = [`${PREVIEW_COOKIE}=${value}`, 'Path=/', 'HttpOnly', 'SameSite=Lax', `Max-Age=${maxAge}`];
|
|
53
|
+
if (secure)
|
|
54
|
+
parts.push('Secure');
|
|
55
|
+
reply.header('set-cookie', parts.join('; '));
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* `GET /_inlay/preview?token&path` turns preview on for this browser (the cookie is the token, so it names the
|
|
59
|
+
* release a release link previews); `GET /_inlay/preview/exit` turns it off.
|
|
60
|
+
*/
|
|
61
|
+
export function registerPreviewRoutes(app, opts) {
|
|
62
|
+
const secure = opts.baseUrl.startsWith('https:');
|
|
63
|
+
app.get(PREVIEW_PATH, async (request, reply) => {
|
|
64
|
+
const query = request.query;
|
|
65
|
+
const token = typeof query.token === 'string' ? query.token : '';
|
|
66
|
+
const now = opts.now();
|
|
67
|
+
const valid = verifyPreviewToken(opts.secret, token, now);
|
|
68
|
+
reply.header('cache-control', 'no-store').header('x-robots-tag', 'noindex');
|
|
69
|
+
if (!valid) {
|
|
70
|
+
return reply
|
|
71
|
+
.code(403)
|
|
72
|
+
.type('text/html; charset=utf-8')
|
|
73
|
+
.send(catalogPage('preview.expired.title', 'preview.expired'));
|
|
74
|
+
}
|
|
75
|
+
setCookie(reply, token, Math.ceil((valid.expiresAt.getTime() - now.getTime()) / 1000), secure);
|
|
76
|
+
return reply.redirect(safeTarget(query.path), 302);
|
|
77
|
+
});
|
|
78
|
+
app.get(PREVIEW_EXIT_PATH, async (_request, reply) => {
|
|
79
|
+
setCookie(reply, '', 0, secure);
|
|
80
|
+
return reply.header('cache-control', 'no-store').redirect('/', 302);
|
|
81
|
+
});
|
|
82
|
+
}
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { lstat, readFile, realpath } from 'node:fs/promises';
|
|
3
|
+
import { extname, resolve, sep } from 'node:path';
|
|
4
|
+
import { etagMatches } from './cache.js';
|
|
5
|
+
import { catalogPage } from './render.js';
|
|
6
|
+
const TYPES = {
|
|
7
|
+
'.css': 'text/css; charset=utf-8',
|
|
8
|
+
'.js': 'text/javascript; charset=utf-8',
|
|
9
|
+
'.mjs': 'text/javascript; charset=utf-8',
|
|
10
|
+
'.json': 'application/json; charset=utf-8',
|
|
11
|
+
'.svg': 'image/svg+xml',
|
|
12
|
+
'.png': 'image/png',
|
|
13
|
+
'.jpg': 'image/jpeg',
|
|
14
|
+
'.jpeg': 'image/jpeg',
|
|
15
|
+
'.gif': 'image/gif',
|
|
16
|
+
'.webp': 'image/webp',
|
|
17
|
+
'.avif': 'image/avif',
|
|
18
|
+
'.ico': 'image/x-icon',
|
|
19
|
+
'.woff': 'font/woff',
|
|
20
|
+
'.woff2': 'font/woff2',
|
|
21
|
+
'.ttf': 'font/ttf',
|
|
22
|
+
'.txt': 'text/plain; charset=utf-8',
|
|
23
|
+
'.xml': 'application/xml; charset=utf-8',
|
|
24
|
+
'.webmanifest': 'application/manifest+json; charset=utf-8',
|
|
25
|
+
'.pdf': 'application/pdf',
|
|
26
|
+
'.map': 'application/json; charset=utf-8',
|
|
27
|
+
};
|
|
28
|
+
const ENCODED = /%2e|%2f|%5c/i;
|
|
29
|
+
/** The absolute path under `dir` that the raw wildcard names, or null when it is empty, tricky or outside `dir`. */
|
|
30
|
+
function locate(dir, rawPath) {
|
|
31
|
+
if (rawPath === '' || ENCODED.test(rawPath) || rawPath.includes('\\'))
|
|
32
|
+
return null;
|
|
33
|
+
let decoded;
|
|
34
|
+
try {
|
|
35
|
+
decoded = decodeURIComponent(rawPath);
|
|
36
|
+
}
|
|
37
|
+
catch {
|
|
38
|
+
return null;
|
|
39
|
+
}
|
|
40
|
+
if (decoded.includes('\\') || decoded.includes('\0'))
|
|
41
|
+
return null;
|
|
42
|
+
const segments = decoded.split('/');
|
|
43
|
+
if (segments.some((s) => s === '' || s.startsWith('.')))
|
|
44
|
+
return null;
|
|
45
|
+
const root = resolve(dir);
|
|
46
|
+
const file = resolve(root, ...segments);
|
|
47
|
+
return file.startsWith(root + sep) ? file : null;
|
|
48
|
+
}
|
|
49
|
+
/** Serves the files under `opts.dir` at `/public/*`, GET and HEAD, never anything outside it. */
|
|
50
|
+
export function registerPublicRoutes(app, opts) {
|
|
51
|
+
app.route({
|
|
52
|
+
method: ['GET', 'HEAD'],
|
|
53
|
+
url: '/public/*',
|
|
54
|
+
handler: async (request, reply) => {
|
|
55
|
+
const missing = () => reply.code(404).type('text/html; charset=utf-8').header('cache-control', 'no-store').send(catalogPage('site.notFound.title', 'site.notFound'));
|
|
56
|
+
const wildcard = request.params['*'] ?? '';
|
|
57
|
+
const q = request.raw.url?.indexOf('?') ?? -1;
|
|
58
|
+
const rawUrl = request.raw.url ?? '';
|
|
59
|
+
const rawPath = (q === -1 ? rawUrl : rawUrl.slice(0, q)).slice('/public/'.length);
|
|
60
|
+
const file = locate(opts.dir, rawPath === '' ? wildcard : rawPath);
|
|
61
|
+
if (file === null)
|
|
62
|
+
return missing();
|
|
63
|
+
let bytes;
|
|
64
|
+
try {
|
|
65
|
+
// A symlink is never followed: not as the file, nor as a folder on the way to it.
|
|
66
|
+
if (!(await lstat(file)).isFile())
|
|
67
|
+
return missing();
|
|
68
|
+
if (!(await realpath(file)).startsWith((await realpath(opts.dir)) + sep))
|
|
69
|
+
return missing();
|
|
70
|
+
bytes = await readFile(file);
|
|
71
|
+
}
|
|
72
|
+
catch {
|
|
73
|
+
return missing();
|
|
74
|
+
}
|
|
75
|
+
const etag = `"${createHash('sha256').update(bytes).digest('hex').slice(0, 32)}"`;
|
|
76
|
+
reply.header('cache-control', `public, max-age=${opts.maxAge}`).header('etag', etag);
|
|
77
|
+
if (etagMatches(request.headers['if-none-match'], etag))
|
|
78
|
+
return reply.code(304).send();
|
|
79
|
+
const ext = extname(file).toLowerCase();
|
|
80
|
+
reply.type(TYPES[ext] ?? 'application/octet-stream').header('x-content-type-options', 'nosniff');
|
|
81
|
+
// An SVG opened on its own could run script on the site's origin.
|
|
82
|
+
if (ext === '.svg')
|
|
83
|
+
reply.header('content-security-policy', "default-src 'none'; style-src 'unsafe-inline'");
|
|
84
|
+
return request.method === 'HEAD' ? reply.header('content-length', bytes.length).send() : reply.send(bytes);
|
|
85
|
+
},
|
|
86
|
+
});
|
|
87
|
+
}
|