@10x-media/fields 0.1.0-beta.0 → 0.1.0-beta.10

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 (320) hide show
  1. package/CHANGELOG.md +173 -0
  2. package/README.md +8 -4
  3. package/dist/exports/client.d.ts +10 -1
  4. package/dist/exports/client.js +9 -1
  5. package/dist/exports/color-utils.d.ts +4 -2
  6. package/dist/exports/color-utils.js +3 -1
  7. package/dist/exports/color.d.ts +5 -2
  8. package/dist/exports/color.js +4 -1
  9. package/dist/exports/encrypted.d.ts +7 -4
  10. package/dist/exports/encrypted.js +6 -3
  11. package/dist/exports/icon-adapters/radix.d.ts +2 -2
  12. package/dist/exports/icon-adapters/radix.js +2 -2
  13. package/dist/exports/icon-react.d.ts +2 -2
  14. package/dist/exports/icon.d.ts +6 -2
  15. package/dist/exports/icon.js +6 -2
  16. package/dist/exports/measurement-utils.d.ts +9 -0
  17. package/dist/exports/measurement-utils.js +8 -0
  18. package/dist/exports/measurement.d.ts +11 -0
  19. package/dist/exports/measurement.js +10 -0
  20. package/dist/exports/phone-utils.d.ts +4 -0
  21. package/dist/exports/phone-utils.js +4 -0
  22. package/dist/exports/phone.d.ts +6 -0
  23. package/dist/exports/phone.js +3 -0
  24. package/dist/exports/rsc.d.ts +5 -1
  25. package/dist/exports/rsc.js +5 -1
  26. package/dist/exports/types.d.ts +3 -2
  27. package/dist/fields/color/client/ColorField.d.ts +2 -0
  28. package/dist/fields/color/client/ColorField.js +35 -288
  29. package/dist/fields/color/client/ColorField.js.map +1 -1
  30. package/dist/fields/color/client/ColorInput.d.ts +44 -0
  31. package/dist/fields/color/client/ColorInput.js +374 -0
  32. package/dist/fields/color/client/ColorInput.js.map +1 -0
  33. package/dist/fields/color/client/ColorPickerPanel.d.ts +3 -1
  34. package/dist/fields/color/client/ColorPickerPanel.js +31 -5
  35. package/dist/fields/color/client/ColorPickerPanel.js.map +1 -1
  36. package/dist/fields/color/client/colorField.css +30 -0
  37. package/dist/fields/color/colorField.d.ts +9 -2
  38. package/dist/fields/color/colorField.js +68 -15
  39. package/dist/fields/color/colorField.js.map +1 -1
  40. package/dist/fields/color/engine/index.d.ts +2 -1
  41. package/dist/fields/color/engine/scheme.d.ts +13 -0
  42. package/dist/fields/color/engine/scheme.js +12 -0
  43. package/dist/fields/color/engine/scheme.js.map +1 -0
  44. package/dist/fields/color/options.d.ts +5 -4
  45. package/dist/fields/color/options.js.map +1 -1
  46. package/dist/fields/color/paths.d.ts +1 -0
  47. package/dist/fields/color/paths.js +32 -0
  48. package/dist/fields/color/paths.js.map +1 -0
  49. package/dist/fields/color/presetChip.js +10 -9
  50. package/dist/fields/color/presetChip.js.map +1 -1
  51. package/dist/fields/color/presetReference.d.ts +13 -0
  52. package/dist/fields/color/presetReference.js +94 -0
  53. package/dist/fields/color/presetReference.js.map +1 -0
  54. package/dist/fields/color/presetsFromArray.d.ts +30 -0
  55. package/dist/fields/color/presetsFromArray.js +58 -0
  56. package/dist/fields/color/presetsFromArray.js.map +1 -0
  57. package/dist/fields/color/presetsFromDoc.js +1 -23
  58. package/dist/fields/color/presetsFromDoc.js.map +1 -1
  59. package/dist/fields/color/resolvePresets.d.ts +2 -2
  60. package/dist/fields/color/resolvePresets.js +38 -8
  61. package/dist/fields/color/resolvePresets.js.map +1 -1
  62. package/dist/fields/color/schemeValue.js +30 -0
  63. package/dist/fields/color/schemeValue.js.map +1 -0
  64. package/dist/fields/color/server/ColorCell.js +9 -3
  65. package/dist/fields/color/server/ColorCell.js.map +1 -1
  66. package/dist/fields/color/server/colorCell.css +5 -0
  67. package/dist/fields/color/valueIssue.js +23 -0
  68. package/dist/fields/color/valueIssue.js.map +1 -0
  69. package/dist/fields/encrypted/boot.js +2 -1
  70. package/dist/fields/encrypted/boot.js.map +1 -1
  71. package/dist/fields/encrypted/components/EncryptedInput.js +4 -1
  72. package/dist/fields/encrypted/components/EncryptedInput.js.map +1 -1
  73. package/dist/fields/encrypted/components/EncryptedTextarea.js +6 -2
  74. package/dist/fields/encrypted/components/EncryptedTextarea.js.map +1 -1
  75. package/dist/fields/encrypted/components/ProtectedCell.d.ts +15 -6
  76. package/dist/fields/encrypted/components/ProtectedCell.js +37 -8
  77. package/dist/fields/encrypted/components/ProtectedCell.js.map +1 -1
  78. package/dist/fields/encrypted/components/ProtectedField.css +134 -39
  79. package/dist/fields/encrypted/components/ProtectedField.d.ts +3 -0
  80. package/dist/fields/encrypted/components/ProtectedField.js +14 -0
  81. package/dist/fields/encrypted/components/ProtectedField.js.map +1 -1
  82. package/dist/fields/encrypted/components/WriteOnlyActions.js +65 -0
  83. package/dist/fields/encrypted/components/WriteOnlyActions.js.map +1 -0
  84. package/dist/fields/encrypted/components/WriteOnlyField.js +286 -0
  85. package/dist/fields/encrypted/components/WriteOnlyField.js.map +1 -0
  86. package/dist/fields/encrypted/components/writeOnlyIntent.js +69 -0
  87. package/dist/fields/encrypted/components/writeOnlyIntent.js.map +1 -0
  88. package/dist/fields/encrypted/crypto/wire.d.ts +10 -1
  89. package/dist/fields/encrypted/crypto/wire.js +1 -1
  90. package/dist/fields/encrypted/encryptedField.js +63 -6
  91. package/dist/fields/encrypted/encryptedField.js.map +1 -1
  92. package/dist/fields/encrypted/generateSecret.d.ts +10 -0
  93. package/dist/fields/encrypted/generateSecret.js +41 -0
  94. package/dist/fields/encrypted/generateSecret.js.map +1 -0
  95. package/dist/fields/encrypted/hint.js +67 -0
  96. package/dist/fields/encrypted/hint.js.map +1 -0
  97. package/dist/fields/encrypted/hooks.js +59 -31
  98. package/dist/fields/encrypted/hooks.js.map +1 -1
  99. package/dist/fields/encrypted/queryRewrite.d.ts +10 -2
  100. package/dist/fields/encrypted/queryRewrite.js +34 -8
  101. package/dist/fields/encrypted/queryRewrite.js.map +1 -1
  102. package/dist/fields/encrypted/rawRead.d.ts +24 -0
  103. package/dist/fields/encrypted/rawRead.js +40 -0
  104. package/dist/fields/encrypted/rawRead.js.map +1 -0
  105. package/dist/fields/encrypted/scan.js +21 -4
  106. package/dist/fields/encrypted/scan.js.map +1 -1
  107. package/dist/fields/encrypted/types.d.ts +67 -2
  108. package/dist/fields/encrypted/types.js +8 -1
  109. package/dist/fields/encrypted/types.js.map +1 -1
  110. package/dist/fields/encrypted/utils/decryptAllData.js +2 -2
  111. package/dist/fields/encrypted/utils/decryptAllData.js.map +1 -1
  112. package/dist/fields/encrypted/utils/decryptFieldValue.d.ts +30 -0
  113. package/dist/fields/encrypted/utils/decryptFieldValue.js +56 -0
  114. package/dist/fields/encrypted/utils/decryptFieldValue.js.map +1 -0
  115. package/dist/fields/encrypted/utils/readEncryptedField.d.ts +51 -0
  116. package/dist/fields/encrypted/utils/readEncryptedField.js +96 -0
  117. package/dist/fields/encrypted/utils/readEncryptedField.js.map +1 -0
  118. package/dist/fields/icon/adapters/lucide/generated/manifest.js.map +1 -1
  119. package/dist/fields/icon/adapters/lucide/generated/nodes.js.map +1 -1
  120. package/dist/fields/icon/adapters/radix/adapter.js +7 -0
  121. package/dist/fields/icon/adapters/radix/adapter.js.map +1 -1
  122. package/dist/fields/icon/adapters/radix/client.d.ts +3 -2
  123. package/dist/fields/icon/adapters/radix/client.js +3 -2
  124. package/dist/fields/icon/adapters/radix/client.js.map +1 -1
  125. package/dist/fields/icon/adapters/radix/generated/manifest.js.map +1 -1
  126. package/dist/fields/icon/adapters/radix/generated/nodes.js +3625 -0
  127. package/dist/fields/icon/adapters/radix/generated/nodes.js.map +1 -0
  128. package/dist/fields/icon/adapters/tabler/generated/manifest.js.map +1 -1
  129. package/dist/fields/icon/adapters/tabler/generated/nodes.js.map +1 -1
  130. package/dist/fields/icon/client/DrawerGlyph.js +34 -17
  131. package/dist/fields/icon/client/DrawerGlyph.js.map +1 -1
  132. package/dist/fields/icon/client/IconDrawerContent.js +9 -45
  133. package/dist/fields/icon/client/IconDrawerContent.js.map +1 -1
  134. package/dist/fields/icon/client/IconFieldClient.d.ts +7 -0
  135. package/dist/fields/icon/client/IconFieldClient.js +15 -7
  136. package/dist/fields/icon/client/IconFieldClient.js.map +1 -1
  137. package/dist/fields/icon/client/IconGridCell.js +67 -0
  138. package/dist/fields/icon/client/IconGridCell.js.map +1 -0
  139. package/dist/fields/icon/client/icon-field.css +12 -2
  140. package/dist/fields/icon/codegen/emit.js +5 -4
  141. package/dist/fields/icon/codegen/emit.js.map +1 -1
  142. package/dist/fields/icon/codegen/generate.js +32 -6
  143. package/dist/fields/icon/codegen/generate.js.map +1 -1
  144. package/dist/fields/icon/layers/coalesce.js +41 -0
  145. package/dist/fields/icon/layers/coalesce.js.map +1 -0
  146. package/dist/fields/icon/layers/manifestCache.d.ts +6 -0
  147. package/dist/fields/icon/layers/manifestCache.js +49 -0
  148. package/dist/fields/icon/layers/manifestCache.js.map +1 -0
  149. package/dist/fields/icon/layers/resolve.d.ts +20 -0
  150. package/dist/fields/icon/layers/resolve.js +63 -0
  151. package/dist/fields/icon/layers/resolve.js.map +1 -0
  152. package/dist/fields/icon/layers/upload.d.ts +52 -0
  153. package/dist/fields/icon/layers/upload.js +116 -0
  154. package/dist/fields/icon/layers/upload.js.map +1 -0
  155. package/dist/fields/icon/plugin.js +24 -0
  156. package/dist/fields/icon/plugin.js.map +1 -1
  157. package/dist/fields/icon/react/createIcon.d.ts +5 -0
  158. package/dist/fields/icon/react/createIcon.js +22 -4
  159. package/dist/fields/icon/react/createIcon.js.map +1 -1
  160. package/dist/fields/icon/react/createRscIcon.js +22 -1
  161. package/dist/fields/icon/react/createRscIcon.js.map +1 -1
  162. package/dist/fields/icon/react/resolveRendered.js +21 -0
  163. package/dist/fields/icon/react/resolveRendered.js.map +1 -0
  164. package/dist/fields/icon/react/types.d.ts +15 -1
  165. package/dist/fields/icon/rsc/IconCell.d.ts +2 -2
  166. package/dist/fields/icon/rsc/IconCell.js +12 -5
  167. package/dist/fields/icon/rsc/IconCell.js.map +1 -1
  168. package/dist/fields/icon/rsc/IconFieldServer.js +16 -2
  169. package/dist/fields/icon/rsc/IconFieldServer.js.map +1 -1
  170. package/dist/fields/icon/rsc/IconLibrarySelectServer.js +1 -1
  171. package/dist/fields/icon/rsc/IconLibrarySelectServer.js.map +1 -1
  172. package/dist/fields/icon/server/endpoint.d.ts +12 -0
  173. package/dist/fields/icon/server/endpoint.js +52 -0
  174. package/dist/fields/icon/server/endpoint.js.map +1 -0
  175. package/dist/fields/icon/server/manifestCache.js +9 -4
  176. package/dist/fields/icon/server/manifestCache.js.map +1 -1
  177. package/dist/fields/icon/server/resolveIconMeta.js +31 -0
  178. package/dist/fields/icon/server/resolveIconMeta.js.map +1 -0
  179. package/dist/fields/icon/server/validate.js +5 -2
  180. package/dist/fields/icon/server/validate.js.map +1 -1
  181. package/dist/fields/icon/shared/adapterComponents.d.ts +3 -2
  182. package/dist/fields/icon/shared/iconLabel.js +26 -0
  183. package/dist/fields/icon/shared/iconLabel.js.map +1 -0
  184. package/dist/fields/measurement/client/MeasurementCell.d.ts +18 -0
  185. package/dist/fields/measurement/client/MeasurementCell.js +47 -0
  186. package/dist/fields/measurement/client/MeasurementCell.js.map +1 -0
  187. package/dist/fields/measurement/client/MeasurementField.d.ts +13 -0
  188. package/dist/fields/measurement/client/MeasurementField.js +70 -0
  189. package/dist/fields/measurement/client/MeasurementField.js.map +1 -0
  190. package/dist/fields/measurement/client/MeasurementInput.d.ts +42 -0
  191. package/dist/fields/measurement/client/MeasurementInput.js +327 -0
  192. package/dist/fields/measurement/client/MeasurementInput.js.map +1 -0
  193. package/dist/fields/measurement/client/MeasurementUnitsProvider.d.ts +24 -0
  194. package/dist/fields/measurement/client/MeasurementUnitsProvider.js +61 -0
  195. package/dist/fields/measurement/client/MeasurementUnitsProvider.js.map +1 -0
  196. package/dist/fields/measurement/client/editModel.js +124 -0
  197. package/dist/fields/measurement/client/editModel.js.map +1 -0
  198. package/dist/fields/measurement/client/measurementCell.css +4 -0
  199. package/dist/fields/measurement/client/measurementField.css +215 -0
  200. package/dist/fields/measurement/client/useMeasurementModel.d.ts +19 -0
  201. package/dist/fields/measurement/client/useMeasurementModel.js +85 -0
  202. package/dist/fields/measurement/client/useMeasurementModel.js.map +1 -0
  203. package/dist/fields/measurement/engine/convert.d.ts +8 -0
  204. package/dist/fields/measurement/engine/convert.js +21 -0
  205. package/dist/fields/measurement/engine/convert.js.map +1 -0
  206. package/dist/fields/measurement/engine/format.d.ts +37 -0
  207. package/dist/fields/measurement/engine/format.js +156 -0
  208. package/dist/fields/measurement/engine/format.js.map +1 -0
  209. package/dist/fields/measurement/engine/locale.d.ts +25 -0
  210. package/dist/fields/measurement/engine/locale.js +79 -0
  211. package/dist/fields/measurement/engine/locale.js.map +1 -0
  212. package/dist/fields/measurement/engine/precision.d.ts +34 -0
  213. package/dist/fields/measurement/engine/precision.js +63 -0
  214. package/dist/fields/measurement/engine/precision.js.map +1 -0
  215. package/dist/fields/measurement/engine/registry.d.ts +55 -0
  216. package/dist/fields/measurement/engine/registry.js +117 -0
  217. package/dist/fields/measurement/engine/registry.js.map +1 -0
  218. package/dist/fields/measurement/engine/units.d.ts +178 -0
  219. package/dist/fields/measurement/engine/units.js +198 -0
  220. package/dist/fields/measurement/engine/units.js.map +1 -0
  221. package/dist/fields/measurement/measurementField.d.ts +17 -0
  222. package/dist/fields/measurement/measurementField.js +139 -0
  223. package/dist/fields/measurement/measurementField.js.map +1 -0
  224. package/dist/fields/measurement/options.d.ts +76 -0
  225. package/dist/fields/measurement/options.js +9 -0
  226. package/dist/fields/measurement/options.js.map +1 -0
  227. package/dist/fields/measurement/presets.d.ts +117 -0
  228. package/dist/fields/measurement/presets.js +136 -0
  229. package/dist/fields/measurement/presets.js.map +1 -0
  230. package/dist/fields/measurement/server/MeasurementCellServer.d.ts +21 -0
  231. package/dist/fields/measurement/server/MeasurementCellServer.js +53 -0
  232. package/dist/fields/measurement/server/MeasurementCellServer.js.map +1 -0
  233. package/dist/fields/measurement/server/MeasurementFieldServer.d.ts +16 -0
  234. package/dist/fields/measurement/server/MeasurementFieldServer.js +45 -0
  235. package/dist/fields/measurement/server/MeasurementFieldServer.js.map +1 -0
  236. package/dist/fields/measurement/server/getUserUnits.js +39 -0
  237. package/dist/fields/measurement/server/getUserUnits.js.map +1 -0
  238. package/dist/fields/measurement/server/resolvePrecisionSafe.js +24 -0
  239. package/dist/fields/measurement/server/resolvePrecisionSafe.js.map +1 -0
  240. package/dist/fields/measurement/server/resolveRegistryDefault.js +26 -0
  241. package/dist/fields/measurement/server/resolveRegistryDefault.js.map +1 -0
  242. package/dist/fields/phoneNumber/client/CountryFlag.d.ts +16 -0
  243. package/dist/fields/phoneNumber/client/CountryFlag.js +40 -0
  244. package/dist/fields/phoneNumber/client/CountryFlag.js.map +1 -0
  245. package/dist/fields/phoneNumber/client/CountryPicker.d.ts +21 -0
  246. package/dist/fields/phoneNumber/client/CountryPicker.js +255 -0
  247. package/dist/fields/phoneNumber/client/CountryPicker.js.map +1 -0
  248. package/dist/fields/phoneNumber/client/PhoneNumberField.d.ts +26 -0
  249. package/dist/fields/phoneNumber/client/PhoneNumberField.js +318 -0
  250. package/dist/fields/phoneNumber/client/PhoneNumberField.js.map +1 -0
  251. package/dist/fields/phoneNumber/client/editModel.js +86 -0
  252. package/dist/fields/phoneNumber/client/editModel.js.map +1 -0
  253. package/dist/fields/phoneNumber/client/phoneNumberField.css +305 -0
  254. package/dist/fields/phoneNumber/engine/countries.d.ts +36 -0
  255. package/dist/fields/phoneNumber/engine/countries.js +68 -0
  256. package/dist/fields/phoneNumber/engine/countries.js.map +1 -0
  257. package/dist/fields/phoneNumber/engine/draft.d.ts +13 -0
  258. package/dist/fields/phoneNumber/engine/draft.js +72 -0
  259. package/dist/fields/phoneNumber/engine/draft.js.map +1 -0
  260. package/dist/fields/phoneNumber/engine/metadata.d.ts +11 -0
  261. package/dist/fields/phoneNumber/engine/metadata.js +32 -0
  262. package/dist/fields/phoneNumber/engine/metadata.js.map +1 -0
  263. package/dist/fields/phoneNumber/engine/phone.d.ts +37 -0
  264. package/dist/fields/phoneNumber/engine/phone.js +59 -0
  265. package/dist/fields/phoneNumber/engine/phone.js.map +1 -0
  266. package/dist/fields/phoneNumber/options.d.ts +72 -0
  267. package/dist/fields/phoneNumber/options.js +37 -0
  268. package/dist/fields/phoneNumber/options.js.map +1 -0
  269. package/dist/fields/phoneNumber/phoneNumberField.d.ts +14 -0
  270. package/dist/fields/phoneNumber/phoneNumberField.js +167 -0
  271. package/dist/fields/phoneNumber/phoneNumberField.js.map +1 -0
  272. package/dist/fields/phoneNumber/server/PhoneNumberCellServer.d.ts +19 -0
  273. package/dist/fields/phoneNumber/server/PhoneNumberCellServer.js +73 -0
  274. package/dist/fields/phoneNumber/server/PhoneNumberCellServer.js.map +1 -0
  275. package/dist/fields/phoneNumber/server/PhoneNumberFieldServer.d.ts +16 -0
  276. package/dist/fields/phoneNumber/server/PhoneNumberFieldServer.js +57 -0
  277. package/dist/fields/phoneNumber/server/PhoneNumberFieldServer.js.map +1 -0
  278. package/dist/fields/phoneNumber/server/flagsEndpoint.js +51 -0
  279. package/dist/fields/phoneNumber/server/flagsEndpoint.js.map +1 -0
  280. package/dist/fields/phoneNumber/server/readPhoneOptions.js +18 -0
  281. package/dist/fields/phoneNumber/server/readPhoneOptions.js.map +1 -0
  282. package/dist/fields/phoneNumber/server/resolvePhoneOptionsSafe.js +33 -0
  283. package/dist/fields/phoneNumber/server/resolvePhoneOptionsSafe.js.map +1 -0
  284. package/dist/index.d.ts +5 -3
  285. package/dist/index.js +35 -1
  286. package/dist/index.js.map +1 -1
  287. package/dist/translations/ar.js +62 -0
  288. package/dist/translations/ar.js.map +1 -0
  289. package/dist/translations/de.js +19 -1
  290. package/dist/translations/de.js.map +1 -1
  291. package/dist/translations/en.js +19 -1
  292. package/dist/translations/en.js.map +1 -1
  293. package/dist/translations/es.js +62 -0
  294. package/dist/translations/es.js.map +1 -0
  295. package/dist/translations/fr.js +62 -0
  296. package/dist/translations/fr.js.map +1 -0
  297. package/dist/translations/id.js +62 -0
  298. package/dist/translations/id.js.map +1 -0
  299. package/dist/translations/index.d.ts +10 -1
  300. package/dist/translations/index.js +19 -1
  301. package/dist/translations/index.js.map +1 -1
  302. package/dist/translations/keys.d.ts +19 -1
  303. package/dist/translations/keys.js +20 -2
  304. package/dist/translations/keys.js.map +1 -1
  305. package/dist/translations/ko.js +62 -0
  306. package/dist/translations/ko.js.map +1 -0
  307. package/dist/translations/pt.js +62 -0
  308. package/dist/translations/pt.js.map +1 -0
  309. package/dist/translations/ru.js +62 -0
  310. package/dist/translations/ru.js.map +1 -0
  311. package/dist/translations/uk.js +62 -0
  312. package/dist/translations/uk.js.map +1 -0
  313. package/dist/translations/zh.js +62 -0
  314. package/dist/translations/zh.js.map +1 -0
  315. package/dist/types.d.ts +165 -8
  316. package/dist/utils/resolveStaticLabel.js +13 -0
  317. package/dist/utils/resolveStaticLabel.js.map +1 -0
  318. package/package.json +31 -7
  319. package/dist/fields/icon/rsc/resolveStaticLabel.js +0 -16
  320. package/dist/fields/icon/rsc/resolveStaticLabel.js.map +0 -1
