@10x-media/form-builder 0.1.0-beta.9 → 4.0.0-alpha.1
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.
- package/CHANGELOG.md +173 -0
- package/README.md +11 -3
- package/dist/actions/assertNoBlockCollision.js +18 -0
- package/dist/actions/assertNoBlockCollision.js.map +1 -0
- package/dist/actions/body/serializeBody.d.ts +16 -14
- package/dist/actions/body/serializeBody.js +5 -8
- package/dist/actions/body/serializeBody.js.map +1 -1
- package/dist/actions/builtin/confirmation.js +2 -1
- package/dist/actions/builtin/confirmation.js.map +1 -1
- package/dist/actions/builtin/emailAction.d.ts +15 -3
- package/dist/actions/builtin/emailAction.js +72 -20
- package/dist/actions/builtin/emailAction.js.map +1 -1
- package/dist/actions/builtin/emailTeam.js +11 -5
- package/dist/actions/builtin/emailTeam.js.map +1 -1
- package/dist/actions/defineAction.d.ts +37 -6
- package/dist/actions/defineAction.js +14 -1
- package/dist/actions/defineAction.js.map +1 -1
- package/dist/actions/dispatch.d.ts +12 -0
- package/dist/actions/dispatch.js +103 -30
- package/dist/actions/dispatch.js.map +1 -1
- package/dist/actions/dispatchContext.js +19 -0
- package/dist/actions/dispatchContext.js.map +1 -0
- package/dist/actions/emailRecipients.js +38 -8
- package/dist/actions/emailRecipients.js.map +1 -1
- package/dist/actions/emailRender.d.ts +27 -0
- package/dist/actions/fromAddresses.d.ts +19 -1
- package/dist/actions/fromAddresses.js +66 -9
- package/dist/actions/fromAddresses.js.map +1 -1
- package/dist/actions/recipientSources.d.ts +23 -0
- package/dist/actions/recipientSources.js +11 -0
- package/dist/actions/recipientSources.js.map +1 -0
- package/dist/actions/registry.js +3 -1
- package/dist/actions/registry.js.map +1 -1
- package/dist/actions/runActions.d.ts +2 -0
- package/dist/actions/runActions.js +13 -8
- package/dist/actions/runActions.js.map +1 -1
- package/dist/actions/sign.js.map +1 -1
- package/dist/actions/submissionContext.d.ts +34 -0
- package/dist/actions/task.js +43 -16
- package/dist/actions/task.js.map +1 -1
- package/dist/aggregation/aggregateResponses.js +3 -4
- package/dist/aggregation/aggregateResponses.js.map +1 -1
- package/dist/aggregation/resolveResultsRequest.d.ts +6 -0
- package/dist/aggregation/resolveResultsRequest.js +69 -26
- package/dist/aggregation/resolveResultsRequest.js.map +1 -1
- package/dist/calc/computeCalcFields.d.ts +5 -3
- package/dist/calc/computeCalcFields.js +4 -3
- package/dist/calc/computeCalcFields.js.map +1 -1
- package/dist/calc/evaluate.d.ts +26 -3
- package/dist/calc/evaluate.js +33 -11
- package/dist/calc/evaluate.js.map +1 -1
- package/dist/calc/formatCalc.d.ts +11 -0
- package/dist/calc/formatCalc.js +35 -0
- package/dist/calc/formatCalc.js.map +1 -0
- package/dist/calc/formatCalcValue.d.ts +17 -0
- package/dist/calc/formatCalcValue.js +17 -0
- package/dist/calc/formatCalcValue.js.map +1 -0
- package/dist/calc/normalizeCalc.d.ts +17 -3
- package/dist/calc/normalizeCalc.js +39 -17
- package/dist/calc/normalizeCalc.js.map +1 -1
- package/dist/calc/registry.d.ts +43 -0
- package/dist/calc/registry.js +27 -0
- package/dist/calc/registry.js.map +1 -0
- package/dist/calc/resolveCalcContext.d.ts +36 -0
- package/dist/calc/resolveCalcContext.js +87 -0
- package/dist/calc/resolveCalcContext.js.map +1 -0
- package/dist/calc/types.d.ts +19 -4
- package/dist/calc/types.js +3 -2
- package/dist/calc/types.js.map +1 -1
- package/dist/client/ByteSizeField.js +11 -8
- package/dist/client/ByteSizeField.js.map +1 -1
- package/dist/client/CalcExpressionBuilder.d.ts +20 -0
- package/dist/client/CalcExpressionBuilder.js +888 -0
- package/dist/client/CalcExpressionBuilder.js.map +1 -0
- package/dist/client/ClosePollButton.js +3 -3
- package/dist/client/ClosePollButton.js.map +1 -1
- package/dist/client/CondensedArray.d.ts +2 -2
- package/dist/client/CondensedArray.js +5 -7
- package/dist/client/CondensedArray.js.map +1 -1
- package/dist/client/ConditionBuilder.js +5 -7
- package/dist/client/ConditionBuilder.js.map +1 -1
- package/dist/client/ConditionRow.js +3 -3
- package/dist/client/ConditionRow.js.map +1 -1
- package/dist/client/ConsentBlockLabel.js +2 -2
- package/dist/client/ConsentBlockLabel.js.map +1 -1
- package/dist/client/ConsentRetentionNotice.d.ts +11 -0
- package/dist/client/ConsentRetentionNotice.js +23 -0
- package/dist/client/ConsentRetentionNotice.js.map +1 -0
- package/dist/client/EndpointOptionsSelect.d.ts +17 -7
- package/dist/client/EndpointOptionsSelect.js +18 -14
- package/dist/client/EndpointOptionsSelect.js.map +1 -1
- package/dist/client/FieldBlockLabel.js +2 -2
- package/dist/client/FieldBlockLabel.js.map +1 -1
- package/dist/client/FieldNameSelect.d.ts +1 -0
- package/dist/client/FieldNameSelect.js +2 -4
- package/dist/client/FieldNameSelect.js.map +1 -1
- package/dist/client/FlowBuilder.js +31 -23
- package/dist/client/FlowBuilder.js.map +1 -1
- package/dist/client/FormConditionField.js +0 -1
- package/dist/client/FormConditionField.js.map +1 -1
- package/dist/client/RecipientsSelect.d.ts +9 -2
- package/dist/client/RecipientsSelect.js +31 -10
- package/dist/client/RecipientsSelect.js.map +1 -1
- package/dist/client/admin.css +345 -72
- package/dist/client/endpointOptions.d.ts +11 -0
- package/dist/client/endpointOptions.js +17 -8
- package/dist/client/endpointOptions.js.map +1 -1
- package/dist/collections/formSubmissions.js +145 -51
- package/dist/collections/formSubmissions.js.map +1 -1
- package/dist/collections/forms.js +170 -65
- package/dist/collections/forms.js.map +1 -1
- package/dist/collections/formsEndpoints.js +31 -26
- package/dist/collections/formsEndpoints.js.map +1 -1
- package/dist/collections/settingsFields.d.ts +32 -0
- package/dist/collections/settingsFields.js +55 -0
- package/dist/collections/settingsFields.js.map +1 -0
- package/dist/consent/captureConsent.d.ts +2 -1
- package/dist/consent/captureConsent.js +4 -1
- package/dist/consent/captureConsent.js.map +1 -1
- package/dist/consent/consentSourcesField.d.ts +7 -1
- package/dist/consent/consentSourcesField.js +15 -1
- package/dist/consent/consentSourcesField.js.map +1 -1
- package/dist/consent/effectiveStatement.js +16 -0
- package/dist/consent/effectiveStatement.js.map +1 -0
- package/dist/consent/resolveConsentSourcesRequest.js +2 -2
- package/dist/consent/resolveConsentSourcesRequest.js.map +1 -1
- package/dist/consent/resolveConsentStatements.js +3 -1
- package/dist/consent/resolveConsentStatements.js.map +1 -1
- package/dist/consent/resolvePublishedVersionRef.js +1 -0
- package/dist/consent/resolvePublishedVersionRef.js.map +1 -1
- package/dist/consent/types.d.ts +8 -0
- package/dist/context/formContext.d.ts +30 -0
- package/dist/context/formContext.js +54 -0
- package/dist/context/formContext.js.map +1 -0
- package/dist/email/departmentsField.d.ts +6 -1
- package/dist/email/departmentsField.js +6 -1
- package/dist/email/departmentsField.js.map +1 -1
- package/dist/exports/client.d.ts +3 -1
- package/dist/exports/client.js +3 -1
- package/dist/exports/i18n.d.ts +14 -2
- package/dist/exports/i18n.js +14 -2
- package/dist/exports/react.d.ts +23 -5
- package/dist/exports/react.js +17 -1
- package/dist/exports/rsc.d.ts +4 -1
- package/dist/exports/rsc.js +7 -4
- package/dist/exports/types.d.ts +4 -3
- package/dist/fields/buildFieldBlocks.js +2 -1
- package/dist/fields/buildFieldBlocks.js.map +1 -1
- package/dist/fields/builtin/calculation.d.ts +17 -0
- package/dist/fields/builtin/calculation.js +70 -127
- package/dist/fields/builtin/calculation.js.map +1 -1
- package/dist/fields/builtin/checkbox.js +15 -0
- package/dist/fields/builtin/checkbox.js.map +1 -1
- package/dist/fields/builtin/consent.js +21 -1
- package/dist/fields/builtin/consent.js.map +1 -1
- package/dist/fields/builtin/email.js +7 -0
- package/dist/fields/builtin/email.js.map +1 -1
- package/dist/fields/builtin/index.d.ts +6 -2
- package/dist/fields/builtin/index.js +9 -4
- package/dist/fields/builtin/index.js.map +1 -1
- package/dist/fields/builtin/select.js +20 -1
- package/dist/fields/builtin/select.js.map +1 -1
- package/dist/fields/builtin/text.js +7 -0
- package/dist/fields/builtin/text.js.map +1 -1
- package/dist/fields/instanceOptions.js +1 -1
- package/dist/fields/instanceOptions.js.map +1 -1
- package/dist/fields/sharedConfig.js +15 -11
- package/dist/fields/sharedConfig.js.map +1 -1
- package/dist/fields/types.d.ts +8 -2
- package/dist/form/findFormAtLocale.d.ts +30 -0
- package/dist/form/findFormAtLocale.js +88 -0
- package/dist/form/findFormAtLocale.js.map +1 -0
- package/dist/form/pollState.d.ts +2 -1
- package/dist/form/pollState.js.map +1 -1
- package/dist/form/toFormDocument.d.ts +8 -0
- package/dist/form/toFormDocument.js +3 -1
- package/dist/form/toFormDocument.js.map +1 -1
- package/dist/form/types.d.ts +9 -1
- package/dist/index.d.ts +22 -6
- package/dist/index.js +63 -17
- package/dist/index.js.map +1 -1
- package/dist/options.d.ts +113 -4
- package/dist/plugin/collectionSlugs.d.ts +28 -0
- package/dist/plugin/collectionSlugs.js +65 -0
- package/dist/plugin/collectionSlugs.js.map +1 -0
- package/dist/plugin/customState.js +1 -1
- package/dist/plugin/customState.js.map +1 -1
- package/dist/plugin/registerCollections.js +38 -21
- package/dist/plugin/registerCollections.js.map +1 -1
- package/dist/poll/closeJob.d.ts +4 -3
- package/dist/poll/closeJob.js +13 -10
- package/dist/poll/closeJob.js.map +1 -1
- package/dist/poll/outcomeBeforeChange.js +2 -2
- package/dist/poll/outcomeBeforeChange.js.map +1 -1
- package/dist/poll/pollTypeRegistry.js +1 -1
- package/dist/poll/resolvePollCloseRequest.js +5 -4
- package/dist/poll/resolvePollCloseRequest.js.map +1 -1
- package/dist/poll/resolvePollOptionsRequest.js +2 -2
- package/dist/poll/resolvePollOptionsRequest.js.map +1 -1
- package/dist/poll/resolvePollOutcome.d.ts +6 -0
- package/dist/poll/resolvePollOutcome.js +20 -6
- package/dist/poll/resolvePollOutcome.js.map +1 -1
- package/dist/poll/votes/aggregateFromVotes.d.ts +27 -0
- package/dist/poll/votes/aggregateFromVotes.js +55 -0
- package/dist/poll/votes/aggregateFromVotes.js.map +1 -0
- package/dist/poll/votes/answerValues.js +16 -0
- package/dist/poll/votes/answerValues.js.map +1 -0
- package/dist/poll/votes/bumpPollVote.js +91 -0
- package/dist/poll/votes/bumpPollVote.js.map +1 -0
- package/dist/poll/votes/recountPollVotes.d.ts +20 -0
- package/dist/poll/votes/recountPollVotes.js +63 -0
- package/dist/poll/votes/recountPollVotes.js.map +1 -0
- package/dist/poll/votes/voteTallyHook.js +76 -0
- package/dist/poll/votes/voteTallyHook.js.map +1 -0
- package/dist/poll/votes/votesCollection.d.ts +23 -0
- package/dist/poll/votes/votesCollection.js +96 -0
- package/dist/poll/votes/votesCollection.js.map +1 -0
- package/dist/react/Form.d.ts +49 -7
- package/dist/react/Form.js +48 -13
- package/dist/react/Form.js.map +1 -1
- package/dist/react/FormContext.d.ts +8 -1
- package/dist/react/FormContext.js.map +1 -1
- package/dist/react/FormResults.d.ts +4 -2
- package/dist/react/FormResults.js +21 -8
- package/dist/react/FormResults.js.map +1 -1
- package/dist/react/Poll.d.ts +25 -2
- package/dist/react/Poll.js +76 -25
- package/dist/react/Poll.js.map +1 -1
- package/dist/react/adapters.d.ts +35 -0
- package/dist/react/adapters.js +11 -0
- package/dist/react/adapters.js.map +1 -0
- package/dist/react/captcha/HcaptchaCaptcha.d.ts +4 -1
- package/dist/react/captcha/HcaptchaCaptcha.js +2 -2
- package/dist/react/captcha/HcaptchaCaptcha.js.map +1 -1
- package/dist/react/captcha/RecaptchaCaptcha.d.ts +4 -1
- package/dist/react/captcha/RecaptchaCaptcha.js +2 -2
- package/dist/react/captcha/RecaptchaCaptcha.js.map +1 -1
- package/dist/react/captcha/TurnstileCaptcha.d.ts +4 -1
- package/dist/react/captcha/TurnstileCaptcha.js +2 -2
- package/dist/react/captcha/TurnstileCaptcha.js.map +1 -1
- package/dist/react/captcha/useCaptchaScript.js +23 -5
- package/dist/react/captcha/useCaptchaScript.js.map +1 -1
- package/dist/react/fetchResults.d.ts +6 -3
- package/dist/react/fetchResults.js +10 -5
- package/dist/react/fetchResults.js.map +1 -1
- package/dist/react/primitives/Checkbox.d.ts +4 -2
- package/dist/react/primitives/Checkbox.js +3 -2
- package/dist/react/primitives/Checkbox.js.map +1 -1
- package/dist/react/primitives/ChoiceGroup.d.ts +40 -0
- package/dist/react/primitives/ChoiceGroup.js +33 -0
- package/dist/react/primitives/ChoiceGroup.js.map +1 -0
- package/dist/react/primitives/FieldShell.d.ts +11 -1
- package/dist/react/primitives/FieldShell.js +43 -33
- package/dist/react/primitives/FieldShell.js.map +1 -1
- package/dist/react/primitives/Input.d.ts +3 -1
- package/dist/react/primitives/Input.js +2 -1
- package/dist/react/primitives/Input.js.map +1 -1
- package/dist/react/renderers/calculation.js +6 -1
- package/dist/react/renderers/calculation.js.map +1 -1
- package/dist/react/renderers/checkbox.js +2 -1
- package/dist/react/renderers/checkbox.js.map +1 -1
- package/dist/react/renderers/consent.js +8 -3
- package/dist/react/renderers/consent.js.map +1 -1
- package/dist/react/renderers/email.js +3 -1
- package/dist/react/renderers/email.js.map +1 -1
- package/dist/react/renderers/repeater.js +5 -0
- package/dist/react/renderers/repeater.js.map +1 -1
- package/dist/react/renderers/select.js +20 -2
- package/dist/react/renderers/select.js.map +1 -1
- package/dist/react/renderers/text.js +3 -1
- package/dist/react/renderers/text.js.map +1 -1
- package/dist/react/state.d.ts +10 -0
- package/dist/react/state.js +45 -1
- package/dist/react/state.js.map +1 -1
- package/dist/react/submitForm.d.ts +20 -3
- package/dist/react/submitForm.js +8 -4
- package/dist/react/submitForm.js.map +1 -1
- package/dist/react/useCalcValues.d.ts +10 -0
- package/dist/react/useCalcValues.js +13 -0
- package/dist/react/useCalcValues.js.map +1 -0
- package/dist/react/useField.js +2 -1
- package/dist/react/useField.js.map +1 -1
- package/dist/recall/resolver.js +1 -1
- package/dist/recall/resolver.js.map +1 -1
- package/dist/spam/constants.js +7 -1
- package/dist/spam/constants.js.map +1 -1
- package/dist/spam/spamGuard.js +2 -1
- package/dist/spam/spamGuard.js.map +1 -1
- package/dist/submissions/SubmissionAnswersClient.js +14 -14
- package/dist/submissions/SubmissionAnswersClient.js.map +1 -1
- package/dist/submissions/createSubmission.d.ts +7 -1
- package/dist/submissions/createSubmission.js +10 -5
- package/dist/submissions/createSubmission.js.map +1 -1
- package/dist/submissions/formIdOf.js +13 -0
- package/dist/submissions/formIdOf.js.map +1 -0
- package/dist/submissions/resolveVotedSubmission.d.ts +27 -0
- package/dist/submissions/resolveVotedSubmission.js +51 -0
- package/dist/submissions/resolveVotedSubmission.js.map +1 -0
- package/dist/submissions/runSubmission.js +6 -5
- package/dist/submissions/runSubmission.js.map +1 -1
- package/dist/submissions/submissionLocale.js +39 -0
- package/dist/submissions/submissionLocale.js.map +1 -0
- package/dist/submissions/validateSubmission.js +125 -79
- package/dist/submissions/validateSubmission.js.map +1 -1
- package/dist/submissions/verifyContext.js +35 -0
- package/dist/submissions/verifyContext.js.map +1 -0
- package/dist/submissions/voteChange.js +21 -0
- package/dist/submissions/voteChange.js.map +1 -0
- package/dist/submissions/voteChangeEndpoint.js +110 -0
- package/dist/submissions/voteChangeEndpoint.js.map +1 -0
- package/dist/submissions/votedCookie.d.ts +10 -4
- package/dist/submissions/votedCookie.js +49 -11
- package/dist/submissions/votedCookie.js.map +1 -1
- package/dist/translations/ar.d.ts +7 -0
- package/dist/translations/ar.js +379 -0
- package/dist/translations/ar.js.map +1 -0
- package/dist/translations/clientRuntimeKeys.d.ts +17 -0
- package/dist/translations/clientRuntimeKeys.js +48 -0
- package/dist/translations/clientRuntimeKeys.js.map +1 -0
- package/dist/translations/de.d.ts +12 -0
- package/dist/translations/de.js +78 -3
- package/dist/translations/de.js.map +1 -1
- package/dist/translations/en.js +78 -3
- package/dist/translations/en.js.map +1 -1
- package/dist/translations/es.d.ts +7 -0
- package/dist/translations/es.js +379 -0
- package/dist/translations/es.js.map +1 -0
- package/dist/translations/fr.d.ts +7 -0
- package/dist/translations/fr.js +379 -0
- package/dist/translations/fr.js.map +1 -0
- package/dist/translations/id.d.ts +7 -0
- package/dist/translations/id.js +379 -0
- package/dist/translations/id.js.map +1 -0
- package/dist/translations/index.d.ts +23 -6
- package/dist/translations/index.js +31 -6
- package/dist/translations/index.js.map +1 -1
- package/dist/translations/keys.d.ts +76 -1
- package/dist/translations/keys.js +76 -1
- package/dist/translations/keys.js.map +1 -1
- package/dist/translations/ko.d.ts +7 -0
- package/dist/translations/ko.js +379 -0
- package/dist/translations/ko.js.map +1 -0
- package/dist/translations/makeTranslate.d.ts +7 -3
- package/dist/translations/makeTranslate.js +12 -3
- package/dist/translations/makeTranslate.js.map +1 -1
- package/dist/translations/pt.d.ts +7 -0
- package/dist/translations/pt.js +379 -0
- package/dist/translations/pt.js.map +1 -0
- package/dist/translations/ru.d.ts +7 -0
- package/dist/translations/ru.js +379 -0
- package/dist/translations/ru.js.map +1 -0
- package/dist/translations/uk.d.ts +7 -0
- package/dist/translations/uk.js +379 -0
- package/dist/translations/uk.js.map +1 -0
- package/dist/translations/zh.d.ts +7 -0
- package/dist/translations/zh.js +379 -0
- package/dist/translations/zh.js.map +1 -0
- package/dist/validation/builtin/index.js +2 -0
- package/dist/validation/builtin/index.js.map +1 -1
- package/dist/validation/builtin/integer.js +15 -0
- package/dist/validation/builtin/integer.js.map +1 -0
- package/dist/validation/builtin/notAlreadySubmitted.js +5 -3
- package/dist/validation/builtin/notAlreadySubmitted.js.map +1 -1
- package/package.json +24 -16
- package/styles/form-builder.css +84 -0
|
@@ -12,7 +12,17 @@ import { resolvePollOptionsRequest } from "../poll/resolvePollOptionsRequest.js"
|
|
|
12
12
|
* (anonymous callers get a 403 from the helper, not here). Extracted from `buildFormsCollection`
|
|
13
13
|
* so the collection builder stays focused on field and hook composition.
|
|
14
14
|
*/
|
|
15
|
-
|
|
15
|
+
/** A request-scoped GET route at its id-less path plus the legacy doc-scoped path, one handler. */
|
|
16
|
+
const requestScopedRoutes = (name, handler) => [{
|
|
17
|
+
path: `/${name}`,
|
|
18
|
+
method: "get",
|
|
19
|
+
handler
|
|
20
|
+
}, {
|
|
21
|
+
path: `/:id/${name}`,
|
|
22
|
+
method: "get",
|
|
23
|
+
handler
|
|
24
|
+
}];
|
|
25
|
+
const buildFormsEndpoints = ({ resultsAccess, pollResultsTypes, pollVotesEnabled, consentSources, fromAddresses, fromSources, departments }) => [
|
|
16
26
|
{
|
|
17
27
|
path: "/:id/results",
|
|
18
28
|
method: "get",
|
|
@@ -25,7 +35,8 @@ const buildFormsEndpoints = ({ resultsAccess, pollResultsTypes, consentSources,
|
|
|
25
35
|
isAuthed: Boolean(req.user),
|
|
26
36
|
req,
|
|
27
37
|
access: resultsAccess,
|
|
28
|
-
eligibleTypes: pollResultsTypes
|
|
38
|
+
eligibleTypes: pollResultsTypes,
|
|
39
|
+
pollVotesEnabled
|
|
29
40
|
});
|
|
30
41
|
return Response.json(body, { status });
|
|
31
42
|
}
|
|
@@ -51,6 +62,7 @@ const buildFormsEndpoints = ({ resultsAccess, pollResultsTypes, consentSources,
|
|
|
51
62
|
payload: req.payload,
|
|
52
63
|
formId: req.routeParams?.id,
|
|
53
64
|
isAuthed: Boolean(req.user),
|
|
65
|
+
pollVotesEnabled,
|
|
54
66
|
req
|
|
55
67
|
});
|
|
56
68
|
return Response.json(body, { status });
|
|
@@ -70,30 +82,23 @@ const buildFormsEndpoints = ({ resultsAccess, pollResultsTypes, consentSources,
|
|
|
70
82
|
return Response.json(body, { status });
|
|
71
83
|
}
|
|
72
84
|
}] : [],
|
|
73
|
-
...fromAddresses ?
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
}
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
isAuthed: Boolean(req.user),
|
|
91
|
-
req,
|
|
92
|
-
resolver: departments
|
|
93
|
-
});
|
|
94
|
-
return Response.json(body, { status });
|
|
95
|
-
}
|
|
96
|
-
}] : []
|
|
85
|
+
...fromAddresses || fromSources ? requestScopedRoutes("from-addresses", async (req) => {
|
|
86
|
+
const { status, body } = await resolveFromAddressesRequest({
|
|
87
|
+
isAuthed: Boolean(req.user),
|
|
88
|
+
req,
|
|
89
|
+
resolver: fromAddresses,
|
|
90
|
+
sources: fromSources
|
|
91
|
+
});
|
|
92
|
+
return Response.json(body, { status });
|
|
93
|
+
}) : [],
|
|
94
|
+
...departments ? requestScopedRoutes("departments", async (req) => {
|
|
95
|
+
const { status, body } = await resolveDepartmentsRequest({
|
|
96
|
+
isAuthed: Boolean(req.user),
|
|
97
|
+
req,
|
|
98
|
+
resolver: departments
|
|
99
|
+
});
|
|
100
|
+
return Response.json(body, { status });
|
|
101
|
+
}) : []
|
|
97
102
|
];
|
|
98
103
|
//#endregion
|
|
99
104
|
export { buildFormsEndpoints };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"formsEndpoints.js","names":[],"sources":["../../src/collections/formsEndpoints.ts"],"sourcesContent":["import type { CollectionConfig, PayloadRequest } from 'payload'\nimport {
|
|
1
|
+
{"version":3,"file":"formsEndpoints.js","names":[],"sources":["../../src/collections/formsEndpoints.ts"],"sourcesContent":["import type { CollectionConfig, PayloadRequest } from 'payload'\nimport {\n\ttype FromAddressesResolver,\n\ttype FromAddressSourceRegistry,\n\tresolveFromAddressesRequest,\n} from '../actions/fromAddresses'\nimport {\n\ttype FormResultsAccess,\n\tresolveFormResultsRequest,\n} from '../aggregation/resolveResultsRequest'\nimport { resolveConsentSourcesRequest } from '../consent/resolveConsentSourcesRequest'\nimport type { ConsentSourcesResolver } from '../consent/types'\nimport { type DepartmentEmailsResolver, resolveDepartmentsRequest } from '../email/departments'\nimport { resolvePollCloseRequest } from '../poll/resolvePollCloseRequest'\nimport { resolvePollOptionsRequest } from '../poll/resolvePollOptionsRequest'\n\ntype FormsEndpointDeps = {\n\t/** Host seam gating anonymous results reads (plugin option `results.access`). */\n\tresultsAccess?: FormResultsAccess\n\t/** The poll-eligible field-type names; the `/:id/results` endpoint restricts reads to these. */\n\tpollResultsTypes: string[]\n\t/** Whether the hidden tally store backs poll reads and the close endpoint's outcome aggregation. */\n\tpollVotesEnabled: boolean\n\t/** The plugin `consent.sources` option; present registers the `/:id/consent-sources` endpoint. */\n\tconsentSources?: ConsentSourcesResolver\n\t/** The plugin `email.fromAddresses` option; this or `fromSources` present registers the `/:id/from-addresses` endpoint. */\n\tfromAddresses?: FromAddressesResolver\n\t/** The plugin `email.fromSources` option; served ahead of the resolver's literals. */\n\tfromSources?: FromAddressSourceRegistry\n\t/** The plugin `email.departments` option; present registers the `/:id/departments` endpoint. */\n\tdepartments?: DepartmentEmailsResolver\n}\n\n/**\n * The forms collection's built-in endpoints: poll results/options/close, plus the optional\n * consent-sources, from-addresses, and departments option endpoints that only exist when the\n * matching plugin option is set. Each delegates to its request helper, which owns the auth check\n * (anonymous callers get a 403 from the helper, not here). Extracted from `buildFormsCollection`\n * so the collection builder stays focused on field and hook composition.\n */\n/** A request-scoped GET route at its id-less path plus the legacy doc-scoped path, one handler. */\nconst requestScopedRoutes = (\n\tname: string,\n\thandler: (req: PayloadRequest) => Promise<Response>\n): Exclude<CollectionConfig['endpoints'], false | undefined> => [\n\t{ path: `/${name}`, method: 'get', handler },\n\t{ path: `/:id/${name}`, method: 'get', handler },\n]\n\nexport const buildFormsEndpoints = ({\n\tresultsAccess,\n\tpollResultsTypes,\n\tpollVotesEnabled,\n\tconsentSources,\n\tfromAddresses,\n\tfromSources,\n\tdepartments,\n}: FormsEndpointDeps): Exclude<CollectionConfig['endpoints'], false | undefined> => [\n\t{\n\t\tpath: '/:id/results',\n\t\tmethod: 'get',\n\t\thandler: async (req: PayloadRequest) => {\n\t\t\tconst field = typeof req.query?.field === 'string' ? req.query.field : undefined\n\t\t\tconst { status, body } = await resolveFormResultsRequest({\n\t\t\t\tpayload: req.payload,\n\t\t\t\tformId: req.routeParams?.id as number | string | undefined,\n\t\t\t\tfield,\n\t\t\t\tisAuthed: Boolean(req.user),\n\t\t\t\treq,\n\t\t\t\taccess: resultsAccess,\n\t\t\t\teligibleTypes: pollResultsTypes,\n\t\t\t\tpollVotesEnabled,\n\t\t\t})\n\t\t\treturn Response.json(body, { status })\n\t\t},\n\t},\n\t{\n\t\tpath: '/:id/poll-options',\n\t\tmethod: 'get',\n\t\thandler: async (req: PayloadRequest) => {\n\t\t\tconst { status, body } = await resolvePollOptionsRequest({\n\t\t\t\tpayload: req.payload,\n\t\t\t\tformId: req.routeParams?.id as number | string | undefined,\n\t\t\t\tisAuthed: Boolean(req.user),\n\t\t\t\treq,\n\t\t\t})\n\t\t\treturn Response.json(body, { status })\n\t\t},\n\t},\n\t// Trusted admin action (authenticated only): close a poll now and resolve its outcome. A POST\n\t// because it mutates; auth is `Boolean(req.user)` so an anonymous caller gets 403 from the helper.\n\t{\n\t\tpath: '/:id/close',\n\t\tmethod: 'post',\n\t\thandler: async (req: PayloadRequest) => {\n\t\t\tconst { status, body } = await resolvePollCloseRequest({\n\t\t\t\tpayload: req.payload,\n\t\t\t\tformId: req.routeParams?.id as number | string | undefined,\n\t\t\t\tisAuthed: Boolean(req.user),\n\t\t\t\tpollVotesEnabled,\n\t\t\t\treq,\n\t\t\t})\n\t\t\treturn Response.json(body, { status })\n\t\t},\n\t},\n\t...(consentSources\n\t\t? [\n\t\t\t\t{\n\t\t\t\t\tpath: '/:id/consent-sources',\n\t\t\t\t\tmethod: 'get' as const,\n\t\t\t\t\thandler: async (req: PayloadRequest) => {\n\t\t\t\t\t\tconst { status, body } = await resolveConsentSourcesRequest({\n\t\t\t\t\t\t\tpayload: req.payload,\n\t\t\t\t\t\t\tformId: req.routeParams?.id as number | string | undefined,\n\t\t\t\t\t\t\tisAuthed: Boolean(req.user),\n\t\t\t\t\t\t\treq,\n\t\t\t\t\t\t\tresolver: consentSources,\n\t\t\t\t\t\t})\n\t\t\t\t\t\treturn Response.json(body, { status })\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t]\n\t\t: []),\n\t// The from-addresses and departments sets are request-scoped (e.g. per tenant), never per-form.\n\t// Each lives at the id-less path the selects call (which is what lets their options load while\n\t// a form is still being created), with the legacy `/:id/` route kept on the same handler for\n\t// integrators that hardcoded it.\n\t...(fromAddresses || fromSources\n\t\t? requestScopedRoutes('from-addresses', async (req: PayloadRequest) => {\n\t\t\t\tconst { status, body } = await resolveFromAddressesRequest({\n\t\t\t\t\tisAuthed: Boolean(req.user),\n\t\t\t\t\treq,\n\t\t\t\t\tresolver: fromAddresses,\n\t\t\t\t\tsources: fromSources,\n\t\t\t\t})\n\t\t\t\treturn Response.json(body, { status })\n\t\t\t})\n\t\t: []),\n\t...(departments\n\t\t? requestScopedRoutes('departments', async (req: PayloadRequest) => {\n\t\t\t\tconst { status, body } = await resolveDepartmentsRequest({\n\t\t\t\t\tisAuthed: Boolean(req.user),\n\t\t\t\t\treq,\n\t\t\t\t\tresolver: departments,\n\t\t\t\t})\n\t\t\t\treturn Response.json(body, { status })\n\t\t\t})\n\t\t: []),\n]\n"],"mappings":";;;;;;;;;;;;;;;AAyCA,MAAM,uBACL,MACA,YAC+D,CAC/D;CAAE,MAAM,IAAI;CAAQ,QAAQ;CAAO;AAAQ,GAC3C;CAAE,MAAM,QAAQ;CAAQ,QAAQ;CAAO;AAAQ,CAChD;AAEA,MAAa,uBAAuB,EACnC,eACA,kBACA,kBACA,gBACA,eACA,aACA,kBACmF;CACnF;EACC,MAAM;EACN,QAAQ;EACR,SAAS,OAAO,QAAwB;GACvC,MAAM,QAAQ,OAAO,IAAI,OAAO,UAAU,WAAW,IAAI,MAAM,QAAQ,KAAA;GACvE,MAAM,EAAE,QAAQ,SAAS,MAAM,0BAA0B;IACxD,SAAS,IAAI;IACb,QAAQ,IAAI,aAAa;IACzB;IACA,UAAU,QAAQ,IAAI,IAAI;IAC1B;IACA,QAAQ;IACR,eAAe;IACf;GACD,CAAC;GACD,OAAO,SAAS,KAAK,MAAM,EAAE,OAAO,CAAC;EACtC;CACD;CACA;EACC,MAAM;EACN,QAAQ;EACR,SAAS,OAAO,QAAwB;GACvC,MAAM,EAAE,QAAQ,SAAS,MAAM,0BAA0B;IACxD,SAAS,IAAI;IACb,QAAQ,IAAI,aAAa;IACzB,UAAU,QAAQ,IAAI,IAAI;IAC1B;GACD,CAAC;GACD,OAAO,SAAS,KAAK,MAAM,EAAE,OAAO,CAAC;EACtC;CACD;CAGA;EACC,MAAM;EACN,QAAQ;EACR,SAAS,OAAO,QAAwB;GACvC,MAAM,EAAE,QAAQ,SAAS,MAAM,wBAAwB;IACtD,SAAS,IAAI;IACb,QAAQ,IAAI,aAAa;IACzB,UAAU,QAAQ,IAAI,IAAI;IAC1B;IACA;GACD,CAAC;GACD,OAAO,SAAS,KAAK,MAAM,EAAE,OAAO,CAAC;EACtC;CACD;CACA,GAAI,iBACD,CACA;EACC,MAAM;EACN,QAAQ;EACR,SAAS,OAAO,QAAwB;GACvC,MAAM,EAAE,QAAQ,SAAS,MAAM,6BAA6B;IAC3D,SAAS,IAAI;IACb,QAAQ,IAAI,aAAa;IACzB,UAAU,QAAQ,IAAI,IAAI;IAC1B;IACA,UAAU;GACX,CAAC;GACD,OAAO,SAAS,KAAK,MAAM,EAAE,OAAO,CAAC;EACtC;CACD,CACD,IACC,CAAC;CAKJ,GAAI,iBAAiB,cAClB,oBAAoB,kBAAkB,OAAO,QAAwB;EACrE,MAAM,EAAE,QAAQ,SAAS,MAAM,4BAA4B;GAC1D,UAAU,QAAQ,IAAI,IAAI;GAC1B;GACA,UAAU;GACV,SAAS;EACV,CAAC;EACD,OAAO,SAAS,KAAK,MAAM,EAAE,OAAO,CAAC;CACtC,CAAC,IACA,CAAC;CACJ,GAAI,cACD,oBAAoB,eAAe,OAAO,QAAwB;EAClE,MAAM,EAAE,QAAQ,SAAS,MAAM,0BAA0B;GACxD,UAAU,QAAQ,IAAI,IAAI;GAC1B;GACA,UAAU;EACX,CAAC;EACD,OAAO,SAAS,KAAK,MAAM,EAAE,OAAO,CAAC;CACtC,CAAC,IACA,CAAC;AACL"}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { Field } from "payload";
|
|
2
|
+
|
|
3
|
+
//#region src/collections/settingsFields.d.ts
|
|
4
|
+
/** The default form-level flag fields, keyed by flag. What the `settings.fields` seam receives. */
|
|
5
|
+
type DefaultSettingsFields = {
|
|
6
|
+
multistep: Field;
|
|
7
|
+
pollEnabled: Field;
|
|
8
|
+
persistSubmissions: Field; /** Sidebar notice shown when a non-persisting form carries a consent field: proofs are pruned with the row. */
|
|
9
|
+
consentRetentionNotice: Field;
|
|
10
|
+
};
|
|
11
|
+
/**
|
|
12
|
+
* Composes the three form-level flag fields. Receives the defaults and returns the final field
|
|
13
|
+
* array placed verbatim at the forms collection root, so a host can relocate a flag (strip
|
|
14
|
+
* `admin.position`), wrap them in a row, append its own, or drop one.
|
|
15
|
+
*/
|
|
16
|
+
type SettingsFieldsOverride = (args: {
|
|
17
|
+
defaultFields: DefaultSettingsFields;
|
|
18
|
+
}) => Field[];
|
|
19
|
+
/** The plugin `settings` option: the three form-level flags and their composition seam. */
|
|
20
|
+
type SettingsOption = {
|
|
21
|
+
fields?: SettingsFieldsOverride;
|
|
22
|
+
};
|
|
23
|
+
/**
|
|
24
|
+
* The three flags: behavior, never localized, sidebar checkboxes by default. `multistep` gates the
|
|
25
|
+
* Flow tab and the client's step navigation; `pollEnabled` gates the Poll tab and marks the form a
|
|
26
|
+
* poll; `persistSubmissions` (default checked) tells the plugin whether to keep a submission's row
|
|
27
|
+
* after its actions run, or prune it (a pure signup form's opt-out).
|
|
28
|
+
*/
|
|
29
|
+
declare const buildDefaultSettingsFields: () => DefaultSettingsFields;
|
|
30
|
+
//#endregion
|
|
31
|
+
export { DefaultSettingsFields, SettingsFieldsOverride, SettingsOption, buildDefaultSettingsFields };
|
|
32
|
+
//# sourceMappingURL=settingsFields.d.ts.map
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import { keys } from "../translations/keys.js";
|
|
2
|
+
import { labelForKey } from "../translations/server.js";
|
|
3
|
+
//#region src/collections/settingsFields.ts
|
|
4
|
+
/**
|
|
5
|
+
* The three flags: behavior, never localized, sidebar checkboxes by default. `multistep` gates the
|
|
6
|
+
* Flow tab and the client's step navigation; `pollEnabled` gates the Poll tab and marks the form a
|
|
7
|
+
* poll; `persistSubmissions` (default checked) tells the plugin whether to keep a submission's row
|
|
8
|
+
* after its actions run, or prune it (a pure signup form's opt-out).
|
|
9
|
+
*/
|
|
10
|
+
const buildDefaultSettingsFields = () => ({
|
|
11
|
+
multistep: {
|
|
12
|
+
name: "multistep",
|
|
13
|
+
type: "checkbox",
|
|
14
|
+
defaultValue: false,
|
|
15
|
+
label: labelForKey(keys.formMultistep),
|
|
16
|
+
admin: { position: "sidebar" }
|
|
17
|
+
},
|
|
18
|
+
pollEnabled: {
|
|
19
|
+
name: "pollEnabled",
|
|
20
|
+
type: "checkbox",
|
|
21
|
+
defaultValue: false,
|
|
22
|
+
label: labelForKey(keys.formPollEnabled),
|
|
23
|
+
admin: { position: "sidebar" }
|
|
24
|
+
},
|
|
25
|
+
persistSubmissions: {
|
|
26
|
+
name: "persistSubmissions",
|
|
27
|
+
type: "checkbox",
|
|
28
|
+
defaultValue: true,
|
|
29
|
+
label: labelForKey(keys.formPersistSubmissions),
|
|
30
|
+
admin: { position: "sidebar" }
|
|
31
|
+
},
|
|
32
|
+
consentRetentionNotice: {
|
|
33
|
+
name: "consentRetentionNotice",
|
|
34
|
+
type: "ui",
|
|
35
|
+
admin: {
|
|
36
|
+
position: "sidebar",
|
|
37
|
+
condition: (data) => data?.persistSubmissions === false && Array.isArray(data?.fields) && (data.fields ?? []).some((field) => field?.blockType === "consent"),
|
|
38
|
+
components: { Field: "@10x-media/form-builder/client#ConsentRetentionNotice" }
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
});
|
|
42
|
+
const composeSettingsFields = (settings) => {
|
|
43
|
+
const defaultFields = buildDefaultSettingsFields();
|
|
44
|
+
if (settings?.fields) return settings.fields({ defaultFields });
|
|
45
|
+
return [
|
|
46
|
+
defaultFields.multistep,
|
|
47
|
+
defaultFields.pollEnabled,
|
|
48
|
+
defaultFields.persistSubmissions,
|
|
49
|
+
defaultFields.consentRetentionNotice
|
|
50
|
+
];
|
|
51
|
+
};
|
|
52
|
+
//#endregion
|
|
53
|
+
export { buildDefaultSettingsFields, composeSettingsFields };
|
|
54
|
+
|
|
55
|
+
//# sourceMappingURL=settingsFields.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"settingsFields.js","names":[],"sources":["../../src/collections/settingsFields.ts"],"sourcesContent":["import type { Field } from 'payload'\nimport { keys } from '../translations/keys'\nimport { labelForKey } from '../translations/server'\n\n/** The default form-level flag fields, keyed by flag. What the `settings.fields` seam receives. */\nexport type DefaultSettingsFields = {\n\tmultistep: Field\n\tpollEnabled: Field\n\tpersistSubmissions: Field\n\t/** Sidebar notice shown when a non-persisting form carries a consent field: proofs are pruned with the row. */\n\tconsentRetentionNotice: Field\n}\n\n/**\n * Composes the three form-level flag fields. Receives the defaults and returns the final field\n * array placed verbatim at the forms collection root, so a host can relocate a flag (strip\n * `admin.position`), wrap them in a row, append its own, or drop one.\n */\nexport type SettingsFieldsOverride = (args: { defaultFields: DefaultSettingsFields }) => Field[]\n\n/** The plugin `settings` option: the three form-level flags and their composition seam. */\nexport type SettingsOption = {\n\tfields?: SettingsFieldsOverride\n}\n\n/**\n * The three flags: behavior, never localized, sidebar checkboxes by default. `multistep` gates the\n * Flow tab and the client's step navigation; `pollEnabled` gates the Poll tab and marks the form a\n * poll; `persistSubmissions` (default checked) tells the plugin whether to keep a submission's row\n * after its actions run, or prune it (a pure signup form's opt-out).\n */\nexport const buildDefaultSettingsFields = (): DefaultSettingsFields => ({\n\tmultistep: {\n\t\tname: 'multistep',\n\t\ttype: 'checkbox',\n\t\tdefaultValue: false,\n\t\tlabel: labelForKey(keys.formMultistep),\n\t\tadmin: { position: 'sidebar' },\n\t},\n\tpollEnabled: {\n\t\tname: 'pollEnabled',\n\t\ttype: 'checkbox',\n\t\tdefaultValue: false,\n\t\tlabel: labelForKey(keys.formPollEnabled),\n\t\tadmin: { position: 'sidebar' },\n\t},\n\tpersistSubmissions: {\n\t\tname: 'persistSubmissions',\n\t\ttype: 'checkbox',\n\t\tdefaultValue: true,\n\t\tlabel: labelForKey(keys.formPersistSubmissions),\n\t\tadmin: { position: 'sidebar' },\n\t},\n\t// A visible contradiction notice, not a refusal: a consent field on a non-persisting form is\n\t// legitimate when the consent record lives elsewhere (a double opt-in provider), but the proof\n\t// is pruned with the row, and that must never be silent.\n\tconsentRetentionNotice: {\n\t\tname: 'consentRetentionNotice',\n\t\ttype: 'ui',\n\t\tadmin: {\n\t\t\tposition: 'sidebar',\n\t\t\tcondition: (data) =>\n\t\t\t\t(data as { persistSubmissions?: unknown })?.persistSubmissions === false &&\n\t\t\t\tArray.isArray((data as { fields?: unknown })?.fields) &&\n\t\t\t\t((data as { fields: { blockType?: unknown }[] }).fields ?? []).some(\n\t\t\t\t\t(field) => field?.blockType === 'consent'\n\t\t\t\t),\n\t\t\tcomponents: { Field: '@10x-media/form-builder/client#ConsentRetentionNotice' },\n\t\t},\n\t},\n})\n\nexport const composeSettingsFields = (settings: SettingsOption | undefined): Field[] => {\n\tconst defaultFields = buildDefaultSettingsFields()\n\tif (settings?.fields) {\n\t\treturn settings.fields({ defaultFields })\n\t}\n\treturn [\n\t\tdefaultFields.multistep,\n\t\tdefaultFields.pollEnabled,\n\t\tdefaultFields.persistSubmissions,\n\t\tdefaultFields.consentRetentionNotice,\n\t]\n}\n"],"mappings":";;;;;;;;;AA+BA,MAAa,oCAA2D;CACvE,WAAW;EACV,MAAM;EACN,MAAM;EACN,cAAc;EACd,OAAO,YAAY,KAAK,aAAa;EACrC,OAAO,EAAE,UAAU,UAAU;CAC9B;CACA,aAAa;EACZ,MAAM;EACN,MAAM;EACN,cAAc;EACd,OAAO,YAAY,KAAK,eAAe;EACvC,OAAO,EAAE,UAAU,UAAU;CAC9B;CACA,oBAAoB;EACnB,MAAM;EACN,MAAM;EACN,cAAc;EACd,OAAO,YAAY,KAAK,sBAAsB;EAC9C,OAAO,EAAE,UAAU,UAAU;CAC9B;CAIA,wBAAwB;EACvB,MAAM;EACN,MAAM;EACN,OAAO;GACN,UAAU;GACV,YAAY,SACV,MAA2C,uBAAuB,SACnE,MAAM,QAAS,MAA+B,MAAM,MAClD,KAA+C,UAAU,CAAC,GAAG,MAC7D,UAAU,OAAO,cAAc,SACjC;GACD,YAAY,EAAE,OAAO,wDAAwD;EAC9E;CACD;AACD;AAEA,MAAa,yBAAyB,aAAkD;CACvF,MAAM,gBAAgB,2BAA2B;CACjD,IAAI,UAAU,QACb,OAAO,SAAS,OAAO,EAAE,cAAc,CAAC;CAEzC,OAAO;EACN,cAAc;EACd,cAAc;EACd,cAAc;EACd,cAAc;CACf;AACD"}
|
|
@@ -12,7 +12,8 @@ type ConsentProof = {
|
|
|
12
12
|
versionRef?: string; /** The source label at submit time, so an audit names the statement even after a rename or delete. */
|
|
13
13
|
name?: string; /** sha256 of the statement plain text agreed to: tamper-evident and PII-free. */
|
|
14
14
|
statementHash?: string; /** Plain-text snapshot of the statement agreed to, for a human-readable audit. */
|
|
15
|
-
statementText?: string;
|
|
15
|
+
statementText?: string; /** Present only for a notice display, where submitting was the act of consent; absent means a ticked checkbox. */
|
|
16
|
+
display?: 'notice';
|
|
16
17
|
at: string;
|
|
17
18
|
};
|
|
18
19
|
/**
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { textOfBody } from "../actions/body/textOfBody.js";
|
|
2
|
+
import { consentDisplayOf, effectiveConsentStatement } from "./effectiveStatement.js";
|
|
2
3
|
import { resolvePublishedVersionRef } from "./resolvePublishedVersionRef.js";
|
|
3
4
|
import { createHash } from "node:crypto";
|
|
4
5
|
import { hasDraftsEnabled } from "payload/shared";
|
|
@@ -33,10 +34,12 @@ const captureConsent = async (args) => {
|
|
|
33
34
|
const source = typeof args.field.source === "string" ? args.field.source : "";
|
|
34
35
|
const entry = source ? args.entries.find((candidate) => candidate.id === source) : void 0;
|
|
35
36
|
const snapshot = args.snapshot ?? "both";
|
|
37
|
+
const display = consentDisplayOf(args.field);
|
|
36
38
|
const withSnapshot = (proof) => {
|
|
39
|
+
if (display === "notice") proof.display = "notice";
|
|
37
40
|
if (!entry || snapshot === false) return proof;
|
|
38
41
|
if (typeof entry.name === "string" && entry.name.trim().length > 0) proof.name = entry.name.trim();
|
|
39
|
-
const text = textOfBody(entry
|
|
42
|
+
const text = textOfBody(effectiveConsentStatement(entry, display));
|
|
40
43
|
if (text.length > 0) {
|
|
41
44
|
if (snapshot === "hash" || snapshot === "both") proof.statementHash = createHash("sha256").update(text).digest("hex");
|
|
42
45
|
if (snapshot === "text" || snapshot === "both") proof.statementText = text;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"captureConsent.js","names":[],"sources":["../../src/consent/captureConsent.ts"],"sourcesContent":["import { createHash } from 'node:crypto'\nimport type { Payload, PayloadRequest } from 'payload'\nimport { hasDraftsEnabled } from 'payload/shared'\nimport { textOfBody } from '../actions/body/textOfBody'\nimport type { FormFieldInstance } from '../submissions/types'\nimport { resolvePublishedVersionRef } from './resolvePublishedVersionRef'\nimport type { ConsentSourceEntry, ConsentSourcePage } from './types'\n\n/** What a submission snapshots of the agreed wording. `'hash'` and `'text'` combine as `'both'`. */\nexport type ConsentSnapshotMode = 'hash' | 'text' | 'both' | false\n\nexport type ConsentProof = {\n\tagreed: boolean\n\t/** The source `id` the field referenced; empty when the author never picked one. */\n\tsource: string\n\tpage?: ConsentSourcePage\n\tversionRef?: string\n\t/** The source label at submit time, so an audit names the statement even after a rename or delete. */\n\tname?: string\n\t/** sha256 of the statement plain text agreed to: tamper-evident and PII-free. */\n\tstatementHash?: string\n\t/** Plain-text snapshot of the statement agreed to, for a human-readable audit. */\n\tstatementText?: string\n\tat: string\n}\n\n/**\n * The authoritative consent proof, built at submit time from the server's own view of the source\n * (the field carries an id, never a statement, so there is nothing here the client could forge).\n *\n * Proof is id-based on purpose: it records which document was agreed to, so renaming, re-slugging,\n * or re-routing the policy leaves every past proof intact and resolvable. `snapshot` additionally\n * captures the agreed wording (a `statementHash`, the plain `statementText`, or both) plus the source\n * `name`, so an audit shows exactly what was agreed to independent of later edits; `false` keeps the\n * lean id-only proof. The snapshot is captured in every branch, including a refusal and a page-less\n * source.\n *\n * Time-of-check/time-of-use: a visitor reads the wording resolved when the form loaded, but the\n * snapshot here is re-resolved from the source at submit. If the source text changed in that window,\n * the proof records the submit-time wording, not the exact bytes rendered earlier. This is\n * deliberate, the server's live view is authoritative and the window is one visitor session; a form\n * that must freeze the exact wording agreed to should version the source (drafts give a `versionRef`\n * pinning the published version, below).\n *\n * `versionRef` is recorded only when the page's collection has drafts enabled, and then it is the\n * published version document's own id. Versions without drafts get no `versionRef`, because there\n * is no published/draft distinction to pin to: `_status` only exists under drafts, so a\n * published-version lookup there matches nothing, and recording that as a version reference would\n * be inventing one. Absent means absent, in both cases.\n *\n * `now` is injected by the caller (`new Date().toISOString()`) for testability.\n */\nexport const captureConsent = async (args: {\n\tfield: FormFieldInstance\n\tagreed: boolean\n\t/** The host's resolved sources for this request (see `resolveConsentEntries`). */\n\tentries: ConsentSourceEntry[]\n\tpayload: Payload\n\treq?: PayloadRequest\n\tnow: string\n\t/** What to snapshot of the agreed wording (plugin option `consent.snapshot`); defaults to `'both'`. */\n\tsnapshot?: ConsentSnapshotMode\n}): Promise<ConsentProof> => {\n\tconst source = typeof args.field.source === 'string' ? args.field.source : ''\n\tconst entry = source ? args.entries.find((candidate) => candidate.id === source) : undefined\n\tconst snapshot = args.snapshot ?? 'both'\n\n\t// Capture the agreed wording (and the source label) onto every proof branch. Kept out of the two\n\t// returns so a refusal and a page-less source are snapshotted the same as the happy path.\n\tconst withSnapshot = (proof: ConsentProof): ConsentProof => {\n\t\tif (!entry || snapshot === false) {\n\t\t\treturn proof\n\t\t}\n\t\tif (typeof entry.name === 'string' && entry.name.trim().length > 0) {\n\t\t\tproof.name = entry.name.trim()\n\t\t}\n\t\tconst text = textOfBody(entry
|
|
1
|
+
{"version":3,"file":"captureConsent.js","names":[],"sources":["../../src/consent/captureConsent.ts"],"sourcesContent":["import { createHash } from 'node:crypto'\nimport type { Payload, PayloadRequest } from 'payload'\nimport { hasDraftsEnabled } from 'payload/shared'\nimport { textOfBody } from '../actions/body/textOfBody'\nimport type { FormFieldInstance } from '../submissions/types'\nimport { consentDisplayOf, effectiveConsentStatement } from './effectiveStatement'\nimport { resolvePublishedVersionRef } from './resolvePublishedVersionRef'\nimport type { ConsentSourceEntry, ConsentSourcePage } from './types'\n\n/** What a submission snapshots of the agreed wording. `'hash'` and `'text'` combine as `'both'`. */\nexport type ConsentSnapshotMode = 'hash' | 'text' | 'both' | false\n\nexport type ConsentProof = {\n\tagreed: boolean\n\t/** The source `id` the field referenced; empty when the author never picked one. */\n\tsource: string\n\tpage?: ConsentSourcePage\n\tversionRef?: string\n\t/** The source label at submit time, so an audit names the statement even after a rename or delete. */\n\tname?: string\n\t/** sha256 of the statement plain text agreed to: tamper-evident and PII-free. */\n\tstatementHash?: string\n\t/** Plain-text snapshot of the statement agreed to, for a human-readable audit. */\n\tstatementText?: string\n\t/** Present only for a notice display, where submitting was the act of consent; absent means a ticked checkbox. */\n\tdisplay?: 'notice'\n\tat: string\n}\n\n/**\n * The authoritative consent proof, built at submit time from the server's own view of the source\n * (the field carries an id, never a statement, so there is nothing here the client could forge).\n *\n * Proof is id-based on purpose: it records which document was agreed to, so renaming, re-slugging,\n * or re-routing the policy leaves every past proof intact and resolvable. `snapshot` additionally\n * captures the agreed wording (a `statementHash`, the plain `statementText`, or both) plus the source\n * `name`, so an audit shows exactly what was agreed to independent of later edits; `false` keeps the\n * lean id-only proof. The snapshot is captured in every branch, including a refusal and a page-less\n * source.\n *\n * Time-of-check/time-of-use: a visitor reads the wording resolved when the form loaded, but the\n * snapshot here is re-resolved from the source at submit. If the source text changed in that window,\n * the proof records the submit-time wording, not the exact bytes rendered earlier. This is\n * deliberate, the server's live view is authoritative and the window is one visitor session; a form\n * that must freeze the exact wording agreed to should version the source (drafts give a `versionRef`\n * pinning the published version, below).\n *\n * `versionRef` is recorded only when the page's collection has drafts enabled, and then it is the\n * published version document's own id. Versions without drafts get no `versionRef`, because there\n * is no published/draft distinction to pin to: `_status` only exists under drafts, so a\n * published-version lookup there matches nothing, and recording that as a version reference would\n * be inventing one. Absent means absent, in both cases.\n *\n * `now` is injected by the caller (`new Date().toISOString()`) for testability.\n */\nexport const captureConsent = async (args: {\n\tfield: FormFieldInstance\n\tagreed: boolean\n\t/** The host's resolved sources for this request (see `resolveConsentEntries`). */\n\tentries: ConsentSourceEntry[]\n\tpayload: Payload\n\treq?: PayloadRequest\n\tnow: string\n\t/** What to snapshot of the agreed wording (plugin option `consent.snapshot`); defaults to `'both'`. */\n\tsnapshot?: ConsentSnapshotMode\n}): Promise<ConsentProof> => {\n\tconst source = typeof args.field.source === 'string' ? args.field.source : ''\n\tconst entry = source ? args.entries.find((candidate) => candidate.id === source) : undefined\n\tconst snapshot = args.snapshot ?? 'both'\n\tconst display = consentDisplayOf(args.field)\n\n\t// Capture the agreed wording (and the source label) onto every proof branch. Kept out of the two\n\t// returns so a refusal and a page-less source are snapshotted the same as the happy path. The\n\t// wording is selected per the field's display through the same helper the render path uses, so\n\t// the proof attests to the sentence the visitor saw.\n\tconst withSnapshot = (proof: ConsentProof): ConsentProof => {\n\t\tif (display === 'notice') {\n\t\t\tproof.display = 'notice'\n\t\t}\n\t\tif (!entry || snapshot === false) {\n\t\t\treturn proof\n\t\t}\n\t\tif (typeof entry.name === 'string' && entry.name.trim().length > 0) {\n\t\t\tproof.name = entry.name.trim()\n\t\t}\n\t\tconst text = textOfBody(effectiveConsentStatement(entry, display))\n\t\tif (text.length > 0) {\n\t\t\tif (snapshot === 'hash' || snapshot === 'both') {\n\t\t\t\tproof.statementHash = createHash('sha256').update(text).digest('hex')\n\t\t\t}\n\t\t\tif (snapshot === 'text' || snapshot === 'both') {\n\t\t\t\tproof.statementText = text\n\t\t\t}\n\t\t}\n\t\treturn proof\n\t}\n\n\tconst page = entry?.page\n\tif (!page) {\n\t\treturn withSnapshot({ agreed: args.agreed, source, at: args.now })\n\t}\n\t// `page.relationTo` is a runtime string; cast the key so the lookup type-checks against a host's\n\t// narrowed collection map (a consumer's generated `CollectionSlug`) as well as the plugin's own\n\t// broad one. The value is still guarded below, since an unregistered slug resolves to undefined.\n\tconst collection = args.payload.collections[page.relationTo as keyof Payload['collections']]\n\tconst versionRef =\n\t\tcollection && hasDraftsEnabled(collection.config)\n\t\t\t? await resolvePublishedVersionRef({\n\t\t\t\t\tpayload: args.payload,\n\t\t\t\t\tcollection: page.relationTo,\n\t\t\t\t\tid: page.id,\n\t\t\t\t\treq: args.req,\n\t\t\t\t})\n\t\t\t: null\n\treturn withSnapshot({\n\t\tagreed: args.agreed,\n\t\tsource,\n\t\tpage: { relationTo: page.relationTo, id: page.id },\n\t\t...(versionRef ? { versionRef } : {}),\n\t\tat: args.now,\n\t})\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuDA,MAAa,iBAAiB,OAAO,SAUR;CAC5B,MAAM,SAAS,OAAO,KAAK,MAAM,WAAW,WAAW,KAAK,MAAM,SAAS;CAC3E,MAAM,QAAQ,SAAS,KAAK,QAAQ,MAAM,cAAc,UAAU,OAAO,MAAM,IAAI,KAAA;CACnF,MAAM,WAAW,KAAK,YAAY;CAClC,MAAM,UAAU,iBAAiB,KAAK,KAAK;CAM3C,MAAM,gBAAgB,UAAsC;EAC3D,IAAI,YAAY,UACf,MAAM,UAAU;EAEjB,IAAI,CAAC,SAAS,aAAa,OAC1B,OAAO;EAER,IAAI,OAAO,MAAM,SAAS,YAAY,MAAM,KAAK,KAAK,EAAE,SAAS,GAChE,MAAM,OAAO,MAAM,KAAK,KAAK;EAE9B,MAAM,OAAO,WAAW,0BAA0B,OAAO,OAAO,CAAC;EACjE,IAAI,KAAK,SAAS,GAAG;GACpB,IAAI,aAAa,UAAU,aAAa,QACvC,MAAM,gBAAgB,WAAW,QAAQ,EAAE,OAAO,IAAI,EAAE,OAAO,KAAK;GAErE,IAAI,aAAa,UAAU,aAAa,QACvC,MAAM,gBAAgB;EAExB;EACA,OAAO;CACR;CAEA,MAAM,OAAO,OAAO;CACpB,IAAI,CAAC,MACJ,OAAO,aAAa;EAAE,QAAQ,KAAK;EAAQ;EAAQ,IAAI,KAAK;CAAI,CAAC;CAKlE,MAAM,aAAa,KAAK,QAAQ,YAAY,KAAK;CACjD,MAAM,aACL,cAAc,iBAAiB,WAAW,MAAM,IAC7C,MAAM,2BAA2B;EACjC,SAAS,KAAK;EACd,YAAY,KAAK;EACjB,IAAI,KAAK;EACT,KAAK,KAAK;CACX,CAAC,IACA;CACJ,OAAO,aAAa;EACnB,QAAQ,KAAK;EACb;EACA,MAAM;GAAE,YAAY,KAAK;GAAY,IAAI,KAAK;EAAG;EACjD,GAAI,aAAa,EAAE,WAAW,IAAI,CAAC;EACnC,IAAI,KAAK;CACV,CAAC;AACF"}
|
|
@@ -45,7 +45,13 @@ type ConsentSourcesFieldOptions = {
|
|
|
45
45
|
* formBuilder({
|
|
46
46
|
* consent: {
|
|
47
47
|
* sources: async ({ req }) => {
|
|
48
|
-
* const settings = await req.payload.findGlobal({
|
|
48
|
+
* const settings = await req.payload.findGlobal({
|
|
49
|
+
* slug: 'settings',
|
|
50
|
+
* depth: 0,
|
|
51
|
+
* locale: req.locale,
|
|
52
|
+
* overrideAccess: true,
|
|
53
|
+
* req,
|
|
54
|
+
* })
|
|
49
55
|
* return (settings.consentSources ?? []).map((row) => ({ ... }))
|
|
50
56
|
* },
|
|
51
57
|
* },
|
|
@@ -29,7 +29,13 @@ import { localizedIf } from "../fields/localizedIf.js";
|
|
|
29
29
|
* formBuilder({
|
|
30
30
|
* consent: {
|
|
31
31
|
* sources: async ({ req }) => {
|
|
32
|
-
* const settings = await req.payload.findGlobal({
|
|
32
|
+
* const settings = await req.payload.findGlobal({
|
|
33
|
+
* slug: 'settings',
|
|
34
|
+
* depth: 0,
|
|
35
|
+
* locale: req.locale,
|
|
36
|
+
* overrideAccess: true,
|
|
37
|
+
* req,
|
|
38
|
+
* })
|
|
33
39
|
* return (settings.consentSources ?? []).map((row) => ({ ... }))
|
|
34
40
|
* },
|
|
35
41
|
* },
|
|
@@ -80,6 +86,14 @@ const consentSourcesField = (options = {}) => {
|
|
|
80
86
|
...options.editor ? { editor: options.editor } : {},
|
|
81
87
|
...localizedIf(localize)
|
|
82
88
|
},
|
|
89
|
+
{
|
|
90
|
+
name: "noticeStatement",
|
|
91
|
+
type: "richText",
|
|
92
|
+
label: labelForKey(keys.consentSourceNoticeStatement),
|
|
93
|
+
admin: { description: labelForKey(keys.consentSourceNoticeStatementDescription) },
|
|
94
|
+
...options.editor ? { editor: options.editor } : {},
|
|
95
|
+
...localizedIf(localize)
|
|
96
|
+
},
|
|
83
97
|
...pageField
|
|
84
98
|
]
|
|
85
99
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"consentSourcesField.js","names":[],"sources":["../../src/consent/consentSourcesField.ts"],"sourcesContent":["import type { ArrayField, CollectionSlug, Field, RichTextField } from 'payload'\nimport { localizedIf } from '../fields/localizedIf'\nimport { keys } from '../translations/keys'\nimport { labelForKey } from '../translations/server'\n\nexport type ConsentSourcesFieldOptions = {\n\t/** Field name, i.e. what the row array is stored under. Defaults to `consentSources`. */\n\tname?: string\n\t/** Field label. Defaults to the plugin's translated one. */\n\tlabel?: ArrayField['label']\n\t/**\n\t * Collections whose documents can be picked as a source's policy page. Omitted (the default):\n\t * no page picker at all, so sources are statement-only and their proofs carry no page or\n\t * version reference. Always stored polymorphically, even for a single slug (see below).\n\t */\n\trelationTo?: CollectionSlug | CollectionSlug[]\n\t/**\n\t * Whether the visitor-facing `statement` and `name` carry `localized: true`. Default `true`;\n\t * Payload strips the flag on hosts without `localization`, so it is safe either way. Mirrors\n\t * the plugin's `localizeContent` option, which this host-called factory cannot see.\n\t */\n\tlocalized?: boolean\n\t/** Overrides the project's default richText editor for the `statement`, as `richText.editor` does plugin-side. */\n\teditor?: RichTextField['editor']\n}\n\n/**\n * The consent sources array, for the host to place on any collection or global they own: a\n * settings global, a tenants collection, a legal-pages parent, wherever the sources belong. The\n * plugin never registers it and never guesses where it lives; a matching `consent.sources` resolver\n * reads it back (see {@link ConsentSourcesResolver}), which is also where multi-tenant scoping goes:\n * place this on the tenant-scoped document and have the resolver return only the sources of the\n * tenant it derives from `req`.\n *\n * A row is a `name` (shown when picking the source on a form, and used as the policy link text\n * beside the statement), the `statement` the visitor agrees to, and optionally the `page` that\n * statement belongs to. The stable reference a consent field stores, and the only part that must\n * outlive edits, is the row's own auto-assigned `id`: it survives a `name` edit or reordering,\n * unlike a hand-authored key would. Authors fill in no version, no URL, and no document id by\n * hand: the version is detected and recorded at submit time, and the page is a picker.\n *\n * `page` is always polymorphic, even when `relationTo` names a single collection, because a\n * monomorphic relationship stores a bare id: the proof needs the collection alongside it to stay\n * resolvable, and a host adding a second collection later would otherwise change the stored shape.\n *\n * ```ts\n * // The host's own collection or global:\n * fields: [consentSourcesField({ relationTo: ['pages', 'legal-notices'] })]\n *\n * // The plugin, reading it back:\n * formBuilder({\n * consent: {\n * sources: async ({ req }) => {\n * const settings = await req.payload.findGlobal({ slug: 'settings'
|
|
1
|
+
{"version":3,"file":"consentSourcesField.js","names":[],"sources":["../../src/consent/consentSourcesField.ts"],"sourcesContent":["import type { ArrayField, CollectionSlug, Field, RichTextField } from 'payload'\nimport { localizedIf } from '../fields/localizedIf'\nimport { keys } from '../translations/keys'\nimport { labelForKey } from '../translations/server'\n\nexport type ConsentSourcesFieldOptions = {\n\t/** Field name, i.e. what the row array is stored under. Defaults to `consentSources`. */\n\tname?: string\n\t/** Field label. Defaults to the plugin's translated one. */\n\tlabel?: ArrayField['label']\n\t/**\n\t * Collections whose documents can be picked as a source's policy page. Omitted (the default):\n\t * no page picker at all, so sources are statement-only and their proofs carry no page or\n\t * version reference. Always stored polymorphically, even for a single slug (see below).\n\t */\n\trelationTo?: CollectionSlug | CollectionSlug[]\n\t/**\n\t * Whether the visitor-facing `statement` and `name` carry `localized: true`. Default `true`;\n\t * Payload strips the flag on hosts without `localization`, so it is safe either way. Mirrors\n\t * the plugin's `localizeContent` option, which this host-called factory cannot see.\n\t */\n\tlocalized?: boolean\n\t/** Overrides the project's default richText editor for the `statement`, as `richText.editor` does plugin-side. */\n\teditor?: RichTextField['editor']\n}\n\n/**\n * The consent sources array, for the host to place on any collection or global they own: a\n * settings global, a tenants collection, a legal-pages parent, wherever the sources belong. The\n * plugin never registers it and never guesses where it lives; a matching `consent.sources` resolver\n * reads it back (see {@link ConsentSourcesResolver}), which is also where multi-tenant scoping goes:\n * place this on the tenant-scoped document and have the resolver return only the sources of the\n * tenant it derives from `req`.\n *\n * A row is a `name` (shown when picking the source on a form, and used as the policy link text\n * beside the statement), the `statement` the visitor agrees to, and optionally the `page` that\n * statement belongs to. The stable reference a consent field stores, and the only part that must\n * outlive edits, is the row's own auto-assigned `id`: it survives a `name` edit or reordering,\n * unlike a hand-authored key would. Authors fill in no version, no URL, and no document id by\n * hand: the version is detected and recorded at submit time, and the page is a picker.\n *\n * `page` is always polymorphic, even when `relationTo` names a single collection, because a\n * monomorphic relationship stores a bare id: the proof needs the collection alongside it to stay\n * resolvable, and a host adding a second collection later would otherwise change the stored shape.\n *\n * ```ts\n * // The host's own collection or global:\n * fields: [consentSourcesField({ relationTo: ['pages', 'legal-notices'] })]\n *\n * // The plugin, reading it back:\n * formBuilder({\n * consent: {\n * sources: async ({ req }) => {\n * const settings = await req.payload.findGlobal({\n * slug: 'settings',\n * depth: 0,\n * locale: req.locale,\n * overrideAccess: true,\n * req,\n * })\n * return (settings.consentSources ?? []).map((row) => ({ ... }))\n * },\n * },\n * })\n * ```\n *\n * The resolver receives the whole form document, so derive tenant scoping from a field on it rather\n * than reading the form back: reading the `forms` collection from the resolver re-enters this form's\n * afterRead hook (the plugin guards against the resulting recursion, but the read is still wasted).\n *\n * A resolver reading its settings document must not thread the save's `req` into a `locale: 'all'`\n * read from within a form's save validation: that flips `req.locale` to `all` and corrupts the\n * localized write of the document being saved. It reads already-committed data, so no `req` is needed.\n */\nexport const consentSourcesField = (options: ConsentSourcesFieldOptions = {}): ArrayField => {\n\tconst localize = options.localized !== false\n\t// An empty `relationTo` array is treated as \"no page picker\", not a relationship field pointing\n\t// at nothing (which Payload rejects at boot).\n\tconst relationTo =\n\t\toptions.relationTo && (!Array.isArray(options.relationTo) || options.relationTo.length > 0)\n\t\t\t? options.relationTo\n\t\t\t: undefined\n\tconst pageField: Field[] = relationTo\n\t\t? [\n\t\t\t\t{\n\t\t\t\t\tname: 'page',\n\t\t\t\t\ttype: 'relationship',\n\t\t\t\t\trelationTo: Array.isArray(relationTo) ? relationTo : [relationTo],\n\t\t\t\t\tlabel: labelForKey(keys.consentSourcePage),\n\t\t\t\t\tadmin: { description: labelForKey(keys.consentSourcePageDescription) },\n\t\t\t\t},\n\t\t\t]\n\t\t: []\n\n\treturn {\n\t\tname: options.name ?? 'consentSources',\n\t\ttype: 'array',\n\t\tlabel: options.label ?? labelForKey(keys.consentSourcesField),\n\t\tlabels: {\n\t\t\tsingular: labelForKey(keys.consentSourceSingular),\n\t\t\tplural: labelForKey(keys.consentSourcePlural),\n\t\t},\n\t\tadmin: {\n\t\t\tdescription: labelForKey(keys.consentSourcesFieldDescription),\n\t\t\tcomponents: { RowLabel: '@10x-media/form-builder/client#ConsentSourceRowLabel' },\n\t\t},\n\t\tfields: [\n\t\t\t{\n\t\t\t\tname: 'name',\n\t\t\t\ttype: 'text',\n\t\t\t\tlabel: labelForKey(keys.consentSourceLabel),\n\t\t\t\t...localizedIf(localize),\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: 'statement',\n\t\t\t\ttype: 'richText',\n\t\t\t\tlabel: labelForKey(keys.consentSourceStatement),\n\t\t\t\t...(options.editor ? { editor: options.editor } : {}),\n\t\t\t\t...localizedIf(localize),\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: 'noticeStatement',\n\t\t\t\ttype: 'richText',\n\t\t\t\tlabel: labelForKey(keys.consentSourceNoticeStatement),\n\t\t\t\tadmin: { description: labelForKey(keys.consentSourceNoticeStatementDescription) },\n\t\t\t\t...(options.editor ? { editor: options.editor } : {}),\n\t\t\t\t...localizedIf(localize),\n\t\t\t},\n\t\t\t...pageField,\n\t\t],\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0EA,MAAa,uBAAuB,UAAsC,CAAC,MAAkB;CAC5F,MAAM,WAAW,QAAQ,cAAc;CAGvC,MAAM,aACL,QAAQ,eAAe,CAAC,MAAM,QAAQ,QAAQ,UAAU,KAAK,QAAQ,WAAW,SAAS,KACtF,QAAQ,aACR,KAAA;CACJ,MAAM,YAAqB,aACxB,CACA;EACC,MAAM;EACN,MAAM;EACN,YAAY,MAAM,QAAQ,UAAU,IAAI,aAAa,CAAC,UAAU;EAChE,OAAO,YAAY,KAAK,iBAAiB;EACzC,OAAO,EAAE,aAAa,YAAY,KAAK,4BAA4B,EAAE;CACtE,CACD,IACC,CAAC;CAEJ,OAAO;EACN,MAAM,QAAQ,QAAQ;EACtB,MAAM;EACN,OAAO,QAAQ,SAAS,YAAY,KAAK,mBAAmB;EAC5D,QAAQ;GACP,UAAU,YAAY,KAAK,qBAAqB;GAChD,QAAQ,YAAY,KAAK,mBAAmB;EAC7C;EACA,OAAO;GACN,aAAa,YAAY,KAAK,8BAA8B;GAC5D,YAAY,EAAE,UAAU,uDAAuD;EAChF;EACA,QAAQ;GACP;IACC,MAAM;IACN,MAAM;IACN,OAAO,YAAY,KAAK,kBAAkB;IAC1C,GAAG,YAAY,QAAQ;GACxB;GACA;IACC,MAAM;IACN,MAAM;IACN,OAAO,YAAY,KAAK,sBAAsB;IAC9C,GAAI,QAAQ,SAAS,EAAE,QAAQ,QAAQ,OAAO,IAAI,CAAC;IACnD,GAAG,YAAY,QAAQ;GACxB;GACA;IACC,MAAM;IACN,MAAM;IACN,OAAO,YAAY,KAAK,4BAA4B;IACpD,OAAO,EAAE,aAAa,YAAY,KAAK,uCAAuC,EAAE;IAChF,GAAI,QAAQ,SAAS,EAAE,QAAQ,QAAQ,OAAO,IAAI,CAAC;IACnD,GAAG,YAAY,QAAQ;GACxB;GACA,GAAG;EACJ;CACD;AACD"}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { textOfBody } from "../actions/body/textOfBody.js";
|
|
2
|
+
//#region src/consent/effectiveStatement.ts
|
|
3
|
+
/** A consent field instance's display, defaulting anything but an explicit `'notice'` to `'checkbox'`. */
|
|
4
|
+
const consentDisplayOf = (field) => field?.display === "notice" ? "notice" : "checkbox";
|
|
5
|
+
/**
|
|
6
|
+
* The wording a consent field shows for its display: the source's `noticeStatement` for a notice
|
|
7
|
+
* (falling back to `statement` when it is absent or empty), the `statement` for a checkbox. Both
|
|
8
|
+
* the render path (`resolveConsentStatements`) and the proof path (`captureConsent`) select
|
|
9
|
+
* through this one function, which is what guarantees the snapshot attests to the wording the
|
|
10
|
+
* visitor actually saw.
|
|
11
|
+
*/
|
|
12
|
+
const effectiveConsentStatement = (entry, display) => display === "notice" && textOfBody(entry.noticeStatement).trim().length > 0 ? entry.noticeStatement : entry.statement;
|
|
13
|
+
//#endregion
|
|
14
|
+
export { consentDisplayOf, effectiveConsentStatement };
|
|
15
|
+
|
|
16
|
+
//# sourceMappingURL=effectiveStatement.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"effectiveStatement.js","names":[],"sources":["../../src/consent/effectiveStatement.ts"],"sourcesContent":["import { textOfBody } from '../actions/body/textOfBody'\nimport type { ConsentSourceEntry } from './types'\n\n/** How a consent field presents itself: a box to tick, or a passive notice the submit agrees to. */\nexport type ConsentDisplay = 'checkbox' | 'notice'\n\n/** A consent field instance's display, defaulting anything but an explicit `'notice'` to `'checkbox'`. */\nexport const consentDisplayOf = (field: unknown): ConsentDisplay =>\n\t(field as { display?: unknown } | null | undefined)?.display === 'notice' ? 'notice' : 'checkbox'\n\n/**\n * The wording a consent field shows for its display: the source's `noticeStatement` for a notice\n * (falling back to `statement` when it is absent or empty), the `statement` for a checkbox. Both\n * the render path (`resolveConsentStatements`) and the proof path (`captureConsent`) select\n * through this one function, which is what guarantees the snapshot attests to the wording the\n * visitor actually saw.\n */\nexport const effectiveConsentStatement = (\n\tentry: Pick<ConsentSourceEntry, 'statement' | 'noticeStatement'>,\n\tdisplay: ConsentDisplay\n): unknown =>\n\tdisplay === 'notice' && textOfBody(entry.noticeStatement).trim().length > 0\n\t\t? entry.noticeStatement\n\t\t: entry.statement\n"],"mappings":";;;AAOA,MAAa,oBAAoB,UAC/B,OAAoD,YAAY,WAAW,WAAW;;;;;;;;AASxF,MAAa,6BACZ,OACA,YAEA,YAAY,YAAY,WAAW,MAAM,eAAe,EAAE,KAAK,EAAE,SAAS,IACvE,MAAM,kBACN,MAAM"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { resolveConsentEntries } from "./resolveConsentEntries.js";
|
|
2
|
-
import {
|
|
2
|
+
import { pluginSlugsOf } from "../plugin/collectionSlugs.js";
|
|
3
3
|
//#region src/consent/resolveConsentSourcesRequest.ts
|
|
4
4
|
/**
|
|
5
5
|
* Authorize and resolve the `GET /:id/consent-sources` request backing the consent `source` select:
|
|
@@ -19,7 +19,7 @@ const resolveConsentSourcesRequest = async (args) => {
|
|
|
19
19
|
body: { errors: [{ message: "Missing form id" }] }
|
|
20
20
|
};
|
|
21
21
|
const form = await payload.findByID({
|
|
22
|
-
collection:
|
|
22
|
+
collection: pluginSlugsOf(payload).forms,
|
|
23
23
|
id: formId,
|
|
24
24
|
depth: 0,
|
|
25
25
|
req
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"resolveConsentSourcesRequest.js","names":[],"sources":["../../src/consent/resolveConsentSourcesRequest.ts"],"sourcesContent":["import type { Payload, PayloadRequest } from 'payload'\nimport {
|
|
1
|
+
{"version":3,"file":"resolveConsentSourcesRequest.js","names":[],"sources":["../../src/consent/resolveConsentSourcesRequest.ts"],"sourcesContent":["import type { Payload, PayloadRequest } from 'payload'\nimport { pluginSlugsOf } from '../plugin/collectionSlugs'\nimport { resolveConsentEntries } from './resolveConsentEntries'\nimport type { ConsentSourcesResolver } from './types'\n\n/** One selectable consent source for the consent field's `source` select. */\nexport type ConsentSourceOption = { label: string; value: string }\n\nexport type ResolveConsentSourcesRequestArgs = {\n\tpayload: Payload\n\tformId: number | string | undefined\n\t/** Whether the caller is authenticated (an admin/user). */\n\tisAuthed: boolean\n\treq: PayloadRequest\n\tresolver: ConsentSourcesResolver\n}\n\nexport type ResolveConsentSourcesRequestResult = {\n\tstatus: number\n\tbody: { options: ConsentSourceOption[] } | { errors: { message: string }[] }\n}\n\n/**\n * Authorize and resolve the `GET /:id/consent-sources` request backing the consent `source` select:\n * authenticated callers get the host's sources for this request (a multi-tenant resolver scoping by\n * `req` therefore offers an author only their own tenant's), anonymous callers are always refused.\n * Statuses mirror the poll-options endpoint: 400 missing id, 403 unauthenticated, 404 unknown form,\n * 503 when the resolver throws (fail closed).\n */\nexport const resolveConsentSourcesRequest = async (\n\targs: ResolveConsentSourcesRequestArgs\n): Promise<ResolveConsentSourcesRequestResult> => {\n\tconst { payload, formId, isAuthed, req, resolver } = args\n\tif (!isAuthed) {\n\t\treturn { status: 403, body: { errors: [{ message: 'Forbidden' }] } }\n\t}\n\tif (formId == null) {\n\t\treturn { status: 400, body: { errors: [{ message: 'Missing form id' }] } }\n\t}\n\t// Load under the caller's own read access (no overrideAccess): a tenant-scoped `forms.access.read`\n\t// then refuses a cross-tenant form id (null -> 404), so an authed user can never enumerate another\n\t// tenant's consent source labels/ids.\n\tconst form = await payload\n\t\t.findByID({ collection: pluginSlugsOf(payload).forms, id: formId, depth: 0, req })\n\t\t.catch(() => null)\n\tif (!form) {\n\t\treturn { status: 404, body: { errors: [{ message: 'Not found' }] } }\n\t}\n\ttry {\n\t\tconst entries = await resolveConsentEntries({ payload, req, form, sources: resolver })\n\t\treturn {\n\t\t\tstatus: 200,\n\t\t\tbody: {\n\t\t\t\toptions: entries.map((entry) => ({ label: entry.name ?? entry.id, value: entry.id })),\n\t\t\t},\n\t\t}\n\t} catch {\n\t\treturn { status: 503, body: { errors: [{ message: 'Consent sources unavailable' }] } }\n\t}\n}\n"],"mappings":";;;;;;;;;;AA6BA,MAAa,+BAA+B,OAC3C,SACiD;CACjD,MAAM,EAAE,SAAS,QAAQ,UAAU,KAAK,aAAa;CACrD,IAAI,CAAC,UACJ,OAAO;EAAE,QAAQ;EAAK,MAAM,EAAE,QAAQ,CAAC,EAAE,SAAS,YAAY,CAAC,EAAE;CAAE;CAEpE,IAAI,UAAU,MACb,OAAO;EAAE,QAAQ;EAAK,MAAM,EAAE,QAAQ,CAAC,EAAE,SAAS,kBAAkB,CAAC,EAAE;CAAE;CAK1E,MAAM,OAAO,MAAM,QACjB,SAAS;EAAE,YAAY,cAAc,OAAO,EAAE;EAAO,IAAI;EAAQ,OAAO;EAAG;CAAI,CAAC,EAChF,YAAY,IAAI;CAClB,IAAI,CAAC,MACJ,OAAO;EAAE,QAAQ;EAAK,MAAM,EAAE,QAAQ,CAAC,EAAE,SAAS,YAAY,CAAC,EAAE;CAAE;CAEpE,IAAI;EAEH,OAAO;GACN,QAAQ;GACR,MAAM,EACL,UAAS,MAJW,sBAAsB;IAAE;IAAS;IAAK;IAAM,SAAS;GAAS,CAAC,GAIlE,KAAK,WAAW;IAAE,OAAO,MAAM,QAAQ,MAAM;IAAI,OAAO,MAAM;GAAG,EAAE,EACrF;EACD;CACD,QAAQ;EACP,OAAO;GAAE,QAAQ;GAAK,MAAM,EAAE,QAAQ,CAAC,EAAE,SAAS,8BAA8B,CAAC,EAAE;EAAE;CACtF;AACD"}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { resolveConsentEntries } from "./resolveConsentEntries.js";
|
|
2
|
+
import { consentDisplayOf, effectiveConsentStatement } from "./effectiveStatement.js";
|
|
2
3
|
//#region src/consent/resolveConsentStatements.ts
|
|
3
4
|
/**
|
|
4
5
|
* Resolve every consent field's statement for this request, ready to hand to
|
|
@@ -28,8 +29,9 @@ const resolveConsentStatements = async (args) => {
|
|
|
28
29
|
const entry = entries.find((candidate) => candidate.id === field.source);
|
|
29
30
|
if (!entry) continue;
|
|
30
31
|
const label = typeof entry.name === "string" && entry.name.trim() !== "" ? entry.name : "";
|
|
32
|
+
const wording = effectiveConsentStatement(entry, consentDisplayOf(field));
|
|
31
33
|
statements[field.name] = {
|
|
32
|
-
...
|
|
34
|
+
...wording != null ? { statement: wording } : {},
|
|
33
35
|
...label && typeof entry.url === "string" && entry.url.length > 0 ? { link: {
|
|
34
36
|
label,
|
|
35
37
|
url: entry.url
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"resolveConsentStatements.js","names":[],"sources":["../../src/consent/resolveConsentStatements.ts"],"sourcesContent":["import type { Payload, PayloadRequest } from 'payload'\nimport { resolveConsentEntries } from './resolveConsentEntries'\nimport type { ConsentSourcesResolver } from './types'\n\n/** What a consent field shows the visitor, resolved from its source at request time. */\nexport type ConsentStatement = {\n\t/** Rich text state (or whatever the host's resolver returned), for the request's locale. */\n\tstatement?: unknown\n\t/** The policy link beside the statement, present only when the source carries both a `url` and a `label`. */\n\tlink?: { label: string; url: string }\n}\n\n/** Resolved statements keyed by consent field name, as `toFormDocument`'s `consentStatements` takes them. */\nexport type ConsentStatements = Record<string, ConsentStatement>\n\nexport type ResolveConsentStatementsArgs = {\n\tpayload: Payload\n\treq: PayloadRequest\n\t/** A loaded forms document; its consent fields' `source` ids drive resolution. The whole doc is forwarded to the resolver. */\n\tform: {\n\t\tid: number | string\n\t\ttitle?: string | null\n\t\tfields?: { blockType: string; name?: string; [key: string]: unknown }[] | null\n\t}\n\t/** Resolver override for plugin-internal callers; defaults to the one the plugin stashed on the config. */\n\tsources?: ConsentSourcesResolver\n}\n\n/**\n * Resolve every consent field's statement for this request, ready to hand to\n * `toFormDocument(doc, { consentStatements })`.\n *\n * The statement is a live reference, not a copy: a form stores only its source id, and the\n * sentence the visitor reads is resolved here, in their locale, from whatever the source says\n * right now. So correcting a policy sentence corrects every form referencing it, with nothing to\n * re-save, and a form rendered without this step shows no statement at all rather than a stale one.\n *\n * Call it server-side (a Server Component, a route handler) before rendering `<Form>`. Throws\n * whatever the host's resolver throws, so a page can decide between failing and rendering without\n * consent; a submit resolves the source again regardless, and the proof is built from that.\n */\nexport const resolveConsentStatements = async (\n\targs: ResolveConsentStatementsArgs\n): Promise<ConsentStatements> => {\n\tconst { payload, req, form, sources } = args\n\tconst consentFields = (form.fields ?? []).filter(\n\t\t(field): field is { blockType: string; name: string; source?: unknown } =>\n\t\t\tfield.blockType === 'consent' && typeof field.name === 'string' && field.name.length > 0\n\t)\n\tif (consentFields.length === 0) {\n\t\treturn {}\n\t}\n\tconst entries = await resolveConsentEntries({ payload, req, form, sources })\n\tconst statements: ConsentStatements = {}\n\tfor (const field of consentFields) {\n\t\tconst entry = entries.find((candidate) => candidate.id === field.source)\n\t\tif (!entry) {\n\t\t\tcontinue\n\t\t}\n\t\t// The link needs a name of its own, so it takes the source's `name` and never falls back to\n\t\t// the `id`: the id is a machine identifier, and showing it as the words a visitor clicks is\n\t\t// worse than no link at all. A source with a url and no name simply has no link.\n\t\tconst label = typeof entry.name === 'string' && entry.name.trim() !== '' ? entry.name : ''\n\t\tstatements[field.name] = {\n\t\t\t...(
|
|
1
|
+
{"version":3,"file":"resolveConsentStatements.js","names":[],"sources":["../../src/consent/resolveConsentStatements.ts"],"sourcesContent":["import type { Payload, PayloadRequest } from 'payload'\nimport { consentDisplayOf, effectiveConsentStatement } from './effectiveStatement'\nimport { resolveConsentEntries } from './resolveConsentEntries'\nimport type { ConsentSourcesResolver } from './types'\n\n/** What a consent field shows the visitor, resolved from its source at request time. */\nexport type ConsentStatement = {\n\t/** Rich text state (or whatever the host's resolver returned), for the request's locale. */\n\tstatement?: unknown\n\t/** The policy link beside the statement, present only when the source carries both a `url` and a `label`. */\n\tlink?: { label: string; url: string }\n}\n\n/** Resolved statements keyed by consent field name, as `toFormDocument`'s `consentStatements` takes them. */\nexport type ConsentStatements = Record<string, ConsentStatement>\n\nexport type ResolveConsentStatementsArgs = {\n\tpayload: Payload\n\treq: PayloadRequest\n\t/** A loaded forms document; its consent fields' `source` ids drive resolution. The whole doc is forwarded to the resolver. */\n\tform: {\n\t\tid: number | string\n\t\ttitle?: string | null\n\t\tfields?: { blockType: string; name?: string; [key: string]: unknown }[] | null\n\t}\n\t/** Resolver override for plugin-internal callers; defaults to the one the plugin stashed on the config. */\n\tsources?: ConsentSourcesResolver\n}\n\n/**\n * Resolve every consent field's statement for this request, ready to hand to\n * `toFormDocument(doc, { consentStatements })`.\n *\n * The statement is a live reference, not a copy: a form stores only its source id, and the\n * sentence the visitor reads is resolved here, in their locale, from whatever the source says\n * right now. So correcting a policy sentence corrects every form referencing it, with nothing to\n * re-save, and a form rendered without this step shows no statement at all rather than a stale one.\n *\n * Call it server-side (a Server Component, a route handler) before rendering `<Form>`. Throws\n * whatever the host's resolver throws, so a page can decide between failing and rendering without\n * consent; a submit resolves the source again regardless, and the proof is built from that.\n */\nexport const resolveConsentStatements = async (\n\targs: ResolveConsentStatementsArgs\n): Promise<ConsentStatements> => {\n\tconst { payload, req, form, sources } = args\n\tconst consentFields = (form.fields ?? []).filter(\n\t\t(field): field is { blockType: string; name: string; source?: unknown; display?: unknown } =>\n\t\t\tfield.blockType === 'consent' && typeof field.name === 'string' && field.name.length > 0\n\t)\n\tif (consentFields.length === 0) {\n\t\treturn {}\n\t}\n\tconst entries = await resolveConsentEntries({ payload, req, form, sources })\n\tconst statements: ConsentStatements = {}\n\tfor (const field of consentFields) {\n\t\tconst entry = entries.find((candidate) => candidate.id === field.source)\n\t\tif (!entry) {\n\t\t\tcontinue\n\t\t}\n\t\t// The link needs a name of its own, so it takes the source's `name` and never falls back to\n\t\t// the `id`: the id is a machine identifier, and showing it as the words a visitor clicks is\n\t\t// worse than no link at all. A source with a url and no name simply has no link.\n\t\tconst label = typeof entry.name === 'string' && entry.name.trim() !== '' ? entry.name : ''\n\t\t// The wording is selected per the field's display through the same helper the proof path\n\t\t// uses, so what renders is what a submit snapshots. The client only ever sees `statement`.\n\t\tconst wording = effectiveConsentStatement(entry, consentDisplayOf(field))\n\t\tstatements[field.name] = {\n\t\t\t...(wording != null ? { statement: wording } : {}),\n\t\t\t...(label && typeof entry.url === 'string' && entry.url.length > 0\n\t\t\t\t? { link: { label, url: entry.url } }\n\t\t\t\t: {}),\n\t\t}\n\t}\n\treturn statements\n}\n"],"mappings":";;;;;;;;;;;;;;;;AA0CA,MAAa,2BAA2B,OACvC,SACgC;CAChC,MAAM,EAAE,SAAS,KAAK,MAAM,YAAY;CACxC,MAAM,iBAAiB,KAAK,UAAU,CAAC,GAAG,QACxC,UACA,MAAM,cAAc,aAAa,OAAO,MAAM,SAAS,YAAY,MAAM,KAAK,SAAS,CACzF;CACA,IAAI,cAAc,WAAW,GAC5B,OAAO,CAAC;CAET,MAAM,UAAU,MAAM,sBAAsB;EAAE;EAAS;EAAK;EAAM;CAAQ,CAAC;CAC3E,MAAM,aAAgC,CAAC;CACvC,KAAK,MAAM,SAAS,eAAe;EAClC,MAAM,QAAQ,QAAQ,MAAM,cAAc,UAAU,OAAO,MAAM,MAAM;EACvE,IAAI,CAAC,OACJ;EAKD,MAAM,QAAQ,OAAO,MAAM,SAAS,YAAY,MAAM,KAAK,KAAK,MAAM,KAAK,MAAM,OAAO;EAGxF,MAAM,UAAU,0BAA0B,OAAO,iBAAiB,KAAK,CAAC;EACxE,WAAW,MAAM,QAAQ;GACxB,GAAI,WAAW,OAAO,EAAE,WAAW,QAAQ,IAAI,CAAC;GAChD,GAAI,SAAS,OAAO,MAAM,QAAQ,YAAY,MAAM,IAAI,SAAS,IAC9D,EAAE,MAAM;IAAE;IAAO,KAAK,MAAM;GAAI,EAAE,IAClC,CAAC;EACL;CACD;CACA,OAAO;AACR"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"resolvePublishedVersionRef.js","names":[],"sources":["../../src/consent/resolvePublishedVersionRef.ts"],"sourcesContent":["import type { Payload, PayloadRequest } from 'payload'\n\nexport type ResolvePublishedVersionRefArgs = {\n\tpayload: Payload\n\tcollection: string\n\tid: number | string\n\t/** Threaded into `findVersions` so a version written earlier in the same transaction is visible. */\n\treq?: PayloadRequest\n}\n\n/**\n * The id of a document's latest published version, or null when nothing is published.\n *\n * Drafts-only, and deliberately not a versions check: `_status` exists only where\n * `versions.drafts` is on (Payload adds the base version fields inside that branch when\n * sanitizing), so on a collection with plain versions and no drafts this query matches nothing and\n * returns null, which is indistinguishable from having no versions at all. Callers must decide the\n * difference themselves with `hasDraftsEnabled` rather than reading null as \"no versions\" (see\n * `captureConsent`). Never throws.\n */\nexport const resolvePublishedVersionRef = async (\n\targs: ResolvePublishedVersionRefArgs\n): Promise<string | null> => {\n\ttry {\n\t\tconst result = await args.payload.findVersions({\n\t\t\tcollection: args.collection as never,\n\t\t\twhere: {\n\t\t\t\tand: [{ parent: { equals: args.id } }, { 'version._status': { equals: 'published' } }],\n\t\t\t},\n\t\t\tsort: '-updatedAt',\n\t\t\tlimit: 1,\n\t\t\tdepth: 0,\n\t\t\treq: args.req,\n\t\t})\n\t\tconst doc = result?.docs?.[0]\n\t\treturn doc ? String(doc.id) : null\n\t} catch {\n\t\treturn null\n\t}\n}\n"],"mappings":";;;;;;;;;;;AAoBA,MAAa,6BAA6B,OACzC,SAC4B;CAC5B,IAAI;
|
|
1
|
+
{"version":3,"file":"resolvePublishedVersionRef.js","names":[],"sources":["../../src/consent/resolvePublishedVersionRef.ts"],"sourcesContent":["import type { Payload, PayloadRequest } from 'payload'\n\nexport type ResolvePublishedVersionRefArgs = {\n\tpayload: Payload\n\tcollection: string\n\tid: number | string\n\t/** Threaded into `findVersions` so a version written earlier in the same transaction is visible. */\n\treq?: PayloadRequest\n}\n\n/**\n * The id of a document's latest published version, or null when nothing is published.\n *\n * Drafts-only, and deliberately not a versions check: `_status` exists only where\n * `versions.drafts` is on (Payload adds the base version fields inside that branch when\n * sanitizing), so on a collection with plain versions and no drafts this query matches nothing and\n * returns null, which is indistinguishable from having no versions at all. Callers must decide the\n * difference themselves with `hasDraftsEnabled` rather than reading null as \"no versions\" (see\n * `captureConsent`). Never throws.\n */\nexport const resolvePublishedVersionRef = async (\n\targs: ResolvePublishedVersionRefArgs\n): Promise<string | null> => {\n\ttry {\n\t\tconst result = await args.payload.findVersions({\n\t\t\tcollection: args.collection as never,\n\t\t\twhere: {\n\t\t\t\tand: [{ parent: { equals: args.id } }, { 'version._status': { equals: 'published' } }],\n\t\t\t},\n\t\t\tsort: '-updatedAt',\n\t\t\tlimit: 1,\n\t\t\tdepth: 0,\n\t\t\t// A system lookup on behalf of a submission: the submitter has no read access to versions.\n\t\t\toverrideAccess: true,\n\t\t\treq: args.req,\n\t\t})\n\t\tconst doc = result?.docs?.[0]\n\t\treturn doc ? String(doc.id) : null\n\t} catch {\n\t\treturn null\n\t}\n}\n"],"mappings":";;;;;;;;;;;AAoBA,MAAa,6BAA6B,OACzC,SAC4B;CAC5B,IAAI;EAaH,MAAM,OAAM,MAZS,KAAK,QAAQ,aAAa;GAC9C,YAAY,KAAK;GACjB,OAAO,EACN,KAAK,CAAC,EAAE,QAAQ,EAAE,QAAQ,KAAK,GAAG,EAAE,GAAG,EAAE,mBAAmB,EAAE,QAAQ,YAAY,EAAE,CAAC,EACtF;GACA,MAAM;GACN,OAAO;GACP,OAAO;GAEP,gBAAgB;GAChB,KAAK,KAAK;EACX,CAAC,IACmB,OAAO;EAC3B,OAAO,MAAM,OAAO,IAAI,EAAE,IAAI;CAC/B,QAAQ;EACP,OAAO;CACR;AACD"}
|
package/dist/consent/types.d.ts
CHANGED
|
@@ -23,6 +23,14 @@ type ConsentSourceEntry = {
|
|
|
23
23
|
id: string;
|
|
24
24
|
name?: string;
|
|
25
25
|
statement?: unknown;
|
|
26
|
+
/**
|
|
27
|
+
* The wording a `display: 'notice'` consent field shows instead of `statement` ("By
|
|
28
|
+
* subscribing, you agree..." rather than "I accept..."). Same consent, same policy, same id in
|
|
29
|
+
* every proof; only the sentence differs. Absent or empty falls back to `statement`. A resolver
|
|
30
|
+
* mapping `consentSourcesField()` rows must forward the row's `noticeStatement` for notice
|
|
31
|
+
* displays to pick it up.
|
|
32
|
+
*/
|
|
33
|
+
noticeStatement?: unknown;
|
|
26
34
|
page?: ConsentSourcePage;
|
|
27
35
|
url?: string;
|
|
28
36
|
};
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { Payload } from "payload";
|
|
2
|
+
|
|
3
|
+
//#region src/context/formContext.d.ts
|
|
4
|
+
/** A verified reference to the document a form was rendered for. Never a secret: the id is already public. */
|
|
5
|
+
type FormContextReference = {
|
|
6
|
+
relationTo: string;
|
|
7
|
+
value: string | number;
|
|
8
|
+
};
|
|
9
|
+
/**
|
|
10
|
+
* Sign a `{ relationTo, value }` reference into a compact `v1.<base64url(payload)>.<hmac>` token: a
|
|
11
|
+
* rendering surface mints one per document it renders a form for, the client carries it, and the plugin
|
|
12
|
+
* verifies it on submit. Signed (HMAC-SHA256 over the payload with `secret ?? payload.secret`), not
|
|
13
|
+
* encrypted: the reference is not a secret, the signature only stops rewriting. `expiresIn` (seconds,
|
|
14
|
+
* default one day) bounds replay.
|
|
15
|
+
*/
|
|
16
|
+
declare const signFormContext: (args: {
|
|
17
|
+
payload: Payload;
|
|
18
|
+
relationTo: string;
|
|
19
|
+
value: string | number;
|
|
20
|
+
expiresIn?: number;
|
|
21
|
+
secret?: string;
|
|
22
|
+
}) => string;
|
|
23
|
+
/**
|
|
24
|
+
* Verify a token minted by `signFormContext` and return its reference, or null on any failure (wrong
|
|
25
|
+
* version, malformed, bad signature, or expired). Never throws, and the signature check is constant-time.
|
|
26
|
+
*/
|
|
27
|
+
declare const verifyFormContext: (token: string, secret: string, nowMs?: number) => FormContextReference | null;
|
|
28
|
+
//#endregion
|
|
29
|
+
export { FormContextReference, signFormContext, verifyFormContext };
|
|
30
|
+
//# sourceMappingURL=formContext.d.ts.map
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import { createHmac, timingSafeEqual } from "node:crypto";
|
|
2
|
+
//#region src/context/formContext.ts
|
|
3
|
+
const VERSION = "v1";
|
|
4
|
+
const DEFAULT_EXPIRES_IN_SECONDS = 86400;
|
|
5
|
+
const hmacHex = (body, secret) => createHmac("sha256", secret).update(body).digest("hex");
|
|
6
|
+
/**
|
|
7
|
+
* Sign a `{ relationTo, value }` reference into a compact `v1.<base64url(payload)>.<hmac>` token: a
|
|
8
|
+
* rendering surface mints one per document it renders a form for, the client carries it, and the plugin
|
|
9
|
+
* verifies it on submit. Signed (HMAC-SHA256 over the payload with `secret ?? payload.secret`), not
|
|
10
|
+
* encrypted: the reference is not a secret, the signature only stops rewriting. `expiresIn` (seconds,
|
|
11
|
+
* default one day) bounds replay.
|
|
12
|
+
*/
|
|
13
|
+
const signFormContext = (args) => {
|
|
14
|
+
const { payload, relationTo, value, expiresIn, secret } = args;
|
|
15
|
+
const exp = Math.floor(Date.now() / 1e3) + (expiresIn ?? DEFAULT_EXPIRES_IN_SECONDS);
|
|
16
|
+
const body = Buffer.from(JSON.stringify({
|
|
17
|
+
relationTo,
|
|
18
|
+
value,
|
|
19
|
+
exp
|
|
20
|
+
})).toString("base64url");
|
|
21
|
+
return `${VERSION}.${body}.${hmacHex(body, secret ?? payload.secret)}`;
|
|
22
|
+
};
|
|
23
|
+
/**
|
|
24
|
+
* Verify a token minted by `signFormContext` and return its reference, or null on any failure (wrong
|
|
25
|
+
* version, malformed, bad signature, or expired). Never throws, and the signature check is constant-time.
|
|
26
|
+
*/
|
|
27
|
+
const verifyFormContext = (token, secret, nowMs = Date.now()) => {
|
|
28
|
+
const parts = token.split(".");
|
|
29
|
+
if (parts.length !== 3 || parts[0] !== VERSION) return null;
|
|
30
|
+
const [, body, signature] = parts;
|
|
31
|
+
const expected = hmacHex(body ?? "", secret);
|
|
32
|
+
const given = Buffer.from(signature ?? "");
|
|
33
|
+
const want = Buffer.from(expected);
|
|
34
|
+
if (given.byteLength !== want.byteLength || !timingSafeEqual(given, want)) return null;
|
|
35
|
+
let parsed;
|
|
36
|
+
try {
|
|
37
|
+
parsed = JSON.parse(Buffer.from(body ?? "", "base64url").toString("utf8"));
|
|
38
|
+
} catch {
|
|
39
|
+
return null;
|
|
40
|
+
}
|
|
41
|
+
if (!parsed || typeof parsed !== "object") return null;
|
|
42
|
+
const { relationTo, value, exp } = parsed;
|
|
43
|
+
if (typeof relationTo !== "string" || relationTo.length === 0) return null;
|
|
44
|
+
if (typeof value !== "string" && typeof value !== "number") return null;
|
|
45
|
+
if (typeof exp !== "number" || exp * 1e3 <= nowMs) return null;
|
|
46
|
+
return {
|
|
47
|
+
relationTo,
|
|
48
|
+
value
|
|
49
|
+
};
|
|
50
|
+
};
|
|
51
|
+
//#endregion
|
|
52
|
+
export { signFormContext, verifyFormContext };
|
|
53
|
+
|
|
54
|
+
//# sourceMappingURL=formContext.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"formContext.js","names":[],"sources":["../../src/context/formContext.ts"],"sourcesContent":["import { createHmac, timingSafeEqual } from 'node:crypto'\nimport type { Payload } from 'payload'\n\n/** A verified reference to the document a form was rendered for. Never a secret: the id is already public. */\nexport type FormContextReference = { relationTo: string; value: string | number }\n\nconst VERSION = 'v1'\nconst DEFAULT_EXPIRES_IN_SECONDS = 86_400\n\nconst hmacHex = (body: string, secret: string): string =>\n\tcreateHmac('sha256', secret).update(body).digest('hex')\n\n/**\n * Sign a `{ relationTo, value }` reference into a compact `v1.<base64url(payload)>.<hmac>` token: a\n * rendering surface mints one per document it renders a form for, the client carries it, and the plugin\n * verifies it on submit. Signed (HMAC-SHA256 over the payload with `secret ?? payload.secret`), not\n * encrypted: the reference is not a secret, the signature only stops rewriting. `expiresIn` (seconds,\n * default one day) bounds replay.\n */\nexport const signFormContext = (args: {\n\tpayload: Payload\n\trelationTo: string\n\tvalue: string | number\n\texpiresIn?: number\n\tsecret?: string\n}): string => {\n\tconst { payload, relationTo, value, expiresIn, secret } = args\n\tconst exp = Math.floor(Date.now() / 1000) + (expiresIn ?? DEFAULT_EXPIRES_IN_SECONDS)\n\tconst body = Buffer.from(JSON.stringify({ relationTo, value, exp })).toString('base64url')\n\treturn `${VERSION}.${body}.${hmacHex(body, secret ?? payload.secret)}`\n}\n\n/**\n * Verify a token minted by `signFormContext` and return its reference, or null on any failure (wrong\n * version, malformed, bad signature, or expired). Never throws, and the signature check is constant-time.\n */\nexport const verifyFormContext = (\n\ttoken: string,\n\tsecret: string,\n\tnowMs: number = Date.now()\n): FormContextReference | null => {\n\tconst parts = token.split('.')\n\tif (parts.length !== 3 || parts[0] !== VERSION) {\n\t\treturn null\n\t}\n\tconst [, body, signature] = parts\n\tconst expected = hmacHex(body ?? '', secret)\n\tconst given = Buffer.from(signature ?? '')\n\tconst want = Buffer.from(expected)\n\tif (given.byteLength !== want.byteLength || !timingSafeEqual(given, want)) {\n\t\treturn null\n\t}\n\tlet parsed: unknown\n\ttry {\n\t\tparsed = JSON.parse(Buffer.from(body ?? '', 'base64url').toString('utf8'))\n\t} catch {\n\t\treturn null\n\t}\n\tif (!parsed || typeof parsed !== 'object') {\n\t\treturn null\n\t}\n\tconst { relationTo, value, exp } = parsed as Record<string, unknown>\n\tif (typeof relationTo !== 'string' || relationTo.length === 0) {\n\t\treturn null\n\t}\n\tif (typeof value !== 'string' && typeof value !== 'number') {\n\t\treturn null\n\t}\n\tif (typeof exp !== 'number' || exp * 1000 <= nowMs) {\n\t\treturn null\n\t}\n\treturn { relationTo, value }\n}\n"],"mappings":";;AAMA,MAAM,UAAU;AAChB,MAAM,6BAA6B;AAEnC,MAAM,WAAW,MAAc,WAC9B,WAAW,UAAU,MAAM,EAAE,OAAO,IAAI,EAAE,OAAO,KAAK;;;;;;;;AASvD,MAAa,mBAAmB,SAMlB;CACb,MAAM,EAAE,SAAS,YAAY,OAAO,WAAW,WAAW;CAC1D,MAAM,MAAM,KAAK,MAAM,KAAK,IAAI,IAAI,GAAI,KAAK,aAAa;CAC1D,MAAM,OAAO,OAAO,KAAK,KAAK,UAAU;EAAE;EAAY;EAAO;CAAI,CAAC,CAAC,EAAE,SAAS,WAAW;CACzF,OAAO,GAAG,QAAQ,GAAG,KAAK,GAAG,QAAQ,MAAM,UAAU,QAAQ,MAAM;AACpE;;;;;AAMA,MAAa,qBACZ,OACA,QACA,QAAgB,KAAK,IAAI,MACQ;CACjC,MAAM,QAAQ,MAAM,MAAM,GAAG;CAC7B,IAAI,MAAM,WAAW,KAAK,MAAM,OAAO,SACtC,OAAO;CAER,MAAM,GAAG,MAAM,aAAa;CAC5B,MAAM,WAAW,QAAQ,QAAQ,IAAI,MAAM;CAC3C,MAAM,QAAQ,OAAO,KAAK,aAAa,EAAE;CACzC,MAAM,OAAO,OAAO,KAAK,QAAQ;CACjC,IAAI,MAAM,eAAe,KAAK,cAAc,CAAC,gBAAgB,OAAO,IAAI,GACvE,OAAO;CAER,IAAI;CACJ,IAAI;EACH,SAAS,KAAK,MAAM,OAAO,KAAK,QAAQ,IAAI,WAAW,EAAE,SAAS,MAAM,CAAC;CAC1E,QAAQ;EACP,OAAO;CACR;CACA,IAAI,CAAC,UAAU,OAAO,WAAW,UAChC,OAAO;CAER,MAAM,EAAE,YAAY,OAAO,QAAQ;CACnC,IAAI,OAAO,eAAe,YAAY,WAAW,WAAW,GAC3D,OAAO;CAER,IAAI,OAAO,UAAU,YAAY,OAAO,UAAU,UACjD,OAAO;CAER,IAAI,OAAO,QAAQ,YAAY,MAAM,OAAQ,OAC5C,OAAO;CAER,OAAO;EAAE;EAAY;CAAM;AAC5B"}
|