@10x-media/fields 0.1.0-beta.4 → 0.1.0-beta.5

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 (63) hide show
  1. package/CHANGELOG.md +32 -0
  2. package/README.md +2 -0
  3. package/dist/exports/encrypted.d.ts +7 -4
  4. package/dist/exports/encrypted.js +6 -3
  5. package/dist/fields/encrypted/boot.js +2 -1
  6. package/dist/fields/encrypted/boot.js.map +1 -1
  7. package/dist/fields/encrypted/components/EncryptedInput.js +4 -1
  8. package/dist/fields/encrypted/components/EncryptedInput.js.map +1 -1
  9. package/dist/fields/encrypted/components/EncryptedTextarea.js +6 -2
  10. package/dist/fields/encrypted/components/EncryptedTextarea.js.map +1 -1
  11. package/dist/fields/encrypted/components/ProtectedCell.d.ts +15 -6
  12. package/dist/fields/encrypted/components/ProtectedCell.js +37 -8
  13. package/dist/fields/encrypted/components/ProtectedCell.js.map +1 -1
  14. package/dist/fields/encrypted/components/ProtectedField.css +134 -39
  15. package/dist/fields/encrypted/components/ProtectedField.d.ts +3 -0
  16. package/dist/fields/encrypted/components/ProtectedField.js +14 -0
  17. package/dist/fields/encrypted/components/ProtectedField.js.map +1 -1
  18. package/dist/fields/encrypted/components/WriteOnlyActions.js +65 -0
  19. package/dist/fields/encrypted/components/WriteOnlyActions.js.map +1 -0
  20. package/dist/fields/encrypted/components/WriteOnlyField.js +286 -0
  21. package/dist/fields/encrypted/components/WriteOnlyField.js.map +1 -0
  22. package/dist/fields/encrypted/components/writeOnlyIntent.js +69 -0
  23. package/dist/fields/encrypted/components/writeOnlyIntent.js.map +1 -0
  24. package/dist/fields/encrypted/crypto/wire.d.ts +10 -1
  25. package/dist/fields/encrypted/crypto/wire.js +1 -1
  26. package/dist/fields/encrypted/encryptedField.js +63 -6
  27. package/dist/fields/encrypted/encryptedField.js.map +1 -1
  28. package/dist/fields/encrypted/generateSecret.d.ts +10 -0
  29. package/dist/fields/encrypted/generateSecret.js +41 -0
  30. package/dist/fields/encrypted/generateSecret.js.map +1 -0
  31. package/dist/fields/encrypted/hint.js +67 -0
  32. package/dist/fields/encrypted/hint.js.map +1 -0
  33. package/dist/fields/encrypted/hooks.js +59 -31
  34. package/dist/fields/encrypted/hooks.js.map +1 -1
  35. package/dist/fields/encrypted/queryRewrite.d.ts +10 -2
  36. package/dist/fields/encrypted/queryRewrite.js +34 -8
  37. package/dist/fields/encrypted/queryRewrite.js.map +1 -1
  38. package/dist/fields/encrypted/rawRead.d.ts +24 -0
  39. package/dist/fields/encrypted/rawRead.js +40 -0
  40. package/dist/fields/encrypted/rawRead.js.map +1 -0
  41. package/dist/fields/encrypted/scan.js +21 -4
  42. package/dist/fields/encrypted/scan.js.map +1 -1
  43. package/dist/fields/encrypted/types.d.ts +67 -2
  44. package/dist/fields/encrypted/types.js +8 -1
  45. package/dist/fields/encrypted/types.js.map +1 -1
  46. package/dist/fields/encrypted/utils/decryptAllData.js +2 -2
  47. package/dist/fields/encrypted/utils/decryptAllData.js.map +1 -1
  48. package/dist/fields/encrypted/utils/decryptFieldValue.d.ts +30 -0
  49. package/dist/fields/encrypted/utils/decryptFieldValue.js +56 -0
  50. package/dist/fields/encrypted/utils/decryptFieldValue.js.map +1 -0
  51. package/dist/fields/encrypted/utils/readEncryptedField.d.ts +51 -0
  52. package/dist/fields/encrypted/utils/readEncryptedField.js +96 -0
  53. package/dist/fields/encrypted/utils/readEncryptedField.js.map +1 -0
  54. package/dist/index.js +2 -1
  55. package/dist/index.js.map +1 -1
  56. package/dist/translations/de.js +8 -1
  57. package/dist/translations/de.js.map +1 -1
  58. package/dist/translations/en.js +8 -1
  59. package/dist/translations/en.js.map +1 -1
  60. package/dist/translations/keys.d.ts +7 -0
  61. package/dist/translations/keys.js +8 -1
  62. package/dist/translations/keys.js.map +1 -1
  63. package/package.json +6 -6
