@10x-media/fields 0.1.0-beta.3 → 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 (66) hide show
  1. package/CHANGELOG.md +38 -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/color/client/ColorField.js +55 -35
  6. package/dist/fields/color/client/ColorField.js.map +1 -1
  7. package/dist/fields/color/client/colorField.css +23 -0
  8. package/dist/fields/encrypted/boot.js +2 -1
  9. package/dist/fields/encrypted/boot.js.map +1 -1
  10. package/dist/fields/encrypted/components/EncryptedInput.js +4 -1
  11. package/dist/fields/encrypted/components/EncryptedInput.js.map +1 -1
  12. package/dist/fields/encrypted/components/EncryptedTextarea.js +6 -2
  13. package/dist/fields/encrypted/components/EncryptedTextarea.js.map +1 -1
  14. package/dist/fields/encrypted/components/ProtectedCell.d.ts +15 -6
  15. package/dist/fields/encrypted/components/ProtectedCell.js +37 -8
  16. package/dist/fields/encrypted/components/ProtectedCell.js.map +1 -1
  17. package/dist/fields/encrypted/components/ProtectedField.css +134 -39
  18. package/dist/fields/encrypted/components/ProtectedField.d.ts +3 -0
  19. package/dist/fields/encrypted/components/ProtectedField.js +14 -0
  20. package/dist/fields/encrypted/components/ProtectedField.js.map +1 -1
  21. package/dist/fields/encrypted/components/WriteOnlyActions.js +65 -0
  22. package/dist/fields/encrypted/components/WriteOnlyActions.js.map +1 -0
  23. package/dist/fields/encrypted/components/WriteOnlyField.js +286 -0
  24. package/dist/fields/encrypted/components/WriteOnlyField.js.map +1 -0
  25. package/dist/fields/encrypted/components/writeOnlyIntent.js +69 -0
  26. package/dist/fields/encrypted/components/writeOnlyIntent.js.map +1 -0
  27. package/dist/fields/encrypted/crypto/wire.d.ts +10 -1
  28. package/dist/fields/encrypted/crypto/wire.js +1 -1
  29. package/dist/fields/encrypted/encryptedField.js +63 -6
  30. package/dist/fields/encrypted/encryptedField.js.map +1 -1
  31. package/dist/fields/encrypted/generateSecret.d.ts +10 -0
  32. package/dist/fields/encrypted/generateSecret.js +41 -0
  33. package/dist/fields/encrypted/generateSecret.js.map +1 -0
  34. package/dist/fields/encrypted/hint.js +67 -0
  35. package/dist/fields/encrypted/hint.js.map +1 -0
  36. package/dist/fields/encrypted/hooks.js +59 -31
  37. package/dist/fields/encrypted/hooks.js.map +1 -1
  38. package/dist/fields/encrypted/queryRewrite.d.ts +10 -2
  39. package/dist/fields/encrypted/queryRewrite.js +34 -8
  40. package/dist/fields/encrypted/queryRewrite.js.map +1 -1
  41. package/dist/fields/encrypted/rawRead.d.ts +24 -0
  42. package/dist/fields/encrypted/rawRead.js +40 -0
  43. package/dist/fields/encrypted/rawRead.js.map +1 -0
  44. package/dist/fields/encrypted/scan.js +21 -4
  45. package/dist/fields/encrypted/scan.js.map +1 -1
  46. package/dist/fields/encrypted/types.d.ts +67 -2
  47. package/dist/fields/encrypted/types.js +8 -1
  48. package/dist/fields/encrypted/types.js.map +1 -1
  49. package/dist/fields/encrypted/utils/decryptAllData.js +2 -2
  50. package/dist/fields/encrypted/utils/decryptAllData.js.map +1 -1
  51. package/dist/fields/encrypted/utils/decryptFieldValue.d.ts +30 -0
  52. package/dist/fields/encrypted/utils/decryptFieldValue.js +56 -0
  53. package/dist/fields/encrypted/utils/decryptFieldValue.js.map +1 -0
  54. package/dist/fields/encrypted/utils/readEncryptedField.d.ts +51 -0
  55. package/dist/fields/encrypted/utils/readEncryptedField.js +96 -0
  56. package/dist/fields/encrypted/utils/readEncryptedField.js.map +1 -0
  57. package/dist/index.js +2 -1
  58. package/dist/index.js.map +1 -1
  59. package/dist/translations/de.js +8 -1
  60. package/dist/translations/de.js.map +1 -1
  61. package/dist/translations/en.js +8 -1
  62. package/dist/translations/en.js.map +1 -1
  63. package/dist/translations/keys.d.ts +7 -0
  64. package/dist/translations/keys.js +8 -1
  65. package/dist/translations/keys.js.map +1 -1
  66. package/package.json +6 -6
