@decocms/blocks 8.0.0 → 8.1.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 (175) hide show
  1. package/bin/deco.js +13 -0
  2. package/package.json +39 -3
  3. package/src/cms/applySectionConventions.ts +26 -2
  4. package/src/cms/blockSource.ts +37 -0
  5. package/src/cms/client.ts +5 -0
  6. package/src/cms/deferredTrigger.ts +58 -0
  7. package/src/cms/draftSource.ts +171 -57
  8. package/src/cms/index.ts +32 -3
  9. package/src/cms/loader.ts +318 -59
  10. package/src/cms/registry.ts +22 -0
  11. package/src/cms/renderJson.ts +179 -0
  12. package/src/cms/resolve.ts +396 -95
  13. package/src/cms/schema.ts +9 -5
  14. package/src/cms/sectionLoaders.ts +106 -56
  15. package/src/hooks/Image.tsx +70 -6
  16. package/src/hooks/LiveControls.tsx +30 -8
  17. package/src/hooks/Stats.tsx +134 -0
  18. package/src/hooks/index.ts +5 -0
  19. package/src/hooks/useLoadMore.ts +100 -0
  20. package/src/index.ts +37 -0
  21. package/src/middleware/observability.ts +173 -16
  22. package/src/preview/DraftPreviewBadge.tsx +306 -0
  23. package/src/preview/decoMark.ts +11 -0
  24. package/src/preview/index.ts +8 -0
  25. package/src/protocol/assets.ts +124 -0
  26. package/src/protocol/canonical.ts +7 -0
  27. package/src/protocol/ciphertext.ts +6 -0
  28. package/src/protocol/client.ts +170 -0
  29. package/src/protocol/conformance/cases/assets.ts +81 -0
  30. package/src/protocol/conformance/cases/guards.ts +314 -0
  31. package/src/protocol/conformance/cases/reads.ts +168 -0
  32. package/src/protocol/conformance/cases/types.ts +9 -0
  33. package/src/protocol/conformance/cases/wire.ts +138 -0
  34. package/src/protocol/conformance/cases/writes.ts +345 -0
  35. package/src/protocol/conformance/contentHashFixtures.ts +79 -0
  36. package/src/protocol/conformance/context.ts +222 -0
  37. package/src/protocol/conformance/index.ts +140 -0
  38. package/src/protocol/errors.ts +142 -0
  39. package/src/protocol/index.ts +39 -0
  40. package/src/protocol/keys.ts +279 -0
  41. package/src/protocol/params.ts +67 -0
  42. package/src/protocol/secrets.ts +231 -0
  43. package/src/protocol/server/assets.ts +119 -0
  44. package/src/protocol/server/auth.ts +49 -0
  45. package/src/protocol/server/bodyCache.ts +84 -0
  46. package/src/protocol/server/content.ts +175 -0
  47. package/src/protocol/server/core.ts +112 -0
  48. package/src/protocol/server/handler.ts +102 -0
  49. package/src/protocol/server/http.ts +139 -0
  50. package/src/protocol/server/index.ts +11 -0
  51. package/src/protocol/server/methods/apply.ts +341 -0
  52. package/src/protocol/server/methods/read.ts +156 -0
  53. package/src/protocol/server/rpc.ts +136 -0
  54. package/src/protocol/storage/fs/hash.ts +21 -0
  55. package/src/protocol/storage/fs/index.ts +338 -0
  56. package/src/protocol/storage/fs/lock.ts +68 -0
  57. package/src/protocol/storage/fs/transaction.ts +183 -0
  58. package/src/protocol/storage/fs/unsupported.ts +15 -0
  59. package/src/protocol/storage/memory.ts +238 -0
  60. package/src/protocol/storage.ts +182 -0
  61. package/src/protocol/types.ts +172 -0
  62. package/src/sdk/abTesting.ts +60 -3
  63. package/src/sdk/analytics.ts +72 -2
  64. package/src/sdk/cacheHeaders.ts +210 -10
  65. package/src/sdk/cacheStorage.ts +287 -0
  66. package/src/sdk/cachedLoader.ts +143 -90
  67. package/src/sdk/crypto.ts +16 -2
  68. package/src/sdk/deepOmit.ts +52 -0
  69. package/src/sdk/encoding.ts +2 -5
  70. package/src/sdk/experiments.ts +314 -0
  71. package/src/sdk/fetchCache.ts +269 -0
  72. package/src/sdk/fetchTimeout.ts +58 -0
  73. package/src/sdk/flags.ts +38 -8
  74. package/src/sdk/index.ts +7 -0
  75. package/src/sdk/instrumentedFetch.ts +25 -2
  76. package/src/sdk/nonce.ts +46 -0
  77. package/src/sdk/normalizeUrls.ts +2 -2
  78. package/src/sdk/observability.ts +8 -1
  79. package/src/sdk/otel.ts +131 -25
  80. package/src/sdk/otelHttpLog.ts +4 -4
  81. package/src/sdk/otelHttpMeter.ts +39 -13
  82. package/src/sdk/otelHttpTracer.ts +4 -4
  83. package/src/sdk/redirects.ts +113 -5
  84. package/src/sdk/responseCache.ts +82 -0
  85. package/src/sdk/urlUtils.ts +49 -0
  86. package/src/sdk/useSuggestions.ts +1 -1
  87. package/src/v8/analytics.ts +50 -0
  88. package/src/v8/background.ts +107 -0
  89. package/src/v8/builtins/data.ts +23 -0
  90. package/src/v8/builtins/index.ts +26 -0
  91. package/src/v8/builtins/lazy.ts +23 -0
  92. package/src/v8/builtins/legacy.ts +65 -0
  93. package/src/v8/builtins/matchers.ts +31 -0
  94. package/src/v8/builtins/multivariate.ts +25 -0
  95. package/src/v8/builtins/secret.ts +82 -0
  96. package/src/v8/canonical.ts +117 -0
  97. package/src/v8/ciphertext.ts +158 -0
  98. package/src/v8/cli/builtins.ts +20 -0
  99. package/src/v8/cli/check/index.ts +774 -0
  100. package/src/v8/cli/check/messages.ts +168 -0
  101. package/src/v8/cli/content.ts +287 -0
  102. package/src/v8/cli/index.ts +17 -0
  103. package/src/v8/cli/log.ts +18 -0
  104. package/src/v8/cli/main.ts +12 -0
  105. package/src/v8/cli/root.ts +66 -0
  106. package/src/v8/cli/run.ts +236 -0
  107. package/src/v8/cli/schema/builtinSchemas.ts +236 -0
  108. package/src/v8/cli/schema/generate.ts +507 -0
  109. package/src/v8/cli/schema/index.ts +63 -0
  110. package/src/v8/cli/schema/tsProgram.ts +497 -0
  111. package/src/v8/cli/schema/typeToSchema.ts +689 -0
  112. package/src/v8/cli/serve/server.ts +303 -0
  113. package/src/v8/cli/watch.ts +86 -0
  114. package/src/v8/client.ts +147 -0
  115. package/src/v8/cms.ts +237 -0
  116. package/src/v8/content.ts +195 -0
  117. package/src/v8/draft.ts +136 -0
  118. package/src/v8/errors.ts +59 -0
  119. package/src/v8/fetch.ts +152 -0
  120. package/src/v8/identity.ts +65 -0
  121. package/src/v8/index.ts +39 -0
  122. package/src/v8/json.ts +74 -0
  123. package/src/v8/matchRoute.ts +204 -0
  124. package/src/v8/remoteLoader.ts +282 -0
  125. package/src/v8/resolver.ts +278 -0
  126. package/src/v8/secrets.ts +17 -0
  127. package/src/v8/telemetry.ts +533 -0
  128. package/src/v8/types.ts +240 -0
  129. package/src/cms/blockSource.test.ts +0 -76
  130. package/src/cms/client.browserBundle.test.ts +0 -44
  131. package/src/cms/draftSource.test.ts +0 -343
  132. package/src/cms/layoutCacheRace.test.ts +0 -181
  133. package/src/cms/loadDecofileDirectory.test.ts +0 -109
  134. package/src/cms/loader.test.ts +0 -200
  135. package/src/cms/registry.test.ts +0 -110
  136. package/src/cms/resolve.test.ts +0 -980
  137. package/src/cms/schema.test.ts +0 -356
  138. package/src/cms/sectionLoaderContext.test.ts +0 -111
  139. package/src/cms/sectionLoaders.test.ts +0 -533
  140. package/src/cms/sectionMixins.test.ts +0 -167
  141. package/src/cms/stickyFlags.test.ts +0 -117
  142. package/src/flags/flags.test.ts +0 -148
  143. package/src/hooks/Image.test.ts +0 -100
  144. package/src/hooks/RenderSection.test.tsx +0 -81
  145. package/src/matchers/builtins.test.ts +0 -318
  146. package/src/matchers/override.test.ts +0 -205
  147. package/src/middleware/hydrationContext.test.ts +0 -61
  148. package/src/middleware/observability.test.ts +0 -242
  149. package/src/middleware/validateSection.test.ts +0 -147
  150. package/src/sdk/abTesting.test.ts +0 -326
  151. package/src/sdk/cacheHeaders.test.ts +0 -115
  152. package/src/sdk/cachedLoader.test.ts +0 -122
  153. package/src/sdk/cachedLoaderModule.test.ts +0 -209
  154. package/src/sdk/cn.test.ts +0 -34
  155. package/src/sdk/composite.test.ts +0 -121
  156. package/src/sdk/cookie.test.ts +0 -108
  157. package/src/sdk/encoding.test.ts +0 -71
  158. package/src/sdk/env.test.ts +0 -33
  159. package/src/sdk/flags.test.ts +0 -91
  160. package/src/sdk/http.test.ts +0 -71
  161. package/src/sdk/inflightTimeout.test.ts +0 -35
  162. package/src/sdk/instrumentedFetch.test.ts +0 -559
  163. package/src/sdk/invoke.test.ts +0 -115
  164. package/src/sdk/logger.test.ts +0 -432
  165. package/src/sdk/otel.test.ts +0 -526
  166. package/src/sdk/otelAdapters.test.ts +0 -89
  167. package/src/sdk/otelHttpLog.test.ts +0 -457
  168. package/src/sdk/otelHttpMeter.test.ts +0 -292
  169. package/src/sdk/otelHttpTracer.test.ts +0 -474
  170. package/src/sdk/requestContextStorage.browser.test.ts +0 -29
  171. package/src/sdk/urlRedaction.test.ts +0 -73
  172. package/src/sdk/useDevice.test.ts +0 -130
  173. package/src/sdk/useScript.test.ts +0 -128
  174. package/src/sdk/useSuggestions.test.ts +0 -230
  175. package/tsconfig.json +0 -7
@@ -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
+ }
@@ -0,0 +1,20 @@
1
+ /**
2
+ * Names the CLI knows without reading any code: the built-in blocks (the
3
+ * core's reserved names) and the legacy alias table.
4
+ */
5
+ import { RESERVED_NAMES } from "../builtins";
6
+
7
+ /** Spec: built-in-blocks. Every block map gets these, in this order. */
8
+ export const BUILT_IN_BLOCKS: readonly string[] = [...RESERVED_NAMES];
9
+
10
+ export function isBuiltIn(name: string): boolean {
11
+ return RESERVED_NAMES.has(name);
12
+ }
13
+
14
+ /**
15
+ * The legacy alias table lives with the runtime's alias bridge, so the
16
+ * schema, the content module and resolution share one list. The site
17
+ * editor's special screens still look types up by these names (spec:
18
+ * studio-compatibility › Well-known types and the alias table).
19
+ */
20
+ export { LEGACY_ALIASES, storesPlainVariants } from "../builtins/legacy";