@decocms/tanstack 8.9.1 → 8.10.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 (46) hide show
  1. package/README.md +4 -4
  2. package/dist/csp.d.ts +32 -0
  3. package/dist/csp.d.ts.map +1 -0
  4. package/dist/csp.js +76 -0
  5. package/dist/csp.js.map +1 -0
  6. package/dist/index.d.ts +5 -3
  7. package/dist/index.d.ts.map +1 -1
  8. package/dist/index.js +5 -3
  9. package/dist/index.js.map +1 -1
  10. package/dist/react/DecoDocument.d.ts +16 -2
  11. package/dist/react/DecoDocument.d.ts.map +1 -1
  12. package/dist/react/DecoDocument.js +15 -10
  13. package/dist/react/DecoDocument.js.map +1 -1
  14. package/dist/studio.d.ts +20 -0
  15. package/dist/studio.d.ts.map +1 -1
  16. package/dist/studio.js +47 -0
  17. package/dist/studio.js.map +1 -1
  18. package/dist/worker/assignments.d.ts.map +1 -1
  19. package/dist/worker/assignments.js +3 -9
  20. package/dist/worker/assignments.js.map +1 -1
  21. package/dist/worker/cache.d.ts +10 -2
  22. package/dist/worker/cache.d.ts.map +1 -1
  23. package/dist/worker/cache.js +26 -2
  24. package/dist/worker/cache.js.map +1 -1
  25. package/dist/worker/drafts.d.ts +2 -1
  26. package/dist/worker/drafts.d.ts.map +1 -1
  27. package/dist/worker/drafts.js +3 -2
  28. package/dist/worker/drafts.js.map +1 -1
  29. package/dist/worker/index.d.ts +14 -2
  30. package/dist/worker/index.d.ts.map +1 -1
  31. package/dist/worker/index.js +26 -39
  32. package/dist/worker/index.js.map +1 -1
  33. package/dist/worker/security.d.ts +7 -6
  34. package/dist/worker/security.d.ts.map +1 -1
  35. package/dist/worker/security.js +14 -30
  36. package/dist/worker/security.js.map +1 -1
  37. package/package.json +2 -2
  38. package/src/csp.ts +99 -0
  39. package/src/index.ts +12 -3
  40. package/src/react/DecoDocument.tsx +30 -6
  41. package/src/studio.ts +47 -0
  42. package/src/worker/assignments.ts +4 -13
  43. package/src/worker/cache.ts +19 -2
  44. package/src/worker/drafts.ts +3 -2
  45. package/src/worker/index.ts +42 -44
  46. package/src/worker/security.ts +19 -33
package/src/studio.ts CHANGED
@@ -31,6 +31,53 @@ export const STUDIO_FRAME_ANCESTORS: readonly string[] = Object.freeze([
31
31
  "https://*.deco.studio",
32
32
  ]);
33
33
 
34
+ /** Studio's production origin. */
35
+ export const STUDIO_ORIGIN = "https://studio.decocms.com";
36
+
37
+ /**
38
+ * The exact origins a page trusts for the Studio channel by default, and adds
39
+ * to its CSP (`script-src`, `frame-ancestors`): Studio's production and
40
+ * staging origins. No wildcard: each one is compared exactly.
41
+ */
42
+ export const DEFAULT_STUDIO_ORIGINS: readonly string[] = Object.freeze([
43
+ STUDIO_ORIGIN,
44
+ "https://studio-stg.decocms.com",
45
+ ]);
46
+
47
+ /** `value` as an exact http(s) origin (`https://host[:port]`, a trailing `/` dropped; no wildcard), or `""`. */
48
+ function asOrigin(value: unknown): string {
49
+ if (typeof value !== "string") return "";
50
+ const trimmed = value.trim();
51
+ try {
52
+ const url = new URL(trimmed);
53
+ if (url.protocol !== "https:" && url.protocol !== "http:") return "";
54
+ // A host name or an IP address: a URL parser accepts `*` in a host, which a
55
+ // CSP source would read as a wildcard.
56
+ if (!/^(\[[0-9a-f:.]+\]|[a-z0-9_.-]+)$/.test(url.hostname)) return "";
57
+ return trimmed === url.origin || trimmed === `${url.origin}/` ? url.origin : "";
58
+ } catch {
59
+ return "";
60
+ }
61
+ }
62
+
63
+ /**
64
+ * The Studio origins the page trusts: the Studio channel accepts messages and
65
+ * modules from them, and the binding adds them to the page's CSP `script-src`
66
+ * and `frame-ancestors`. The binding option when given (an empty list turns
67
+ * the channel off), else the `DECO_STUDIO_ORIGIN` environment variable, a
68
+ * comma-separated list (a local or staging Studio, such as
69
+ * `http://localhost:3000`; read where `process.env` exists, so on the
70
+ * server), else {@link DEFAULT_STUDIO_ORIGINS}. Each entry must be an exact
71
+ * http(s) origin; any other value (a path, a wildcard, a CSP keyword) is
72
+ * dropped, so the list never widens the CSP beyond origins.
73
+ */
74
+ export function studioOrigins(option?: readonly string[]): readonly string[] {
75
+ const env = (globalThis as { process?: { env?: Record<string, string | undefined> } }).process
76
+ ?.env?.DECO_STUDIO_ORIGIN;
77
+ const list = option ?? (env?.trim() ? env.split(",") : DEFAULT_STUDIO_ORIGINS);
78
+ return [...new Set(list.map(asOrigin).filter(Boolean))];
79
+ }
80
+
34
81
  /**
35
82
  * Whether `origin` (a `MessageEvent.origin`, an `Origin` header) is one of
36
83
  * {@link STUDIO_ORIGINS}: `https`, the default port, and `decocms.com` or a
@@ -38,22 +38,13 @@ function isRecord(value: unknown): value is Record<string, unknown> {
38
38
  }
39
39
 
40
40
  /**
41
- * Whether the content saves a block of `type`: listing never fails on a
42
- * missing block, so a site without tests or campaigns reports no error.
41
+ * The saved `block` resolved, each name `true` or `false`; none when it is
42
+ * missing. Whether it exists comes from the index (`NOT_FOUND`, which is no
43
+ * error to report), with no body listed.
43
44
  */