@@ -0,0 +1,10 @@
1
+ //#region src/fields/encrypted/generateSecret.d.ts
2
+ interface NormalizedGenerate {
3
+ /** Deduplicated code points, so sampling is uniform and never splits a surrogate pair. */
4
+ charset: string[];
5
+ length: number;
6
+ prefix: string;
7
+ }
8
+ //#endregion
9
+ export { NormalizedGenerate };
10
+ //# sourceMappingURL=generateSecret.d.ts.map
@@ -0,0 +1,41 @@
1
+ //#region src/fields/encrypted/generateSecret.ts
2
+ const DEFAULT_CHARSET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
3
+ const MIN_LENGTH = 8;
4
+ const MAX_LENGTH = 128;
5
+ const MIN_CHARSET = 10;
6
+ /** Byte-based rejection sampling can address at most 256 symbols. */
7
+ const MAX_CHARSET = 256;
8
+ /** Validates and normalizes a generate config; throws with the field name on misuse. */
9
+ const normalizeGenerate = (config, fieldName) => {
10
+ const given = config === true ? {} : config;
11
+ const length = given.length ?? 32;
12
+ if (!Number.isInteger(length) || length < MIN_LENGTH || length > MAX_LENGTH) throw new Error(`@10x-media/fields: encryptedField '${fieldName}': generate.length must be an integer in [${MIN_LENGTH}, ${MAX_LENGTH}]`);
13
+ const charset = [...new Set(given.charset ?? DEFAULT_CHARSET)];
14
+ if (charset.length < MIN_CHARSET || charset.length > MAX_CHARSET) throw new Error(`@10x-media/fields: encryptedField '${fieldName}': generate.charset needs ${MIN_CHARSET} to ${MAX_CHARSET} distinct characters`);
15
+ return {
16
+ charset,
17
+ length,
18
+ prefix: given.prefix ?? ""
19
+ };
20
+ };
21
+ /**
22
+ * Crypto-random secret for the admin Generate action. Rejection sampling over
23
+ * the deduplicated code-point array keeps the distribution uniform (the
24
+ * charset cap guarantees a non-zero acceptance window). Async so a future
25
+ * custom source (server-issued keys, a KMS) can slot in behind the same call
26
+ * site.
27
+ */
28
+ const generateSecret = async ({ charset, length, prefix }) => {
29
+ const chars = [];
30
+ const limit = 256 - 256 % charset.length;
31
+ while (chars.length < length) {
32
+ const batch = new Uint8Array(length * 2);
33
+ globalThis.crypto.getRandomValues(batch);
34
+ for (const byte of batch) if (byte < limit && chars.length < length) chars.push(charset[byte % charset.length]);
35
+ }
36
+ return `${prefix}${chars.join("")}`;
37
+ };
38
+ //#endregion
39
+ export { generateSecret, normalizeGenerate };
40
+
41
+ //# sourceMappingURL=generateSecret.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"generateSecret.js","names":[],"sources":["../../../src/fields/encrypted/generateSecret.ts"],"sourcesContent":["import type { EncryptedGenerateConfig } from './types'\n\nconst DEFAULT_CHARSET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'\nconst MIN_LENGTH = 8\nconst MAX_LENGTH = 128\nconst MIN_CHARSET = 10\n/** Byte-based rejection sampling can address at most 256 symbols. */\nconst MAX_CHARSET = 256\n\nexport interface NormalizedGenerate {\n\t/** Deduplicated code points, so sampling is uniform and never splits a surrogate pair. */\n\tcharset: string[]\n\tlength: number\n\tprefix: string\n}\n\n/** Validates and normalizes a generate config; throws with the field name on misuse. */\nexport const normalizeGenerate = (\n\tconfig: true | EncryptedGenerateConfig,\n\tfieldName: string\n): NormalizedGenerate => {\n\tconst given = config === true ? {} : config\n\tconst length = given.length ?? 32\n\tif (!Number.isInteger(length) || length < MIN_LENGTH || length > MAX_LENGTH) {\n\t\tthrow new Error(\n\t\t\t`@10x-media/fields: encryptedField '${fieldName}': generate.length must be an integer in [${MIN_LENGTH}, ${MAX_LENGTH}]`\n\t\t)\n\t}\n\tconst charset = [...new Set(given.charset ?? DEFAULT_CHARSET)]\n\tif (charset.length < MIN_CHARSET || charset.length > MAX_CHARSET) {\n\t\tthrow new Error(\n\t\t\t`@10x-media/fields: encryptedField '${fieldName}': generate.charset needs ${MIN_CHARSET} to ${MAX_CHARSET} distinct characters`\n\t\t)\n\t}\n\treturn { charset, length, prefix: given.prefix ?? '' }\n}\n\n/**\n * Crypto-random secret for the admin Generate action. Rejection sampling over\n * the deduplicated code-point array keeps the distribution uniform (the\n * charset cap guarantees a non-zero acceptance window). Async so a future\n * custom source (server-issued keys, a KMS) can slot in behind the same call\n * site.\n */\nexport const generateSecret = async ({\n\tcharset,\n\tlength,\n\tprefix,\n}: NormalizedGenerate): Promise<string> => {\n\tconst chars: string[] = []\n\tconst limit = 256 - (256 % charset.length)\n\twhile (chars.length < length) {\n\t\tconst batch = new Uint8Array(length * 2)\n\t\tglobalThis.crypto.getRandomValues(batch)\n\t\tfor (const byte of batch) {\n\t\t\tif (byte < limit && chars.length < length) {\n\t\t\t\tchars.push(charset[byte % charset.length] as string)\n\t\t\t}\n\t\t}\n\t}\n\treturn `${prefix}${chars.join('')}`\n}\n"],"mappings":";AAEA,MAAM,kBAAkB;AACxB,MAAM,aAAa;AACnB,MAAM,aAAa;AACnB,MAAM,cAAc;;AAEpB,MAAM,cAAc;;AAUpB,MAAa,qBACZ,QACA,cACwB;CACxB,MAAM,QAAQ,WAAW,OAAO,CAAC,IAAI;CACrC,MAAM,SAAS,MAAM,UAAU;CAC/B,IAAI,CAAC,OAAO,UAAU,MAAM,KAAK,SAAS,cAAc,SAAS,YAChE,MAAM,IAAI,MACT,sCAAsC,UAAU,4CAA4C,WAAW,IAAI,WAAW,EACvH;CAED,MAAM,UAAU,CAAC,GAAG,IAAI,IAAI,MAAM,WAAW,eAAe,CAAC;CAC7D,IAAI,QAAQ,SAAS,eAAe,QAAQ,SAAS,aACpD,MAAM,IAAI,MACT,sCAAsC,UAAU,4BAA4B,YAAY,MAAM,YAAY,qBAC3G;CAED,OAAO;EAAE;EAAS;EAAQ,QAAQ,MAAM,UAAU;CAAG;AACtD;;;;;;;;AASA,MAAa,iBAAiB,OAAO,EACpC,SACA,QACA,aAC0C;CAC1C,MAAM,QAAkB,CAAC;CACzB,MAAM,QAAQ,MAAO,MAAM,QAAQ;CACnC,OAAO,MAAM,SAAS,QAAQ;EAC7B,MAAM,QAAQ,IAAI,WAAW,SAAS,CAAC;EACvC,WAAW,OAAO,gBAAgB,KAAK;EACvC,KAAK,MAAM,QAAQ,OAClB,IAAI,OAAO,SAAS,MAAM,SAAS,QAClC,MAAM,KAAK,QAAQ,OAAO,QAAQ,OAAiB;CAGtD;CACA,OAAO,GAAG,SAAS,MAAM,KAAK,EAAE;AACjC"}
@@ -0,0 +1,67 @@
1
+ /**
2
+ * Canonical gap marker in the STORED hint (`sk_d····9d3f`). Storage stays
3
+ * compact and length-neutral; display layers swap it for the field's
4
+ * `maskDots` run via `formatHint` so the concealed span matches the masked
5
+ * aesthetic everywhere.
6
+ */
7
+ const HINT_GAP = "····";
8
+ /** Validates and normalizes a hint config; throws with the field name on misuse. */
9
+ const normalizeHint = (config, fieldName) => {
10
+ const prefix = config.prefix ?? 0;
11
+ const suffix = config.suffix ?? 0;
12
+ const valid = (n) => Number.isInteger(n) && n >= 0;
13
+ if (!valid(prefix) || !valid(suffix) || prefix + suffix === 0) throw new Error(`@10x-media/fields: encryptedField '${fieldName}': hint needs non-negative integer prefix/suffix with at least one character`);
14
+ if (prefix + suffix > 32) throw new Error(`@10x-media/fields: encryptedField '${fieldName}': hint may expose at most 32 characters (got prefix ${prefix} + suffix ${suffix})`);
15
+ return {
16
+ prefix,
17
+ suffix
18
+ };
19
+ };
20
+ /**
21
+ * The stored identification hint for one plaintext, e.g. `sk_l····9d3f`, or
22
+ * null when the value is not a string, too short to hint without giving most
23
+ * of it away, or its exposed ends contain the gap glyph themselves (a `·` in
24
+ * the exposed text would blur where the concealed span starts, so such values
25
+ * store no hint; real credentials never contain U+00B7). Computed at seal
26
+ * time only; reads never touch the plaintext.
27
+ *
28
+ * Two length guards, because a hint's safety is a property of the value it
29
+ * slices rather than of the config that asks for the slice. The hidden
30
+ * remainder must be at least as long as the exposed ends, so a config sized
31
+ * for long tokens degrades to no hint on a short value instead of exposing
32
+ * half of it; and it must clear an absolute floor, since a short value stays
33
+ * guessable at any ratio. A config within the old 8-character ceiling can
34
+ * never fail the ratio it did not have to satisfy before: it already had to
35
+ * leave `HINT_MIN_HIDDEN` hidden, which was the same 8.
36
+ */
37
+ const makeHint = (plaintext, hint) => {
38
+ if (typeof plaintext !== "string") return null;
39
+ const chars = [...plaintext];
40
+ const exposed = hint.prefix + hint.suffix;
41
+ const hidden = chars.length - exposed;
42
+ if (hidden < 8 || hidden < exposed) return null;
43
+ const start = hint.prefix > 0 ? chars.slice(0, hint.prefix).join("") : "";
44
+ const end = hint.suffix > 0 ? chars.slice(-hint.suffix).join("") : "";
45
+ if (start.includes("·") || end.includes("·")) return null;
46
+ return `${start}${HINT_GAP}${end}`;
47
+ };
48
+ /**
49
+ * Renders a stored hint for display: the canonical gap becomes the `maskDots`
50
+ * bullet run, so `sk_d····9d3f` with maskDots 8 shows as `sk_d••••••••9d3f`.
51
+ *
52
+ * The run is additive: the hint's ends wrap the exact bullet run a hint-less
53
+ * concealed value shows, never fewer. One count everywhere is what makes the
54
+ * bullets legible as "concealed" rather than as information, and it keeps the
55
+ * count a pure presentation choice, decided by `maskDots` alone. A hint too
56
+ * wide for its container is the container's problem, and both the input and
57
+ * the list cell clamp with an ellipsis rather than letting the run absorb it.
58
+ */
59
+ const formatHint = (hint, dots) => {
60
+ const index = hint.indexOf(HINT_GAP);
61
+ if (index === -1) return hint;
62
+ return `${hint.slice(0, index)}${"•".repeat(Math.max(1, Math.trunc(dots)))}${hint.slice(index + 4)}`;
63
+ };
64
+ //#endregion
65
+ export { formatHint, makeHint, normalizeHint };
66
+
67
+ //# sourceMappingURL=hint.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"hint.js","names":[],"sources":["../../../src/fields/encrypted/hint.ts"],"sourcesContent":["import type { EncryptedHintConfig } from './types'\n\n/**\n * Ceiling on the plaintext characters a hint may expose across both ends.\n *\n * A ceiling alone is a poor safety control, because what makes a hint safe is\n * how much of the value stays hidden, not how much shows: 32 characters of a\n * 128-character token is nothing, and 32 of a 40-character one is most of it.\n * `makeHint` enforces the ratio, and this is the blunt upper bound on top of\n * it, high enough for the prefixed formats credentials actually use\n * (`sk_live_`, `whsec_`, `ghp_`, `xoxb-`), where a fixed budget would be spent\n * on a constant that identifies nothing.\n */\nexport const HINT_MAX_CHARS = 32\n/**\n * Floor on the characters a hint must leave hidden, whatever the ratio allows.\n * Below this a short value is guessable however small a fraction is exposed.\n */\nexport const HINT_MIN_HIDDEN = 8\n\n/**\n * Canonical gap marker in the STORED hint (`sk_d····9d3f`). Storage stays\n * compact and length-neutral; display layers swap it for the field's\n * `maskDots` run via `formatHint` so the concealed span matches the masked\n * aesthetic everywhere.\n */\nexport const HINT_GAP = '····'\n\nexport interface NormalizedHint {\n\tprefix: number\n\tsuffix: number\n}\n\n/** Validates and normalizes a hint config; throws with the field name on misuse. */\nexport const normalizeHint = (config: EncryptedHintConfig, fieldName: string): NormalizedHint => {\n\tconst prefix = config.prefix ?? 0\n\tconst suffix = config.suffix ?? 0\n\tconst valid = (n: number) => Number.isInteger(n) && n >= 0\n\tif (!valid(prefix) || !valid(suffix) || prefix + suffix === 0) {\n\t\tthrow new Error(\n\t\t\t`@10x-media/fields: encryptedField '${fieldName}': hint needs non-negative integer prefix/suffix with at least one character`\n\t\t)\n\t}\n\tif (prefix + suffix > HINT_MAX_CHARS) {\n\t\tthrow new Error(\n\t\t\t`@10x-media/fields: encryptedField '${fieldName}': hint may expose at most ${HINT_MAX_CHARS} characters (got prefix ${prefix} + suffix ${suffix})`\n\t\t)\n\t}\n\treturn { prefix, suffix }\n}\n\n/**\n * The stored identification hint for one plaintext, e.g. `sk_l····9d3f`, or\n * null when the value is not a string, too short to hint without giving most\n * of it away, or its exposed ends contain the gap glyph themselves (a `·` in\n * the exposed text would blur where the concealed span starts, so such values\n * store no hint; real credentials never contain U+00B7). Computed at seal\n * time only; reads never touch the plaintext.\n *\n * Two length guards, because a hint's safety is a property of the value it\n * slices rather than of the config that asks for the slice. The hidden\n * remainder must be at least as long as the exposed ends, so a config sized\n * for long tokens degrades to no hint on a short value instead of exposing\n * half of it; and it must clear an absolute floor, since a short value stays\n * guessable at any ratio. A config within the old 8-character ceiling can\n * never fail the ratio it did not have to satisfy before: it already had to\n * leave `HINT_MIN_HIDDEN` hidden, which was the same 8.\n */\nexport const makeHint = (plaintext: unknown, hint: NormalizedHint): string | null => {\n\tif (typeof plaintext !== 'string') {\n\t\treturn null\n\t}\n\t// Code points, not UTF-16 units: slicing units can split a surrogate pair\n\t// into an unpaired half, and unit counts make an astral-character value look\n\t// twice as long as it is, overstating what the guards think stays hidden.\n\tconst chars = [...plaintext]\n\tconst exposed = hint.prefix + hint.suffix\n\tconst hidden = chars.length - exposed\n\tif (hidden < HINT_MIN_HIDDEN || hidden < exposed) {\n\t\treturn null\n\t}\n\tconst start = hint.prefix > 0 ? chars.slice(0, hint.prefix).join('') : ''\n\tconst end = hint.suffix > 0 ? chars.slice(-hint.suffix).join('') : ''\n\tif (start.includes('·') || end.includes('·')) {\n\t\treturn null\n\t}\n\treturn `${start}${HINT_GAP}${end}`\n}\n\n/**\n * Renders a stored hint for display: the canonical gap becomes the `maskDots`\n * bullet run, so `sk_d····9d3f` with maskDots 8 shows as `sk_d••••••••9d3f`.\n *\n * The run is additive: the hint's ends wrap the exact bullet run a hint-less\n * concealed value shows, never fewer. One count everywhere is what makes the\n * bullets legible as \"concealed\" rather than as information, and it keeps the\n * count a pure presentation choice, decided by `maskDots` alone. A hint too\n * wide for its container is the container's problem, and both the input and\n * the list cell clamp with an ellipsis rather than letting the run absorb it.\n */\nexport const formatHint = (hint: string, dots: number): string => {\n\tconst index = hint.indexOf(HINT_GAP)\n\tif (index === -1) {\n\t\treturn hint\n\t}\n\treturn `${hint.slice(0, index)}${'•'.repeat(Math.max(1, Math.trunc(dots)))}${hint.slice(index + HINT_GAP.length)}`\n}\n"],"mappings":";;;;;;AA0BA,MAAa,WAAW;;AAQxB,MAAa,iBAAiB,QAA6B,cAAsC;CAChG,MAAM,SAAS,OAAO,UAAU;CAChC,MAAM,SAAS,OAAO,UAAU;CAChC,MAAM,SAAS,MAAc,OAAO,UAAU,CAAC,KAAK,KAAK;CACzD,IAAI,CAAC,MAAM,MAAM,KAAK,CAAC,MAAM,MAAM,KAAK,SAAS,WAAW,GAC3D,MAAM,IAAI,MACT,sCAAsC,UAAU,6EACjD;CAED,IAAI,SAAS,SAAA,IACZ,MAAM,IAAI,MACT,sCAAsC,UAAU,uDAAsE,OAAO,YAAY,OAAO,EACjJ;CAED,OAAO;EAAE;EAAQ;CAAO;AACzB;;;;;;;;;;;;;;;;;;AAmBA,MAAa,YAAY,WAAoB,SAAwC;CACpF,IAAI,OAAO,cAAc,UACxB,OAAO;CAKR,MAAM,QAAQ,CAAC,GAAG,SAAS;CAC3B,MAAM,UAAU,KAAK,SAAS,KAAK;CACnC,MAAM,SAAS,MAAM,SAAS;CAC9B,IAAI,SAAA,KAA4B,SAAS,SACxC,OAAO;CAER,MAAM,QAAQ,KAAK,SAAS,IAAI,MAAM,MAAM,GAAG,KAAK,MAAM,EAAE,KAAK,EAAE,IAAI;CACvE,MAAM,MAAM,KAAK,SAAS,IAAI,MAAM,MAAM,CAAC,KAAK,MAAM,EAAE,KAAK,EAAE,IAAI;CACnE,IAAI,MAAM,SAAS,GAAG,KAAK,IAAI,SAAS,GAAG,GAC1C,OAAO;CAER,OAAO,GAAG,QAAQ,WAAW;AAC9B;;;;;;;;;;;;AAaA,MAAa,cAAc,MAAc,SAAyB;CACjE,MAAM,QAAQ,KAAK,QAAQ,QAAQ;CACnC,IAAI,UAAU,IACb,OAAO;CAER,OAAO,GAAG,KAAK,MAAM,GAAG,KAAK,IAAI,IAAI,OAAO,KAAK,IAAI,GAAG,KAAK,MAAM,IAAI,CAAC,CAAC,IAAI,KAAK,MAAM,QAAQ,CAAe;AAChH"}
@@ -1,9 +1,10 @@
1
1
  import { resolveKeys } from "./crypto/keys.js";