@@ -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;CAAM,OAAO;CAAW,gBAAgB,GAAG;AAAC,IAAI,CAAC,MAAM,OAAO,SAAS,CAC5F;;;;;;AAOD,MAAa,qBACZ,QACA,MACA,QACc;CACd,IAAI,CAAC,OAAO,WACX,OAAO,CAAC,SAAS,CAAC,MAAM,OAAO,SAAS,CAAC,CAAC;CAE3C,MAAM,QAAQ,IAAI,QAAQ,OAAO,eAC9B,IAAI,QAAQ,OAAO,aAAa,cAChC,CAAC,cAAc,IAAI,QAAQ,MAAM,CAAC;CACrC,MAAM,QAAQ,gBAAgB,GAAG;CAEj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O,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,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,M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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, Where } 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, Where } 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,OAAO,OAAO;GACjC;EACD,KAAK;GACJ,UAAU,aAAa,OAAO,OAAO;GACrC;EACD,KAAK;GACJ,UAAU,KAAK,YAAY,OAAO;GAClC;EACD,KAAK;GACJ,UAAU,SAAS,YAAY,OAAO;GACtC;EACD,KAAK;GAGJ,UAAU,SAAS;GACnB;EACD;GAIC,KAAK,QAAQ;GACb,OAAO,EAAE,QAAA,IAAsB;CACjC;CAED,OAAO;AACR;;AAGA,MAAa,yBAAyB,OAAO,SAKvB;CACrB,MAAM,EAAE,SAAS,SAAS,aAAa,CA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ewrite.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;CACxB;CACA,MAAM,YAAqC,CAAC;CAC5C,KAAK,MAAM,CAAC,UAAU,YAAY,OAAO,QAAQ,UAAU,GAC1D,QAAQ,UAAR;EACC,KAAK;GACJ,UAAU,SAAS,OAAO,OAAO;GACjC;EACD,KAAK;GACJ,UAAU,aAAa,OAAO,OAAO;GACrC;EACD,KAAK;GACJ,UAAU,KAAK,YAAY,OAAO;GAClC;EACD,KAAK;GACJ,UAAU,SAAS,YAAY,OAAO;GACtC;EACD,KAAK;GAGJ,UAAU,SAAS;GACnB;EACD;GAIC,KAA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ACvB,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,KAAK,EAAE,GACxE,MAAM,IAAI,MAAM,MAAM;OAEjB,IAAI,MAAM,SAAS,SAAS,MAAM,SAAS,eACjD,KAAK,MAAM,CAAC,MAAM,WAAW,KAAK,MAAM,QAAQ,MAAM,GACrD,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,KAAK,IAAI,QAAQ,SAAS,GACtD,MAAM,IAAI,MAAM,MAAM;EAExB;CAEF;CACA,OAAO;AACR;;;;;;;AAQA,MAAM,wBAAQ,IAAI,QAA4D;AAE9E,MAAM,wBAAmD,IAAI,IAAI;;AAGjE,MAAa,uBACZ,WAC+C;CAC/C,IAAI,CAAC,QACJ,OAAO;CAER,MAAM,MAAM,MAAM,IAAI,MAAM;CAC5B,IAAI,KACH,OAAO;CAER,MAAM,UAAU,KAAK,QAAQ,EAAE;CAC/B,MAAM,IAAI,QAAQ,OAAO;CACzB,OAAO;AACR;AAEA,MAAa,iBACZ,YAC+C;CAC/C,MAAM,sBAAM,IAAI,IAAkC;CAClD,KAAK,MAAM,CAAC,MAAM,WAAW,SAC5B,IAAI,OAAO,aAAa,OAAO,UAC9B,IAAI,IAAI,MAAM,MAAM;CAGtB,OAAO;AACR"}
@@ -4,8 +4,63 @@ import { CheckboxField, CodeField, DateField, EmailField, JSONField, NumberField
4
4
  //#region src/fields/encrypted/types.d.ts
5
5
  type EncryptedSourceField = CheckboxField | CodeField | DateField | EmailField | JSONField | NumberField | PointField | RadioField | RichTextField | SelectField | TextareaField | TextField;
6
6
  type EncryptedSourceType = EncryptedSourceField['type'];
7
- type EncryptedProtection = 'masked' | 'none';
7
+ /**
8
+ * Confidentiality ladder for the admin and API surface. `'none'` renders the
9
+ * native component with the value visible; `'masked'` (default) conceals behind
10
+ * dots with a reveal toggle; `'writeOnly'` additionally strips the field from
11
+ * every read result (REST, GraphQL, Local API) so the plaintext never leaves
12
+ * the server. Write-only values are read deliberately via `readEncryptedField`
13
+ * or `decryptFieldValue`.
14
+ */
15
+ type EncryptedProtection = 'masked' | 'none' | 'writeOnly';
16
+ /**
17
+ * Identification hint for a write-only field: how many leading and trailing
18
+ * plaintext characters to store beside the ciphertext at seal time (never
19
+ * derived by decrypting on read). `prefix + suffix` is capped at 32, enough to
20
+ * carry a constant format prefix (`sk_live_`, `whsec_`) and still say which
21
+ * key this is.
22
+ *
23
+ * The cap is the blunt guard. What decides whether a hint is stored at all is
24
+ * the value being sliced: it must keep at least as many characters hidden as
25
+ * the hint exposes, and at least 8 either way. So one config can sit on a
26
+ * collection holding both long tokens and short ones, hinting the first and
27
+ * silently declining the second, rather than exposing half of it.
28
+ */
29
+ interface EncryptedHintConfig {
30
+ prefix?: number;
31
+ suffix?: number;
32
+ }
33
+ /**
34
+ * Generator for a write-only field's admin Generate action. `true` uses the
35
+ * default: 32 chars of crypto-random base62. Values are generated client-side
36
+ * in the form, so a generated secret is visible and copyable exactly until
37
+ * save, then never again.
38
+ */
39
+ interface EncryptedGenerateConfig {
40
+ /** Generated length excluding the prefix. Integer in [8, 128], rejected otherwise; default 32. */
41
+ length?: number;
42
+ /** Literal prefix, e.g. 'whsec_'. Counts toward the hint but not `length`. */
43
+ prefix?: string;
44
+ /** Alphabet to sample from: 10 to 256 distinct code points (duplicates collapse). Default base62. */
45
+ charset?: string;
46
+ }
8
47
  interface EncryptedFieldOptions {
48
+ /**
49
+ * Pins the first component of the ciphertext's AAD binding, which otherwise
50
+ * is the collection or global slug. For a field on a collection whose slug a
51
+ * consumer can configure (a plugin-owned collection), the slug is a poor
52
+ * binding: renaming it makes every stored value fail authentication, and no
53
+ * utility can recover them because reads resolve the binding from the
54
+ * current slug too. A pinned scope survives the rename.
55
+ *
56
+ * Must not contain `.` (the AAD component separator) and must be unique per
57
+ * logical schema: two fields of the same name sharing a scope share a
58
+ * binding, which widens the documented same-field ciphertext portability
59
+ * across their collections. Decide it before data exists; changing it later
60
+ * is a re-keying event, and stored values become unreadable exactly as a
61
+ * slug rename would have made them.
62
+ */
63
+ aadScope?: string;
9
64
  keys?: KeysConfig;
10
65
  /**
11
66
  * Cosmetic number of dots shown while the field is concealed in the admin.
@@ -19,6 +74,16 @@ interface EncryptedFieldOptions {
19
74
  }) => TextField;
20
75
  protection?: EncryptedProtection;
21
76
  queryable?: boolean;
77
+ /**
78
+ * Write-only fields only: whether the admin offers the clear (×) action.
79
+ * Defaults to `true` for optional fields and is forced off for `required`
80
+ * ones (clearing a required secret could never save).
81
+ */
82
+ clearable?: boolean;
83
+ /** Write-only text/email fields only: store an identification hint. */
84
+ hint?: EncryptedHintConfig;
85
+ /** Write-only text fields only: enable the admin Generate action. */
86
+ generate?: true | EncryptedGenerateConfig;
22
87
  }
23
88
  /** Serializable subset shipped to ProtectedField via clientProps. */
24
89
  interface EncryptedFieldPatch {
@@ -31,5 +96,5 @@ interface EncryptedFieldPatch {
31
96
  type: EncryptedSourceType;
32
97
  }
33
98
  //#endregion
34
- export { EncryptedFieldOptions, EncryptedFieldPatch, EncryptedProtection, EncryptedSourceField };
99
+ export { EncryptedFieldOptions, EncryptedFieldPatch, EncryptedGenerateConfig, EncryptedHintConfig, EncryptedProtection, EncryptedSourceField };
35
100
  //# sourceMappingURL=types.d.ts.map
@@ -2,11 +2,18 @@
2
2
  /** Request-context modes the encrypted hooks respect (utilities set them). */
3
3
  const ENCRYPTED_CONTEXT_KEY = "tenxFieldsEncrypted";
4
4
  const FIELDS_CUSTOM_KEY = "@10x-media/fields";
5
+ /**
6
+ * The AAD's first component for one marker: the pinned scope when the field
7
+ * declares one, else the schema slug the caller resolved. Every construction
8
+ * site goes through this so a pinned scope cannot be honoured on seal and
9
+ * missed on read.
10
+ */
11
+ const aadScopeOf = (marker, slug) => marker.aadScope ?? slug;
5
12
  const getEncryptedMarker = (field) => {
6
13
  const entry = field.custom?.[FIELDS_CUSTOM_KEY];
7
14
  if (entry && typeof entry === "object" && "encrypted" in entry) return entry.encrypted;
8
15
  };
9
16
  //#endregion
10
- export { ENCRYPTED_CONTEXT_KEY, FIELDS_CUSTOM_KEY, getEncryptedMarker };
17
+ export { ENCRYPTED_CONTEXT_KEY, FIELDS_CUSTOM_KEY, aadScopeOf, getEncryptedMarker };
11
18
 
12
19
  //# sourceMappingURL=types.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"types.js","names":[],"sources":["../../../src/fields/encrypted/types.ts"],"sourcesContent":["import type {\n\tCheckboxField,\n\tCodeField,\n\tDateField,\n\tEmailField,\n\tJSONField,\n\tNumberField,\n\tPointField,\n\tRadioField,\n\tRichTextField,\n\tSelectField,\n\tTextareaField,\n\tTextField,\n} from 'payload'\nimport type { DecryptFailurePolicy, KeysConfig } from '../../types'\nimport type { BidxNormalize } from './crypto/bidx'\n\nexport type EncryptedSourceField =\n\t| CheckboxField\n\t| CodeField\n\t| DateField\n\t| EmailField\n\t| JSONField\n\t| NumberField\n\t| PointField\n\t| RadioField\n\t| RichTextField\n\t| SelectField\n\t| TextareaField\n\t| TextField\n\nexport type EncryptedSourceType = EncryptedSourceField['type']\n\nexport type EncryptedProtection = 'masked' | 'none'\n\nexport interface EncryptedFieldOptions {\n\tkeys?: KeysConfig\n\t/**\n\t * Cosmetic number of dots shown while the field is concealed in the admin.\n\t * Decoupled from the real value length (unknown until reveal). Clamped to\n\t * [1, 64] at the factory; defaults to 8. Ignored by the checkbox facsimile.\n\t */\n\tmaskDots?: number\n\tonDecryptFailure?: DecryptFailurePolicy\n\toverrides?: (args: { field: TextField }) => TextField\n\tprotection?: EncryptedProtection\n\tqueryable?: boolean\n}\n\n/** Request-context modes the encrypted hooks respect (utilities set them). */\nexport const ENCRYPTED_CONTEXT_KEY = 'tenxFieldsEncrypted'\nexport type EncryptedContextMode = 'decrypt' | 'raw' | 'rotate'\n\nexport const FIELDS_CUSTOM_KEY = '@10x-media/fields'\n\n/**\n * Server-side marker the factory stamps on `field.custom`. `custom` is in\n * Payload's serverOnlyFieldProperties list, so KeysConfig functions never\n * reach the client. Consumed by the query rewrite, boot check, and utilities.\n */\nexport interface EncryptedFieldMarker {\n\tbidxName?: string\n\tfieldName: string\n\thasMany: boolean\n\tkeys?: KeysConfig\n\tlocalized: boolean\n\tnormalize: BidxNormalize\n\tonDecryptFailure?: DecryptFailurePolicy\n\tqueryable: boolean\n\tsourceType: EncryptedSourceType\n}\n\n/** Serializable subset shipped to ProtectedField via clientProps. */\nexport interface EncryptedFieldPatch {\n\tadmin?: Record<string, unknown>\n\thasMany?: boolean\n\toptions?: { label: string; value: string }[]\n\ttype: EncryptedSourceType\n}\n\nexport const getEncryptedMarker = (field: {\n\tcustom?: Record<string, unknown>\n}): EncryptedFieldMarker | undefined => {\n\tconst entry = field.custom?.[FIELDS_CUSTOM_KEY]\n\tif (entry && typeof entry === 'object' && 'encrypted' in entry) {\n\t\treturn (entry as { encrypted: EncryptedFieldMarker }).encrypted\n\t}\n\treturn undefined\n}\n"],"mappings":";;AAkDA,MAAa,wBAAwB;AAGrC,MAAa,oBAAoB;AA2BjC,MAAa,sBAAsB,UAEK;CACvC,MAAM,QAAQ,MAAM,SAAS;CAC7B,IAAI,SAAS,OAAO,UAAU,YAAY,eAAe,OACxD,OAAQ,MAA8C;AAGxD"}
1
+ {"version":3,"file":"types.js","names":[],"sources":["../../../src/fields/encrypted/types.ts"],"sourcesContent":["import type {\n\tCheckboxField,\n\tCodeField,\n\tDateField,\n\tEmailField,\n\tJSONField,\n\tNumberField,\n\tPointField,\n\tRadioField,\n\tRichTextField,\n\tSelectField,\n\tTextareaField,\n\tTextField,\n} from 'payload'\nimport type { DecryptFailurePolicy, KeysConfig } from '../../types'\nimport type { BidxNormalize } from './crypto/bidx'\n\nexport type EncryptedSourceField =\n\t| CheckboxField\n\t| CodeField\n\t| DateField\n\t| EmailField\n\t| JSONField\n\t| NumberField\n\t| PointField\n\t| RadioField\n\t| RichTextField\n\t| SelectField\n\t| TextareaField\n\t| TextField\n\nexport type EncryptedSourceType = EncryptedSourceField['type']\n\n/**\n * Confidentiality ladder for the admin and API surface. `'none'` renders the\n * native component with the value visible; `'masked'` (default) conceals behind\n * dots with a reveal toggle; `'writeOnly'` additionally strips the field from\n * every read result (REST, GraphQL, Local API) so the plaintext never leaves\n * the server. Write-only values are read deliberately via `readEncryptedField`\n * or `decryptFieldValue`.\n */\nexport type EncryptedProtection = 'masked' | 'none' | 'writeOnly'\n\n/**\n * Identification hint for a write-only field: how many leading and trailing\n * plaintext characters to store beside the ciphertext at seal time (never\n * derived by decrypting on read). `prefix + suffix` is capped at 32, enough to\n * carry a constant format prefix (`sk_live_`, `whsec_`) and still say which\n * key this is.\n *\n * The cap is the blunt guard. What decides whether a hint is stored at all is\n * the value being sliced: it must keep at least as many characters hidden as\n * the hint exposes, and at least 8 either way. So one config can sit on a\n * collection holding both long tokens and short ones, hinting the first and\n * silently declining the second, rather than exposing half of it.\n */\nexport interface EncryptedHintConfig {\n\tprefix?: number\n\tsuffix?: number\n}\n\n/**\n * Generator for a write-only field's admin Generate action. `true` uses the\n * default: 32 chars of crypto-random base62. Values are generated client-side\n * in the form, so a generated secret is visible and copyable exactly until\n * save, then never again.\n */\nexport interface EncryptedGenerateConfig {\n\t/** Generated length excluding the prefix. Integer in [8, 128], rejected otherwise; default 32. */\n\tlength?: number\n\t/** Literal prefix, e.g. 'whsec_'. Counts toward the hint but not `length`. */\n\tprefix?: string\n\t/** Alphabet to sample from: 10 to 256 distinct code points (duplicates collapse). Default base62. */\n\tcharset?: string\n}\n\nexport interface EncryptedFieldOptions {\n\t/**\n\t * Pins the first component of the ciphertext's AAD binding, which otherwise\n\t * is the collection or global slug. For a field on a collection whose slug a\n\t * consumer can configure (a plugin-owned collection), the slug is a poor\n\t * binding: renaming it makes every stored value fail authentication, and no\n\t * utility can recover them because reads resolve the binding from the\n\t * current slug too. A pinned scope survives the rename.\n\t *\n\t * Must not contain `.` (the AAD component separator) and must be unique per\n\t * logical schema: two fields of the same name sharing a scope share a\n\t * binding, which widens the documented same-field ciphertext portability\n\t * across their collections. Decide it before data exists; changing it later\n\t * is a re-keying event, and stored values become unreadable exactly as a\n\t * slug rename would have made them.\n\t */\n\taadScope?: string\n\tkeys?: KeysConfig\n\t/**\n\t * Cosmetic number of dots shown while the field is concealed in the admin.\n\t * Decoupled from the real value length (unknown until reveal). Clamped to\n\t * [1, 64] at the factory; defaults to 8. Ignored by the checkbox facsimile.\n\t */\n\tmaskDots?: number\n\tonDecryptFailure?: DecryptFailurePolicy\n\toverrides?: (args: { field: TextField }) => TextField\n\tprotection?: EncryptedProtection\n\tqueryable?: boolean\n\t/**\n\t * Write-only fields only: whether the admin offers the clear (×) action.\n\t * Defaults to `true` for optional fields and is forced off for `required`\n\t * ones (clearing a required secret could never save).\n\t */\n\tclearable?: boolean\n\t/** Write-only text/email fields only: store an identification hint. */\n\thint?: EncryptedHintConfig\n\t/** Write-only text fields only: enable the admin Generate action. */\n\tgenerate?: true | EncryptedGenerateConfig\n}\n\n/** Request-context modes the encrypted hooks respect (utilities set them). */\nexport const ENCRYPTED_CONTEXT_KEY = 'tenxFieldsEncrypted'\nexport type EncryptedContextMode = 'decrypt' | 'raw' | 'rotate'\n\nexport const FIELDS_CUSTOM_KEY = '@10x-media/fields'\n\n/**\n * Server-side marker the factory stamps on `field.custom`. `custom` is in\n * Payload's serverOnlyFieldProperties list, so KeysConfig functions never\n * reach the client. Consumed by the query rewrite, boot check, and utilities.\n */\nexport interface EncryptedFieldMarker {\n\t/** Pinned AAD scope; the schema slug when absent. See EncryptedFieldOptions. */\n\taadScope?: string\n\tbidxName?: string\n\tfieldName: string\n\thasMany: boolean\n\tkeys?: KeysConfig\n\tlocalized: boolean\n\tnormalize: BidxNormalize\n\tonDecryptFailure?: DecryptFailurePolicy\n\tqueryable: boolean\n\t/** Name of the virtual set-indicator sibling; present only when `writeOnly`. */\n\tsetName?: string\n\t/** Normalized hint config; present only when `writeOnly` with a hint. */\n\thint?: { prefix: number; suffix: number }\n\t/** Name of the stored hint sibling; present only when `hint` is. */\n\thintName?: string\n\tsourceType: EncryptedSourceType\n\twriteOnly: boolean\n}\n\n/** Serializable subset shipped to ProtectedField via clientProps. */\nexport interface EncryptedFieldPatch {\n\tadmin?: Record<string, unknown>\n\thasMany?: boolean\n\toptions?: { label: string; value: string }[]\n\ttype: EncryptedSourceType\n}\n\n/**\n * The AAD's first component for one marker: the pinned scope when the field\n * declares one, else the schema slug the caller resolved. Every construction\n * site goes through this so a pinned scope cannot be honoured on seal and\n * missed on read.\n */\nexport const aadScopeOf = (marker: EncryptedFieldMarker, slug: string): string =>\n\tmarker.aadScope ?? slug\n\nexport const getEncryptedMarker = (field: {\n\tcustom?: Record<string, unknown>\n}): EncryptedFieldMarker | undefined => {\n\tconst entry = field.custom?.[FIELDS_CUSTOM_KEY]\n\tif (entry && typeof entry === 'object' && 'encrypted' in entry) {\n\t\treturn (entry as { encrypted: EncryptedFieldMarker }).encrypted\n\t}\n\treturn undefined\n}\n"],"mappings":";;AAqHA,MAAa,wBAAwB;AAGrC,MAAa,oBAAoB;;;;;;;AA0CjC,MAAa,cAAc,QAA8B,SACxD,OAAO,YAAY;AAEpB,MAAa,sBAAsB,UAEK;CACvC,MAAM,QAAQ,MAAM,SAAS;CAC7B,IAAI,SAAS,OAAO,UAAU,YAAY,eAAe,OACxD,OAAQ,MAA8C;AAGxD"}
@@ -1,5 +1,5 @@
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 { scanEncryptedFields } from "../scan.js";
4
4
  import { getFieldsRegistry } from "../../../plugin/registry.js";
5
5
  import { isSealed, unseal } from "../crypto/wire.js";
@@ -30,7 +30,7 @@ const decryptAllData = async (payload, options = {}) => {
30
30
  report.collections[collection.slug] = stats;
31
31
  const openValue = async ({ locale, marker, slug, value }) => {
32
32
  const ring = await resolveKeys(marker.keys ?? registry?.encrypted?.keys, payload.config.secret);
33
- const base = `${slug}.${marker.fieldName}`;
33
+ const base = `${aadScopeOf(marker, slug)}.${marker.fieldName}`;
34
34
  const candidates = marker.localized ? [...locale ? [`${base}.${locale}`] : [], ...localeCodes.map((code) => `${base}.${code}`)] : [base];
35
35
  const openOne = (item) => {
36
36
  if (!isSealed(item)) return item;
@@ -1 +1 @@
1
- {"version":3,"file":"decryptAllData.js","names":[],"sources":["../../../../src/fields/encrypted/utils/decryptAllData.ts"],"sourcesContent":["import type { Payload } from 'payload'\nimport { getFieldsRegistry } from '../../../plugin/registry'\nimport { resolveKeys } from '../crypto/keys'\nimport { isSealed, unseal } from '../crypto/wire'\nimport { scanEncryptedFields } from '../scan'\nimport { ENCRYPTED_CONTEXT_KEY, type EncryptedFieldMarker } from '../types'\nimport { getAtPath, pageThrough, setAtPath } from './pageThrough'\nimport type { RotateOptions, RotateReport } from './rotateEncryptedFields'\n\ninterface OpenValueArgs {\n\tlocale?: string\n\tmarker: EncryptedFieldMarker\n\tslug: string\n\tvalue: unknown\n}\n\n/**\n * Removal path: unseals every sealed value and stores it as plaintext, with\n * hooks in 'decrypt' mode so nothing re-seals. Non-string plaintexts are\n * stored JSON-stringified (the backing column is text); swapping the field\n * back to its native type afterwards is a schema migration the consumer owns\n * (documented in the removal guide). The decrypt-mode beforeChange hook nulls\n * each blind-index sibling at its own container scope, so this never writes the\n * index by hand (a flat write would mis-scope a nested field's index).\n */\nexport const decryptAllData = async (\n\tpayload: Payload,\n\toptions: RotateOptions = {}\n): Promise<RotateReport> => {\n\tconst { batchSize = 100, collections, dryRun = false } = options\n\tconst report: RotateReport = { collections: {} }\n\tconst registry = getFieldsRegistry(payload.config)\n\tconst localeCodes = payload.config.localization ? payload.config.localization.localeCodes : []\n\n\tfor (const collection of payload.config.collections) {\n\t\tif (collections && !collections.includes(collection.slug)) {\n\t\t\tcontinue\n\t\t}\n\t\tconst markers = scanEncryptedFields(collection.fields)\n\t\tif (markers.size === 0) {\n\t\t\tcontinue\n\t\t}\n\t\tconst stats = { rotated: 0, scanned: 0 }\n\t\treport.collections[collection.slug] = stats\n\n\t\tconst openValue = async ({ locale, marker, slug, value }: OpenValueArgs): Promise<unknown> => {\n\t\t\tconst ring = await resolveKeys(\n\t\t\t\tmarker.keys ?? registry?.encrypted?.keys,\n\t\t\t\tpayload.config.secret\n\t\t\t)\n\t\t\tconst base = `${slug}.${marker.fieldName}`\n\t\t\tconst candidates = marker.localized\n\t\t\t\t? [\n\t\t\t\t\t\t...(locale ? [`${base}.${locale}`] : []),\n\t\t\t\t\t\t...localeCodes.map((code) => `${base}.${code}`),\n\t\t\t\t\t]\n\t\t\t\t: [base]\n\t\t\tconst openOne = (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\tconst plaintext = unseal(item, ring.dataKeys, candidates)\n\t\t\t\treturn typeof plaintext === 'string' ? plaintext : JSON.stringify(plaintext)\n\t\t\t}\n\t\t\treturn Array.isArray(value) ? value.map(openOne) : openOne(value)\n\t\t}\n\n\t\tfor await (const docs of pageThrough({ batchSize, collection: collection.slug, payload })) {\n\t\t\tfor (const doc of docs) {\n\t\t\t\tstats.scanned += 1\n\t\t\t\tconst patch: Record<string, unknown> = {}\n\t\t\t\tconst localePatches = new Map<string, Record<string, unknown>>()\n\t\t\t\tfor (const [path, marker] of markers) {\n\t\t\t\t\tconst value = getAtPath(doc, path)\n\t\t\t\t\tif (value === undefined || value === null) {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tif (marker.localized && typeof value === 'object' && !Array.isArray(value)) {\n\t\t\t\t\t\tfor (const locale of localeCodes) {\n\t\t\t\t\t\t\tconst localeValue = (value as Record<string, unknown>)[locale]\n\t\t\t\t\t\t\tif (localeValue === undefined || localeValue === null) {\n\t\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tconst localePatch = localePatches.get(locale) ?? {}\n\t\t\t\t\t\t\tsetAtPath(\n\t\t\t\t\t\t\t\tlocalePatch,\n\t\t\t\t\t\t\t\tpath,\n\t\t\t\t\t\t\t\tawait openValue({ locale, marker, slug: collection.slug, value: localeValue })\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\tlocalePatches.set(locale, localePatch)\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\tsetAtPath(patch, path, await openValue({ marker, slug: collection.slug, value }))\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tconst hasWork = Object.keys(patch).length > 0 || localePatches.size > 0\n\t\t\t\tif (!hasWork) {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tstats.rotated += 1\n\t\t\t\tif (dryRun) {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tif (Object.keys(patch).length > 0) {\n\t\t\t\t\tawait payload.update({\n\t\t\t\t\t\tcollection: collection.slug,\n\t\t\t\t\t\tcontext: { [ENCRYPTED_CONTEXT_KEY]: 'decrypt' },\n\t\t\t\t\t\tdata: patch,\n\t\t\t\t\t\tdepth: 0,\n\t\t\t\t\t\tid: doc.id as string | number,\n\t\t\t\t\t\toverrideAccess: true,\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t\tfor (const [locale, localePatch] of localePatches) {\n\t\t\t\t\tawait payload.update({\n\t\t\t\t\t\tcollection: collection.slug,\n\t\t\t\t\t\tcontext: { [ENCRYPTED_CONTEXT_KEY]: 'decrypt' },\n\t\t\t\t\t\tdata: localePatch,\n\t\t\t\t\t\tdepth: 0,\n\t\t\t\t\t\tid: doc.id as string | number,\n\t\t\t\t\t\tlocale: locale as never,\n\t\t\t\t\t\toverrideAccess: true,\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn report\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAyBA,MAAa,iBAAiB,OAC7B,SACA,UAAyB,CAAC,MACC;CAC3B,MAAM,EAAE,YAAY,KAAK,aAAa,SAAS,UAAU;CACzD,MAAM,SAAuB,EAAE,aAAa,CAAC,EAAE;CAC/C,MAAM,WAAW,kBAAkB,QAAQ,MAAM;CACjD,MAAM,cAAc,QAAQ,OAAO,eAAe,QAAQ,OAAO,aAAa,cAAc,CAAC;CAE7F,KAAK,MAAM,cAAc,QAAQ,OAAO,aAAa;EACpD,IAAI,eAAe,CAAC,YAAY,SAAS,WAAW,IAAI,GACvD;EAED,MAAM,UAAU,oBA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AI,MAAM,KAAK,CAAC;KAClD,UACC,aACA,MACA,MAAM,UAAU;MAAE;MAAQ;MAAQ,MAAM,WAAW;MAAM,OAAO;KAAY,CAAC,CAC9E;KACA,cAAc,IAAI,QAAQ,WAAW;IACtC;SAEA,UAAU,OAAO,MAAM,MAAM,UAAU;KAAE;KAAQ,MAAM,WAAW;KAAM;IAAM,CAAC,CAAC;GAElF;GAEA,IAAI,EADY,OAAO,KAAK,KAAK,EAAE,SAAS,KAAK,cAAc,OAAO,IAErE;GAED,MAAM,WAAW;GACjB,IAAI,QACH;GAED,IAAI,OAAO,KAAK,KAAK,EAAE,SAAS,GAC/B,MAAM,QAAQ,OAAO;IACpB,YAAY,WAAW;IACvB,SAAS,GAAG,wBAAwB,UAAU;IAC9C,MAAM;IACN,OAAO;IACP,IAAI,IAAI;IACR,gBAAgB;GACjB,CAAC;GAEF,KAAK,MAAM,CAAC,QAAQ,gBAAgB,eACnC,MAAM,QAAQ,OAAO;IACpB,YAAY,WAAW;IACvB,SAAS,GAAG,wBAAwB,UAAU;IAC9C,MAAM;IACN,OAAO;IACP,IAAI,IAAI;IACA;IACR,gBAAgB;GACjB,CAAC;EAEH;CAEF;CACA,OAAO;AACR"}
1
+ {"version":3,"file":"decryptAllData.js","names":[],"sources":["../../../../src/fields/encrypted/utils/decryptAllData.ts"],"sourcesContent":["import type { Payload } from 'payload'\nimport { getFieldsRegistry } from '../../../plugin/registry'\nimport { resolveKeys } from '../crypto/keys'\nimport { isSealed, unseal } from '../crypto/wire'\nimport { scanEncryptedFields } from '../scan'\nimport { aadScopeOf, ENCRYPTED_CONTEXT_KEY, type EncryptedFieldMarker } from '../types'\nimport { getAtPath, pageThrough, setAtPath } from './pageThrough'\nimport type { RotateOptions, RotateReport } from './rotateEncryptedFields'\n\ninterface OpenValueArgs {\n\tlocale?: string\n\tmarker: EncryptedFieldMarker\n\tslug: string\n\tvalue: unknown\n}\n\n/**\n * Removal path: unseals every sealed value and stores it as plaintext, with\n * hooks in 'decrypt' mode so nothing re-seals. Non-string plaintexts are\n * stored JSON-stringified (the backing column is text); swapping the field\n * back to its native type afterwards is a schema migration the consumer owns\n * (documented in the removal guide). The decrypt-mode beforeChange hook nulls\n * each blind-index sibling at its own container scope, so this never writes the\n * index by hand (a flat write would mis-scope a nested field's index).\n */\nexport const decryptAllData = async (\n\tpayload: Payload,\n\toptions: RotateOptions = {}\n): Promise<RotateReport> => {\n\tconst { batchSize = 100, collections, dryRun = false } = options\n\tconst report: RotateReport = { collections: {} }\n\tconst registry = getFieldsRegistry(payload.config)\n\tconst localeCodes = payload.config.localization ? payload.config.localization.localeCodes : []\n\n\tfor (const collection of payload.config.collections) {\n\t\tif (collections && !collections.includes(collection.slug)) {\n\t\t\tcontinue\n\t\t}\n\t\tconst markers = scanEncryptedFields(collection.fields)\n\t\tif (markers.size === 0) {\n\t\t\tcontinue\n\t\t}\n\t\tconst stats = { rotated: 0, scanned: 0 }\n\t\treport.collections[collection.slug] = stats\n\n\t\tconst openValue = async ({ locale, marker, slug, value }: OpenValueArgs): Promise<unknown> => {\n\t\t\tconst ring = await resolveKeys(\n\t\t\t\tmarker.keys ?? registry?.encrypted?.keys,\n\t\t\t\tpayload.config.secret\n\t\t\t)\n\t\t\tconst base = `${aadScopeOf(marker, slug)}.${marker.fieldName}`\n\t\t\tconst candidates = marker.localized\n\t\t\t\t? [\n\t\t\t\t\t\t...(locale ? [`${base}.${locale}`] : []),\n\t\t\t\t\t\t...localeCodes.map((code) => `${base}.${code}`),\n\t\t\t\t\t]\n\t\t\t\t: [base]\n\t\t\tconst openOne = (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\tconst plaintext = unseal(item, ring.dataKeys, candidates)\n\t\t\t\treturn typeof plaintext === 'string' ? plaintext : JSON.stringify(plaintext)\n\t\t\t}\n\t\t\treturn Array.isArray(value) ? value.map(openOne) : openOne(value)\n\t\t}\n\n\t\tfor await (const docs of pageThrough({ batchSize, collection: collection.slug, payload })) {\n\t\t\tfor (const doc of docs) {\n\t\t\t\tstats.scanned += 1\n\t\t\t\tconst patch: Record<string, unknown> = {}\n\t\t\t\tconst localePatches = new Map<string, Record<string, unknown>>()\n\t\t\t\tfor (const [path, marker] of markers) {\n\t\t\t\t\tconst value = getAtPath(doc, path)\n\t\t\t\t\tif (value === undefined || value === null) {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tif (marker.localized && typeof value === 'object' && !Array.isArray(value)) {\n\t\t\t\t\t\tfor (const locale of localeCodes) {\n\t\t\t\t\t\t\tconst localeValue = (value as Record<string, unknown>)[locale]\n\t\t\t\t\t\t\tif (localeValue === undefined || localeValue === null) {\n\t\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tconst localePatch = localePatches.get(locale) ?? {}\n\t\t\t\t\t\t\tsetAtPath(\n\t\t\t\t\t\t\t\tlocalePatch,\n\t\t\t\t\t\t\t\tpath,\n\t\t\t\t\t\t\t\tawait openValue({ locale, marker, slug: collection.slug, value: localeValue })\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\tlocalePatches.set(locale, localePatch)\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\tsetAtPath(patch, path, await openValue({ marker, slug: collection.slug, value }))\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tconst hasWork = Object.keys(patch).length > 0 || localePatches.size > 0\n\t\t\t\tif (!hasWork) {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tstats.rotated += 1\n\t\t\t\tif (dryRun) {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tif (Object.keys(patch).length > 0) {\n\t\t\t\t\tawait payload.update({\n\t\t\t\t\t\tcollection: collection.slug,\n\t\t\t\t\t\tcontext: { [ENCRYPTED_CONTEXT_KEY]: 'decrypt' },\n\t\t\t\t\t\tdata: patch,\n\t\t\t\t\t\tdepth: 0,\n\t\t\t\t\t\tid: doc.id as string | number,\n\t\t\t\t\t\toverrideAccess: true,\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t\tfor (const [locale, localePatch] of localePatches) {\n\t\t\t\t\tawait payload.update({\n\t\t\t\t\t\tcollection: collection.slug,\n\t\t\t\t\t\tcontext: { [ENCRYPTED_CONTEXT_KEY]: 'decrypt' },\n\t\t\t\t\t\tdata: localePatch,\n\t\t\t\t\t\tdepth: 0,\n\t\t\t\t\t\tid: doc.id as string | number,\n\t\t\t\t\t\tlocale: locale as never,\n\t\t\t\t\t\toverrideAccess: true,\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn report\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAyBA,MAAa,iBAAiB,OAC7B,SACA,UAAyB,CAAC,MACC;CAC3B,MAAM,EAAE,YAAY,KAAK,aAAa,SAAS,UAAU;CACzD,MAAM,SAAuB,EAAE,aAAa,CAAC,EAAE;CAC/C,MAAM,WAAW,kBAAkB,QAAQ,MAAM;CACjD,MAAM,cAAc,QAAQ,OAAO,eAAe,QAAQ,OAAO,aAAa,cAAc,CAAC;CAE7F,KAAK,MAAM,cAAc,QAAQ,OAAO,aAAa;EACpD,IAAI,eAAe,CAAC,YAAY,SAAS,WAAW,IAAI,GACvD;EAED,MAAM,UAAU,oBAAoB,WAAW,MAAM;EACrD,IAAI,QAAQ,SAAS,GACpB;EAED,MAAM,QAAQ;GAAE,SAAS;GAAG,SAAS;EAAE;EACvC,OAAO,YAAY,WAAW,QAAQ;EAEtC,MAAM,YAAY,OAAO,EAAE,QAAQ,QAAQ,MAAM,YAA6C;GAC7F,MAAM,OAAO,MAAM,YAClB,OAAO,QAAQ,UAAU,WAAW,MACpC,QAAQ,OAAO,MAChB;GACA,MAAM,OAAO,GAAG,WAAW,QAAQ,IAAI,EAAE,GAAG,OAAO;GACnD,MAAM,aAAa,OAAO,YACvB,CACA,GAAI,SAAS,CAAC,GAAG,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