@decocms/blocks 7.71.6 → 8.0.0-next.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 (148) hide show
  1. package/bin/deco.js +13 -0
  2. package/package.json +32 -3
  3. package/src/cms/schema.ts +1 -1
  4. package/src/hooks/LiveControls.tsx +2 -0
  5. package/src/hooks/useLoadMore.ts +2 -0
  6. package/src/index.ts +37 -0
  7. package/src/protocol/assets.ts +124 -0
  8. package/src/protocol/canonical.ts +7 -0
  9. package/src/protocol/ciphertext.ts +6 -0
  10. package/src/protocol/client.ts +170 -0
  11. package/src/protocol/conformance/cases/assets.ts +81 -0
  12. package/src/protocol/conformance/cases/guards.ts +314 -0
  13. package/src/protocol/conformance/cases/reads.ts +168 -0
  14. package/src/protocol/conformance/cases/types.ts +9 -0
  15. package/src/protocol/conformance/cases/wire.ts +138 -0
  16. package/src/protocol/conformance/cases/writes.ts +345 -0
  17. package/src/protocol/conformance/contentHashFixtures.ts +79 -0
  18. package/src/protocol/conformance/context.ts +222 -0
  19. package/src/protocol/conformance/index.ts +140 -0
  20. package/src/protocol/errors.ts +142 -0
  21. package/src/protocol/index.ts +39 -0
  22. package/src/protocol/keys.ts +279 -0
  23. package/src/protocol/params.ts +67 -0
  24. package/src/protocol/secrets.ts +231 -0
  25. package/src/protocol/server/assets.ts +119 -0
  26. package/src/protocol/server/auth.ts +49 -0
  27. package/src/protocol/server/bodyCache.ts +84 -0
  28. package/src/protocol/server/content.ts +175 -0
  29. package/src/protocol/server/core.ts +112 -0
  30. package/src/protocol/server/handler.ts +102 -0
  31. package/src/protocol/server/http.ts +139 -0
  32. package/src/protocol/server/index.ts +11 -0
  33. package/src/protocol/server/methods/apply.ts +341 -0
  34. package/src/protocol/server/methods/read.ts +156 -0
  35. package/src/protocol/server/rpc.ts +136 -0
  36. package/src/protocol/storage/fs/hash.ts +21 -0
  37. package/src/protocol/storage/fs/index.ts +338 -0
  38. package/src/protocol/storage/fs/lock.ts +68 -0
  39. package/src/protocol/storage/fs/transaction.ts +183 -0
  40. package/src/protocol/storage/fs/unsupported.ts +15 -0
  41. package/src/protocol/storage/memory.ts +238 -0
  42. package/src/protocol/storage.ts +182 -0
  43. package/src/protocol/types.ts +172 -0
  44. package/src/v8/analytics.ts +50 -0
  45. package/src/v8/background.ts +107 -0
  46. package/src/v8/builtins/data.ts +23 -0
  47. package/src/v8/builtins/index.ts +26 -0
  48. package/src/v8/builtins/lazy.ts +23 -0
  49. package/src/v8/builtins/legacy.ts +65 -0
  50. package/src/v8/builtins/matchers.ts +31 -0
  51. package/src/v8/builtins/multivariate.ts +25 -0
  52. package/src/v8/builtins/secret.ts +82 -0
  53. package/src/v8/canonical.ts +117 -0
  54. package/src/v8/ciphertext.ts +158 -0
  55. package/src/v8/cli/builtins.ts +20 -0
  56. package/src/v8/cli/check/index.ts +774 -0
  57. package/src/v8/cli/check/messages.ts +168 -0
  58. package/src/v8/cli/content.ts +287 -0
  59. package/src/v8/cli/index.ts +17 -0
  60. package/src/v8/cli/log.ts +18 -0
  61. package/src/v8/cli/main.ts +12 -0
  62. package/src/v8/cli/root.ts +66 -0
  63. package/src/v8/cli/run.ts +236 -0
  64. package/src/v8/cli/schema/builtinSchemas.ts +236 -0
  65. package/src/v8/cli/schema/generate.ts +507 -0
  66. package/src/v8/cli/schema/index.ts +63 -0
  67. package/src/v8/cli/schema/tsProgram.ts +497 -0
  68. package/src/v8/cli/schema/typeToSchema.ts +689 -0
  69. package/src/v8/cli/serve/server.ts +303 -0
  70. package/src/v8/cli/watch.ts +86 -0
  71. package/src/v8/client.ts +147 -0
  72. package/src/v8/cms.ts +237 -0
  73. package/src/v8/content.ts +195 -0
  74. package/src/v8/draft.ts +136 -0
  75. package/src/v8/errors.ts +59 -0
  76. package/src/v8/fetch.ts +152 -0
  77. package/src/v8/identity.ts +65 -0
  78. package/src/v8/index.ts +39 -0
  79. package/src/v8/json.ts +74 -0
  80. package/src/v8/matchRoute.ts +204 -0
  81. package/src/v8/remoteLoader.ts +282 -0
  82. package/src/v8/resolver.ts +278 -0
  83. package/src/v8/secrets.ts +17 -0
  84. package/src/v8/telemetry.ts +533 -0
  85. package/src/v8/types.ts +240 -0
  86. package/src/cms/blockSource.test.ts +0 -76
  87. package/src/cms/client.browserBundle.test.ts +0 -44
  88. package/src/cms/deferredTrigger.test.ts +0 -32
  89. package/src/cms/draftSource.test.ts +0 -519
  90. package/src/cms/layoutCacheRace.test.ts +0 -181
  91. package/src/cms/loadDecofileDirectory.test.ts +0 -109
  92. package/src/cms/loader.test.ts +0 -557
  93. package/src/cms/registry.test.ts +0 -110
  94. package/src/cms/renderJson.test.ts +0 -167
  95. package/src/cms/resolve.test.ts +0 -1492
  96. package/src/cms/schema.test.ts +0 -356
  97. package/src/cms/sectionLoaderContext.test.ts +0 -111
  98. package/src/cms/sectionLoaders.test.ts +0 -625
  99. package/src/cms/sectionMixins.test.ts +0 -167
  100. package/src/cms/stickyFlags.test.ts +0 -117
  101. package/src/flags/flags.test.ts +0 -148
  102. package/src/hooks/Image.test.ts +0 -239
  103. package/src/hooks/RenderSection.test.tsx +0 -81
  104. package/src/hooks/Stats.test.ts +0 -112
  105. package/src/hooks/useLoadMore.test.ts +0 -205
  106. package/src/matchers/builtins.test.ts +0 -318
  107. package/src/matchers/override.test.ts +0 -205
  108. package/src/middleware/hydrationContext.test.ts +0 -61
  109. package/src/middleware/observability.test.ts +0 -335
  110. package/src/middleware/validateSection.test.ts +0 -147
  111. package/src/preview/DraftPreviewBadge.render.test.tsx +0 -67
  112. package/src/preview/DraftPreviewBadge.test.ts +0 -55
  113. package/src/sdk/abTesting.test.ts +0 -381
  114. package/src/sdk/cacheHeaders.test.ts +0 -258
  115. package/src/sdk/cacheStorage.test.ts +0 -242
  116. package/src/sdk/cachedLoader.test.ts +0 -122
  117. package/src/sdk/cachedLoaderMaxBytes.test.ts +0 -23
  118. package/src/sdk/cachedLoaderModule.test.ts +0 -209
  119. package/src/sdk/cachedLoaderSizeMetric.test.ts +0 -93
  120. package/src/sdk/cn.test.ts +0 -34
  121. package/src/sdk/composite.test.ts +0 -121
  122. package/src/sdk/cookie.test.ts +0 -108
  123. package/src/sdk/crypto.test.ts +0 -65
  124. package/src/sdk/deepOmit.test.ts +0 -45
  125. package/src/sdk/encoding.test.ts +0 -71
  126. package/src/sdk/env.test.ts +0 -33
  127. package/src/sdk/experiments.test.ts +0 -328
  128. package/src/sdk/fetchCache.test.ts +0 -164
  129. package/src/sdk/flags.test.ts +0 -91
  130. package/src/sdk/http.test.ts +0 -71
  131. package/src/sdk/inflightTimeout.test.ts +0 -35
  132. package/src/sdk/instrumentedFetch.test.ts +0 -559
  133. package/src/sdk/invoke.test.ts +0 -115
  134. package/src/sdk/logger.test.ts +0 -432
  135. package/src/sdk/otel.test.ts +0 -691
  136. package/src/sdk/otelAdapters.test.ts +0 -89
  137. package/src/sdk/otelHttpLog.test.ts +0 -457
  138. package/src/sdk/otelHttpMeter.test.ts +0 -395
  139. package/src/sdk/otelHttpTracer.test.ts +0 -474
  140. package/src/sdk/replaceStream.test.ts +0 -117
  141. package/src/sdk/requestContextStorage.browser.test.ts +0 -29
  142. package/src/sdk/splitExactRedirects.test.ts +0 -154
  143. package/src/sdk/urlRedaction.test.ts +0 -73
  144. package/src/sdk/urlUtils.test.ts +0 -34
  145. package/src/sdk/useDevice.test.ts +0 -130
  146. package/src/sdk/useScript.test.ts +0 -128
  147. package/src/sdk/useSuggestions.test.ts +0 -230
  148. package/tsconfig.json +0 -7