2
- import { ENCRYPTED_CONTEXT_KEY } from "./types.js";
2
+ import { ENCRYPTED_CONTEXT_KEY, aadScopeOf } from "./types.js";
3
3
  import { computeBidx } from "./crypto/bidx.js";
4
4
  import { getFieldsRegistry } from "../../plugin/registry.js";
5
5
  import { buildAad } from "./crypto/aad.js";
6
6
  import { isSealed, parseWire, seal, unseal } from "./crypto/wire.js";
7
+ import { makeHint } from "./hint.js";
7
8
  import { sealedArrayKey, stashPlaintext } from "./plaintextStash.js";
8
9
  //#region src/fields/encrypted/hooks.ts
9
10
  /** Raised on read when decryption fails and the policy is 'throw'. */
@@ -28,29 +29,31 @@ const operationLocale = (req) => {
28
29
  return locale;
29
30
  };
30
31
  /**
31
- * AAD binds a ciphertext to its `${slug}.${field}[.${locale}]` slot via
32
- * buildAad, which rejects any dotted component so the joined data stays
33
- * unambiguous (a dotted slug/locale would blur the cross-field binding).
32
+ * AAD binds a ciphertext to its `${scope}.${field}[.${locale}]` slot, where the
33
+ * scope is the field's pinned `aadScope` or the schema slug, via buildAad,
34
+ * which rejects any dotted component so the joined data stays unambiguous (a
35
+ * dotted scope or locale would blur the cross-field binding).
34
36
  */