@@ -1,9 +1,10 @@
1
1
  import { resolveKeys } from "./crypto/keys.js";
2
- import { ENCRYPTED_CONTEXT_KEY } from "./types.js";
2
+ import { ENCRYPTED_CONTEXT_KEY, aadScopeOf } from "./types.js";
3
3
  import { computeBidx } from "./crypto/bidx.js";
4
4
  import { getFieldsRegistry } from "../../plugin/registry.js";
5
5
  import { buildAad } from "./crypto/aad.js";
6
6
  import { isSealed, parseWire, seal, unseal } from "./crypto/wire.js";
7
+ import { makeHint } from "./hint.js";
7
8
  import { sealedArrayKey, stashPlaintext } from "./plaintextStash.js";
8
9
  //#region src/fields/encrypted/hooks.ts
9
10
  /** Raised on read when decryption fails and the policy is 'throw'. */
@@ -28,29 +29,31 @@ const operationLocale = (req) => {
28
29
  return locale;
29
30
  };
30
31
  /**
31
- * AAD binds a ciphertext to its `${slug}.${field}[.${locale}]` slot via
32
- * buildAad, which rejects any dotted component so the joined data stays
33
- * unambiguous (a dotted slug/locale would blur the cross-field binding).
32
+ * AAD binds a ciphertext to its `${scope}.${field}[.${locale}]` slot, where the
33
+ * scope is the field's pinned `aadScope` or the schema slug, via buildAad,
34
+ * which rejects any dotted component so the joined data stays unambiguous (a
35
+ * dotted scope or locale would blur the cross-field binding).
34
36
  */
35
- const sealAad = (marker, slug, req) => buildAad(marker.localized ? [
36
- slug,
37
+ const sealAad = (marker, slug, req) => {
38
+ if (marker.localized) return localeAad(marker, slug, operationLocale(req));
39
+ return buildAad([aadScopeOf(marker, slug), marker.fieldName]);
40
+ };
41
+ /** The AAD for one locale of a localized field; locale-map writes seal per entry. */
42
+ const localeAad = (marker, slug, locale) => buildAad([
43
+ aadScopeOf(marker, slug),
37
44
  marker.fieldName,
38
- operationLocale(req)
39
- ] : [slug, marker.fieldName]);
45
+ locale
46
+ ]);
40
47
  /**
41
48
  * Read-side AAD candidates. Localized fields try the request locale first,
42
49
  * then every configured locale: fallbackLocale hoisting and locale=all hook
43
50
  * execution mean the hook cannot know which locale sealed the value.
44
51
  */
45
52
  const readAadCandidates = (marker, slug, req) => {
46
- if (!marker.localized) return [buildAad([slug, marker.fieldName])];
53
+ if (!marker.localized) return [buildAad([aadScopeOf(marker, slug), marker.fieldName])];
47
54
  const codes = req.payload.config.localization ? req.payload.config.localization.localeCodes : [defaultLocale(req.payload.config)];
48
55
  const first = operationLocale(req);
49
- return [first, ...codes.filter((code) => code !== first)].map((code) => buildAad([
50
- slug,
51
- marker.fieldName,
52
- code
53
- ]));
56
+ return [first, ...codes.filter((code) => code !== first)].map((code) => localeAad(marker, slug, code));
54
57
  };
