@decocms/blocks 8.7.0 → 8.9.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 (164) hide show
  1. package/dist/index.d.ts +1 -1
  2. package/dist/index.d.ts.map +1 -1
  3. package/dist/index.js +1 -1
  4. package/dist/index.js.map +1 -1
  5. package/dist/protocol/conformance/cases/changes.d.ts.map +1 -1
  6. package/dist/protocol/conformance/cases/changes.js +14 -3
  7. package/dist/protocol/conformance/cases/changes.js.map +1 -1
  8. package/dist/protocol/conformance/cases/guards.d.ts.map +1 -1
  9. package/dist/protocol/conformance/cases/guards.js +19 -42
  10. package/dist/protocol/conformance/cases/guards.js.map +1 -1
  11. package/dist/protocol/conformance/cases/overlay.d.ts +3 -0
  12. package/dist/protocol/conformance/cases/overlay.d.ts.map +1 -0
  13. package/dist/protocol/conformance/cases/overlay.js +164 -0
  14. package/dist/protocol/conformance/cases/overlay.js.map +1 -0
  15. package/dist/protocol/conformance/cases/reads.js +5 -5
  16. package/dist/protocol/conformance/cases/reads.js.map +1 -1
  17. package/dist/protocol/conformance/cases/writes.d.ts.map +1 -1
  18. package/dist/protocol/conformance/cases/writes.js +15 -3
  19. package/dist/protocol/conformance/cases/writes.js.map +1 -1
  20. package/dist/protocol/conformance/context.d.ts +0 -10
  21. package/dist/protocol/conformance/context.d.ts.map +1 -1
  22. package/dist/protocol/conformance/context.js.map +1 -1
  23. package/dist/protocol/conformance/index.d.ts.map +1 -1
  24. package/dist/protocol/conformance/index.js +2 -0
  25. package/dist/protocol/conformance/index.js.map +1 -1
  26. package/dist/protocol/server/content.d.ts +8 -1
  27. package/dist/protocol/server/content.d.ts.map +1 -1
  28. package/dist/protocol/server/content.js +18 -3
  29. package/dist/protocol/server/content.js.map +1 -1
  30. package/dist/protocol/server/core.d.ts +0 -6
  31. package/dist/protocol/server/core.d.ts.map +1 -1
  32. package/dist/protocol/server/core.js +0 -2
  33. package/dist/protocol/server/core.js.map +1 -1
  34. package/dist/protocol/server/methods/apply.d.ts +16 -5
  35. package/dist/protocol/server/methods/apply.d.ts.map +1 -1
  36. package/dist/protocol/server/methods/apply.js +42 -38
  37. package/dist/protocol/server/methods/apply.js.map +1 -1
  38. package/dist/protocol/server/methods/changes.d.ts.map +1 -1
  39. package/dist/protocol/server/methods/changes.js +31 -3
  40. package/dist/protocol/server/methods/changes.js.map +1 -1
  41. package/dist/protocol/server/methods/read.d.ts.map +1 -1
  42. package/dist/protocol/server/methods/read.js +2 -23
  43. package/dist/protocol/server/methods/read.js.map +1 -1
  44. package/dist/protocol/storage/fs/index.d.ts.map +1 -1
  45. package/dist/protocol/storage/fs/index.js +0 -18
  46. package/dist/protocol/storage/fs/index.js.map +1 -1
  47. package/dist/protocol/storage/memory.d.ts +11 -3
  48. package/dist/protocol/storage/memory.d.ts.map +1 -1
  49. package/dist/protocol/storage/memory.js +114 -45
  50. package/dist/protocol/storage/memory.js.map +1 -1
  51. package/dist/protocol/storage.d.ts +68 -18
  52. package/dist/protocol/storage.d.ts.map +1 -1
  53. package/dist/protocol/storage.js +7 -0
  54. package/dist/protocol/storage.js.map +1 -1
  55. package/dist/protocol/types.d.ts +51 -8
  56. package/dist/protocol/types.d.ts.map +1 -1
  57. package/dist/protocol/types.js +5 -3
  58. package/dist/protocol/types.js.map +1 -1
  59. package/dist/v8/analytics.d.ts +6 -2
  60. package/dist/v8/analytics.d.ts.map +1 -1
  61. package/dist/v8/analytics.js +24 -5
  62. package/dist/v8/analytics.js.map +1 -1
  63. package/dist/v8/builtins/data.d.ts +4 -0
  64. package/dist/v8/builtins/data.d.ts.map +1 -1
  65. package/dist/v8/builtins/data.js +6 -0
  66. package/dist/v8/builtins/data.js.map +1 -1
  67. package/dist/v8/builtins/index.d.ts +1 -4
  68. package/dist/v8/builtins/index.d.ts.map +1 -1
  69. package/dist/v8/builtins/index.js +1 -6
  70. package/dist/v8/builtins/index.js.map +1 -1
  71. package/dist/v8/builtins/legacy.d.ts +4 -4
  72. package/dist/v8/builtins/legacy.d.ts.map +1 -1
  73. package/dist/v8/builtins/legacy.js +4 -5
  74. package/dist/v8/builtins/legacy.js.map +1 -1
  75. package/dist/v8/cli/builtins.d.ts.map +1 -1
  76. package/dist/v8/cli/builtins.js +0 -1
  77. package/dist/v8/cli/builtins.js.map +1 -1
  78. package/dist/v8/cli/check/index.d.ts +1 -1
  79. package/dist/v8/cli/check/index.d.ts.map +1 -1
  80. package/dist/v8/cli/check/index.js +13 -33
  81. package/dist/v8/cli/check/index.js.map +1 -1
  82. package/dist/v8/cli/schema/builtinSchemas.d.ts.map +1 -1
  83. package/dist/v8/cli/schema/builtinSchemas.js +6 -8
  84. package/dist/v8/cli/schema/builtinSchemas.js.map +1 -1
  85. package/dist/v8/cli/schema/generate.d.ts.map +1 -1
  86. package/dist/v8/cli/schema/generate.js +1 -8
  87. package/dist/v8/cli/schema/generate.js.map +1 -1
  88. package/dist/v8/cli/schema/typeToSchema.d.ts +0 -1
  89. package/dist/v8/cli/schema/typeToSchema.d.ts.map +1 -1
  90. package/dist/v8/cli/schema/typeToSchema.js +5 -30
  91. package/dist/v8/cli/schema/typeToSchema.js.map +1 -1
  92. package/dist/v8/client.d.ts +1 -1
  93. package/dist/v8/client.d.ts.map +1 -1
  94. package/dist/v8/cms.d.ts.map +1 -1
  95. package/dist/v8/cms.js +5 -13
  96. package/dist/v8/cms.js.map +1 -1
  97. package/dist/v8/index.d.ts +1 -1
  98. package/dist/v8/index.d.ts.map +1 -1
  99. package/dist/v8/resolver.d.ts +1 -1
  100. package/dist/v8/resolver.d.ts.map +1 -1
  101. package/dist/v8/telemetry.d.ts +0 -2
  102. package/dist/v8/telemetry.d.ts.map +1 -1
  103. package/dist/v8/telemetry.js +5 -20
  104. package/dist/v8/telemetry.js.map +1 -1
  105. package/dist/v8/types.d.ts +4 -8
  106. package/dist/v8/types.d.ts.map +1 -1
  107. package/package.json +1 -6
  108. package/src/index.ts +1 -2
  109. package/src/protocol/conformance/cases/changes.ts +16 -4
  110. package/src/protocol/conformance/cases/guards.ts +19 -55
  111. package/src/protocol/conformance/cases/overlay.ts +195 -0
  112. package/src/protocol/conformance/cases/reads.ts +4 -4
  113. package/src/protocol/conformance/cases/writes.ts +15 -3
  114. package/src/protocol/conformance/context.ts +0 -7
  115. package/src/protocol/conformance/index.ts +2 -0
  116. package/src/protocol/server/content.ts +30 -4
  117. package/src/protocol/server/core.ts +0 -3
  118. package/src/protocol/server/methods/apply.ts +43 -38
  119. package/src/protocol/server/methods/changes.ts +42 -4
  120. package/src/protocol/server/methods/read.ts +2 -24
  121. package/src/protocol/storage/fs/index.ts +0 -18
  122. package/src/protocol/storage/memory.ts +124 -46
  123. package/src/protocol/storage.ts +69 -18
  124. package/src/protocol/types.ts +51 -8
  125. package/src/v8/analytics.ts +26 -5
  126. package/src/v8/builtins/data.ts +8 -0
  127. package/src/v8/builtins/index.ts +1 -6
  128. package/src/v8/builtins/legacy.ts +4 -5
  129. package/src/v8/cli/builtins.ts +0 -1
  130. package/src/v8/cli/check/index.ts +15 -34
  131. package/src/v8/cli/schema/builtinSchemas.ts +6 -8
  132. package/src/v8/cli/schema/generate.ts +1 -8
  133. package/src/v8/cli/schema/typeToSchema.ts +5 -31
  134. package/src/v8/client.ts +1 -1
  135. package/src/v8/cms.ts +5 -14
  136. package/src/v8/index.ts +0 -1
  137. package/src/v8/resolver.ts +1 -1
  138. package/src/v8/telemetry.ts +5 -20
  139. package/src/v8/types.ts +4 -5
  140. package/dist/protocol/ciphertext.d.ts +0 -7
  141. package/dist/protocol/ciphertext.d.ts.map +0 -1
  142. package/dist/protocol/ciphertext.js +0 -7
  143. package/dist/protocol/ciphertext.js.map +0 -1
  144. package/dist/protocol/secrets.d.ts +0 -22
  145. package/dist/protocol/secrets.d.ts.map +0 -1
  146. package/dist/protocol/secrets.js +0 -207
  147. package/dist/protocol/secrets.js.map +0 -1
  148. package/dist/v8/builtins/secret.d.ts +0 -7
  149. package/dist/v8/builtins/secret.d.ts.map +0 -1
  150. package/dist/v8/builtins/secret.js +0 -68
  151. package/dist/v8/builtins/secret.js.map +0 -1
  152. package/dist/v8/ciphertext.d.ts +0 -58
  153. package/dist/v8/ciphertext.d.ts.map +0 -1
  154. package/dist/v8/ciphertext.js +0 -134
  155. package/dist/v8/ciphertext.js.map +0 -1
  156. package/dist/v8/secrets.d.ts +0 -9
  157. package/dist/v8/secrets.d.ts.map +0 -1
  158. package/dist/v8/secrets.js +0 -14
  159. package/dist/v8/secrets.js.map +0 -1
  160. package/src/protocol/ciphertext.ts +0 -6
  161. package/src/protocol/secrets.ts +0 -239
  162. package/src/v8/builtins/secret.ts +0 -82
  163. package/src/v8/ciphertext.ts +0 -158
  164. package/src/v8/secrets.ts +0 -17