35
- const sealAad = (marker, slug, req) => buildAad(marker.localized ? [
36
- slug,
37
+ const sealAad = (marker, slug, req) => {
38
+ if (marker.localized) return localeAad(marker, slug, operationLocale(req));
39
+ return buildAad([aadScopeOf(marker, slug), marker.fieldName]);
40
+ };
41
+ /** The AAD for one locale of a localized field; locale-map writes seal per entry. */
42
+ const localeAad = (marker, slug, locale) => buildAad([
43
+ aadScopeOf(marker, slug),
37
44
  marker.fieldName,
38
- operationLocale(req)
39
- ] : [slug, marker.fieldName]);
45
+ locale
46
+ ]);
40
47
  /**
41
48
  * Read-side AAD candidates. Localized fields try the request locale first,
42
49
  * then every configured locale: fallbackLocale hoisting and locale=all hook
43
50
  * execution mean the hook cannot know which locale sealed the value.
44
51
  */
45
52
  const readAadCandidates = (marker, slug, req) => {
46
- if (!marker.localized) return [buildAad([slug, marker.fieldName])];
53
+ if (!marker.localized) return [buildAad([aadScopeOf(marker, slug), marker.fieldName])];
47
54
  const codes = req.payload.config.localization ? req.payload.config.localization.localeCodes : [defaultLocale(req.payload.config)];
48
55
  const first = operationLocale(req);
49
- return [first, ...codes.filter((code) => code !== first)].map((code) => buildAad([
50
- slug,
51
- marker.fieldName,
52
- code
53
- ]));
56
+ return [first, ...codes.filter((code) => code !== first)].map((code) => localeAad(marker, slug, code));
54
57
  };