55
58
  /**
56
59
  * The active utility mode from the request context, or undefined for a normal
@@ -82,6 +85,7 @@ const makeBeforeChangeHook = (marker) => {
82
85
  if (mode === "raw") return value;
83
86
  if (mode === "decrypt") {
84
87
  if (marker.queryable && marker.bidxName) siblingData[marker.bidxName] = null;
88
+ if (marker.hintName) siblingData[marker.hintName] = null;
85
89
  return value;
86
90
  }
87
91
  const slug = aadSlug(collection, global);
@@ -105,22 +109,24 @@ const makeBeforeChangeHook = (marker) => {
105
109
  return marker.hasMany && Array.isArray(value) ? value.map(rotateOne) : rotateOne(value);
106
110
  }
107
111
  if (value === void 0) return;
108
- if (value === null) {
112
+ if (value === null || marker.writeOnly && value === "") {
109
113
  if (marker.queryable && marker.bidxName) siblingData[marker.bidxName] = null;
114
+ if (marker.hintName) siblingData[marker.hintName] = null;
110
115
  return null;
111
116
  }
112
117
  if (marker.localized && req.locale === "all" && isLocaleMap(value)) {
113
118
  const sealedMap = {};
114
- for (const [locale, localeValue] of Object.entries(value)) sealedMap[locale] = sealValueForLocale(localeValue, {
115
- aad: buildAad([
116
- slug,
117
- marker.fieldName,
118
- locale
119
- ]),
120
- hasMany: marker.hasMany,
121
- key: activeKey,
122
- keyId: ring.activeId
123
- });
119
+ const hintMap = {};
120
+ for (const [locale, localeValue] of Object.entries(value)) {
121
+ sealedMap[locale] = sealValueForLocale(localeValue, {
122
+ aad: localeAad(marker, slug, locale),
123
+ hasMany: marker.hasMany,
124
+ key: activeKey,
125
+ keyId: ring.activeId
126
+ });
127
+ if (marker.hint && !isSealed(localeValue)) hintMap[locale] = localeValue == null ? null : makeHint(localeValue, marker.hint);
128
+ }
129
+ if (marker.hintName && Object.keys(hintMap).length > 0) siblingData[marker.hintName] = hintMap;
124
130
  return sealedMap;
125
131
  }
126
132
  const aad = sealAad(marker, slug, req);
@@ -140,6 +146,7 @@ const makeBeforeChangeHook = (marker) => {
140
146
  const sealed = sealOne(value);
141
147
  stashPlaintext(req, sealed, value);
142
148
  if (marker.queryable && marker.bidxName) siblingData[marker.bidxName] = computeBidx(value, ring.indexKey, marker.normalize);
149
+ if (marker.hint && marker.hintName) siblingData[marker.hintName] = makeHint(value, marker.hint);
143
150
  return sealed;
144
151
  };
145
152
  };
@@ -196,6 +203,7 @@ const makeAfterReadHook = (marker) => {
196
203
  const { collection, context, global, req, value } = args;
197
204
  if (value === void 0 || value === null) return value;
198
205
  if (contextMode(context)) return value;
206
+ if (marker.writeOnly) return value;
199
207
  const slug = aadSlug(collection, global);
200
208
  const ring = await ringForRequest(req, marker);
201
209
  const openArgs = {
@@ -210,6 +218,30 @@ const makeAfterReadHook = (marker) => {
210
218
  };
211
219
  };
212
220
  /**
221
+ * Recursive presence check for a stored write-only sibling: arrays count only
222
+ * when some item is present, locale maps only when some locale's value is,
223
+ * including a locale map of arrays. `{ en: [] }` and `{ en: [null] }` read as
224
+ * unset; a sealed string (or pre-adoption scalar) reads as set.
225
+ */
226
+ const hasStoredValue = (value) => {
227
+ if (value == null) return false;
228
+ if (Array.isArray(value)) return value.some(hasStoredValue);
229
+ if (typeof value === "object") return Object.values(value).some(hasStoredValue);
230
+ return true;
231
+ };
232
+ /**
233
+ * afterRead on the virtual set-indicator sibling of a write-only field: true
234
+ * when the stored sibling holds anything (sealed, or pre-adoption plaintext).
235
+ * A locale-map sibling (locale=all read) counts as set when any locale has a
236
+ * value. Utility flows pass through so raw reads see no synthesized data.
237
+ */
238
+ const makeSetIndicatorHook = (fieldName) => {
239
+ return ({ context, siblingData, value }) => {
240
+ if (contextMode(context)) return value;
241
+ return hasStoredValue(siblingData[fieldName]);
242
+ };
243
+ };
244
+ /**
213
245
  * afterRead on the virtual richText field: decrypts the ciphertext sibling into
214
246
  * a SerializedEditorState. The virtual field is never persisted, so its own
215
247
  * value is always undefined and the ciphertext SIBLING is the source. The
@@ -259,11 +291,7 @@ const makeRichTextSealHook = (marker, storedName) => {
259
291
  if (marker.localized && req.locale === "all" && isLocaleMap(value)) {
260
292
  const sealedMap = {};
261
293
  for (const [locale, localeValue] of Object.entries(value)) sealedMap[locale] = localeValue == null || isSealed(localeValue) ? localeValue : seal({
262
- aad: buildAad([
263
- slug,
264
- marker.fieldName,
265
- locale
266
- ]),
294
+ aad: localeAad(marker, slug, locale),
267
295
  key: activeKey,
268
296
  keyId: ring.activeId,
269
297
  plaintext: localeValue
@@ -321,6 +349,6 @@ const makeRichTextValidate = () => {
321
349
  };
322
350
  };
323
351
  //#endregion
324
- export { DecryptFailedError, contextMode, makeAfterReadHook, makeBeforeChangeHook, makeRichTextCiphertextHook, makeRichTextDecryptHook, makeRichTextSealHook, makeRichTextValidate, ringForRequest };
352
+ export { DecryptFailedError, contextMode, makeAfterReadHook, makeBeforeChangeHook, makeRichTextCiphertextHook, makeRichTextDecryptHook, makeRichTextSealHook, makeRichTextValidate, makeSetIndicatorHook, ringForRequest };
325
353
 
326
354
  //# sourceMappingURL=hooks.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"hooks.js","names":[],"sources":["../../../src/fields/encrypted/hooks.ts"],"sourcesContent":["import type { FieldHook, PayloadRequest, RichTextField, SanitizedConfig, Validate } from 'payload'\nimport { getFieldsRegistry } from '../../plugin/registry'\nimport type { DecryptFailurePolicy } from '../../types'\nimport { buildAad } from './crypto/aad'\nimport { computeBidx } from './crypto/bidx'\nimport { type KeyRing, resolveKeys } from './crypto/keys'\nimport { isSealed, parseWire, seal, unseal } from './crypto/wire'\nimport { sealedArrayKey, stashPlaintext } from './plaintextStash'\nimport {\n\tENCRYPTED_CONTEXT_KEY,\n\ttype EncryptedContextMode,\n\ttype EncryptedFieldMarker,\n} from './types'\n\nexport interface DecryptFailedArgs {\n\tcause: unknown\n\tfield: string\n\tkeyId: string | undefined\n\tslug: string\n}\n\n/** Raised on read when decryption fails and the policy is 'throw'. */\nexport class DecryptFailedError extends Error {\n\tconstructor({ cause, field, keyId, slug }: DecryptFailedArgs) {\n\t\tconst keyInfo = keyId ? ` (keyId '${keyId}')` : ''\n\t\tsuper(\n\t\t\t`@10x-media/fields: failed to decrypt ${slug}.${field}${keyInfo}: ${cause instanceof Error ? cause.name : 'unknown error'}`\n\t\t)\n\t\tthis.name = 'DecryptFailedError'\n\t\tthis.cause = cause\n\t}\n}\n\nexport const ringForRequest = (\n\treq: PayloadRequest,\n\tmarker: EncryptedFieldMarker\n): Promise<KeyRing> => {\n\tconst registry = getFieldsRegistry(req.payload.config)\n\treturn resolveKeys(marker.keys ?? registry?.encrypted?.keys, req.payload.config.secret)\n}\n\ntype SlugHolder = { slug: string } | null | undefined\n\nconst aadSlug = (collection: SlugHolder, global: SlugHolder): string =>\n\tcollection?.slug ?? global?.slug ?? ''\n\nconst defaultLocale = (config: SanitizedConfig): string =>\n\tconfig.localization ? config.localization.defaultLocale : 'en'\n\n/** Mirrors beforeChange/promise.ts: the locale a write applies to. */\nconst operationLocale = (req: PayloadRequest): string => {\n\tconst locale = req.locale\n\tif (!locale || locale === 'all') {\n\t\treturn defaultLocale(req.payload.config)\n\t}\n\treturn locale\n}\n\n/**\n * AAD binds a ciphertext to its `${slug}.${field}[.${locale}]` slot via\n * buildAad, which rejects any dotted component so the joined data stays\n * unambiguous (a dotted slug/locale would blur the cross-field binding).\n */\nexport const sealAad = (marker: EncryptedFieldMarker, slug: string, req: PayloadRequest): string =>\n\tbuildAad(\n\t\tmarker.localized ? [slug, marker.fieldName, operationLocale(req)] : [slug, marker.fieldName]\n\t)\n\n/**\n * Read-side AAD candidates. Localized fields try the request locale first,\n * then every configured locale: fallbackLocale hoisting and locale=all hook\n * execution mean the hook cannot know which locale sealed the value.\n */\nexport const readAadCandidates = (\n\tmarker: EncryptedFieldMarker,\n\tslug: string,\n\treq: PayloadRequest\n): string[] => {\n\tif (!marker.localized) {\n\t\treturn [buildAad([slug, marker.fieldName])]\n\t}\n\tconst codes = req.payload.config.localization\n\t\t? req.payload.config.localization.localeCodes\n\t\t: [defaultLocale(req.payload.config)]\n\tconst first = operationLocale(req)\n\tconst ordered = [first, ...codes.filter((code) => code !== first)]\n\treturn ordered.map((code) => buildAad([slug, marker.fieldName, code]))\n}\n\n/**\n * The active utility mode from the request context, or undefined for a normal\n * operation (including a missing context, which reads as normal). Reused by the\n * response stripper so bulk utilities (which read in `raw` mode) still see the\n * ciphertext and blind-index siblings, while a normal read strips them.\n */\nexport const contextMode = (\n\tcontext: Record<string, unknown> | undefined\n): EncryptedContextMode | undefined => {\n\tconst mode = context?.[ENCRYPTED_CONTEXT_KEY]\n\treturn mode === 'decrypt' || mode === 'raw' || mode === 'rotate' ? mode : undefined\n}\n\n/** A locale=all write hands the hook a `{ [locale]: value }` map, not a scalar. */\nconst isLocaleMap = (value: unknown): value is Record<string, unknown> =>\n\ttypeof value === 'object' && value !== null && !Array.isArray(value)\n\ninterface SealForLocaleArgs {\n\taad: string\n\thasMany: boolean\n\tkey: Buffer\n\tkeyId: string\n}\n\n/** Seal one locale's value, passing already-sealed items through unchanged. */\nconst sealValueForLocale = (value: unknown, args: SealForLocaleArgs): unknown => {\n\tif (value == null) {\n\t\treturn value\n\t}\n\tconst sealItem = (item: unknown): unknown =>\n\t\tisSealed(item)\n\t\t\t? item\n\t\t\t: seal({ aad: args.aad, key: args.key, keyId: args.keyId, plaintext: item })\n\treturn args.hasMany && Array.isArray(value) ? value.map(sealItem) : sealItem(value)\n}\n\nexport const makeBeforeChangeHook = (marker: EncryptedFieldMarker): FieldHook => {\n\treturn async (args) => {\n\t\tconst { collection, global, req, siblingData, value } = args\n\t\tconst mode = contextMode(req.context as Record<string, unknown>)\n\n\t\t// Utilities read ciphertext untouched.\n\t\tif (mode === 'raw') {\n\t\t\treturn value\n\t\t}\n\t\t// Removal path: store incoming plaintext without sealing, drop the now\n\t\t// meaningless blind index.\n\t\tif (mode === 'decrypt') {\n\t\t\tif (marker.queryable && marker.bidxName) {\n\t\t\t\tsiblingData[marker.bidxName] = null\n\t\t\t}\n\t\t\treturn value\n\t\t}\n\n\t\tconst slug = aadSlug(collection, global)\n\t\tconst ring = await ringForRequest(req, marker)\n\t\tconst activeKey = ring.dataKeys.get(ring.activeId) as Buffer\n\n\t\tif (mode === 'rotate') {\n\t\t\tconst candidates = readAadCandidates(marker, slug, req)\n\t\t\tconst writeAad = sealAad(marker, slug, req)\n\t\t\tconst rotateOne = (item: unknown): unknown => {\n\t\t\t\tif (!isSealed(item)) {\n\t\t\t\t\treturn item\n\t\t\t\t}\n\t\t\t\tif (parseWire(item).keyId === ring.activeId) {\n\t\t\t\t\treturn item\n\t\t\t\t}\n\t\t\t\tconst plaintext = unseal(item, ring.dataKeys, candidates)\n\t\t\t\tif (marker.queryable && marker.bidxName) {\n\t\t\t\t\tsiblingData[marker.bidxName] = computeBidx(plaintext, ring.indexKey, marker.normalize)\n\t\t\t\t}\n\t\t\t\treturn seal({ aad: writeAad, key: activeKey, keyId: ring.activeId, plaintext })\n\t\t\t}\n\t\t\treturn marker.hasMany && Array.isArray(value) ? value.map(rotateOne) : rotateOne(value)\n\t\t}\n\n\t\tif (value === undefined) {\n\t\t\treturn undefined\n\t\t}\n\t\tif (value === null) {\n\t\t\tif (marker.queryable && marker.bidxName) {\n\t\t\t\tsiblingData[marker.bidxName] = null\n\t\t\t}\n\t\t\treturn null\n\t\t}\n\n\t\t// locale=all write: value is a `{ [locale]: value }` map. Seal each locale\n\t\t// under its own locale AAD so afterRead's per-locale unseal opens it (a\n\t\t// single blob sealed under the default-locale AAD would not). Plaintext\n\t\t// validation and blind-index maintenance for bulk all-locales writes are\n\t\t// deferred to per-locale writes (covered by Batch E int tests).\n\t\tif (marker.localized && req.locale === 'all' && isLocaleMap(value)) {\n\t\t\tconst sealedMap: Record<string, unknown> = {}\n\t\t\tfor (const [locale, localeValue] of Object.entries(value)) {\n\t\t\t\tsealedMap[locale] = sealValueForLocale(localeValue, {\n\t\t\t\t\taad: buildAad([slug, marker.fieldName, locale]),\n\t\t\t\t\thasMany: marker.hasMany,\n\t\t\t\t\tkey: activeKey,\n\t\t\t\t\tkeyId: ring.activeId,\n\t\t\t\t})\n\t\t\t}\n\t\t\treturn sealedMap\n\t\t}\n\n\t\tconst aad = sealAad(marker, slug, req)\n\t\tconst sealOne = (item: unknown): string =>\n\t\t\tseal({ aad, key: activeKey, keyId: ring.activeId, plaintext: item })\n\n\t\tif (marker.hasMany) {\n\t\t\tif (!Array.isArray(value)) {\n\t\t\t\treturn value\n\t\t\t}\n\t\t\t// Seal PER ITEM so an already-sealed item (a passthrough from a prior\n\t\t\t// read, e.g. a mixed array) is never wrapped in a second GCM layer.\n\t\t\tconst sealedArray = value.map((item) => (isSealed(item) ? item : sealOne(item)))\n\t\t\t// Stash the plaintext for the composed validate, keyed by the sealed\n\t\t\t// output (unique per write), only for a fresh all-plaintext write. A\n\t\t\t// mixed/passthrough array is not stashed; its already-sealed items were\n\t\t\t// validated when first written, so their re-validation is deferred.\n\t\t\tif (!value.some(isSealed)) {\n\t\t\t\tstashPlaintext(req, sealedArrayKey(sealedArray), value)\n\t\t\t}\n\t\t\treturn sealedArray\n\t\t}\n\n\t\t// Single value already sealed: a resubmitted read or unchanged sibling;\n\t\t// passthrough without re-sealing (no plaintext to stash).\n\t\tif (isSealed(value)) {\n\t\t\treturn value\n\t\t}\n\t\t// Stash the plaintext for the composed validate, keyed by the sealed value\n\t\t// (unique per write); do not validate/throw here.\n\t\tconst sealed = sealOne(value)\n\t\tstashPlaintext(req, sealed, value)\n\t\tif (marker.queryable && marker.bidxName) {\n\t\t\tsiblingData[marker.bidxName] = computeBidx(value, ring.indexKey, marker.normalize)\n\t\t}\n\t\treturn sealed\n\t}\n}\n\ninterface ApplyPolicyArgs {\n\terror: unknown\n\tmarker: EncryptedFieldMarker\n\tpolicy: DecryptFailurePolicy\n\traw: unknown\n\tslug: string\n}\n\nconst applyPolicy = ({ error, marker, policy, raw, slug }: ApplyPolicyArgs): unknown => {\n\tif (policy === 'null') {\n\t\treturn null\n\t}\n\tif (policy === 'passthrough') {\n\t\treturn raw\n\t}\n\tif (typeof policy === 'function') {\n\t\treturn policy({\n\t\t\tcollection: slug,\n\t\t\terror,\n\t\t\tfield: marker.fieldName,\n\t\t\tvalue: typeof raw === 'string' ? raw : String(raw),\n\t\t})\n\t}\n\tconst keyId = isSealed(raw) ? (raw as string).split('.')[1] : undefined\n\tthrow new DecryptFailedError({ cause: error, field: marker.fieldName, keyId, slug })\n}\n\ninterface OpenSealedArgs {\n\tcandidates: string[]\n\tmarker: EncryptedFieldMarker\n\tpolicy: DecryptFailurePolicy\n\tring: KeyRing\n\tslug: string\n}\n\n/**\n * Unseals one value, applying the decrypt-failure policy on a non-sealed item\n * (plaintext at rest is pre-adoption data; passthrough is the lazy-migration\n * mode) or a failed unseal. Shared by the scalar afterRead hook and the\n * richText decrypt hook.\n */\nconst openSealed = (item: unknown, args: OpenSealedArgs): unknown => {\n\tconst { candidates, marker, policy, ring, slug } = args\n\tif (!isSealed(item)) {\n\t\treturn applyPolicy({ error: new Error('value is not sealed'), marker, policy, raw: item, slug })\n\t}\n\ttry {\n\t\treturn unseal(item, ring.dataKeys, candidates)\n\t} catch (error) {\n\t\treturn applyPolicy({ error, marker, policy, raw: item, slug })\n\t}\n}\n\nconst resolvePolicy = (req: PayloadRequest, marker: EncryptedFieldMarker): DecryptFailurePolicy => {\n\tconst registry = getFieldsRegistry(req.payload.config)\n\treturn marker.onDecryptFailure ?? registry?.encrypted?.onDecryptFailure ?? 'throw'\n}\n\nexport const makeAfterReadHook = (marker: EncryptedFieldMarker): FieldHook => {\n\treturn async (args) => {\n\t\tconst { collection, context, global, req, value } = args\n\t\tif (value === undefined || value === null) {\n\t\t\treturn value\n\t\t}\n\t\tif (contextMode(context)) {\n\t\t\treturn value\n\t\t}\n\t\tconst slug = aadSlug(collection, global)\n\t\tconst ring = await ringForRequest(req, marker)\n\t\tconst openArgs: OpenSealedArgs = {\n\t\t\tcandidates: readAadCandidates(marker, slug, req),\n\t\t\tmarker,\n\t\t\tpolicy: resolvePolicy(req, marker),\n\t\t\tring,\n\t\t\tslug,\n\t\t}\n\t\tconst openOne = (item: unknown): unknown => openSealed(item, openArgs)\n\t\treturn marker.hasMany && Array.isArray(value) ? value.map(openOne) : openOne(value)\n\t}\n}\n\n/**\n * afterRead on the virtual richText field: decrypts the ciphertext sibling into\n * a SerializedEditorState. The virtual field is never persisted, so its own\n * value is always undefined and the ciphertext SIBLING is the source. The\n * ciphertext field has no afterRead, so that sibling holds raw ciphertext for\n * the whole phase, making this the single deterministic reader. Runs before the\n * editor's own afterRead, which then populates upload/relationship nodes on the\n * decrypted object.\n */\nexport const makeRichTextDecryptHook = (\n\tmarker: EncryptedFieldMarker,\n\tstoredName: string\n): FieldHook => {\n\treturn async (args) => {\n\t\tconst { collection, context, global, req, siblingData } = args\n\t\tif (contextMode(context)) {\n\t\t\treturn args.value\n\t\t}\n\t\tconst ciphertext = (siblingData as Record<string, unknown>)[storedName]\n\t\tif (ciphertext === undefined || ciphertext === null) {\n\t\t\treturn ciphertext\n\t\t}\n\t\tconst slug = aadSlug(collection, global)\n\t\tconst ring = await ringForRequest(req, marker)\n\t\treturn openSealed(ciphertext, {\n\t\t\tcandidates: readAadCandidates(marker, slug, req),\n\t\t\tmarker,\n\t\t\tpolicy: resolvePolicy(req, marker),\n\t\t\tring,\n\t\t\tslug,\n\t\t})\n\t}\n}\n\n/**\n * beforeChange on the virtual richText field: seals the submitted\n * SerializedEditorState into the ciphertext sibling and returns the plaintext\n * unchanged (Payload drops it at the DB write since the field is virtual). The\n * sole normal-mode writer of the ciphertext slot. Utility flows (rotate/decrypt/\n * raw) pass through untouched; the ciphertext field's own hook handles rotation.\n * An absent value (partial write) preserves the existing ciphertext.\n */\nexport const makeRichTextSealHook = (\n\tmarker: EncryptedFieldMarker,\n\tstoredName: string\n): FieldHook => {\n\treturn async (args) => {\n\t\tconst { collection, global, req, siblingData, value } = args\n\t\tif (contextMode(req.context as Record<string, unknown>)) {\n\t\t\treturn value\n\t\t}\n\t\tif (value === undefined) {\n\t\t\treturn undefined\n\t\t}\n\t\tconst sibling = siblingData as Record<string, unknown>\n\t\tif (value === null) {\n\t\t\tsibling[storedName] = null\n\t\t\treturn null\n\t\t}\n\t\tconst slug = aadSlug(collection, global)\n\t\tconst ring = await ringForRequest(req, marker)\n\t\tconst activeKey = ring.dataKeys.get(ring.activeId) as Buffer\n\t\t// locale=all write: value is a `{ [locale]: SerializedEditorState }` map.\n\t\t// Seal each locale under its own locale AAD so the per-locale decrypt opens\n\t\t// it, mirroring the scalar hook's locale-map handling.\n\t\tif (marker.localized && req.locale === 'all' && isLocaleMap(value)) {\n\t\t\tconst sealedMap: Record<string, unknown> = {}\n\t\t\tfor (const [locale, localeValue] of Object.entries(value)) {\n\t\t\t\tsealedMap[locale] =\n\t\t\t\t\tlocaleValue == null || isSealed(localeValue)\n\t\t\t\t\t\t? localeValue\n\t\t\t\t\t\t: seal({\n\t\t\t\t\t\t\t\taad: buildAad([slug, marker.fieldName, locale]),\n\t\t\t\t\t\t\t\tkey: activeKey,\n\t\t\t\t\t\t\t\tkeyId: ring.activeId,\n\t\t\t\t\t\t\t\tplaintext: localeValue,\n\t\t\t\t\t\t\t})\n\t\t\t}\n\t\t\tsibling[storedName] = sealedMap\n\t\t\treturn value\n\t\t}\n\t\tsibling[storedName] = isSealed(value)\n\t\t\t? value\n\t\t\t: seal({\n\t\t\t\t\taad: sealAad(marker, slug, req),\n\t\t\t\t\tkey: activeKey,\n\t\t\t\t\tkeyId: ring.activeId,\n\t\t\t\t\tplaintext: value,\n\t\t\t\t})\n\t\treturn value\n\t}\n}\n\n/**\n * beforeChange on the hidden ciphertext field. A no-op in every mode except\n * rotate (the virtual field's seal hook is the sole normal-mode producer of this\n * slot). Under rotate it unseals with the stale key and reseals with the active\n * key so rotateEncryptedFields round-trips, mirroring the scalar rotate branch.\n */\nexport const makeRichTextCiphertextHook = (marker: EncryptedFieldMarker): FieldHook => {\n\treturn async (args) => {\n\t\tconst { collection, global, req, value } = args\n\t\tif (contextMode(req.context as Record<string, unknown>) !== 'rotate') {\n\t\t\treturn undefined\n\t\t}\n\t\tif (!isSealed(value)) {\n\t\t\treturn value\n\t\t}\n\t\tconst ring = await ringForRequest(req, marker)\n\t\tif (parseWire(value).keyId === ring.activeId) {\n\t\t\treturn value\n\t\t}\n\t\tconst slug = aadSlug(collection, global)\n\t\tconst plaintext = unseal(value, ring.dataKeys, readAadCandidates(marker, slug, req))\n\t\tconst activeKey = ring.dataKeys.get(ring.activeId) as Buffer\n\t\treturn seal({\n\t\t\taad: sealAad(marker, slug, req),\n\t\t\tkey: activeKey,\n\t\t\tkeyId: ring.activeId,\n\t\t\tplaintext,\n\t\t})\n\t}\n}\n\n/**\n * Validate for the virtual richText field. Delegates to the editor's own\n * validate (required + node-level validation) for full parity with a native\n * richText field. Skips utility flows and absent values: rotate/decrypt patch\n * only the ciphertext sibling, so the virtual value is undefined then, and a\n * required check must not trip on that.\n */\nexport const makeRichTextValidate = (): Validate<unknown, unknown, unknown, RichTextField> => {\n\treturn (value, options) => {\n\t\tif (contextMode(options.req.context as Record<string, unknown>)) {\n\t\t\treturn true\n\t\t}\n\t\tif (value === undefined) {\n\t\t\treturn true\n\t\t}\n\t\tconst { editor } = options\n\t\tif (!editor || typeof editor === 'function' || typeof editor.validate !== 'function') {\n\t\t\treturn true\n\t\t}\n\t\treturn editor.validate(value, options)\n\t}\n}\n"],"mappings":";;;;;;;;;AAsBA,IAAa,qBAAb,cAAwC,MAAM;CAC7C,YAAY,EAAE,OAAO,OAAO,OAAO,QAA2B;EAC7D,MAAM,UAAU,QAAQ,YAAY,MAAM,MAAM;EAChD,MACC,wCAAwC,KAAK,GAAG,QAAQ,QAAQ,IAAI,iBAAiB,QAAQ,MAAM,OAAO,iBAC3G;EACA,KAAK,OAAO;EACZ,KAAK,QAAQ;CACd;AACD;AAEA,MAAa,kBACZ,KACA,WACsB;CACtB,MAAM,WAAW,kBAAkB,IAAI,QAAQ,MAAM;CACrD,OAAO,YAAY,OAAO,QAAQ,UAAU,WAAW,MAAM,IAAI,QAAQ,OAAO,MAAM;AACvF;AAIA,MAAM,WAAW,YAAwB,WACxC,YAAY,QAAQ,QAAQ,QAAQ;AAErC,MAAM,iBAAiB,WACtB,OAAO,eAAe,OAAO,aAAa,gBAAgB;;AAG3D,MAAM,mBAAmB,QAAgC;CACxD,MAAM,SAAS,IAAI;CACnB,IAAI,CAAC,UAAU,WAAW,OACzB,OAAO,cAAc,IAAI,QAAQ,MAAM;CAExC,OAAO;AACR;;;;;;AAOA,MAAa,WAAW,QAA8B,MAAc,QACnE,SACC,OAAO,YAAY;CAAC;C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AS,IAAI,KAAK,QAAQ;EACjD,OAAO,KAAK;GACX,KAAK,QAAQ,QAAQ,MAAM,GAAG;GAC9B,KAAK;GACL,OAAO,KAAK;GACZ;EACD,CAAC;CACF;AACD;;;;;;;;AASA,MAAa,6BAAiF;CAC7F,QAAQ,OAAO,YAAY;EAC1B,IAAI,YAAY,QAAQ,IAAI,OAAkC,GAC7D,OAAO;EAER,IAAI,UAAU,KAAA,GACb,OAAO;EAER,MAAM,EAAE,WAAW;EACnB,IAAI,CAAC,UAAU,OAAO,WAAW,cAAc,OAAO,OAAO,aAAa,YACzE,OAAO;EAER,OAAO,OAAO,SAAS,OAAO,OAAO;CACtC;AACD"}
1
+ {"version":3,"file":"hooks.js","names":[],"sources":["../../../src/fields/encrypted/hooks.ts"],"sourcesContent":["import type { FieldHook, PayloadRequest, RichTextField, SanitizedConfig, Validate } from 'payload'\nimport { getFieldsRegistry } from '../../plugin/registry'\nimport type { DecryptFailurePolicy } from '../../types'\nimport { buildAad } from './crypto/aad'\nimport { computeBidx } from './crypto/bidx'\nimport { type KeyRing, resolveKeys } from './crypto/keys'\nimport { isSealed, parseWire, seal, unseal } from './crypto/wire'\nimport { makeHint } from './hint'\nimport { sealedArrayKey, stashPlaintext } from './plaintextStash'\nimport {\n\taadScopeOf,\n\tENCRYPTED_CONTEXT_KEY,\n\ttype EncryptedContextMode,\n\ttype EncryptedFieldMarker,\n} from './types'\n\nexport interface DecryptFailedArgs {\n\tcause: unknown\n\tfield: string\n\tkeyId: string | undefined\n\tslug: string\n}\n\n/** Raised on read when decryption fails and the policy is 'throw'. */\nexport class DecryptFailedError extends Error {\n\tconstructor({ cause, field, keyId, slug }: DecryptFailedArgs) {\n\t\tconst keyInfo = keyId ? ` (keyId '${keyId}')` : ''\n\t\tsuper(\n\t\t\t`@10x-media/fields: failed to decrypt ${slug}.${field}${keyInfo}: ${cause instanceof Error ? cause.name : 'unknown error'}`\n\t\t)\n\t\tthis.name = 'DecryptFailedError'\n\t\tthis.cause = cause\n\t}\n}\n\nexport const ringForRequest = (\n\treq: PayloadRequest,\n\tmarker: EncryptedFieldMarker\n): Promise<KeyRing> => {\n\tconst registry = getFieldsRegistry(req.payload.config)\n\treturn resolveKeys(marker.keys ?? registry?.encrypted?.keys, req.payload.config.secret)\n}\n\ntype SlugHolder = { slug: string } | null | undefined\n\nconst aadSlug = (collection: SlugHolder, global: SlugHolder): string =>\n\tcollection?.slug ?? global?.slug ?? ''\n\nconst defaultLocale = (config: SanitizedConfig): string =>\n\tconfig.localization ? config.localization.defaultLocale : 'en'\n\n/** Mirrors beforeChange/promise.ts: the locale a write applies to. */\nconst operationLocale = (req: PayloadRequest): string => {\n\tconst locale = req.locale\n\tif (!locale || locale === 'all') {\n\t\treturn defaultLocale(req.payload.config)\n\t}\n\treturn locale\n}\n\n/**\n * AAD binds a ciphertext to its `${scope}.${field}[.${locale}]` slot, where the\n * scope is the field's pinned `aadScope` or the schema slug, via buildAad,\n * which rejects any dotted component so the joined data stays unambiguous (a\n * dotted scope or locale would blur the cross-field binding).\n */\nexport const sealAad = (\n\tmarker: EncryptedFieldMarker,\n\tslug: string,\n\treq: PayloadRequest\n): string => {\n\tif (marker.localized) {\n\t\treturn localeAad(marker, slug, operationLocale(req))\n\t}\n\treturn buildAad([aadScopeOf(marker, slug), marker.fieldName])\n}\n\n/** The AAD for one locale of a localized field; locale-map writes seal per entry. */\nconst localeAad = (marker: EncryptedFieldMarker, slug: string, locale: string): string =>\n\tbuildAad([aadScopeOf(marker, slug), marker.fieldName, locale])\n\n/**\n * Read-side AAD candidates. Localized fields try the request locale first,\n * then every configured locale: fallbackLocale hoisting and locale=all hook\n * execution mean the hook cannot know which locale sealed the value.\n */\nexport const readAadCandidates = (\n\tmarker: EncryptedFieldMarker,\n\tslug: string,\n\treq: PayloadRequest\n): string[] => {\n\tif (!marker.localized) {\n\t\treturn [buildAad([aadScopeOf(marker, slug), marker.fieldName])]\n\t}\n\tconst codes = req.payload.config.localization\n\t\t? req.payload.config.localization.localeCodes\n\t\t: [defaultLocale(req.payload.config)]\n\tconst first = operationLocale(req)\n\tconst ordered = [first, ...codes.filter((code) => code !== first)]\n\treturn ordered.map((code) => localeAad(marker, slug, code))\n}\n\n/**\n * The active utility mode from the request context, or undefined for a normal\n * operation (including a missing context, which reads as normal). Reused by the\n * response stripper so bulk utilities (which read in `raw` mode) still see the\n * ciphertext and blind-index siblings, while a normal read strips them.\n */\nexport const contextMode = (\n\tcontext: Record<string, unknown> | undefined\n): EncryptedContextMode | undefined => {\n\tconst mode = context?.[ENCRYPTED_CONTEXT_KEY]\n\treturn mode === 'decrypt' || mode === 'raw' || mode === 'rotate' ? mode : undefined\n}\n\n/** A locale=all write hands the hook a `{ [locale]: value }` map, not a scalar. */\nconst isLocaleMap = (value: unknown): value is Record<string, unknown> =>\n\ttypeof value === 'object' && value !== null && !Array.isArray(value)\n\ninterface SealForLocaleArgs {\n\taad: string\n\thasMany: boolean\n\tkey: Buffer\n\tkeyId: string\n}\n\n/** Seal one locale's value, passing already-sealed items through unchanged. */\nconst sealValueForLocale = (value: unknown, args: SealForLocaleArgs): unknown => {\n\tif (value == null) {\n\t\treturn value\n\t}\n\tconst sealItem = (item: unknown): unknown =>\n\t\tisSealed(item)\n\t\t\t? item\n\t\t\t: seal({ aad: args.aad, key: args.key, keyId: args.keyId, plaintext: item })\n\treturn args.hasMany && Array.isArray(value) ? value.map(sealItem) : sealItem(value)\n}\n\nexport const makeBeforeChangeHook = (marker: EncryptedFieldMarker): FieldHook => {\n\treturn async (args) => {\n\t\tconst { collection, global, req, siblingData, value } = args\n\t\tconst mode = contextMode(req.context as Record<string, unknown>)\n\n\t\t// Utilities read ciphertext untouched.\n\t\tif (mode === 'raw') {\n\t\t\treturn value\n\t\t}\n\t\t// Removal path: store incoming plaintext without sealing, drop the now\n\t\t// meaningless blind index and hint.\n\t\tif (mode === 'decrypt') {\n\t\t\tif (marker.queryable && marker.bidxName) {\n\t\t\t\tsiblingData[marker.bidxName] = null\n\t\t\t}\n\t\t\tif (marker.hintName) {\n\t\t\t\tsiblingData[marker.hintName] = null\n\t\t\t}\n\t\t\treturn value\n\t\t}\n\n\t\tconst slug = aadSlug(collection, global)\n\t\tconst ring = await ringForRequest(req, marker)\n\t\tconst activeKey = ring.dataKeys.get(ring.activeId) as Buffer\n\n\t\tif (mode === 'rotate') {\n\t\t\tconst candidates = readAadCandidates(marker, slug, req)\n\t\t\tconst writeAad = sealAad(marker, slug, req)\n\t\t\tconst rotateOne = (item: unknown): unknown => {\n\t\t\t\tif (!isSealed(item)) {\n\t\t\t\t\treturn item\n\t\t\t\t}\n\t\t\t\tif (parseWire(item).keyId === ring.activeId) {\n\t\t\t\t\treturn item\n\t\t\t\t}\n\t\t\t\tconst plaintext = unseal(item, ring.dataKeys, candidates)\n\t\t\t\tif (marker.queryable && marker.bidxName) {\n\t\t\t\t\tsiblingData[marker.bidxName] = computeBidx(plaintext, ring.indexKey, marker.normalize)\n\t\t\t\t}\n\t\t\t\treturn seal({ aad: writeAad, key: activeKey, keyId: ring.activeId, plaintext })\n\t\t\t}\n\t\t\treturn marker.hasMany && Array.isArray(value) ? value.map(rotateOne) : rotateOne(value)\n\t\t}\n\n\t\tif (value === undefined) {\n\t\t\treturn undefined\n\t\t}\n\t\t// A write-only empty string clears like null: sealing '' would create a\n\t\t// trap state (\"set\" with an empty credential) that no caller can ever\n\t\t// read back to diagnose. The admin never sends '', so this only guards\n\t\t// direct API writes; other encrypted fields keep sealing '' as before.\n\t\tif (value === null || (marker.writeOnly && value === '')) {\n\t\t\tif (marker.queryable && marker.bidxName) {\n\t\t\t\tsiblingData[marker.bidxName] = null\n\t\t\t}\n\t\t\tif (marker.hintName) {\n\t\t\t\tsiblingData[marker.hintName] = null\n\t\t\t}\n\t\t\treturn null\n\t\t}\n\n\t\t// locale=all write: value is a `{ [locale]: value }` map. Seal each locale\n\t\t// under its own locale AAD so afterRead's per-locale unseal opens it (a\n\t\t// single blob sealed under the default-locale AAD would not). Plaintext\n\t\t// validation and blind-index maintenance for bulk all-locales writes are\n\t\t// deferred to per-locale writes (covered by Batch E int tests).\n\t\tif (marker.localized && req.locale === 'all' && isLocaleMap(value)) {\n\t\t\tconst sealedMap: Record<string, unknown> = {}\n\t\t\tconst hintMap: Record<string, unknown> = {}\n\t\t\tfor (const [locale, localeValue] of Object.entries(value)) {\n\t\t\t\tsealedMap[locale] = sealValueForLocale(localeValue, {\n\t\t\t\t\taad: localeAad(marker, slug, locale),\n\t\t\t\t\thasMany: marker.hasMany,\n\t\t\t\t\tkey: activeKey,\n\t\t\t\t\tkeyId: ring.activeId,\n\t\t\t\t})\n\t\t\t\tif (marker.hint && !isSealed(localeValue)) {\n\t\t\t\t\thintMap[locale] = localeValue == null ? null : makeHint(localeValue, marker.hint)\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (marker.hintName && Object.keys(hintMap).length > 0) {\n\t\t\t\tsiblingData[marker.hintName] = hintMap\n\t\t\t}\n\t\t\treturn sealedMap\n\t\t}\n\n\t\tconst aad = sealAad(marker, slug, req)\n\t\tconst sealOne = (item: unknown): string =>\n\t\t\tseal({ aad, key: activeKey, keyId: ring.activeId, plaintext: item })\n\n\t\tif (marker.hasMany) {\n\t\t\tif (!Array.isArray(value)) {\n\t\t\t\treturn value\n\t\t\t}\n\t\t\t// Seal PER ITEM so an already-sealed item (a passthrough from a prior\n\t\t\t// read, e.g. a mixed array) is never wrapped in a second GCM layer.\n\t\t\tconst sealedArray = value.map((item) => (isSealed(item) ? item : sealOne(item)))\n\t\t\t// Stash the plaintext for the composed validate, keyed by the sealed\n\t\t\t// output (unique per write), only for a fresh all-plaintext write. A\n\t\t\t// mixed/passthrough array is not stashed; its already-sealed items were\n\t\t\t// validated when first written, so their re-validation is deferred.\n\t\t\tif (!value.some(isSealed)) {\n\t\t\t\tstashPlaintext(req, sealedArrayKey(sealedArray), value)\n\t\t\t}\n\t\t\treturn sealedArray\n\t\t}\n\n\t\t// Single value already sealed: a resubmitted read or unchanged sibling;\n\t\t// passthrough without re-sealing (no plaintext to stash).\n\t\tif (isSealed(value)) {\n\t\t\treturn value\n\t\t}\n\t\t// Stash the plaintext for the composed validate, keyed by the sealed value\n\t\t// (unique per write); do not validate/throw here.\n\t\tconst sealed = sealOne(value)\n\t\tstashPlaintext(req, sealed, value)\n\t\tif (marker.queryable && marker.bidxName) {\n\t\t\tsiblingData[marker.bidxName] = computeBidx(value, ring.indexKey, marker.normalize)\n\t\t}\n\t\t// The hint derives from the same plaintext this seal consumes, so hint and\n\t\t// ciphertext can never drift. A sealed passthrough above never lands here,\n\t\t// which is what keeps an unchanged value's hint intact.\n\t\tif (marker.hint && marker.hintName) {\n\t\t\tsiblingData[marker.hintName] = makeHint(value, marker.hint)\n\t\t}\n\t\treturn sealed\n\t}\n}\n\ninterface ApplyPolicyArgs {\n\terror: unknown\n\tmarker: EncryptedFieldMarker\n\tpolicy: DecryptFailurePolicy\n\traw: unknown\n\tslug: string\n}\n\nconst applyPolicy = ({ error, marker, policy, raw, slug }: ApplyPolicyArgs): unknown => {\n\tif (policy === 'null') {\n\t\treturn null\n\t}\n\tif (policy === 'passthrough') {\n\t\treturn raw\n\t}\n\tif (typeof policy === 'function') {\n\t\treturn policy({\n\t\t\tcollection: slug,\n\t\t\terror,\n\t\t\tfield: marker.fieldName,\n\t\t\tvalue: typeof raw === 'string' ? raw : String(raw),\n\t\t})\n\t}\n\tconst keyId = isSealed(raw) ? (raw as string).split('.')[1] : undefined\n\tthrow new DecryptFailedError({ cause: error, field: marker.fieldName, keyId, slug })\n}\n\ninterface OpenSealedArgs {\n\tcandidates: string[]\n\tmarker: EncryptedFieldMarker\n\tpolicy: DecryptFailurePolicy\n\tring: KeyRing\n\tslug: string\n}\n\n/**\n * Unseals one value, applying the decrypt-failure policy on a non-sealed item\n * (plaintext at rest is pre-adoption data; passthrough is the lazy-migration\n * mode) or a failed unseal. Shared by the scalar afterRead hook and the\n * richText decrypt hook.\n */\nconst openSealed = (item: unknown, args: OpenSealedArgs): unknown => {\n\tconst { candidates, marker, policy, ring, slug } = args\n\tif (!isSealed(item)) {\n\t\treturn applyPolicy({ error: new Error('value is not sealed'), marker, policy, raw: item, slug })\n\t}\n\ttry {\n\t\treturn unseal(item, ring.dataKeys, candidates)\n\t} catch (error) {\n\t\treturn applyPolicy({ error, marker, policy, raw: item, slug })\n\t}\n}\n\nconst resolvePolicy = (req: PayloadRequest, marker: EncryptedFieldMarker): DecryptFailurePolicy => {\n\tconst registry = getFieldsRegistry(req.payload.config)\n\treturn marker.onDecryptFailure ?? registry?.encrypted?.onDecryptFailure ?? 'throw'\n}\n\nexport const makeAfterReadHook = (marker: EncryptedFieldMarker): FieldHook => {\n\treturn async (args) => {\n\t\tconst { collection, context, global, req, value } = args\n\t\tif (value === undefined || value === null) {\n\t\t\treturn value\n\t\t}\n\t\tif (contextMode(context)) {\n\t\t\treturn value\n\t\t}\n\t\t// Write-only never decrypts on read: the sealed value passes through and the\n\t\t// collection/global strip hook removes the field from the response, so even\n\t\t// standalone usage (no plugin, no strip) exposes ciphertext at worst.\n\t\tif (marker.writeOnly) {\n\t\t\treturn value\n\t\t}\n\t\tconst slug = aadSlug(collection, global)\n\t\tconst ring = await ringForRequest(req, marker)\n\t\tconst openArgs: OpenSealedArgs = {\n\t\t\tcandidates: readAadCandidates(marker, slug, req),\n\t\t\tmarker,\n\t\t\tpolicy: resolvePolicy(req, marker),\n\t\t\tring,\n\t\t\tslug,\n\t\t}\n\t\tconst openOne = (item: unknown): unknown => openSealed(item, openArgs)\n\t\treturn marker.hasMany && Array.isArray(value) ? value.map(openOne) : openOne(value)\n\t}\n}\n\n/**\n * Recursive presence check for a stored write-only sibling: arrays count only\n * when some item is present, locale maps only when some locale's value is,\n * including a locale map of arrays. `{ en: [] }` and `{ en: [null] }` read as\n * unset; a sealed string (or pre-adoption scalar) reads as set.\n */\nconst hasStoredValue = (value: unknown): boolean => {\n\tif (value == null) {\n\t\treturn false\n\t}\n\tif (Array.isArray(value)) {\n\t\treturn value.some(hasStoredValue)\n\t}\n\tif (typeof value === 'object') {\n\t\treturn Object.values(value).some(hasStoredValue)\n\t}\n\treturn true\n}\n\n/**\n * afterRead on the virtual set-indicator sibling of a write-only field: true\n * when the stored sibling holds anything (sealed, or pre-adoption plaintext).\n * A locale-map sibling (locale=all read) counts as set when any locale has a\n * value. Utility flows pass through so raw reads see no synthesized data.\n */\nexport const makeSetIndicatorHook = (fieldName: string): FieldHook => {\n\treturn ({ context, siblingData, value }) => {\n\t\tif (contextMode(context)) {\n\t\t\treturn value\n\t\t}\n\t\treturn hasStoredValue((siblingData as Record<string, unknown>)[fieldName])\n\t}\n}\n\n/**\n * afterRead on the virtual richText field: decrypts the ciphertext sibling into\n * a SerializedEditorState. The virtual field is never persisted, so its own\n * value is always undefined and the ciphertext SIBLING is the source. The\n * ciphertext field has no afterRead, so that sibling holds raw ciphertext for\n * the whole phase, making this the single deterministic reader. Runs before the\n * editor's own afterRead, which then populates upload/relationship nodes on the\n * decrypted object.\n */\nexport const makeRichTextDecryptHook = (\n\tmarker: EncryptedFieldMarker,\n\tstoredName: string\n): FieldHook => {\n\treturn async (args) => {\n\t\tconst { collection, context, global, req, siblingData } = args\n\t\tif (contextMode(context)) {\n\t\t\treturn args.value\n\t\t}\n\t\tconst ciphertext = (siblingData as Record<string, unknown>)[storedName]\n\t\tif (ciphertext === undefined || ciphertext === null) {\n\t\t\treturn ciphertext\n\t\t}\n\t\tconst slug = aadSlug(collection, global)\n\t\tconst ring = await ringForRequest(req, marker)\n\t\treturn openSealed(ciphertext, {\n\t\t\tcandidates: readAadCandidates(marker, slug, req),\n\t\t\tmarker,\n\t\t\tpolicy: resolvePolicy(req, marker),\n\t\t\tring,\n\t\t\tslug,\n\t\t})\n\t}\n}\n\n/**\n * beforeChange on the virtual richText field: seals the submitted\n * SerializedEditorState into the ciphertext sibling and returns the plaintext\n * unchanged (Payload drops it at the DB write since the field is virtual). The\n * sole normal-mode writer of the ciphertext slot. Utility flows (rotate/decrypt/\n * raw) pass through untouched; the ciphertext field's own hook handles rotation.\n * An absent value (partial write) preserves the existing ciphertext.\n */\nexport const makeRichTextSealHook = (\n\tmarker: EncryptedFieldMarker,\n\tstoredName: string\n): FieldHook => {\n\treturn async (args) => {\n\t\tconst { collection, global, req, siblingData, value } = args\n\t\tif (contextMode(req.context as Record<string, unknown>)) {\n\t\t\treturn value\n\t\t}\n\t\tif (value === undefined) {\n\t\t\treturn undefined\n\t\t}\n\t\tconst sibling = siblingData as Record<string, unknown>\n\t\tif (value === null) {\n\t\t\tsibling[storedName] = null\n\t\t\treturn null\n\t\t}\n\t\tconst slug = aadSlug(collection, global)\n\t\tconst ring = await ringForRequest(req, marker)\n\t\tconst activeKey = ring.dataKeys.get(ring.activeId) as Buffer\n\t\t// locale=all write: value is a `{ [locale]: SerializedEditorState }` map.\n\t\t// Seal each locale under its own locale AAD so the per-locale decrypt opens\n\t\t// it, mirroring the scalar hook's locale-map handling.\n\t\tif (marker.localized && req.locale === 'all' && isLocaleMap(value)) {\n\t\t\tconst sealedMap: Record<string, unknown> = {}\n\t\t\tfor (const [locale, localeValue] of Object.entries(value)) {\n\t\t\t\tsealedMap[locale] =\n\t\t\t\t\tlocaleValue == null || isSealed(localeValue)\n\t\t\t\t\t\t? localeValue\n\t\t\t\t\t\t: seal({\n\t\t\t\t\t\t\t\taad: localeAad(marker, slug, locale),\n\t\t\t\t\t\t\t\tkey: activeKey,\n\t\t\t\t\t\t\t\tkeyId: ring.activeId,\n\t\t\t\t\t\t\t\tplaintext: localeValue,\n\t\t\t\t\t\t\t})\n\t\t\t}\n\t\t\tsibling[storedName] = sealedMap\n\t\t\treturn value\n\t\t}\n\t\tsibling[storedName] = isSealed(value)\n\t\t\t? value\n\t\t\t: seal({\n\t\t\t\t\taad: sealAad(marker, slug, req),\n\t\t\t\t\tkey: activeKey,\n\t\t\t\t\tkeyId: ring.activeId,\n\t\t\t\t\tplaintext: value,\n\t\t\t\t})\n\t\treturn value\n\t}\n}\n\n/**\n * beforeChange on the hidden ciphertext field. A no-op in every mode except\n * rotate (the virtual field's seal hook is the sole normal-mode producer of this\n * slot). Under rotate it unseals with the stale key and reseals with the active\n * key so rotateEncryptedFields round-trips, mirroring the scalar rotate branch.\n */\nexport const makeRichTextCiphertextHook = (marker: EncryptedFieldMarker): FieldHook => {\n\treturn async (args) => {\n\t\tconst { collection, global, req, value } = args\n\t\tif (contextMode(req.context as Record<string, unknown>) !== 'rotate') {\n\t\t\treturn undefined\n\t\t}\n\t\tif (!isSealed(value)) {\n\t\t\treturn value\n\t\t}\n\t\tconst ring = await ringForRequest(req, marker)\n\t\tif (parseWire(value).keyId === ring.activeId) {\n\t\t\treturn value\n\t\t}\n\t\tconst slug = aadSlug(collection, global)\n\t\tconst plaintext = unseal(value, ring.dataKeys, readAadCandidates(marker, slug, req))\n\t\tconst activeKey = ring.dataKeys.get(ring.activeId) as Buffer\n\t\treturn seal({\n\t\t\taad: sealAad(marker, slug, req),\n\t\t\tkey: activeKey,\n\t\t\tkeyId: ring.activeId,\n\t\t\tplaintext,\n\t\t})\n\t}\n}\n\n/**\n * Validate for the virtual richText field. Delegates to the editor's own\n * validate (required + node-level validation) for full parity with a native\n * richText field. Skips utility flows and absent values: rotate/decrypt patch\n * only the ciphertext sibling, so the virtual value is undefined then, and a\n * required check must not trip on that.\n */\nexport const makeRichTextValidate = (): Validate<unknown, unknown, unknown, RichTextField> => {\n\treturn (value, options) => {\n\t\tif (contextMode(options.req.context as Record<string, unknown>)) {\n\t\t\treturn true\n\t\t}\n\t\tif (value === undefined) {\n\t\t\treturn true\n\t\t}\n\t\tconst { editor } = options\n\t\tif (!editor || typeof editor === 'function' || typeof editor.validate !== 'function') {\n\t\t\treturn true\n\t\t}\n\t\treturn editor.validate(value, options)\n\t}\n}\n"],"mappings":";;;;;;;;;;AAwBA,IAAa,qBAAb,cAAwC,MAAM;CAC7C,YAAY,EAAE,OAAO,OAAO,OAAO,QAA2B;EAC7D,MAAM,UAAU,QAAQ,YAAY,MAAM,MAAM;EAChD,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I,OAAkC,MAAM,UAC3D;EAED,IAAI,CAAC,SAAS,KAAK,GAClB,OAAO;EAER,MAAM,OAAO,MAAM,eAAe,KAAK,MAAM;EAC7C,IAAI,UAAU,KAAK,EAAE,UAAU,KAAK,UACnC,OAAO;EAER,MAAM,OAAO,QAAQ,YAAY,MAAM;EACvC,MAAM,YAAY,OAAO,OAAO,KAAK,UAAU,kBAAkB,QAAQ,MAAM,GAAG,CAAC;EACnF,MAAM,YAAY,KAAK,SAAS,IAAI,KAAK,QAAQ;EACjD,OAAO,KAAK;GACX,KAAK,QAAQ,QAAQ,MAAM,GAAG;GAC9B,KAAK;GACL,OAAO,KAAK;GACZ;EACD,CAAC;CACF;AACD;;;;;;;;AASA,MAAa,6BAAiF;CAC7F,QAAQ,OAAO,YAAY;EAC1B,IAAI,YAAY,QAAQ,IAAI,OAAkC,GAC7D,OAAO;EAER,IAAI,UAAU,KAAA,GACb,OAAO;EAER,MAAM,EAAE,WAAW;EACnB,IAAI,CAAC,UAAU,OAAO,WAAW,cAAc,OAAO,OAAO,aAAa,YACzE,OAAO;EAER,OAAO,OAAO,SAAS,OAAO,OAAO;CACtC;AACD"}
@@ -1,4 +1,4 @@
1
- import { CollectionConfig } from "payload";
1
+ import { CollectionConfig, GlobalConfig, Where } from "payload";
2
2
 
3
3
  //#region src/fields/encrypted/queryRewrite.d.ts
4
4
  /**
@@ -7,6 +7,14 @@ import { CollectionConfig } from "payload";
7
7
  * directly only when using encryptedField() standalone without the plugin.
8
8
  */
9
9
  declare const withEncryptedQueryRewrite: (collection: CollectionConfig) => CollectionConfig;
10
+ /**
11
+ * Attaches the response stripper to a global. Globals take no `where`, so this
12
+ * is the strip alone: blind-index hashes, richText ciphertext siblings, and
13
+ * write-only fields never surface in a read result. The fields() plugin applies
14
+ * this to every global automatically; call it directly only when using
15
+ * encryptedField() standalone without the plugin.
16
+ */
17
+ declare const withEncryptedResponseStrip: (global: GlobalConfig) => GlobalConfig;
10
18
  //#endregion
11
- export { withEncryptedQueryRewrite };
19
+ export { withEncryptedQueryRewrite, withEncryptedResponseStrip };
12
20
  //# sourceMappingURL=queryRewrite.d.ts.map
@@ -96,10 +96,11 @@ const deleteAtPath = (doc, path) => {
96
96
  };
97
97
  /**
98
98
  * Removes server-only encrypted paths from read results: blind-index hashes (so
99
- * the keyed index value never leaves the server) and richText ciphertext
100
- * siblings (opaque strings the virtual editor field replaces). `admin.hidden`
101
- * keeps both readable by the plugin's own hooks but, unlike top-level `hidden`,
102
- * does not strip them from responses.
99
+ * the keyed index value never leaves the server), richText ciphertext siblings
100
+ * (opaque strings the virtual editor field replaces), and write-only fields
101
+ * (whose sealed value passes afterRead untouched and must not surface at all).
102
+ * `admin.hidden` keeps the siblings readable by the plugin's own hooks but,
103
+ * unlike top-level `hidden`, does not strip them from responses.
103
104
  */
104
105
  const makeStripPathsHook = (paths) => {
105
106
  return ({ context, doc }) => {
@@ -108,6 +109,15 @@ const makeStripPathsHook = (paths) => {
108
109
  return doc;
109
110
  };
110
111
  };
112
+ /** Response paths a normal read must not surface, per marker kind. */
113
+ const stripPathsFor = (markers) => {
114
+ const paths = [];
115
+ for (const [path, marker] of markers) {
116
+ if (marker.queryable && marker.bidxName) paths.push(bidxPathFor(path, marker.bidxName));
117
+ if (marker.sourceType === "richText" || marker.writeOnly) paths.push(path);
118
+ }
119
+ return paths;
120
+ };
111
121
  /**
112
122
  * Attaches the blind-index where-rewrite and response stripper to a collection.
113
123
  * The fields() plugin applies this to every collection automatically; call it
@@ -116,9 +126,7 @@ const makeStripPathsHook = (paths) => {
116
126
  const withEncryptedQueryRewrite = (collection) => {
117
127
  const allMarkers = scanEncryptedFields(collection.fields);
118
128
  const queryableMarkers = queryableOnly(allMarkers);
119
- const bidxPaths = [...queryableMarkers].map(([path, marker]) => bidxPathFor(path, marker.bidxName));
120
- const ciphertextPaths = [...allMarkers].filter(([, marker]) => marker.sourceType === "richText").map(([path]) => path);
121
- const stripPaths = [...bidxPaths, ...ciphertextPaths];
129
+ const stripPaths = stripPathsFor(allMarkers);
122
130
  if (queryableMarkers.size === 0 && stripPaths.length === 0) return collection;
123
131
  const hooks = { ...collection.hooks };
124
132
  if (stripPaths.length > 0) hooks.afterRead = [...collection.hooks?.afterRead ?? [], makeStripPathsHook(stripPaths)];
@@ -128,7 +136,25 @@ const withEncryptedQueryRewrite = (collection) => {
128
136
  hooks
129
137
  };
130
138
  };
139
+ /**
140
+ * Attaches the response stripper to a global. Globals take no `where`, so this
141
+ * is the strip alone: blind-index hashes, richText ciphertext siblings, and
142
+ * write-only fields never surface in a read result. The fields() plugin applies
143
+ * this to every global automatically; call it directly only when using
144
+ * encryptedField() standalone without the plugin.
145
+ */
146
+ const withEncryptedResponseStrip = (global) => {
147
+ const stripPaths = stripPathsFor(scanEncryptedFields(global.fields));
148
+ if (stripPaths.length === 0) return global;
149
+ return {
150
+ ...global,
151
+ hooks: {
152
+ ...global.hooks,
153
+ afterRead: [...global.hooks?.afterRead ?? [], makeStripPathsHook(stripPaths)]
154
+ }
155
+ };
156
+ };
131
157
  //#endregion
132
- export { withEncryptedQueryRewrite };
158
+ export { withEncryptedQueryRewrite, withEncryptedResponseStrip };
133
159
 
134
160
  //# sourceMappingURL=queryRewrite.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"queryRewrite.js","names":[],"sources":["../../../src/fields/encrypted/queryRewrite.ts"],"sourcesContent":["import type {\n\tCollectionAfterReadHook,\n\tCollectionBeforeOperationHook,\n\tCollectionConfig,\n\tPayloadRequest,\n\tWhere,\n} from 'payload'\nimport { computeBidx } from './crypto/bidx'\nimport type { KeyRing } from './crypto/keys'\nimport { contextMode, ringForRequest } from './hooks'\nimport { queryableOnly, scanEncryptedFields } from './scan'\nimport type { EncryptedFieldMarker } from './types'\n\ntype RingResolver = (marker: EncryptedFieldMarker) => Promise<KeyRing>\n\ntype UnsupportedWarn = (path: string, operator: string) => void\n\n/**\n * A blind index answers exact-match only. An unsupported operator is rewritten\n * to this sentinel so the query matches nothing: every real index value is a\n * 24-char base64url string, and a single space is not one. Exported for tests.\n */\nexport const BIDX_NO_MATCH = ' '\n\nconst isPlainObject = (value: unknown): value is Record<string, unknown> =>\n\ttypeof value === 'object' && value !== null && !Array.isArray(value)\n\nconst rewriteConstraint = async (args: {\n\tconstraint: Record<string, unknown>\n\tmarker: EncryptedFieldMarker\n\tringFor: RingResolver\n\twarn: (operator: string) => void\n}): Promise<Record<string, unknown>> => {\n\tconst { constraint, marker, ringFor, warn } = args\n\tconst ring = await ringFor(marker)\n\tconst toBidx = (value: unknown): unknown =>\n\t\tvalue === null ? null : computeBidx(value, ring.indexKey, marker.normalize)\n\t// Payload's REST layer delivers `in`/`not_in` as a comma-joined string, the\n\t// admin and Local API as an array; hash each element under either shape.\n\tconst toBidxArray = (value: unknown): unknown[] => {\n\t\tconst items = Array.isArray(value)\n\t\t\t? value\n\t\t\t: typeof value === 'string'\n\t\t\t\t? value.split(',').map((item) => item.trim())\n\t\t\t\t: []\n\t\treturn items.map(toBidx)\n\t}\n\tconst rewritten: Record<string, unknown> = {}\n\tfor (const [operator, operand] of Object.entries(constraint)) {\n\t\tswitch (operator) {\n\t\t\tcase 'equals':\n\t\t\t\trewritten.equals = toBidx(operand)\n\t\t\t\tbreak\n\t\t\tcase 'not_equals':\n\t\t\t\trewritten.not_equals = toBidx(operand)\n\t\t\t\tbreak\n\t\t\tcase 'in':\n\t\t\t\trewritten.in = toBidxArray(operand)\n\t\t\t\tbreak\n\t\t\tcase 'not_in':\n\t\t\t\trewritten.not_in = toBidxArray(operand)\n\t\t\t\tbreak\n\t\t\tcase 'exists':\n\t\t\t\t// The blind index is written iff the source has a value, so its\n\t\t\t\t// existence tracks the source's. The boolean passes through unhashed.\n\t\t\t\trewritten.exists = operand\n\t\t\t\tbreak\n\t\t\tdefault:\n\t\t\t\t// Substring, range, comparison, and geo operators cannot run over a\n\t\t\t\t// blind index. Match nothing rather than querying the ciphertext\n\t\t\t\t// column, which would read as a working filter while returning junk.\n\t\t\t\twarn(operator)\n\t\t\t\treturn { equals: BIDX_NO_MATCH }\n\t\t}\n\t}\n\treturn rewritten\n}\n\n/** Recursively rewrites queryable encrypted paths to their blind-index siblings. */\nexport const rewriteWhereForMarkers = async (args: {\n\tmarkers: Map<string, EncryptedFieldMarker>\n\tringFor: RingResolver\n\twarn?: UnsupportedWarn\n\twhere: Where\n}): Promise<Where> => {\n\tconst { markers, ringFor, warn = () => {}, where } = args\n\tconst out: Where = {}\n\tfor (const [key, value] of Object.entries(where)) {\n\t\tif ((key === 'and' || key === 'or') && Array.isArray(value)) {\n\t\t\tout[key] = await Promise.all(\n\t\t\t\tvalue.map((nested) =>\n\t\t\t\t\trewriteWhereForMarkers({ markers, ringFor, warn, where: nested as Where })\n\t\t\t\t)\n\t\t\t)\n\t\t\tcontinue\n\t\t}\n\t\tconst marker = markers.get(key)\n\t\tif (marker?.bidxName && isPlainObject(value)) {\n\t\t\tconst rewritten = await rewriteConstraint({\n\t\t\t\tconstraint: value,\n\t\t\t\tmarker,\n\t\t\t\tringFor,\n\t\t\t\twarn: (operator) => warn(key, operator),\n\t\t\t})\n\t\t\tconst bidxPath = key.includes('.')\n\t\t\t\t? `${key.slice(0, key.lastIndexOf('.') + 1)}${marker.bidxName}`\n\t\t\t\t: marker.bidxName\n\t\t\tout[bidxPath] = { ...(out[bidxPath] as Record<string, unknown>), ...rewritten }\n\t\t\tcontinue\n\t\t}\n\t\tout[key] = value as Where[string]\n\t}\n\treturn out\n}\n\nconst makeHook = (markers: Map<string, EncryptedFieldMarker>): CollectionBeforeOperationHook => {\n\treturn async ({ args, req }) => {\n\t\tif (isPlainObject(args) && 'where' in args && isPlainObject(args.where)) {\n\t\t\tconst payloadReq = req as PayloadRequest\n\t\t\tconst where = await rewriteWhereForMarkers({\n\t\t\t\tmarkers,\n\t\t\t\tringFor: (marker) => ringForRequest(payloadReq, marker),\n\t\t\t\twarn: (path, operator) =>\n\t\t\t\t\tpayloadReq.payload?.logger?.warn?.(\n\t\t\t\t\t\t`@10x-media/fields: operator '${operator}' cannot run on the encrypted field '${path}'. Blind-index filtering supports exact match only (equals, not_equals, in, not_in, exists); this constraint will match nothing.`\n\t\t\t\t\t),\n\t\t\t\twhere: args.where as Where,\n\t\t\t})\n\t\t\treturn { ...args, where }\n\t\t}\n\t\treturn args\n\t}\n}\n\nconst bidxPathFor = (path: string, bidxName: string): string =>\n\tpath.includes('.') ? `${path.slice(0, path.lastIndexOf('.') + 1)}${bidxName}` : bidxName\n\nconst deleteAtPath = (doc: Record<string, unknown>, path: string): void => {\n\tconst segments = path.split('.')\n\tlet node: Record<string, unknown> = doc\n\tfor (const segment of segments.slice(0, -1)) {\n\t\tconst next = node[segment]\n\t\tif (!next || typeof next !== 'object') {\n\t\t\treturn\n\t\t}\n\t\tnode = next as Record<string, unknown>\n\t}\n\tdelete node[segments[segments.length - 1] as string]\n}\n\n/**\n * Removes server-only encrypted paths from read results: blind-index hashes (so\n * the keyed index value never leaves the server) and richText ciphertext\n * siblings (opaque strings the virtual editor field replaces). `admin.hidden`\n * keeps both readable by the plugin's own hooks but, unlike top-level `hidden`,\n * does not strip them from responses.\n */\nconst makeStripPathsHook = (paths: string[]): CollectionAfterReadHook => {\n\treturn ({ context, doc }) => {\n\t\t// Bulk utilities (rotate/adopt/remove) read via pageThrough in `raw`\n\t\t// context and need the ciphertext + blind-index siblings; stripping them\n\t\t// here would make key rotation silently skip every richText field. Only\n\t\t// strip on normal reads.\n\t\tif (contextMode(context as Record<string, unknown>)) {\n\t\t\treturn doc\n\t\t}\n\t\tfor (const path of paths) {\n\t\t\tdeleteAtPath(doc as Record<string, unknown>, path)\n\t\t}\n\t\treturn doc\n\t}\n}\n\n/**\n * Attaches the blind-index where-rewrite and response stripper to a collection.\n * The fields() plugin applies this to every collection automatically; call it\n * directly only when using encryptedField() standalone without the plugin.\n */\nexport const withEncryptedQueryRewrite = (collection: CollectionConfig): CollectionConfig => {\n\tconst allMarkers = scanEncryptedFields(collection.fields)\n\tconst queryableMarkers = queryableOnly(allMarkers)\n\tconst bidxPaths = [...queryableMarkers].map(([path, marker]) =>\n\t\tbidxPathFor(path, marker.bidxName as string)\n\t)\n\t// richText stores its ciphertext under the marker's own scan path\n\t// (`${name}_encrypted`); strip it so the opaque string never surfaces in a\n\t// response, mirroring the bidx strip.\n\tconst ciphertextPaths = [...allMarkers]\n\t\t.filter(([, marker]) => marker.sourceType === 'richText')\n\t\t.map(([path]) => path)\n\tconst stripPaths = [...bidxPaths, ...ciphertextPaths]\n\tif (queryableMarkers.size === 0 && stripPaths.length === 0) {\n\t\treturn collection\n\t}\n\tconst hooks: NonNullable<CollectionConfig['hooks']> = { ...collection.hooks }\n\tif (stripPaths.length > 0) {\n\t\thooks.afterRead = [...(collection.hooks?.afterRead ?? []), makeStripPathsHook(stripPaths)]\n\t}\n\tif (queryableMarkers.size > 0) {\n\t\thooks.beforeOperation = [\n\t\t\tmakeHook(queryableMarkers),\n\t\t\t...(collection.hooks?.beforeOperation ?? []),\n\t\t]\n\t}\n\treturn { ...collection, hooks }\n}\n"],"mappings":";;;AAwBA,MAAM,iBAAiB,UACtB,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;AAEpE,MAAM,oBAAoB,OAAO,SAKO;CACvC,MAAM,EAAE,YAAY,QAAQ,SAAS,SAAS;CAC9C,MAAM,OAAO,MAAM,QAAQ,MAAM;CACjC,MAAM,UAAU,UACf,UAAU,OAAO,OAAO,YAAY,OAAO,KAAK,UAAU,OAAO,SAAS;CAG3E,MAAM,eAAe,UAA8B;EAMlD,QALc,MAAM,QAAQ,KAAK,IAC9B,QACA,OAAO,UAAU,WAChB,MAAM,MAAM,GAAG,EAAE,KAAK,SAAS,KAAK,KAAK,CAAC,IAC1C,CAAC,GACQ,IAAI,MAAM;CACxB;CACA,MAAM,YAAqC,CAAC;CAC5C,KAAK,MAAM,CAAC,UAAU,YAAY,OAAO,QAAQ,UAAU,GAC1D,QAAQ,UAAR;EACC,KAAK;GACJ,UAAU,SAAS,O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,GAAG,WAAW,MAAM;CAC5E,IAAI,WAAW,SAAS,GACvB,MAAM,YAAY,CAAC,GAAI,WAAW,OAAO,aAAa,CAAC,GAAI,mBAAmB,UAAU,CAAC;CAE1F,IAAI,iBAAiB,OAAO,GAC3B,MAAM,kBAAkB,CACvB,SAAS,gBAAgB,GACzB,GAAI,WAAW,OAAO,mBAAmB,CAAC,CAC3C;CAED,OAAO;EAAE,GAAG;EAAY;CAAM;AAC/B"}
1
+ {"version":3,"file":"queryRewrite.js","names":[],"sources":["../../../src/fields/encrypted/queryRewrite.ts"],"sourcesContent":["import type {\n\tCollectionAfterReadHook,\n\tCollectionBeforeOperationHook,\n\tCollectionConfig,\n\tGlobalAfterReadHook,\n\tGlobalConfig,\n\tPayloadRequest,\n\tWhere,\n} from 'payload'\nimport { computeBidx } from './crypto/bidx'\nimport type { KeyRing } from './crypto/keys'\nimport { contextMode, ringForRequest } from './hooks'\nimport { queryableOnly, scanEncryptedFields } from './scan'\nimport type { EncryptedFieldMarker } from './types'\n\ntype RingResolver = (marker: EncryptedFieldMarker) => Promise<KeyRing>\n\ntype UnsupportedWarn = (path: string, operator: string) => void\n\n/**\n * A blind index answers exact-match only. An unsupported operator is rewritten\n * to this sentinel so the query matches nothing: every real index value is a\n * 24-char base64url string, and a single space is not one. Exported for tests.\n */\nexport const BIDX_NO_MATCH = ' '\n\nconst isPlainObject = (value: unknown): value is Record<string, unknown> =>\n\ttypeof value === 'object' && value !== null && !Array.isArray(value)\n\nconst rewriteConstraint = async (args: {\n\tconstraint: Record<string, unknown>\n\tmarker: EncryptedFieldMarker\n\tringFor: RingResolver\n\twarn: (operator: string) => void\n}): Promise<Record<string, unknown>> => {\n\tconst { constraint, marker, ringFor, warn } = args\n\tconst ring = await ringFor(marker)\n\tconst toBidx = (value: unknown): unknown =>\n\t\tvalue === null ? null : computeBidx(value, ring.indexKey, marker.normalize)\n\t// Payload's REST layer delivers `in`/`not_in` as a comma-joined string, the\n\t// admin and Local API as an array; hash each element under either shape.\n\tconst toBidxArray = (value: unknown): unknown[] => {\n\t\tconst items = Array.isArray(value)\n\t\t\t? value\n\t\t\t: typeof value === 'string'\n\t\t\t\t? value.split(',').map((item) => item.trim())\n\t\t\t\t: []\n\t\treturn items.map(toBidx)\n\t}\n\tconst rewritten: Record<string, unknown> = {}\n\tfor (const [operator, operand] of Object.entries(constraint)) {\n\t\tswitch (operator) {\n\t\t\tcase 'equals':\n\t\t\t\trewritten.equals = toBidx(operand)\n\t\t\t\tbreak\n\t\t\tcase 'not_equals':\n\t\t\t\trewritten.not_equals = toBidx(operand)\n\t\t\t\tbreak\n\t\t\tcase 'in':\n\t\t\t\trewritten.in = toBidxArray(operand)\n\t\t\t\tbreak\n\t\t\tcase 'not_in':\n\t\t\t\trewritten.not_in = toBidxArray(operand)\n\t\t\t\tbreak\n\t\t\tcase 'exists':\n\t\t\t\t// The blind index is written iff the source has a value, so its\n\t\t\t\t// existence tracks the source's. The boolean passes through unhashed.\n\t\t\t\trewritten.exists = operand\n\t\t\t\tbreak\n\t\t\tdefault:\n\t\t\t\t// Substring, range, comparison, and geo operators cannot run over a\n\t\t\t\t// blind index. Match nothing rather than querying the ciphertext\n\t\t\t\t// column, which would read as a working filter while returning junk.\n\t\t\t\twarn(operator)\n\t\t\t\treturn { equals: BIDX_NO_MATCH }\n\t\t}\n\t}\n\treturn rewritten\n}\n\n/** Recursively rewrites queryable encrypted paths to their blind-index siblings. */\nexport const rewriteWhereForMarkers = async (args: {\n\tmarkers: ReadonlyMap<string, EncryptedFieldMarker>\n\tringFor: RingResolver\n\twarn?: UnsupportedWarn\n\twhere: Where\n}): Promise<Where> => {\n\tconst { markers, ringFor, warn = () => {}, where } = args\n\tconst out: Where = {}\n\tfor (const [key, value] of Object.entries(where)) {\n\t\tif ((key === 'and' || key === 'or') && Array.isArray(value)) {\n\t\t\tout[key] = await Promise.all(\n\t\t\t\tvalue.map((nested) =>\n\t\t\t\t\trewriteWhereForMarkers({ markers, ringFor, warn, where: nested as Where })\n\t\t\t\t)\n\t\t\t)\n\t\t\tcontinue\n\t\t}\n\t\tconst marker = markers.get(key)\n\t\tif (marker?.bidxName && isPlainObject(value)) {\n\t\t\tconst rewritten = await rewriteConstraint({\n\t\t\t\tconstraint: value,\n\t\t\t\tmarker,\n\t\t\t\tringFor,\n\t\t\t\twarn: (operator) => warn(key, operator),\n\t\t\t})\n\t\t\tconst bidxPath = key.includes('.')\n\t\t\t\t? `${key.slice(0, key.lastIndexOf('.') + 1)}${marker.bidxName}`\n\t\t\t\t: marker.bidxName\n\t\t\tout[bidxPath] = { ...(out[bidxPath] as Record<string, unknown>), ...rewritten }\n\t\t\tcontinue\n\t\t}\n\t\tout[key] = value as Where[string]\n\t}\n\treturn out\n}\n\nconst makeHook = (\n\tmarkers: ReadonlyMap<string, EncryptedFieldMarker>\n): CollectionBeforeOperationHook => {\n\treturn async ({ args, req }) => {\n\t\tif (isPlainObject(args) && 'where' in args && isPlainObject(args.where)) {\n\t\t\tconst payloadReq = req as PayloadRequest\n\t\t\tconst where = await rewriteWhereForMarkers({\n\t\t\t\tmarkers,\n\t\t\t\tringFor: (marker) => ringForRequest(payloadReq, marker),\n\t\t\t\twarn: (path, operator) =>\n\t\t\t\t\tpayloadReq.payload?.logger?.warn?.(\n\t\t\t\t\t\t`@10x-media/fields: operator '${operator}' cannot run on the encrypted field '${path}'. Blind-index filtering supports exact match only (equals, not_equals, in, not_in, exists); this constraint will match nothing.`\n\t\t\t\t\t),\n\t\t\t\twhere: args.where as Where,\n\t\t\t})\n\t\t\treturn { ...args, where }\n\t\t}\n\t\treturn args\n\t}\n}\n\nconst bidxPathFor = (path: string, bidxName: string): string =>\n\tpath.includes('.') ? `${path.slice(0, path.lastIndexOf('.') + 1)}${bidxName}` : bidxName\n\nconst deleteAtPath = (doc: Record<string, unknown>, path: string): void => {\n\tconst segments = path.split('.')\n\tlet node: Record<string, unknown> = doc\n\tfor (const segment of segments.slice(0, -1)) {\n\t\tconst next = node[segment]\n\t\tif (!next || typeof next !== 'object') {\n\t\t\treturn\n\t\t}\n\t\tnode = next as Record<string, unknown>\n\t}\n\tdelete node[segments[segments.length - 1] as string]\n}\n\n/**\n * Removes server-only encrypted paths from read results: blind-index hashes (so\n * the keyed index value never leaves the server), richText ciphertext siblings\n * (opaque strings the virtual editor field replaces), and write-only fields\n * (whose sealed value passes afterRead untouched and must not surface at all).\n * `admin.hidden` keeps the siblings readable by the plugin's own hooks but,\n * unlike top-level `hidden`, does not strip them from responses.\n */\nconst makeStripPathsHook = (paths: string[]): CollectionAfterReadHook & GlobalAfterReadHook => {\n\treturn ({ context, doc }) => {\n\t\t// Bulk utilities (rotate/adopt/remove) read via pageThrough in `raw`\n\t\t// context and need the ciphertext + blind-index siblings; stripping them\n\t\t// here would make key rotation silently skip every richText field. Only\n\t\t// strip on normal reads.\n\t\tif (contextMode(context as Record<string, unknown>)) {\n\t\t\treturn doc\n\t\t}\n\t\tfor (const path of paths) {\n\t\t\tdeleteAtPath(doc as Record<string, unknown>, path)\n\t\t}\n\t\treturn doc\n\t}\n}\n\n/** Response paths a normal read must not surface, per marker kind. */\nconst stripPathsFor = (markers: ReadonlyMap<string, EncryptedFieldMarker>): string[] => {\n\tconst paths: string[] = []\n\tfor (const [path, marker] of markers) {\n\t\tif (marker.queryable && marker.bidxName) {\n\t\t\tpaths.push(bidxPathFor(path, marker.bidxName))\n\t\t}\n\t\t// richText stores its ciphertext under the marker's own scan path\n\t\t// (`${name}_encrypted`); the write-only path IS the stored field itself.\n\t\tif (marker.sourceType === 'richText' || marker.writeOnly) {\n\t\t\tpaths.push(path)\n\t\t}\n\t}\n\treturn paths\n}\n\n/**\n * Attaches the blind-index where-rewrite and response stripper to a collection.\n * The fields() plugin applies this to every collection automatically; call it\n * directly only when using encryptedField() standalone without the plugin.\n */\nexport const withEncryptedQueryRewrite = (collection: CollectionConfig): CollectionConfig => {\n\tconst allMarkers = scanEncryptedFields(collection.fields)\n\tconst queryableMarkers = queryableOnly(allMarkers)\n\tconst stripPaths = stripPathsFor(allMarkers)\n\tif (queryableMarkers.size === 0 && stripPaths.length === 0) {\n\t\treturn collection\n\t}\n\tconst hooks: NonNullable<CollectionConfig['hooks']> = { ...collection.hooks }\n\tif (stripPaths.length > 0) {\n\t\thooks.afterRead = [...(collection.hooks?.afterRead ?? []), makeStripPathsHook(stripPaths)]\n\t}\n\tif (queryableMarkers.size > 0) {\n\t\thooks.beforeOperation = [\n\t\t\tmakeHook(queryableMarkers),\n\t\t\t...(collection.hooks?.beforeOperation ?? []),\n\t\t]\n\t}\n\treturn { ...collection, hooks }\n}\n\n/**\n * Attaches the response stripper to a global. Globals take no `where`, so this\n * is the strip alone: blind-index hashes, richText ciphertext siblings, and\n * write-only fields never surface in a read result. The fields() plugin applies\n * this to every global automatically; call it directly only when using\n * encryptedField() standalone without the plugin.\n */\nexport const withEncryptedResponseStrip = (global: GlobalConfig): GlobalConfig => {\n\tconst stripPaths = stripPathsFor(scanEncryptedFields(global.fields))\n\tif (stripPaths.length === 0) {\n\t\treturn global\n\t}\n\treturn {\n\t\t...global,\n\t\thooks: {\n\t\t\t...global.hooks,\n\t\t\tafterRead: [...(global.hooks?.afterRead ?? []), makeStripPathsHook(stripPaths)],\n\t\t},\n\t}\n}\n"],"mappings":";;;AA0BA,MAAM,iBAAiB,UACtB,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;AAEpE,MAAM,oBAAoB,OAAO,SAKO;CACvC,MAAM,EAAE,YAAY,QAAQ,SAAS,SAAS;CAC9C,MAAM,OAAO,MAAM,QAAQ,MAAM;CACjC,MAAM,UAAU,UACf,UAAU,OAAO,OAAO,YAAY,OAAO,KAAK,UAAU,OAAO,SAAS;CAG3E,MAAM,eAAe,UAA8B;EAMlD,QALc,MAAM,QAAQ,KAAK,IAC9B,QACA,OAAO,UAAU,WAChB,MAAM,MAAM,GAAG,EAAE,KAAK,SAAS,KAAK,KAAK,CAAC,IAC1C,CAAC,GACQ,IAAI,MAAM;CAC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Aa,oBAAoB,WAAW,MAAM;CACxD,MAAM,mBAAmB,cAAc,UAAU;CACjD,MAAM,aAAa,cAAc,UAAU;CAC3C,IAAI,iBAAiB,SAAS,KAAK,WAAW,WAAW,GACxD,OAAO;CAER,MAAM,QAAgD,EAAE,GAAG,WAAW,MAAM;CAC5E,IAAI,WAAW,SAAS,GACvB,MAAM,YAAY,CAAC,GAAI,WAAW,OAAO,aAAa,CAAC,GAAI,mBAAmB,UAAU,CAAC;CAE1F,IAAI,iBAAiB,OAAO,GAC3B,MAAM,kBAAkB,CACvB,SAAS,gBAAgB,GACzB,GAAI,WAAW,OAAO,mBAAmB,CAAC,CAC3C;CAED,OAAO;EAAE,GAAG;EAAY;CAAM;AAC/B;;;;;;;;AASA,MAAa,8BAA8B,WAAuC;CACjF,MAAM,aAAa,cAAc,oBAAoB,OAAO,MAAM,CAAC;CACnE,IAAI,WAAW,WAAW,GACzB,OAAO;CAER,OAAO;EACN,GAAG;EACH,OAAO;GACN,GAAG,OAAO;GACV,WAAW,CAAC,GAAI,OAAO,OAAO,aAAa,CAAC,GAAI,mBAAmB,UAAU,CAAC;EAC/E;CACD;AACD"}
@@ -0,0 +1,24 @@
1
+ import { PayloadRequest } from "payload";
2
+
3
+ //#region src/fields/encrypted/rawRead.d.ts
4
+ /**
5
+ * Run reads with encrypted fields left as stored ciphertext, then put the
6
+ * request back exactly as it was. Inside the window the write-only response
7
+ * strip and the decrypt-on-read step stand down for every encrypted field the
8
+ * reads touch, so the caller's own queries return `pfe1.…` wire strings for
9
+ * `decryptFieldValue`. The previous mode is restored rather than cleared, so a
10
+ * window nested in another does not close it.
11
+ *
12
+ * The request's dataloader is swapped for a private one and restored too: its
13
+ * cache key does not include the context, so a related document populated at
14
+ * `depth > 0` in here would otherwise be cached as ciphertext and served that
15
+ * way to an ordinary read later on the same request.
16
+ *
17
+ * Two caller constraints: the reads inside must be given this same `req` (the
18
+ * mode travels on the request), and the window is not a concurrency boundary
19
+ * (an unrelated read overlapping it sees ciphertext too).
20
+ */
21
+ declare const withRawEncrypted: <T>(req: PayloadRequest, read: () => Promise<T>) => Promise<T>;
22
+ //#endregion
23
+ export { withRawEncrypted };
24
+ //# sourceMappingURL=rawRead.d.ts.map
@@ -0,0 +1,40 @@
1
+ import { ENCRYPTED_CONTEXT_KEY } from "./types.js";
2
+ import { getDataLoader } from "payload";
3
+ //#region src/fields/encrypted/rawRead.ts
4
+ /**
5
+ * Run reads with encrypted fields left as stored ciphertext, then put the
6
+ * request back exactly as it was. Inside the window the write-only response
7
+ * strip and the decrypt-on-read step stand down for every encrypted field the
8
+ * reads touch, so the caller's own queries return `pfe1.…` wire strings for
9
+ * `decryptFieldValue`. The previous mode is restored rather than cleared, so a
10
+ * window nested in another does not close it.
11
+ *
12
+ * The request's dataloader is swapped for a private one and restored too: its
13
+ * cache key does not include the context, so a related document populated at
14
+ * `depth > 0` in here would otherwise be cached as ciphertext and served that
15
+ * way to an ordinary read later on the same request.
16
+ *
17
+ * Two caller constraints: the reads inside must be given this same `req` (the
18
+ * mode travels on the request), and the window is not a concurrency boundary
19
+ * (an unrelated read overlapping it sees ciphertext too).
20
+ */
21
+ const withRawEncrypted = async (req, read) => {
22
+ if (!req.context) req.context = {};
23
+ const hadMode = ENCRYPTED_CONTEXT_KEY in req.context;
24
+ const previousMode = req.context[ENCRYPTED_CONTEXT_KEY];
25
+ const previousLoader = req.payloadDataLoader;
26
+ try {
27
+ req.context[ENCRYPTED_CONTEXT_KEY] = "raw";
28
+ req.payloadDataLoader = getDataLoader(req);
29
+ return await read();
30
+ } finally {
31
+ const context = req.context ?? {};
32
+ if (hadMode) context[ENCRYPTED_CONTEXT_KEY] = previousMode;
33
+ else delete context[ENCRYPTED_CONTEXT_KEY];
34
+ req.payloadDataLoader = previousLoader;
35
+ }
36
+ };
37
+ //#endregion
38
+ export { withRawEncrypted };
39
+
40
+ //# sourceMappingURL=rawRead.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"rawRead.js","names":[],"sources":["../../../src/fields/encrypted/rawRead.ts"],"sourcesContent":["import { getDataLoader, type PayloadRequest } from 'payload'\nimport { ENCRYPTED_CONTEXT_KEY } from './types'\n\n/**\n * Run reads with encrypted fields left as stored ciphertext, then put the\n * request back exactly as it was. Inside the window the write-only response\n * strip and the decrypt-on-read step stand down for every encrypted field the\n * reads touch, so the caller's own queries return `pfe1.…` wire strings for\n * `decryptFieldValue`. The previous mode is restored rather than cleared, so a\n * window nested in another does not close it.\n *\n * The request's dataloader is swapped for a private one and restored too: its\n * cache key does not include the context, so a related document populated at\n * `depth > 0` in here would otherwise be cached as ciphertext and served that\n * way to an ordinary read later on the same request.\n *\n * Two caller constraints: the reads inside must be given this same `req` (the\n * mode travels on the request), and the window is not a concurrency boundary\n * (an unrelated read overlapping it sees ciphertext too).\n */\nexport const withRawEncrypted = async <T>(\n\treq: PayloadRequest,\n\tread: () => Promise<T>\n): Promise<T> => {\n\t// A hand-built request (tests, jobs) may carry no context at all, and the\n\t// mode has nowhere to live without one.\n\tif (!req.context) {\n\t\treq.context = {}\n\t}\n\tconst hadMode = ENCRYPTED_CONTEXT_KEY in req.context\n\tconst previousMode = req.context[ENCRYPTED_CONTEXT_KEY]\n\tconst previousLoader = req.payloadDataLoader\n\ttry {\n\t\treq.context[ENCRYPTED_CONTEXT_KEY] = 'raw'\n\t\treq.payloadDataLoader = getDataLoader(req)\n\t\treturn await read()\n\t} finally {\n\t\t// Read `req.context` again rather than closing over it: a local API\n\t\t// operation replaces the object with a merged copy, so the property has to\n\t\t// be restored on whichever object is current.\n\t\tconst context = req.context ?? {}\n\t\tif (hadMode) {\n\t\t\tcontext[ENCRYPTED_CONTEXT_KEY] = previousMode\n\t\t} else {\n\t\t\tdelete context[ENCRYPTED_CONTEXT_KEY]\n\t\t}\n\t\treq.payloadDataLoader = previousLoader\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAoBA,MAAa,mBAAmB,OAC/B,KACA,SACgB;CAGhB,IAAI,CAAC,IAAI,SACR,IAAI,UAAU,CAAC;CAEhB,MAAM,UAAU,yBAAyB,IAAI;CAC7C,MAAM,eAAe,IAAI,QAAQ;CACjC,MAAM,iBAAiB,IAAI;CAC3B,IAAI;EACH,IAAI,QAAQ,yBAAyB;EACrC,IAAI,oBAAoB,cAAc,GAAG;EACzC,OAAO,MAAM,KAAK;CACnB,UAAU;EAIT,MAAM,UAAU,IAAI,WAAW,CAAC;EAChC,IAAI,SACH,QAAQ,yBAAyB;OAEjC,OAAO,QAAQ;EAEhB,IAAI,oBAAoB;CACzB;AACD"}
@@ -6,7 +6,7 @@ import { getEncryptedMarker } from "./types.js";
6
6
  * Fields inside arrays and blocks encrypt at runtime but are excluded here:
7
7
  * query rewrite and bulk utilities do not address per-row paths in v1.
8
8
  */
9
- const scanEncryptedFields = (fields, prefix = "") => {
9
+ const walk = (fields, prefix) => {
10
10
  const found = /* @__PURE__ */ new Map();
11
11
  for (const field of fields ?? []) {
12
12
  if ("name" in field && typeof field.name === "string") {
@@ -16,15 +16,32 @@ const scanEncryptedFields = (fields, prefix = "") => {
16
16
  continue;
17
17
  }
18
18
  }
19
- if (field.type === "group" && "name" in field && field.name) for (const [path, marker] of scanEncryptedFields(field.fields, `${prefix}${field.name}.`)) found.set(path, marker);
20
- else if (field.type === "row" || field.type === "collapsible") for (const [path, marker] of scanEncryptedFields(field.fields, prefix)) found.set(path, marker);
19
+ if (field.type === "group" && "name" in field && field.name) for (const [path, marker] of walk(field.fields, `${prefix}${field.name}.`)) found.set(path, marker);
20
+ else if (field.type === "row" || field.type === "collapsible") for (const [path, marker] of walk(field.fields, prefix)) found.set(path, marker);
21
21
  else if (field.type === "tabs") for (const tab of field.tabs) {
22
22
  const tabPrefix = "name" in tab && tab.name ? `${prefix}${tab.name}.` : prefix;
23
- for (const [path, marker] of scanEncryptedFields(tab.fields, tabPrefix)) found.set(path, marker);
23
+ for (const [path, marker] of walk(tab.fields, tabPrefix)) found.set(path, marker);
24
24
  }
25
25
  }
26
26
  return found;
27
27
  };
28
+ /**
29
+ * Cached per field array. Sanitized configs are built once and their field
30
+ * arrays live for the process, so the scan result cannot go stale; a WeakMap
31
+ * keyed on the array lets a discarded config (every booted Payload in a test
32
+ * run) be collected with it.
33
+ */
34
+ const cache = /* @__PURE__ */ new WeakMap();
35
+ const EMPTY = /* @__PURE__ */ new Map();
36
+ /** Encrypted markers by dot path for one schema's fields. */
37
+ const scanEncryptedFields = (fields) => {
38
+ if (!fields) return EMPTY;
39
+ const hit = cache.get(fields);
40
+ if (hit) return hit;
41
+ const scanned = walk(fields, "");
42
+ cache.set(fields, scanned);
43
+ return scanned;
44
+ };
28
45
  const queryableOnly = (markers) => {
29
46
  const out = /* @__PURE__ */ new Map();
30
47
  for (const [path, marker] of markers) if (marker.queryable && marker.bidxName) out.set(path, marker);
@@ -1 +1 @@
1
- {"version":3,"file":"scan.js","names":[],"sources":["../../../src/fields/encrypted/scan.ts"],"sourcesContent":["import type { Field } from 'payload'\nimport { type EncryptedFieldMarker, getEncryptedMarker } from './types'\n\n/**\n * Walks named containers (group, named tabs) and layout containers (row,\n * collapsible, unnamed tabs) collecting encrypted markers by dot path.\n * Fields inside arrays and blocks encrypt at runtime but are excluded here:\n * query rewrite and bulk utilities do not address per-row paths in v1.\n */\nexport const scanEncryptedFields = (\n\tfields: Field[] | undefined,\n\tprefix = ''\n): Map<string, EncryptedFieldMarker> => {\n\tconst found = new Map<string, EncryptedFieldMarker>()\n\tfor (const field of fields ?? []) {\n\t\tif ('name' in field && typeof field.name === 'string') {\n\t\t\tconst marker = getEncryptedMarker(field as { custom?: Record<string, unknown> })\n\t\t\tif (marker) {\n\t\t\t\tfound.set(`${prefix}${field.name}`, marker)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t\tif (field.type === 'group' && 'name' in field && field.name) {\n\t\t\tfor (const [path, marker] of scanEncryptedFields(field.fields, `${prefix}${field.name}.`)) {\n\t\t\t\tfound.set(path, marker)\n\t\t\t}\n\t\t} else if (field.type === 'row' || field.type === 'collapsible') {\n\t\t\tfor (const [path, marker] of scanEncryptedFields(field.fields, prefix)) {\n\t\t\t\tfound.set(path, marker)\n\t\t\t}\n\t\t} else if (field.type === 'tabs') {\n\t\t\tfor (const tab of field.tabs) {\n\t\t\t\tconst tabPrefix = 'name' in tab && tab.name ? `${prefix}${tab.name}.` : prefix\n\t\t\t\tfor (const [path, marker] of scanEncryptedFields(tab.fields, tabPrefix)) {\n\t\t\t\t\tfound.set(path, marker)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn found\n}\n\nexport const queryableOnly = (\n\tmarkers: Map<string, EncryptedFieldMarker>\n): Map<string, EncryptedFieldMarker> => {\n\tconst out = new Map<string, EncryptedFieldMarker>()\n\tfor (const [path, marker] of markers) {\n\t\tif (marker.queryable && marker.bidxName) {\n\t\t\tout.set(path, marker)\n\t\t}\n\t}\n\treturn out\n}\n"],"mappings":";;;;;;;;AASA,MAAa,uBACZ,QACA,SAAS,OAC8B;CACvC,MAAM,wBAAQ,IAAI,IAAkC;CACpD,KAAK,MAAM,SAAS,UAAU,CAAC,GAAG;EACjC,IAAI,UAAU,SAAS,OAAO,MAAM,SAAS,UAAU;GACtD,MAAM,SAAS,mBAAmB,KAA6C;GAC/E,IAAI,QAAQ;IACX,MAAM,IAAI,GAAG,SAAS,MAAM,QAAQ,MAAM;IAC1C;GACD;EACD;EACA,IAAI,MAAM,SAAS,WAAW,UAAU,SAAS,MAAM,MACtD,KAAK,MAAM,CAAC,MAAM,WAAW,oBAAoB,MAAM,QAAQ,GAAG,SAAS,MAAM,KAAK,EAAE,GACvF,MAAM,IAAI,MAAM,MAAM;OAEjB,IAAI,MAAM,SAAS,SAAS,MAAM,SAAS,eACjD,KAAK,MAAM,CAAC,MAAM,WAAW,oBAAoB,MAAM,QAAQ,MAAM,GACpE,MAAM,IAAI,MAAM,MAAM;OAEjB,IAAI,MAAM,SAAS,QACzB,KAAK,MAAM,OAAO,MAAM,MAAM;GAC7B,MAAM,YAAY,UAAU,OAAO,IAAI,OAAO,GAAG,SAAS,IAAI,KAAK,KAAK;GACxE,KAAK,MAAM,CAAC,MAAM,WAAW,oBAAoB,IAAI,QAAQ,SAAS,GACrE,MAAM,IAAI,MAAM,MAAM;EAExB;CAEF;CACA,OAAO;AACR;AAEA,MAAa,iBACZ,YACuC;CACvC,MAAM,sBAAM,IAAI,IAAkC;CAClD,KAAK,MAAM,CAAC,MAAM,WAAW,SAC5B,IAAI,OAAO,aAAa,OAAO,UAC9B,IAAI,IAAI,MAAM,MAAM;CAGtB,OAAO;AACR"}
1
+ {"version":3,"file":"scan.js","names":[],"sources":["../../../src/fields/encrypted/scan.ts"],"sourcesContent":["import type { Field } from 'payload'\nimport { type EncryptedFieldMarker, getEncryptedMarker } from './types'\n\n/**\n * Walks named containers (group, named tabs) and layout containers (row,\n * collapsible, unnamed tabs) collecting encrypted markers by dot path.\n * Fields inside arrays and blocks encrypt at runtime but are excluded here:\n * query rewrite and bulk utilities do not address per-row paths in v1.\n */\nconst walk = (fields: Field[] | undefined, prefix: string): Map<string, EncryptedFieldMarker> => {\n\tconst found = new Map<string, EncryptedFieldMarker>()\n\tfor (const field of fields ?? []) {\n\t\tif ('name' in field && typeof field.name === 'string') {\n\t\t\tconst marker = getEncryptedMarker(field as { custom?: Record<string, unknown> })\n\t\t\tif (marker) {\n\t\t\t\tfound.set(`${prefix}${field.name}`, marker)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t\tif (field.type === 'group' && 'name' in field && field.name) {\n\t\t\tfor (const [path, marker] of walk(field.fields, `${prefix}${field.name}.`)) {\n\t\t\t\tfound.set(path, marker)\n\t\t\t}\n\t\t} else if (field.type === 'row' || field.type === 'collapsible') {\n\t\t\tfor (const [path, marker] of walk(field.fields, prefix)) {\n\t\t\t\tfound.set(path, marker)\n\t\t\t}\n\t\t} else if (field.type === 'tabs') {\n\t\t\tfor (const tab of field.tabs) {\n\t\t\t\tconst tabPrefix = 'name' in tab && tab.name ? `${prefix}${tab.name}.` : prefix\n\t\t\t\tfor (const [path, marker] of walk(tab.fields, tabPrefix)) {\n\t\t\t\t\tfound.set(path, marker)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn found\n}\n\n/**\n * Cached per field array. Sanitized configs are built once and their field\n * arrays live for the process, so the scan result cannot go stale; a WeakMap\n * keyed on the array lets a discarded config (every booted Payload in a test\n * run) be collected with it.\n */\nconst cache = new WeakMap<Field[], ReadonlyMap<string, EncryptedFieldMarker>>()\n\nconst EMPTY: ReadonlyMap<string, EncryptedFieldMarker> = new Map()\n\n/** Encrypted markers by dot path for one schema's fields. */\nexport const scanEncryptedFields = (\n\tfields: Field[] | undefined\n): ReadonlyMap<string, EncryptedFieldMarker> => {\n\tif (!fields) {\n\t\treturn EMPTY\n\t}\n\tconst hit = cache.get(fields)\n\tif (hit) {\n\t\treturn hit\n\t}\n\tconst scanned = walk(fields, '')\n\tcache.set(fields, scanned)\n\treturn scanned\n}\n\nexport const queryableOnly = (\n\tmarkers: ReadonlyMap<string, EncryptedFieldMarker>\n): ReadonlyMap<string, EncryptedFieldMarker> => {\n\tconst out = new Map<string, EncryptedFieldMarker>()\n\tfor (const [path, marker] of markers) {\n\t\tif (marker.queryable && marker.bidxName) {\n\t\t\tout.set(path, marker)\n\t\t}\n\t}\n\treturn out\n}\n"],"mappings":";;;;;;;;AASA,MAAM,QAAQ,QAA6B,WAAsD;CAChG,MAAM,wBAAQ,IAAI,IAAkC;CACpD,KAAK,MAAM,SAAS,UAAU,CAAC,GAAG;EACjC,IAAI,UAAU,SAAS,OAAO,MAAM,SAAS,UAAU;GACtD,MAAM,SAAS,mBAAmB,KAA6C;GAC/E,IAAI,QAAQ;IACX,MAAM,IAAI,GAAG,SAAS,MAAM,QAAQ,MAAM;IAC1C;GACD;EACD;EACA,IAAI,MAAM,SAAS,WAAW,UAAU,SAAS,MAAM,MACtD,KAAK,MAAM,CAAC,MAAM,WAAW,KAAK,MAAM,QAAQ,GAAG,SAAS,MAAM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