@@ -1,134 +0,0 @@
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
- /** The format version every ciphertext starts with. */
23
- export const CIPHERTEXT_VERSION = "v1";
24
- /** The wrapped-key lengths a ciphertext may carry: 2048-, 3072- and 4096-bit RSA. */
25
- export const WRAPPED_KEY_BYTES = [256, 384, 512];
26
- /** The AES-GCM nonce length. */
27
- export const IV_BYTES = 12;
28
- /** The AES-GCM authentication tag length, the smallest ciphertext segment. */
29
- export const GCM_TAG_BYTES = 16;
30
- /**
31
- * The shape of a ciphertext: `v1.` and three base64url segments. A match is
32
- * necessary but not sufficient; `parseCiphertext` also checks segment lengths.
33
- */
34
- export const CIPHERTEXT_PATTERN = /^v1\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/;
35
- const BASE64URL = /^[A-Za-z0-9_-]*$/;
36
- /** Unpadded base64url. */
37
- export function encodeBase64Url(bytes) {
38
- let binary = "";
39
- for (let i = 0; i < bytes.length; i += 0x8000) {
40
- binary += String.fromCharCode(...bytes.subarray(i, i + 0x8000));
41
- }
42
- return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
43
- }
44
- /** Decodes unpadded base64url; `null` when `text` isn't canonical base64url. */
45
- export function decodeBase64Url(text) {
46
- if (!BASE64URL.test(text) || text.length % 4 === 1)
47
- return null;
48
- const padded = text.replace(/-/g, "+").replace(/_/g, "/") + "=".repeat((4 - (text.length % 4)) % 4);
49
- let binary;
50
- try {
51
- binary = atob(padded);
52
- }
53
- catch {
54
- return null;
55
- }
56
- const bytes = Uint8Array.from(binary, (c) => c.charCodeAt(0));
57
- // Reject non-canonical encodings (stray low bits), so one value has one spelling.
58
- return encodeBase64Url(bytes) === text ? bytes : null;
59
- }
60
- const validParts = ({ wrappedKey, iv, ciphertext }) => WRAPPED_KEY_BYTES.includes(wrappedKey.byteLength) &&
61
- iv.byteLength === IV_BYTES &&
62
- ciphertext.byteLength >= GCM_TAG_BYTES;
63
- /** Splits and decodes a ciphertext; `null` when it isn't well formed. */
64
- export function parseCiphertext(text) {
65
- if (typeof text !== "string" || !CIPHERTEXT_PATTERN.test(text))
66
- return null;
67
- const [, rawKey, rawIv, rawCiphertext] = text.split(".");
68
- const wrappedKey = decodeBase64Url(rawKey);
69
- const iv = decodeBase64Url(rawIv);
70
- const ciphertext = decodeBase64Url(rawCiphertext);
71
- if (!wrappedKey || !iv || !ciphertext)
72
- return null;
73
- const parts = { wrappedKey, iv, ciphertext };
74
- return validParts(parts) ? parts : null;
75
- }
76
- /** Joins decoded segments into a ciphertext. Throws when a segment has the wrong length. */
77
- export function formatCiphertext(parts) {
78
- if (!validParts(parts)) {
79
- throw new RangeError(`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`);
80
- }
81
- return [
82
- CIPHERTEXT_VERSION,
83
- encodeBase64Url(parts.wrappedKey),
84
- encodeBase64Url(parts.iv),
85
- encodeBase64Url(parts.ciphertext),
86
- ].join(".");
87
- }
88
- const PEM_BLOCK = /-----BEGIN ([A-Z ]+)-----([\s\S]*?)-----END \1-----/g;
89
- /** The DER bytes of a single `PUBLIC KEY` PEM block; `null` for anything else. */
90
- export function publicKeyDerFromPem(pem) {
91
- const blocks = [...pem.matchAll(PEM_BLOCK)];
92
- const block = blocks[0];
93
- if (blocks.length !== 1 || !block || block[1] !== "PUBLIC KEY")
94
- return null;
95
- if (pem.replace(block[0], "").trim() !== "")
96
- return null;
97
- const body = (block[2] ?? "").replace(/\s+/g, "");
98
- if (!/^[A-Za-z0-9+/]+={0,2}$/.test(body))
99
- return null;
100
- try {
101
- return Uint8Array.from(atob(body), (c) => c.charCodeAt(0));
102
- }
103
- catch {
104
- return null;
105
- }
106
- }
107
- /** A `PUBLIC KEY` PEM block for SPKI `der` bytes, with 64-character lines. */
108
- export function publicKeyPemFromDer(der) {
109
- let binary = "";
110
- for (const byte of der)
111
- binary += String.fromCharCode(byte);
112
- const lines = btoa(binary)
113
- .match(/.{1,64}/g)
114
- ?.join("\n") ?? "";
115
- return `-----BEGIN PUBLIC KEY-----\n${lines}\n-----END PUBLIC KEY-----\n`;
116
- }
117
- /**
118
- * Encrypts `value` for the holder of the private key matching `publicKeyPem`
119
- * (an SPKI `PUBLIC KEY` PEM, such as `.deco/secrets.pub`).
120
- */
121
- export async function encryptToCiphertext(publicKeyPem, value) {
122
- const der = publicKeyDerFromPem(publicKeyPem);
123
- if (!der)
124
- throw new TypeError("the public key must be a single PUBLIC KEY PEM block");
125
- const rsa = await crypto.subtle.importKey("spki", der, { name: "RSA-OAEP", hash: "SHA-256" }, false, ["encrypt"]);
126
- const aesKey = crypto.getRandomValues(new Uint8Array(32));
127
- const aes = await crypto.subtle.importKey("raw", aesKey, "AES-GCM", false, ["encrypt"]);
128
- const iv = crypto.getRandomValues(new Uint8Array(IV_BYTES));
129
- const ciphertext = new Uint8Array(await crypto.subtle.encrypt({ name: "AES-GCM", iv }, aes, new TextEncoder().encode(value)));
130
- const wrappedKey = new Uint8Array(await crypto.subtle.encrypt({ name: "RSA-OAEP" }, rsa, aesKey));
131
- aesKey.fill(0);
132
- return formatCiphertext({ wrappedKey, iv, ciphertext });
133
- }
134
- //# sourceMappingURL=ciphertext.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"ciphertext.js","sourceRoot":"","sources":["../../src/v8/ciphertext.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;AAEH,uDAAuD;AACvD,MAAM,CAAC,MAAM,kBAAkB,GAAG,IAAI,CAAC;AAEvC,qFAAqF;AACrF,MAAM,CAAC,MAAM,iBAAiB,GAAsB,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,CAAC,CAAC;AAEpE,gCAAgC;AAChC,MAAM,CAAC,MAAM,QAAQ,GAAG,EAAE,CAAC;AAE3B,8EAA8E;AAC9E,MAAM,CAAC,MAAM,aAAa,GAAG,EAAE,CAAC;AAEhC;;;GAGG;AACH,MAAM,CAAC,MAAM,kBAAkB,GAAG,sDAAsD,CAAC;AASzF,MAAM,SAAS,GAAG,kBAAkB,CAAC;AAErC,0BAA0B;AAC1B,MAAM,UAAU,eAAe,CAAC,KAAiB;IAC/C,IAAI,MAAM,GAAG,EAAE,CAAC;IAChB,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC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,EAAE,EAAE,GAAG,EAAE,MAAM,CAAC,CAAC,CAAC;IAClG,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IACf,OAAO,gBAAgB,CAAC,EAAE,UAAU,EAAE,EAAE,EAAE,UAAU,EAAE,CAAC,CAAC;AAC1D,CAAC"}
@@ -1,9 +0,0 @@
1
- /**
2
- * Encrypts `value` with your public key (the contents of `.deco/secrets.pub`)
3
- * and returns a ready `secret` block.
4
- */
5
- export declare function encryptSecret(publicKey: string, value: string): Promise<{
6
- __resolveType: "secret";
7
- ciphertext: string;
8
- }>;
9
- //# sourceMappingURL=secrets.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"secrets.d.ts","sourceRoot":"","sources":["../../src/v8/secrets.ts"],"names":[],"mappings":"AAOA;;;GAGG;AACH,wBAAsB,aAAa,CACjC,SAAS,EAAE,MAAM,EACjB,KAAK,EAAE,MAAM,GACZ,OAAO,CAAC;IAAE,aAAa,EAAE,QAAQ,CAAC;IAAC,UAAU,EAAE,MAAM,CAAA;CAAE,CAAC,CAE1D"}
@@ -1,14 +0,0 @@
1
- /**
2
- * `@decocms/blocks/secrets`: encrypts a value for a `secret` block, for a
3
- * script or an AI agent that writes content (see /next/api-reference#secrets).
4
- * Web Crypto only, so it runs in browsers, on Workers and on Node.
5
- */
6
- import { encryptToCiphertext } from "./ciphertext.js";
7
- /**
8
- * Encrypts `value` with your public key (the contents of `.deco/secrets.pub`)
9
- * and returns a ready `secret` block.
10
- */
11
- export async function encryptSecret(publicKey, value) {
12
- return { __resolveType: "secret", ciphertext: await encryptToCiphertext(publicKey, value) };
13
- }
14
- //# sourceMappingURL=secrets.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"secrets.js","sourceRoot":"","sources":["../../src/v8/secrets.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,EAAE,mBAAmB,EAAE,MAAM,iBAAiB,CAAC;AAEtD;;;GAGG;AACH,MAAM,CAAC,KAAK,UAAU,aAAa,CACjC,SAAiB,EACjB,KAAa;IAEb,OAAO,EAAE,aAAa,EAAE,QAAQ,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAC,SAAS,EAAE,KAAK,CAAC,EAAE,CAAC;AAC9F,CAAC"}
@@ -1,6 +0,0 @@
1
- /**
2
- * The secret ciphertext format. The implementation is a dependency-free leaf
3
- * module of the SDK (`src/v8/ciphertext.ts`), where the `secret` built-in
4
- * decrypts it; the protocol re-exports it for its secret guard.
5
- */
6
- export * from "../v8/ciphertext.ts";
@@ -1,239 +0,0 @@
1
- /**
2
- * The secret guard: the content protocol refuses plain text in a `Secret`
3
- * field, so the site editor and agents can't save a credential by mistake.
4
- *
5
- * A `Secret` field must hold a `secret` block with a well-formed
6
- * `ciphertext` (`{ "__resolveType": "secret", "ciphertext": "v1.…" }`, in the
7
- * format `./ciphertext` pins: three base64url segments of checked lengths), or a
8
- * variant block whose every value does. Every `secret` block anywhere in an
9
- * entry must carry a well-formed `ciphertext`, whatever its field.
10
- *
11
- * The schema marks a `Secret` field with `"format": "secret"` — the contract
12
- * `deco schema` emits for the `Secret` type. A legacy secret loader block
13
- * (`website/loaders/secret.ts`) is left alone. Browser-safe.
14
- */
15
- import { parseCiphertext } from "./ciphertext.ts";
16
- import type { BlockViolation } from "./errors.ts";
17
- import type { DecoMeta } from "./types.ts";
18
-
19
- /** The built-in block type that holds an encrypted value. */
20
- export const SECRET_BLOCK_TYPE = "secret";
21
-
22
- /** The JSON Schema `format` that marks a `Secret` field. */
23
- export const SECRET_FORMAT = "secret";
24
-
25
- const MULTIVARIATE_TYPES = new Set(["multivariate", "website/flags/multivariate.ts"]);
26
- const LAZY_TYPE = "lazy";
27
- /**
28
- * The legacy (v7) secret loader. Its `encrypted` prop is a string marked
29
- * `"format": "secret"` that already holds the site's own ciphertext, so it
30
- * isn't a `Secret` field; its blocks are migrated, not guarded.
31
- */
32
- const LEGACY_SECRET_LOADER = /(^|\/)loaders\/secret\.ts$/;
33
- const MAX_DEPTH = 512;
34
-
35
- type Json = Record<string, unknown>;
36
-
37
- const isObject = (value: unknown): value is Json =>
38
- typeof value === "object" && value !== null && !Array.isArray(value);
39
-
40
- const resolveTypeOf = (value: unknown): string | undefined =>
41
- isObject(value) && typeof value.__resolveType === "string" ? value.__resolveType : undefined;
42
-
43
- const escapePointer = (key: string) => key.replace(/~/g, "~0").replace(/\//g, "~1");
44
-
45
- /**
46
- * True when `ciphertext` is a well-formed secret ciphertext:
47
- * `v1.<wrappedKey>.<iv>.<ciphertext>` with segment lengths an RSA-OAEP and
48
- * AES-256-GCM encryption produces. Checking it needs no key.
49
- */
50
- export function isWellFormedCiphertext(ciphertext: unknown): ciphertext is string {
51
- return parseCiphertext(ciphertext) !== null;
52
- }
53
-
54
- /** True when a JSON Schema node describes a `Secret` field. */
55
- export function isSecretFieldSchema(schema: unknown): boolean {
56
- return isObject(schema) && schema.format === SECRET_FORMAT;
57
- }
58
-
59
- /** True when `value` is a `secret` block with a well-formed `ciphertext`. */
60
- export function isSecretBlock(value: unknown): boolean {
61
- return (
62
- resolveTypeOf(value) === SECRET_BLOCK_TYPE && isWellFormedCiphertext((value as Json).ciphertext)
63
- );
64
- }
65
-
66
- const blockIndexCache = new WeakMap<object, Map<string, unknown>>();
67
-
68
- /** Every block type in the schema's manifest, by key, to the schema of its arguments. */
69
- function blockIndex(meta: DecoMeta): Map<string, unknown> {
70
- const cached = blockIndexCache.get(meta);
71
- if (cached) return cached;
72
- const index = new Map<string, unknown>();
73
- for (const group of Object.values(meta.manifest?.blocks ?? {})) {
74
- if (!isObject(group)) continue;
75
- for (const [key, schema] of Object.entries(group)) {
76
- if (!index.has(key)) index.set(key, schema);
77
- }
78
- }
79
- blockIndexCache.set(meta, index);
80
- return index;
81
- }
82
-
83
- class SecretWalker {
84
- readonly violations: BlockViolation[] = [];
85
-
86
- constructor(
87
- private readonly name: string,
88
- private readonly meta: DecoMeta | null,
89
- ) {}
90
-
91
- private report(pointer: string, rule: string, message: string) {
92
- this.violations.push({ name: this.name, pointer, rule, message });
93
- }
94
-
95
- /** Follows local `$ref`s into `schema.definitions`. */
96
- private deref(schema: unknown): unknown {
97
- let current = schema;
98
- for (let hops = 0; hops < 32 && isObject(current) && typeof current.$ref === "string"; hops++) {
99
- const match = /^#\/definitions\/(.+)$/.exec(current.$ref);
100
- if (!match) return current;
101
- const key = decodeURIComponent(match[1]!).replace(/~1/g, "/").replace(/~0/g, "~");
102
- current = this.meta?.schema?.definitions?.[key];
103
- }
104
- return current;
105
- }
106
-
107
- /** The schemas of a node, flattened through `allOf`/`anyOf`/`oneOf`. */
108
- private branches(schema: unknown, depth = 0): Json[] {
109
- const node = this.deref(schema);
110
- if (!isObject(node) || depth > 16) return [];
111
- const out: Json[] = [node];
112
- for (const combinator of ["allOf", "anyOf", "oneOf"] as const) {
113
- const list = node[combinator];
114
- if (Array.isArray(list)) for (const item of list) out.push(...this.branches(item, depth + 1));
115
- }
116
- return out;
117
- }
118
-
119
- private isSecretField(schema: unknown): boolean {
120
- return this.branches(schema).some(isSecretFieldSchema);
121
- }
122
-
123
- private propertySchema(schema: unknown, key: string): unknown {
124
- for (const branch of this.branches(schema)) {
125
- const properties = branch.properties;
126
- if (isObject(properties) && key in properties) return properties[key];
127
- }
128
- for (const branch of this.branches(schema)) {
129
- if (isObject(branch.additionalProperties)) return branch.additionalProperties;
130
- }
131
- return undefined;
132
- }
133
-
134
- private itemSchema(schema: unknown): unknown {
135
- for (const branch of this.branches(schema)) {
136
- if (isObject(branch.items)) return branch.items;
137
- }
138
- return undefined;
139
- }
140
-
141
- /** A value stored in a `Secret` field. */
142
- checkSecretValue(value: unknown, pointer: string, depth: number) {
143
- if (depth > MAX_DEPTH)
144
- return this.report(pointer, "too-deep", "the value is nested too deeply");
145
- const type = resolveTypeOf(value);
146
- if (type === SECRET_BLOCK_TYPE) return this.walkBlock(value as Json, pointer, depth);
147
- if (type !== undefined && MULTIVARIATE_TYPES.has(type)) {
148
- const variants = (value as Json).variants;
149
- if (!Array.isArray(variants)) {
150
- return this.report(
151
- pointer,
152
- "secret-field",
153
- "a Secret field holds a variant block without variants",
154
- );
155
- }
156
- for (const [index, variant] of variants.entries()) {
157
- const at = `${pointer}/variants/${index}`;
158
- if (!isObject(variant)) {
159
- this.report(at, "secret-field", "a variant must be an object");
160
- continue;
161
- }
162
- if (variant.rule !== undefined) this.walkAny(variant.rule, `${at}/rule`, depth + 1);
163
- let inner = variant.value;
164
- let innerAt = `${at}/value`;
165
- if (resolveTypeOf(inner) === LAZY_TYPE) {
166
- inner = (inner as Json).value;
167
- innerAt = `${innerAt}/value`;
168
- }
169
- this.checkSecretValue(inner, innerAt, depth + 1);
170
- }
171
- return;
172
- }
173
- this.report(
174
- pointer,
175
- "secret-field",
176
- 'a Secret field must hold a "secret" block with a well-formed ciphertext, never plain text',
177
- );
178
- }
179
-
180
- /** A block value: its own definition (from the manifest) describes its arguments. */
181
- walkBlock(block: Json, pointer: string, depth: number) {
182
- const type = block.__resolveType as string;
183
- if (type === SECRET_BLOCK_TYPE && !isWellFormedCiphertext(block.ciphertext)) {
184
- this.report(
185
- pointer,
186
- "secret-ciphertext",
187
- 'a "secret" block must carry a well-formed "ciphertext" (v1.<wrappedKey>.<iv>.<ciphertext>)',
188
- );
189
- }
190
- const definition =
191
- this.meta && !LEGACY_SECRET_LOADER.test(type) ? blockIndex(this.meta).get(type) : undefined;
192
- this.walkObject(block, definition, pointer, depth);
193
- }
194
-
195
- private walkObject(object: Json, schema: unknown, pointer: string, depth: number) {
196
- for (const [key, child] of Object.entries(object)) {
197
- if (key === "__resolveType") continue;
198
- const childSchema = schema === undefined ? undefined : this.propertySchema(schema, key);
199
- this.walk(child, childSchema, `${pointer}/${escapePointer(key)}`, depth + 1);
200
- }
201
- }
202
-
203
- walk(value: unknown, schema: unknown, pointer: string, depth: number) {
204
- if (depth > MAX_DEPTH)
205
- return this.report(pointer, "too-deep", "the value is nested too deeply");
206
- if (schema !== undefined && this.isSecretField(schema)) {
207
- return this.checkSecretValue(value, pointer, depth);
208
- }
209
- if (Array.isArray(value)) {
210
- const items = schema === undefined ? undefined : this.itemSchema(schema);
211
- for (const [index, item] of value.entries()) {
212
- this.walk(item, items, `${pointer}/${index}`, depth + 1);
213
- }
214
- return;
215
- }
216
- if (!isObject(value)) return;
217
- // A nested block is described by its own definition, not the field's union.
218
- if (resolveTypeOf(value) !== undefined) return this.walkBlock(value, pointer, depth);
219
- this.walkObject(value, schema, pointer, depth);
220
- }
221
-
222
- walkAny(value: unknown, pointer: string, depth: number) {
223
- this.walk(value, undefined, pointer, depth);
224
- }
225
- }
226
-
227
- /**
228
- * Checks one entry against the secret guard. `meta` is the parsed schema;
229
- * without one, only the `secret` blocks' ciphertexts can be checked.
230
- */
231
- export function checkSecrets(
232
- name: string,
233
- entry: unknown,
234
- meta: DecoMeta | null,
235
- ): BlockViolation[] {
236
- const walker = new SecretWalker(name, meta);
237
- walker.walk(entry, undefined, "", 0);
238
- return walker.violations;
239
- }
@@ -1,82 +0,0 @@
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.ts";
21
- import type { BlockFunction } from "../types.ts";
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
- }
@@ -1,158 +0,0 @@
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
- }