55
58
  /**
56
59
  * The active utility mode from the request context, or undefined for a normal
@@ -82,6 +85,7 @@ const makeBeforeChangeHook = (marker) => {
82
85
  if (mode === "raw") return value;
83
86
  if (mode === "decrypt") {
84
87
  if (marker.queryable && marker.bidxName) siblingData[marker.bidxName] = null;
88
+ if (marker.hintName) siblingData[marker.hintName] = null;
85
89
  return value;
86
90
  }
87
91
  const slug = aadSlug(collection, global);
@@ -105,22 +109,24 @@ const makeBeforeChangeHook = (marker) => {
105
109
  return marker.hasMany && Array.isArray(value) ? value.map(rotateOne) : rotateOne(value);
106
110
  }
107
111
  if (value === void 0) return;
108
- if (value === null) {
112
+ if (value === null || marker.writeOnly && value === "") {
109
113
  if (marker.queryable && marker.bidxName) siblingData[marker.bidxName] = null;
114
+ if (marker.hintName) siblingData[marker.hintName] = null;
110
115
  return null;
111
116
  }
112
117
  if (marker.localized && req.locale === "all" && isLocaleMap(value)) {
113
118
  const sealedMap = {};
114
- for (const [locale, localeValue] of Object.entries(value)) sealedMap[locale] = sealValueForLocale(localeValue, {
115
- aad: buildAad([
116
- slug,
117
- marker.fieldName,
118
- locale
119
- ]),
120
- hasMany: marker.hasMany,
121
- key: activeKey,
122
- keyId: ring.activeId
123
- });
119
+ const hintMap = {};
120
+ for (const [locale, localeValue] of Object.entries(value)) {
121
+ sealedMap[locale] = sealValueForLocale(localeValue, {
122
+ aad: localeAad(marker, slug, locale),
123
+ hasMany: marker.hasMany,
124
+ key: activeKey,
125
+ keyId: ring.activeId
126
+ });
127
+ if (marker.hint && !isSealed(localeValue)) hintMap[locale] = localeValue == null ? null : makeHint(localeValue, marker.hint);
128
+ }
129
+ if (marker.hintName && Object.keys(hintMap).length > 0) siblingData[marker.hintName] = hintMap;
124
130
  return sealedMap;
125
131
  }
126
132
  const aad = sealAad(marker, slug, req);
@@ -140,6 +146,7 @@ const makeBeforeChangeHook = (marker) => {
140
146
  const sealed = sealOne(value);
141
147
  stashPlaintext(req, sealed, value);
142
148
  if (marker.queryable && marker.bidxName) siblingData[marker.bidxName] = computeBidx(value, ring.indexKey, marker.normalize);
149
+ if (marker.hint && marker.hintName) siblingData[marker.hintName] = makeHint(value, marker.hint);
143
150
  return sealed;
144
151
  };
145
152
  };
@@ -196,6 +203,7 @@ const makeAfterReadHook = (marker) => {
196
203
  const { collection, context, global, req, value } = args;
197
204
  if (value === void 0 || value === null) return value;
198
205
  if (contextMode(context)) return value;
206
+ if (marker.writeOnly) return value;
199
207
  const slug = aadSlug(collection, global);
200
208
  const ring = await ringForRequest(req, marker);
201
209
  const openArgs = {
@@ -210,6 +218,30 @@ const makeAfterReadHook = (marker) => {
210
218
  };
211
219
  };
212
220
  /**
221
+ * Recursive presence check for a stored write-only sibling: arrays count only
222
+ * when some item is present, locale maps only when some locale's value is,
223
+ * including a locale map of arrays. `{ en: [] }` and `{ en: [null] }` read as
224
+ * unset; a sealed string (or pre-adoption scalar) reads as set.
225
+ */
226
+ const hasStoredValue = (value) => {
227
+ if (value == null) return false;
228
+ if (Array.isArray(value)) return value.some(hasStoredValue);
229
+ if (typeof value === "object") return Object.values(value).some(hasStoredValue);
230
+ return true;
231
+ };
232
+ /**
233
+ * afterRead on the virtual set-indicator sibling of a write-only field: true
234
+ * when the stored sibling holds anything (sealed, or pre-adoption plaintext).
235
+ * A locale-map sibling (locale=all read) counts as set when any locale has a
236
+ * value. Utility flows pass through so raw reads see no synthesized data.
237
+ */
238
+ const makeSetIndicatorHook = (fieldName) => {
239
+ return ({ context, siblingData, value }) => {
240
+ if (contextMode(context)) return value;
241
+ return hasStoredValue(siblingData[fieldName]);
242
+ };
243
+ };
244
+ /**
213
245
  * afterRead on the virtual richText field: decrypts the ciphertext sibling into
214
246
  * a SerializedEditorState. The virtual field is never persisted, so its own
215
247
  * value is always undefined and the ciphertext SIBLING is the source. The
@@ -259,11 +291,7 @@ const makeRichTextSealHook = (marker, storedName) => {
259
291
  if (marker.localized && req.locale === "all" && isLocaleMap(value)) {
260
292
  const sealedMap = {};
261
293
  for (const [locale, localeValue] of Object.entries(value)) sealedMap[locale] = localeValue == null || isSealed(localeValue) ? localeValue : seal({
262
- aad: buildAad([
263
- slug,
264
- marker.fieldName,
265
- locale
266
- ]),
294
+ aad: localeAad(marker, slug, locale),
267
295
  key: activeKey,
268
296
  keyId: ring.activeId,
269
297
  plaintext: localeValue
@@ -321,6 +349,6 @@ const makeRichTextValidate = () => {
321
349
  };
322
350
  };
323
351
  //#endregion
324
- export { DecryptFailedError, contextMode, makeAfterReadHook, makeBeforeChangeHook, makeRichTextCiphertextHook, makeRichTextDecryptHook, makeRichTextSealHook, makeRichTextValidate, ringForRequest };
352
+ export { DecryptFailedError, contextMode, makeAfterReadHook, makeBeforeChangeHook, makeRichTextCiphertextHook, makeRichTextDecryptHook, makeRichTextSealHook, makeRichTextValidate, makeSetIndicatorHook, ringForRequest };
325
353
 
326
354
  //# sourceMappingURL=hooks.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"hooks.js","names":[],"sources":["../../../src/fields/encrypted/hooks.ts"],"sourcesContent":["import type { FieldHook, PayloadRequest, RichTextField, SanitizedConfig, Validate } from 'payload'\nimport { getFieldsRegistry } from '../../plugin/registry'\nimport type { DecryptFailurePolicy } from '../../types'\nimport { buildAad } from './crypto/aad'\nimport { computeBidx } from './crypto/bidx'\nimport { type KeyRing, resolveKeys } from './crypto/keys'\nimport { isSealed, parseWire, seal, unseal } from './crypto/wire'\nimport { sealedArrayKey, stashPlaintext } from './plaintextStash'\nimport {\n\tENCRYPTED_CONTEXT_KEY,\n\ttype EncryptedContextMode,\n\ttype EncryptedFieldMarker,\n} from './types'\n\nexport interface DecryptFailedArgs {\n\tcause: unknown\n\tfield: string\n\tkeyId: string | undefined\n\tslug: string\n}\n\n/** Raised on read when decryption fails and the policy is 'throw'. */\nexport class DecryptFailedError extends Error {\n\tconstructor({ cause, field, keyId, slug }: DecryptFailedArgs) {\n\t\tconst keyInfo = keyId ? ` (keyId '${keyId}')` : ''\n\t\tsuper(\n\t\t\t`@10x-media/fields: failed to decrypt ${slug}.${field}${keyInfo}: ${cause instanceof Error ? cause.name : 'unknown error'}`\n\t\t)\n\t\tthis.name = 'DecryptFailedError'\n\t\tthis.cause = cause\n\t}\n}\n\nexport const ringForRequest = (\n\treq: PayloadRequest,\n\tmarker: EncryptedFieldMarker\n): Promise<KeyRing> => {\n\tconst registry = getFieldsRegistry(req.payload.config)\n\treturn resolveKeys(marker.keys ?? registry?.encrypted?.keys, req.payload.config.secret)\n}\n\ntype SlugHolder = { slug: string } | null | undefined\n\nconst aadSlug = (collection: SlugHolder, global: SlugHolder): string =>\n\tcollection?.slug ?? global?.slug ?? ''\n\nconst defaultLocale = (config: SanitizedConfig): string =>\n\tconfig.localization ? config.localization.defaultLocale : 'en'\n\n/** Mirrors beforeChange/promise.ts: the locale a write applies to. */\nconst operationLocale = (req: PayloadRequest): string => {\n\tconst locale = req.locale\n\tif (!locale || locale === 'all') {\n\t\treturn defaultLocale(req.payload.config)\n\t}\n\treturn locale\n}\n\n/**\n * AAD binds a ciphertext to its `${slug}.${field}[.${locale}]` slot via\n * buildAad, which rejects any dotted component so the joined data stays\n * unambiguous (a dotted slug/locale would blur the cross-field binding).\n */\nexport const sealAad = (marker: EncryptedFieldMarker, slug: string, req: PayloadRequest): string =>\n\tbuildAad(\n\t\tmarker.localized ? [slug, marker.fieldName, operationLocale(req)] : [slug, marker.fieldName]\n\t)\n\n/**\n * Read-side AAD candidates. Localized fields try the request locale first,\n * then every configured locale: fallbackLocale hoisting and locale=all hook\n * execution mean the hook cannot know which locale sealed the value.\n */\nexport const readAadCandidates = (\n\tmarker: EncryptedFieldMarker,\n\tslug: string,\n\treq: PayloadRequest\n): string[] => {\n\tif (!marker.localized) {\n\t\treturn [buildAad([slug, marker.fieldName])]\n\t}\n\tconst codes = req.payload.config.localization\n\t\t? req.payload.config.localization.localeCodes\n\t\t: [defaultLocale(req.payload.config)]\n\tconst first = operationLocale(req)\n\tconst ordered = [first, ...codes.filter((code) => code !== first)]\n\treturn ordered.map((code) => buildAad([slug, marker.fieldName, code]))\n}\n\n/**\n * The active utility mode from the request context, or undefined for a normal\n * operation (including a missing context, which reads as normal). Reused by the\n * response stripper so bulk utilities (which read in `raw` mode) still see the\n * ciphertext and blind-index siblings, while a normal read strips them.\n */\nexport const contextMode = (\n\tcontext: Record<string, unknown> | undefined\n): EncryptedContextMode | undefined => {\n\tconst mode = context?.[ENCRYPTED_CONTEXT_KEY]\n\treturn mode === 'decrypt' || mode === 'raw' || mode === 'rotate' ? mode : undefined\n}\n\n/** A locale=all write hands the hook a `{ [locale]: value }` map, not a scalar. */\nconst isLocaleMap = (value: unknown): value is Record<string, unknown> =>\n\ttypeof value === 'object' && value !== null && !Array.isArray(value)\n\ninterface SealForLocaleArgs {\n\taad: string\n\thasMany: boolean\n\tkey: Buffer\n\tkeyId: string\n}\n\n/** Seal one locale's value, passing already-sealed items through unchanged. */\nconst sealValueForLocale = (value: unknown, args: SealForLocaleArgs): unknown => {\n\tif (value == null) {\n\t\treturn value\n\t}\n\tconst sealItem = (item: unknown): unknown =>\n\t\tisSealed(item)\n\t\t\t? item\n\t\t\t: seal({ aad: args.aad, key: args.key, keyId: args.keyId, plaintext: item })\n\treturn args.hasMany && Array.isArray(value) ? value.map(sealItem) : sealItem(value)\n}\n\nexport const makeBeforeChangeHook = (marker: EncryptedFieldMarker): FieldHook => {\n\treturn async (args) => {\n\t\tconst { collection, global, req, siblingData, value } = args\n\t\tconst mode = contextMode(req.context as Record<string, unknown>)\n\n\t\t// Utilities read ciphertext untouched.\n\t\tif (mode === 'raw') {\n\t\t\treturn value\n\t\t}\n\t\t// Removal path: store incoming plaintext without sealing, drop the now\n\t\t// meaningless blind index.\n\t\tif (mode === 'decrypt') {\n\t\t\tif (marker.queryable && marker.bidxName) {\n\t\t\t\tsiblingData[marker.bidxName] = null\n\t\t\t}\n\t\t\treturn value\n\t\t}\n\n\t\tconst slug = aadSlug(collection, global)\n\t\tconst ring = await ringForRequest(req, marker)\n\t\tconst activeKey = ring.dataKeys.get(ring.activeId) as Buffer\n\n\t\tif (mode === 'rotate') {\n\t\t\tconst candidates = readAadCandidates(marker, slug, req)\n\t\t\tconst writeAad = sealAad(marker, slug, req)\n\t\t\tconst rotateOne = (item: unknown): unknown => {\n\t\t\t\tif (!isSealed(item)) {\n\t\t\t\t\treturn item\n\t\t\t\t}\n\t\t\t\tif (parseWire(item).keyId === ring.activeId) {\n\t\t\t\t\treturn item\n\t\t\t\t}\n\t\t\t\tconst plaintext = unseal(item, ring.dataKeys, candidates)\n\t\t\t\tif (marker.queryable && marker.bidxName) {\n\t\t\t\t\tsiblingData[marker.bidxName] = computeBidx(plaintext, ring.indexKey, marker.normalize)\n\t\t\t\t}\n\t\t\t\treturn seal({ aad: writeAad, key: activeKey, keyId: ring.activeId, plaintext })\n\t\t\t}\n\t\t\treturn marker.hasMany && Array.isArray(value) ? value.map(rotateOne) : rotateOne(value)\n\t\t}\n\n\t\tif (value === undefined) {\n\t\t\treturn undefined\n\t\t}\n\t\tif (value === null) {\n\t\t\tif (marker.queryable && marker.bidxName) {\n\t\t\t\tsiblingData[marker.bidxName] = null\n\t\t\t}\n\t\t\treturn null\n\t\t}\n\n\t\t// locale=all write: value is a `{ [locale]: value }` map. Seal each locale\n\t\t// under its own locale AAD so afterRead's per-locale unseal opens it (a\n\t\t// single blob sealed under the default-locale AAD would not). Plaintext\n\t\t// validation and blind-index maintenance for bulk all-locales writes are\n\t\t// deferred to per-locale writes (covered by Batch E int tests).\n\t\tif (marker.localized && req.locale === 'all' && isLocaleMap(value)) {\n\t\t\tconst sealedMap: Record<string, unknown> = {}\n\t\t\tfor (const [locale, localeValue] of Object.entries(value)) {\n\t\t\t\tsealedMap[locale] = sealValueForLocale(localeValue, {\n\t\t\t\t\taad: buildAad([slug, marker.fieldName, locale]),\n\t\t\t\t\thasMany: marker.hasMany,\n\t\t\t\t\tkey: activeKey,\n\t\t\t\t\tkeyId: ring.activeId,\n\t\t\t\t})\n\t\t\t}\n\t\t\treturn sealedMap\n\t\t}\n\n\t\tconst aad = sealAad(marker, slug, req)\n\t\tconst sealOne = (item: unknown): string =>\n\t\t\tseal({ aad, key: activeKey, keyId: ring.activeId, plaintext: item })\n\n\t\tif (marker.hasMany) {\n\t\t\tif (!Array.isArray(value)) {\n\t\t\t\treturn value\n\t\t\t}\n\t\t\t// Seal PER ITEM so an already-sealed item (a passthrough from a prior\n\t\t\t// read, e.g. a mixed array) is never wrapped in a second GCM layer.\n\t\t\tconst sealedArray = value.map((item) => (isSealed(item) ? item : sealOne(item)))\n\t\t\t// Stash the plaintext for the composed validate, keyed by the sealed\n\t\t\t// output (unique per write), only for a fresh all-plaintext write. A\n\t\t\t// mixed/passthrough array is not stashed; its already-sealed items were\n\t\t\t// validated when first written, so their re-validation is deferred.\n\t\t\tif (!value.some(isSealed)) {\n\t\t\t\tstashPlaintext(req, sealedArrayKey(sealedArray), value)\n\t\t\t}\n\t\t\treturn sealedArray\n\t\t}\n\n\t\t// Single value already sealed: a resubmitted read or unchanged sibling;\n\t\t// passthrough without re-sealing (no plaintext to stash).\n\t\tif (isSealed(value)) {\n\t\t\treturn value\n\t\t}\n\t\t// Stash the plaintext for the composed validate, keyed by the sealed value\n\t\t// (unique per write); do not validate/throw here.\n\t\tconst sealed = sealOne(value)\n\t\tstashPlaintext(req, sealed, value)\n\t\tif (marker.queryable && marker.bidxName) {\n\t\t\tsiblingData[marker.bidxName] = computeBidx(value, ring.indexKey, marker.normalize)\n\t\t}\n\t\treturn sealed\n\t}\n}\n\ninterface ApplyPolicyArgs {\n\terror: unknown\n\tmarker: EncryptedFieldMarker\n\tpolicy: DecryptFailurePolicy\n\traw: unknown\n\tslug: string\n}\n\nconst applyPolicy = ({ error, marker, policy, raw, slug }: ApplyPolicyArgs): unknown => {\n\tif (policy === 'null') {\n\t\treturn null\n\t}\n\tif (policy === 'passthrough') {\n\t\treturn raw\n\t}\n\tif (typeof policy === 'function') {\n\t\treturn policy({\n\t\t\tcollection: slug,\n\t\t\terror,\n\t\t\tfield: marker.fieldName,\n\t\t\tvalue: typeof raw === 'string' ? raw : String(raw),\n\t\t})\n\t}\n\tconst keyId = isSealed(raw) ? (raw as string).split('.')[1] : undefined\n\tthrow new DecryptFailedError({ cause: error, field: marker.fieldName, keyId, slug })\n}\n\ninterface OpenSealedArgs {\n\tcandidates: string[]\n\tmarker: EncryptedFieldMarker\n\tpolicy: DecryptFailurePolicy\n\tring: KeyRing\n\tslug: string\n}\n\n/**\n * Unseals one value, applying the decrypt-failure policy on a non-sealed item\n * (plaintext at rest is pre-adoption data; passthrough is the lazy-migration\n * mode) or a failed unseal. Shared by the scalar afterRead hook and the\n * richText decrypt hook.\n */\nconst openSealed = (item: unknown, args: OpenSealedArgs): unknown => {\n\tconst { candidates, marker, policy, ring, slug } = args\n\tif (!isSealed(item)) {\n\t\treturn applyPolicy({ error: new Error('value is not sealed'), marker, policy, raw: item, slug })\n\t}\n\ttry {\n\t\treturn unseal(item, ring.dataKeys, candidates)\n\t} catch (error) {\n\t\treturn applyPolicy({ error, marker, policy, raw: item, slug })\n\t}\n}\n\nconst resolvePolicy = (req: PayloadRequest, marker: EncryptedFieldMarker): DecryptFailurePolicy => {\n\tconst registry = getFieldsRegistry(req.payload.config)\n\treturn marker.onDecryptFailure ?? registry?.encrypted?.onDecryptFailure ?? 'throw'\n}\n\nexport const makeAfterReadHook = (marker: EncryptedFieldMarker): FieldHook => {\n\treturn async (args) => {\n\t\tconst { collection, context, global, req, value } = args\n\t\tif (value === undefined || value === null) {\n\t\t\treturn value\n\t\t}\n\t\tif (contextMode(context)) {\n\t\t\treturn value\n\t\t}\n\t\tconst slug = aadSlug(collection, global)\n\t\tconst ring = await ringForRequest(req, marker)\n\t\tconst openArgs: OpenSealedArgs = {\n\t\t\tcandidates: readAadCandidates(marker, slug, req),\n\t\t\tmarker,\n\t\t\tpolicy: resolvePolicy(req, marker),\n\t\t\tring,\n\t\t\tslug,\n\t\t}\n\t\tconst openOne = (item: unknown): unknown => openSealed(item, openArgs)\n\t\treturn marker.hasMany && Array.isArray(value) ? value.map(openOne) : openOne(value)\n\t}\n}\n\n/**\n * afterRead on the virtual richText field: decrypts the ciphertext sibling into\n * a SerializedEditorState. The virtual field is never persisted, so its own\n * value is always undefined and the ciphertext SIBLING is the source. The\n * ciphertext field has no afterRead, so that sibling holds raw ciphertext for\n * the whole phase, making this the single deterministic reader. Runs before the\n * editor's own afterRead, which then populates upload/relationship nodes on the\n * decrypted object.\n */\nexport const makeRichTextDecryptHook = (\n\tmarker: EncryptedFieldMarker,\n\tstoredName: string\n): FieldHook => {\n\treturn async (args) => {\n\t\tconst { collection, context, global, req, siblingData } = args\n\t\tif (contextMode(context)) {\n\t\t\treturn args.value\n\t\t}\n\t\tconst ciphertext = (siblingData as Record<string, unknown>)[storedName]\n\t\tif (ciphertext === undefined || ciphertext === null) {\n\t\t\treturn ciphertext\n\t\t}\n\t\tconst slug = aadSlug(collection, global)\n\t\tconst ring = await ringForRequest(req, marker)\n\t\treturn openSealed(ciphertext, {\n\t\t\tcandidates: readAadCandidates(marker, slug, req),\n\t\t\tmarker,\n\t\t\tpolicy: resolvePolicy(req, marker),\n\t\t\tring,\n\t\t\tslug,\n\t\t})\n\t}\n}\n\n/**\n * beforeChange on the virtual richText field: seals the submitted\n * SerializedEditorState into the ciphertext sibling and returns the plaintext\n * unchanged (Payload drops it at the DB write since the field is virtual). The\n * sole normal-mode writer of the ciphertext slot. Utility flows (rotate/decrypt/\n * raw) pass through untouched; the ciphertext field's own hook handles rotation.\n * An absent value (partial write) preserves the existing ciphertext.\n */\nexport const makeRichTextSealHook = (\n\tmarker: EncryptedFieldMarker,\n\tstoredName: string\n): FieldHook => {\n\treturn async (args) => {\n\t\tconst { collection, global, req, siblingData, value } = args\n\t\tif (contextMode(req.context as Record<string, unknown>)) {\n\t\t\treturn value\n\t\t}\n\t\tif (value === undefined) {\n\t\t\treturn undefined\n\t\t}\n\t\tconst sibling = siblingData as Record<string, unknown>\n\t\tif (value === null) {\n\t\t\tsibling[storedName] = null\n\t\t\treturn null\n\t\t}\n\t\tconst slug = aadSlug(collection, global)\n\t\tconst ring = await ringForRequest(req, marker)\n\t\tconst activeKey = ring.dataKeys.get(ring.activeId) as Buffer\n\t\t// locale=all write: value is a `{ [locale]: SerializedEditorState }` map.\n\t\t// Seal each locale under its own locale AAD so the per-locale decrypt opens\n\t\t// it, mirroring the scalar hook's locale-map handling.\n\t\tif (marker.localized && req.locale === 'all' && isLocaleMap(value)) {\n\t\t\tconst sealedMap: Record<string, unknown> = {}\n\t\t\tfor (const [locale, localeValue] of Object.entries(value)) {\n\t\t\t\tsealedMap[locale] =\n\t\t\t\t\tlocaleValue == null || isSealed(localeValue)\n\t\t\t\t\t\t? localeValue\n\t\t\t\t\t\t: seal({\n\t\t\t\t\t\t\t\taad: buildAad([slug, marker.fieldName, locale]),\n\t\t\t\t\t\t\t\tkey: activeKey,\n\t\t\t\t\t\t\t\tkeyId: ring.activeId,\n\t\t\t\t\t\t\t\tplaintext: localeValue,\n\t\t\t\t\t\t\t})\n\t\t\t}\n\t\t\tsibling[storedName] = sealedMap\n\t\t\treturn value\n\t\t}\n\t\tsibling[storedName] = isSealed(value)\n\t\t\t? value\n\t\t\t: seal({\n\t\t\t\t\taad: sealAad(marker, slug, req),\n\t\t\t\t\tkey: activeKey,\n\t\t\t\t\tkeyId: ring.activeId,\n\t\t\t\t\tplaintext: value,\n\t\t\t\t})\n\t\treturn value\n\t}\n}\n\n/**\n * beforeChange on the hidden ciphertext field. A no-op in every mode except\n * rotate (the virtual field's seal hook is the sole normal-mode producer of this\n * slot). Under rotate it unseals with the stale key and reseals with the active\n * key so rotateEncryptedFields round-trips, mirroring the scalar rotate branch.\n */\nexport const makeRichTextCiphertextHook = (marker: EncryptedFieldMarker): FieldHook => {\n\treturn async (args) => {\n\t\tconst { collection, global, req, value } = args\n\t\tif (contextMode(req.context as Record<string, unknown>) !== 'rotate') {\n\t\t\treturn undefined\n\t\t}\n\t\tif (!isSealed(value)) {\n\t\t\treturn value\n\t\t}\n\t\tconst ring = await ringForRequest(req, marker)\n\t\tif (parseWire(value).keyId === ring.activeId) {\n\t\t\treturn value\n\t\t}\n\t\tconst slug = aadSlug(collection, global)\n\t\tconst plaintext = unseal(value, ring.dataKeys, readAadCandidates(marker, slug, req))\n\t\tconst activeKey = ring.dataKeys.get(ring.activeId) as Buffer\n\t\treturn seal({\n\t\t\taad: sealAad(marker, slug, req),\n\t\t\tkey: activeKey,\n\t\t\tkeyId: ring.activeId,\n\t\t\tplaintext,\n\t\t})\n\t}\n}\n\n/**\n * Validate for the virtual richText field. Delegates to the editor's own\n * validate (required + node-level validation) for full parity with a native\n * richText field. Skips utility flows and absent values: rotate/decrypt patch\n * only the ciphertext sibling, so the virtual value is undefined then, and a\n * required check must not trip on that.\n */\nexport const makeRichTextValidate = (): Validate<unknown, unknown, unknown, RichTextField> => {\n\treturn (value, options) => {\n\t\tif (contextMode(options.req.context as Record<string, unknown>)) {\n\t\t\treturn true\n\t\t}\n\t\tif (value === undefined) {\n\t\t\treturn true\n\t\t}\n\t\tconst { editor } = options\n\t\tif (!editor || typeof editor === 'function' || typeof editor.validate !== 'function') {\n\t\t\treturn true\n\t\t}\n\t\treturn editor.validate(value, options)\n\t}\n}\n"],"mappings":";;;;;;;;;AAsBA,IAAa,qBAAb,cAAwC,MAAM;CAC7C,YAAY,EAAE,OAAO,OAAO,OAAO,QAA2B;EAC7D,MAAM,UAAU,QAAQ,YAAY,MAAM,MAAM;EAChD,MACC,wCAAwC,KAAK,GAAG,QAAQ,QAAQ,IAAI,iBAAiB,QAAQ,MAAM,OAAO,iBAC3G;EACA,KAAK,OAAO;EACZ,KAAK,QAAQ;CACd;AACD;AAEA,MAAa,kBACZ,KACA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;EACZ,CAAC;EACH,OAAO;CACR;AACD;;;;;;;AAQA,MAAa,8BAA8B,WAA4C;CACtF,OAAO,OAAO,SAAS;EACtB,MAAM,EAAE,YAAY,QAAQ,KAAK,UAAU;EAC3C,IAAI,YAAY,IAAI,OAAkC,MAAM,UAC3D;EAED,IAAI,CAAC,SAAS,KAAK,GAClB,OAAO;EAER,MAAM,OAAO,MAAM,eAAe,KAAK,MAAM;EAC7C,IAAI,UAAU,KAAK,EAAE,UAAU,KAAK,UACnC,OAAO;EAER,MAAM,OAAO,QAAQ,YAAY,MAAM;EACvC,MAAM,YAAY,OAAO,OAAO,KAAK,UAAU,kBAAkB,QAAQ,MAAM,GAAG,CAAC;EACnF,MAAM,YAAY,KAAK,SAAS,IAAI,KAAK,QAAQ;EACjD,OAAO,KAAK;GACX,KAAK,QAAQ,QAAQ,MAAM,GAAG;GAC9B,KAAK;GACL,OAAO,KAAK;GACZ;EACD,CAAC;CACF;AACD;;;;;;;;AASA,MAAa,6BAAiF;CAC7F,QAAQ,OAAO,YAAY;EAC1B,IAAI,YAAY,QAAQ,IAAI,OAAkC,GAC7D,OAAO;EAER,IAAI,UAAU,KAAA,GACb,OAAO;EAER,MAAM,EAAE,WAAW;EACnB,IAAI,CAAC,UAAU,OAAO,WAAW,cAAc,OAAO,OAAO,aAAa,YACzE,OAAO;EAER,OAAO,OAAO,SAAS,OAAO,OAAO;CACtC;AACD"}
1
+ {"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,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;;;;;;;AAQA,MAAa,WACZ,QACA,MACA,QACY;CACZ,IAAI,OAAO,WACV,OAAO,UAAU,QAAQ,MAAM,gBAAgB,GAAG,CAAC;CAEpD,OAAO,SAAS,CAAC,WAAW,QAAQ,IAAI,GAAG,OAAO,SAAS,CAAC;AAC7D;;AAGA,MAAM,aAAa,QAA8B,MAAc,WAC9D,SAAS;CAAC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Config, 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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D,OAAO;CACR;AACD;;;;;;AAOA,MAAa,6BAA6B,eAAmD;CAC5F,MAAM,aAAa,oBAAoB,WAAW,MAAM;CACxD,MAAM,mBAAmB,cAAc,UAAU;CACjD,MAAM,YAAY,CAAC,GAAG,gBAAgB,EAAE,KAAK,CAAC,MAAM,YACnD,YAAY,MAAM,OAAO,QAAkB,CAC5C;CAIA,MAAM,kBAAkB,CAAC,GAAG,UAAU,EACpC,QAAQ,GAAG,YAAY,OAAO,eAAe,UAAU,EACvD,KAAK,CAAC,UAAU,IAAI;CACtB,MAAM,aAAa,CAAC,GAAG,WAAW,GAAG,eAAe;CACpD,IAAI,iBAAiB,SAAS,KAAK,WAAW,WAAW,GACxD,OAAO;CAER,MAAM,QAAgD,EAAE,GAAG,WAAW,MAAM;CAC5E,IAAI,WAAW,SAAS,GACvB,MAAM,YAAY,CAAC,GAAI,WAAW,OAAO,aAAa,CAAC,GAAI,mBAAmB,UAAU,CAAC;CAE1F,IAAI,iBAAiB,OAAO,GAC3B,MAAM,kBAAkB,CACvB,SAAS,gBAAgB,GACzB,GAAI,WAAW,OAAO,mBAAmB,CAAC,CAC3C;CAED,OAAO;EAAE,GAAG;EAAY;CAAM;AAC/B"}
1
+ {"version":3,"file":"queryRewrite.js","names":[],"sources":["../../../src/fields/encrypted/queryRewrite.ts"],"sourcesContent":["import type {\n\tCollectionAfterReadHook,\n\tCollectionBeforeOperationHook,\n\tCollectionConfig,\n\tGlobalAfterReadHook,\n\tGlobalConfig,\n\tPayloadRequest,\n\tWhere,\n} from 'payload'\nimport { computeBidx } from './crypto/bidx'\nimport type { KeyRing } from './crypto/keys'\nimport { contextMode, ringForRequest } from './hooks'\nimport { queryableOnly, scanEncryptedFields } from './scan'\nimport type { EncryptedFieldMarker } from './types'\n\ntype RingResolver = (marker: EncryptedFieldMarker) => Promise<KeyRing>\n\ntype UnsupportedWarn = (path: string, operator: string) => void\n\n/**\n * A blind index answers exact-match only. An unsupported operator is rewritten\n * to this sentinel so the query matches nothing: every real index value is a\n * 24-char base64url string, and a single space is not one. Exported for tests.\n */\nexport const BIDX_NO_MATCH = ' '\n\nconst isPlainObject = (value: unknown): value is Record<string, unknown> =>\n\ttypeof value === 'object' && value !== null && !Array.isArray(value)\n\nconst rewriteConstraint = async (args: {\n\tconstraint: Record<string, unknown>\n\tmarker: EncryptedFieldMarker\n\tringFor: RingResolver\n\twarn: (operator: string) => void\n}): Promise<Record<string, unknown>> => {\n\tconst { constraint, marker, ringFor, warn } = args\n\tconst ring = await ringFor(marker)\n\tconst toBidx = (value: unknown): unknown =>\n\t\tvalue === null ? null : computeBidx(value, ring.indexKey, marker.normalize)\n\t// Payload's REST layer delivers `in`/`not_in` as a comma-joined string, the\n\t// admin and Local API as an array; hash each element under either shape.\n\tconst toBidxArray = (value: unknown): unknown[] => {\n\t\tconst items = Array.isArray(value)\n\t\t\t? value\n\t\t\t: typeof value === 'string'\n\t\t\t\t? value.split(',').map((item) => item.trim())\n\t\t\t\t: []\n\t\treturn items.map(toBidx)\n\t}\n\tconst rewritten: Record<string, unknown> = {}\n\tfor (const [operator, operand] of Object.entries(constraint)) {\n\t\tswitch (operator) {\n\t\t\tcase 'equals':\n\t\t\t\trewritten.equals = toBidx(operand)\n\t\t\t\tbreak\n\t\t\tcase 'not_equals':\n\t\t\t\trewritten.not_equals = toBidx(operand)\n\t\t\t\tbreak\n\t\t\tcase 'in':\n\t\t\t\trewritten.in = toBidxArray(operand)\n\t\t\t\tbreak\n\t\t\tcase 'not_in':\n\t\t\t\trewritten.not_in = toBidxArray(operand)\n\t\t\t\tbreak\n\t\t\tcase 'exists':\n\t\t\t\t// The blind index is written iff the source has a value, so its\n\t\t\t\t// existence tracks the source's. The boolean passes through unhashed.\n\t\t\t\trewritten.exists = operand\n\t\t\t\tbreak\n\t\t\tdefault:\n\t\t\t\t// Substring, range, comparison, and geo operators cannot run over a\n\t\t\t\t// blind index. Match nothing rather than querying the ciphertext\n\t\t\t\t// column, which would read as a working filter while returning junk.\n\t\t\t\twarn(operator)\n\t\t\t\treturn { equals: BIDX_NO_MATCH }\n\t\t}\n\t}\n\treturn rewritten\n}\n\n/** Recursively rewrites queryable encrypted paths to their blind-index siblings. */\nexport const rewriteWhereForMarkers = async (args: {\n\tmarkers: ReadonlyMap<string, EncryptedFieldMarker>\n\tringFor: RingResolver\n\twarn?: UnsupportedWarn\n\twhere: Where\n}): Promise<Where> => {\n\tconst { markers, ringFor, warn = () => {}, where } = args\n\tconst out: Where = {}\n\tfor (const [key, value] of Object.entries(where)) {\n\t\tif ((key === 'and' || key === 'or') && Array.isArray(value)) {\n\t\t\tout[key] = await Promise.all(\n\t\t\t\tvalue.map((nested) =>\n\t\t\t\t\trewriteWhereForMarkers({ markers, ringFor, warn, where: nested as Where })\n\t\t\t\t)\n\t\t\t)\n\t\t\tcontinue\n\t\t}\n\t\tconst marker = markers.get(key)\n\t\tif (marker?.bidxName && isPlainObject(value)) {\n\t\t\tconst rewritten = await rewriteConstraint({\n\t\t\t\tconstraint: value,\n\t\t\t\tmarker,\n\t\t\t\tringFor,\n\t\t\t\twarn: (operator) => warn(key, operator),\n\t\t\t})\n\t\t\tconst bidxPath = key.includes('.')\n\t\t\t\t? `${key.slice(0, key.lastIndexOf('.') + 1)}${marker.bidxName}`\n\t\t\t\t: marker.bidxName\n\t\t\tout[bidxPath] = { ...(out[bidxPath] as Record<string, unknown>), ...rewritten }\n\t\t\tcontinue\n\t\t}\n\t\tout[key] = value as Where[string]\n\t}\n\treturn out\n}\n\nconst makeHook = (\n\tmarkers: ReadonlyMap<string, EncryptedFieldMarker>\n): CollectionBeforeOperationHook => {\n\treturn async ({ args, req }) => {\n\t\tif (isPlainObject(args) && 'where' in args && isPlainObject(args.where)) {\n\t\t\tconst payloadReq = req as PayloadRequest\n\t\t\tconst where = await rewriteWhereForMarkers({\n\t\t\t\tmarkers,\n\t\t\t\tringFor: (marker) => ringForRequest(payloadReq, marker),\n\t\t\t\twarn: (path, operator) =>\n\t\t\t\t\tpayloadReq.payload?.logger?.warn?.(\n\t\t\t\t\t\t`@10x-media/fields: operator '${operator}' cannot run on the encrypted field '${path}'. Blind-index filtering supports exact match only (equals, not_equals, in, not_in, exists); this constraint will match nothing.`\n\t\t\t\t\t),\n\t\t\t\twhere: args.where as Where,\n\t\t\t})\n\t\t\treturn { ...args, where }\n\t\t}\n\t\treturn args\n\t}\n}\n\nconst bidxPathFor = (path: string, bidxName: string): string =>\n\tpath.includes('.') ? `${path.slice(0, path.lastIndexOf('.') + 1)}${bidxName}` : bidxName\n\nconst deleteAtPath = (doc: Record<string, unknown>, path: string): void => {\n\tconst segments = path.split('.')\n\tlet node: Record<string, unknown> = doc\n\tfor (const segment of segments.slice(0, -1)) {\n\t\tconst next = node[segment]\n\t\tif (!next || typeof next !== 'object') {\n\t\t\treturn\n\t\t}\n\t\tnode = next as Record<string, unknown>\n\t}\n\tdelete node[segments[segments.length - 1] as string]\n}\n\n/**\n * Removes server-only encrypted paths from read results: blind-index hashes (so\n * the keyed index value never leaves the server), richText ciphertext siblings\n * (opaque strings the virtual editor field replaces), and write-only fields\n * (whose sealed value passes afterRead untouched and must not surface at all).\n * `admin.hidden` keeps the siblings readable by the plugin's own hooks but,\n * unlike top-level `hidden`, does not strip them from responses.\n */\nconst makeStripPathsHook = (paths: string[]): CollectionAfterReadHook & GlobalAfterReadHook => {\n\treturn ({ context, doc }) => {\n\t\t// Bulk utilities (rotate/adopt/remove) read via pageThrough in `raw`\n\t\t// context and need the ciphertext + blind-index siblings; stripping them\n\t\t// here would make key rotation silently skip every richText field. Only\n\t\t// strip on normal reads.\n\t\tif (contextMode(context as Record<string, unknown>)) {\n\t\t\treturn doc\n\t\t}\n\t\tfor (const path of paths) {\n\t\t\tdeleteAtPath(doc as Record<string, unknown>, path)\n\t\t}\n\t\treturn doc\n\t}\n}\n\n/** Response paths a normal read must not surface, per marker kind. */\nconst stripPathsFor = (markers: ReadonlyMap<string, EncryptedFieldMarker>): string[] => {\n\tconst paths: string[] = []\n\tfor (const [path, marker] of markers) {\n\t\tif (marker.queryable && marker.bidxName) {\n\t\t\tpaths.push(bidxPathFor(path, marker.bidxName))\n\t\t}\n\t\t// richText stores its ciphertext under the marker's own scan path\n\t\t// (`${name}_encrypted`); the write-only path IS the stored field itself.\n\t\tif (marker.sourceType === 'richText' || marker.writeOnly) {\n\t\t\tpaths.push(path)\n\t\t}\n\t}\n\treturn paths\n}\n\n/**\n * Attaches the blind-index where-rewrite and response stripper to a collection.\n * The fields() plugin applies this to every collection automatically; call it\n * directly only when using encryptedField() standalone without the plugin.\n */\nexport const withEncryptedQueryRewrite = (collection: CollectionConfig): CollectionConfig => {\n\tconst allMarkers = scanEncryptedFields(collection.fields)\n\tconst queryableMarkers = queryableOnly(allMarkers)\n\tconst stripPaths = stripPathsFor(allMarkers)\n\tif (queryableMarkers.size === 0 && stripPaths.length === 0) {\n\t\treturn collection\n\t}\n\tconst hooks: NonNullable<CollectionConfig['hooks']> = { ...collection.hooks }\n\tif (stripPaths.length > 0) {\n\t\thooks.afterRead = [...(collection.hooks?.afterRead ?? []), makeStripPathsHook(stripPaths)]\n\t}\n\tif (queryableMarkers.size > 0) {\n\t\thooks.beforeOperation = [\n\t\t\tmakeHook(queryableMarkers),\n\t\t\t...(collection.hooks?.beforeOperation ?? []),\n\t\t]\n\t}\n\treturn { ...collection, hooks }\n}\n\n/**\n * Attaches the response stripper to a global. Globals take no `where`, so this\n * is the strip alone: blind-index hashes, richText ciphertext siblings, and\n * write-only fields never surface in a read result. The fields() plugin applies\n * this to every global automatically; call it directly only when using\n * encryptedField() standalone without the plugin.\n */\nexport const withEncryptedResponseStrip = (global: GlobalConfig): GlobalConfig => {\n\tconst stripPaths = stripPathsFor(scanEncryptedFields(global.fields))\n\tif (stripPaths.length === 0) {\n\t\treturn global\n\t}\n\treturn {\n\t\t...global,\n\t\thooks: {\n\t\t\t...global.hooks,\n\t\t\tafterRead: [...(global.hooks?.afterRead ?? []), makeStripPathsHook(stripPaths)],\n\t\t},\n\t}\n}\n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#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