@10x-media/fields 0.1.0-beta.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 (299) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/LICENSE +21 -0
  3. package/README.md +62 -0
  4. package/dist/exports/client.d.ts +7 -0
  5. package/dist/exports/client.js +8 -0
  6. package/dist/exports/color-utils.d.ts +9 -0
  7. package/dist/exports/color-utils.js +7 -0
  8. package/dist/exports/color.d.ts +6 -0
  9. package/dist/exports/color.js +5 -0
  10. package/dist/exports/encrypted.d.ts +12 -0
  11. package/dist/exports/encrypted.js +10 -0
  12. package/dist/exports/i18n.d.ts +3 -0
  13. package/dist/exports/i18n.js +3 -0
  14. package/dist/exports/icon-adapters/lucide.d.ts +5 -0
  15. package/dist/exports/icon-adapters/lucide.js +4 -0
  16. package/dist/exports/icon-adapters/radix.d.ts +5 -0
  17. package/dist/exports/icon-adapters/radix.js +4 -0
  18. package/dist/exports/icon-adapters/tabler.d.ts +5 -0
  19. package/dist/exports/icon-adapters/tabler.js +4 -0
  20. package/dist/exports/icon-codegen.d.ts +4 -0
  21. package/dist/exports/icon-codegen.js +2 -0
  22. package/dist/exports/icon-react.d.ts +4 -0
  23. package/dist/exports/icon-react.js +3 -0
  24. package/dist/exports/icon.d.ts +8 -0
  25. package/dist/exports/icon.js +7 -0
  26. package/dist/exports/rsc.d.ts +10 -0
  27. package/dist/exports/rsc.js +9 -0
  28. package/dist/exports/types.d.ts +4 -0
  29. package/dist/exports/types.js +1 -0
  30. package/dist/fields/color/client/ColorField.d.ts +13 -0
  31. package/dist/fields/color/client/ColorField.js +321 -0
  32. package/dist/fields/color/client/ColorField.js.map +1 -0
  33. package/dist/fields/color/client/ColorPickerPanel.d.ts +29 -0
  34. package/dist/fields/color/client/ColorPickerPanel.js +233 -0
  35. package/dist/fields/color/client/ColorPickerPanel.js.map +1 -0
  36. package/dist/fields/color/client/colorField.css +411 -0
  37. package/dist/fields/color/client/icons.js +38 -0
  38. package/dist/fields/color/client/icons.js.map +1 -0
  39. package/dist/fields/color/colorField.d.ts +20 -0
  40. package/dist/fields/color/colorField.js +102 -0
  41. package/dist/fields/color/colorField.js.map +1 -0
  42. package/dist/fields/color/commitValue.js +29 -0
  43. package/dist/fields/color/commitValue.js.map +1 -0
  44. package/dist/fields/color/engine/contrast.d.ts +10 -0
  45. package/dist/fields/color/engine/contrast.js +25 -0
  46. package/dist/fields/color/engine/contrast.js.map +1 -0
  47. package/dist/fields/color/engine/convert.d.ts +28 -0
  48. package/dist/fields/color/engine/convert.js +232 -0
  49. package/dist/fields/color/engine/convert.js.map +1 -0
  50. package/dist/fields/color/engine/format.d.ts +15 -0
  51. package/dist/fields/color/engine/format.js +53 -0
  52. package/dist/fields/color/engine/format.js.map +1 -0
  53. package/dist/fields/color/engine/index.d.ts +8 -0
  54. package/dist/fields/color/engine/namedColors.d.ts +9 -0
  55. package/dist/fields/color/engine/namedColors.js +159 -0
  56. package/dist/fields/color/engine/namedColors.js.map +1 -0
  57. package/dist/fields/color/engine/parse.d.ts +12 -0
  58. package/dist/fields/color/engine/parse.js +151 -0
  59. package/dist/fields/color/engine/parse.js.map +1 -0
  60. package/dist/fields/color/engine/salvage.d.ts +13 -0
  61. package/dist/fields/color/engine/salvage.js +75 -0
  62. package/dist/fields/color/engine/salvage.js.map +1 -0
  63. package/dist/fields/color/engine/types.d.ts +34 -0
  64. package/dist/fields/color/options.d.ts +55 -0
  65. package/dist/fields/color/options.js +8 -0
  66. package/dist/fields/color/options.js.map +1 -0
  67. package/dist/fields/color/presetChip.js +27 -0
  68. package/dist/fields/color/presetChip.js.map +1 -0
  69. package/dist/fields/color/presetsFromDoc.d.ts +27 -0
  70. package/dist/fields/color/presetsFromDoc.js +74 -0
  71. package/dist/fields/color/presetsFromDoc.js.map +1 -0
  72. package/dist/fields/color/resolveFormat.js +16 -0
  73. package/dist/fields/color/resolveFormat.js.map +1 -0
  74. package/dist/fields/color/resolvePresets.d.ts +29 -0
  75. package/dist/fields/color/resolvePresets.js +39 -0
  76. package/dist/fields/color/resolvePresets.js.map +1 -0
  77. package/dist/fields/color/server/ColorCell.d.ts +6 -0
  78. package/dist/fields/color/server/ColorCell.js +34 -0
  79. package/dist/fields/color/server/ColorCell.js.map +1 -0
  80. package/dist/fields/color/server/ColorFieldServer.d.ts +18 -0
  81. package/dist/fields/color/server/ColorFieldServer.js +69 -0
  82. package/dist/fields/color/server/ColorFieldServer.js.map +1 -0
  83. package/dist/fields/color/server/colorCell.css +32 -0
  84. package/dist/fields/encrypted/boot.d.ts +14 -0
  85. package/dist/fields/encrypted/boot.js +22 -0
  86. package/dist/fields/encrypted/boot.js.map +1 -0
  87. package/dist/fields/encrypted/components/EncryptedInput.js +89 -0
  88. package/dist/fields/encrypted/components/EncryptedInput.js.map +1 -0
  89. package/dist/fields/encrypted/components/EncryptedTextarea.js +86 -0
  90. package/dist/fields/encrypted/components/EncryptedTextarea.js.map +1 -0
  91. package/dist/fields/encrypted/components/EyeToggle.js +51 -0
  92. package/dist/fields/encrypted/components/EyeToggle.js.map +1 -0
  93. package/dist/fields/encrypted/components/MaskDots.js +20 -0
  94. package/dist/fields/encrypted/components/MaskDots.js.map +1 -0
  95. package/dist/fields/encrypted/components/ProtectedCell.d.ts +19 -0
  96. package/dist/fields/encrypted/components/ProtectedCell.js +44 -0
  97. package/dist/fields/encrypted/components/ProtectedCell.js.map +1 -0
  98. package/dist/fields/encrypted/components/ProtectedField.css +180 -0
  99. package/dist/fields/encrypted/components/ProtectedField.d.ts +30 -0
  100. package/dist/fields/encrypted/components/ProtectedField.js +95 -0
  101. package/dist/fields/encrypted/components/ProtectedField.js.map +1 -0
  102. package/dist/fields/encrypted/components/ProtectedRichText.d.ts +21 -0
  103. package/dist/fields/encrypted/components/ProtectedRichText.js +35 -0
  104. package/dist/fields/encrypted/components/ProtectedRichText.js.map +1 -0
  105. package/dist/fields/encrypted/components/RichTextRevealGate.d.ts +24 -0
  106. package/dist/fields/encrypted/components/RichTextRevealGate.js +87 -0
  107. package/dist/fields/encrypted/components/RichTextRevealGate.js.map +1 -0
  108. package/dist/fields/encrypted/components/StructuralField.js +64 -0
  109. package/dist/fields/encrypted/components/StructuralField.js.map +1 -0
  110. package/dist/fields/encrypted/components/facsimiles.js +219 -0
  111. package/dist/fields/encrypted/components/facsimiles.js.map +1 -0
  112. package/dist/fields/encrypted/components/placement.js +21 -0
  113. package/dist/fields/encrypted/components/placement.js.map +1 -0
  114. package/dist/fields/encrypted/crypto/aad.js +29 -0
  115. package/dist/fields/encrypted/crypto/aad.js.map +1 -0
  116. package/dist/fields/encrypted/crypto/bidx.js +26 -0
  117. package/dist/fields/encrypted/crypto/bidx.js.map +1 -0
  118. package/dist/fields/encrypted/crypto/keys.d.ts +31 -0
  119. package/dist/fields/encrypted/crypto/keys.js +113 -0
  120. package/dist/fields/encrypted/crypto/keys.js.map +1 -0
  121. package/dist/fields/encrypted/crypto/wire.d.ts +23 -0
  122. package/dist/fields/encrypted/crypto/wire.js +135 -0
  123. package/dist/fields/encrypted/crypto/wire.js.map +1 -0
  124. package/dist/fields/encrypted/encryptedField.d.ts +15 -0
  125. package/dist/fields/encrypted/encryptedField.js +187 -0
  126. package/dist/fields/encrypted/encryptedField.js.map +1 -0
  127. package/dist/fields/encrypted/hooks.d.ts +21 -0
  128. package/dist/fields/encrypted/hooks.js +326 -0
  129. package/dist/fields/encrypted/hooks.js.map +1 -0
  130. package/dist/fields/encrypted/maskDots.js +16 -0
  131. package/dist/fields/encrypted/maskDots.js.map +1 -0
  132. package/dist/fields/encrypted/plaintextStash.js +57 -0
  133. package/dist/fields/encrypted/plaintextStash.js.map +1 -0
  134. package/dist/fields/encrypted/queryRewrite.d.ts +12 -0
  135. package/dist/fields/encrypted/queryRewrite.js +134 -0
  136. package/dist/fields/encrypted/queryRewrite.js.map +1 -0
  137. package/dist/fields/encrypted/scan.js +36 -0
  138. package/dist/fields/encrypted/scan.js.map +1 -0
  139. package/dist/fields/encrypted/types.d.ts +35 -0
  140. package/dist/fields/encrypted/types.js +12 -0
  141. package/dist/fields/encrypted/types.js.map +1 -0
  142. package/dist/fields/encrypted/typescriptSchema.js +41 -0
  143. package/dist/fields/encrypted/typescriptSchema.js.map +1 -0
  144. package/dist/fields/encrypted/utils/decryptAllData.d.ts +17 -0
  145. package/dist/fields/encrypted/utils/decryptAllData.js +98 -0
  146. package/dist/fields/encrypted/utils/decryptAllData.js.map +1 -0
  147. package/dist/fields/encrypted/utils/encryptExistingData.d.ts +14 -0
  148. package/dist/fields/encrypted/utils/encryptExistingData.js +72 -0
  149. package/dist/fields/encrypted/utils/encryptExistingData.js.map +1 -0
  150. package/dist/fields/encrypted/utils/pageThrough.js +42 -0
  151. package/dist/fields/encrypted/utils/pageThrough.js.map +1 -0
  152. package/dist/fields/encrypted/utils/rotateEncryptedFields.d.ts +27 -0
  153. package/dist/fields/encrypted/utils/rotateEncryptedFields.js +92 -0
  154. package/dist/fields/encrypted/utils/rotateEncryptedFields.js.map +1 -0
  155. package/dist/fields/encrypted/validators.js +111 -0
  156. package/dist/fields/encrypted/validators.js.map +1 -0
  157. package/dist/fields/icon/adapters/lucide/adapter.d.ts +8 -0
  158. package/dist/fields/icon/adapters/lucide/adapter.js +15 -0
  159. package/dist/fields/icon/adapters/lucide/adapter.js.map +1 -0
  160. package/dist/fields/icon/adapters/lucide/client.d.ts +10 -0
  161. package/dist/fields/icon/adapters/lucide/client.js +41 -0
  162. package/dist/fields/icon/adapters/lucide/client.js.map +1 -0
  163. package/dist/fields/icon/adapters/lucide/generated/manifest.js +23338 -0
  164. package/dist/fields/icon/adapters/lucide/generated/manifest.js.map +1 -0
  165. package/dist/fields/icon/adapters/lucide/generated/nodes.js +14296 -0
  166. package/dist/fields/icon/adapters/lucide/generated/nodes.js.map +1 -0
  167. package/dist/fields/icon/adapters/lucide/renderer.d.ts +7 -0
  168. package/dist/fields/icon/adapters/lucide/renderer.js +13 -0
  169. package/dist/fields/icon/adapters/lucide/renderer.js.map +1 -0
  170. package/dist/fields/icon/adapters/radix/adapter.d.ts +8 -0
  171. package/dist/fields/icon/adapters/radix/adapter.js +14 -0
  172. package/dist/fields/icon/adapters/radix/adapter.js.map +1 -0
  173. package/dist/fields/icon/adapters/radix/client.d.ts +8 -0
  174. package/dist/fields/icon/adapters/radix/client.js +20 -0
  175. package/dist/fields/icon/adapters/radix/client.js.map +1 -0
  176. package/dist/fields/icon/adapters/radix/generated/imports.js +324 -0
  177. package/dist/fields/icon/adapters/radix/generated/imports.js.map +1 -0
  178. package/dist/fields/icon/adapters/radix/generated/manifest.js +1805 -0
  179. package/dist/fields/icon/adapters/radix/generated/manifest.js.map +1 -0
  180. package/dist/fields/icon/adapters/radix/renderer.d.ts +7 -0
  181. package/dist/fields/icon/adapters/radix/renderer.js +23 -0
  182. package/dist/fields/icon/adapters/radix/renderer.js.map +1 -0
  183. package/dist/fields/icon/adapters/tabler/adapter.d.ts +8 -0
  184. package/dist/fields/icon/adapters/tabler/adapter.js +15 -0
  185. package/dist/fields/icon/adapters/tabler/adapter.js.map +1 -0
  186. package/dist/fields/icon/adapters/tabler/client.d.ts +9 -0
  187. package/dist/fields/icon/adapters/tabler/client.js +18 -0
  188. package/dist/fields/icon/adapters/tabler/client.js.map +1 -0
  189. package/dist/fields/icon/adapters/tabler/generated/imports.js +4942 -0
  190. package/dist/fields/icon/adapters/tabler/generated/imports.js.map +1 -0
  191. package/dist/fields/icon/adapters/tabler/generated/manifest.js +61269 -0
  192. package/dist/fields/icon/adapters/tabler/generated/manifest.js.map +1 -0
  193. package/dist/fields/icon/adapters/tabler/generated/nodes.js +26749 -0
  194. package/dist/fields/icon/adapters/tabler/generated/nodes.js.map +1 -0
  195. package/dist/fields/icon/adapters/tabler/renderer.d.ts +7 -0
  196. package/dist/fields/icon/adapters/tabler/renderer.js +13 -0
  197. package/dist/fields/icon/adapters/tabler/renderer.js.map +1 -0
  198. package/dist/fields/icon/client/DrawerGlyph.js +32 -0
  199. package/dist/fields/icon/client/DrawerGlyph.js.map +1 -0
  200. package/dist/fields/icon/client/IconDrawerContent.js +294 -0
  201. package/dist/fields/icon/client/IconDrawerContent.js.map +1 -0
  202. package/dist/fields/icon/client/IconFieldClient.d.ts +19 -0
  203. package/dist/fields/icon/client/IconFieldClient.js +245 -0
  204. package/dist/fields/icon/client/IconFieldClient.js.map +1 -0
  205. package/dist/fields/icon/client/IconLibrarySelect.d.ts +14 -0
  206. package/dist/fields/icon/client/IconLibrarySelect.js +36 -0
  207. package/dist/fields/icon/client/IconLibrarySelect.js.map +1 -0
  208. package/dist/fields/icon/client/availableLibraries.js +25 -0
  209. package/dist/fields/icon/client/availableLibraries.js.map +1 -0
  210. package/dist/fields/icon/client/generatedAdapter.js +88 -0
  211. package/dist/fields/icon/client/generatedAdapter.js.map +1 -0
  212. package/dist/fields/icon/client/icon-field.css +524 -0
  213. package/dist/fields/icon/client/useRecentIcons.js +32 -0
  214. package/dist/fields/icon/client/useRecentIcons.js.map +1 -0
  215. package/dist/fields/icon/codegen/emit.js +81 -0
  216. package/dist/fields/icon/codegen/emit.js.map +1 -0
  217. package/dist/fields/icon/codegen/generate.d.ts +10 -0
  218. package/dist/fields/icon/codegen/generate.js +59 -0
  219. package/dist/fields/icon/codegen/generate.js.map +1 -0
  220. package/dist/fields/icon/codegen/sources/lucide.js +52 -0
  221. package/dist/fields/icon/codegen/sources/lucide.js.map +1 -0
  222. package/dist/fields/icon/codegen/sources/radix.js +33 -0
  223. package/dist/fields/icon/codegen/sources/radix.js.map +1 -0
  224. package/dist/fields/icon/codegen/sources/tabler.js +31 -0
  225. package/dist/fields/icon/codegen/sources/tabler.js.map +1 -0
  226. package/dist/fields/icon/codegen/types.d.ts +36 -0
  227. package/dist/fields/icon/defineIconAdapter.d.ts +8 -0
  228. package/dist/fields/icon/defineIconAdapter.js +10 -0
  229. package/dist/fields/icon/defineIconAdapter.js.map +1 -0
  230. package/dist/fields/icon/plugin.js +55 -0
  231. package/dist/fields/icon/plugin.js.map +1 -0
  232. package/dist/fields/icon/react/createIcon.d.ts +15 -0
  233. package/dist/fields/icon/react/createIcon.js +47 -0
  234. package/dist/fields/icon/react/createIcon.js.map +1 -0
  235. package/dist/fields/icon/react/createRscIcon.d.ts +12 -0
  236. package/dist/fields/icon/react/createRscIcon.js +27 -0
  237. package/dist/fields/icon/react/createRscIcon.js.map +1 -0
  238. package/dist/fields/icon/react/types.d.ts +24 -0
  239. package/dist/fields/icon/rsc/IconCell.d.ts +14 -0
  240. package/dist/fields/icon/rsc/IconCell.js +32 -0
  241. package/dist/fields/icon/rsc/IconCell.js.map +1 -0
  242. package/dist/fields/icon/rsc/IconFieldServer.d.ts +24 -0
  243. package/dist/fields/icon/rsc/IconFieldServer.js +74 -0
  244. package/dist/fields/icon/rsc/IconFieldServer.js.map +1 -0
  245. package/dist/fields/icon/rsc/IconLibrarySelectServer.d.ts +13 -0
  246. package/dist/fields/icon/rsc/IconLibrarySelectServer.js +24 -0
  247. package/dist/fields/icon/rsc/IconLibrarySelectServer.js.map +1 -0
  248. package/dist/fields/icon/rsc/resolveStaticLabel.js +16 -0
  249. package/dist/fields/icon/rsc/resolveStaticLabel.js.map +1 -0
  250. package/dist/fields/icon/server/availability.d.ts +32 -0
  251. package/dist/fields/icon/server/availability.js +58 -0
  252. package/dist/fields/icon/server/availability.js.map +1 -0
  253. package/dist/fields/icon/server/iconField.d.ts +32 -0
  254. package/dist/fields/icon/server/iconField.js +48 -0
  255. package/dist/fields/icon/server/iconField.js.map +1 -0
  256. package/dist/fields/icon/server/iconLibraryField.d.ts +23 -0
  257. package/dist/fields/icon/server/iconLibraryField.js +50 -0
  258. package/dist/fields/icon/server/iconLibraryField.js.map +1 -0
  259. package/dist/fields/icon/server/libraryOptions.d.ts +12 -0
  260. package/dist/fields/icon/server/libraryOptions.js +13 -0
  261. package/dist/fields/icon/server/libraryOptions.js.map +1 -0
  262. package/dist/fields/icon/server/manifestCache.js +17 -0
  263. package/dist/fields/icon/server/manifestCache.js.map +1 -0
  264. package/dist/fields/icon/server/validate.js +37 -0
  265. package/dist/fields/icon/server/validate.js.map +1 -0
  266. package/dist/fields/icon/shared/adapterComponents.d.ts +23 -0
  267. package/dist/fields/icon/shared/formatIconLabel.js +16 -0
  268. package/dist/fields/icon/shared/formatIconLabel.js.map +1 -0
  269. package/dist/fields/icon/shared/search.js +58 -0
  270. package/dist/fields/icon/shared/search.js.map +1 -0
  271. package/dist/fields/icon/shared/value.d.ts +16 -0
  272. package/dist/fields/icon/shared/value.js +27 -0
  273. package/dist/fields/icon/shared/value.js.map +1 -0
  274. package/dist/index.d.ts +39 -0
  275. package/dist/index.js +41 -0
  276. package/dist/index.js.map +1 -0
  277. package/dist/plugin/registerTranslations.js +19 -0
  278. package/dist/plugin/registerTranslations.js.map +1 -0
  279. package/dist/plugin/registry.d.ts +9 -0
  280. package/dist/plugin/registry.js +14 -0
  281. package/dist/plugin/registry.js.map +1 -0
  282. package/dist/translations/de.js +49 -0
  283. package/dist/translations/de.js.map +1 -0
  284. package/dist/translations/en.js +49 -0
  285. package/dist/translations/en.js.map +1 -0
  286. package/dist/translations/index.d.ts +15 -0
  287. package/dist/translations/index.js +30 -0
  288. package/dist/translations/index.js.map +1 -0
  289. package/dist/translations/keys.d.ts +48 -0
  290. package/dist/translations/keys.js +48 -0
  291. package/dist/translations/keys.js.map +1 -0
  292. package/dist/translations/server.js +13 -0
  293. package/dist/translations/server.js.map +1 -0
  294. package/dist/translations/useTranslation.js +12 -0
  295. package/dist/translations/useTranslation.js.map +1 -0
  296. package/dist/types.d.ts +105 -0
  297. package/dist/utils/memoForRequest.js +25 -0
  298. package/dist/utils/memoForRequest.js.map +1 -0
  299. package/package.json +196 -0