@@ -0,0 +1,107 @@
1
+ /**
2
+ * Work that runs beside requests, never in front of them: release checks and
3
+ * telemetry batches (see /next/hosted-releases-internals and
4
+ * /next/telemetry-internals#sending-in-the-background).
5
+ *
6
+ * Where it runs, in order:
7
+ * - a host hook a framework binding installs under {@link BACKGROUND_HOOK};
8
+ * - on Cloudflare Workers, which run no timers between requests, the
9
+ * platform's `waitUntil` (from `cloudflare:workers`), so the task runs
10
+ * after the response with no binding and no user code: the core installs
11
+ * that hook itself;
12
+ * - `requestIdleCallback` (browsers, React Native);
13
+ * - `scheduler.postTask({ priority: "background" })`;
14
+ * - an unref'd `setTimeout` (so Node never stays alive for it), then
15
+ * `setImmediate` where it exists.
16
+ *
17
+ * A task never throws into its caller: errors and rejections are swallowed.
18
+ */
19
+
20
+ /** Where a binding installs `(task) => void` to run background work its own way. */
21
+ const BACKGROUND_HOOK = Symbol.for("decocms.blocks.background");
22
+
23
+ type Task = () => unknown;
24
+
25
+ type WaitUntil = (promise: Promise<unknown>) => void;
26
+
27
+ /** Workers identify themselves in `navigator.userAgent`. */
28
+ function onWorkers(): boolean {
29
+ return (
30
+ (globalThis as { navigator?: { userAgent?: string } }).navigator?.userAgent ===
31
+ "Cloudflare-Workers"
32
+ );
33
+ }
34
+
35
+ /**
36
+ * `cloudflare:workers`, loaded once. The specifier is computed so bundlers
37
+ * for other targets (browsers, Node) never try to resolve it.
38
+ */
39
+ let workers: Promise<WaitUntil | undefined> | undefined;
40
+ function workersWaitUntil(): Promise<WaitUntil | undefined> {
41
+ const specifier = ["cloudflare", "workers"].join(":");
42
+ workers ??= import(/* @vite-ignore */ /* webpackIgnore: true */ specifier).then(
43
+ (mod: { waitUntil?: WaitUntil }) =>
44
+ typeof mod.waitUntil === "function" ? mod.waitUntil : undefined,
45
+ () => undefined,
46
+ );
47
+ return workers;
48
+ }
49
+
50
+ interface BackgroundGlobals {
51
+ [BACKGROUND_HOOK]?: (task: () => Promise<void>) => void;
52
+ requestIdleCallback?: (callback: () => void) => unknown;
53
+ scheduler?: {
54
+ postTask?: (callback: () => void, options: { priority: string }) => Promise<unknown>;
55
+ };
56
+ setImmediate?: (callback: () => void) => unknown;
57
+ }
58
+
59
+ export function runInBackground(task: Task): void {
60
+ const run = async (): Promise<void> => {
61
+ try {
62
+ await task();
63
+ } catch {
64
+ // Background work fails quietly; nothing reaches a request.
65
+ }
66
+ };
67
+ const g = globalThis as BackgroundGlobals;
68
+ const hook = g[BACKGROUND_HOOK];
69
+ if (typeof hook === "function") {
70
+ hook(run);
71
+ return;
72
+ }
73
+ if (onWorkers()) {
74
+ void workersWaitUntil().then((waitUntil) => {
75
+ if (waitUntil === undefined) return void run();
76
+ // From now on, hand every task straight to the platform.
77
+ if (typeof g[BACKGROUND_HOOK] !== "function") {
78
+ g[BACKGROUND_HOOK] = (next) => waitUntil(next());
79
+ }
80
+ g[BACKGROUND_HOOK]?.(run);
81
+ });
82
+ return;
83
+ }
84
+ if (typeof g.requestIdleCallback === "function") {
85
+ g.requestIdleCallback(() => void run());
86
+ return;
87
+ }
88
+ if (typeof g.scheduler?.postTask === "function") {
89
+ g.scheduler.postTask(() => void run(), { priority: "background" }).catch(() => {});
90
+ return;
91
+ }
92
+ later(0, () => {
93
+ if (typeof g.setImmediate === "function") g.setImmediate(() => void run());
94
+ else void run();
95
+ });
96
+ }
97
+
98
+ /** `setTimeout` that never keeps a Node process alive. */
99
+ export function later(ms: number, callback: () => void): void {
100
+ const timer = setTimeout(callback, ms) as unknown as { unref?: () => void };
101
+ timer?.unref?.();
102
+ }
103
+
104
+ /** Whether a binding installed a background hook (then batches go out after each response). */
105
+ export function hasBackgroundHook(): boolean {
106
+ return typeof (globalThis as BackgroundGlobals)[BACKGROUND_HOOK] === "function";
107
+ }
@@ -0,0 +1,23 @@
1
+ import type { Analytics, Redirect, Telemetry } from "../types";
2
+
3
+ /** The hosted Deco CMS collector: where page views go when `collector` is left out. */
4
+ export const HOSTED_ANALYTICS_COLLECTOR = "https://d.lilstts.com/events";
5
+
6
+ /**
7
+ * `page`: its inputs are already resolved (`seo` and every block in
8
+ * `sections`), so the page is its input.
9
+ */
10
+ export const page = <P>(props: P): P => props;
11
+
12
+ /** `redirect`: returns its arguments as saved. */
13
+ export const redirect = (props: Redirect): Redirect => props;
14
+
15
+ /** `telemetry`: the type of the well-known `Telemetry` saved block; returns its arguments. */
16
+ export const telemetry = (props: Telemetry = {}): Telemetry => props;
17
+
18
+ /** `analytics`: returns its input with the defaults filled in. */
19
+ export const analytics = (props: Analytics = {}): Required<Analytics> => ({
20
+ ...props,
21
+ collector: props.collector ?? HOSTED_ANALYTICS_COLLECTOR,
22
+ enabled: props.enabled ?? true,
23
+ });
@@ -0,0 +1,26 @@
1
+ import type { BlockFunction } from "../types";
2
+ import { analytics, page, redirect, telemetry } from "./data";
3
+ import { lazy } from "./lazy";
4
+ import { always, date, never } from "./matchers";
5
+ import { multivariate } from "./multivariate";
6
+ import { secretBlock } from "./secret";
7
+
8
+ /**
9
+ * The built-in blocks every block map gets. `secret` here has no key, so it
10
+ * always fails; each CMS replaces it with one holding its `secrets.key`.
11
+ */
12
+ export const builtIns: Readonly<Record<string, BlockFunction>> = Object.freeze({
13
+ lazy,
14
+ multivariate,
15
+ always,
16
+ never,
17
+ date,
18
+ page,
19
+ redirect,
20
+ telemetry,
21
+ analytics,
22
+ secret: secretBlock(),
23
+ });
24
+
25
+ /** Names no saved block can take (see /next/saved-blocks#names). */
26
+ export const RESERVED_NAMES: ReadonlySet<string> = new Set(Object.keys(builtIns));
@@ -0,0 +1,23 @@
1
+ import type { Lazy } from "../types";
2
+
3
+ /** Marks the built-in `lazy` function, the resolver's one special case. */
4
+ const LAZY_BLOCK: unique symbol = Symbol.for("decocms.blocks.v8.lazy");
5
+
6
+ /**
7
+ * The built-in `lazy` block. The resolver never calls it: it sees the marker
8
+ * and hands the parent a memoized `() => Promise<T>` that resolves `value`
9
+ * only when called. Called directly (outside the resolver), it wraps an
10
+ * already-resolved value, so it still honours the `Lazy<T>` contract.
11
+ */
12
+ export const lazy = Object.assign(
13
+ <T>({ value }: { value: T }): Lazy<T> =>
14
+ () =>
15
+ Promise.resolve(value),
16
+ { [LAZY_BLOCK]: true as const },
17
+ );
18
+
19
+ export function isLazyBuiltin(fn: unknown): boolean {
20
+ return (
21
+ typeof fn === "function" && (fn as unknown as Record<symbol, unknown>)[LAZY_BLOCK] === true
22
+ );
23
+ }
@@ -0,0 +1,65 @@
1
+ /**
2
+ * The legacy alias bridge: the well-known Fresh/Deno and v7 type names the
3
+ * site editor still writes, mapped to the built-ins, so v7 content resolves
4
+ * without a block-map entry (see /next/studio-compatibility#well-known-types-and-the-alias-table
5
+ * and /next/renames-and-migrations#rename-a-type-with-an-alias).
6
+ *
7
+ * A snapshot's own `aliases` (the table `deco content` writes) win over these, and a key in the block map wins over
8
+ * both, so a site can still register a legacy name itself.
9
+ *
10
+ * - Redirects keep v7's nested shape: `redirect` returns its arguments as
11
+ * saved, and `matchRoute` accepts both shapes.
12
+ * - `website/loaders/secret.ts` resolves as `secret`, which needs the
13
+ * `ciphertext` the one-time re-encryption writes (see
14
+ * /next/renames-and-migrations#secrets); a v7 `encrypted` value fails that
15
+ * block with `BLOCK_FAILED`.
16
+ * - Legacy variants are saved as plain values; on the way to `multivariate`
17
+ * each one is wrapped in a `lazy` block, so only the chosen one runs.
18
+ */
19
+ import { isPlainObject, type JsonObject } from "../json";
20
+
21
+ /**
22
+ * Legacy type name → built-in. The one table: the runtime falls back to it,
23
+ * and `deco schema` / `deco content` write it into the schema and the content
24
+ * module. Exactly the names the site editor's special screens look for
25
+ * (/next/studio-compatibility#well-known-types-and-the-alias-table); other
26
+ * legacy names (`$live/…`, the per-kind multivariate files, the date
27
+ * matcher) are rewritten to these by the one-time migration
28
+ * (`@decocms/blocks-migrate`), and types with no built-in counterpart are
29
+ * left to the site's block map.
30
+ */
31
+ export const LEGACY_ALIASES: Readonly<Record<string, string>> = Object.freeze({
32
+ "website/pages/Page.tsx": "page",
33
+ "$live/pages/LivePage.tsx": "page",
34
+ "website/flags/multivariate.ts": "multivariate",
35
+ "website/flags/multivariate/section.ts": "multivariate",
36
+ "website/matchers/always.ts": "always",
37
+ "website/matchers/never.ts": "never",
38
+ "website/loaders/redirect.ts": "redirect",
39
+ "website/loaders/secret.ts": "secret",
40
+ });
41
+
42
+ /**
43
+ * Whether a legacy name stores its variants' values plain (every legacy name
44
+ * for `multivariate`); under the short name each value carries a `lazy`.
45
+ */
46
+ export function storesPlainVariants(type: string): boolean {
47
+ return Object.hasOwn(LEGACY_ALIASES, type) && LEGACY_ALIASES[type] === "multivariate";
48
+ }
49
+
50
+ /**
51
+ * A legacy variants block with each plain `value` wrapped in `lazy`; any
52
+ * other block as is. A value that already is a `lazy` block stays one.
53
+ */
54
+ export function wrapLegacyVariants(type: string, node: JsonObject): JsonObject {
55
+ if (!storesPlainVariants(type) || !Array.isArray(node.variants)) return node;
56
+ return {
57
+ ...node,
58
+ variants: node.variants.map((variant) =>
59
+ isPlainObject(variant) &&
60
+ !(isPlainObject(variant.value) && variant.value.__resolveType === "lazy")
61
+ ? { ...variant, value: { __resolveType: "lazy", value: variant.value } }
62
+ : variant,
63
+ ),
64
+ };
65
+ }
@@ -0,0 +1,31 @@
1
+ /** `always`: the fallback rule. */
2
+ export const always = (): boolean => true;
3
+
4
+ /** `never`: the rule the site editor uses to hide a block. */
5
+ export const never = (): boolean => false;
6
+
7
+ /** Inputs of the built-in `date` matcher: ISO 8601 strings, both optional. */
8
+ interface DateProps {
9
+ /** Inclusive. */
10
+ start?: string;
11
+ /** Exclusive: `end` itself doesn't match. */
12
+ end?: string;
13
+ }
14
+
15
+ /**
16
+ * `date`: `true` from `start` (inclusive) until `end` (exclusive). A date
17
+ * without a time means midnight UTC. An unparseable bound never matches, so a
18
+ * typo can't switch a campaign on.
19
+ */
20
+ export const date = ({ start, end }: DateProps = {}): boolean => {
21
+ const now = Date.now();
22
+ if (start !== undefined && start !== null && start !== "") {
23
+ const from = Date.parse(start);
24
+ if (Number.isNaN(from) || now < from) return false;
25
+ }
26
+ if (end !== undefined && end !== null && end !== "") {
27
+ const until = Date.parse(end);
28
+ if (Number.isNaN(until) || now >= until) return false;
29
+ }
30
+ return true;
31
+ };
@@ -0,0 +1,25 @@
1
+ import type { Variant } from "../types";
2
+
3
+ interface MultivariateProps<T> {
4
+ variants?: Variant<T>[];
5
+ /** The stable ID of an A/B test; results are kept per ID. */
6
+ experiment?: string;
7
+ }
8
+
9
+ /**
10
+ * `multivariate`: runs the first variant whose rule is `true` and returns its
11
+ * value, or `undefined` when no rule is. Only the chosen variant runs, because
12
+ * each `value` is a `Lazy<T>`. A value saved without the `lazy` wrapper (which
13
+ * `deco check` flags) is returned as is rather than failing the page.
14
+ */
15
+ export const multivariate = async <T>({
16
+ variants,
17
+ }: MultivariateProps<T> = {}): Promise<T | undefined> => {
18
+ if (!Array.isArray(variants)) return undefined;
19
+ for (const variant of variants) {
20
+ if (variant?.rule !== true) continue;
21
+ const value = variant.value as unknown;
22
+ return typeof value === "function" ? await (value as () => Promise<T>)() : (value as T);
23
+ }
24
+ return undefined;
25
+ };
@@ -0,0 +1,82 @@
1
+ /**
2
+ * The built-in `secret` block (see /next/built-in-blocks#secrets):
3
+ * `{ "__resolveType": "secret", "ciphertext": "v1.…" }` resolves to the
4
+ * decrypted string, on the server only.
5
+ *
6
+ * The ciphertext format lives in `../ciphertext` (a leaf module with no
7
+ * imports, which the protocol re-exports): a fresh AES-256-GCM key per value, wrapped with the
8
+ * site's RSA public key using RSA-OAEP and SHA-256. Decrypting takes the
9
+ * matching PKCS#8 private key, the PEM `createCMS({ secrets: { key } })` gets.
10
+ *
11
+ * Every failure (no key, the wrong key, a malformed ciphertext, a browser)
12
+ * throws, so the resolver reports `BLOCK_FAILED` for that block alone. No
13
+ * message ever includes the key or a decrypted value. `{ run: false }` and
14
+ * `client.list` never run functions, so they return the ciphertext as saved.
15
+ *
16
+ * Every decrypted value is handed to `onDecrypt` (the CMS redacts it from
17
+ * telemetry). A decrypted value stays on the server because it's resolved
18
+ * there; tainting it (React's taint API) is up to the site's own code.
19
+ */
20
+ import { parseCiphertext } from "../ciphertext";
21
+ import type { BlockFunction } from "../types";
22
+
23
+ /** True in a browser, where a secret must never be decrypted. */
24
+ function inBrowser(): boolean {
25
+ const scope = globalThis as { window?: unknown; document?: unknown };
26
+ return typeof scope.window === "object" && typeof scope.document === "object";
27
+ }
28
+
29
+ /** The DER bytes of a single `PRIVATE KEY` (PKCS#8) PEM block. */
30
+ function privateKeyDer(pem: string): Uint8Array {
31
+ const match = /-----BEGIN PRIVATE KEY-----([\s\S]*?)-----END PRIVATE KEY-----/.exec(pem);
32
+ return Uint8Array.from(atob(match?.[1]?.replace(/\s+/g, "") ?? ""), (c) => c.charCodeAt(0));
33
+ }
34
+
35
+ /**
36
+ * The `secret` block for one private key. The CMS creates one per instance;
37
+ * the built-in list holds the keyless one, which always fails.
38
+ */
39
+ export function secretBlock(key?: string, onDecrypt?: (value: string) => void): BlockFunction {
40
+ let imported: Promise<CryptoKey> | undefined;
41
+ return async ({ ciphertext }: { ciphertext?: unknown } = {}): Promise<string> => {
42
+ if (inBrowser()) throw new Error("a secret block resolves on the server only");
43
+ if (!key) throw new Error("no key to decrypt secrets: pass createCMS({ secrets: { key } })");
44
+ const parts = parseCiphertext(ciphertext);
45
+ if (!parts) throw new Error("the ciphertext is not well formed");
46
+ imported ??= Promise.resolve().then(() =>
47
+ crypto.subtle.importKey(
48
+ "pkcs8",
49
+ privateKeyDer(key) as BufferSource,
50
+ { name: "RSA-OAEP", hash: "SHA-256" },
51
+ false,
52
+ ["decrypt"],
53
+ ),
54
+ );
55
+ let rsa: CryptoKey;
56
+ try {
57
+ rsa = await imported;
58
+ } catch {
59
+ throw new Error("the secrets key is not an RSA private key in PKCS#8 PEM");
60
+ }
61
+ let value: string;
62
+ try {
63
+ const raw = await crypto.subtle.decrypt(
64
+ { name: "RSA-OAEP" },
65
+ rsa,
66
+ parts.wrappedKey as BufferSource,
67
+ );
68
+ const aes = await crypto.subtle.importKey("raw", raw, "AES-GCM", false, ["decrypt"]);
69
+ const plain = await crypto.subtle.decrypt(
70
+ { name: "AES-GCM", iv: parts.iv as BufferSource },
71
+ aes,
72
+ parts.ciphertext as BufferSource,
73
+ );
74
+ value = new TextDecoder().decode(plain);
75
+ } catch {
76
+ // Web Crypto's errors say nothing useful, and this one never names the value.
77
+ throw new Error("the secret could not be decrypted with this key");
78
+ }
79
+ onDecrypt?.(value);
80
+ return value;
81
+ };
82
+ }
@@ -0,0 +1,117 @@
1
+ /**
2
+ * Canonical JSON and hashing shared by the protocol's request digests.
3
+ *
4
+ * Canonical form: object keys recursively sorted in JavaScript code-unit
5
+ * order, array order preserved, compact UTF-8 JSON with no trailing newline,
6
+ * JSON string escaping and number encoding (negative zero becomes zero).
7
+ * Values JSON can't represent (undefined, functions, symbols, bigints,
8
+ * non-finite numbers, cycles) are rejected rather than silently dropped.
9
+ *
10
+ * Uses Web Crypto, so it runs in browsers, on Workers and on Node.
11
+ */
12
+
13
+ export class CanonicalJsonError extends Error {
14
+ constructor(message: string) {
15
+ super(message);
16
+ this.name = "CanonicalJsonError";
17
+ }
18
+ }
19
+
20
+ function write(value: unknown, path: string, seen: Set<object>, out: string[]): void {
21
+ if (value === null) {
22
+ out.push("null");
23
+ return;
24
+ }
25
+ switch (typeof value) {
26
+ case "string":
27
+ out.push(JSON.stringify(value));
28
+ return;
29
+ case "boolean":
30
+ out.push(value ? "true" : "false");
31
+ return;
32
+ case "number":
33
+ if (!Number.isFinite(value)) {
34
+ throw new CanonicalJsonError(`${path}: ${value} can't be represented in JSON`);
35
+ }
36
+ out.push(Object.is(value, -0) ? "0" : JSON.stringify(value));
37
+ return;
38
+ case "object":
39
+ break;
40
+ default:
41
+ throw new CanonicalJsonError(`${path}: a ${typeof value} can't be represented in JSON`);
42
+ }
43
+ const object = value as object;
44
+ if (seen.has(object))
45
+ throw new CanonicalJsonError(`${path}: a cycle can't be represented in JSON`);
46
+ seen.add(object);
47
+ if (Array.isArray(object)) {
48
+ out.push("[");
49
+ object.forEach((item, index) => {
50
+ if (index > 0) out.push(",");
51
+ write(item, `${path}/${index}`, seen, out);
52
+ });
53
+ out.push("]");
54
+ } else {
55
+ const prototype = Object.getPrototypeOf(object);
56
+ if (prototype !== Object.prototype && prototype !== null) {
57
+ throw new CanonicalJsonError(`${path}: only plain objects can be represented in JSON`);
58
+ }
59
+ // Code-unit order, which is what the default sort compares.
60
+ const keys = Object.keys(object).sort();
61
+ out.push("{");
62
+ keys.forEach((key, index) => {
63
+ if (index > 0) out.push(",");
64
+ out.push(JSON.stringify(key), ":");
65
+ write((object as Record<string, unknown>)[key], `${path}/${key}`, seen, out);
66
+ });
67
+ out.push("}");
68
+ }
69
+ seen.delete(object);
70
+ }
71
+
72
+ /** Serializes `value` to canonical JSON. Throws CanonicalJsonError for values JSON can't represent. */
73
+ export function canonicalJson(value: unknown): string {
74
+ const out: string[] = [];
75
+ write(value, "", new Set(), out);
76
+ return out.join("");
77
+ }
78
+
79
+ const hex = (bytes: ArrayBuffer) =>
80
+ Array.from(new Uint8Array(bytes), (b) => b.toString(16).padStart(2, "0")).join("");
81
+
82
+ /** SHA-256 of `data` (strings are UTF-8 encoded), as lowercase hex. */
83
+ export async function sha256Hex(data: string | Uint8Array): Promise<string> {
84
+ const bytes = typeof data === "string" ? new TextEncoder().encode(data) : data;
85
+ return hex(await crypto.subtle.digest("SHA-256", bytes as BufferSource));
86
+ }
87
+
88
+ /**
89
+ * The version of the canonical content-hashing format below. A snapshot
90
+ * envelope records it beside the revision; the revision itself is excluded
91
+ * from its own hash.
92
+ */
93
+ export const CONTENT_HASH_FORMAT = 1;
94
+
95
+ /**
96
+ * The content revision of a `blocks` map: SHA-256 over its canonical JSON,
97
+ * lowercase hex. The one definition the CLI, the release materializer and
98
+ * the site editor's backend share; `contentHashFixtures` (in
99
+ * `@decocms/blocks/protocol/conformance`) pins its output.
100
+ *
101
+ * This identifies content, not storage: a storage's `blocks.list` revision
102
+ * is opaque and may be computed differently (from file versions).
103
+ */
104
+ export async function computeContentRevision(blocks: Record<string, unknown>): Promise<string> {
105
+ return sha256Hex(canonicalJson(blocks));
106
+ }
107
+
108
+ /** The domain prefix of `blocks.apply` request digests, so they never equal another hash. */
109
+ export const APPLY_DIGEST_DOMAIN = "deco-content/blocks.apply@1\n";
110
+
111
+ /**
112
+ * The digest a request key is bound to: SHA-256 over the domain prefix and
113
+ * the canonical JSON of every supplied parameter.
114
+ */
115
+ export function applyRequestDigest(params: object): Promise<string> {
116
+ return sha256Hex(APPLY_DIGEST_DOMAIN + canonicalJson(params));
117
+ }
@@ -0,0 +1,158 @@
1
+ /**
2
+ * The `secret` block's ciphertext format, in one place: the secret guard
3
+ * checks it, and `encryptSecret` (`@decocms/blocks/secrets`) produces it.
4
+ *
5
+ * ```
6
+ * v1.<wrappedKey>.<iv>.<ciphertext>
7
+ * ```
8
+ *
9
+ * Each segment is unpadded base64url. A fresh AES-256-GCM key encrypts the
10
+ * UTF-8 value; the key is wrapped with the site's RSA public key using
11
+ * RSA-OAEP with SHA-256.
12
+ *
13
+ * - `wrappedKey` — the RSA-OAEP output: as long as the modulus, so 256, 384
14
+ * or 512 bytes (2048-, 3072- or 4096-bit keys; `deco` creates 3072-bit ones).
15
+ * - `iv` — the AES-GCM nonce: exactly 12 bytes.
16
+ * - `ciphertext` — the AES-GCM output, its 16-byte tag included: at least 16 bytes.
17
+ *
18
+ * Checking the structure needs no key, so the content protocol and
19
+ * `deco check` refuse text that merely looks like a ciphertext (`v1.hunter2`).
20
+ * Web Crypto only: runs in browsers, on Workers and on Node.
21
+ */
22
+
23
+ /** The format version every ciphertext starts with. */
24
+ export const CIPHERTEXT_VERSION = "v1";
25
+
26
+ /** The wrapped-key lengths a ciphertext may carry: 2048-, 3072- and 4096-bit RSA. */
27
+ export const WRAPPED_KEY_BYTES: readonly number[] = [256, 384, 512];
28
+
29
+ /** The AES-GCM nonce length. */
30
+ export const IV_BYTES = 12;
31
+
32
+ /** The AES-GCM authentication tag length, the smallest ciphertext segment. */
33
+ export const GCM_TAG_BYTES = 16;
34
+
35
+ /**
36
+ * The shape of a ciphertext: `v1.` and three base64url segments. A match is
37
+ * necessary but not sufficient; `parseCiphertext` also checks segment lengths.
38
+ */
39
+ export const CIPHERTEXT_PATTERN = /^v1\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/;
40
+
41
+ /** The decoded segments of a ciphertext. */
42
+ export interface CiphertextParts {
43
+ wrappedKey: Uint8Array;
44
+ iv: Uint8Array;
45
+ ciphertext: Uint8Array;
46
+ }
47
+
48
+ const BASE64URL = /^[A-Za-z0-9_-]*$/;
49
+
50
+ /** Unpadded base64url. */
51
+ export function encodeBase64Url(bytes: Uint8Array): string {
52
+ let binary = "";
53
+ for (let i = 0; i < bytes.length; i += 0x8000) {
54
+ binary += String.fromCharCode(...bytes.subarray(i, i + 0x8000));
55
+ }
56
+ return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
57
+ }
58
+
59
+ /** Decodes unpadded base64url; `null` when `text` isn't canonical base64url. */
60
+ export function decodeBase64Url(text: string): Uint8Array | null {
61
+ if (!BASE64URL.test(text) || text.length % 4 === 1) return null;
62
+ const padded =
63
+ text.replace(/-/g, "+").replace(/_/g, "/") + "=".repeat((4 - (text.length % 4)) % 4);
64
+ let binary: string;
65
+ try {
66
+ binary = atob(padded);
67
+ } catch {
68
+ return null;
69
+ }
70
+ const bytes = Uint8Array.from(binary, (c) => c.charCodeAt(0));
71
+ // Reject non-canonical encodings (stray low bits), so one value has one spelling.
72
+ return encodeBase64Url(bytes) === text ? bytes : null;
73
+ }
74
+
75
+ const validParts = ({ wrappedKey, iv, ciphertext }: CiphertextParts) =>
76
+ WRAPPED_KEY_BYTES.includes(wrappedKey.byteLength) &&
77
+ iv.byteLength === IV_BYTES &&
78
+ ciphertext.byteLength >= GCM_TAG_BYTES;
79
+
80
+ /** Splits and decodes a ciphertext; `null` when it isn't well formed. */
81
+ export function parseCiphertext(text: unknown): CiphertextParts | null {
82
+ if (typeof text !== "string" || !CIPHERTEXT_PATTERN.test(text)) return null;
83
+ const [, rawKey, rawIv, rawCiphertext] = text.split(".");
84
+ const wrappedKey = decodeBase64Url(rawKey!);
85
+ const iv = decodeBase64Url(rawIv!);
86
+ const ciphertext = decodeBase64Url(rawCiphertext!);
87
+ if (!wrappedKey || !iv || !ciphertext) return null;
88
+ const parts = { wrappedKey, iv, ciphertext };
89
+ return validParts(parts) ? parts : null;
90
+ }
91
+
92
+ /** Joins decoded segments into a ciphertext. Throws when a segment has the wrong length. */
93
+ export function formatCiphertext(parts: CiphertextParts): string {
94
+ if (!validParts(parts)) {
95
+ throw new RangeError(
96
+ `a ciphertext needs a ${WRAPPED_KEY_BYTES.join("/")}-byte wrapped key, a ${IV_BYTES}-byte iv and at least ${GCM_TAG_BYTES} bytes of ciphertext`,
97
+ );
98
+ }
99
+ return [
100
+ CIPHERTEXT_VERSION,
101
+ encodeBase64Url(parts.wrappedKey),
102
+ encodeBase64Url(parts.iv),
103
+ encodeBase64Url(parts.ciphertext),
104
+ ].join(".");
105
+ }
106
+
107
+ const PEM_BLOCK = /-----BEGIN ([A-Z ]+)-----([\s\S]*?)-----END \1-----/g;
108
+
109
+ /** The DER bytes of a single `PUBLIC KEY` PEM block; `null` for anything else. */
110
+ export function publicKeyDerFromPem(pem: string): Uint8Array | null {
111
+ const blocks = [...pem.matchAll(PEM_BLOCK)];
112
+ const block = blocks[0];
113
+ if (blocks.length !== 1 || !block || block[1] !== "PUBLIC KEY") return null;
114
+ if (pem.replace(block[0], "").trim() !== "") return null;
115
+ const body = (block[2] ?? "").replace(/\s+/g, "");
116
+ if (!/^[A-Za-z0-9+/]+={0,2}$/.test(body)) return null;
117
+ try {
118
+ return Uint8Array.from(atob(body), (c) => c.charCodeAt(0));
119
+ } catch {
120
+ return null;
121
+ }
122
+ }
123
+
124
+ /** A `PUBLIC KEY` PEM block for SPKI `der` bytes, with 64-character lines. */
125
+ export function publicKeyPemFromDer(der: Uint8Array): string {
126
+ let binary = "";
127
+ for (const byte of der) binary += String.fromCharCode(byte);
128
+ const lines =
129
+ btoa(binary)
130
+ .match(/.{1,64}/g)
131
+ ?.join("\n") ?? "";
132
+ return `-----BEGIN PUBLIC KEY-----\n${lines}\n-----END PUBLIC KEY-----\n`;
133
+ }
134
+
135
+ /**
136
+ * Encrypts `value` for the holder of the private key matching `publicKeyPem`
137
+ * (an SPKI `PUBLIC KEY` PEM, such as `.deco/secrets.pub`).
138
+ */
139
+ export async function encryptToCiphertext(publicKeyPem: string, value: string): Promise<string> {
140
+ const der = publicKeyDerFromPem(publicKeyPem);
141
+ if (!der) throw new TypeError("the public key must be a single PUBLIC KEY PEM block");
142
+ const rsa = await crypto.subtle.importKey(
143
+ "spki",
144
+ der as BufferSource,
145
+ { name: "RSA-OAEP", hash: "SHA-256" },
146
+ false,
147
+ ["encrypt"],
148
+ );
149
+ const aesKey = crypto.getRandomValues(new Uint8Array(32));
150
+ const aes = await crypto.subtle.importKey("raw", aesKey, "AES-GCM", false, ["encrypt"]);
151
+ const iv = crypto.getRandomValues(new Uint8Array(IV_BYTES));
152
+ const ciphertext = new Uint8Array(
153
+ await crypto.subtle.encrypt({ name: "AES-GCM", iv }, aes, new TextEncoder().encode(value)),
154
+ );
155
+ const wrappedKey = new Uint8Array(await crypto.subtle.encrypt({ name: "RSA-OAEP" }, rsa, aesKey));
156
+ aesKey.fill(0);
157
+ return formatCiphertext({ wrappedKey, iv, ciphertext });
158
+ }