44
- async function saves(client: Reader, type: string): Promise<boolean> {
45
- const [list] = await client.list(type);
46
- return (list?.length ?? 0) > 0;
47
- }
48
-
49
- /** The saved `block` resolved, each name `true` or `false`; none when it is missing. */
50
- async function decided(
51
- client: Reader,
52
- spec: { block: string; type: string },
53
- ): Promise<Assignments> {
45
+ async function decided(client: Reader, spec: { block: string }): Promise<Assignments> {
54
46
  const out = record();
55
47
  try {
56
- if (!(await saves(client, spec.type))) return out;
57
48
  const [value] = await client.resolve<unknown>(spec.block);
58
49
  if (!isRecord(value)) return out;
59
50
  for (const name of Object.keys(value).sort(byCodeUnit)) out[name] = value[name] === true;
@@ -4,9 +4,10 @@
4
4
  * version every key carries, and the version (draft or old release) a request
5
5
  * renders. The worker caches nothing itself.
6
6
  */
7
- import type { CMS } from "@decocms/blocks";
7
+ import { type CMS, matchRoute } from "@decocms/blocks";
8
8
  import { VERSION_HEADER } from "../draft.ts";
9
9
  import { hasDraftSignal } from "./drafts.ts";
10
+ import { serverFnPagePath } from "./serverFn.ts";
10
11
 
11
12
  /**
12
13
  * Whether a request may be served from or stored in a shared cache at all:
@@ -35,14 +36,30 @@ export function isCacheable(
35
36
  * `<build>.<content revision>`, for every cache key: a new build or a
36
37
  * published release gets new entries at once. The build alone when the
37
38
  * revision can't be read.
39
+ *
40
+ * With `url` (the request's, `page.url`), the revision is the one the page
41
+ * renders. Right after a publish, a page whose new blocks aren't cached yet is
42
+ * served on the previous index while they load (the previous-index rule):
43
+ * this pins the same way, on the page the URL routes to (for a server
44
+ * function, the page its payload loads), so a page rendered on the previous
45
+ * index is never stored under the new revision. Without `url`, the revision a
46
+ * request that reads no page pins.
38
47
  */
39
48
  export async function cacheVersion(
40
49
  cms: Pick<CMS, "forRelease">,
41
50
  buildHash: string,
51
+ url?: URL,
42
52
  ): Promise<string> {
43
53
  let revision = "";
44
54
  try {
45
- revision = await cms.forRelease().revision();
55
+ const client = cms.forRelease();
56
+ if (url !== undefined) {
57
+ const [routes] = await client.routes();
58
+ const match = matchRoute(serverFnPagePath(url) ?? url, { routes: routes ?? [] });
59
+ // Pins on the page, as the page's own client does.
60
+ if (match.kind === "match") client.prefetch(match.entry.name);
61
+ }
62
+ revision = await client.revision();
46
63
  } catch {
47
64
  // The content didn't load: key on the build only.
48
65
  }
@@ -117,7 +117,8 @@ export interface DraftDecision {
117
117
  * request first checks for the latest release, once (`cms.checkRelease()`),
118
118
  * and the host check and every draft read share that check. A draft
119
119
  * pointer is read once before the page renders (`forDraft(...).revision()`,
120
- * the same read the page makes, shared while in flight): a draft that can't
120
+ * the same read the page makes: every draft read under the request's release
121
+ * check shares one read of the draft's files): a draft that can't
121
122
  * be read gives the release and `unavailable`, never an error page.
122
123
  */
123
124
  export async function decideDraft(
@@ -161,7 +162,7 @@ export async function decideDraft(
161
162
  */
162
163
  function isDraftGone(error: unknown): boolean {
163
164
  for (let e = error, depth = 0; e instanceof Error && depth < 5; e = e.cause, depth++) {
164
- if (/draft changes: HTTP (404|410)\b/.test(e.message)) return true;
165
+ if (/draft (?:changes|index): HTTP (?:404|410)\b/.test(e.message)) return true;
165
166
  }
166
167
  return false;
167
168
  }
@@ -24,7 +24,8 @@
24
24
  * copy never carries one. A page request with `Authorization` is never
25
25
  * handed to it and answers `private, no-cache, no-store`. A response with no
26
26
  * `CDN-Cache-Control` tells the CDN `no-store`, at one exit.
27
- * - Security headers and `frame-ancestors` for Studio; immutable fingerprinted
27
+ * - Security headers, and Studio's origins in the CSP (`frame-ancestors`,
28
+ * `script-src`: the Studio channel's list, `studioOrigins`); immutable fingerprinted
28
29
  * assets; one `Set-Cookie` per cookie; `x-page-status`.
29
30
  * - The visitor: on a page or server-function request, `readVisitor` from
30
31
  * `@decocms/blocks/experiments` (the `deco_segment` cookie, or a new
@@ -44,13 +45,14 @@
44
45
  * `pageCache` answered with) and the device; nothing when the CMS has no
45
46
  * telemetry.
46
47
  */
47
- import { type CMS, matchRoute, type Redirect, type Route } from "@decocms/blocks";
48
+ import { type CMS, matchRoute, type Redirect } from "@decocms/blocks";
48
49
  import { readVisitor, serializeVisitor, type Visitor } from "@decocms/blocks/experiments";
49
50
  import { recordServerRequest } from "@decocms/blocks/metrics";
50
51
  import { runInScope } from "@decocms/tanstack/scope";
51
52
  import { ASSIGNMENTS_HEADER, serializeAssignments } from "../assignments.ts";
52
53
  import { draftResponseHeaders, RELEASE_CHECK_HEADER, VERSION_HEADER } from "../draft.ts";
53
54
  import { PAGE_STATUS_HEADER } from "../shared.ts";
55
+ import { studioOrigins } from "../studio.ts";
54
56
  import { VISITOR_HEADER } from "../visitor.ts";
55
57
  import { type RequestAssignments, readAssignments } from "./assignments.ts";
56
58
  import { isCacheable } from "./cache.ts";
@@ -128,8 +130,19 @@ export interface DecoWorkerOptions<Env = unknown> {
128
130
  cms: CMS;
129
131
  /** Local development (`import.meta.env.DEV`): `pageCache` is never called, loopback may frame the site. */
130
132
  dev?: boolean;
131
- /** The site's Content-Security-Policy. Studio's `frame-ancestors` is always added. */
133
+ /**
134
+ * The site's Content-Security-Policy. Studio's origins are always added:
135
+ * to `frame-ancestors` (when the site sets none) and to `script-src`.
136
+ */
132
137
  csp?: CspOptions;
138
+ /**
139
+ * The Studio origins the CSP allows (`script-src`, `frame-ancestors`),
140
+ * exact origins. Default: `DECO_STUDIO_ORIGIN` (comma-separated), else
141
+ * Studio's production and staging origins (`studioOrigins()` of
142
+ * `@decocms/tanstack`). A site that sets `studioOrigins` on `DecoDocument`
143
+ * sets the same list here; `DECO_STUDIO_ORIGIN` sets both.
144
+ */
145
+ studioOrigins?: readonly string[];
133
146
  /**
134
147
  * The site's own page cache (the example worker entry the README links), called for
135
148
  * every page and server-function request `isCacheable` accepts. Without
@@ -231,58 +244,38 @@ function mutable(response: Response): Response {
231
244
  export function createDecoWorker<Env = unknown>(options: DecoWorkerOptions<Env>): DecoWorker<Env> {
232
245
  const { cms, serverEntry } = options;
233
246
  const dev = options.dev === true;
234
- const securityHeaders = htmlSecurityHeaders(options.csp, dev);
247
+ // On the first HTML response, not at creation: the environment is read where
248
+ // the document reads it.
249
+ let securityHeaders: Record<string, string> | undefined;
235
250
  const preloadLinks = [
236
251
  ...(options.preload?.styles ?? []).map((href) => `<${href}>; rel=preload; as=style`),
237
252
  ...(options.preload?.fonts ?? []).map((href) => `<${href}>; rel=preload; as=font; crossorigin`),
238
253
  ];
239
254
 
240
- // The release's redirects, read once per revision (a draft's are read each time).
241
- let releaseRedirects: { revision: string; list: Promise<Redirect[]> } | undefined;
242
-
255
+ // The redirects block, read through the client (its body is held by hash
256
+ // once fetched). The page the URL routes to is prefetched first, so its
257
+ // subtree goes out in the same wave as the redirects block (the app's
258
+ // later reads find the bodies by hash) and this client pins the index the
259
+ // page's client pins.
243
260
  async function redirectsFor(
261
+ url: URL,
244
262
  pointer: string | null,
245
263
  releaseCheck: string | undefined,
246
264
  ): Promise<Redirect[]> {
247
- const read = async (client: ReturnType<CMS["forRelease"]>) => {
248
- const [list] = await client.list<Redirect>("redirect");
249
- return list ?? [];
250
- };
251
- if (pointer) return read(cms.client({ version: pointer, releaseCheck }));
252
- const client = cms.client();
253
- const revision = await client.revision();
254
- if (releaseRedirects?.revision !== revision) {
255
- releaseRedirects = { revision, list: read(client) };
256
- }
257
- return releaseRedirects.list;
265
+ const client = pointer ? cms.client({ version: pointer, releaseCheck }) : cms.client();
266
+ const [routes] = await client.routes();
267
+ const match = matchRoute(url, { routes: routes ?? [] });
268
+ if (match.kind === "match") client.prefetch(match.entry.name);
269
+ const [list] = await client.redirects();
270
+ return list ?? [];
258
271
  }
259
272
 
260
- // The release's page templates, for `http.route`: read once per revision,
261
- // and only while telemetry is measuring (`recordServerRequest` calls the
262
- // route function only then).
263
- let metricRoutes: { revision: string; pages: Promise<Route[]> } | undefined;
264
-
273
+ // The release's page templates, for `http.route`: the index's routes, read
274
+ // only while telemetry is measuring (`recordServerRequest` calls the route
275
+ // function only then). The same array per revision, so its trie is built once.
265
276
  async function routeTemplate(url: URL): Promise<string | undefined> {
266
- const client = cms.forRelease();
267
- const revision = await client.revision();
268
- let routes = metricRoutes;
269
- if (routes?.revision !== revision) {
270
- const pages = client
271
- .list<{ path?: unknown }>("page")
272
- .then(([list]) =>
273
- (list ?? []).flatMap((p) =>
274
- typeof p?.path === "string" ? [{ name: p.path, path: p.path }] : [],
275
- ),
276
- );
277
- const entry = { revision, pages };
278
- metricRoutes = entry;
279
- routes = entry;
280
- // A failed read is tried again on the next request, not kept for the revision.
281
- pages.catch(() => {
282
- if (metricRoutes === entry) metricRoutes = undefined;
283
- });
284
- }
285
- const match = matchRoute(url, { routes: await routes.pages });
277
+ const [routes] = await cms.forRelease().routes();
278
+ const match = matchRoute(url, { routes: routes ?? [] });
286
279
  return match.kind === "match" ? match.entry.path : undefined;
287
280
  }
288
281
 
@@ -328,7 +321,7 @@ export function createDecoWorker<Env = unknown>(options: DecoWorkerOptions<Env>)
328
321
  releaseCheck: string | undefined,
329
322
  ): Promise<Response | null> {
330
323
  try {
331
- const redirects = await redirectsFor(pointer, releaseCheck);
324
+ const redirects = await redirectsFor(url, pointer, releaseCheck);
332
325
  if (!redirects.length) return null;
333
326
  const match = matchRoute(url, { routes: [], redirects });
334
327
  if (match.kind !== "redirect") return null;
@@ -587,6 +580,11 @@ export function createDecoWorker<Env = unknown>(options: DecoWorkerOptions<Env>)
587
580
  if (served.visitorCookie) response.headers.append("Set-Cookie", served.visitorCookie);
588
581
  dedupeSetCookies(response);
589
582
  if (isHtml(response)) {
583
+ securityHeaders ??= htmlSecurityHeaders(
584
+ options.csp,
585
+ dev,
586
+ studioOrigins(options.studioOrigins),
587
+ );
590
588
  for (const [k, v] of Object.entries(securityHeaders)) {
591
589
  if (!response.headers.has(k)) response.headers.set(k, v);
592
590
  }
@@ -1,11 +1,13 @@
1
1
  /**
2
2
  * The headers every HTML response carries: v7's security headers, the site's
3
- * Content-Security-Policy, and `frame-ancestors` so Deco Studio's site editor
4
- * (and nothing else the site doesn't name) can show the page in its frame. No
5
- * `X-Frame-Options`: `frame-ancestors` supersedes it and, unlike `SAMEORIGIN`,
6
- * can allow Studio's origin.
3
+ * Content-Security-Policy, and what Studio needs in it (`withStudioCsp`):
4
+ * `frame-ancestors` so Deco Studio's site editor (and nothing else the site
5
+ * doesn't name) can show the page in its frame, and Studio's origins in
6
+ * `script-src` so the Studio channel can import Studio's modules. No
7
+ * `X-Frame-Options`: `frame-ancestors` supersedes it and, unlike
8
+ * `SAMEORIGIN`, can allow Studio's origin.
7
9
  */
8
- import { STUDIO_FRAME_ANCESTORS } from "../studio.ts";
10
+ import { cspDirectives, withStudioCsp } from "../csp.ts";
9
11
 
10
12
  export const SECURITY_HEADERS: Readonly<Record<string, string>> = {
11
13
  "X-Content-Type-Options": "nosniff",
@@ -16,45 +18,29 @@ export const SECURITY_HEADERS: Readonly<Record<string, string>> = {
16
18
  "Cross-Origin-Opener-Policy": "same-origin-allow-popups",
17
19
  };
18
20
 
19
- /** A Studio on this machine, in local development. */
20
- const LOOPBACK_ANCESTORS = ["http://localhost:*", "http://127.0.0.1:*"];
21
-
22
21
  export interface CspOptions {
23
- /** The enforced policy's directives (`frame-ancestors` is added when they have none). */
22
+ /**
23
+ * The enforced policy's directives. `frame-ancestors` is added when they
24
+ * have none; Studio's origins are added to `script-src` (`withStudioCsp`).
25
+ */
24
26
  enforce?: string | readonly string[];
25
- /** Directives sent as `Content-Security-Policy-Report-Only`. */
27
+ /** Directives sent as `Content-Security-Policy-Report-Only` (Studio's origins added to its `script-src`). */
26
28
  reportOnly?: string | readonly string[];
27
29
  /** More origins that may frame the site, besides Studio's (a marketing tool's editor). */
28
30
  frameAncestors?: readonly string[];
29
31
  }
30
32
 
31
- function directives(value: string | readonly string[] | undefined): string[] {
32
- if (value === undefined) return [];
33
- const list = typeof value === "string" ? value.split(";") : [...value];
34
- return list.map((d) => d.trim()).filter(Boolean);
35
- }
36
-
37
- /** The `frame-ancestors` sources: Studio's, the site's own, and loopback in development. */
38
- export function frameAncestors(csp: CspOptions | undefined, dev: boolean): string[] {
39
- return [
40
- ...new Set([
41
- ...STUDIO_FRAME_ANCESTORS,
42
- ...(csp?.frameAncestors ?? []),
43
- ...(dev ? LOOPBACK_ANCESTORS : []),
44
- ]),
45
- ];
46
- }
47
-
48
- /** Every HTML response's security headers. */
33
+ /** Every HTML response's security headers. `studioOrigins`: the list the Studio channel trusts. */
49
34
  export function htmlSecurityHeaders(
50
35
  csp: CspOptions | undefined,
51
36
  dev: boolean,
37
+ studioOrigins?: readonly string[],
52
38
  ): Record<string, string> {
53
- const enforce = directives(csp?.enforce);
54
- if (!enforce.some((d) => /^frame-ancestors(\s|$)/i.test(d))) {
55
- enforce.push(`frame-ancestors ${frameAncestors(csp, dev).join(" ")}`);
56
- }
57
- const reportOnly = directives(csp?.reportOnly);
39
+ const options = { studioOrigins, frameAncestors: csp?.frameAncestors, dev };
40
+ const enforce = withStudioCsp(csp?.enforce, options);
41
+ const reportOnly = cspDirectives(csp?.reportOnly).length
42
+ ? withStudioCsp(csp?.reportOnly, { ...options, addFrameAncestors: false })
43
+ : [];
58
44
  return {
59
45
  ...SECURITY_HEADERS,
60
46
  "Content-Security-Policy": enforce.join("; "),