@@ -0,0 +1,135 @@
1
+ import { createCipheriv, createDecipheriv, randomBytes } from "node:crypto";
2
+ //#region src/fields/encrypted/crypto/wire.ts
3
+ const WIRE_PREFIX = "pfe1";
4
+ /** GCM standard nonce size; unique per seal via randomBytes. */
5
+ const IV_LENGTH = 12;
6
+ const TAG_LENGTH = 16;
7
+ const SEGMENT_PATTERN = /^[A-Za-z0-9_-]+$/;
8
+ var MalformedCiphertextError = class extends Error {
9
+ constructor(reason) {
10
+ super(`@10x-media/fields: malformed ciphertext: ${reason}`);
11
+ this.name = "MalformedCiphertextError";
12
+ }
13
+ };
14
+ var UnknownKeyIdError = class extends Error {
15
+ keyId;
16
+ constructor(keyId) {
17
+ super(`@10x-media/fields: no key configured for keyId '${keyId}'`);
18
+ this.name = "UnknownKeyIdError";
19
+ this.keyId = keyId;
20
+ }
21
+ };
22
+ var AuthenticationFailedError = class extends Error {
23
+ keyId;
24
+ constructor(keyId) {
25
+ super(`@10x-media/fields: ciphertext failed authentication (keyId '${keyId}')`);
26
+ this.name = "AuthenticationFailedError";
27
+ this.keyId = keyId;
28
+ }
29
+ };
30
+ /**
31
+ * The ciphertext authenticated (correct key + AAD + tag) but the decrypted
32
+ * bytes are not valid JSON. Distinct from AuthenticationFailedError: auth
33
+ * succeeded, so this is non-retryable corruption, not a wrong key or AAD.
34
+ */
35
+ var CorruptPlaintextError = class extends Error {
36
+ keyId;
37
+ constructor(keyId, cause) {
38
+ super(`@10x-media/fields: ciphertext authenticated but plaintext is not valid JSON (keyId '${keyId}')`);
39
+ this.name = "CorruptPlaintextError";
40
+ this.keyId = keyId;
41
+ this.cause = cause;
42
+ }
43
+ };
44
+ /**
45
+ * JSON.stringify -> AES-256-GCM -> `pfe1.<keyId>.<iv>.<ct>.<tag>` (base64url).
46
+ * The JSON round-trip preserves JS types (number, boolean, arrays, objects);
47
+ * AAD binds the ciphertext to its collection.field[.locale] slot.
48
+ */
49
+ const seal = ({ aad, key, keyId, plaintext }) => {
50
+ const iv = randomBytes(IV_LENGTH);
51
+ const cipher = createCipheriv("aes-256-gcm", key, iv, { authTagLength: TAG_LENGTH });
52
+ cipher.setAAD(Buffer.from(aad, "utf8"));
53
+ const ciphertext = Buffer.concat([cipher.update(JSON.stringify(plaintext), "utf8"), cipher.final()]);
54
+ const tag = cipher.getAuthTag();
55
+ return [
56
+ WIRE_PREFIX,
57
+ keyId,
58
+ iv.toString("base64url"),
59
+ ciphertext.toString("base64url"),
60
+ tag.toString("base64url")
61
+ ].join(".");
62
+ };
63
+ const parseWire = (value) => {
64
+ const segments = value.split(".");
65
+ if (segments.length !== 5) throw new MalformedCiphertextError(`expected 5 segments, got ${segments.length}`);
66
+ const [prefix, keyId, ivRaw, ctRaw, tagRaw] = segments;
67
+ if (prefix !== "pfe1") throw new MalformedCiphertextError(`unknown prefix '${prefix}'`);
68
+ if (!SEGMENT_PATTERN.test(keyId)) throw new MalformedCiphertextError("invalid keyId segment");
69
+ for (const segment of [
70
+ ivRaw,
71
+ ctRaw,
72
+ tagRaw
73
+ ]) if (!SEGMENT_PATTERN.test(segment)) throw new MalformedCiphertextError("invalid base64url segment");
74
+ const iv = Buffer.from(ivRaw, "base64url");
75
+ const ciphertext = Buffer.from(ctRaw, "base64url");
76
+ const tag = Buffer.from(tagRaw, "base64url");
77
+ if (iv.length !== IV_LENGTH) throw new MalformedCiphertextError(`iv must be ${IV_LENGTH} bytes`);
78
+ if (tag.length !== TAG_LENGTH) throw new MalformedCiphertextError(`tag must be ${TAG_LENGTH} bytes`);
79
+ if (ciphertext.length === 0) throw new MalformedCiphertextError("empty ciphertext");
80
+ return {
81
+ ciphertext,
82
+ iv,
83
+ keyId,
84
+ tag
85
+ };
86
+ };
87
+ /**
88
+ * True only for a structurally valid wire string: prefix, 5 segments, base64url
89
+ * charset, and correct IV/tag byte lengths (a full parseWire, minus the GCM
90
+ * work). Validating the structure, not just the prefix and dot count, keeps a
91
+ * free-text secret literally shaped `pfe1.a.b.c.d` from being mistaken for
92
+ * ciphertext (which would skip its plaintext validation). Never throws.
93
+ */
94
+ const isSealed = (value) => {
95
+ if (typeof value !== "string") return false;
96
+ try {
97
+ parseWire(value);
98
+ return true;
99
+ } catch {
100
+ return false;
101
+ }
102
+ };
103
+ /**
104
+ * Decrypts with the key selected by the embedded keyId, trying each AAD
105
+ * candidate in order. Multiple candidates exist only for localized fields,
106
+ * where Payload's fallbackLocale hoisting and locale=all hook execution hide
107
+ * which locale a value belongs to (see plan Deviation 3). A failed candidate
108
+ * costs one GCM operation; candidates are bounded by the configured locales.
109
+ */
110
+ const unseal = (value, dataKeys, aadCandidates) => {
111
+ const { ciphertext, iv, keyId, tag } = parseWire(value);
112
+ const key = dataKeys.get(keyId);
113
+ if (!key) throw new UnknownKeyIdError(keyId);
114
+ for (const aad of aadCandidates) {
115
+ let json;
116
+ try {
117
+ const decipher = createDecipheriv("aes-256-gcm", key, iv, { authTagLength: TAG_LENGTH });
118
+ decipher.setAAD(Buffer.from(aad, "utf8"));
119
+ decipher.setAuthTag(tag);
120
+ json = Buffer.concat([decipher.update(ciphertext), decipher.final()]).toString("utf8");
121
+ } catch {
122
+ continue;
123
+ }
124
+ try {
125
+ return JSON.parse(json);
126
+ } catch (cause) {
127
+ throw new CorruptPlaintextError(keyId, cause);
128
+ }
129
+ }
130
+ throw new AuthenticationFailedError(keyId);
131
+ };
132
+ //#endregion
133
+ export { AuthenticationFailedError, MalformedCiphertextError, UnknownKeyIdError, isSealed, parseWire, seal, unseal };
134
+
135
+ //# sourceMappingURL=wire.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"wire.js","names":[],"sources":["../../../../src/fields/encrypted/crypto/wire.ts"],"sourcesContent":["import { createCipheriv, createDecipheriv, randomBytes } from 'node:crypto'\n\nexport const WIRE_PREFIX = 'pfe1'\n/** GCM standard nonce size; unique per seal via randomBytes. */\nconst IV_LENGTH = 12\nconst TAG_LENGTH = 16\nconst SEGMENT_PATTERN = /^[A-Za-z0-9_-]+$/\n\nexport class MalformedCiphertextError extends Error {\n\tconstructor(reason: string) {\n\t\tsuper(`@10x-media/fields: malformed ciphertext: ${reason}`)\n\t\tthis.name = 'MalformedCiphertextError'\n\t}\n}\n\nexport class UnknownKeyIdError extends Error {\n\treadonly keyId: string\n\tconstructor(keyId: string) {\n\t\tsuper(`@10x-media/fields: no key configured for keyId '${keyId}'`)\n\t\tthis.name = 'UnknownKeyIdError'\n\t\tthis.keyId = keyId\n\t}\n}\n\nexport class AuthenticationFailedError extends Error {\n\treadonly keyId: string\n\tconstructor(keyId: string) {\n\t\tsuper(`@10x-media/fields: ciphertext failed authentication (keyId '${keyId}')`)\n\t\tthis.name = 'AuthenticationFailedError'\n\t\tthis.keyId = keyId\n\t}\n}\n\n/**\n * The ciphertext authenticated (correct key + AAD + tag) but the decrypted\n * bytes are not valid JSON. Distinct from AuthenticationFailedError: auth\n * succeeded, so this is non-retryable corruption, not a wrong key or AAD.\n */\nexport class CorruptPlaintextError extends Error {\n\treadonly keyId: string\n\tconstructor(keyId: string, cause: unknown) {\n\t\tsuper(\n\t\t\t`@10x-media/fields: ciphertext authenticated but plaintext is not valid JSON (keyId '${keyId}')`\n\t\t)\n\t\tthis.name = 'CorruptPlaintextError'\n\t\tthis.keyId = keyId\n\t\tthis.cause = cause\n\t}\n}\n\nexport interface SealArgs {\n\taad: string\n\tkey: Buffer\n\tkeyId: string\n\tplaintext: unknown\n}\n\n/**\n * JSON.stringify -> AES-256-GCM -> `pfe1.<keyId>.<iv>.<ct>.<tag>` (base64url).\n * The JSON round-trip preserves JS types (number, boolean, arrays, objects);\n * AAD binds the ciphertext to its collection.field[.locale] slot.\n */\nexport const seal = ({ aad, key, keyId, plaintext }: SealArgs): string => {\n\tconst iv = randomBytes(IV_LENGTH)\n\tconst cipher = createCipheriv('aes-256-gcm', key, iv, { authTagLength: TAG_LENGTH })\n\tcipher.setAAD(Buffer.from(aad, 'utf8'))\n\tconst ciphertext = Buffer.concat([\n\t\tcipher.update(JSON.stringify(plaintext), 'utf8'),\n\t\tcipher.final(),\n\t])\n\tconst tag = cipher.getAuthTag()\n\treturn [\n\t\tWIRE_PREFIX,\n\t\tkeyId,\n\t\tiv.toString('base64url'),\n\t\tciphertext.toString('base64url'),\n\t\ttag.toString('base64url'),\n\t].join('.')\n}\n\nexport interface ParsedWire {\n\tciphertext: Buffer\n\tiv: Buffer\n\tkeyId: string\n\ttag: Buffer\n}\n\nexport const parseWire = (value: string): ParsedWire => {\n\tconst segments = value.split('.')\n\tif (segments.length !== 5) {\n\t\tthrow new MalformedCiphertextError(`expected 5 segments, got ${segments.length}`)\n\t}\n\tconst [prefix, keyId, ivRaw, ctRaw, tagRaw] = segments as [string, string, string, string, string]\n\tif (prefix !== WIRE_PREFIX) {\n\t\tthrow new MalformedCiphertextError(`unknown prefix '${prefix}'`)\n\t}\n\tif (!SEGMENT_PATTERN.test(keyId)) {\n\t\tthrow new MalformedCiphertextError('invalid keyId segment')\n\t}\n\tfor (const segment of [ivRaw, ctRaw, tagRaw]) {\n\t\tif (!SEGMENT_PATTERN.test(segment)) {\n\t\t\tthrow new MalformedCiphertextError('invalid base64url segment')\n\t\t}\n\t}\n\tconst iv = Buffer.from(ivRaw, 'base64url')\n\tconst ciphertext = Buffer.from(ctRaw, 'base64url')\n\tconst tag = Buffer.from(tagRaw, 'base64url')\n\tif (iv.length !== IV_LENGTH) {\n\t\tthrow new MalformedCiphertextError(`iv must be ${IV_LENGTH} bytes`)\n\t}\n\tif (tag.length !== TAG_LENGTH) {\n\t\tthrow new MalformedCiphertextError(`tag must be ${TAG_LENGTH} bytes`)\n\t}\n\tif (ciphertext.length === 0) {\n\t\tthrow new MalformedCiphertextError('empty ciphertext')\n\t}\n\treturn { ciphertext, iv, keyId, tag }\n}\n\n/**\n * True only for a structurally valid wire string: prefix, 5 segments, base64url\n * charset, and correct IV/tag byte lengths (a full parseWire, minus the GCM\n * work). Validating the structure, not just the prefix and dot count, keeps a\n * free-text secret literally shaped `pfe1.a.b.c.d` from being mistaken for\n * ciphertext (which would skip its plaintext validation). Never throws.\n */\nexport const isSealed = (value: unknown): value is string => {\n\tif (typeof value !== 'string') {\n\t\treturn false\n\t}\n\ttry {\n\t\tparseWire(value)\n\t\treturn true\n\t} catch {\n\t\treturn false\n\t}\n}\n\n/**\n * Decrypts with the key selected by the embedded keyId, trying each AAD\n * candidate in order. Multiple candidates exist only for localized fields,\n * where Payload's fallbackLocale hoisting and locale=all hook execution hide\n * which locale a value belongs to (see plan Deviation 3). A failed candidate\n * costs one GCM operation; candidates are bounded by the configured locales.\n */\nexport const unseal = (\n\tvalue: string,\n\tdataKeys: ReadonlyMap<string, Buffer>,\n\taadCandidates: readonly string[]\n): unknown => {\n\tconst { ciphertext, iv, keyId, tag } = parseWire(value)\n\tconst key = dataKeys.get(keyId)\n\tif (!key) {\n\t\tthrow new UnknownKeyIdError(keyId)\n\t}\n\tfor (const aad of aadCandidates) {\n\t\tlet json: string\n\t\ttry {\n\t\t\tconst decipher = createDecipheriv('aes-256-gcm', key, iv, { authTagLength: TAG_LENGTH })\n\t\t\tdecipher.setAAD(Buffer.from(aad, 'utf8'))\n\t\t\tdecipher.setAuthTag(tag)\n\t\t\tjson = Buffer.concat([decipher.update(ciphertext), decipher.final()]).toString('utf8')\n\t\t} catch {\n\t\t\t// GCM auth failed for this candidate; try the next\n\t\t\tcontinue\n\t\t}\n\t\t// Auth succeeded: a JSON parse failure is non-retryable corruption, not an\n\t\t// auth failure. Do not fall through to the next candidate or the final throw.\n\t\ttry {\n\t\t\treturn JSON.parse(json)\n\t\t} catch (cause) {\n\t\t\tthrow new CorruptPlaintextError(keyId, cause)\n\t\t}\n\t}\n\tthrow new AuthenticationFailedError(keyId)\n}\n"],"mappings":";;AAEA,MAAa,cAAc;;AAE3B,MAAM,YAAY;AAClB,MAAM,aAAa;AACnB,MAAM,kBAAkB;AAExB,IAAa,2BAAb,cAA8C,MAAM;CACnD,YAAY,QAAgB;EAC3B,MAAM,4CAA4C,QAAQ;EAC1D,KAAK,OAAO;CACb;AACD;AAEA,IAAa,oBAAb,cAAuC,MAAM;CAC5C;CACA,YAAY,OAAe;EAC1B,MAAM,mDAAmD,MAAM,EAAE;EACjE,KAAK,OAAO;EACZ,KAAK,QAAQ;CACd;AACD;AAEA,IAAa,4BAAb,cAA+C,MAAM;CACpD;CACA,YAAY,OAAe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,OAAO,WAAW;CACjD,MAAM,MAAM,OAAO,KAAK,QAAQ,WAAW;CAC3C,IAAI,GAAG,WAAW,WACjB,MAAM,IAAI,yBAAyB,cAAc,UAAU,OAAO;CAEnE,IAAI,IAAI,WAAW,YAClB,MAAM,IAAI,yBAAyB,eAAe,WAAW,OAAO;CAErE,IAAI,WAAW,WAAW,GACzB,MAAM,IAAI,yBAAyB,kBAAkB;CAEtD,OAAO;EAAE;EAAY;EAAI;EAAO;CAAI;AACrC;;;;;;;;AASA,MAAa,YAAY,UAAoC;CAC5D,IAAI,OAAO,UAAU,UACpB,OAAO;CAER,IAAI;EACH,UAAU,KAAK;EACf,OAAO;CACR,QAAQ;EACP,OAAO;CACR;AACD;;;;;;;;AASA,MAAa,UACZ,OACA,UACA,kBACa;CACb,MAAM,EAAE,YAAY,IAAI,OAAO,QAAQ,UAAU,KAAK;CACtD,MAAM,MAAM,SAAS,IAAI,KAAK;CAC9B,IAAI,CAAC,KACJ,MAAM,IAAI,kBAAkB,KAAK;CAElC,KAAK,MAAM,OAAO,eAAe;EAChC,IAAI;EACJ,IAAI;GACH,MAAM,WAAW,iBAAiB,eAAe,KAAK,IAAI,EAAE,eAAe,WAAW,CAAC;GACvF,SAAS,OAAO,OAAO,KAAK,KAAK,MAAM,CAAC;GACxC,SAAS,WAAW,GAAG;GACvB,OAAO,OAAO,OAAO,CAAC,SAAS,OAAO,UAAU,GAAG,SAAS,MAAM,CAAC,CAAC,EAAE,SAAS,MAAM;EACtF,QAAQ;GAEP;EACD;EAGA,IAAI;GACH,OAAO,KAAK,MAAM,IAAI;EACvB,SAAS,OAAO;GACf,MAAM,IAAI,sBAAsB,OAAO,KAAK;EAC7C;CACD;CACA,MAAM,IAAI,0BAA0B,KAAK;AAC1C"}
@@ -0,0 +1,15 @@
1
+ import { EncryptedFieldOptions, EncryptedSourceField } from "./types.js";
2
+ import { Field } from "payload";
3
+
4
+ //#region src/fields/encrypted/encryptedField.d.ts
5
+ /**
6
+ * Wraps a Payload field config (text, textarea, email, number, checkbox,
7
+ * date, select, radio, code, json, point, richText) in transparent AES-256-GCM
8
+ * encryption at rest. Returns `[storedField]`, or `[storedField, bidxField]`
9
+ * when `queryable` adds a blind-index sibling; richText returns
10
+ * `[virtualEditorField, ciphertextField]`. Spread into `fields: [...]`.
11
+ */
12
+ declare const encryptedField: (source: EncryptedSourceField, options?: EncryptedFieldOptions) => Field[];
13
+ //#endregion
14
+ export { encryptedField };
15
+ //# sourceMappingURL=encryptedField.d.ts.map
@@ -0,0 +1,187 @@
1
+ import { validateKeysConfig } from "./crypto/keys.js";
2
+ import { FIELDS_CUSTOM_KEY } from "./types.js";
3
+ import { makeAfterReadHook, makeBeforeChangeHook, makeRichTextCiphertextHook, makeRichTextDecryptHook, makeRichTextSealHook, makeRichTextValidate } from "./hooks.js";
4
+ import { clampMaskDots } from "./maskDots.js";
5
+ import { typescriptSchemaFor } from "./typescriptSchema.js";
6
+ import { makeComposedValidate, makeEffectiveValidator } from "./validators.js";
7
+ //#region src/fields/encrypted/encryptedField.ts
8
+ /** Admin keys forwarded to the client patch so native components render correctly. */
9
+ const PATCH_ADMIN_KEYS = [
10
+ "autoComplete",
11
+ "date",
12
+ "editorOptions",
13
+ "language",
14
+ "placeholder",
15
+ "rows",
16
+ "step"
17
+ ];
18
+ /**
19
+ * Field types whose plaintext is a single scalar the blind index can key on.
20
+ * Blind indexes HMAC a normalized string/number; non-scalar values (objects,
21
+ * tuples, arrays, booleans) have no meaningful equality index, so queryable is
22
+ * rejected for them at the factory (complements the crypto-layer bidx guard).
23
+ */
24
+ const QUERYABLE_SOURCE_TYPES = new Set([
25
+ "email",
26
+ "number",
27
+ "text"
28
+ ]);
29
+ const buildFieldPatch = (source) => {
30
+ const patch = {
31
+ admin: {},
32
+ type: source.type
33
+ };
34
+ if ("hasMany" in source && source.hasMany === true) patch.hasMany = true;
35
+ if ("options" in source) patch.options = source.options.map((option) => {
36
+ if (typeof option === "string") return {
37
+ label: option,
38
+ value: option
39
+ };
40
+ if (typeof option.label !== "string") throw new Error(`@10x-media/fields: encryptedField '${source.name}': option labels must be plain strings (labels travel to the admin client via clientProps)`);
41
+ return {
42
+ label: option.label,
43
+ value: option.value
44
+ };
45
+ });
46
+ const admin = source.admin ?? {};
47
+ for (const key of PATCH_ADMIN_KEYS) if (admin[key] !== void 0) patch.admin[key] = admin[key];
48
+ return patch;
49
+ };
50
+ /**
51
+ * Emits the two-field pair for an encrypted richText source: a real, virtual
52
+ * (never persisted) richText field carrying the app's full editor for editing,
53
+ * synced by hooks to a hidden ciphertext text sibling that holds the data at
54
+ * rest. A `type:'text'` field cannot trigger Payload's richText schema/import-map
55
+ * pipeline, so a real richText field is required for full node parity; `virtual`
56
+ * keeps its plaintext out of both DB adapters (they skip virtual fields).
57
+ */
58
+ const buildRichTextFields = (args) => {
59
+ const { marker, protection, source } = args;
60
+ const storedName = `${source.name}_encrypted`;
61
+ const sourceAdmin = source.admin ?? {};
62
+ return [{
63
+ ...source,
64
+ admin: {
65
+ ...sourceAdmin,
66
+ components: {
67
+ ...sourceAdmin.components,
68
+ ...protection === "masked" ? { Field: {
69
+ path: "@10x-media/fields/rsc#ProtectedRichText",
70
+ serverProps: { protection }
71
+ } } : {}
72
+ },
73
+ readOnly: false
74
+ },
75
+ hooks: {
76
+ ...source.hooks,
77
+ afterRead: [makeRichTextDecryptHook(marker, storedName), ...source.hooks?.afterRead ?? []],
78
+ beforeChange: [...source.hooks?.beforeChange ?? [], makeRichTextSealHook(marker, storedName)]
79
+ },
80
+ type: "richText",
81
+ validate: makeRichTextValidate(),
82
+ virtual: true
83
+ }, {
84
+ name: storedName,
85
+ type: "text",
86
+ admin: {
87
+ disableListColumn: true,
88
+ disableListFilter: true,
89
+ hidden: true
90
+ },
91
+ custom: { [FIELDS_CUSTOM_KEY]: { encrypted: marker } },
92
+ hooks: { beforeChange: [makeRichTextCiphertextHook(marker)] },
93
+ ...marker.localized ? { localized: true } : {}
94
+ }];
95
+ };
96
+ /**
97
+ * Wraps a Payload field config (text, textarea, email, number, checkbox,
98
+ * date, select, radio, code, json, point, richText) in transparent AES-256-GCM
99
+ * encryption at rest. Returns `[storedField]`, or `[storedField, bidxField]`
100
+ * when `queryable` adds a blind-index sibling; richText returns
101
+ * `[virtualEditorField, ciphertextField]`. Spread into `fields: [...]`.
102
+ */
103
+ const encryptedField = (source, options = {}) => {
104
+ const { keys, maskDots: maskDotsOption, onDecryptFailure, overrides, protection = "masked", queryable = false } = options;
105
+ const maskDots = clampMaskDots(maskDotsOption);
106
+ if (keys) validateKeysConfig(keys);
107
+ const hasMany = "hasMany" in source && source.hasMany === true;
108
+ const unique = "unique" in source && source.unique === true;
109
+ if (queryable && hasMany) throw new Error(`@10x-media/fields: encryptedField '${source.name}': queryable is not supported with hasMany`);
110
+ if (queryable && !QUERYABLE_SOURCE_TYPES.has(source.type)) throw new Error(`@10x-media/fields: encryptedField '${source.name}': queryable is only supported for text, email, and number fields (the blind index requires a scalar value; '${source.type}' is not scalar)`);
111
+ if (unique && !queryable) throw new Error(`@10x-media/fields: encryptedField '${source.name}': unique requires queryable: true (uniqueness is enforced on the blind index; every ciphertext is unique by construction)`);
112
+ const marker = {
113
+ bidxName: queryable ? `${source.name}_bidx` : void 0,
114
+ fieldName: source.name,
115
+ hasMany,
116
+ keys,
117
+ localized: "localized" in source && source.localized === true,
118
+ normalize: source.type === "email" ? "email" : "standard",
119
+ onDecryptFailure,
120
+ queryable,
121
+ sourceType: source.type
122
+ };
123
+ if (source.type === "richText") return buildRichTextFields({
124
+ marker,
125
+ protection,
126
+ source
127
+ });
128
+ const effective = makeEffectiveValidator(source);
129
+ const fieldPatch = buildFieldPatch(source);
130
+ const sourceAdmin = source.admin;
131
+ const { defaultValue: _defaultValue, editor: _editor, hooks: sourceHooks, index: _index, max: _max, maxLength: _maxLength, min: _min, minLength: _minLength, options: _options, typescriptSchema: _ts, unique: _unique, validate: _validate, ...rest } = source;
132
+ let stored = {
133
+ ...rest,
134
+ type: "text",
135
+ ...hasMany ? { hasMany: true } : {},
136
+ admin: {
137
+ ...sourceAdmin,
138
+ ...queryable ? {} : { disableListFilter: true },
139
+ components: {
140
+ ...sourceAdmin?.components ?? {},
141
+ Field: {
142
+ clientProps: {
143
+ componentKey: source.type,
144
+ fieldPatch,
145
+ maskDots,
146
+ protection
147
+ },
148
+ path: "@10x-media/fields/client#ProtectedField"
149
+ },
150
+ ...protection === "masked" ? { Cell: {
151
+ clientProps: { maskDots },
152
+ path: "@10x-media/fields/rsc#ProtectedCell"
153
+ } } : {}
154
+ }
155
+ },
156
+ custom: {
157
+ ...source.custom,
158
+ [FIELDS_CUSTOM_KEY]: { encrypted: marker }
159
+ },
160
+ hooks: {
161
+ ...sourceHooks,
162
+ afterRead: [makeAfterReadHook(marker), ...sourceHooks?.afterRead ?? []],
163
+ beforeChange: [...sourceHooks?.beforeChange ?? [], makeBeforeChangeHook(marker)]
164
+ },
165
+ typescriptSchema: typescriptSchemaFor(source),
166
+ validate: makeComposedValidate(effective)
167
+ };
168
+ if (overrides) stored = overrides({ field: stored });
169
+ if (!queryable) return [stored];
170
+ const bidx = {
171
+ name: marker.bidxName,
172
+ type: "text",
173
+ admin: {
174
+ disableListColumn: true,
175
+ disableListFilter: true,
176
+ hidden: true
177
+ },
178
+ index: true,
179
+ ...marker.localized ? { localized: true } : {},
180
+ ...unique ? { unique: true } : {}
181
+ };
182
+ return [stored, bidx];
183
+ };
184
+ //#endregion
185
+ export { encryptedField };
186
+
187
+ //# sourceMappingURL=encryptedField.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"encryptedField.js","names":[],"sources":["../../../src/fields/encrypted/encryptedField.ts"],"sourcesContent":["import type { Field, RichTextField, TextField } from 'payload'\nimport { validateKeysConfig } from './crypto/keys'\nimport {\n\tmakeAfterReadHook,\n\tmakeBeforeChangeHook,\n\tmakeRichTextCiphertextHook,\n\tmakeRichTextDecryptHook,\n\tmakeRichTextSealHook,\n\tmakeRichTextValidate,\n} from './hooks'\nimport { clampMaskDots } from './maskDots'\nimport {\n\ttype EncryptedFieldMarker,\n\ttype EncryptedFieldOptions,\n\ttype EncryptedFieldPatch,\n\ttype EncryptedProtection,\n\ttype EncryptedSourceField,\n\ttype EncryptedSourceType,\n\tFIELDS_CUSTOM_KEY,\n} from './types'\nimport { typescriptSchemaFor } from './typescriptSchema'\nimport { makeComposedValidate, makeEffectiveValidator } from './validators'\n\n/** Admin keys forwarded to the client patch so native components render correctly. */\nconst PATCH_ADMIN_KEYS = [\n\t'autoComplete',\n\t'date',\n\t'editorOptions',\n\t'language',\n\t'placeholder',\n\t'rows',\n\t'step',\n] as const\n\n/**\n * Field types whose plaintext is a single scalar the blind index can key on.\n * Blind indexes HMAC a normalized string/number; non-scalar values (objects,\n * tuples, arrays, booleans) have no meaningful equality index, so queryable is\n * rejected for them at the factory (complements the crypto-layer bidx guard).\n */\nconst QUERYABLE_SOURCE_TYPES: ReadonlySet<EncryptedSourceType> = new Set([\n\t'email',\n\t'number',\n\t'text',\n])\n\nconst buildFieldPatch = (source: EncryptedSourceField): EncryptedFieldPatch => {\n\tconst patch: EncryptedFieldPatch = { admin: {}, type: source.type }\n\tif ('hasMany' in source && source.hasMany === true) {\n\t\tpatch.hasMany = true\n\t}\n\tif ('options' in source) {\n\t\tpatch.options = source.options.map((option) => {\n\t\t\tif (typeof option === 'string') {\n\t\t\t\treturn { label: option, value: option }\n\t\t\t}\n\t\t\tif (typeof option.label !== 'string') {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`@10x-media/fields: encryptedField '${source.name}': option labels must be plain strings (labels travel to the admin client via clientProps)`\n\t\t\t\t)\n\t\t\t}\n\t\t\treturn { label: option.label, value: option.value }\n\t\t})\n\t}\n\tconst admin = (source.admin ?? {}) as Record<string, unknown>\n\tfor (const key of PATCH_ADMIN_KEYS) {\n\t\tif (admin[key] !== undefined) {\n\t\t\t;(patch.admin as Record<string, unknown>)[key] = admin[key]\n\t\t}\n\t}\n\treturn patch\n}\n\n/**\n * Emits the two-field pair for an encrypted richText source: a real, virtual\n * (never persisted) richText field carrying the app's full editor for editing,\n * synced by hooks to a hidden ciphertext text sibling that holds the data at\n * rest. A `type:'text'` field cannot trigger Payload's richText schema/import-map\n * pipeline, so a real richText field is required for full node parity; `virtual`\n * keeps its plaintext out of both DB adapters (they skip virtual fields).\n */\nconst buildRichTextFields = (args: {\n\tmarker: EncryptedFieldMarker\n\tprotection: EncryptedProtection\n\tsource: RichTextField\n}): Field[] => {\n\tconst { marker, protection, source } = args\n\tconst storedName = `${source.name}_encrypted`\n\tconst sourceAdmin = source.admin ?? {}\n\tconst virtual: RichTextField = {\n\t\t...source,\n\t\t// editor is inherited from config.editor (or source.editor if pinned) so the\n\t\t// app's complete node set mounts; readOnly:false is required or sanitize\n\t\t// forces a virtual affectsData field readOnly.\n\t\tadmin: {\n\t\t\t...sourceAdmin,\n\t\t\tcomponents: {\n\t\t\t\t...sourceAdmin.components,\n\t\t\t\t...(protection === 'masked'\n\t\t\t\t\t? {\n\t\t\t\t\t\t\tField: {\n\t\t\t\t\t\t\t\tpath: '@10x-media/fields/rsc#ProtectedRichText',\n\t\t\t\t\t\t\t\tserverProps: { protection },\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t}\n\t\t\t\t\t: {}),\n\t\t\t},\n\t\t\treadOnly: false,\n\t\t},\n\t\thooks: {\n\t\t\t...source.hooks,\n\t\t\tafterRead: [makeRichTextDecryptHook(marker, storedName), ...(source.hooks?.afterRead ?? [])],\n\t\t\tbeforeChange: [\n\t\t\t\t...(source.hooks?.beforeChange ?? []),\n\t\t\t\tmakeRichTextSealHook(marker, storedName),\n\t\t\t],\n\t\t},\n\t\ttype: 'richText',\n\t\tvalidate: makeRichTextValidate(),\n\t\tvirtual: true,\n\t}\n\tconst ciphertext: TextField = {\n\t\tname: storedName,\n\t\ttype: 'text',\n\t\t// admin.hidden (not top-level hidden) keeps the value readable by the virtual\n\t\t// field's decrypt hook; top-level hidden strips it early in afterRead and\n\t\t// races the decrypt read.\n\t\tadmin: { disableListColumn: true, disableListFilter: true, hidden: true },\n\t\tcustom: { [FIELDS_CUSTOM_KEY]: { encrypted: marker } },\n\t\thooks: { beforeChange: [makeRichTextCiphertextHook(marker)] },\n\t\t...(marker.localized ? { localized: true } : {}),\n\t}\n\treturn [virtual, ciphertext]\n}\n\n/**\n * Wraps a Payload field config (text, textarea, email, number, checkbox,\n * date, select, radio, code, json, point, richText) in transparent AES-256-GCM\n * encryption at rest. Returns `[storedField]`, or `[storedField, bidxField]`\n * when `queryable` adds a blind-index sibling; richText returns\n * `[virtualEditorField, ciphertextField]`. Spread into `fields: [...]`.\n */\nexport const encryptedField = (\n\tsource: EncryptedSourceField,\n\toptions: EncryptedFieldOptions = {}\n): Field[] => {\n\tconst {\n\t\tkeys,\n\t\tmaskDots: maskDotsOption,\n\t\tonDecryptFailure,\n\t\toverrides,\n\t\tprotection = 'masked',\n\t\tqueryable = false,\n\t} = options\n\tconst maskDots = clampMaskDots(maskDotsOption)\n\tif (keys) {\n\t\tvalidateKeysConfig(keys)\n\t}\n\tconst hasMany = 'hasMany' in source && source.hasMany === true\n\tconst unique = 'unique' in source && source.unique === true\n\tif (queryable && hasMany) {\n\t\tthrow new Error(\n\t\t\t`@10x-media/fields: encryptedField '${source.name}': queryable is not supported with hasMany`\n\t\t)\n\t}\n\tif (queryable && !QUERYABLE_SOURCE_TYPES.has(source.type)) {\n\t\tthrow new Error(\n\t\t\t`@10x-media/fields: encryptedField '${source.name}': queryable is only supported for text, email, and number fields (the blind index requires a scalar value; '${source.type}' is not scalar)`\n\t\t)\n\t}\n\tif (unique && !queryable) {\n\t\tthrow new Error(\n\t\t\t`@10x-media/fields: encryptedField '${source.name}': unique requires queryable: true (uniqueness is enforced on the blind index; every ciphertext is unique by construction)`\n\t\t)\n\t}\n\n\tconst marker: EncryptedFieldMarker = {\n\t\tbidxName: queryable ? `${source.name}_bidx` : undefined,\n\t\tfieldName: source.name,\n\t\thasMany,\n\t\tkeys,\n\t\tlocalized: 'localized' in source && source.localized === true,\n\t\tnormalize: source.type === 'email' ? 'email' : 'standard',\n\t\tonDecryptFailure,\n\t\tqueryable,\n\t\tsourceType: source.type,\n\t}\n\n\t// richText returns a virtual editor field plus a hidden ciphertext sibling.\n\t// `overrides` targets the scalar stored text column shape, so it does not apply\n\t// to the richText editor field and is intentionally skipped here.\n\tif (source.type === 'richText') {\n\t\treturn buildRichTextFields({ marker, protection, source })\n\t}\n\n\tconst effective = makeEffectiveValidator(source)\n\tconst fieldPatch = buildFieldPatch(source)\n\t// `source` is a union of 12 field types, so `source.admin` (and its\n\t// `components`) carries the union of every field's admin shape. Narrow to the\n\t// stored text field's admin type once here so the passthrough spreads below\n\t// typecheck against the correct target instead of the incompatible union.\n\tconst sourceAdmin = source.admin as TextField['admin']\n\n\t// Spread keeps admin passthrough (description, width, condition, readOnly,\n\t// position, custom labels) and access control on the stored field. Stripped:\n\t// hooks/validate/typescriptSchema/index/unique/editor (rebuilt or moved to the\n\t// bidx sibling); defaultValue (a static default emits a PLAINTEXT column\n\t// default in drizzle, i.e. plaintext at rest on an INSERT that omits the\n\t// column); and source-type-only constraints (options/min/max/min-maxLength)\n\t// which are inert on a text column and already enforced on plaintext by the\n\t// effective validator.\n\tconst {\n\t\tdefaultValue: _defaultValue,\n\t\teditor: _editor,\n\t\thooks: sourceHooks,\n\t\tindex: _index,\n\t\tmax: _max,\n\t\tmaxLength: _maxLength,\n\t\tmin: _min,\n\t\tminLength: _minLength,\n\t\toptions: _options,\n\t\ttypescriptSchema: _ts,\n\t\tunique: _unique,\n\t\tvalidate: _validate,\n\t\t...rest\n\t} = source as EncryptedSourceField & Record<string, unknown>\n\n\tlet stored: TextField = {\n\t\t...(rest as unknown as TextField),\n\t\ttype: 'text',\n\t\t...(hasMany ? { hasMany: true } : {}),\n\t\tadmin: {\n\t\t\t...sourceAdmin,\n\t\t\t// A non-queryable encrypted field can only ever filter its ciphertext\n\t\t\t// column (matching nothing), so keep it out of the list filter UI. A\n\t\t\t// queryable field stays filterable; the where-rewrite maps it to the\n\t\t\t// blind index.\n\t\t\t...(queryable ? {} : { disableListFilter: true }),\n\t\t\tcomponents: {\n\t\t\t\t...(sourceAdmin?.components ?? {}),\n\t\t\t\tField: {\n\t\t\t\t\tclientProps: { componentKey: source.type, fieldPatch, maskDots, protection },\n\t\t\t\t\tpath: '@10x-media/fields/client#ProtectedField',\n\t\t\t\t},\n\t\t\t\t...(protection === 'masked'\n\t\t\t\t\t? { Cell: { clientProps: { maskDots }, path: '@10x-media/fields/rsc#ProtectedCell' } }\n\t\t\t\t\t: {}),\n\t\t\t},\n\t\t},\n\t\tcustom: { ...source.custom, [FIELDS_CUSTOM_KEY]: { encrypted: marker } },\n\t\thooks: {\n\t\t\t...sourceHooks,\n\t\t\tafterRead: [makeAfterReadHook(marker), ...(sourceHooks?.afterRead ?? [])],\n\t\t\tbeforeChange: [...(sourceHooks?.beforeChange ?? []), makeBeforeChangeHook(marker)],\n\t\t},\n\t\ttypescriptSchema: typescriptSchemaFor(source),\n\t\tvalidate: makeComposedValidate(effective),\n\t}\n\n\tif (overrides) {\n\t\tstored = overrides({ field: stored })\n\t}\n\n\tif (!queryable) {\n\t\treturn [stored]\n\t}\n\n\t// admin.hidden (not top-level `hidden: true`) keeps the blind index in the\n\t// flattened schema so Payload's query-path validation grants it read\n\t// permission and the where-rewrite can target it; top-level hidden makes a\n\t// rewritten `equals` query fail with a 403. The keyed hash is stripped from\n\t// API responses by the plugin's collection afterRead (see withEncryptedQueryRewrite)\n\t// so the index value never leaves the server; exposing it lets a reader see\n\t// which rows share a value.\n\tconst bidx: TextField = {\n\t\tname: marker.bidxName as string,\n\t\ttype: 'text',\n\t\tadmin: { disableListColumn: true, disableListFilter: true, hidden: true },\n\t\tindex: true,\n\t\t...(marker.localized ? { localized: true } : {}),\n\t\t...(unique ? { unique: true } : {}),\n\t}\n\treturn [stored, bidx]\n}\n"],"mappings":";;;;;;;;AAwBA,MAAM,mBAAmB;CACxB;CACA;CACA;CACA;CACA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ted/hooks.d.ts
4
+ interface DecryptFailedArgs {
5
+ cause: unknown;
6
+ field: string;
7
+ keyId: string | undefined;
8
+ slug: string;
9
+ }
10
+ /** Raised on read when decryption fails and the policy is 'throw'. */
11
+ declare class DecryptFailedError extends Error {
12
+ constructor({
13
+ cause,
14
+ field,
15
+ keyId,
16
+ slug
17
+ }: DecryptFailedArgs);
18
+ }
19
+ //#endregion
20
+ export { DecryptFailedError };
21
+ //# sourceMappingURL=hooks.d.ts.map